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