jpx.js 72 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942
  1. /**
  2. * @licstart The following is the entire license notice for the
  3. * Javascript code in this page
  4. *
  5. * Copyright 2017 Mozilla Foundation
  6. *
  7. * Licensed under the Apache License, Version 2.0 (the "License");
  8. * you may not use this file except in compliance with the License.
  9. * You may obtain a copy of the License at
  10. *
  11. * http://www.apache.org/licenses/LICENSE-2.0
  12. *
  13. * Unless required by applicable law or agreed to in writing, software
  14. * distributed under the License is distributed on an "AS IS" BASIS,
  15. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  16. * See the License for the specific language governing permissions and
  17. * limitations under the License.
  18. *
  19. * @licend The above is the entire license notice for the
  20. * Javascript code in this page
  21. */
  22. 'use strict';
  23. Object.defineProperty(exports, "__esModule", {
  24. value: true
  25. });
  26. exports.JpxImage = undefined;
  27. var _util = require('../shared/util');
  28. var _arithmetic_decoder = require('./arithmetic_decoder');
  29. var JpxError = function JpxErrorClosure() {
  30. function JpxError(msg) {
  31. this.message = 'JPX error: ' + msg;
  32. }
  33. JpxError.prototype = new Error();
  34. JpxError.prototype.name = 'JpxError';
  35. JpxError.constructor = JpxError;
  36. return JpxError;
  37. }();
  38. var JpxImage = function JpxImageClosure() {
  39. var SubbandsGainLog2 = {
  40. 'LL': 0,
  41. 'LH': 1,
  42. 'HL': 1,
  43. 'HH': 2
  44. };
  45. function JpxImage() {
  46. this.failOnCorruptedImage = false;
  47. }
  48. JpxImage.prototype = {
  49. parse: function JpxImage_parse(data) {
  50. var head = (0, _util.readUint16)(data, 0);
  51. if (head === 0xFF4F) {
  52. this.parseCodestream(data, 0, data.length);
  53. return;
  54. }
  55. var position = 0,
  56. length = data.length;
  57. while (position < length) {
  58. var headerSize = 8;
  59. var lbox = (0, _util.readUint32)(data, position);
  60. var tbox = (0, _util.readUint32)(data, position + 4);
  61. position += headerSize;
  62. if (lbox === 1) {
  63. lbox = (0, _util.readUint32)(data, position) * 4294967296 + (0, _util.readUint32)(data, position + 4);
  64. position += 8;
  65. headerSize += 8;
  66. }
  67. if (lbox === 0) {
  68. lbox = length - position + headerSize;
  69. }
  70. if (lbox < headerSize) {
  71. throw new JpxError('Invalid box field size');
  72. }
  73. var dataLength = lbox - headerSize;
  74. var jumpDataLength = true;
  75. switch (tbox) {
  76. case 0x6A703268:
  77. jumpDataLength = false;
  78. break;
  79. case 0x636F6C72:
  80. var method = data[position];
  81. if (method === 1) {
  82. var colorspace = (0, _util.readUint32)(data, position + 3);
  83. switch (colorspace) {
  84. case 16:
  85. case 17:
  86. case 18:
  87. break;
  88. default:
  89. (0, _util.warn)('Unknown colorspace ' + colorspace);
  90. break;
  91. }
  92. } else if (method === 2) {
  93. (0, _util.info)('ICC profile not supported');
  94. }
  95. break;
  96. case 0x6A703263:
  97. this.parseCodestream(data, position, position + dataLength);
  98. break;
  99. case 0x6A502020:
  100. if ((0, _util.readUint32)(data, position) !== 0x0d0a870a) {
  101. (0, _util.warn)('Invalid JP2 signature');
  102. }
  103. break;
  104. case 0x6A501A1A:
  105. case 0x66747970:
  106. case 0x72726571:
  107. case 0x72657320:
  108. case 0x69686472:
  109. break;
  110. default:
  111. var headerType = String.fromCharCode(tbox >> 24 & 0xFF, tbox >> 16 & 0xFF, tbox >> 8 & 0xFF, tbox & 0xFF);
  112. (0, _util.warn)('Unsupported header type ' + tbox + ' (' + headerType + ')');
  113. break;
  114. }
  115. if (jumpDataLength) {
  116. position += dataLength;
  117. }
  118. }
  119. },
  120. parseImageProperties: function JpxImage_parseImageProperties(stream) {
  121. var newByte = stream.getByte();
  122. while (newByte >= 0) {
  123. var oldByte = newByte;
  124. newByte = stream.getByte();
  125. var code = oldByte << 8 | newByte;
  126. if (code === 0xFF51) {
  127. stream.skip(4);
  128. var Xsiz = stream.getInt32() >>> 0;
  129. var Ysiz = stream.getInt32() >>> 0;
  130. var XOsiz = stream.getInt32() >>> 0;
  131. var YOsiz = stream.getInt32() >>> 0;
  132. stream.skip(16);
  133. var Csiz = stream.getUint16();
  134. this.width = Xsiz - XOsiz;
  135. this.height = Ysiz - YOsiz;
  136. this.componentsCount = Csiz;
  137. this.bitsPerComponent = 8;
  138. return;
  139. }
  140. }
  141. throw new JpxError('No size marker found in JPX stream');
  142. },
  143. parseCodestream: function JpxImage_parseCodestream(data, start, end) {
  144. var context = {};
  145. var doNotRecover = false;
  146. try {
  147. var position = start;
  148. while (position + 1 < end) {
  149. var code = (0, _util.readUint16)(data, position);
  150. position += 2;
  151. var length = 0,
  152. j,
  153. sqcd,
  154. spqcds,
  155. spqcdSize,
  156. scalarExpounded,
  157. tile;
  158. switch (code) {
  159. case 0xFF4F:
  160. context.mainHeader = true;
  161. break;
  162. case 0xFFD9:
  163. break;
  164. case 0xFF51:
  165. length = (0, _util.readUint16)(data, position);
  166. var siz = {};
  167. siz.Xsiz = (0, _util.readUint32)(data, position + 4);
  168. siz.Ysiz = (0, _util.readUint32)(data, position + 8);
  169. siz.XOsiz = (0, _util.readUint32)(data, position + 12);
  170. siz.YOsiz = (0, _util.readUint32)(data, position + 16);
  171. siz.XTsiz = (0, _util.readUint32)(data, position + 20);
  172. siz.YTsiz = (0, _util.readUint32)(data, position + 24);
  173. siz.XTOsiz = (0, _util.readUint32)(data, position + 28);
  174. siz.YTOsiz = (0, _util.readUint32)(data, position + 32);
  175. var componentsCount = (0, _util.readUint16)(data, position + 36);
  176. siz.Csiz = componentsCount;
  177. var components = [];
  178. j = position + 38;
  179. for (var i = 0; i < componentsCount; i++) {
  180. var component = {
  181. precision: (data[j] & 0x7F) + 1,
  182. isSigned: !!(data[j] & 0x80),
  183. XRsiz: data[j + 1],
  184. YRsiz: data[j + 1]
  185. };
  186. calculateComponentDimensions(component, siz);
  187. components.push(component);
  188. }
  189. context.SIZ = siz;
  190. context.components = components;
  191. calculateTileGrids(context, components);
  192. context.QCC = [];
  193. context.COC = [];
  194. break;
  195. case 0xFF5C:
  196. length = (0, _util.readUint16)(data, position);
  197. var qcd = {};
  198. j = position + 2;
  199. sqcd = data[j++];
  200. switch (sqcd & 0x1F) {
  201. case 0:
  202. spqcdSize = 8;
  203. scalarExpounded = true;
  204. break;
  205. case 1:
  206. spqcdSize = 16;
  207. scalarExpounded = false;
  208. break;
  209. case 2:
  210. spqcdSize = 16;
  211. scalarExpounded = true;
  212. break;
  213. default:
  214. throw new Error('Invalid SQcd value ' + sqcd);
  215. }
  216. qcd.noQuantization = spqcdSize === 8;
  217. qcd.scalarExpounded = scalarExpounded;
  218. qcd.guardBits = sqcd >> 5;
  219. spqcds = [];
  220. while (j < length + position) {
  221. var spqcd = {};
  222. if (spqcdSize === 8) {
  223. spqcd.epsilon = data[j++] >> 3;
  224. spqcd.mu = 0;
  225. } else {
  226. spqcd.epsilon = data[j] >> 3;
  227. spqcd.mu = (data[j] & 0x7) << 8 | data[j + 1];
  228. j += 2;
  229. }
  230. spqcds.push(spqcd);
  231. }
  232. qcd.SPqcds = spqcds;
  233. if (context.mainHeader) {
  234. context.QCD = qcd;
  235. } else {
  236. context.currentTile.QCD = qcd;
  237. context.currentTile.QCC = [];
  238. }
  239. break;
  240. case 0xFF5D:
  241. length = (0, _util.readUint16)(data, position);
  242. var qcc = {};
  243. j = position + 2;
  244. var cqcc;
  245. if (context.SIZ.Csiz < 257) {
  246. cqcc = data[j++];
  247. } else {
  248. cqcc = (0, _util.readUint16)(data, j);
  249. j += 2;
  250. }
  251. sqcd = data[j++];
  252. switch (sqcd & 0x1F) {
  253. case 0:
  254. spqcdSize = 8;
  255. scalarExpounded = true;
  256. break;
  257. case 1:
  258. spqcdSize = 16;
  259. scalarExpounded = false;
  260. break;
  261. case 2:
  262. spqcdSize = 16;
  263. scalarExpounded = true;
  264. break;
  265. default:
  266. throw new Error('Invalid SQcd value ' + sqcd);
  267. }
  268. qcc.noQuantization = spqcdSize === 8;
  269. qcc.scalarExpounded = scalarExpounded;
  270. qcc.guardBits = sqcd >> 5;
  271. spqcds = [];
  272. while (j < length + position) {
  273. spqcd = {};
  274. if (spqcdSize === 8) {
  275. spqcd.epsilon = data[j++] >> 3;
  276. spqcd.mu = 0;
  277. } else {
  278. spqcd.epsilon = data[j] >> 3;
  279. spqcd.mu = (data[j] & 0x7) << 8 | data[j + 1];
  280. j += 2;
  281. }
  282. spqcds.push(spqcd);
  283. }
  284. qcc.SPqcds = spqcds;
  285. if (context.mainHeader) {
  286. context.QCC[cqcc] = qcc;
  287. } else {
  288. context.currentTile.QCC[cqcc] = qcc;
  289. }
  290. break;
  291. case 0xFF52:
  292. length = (0, _util.readUint16)(data, position);
  293. var cod = {};
  294. j = position + 2;
  295. var scod = data[j++];
  296. cod.entropyCoderWithCustomPrecincts = !!(scod & 1);
  297. cod.sopMarkerUsed = !!(scod & 2);
  298. cod.ephMarkerUsed = !!(scod & 4);
  299. cod.progressionOrder = data[j++];
  300. cod.layersCount = (0, _util.readUint16)(data, j);
  301. j += 2;
  302. cod.multipleComponentTransform = data[j++];
  303. cod.decompositionLevelsCount = data[j++];
  304. cod.xcb = (data[j++] & 0xF) + 2;
  305. cod.ycb = (data[j++] & 0xF) + 2;
  306. var blockStyle = data[j++];
  307. cod.selectiveArithmeticCodingBypass = !!(blockStyle & 1);
  308. cod.resetContextProbabilities = !!(blockStyle & 2);
  309. cod.terminationOnEachCodingPass = !!(blockStyle & 4);
  310. cod.verticalyStripe = !!(blockStyle & 8);
  311. cod.predictableTermination = !!(blockStyle & 16);
  312. cod.segmentationSymbolUsed = !!(blockStyle & 32);
  313. cod.reversibleTransformation = data[j++];
  314. if (cod.entropyCoderWithCustomPrecincts) {
  315. var precinctsSizes = [];
  316. while (j < length + position) {
  317. var precinctsSize = data[j++];
  318. precinctsSizes.push({
  319. PPx: precinctsSize & 0xF,
  320. PPy: precinctsSize >> 4
  321. });
  322. }
  323. cod.precinctsSizes = precinctsSizes;
  324. }
  325. var unsupported = [];
  326. if (cod.selectiveArithmeticCodingBypass) {
  327. unsupported.push('selectiveArithmeticCodingBypass');
  328. }
  329. if (cod.resetContextProbabilities) {
  330. unsupported.push('resetContextProbabilities');
  331. }
  332. if (cod.terminationOnEachCodingPass) {
  333. unsupported.push('terminationOnEachCodingPass');
  334. }
  335. if (cod.verticalyStripe) {
  336. unsupported.push('verticalyStripe');
  337. }
  338. if (cod.predictableTermination) {
  339. unsupported.push('predictableTermination');
  340. }
  341. if (unsupported.length > 0) {
  342. doNotRecover = true;
  343. throw new Error('Unsupported COD options (' + unsupported.join(', ') + ')');
  344. }
  345. if (context.mainHeader) {
  346. context.COD = cod;
  347. } else {
  348. context.currentTile.COD = cod;
  349. context.currentTile.COC = [];
  350. }
  351. break;
  352. case 0xFF90:
  353. length = (0, _util.readUint16)(data, position);
  354. tile = {};
  355. tile.index = (0, _util.readUint16)(data, position + 2);
  356. tile.length = (0, _util.readUint32)(data, position + 4);
  357. tile.dataEnd = tile.length + position - 2;
  358. tile.partIndex = data[position + 8];
  359. tile.partsCount = data[position + 9];
  360. context.mainHeader = false;
  361. if (tile.partIndex === 0) {
  362. tile.COD = context.COD;
  363. tile.COC = context.COC.slice(0);
  364. tile.QCD = context.QCD;
  365. tile.QCC = context.QCC.slice(0);
  366. }
  367. context.currentTile = tile;
  368. break;
  369. case 0xFF93:
  370. tile = context.currentTile;
  371. if (tile.partIndex === 0) {
  372. initializeTile(context, tile.index);
  373. buildPackets(context);
  374. }
  375. length = tile.dataEnd - position;
  376. parseTilePackets(context, data, position, length);
  377. break;
  378. case 0xFF55:
  379. case 0xFF57:
  380. case 0xFF58:
  381. case 0xFF64:
  382. length = (0, _util.readUint16)(data, position);
  383. break;
  384. case 0xFF53:
  385. throw new Error('Codestream code 0xFF53 (COC) is ' + 'not implemented');
  386. default:
  387. throw new Error('Unknown codestream code: ' + code.toString(16));
  388. }
  389. position += length;
  390. }
  391. } catch (e) {
  392. if (doNotRecover || this.failOnCorruptedImage) {
  393. throw new JpxError(e.message);
  394. } else {
  395. (0, _util.warn)('JPX: Trying to recover from: ' + e.message);
  396. }
  397. }
  398. this.tiles = transformComponents(context);
  399. this.width = context.SIZ.Xsiz - context.SIZ.XOsiz;
  400. this.height = context.SIZ.Ysiz - context.SIZ.YOsiz;
  401. this.componentsCount = context.SIZ.Csiz;
  402. }
  403. };
  404. function calculateComponentDimensions(component, siz) {
  405. component.x0 = Math.ceil(siz.XOsiz / component.XRsiz);
  406. component.x1 = Math.ceil(siz.Xsiz / component.XRsiz);
  407. component.y0 = Math.ceil(siz.YOsiz / component.YRsiz);
  408. component.y1 = Math.ceil(siz.Ysiz / component.YRsiz);
  409. component.width = component.x1 - component.x0;
  410. component.height = component.y1 - component.y0;
  411. }
  412. function calculateTileGrids(context, components) {
  413. var siz = context.SIZ;
  414. var tile,
  415. tiles = [];
  416. var numXtiles = Math.ceil((siz.Xsiz - siz.XTOsiz) / siz.XTsiz);
  417. var numYtiles = Math.ceil((siz.Ysiz - siz.YTOsiz) / siz.YTsiz);
  418. for (var q = 0; q < numYtiles; q++) {
  419. for (var p = 0; p < numXtiles; p++) {
  420. tile = {};
  421. tile.tx0 = Math.max(siz.XTOsiz + p * siz.XTsiz, siz.XOsiz);
  422. tile.ty0 = Math.max(siz.YTOsiz + q * siz.YTsiz, siz.YOsiz);
  423. tile.tx1 = Math.min(siz.XTOsiz + (p + 1) * siz.XTsiz, siz.Xsiz);
  424. tile.ty1 = Math.min(siz.YTOsiz + (q + 1) * siz.YTsiz, siz.Ysiz);
  425. tile.width = tile.tx1 - tile.tx0;
  426. tile.height = tile.ty1 - tile.ty0;
  427. tile.components = [];
  428. tiles.push(tile);
  429. }
  430. }
  431. context.tiles = tiles;
  432. var componentsCount = siz.Csiz;
  433. for (var i = 0, ii = componentsCount; i < ii; i++) {
  434. var component = components[i];
  435. for (var j = 0, jj = tiles.length; j < jj; j++) {
  436. var tileComponent = {};
  437. tile = tiles[j];
  438. tileComponent.tcx0 = Math.ceil(tile.tx0 / component.XRsiz);
  439. tileComponent.tcy0 = Math.ceil(tile.ty0 / component.YRsiz);
  440. tileComponent.tcx1 = Math.ceil(tile.tx1 / component.XRsiz);
  441. tileComponent.tcy1 = Math.ceil(tile.ty1 / component.YRsiz);
  442. tileComponent.width = tileComponent.tcx1 - tileComponent.tcx0;
  443. tileComponent.height = tileComponent.tcy1 - tileComponent.tcy0;
  444. tile.components[i] = tileComponent;
  445. }
  446. }
  447. }
  448. function getBlocksDimensions(context, component, r) {
  449. var codOrCoc = component.codingStyleParameters;
  450. var result = {};
  451. if (!codOrCoc.entropyCoderWithCustomPrecincts) {
  452. result.PPx = 15;
  453. result.PPy = 15;
  454. } else {
  455. result.PPx = codOrCoc.precinctsSizes[r].PPx;
  456. result.PPy = codOrCoc.precinctsSizes[r].PPy;
  457. }
  458. result.xcb_ = r > 0 ? Math.min(codOrCoc.xcb, result.PPx - 1) : Math.min(codOrCoc.xcb, result.PPx);
  459. result.ycb_ = r > 0 ? Math.min(codOrCoc.ycb, result.PPy - 1) : Math.min(codOrCoc.ycb, result.PPy);
  460. return result;
  461. }
  462. function buildPrecincts(context, resolution, dimensions) {
  463. var precinctWidth = 1 << dimensions.PPx;
  464. var precinctHeight = 1 << dimensions.PPy;
  465. var isZeroRes = resolution.resLevel === 0;
  466. var precinctWidthInSubband = 1 << dimensions.PPx + (isZeroRes ? 0 : -1);
  467. var precinctHeightInSubband = 1 << dimensions.PPy + (isZeroRes ? 0 : -1);
  468. var numprecinctswide = resolution.trx1 > resolution.trx0 ? Math.ceil(resolution.trx1 / precinctWidth) - Math.floor(resolution.trx0 / precinctWidth) : 0;
  469. var numprecinctshigh = resolution.try1 > resolution.try0 ? Math.ceil(resolution.try1 / precinctHeight) - Math.floor(resolution.try0 / precinctHeight) : 0;
  470. var numprecincts = numprecinctswide * numprecinctshigh;
  471. resolution.precinctParameters = {
  472. precinctWidth: precinctWidth,
  473. precinctHeight: precinctHeight,
  474. numprecinctswide: numprecinctswide,
  475. numprecinctshigh: numprecinctshigh,
  476. numprecincts: numprecincts,
  477. precinctWidthInSubband: precinctWidthInSubband,
  478. precinctHeightInSubband: precinctHeightInSubband
  479. };
  480. }
  481. function buildCodeblocks(context, subband, dimensions) {
  482. var xcb_ = dimensions.xcb_;
  483. var ycb_ = dimensions.ycb_;
  484. var codeblockWidth = 1 << xcb_;
  485. var codeblockHeight = 1 << ycb_;
  486. var cbx0 = subband.tbx0 >> xcb_;
  487. var cby0 = subband.tby0 >> ycb_;
  488. var cbx1 = subband.tbx1 + codeblockWidth - 1 >> xcb_;
  489. var cby1 = subband.tby1 + codeblockHeight - 1 >> ycb_;
  490. var precinctParameters = subband.resolution.precinctParameters;
  491. var codeblocks = [];
  492. var precincts = [];
  493. var i, j, codeblock, precinctNumber;
  494. for (j = cby0; j < cby1; j++) {
  495. for (i = cbx0; i < cbx1; i++) {
  496. codeblock = {
  497. cbx: i,
  498. cby: j,
  499. tbx0: codeblockWidth * i,
  500. tby0: codeblockHeight * j,
  501. tbx1: codeblockWidth * (i + 1),
  502. tby1: codeblockHeight * (j + 1)
  503. };
  504. codeblock.tbx0_ = Math.max(subband.tbx0, codeblock.tbx0);
  505. codeblock.tby0_ = Math.max(subband.tby0, codeblock.tby0);
  506. codeblock.tbx1_ = Math.min(subband.tbx1, codeblock.tbx1);
  507. codeblock.tby1_ = Math.min(subband.tby1, codeblock.tby1);
  508. var pi = Math.floor((codeblock.tbx0_ - subband.tbx0) / precinctParameters.precinctWidthInSubband);
  509. var pj = Math.floor((codeblock.tby0_ - subband.tby0) / precinctParameters.precinctHeightInSubband);
  510. precinctNumber = pi + pj * precinctParameters.numprecinctswide;
  511. codeblock.precinctNumber = precinctNumber;
  512. codeblock.subbandType = subband.type;
  513. codeblock.Lblock = 3;
  514. if (codeblock.tbx1_ <= codeblock.tbx0_ || codeblock.tby1_ <= codeblock.tby0_) {
  515. continue;
  516. }
  517. codeblocks.push(codeblock);
  518. var precinct = precincts[precinctNumber];
  519. if (precinct !== undefined) {
  520. if (i < precinct.cbxMin) {
  521. precinct.cbxMin = i;
  522. } else if (i > precinct.cbxMax) {
  523. precinct.cbxMax = i;
  524. }
  525. if (j < precinct.cbyMin) {
  526. precinct.cbxMin = j;
  527. } else if (j > precinct.cbyMax) {
  528. precinct.cbyMax = j;
  529. }
  530. } else {
  531. precincts[precinctNumber] = precinct = {
  532. cbxMin: i,
  533. cbyMin: j,
  534. cbxMax: i,
  535. cbyMax: j
  536. };
  537. }
  538. codeblock.precinct = precinct;
  539. }
  540. }
  541. subband.codeblockParameters = {
  542. codeblockWidth: xcb_,
  543. codeblockHeight: ycb_,
  544. numcodeblockwide: cbx1 - cbx0 + 1,
  545. numcodeblockhigh: cby1 - cby0 + 1
  546. };
  547. subband.codeblocks = codeblocks;
  548. subband.precincts = precincts;
  549. }
  550. function createPacket(resolution, precinctNumber, layerNumber) {
  551. var precinctCodeblocks = [];
  552. var subbands = resolution.subbands;
  553. for (var i = 0, ii = subbands.length; i < ii; i++) {
  554. var subband = subbands[i];
  555. var codeblocks = subband.codeblocks;
  556. for (var j = 0, jj = codeblocks.length; j < jj; j++) {
  557. var codeblock = codeblocks[j];
  558. if (codeblock.precinctNumber !== precinctNumber) {
  559. continue;
  560. }
  561. precinctCodeblocks.push(codeblock);
  562. }
  563. }
  564. return {
  565. layerNumber: layerNumber,
  566. codeblocks: precinctCodeblocks
  567. };
  568. }
  569. function LayerResolutionComponentPositionIterator(context) {
  570. var siz = context.SIZ;
  571. var tileIndex = context.currentTile.index;
  572. var tile = context.tiles[tileIndex];
  573. var layersCount = tile.codingStyleDefaultParameters.layersCount;
  574. var componentsCount = siz.Csiz;
  575. var maxDecompositionLevelsCount = 0;
  576. for (var q = 0; q < componentsCount; q++) {
  577. maxDecompositionLevelsCount = Math.max(maxDecompositionLevelsCount, tile.components[q].codingStyleParameters.decompositionLevelsCount);
  578. }
  579. var l = 0,
  580. r = 0,
  581. i = 0,
  582. k = 0;
  583. this.nextPacket = function JpxImage_nextPacket() {
  584. for (; l < layersCount; l++) {
  585. for (; r <= maxDecompositionLevelsCount; r++) {
  586. for (; i < componentsCount; i++) {
  587. var component = tile.components[i];
  588. if (r > component.codingStyleParameters.decompositionLevelsCount) {
  589. continue;
  590. }
  591. var resolution = component.resolutions[r];
  592. var numprecincts = resolution.precinctParameters.numprecincts;
  593. for (; k < numprecincts;) {
  594. var packet = createPacket(resolution, k, l);
  595. k++;
  596. return packet;
  597. }
  598. k = 0;
  599. }
  600. i = 0;
  601. }
  602. r = 0;
  603. }
  604. throw new JpxError('Out of packets');
  605. };
  606. }
  607. function ResolutionLayerComponentPositionIterator(context) {
  608. var siz = context.SIZ;
  609. var tileIndex = context.currentTile.index;
  610. var tile = context.tiles[tileIndex];
  611. var layersCount = tile.codingStyleDefaultParameters.layersCount;
  612. var componentsCount = siz.Csiz;
  613. var maxDecompositionLevelsCount = 0;
  614. for (var q = 0; q < componentsCount; q++) {
  615. maxDecompositionLevelsCount = Math.max(maxDecompositionLevelsCount, tile.components[q].codingStyleParameters.decompositionLevelsCount);
  616. }
  617. var r = 0,
  618. l = 0,
  619. i = 0,
  620. k = 0;
  621. this.nextPacket = function JpxImage_nextPacket() {
  622. for (; r <= maxDecompositionLevelsCount; r++) {
  623. for (; l < layersCount; l++) {
  624. for (; i < componentsCount; i++) {
  625. var component = tile.components[i];
  626. if (r > component.codingStyleParameters.decompositionLevelsCount) {
  627. continue;
  628. }
  629. var resolution = component.resolutions[r];
  630. var numprecincts = resolution.precinctParameters.numprecincts;
  631. for (; k < numprecincts;) {
  632. var packet = createPacket(resolution, k, l);
  633. k++;
  634. return packet;
  635. }
  636. k = 0;
  637. }
  638. i = 0;
  639. }
  640. l = 0;
  641. }
  642. throw new JpxError('Out of packets');
  643. };
  644. }
  645. function ResolutionPositionComponentLayerIterator(context) {
  646. var siz = context.SIZ;
  647. var tileIndex = context.currentTile.index;
  648. var tile = context.tiles[tileIndex];
  649. var layersCount = tile.codingStyleDefaultParameters.layersCount;
  650. var componentsCount = siz.Csiz;
  651. var l, r, c, p;
  652. var maxDecompositionLevelsCount = 0;
  653. for (c = 0; c < componentsCount; c++) {
  654. var component = tile.components[c];
  655. maxDecompositionLevelsCount = Math.max(maxDecompositionLevelsCount, component.codingStyleParameters.decompositionLevelsCount);
  656. }
  657. var maxNumPrecinctsInLevel = new Int32Array(maxDecompositionLevelsCount + 1);
  658. for (r = 0; r <= maxDecompositionLevelsCount; ++r) {
  659. var maxNumPrecincts = 0;
  660. for (c = 0; c < componentsCount; ++c) {
  661. var resolutions = tile.components[c].resolutions;
  662. if (r < resolutions.length) {
  663. maxNumPrecincts = Math.max(maxNumPrecincts, resolutions[r].precinctParameters.numprecincts);
  664. }
  665. }
  666. maxNumPrecinctsInLevel[r] = maxNumPrecincts;
  667. }
  668. l = 0;
  669. r = 0;
  670. c = 0;
  671. p = 0;
  672. this.nextPacket = function JpxImage_nextPacket() {
  673. for (; r <= maxDecompositionLevelsCount; r++) {
  674. for (; p < maxNumPrecinctsInLevel[r]; p++) {
  675. for (; c < componentsCount; c++) {
  676. var component = tile.components[c];
  677. if (r > component.codingStyleParameters.decompositionLevelsCount) {
  678. continue;
  679. }
  680. var resolution = component.resolutions[r];
  681. var numprecincts = resolution.precinctParameters.numprecincts;
  682. if (p >= numprecincts) {
  683. continue;
  684. }
  685. for (; l < layersCount;) {
  686. var packet = createPacket(resolution, p, l);
  687. l++;
  688. return packet;
  689. }
  690. l = 0;
  691. }
  692. c = 0;
  693. }
  694. p = 0;
  695. }
  696. throw new JpxError('Out of packets');
  697. };
  698. }
  699. function PositionComponentResolutionLayerIterator(context) {
  700. var siz = context.SIZ;
  701. var tileIndex = context.currentTile.index;
  702. var tile = context.tiles[tileIndex];
  703. var layersCount = tile.codingStyleDefaultParameters.layersCount;
  704. var componentsCount = siz.Csiz;
  705. var precinctsSizes = getPrecinctSizesInImageScale(tile);
  706. var precinctsIterationSizes = precinctsSizes;
  707. var l = 0,
  708. r = 0,
  709. c = 0,
  710. px = 0,
  711. py = 0;
  712. this.nextPacket = function JpxImage_nextPacket() {
  713. for (; py < precinctsIterationSizes.maxNumHigh; py++) {
  714. for (; px < precinctsIterationSizes.maxNumWide; px++) {
  715. for (; c < componentsCount; c++) {
  716. var component = tile.components[c];
  717. var decompositionLevelsCount = component.codingStyleParameters.decompositionLevelsCount;
  718. for (; r <= decompositionLevelsCount; r++) {
  719. var resolution = component.resolutions[r];
  720. var sizeInImageScale = precinctsSizes.components[c].resolutions[r];
  721. var k = getPrecinctIndexIfExist(px, py, sizeInImageScale, precinctsIterationSizes, resolution);
  722. if (k === null) {
  723. continue;
  724. }
  725. for (; l < layersCount;) {
  726. var packet = createPacket(resolution, k, l);
  727. l++;
  728. return packet;
  729. }
  730. l = 0;
  731. }
  732. r = 0;
  733. }
  734. c = 0;
  735. }
  736. px = 0;
  737. }
  738. throw new JpxError('Out of packets');
  739. };
  740. }
  741. function ComponentPositionResolutionLayerIterator(context) {
  742. var siz = context.SIZ;
  743. var tileIndex = context.currentTile.index;
  744. var tile = context.tiles[tileIndex];
  745. var layersCount = tile.codingStyleDefaultParameters.layersCount;
  746. var componentsCount = siz.Csiz;
  747. var precinctsSizes = getPrecinctSizesInImageScale(tile);
  748. var l = 0,
  749. r = 0,
  750. c = 0,
  751. px = 0,
  752. py = 0;
  753. this.nextPacket = function JpxImage_nextPacket() {
  754. for (; c < componentsCount; ++c) {
  755. var component = tile.components[c];
  756. var precinctsIterationSizes = precinctsSizes.components[c];
  757. var decompositionLevelsCount = component.codingStyleParameters.decompositionLevelsCount;
  758. for (; py < precinctsIterationSizes.maxNumHigh; py++) {
  759. for (; px < precinctsIterationSizes.maxNumWide; px++) {
  760. for (; r <= decompositionLevelsCount; r++) {
  761. var resolution = component.resolutions[r];
  762. var sizeInImageScale = precinctsIterationSizes.resolutions[r];
  763. var k = getPrecinctIndexIfExist(px, py, sizeInImageScale, precinctsIterationSizes, resolution);
  764. if (k === null) {
  765. continue;
  766. }
  767. for (; l < layersCount;) {
  768. var packet = createPacket(resolution, k, l);
  769. l++;
  770. return packet;
  771. }
  772. l = 0;
  773. }
  774. r = 0;
  775. }
  776. px = 0;
  777. }
  778. py = 0;
  779. }
  780. throw new JpxError('Out of packets');
  781. };
  782. }
  783. function getPrecinctIndexIfExist(pxIndex, pyIndex, sizeInImageScale, precinctIterationSizes, resolution) {
  784. var posX = pxIndex * precinctIterationSizes.minWidth;
  785. var posY = pyIndex * precinctIterationSizes.minHeight;
  786. if (posX % sizeInImageScale.width !== 0 || posY % sizeInImageScale.height !== 0) {
  787. return null;
  788. }
  789. var startPrecinctRowIndex = posY / sizeInImageScale.width * resolution.precinctParameters.numprecinctswide;
  790. return posX / sizeInImageScale.height + startPrecinctRowIndex;
  791. }
  792. function getPrecinctSizesInImageScale(tile) {
  793. var componentsCount = tile.components.length;
  794. var minWidth = Number.MAX_VALUE;
  795. var minHeight = Number.MAX_VALUE;
  796. var maxNumWide = 0;
  797. var maxNumHigh = 0;
  798. var sizePerComponent = new Array(componentsCount);
  799. for (var c = 0; c < componentsCount; c++) {
  800. var component = tile.components[c];
  801. var decompositionLevelsCount = component.codingStyleParameters.decompositionLevelsCount;
  802. var sizePerResolution = new Array(decompositionLevelsCount + 1);
  803. var minWidthCurrentComponent = Number.MAX_VALUE;
  804. var minHeightCurrentComponent = Number.MAX_VALUE;
  805. var maxNumWideCurrentComponent = 0;
  806. var maxNumHighCurrentComponent = 0;
  807. var scale = 1;
  808. for (var r = decompositionLevelsCount; r >= 0; --r) {
  809. var resolution = component.resolutions[r];
  810. var widthCurrentResolution = scale * resolution.precinctParameters.precinctWidth;
  811. var heightCurrentResolution = scale * resolution.precinctParameters.precinctHeight;
  812. minWidthCurrentComponent = Math.min(minWidthCurrentComponent, widthCurrentResolution);
  813. minHeightCurrentComponent = Math.min(minHeightCurrentComponent, heightCurrentResolution);
  814. maxNumWideCurrentComponent = Math.max(maxNumWideCurrentComponent, resolution.precinctParameters.numprecinctswide);
  815. maxNumHighCurrentComponent = Math.max(maxNumHighCurrentComponent, resolution.precinctParameters.numprecinctshigh);
  816. sizePerResolution[r] = {
  817. width: widthCurrentResolution,
  818. height: heightCurrentResolution
  819. };
  820. scale <<= 1;
  821. }
  822. minWidth = Math.min(minWidth, minWidthCurrentComponent);
  823. minHeight = Math.min(minHeight, minHeightCurrentComponent);
  824. maxNumWide = Math.max(maxNumWide, maxNumWideCurrentComponent);
  825. maxNumHigh = Math.max(maxNumHigh, maxNumHighCurrentComponent);
  826. sizePerComponent[c] = {
  827. resolutions: sizePerResolution,
  828. minWidth: minWidthCurrentComponent,
  829. minHeight: minHeightCurrentComponent,
  830. maxNumWide: maxNumWideCurrentComponent,
  831. maxNumHigh: maxNumHighCurrentComponent
  832. };
  833. }
  834. return {
  835. components: sizePerComponent,
  836. minWidth: minWidth,
  837. minHeight: minHeight,
  838. maxNumWide: maxNumWide,
  839. maxNumHigh: maxNumHigh
  840. };
  841. }
  842. function buildPackets(context) {
  843. var siz = context.SIZ;
  844. var tileIndex = context.currentTile.index;
  845. var tile = context.tiles[tileIndex];
  846. var componentsCount = siz.Csiz;
  847. for (var c = 0; c < componentsCount; c++) {
  848. var component = tile.components[c];
  849. var decompositionLevelsCount = component.codingStyleParameters.decompositionLevelsCount;
  850. var resolutions = [];
  851. var subbands = [];
  852. for (var r = 0; r <= decompositionLevelsCount; r++) {
  853. var blocksDimensions = getBlocksDimensions(context, component, r);
  854. var resolution = {};
  855. var scale = 1 << decompositionLevelsCount - r;
  856. resolution.trx0 = Math.ceil(component.tcx0 / scale);
  857. resolution.try0 = Math.ceil(component.tcy0 / scale);
  858. resolution.trx1 = Math.ceil(component.tcx1 / scale);
  859. resolution.try1 = Math.ceil(component.tcy1 / scale);
  860. resolution.resLevel = r;
  861. buildPrecincts(context, resolution, blocksDimensions);
  862. resolutions.push(resolution);
  863. var subband;
  864. if (r === 0) {
  865. subband = {};
  866. subband.type = 'LL';
  867. subband.tbx0 = Math.ceil(component.tcx0 / scale);
  868. subband.tby0 = Math.ceil(component.tcy0 / scale);
  869. subband.tbx1 = Math.ceil(component.tcx1 / scale);
  870. subband.tby1 = Math.ceil(component.tcy1 / scale);
  871. subband.resolution = resolution;
  872. buildCodeblocks(context, subband, blocksDimensions);
  873. subbands.push(subband);
  874. resolution.subbands = [subband];
  875. } else {
  876. var bscale = 1 << decompositionLevelsCount - r + 1;
  877. var resolutionSubbands = [];
  878. subband = {};
  879. subband.type = 'HL';
  880. subband.tbx0 = Math.ceil(component.tcx0 / bscale - 0.5);
  881. subband.tby0 = Math.ceil(component.tcy0 / bscale);
  882. subband.tbx1 = Math.ceil(component.tcx1 / bscale - 0.5);
  883. subband.tby1 = Math.ceil(component.tcy1 / bscale);
  884. subband.resolution = resolution;
  885. buildCodeblocks(context, subband, blocksDimensions);
  886. subbands.push(subband);
  887. resolutionSubbands.push(subband);
  888. subband = {};
  889. subband.type = 'LH';
  890. subband.tbx0 = Math.ceil(component.tcx0 / bscale);
  891. subband.tby0 = Math.ceil(component.tcy0 / bscale - 0.5);
  892. subband.tbx1 = Math.ceil(component.tcx1 / bscale);
  893. subband.tby1 = Math.ceil(component.tcy1 / bscale - 0.5);
  894. subband.resolution = resolution;
  895. buildCodeblocks(context, subband, blocksDimensions);
  896. subbands.push(subband);
  897. resolutionSubbands.push(subband);
  898. subband = {};
  899. subband.type = 'HH';
  900. subband.tbx0 = Math.ceil(component.tcx0 / bscale - 0.5);
  901. subband.tby0 = Math.ceil(component.tcy0 / bscale - 0.5);
  902. subband.tbx1 = Math.ceil(component.tcx1 / bscale - 0.5);
  903. subband.tby1 = Math.ceil(component.tcy1 / bscale - 0.5);
  904. subband.resolution = resolution;
  905. buildCodeblocks(context, subband, blocksDimensions);
  906. subbands.push(subband);
  907. resolutionSubbands.push(subband);
  908. resolution.subbands = resolutionSubbands;
  909. }
  910. }
  911. component.resolutions = resolutions;
  912. component.subbands = subbands;
  913. }
  914. var progressionOrder = tile.codingStyleDefaultParameters.progressionOrder;
  915. switch (progressionOrder) {
  916. case 0:
  917. tile.packetsIterator = new LayerResolutionComponentPositionIterator(context);
  918. break;
  919. case 1:
  920. tile.packetsIterator = new ResolutionLayerComponentPositionIterator(context);
  921. break;
  922. case 2:
  923. tile.packetsIterator = new ResolutionPositionComponentLayerIterator(context);
  924. break;
  925. case 3:
  926. tile.packetsIterator = new PositionComponentResolutionLayerIterator(context);
  927. break;
  928. case 4:
  929. tile.packetsIterator = new ComponentPositionResolutionLayerIterator(context);
  930. break;
  931. default:
  932. throw new JpxError('Unsupported progression order ' + progressionOrder);
  933. }
  934. }
  935. function parseTilePackets(context, data, offset, dataLength) {
  936. var position = 0;
  937. var buffer,
  938. bufferSize = 0,
  939. skipNextBit = false;
  940. function readBits(count) {
  941. while (bufferSize < count) {
  942. var b = data[offset + position];
  943. position++;
  944. if (skipNextBit) {
  945. buffer = buffer << 7 | b;
  946. bufferSize += 7;
  947. skipNextBit = false;
  948. } else {
  949. buffer = buffer << 8 | b;
  950. bufferSize += 8;
  951. }
  952. if (b === 0xFF) {
  953. skipNextBit = true;
  954. }
  955. }
  956. bufferSize -= count;
  957. return buffer >>> bufferSize & (1 << count) - 1;
  958. }
  959. function skipMarkerIfEqual(value) {
  960. if (data[offset + position - 1] === 0xFF && data[offset + position] === value) {
  961. skipBytes(1);
  962. return true;
  963. } else if (data[offset + position] === 0xFF && data[offset + position + 1] === value) {
  964. skipBytes(2);
  965. return true;
  966. }
  967. return false;
  968. }
  969. function skipBytes(count) {
  970. position += count;
  971. }
  972. function alignToByte() {
  973. bufferSize = 0;
  974. if (skipNextBit) {
  975. position++;
  976. skipNextBit = false;
  977. }
  978. }
  979. function readCodingpasses() {
  980. if (readBits(1) === 0) {
  981. return 1;
  982. }
  983. if (readBits(1) === 0) {
  984. return 2;
  985. }
  986. var value = readBits(2);
  987. if (value < 3) {
  988. return value + 3;
  989. }
  990. value = readBits(5);
  991. if (value < 31) {
  992. return value + 6;
  993. }
  994. value = readBits(7);
  995. return value + 37;
  996. }
  997. var tileIndex = context.currentTile.index;
  998. var tile = context.tiles[tileIndex];
  999. var sopMarkerUsed = context.COD.sopMarkerUsed;
  1000. var ephMarkerUsed = context.COD.ephMarkerUsed;
  1001. var packetsIterator = tile.packetsIterator;
  1002. while (position < dataLength) {
  1003. alignToByte();
  1004. if (sopMarkerUsed && skipMarkerIfEqual(0x91)) {
  1005. skipBytes(4);
  1006. }
  1007. var packet = packetsIterator.nextPacket();
  1008. if (!readBits(1)) {
  1009. continue;
  1010. }
  1011. var layerNumber = packet.layerNumber;
  1012. var queue = [],
  1013. codeblock;
  1014. for (var i = 0, ii = packet.codeblocks.length; i < ii; i++) {
  1015. codeblock = packet.codeblocks[i];
  1016. var precinct = codeblock.precinct;
  1017. var codeblockColumn = codeblock.cbx - precinct.cbxMin;
  1018. var codeblockRow = codeblock.cby - precinct.cbyMin;
  1019. var codeblockIncluded = false;
  1020. var firstTimeInclusion = false;
  1021. var valueReady;
  1022. if (codeblock['included'] !== undefined) {
  1023. codeblockIncluded = !!readBits(1);
  1024. } else {
  1025. precinct = codeblock.precinct;
  1026. var inclusionTree, zeroBitPlanesTree;
  1027. if (precinct['inclusionTree'] !== undefined) {
  1028. inclusionTree = precinct.inclusionTree;
  1029. } else {
  1030. var width = precinct.cbxMax - precinct.cbxMin + 1;
  1031. var height = precinct.cbyMax - precinct.cbyMin + 1;
  1032. inclusionTree = new InclusionTree(width, height, layerNumber);
  1033. zeroBitPlanesTree = new TagTree(width, height);
  1034. precinct.inclusionTree = inclusionTree;
  1035. precinct.zeroBitPlanesTree = zeroBitPlanesTree;
  1036. }
  1037. if (inclusionTree.reset(codeblockColumn, codeblockRow, layerNumber)) {
  1038. while (true) {
  1039. if (readBits(1)) {
  1040. valueReady = !inclusionTree.nextLevel();
  1041. if (valueReady) {
  1042. codeblock.included = true;
  1043. codeblockIncluded = firstTimeInclusion = true;
  1044. break;
  1045. }
  1046. } else {
  1047. inclusionTree.incrementValue(layerNumber);
  1048. break;
  1049. }
  1050. }
  1051. }
  1052. }
  1053. if (!codeblockIncluded) {
  1054. continue;
  1055. }
  1056. if (firstTimeInclusion) {
  1057. zeroBitPlanesTree = precinct.zeroBitPlanesTree;
  1058. zeroBitPlanesTree.reset(codeblockColumn, codeblockRow);
  1059. while (true) {
  1060. if (readBits(1)) {
  1061. valueReady = !zeroBitPlanesTree.nextLevel();
  1062. if (valueReady) {
  1063. break;
  1064. }
  1065. } else {
  1066. zeroBitPlanesTree.incrementValue();
  1067. }
  1068. }
  1069. codeblock.zeroBitPlanes = zeroBitPlanesTree.value;
  1070. }
  1071. var codingpasses = readCodingpasses();
  1072. while (readBits(1)) {
  1073. codeblock.Lblock++;
  1074. }
  1075. var codingpassesLog2 = (0, _util.log2)(codingpasses);
  1076. var bits = (codingpasses < 1 << codingpassesLog2 ? codingpassesLog2 - 1 : codingpassesLog2) + codeblock.Lblock;
  1077. var codedDataLength = readBits(bits);
  1078. queue.push({
  1079. codeblock: codeblock,
  1080. codingpasses: codingpasses,
  1081. dataLength: codedDataLength
  1082. });
  1083. }
  1084. alignToByte();
  1085. if (ephMarkerUsed) {
  1086. skipMarkerIfEqual(0x92);
  1087. }
  1088. while (queue.length > 0) {
  1089. var packetItem = queue.shift();
  1090. codeblock = packetItem.codeblock;
  1091. if (codeblock['data'] === undefined) {
  1092. codeblock.data = [];
  1093. }
  1094. codeblock.data.push({
  1095. data: data,
  1096. start: offset + position,
  1097. end: offset + position + packetItem.dataLength,
  1098. codingpasses: packetItem.codingpasses
  1099. });
  1100. position += packetItem.dataLength;
  1101. }
  1102. }
  1103. return position;
  1104. }
  1105. function copyCoefficients(coefficients, levelWidth, levelHeight, subband, delta, mb, reversible, segmentationSymbolUsed) {
  1106. var x0 = subband.tbx0;
  1107. var y0 = subband.tby0;
  1108. var width = subband.tbx1 - subband.tbx0;
  1109. var codeblocks = subband.codeblocks;
  1110. var right = subband.type.charAt(0) === 'H' ? 1 : 0;
  1111. var bottom = subband.type.charAt(1) === 'H' ? levelWidth : 0;
  1112. for (var i = 0, ii = codeblocks.length; i < ii; ++i) {
  1113. var codeblock = codeblocks[i];
  1114. var blockWidth = codeblock.tbx1_ - codeblock.tbx0_;
  1115. var blockHeight = codeblock.tby1_ - codeblock.tby0_;
  1116. if (blockWidth === 0 || blockHeight === 0) {
  1117. continue;
  1118. }
  1119. if (codeblock['data'] === undefined) {
  1120. continue;
  1121. }
  1122. var bitModel, currentCodingpassType;
  1123. bitModel = new BitModel(blockWidth, blockHeight, codeblock.subbandType, codeblock.zeroBitPlanes, mb);
  1124. currentCodingpassType = 2;
  1125. var data = codeblock.data,
  1126. totalLength = 0,
  1127. codingpasses = 0;
  1128. var j, jj, dataItem;
  1129. for (j = 0, jj = data.length; j < jj; j++) {
  1130. dataItem = data[j];
  1131. totalLength += dataItem.end - dataItem.start;
  1132. codingpasses += dataItem.codingpasses;
  1133. }
  1134. var encodedData = new Uint8Array(totalLength);
  1135. var position = 0;
  1136. for (j = 0, jj = data.length; j < jj; j++) {
  1137. dataItem = data[j];
  1138. var chunk = dataItem.data.subarray(dataItem.start, dataItem.end);
  1139. encodedData.set(chunk, position);
  1140. position += chunk.length;
  1141. }
  1142. var decoder = new _arithmetic_decoder.ArithmeticDecoder(encodedData, 0, totalLength);
  1143. bitModel.setDecoder(decoder);
  1144. for (j = 0; j < codingpasses; j++) {
  1145. switch (currentCodingpassType) {
  1146. case 0:
  1147. bitModel.runSignificancePropagationPass();
  1148. break;
  1149. case 1:
  1150. bitModel.runMagnitudeRefinementPass();
  1151. break;
  1152. case 2:
  1153. bitModel.runCleanupPass();
  1154. if (segmentationSymbolUsed) {
  1155. bitModel.checkSegmentationSymbol();
  1156. }
  1157. break;
  1158. }
  1159. currentCodingpassType = (currentCodingpassType + 1) % 3;
  1160. }
  1161. var offset = codeblock.tbx0_ - x0 + (codeblock.tby0_ - y0) * width;
  1162. var sign = bitModel.coefficentsSign;
  1163. var magnitude = bitModel.coefficentsMagnitude;
  1164. var bitsDecoded = bitModel.bitsDecoded;
  1165. var magnitudeCorrection = reversible ? 0 : 0.5;
  1166. var k, n, nb;
  1167. position = 0;
  1168. var interleave = subband.type !== 'LL';
  1169. for (j = 0; j < blockHeight; j++) {
  1170. var row = offset / width | 0;
  1171. var levelOffset = 2 * row * (levelWidth - width) + right + bottom;
  1172. for (k = 0; k < blockWidth; k++) {
  1173. n = magnitude[position];
  1174. if (n !== 0) {
  1175. n = (n + magnitudeCorrection) * delta;
  1176. if (sign[position] !== 0) {
  1177. n = -n;
  1178. }
  1179. nb = bitsDecoded[position];
  1180. var pos = interleave ? levelOffset + (offset << 1) : offset;
  1181. if (reversible && nb >= mb) {
  1182. coefficients[pos] = n;
  1183. } else {
  1184. coefficients[pos] = n * (1 << mb - nb);
  1185. }
  1186. }
  1187. offset++;
  1188. position++;
  1189. }
  1190. offset += width - blockWidth;
  1191. }
  1192. }
  1193. }
  1194. function transformTile(context, tile, c) {
  1195. var component = tile.components[c];
  1196. var codingStyleParameters = component.codingStyleParameters;
  1197. var quantizationParameters = component.quantizationParameters;
  1198. var decompositionLevelsCount = codingStyleParameters.decompositionLevelsCount;
  1199. var spqcds = quantizationParameters.SPqcds;
  1200. var scalarExpounded = quantizationParameters.scalarExpounded;
  1201. var guardBits = quantizationParameters.guardBits;
  1202. var segmentationSymbolUsed = codingStyleParameters.segmentationSymbolUsed;
  1203. var precision = context.components[c].precision;
  1204. var reversible = codingStyleParameters.reversibleTransformation;
  1205. var transform = reversible ? new ReversibleTransform() : new IrreversibleTransform();
  1206. var subbandCoefficients = [];
  1207. var b = 0;
  1208. for (var i = 0; i <= decompositionLevelsCount; i++) {
  1209. var resolution = component.resolutions[i];
  1210. var width = resolution.trx1 - resolution.trx0;
  1211. var height = resolution.try1 - resolution.try0;
  1212. var coefficients = new Float32Array(width * height);
  1213. for (var j = 0, jj = resolution.subbands.length; j < jj; j++) {
  1214. var mu, epsilon;
  1215. if (!scalarExpounded) {
  1216. mu = spqcds[0].mu;
  1217. epsilon = spqcds[0].epsilon + (i > 0 ? 1 - i : 0);
  1218. } else {
  1219. mu = spqcds[b].mu;
  1220. epsilon = spqcds[b].epsilon;
  1221. b++;
  1222. }
  1223. var subband = resolution.subbands[j];
  1224. var gainLog2 = SubbandsGainLog2[subband.type];
  1225. var delta = reversible ? 1 : Math.pow(2, precision + gainLog2 - epsilon) * (1 + mu / 2048);
  1226. var mb = guardBits + epsilon - 1;
  1227. copyCoefficients(coefficients, width, height, subband, delta, mb, reversible, segmentationSymbolUsed);
  1228. }
  1229. subbandCoefficients.push({
  1230. width: width,
  1231. height: height,
  1232. items: coefficients
  1233. });
  1234. }
  1235. var result = transform.calculate(subbandCoefficients, component.tcx0, component.tcy0);
  1236. return {
  1237. left: component.tcx0,
  1238. top: component.tcy0,
  1239. width: result.width,
  1240. height: result.height,
  1241. items: result.items
  1242. };
  1243. }
  1244. function transformComponents(context) {
  1245. var siz = context.SIZ;
  1246. var components = context.components;
  1247. var componentsCount = siz.Csiz;
  1248. var resultImages = [];
  1249. for (var i = 0, ii = context.tiles.length; i < ii; i++) {
  1250. var tile = context.tiles[i];
  1251. var transformedTiles = [];
  1252. var c;
  1253. for (c = 0; c < componentsCount; c++) {
  1254. transformedTiles[c] = transformTile(context, tile, c);
  1255. }
  1256. var tile0 = transformedTiles[0];
  1257. var out = new Uint8ClampedArray(tile0.items.length * componentsCount);
  1258. var result = {
  1259. left: tile0.left,
  1260. top: tile0.top,
  1261. width: tile0.width,
  1262. height: tile0.height,
  1263. items: out
  1264. };
  1265. var shift, offset;
  1266. var pos = 0,
  1267. j,
  1268. jj,
  1269. y0,
  1270. y1,
  1271. y2;
  1272. if (tile.codingStyleDefaultParameters.multipleComponentTransform) {
  1273. var fourComponents = componentsCount === 4;
  1274. var y0items = transformedTiles[0].items;
  1275. var y1items = transformedTiles[1].items;
  1276. var y2items = transformedTiles[2].items;
  1277. var y3items = fourComponents ? transformedTiles[3].items : null;
  1278. shift = components[0].precision - 8;
  1279. offset = (128 << shift) + 0.5;
  1280. var component0 = tile.components[0];
  1281. var alpha01 = componentsCount - 3;
  1282. jj = y0items.length;
  1283. if (!component0.codingStyleParameters.reversibleTransformation) {
  1284. for (j = 0; j < jj; j++, pos += alpha01) {
  1285. y0 = y0items[j] + offset;
  1286. y1 = y1items[j];
  1287. y2 = y2items[j];
  1288. out[pos++] = y0 + 1.402 * y2 >> shift;
  1289. out[pos++] = y0 - 0.34413 * y1 - 0.71414 * y2 >> shift;
  1290. out[pos++] = y0 + 1.772 * y1 >> shift;
  1291. }
  1292. } else {
  1293. for (j = 0; j < jj; j++, pos += alpha01) {
  1294. y0 = y0items[j] + offset;
  1295. y1 = y1items[j];
  1296. y2 = y2items[j];
  1297. var g = y0 - (y2 + y1 >> 2);
  1298. out[pos++] = g + y2 >> shift;
  1299. out[pos++] = g >> shift;
  1300. out[pos++] = g + y1 >> shift;
  1301. }
  1302. }
  1303. if (fourComponents) {
  1304. for (j = 0, pos = 3; j < jj; j++, pos += 4) {
  1305. out[pos] = y3items[j] + offset >> shift;
  1306. }
  1307. }
  1308. } else {
  1309. for (c = 0; c < componentsCount; c++) {
  1310. var items = transformedTiles[c].items;
  1311. shift = components[c].precision - 8;
  1312. offset = (128 << shift) + 0.5;
  1313. for (pos = c, j = 0, jj = items.length; j < jj; j++) {
  1314. out[pos] = items[j] + offset >> shift;
  1315. pos += componentsCount;
  1316. }
  1317. }
  1318. }
  1319. resultImages.push(result);
  1320. }
  1321. return resultImages;
  1322. }
  1323. function initializeTile(context, tileIndex) {
  1324. var siz = context.SIZ;
  1325. var componentsCount = siz.Csiz;
  1326. var tile = context.tiles[tileIndex];
  1327. for (var c = 0; c < componentsCount; c++) {
  1328. var component = tile.components[c];
  1329. var qcdOrQcc = context.currentTile.QCC[c] !== undefined ? context.currentTile.QCC[c] : context.currentTile.QCD;
  1330. component.quantizationParameters = qcdOrQcc;
  1331. var codOrCoc = context.currentTile.COC[c] !== undefined ? context.currentTile.COC[c] : context.currentTile.COD;
  1332. component.codingStyleParameters = codOrCoc;
  1333. }
  1334. tile.codingStyleDefaultParameters = context.currentTile.COD;
  1335. }
  1336. var TagTree = function TagTreeClosure() {
  1337. function TagTree(width, height) {
  1338. var levelsLength = (0, _util.log2)(Math.max(width, height)) + 1;
  1339. this.levels = [];
  1340. for (var i = 0; i < levelsLength; i++) {
  1341. var level = {
  1342. width: width,
  1343. height: height,
  1344. items: []
  1345. };
  1346. this.levels.push(level);
  1347. width = Math.ceil(width / 2);
  1348. height = Math.ceil(height / 2);
  1349. }
  1350. }
  1351. TagTree.prototype = {
  1352. reset: function TagTree_reset(i, j) {
  1353. var currentLevel = 0,
  1354. value = 0,
  1355. level;
  1356. while (currentLevel < this.levels.length) {
  1357. level = this.levels[currentLevel];
  1358. var index = i + j * level.width;
  1359. if (level.items[index] !== undefined) {
  1360. value = level.items[index];
  1361. break;
  1362. }
  1363. level.index = index;
  1364. i >>= 1;
  1365. j >>= 1;
  1366. currentLevel++;
  1367. }
  1368. currentLevel--;
  1369. level = this.levels[currentLevel];
  1370. level.items[level.index] = value;
  1371. this.currentLevel = currentLevel;
  1372. delete this.value;
  1373. },
  1374. incrementValue: function TagTree_incrementValue() {
  1375. var level = this.levels[this.currentLevel];
  1376. level.items[level.index]++;
  1377. },
  1378. nextLevel: function TagTree_nextLevel() {
  1379. var currentLevel = this.currentLevel;
  1380. var level = this.levels[currentLevel];
  1381. var value = level.items[level.index];
  1382. currentLevel--;
  1383. if (currentLevel < 0) {
  1384. this.value = value;
  1385. return false;
  1386. }
  1387. this.currentLevel = currentLevel;
  1388. level = this.levels[currentLevel];
  1389. level.items[level.index] = value;
  1390. return true;
  1391. }
  1392. };
  1393. return TagTree;
  1394. }();
  1395. var InclusionTree = function InclusionTreeClosure() {
  1396. function InclusionTree(width, height, defaultValue) {
  1397. var levelsLength = (0, _util.log2)(Math.max(width, height)) + 1;
  1398. this.levels = [];
  1399. for (var i = 0; i < levelsLength; i++) {
  1400. var items = new Uint8Array(width * height);
  1401. for (var j = 0, jj = items.length; j < jj; j++) {
  1402. items[j] = defaultValue;
  1403. }
  1404. var level = {
  1405. width: width,
  1406. height: height,
  1407. items: items
  1408. };
  1409. this.levels.push(level);
  1410. width = Math.ceil(width / 2);
  1411. height = Math.ceil(height / 2);
  1412. }
  1413. }
  1414. InclusionTree.prototype = {
  1415. reset: function InclusionTree_reset(i, j, stopValue) {
  1416. var currentLevel = 0;
  1417. while (currentLevel < this.levels.length) {
  1418. var level = this.levels[currentLevel];
  1419. var index = i + j * level.width;
  1420. level.index = index;
  1421. var value = level.items[index];
  1422. if (value === 0xFF) {
  1423. break;
  1424. }
  1425. if (value > stopValue) {
  1426. this.currentLevel = currentLevel;
  1427. this.propagateValues();
  1428. return false;
  1429. }
  1430. i >>= 1;
  1431. j >>= 1;
  1432. currentLevel++;
  1433. }
  1434. this.currentLevel = currentLevel - 1;
  1435. return true;
  1436. },
  1437. incrementValue: function InclusionTree_incrementValue(stopValue) {
  1438. var level = this.levels[this.currentLevel];
  1439. level.items[level.index] = stopValue + 1;
  1440. this.propagateValues();
  1441. },
  1442. propagateValues: function InclusionTree_propagateValues() {
  1443. var levelIndex = this.currentLevel;
  1444. var level = this.levels[levelIndex];
  1445. var currentValue = level.items[level.index];
  1446. while (--levelIndex >= 0) {
  1447. level = this.levels[levelIndex];
  1448. level.items[level.index] = currentValue;
  1449. }
  1450. },
  1451. nextLevel: function InclusionTree_nextLevel() {
  1452. var currentLevel = this.currentLevel;
  1453. var level = this.levels[currentLevel];
  1454. var value = level.items[level.index];
  1455. level.items[level.index] = 0xFF;
  1456. currentLevel--;
  1457. if (currentLevel < 0) {
  1458. return false;
  1459. }
  1460. this.currentLevel = currentLevel;
  1461. level = this.levels[currentLevel];
  1462. level.items[level.index] = value;
  1463. return true;
  1464. }
  1465. };
  1466. return InclusionTree;
  1467. }();
  1468. var BitModel = function BitModelClosure() {
  1469. var UNIFORM_CONTEXT = 17;
  1470. var RUNLENGTH_CONTEXT = 18;
  1471. var LLAndLHContextsLabel = new Uint8Array([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, 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, 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]);
  1472. var HLContextLabel = new Uint8Array([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, 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, 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]);
  1473. var HHContextLabel = new Uint8Array([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, 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, 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]);
  1474. function BitModel(width, height, subband, zeroBitPlanes, mb) {
  1475. this.width = width;
  1476. this.height = height;
  1477. this.contextLabelTable = subband === 'HH' ? HHContextLabel : subband === 'HL' ? HLContextLabel : LLAndLHContextsLabel;
  1478. var coefficientCount = width * height;
  1479. this.neighborsSignificance = new Uint8Array(coefficientCount);
  1480. this.coefficentsSign = new Uint8Array(coefficientCount);
  1481. this.coefficentsMagnitude = mb > 14 ? new Uint32Array(coefficientCount) : mb > 6 ? new Uint16Array(coefficientCount) : new Uint8Array(coefficientCount);
  1482. this.processingFlags = new Uint8Array(coefficientCount);
  1483. var bitsDecoded = new Uint8Array(coefficientCount);
  1484. if (zeroBitPlanes !== 0) {
  1485. for (var i = 0; i < coefficientCount; i++) {
  1486. bitsDecoded[i] = zeroBitPlanes;
  1487. }
  1488. }
  1489. this.bitsDecoded = bitsDecoded;
  1490. this.reset();
  1491. }
  1492. BitModel.prototype = {
  1493. setDecoder: function BitModel_setDecoder(decoder) {
  1494. this.decoder = decoder;
  1495. },
  1496. reset: function BitModel_reset() {
  1497. this.contexts = new Int8Array(19);
  1498. this.contexts[0] = 4 << 1 | 0;
  1499. this.contexts[UNIFORM_CONTEXT] = 46 << 1 | 0;
  1500. this.contexts[RUNLENGTH_CONTEXT] = 3 << 1 | 0;
  1501. },
  1502. setNeighborsSignificance: function BitModel_setNeighborsSignificance(row, column, index) {
  1503. var neighborsSignificance = this.neighborsSignificance;
  1504. var width = this.width,
  1505. height = this.height;
  1506. var left = column > 0;
  1507. var right = column + 1 < width;
  1508. var i;
  1509. if (row > 0) {
  1510. i = index - width;
  1511. if (left) {
  1512. neighborsSignificance[i - 1] += 0x10;
  1513. }
  1514. if (right) {
  1515. neighborsSignificance[i + 1] += 0x10;
  1516. }
  1517. neighborsSignificance[i] += 0x04;
  1518. }
  1519. if (row + 1 < height) {
  1520. i = index + width;
  1521. if (left) {
  1522. neighborsSignificance[i - 1] += 0x10;
  1523. }
  1524. if (right) {
  1525. neighborsSignificance[i + 1] += 0x10;
  1526. }
  1527. neighborsSignificance[i] += 0x04;
  1528. }
  1529. if (left) {
  1530. neighborsSignificance[index - 1] += 0x01;
  1531. }
  1532. if (right) {
  1533. neighborsSignificance[index + 1] += 0x01;
  1534. }
  1535. neighborsSignificance[index] |= 0x80;
  1536. },
  1537. runSignificancePropagationPass: function BitModel_runSignificancePropagationPass() {
  1538. var decoder = this.decoder;
  1539. var width = this.width,
  1540. height = this.height;
  1541. var coefficentsMagnitude = this.coefficentsMagnitude;
  1542. var coefficentsSign = this.coefficentsSign;
  1543. var neighborsSignificance = this.neighborsSignificance;
  1544. var processingFlags = this.processingFlags;
  1545. var contexts = this.contexts;
  1546. var labels = this.contextLabelTable;
  1547. var bitsDecoded = this.bitsDecoded;
  1548. var processedInverseMask = ~1;
  1549. var processedMask = 1;
  1550. var firstMagnitudeBitMask = 2;
  1551. for (var i0 = 0; i0 < height; i0 += 4) {
  1552. for (var j = 0; j < width; j++) {
  1553. var index = i0 * width + j;
  1554. for (var i1 = 0; i1 < 4; i1++, index += width) {
  1555. var i = i0 + i1;
  1556. if (i >= height) {
  1557. break;
  1558. }
  1559. processingFlags[index] &= processedInverseMask;
  1560. if (coefficentsMagnitude[index] || !neighborsSignificance[index]) {
  1561. continue;
  1562. }
  1563. var contextLabel = labels[neighborsSignificance[index]];
  1564. var decision = decoder.readBit(contexts, contextLabel);
  1565. if (decision) {
  1566. var sign = this.decodeSignBit(i, j, index);
  1567. coefficentsSign[index] = sign;
  1568. coefficentsMagnitude[index] = 1;
  1569. this.setNeighborsSignificance(i, j, index);
  1570. processingFlags[index] |= firstMagnitudeBitMask;
  1571. }
  1572. bitsDecoded[index]++;
  1573. processingFlags[index] |= processedMask;
  1574. }
  1575. }
  1576. }
  1577. },
  1578. decodeSignBit: function BitModel_decodeSignBit(row, column, index) {
  1579. var width = this.width,
  1580. height = this.height;
  1581. var coefficentsMagnitude = this.coefficentsMagnitude;
  1582. var coefficentsSign = this.coefficentsSign;
  1583. var contribution, sign0, sign1, significance1;
  1584. var contextLabel, decoded;
  1585. significance1 = column > 0 && coefficentsMagnitude[index - 1] !== 0;
  1586. if (column + 1 < width && coefficentsMagnitude[index + 1] !== 0) {
  1587. sign1 = coefficentsSign[index + 1];
  1588. if (significance1) {
  1589. sign0 = coefficentsSign[index - 1];
  1590. contribution = 1 - sign1 - sign0;
  1591. } else {
  1592. contribution = 1 - sign1 - sign1;
  1593. }
  1594. } else if (significance1) {
  1595. sign0 = coefficentsSign[index - 1];
  1596. contribution = 1 - sign0 - sign0;
  1597. } else {
  1598. contribution = 0;
  1599. }
  1600. var horizontalContribution = 3 * contribution;
  1601. significance1 = row > 0 && coefficentsMagnitude[index - width] !== 0;
  1602. if (row + 1 < height && coefficentsMagnitude[index + width] !== 0) {
  1603. sign1 = coefficentsSign[index + width];
  1604. if (significance1) {
  1605. sign0 = coefficentsSign[index - width];
  1606. contribution = 1 - sign1 - sign0 + horizontalContribution;
  1607. } else {
  1608. contribution = 1 - sign1 - sign1 + horizontalContribution;
  1609. }
  1610. } else if (significance1) {
  1611. sign0 = coefficentsSign[index - width];
  1612. contribution = 1 - sign0 - sign0 + horizontalContribution;
  1613. } else {
  1614. contribution = horizontalContribution;
  1615. }
  1616. if (contribution >= 0) {
  1617. contextLabel = 9 + contribution;
  1618. decoded = this.decoder.readBit(this.contexts, contextLabel);
  1619. } else {
  1620. contextLabel = 9 - contribution;
  1621. decoded = this.decoder.readBit(this.contexts, contextLabel) ^ 1;
  1622. }
  1623. return decoded;
  1624. },
  1625. runMagnitudeRefinementPass: function BitModel_runMagnitudeRefinementPass() {
  1626. var decoder = this.decoder;
  1627. var width = this.width,
  1628. height = this.height;
  1629. var coefficentsMagnitude = this.coefficentsMagnitude;
  1630. var neighborsSignificance = this.neighborsSignificance;
  1631. var contexts = this.contexts;
  1632. var bitsDecoded = this.bitsDecoded;
  1633. var processingFlags = this.processingFlags;
  1634. var processedMask = 1;
  1635. var firstMagnitudeBitMask = 2;
  1636. var length = width * height;
  1637. var width4 = width * 4;
  1638. for (var index0 = 0, indexNext; index0 < length; index0 = indexNext) {
  1639. indexNext = Math.min(length, index0 + width4);
  1640. for (var j = 0; j < width; j++) {
  1641. for (var index = index0 + j; index < indexNext; index += width) {
  1642. if (!coefficentsMagnitude[index] || (processingFlags[index] & processedMask) !== 0) {
  1643. continue;
  1644. }
  1645. var contextLabel = 16;
  1646. if ((processingFlags[index] & firstMagnitudeBitMask) !== 0) {
  1647. processingFlags[index] ^= firstMagnitudeBitMask;
  1648. var significance = neighborsSignificance[index] & 127;
  1649. contextLabel = significance === 0 ? 15 : 14;
  1650. }
  1651. var bit = decoder.readBit(contexts, contextLabel);
  1652. coefficentsMagnitude[index] = coefficentsMagnitude[index] << 1 | bit;
  1653. bitsDecoded[index]++;
  1654. processingFlags[index] |= processedMask;
  1655. }
  1656. }
  1657. }
  1658. },
  1659. runCleanupPass: function BitModel_runCleanupPass() {
  1660. var decoder = this.decoder;
  1661. var width = this.width,
  1662. height = this.height;
  1663. var neighborsSignificance = this.neighborsSignificance;
  1664. var coefficentsMagnitude = this.coefficentsMagnitude;
  1665. var coefficentsSign = this.coefficentsSign;
  1666. var contexts = this.contexts;
  1667. var labels = this.contextLabelTable;
  1668. var bitsDecoded = this.bitsDecoded;
  1669. var processingFlags = this.processingFlags;
  1670. var processedMask = 1;
  1671. var firstMagnitudeBitMask = 2;
  1672. var oneRowDown = width;
  1673. var twoRowsDown = width * 2;
  1674. var threeRowsDown = width * 3;
  1675. var iNext;
  1676. for (var i0 = 0; i0 < height; i0 = iNext) {
  1677. iNext = Math.min(i0 + 4, height);
  1678. var indexBase = i0 * width;
  1679. var checkAllEmpty = i0 + 3 < height;
  1680. for (var j = 0; j < width; j++) {
  1681. var index0 = indexBase + j;
  1682. var allEmpty = checkAllEmpty && processingFlags[index0] === 0 && processingFlags[index0 + oneRowDown] === 0 && processingFlags[index0 + twoRowsDown] === 0 && processingFlags[index0 + threeRowsDown] === 0 && neighborsSignificance[index0] === 0 && neighborsSignificance[index0 + oneRowDown] === 0 && neighborsSignificance[index0 + twoRowsDown] === 0 && neighborsSignificance[index0 + threeRowsDown] === 0;
  1683. var i1 = 0,
  1684. index = index0;
  1685. var i = i0,
  1686. sign;
  1687. if (allEmpty) {
  1688. var hasSignificantCoefficent = decoder.readBit(contexts, RUNLENGTH_CONTEXT);
  1689. if (!hasSignificantCoefficent) {
  1690. bitsDecoded[index0]++;
  1691. bitsDecoded[index0 + oneRowDown]++;
  1692. bitsDecoded[index0 + twoRowsDown]++;
  1693. bitsDecoded[index0 + threeRowsDown]++;
  1694. continue;
  1695. }
  1696. i1 = decoder.readBit(contexts, UNIFORM_CONTEXT) << 1 | decoder.readBit(contexts, UNIFORM_CONTEXT);
  1697. if (i1 !== 0) {
  1698. i = i0 + i1;
  1699. index += i1 * width;
  1700. }
  1701. sign = this.decodeSignBit(i, j, index);
  1702. coefficentsSign[index] = sign;
  1703. coefficentsMagnitude[index] = 1;
  1704. this.setNeighborsSignificance(i, j, index);
  1705. processingFlags[index] |= firstMagnitudeBitMask;
  1706. index = index0;
  1707. for (var i2 = i0; i2 <= i; i2++, index += width) {
  1708. bitsDecoded[index]++;
  1709. }
  1710. i1++;
  1711. }
  1712. for (i = i0 + i1; i < iNext; i++, index += width) {
  1713. if (coefficentsMagnitude[index] || (processingFlags[index] & processedMask) !== 0) {
  1714. continue;
  1715. }
  1716. var contextLabel = labels[neighborsSignificance[index]];
  1717. var decision = decoder.readBit(contexts, contextLabel);
  1718. if (decision === 1) {
  1719. sign = this.decodeSignBit(i, j, index);
  1720. coefficentsSign[index] = sign;
  1721. coefficentsMagnitude[index] = 1;
  1722. this.setNeighborsSignificance(i, j, index);
  1723. processingFlags[index] |= firstMagnitudeBitMask;
  1724. }
  1725. bitsDecoded[index]++;
  1726. }
  1727. }
  1728. }
  1729. },
  1730. checkSegmentationSymbol: function BitModel_checkSegmentationSymbol() {
  1731. var decoder = this.decoder;
  1732. var contexts = this.contexts;
  1733. var symbol = decoder.readBit(contexts, UNIFORM_CONTEXT) << 3 | decoder.readBit(contexts, UNIFORM_CONTEXT) << 2 | decoder.readBit(contexts, UNIFORM_CONTEXT) << 1 | decoder.readBit(contexts, UNIFORM_CONTEXT);
  1734. if (symbol !== 0xA) {
  1735. throw new JpxError('Invalid segmentation symbol');
  1736. }
  1737. }
  1738. };
  1739. return BitModel;
  1740. }();
  1741. var Transform = function TransformClosure() {
  1742. function Transform() {}
  1743. Transform.prototype.calculate = function transformCalculate(subbands, u0, v0) {
  1744. var ll = subbands[0];
  1745. for (var i = 1, ii = subbands.length; i < ii; i++) {
  1746. ll = this.iterate(ll, subbands[i], u0, v0);
  1747. }
  1748. return ll;
  1749. };
  1750. Transform.prototype.extend = function extend(buffer, offset, size) {
  1751. var i1 = offset - 1,
  1752. j1 = offset + 1;
  1753. var i2 = offset + size - 2,
  1754. j2 = offset + size;
  1755. buffer[i1--] = buffer[j1++];
  1756. buffer[j2++] = buffer[i2--];
  1757. buffer[i1--] = buffer[j1++];
  1758. buffer[j2++] = buffer[i2--];
  1759. buffer[i1--] = buffer[j1++];
  1760. buffer[j2++] = buffer[i2--];
  1761. buffer[i1] = buffer[j1];
  1762. buffer[j2] = buffer[i2];
  1763. };
  1764. Transform.prototype.iterate = function Transform_iterate(ll, hl_lh_hh, u0, v0) {
  1765. var llWidth = ll.width,
  1766. llHeight = ll.height,
  1767. llItems = ll.items;
  1768. var width = hl_lh_hh.width;
  1769. var height = hl_lh_hh.height;
  1770. var items = hl_lh_hh.items;
  1771. var i, j, k, l, u, v;
  1772. for (k = 0, i = 0; i < llHeight; i++) {
  1773. l = i * 2 * width;
  1774. for (j = 0; j < llWidth; j++, k++, l += 2) {
  1775. items[l] = llItems[k];
  1776. }
  1777. }
  1778. llItems = ll.items = null;
  1779. var bufferPadding = 4;
  1780. var rowBuffer = new Float32Array(width + 2 * bufferPadding);
  1781. if (width === 1) {
  1782. if ((u0 & 1) !== 0) {
  1783. for (v = 0, k = 0; v < height; v++, k += width) {
  1784. items[k] *= 0.5;
  1785. }
  1786. }
  1787. } else {
  1788. for (v = 0, k = 0; v < height; v++, k += width) {
  1789. rowBuffer.set(items.subarray(k, k + width), bufferPadding);
  1790. this.extend(rowBuffer, bufferPadding, width);
  1791. this.filter(rowBuffer, bufferPadding, width);
  1792. items.set(rowBuffer.subarray(bufferPadding, bufferPadding + width), k);
  1793. }
  1794. }
  1795. var numBuffers = 16;
  1796. var colBuffers = [];
  1797. for (i = 0; i < numBuffers; i++) {
  1798. colBuffers.push(new Float32Array(height + 2 * bufferPadding));
  1799. }
  1800. var b,
  1801. currentBuffer = 0;
  1802. ll = bufferPadding + height;
  1803. if (height === 1) {
  1804. if ((v0 & 1) !== 0) {
  1805. for (u = 0; u < width; u++) {
  1806. items[u] *= 0.5;
  1807. }
  1808. }
  1809. } else {
  1810. for (u = 0; u < width; u++) {
  1811. if (currentBuffer === 0) {
  1812. numBuffers = Math.min(width - u, numBuffers);
  1813. for (k = u, l = bufferPadding; l < ll; k += width, l++) {
  1814. for (b = 0; b < numBuffers; b++) {
  1815. colBuffers[b][l] = items[k + b];
  1816. }
  1817. }
  1818. currentBuffer = numBuffers;
  1819. }
  1820. currentBuffer--;
  1821. var buffer = colBuffers[currentBuffer];
  1822. this.extend(buffer, bufferPadding, height);
  1823. this.filter(buffer, bufferPadding, height);
  1824. if (currentBuffer === 0) {
  1825. k = u - numBuffers + 1;
  1826. for (l = bufferPadding; l < ll; k += width, l++) {
  1827. for (b = 0; b < numBuffers; b++) {
  1828. items[k + b] = colBuffers[b][l];
  1829. }
  1830. }
  1831. }
  1832. }
  1833. }
  1834. return {
  1835. width: width,
  1836. height: height,
  1837. items: items
  1838. };
  1839. };
  1840. return Transform;
  1841. }();
  1842. var IrreversibleTransform = function IrreversibleTransformClosure() {
  1843. function IrreversibleTransform() {
  1844. Transform.call(this);
  1845. }
  1846. IrreversibleTransform.prototype = Object.create(Transform.prototype);
  1847. IrreversibleTransform.prototype.filter = function irreversibleTransformFilter(x, offset, length) {
  1848. var len = length >> 1;
  1849. offset = offset | 0;
  1850. var j, n, current, next;
  1851. var alpha = -1.586134342059924;
  1852. var beta = -0.052980118572961;
  1853. var gamma = 0.882911075530934;
  1854. var delta = 0.443506852043971;
  1855. var K = 1.230174104914001;
  1856. var K_ = 1 / K;
  1857. j = offset - 3;
  1858. for (n = len + 4; n--; j += 2) {
  1859. x[j] *= K_;
  1860. }
  1861. j = offset - 2;
  1862. current = delta * x[j - 1];
  1863. for (n = len + 3; n--; j += 2) {
  1864. next = delta * x[j + 1];
  1865. x[j] = K * x[j] - current - next;
  1866. if (n--) {
  1867. j += 2;
  1868. current = delta * x[j + 1];
  1869. x[j] = K * x[j] - current - next;
  1870. } else {
  1871. break;
  1872. }
  1873. }
  1874. j = offset - 1;
  1875. current = gamma * x[j - 1];
  1876. for (n = len + 2; n--; j += 2) {
  1877. next = gamma * x[j + 1];
  1878. x[j] -= current + next;
  1879. if (n--) {
  1880. j += 2;
  1881. current = gamma * x[j + 1];
  1882. x[j] -= current + next;
  1883. } else {
  1884. break;
  1885. }
  1886. }
  1887. j = offset;
  1888. current = beta * x[j - 1];
  1889. for (n = len + 1; n--; j += 2) {
  1890. next = beta * x[j + 1];
  1891. x[j] -= current + next;
  1892. if (n--) {
  1893. j += 2;
  1894. current = beta * x[j + 1];
  1895. x[j] -= current + next;
  1896. } else {
  1897. break;
  1898. }
  1899. }
  1900. if (len !== 0) {
  1901. j = offset + 1;
  1902. current = alpha * x[j - 1];
  1903. for (n = len; n--; j += 2) {
  1904. next = alpha * x[j + 1];
  1905. x[j] -= current + next;
  1906. if (n--) {
  1907. j += 2;
  1908. current = alpha * x[j + 1];
  1909. x[j] -= current + next;
  1910. } else {
  1911. break;
  1912. }
  1913. }
  1914. }
  1915. };
  1916. return IrreversibleTransform;
  1917. }();
  1918. var ReversibleTransform = function ReversibleTransformClosure() {
  1919. function ReversibleTransform() {
  1920. Transform.call(this);
  1921. }
  1922. ReversibleTransform.prototype = Object.create(Transform.prototype);
  1923. ReversibleTransform.prototype.filter = function reversibleTransformFilter(x, offset, length) {
  1924. var len = length >> 1;
  1925. offset = offset | 0;
  1926. var j, n;
  1927. for (j = offset, n = len + 1; n--; j += 2) {
  1928. x[j] -= x[j - 1] + x[j + 1] + 2 >> 2;
  1929. }
  1930. for (j = offset + 1, n = len; n--; j += 2) {
  1931. x[j] += x[j - 1] + x[j + 1] >> 1;
  1932. }
  1933. };
  1934. return ReversibleTransform;
  1935. }();
  1936. return JpxImage;
  1937. }();
  1938. exports.JpxImage = JpxImage;