Skip to content

Commit

Permalink
Add video export + layout changes
Browse files Browse the repository at this point in the history
  • Loading branch information
KristjanESPERANTO committed Dec 29, 2021
1 parent feb8fe8 commit 49cd051
Show file tree
Hide file tree
Showing 7 changed files with 1,565 additions and 33 deletions.
68 changes: 49 additions & 19 deletions app.js
Original file line number Diff line number Diff line change
Expand Up @@ -7,26 +7,37 @@ let canvasHeight;
let canvasWidth;
let canvasCounter = 0;

let slider = document.getElementById("slider");
const slider = document.getElementById("slider");
let intervalValue = document.getElementById("intervalValue");
intervalValue.innerText = slider.value;
slider.oninput = function () { intervalValue.innerText = this.value; };

let slidesCounter = document.getElementById("slides");

function deleteSlide(e) {
e.parentNode.parentNode.removeChild(e.parentNode);
e.parentNode.parentNode.parentNode.removeChild(e.parentNode.parentNode);
canvasCounter = canvasCounter - 1;
slidesCounter.innerText = canvasCounter;
}

function addCanvas() {
let wrapper = document.getElementById("wrapper");
const lineBreak = document.createElement("br");

const gridContainer = document.createElement("div");
gridContainer.className = "grid-container";

const canvasContainer = document.createElement("div");
const deleteSpan = document.createElement("button");
deleteSpan.onclick = function () { deleteSlide(this); };
deleteSpan.innerText = "Delete";
canvasContainer.className = "grid-item";
gridContainer.appendChild(canvasContainer);

const buttonContainer = document.createElement("div");
buttonContainer.className = "grid-item";
gridContainer.appendChild(buttonContainer);

const deleteButton = document.createElement("button");
deleteButton.onclick = function () { deleteSlide(this); };
deleteButton.innerText = "Delete";
buttonContainer.appendChild(deleteButton);

canvasCounter += 1;
let animationContainer = document.getElementById("animationContainer");
Expand All @@ -35,39 +46,58 @@ function addCanvas() {
}
let slidesContainer = document.getElementById("slidesContainer");
slidesContainer.style.display = "unset";
slidesContainer.appendChild(gridContainer);
slidesCounter.innerText = canvasCounter;

html2canvas(wrapper).then(function (canvas) {
canvasHeight = canvas.height;
canvasWidth = canvas.width;
canvasContainer.appendChild(canvas);
canvasContainer.appendChild(deleteSpan);
slidesContainer.appendChild(canvasContainer);
slidesContainer.appendChild(lineBreak);
});
}

function mergeCanvases() {
let encoder = new GIFEncoder();
encoder.setRepeat(0);
encoder.setDelay(slider.value);
let canvases = document.getElementsByTagName("canvas");
let gifEncoder = new GIFEncoder();
let videoWriter = new WebMWriter({
quality: 0.95,
frameDuration: slider.value,
});

gifEncoder.setRepeat(0);
gifEncoder.setDelay(slider.value);
gifEncoder.setSize(canvasWidth, canvasHeight);
gifEncoder.start();

encoder.setSize(canvasWidth, canvasHeight);
encoder.start();
let canvases = document.getElementsByTagName("canvas");

for (let canvas of canvases) {
let context = canvas.getContext("2d");
encoder.addFrame(context);
gifEncoder.addFrame(context);
videoWriter.addFrame(canvas);
}

encoder.finish();
finalizeGif(gifEncoder);
finalizeVideo(videoWriter);
}

function finalizeGif(gifEncoder) {
gifEncoder.finish();
let gifAnimation = document.getElementById("gifAnimation");
gifAnimation.src = "data:image/gif;base64," + encode64(encoder.stream().getData());
gifAnimation.src = "data:image/gif;base64," + encode64(gifEncoder.stream().getData());
gifAnimation.width = canvasWidth;
gifAnimation.height = canvasHeight;
let gifAnimationContainer = document.getElementById("gifAnimationContainer");
gifAnimationContainer.style.display = "unset";
document.getElementById('gifSize').innerHTML = "~" + Math.ceil(gifAnimation.src.length / 1300) + "kB";
}

function finalizeVideo(videoWriter) {
videoWriter.complete().then(function (webMBlob) {
let url = (window.webkitURL || window.URL).createObjectURL(webMBlob);
document.getElementById('video').src = url;
document.getElementById('downloadVideo').href = url;
document.getElementById('videoSize').innerHTML = "~" + Math.ceil(webMBlob.size / 1024) + "kB";
});
}

