dwv 0.26.0 → 0.26.2

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.
Files changed (38) hide show
  1. package/decoders/dwv/decode-rle.js +22 -22
  2. package/decoders/dwv/rle.js +103 -103
  3. package/decoders/pdfjs/arithmetic_decoder.js +185 -185
  4. package/decoders/pdfjs/decode-jpeg2000.js +18 -18
  5. package/decoders/pdfjs/decode-jpegbaseline.js +18 -18
  6. package/decoders/pdfjs/jpg.js +1072 -1072
  7. package/decoders/pdfjs/jpx.js +2237 -2237
  8. package/decoders/pdfjs/readme.md +15 -15
  9. package/decoders/pdfjs/util.js +1588 -1588
  10. package/decoders/rii-mango/decode-jpegloss.js +34 -34
  11. package/decoders/rii-mango/lossless.js +1755 -1755
  12. package/decoders/rii-mango/readme.md +12 -12
  13. package/dist/dwv.js +27526 -27512
  14. package/dist/dwv.min.js +3 -3
  15. package/license.txt +674 -674
  16. package/locales/de/overlays.json +62 -62
  17. package/locales/de/translation.json +236 -236
  18. package/locales/en/overlays.json +62 -62
  19. package/locales/en/translation.json +236 -236
  20. package/locales/es/overlays.json +62 -62
  21. package/locales/es/translation.json +236 -236
  22. package/locales/fr/overlays.json +62 -62
  23. package/locales/fr/translation.json +236 -236
  24. package/locales/it/overlays.json +62 -62
  25. package/locales/it/translation.json +236 -236
  26. package/locales/jp/overlays.json +62 -62
  27. package/locales/jp/translation.json +236 -236
  28. package/locales/ro/overlays.json +62 -62
  29. package/locales/ro/translation.json +236 -236
  30. package/locales/ru/overlays.json +62 -62
  31. package/locales/ru/translation.json +236 -236
  32. package/locales/zh/overlays.json +62 -62
  33. package/locales/zh/translation.json +236 -236
  34. package/package.json +50 -50
  35. package/readme.md +66 -66
  36. package/build/dist/dwv.js +0 -27512
  37. package/build/dist/dwv.min.js +0 -3
  38. package/dist/dwv-0.26.0.min.js +0 -3
