Skip to content

Instantly share code, notes, and snippets.

@jpsilvashy
Forked from jbouny/nodejs-webm
Created November 22, 2017 23:04
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jpsilvashy/2d6bb0e11b626f92430fb39ef6053aeb to your computer and use it in GitHub Desktop.
Save jpsilvashy/2d6bb0e11b626f92430fb39ef6053aeb to your computer and use it in GitHub Desktop.
Node.js WebM generation with whammy and sharp
var Whammy = require('node-whammy'),
sharp = require('sharp');
function canvasToWebp(canvas, callback) {
sharp(canvas.toBuffer()).toFormat(sharp.format.webp).toBuffer(function(e, webpbuffer) {
var webpDataURL = 'data:image/webp;base64,' + webpbuffer.toString('base64');
callback(webpDataURL);
});
}
function sendAsWEBP(response, canvas) {
var encoder = new Whammy.Video(7);
var currentId = 0,
time = 0,
timeout = 20000,
delay = 20
addedFrame = -1,
totalFrames = 3,
tmpFrames = Array.apply(null, Array(totalFrames));
var addFrame = function addFrame(context) {
var id = currentId++;
canvasToWebp(context.canvas, function(webmData) {
tmpFrames[id] = webmData;
for(var i = addedFrame + 1; i < totalFrames; ++i) {
if(tmpFrames[i] !== undefined) {
encoder.add(tmpFrames[i]);
addedFrame = i;
}
else {
break;
}
}
});
};
var checkReady = function checkReady() {
if(totalFrames <= addedFrame + 1) {
try {
var output = encoder.compile(true);
response.type('webm');
response.send(new Buffer(output));
console.log('Webm compilation: ' + time + 'ms');
}
catch(err) {
response.send(err.toString());
}
}
else if((time += delay) < timeout) {
setTimeout(checkReady, delay);
}
else {
response.send('Timeout of ' + timeout + 'ms exceed');
}
};
var context = canvas.getContext("2d");
// Add 3 frames
addFrame(context);
addFrame(context);
addFrame(context);
setTimeout(checkReady, delay);
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment