forked from mozilla/pdf.js
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathjpx.js
More file actions
2354 lines (2225 loc) · 75.2 KB
/
jpx.js
File metadata and controls
2354 lines (2225 loc) · 75.2 KB
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
/* Copyright 2012 Mozilla Foundation
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import { BaseException, info, unreachable, warn } from "../shared/util.js";
import { log2, readUint16, readUint32 } from "./core_utils.js";
import { ArithmeticDecoder } from "./arithmetic_decoder.js";
class JpxError extends BaseException {
constructor(msg) {
super(`JPX error: ${msg}`, "JpxError");
}
}
// Table E.1
const SubbandsGainLog2 = {
LL: 0,
LH: 1,
HL: 1,
HH: 2,
};
class JpxImage {
constructor() {
this.failOnCorruptedImage = false;
}
parse(data) {
const head = readUint16(data, 0);
// No box header, immediate start of codestream (SOC)
if (head === 0xff4f) {
this.parseCodestream(data, 0, data.length);
return;
}
const length = data.length;
let position = 0;
while (position < length) {
let headerSize = 8;
let lbox = readUint32(data, position);
const tbox = readUint32(data, position + 4);
position += headerSize;
if (lbox === 1) {
// XLBox: read UInt64 according to spec.
// JavaScript's int precision of 53 bit should be sufficient here.
lbox =
readUint32(data, position) * 4294967296 +
readUint32(data, position + 4);
position += 8;
headerSize += 8;
}
if (lbox === 0) {
lbox = length - position + headerSize;
}
if (lbox < headerSize) {
throw new JpxError("Invalid box field size");
}
const dataLength = lbox - headerSize;
let jumpDataLength = true;
switch (tbox) {
case 0x6a703268: // 'jp2h'
jumpDataLength = false; // parsing child boxes
break;
case 0x636f6c72: // 'colr'
// Colorspaces are not used, the CS from the PDF is used.
const method = data[position];
if (method === 1) {
// enumerated colorspace
const colorspace = readUint32(data, position + 3);
switch (colorspace) {
case 16: // this indicates a sRGB colorspace
case 17: // this indicates a grayscale colorspace
case 18: // this indicates a YUV colorspace
break;
default:
warn("Unknown colorspace " + colorspace);
break;
}
} else if (method === 2) {
info("ICC profile not supported");
}
break;
case 0x6a703263: // 'jp2c'
this.parseCodestream(data, position, position + dataLength);
break;
case 0x6a502020: // 'jP\024\024'
if (readUint32(data, position) !== 0x0d0a870a) {
warn("Invalid JP2 signature");
}
break;
// The following header types are valid but currently not used:
case 0x6a501a1a: // 'jP\032\032'
case 0x66747970: // 'ftyp'
case 0x72726571: // 'rreq'
case 0x72657320: // 'res '
case 0x69686472: // 'ihdr'
break;
default:
const headerType = String.fromCharCode(
(tbox >> 24) & 0xff,
(tbox >> 16) & 0xff,
(tbox >> 8) & 0xff,
tbox & 0xff
);
warn(`Unsupported header type ${tbox} (${headerType}).`);
break;
}
if (jumpDataLength) {
position += dataLength;
}
}
}
parseImageProperties(stream) {
let newByte = stream.getByte();
while (newByte >= 0) {
const oldByte = newByte;
newByte = stream.getByte();
const code = (oldByte << 8) | newByte;
// Image and tile size (SIZ)
if (code === 0xff51) {
stream.skip(4);
const Xsiz = stream.getInt32() >>> 0; // Byte 4
const Ysiz = stream.getInt32() >>> 0; // Byte 8
const XOsiz = stream.getInt32() >>> 0; // Byte 12
const YOsiz = stream.getInt32() >>> 0; // Byte 16
stream.skip(16);
const Csiz = stream.getUint16(); // Byte 36
this.width = Xsiz - XOsiz;
this.height = Ysiz - YOsiz;
this.componentsCount = Csiz;
// Results are always returned as `Uint8ClampedArray`s.
this.bitsPerComponent = 8;
return;
}
}
throw new JpxError("No size marker found in JPX stream");
}
parseCodestream(data, start, end) {
const context = {};
let doNotRecover = false;
try {
let position = start;
while (position + 1 < end) {
const code = readUint16(data, position);
position += 2;
let length = 0,
j,
sqcd,
spqcds,
spqcdSize,
scalarExpounded,
tile;
switch (code) {
case 0xff4f: // Start of codestream (SOC)
context.mainHeader = true;
break;
case 0xffd9: // End of codestream (EOC)
break;
case 0xff51: // Image and tile size (SIZ)
length = readUint16(data, position);
const siz = {};
siz.Xsiz = readUint32(data, position + 4);
siz.Ysiz = readUint32(data, position + 8);
siz.XOsiz = readUint32(data, position + 12);
siz.YOsiz = readUint32(data, position + 16);
siz.XTsiz = readUint32(data, position + 20);
siz.YTsiz = readUint32(data, position + 24);
siz.XTOsiz = readUint32(data, position + 28);
siz.YTOsiz = readUint32(data, position + 32);
const componentsCount = readUint16(data, position + 36);
siz.Csiz = componentsCount;
const components = [];
j = position + 38;
for (let i = 0; i < componentsCount; i++) {
const component = {
precision: (data[j] & 0x7f) + 1,
isSigned: !!(data[j] & 0x80),
XRsiz: data[j + 1],
YRsiz: data[j + 2],
};
j += 3;
calculateComponentDimensions(component, siz);
components.push(component);
}
context.SIZ = siz;
context.components = components;
calculateTileGrids(context, components);
context.QCC = [];
context.COC = [];
break;
case 0xff5c: // Quantization default (QCD)
length = readUint16(data, position);
const qcd = {};
j = position + 2;
sqcd = data[j++];
switch (sqcd & 0x1f) {
case 0:
spqcdSize = 8;
scalarExpounded = true;
break;
case 1:
spqcdSize = 16;
scalarExpounded = false;
break;
case 2:
spqcdSize = 16;
scalarExpounded = true;
break;
default:
throw new Error("Invalid SQcd value " + sqcd);
}
qcd.noQuantization = spqcdSize === 8;
qcd.scalarExpounded = scalarExpounded;
qcd.guardBits = sqcd >> 5;
spqcds = [];
while (j < length + position) {
const spqcd = {};
if (spqcdSize === 8) {
spqcd.epsilon = data[j++] >> 3;
spqcd.mu = 0;
} else {
spqcd.epsilon = data[j] >> 3;
spqcd.mu = ((data[j] & 0x7) << 8) | data[j + 1];
j += 2;
}
spqcds.push(spqcd);
}
qcd.SPqcds = spqcds;
if (context.mainHeader) {
context.QCD = qcd;
} else {
context.currentTile.QCD = qcd;
context.currentTile.QCC = [];
}
break;
case 0xff5d: // Quantization component (QCC)
length = readUint16(data, position);
const qcc = {};
j = position + 2;
let cqcc;
if (context.SIZ.Csiz < 257) {
cqcc = data[j++];
} else {
cqcc = readUint16(data, j);
j += 2;
}
sqcd = data[j++];
switch (sqcd & 0x1f) {
case 0:
spqcdSize = 8;
scalarExpounded = true;
break;
case 1:
spqcdSize = 16;
scalarExpounded = false;
break;
case 2:
spqcdSize = 16;
scalarExpounded = true;
break;
default:
throw new Error("Invalid SQcd value " + sqcd);
}
qcc.noQuantization = spqcdSize === 8;
qcc.scalarExpounded = scalarExpounded;
qcc.guardBits = sqcd >> 5;
spqcds = [];
while (j < length + position) {
const spqcd = {};
if (spqcdSize === 8) {
spqcd.epsilon = data[j++] >> 3;
spqcd.mu = 0;
} else {
spqcd.epsilon = data[j] >> 3;
spqcd.mu = ((data[j] & 0x7) << 8) | data[j + 1];
j += 2;
}
spqcds.push(spqcd);
}
qcc.SPqcds = spqcds;
if (context.mainHeader) {
context.QCC[cqcc] = qcc;
} else {
context.currentTile.QCC[cqcc] = qcc;
}
break;
case 0xff52: // Coding style default (COD)
length = readUint16(data, position);
const cod = {};
j = position + 2;
const scod = data[j++];
cod.entropyCoderWithCustomPrecincts = !!(scod & 1);
cod.sopMarkerUsed = !!(scod & 2);
cod.ephMarkerUsed = !!(scod & 4);
cod.progressionOrder = data[j++];
cod.layersCount = readUint16(data, j);
j += 2;
cod.multipleComponentTransform = data[j++];
cod.decompositionLevelsCount = data[j++];
cod.xcb = (data[j++] & 0xf) + 2;
cod.ycb = (data[j++] & 0xf) + 2;
const blockStyle = data[j++];
cod.selectiveArithmeticCodingBypass = !!(blockStyle & 1);
cod.resetContextProbabilities = !!(blockStyle & 2);
cod.terminationOnEachCodingPass = !!(blockStyle & 4);
cod.verticallyStripe = !!(blockStyle & 8);
cod.predictableTermination = !!(blockStyle & 16);
cod.segmentationSymbolUsed = !!(blockStyle & 32);
cod.reversibleTransformation = data[j++];
if (cod.entropyCoderWithCustomPrecincts) {
const precinctsSizes = [];
while (j < length + position) {
const precinctsSize = data[j++];
precinctsSizes.push({
PPx: precinctsSize & 0xf,
PPy: precinctsSize >> 4,
});
}
cod.precinctsSizes = precinctsSizes;
}
const unsupported = [];
if (cod.selectiveArithmeticCodingBypass) {
unsupported.push("selectiveArithmeticCodingBypass");
}
if (cod.terminationOnEachCodingPass) {
unsupported.push("terminationOnEachCodingPass");
}
if (cod.verticallyStripe) {
unsupported.push("verticallyStripe");
}
if (cod.predictableTermination) {
unsupported.push("predictableTermination");
}
if (unsupported.length > 0) {
doNotRecover = true;
warn(`JPX: Unsupported COD options (${unsupported.join(", ")}).`);
}
if (context.mainHeader) {
context.COD = cod;
} else {
context.currentTile.COD = cod;
context.currentTile.COC = [];
}
break;
case 0xff90: // Start of tile-part (SOT)
length = readUint16(data, position);
tile = {};
tile.index = readUint16(data, position + 2);
tile.length = readUint32(data, position + 4);
tile.dataEnd = tile.length + position - 2;
tile.partIndex = data[position + 8];
tile.partsCount = data[position + 9];
context.mainHeader = false;
if (tile.partIndex === 0) {
// reset component specific settings
tile.COD = context.COD;
tile.COC = context.COC.slice(0); // clone of the global COC
tile.QCD = context.QCD;
tile.QCC = context.QCC.slice(0); // clone of the global COC
}
context.currentTile = tile;
break;
case 0xff93: // Start of data (SOD)
tile = context.currentTile;
if (tile.partIndex === 0) {
initializeTile(context, tile.index);
buildPackets(context);
}
// moving to the end of the data
length = tile.dataEnd - position;
parseTilePackets(context, data, position, length);
break;
case 0xff53: // Coding style component (COC)
warn("JPX: Codestream code 0xFF53 (COC) is not implemented.");
/* falls through */
case 0xff55: // Tile-part lengths, main header (TLM)
case 0xff57: // Packet length, main header (PLM)
case 0xff58: // Packet length, tile-part header (PLT)
case 0xff64: // Comment (COM)
length = readUint16(data, position);
// skipping content
break;
default:
throw new Error("Unknown codestream code: " + code.toString(16));
}
position += length;
}
} catch (e) {
if (doNotRecover || this.failOnCorruptedImage) {
throw new JpxError(e.message);
} else {
warn(`JPX: Trying to recover from: "${e.message}".`);
}
}
this.tiles = transformComponents(context);
this.width = context.SIZ.Xsiz - context.SIZ.XOsiz;
this.height = context.SIZ.Ysiz - context.SIZ.YOsiz;
this.componentsCount = context.SIZ.Csiz;
}
}
function calculateComponentDimensions(component, siz) {
// Section B.2 Component mapping
component.x0 = Math.ceil(siz.XOsiz / component.XRsiz);
component.x1 = Math.ceil(siz.Xsiz / component.XRsiz);
component.y0 = Math.ceil(siz.YOsiz / component.YRsiz);
component.y1 = Math.ceil(siz.Ysiz / component.YRsiz);
component.width = component.x1 - component.x0;
component.height = component.y1 - component.y0;
}
function calculateTileGrids(context, components) {
const siz = context.SIZ;
// Section B.3 Division into tile and tile-components
const tiles = [];
let tile;
const numXtiles = Math.ceil((siz.Xsiz - siz.XTOsiz) / siz.XTsiz);
const numYtiles = Math.ceil((siz.Ysiz - siz.YTOsiz) / siz.YTsiz);
for (let q = 0; q < numYtiles; q++) {
for (let p = 0; p < numXtiles; p++) {
tile = {};
tile.tx0 = Math.max(siz.XTOsiz + p * siz.XTsiz, siz.XOsiz);
tile.ty0 = Math.max(siz.YTOsiz + q * siz.YTsiz, siz.YOsiz);
tile.tx1 = Math.min(siz.XTOsiz + (p + 1) * siz.XTsiz, siz.Xsiz);
tile.ty1 = Math.min(siz.YTOsiz + (q + 1) * siz.YTsiz, siz.Ysiz);
tile.width = tile.tx1 - tile.tx0;
tile.height = tile.ty1 - tile.ty0;
tile.components = [];
tiles.push(tile);
}
}
context.tiles = tiles;
const componentsCount = siz.Csiz;
for (let i = 0, ii = componentsCount; i < ii; i++) {
const component = components[i];
for (let j = 0, jj = tiles.length; j < jj; j++) {
const tileComponent = {};
tile = tiles[j];
tileComponent.tcx0 = Math.ceil(tile.tx0 / component.XRsiz);
tileComponent.tcy0 = Math.ceil(tile.ty0 / component.YRsiz);
tileComponent.tcx1 = Math.ceil(tile.tx1 / component.XRsiz);
tileComponent.tcy1 = Math.ceil(tile.ty1 / component.YRsiz);
tileComponent.width = tileComponent.tcx1 - tileComponent.tcx0;
tileComponent.height = tileComponent.tcy1 - tileComponent.tcy0;
tile.components[i] = tileComponent;
}
}
}
function getBlocksDimensions(context, component, r) {
const codOrCoc = component.codingStyleParameters;
const result = {};
if (!codOrCoc.entropyCoderWithCustomPrecincts) {
result.PPx = 15;
result.PPy = 15;
} else {
result.PPx = codOrCoc.precinctsSizes[r].PPx;
result.PPy = codOrCoc.precinctsSizes[r].PPy;
}
// calculate codeblock size as described in section B.7
result.xcb_ =
r > 0
? Math.min(codOrCoc.xcb, result.PPx - 1)
: Math.min(codOrCoc.xcb, result.PPx);
result.ycb_ =
r > 0
? Math.min(codOrCoc.ycb, result.PPy - 1)
: Math.min(codOrCoc.ycb, result.PPy);
return result;
}
function buildPrecincts(context, resolution, dimensions) {
// Section B.6 Division resolution to precincts
const precinctWidth = 1 << dimensions.PPx;
const precinctHeight = 1 << dimensions.PPy;
// Jasper introduces codeblock groups for mapping each subband codeblocks
// to precincts. Precinct partition divides a resolution according to width
// and height parameters. The subband that belongs to the resolution level
// has a different size than the level, unless it is the zero resolution.
// From Jasper documentation: jpeg2000.pdf, section K: Tier-2 coding:
// The precinct partitioning for a particular subband is derived from a
// partitioning of its parent LL band (i.e., the LL band at the next higher
// resolution level)... The LL band associated with each resolution level is
// divided into precincts... Each of the resulting precinct regions is then
// mapped into its child subbands (if any) at the next lower resolution
// level. This is accomplished by using the coordinate transformation
// (u, v) = (ceil(x/2), ceil(y/2)) where (x, y) and (u, v) are the
// coordinates of a point in the LL band and child subband, respectively.
const isZeroRes = resolution.resLevel === 0;
const precinctWidthInSubband = 1 << (dimensions.PPx + (isZeroRes ? 0 : -1));
const precinctHeightInSubband = 1 << (dimensions.PPy + (isZeroRes ? 0 : -1));
const numprecinctswide =
resolution.trx1 > resolution.trx0
? Math.ceil(resolution.trx1 / precinctWidth) -
Math.floor(resolution.trx0 / precinctWidth)
: 0;
const numprecinctshigh =
resolution.try1 > resolution.try0
? Math.ceil(resolution.try1 / precinctHeight) -
Math.floor(resolution.try0 / precinctHeight)
: 0;
const numprecincts = numprecinctswide * numprecinctshigh;
resolution.precinctParameters = {
precinctWidth,
precinctHeight,
numprecinctswide,
numprecinctshigh,
numprecincts,
precinctWidthInSubband,
precinctHeightInSubband,
};
}
function buildCodeblocks(context, subband, dimensions) {
// Section B.7 Division sub-band into code-blocks
const xcb_ = dimensions.xcb_;
const ycb_ = dimensions.ycb_;
const codeblockWidth = 1 << xcb_;
const codeblockHeight = 1 << ycb_;
const cbx0 = subband.tbx0 >> xcb_;
const cby0 = subband.tby0 >> ycb_;
const cbx1 = (subband.tbx1 + codeblockWidth - 1) >> xcb_;
const cby1 = (subband.tby1 + codeblockHeight - 1) >> ycb_;
const precinctParameters = subband.resolution.precinctParameters;
const codeblocks = [];
const precincts = [];
let i, j, codeblock, precinctNumber;
for (j = cby0; j < cby1; j++) {
for (i = cbx0; i < cbx1; i++) {
codeblock = {
cbx: i,
cby: j,
tbx0: codeblockWidth * i,
tby0: codeblockHeight * j,
tbx1: codeblockWidth * (i + 1),
tby1: codeblockHeight * (j + 1),
};
codeblock.tbx0_ = Math.max(subband.tbx0, codeblock.tbx0);
codeblock.tby0_ = Math.max(subband.tby0, codeblock.tby0);
codeblock.tbx1_ = Math.min(subband.tbx1, codeblock.tbx1);
codeblock.tby1_ = Math.min(subband.tby1, codeblock.tby1);
// Calculate precinct number for this codeblock, codeblock position
// should be relative to its subband, use actual dimension and position
// See comment about codeblock group width and height
const pi = Math.floor(
(codeblock.tbx0_ - subband.tbx0) /
precinctParameters.precinctWidthInSubband
);
const pj = Math.floor(
(codeblock.tby0_ - subband.tby0) /
precinctParameters.precinctHeightInSubband
);
precinctNumber = pi + pj * precinctParameters.numprecinctswide;
codeblock.precinctNumber = precinctNumber;
codeblock.subbandType = subband.type;
codeblock.Lblock = 3;
if (
codeblock.tbx1_ <= codeblock.tbx0_ ||
codeblock.tby1_ <= codeblock.tby0_
) {
continue;
}
codeblocks.push(codeblock);
// building precinct for the sub-band
let precinct = precincts[precinctNumber];
if (precinct !== undefined) {
if (i < precinct.cbxMin) {
precinct.cbxMin = i;
} else if (i > precinct.cbxMax) {
precinct.cbxMax = i;
}
if (j < precinct.cbyMin) {
precinct.cbxMin = j;
} else if (j > precinct.cbyMax) {
precinct.cbyMax = j;
}
} else {
precincts[precinctNumber] = precinct = {
cbxMin: i,
cbyMin: j,
cbxMax: i,
cbyMax: j,
};
}
codeblock.precinct = precinct;
}
}
subband.codeblockParameters = {
codeblockWidth: xcb_,
codeblockHeight: ycb_,
numcodeblockwide: cbx1 - cbx0 + 1,
numcodeblockhigh: cby1 - cby0 + 1,
};
subband.codeblocks = codeblocks;
subband.precincts = precincts;
}
function createPacket(resolution, precinctNumber, layerNumber) {
const precinctCodeblocks = [];
// Section B.10.8 Order of info in packet
const subbands = resolution.subbands;
// sub-bands already ordered in 'LL', 'HL', 'LH', and 'HH' sequence
for (let i = 0, ii = subbands.length; i < ii; i++) {
const subband = subbands[i];
const codeblocks = subband.codeblocks;
for (let j = 0, jj = codeblocks.length; j < jj; j++) {
const codeblock = codeblocks[j];
if (codeblock.precinctNumber !== precinctNumber) {
continue;
}
precinctCodeblocks.push(codeblock);
}
}
return {
layerNumber,
codeblocks: precinctCodeblocks,
};
}
function LayerResolutionComponentPositionIterator(context) {
const siz = context.SIZ;
const tileIndex = context.currentTile.index;
const tile = context.tiles[tileIndex];
const layersCount = tile.codingStyleDefaultParameters.layersCount;
const componentsCount = siz.Csiz;
let maxDecompositionLevelsCount = 0;
for (let q = 0; q < componentsCount; q++) {
maxDecompositionLevelsCount = Math.max(
maxDecompositionLevelsCount,
tile.components[q].codingStyleParameters.decompositionLevelsCount
);
}
let l = 0,
r = 0,
i = 0,
k = 0;
this.nextPacket = function JpxImage_nextPacket() {
// Section B.12.1.1 Layer-resolution-component-position
for (; l < layersCount; l++) {
for (; r <= maxDecompositionLevelsCount; r++) {
for (; i < componentsCount; i++) {
const component = tile.components[i];
if (r > component.codingStyleParameters.decompositionLevelsCount) {
continue;
}
const resolution = component.resolutions[r];
const numprecincts = resolution.precinctParameters.numprecincts;
for (; k < numprecincts; ) {
const packet = createPacket(resolution, k, l);
k++;
return packet;
}
k = 0;
}
i = 0;
}
r = 0;
}
throw new JpxError("Out of packets");
};
}
function ResolutionLayerComponentPositionIterator(context) {
const siz = context.SIZ;
const tileIndex = context.currentTile.index;
const tile = context.tiles[tileIndex];
const layersCount = tile.codingStyleDefaultParameters.layersCount;
const componentsCount = siz.Csiz;
let maxDecompositionLevelsCount = 0;
for (let q = 0; q < componentsCount; q++) {
maxDecompositionLevelsCount = Math.max(
maxDecompositionLevelsCount,
tile.components[q].codingStyleParameters.decompositionLevelsCount
);
}
let r = 0,
l = 0,
i = 0,
k = 0;
this.nextPacket = function JpxImage_nextPacket() {
// Section B.12.1.2 Resolution-layer-component-position
for (; r <= maxDecompositionLevelsCount; r++) {
for (; l < layersCount; l++) {
for (; i < componentsCount; i++) {
const component = tile.components[i];
if (r > component.codingStyleParameters.decompositionLevelsCount) {
continue;
}
const resolution = component.resolutions[r];
const numprecincts = resolution.precinctParameters.numprecincts;
for (; k < numprecincts; ) {
const packet = createPacket(resolution, k, l);
k++;
return packet;
}
k = 0;
}
i = 0;
}
l = 0;
}
throw new JpxError("Out of packets");
};
}
function ResolutionPositionComponentLayerIterator(context) {
const siz = context.SIZ;
const tileIndex = context.currentTile.index;
const tile = context.tiles[tileIndex];
const layersCount = tile.codingStyleDefaultParameters.layersCount;
const componentsCount = siz.Csiz;
let l, r, c, p;
let maxDecompositionLevelsCount = 0;
for (c = 0; c < componentsCount; c++) {
const component = tile.components[c];
maxDecompositionLevelsCount = Math.max(
maxDecompositionLevelsCount,
component.codingStyleParameters.decompositionLevelsCount
);
}
const maxNumPrecinctsInLevel = new Int32Array(
maxDecompositionLevelsCount + 1
);
for (r = 0; r <= maxDecompositionLevelsCount; ++r) {
let maxNumPrecincts = 0;
for (c = 0; c < componentsCount; ++c) {
const resolutions = tile.components[c].resolutions;
if (r < resolutions.length) {
maxNumPrecincts = Math.max(
maxNumPrecincts,
resolutions[r].precinctParameters.numprecincts
);
}
}
maxNumPrecinctsInLevel[r] = maxNumPrecincts;
}
l = 0;
r = 0;
c = 0;
p = 0;
this.nextPacket = function JpxImage_nextPacket() {
// Section B.12.1.3 Resolution-position-component-layer
for (; r <= maxDecompositionLevelsCount; r++) {
for (; p < maxNumPrecinctsInLevel[r]; p++) {
for (; c < componentsCount; c++) {
const component = tile.components[c];
if (r > component.codingStyleParameters.decompositionLevelsCount) {
continue;
}
const resolution = component.resolutions[r];
const numprecincts = resolution.precinctParameters.numprecincts;
if (p >= numprecincts) {
continue;
}
for (; l < layersCount; ) {
const packet = createPacket(resolution, p, l);
l++;
return packet;
}
l = 0;
}
c = 0;
}
p = 0;
}
throw new JpxError("Out of packets");
};
}
function PositionComponentResolutionLayerIterator(context) {
const siz = context.SIZ;
const tileIndex = context.currentTile.index;
const tile = context.tiles[tileIndex];
const layersCount = tile.codingStyleDefaultParameters.layersCount;
const componentsCount = siz.Csiz;
const precinctsSizes = getPrecinctSizesInImageScale(tile);
const precinctsIterationSizes = precinctsSizes;
let l = 0,
r = 0,
c = 0,
px = 0,
py = 0;
this.nextPacket = function JpxImage_nextPacket() {
// Section B.12.1.4 Position-component-resolution-layer
for (; py < precinctsIterationSizes.maxNumHigh; py++) {
for (; px < precinctsIterationSizes.maxNumWide; px++) {
for (; c < componentsCount; c++) {
const component = tile.components[c];
const decompositionLevelsCount =
component.codingStyleParameters.decompositionLevelsCount;
for (; r <= decompositionLevelsCount; r++) {
const resolution = component.resolutions[r];
const sizeInImageScale =
precinctsSizes.components[c].resolutions[r];
const k = getPrecinctIndexIfExist(
px,
py,
sizeInImageScale,
precinctsIterationSizes,
resolution
);
if (k === null) {
continue;
}
for (; l < layersCount; ) {
const packet = createPacket(resolution, k, l);
l++;
return packet;
}
l = 0;
}
r = 0;
}
c = 0;
}
px = 0;
}
throw new JpxError("Out of packets");
};
}
function ComponentPositionResolutionLayerIterator(context) {
const siz = context.SIZ;
const tileIndex = context.currentTile.index;
const tile = context.tiles[tileIndex];
const layersCount = tile.codingStyleDefaultParameters.layersCount;
const componentsCount = siz.Csiz;
const precinctsSizes = getPrecinctSizesInImageScale(tile);
let l = 0,
r = 0,
c = 0,
px = 0,
py = 0;
this.nextPacket = function JpxImage_nextPacket() {
// Section B.12.1.5 Component-position-resolution-layer
for (; c < componentsCount; ++c) {
const component = tile.components[c];
const precinctsIterationSizes = precinctsSizes.components[c];
const decompositionLevelsCount =
component.codingStyleParameters.decompositionLevelsCount;
for (; py < precinctsIterationSizes.maxNumHigh; py++) {
for (; px < precinctsIterationSizes.maxNumWide; px++) {
for (; r <= decompositionLevelsCount; r++) {
const resolution = component.resolutions[r];
const sizeInImageScale = precinctsIterationSizes.resolutions[r];
const k = getPrecinctIndexIfExist(
px,
py,
sizeInImageScale,
precinctsIterationSizes,
resolution
);
if (k === null) {
continue;
}
for (; l < layersCount; ) {
const packet = createPacket(resolution, k, l);
l++;
return packet;
}
l = 0;
}
r = 0;
}
px = 0;
}
py = 0;
}
throw new JpxError("Out of packets");
};
}
function getPrecinctIndexIfExist(
pxIndex,
pyIndex,
sizeInImageScale,
precinctIterationSizes,
resolution
) {
const posX = pxIndex * precinctIterationSizes.minWidth;
const posY = pyIndex * precinctIterationSizes.minHeight;
if (
posX % sizeInImageScale.width !== 0 ||
posY % sizeInImageScale.height !== 0
) {
return null;
}
const startPrecinctRowIndex =
(posY / sizeInImageScale.width) *
resolution.precinctParameters.numprecinctswide;
return posX / sizeInImageScale.height + startPrecinctRowIndex;
}
function getPrecinctSizesInImageScale(tile) {
const componentsCount = tile.components.length;
let minWidth = Number.MAX_VALUE;
let minHeight = Number.MAX_VALUE;
let maxNumWide = 0;
let maxNumHigh = 0;
const sizePerComponent = new Array(componentsCount);
for (let c = 0; c < componentsCount; c++) {
const component = tile.components[c];
const decompositionLevelsCount =
component.codingStyleParameters.decompositionLevelsCount;
const sizePerResolution = new Array(decompositionLevelsCount + 1);
let minWidthCurrentComponent = Number.MAX_VALUE;
let minHeightCurrentComponent = Number.MAX_VALUE;
let maxNumWideCurrentComponent = 0;
let maxNumHighCurrentComponent = 0;
let scale = 1;
for (let r = decompositionLevelsCount; r >= 0; --r) {
const resolution = component.resolutions[r];
const widthCurrentResolution =
scale * resolution.precinctParameters.precinctWidth;
const heightCurrentResolution =
scale * resolution.precinctParameters.precinctHeight;
minWidthCurrentComponent = Math.min(
minWidthCurrentComponent,
widthCurrentResolution
);
minHeightCurrentComponent = Math.min(
minHeightCurrentComponent,
heightCurrentResolution
);
maxNumWideCurrentComponent = Math.max(
maxNumWideCurrentComponent,
resolution.precinctParameters.numprecinctswide
);
maxNumHighCurrentComponent = Math.max(
maxNumHighCurrentComponent,
resolution.precinctParameters.numprecinctshigh
);
sizePerResolution[r] = {
width: widthCurrentResolution,
height: heightCurrentResolution,
};
scale <<= 1;
}
minWidth = Math.min(minWidth, minWidthCurrentComponent);
minHeight = Math.min(minHeight, minHeightCurrentComponent);
maxNumWide = Math.max(maxNumWide, maxNumWideCurrentComponent);
maxNumHigh = Math.max(maxNumHigh, maxNumHighCurrentComponent);
sizePerComponent[c] = {
resolutions: sizePerResolution,
minWidth: minWidthCurrentComponent,
minHeight: minHeightCurrentComponent,
maxNumWide: maxNumWideCurrentComponent,
maxNumHigh: maxNumHighCurrentComponent,
};
}
return {
components: sizePerComponent,
minWidth,
minHeight,
maxNumWide,
maxNumHigh,
};
}
function buildPackets(context) {
const siz = context.SIZ;
const tileIndex = context.currentTile.index;
const tile = context.tiles[tileIndex];
const componentsCount = siz.Csiz;
// Creating resolutions and sub-bands for each component
for (let c = 0; c < componentsCount; c++) {
const component = tile.components[c];
const decompositionLevelsCount =
component.codingStyleParameters.decompositionLevelsCount;
// Section B.5 Resolution levels and sub-bands
const resolutions = [];
const subbands = [];
for (let r = 0; r <= decompositionLevelsCount; r++) {
const blocksDimensions = getBlocksDimensions(context, component, r);
const resolution = {};
const scale = 1 << (decompositionLevelsCount - r);
resolution.trx0 = Math.ceil(component.tcx0 / scale);
resolution.try0 = Math.ceil(component.tcy0 / scale);
resolution.trx1 = Math.ceil(component.tcx1 / scale);
resolution.try1 = Math.ceil(component.tcy1 / scale);