function shiftLine() {
Expand Down Expand Up @@ -173,4 +203,4 @@ const fontSize4 = document.querySelector("#fontSize4");
fontSize4.oninput = function () {
let line = document.getElementById("tr4");
line.style.fontSize = fontSize4.value + "px";
};
};
30 changes: 24 additions & 6 deletions index.html
Original file line number Diff line number Diff line change
Expand Up @@ -17,8 +17,8 @@ <h1>PIDasGIF</h1>

<main>
<h2>You can edit this table</h2>
<div id="container">
<div id="wrapper">
<div class="grid-container">
<div class="grid-item" id="wrapper">
<table contenteditable="true" spellcheck="false" id="pidTable">
<colgroup>
<col id="lineColumn">
Expand Down Expand Up @@ -47,8 +47,8 @@ <h2>You can edit this table</h2>
</tr>
</table>
</div>
<div class="grid-item">

<div>
<table id="lineControls">
<tr>
<th>Departure</th>
Expand Down Expand Up @@ -127,13 +127,30 @@ <h2>You can edit this table</h2>

<div id="gifAnimationContainer">
<h2>Animation Result</h2>
<img id="gifAnimation"><br>
<button onclick="downloadCanvas()">💾 Download</button>
<div class="grid-container">
<div class="grid-item">
<img id="gifAnimation">
</div>
<div class="grid-item">
<button onclick="downloadCanvas()">💾 Download GIF</button>
<div id="gifSize"></div>
</div>
<div class="grid-item">
<video id="video" controls autoplay loop></video>
</div>
<div class="grid-item">
<a style="text-decoration: none; color:inherit" id="downloadVideo" download="video.webm">
<button>💾 Download Video</button>
<div id="videoSize"></div>
</a>
</div>
</div>
</div>

<div id="slidesContainer">
<h2>Slides:<span id="slides"></span></h2>
</div>

</main>

<div id="github">
Expand All @@ -151,8 +168,9 @@ <h2>Slides:<span id="slides"></span></h2>
<script src="./third-party/jsgif/LZWEncoder.js"></script>
<script src="./third-party/jsgif/NeuQuant.js"></script>
<script src="./third-party/jsgif/GIFEncoder.js"></script>
<script src="./third-party/webm-writer-js/webm-writer-0.3.0.js"></script>
<script src="./app.js"></script>

</body>

</html>
</html>
4 changes: 3 additions & 1 deletion license.md
Original file line number Diff line number Diff line change
@@ -1,5 +1,7 @@
# ISC License

Copyright (c) Jahr 2021, Kristjan ESPERANTO

Permission to use, copy, modify, and/or distribute this software for any purpose with or without fee is hereby granted, provided that the above copyright notice and this permission notice appear in all copies.

THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
6 changes: 6 additions & 0 deletions readme.md
Original file line number Diff line number Diff line change
Expand Up @@ -17,10 +17,15 @@ Create an animated GIF file to simulate a passenger information display.

## Todo

