jpx.js 72 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351
  1. /**
  2. * @licstart The following is the entire license notice for the
  3. * Javascript code in this page
  4. *
  5. * Copyright 2020 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}`);
  33. }
  34. }
  35. var JpxImage = function JpxImageClosure() {
  36. var SubbandsGainLog2 = {
  37. LL: 0,
  38. LH: 1,
  39. HL: 1,
  40. HH: 2
  41. };
  42. function JpxImage() {
  43. this.failOnCorruptedImage = false;
  44. }
  45. JpxImage.prototype = {
  46. parse: function JpxImage_parse(data) {
  47. var head = (0, _core_utils.readUint16)(data, 0);
  48. if (head === 0xff4f) {
  49. this.parseCodestream(data, 0, data.length);
  50. return;
  51. }
  52. var position = 0,
  53. length = data.length;
  54. while (position < length) {
  55. var headerSize = 8;
  56. var lbox = (0, _core_utils.readUint32)(data, position);
  57. var tbox = (0, _core_utils.readUint32)(data, position + 4);
  58. position += headerSize;
  59. if (lbox === 1) {
  60. lbox = (0, _core_utils.readUint32)(data, position) * 4294967296 + (0, _core_utils.readUint32)(data, position + 4);
  61. position += 8;
  62. headerSize += 8;
  63. }
  64. if (lbox === 0) {
  65. lbox = length - position + headerSize;
  66. }
  67. if (lbox < headerSize) {
  68. throw new JpxError("Invalid box field size");
  69. }
  70. var dataLength = lbox - headerSize;
  71. var jumpDataLength = true;
  72. switch (tbox) {
  73. case 0x6a703268:
  74. jumpDataLength = false;
  75. break;
  76. case 0x636f6c72:
  77. var method = data[position];
  78. if (method === 1) {
  79. var colorspace = (0, _core_utils.readUint32)(data, position + 3);
  80. switch (colorspace) {
  81. case 16:
  82. case 17:
  83. case 18:
  84. break;
  85. default:
  86. (0, _util.warn)("Unknown colorspace " + colorspace);
  87. break;
  88. }
  89. } else if (method === 2) {
  90. (0, _util.info)("ICC profile not supported");
  91. }
  92. break;
  93. case 0x6a703263:
  94. this.parseCodestream(data, position, position + dataLength);
  95. break;
  96. case 0x6a502020:
  97. if ((0, _core_utils.readUint32)(data, position) !== 0x0d0a870a) {
  98. (0, _util.warn)("Invalid JP2 signature");
  99. }
  100. break;
  101. case 0x6a501a1a:
  102. case 0x66747970:
  103. case 0x72726571:
  104. case 0x72657320:
  105. case 0x69686472:
  106. break;
  107. default:
  108. var headerType = String.fromCharCode(tbox >> 24 & 0xff, tbox >> 16 & 0xff, tbox >> 8 & 0xff, tbox & 0xff);
  109. (0, _util.warn)("Unsupported header type " + tbox + " (" + headerType + ")");
  110. break;
  111. }
  112. if (jumpDataLength) {
  113. position += dataLength;
  114. }
  115. }
  116. },
  117. parseImageProperties: function JpxImage_parseImageProperties(stream) {
  118. var newByte = stream.getByte();
  119. while (newByte >= 0) {
  120. var oldByte = newByte;
  121. newByte = stream.getByte();
  122. var code = oldByte << 8 | newByte;
  123. if (code === 0xff51) {
  124. stream.skip(4);
  125. var Xsiz = stream.getInt32() >>> 0;
  126. var Ysiz = stream.getInt32() >>> 0;
  127. var XOsiz = stream.getInt32() >>> 0;
  128. var YOsiz = stream.getInt32() >>> 0;
  129. stream.skip(16);
  130. var Csiz = stream.getUint16();
  131. this.width = Xsiz - XOsiz;
  132. this.height = Ysiz - YOsiz;
  133. this.componentsCount = Csiz;
  134. this.bitsPerComponent = 8;
  135. return;
  136. }
  137. }
  138. throw new JpxError("No size marker found in JPX stream");
  139. },
  140. parseCodestream: function JpxImage_parseCodestream(data, start, end) {
  141. var context = {};
  142. var doNotRecover = false;
  143. try {
  144. var position = start;
  145. while (position + 1 < end) {
  146. var code = (0, _core_utils.readUint16)(data, position);
  147. position += 2;
  148. var length = 0,
  149. j,
  150. sqcd,
  151. spqcds,
  152. spqcdSize,
  153. scalarExpounded,
  154. tile;
  155. switch (code) {
  156. case 0xff4f:
  157. context.mainHeader = true;
  158. break;
  159. case 0xffd9:
  160. break;
  161. case 0xff51:
  162. length = (0, _core_utils.readUint16)(data, position);
  163. var siz = {};
  164. siz.Xsiz = (0, _core_utils.readUint32)(data, position + 4);
  165. siz.Ysiz = (0, _core_utils.readUint32)(data, position + 8);
  166. siz.XOsiz = (0, _core_utils.readUint32)(data, position + 12);
  167. siz.YOsiz = (0, _core_utils.readUint32)(data, position + 16);
  168. siz.XTsiz = (0, _core_utils.readUint32)(data, position + 20);
  169. siz.YTsiz = (0, _core_utils.readUint32)(data, position + 24);
  170. siz.XTOsiz = (0, _core_utils.readUint32)(data, position + 28);
  171. siz.YTOsiz = (0, _core_utils.readUint32)(data, position + 32);
  172. var componentsCount = (0, _core_utils.readUint16)(data, position + 36);
  173. siz.Csiz = componentsCount;
  174. var components = [];
  175. j = position + 38;
  176. for (var i = 0; i < componentsCount; i++) {
  177. var component = {
  178. precision: (data[j] & 0x7f) + 1,
  179. isSigned: !!(data[j] & 0x80),
  180. XRsiz: data[j + 1],
  181. YRsiz: data[j + 2]
  182. };
  183. j += 3;
  184. calculateComponentDimensions(component, siz);
  185. components.push(component);
  186. }
  187. context.SIZ = siz;
  188. context.components = components;
  189. calculateTileGrids(context, components);
  190. context.QCC = [];
  191. context.COC = [];
  192. break;
  193. case 0xff5c:
  194. length = (0, _core_utils.readUint16)(data, position);
  195. var qcd = {};
  196. j = position + 2;
  197. sqcd = data[j++];
  198. switch (sqcd & 0x1f) {
  199. case 0:
  200. spqcdSize = 8;
  201. scalarExpounded = true;
  202. break;
  203. case 1:
  204. spqcdSize = 16;
  205. scalarExpounded = false;
  206. break;
  207. case 2:
  208. spqcdSize = 16;
  209. scalarExpounded = true;
  210. break;
  211. default:
  212. throw new Error("Invalid SQcd value " + sqcd);
  213. }
  214. qcd.noQuantization = spqcdSize === 8;
  215. qcd.scalarExpounded = scalarExpounded;
  216. qcd.guardBits = sqcd >> 5;
  217. spqcds = [];
  218. while (j < length + position) {
  219. var spqcd = {};
  220. if (spqcdSize === 8) {
  221. spqcd.epsilon = data[j++] >> 3;
  222. spqcd.mu = 0;
  223. } else {
  224. spqcd.epsilon = data[j] >> 3;
  225. spqcd.mu = (data[j] & 0x7) << 8 | data[j + 1];
  226. j += 2;
  227. }
  228. spqcds.push(spqcd);
  229. }
  230. qcd.SPqcds = spqcds;
  231. if (context.mainHeader) {
  232. context.QCD = qcd;
  233. } else {
  234. context.currentTile.QCD = qcd;
  235. context.currentTile.QCC = [];
  236. }
  237. break;
  238. case 0xff5d:
  239. length = (0, _core_utils.readUint16)(data, position);
  240. var qcc = {};
  241. j = position + 2;
  242. var cqcc;
  243. if (context.SIZ.Csiz < 257) {
  244. cqcc = data[j++];
  245. } else {
  246. cqcc = (0, _core_utils.readUint16)(data, j);
  247. j += 2;
  248. }
  249. sqcd = data[j++];
  250. switch (sqcd & 0x1f) {
  251. case 0:
  252. spqcdSize = 8;
  253. scalarExpounded = true;
  254. break;
  255. case 1:
  256. spqcdSize = 16;
  257. scalarExpounded = false;
  258. break;
  259. case 2:
  260. spqcdSize = 16;
  261. scalarExpounded = true;
  262. break;
  263. default:
  264. throw new Error("Invalid SQcd value " + sqcd);
  265. }
  266. qcc.noQuantization = spqcdSize === 8;
  267. qcc.scalarExpounded = scalarExpounded;
  268. qcc.guardBits = sqcd >> 5;
  269. spqcds = [];
  270. while (j < length + position) {
  271. spqcd = {};
  272. if (spqcdSize === 8) {
  273. spqcd.epsilon = data[j++] >> 3;
  274. spqcd.mu = 0;
  275. } else {
  276. spqcd.epsilon = data[j] >> 3;
  277. spqcd.mu = (data[j] & 0x7) << 8 | data[j + 1];
  278. j += 2;
  279. }
  280. spqcds.push(spqcd);
  281. }
  282. qcc.SPqcds = spqcds;
  283. if (context.mainHeader) {
  284. context.QCC[cqcc] = qcc;
  285. } else {
  286. context.currentTile.QCC[cqcc] = qcc;
  287. }
  288. break;
  289. case 0xff52:
  290. length = (0, _core_utils.readUint16)(data, position);
  291. var cod = {};
  292. j = position + 2;
  293. var scod = data[j++];
  294. cod.entropyCoderWithCustomPrecincts = !!(scod & 1);
  295. cod.sopMarkerUsed = !!(scod & 2);
  296. cod.ephMarkerUsed = !!(scod & 4);
  297. cod.progressionOrder = data[j++];
  298. cod.layersCount = (0, _core_utils.readUint16)(data, j);
  299. j += 2;
  300. cod.multipleComponentTransform = data[j++];
  301. cod.decompositionLevelsCount = data[j++];
  302. cod.xcb = (data[j++] & 0xf) + 2;
  303. cod.ycb = (data[j++] & 0xf) + 2;
  304. var blockStyle = data[j++];
  305. cod.selectiveArithmeticCodingBypass = !!(blockStyle & 1);
  306. cod.resetContextProbabilities = !!(blockStyle & 2);
  307. cod.terminationOnEachCodingPass = !!(blockStyle & 4);
  308. cod.verticallyStripe = !!(blockStyle & 8);
  309. cod.predictableTermination = !!(blockStyle & 16);
  310. cod.segmentationSymbolUsed = !!(blockStyle & 32);
  311. cod.reversibleTransformation = data[j++];
  312. if (cod.entropyCoderWithCustomPrecincts) {
  313. var precinctsSizes = [];
  314. while (j < length + position) {
  315. var precinctsSize = data[j++];
  316. precinctsSizes.push({
  317. PPx: precinctsSize & 0xf,
  318. PPy: precinctsSize >> 4
  319. });
  320. }
  321. cod.precinctsSizes = precinctsSizes;
  322. }
  323. var unsupported = [];
  324. if (cod.selectiveArithmeticCodingBypass) {
  325. unsupported.push("selectiveArithmeticCodingBypass");
  326. }
  327. if (cod.resetContextProbabilities) {
  328. unsupported.push("resetContextProbabilities");
  329. }
  330. if (cod.terminationOnEachCodingPass) {
  331. unsupported.push("terminationOnEachCodingPass");
  332. }
  333. if (cod.verticallyStripe) {
  334. unsupported.push("verticallyStripe");
  335. }
  336. if (cod.predictableTermination) {
  337. unsupported.push("predictableTermination");
  338. }
  339. if (unsupported.length > 0) {
  340. doNotRecover = true;
  341. throw new Error("Unsupported COD options (" + unsupported.join(", ") + ")");
  342. }
  343. if (context.mainHeader) {
  344. context.COD = cod;
  345. } else {
  346. context.currentTile.COD = cod;
  347. context.currentTile.COC = [];
  348. }
  349. break;
  350. case 0xff90:
  351. length = (0, _core_utils.readUint16)(data, position);
  352. tile = {};
  353. tile.index = (0, _core_utils.readUint16)(data, position + 2);
  354. tile.length = (0, _core_utils.readUint32)(data, position + 4);
  355. tile.dataEnd = tile.length + position - 2;
  356. tile.partIndex = data[position + 8];
  357. tile.partsCount = data[position + 9];
  358. context.mainHeader = false;
  359. if (tile.partIndex === 0) {
  360. tile.COD = context.COD;
  361. tile.COC = context.COC.slice(0);
  362. tile.QCD = context.QCD;
  363. tile.QCC = context.QCC.slice(0);
  364. }
  365. context.currentTile = tile;
  366. break;
  367. case 0xff93:
  368. tile = context.currentTile;
  369. if (tile.partIndex === 0) {
  370. initializeTile(context, tile.index);
  371. buildPackets(context);
  372. }
  373. length = tile.dataEnd - position;
  374. parseTilePackets(context, data, position, length);
  375. break;
  376. case 0xff55:
  377. case 0xff57:
  378. case 0xff58:
  379. case 0xff64:
  380. length = (0, _core_utils.readUint16)(data, position);
  381. break;
  382. case 0xff53:
  383. throw new Error("Codestream code 0xFF53 (COC) is not implemented");
  384. default:
  385. throw new Error("Unknown codestream code: " + code.toString(16));
  386. }
  387. position += length;
  388. }
  389. } catch (e) {
  390. if (doNotRecover || this.failOnCorruptedImage) {
  391. throw new JpxError(e.message);
  392. } else {
  393. (0, _util.warn)("JPX: Trying to recover from: " + e.message);
  394. }
  395. }
  396. this.tiles = transformComponents(context);
  397. this.width = context.SIZ.Xsiz - context.SIZ.XOsiz;
  398. this.height = context.SIZ.Ysiz - context.SIZ.YOsiz;
  399. this.componentsCount = context.SIZ.Csiz;
  400. }
  401. };
  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. var siz = context.SIZ;
  412. var tile,
  413. tiles = [];
  414. var numXtiles = Math.ceil((siz.Xsiz - siz.XTOsiz) / siz.XTsiz);
  415. var numYtiles = Math.ceil((siz.Ysiz - siz.YTOsiz) / siz.YTsiz);
  416. for (var q = 0; q < numYtiles; q++) {
  417. for (var 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. var componentsCount = siz.Csiz;
  431. for (var i = 0, ii = componentsCount; i < ii; i++) {
  432. var component = components[i];
  433. for (var j = 0, jj = tiles.length; j < jj; j++) {
  434. var 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. var codOrCoc = component.codingStyleParameters;
  448. var 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. var precinctWidth = 1 << dimensions.PPx;
  462. var precinctHeight = 1 << dimensions.PPy;
  463. var isZeroRes = resolution.resLevel === 0;
  464. var precinctWidthInSubband = 1 << dimensions.PPx + (isZeroRes ? 0 : -1);
  465. var precinctHeightInSubband = 1 << dimensions.PPy + (isZeroRes ? 0 : -1);
  466. var numprecinctswide = resolution.trx1 > resolution.trx0 ? Math.ceil(resolution.trx1 / precinctWidth) - Math.floor(resolution.trx0 / precinctWidth) : 0;
  467. var numprecinctshigh = resolution.try1 > resolution.try0 ? Math.ceil(resolution.try1 / precinctHeight) - Math.floor(resolution.try0 / precinctHeight) : 0;
  468. var 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. var xcb_ = dimensions.xcb_;
  481. var ycb_ = dimensions.ycb_;
  482. var codeblockWidth = 1 << xcb_;
  483. var codeblockHeight = 1 << ycb_;
  484. var cbx0 = subband.tbx0 >> xcb_;
  485. var cby0 = subband.tby0 >> ycb_;
  486. var cbx1 = subband.tbx1 + codeblockWidth - 1 >> xcb_;
  487. var cby1 = subband.tby1 + codeblockHeight - 1 >> ycb_;
  488. var precinctParameters = subband.resolution.precinctParameters;
  489. var codeblocks = [];
  490. var precincts = [];
  491. var 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. var pi = Math.floor((codeblock.tbx0_ - subband.tbx0) / precinctParameters.precinctWidthInSubband);
  507. var 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. var 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. var precinctCodeblocks = [];
  550. var subbands = resolution.subbands;
  551. for (var i = 0, ii = subbands.length; i < ii; i++) {
  552. var subband = subbands[i];
  553. var codeblocks = subband.codeblocks;
  554. for (var j = 0, jj = codeblocks.length; j < jj; j++) {
  555. var 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. var siz = context.SIZ;
  569. var tileIndex = context.currentTile.index;
  570. var tile = context.tiles[tileIndex];
  571. var layersCount = tile.codingStyleDefaultParameters.layersCount;
  572. var componentsCount = siz.Csiz;
  573. var maxDecompositionLevelsCount = 0;
  574. for (var q = 0; q < componentsCount; q++) {
  575. maxDecompositionLevelsCount = Math.max(maxDecompositionLevelsCount, tile.components[q].codingStyleParameters.decompositionLevelsCount);
  576. }
  577. var 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. var component = tile.components[i];
  586. if (r > component.codingStyleParameters.decompositionLevelsCount) {
  587. continue;
  588. }
  589. var resolution = component.resolutions[r];
  590. var numprecincts = resolution.precinctParameters.numprecincts;
  591. for (; k < numprecincts;) {
  592. var 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. var siz = context.SIZ;
  607. var tileIndex = context.currentTile.index;
  608. var tile = context.tiles[tileIndex];
  609. var layersCount = tile.codingStyleDefaultParameters.layersCount;
  610. var componentsCount = siz.Csiz;
  611. var maxDecompositionLevelsCount = 0;
  612. for (var q = 0; q < componentsCount; q++) {
  613. maxDecompositionLevelsCount = Math.max(maxDecompositionLevelsCount, tile.components[q].codingStyleParameters.decompositionLevelsCount);
  614. }
  615. var 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. var component = tile.components[i];
  624. if (r > component.codingStyleParameters.decompositionLevelsCount) {
  625. continue;
  626. }
  627. var resolution = component.resolutions[r];
  628. var numprecincts = resolution.precinctParameters.numprecincts;
  629. for (; k < numprecincts;) {
  630. var 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. var siz = context.SIZ;
  645. var tileIndex = context.currentTile.index;
  646. var tile = context.tiles[tileIndex];
  647. var layersCount = tile.codingStyleDefaultParameters.layersCount;
  648. var componentsCount = siz.Csiz;
  649. var l, r, c, p;
  650. var 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. var maxNumPrecinctsInLevel = new Int32Array(maxDecompositionLevelsCount + 1);
  656. for (r = 0; r <= maxDecompositionLevelsCount; ++r) {
  657. var maxNumPrecincts = 0;
  658. for (c = 0; c < componentsCount; ++c) {
  659. var 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. var resolution = component.resolutions[r];
  679. var numprecincts = resolution.precinctParameters.numprecincts;
  680. if (p >= numprecincts) {
  681. continue;
  682. }
  683. for (; l < layersCount;) {
  684. var 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. var siz = context.SIZ;
  699. var tileIndex = context.currentTile.index;
  700. var tile = context.tiles[tileIndex];
  701. var layersCount = tile.codingStyleDefaultParameters.layersCount;
  702. var componentsCount = siz.Csiz;
  703. var precinctsSizes = getPrecinctSizesInImageScale(tile);
  704. var precinctsIterationSizes = precinctsSizes;
  705. var 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. var component = tile.components[c];
  715. var decompositionLevelsCount = component.codingStyleParameters.decompositionLevelsCount;
  716. for (; r <= decompositionLevelsCount; r++) {
  717. var resolution = component.resolutions[r];
  718. var sizeInImageScale = precinctsSizes.components[c].resolutions[r];
  719. var k = getPrecinctIndexIfExist(px, py, sizeInImageScale, precinctsIterationSizes, resolution);
  720. if (k === null) {
  721. continue;
  722. }
  723. for (; l < layersCount;) {
  724. var 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. var siz = context.SIZ;
  741. var tileIndex = context.currentTile.index;
  742. var tile = context.tiles[tileIndex];
  743. var layersCount = tile.codingStyleDefaultParameters.layersCount;
  744. var componentsCount = siz.Csiz;
  745. var precinctsSizes = getPrecinctSizesInImageScale(tile);
  746. var 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. var component = tile.components[c];
  754. var precinctsIterationSizes = precinctsSizes.components[c];
  755. var decompositionLevelsCount = component.codingStyleParameters.decompositionLevelsCount;
  756. for (; py < precinctsIterationSizes.maxNumHigh; py++) {
  757. for (; px < precinctsIterationSizes.maxNumWide; px++) {
  758. for (; r <= decompositionLevelsCount; r++) {
  759. var resolution = component.resolutions[r];
  760. var sizeInImageScale = precinctsIterationSizes.resolutions[r];
  761. var k = getPrecinctIndexIfExist(px, py, sizeInImageScale, precinctsIterationSizes, resolution);
  762. if (k === null) {
  763. continue;
  764. }
  765. for (; l < layersCount;) {
  766. var 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. var posX = pxIndex * precinctIterationSizes.minWidth;
  783. var posY = pyIndex * precinctIterationSizes.minHeight;
  784. if (posX % sizeInImageScale.width !== 0 || posY % sizeInImageScale.height !== 0) {
  785. return null;
  786. }
  787. var startPrecinctRowIndex = posY / sizeInImageScale.width * resolution.precinctParameters.numprecinctswide;
  788. return posX / sizeInImageScale.height + startPrecinctRowIndex;
  789. }
  790. function getPrecinctSizesInImageScale(tile) {
  791. var componentsCount = tile.components.length;
  792. var minWidth = Number.MAX_VALUE;
  793. var minHeight = Number.MAX_VALUE;
  794. var maxNumWide = 0;
  795. var maxNumHigh = 0;
  796. var sizePerComponent = new Array(componentsCount);
  797. for (var c = 0; c < componentsCount; c++) {
  798. var component = tile.components[c];
  799. var decompositionLevelsCount = component.codingStyleParameters.decompositionLevelsCount;
  800. var sizePerResolution = new Array(decompositionLevelsCount + 1);
  801. var minWidthCurrentComponent = Number.MAX_VALUE;
  802. var minHeightCurrentComponent = Number.MAX_VALUE;
  803. var maxNumWideCurrentComponent = 0;
  804. var maxNumHighCurrentComponent = 0;
  805. var scale = 1;
  806. for (var r = decompositionLevelsCount; r >= 0; --r) {
  807. var resolution = component.resolutions[r];
  808. var widthCurrentResolution = scale * resolution.precinctParameters.precinctWidth;
  809. var 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. var siz = context.SIZ;
  842. var tileIndex = context.currentTile.index;
  843. var tile = context.tiles[tileIndex];
  844. var componentsCount = siz.Csiz;
  845. for (var c = 0; c < componentsCount; c++) {
  846. var component = tile.components[c];
  847. var decompositionLevelsCount = component.codingStyleParameters.decompositionLevelsCount;
  848. var resolutions = [];
  849. var subbands = [];
  850. for (var r = 0; r <= decompositionLevelsCount; r++) {
  851. var blocksDimensions = getBlocksDimensions(context, component, r);
  852. var resolution = {};
  853. var 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. var 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. var bscale = 1 << decompositionLevelsCount - r + 1;
  875. var 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. var 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. var position = 0;
  935. var buffer,
  936. bufferSize = 0,
  937. skipNextBit = false;
  938. function readBits(count) {
  939. while (bufferSize < count) {
  940. var 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. var 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. var tileIndex = context.currentTile.index;
  996. var tile = context.tiles[tileIndex];
  997. var sopMarkerUsed = context.COD.sopMarkerUsed;
  998. var ephMarkerUsed = context.COD.ephMarkerUsed;
  999. var packetsIterator = tile.packetsIterator;
  1000. while (position < dataLength) {
  1001. alignToByte();
  1002. if (sopMarkerUsed && skipMarkerIfEqual(0x91)) {
  1003. skipBytes(4);
  1004. }
  1005. var packet = packetsIterator.nextPacket();
  1006. if (!readBits(1)) {
  1007. continue;
  1008. }
  1009. var layerNumber = packet.layerNumber;
  1010. var queue = [],
  1011. codeblock;
  1012. for (var i = 0, ii = packet.codeblocks.length; i < ii; i++) {
  1013. codeblock = packet.codeblocks[i];
  1014. var precinct = codeblock.precinct;
  1015. var codeblockColumn = codeblock.cbx - precinct.cbxMin;
  1016. var codeblockRow = codeblock.cby - precinct.cbyMin;
  1017. var codeblockIncluded = false;
  1018. var firstTimeInclusion = false;
  1019. var valueReady;
  1020. if (codeblock.included !== undefined) {
  1021. codeblockIncluded = !!readBits(1);
  1022. } else {
  1023. precinct = codeblock.precinct;
  1024. var inclusionTree, zeroBitPlanesTree;
  1025. if (precinct.inclusionTree !== undefined) {
  1026. inclusionTree = precinct.inclusionTree;
  1027. } else {
  1028. var width = precinct.cbxMax - precinct.cbxMin + 1;
  1029. var 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. }
  1035. if (inclusionTree.reset(codeblockColumn, codeblockRow, layerNumber)) {
  1036. while (true) {
  1037. if (readBits(1)) {
  1038. valueReady = !inclusionTree.nextLevel();
  1039. if (valueReady) {
  1040. codeblock.included = true;
  1041. codeblockIncluded = firstTimeInclusion = true;
  1042. break;
  1043. }
  1044. } else {
  1045. inclusionTree.incrementValue(layerNumber);
  1046. break;
  1047. }
  1048. }
  1049. }
  1050. }
  1051. if (!codeblockIncluded) {
  1052. continue;
  1053. }
  1054. if (firstTimeInclusion) {
  1055. zeroBitPlanesTree = precinct.zeroBitPlanesTree;
  1056. zeroBitPlanesTree.reset(codeblockColumn, codeblockRow);
  1057. while (true) {
  1058. if (readBits(1)) {
  1059. valueReady = !zeroBitPlanesTree.nextLevel();
  1060. if (valueReady) {
  1061. break;
  1062. }
  1063. } else {
  1064. zeroBitPlanesTree.incrementValue();
  1065. }
  1066. }
  1067. codeblock.zeroBitPlanes = zeroBitPlanesTree.value;
  1068. }
  1069. var codingpasses = readCodingpasses();
  1070. while (readBits(1)) {
  1071. codeblock.Lblock++;
  1072. }
  1073. var codingpassesLog2 = (0, _core_utils.log2)(codingpasses);
  1074. var bits = (codingpasses < 1 << codingpassesLog2 ? codingpassesLog2 - 1 : codingpassesLog2) + codeblock.Lblock;
  1075. var codedDataLength = readBits(bits);
  1076. queue.push({
  1077. codeblock,
  1078. codingpasses,
  1079. dataLength: codedDataLength
  1080. });
  1081. }
  1082. alignToByte();
  1083. if (ephMarkerUsed) {
  1084. skipMarkerIfEqual(0x92);
  1085. }
  1086. while (queue.length > 0) {
  1087. var packetItem = queue.shift();
  1088. codeblock = packetItem.codeblock;
  1089. if (codeblock.data === undefined) {
  1090. codeblock.data = [];
  1091. }
  1092. codeblock.data.push({
  1093. data,
  1094. start: offset + position,
  1095. end: offset + position + packetItem.dataLength,
  1096. codingpasses: packetItem.codingpasses
  1097. });
  1098. position += packetItem.dataLength;
  1099. }
  1100. }
  1101. return position;
  1102. }
  1103. function copyCoefficients(coefficients, levelWidth, levelHeight, subband, delta, mb, reversible, segmentationSymbolUsed) {
  1104. var x0 = subband.tbx0;
  1105. var y0 = subband.tby0;
  1106. var width = subband.tbx1 - subband.tbx0;
  1107. var codeblocks = subband.codeblocks;
  1108. var right = subband.type.charAt(0) === "H" ? 1 : 0;
  1109. var bottom = subband.type.charAt(1) === "H" ? levelWidth : 0;
  1110. for (var i = 0, ii = codeblocks.length; i < ii; ++i) {
  1111. var codeblock = codeblocks[i];
  1112. var blockWidth = codeblock.tbx1_ - codeblock.tbx0_;
  1113. var blockHeight = codeblock.tby1_ - codeblock.tby0_;
  1114. if (blockWidth === 0 || blockHeight === 0) {
  1115. continue;
  1116. }
  1117. if (codeblock.data === undefined) {
  1118. continue;
  1119. }
  1120. var bitModel, currentCodingpassType;
  1121. bitModel = new BitModel(blockWidth, blockHeight, codeblock.subbandType, codeblock.zeroBitPlanes, mb);
  1122. currentCodingpassType = 2;
  1123. var data = codeblock.data,
  1124. totalLength = 0,
  1125. codingpasses = 0;
  1126. var j, jj, dataItem;
  1127. for (j = 0, jj = data.length; j < jj; j++) {
  1128. dataItem = data[j];
  1129. totalLength += dataItem.end - dataItem.start;
  1130. codingpasses += dataItem.codingpasses;
  1131. }
  1132. var encodedData = new Uint8Array(totalLength);
  1133. var position = 0;
  1134. for (j = 0, jj = data.length; j < jj; j++) {
  1135. dataItem = data[j];
  1136. var chunk = dataItem.data.subarray(dataItem.start, dataItem.end);
  1137. encodedData.set(chunk, position);
  1138. position += chunk.length;
  1139. }
  1140. var decoder = new _arithmetic_decoder.ArithmeticDecoder(encodedData, 0, totalLength);
  1141. bitModel.setDecoder(decoder);
  1142. for (j = 0; j < codingpasses; j++) {
  1143. switch (currentCodingpassType) {
  1144. case 0:
  1145. bitModel.runSignificancePropagationPass();
  1146. break;
  1147. case 1:
  1148. bitModel.runMagnitudeRefinementPass();
  1149. break;
  1150. case 2:
  1151. bitModel.runCleanupPass();
  1152. if (segmentationSymbolUsed) {
  1153. bitModel.checkSegmentationSymbol();
  1154. }
  1155. break;
  1156. }
  1157. currentCodingpassType = (currentCodingpassType + 1) % 3;
  1158. }
  1159. var offset = codeblock.tbx0_ - x0 + (codeblock.tby0_ - y0) * width;
  1160. var sign = bitModel.coefficentsSign;
  1161. var magnitude = bitModel.coefficentsMagnitude;
  1162. var bitsDecoded = bitModel.bitsDecoded;
  1163. var magnitudeCorrection = reversible ? 0 : 0.5;
  1164. var k, n, nb;
  1165. position = 0;
  1166. var interleave = subband.type !== "LL";
  1167. for (j = 0; j < blockHeight; j++) {
  1168. var row = offset / width | 0;
  1169. var levelOffset = 2 * row * (levelWidth - width) + right + bottom;
  1170. for (k = 0; k < blockWidth; k++) {
  1171. n = magnitude[position];
  1172. if (n !== 0) {
  1173. n = (n + magnitudeCorrection) * delta;
  1174. if (sign[position] !== 0) {
  1175. n = -n;
  1176. }
  1177. nb = bitsDecoded[position];
  1178. var pos = interleave ? levelOffset + (offset << 1) : offset;
  1179. if (reversible && nb >= mb) {
  1180. coefficients[pos] = n;
  1181. } else {
  1182. coefficients[pos] = n * (1 << mb - nb);
  1183. }
  1184. }
  1185. offset++;
  1186. position++;
  1187. }
  1188. offset += width - blockWidth;
  1189. }
  1190. }
  1191. }
  1192. function transformTile(context, tile, c) {
  1193. var component = tile.components[c];
  1194. var codingStyleParameters = component.codingStyleParameters;
  1195. var quantizationParameters = component.quantizationParameters;
  1196. var decompositionLevelsCount = codingStyleParameters.decompositionLevelsCount;
  1197. var spqcds = quantizationParameters.SPqcds;
  1198. var scalarExpounded = quantizationParameters.scalarExpounded;
  1199. var guardBits = quantizationParameters.guardBits;
  1200. var segmentationSymbolUsed = codingStyleParameters.segmentationSymbolUsed;
  1201. var precision = context.components[c].precision;
  1202. var reversible = codingStyleParameters.reversibleTransformation;
  1203. var transform = reversible ? new ReversibleTransform() : new IrreversibleTransform();
  1204. var subbandCoefficients = [];
  1205. var b = 0;
  1206. for (var i = 0; i <= decompositionLevelsCount; i++) {
  1207. var resolution = component.resolutions[i];
  1208. var width = resolution.trx1 - resolution.trx0;
  1209. var height = resolution.try1 - resolution.try0;
  1210. var coefficients = new Float32Array(width * height);
  1211. for (var j = 0, jj = resolution.subbands.length; j < jj; j++) {
  1212. var mu, epsilon;
  1213. if (!scalarExpounded) {
  1214. mu = spqcds[0].mu;
  1215. epsilon = spqcds[0].epsilon + (i > 0 ? 1 - i : 0);
  1216. } else {
  1217. mu = spqcds[b].mu;
  1218. epsilon = spqcds[b].epsilon;
  1219. b++;
  1220. }
  1221. var subband = resolution.subbands[j];
  1222. var gainLog2 = SubbandsGainLog2[subband.type];
  1223. var delta = reversible ? 1 : 2 ** (precision + gainLog2 - epsilon) * (1 + mu / 2048);
  1224. var mb = guardBits + epsilon - 1;
  1225. copyCoefficients(coefficients, width, height, subband, delta, mb, reversible, segmentationSymbolUsed);
  1226. }
  1227. subbandCoefficients.push({
  1228. width,
  1229. height,
  1230. items: coefficients
  1231. });
  1232. }
  1233. var result = transform.calculate(subbandCoefficients, component.tcx0, component.tcy0);
  1234. return {
  1235. left: component.tcx0,
  1236. top: component.tcy0,
  1237. width: result.width,
  1238. height: result.height,
  1239. items: result.items
  1240. };
  1241. }
  1242. function transformComponents(context) {
  1243. var siz = context.SIZ;
  1244. var components = context.components;
  1245. var componentsCount = siz.Csiz;
  1246. var resultImages = [];
  1247. for (var i = 0, ii = context.tiles.length; i < ii; i++) {
  1248. var tile = context.tiles[i];
  1249. var transformedTiles = [];
  1250. var c;
  1251. for (c = 0; c < componentsCount; c++) {
  1252. transformedTiles[c] = transformTile(context, tile, c);
  1253. }
  1254. var tile0 = transformedTiles[0];
  1255. var out = new Uint8ClampedArray(tile0.items.length * componentsCount);
  1256. var result = {
  1257. left: tile0.left,
  1258. top: tile0.top,
  1259. width: tile0.width,
  1260. height: tile0.height,
  1261. items: out
  1262. };
  1263. var shift, offset;
  1264. var pos = 0,
  1265. j,
  1266. jj,
  1267. y0,
  1268. y1,
  1269. y2;
  1270. if (tile.codingStyleDefaultParameters.multipleComponentTransform) {
  1271. var fourComponents = componentsCount === 4;
  1272. var y0items = transformedTiles[0].items;
  1273. var y1items = transformedTiles[1].items;
  1274. var y2items = transformedTiles[2].items;
  1275. var y3items = fourComponents ? transformedTiles[3].items : null;
  1276. shift = components[0].precision - 8;
  1277. offset = (128 << shift) + 0.5;
  1278. var component0 = tile.components[0];
  1279. var alpha01 = componentsCount - 3;
  1280. jj = y0items.length;
  1281. if (!component0.codingStyleParameters.reversibleTransformation) {
  1282. for (j = 0; j < jj; j++, pos += alpha01) {
  1283. y0 = y0items[j] + offset;
  1284. y1 = y1items[j];
  1285. y2 = y2items[j];
  1286. out[pos++] = y0 + 1.402 * y2 >> shift;
  1287. out[pos++] = y0 - 0.34413 * y1 - 0.71414 * y2 >> shift;
  1288. out[pos++] = y0 + 1.772 * y1 >> shift;
  1289. }
  1290. } else {
  1291. for (j = 0; j < jj; j++, pos += alpha01) {
  1292. y0 = y0items[j] + offset;
  1293. y1 = y1items[j];
  1294. y2 = y2items[j];
  1295. const g = y0 - (y2 + y1 >> 2);
  1296. out[pos++] = g + y2 >> shift;
  1297. out[pos++] = g >> shift;
  1298. out[pos++] = g + y1 >> shift;
  1299. }
  1300. }
  1301. if (fourComponents) {
  1302. for (j = 0, pos = 3; j < jj; j++, pos += 4) {
  1303. out[pos] = y3items[j] + offset >> shift;
  1304. }
  1305. }
  1306. } else {
  1307. for (c = 0; c < componentsCount; c++) {
  1308. var items = transformedTiles[c].items;
  1309. shift = components[c].precision - 8;
  1310. offset = (128 << shift) + 0.5;
  1311. for (pos = c, j = 0, jj = items.length; j < jj; j++) {
  1312. out[pos] = items[j] + offset >> shift;
  1313. pos += componentsCount;
  1314. }
  1315. }
  1316. }
  1317. resultImages.push(result);
  1318. }
  1319. return resultImages;
  1320. }
  1321. function initializeTile(context, tileIndex) {
  1322. var siz = context.SIZ;
  1323. var componentsCount = siz.Csiz;
  1324. var tile = context.tiles[tileIndex];
  1325. for (var c = 0; c < componentsCount; c++) {
  1326. var component = tile.components[c];
  1327. var qcdOrQcc = context.currentTile.QCC[c] !== undefined ? context.currentTile.QCC[c] : context.currentTile.QCD;
  1328. component.quantizationParameters = qcdOrQcc;
  1329. var codOrCoc = context.currentTile.COC[c] !== undefined ? context.currentTile.COC[c] : context.currentTile.COD;
  1330. component.codingStyleParameters = codOrCoc;
  1331. }
  1332. tile.codingStyleDefaultParameters = context.currentTile.COD;
  1333. }
  1334. var TagTree = function TagTreeClosure() {
  1335. function TagTree(width, height) {
  1336. var levelsLength = (0, _core_utils.log2)(Math.max(width, height)) + 1;
  1337. this.levels = [];
  1338. for (var i = 0; i < levelsLength; i++) {
  1339. var level = {
  1340. width,
  1341. height,
  1342. items: []
  1343. };
  1344. this.levels.push(level);
  1345. width = Math.ceil(width / 2);
  1346. height = Math.ceil(height / 2);
  1347. }
  1348. }
  1349. TagTree.prototype = {
  1350. reset: function TagTree_reset(i, j) {
  1351. var currentLevel = 0,
  1352. value = 0,
  1353. level;
  1354. while (currentLevel < this.levels.length) {
  1355. level = this.levels[currentLevel];
  1356. var index = i + j * level.width;
  1357. if (level.items[index] !== undefined) {
  1358. value = level.items[index];
  1359. break;
  1360. }
  1361. level.index = index;
  1362. i >>= 1;
  1363. j >>= 1;
  1364. currentLevel++;
  1365. }
  1366. currentLevel--;
  1367. level = this.levels[currentLevel];
  1368. level.items[level.index] = value;
  1369. this.currentLevel = currentLevel;
  1370. delete this.value;
  1371. },
  1372. incrementValue: function TagTree_incrementValue() {
  1373. var level = this.levels[this.currentLevel];
  1374. level.items[level.index]++;
  1375. },
  1376. nextLevel: function TagTree_nextLevel() {
  1377. var currentLevel = this.currentLevel;
  1378. var level = this.levels[currentLevel];
  1379. var value = level.items[level.index];
  1380. currentLevel--;
  1381. if (currentLevel < 0) {
  1382. this.value = value;
  1383. return false;
  1384. }
  1385. this.currentLevel = currentLevel;
  1386. level = this.levels[currentLevel];
  1387. level.items[level.index] = value;
  1388. return true;
  1389. }
  1390. };
  1391. return TagTree;
  1392. }();
  1393. var InclusionTree = function InclusionTreeClosure() {
  1394. function InclusionTree(width, height, defaultValue) {
  1395. var levelsLength = (0, _core_utils.log2)(Math.max(width, height)) + 1;
  1396. this.levels = [];
  1397. for (var i = 0; i < levelsLength; i++) {
  1398. var items = new Uint8Array(width * height);
  1399. for (var j = 0, jj = items.length; j < jj; j++) {
  1400. items[j] = defaultValue;
  1401. }
  1402. var 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. InclusionTree.prototype = {
  1413. reset: function InclusionTree_reset(i, j, stopValue) {
  1414. var currentLevel = 0;
  1415. while (currentLevel < this.levels.length) {
  1416. var level = this.levels[currentLevel];
  1417. var index = i + j * level.width;
  1418. level.index = index;
  1419. var value = level.items[index];
  1420. if (value === 0xff) {
  1421. break;
  1422. }
  1423. if (value > stopValue) {
  1424. this.currentLevel = currentLevel;
  1425. this.propagateValues();
  1426. return false;
  1427. }
  1428. i >>= 1;
  1429. j >>= 1;
  1430. currentLevel++;
  1431. }
  1432. this.currentLevel = currentLevel - 1;
  1433. return true;
  1434. },
  1435. incrementValue: function InclusionTree_incrementValue(stopValue) {
  1436. var level = this.levels[this.currentLevel];
  1437. level.items[level.index] = stopValue + 1;
  1438. this.propagateValues();
  1439. },
  1440. propagateValues: function InclusionTree_propagateValues() {
  1441. var levelIndex = this.currentLevel;
  1442. var level = this.levels[levelIndex];
  1443. var currentValue = level.items[level.index];
  1444. while (--levelIndex >= 0) {
  1445. level = this.levels[levelIndex];
  1446. level.items[level.index] = currentValue;
  1447. }
  1448. },
  1449. nextLevel: function InclusionTree_nextLevel() {
  1450. var currentLevel = this.currentLevel;
  1451. var level = this.levels[currentLevel];
  1452. var value = level.items[level.index];
  1453. level.items[level.index] = 0xff;
  1454. currentLevel--;
  1455. if (currentLevel < 0) {
  1456. return false;
  1457. }
  1458. this.currentLevel = currentLevel;
  1459. level = this.levels[currentLevel];
  1460. level.items[level.index] = value;
  1461. return true;
  1462. }
  1463. };
  1464. return InclusionTree;
  1465. }();
  1466. var BitModel = function BitModelClosure() {
  1467. var UNIFORM_CONTEXT = 17;
  1468. var RUNLENGTH_CONTEXT = 18;
  1469. 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]);
  1470. 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]);
  1471. 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]);
  1472. function BitModel(width, height, subband, zeroBitPlanes, mb) {
  1473. this.width = width;
  1474. this.height = height;
  1475. let contextLabelTable;
  1476. if (subband === "HH") {
  1477. contextLabelTable = HHContextLabel;
  1478. } else if (subband === "HL") {
  1479. contextLabelTable = HLContextLabel;
  1480. } else {
  1481. contextLabelTable = LLAndLHContextsLabel;
  1482. }
  1483. this.contextLabelTable = contextLabelTable;
  1484. var coefficientCount = width * height;
  1485. this.neighborsSignificance = new Uint8Array(coefficientCount);
  1486. this.coefficentsSign = new Uint8Array(coefficientCount);
  1487. let coefficentsMagnitude;
  1488. if (mb > 14) {
  1489. coefficentsMagnitude = new Uint32Array(coefficientCount);
  1490. } else if (mb > 6) {
  1491. coefficentsMagnitude = new Uint16Array(coefficientCount);
  1492. } else {
  1493. coefficentsMagnitude = new Uint8Array(coefficientCount);
  1494. }
  1495. this.coefficentsMagnitude = coefficentsMagnitude;
  1496. this.processingFlags = new Uint8Array(coefficientCount);
  1497. var bitsDecoded = new Uint8Array(coefficientCount);
  1498. if (zeroBitPlanes !== 0) {
  1499. for (var i = 0; i < coefficientCount; i++) {
  1500. bitsDecoded[i] = zeroBitPlanes;
  1501. }
  1502. }
  1503. this.bitsDecoded = bitsDecoded;
  1504. this.reset();
  1505. }
  1506. BitModel.prototype = {
  1507. setDecoder: function BitModel_setDecoder(decoder) {
  1508. this.decoder = decoder;
  1509. },
  1510. reset: function BitModel_reset() {
  1511. this.contexts = new Int8Array(19);
  1512. this.contexts[0] = 4 << 1 | 0;
  1513. this.contexts[UNIFORM_CONTEXT] = 46 << 1 | 0;
  1514. this.contexts[RUNLENGTH_CONTEXT] = 3 << 1 | 0;
  1515. },
  1516. setNeighborsSignificance: function BitModel_setNeighborsSignificance(row, column, index) {
  1517. var neighborsSignificance = this.neighborsSignificance;
  1518. var width = this.width,
  1519. height = this.height;
  1520. var left = column > 0;
  1521. var right = column + 1 < width;
  1522. var i;
  1523. if (row > 0) {
  1524. i = index - width;
  1525. if (left) {
  1526. neighborsSignificance[i - 1] += 0x10;
  1527. }
  1528. if (right) {
  1529. neighborsSignificance[i + 1] += 0x10;
  1530. }
  1531. neighborsSignificance[i] += 0x04;
  1532. }
  1533. if (row + 1 < height) {
  1534. i = index + width;
  1535. if (left) {
  1536. neighborsSignificance[i - 1] += 0x10;
  1537. }
  1538. if (right) {
  1539. neighborsSignificance[i + 1] += 0x10;
  1540. }
  1541. neighborsSignificance[i] += 0x04;
  1542. }
  1543. if (left) {
  1544. neighborsSignificance[index - 1] += 0x01;
  1545. }
  1546. if (right) {
  1547. neighborsSignificance[index + 1] += 0x01;
  1548. }
  1549. neighborsSignificance[index] |= 0x80;
  1550. },
  1551. runSignificancePropagationPass: function BitModel_runSignificancePropagationPass() {
  1552. var decoder = this.decoder;
  1553. var width = this.width,
  1554. height = this.height;
  1555. var coefficentsMagnitude = this.coefficentsMagnitude;
  1556. var coefficentsSign = this.coefficentsSign;
  1557. var neighborsSignificance = this.neighborsSignificance;
  1558. var processingFlags = this.processingFlags;
  1559. var contexts = this.contexts;
  1560. var labels = this.contextLabelTable;
  1561. var bitsDecoded = this.bitsDecoded;
  1562. var processedInverseMask = ~1;
  1563. var processedMask = 1;
  1564. var firstMagnitudeBitMask = 2;
  1565. for (var i0 = 0; i0 < height; i0 += 4) {
  1566. for (var j = 0; j < width; j++) {
  1567. var index = i0 * width + j;
  1568. for (var i1 = 0; i1 < 4; i1++, index += width) {
  1569. var i = i0 + i1;
  1570. if (i >= height) {
  1571. break;
  1572. }
  1573. processingFlags[index] &= processedInverseMask;
  1574. if (coefficentsMagnitude[index] || !neighborsSignificance[index]) {
  1575. continue;
  1576. }
  1577. var contextLabel = labels[neighborsSignificance[index]];
  1578. var decision = decoder.readBit(contexts, contextLabel);
  1579. if (decision) {
  1580. var sign = this.decodeSignBit(i, j, index);
  1581. coefficentsSign[index] = sign;
  1582. coefficentsMagnitude[index] = 1;
  1583. this.setNeighborsSignificance(i, j, index);
  1584. processingFlags[index] |= firstMagnitudeBitMask;
  1585. }
  1586. bitsDecoded[index]++;
  1587. processingFlags[index] |= processedMask;
  1588. }
  1589. }
  1590. }
  1591. },
  1592. decodeSignBit: function BitModel_decodeSignBit(row, column, index) {
  1593. var width = this.width,
  1594. height = this.height;
  1595. var coefficentsMagnitude = this.coefficentsMagnitude;
  1596. var coefficentsSign = this.coefficentsSign;
  1597. var contribution, sign0, sign1, significance1;
  1598. var contextLabel, decoded;
  1599. significance1 = column > 0 && coefficentsMagnitude[index - 1] !== 0;
  1600. if (column + 1 < width && coefficentsMagnitude[index + 1] !== 0) {
  1601. sign1 = coefficentsSign[index + 1];
  1602. if (significance1) {
  1603. sign0 = coefficentsSign[index - 1];
  1604. contribution = 1 - sign1 - sign0;
  1605. } else {
  1606. contribution = 1 - sign1 - sign1;
  1607. }
  1608. } else if (significance1) {
  1609. sign0 = coefficentsSign[index - 1];
  1610. contribution = 1 - sign0 - sign0;
  1611. } else {
  1612. contribution = 0;
  1613. }
  1614. var horizontalContribution = 3 * contribution;
  1615. significance1 = row > 0 && coefficentsMagnitude[index - width] !== 0;
  1616. if (row + 1 < height && coefficentsMagnitude[index + width] !== 0) {
  1617. sign1 = coefficentsSign[index + width];
  1618. if (significance1) {
  1619. sign0 = coefficentsSign[index - width];
  1620. contribution = 1 - sign1 - sign0 + horizontalContribution;
  1621. } else {
  1622. contribution = 1 - sign1 - sign1 + horizontalContribution;
  1623. }
  1624. } else if (significance1) {
  1625. sign0 = coefficentsSign[index - width];
  1626. contribution = 1 - sign0 - sign0 + horizontalContribution;
  1627. } else {
  1628. contribution = horizontalContribution;
  1629. }
  1630. if (contribution >= 0) {
  1631. contextLabel = 9 + contribution;
  1632. decoded = this.decoder.readBit(this.contexts, contextLabel);
  1633. } else {
  1634. contextLabel = 9 - contribution;
  1635. decoded = this.decoder.readBit(this.contexts, contextLabel) ^ 1;
  1636. }
  1637. return decoded;
  1638. },
  1639. runMagnitudeRefinementPass: function BitModel_runMagnitudeRefinementPass() {
  1640. var decoder = this.decoder;
  1641. var width = this.width,
  1642. height = this.height;
  1643. var coefficentsMagnitude = this.coefficentsMagnitude;
  1644. var neighborsSignificance = this.neighborsSignificance;
  1645. var contexts = this.contexts;
  1646. var bitsDecoded = this.bitsDecoded;
  1647. var processingFlags = this.processingFlags;
  1648. var processedMask = 1;
  1649. var firstMagnitudeBitMask = 2;
  1650. var length = width * height;
  1651. var width4 = width * 4;
  1652. for (var index0 = 0, indexNext; index0 < length; index0 = indexNext) {
  1653. indexNext = Math.min(length, index0 + width4);
  1654. for (var j = 0; j < width; j++) {
  1655. for (var index = index0 + j; index < indexNext; index += width) {
  1656. if (!coefficentsMagnitude[index] || (processingFlags[index] & processedMask) !== 0) {
  1657. continue;
  1658. }
  1659. var contextLabel = 16;
  1660. if ((processingFlags[index] & firstMagnitudeBitMask) !== 0) {
  1661. processingFlags[index] ^= firstMagnitudeBitMask;
  1662. var significance = neighborsSignificance[index] & 127;
  1663. contextLabel = significance === 0 ? 15 : 14;
  1664. }
  1665. var bit = decoder.readBit(contexts, contextLabel);
  1666. coefficentsMagnitude[index] = coefficentsMagnitude[index] << 1 | bit;
  1667. bitsDecoded[index]++;
  1668. processingFlags[index] |= processedMask;
  1669. }
  1670. }
  1671. }
  1672. },
  1673. runCleanupPass: function BitModel_runCleanupPass() {
  1674. var decoder = this.decoder;
  1675. var width = this.width,
  1676. height = this.height;
  1677. var neighborsSignificance = this.neighborsSignificance;
  1678. var coefficentsMagnitude = this.coefficentsMagnitude;
  1679. var coefficentsSign = this.coefficentsSign;
  1680. var contexts = this.contexts;
  1681. var labels = this.contextLabelTable;
  1682. var bitsDecoded = this.bitsDecoded;
  1683. var processingFlags = this.processingFlags;
  1684. var processedMask = 1;
  1685. var firstMagnitudeBitMask = 2;
  1686. var oneRowDown = width;
  1687. var twoRowsDown = width * 2;
  1688. var threeRowsDown = width * 3;
  1689. var iNext;
  1690. for (var i0 = 0; i0 < height; i0 = iNext) {
  1691. iNext = Math.min(i0 + 4, height);
  1692. var indexBase = i0 * width;
  1693. var checkAllEmpty = i0 + 3 < height;
  1694. for (var j = 0; j < width; j++) {
  1695. var index0 = indexBase + j;
  1696. 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;
  1697. var i1 = 0,
  1698. index = index0;
  1699. var i = i0,
  1700. sign;
  1701. if (allEmpty) {
  1702. var hasSignificantCoefficent = decoder.readBit(contexts, RUNLENGTH_CONTEXT);
  1703. if (!hasSignificantCoefficent) {
  1704. bitsDecoded[index0]++;
  1705. bitsDecoded[index0 + oneRowDown]++;
  1706. bitsDecoded[index0 + twoRowsDown]++;
  1707. bitsDecoded[index0 + threeRowsDown]++;
  1708. continue;
  1709. }
  1710. i1 = decoder.readBit(contexts, UNIFORM_CONTEXT) << 1 | decoder.readBit(contexts, UNIFORM_CONTEXT);
  1711. if (i1 !== 0) {
  1712. i = i0 + i1;
  1713. index += i1 * width;
  1714. }
  1715. sign = this.decodeSignBit(i, j, index);
  1716. coefficentsSign[index] = sign;
  1717. coefficentsMagnitude[index] = 1;
  1718. this.setNeighborsSignificance(i, j, index);
  1719. processingFlags[index] |= firstMagnitudeBitMask;
  1720. index = index0;
  1721. for (var i2 = i0; i2 <= i; i2++, index += width) {
  1722. bitsDecoded[index]++;
  1723. }
  1724. i1++;
  1725. }
  1726. for (i = i0 + i1; i < iNext; i++, index += width) {
  1727. if (coefficentsMagnitude[index] || (processingFlags[index] & processedMask) !== 0) {
  1728. continue;
  1729. }
  1730. var contextLabel = labels[neighborsSignificance[index]];
  1731. var decision = decoder.readBit(contexts, contextLabel);
  1732. if (decision === 1) {
  1733. sign = this.decodeSignBit(i, j, index);
  1734. coefficentsSign[index] = sign;
  1735. coefficentsMagnitude[index] = 1;
  1736. this.setNeighborsSignificance(i, j, index);
  1737. processingFlags[index] |= firstMagnitudeBitMask;
  1738. }
  1739. bitsDecoded[index]++;
  1740. }
  1741. }
  1742. }
  1743. },
  1744. checkSegmentationSymbol: function BitModel_checkSegmentationSymbol() {
  1745. var decoder = this.decoder;
  1746. var contexts = this.contexts;
  1747. 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);
  1748. if (symbol !== 0xa) {
  1749. throw new JpxError("Invalid segmentation symbol");
  1750. }
  1751. }
  1752. };
  1753. return BitModel;
  1754. }();
  1755. var Transform = function TransformClosure() {
  1756. function Transform() {}
  1757. Transform.prototype.calculate = function transformCalculate(subbands, u0, v0) {
  1758. var ll = subbands[0];
  1759. for (var i = 1, ii = subbands.length; i < ii; i++) {
  1760. ll = this.iterate(ll, subbands[i], u0, v0);
  1761. }
  1762. return ll;
  1763. };
  1764. Transform.prototype.extend = function extend(buffer, offset, size) {
  1765. var i1 = offset - 1,
  1766. j1 = offset + 1;
  1767. var i2 = offset + size - 2,
  1768. j2 = offset + size;
  1769. buffer[i1--] = buffer[j1++];
  1770. buffer[j2++] = buffer[i2--];
  1771. buffer[i1--] = buffer[j1++];
  1772. buffer[j2++] = buffer[i2--];
  1773. buffer[i1--] = buffer[j1++];
  1774. buffer[j2++] = buffer[i2--];
  1775. buffer[i1] = buffer[j1];
  1776. buffer[j2] = buffer[i2];
  1777. };
  1778. Transform.prototype.iterate = function Transform_iterate(ll, hl_lh_hh, u0, v0) {
  1779. var llWidth = ll.width,
  1780. llHeight = ll.height,
  1781. llItems = ll.items;
  1782. var width = hl_lh_hh.width;
  1783. var height = hl_lh_hh.height;
  1784. var items = hl_lh_hh.items;
  1785. var i, j, k, l, u, v;
  1786. for (k = 0, i = 0; i < llHeight; i++) {
  1787. l = i * 2 * width;
  1788. for (j = 0; j < llWidth; j++, k++, l += 2) {
  1789. items[l] = llItems[k];
  1790. }
  1791. }
  1792. llItems = ll.items = null;
  1793. var bufferPadding = 4;
  1794. var rowBuffer = new Float32Array(width + 2 * bufferPadding);
  1795. if (width === 1) {
  1796. if ((u0 & 1) !== 0) {
  1797. for (v = 0, k = 0; v < height; v++, k += width) {
  1798. items[k] *= 0.5;
  1799. }
  1800. }
  1801. } else {
  1802. for (v = 0, k = 0; v < height; v++, k += width) {
  1803. rowBuffer.set(items.subarray(k, k + width), bufferPadding);
  1804. this.extend(rowBuffer, bufferPadding, width);
  1805. this.filter(rowBuffer, bufferPadding, width);
  1806. items.set(rowBuffer.subarray(bufferPadding, bufferPadding + width), k);
  1807. }
  1808. }
  1809. var numBuffers = 16;
  1810. var colBuffers = [];
  1811. for (i = 0; i < numBuffers; i++) {
  1812. colBuffers.push(new Float32Array(height + 2 * bufferPadding));
  1813. }
  1814. var b,
  1815. currentBuffer = 0;
  1816. ll = bufferPadding + height;
  1817. if (height === 1) {
  1818. if ((v0 & 1) !== 0) {
  1819. for (u = 0; u < width; u++) {
  1820. items[u] *= 0.5;
  1821. }
  1822. }
  1823. } else {
  1824. for (u = 0; u < width; u++) {
  1825. if (currentBuffer === 0) {
  1826. numBuffers = Math.min(width - u, numBuffers);
  1827. for (k = u, l = bufferPadding; l < ll; k += width, l++) {
  1828. for (b = 0; b < numBuffers; b++) {
  1829. colBuffers[b][l] = items[k + b];
  1830. }
  1831. }
  1832. currentBuffer = numBuffers;
  1833. }
  1834. currentBuffer--;
  1835. var buffer = colBuffers[currentBuffer];
  1836. this.extend(buffer, bufferPadding, height);
  1837. this.filter(buffer, bufferPadding, height);
  1838. if (currentBuffer === 0) {
  1839. k = u - numBuffers + 1;
  1840. for (l = bufferPadding; l < ll; k += width, l++) {
  1841. for (b = 0; b < numBuffers; b++) {
  1842. items[k + b] = colBuffers[b][l];
  1843. }
  1844. }
  1845. }
  1846. }
  1847. }
  1848. return {
  1849. width,
  1850. height,
  1851. items
  1852. };
  1853. };
  1854. return Transform;
  1855. }();
  1856. var IrreversibleTransform = function IrreversibleTransformClosure() {
  1857. function IrreversibleTransform() {
  1858. Transform.call(this);
  1859. }
  1860. IrreversibleTransform.prototype = Object.create(Transform.prototype);
  1861. IrreversibleTransform.prototype.filter = function irreversibleTransformFilter(x, offset, length) {
  1862. var len = length >> 1;
  1863. offset = offset | 0;
  1864. var j, n, current, next;
  1865. var alpha = -1.586134342059924;
  1866. var beta = -0.052980118572961;
  1867. var gamma = 0.882911075530934;
  1868. var delta = 0.443506852043971;
  1869. var K = 1.230174104914001;
  1870. var K_ = 1 / K;
  1871. j = offset - 3;
  1872. for (n = len + 4; n--; j += 2) {
  1873. x[j] *= K_;
  1874. }
  1875. j = offset - 2;
  1876. current = delta * x[j - 1];
  1877. for (n = len + 3; n--; j += 2) {
  1878. next = delta * x[j + 1];
  1879. x[j] = K * x[j] - current - next;
  1880. if (n--) {
  1881. j += 2;
  1882. current = delta * x[j + 1];
  1883. x[j] = K * x[j] - current - next;
  1884. } else {
  1885. break;
  1886. }
  1887. }
  1888. j = offset - 1;
  1889. current = gamma * x[j - 1];
  1890. for (n = len + 2; n--; j += 2) {
  1891. next = gamma * x[j + 1];
  1892. x[j] -= current + next;
  1893. if (n--) {
  1894. j += 2;
  1895. current = gamma * x[j + 1];
  1896. x[j] -= current + next;
  1897. } else {
  1898. break;
  1899. }
  1900. }
  1901. j = offset;
  1902. current = beta * x[j - 1];
  1903. for (n = len + 1; n--; j += 2) {
  1904. next = beta * x[j + 1];
  1905. x[j] -= current + next;
  1906. if (n--) {
  1907. j += 2;
  1908. current = beta * x[j + 1];
  1909. x[j] -= current + next;
  1910. } else {
  1911. break;
  1912. }
  1913. }
  1914. if (len !== 0) {
  1915. j = offset + 1;
  1916. current = alpha * x[j - 1];
  1917. for (n = len; n--; j += 2) {
  1918. next = alpha * x[j + 1];
  1919. x[j] -= current + next;
  1920. if (n--) {
  1921. j += 2;
  1922. current = alpha * x[j + 1];
  1923. x[j] -= current + next;
  1924. } else {
  1925. break;
  1926. }
  1927. }
  1928. }
  1929. };
  1930. return IrreversibleTransform;
  1931. }();
  1932. var ReversibleTransform = function ReversibleTransformClosure() {
  1933. function ReversibleTransform() {
  1934. Transform.call(this);
  1935. }
  1936. ReversibleTransform.prototype = Object.create(Transform.prototype);
  1937. ReversibleTransform.prototype.filter = function reversibleTransformFilter(x, offset, length) {
  1938. var len = length >> 1;
  1939. offset = offset | 0;
  1940. var j, n;
  1941. for (j = offset, n = len + 1; n--; j += 2) {
  1942. x[j] -= x[j - 1] + x[j + 1] + 2 >> 2;
  1943. }
  1944. for (j = offset + 1, n = len; n--; j += 2) {
  1945. x[j] += x[j - 1] + x[j + 1] >> 1;
  1946. }
  1947. };
  1948. return ReversibleTransform;
  1949. }();
  1950. return JpxImage;
  1951. }();
  1952. exports.JpxImage = JpxImage;