@loaders.gl/video 4.0.0-alpha.4 → 4.0.0-alpha.5

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,2415 @@
1
+ // @ts-nocheck
2
+ /* eslint-disable */
3
+
4
+ /* Copyrights for code authored by Yahoo Inc. is licensed under the following terms:
5
+ MIT License
6
+ Copyright 2017 Yahoo Inc.
7
+ 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:
8
+ The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
9
+ 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.
10
+ */
11
+ /*
12
+ utils.js
13
+ ========
14
+ */
15
+ /* Copyright 2017 Yahoo Inc.
16
+ * Copyrights licensed under the MIT License. See the accompanying LICENSE file for terms.
17
+ */
18
+ var utils = {
19
+ URL: window.URL || window.webkitURL || window.mozURL || window.msURL,
20
+ getUserMedia: (function () {
21
+ const getUserMedia =
22
+ navigator.getUserMedia ||
23
+ navigator.webkitGetUserMedia ||
24
+ navigator.mozGetUserMedia ||
25
+ navigator.msGetUserMedia;
26
+ return getUserMedia ? getUserMedia.bind(navigator) : getUserMedia;
27
+ })(),
28
+ requestAnimFrame:
29
+ window.requestAnimationFrame ||
30
+ window.webkitRequestAnimationFrame ||
31
+ window.mozRequestAnimationFrame ||
32
+ window.oRequestAnimationFrame ||
33
+ window.msRequestAnimationFrame,
34
+ requestTimeout: function requestTimeout(callback, delay) {
35
+ callback = callback || utils.noop;
36
+ delay = delay || 0;
37
+ if (!utils.requestAnimFrame) {
38
+ return setTimeout(callback, delay);
39
+ }
40
+ const start = new Date().getTime();
41
+ const handle = new Object();
42
+ const requestAnimFrame = utils.requestAnimFrame;
43
+ const loop = function loop() {
44
+ const current = new Date().getTime();
45
+ const delta = current - start;
46
+ delta >= delay ? callback.call() : (handle.value = requestAnimFrame(loop));
47
+ };
48
+ handle.value = requestAnimFrame(loop);
49
+ return handle;
50
+ },
51
+ Blob:
52
+ window.Blob ||
53
+ window.BlobBuilder ||
54
+ window.WebKitBlobBuilder ||
55
+ window.MozBlobBuilder ||
56
+ window.MSBlobBuilder,
57
+ btoa: (function () {
58
+ const btoa =
59
+ window.btoa ||
60
+ function (input) {
61
+ let output = '';
62
+ let i = 0;
63
+ const l = input.length;
64
+ const key = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=';
65
+ let chr1 = void 0;
66
+ let chr2 = void 0;
67
+ let chr3 = void 0;
68
+ let enc1 = void 0;
69
+ let enc2 = void 0;
70
+ let enc3 = void 0;
71
+ let enc4 = void 0;
72
+ while (i < l) {
73
+ chr1 = input.charCodeAt(i++);
74
+ chr2 = input.charCodeAt(i++);
75
+ chr3 = input.charCodeAt(i++);
76
+ enc1 = chr1 >> 2;
77
+ enc2 = ((chr1 & 3) << 4) | (chr2 >> 4);
78
+ enc3 = ((chr2 & 15) << 2) | (chr3 >> 6);
79
+ enc4 = chr3 & 63;
80
+ if (isNaN(chr2)) {
81
+ enc3 = enc4 = 64;
82
+ } else if (isNaN(chr3)) {
83
+ enc4 = 64;
84
+ }
85
+ output =
86
+ output + key.charAt(enc1) + key.charAt(enc2) + key.charAt(enc3) + key.charAt(enc4);
87
+ }
88
+ return output;
89
+ };
90
+ return btoa ? btoa.bind(window) : utils.noop;
91
+ })(),
92
+ isObject: function isObject(obj) {
93
+ return obj && Object.prototype.toString.call(obj) === '[object Object]';
94
+ },
95
+ isEmptyObject: function isEmptyObject(obj) {
96
+ return utils.isObject(obj) && !Object.keys(obj).length;
97
+ },
98
+ isArray: function isArray(arr) {
99
+ return arr && Array.isArray(arr);
100
+ },
101
+ isFunction: function isFunction(func) {
102
+ return func && typeof func === 'function';
103
+ },
104
+ isElement: function isElement(elem) {
105
+ return elem && elem.nodeType === 1;
106
+ },
107
+ isString: function isString(value) {
108
+ return typeof value === 'string' || Object.prototype.toString.call(value) === '[object String]';
109
+ },
110
+ isSupported: {
111
+ canvas: function canvas() {
112
+ const el = document.createElement('canvas');
113
+ return el && el.getContext && el.getContext('2d');
114
+ },
115
+ webworkers: function webworkers() {
116
+ return window.Worker;
117
+ },
118
+ blob: function blob() {
119
+ return utils.Blob;
120
+ },
121
+ Uint8Array: function Uint8Array() {
122
+ return window.Uint8Array;
123
+ },
124
+ Uint32Array: function Uint32Array() {
125
+ return window.Uint32Array;
126
+ },
127
+ videoCodecs: (function () {
128
+ const testEl = document.createElement('video');
129
+ const supportObj = {
130
+ mp4: false,
131
+ h264: false,
132
+ ogv: false,
133
+ ogg: false,
134
+ webm: false
135
+ };
136
+ try {
137
+ if (testEl && testEl.canPlayType) {
138
+ // Check for MPEG-4 support
139
+ supportObj.mp4 = testEl.canPlayType('video/mp4; codecs="mp4v.20.8"') !== '';
140
+ // Check for h264 support
141
+ supportObj.h264 =
142
+ (testEl.canPlayType('video/mp4; codecs="avc1.42E01E"') ||
143
+ testEl.canPlayType('video/mp4; codecs="avc1.42E01E, mp4a.40.2"')) !== '';
144
+ // Check for Ogv support
145
+ supportObj.ogv = testEl.canPlayType('video/ogg; codecs="theora"') !== '';
146
+ // Check for Ogg support
147
+ supportObj.ogg = testEl.canPlayType('video/ogg; codecs="theora"') !== '';
148
+ // Check for Webm support
149
+ supportObj.webm = testEl.canPlayType('video/webm; codecs="vp8, vorbis"') !== -1;
150
+ }
151
+ } catch (e) {}
152
+ return supportObj;
153
+ })()
154
+ },
155
+ noop: function noop() {},
156
+ each: function each(collection, callback) {
157
+ let x = void 0;
158
+ let len = void 0;
159
+ if (utils.isArray(collection)) {
160
+ x = -1;
161
+ len = collection.length;
162
+ while (++x < len) {
163
+ if (callback(x, collection[x]) === false) {
164
+ break;
165
+ }
166
+ }
167
+ } else if (utils.isObject(collection)) {
168
+ for (x in collection) {
169
+ if (collection.hasOwnProperty(x)) {
170
+ if (callback(x, collection[x]) === false) {
171
+ break;
172
+ }
173
+ }
174
+ }
175
+ }
176
+ },
177
+ normalizeOptions: function normalizeOptions(defaultOptions, userOptions) {
178
+ if (!utils.isObject(defaultOptions) || !utils.isObject(userOptions) || !Object.keys) {
179
+ return;
180
+ }
181
+ const newObj = {};
182
+ utils.each(defaultOptions, function (key, val) {
183
+ newObj[key] = defaultOptions[key];
184
+ });
185
+ utils.each(userOptions, function (key, val) {
186
+ const currentUserOption = userOptions[key];
187
+ if (!utils.isObject(currentUserOption)) {
188
+ newObj[key] = currentUserOption;
189
+ } else if (!defaultOptions[key]) {
190
+ newObj[key] = currentUserOption;
191
+ } else {
192
+ newObj[key] = utils.normalizeOptions(defaultOptions[key], currentUserOption);
193
+ }
194
+ });
195
+ return newObj;
196
+ },
197
+ setCSSAttr: function setCSSAttr(elem, attr, val) {
198
+ if (!utils.isElement(elem)) {
199
+ return;
200
+ }
201
+ if (utils.isString(attr) && utils.isString(val)) {
202
+ elem.style[attr] = val;
203
+ } else if (utils.isObject(attr)) {
204
+ utils.each(attr, function (key, val) {
205
+ elem.style[key] = val;
206
+ });
207
+ }
208
+ },
209
+ removeElement: function removeElement(node) {
210
+ if (!utils.isElement(node)) {
211
+ return;
212
+ }
213
+ if (node.parentNode) {
214
+ node.parentNode.removeChild(node);
215
+ }
216
+ },
217
+ createWebWorker: function createWebWorker(content) {
218
+ if (!utils.isString(content)) {
219
+ return {};
220
+ }
221
+ try {
222
+ const blob = new utils.Blob([content], {
223
+ type: 'text/javascript'
224
+ });
225
+ const objectUrl = utils.URL.createObjectURL(blob);
226
+ const worker = new Worker(objectUrl);
227
+ return {
228
+ objectUrl,
229
+ worker
230
+ };
231
+ } catch (e) {
232
+ return `${e}`;
233
+ }
234
+ },
235
+ getExtension: function getExtension(src) {
236
+ return src.substr(src.lastIndexOf('.') + 1, src.length);
237
+ },
238
+ getFontSize: function getFontSize() {
239
+ const options = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
240
+ if (!document.body || options.resizeFont === false) {
241
+ return options.fontSize;
242
+ }
243
+ const text = options.text;
244
+ const containerWidth = options.gifWidth;
245
+ let fontSize = parseInt(options.fontSize, 10);
246
+ const minFontSize = parseInt(options.minFontSize, 10);
247
+ const div = document.createElement('div');
248
+ const span = document.createElement('span');
249
+ div.setAttribute('width', containerWidth);
250
+ div.appendChild(span);
251
+ span.innerHTML = text;
252
+ span.style.fontSize = `${fontSize}px`;
253
+ span.style.textIndent = '-9999px';
254
+ span.style.visibility = 'hidden';
255
+ document.body.appendChild(span);
256
+ while (span.offsetWidth > containerWidth && fontSize >= minFontSize) {
257
+ span.style.fontSize = `${--fontSize}px`;
258
+ }
259
+ document.body.removeChild(span);
260
+ return `${fontSize}px`;
261
+ },
262
+ webWorkerError: false
263
+ };
264
+ const utils$2 = Object.freeze({
265
+ default: utils
266
+ });
267
+ /*
268
+ error.js
269
+ ========
270
+ */
271
+ /* Copyright 2017 Yahoo Inc.
272
+ * Copyrights licensed under the MIT License. See the accompanying LICENSE file for terms.
273
+ */
274
+ // Dependencies
275
+ var error = {
276
+ validate: function validate(skipObj) {
277
+ skipObj = utils.isObject(skipObj) ? skipObj : {};
278
+ let errorObj = {};
279
+ utils.each(error.validators, function (indece, currentValidator) {
280
+ const errorCode = currentValidator.errorCode;
281
+ if (!skipObj[errorCode] && !currentValidator.condition) {
282
+ errorObj = currentValidator;
283
+ errorObj.error = true;
284
+ return false;
285
+ }
286
+ });
287
+ delete errorObj.condition;
288
+ return errorObj;
289
+ },
290
+ isValid: function isValid(skipObj) {
291
+ const errorObj = error.validate(skipObj);
292
+ const isValid = errorObj.error !== true;
293
+ return isValid;
294
+ },
295
+ validators: [
296
+ {
297
+ condition: utils.isFunction(utils.getUserMedia),
298
+ errorCode: 'getUserMedia',
299
+ errorMsg: 'The getUserMedia API is not supported in your browser'
300
+ },
301
+ {
302
+ condition: utils.isSupported.canvas(),
303
+ errorCode: 'canvas',
304
+ errorMsg: 'Canvas elements are not supported in your browser'
305
+ },
306
+ {
307
+ condition: utils.isSupported.webworkers(),
308
+ errorCode: 'webworkers',
309
+ errorMsg: 'The Web Workers API is not supported in your browser'
310
+ },
311
+ {
312
+ condition: utils.isFunction(utils.URL),
313
+ errorCode: 'window.URL',
314
+ errorMsg: 'The window.URL API is not supported in your browser'
315
+ },
316
+ {
317
+ condition: utils.isSupported.blob(),
318
+ errorCode: 'window.Blob',
319
+ errorMsg: 'The window.Blob File API is not supported in your browser'
320
+ },
321
+ {
322
+ condition: utils.isSupported.Uint8Array(),
323
+ errorCode: 'window.Uint8Array',
324
+ errorMsg: 'The window.Uint8Array function constructor is not supported in your browser'
325
+ },
326
+ {
327
+ condition: utils.isSupported.Uint32Array(),
328
+ errorCode: 'window.Uint32Array',
329
+ errorMsg: 'The window.Uint32Array function constructor is not supported in your browser'
330
+ }
331
+ ],
332
+ messages: {
333
+ videoCodecs: {
334
+ errorCode: 'videocodec',
335
+ errorMsg: 'The video codec you are trying to use is not supported in your browser'
336
+ }
337
+ }
338
+ };
339
+ const error$2 = Object.freeze({
340
+ default: error
341
+ });
342
+ /*
343
+ defaultOptions.js
344
+ =================
345
+ */
346
+ /* Copyright 2017 Yahoo Inc.
347
+ * Copyrights licensed under the MIT License. See the accompanying LICENSE file for terms.
348
+ */
349
+ // Helpers
350
+ const noop = function noop() {};
351
+ const defaultOptions = {
352
+ sampleInterval: 10,
353
+ numWorkers: 2,
354
+ filter: '',
355
+ gifWidth: 200,
356
+ gifHeight: 200,
357
+ interval: 0.1,
358
+ numFrames: 10,
359
+ frameDuration: 1,
360
+ keepCameraOn: false,
361
+ images: [],
362
+ video: null,
363
+ webcamVideoElement: null,
364
+ cameraStream: null,
365
+ text: '',
366
+ fontWeight: 'normal',
367
+ fontSize: '16px',
368
+ minFontSize: '10px',
369
+ resizeFont: false,
370
+ fontFamily: 'sans-serif',
371
+ fontColor: '#ffffff',
372
+ textAlign: 'center',
373
+ textBaseline: 'bottom',
374
+ textXCoordinate: null,
375
+ textYCoordinate: null,
376
+ progressCallback: noop,
377
+ completeCallback: noop,
378
+ saveRenderingContexts: false,
379
+ savedRenderingContexts: [],
380
+ crossOrigin: 'Anonymous'
381
+ };
382
+ const defaultOptions$2 = Object.freeze({
383
+ default: defaultOptions
384
+ });
385
+ /*
386
+ isSupported.js
387
+ ==============
388
+ */
389
+ /* Copyright 2017 Yahoo Inc.
390
+ * Copyrights licensed under the MIT License. See the accompanying LICENSE file for terms.
391
+ */
392
+ // Dependencies
393
+ function isSupported() {
394
+ return error.isValid();
395
+ }
396
+ /*
397
+ isWebCamGIFSupported.js
398
+ =======================
399
+ */
400
+ /* Copyright 2017 Yahoo Inc.
401
+ * Copyrights licensed under the MIT License. See the accompanying LICENSE file for terms.
402
+ */
403
+ function isWebCamGIFSupported() {
404
+ return error.isValid();
405
+ }
406
+ /*
407
+ isSupported.js
408
+ ==============
409
+ */
410
+ /* Copyright 2017 Yahoo Inc.
411
+ * Copyrights licensed under the MIT License. See the accompanying LICENSE file for terms.
412
+ */
413
+ // Dependencies
414
+ function isSupported$1() {
415
+ const options = {
416
+ getUserMedia: true
417
+ };
418
+ return error.isValid(options);
419
+ }
420
+ /*
421
+ isExistingVideoGIFSupported.js
422
+ ==============================
423
+ */
424
+ /* Copyright 2017 Yahoo Inc.
425
+ * Copyrights licensed under the MIT License. See the accompanying LICENSE file for terms.
426
+ */
427
+ // Dependencies
428
+ function isExistingVideoGIFSupported(codecs) {
429
+ let hasValidCodec = false;
430
+ if (utils.isArray(codecs) && codecs.length) {
431
+ utils.each(codecs, function (indece, currentCodec) {
432
+ if (utils.isSupported.videoCodecs[currentCodec]) {
433
+ hasValidCodec = true;
434
+ }
435
+ });
436
+ if (!hasValidCodec) {
437
+ return false;
438
+ }
439
+ } else if (utils.isString(codecs) && codecs.length) {
440
+ if (!utils.isSupported.videoCodecs[codecs]) {
441
+ return false;
442
+ }
443
+ }
444
+ return error.isValid({
445
+ getUserMedia: true
446
+ });
447
+ }
448
+ /*
449
+ NeuQuant.js
450
+ ===========
451
+ */
452
+ /*
453
+ * NeuQuant Neural-Net Quantization Algorithm
454
+ * ------------------------------------------
455
+ *
456
+ * Copyright (c) 1994 Anthony Dekker
457
+ *
458
+ * NEUQUANT Neural-Net quantization algorithm by Anthony Dekker, 1994. See
459
+ * "Kohonen neural networks for optimal colour quantization" in "Network:
460
+ * Computation in Neural Systems" Vol. 5 (1994) pp 351-367. for a discussion of
461
+ * the algorithm.
462
+ *
463
+ * Any party obtaining a copy of these files from the author, directly or
464
+ * indirectly, is granted, free of charge, a full and unrestricted irrevocable,
465
+ * world-wide, paid up, royalty-free, nonexclusive right and license to deal in
466
+ * this software and documentation files (the "Software"), including without
467
+ * limitation the rights to use, copy, modify, merge, publish, distribute,
468
+ * sublicense, and/or sell copies of the Software, and to permit persons who
469
+ * receive copies from any such party to do so, with the only requirement being
470
+ * that this copyright notice remain intact.
471
+ */
472
+ /*
473
+ * This class handles Neural-Net quantization algorithm
474
+ * @author Kevin Weiner (original Java version - kweiner@fmsware.com)
475
+ * @author Thibault Imbert (AS3 version - bytearray.org)
476
+ * @version 0.1 AS3 implementation
477
+ * @version 0.2 JS->AS3 "translation" by antimatter15
478
+ * @version 0.3 JS clean up + using modern JS idioms by sole - http://soledadpenades.com
479
+ * Also implement fix in color conversion described at http://stackoverflow.com/questions/16371712/neuquant-js-javascript-color-quantization-hidden-bug-in-js-conversion
480
+ */
481
+ function NeuQuant() {
482
+ const netsize = 256; // number of colours used
483
+ // four primes near 500 - assume no image has a length so large
484
+ // that it is divisible by all four primes
485
+ const prime1 = 499;
486
+ const prime2 = 491;
487
+ const prime3 = 487;
488
+ const prime4 = 503;
489
+ // minimum size for input image
490
+ const minpicturebytes = 3 * prime4;
491
+ // Network Definitions
492
+ const maxnetpos = netsize - 1;
493
+ const netbiasshift = 4; // bias for colour values
494
+ const ncycles = 100; // no. of learning cycles
495
+ // defs for freq and bias
496
+ const intbiasshift = 16; // bias for fractions
497
+ const intbias = 1 << intbiasshift;
498
+ const gammashift = 10; // gamma = 1024
499
+ const gamma = 1 << gammashift;
500
+ const betashift = 10;
501
+ const beta = intbias >> betashift; // beta = 1/1024
502
+ const betagamma = intbias << (gammashift - betashift);
503
+ // defs for decreasing radius factor
504
+ // For 256 colors, radius starts at 32.0 biased by 6 bits
505
+ // and decreases by a factor of 1/30 each cycle
506
+ const initrad = netsize >> 3;
507
+ const radiusbiasshift = 6;
508
+ const radiusbias = 1 << radiusbiasshift;
509
+ const initradius = initrad * radiusbias;
510
+ const radiusdec = 30;
511
+ // defs for decreasing alpha factor
512
+ // Alpha starts at 1.0 biased by 10 bits
513
+ const alphabiasshift = 10;
514
+ const initalpha = 1 << alphabiasshift;
515
+ let alphadec;
516
+ // radbias and alpharadbias used for radpower calculation
517
+ const radbiasshift = 8;
518
+ const radbias = 1 << radbiasshift;
519
+ const alpharadbshift = alphabiasshift + radbiasshift;
520
+ const alpharadbias = 1 << alpharadbshift;
521
+ // Input image
522
+ let thepicture;
523
+ // Height * Width * 3
524
+ let lengthcount;
525
+ // Sampling factor 1..30
526
+ let samplefac;
527
+ // The network itself
528
+ let network;
529
+ const netindex = [];
530
+ // for network lookup - really 256
531
+ const bias = [];
532
+ // bias and freq arrays for learning
533
+ const freq = [];
534
+ const radpower = [];
535
+ function NeuQuantConstructor(thepic, len, sample) {
536
+ let i;
537
+ let p;
538
+ thepicture = thepic;
539
+ lengthcount = len;
540
+ samplefac = sample;
541
+ network = new Array(netsize);
542
+ for (i = 0; i < netsize; i++) {
543
+ network[i] = new Array(4);
544
+ p = network[i];
545
+ p[0] = p[1] = p[2] = ((i << (netbiasshift + 8)) / netsize) | 0;
546
+ freq[i] = (intbias / netsize) | 0; // 1 / netsize
547
+ bias[i] = 0;
548
+ }
549
+ }
550
+ function colorMap() {
551
+ const map = [];
552
+ const index = new Array(netsize);
553
+ for (let i = 0; i < netsize; i++) {
554
+ index[network[i][3]] = i;
555
+ }
556
+ let k = 0;
557
+ for (let l = 0; l < netsize; l++) {
558
+ const j = index[l];
559
+ map[k++] = network[j][0];
560
+ map[k++] = network[j][1];
561
+ map[k++] = network[j][2];
562
+ }
563
+ return map;
564
+ }
565
+ // Insertion sort of network and building of netindex[0..255]
566
+ // (to do after unbias)
567
+ function inxbuild() {
568
+ let i;
569
+ let j;
570
+ let smallpos;
571
+ let smallval;
572
+ let p;
573
+ let q;
574
+ let previouscol;
575
+ let startpos;
576
+ previouscol = 0;
577
+ startpos = 0;
578
+ for (i = 0; i < netsize; i++) {
579
+ p = network[i];
580
+ smallpos = i;
581
+ smallval = p[1]; // index on g
582
+ // find smallest in i..netsize-1
583
+ for (j = i + 1; j < netsize; j++) {
584
+ q = network[j];
585
+ if (q[1] < smallval) {
586
+ // index on g
587
+ smallpos = j;
588
+ smallval = q[1]; // index on g
589
+ }
590
+ }
591
+ q = network[smallpos];
592
+ // swap p (i) and q (smallpos) entries
593
+ if (i != smallpos) {
594
+ j = q[0];
595
+ q[0] = p[0];
596
+ p[0] = j;
597
+ j = q[1];
598
+ q[1] = p[1];
599
+ p[1] = j;
600
+ j = q[2];
601
+ q[2] = p[2];
602
+ p[2] = j;
603
+ j = q[3];
604
+ q[3] = p[3];
605
+ p[3] = j;
606
+ }
607
+ // smallval entry is now in position i
608
+ if (smallval != previouscol) {
609
+ netindex[previouscol] = (startpos + i) >> 1;
610
+ for (j = previouscol + 1; j < smallval; j++) {
611
+ netindex[j] = i;
612
+ }
613
+ previouscol = smallval;
614
+ startpos = i;
615
+ }
616
+ }
617
+ netindex[previouscol] = (startpos + maxnetpos) >> 1;
618
+ for (j = previouscol + 1; j < 256; j++) {
619
+ netindex[j] = maxnetpos; // really 256
620
+ }
621
+ }
622
+ // Main Learning Loop
623
+ function learn() {
624
+ let i;
625
+ let j;
626
+ let b;
627
+ let g;
628
+ let r;
629
+ let radius;
630
+ let rad;
631
+ let alpha;
632
+ let step;
633
+ let delta;
634
+ let samplepixels;
635
+ let p;
636
+ let pix;
637
+ let lim;
638
+ if (lengthcount < minpicturebytes) {
639
+ samplefac = 1;
640
+ }
641
+ alphadec = 30 + (samplefac - 1) / 3;
642
+ p = thepicture;
643
+ pix = 0;
644
+ lim = lengthcount;
645
+ samplepixels = lengthcount / (3 * samplefac);
646
+ delta = (samplepixels / ncycles) | 0;
647
+ alpha = initalpha;
648
+ radius = initradius;
649
+ rad = radius >> radiusbiasshift;
650
+ if (rad <= 1) {
651
+ rad = 0;
652
+ }
653
+ for (i = 0; i < rad; i++) {
654
+ radpower[i] = alpha * (((rad * rad - i * i) * radbias) / (rad * rad));
655
+ }
656
+ if (lengthcount < minpicturebytes) {
657
+ step = 3;
658
+ } else if (lengthcount % prime1 !== 0) {
659
+ step = 3 * prime1;
660
+ } else if (lengthcount % prime2 !== 0) {
661
+ step = 3 * prime2;
662
+ } else if (lengthcount % prime3 !== 0) {
663
+ step = 3 * prime3;
664
+ } else {
665
+ step = 3 * prime4;
666
+ }
667
+ i = 0;
668
+ while (i < samplepixels) {
669
+ b = (p[pix + 0] & 0xff) << netbiasshift;
670
+ g = (p[pix + 1] & 0xff) << netbiasshift;
671
+ r = (p[pix + 2] & 0xff) << netbiasshift;
672
+ j = contest(b, g, r);
673
+ altersingle(alpha, j, b, g, r);
674
+ if (rad !== 0) {
675
+ // Alter neighbours
676
+ alterneigh(rad, j, b, g, r);
677
+ }
678
+ pix += step;
679
+ if (pix >= lim) {
680
+ pix -= lengthcount;
681
+ }
682
+ i++;
683
+ if (delta === 0) {
684
+ delta = 1;
685
+ }
686
+ if (i % delta === 0) {
687
+ alpha -= alpha / alphadec;
688
+ radius -= radius / radiusdec;
689
+ rad = radius >> radiusbiasshift;
690
+ if (rad <= 1) {
691
+ rad = 0;
692
+ }
693
+ for (j = 0; j < rad; j++) {
694
+ radpower[j] = alpha * (((rad * rad - j * j) * radbias) / (rad * rad));
695
+ }
696
+ }
697
+ }
698
+ }
699
+ // Search for BGR values 0..255 (after net is unbiased) and return colour index
700
+ function map(b, g, r) {
701
+ let i;
702
+ let j;
703
+ let dist;
704
+ let a;
705
+ let bestd;
706
+ let p;
707
+ let best;
708
+ // Biggest possible distance is 256 * 3
709
+ bestd = 1000;
710
+ best = -1;
711
+ i = netindex[g]; // index on g
712
+ j = i - 1; // start at netindex[g] and work outwards
713
+ while (i < netsize || j >= 0) {
714
+ if (i < netsize) {
715
+ p = network[i];
716
+ dist = p[1] - g; // inx key
717
+ if (dist >= bestd) {
718
+ i = netsize; // stop iter
719
+ } else {
720
+ i++;
721
+ if (dist < 0) {
722
+ dist = -dist;
723
+ }
724
+ a = p[0] - b;
725
+ if (a < 0) {
726
+ a = -a;
727
+ }
728
+ dist += a;
729
+ if (dist < bestd) {
730
+ a = p[2] - r;
731
+ if (a < 0) {
732
+ a = -a;
733
+ }
734
+ dist += a;
735
+ if (dist < bestd) {
736
+ bestd = dist;
737
+ best = p[3];
738
+ }
739
+ }
740
+ }
741
+ }
742
+ if (j >= 0) {
743
+ p = network[j];
744
+ dist = g - p[1]; // inx key - reverse dif
745
+ if (dist >= bestd) {
746
+ j = -1; // stop iter
747
+ } else {
748
+ j--;
749
+ if (dist < 0) {
750
+ dist = -dist;
751
+ }
752
+ a = p[0] - b;
753
+ if (a < 0) {
754
+ a = -a;
755
+ }
756
+ dist += a;
757
+ if (dist < bestd) {
758
+ a = p[2] - r;
759
+ if (a < 0) {
760
+ a = -a;
761
+ }
762
+ dist += a;
763
+ if (dist < bestd) {
764
+ bestd = dist;
765
+ best = p[3];
766
+ }
767
+ }
768
+ }
769
+ }
770
+ }
771
+ return best;
772
+ }
773
+ function process() {
774
+ learn();
775
+ unbiasnet();
776
+ inxbuild();
777
+ return colorMap();
778
+ }
779
+ // Unbias network to give byte values 0..255 and record position i
780
+ // to prepare for sort
781
+ function unbiasnet() {
782
+ let i;
783
+ let j;
784
+ for (i = 0; i < netsize; i++) {
785
+ network[i][0] >>= netbiasshift;
786
+ network[i][1] >>= netbiasshift;
787
+ network[i][2] >>= netbiasshift;
788
+ network[i][3] = i; // record colour no
789
+ }
790
+ }
791
+ // Move adjacent neurons by precomputed alpha*(1-((i-j)^2/[r]^2))
792
+ // in radpower[|i-j|]
793
+ function alterneigh(rad, i, b, g, r) {
794
+ let j;
795
+ let k;
796
+ let lo;
797
+ let hi;
798
+ let a;
799
+ let m;
800
+ let p;
801
+ lo = i - rad;
802
+ if (lo < -1) {
803
+ lo = -1;
804
+ }
805
+ hi = i + rad;
806
+ if (hi > netsize) {
807
+ hi = netsize;
808
+ }
809
+ j = i + 1;
810
+ k = i - 1;
811
+ m = 1;
812
+ while (j < hi || k > lo) {
813
+ a = radpower[m++];
814
+ if (j < hi) {
815
+ p = network[j++];
816
+ try {
817
+ p[0] -= ((a * (p[0] - b)) / alpharadbias) | 0;
818
+ p[1] -= ((a * (p[1] - g)) / alpharadbias) | 0;
819
+ p[2] -= ((a * (p[2] - r)) / alpharadbias) | 0;
820
+ } catch (e) {}
821
+ }
822
+ if (k > lo) {
823
+ p = network[k--];
824
+ try {
825
+ p[0] -= ((a * (p[0] - b)) / alpharadbias) | 0;
826
+ p[1] -= ((a * (p[1] - g)) / alpharadbias) | 0;
827
+ p[2] -= ((a * (p[2] - r)) / alpharadbias) | 0;
828
+ } catch (e) {}
829
+ }
830
+ }
831
+ }
832
+ // Move neuron i towards biased (b,g,r) by factor alpha
833
+ function altersingle(alpha, i, b, g, r) {
834
+ // alter hit neuron
835
+ const n = network[i];
836
+ const alphaMult = alpha / initalpha;
837
+ n[0] -= (alphaMult * (n[0] - b)) | 0;
838
+ n[1] -= (alphaMult * (n[1] - g)) | 0;
839
+ n[2] -= (alphaMult * (n[2] - r)) | 0;
840
+ }
841
+ // Search for biased BGR values
842
+ function contest(b, g, r) {
843
+ // finds closest neuron (min dist) and updates freq
844
+ // finds best neuron (min dist-bias) and returns position
845
+ // for frequently chosen neurons, freq[i] is high and bias[i] is negative
846
+ // bias[i] = gamma*((1/netsize)-freq[i])
847
+ let i;
848
+ let dist;
849
+ let a;
850
+ let biasdist;
851
+ let betafreq;
852
+ let bestpos;
853
+ let bestbiaspos;
854
+ let bestd;
855
+ let bestbiasd;
856
+ let n;
857
+ bestd = ~(1 << 31);
858
+ bestbiasd = bestd;
859
+ bestpos = -1;
860
+ bestbiaspos = bestpos;
861
+ for (i = 0; i < netsize; i++) {
862
+ n = network[i];
863
+ dist = n[0] - b;
864
+ if (dist < 0) {
865
+ dist = -dist;
866
+ }
867
+ a = n[1] - g;
868
+ if (a < 0) {
869
+ a = -a;
870
+ }
871
+ dist += a;
872
+ a = n[2] - r;
873
+ if (a < 0) {
874
+ a = -a;
875
+ }
876
+ dist += a;
877
+ if (dist < bestd) {
878
+ bestd = dist;
879
+ bestpos = i;
880
+ }
881
+ biasdist = dist - (bias[i] >> (intbiasshift - netbiasshift));
882
+ if (biasdist < bestbiasd) {
883
+ bestbiasd = biasdist;
884
+ bestbiaspos = i;
885
+ }
886
+ betafreq = freq[i] >> betashift;
887
+ freq[i] -= betafreq;
888
+ bias[i] += betafreq << gammashift;
889
+ }
890
+ freq[bestpos] += beta;
891
+ bias[bestpos] -= betagamma;
892
+ return bestbiaspos;
893
+ }
894
+ NeuQuantConstructor.apply(this, arguments);
895
+ const exports = {};
896
+ exports.map = map;
897
+ exports.process = process;
898
+ return exports;
899
+ }
900
+ /*
901
+ processFrameWorker.js
902
+ =====================
903
+ */
904
+ /* Copyright 2017 Yahoo Inc.
905
+ * Copyrights licensed under the MIT License. See the accompanying LICENSE file for terms.
906
+ */
907
+ function workerCode() {
908
+ const self = this;
909
+ try {
910
+ self.onmessage = function (ev) {
911
+ const data = ev.data || {};
912
+ let response;
913
+ if (data.gifshot) {
914
+ response = workerMethods.run(data);
915
+ postMessage(response);
916
+ }
917
+ };
918
+ } catch (e) {}
919
+ var workerMethods = {
920
+ dataToRGB: function dataToRGB(data, width, height) {
921
+ const length = width * height * 4;
922
+ let i = 0;
923
+ const rgb = [];
924
+ while (i < length) {
925
+ rgb.push(data[i++]);
926
+ rgb.push(data[i++]);
927
+ rgb.push(data[i++]);
928
+ i++; // for the alpha channel which we don't care about
929
+ }
930
+ return rgb;
931
+ },
932
+ componentizedPaletteToArray: function componentizedPaletteToArray(paletteRGB) {
933
+ paletteRGB = paletteRGB || [];
934
+ const paletteArray = [];
935
+ for (let i = 0; i < paletteRGB.length; i += 3) {
936
+ const r = paletteRGB[i];
937
+ const g = paletteRGB[i + 1];
938
+ const b = paletteRGB[i + 2];
939
+ paletteArray.push((r << 16) | (g << 8) | b);
940
+ }
941
+ return paletteArray;
942
+ },
943
+ // This is the "traditional" Animated_GIF style of going from RGBA to indexed color frames
944
+ processFrameWithQuantizer: function processFrameWithQuantizer(
945
+ imageData,
946
+ width,
947
+ height,
948
+ sampleInterval
949
+ ) {
950
+ const rgbComponents = this.dataToRGB(imageData, width, height);
951
+ const nq = new NeuQuant(rgbComponents, rgbComponents.length, sampleInterval);
952
+ const paletteRGB = nq.process();
953
+ const paletteArray = new Uint32Array(this.componentizedPaletteToArray(paletteRGB));
954
+ const numberPixels = width * height;
955
+ const indexedPixels = new Uint8Array(numberPixels);
956
+ let k = 0;
957
+ for (let i = 0; i < numberPixels; i++) {
958
+ const r = rgbComponents[k++];
959
+ const g = rgbComponents[k++];
960
+ const b = rgbComponents[k++];
961
+ indexedPixels[i] = nq.map(r, g, b);
962
+ }
963
+ return {
964
+ pixels: indexedPixels,
965
+ palette: paletteArray
966
+ };
967
+ },
968
+ run: function run(frame) {
969
+ frame = frame || {};
970
+ const _frame = frame;
971
+ const height = _frame.height;
972
+ const palette = _frame.palette;
973
+ const sampleInterval = _frame.sampleInterval;
974
+ const width = _frame.width;
975
+ const imageData = frame.data;
976
+ return this.processFrameWithQuantizer(imageData, width, height, sampleInterval);
977
+ }
978
+ };
979
+ return workerMethods;
980
+ }
981
+ /*
982
+ gifWriter.js
983
+ ============
984
+ */
985
+ // (c) Dean McNamee <dean@gmail.com>, 2013.
986
+ //
987
+ // https://github.com/deanm/omggif
988
+ //
989
+ // Permission is hereby granted, free of charge, to any person obtaining a copy
990
+ // of this software and associated documentation files (the "Software"), to
991
+ // deal in the Software without restriction, including without limitation the
992
+ // rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
993
+ // sell copies of the Software, and to permit persons to whom the Software is
994
+ // furnished to do so, subject to the following conditions:
995
+ //
996
+ // The above copyright notice and this permission notice shall be included in
997
+ // all copies or substantial portions of the Software.
998
+ //
999
+ // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
1000
+ // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
1001
+ // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
1002
+ // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
1003
+ // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
1004
+ // FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
1005
+ // IN THE SOFTWARE.
1006
+ //
1007
+ // omggif is a JavaScript implementation of a GIF 89a encoder and decoder,
1008
+ // including animation and compression. It does not rely on any specific
1009
+ // underlying system, so should run in the browser, Node, or Plask.
1010
+ function gifWriter(buf, width, height, gopts) {
1011
+ let p = 0;
1012
+ gopts = gopts === undefined ? {} : gopts;
1013
+ const loop_count = gopts.loop === undefined ? null : gopts.loop;
1014
+ const global_palette = gopts.palette === undefined ? null : gopts.palette;
1015
+ if (width <= 0 || height <= 0 || width > 65535 || height > 65535) throw 'Width/Height invalid.';
1016
+ function check_palette_and_num_colors(palette) {
1017
+ const num_colors = palette.length;
1018
+ if (num_colors < 2 || num_colors > 256 || num_colors & (num_colors - 1))
1019
+ throw 'Invalid code/color length, must be power of 2 and 2 .. 256.';
1020
+ return num_colors;
1021
+ }
1022
+ // - Header.
1023
+ buf[p++] = 0x47;
1024
+ buf[p++] = 0x49;
1025
+ buf[p++] = 0x46; // GIF
1026
+ buf[p++] = 0x38;
1027
+ buf[p++] = 0x39;
1028
+ buf[p++] = 0x61; // 89a
1029
+ // Handling of Global Color Table (palette) and background index.
1030
+ const gp_num_colors_pow2 = 0;
1031
+ const background = 0;
1032
+ // - Logical Screen Descriptor.
1033
+ // NOTE(deanm): w/h apparently ignored by implementations, but set anyway.
1034
+ buf[p++] = width & 0xff;
1035
+ buf[p++] = (width >> 8) & 0xff;
1036
+ buf[p++] = height & 0xff;
1037
+ buf[p++] = (height >> 8) & 0xff;
1038
+ // NOTE: Indicates 0-bpp original color resolution (unused?).
1039
+ buf[p++] =
1040
+ (global_palette !== null ? 0x80 : 0) | // Global Color Table Flag.
1041
+ gp_num_colors_pow2; // NOTE: No sort flag (unused?).
1042
+ buf[p++] = background; // Background Color Index.
1043
+ buf[p++] = 0; // Pixel aspect ratio (unused?).
1044
+ if (loop_count !== null) {
1045
+ // Netscape block for looping.
1046
+ if (loop_count < 0 || loop_count > 65535) throw 'Loop count invalid.';
1047
+ // Extension code, label, and length.
1048
+ buf[p++] = 0x21;
1049
+ buf[p++] = 0xff;
1050
+ buf[p++] = 0x0b;
1051
+ // NETSCAPE2.0
1052
+ buf[p++] = 0x4e;
1053
+ buf[p++] = 0x45;
1054
+ buf[p++] = 0x54;
1055
+ buf[p++] = 0x53;
1056
+ buf[p++] = 0x43;
1057
+ buf[p++] = 0x41;
1058
+ buf[p++] = 0x50;
1059
+ buf[p++] = 0x45;
1060
+ buf[p++] = 0x32;
1061
+ buf[p++] = 0x2e;
1062
+ buf[p++] = 0x30;
1063
+ // Sub-block
1064
+ buf[p++] = 0x03;
1065
+ buf[p++] = 0x01;
1066
+ buf[p++] = loop_count & 0xff;
1067
+ buf[p++] = (loop_count >> 8) & 0xff;
1068
+ buf[p++] = 0x00; // Terminator.
1069
+ }
1070
+ let ended = false;
1071
+ this.addFrame = function (x, y, w, h, indexed_pixels, opts) {
1072
+ if (ended === true) {
1073
+ --p;
1074
+ ended = false;
1075
+ } // Un-end.
1076
+ opts = opts === undefined ? {} : opts;
1077
+ // TODO(deanm): Bounds check x, y. Do they need to be within the virtual
1078
+ // canvas width/height, I imagine?
1079
+ if (x < 0 || y < 0 || x > 65535 || y > 65535) throw 'x/y invalid.';
1080
+ if (w <= 0 || h <= 0 || w > 65535 || h > 65535) throw 'Width/Height invalid.';
1081
+ if (indexed_pixels.length < w * h) throw 'Not enough pixels for the frame size.';
1082
+ let using_local_palette = true;
1083
+ let palette = opts.palette;
1084
+ if (palette === undefined || palette === null) {
1085
+ using_local_palette = false;
1086
+ palette = global_palette;
1087
+ }
1088
+ if (palette === undefined || palette === null)
1089
+ throw 'Must supply either a local or global palette.';
1090
+ let num_colors = check_palette_and_num_colors(palette);
1091
+ // Compute the min_code_size (power of 2), destroying num_colors.
1092
+ let min_code_size = 0;
1093
+ while ((num_colors >>= 1)) {
1094
+ ++min_code_size;
1095
+ }
1096
+ num_colors = 1 << min_code_size; // Now we can easily get it back.
1097
+ const delay = opts.delay === undefined ? 0 : opts.delay;
1098
+ // From the spec:
1099
+ // 0 - No disposal specified. The decoder is
1100
+ // not required to take any action.
1101
+ // 1 - Do not dispose. The graphic is to be left
1102
+ // in place.
1103
+ // 2 - Restore to background color. The area used by the
1104
+ // graphic must be restored to the background color.
1105
+ // 3 - Restore to previous. The decoder is required to
1106
+ // restore the area overwritten by the graphic with
1107
+ // what was there prior to rendering the graphic.
1108
+ // 4-7 - To be defined.
1109
+ // NOTE(deanm): Dispose background doesn't really work, apparently most
1110
+ // browsers ignore the background palette index and clear to transparency.
1111
+ const disposal = opts.disposal === undefined ? 0 : opts.disposal;
1112
+ if (disposal < 0 || disposal > 3)
1113
+ // 4-7 is reserved.
1114
+ throw 'Disposal out of range.';
1115
+ let use_transparency = false;
1116
+ let transparent_index = 0;
1117
+ if (opts.transparent !== undefined && opts.transparent !== null) {
1118
+ use_transparency = true;
1119
+ transparent_index = opts.transparent;
1120
+ if (transparent_index < 0 || transparent_index >= num_colors)
1121
+ throw 'Transparent color index.';
1122
+ }
1123
+ if (disposal !== 0 || use_transparency || delay !== 0) {
1124
+ // - Graphics Control Extension
1125
+ buf[p++] = 0x21;
1126
+ buf[p++] = 0xf9; // Extension / Label.
1127
+ buf[p++] = 4; // Byte size.
1128
+ buf[p++] = (disposal << 2) | (use_transparency === true ? 1 : 0);
1129
+ buf[p++] = delay & 0xff;
1130
+ buf[p++] = (delay >> 8) & 0xff;
1131
+ buf[p++] = transparent_index; // Transparent color index.
1132
+ buf[p++] = 0; // Block Terminator.
1133
+ }
1134
+ // - Image Descriptor
1135
+ buf[p++] = 0x2c; // Image Seperator.
1136
+ buf[p++] = x & 0xff;
1137
+ buf[p++] = (x >> 8) & 0xff; // Left.
1138
+ buf[p++] = y & 0xff;
1139
+ buf[p++] = (y >> 8) & 0xff; // Top.
1140
+ buf[p++] = w & 0xff;
1141
+ buf[p++] = (w >> 8) & 0xff;
1142
+ buf[p++] = h & 0xff;
1143
+ buf[p++] = (h >> 8) & 0xff;
1144
+ // NOTE: No sort flag (unused?).
1145
+ // TODO(deanm): Support interlace.
1146
+ buf[p++] = using_local_palette === true ? 0x80 | (min_code_size - 1) : 0;
1147
+ // - Local Color Table
1148
+ if (using_local_palette === true) {
1149
+ for (let i = 0, il = palette.length; i < il; ++i) {
1150
+ const rgb = palette[i];
1151
+ buf[p++] = (rgb >> 16) & 0xff;
1152
+ buf[p++] = (rgb >> 8) & 0xff;
1153
+ buf[p++] = rgb & 0xff;
1154
+ }
1155
+ }
1156
+ p = GifWriterOutputLZWCodeStream(buf, p, min_code_size < 2 ? 2 : min_code_size, indexed_pixels);
1157
+ };
1158
+ this.end = function () {
1159
+ if (ended === false) {
1160
+ buf[p++] = 0x3b; // Trailer.
1161
+ ended = true;
1162
+ }
1163
+ return p;
1164
+ };
1165
+ // Main compression routine, palette indexes -> LZW code stream.
1166
+ // |index_stream| must have at least one entry.
1167
+ function GifWriterOutputLZWCodeStream(buf, p, min_code_size, index_stream) {
1168
+ buf[p++] = min_code_size;
1169
+ let cur_subblock = p++; // Pointing at the length field.
1170
+ const clear_code = 1 << min_code_size;
1171
+ const code_mask = clear_code - 1;
1172
+ const eoi_code = clear_code + 1;
1173
+ let next_code = eoi_code + 1;
1174
+ let cur_code_size = min_code_size + 1; // Number of bits per code.
1175
+ let cur_shift = 0;
1176
+ // We have at most 12-bit codes, so we should have to hold a max of 19
1177
+ // bits here (and then we would write out).
1178
+ let cur = 0;
1179
+ function emit_bytes_to_buffer(bit_block_size) {
1180
+ while (cur_shift >= bit_block_size) {
1181
+ buf[p++] = cur & 0xff;
1182
+ cur >>= 8;
1183
+ cur_shift -= 8;
1184
+ if (p === cur_subblock + 256) {
1185
+ // Finished a subblock.
1186
+ buf[cur_subblock] = 255;
1187
+ cur_subblock = p++;
1188
+ }
1189
+ }
1190
+ }
1191
+ function emit_code(c) {
1192
+ cur |= c << cur_shift;
1193
+ cur_shift += cur_code_size;
1194
+ emit_bytes_to_buffer(8);
1195
+ }
1196
+ // I am not an expert on the topic, and I don't want to write a thesis.
1197
+ // However, it is good to outline here the basic algorithm and the few data
1198
+ // structures and optimizations here that make this implementation fast.
1199
+ // The basic idea behind LZW is to build a table of previously seen runs
1200
+ // addressed by a short id (herein called output code). All data is
1201
+ // referenced by a code, which represents one or more values from the
1202
+ // original input stream. All input bytes can be referenced as the same
1203
+ // value as an output code. So if you didn't want any compression, you
1204
+ // could more or less just output the original bytes as codes (there are
1205
+ // some details to this, but it is the idea). In order to achieve
1206
+ // compression, values greater then the input range (codes can be up to
1207
+ // 12-bit while input only 8-bit) represent a sequence of previously seen
1208
+ // inputs. The decompressor is able to build the same mapping while
1209
+ // decoding, so there is always a shared common knowledge between the
1210
+ // encoding and decoder, which is also important for "timing" aspects like
1211
+ // how to handle variable bit width code encoding.
1212
+ //
1213
+ // One obvious but very important consequence of the table system is there
1214
+ // is always a unique id (at most 12-bits) to map the runs. 'A' might be
1215
+ // 4, then 'AA' might be 10, 'AAA' 11, 'AAAA' 12, etc. This relationship
1216
+ // can be used for an effecient lookup strategy for the code mapping. We
1217
+ // need to know if a run has been seen before, and be able to map that run
1218
+ // to the output code. Since we start with known unique ids (input bytes),
1219
+ // and then from those build more unique ids (table entries), we can
1220
+ // continue this chain (almost like a linked list) to always have small
1221
+ // integer values that represent the current byte chains in the encoder.
1222
+ // This means instead of tracking the input bytes (AAAABCD) to know our
1223
+ // current state, we can track the table entry for AAAABC (it is guaranteed
1224
+ // to exist by the nature of the algorithm) and the next character D.
1225
+ // Therefor the tuple of (table_entry, byte) is guaranteed to also be
1226
+ // unique. This allows us to create a simple lookup key for mapping input
1227
+ // sequences to codes (table indices) without having to store or search
1228
+ // any of the code sequences. So if 'AAAA' has a table entry of 12, the
1229
+ // tuple of ('AAAA', K) for any input byte K will be unique, and can be our
1230
+ // key. This leads to a integer value at most 20-bits, which can always
1231
+ // fit in an SMI value and be used as a fast sparse array / object key.
1232
+ // Output code for the current contents of the index buffer.
1233
+ let ib_code = index_stream[0] & code_mask; // Load first input index.
1234
+ let code_table = {}; // Key'd on our 20-bit "tuple".
1235
+ emit_code(clear_code); // Spec says first code should be a clear code.
1236
+ // First index already loaded, process the rest of the stream.
1237
+ for (let i = 1, il = index_stream.length; i < il; ++i) {
1238
+ const k = index_stream[i] & code_mask;
1239
+ const cur_key = (ib_code << 8) | k; // (prev, k) unique tuple.
1240
+ const cur_code = code_table[cur_key]; // buffer + k.
1241
+ // Check if we have to create a new code table entry.
1242
+ if (cur_code === undefined) {
1243
+ // We don't have buffer + k.
1244
+ // Emit index buffer (without k).
1245
+ // This is an inline version of emit_code, because this is the core
1246
+ // writing routine of the compressor (and V8 cannot inline emit_code
1247
+ // because it is a closure here in a different context). Additionally
1248
+ // we can call emit_byte_to_buffer less often, because we can have
1249
+ // 30-bits (from our 31-bit signed SMI), and we know our codes will only
1250
+ // be 12-bits, so can safely have 18-bits there without overflow.
1251
+ // emit_code(ib_code);
1252
+ cur |= ib_code << cur_shift;
1253
+ cur_shift += cur_code_size;
1254
+ while (cur_shift >= 8) {
1255
+ buf[p++] = cur & 0xff;
1256
+ cur >>= 8;
1257
+ cur_shift -= 8;
1258
+ if (p === cur_subblock + 256) {
1259
+ // Finished a subblock.
1260
+ buf[cur_subblock] = 255;
1261
+ cur_subblock = p++;
1262
+ }
1263
+ }
1264
+ if (next_code === 4096) {
1265
+ // Table full, need a clear.
1266
+ emit_code(clear_code);
1267
+ next_code = eoi_code + 1;
1268
+ cur_code_size = min_code_size + 1;
1269
+ code_table = {};
1270
+ } else {
1271
+ // Table not full, insert a new entry.
1272
+ // Increase our variable bit code sizes if necessary. This is a bit
1273
+ // tricky as it is based on "timing" between the encoding and
1274
+ // decoder. From the encoders perspective this should happen after
1275
+ // we've already emitted the index buffer and are about to create the
1276
+ // first table entry that would overflow our current code bit size.
1277
+ if (next_code >= 1 << cur_code_size) ++cur_code_size;
1278
+ code_table[cur_key] = next_code++; // Insert into code table.
1279
+ }
1280
+ ib_code = k; // Index buffer to single input k.
1281
+ } else {
1282
+ ib_code = cur_code; // Index buffer to sequence in code table.
1283
+ }
1284
+ }
1285
+ emit_code(ib_code); // There will still be something in the index buffer.
1286
+ emit_code(eoi_code); // End Of Information.
1287
+ // Flush / finalize the sub-blocks stream to the buffer.
1288
+ emit_bytes_to_buffer(1);
1289
+ // Finish the sub-blocks, writing out any unfinished lengths and
1290
+ // terminating with a sub-block of length 0. If we have already started
1291
+ // but not yet used a sub-block it can just become the terminator.
1292
+ if (cur_subblock + 1 === p) {
1293
+ // Started but unused.
1294
+ buf[cur_subblock] = 0;
1295
+ } else {
1296
+ // Started and used, write length and additional terminator block.
1297
+ buf[cur_subblock] = p - cur_subblock - 1;
1298
+ buf[p++] = 0;
1299
+ }
1300
+ return p;
1301
+ }
1302
+ }
1303
+ /*
1304
+ animatedGIF.js
1305
+ ==============
1306
+ */
1307
+ /* Copyright 2017 Yahoo Inc.
1308
+ * Copyrights licensed under the MIT License. See the accompanying LICENSE file for terms.
1309
+ */
1310
+ // Dependencies
1311
+ // Helpers
1312
+ const noop$2 = function noop() {};
1313
+ const AnimatedGIF = function AnimatedGIF(options) {
1314
+ this.canvas = null;
1315
+ this.ctx = null;
1316
+ this.repeat = 0;
1317
+ this.frames = [];
1318
+ this.numRenderedFrames = 0;
1319
+ this.onRenderCompleteCallback = noop$2;
1320
+ this.onRenderProgressCallback = noop$2;
1321
+ this.workers = [];
1322
+ this.availableWorkers = [];
1323
+ this.generatingGIF = false;
1324
+ this.options = options;
1325
+ // Constructs and initializes the the web workers appropriately
1326
+ this.initializeWebWorkers(options);
1327
+ };
1328
+ AnimatedGIF.prototype = {
1329
+ workerMethods: workerCode(),
1330
+ initializeWebWorkers: function initializeWebWorkers(options) {
1331
+ const self = this;
1332
+ const processFrameWorkerCode = `${NeuQuant.toString()}(${workerCode.toString()}());`;
1333
+ let webWorkerObj = void 0;
1334
+ let objectUrl = void 0;
1335
+ let webWorker = void 0;
1336
+ let numWorkers = void 0;
1337
+ let x = -1;
1338
+ let workerError = '';
1339
+ numWorkers = options.numWorkers;
1340
+ while (++x < numWorkers) {
1341
+ webWorkerObj = utils.createWebWorker(processFrameWorkerCode);
1342
+ if (utils.isObject(webWorkerObj)) {
1343
+ objectUrl = webWorkerObj.objectUrl;
1344
+ webWorker = webWorkerObj.worker;
1345
+ self.workers.push({
1346
+ worker: webWorker,
1347
+ objectUrl
1348
+ });
1349
+ self.availableWorkers.push(webWorker);
1350
+ } else {
1351
+ workerError = webWorkerObj;
1352
+ utils.webWorkerError = Boolean(webWorkerObj);
1353
+ }
1354
+ }
1355
+ this.workerError = workerError;
1356
+ this.canvas = document.createElement('canvas');
1357
+ this.canvas.width = options.gifWidth;
1358
+ this.canvas.height = options.gifHeight;
1359
+ this.ctx = this.canvas.getContext('2d');
1360
+ this.frames = [];
1361
+ },
1362
+ // Return a worker for processing a frame
1363
+ getWorker: function getWorker() {
1364
+ return this.availableWorkers.pop();
1365
+ },
1366
+ // Restores a worker to the pool
1367
+ freeWorker: function freeWorker(worker) {
1368
+ this.availableWorkers.push(worker);
1369
+ },
1370
+ byteMap: (function () {
1371
+ const byteMap = [];
1372
+ for (let i = 0; i < 256; i++) {
1373
+ byteMap[i] = String.fromCharCode(i);
1374
+ }
1375
+ return byteMap;
1376
+ })(),
1377
+ bufferToString: function bufferToString(buffer) {
1378
+ const numberValues = buffer.length;
1379
+ let str = '';
1380
+ let x = -1;
1381
+ while (++x < numberValues) {
1382
+ str += this.byteMap[buffer[x]];
1383
+ }
1384
+ return str;
1385
+ },
1386
+ onFrameFinished: function onFrameFinished(progressCallback) {
1387
+ // The GIF is not written until we're done with all the frames
1388
+ // because they might not be processed in the same order
1389
+ const self = this;
1390
+ const frames = self.frames;
1391
+ const options = self.options;
1392
+ const hasExistingImages = Boolean((options.images || []).length);
1393
+ const allDone = frames.every(function (frame) {
1394
+ return !frame.beingProcessed && frame.done;
1395
+ });
1396
+ self.numRenderedFrames++;
1397
+ if (hasExistingImages) {
1398
+ progressCallback(self.numRenderedFrames / frames.length);
1399
+ }
1400
+ self.onRenderProgressCallback((self.numRenderedFrames * 0.75) / frames.length);
1401
+ if (allDone) {
1402
+ if (!self.generatingGIF) {
1403
+ self.generateGIF(frames, self.onRenderCompleteCallback);
1404
+ }
1405
+ } else {
1406
+ utils.requestTimeout(function () {
1407
+ self.processNextFrame();
1408
+ }, 1);
1409
+ }
1410
+ },
1411
+ processFrame: function processFrame(position) {
1412
+ const AnimatedGifContext = this;
1413
+ const options = this.options;
1414
+ const _options = this.options;
1415
+ const progressCallback = _options.progressCallback;
1416
+ const sampleInterval = _options.sampleInterval;
1417
+ const frames = this.frames;
1418
+ let frame = void 0;
1419
+ let worker = void 0;
1420
+ const done = function done() {
1421
+ const ev = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
1422
+ const data = ev.data;
1423
+ // Delete original data, and free memory
1424
+ delete frame.data;
1425
+ frame.pixels = Array.prototype.slice.call(data.pixels);
1426
+ frame.palette = Array.prototype.slice.call(data.palette);
1427
+ frame.done = true;
1428
+ frame.beingProcessed = false;
1429
+ AnimatedGifContext.freeWorker(worker);
1430
+ AnimatedGifContext.onFrameFinished(progressCallback);
1431
+ };
1432
+ frame = frames[position];
1433
+ if (frame.beingProcessed || frame.done) {
1434
+ this.onFrameFinished();
1435
+ return;
1436
+ }
1437
+ frame.sampleInterval = sampleInterval;
1438
+ frame.beingProcessed = true;
1439
+ frame.gifshot = true;
1440
+ worker = this.getWorker();
1441
+ if (worker) {
1442
+ // Process the frame in a web worker
1443
+ worker.onmessage = done;
1444
+ worker.postMessage(frame);
1445
+ } else {
1446
+ // Process the frame in the current thread
1447
+ done({
1448
+ data: AnimatedGifContext.workerMethods.run(frame)
1449
+ });
1450
+ }
1451
+ },
1452
+ startRendering: function startRendering(completeCallback) {
1453
+ this.onRenderCompleteCallback = completeCallback;
1454
+ for (let i = 0; i < this.options.numWorkers && i < this.frames.length; i++) {
1455
+ this.processFrame(i);
1456
+ }
1457
+ },
1458
+ processNextFrame: function processNextFrame() {
1459
+ let position = -1;
1460
+ for (let i = 0; i < this.frames.length; i++) {
1461
+ const frame = this.frames[i];
1462
+ if (!frame.done && !frame.beingProcessed) {
1463
+ position = i;
1464
+ break;
1465
+ }
1466
+ }
1467
+ if (position >= 0) {
1468
+ this.processFrame(position);
1469
+ }
1470
+ },
1471
+ // Takes the already processed data in frames and feeds it to a new
1472
+ // GifWriter instance in order to get the binary GIF file
1473
+ generateGIF: function generateGIF(frames, callback) {
1474
+ // TODO: Weird: using a simple JS array instead of a typed array,
1475
+ // the files are WAY smaller o_o. Patches/explanations welcome!
1476
+ const buffer = []; // new Uint8Array(width * height * frames.length * 5);
1477
+ const gifOptions = {
1478
+ loop: this.repeat
1479
+ };
1480
+ const options = this.options;
1481
+ const interval = options.interval;
1482
+ const frameDuration = options.frameDuration;
1483
+ const existingImages = options.images;
1484
+ const hasExistingImages = Boolean(existingImages.length);
1485
+ const height = options.gifHeight;
1486
+ const width = options.gifWidth;
1487
+ const gifWriter$$1 = new gifWriter(buffer, width, height, gifOptions);
1488
+ const onRenderProgressCallback = this.onRenderProgressCallback;
1489
+ const delay = hasExistingImages ? interval * 100 : 0;
1490
+ let bufferToString = void 0;
1491
+ let gif = void 0;
1492
+ this.generatingGIF = true;
1493
+ utils.each(frames, function (iterator, frame) {
1494
+ const framePalette = frame.palette;
1495
+ onRenderProgressCallback(0.75 + (0.25 * frame.position * 1.0) / frames.length);
1496
+ for (let i = 0; i < frameDuration; i++) {
1497
+ gifWriter$$1.addFrame(0, 0, width, height, frame.pixels, {
1498
+ palette: framePalette,
1499
+ delay
1500
+ });
1501
+ }
1502
+ });
1503
+ gifWriter$$1.end();
1504
+ onRenderProgressCallback(1.0);
1505
+ this.frames = [];
1506
+ this.generatingGIF = false;
1507
+ if (utils.isFunction(callback)) {
1508
+ bufferToString = this.bufferToString(buffer);
1509
+ gif = `data:image/gif;base64,${utils.btoa(bufferToString)}`;
1510
+ callback(gif);
1511
+ }
1512
+ },
1513
+ // From GIF: 0 = loop forever, null = not looping, n > 0 = loop n times and stop
1514
+ setRepeat: function setRepeat(r) {
1515
+ this.repeat = r;
1516
+ },
1517
+ addFrame: function addFrame(element, gifshotOptions) {
1518
+ gifshotOptions = utils.isObject(gifshotOptions) ? gifshotOptions : {};
1519
+ const self = this;
1520
+ const ctx = self.ctx;
1521
+ const options = self.options;
1522
+ const width = options.gifWidth;
1523
+ const height = options.gifHeight;
1524
+ const fontSize = utils.getFontSize(gifshotOptions);
1525
+ const _gifshotOptions = gifshotOptions;
1526
+ const filter = _gifshotOptions.filter;
1527
+ const fontColor = _gifshotOptions.fontColor;
1528
+ const fontFamily = _gifshotOptions.fontFamily;
1529
+ const fontWeight = _gifshotOptions.fontWeight;
1530
+ const gifHeight = _gifshotOptions.gifHeight;
1531
+ const gifWidth = _gifshotOptions.gifWidth;
1532
+ const text = _gifshotOptions.text;
1533
+ const textAlign = _gifshotOptions.textAlign;
1534
+ const textBaseline = _gifshotOptions.textBaseline;
1535
+ const textXCoordinate = gifshotOptions.textXCoordinate
1536
+ ? gifshotOptions.textXCoordinate
1537
+ : textAlign === 'left'
1538
+ ? 1
1539
+ : textAlign === 'right'
1540
+ ? width
1541
+ : width / 2;
1542
+ const textYCoordinate = gifshotOptions.textYCoordinate
1543
+ ? gifshotOptions.textYCoordinate
1544
+ : textBaseline === 'top'
1545
+ ? 1
1546
+ : textBaseline === 'center'
1547
+ ? height / 2
1548
+ : height;
1549
+ const font = `${fontWeight} ${fontSize} ${fontFamily}`;
1550
+ let imageData = void 0;
1551
+ try {
1552
+ ctx.filter = filter;
1553
+ ctx.drawImage(element, 0, 0, width, height);
1554
+ if (text) {
1555
+ ctx.font = font;
1556
+ ctx.fillStyle = fontColor;
1557
+ ctx.textAlign = textAlign;
1558
+ ctx.textBaseline = textBaseline;
1559
+ ctx.fillText(text, textXCoordinate, textYCoordinate);
1560
+ }
1561
+ imageData = ctx.getImageData(0, 0, width, height);
1562
+ self.addFrameImageData(imageData);
1563
+ } catch (e) {
1564
+ return `${e}`;
1565
+ }
1566
+ },
1567
+ addFrameImageData: function addFrameImageData() {
1568
+ const imageData = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
1569
+ const frames = this.frames;
1570
+ const imageDataArray = imageData.data;
1571
+ this.frames.push({
1572
+ data: imageDataArray,
1573
+ width: imageData.width,
1574
+ height: imageData.height,
1575
+ palette: null,
1576
+ dithering: null,
1577
+ done: false,
1578
+ beingProcessed: false,
1579
+ position: frames.length
1580
+ });
1581
+ },
1582
+ onRenderProgress: function onRenderProgress(callback) {
1583
+ this.onRenderProgressCallback = callback;
1584
+ },
1585
+ isRendering: function isRendering() {
1586
+ return this.generatingGIF;
1587
+ },
1588
+ getBase64GIF: function getBase64GIF(completeCallback) {
1589
+ const self = this;
1590
+ const onRenderComplete = function onRenderComplete(gif) {
1591
+ self.destroyWorkers();
1592
+ utils.requestTimeout(function () {
1593
+ completeCallback(gif);
1594
+ }, 0);
1595
+ };
1596
+ self.startRendering(onRenderComplete);
1597
+ },
1598
+ destroyWorkers: function destroyWorkers() {
1599
+ if (this.workerError) {
1600
+ return;
1601
+ }
1602
+ const workers = this.workers;
1603
+ // Explicitly ask web workers to die so they are explicitly GC'ed
1604
+ utils.each(workers, function (iterator, workerObj) {
1605
+ const worker = workerObj.worker;
1606
+ const objectUrl = workerObj.objectUrl;
1607
+ worker.terminate();
1608
+ utils.URL.revokeObjectURL(objectUrl);
1609
+ });
1610
+ }
1611
+ };
1612
+ /*
1613
+ getBase64GIF.js
1614
+ ===============
1615
+ */
1616
+ /* Copyright 2017 Yahoo Inc.
1617
+ * Copyrights licensed under the MIT License. See the accompanying LICENSE file for terms.
1618
+ */
1619
+ function getBase64GIF(animatedGifInstance, callback) {
1620
+ // This is asynchronous, rendered with WebWorkers
1621
+ animatedGifInstance.getBase64GIF(function (image) {
1622
+ callback({
1623
+ error: false,
1624
+ errorCode: '',
1625
+ errorMsg: '',
1626
+ image
1627
+ });
1628
+ });
1629
+ }
1630
+ /*
1631
+ existingImages.js
1632
+ =================
1633
+ */
1634
+ /* Copyright 2017 Yahoo Inc.
1635
+ * Copyrights licensed under the MIT License. See the accompanying LICENSE file for terms.
1636
+ */
1637
+ function existingImages() {
1638
+ const obj = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
1639
+ const self = this;
1640
+ const callback = obj.callback;
1641
+ const images = obj.images;
1642
+ const options = obj.options;
1643
+ let imagesLength = obj.imagesLength;
1644
+ const skipObj = {
1645
+ getUserMedia: true,
1646
+ 'window.URL': true
1647
+ };
1648
+ const errorObj = error.validate(skipObj);
1649
+ const loadedImages = [];
1650
+ let loadedImagesLength = 0;
1651
+ let tempImage = void 0;
1652
+ let ag = void 0;
1653
+ if (errorObj.error) {
1654
+ return callback(errorObj);
1655
+ }
1656
+ // change workerPath to point to where Animated_GIF.worker.js is
1657
+ ag = new AnimatedGIF(options);
1658
+ utils.each(images, function (index, image) {
1659
+ const currentImage = image;
1660
+ // if (image.src) {
1661
+ // currentImage = currentImage.src;
1662
+ // }
1663
+ if (utils.isElement(currentImage)) {
1664
+ if (options.crossOrigin) {
1665
+ currentImage.crossOrigin = options.crossOrigin;
1666
+ }
1667
+ loadedImages[index] = currentImage;
1668
+ loadedImagesLength += 1;
1669
+ if (loadedImagesLength === imagesLength) {
1670
+ addLoadedImagesToGif();
1671
+ }
1672
+ } else if (utils.isString(currentImage)) {
1673
+ tempImage = new Image();
1674
+ if (options.crossOrigin) {
1675
+ tempImage.crossOrigin = options.crossOrigin;
1676
+ }
1677
+ (function (tempImage) {
1678
+ if (image.text) {
1679
+ tempImage.text = image.text;
1680
+ }
1681
+ tempImage.onerror = function (e) {
1682
+ let obj = void 0;
1683
+ --imagesLength; // skips over images that error out
1684
+ if (imagesLength === 0) {
1685
+ obj = {};
1686
+ obj.error = 'None of the requested images was capable of being retrieved';
1687
+ return callback(obj);
1688
+ }
1689
+ };
1690
+ tempImage.onload = function (e) {
1691
+ if (image.text) {
1692
+ loadedImages[index] = {
1693
+ img: tempImage,
1694
+ text: tempImage.text
1695
+ };
1696
+ } else {
1697
+ loadedImages[index] = tempImage;
1698
+ }
1699
+ loadedImagesLength += 1;
1700
+ if (loadedImagesLength === imagesLength) {
1701
+ addLoadedImagesToGif();
1702
+ }
1703
+ utils.removeElement(tempImage);
1704
+ };
1705
+ tempImage.src = currentImage;
1706
+ })(tempImage);
1707
+ utils.setCSSAttr(tempImage, {
1708
+ position: 'fixed',
1709
+ opacity: '0'
1710
+ });
1711
+ document.body.appendChild(tempImage);
1712
+ }
1713
+ });
1714
+ function addLoadedImagesToGif() {
1715
+ utils.each(loadedImages, function (index, loadedImage) {
1716
+ if (loadedImage) {
1717
+ if (loadedImage.text) {
1718
+ ag.addFrame(loadedImage.img, options, loadedImage.text);
1719
+ } else {
1720
+ ag.addFrame(loadedImage, options);
1721
+ }
1722
+ }
1723
+ });
1724
+ getBase64GIF(ag, callback);
1725
+ }
1726
+ }
1727
+ /*
1728
+ screenShot.js
1729
+ =============
1730
+ */
1731
+ /* Copyright 2017 Yahoo Inc.
1732
+ * Copyrights licensed under the MIT License. See the accompanying LICENSE file for terms.
1733
+ */
1734
+ // Dependencies
1735
+ // Helpers
1736
+ const noop$3 = function noop() {};
1737
+ const screenShot = {
1738
+ getGIF: function getGIF() {
1739
+ const options = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
1740
+ let callback = arguments[1];
1741
+ callback = utils.isFunction(callback) ? callback : noop$3;
1742
+ const canvas = document.createElement('canvas');
1743
+ let context = void 0;
1744
+ const existingImages = options.images;
1745
+ const hasExistingImages = Boolean(existingImages.length);
1746
+ const cameraStream = options.cameraStream;
1747
+ const crop = options.crop;
1748
+ const filter = options.filter;
1749
+ const fontColor = options.fontColor;
1750
+ const fontFamily = options.fontFamily;
1751
+ const fontWeight = options.fontWeight;
1752
+ const keepCameraOn = options.keepCameraOn;
1753
+ const numWorkers = options.numWorkers;
1754
+ const progressCallback = options.progressCallback;
1755
+ const saveRenderingContexts = options.saveRenderingContexts;
1756
+ const savedRenderingContexts = options.savedRenderingContexts;
1757
+ const text = options.text;
1758
+ const textAlign = options.textAlign;
1759
+ const textBaseline = options.textBaseline;
1760
+ const videoElement = options.videoElement;
1761
+ const videoHeight = options.videoHeight;
1762
+ const videoWidth = options.videoWidth;
1763
+ const webcamVideoElement = options.webcamVideoElement;
1764
+ const gifWidth = Number(options.gifWidth);
1765
+ const gifHeight = Number(options.gifHeight);
1766
+ let interval = Number(options.interval);
1767
+ const sampleInterval = Number(options.sampleInterval);
1768
+ const waitBetweenFrames = hasExistingImages ? 0 : interval * 1000;
1769
+ const renderingContextsToSave = [];
1770
+ let numFrames = savedRenderingContexts.length
1771
+ ? savedRenderingContexts.length
1772
+ : options.numFrames;
1773
+ let pendingFrames = numFrames;
1774
+ const ag = new AnimatedGIF(options);
1775
+ const fontSize = utils.getFontSize(options);
1776
+ const textXCoordinate = options.textXCoordinate
1777
+ ? options.textXCoordinate
1778
+ : textAlign === 'left'
1779
+ ? 1
1780
+ : textAlign === 'right'
1781
+ ? gifWidth
1782
+ : gifWidth / 2;
1783
+ const textYCoordinate = options.textYCoordinate
1784
+ ? options.textYCoordinate
1785
+ : textBaseline === 'top'
1786
+ ? 1
1787
+ : textBaseline === 'center'
1788
+ ? gifHeight / 2
1789
+ : gifHeight;
1790
+ const font = `${fontWeight} ${fontSize} ${fontFamily}`;
1791
+ let sourceX = crop ? Math.floor(crop.scaledWidth / 2) : 0;
1792
+ let sourceWidth = crop ? videoWidth - crop.scaledWidth : 0;
1793
+ let sourceY = crop ? Math.floor(crop.scaledHeight / 2) : 0;
1794
+ let sourceHeight = crop ? videoHeight - crop.scaledHeight : 0;
1795
+ const captureFrames = function captureSingleFrame() {
1796
+ const framesLeft = pendingFrames - 1;
1797
+ if (savedRenderingContexts.length) {
1798
+ context.putImageData(savedRenderingContexts[numFrames - pendingFrames], 0, 0);
1799
+ finishCapture();
1800
+ } else {
1801
+ drawVideo();
1802
+ }
1803
+ function drawVideo() {
1804
+ try {
1805
+ // Makes sure the canvas video heights/widths are in bounds
1806
+ if (sourceWidth > videoWidth) {
1807
+ sourceWidth = videoWidth;
1808
+ }
1809
+ if (sourceHeight > videoHeight) {
1810
+ sourceHeight = videoHeight;
1811
+ }
1812
+ if (sourceX < 0) {
1813
+ sourceX = 0;
1814
+ }
1815
+ if (sourceY < 0) {
1816
+ sourceY = 0;
1817
+ }
1818
+ context.filter = filter;
1819
+ context.drawImage(
1820
+ videoElement,
1821
+ sourceX,
1822
+ sourceY,
1823
+ sourceWidth,
1824
+ sourceHeight,
1825
+ 0,
1826
+ 0,
1827
+ gifWidth,
1828
+ gifHeight
1829
+ );
1830
+ finishCapture();
1831
+ } catch (e) {
1832
+ // There is a Firefox bug that sometimes throws NS_ERROR_NOT_AVAILABLE and
1833
+ // and IndexSizeError errors when drawing a video element to the canvas
1834
+ if (e.name === 'NS_ERROR_NOT_AVAILABLE') {
1835
+ // Wait 100ms before trying again
1836
+ utils.requestTimeout(drawVideo, 100);
1837
+ } else {
1838
+ throw e;
1839
+ }
1840
+ }
1841
+ }
1842
+ function finishCapture() {
1843
+ let imageData = void 0;
1844
+ if (saveRenderingContexts) {
1845
+ renderingContextsToSave.push(context.getImageData(0, 0, gifWidth, gifHeight));
1846
+ }
1847
+ // If there is text to display, make sure to display it on the canvas after the image is drawn
1848
+ if (text) {
1849
+ context.font = font;
1850
+ context.fillStyle = fontColor;
1851
+ context.textAlign = textAlign;
1852
+ context.textBaseline = textBaseline;
1853
+ context.fillText(text, textXCoordinate, textYCoordinate);
1854
+ }
1855
+ imageData = context.getImageData(0, 0, gifWidth, gifHeight);
1856
+ ag.addFrameImageData(imageData);
1857
+ pendingFrames = framesLeft;
1858
+ // Call back with an r value indicating how far along we are in capture
1859
+ progressCallback((numFrames - pendingFrames) / numFrames);
1860
+ if (framesLeft > 0) {
1861
+ // test
1862
+ utils.requestTimeout(captureSingleFrame, waitBetweenFrames);
1863
+ }
1864
+ if (!pendingFrames) {
1865
+ ag.getBase64GIF(function (image) {
1866
+ callback({
1867
+ error: false,
1868
+ errorCode: '',
1869
+ errorMsg: '',
1870
+ image,
1871
+ cameraStream,
1872
+ videoElement,
1873
+ webcamVideoElement,
1874
+ savedRenderingContexts: renderingContextsToSave,
1875
+ keepCameraOn
1876
+ });
1877
+ });
1878
+ }
1879
+ }
1880
+ };
1881
+ numFrames = numFrames !== undefined ? numFrames : 10;
1882
+ interval = interval !== undefined ? interval : 0.1; // In seconds
1883
+ canvas.width = gifWidth;
1884
+ canvas.height = gifHeight;
1885
+ context = canvas.getContext('2d');
1886
+ (function capture() {
1887
+ if (!savedRenderingContexts.length && videoElement.currentTime === 0) {
1888
+ utils.requestTimeout(capture, 100);
1889
+ return;
1890
+ }
1891
+ captureFrames();
1892
+ })();
1893
+ },
1894
+ getCropDimensions: function getCropDimensions() {
1895
+ const obj = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
1896
+ const width = obj.videoWidth;
1897
+ const height = obj.videoHeight;
1898
+ const gifWidth = obj.gifWidth;
1899
+ const gifHeight = obj.gifHeight;
1900
+ const result = {
1901
+ width: 0,
1902
+ height: 0,
1903
+ scaledWidth: 0,
1904
+ scaledHeight: 0
1905
+ };
1906
+ if (width > height) {
1907
+ result.width = Math.round(width * (gifHeight / height)) - gifWidth;
1908
+ result.scaledWidth = Math.round(result.width * (height / gifHeight));
1909
+ } else {
1910
+ result.height = Math.round(height * (gifWidth / width)) - gifHeight;
1911
+ result.scaledHeight = Math.round(result.height * (width / gifWidth));
1912
+ }
1913
+ return result;
1914
+ }
1915
+ };
1916
+ /*
1917
+ videoStream.js
1918
+ ==============
1919
+ */
1920
+ /* Copyright 2017 Yahoo Inc.
1921
+ * Copyrights licensed under the MIT License. See the accompanying LICENSE file for terms.
1922
+ */
1923
+ // Dependencies
1924
+ var videoStream = {
1925
+ loadedData: false,
1926
+ defaultVideoDimensions: {
1927
+ width: 640,
1928
+ height: 480
1929
+ },
1930
+ findVideoSize: function findVideoSizeMethod(obj) {
1931
+ findVideoSizeMethod.attempts = findVideoSizeMethod.attempts || 0;
1932
+ const cameraStream = obj.cameraStream;
1933
+ const completedCallback = obj.completedCallback;
1934
+ const videoElement = obj.videoElement;
1935
+ if (!videoElement) {
1936
+ return;
1937
+ }
1938
+ if (videoElement.videoWidth > 0 && videoElement.videoHeight > 0) {
1939
+ videoElement.removeEventListener('loadeddata', videoStream.findVideoSize);
1940
+ completedCallback({
1941
+ videoElement,
1942
+ cameraStream,
1943
+ videoWidth: videoElement.videoWidth,
1944
+ videoHeight: videoElement.videoHeight
1945
+ });
1946
+ } else if (findVideoSizeMethod.attempts < 10) {
1947
+ findVideoSizeMethod.attempts += 1;
1948
+ utils.requestTimeout(function () {
1949
+ videoStream.findVideoSize(obj);
1950
+ }, 400);
1951
+ } else {
1952
+ completedCallback({
1953
+ videoElement,
1954
+ cameraStream,
1955
+ videoWidth: videoStream.defaultVideoDimensions.width,
1956
+ videoHeight: videoStream.defaultVideoDimensions.height
1957
+ });
1958
+ }
1959
+ },
1960
+ onStreamingTimeout: function onStreamingTimeout(callback) {
1961
+ if (utils.isFunction(callback)) {
1962
+ callback({
1963
+ error: true,
1964
+ errorCode: 'getUserMedia',
1965
+ errorMsg:
1966
+ 'There was an issue with the getUserMedia API - Timed out while trying to start streaming',
1967
+ image: null,
1968
+ cameraStream: {}
1969
+ });
1970
+ }
1971
+ },
1972
+ stream: function stream(obj) {
1973
+ const existingVideo = utils.isArray(obj.existingVideo)
1974
+ ? obj.existingVideo[0]
1975
+ : obj.existingVideo;
1976
+ const cameraStream = obj.cameraStream;
1977
+ const completedCallback = obj.completedCallback;
1978
+ const streamedCallback = obj.streamedCallback;
1979
+ const videoElement = obj.videoElement;
1980
+ if (utils.isFunction(streamedCallback)) {
1981
+ streamedCallback();
1982
+ }
1983
+ if (existingVideo) {
1984
+ if (utils.isString(existingVideo)) {
1985
+ videoElement.src = existingVideo;
1986
+ videoElement.innerHTML = `<source src="${existingVideo}" type="video/${utils.getExtension(
1987
+ existingVideo
1988
+ )}" />`;
1989
+ } else if (existingVideo instanceof Blob) {
1990
+ try {
1991
+ videoElement.src = utils.URL.createObjectURL(existingVideo);
1992
+ } catch (e) {}
1993
+ videoElement.innerHTML = `<source src="${existingVideo}" type="${existingVideo.type}" />`;
1994
+ }
1995
+ } else if (videoElement.mozSrcObject) {
1996
+ videoElement.mozSrcObject = cameraStream;
1997
+ } else if (utils.URL) {
1998
+ try {
1999
+ videoElement.srcObject = cameraStream;
2000
+ videoElement.src = utils.URL.createObjectURL(cameraStream);
2001
+ } catch (e) {
2002
+ videoElement.srcObject = cameraStream;
2003
+ }
2004
+ }
2005
+ videoElement.play();
2006
+ utils.requestTimeout(function checkLoadedData() {
2007
+ checkLoadedData.count = checkLoadedData.count || 0;
2008
+ if (videoStream.loadedData === true) {
2009
+ videoStream.findVideoSize({
2010
+ videoElement,
2011
+ cameraStream,
2012
+ completedCallback
2013
+ });
2014
+ videoStream.loadedData = false;
2015
+ } else {
2016
+ checkLoadedData.count += 1;
2017
+ if (checkLoadedData.count > 10) {
2018
+ videoStream.findVideoSize({
2019
+ videoElement,
2020
+ cameraStream,
2021
+ completedCallback
2022
+ });
2023
+ } else {
2024
+ checkLoadedData();
2025
+ }
2026
+ }
2027
+ }, 0);
2028
+ },
2029
+ startStreaming: function startStreaming(obj) {
2030
+ const errorCallback = utils.isFunction(obj.error) ? obj.error : utils.noop;
2031
+ const streamedCallback = utils.isFunction(obj.streamed) ? obj.streamed : utils.noop;
2032
+ const completedCallback = utils.isFunction(obj.completed) ? obj.completed : utils.noop;
2033
+ const crossOrigin = obj.crossOrigin;
2034
+ const existingVideo = obj.existingVideo;
2035
+ const lastCameraStream = obj.lastCameraStream;
2036
+ const options = obj.options;
2037
+ const webcamVideoElement = obj.webcamVideoElement;
2038
+ const videoElement = utils.isElement(existingVideo)
2039
+ ? existingVideo
2040
+ : webcamVideoElement
2041
+ ? webcamVideoElement
2042
+ : document.createElement('video');
2043
+ const cameraStream = void 0;
2044
+ if (crossOrigin) {
2045
+ videoElement.crossOrigin = options.crossOrigin;
2046
+ }
2047
+ videoElement.autoplay = true;
2048
+ videoElement.loop = true;
2049
+ videoElement.muted = true;
2050
+ videoElement.addEventListener('loadeddata', function (event) {
2051
+ videoStream.loadedData = true;
2052
+ if (options.offset) {
2053
+ videoElement.currentTime = options.offset;
2054
+ }
2055
+ });
2056
+ if (existingVideo) {
2057
+ videoStream.stream({
2058
+ videoElement,
2059
+ existingVideo,
2060
+ completedCallback
2061
+ });
2062
+ } else if (lastCameraStream) {
2063
+ videoStream.stream({
2064
+ videoElement,
2065
+ cameraStream: lastCameraStream,
2066
+ streamedCallback,
2067
+ completedCallback
2068
+ });
2069
+ } else {
2070
+ utils.getUserMedia(
2071
+ {
2072
+ video: true
2073
+ },
2074
+ function (stream) {
2075
+ videoStream.stream({
2076
+ videoElement,
2077
+ cameraStream: stream,
2078
+ streamedCallback,
2079
+ completedCallback
2080
+ });
2081
+ },
2082
+ errorCallback
2083
+ );
2084
+ }
2085
+ },
2086
+ startVideoStreaming: function startVideoStreaming(callback) {
2087
+ const options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
2088
+ const timeoutLength = options.timeout !== undefined ? options.timeout : 0;
2089
+ const originalCallback = options.callback;
2090
+ const webcamVideoElement = options.webcamVideoElement;
2091
+ let noGetUserMediaSupportTimeout = void 0;
2092
+ // Some browsers apparently have support for video streaming because of the
2093
+ // presence of the getUserMedia function, but then do not answer our
2094
+ // calls for streaming.
2095
+ // So we'll set up this timeout and if nothing happens after a while, we'll
2096
+ // conclude that there's no actual getUserMedia support.
2097
+ if (timeoutLength > 0) {
2098
+ noGetUserMediaSupportTimeout = utils.requestTimeout(function () {
2099
+ videoStream.onStreamingTimeout(originalCallback);
2100
+ }, 10000);
2101
+ }
2102
+ videoStream.startStreaming({
2103
+ error: function error() {
2104
+ originalCallback({
2105
+ error: true,
2106
+ errorCode: 'getUserMedia',
2107
+ errorMsg:
2108
+ 'There was an issue with the getUserMedia API - the user probably denied permission',
2109
+ image: null,
2110
+ cameraStream: {}
2111
+ });
2112
+ },
2113
+ streamed: function streamed() {
2114
+ // The streaming started somehow, so we can assume there is getUserMedia support
2115
+ clearTimeout(noGetUserMediaSupportTimeout);
2116
+ },
2117
+ completed: function completed() {
2118
+ const obj = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
2119
+ const cameraStream = obj.cameraStream;
2120
+ const videoElement = obj.videoElement;
2121
+ const videoHeight = obj.videoHeight;
2122
+ const videoWidth = obj.videoWidth;
2123
+ callback({
2124
+ cameraStream,
2125
+ videoElement,
2126
+ videoHeight,
2127
+ videoWidth
2128
+ });
2129
+ },
2130
+ lastCameraStream: options.lastCameraStream,
2131
+ webcamVideoElement,
2132
+ crossOrigin: options.crossOrigin,
2133
+ options
2134
+ });
2135
+ },
2136
+ stopVideoStreaming: function stopVideoStreaming(obj) {
2137
+ obj = utils.isObject(obj) ? obj : {};
2138
+ const _obj = obj;
2139
+ const keepCameraOn = _obj.keepCameraOn;
2140
+ const videoElement = _obj.videoElement;
2141
+ const webcamVideoElement = _obj.webcamVideoElement;
2142
+ const cameraStream = obj.cameraStream || {};
2143
+ const cameraStreamTracks = cameraStream.getTracks ? cameraStream.getTracks() || [] : [];
2144
+ const hasCameraStreamTracks = Boolean(cameraStreamTracks.length);
2145
+ const firstCameraStreamTrack = cameraStreamTracks[0];
2146
+ if (!keepCameraOn && hasCameraStreamTracks) {
2147
+ if (utils.isFunction(firstCameraStreamTrack.stop)) {
2148
+ // Stops the camera stream
2149
+ firstCameraStreamTrack.stop();
2150
+ }
2151
+ }
2152
+ if (utils.isElement(videoElement) && !webcamVideoElement) {
2153
+ // Pauses the video, revokes the object URL (freeing up memory), and remove the video element
2154
+ videoElement.pause();
2155
+ // Destroys the object url
2156
+ if (utils.isFunction(utils.URL.revokeObjectURL) && !utils.webWorkerError) {
2157
+ if (videoElement.src) {
2158
+ utils.URL.revokeObjectURL(videoElement.src);
2159
+ }
2160
+ }
2161
+ // Removes the video element from the DOM
2162
+ utils.removeElement(videoElement);
2163
+ }
2164
+ }
2165
+ };
2166
+ /*
2167
+ stopVideoStreaming.js
2168
+ =====================
2169
+ */
2170
+ /* Copyright 2017 Yahoo Inc.
2171
+ * Copyrights licensed under the MIT License. See the accompanying LICENSE file for terms.
2172
+ */
2173
+ function stopVideoStreaming(options) {
2174
+ options = utils.isObject(options) ? options : {};
2175
+ videoStream.stopVideoStreaming(options);
2176
+ }
2177
+ /*
2178
+ createAndGetGIF.js
2179
+ ==================
2180
+ */
2181
+ /* Copyright 2017 Yahoo Inc.
2182
+ * Copyrights licensed under the MIT License. See the accompanying LICENSE file for terms.
2183
+ */
2184
+ // Dependencies
2185
+ function createAndGetGIF(obj, callback) {
2186
+ const options = obj.options || {};
2187
+ const images = options.images;
2188
+ const video = options.video;
2189
+ const gifWidth = Number(options.gifWidth);
2190
+ const gifHeight = Number(options.gifHeight);
2191
+ const numFrames = Number(options.numFrames);
2192
+ const cameraStream = obj.cameraStream;
2193
+ const videoElement = obj.videoElement;
2194
+ const videoWidth = obj.videoWidth;
2195
+ const videoHeight = obj.videoHeight;
2196
+ const cropDimensions = screenShot.getCropDimensions({
2197
+ videoWidth,
2198
+ videoHeight,
2199
+ gifHeight,
2200
+ gifWidth
2201
+ });
2202
+ const completeCallback = callback;
2203
+ options.crop = cropDimensions;
2204
+ options.videoElement = videoElement;
2205
+ options.videoWidth = videoWidth;
2206
+ options.videoHeight = videoHeight;
2207
+ options.cameraStream = cameraStream;
2208
+ if (!utils.isElement(videoElement)) {
2209
+ return;
2210
+ }
2211
+ videoElement.width = gifWidth + cropDimensions.width;
2212
+ videoElement.height = gifHeight + cropDimensions.height;
2213
+ if (!options.webcamVideoElement) {
2214
+ utils.setCSSAttr(videoElement, {
2215
+ position: 'fixed',
2216
+ opacity: '0'
2217
+ });
2218
+ document.body.appendChild(videoElement);
2219
+ }
2220
+ // Firefox doesn't seem to obey autoplay if the element is not in the DOM when the content
2221
+ // is loaded, so we must manually trigger play after adding it, or the video will be frozen
2222
+ videoElement.play();
2223
+ screenShot.getGIF(options, function (obj) {
2224
+ if ((!images || !images.length) && (!video || !video.length)) {
2225
+ stopVideoStreaming(obj);
2226
+ }
2227
+ completeCallback(obj);
2228
+ });
2229
+ }
2230
+ /*
2231
+ existingVideo.js
2232
+ ================
2233
+ */
2234
+ /* Copyright 2017 Yahoo Inc.
2235
+ * Copyrights licensed under the MIT License. See the accompanying LICENSE file for terms.
2236
+ */
2237
+ // Dependencies
2238
+ function existingVideo() {
2239
+ const obj = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
2240
+ const callback = obj.callback;
2241
+ let existingVideo = obj.existingVideo;
2242
+ const options = obj.options;
2243
+ const skipObj = {
2244
+ getUserMedia: true,
2245
+ 'window.URL': true
2246
+ };
2247
+ const errorObj = error.validate(skipObj);
2248
+ const loadedImages = 0;
2249
+ let videoType = void 0;
2250
+ let videoSrc = void 0;
2251
+ const tempImage = void 0;
2252
+ const ag = void 0;
2253
+ if (errorObj.error) {
2254
+ return callback(errorObj);
2255
+ }
2256
+ if (utils.isElement(existingVideo) && existingVideo.src) {
2257
+ videoSrc = existingVideo.src;
2258
+ videoType = utils.getExtension(videoSrc);
2259
+ if (!utils.isSupported.videoCodecs[videoType]) {
2260
+ return callback(error.messages.videoCodecs);
2261
+ }
2262
+ } else if (utils.isArray(existingVideo)) {
2263
+ utils.each(existingVideo, function (iterator, videoSrc) {
2264
+ if (videoSrc instanceof Blob) {
2265
+ videoType = videoSrc.type.substr(videoSrc.type.lastIndexOf('/') + 1, videoSrc.length);
2266
+ } else {
2267
+ videoType = videoSrc.substr(videoSrc.lastIndexOf('.') + 1, videoSrc.length);
2268
+ }
2269
+ if (utils.isSupported.videoCodecs[videoType]) {
2270
+ existingVideo = videoSrc;
2271
+ return false;
2272
+ }
2273
+ });
2274
+ }
2275
+ videoStream.startStreaming({
2276
+ completed: function completed(obj) {
2277
+ obj.options = options || {};
2278
+ createAndGetGIF(obj, callback);
2279
+ },
2280
+ existingVideo,
2281
+ crossOrigin: options.crossOrigin,
2282
+ options
2283
+ });
2284
+ }
2285
+ /*
2286
+ existingWebcam.js
2287
+ =================
2288
+ */
2289
+ /* Copyright 2017 Yahoo Inc.
2290
+ * Copyrights licensed under the MIT License. See the accompanying LICENSE file for terms.
2291
+ */
2292
+ // Dependencies
2293
+ function existingWebcam() {
2294
+ const obj = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
2295
+ const callback = obj.callback;
2296
+ const lastCameraStream = obj.lastCameraStream;
2297
+ const options = obj.options;
2298
+ const webcamVideoElement = obj.webcamVideoElement;
2299
+ if (!isWebCamGIFSupported()) {
2300
+ return callback(error.validate());
2301
+ }
2302
+ if (options.savedRenderingContexts.length) {
2303
+ screenShot.getGIF(options, function (obj) {
2304
+ callback(obj);
2305
+ });
2306
+ return;
2307
+ }
2308
+ videoStream.startVideoStreaming(
2309
+ function () {
2310
+ const obj = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
2311
+ obj.options = options || {};
2312
+ createAndGetGIF(obj, callback);
2313
+ },
2314
+ {
2315
+ lastCameraStream,
2316
+ callback,
2317
+ webcamVideoElement,
2318
+ crossOrigin: options.crossOrigin
2319
+ }
2320
+ );
2321
+ }
2322
+ /*
2323
+ createGIF.js
2324
+ ============
2325
+ */
2326
+ /* Copyright 2017 Yahoo Inc.
2327
+ * Copyrights licensed under the MIT License. See the accompanying LICENSE file for terms.
2328
+ */
2329
+ // Dependencies
2330
+ function createGIF(userOptions, callback) {
2331
+ callback = utils.isFunction(userOptions) ? userOptions : callback;
2332
+ userOptions = utils.isObject(userOptions) ? userOptions : {};
2333
+ if (!utils.isFunction(callback)) {
2334
+ return;
2335
+ }
2336
+ let options = utils.normalizeOptions(defaultOptions, userOptions) || {};
2337
+ const lastCameraStream = userOptions.cameraStream;
2338
+ const images = options.images;
2339
+ const imagesLength = images ? images.length : 0;
2340
+ const video = options.video;
2341
+ const webcamVideoElement = options.webcamVideoElement;
2342
+ options = utils.normalizeOptions(options, {
2343
+ gifWidth: Math.floor(options.gifWidth),
2344
+ gifHeight: Math.floor(options.gifHeight)
2345
+ });
2346
+ // If the user would like to create a GIF from an existing image(s)
2347
+ if (imagesLength) {
2348
+ existingImages({
2349
+ images,
2350
+ imagesLength,
2351
+ callback,
2352
+ options
2353
+ });
2354
+ } else if (video) {
2355
+ // If the user would like to create a GIF from an existing HTML5 video
2356
+ existingVideo({
2357
+ existingVideo: video,
2358
+ callback,
2359
+ options
2360
+ });
2361
+ } else {
2362
+ // If the user would like to create a GIF from a webcam stream
2363
+ existingWebcam({
2364
+ lastCameraStream,
2365
+ callback,
2366
+ webcamVideoElement,
2367
+ options
2368
+ });
2369
+ }
2370
+ }
2371
+ /*
2372
+ takeSnapShot.js
2373
+ ===============
2374
+ */
2375
+ /* Copyright 2017 Yahoo Inc.
2376
+ * Copyrights licensed under the MIT License. See the accompanying LICENSE file for terms.
2377
+ */
2378
+ function takeSnapShot(userOptions, callback) {
2379
+ callback = utils.isFunction(userOptions) ? userOptions : callback;
2380
+ userOptions = utils.isObject(userOptions) ? userOptions : {};
2381
+ if (!utils.isFunction(callback)) {
2382
+ return;
2383
+ }
2384
+ const mergedOptions = utils.normalizeOptions(defaultOptions, userOptions);
2385
+ const options = utils.normalizeOptions(mergedOptions, {
2386
+ interval: 0.1,
2387
+ numFrames: 1,
2388
+ gifWidth: Math.floor(mergedOptions.gifWidth),
2389
+ gifHeight: Math.floor(mergedOptions.gifHeight)
2390
+ });
2391
+ createGIF(options, callback);
2392
+ }
2393
+ /*
2394
+ API.js
2395
+ ======
2396
+ */
2397
+ /* Copyright 2017 Yahoo Inc.
2398
+ * Copyrights licensed under the MIT License. See the accompanying LICENSE file for terms.
2399
+ */
2400
+ // Dependencies
2401
+ const API = {
2402
+ utils: utils$2,
2403
+ error: error$2,
2404
+ defaultOptions: defaultOptions$2,
2405
+ createGIF,
2406
+ takeSnapShot,
2407
+ stopVideoStreaming,
2408
+ isSupported,
2409
+ isWebCamGIFSupported,
2410
+ isExistingVideoGIFSupported,
2411
+ isExistingImagesGIFSupported: isSupported$1,
2412
+ VERSION: '0.4.5'
2413
+ };
2414
+
2415
+ export default API;