@loaders.gl/video 4.0.0-alpha.1 → 4.0.0-alpha.11

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