diff --git a/README.md b/README.md index e86aeb5..7bbc2a1 100755 --- a/README.md +++ b/README.md @@ -1,5 +1,5 @@ # CCapture.js - A library to capture canvas-based animations -CCapture.js is a library to help capturing animations created with HTML5 `canvas` at a fixed framerate. +CCapture.js is a library to help capturing animations created with HTML5 `canvas` at a fixed framerate. - [What is CCapture.js and why would I need it?](#what-is-ccapturejs-and-why-would-i-need-it) - [Using the code](#using-the-code) @@ -32,28 +32,31 @@ Methods supported so far: - `performance.now` - `HTMLVideoElement.prototype.currentTime`, `HTMLAudioElement.prototype.currentTime` -CCapture.js is more or less [ryg's kkapture](http://www.farb-rausch.de/~fg/kkapture/) but for JavaScript and `canvas`. +CCapture.js is more or less [ryg's kkapture](http://www.farb-rausch.de/~fg/kkapture/) but for JavaScript and `canvas`. The library supports multiple export formats using modular encoders (`CCFrameEncoder): - `CCWebMEncoder` uses [WebM Writer for JavaScript](https://github.com/thenickdude/webm-writer-js/) to create a WebM movie -- `CCPNGEncoder` and `CCJPEGEncoder` export PNG and JPEG files in a TAR file, respectively -- `CCGIFEncoder` uses [gifjs](http://jnordberg.github.io/gif.js/) to create animated GIFs -- `CCFFMpegServerEncoder` uses [ffmpegserver.js](https://github.com/greggman/ffmpegserver.js) to generate video on the server +- `CCMJPGEncoder` uses [mjbuilder.js](http://ushiroad.com/mjpeg/) to create an MJPEG-AVI movie +- `CCPNGEncoder`, `CCJPEGEncoder` and `CCWebPEncoder` export PNG, JPEG and WebP files in a TAR file, respectively +- `CCGIFEncoder` uses [gif.js](http://jnordberg.github.io/gif.js/) to create animated GIFs +- `CCFFMpegServerEncoder` uses [ffmpegserver.js](https://github.com/greggman/ffmpegserver.js) to generate video on the server Forks, pull requests and code critiques are welcome! #### Using the code #### -Include CCapture[.min].js and [WebM Writer](https://github.com/thenickdude/webm-writer-js) or [gifjs](http://jnordberg.github.io/gif.js/). +Include CCapture[.min].js and [WebM Writer](https://github.com/thenickdude/webm-writer-js) or [gifjs](http://jnordberg.github.io/gif.js/). ```html - + + + - + @@ -62,6 +65,14 @@ Or include the whole pack ```html ``` +Or a pack with everything needed for WebM +```html + +``` +Or a pack with everything needed for MJPEG +```html + +``` Or use npm or bower to install the [package](https://www.npmjs.com/package/ccapture.js): ```bash npm install ccapture.js @@ -77,8 +88,11 @@ To create a CCapture object, write: // Create a capturer that exports a WebM video var capturer = new CCapture( { format: 'webm' } ); +// Create a capturer that exports an MJPEG-AVI video +var capturer = new CCapture( { format: 'mjpg' } ); + // Create a capturer that exports an animated GIF -// Notices you have to specify the path to the gif.worker.js +// Notice that you have to specify the path to gif.worker.js var capturer = new CCapture( { format: 'gif', workersPath: 'js/' } ); // Create a capturer that exports PNG images in a TAR file @@ -86,6 +100,9 @@ var capturer = new CCapture( { format: 'png' } ); // Create a capturer that exports JPEG images in a TAR file var capturer = new CCapture( { format: 'jpg' } ); + +// Create a capturer that exports WebP images in a TAR file +var capturer = new CCapture( { format: 'webp' } ); ``` This creates a CCapture object to run at 60fps, non-verbose. You can tweak the object by setting parameters on the constructor: @@ -100,13 +117,13 @@ var capturer = new CCapture( { The complete list of parameters is: - ***framerate***: target framerate for the capture - ***motionBlurFrames***: supersampling of frames to create a motion-blurred frame (0 or 1 make no effect) -- ***format***: webm/gif/png/jpg/ffmpegserver -- ***quality***: quality for webm/jpg +- ***format***: webm/webp/gif/png/jpg/mjpg/ffmpegserver +- ***quality***: quality for webm/webp/jpg/mjpg - ***name***: name of the files to be exported. if no name is provided, a GUID will be generated - ***verbose***: dumps info on the console - ***display***: adds a widget with capturing info (WIP) - ***timeLimit***: automatically stops and downloads when reaching that time (seconds). Very convenient for long captures: set it and forget it (remember autoSaveTime!) -- ***autoSaveTime***: it will automatically download the captured data every n seconds (only available for webm/png/jpg) +- ***autoSaveTime***: it will automatically download the captured data every n seconds (only available for webm/webp/png/jpg/mjpg) - ***startTime***: skip to that mark (seconds) - ***workersPath***: path to the gif worker script @@ -155,7 +172,7 @@ CCapture.js only works on browsers that have a `canvas implementation. **The *autoSaveTime* parameter** -Different browsers have different issues with big files: most break for big `Uint8Array` allocations, or when a file to downloads is larger than 1GB, etc. I haven't been able to find a solid solution for all, so I introduced the `autoSaveTime` parameter, just to prevent loss of large files. If used with a webm/png/jpg capturer, it will automatically compile, download and free the captured frames every *n* seconds specified in the parameter. The downloaded file will have the structure *{name}-part-00000n* and the extension (.webm or .tar). The files inside the TAR file will have the right number of sequence. +Different browsers have different issues with big files: most break for big `Uint8Array` allocations, or when a file to downloads is larger than 1GB, etc. I haven't been able to find a solid solution for all, so I introduced the `autoSaveTime` parameter, just to prevent loss of large files. If used with a webm/webp/png/jpg capturer, it will automatically compile, download and free the captured frames every *n* seconds specified in the parameter. The downloaded file will have the structure *{name}-part-00000n* and the extension (.webm or .tar). The files inside the TAR file will have the right number of sequence. Use an `autoSaveTime` value that give you a file that is small enough to not trip the browser, but large enough to not generate a thousand part files. A value between 10 and 30 seconds for a 4K capture I've found works best: just make sure the file is under 1GB. For most regular, viewport-sized or even Full-HD captures it shouldn't be an issue, but keep in mind this issue. @@ -171,7 +188,7 @@ There's some issues in which memory -mostly from accumulated frames- will not be #### Credits #### -- [WebM Writer](https://github.com/thenickdude/webm-writer-js) +- [WebM Writer](https://github.com/thenickdude/webm-writer-js) - Pre 1.0.9: Slightly modified version of [Whammy.js](https://github.com/antimatter15/whammy) (fixed variable size integer calculations) - Slightly modified version of [tar.js](https://github.com/beatgammit/tar-js) (fixed memory allocations for many files) diff --git a/build/CCapture.all.min.js b/build/CCapture.all.min.js index bda376d..173f5ef 100644 --- a/build/CCapture.all.min.js +++ b/build/CCapture.all.min.js @@ -1,2 +1 @@ -"use strict";function download(t,e,i){function n(t){var e=t.split(/[:;,]/),i=e[1],n="base64"==e[2]?atob:decodeURIComponent,r=n(e.pop()),o=r.length,a=0,s=new Uint8Array(o);for(a;a>8,this.data[this.pos++]=t},t.prototype.writeDoubleBE=function(t){for(var e=new Uint8Array(new Float64Array([t]).buffer),i=e.length-1;i>=0;i--)this.writeByte(e[i])},t.prototype.writeFloatBE=function(t){for(var e=new Uint8Array(new Float32Array([t]).buffer),i=e.length-1;i>=0;i--)this.writeByte(e[i])},t.prototype.writeString=function(t){for(var e=0;e>8),this.writeU8(t);break;case 3:this.writeU8(32|t>>16),this.writeU8(t>>8),this.writeU8(t);break;case 4:this.writeU8(16|t>>24),this.writeU8(t>>16),this.writeU8(t>>8),this.writeU8(t);break;case 5:this.writeU8(8|t/4294967296&7),this.writeU8(t>>24),this.writeU8(t>>16),this.writeU8(t>>8),this.writeU8(t);break;default:throw new RuntimeException("Bad EBML VINT size "+e)}},t.prototype.measureEBMLVarInt=function(t){if(t<127)return 1;if(t<16383)return 2;if(t<2097151)return 3;if(t<268435455)return 4;if(t<34359738367)return 5;throw new RuntimeException("EBML VINT size not supported "+t)},t.prototype.writeEBMLVarInt=function(t){this.writeEBMLVarIntWidth(t,this.measureEBMLVarInt(t))},t.prototype.writeUnsignedIntBE=function(t,e){switch(void 0===e&&(e=this.measureUnsignedInt(t)),e){case 5:this.writeU8(Math.floor(t/4294967296));case 4:this.writeU8(t>>24);case 3:this.writeU8(t>>16);case 2:this.writeU8(t>>8);case 1:this.writeU8(t);break;default:throw new RuntimeException("Bad UINT size "+e)}},t.prototype.measureUnsignedInt=function(t){return t<256?1:t<65536?2:t<1<<24?3:t<4294967296?4:5},t.prototype.getAsDataArray=function(){if(this.posthis.length)throw"Seeking beyond the end of file is not allowed";this.pos=t},this.write=function(e){var i={offset:this.pos,data:e,length:r(e)},f=i.offset>=this.length;this.pos+=i.length,this.length=Math.max(this.length,this.pos),a=a.then(function(){if(h)return new Promise(function(e,r){n(i.data).then(function(n){var r=0,o=Buffer.from(n.buffer),a=function(n,o,s){r+=o,r>=s.length?e():t.write(h,s,r,s.length-r,i.offset+r,a)};t.write(h,o,0,o.length,i.offset,a)})});if(s)return new Promise(function(t,e){s.onwriteend=t,s.seek(i.offset),s.write(new Blob([i.data]))});if(!f)for(var e=0;e=r.offset+r.length)){if(i.offsetr.offset+r.length)throw new Error("Overwrite crosses blob boundaries");return i.offset==r.offset&&i.length==r.length?void(r.data=i.data):n(r.data).then(function(t){return r.data=t,n(i.data)}).then(function(t){i.data=t,r.data.set(i.data,i.offset-r.offset)})}}o.push(i)})},this.complete=function(t){return a=h||s?a.then(function(){return null}):a.then(function(){for(var e=[],i=0;i0&&e.trackNumber<127))throw"TrackNumber must be > 0 and < 127";return i.writeEBMLVarInt(e.trackNumber),i.writeU16BE(e.timecode),i.writeByte(128),{id:163,data:[i.getAsDataArray(),e.frame]}}function l(t){return{id:524531317,data:[{id:231,data:Math.round(t.timecode)}]}}function c(t,e,i){_.push({id:187,data:[{id:179,data:e},{id:183,data:[{id:247,data:t},{id:241,data:a(i)}]}]})}function p(){var e={id:475249515,data:_},i=new t(16+32*_.length);h(i,S.pos,e),S.write(i.getAsDataArray()),D.Cues.positionEBML.data=a(e.offset)}function m(){if(0!=T.length){for(var e=0,i=0;i=E&&m()}function y(){var e=new t(x.size),i=S.pos;h(e,x.dataOffset,x.data),S.seek(x.dataOffset),S.write(e.getAsDataArray()),S.seek(i)}function v(){var e=new t(8),i=S.pos;e.writeDoubleBE(U),S.seek(M.dataOffset),S.write(e.getAsDataArray()),S.seek(i)}var b,k,B,x,E=5e3,A=1,L=!1,T=[],U=0,F=0,I={quality:.95,fileWriter:null,fd:null,frameDuration:null,frameRate:null},D={Cues:{id:new Uint8Array([28,83,187,107]),positionEBML:null},SegmentInfo:{id:new Uint8Array([21,73,169,102]),positionEBML:null},Tracks:{id:new Uint8Array([22,84,174,107]),positionEBML:null}},M={id:17545,data:new s(0)},_=[],S=new e(n.fileWriter||n.fd);this.addFrame=function(t){if(L){if(t.width!=b||t.height!=k)throw"Frame size differs from previous frames"}else b=t.width,k=t.height,u(),L=!0;var e=r(t,{quality:n.quality});if(!e)throw"Couldn't decode WebP frame, does the browser support WebP?";g({frame:o(e),duration:n.frameDuration})},this.complete=function(){return m(),p(),y(),v(),S.complete("video/webm")},this.getWrittenSize=function(){return S.length},n=i(I,n||{}),w()}};"undefined"!=typeof module&&"undefined"!=typeof module.exports?module.exports=t(require("./ArrayBufferDataStream"),require("./BlobBuffer")):window.WebMWriter=t(ArrayBufferDataStream,BlobBuffer)}(),function(){function t(t){var e,i=new Uint8Array(t);for(e=0;e>18&63]+o[t>>12&63]+o[t>>6&63]+o[63&t]}var i,n,r,a=t.length%3,s="";for(i=0,r=t.length-a;in&&(e.push({blocks:o,length:i}),o=[],i=0),o.push(t),i+=t.headerLength+t.inputLength}),e.push({blocks:o,length:i}),e.forEach(function(e){var i=new Uint8Array(e.length),n=0;e.blocks.forEach(function(t){i.set(t.header,n),n+=t.headerLength,i.set(t.input,n),n+=t.inputLength}),t.push(i)}),t.push(new Uint8Array(2*r)),new Blob(t,{type:"octet/stream"})},t.prototype.clear=function(){this.written=0,this.out=n.clean(e)},window.Tar=t}(),function(t){function e(t,i){if({}.hasOwnProperty.call(e.cache,t))return e.cache[t];var n=e.resolve(t);if(!n)throw new Error("Failed to resolve module "+t);var r={id:t,require:e,filename:t,exports:{},loaded:!1,parent:i,children:[]};i&&i.children.push(r);var o=t.slice(0,t.lastIndexOf("/")+1);return e.cache[t]=r.exports,n.call(r.exports,r,r.exports,o,t),r.loaded=!0,e.cache[t]=r.exports}e.modules={},e.cache={},e.resolve=function(t){return{}.hasOwnProperty.call(e.modules,t)?e.modules[t]:void 0},e.define=function(t,i){e.modules[t]=i};var i=function(e){return e="/",{title:"browser",version:"v0.10.26",browser:!0,env:{},argv:[],nextTick:t.setImmediate||function(t){setTimeout(t,0)},cwd:function(){return e},chdir:function(t){e=t}}}();e.define("/gif.coffee",function(t,i,n,r){function o(t,e){return{}.hasOwnProperty.call(t,e)}function a(t,e){for(var i=0,n=e.length;ithis.frames.length;0<=this.frames.length?++e:--e)t.push(e);return t}.apply(this,arguments),n=0,r=i.length;ne;0<=e?++i:--i)t.push(i);return t}.apply(this,arguments),n=0,r=i.length;nt;this.freeWorkers.length<=t?++i:--i)e.push(i);return e}.apply(this,arguments).forEach(function(t){return function(e){var i;return console.log("spawning worker "+e),i=new Worker(t.options.workerScript),i.onmessage=function(t){return function(e){return t.activeWorkers.splice(t.activeWorkers.indexOf(i),1),t.freeWorkers.push(i),t.frameFinished(e.data)}}(t),t.freeWorkers.push(i)}}(this)),t},e.prototype.frameFinished=function(t){return console.log("frame "+t.index+" finished - "+this.activeWorkers.length+" active"),this.finishedFrames++,this.emit("progress",this.finishedFrames/this.frames.length),this.imageParts[t.index]=t,a(null,this.imageParts)?this.renderNextFrame():this.finishRendering()},e.prototype.finishRendering=function(){var t,e,i,n,r,o,a;r=0;for(var s=0,h=this.imageParts.length;s=this.frames.length?void 0:(t=this.frames[this.nextFrame++],i=this.freeWorkers.shift(),e=this.getTask(t),console.log("starting frame "+(e.index+1)+" of "+this.frames.length),this.activeWorkers.push(i),i.postMessage(e))},e.prototype.getContextData=function(t){return t.getImageData(0,0,this.options.width,this.options.height).data},e.prototype.getImageData=function(t){var e;return null!=this._canvas||(this._canvas=document.createElement("canvas"),this._canvas.width=this.options.width,this._canvas.height=this.options.height),e=this._canvas.getContext("2d"),e.setFill=this.options.background,e.fillRect(0,0,this.options.width,this.options.height),e.drawImage(t,0,0),this.getContextData(e)},e.prototype.getTask=function(t){var e,i;if(e=this.frames.indexOf(t),i={index:e,last:e===this.frames.length-1,delay:t.delay,transparent:t.transparent,width:this.options.width,height:this.options.height,quality:this.options.quality,repeat:this.options.repeat,canTransfer:"chrome"===h.name},null!=t.data)i.data=t.data;else if(null!=t.context)i.data=this.getContextData(t.context);else{if(null==t.image)throw new Error("Invalid frame");i.data=this.getImageData(t.image)}return i},e}(u),t.exports=l}),e.define("/browser.coffee",function(t,e,i,n){var r,o,a,s,h;s=navigator.userAgent.toLowerCase(),a=navigator.platform.toLowerCase(),h=s.match(/(opera|ie|firefox|chrome|version)[\s\/:]([\w\d\.]+)?.*?(safari|version[\s\/:]([\w\d\.]+)|$)/)||[null,"unknown",0],o="ie"===h[1]&&document.documentMode,r={name:"version"===h[1]?h[3]:h[1],version:o||parseFloat("opera"===h[1]&&h[4]?h[4]:h[2]),platform:{name:s.match(/ip(?:ad|od|hone)/)?"ios":(s.match(/(?:webos|android)/)||a.match(/mac|win|linux/)||["other"])[0]}},r[r.name]=!0,r[r.name+parseInt(r.version,10)]=!0,r.platform[r.platform.name]=!0,t.exports=r}),e.define("events",function(t,e,n,r){i.EventEmitter||(i.EventEmitter=function(){});var o=e.EventEmitter=i.EventEmitter,a="function"==typeof Array.isArray?Array.isArray:function(t){return"[object Array]"===Object.prototype.toString.call(t)},s=10;o.prototype.setMaxListeners=function(t){this._events||(this._events={}),this._events.maxListeners=t},o.prototype.emit=function(t){if("error"===t&&(!this._events||!this._events.error||a(this._events.error)&&!this._events.error.length))throw arguments[1]instanceof Error?arguments[1]:new Error("Uncaught, unspecified 'error' event.");if(!this._events)return!1;var e=this._events[t];if(!e)return!1;if("function"!=typeof e){if(a(e)){for(var i=Array.prototype.slice.call(arguments,1),n=e.slice(),r=0,o=n.length;r0&&this._events[t].length>i&&(this._events[t].warned=!0,console.error("(node) warning: possible EventEmitter memory leak detected. %d listeners added. Use emitter.setMaxListeners() to increase limit.",this._events[t].length),console.trace())}this._events[t].push(e)}else this._events[t]=[this._events[t],e];else this._events[t]=e;return this},o.prototype.on=o.prototype.addListener,o.prototype.once=function(t,e){var i=this;return i.on(t,function n(){i.removeListener(t,n),e.apply(this,arguments)}),this},o.prototype.removeListener=function(t,e){if("function"!=typeof e)throw new Error("removeListener only takes instances of Function");if(!this._events||!this._events[t])return this;var i=this._events[t];if(a(i)){var n=i.indexOf(e);if(n<0)return this;i.splice(n,1),0==i.length&&delete this._events[t]}else this._events[t]===e&&delete this._events[t];return this},o.prototype.removeAllListeners=function(t){return t&&this._events&&this._events[t]&&(this._events[t]=null),this},o.prototype.listeners=function(t){return this._events||(this._events={}),this._events[t]||(this._events[t]=[]),a(this._events[t])||(this._events[t]=[this._events[t]]),this._events[t]}}),t.GIF=e("/gif.coffee")}.call(this,this),function(){function t(t){return t&&t.Object===Object?t:null}function e(t){return String("0000000"+t).slice(-7)}function i(){function t(){return Math.floor(65536*(1+Math.random())).toString(16).substring(1)}return t()+t()+"-"+t()+"-"+t()+"-"+t()+"-"+t()+t()+t()}function n(t){var e={};this.settings=t,this.on=function(t,i){e[t]=i},this.emit=function(t){var i=e[t];i&&i.apply(null,Array.prototype.slice.call(arguments,1))},this.filename=t.name||i(),this.extension="",this.mimeType=""}function r(t){n.call(this,t),this.extension=".tar",this.mimeType="application/x-tar",this.fileExtension="",this.baseFilename=this.filename,this.tape=null,this.count=0,this.part=1,this.frames=0}function o(t){r.call(this,t),this.type="image/png",this.fileExtension=".png"}function a(t){r.call(this,t),this.type="image/jpeg",this.fileExtension=".jpg",this.quality=t.quality/100||.8}function s(t){var e=document.createElement("canvas");"image/webp"!==e.toDataURL("image/webp").substr(5,10)&&console.log("WebP not supported - try another export format"),n.call(this,t),this.quality=t.quality/100||.8,this.extension=".webm",this.mimeType="video/webm",this.baseFilename=this.filename,this.framerate=t.framerate,this.frames=0,this.part=1,this.videoWriter=new WebMWriter({quality:this.quality,fileWriter:null,fd:null,frameRate:this.framerate})}function h(t){n.call(this,t),t.quality=t.quality/100||.8,this.encoder=new FFMpegServer.Video(t),this.encoder.on("process",function(){this.emit("process")}.bind(this)),this.encoder.on("finished",function(t,e){var i=this.callback;i&&(this.callback=void 0,i(t,e))}.bind(this)),this.encoder.on("progress",function(t){this.settings.onProgress&&this.settings.onProgress(t)}.bind(this)),this.encoder.on("error",function(t){alert(JSON.stringify(t,null,2))}.bind(this))}function f(t){n.call(this,t),this.framerate=this.settings.framerate,this.type="video/webm",this.extension=".webm",this.stream=null,this.mediaRecorder=null,this.chunks=[]}function u(t){n.call(this,t),t.quality=31-(30*t.quality/100||10),t.workers=t.workers||4,this.extension=".gif",this.mimeType="image/gif",this.canvas=document.createElement("canvas"),this.ctx=this.canvas.getContext("2d"),this.sizeSet=!1,this.encoder=new GIF({workers:t.workers,quality:t.quality,workerScript:t.workersPath+"gif.worker.js"}),this.encoder.on("progress",function(t){this.settings.onProgress&&this.settings.onProgress(t)}.bind(this)),this.encoder.on("finished",function(t){var e=this.callback;e&&(this.callback=void 0,e(t))}.bind(this))}function d(t){function e(){function t(){return this._hooked||(this._hooked=!0,this._hookedTime=this.currentTime||0,this.pause(),it.push(this)),this._hookedTime+M.startTime}b("Capturer start"),U=window.Date.now(),T=U+M.startTime,I=window.performance.now(),F=I+M.startTime,window.Date.prototype.getTime=function(){return T},window.Date.now=function(){return T},window.setTimeout=function(t,e){var i={callback:t,time:e,triggerTime:T+e};return _.push(i),b("Timeout set to "+i.time),i},window.clearTimeout=function(t){for(var e=0;e<_.length;e++)_[e]!=t||(_.splice(e,1),b("Timeout cleared"))},window.setInterval=function(t,e){var i={callback:t,time:e,triggerTime:T+e};return S.push(i),b("Interval set to "+i.time),i},window.clearInterval=function(t){return b("clear Interval"),null},window.requestAnimationFrame=function(t){W.push(t)},window.performance.now=function(){return F};try{Object.defineProperty(HTMLVideoElement.prototype,"currentTime",{get:t}),Object.defineProperty(HTMLAudioElement.prototype,"currentTime",{get:t})}catch(t){b(t)}}function i(){e(),D.start(),R=!0}function n(){R=!1,D.stop(),l()}function r(t,e){Z(t,0,e)}function d(){r(y)}function l(){b("Capturer stop"),window.setTimeout=Z,window.setInterval=J,window.clearInterval=Y,window.clearTimeout=$,window.requestAnimationFrame=Q,window.Date.prototype.getTime=et,window.Date.now=X,window.performance.now=tt}function c(){var t=C/M.framerate;(M.frameLimit&&C>=M.frameLimit||M.timeLimit&&t>=M.timeLimit)&&(n(),v());var e=new Date(null);e.setSeconds(t),M.motionBlurFrames>2?j.textContent="CCapture "+M.format+" | "+C+" frames ("+O+" inter) | "+e.toISOString().substr(11,8):j.textContent="CCapture "+M.format+" | "+C+" frames | "+e.toISOString().substr(11,8)}function p(t){N.width===t.width&&N.height===t.height||(N.width=t.width,N.height=t.height,z=new Uint16Array(N.height*N.width*4),V.fillStyle="#0",V.fillRect(0,0,N.width,N.height))}function m(t){V.drawImage(t,0,0),q=V.getImageData(0,0,N.width,N.height);for(var e=0;e2?(p(t),m(t),O>=.5*M.motionBlurFrames?w():d()):(D.add(t),C++,b("Full Frame! "+C)))}function y(){var t=1e3/M.framerate,e=(C+O/M.motionBlurFrames)*t;T=U+e,F=I+e,it.forEach(function(t){t._hookedTime=e/1e3}),c(),b("Frame: "+C+" "+O);for(var i=0;i<_.length;i++)T>=_[i].triggerTime&&(r(_[i].callback),_.splice(i,1));for(var i=0;i=S[i].triggerTime&&(r(S[i].callback),S[i].triggerTime+=S[i].time);W.forEach(function(t){r(t,T-k)}),W=[]}function v(t){t||(t=function(t){return download(t,D.filename+D.extension,D.mimeType),!1}),D.save(t)}function b(t){A&&console.log(t)}function B(t,e){P[t]=e}function x(t){var e=P[t];e&&e.apply(null,Array.prototype.slice.call(arguments,1))}function E(t){x("progress",t)}var A,L,T,U,F,I,d,D,M=t||{},_=(new Date,[]),S=[],C=0,O=0,W=[],R=!1,P={};M.framerate=M.framerate||60,M.motionBlurFrames=2*(M.motionBlurFrames||1),A=M.verbose||!1,L=M.display||!1,M.step=1e3/M.framerate,M.timeLimit=M.timeLimit||0,M.frameLimit=M.frameLimit||0,M.startTime=M.startTime||0;var j=document.createElement("div");j.style.position="absolute",j.style.left=j.style.top=0,j.style.backgroundColor="black",j.style.fontFamily="monospace",j.style.fontSize="11px",j.style.padding="5px",j.style.color="red",j.style.zIndex=1e5,M.display&&document.body.appendChild(j);var z,q,N=document.createElement("canvas"),V=N.getContext("2d");b("Step is set to "+M.step+"ms");var G={gif:u,webm:s,ffmpegserver:h,png:o,jpg:a,"webm-mediarecorder":f},H=G[M.format];if(!H)throw"Error: Incorrect or missing format: Valid formats are "+Object.keys(G).join(", ");if(D=new H(M),D.step=d,D.on("process",y),D.on("progress",E),"performance"in window==0&&(window.performance={}),Date.now=Date.now||function(){return(new Date).getTime()},"now"in window.performance==0){var K=Date.now();performance.timing&&performance.timing.navigationStart&&(K=performance.timing.navigationStart),window.performance.now=function(){return Date.now()-K}}var Z=window.setTimeout,J=window.setInterval,Y=window.clearInterval,$=window.clearTimeout,Q=window.requestAnimationFrame,X=window.Date.now,tt=window.performance.now,et=window.Date.prototype.getTime,it=[];return{start:i,capture:g,stop:n,save:v,on:B}}var l={function:!0,object:!0},c=(parseFloat,parseInt,l[typeof exports]&&exports&&!exports.nodeType?exports:void 0),p=l[typeof module]&&module&&!module.nodeType?module:void 0,m=p&&p.exports===c?c:void 0,w=t(c&&p&&"object"==typeof global&&global),g=t(l[typeof self]&&self),y=t(l[typeof window]&&window),v=t(l[typeof this]&&this),b=w||y!==(v&&v.window)&&y||g||v||Function("return this")();"gc"in window||(window.gc=function(){}),HTMLCanvasElement.prototype.toBlob||Object.defineProperty(HTMLCanvasElement.prototype,"toBlob",{value:function(t,e,i){for(var n=atob(this.toDataURL(e,i).split(",")[1]),r=n.length,o=new Uint8Array(r),a=0;a0&&this.frames/this.settings.framerate>=this.settings.autoSaveTime?this.save(function(t){this.filename=this.baseFilename+"-part-"+e(this.part),download(t,this.filename+this.extension,this.mimeType);var i=this.count;this.dispose(),this.count=i+1,this.part++,this.filename=this.baseFilename+"-part-"+e(this.part),this.frames=0,this.step()}.bind(this)):(this.count++,this.frames++,this.step())}.bind(this),i.readAsArrayBuffer(t)},r.prototype.save=function(t){t(this.tape.save())},r.prototype.dispose=function(){this.tape=new Tar,this.count=0},o.prototype=Object.create(r.prototype),o.prototype.add=function(t){t.toBlob(function(t){r.prototype.add.call(this,t)}.bind(this),this.type)},a.prototype=Object.create(r.prototype),a.prototype.add=function(t){t.toBlob(function(t){r.prototype.add.call(this,t)}.bind(this),this.type,this.quality)},s.prototype=Object.create(n.prototype),s.prototype.start=function(t){this.dispose()},s.prototype.add=function(t){this.videoWriter.addFrame(t),this.settings.autoSaveTime>0&&this.frames/this.settings.framerate>=this.settings.autoSaveTime?this.save(function(t){this.filename=this.baseFilename+"-part-"+e(this.part),download(t,this.filename+this.extension,this.mimeType),this.dispose(),this.part++,this.filename=this.baseFilename+"-part-"+e(this.part),this.step()}.bind(this)):(this.frames++,this.step())},s.prototype.save=function(t){this.videoWriter.complete().then(t)},s.prototype.dispose=function(t){this.frames=0,this.videoWriter=new WebMWriter({quality:this.quality,fileWriter:null,fd:null,frameRate:this.framerate})},h.prototype=Object.create(n.prototype),h.prototype.start=function(){this.encoder.start(this.settings)},h.prototype.add=function(t){this.encoder.add(t)},h.prototype.save=function(t){this.callback=t,this.encoder.end()},h.prototype.safeToProceed=function(){return this.encoder.safeToProceed()},f.prototype=Object.create(n.prototype),f.prototype.add=function(t){this.stream||(this.stream=t.captureStream(this.framerate),this.mediaRecorder=new MediaRecorder(this.stream),this.mediaRecorder.start(),this.mediaRecorder.ondataavailable=function(t){this.chunks.push(t.data)}.bind(this)),this.step()},f.prototype.save=function(t){this.mediaRecorder.onstop=function(e){var i=new Blob(this.chunks,{type:"video/webm"});this.chunks=[],t(i)}.bind(this),this.mediaRecorder.stop()},u.prototype=Object.create(n.prototype),u.prototype.add=function(t){this.sizeSet||(this.encoder.setOption("width",t.width),this.encoder.setOption("height",t.height),this.sizeSet=!0),this.canvas.width=t.width,this.canvas.height=t.height,this.ctx.drawImage(t,0,0),this.encoder.addFrame(this.ctx,{copy:!0,delay:this.settings.step}),this.step()},u.prototype.save=function(t){this.callback=t,this.encoder.render()},(y||g||{}).CCapture=d,"function"==typeof define&&"object"==typeof define.amd&&define.amd?define(function(){return d}):c&&p?(m&&((p.exports=d).CCapture=d),c.CCapture=d):b.CCapture=d}(); \ No newline at end of file +"use strict";function download(t,e,i){var r,n,a,o=window,s="application/octet-stream",h=i||s,d=t,l=document,u=l.createElement("a"),f=function(t){return String(t)},c=o.Blob||o.MozBlob||o.WebKitBlob||f,p=o.MSBlobBuilder||o.WebKitBlobBuilder||o.BlobBuilder,w=e||"download";if("true"===String(this)&&(h=(d=[d,h])[0],d=d[1]),String(d).match(/^data\:[\w+\-]+\/[\w+\-]+[,;]/))return navigator.msSaveBlob?navigator.msSaveBlob(function(t){var e=t.split(/[:;,]/),i=e[1],r=("base64"==e[2]?atob:decodeURIComponent)(e.pop()),n=r.length,a=0,o=new Uint8Array(n);for(;a>8,this.data[this.pos++]=t},t.prototype.writeDoubleBE=function(t){let e=new Uint8Array(new Float64Array([t]).buffer);for(let t=e.length-1;t>=0;t--)this.writeByte(e[t])},t.prototype.writeFloatBE=function(t){let e=new Uint8Array(new Float32Array([t]).buffer);for(let t=e.length-1;t>=0;t--)this.writeByte(e[t])},t.prototype.writeString=function(t){for(let e=0;e>8),this.writeU8(t);break;case 3:this.writeU8(32|t>>16),this.writeU8(t>>8),this.writeU8(t);break;case 4:this.writeU8(16|t>>24),this.writeU8(t>>16),this.writeU8(t>>8),this.writeU8(t);break;case 5:this.writeU8(8|t/4294967296&7),this.writeU8(t>>24),this.writeU8(t>>16),this.writeU8(t>>8),this.writeU8(t);break;default:throw new Error("Bad EBML VINT size "+e)}},t.prototype.measureEBMLVarInt=function(t){if(t<127)return 1;if(t<16383)return 2;if(t<2097151)return 3;if(t<268435455)return 4;if(t<34359738367)return 5;throw new Error("EBML VINT size not supported "+t)},t.prototype.writeEBMLVarInt=function(t){this.writeEBMLVarIntWidth(t,this.measureEBMLVarInt(t))},t.prototype.writeUnsignedIntBE=function(t,e){switch(void 0===e&&(e=this.measureUnsignedInt(t)),e){case 5:this.writeU8(Math.floor(t/4294967296));case 4:this.writeU8(t>>24);case 3:this.writeU8(t>>16);case 2:this.writeU8(t>>8);case 1:this.writeU8(t);break;default:throw new Error("Bad UINT size "+e)}},t.prototype.measureUnsignedInt=function(t){return t<256?1:t<65536?2:t<1<<24?3:t<4294967296?4:5},t.prototype.getAsDataArray=function(){if(this.posthis.length)throw new Error("Seeking beyond the end of file is not allowed");this.pos=t},this.write=function(e){let o={offset:this.pos,data:e,length:function(t){let e=t.byteLength||t.length||t.size;if(!Number.isInteger(e))throw new Error("Failed to determine size of element");return e}(e)},h=o.offset>=this.length;this.pos+=o.length,this.length=Math.max(this.length,this.pos),r=r.then(function(){if(a)return new Promise(function(e,i){s(o.data).then(function(i){let r=0,n=Buffer.from(i.buffer),s=function(i,n,h){(r+=n)>=h.length?e():t.write(a,h,r,h.length-r,o.offset+r,s)};t.write(a,n,0,n.length,o.offset,s)})});if(n)return new Promise(function(t,e){n.onwriteend=t,n.seek(o.offset),n.write(new Blob([o.data]))});if(!h)for(let t=0;t=e.offset+e.length)){if(o.offsete.offset+e.length)throw new Error("Overwrite crosses blob boundaries");return o.offset==e.offset&&o.length==e.length?void(e.data=o.data):s(e.data).then(function(t){return e.data=t,s(o.data)}).then(function(t){o.data=t,e.data.set(o.data,o.offset-e.offset)})}}i.push(o)})},this.complete=function(t){return r=a||n?r.then(function(){return null}):r.then(function(){let e=[];for(let t=0;t>>0,e+=4,a){case"VP8 ":return{frame:t.substring(e,e+n),hasAlpha:i};case"ALPH":i=!0}e+=n,0!=(1&n)&&e++}var r;throw new Error("Failed to find VP8 keyframe in WebP image, is this image mistakenly encoded in the Lossless WebP format?")}function i(t){this.value=t}function r(t,e,n){if(Array.isArray(n))for(let i=0;i0&&t.trackNumber<127))throw new Error("TrackNumber must be > 0 and < 127");return r.writeEBMLVarInt(t.trackNumber),r.writeU16BE(t.timecode),r.writeByte(0),{id:160,data:[e={id:161,data:[r.getAsDataArray(),t.frame]},i={id:30113,data:[{id:166,data:[{id:238,data:1},{id:165,data:t.alpha}]}]}]}}(t):function(t){let e=new n(4);if(!(t.trackNumber>0&&t.trackNumber<127))throw new Error("TrackNumber must be > 0 and < 127");return e.writeEBMLVarInt(t.trackNumber),e.writeU16BE(t.timecode),e.writeByte(128),{id:163,data:[e.getAsDataArray(),t.frame]}}(t)}function F(){if(0===g.length)return;let t=0;for(let e=0;e=d&&F()}({frame:s.frame,duration:a,alpha:h?e(t(h,o.alphaQuality)).frame:null})},this.complete=function(){return u||I(),F(),function(){let t={id:475249515,data:B},e=new n(16+32*B.length);r(e,C.pos,t),C.write(e.getAsDataArray()),S.Cues.positionEBML.data=k(t.offset)}(),function(){let t=new n(h.size),e=C.pos;r(t,h.dataOffset,h.data),C.seek(h.dataOffset),C.write(t.getAsDataArray()),C.seek(e)}(),function(){let t=new n(8),e=C.pos;t.writeDoubleBE(y),C.seek(L.dataOffset),C.write(t.getAsDataArray()),C.seek(e)}(),C.complete("video/webm")},this.getWrittenSize=function(){return C.length},o=function(t,e){let i={};return[t,e].forEach(function(t){for(let e in t)Object.prototype.hasOwnProperty.call(t,e)&&(i[e]=t[e])}),i}(b,o||{}),function(){if(!o.frameDuration){if(!o.frameRate)throw new Error("Missing required frameDuration or frameRate setting");o.frameDuration=1e3/o.frameRate}o.quality=Math.max(Math.min(o.quality,.99999),0),void 0===o.alphaQuality?o.alphaQuality=o.quality:o.alphaQuality=Math.max(Math.min(o.alphaQuality,.99999),0)}()}};"undefined"!=typeof module&&void 0!==module.exports?module.exports=n(require("./ArrayBufferDataStream"),require("./BlobBuffer")):window.WebMWriter=n(window.ArrayBufferDataStream,window.BlobBuffer)}(),function(t){function e(t){this.data=[],this.base64=new i,this.movieDesc={w:0,h:0,fps:0,videoStreamSize:0,maxJPEGSize:0},this.avi=e.createAVIStruct(),this.headerLIST=e.createHeaderLIST(),this.moviLIST=e.createMoviLIST(),this.frameList=[],this.verbose=t||!1}e.prototype={setup:function(t,e,i,r){this.movieDesc.w=t,this.movieDesc.h=e,this.movieDesc.fps=i,this.quality=void 0===r?.92:r},addCanvasFrame:function(t){var e=t.toDataURL("image/jpeg",this.quality),i=e.indexOf(",")+1,r=this.base64.decode(e.substring(i));r.length%2==1&&r.push(0);for(var n=new ArrayBuffer(r.length),a=new Uint8Array(n),o=0;o>4)&255;if(e.push(d),null==s)break;var l=(o<<4)+(s>>2)&255;if(e.push(l),null==h)break;var u=(s<<6)+h&255;e.push(u)}return e},t.MotionJPEGBuilder=e}(window),function(){var t=["A","B","C","D","E","F","G","H","I","J","K","L","M","N","O","P","Q","R","S","T","U","V","W","X","Y","Z","a","b","c","d","e","f","g","h","i","j","k","l","m","n","o","p","q","r","s","t","u","v","w","x","y","z","0","1","2","3","4","5","6","7","8","9","+","/"];function e(t){var e,i=new Uint8Array(t);for(e=0;e>18&63]+t[a>>12&63]+t[a>>6&63]+t[63&a];switch(s.length%4){case 1:s+="=";break;case 2:s+="=="}return s}}(),function(){var t,e=window.utils;t=[{field:"fileName",length:100},{field:"fileMode",length:8},{field:"uid",length:8},{field:"gid",length:8},{field:"fileSize",length:12},{field:"mtime",length:12},{field:"checksum",length:8},{field:"type",length:1},{field:"linkName",length:100},{field:"ustar",length:8},{field:"owner",length:32},{field:"group",length:32},{field:"majorNumber",length:8},{field:"minorNumber",length:8},{field:"filenamePrefix",length:155},{field:"padding",length:12}],window.header={},window.header.structure=t,window.header.format=function(i,r){var n=e.clean(512),a=0;return t.forEach(function(t){var e,r,o=i[t.field]||"";for(e=0,r=o.length;en&&(e.push({blocks:a,length:i}),a=[],i=0),a.push(t),i+=t.headerLength+t.inputLength}),e.push({blocks:a,length:i}),e.forEach(function(e){var i=new Uint8Array(e.length),r=0;e.blocks.forEach(function(t){i.set(t.header,r),r+=t.headerLength,i.set(t.input,r),r+=t.inputLength}),t.push(i)}),t.push(new Uint8Array(2*r)),new Blob(t,{type:"octet/stream"})},n.prototype.clear=function(){this.written=0,this.out=i.clean(t)},window.Tar=n}(),function(t){if("object"==typeof exports&&"undefined"!=typeof module)module.exports=t();else if("function"==typeof define&&define.amd)define([],t);else{("undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof self?self:this).GIF=t()}}(function(){return function t(e,i,r){function n(o,s){if(!i[o]){if(!e[o]){var h="function"==typeof require&&require;if(!s&&h)return h(o,!0);if(a)return a(o,!0);var d=new Error("Cannot find module '"+o+"'");throw d.code="MODULE_NOT_FOUND",d}var l=i[o]={exports:{}};e[o][0].call(l.exports,function(t){var i=e[o][1][t];return n(i||t)},l,l.exports,t,e,i,r)}return i[o].exports}for(var a="function"==typeof require&&require,o=0;o0&&this._events[t].length>i&&(this._events[t].warned=!0,console.error("(node) warning: possible EventEmitter memory leak detected. %d listeners added. Use emitter.setMaxListeners() to increase limit.",this._events[t].length),"function"==typeof console.trace&&console.trace()),this},r.prototype.on=r.prototype.addListener,r.prototype.once=function(t,e){if(!n(e))throw TypeError("listener must be a function");var i=!1;function r(){this.removeListener(t,r),i||(i=!0,e.apply(this,arguments))}return r.listener=e,this.on(t,r),this},r.prototype.removeListener=function(t,e){var i,r,o,s;if(!n(e))throw TypeError("listener must be a function");if(!this._events||!this._events[t])return this;if(o=(i=this._events[t]).length,r=-1,i===e||n(i.listener)&&i.listener===e)delete this._events[t],this._events.removeListener&&this.emit("removeListener",t,e);else if(a(i)){for(s=o;s-- >0;)if(i[s]===e||i[s].listener&&i[s].listener===e){r=s;break}if(r<0)return this;1===i.length?(i.length=0,delete this._events[t]):i.splice(r,1),this._events.removeListener&&this.emit("removeListener",t,e)}return this},r.prototype.removeAllListeners=function(t){var e,i;if(!this._events)return this;if(!this._events.removeListener)return 0===arguments.length?this._events={}:this._events[t]&&delete this._events[t],this;if(0===arguments.length){for(e in this._events)"removeListener"!==e&&this.removeAllListeners(e);return this.removeAllListeners("removeListener"),this._events={},this}if(n(i=this._events[t]))this.removeListener(t,i);else if(i)for(;i.length;)this.removeListener(t,i[i.length-1]);return delete this._events[t],this},r.prototype.listeners=function(t){return this._events&&this._events[t]?n(this._events[t])?[this._events[t]]:this._events[t].slice():[]},r.prototype.listenerCount=function(t){if(this._events){var e=this._events[t];if(n(e))return 1;if(e)return e.length}return 0},r.listenerCount=function(t,e){return t.listenerCount(e)}},{}],2:[function(t,e,i){var r,n,a,o,s;s=navigator.userAgent.toLowerCase(),o=navigator.platform.toLowerCase(),a="ie"===(r=s.match(/(opera|ie|firefox|chrome|version)[\s\/:]([\w\d\.]+)?.*?(safari|version[\s\/:]([\w\d\.]+)|$)/)||[null,"unknown",0])[1]&&document.documentMode,(n={name:"version"===r[1]?r[3]:r[1],version:a||parseFloat("opera"===r[1]&&r[4]?r[4]:r[2]),platform:{name:s.match(/ip(?:ad|od|hone)/)?"ios":(s.match(/(?:webos|android)/)||o.match(/mac|win|linux/)||["other"])[0]}})[n.name]=!0,n[n.name+parseInt(n.version,10)]=!0,n.platform[n.platform.name]=!0,e.exports=n},{}],3:[function(t,e,i){var r,n,a,o={}.hasOwnProperty,s=[].indexOf||function(t){for(var e=0,i=this.length;ee;0<=e?++t:--t)i.push(null);return i}.call(this),e=this.spawnWorkers(),!0===this.options.globalPalette)this.renderNextFrame();else for(t=0,i=e;0<=i?ti;0<=i?++t:--t)this.renderNextFrame();return this.emit("start"),this.emit("progress",0)},n.prototype.abort=function(){for(var t;null!=(t=this.activeWorkers.shift());)this.log("killing active worker"),t.terminate();return this.running=!1,this.emit("abort")},n.prototype.spawnWorkers=function(){var t,e,i,r;return t=Math.min(this.options.workers,this.frames.length),function(){i=[];for(var r=e=this.freeWorkers.length;e<=t?rt;e<=t?r++:r--)i.push(r);return i}.apply(this).forEach((r=this,function(t){var e;return r.log("spawning worker "+t),(e=new Worker(r.options.workerScript)).onmessage=function(t){return r.activeWorkers.splice(r.activeWorkers.indexOf(e),1),r.freeWorkers.push(e),r.frameFinished(t.data)},r.freeWorkers.push(e)})),t},n.prototype.frameFinished=function(t){var e,i;if(this.log("frame "+t.index+" finished - "+this.activeWorkers.length+" active"),this.finishedFrames++,this.emit("progress",this.finishedFrames/this.frames.length),this.imageParts[t.index]=t,!0===this.options.globalPalette&&(this.options.globalPalette=t.globalPalette,this.log("global palette analyzed"),this.frames.length>2))for(e=1,i=this.freeWorkers.length;1<=i?ei;1<=i?++e:--e)this.renderNextFrame();return s.call(this.imageParts,null)>=0?this.renderNextFrame():this.finishRendering()},n.prototype.finishRendering=function(){var t,e,i,r,n,a,o,s,h,d,l,u,f,c,p,w;for(s=0,n=0,h=(c=this.imageParts).length;n=this.frames.length))return t=this.frames[this.nextFrame++],i=this.freeWorkers.shift(),e=this.getTask(t),this.log("starting frame "+(e.index+1)+" of "+this.frames.length),this.activeWorkers.push(i),i.postMessage(e)},n.prototype.getContextData=function(t){return t.getImageData(0,0,this.options.width,this.options.height).data},n.prototype.getImageData=function(t){var e;return null==this._canvas&&(this._canvas=document.createElement("canvas"),this._canvas.width=this.options.width,this._canvas.height=this.options.height),(e=this._canvas.getContext("2d")).setFill=this.options.background,e.fillRect(0,0,this.options.width,this.options.height),e.drawImage(t,0,0),this.getContextData(e)},n.prototype.getTask=function(t){var e,i;if(i={index:e=this.frames.indexOf(t),last:e===this.frames.length-1,delay:t.delay,transparent:t.transparent,width:this.options.width,height:this.options.height,quality:this.options.quality,dither:this.options.dither,globalPalette:this.options.globalPalette,repeat:this.options.repeat,canTransfer:"chrome"===a.name},null!=t.data)i.data=t.data;else if(null!=t.context)i.data=this.getContextData(t.context);else{if(null==t.image)throw new Error("Invalid frame");i.data=this.getImageData(t.image)}return i},n.prototype.log=function(){var t;if(t=1<=arguments.length?h.call(arguments,0):[],this.options.debug)return console.log.apply(console,t)},n}(),e.exports=n},{"./browser.coffee":2,events:1}]},{},[3])(3)}),function(){var t={function:!0,object:!0};function e(t){return t&&t.Object===Object?t:null}parseFloat,parseInt;var i=t[typeof exports]&&exports&&!exports.nodeType?exports:void 0,r=t[typeof module]&&module&&!module.nodeType?module:void 0,n=r&&r.exports===i?i:void 0,a=e(i&&r&&"object"==typeof global&&global),o=e(t[typeof self]&&self),s=e(t[typeof window]&&window),h=e(t[typeof this]&&this),d=a||s!==(h&&h.window)&&s||o||h||Function("return this")();function l(t){return String("0000000"+t).slice(-7)}"gc"in window||(window.gc=function(){}),HTMLCanvasElement.prototype.toBlob||Object.defineProperty(HTMLCanvasElement.prototype,"toBlob",{value:function(t,e,i){for(var r=atob(this.toDataURL(e,i).split(",")[1]),n=r.length,a=new Uint8Array(n),o=0;o=h.frameLimit||h.timeLimit&&t>=h.timeLimit)&&(q(),N());var e=new Date(null);e.setSeconds(t),h.motionBlurFrames>2?k.textContent="CCapture "+h.format+" | "+f+" frames ("+c+" inter) | "+e.toISOString().substr(11,8):k.textContent="CCapture "+h.format+" | "+f+" frames | "+e.toISOString().substr(11,8)}(),H("Frame: "+f+" "+c);for(var o=0;o=d[o].triggerTime&&(j(d[o].callback),d.splice(o,1));for(o=0;o=l[o].triggerTime&&(j(l[o].callback),l[o].triggerTime+=l[o].time);L.forEach(function(t){j(t,i-u)}),L=[]}function N(t){t||(t=function(t){return download(t,s.filename+s.extension,s.mimeType),!1}),s.save(t)}function H(t){e&&console.log(t)}return{start:function(){!function(){function t(){return this._hooked||(this._hooked=!0,this._hookedTime=this.currentTime||0,this.pause(),W.push(this)),this._hookedTime+h.startTime}H("Capturer start"),r=window.Date.now(),i=r+h.startTime,a=window.performance.now(),n=a+h.startTime,window.Date.prototype.getTime=function(){return i},window.Date.now=function(){return i},window.setTimeout=function(t,e){var r={callback:t,time:e,triggerTime:i+e};return d.push(r),H("Timeout set to "+r.time),r},window.clearTimeout=function(t){for(var e=0;e2?(function(t){F.width===t.width&&F.height===t.height||(F.width=t.width,F.height=t.height,I=new Uint16Array(F.height*F.width*4),E.fillStyle="#0",E.fillRect(0,0,F.width,F.height))}(t),function(t){E.drawImage(t,0,0),T=E.getImageData(0,0,F.width,F.height);for(var e=0;e=.5*h.motionBlurFrames?function(){for(var t=T.data,e=0;e0&&this.frames/this.settings.framerate>=this.settings.autoSaveTime?this.save(function(t){this.filename=this.baseFilename+"-part-"+l(this.part),download(t,this.filename+this.extension,this.mimeType);var e=this.count;this.dispose(),this.count=e+1,this.part++,this.filename=this.baseFilename+"-part-"+l(this.part),this.frames=0,this.step()}.bind(this)):(this.count++,this.frames++,this.step())}.bind(this),e.readAsArrayBuffer(t)},c.prototype.save=function(t){t(this.tape.save())},c.prototype.dispose=function(){this.tape=new Tar,this.count=0},p.prototype=Object.create(c.prototype),p.prototype.add=function(t){t.toBlob(function(t){c.prototype.add.call(this,t)}.bind(this),this.type)},w.prototype=Object.create(c.prototype),w.prototype.add=function(t){t.toBlob(function(t){c.prototype.add.call(this,t)}.bind(this),this.type,this.quality)},m.prototype=Object.create(c.prototype),m.prototype.add=function(t){t.toBlob(function(t){c.prototype.add.call(this,t)}.bind(this),this.type,this.quality)},g.prototype=Object.create(f.prototype),g.prototype.start=function(){this.dispose()},g.prototype.add=function(t){this.initialized||(this.builder.setup(t.width,t.height,this.settings.framerate,this.settings.quality/100||.8),this.initialized=!0),this.builder.addCanvasFrame(t),this.settings.autoSaveTime>0&&this.frames/this.settings.framerate>=this.settings.autoSaveTime?this.save(function(t){this.filename=this.baseFilename+"-part-"+l(this.part),download(t,this.filename+this.extension,this.mimeType),this.frames=0,this.part++,this.filename=this.baseFilename+"-part-"+l(this.part),this.step()}.bind(this)):(this.frames++,this.step())},g.prototype.save=function(t){this.builder.finish(t)},g.prototype.dispose=function(){this.builder=new MotionJPEGBuilder,this.initialized=!1},y.prototype=Object.create(f.prototype),y.prototype.start=function(t){this.dispose()},y.prototype.add=function(t){this.videoWriter.addFrame(t),this.settings.autoSaveTime>0&&this.frames/this.settings.framerate>=this.settings.autoSaveTime?this.save(function(t){this.filename=this.baseFilename+"-part-"+l(this.part),download(t,this.filename+this.extension,this.mimeType),this.dispose(),this.part++,this.filename=this.baseFilename+"-part-"+l(this.part),this.step()}.bind(this)):(this.frames++,this.step())},y.prototype.save=function(t){this.videoWriter.complete().then(t)},y.prototype.dispose=function(t){this.frames=0,this.videoWriter=new WebMWriter({quality:this.quality,fileWriter:null,fd:null,frameRate:this.framerate})},v.prototype=Object.create(f.prototype),v.prototype.start=function(){this.encoder.start(this.settings)},v.prototype.add=function(t){this.encoder.add(t)},v.prototype.save=function(t){this.callback=t,this.encoder.end()},v.prototype.safeToProceed=function(){return this.encoder.safeToProceed()},b.prototype=Object.create(f.prototype),b.prototype.add=function(t){this.stream||(this.stream=t.captureStream(this.framerate),this.mediaRecorder=new MediaRecorder(this.stream),this.mediaRecorder.start(),this.mediaRecorder.ondataavailable=function(t){this.chunks.push(t.data)}.bind(this)),this.step()},b.prototype.save=function(t){this.mediaRecorder.onstop=function(e){var i=new Blob(this.chunks,{type:"video/webm"});this.chunks=[],t(i)}.bind(this),this.mediaRecorder.stop()},S.prototype=Object.create(f.prototype),S.prototype.add=function(t){this.sizeSet||(this.encoder.setOption("width",t.width),this.encoder.setOption("height",t.height),this.sizeSet=!0),this.canvas.width=t.width,this.canvas.height=t.height,this.ctx.drawImage(t,0,0),this.encoder.addFrame(this.ctx,{copy:!0,delay:this.settings.step}),this.step()},S.prototype.save=function(t){this.callback=t,this.encoder.render()},(s||o||{}).CCapture=L,"function"==typeof define&&"object"==typeof define.amd&&define.amd?define(function(){return L}):i&&r?(n&&((r.exports=L).CCapture=L),i.CCapture=L):d.CCapture=L}(); \ No newline at end of file diff --git a/build/CCapture.min.js b/build/CCapture.min.js index 5f8e144..efeedda 100755 --- a/build/CCapture.min.js +++ b/build/CCapture.min.js @@ -1 +1 @@ -!function(){"use strict";function t(t){return t&&t.Object===Object?t:null}function e(t){return String("0000000"+t).slice(-7)}function i(){function t(){return Math.floor(65536*(1+Math.random())).toString(16).substring(1)}return t()+t()+"-"+t()+"-"+t()+"-"+t()+"-"+t()+t()+t()}function n(t){var e={};this.settings=t,this.on=function(t,i){e[t]=i},this.emit=function(t){var i=e[t];i&&i.apply(null,Array.prototype.slice.call(arguments,1))},this.filename=t.name||i(),this.extension="",this.mimeType=""}function o(t){n.call(this,t),this.extension=".tar",this.mimeType="application/x-tar",this.fileExtension="",this.baseFilename=this.filename,this.tape=null,this.count=0,this.part=1,this.frames=0}function r(t){o.call(this,t),this.type="image/png",this.fileExtension=".png"}function a(t){o.call(this,t),this.type="image/jpeg",this.fileExtension=".jpg",this.quality=t.quality/100||.8}function s(t){var e=document.createElement("canvas");"image/webp"!==e.toDataURL("image/webp").substr(5,10)&&console.log("WebP not supported - try another export format"),n.call(this,t),this.quality=t.quality/100||.8,this.extension=".webm",this.mimeType="video/webm",this.baseFilename=this.filename,this.framerate=t.framerate,this.frames=0,this.part=1,this.videoWriter=new WebMWriter({quality:this.quality,fileWriter:null,fd:null,frameRate:this.framerate})}function c(t){n.call(this,t),t.quality=t.quality/100||.8,this.encoder=new FFMpegServer.Video(t),this.encoder.on("process",function(){this.emit("process")}.bind(this)),this.encoder.on("finished",function(t,e){var i=this.callback;i&&(this.callback=void 0,i(t,e))}.bind(this)),this.encoder.on("progress",function(t){this.settings.onProgress&&this.settings.onProgress(t)}.bind(this)),this.encoder.on("error",function(t){alert(JSON.stringify(t,null,2))}.bind(this))}function p(t){n.call(this,t),this.framerate=this.settings.framerate,this.type="video/webm",this.extension=".webm",this.stream=null,this.mediaRecorder=null,this.chunks=[]}function h(t){n.call(this,t),t.quality=31-(30*t.quality/100||10),t.workers=t.workers||4,this.extension=".gif",this.mimeType="image/gif",this.canvas=document.createElement("canvas"),this.ctx=this.canvas.getContext("2d"),this.sizeSet=!1,this.encoder=new GIF({workers:t.workers,quality:t.quality,workerScript:t.workersPath+"gif.worker.js"}),this.encoder.on("progress",function(t){this.settings.onProgress&&this.settings.onProgress(t)}.bind(this)),this.encoder.on("finished",function(t){var e=this.callback;e&&(this.callback=void 0,e(t))}.bind(this))}function m(t){function e(){function t(){return this._hooked||(this._hooked=!0,this._hookedTime=this.currentTime||0,this.pause(),it.push(this)),this._hookedTime+B.startTime}b("Capturer start"),j=window.Date.now(),C=j+B.startTime,I=window.performance.now(),q=I+B.startTime,window.Date.prototype.getTime=function(){return C},window.Date.now=function(){return C},window.setTimeout=function(t,e){var i={callback:t,time:e,triggerTime:C+e};return E.push(i),b("Timeout set to "+i.time),i},window.clearTimeout=function(t){for(var e=0;e=B.frameLimit||B.timeLimit&&t>=B.timeLimit)&&(n(),v());var e=new Date(null);e.setSeconds(t),B.motionBlurFrames>2?z.textContent="CCapture "+B.format+" | "+R+" frames ("+A+" inter) | "+e.toISOString().substr(11,8):z.textContent="CCapture "+B.format+" | "+R+" frames | "+e.toISOString().substr(11,8)}function l(t){H.width===t.width&&H.height===t.height||(H.width=t.width,H.height=t.height,U=new Uint16Array(H.height*H.width*4),V.fillStyle="#0",V.fillRect(0,0,H.width,H.height))}function f(t){V.drawImage(t,0,0),_=V.getImageData(0,0,H.width,H.height);for(var e=0;e2?(l(t),f(t),A>=.5*B.motionBlurFrames?w():m()):(O.add(t),R++,b("Full Frame! "+R)))}function g(){var t=1e3/B.framerate,e=(R+A/B.motionBlurFrames)*t;C=j+e,q=I+e,it.forEach(function(t){t._hookedTime=e/1e3}),u(),b("Frame: "+R+" "+A);for(var i=0;i=E[i].triggerTime&&(o(E[i].callback),E.splice(i,1));for(var i=0;i=L[i].triggerTime&&(o(L[i].callback),L[i].triggerTime+=L[i].time);P.forEach(function(t){o(t,C-T)}),P=[]}function v(t){t||(t=function(t){return download(t,O.filename+O.extension,O.mimeType),!1}),O.save(t)}function b(t){S&&console.log(t)}function F(t,e){W[t]=e}function x(t){var e=W[t];e&&e.apply(null,Array.prototype.slice.call(arguments,1))}function k(t){x("progress",t)}var S,D,C,j,q,I,m,O,B=t||{},E=(new Date,[]),L=[],R=0,A=0,P=[],M=!1,W={};B.framerate=B.framerate||60,B.motionBlurFrames=2*(B.motionBlurFrames||1),S=B.verbose||!1,D=B.display||!1,B.step=1e3/B.framerate,B.timeLimit=B.timeLimit||0,B.frameLimit=B.frameLimit||0,B.startTime=B.startTime||0;var z=document.createElement("div");z.style.position="absolute",z.style.left=z.style.top=0,z.style.backgroundColor="black",z.style.fontFamily="monospace",z.style.fontSize="11px",z.style.padding="5px",z.style.color="red",z.style.zIndex=1e5,B.display&&document.body.appendChild(z);var U,_,H=document.createElement("canvas"),V=H.getContext("2d");b("Step is set to "+B.step+"ms");var G={gif:h,webm:s,ffmpegserver:c,png:r,jpg:a,"webm-mediarecorder":p},J=G[B.format];if(!J)throw"Error: Incorrect or missing format: Valid formats are "+Object.keys(G).join(", ");if(O=new J(B),O.step=m,O.on("process",g),O.on("progress",k),"performance"in window==0&&(window.performance={}),Date.now=Date.now||function(){return(new Date).getTime()},"now"in window.performance==0){var N=Date.now();performance.timing&&performance.timing.navigationStart&&(N=performance.timing.navigationStart),window.performance.now=function(){return Date.now()-N}}var K=window.setTimeout,Q=window.setInterval,X=window.clearInterval,Y=window.clearTimeout,Z=window.requestAnimationFrame,$=window.Date.now,tt=window.performance.now,et=window.Date.prototype.getTime,it=[];return{start:i,capture:y,stop:n,save:v,on:F}}var d={function:!0,object:!0},u=(parseFloat,parseInt,d[typeof exports]&&exports&&!exports.nodeType?exports:void 0),l=d[typeof module]&&module&&!module.nodeType?module:void 0,f=l&&l.exports===u?u:void 0,w=t(u&&l&&"object"==typeof global&&global),y=t(d[typeof self]&&self),g=t(d[typeof window]&&window),v=t(d[typeof this]&&this),b=w||g!==(v&&v.window)&&g||y||v||Function("return this")();"gc"in window||(window.gc=function(){}),HTMLCanvasElement.prototype.toBlob||Object.defineProperty(HTMLCanvasElement.prototype,"toBlob",{value:function(t,e,i){for(var n=atob(this.toDataURL(e,i).split(",")[1]),o=n.length,r=new Uint8Array(o),a=0;a0&&this.frames/this.settings.framerate>=this.settings.autoSaveTime?this.save(function(t){this.filename=this.baseFilename+"-part-"+e(this.part),download(t,this.filename+this.extension,this.mimeType);var i=this.count;this.dispose(),this.count=i+1,this.part++,this.filename=this.baseFilename+"-part-"+e(this.part),this.frames=0,this.step()}.bind(this)):(this.count++,this.frames++,this.step())}.bind(this),i.readAsArrayBuffer(t)},o.prototype.save=function(t){t(this.tape.save())},o.prototype.dispose=function(){this.tape=new Tar,this.count=0},r.prototype=Object.create(o.prototype),r.prototype.add=function(t){t.toBlob(function(t){o.prototype.add.call(this,t)}.bind(this),this.type)},a.prototype=Object.create(o.prototype),a.prototype.add=function(t){t.toBlob(function(t){o.prototype.add.call(this,t)}.bind(this),this.type,this.quality)},s.prototype=Object.create(n.prototype),s.prototype.start=function(t){this.dispose()},s.prototype.add=function(t){this.videoWriter.addFrame(t),this.settings.autoSaveTime>0&&this.frames/this.settings.framerate>=this.settings.autoSaveTime?this.save(function(t){this.filename=this.baseFilename+"-part-"+e(this.part),download(t,this.filename+this.extension,this.mimeType),this.dispose(),this.part++,this.filename=this.baseFilename+"-part-"+e(this.part),this.step()}.bind(this)):(this.frames++,this.step())},s.prototype.save=function(t){this.videoWriter.complete().then(t)},s.prototype.dispose=function(t){this.frames=0,this.videoWriter=new WebMWriter({quality:this.quality,fileWriter:null,fd:null,frameRate:this.framerate})},c.prototype=Object.create(n.prototype),c.prototype.start=function(){this.encoder.start(this.settings)},c.prototype.add=function(t){this.encoder.add(t)},c.prototype.save=function(t){this.callback=t,this.encoder.end()},c.prototype.safeToProceed=function(){return this.encoder.safeToProceed()},p.prototype=Object.create(n.prototype),p.prototype.add=function(t){this.stream||(this.stream=t.captureStream(this.framerate),this.mediaRecorder=new MediaRecorder(this.stream),this.mediaRecorder.start(),this.mediaRecorder.ondataavailable=function(t){this.chunks.push(t.data)}.bind(this)),this.step()},p.prototype.save=function(t){this.mediaRecorder.onstop=function(e){var i=new Blob(this.chunks,{type:"video/webm"});this.chunks=[],t(i)}.bind(this),this.mediaRecorder.stop()},h.prototype=Object.create(n.prototype),h.prototype.add=function(t){this.sizeSet||(this.encoder.setOption("width",t.width),this.encoder.setOption("height",t.height),this.sizeSet=!0),this.canvas.width=t.width,this.canvas.height=t.height,this.ctx.drawImage(t,0,0),this.encoder.addFrame(this.ctx,{copy:!0,delay:this.settings.step}),this.step()},h.prototype.save=function(t){this.callback=t,this.encoder.render()},(g||y||{}).CCapture=m,"function"==typeof define&&"object"==typeof define.amd&&define.amd?define(function(){return m}):u&&l?(f&&((l.exports=m).CCapture=m),u.CCapture=m):b.CCapture=m}(); \ No newline at end of file +!function(){"use strict";var t={function:!0,object:!0};function e(t){return t&&t.Object===Object?t:null}parseFloat,parseInt;var i=t[typeof exports]&&exports&&!exports.nodeType?exports:void 0,o=t[typeof module]&&module&&!module.nodeType?module:void 0,n=o&&o.exports===i?i:void 0,s=e(i&&o&&"object"==typeof global&&global),r=e(t[typeof self]&&self),a=e(t[typeof window]&&window),h=e(t[typeof this]&&this),p=s||a!==(h&&h.window)&&a||r||h||Function("return this")();function c(t){return String("0000000"+t).slice(-7)}"gc"in window||(window.gc=function(){}),HTMLCanvasElement.prototype.toBlob||Object.defineProperty(HTMLCanvasElement.prototype,"toBlob",{value:function(t,e,i){for(var o=atob(this.toDataURL(e,i).split(",")[1]),n=o.length,s=new Uint8Array(n),r=0;r=h.frameLimit||h.timeLimit&&t>=h.timeLimit)&&(U(),V());var e=new Date(null);e.setSeconds(t),h.motionBlurFrames>2?j.textContent="CCapture "+h.format+" | "+d+" frames ("+u+" inter) | "+e.toISOString().substr(11,8):j.textContent="CCapture "+h.format+" | "+d+" frames | "+e.toISOString().substr(11,8)}(),G("Frame: "+d+" "+u);for(var r=0;r=p[r].triggerTime&&(_(p[r].callback),p.splice(r,1));for(r=0;r=c[r].triggerTime&&(_(c[r].callback),c[r].triggerTime+=c[r].time);F.forEach(function(t){_(t,i-l)}),F=[]}function V(t){t||(t=function(t){return download(t,a.filename+a.extension,a.mimeType),!1}),a.save(t)}function G(t){e&&console.log(t)}return{start:function(){!function(){function t(){return this._hooked||(this._hooked=!0,this._hookedTime=this.currentTime||0,this.pause(),z.push(this)),this._hookedTime+h.startTime}G("Capturer start"),o=window.Date.now(),i=o+h.startTime,s=window.performance.now(),n=s+h.startTime,window.Date.prototype.getTime=function(){return i},window.Date.now=function(){return i},window.setTimeout=function(t,e){var o={callback:t,time:e,triggerTime:i+e};return p.push(o),G("Timeout set to "+o.time),o},window.clearTimeout=function(t){for(var e=0;e2?(function(t){q.width===t.width&&q.height===t.height||(q.width=t.width,q.height=t.height,C=new Uint16Array(q.height*q.width*4),O.fillStyle="#0",O.fillRect(0,0,q.width,q.height))}(t),function(t){O.drawImage(t,0,0),S=O.getImageData(0,0,q.width,q.height);for(var e=0;e=.5*h.motionBlurFrames?function(){for(var t=S.data,e=0;e0&&this.frames/this.settings.framerate>=this.settings.autoSaveTime?this.save(function(t){this.filename=this.baseFilename+"-part-"+c(this.part),download(t,this.filename+this.extension,this.mimeType);var e=this.count;this.dispose(),this.count=e+1,this.part++,this.filename=this.baseFilename+"-part-"+c(this.part),this.frames=0,this.step()}.bind(this)):(this.count++,this.frames++,this.step())}.bind(this),e.readAsArrayBuffer(t)},u.prototype.save=function(t){t(this.tape.save())},u.prototype.dispose=function(){this.tape=new Tar,this.count=0},m.prototype=Object.create(u.prototype),m.prototype.add=function(t){t.toBlob(function(t){u.prototype.add.call(this,t)}.bind(this),this.type)},f.prototype=Object.create(u.prototype),f.prototype.add=function(t){t.toBlob(function(t){u.prototype.add.call(this,t)}.bind(this),this.type,this.quality)},y.prototype=Object.create(u.prototype),y.prototype.add=function(t){t.toBlob(function(t){u.prototype.add.call(this,t)}.bind(this),this.type,this.quality)},w.prototype=Object.create(d.prototype),w.prototype.start=function(){this.dispose()},w.prototype.add=function(t){this.initialized||(this.builder.setup(t.width,t.height,this.settings.framerate,this.settings.quality/100||.8),this.initialized=!0),this.builder.addCanvasFrame(t),this.settings.autoSaveTime>0&&this.frames/this.settings.framerate>=this.settings.autoSaveTime?this.save(function(t){this.filename=this.baseFilename+"-part-"+c(this.part),download(t,this.filename+this.extension,this.mimeType),this.frames=0,this.part++,this.filename=this.baseFilename+"-part-"+c(this.part),this.step()}.bind(this)):(this.frames++,this.step())},w.prototype.save=function(t){this.builder.finish(t)},w.prototype.dispose=function(){this.builder=new MotionJPEGBuilder,this.initialized=!1},g.prototype=Object.create(d.prototype),g.prototype.start=function(t){this.dispose()},g.prototype.add=function(t){this.videoWriter.addFrame(t),this.settings.autoSaveTime>0&&this.frames/this.settings.framerate>=this.settings.autoSaveTime?this.save(function(t){this.filename=this.baseFilename+"-part-"+c(this.part),download(t,this.filename+this.extension,this.mimeType),this.dispose(),this.part++,this.filename=this.baseFilename+"-part-"+c(this.part),this.step()}.bind(this)):(this.frames++,this.step())},g.prototype.save=function(t){this.videoWriter.complete().then(t)},g.prototype.dispose=function(t){this.frames=0,this.videoWriter=new WebMWriter({quality:this.quality,fileWriter:null,fd:null,frameRate:this.framerate})},b.prototype=Object.create(d.prototype),b.prototype.start=function(){this.encoder.start(this.settings)},b.prototype.add=function(t){this.encoder.add(t)},b.prototype.save=function(t){this.callback=t,this.encoder.end()},b.prototype.safeToProceed=function(){return this.encoder.safeToProceed()},v.prototype=Object.create(d.prototype),v.prototype.add=function(t){this.stream||(this.stream=t.captureStream(this.framerate),this.mediaRecorder=new MediaRecorder(this.stream),this.mediaRecorder.start(),this.mediaRecorder.ondataavailable=function(t){this.chunks.push(t.data)}.bind(this)),this.step()},v.prototype.save=function(t){this.mediaRecorder.onstop=function(e){var i=new Blob(this.chunks,{type:"video/webm"});this.chunks=[],t(i)}.bind(this),this.mediaRecorder.stop()},T.prototype=Object.create(d.prototype),T.prototype.add=function(t){this.sizeSet||(this.encoder.setOption("width",t.width),this.encoder.setOption("height",t.height),this.sizeSet=!0),this.canvas.width=t.width,this.canvas.height=t.height,this.ctx.drawImage(t,0,0),this.encoder.addFrame(this.ctx,{copy:!0,delay:this.settings.step}),this.step()},T.prototype.save=function(t){this.callback=t,this.encoder.render()},(a||r||{}).CCapture=F,"function"==typeof define&&"object"==typeof define.amd&&define.amd?define(function(){return F}):i&&o?(n&&((o.exports=F).CCapture=F),i.CCapture=F):p.CCapture=F}(); \ No newline at end of file diff --git a/build/CCapture.mjpg.min.js b/build/CCapture.mjpg.min.js new file mode 100644 index 0000000..392e61c --- /dev/null +++ b/build/CCapture.mjpg.min.js @@ -0,0 +1 @@ +function download(e,t,i){var r,o,a,n=window,s="application/octet-stream",d=i||s,h=e,c=document,u=c.createElement("a"),l=function(e){return String(e)},p=n.Blob||n.MozBlob||n.WebKitBlob||l,m=n.MSBlobBuilder||n.WebKitBlobBuilder||n.BlobBuilder,f=t||"download";if("true"===String(this)&&(d=(h=[h,d])[0],h=h[1]),String(h).match(/^data\:[\w+\-]+\/[\w+\-]+[,;]/))return navigator.msSaveBlob?navigator.msSaveBlob(function(e){var t=e.split(/[:;,]/),i=t[1],r=("base64"==t[2]?atob:decodeURIComponent)(t.pop()),o=r.length,a=0,n=new Uint8Array(o);for(;a>4)&255;if(t.push(h),null==s)break;var c=(n<<4)+(s>>2)&255;if(t.push(c),null==d)break;var u=(s<<6)+d&255;t.push(u)}return t},e.MotionJPEGBuilder=t}(window),function(){"use strict";var e={function:!0,object:!0};function t(e){return e&&e.Object===Object?e:null}parseFloat,parseInt;var i=e[typeof exports]&&exports&&!exports.nodeType?exports:void 0,r=e[typeof module]&&module&&!module.nodeType?module:void 0,o=r&&r.exports===i?i:void 0,a=t(i&&r&&"object"==typeof global&&global),n=t(e[typeof self]&&self),s=t(e[typeof window]&&window),d=t(e[typeof this]&&this),h=a||s!==(d&&d.window)&&s||n||d||Function("return this")();function c(e){return String("0000000"+e).slice(-7)}"gc"in window||(window.gc=function(){}),HTMLCanvasElement.prototype.toBlob||Object.defineProperty(HTMLCanvasElement.prototype,"toBlob",{value:function(e,t,i){for(var r=atob(this.toDataURL(t,i).split(",")[1]),o=r.length,a=new Uint8Array(o),n=0;n=d.frameLimit||d.timeLimit&&e>=d.timeLimit)&&(U(),V());var t=new Date(null);t.setSeconds(e),d.motionBlurFrames>2?I.textContent="CCapture "+d.format+" | "+l+" frames ("+p+" inter) | "+t.toISOString().substr(11,8):I.textContent="CCapture "+d.format+" | "+l+" frames | "+t.toISOString().substr(11,8)}(),G("Frame: "+l+" "+p);for(var n=0;n=h[n].triggerTime&&(W(h[n].callback),h.splice(n,1));for(n=0;n=c[n].triggerTime&&(W(c[n].callback),c[n].triggerTime+=c[n].time);T.forEach(function(e){W(e,i-u)}),T=[]}function V(e){e||(e=function(e){return download(e,s.filename+s.extension,s.mimeType),!1}),s.save(e)}function G(e){t&&console.log(e)}return{start:function(){!function(){function e(){return this._hooked||(this._hooked=!0,this._hookedTime=this.currentTime||0,this.pause(),q.push(this)),this._hookedTime+d.startTime}G("Capturer start"),r=window.Date.now(),i=r+d.startTime,a=window.performance.now(),o=a+d.startTime,window.Date.prototype.getTime=function(){return i},window.Date.now=function(){return i},window.setTimeout=function(e,t){var r={callback:e,time:t,triggerTime:i+t};return h.push(r),G("Timeout set to "+r.time),r},window.clearTimeout=function(e){for(var t=0;t2?(function(e){B.width===e.width&&B.height===e.height||(B.width=e.width,B.height=e.height,L=new Uint16Array(B.height*B.width*4),D.fillStyle="#0",D.fillRect(0,0,B.width,B.height))}(e),function(e){D.drawImage(e,0,0),z=D.getImageData(0,0,B.width,B.height);for(var t=0;t=.5*d.motionBlurFrames?function(){for(var e=z.data,t=0;t0&&this.frames/this.settings.framerate>=this.settings.autoSaveTime?this.save(function(e){this.filename=this.baseFilename+"-part-"+c(this.part),download(e,this.filename+this.extension,this.mimeType);var t=this.count;this.dispose(),this.count=t+1,this.part++,this.filename=this.baseFilename+"-part-"+c(this.part),this.frames=0,this.step()}.bind(this)):(this.count++,this.frames++,this.step())}.bind(this),t.readAsArrayBuffer(e)},p.prototype.save=function(e){e(this.tape.save())},p.prototype.dispose=function(){this.tape=new Tar,this.count=0},m.prototype=Object.create(p.prototype),m.prototype.add=function(e){e.toBlob(function(e){p.prototype.add.call(this,e)}.bind(this),this.type)},f.prototype=Object.create(p.prototype),f.prototype.add=function(e){e.toBlob(function(e){p.prototype.add.call(this,e)}.bind(this),this.type,this.quality)},w.prototype=Object.create(p.prototype),w.prototype.add=function(e){e.toBlob(function(e){p.prototype.add.call(this,e)}.bind(this),this.type,this.quality)},y.prototype=Object.create(l.prototype),y.prototype.start=function(){this.dispose()},y.prototype.add=function(e){this.initialized||(this.builder.setup(e.width,e.height,this.settings.framerate,this.settings.quality/100||.8),this.initialized=!0),this.builder.addCanvasFrame(e),this.settings.autoSaveTime>0&&this.frames/this.settings.framerate>=this.settings.autoSaveTime?this.save(function(e){this.filename=this.baseFilename+"-part-"+c(this.part),download(e,this.filename+this.extension,this.mimeType),this.frames=0,this.part++,this.filename=this.baseFilename+"-part-"+c(this.part),this.step()}.bind(this)):(this.frames++,this.step())},y.prototype.save=function(e){this.builder.finish(e)},y.prototype.dispose=function(){this.builder=new MotionJPEGBuilder,this.initialized=!1},g.prototype=Object.create(l.prototype),g.prototype.start=function(e){this.dispose()},g.prototype.add=function(e){this.videoWriter.addFrame(e),this.settings.autoSaveTime>0&&this.frames/this.settings.framerate>=this.settings.autoSaveTime?this.save(function(e){this.filename=this.baseFilename+"-part-"+c(this.part),download(e,this.filename+this.extension,this.mimeType),this.dispose(),this.part++,this.filename=this.baseFilename+"-part-"+c(this.part),this.step()}.bind(this)):(this.frames++,this.step())},g.prototype.save=function(e){this.videoWriter.complete().then(e)},g.prototype.dispose=function(e){this.frames=0,this.videoWriter=new WebMWriter({quality:this.quality,fileWriter:null,fd:null,frameRate:this.framerate})},v.prototype=Object.create(l.prototype),v.prototype.start=function(){this.encoder.start(this.settings)},v.prototype.add=function(e){this.encoder.add(e)},v.prototype.save=function(e){this.callback=e,this.encoder.end()},v.prototype.safeToProceed=function(){return this.encoder.safeToProceed()},S.prototype=Object.create(l.prototype),S.prototype.add=function(e){this.stream||(this.stream=e.captureStream(this.framerate),this.mediaRecorder=new MediaRecorder(this.stream),this.mediaRecorder.start(),this.mediaRecorder.ondataavailable=function(e){this.chunks.push(e.data)}.bind(this)),this.step()},S.prototype.save=function(e){this.mediaRecorder.onstop=function(t){var i=new Blob(this.chunks,{type:"video/webm"});this.chunks=[],e(i)}.bind(this),this.mediaRecorder.stop()},b.prototype=Object.create(l.prototype),b.prototype.add=function(e){this.sizeSet||(this.encoder.setOption("width",e.width),this.encoder.setOption("height",e.height),this.sizeSet=!0),this.canvas.width=e.width,this.canvas.height=e.height,this.ctx.drawImage(e,0,0),this.encoder.addFrame(this.ctx,{copy:!0,delay:this.settings.step}),this.step()},b.prototype.save=function(e){this.callback=e,this.encoder.render()},(s||n||{}).CCapture=T,"function"==typeof define&&"object"==typeof define.amd&&define.amd?define(function(){return T}):i&&r?(o&&((r.exports=T).CCapture=T),i.CCapture=T):h.CCapture=T}(); \ No newline at end of file diff --git a/build/CCapture.webm.min.js b/build/CCapture.webm.min.js new file mode 100644 index 0000000..115e200 --- /dev/null +++ b/build/CCapture.webm.min.js @@ -0,0 +1 @@ +"use strict";function download(t,e,i){var n,r,a,o=window,s="application/octet-stream",d=i||s,h=t,f=document,l=f.createElement("a"),u=function(t){return String(t)},p=o.Blob||o.MozBlob||o.WebKitBlob||u,c=o.MSBlobBuilder||o.WebKitBlobBuilder||o.BlobBuilder,m=e||"download";if("true"===String(this)&&(d=(h=[h,d])[0],h=h[1]),String(h).match(/^data\:[\w+\-]+\/[\w+\-]+[,;]/))return navigator.msSaveBlob?navigator.msSaveBlob(function(t){var e=t.split(/[:;,]/),i=e[1],n=("base64"==e[2]?atob:decodeURIComponent)(e.pop()),r=n.length,a=0,o=new Uint8Array(r);for(;a>8,this.data[this.pos++]=t},t.prototype.writeDoubleBE=function(t){let e=new Uint8Array(new Float64Array([t]).buffer);for(let t=e.length-1;t>=0;t--)this.writeByte(e[t])},t.prototype.writeFloatBE=function(t){let e=new Uint8Array(new Float32Array([t]).buffer);for(let t=e.length-1;t>=0;t--)this.writeByte(e[t])},t.prototype.writeString=function(t){for(let e=0;e>8),this.writeU8(t);break;case 3:this.writeU8(32|t>>16),this.writeU8(t>>8),this.writeU8(t);break;case 4:this.writeU8(16|t>>24),this.writeU8(t>>16),this.writeU8(t>>8),this.writeU8(t);break;case 5:this.writeU8(8|t/4294967296&7),this.writeU8(t>>24),this.writeU8(t>>16),this.writeU8(t>>8),this.writeU8(t);break;default:throw new Error("Bad EBML VINT size "+e)}},t.prototype.measureEBMLVarInt=function(t){if(t<127)return 1;if(t<16383)return 2;if(t<2097151)return 3;if(t<268435455)return 4;if(t<34359738367)return 5;throw new Error("EBML VINT size not supported "+t)},t.prototype.writeEBMLVarInt=function(t){this.writeEBMLVarIntWidth(t,this.measureEBMLVarInt(t))},t.prototype.writeUnsignedIntBE=function(t,e){switch(void 0===e&&(e=this.measureUnsignedInt(t)),e){case 5:this.writeU8(Math.floor(t/4294967296));case 4:this.writeU8(t>>24);case 3:this.writeU8(t>>16);case 2:this.writeU8(t>>8);case 1:this.writeU8(t);break;default:throw new Error("Bad UINT size "+e)}},t.prototype.measureUnsignedInt=function(t){return t<256?1:t<65536?2:t<1<<24?3:t<4294967296?4:5},t.prototype.getAsDataArray=function(){if(this.posthis.length)throw new Error("Seeking beyond the end of file is not allowed");this.pos=t},this.write=function(e){let o={offset:this.pos,data:e,length:function(t){let e=t.byteLength||t.length||t.size;if(!Number.isInteger(e))throw new Error("Failed to determine size of element");return e}(e)},d=o.offset>=this.length;this.pos+=o.length,this.length=Math.max(this.length,this.pos),n=n.then(function(){if(a)return new Promise(function(e,i){s(o.data).then(function(i){let n=0,r=Buffer.from(i.buffer),s=function(i,r,d){(n+=r)>=d.length?e():t.write(a,d,n,d.length-n,o.offset+n,s)};t.write(a,r,0,r.length,o.offset,s)})});if(r)return new Promise(function(t,e){r.onwriteend=t,r.seek(o.offset),r.write(new Blob([o.data]))});if(!d)for(let t=0;t=e.offset+e.length)){if(o.offsete.offset+e.length)throw new Error("Overwrite crosses blob boundaries");return o.offset==e.offset&&o.length==e.length?void(e.data=o.data):s(e.data).then(function(t){return e.data=t,s(o.data)}).then(function(t){o.data=t,e.data.set(o.data,o.offset-e.offset)})}}i.push(o)})},this.complete=function(t){return n=a||r?n.then(function(){return null}):n.then(function(){let e=[];for(let t=0;t>>0,e+=4,a){case"VP8 ":return{frame:t.substring(e,e+r),hasAlpha:i};case"ALPH":i=!0}e+=r,0!=(1&r)&&e++}var n;throw new Error("Failed to find VP8 keyframe in WebP image, is this image mistakenly encoded in the Lossless WebP format?")}function i(t){this.value=t}function n(t,e,r){if(Array.isArray(r))for(let i=0;i0&&t.trackNumber<127))throw new Error("TrackNumber must be > 0 and < 127");return n.writeEBMLVarInt(t.trackNumber),n.writeU16BE(t.timecode),n.writeByte(0),{id:160,data:[e={id:161,data:[n.getAsDataArray(),t.frame]},i={id:30113,data:[{id:166,data:[{id:238,data:1},{id:165,data:t.alpha}]}]}]}}(t):function(t){let e=new r(4);if(!(t.trackNumber>0&&t.trackNumber<127))throw new Error("TrackNumber must be > 0 and < 127");return e.writeEBMLVarInt(t.trackNumber),e.writeU16BE(t.timecode),e.writeByte(128),{id:163,data:[e.getAsDataArray(),t.frame]}}(t)}function M(){if(0===y.length)return;let t=0;for(let e=0;e=h&&M()}({frame:s.frame,duration:a,alpha:d?e(t(d,o.alphaQuality)).frame:null})},this.complete=function(){return l||U(),M(),function(){let t={id:475249515,data:A},e=new r(16+32*A.length);n(e,T.pos,t),T.write(e.getAsDataArray()),B.Cues.positionEBML.data=k(t.offset)}(),function(){let t=new r(d.size),e=T.pos;n(t,d.dataOffset,d.data),T.seek(d.dataOffset),T.write(t.getAsDataArray()),T.seek(e)}(),function(){let t=new r(8),e=T.pos;t.writeDoubleBE(g),T.seek(E.dataOffset),T.write(t.getAsDataArray()),T.seek(e)}(),T.complete("video/webm")},this.getWrittenSize=function(){return T.length},o=function(t,e){let i={};return[t,e].forEach(function(t){for(let e in t)Object.prototype.hasOwnProperty.call(t,e)&&(i[e]=t[e])}),i}(v,o||{}),function(){if(!o.frameDuration){if(!o.frameRate)throw new Error("Missing required frameDuration or frameRate setting");o.frameDuration=1e3/o.frameRate}o.quality=Math.max(Math.min(o.quality,.99999),0),void 0===o.alphaQuality?o.alphaQuality=o.quality:o.alphaQuality=Math.max(Math.min(o.alphaQuality,.99999),0)}()}};"undefined"!=typeof module&&void 0!==module.exports?module.exports=r(require("./ArrayBufferDataStream"),require("./BlobBuffer")):window.WebMWriter=r(window.ArrayBufferDataStream,window.BlobBuffer)}(),function(){var t={function:!0,object:!0};function e(t){return t&&t.Object===Object?t:null}parseFloat,parseInt;var i=t[typeof exports]&&exports&&!exports.nodeType?exports:void 0,n=t[typeof module]&&module&&!module.nodeType?module:void 0,r=n&&n.exports===i?i:void 0,a=e(i&&n&&"object"==typeof global&&global),o=e(t[typeof self]&&self),s=e(t[typeof window]&&window),d=e(t[typeof this]&&this),h=a||s!==(d&&d.window)&&s||o||d||Function("return this")();function f(t){return String("0000000"+t).slice(-7)}"gc"in window||(window.gc=function(){}),HTMLCanvasElement.prototype.toBlob||Object.defineProperty(HTMLCanvasElement.prototype,"toBlob",{value:function(t,e,i){for(var n=atob(this.toDataURL(e,i).split(",")[1]),r=n.length,a=new Uint8Array(r),o=0;o=d.frameLimit||d.timeLimit&&t>=d.timeLimit)&&(W(),H());var e=new Date(null);e.setSeconds(t),d.motionBlurFrames>2?k.textContent="CCapture "+d.format+" | "+u+" frames ("+p+" inter) | "+e.toISOString().substr(11,8):k.textContent="CCapture "+d.format+" | "+u+" frames | "+e.toISOString().substr(11,8)}(),Q("Frame: "+u+" "+p);for(var o=0;o=h[o].triggerTime&&(V(h[o].callback),h.splice(o,1));for(o=0;o=f[o].triggerTime&&(V(f[o].callback),f[o].triggerTime+=f[o].time);E.forEach(function(t){V(t,i-l)}),E=[]}function H(t){t||(t=function(t){return download(t,s.filename+s.extension,s.mimeType),!1}),s.save(t)}function Q(t){e&&console.log(t)}return{start:function(){!function(){function t(){return this._hooked||(this._hooked=!0,this._hookedTime=this.currentTime||0,this.pause(),z.push(this)),this._hookedTime+d.startTime}Q("Capturer start"),n=window.Date.now(),i=n+d.startTime,a=window.performance.now(),r=a+d.startTime,window.Date.prototype.getTime=function(){return i},window.Date.now=function(){return i},window.setTimeout=function(t,e){var n={callback:t,time:e,triggerTime:i+e};return h.push(n),Q("Timeout set to "+n.time),n},window.clearTimeout=function(t){for(var e=0;e2?(function(t){M.width===t.width&&M.height===t.height||(M.width=t.width,M.height=t.height,U=new Uint16Array(M.height*M.width*4),I.fillStyle="#0",I.fillRect(0,0,M.width,M.height))}(t),function(t){I.drawImage(t,0,0),L=I.getImageData(0,0,M.width,M.height);for(var e=0;e=.5*d.motionBlurFrames?function(){for(var t=L.data,e=0;e0&&this.frames/this.settings.framerate>=this.settings.autoSaveTime?this.save(function(t){this.filename=this.baseFilename+"-part-"+f(this.part),download(t,this.filename+this.extension,this.mimeType);var e=this.count;this.dispose(),this.count=e+1,this.part++,this.filename=this.baseFilename+"-part-"+f(this.part),this.frames=0,this.step()}.bind(this)):(this.count++,this.frames++,this.step())}.bind(this),e.readAsArrayBuffer(t)},p.prototype.save=function(t){t(this.tape.save())},p.prototype.dispose=function(){this.tape=new Tar,this.count=0},c.prototype=Object.create(p.prototype),c.prototype.add=function(t){t.toBlob(function(t){p.prototype.add.call(this,t)}.bind(this),this.type)},m.prototype=Object.create(p.prototype),m.prototype.add=function(t){t.toBlob(function(t){p.prototype.add.call(this,t)}.bind(this),this.type,this.quality)},w.prototype=Object.create(p.prototype),w.prototype.add=function(t){t.toBlob(function(t){p.prototype.add.call(this,t)}.bind(this),this.type,this.quality)},y.prototype=Object.create(u.prototype),y.prototype.start=function(){this.dispose()},y.prototype.add=function(t){this.initialized||(this.builder.setup(t.width,t.height,this.settings.framerate,this.settings.quality/100||.8),this.initialized=!0),this.builder.addCanvasFrame(t),this.settings.autoSaveTime>0&&this.frames/this.settings.framerate>=this.settings.autoSaveTime?this.save(function(t){this.filename=this.baseFilename+"-part-"+f(this.part),download(t,this.filename+this.extension,this.mimeType),this.frames=0,this.part++,this.filename=this.baseFilename+"-part-"+f(this.part),this.step()}.bind(this)):(this.frames++,this.step())},y.prototype.save=function(t){this.builder.finish(t)},y.prototype.dispose=function(){this.builder=new MotionJPEGBuilder,this.initialized=!1},g.prototype=Object.create(u.prototype),g.prototype.start=function(t){this.dispose()},g.prototype.add=function(t){this.videoWriter.addFrame(t),this.settings.autoSaveTime>0&&this.frames/this.settings.framerate>=this.settings.autoSaveTime?this.save(function(t){this.filename=this.baseFilename+"-part-"+f(this.part),download(t,this.filename+this.extension,this.mimeType),this.dispose(),this.part++,this.filename=this.baseFilename+"-part-"+f(this.part),this.step()}.bind(this)):(this.frames++,this.step())},g.prototype.save=function(t){this.videoWriter.complete().then(t)},g.prototype.dispose=function(t){this.frames=0,this.videoWriter=new WebMWriter({quality:this.quality,fileWriter:null,fd:null,frameRate:this.framerate})},b.prototype=Object.create(u.prototype),b.prototype.start=function(){this.encoder.start(this.settings)},b.prototype.add=function(t){this.encoder.add(t)},b.prototype.save=function(t){this.callback=t,this.encoder.end()},b.prototype.safeToProceed=function(){return this.encoder.safeToProceed()},v.prototype=Object.create(u.prototype),v.prototype.add=function(t){this.stream||(this.stream=t.captureStream(this.framerate),this.mediaRecorder=new MediaRecorder(this.stream),this.mediaRecorder.start(),this.mediaRecorder.ondataavailable=function(t){this.chunks.push(t.data)}.bind(this)),this.step()},v.prototype.save=function(t){this.mediaRecorder.onstop=function(e){var i=new Blob(this.chunks,{type:"video/webm"});this.chunks=[],t(i)}.bind(this),this.mediaRecorder.stop()},B.prototype=Object.create(u.prototype),B.prototype.add=function(t){this.sizeSet||(this.encoder.setOption("width",t.width),this.encoder.setOption("height",t.height),this.sizeSet=!0),this.canvas.width=t.width,this.canvas.height=t.height,this.ctx.drawImage(t,0,0),this.encoder.addFrame(this.ctx,{copy:!0,delay:this.settings.step}),this.step()},B.prototype.save=function(t){this.callback=t,this.encoder.render()},(s||o||{}).CCapture=E,"function"==typeof define&&"object"==typeof define.amd&&define.amd?define(function(){return E}):i&&n?(r&&((n.exports=E).CCapture=E),i.CCapture=E):h.CCapture=E}(); \ No newline at end of file diff --git a/build/tar.min.js b/build/tar.min.js new file mode 100644 index 0000000..ae52fb7 --- /dev/null +++ b/build/tar.min.js @@ -0,0 +1 @@ +!function(){"use strict";var t=["A","B","C","D","E","F","G","H","I","J","K","L","M","N","O","P","Q","R","S","T","U","V","W","X","Y","Z","a","b","c","d","e","f","g","h","i","j","k","l","m","n","o","p","q","r","s","t","u","v","w","x","y","z","0","1","2","3","4","5","6","7","8","9","+","/"];function e(t){var e,n=new Uint8Array(t);for(e=0;e>18&63]+t[o>>12&63]+t[o>>6&63]+t[63&o];switch(l.length%4){case 1:l+="=";break;case 2:l+="=="}return l}}(),function(){"use strict";var t,e=window.utils;t=[{field:"fileName",length:100},{field:"fileMode",length:8},{field:"uid",length:8},{field:"gid",length:8},{field:"fileSize",length:12},{field:"mtime",length:12},{field:"checksum",length:8},{field:"type",length:1},{field:"linkName",length:100},{field:"ustar",length:8},{field:"owner",length:32},{field:"group",length:32},{field:"majorNumber",length:8},{field:"minorNumber",length:8},{field:"filenamePrefix",length:155},{field:"padding",length:12}],window.header={},window.header.structure=t,window.header.format=function(n,i){var r=e.clean(512),o=0;return t.forEach(function(t){var e,i,h=n[t.field]||"";for(e=0,i=h.length;er&&(e.push({blocks:o,length:n}),o=[],n=0),o.push(t),n+=t.headerLength+t.inputLength}),e.push({blocks:o,length:n}),e.forEach(function(e){var n=new Uint8Array(e.length),i=0;e.blocks.forEach(function(t){n.set(t.header,i),i+=t.headerLength,n.set(t.input,i),i+=t.inputLength}),t.push(n)}),t.push(new Uint8Array(2*i)),new Blob(t,{type:"octet/stream"})},r.prototype.clear=function(){this.written=0,this.out=n.clean(t)},window.Tar=r}(); \ No newline at end of file diff --git a/src/CCapture.js b/src/CCapture.js index 703972d..e3b6dfb 100755 --- a/src/CCapture.js +++ b/src/CCapture.js @@ -73,44 +73,6 @@ if (!HTMLCanvasElement.prototype.toBlob) { }); } -// @license http://opensource.org/licenses/MIT -// copyright Paul Irish 2015 - - -// Date.now() is supported everywhere except IE8. For IE8 we use the Date.now polyfill -// github.com/Financial-Times/polyfill-service/blob/master/polyfills/Date.now/polyfill.js -// as Safari 6 doesn't have support for NavigationTiming, we use a Date.now() timestamp for relative values - -// if you want values similar to what you'd get with real perf.now, place this towards the head of the page -// but in reality, you're just getting the delta between now() calls, so it's not terribly important where it's placed - - -(function(){ - - if ("performance" in window == false) { - window.performance = {}; - } - - Date.now = (Date.now || function () { // thanks IE8 - return new Date().getTime(); - }); - - if ("now" in window.performance == false){ - - var nowOffset = Date.now(); - - if (performance.timing && performance.timing.navigationStart){ - nowOffset = performance.timing.navigationStart - } - - window.performance.now = function now(){ - return Date.now() - nowOffset; - } - } - -})(); - - function pad( n ) { return String("0000000" + n).slice(-7); } @@ -267,6 +229,90 @@ CCJPEGEncoder.prototype.add = function( canvas ) { } +function CCWebPEncoder( settings ) { + + CCTarEncoder.call( this, settings ); + + this.type = 'image/webp'; + this.fileExtension = '.webp'; + this.quality = ( settings.quality / 100 ) || .8; + +} + +CCWebPEncoder.prototype = Object.create( CCTarEncoder.prototype ); + +CCWebPEncoder.prototype.add = function( canvas ) { + + canvas.toBlob( function( blob ) { + CCTarEncoder.prototype.add.call( this, blob ); + }.bind( this ), this.type, this.quality ) + +} + +function CCMJPGEncoder( settings ) { + + CCFrameEncoder.call( this, settings ); + + this.extension = 'avi'; + this.mimeType = 'video/avi'; + this.baseFilename = this.filename; + this.builder = null; + this.part = 1; + this.frames = 0; + this.initialized = false; +} + +CCMJPGEncoder.prototype = Object.create( CCFrameEncoder.prototype ); + +CCMJPGEncoder.prototype.start = function() { + + this.dispose(); + +}; + +CCMJPGEncoder.prototype.add = function( canvas ) { + + if (!this.initialized) { + this.builder.setup( + canvas.width, + canvas.height, + this.settings.framerate, + (this.settings.quality / 100) || .8 + ); + this.initialized = true; + } + + this.builder.addCanvasFrame( canvas ); + + if( this.settings.autoSaveTime > 0 && ( this.frames / this.settings.framerate ) >= this.settings.autoSaveTime ) { + this.save( function( blob ) { + this.filename = this.baseFilename + '-part-' + pad( this.part ); + download( blob, this.filename + this.extension, this.mimeType ); + this.frames = 0; + this.part++; + this.filename = this.baseFilename + '-part-' + pad( this.part ); + this.step(); + }.bind( this ) ) + } else { + this.frames++; + this.step(); + } + +} + +CCMJPGEncoder.prototype.save = function( callback ) { + + this.builder.finish( callback ); + +} + +CCMJPGEncoder.prototype.dispose = function() { + + this.builder = new MotionJPEGBuilder(); + this.initialized = false; + +} + /* WebM Encoder @@ -631,8 +677,10 @@ function CCapture( settings ) { gif: CCGIFEncoder, webm: CCWebMEncoder, ffmpegserver: CCFFMpegServerEncoder, + mjpg: CCMJPGEncoder, png: CCPNGEncoder, jpg: CCJPEGEncoder, + webp: CCWebPEncoder, 'webm-mediarecorder': CCStreamEncoder }; @@ -650,23 +698,6 @@ function CCapture( settings ) { window.performance = {}; } - Date.now = (Date.now || function () { // thanks IE8 - return new Date().getTime(); - }); - - if ("now" in window.performance == false){ - - var nowOffset = Date.now(); - - if (performance.timing && performance.timing.navigationStart){ - nowOffset = performance.timing.navigationStart - } - - window.performance.now = function now(){ - return Date.now() - nowOffset; - } - } - var _oldSetTimeout = window.setTimeout, _oldSetInterval = window.setInterval, _oldClearInterval = window.clearInterval, diff --git a/src/gif.js b/src/gif.js index a0b7b63..4f3399d 100755 --- a/src/gif.js +++ b/src/gif.js @@ -1,3 +1,3 @@ -(function(c){function a(b,d){if({}.hasOwnProperty.call(a.cache,b))return a.cache[b];var e=a.resolve(b);if(!e)throw new Error('Failed to resolve module '+b);var c={id:b,require:a,filename:b,exports:{},loaded:!1,parent:d,children:[]};d&&d.children.push(c);var f=b.slice(0,b.lastIndexOf('/')+1);return a.cache[b]=c.exports,e.call(c.exports,c,c.exports,f,b),c.loaded=!0,a.cache[b]=c.exports}a.modules={},a.cache={},a.resolve=function(b){return{}.hasOwnProperty.call(a.modules,b)?a.modules[b]:void 0},a.define=function(b,c){a.modules[b]=c};var b=function(a){return a='/',{title:'browser',version:'v0.10.26',browser:!0,env:{},argv:[],nextTick:c.setImmediate||function(a){setTimeout(a,0)},cwd:function(){return a},chdir:function(b){a=b}}}();a.define('/gif.coffee',function(d,m,l,k){function g(a,b){return{}.hasOwnProperty.call(a,b)}function j(d,b){for(var a=0,c=b.length;athis.frames.length;0<=this.frames.length?++a:--a)b.push(a);return b}.apply(this,arguments),a=0,e=b.length;aa;0<=a?++b:--b)c.push(b);return c}.apply(this,arguments),b=0,e=c.length;ba;this.freeWorkers.length<=a?++b:--b)c.push(b);return c}.apply(this,arguments).forEach(function(a){return function(c){var b;return console.log('spawning worker '+c),b=new Worker(a.options.workerScript),b.onmessage=function(a){return function(c){return a.activeWorkers.splice(a.activeWorkers.indexOf(b),1),a.freeWorkers.push(b),a.frameFinished(c.data)}}(a),a.freeWorkers.push(b)}}(this)),a},a.prototype.frameFinished=function(a){return console.log('frame '+a.index+' finished - '+this.activeWorkers.length+' active'),this.finishedFrames++,this.emit('progress',this.finishedFrames/this.frames.length),this.imageParts[a.index]=a,j(null,this.imageParts)?this.renderNextFrame():this.finishRendering()},a.prototype.finishRendering=function(){var e,a,k,m,b,d,h;b=0;for(var f=0,j=this.imageParts.length;f=this.frames.length?void 0:(c=this.frames[this.nextFrame++],b=this.freeWorkers.shift(),a=this.getTask(c),console.log('starting frame '+(a.index+1)+' of '+this.frames.length),this.activeWorkers.push(b),b.postMessage(a))},a.prototype.getContextData=function(a){return a.getImageData(0,0,this.options.width,this.options.height).data},a.prototype.getImageData=function(b){var a;return null!=this._canvas||(this._canvas=document.createElement('canvas'),this._canvas.width=this.options.width,this._canvas.height=this.options.height),a=this._canvas.getContext('2d'),a.setFill=this.options.background,a.fillRect(0,0,this.options.width,this.options.height),a.drawImage(b,0,0),this.getContextData(a)},a.prototype.getTask=function(a){var c,b;if(c=this.frames.indexOf(a),b={index:c,last:c===this.frames.length-1,delay:a.delay,transparent:a.transparent,width:this.options.width,height:this.options.height,quality:this.options.quality,repeat:this.options.repeat,canTransfer:h.name==='chrome'},null!=a.data)b.data=a.data;else if(null!=a.context)b.data=this.getContextData(a.context);else if(null!=a.image)b.data=this.getImageData(a.image);else throw new Error('Invalid frame');return b},a}(f),d.exports=e}),a.define('/browser.coffee',function(f,g,h,i){var a,d,e,c,b;c=navigator.userAgent.toLowerCase(),e=navigator.platform.toLowerCase(),b=c.match(/(opera|ie|firefox|chrome|version)[\s\/:]([\w\d\.]+)?.*?(safari|version[\s\/:]([\w\d\.]+)|$)/)||[null,'unknown',0],d=b[1]==='ie'&&document.documentMode,a={name:b[1]==='version'?b[3]:b[1],version:d||parseFloat(b[1]==='opera'&&b[4]?b[4]:b[2]),platform:{name:c.match(/ip(?:ad|od|hone)/)?'ios':(c.match(/(?:webos|android)/)||e.match(/mac|win|linux/)||['other'])[0]}},a[a.name]=!0,a[a.name+parseInt(a.version,10)]=!0,a.platform[a.platform.name]=!0,f.exports=a}),a.define('events',function(f,e,g,h){b.EventEmitter||(b.EventEmitter=function(){});var a=e.EventEmitter=b.EventEmitter,c=typeof Array.isArray==='function'?Array.isArray:function(a){return Object.prototype.toString.call(a)==='[object Array]'},d=10;a.prototype.setMaxListeners=function(a){this._events||(this._events={}),this._events.maxListeners=a},a.prototype.emit=function(f){if(f==='error'&&(!(this._events&&this._events.error)||c(this._events.error)&&!this._events.error.length))throw arguments[1]instanceof Error?arguments[1]:new Error("Uncaught, unspecified 'error' event.");if(!this._events)return!1;var a=this._events[f];if(!a)return!1;if(!(typeof a=='function'))if(c(a)){var b=Array.prototype.slice.call(arguments,1),e=a.slice();for(var d=0,g=e.length;d0&&this._events[a].length>e&&(this._events[a].warned=!0,console.error('(node) warning: possible EventEmitter memory leak detected. %d listeners added. Use emitter.setMaxListeners() to increase limit.',this._events[a].length),console.trace())}this._events[a].push(b)}else this._events[a]=[this._events[a],b];return this},a.prototype.on=a.prototype.addListener,a.prototype.once=function(b,c){var a=this;return a.on(b,function d(){a.removeListener(b,d),c.apply(this,arguments)}),this},a.prototype.removeListener=function(a,d){if('function'!==typeof d)throw new Error('removeListener only takes instances of Function');if(!(this._events&&this._events[a]))return this;var b=this._events[a];if(c(b)){var e=b.indexOf(d);if(e<0)return this;b.splice(e,1),b.length==0&&delete this._events[a]}else this._events[a]===d&&delete this._events[a];return this},a.prototype.removeAllListeners=function(a){return a&&this._events&&this._events[a]&&(this._events[a]=null),this},a.prototype.listeners=function(a){return this._events||(this._events={}),this._events[a]||(this._events[a]=[]),c(this._events[a])||(this._events[a]=[this._events[a]]),this._events[a]}}),c.GIF=a('/gif.coffee')}.call(this,this)) +// gif.js 0.2.0 - https://github.com/jnordberg/gif.js +(function(f){if(typeof exports==="object"&&typeof module!=="undefined"){module.exports=f()}else if(typeof define==="function"&&define.amd){define([],f)}else{var g;if(typeof window!=="undefined"){g=window}else if(typeof global!=="undefined"){g=global}else if(typeof self!=="undefined"){g=self}else{g=this}g.GIF=f()}})(function(){var define,module,exports;return function e(t,n,r){function s(o,u){if(!n[o]){if(!t[o]){var a=typeof require=="function"&&require;if(!u&&a)return a(o,!0);if(i)return i(o,!0);var f=new Error("Cannot find module '"+o+"'");throw f.code="MODULE_NOT_FOUND",f}var l=n[o]={exports:{}};t[o][0].call(l.exports,function(e){var n=t[o][1][e];return s(n?n:e)},l,l.exports,e,t,n,r)}return n[o].exports}var i=typeof require=="function"&&require;for(var o=0;o0&&this._events[type].length>m){this._events[type].warned=true;console.error("(node) warning: possible EventEmitter memory "+"leak detected. %d listeners added. "+"Use emitter.setMaxListeners() to increase limit.",this._events[type].length);if(typeof console.trace==="function"){console.trace()}}}return this};EventEmitter.prototype.on=EventEmitter.prototype.addListener;EventEmitter.prototype.once=function(type,listener){if(!isFunction(listener))throw TypeError("listener must be a function");var fired=false;function g(){this.removeListener(type,g);if(!fired){fired=true;listener.apply(this,arguments)}}g.listener=listener;this.on(type,g);return this};EventEmitter.prototype.removeListener=function(type,listener){var list,position,length,i;if(!isFunction(listener))throw TypeError("listener must be a function");if(!this._events||!this._events[type])return this;list=this._events[type];length=list.length;position=-1;if(list===listener||isFunction(list.listener)&&list.listener===listener){delete this._events[type];if(this._events.removeListener)this.emit("removeListener",type,listener)}else if(isObject(list)){for(i=length;i-- >0;){if(list[i]===listener||list[i].listener&&list[i].listener===listener){position=i;break}}if(position<0)return this;if(list.length===1){list.length=0;delete this._events[type]}else{list.splice(position,1)}if(this._events.removeListener)this.emit("removeListener",type,listener)}return this};EventEmitter.prototype.removeAllListeners=function(type){var key,listeners;if(!this._events)return this;if(!this._events.removeListener){if(arguments.length===0)this._events={};else if(this._events[type])delete this._events[type];return this}if(arguments.length===0){for(key in this._events){if(key==="removeListener")continue;this.removeAllListeners(key)}this.removeAllListeners("removeListener");this._events={};return this}listeners=this._events[type];if(isFunction(listeners)){this.removeListener(type,listeners)}else if(listeners){while(listeners.length)this.removeListener(type,listeners[listeners.length-1])}delete this._events[type];return this};EventEmitter.prototype.listeners=function(type){var ret;if(!this._events||!this._events[type])ret=[];else if(isFunction(this._events[type]))ret=[this._events[type]];else ret=this._events[type].slice();return ret};EventEmitter.prototype.listenerCount=function(type){if(this._events){var evlistener=this._events[type];if(isFunction(evlistener))return 1;else if(evlistener)return evlistener.length}return 0};EventEmitter.listenerCount=function(emitter,type){return emitter.listenerCount(type)};function isFunction(arg){return typeof arg==="function"}function isNumber(arg){return typeof arg==="number"}function isObject(arg){return typeof arg==="object"&&arg!==null}function isUndefined(arg){return arg===void 0}},{}],2:[function(require,module,exports){var UA,browser,mode,platform,ua;ua=navigator.userAgent.toLowerCase();platform=navigator.platform.toLowerCase();UA=ua.match(/(opera|ie|firefox|chrome|version)[\s\/:]([\w\d\.]+)?.*?(safari|version[\s\/:]([\w\d\.]+)|$)/)||[null,"unknown",0];mode=UA[1]==="ie"&&document.documentMode;browser={name:UA[1]==="version"?UA[3]:UA[1],version:mode||parseFloat(UA[1]==="opera"&&UA[4]?UA[4]:UA[2]),platform:{name:ua.match(/ip(?:ad|od|hone)/)?"ios":(ua.match(/(?:webos|android)/)||platform.match(/mac|win|linux/)||["other"])[0]}};browser[browser.name]=true;browser[browser.name+parseInt(browser.version,10)]=true;browser.platform[browser.platform.name]=true;module.exports=browser},{}],3:[function(require,module,exports){var EventEmitter,GIF,browser,extend=function(child,parent){for(var key in parent){if(hasProp.call(parent,key))child[key]=parent[key]}function ctor(){this.constructor=child}ctor.prototype=parent.prototype;child.prototype=new ctor;child.__super__=parent.prototype;return child},hasProp={}.hasOwnProperty,indexOf=[].indexOf||function(item){for(var i=0,l=this.length;iref;i=0<=ref?++j:--j){results.push(null)}return results}.call(this);numWorkers=this.spawnWorkers();if(this.options.globalPalette===true){this.renderNextFrame()}else{for(i=j=0,ref=numWorkers;0<=ref?jref;i=0<=ref?++j:--j){this.renderNextFrame()}}this.emit("start");return this.emit("progress",0)};GIF.prototype.abort=function(){var worker;while(true){worker=this.activeWorkers.shift();if(worker==null){break}this.log("killing active worker");worker.terminate()}this.running=false;return this.emit("abort")};GIF.prototype.spawnWorkers=function(){var j,numWorkers,ref,results;numWorkers=Math.min(this.options.workers,this.frames.length);(function(){results=[];for(var j=ref=this.freeWorkers.length;ref<=numWorkers?jnumWorkers;ref<=numWorkers?j++:j--){results.push(j)}return results}).apply(this).forEach(function(_this){return function(i){var worker;_this.log("spawning worker "+i);worker=new Worker(_this.options.workerScript);worker.onmessage=function(event){_this.activeWorkers.splice(_this.activeWorkers.indexOf(worker),1);_this.freeWorkers.push(worker);return _this.frameFinished(event.data)};return _this.freeWorkers.push(worker)}}(this));return numWorkers};GIF.prototype.frameFinished=function(frame){var i,j,ref;this.log("frame "+frame.index+" finished - "+this.activeWorkers.length+" active");this.finishedFrames++;this.emit("progress",this.finishedFrames/this.frames.length);this.imageParts[frame.index]=frame;if(this.options.globalPalette===true){this.options.globalPalette=frame.globalPalette;this.log("global palette analyzed");if(this.frames.length>2){for(i=j=1,ref=this.freeWorkers.length;1<=ref?jref;i=1<=ref?++j:--j){this.renderNextFrame()}}}if(indexOf.call(this.imageParts,null)>=0){return this.renderNextFrame()}else{return this.finishRendering()}};GIF.prototype.finishRendering=function(){var data,frame,i,image,j,k,l,len,len1,len2,len3,offset,page,ref,ref1,ref2;len=0;ref=this.imageParts;for(j=0,len1=ref.length;j=this.frames.length){return}frame=this.frames[this.nextFrame++];worker=this.freeWorkers.shift();task=this.getTask(frame);this.log("starting frame "+(task.index+1)+" of "+this.frames.length);this.activeWorkers.push(worker);return worker.postMessage(task)};GIF.prototype.getContextData=function(ctx){return ctx.getImageData(0,0,this.options.width,this.options.height).data};GIF.prototype.getImageData=function(image){var ctx;if(this._canvas==null){this._canvas=document.createElement("canvas");this._canvas.width=this.options.width;this._canvas.height=this.options.height}ctx=this._canvas.getContext("2d");ctx.setFill=this.options.background;ctx.fillRect(0,0,this.options.width,this.options.height);ctx.drawImage(image,0,0);return this.getContextData(ctx)};GIF.prototype.getTask=function(frame){var index,task;index=this.frames.indexOf(frame);task={index:index,last:index===this.frames.length-1,delay:frame.delay,transparent:frame.transparent,width:this.options.width,height:this.options.height,quality:this.options.quality,dither:this.options.dither,globalPalette:this.options.globalPalette,repeat:this.options.repeat,canTransfer:browser.name==="chrome"};if(frame.data!=null){task.data=frame.data}else if(frame.context!=null){task.data=this.getContextData(frame.context)}else if(frame.image!=null){task.data=this.getImageData(frame.image)}else{throw new Error("Invalid frame")}return task};GIF.prototype.log=function(){var args;args=1<=arguments.length?slice.call(arguments,0):[];if(!this.options.debug){return}return console.log.apply(console,args)};return GIF}(EventEmitter);module.exports=GIF},{"./browser.coffee":2,events:1}]},{},[3])(3)}); //# sourceMappingURL=gif.js.map -// gif.js 0.1.6 - https://github.com/jnordberg/gif.js \ No newline at end of file diff --git a/src/gif.js.map b/src/gif.js.map new file mode 100644 index 0000000..0138ef4 --- /dev/null +++ b/src/gif.js.map @@ -0,0 +1 @@ +{"version":3,"sources":["node_modules/browser-pack/_prelude.js","node_modules/events/events.js","src/browser.coffee","src/gif.coffee"],"names":["f","exports","module","define","amd","g","window","global","self","this","GIF","e","t","n","r","s","o","u","a","require","i","Error","code","l","call","length","1","EventEmitter","_events","_maxListeners","undefined","prototype","defaultMaxListeners","setMaxListeners","isNumber","isNaN","TypeError","emit","type","er","handler","len","args","listeners","error","isObject","arguments","err","context","isUndefined","isFunction","Array","slice","apply","addListener","listener","m","newListener","push","warned","console","trace","on","once","fired","removeListener","list","position","splice","removeAllListeners","key","ret","listenerCount","evlistener","emitter","arg","UA","browser","mode","platform","ua","navigator","userAgent","toLowerCase","match","document","documentMode","name","version","parseFloat","parseInt","extend","child","parent","hasProp","ctor","constructor","__super__","superClass","defaults","frameDefaults","workerScript","workers","repeat","background","quality","width","height","transparent","debug","dither","delay","copy","options","base","value","running","frames","freeWorkers","activeWorkers","setOptions","setOption","_canvas","results","addFrame","image","frame","ImageData","data","CanvasRenderingContext2D","WebGLRenderingContext","getContextData","childNodes","getImageData","render","j","numWorkers","ref","nextFrame","finishedFrames","imageParts","spawnWorkers","globalPalette","renderNextFrame","abort","worker","shift","log","terminate","Math","min","forEach","_this","Worker","onmessage","event","indexOf","frameFinished","index","finishRendering","k","len1","len2","len3","offset","page","ref1","ref2","pageSize","cursor","round","Uint8Array","set","Blob","task","getTask","postMessage","ctx","createElement","getContext","setFill","fillRect","drawImage","last","canTransfer"],"mappings":"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","sourceRoot":"","sourcesContent":["(function e(t,n,r){function s(o,u){if(!n[o]){if(!t[o]){var a=typeof require==\"function\"&&require;if(!u&&a)return a(o,!0);if(i)return i(o,!0);var f=new Error(\"Cannot find module '\"+o+\"'\");throw f.code=\"MODULE_NOT_FOUND\",f}var l=n[o]={exports:{}};t[o][0].call(l.exports,function(e){var n=t[o][1][e];return s(n?n:e)},l,l.exports,e,t,n,r)}return n[o].exports}var i=typeof require==\"function\"&&require;for(var o=0;o 0 && this._events[type].length > m) {\n this._events[type].warned = true;\n console.error('(node) warning: possible EventEmitter memory ' +\n 'leak detected. %d listeners added. ' +\n 'Use emitter.setMaxListeners() to increase limit.',\n this._events[type].length);\n if (typeof console.trace === 'function') {\n // not supported in IE 10\n console.trace();\n }\n }\n }\n\n return this;\n};\n\nEventEmitter.prototype.on = EventEmitter.prototype.addListener;\n\nEventEmitter.prototype.once = function(type, listener) {\n if (!isFunction(listener))\n throw TypeError('listener must be a function');\n\n var fired = false;\n\n function g() {\n this.removeListener(type, g);\n\n if (!fired) {\n fired = true;\n listener.apply(this, arguments);\n }\n }\n\n g.listener = listener;\n this.on(type, g);\n\n return this;\n};\n\n// emits a 'removeListener' event iff the listener was removed\nEventEmitter.prototype.removeListener = function(type, listener) {\n var list, position, length, i;\n\n if (!isFunction(listener))\n throw TypeError('listener must be a function');\n\n if (!this._events || !this._events[type])\n return this;\n\n list = this._events[type];\n length = list.length;\n position = -1;\n\n if (list === listener ||\n (isFunction(list.listener) && list.listener === listener)) {\n delete this._events[type];\n if (this._events.removeListener)\n this.emit('removeListener', type, listener);\n\n } else if (isObject(list)) {\n for (i = length; i-- > 0;) {\n if (list[i] === listener ||\n (list[i].listener && list[i].listener === listener)) {\n position = i;\n break;\n }\n }\n\n if (position < 0)\n return this;\n\n if (list.length === 1) {\n list.length = 0;\n delete this._events[type];\n } else {\n list.splice(position, 1);\n }\n\n if (this._events.removeListener)\n this.emit('removeListener', type, listener);\n }\n\n return this;\n};\n\nEventEmitter.prototype.removeAllListeners = function(type) {\n var key, listeners;\n\n if (!this._events)\n return this;\n\n // not listening for removeListener, no need to emit\n if (!this._events.removeListener) {\n if (arguments.length === 0)\n this._events = {};\n else if (this._events[type])\n delete this._events[type];\n return this;\n }\n\n // emit removeListener for all listeners on all events\n if (arguments.length === 0) {\n for (key in this._events) {\n if (key === 'removeListener') continue;\n this.removeAllListeners(key);\n }\n this.removeAllListeners('removeListener');\n this._events = {};\n return this;\n }\n\n listeners = this._events[type];\n\n if (isFunction(listeners)) {\n this.removeListener(type, listeners);\n } else if (listeners) {\n // LIFO order\n while (listeners.length)\n this.removeListener(type, listeners[listeners.length - 1]);\n }\n delete this._events[type];\n\n return this;\n};\n\nEventEmitter.prototype.listeners = function(type) {\n var ret;\n if (!this._events || !this._events[type])\n ret = [];\n else if (isFunction(this._events[type]))\n ret = [this._events[type]];\n else\n ret = this._events[type].slice();\n return ret;\n};\n\nEventEmitter.prototype.listenerCount = function(type) {\n if (this._events) {\n var evlistener = this._events[type];\n\n if (isFunction(evlistener))\n return 1;\n else if (evlistener)\n return evlistener.length;\n }\n return 0;\n};\n\nEventEmitter.listenerCount = function(emitter, type) {\n return emitter.listenerCount(type);\n};\n\nfunction isFunction(arg) {\n return typeof arg === 'function';\n}\n\nfunction isNumber(arg) {\n return typeof arg === 'number';\n}\n\nfunction isObject(arg) {\n return typeof arg === 'object' && arg !== null;\n}\n\nfunction isUndefined(arg) {\n return arg === void 0;\n}\n","### CoffeeScript version of the browser detection from MooTools ###\n\nua = navigator.userAgent.toLowerCase()\nplatform = navigator.platform.toLowerCase()\nUA = ua.match(/(opera|ie|firefox|chrome|version)[\\s\\/:]([\\w\\d\\.]+)?.*?(safari|version[\\s\\/:]([\\w\\d\\.]+)|$)/) or [null, 'unknown', 0]\nmode = UA[1] == 'ie' && document.documentMode\n\nbrowser =\n name: if UA[1] is 'version' then UA[3] else UA[1]\n version: mode or parseFloat(if UA[1] is 'opera' && UA[4] then UA[4] else UA[2])\n\n platform:\n name: if ua.match(/ip(?:ad|od|hone)/) then 'ios' else (ua.match(/(?:webos|android)/) or platform.match(/mac|win|linux/) or ['other'])[0]\n\nbrowser[browser.name] = true\nbrowser[browser.name + parseInt(browser.version, 10)] = true\nbrowser.platform[browser.platform.name] = true\n\nmodule.exports = browser\n","{EventEmitter} = require 'events'\nbrowser = require './browser.coffee'\n\nclass GIF extends EventEmitter\n\n defaults =\n workerScript: 'gif.worker.js'\n workers: 2\n repeat: 0 # repeat forever, -1 = repeat once\n background: '#fff'\n quality: 10 # pixel sample interval, lower is better\n width: null # size derermined from first frame if possible\n height: null\n transparent: null\n debug: false\n dither: false # see GIFEncoder.js for dithering options\n\n frameDefaults =\n delay: 500 # ms\n copy: false\n\n constructor: (options) ->\n @running = false\n\n @options = {}\n @frames = []\n\n @freeWorkers = []\n @activeWorkers = []\n\n @setOptions options\n for key, value of defaults\n @options[key] ?= value\n\n setOption: (key, value) ->\n @options[key] = value\n if @_canvas? and key in ['width', 'height']\n @_canvas[key] = value\n\n setOptions: (options) ->\n @setOption key, value for own key, value of options\n\n addFrame: (image, options={}) ->\n frame = {}\n frame.transparent = @options.transparent\n for key of frameDefaults\n frame[key] = options[key] or frameDefaults[key]\n\n # use the images width and height for options unless already set\n @setOption 'width', image.width unless @options.width?\n @setOption 'height', image.height unless @options.height?\n\n if ImageData? and image instanceof ImageData\n frame.data = image.data\n else if (CanvasRenderingContext2D? and image instanceof CanvasRenderingContext2D) or (WebGLRenderingContext? and image instanceof WebGLRenderingContext)\n if options.copy\n frame.data = @getContextData image\n else\n frame.context = image\n else if image.childNodes?\n if options.copy\n frame.data = @getImageData image\n else\n frame.image = image\n else\n throw new Error 'Invalid image'\n\n @frames.push frame\n\n render: ->\n throw new Error 'Already running' if @running\n\n if not @options.width? or not @options.height?\n throw new Error 'Width and height must be set prior to rendering'\n\n @running = true\n @nextFrame = 0\n @finishedFrames = 0\n\n @imageParts = (null for i in [0...@frames.length])\n numWorkers = @spawnWorkers()\n # we need to wait for the palette\n if @options.globalPalette == true\n @renderNextFrame()\n else\n @renderNextFrame() for i in [0...numWorkers]\n\n @emit 'start'\n @emit 'progress', 0\n\n abort: ->\n loop\n worker = @activeWorkers.shift()\n break unless worker?\n @log 'killing active worker'\n worker.terminate()\n @running = false\n @emit 'abort'\n\n # private\n\n spawnWorkers: ->\n numWorkers = Math.min(@options.workers, @frames.length)\n [@freeWorkers.length...numWorkers].forEach (i) =>\n @log \"spawning worker #{ i }\"\n worker = new Worker @options.workerScript\n worker.onmessage = (event) =>\n @activeWorkers.splice @activeWorkers.indexOf(worker), 1\n @freeWorkers.push worker\n @frameFinished event.data\n @freeWorkers.push worker\n return numWorkers\n\n frameFinished: (frame) ->\n @log \"frame #{ frame.index } finished - #{ @activeWorkers.length } active\"\n @finishedFrames++\n @emit 'progress', @finishedFrames / @frames.length\n @imageParts[frame.index] = frame\n # remember calculated palette, spawn the rest of the workers\n if @options.globalPalette == true\n @options.globalPalette = frame.globalPalette\n @log 'global palette analyzed'\n @renderNextFrame() for i in [1...@freeWorkers.length] if @frames.length > 2\n if null in @imageParts\n @renderNextFrame()\n else\n @finishRendering()\n\n finishRendering: ->\n len = 0\n for frame in @imageParts\n len += (frame.data.length - 1) * frame.pageSize + frame.cursor\n len += frame.pageSize - frame.cursor\n @log \"rendering finished - filesize #{ Math.round(len / 1000) }kb\"\n data = new Uint8Array len\n offset = 0\n for frame in @imageParts\n for page, i in frame.data\n data.set page, offset\n if i is frame.data.length - 1\n offset += frame.cursor\n else\n offset += frame.pageSize\n\n image = new Blob [data],\n type: 'image/gif'\n\n @emit 'finished', image, data\n\n renderNextFrame: ->\n throw new Error 'No free workers' if @freeWorkers.length is 0\n return if @nextFrame >= @frames.length # no new frame to render\n\n frame = @frames[@nextFrame++]\n worker = @freeWorkers.shift()\n task = @getTask frame\n\n @log \"starting frame #{ task.index + 1 } of #{ @frames.length }\"\n @activeWorkers.push worker\n worker.postMessage task#, [task.data.buffer]\n\n getContextData: (ctx) ->\n return ctx.getImageData(0, 0, @options.width, @options.height).data\n\n getImageData: (image) ->\n if not @_canvas?\n @_canvas = document.createElement 'canvas'\n @_canvas.width = @options.width\n @_canvas.height = @options.height\n\n ctx = @_canvas.getContext '2d'\n ctx.setFill = @options.background\n ctx.fillRect 0, 0, @options.width, @options.height\n ctx.drawImage image, 0, 0\n\n return @getContextData ctx\n\n getTask: (frame) ->\n index = @frames.indexOf frame\n task =\n index: index\n last: index is (@frames.length - 1)\n delay: frame.delay\n transparent: frame.transparent\n width: @options.width\n height: @options.height\n quality: @options.quality\n dither: @options.dither\n globalPalette: @options.globalPalette\n repeat: @options.repeat\n canTransfer: (browser.name is 'chrome')\n\n if frame.data?\n task.data = frame.data\n else if frame.context?\n task.data = @getContextData frame.context\n else if frame.image?\n task.data = @getImageData frame.image\n else\n throw new Error 'Invalid frame'\n\n return task\n\n log: (args...) ->\n return unless @options.debug\n console.log args...\n\n\nmodule.exports = GIF\n"]} diff --git a/src/gif.worker.js b/src/gif.worker.js index c408597..269624e 100755 --- a/src/gif.worker.js +++ b/src/gif.worker.js @@ -1,3 +1,3 @@ -(function(b){function a(b,d){if({}.hasOwnProperty.call(a.cache,b))return a.cache[b];var e=a.resolve(b);if(!e)throw new Error('Failed to resolve module '+b);var c={id:b,require:a,filename:b,exports:{},loaded:!1,parent:d,children:[]};d&&d.children.push(c);var f=b.slice(0,b.lastIndexOf('/')+1);return a.cache[b]=c.exports,e.call(c.exports,c,c.exports,f,b),c.loaded=!0,a.cache[b]=c.exports}a.modules={},a.cache={},a.resolve=function(b){return{}.hasOwnProperty.call(a.modules,b)?a.modules[b]:void 0},a.define=function(b,c){a.modules[b]=c},a.define('/gif.worker.coffee',function(d,e,f,g){var b,c;b=a('/GIFEncoder.js',d),c=function(a){var c,e,d,f;return c=new b(a.width,a.height),a.index===0?c.writeHeader():c.firstFrame=!1,c.setTransparent(a.transparent),c.setRepeat(a.repeat),c.setDelay(a.delay),c.setQuality(a.quality),c.addFrame(a.data),a.last&&c.finish(),d=c.stream(),a.data=d.pages,a.cursor=d.cursor,a.pageSize=d.constructor.pageSize,a.canTransfer?(f=function(c){for(var b=0,d=a.data.length;b=c.pageSize&&this.newPage(),this.pages[this.page][this.cursor++]=a},c.prototype.writeUTFBytes=function(b){for(var c=b.length,a=0;a=0&&(this.dispose=a)},b.prototype.setRepeat=function(a){this.repeat=a},b.prototype.setTransparent=function(a){this.transparent=a},b.prototype.addFrame=function(a){this.image=a,this.getImagePixels(),this.analyzePixels(),this.firstFrame&&(this.writeLSD(),this.writePalette(),this.repeat>=0&&this.writeNetscapeExt()),this.writeGraphicCtrlExt(),this.writeImageDesc(),this.firstFrame||this.writePalette(),this.writePixels(),this.firstFrame=!1},b.prototype.finish=function(){this.out.writeByte(59)},b.prototype.setQuality=function(a){a<1&&(a=1),this.sample=a},b.prototype.writeHeader=function(){this.out.writeUTFBytes('GIF89a')},b.prototype.analyzePixels=function(){var g=this.pixels.length,d=g/3;this.indexedPixels=new Uint8Array(d);var a=new f(this.pixels,this.sample);a.buildColormap(),this.colorTab=a.getColormap();var b=0;for(var c=0;c>16,l=(e&65280)>>8,m=e&255,c=0,d=16777216,j=this.colorTab.length;for(var a=0;a=0&&(a=dispose&7),a<<=2,this.out.writeByte(0|a|0|b),this.writeShort(this.delay),this.out.writeByte(this.transIndex),this.out.writeByte(0)},b.prototype.writeImageDesc=function(){this.out.writeByte(44),this.writeShort(0),this.writeShort(0),this.writeShort(this.width),this.writeShort(this.height),this.firstFrame?this.out.writeByte(0):this.out.writeByte(128|this.palSize)},b.prototype.writeLSD=function(){this.writeShort(this.width),this.writeShort(this.height),this.out.writeByte(240|this.palSize),this.out.writeByte(0),this.out.writeByte(0)},b.prototype.writeNetscapeExt=function(){this.out.writeByte(33),this.out.writeByte(255),this.out.writeByte(11),this.out.writeUTFBytes('NETSCAPE2.0'),this.out.writeByte(3),this.out.writeByte(1),this.writeShort(this.repeat),this.out.writeByte(0)},b.prototype.writePalette=function(){this.out.writeBytes(this.colorTab);var b=768-this.colorTab.length;for(var a=0;a>8&255)},b.prototype.writePixels=function(){var a=new g(this.width,this.height,this.indexedPixels,this.colorDepth);a.encode(this.out)},b.prototype.stream=function(){return this.out},e.exports=b}),a.define('/LZWEncoder.js',function(e,g,h,i){function f(y,D,C,B){function w(a,b){r[f++]=a,f>=254&&t(b)}function x(b){u(a),k=i+2,j=!0,l(i,b)}function u(b){for(var a=0;a=0){y=w-d,d===0&&(y=1);do if((d-=y)<0&&(d+=w),h[d]===g){e=n[d];continue a}while(h[d]>=0)}l(e,r),e=t,k<1<0&&(a.writeByte(f),a.writeBytes(r,0,f),f=0)}function p(a){return(1<0?g|=a<=8)w(g&255,c),g>>=8,e-=8;if((k>m||j)&&(j?(m=p(n_bits=q),j=!1):(++n_bits,n_bits==b?m=1<0)w(g&255,c),g>>=8,e-=8;t(c)}}var s=Math.max(2,B),r=new Uint8Array(256),h=new Int32Array(a),n=new Int32Array(a),g,e=0,f,k=0,m,j=!1,q,i,o;this.encode=z}var c=-1,b=12,a=5003,d=[0,1,3,7,15,31,63,127,255,511,1023,2047,4095,8191,16383,32767,65535];e.exports=f}),a.define('/TypedNeuQuant.js',function(A,F,E,D){function C(A,B){function I(){o=[],q=new Int32Array(256),t=new Int32Array(a),y=new Int32Array(a),z=new Int32Array(a>>3);var c,d;for(c=0;c>=b,o[c][1]>>=b,o[c][2]>>=b,o[c][3]=c}function K(b,a,c,e,f){o[a][0]-=b*(o[a][0]-c)/d,o[a][1]-=b*(o[a][1]-e)/d,o[a][2]-=b*(o[a][2]-f)/d}function L(j,e,n,l,k){var h=Math.abs(e-j),i=Math.min(e+j,a),g=e+1,f=e-1,m=1,b,d;while(gh)d=z[m++],gh&&(b=o[f--],b[0]-=d*(b[0]-n)/c,b[1]-=d*(b[1]-l)/c,b[2]-=d*(b[2]-k)/c)}function C(p,s,q){var h=2147483647,k=h,d=-1,m=d,c,j,e,n,l;for(c=0;c>i-b),n>g,y[c]-=l,t[c]+=l<>1,b=f+1;b>1,b=f+1;b<256;b++)q[b]=n}function E(j,i,k){var b,d,c,e=1e3,h=-1,f=q[i],g=f-1;while(f=0)f=e?f=a:(f++,c<0&&(c=-c),b=d[0]-j,b<0&&(b=-b),c+=b,c=0&&(d=o[g],c=i-d[1],c>=e?g=-1:(g--,c<0&&(c=-c),b=d[0]-j,b<0&&(b=-b),c+=b,c>h;for(a<=1&&(a=0),c=0;c=f&&(g-=f),c++,q===0&&(q=1),c%q===0)for(n-=n/D,o-=o/v,a=o>>h,a<=1&&(a=0),e=0;e>g,r=e<>3,h=6,t=1<=ByteArray.pageSize)this.newPage();this.pages[this.page][this.cursor++]=val};ByteArray.prototype.writeUTFBytes=function(string){for(var l=string.length,i=0;i=0)this.dispose=disposalCode};GIFEncoder.prototype.setRepeat=function(repeat){this.repeat=repeat};GIFEncoder.prototype.setTransparent=function(color){this.transparent=color};GIFEncoder.prototype.addFrame=function(imageData){this.image=imageData;this.colorTab=this.globalPalette&&this.globalPalette.slice?this.globalPalette:null;this.getImagePixels();this.analyzePixels();if(this.globalPalette===true)this.globalPalette=this.colorTab;if(this.firstFrame){this.writeLSD();this.writePalette();if(this.repeat>=0){this.writeNetscapeExt()}}this.writeGraphicCtrlExt();this.writeImageDesc();if(!this.firstFrame&&!this.globalPalette)this.writePalette();this.writePixels();this.firstFrame=false};GIFEncoder.prototype.finish=function(){this.out.writeByte(59)};GIFEncoder.prototype.setQuality=function(quality){if(quality<1)quality=1;this.sample=quality};GIFEncoder.prototype.setDither=function(dither){if(dither===true)dither="FloydSteinberg";this.dither=dither};GIFEncoder.prototype.setGlobalPalette=function(palette){this.globalPalette=palette};GIFEncoder.prototype.getGlobalPalette=function(){return this.globalPalette&&this.globalPalette.slice&&this.globalPalette.slice(0)||this.globalPalette};GIFEncoder.prototype.writeHeader=function(){this.out.writeUTFBytes("GIF89a")};GIFEncoder.prototype.analyzePixels=function(){if(!this.colorTab){this.neuQuant=new NeuQuant(this.pixels,this.sample);this.neuQuant.buildColormap();this.colorTab=this.neuQuant.getColormap()}if(this.dither){this.ditherPixels(this.dither.replace("-serpentine",""),this.dither.match(/-serpentine/)!==null)}else{this.indexPixels()}this.pixels=null;this.colorDepth=8;this.palSize=7;if(this.transparent!==null){this.transIndex=this.findClosest(this.transparent,true)}};GIFEncoder.prototype.indexPixels=function(imgq){var nPix=this.pixels.length/3;this.indexedPixels=new Uint8Array(nPix);var k=0;for(var j=0;j=0&&x1+x=0&&y1+y>16,(c&65280)>>8,c&255,used)};GIFEncoder.prototype.findClosestRGB=function(r,g,b,used){if(this.colorTab===null)return-1;if(this.neuQuant&&!used){return this.neuQuant.lookupRGB(r,g,b)}var c=b|g<<8|r<<16;var minpos=0;var dmin=256*256*256;var len=this.colorTab.length;for(var i=0,index=0;i=0){disp=dispose&7}disp<<=2;this.out.writeByte(0|disp|0|transp);this.writeShort(this.delay);this.out.writeByte(this.transIndex);this.out.writeByte(0)};GIFEncoder.prototype.writeImageDesc=function(){this.out.writeByte(44);this.writeShort(0);this.writeShort(0);this.writeShort(this.width);this.writeShort(this.height);if(this.firstFrame||this.globalPalette){this.out.writeByte(0)}else{this.out.writeByte(128|0|0|0|this.palSize)}};GIFEncoder.prototype.writeLSD=function(){this.writeShort(this.width);this.writeShort(this.height);this.out.writeByte(128|112|0|this.palSize);this.out.writeByte(0);this.out.writeByte(0)};GIFEncoder.prototype.writeNetscapeExt=function(){this.out.writeByte(33);this.out.writeByte(255);this.out.writeByte(11);this.out.writeUTFBytes("NETSCAPE2.0");this.out.writeByte(3);this.out.writeByte(1);this.writeShort(this.repeat);this.out.writeByte(0)};GIFEncoder.prototype.writePalette=function(){this.out.writeBytes(this.colorTab);var n=3*256-this.colorTab.length;for(var i=0;i>8&255)};GIFEncoder.prototype.writePixels=function(){var enc=new LZWEncoder(this.width,this.height,this.indexedPixels,this.colorDepth);enc.encode(this.out)};GIFEncoder.prototype.stream=function(){return this.out};module.exports=GIFEncoder},{"./LZWEncoder.js":2,"./TypedNeuQuant.js":3}],2:[function(require,module,exports){var EOF=-1;var BITS=12;var HSIZE=5003;var masks=[0,1,3,7,15,31,63,127,255,511,1023,2047,4095,8191,16383,32767,65535];function LZWEncoder(width,height,pixels,colorDepth){var initCodeSize=Math.max(2,colorDepth);var accum=new Uint8Array(256);var htab=new Int32Array(HSIZE);var codetab=new Int32Array(HSIZE);var cur_accum,cur_bits=0;var a_count;var free_ent=0;var maxcode;var clear_flg=false;var g_init_bits,ClearCode,EOFCode;function char_out(c,outs){accum[a_count++]=c;if(a_count>=254)flush_char(outs)}function cl_block(outs){cl_hash(HSIZE);free_ent=ClearCode+2;clear_flg=true;output(ClearCode,outs)}function cl_hash(hsize){for(var i=0;i=0){disp=hsize_reg-i;if(i===0)disp=1;do{if((i-=disp)<0)i+=hsize_reg;if(htab[i]===fcode){ent=codetab[i];continue outer_loop}}while(htab[i]>=0)}output(ent,outs);ent=c;if(free_ent<1<0){outs.writeByte(a_count);outs.writeBytes(accum,0,a_count);a_count=0}}function MAXCODE(n_bits){return(1<0)cur_accum|=code<=8){char_out(cur_accum&255,outs);cur_accum>>=8;cur_bits-=8}if(free_ent>maxcode||clear_flg){if(clear_flg){maxcode=MAXCODE(n_bits=g_init_bits);clear_flg=false}else{++n_bits;if(n_bits==BITS)maxcode=1<0){char_out(cur_accum&255,outs);cur_accum>>=8;cur_bits-=8}flush_char(outs)}}this.encode=encode}module.exports=LZWEncoder},{}],3:[function(require,module,exports){var ncycles=100;var netsize=256;var maxnetpos=netsize-1;var netbiasshift=4;var intbiasshift=16;var intbias=1<>betashift;var betagamma=intbias<>3;var radiusbiasshift=6;var radiusbias=1<>3);var i,v;for(i=0;i>=netbiasshift;network[i][1]>>=netbiasshift;network[i][2]>>=netbiasshift;network[i][3]=i}}function altersingle(alpha,i,b,g,r){network[i][0]-=alpha*(network[i][0]-b)/initalpha;network[i][1]-=alpha*(network[i][1]-g)/initalpha;network[i][2]-=alpha*(network[i][2]-r)/initalpha}function alterneigh(radius,i,b,g,r){var lo=Math.abs(i-radius);var hi=Math.min(i+radius,netsize);var j=i+1;var k=i-1;var m=1;var p,a;while(jlo){a=radpower[m++];if(jlo){p=network[k--];p[0]-=a*(p[0]-b)/alpharadbias;p[1]-=a*(p[1]-g)/alpharadbias;p[2]-=a*(p[2]-r)/alpharadbias}}}function contest(b,g,r){var bestd=~(1<<31);var bestbiasd=bestd;var bestpos=-1;var bestbiaspos=bestpos;var i,n,dist,biasdist,betafreq;for(i=0;i>intbiasshift-netbiasshift);if(biasdist>betashift;freq[i]-=betafreq;bias[i]+=betafreq<>1;for(j=previouscol+1;j>1;for(j=previouscol+1;j<256;j++)netindex[j]=maxnetpos}function inxsearch(b,g,r){var a,p,dist;var bestd=1e3;var best=-1;var i=netindex[g];var j=i-1;while(i=0){if(i=bestd)i=netsize;else{i++;if(dist<0)dist=-dist;a=p[0]-b;if(a<0)a=-a;dist+=a;if(dist=0){p=network[j];dist=g-p[1];if(dist>=bestd)j=-1;else{j--;if(dist<0)dist=-dist;a=p[0]-b;if(a<0)a=-a;dist+=a;if(dist>radiusbiasshift;if(rad<=1)rad=0;for(i=0;i=lengthcount)pix-=lengthcount;i++;if(delta===0)delta=1;if(i%delta===0){alpha-=alpha/alphadec;radius-=radius/radiusdec;rad=radius>>radiusbiasshift;if(rad<=1)rad=0;for(j=0;j= ByteArray.pageSize) this.newPage();\n this.pages[this.page][this.cursor++] = val;\n};\n\nByteArray.prototype.writeUTFBytes = function(string) {\n for (var l = string.length, i = 0; i < l; i++)\n this.writeByte(string.charCodeAt(i));\n};\n\nByteArray.prototype.writeBytes = function(array, offset, length) {\n for (var l = length || array.length, i = offset || 0; i < l; i++)\n this.writeByte(array[i]);\n};\n\nfunction GIFEncoder(width, height) {\n // image size\n this.width = ~~width;\n this.height = ~~height;\n\n // transparent color if given\n this.transparent = null;\n\n // transparent index in color table\n this.transIndex = 0;\n\n // -1 = no repeat, 0 = forever. anything else is repeat count\n this.repeat = -1;\n\n // frame delay (hundredths)\n this.delay = 0;\n\n this.image = null; // current frame\n this.pixels = null; // BGR byte array from frame\n this.indexedPixels = null; // converted frame indexed to palette\n this.colorDepth = null; // number of bit planes\n this.colorTab = null; // RGB palette\n this.neuQuant = null; // NeuQuant instance that was used to generate this.colorTab.\n this.usedEntry = new Array(); // active palette entries\n this.palSize = 7; // color table size (bits-1)\n this.dispose = -1; // disposal code (-1 = use default)\n this.firstFrame = true;\n this.sample = 10; // default sample interval for quantizer\n this.dither = false; // default dithering\n this.globalPalette = false;\n\n this.out = new ByteArray();\n}\n\n/*\n Sets the delay time between each frame, or changes it for subsequent frames\n (applies to last frame added)\n*/\nGIFEncoder.prototype.setDelay = function(milliseconds) {\n this.delay = Math.round(milliseconds / 10);\n};\n\n/*\n Sets frame rate in frames per second.\n*/\nGIFEncoder.prototype.setFrameRate = function(fps) {\n this.delay = Math.round(100 / fps);\n};\n\n/*\n Sets the GIF frame disposal code for the last added frame and any\n subsequent frames.\n\n Default is 0 if no transparent color has been set, otherwise 2.\n*/\nGIFEncoder.prototype.setDispose = function(disposalCode) {\n if (disposalCode >= 0) this.dispose = disposalCode;\n};\n\n/*\n Sets the number of times the set of GIF frames should be played.\n\n -1 = play once\n 0 = repeat indefinitely\n\n Default is -1\n\n Must be invoked before the first image is added\n*/\n\nGIFEncoder.prototype.setRepeat = function(repeat) {\n this.repeat = repeat;\n};\n\n/*\n Sets the transparent color for the last added frame and any subsequent\n frames. Since all colors are subject to modification in the quantization\n process, the color in the final palette for each frame closest to the given\n color becomes the transparent color for that frame. May be set to null to\n indicate no transparent color.\n*/\nGIFEncoder.prototype.setTransparent = function(color) {\n this.transparent = color;\n};\n\n/*\n Adds next GIF frame. The frame is not written immediately, but is\n actually deferred until the next frame is received so that timing\n data can be inserted. Invoking finish() flushes all frames.\n*/\nGIFEncoder.prototype.addFrame = function(imageData) {\n this.image = imageData;\n\n this.colorTab = this.globalPalette && this.globalPalette.slice ? this.globalPalette : null;\n\n this.getImagePixels(); // convert to correct format if necessary\n this.analyzePixels(); // build color table & map pixels\n\n if (this.globalPalette === true) this.globalPalette = this.colorTab;\n\n if (this.firstFrame) {\n this.writeLSD(); // logical screen descriptior\n this.writePalette(); // global color table\n if (this.repeat >= 0) {\n // use NS app extension to indicate reps\n this.writeNetscapeExt();\n }\n }\n\n this.writeGraphicCtrlExt(); // write graphic control extension\n this.writeImageDesc(); // image descriptor\n if (!this.firstFrame && !this.globalPalette) this.writePalette(); // local color table\n this.writePixels(); // encode and write pixel data\n\n this.firstFrame = false;\n};\n\n/*\n Adds final trailer to the GIF stream, if you don't call the finish method\n the GIF stream will not be valid.\n*/\nGIFEncoder.prototype.finish = function() {\n this.out.writeByte(0x3b); // gif trailer\n};\n\n/*\n Sets quality of color quantization (conversion of images to the maximum 256\n colors allowed by the GIF specification). Lower values (minimum = 1)\n produce better colors, but slow processing significantly. 10 is the\n default, and produces good color mapping at reasonable speeds. Values\n greater than 20 do not yield significant improvements in speed.\n*/\nGIFEncoder.prototype.setQuality = function(quality) {\n if (quality < 1) quality = 1;\n this.sample = quality;\n};\n\n/*\n Sets dithering method. Available are:\n - FALSE no dithering\n - TRUE or FloydSteinberg\n - FalseFloydSteinberg\n - Stucki\n - Atkinson\n You can add '-serpentine' to use serpentine scanning\n*/\nGIFEncoder.prototype.setDither = function(dither) {\n if (dither === true) dither = 'FloydSteinberg';\n this.dither = dither;\n};\n\n/*\n Sets global palette for all frames.\n You can provide TRUE to create global palette from first picture.\n Or an array of r,g,b,r,g,b,...\n*/\nGIFEncoder.prototype.setGlobalPalette = function(palette) {\n this.globalPalette = palette;\n};\n\n/*\n Returns global palette used for all frames.\n If setGlobalPalette(true) was used, then this function will return\n calculated palette after the first frame is added.\n*/\nGIFEncoder.prototype.getGlobalPalette = function() {\n return (this.globalPalette && this.globalPalette.slice && this.globalPalette.slice(0)) || this.globalPalette;\n};\n\n/*\n Writes GIF file header\n*/\nGIFEncoder.prototype.writeHeader = function() {\n this.out.writeUTFBytes(\"GIF89a\");\n};\n\n/*\n Analyzes current frame colors and creates color map.\n*/\nGIFEncoder.prototype.analyzePixels = function() {\n if (!this.colorTab) {\n this.neuQuant = new NeuQuant(this.pixels, this.sample);\n this.neuQuant.buildColormap(); // create reduced palette\n this.colorTab = this.neuQuant.getColormap();\n }\n\n // map image pixels to new palette\n if (this.dither) {\n this.ditherPixels(this.dither.replace('-serpentine', ''), this.dither.match(/-serpentine/) !== null);\n } else {\n this.indexPixels();\n }\n\n this.pixels = null;\n this.colorDepth = 8;\n this.palSize = 7;\n\n // get closest match to transparent color if specified\n if (this.transparent !== null) {\n this.transIndex = this.findClosest(this.transparent, true);\n }\n};\n\n/*\n Index pixels, without dithering\n*/\nGIFEncoder.prototype.indexPixels = function(imgq) {\n var nPix = this.pixels.length / 3;\n this.indexedPixels = new Uint8Array(nPix);\n var k = 0;\n for (var j = 0; j < nPix; j++) {\n var index = this.findClosestRGB(\n this.pixels[k++] & 0xff,\n this.pixels[k++] & 0xff,\n this.pixels[k++] & 0xff\n );\n this.usedEntry[index] = true;\n this.indexedPixels[j] = index;\n }\n};\n\n/*\n Taken from http://jsbin.com/iXofIji/2/edit by PAEz\n*/\nGIFEncoder.prototype.ditherPixels = function(kernel, serpentine) {\n var kernels = {\n FalseFloydSteinberg: [\n [3 / 8, 1, 0],\n [3 / 8, 0, 1],\n [2 / 8, 1, 1]\n ],\n FloydSteinberg: [\n [7 / 16, 1, 0],\n [3 / 16, -1, 1],\n [5 / 16, 0, 1],\n [1 / 16, 1, 1]\n ],\n Stucki: [\n [8 / 42, 1, 0],\n [4 / 42, 2, 0],\n [2 / 42, -2, 1],\n [4 / 42, -1, 1],\n [8 / 42, 0, 1],\n [4 / 42, 1, 1],\n [2 / 42, 2, 1],\n [1 / 42, -2, 2],\n [2 / 42, -1, 2],\n [4 / 42, 0, 2],\n [2 / 42, 1, 2],\n [1 / 42, 2, 2]\n ],\n Atkinson: [\n [1 / 8, 1, 0],\n [1 / 8, 2, 0],\n [1 / 8, -1, 1],\n [1 / 8, 0, 1],\n [1 / 8, 1, 1],\n [1 / 8, 0, 2]\n ]\n };\n\n if (!kernel || !kernels[kernel]) {\n throw 'Unknown dithering kernel: ' + kernel;\n }\n\n var ds = kernels[kernel];\n var index = 0,\n height = this.height,\n width = this.width,\n data = this.pixels;\n var direction = serpentine ? -1 : 1;\n\n this.indexedPixels = new Uint8Array(this.pixels.length / 3);\n\n for (var y = 0; y < height; y++) {\n\n if (serpentine) direction = direction * -1;\n\n for (var x = (direction == 1 ? 0 : width - 1), xend = (direction == 1 ? width : 0); x !== xend; x += direction) {\n\n index = (y * width) + x;\n // Get original colour\n var idx = index * 3;\n var r1 = data[idx];\n var g1 = data[idx + 1];\n var b1 = data[idx + 2];\n\n // Get converted colour\n idx = this.findClosestRGB(r1, g1, b1);\n this.usedEntry[idx] = true;\n this.indexedPixels[index] = idx;\n idx *= 3;\n var r2 = this.colorTab[idx];\n var g2 = this.colorTab[idx + 1];\n var b2 = this.colorTab[idx + 2];\n\n var er = r1 - r2;\n var eg = g1 - g2;\n var eb = b1 - b2;\n\n for (var i = (direction == 1 ? 0: ds.length - 1), end = (direction == 1 ? ds.length : 0); i !== end; i += direction) {\n var x1 = ds[i][1]; // *direction; // Should this by timesd by direction?..to make the kernel go in the opposite direction....got no idea....\n var y1 = ds[i][2];\n if (x1 + x >= 0 && x1 + x < width && y1 + y >= 0 && y1 + y < height) {\n var d = ds[i][0];\n idx = index + x1 + (y1 * width);\n idx *= 3;\n\n data[idx] = Math.max(0, Math.min(255, data[idx] + er * d));\n data[idx + 1] = Math.max(0, Math.min(255, data[idx + 1] + eg * d));\n data[idx + 2] = Math.max(0, Math.min(255, data[idx + 2] + eb * d));\n }\n }\n }\n }\n};\n\n/*\n Returns index of palette color closest to c\n*/\nGIFEncoder.prototype.findClosest = function(c, used) {\n return this.findClosestRGB((c & 0xFF0000) >> 16, (c & 0x00FF00) >> 8, (c & 0x0000FF), used);\n};\n\nGIFEncoder.prototype.findClosestRGB = function(r, g, b, used) {\n if (this.colorTab === null) return -1;\n\n if (this.neuQuant && !used) {\n return this.neuQuant.lookupRGB(r, g, b);\n }\n \n var c = b | (g << 8) | (r << 16);\n\n var minpos = 0;\n var dmin = 256 * 256 * 256;\n var len = this.colorTab.length;\n\n for (var i = 0, index = 0; i < len; index++) {\n var dr = r - (this.colorTab[i++] & 0xff);\n var dg = g - (this.colorTab[i++] & 0xff);\n var db = b - (this.colorTab[i++] & 0xff);\n var d = dr * dr + dg * dg + db * db;\n if ((!used || this.usedEntry[index]) && (d < dmin)) {\n dmin = d;\n minpos = index;\n }\n }\n\n return minpos;\n};\n\n/*\n Extracts image pixels into byte array pixels\n (removes alphachannel from canvas imagedata)\n*/\nGIFEncoder.prototype.getImagePixels = function() {\n var w = this.width;\n var h = this.height;\n this.pixels = new Uint8Array(w * h * 3);\n\n var data = this.image;\n var srcPos = 0;\n var count = 0;\n\n for (var i = 0; i < h; i++) {\n for (var j = 0; j < w; j++) {\n this.pixels[count++] = data[srcPos++];\n this.pixels[count++] = data[srcPos++];\n this.pixels[count++] = data[srcPos++];\n srcPos++;\n }\n }\n};\n\n/*\n Writes Graphic Control Extension\n*/\nGIFEncoder.prototype.writeGraphicCtrlExt = function() {\n this.out.writeByte(0x21); // extension introducer\n this.out.writeByte(0xf9); // GCE label\n this.out.writeByte(4); // data block size\n\n var transp, disp;\n if (this.transparent === null) {\n transp = 0;\n disp = 0; // dispose = no action\n } else {\n transp = 1;\n disp = 2; // force clear if using transparent color\n }\n\n if (this.dispose >= 0) {\n disp = dispose & 7; // user override\n }\n disp <<= 2;\n\n // packed fields\n this.out.writeByte(\n 0 | // 1:3 reserved\n disp | // 4:6 disposal\n 0 | // 7 user input - 0 = none\n transp // 8 transparency flag\n );\n\n this.writeShort(this.delay); // delay x 1/100 sec\n this.out.writeByte(this.transIndex); // transparent color index\n this.out.writeByte(0); // block terminator\n};\n\n/*\n Writes Image Descriptor\n*/\nGIFEncoder.prototype.writeImageDesc = function() {\n this.out.writeByte(0x2c); // image separator\n this.writeShort(0); // image position x,y = 0,0\n this.writeShort(0);\n this.writeShort(this.width); // image size\n this.writeShort(this.height);\n\n // packed fields\n if (this.firstFrame || this.globalPalette) {\n // no LCT - GCT is used for first (or only) frame\n this.out.writeByte(0);\n } else {\n // specify normal LCT\n this.out.writeByte(\n 0x80 | // 1 local color table 1=yes\n 0 | // 2 interlace - 0=no\n 0 | // 3 sorted - 0=no\n 0 | // 4-5 reserved\n this.palSize // 6-8 size of color table\n );\n }\n};\n\n/*\n Writes Logical Screen Descriptor\n*/\nGIFEncoder.prototype.writeLSD = function() {\n // logical screen size\n this.writeShort(this.width);\n this.writeShort(this.height);\n\n // packed fields\n this.out.writeByte(\n 0x80 | // 1 : global color table flag = 1 (gct used)\n 0x70 | // 2-4 : color resolution = 7\n 0x00 | // 5 : gct sort flag = 0\n this.palSize // 6-8 : gct size\n );\n\n this.out.writeByte(0); // background color index\n this.out.writeByte(0); // pixel aspect ratio - assume 1:1\n};\n\n/*\n Writes Netscape application extension to define repeat count.\n*/\nGIFEncoder.prototype.writeNetscapeExt = function() {\n this.out.writeByte(0x21); // extension introducer\n this.out.writeByte(0xff); // app extension label\n this.out.writeByte(11); // block size\n this.out.writeUTFBytes('NETSCAPE2.0'); // app id + auth code\n this.out.writeByte(3); // sub-block size\n this.out.writeByte(1); // loop sub-block id\n this.writeShort(this.repeat); // loop count (extra iterations, 0=repeat forever)\n this.out.writeByte(0); // block terminator\n};\n\n/*\n Writes color table\n*/\nGIFEncoder.prototype.writePalette = function() {\n this.out.writeBytes(this.colorTab);\n var n = (3 * 256) - this.colorTab.length;\n for (var i = 0; i < n; i++)\n this.out.writeByte(0);\n};\n\nGIFEncoder.prototype.writeShort = function(pValue) {\n this.out.writeByte(pValue & 0xFF);\n this.out.writeByte((pValue >> 8) & 0xFF);\n};\n\n/*\n Encodes and writes pixel data\n*/\nGIFEncoder.prototype.writePixels = function() {\n var enc = new LZWEncoder(this.width, this.height, this.indexedPixels, this.colorDepth);\n enc.encode(this.out);\n};\n\n/*\n Retrieves the GIF stream\n*/\nGIFEncoder.prototype.stream = function() {\n return this.out;\n};\n\nmodule.exports = GIFEncoder;\n","/*\n LZWEncoder.js\n\n Authors\n Kevin Weiner (original Java version - kweiner@fmsware.com)\n Thibault Imbert (AS3 version - bytearray.org)\n Johan Nordberg (JS version - code@johan-nordberg.com)\n\n Acknowledgements\n GIFCOMPR.C - GIF Image compression routines\n Lempel-Ziv compression based on 'compress'. GIF modifications by\n David Rowley (mgardi@watdcsu.waterloo.edu)\n GIF Image compression - modified 'compress'\n Based on: compress.c - File compression ala IEEE Computer, June 1984.\n By Authors: Spencer W. Thomas (decvax!harpo!utah-cs!utah-gr!thomas)\n Jim McKie (decvax!mcvax!jim)\n Steve Davies (decvax!vax135!petsd!peora!srd)\n Ken Turkowski (decvax!decwrl!turtlevax!ken)\n James A. Woods (decvax!ihnp4!ames!jaw)\n Joe Orost (decvax!vax135!petsd!joe)\n*/\n\nvar EOF = -1;\nvar BITS = 12;\nvar HSIZE = 5003; // 80% occupancy\nvar masks = [0x0000, 0x0001, 0x0003, 0x0007, 0x000F, 0x001F,\n 0x003F, 0x007F, 0x00FF, 0x01FF, 0x03FF, 0x07FF,\n 0x0FFF, 0x1FFF, 0x3FFF, 0x7FFF, 0xFFFF];\n\nfunction LZWEncoder(width, height, pixels, colorDepth) {\n var initCodeSize = Math.max(2, colorDepth);\n\n var accum = new Uint8Array(256);\n var htab = new Int32Array(HSIZE);\n var codetab = new Int32Array(HSIZE);\n\n var cur_accum, cur_bits = 0;\n var a_count;\n var free_ent = 0; // first unused entry\n var maxcode;\n\n // block compression parameters -- after all codes are used up,\n // and compression rate changes, start over.\n var clear_flg = false;\n\n // Algorithm: use open addressing double hashing (no chaining) on the\n // prefix code / next character combination. We do a variant of Knuth's\n // algorithm D (vol. 3, sec. 6.4) along with G. Knott's relatively-prime\n // secondary probe. Here, the modular division first probe is gives way\n // to a faster exclusive-or manipulation. Also do block compression with\n // an adaptive reset, whereby the code table is cleared when the compression\n // ratio decreases, but after the table fills. The variable-length output\n // codes are re-sized at this point, and a special CLEAR code is generated\n // for the decompressor. Late addition: construct the table according to\n // file size for noticeable speed improvement on small files. Please direct\n // questions about this implementation to ames!jaw.\n var g_init_bits, ClearCode, EOFCode;\n\n // Add a character to the end of the current packet, and if it is 254\n // characters, flush the packet to disk.\n function char_out(c, outs) {\n accum[a_count++] = c;\n if (a_count >= 254) flush_char(outs);\n }\n\n // Clear out the hash table\n // table clear for block compress\n function cl_block(outs) {\n cl_hash(HSIZE);\n free_ent = ClearCode + 2;\n clear_flg = true;\n output(ClearCode, outs);\n }\n\n // Reset code table\n function cl_hash(hsize) {\n for (var i = 0; i < hsize; ++i) htab[i] = -1;\n }\n\n function compress(init_bits, outs) {\n var fcode, c, i, ent, disp, hsize_reg, hshift;\n\n // Set up the globals: g_init_bits - initial number of bits\n g_init_bits = init_bits;\n\n // Set up the necessary values\n clear_flg = false;\n n_bits = g_init_bits;\n maxcode = MAXCODE(n_bits);\n\n ClearCode = 1 << (init_bits - 1);\n EOFCode = ClearCode + 1;\n free_ent = ClearCode + 2;\n\n a_count = 0; // clear packet\n\n ent = nextPixel();\n\n hshift = 0;\n for (fcode = HSIZE; fcode < 65536; fcode *= 2) ++hshift;\n hshift = 8 - hshift; // set hash code range bound\n hsize_reg = HSIZE;\n cl_hash(hsize_reg); // clear hash table\n\n output(ClearCode, outs);\n\n outer_loop: while ((c = nextPixel()) != EOF) {\n fcode = (c << BITS) + ent;\n i = (c << hshift) ^ ent; // xor hashing\n if (htab[i] === fcode) {\n ent = codetab[i];\n continue;\n } else if (htab[i] >= 0) { // non-empty slot\n disp = hsize_reg - i; // secondary hash (after G. Knott)\n if (i === 0) disp = 1;\n do {\n if ((i -= disp) < 0) i += hsize_reg;\n if (htab[i] === fcode) {\n ent = codetab[i];\n continue outer_loop;\n }\n } while (htab[i] >= 0);\n }\n output(ent, outs);\n ent = c;\n if (free_ent < 1 << BITS) {\n codetab[i] = free_ent++; // code -> hashtable\n htab[i] = fcode;\n } else {\n cl_block(outs);\n }\n }\n\n // Put out the final code.\n output(ent, outs);\n output(EOFCode, outs);\n }\n\n function encode(outs) {\n outs.writeByte(initCodeSize); // write \"initial code size\" byte\n remaining = width * height; // reset navigation variables\n curPixel = 0;\n compress(initCodeSize + 1, outs); // compress and write the pixel data\n outs.writeByte(0); // write block terminator\n }\n\n // Flush the packet to disk, and reset the accumulator\n function flush_char(outs) {\n if (a_count > 0) {\n outs.writeByte(a_count);\n outs.writeBytes(accum, 0, a_count);\n a_count = 0;\n }\n }\n\n function MAXCODE(n_bits) {\n return (1 << n_bits) - 1;\n }\n\n // Return the next pixel from the image\n function nextPixel() {\n if (remaining === 0) return EOF;\n --remaining;\n var pix = pixels[curPixel++];\n return pix & 0xff;\n }\n\n function output(code, outs) {\n cur_accum &= masks[cur_bits];\n\n if (cur_bits > 0) cur_accum |= (code << cur_bits);\n else cur_accum = code;\n\n cur_bits += n_bits;\n\n while (cur_bits >= 8) {\n char_out((cur_accum & 0xff), outs);\n cur_accum >>= 8;\n cur_bits -= 8;\n }\n\n // If the next entry is going to be too big for the code size,\n // then increase it, if possible.\n if (free_ent > maxcode || clear_flg) {\n if (clear_flg) {\n maxcode = MAXCODE(n_bits = g_init_bits);\n clear_flg = false;\n } else {\n ++n_bits;\n if (n_bits == BITS) maxcode = 1 << BITS;\n else maxcode = MAXCODE(n_bits);\n }\n }\n\n if (code == EOFCode) {\n // At EOF, write the rest of the buffer.\n while (cur_bits > 0) {\n char_out((cur_accum & 0xff), outs);\n cur_accum >>= 8;\n cur_bits -= 8;\n }\n flush_char(outs);\n }\n }\n\n this.encode = encode;\n}\n\nmodule.exports = LZWEncoder;\n","/* NeuQuant Neural-Net Quantization Algorithm\n * ------------------------------------------\n *\n * Copyright (c) 1994 Anthony Dekker\n *\n * NEUQUANT Neural-Net quantization algorithm by Anthony Dekker, 1994.\n * See \"Kohonen neural networks for optimal colour quantization\"\n * in \"Network: Computation in Neural Systems\" Vol. 5 (1994) pp 351-367.\n * for a discussion of the algorithm.\n * See also http://members.ozemail.com.au/~dekker/NEUQUANT.HTML\n *\n * Any party obtaining a copy of these files from the author, directly or\n * indirectly, is granted, free of charge, a full and unrestricted irrevocable,\n * world-wide, paid up, royalty-free, nonexclusive right and license to deal\n * in this software and documentation files (the \"Software\"), including without\n * limitation the rights to use, copy, modify, merge, publish, distribute, sublicense,\n * and/or sell copies of the Software, and to permit persons who receive\n * copies from any such party to do so, with the only requirement being\n * that this copyright notice remain intact.\n *\n * (JavaScript port 2012 by Johan Nordberg)\n */\n\nvar ncycles = 100; // number of learning cycles\nvar netsize = 256; // number of colors used\nvar maxnetpos = netsize - 1;\n\n// defs for freq and bias\nvar netbiasshift = 4; // bias for colour values\nvar intbiasshift = 16; // bias for fractions\nvar intbias = (1 << intbiasshift);\nvar gammashift = 10;\nvar gamma = (1 << gammashift);\nvar betashift = 10;\nvar beta = (intbias >> betashift); /* beta = 1/1024 */\nvar betagamma = (intbias << (gammashift - betashift));\n\n// defs for decreasing radius factor\nvar initrad = (netsize >> 3); // for 256 cols, radius starts\nvar radiusbiasshift = 6; // at 32.0 biased by 6 bits\nvar radiusbias = (1 << radiusbiasshift);\nvar initradius = (initrad * radiusbias); //and decreases by a\nvar radiusdec = 30; // factor of 1/30 each cycle\n\n// defs for decreasing alpha factor\nvar alphabiasshift = 10; // alpha starts at 1.0\nvar initalpha = (1 << alphabiasshift);\nvar alphadec; // biased by 10 bits\n\n/* radbias and alpharadbias used for radpower calculation */\nvar radbiasshift = 8;\nvar radbias = (1 << radbiasshift);\nvar alpharadbshift = (alphabiasshift + radbiasshift);\nvar alpharadbias = (1 << alpharadbshift);\n\n// four primes near 500 - assume no image has a length so large that it is\n// divisible by all four primes\nvar prime1 = 499;\nvar prime2 = 491;\nvar prime3 = 487;\nvar prime4 = 503;\nvar minpicturebytes = (3 * prime4);\n\n/*\n Constructor: NeuQuant\n\n Arguments:\n\n pixels - array of pixels in RGB format\n samplefac - sampling factor 1 to 30 where lower is better quality\n\n >\n > pixels = [r, g, b, r, g, b, r, g, b, ..]\n >\n*/\nfunction NeuQuant(pixels, samplefac) {\n var network; // int[netsize][4]\n var netindex; // for network lookup - really 256\n\n // bias and freq arrays for learning\n var bias;\n var freq;\n var radpower;\n\n /*\n Private Method: init\n\n sets up arrays\n */\n function init() {\n network = [];\n netindex = new Int32Array(256);\n bias = new Int32Array(netsize);\n freq = new Int32Array(netsize);\n radpower = new Int32Array(netsize >> 3);\n\n var i, v;\n for (i = 0; i < netsize; i++) {\n v = (i << (netbiasshift + 8)) / netsize;\n network[i] = new Float64Array([v, v, v, 0]);\n //network[i] = [v, v, v, 0]\n freq[i] = intbias / netsize;\n bias[i] = 0;\n }\n }\n\n /*\n Private Method: unbiasnet\n\n unbiases network to give byte values 0..255 and record position i to prepare for sort\n */\n function unbiasnet() {\n for (var i = 0; i < netsize; i++) {\n network[i][0] >>= netbiasshift;\n network[i][1] >>= netbiasshift;\n network[i][2] >>= netbiasshift;\n network[i][3] = i; // record color number\n }\n }\n\n /*\n Private Method: altersingle\n\n moves neuron *i* towards biased (b,g,r) by factor *alpha*\n */\n function altersingle(alpha, i, b, g, r) {\n network[i][0] -= (alpha * (network[i][0] - b)) / initalpha;\n network[i][1] -= (alpha * (network[i][1] - g)) / initalpha;\n network[i][2] -= (alpha * (network[i][2] - r)) / initalpha;\n }\n\n /*\n Private Method: alterneigh\n\n moves neurons in *radius* around index *i* towards biased (b,g,r) by factor *alpha*\n */\n function alterneigh(radius, i, b, g, r) {\n var lo = Math.abs(i - radius);\n var hi = Math.min(i + radius, netsize);\n\n var j = i + 1;\n var k = i - 1;\n var m = 1;\n\n var p, a;\n while ((j < hi) || (k > lo)) {\n a = radpower[m++];\n\n if (j < hi) {\n p = network[j++];\n p[0] -= (a * (p[0] - b)) / alpharadbias;\n p[1] -= (a * (p[1] - g)) / alpharadbias;\n p[2] -= (a * (p[2] - r)) / alpharadbias;\n }\n\n if (k > lo) {\n p = network[k--];\n p[0] -= (a * (p[0] - b)) / alpharadbias;\n p[1] -= (a * (p[1] - g)) / alpharadbias;\n p[2] -= (a * (p[2] - r)) / alpharadbias;\n }\n }\n }\n\n /*\n Private Method: contest\n\n searches for biased BGR values\n */\n function contest(b, g, r) {\n /*\n finds closest neuron (min dist) and updates freq\n finds best neuron (min dist-bias) and returns position\n for frequently chosen neurons, freq[i] is high and bias[i] is negative\n bias[i] = gamma * ((1 / netsize) - freq[i])\n */\n\n var bestd = ~(1 << 31);\n var bestbiasd = bestd;\n var bestpos = -1;\n var bestbiaspos = bestpos;\n\n var i, n, dist, biasdist, betafreq;\n for (i = 0; i < netsize; i++) {\n n = network[i];\n\n dist = Math.abs(n[0] - b) + Math.abs(n[1] - g) + Math.abs(n[2] - r);\n if (dist < bestd) {\n bestd = dist;\n bestpos = i;\n }\n\n biasdist = dist - ((bias[i]) >> (intbiasshift - netbiasshift));\n if (biasdist < bestbiasd) {\n bestbiasd = biasdist;\n bestbiaspos = i;\n }\n\n betafreq = (freq[i] >> betashift);\n freq[i] -= betafreq;\n bias[i] += (betafreq << gammashift);\n }\n\n freq[bestpos] += beta;\n bias[bestpos] -= betagamma;\n\n return bestbiaspos;\n }\n\n /*\n Private Method: inxbuild\n\n sorts network and builds netindex[0..255]\n */\n function inxbuild() {\n var i, j, p, q, smallpos, smallval, previouscol = 0, startpos = 0;\n for (i = 0; i < netsize; i++) {\n p = network[i];\n smallpos = i;\n smallval = p[1]; // index on g\n // find smallest in i..netsize-1\n for (j = i + 1; j < netsize; j++) {\n q = network[j];\n if (q[1] < smallval) { // index on g\n smallpos = j;\n smallval = q[1]; // index on g\n }\n }\n q = network[smallpos];\n // swap p (i) and q (smallpos) entries\n if (i != smallpos) {\n j = q[0]; q[0] = p[0]; p[0] = j;\n j = q[1]; q[1] = p[1]; p[1] = j;\n j = q[2]; q[2] = p[2]; p[2] = j;\n j = q[3]; q[3] = p[3]; p[3] = j;\n }\n // smallval entry is now in position i\n\n if (smallval != previouscol) {\n netindex[previouscol] = (startpos + i) >> 1;\n for (j = previouscol + 1; j < smallval; j++)\n netindex[j] = i;\n previouscol = smallval;\n startpos = i;\n }\n }\n netindex[previouscol] = (startpos + maxnetpos) >> 1;\n for (j = previouscol + 1; j < 256; j++)\n netindex[j] = maxnetpos; // really 256\n }\n\n /*\n Private Method: inxsearch\n\n searches for BGR values 0..255 and returns a color index\n */\n function inxsearch(b, g, r) {\n var a, p, dist;\n\n var bestd = 1000; // biggest possible dist is 256*3\n var best = -1;\n\n var i = netindex[g]; // index on g\n var j = i - 1; // start at netindex[g] and work outwards\n\n while ((i < netsize) || (j >= 0)) {\n if (i < netsize) {\n p = network[i];\n dist = p[1] - g; // inx key\n if (dist >= bestd) i = netsize; // stop iter\n else {\n i++;\n if (dist < 0) dist = -dist;\n a = p[0] - b; if (a < 0) a = -a;\n dist += a;\n if (dist < bestd) {\n a = p[2] - r; if (a < 0) a = -a;\n dist += a;\n if (dist < bestd) {\n bestd = dist;\n best = p[3];\n }\n }\n }\n }\n if (j >= 0) {\n p = network[j];\n dist = g - p[1]; // inx key - reverse dif\n if (dist >= bestd) j = -1; // stop iter\n else {\n j--;\n if (dist < 0) dist = -dist;\n a = p[0] - b; if (a < 0) a = -a;\n dist += a;\n if (dist < bestd) {\n a = p[2] - r; if (a < 0) a = -a;\n dist += a;\n if (dist < bestd) {\n bestd = dist;\n best = p[3];\n }\n }\n }\n }\n }\n\n return best;\n }\n\n /*\n Private Method: learn\n\n \"Main Learning Loop\"\n */\n function learn() {\n var i;\n\n var lengthcount = pixels.length;\n var alphadec = 30 + ((samplefac - 1) / 3);\n var samplepixels = lengthcount / (3 * samplefac);\n var delta = ~~(samplepixels / ncycles);\n var alpha = initalpha;\n var radius = initradius;\n\n var rad = radius >> radiusbiasshift;\n\n if (rad <= 1) rad = 0;\n for (i = 0; i < rad; i++)\n radpower[i] = alpha * (((rad * rad - i * i) * radbias) / (rad * rad));\n\n var step;\n if (lengthcount < minpicturebytes) {\n samplefac = 1;\n step = 3;\n } else if ((lengthcount % prime1) !== 0) {\n step = 3 * prime1;\n } else if ((lengthcount % prime2) !== 0) {\n step = 3 * prime2;\n } else if ((lengthcount % prime3) !== 0) {\n step = 3 * prime3;\n } else {\n step = 3 * prime4;\n }\n\n var b, g, r, j;\n var pix = 0; // current pixel\n\n i = 0;\n while (i < samplepixels) {\n b = (pixels[pix] & 0xff) << netbiasshift;\n g = (pixels[pix + 1] & 0xff) << netbiasshift;\n r = (pixels[pix + 2] & 0xff) << netbiasshift;\n\n j = contest(b, g, r);\n\n altersingle(alpha, j, b, g, r);\n if (rad !== 0) alterneigh(rad, j, b, g, r); // alter neighbours\n\n pix += step;\n if (pix >= lengthcount) pix -= lengthcount;\n\n i++;\n\n if (delta === 0) delta = 1;\n if (i % delta === 0) {\n alpha -= alpha / alphadec;\n radius -= radius / radiusdec;\n rad = radius >> radiusbiasshift;\n\n if (rad <= 1) rad = 0;\n for (j = 0; j < rad; j++)\n radpower[j] = alpha * (((rad * rad - j * j) * radbias) / (rad * rad));\n }\n }\n }\n\n /*\n Method: buildColormap\n\n 1. initializes network\n 2. trains it\n 3. removes misconceptions\n 4. builds colorindex\n */\n function buildColormap() {\n init();\n learn();\n unbiasnet();\n inxbuild();\n }\n this.buildColormap = buildColormap;\n\n /*\n Method: getColormap\n\n builds colormap from the index\n\n returns array in the format:\n\n >\n > [r, g, b, r, g, b, r, g, b, ..]\n >\n */\n function getColormap() {\n var map = [];\n var index = [];\n\n for (var i = 0; i < netsize; i++)\n index[network[i][3]] = i;\n\n var k = 0;\n for (var l = 0; l < netsize; l++) {\n var j = index[l];\n map[k++] = (network[j][0]);\n map[k++] = (network[j][1]);\n map[k++] = (network[j][2]);\n }\n return map;\n }\n this.getColormap = getColormap;\n\n /*\n Method: lookupRGB\n\n looks for the closest *r*, *g*, *b* color in the map and\n returns its index\n */\n this.lookupRGB = inxsearch;\n}\n\nmodule.exports = NeuQuant;\n","GIFEncoder = require './GIFEncoder.js'\n\nrenderFrame = (frame) ->\n encoder = new GIFEncoder frame.width, frame.height\n\n if frame.index is 0\n encoder.writeHeader()\n else\n encoder.firstFrame = false\n\n encoder.setTransparent frame.transparent\n encoder.setRepeat frame.repeat\n encoder.setDelay frame.delay\n encoder.setQuality frame.quality\n encoder.setDither frame.dither\n encoder.setGlobalPalette frame.globalPalette\n encoder.addFrame frame.data\n encoder.finish() if frame.last\n if frame.globalPalette == true\n frame.globalPalette = encoder.getGlobalPalette()\n\n stream = encoder.stream()\n frame.data = stream.pages\n frame.cursor = stream.cursor\n frame.pageSize = stream.constructor.pageSize\n\n if frame.canTransfer\n transfer = (page.buffer for page in frame.data)\n self.postMessage frame, transfer\n else\n self.postMessage frame\n\nself.onmessage = (event) -> renderFrame event.data\n"]} diff --git a/src/mjbuilder.js b/src/mjbuilder.js new file mode 100644 index 0000000..c4042f8 --- /dev/null +++ b/src/mjbuilder.js @@ -0,0 +1,479 @@ +/* + Javascript MotionJPEG/AVI Builder + +-- MIT License + +Copyright (c) 2012 Satoshi Ueyama +Adapted by Elizabeth Hudnott + +Permission is hereby granted, free of charge, to any person obtaining a copy of this +software and associated documentation files (the "Software"), to deal in the Software +without restriction, including without limitation the rights to use, copy, modify, +merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit +persons to whom the Software is furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all copies or +substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, +INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR +PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE +FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +DEALINGS IN THE SOFTWARE. +*/ + +(function(aGlobal) { + "use strict"; + var AVIF_HASINDEX = 0x00000010; + var AVIIF_KEYFRAME = 0x00000010; + var RateBase = 1000000; + + function MotionJPEGBuilder(verbose) { + this.data = []; + this.base64 = new Base64(); + this.movieDesc = { + w: 0, + h:0, + fps: 0, + videoStreamSize: 0, + maxJPEGSize: 0, + }; + + this.avi = MotionJPEGBuilder.createAVIStruct(); + this.headerLIST = MotionJPEGBuilder.createHeaderLIST(); + this.moviLIST = MotionJPEGBuilder.createMoviLIST(); + this.frameList = []; + this.verbose = verbose || false; + } + + MotionJPEGBuilder.prototype = { + setup: function(frameWidth, frameHeight, fps, quality) { + this.movieDesc.w = frameWidth; + this.movieDesc.h = frameHeight; + this.movieDesc.fps = fps; + this.quality = quality === undefined ? 0.92 : quality; + }, + + addCanvasFrame: function(canvas) { + var url = canvas.toDataURL('image/jpeg', this.quality); + var dataStart = url.indexOf(',') + 1; + + var bytes = this.base64.decode(url.substring(dataStart)); + if (bytes.length % 2 === 1) { + bytes.push(0); // padding + } + + var arrayBuffer = new ArrayBuffer(bytes.length); + var byteBuffer = new Uint8Array(arrayBuffer); + for (var i = 0;i < bytes.length; i++) { + byteBuffer[i] = bytes[i]; + } + + var blob = new Blob([arrayBuffer], {type: 'image/jpeg'}); + var bsize = blob.size; + this.movieDesc.videoStreamSize += bsize; + this.frameList.push(blob); + + if (this.movieDesc.maxJPEGSize < bsize) { + this.movieDesc.maxJPEGSize = bsize; + } + }, + + addVideoStreamData: function(list, frameBuffer) { + var stream = MotionJPEGBuilder.createMoviStream(); + stream.dwSize = frameBuffer.size; + stream.handler = function(data) { + data.push(frameBuffer); + }; + + list.push(stream); + return stream.dwSize + 8; + }, + + finish: function(onFinish) { + var streamSize = 0; + this.moviLIST.aStreams = []; + var frameCount = this.frameList.length; + var frameIndices = []; + var frOffset = 4; // 'movi' +0 + var IndexEntryOrder = ['chId', 'dwFlags', 'dwOffset', 'dwLength']; + for (var i = 0; i < frameCount; i++) { + var frsize = this.addVideoStreamData(this.moviLIST.aStreams, this.frameList[i]); + frameIndices.push({ + chId: '00dc', + dwFlags: AVIIF_KEYFRAME, + dwOffset: frOffset, + dwLength: frsize - 8, + _order: IndexEntryOrder + }) + + frOffset += frsize; + streamSize += frsize; + }; + + this.moviLIST.dwSize = streamSize + 4; // + 'movi' + + // stream header + + var frameDu = Math.floor(RateBase / this.movieDesc.fps); + var strh = MotionJPEGBuilder.createStreamHeader(); + strh.wRight = this.movieDesc.w; + strh.wBottom = this.movieDesc.h; + strh.dwLength = this.frameList.length; + strh.dwScale = frameDu; + + var bi = MotionJPEGBuilder.createBitmapHeader(); + bi.dwWidth = this.movieDesc.w; + bi.dwHeight = this.movieDesc.h; + bi.dwSizeImage = 3 * bi.dwWidth * bi.dwHeight; + + var strf = MotionJPEGBuilder.createStreamFormat(); + strf.dwSize = bi.dwSize; + strf.sContent = bi; + + var strl = MotionJPEGBuilder.createStreamHeaderLIST(); + strl.dwSize = 4 + (strh.dwSize + 8) + (strf.dwSize + 8); + strl.aList = [strh, strf]; + + // AVI Header + var avih = MotionJPEGBuilder.createAVIMainHeader(); + avih.dwMicroSecPerFrame = frameDu; + avih.dwMaxBytesPerSec = this.movieDesc.maxJPEGSize * this.movieDesc.fps; + avih.dwTotalFrames = this.frameList.length; + avih.dwWidth = this.movieDesc.w; + avih.dwHeight = this.movieDesc.h; + avih.dwSuggestedBufferSize = 0; + + var hdrlSize = 4; + hdrlSize += avih.dwSize + 8; + hdrlSize += strl.dwSize + 8; + this.headerLIST.dwSize = hdrlSize; + this.headerLIST.aData = [avih, strl]; + + var indexChunk = { + chFourCC: 'idx1', + dwSize: frameIndices.length * 16, + aData: frameIndices, + _order: ['chFourCC', 'dwSize', 'aData'] + }; + + // AVI Container + var aviSize = 0; + aviSize += 8 + this.headerLIST.dwSize; + aviSize += 8 + this.moviLIST.dwSize; + aviSize += 8 + indexChunk.dwSize; + + this.avi.dwSize = aviSize + 4; + this.avi.aData = [this.headerLIST, this.moviLIST, indexChunk]; + + this.build(onFinish); + }, + + build: function(onFinish) { + MotionJPEGBuilder.appendStruct(this.data, this.avi); + var blob = new Blob(this.data, {type: 'video/avi'}); + this.data = []; + onFinish(blob); + } + }; + + MotionJPEGBuilder.appendStruct = function(data, s, nest) { + nest = nest || 0; + if (!s._order) { + throw "Structured data must have '_order'"; + } + + var od = s._order; + var len = od.length; + for (var i = 0; i < len; i++) { + var buffer; + var fieldName = od[i]; + var val = s[fieldName]; + if (this.verbose) { + console.log(" ".substring(0,nest) + fieldName); + } + switch(fieldName.charAt(0)) { + case 'b': // BYTE + buffer = new ArrayBuffer(1); + var view = new Uint8Array(buffer); + view[0] = val; + data.push(buffer); + break + case 'c': // chars + data.push(val); + break; + case 'd': // DWORD + buffer = new ArrayBuffer(4); + new DataView(buffer).setUint32(0, val, true); + data.push(buffer); + break; + case 'w': // WORD + buffer = new ArrayBuffer(2); + new DataView(buffer).setUint16(0, val, true); + data.push(buffer); + break + case 'W': // WORD(BE) + buffer = new ArrayBuffer(2); + new DataView(buffer).setUint16(0, val, false); + data.push(buffer); + break + case 'a': // Array of structured data + var dlen = val.length; + for (var j = 0; j < dlen; j++) { + MotionJPEGBuilder.appendStruct(data, val[j], nest+1); + } + break; + case 'r': // Raw(ArrayBuffer) + data.push(val); + break; + case 's': // Structured data + MotionJPEGBuilder.appendStruct(data, val, nest+1); + break; + case 'h': // Handler function + val(data); + break; + default: + throw "Unknown data type: " + fieldName; + break; + } + } + }; + + MotionJPEGBuilder.createAVIStruct = function() { + return { + chRIFF: 'RIFF', + chFourCC: 'AVI ', + dwSize: 0, + aData: null, + _order: ['chRIFF', 'dwSize', 'chFourCC', 'aData'] + }; + }; + + MotionJPEGBuilder.createAVIMainHeader = function() { + return { + chFourCC: 'avih', + dwSize: 56, + // ----- + dwMicroSecPerFrame: 66666, + dwMaxBytesPerSec: 1000, + dwPaddingGranularity: 0, + dwFlags: AVIF_HASINDEX, + // +16 + + dwTotalFrames: 1, + dwInitialFrames: 0, + dwStreams: 1, + dwSuggestedBufferSize: 0, + // +32 + + dwWidth: 10, + dwHeight: 20, + dwReserved1: 0, + dwReserved2: 0, + dwReserved3: 0, + dwReserved4: 0, + // +56 + + _order: [ + 'chFourCC', 'dwSize', + 'dwMicroSecPerFrame', 'dwMaxBytesPerSec', 'dwPaddingGranularity', 'dwFlags', + 'dwTotalFrames', 'dwInitialFrames', 'dwStreams', 'dwSuggestedBufferSize', + 'dwWidth', 'dwHeight', 'dwReserved1', 'dwReserved2', 'dwReserved3', 'dwReserved4' + ] + }; + }; + + MotionJPEGBuilder.createHeaderLIST = function() { + return { + chLIST: 'LIST', + dwSize: 0, + chFourCC: 'hdrl', + aData: null, + _order: ['chLIST', 'dwSize', 'chFourCC', 'aData'] + }; + }; + + MotionJPEGBuilder.createMoviLIST = function() { + return { + chLIST: 'LIST', + dwSize: 0, + chFourCC: 'movi', + aStreams: null, + _order: ['chLIST', 'dwSize', 'chFourCC', 'aStreams'] + }; + }; + + MotionJPEGBuilder.createMoviStream = function() { + return { + chType: '00dc', + dwSize: 0, + handler: null, + _order: ['chType', 'dwSize', 'handler'] + } + }; + + MotionJPEGBuilder.createStreamHeaderLIST = function() { + return { + chLIST: 'LIST', + dwSize: 0, + chFourCC: 'strl', + aList: null, + _order: ['chLIST', 'dwSize', 'chFourCC', 'aList'] + }; + }; + + MotionJPEGBuilder.createStreamFormat = function() { + return { + chFourCC: 'strf', + dwSize: 0, + sContent: null, + _order: ['chFourCC', 'dwSize', 'sContent'] + }; + }; + + MotionJPEGBuilder.createStreamHeader = function() { + return { + chFourCC: 'strh', + dwSize: 56, + chTypeFourCC: 'vids', + chHandlerFourCC: 'mjpg', + // +16 + + dwFlags: 0, + wPriority: 0, + wLanguage: 0, + dwInitialFrames: 0, + dwScale: 66666, + + // +32 + dwRate: RateBase, + dwStart: 0, + dwLength: 0, + dwSuggestedBufferSize: 0, + // +48 + + dwQuality: 10000, + dwSampleSize: 0, + wLeft: 0, + wTop: 0, + wRight: 0, + wBottom: 0, + // +64 + + _order:[ + 'chFourCC', 'dwSize', 'chTypeFourCC', 'chHandlerFourCC', + 'dwFlags', 'wPriority', 'wLanguage', 'dwInitialFrames', 'dwScale', + 'dwRate', 'dwStart', 'dwLength', 'dwSuggestedBufferSize', + 'dwQuality', 'dwSampleSize', 'wLeft', 'wTop', 'wRight', 'wBottom' + ] + }; + }; + + MotionJPEGBuilder.createBitmapHeader = function() { + return { + dwSize: 40, + dwWidth: 10, + dwHeight: 20, + wPlanes: 1, + wBitcount: 24, + chCompression: 'MJPG', + dwSizeImage: 600, + dwXPelsPerMeter: 0, + dwYPelsPerMeter: 0, + dwClrUsed: 0, + dwClrImportant: 0, + _order: [ + 'dwSize', 'dwWidth', 'dwHeight', 'wPlanes', 'wBitcount', 'chCompression', + 'dwSizeImage', 'dwXPelsPerMeter', 'dwYPelsPerMeter', 'dwClrUsed', 'dwClrImportant' + ] + } + }; + + + MotionJPEGBuilder.createMJPEG = function() { + return { + W_SOI: 0xffd8, + aSegments: null, + W_EOI: 0xffd9, + _order: ['dwSOI', 'aSegments', 'dwEOI'] + }; + }; + + MotionJPEGBuilder.KnownMarkers = { + 0xC0: 'SOF0', + 0xC4: 'DHT', + 0xDA: 'SOS', + 0xDB: 'DQT', + 0xDD: 'DRI', + 0xE0: 'APP0' + }; + + var Base64 = function() { + this.initialize(); + }; + + Base64.prototype.initialize = function() { + this.symbols = []; + var startChar = "A".charCodeAt(0); + for(var i = 0; i < 26; i++) { + this.symbols.push(String.fromCharCode(startChar + i)); + } + var startChar = "a".charCodeAt(0); + for(var i = 0; i < 26; i++) { + this.symbols.push(String.fromCharCode(startChar + i)); + } + var startChar = "0".charCodeAt(0); + for(var i = 0; i < 10; i++) { + this.symbols.push(String.fromCharCode(startChar + i)); + } + this.symbols.push("+", "/"); + + this.encodeMap = []; + for(var i = 0; i < this.symbols.length; i++) { + this.encodeMap[i] = this.symbols[i]; + } + + this.decodeMap = []; + for(var i = 0; i < this.symbols.length; i++) { + this.decodeMap[this.symbols[i]] = i; + } + this.decodeMap["="] = null; + }; + + + Base64.prototype.decode = function(encoded) { + if(encoded.length % 4 != 0) { + throw "encoded.length must be a multiple of 4."; + } + + var decoded = []; + var map = this.decodeMap; + for (var i = 0, len = encoded.length; i < len; i += 4) { + var b0 = map[encoded[i]]; + var b1 = map[encoded[i + 1]]; + var b2 = map[encoded[i + 2]]; + var b3 = map[encoded[i + 3]]; + + var d0 = ((b0 << 2) + (b1 >> 4)) & 0xff; + decoded.push(d0); + + if(b2 == null) break; // encoded[i + 1] == "=" + + var d1 = ((b1 << 4) + (b2 >> 2)) & 0xff; + decoded.push(d1); + + if(b3 == null) break; // encoded[i + 2] == "=" + + var d2 = ((b2 << 6) + b3) & 0xff; + decoded.push(d2); + + } + + return decoded; + }; + + + // export + aGlobal.MotionJPEGBuilder = MotionJPEGBuilder; +})(window); diff --git a/src/webm-writer-0.2.0.js b/src/webm-writer-0.3.0.js similarity index 58% rename from src/webm-writer-0.2.0.js rename to src/webm-writer-0.3.0.js index dbe2a25..686ec14 100644 --- a/src/webm-writer-0.2.0.js +++ b/src/webm-writer-0.3.0.js @@ -1,8 +1,8 @@ /** * A tool for presenting an ArrayBuffer as a stream for writing some simple data types. - * + * * By Nicholas Sherlock - * + * * Released under the WTFPLv2 https://en.wikipedia.org/wiki/WTFPL */ @@ -13,17 +13,17 @@ * Create an ArrayBuffer of the given length and present it as a writable stream with methods * for writing data in different formats. */ - var ArrayBufferDataStream = function(length) { + let ArrayBufferDataStream = function(length) { this.data = new Uint8Array(length); this.pos = 0; }; - ArrayBufferDataStream.prototype.seek = function(offset) { - this.pos = offset; + ArrayBufferDataStream.prototype.seek = function(toOffset) { + this.pos = toOffset; }; ArrayBufferDataStream.prototype.writeBytes = function(arr) { - for (var i = 0; i < arr.length; i++) { + for (let i = 0; i < arr.length; i++) { this.data[this.pos++] = arr[i]; } }; @@ -41,19 +41,19 @@ }; ArrayBufferDataStream.prototype.writeDoubleBE = function(d) { - var + let bytes = new Uint8Array(new Float64Array([d]).buffer); - for (var i = bytes.length - 1; i >= 0; i--) { + for (let i = bytes.length - 1; i >= 0; i--) { this.writeByte(bytes[i]); } }; ArrayBufferDataStream.prototype.writeFloatBE = function(d) { - var + let bytes = new Uint8Array(new Float32Array([d]).buffer); - for (var i = bytes.length - 1; i >= 0; i--) { + for (let i = bytes.length - 1; i >= 0; i--) { this.writeByte(bytes[i]); } }; @@ -62,17 +62,17 @@ * Write an ASCII string to the stream */ ArrayBufferDataStream.prototype.writeString = function(s) { - for (var i = 0; i < s.length; i++) { + for (let i = 0; i < s.length; i++) { this.data[this.pos++] = s.charCodeAt(i); } }; /** - * Write the given 32-bit integer to the stream as an EBML variable-length integer using the given byte width + * Write the given 32-bit integer to the stream as an EBML variable-length integer using the given byte width * (use measureEBMLVarInt). - * + * * No error checking is performed to ensure that the supplied width is correct for the integer. - * + * * @param i Integer to be written * @param width Number of bytes to write to the stream */ @@ -97,18 +97,18 @@ this.writeU8(i); break; case 5: - /* - * JavaScript converts its doubles to 32-bit integers for bitwise operations, so we need to do a + /* + * JavaScript converts its doubles to 32-bit integers for bitwise operations, so we need to do a * division by 2^32 instead of a right-shift of 32 to retain those top 3 bits */ - this.writeU8((1 << 3) | ((i / 4294967296) & 0x7)); + this.writeU8((1 << 3) | ((i / 4294967296) & 0x7)); this.writeU8(i >> 24); this.writeU8(i >> 16); this.writeU8(i >> 8); this.writeU8(i); break; default: - throw new RuntimeException("Bad EBML VINT size " + width); + throw new Error("Bad EBML VINT size " + width); } }; @@ -116,7 +116,7 @@ * Return the number of bytes needed to encode the given integer as an EBML VINT. */ ArrayBufferDataStream.prototype.measureEBMLVarInt = function(val) { - if (val < (1 << 7) - 1) { + if (val < (1 << 7) - 1) { /* Top bit is set, leaving 7 bits to hold the integer, but we can't store 127 because * "all bits set to one" is a reserved value. Same thing for the other cases below: */ @@ -130,7 +130,7 @@ } else if (val < 34359738367) { // 2 ^ 35 - 1 (can address 32GB) return 5; } else { - throw new RuntimeException("EBML VINT size not supported " + val); + throw new Error("EBML VINT size not supported " + val); } }; @@ -141,9 +141,9 @@ /** * Write the given unsigned 32-bit integer to the stream in big-endian order using the given byte width. * No error checking is performed to ensure that the supplied width is correct for the integer. - * + * * Omit the width parameter to have it determined automatically for you. - * + * * @param u Unsigned integer to be written * @param width Number of bytes to write to the stream */ @@ -166,7 +166,7 @@ this.writeU8(u); break; default: - throw new RuntimeException("Bad UINT size " + width); + throw new Error("Bad UINT size " + width); } }; @@ -197,7 +197,7 @@ } else if (this.pos == this.data.byteLength) { return this.data; } else { - throw "ArrayBufferDataStream's pos lies beyond end of buffer"; + throw new Error("ArrayBufferDataStream's pos lies beyond end of buffer"); } }; @@ -211,24 +211,24 @@ /** * Allows a series of Blob-convertible objects (ArrayBuffer, Blob, String, etc) to be added to a buffer. Seeking and * overwriting of blobs is allowed. - * - * You can supply a FileWriter, in which case the BlobBuffer is just used as temporary storage before it writes it + * + * You can supply a FileWriter, in which case the BlobBuffer is just used as temporary storage before it writes it * through to the disk. - * + * * By Nicholas Sherlock - * + * * Released under the WTFPLv2 https://en.wikipedia.org/wiki/WTFPL */ (function() { - var BlobBuffer = function(fs) { + let BlobBuffer = function(fs) { return function(destination) { - var + let buffer = [], writePromise = Promise.resolve(), fileWriter = null, fd = null; - if (typeof FileWriter !== "undefined" && destination instanceof FileWriter) { + if (destination && destination.constructor.name === "FileWriter") { fileWriter = destination; } else if (fs && destination) { fd = destination; @@ -243,7 +243,7 @@ // Returns a promise that converts the blob to an ArrayBuffer function readBlobAsBuffer(blob) { return new Promise(function (resolve, reject) { - var + let reader = new FileReader(); reader.addEventListener("loadend", function () { @@ -274,11 +274,11 @@ } function measureData(data) { - var + let result = data.byteLength || data.length || data.size; if (!Number.isInteger(result)) { - throw "Failed to determine size of element"; + throw new Error("Failed to determine size of element"); } return result; @@ -292,15 +292,15 @@ */ this.seek = function (offset) { if (offset < 0) { - throw "Offset may not be negative"; + throw new Error("Offset may not be negative"); } if (isNaN(offset)) { - throw "Offset may not be NaN"; + throw new Error("Offset may not be NaN"); } if (offset > this.length) { - throw "Seeking beyond the end of file is not allowed"; + throw new Error("Seeking beyond the end of file is not allowed"); } this.pos = offset; @@ -313,7 +313,7 @@ * be fully contained by the extent of a previous write). */ this.write = function (data) { - var + let newEntry = { offset: this.pos, data: data, @@ -329,7 +329,7 @@ if (fd) { return new Promise(function(resolve, reject) { convertToUint8Array(newEntry.data).then(function(dataArray) { - var + let totalWritten = 0, buffer = Buffer.from(dataArray.buffer), @@ -358,8 +358,8 @@ // We might be modifying a write that was already buffered in memory. // Slow linear search to find a block we might be overwriting - for (var i = 0; i < buffer.length; i++) { - var + for (let i = 0; i < buffer.length; i++) { + let entry = buffer[i]; // If our new entry overlaps the old one in any way... @@ -411,14 +411,14 @@ } else { // After writes complete we need to merge the buffer to give to the caller writePromise = writePromise.then(function () { - var + let result = []; - for (var i = 0; i < buffer.length; i++) { + for (let i = 0; i < buffer.length; i++) { result.push(buffer[i].data); } - return new Blob(result, {mimeType: mimeType}); + return new Blob(result, {type: mimeType}); }); } @@ -432,208 +432,303 @@ } else { window.BlobBuffer = BlobBuffer(null); } -})();/** +})(); +/** * WebM video encoder for Google Chrome. This implementation is suitable for creating very large video files, because * it can stream Blobs directly to a FileWriter without buffering the entire video in memory. - * - * When FileWriter is not available or not desired, it can buffer the video in memory as a series of Blobs which are + * + * When FileWriter is not available or not desired, it can buffer the video in memory as a series of Blobs which are * eventually returned as one composite Blob. - * + * * By Nicholas Sherlock. - * + * * Based on the ideas from Whammy: https://github.com/antimatter15/whammy - * + * * Released under the WTFPLv2 https://en.wikipedia.org/wiki/WTFPL */ "use strict"; (function() { - var WebMWriter = function(ArrayBufferDataStream, BlobBuffer) { - function extend(base, top) { - var - target = {}; - - [base, top].forEach(function(obj) { - for (var prop in obj) { - if (Object.prototype.hasOwnProperty.call(obj, prop)) { - target[prop] = obj[prop]; - } + function extend(base, top) { + let + target = {}; + + [base, top].forEach(function(obj) { + for (let prop in obj) { + if (Object.prototype.hasOwnProperty.call(obj, prop)) { + target[prop] = obj[prop]; } - }); - - return target; + } + }); + + return target; + } + + /** + * Decode a Base64 data URL into a binary string. + * + * @return {String} The binary string + */ + function decodeBase64WebPDataURL(url) { + if (typeof url !== "string" || !url.match(/^data:image\/webp;base64,/i)) { + throw new Error("Failed to decode WebP Base64 URL"); } - /** - * Decode a Base64 data URL into a binary string. - * - * Returns the binary string, or false if the URL could not be decoded. - */ - function decodeBase64WebPDataURL(url) { - if (typeof url !== "string" || !url.match(/^data:image\/webp;base64,/i)) { - return false; - } - - return window.atob(url.substring("data:image\/webp;base64,".length)); + return window.atob(url.substring("data:image\/webp;base64,".length)); + } + + /** + * Convert the given canvas to a WebP encoded image and return the image data as a string. + * + * @return {String} + */ + function renderAsWebP(canvas, quality) { + let + frame = typeof canvas === 'string' && /^data:image\/webp/.test(canvas) + ? canvas + : canvas.toDataURL('image/webp', quality); + + return decodeBase64WebPDataURL(frame); + } + + /** + * @param {String} string + * @returns {number} + */ + function byteStringToUint32LE(string) { + let + a = string.charCodeAt(0), + b = string.charCodeAt(1), + c = string.charCodeAt(2), + d = string.charCodeAt(3); + + return (a | (b << 8) | (c << 16) | (d << 24)) >>> 0; + } + + /** + * Extract a VP8 keyframe from a WebP image file. + * + * @param {String} webP - Raw binary string + * + * @returns {{hasAlpha: boolean, frame: string}} + */ + function extractKeyframeFromWebP(webP) { + let + cursor = webP.indexOf('VP8', 12); // Start the search after the 12-byte file header + + if (cursor === -1) { + throw new Error("Bad image format, does this browser support WebP?"); } - /** - * Convert a raw binary string (one character = one output byte) to an ArrayBuffer + let + hasAlpha = false; + + /* Cursor now is either directly pointing at a "VP8 " keyframe, or a "VP8X" extended format file header + * Seek through chunks until we find the "VP8 " chunk we're interested in */ - function stringToArrayBuffer(string) { - var - buffer = new ArrayBuffer(string.length), - int8Array = new Uint8Array(buffer); + while (cursor < webP.length - 8) { + let + chunkLength, fourCC; + + fourCC = webP.substring(cursor, cursor + 4); + cursor += 4; + + chunkLength = byteStringToUint32LE(webP.substring(cursor, cursor + 4)); + cursor += 4; - for (var i = 0; i < string.length; i++) { - int8Array[i] = string.charCodeAt(i); + switch (fourCC) { + case "VP8 ": + return { + frame: webP.substring(cursor, cursor + chunkLength), + hasAlpha: hasAlpha + }; + + case "ALPH": + hasAlpha = true; + /* But we otherwise ignore the content of the alpha chunk, since we don't have a decoder for it + * and it isn't VP8-compatible + */ + break; } - return buffer; - } - - /** - * Convert the given canvas to a WebP encoded image and return the image data as a string. - */ - function renderAsWebP(canvas, quality) { - var - frame = canvas.toDataURL('image/webp', {quality: quality}); + cursor += chunkLength; - return decodeBase64WebPDataURL(frame); + if ((chunkLength & 0x01) !== 0) { + cursor++; + // Odd-length chunks have 1 byte of trailing padding that isn't included in their length + } } - function extractKeyframeFromWebP(webP) { - // Assume that Chrome will generate a Simple Lossy WebP which has this header: - var - keyframeStartIndex = webP.indexOf('VP8 '); - - if (keyframeStartIndex == -1) { - throw "Failed to identify beginning of keyframe in WebP image"; + throw new Error("Failed to find VP8 keyframe in WebP image, is this image mistakenly encoded in the Lossless WebP format?"); + } + + // Just a little utility so we can tag values as floats for the EBML encoder's benefit + function EBMLFloat32(value) { + this.value = value; + } + + function EBMLFloat64(value) { + this.value = value; + } + + /** + * Write the given EBML object to the provided ArrayBufferStream. + * + * @param buffer + * @param {Number} bufferFileOffset - The buffer's first byte is at this position inside the video file. + * This is used to complete offset and dataOffset fields in each EBML structure, + * indicating the file offset of the first byte of the EBML element and + * its data payload. + * @param {*} ebml + */ + function writeEBML(buffer, bufferFileOffset, ebml) { + // Is the ebml an array of sibling elements? + if (Array.isArray(ebml)) { + for (let i = 0; i < ebml.length; i++) { + writeEBML(buffer, bufferFileOffset, ebml[i]); } + // Is this some sort of raw data that we want to write directly? + } else if (typeof ebml === "string") { + buffer.writeString(ebml); + } else if (ebml instanceof Uint8Array) { + buffer.writeBytes(ebml); + } else if (ebml.id){ + // We're writing an EBML element + ebml.offset = buffer.pos + bufferFileOffset; - // Skip the header and the 4 bytes that encode the length of the VP8 chunk - keyframeStartIndex += 'VP8 '.length + 4; + buffer.writeUnsignedIntBE(ebml.id); // ID field - return webP.substring(keyframeStartIndex); - } - - // Just a little utility so we can tag values as floats for the EBML encoder's benefit - function EBMLFloat32(value) { - this.value = value; - } - - function EBMLFloat64(value) { - this.value = value; - } - - /** - * Write the given EBML object to the provided ArrayBufferStream. - * - * The buffer's first byte is at bufferFileOffset inside the video file. This is used to complete offset and - * dataOffset fields in each EBML structure, indicating the file offset of the first byte of the EBML element and - * its data payload. - */ - function writeEBML(buffer, bufferFileOffset, ebml) { - // Is the ebml an array of sibling elements? - if (Array.isArray(ebml)) { - for (var i = 0; i < ebml.length; i++) { - writeEBML(buffer, bufferFileOffset, ebml[i]); + // Now we need to write the size field, so we must know the payload size: + + if (Array.isArray(ebml.data)) { + // Writing an array of child elements. We won't try to measure the size of the children up-front + + let + sizePos, dataBegin, dataEnd; + + if (ebml.size === -1) { + // Write the reserved all-one-bits marker to note that the size of this element is unknown/unbounded + buffer.writeByte(0xFF); + } else { + sizePos = buffer.pos; + + /* Write a dummy size field to overwrite later. 4 bytes allows an element maximum size of 256MB, + * which should be plenty (we don't want to have to buffer that much data in memory at one time + * anyway!) + */ + buffer.writeBytes([0, 0, 0, 0]); } - // Is this some sort of raw data that we want to write directly? - } else if (typeof ebml === "string") { - buffer.writeString(ebml); - } else if (ebml instanceof Uint8Array) { - buffer.writeBytes(ebml); - } else if (ebml.id){ - // We're writing an EBML element - ebml.offset = buffer.pos + bufferFileOffset; - buffer.writeUnsignedIntBE(ebml.id); // ID field + dataBegin = buffer.pos; - // Now we need to write the size field, so we must know the payload size: + ebml.dataOffset = dataBegin + bufferFileOffset; + writeEBML(buffer, bufferFileOffset, ebml.data); - if (Array.isArray(ebml.data)) { - // Writing an array of child elements. We won't try to measure the size of the children up-front - - var - sizePos, dataBegin, dataEnd; - - if (ebml.size === -1) { - // Write the reserved all-one-bits marker to note that the size of this element is unknown/unbounded - buffer.writeByte(0xFF); - } else { - sizePos = buffer.pos; - - /* Write a dummy size field to overwrite later. 4 bytes allows an element maximum size of 256MB, - * which should be plenty (we don't want to have to buffer that much data in memory at one time - * anyway!) - */ - buffer.writeBytes([0, 0, 0, 0]); - } - - dataBegin = buffer.pos; + if (ebml.size !== -1) { + dataEnd = buffer.pos; - ebml.dataOffset = dataBegin + bufferFileOffset; - writeEBML(buffer, bufferFileOffset, ebml.data); + ebml.size = dataEnd - dataBegin; - if (ebml.size !== -1) { - dataEnd = buffer.pos; - - ebml.size = dataEnd - dataBegin; - - buffer.seek(sizePos); - buffer.writeEBMLVarIntWidth(ebml.size, 4); // Size field - - buffer.seek(dataEnd); - } - } else if (typeof ebml.data === "string") { - buffer.writeEBMLVarInt(ebml.data.length); // Size field - ebml.dataOffset = buffer.pos + bufferFileOffset; - buffer.writeString(ebml.data); - } else if (typeof ebml.data === "number") { - // Allow the caller to explicitly choose the size if they wish by supplying a size field - if (!ebml.size) { - ebml.size = buffer.measureUnsignedInt(ebml.data); - } + buffer.seek(sizePos); + buffer.writeEBMLVarIntWidth(ebml.size, 4); // Size field - buffer.writeEBMLVarInt(ebml.size); // Size field - ebml.dataOffset = buffer.pos + bufferFileOffset; - buffer.writeUnsignedIntBE(ebml.data, ebml.size); - } else if (ebml.data instanceof EBMLFloat64) { - buffer.writeEBMLVarInt(8); // Size field - ebml.dataOffset = buffer.pos + bufferFileOffset; - buffer.writeDoubleBE(ebml.data.value); - } else if (ebml.data instanceof EBMLFloat32) { - buffer.writeEBMLVarInt(4); // Size field - ebml.dataOffset = buffer.pos + bufferFileOffset; - buffer.writeFloatBE(ebml.data.value); - } else if (ebml.data instanceof Uint8Array) { - buffer.writeEBMLVarInt(ebml.data.byteLength); // Size field - ebml.dataOffset = buffer.pos + bufferFileOffset; - buffer.writeBytes(ebml.data); - } else { - throw "Bad EBML datatype " + typeof ebml.data; + buffer.seek(dataEnd); } + } else if (typeof ebml.data === "string") { + buffer.writeEBMLVarInt(ebml.data.length); // Size field + ebml.dataOffset = buffer.pos + bufferFileOffset; + buffer.writeString(ebml.data); + } else if (typeof ebml.data === "number") { + // Allow the caller to explicitly choose the size if they wish by supplying a size field + if (!ebml.size) { + ebml.size = buffer.measureUnsignedInt(ebml.data); + } + + buffer.writeEBMLVarInt(ebml.size); // Size field + ebml.dataOffset = buffer.pos + bufferFileOffset; + buffer.writeUnsignedIntBE(ebml.data, ebml.size); + } else if (ebml.data instanceof EBMLFloat64) { + buffer.writeEBMLVarInt(8); // Size field + ebml.dataOffset = buffer.pos + bufferFileOffset; + buffer.writeDoubleBE(ebml.data.value); + } else if (ebml.data instanceof EBMLFloat32) { + buffer.writeEBMLVarInt(4); // Size field + ebml.dataOffset = buffer.pos + bufferFileOffset; + buffer.writeFloatBE(ebml.data.value); + } else if (ebml.data instanceof Uint8Array) { + buffer.writeEBMLVarInt(ebml.data.byteLength); // Size field + ebml.dataOffset = buffer.pos + bufferFileOffset; + buffer.writeBytes(ebml.data); } else { - throw "Bad EBML datatype " + typeof ebml.data; + throw new Error("Bad EBML datatype " + typeof ebml.data); } + } else { + throw new Error("Bad EBML datatype " + typeof ebml.data); } - + } + + /** + * @typedef {Object} Frame + * @property {string} frame - Raw VP8 keyframe data + * @property {string} alpha - Raw VP8 keyframe with alpha represented as luminance + * @property {Number} duration + * @property {Number} trackNumber - From 1 to 126 (inclusive) + * @property {Number} timecode + */ + + /** + * @typedef {Object} Cluster + * @property {Number} timecode - Start time for the cluster + */ + + /** + * @param ArrayBufferDataStream - Imported library + * @param BlobBuffer - Imported library + * + * @returns WebMWriter + * + * @constructor + */ + let WebMWriter = function(ArrayBufferDataStream, BlobBuffer) { return function(options) { - var + let MAX_CLUSTER_DURATION_MSEC = 5000, DEFAULT_TRACK_NUMBER = 1, writtenHeader = false, - videoWidth, videoHeight, - + videoWidth = 0, videoHeight = 0, + + /** + * @type {[HTMLCanvasElement]} + */ + alphaBuffer = null, + + /** + * @type {[CanvasRenderingContext2D]} + */ + alphaBufferContext = null, + + /** + * @type {[ImageData]} + */ + alphaBufferData = null, + + /** + * + * @type {Frame[]} + */ clusterFrameBuffer = [], clusterStartTime = 0, clusterDuration = 0, optionDefaults = { - quality: 0.95, // WebM image quality from 0.0 (worst) to 1.0 (best) + quality: 0.95, // WebM image quality from 0.0 (worst) to 0.99999 (best), 1.00 (WebP lossless) is not supported + + 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`. + fileWriter: null, // Chrome FileWriter in order to stream to a file instead of buffering to memory (optional) fd: null, // Node.JS file descriptor to write to instead of buffering (optional) @@ -648,7 +743,8 @@ Tracks: {id: new Uint8Array([0x16, 0x54, 0xAE, 0x6B]), positionEBML: null}, }, - ebmlSegment, + ebmlSegment, // Root element of the EBML document + segmentDuration = { "id": 0x4489, // Duration "data": new EBMLFloat64(0) @@ -663,6 +759,46 @@ function fileOffsetToSegmentRelative(fileOffset) { return fileOffset - ebmlSegment.dataOffset; } + + /** + * Extracts the transparency channel from the supplied canvas and uses it to create a VP8 alpha channel bitstream. + * + * @param {HTMLCanvasElement} source + * + * @return {HTMLCanvasElement} + */ + function convertAlphaToGrayscaleImage(source) { + if (alphaBuffer === null || alphaBuffer.width !== source.width || alphaBuffer.height !== source.height) { + alphaBuffer = document.createElement("canvas"); + alphaBuffer.width = source.width; + alphaBuffer.height = source.height; + + alphaBufferContext = alphaBuffer.getContext("2d"); + alphaBufferData = alphaBufferContext.createImageData(alphaBuffer.width, alphaBuffer.height); + } + + let + sourceContext = source.getContext("2d"), + sourceData = sourceContext.getImageData(0, 0, source.width, source.height).data, + destData = alphaBufferData.data, + dstCursor = 0, + srcEnd = source.width * source.height * 4; + + for (let srcCursor = 3 /* Since pixel byte order is RGBA */; srcCursor < srcEnd; srcCursor += 4) { + let + alpha = sourceData[srcCursor]; + + // Turn the original alpha channel into a brightness value (ends up being the Y in YUV) + destData[dstCursor++] = alpha; + destData[dstCursor++] = alpha; + destData[dstCursor++] = alpha; + destData[dstCursor++] = 255; + } + + alphaBufferContext.putImageData(alphaBufferData, 0, 0); + + return alphaBuffer; + } /** * Create a SeekHead element with descriptors for the points in the global seekPoints array. @@ -671,7 +807,7 @@ * to be overwritten later. */ function createSeekHead() { - var + let seekPositionEBMLTemplate = { "id": 0x53AC, // SeekPosition "size": 5, // Allows for 32GB video files @@ -683,8 +819,8 @@ "data": [] }; - for (var name in seekPoints) { - var + for (let name in seekPoints) { + let seekPoint = seekPoints[name]; seekPoint.positionEBML = Object.create(seekPositionEBMLTemplate); @@ -710,7 +846,7 @@ function writeHeader() { seekHead = createSeekHead(); - var + let ebmlHeader = { "id": 0x1a45dfa3, // EBML "data": [ @@ -764,6 +900,27 @@ ] }, + videoProperties = [ + { + "id": 0xb0, // PixelWidth + "data": videoWidth + }, + { + "id": 0xba, // PixelHeight + "data": videoHeight + } + ]; + + if (options.transparent) { + videoProperties.push( + { + "id": 0x53C0, // AlphaMode + "data": 1 + } + ); + } + + let tracks = { "id": 0x1654ae6b, // Tracks "data": [ @@ -800,16 +957,7 @@ }, { "id": 0xe0, // Video - "data": [ - { - "id": 0xb0, // PixelWidth - "data": videoWidth - }, - { - "id": 0xba, // PixelHeight - "data": videoHeight - } - ] + "data": videoProperties } ] } @@ -826,7 +974,7 @@ ] }; - var + let bufferStream = new ArrayBufferDataStream(256); writeEBML(bufferStream, blobBuffer.pos, [ebmlHeader, ebmlSegment]); @@ -835,22 +983,82 @@ // Now we know where these top-level elements lie in the file: seekPoints.SegmentInfo.positionEBML.data = fileOffsetToSegmentRelative(segmentInfo.offset); seekPoints.Tracks.positionEBML.data = fileOffsetToSegmentRelative(tracks.offset); - }; + + writtenHeader = true; + } + + /** + * Create a BlockGroup element to hold the given keyframe (used when alpha support is required) + * + * @param {Frame} keyframe + * + * @return A BlockGroup EBML element + */ + function createBlockGroupForTransparentKeyframe(keyframe) { + let + block, blockAdditions, + + bufferStream = new ArrayBufferDataStream(1 + 2 + 1); + + // Create a Block to hold the image data: + + if (!(keyframe.trackNumber > 0 && keyframe.trackNumber < 127)) { + throw new Error("TrackNumber must be > 0 and < 127"); + } + + bufferStream.writeEBMLVarInt(keyframe.trackNumber); // Always 1 byte since we limit the range of trackNumber + bufferStream.writeU16BE(keyframe.timecode); + bufferStream.writeByte(0); // Flags byte + + block = { + "id": 0xA1, // Block + "data": [ + bufferStream.getAsDataArray(), + keyframe.frame + ] + }; + + blockAdditions = { + "id": 0x75A1, // BlockAdditions + "data": [ + { + "id": 0xA6, // BlockMore + "data": [ + { + "id": 0xEE, // BlockAddID + "data": 1 // Means "BlockAdditional has a codec-defined meaning, pass it to the codec" + }, + { + "id": 0xA5, // BlockAdditional + "data": keyframe.alpha // The actual alpha channel image + } + ] + } + ] + }; + + return { + "id": 0xA0, // BlockGroup + "data": [ + block, + blockAdditions + ] + }; + } /** - * Create a SimpleBlock keyframe header using these fields: - * timecode - Time of this keyframe - * trackNumber - Track number from 1 to 126 (inclusive) - * frame - Raw frame data payload string + * Create a SimpleBlock element to hold the given keyframe. * - * Returns an EBML element. + * @param {Frame} keyframe + * + * @return A SimpleBlock EBML element. */ - function createKeyframeBlock(keyframe) { - var + function createSimpleBlockForKeyframe(keyframe) { + let bufferStream = new ArrayBufferDataStream(1 + 2 + 1); if (!(keyframe.trackNumber > 0 && keyframe.trackNumber < 127)) { - throw "TrackNumber must be > 0 and < 127"; + throw new Error("TrackNumber must be > 0 and < 127"); } bufferStream.writeEBMLVarInt(keyframe.trackNumber); // Always 1 byte since we limit the range of trackNumber @@ -869,11 +1077,24 @@ ] }; } - + /** - * Create a Cluster node using these fields: + * Create either a SimpleBlock or BlockGroup (if alpha is required) for the given keyframe. * - * timecode - Start time for the cluster + * @param {Frame} keyframe + */ + function createContainerForKeyframe(keyframe) { + if (keyframe.alpha) { + return createBlockGroupForTransparentKeyframe(keyframe); + } + + return createSimpleBlockForKeyframe(keyframe); + } + + /** + * Create a Cluster EBML node. + * + * @param {Cluster} cluster * * Returns an EBML element. */ @@ -919,7 +1140,7 @@ * The seek entry for the Cues in the SeekHead is updated. */ function writeCues() { - var + let ebml = { "id": 0x1C53BB6B, "data": cues @@ -938,27 +1159,27 @@ * Flush the frames in the current clusterFrameBuffer out to the stream as a Cluster. */ function flushClusterFrameBuffer() { - if (clusterFrameBuffer.length == 0) { + if (clusterFrameBuffer.length === 0) { return; } // First work out how large of a buffer we need to hold the cluster data - var + let rawImageSize = 0; - for (var i = 0; i < clusterFrameBuffer.length; i++) { - rawImageSize += clusterFrameBuffer[i].frame.length; + for (let i = 0; i < clusterFrameBuffer.length; i++) { + rawImageSize += clusterFrameBuffer[i].frame.length + (clusterFrameBuffer[i].alpha ? clusterFrameBuffer[i].alpha.length : 0); } - var - buffer = new ArrayBufferDataStream(rawImageSize + clusterFrameBuffer.length * 32), // Estimate 32 bytes per SimpleBlock header + let + buffer = new ArrayBufferDataStream(rawImageSize + clusterFrameBuffer.length * 64), // Estimate 64 bytes per block header cluster = createCluster({ timecode: Math.round(clusterStartTime), }); - - for (var i = 0; i < clusterFrameBuffer.length; i++) { - cluster.data.push(createKeyframeBlock(clusterFrameBuffer[i])); + + for (let i = 0; i < clusterFrameBuffer.length; i++) { + cluster.data.push(createContainerForKeyframe(clusterFrameBuffer[i])); } writeEBML(buffer, blobBuffer.pos, cluster); @@ -977,11 +1198,24 @@ if (options.frameRate) { options.frameDuration = 1000 / options.frameRate; } else { - throw "Missing required frameDuration or frameRate setting"; + throw new Error("Missing required frameDuration or frameRate setting"); } } + + // Avoid 1.0 (lossless) because it creates VP8L lossless frames that WebM doesn't support + options.quality = Math.max(Math.min(options.quality, 0.99999), 0); + + if (options.alphaQuality === undefined) { + options.alphaQuality = options.quality; + } else { + options.alphaQuality = Math.max(Math.min(options.alphaQuality, 0.99999), 0); + } } - + + /** + * + * @param {Frame} frame + */ function addFrameToCluster(frame) { frame.trackNumber = DEFAULT_TRACK_NUMBER; @@ -1003,7 +1237,7 @@ * Call once writing is complete (so the offset of all top level elements is known). */ function rewriteSeekHead() { - var + let seekHeadBuffer = new ArrayBufferDataStream(seekHead.size), oldPos = blobBuffer.pos; @@ -1021,7 +1255,7 @@ * Rewrite the Duration field of the Segment with the newly-discovered video duration. */ function rewriteDuration() { - var + let buffer = new ArrayBufferDataStream(8), oldPos = blobBuffer.pos; @@ -1036,31 +1270,58 @@ } /** - * Add a frame to the video. Currently the frame must be a Canvas element. + * Add a frame to the video. + * + * @param {HTMLCanvasElement|String} frame - A Canvas element that contains the frame, or a WebP string + * you obtained by calling toDataUrl() on an image yourself. + * + * @param {HTMLCanvasElement|String} [alpha] - For transparent video, instead of including the alpha channel + * in your provided `frame`, you can instead provide it separately + * here. The alpha channel of this alpha canvas will be ignored, + * encode your alpha information into this canvas' grayscale + * brightness instead. + * + * This is useful because it allows you to paint the colours + * you need into your `frame` even in regions which are fully + * transparent (which Canvas doesn't normally let you influence). + * This allows you to control the colour of the fringing seen + * around objects on transparent backgrounds. + * + * @param {Number} [overrideFrameDuration] - Set a duration for this frame (in milliseconds) that differs + * from the default */ - this.addFrame = function(canvas) { - if (writtenHeader) { - if (canvas.width != videoWidth || canvas.height != videoHeight) { - throw "Frame size differs from previous frames"; - } - } else { - videoWidth = canvas.width; - videoHeight = canvas.height; + this.addFrame = function(frame, alpha, overrideFrameDuration) { + if (!writtenHeader) { + videoWidth = frame.width || 0; + videoHeight = frame.height || 0; writeHeader(); - writtenHeader = true; } - var - webP = renderAsWebP(canvas, {quality: options.quality}); + let + keyframe = extractKeyframeFromWebP(renderAsWebP(frame, options.quality)), + frameDuration, frameAlpha = null; - if (!webP) { - throw "Couldn't decode WebP frame, does the browser support WebP?"; + if (overrideFrameDuration) { + frameDuration = overrideFrameDuration; + } else if (typeof alpha == "number") { + frameDuration = alpha; + } else { + frameDuration = options.frameDuration; + } + + if (options.transparent) { + if (alpha instanceof HTMLCanvasElement || typeof alpha === "string") { + frameAlpha = alpha; + } else if (keyframe.hasAlpha) { + frameAlpha = convertAlphaToGrayscaleImage(frame); + } } addFrameToCluster({ - frame: extractKeyframeFromWebP(webP), - duration: options.frameDuration + frame: keyframe.frame, + duration: frameDuration, + alpha: frameAlpha ? extractKeyframeFromWebP(renderAsWebP(frameAlpha, options.alphaQuality)).frame : null }); }; @@ -1071,6 +1332,10 @@ * a Blob with the contents of the entire video. */ this.complete = function() { + if (!writtenHeader) { + writeHeader(); + } + flushClusterFrameBuffer(); writeCues(); @@ -1088,10 +1353,10 @@ validateOptions(); }; }; - + if (typeof module !== 'undefined' && typeof module.exports !== 'undefined') { module.exports = WebMWriter(require("./ArrayBufferDataStream"), require("./BlobBuffer")); } else { - window.WebMWriter = WebMWriter(ArrayBufferDataStream, BlobBuffer); + window.WebMWriter = WebMWriter(window.ArrayBufferDataStream, window.BlobBuffer); } })(); diff --git a/utils/build.sh b/utils/build.sh index 9fbda8f..decc772 100755 --- a/utils/build.sh +++ b/utils/build.sh @@ -1,4 +1,7 @@ #!/bin/bash uglifyjs ../src/CCapture.js --compress --mangle -o ../build/CCapture.min.js -uglifyjs ../src/webm-writer-0.2.0.js ../src/download.js ../src/tar.js ../src/gif.js ../src/CCapture.js --compress --mangle -o ../build/CCapture.all.min.js +uglifyjs ../src/webm-writer-0.3.0.js ../src/download.js ../src/mjbuilder.js ../src/tar.js ../src/gif.js ../src/CCapture.js --compress --mangle -o ../build/CCapture.all.min.js +uglifyjs ../src/webm-writer-0.3.0.js ../src/download.js ../src/CCapture.js --compress --mangle -o ../build/CCapture.webm.min.js +uglifyjs ../src/mjbuilder.js ../src/download.js ../src/CCapture.js --compress --mangle -o ../build/CCapture.mjpg.min.js +uglifyjs ../src/tar.js --compress --mangle -o ../build/tar.min.js