jpx.js 72 KB

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