jpx.js 68 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358
  1. /**
  2. * @licstart The following is the entire license notice for the
  3. * Javascript code in this page
  4. *
  5. * Copyright 2022 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.terminationOnEachCodingPass) {
  327. unsupported.push("terminationOnEachCodingPass");
  328. }
  329. if (cod.verticallyStripe) {
  330. unsupported.push("verticallyStripe");
  331. }
  332. if (cod.predictableTermination) {
  333. unsupported.push("predictableTermination");
  334. }
  335. if (unsupported.length > 0) {
  336. doNotRecover = true;
  337. (0, _util.warn)(`JPX: Unsupported COD options (${unsupported.join(", ")}).`);
  338. }
  339. if (context.mainHeader) {
  340. context.COD = cod;
  341. } else {
  342. context.currentTile.COD = cod;
  343. context.currentTile.COC = [];
  344. }
  345. break;
  346. case 0xff90:
  347. length = (0, _core_utils.readUint16)(data, position);
  348. tile = {};
  349. tile.index = (0, _core_utils.readUint16)(data, position + 2);
  350. tile.length = (0, _core_utils.readUint32)(data, position + 4);
  351. tile.dataEnd = tile.length + position - 2;
  352. tile.partIndex = data[position + 8];
  353. tile.partsCount = data[position + 9];
  354. context.mainHeader = false;
  355. if (tile.partIndex === 0) {
  356. tile.COD = context.COD;
  357. tile.COC = context.COC.slice(0);
  358. tile.QCD = context.QCD;
  359. tile.QCC = context.QCC.slice(0);
  360. }
  361. context.currentTile = tile;
  362. break;
  363. case 0xff93:
  364. tile = context.currentTile;
  365. if (tile.partIndex === 0) {
  366. initializeTile(context, tile.index);
  367. buildPackets(context);
  368. }
  369. length = tile.dataEnd - position;
  370. parseTilePackets(context, data, position, length);
  371. break;
  372. case 0xff53:
  373. (0, _util.warn)("JPX: Codestream code 0xFF53 (COC) is not implemented.");
  374. case 0xff55:
  375. case 0xff57:
  376. case 0xff58:
  377. case 0xff64:
  378. length = (0, _core_utils.readUint16)(data, position);
  379. break;
  380. default:
  381. throw new Error("Unknown codestream code: " + code.toString(16));
  382. }
  383. position += length;
  384. }
  385. } catch (e) {
  386. if (doNotRecover || this.failOnCorruptedImage) {
  387. throw new JpxError(e.message);
  388. } else {
  389. (0, _util.warn)(`JPX: Trying to recover from: "${e.message}".`);
  390. }
  391. }
  392. this.tiles = transformComponents(context);
  393. this.width = context.SIZ.Xsiz - context.SIZ.XOsiz;
  394. this.height = context.SIZ.Ysiz - context.SIZ.YOsiz;
  395. this.componentsCount = context.SIZ.Csiz;
  396. }
  397. }
  398. exports.JpxImage = JpxImage;
  399. function calculateComponentDimensions(component, siz) {
  400. component.x0 = Math.ceil(siz.XOsiz / component.XRsiz);
  401. component.x1 = Math.ceil(siz.Xsiz / component.XRsiz);
  402. component.y0 = Math.ceil(siz.YOsiz / component.YRsiz);
  403. component.y1 = Math.ceil(siz.Ysiz / component.YRsiz);
  404. component.width = component.x1 - component.x0;
  405. component.height = component.y1 - component.y0;
  406. }
  407. function calculateTileGrids(context, components) {
  408. const siz = context.SIZ;
  409. const tiles = [];
  410. let tile;
  411. const numXtiles = Math.ceil((siz.Xsiz - siz.XTOsiz) / siz.XTsiz);
  412. const numYtiles = Math.ceil((siz.Ysiz - siz.YTOsiz) / siz.YTsiz);
  413. for (let q = 0; q < numYtiles; q++) {
  414. for (let p = 0; p < numXtiles; p++) {
  415. tile = {};
  416. tile.tx0 = Math.max(siz.XTOsiz + p * siz.XTsiz, siz.XOsiz);
  417. tile.ty0 = Math.max(siz.YTOsiz + q * siz.YTsiz, siz.YOsiz);
  418. tile.tx1 = Math.min(siz.XTOsiz + (p + 1) * siz.XTsiz, siz.Xsiz);
  419. tile.ty1 = Math.min(siz.YTOsiz + (q + 1) * siz.YTsiz, siz.Ysiz);
  420. tile.width = tile.tx1 - tile.tx0;
  421. tile.height = tile.ty1 - tile.ty0;
  422. tile.components = [];
  423. tiles.push(tile);
  424. }
  425. }
  426. context.tiles = tiles;
  427. const componentsCount = siz.Csiz;
  428. for (let i = 0, ii = componentsCount; i < ii; i++) {
  429. const component = components[i];
  430. for (let j = 0, jj = tiles.length; j < jj; j++) {
  431. const tileComponent = {};
  432. tile = tiles[j];
  433. tileComponent.tcx0 = Math.ceil(tile.tx0 / component.XRsiz);
  434. tileComponent.tcy0 = Math.ceil(tile.ty0 / component.YRsiz);
  435. tileComponent.tcx1 = Math.ceil(tile.tx1 / component.XRsiz);
  436. tileComponent.tcy1 = Math.ceil(tile.ty1 / component.YRsiz);
  437. tileComponent.width = tileComponent.tcx1 - tileComponent.tcx0;
  438. tileComponent.height = tileComponent.tcy1 - tileComponent.tcy0;
  439. tile.components[i] = tileComponent;
  440. }
  441. }
  442. }
  443. function getBlocksDimensions(context, component, r) {
  444. const codOrCoc = component.codingStyleParameters;
  445. const result = {};
  446. if (!codOrCoc.entropyCoderWithCustomPrecincts) {
  447. result.PPx = 15;
  448. result.PPy = 15;
  449. } else {
  450. result.PPx = codOrCoc.precinctsSizes[r].PPx;
  451. result.PPy = codOrCoc.precinctsSizes[r].PPy;
  452. }
  453. result.xcb_ = r > 0 ? Math.min(codOrCoc.xcb, result.PPx - 1) : Math.min(codOrCoc.xcb, result.PPx);
  454. result.ycb_ = r > 0 ? Math.min(codOrCoc.ycb, result.PPy - 1) : Math.min(codOrCoc.ycb, result.PPy);
  455. return result;
  456. }
  457. function buildPrecincts(context, resolution, dimensions) {
  458. const precinctWidth = 1 << dimensions.PPx;
  459. const precinctHeight = 1 << dimensions.PPy;
  460. const isZeroRes = resolution.resLevel === 0;
  461. const precinctWidthInSubband = 1 << dimensions.PPx + (isZeroRes ? 0 : -1);
  462. const precinctHeightInSubband = 1 << dimensions.PPy + (isZeroRes ? 0 : -1);
  463. const numprecinctswide = resolution.trx1 > resolution.trx0 ? Math.ceil(resolution.trx1 / precinctWidth) - Math.floor(resolution.trx0 / precinctWidth) : 0;
  464. const numprecinctshigh = resolution.try1 > resolution.try0 ? Math.ceil(resolution.try1 / precinctHeight) - Math.floor(resolution.try0 / precinctHeight) : 0;
  465. const numprecincts = numprecinctswide * numprecinctshigh;
  466. resolution.precinctParameters = {
  467. precinctWidth,
  468. precinctHeight,
  469. numprecinctswide,
  470. numprecinctshigh,
  471. numprecincts,
  472. precinctWidthInSubband,
  473. precinctHeightInSubband
  474. };
  475. }
  476. function buildCodeblocks(context, subband, dimensions) {
  477. const xcb_ = dimensions.xcb_;
  478. const ycb_ = dimensions.ycb_;
  479. const codeblockWidth = 1 << xcb_;
  480. const codeblockHeight = 1 << ycb_;
  481. const cbx0 = subband.tbx0 >> xcb_;
  482. const cby0 = subband.tby0 >> ycb_;
  483. const cbx1 = subband.tbx1 + codeblockWidth - 1 >> xcb_;
  484. const cby1 = subband.tby1 + codeblockHeight - 1 >> ycb_;
  485. const precinctParameters = subband.resolution.precinctParameters;
  486. const codeblocks = [];
  487. const precincts = [];
  488. let i, j, codeblock, precinctNumber;
  489. for (j = cby0; j < cby1; j++) {
  490. for (i = cbx0; i < cbx1; i++) {
  491. codeblock = {
  492. cbx: i,
  493. cby: j,
  494. tbx0: codeblockWidth * i,
  495. tby0: codeblockHeight * j,
  496. tbx1: codeblockWidth * (i + 1),
  497. tby1: codeblockHeight * (j + 1)
  498. };
  499. codeblock.tbx0_ = Math.max(subband.tbx0, codeblock.tbx0);
  500. codeblock.tby0_ = Math.max(subband.tby0, codeblock.tby0);
  501. codeblock.tbx1_ = Math.min(subband.tbx1, codeblock.tbx1);
  502. codeblock.tby1_ = Math.min(subband.tby1, codeblock.tby1);
  503. const pi = Math.floor((codeblock.tbx0_ - subband.tbx0) / precinctParameters.precinctWidthInSubband);
  504. const pj = Math.floor((codeblock.tby0_ - subband.tby0) / precinctParameters.precinctHeightInSubband);
  505. precinctNumber = pi + pj * precinctParameters.numprecinctswide;
  506. codeblock.precinctNumber = precinctNumber;
  507. codeblock.subbandType = subband.type;
  508. codeblock.Lblock = 3;
  509. if (codeblock.tbx1_ <= codeblock.tbx0_ || codeblock.tby1_ <= codeblock.tby0_) {
  510. continue;
  511. }
  512. codeblocks.push(codeblock);
  513. let precinct = precincts[precinctNumber];
  514. if (precinct !== undefined) {
  515. if (i < precinct.cbxMin) {
  516. precinct.cbxMin = i;
  517. } else if (i > precinct.cbxMax) {
  518. precinct.cbxMax = i;
  519. }
  520. if (j < precinct.cbyMin) {
  521. precinct.cbxMin = j;
  522. } else if (j > precinct.cbyMax) {
  523. precinct.cbyMax = j;
  524. }
  525. } else {
  526. precincts[precinctNumber] = precinct = {
  527. cbxMin: i,
  528. cbyMin: j,
  529. cbxMax: i,
  530. cbyMax: j
  531. };
  532. }
  533. codeblock.precinct = precinct;
  534. }
  535. }
  536. subband.codeblockParameters = {
  537. codeblockWidth: xcb_,
  538. codeblockHeight: ycb_,
  539. numcodeblockwide: cbx1 - cbx0 + 1,
  540. numcodeblockhigh: cby1 - cby0 + 1
  541. };
  542. subband.codeblocks = codeblocks;
  543. subband.precincts = precincts;
  544. }
  545. function createPacket(resolution, precinctNumber, layerNumber) {
  546. const precinctCodeblocks = [];
  547. const subbands = resolution.subbands;
  548. for (let i = 0, ii = subbands.length; i < ii; i++) {
  549. const subband = subbands[i];
  550. const codeblocks = subband.codeblocks;
  551. for (let j = 0, jj = codeblocks.length; j < jj; j++) {
  552. const codeblock = codeblocks[j];
  553. if (codeblock.precinctNumber !== precinctNumber) {
  554. continue;
  555. }
  556. precinctCodeblocks.push(codeblock);
  557. }
  558. }
  559. return {
  560. layerNumber,
  561. codeblocks: precinctCodeblocks
  562. };
  563. }
  564. function LayerResolutionComponentPositionIterator(context) {
  565. const siz = context.SIZ;
  566. const tileIndex = context.currentTile.index;
  567. const tile = context.tiles[tileIndex];
  568. const layersCount = tile.codingStyleDefaultParameters.layersCount;
  569. const componentsCount = siz.Csiz;
  570. let maxDecompositionLevelsCount = 0;
  571. for (let q = 0; q < componentsCount; q++) {
  572. maxDecompositionLevelsCount = Math.max(maxDecompositionLevelsCount, tile.components[q].codingStyleParameters.decompositionLevelsCount);
  573. }
  574. let l = 0,
  575. r = 0,
  576. i = 0,
  577. k = 0;
  578. this.nextPacket = function JpxImage_nextPacket() {
  579. for (; l < layersCount; l++) {
  580. for (; r <= maxDecompositionLevelsCount; r++) {
  581. for (; i < componentsCount; i++) {
  582. const component = tile.components[i];
  583. if (r > component.codingStyleParameters.decompositionLevelsCount) {
  584. continue;
  585. }
  586. const resolution = component.resolutions[r];
  587. const numprecincts = resolution.precinctParameters.numprecincts;
  588. for (; k < numprecincts;) {
  589. const packet = createPacket(resolution, k, l);
  590. k++;
  591. return packet;
  592. }
  593. k = 0;
  594. }
  595. i = 0;
  596. }
  597. r = 0;
  598. }
  599. throw new JpxError("Out of packets");
  600. };
  601. }
  602. function ResolutionLayerComponentPositionIterator(context) {
  603. const siz = context.SIZ;
  604. const tileIndex = context.currentTile.index;
  605. const tile = context.tiles[tileIndex];
  606. const layersCount = tile.codingStyleDefaultParameters.layersCount;
  607. const componentsCount = siz.Csiz;
  608. let maxDecompositionLevelsCount = 0;
  609. for (let q = 0; q < componentsCount; q++) {
  610. maxDecompositionLevelsCount = Math.max(maxDecompositionLevelsCount, tile.components[q].codingStyleParameters.decompositionLevelsCount);
  611. }
  612. let r = 0,
  613. l = 0,
  614. i = 0,
  615. k = 0;
  616. this.nextPacket = function JpxImage_nextPacket() {
  617. for (; r <= maxDecompositionLevelsCount; r++) {
  618. for (; l < layersCount; l++) {
  619. for (; i < componentsCount; i++) {
  620. const component = tile.components[i];
  621. if (r > component.codingStyleParameters.decompositionLevelsCount) {
  622. continue;
  623. }
  624. const resolution = component.resolutions[r];
  625. const numprecincts = resolution.precinctParameters.numprecincts;
  626. for (; k < numprecincts;) {
  627. const packet = createPacket(resolution, k, l);
  628. k++;
  629. return packet;
  630. }
  631. k = 0;
  632. }
  633. i = 0;
  634. }
  635. l = 0;
  636. }
  637. throw new JpxError("Out of packets");
  638. };
  639. }
  640. function ResolutionPositionComponentLayerIterator(context) {
  641. const siz = context.SIZ;
  642. const tileIndex = context.currentTile.index;
  643. const tile = context.tiles[tileIndex];
  644. const layersCount = tile.codingStyleDefaultParameters.layersCount;
  645. const componentsCount = siz.Csiz;
  646. let l, r, c, p;
  647. let maxDecompositionLevelsCount = 0;
  648. for (c = 0; c < componentsCount; c++) {
  649. const component = tile.components[c];
  650. maxDecompositionLevelsCount = Math.max(maxDecompositionLevelsCount, component.codingStyleParameters.decompositionLevelsCount);
  651. }
  652. const maxNumPrecinctsInLevel = new Int32Array(maxDecompositionLevelsCount + 1);
  653. for (r = 0; r <= maxDecompositionLevelsCount; ++r) {
  654. let maxNumPrecincts = 0;
  655. for (c = 0; c < componentsCount; ++c) {
  656. const resolutions = tile.components[c].resolutions;
  657. if (r < resolutions.length) {
  658. maxNumPrecincts = Math.max(maxNumPrecincts, resolutions[r].precinctParameters.numprecincts);
  659. }
  660. }
  661. maxNumPrecinctsInLevel[r] = maxNumPrecincts;
  662. }
  663. l = 0;
  664. r = 0;
  665. c = 0;
  666. p = 0;
  667. this.nextPacket = function JpxImage_nextPacket() {
  668. for (; r <= maxDecompositionLevelsCount; r++) {
  669. for (; p < maxNumPrecinctsInLevel[r]; p++) {
  670. for (; c < componentsCount; c++) {
  671. const component = tile.components[c];
  672. if (r > component.codingStyleParameters.decompositionLevelsCount) {
  673. continue;
  674. }
  675. const resolution = component.resolutions[r];
  676. const numprecincts = resolution.precinctParameters.numprecincts;
  677. if (p >= numprecincts) {
  678. continue;
  679. }
  680. for (; l < layersCount;) {
  681. const packet = createPacket(resolution, p, l);
  682. l++;
  683. return packet;
  684. }
  685. l = 0;
  686. }
  687. c = 0;
  688. }
  689. p = 0;
  690. }
  691. throw new JpxError("Out of packets");
  692. };
  693. }
  694. function PositionComponentResolutionLayerIterator(context) {
  695. const siz = context.SIZ;
  696. const tileIndex = context.currentTile.index;
  697. const tile = context.tiles[tileIndex];
  698. const layersCount = tile.codingStyleDefaultParameters.layersCount;
  699. const componentsCount = siz.Csiz;
  700. const precinctsSizes = getPrecinctSizesInImageScale(tile);
  701. const precinctsIterationSizes = precinctsSizes;
  702. let l = 0,
  703. r = 0,
  704. c = 0,
  705. px = 0,
  706. py = 0;
  707. this.nextPacket = function JpxImage_nextPacket() {
  708. for (; py < precinctsIterationSizes.maxNumHigh; py++) {
  709. for (; px < precinctsIterationSizes.maxNumWide; px++) {
  710. for (; c < componentsCount; c++) {
  711. const component = tile.components[c];
  712. const decompositionLevelsCount = component.codingStyleParameters.decompositionLevelsCount;
  713. for (; r <= decompositionLevelsCount; r++) {
  714. const resolution = component.resolutions[r];
  715. const sizeInImageScale = precinctsSizes.components[c].resolutions[r];
  716. const k = getPrecinctIndexIfExist(px, py, sizeInImageScale, precinctsIterationSizes, resolution);
  717. if (k === null) {
  718. continue;
  719. }
  720. for (; l < layersCount;) {
  721. const packet = createPacket(resolution, k, l);
  722. l++;
  723. return packet;
  724. }
  725. l = 0;
  726. }
  727. r = 0;
  728. }
  729. c = 0;
  730. }
  731. px = 0;
  732. }
  733. throw new JpxError("Out of packets");
  734. };
  735. }
  736. function ComponentPositionResolutionLayerIterator(context) {
  737. const siz = context.SIZ;
  738. const tileIndex = context.currentTile.index;
  739. const tile = context.tiles[tileIndex];
  740. const layersCount = tile.codingStyleDefaultParameters.layersCount;
  741. const componentsCount = siz.Csiz;
  742. const precinctsSizes = getPrecinctSizesInImageScale(tile);
  743. let l = 0,
  744. r = 0,
  745. c = 0,
  746. px = 0,
  747. py = 0;
  748. this.nextPacket = function JpxImage_nextPacket() {
  749. for (; c < componentsCount; ++c) {
  750. const component = tile.components[c];
  751. const precinctsIterationSizes = precinctsSizes.components[c];
  752. const decompositionLevelsCount = component.codingStyleParameters.decompositionLevelsCount;
  753. for (; py < precinctsIterationSizes.maxNumHigh; py++) {
  754. for (; px < precinctsIterationSizes.maxNumWide; px++) {
  755. for (; r <= decompositionLevelsCount; r++) {
  756. const resolution = component.resolutions[r];
  757. const sizeInImageScale = precinctsIterationSizes.resolutions[r];
  758. const k = getPrecinctIndexIfExist(px, py, sizeInImageScale, precinctsIterationSizes, resolution);
  759. if (k === null) {
  760. continue;
  761. }
  762. for (; l < layersCount;) {
  763. const packet = createPacket(resolution, k, l);
  764. l++;
  765. return packet;
  766. }
  767. l = 0;
  768. }
  769. r = 0;
  770. }
  771. px = 0;
  772. }
  773. py = 0;
  774. }
  775. throw new JpxError("Out of packets");
  776. };
  777. }
  778. function getPrecinctIndexIfExist(pxIndex, pyIndex, sizeInImageScale, precinctIterationSizes, resolution) {
  779. const posX = pxIndex * precinctIterationSizes.minWidth;
  780. const posY = pyIndex * precinctIterationSizes.minHeight;
  781. if (posX % sizeInImageScale.width !== 0 || posY % sizeInImageScale.height !== 0) {
  782. return null;
  783. }
  784. const startPrecinctRowIndex = posY / sizeInImageScale.width * resolution.precinctParameters.numprecinctswide;
  785. return posX / sizeInImageScale.height + startPrecinctRowIndex;
  786. }
  787. function getPrecinctSizesInImageScale(tile) {
  788. const componentsCount = tile.components.length;
  789. let minWidth = Number.MAX_VALUE;
  790. let minHeight = Number.MAX_VALUE;
  791. let maxNumWide = 0;
  792. let maxNumHigh = 0;
  793. const sizePerComponent = new Array(componentsCount);
  794. for (let c = 0; c < componentsCount; c++) {
  795. const component = tile.components[c];
  796. const decompositionLevelsCount = component.codingStyleParameters.decompositionLevelsCount;
  797. const sizePerResolution = new Array(decompositionLevelsCount + 1);
  798. let minWidthCurrentComponent = Number.MAX_VALUE;
  799. let minHeightCurrentComponent = Number.MAX_VALUE;
  800. let maxNumWideCurrentComponent = 0;
  801. let maxNumHighCurrentComponent = 0;
  802. let scale = 1;
  803. for (let r = decompositionLevelsCount; r >= 0; --r) {
  804. const resolution = component.resolutions[r];
  805. const widthCurrentResolution = scale * resolution.precinctParameters.precinctWidth;
  806. const heightCurrentResolution = scale * resolution.precinctParameters.precinctHeight;
  807. minWidthCurrentComponent = Math.min(minWidthCurrentComponent, widthCurrentResolution);
  808. minHeightCurrentComponent = Math.min(minHeightCurrentComponent, heightCurrentResolution);
  809. maxNumWideCurrentComponent = Math.max(maxNumWideCurrentComponent, resolution.precinctParameters.numprecinctswide);
  810. maxNumHighCurrentComponent = Math.max(maxNumHighCurrentComponent, resolution.precinctParameters.numprecinctshigh);
  811. sizePerResolution[r] = {
  812. width: widthCurrentResolution,
  813. height: heightCurrentResolution
  814. };
  815. scale <<= 1;
  816. }
  817. minWidth = Math.min(minWidth, minWidthCurrentComponent);
  818. minHeight = Math.min(minHeight, minHeightCurrentComponent);
  819. maxNumWide = Math.max(maxNumWide, maxNumWideCurrentComponent);
  820. maxNumHigh = Math.max(maxNumHigh, maxNumHighCurrentComponent);
  821. sizePerComponent[c] = {
  822. resolutions: sizePerResolution,
  823. minWidth: minWidthCurrentComponent,
  824. minHeight: minHeightCurrentComponent,
  825. maxNumWide: maxNumWideCurrentComponent,
  826. maxNumHigh: maxNumHighCurrentComponent
  827. };
  828. }
  829. return {
  830. components: sizePerComponent,
  831. minWidth,
  832. minHeight,
  833. maxNumWide,
  834. maxNumHigh
  835. };
  836. }
  837. function buildPackets(context) {
  838. const siz = context.SIZ;
  839. const tileIndex = context.currentTile.index;
  840. const tile = context.tiles[tileIndex];
  841. const componentsCount = siz.Csiz;
  842. for (let c = 0; c < componentsCount; c++) {
  843. const component = tile.components[c];
  844. const decompositionLevelsCount = component.codingStyleParameters.decompositionLevelsCount;
  845. const resolutions = [];
  846. const subbands = [];
  847. for (let r = 0; r <= decompositionLevelsCount; r++) {
  848. const blocksDimensions = getBlocksDimensions(context, component, r);
  849. const resolution = {};
  850. const scale = 1 << decompositionLevelsCount - r;
  851. resolution.trx0 = Math.ceil(component.tcx0 / scale);
  852. resolution.try0 = Math.ceil(component.tcy0 / scale);
  853. resolution.trx1 = Math.ceil(component.tcx1 / scale);
  854. resolution.try1 = Math.ceil(component.tcy1 / scale);
  855. resolution.resLevel = r;
  856. buildPrecincts(context, resolution, blocksDimensions);
  857. resolutions.push(resolution);
  858. let subband;
  859. if (r === 0) {
  860. subband = {};
  861. subband.type = "LL";
  862. subband.tbx0 = Math.ceil(component.tcx0 / scale);
  863. subband.tby0 = Math.ceil(component.tcy0 / scale);
  864. subband.tbx1 = Math.ceil(component.tcx1 / scale);
  865. subband.tby1 = Math.ceil(component.tcy1 / scale);
  866. subband.resolution = resolution;
  867. buildCodeblocks(context, subband, blocksDimensions);
  868. subbands.push(subband);
  869. resolution.subbands = [subband];
  870. } else {
  871. const bscale = 1 << decompositionLevelsCount - r + 1;
  872. const resolutionSubbands = [];
  873. subband = {};
  874. subband.type = "HL";
  875. subband.tbx0 = Math.ceil(component.tcx0 / bscale - 0.5);
  876. subband.tby0 = Math.ceil(component.tcy0 / bscale);
  877. subband.tbx1 = Math.ceil(component.tcx1 / bscale - 0.5);
  878. subband.tby1 = Math.ceil(component.tcy1 / bscale);
  879. subband.resolution = resolution;
  880. buildCodeblocks(context, subband, blocksDimensions);
  881. subbands.push(subband);
  882. resolutionSubbands.push(subband);
  883. subband = {};
  884. subband.type = "LH";
  885. subband.tbx0 = Math.ceil(component.tcx0 / bscale);
  886. subband.tby0 = Math.ceil(component.tcy0 / bscale - 0.5);
  887. subband.tbx1 = Math.ceil(component.tcx1 / bscale);
  888. subband.tby1 = Math.ceil(component.tcy1 / bscale - 0.5);
  889. subband.resolution = resolution;
  890. buildCodeblocks(context, subband, blocksDimensions);
  891. subbands.push(subband);
  892. resolutionSubbands.push(subband);
  893. subband = {};
  894. subband.type = "HH";
  895. subband.tbx0 = Math.ceil(component.tcx0 / bscale - 0.5);
  896. subband.tby0 = Math.ceil(component.tcy0 / bscale - 0.5);
  897. subband.tbx1 = Math.ceil(component.tcx1 / bscale - 0.5);
  898. subband.tby1 = Math.ceil(component.tcy1 / bscale - 0.5);
  899. subband.resolution = resolution;
  900. buildCodeblocks(context, subband, blocksDimensions);
  901. subbands.push(subband);
  902. resolutionSubbands.push(subband);
  903. resolution.subbands = resolutionSubbands;
  904. }
  905. }
  906. component.resolutions = resolutions;
  907. component.subbands = subbands;
  908. }
  909. const progressionOrder = tile.codingStyleDefaultParameters.progressionOrder;
  910. switch (progressionOrder) {
  911. case 0:
  912. tile.packetsIterator = new LayerResolutionComponentPositionIterator(context);
  913. break;
  914. case 1:
  915. tile.packetsIterator = new ResolutionLayerComponentPositionIterator(context);
  916. break;
  917. case 2:
  918. tile.packetsIterator = new ResolutionPositionComponentLayerIterator(context);
  919. break;
  920. case 3:
  921. tile.packetsIterator = new PositionComponentResolutionLayerIterator(context);
  922. break;
  923. case 4:
  924. tile.packetsIterator = new ComponentPositionResolutionLayerIterator(context);
  925. break;
  926. default:
  927. throw new JpxError(`Unsupported progression order ${progressionOrder}`);
  928. }
  929. }
  930. function parseTilePackets(context, data, offset, dataLength) {
  931. let position = 0;
  932. let buffer,
  933. bufferSize = 0,
  934. skipNextBit = false;
  935. function readBits(count) {
  936. while (bufferSize < count) {
  937. const b = data[offset + position];
  938. position++;
  939. if (skipNextBit) {
  940. buffer = buffer << 7 | b;
  941. bufferSize += 7;
  942. skipNextBit = false;
  943. } else {
  944. buffer = buffer << 8 | b;
  945. bufferSize += 8;
  946. }
  947. if (b === 0xff) {
  948. skipNextBit = true;
  949. }
  950. }
  951. bufferSize -= count;
  952. return buffer >>> bufferSize & (1 << count) - 1;
  953. }
  954. function skipMarkerIfEqual(value) {
  955. if (data[offset + position - 1] === 0xff && data[offset + position] === value) {
  956. skipBytes(1);
  957. return true;
  958. } else if (data[offset + position] === 0xff && data[offset + position + 1] === value) {
  959. skipBytes(2);
  960. return true;
  961. }
  962. return false;
  963. }
  964. function skipBytes(count) {
  965. position += count;
  966. }
  967. function alignToByte() {
  968. bufferSize = 0;
  969. if (skipNextBit) {
  970. position++;
  971. skipNextBit = false;
  972. }
  973. }
  974. function readCodingpasses() {
  975. if (readBits(1) === 0) {
  976. return 1;
  977. }
  978. if (readBits(1) === 0) {
  979. return 2;
  980. }
  981. let value = readBits(2);
  982. if (value < 3) {
  983. return value + 3;
  984. }
  985. value = readBits(5);
  986. if (value < 31) {
  987. return value + 6;
  988. }
  989. value = readBits(7);
  990. return value + 37;
  991. }
  992. const tileIndex = context.currentTile.index;
  993. const tile = context.tiles[tileIndex];
  994. const sopMarkerUsed = context.COD.sopMarkerUsed;
  995. const ephMarkerUsed = context.COD.ephMarkerUsed;
  996. const packetsIterator = tile.packetsIterator;
  997. while (position < dataLength) {
  998. alignToByte();
  999. if (sopMarkerUsed && skipMarkerIfEqual(0x91)) {
  1000. skipBytes(4);
  1001. }
  1002. const packet = packetsIterator.nextPacket();
  1003. if (!readBits(1)) {
  1004. continue;
  1005. }
  1006. const layerNumber = packet.layerNumber,
  1007. queue = [];
  1008. let codeblock;
  1009. for (let i = 0, ii = packet.codeblocks.length; i < ii; i++) {
  1010. codeblock = packet.codeblocks[i];
  1011. let precinct = codeblock.precinct;
  1012. const codeblockColumn = codeblock.cbx - precinct.cbxMin;
  1013. const codeblockRow = codeblock.cby - precinct.cbyMin;
  1014. let codeblockIncluded = false;
  1015. let firstTimeInclusion = false;
  1016. let valueReady, zeroBitPlanesTree;
  1017. if (codeblock.included !== undefined) {
  1018. codeblockIncluded = !!readBits(1);
  1019. } else {
  1020. precinct = codeblock.precinct;
  1021. let inclusionTree;
  1022. if (precinct.inclusionTree !== undefined) {
  1023. inclusionTree = precinct.inclusionTree;
  1024. } else {
  1025. const width = precinct.cbxMax - precinct.cbxMin + 1;
  1026. const height = precinct.cbyMax - precinct.cbyMin + 1;
  1027. inclusionTree = new InclusionTree(width, height, layerNumber);
  1028. zeroBitPlanesTree = new TagTree(width, height);
  1029. precinct.inclusionTree = inclusionTree;
  1030. precinct.zeroBitPlanesTree = zeroBitPlanesTree;
  1031. for (let l = 0; l < layerNumber; l++) {
  1032. if (readBits(1) !== 0) {
  1033. throw new JpxError("Invalid tag tree");
  1034. }
  1035. }
  1036. }
  1037. if (inclusionTree.reset(codeblockColumn, codeblockRow, layerNumber)) {
  1038. while (true) {
  1039. if (readBits(1)) {
  1040. valueReady = !inclusionTree.nextLevel();
  1041. if (valueReady) {
  1042. codeblock.included = true;
  1043. codeblockIncluded = firstTimeInclusion = true;
  1044. break;
  1045. }
  1046. } else {
  1047. inclusionTree.incrementValue(layerNumber);
  1048. break;
  1049. }
  1050. }
  1051. }
  1052. }
  1053. if (!codeblockIncluded) {
  1054. continue;
  1055. }
  1056. if (firstTimeInclusion) {
  1057. zeroBitPlanesTree = precinct.zeroBitPlanesTree;
  1058. zeroBitPlanesTree.reset(codeblockColumn, codeblockRow);
  1059. while (true) {
  1060. if (readBits(1)) {
  1061. valueReady = !zeroBitPlanesTree.nextLevel();
  1062. if (valueReady) {
  1063. break;
  1064. }
  1065. } else {
  1066. zeroBitPlanesTree.incrementValue();
  1067. }
  1068. }
  1069. codeblock.zeroBitPlanes = zeroBitPlanesTree.value;
  1070. }
  1071. const codingpasses = readCodingpasses();
  1072. while (readBits(1)) {
  1073. codeblock.Lblock++;
  1074. }
  1075. const codingpassesLog2 = (0, _core_utils.log2)(codingpasses);
  1076. const bits = (codingpasses < 1 << codingpassesLog2 ? codingpassesLog2 - 1 : codingpassesLog2) + codeblock.Lblock;
  1077. const codedDataLength = readBits(bits);
  1078. queue.push({
  1079. codeblock,
  1080. codingpasses,
  1081. dataLength: codedDataLength
  1082. });
  1083. }
  1084. alignToByte();
  1085. if (ephMarkerUsed) {
  1086. skipMarkerIfEqual(0x92);
  1087. }
  1088. while (queue.length > 0) {
  1089. const packetItem = queue.shift();
  1090. codeblock = packetItem.codeblock;
  1091. if (codeblock.data === undefined) {
  1092. codeblock.data = [];
  1093. }
  1094. codeblock.data.push({
  1095. data,
  1096. start: offset + position,
  1097. end: offset + position + packetItem.dataLength,
  1098. codingpasses: packetItem.codingpasses
  1099. });
  1100. position += packetItem.dataLength;
  1101. }
  1102. }
  1103. return position;
  1104. }
  1105. function copyCoefficients(coefficients, levelWidth, levelHeight, subband, delta, mb, reversible, segmentationSymbolUsed, resetContextProbabilities) {
  1106. const x0 = subband.tbx0;
  1107. const y0 = subband.tby0;
  1108. const width = subband.tbx1 - subband.tbx0;
  1109. const codeblocks = subband.codeblocks;
  1110. const right = subband.type.charAt(0) === "H" ? 1 : 0;
  1111. const bottom = subband.type.charAt(1) === "H" ? levelWidth : 0;
  1112. for (let i = 0, ii = codeblocks.length; i < ii; ++i) {
  1113. const codeblock = codeblocks[i];
  1114. const blockWidth = codeblock.tbx1_ - codeblock.tbx0_;
  1115. const blockHeight = codeblock.tby1_ - codeblock.tby0_;
  1116. if (blockWidth === 0 || blockHeight === 0) {
  1117. continue;
  1118. }
  1119. if (codeblock.data === undefined) {
  1120. continue;
  1121. }
  1122. const bitModel = new BitModel(blockWidth, blockHeight, codeblock.subbandType, codeblock.zeroBitPlanes, mb);
  1123. let currentCodingpassType = 2;
  1124. const data = codeblock.data;
  1125. let totalLength = 0,
  1126. codingpasses = 0;
  1127. let j, jj, dataItem;
  1128. for (j = 0, jj = data.length; j < jj; j++) {
  1129. dataItem = data[j];
  1130. totalLength += dataItem.end - dataItem.start;
  1131. codingpasses += dataItem.codingpasses;
  1132. }
  1133. const encodedData = new Uint8Array(totalLength);
  1134. let position = 0;
  1135. for (j = 0, jj = data.length; j < jj; j++) {
  1136. dataItem = data[j];
  1137. const chunk = dataItem.data.subarray(dataItem.start, dataItem.end);
  1138. encodedData.set(chunk, position);
  1139. position += chunk.length;
  1140. }
  1141. const decoder = new _arithmetic_decoder.ArithmeticDecoder(encodedData, 0, totalLength);
  1142. bitModel.setDecoder(decoder);
  1143. for (j = 0; j < codingpasses; j++) {
  1144. switch (currentCodingpassType) {
  1145. case 0:
  1146. bitModel.runSignificancePropagationPass();
  1147. break;
  1148. case 1:
  1149. bitModel.runMagnitudeRefinementPass();
  1150. break;
  1151. case 2:
  1152. bitModel.runCleanupPass();
  1153. if (segmentationSymbolUsed) {
  1154. bitModel.checkSegmentationSymbol();
  1155. }
  1156. break;
  1157. }
  1158. if (resetContextProbabilities) {
  1159. bitModel.reset();
  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 resetContextProbabilities = codingStyleParameters.resetContextProbabilities;
  1206. const precision = context.components[c].precision;
  1207. const reversible = codingStyleParameters.reversibleTransformation;
  1208. const transform = reversible ? new ReversibleTransform() : new IrreversibleTransform();
  1209. const subbandCoefficients = [];
  1210. let b = 0;
  1211. for (let i = 0; i <= decompositionLevelsCount; i++) {
  1212. const resolution = component.resolutions[i];
  1213. const width = resolution.trx1 - resolution.trx0;
  1214. const height = resolution.try1 - resolution.try0;
  1215. const coefficients = new Float32Array(width * height);
  1216. for (let j = 0, jj = resolution.subbands.length; j < jj; j++) {
  1217. let mu, epsilon;
  1218. if (!scalarExpounded) {
  1219. mu = spqcds[0].mu;
  1220. epsilon = spqcds[0].epsilon + (i > 0 ? 1 - i : 0);
  1221. } else {
  1222. mu = spqcds[b].mu;
  1223. epsilon = spqcds[b].epsilon;
  1224. b++;
  1225. }
  1226. const subband = resolution.subbands[j];
  1227. const gainLog2 = SubbandsGainLog2[subband.type];
  1228. const delta = reversible ? 1 : 2 ** (precision + gainLog2 - epsilon) * (1 + mu / 2048);
  1229. const mb = guardBits + epsilon - 1;
  1230. copyCoefficients(coefficients, width, height, subband, delta, mb, reversible, segmentationSymbolUsed, resetContextProbabilities);
  1231. }
  1232. subbandCoefficients.push({
  1233. width,
  1234. height,
  1235. items: coefficients
  1236. });
  1237. }
  1238. const result = transform.calculate(subbandCoefficients, component.tcx0, component.tcy0);
  1239. return {
  1240. left: component.tcx0,
  1241. top: component.tcy0,
  1242. width: result.width,
  1243. height: result.height,
  1244. items: result.items
  1245. };
  1246. }
  1247. function transformComponents(context) {
  1248. const siz = context.SIZ;
  1249. const components = context.components;
  1250. const componentsCount = siz.Csiz;
  1251. const resultImages = [];
  1252. for (let i = 0, ii = context.tiles.length; i < ii; i++) {
  1253. const tile = context.tiles[i];
  1254. const transformedTiles = [];
  1255. for (let c = 0; c < componentsCount; c++) {
  1256. transformedTiles[c] = transformTile(context, tile, c);
  1257. }
  1258. const tile0 = transformedTiles[0];
  1259. const out = new Uint8ClampedArray(tile0.items.length * componentsCount);
  1260. const result = {
  1261. left: tile0.left,
  1262. top: tile0.top,
  1263. width: tile0.width,
  1264. height: tile0.height,
  1265. items: out
  1266. };
  1267. let shift, offset;
  1268. let pos = 0,
  1269. j,
  1270. jj,
  1271. y0,
  1272. y1,
  1273. y2;
  1274. if (tile.codingStyleDefaultParameters.multipleComponentTransform) {
  1275. const fourComponents = componentsCount === 4;
  1276. const y0items = transformedTiles[0].items;
  1277. const y1items = transformedTiles[1].items;
  1278. const y2items = transformedTiles[2].items;
  1279. const y3items = fourComponents ? transformedTiles[3].items : null;
  1280. shift = components[0].precision - 8;
  1281. offset = (128 << shift) + 0.5;
  1282. const component0 = tile.components[0];
  1283. const alpha01 = componentsCount - 3;
  1284. jj = y0items.length;
  1285. if (!component0.codingStyleParameters.reversibleTransformation) {
  1286. for (j = 0; j < jj; j++, pos += alpha01) {
  1287. y0 = y0items[j] + offset;
  1288. y1 = y1items[j];
  1289. y2 = y2items[j];
  1290. out[pos++] = y0 + 1.402 * y2 >> shift;
  1291. out[pos++] = y0 - 0.34413 * y1 - 0.71414 * y2 >> shift;
  1292. out[pos++] = y0 + 1.772 * y1 >> shift;
  1293. }
  1294. } else {
  1295. for (j = 0; j < jj; j++, pos += alpha01) {
  1296. y0 = y0items[j] + offset;
  1297. y1 = y1items[j];
  1298. y2 = y2items[j];
  1299. const g = y0 - (y2 + y1 >> 2);
  1300. out[pos++] = g + y2 >> shift;
  1301. out[pos++] = g >> shift;
  1302. out[pos++] = g + y1 >> shift;
  1303. }
  1304. }
  1305. if (fourComponents) {
  1306. for (j = 0, pos = 3; j < jj; j++, pos += 4) {
  1307. out[pos] = y3items[j] + offset >> shift;
  1308. }
  1309. }
  1310. } else {
  1311. for (let c = 0; c < componentsCount; c++) {
  1312. const items = transformedTiles[c].items;
  1313. shift = components[c].precision - 8;
  1314. offset = (128 << shift) + 0.5;
  1315. for (pos = c, j = 0, jj = items.length; j < jj; j++) {
  1316. out[pos] = items[j] + offset >> shift;
  1317. pos += componentsCount;
  1318. }
  1319. }
  1320. }
  1321. resultImages.push(result);
  1322. }
  1323. return resultImages;
  1324. }
  1325. function initializeTile(context, tileIndex) {
  1326. const siz = context.SIZ;
  1327. const componentsCount = siz.Csiz;
  1328. const tile = context.tiles[tileIndex];
  1329. for (let c = 0; c < componentsCount; c++) {
  1330. const component = tile.components[c];
  1331. const qcdOrQcc = context.currentTile.QCC[c] !== undefined ? context.currentTile.QCC[c] : context.currentTile.QCD;
  1332. component.quantizationParameters = qcdOrQcc;
  1333. const codOrCoc = context.currentTile.COC[c] !== undefined ? context.currentTile.COC[c] : context.currentTile.COD;
  1334. component.codingStyleParameters = codOrCoc;
  1335. }
  1336. tile.codingStyleDefaultParameters = context.currentTile.COD;
  1337. }
  1338. class TagTree {
  1339. constructor(width, height) {
  1340. const levelsLength = (0, _core_utils.log2)(Math.max(width, height)) + 1;
  1341. this.levels = [];
  1342. for (let i = 0; i < levelsLength; i++) {
  1343. const level = {
  1344. width,
  1345. height,
  1346. items: []
  1347. };
  1348. this.levels.push(level);
  1349. width = Math.ceil(width / 2);
  1350. height = Math.ceil(height / 2);
  1351. }
  1352. }
  1353. reset(i, j) {
  1354. let currentLevel = 0,
  1355. value = 0,
  1356. level;
  1357. while (currentLevel < this.levels.length) {
  1358. level = this.levels[currentLevel];
  1359. const index = i + j * level.width;
  1360. if (level.items[index] !== undefined) {
  1361. value = level.items[index];
  1362. break;
  1363. }
  1364. level.index = index;
  1365. i >>= 1;
  1366. j >>= 1;
  1367. currentLevel++;
  1368. }
  1369. currentLevel--;
  1370. level = this.levels[currentLevel];
  1371. level.items[level.index] = value;
  1372. this.currentLevel = currentLevel;
  1373. delete this.value;
  1374. }
  1375. incrementValue() {
  1376. const level = this.levels[this.currentLevel];
  1377. level.items[level.index]++;
  1378. }
  1379. nextLevel() {
  1380. let currentLevel = this.currentLevel;
  1381. let level = this.levels[currentLevel];
  1382. const value = level.items[level.index];
  1383. currentLevel--;
  1384. if (currentLevel < 0) {
  1385. this.value = value;
  1386. return false;
  1387. }
  1388. this.currentLevel = currentLevel;
  1389. level = this.levels[currentLevel];
  1390. level.items[level.index] = value;
  1391. return true;
  1392. }
  1393. }
  1394. class InclusionTree {
  1395. constructor(width, height, defaultValue) {
  1396. const levelsLength = (0, _core_utils.log2)(Math.max(width, height)) + 1;
  1397. this.levels = [];
  1398. for (let i = 0; i < levelsLength; i++) {
  1399. const items = new Uint8Array(width * height);
  1400. for (let j = 0, jj = items.length; j < jj; j++) {
  1401. items[j] = defaultValue;
  1402. }
  1403. const level = {
  1404. width,
  1405. height,
  1406. items
  1407. };
  1408. this.levels.push(level);
  1409. width = Math.ceil(width / 2);
  1410. height = Math.ceil(height / 2);
  1411. }
  1412. }
  1413. reset(i, j, stopValue) {
  1414. let currentLevel = 0;
  1415. while (currentLevel < this.levels.length) {
  1416. const level = this.levels[currentLevel];
  1417. const index = i + j * level.width;
  1418. level.index = index;
  1419. const 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(stopValue) {
  1436. const level = this.levels[this.currentLevel];
  1437. level.items[level.index] = stopValue + 1;
  1438. this.propagateValues();
  1439. }
  1440. propagateValues() {
  1441. let levelIndex = this.currentLevel;
  1442. let level = this.levels[levelIndex];
  1443. const currentValue = level.items[level.index];
  1444. while (--levelIndex >= 0) {
  1445. level = this.levels[levelIndex];
  1446. level.items[level.index] = currentValue;
  1447. }
  1448. }
  1449. nextLevel() {
  1450. let currentLevel = this.currentLevel;
  1451. let level = this.levels[currentLevel];
  1452. const 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. const BitModel = function BitModelClosure() {
  1465. const UNIFORM_CONTEXT = 17;
  1466. const RUNLENGTH_CONTEXT = 18;
  1467. 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]);
  1468. 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]);
  1469. 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]);
  1470. class BitModel {
  1471. constructor(width, height, subband, zeroBitPlanes, mb) {
  1472. this.width = width;
  1473. this.height = height;
  1474. let contextLabelTable;
  1475. if (subband === "HH") {
  1476. contextLabelTable = HHContextLabel;
  1477. } else if (subband === "HL") {
  1478. contextLabelTable = HLContextLabel;
  1479. } else {
  1480. contextLabelTable = LLAndLHContextsLabel;
  1481. }
  1482. this.contextLabelTable = contextLabelTable;
  1483. const coefficientCount = width * height;
  1484. this.neighborsSignificance = new Uint8Array(coefficientCount);
  1485. this.coefficentsSign = new Uint8Array(coefficientCount);
  1486. let coefficentsMagnitude;
  1487. if (mb > 14) {
  1488. coefficentsMagnitude = new Uint32Array(coefficientCount);
  1489. } else if (mb > 6) {
  1490. coefficentsMagnitude = new Uint16Array(coefficientCount);
  1491. } else {
  1492. coefficentsMagnitude = new Uint8Array(coefficientCount);
  1493. }
  1494. this.coefficentsMagnitude = coefficentsMagnitude;
  1495. this.processingFlags = new Uint8Array(coefficientCount);
  1496. const bitsDecoded = new Uint8Array(coefficientCount);
  1497. if (zeroBitPlanes !== 0) {
  1498. for (let i = 0; i < coefficientCount; i++) {
  1499. bitsDecoded[i] = zeroBitPlanes;
  1500. }
  1501. }
  1502. this.bitsDecoded = bitsDecoded;
  1503. this.reset();
  1504. }
  1505. setDecoder(decoder) {
  1506. this.decoder = decoder;
  1507. }
  1508. reset() {
  1509. this.contexts = new Int8Array(19);
  1510. this.contexts[0] = 4 << 1 | 0;
  1511. this.contexts[UNIFORM_CONTEXT] = 46 << 1 | 0;
  1512. this.contexts[RUNLENGTH_CONTEXT] = 3 << 1 | 0;
  1513. }
  1514. setNeighborsSignificance(row, column, index) {
  1515. const neighborsSignificance = this.neighborsSignificance;
  1516. const width = this.width,
  1517. height = this.height;
  1518. const left = column > 0;
  1519. const right = column + 1 < width;
  1520. let i;
  1521. if (row > 0) {
  1522. i = index - width;
  1523. if (left) {
  1524. neighborsSignificance[i - 1] += 0x10;
  1525. }
  1526. if (right) {
  1527. neighborsSignificance[i + 1] += 0x10;
  1528. }
  1529. neighborsSignificance[i] += 0x04;
  1530. }
  1531. if (row + 1 < height) {
  1532. i = index + width;
  1533. if (left) {
  1534. neighborsSignificance[i - 1] += 0x10;
  1535. }
  1536. if (right) {
  1537. neighborsSignificance[i + 1] += 0x10;
  1538. }
  1539. neighborsSignificance[i] += 0x04;
  1540. }
  1541. if (left) {
  1542. neighborsSignificance[index - 1] += 0x01;
  1543. }
  1544. if (right) {
  1545. neighborsSignificance[index + 1] += 0x01;
  1546. }
  1547. neighborsSignificance[index] |= 0x80;
  1548. }
  1549. runSignificancePropagationPass() {
  1550. const decoder = this.decoder;
  1551. const width = this.width,
  1552. height = this.height;
  1553. const coefficentsMagnitude = this.coefficentsMagnitude;
  1554. const coefficentsSign = this.coefficentsSign;
  1555. const neighborsSignificance = this.neighborsSignificance;
  1556. const processingFlags = this.processingFlags;
  1557. const contexts = this.contexts;
  1558. const labels = this.contextLabelTable;
  1559. const bitsDecoded = this.bitsDecoded;
  1560. const processedInverseMask = ~1;
  1561. const processedMask = 1;
  1562. const firstMagnitudeBitMask = 2;
  1563. for (let i0 = 0; i0 < height; i0 += 4) {
  1564. for (let j = 0; j < width; j++) {
  1565. let index = i0 * width + j;
  1566. for (let i1 = 0; i1 < 4; i1++, index += width) {
  1567. const i = i0 + i1;
  1568. if (i >= height) {
  1569. break;
  1570. }
  1571. processingFlags[index] &= processedInverseMask;
  1572. if (coefficentsMagnitude[index] || !neighborsSignificance[index]) {
  1573. continue;
  1574. }
  1575. const contextLabel = labels[neighborsSignificance[index]];
  1576. const decision = decoder.readBit(contexts, contextLabel);
  1577. if (decision) {
  1578. const sign = this.decodeSignBit(i, j, index);
  1579. coefficentsSign[index] = sign;
  1580. coefficentsMagnitude[index] = 1;
  1581. this.setNeighborsSignificance(i, j, index);
  1582. processingFlags[index] |= firstMagnitudeBitMask;
  1583. }
  1584. bitsDecoded[index]++;
  1585. processingFlags[index] |= processedMask;
  1586. }
  1587. }
  1588. }
  1589. }
  1590. decodeSignBit(row, column, index) {
  1591. const width = this.width,
  1592. height = this.height;
  1593. const coefficentsMagnitude = this.coefficentsMagnitude;
  1594. const coefficentsSign = this.coefficentsSign;
  1595. let contribution, sign0, sign1, significance1;
  1596. let contextLabel, decoded;
  1597. significance1 = column > 0 && coefficentsMagnitude[index - 1] !== 0;
  1598. if (column + 1 < width && coefficentsMagnitude[index + 1] !== 0) {
  1599. sign1 = coefficentsSign[index + 1];
  1600. if (significance1) {
  1601. sign0 = coefficentsSign[index - 1];
  1602. contribution = 1 - sign1 - sign0;
  1603. } else {
  1604. contribution = 1 - sign1 - sign1;
  1605. }
  1606. } else if (significance1) {
  1607. sign0 = coefficentsSign[index - 1];
  1608. contribution = 1 - sign0 - sign0;
  1609. } else {
  1610. contribution = 0;
  1611. }
  1612. const horizontalContribution = 3 * contribution;
  1613. significance1 = row > 0 && coefficentsMagnitude[index - width] !== 0;
  1614. if (row + 1 < height && coefficentsMagnitude[index + width] !== 0) {
  1615. sign1 = coefficentsSign[index + width];
  1616. if (significance1) {
  1617. sign0 = coefficentsSign[index - width];
  1618. contribution = 1 - sign1 - sign0 + horizontalContribution;
  1619. } else {
  1620. contribution = 1 - sign1 - sign1 + horizontalContribution;
  1621. }
  1622. } else if (significance1) {
  1623. sign0 = coefficentsSign[index - width];
  1624. contribution = 1 - sign0 - sign0 + horizontalContribution;
  1625. } else {
  1626. contribution = horizontalContribution;
  1627. }
  1628. if (contribution >= 0) {
  1629. contextLabel = 9 + contribution;
  1630. decoded = this.decoder.readBit(this.contexts, contextLabel);
  1631. } else {
  1632. contextLabel = 9 - contribution;
  1633. decoded = this.decoder.readBit(this.contexts, contextLabel) ^ 1;
  1634. }
  1635. return decoded;
  1636. }
  1637. runMagnitudeRefinementPass() {
  1638. const decoder = this.decoder;
  1639. const width = this.width,
  1640. height = this.height;
  1641. const coefficentsMagnitude = this.coefficentsMagnitude;
  1642. const neighborsSignificance = this.neighborsSignificance;
  1643. const contexts = this.contexts;
  1644. const bitsDecoded = this.bitsDecoded;
  1645. const processingFlags = this.processingFlags;
  1646. const processedMask = 1;
  1647. const firstMagnitudeBitMask = 2;
  1648. const length = width * height;
  1649. const width4 = width * 4;
  1650. for (let index0 = 0, indexNext; index0 < length; index0 = indexNext) {
  1651. indexNext = Math.min(length, index0 + width4);
  1652. for (let j = 0; j < width; j++) {
  1653. for (let index = index0 + j; index < indexNext; index += width) {
  1654. if (!coefficentsMagnitude[index] || (processingFlags[index] & processedMask) !== 0) {
  1655. continue;
  1656. }
  1657. let contextLabel = 16;
  1658. if ((processingFlags[index] & firstMagnitudeBitMask) !== 0) {
  1659. processingFlags[index] ^= firstMagnitudeBitMask;
  1660. const significance = neighborsSignificance[index] & 127;
  1661. contextLabel = significance === 0 ? 15 : 14;
  1662. }
  1663. const bit = decoder.readBit(contexts, contextLabel);
  1664. coefficentsMagnitude[index] = coefficentsMagnitude[index] << 1 | bit;
  1665. bitsDecoded[index]++;
  1666. processingFlags[index] |= processedMask;
  1667. }
  1668. }
  1669. }
  1670. }
  1671. runCleanupPass() {
  1672. const decoder = this.decoder;
  1673. const width = this.width,
  1674. height = this.height;
  1675. const neighborsSignificance = this.neighborsSignificance;
  1676. const coefficentsMagnitude = this.coefficentsMagnitude;
  1677. const coefficentsSign = this.coefficentsSign;
  1678. const contexts = this.contexts;
  1679. const labels = this.contextLabelTable;
  1680. const bitsDecoded = this.bitsDecoded;
  1681. const processingFlags = this.processingFlags;
  1682. const processedMask = 1;
  1683. const firstMagnitudeBitMask = 2;
  1684. const oneRowDown = width;
  1685. const twoRowsDown = width * 2;
  1686. const threeRowsDown = width * 3;
  1687. let iNext;
  1688. for (let i0 = 0; i0 < height; i0 = iNext) {
  1689. iNext = Math.min(i0 + 4, height);
  1690. const indexBase = i0 * width;
  1691. const checkAllEmpty = i0 + 3 < height;
  1692. for (let j = 0; j < width; j++) {
  1693. const index0 = indexBase + j;
  1694. 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;
  1695. let i1 = 0,
  1696. index = index0;
  1697. let i = i0,
  1698. sign;
  1699. if (allEmpty) {
  1700. const hasSignificantCoefficent = decoder.readBit(contexts, RUNLENGTH_CONTEXT);
  1701. if (!hasSignificantCoefficent) {
  1702. bitsDecoded[index0]++;
  1703. bitsDecoded[index0 + oneRowDown]++;
  1704. bitsDecoded[index0 + twoRowsDown]++;
  1705. bitsDecoded[index0 + threeRowsDown]++;
  1706. continue;
  1707. }
  1708. i1 = decoder.readBit(contexts, UNIFORM_CONTEXT) << 1 | decoder.readBit(contexts, UNIFORM_CONTEXT);
  1709. if (i1 !== 0) {
  1710. i = i0 + i1;
  1711. index += i1 * width;
  1712. }
  1713. sign = this.decodeSignBit(i, j, index);
  1714. coefficentsSign[index] = sign;
  1715. coefficentsMagnitude[index] = 1;
  1716. this.setNeighborsSignificance(i, j, index);
  1717. processingFlags[index] |= firstMagnitudeBitMask;
  1718. index = index0;
  1719. for (let i2 = i0; i2 <= i; i2++, index += width) {
  1720. bitsDecoded[index]++;
  1721. }
  1722. i1++;
  1723. }
  1724. for (i = i0 + i1; i < iNext; i++, index += width) {
  1725. if (coefficentsMagnitude[index] || (processingFlags[index] & processedMask) !== 0) {
  1726. continue;
  1727. }
  1728. const contextLabel = labels[neighborsSignificance[index]];
  1729. const decision = decoder.readBit(contexts, contextLabel);
  1730. if (decision === 1) {
  1731. sign = this.decodeSignBit(i, j, index);
  1732. coefficentsSign[index] = sign;
  1733. coefficentsMagnitude[index] = 1;
  1734. this.setNeighborsSignificance(i, j, index);
  1735. processingFlags[index] |= firstMagnitudeBitMask;
  1736. }
  1737. bitsDecoded[index]++;
  1738. }
  1739. }
  1740. }
  1741. }
  1742. checkSegmentationSymbol() {
  1743. const decoder = this.decoder;
  1744. const contexts = this.contexts;
  1745. 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);
  1746. if (symbol !== 0xa) {
  1747. throw new JpxError("Invalid segmentation symbol");
  1748. }
  1749. }
  1750. }
  1751. return BitModel;
  1752. }();
  1753. class Transform {
  1754. constructor() {
  1755. if (this.constructor === Transform) {
  1756. (0, _util.unreachable)("Cannot initialize Transform.");
  1757. }
  1758. }
  1759. calculate(subbands, u0, v0) {
  1760. let ll = subbands[0];
  1761. for (let i = 1, ii = subbands.length; i < ii; i++) {
  1762. ll = this.iterate(ll, subbands[i], u0, v0);
  1763. }
  1764. return ll;
  1765. }
  1766. extend(buffer, offset, size) {
  1767. let i1 = offset - 1,
  1768. j1 = offset + 1;
  1769. let i2 = offset + size - 2,
  1770. j2 = offset + size;
  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. buffer[i1] = buffer[j1];
  1778. buffer[j2] = buffer[i2];
  1779. }
  1780. filter(x, offset, length) {
  1781. (0, _util.unreachable)("Abstract method `filter` called");
  1782. }
  1783. iterate(ll, hl_lh_hh, u0, v0) {
  1784. const llWidth = ll.width,
  1785. llHeight = ll.height;
  1786. let llItems = ll.items;
  1787. const width = hl_lh_hh.width;
  1788. const height = hl_lh_hh.height;
  1789. const items = hl_lh_hh.items;
  1790. let i, j, k, l, u, v;
  1791. for (k = 0, i = 0; i < llHeight; i++) {
  1792. l = i * 2 * width;
  1793. for (j = 0; j < llWidth; j++, k++, l += 2) {
  1794. items[l] = llItems[k];
  1795. }
  1796. }
  1797. llItems = ll.items = null;
  1798. const bufferPadding = 4;
  1799. const rowBuffer = new Float32Array(width + 2 * bufferPadding);
  1800. if (width === 1) {
  1801. if ((u0 & 1) !== 0) {
  1802. for (v = 0, k = 0; v < height; v++, k += width) {
  1803. items[k] *= 0.5;
  1804. }
  1805. }
  1806. } else {
  1807. for (v = 0, k = 0; v < height; v++, k += width) {
  1808. rowBuffer.set(items.subarray(k, k + width), bufferPadding);
  1809. this.extend(rowBuffer, bufferPadding, width);
  1810. this.filter(rowBuffer, bufferPadding, width);
  1811. items.set(rowBuffer.subarray(bufferPadding, bufferPadding + width), k);
  1812. }
  1813. }
  1814. let numBuffers = 16;
  1815. const colBuffers = [];
  1816. for (i = 0; i < numBuffers; i++) {
  1817. colBuffers.push(new Float32Array(height + 2 * bufferPadding));
  1818. }
  1819. let b,
  1820. currentBuffer = 0;
  1821. ll = bufferPadding + height;
  1822. if (height === 1) {
  1823. if ((v0 & 1) !== 0) {
  1824. for (u = 0; u < width; u++) {
  1825. items[u] *= 0.5;
  1826. }
  1827. }
  1828. } else {
  1829. for (u = 0; u < width; u++) {
  1830. if (currentBuffer === 0) {
  1831. numBuffers = Math.min(width - u, numBuffers);
  1832. for (k = u, l = bufferPadding; l < ll; k += width, l++) {
  1833. for (b = 0; b < numBuffers; b++) {
  1834. colBuffers[b][l] = items[k + b];
  1835. }
  1836. }
  1837. currentBuffer = numBuffers;
  1838. }
  1839. currentBuffer--;
  1840. const buffer = colBuffers[currentBuffer];
  1841. this.extend(buffer, bufferPadding, height);
  1842. this.filter(buffer, bufferPadding, height);
  1843. if (currentBuffer === 0) {
  1844. k = u - numBuffers + 1;
  1845. for (l = bufferPadding; l < ll; k += width, l++) {
  1846. for (b = 0; b < numBuffers; b++) {
  1847. items[k + b] = colBuffers[b][l];
  1848. }
  1849. }
  1850. }
  1851. }
  1852. }
  1853. return {
  1854. width,
  1855. height,
  1856. items
  1857. };
  1858. }
  1859. }
  1860. class IrreversibleTransform extends Transform {
  1861. filter(x, offset, length) {
  1862. const len = length >> 1;
  1863. offset |= 0;
  1864. let j, n, current, next;
  1865. const alpha = -1.586134342059924;
  1866. const beta = -0.052980118572961;
  1867. const gamma = 0.882911075530934;
  1868. const delta = 0.443506852043971;
  1869. const K = 1.230174104914001;
  1870. const 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. }
  1931. class ReversibleTransform extends Transform {
  1932. filter(x, offset, length) {
  1933. const len = length >> 1;
  1934. offset |= 0;
  1935. let j, n;
  1936. for (j = offset, n = len + 1; n--; j += 2) {
  1937. x[j] -= x[j - 1] + x[j + 1] + 2 >> 2;
  1938. }
  1939. for (j = offset + 1, n = len; n--; j += 2) {
  1940. x[j] += x[j - 1] + x[j + 1] >> 1;
  1941. }
  1942. }
  1943. }