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

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