@yft-design/psd-lib 1.0.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/jpeg.js ADDED
@@ -0,0 +1,1017 @@
1
+ // based on https://github.com/jpeg-js/jpeg-js
2
+ /*
3
+ Copyright 2011 notmasteryet
4
+
5
+ Licensed under the Apache License, Version 2.0 (the "License");
6
+ you may not use this file except in compliance with the License.
7
+ You may obtain a copy of the License at
8
+
9
+ http://www.apache.org/licenses/LICENSE-2.0
10
+
11
+ Unless required by applicable law or agreed to in writing, software
12
+ distributed under the License is distributed on an "AS IS" BASIS,
13
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14
+ See the License for the specific language governing permissions and
15
+ limitations under the License.
16
+ */
17
+ const dctZigZag = new Int32Array([
18
+ 0,
19
+ 1, 8,
20
+ 16, 9, 2,
21
+ 3, 10, 17, 24,
22
+ 32, 25, 18, 11, 4,
23
+ 5, 12, 19, 26, 33, 40,
24
+ 48, 41, 34, 27, 20, 13, 6,
25
+ 7, 14, 21, 28, 35, 42, 49, 56,
26
+ 57, 50, 43, 36, 29, 22, 15,
27
+ 23, 30, 37, 44, 51, 58,
28
+ 59, 52, 45, 38, 31,
29
+ 39, 46, 53, 60,
30
+ 61, 54, 47,
31
+ 55, 62,
32
+ 63
33
+ ]);
34
+ const dctCos1 = 4017; // cos(pi/16)
35
+ const dctSin1 = 799; // sin(pi/16)
36
+ const dctCos3 = 3406; // cos(3*pi/16)
37
+ const dctSin3 = 2276; // sin(3*pi/16)
38
+ const dctCos6 = 1567; // cos(6*pi/16)
39
+ const dctSin6 = 3784; // sin(6*pi/16)
40
+ const dctSqrt2 = 5793; // sqrt(2)
41
+ const dctSqrt1d2 = 2896; // sqrt(2) / 2
42
+ const maxResolutionInMP = 100; // Don't decode more than 100 megapixels
43
+ const maxMemoryUsageBytes = 64 * 1024 * 1024; // Don't decode if memory footprint is more than 64MB
44
+ let totalBytesAllocated = 0; // avoid unexpected OOMs from untrusted content.
45
+ function requestMemoryAllocation(increaseAmount) {
46
+ const totalMemoryImpactBytes = totalBytesAllocated + increaseAmount;
47
+ if (totalMemoryImpactBytes > maxMemoryUsageBytes) {
48
+ const exceededAmount = Math.ceil((totalMemoryImpactBytes - maxMemoryUsageBytes) / 1024 / 1024);
49
+ throw new Error(`Max memory limit exceeded by at least ${exceededAmount}MB`);
50
+ }
51
+ totalBytesAllocated = totalMemoryImpactBytes;
52
+ }
53
+ function buildHuffmanTable(codeLengths, values) {
54
+ let length = 16;
55
+ while (length > 0 && !codeLengths[length - 1])
56
+ length--;
57
+ const code = [{ children: [], index: 0 }];
58
+ let k = 0;
59
+ let p = code[0];
60
+ for (let i = 0; i < length; i++) {
61
+ for (let j = 0; j < codeLengths[i]; j++) {
62
+ p = code.pop();
63
+ p.children[p.index] = values[k];
64
+ while (p.index > 0) {
65
+ if (code.length === 0)
66
+ throw new Error('Could not recreate Huffman Table');
67
+ p = code.pop();
68
+ }
69
+ p.index++;
70
+ code.push(p);
71
+ while (code.length <= i) {
72
+ const q = { children: [], index: 0 };
73
+ code.push(q);
74
+ p.children[p.index] = q.children;
75
+ p = q;
76
+ }
77
+ k++;
78
+ }
79
+ if (i + 1 < length) {
80
+ // p here points to last code
81
+ const q = { children: [], index: 0 };
82
+ code.push(q);
83
+ p.children[p.index] = q.children;
84
+ p = q;
85
+ }
86
+ }
87
+ return code[0].children;
88
+ }
89
+ function decodeScan(data, offset, frame, components, resetInterval, spectralStart, spectralEnd, successivePrev, successive) {
90
+ const mcusPerLine = frame.mcusPerLine;
91
+ const progressive = frame.progressive;
92
+ const startOffset = offset;
93
+ let bitsData = 0;
94
+ let bitsCount = 0;
95
+ function readBit() {
96
+ if (bitsCount > 0) {
97
+ bitsCount--;
98
+ return (bitsData >> bitsCount) & 1;
99
+ }
100
+ bitsData = data[offset++];
101
+ if (bitsData == 0xFF) {
102
+ const nextByte = data[offset++];
103
+ if (nextByte)
104
+ throw new Error(`unexpected marker: ${((bitsData << 8) | nextByte).toString(16)}`);
105
+ // unstuff 0
106
+ }
107
+ bitsCount = 7;
108
+ return bitsData >>> 7;
109
+ }
110
+ function decodeHuffman(tree) {
111
+ let node = tree;
112
+ while (true) {
113
+ node = node[readBit()];
114
+ if (typeof node === 'number')
115
+ return node;
116
+ if (node === undefined)
117
+ throw new Error('invalid huffman sequence');
118
+ }
119
+ }
120
+ function receive(length) {
121
+ let n = 0;
122
+ while (length > 0) {
123
+ n = (n << 1) | readBit();
124
+ length--;
125
+ }
126
+ return n;
127
+ }
128
+ function receiveAndExtend(length) {
129
+ let n = receive(length);
130
+ if (n >= 1 << (length - 1))
131
+ return n;
132
+ return n + (-1 << length) + 1;
133
+ }
134
+ function decodeBaseline(component, zz) {
135
+ const t = decodeHuffman(component.huffmanTableDC);
136
+ const diff = t === 0 ? 0 : receiveAndExtend(t);
137
+ zz[0] = (component.pred += diff);
138
+ let k = 1;
139
+ while (k < 64) {
140
+ const rs = decodeHuffman(component.huffmanTableAC);
141
+ const s = rs & 15;
142
+ const r = rs >> 4;
143
+ if (s === 0) {
144
+ if (r < 15)
145
+ break;
146
+ k += 16;
147
+ continue;
148
+ }
149
+ k += r;
150
+ const z = dctZigZag[k];
151
+ zz[z] = receiveAndExtend(s);
152
+ k++;
153
+ }
154
+ }
155
+ function decodeDCFirst(component, zz) {
156
+ const t = decodeHuffman(component.huffmanTableDC);
157
+ const diff = t === 0 ? 0 : (receiveAndExtend(t) << successive);
158
+ zz[0] = (component.pred += diff);
159
+ }
160
+ function decodeDCSuccessive(_component, zz) {
161
+ zz[0] |= readBit() << successive;
162
+ }
163
+ let eobrun = 0;
164
+ function decodeACFirst(component, zz) {
165
+ if (eobrun > 0) {
166
+ eobrun--;
167
+ return;
168
+ }
169
+ let k = spectralStart, e = spectralEnd;
170
+ while (k <= e) {
171
+ const rs = decodeHuffman(component.huffmanTableAC);
172
+ const s = rs & 15;
173
+ const r = rs >> 4;
174
+ if (s === 0) {
175
+ if (r < 15) {
176
+ eobrun = receive(r) + (1 << r) - 1;
177
+ break;
178
+ }
179
+ k += 16;
180
+ continue;
181
+ }
182
+ k += r;
183
+ const z = dctZigZag[k];
184
+ zz[z] = receiveAndExtend(s) * (1 << successive);
185
+ k++;
186
+ }
187
+ }
188
+ let successiveACState = 0;
189
+ let successiveACNextValue = 0;
190
+ function decodeACSuccessive(component, zz) {
191
+ let k = spectralStart;
192
+ let e = spectralEnd;
193
+ let r = 0;
194
+ while (k <= e) {
195
+ const z = dctZigZag[k];
196
+ const direction = zz[z] < 0 ? -1 : 1;
197
+ switch (successiveACState) {
198
+ case 0: // initial state
199
+ const rs = decodeHuffman(component.huffmanTableAC);
200
+ const s = rs & 15;
201
+ r = rs >> 4; // this was new variable in old code
202
+ if (s === 0) {
203
+ if (r < 15) {
204
+ eobrun = receive(r) + (1 << r);
205
+ successiveACState = 4;
206
+ }
207
+ else {
208
+ r = 16;
209
+ successiveACState = 1;
210
+ }
211
+ }
212
+ else {
213
+ if (s !== 1)
214
+ throw new Error('invalid ACn encoding');
215
+ successiveACNextValue = receiveAndExtend(s);
216
+ successiveACState = r ? 2 : 3;
217
+ }
218
+ continue;
219
+ case 1: // skipping r zero items
220
+ case 2:
221
+ if (zz[z]) {
222
+ zz[z] += (readBit() << successive) * direction;
223
+ }
224
+ else {
225
+ r--;
226
+ if (r === 0)
227
+ successiveACState = successiveACState == 2 ? 3 : 0;
228
+ }
229
+ break;
230
+ case 3: // set value for a zero item
231
+ if (zz[z]) {
232
+ zz[z] += (readBit() << successive) * direction;
233
+ }
234
+ else {
235
+ zz[z] = successiveACNextValue << successive;
236
+ successiveACState = 0;
237
+ }
238
+ break;
239
+ case 4: // eob
240
+ if (zz[z]) {
241
+ zz[z] += (readBit() << successive) * direction;
242
+ }
243
+ break;
244
+ }
245
+ k++;
246
+ }
247
+ if (successiveACState === 4) {
248
+ eobrun--;
249
+ if (eobrun === 0)
250
+ successiveACState = 0;
251
+ }
252
+ }
253
+ function decodeMcu(component, decode, mcu, row, col) {
254
+ const mcuRow = (mcu / mcusPerLine) | 0;
255
+ const mcuCol = mcu % mcusPerLine;
256
+ const blockRow = mcuRow * component.v + row;
257
+ const blockCol = mcuCol * component.h + col;
258
+ // If the block is missing, just skip it.
259
+ if (component.blocks[blockRow] === undefined)
260
+ return;
261
+ decode(component, component.blocks[blockRow][blockCol]);
262
+ }
263
+ function decodeBlock(component, decode, mcu) {
264
+ const blockRow = (mcu / component.blocksPerLine) | 0;
265
+ const blockCol = mcu % component.blocksPerLine;
266
+ // If the block is missing, just skip it.
267
+ if (component.blocks[blockRow] === undefined)
268
+ return;
269
+ decode(component, component.blocks[blockRow][blockCol]);
270
+ }
271
+ const componentsLength = components.length;
272
+ let component;
273
+ let decodeFn;
274
+ if (progressive) {
275
+ if (spectralStart === 0) {
276
+ decodeFn = successivePrev === 0 ? decodeDCFirst : decodeDCSuccessive;
277
+ }
278
+ else {
279
+ decodeFn = successivePrev === 0 ? decodeACFirst : decodeACSuccessive;
280
+ }
281
+ }
282
+ else {
283
+ decodeFn = decodeBaseline;
284
+ }
285
+ let mcu = 0;
286
+ let mcuExpected;
287
+ if (componentsLength == 1) {
288
+ mcuExpected = components[0].blocksPerLine * components[0].blocksPerColumn;
289
+ }
290
+ else {
291
+ mcuExpected = mcusPerLine * frame.mcusPerColumn;
292
+ }
293
+ if (!resetInterval)
294
+ resetInterval = mcuExpected;
295
+ let h;
296
+ let v;
297
+ let marker;
298
+ while (mcu < mcuExpected) {
299
+ // reset interval stuff
300
+ for (let i = 0; i < componentsLength; i++)
301
+ components[i].pred = 0;
302
+ eobrun = 0;
303
+ if (componentsLength == 1) {
304
+ component = components[0];
305
+ for (let n = 0; n < resetInterval; n++) {
306
+ decodeBlock(component, decodeFn, mcu);
307
+ mcu++;
308
+ }
309
+ }
310
+ else {
311
+ for (let n = 0; n < resetInterval; n++) {
312
+ for (let i = 0; i < componentsLength; i++) {
313
+ component = components[i];
314
+ h = component.h;
315
+ v = component.v;
316
+ for (let j = 0; j < v; j++) {
317
+ for (let k = 0; k < h; k++) {
318
+ decodeMcu(component, decodeFn, mcu, j, k);
319
+ }
320
+ }
321
+ }
322
+ mcu++;
323
+ // If we've reached our expected MCU's, stop decoding
324
+ if (mcu === mcuExpected)
325
+ break;
326
+ }
327
+ }
328
+ if (mcu === mcuExpected) {
329
+ // Skip trailing bytes at the end of the scan - until we reach the next marker
330
+ do {
331
+ if (data[offset] === 0xFF) {
332
+ if (data[offset + 1] !== 0x00) {
333
+ break;
334
+ }
335
+ }
336
+ offset += 1;
337
+ } while (offset < data.length - 2);
338
+ }
339
+ // find marker
340
+ bitsCount = 0;
341
+ marker = (data[offset] << 8) | data[offset + 1];
342
+ if (marker < 0xFF00)
343
+ throw new Error('marker was not found');
344
+ if (marker >= 0xFFD0 && marker <= 0xFFD7) { // RSTx
345
+ offset += 2;
346
+ }
347
+ else {
348
+ break;
349
+ }
350
+ }
351
+ return offset - startOffset;
352
+ }
353
+ function buildComponentData(component) {
354
+ const lines = [];
355
+ const blocksPerLine = component.blocksPerLine;
356
+ const blocksPerColumn = component.blocksPerColumn;
357
+ const samplesPerLine = blocksPerLine << 3;
358
+ // Only 1 used per invocation of this function and garbage collected after invocation, so no need to account for its memory footprint.
359
+ const R = new Int32Array(64);
360
+ const r = new Uint8Array(64);
361
+ // A port of poppler's IDCT method which in turn is taken from:
362
+ // Christoph Loeffler, Adriaan Ligtenberg, George S. Moschytz,
363
+ // "Practical Fast 1-D DCT Algorithms with 11 Multiplications",
364
+ // IEEE Intl. Conf. on Acoustics, Speech & Signal Processing, 1989,
365
+ // 988-991.
366
+ function quantizeAndInverse(zz, dataOut, dataIn) {
367
+ const qt = component.quantizationTable;
368
+ const p = dataIn;
369
+ // dequant
370
+ for (let i = 0; i < 64; i++) {
371
+ p[i] = zz[i] * qt[i];
372
+ }
373
+ // inverse DCT on rows
374
+ for (let i = 0; i < 8; ++i) {
375
+ const row = 8 * i;
376
+ // check for all-zero AC coefficients
377
+ if (p[1 + row] == 0 && p[2 + row] == 0 && p[3 + row] == 0 &&
378
+ p[4 + row] == 0 && p[5 + row] == 0 && p[6 + row] == 0 &&
379
+ p[7 + row] == 0) {
380
+ const t = (dctSqrt2 * p[0 + row] + 512) >> 10;
381
+ p[0 + row] = t;
382
+ p[1 + row] = t;
383
+ p[2 + row] = t;
384
+ p[3 + row] = t;
385
+ p[4 + row] = t;
386
+ p[5 + row] = t;
387
+ p[6 + row] = t;
388
+ p[7 + row] = t;
389
+ continue;
390
+ }
391
+ // stage 4
392
+ let v0 = (dctSqrt2 * p[0 + row] + 128) >> 8;
393
+ let v1 = (dctSqrt2 * p[4 + row] + 128) >> 8;
394
+ let v2 = p[2 + row];
395
+ let v3 = p[6 + row];
396
+ let v4 = (dctSqrt1d2 * (p[1 + row] - p[7 + row]) + 128) >> 8;
397
+ let v7 = (dctSqrt1d2 * (p[1 + row] + p[7 + row]) + 128) >> 8;
398
+ let v5 = p[3 + row] << 4;
399
+ let v6 = p[5 + row] << 4;
400
+ // stage 3
401
+ let t = (v0 - v1 + 1) >> 1;
402
+ v0 = (v0 + v1 + 1) >> 1;
403
+ v1 = t;
404
+ t = (v2 * dctSin6 + v3 * dctCos6 + 128) >> 8;
405
+ v2 = (v2 * dctCos6 - v3 * dctSin6 + 128) >> 8;
406
+ v3 = t;
407
+ t = (v4 - v6 + 1) >> 1;
408
+ v4 = (v4 + v6 + 1) >> 1;
409
+ v6 = t;
410
+ t = (v7 + v5 + 1) >> 1;
411
+ v5 = (v7 - v5 + 1) >> 1;
412
+ v7 = t;
413
+ // stage 2
414
+ t = (v0 - v3 + 1) >> 1;
415
+ v0 = (v0 + v3 + 1) >> 1;
416
+ v3 = t;
417
+ t = (v1 - v2 + 1) >> 1;
418
+ v1 = (v1 + v2 + 1) >> 1;
419
+ v2 = t;
420
+ t = (v4 * dctSin3 + v7 * dctCos3 + 2048) >> 12;
421
+ v4 = (v4 * dctCos3 - v7 * dctSin3 + 2048) >> 12;
422
+ v7 = t;
423
+ t = (v5 * dctSin1 + v6 * dctCos1 + 2048) >> 12;
424
+ v5 = (v5 * dctCos1 - v6 * dctSin1 + 2048) >> 12;
425
+ v6 = t;
426
+ // stage 1
427
+ p[0 + row] = v0 + v7;
428
+ p[7 + row] = v0 - v7;
429
+ p[1 + row] = v1 + v6;
430
+ p[6 + row] = v1 - v6;
431
+ p[2 + row] = v2 + v5;
432
+ p[5 + row] = v2 - v5;
433
+ p[3 + row] = v3 + v4;
434
+ p[4 + row] = v3 - v4;
435
+ }
436
+ // inverse DCT on columns
437
+ for (let i = 0; i < 8; ++i) {
438
+ const col = i;
439
+ // check for all-zero AC coefficients
440
+ if (p[1 * 8 + col] == 0 && p[2 * 8 + col] == 0 && p[3 * 8 + col] == 0 &&
441
+ p[4 * 8 + col] == 0 && p[5 * 8 + col] == 0 && p[6 * 8 + col] == 0 &&
442
+ p[7 * 8 + col] == 0) {
443
+ const t = (dctSqrt2 * dataIn[i + 0] + 8192) >> 14;
444
+ p[0 * 8 + col] = t;
445
+ p[1 * 8 + col] = t;
446
+ p[2 * 8 + col] = t;
447
+ p[3 * 8 + col] = t;
448
+ p[4 * 8 + col] = t;
449
+ p[5 * 8 + col] = t;
450
+ p[6 * 8 + col] = t;
451
+ p[7 * 8 + col] = t;
452
+ continue;
453
+ }
454
+ // stage 4
455
+ let v0 = (dctSqrt2 * p[0 * 8 + col] + 2048) >> 12;
456
+ let v1 = (dctSqrt2 * p[4 * 8 + col] + 2048) >> 12;
457
+ let v2 = p[2 * 8 + col];
458
+ let v3 = p[6 * 8 + col];
459
+ let v4 = (dctSqrt1d2 * (p[1 * 8 + col] - p[7 * 8 + col]) + 2048) >> 12;
460
+ let v7 = (dctSqrt1d2 * (p[1 * 8 + col] + p[7 * 8 + col]) + 2048) >> 12;
461
+ let v5 = p[3 * 8 + col];
462
+ let v6 = p[5 * 8 + col];
463
+ // stage 3
464
+ let t = (v0 - v1 + 1) >> 1;
465
+ v0 = (v0 + v1 + 1) >> 1;
466
+ v1 = t;
467
+ t = (v2 * dctSin6 + v3 * dctCos6 + 2048) >> 12;
468
+ v2 = (v2 * dctCos6 - v3 * dctSin6 + 2048) >> 12;
469
+ v3 = t;
470
+ t = (v4 - v6 + 1) >> 1;
471
+ v4 = (v4 + v6 + 1) >> 1;
472
+ v6 = t;
473
+ t = (v7 + v5 + 1) >> 1;
474
+ v5 = (v7 - v5 + 1) >> 1;
475
+ v7 = t;
476
+ // stage 2
477
+ t = (v0 - v3 + 1) >> 1;
478
+ v0 = (v0 + v3 + 1) >> 1;
479
+ v3 = t;
480
+ t = (v1 - v2 + 1) >> 1;
481
+ v1 = (v1 + v2 + 1) >> 1;
482
+ v2 = t;
483
+ t = (v4 * dctSin3 + v7 * dctCos3 + 2048) >> 12;
484
+ v4 = (v4 * dctCos3 - v7 * dctSin3 + 2048) >> 12;
485
+ v7 = t;
486
+ t = (v5 * dctSin1 + v6 * dctCos1 + 2048) >> 12;
487
+ v5 = (v5 * dctCos1 - v6 * dctSin1 + 2048) >> 12;
488
+ v6 = t;
489
+ // stage 1
490
+ p[0 * 8 + col] = v0 + v7;
491
+ p[7 * 8 + col] = v0 - v7;
492
+ p[1 * 8 + col] = v1 + v6;
493
+ p[6 * 8 + col] = v1 - v6;
494
+ p[2 * 8 + col] = v2 + v5;
495
+ p[5 * 8 + col] = v2 - v5;
496
+ p[3 * 8 + col] = v3 + v4;
497
+ p[4 * 8 + col] = v3 - v4;
498
+ }
499
+ // convert to 8-bit integers
500
+ for (let i = 0; i < 64; ++i) {
501
+ const sample = 128 + ((p[i] + 8) >> 4);
502
+ dataOut[i] = sample < 0 ? 0 : sample > 0xFF ? 0xFF : sample;
503
+ }
504
+ }
505
+ requestMemoryAllocation(samplesPerLine * blocksPerColumn * 8);
506
+ for (let blockRow = 0; blockRow < blocksPerColumn; blockRow++) {
507
+ const scanLine = blockRow << 3;
508
+ for (let i = 0; i < 8; i++)
509
+ lines.push(new Uint8Array(samplesPerLine));
510
+ for (let blockCol = 0; blockCol < blocksPerLine; blockCol++) {
511
+ quantizeAndInverse(component.blocks[blockRow][blockCol], r, R);
512
+ let offset = 0;
513
+ const sample = blockCol << 3;
514
+ for (let j = 0; j < 8; j++) {
515
+ const line = lines[scanLine + j];
516
+ for (let i = 0; i < 8; i++)
517
+ line[sample + i] = r[offset++];
518
+ }
519
+ }
520
+ }
521
+ return lines;
522
+ }
523
+ function clampTo8bit(a) {
524
+ return a < 0 ? 0 : a > 255 ? 255 : a;
525
+ }
526
+ function parse(data) {
527
+ const self = {
528
+ width: 0,
529
+ height: 0,
530
+ comments: [],
531
+ adobe: undefined,
532
+ components: [],
533
+ exifBuffer: undefined,
534
+ jfif: undefined,
535
+ };
536
+ const maxResolutionInPixels = maxResolutionInMP * 1000 * 1000;
537
+ let offset = 0;
538
+ function readUint16() {
539
+ const value = (data[offset] << 8) | data[offset + 1];
540
+ offset += 2;
541
+ return value;
542
+ }
543
+ function readDataBlock() {
544
+ const length = readUint16();
545
+ const array = data.subarray(offset, offset + length - 2);
546
+ offset += array.length;
547
+ return array;
548
+ }
549
+ function prepareComponents(frame) {
550
+ let maxH = 0, maxV = 0;
551
+ for (let componentId in frame.components) {
552
+ if (frame.components.hasOwnProperty(componentId)) {
553
+ const component = frame.components[componentId];
554
+ if (maxH < component.h)
555
+ maxH = component.h;
556
+ if (maxV < component.v)
557
+ maxV = component.v;
558
+ }
559
+ }
560
+ const mcusPerLine = Math.ceil(frame.samplesPerLine / 8 / maxH);
561
+ const mcusPerColumn = Math.ceil(frame.scanLines / 8 / maxV);
562
+ for (let componentId in frame.components) {
563
+ if (frame.components.hasOwnProperty(componentId)) {
564
+ const component = frame.components[componentId];
565
+ const blocksPerLine = Math.ceil(Math.ceil(frame.samplesPerLine / 8) * component.h / maxH);
566
+ const blocksPerColumn = Math.ceil(Math.ceil(frame.scanLines / 8) * component.v / maxV);
567
+ const blocksPerLineForMcu = mcusPerLine * component.h;
568
+ const blocksPerColumnForMcu = mcusPerColumn * component.v;
569
+ const blocksToAllocate = blocksPerColumnForMcu * blocksPerLineForMcu;
570
+ const blocks = [];
571
+ // Each block is a Int32Array of length 64 (4 x 64 = 256 bytes)
572
+ requestMemoryAllocation(blocksToAllocate * 256);
573
+ for (let i = 0; i < blocksPerColumnForMcu; i++) {
574
+ const row = [];
575
+ for (let j = 0; j < blocksPerLineForMcu; j++) {
576
+ row.push(new Int32Array(64));
577
+ }
578
+ blocks.push(row);
579
+ }
580
+ component.blocksPerLine = blocksPerLine;
581
+ component.blocksPerColumn = blocksPerColumn;
582
+ component.blocks = blocks;
583
+ }
584
+ }
585
+ frame.maxH = maxH;
586
+ frame.maxV = maxV;
587
+ frame.mcusPerLine = mcusPerLine;
588
+ frame.mcusPerColumn = mcusPerColumn;
589
+ }
590
+ let jfif = null;
591
+ let adobe = null;
592
+ let frame = undefined;
593
+ let resetInterval = 0;
594
+ let quantizationTables = [];
595
+ let frames = [];
596
+ let huffmanTablesAC = [];
597
+ let huffmanTablesDC = [];
598
+ let fileMarker = readUint16();
599
+ let malformedDataOffset = -1;
600
+ if (fileMarker != 0xFFD8) { // SOI (Start of Image)
601
+ throw new Error('SOI not found');
602
+ }
603
+ fileMarker = readUint16();
604
+ while (fileMarker != 0xFFD9) { // EOI (End of image)
605
+ switch (fileMarker) {
606
+ case 0xFF00: break;
607
+ case 0xFFE0: // APP0 (Application Specific)
608
+ case 0xFFE1: // APP1
609
+ case 0xFFE2: // APP2
610
+ case 0xFFE3: // APP3
611
+ case 0xFFE4: // APP4
612
+ case 0xFFE5: // APP5
613
+ case 0xFFE6: // APP6
614
+ case 0xFFE7: // APP7
615
+ case 0xFFE8: // APP8
616
+ case 0xFFE9: // APP9
617
+ case 0xFFEA: // APP10
618
+ case 0xFFEB: // APP11
619
+ case 0xFFEC: // APP12
620
+ case 0xFFED: // APP13
621
+ case 0xFFEE: // APP14
622
+ case 0xFFEF: // APP15
623
+ case 0xFFFE: { // COM (Comment)
624
+ const appData = readDataBlock();
625
+ if (fileMarker === 0xFFFE) {
626
+ let comment = '';
627
+ for (let ii = 0; ii < appData.byteLength; ii++) {
628
+ comment += String.fromCharCode(appData[ii]);
629
+ }
630
+ self.comments.push(comment);
631
+ }
632
+ if (fileMarker === 0xFFE0) {
633
+ if (appData[0] === 0x4A && appData[1] === 0x46 && appData[2] === 0x49 &&
634
+ appData[3] === 0x46 && appData[4] === 0) { // 'JFIF\x00'
635
+ jfif = {
636
+ version: { major: appData[5], minor: appData[6] },
637
+ densityUnits: appData[7],
638
+ xDensity: (appData[8] << 8) | appData[9],
639
+ yDensity: (appData[10] << 8) | appData[11],
640
+ thumbWidth: appData[12],
641
+ thumbHeight: appData[13],
642
+ thumbData: appData.subarray(14, 14 + 3 * appData[12] * appData[13])
643
+ };
644
+ }
645
+ }
646
+ // TODO APP1 - Exif
647
+ if (fileMarker === 0xFFE1) {
648
+ if (appData[0] === 0x45 &&
649
+ appData[1] === 0x78 &&
650
+ appData[2] === 0x69 &&
651
+ appData[3] === 0x66 &&
652
+ appData[4] === 0) { // 'EXIF\x00'
653
+ self.exifBuffer = appData.subarray(5, appData.length);
654
+ }
655
+ }
656
+ if (fileMarker === 0xFFEE) {
657
+ if (appData[0] === 0x41 && appData[1] === 0x64 && appData[2] === 0x6F &&
658
+ appData[3] === 0x62 && appData[4] === 0x65 && appData[5] === 0) { // 'Adobe\x00'
659
+ adobe = {
660
+ version: appData[6],
661
+ flags0: (appData[7] << 8) | appData[8],
662
+ flags1: (appData[9] << 8) | appData[10],
663
+ transformCode: appData[11]
664
+ };
665
+ }
666
+ }
667
+ break;
668
+ }
669
+ case 0xFFDB: { // DQT (Define Quantization Tables)
670
+ const quantizationTablesLength = readUint16();
671
+ const quantizationTablesEnd = quantizationTablesLength + offset - 2;
672
+ while (offset < quantizationTablesEnd) {
673
+ const quantizationTableSpec = data[offset++];
674
+ requestMemoryAllocation(64 * 4);
675
+ const tableData = new Int32Array(64);
676
+ if ((quantizationTableSpec >> 4) === 0) { // 8 bit values
677
+ for (let j = 0; j < 64; j++) {
678
+ const z = dctZigZag[j];
679
+ tableData[z] = data[offset++];
680
+ }
681
+ }
682
+ else if ((quantizationTableSpec >> 4) === 1) { //16 bit
683
+ for (let j = 0; j < 64; j++) {
684
+ const z = dctZigZag[j];
685
+ tableData[z] = readUint16();
686
+ }
687
+ }
688
+ else
689
+ throw new Error('DQT: invalid table spec');
690
+ quantizationTables[quantizationTableSpec & 15] = tableData;
691
+ }
692
+ break;
693
+ }
694
+ case 0xFFC0: // SOF0 (Start of Frame, Baseline DCT)
695
+ case 0xFFC1: // SOF1 (Start of Frame, Extended DCT)
696
+ case 0xFFC2: { // SOF2 (Start of Frame, Progressive DCT)
697
+ readUint16(); // skip data length
698
+ frame = {
699
+ extended: (fileMarker === 0xFFC1),
700
+ progressive: (fileMarker === 0xFFC2),
701
+ precision: data[offset++],
702
+ scanLines: readUint16(),
703
+ samplesPerLine: readUint16(),
704
+ components: {},
705
+ componentsOrder: [],
706
+ maxH: 0,
707
+ maxV: 0,
708
+ mcusPerLine: 0,
709
+ mcusPerColumn: 0,
710
+ };
711
+ const pixelsInFrame = frame.scanLines * frame.samplesPerLine;
712
+ if (pixelsInFrame > maxResolutionInPixels) {
713
+ const exceededAmount = Math.ceil((pixelsInFrame - maxResolutionInPixels) / 1e6);
714
+ throw new Error(`maxResolutionInMP limit exceeded by ${exceededAmount}MP`);
715
+ }
716
+ const componentsCount = data[offset++];
717
+ for (let i = 0; i < componentsCount; i++) {
718
+ const componentId = data[offset];
719
+ const h = data[offset + 1] >> 4;
720
+ const v = data[offset + 1] & 15;
721
+ const qId = data[offset + 2];
722
+ frame.componentsOrder.push(componentId);
723
+ frame.components[componentId] = {
724
+ h: h,
725
+ v: v,
726
+ quantizationIdx: qId,
727
+ blocksPerColumn: 0,
728
+ blocksPerLine: 0,
729
+ blocks: [],
730
+ pred: 0,
731
+ };
732
+ offset += 3;
733
+ }
734
+ prepareComponents(frame);
735
+ frames.push(frame);
736
+ break;
737
+ }
738
+ case 0xFFC4: { // DHT (Define Huffman Tables)
739
+ const huffmanLength = readUint16();
740
+ for (let i = 2; i < huffmanLength;) {
741
+ const huffmanTableSpec = data[offset++];
742
+ const codeLengths = new Uint8Array(16);
743
+ let codeLengthSum = 0;
744
+ for (let j = 0; j < 16; j++, offset++) {
745
+ codeLengthSum += (codeLengths[j] = data[offset]);
746
+ }
747
+ requestMemoryAllocation(16 + codeLengthSum);
748
+ const huffmanValues = new Uint8Array(codeLengthSum);
749
+ for (let j = 0; j < codeLengthSum; j++, offset++) {
750
+ huffmanValues[j] = data[offset];
751
+ }
752
+ i += 17 + codeLengthSum;
753
+ const index = huffmanTableSpec & 15;
754
+ const table = (huffmanTableSpec >> 4) === 0 ? huffmanTablesDC : huffmanTablesAC;
755
+ table[index] = buildHuffmanTable(codeLengths, huffmanValues);
756
+ }
757
+ break;
758
+ }
759
+ case 0xFFDD: // DRI (Define Restart Interval)
760
+ readUint16(); // skip data length
761
+ resetInterval = readUint16();
762
+ break;
763
+ case 0xFFDC: // Number of Lines marker
764
+ readUint16(); // skip data length
765
+ readUint16(); // Ignore this data since it represents the image height
766
+ break;
767
+ case 0xFFDA: { // SOS (Start of Scan)
768
+ readUint16(); // skip data length
769
+ const selectorsCount = data[offset++];
770
+ const components = [];
771
+ for (let i = 0; i < selectorsCount; i++) {
772
+ const component = frame.components[data[offset++]];
773
+ const tableSpec = data[offset++];
774
+ component.huffmanTableDC = huffmanTablesDC[tableSpec >> 4];
775
+ component.huffmanTableAC = huffmanTablesAC[tableSpec & 15];
776
+ components.push(component);
777
+ }
778
+ const spectralStart = data[offset++];
779
+ const spectralEnd = data[offset++];
780
+ const successiveApproximation = data[offset++];
781
+ const processed = decodeScan(data, offset, frame, components, resetInterval, spectralStart, spectralEnd, successiveApproximation >> 4, successiveApproximation & 15);
782
+ offset += processed;
783
+ break;
784
+ }
785
+ case 0xFFFF: // Fill bytes
786
+ if (data[offset] !== 0xFF) { // Avoid skipping a valid marker.
787
+ offset--;
788
+ }
789
+ break;
790
+ default: {
791
+ if (data[offset - 3] == 0xFF && data[offset - 2] >= 0xC0 && data[offset - 2] <= 0xFE) {
792
+ // could be incorrect encoding -- last 0xFF byte of the previous
793
+ // block was eaten by the encoder
794
+ offset -= 3;
795
+ break;
796
+ }
797
+ else if (fileMarker === 0xE0 || fileMarker == 0xE1) {
798
+ // Recover from malformed APP1 markers popular in some phone models.
799
+ // See https://github.com/eugeneware/jpeg-js/issues/82
800
+ if (malformedDataOffset !== -1) {
801
+ throw new Error(`first unknown JPEG marker at offset ${malformedDataOffset.toString(16)}, second unknown JPEG marker ${fileMarker.toString(16)} at offset ${(offset - 1).toString(16)}`);
802
+ }
803
+ malformedDataOffset = offset - 1;
804
+ const nextOffset = readUint16();
805
+ if (data[offset + nextOffset - 2] === 0xFF) {
806
+ offset += nextOffset - 2;
807
+ break;
808
+ }
809
+ }
810
+ throw new Error('unknown JPEG marker ' + fileMarker.toString(16));
811
+ }
812
+ }
813
+ fileMarker = readUint16();
814
+ }
815
+ if (frames.length != 1)
816
+ throw new Error('only single frame JPEGs supported');
817
+ // set each frame's components quantization table
818
+ for (let i = 0; i < frames.length; i++) {
819
+ const cp = frames[i].components;
820
+ for (let j in cp) { // TODO: don't use `in`
821
+ cp[j].quantizationTable = quantizationTables[cp[j].quantizationIdx];
822
+ delete cp[j].quantizationIdx; // TODO: why ???
823
+ }
824
+ }
825
+ self.width = frame.samplesPerLine;
826
+ self.height = frame.scanLines;
827
+ self.jfif = jfif;
828
+ self.adobe = adobe;
829
+ self.components = [];
830
+ for (let i = 0; i < frame.componentsOrder.length; i++) {
831
+ const component = frame.components[frame.componentsOrder[i]];
832
+ self.components.push({
833
+ lines: buildComponentData(component),
834
+ scaleX: component.h / frame.maxH,
835
+ scaleY: component.v / frame.maxV
836
+ });
837
+ }
838
+ return self;
839
+ }
840
+ function getData(decoded) {
841
+ let offset = 0;
842
+ let colorTransform = false;
843
+ const width = decoded.width;
844
+ const height = decoded.height;
845
+ const dataLength = width * height * decoded.components.length;
846
+ requestMemoryAllocation(dataLength);
847
+ const data = new Uint8Array(dataLength);
848
+ switch (decoded.components.length) {
849
+ case 1: {
850
+ const component1 = decoded.components[0];
851
+ for (let y = 0; y < height; y++) {
852
+ const component1Line = component1.lines[0 | (y * component1.scaleY)];
853
+ for (let x = 0; x < width; x++) {
854
+ const Y = component1Line[0 | (x * component1.scaleX)];
855
+ data[offset++] = Y;
856
+ }
857
+ }
858
+ break;
859
+ }
860
+ case 2: {
861
+ // PDF might compress two component data in custom colorspace
862
+ const component1 = decoded.components[0];
863
+ const component2 = decoded.components[1];
864
+ for (let y = 0; y < height; y++) {
865
+ const component1Line = component1.lines[0 | (y * component1.scaleY)];
866
+ const component2Line = component2.lines[0 | (y * component2.scaleY)];
867
+ for (let x = 0; x < width; x++) {
868
+ const Y1 = component1Line[0 | (x * component1.scaleX)];
869
+ data[offset++] = Y1;
870
+ const Y2 = component2Line[0 | (x * component2.scaleX)];
871
+ data[offset++] = Y2;
872
+ }
873
+ }
874
+ break;
875
+ }
876
+ case 3: {
877
+ // The default transform for three components is true
878
+ colorTransform = true;
879
+ // The adobe transform marker overrides any previous setting
880
+ if (decoded.adobe && decoded.adobe.transformCode)
881
+ colorTransform = true;
882
+ const component1 = decoded.components[0];
883
+ const component2 = decoded.components[1];
884
+ const component3 = decoded.components[2];
885
+ for (let y = 0; y < height; y++) {
886
+ const component1Line = component1.lines[0 | (y * component1.scaleY)];
887
+ const component2Line = component2.lines[0 | (y * component2.scaleY)];
888
+ const component3Line = component3.lines[0 | (y * component3.scaleY)];
889
+ for (let x = 0; x < width; x++) {
890
+ let Y, Cb, Cr, R, G, B;
891
+ if (!colorTransform) {
892
+ R = component1Line[0 | (x * component1.scaleX)];
893
+ G = component2Line[0 | (x * component2.scaleX)];
894
+ B = component3Line[0 | (x * component3.scaleX)];
895
+ }
896
+ else {
897
+ Y = component1Line[0 | (x * component1.scaleX)];
898
+ Cb = component2Line[0 | (x * component2.scaleX)];
899
+ Cr = component3Line[0 | (x * component3.scaleX)];
900
+ R = clampTo8bit(Y + 1.402 * (Cr - 128));
901
+ G = clampTo8bit(Y - 0.3441363 * (Cb - 128) - 0.71413636 * (Cr - 128));
902
+ B = clampTo8bit(Y + 1.772 * (Cb - 128));
903
+ }
904
+ data[offset++] = R;
905
+ data[offset++] = G;
906
+ data[offset++] = B;
907
+ }
908
+ }
909
+ break;
910
+ }
911
+ case 4: {
912
+ if (!decoded.adobe)
913
+ throw new Error('Unsupported color mode (4 components)');
914
+ // The default transform for four components is false
915
+ colorTransform = false;
916
+ // The adobe transform marker overrides any previous setting
917
+ if (decoded.adobe && decoded.adobe.transformCode)
918
+ colorTransform = true;
919
+ const component1 = decoded.components[0];
920
+ const component2 = decoded.components[1];
921
+ const component3 = decoded.components[2];
922
+ const component4 = decoded.components[3];
923
+ for (let y = 0; y < height; y++) {
924
+ const component1Line = component1.lines[0 | (y * component1.scaleY)];
925
+ const component2Line = component2.lines[0 | (y * component2.scaleY)];
926
+ const component3Line = component3.lines[0 | (y * component3.scaleY)];
927
+ const component4Line = component4.lines[0 | (y * component4.scaleY)];
928
+ for (let x = 0; x < width; x++) {
929
+ let Y, Cb, Cr, K, C, M, Ye;
930
+ if (!colorTransform) {
931
+ C = component1Line[0 | (x * component1.scaleX)];
932
+ M = component2Line[0 | (x * component2.scaleX)];
933
+ Ye = component3Line[0 | (x * component3.scaleX)];
934
+ K = component4Line[0 | (x * component4.scaleX)];
935
+ }
936
+ else {
937
+ Y = component1Line[0 | (x * component1.scaleX)];
938
+ Cb = component2Line[0 | (x * component2.scaleX)];
939
+ Cr = component3Line[0 | (x * component3.scaleX)];
940
+ K = component4Line[0 | (x * component4.scaleX)];
941
+ C = 255 - clampTo8bit(Y + 1.402 * (Cr - 128));
942
+ M = 255 - clampTo8bit(Y - 0.3441363 * (Cb - 128) - 0.71413636 * (Cr - 128));
943
+ Ye = 255 - clampTo8bit(Y + 1.772 * (Cb - 128));
944
+ }
945
+ data[offset++] = 255 - C;
946
+ data[offset++] = 255 - M;
947
+ data[offset++] = 255 - Ye;
948
+ data[offset++] = 255 - K;
949
+ }
950
+ }
951
+ break;
952
+ }
953
+ default:
954
+ throw new Error('Unsupported color mode');
955
+ }
956
+ return data;
957
+ }
958
+ export function decodeJpeg(encoded, createImageData) {
959
+ totalBytesAllocated = 0;
960
+ if (encoded.length === 0)
961
+ throw new Error('Empty jpeg buffer');
962
+ const decoded = parse(encoded);
963
+ requestMemoryAllocation(decoded.width * decoded.height * 4);
964
+ const data = getData(decoded);
965
+ const imageData = createImageData(decoded.width, decoded.height);
966
+ const width = imageData.width;
967
+ const height = imageData.height;
968
+ const imageDataArray = imageData.data;
969
+ let i = 0;
970
+ let j = 0;
971
+ switch (decoded.components.length) {
972
+ case 1:
973
+ for (let y = 0; y < height; y++) {
974
+ for (let x = 0; x < width; x++) {
975
+ const Y = data[i++];
976
+ imageDataArray[j++] = Y;
977
+ imageDataArray[j++] = Y;
978
+ imageDataArray[j++] = Y;
979
+ imageDataArray[j++] = 255;
980
+ }
981
+ }
982
+ break;
983
+ case 3:
984
+ for (let y = 0; y < height; y++) {
985
+ for (let x = 0; x < width; x++) {
986
+ const R = data[i++];
987
+ const G = data[i++];
988
+ const B = data[i++];
989
+ imageDataArray[j++] = R;
990
+ imageDataArray[j++] = G;
991
+ imageDataArray[j++] = B;
992
+ imageDataArray[j++] = 255;
993
+ }
994
+ }
995
+ break;
996
+ case 4:
997
+ for (let y = 0; y < height; y++) {
998
+ for (let x = 0; x < width; x++) {
999
+ const C = data[i++];
1000
+ const M = data[i++];
1001
+ const Y = data[i++];
1002
+ const K = data[i++];
1003
+ const R = 255 - clampTo8bit(C * (1 - K / 255) + K);
1004
+ const G = 255 - clampTo8bit(M * (1 - K / 255) + K);
1005
+ const B = 255 - clampTo8bit(Y * (1 - K / 255) + K);
1006
+ imageDataArray[j++] = R;
1007
+ imageDataArray[j++] = G;
1008
+ imageDataArray[j++] = B;
1009
+ imageDataArray[j++] = 255;
1010
+ }
1011
+ }
1012
+ break;
1013
+ default:
1014
+ throw new Error('Unsupported color mode');
1015
+ }
1016
+ return imageData;
1017
+ }