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