@loaders.gl/video 4.2.0-alpha.3 → 4.2.0-alpha.5

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