@loaders.gl/video 4.0.0-alpha.9 → 4.0.0-beta.1

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