/* FileSaver.js * A saveAs() FileSaver implementation. * 2013-10-21 * * By Eli Grey, http://eligrey.com * License: X11/MIT * See LICENSE.md */ /*global self */ /*jslint bitwise: true, regexp: true, confusion: true, es5: true, vars: true, white: true, plusplus: true */ /*! @source http://purl.eligrey.com/github/FileSaver.js/blob/master/FileSaver.js */ var saveAs = saveAs || (typeof navigator !== 'undefined' && navigator.msSaveOrOpenBlob && navigator.msSaveOrOpenBlob.bind(navigator)) || (function(view) { "use strict"; var doc = view.document // only get URL when necessary in case BlobBuilder.js hasn't overridden it yet , get_URL = function() { return view.URL || view.webkitURL || view; } , URL = view.URL || view.webkitURL || view , save_link = doc.createElementNS("http://www.w3.org/1999/xhtml", "a") , can_use_save_link = !view.externalHost && "download" in save_link , click = function(node) { var event = doc.createEvent("MouseEvents"); event.initMouseEvent( "click", true, false, view, 0, 0, 0, 0, 0 , false, false, false, false, 0, null ); node.dispatchEvent(event); } , webkit_req_fs = view.webkitRequestFileSystem , req_fs = view.requestFileSystem || webkit_req_fs || view.mozRequestFileSystem , throw_outside = function (ex) { (view.setImmediate || view.setTimeout)(function() { throw ex; }, 0); } , force_saveable_type = "application/octet-stream" , fs_min_size = 0 , deletion_queue = [] , process_deletion_queue = function() { var i = deletion_queue.length; while (i--) { var file = deletion_queue[i]; if (typeof file === "string") { // file is an object URL URL.revokeObjectURL(file); } else { // file is a File file.remove(); } } deletion_queue.length = 0; // clear queue } , dispatch = function(filesaver, event_types, event) { event_types = [].concat(event_types); var i = event_types.length; while (i--) { var listener = filesaver["on" + event_types[i]]; if (typeof listener === "function") { try { listener.call(filesaver, event || filesaver); } catch (ex) { throw_outside(ex); } } } } , FileSaver = function(blob, name) { // First try a.download, then web filesystem, then object URLs var filesaver = this , type = blob.type , blob_changed = false , object_url , target_view , get_object_url = function() { var object_url = get_URL().createObjectURL(blob); deletion_queue.push(object_url); return object_url; } , dispatch_all = function() { dispatch(filesaver, "writestart progress write writeend".split(" ")); } // on any filesys errors revert to saving with object URLs , fs_error = function() { // don't create more object URLs than needed if (blob_changed || !object_url) { object_url = get_object_url(blob); } if (target_view) { target_view.location.href = object_url; } else { window.open(object_url, "_blank"); } filesaver.readyState = filesaver.DONE; dispatch_all(); } , abortable = function(func) { return function() { if (filesaver.readyState !== filesaver.DONE) { return func.apply(this, arguments); } }; } , create_if_not_found = {create: true, exclusive: false} , slice ; filesaver.readyState = filesaver.INIT; if (!name) { name = "download"; } if (can_use_save_link) { object_url = get_object_url(blob); // FF for Android has a nasty garbage collection mechanism // that turns all objects that are not pure javascript into 'deadObject' // this means `doc` and `save_link` are unusable and need to be recreated // `view` is usable though: doc = view.document; save_link = doc.createElementNS("http://www.w3.org/1999/xhtml", "a"); save_link.href = object_url; save_link.download = name; var event = doc.createEvent("MouseEvents"); event.initMouseEvent( "click", true, false, view, 0, 0, 0, 0, 0 , false, false, false, false, 0, null ); save_link.dispatchEvent(event); filesaver.readyState = filesaver.DONE; dispatch_all(); return; } // Object and web filesystem URLs have a problem saving in Google Chrome when // viewed in a tab, so I force save with application/octet-stream // http://code.google.com/p/chromium/issues/detail?id=91158 if (view.chrome && type && type !== force_saveable_type) { slice = blob.slice || blob.webkitSlice; blob = slice.call(blob, 0, blob.size, force_saveable_type); blob_changed = true; } // Since I can't be sure that the guessed media type will trigger a download // in WebKit, I append .download to the filename. // https://bugs.webkit.org/show_bug.cgi?id=65440 if (webkit_req_fs && name !== "download") { name += ".download"; } if (type === force_saveable_type || webkit_req_fs) { target_view = view; } if (!req_fs) { fs_error(); return; } fs_min_size += blob.size; req_fs(view.TEMPORARY, fs_min_size, abortable(function(fs) { fs.root.getDirectory("saved", create_if_not_found, abortable(function(dir) { var save = function() { dir.getFile(name, create_if_not_found, abortable(function(file) { file.createWriter(abortable(function(writer) { writer.onwriteend = function(event) { target_view.location.href = file.toURL(); deletion_queue.push(file); filesaver.readyState = filesaver.DONE; dispatch(filesaver, "writeend", event); }; writer.onerror = function() { var error = writer.error; if (error.code !== error.ABORT_ERR) { fs_error(); } }; "writestart progress write abort".split(" ").forEach(function(event) { writer["on" + event] = filesaver["on" + event]; }); writer.write(blob); filesaver.abort = function() { writer.abort(); filesaver.readyState = filesaver.DONE; }; filesaver.readyState = filesaver.WRITING; }), fs_error); }), fs_error); }; dir.getFile(name, {create: false}, abortable(function(file) { // delete file if it already exists file.remove(); save(); }), abortable(function(ex) { if (ex.code === ex.NOT_FOUND_ERR) { save(); } else { fs_error(); } })); }), fs_error); }), fs_error); } , FS_proto = FileSaver.prototype , saveAs = function(blob, name) { return new FileSaver(blob, name); } ; FS_proto.abort = function() { var filesaver = this; filesaver.readyState = filesaver.DONE; dispatch(filesaver, "abort"); }; FS_proto.readyState = FS_proto.INIT = 0; FS_proto.WRITING = 1; FS_proto.DONE = 2; FS_proto.error = FS_proto.onwritestart = FS_proto.onprogress = FS_proto.onwrite = FS_proto.onabort = FS_proto.onerror = FS_proto.onwriteend = null; view.addEventListener("unload", process_deletion_queue, false); return saveAs; }(this.self || this.window || this.content)); // `self` is undefined in Firefox for Android content script context // while `this` is nsIContentFrameMessageManager // with an attribute `content` that corresponds to the window if (typeof module !== 'undefined') module.exports = saveAs; ;window.dataUriToBlob = (function(){ /** * Blob constructor. */ var Blob = window.Blob; /** * ArrayBufferView support. */ var hasArrayBufferView = new Blob([new Uint8Array(100)]).size == 100; /** * Return a `Blob` for the given data `uri`. * * @param {String} uri * @return {Blob} * @api public */ var dataUriToBlob = function(uri){ var data = uri.split(',')[1]; var bytes = atob(data); var buf = new ArrayBuffer(bytes.length); var arr = new Uint8Array(buf); for (var i = 0; i < bytes.length; i++) { arr[i] = bytes.charCodeAt(i); } if (!hasArrayBufferView) arr = buf; var blob = new Blob([arr], { type: mime(uri) }); blob.slice = blob.slice || blob.webkitSlice; return blob; }; /** * Return data uri mime type. */ function mime(uri) { return uri.split(';')[0].slice(5); } return dataUriToBlob; })() ;/* asdf.us/dither */ var workerURL=URL.createObjectURL(new Blob(["(",function(){function a(a){var c=a.imageData,d=b(c.data),e=new NeuQuant(d,d.length,1),f=e.process();self.postMessage({task:"quantize",neuquant:e.save(),colortab:f})}function b(a){for(var b=[],c=0,d=0,e=a.length;e>c;d+=4)b[c++]=a[d],b[c++]=a[d+1],b[c++]=a[d+2];return b}function c(a){var b=a.frame_index,c=a.frame_length,d=a.height,e=a.width,f=a.imageData,g=a.delay,h=a.neuquant,i=a.colortab,j=new GIFEncoder;j.setRepeat(0),j.setQuality(1),j.setSize(e,d),j.setDelay(g),0==b?j.start():(j.cont(),j.setProperties(!0,!1)),j.setNeuquant(h,i),j.addFrame(f,!0),c==b&&j.finish(),self.postMessage({task:"encode",frame_index:b,frame_data:j.stream().getData()})}GIFEncoder=function(){function a(){this.bin=[]}for(var b=0,c={};256>b;b++)c[b]=String.fromCharCode(b);a.prototype.getData=function(){for(var a="",b=this.bin.length,d=0;b>d;d++)a+=c[this.bin[d]];return a},a.prototype.writeByte=function(a){this.bin.push(a)},a.prototype.writeUTFBytes=function(a){for(var b=a.length,c=0;b>c;c++)this.writeByte(a.charCodeAt(c))},a.prototype.writeBytes=function(a,b,c){for(var d=c||a.length,e=b||0;d>e;e++)this.writeByte(a[e])};{var d,e,f,g,h,i,j,k,l,m={},n=null,o=-1,p=0,q=!1,r=new Array,s=7,t=-1,u=!1,v=!0,w=!1,x=1,y=null,z=(m.setDelay=function(a){p=Math.round(a/10)},m.setDispose=function(a){a>=0&&(t=a)},m.setRepeat=function(a){a>=0&&(o=a)},m.setTransparent=function(a){n=a},m.addFrame=function(a,b){if(null==a||!q||null==g)throw new Error("Please call start method before calling addFrame");var c=!0;try{b?h=a:(h=a.getImageData(0,0,a.canvas.width,a.canvas.height).data,w||A(a.canvas.width,a.canvas.height)),D(),B(),v&&(G(),I(),o>=0&&H()),E(),F(),v||I(),K(),v=!1}catch(d){c=!1}return c},m.finish=function(){if(!q)return!1;var a=!0;q=!1;try{g.writeByte(59)}catch(b){a=!1}return a},function(){f=0,h=null,i=null,j=null,l=null,u=!1,v=!0}),A=(m.setFrameRate=function(a){15!=a&&(p=Math.round(100/a))},m.setQuality=function(a){x=Math.max(1,a)},m.setSize=function(a,b){(!q||v)&&(d=a,e=b,1>d&&(d=320),1>e&&(e=240),w=!0)}),B=(m.setNeuquant=function(a,b){y=a,l=b},m.start=function(){z();var b=!0;u=!1,g=new a;try{g.writeUTFBytes("GIF89a")}catch(c){b=!1}return q=b},m.cont=function(){z();var b=!0;return u=!1,g=new a,q=b},function(){var a=i.length,b=a/3;j=[];var c;y&&l?(c=new NeuQuant,c.load(y)):(c=new NeuQuant(i,a,x),l=c.process());for(var d=0,e=0;b>e;e++){var g=c.map(255&i[d++],255&i[d++],255&i[d++]);r[g]=!0,j[e]=g}i=null,k=8,s=7,null!=n&&(f=C(n))}),C=function(a){if(null==l)return-1;for(var b=(16711680&a)>>16,c=(65280&a)>>8,d=255&a,e=0,f=16777216,g=l.length,h=0;g>h;){var i=b-(255&l[h++]),j=c-(255&l[h++]),k=d-(255&l[h]),m=i*i+j*j+k*k,n=h/3;r[n]&&f>m&&(f=m,e=n),h++}return e},D=function(){var a=d,b=e;i=[];for(var c=h,f=0,g=0;b>g;g++)for(var j=0;a>j;j++){var k=g*a*4+4*j;i[f++]=c[k],i[f++]=c[k+1],i[f++]=c[k+2]}},E=function(){g.writeByte(33),g.writeByte(249),g.writeByte(4);var a,b;null==n?(a=0,b=0):(a=1,b=2),t>=0&&(b=7&t),b<<=2,g.writeByte(0|b|0|a),J(p),g.writeByte(f),g.writeByte(0)},F=function(){g.writeByte(44),J(0),J(0),J(d),J(e),v?g.writeByte(0):g.writeByte(128|s)},G=function(){J(d),J(e),g.writeByte(240|s),g.writeByte(0),g.writeByte(0)},H=function(){g.writeByte(33),g.writeByte(255),g.writeByte(11),g.writeUTFBytes("NETSCAPE2.0"),g.writeByte(3),g.writeByte(1),J(o),g.writeByte(0)},I=function(){g.writeBytes(l);for(var a=768-l.length,b=0;a>b;b++)g.writeByte(0)},J=function(a){g.writeByte(255&a),g.writeByte(a>>8&255)},K=function(){var a=new LZWEncoder(d,e,j,k);a.encode(g)};m.stream=function(){return g},m.setProperties=function(a,b){q=a,v=b}}return m},LZWEncoder=function(){var a,b,c,d,e,f,g,h,i,j,k,l,m={},n=-1,o=12,p=5003,q=o,r=1<=254&&G(b)},D=function(a){E(u),v=j+2,w=!0,J(j,a)},E=function(a){for(var b=0;a>b;++b)s[b]=-1},F=m.compress=function(a,b){var c,d,e,f,m,o,p;for(i=a,w=!1,g=i,h=H(g),j=1<c;c*=2)++p;p=8-p,o=u,E(o),J(j,b);a:for(;(e=I())!=n;)if(c=(e<=0){m=o-d,0==d&&(m=1);do if((d-=m)<0&&(d+=o),s[d]==c){f=t[d];continue a}while(s[d]>=0)}J(f,b),f=e,r>v?(t[d]=v++,s[d]=c):D(b)}else f=t[d];J(f,b),J(k,b)},G=(m.encode=function(c){c.writeByte(d),e=a*b,f=0,F(d+1,c),c.writeByte(0)},function(a){l>0&&(a.writeByte(l),a.writeBytes(A,0,l),l=0)}),H=function(a){return(1<0?x|=a<=8;)C(255&x,b),x>>=8,y-=8;if((v>h||w)&&(w?(h=H(g=i),w=!1):(++g,h=g==q?r:H(g))),a==k){for(;y>0;)C(255&x,b),x>>=8,y-=8;G(b)}};return B.apply(this,arguments),m},NeuQuant=function(){var a,b,c,d,e,f={},g=128,h=499,i=491,j=487,k=503,l=3*k,m=g-1,n=4,o=100,p=16,q=1<>s,u=q<>3,w=6,x=1<i;i++)e[i]=new Array(4),j=e[i],j[0]=j[1]=j[2]=(i<c;c++)b[e[c][3]]=c;for(var d=0,f=0;g>f;f++){var h=b[f];a[d++]=e[h][0],a[d++]=e[h][1],a[d++]=e[h][2]}return a},M=function(){var a,b,c,d,f,h,i,j;for(i=0,j=0,a=0;g>a;a++){for(f=e[a],c=a,d=f[1],b=a+1;g>b;b++)h=e[b],h[1]>1,b=i+1;d>b;b++)G[b]=a;i=d,j=a}}for(G[i]=j+m>>1,b=i+1;256>b;b++)G[b]=m},N=function(){var e,f,g,m,p,q,r,s,t,u,v,x,A,C;for(l>c&&(d=1),a=30+(d-1)/3,x=b,A=0,C=c,v=c/(3*d),u=v/o,s=B,q=y,r=q>>w,1>=r&&(r=0),e=0;r>e;e++)J[e]=s*((r*r-e*e)*D/(r*r));for(t=l>c?3:c%h!=0?3*h:c%i!=0?3*i:c%j!=0?3*j:3*k,e=0;v>e;)if(g=(255&x[A+0])<=C&&(A-=c),e++,0==u&&(u=1),e%u==0)for(s-=s/a,q-=q/z,r=q>>w,1>=r&&(r=0),f=0;r>f;f++)J[f]=s*((r*r-f*f)*D/(r*r))},O=(f.save=function(){var a={netindex:G,netsize:g,network:e};return a},f.load=function(a){G=a.netindex,g=a.netsize,e=a.network},f.map=function(a,b,c){var d,f,h,i,j,k,l;for(j=1e3,l=-1,d=G[b],f=d-1;g>d||f>=0;)g>d&&(k=e[d],h=k[1]-b,h>=j?d=g:(d++,0>h&&(h=-h),i=k[0]-a,0>i&&(i=-i),h+=i,j>h&&(i=k[2]-c,0>i&&(i=-i),h+=i,j>h&&(j=h,l=k[3])))),f>=0&&(k=e[f],h=b-k[1],h>=j?f=-1:(f--,0>h&&(h=-h),i=k[0]-a,0>i&&(i=-i),h+=i,j>h&&(i=k[2]-c,0>i&&(i=-i),h+=i,j>h&&(j=h,l=k[3]))));return l},f.process=function(){return N(),O(),M(),L()},function(){var a;for(a=0;g>a;a++)e[a][0]>>=n,e[a][1]>>=n,e[a][2]>>=n,e[a][3]=a}),P=function(a,b,c,d,f){var h,i,j,k,l,m,n;for(j=b-a,-1>j&&(j=-1),k=b+a,k>g&&(k=g),h=b+1,i=b-1,m=1;k>h||i>j;){if(l=J[m++],k>h){n=e[h++];try{n[0]-=l*(n[0]-c)/F,n[1]-=l*(n[1]-d)/F,n[2]-=l*(n[2]-f)/F}catch(o){}}if(i>j){n=e[i--];try{n[0]-=l*(n[0]-c)/F,n[1]-=l*(n[1]-d)/F,n[2]-=l*(n[2]-f)/F}catch(o){}}}},Q=function(a,b,c,d,f){var g=e[b];g[0]-=a*(g[0]-c)/B,g[1]-=a*(g[1]-d)/B,g[2]-=a*(g[2]-f)/B},R=function(a,b,c){var d,f,h,i,j,k,l,m,o,q;for(m=~(1<<31),o=m,k=-1,l=k,d=0;g>d;d++)q=e[d],f=q[0]-a,0>f&&(f=-f),h=q[1]-b,0>h&&(h=-h),f+=h,h=q[2]-c,0>h&&(h=-h),f+=h,m>f&&(m=f,k=d),i=f-(H[d]>>p-n),o>i&&(o=i,l=d),j=I[d]>>s,I[d]-=j,H[d]+=j< true // globber("*:c".split(":"), "a:b:c".split(":")) => true // globber("a:*".split(":"), "a:b:c".split(":")) => true // globber("a:*:c".split(":"), "a:b:c".split(":")) => true // based on codegolf.stackexchange.com/questions/467/implement-glob-matcher var globber = function(patterns, strings) { // console.log("globber called with: " + patterns.join(":"), strings.join(":")) var first = patterns[0], rest = patterns.slice(1), len = strings.length, matchFound; if(first === '*') { for(var i = 0; i <= len; ++i) { // console.log("* " + i + " trying " + rest.join(":") + " with " + strings.slice(i).join(":")) if(globber(rest, strings.slice(i))) return true; } return false; } else { matchFound = (first === strings[0]); // console.log ("literal matching " + first + " " + strings[0] + " " + !!matched) } return matchFound && ((!rest.length && !len) || globber(rest, strings.slice(1))); }; var setproto = function(obj, proto){ if (obj.__proto__) obj.__proto__ = proto; else for (var key in proto) obj[key] = proto[key]; }; var Tube = (function(){ var globcache = {}; var Tube = function(opts){ opts = opts || {}; if (opts.queue){ var c = function(){ var args = arguments; // queueOrNextTick (function(){ c.send.apply(c, args) }); nextTick (function(){ c.send.apply(c, args) }); return c; }; } else { var c = function(){ c.send.apply(c, arguments); return c; }; } setproto(c, Tube.proto); c.listeners = {}; c.globListeners = {}; return c; }; Tube.total = {}; Tube.proto = {}; /* adds fns as listeners to a channel on("msg", fn, {opts}) on("msg", [fn, fn2], {opts}) on("msg msg2 msg3", fn, {opts}) on({"msg": fn, "msg2": fn2}, {opts}) */ Tube.proto.on = function(){ var chan = this; if (typeof arguments[0] === "string") { //if (arguments.length > 1) { // on("msg", f) var msgMap = {}; msgMap[arguments[0]] = arguments[1]; var opts = arguments[2] || {}; } else { // on({"msg": f, ...}) var msgMap = arguments[0]; var opts = arguments[1] || {}; } for (var string in msgMap){ var msgs = string.split(" "); var fs = msgMap[string]; if (!Array.isArray(fs)) fs = [fs]; for(var i=0, f; f=fs[i]; i++){ if (!f.uid) f.uid = Uid(); } for(var i=0, msg; msg=msgs[i]; i++){ var listeners = (msg.indexOf("*") === -1) ? chan.listeners : chan.globListeners; // todo: this probably wastes a lot of memory? // make a copy of the listener, add to it, and replace the listener // why not just push directly? // send might be iterating over it... and that will fuck up the iteration listeners[msg] = (msg in listeners) ? listeners[msg].concat(fs) : fs.concat(); } } return chan; }; /* off() off("a:b:c") off(f) off("a:b:c", f) off("a:b:c d:e:f") off([f, f2]) off({"a": f, "b": f2}) */ Tube.proto.off = function(){ var chan = this; var listeners, i, msgs, msg; // off() : delete all listeners. but replace, instead of delete if (arguments.length === 0) { chan.listeners = {}; chan.globListeners = {}; return chan; } // off("a:b:c d:e:f") // remove all matching listeners if (arguments.length === 1 && typeof arguments[0] === "string"){ // question... will this fuck up send if we delete in the middle of it dispatching? msgs = arguments[0].split(" "); for (i=0; msg=msgs[i]; i++){ delete chan.listeners[msg]; delete chan.globListeners[msg]; } return chan; } // off(f) or off([f, f2]) // remove all matching functions if (typeof arguments[0] === "function" || Array.isArray(arguments[0])) { var fs = (typeof arguments[0] === "function") ? [arguments[0]] : arguments[0]; // TODO return chan; } // off("a:b:c", f) or off({"a": f, "b": f2}) if (arguments.length > 1) { // off("msg", f) var msgMap = {}; msgMap[arguments[0]] = arguments[1]; } else { // off({"msg": f, ...}) var msgMap = arguments[0]; } for (var string in msgMap){ msgs = string.split(" "); var fs = msgMap[string]; if (typeof fs === "function") fs = [fs]; for(var i=0; msg=msgs[i]; i++){ if (msg in chan.listeners) listeners = chan.listeners; else if (msg in chan.globListeners) listeners = chan.globListeners; else continue; // gotta do this carefully in case we are still iterating through the listener in send // build a new array and assign it to the property, instead of mutating it. // console.log(" length of listeners[" + msg + "]: " + listeners[msg].length) // console.log(listeners[msg].join(",")); // console.log(fs.join(",")); listeners[msg] = listeners[msg].filter( function(f){ return fs.indexOf(f) === -1 } ); // console.log(" length of listeners[" + msg + "]: " + listeners[msg].length) } } return chan; }; /* c = Tube() c.on("foo", fn) c("foo", "bar", []) will call fn("bar", [], "foo") */ Tube.proto.send = function(msgString /*, data... */){ // todo: don't do this? if (!Tube.total[msgString]) Tube.total[msgString] = 0 Tube.total[msgString]+=1; var listener, listeners = this.listeners, globListeners = this.globListeners, //args = Array.prototype.splice.call(arguments, 1), msgs = tokenize(msgString), msg, f; if (arguments.length) { var args = Array.prototype.splice.call(arguments, 1); args.push(msgString); } else { var args = []; } for (var m=0; msg=msgs[m]; m++){ var fsToRun = []; var uidKeyFnValue = {}; var uidKeyMsgStringValue = {}; // note this will die on errors // todo: implement http://dean.edwards.name/weblog/2009/03/callbacks-vs-events/ // exact matches if (listener = listeners[msg]) { for (var i=0; f=listener[i]; i++){ // fsToRun.push([f, msg]); uidKeyFnValue[f.uid] = f; uidKeyMsgStringValue[f.uid] = msg; } } // glob matches var msgSplit = msg.split(":"); for (var pattern in globListeners){ if (pattern !== "*") { // * always matches var patternSplit = globcache[pattern] || (globcache[pattern] = pattern.split(":")); if (!globber(patternSplit, msgSplit)) continue; } listener = globListeners[pattern]; for (var i=0; f=listener[i]; i++){ //f.apply(window, args); // hm possibly pass the actual message to the func // fsToRun.push([f, msg]); uidKeyFnValue[f.uid] = f; uidKeyMsgStringValue[f.uid] = msg; } } var fns = []; for (var f in uidKeyFnValue) fns.push(uidKeyFnValue[f]); for (var i=0, f; f=fns[i]; i++) f.apply(f, args); } return this; }; return Tube; })() ;// Number of WebWorkers to create var WORKERS = 4; // Number of frames to use to build the gif palette (takes longest) var FRAMES_TO_QUANTIZE = 4; // Upload these gifs when finished?? var DO_UPLOAD = true; function GifEncoder(){ var base = this; this.working = false; var canvases = []; var contexts = []; var frames = []; var delays = []; var width = 0; var height = 0; var frames_done = 0; var initted = Date.now(); var started = Date.now(); var tube = base.tube = new Tube () var workers = new Factory (); var width, height; var neuquant, colortab; workers.hire("message", receiveMessage); workers.hire("quantize", receiveQuantize); workers.hire("encode", receiveEncode); var reset = this.reset = function(){ resetFrames() neuquant = null; colortab = null; base.quantized = false } var resetFrames = this.resetFrames = function(){ canvases = []; contexts = []; frames = []; delays = []; width = 0; height = 0; frames_done = 0; } this.on = function(){ base.tube.on.apply(base.tube, arguments) }; this.off = function(){ base.tube.off.apply(base.tube, arguments) }; var addFrame = this.addFrame = function(canvas, delay) { var ctx = canvas.getContext('2d'); canvases.push(canvas); contexts.push(ctx); delays.push(delay); if (canvases.length == 1) { width = canvas.width; height = canvas.height; } } var addFrames = this.addFrames = function(canvas_array, delay){ for (var i = 0; i < canvas_array.length; i++) { var canvas = canvas_array[i] var ctx = canvas.getContext('2d'); canvases.push(canvas); contexts.push(ctx); delays.push(delay); } if (canvases.length == canvas_array.length) { width = canvas_array[0].width; height = canvas_array[0].height; } } var copyFrame = this.copyFrame = function(canvas, delay) { var newCanvas = document.createElement("canvas"); var ctx = newCanvas.getContext('2d'); ctx.drawImage(canvas, 0, 0, canvas.width, canvas.height); canvases.push(newCanvas); contexts.push(ctx); delays.push(delay); if (canvases.length == 1) { width = canvas.width; height = canvas.height; } } function Factory () { var base = this; var w = 0; // which worker to work next var ww = []; base.init = function(){ for (var i = 0; i < WORKERS; i++) { // var worker = new Worker('http://asdf.us/gif-recorder/js/gif-encode/worker.concat.js'); var worker = new Worker (workerURL); // via blobify worker.onmessage = base.receiveWork; ww.push(worker); } } var tasks = {}; base.hire = function(task, cb){ tasks[task] = cb; } base.work = function(job){ ww[++w % ww.length].postMessage(job); } base.receiveWork = function(e){ e.data.task in tasks && tasks[e.data.task](e); } base.init(); } function receiveMessage(e){ console.log("[WORKER]", e.data.message); } var neuquant, colortab; var quantize = this.quantize = function () { initted = Date.now(); started = Date.now(); var spritedata = spriteSheet(FRAMES_TO_QUANTIZE); workers.work({ task: 'quantize', imageData: spritedata }); } function receiveQuantize(e) { console.log(Date.now() - started, "quantization done"); neuquant = e.data.neuquant; colortab = e.data.colortab; base.quantized = true base.tube("quantized") } var encode = this.encode = function (nq, ct) { if (! canvases.length) { throw Error ("No frames to encode") } nq = nq || neuquant ct = ct || colortab started = Date.now(); frames_done = 0; console.log('working .... '); var i = 0; function sendWork () { if (i == canvases.length) return doneSending(); var ctx = contexts[i]; var imdata = ctx.getImageData(0, 0, width, height).data; var delay = delays[i]; workers.work({ task: 'encode', frame_index: i, frame_length: contexts.length-1, height: height, width: width, delay: delay, imageData: imdata, neuquant: neuquant, colortab: colortab }); i++; setTimeout(sendWork, 16); } function doneSending(){ base.tube("done_sending") } sendWork(); } function receiveEncode(e){ var frame_index = e.data["frame_index"]; var frame_data = e.data["frame_data"]; frames[frame_index] = frame_data; base.tube("encoded-frame", frames.length, canvases.length) for (var j = 0; j < canvases.length; j++) { if (frames[j] == null) { return; } } console.log("FINISHED " + canvases.length); var binary_gif = frames.join(''); var base64_gif = window.btoa(binary_gif); var data_url = 'data:image/gif;base64,'+base64_gif; base.working = false; // photo.setAttribute('src', data_url); // ui.doneEncodingPicture(); base.tube("rendered", binary_gif) base.tube("rendered-url", data_url) // if (DO_UPLOAD) upload( base64_gif ); console.log((Date.now() - started), "processed frames"); console.log((Date.now() - initted), "done"); } // function upload (base64_gif) { // $("#working").html("UPLOADING") // // console.log("starting upload") // var params = { // url: base64_gif // } // $.ajax({ // 'url': "/photos.json", // 'type': 'post', // 'data': csrf(params), // 'success': function(data){ // // // $("#share").data("href", "/photos/" + data.hash) // // $("#share, #make-another").fadeIn(400); // console.log(data); // console.log((Date.now() - started), "uploaded"); // // $("#photo").attr("src", data.url); // // window.location.href = "/photos/" + data.hash // localStorage.setItem('hash', data.hash) // window.location.href = "/" // // data.hash // } // }); // console.log("ok"); // } function spriteSheet (frameCount) { var start = Date.now(); frameCount = Math.min(contexts.length, frameCount); var sprites = document.createElement("canvas"); var spriteContext = sprites.getContext('2d'); sprites.width = width; sprites.height = height * frameCount; var spritedata = spriteContext.getImageData(0, 0, sprites.width, sprites.height) var spritedatadata = spritedata.data var j = 0; var ctxz = sample(contexts, 4); while (frameCount--) { var ctx = ctxz[frameCount]; var imdata = ctx.getImageData(0, 0, width, height).data; for (var n = 0; n < imdata.length; j++, n++) { spritedatadata[j] = imdata[n]; } } // spriteContext.putImageData(spritedata, 0, 0, 0, 0, sprites.width, sprites.height); // upload( sprites.toDataURL("image/png").split(",")[1] console.log(Date.now() - start, "built spritesheet"); return spritedata; } } ;var UI_TEMPLATE = [ '
', '
', '
', 'frames ', 'delay ', '', '', '', '
', 'w ', 'h ', 'x ', 'y ', '
', '
', '
' ].join("") ;(function(){ if ($("gif-recorder")) return; var canvases = document.getElementsByTagName("canvas") if (canvases.length == 0) { alert("no canvas found"); return; } var biggest = 0, biggest_area = 0; for (var i in canvases) { var area = canvases[i].width*canvases[i].height if (area > biggest_area) biggest = i; } var source = canvases[biggest] var encoder = new GifEncoder() encoder.on("encoded-frame", encoded_frame) encoder.on("rendered", rendered_bytes) encoder.on("rendered-url", rendered_url) var w, h, x, y; var w_el, h_el, x_el, y_el; var last_t, frame_t, count, delay, offset, done; var frames = [] var curtain, outline var dragging = false var lastGif init() function init(){ document.body.style.width = "100%" document.body.style.height = "100%" document.body.parentNode.style.width = "100%" document.body.parentNode.style.height = "100%" // var template = $("template").innerHTML var el = document.createElement("div") el.id = "gif-recorder" // el.innerHTML = template el.innerHTML = UI_TEMPLATE document.body.appendChild(el) bind() activate() } function bind(){ curtain = $("curtain") outline = $("outline") controls = $("controls") w_el = $("w_el") h_el = $("h_el") x_el = $("x_el") y_el = $("y_el") $("record").addEventListener("click", record, false) $("save").addEventListener("click", save, false) curtain.addEventListener("mousedown", box_start, false) curtain.addEventListener("mousemove", box_size, false) curtain.addEventListener("mouseup", box_end, false) w_el.addEventListener("change", box_position, false) h_el.addEventListener("change", box_position, false) x_el.addEventListener("change", box_position, false) y_el.addEventListener("change", box_position, false) window.addEventListener("keydown", keydown, false) } var listening = false function activate(){ listening = true outline.style.display = "none" controls.style.display = "block" curtain.style.display = "block" } function deactivate(){ listening = false outline.style.display = "none" controls.style.display = "none" curtain.style.display = "none" } function keydown(e){ if (e.keyCode == 27) { // esc ! activated ? activate : deactivate } } function defer(callback){ var timeout = null return function(){ clearTimeout(timeout) timeout = setTimeout(callback, 300) } } function box_start(e){ if (! listening) return e.stopPropagation() x = e.pageX y = e.pageY w = 1 h = 1 dragging = true box_resize() } function box_position(){ w = _int(w_el) h = _int(h_el) x = _int(x_el) y = _int(y_el) box_resize() } function box_resize(){ if (isNaN(w) || isNaN(h) || isNaN(x) || isNaN(y)) return w_el.value = ~~(w) h_el.value = ~~(h) x_el.value = ~~(x) y_el.value = ~~(y) outline.style.left = px(x-1) outline.style.top = px(y-1) outline.style.width = px(w) outline.style.height = px(h) outline.style.display = "block" enable("record") } function box_size(e){ if (! dragging) return e.stopPropagation() w = e.pageX - x h = e.pageY - y box_resize() } function box_end(e){ e.preventDefault() dragging = false controls.style.display = "block" $("record").focus() } function _int(el){ return parseInt(typeof el == "string" ? $(el).value : el.value) } function _float(el){ return parseFloat(typeof el == "string" ? $(el).value : el.value) } function show(id){ $(id).style.display="block" } function hide(id){ $(id).style.display="none" } function enable(id){ $(id).removeAttribute("disabled") } function disable(id){ $(id).setAttribute("disabled","disabled") } function clickable(id){ $(id).style.pointerEvents = "auto" } function unclickable(id){ $(id).style.pointerEvents = "none" } function px(n){ return (~~n) + "px" } function record(e){ if (! listening) return e.stopPropagation() count = _int("framecount") delay = _float("framedelay") * 1000 offset = source.getBoundingClientRect(); console.log(count, delay) if (isNaN(count) || isNaN(delay)) return done = 0 frame_t = 0 build() capture() last_t = +new Date() requestAnimationFrame(recordloop) status("recording") disable("record") unclickable("curtain") unclickable("controls") } function recordloop(){ var canvas = document.createElement("canvas") var t = +new Date() frame_t += t - last_t last_t = t if (frame_t > delay) { frame_t -= delay capture() } if (done == count) { render() } else { requestAnimationFrame(recordloop) } } function build(){ frames = new Array(count) for (var i = 0; i < count; i++){ frames[i] = document.createElement("canvas") frames[i].height = h frames[i].width = w } } function backgroundColor(){ var colors = [ source.style.backgroundColor, document.body.style.backgroundColor, "white" ] for (var i in colors) { if (colors[i] && colors[i] != "") return colors[i] } } function capture(){ var frame = frames[done++] var ctx = frame.getContext('2d') ctx.fillStyle = backgroundColor() ctx.fillRect(0,0,w,h) ctx.drawImage(source, x-offset.left, y-offset.top, w, h, 0, 0, w, h) } function render(){ encoder.reset() encoder.addFrames(frames, delay) status("encoding") try { encoder.encode() } catch (e) { rendering = false status(e) throw e } } function $(s){ return document.getElementById("ge_" + s) } function status(s){ $("status").innerHTML = s } function encoded_frame(done,count){ status("encoded " + done + " / " + count) } function rendered_bytes(bytes){ status(filesize(bytes.length)) } function rendered_url(url){ var image = new Image () lastGif = image.src = url $("preview").innerHTML = "" $("preview").appendChild(image) rendering = false enable("record") enable("save") clickable("curtain") clickable("controls") } function save (e){ e.stopPropagation() if (! lastGif) return; var filename = (window.location.host + window.location.pathname).replace(/[^a-zA-Z0-9]/g,"-").replace(/-+/,"-") var blob = dataUriToBlob(lastGif) saveAs(blob, filename + "-" + (+new Date()) + ".gif"); } function filesize(n) { if (n < 1e3) return n + " bytes" if (n < 1e6) return decimalString(n/1e3) + " kb" if (n < 1e9) return decimalString(n/1e6) + " mb" return "WAY TOO BIG DUDE" } function decimalString(n){ var m = Math.floor(n); return m + "." + Math.round((n-m)*10) } })()