@@ -1,2237 +1,2237 @@
1
- /* -*- Mode: Java; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
2
- /* vim: set shiftwidth=2 tabstop=2 autoindent cindent expandtab: */
3
- /* Copyright 2012 Mozilla Foundation
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
- /* globals ArithmeticDecoder, globalScope, log2, readUint16, readUint32,
18
- info, warn */
19
-
20
- 'use strict';
21
-
22
- var JpxImage = (function JpxImageClosure() {
23
- // Table E.1
24
- var SubbandsGainLog2 = {
25
- 'LL': 0,
26
- 'LH': 1,
27
- 'HL': 1,
28
- 'HH': 2
29
- };
30
- function JpxImage() {
31
- this.failOnCorruptedImage = true;
32
- }
33
- JpxImage.prototype = {
34
- parse: function JpxImage_parse(data) {
35
-
36
- var head = readUint16(data, 0);
37
- // No box header, immediate start of codestream (SOC)
38
- if (head === 0xFF4F) {
39
- this.parseCodestream(data, 0, data.length);
40
- return;
41
- }
42
-
43
- var position = 0, length = data.length;
44
- while (position < length) {
45
- var headerSize = 8;
46
- var lbox = readUint32(data, position);
47
- var tbox = readUint32(data, position + 4);
48
- position += headerSize;
49
- if (lbox === 1) {
50
- // XLBox: read UInt64 according to spec.
51
- // JavaScript's int precision of 53 bit should be sufficient here.
52
- lbox = readUint32(data, position) * 4294967296 +
53
- readUint32(data, position + 4);
54
- position += 8;
55
- headerSize += 8;
56
- }
57
- if (lbox === 0) {
58
- lbox = length - position + headerSize;
59
- }
60
- if (lbox < headerSize) {
61
- throw new Error('JPX Error: Invalid box field size');
62
- }
63
- var dataLength = lbox - headerSize;
64
- var jumpDataLength = true;
65
- switch (tbox) {
66
- case 0x6A703268: // 'jp2h'
67
- jumpDataLength = false; // parsing child boxes
68
- break;
69
- case 0x636F6C72: // 'colr'
70
- // Colorspaces are not used, the CS from the PDF is used.
71
- var method = data[position];
72
- var precedence = data[position + 1];
73
- var approximation = data[position + 2];
74
- if (method === 1) {
75
- // enumerated colorspace
76
- var colorspace = readUint32(data, position + 3);
77
- switch (colorspace) {
78
- case 16: // this indicates a sRGB colorspace
79
- case 17: // this indicates a grayscale colorspace
80
- case 18: // this indicates a YUV colorspace
81
- break;
82
- default:
83
- warn('Unknown colorspace ' + colorspace);
84
- break;
85
- }
86
- } else if (method === 2) {
87
- info('ICC profile not supported');
88
- }
89
- break;
90
- case 0x6A703263: // 'jp2c'
91
- this.parseCodestream(data, position, position + dataLength);
92
- break;
93
- case 0x6A502020: // 'jP\024\024'
94
- if (0x0d0a870a !== readUint32(data, position)) {
95
- warn('Invalid JP2 signature');
96
- }
97
- break;
98
- // The following header types are valid but currently not used:
99
- case 0x6A501A1A: // 'jP\032\032'
100
- case 0x66747970: // 'ftyp'
101
- case 0x72726571: // 'rreq'
102
- case 0x72657320: // 'res '
103
- case 0x69686472: // 'ihdr'
104
- break;
105
- default:
106
- var headerType = String.fromCharCode((tbox >> 24) & 0xFF,
107
- (tbox >> 16) & 0xFF,
108
- (tbox >> 8) & 0xFF,
109
- tbox & 0xFF);
110
- warn('Unsupported header type ' + tbox + ' (' + headerType + ')');
111
- break;
112
- }
113
- if (jumpDataLength) {
114
- position += dataLength;
115
- }
116
- }
117
- },
118
- parseImageProperties: function JpxImage_parseImageProperties(stream) {
119
- var newByte = stream.getByte();
120
- while (newByte >= 0) {
121
- var oldByte = newByte;
122
- newByte = stream.getByte();
123
- var code = (oldByte << 8) | newByte;
124
- // Image and tile size (SIZ)
125
- if (code === 0xFF51) {
126
- stream.skip(4);
127
- var Xsiz = stream.getInt32() >>> 0; // Byte 4
128
- var Ysiz = stream.getInt32() >>> 0; // Byte 8
129
- var XOsiz = stream.getInt32() >>> 0; // Byte 12
130
- var YOsiz = stream.getInt32() >>> 0; // Byte 16
131
- stream.skip(16);
132
- var Csiz = stream.getUint16(); // Byte 36
133
- this.width = Xsiz - XOsiz;
134
- this.height = Ysiz - YOsiz;
135
- this.componentsCount = Csiz;
136
- // Results are always returned as Uint8Arrays
137
- this.bitsPerComponent = 8;
138
- return;
139
- }
140
- }
141
- throw new Error('JPX Error: No size marker found in JPX stream');
142
- },
143
- parseCodestream: function JpxImage_parseCodestream(data, start, end) {
144
- var context = {};
145
- try {
146
- var doNotRecover = false;
147
- var position = start;
148
- while (position + 1 < end) {
149
- var code = readUint16(data, position);
150
- position += 2;
151
-
152
- var length = 0, j, sqcd, spqcds, spqcdSize, scalarExpounded, tile;
153
- switch (code) {
154
- case 0xFF4F: // Start of codestream (SOC)
155
- context.mainHeader = true;
156
- break;
157
- case 0xFFD9: // End of codestream (EOC)
158
- break;
159
- case 0xFF51: // Image and tile size (SIZ)
160
- length = readUint16(data, position);
161
- var siz = {};
162
- siz.Xsiz = readUint32(data, position + 4);
163
- siz.Ysiz = readUint32(data, position + 8);
164
- siz.XOsiz = readUint32(data, position + 12);
165
- siz.YOsiz = readUint32(data, position + 16);
166
- siz.XTsiz = readUint32(data, position + 20);
167
- siz.YTsiz = readUint32(data, position + 24);
168
- siz.XTOsiz = readUint32(data, position + 28);
169
- siz.YTOsiz = readUint32(data, position + 32);
170
- var componentsCount = readUint16(data, position + 36);
171
- siz.Csiz = componentsCount;
172
- var components = [];
173
- j = position + 38;
174
- for (var i = 0; i < componentsCount; i++) {
175
- var component = {
176
- precision: (data[j] & 0x7F) + 1,
177
- isSigned: !!(data[j] & 0x80),
178
- XRsiz: data[j + 1],
179
- YRsiz: data[j + 1]
180
- };
181
- calculateComponentDimensions(component, siz);
182
- components.push(component);
183
- }
184
- context.SIZ = siz;
185
- context.components = components;
186
- calculateTileGrids(context, components);
187
- context.QCC = [];
188
- context.COC = [];
189
- break;
190
- case 0xFF5C: // Quantization default (QCD)
191
- length = readUint16(data, position);
192
- var qcd = {};
193
- j = position + 2;
194
- sqcd = data[j++];
195
- switch (sqcd & 0x1F) {
196
- case 0:
197
- spqcdSize = 8;
198
- scalarExpounded = true;
199
- break;
200
- case 1:
201
- spqcdSize = 16;
202
- scalarExpounded = false;
203
- break;
204
- case 2:
205
- spqcdSize = 16;
206
- scalarExpounded = true;
207
- break;
208
- default:
209
- throw new Error('JPX Error: Invalid SQcd value ' + sqcd);
210
- }
211
- qcd.noQuantization = (spqcdSize === 8);
212
- qcd.scalarExpounded = scalarExpounded;
213
- qcd.guardBits = sqcd >> 5;
214
- spqcds = [];
215
- while (j < length + position) {
216
- var spqcd = {};
217
- if (spqcdSize === 8) {
218
- spqcd.epsilon = data[j++] >> 3;
219
- spqcd.mu = 0;
220
- } else {
221
- spqcd.epsilon = data[j] >> 3;
222
- spqcd.mu = ((data[j] & 0x7) << 8) | data[j + 1];
223
- j += 2;
224
- }
225
- spqcds.push(spqcd);
226
- }
227
- qcd.SPqcds = spqcds;
228
- if (context.mainHeader) {
229
- context.QCD = qcd;
230
- } else {
231
- context.currentTile.QCD = qcd;
232
- context.currentTile.QCC = [];
233
- }
234
- break;
235
- case 0xFF5D: // Quantization component (QCC)
236
- length = readUint16(data, position);
237
- var qcc = {};
238
- j = position + 2;
239
- var cqcc;
240
- if (context.SIZ.Csiz < 257) {
241
- cqcc = data[j++];
242
- } else {
243
- cqcc = readUint16(data, j);
244
- j += 2;
245
- }
246
- sqcd = data[j++];
247
- switch (sqcd & 0x1F) {
248
- case 0:
249
- spqcdSize = 8;
250
- scalarExpounded = true;
251
- break;
252
- case 1:
253
- spqcdSize = 16;
254
- scalarExpounded = false;
255
- break;
256
- case 2:
257
- spqcdSize = 16;
258
- scalarExpounded = true;
259
- break;
260
- default:
261
- throw new Error('JPX Error: Invalid SQcd value ' + sqcd);
262
- }
263
- qcc.noQuantization = (spqcdSize === 8);
264
- qcc.scalarExpounded = scalarExpounded;
265
- qcc.guardBits = sqcd >> 5;
266
- spqcds = [];
267
- while (j < (length + position)) {
268
- spqcd = {};
269
- if (spqcdSize === 8) {
270
- spqcd.epsilon = data[j++] >> 3;
271
- spqcd.mu = 0;
272
- } else {
273
- spqcd.epsilon = data[j] >> 3;
274
- spqcd.mu = ((data[j] & 0x7) << 8) | data[j + 1];
275
- j += 2;
276
- }
277
- spqcds.push(spqcd);
278
- }
279
- qcc.SPqcds = spqcds;
280
- if (context.mainHeader) {
281
- context.QCC[cqcc] = qcc;
282
- } else {
283
- context.currentTile.QCC[cqcc] = qcc;
284
- }
285
- break;
286
- case 0xFF52: // Coding style default (COD)
287
- length = readUint16(data, position);
288
- var cod = {};
289
- j = position + 2;
290
- var scod = data[j++];
291
- cod.entropyCoderWithCustomPrecincts = !!(scod & 1);
292
- cod.sopMarkerUsed = !!(scod & 2);
293
- cod.ephMarkerUsed = !!(scod & 4);
294
- cod.progressionOrder = data[j++];
295
- cod.layersCount = readUint16(data, j);
296
- j += 2;
297
- cod.multipleComponentTransform = data[j++];
298
-
299
- cod.decompositionLevelsCount = data[j++];
300
- cod.xcb = (data[j++] & 0xF) + 2;
301
- cod.ycb = (data[j++] & 0xF) + 2;
302
- var blockStyle = data[j++];
303
- cod.selectiveArithmeticCodingBypass = !!(blockStyle & 1);
304
- cod.resetContextProbabilities = !!(blockStyle & 2);
305
- cod.terminationOnEachCodingPass = !!(blockStyle & 4);
306
- cod.verticalyStripe = !!(blockStyle & 8);
307
- cod.predictableTermination = !!(blockStyle & 16);
308
- cod.segmentationSymbolUsed = !!(blockStyle & 32);
309
- cod.reversibleTransformation = data[j++];
310
- if (cod.entropyCoderWithCustomPrecincts) {
311
- var precinctsSizes = [];
312
- while (j < length + position) {
313
- var precinctsSize = data[j++];
314
- precinctsSizes.push({
315
- PPx: precinctsSize & 0xF,
316
- PPy: precinctsSize >> 4
317
- });
318
- }
319
- cod.precinctsSizes = precinctsSizes;
320
- }
321
- var unsupported = [];
322
- if (cod.selectiveArithmeticCodingBypass) {
323
- unsupported.push('selectiveArithmeticCodingBypass');
324
- }
325
- if (cod.resetContextProbabilities) {
326
- unsupported.push('resetContextProbabilities');
327
- }
328
- if (cod.terminationOnEachCodingPass) {
329
- unsupported.push('terminationOnEachCodingPass');
330
- }
331
- if (cod.verticalyStripe) {
332
- unsupported.push('verticalyStripe');
333
- }
334
- if (cod.predictableTermination) {
335
- unsupported.push('predictableTermination');
336
- }
337
- if (unsupported.length > 0) {
338
- doNotRecover = true;
339
- throw new Error('JPX Error: Unsupported COD options (' +
340
- unsupported.join(', ') + ')');
341
- }
342
- if (context.mainHeader) {
343
- context.COD = cod;
344
- } else {
345
- context.currentTile.COD = cod;
346
- context.currentTile.COC = [];
347
- }
348
- break;
349
- case 0xFF90: // Start of tile-part (SOT)
350
- length = readUint16(data, position);
351
- tile = {};
352
- tile.index = readUint16(data, position + 2);
353
- tile.length = readUint32(data, position + 4);
354
- tile.dataEnd = tile.length + position - 2;
355
- tile.partIndex = data[position + 8];
356
- tile.partsCount = data[position + 9];
357
-
358
- context.mainHeader = false;
359
- if (tile.partIndex === 0) {
360
- // reset component specific settings
361
- tile.COD = context.COD;
362
- tile.COC = context.COC.slice(0); // clone of the global COC
363
- tile.QCD = context.QCD;
364
- tile.QCC = context.QCC.slice(0); // clone of the global COC
365
- }
366
- context.currentTile = tile;
367
- break;
368
- case 0xFF93: // Start of data (SOD)
369
- tile = context.currentTile;
370
- if (tile.partIndex === 0) {
371
- initializeTile(context, tile.index);
372
- buildPackets(context);
373
- }
374
-
375
- // moving to the end of the data
376
- length = tile.dataEnd - position;
377
- parseTilePackets(context, data, position, length);
378
- break;
379
- case 0xFF55: // Tile-part lengths, main header (TLM)
380
- case 0xFF57: // Packet length, main header (PLM)
381
- case 0xFF58: // Packet length, tile-part header (PLT)
382
- case 0xFF64: // Comment (COM)
383
- case 0xFF53: // Coding style component (COC)
384
- length = readUint16(data, position);
385
- // skipping content
386
- break;
387
- default:
388
- throw new Error('JPX Error: Unknown codestream code: ' +
389
- code.toString(16));
390
- }
391
- position += length;
392
- }
393
- } catch (e) {
394
- if (doNotRecover || this.failOnCorruptedImage) {
395
- throw e;
396
- } else {
397
- warn('Trying to recover from ' + e.message);
398
- }
399
- }
400
- this.tiles = transformComponents(context);
401
- this.width = context.SIZ.Xsiz - context.SIZ.XOsiz;
402
- this.height = context.SIZ.Ysiz - context.SIZ.YOsiz;
403
- this.componentsCount = context.SIZ.Csiz;
404
- }
405
- };
406
- function calculateComponentDimensions(component, siz) {
407
- // Section B.2 Component mapping
408
- component.x0 = Math.ceil(siz.XOsiz / component.XRsiz);
409
- component.x1 = Math.ceil(siz.Xsiz / component.XRsiz);
410
- component.y0 = Math.ceil(siz.YOsiz / component.YRsiz);
411
- component.y1 = Math.ceil(siz.Ysiz / component.YRsiz);
412
- component.width = component.x1 - component.x0;
413
- component.height = component.y1 - component.y0;
414
- }
415
- function calculateTileGrids(context, components) {
416
- var siz = context.SIZ;
417
- // Section B.3 Division into tile and tile-components
418
- var tile, tiles = [];
419
- var numXtiles = Math.ceil((siz.Xsiz - siz.XTOsiz) / siz.XTsiz);
420
- var numYtiles = Math.ceil((siz.Ysiz - siz.YTOsiz) / siz.YTsiz);
421
- for (var q = 0; q < numYtiles; q++) {
422
- for (var p = 0; p < numXtiles; p++) {
423
- tile = {};
424
- tile.tx0 = Math.max(siz.XTOsiz + p * siz.XTsiz, siz.XOsiz);
425
- tile.ty0 = Math.max(siz.YTOsiz + q * siz.YTsiz, siz.YOsiz);
426
- tile.tx1 = Math.min(siz.XTOsiz + (p + 1) * siz.XTsiz, siz.Xsiz);
427
- tile.ty1 = Math.min(siz.YTOsiz + (q + 1) * siz.YTsiz, siz.Ysiz);
428
- tile.width = tile.tx1 - tile.tx0;
429
- tile.height = tile.ty1 - tile.ty0;
430
- tile.components = [];
431
- tiles.push(tile);
432
- }
433
- }
434
- context.tiles = tiles;
435
-
436
- var componentsCount = siz.Csiz;
437
- for (var i = 0, ii = componentsCount; i < ii; i++) {
438
- var component = components[i];
439
- for (var j = 0, jj = tiles.length; j < jj; j++) {
440
- var tileComponent = {};
441
- tile = tiles[j];
442
- tileComponent.tcx0 = Math.ceil(tile.tx0 / component.XRsiz);
443
- tileComponent.tcy0 = Math.ceil(tile.ty0 / component.YRsiz);
444
- tileComponent.tcx1 = Math.ceil(tile.tx1 / component.XRsiz);
445
- tileComponent.tcy1 = Math.ceil(tile.ty1 / component.YRsiz);
446
- tileComponent.width = tileComponent.tcx1 - tileComponent.tcx0;
447
- tileComponent.height = tileComponent.tcy1 - tileComponent.tcy0;
448
- tile.components[i] = tileComponent;
449
- }
450
- }
451
- }
452
- function getBlocksDimensions(context, component, r) {
453
- var codOrCoc = component.codingStyleParameters;
454
- var result = {};
455
- if (!codOrCoc.entropyCoderWithCustomPrecincts) {
456
- result.PPx = 15;
457
- result.PPy = 15;
458
- } else {
459
- result.PPx = codOrCoc.precinctsSizes[r].PPx;
460
- result.PPy = codOrCoc.precinctsSizes[r].PPy;
461
- }
462
- // calculate codeblock size as described in section B.7
463
- result.xcb_ = (r > 0 ? Math.min(codOrCoc.xcb, result.PPx - 1) :
464
- Math.min(codOrCoc.xcb, result.PPx));
465
- result.ycb_ = (r > 0 ? Math.min(codOrCoc.ycb, result.PPy - 1) :
466
- Math.min(codOrCoc.ycb, result.PPy));
467
- return result;
468
- }
469
- function buildPrecincts(context, resolution, dimensions) {
470
- // Section B.6 Division resolution to precincts
471
- var precinctWidth = 1 << dimensions.PPx;
472
- var precinctHeight = 1 << dimensions.PPy;
473
- // Jasper introduces codeblock groups for mapping each subband codeblocks
474
- // to precincts. Precinct partition divides a resolution according to width
475
- // and height parameters. The subband that belongs to the resolution level
476
- // has a different size than the level, unless it is the zero resolution.
477
-
478
- // From Jasper documentation: jpeg2000.pdf, section K: Tier-2 coding:
479
- // The precinct partitioning for a particular subband is derived from a
480
- // partitioning of its parent LL band (i.e., the LL band at the next higher
481
- // resolution level)... The LL band associated with each resolution level is
482
- // divided into precincts... Each of the resulting precinct regions is then
483
- // mapped into its child subbands (if any) at the next lower resolution
484
- // level. This is accomplished by using the coordinate transformation
485
- // (u, v) = (ceil(x/2), ceil(y/2)) where (x, y) and (u, v) are the
486
- // coordinates of a point in the LL band and child subband, respectively.
487
- var isZeroRes = resolution.resLevel === 0;
488
- var precinctWidthInSubband = 1 << (dimensions.PPx + (isZeroRes ? 0 : -1));
489
- var precinctHeightInSubband = 1 << (dimensions.PPy + (isZeroRes ? 0 : -1));
490
- var numprecinctswide = (resolution.trx1 > resolution.trx0 ?
491
- Math.ceil(resolution.trx1 / precinctWidth) -
492
- Math.floor(resolution.trx0 / precinctWidth) : 0);
493
- var numprecinctshigh = (resolution.try1 > resolution.try0 ?
494
- Math.ceil(resolution.try1 / precinctHeight) -
495
- Math.floor(resolution.try0 / precinctHeight) : 0);
496
- var numprecincts = numprecinctswide * numprecinctshigh;
497
-
498
- resolution.precinctParameters = {
499
- precinctWidth: precinctWidth,
500
- precinctHeight: precinctHeight,
501
- numprecinctswide: numprecinctswide,
502
- numprecinctshigh: numprecinctshigh,
503
- numprecincts: numprecincts,
504
- precinctWidthInSubband: precinctWidthInSubband,
505
- precinctHeightInSubband: precinctHeightInSubband
506
- };
507
- }
508
- function buildCodeblocks(context, subband, dimensions) {
509
- // Section B.7 Division sub-band into code-blocks
510
- var xcb_ = dimensions.xcb_;
511
- var ycb_ = dimensions.ycb_;
512
- var codeblockWidth = 1 << xcb_;
513
- var codeblockHeight = 1 << ycb_;
514
- var cbx0 = subband.tbx0 >> xcb_;
515
- var cby0 = subband.tby0 >> ycb_;
516
- var cbx1 = (subband.tbx1 + codeblockWidth - 1) >> xcb_;
517
- var cby1 = (subband.tby1 + codeblockHeight - 1) >> ycb_;
518
- var precinctParameters = subband.resolution.precinctParameters;
519
- var codeblocks = [];
520
- var precincts = [];
521
- var i, j, codeblock, precinctNumber;
522
- for (j = cby0; j < cby1; j++) {
523
- for (i = cbx0; i < cbx1; i++) {
524
- codeblock = {
525
- cbx: i,
526
- cby: j,
527
- tbx0: codeblockWidth * i,
528
- tby0: codeblockHeight * j,
529
- tbx1: codeblockWidth * (i + 1),
530
- tby1: codeblockHeight * (j + 1)
531
- };
532
-
533
- codeblock.tbx0_ = Math.max(subband.tbx0, codeblock.tbx0);
534
- codeblock.tby0_ = Math.max(subband.tby0, codeblock.tby0);
535
- codeblock.tbx1_ = Math.min(subband.tbx1, codeblock.tbx1);
536
- codeblock.tby1_ = Math.min(subband.tby1, codeblock.tby1);
537
-
538
- // Calculate precinct number for this codeblock, codeblock position
539
- // should be relative to its subband, use actual dimension and position
540
- // See comment about codeblock group width and height
541
- var pi = Math.floor((codeblock.tbx0_ - subband.tbx0) /
542
- precinctParameters.precinctWidthInSubband);
543
- var pj = Math.floor((codeblock.tby0_ - subband.tby0) /
544
- precinctParameters.precinctHeightInSubband);
545
- precinctNumber = pi + (pj * precinctParameters.numprecinctswide);
546
-
547
- codeblock.precinctNumber = precinctNumber;
548
- codeblock.subbandType = subband.type;
549
- codeblock.Lblock = 3;
550
-
551
- if (codeblock.tbx1_ <= codeblock.tbx0_ ||
552
- codeblock.tby1_ <= codeblock.tby0_) {
553
- continue;
554
- }
555
- codeblocks.push(codeblock);
556
- // building precinct for the sub-band
557
- var precinct = precincts[precinctNumber];
558
- if (precinct !== undefined) {
559
- if (i < precinct.cbxMin) {
560
- precinct.cbxMin = i;
561
- } else if (i > precinct.cbxMax) {
562
- precinct.cbxMax = i;
563
- }
564
- if (j < precinct.cbyMin) {
565
- precinct.cbxMin = j;
566
- } else if (j > precinct.cbyMax) {
567
- precinct.cbyMax = j;
568
- }
569
- } else {
570
- precincts[precinctNumber] = precinct = {
571
- cbxMin: i,
572
- cbyMin: j,
573
- cbxMax: i,
574
- cbyMax: j
575
- };
576
- }
577
- codeblock.precinct = precinct;
578
- }
579
- }
580
- subband.codeblockParameters = {
581
- codeblockWidth: xcb_,
582
- codeblockHeight: ycb_,
583
- numcodeblockwide: cbx1 - cbx0 + 1,
584
- numcodeblockhigh: cby1 - cby0 + 1
585
- };
586
- subband.codeblocks = codeblocks;
587
- subband.precincts = precincts;
588
- }
589
- function createPacket(resolution, precinctNumber, layerNumber) {
590
- var precinctCodeblocks = [];
591
- // Section B.10.8 Order of info in packet
592
- var subbands = resolution.subbands;
593
- // sub-bands already ordered in 'LL', 'HL', 'LH', and 'HH' sequence
594
- for (var i = 0, ii = subbands.length; i < ii; i++) {
595
- var subband = subbands[i];
596
- var codeblocks = subband.codeblocks;
597
- for (var j = 0, jj = codeblocks.length; j < jj; j++) {
598
- var codeblock = codeblocks[j];
599
- if (codeblock.precinctNumber !== precinctNumber) {
600
- continue;
601
- }
602
- precinctCodeblocks.push(codeblock);
603
- }
604
- }
605
- return {
606
- layerNumber: layerNumber,
607
- codeblocks: precinctCodeblocks
608
- };
609
- }
610
- function LayerResolutionComponentPositionIterator(context) {
611
- var siz = context.SIZ;
612
- var tileIndex = context.currentTile.index;
613
- var tile = context.tiles[tileIndex];
614
- var layersCount = tile.codingStyleDefaultParameters.layersCount;
615
- var componentsCount = siz.Csiz;
616
- var maxDecompositionLevelsCount = 0;
617
- for (var q = 0; q < componentsCount; q++) {
618
- maxDecompositionLevelsCount = Math.max(maxDecompositionLevelsCount,
619
- tile.components[q].codingStyleParameters.decompositionLevelsCount);
620
- }
621
-
622
- var l = 0, r = 0, i = 0, k = 0;
623
-
624
- this.nextPacket = function JpxImage_nextPacket() {
625
- // Section B.12.1.1 Layer-resolution-component-position
626
- for (; l < layersCount; l++) {
627
- for (; r <= maxDecompositionLevelsCount; r++) {
628
- for (; i < componentsCount; i++) {
629
- var component = tile.components[i];
630
- if (r > component.codingStyleParameters.decompositionLevelsCount) {
631
- continue;
632
- }
633
-
634
- var resolution = component.resolutions[r];
635
- var numprecincts = resolution.precinctParameters.numprecincts;
636
- for (; k < numprecincts;) {
637
- var packet = createPacket(resolution, k, l);
638
- k++;
639
- return packet;
640
- }
641
- k = 0;
642
- }
643
- i = 0;
644
- }
645
- r = 0;
646
- }
647
- };
648
- }
649
- function ResolutionLayerComponentPositionIterator(context) {
650
- var siz = context.SIZ;
651
- var tileIndex = context.currentTile.index;
652
- var tile = context.tiles[tileIndex];
653
- var layersCount = tile.codingStyleDefaultParameters.layersCount;
654
- var componentsCount = siz.Csiz;
655
- var maxDecompositionLevelsCount = 0;
656
- for (var q = 0; q < componentsCount; q++) {
657
- maxDecompositionLevelsCount = Math.max(maxDecompositionLevelsCount,
658
- tile.components[q].codingStyleParameters.decompositionLevelsCount);
659
- }
660
-
661
- var r = 0, l = 0, i = 0, k = 0;
662
-
663
- this.nextPacket = function JpxImage_nextPacket() {
664
- // Section B.12.1.2 Resolution-layer-component-position
665
- for (; r <= maxDecompositionLevelsCount; r++) {
666
- for (; l < layersCount; l++) {
667
- for (; i < componentsCount; i++) {
668
- var component = tile.components[i];
669
- if (r > component.codingStyleParameters.decompositionLevelsCount) {
670
- continue;
671
- }
672
-
673
- var resolution = component.resolutions[r];
674
- var numprecincts = resolution.precinctParameters.numprecincts;
675
- for (; k < numprecincts;) {
676
- var packet = createPacket(resolution, k, l);
677
- k++;
678
- return packet;
679
- }
680
- k = 0;
681
- }
682
- i = 0;
683
- }
684
- l = 0;
685
- }
686
- };
687
- }
688
- function ResolutionPositionComponentLayerIterator(context) {
689
- var siz = context.SIZ;
690
- var tileIndex = context.currentTile.index;
691
- var tile = context.tiles[tileIndex];
692
- var layersCount = tile.codingStyleDefaultParameters.layersCount;
693
- var componentsCount = siz.Csiz;
694
- var l, r, c, p;
695
- var maxDecompositionLevelsCount = 0;
696
- for (c = 0; c < componentsCount; c++) {
697
- var component = tile.components[c];
698
- maxDecompositionLevelsCount = Math.max(maxDecompositionLevelsCount,
699
- component.codingStyleParameters.decompositionLevelsCount);
700
- }
701
- var maxNumPrecinctsInLevel = new Int32Array(
702
- maxDecompositionLevelsCount + 1);
703
- for (r = 0; r <= maxDecompositionLevelsCount; ++r) {
704
- var maxNumPrecincts = 0;
705
- for (c = 0; c < componentsCount; ++c) {
706
- var resolutions = tile.components[c].resolutions;
707
- if (r < resolutions.length) {
708
- maxNumPrecincts = Math.max(maxNumPrecincts,
709
- resolutions[r].precinctParameters.numprecincts);
710
- }
711
- }
712
- maxNumPrecinctsInLevel[r] = maxNumPrecincts;
713
- }
714
- l = 0;
715
- r = 0;
716
- c = 0;
717
- p = 0;
718
-
719
- this.nextPacket = function JpxImage_nextPacket() {
720
- // Section B.12.1.3 Resolution-position-component-layer
721
- for (; r <= maxDecompositionLevelsCount; r++) {
722
- for (; p < maxNumPrecinctsInLevel[r]; p++) {
723
- for (; c < componentsCount; c++) {
724
- var component = tile.components[c];
725
- if (r > component.codingStyleParameters.decompositionLevelsCount) {
726
- continue;
727
- }
728
- var resolution = component.resolutions[r];
729
- var numprecincts = resolution.precinctParameters.numprecincts;
730
- if (p >= numprecincts) {
731
- continue;
732
- }
733
- for (; l < layersCount;) {
734
- var packet = createPacket(resolution, p, l);
735
- l++;
736
- return packet;
737
- }
738
- l = 0;
739
- }
740
- c = 0;
741
- }
742
- p = 0;
743
- }
744
- };
745
- }
746
- function PositionComponentResolutionLayerIterator(context) {
747
- var siz = context.SIZ;
748
- var tileIndex = context.currentTile.index;
749
- var tile = context.tiles[tileIndex];
750
- var layersCount = tile.codingStyleDefaultParameters.layersCount;
751
- var componentsCount = siz.Csiz;
752
- var precinctsSizes = getPrecinctSizesInImageScale(tile);
753
- var precinctsIterationSizes = precinctsSizes;
754
- var l = 0, r = 0, c = 0, px = 0, py = 0;
755
-
756
- this.nextPacket = function JpxImage_nextPacket() {
757
- // Section B.12.1.4 Position-component-resolution-layer
758
- for (; py < precinctsIterationSizes.maxNumHigh; py++) {
759
- for (; px < precinctsIterationSizes.maxNumWide; px++) {
760
- for (; c < componentsCount; c++) {
761
- var component = tile.components[c];
762
- var decompositionLevelsCount =
763
- component.codingStyleParameters.decompositionLevelsCount;
764
- for (; r <= decompositionLevelsCount; r++) {
765
- var resolution = component.resolutions[r];
766
- var sizeInImageScale =
767
- precinctsSizes.components[c].resolutions[r];
768
- var k = getPrecinctIndexIfExist(
769
- px,
770
- py,
771
- sizeInImageScale,
772
- precinctsIterationSizes,
773
- resolution);
774
- if (k === null) {
775
- continue;
776
- }
777
- for (; l < layersCount;) {
778
- var packet = createPacket(resolution, k, l);
779
- l++;
780
- return packet;
781
- }
782
- l = 0;
783
- }
784
- r = 0;
785
- }
786
- c = 0;
787
- }
788
- px = 0;
789
- }
790
- };
791
- }
792
- function ComponentPositionResolutionLayerIterator(context) {
793
- var siz = context.SIZ;
794
- var tileIndex = context.currentTile.index;
795
- var tile = context.tiles[tileIndex];
796
- var layersCount = tile.codingStyleDefaultParameters.layersCount;
797
- var componentsCount = siz.Csiz;
798
- var precinctsSizes = getPrecinctSizesInImageScale(tile);
799
- var l = 0, r = 0, c = 0, px = 0, py = 0;
800
-
801
- this.nextPacket = function JpxImage_nextPacket() {
802
- // Section B.12.1.5 Component-position-resolution-layer
803
- for (; c < componentsCount; ++c) {
804
- var component = tile.components[c];
805
- var precinctsIterationSizes = precinctsSizes.components[c];
806
- var decompositionLevelsCount =
807
- component.codingStyleParameters.decompositionLevelsCount;
808
- for (; py < precinctsIterationSizes.maxNumHigh; py++) {
809
- for (; px < precinctsIterationSizes.maxNumWide; px++) {
810
- for (; r <= decompositionLevelsCount; r++) {
811
- var resolution = component.resolutions[r];
812
- var sizeInImageScale = precinctsIterationSizes.resolutions[r];
813
- var k = getPrecinctIndexIfExist(
814
- px,
815
- py,
816
- sizeInImageScale,
817
- precinctsIterationSizes,
818
- resolution);
819
- if (k === null) {
820
- continue;
821
- }
822
- for (; l < layersCount;) {
823
- var packet = createPacket(resolution, k, l);
824
- l++;
825
- return packet;
826
- }
827
- l = 0;
828
- }
829
- r = 0;
830
- }
831
- px = 0;
832
- }
833
- py = 0;
834
- }
835
- };
836
- }
837
- function getPrecinctIndexIfExist(
838
- pxIndex, pyIndex, sizeInImageScale, precinctIterationSizes, resolution) {
839
- var posX = pxIndex * precinctIterationSizes.minWidth;
840
- var posY = pyIndex * precinctIterationSizes.minHeight;
841
- if (posX % sizeInImageScale.width !== 0 ||
842
- posY % sizeInImageScale.height !== 0) {
843
- return null;
844
- }
845
- var startPrecinctRowIndex =
846
- (posY / sizeInImageScale.width) *
847
- resolution.precinctParameters.numprecinctswide;
848
- return (posX / sizeInImageScale.height) + startPrecinctRowIndex;
849
- }
850
- function getPrecinctSizesInImageScale(tile) {
851
- var componentsCount = tile.components.length;
852
- var minWidth = Number.MAX_VALUE;
853
- var minHeight = Number.MAX_VALUE;
854
- var maxNumWide = 0;
855
- var maxNumHigh = 0;
856
- var sizePerComponent = new Array(componentsCount);
857
- for (var c = 0; c < componentsCount; c++) {
858
- var component = tile.components[c];
859
- var decompositionLevelsCount =
860
- component.codingStyleParameters.decompositionLevelsCount;
861
- var sizePerResolution = new Array(decompositionLevelsCount + 1);
862
- var minWidthCurrentComponent = Number.MAX_VALUE;
863
- var minHeightCurrentComponent = Number.MAX_VALUE;
864
- var maxNumWideCurrentComponent = 0;
865
- var maxNumHighCurrentComponent = 0;
866
- var scale = 1;
867
- for (var r = decompositionLevelsCount; r >= 0; --r) {
868
- var resolution = component.resolutions[r];
869
- var widthCurrentResolution =
870
- scale * resolution.precinctParameters.precinctWidth;
871
- var heightCurrentResolution =
872
- scale * resolution.precinctParameters.precinctHeight;
873
- minWidthCurrentComponent = Math.min(
874
- minWidthCurrentComponent,
875
- widthCurrentResolution);
876
- minHeightCurrentComponent = Math.min(
877
- minHeightCurrentComponent,
878
- heightCurrentResolution);
879
- maxNumWideCurrentComponent = Math.max(maxNumWideCurrentComponent,
880
- resolution.precinctParameters.numprecinctswide);
881
- maxNumHighCurrentComponent = Math.max(maxNumHighCurrentComponent,
882
- resolution.precinctParameters.numprecinctshigh);
883
- sizePerResolution[r] = {
884
- width: widthCurrentResolution,
885
- height: heightCurrentResolution
886
- };
887
- scale <<= 1;
888
- }
889
- minWidth = Math.min(minWidth, minWidthCurrentComponent);
890
- minHeight = Math.min(minHeight, minHeightCurrentComponent);
891
- maxNumWide = Math.max(maxNumWide, maxNumWideCurrentComponent);
892
- maxNumHigh = Math.max(maxNumHigh, maxNumHighCurrentComponent);
893
- sizePerComponent[c] = {
894
- resolutions: sizePerResolution,
895
- minWidth: minWidthCurrentComponent,
896
- minHeight: minHeightCurrentComponent,
897
- maxNumWide: maxNumWideCurrentComponent,
898
- maxNumHigh: maxNumHighCurrentComponent
899
- };
900
- }
901
- return {
902
- components: sizePerComponent,
903
- minWidth: minWidth,
904
- minHeight: minHeight,
905
- maxNumWide: maxNumWide,
906
- maxNumHigh: maxNumHigh
907
- };
908
- }
909
- function buildPackets(context) {
910
- var siz = context.SIZ;
911
- var tileIndex = context.currentTile.index;
912
- var tile = context.tiles[tileIndex];
913
- var componentsCount = siz.Csiz;
914
- // Creating resolutions and sub-bands for each component
915
- for (var c = 0; c < componentsCount; c++) {
916
- var component = tile.components[c];
917
- var decompositionLevelsCount =
918
- component.codingStyleParameters.decompositionLevelsCount;
919
- // Section B.5 Resolution levels and sub-bands
920
- var resolutions = [];
921
- var subbands = [];
922
- for (var r = 0; r <= decompositionLevelsCount; r++) {
923
- var blocksDimensions = getBlocksDimensions(context, component, r);
924
- var resolution = {};
925
- var scale = 1 << (decompositionLevelsCount - r);
926
- resolution.trx0 = Math.ceil(component.tcx0 / scale);
927
- resolution.try0 = Math.ceil(component.tcy0 / scale);
928
- resolution.trx1 = Math.ceil(component.tcx1 / scale);
929
- resolution.try1 = Math.ceil(component.tcy1 / scale);
930
- resolution.resLevel = r;
931
- buildPrecincts(context, resolution, blocksDimensions);
932
- resolutions.push(resolution);
933
-
934
- var subband;
935
- if (r === 0) {
936
- // one sub-band (LL) with last decomposition
937
- subband = {};
938
- subband.type = 'LL';
939
- subband.tbx0 = Math.ceil(component.tcx0 / scale);
940
- subband.tby0 = Math.ceil(component.tcy0 / scale);
941
- subband.tbx1 = Math.ceil(component.tcx1 / scale);
942
- subband.tby1 = Math.ceil(component.tcy1 / scale);
943
- subband.resolution = resolution;
944
- buildCodeblocks(context, subband, blocksDimensions);
945
- subbands.push(subband);
946
- resolution.subbands = [subband];
947
- } else {
948
- var bscale = 1 << (decompositionLevelsCount - r + 1);
949
- var resolutionSubbands = [];
950
- // three sub-bands (HL, LH and HH) with rest of decompositions
951
- subband = {};
952
- subband.type = 'HL';
953
- subband.tbx0 = Math.ceil(component.tcx0 / bscale - 0.5);
954
- subband.tby0 = Math.ceil(component.tcy0 / bscale);
955
- subband.tbx1 = Math.ceil(component.tcx1 / bscale - 0.5);
956
- subband.tby1 = Math.ceil(component.tcy1 / bscale);
957
- subband.resolution = resolution;
958
- buildCodeblocks(context, subband, blocksDimensions);
959
- subbands.push(subband);
960
- resolutionSubbands.push(subband);
961
-
962
- subband = {};
963
- subband.type = 'LH';
964
- subband.tbx0 = Math.ceil(component.tcx0 / bscale);
965
- subband.tby0 = Math.ceil(component.tcy0 / bscale - 0.5);
966
- subband.tbx1 = Math.ceil(component.tcx1 / bscale);
967
- subband.tby1 = Math.ceil(component.tcy1 / bscale - 0.5);
968
- subband.resolution = resolution;
969
- buildCodeblocks(context, subband, blocksDimensions);
970
- subbands.push(subband);
971
- resolutionSubbands.push(subband);
972
-
973
- subband = {};
974
- subband.type = 'HH';
975
- subband.tbx0 = Math.ceil(component.tcx0 / bscale - 0.5);
976
- subband.tby0 = Math.ceil(component.tcy0 / bscale - 0.5);
977
- subband.tbx1 = Math.ceil(component.tcx1 / bscale - 0.5);
978
- subband.tby1 = Math.ceil(component.tcy1 / bscale - 0.5);
979
- subband.resolution = resolution;
980
- buildCodeblocks(context, subband, blocksDimensions);
981
- subbands.push(subband);
982
- resolutionSubbands.push(subband);
983
-
984
- resolution.subbands = resolutionSubbands;
985
- }
986
- }
987
- component.resolutions = resolutions;
988
- component.subbands = subbands;
989
- }
990
- // Generate the packets sequence
991
- var progressionOrder = tile.codingStyleDefaultParameters.progressionOrder;
992
- switch (progressionOrder) {
993
- case 0:
994
- tile.packetsIterator =
995
- new LayerResolutionComponentPositionIterator(context);
996
- break;
997
- case 1:
998
- tile.packetsIterator =
999
- new ResolutionLayerComponentPositionIterator(context);
1000
- break;
1001
- case 2:
1002
- tile.packetsIterator =
1003
- new ResolutionPositionComponentLayerIterator(context);
1004
- break;
1005
- case 3:
1006
- tile.packetsIterator =
1007
- new PositionComponentResolutionLayerIterator(context);
1008
- break;
1009
- case 4:
1010
- tile.packetsIterator =
1011
- new ComponentPositionResolutionLayerIterator(context);
1012
- break;
1013
- default:
1014
- throw new Error('JPX Error: Unsupported progression order ' +
1015
- progressionOrder);
1016
- }
1017
- }
1018
- function parseTilePackets(context, data, offset, dataLength) {
1019
- var position = 0;
1020
- var buffer, bufferSize = 0, skipNextBit = false;
1021
- function readBits(count) {
1022
- while (bufferSize < count) {
1023
- var b = data[offset + position];
1024
- position++;
1025
- if (skipNextBit) {
1026
- buffer = (buffer << 7) | b;
1027
- bufferSize += 7;
1028
- skipNextBit = false;
1029
- } else {
1030
- buffer = (buffer << 8) | b;
1031
- bufferSize += 8;
1032
- }
1033
- if (b === 0xFF) {
1034
- skipNextBit = true;
1035
- }
1036
- }
1037
- bufferSize -= count;
1038
- return (buffer >>> bufferSize) & ((1 << count) - 1);
1039
- }
1040
- function skipMarkerIfEqual(value) {
1041
- if (data[offset + position - 1] === 0xFF &&
1042
- data[offset + position] === value) {
1043
- skipBytes(1);
1044
- return true;
1045
- } else if (data[offset + position] === 0xFF &&
1046
- data[offset + position + 1] === value) {
1047
- skipBytes(2);
1048
- return true;
1049
- }
1050
- return false;
1051
- }
1052
- function skipBytes(count) {
1053
- position += count;
1054
- }
1055
- function alignToByte() {
1056
- bufferSize = 0;
1057
- if (skipNextBit) {
1058
- position++;
1059
- skipNextBit = false;
1060
- }
1061
- }
1062
- function readCodingpasses() {
1063
- if (readBits(1) === 0) {
1064
- return 1;
1065
- }
1066
- if (readBits(1) === 0) {
1067
- return 2;
1068
- }
1069
- var value = readBits(2);
1070
- if (value < 3) {
1071
- return value + 3;
1072
- }
1073
- value = readBits(5);
1074
- if (value < 31) {
1075
- return value + 6;
1076
- }
1077
- value = readBits(7);
1078
- return value + 37;
1079
- }
1080
- var tileIndex = context.currentTile.index;
1081
- var tile = context.tiles[tileIndex];
1082
- var sopMarkerUsed = context.COD.sopMarkerUsed;
1083
- var ephMarkerUsed = context.COD.ephMarkerUsed;
1084
- var packetsIterator = tile.packetsIterator;
1085
- while (position < dataLength) {
1086
- alignToByte();
1087
- if (sopMarkerUsed && skipMarkerIfEqual(0x91)) {
1088
- // Skip also marker segment length and packet sequence ID
1089
- skipBytes(4);
1090
- }
1091
- var packet = packetsIterator.nextPacket();
1092
- if (packet===undefined) {
1093
- //No more packets. Stream is truncated.
1094
- return;
1095
- }
1096
- if (!readBits(1)) {
1097
- continue;
1098
- }
1099
- var layerNumber = packet.layerNumber;
1100
- var queue = [], codeblock;
1101
- for (var i = 0, ii = packet.codeblocks.length; i < ii; i++) {
1102
- codeblock = packet.codeblocks[i];
1103
- var precinct = codeblock.precinct;
1104
- var codeblockColumn = codeblock.cbx - precinct.cbxMin;
1105
- var codeblockRow = codeblock.cby - precinct.cbyMin;
1106
- var codeblockIncluded = false;
1107
- var firstTimeInclusion = false;
1108
- var valueReady;
1109
- if (codeblock['included'] !== undefined) {
1110
- codeblockIncluded = !!readBits(1);
1111
- } else {
1112
- // reading inclusion tree
1113
- precinct = codeblock.precinct;
1114
- var inclusionTree, zeroBitPlanesTree;
1115
- if (precinct['inclusionTree'] !== undefined) {
1116
- inclusionTree = precinct.inclusionTree;
1117
- } else {
1118
- // building inclusion and zero bit-planes trees
1119
- var width = precinct.cbxMax - precinct.cbxMin + 1;
1120
- var height = precinct.cbyMax - precinct.cbyMin + 1;
1121
- inclusionTree = new InclusionTree(width, height, layerNumber);
1122
- zeroBitPlanesTree = new TagTree(width, height);
1123
- precinct.inclusionTree = inclusionTree;
1124
- precinct.zeroBitPlanesTree = zeroBitPlanesTree;
1125
- for (var l=0; l < layerNumber; l++) {
1126
- if (readBits(1) !== 0) {
1127
- throw new Error('JPX Error: Invalid tag tree');
1128
- }
1129
- }
1130
- }
1131
-
1132
- if (inclusionTree.reset(codeblockColumn, codeblockRow, layerNumber)) {
1133
- while (true) {
1134
- if (readBits(1)) {
1135
- valueReady = !inclusionTree.nextLevel();
1136
- if (valueReady) {
1137
- codeblock.included = true;
1138
- codeblockIncluded = firstTimeInclusion = true;
1139
- break;
1140
- }
1141
- } else {
1142
- inclusionTree.incrementValue(layerNumber);
1143
- break;
1144
- }
1145
- }
1146
- }
1147
- }
1148
- if (!codeblockIncluded) {
1149
- continue;
1150
- }
1151
- if (firstTimeInclusion) {
1152
- zeroBitPlanesTree = precinct.zeroBitPlanesTree;
1153
- zeroBitPlanesTree.reset(codeblockColumn, codeblockRow);
1154
- while (true) {
1155
- if (readBits(1)) {
1156
- valueReady = !zeroBitPlanesTree.nextLevel();
1157
- if (valueReady) {
1158
- break;
1159
- }
1160
- } else {
1161
- zeroBitPlanesTree.incrementValue();
1162
- }
1163
- }
1164
- codeblock.zeroBitPlanes = zeroBitPlanesTree.value;
1165
- }
1166
- var codingpasses = readCodingpasses();
1167
- while (readBits(1)) {
1168
- codeblock.Lblock++;
1169
- }
1170
- var codingpassesLog2 = log2(codingpasses);
1171
- // rounding down log2
1172
- var bits = ((codingpasses < (1 << codingpassesLog2)) ?
1173
- codingpassesLog2 - 1 : codingpassesLog2) + codeblock.Lblock;
1174
- var codedDataLength = readBits(bits);
1175
- queue.push({
1176
- codeblock: codeblock,
1177
- codingpasses: codingpasses,
1178
- dataLength: codedDataLength
1179
- });
1180
- }
1181
- alignToByte();
1182
- if (ephMarkerUsed) {
1183
- skipMarkerIfEqual(0x92);
1184
- }
1185
- while (queue.length > 0) {
1186
- var packetItem = queue.shift();
1187
- codeblock = packetItem.codeblock;
1188
- if (codeblock['data'] === undefined) {
1189
- codeblock.data = [];
1190
- }
1191
- codeblock.data.push({
1192
- data: data,
1193
- start: offset + position,
1194
- end: offset + position + packetItem.dataLength,
1195
- codingpasses: packetItem.codingpasses
1196
- });
1197
- position += packetItem.dataLength;
1198
- }
1199
- }
1200
- return position;
1201
- }
1202
- function copyCoefficients(coefficients, levelWidth, levelHeight, subband,
1203
- delta, mb, reversible, segmentationSymbolUsed) {
1204
- var x0 = subband.tbx0;
1205
- var y0 = subband.tby0;
1206
- var width = subband.tbx1 - subband.tbx0;
1207
- var codeblocks = subband.codeblocks;
1208
- var right = subband.type.charAt(0) === 'H' ? 1 : 0;
1209
- var bottom = subband.type.charAt(1) === 'H' ? levelWidth : 0;
1210
-
1211
- for (var i = 0, ii = codeblocks.length; i < ii; ++i) {
1212
- var codeblock = codeblocks[i];
1213
- var blockWidth = codeblock.tbx1_ - codeblock.tbx0_;
1214
- var blockHeight = codeblock.tby1_ - codeblock.tby0_;
1215
- if (blockWidth === 0 || blockHeight === 0) {
1216
- continue;
1217
- }
1218
- if (codeblock['data'] === undefined) {
1219
- continue;
1220
- }
1221
-
1222
- var bitModel, currentCodingpassType;
1223
- bitModel = new BitModel(blockWidth, blockHeight, codeblock.subbandType,
1224
- codeblock.zeroBitPlanes, mb);
1225
- currentCodingpassType = 2; // first bit plane starts from cleanup
1226
-
1227
- // collect data
1228
- var data = codeblock.data, totalLength = 0, codingpasses = 0;
1229
- var j, jj, dataItem;
1230
- for (j = 0, jj = data.length; j < jj; j++) {
1231
- dataItem = data[j];
1232
- totalLength += dataItem.end - dataItem.start;
1233
- codingpasses += dataItem.codingpasses;
1234
- }
1235
- var encodedData = new Int16Array(totalLength);
1236
- var position = 0;
1237
- for (j = 0, jj = data.length; j < jj; j++) {
1238
- dataItem = data[j];
1239
- var chunk = dataItem.data.subarray(dataItem.start, dataItem.end);
1240
- encodedData.set(chunk, position);
1241
- position += chunk.length;
1242
- }
1243
- // decoding the item
1244
- var decoder = new ArithmeticDecoder(encodedData, 0, totalLength);
1245
- bitModel.setDecoder(decoder);
1246
-
1247
- for (j = 0; j < codingpasses; j++) {
1248
- switch (currentCodingpassType) {
1249
- case 0:
1250
- bitModel.runSignificancePropogationPass();
1251
- break;
1252
- case 1:
1253
- bitModel.runMagnitudeRefinementPass();
1254
- break;
1255
- case 2:
1256
- bitModel.runCleanupPass();
1257
- if (segmentationSymbolUsed) {
1258
- bitModel.checkSegmentationSymbol();
1259
- }
1260
- break;
1261
- }
1262
- currentCodingpassType = (currentCodingpassType + 1) % 3;
1263
- }
1264
-
1265
- var offset = (codeblock.tbx0_ - x0) + (codeblock.tby0_ - y0) * width;
1266
- var sign = bitModel.coefficentsSign;
1267
- var magnitude = bitModel.coefficentsMagnitude;
1268
- var bitsDecoded = bitModel.bitsDecoded;
1269
- var magnitudeCorrection = reversible ? 0 : 0.5;
1270
- var k, n, nb;
1271
- position = 0;
1272
- // Do the interleaving of Section F.3.3 here, so we do not need
1273
- // to copy later. LL level is not interleaved, just copied.
1274
- var interleave = (subband.type !== 'LL');
1275
- for (j = 0; j < blockHeight; j++) {
1276
- var row = (offset / width) | 0; // row in the non-interleaved subband
1277
- var levelOffset = 2 * row * (levelWidth - width) + right + bottom;
1278
- for (k = 0; k < blockWidth; k++) {
1279
- n = magnitude[position];
1280
- if (n !== 0) {
1281
- n = (n + magnitudeCorrection) * delta;
1282
- if (sign[position] !== 0) {
1283
- n = -n;
1284
- }
1285
- nb = bitsDecoded[position];
1286
- var pos = interleave ? (levelOffset + (offset << 1)) : offset;
1287
- if (reversible && (nb >= mb)) {
1288
- coefficients[pos] = n;
1289
- } else {
1290
- coefficients[pos] = n * (1 << (mb - nb));
1291
- }
1292
- }
1293
- offset++;
1294
- position++;
1295
- }
1296
- offset += width - blockWidth;
1297
- }
1298
- }
1299
- }
1300
- function transformTile(context, tile, c) {
1301
- var component = tile.components[c];
1302
- var codingStyleParameters = component.codingStyleParameters;
1303
- var quantizationParameters = component.quantizationParameters;
1304
- var decompositionLevelsCount =
1305
- codingStyleParameters.decompositionLevelsCount;
1306
- var spqcds = quantizationParameters.SPqcds;
1307
- var scalarExpounded = quantizationParameters.scalarExpounded;
1308
- var guardBits = quantizationParameters.guardBits;
1309
- var segmentationSymbolUsed = codingStyleParameters.segmentationSymbolUsed;
1310
- var precision = context.components[c].precision;
1311
-
1312
- var reversible = codingStyleParameters.reversibleTransformation;
1313
- var transform = (reversible ? new ReversibleTransform() :
1314
- new IrreversibleTransform());
1315
-
1316
- var subbandCoefficients = [];
1317
- var b = 0;
1318
- for (var i = 0; i <= decompositionLevelsCount; i++) {
1319
- var resolution = component.resolutions[i];
1320
-
1321
- var width = resolution.trx1 - resolution.trx0;
1322
- var height = resolution.try1 - resolution.try0;
1323
- // Allocate space for the whole sublevel.
1324
- var coefficients = new Float32Array(width * height);
1325
-
1326
- for (var j = 0, jj = resolution.subbands.length; j < jj; j++) {
1327
- var mu, epsilon;
1328
- if (!scalarExpounded) {
1329
- // formula E-5
1330
- mu = spqcds[0].mu;
1331
- epsilon = spqcds[0].epsilon + (i > 0 ? 1 - i : 0);
1332
- } else {
1333
- mu = spqcds[b].mu;
1334
- epsilon = spqcds[b].epsilon;
1335
- b++;
1336
- }
1337
-
1338
- var subband = resolution.subbands[j];
1339
- var gainLog2 = SubbandsGainLog2[subband.type];
1340
-
1341
- // calulate quantization coefficient (Section E.1.1.1)
1342
- var delta = (reversible ? 1 :
1343
- Math.pow(2, precision + gainLog2 - epsilon) * (1 + mu / 2048));
1344
- var mb = (guardBits + epsilon - 1);
1345
-
1346
- // In the first resolution level, copyCoefficients will fill the
1347
- // whole array with coefficients. In the succeding passes,
1348
- // copyCoefficients will consecutively fill in the values that belong
1349
- // to the interleaved positions of the HL, LH, and HH coefficients.
1350
- // The LL coefficients will then be interleaved in Transform.iterate().
1351
- copyCoefficients(coefficients, width, height, subband, delta, mb,
1352
- reversible, segmentationSymbolUsed);
1353
- }
1354
- subbandCoefficients.push({
1355
- width: width,
1356
- height: height,
1357
- items: coefficients
1358
- });
1359
- }
1360
-
1361
- var result = transform.calculate(subbandCoefficients,
1362
- component.tcx0, component.tcy0);
1363
- return {
1364
- left: component.tcx0,
1365
- top: component.tcy0,
1366
- width: result.width,
1367
- height: result.height,
1368
- items: result.items
1369
- };
1370
- }
1371
- function transformComponents(context) {
1372
- var siz = context.SIZ;
1373
- var components = context.components;
1374
- var componentsCount = siz.Csiz;
1375
- var resultImages = [];
1376
- for (var i = 0, ii = context.tiles.length; i < ii; i++) {
1377
- var tile = context.tiles[i];
1378
- var transformedTiles = [];
1379
- var c;
1380
- for (c = 0; c < componentsCount; c++) {
1381
- transformedTiles[c] = transformTile(context, tile, c);
1382
- }
1383
- var tile0 = transformedTiles[0];
1384
- var out = new Int16Array(tile0.items.length * componentsCount);
1385
- var result = {
1386
- left: tile0.left,
1387
- top: tile0.top,
1388
- width: tile0.width,
1389
- height: tile0.height,
1390
- items: out
1391
- };
1392
-
1393
- // Section G.2.2 Inverse multi component transform
1394
- var shift, offset, max, min, maxK;
1395
- var pos = 0, j, jj, y0, y1, y2, r, g, b, k, val;
1396
- if (tile.codingStyleDefaultParameters.multipleComponentTransform) {
1397
- var fourComponents = componentsCount === 4;
1398
- var y0items = transformedTiles[0].items;
1399
- var y1items = transformedTiles[1].items;
1400
- var y2items = transformedTiles[2].items;
1401
- var y3items = fourComponents ? transformedTiles[3].items : null;
1402
-
1403
- // HACK: The multiple component transform formulas below assume that
1404
- // all components have the same precision. With this in mind, we
1405
- // compute shift and offset only once.
1406
- shift = components[0].precision - 8;
1407
- offset = (128 << shift) + 0.5;
1408
- max = 255 * (1 << shift);
1409
- maxK = max * 0.5;
1410
- min = -maxK;
1411
-
1412
- var component0 = tile.components[0];
1413
- var alpha01 = componentsCount - 3;
1414
- jj = y0items.length;
1415
- if (!component0.codingStyleParameters.reversibleTransformation) {
1416
- // inverse irreversible multiple component transform
1417
- for (j = 0; j < jj; j++, pos += alpha01) {
1418
- y0 = y0items[j] + offset;
1419
- y1 = y1items[j];
1420
- y2 = y2items[j];
1421
- r = y0 + 1.402 * y2;
1422
- g = y0 - 0.34413 * y1 - 0.71414 * y2;
1423
- b = y0 + 1.772 * y1;
1424
- out[pos++] = r <= 0 ? 0 : r >= max ? 255 : r >> shift;
1425
- out[pos++] = g <= 0 ? 0 : g >= max ? 255 : g >> shift;
1426
- out[pos++] = b <= 0 ? 0 : b >= max ? 255 : b >> shift;
1427
- }
1428
- } else {
1429
- // inverse reversible multiple component transform
1430
- for (j = 0; j < jj; j++, pos += alpha01) {
1431
- y0 = y0items[j] + offset;
1432
- y1 = y1items[j];
1433
- y2 = y2items[j];
1434
- g = y0 - ((y2 + y1) >> 2);
1435
- r = g + y2;
1436
- b = g + y1;
1437
- out[pos++] = r <= 0 ? 0 : r >= max ? 255 : r >> shift;
1438
- out[pos++] = g <= 0 ? 0 : g >= max ? 255 : g >> shift;
1439
- out[pos++] = b <= 0 ? 0 : b >= max ? 255 : b >> shift;
1440
- }
1441
- }
1442
- if (fourComponents) {
1443
- for (j = 0, pos = 3; j < jj; j++, pos += 4) {
1444
- k = y3items[j];
1445
- out[pos] = k <= min ? 0 : k >= maxK ? 255 : (k + offset) >> shift;
1446
- }
1447
- }
1448
- } else { // no multi-component transform
1449
- for (c = 0; c < componentsCount; c++) {
1450
- if (components[c].precision === 8){
1451
- var items = transformedTiles[c].items;
1452
- shift = components[c].precision - 8;
1453
- offset = (128 << shift) + 0.5;
1454
- max = (127.5 * (1 << shift));
1455
- min = -max;
1456
- for (pos = c, j = 0, jj = items.length; j < jj; j++) {
1457
- val = items[j];
1458
- out[pos] = val <= min ? 0 :
1459
- val >= max ? 255 : (val + offset) >> shift;
1460
- pos += componentsCount;
1461
- }
1462
- }else{
1463
- var isSigned = components[c].isSigned;
1464
- var items = transformedTiles[c].items;
1465
-
1466
- if(isSigned){
1467
- shift = 0;
1468
- offset = 0;
1469
- }else{
1470
- shift = components[c].precision - 8;
1471
- offset = (128 << shift) + 0.5;
1472
- }
1473
-
1474
- for (pos = c, j = 0, jj = items.length; j < jj; j++) {
1475
- val = items[j];
1476
- out[pos] = (val + offset);
1477
- pos += componentsCount;
1478
- }
1479
- }
1480
- }
1481
- }
1482
- resultImages.push(result);
1483
- }
1484
- return resultImages;
1485
- }
1486
- function initializeTile(context, tileIndex) {
1487
- var siz = context.SIZ;
1488
- var componentsCount = siz.Csiz;
1489
- var tile = context.tiles[tileIndex];
1490
- for (var c = 0; c < componentsCount; c++) {
1491
- var component = tile.components[c];
1492
- var qcdOrQcc = (context.currentTile.QCC[c] !== undefined ?
1493
- context.currentTile.QCC[c] : context.currentTile.QCD);
1494
- component.quantizationParameters = qcdOrQcc;
1495
- var codOrCoc = (context.currentTile.COC[c] !== undefined ?
1496
- context.currentTile.COC[c] : context.currentTile.COD);
1497
- component.codingStyleParameters = codOrCoc;
1498
- }
1499
- tile.codingStyleDefaultParameters = context.currentTile.COD;
1500
- }
1501
-
1502
- // Section B.10.2 Tag trees
1503
- var TagTree = (function TagTreeClosure() {
1504
- function TagTree(width, height) {
1505
- var levelsLength = log2(Math.max(width, height)) + 1;
1506
- this.levels = [];
1507
- for (var i = 0; i < levelsLength; i++) {
1508
- var level = {
1509
- width: width,
1510
- height: height,
1511
- items: []
1512
- };
1513
- this.levels.push(level);
1514
- width = Math.ceil(width / 2);
1515
- height = Math.ceil(height / 2);
1516
- }
1517
- }
1518
- TagTree.prototype = {
1519
- reset: function TagTree_reset(i, j) {
1520
- var currentLevel = 0, value = 0, level;
1521
- while (currentLevel < this.levels.length) {
1522
- level = this.levels[currentLevel];
1523
- var index = i + j * level.width;
1524
- if (level.items[index] !== undefined) {
1525
- value = level.items[index];
1526
- break;
1527
- }
1528
- level.index = index;
1529
- i >>= 1;
1530
- j >>= 1;
1531
- currentLevel++;
1532
- }
1533
- currentLevel--;
1534
- level = this.levels[currentLevel];
1535
- level.items[level.index] = value;
1536
- this.currentLevel = currentLevel;
1537
- delete this.value;
1538
- },
1539
- incrementValue: function TagTree_incrementValue() {
1540
- var level = this.levels[this.currentLevel];
1541
- level.items[level.index]++;
1542
- },
1543
- nextLevel: function TagTree_nextLevel() {
1544
- var currentLevel = this.currentLevel;
1545
- var level = this.levels[currentLevel];
1546
- var value = level.items[level.index];
1547
- currentLevel--;
1548
- if (currentLevel < 0) {
1549
- this.value = value;
1550
- return false;
1551
- }
1552
-
1553
- this.currentLevel = currentLevel;
1554
- level = this.levels[currentLevel];
1555
- level.items[level.index] = value;
1556
- return true;
1557
- }
1558
- };
1559
- return TagTree;
1560
- })();
1561
-
1562
- var InclusionTree = (function InclusionTreeClosure() {
1563
- function InclusionTree(width, height, defaultValue) {
1564
- var levelsLength = log2(Math.max(width, height)) + 1;
1565
- this.levels = [];
1566
- for (var i = 0; i < levelsLength; i++) {
1567
- var items = new Int16Array(width * height);
1568
- for (var j = 0, jj = items.length; j < jj; j++) {
1569
- items[j] = defaultValue;
1570
- }
1571
-
1572
- var level = {
1573
- width: width,
1574
- height: height,
1575
- items: items
1576
- };
1577
- this.levels.push(level);
1578
-
1579
- width = Math.ceil(width / 2);
1580
- height = Math.ceil(height / 2);
1581
- }
1582
- }
1583
- InclusionTree.prototype = {
1584
- reset: function InclusionTree_reset(i, j, stopValue) {
1585
- var currentLevel = 0;
1586
- while (currentLevel < this.levels.length) {
1587
- var level = this.levels[currentLevel];
1588
- var index = i + j * level.width;
1589
- level.index = index;
1590
- var value = level.items[index];
1591
-
1592
- if (value === 0xFF) {
1593
- break;
1594
- }
1595
-
1596
- if (value > stopValue) {
1597
- this.currentLevel = currentLevel;
1598
- // already know about this one, propagating the value to top levels
1599
- this.propagateValues();
1600
- return false;
1601
- }
1602
-
1603
- i >>= 1;
1604
- j >>= 1;
1605
- currentLevel++;
1606
- }
1607
- this.currentLevel = currentLevel - 1;
1608
- return true;
1609
- },
1610
- incrementValue: function InclusionTree_incrementValue(stopValue) {
1611
- var level = this.levels[this.currentLevel];
1612
- level.items[level.index] = stopValue + 1;
1613
- this.propagateValues();
1614
- },
1615
- propagateValues: function InclusionTree_propagateValues() {
1616
- var levelIndex = this.currentLevel;
1617
- var level = this.levels[levelIndex];
1618
- var currentValue = level.items[level.index];
1619
- while (--levelIndex >= 0) {
1620
- level = this.levels[levelIndex];
1621
- level.items[level.index] = currentValue;
1622
- }
1623
- },
1624
- nextLevel: function InclusionTree_nextLevel() {
1625
- var currentLevel = this.currentLevel;
1626
- var level = this.levels[currentLevel];
1627
- var value = level.items[level.index];
1628
- level.items[level.index] = 0xFF;
1629
- currentLevel--;
1630
- if (currentLevel < 0) {
1631
- return false;
1632
- }
1633
-
1634
- this.currentLevel = currentLevel;
1635
- level = this.levels[currentLevel];
1636
- level.items[level.index] = value;
1637
- return true;
1638
- }
1639
- };
1640
- return InclusionTree;
1641
- })();
1642
-
1643
- // Section D. Coefficient bit modeling
1644
- var BitModel = (function BitModelClosure() {
1645
- var UNIFORM_CONTEXT = 17;
1646
- var RUNLENGTH_CONTEXT = 18;
1647
- // Table D-1
1648
- // The index is binary presentation: 0dddvvhh, ddd - sum of Di (0..4),
1649
- // vv - sum of Vi (0..2), and hh - sum of Hi (0..2)
1650
- var LLAndLHContextsLabel = new Uint8Array([
1651
- 0, 5, 8, 0, 3, 7, 8, 0, 4, 7, 8, 0, 0, 0, 0, 0, 1, 6, 8, 0, 3, 7, 8, 0, 4,
1652
- 7, 8, 0, 0, 0, 0, 0, 2, 6, 8, 0, 3, 7, 8, 0, 4, 7, 8, 0, 0, 0, 0, 0, 2, 6,
1653
- 8, 0, 3, 7, 8, 0, 4, 7, 8, 0, 0, 0, 0, 0, 2, 6, 8, 0, 3, 7, 8, 0, 4, 7, 8
1654
- ]);
1655
- var HLContextLabel = new Uint8Array([
1656
- 0, 3, 4, 0, 5, 7, 7, 0, 8, 8, 8, 0, 0, 0, 0, 0, 1, 3, 4, 0, 6, 7, 7, 0, 8,
1657
- 8, 8, 0, 0, 0, 0, 0, 2, 3, 4, 0, 6, 7, 7, 0, 8, 8, 8, 0, 0, 0, 0, 0, 2, 3,
1658
- 4, 0, 6, 7, 7, 0, 8, 8, 8, 0, 0, 0, 0, 0, 2, 3, 4, 0, 6, 7, 7, 0, 8, 8, 8
1659
- ]);
1660
- var HHContextLabel = new Uint8Array([
1661
- 0, 1, 2, 0, 1, 2, 2, 0, 2, 2, 2, 0, 0, 0, 0, 0, 3, 4, 5, 0, 4, 5, 5, 0, 5,
1662
- 5, 5, 0, 0, 0, 0, 0, 6, 7, 7, 0, 7, 7, 7, 0, 7, 7, 7, 0, 0, 0, 0, 0, 8, 8,
1663
- 8, 0, 8, 8, 8, 0, 8, 8, 8, 0, 0, 0, 0, 0, 8, 8, 8, 0, 8, 8, 8, 0, 8, 8, 8
1664
- ]);
1665
-
1666
- function BitModel(width, height, subband, zeroBitPlanes, mb) {
1667
- this.width = width;
1668
- this.height = height;
1669
-
1670
- this.contextLabelTable = (subband === 'HH' ? HHContextLabel :
1671
- (subband === 'HL' ? HLContextLabel : LLAndLHContextsLabel));
1672
-
1673
- var coefficientCount = width * height;
1674
-
1675
- // coefficients outside the encoding region treated as insignificant
1676
- // add border state cells for significanceState
1677
- this.neighborsSignificance = new Uint8Array(coefficientCount);
1678
- this.coefficentsSign = new Uint8Array(coefficientCount);
1679
- this.coefficentsMagnitude = mb > 14 ? new Uint32Array(coefficientCount) :
1680
- mb > 6 ? new Uint16Array(coefficientCount) :
1681
- new Uint8Array(coefficientCount);
1682
- this.processingFlags = new Uint8Array(coefficientCount);
1683
-
1684
- var bitsDecoded = new Uint8Array(coefficientCount);
1685
- if (zeroBitPlanes !== 0) {
1686
- for (var i = 0; i < coefficientCount; i++) {
1687
- bitsDecoded[i] = zeroBitPlanes;
1688
- }
1689
- }
1690
- this.bitsDecoded = bitsDecoded;
1691
-
1692
- this.reset();
1693
- }
1694
-
1695
- BitModel.prototype = {
1696
- setDecoder: function BitModel_setDecoder(decoder) {
1697
- this.decoder = decoder;
1698
- },
1699
- reset: function BitModel_reset() {
1700
- // We have 17 contexts that are accessed via context labels,
1701
- // plus the uniform and runlength context.
1702
- this.contexts = new Int8Array(19);
1703
-
1704
- // Contexts are packed into 1 byte:
1705
- // highest 7 bits carry the index, lowest bit carries mps
1706
- this.contexts[0] = (4 << 1) | 0;
1707
- this.contexts[UNIFORM_CONTEXT] = (46 << 1) | 0;
1708
- this.contexts[RUNLENGTH_CONTEXT] = (3 << 1) | 0;
1709
- },
1710
- setNeighborsSignificance:
1711
- function BitModel_setNeighborsSignificance(row, column, index) {
1712
- var neighborsSignificance = this.neighborsSignificance;
1713
- var width = this.width, height = this.height;
1714
- var left = (column > 0);
1715
- var right = (column + 1 < width);
1716
- var i;
1717
-
1718
- if (row > 0) {
1719
- i = index - width;
1720
- if (left) {
1721
- neighborsSignificance[i - 1] += 0x10;
1722
- }
1723
- if (right) {
1724
- neighborsSignificance[i + 1] += 0x10;
1725
- }
1726
- neighborsSignificance[i] += 0x04;
1727
- }
1728
-
1729
- if (row + 1 < height) {
1730
- i = index + width;
1731
- if (left) {
1732
- neighborsSignificance[i - 1] += 0x10;
1733
- }
1734
- if (right) {
1735
- neighborsSignificance[i + 1] += 0x10;
1736
- }
1737
- neighborsSignificance[i] += 0x04;
1738
- }
1739
-
1740
- if (left) {
1741
- neighborsSignificance[index - 1] += 0x01;
1742
- }
1743
- if (right) {
1744
- neighborsSignificance[index + 1] += 0x01;
1745
- }
1746
- neighborsSignificance[index] |= 0x80;
1747
- },
1748
- runSignificancePropogationPass:
1749
- function BitModel_runSignificancePropogationPass() {
1750
- var decoder = this.decoder;
1751
- var width = this.width, height = this.height;
1752
- var coefficentsMagnitude = this.coefficentsMagnitude;
1753
- var coefficentsSign = this.coefficentsSign;
1754
- var neighborsSignificance = this.neighborsSignificance;
1755
- var processingFlags = this.processingFlags;
1756
- var contexts = this.contexts;
1757
- var labels = this.contextLabelTable;
1758
- var bitsDecoded = this.bitsDecoded;
1759
- var processedInverseMask = ~1;
1760
- var processedMask = 1;
1761
- var firstMagnitudeBitMask = 2;
1762
-
1763
- for (var i0 = 0; i0 < height; i0 += 4) {
1764
- for (var j = 0; j < width; j++) {
1765
- var index = i0 * width + j;
1766
- for (var i1 = 0; i1 < 4; i1++, index += width) {
1767
- var i = i0 + i1;
1768
- if (i >= height) {
1769
- break;
1770
- }
1771
- // clear processed flag first
1772
- processingFlags[index] &= processedInverseMask;
1773
-
1774
- if (coefficentsMagnitude[index] ||
1775
- !neighborsSignificance[index]) {
1776
- continue;
1777
- }
1778
-
1779
- var contextLabel = labels[neighborsSignificance[index]];
1780
- var decision = decoder.readBit(contexts, contextLabel);
1781
- if (decision) {
1782
- var sign = this.decodeSignBit(i, j, index);
1783
- coefficentsSign[index] = sign;
1784
- coefficentsMagnitude[index] = 1;
1785
- this.setNeighborsSignificance(i, j, index);
1786
- processingFlags[index] |= firstMagnitudeBitMask;
1787
- }
1788
- bitsDecoded[index]++;
1789
- processingFlags[index] |= processedMask;
1790
- }
1791
- }
1792
- }
1793
- },
1794
- decodeSignBit: function BitModel_decodeSignBit(row, column, index) {
1795
- var width = this.width, height = this.height;
1796
- var coefficentsMagnitude = this.coefficentsMagnitude;
1797
- var coefficentsSign = this.coefficentsSign;
1798
- var contribution, sign0, sign1, significance1;
1799
- var contextLabel, decoded;
1800
-
1801
- // calculate horizontal contribution
1802
- significance1 = (column > 0 && coefficentsMagnitude[index - 1] !== 0);
1803
- if (column + 1 < width && coefficentsMagnitude[index + 1] !== 0) {
1804
- sign1 = coefficentsSign[index + 1];
1805
- if (significance1) {
1806
- sign0 = coefficentsSign[index - 1];
1807
- contribution = 1 - sign1 - sign0;
1808
- } else {
1809
- contribution = 1 - sign1 - sign1;
1810
- }
1811
- } else if (significance1) {
1812
- sign0 = coefficentsSign[index - 1];
1813
- contribution = 1 - sign0 - sign0;
1814
- } else {
1815
- contribution = 0;
1816
- }
1817
- var horizontalContribution = 3 * contribution;
1818
-
1819
- // calculate vertical contribution and combine with the horizontal
1820
- significance1 = (row > 0 && coefficentsMagnitude[index - width] !== 0);
1821
- if (row + 1 < height && coefficentsMagnitude[index + width] !== 0) {
1822
- sign1 = coefficentsSign[index + width];
1823
- if (significance1) {
1824
- sign0 = coefficentsSign[index - width];
1825
- contribution = 1 - sign1 - sign0 + horizontalContribution;
1826
- } else {
1827
- contribution = 1 - sign1 - sign1 + horizontalContribution;
1828
- }
1829
- } else if (significance1) {
1830
- sign0 = coefficentsSign[index - width];
1831
- contribution = 1 - sign0 - sign0 + horizontalContribution;
1832
- } else {
1833
- contribution = horizontalContribution;
1834
- }
1835
-
1836
- if (contribution >= 0) {
1837
- contextLabel = 9 + contribution;
1838
- decoded = this.decoder.readBit(this.contexts, contextLabel);
1839
- } else {
1840
- contextLabel = 9 - contribution;
1841
- decoded = this.decoder.readBit(this.contexts, contextLabel) ^ 1;
1842
- }
1843
- return decoded;
1844
- },
1845
- runMagnitudeRefinementPass:
1846
- function BitModel_runMagnitudeRefinementPass() {
1847
- var decoder = this.decoder;
1848
- var width = this.width, height = this.height;
1849
- var coefficentsMagnitude = this.coefficentsMagnitude;
1850
- var neighborsSignificance = this.neighborsSignificance;
1851
- var contexts = this.contexts;
1852
- var bitsDecoded = this.bitsDecoded;
1853
- var processingFlags = this.processingFlags;
1854
- var processedMask = 1;
1855
- var firstMagnitudeBitMask = 2;
1856
- var length = width * height;
1857
- var width4 = width * 4;
1858
-
1859
- for (var index0 = 0, indexNext; index0 < length; index0 = indexNext) {
1860
- indexNext = Math.min(length, index0 + width4);
1861
- for (var j = 0; j < width; j++) {
1862
- for (var index = index0 + j; index < indexNext; index += width) {
1863
-
1864
- // significant but not those that have just become
1865
- if (!coefficentsMagnitude[index] ||
1866
- (processingFlags[index] & processedMask) !== 0) {
1867
- continue;
1868
- }
1869
-
1870
- var contextLabel = 16;
1871
- if ((processingFlags[index] & firstMagnitudeBitMask) !== 0) {
1872
- processingFlags[index] ^= firstMagnitudeBitMask;
1873
- // first refinement
1874
- var significance = neighborsSignificance[index] & 127;
1875
- contextLabel = significance === 0 ? 15 : 14;
1876
- }
1877
-
1878
- var bit = decoder.readBit(contexts, contextLabel);
1879
- coefficentsMagnitude[index] =
1880
- (coefficentsMagnitude[index] << 1) | bit;
1881
- bitsDecoded[index]++;
1882
- processingFlags[index] |= processedMask;
1883
- }
1884
- }
1885
- }
1886
- },
1887
- runCleanupPass: function BitModel_runCleanupPass() {
1888
- var decoder = this.decoder;
1889
- var width = this.width, height = this.height;
1890
- var neighborsSignificance = this.neighborsSignificance;
1891
- var coefficentsMagnitude = this.coefficentsMagnitude;
1892
- var coefficentsSign = this.coefficentsSign;
1893
- var contexts = this.contexts;
1894
- var labels = this.contextLabelTable;
1895
- var bitsDecoded = this.bitsDecoded;
1896
- var processingFlags = this.processingFlags;
1897
- var processedMask = 1;
1898
- var firstMagnitudeBitMask = 2;
1899
- var oneRowDown = width;
1900
- var twoRowsDown = width * 2;
1901
- var threeRowsDown = width * 3;
1902
- var iNext;
1903
- for (var i0 = 0; i0 < height; i0 = iNext) {
1904
- iNext = Math.min(i0 + 4, height);
1905
- var indexBase = i0 * width;
1906
- var checkAllEmpty = i0 + 3 < height;
1907
- for (var j = 0; j < width; j++) {
1908
- var index0 = indexBase + j;
1909
- // using the property: labels[neighborsSignificance[index]] === 0
1910
- // when neighborsSignificance[index] === 0
1911
- var allEmpty = (checkAllEmpty &&
1912
- processingFlags[index0] === 0 &&
1913
- processingFlags[index0 + oneRowDown] === 0 &&
1914
- processingFlags[index0 + twoRowsDown] === 0 &&
1915
- processingFlags[index0 + threeRowsDown] === 0 &&
1916
- neighborsSignificance[index0] === 0 &&
1917
- neighborsSignificance[index0 + oneRowDown] === 0 &&
1918
- neighborsSignificance[index0 + twoRowsDown] === 0 &&
1919
- neighborsSignificance[index0 + threeRowsDown] === 0);
1920
- var i1 = 0, index = index0;
1921
- var i = i0, sign;
1922
- if (allEmpty) {
1923
- var hasSignificantCoefficent =
1924
- decoder.readBit(contexts, RUNLENGTH_CONTEXT);
1925
- if (!hasSignificantCoefficent) {
1926
- bitsDecoded[index0]++;
1927
- bitsDecoded[index0 + oneRowDown]++;
1928
- bitsDecoded[index0 + twoRowsDown]++;
1929
- bitsDecoded[index0 + threeRowsDown]++;
1930
- continue; // next column
1931
- }
1932
- i1 = (decoder.readBit(contexts, UNIFORM_CONTEXT) << 1) |
1933
- decoder.readBit(contexts, UNIFORM_CONTEXT);
1934
- if (i1 !== 0) {
1935
- i = i0 + i1;
1936
- index += i1 * width;
1937
- }
1938
-
1939
- sign = this.decodeSignBit(i, j, index);
1940
- coefficentsSign[index] = sign;
1941
- coefficentsMagnitude[index] = 1;
1942
- this.setNeighborsSignificance(i, j, index);
1943
- processingFlags[index] |= firstMagnitudeBitMask;
1944
-
1945
- index = index0;
1946
- for (var i2 = i0; i2 <= i; i2++, index += width) {
1947
- bitsDecoded[index]++;
1948
- }
1949
-
1950
- i1++;
1951
- }
1952
- for (i = i0 + i1; i < iNext; i++, index += width) {
1953
- if (coefficentsMagnitude[index] ||
1954
- (processingFlags[index] & processedMask) !== 0) {
1955
- continue;
1956
- }
1957
-
1958
- var contextLabel = labels[neighborsSignificance[index]];
1959
- var decision = decoder.readBit(contexts, contextLabel);
1960
- if (decision === 1) {
1961
- sign = this.decodeSignBit(i, j, index);
1962
- coefficentsSign[index] = sign;
1963
- coefficentsMagnitude[index] = 1;
1964
- this.setNeighborsSignificance(i, j, index);
1965
- processingFlags[index] |= firstMagnitudeBitMask;
1966
- }
1967
- bitsDecoded[index]++;
1968
- }
1969
- }
1970
- }
1971
- },
1972
- checkSegmentationSymbol: function BitModel_checkSegmentationSymbol() {
1973
- var decoder = this.decoder;
1974
- var contexts = this.contexts;
1975
- var symbol = (decoder.readBit(contexts, UNIFORM_CONTEXT) << 3) |
1976
- (decoder.readBit(contexts, UNIFORM_CONTEXT) << 2) |
1977
- (decoder.readBit(contexts, UNIFORM_CONTEXT) << 1) |
1978
- decoder.readBit(contexts, UNIFORM_CONTEXT);
1979
- if (symbol !== 0xA) {
1980
- throw new Error('JPX Error: Invalid segmentation symbol');
1981
- }
1982
- }
1983
- };
1984
-
1985
- return BitModel;
1986
- })();
1987
-
1988
- // Section F, Discrete wavelet transformation
1989
- var Transform = (function TransformClosure() {
1990
- function Transform() {}
1991
-
1992
- Transform.prototype.calculate =
1993
- function transformCalculate(subbands, u0, v0) {
1994
- var ll = subbands[0];
1995
- for (var i = 1, ii = subbands.length; i < ii; i++) {
1996
- ll = this.iterate(ll, subbands[i], u0, v0);
1997
- }
1998
- return ll;
1999
- };
2000
- Transform.prototype.extend = function extend(buffer, offset, size) {
2001
- // Section F.3.7 extending... using max extension of 4
2002
- var i1 = offset - 1, j1 = offset + 1;
2003
- var i2 = offset + size - 2, j2 = offset + size;
2004
- buffer[i1--] = buffer[j1++];
2005
- buffer[j2++] = buffer[i2--];
2006
- buffer[i1--] = buffer[j1++];
2007
- buffer[j2++] = buffer[i2--];
2008
- buffer[i1--] = buffer[j1++];
2009
- buffer[j2++] = buffer[i2--];
2010
- buffer[i1] = buffer[j1];
2011
- buffer[j2] = buffer[i2];
2012
- };
2013
- Transform.prototype.iterate = function Transform_iterate(ll, hl_lh_hh,
2014
- u0, v0) {
2015
- var llWidth = ll.width, llHeight = ll.height, llItems = ll.items;
2016
- var width = hl_lh_hh.width;
2017
- var height = hl_lh_hh.height;
2018
- var items = hl_lh_hh.items;
2019
- var i, j, k, l, u, v;
2020
-
2021
- // Interleave LL according to Section F.3.3
2022
- for (k = 0, i = 0; i < llHeight; i++) {
2023
- l = i * 2 * width;
2024
- for (j = 0; j < llWidth; j++, k++, l += 2) {
2025
- items[l] = llItems[k];
2026
- }
2027
- }
2028
- // The LL band is not needed anymore.
2029
- llItems = ll.items = null;
2030
-
2031
- var bufferPadding = 4;
2032
- var rowBuffer = new Float32Array(width + 2 * bufferPadding);
2033
-
2034
- // Section F.3.4 HOR_SR
2035
- if (width === 1) {
2036
- // if width = 1, when u0 even keep items as is, when odd divide by 2
2037
- if ((u0 & 1) !== 0) {
2038
- for (v = 0, k = 0; v < height; v++, k += width) {
2039
- items[k] *= 0.5;
2040
- }
2041
- }
2042
- } else {
2043
- for (v = 0, k = 0; v < height; v++, k += width) {
2044
- rowBuffer.set(items.subarray(k, k + width), bufferPadding);
2045
-
2046
- this.extend(rowBuffer, bufferPadding, width);
2047
- this.filter(rowBuffer, bufferPadding, width);
2048
-
2049
- items.set(
2050
- rowBuffer.subarray(bufferPadding, bufferPadding + width),
2051
- k);
2052
- }
2053
- }
2054
-
2055
- // Accesses to the items array can take long, because it may not fit into
2056
- // CPU cache and has to be fetched from main memory. Since subsequent
2057
- // accesses to the items array are not local when reading columns, we
2058
- // have a cache miss every time. To reduce cache misses, get up to
2059
- // 'numBuffers' items at a time and store them into the individual
2060
- // buffers. The colBuffers should be small enough to fit into CPU cache.
2061
- var numBuffers = 16;
2062
- var colBuffers = [];
2063
- for (i = 0; i < numBuffers; i++) {
2064
- colBuffers.push(new Float32Array(height + 2 * bufferPadding));
2065
- }
2066
- var b, currentBuffer = 0;
2067
- ll = bufferPadding + height;
2068
-
2069
- // Section F.3.5 VER_SR
2070
- if (height === 1) {
2071
- // if height = 1, when v0 even keep items as is, when odd divide by 2
2072
- if ((v0 & 1) !== 0) {
2073
- for (u = 0; u < width; u++) {
2074
- items[u] *= 0.5;
2075
- }
2076
- }
2077
- } else {
2078
- for (u = 0; u < width; u++) {
2079
- // if we ran out of buffers, copy several image columns at once
2080
- if (currentBuffer === 0) {
2081
- numBuffers = Math.min(width - u, numBuffers);
2082
- for (k = u, l = bufferPadding; l < ll; k += width, l++) {
2083
- for (b = 0; b < numBuffers; b++) {
2084
- colBuffers[b][l] = items[k + b];
2085
- }
2086
- }
2087
- currentBuffer = numBuffers;
2088
- }
2089
-
2090
- currentBuffer--;
2091
- var buffer = colBuffers[currentBuffer];
2092
- this.extend(buffer, bufferPadding, height);
2093
- this.filter(buffer, bufferPadding, height);
2094
-
2095
- // If this is last buffer in this group of buffers, flush all buffers.
2096
- if (currentBuffer === 0) {
2097
- k = u - numBuffers + 1;
2098
- for (l = bufferPadding; l < ll; k += width, l++) {
2099
- for (b = 0; b < numBuffers; b++) {
2100
- items[k + b] = colBuffers[b][l];
2101
- }
2102
- }
2103
- }
2104
- }
2105
- }
2106
-
2107
- return {
2108
- width: width,
2109
- height: height,
2110
- items: items
2111
- };
2112
- };
2113
- return Transform;
2114
- })();
2115
-
2116
- // Section 3.8.2 Irreversible 9-7 filter
2117
- var IrreversibleTransform = (function IrreversibleTransformClosure() {
2118
- function IrreversibleTransform() {
2119
- Transform.call(this);
2120
- }
2121
-
2122
- IrreversibleTransform.prototype = Object.create(Transform.prototype);
2123
- IrreversibleTransform.prototype.filter =
2124
- function irreversibleTransformFilter(x, offset, length) {
2125
- var len = length >> 1;
2126
- offset = offset | 0;
2127
- var j, n, current, next;
2128
-
2129
- var alpha = -1.586134342059924;
2130
- var beta = -0.052980118572961;
2131
- var gamma = 0.882911075530934;
2132
- var delta = 0.443506852043971;
2133
- var K = 1.230174104914001;
2134
- var K_ = 1 / K;
2135
-
2136
- // step 1 is combined with step 3
2137
-
2138
- // step 2
2139
- j = offset - 3;
2140
- for (n = len + 4; n--; j += 2) {
2141
- x[j] *= K_;
2142
- }
2143
-
2144
- // step 1 & 3
2145
- j = offset - 2;
2146
- current = delta * x[j -1];
2147
- for (n = len + 3; n--; j += 2) {
2148
- next = delta * x[j + 1];
2149
- x[j] = K * x[j] - current - next;
2150
- if (n--) {
2151
- j += 2;
2152
- current = delta * x[j + 1];
2153
- x[j] = K * x[j] - current - next;
2154
- } else {
2155
- break;
2156
- }
2157
- }
2158
-
2159
- // step 4
2160
- j = offset - 1;
2161
- current = gamma * x[j - 1];
2162
- for (n = len + 2; n--; j += 2) {
2163
- next = gamma * x[j + 1];
2164
- x[j] -= current + next;
2165
- if (n--) {
2166
- j += 2;
2167
- current = gamma * x[j + 1];
2168
- x[j] -= current + next;
2169
- } else {
2170
- break;
2171
- }
2172
- }
2173
-
2174
- // step 5
2175
- j = offset;
2176
- current = beta * x[j - 1];
2177
- for (n = len + 1; n--; j += 2) {
2178
- next = beta * x[j + 1];
2179
- x[j] -= current + next;
2180
- if (n--) {
2181
- j += 2;
2182
- current = beta * x[j + 1];
2183
- x[j] -= current + next;
2184
- } else {
2185
- break;
2186
- }
2187
- }
2188
-
2189
- // step 6
2190
- if (len !== 0) {
2191
- j = offset + 1;
2192
- current = alpha * x[j - 1];
2193
- for (n = len; n--; j += 2) {
2194
- next = alpha * x[j + 1];
2195
- x[j] -= current + next;
2196
- if (n--) {
2197
- j += 2;
2198
- current = alpha * x[j + 1];
2199
- x[j] -= current + next;
2200
- } else {
2201
- break;
2202
- }
2203
- }
2204
- }
2205
- };
2206
-
2207
- return IrreversibleTransform;
2208
- })();
2209
-
2210
- // Section 3.8.1 Reversible 5-3 filter
2211
- var ReversibleTransform = (function ReversibleTransformClosure() {
2212
- function ReversibleTransform() {
2213
- Transform.call(this);
2214
- }
2215
-
2216
- ReversibleTransform.prototype = Object.create(Transform.prototype);
2217
- ReversibleTransform.prototype.filter =
2218
- function reversibleTransformFilter(x, offset, length) {
2219
- var len = length >> 1;
2220
- offset = offset | 0;
2221
- var j, n;
2222
-
2223
- for (j = offset, n = len + 1; n--; j += 2) {
2224
- x[j] -= (x[j - 1] + x[j + 1] + 2) >> 2;
2225
- }
2226
-
2227
- for (j = offset + 1, n = len; n--; j += 2) {
2228
- x[j] += (x[j - 1] + x[j + 1]) >> 1;
2229
- }
2230
- };
2231
-
2232
- return ReversibleTransform;
2233
- })();
2234
-
2235
- return JpxImage;
2236
- })();
2237
-
1
+ /* -*- Mode: Java; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
2
+ /* vim: set shiftwidth=2 tabstop=2 autoindent cindent expandtab: */
3
+ /* Copyright 2012 Mozilla Foundation
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
+ /* globals ArithmeticDecoder, globalScope, log2, readUint16, readUint32,
18
+ info, warn */
19
+
20
+ 'use strict';
21
+
22
+ var JpxImage = (function JpxImageClosure() {
23
+ // Table E.1
24
+ var SubbandsGainLog2 = {
25
+ 'LL': 0,
26
+ 'LH': 1,
27
+ 'HL': 1,
28
+ 'HH': 2
29
+ };
30
+ function JpxImage() {
31
+ this.failOnCorruptedImage = true;
32
+ }
33
+ JpxImage.prototype = {
34
+ parse: function JpxImage_parse(data) {
35
+
36
+ var head = readUint16(data, 0);
37
+ // No box header, immediate start of codestream (SOC)
38
+ if (head === 0xFF4F) {
39
+ this.parseCodestream(data, 0, data.length);
40
+ return;
41
+ }
42
+
43
+ var position = 0, length = data.length;
44
+ while (position < length) {
45
+ var headerSize = 8;
46
+ var lbox = readUint32(data, position);
47
+ var tbox = readUint32(data, position + 4);
48
+ position += headerSize;
49
+ if (lbox === 1) {
50
+ // XLBox: read UInt64 according to spec.
51
+ // JavaScript's int precision of 53 bit should be sufficient here.
52
+ lbox = readUint32(data, position) * 4294967296 +
53
+ readUint32(data, position + 4);
54
+ position += 8;
55
+ headerSize += 8;
56
+ }
57
+ if (lbox === 0) {
58
+ lbox = length - position + headerSize;
59
+ }
60
+ if (lbox < headerSize) {
61
+ throw new Error('JPX Error: Invalid box field size');
62
+ }
63
+ var dataLength = lbox - headerSize;
64
+ var jumpDataLength = true;
65
+ switch (tbox) {
66
+ case 0x6A703268: // 'jp2h'
67
+ jumpDataLength = false; // parsing child boxes
68
+ break;
69
+ case 0x636F6C72: // 'colr'
70
+ // Colorspaces are not used, the CS from the PDF is used.
71
+ var method = data[position];
72
+ var precedence = data[position + 1];
73
+ var approximation = data[position + 2];
74
+ if (method === 1) {
75
+ // enumerated colorspace
76
+ var colorspace = readUint32(data, position + 3);
77
+ switch (colorspace) {
78
+ case 16: // this indicates a sRGB colorspace
79
+ case 17: // this indicates a grayscale colorspace
80
+ case 18: // this indicates a YUV colorspace
81
+ break;
82
+ default:
83
+ warn('Unknown colorspace ' + colorspace);
84
+ break;
85
+ }
86
+ } else if (method === 2) {
87
+ info('ICC profile not supported');
88
+ }
89
+ break;
90
+ case 0x6A703263: // 'jp2c'
91
+ this.parseCodestream(data, position, position + dataLength);
92
+ break;
93
+ case 0x6A502020: // 'jP\024\024'
94
+ if (0x0d0a870a !== readUint32(data, position)) {
95
+ warn('Invalid JP2 signature');
96
+ }
97
+ break;
98
+ // The following header types are valid but currently not used:
99
+ case 0x6A501A1A: // 'jP\032\032'
100
+ case 0x66747970: // 'ftyp'
101
+ case 0x72726571: // 'rreq'
102
+ case 0x72657320: // 'res '
103
+ case 0x69686472: // 'ihdr'
104
+ break;
105
+ default:
106
+ var headerType = String.fromCharCode((tbox >> 24) & 0xFF,
107
+ (tbox >> 16) & 0xFF,
108
+ (tbox >> 8) & 0xFF,
109
+ tbox & 0xFF);
110
+ warn('Unsupported header type ' + tbox + ' (' + headerType + ')');
111
+ break;
112
+ }
113
+ if (jumpDataLength) {
114
+ position += dataLength;
115
+ }
116
+ }
117
+ },
118
+ parseImageProperties: function JpxImage_parseImageProperties(stream) {
119
+ var newByte = stream.getByte();
120
+ while (newByte >= 0) {
121
+ var oldByte = newByte;
122
+ newByte = stream.getByte();
123
+ var code = (oldByte << 8) | newByte;
124
+ // Image and tile size (SIZ)
125
+ if (code === 0xFF51) {
126
+ stream.skip(4);
127
+ var Xsiz = stream.getInt32() >>> 0; // Byte 4
128
+ var Ysiz = stream.getInt32() >>> 0; // Byte 8
129
+ var XOsiz = stream.getInt32() >>> 0; // Byte 12
130
+ var YOsiz = stream.getInt32() >>> 0; // Byte 16
131
+ stream.skip(16);
132
+ var Csiz = stream.getUint16(); // Byte 36
133
+ this.width = Xsiz - XOsiz;
134
+ this.height = Ysiz - YOsiz;
135
+ this.componentsCount = Csiz;
136
+ // Results are always returned as Uint8Arrays
137
+ this.bitsPerComponent = 8;
138
+ return;
139
+ }
140
+ }
141
+ throw new Error('JPX Error: No size marker found in JPX stream');
142
+ },
143
+ parseCodestream: function JpxImage_parseCodestream(data, start, end) {
144
+ var context = {};
145
+ try {
146
+ var doNotRecover = false;
147
+ var position = start;
148
+ while (position + 1 < end) {
149
+ var code = readUint16(data, position);
150
+ position += 2;
151
+
152
+ var length = 0, j, sqcd, spqcds, spqcdSize, scalarExpounded, tile;
153
+ switch (code) {
154
+ case 0xFF4F: // Start of codestream (SOC)
155
+ context.mainHeader = true;
156
+ break;
157
+ case 0xFFD9: // End of codestream (EOC)
158
+ break;
159
+ case 0xFF51: // Image and tile size (SIZ)
160
+ length = readUint16(data, position);
161
+ var siz = {};
162
+ siz.Xsiz = readUint32(data, position + 4);
163
+ siz.Ysiz = readUint32(data, position + 8);
164
+ siz.XOsiz = readUint32(data, position + 12);
165
+ siz.YOsiz = readUint32(data, position + 16);
166
+ siz.XTsiz = readUint32(data, position + 20);
167
+ siz.YTsiz = readUint32(data, position + 24);
168
+ siz.XTOsiz = readUint32(data, position + 28);
169
+ siz.YTOsiz = readUint32(data, position + 32);
170
+ var componentsCount = readUint16(data, position + 36);
171
+ siz.Csiz = componentsCount;
172
+ var components = [];
173
+ j = position + 38;
174
+ for (var i = 0; i < componentsCount; i++) {
175
+ var component = {
176
+ precision: (data[j] & 0x7F) + 1,
177
+ isSigned: !!(data[j] & 0x80),
178
+ XRsiz: data[j + 1],
179
+ YRsiz: data[j + 1]
180
+ };
181
+ calculateComponentDimensions(component, siz);
182
+ components.push(component);
183
+ }
184
+ context.SIZ = siz;
185
+ context.components = components;
186
+ calculateTileGrids(context, components);
187
+ context.QCC = [];
188
+ context.COC = [];
189
+ break;
190
+ case 0xFF5C: // Quantization default (QCD)
191
+ length = readUint16(data, position);
192
+ var qcd = {};
193
+ j = position + 2;
194
+ sqcd = data[j++];
195
+ switch (sqcd & 0x1F) {
196
+ case 0:
197
+ spqcdSize = 8;
198
+ scalarExpounded = true;
199
+ break;
200
+ case 1:
201
+ spqcdSize = 16;
202
+ scalarExpounded = false;
203
+ break;
204
+ case 2:
205
+ spqcdSize = 16;
206
+ scalarExpounded = true;
207
+ break;
208
+ default:
209
+ throw new Error('JPX Error: Invalid SQcd value ' + sqcd);
210
+ }
211
+ qcd.noQuantization = (spqcdSize === 8);
212
+ qcd.scalarExpounded = scalarExpounded;
213
+ qcd.guardBits = sqcd >> 5;
214
+ spqcds = [];
215
+ while (j < length + position) {
216
+ var spqcd = {};
217
+ if (spqcdSize === 8) {
218
+ spqcd.epsilon = data[j++] >> 3;
219
+ spqcd.mu = 0;
220
+ } else {
221
+ spqcd.epsilon = data[j] >> 3;
222
+ spqcd.mu = ((data[j] & 0x7) << 8) | data[j + 1];
223
+ j += 2;
224
+ }
225
+ spqcds.push(spqcd);
226
+ }
227
+ qcd.SPqcds = spqcds;
228
+ if (context.mainHeader) {
229
+ context.QCD = qcd;
230
+ } else {
231
+ context.currentTile.QCD = qcd;
232
+ context.currentTile.QCC = [];
233
+ }
234
+ break;
235
+ case 0xFF5D: // Quantization component (QCC)
236
+ length = readUint16(data, position);
237
+ var qcc = {};
238
+ j = position + 2;
239
+ var cqcc;
240
+ if (context.SIZ.Csiz < 257) {
241
+ cqcc = data[j++];
242
+ } else {
243
+ cqcc = readUint16(data, j);
244
+ j += 2;
245
+ }
246
+ sqcd = data[j++];
247
+ switch (sqcd & 0x1F) {
248
+ case 0:
249
+ spqcdSize = 8;
250
+ scalarExpounded = true;
251
+ break;
252
+ case 1:
253
+ spqcdSize = 16;
254
+ scalarExpounded = false;
255
+ break;
256
+ case 2:
257
+ spqcdSize = 16;
258
+ scalarExpounded = true;
259
+ break;
260
+ default:
261
+ throw new Error('JPX Error: Invalid SQcd value ' + sqcd);
262
+ }
263
+ qcc.noQuantization = (spqcdSize === 8);
264
+ qcc.scalarExpounded = scalarExpounded;
265
+ qcc.guardBits = sqcd >> 5;
266
+ spqcds = [];
267
+ while (j < (length + position)) {
268
+ spqcd = {};
269
+ if (spqcdSize === 8) {
270
+ spqcd.epsilon = data[j++] >> 3;
271
+ spqcd.mu = 0;
272
+ } else {
273
+ spqcd.epsilon = data[j] >> 3;
274
+ spqcd.mu = ((data[j] & 0x7) << 8) | data[j + 1];
275
+ j += 2;
276
+ }
277
+ spqcds.push(spqcd);
278
+ }
279
+ qcc.SPqcds = spqcds;
280
+ if (context.mainHeader) {
281
+ context.QCC[cqcc] = qcc;
282
+ } else {
283
+ context.currentTile.QCC[cqcc] = qcc;
284
+ }
285
+ break;
286
+ case 0xFF52: // Coding style default (COD)
287
+ length = readUint16(data, position);
288
+ var cod = {};
289
+ j = position + 2;
290
+ var scod = data[j++];
291
+ cod.entropyCoderWithCustomPrecincts = !!(scod & 1);
292
+ cod.sopMarkerUsed = !!(scod & 2);
293
+ cod.ephMarkerUsed = !!(scod & 4);
294
+ cod.progressionOrder = data[j++];
295
+ cod.layersCount = readUint16(data, j);
296
+ j += 2;
297
+ cod.multipleComponentTransform = data[j++];
298
+
299
+ cod.decompositionLevelsCount = data[j++];
300
+ cod.xcb = (data[j++] & 0xF) + 2;
301
+ cod.ycb = (data[j++] & 0xF) + 2;
302
+ var blockStyle = data[j++];
303
+ cod.selectiveArithmeticCodingBypass = !!(blockStyle & 1);
304
+ cod.resetContextProbabilities = !!(blockStyle & 2);
305
+ cod.terminationOnEachCodingPass = !!(blockStyle & 4);
306
+ cod.verticalyStripe = !!(blockStyle & 8);
307
+ cod.predictableTermination = !!(blockStyle & 16);
308
+ cod.segmentationSymbolUsed = !!(blockStyle & 32);
309
+ cod.reversibleTransformation = data[j++];
310
+ if (cod.entropyCoderWithCustomPrecincts) {
311
+ var precinctsSizes = [];
312
+ while (j < length + position) {
313
+ var precinctsSize = data[j++];
314
+ precinctsSizes.push({
315
+ PPx: precinctsSize & 0xF,
316
+ PPy: precinctsSize >> 4
317
+ });
318
+ }
319
+ cod.precinctsSizes = precinctsSizes;
320
+ }
321
+ var unsupported = [];
322
+ if (cod.selectiveArithmeticCodingBypass) {
323
+ unsupported.push('selectiveArithmeticCodingBypass');
324
+ }
325
+ if (cod.resetContextProbabilities) {
326
+ unsupported.push('resetContextProbabilities');
327
+ }
328
+ if (cod.terminationOnEachCodingPass) {
329
+ unsupported.push('terminationOnEachCodingPass');
330
+ }
331
+ if (cod.verticalyStripe) {
332
+ unsupported.push('verticalyStripe');
333
+ }
334
+ if (cod.predictableTermination) {
335
+ unsupported.push('predictableTermination');
336
+ }
337
+ if (unsupported.length > 0) {
338
+ doNotRecover = true;
339
+ throw new Error('JPX Error: Unsupported COD options (' +
340
+ unsupported.join(', ') + ')');
341
+ }
342
+ if (context.mainHeader) {
343
+ context.COD = cod;
344
+ } else {
345
+ context.currentTile.COD = cod;
346
+ context.currentTile.COC = [];
347
+ }
348
+ break;
349
+ case 0xFF90: // Start of tile-part (SOT)
350
+ length = readUint16(data, position);
351
+ tile = {};
352
+ tile.index = readUint16(data, position + 2);
353
+ tile.length = readUint32(data, position + 4);
354
+ tile.dataEnd = tile.length + position - 2;
355
+ tile.partIndex = data[position + 8];
356
+ tile.partsCount = data[position + 9];
357
+
358
+ context.mainHeader = false;
359
+ if (tile.partIndex === 0) {
360
+ // reset component specific settings
361
+ tile.COD = context.COD;
362
+ tile.COC = context.COC.slice(0); // clone of the global COC
363
+ tile.QCD = context.QCD;
364
+ tile.QCC = context.QCC.slice(0); // clone of the global COC
365
+ }
366
+ context.currentTile = tile;
367
+ break;
368
+ case 0xFF93: // Start of data (SOD)
369
+ tile = context.currentTile;
370
+ if (tile.partIndex === 0) {
371
+ initializeTile(context, tile.index);
372
+ buildPackets(context);
373
+ }
374
+
375
+ // moving to the end of the data
376
+ length = tile.dataEnd - position;
377
+ parseTilePackets(context, data, position, length);
378
+ break;
379
+ case 0xFF55: // Tile-part lengths, main header (TLM)
380
+ case 0xFF57: // Packet length, main header (PLM)
381
+ case 0xFF58: // Packet length, tile-part header (PLT)
382
+ case 0xFF64: // Comment (COM)
383
+ case 0xFF53: // Coding style component (COC)
384
+ length = readUint16(data, position);
385
+ // skipping content
386
+ break;
387
+ default:
388
+ throw new Error('JPX Error: Unknown codestream code: ' +
389
+ code.toString(16));
390
+ }
391
+ position += length;
392
+ }
393
+ } catch (e) {
394
+ if (doNotRecover || this.failOnCorruptedImage) {
395
+ throw e;
396
+ } else {
397
+ warn('Trying to recover from ' + e.message);
398
+ }
399
+ }
400
+ this.tiles = transformComponents(context);
401
+ this.width = context.SIZ.Xsiz - context.SIZ.XOsiz;
402
+ this.height = context.SIZ.Ysiz - context.SIZ.YOsiz;
403
+ this.componentsCount = context.SIZ.Csiz;
404
+ }
405
+ };
406
+ function calculateComponentDimensions(component, siz) {
407
+ // Section B.2 Component mapping
408
+ component.x0 = Math.ceil(siz.XOsiz / component.XRsiz);
409
+ component.x1 = Math.ceil(siz.Xsiz / component.XRsiz);
410
+ component.y0 = Math.ceil(siz.YOsiz / component.YRsiz);
411
+ component.y1 = Math.ceil(siz.Ysiz / component.YRsiz);
412
+ component.width = component.x1 - component.x0;
413
+ component.height = component.y1 - component.y0;
414
+ }
415
+ function calculateTileGrids(context, components) {
416
+ var siz = context.SIZ;
417
+ // Section B.3 Division into tile and tile-components
418
+ var tile, tiles = [];
419
+ var numXtiles = Math.ceil((siz.Xsiz - siz.XTOsiz) / siz.XTsiz);
420
+ var numYtiles = Math.ceil((siz.Ysiz - siz.YTOsiz) / siz.YTsiz);
421
+ for (var q = 0; q < numYtiles; q++) {
422
+ for (var p = 0; p < numXtiles; p++) {
423
+ tile = {};
424
+ tile.tx0 = Math.max(siz.XTOsiz + p * siz.XTsiz, siz.XOsiz);
425
+ tile.ty0 = Math.max(siz.YTOsiz + q * siz.YTsiz, siz.YOsiz);
426
+ tile.tx1 = Math.min(siz.XTOsiz + (p + 1) * siz.XTsiz, siz.Xsiz);
427
+ tile.ty1 = Math.min(siz.YTOsiz + (q + 1) * siz.YTsiz, siz.Ysiz);
428
+ tile.width = tile.tx1 - tile.tx0;
429
+ tile.height = tile.ty1 - tile.ty0;
430
+ tile.components = [];
431
+ tiles.push(tile);
432
+ }
433
+ }
434
+ context.tiles = tiles;
435
+
436
+ var componentsCount = siz.Csiz;
437
+ for (var i = 0, ii = componentsCount; i < ii; i++) {
438
+ var component = components[i];
439
+ for (var j = 0, jj = tiles.length; j < jj; j++) {
440
+ var tileComponent = {};
441
+ tile = tiles[j];
442
+ tileComponent.tcx0 = Math.ceil(tile.tx0 / component.XRsiz);
443
+ tileComponent.tcy0 = Math.ceil(tile.ty0 / component.YRsiz);
444
+ tileComponent.tcx1 = Math.ceil(tile.tx1 / component.XRsiz);
445
+ tileComponent.tcy1 = Math.ceil(tile.ty1 / component.YRsiz);
446
+ tileComponent.width = tileComponent.tcx1 - tileComponent.tcx0;
447
+ tileComponent.height = tileComponent.tcy1 - tileComponent.tcy0;
448
+ tile.components[i] = tileComponent;
449
+ }
450
+ }
451
+ }
452
+ function getBlocksDimensions(context, component, r) {
453
+ var codOrCoc = component.codingStyleParameters;
454
+ var result = {};
455
+ if (!codOrCoc.entropyCoderWithCustomPrecincts) {
456
+ result.PPx = 15;
457
+ result.PPy = 15;
458
+ } else {
459
+ result.PPx = codOrCoc.precinctsSizes[r].PPx;
460
+ result.PPy = codOrCoc.precinctsSizes[r].PPy;
461
+ }
462
+ // calculate codeblock size as described in section B.7
463
+ result.xcb_ = (r > 0 ? Math.min(codOrCoc.xcb, result.PPx - 1) :
464
+ Math.min(codOrCoc.xcb, result.PPx));
465
+ result.ycb_ = (r > 0 ? Math.min(codOrCoc.ycb, result.PPy - 1) :
466
+ Math.min(codOrCoc.ycb, result.PPy));
467
+ return result;
468
+ }
469
+ function buildPrecincts(context, resolution, dimensions) {
470
+ // Section B.6 Division resolution to precincts
471
+ var precinctWidth = 1 << dimensions.PPx;
472
+ var precinctHeight = 1 << dimensions.PPy;
473
+ // Jasper introduces codeblock groups for mapping each subband codeblocks
474
+ // to precincts. Precinct partition divides a resolution according to width
475
+ // and height parameters. The subband that belongs to the resolution level
476
+ // has a different size than the level, unless it is the zero resolution.
477
+
478
+ // From Jasper documentation: jpeg2000.pdf, section K: Tier-2 coding:
479
+ // The precinct partitioning for a particular subband is derived from a
480
+ // partitioning of its parent LL band (i.e., the LL band at the next higher
481
+ // resolution level)... The LL band associated with each resolution level is
482
+ // divided into precincts... Each of the resulting precinct regions is then
483
+ // mapped into its child subbands (if any) at the next lower resolution
484
+ // level. This is accomplished by using the coordinate transformation
485
+ // (u, v) = (ceil(x/2), ceil(y/2)) where (x, y) and (u, v) are the
486
+ // coordinates of a point in the LL band and child subband, respectively.
487
+ var isZeroRes = resolution.resLevel === 0;
488
+ var precinctWidthInSubband = 1 << (dimensions.PPx + (isZeroRes ? 0 : -1));
489
+ var precinctHeightInSubband = 1 << (dimensions.PPy + (isZeroRes ? 0 : -1));
490
+ var numprecinctswide = (resolution.trx1 > resolution.trx0 ?
491
+ Math.ceil(resolution.trx1 / precinctWidth) -
492
+ Math.floor(resolution.trx0 / precinctWidth) : 0);
493
+ var numprecinctshigh = (resolution.try1 > resolution.try0 ?
494
+ Math.ceil(resolution.try1 / precinctHeight) -
495
+ Math.floor(resolution.try0 / precinctHeight) : 0);
496
+ var numprecincts = numprecinctswide * numprecinctshigh;
497
+
498
+ resolution.precinctParameters = {
499
+ precinctWidth: precinctWidth,
500
+ precinctHeight: precinctHeight,
501
+ numprecinctswide: numprecinctswide,
502
+ numprecinctshigh: numprecinctshigh,
503
+ numprecincts: numprecincts,
504
+ precinctWidthInSubband: precinctWidthInSubband,
505
+ precinctHeightInSubband: precinctHeightInSubband
506
+ };
507
+ }
508
+ function buildCodeblocks(context, subband, dimensions) {
509
+ // Section B.7 Division sub-band into code-blocks
510
+ var xcb_ = dimensions.xcb_;
511
+ var ycb_ = dimensions.ycb_;
512
+ var codeblockWidth = 1 << xcb_;
513
+ var codeblockHeight = 1 << ycb_;
514
+ var cbx0 = subband.tbx0 >> xcb_;
515
+ var cby0 = subband.tby0 >> ycb_;
516
+ var cbx1 = (subband.tbx1 + codeblockWidth - 1) >> xcb_;
517
+ var cby1 = (subband.tby1 + codeblockHeight - 1) >> ycb_;
518
+ var precinctParameters = subband.resolution.precinctParameters;
519
+ var codeblocks = [];
520
+ var precincts = [];
521
+ var i, j, codeblock, precinctNumber;
522
+ for (j = cby0; j < cby1; j++) {
523
+ for (i = cbx0; i < cbx1; i++) {
524
+ codeblock = {
525
+ cbx: i,
526
+ cby: j,
527
+ tbx0: codeblockWidth * i,
528
+ tby0: codeblockHeight * j,
529
+ tbx1: codeblockWidth * (i + 1),
530
+ tby1: codeblockHeight * (j + 1)
531
+ };
532
+
533
+ codeblock.tbx0_ = Math.max(subband.tbx0, codeblock.tbx0);
534
+ codeblock.tby0_ = Math.max(subband.tby0, codeblock.tby0);
535
+ codeblock.tbx1_ = Math.min(subband.tbx1, codeblock.tbx1);
536
+ codeblock.tby1_ = Math.min(subband.tby1, codeblock.tby1);
537
+
538
+ // Calculate precinct number for this codeblock, codeblock position
539
+ // should be relative to its subband, use actual dimension and position
540
+ // See comment about codeblock group width and height
541
+ var pi = Math.floor((codeblock.tbx0_ - subband.tbx0) /
542
+ precinctParameters.precinctWidthInSubband);
543
+ var pj = Math.floor((codeblock.tby0_ - subband.tby0) /
544
+ precinctParameters.precinctHeightInSubband);
545
+ precinctNumber = pi + (pj * precinctParameters.numprecinctswide);
546
+
547
+ codeblock.precinctNumber = precinctNumber;
548
+ codeblock.subbandType = subband.type;
549
+ codeblock.Lblock = 3;
550
+
551
+ if (codeblock.tbx1_ <= codeblock.tbx0_ ||
552
+ codeblock.tby1_ <= codeblock.tby0_) {
553
+ continue;
554
+ }
555
+ codeblocks.push(codeblock);
556
+ // building precinct for the sub-band
557
+ var precinct = precincts[precinctNumber];
558
+ if (precinct !== undefined) {
559
+ if (i < precinct.cbxMin) {
560
+ precinct.cbxMin = i;
561
+ } else if (i > precinct.cbxMax) {
562
+ precinct.cbxMax = i;
563
+ }
564
+ if (j < precinct.cbyMin) {
565
+ precinct.cbxMin = j;
566
+ } else if (j > precinct.cbyMax) {
567
+ precinct.cbyMax = j;
568
+ }
569
+ } else {
570
+ precincts[precinctNumber] = precinct = {
571
+ cbxMin: i,
572
+ cbyMin: j,
573
+ cbxMax: i,
574
+ cbyMax: j
575
+ };
576
+ }
577
+ codeblock.precinct = precinct;
578
+ }
579
+ }
580
+ subband.codeblockParameters = {
581
+ codeblockWidth: xcb_,
582
+ codeblockHeight: ycb_,
583
+ numcodeblockwide: cbx1 - cbx0 + 1,
584
+ numcodeblockhigh: cby1 - cby0 + 1
585
+ };
586
+ subband.codeblocks = codeblocks;
587
+ subband.precincts = precincts;
588
+ }
589
+ function createPacket(resolution, precinctNumber, layerNumber) {
590
+ var precinctCodeblocks = [];
591
+ // Section B.10.8 Order of info in packet
592
+ var subbands = resolution.subbands;
593
+ // sub-bands already ordered in 'LL', 'HL', 'LH', and 'HH' sequence
594
+ for (var i = 0, ii = subbands.length; i < ii; i++) {
595
+ var subband = subbands[i];
596
+ var codeblocks = subband.codeblocks;
597
+ for (var j = 0, jj = codeblocks.length; j < jj; j++) {
598
+ var codeblock = codeblocks[j];
599
+ if (codeblock.precinctNumber !== precinctNumber) {
600
+ continue;
601
+ }
602
+ precinctCodeblocks.push(codeblock);
603
+ }
604
+ }
605
+ return {
606
+ layerNumber: layerNumber,
607
+ codeblocks: precinctCodeblocks
608
+ };
609
+ }
610
+ function LayerResolutionComponentPositionIterator(context) {
611
+ var siz = context.SIZ;
612
+ var tileIndex = context.currentTile.index;
613
+ var tile = context.tiles[tileIndex];
614
+ var layersCount = tile.codingStyleDefaultParameters.layersCount;
615
+ var componentsCount = siz.Csiz;
616
+ var maxDecompositionLevelsCount = 0;
617
+ for (var q = 0; q < componentsCount; q++) {
618
+ maxDecompositionLevelsCount = Math.max(maxDecompositionLevelsCount,
619
+ tile.components[q].codingStyleParameters.decompositionLevelsCount);
620
+ }
621
+
622
+ var l = 0, r = 0, i = 0, k = 0;
623
+
624
+ this.nextPacket = function JpxImage_nextPacket() {
625
+ // Section B.12.1.1 Layer-resolution-component-position
626
+ for (; l < layersCount; l++) {
627
+ for (; r <= maxDecompositionLevelsCount; r++) {
628
+ for (; i < componentsCount; i++) {
629
+ var component = tile.components[i];
630
+ if (r > component.codingStyleParameters.decompositionLevelsCount) {
631
+ continue;
632
+ }
633
+
634
+ var resolution = component.resolutions[r];
635
+ var numprecincts = resolution.precinctParameters.numprecincts;
636
+ for (; k < numprecincts;) {
637
+ var packet = createPacket(resolution, k, l);
638
+ k++;
639
+ return packet;
640
+ }
641
+ k = 0;
642
+ }
643
+ i = 0;
644
+ }
645
+ r = 0;
646
+ }
647
+ };
648
+ }
649
+ function ResolutionLayerComponentPositionIterator(context) {
650
+ var siz = context.SIZ;
651
+ var tileIndex = context.currentTile.index;
652
+ var tile = context.tiles[tileIndex];
653
+ var layersCount = tile.codingStyleDefaultParameters.layersCount;
654
+ var componentsCount = siz.Csiz;
655
+ var maxDecompositionLevelsCount = 0;
656
+ for (var q = 0; q < componentsCount; q++) {
657
+ maxDecompositionLevelsCount = Math.max(maxDecompositionLevelsCount,
658
+ tile.components[q].codingStyleParameters.decompositionLevelsCount);
659
+ }
660
+
661
+ var r = 0, l = 0, i = 0, k = 0;
662
+
663
+ this.nextPacket = function JpxImage_nextPacket() {
664
+ // Section B.12.1.2 Resolution-layer-component-position
665
+ for (; r <= maxDecompositionLevelsCount; r++) {
666
+ for (; l < layersCount; l++) {
667
+ for (; i < componentsCount; i++) {
668
+ var component = tile.components[i];
669
+ if (r > component.codingStyleParameters.decompositionLevelsCount) {
670
+ continue;
671
+ }
672
+
673
+ var resolution = component.resolutions[r];
674
+ var numprecincts = resolution.precinctParameters.numprecincts;
675
+ for (; k < numprecincts;) {
676
+ var packet = createPacket(resolution, k, l);
677
+ k++;
678
+ return packet;
679
+ }
680
+ k = 0;
681
+ }
682
+ i = 0;
683
+ }
684
+ l = 0;
685
+ }
686
+ };
687
+ }
688
+ function ResolutionPositionComponentLayerIterator(context) {
689
+ var siz = context.SIZ;
690
+ var tileIndex = context.currentTile.index;
691
+ var tile = context.tiles[tileIndex];
692
+ var layersCount = tile.codingStyleDefaultParameters.layersCount;
693
+ var componentsCount = siz.Csiz;
694
+ var l, r, c, p;
695
+ var maxDecompositionLevelsCount = 0;
696
+ for (c = 0; c < componentsCount; c++) {
697
+ var component = tile.components[c];
698
+ maxDecompositionLevelsCount = Math.max(maxDecompositionLevelsCount,
699
+ component.codingStyleParameters.decompositionLevelsCount);
700
+ }
701
+ var maxNumPrecinctsInLevel = new Int32Array(
702
+ maxDecompositionLevelsCount + 1);
703
+ for (r = 0; r <= maxDecompositionLevelsCount; ++r) {
704
+ var maxNumPrecincts = 0;
705
+ for (c = 0; c < componentsCount; ++c) {
706
+ var resolutions = tile.components[c].resolutions;
707
+ if (r < resolutions.length) {
708
+ maxNumPrecincts = Math.max(maxNumPrecincts,
709
+ resolutions[r].precinctParameters.numprecincts);
710
+ }
711
+ }
712
+ maxNumPrecinctsInLevel[r] = maxNumPrecincts;
713
+ }
714
+ l = 0;
715
+ r = 0;
716
+ c = 0;
717
+ p = 0;
718
+
719
+ this.nextPacket = function JpxImage_nextPacket() {
720
+ // Section B.12.1.3 Resolution-position-component-layer
721
+ for (; r <= maxDecompositionLevelsCount; r++) {
722
+ for (; p < maxNumPrecinctsInLevel[r]; p++) {
723
+ for (; c < componentsCount; c++) {
724
+ var component = tile.components[c];
725
+ if (r > component.codingStyleParameters.decompositionLevelsCount) {
726
+ continue;
727
+ }
728
+ var resolution = component.resolutions[r];
729
+ var numprecincts = resolution.precinctParameters.numprecincts;
730
+ if (p >= numprecincts) {
731
+ continue;
732
+ }
733
+ for (; l < layersCount;) {
734
+ var packet = createPacket(resolution, p, l);
735
+ l++;
736
+ return packet;
737
+ }
738
+ l = 0;
739
+ }
740
+ c = 0;
741
+ }
742
+ p = 0;
743
+ }
744
+ };
745
+ }
746
+ function PositionComponentResolutionLayerIterator(context) {
747
+ var siz = context.SIZ;
748
+ var tileIndex = context.currentTile.index;
749
+ var tile = context.tiles[tileIndex];
750
+ var layersCount = tile.codingStyleDefaultParameters.layersCount;
751
+ var componentsCount = siz.Csiz;
752
+ var precinctsSizes = getPrecinctSizesInImageScale(tile);
753
+ var precinctsIterationSizes = precinctsSizes;
754
+ var l = 0, r = 0, c = 0, px = 0, py = 0;
755
+
756
+ this.nextPacket = function JpxImage_nextPacket() {
757
+ // Section B.12.1.4 Position-component-resolution-layer
758
+ for (; py < precinctsIterationSizes.maxNumHigh; py++) {
759
+ for (; px < precinctsIterationSizes.maxNumWide; px++) {
760
+ for (; c < componentsCount; c++) {
761
+ var component = tile.components[c];
762
+ var decompositionLevelsCount =
763
+ component.codingStyleParameters.decompositionLevelsCount;
764
+ for (; r <= decompositionLevelsCount; r++) {
765
+ var resolution = component.resolutions[r];
766
+ var sizeInImageScale =
767
+ precinctsSizes.components[c].resolutions[r];
768
+ var k = getPrecinctIndexIfExist(
769
+ px,
770
+ py,
771
+ sizeInImageScale,
772
+ precinctsIterationSizes,
773
+ resolution);
774
+ if (k === null) {
775
+ continue;
776
+ }
777
+ for (; l < layersCount;) {
778
+ var packet = createPacket(resolution, k, l);
779
+ l++;
780
+ return packet;
781
+ }
782
+ l = 0;
783
+ }
784
+ r = 0;
785
+ }
786
+ c = 0;
787
+ }
788
+ px = 0;
789
+ }
790
+ };
791
+ }
792
+ function ComponentPositionResolutionLayerIterator(context) {
793
+ var siz = context.SIZ;
794
+ var tileIndex = context.currentTile.index;
795
+ var tile = context.tiles[tileIndex];
796
+ var layersCount = tile.codingStyleDefaultParameters.layersCount;
797
+ var componentsCount = siz.Csiz;
798
+ var precinctsSizes = getPrecinctSizesInImageScale(tile);
799
+ var l = 0, r = 0, c = 0, px = 0, py = 0;
800
+
801
+ this.nextPacket = function JpxImage_nextPacket() {
802
+ // Section B.12.1.5 Component-position-resolution-layer
803
+ for (; c < componentsCount; ++c) {
804
+ var component = tile.components[c];
805
+ var precinctsIterationSizes = precinctsSizes.components[c];
806
+ var decompositionLevelsCount =
807
+ component.codingStyleParameters.decompositionLevelsCount;
808
+ for (; py < precinctsIterationSizes.maxNumHigh; py++) {
809
+ for (; px < precinctsIterationSizes.maxNumWide; px++) {
810
+ for (; r <= decompositionLevelsCount; r++) {
811
+ var resolution = component.resolutions[r];
812
+ var sizeInImageScale = precinctsIterationSizes.resolutions[r];
813
+ var k = getPrecinctIndexIfExist(
814
+ px,
815
+ py,
816
+ sizeInImageScale,
817
+ precinctsIterationSizes,
818
+ resolution);
819
+ if (k === null) {
820
+ continue;
821
+ }
822
+ for (; l < layersCount;) {
823
+ var packet = createPacket(resolution, k, l);
824
+ l++;
825
+ return packet;
826
+ }
827
+ l = 0;
828
+ }
829
+ r = 0;
830
+ }
831
+ px = 0;
832
+ }
833
+ py = 0;
834
+ }
835
+ };
836
+ }
837
+ function getPrecinctIndexIfExist(
838
+ pxIndex, pyIndex, sizeInImageScale, precinctIterationSizes, resolution) {
839
+ var posX = pxIndex * precinctIterationSizes.minWidth;
840
+ var posY = pyIndex * precinctIterationSizes.minHeight;
841
+ if (posX % sizeInImageScale.width !== 0 ||
842
+ posY % sizeInImageScale.height !== 0) {
843
+ return null;
844
+ }
845
+ var startPrecinctRowIndex =
846
+ (posY / sizeInImageScale.width) *
847
+ resolution.precinctParameters.numprecinctswide;
848
+ return (posX / sizeInImageScale.height) + startPrecinctRowIndex;
849
+ }
850
+ function getPrecinctSizesInImageScale(tile) {
851
+ var componentsCount = tile.components.length;
852
+ var minWidth = Number.MAX_VALUE;
853
+ var minHeight = Number.MAX_VALUE;
854
+ var maxNumWide = 0;
855
+ var maxNumHigh = 0;
856
+ var sizePerComponent = new Array(componentsCount);
857
+ for (var c = 0; c < componentsCount; c++) {
858
+ var component = tile.components[c];
859
+ var decompositionLevelsCount =
860
+ component.codingStyleParameters.decompositionLevelsCount;
861
+ var sizePerResolution = new Array(decompositionLevelsCount + 1);
862
+ var minWidthCurrentComponent = Number.MAX_VALUE;
863
+ var minHeightCurrentComponent = Number.MAX_VALUE;
864
+ var maxNumWideCurrentComponent = 0;
865
+ var maxNumHighCurrentComponent = 0;
866
+ var scale = 1;
867
+ for (var r = decompositionLevelsCount; r >= 0; --r) {
868
+ var resolution = component.resolutions[r];
869
+ var widthCurrentResolution =
870
+ scale * resolution.precinctParameters.precinctWidth;
871
+ var heightCurrentResolution =
872
+ scale * resolution.precinctParameters.precinctHeight;
873
+ minWidthCurrentComponent = Math.min(
874
+ minWidthCurrentComponent,
875
+ widthCurrentResolution);
876
+ minHeightCurrentComponent = Math.min(
877
+ minHeightCurrentComponent,
878
+ heightCurrentResolution);
879
+ maxNumWideCurrentComponent = Math.max(maxNumWideCurrentComponent,
880
+ resolution.precinctParameters.numprecinctswide);
881
+ maxNumHighCurrentComponent = Math.max(maxNumHighCurrentComponent,
882
+ resolution.precinctParameters.numprecinctshigh);
883
+ sizePerResolution[r] = {
884
+ width: widthCurrentResolution,
885
+ height: heightCurrentResolution
886
+ };
887
+ scale <<= 1;
888
+ }
889
+ minWidth = Math.min(minWidth, minWidthCurrentComponent);
890
+ minHeight = Math.min(minHeight, minHeightCurrentComponent);
891
+ maxNumWide = Math.max(maxNumWide, maxNumWideCurrentComponent);
892
+ maxNumHigh = Math.max(maxNumHigh, maxNumHighCurrentComponent);
893
+ sizePerComponent[c] = {
894
+ resolutions: sizePerResolution,
895
+ minWidth: minWidthCurrentComponent,
896
+ minHeight: minHeightCurrentComponent,
897
+ maxNumWide: maxNumWideCurrentComponent,
898
+ maxNumHigh: maxNumHighCurrentComponent
899
+ };
900
+ }
901
+ return {
902
+ components: sizePerComponent,
903
+ minWidth: minWidth,
904
+ minHeight: minHeight,
905
+ maxNumWide: maxNumWide,
906
+ maxNumHigh: maxNumHigh
907
+ };
908
+ }
909
+ function buildPackets(context) {
910
+ var siz = context.SIZ;
911
+ var tileIndex = context.currentTile.index;
912
+ var tile = context.tiles[tileIndex];
913
+ var componentsCount = siz.Csiz;
914
+ // Creating resolutions and sub-bands for each component
915
+ for (var c = 0; c < componentsCount; c++) {
916
+ var component = tile.components[c];
917
+ var decompositionLevelsCount =
918
+ component.codingStyleParameters.decompositionLevelsCount;
919
+ // Section B.5 Resolution levels and sub-bands
920
+ var resolutions = [];
921
+ var subbands = [];
922
+ for (var r = 0; r <= decompositionLevelsCount; r++) {
923
+ var blocksDimensions = getBlocksDimensions(context, component, r);
924
+ var resolution = {};
925
+ var scale = 1 << (decompositionLevelsCount - r);
926
+ resolution.trx0 = Math.ceil(component.tcx0 / scale);
927
+ resolution.try0 = Math.ceil(component.tcy0 / scale);
928
+ resolution.trx1 = Math.ceil(component.tcx1 / scale);
929
+ resolution.try1 = Math.ceil(component.tcy1 / scale);
930
+ resolution.resLevel = r;
931
+ buildPrecincts(context, resolution, blocksDimensions);
932
+ resolutions.push(resolution);
933
+
934
+ var subband;
935
+ if (r === 0) {
936
+ // one sub-band (LL) with last decomposition
937
+ subband = {};
938
+ subband.type = 'LL';
939
+ subband.tbx0 = Math.ceil(component.tcx0 / scale);
940
+ subband.tby0 = Math.ceil(component.tcy0 / scale);
941
+ subband.tbx1 = Math.ceil(component.tcx1 / scale);
942
+ subband.tby1 = Math.ceil(component.tcy1 / scale);
943
+ subband.resolution = resolution;
944
+ buildCodeblocks(context, subband, blocksDimensions);
945
+ subbands.push(subband);
946
+ resolution.subbands = [subband];
947
+ } else {
948
+ var bscale = 1 << (decompositionLevelsCount - r + 1);
949
+ var resolutionSubbands = [];
950
+ // three sub-bands (HL, LH and HH) with rest of decompositions
951
+ subband = {};
952
+ subband.type = 'HL';
953
+ subband.tbx0 = Math.ceil(component.tcx0 / bscale - 0.5);
954
+ subband.tby0 = Math.ceil(component.tcy0 / bscale);
955
+ subband.tbx1 = Math.ceil(component.tcx1 / bscale - 0.5);
956
+ subband.tby1 = Math.ceil(component.tcy1 / bscale);
957
+ subband.resolution = resolution;
958
+ buildCodeblocks(context, subband, blocksDimensions);
959
+ subbands.push(subband);
960
+ resolutionSubbands.push(subband);
961
+
962
+ subband = {};
963
+ subband.type = 'LH';
964
+ subband.tbx0 = Math.ceil(component.tcx0 / bscale);
965
+ subband.tby0 = Math.ceil(component.tcy0 / bscale - 0.5);
966
+ subband.tbx1 = Math.ceil(component.tcx1 / bscale);
967
+ subband.tby1 = Math.ceil(component.tcy1 / bscale - 0.5);
968
+ subband.resolution = resolution;
969
+ buildCodeblocks(context, subband, blocksDimensions);
970
+ subbands.push(subband);
971
+ resolutionSubbands.push(subband);
972
+
973
+ subband = {};
974
+ subband.type = 'HH';
975
+ subband.tbx0 = Math.ceil(component.tcx0 / bscale - 0.5);
976
+ subband.tby0 = Math.ceil(component.tcy0 / bscale - 0.5);
977
+ subband.tbx1 = Math.ceil(component.tcx1 / bscale - 0.5);
978
+ subband.tby1 = Math.ceil(component.tcy1 / bscale - 0.5);
979
+ subband.resolution = resolution;
980
+ buildCodeblocks(context, subband, blocksDimensions);
981
+ subbands.push(subband);
982
+ resolutionSubbands.push(subband);
983
+
984
+ resolution.subbands = resolutionSubbands;
985
+ }
986
+ }
987
+ component.resolutions = resolutions;
988
+ component.subbands = subbands;
989
+ }
990
+ // Generate the packets sequence
991
+ var progressionOrder = tile.codingStyleDefaultParameters.progressionOrder;
992
+ switch (progressionOrder) {
993
+ case 0:
994
+ tile.packetsIterator =
995
+ new LayerResolutionComponentPositionIterator(context);
996
+ break;
997
+ case 1:
998
+ tile.packetsIterator =
999
+ new ResolutionLayerComponentPositionIterator(context);
1000
+ break;
1001
+ case 2:
1002
+ tile.packetsIterator =
1003
+ new ResolutionPositionComponentLayerIterator(context);
1004
+ break;
1005
+ case 3:
1006
+ tile.packetsIterator =
1007
+ new PositionComponentResolutionLayerIterator(context);
1008
+ break;
1009
+ case 4:
1010
+ tile.packetsIterator =
1011
+ new ComponentPositionResolutionLayerIterator(context);
1012
+ break;
1013
+ default:
1014
+ throw new Error('JPX Error: Unsupported progression order ' +
1015
+ progressionOrder);
1016
+ }
1017
+ }
1018
+ function parseTilePackets(context, data, offset, dataLength) {
1019
+ var position = 0;
1020
+ var buffer, bufferSize = 0, skipNextBit = false;
1021
+ function readBits(count) {
1022
+ while (bufferSize < count) {
1023
+ var b = data[offset + position];
1024
+ position++;
1025
+ if (skipNextBit) {
1026
+ buffer = (buffer << 7) | b;
1027
+ bufferSize += 7;
1028
+ skipNextBit = false;
1029
+ } else {
1030
+ buffer = (buffer << 8) | b;
1031
+ bufferSize += 8;
1032
+ }
1033
+ if (b === 0xFF) {
1034
+ skipNextBit = true;
1035
+ }
1036
+ }
1037
+ bufferSize -= count;
1038
+ return (buffer >>> bufferSize) & ((1 << count) - 1);
1039
+ }
1040
+ function skipMarkerIfEqual(value) {
1041
+ if (data[offset + position - 1] === 0xFF &&
1042
+ data[offset + position] === value) {
1043
+ skipBytes(1);
1044
+ return true;
1045
+ } else if (data[offset + position] === 0xFF &&
1046
+ data[offset + position + 1] === value) {
1047
+ skipBytes(2);
1048
+ return true;
1049
+ }
1050
+ return false;
1051
+ }
1052
+ function skipBytes(count) {
1053
+ position += count;
1054
+ }
1055
+ function alignToByte() {
1056
+ bufferSize = 0;
1057
+ if (skipNextBit) {
1058
+ position++;
1059
+ skipNextBit = false;
1060
+ }
1061
+ }
1062
+ function readCodingpasses() {
1063
+ if (readBits(1) === 0) {
1064
+ return 1;
1065
+ }
1066
+ if (readBits(1) === 0) {
1067
+ return 2;
1068
+ }
1069
+ var value = readBits(2);
1070
+ if (value < 3) {
1071
+ return value + 3;
1072
+ }
1073
+ value = readBits(5);
1074
+ if (value < 31) {
1075
+ return value + 6;
1076
+ }
1077
+ value = readBits(7);
1078
+ return value + 37;
1079
+ }
1080
+ var tileIndex = context.currentTile.index;
1081
+ var tile = context.tiles[tileIndex];
1082
+ var sopMarkerUsed = context.COD.sopMarkerUsed;
1083
+ var ephMarkerUsed = context.COD.ephMarkerUsed;
1084
+ var packetsIterator = tile.packetsIterator;
1085
+ while (position < dataLength) {
1086
+ alignToByte();
1087
+ if (sopMarkerUsed && skipMarkerIfEqual(0x91)) {
1088
+ // Skip also marker segment length and packet sequence ID
1089
+ skipBytes(4);
1090
+ }
1091
+ var packet = packetsIterator.nextPacket();
1092
+ if (packet===undefined) {
1093
+ //No more packets. Stream is truncated.
1094
+ return;
1095
+ }
1096
+ if (!readBits(1)) {
1097
+ continue;
1098
+ }
1099
+ var layerNumber = packet.layerNumber;
1100
+ var queue = [], codeblock;
1101
+ for (var i = 0, ii = packet.codeblocks.length; i < ii; i++) {
1102
+ codeblock = packet.codeblocks[i];
1103
+ var precinct = codeblock.precinct;
1104
+ var codeblockColumn = codeblock.cbx - precinct.cbxMin;
1105
+ var codeblockRow = codeblock.cby - precinct.cbyMin;
1106
+ var codeblockIncluded = false;
1107
+ var firstTimeInclusion = false;
1108
+ var valueReady;
1109
+ if (codeblock['included'] !== undefined) {
1110
+ codeblockIncluded = !!readBits(1);
1111
+ } else {
1112
+ // reading inclusion tree
1113
+ precinct = codeblock.precinct;
1114
+ var inclusionTree, zeroBitPlanesTree;
1115
+ if (precinct['inclusionTree'] !== undefined) {
1116
+ inclusionTree = precinct.inclusionTree;
1117
+ } else {
1118
+ // building inclusion and zero bit-planes trees
1119
+ var width = precinct.cbxMax - precinct.cbxMin + 1;
1120
+ var height = precinct.cbyMax - precinct.cbyMin + 1;
1121
+ inclusionTree = new InclusionTree(width, height, layerNumber);
1122
+ zeroBitPlanesTree = new TagTree(width, height);
1123
+ precinct.inclusionTree = inclusionTree;
1124
+ precinct.zeroBitPlanesTree = zeroBitPlanesTree;
1125
+ for (var l=0; l < layerNumber; l++) {
1126
+ if (readBits(1) !== 0) {
1127
+ throw new Error('JPX Error: Invalid tag tree');
1128
+ }
1129
+ }
1130
+ }
1131
+
1132
+ if (inclusionTree.reset(codeblockColumn, codeblockRow, layerNumber)) {
1133
+ while (true) {
1134
+ if (readBits(1)) {
1135
+ valueReady = !inclusionTree.nextLevel();
1136
+ if (valueReady) {
1137
+ codeblock.included = true;
1138
+ codeblockIncluded = firstTimeInclusion = true;
1139
+ break;
1140
+ }
1141
+ } else {
1142
+ inclusionTree.incrementValue(layerNumber);
1143
+ break;
1144
+ }
1145
+ }
1146
+ }
1147
+ }
1148
+ if (!codeblockIncluded) {
1149
+ continue;
1150
+ }
1151
+ if (firstTimeInclusion) {
1152
+ zeroBitPlanesTree = precinct.zeroBitPlanesTree;
1153
+ zeroBitPlanesTree.reset(codeblockColumn, codeblockRow);
1154
+ while (true) {
1155
+ if (readBits(1)) {
1156
+ valueReady = !zeroBitPlanesTree.nextLevel();
1157
+ if (valueReady) {
1158
+ break;
1159
+ }
1160
+ } else {
1161
+ zeroBitPlanesTree.incrementValue();
1162
+ }
1163
+ }
1164
+ codeblock.zeroBitPlanes = zeroBitPlanesTree.value;
1165
+ }
1166
+ var codingpasses = readCodingpasses();
1167
+ while (readBits(1)) {
1168
+ codeblock.Lblock++;
1169
+ }
1170
+ var codingpassesLog2 = log2(codingpasses);
1171
+ // rounding down log2
1172
+ var bits = ((codingpasses < (1 << codingpassesLog2)) ?
1173
+ codingpassesLog2 - 1 : codingpassesLog2) + codeblock.Lblock;
1174
+ var codedDataLength = readBits(bits);
1175
+ queue.push({
1176
+ codeblock: codeblock,
1177
+ codingpasses: codingpasses,
1178
+ dataLength: codedDataLength
1179
+ });
1180
+ }
1181
+ alignToByte();
1182
+ if (ephMarkerUsed) {
1183
+ skipMarkerIfEqual(0x92);
1184
+ }
1185
+ while (queue.length > 0) {
1186
+ var packetItem = queue.shift();
1187
+ codeblock = packetItem.codeblock;
1188
+ if (codeblock['data'] === undefined) {
1189
+ codeblock.data = [];
1190
+ }
1191
+ codeblock.data.push({
1192
+ data: data,
1193
+ start: offset + position,
1194
+ end: offset + position + packetItem.dataLength,
1195
+ codingpasses: packetItem.codingpasses
1196
+ });
1197
+ position += packetItem.dataLength;
1198
+ }
1199
+ }
1200
+ return position;
1201
+ }
1202
+ function copyCoefficients(coefficients, levelWidth, levelHeight, subband,
1203
+ delta, mb, reversible, segmentationSymbolUsed) {
1204
+ var x0 = subband.tbx0;
1205
+ var y0 = subband.tby0;
1206
+ var width = subband.tbx1 - subband.tbx0;
1207
+ var codeblocks = subband.codeblocks;
1208
+ var right = subband.type.charAt(0) === 'H' ? 1 : 0;
1209
+ var bottom = subband.type.charAt(1) === 'H' ? levelWidth : 0;
1210
+
1211
+ for (var i = 0, ii = codeblocks.length; i < ii; ++i) {
1212
+ var codeblock = codeblocks[i];
1213
+ var blockWidth = codeblock.tbx1_ - codeblock.tbx0_;
1214
+ var blockHeight = codeblock.tby1_ - codeblock.tby0_;
1215
+ if (blockWidth === 0 || blockHeight === 0) {
1216
+ continue;
1217
+ }
1218
+ if (codeblock['data'] === undefined) {
1219
+ continue;
1220
+ }
1221
+
1222
+ var bitModel, currentCodingpassType;
1223
+ bitModel = new BitModel(blockWidth, blockHeight, codeblock.subbandType,
1224
+ codeblock.zeroBitPlanes, mb);
1225
+ currentCodingpassType = 2; // first bit plane starts from cleanup
1226
+
1227
+ // collect data
1228
+ var data = codeblock.data, totalLength = 0, codingpasses = 0;
1229
+ var j, jj, dataItem;
1230
+ for (j = 0, jj = data.length; j < jj; j++) {
1231
+ dataItem = data[j];
1232
+ totalLength += dataItem.end - dataItem.start;
1233
+ codingpasses += dataItem.codingpasses;
1234
+ }
1235
+ var encodedData = new Int16Array(totalLength);
1236
+ var position = 0;
1237
+ for (j = 0, jj = data.length; j < jj; j++) {
1238
+ dataItem = data[j];
1239
+ var chunk = dataItem.data.subarray(dataItem.start, dataItem.end);
1240
+ encodedData.set(chunk, position);
1241
+ position += chunk.length;
1242
+ }
1243
+ // decoding the item
1244
+ var decoder = new ArithmeticDecoder(encodedData, 0, totalLength);
1245
+ bitModel.setDecoder(decoder);
1246
+
1247
+ for (j = 0; j < codingpasses; j++) {
1248
+ switch (currentCodingpassType) {
1249
+ case 0:
1250
+ bitModel.runSignificancePropogationPass();
1251
+ break;
1252
+ case 1:
1253
+ bitModel.runMagnitudeRefinementPass();
1254
+ break;
1255
+ case 2:
1256
+ bitModel.runCleanupPass();
1257
+ if (segmentationSymbolUsed) {
1258
+ bitModel.checkSegmentationSymbol();
1259
+ }
1260
+ break;
1261
+ }
1262
+ currentCodingpassType = (currentCodingpassType + 1) % 3;
1263
+ }
1264
+
1265
+ var offset = (codeblock.tbx0_ - x0) + (codeblock.tby0_ - y0) * width;
1266
+ var sign = bitModel.coefficentsSign;
1267
+ var magnitude = bitModel.coefficentsMagnitude;
1268
+ var bitsDecoded = bitModel.bitsDecoded;
1269
+ var magnitudeCorrection = reversible ? 0 : 0.5;
1270
+ var k, n, nb;
1271
+ position = 0;
1272
+ // Do the interleaving of Section F.3.3 here, so we do not need
1273
+ // to copy later. LL level is not interleaved, just copied.
1274
+ var interleave = (subband.type !== 'LL');
1275
+ for (j = 0; j < blockHeight; j++) {
1276
+ var row = (offset / width) | 0; // row in the non-interleaved subband
1277
+ var levelOffset = 2 * row * (levelWidth - width) + right + bottom;
1278
+ for (k = 0; k < blockWidth; k++) {
1279
+ n = magnitude[position];
1280
+ if (n !== 0) {
1281
+ n = (n + magnitudeCorrection) * delta;
1282
+ if (sign[position] !== 0) {
1283
+ n = -n;
1284
+ }
1285
+ nb = bitsDecoded[position];
1286
+ var pos = interleave ? (levelOffset + (offset << 1)) : offset;
1287
+ if (reversible && (nb >= mb)) {
1288
+ coefficients[pos] = n;
1289
+ } else {
1290
+ coefficients[pos] = n * (1 << (mb - nb));
1291
+ }
1292
+ }
1293
+ offset++;
1294
+ position++;
1295
+ }
1296
+ offset += width - blockWidth;
1297
+ }
1298
+ }
1299
+ }
1300
+ function transformTile(context, tile, c) {
1301
+ var component = tile.components[c];
1302
+ var codingStyleParameters = component.codingStyleParameters;
1303
+ var quantizationParameters = component.quantizationParameters;
1304
+ var decompositionLevelsCount =
1305
+ codingStyleParameters.decompositionLevelsCount;
1306
+ var spqcds = quantizationParameters.SPqcds;
1307
+ var scalarExpounded = quantizationParameters.scalarExpounded;
1308
+ var guardBits = quantizationParameters.guardBits;
1309
+ var segmentationSymbolUsed = codingStyleParameters.segmentationSymbolUsed;
1310
+ var precision = context.components[c].precision;
1311
+
1312
+ var reversible = codingStyleParameters.reversibleTransformation;
1313
+ var transform = (reversible ? new ReversibleTransform() :
1314
+ new IrreversibleTransform());
1315
+
1316
+ var subbandCoefficients = [];
1317
+ var b = 0;
1318
+ for (var i = 0; i <= decompositionLevelsCount; i++) {
1319
+ var resolution = component.resolutions[i];
1320
+
1321
+ var width = resolution.trx1 - resolution.trx0;
1322
+ var height = resolution.try1 - resolution.try0;
1323
+ // Allocate space for the whole sublevel.
1324
+ var coefficients = new Float32Array(width * height);
1325
+
1326
+ for (var j = 0, jj = resolution.subbands.length; j < jj; j++) {
1327
+ var mu, epsilon;
1328
+ if (!scalarExpounded) {
1329
+ // formula E-5
1330
+ mu = spqcds[0].mu;
1331
+ epsilon = spqcds[0].epsilon + (i > 0 ? 1 - i : 0);
1332
+ } else {
1333
+ mu = spqcds[b].mu;
1334
+ epsilon = spqcds[b].epsilon;
1335
+ b++;
1336
+ }
1337
+
1338
+ var subband = resolution.subbands[j];
1339
+ var gainLog2 = SubbandsGainLog2[subband.type];
1340
+
1341
+ // calulate quantization coefficient (Section E.1.1.1)
1342
+ var delta = (reversible ? 1 :
1343
+ Math.pow(2, precision + gainLog2 - epsilon) * (1 + mu / 2048));
1344
+ var mb = (guardBits + epsilon - 1);
1345
+
1346
+ // In the first resolution level, copyCoefficients will fill the
1347
+ // whole array with coefficients. In the succeding passes,
1348
+ // copyCoefficients will consecutively fill in the values that belong
1349
+ // to the interleaved positions of the HL, LH, and HH coefficients.
1350
+ // The LL coefficients will then be interleaved in Transform.iterate().
1351
+ copyCoefficients(coefficients, width, height, subband, delta, mb,
1352
+ reversible, segmentationSymbolUsed);
1353
+ }
1354
+ subbandCoefficients.push({
1355
+ width: width,
1356
+ height: height,
1357
+ items: coefficients
1358
+ });
1359
+ }
1360
+
1361
+ var result = transform.calculate(subbandCoefficients,
1362
+ component.tcx0, component.tcy0);
1363
+ return {
1364
+ left: component.tcx0,
1365
+ top: component.tcy0,
1366
+ width: result.width,
1367
+ height: result.height,
1368
+ items: result.items
1369
+ };
1370
+ }
1371
+ function transformComponents(context) {
1372
+ var siz = context.SIZ;
1373
+ var components = context.components;
1374
+ var componentsCount = siz.Csiz;
1375
+ var resultImages = [];
1376
+ for (var i = 0, ii = context.tiles.length; i < ii; i++) {
1377
+ var tile = context.tiles[i];
1378
+ var transformedTiles = [];
1379
+ var c;
1380
+ for (c = 0; c < componentsCount; c++) {
1381
+ transformedTiles[c] = transformTile(context, tile, c);
1382
+ }
1383
+ var tile0 = transformedTiles[0];
1384
+ var out = new Int16Array(tile0.items.length * componentsCount);
1385
+ var result = {
1386
+ left: tile0.left,
1387
+ top: tile0.top,
1388
+ width: tile0.width,
1389
+ height: tile0.height,
1390
+ items: out
1391
+ };
1392
+
1393
+ // Section G.2.2 Inverse multi component transform
1394
+ var shift, offset, max, min, maxK;
1395
+ var pos = 0, j, jj, y0, y1, y2, r, g, b, k, val;
1396
+ if (tile.codingStyleDefaultParameters.multipleComponentTransform) {
1397
+ var fourComponents = componentsCount === 4;
1398
+ var y0items = transformedTiles[0].items;
1399
+ var y1items = transformedTiles[1].items;
1400
+ var y2items = transformedTiles[2].items;
1401
+ var y3items = fourComponents ? transformedTiles[3].items : null;
1402
+
1403
+ // HACK: The multiple component transform formulas below assume that
1404
+ // all components have the same precision. With this in mind, we
1405
+ // compute shift and offset only once.
1406
+ shift = components[0].precision - 8;
1407
+ offset = (128 << shift) + 0.5;
1408
+ max = 255 * (1 << shift);
1409
+ maxK = max * 0.5;
1410
+ min = -maxK;
1411
+
1412
+ var component0 = tile.components[0];
1413
+ var alpha01 = componentsCount - 3;
1414
+ jj = y0items.length;
1415
+ if (!component0.codingStyleParameters.reversibleTransformation) {
1416
+ // inverse irreversible multiple component transform
1417
+ for (j = 0; j < jj; j++, pos += alpha01) {
1418
+ y0 = y0items[j] + offset;
1419
+ y1 = y1items[j];
1420
+ y2 = y2items[j];
1421
+ r = y0 + 1.402 * y2;
1422
+ g = y0 - 0.34413 * y1 - 0.71414 * y2;
1423
+ b = y0 + 1.772 * y1;
1424
+ out[pos++] = r <= 0 ? 0 : r >= max ? 255 : r >> shift;
1425
+ out[pos++] = g <= 0 ? 0 : g >= max ? 255 : g >> shift;
1426
+ out[pos++] = b <= 0 ? 0 : b >= max ? 255 : b >> shift;
1427
+ }
1428
+ } else {
1429
+ // inverse reversible multiple component transform
1430
+ for (j = 0; j < jj; j++, pos += alpha01) {
1431
+ y0 = y0items[j] + offset;
1432
+ y1 = y1items[j];
1433
+ y2 = y2items[j];
1434
+ g = y0 - ((y2 + y1) >> 2);
1435
+ r = g + y2;
1436
+ b = g + y1;
1437
+ out[pos++] = r <= 0 ? 0 : r >= max ? 255 : r >> shift;
1438
+ out[pos++] = g <= 0 ? 0 : g >= max ? 255 : g >> shift;
1439
+ out[pos++] = b <= 0 ? 0 : b >= max ? 255 : b >> shift;
1440
+ }
1441
+ }
1442
+ if (fourComponents) {
1443
+ for (j = 0, pos = 3; j < jj; j++, pos += 4) {
1444
+ k = y3items[j];
1445
+ out[pos] = k <= min ? 0 : k >= maxK ? 255 : (k + offset) >> shift;
1446
+ }
1447
+ }
1448
+ } else { // no multi-component transform
1449
+ for (c = 0; c < componentsCount; c++) {
1450
+ if (components[c].precision === 8){
1451
+ var items = transformedTiles[c].items;
1452
+ shift = components[c].precision - 8;
1453
+ offset = (128 << shift) + 0.5;
1454
+ max = (127.5 * (1 << shift));
1455
+ min = -max;
1456
+ for (pos = c, j = 0, jj = items.length; j < jj; j++) {
1457
+ val = items[j];
1458
+ out[pos] = val <= min ? 0 :
1459
+ val >= max ? 255 : (val + offset) >> shift;
1460
+ pos += componentsCount;
1461
+ }
1462
+ }else{
1463
+ var isSigned = components[c].isSigned;
1464
+ var items = transformedTiles[c].items;
1465
+
1466
+ if(isSigned){
1467
+ shift = 0;
1468
+ offset = 0;
1469
+ }else{
1470
+ shift = components[c].precision - 8;
1471
+ offset = (128 << shift) + 0.5;
1472
+ }
1473
+
1474
+ for (pos = c, j = 0, jj = items.length; j < jj; j++) {
1475
+ val = items[j];
1476
+ out[pos] = (val + offset);
1477
+ pos += componentsCount;
1478
+ }
1479
+ }
1480
+ }
1481
+ }
1482
+ resultImages.push(result);
1483
+ }
1484
+ return resultImages;
1485
+ }
1486
+ function initializeTile(context, tileIndex) {
1487
+ var siz = context.SIZ;
1488
+ var componentsCount = siz.Csiz;
1489
+ var tile = context.tiles[tileIndex];
1490
+ for (var c = 0; c < componentsCount; c++) {
1491
+ var component = tile.components[c];
1492
+ var qcdOrQcc = (context.currentTile.QCC[c] !== undefined ?
1493
+ context.currentTile.QCC[c] : context.currentTile.QCD);
1494
+ component.quantizationParameters = qcdOrQcc;
1495
+ var codOrCoc = (context.currentTile.COC[c] !== undefined ?
1496
+ context.currentTile.COC[c] : context.currentTile.COD);
1497
+ component.codingStyleParameters = codOrCoc;
1498
+ }
1499
+ tile.codingStyleDefaultParameters = context.currentTile.COD;
1500
+ }
1501
+
1502
+ // Section B.10.2 Tag trees
1503
+ var TagTree = (function TagTreeClosure() {
1504
+ function TagTree(width, height) {
1505
+ var levelsLength = log2(Math.max(width, height)) + 1;
1506
+ this.levels = [];
1507
+ for (var i = 0; i < levelsLength; i++) {
1508
+ var level = {
1509
+ width: width,
1510
+ height: height,
1511
+ items: []
1512
+ };
1513
+ this.levels.push(level);
1514
+ width = Math.ceil(width / 2);
1515
+ height = Math.ceil(height / 2);
1516
+ }
1517
+ }
1518
+ TagTree.prototype = {
1519
+ reset: function TagTree_reset(i, j) {
1520
+ var currentLevel = 0, value = 0, level;
1521
+ while (currentLevel < this.levels.length) {
1522
+ level = this.levels[currentLevel];
1523
+ var index = i + j * level.width;
1524
+ if (level.items[index] !== undefined) {
1525
+ value = level.items[index];
1526
+ break;
1527
+ }
1528
+ level.index = index;
1529
+ i >>= 1;
1530
+ j >>= 1;
1531
+ currentLevel++;
1532
+ }
1533
+ currentLevel--;
1534
+ level = this.levels[currentLevel];
1535
+ level.items[level.index] = value;
1536
+ this.currentLevel = currentLevel;
1537
+ delete this.value;
1538
+ },
1539
+ incrementValue: function TagTree_incrementValue() {
1540
+ var level = this.levels[this.currentLevel];
1541
+ level.items[level.index]++;
1542
+ },
1543
+ nextLevel: function TagTree_nextLevel() {
1544
+ var currentLevel = this.currentLevel;
1545
+ var level = this.levels[currentLevel];
1546
+ var value = level.items[level.index];
1547
+ currentLevel--;
1548
+ if (currentLevel < 0) {
1549
+ this.value = value;
1550
+ return false;
1551
+ }
1552
+
1553
+ this.currentLevel = currentLevel;
1554
+ level = this.levels[currentLevel];
1555
+ level.items[level.index] = value;
1556
+ return true;
1557
+ }
1558
+ };
1559
+ return TagTree;
1560
+ })();
1561
+
1562
+ var InclusionTree = (function InclusionTreeClosure() {
1563
+ function InclusionTree(width, height, defaultValue) {
1564
+ var levelsLength = log2(Math.max(width, height)) + 1;
1565
+ this.levels = [];
1566
+ for (var i = 0; i < levelsLength; i++) {
1567
+ var items = new Int16Array(width * height);
1568
+ for (var j = 0, jj = items.length; j < jj; j++) {
1569
+ items[j] = defaultValue;
1570
+ }
1571
+
1572
+ var level = {
1573
+ width: width,
1574
+ height: height,
1575
+ items: items
1576
+ };
1577
+ this.levels.push(level);
1578
+
1579
+ width = Math.ceil(width / 2);
1580
+ height = Math.ceil(height / 2);
1581
+ }
1582
+ }
1583
+ InclusionTree.prototype = {
1584
+ reset: function InclusionTree_reset(i, j, stopValue) {
1585
+ var currentLevel = 0;
1586
+ while (currentLevel < this.levels.length) {
1587
+ var level = this.levels[currentLevel];
1588
+ var index = i + j * level.width;
1589
+ level.index = index;
1590
+ var value = level.items[index];
1591
+
1592
+ if (value === 0xFF) {
1593
+ break;
1594
+ }
1595
+
1596
+ if (value > stopValue) {
1597
+ this.currentLevel = currentLevel;
1598
+ // already know about this one, propagating the value to top levels
1599
+ this.propagateValues();
1600
+ return false;
1601
+ }
1602
+
1603
+ i >>= 1;
1604
+ j >>= 1;
1605
+ currentLevel++;
1606
+ }
1607
+ this.currentLevel = currentLevel - 1;
1608
+ return true;
1609
+ },
1610
+ incrementValue: function InclusionTree_incrementValue(stopValue) {
1611
+ var level = this.levels[this.currentLevel];
1612
+ level.items[level.index] = stopValue + 1;
1613
+ this.propagateValues();
1614
+ },
1615
+ propagateValues: function InclusionTree_propagateValues() {
1616
+ var levelIndex = this.currentLevel;
1617
+ var level = this.levels[levelIndex];
1618
+ var currentValue = level.items[level.index];
1619
+ while (--levelIndex >= 0) {
1620
+ level = this.levels[levelIndex];
1621
+ level.items[level.index] = currentValue;
1622
+ }
1623
+ },
1624
+ nextLevel: function InclusionTree_nextLevel() {
1625
+ var currentLevel = this.currentLevel;
1626
+ var level = this.levels[currentLevel];
1627
+ var value = level.items[level.index];
1628
+ level.items[level.index] = 0xFF;
1629
+ currentLevel--;
1630
+ if (currentLevel < 0) {
1631
+ return false;
1632
+ }
1633
+
1634
+ this.currentLevel = currentLevel;
1635
+ level = this.levels[currentLevel];
1636
+ level.items[level.index] = value;
1637
+ return true;
1638
+ }
1639
+ };
1640
+ return InclusionTree;
1641
+ })();
1642
+
1643
+ // Section D. Coefficient bit modeling
1644
+ var BitModel = (function BitModelClosure() {
1645
+ var UNIFORM_CONTEXT = 17;
1646
+ var RUNLENGTH_CONTEXT = 18;
1647
+ // Table D-1
1648
+ // The index is binary presentation: 0dddvvhh, ddd - sum of Di (0..4),
1649
+ // vv - sum of Vi (0..2), and hh - sum of Hi (0..2)
1650
+ var LLAndLHContextsLabel = new Uint8Array([
1651
+ 0, 5, 8, 0, 3, 7, 8, 0, 4, 7, 8, 0, 0, 0, 0, 0, 1, 6, 8, 0, 3, 7, 8, 0, 4,
1652
+ 7, 8, 0, 0, 0, 0, 0, 2, 6, 8, 0, 3, 7, 8, 0, 4, 7, 8, 0, 0, 0, 0, 0, 2, 6,
1653
+ 8, 0, 3, 7, 8, 0, 4, 7, 8, 0, 0, 0, 0, 0, 2, 6, 8, 0, 3, 7, 8, 0, 4, 7, 8
1654
+ ]);
1655
+ var HLContextLabel = new Uint8Array([
1656
+ 0, 3, 4, 0, 5, 7, 7, 0, 8, 8, 8, 0, 0, 0, 0, 0, 1, 3, 4, 0, 6, 7, 7, 0, 8,
1657
+ 8, 8, 0, 0, 0, 0, 0, 2, 3, 4, 0, 6, 7, 7, 0, 8, 8, 8, 0, 0, 0, 0, 0, 2, 3,
1658
+ 4, 0, 6, 7, 7, 0, 8, 8, 8, 0, 0, 0, 0, 0, 2, 3, 4, 0, 6, 7, 7, 0, 8, 8, 8
1659
+ ]);
1660
+ var HHContextLabel = new Uint8Array([
1661
+ 0, 1, 2, 0, 1, 2, 2, 0, 2, 2, 2, 0, 0, 0, 0, 0, 3, 4, 5, 0, 4, 5, 5, 0, 5,
1662
+ 5, 5, 0, 0, 0, 0, 0, 6, 7, 7, 0, 7, 7, 7, 0, 7, 7, 7, 0, 0, 0, 0, 0, 8, 8,
1663
+ 8, 0, 8, 8, 8, 0, 8, 8, 8, 0, 0, 0, 0, 0, 8, 8, 8, 0, 8, 8, 8, 0, 8, 8, 8
1664
+ ]);
1665
+
1666
+ function BitModel(width, height, subband, zeroBitPlanes, mb) {
1667
+ this.width = width;
1668
+ this.height = height;
1669
+
1670
+ this.contextLabelTable = (subband === 'HH' ? HHContextLabel :
1671
+ (subband === 'HL' ? HLContextLabel : LLAndLHContextsLabel));
1672
+
1673
+ var coefficientCount = width * height;
1674
+
1675
+ // coefficients outside the encoding region treated as insignificant
1676
+ // add border state cells for significanceState
1677
+ this.neighborsSignificance = new Uint8Array(coefficientCount);
1678
+ this.coefficentsSign = new Uint8Array(coefficientCount);
1679
+ this.coefficentsMagnitude = mb > 14 ? new Uint32Array(coefficientCount) :
1680
+ mb > 6 ? new Uint16Array(coefficientCount) :
1681
+ new Uint8Array(coefficientCount);
1682
+ this.processingFlags = new Uint8Array(coefficientCount);
1683
+
1684
+ var bitsDecoded = new Uint8Array(coefficientCount);
1685
+ if (zeroBitPlanes !== 0) {
1686
+ for (var i = 0; i < coefficientCount; i++) {
1687
+ bitsDecoded[i] = zeroBitPlanes;
1688
+ }
1689
+ }
1690
+ this.bitsDecoded = bitsDecoded;
1691
+
1692
+ this.reset();
1693
+ }
1694
+
1695
+ BitModel.prototype = {
1696
+ setDecoder: function BitModel_setDecoder(decoder) {
1697
+ this.decoder = decoder;
1698
+ },
1699
+ reset: function BitModel_reset() {
1700
+ // We have 17 contexts that are accessed via context labels,
1701
+ // plus the uniform and runlength context.
1702
+ this.contexts = new Int8Array(19);
1703
+
1704
+ // Contexts are packed into 1 byte:
1705
+ // highest 7 bits carry the index, lowest bit carries mps
1706
+ this.contexts[0] = (4 << 1) | 0;
1707
+ this.contexts[UNIFORM_CONTEXT] = (46 << 1) | 0;
1708
+ this.contexts[RUNLENGTH_CONTEXT] = (3 << 1) | 0;
1709
+ },
1710
+ setNeighborsSignificance:
1711
+ function BitModel_setNeighborsSignificance(row, column, index) {
1712
+ var neighborsSignificance = this.neighborsSignificance;
1713
+ var width = this.width, height = this.height;
1714
+ var left = (column > 0);
1715
+ var right = (column + 1 < width);
1716
+ var i;
1717
+
1718
+ if (row > 0) {
1719
+ i = index - width;
1720
+ if (left) {
1721
+ neighborsSignificance[i - 1] += 0x10;
1722
+ }
1723
+ if (right) {
1724
+ neighborsSignificance[i + 1] += 0x10;
1725
+ }
1726
+ neighborsSignificance[i] += 0x04;
1727
+ }
1728
+
1729
+ if (row + 1 < height) {
1730
+ i = index + width;
1731
+ if (left) {
1732
+ neighborsSignificance[i - 1] += 0x10;
1733
+ }
1734
+ if (right) {
1735
+ neighborsSignificance[i + 1] += 0x10;
1736
+ }
1737
+ neighborsSignificance[i] += 0x04;
1738
+ }
1739
+
1740
+ if (left) {
1741
+ neighborsSignificance[index - 1] += 0x01;
1742
+ }
1743
+ if (right) {
1744
+ neighborsSignificance[index + 1] += 0x01;
1745
+ }
1746
+ neighborsSignificance[index] |= 0x80;
1747
+ },
1748
+ runSignificancePropogationPass:
1749
+ function BitModel_runSignificancePropogationPass() {
1750
+ var decoder = this.decoder;
1751
+ var width = this.width, height = this.height;
1752
+ var coefficentsMagnitude = this.coefficentsMagnitude;
1753
+ var coefficentsSign = this.coefficentsSign;
1754
+ var neighborsSignificance = this.neighborsSignificance;
1755
+ var processingFlags = this.processingFlags;
1756
+ var contexts = this.contexts;
1757
+ var labels = this.contextLabelTable;
1758
+ var bitsDecoded = this.bitsDecoded;
1759
+ var processedInverseMask = ~1;
1760
+ var processedMask = 1;
1761
+ var firstMagnitudeBitMask = 2;
1762
+
1763
+ for (var i0 = 0; i0 < height; i0 += 4) {
1764
+ for (var j = 0; j < width; j++) {
1765
+ var index = i0 * width + j;
1766
+ for (var i1 = 0; i1 < 4; i1++, index += width) {
1767
+ var i = i0 + i1;
1768
+ if (i >= height) {
1769
+ break;
1770
+ }
1771
+ // clear processed flag first
1772
+ processingFlags[index] &= processedInverseMask;
1773
+
1774
+ if (coefficentsMagnitude[index] ||
1775
+ !neighborsSignificance[index]) {
1776
+ continue;
1777
+ }
1778
+
1779
+ var contextLabel = labels[neighborsSignificance[index]];
1780
+ var decision = decoder.readBit(contexts, contextLabel);
1781
+ if (decision) {
1782
+ var sign = this.decodeSignBit(i, j, index);
1783
+ coefficentsSign[index] = sign;
1784
+ coefficentsMagnitude[index] = 1;
1785
+ this.setNeighborsSignificance(i, j, index);
1786
+ processingFlags[index] |= firstMagnitudeBitMask;
1787
+ }
1788
+ bitsDecoded[index]++;
1789
+ processingFlags[index] |= processedMask;
1790
+ }
1791
+ }
1792
+ }
1793
+ },
1794
+ decodeSignBit: function BitModel_decodeSignBit(row, column, index) {
1795
+ var width = this.width, height = this.height;
1796
+ var coefficentsMagnitude = this.coefficentsMagnitude;
1797
+ var coefficentsSign = this.coefficentsSign;
1798
+ var contribution, sign0, sign1, significance1;
1799
+ var contextLabel, decoded;
1800
+
1801
+ // calculate horizontal contribution
1802
+ significance1 = (column > 0 && coefficentsMagnitude[index - 1] !== 0);
1803
+ if (column + 1 < width && coefficentsMagnitude[index + 1] !== 0) {
1804
+ sign1 = coefficentsSign[index + 1];
1805
+ if (significance1) {
1806
+ sign0 = coefficentsSign[index - 1];
1807
+ contribution = 1 - sign1 - sign0;
1808
+ } else {
1809
+ contribution = 1 - sign1 - sign1;
1810
+ }
1811
+ } else if (significance1) {
1812
+ sign0 = coefficentsSign[index - 1];
1813
+ contribution = 1 - sign0 - sign0;
1814
+ } else {
1815
+ contribution = 0;
1816
+ }
1817
+ var horizontalContribution = 3 * contribution;
1818
+
1819
+ // calculate vertical contribution and combine with the horizontal
1820
+ significance1 = (row > 0 && coefficentsMagnitude[index - width] !== 0);
1821
+ if (row + 1 < height && coefficentsMagnitude[index + width] !== 0) {
1822
+ sign1 = coefficentsSign[index + width];
1823
+ if (significance1) {
1824
+ sign0 = coefficentsSign[index - width];
1825
+ contribution = 1 - sign1 - sign0 + horizontalContribution;
1826
+ } else {
1827
+ contribution = 1 - sign1 - sign1 + horizontalContribution;
1828
+ }
1829
+ } else if (significance1) {
1830
+ sign0 = coefficentsSign[index - width];
1831
+ contribution = 1 - sign0 - sign0 + horizontalContribution;
1832
+ } else {
1833
+ contribution = horizontalContribution;
1834
+ }
1835
+
1836
+ if (contribution >= 0) {
1837
+ contextLabel = 9 + contribution;
1838
+ decoded = this.decoder.readBit(this.contexts, contextLabel);
1839
+ } else {
1840
+ contextLabel = 9 - contribution;
1841
+ decoded = this.decoder.readBit(this.contexts, contextLabel) ^ 1;
1842
+ }
1843
+ return decoded;
1844
+ },
1845
+ runMagnitudeRefinementPass:
1846
+ function BitModel_runMagnitudeRefinementPass() {
1847
+ var decoder = this.decoder;
1848
+ var width = this.width, height = this.height;
1849
+ var coefficentsMagnitude = this.coefficentsMagnitude;
1850
+ var neighborsSignificance = this.neighborsSignificance;
1851
+ var contexts = this.contexts;
1852
+ var bitsDecoded = this.bitsDecoded;
1853
+ var processingFlags = this.processingFlags;
1854
+ var processedMask = 1;
1855
+ var firstMagnitudeBitMask = 2;
1856
+ var length = width * height;
1857
+ var width4 = width * 4;
1858
+
1859
+ for (var index0 = 0, indexNext; index0 < length; index0 = indexNext) {
1860
+ indexNext = Math.min(length, index0 + width4);
1861
+ for (var j = 0; j < width; j++) {
1862
+ for (var index = index0 + j; index < indexNext; index += width) {
1863
+
1864
+ // significant but not those that have just become
1865
+ if (!coefficentsMagnitude[index] ||
1866
+ (processingFlags[index] & processedMask) !== 0) {
1867
+ continue;
1868
+ }
1869
+
1870
+ var contextLabel = 16;
1871
+ if ((processingFlags[index] & firstMagnitudeBitMask) !== 0) {
1872
+ processingFlags[index] ^= firstMagnitudeBitMask;
1873
+ // first refinement
1874
+ var significance = neighborsSignificance[index] & 127;
1875
+ contextLabel = significance === 0 ? 15 : 14;
1876
+ }
1877
+
1878
+ var bit = decoder.readBit(contexts, contextLabel);
1879
+ coefficentsMagnitude[index] =
1880
+ (coefficentsMagnitude[index] << 1) | bit;
1881
+ bitsDecoded[index]++;
1882
+ processingFlags[index] |= processedMask;
1883
+ }
1884
+ }
1885
+ }
1886
+ },
1887
+ runCleanupPass: function BitModel_runCleanupPass() {
1888
+ var decoder = this.decoder;
1889
+ var width = this.width, height = this.height;
1890
+ var neighborsSignificance = this.neighborsSignificance;
1891
+ var coefficentsMagnitude = this.coefficentsMagnitude;
1892
+ var coefficentsSign = this.coefficentsSign;
1893
+ var contexts = this.contexts;
1894
+ var labels = this.contextLabelTable;
1895
+ var bitsDecoded = this.bitsDecoded;
1896
+ var processingFlags = this.processingFlags;
1897
+ var processedMask = 1;
1898
+ var firstMagnitudeBitMask = 2;
1899
+ var oneRowDown = width;
1900
+ var twoRowsDown = width * 2;
1901
+ var threeRowsDown = width * 3;
1902
+ var iNext;
1903
+ for (var i0 = 0; i0 < height; i0 = iNext) {
1904
+ iNext = Math.min(i0 + 4, height);
1905
+ var indexBase = i0 * width;
1906
+ var checkAllEmpty = i0 + 3 < height;
1907
+ for (var j = 0; j < width; j++) {
1908
+ var index0 = indexBase + j;
1909
+ // using the property: labels[neighborsSignificance[index]] === 0
1910
+ // when neighborsSignificance[index] === 0
1911
+ var allEmpty = (checkAllEmpty &&
1912
+ processingFlags[index0] === 0 &&
1913
+ processingFlags[index0 + oneRowDown] === 0 &&
1914
+ processingFlags[index0 + twoRowsDown] === 0 &&
1915
+ processingFlags[index0 + threeRowsDown] === 0 &&
1916
+ neighborsSignificance[index0] === 0 &&
1917
+ neighborsSignificance[index0 + oneRowDown] === 0 &&
1918
+ neighborsSignificance[index0 + twoRowsDown] === 0 &&
1919
+ neighborsSignificance[index0 + threeRowsDown] === 0);
1920
+ var i1 = 0, index = index0;
1921
+ var i = i0, sign;
1922
+ if (allEmpty) {
1923
+ var hasSignificantCoefficent =
1924
+ decoder.readBit(contexts, RUNLENGTH_CONTEXT);
1925
+ if (!hasSignificantCoefficent) {
1926
+ bitsDecoded[index0]++;
1927
+ bitsDecoded[index0 + oneRowDown]++;
1928
+ bitsDecoded[index0 + twoRowsDown]++;
1929
+ bitsDecoded[index0 + threeRowsDown]++;
1930
+ continue; // next column
1931
+ }
1932
+ i1 = (decoder.readBit(contexts, UNIFORM_CONTEXT) << 1) |
1933
+ decoder.readBit(contexts, UNIFORM_CONTEXT);
1934
+ if (i1 !== 0) {
1935
+ i = i0 + i1;
1936
+ index += i1 * width;
1937
+ }
1938
+
1939
+ sign = this.decodeSignBit(i, j, index);
1940
+ coefficentsSign[index] = sign;
1941
+ coefficentsMagnitude[index] = 1;
1942
+ this.setNeighborsSignificance(i, j, index);
1943
+ processingFlags[index] |= firstMagnitudeBitMask;
1944
+
1945
+ index = index0;
1946
+ for (var i2 = i0; i2 <= i; i2++, index += width) {
1947
+ bitsDecoded[index]++;
1948
+ }
1949
+
1950
+ i1++;
1951
+ }
1952
+ for (i = i0 + i1; i < iNext; i++, index += width) {
1953
+ if (coefficentsMagnitude[index] ||
1954
+ (processingFlags[index] & processedMask) !== 0) {
1955
+ continue;
1956
+ }
1957
+
1958
+ var contextLabel = labels[neighborsSignificance[index]];
1959
+ var decision = decoder.readBit(contexts, contextLabel);
1960
+ if (decision === 1) {
1961
+ sign = this.decodeSignBit(i, j, index);
1962
+ coefficentsSign[index] = sign;
1963
+ coefficentsMagnitude[index] = 1;
1964
+ this.setNeighborsSignificance(i, j, index);
1965
+ processingFlags[index] |= firstMagnitudeBitMask;
1966
+ }
1967
+ bitsDecoded[index]++;
1968
+ }
1969
+ }
1970
+ }
1971
+ },
1972
+ checkSegmentationSymbol: function BitModel_checkSegmentationSymbol() {
1973
+ var decoder = this.decoder;
1974
+ var contexts = this.contexts;
1975
+ var symbol = (decoder.readBit(contexts, UNIFORM_CONTEXT) << 3) |
1976
+ (decoder.readBit(contexts, UNIFORM_CONTEXT) << 2) |
1977
+ (decoder.readBit(contexts, UNIFORM_CONTEXT) << 1) |
1978
+ decoder.readBit(contexts, UNIFORM_CONTEXT);
1979
+ if (symbol !== 0xA) {
1980
+ throw new Error('JPX Error: Invalid segmentation symbol');
1981
+ }
1982
+ }
1983
+ };
1984
+
1985
+ return BitModel;
1986
+ })();
1987
+
1988
+ // Section F, Discrete wavelet transformation
1989
+ var Transform = (function TransformClosure() {
1990
+ function Transform() {}
1991
+
1992
+ Transform.prototype.calculate =
1993
+ function transformCalculate(subbands, u0, v0) {
1994
+ var ll = subbands[0];
1995
+ for (var i = 1, ii = subbands.length; i < ii; i++) {
1996
+ ll = this.iterate(ll, subbands[i], u0, v0);
1997
+ }
1998
+ return ll;
1999
+ };
2000
+ Transform.prototype.extend = function extend(buffer, offset, size) {
2001
+ // Section F.3.7 extending... using max extension of 4
2002
+ var i1 = offset - 1, j1 = offset + 1;
2003
+ var i2 = offset + size - 2, j2 = offset + size;
2004
+ buffer[i1--] = buffer[j1++];
2005
+ buffer[j2++] = buffer[i2--];
2006
+ buffer[i1--] = buffer[j1++];
2007
+ buffer[j2++] = buffer[i2--];
2008
+ buffer[i1--] = buffer[j1++];
2009
+ buffer[j2++] = buffer[i2--];
2010
+ buffer[i1] = buffer[j1];
2011
+ buffer[j2] = buffer[i2];
2012
+ };
2013
+ Transform.prototype.iterate = function Transform_iterate(ll, hl_lh_hh,
2014
+ u0, v0) {
2015
+ var llWidth = ll.width, llHeight = ll.height, llItems = ll.items;
2016
+ var width = hl_lh_hh.width;
2017
+ var height = hl_lh_hh.height;
2018
+ var items = hl_lh_hh.items;
2019
+ var i, j, k, l, u, v;
2020
+
2021
+ // Interleave LL according to Section F.3.3
2022
+ for (k = 0, i = 0; i < llHeight; i++) {
2023
+ l = i * 2 * width;
2024
+ for (j = 0; j < llWidth; j++, k++, l += 2) {
2025
+ items[l] = llItems[k];
2026
+ }
2027
+ }
2028
+ // The LL band is not needed anymore.
2029
+ llItems = ll.items = null;
2030
+
2031
+ var bufferPadding = 4;
2032
+ var rowBuffer = new Float32Array(width + 2 * bufferPadding);
2033
+
2034
+ // Section F.3.4 HOR_SR
2035
+ if (width === 1) {
2036
+ // if width = 1, when u0 even keep items as is, when odd divide by 2
2037
+ if ((u0 & 1) !== 0) {
2038
+ for (v = 0, k = 0; v < height; v++, k += width) {
2039
+ items[k] *= 0.5;
2040
+ }
2041
+ }
2042
+ } else {
2043
+ for (v = 0, k = 0; v < height; v++, k += width) {
2044
+ rowBuffer.set(items.subarray(k, k + width), bufferPadding);
2045
+
2046
+ this.extend(rowBuffer, bufferPadding, width);
2047
+ this.filter(rowBuffer, bufferPadding, width);
2048
+
2049
+ items.set(
2050
+ rowBuffer.subarray(bufferPadding, bufferPadding + width),
2051
+ k);
2052
+ }
2053
+ }
2054
+
2055
+ // Accesses to the items array can take long, because it may not fit into
2056
+ // CPU cache and has to be fetched from main memory. Since subsequent
2057
+ // accesses to the items array are not local when reading columns, we
2058
+ // have a cache miss every time. To reduce cache misses, get up to
2059
+ // 'numBuffers' items at a time and store them into the individual
2060
+ // buffers. The colBuffers should be small enough to fit into CPU cache.
2061
+ var numBuffers = 16;
2062
+ var colBuffers = [];
2063
+ for (i = 0; i < numBuffers; i++) {
2064
+ colBuffers.push(new Float32Array(height + 2 * bufferPadding));
2065
+ }
2066
+ var b, currentBuffer = 0;
2067
+ ll = bufferPadding + height;
2068
+
2069
+ // Section F.3.5 VER_SR
2070
+ if (height === 1) {
2071
+ // if height = 1, when v0 even keep items as is, when odd divide by 2
2072
+ if ((v0 & 1) !== 0) {
2073
+ for (u = 0; u < width; u++) {
2074
+ items[u] *= 0.5;
2075
+ }
2076
+ }
2077
+ } else {
2078
+ for (u = 0; u < width; u++) {
2079
+ // if we ran out of buffers, copy several image columns at once
2080
+ if (currentBuffer === 0) {
2081
+ numBuffers = Math.min(width - u, numBuffers);
2082
+ for (k = u, l = bufferPadding; l < ll; k += width, l++) {
2083
+ for (b = 0; b < numBuffers; b++) {
2084
+ colBuffers[b][l] = items[k + b];
2085
+ }
2086
+ }
2087
+ currentBuffer = numBuffers;
2088
+ }
2089
+
2090
+ currentBuffer--;
2091
+ var buffer = colBuffers[currentBuffer];
2092
+ this.extend(buffer, bufferPadding, height);
2093
+ this.filter(buffer, bufferPadding, height);
2094
+
2095
+ // If this is last buffer in this group of buffers, flush all buffers.
2096
+ if (currentBuffer === 0) {
2097
+ k = u - numBuffers + 1;
2098
+ for (l = bufferPadding; l < ll; k += width, l++) {
2099
+ for (b = 0; b < numBuffers; b++) {
2100
+ items[k + b] = colBuffers[b][l];
2101
+ }
2102
+ }
2103
+ }
2104
+ }
2105
+ }
2106
+
2107
+ return {
2108
+ width: width,
2109
+ height: height,
2110
+ items: items
2111
+ };
2112
+ };
2113
+ return Transform;
2114
+ })();
2115
+
2116
+ // Section 3.8.2 Irreversible 9-7 filter
2117
+ var IrreversibleTransform = (function IrreversibleTransformClosure() {
2118
+ function IrreversibleTransform() {
2119
+ Transform.call(this);
2120
+ }
2121
+
2122
+ IrreversibleTransform.prototype = Object.create(Transform.prototype);
2123
+ IrreversibleTransform.prototype.filter =
2124
+ function irreversibleTransformFilter(x, offset, length) {
2125
+ var len = length >> 1;
2126
+ offset = offset | 0;
2127
+ var j, n, current, next;
2128
+
2129
+ var alpha = -1.586134342059924;
2130
+ var beta = -0.052980118572961;
2131
+ var gamma = 0.882911075530934;
2132
+ var delta = 0.443506852043971;
2133
+ var K = 1.230174104914001;
2134
+ var K_ = 1 / K;
2135
+
2136
+ // step 1 is combined with step 3
2137
+
2138
+ // step 2
2139
+ j = offset - 3;
2140
+ for (n = len + 4; n--; j += 2) {
2141
+ x[j] *= K_;
2142
+ }
2143
+
2144
+ // step 1 & 3
2145
+ j = offset - 2;
2146
+ current = delta * x[j -1];
2147
+ for (n = len + 3; n--; j += 2) {
2148
+ next = delta * x[j + 1];
2149
+ x[j] = K * x[j] - current - next;
2150
+ if (n--) {
2151
+ j += 2;
2152
+ current = delta * x[j + 1];
2153
+ x[j] = K * x[j] - current - next;
2154
+ } else {
2155
+ break;
2156
+ }
2157
+ }
2158
+
2159
+ // step 4
2160
+ j = offset - 1;
2161
+ current = gamma * x[j - 1];
2162
+ for (n = len + 2; n--; j += 2) {
2163
+ next = gamma * x[j + 1];
2164
+ x[j] -= current + next;
2165
+ if (n--) {
2166
+ j += 2;
2167
+ current = gamma * x[j + 1];
2168
+ x[j] -= current + next;
2169
+ } else {
2170
+ break;
2171
+ }
2172
+ }
2173
+
2174
+ // step 5
2175
+ j = offset;
2176
+ current = beta * x[j - 1];
2177
+ for (n = len + 1; n--; j += 2) {
2178
+ next = beta * x[j + 1];
2179
+ x[j] -= current + next;
2180
+ if (n--) {
2181
+ j += 2;
2182
+ current = beta * x[j + 1];
2183
+ x[j] -= current + next;
2184
+ } else {
2185
+ break;
2186
+ }
2187
+ }
2188
+
2189
+ // step 6
2190
+ if (len !== 0) {
2191
+ j = offset + 1;
2192
+ current = alpha * x[j - 1];
2193
+ for (n = len; n--; j += 2) {
2194
+ next = alpha * x[j + 1];
2195
+ x[j] -= current + next;
2196
+ if (n--) {
2197
+ j += 2;
2198
+ current = alpha * x[j + 1];
2199
+ x[j] -= current + next;
2200
+ } else {
2201
+ break;
2202
+ }
2203
+ }
2204
+ }
2205
+ };
2206
+
2207
+ return IrreversibleTransform;
2208
+ })();
2209
+
2210
+ // Section 3.8.1 Reversible 5-3 filter
2211
+ var ReversibleTransform = (function ReversibleTransformClosure() {
2212
+ function ReversibleTransform() {
2213
+ Transform.call(this);
2214
+ }
2215
+
2216
+ ReversibleTransform.prototype = Object.create(Transform.prototype);
2217
+ ReversibleTransform.prototype.filter =
2218
+ function reversibleTransformFilter(x, offset, length) {
2219
+ var len = length >> 1;
2220
+ offset = offset | 0;
2221
+ var j, n;
2222
+
2223
+ for (j = offset, n = len + 1; n--; j += 2) {
2224
+ x[j] -= (x[j - 1] + x[j + 1] + 2) >> 2;
2225
+ }
2226
+
2227
+ for (j = offset + 1, n = len; n--; j += 2) {
2228
+ x[j] += (x[j - 1] + x[j + 1]) >> 1;
2229
+ }
2230
+ };
2231
+
2232
+ return ReversibleTransform;
2233
+ })();
2234
+
2235
+ return JpxImage;
2236
+ })();
2237
+