2
0

jpx.js 68 KB

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