- Browser support WebM
- Determine video length
- Spinner after "Create Animation"
- Seems that the video encoder has a problem with many (>30) slides
- Check if [ccapture.js](https://github.com/spite/ccapture.js/) can replace jsgif - ccapture.js should be faster and can output video
- Check if [gif.js](https://github.com/jnordberg/gif.js) can replace jsgif - gif.js should be faster
- Video export option: ogm, wmv, mpg, webm, ogv, mov, asx, mpeg, mp4, m4v or avi
- Refactoring
- Find out why the font color is not so clear in the video

## Third-Party

Expand All @@ -31,3 +36,4 @@ This is an overview of the third-party software and data we use. Many thanks to
| [24 LED](https://fonts2u.com/24-led.font) | General Public License with font-exception and Open Font License | 0.001 2009 | Font |
| [html2canvas](https://github.com/niklasvh/html2canvas/) | MIT | 1.3.3 | Convert the table to a canvas |
| [jsgif](https://github.com/egfx/jsgif) | MIT | 2021-03-07 | Convert canvases to animated GIF |
| [webm-writer-js](https://github.com/thenickdude/webm-writer-js) | WTFPLv2 | 0.3.0 | Convert canvases to WebM |
22 changes: 15 additions & 7 deletions stylesheet.css
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,20 @@
url("./third-party/24_LED/24_LED.svg#24LED") format("svg");
}

.grid-container {
margin: 0 auto;
display: grid;
grid-template-columns: 900px 450px;
width: max-content;
}
.grid-item {
margin: auto;
}

.grid-item:nth-child(even) {
margin-left: 20px;
}

#pidTable {
table-layout: fixed;
border-spacing: 0;
Expand Down Expand Up @@ -67,16 +81,10 @@ td * {
margin: auto 25px;
}

#container {
display: flex;
margin: 25px auto;
width: max-content;
}

#controls {
display: flex;
width: max-content;
margin: auto;
margin: 25px auto;
}

#lineControls {
Expand Down
106 changes: 106 additions & 0 deletions third-party/webm-writer-js/Readme.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,106 @@
# WebM Writer for JavaScript

This is a JavaScript-based WebM video encoder based on the ideas from [Whammy][]. It allows you to turn a series of
Canvas frames into a WebM video.

This implementation allows you to create very large video files (exceeding the size of available memory), because when
running in a privileged context like a Chrome extension or Electron app, it can stream chunks immediately to a file on disk
using [Chrome's FileWriter][] while the video is being constructed, instead of needing to buffer the entire video in
memory before saving can begin. Video sizes in excess of 4GB can be written. The implementation currently tops out at
32GB, but this could be extended.

When a FileWriter is not available, it can instead buffer the video in memory as a series of Blobs which are eventually
returned to the calling code as one composite Blob. This Blob can be displayed in a &lt;video&gt; element, transmitted
to a server, or used for some other purpose. Note that some browsers size limits on Blobs, particularly mobile
browsers, check out the [Blob size limits][].

[Chrome's FileWriter]: https://developer.chrome.com/apps/fileSystem
[Whammy]: https://github.com/antimatter15/whammy
[Blob size limits]: https://github.com/eligrey/FileSaver.js/

## Compatibility

Because this code relies on browser support for encoding a Canvas as a WebP image (using `toDataURL()`), it is presently
only supported in Google Chrome, or a similar environment like Electron. It will throw an exception on other browsers or
on vanilla Node.

## Usage (Chrome)

Download the script from the [Releases tab][] above. You should end up with a `webm-writer-x.x.x.js` file to add to your
project.

[Releases tab]: https://github.com/thenickdude/webm-writer-js/releases

Include the script in your header:

```html
<script type="text/javascript" src="webm-writer-0.3.0.js"></script>
```

First construct the writer, passing in any options you want to customize:

```js
var videoWriter = new WebMWriter({
quality: 0.95, // WebM image quality from 0.0 (worst) to 0.99999 (best), 1.00 (VP8L lossless) is not supported
fileWriter: null, // FileWriter in order to stream to a file instead of buffering to memory (optional)
fd: null, // Node.js file handle to write to instead of buffering to memory (optional)

// You must supply one of:
frameDuration: null, // Duration of frames in milliseconds
frameRate: null, // Number of frames per second

transparent: false, // True if an alpha channel should be included in the video
alphaQuality: undefined, // Allows you to set the quality level of the alpha channel separately.
// If not specified this defaults to the same value as `quality`.
});
```

Add as many Canvas frames as you like to build your video:

```js
videoWriter.addFrame(canvas);
```

You can override the duration of a specific frame in milliseconds like so:

```js
videoWriter.addFrame(canvas, 100);
```

Note that if the canvas' dimensions change between frames, the resulting WebM video may not be compatible with all players,
because the frame dimensions will differ from the overall track's dimensions. This could be improved in the future.

When you're done, you must call `complete()` to finish writing the video:

```js
videoWriter.complete();
```

`complete()` returns a Promise which resolves when writing is completed.

If you didn't supply a `fileWriter` or `fd` in the options, the Promise will resolve to Blob which represents the video. You
could display this blob in an HTML5 &lt;video&gt; tag:

```js
videoWriter.complete().then(function(webMBlob) {
$("video").attr("src", URL.createObjectURL(webMBlob));
});
```

## Usage (Electron)

The video encoder can use Node.js file APIs to write the video to disk when running under Electron. There is an example
in `test/electron`. Run `npm install` in that directory to fetch required libraries, then `npm start` to launch Electron.

## Transparent WebM support

Transparent WebM files are supported, check out the example in test/transparent. However, because I'm re-using Chrome's
WebP encoder to create the alpha channel, and the alpha channel is taken from the Y channel of a YUV-encoded WebP frame,
and Y values are clamped by Chrome to be in the range 22-240 instead of the full 0-255 range, the encoded video can
neither be fully opaque or fully transparent :(.

Sorry, I wasn't able to find a workaround to get that to work.

## License

This project is licensed under the WTFPLv2 https://en.wikipedia.org/wiki/WTFPL
Loading

0 comments on commit 49cd051

Please sign in to comment.