jpx.js 72 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943
  1. /* Copyright 2017 Mozilla Foundation
  2. *
  3. * Licensed under the Apache License, Version 2.0 (the "License");
  4. * you may not use this file except in compliance with the License.
  5. * You may obtain a copy of the License at
  6. *
  7. * http://www.apache.org/licenses/LICENSE-2.0
  8. *
  9. * Unless required by applicable law or agreed to in writing, software
  10. * distributed under the License is distributed on an "AS IS" BASIS,
  11. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. * See the License for the specific language governing permissions and
  13. * limitations under the License.
  14. */
  15. 'use strict';
  16. Object.defineProperty(exports, "__esModule", {
  17. value: true
  18. });
  19. exports.JpxImage = undefined;
  20. var _util = require('../shared/util');
  21. var _arithmetic_decoder = require('./arithmetic_decoder');
  22. var JpxImage = function JpxImageClosure() {
  23. var SubbandsGainLog2 = {
  24. 'LL': 0,
  25. 'LH': 1,
  26. 'HL': 1,
  27. 'HH': 2
  28. };
  29. function JpxImage() {
  30. this.failOnCorruptedImage = false;
  31. }
  32. JpxImage.prototype = {
  33. parse: function JpxImage_parse(data) {
  34. var head = (0, _util.readUint16)(data, 0);
  35. if (head === 0xFF4F) {
  36. this.parseCodestream(data, 0, data.length);
  37. return;
  38. }
  39. var position = 0,
  40. length = data.length;
  41. while (position < length) {
  42. var headerSize = 8;
  43. var lbox = (0, _util.readUint32)(data, position);
  44. var tbox = (0, _util.readUint32)(data, position + 4);
  45. position += headerSize;
  46. if (lbox === 1) {
  47. lbox = (0, _util.readUint32)(data, position) * 4294967296 + (0, _util.readUint32)(data, position + 4);
  48. position += 8;
  49. headerSize += 8;
  50. }
  51. if (lbox === 0) {
  52. lbox = length - position + headerSize;
  53. }
  54. if (lbox < headerSize) {
  55. (0, _util.error)('JPX Error: Invalid box field size');
  56. }
  57. var dataLength = lbox - headerSize;
  58. var jumpDataLength = true;
  59. switch (tbox) {
  60. case 0x6A703268:
  61. jumpDataLength = false;
  62. break;
  63. case 0x636F6C72:
  64. var method = data[position];
  65. if (method === 1) {
  66. var colorspace = (0, _util.readUint32)(data, position + 3);
  67. switch (colorspace) {
  68. case 16:
  69. case 17:
  70. case 18:
  71. break;
  72. default:
  73. (0, _util.warn)('Unknown colorspace ' + colorspace);
  74. break;
  75. }
  76. } else if (method === 2) {
  77. (0, _util.info)('ICC profile not supported');
  78. }
  79. break;
  80. case 0x6A703263:
  81. this.parseCodestream(data, position, position + dataLength);
  82. break;
  83. case 0x6A502020:
  84. if ((0, _util.readUint32)(data, position) !== 0x0d0a870a) {
  85. (0, _util.warn)('Invalid JP2 signature');
  86. }
  87. break;
  88. case 0x6A501A1A:
  89. case 0x66747970:
  90. case 0x72726571:
  91. case 0x72657320:
  92. case 0x69686472:
  93. break;
  94. default:
  95. var headerType = String.fromCharCode(tbox >> 24 & 0xFF, tbox >> 16 & 0xFF, tbox >> 8 & 0xFF, tbox & 0xFF);
  96. (0, _util.warn)('Unsupported header type ' + tbox + ' (' + headerType + ')');
  97. break;
  98. }
  99. if (jumpDataLength) {
  100. position += dataLength;
  101. }
  102. }
  103. },
  104. parseImageProperties: function JpxImage_parseImageProperties(stream) {
  105. var newByte = stream.getByte();
  106. while (newByte >= 0) {
  107. var oldByte = newByte;
  108. newByte = stream.getByte();
  109. var code = oldByte << 8 | newByte;
  110. if (code === 0xFF51) {
  111. stream.skip(4);
  112. var Xsiz = stream.getInt32() >>> 0;
  113. var Ysiz = stream.getInt32() >>> 0;
  114. var XOsiz = stream.getInt32() >>> 0;
  115. var YOsiz = stream.getInt32() >>> 0;
  116. stream.skip(16);
  117. var Csiz = stream.getUint16();
  118. this.width = Xsiz - XOsiz;
  119. this.height = Ysiz - YOsiz;
  120. this.componentsCount = Csiz;
  121. this.bitsPerComponent = 8;
  122. return;
  123. }
  124. }
  125. (0, _util.error)('JPX Error: No size marker found in JPX stream');
  126. },
  127. parseCodestream: function JpxImage_parseCodestream(data, start, end) {
  128. var context = {};
  129. var doNotRecover = false;
  130. try {
  131. var position = start;
  132. while (position + 1 < end) {
  133. var code = (0, _util.readUint16)(data, position);
  134. position += 2;
  135. var length = 0,
  136. j,
  137. sqcd,
  138. spqcds,
  139. spqcdSize,
  140. scalarExpounded,
  141. tile;
  142. switch (code) {
  143. case 0xFF4F:
  144. context.mainHeader = true;
  145. break;
  146. case 0xFFD9:
  147. break;
  148. case 0xFF51:
  149. length = (0, _util.readUint16)(data, position);
  150. var siz = {};
  151. siz.Xsiz = (0, _util.readUint32)(data, position + 4);
  152. siz.Ysiz = (0, _util.readUint32)(data, position + 8);
  153. siz.XOsiz = (0, _util.readUint32)(data, position + 12);
  154. siz.YOsiz = (0, _util.readUint32)(data, position + 16);
  155. siz.XTsiz = (0, _util.readUint32)(data, position + 20);
  156. siz.YTsiz = (0, _util.readUint32)(data, position + 24);
  157. siz.XTOsiz = (0, _util.readUint32)(data, position + 28);
  158. siz.YTOsiz = (0, _util.readUint32)(data, position + 32);
  159. var componentsCount = (0, _util.readUint16)(data, position + 36);
  160. siz.Csiz = componentsCount;
  161. var components = [];
  162. j = position + 38;
  163. for (var i = 0; i < componentsCount; i++) {
  164. var component = {
  165. precision: (data[j] & 0x7F) + 1,
  166. isSigned: !!(data[j] & 0x80),
  167. XRsiz: data[j + 1],
  168. YRsiz: data[j + 1]
  169. };
  170. calculateComponentDimensions(component, siz);
  171. components.push(component);
  172. }
  173. context.SIZ = siz;
  174. context.components = components;
  175. calculateTileGrids(context, components);
  176. context.QCC = [];
  177. context.COC = [];
  178. break;
  179. case 0xFF5C:
  180. length = (0, _util.readUint16)(data, position);
  181. var qcd = {};
  182. j = position + 2;
  183. sqcd = data[j++];
  184. switch (sqcd & 0x1F) {
  185. case 0:
  186. spqcdSize = 8;
  187. scalarExpounded = true;
  188. break;
  189. case 1:
  190. spqcdSize = 16;
  191. scalarExpounded = false;
  192. break;
  193. case 2:
  194. spqcdSize = 16;
  195. scalarExpounded = true;
  196. break;
  197. default:
  198. throw new Error('Invalid SQcd value ' + sqcd);
  199. }
  200. qcd.noQuantization = spqcdSize === 8;
  201. qcd.scalarExpounded = scalarExpounded;
  202. qcd.guardBits = sqcd >> 5;
  203. spqcds = [];
  204. while (j < length + position) {
  205. var spqcd = {};
  206. if (spqcdSize === 8) {
  207. spqcd.epsilon = data[j++] >> 3;
  208. spqcd.mu = 0;
  209. } else {
  210. spqcd.epsilon = data[j] >> 3;
  211. spqcd.mu = (data[j] & 0x7) << 8 | data[j + 1];
  212. j += 2;
  213. }
  214. spqcds.push(spqcd);
  215. }
  216. qcd.SPqcds = spqcds;
  217. if (context.mainHeader) {
  218. context.QCD = qcd;
  219. } else {
  220. context.currentTile.QCD = qcd;
  221. context.currentTile.QCC = [];
  222. }
  223. break;
  224. case 0xFF5D:
  225. length = (0, _util.readUint16)(data, position);
  226. var qcc = {};
  227. j = position + 2;
  228. var cqcc;
  229. if (context.SIZ.Csiz < 257) {
  230. cqcc = data[j++];
  231. } else {
  232. cqcc = (0, _util.readUint16)(data, j);
  233. j += 2;
  234. }
  235. sqcd = data[j++];
  236. switch (sqcd & 0x1F) {
  237. case 0:
  238. spqcdSize = 8;
  239. scalarExpounded = true;
  240. break;
  241. case 1:
  242. spqcdSize = 16;
  243. scalarExpounded = false;
  244. break;
  245. case 2:
  246. spqcdSize = 16;
  247. scalarExpounded = true;
  248. break;
  249. default:
  250. throw new Error('Invalid SQcd value ' + sqcd);
  251. }
  252. qcc.noQuantization = spqcdSize === 8;
  253. qcc.scalarExpounded = scalarExpounded;
  254. qcc.guardBits = sqcd >> 5;
  255. spqcds = [];
  256. while (j < length + position) {
  257. spqcd = {};
  258. if (spqcdSize === 8) {
  259. spqcd.epsilon = data[j++] >> 3;
  260. spqcd.mu = 0;
  261. } else {
  262. spqcd.epsilon = data[j] >> 3;
  263. spqcd.mu = (data[j] & 0x7) << 8 | data[j + 1];
  264. j += 2;
  265. }
  266. spqcds.push(spqcd);
  267. }
  268. qcc.SPqcds = spqcds;
  269. if (context.mainHeader) {
  270. context.QCC[cqcc] = qcc;
  271. } else {
  272. context.currentTile.QCC[cqcc] = qcc;
  273. }
  274. break;
  275. case 0xFF52:
  276. length = (0, _util.readUint16)(data, position);
  277. var cod = {};
  278. j = position + 2;
  279. var scod = data[j++];
  280. cod.entropyCoderWithCustomPrecincts = !!(scod & 1);
  281. cod.sopMarkerUsed = !!(scod & 2);
  282. cod.ephMarkerUsed = !!(scod & 4);
  283. cod.progressionOrder = data[j++];
  284. cod.layersCount = (0, _util.readUint16)(data, j);
  285. j += 2;
  286. cod.multipleComponentTransform = data[j++];
  287. cod.decompositionLevelsCount = data[j++];
  288. cod.xcb = (data[j++] & 0xF) + 2;
  289. cod.ycb = (data[j++] & 0xF) + 2;
  290. var blockStyle = data[j++];
  291. cod.selectiveArithmeticCodingBypass = !!(blockStyle & 1);
  292. cod.resetContextProbabilities = !!(blockStyle & 2);
  293. cod.terminationOnEachCodingPass = !!(blockStyle & 4);
  294. cod.verticalyStripe = !!(blockStyle & 8);
  295. cod.predictableTermination = !!(blockStyle & 16);
  296. cod.segmentationSymbolUsed = !!(blockStyle & 32);
  297. cod.reversibleTransformation = data[j++];
  298. if (cod.entropyCoderWithCustomPrecincts) {
  299. var precinctsSizes = [];
  300. while (j < length + position) {
  301. var precinctsSize = data[j++];
  302. precinctsSizes.push({
  303. PPx: precinctsSize & 0xF,
  304. PPy: precinctsSize >> 4
  305. });
  306. }
  307. cod.precinctsSizes = precinctsSizes;
  308. }
  309. var unsupported = [];
  310. if (cod.selectiveArithmeticCodingBypass) {
  311. unsupported.push('selectiveArithmeticCodingBypass');
  312. }
  313. if (cod.resetContextProbabilities) {
  314. unsupported.push('resetContextProbabilities');
  315. }
  316. if (cod.terminationOnEachCodingPass) {
  317. unsupported.push('terminationOnEachCodingPass');
  318. }
  319. if (cod.verticalyStripe) {
  320. unsupported.push('verticalyStripe');
  321. }
  322. if (cod.predictableTermination) {
  323. unsupported.push('predictableTermination');
  324. }
  325. if (unsupported.length > 0) {
  326. doNotRecover = true;
  327. throw new Error('Unsupported COD options (' + unsupported.join(', ') + ')');
  328. }
  329. if (context.mainHeader) {
  330. context.COD = cod;
  331. } else {
  332. context.currentTile.COD = cod;
  333. context.currentTile.COC = [];
  334. }
  335. break;
  336. case 0xFF90:
  337. length = (0, _util.readUint16)(data, position);
  338. tile = {};
  339. tile.index = (0, _util.readUint16)(data, position + 2);
  340. tile.length = (0, _util.readUint32)(data, position + 4);
  341. tile.dataEnd = tile.length + position - 2;
  342. tile.partIndex = data[position + 8];
  343. tile.partsCount = data[position + 9];
  344. context.mainHeader = false;
  345. if (tile.partIndex === 0) {
  346. tile.COD = context.COD;
  347. tile.COC = context.COC.slice(0);
  348. tile.QCD = context.QCD;
  349. tile.QCC = context.QCC.slice(0);
  350. }
  351. context.currentTile = tile;
  352. break;
  353. case 0xFF93:
  354. tile = context.currentTile;
  355. if (tile.partIndex === 0) {
  356. initializeTile(context, tile.index);
  357. buildPackets(context);
  358. }
  359. length = tile.dataEnd - position;
  360. parseTilePackets(context, data, position, length);
  361. break;
  362. case 0xFF55:
  363. case 0xFF57:
  364. case 0xFF58:
  365. case 0xFF64:
  366. length = (0, _util.readUint16)(data, position);
  367. break;
  368. case 0xFF53:
  369. throw new Error('Codestream code 0xFF53 (COC) is ' + 'not implemented');
  370. default:
  371. throw new Error('Unknown codestream code: ' + code.toString(16));
  372. }
  373. position += length;
  374. }
  375. } catch (e) {
  376. if (doNotRecover || this.failOnCorruptedImage) {
  377. (0, _util.error)('JPX Error: ' + e.message);
  378. } else {
  379. (0, _util.warn)('JPX: Trying to recover from: ' + e.message);
  380. }
  381. }
  382. this.tiles = transformComponents(context);
  383. this.width = context.SIZ.Xsiz - context.SIZ.XOsiz;
  384. this.height = context.SIZ.Ysiz - context.SIZ.YOsiz;
  385. this.componentsCount = context.SIZ.Csiz;
  386. }
  387. };
  388. function calculateComponentDimensions(component, siz) {
  389. component.x0 = Math.ceil(siz.XOsiz / component.XRsiz);
  390. component.x1 = Math.ceil(siz.Xsiz / component.XRsiz);
  391. component.y0 = Math.ceil(siz.YOsiz / component.YRsiz);
  392. component.y1 = Math.ceil(siz.Ysiz / component.YRsiz);
  393. component.width = component.x1 - component.x0;
  394. component.height = component.y1 - component.y0;
  395. }
  396. function calculateTileGrids(context, components) {
  397. var siz = context.SIZ;
  398. var tile,
  399. tiles = [];
  400. var numXtiles = Math.ceil((siz.Xsiz - siz.XTOsiz) / siz.XTsiz);
  401. var numYtiles = Math.ceil((siz.Ysiz - siz.YTOsiz) / siz.YTsiz);
  402. for (var q = 0; q < numYtiles; q++) {
  403. for (var p = 0; p < numXtiles; p++) {
  404. tile = {};
  405. tile.tx0 = Math.max(siz.XTOsiz + p * siz.XTsiz, siz.XOsiz);
  406. tile.ty0 = Math.max(siz.YTOsiz + q * siz.YTsiz, siz.YOsiz);
  407. tile.tx1 = Math.min(siz.XTOsiz + (p + 1) * siz.XTsiz, siz.Xsiz);
  408. tile.ty1 = Math.min(siz.YTOsiz + (q + 1) * siz.YTsiz, siz.Ysiz);
  409. tile.width = tile.tx1 - tile.tx0;
  410. tile.height = tile.ty1 - tile.ty0;
  411. tile.components = [];
  412. tiles.push(tile);
  413. }
  414. }
  415. context.tiles = tiles;
  416. var componentsCount = siz.Csiz;
  417. for (var i = 0, ii = componentsCount; i < ii; i++) {
  418. var component = components[i];
  419. for (var j = 0, jj = tiles.length; j < jj; j++) {
  420. var tileComponent = {};
  421. tile = tiles[j];
  422. tileComponent.tcx0 = Math.ceil(tile.tx0 / component.XRsiz);
  423. tileComponent.tcy0 = Math.ceil(tile.ty0 / component.YRsiz);
  424. tileComponent.tcx1 = Math.ceil(tile.tx1 / component.XRsiz);
  425. tileComponent.tcy1 = Math.ceil(tile.ty1 / component.YRsiz);
  426. tileComponent.width = tileComponent.tcx1 - tileComponent.tcx0;
  427. tileComponent.height = tileComponent.tcy1 - tileComponent.tcy0;
  428. tile.components[i] = tileComponent;
  429. }
  430. }
  431. }
  432. function getBlocksDimensions(context, component, r) {
  433. var codOrCoc = component.codingStyleParameters;
  434. var result = {};
  435. if (!codOrCoc.entropyCoderWithCustomPrecincts) {
  436. result.PPx = 15;
  437. result.PPy = 15;
  438. } else {
  439. result.PPx = codOrCoc.precinctsSizes[r].PPx;
  440. result.PPy = codOrCoc.precinctsSizes[r].PPy;
  441. }
  442. result.xcb_ = r > 0 ? Math.min(codOrCoc.xcb, result.PPx - 1) : Math.min(codOrCoc.xcb, result.PPx);
  443. result.ycb_ = r > 0 ? Math.min(codOrCoc.ycb, result.PPy - 1) : Math.min(codOrCoc.ycb, result.PPy);
  444. return result;
  445. }
  446. function buildPrecincts(context, resolution, dimensions) {
  447. var precinctWidth = 1 << dimensions.PPx;
  448. var precinctHeight = 1 << dimensions.PPy;
  449. var isZeroRes = resolution.resLevel === 0;
  450. var precinctWidthInSubband = 1 << dimensions.PPx + (isZeroRes ? 0 : -1);
  451. var precinctHeightInSubband = 1 << dimensions.PPy + (isZeroRes ? 0 : -1);
  452. var numprecinctswide = resolution.trx1 > resolution.trx0 ? Math.ceil(resolution.trx1 / precinctWidth) - Math.floor(resolution.trx0 / precinctWidth) : 0;
  453. var numprecinctshigh = resolution.try1 > resolution.try0 ? Math.ceil(resolution.try1 / precinctHeight) - Math.floor(resolution.try0 / precinctHeight) : 0;
  454. var numprecincts = numprecinctswide * numprecinctshigh;
  455. resolution.precinctParameters = {
  456. precinctWidth: precinctWidth,
  457. precinctHeight: precinctHeight,
  458. numprecinctswide: numprecinctswide,
  459. numprecinctshigh: numprecinctshigh,
  460. numprecincts: numprecincts,
  461. precinctWidthInSubband: precinctWidthInSubband,
  462. precinctHeightInSubband: precinctHeightInSubband
  463. };
  464. }
  465. function buildCodeblocks(context, subband, dimensions) {
  466. var xcb_ = dimensions.xcb_;
  467. var ycb_ = dimensions.ycb_;
  468. var codeblockWidth = 1 << xcb_;
  469. var codeblockHeight = 1 << ycb_;
  470. var cbx0 = subband.tbx0 >> xcb_;
  471. var cby0 = subband.tby0 >> ycb_;
  472. var cbx1 = subband.tbx1 + codeblockWidth - 1 >> xcb_;
  473. var cby1 = subband.tby1 + codeblockHeight - 1 >> ycb_;
  474. var precinctParameters = subband.resolution.precinctParameters;
  475. var codeblocks = [];
  476. var precincts = [];
  477. var i, j, codeblock, precinctNumber;
  478. for (j = cby0; j < cby1; j++) {
  479. for (i = cbx0; i < cbx1; i++) {
  480. codeblock = {
  481. cbx: i,
  482. cby: j,
  483. tbx0: codeblockWidth * i,
  484. tby0: codeblockHeight * j,
  485. tbx1: codeblockWidth * (i + 1),
  486. tby1: codeblockHeight * (j + 1)
  487. };
  488. codeblock.tbx0_ = Math.max(subband.tbx0, codeblock.tbx0);
  489. codeblock.tby0_ = Math.max(subband.tby0, codeblock.tby0);
  490. codeblock.tbx1_ = Math.min(subband.tbx1, codeblock.tbx1);
  491. codeblock.tby1_ = Math.min(subband.tby1, codeblock.tby1);
  492. var pi = Math.floor((codeblock.tbx0_ - subband.tbx0) / precinctParameters.precinctWidthInSubband);
  493. var pj = Math.floor((codeblock.tby0_ - subband.tby0) / precinctParameters.precinctHeightInSubband);
  494. precinctNumber = pi + pj * precinctParameters.numprecinctswide;
  495. codeblock.precinctNumber = precinctNumber;
  496. codeblock.subbandType = subband.type;
  497. codeblock.Lblock = 3;
  498. if (codeblock.tbx1_ <= codeblock.tbx0_ || codeblock.tby1_ <= codeblock.tby0_) {
  499. continue;
  500. }
  501. codeblocks.push(codeblock);
  502. var precinct = precincts[precinctNumber];
  503. if (precinct !== undefined) {
  504. if (i < precinct.cbxMin) {
  505. precinct.cbxMin = i;
  506. } else if (i > precinct.cbxMax) {
  507. precinct.cbxMax = i;
  508. }
  509. if (j < precinct.cbyMin) {
  510. precinct.cbxMin = j;
  511. } else if (j > precinct.cbyMax) {
  512. precinct.cbyMax = j;
  513. }
  514. } else {
  515. precincts[precinctNumber] = precinct = {
  516. cbxMin: i,
  517. cbyMin: j,
  518. cbxMax: i,
  519. cbyMax: j
  520. };
  521. }
  522. codeblock.precinct = precinct;
  523. }
  524. }
  525. subband.codeblockParameters = {
  526. codeblockWidth: xcb_,
  527. codeblockHeight: ycb_,
  528. numcodeblockwide: cbx1 - cbx0 + 1,
  529. numcodeblockhigh: cby1 - cby0 + 1
  530. };
  531. subband.codeblocks = codeblocks;
  532. subband.precincts = precincts;
  533. }
  534. function createPacket(resolution, precinctNumber, layerNumber) {
  535. var precinctCodeblocks = [];
  536. var subbands = resolution.subbands;
  537. for (var i = 0, ii = subbands.length; i < ii; i++) {
  538. var subband = subbands[i];
  539. var codeblocks = subband.codeblocks;
  540. for (var j = 0, jj = codeblocks.length; j < jj; j++) {
  541. var codeblock = codeblocks[j];
  542. if (codeblock.precinctNumber !== precinctNumber) {
  543. continue;
  544. }
  545. precinctCodeblocks.push(codeblock);
  546. }
  547. }
  548. return {
  549. layerNumber: layerNumber,
  550. codeblocks: precinctCodeblocks
  551. };
  552. }
  553. function LayerResolutionComponentPositionIterator(context) {
  554. var siz = context.SIZ;
  555. var tileIndex = context.currentTile.index;
  556. var tile = context.tiles[tileIndex];
  557. var layersCount = tile.codingStyleDefaultParameters.layersCount;
  558. var componentsCount = siz.Csiz;
  559. var maxDecompositionLevelsCount = 0;
  560. for (var q = 0; q < componentsCount; q++) {
  561. maxDecompositionLevelsCount = Math.max(maxDecompositionLevelsCount, tile.components[q].codingStyleParameters.decompositionLevelsCount);
  562. }
  563. var l = 0,
  564. r = 0,
  565. i = 0,
  566. k = 0;
  567. this.nextPacket = function JpxImage_nextPacket() {
  568. for (; l < layersCount; l++) {
  569. for (; r <= maxDecompositionLevelsCount; r++) {
  570. for (; i < componentsCount; i++) {
  571. var component = tile.components[i];
  572. if (r > component.codingStyleParameters.decompositionLevelsCount) {
  573. continue;
  574. }
  575. var resolution = component.resolutions[r];
  576. var numprecincts = resolution.precinctParameters.numprecincts;
  577. for (; k < numprecincts;) {
  578. var packet = createPacket(resolution, k, l);
  579. k++;
  580. return packet;
  581. }
  582. k = 0;
  583. }
  584. i = 0;
  585. }
  586. r = 0;
  587. }
  588. (0, _util.error)('JPX Error: Out of packets');
  589. };
  590. }
  591. function ResolutionLayerComponentPositionIterator(context) {
  592. var siz = context.SIZ;
  593. var tileIndex = context.currentTile.index;
  594. var tile = context.tiles[tileIndex];
  595. var layersCount = tile.codingStyleDefaultParameters.layersCount;
  596. var componentsCount = siz.Csiz;
  597. var maxDecompositionLevelsCount = 0;
  598. for (var q = 0; q < componentsCount; q++) {
  599. maxDecompositionLevelsCount = Math.max(maxDecompositionLevelsCount, tile.components[q].codingStyleParameters.decompositionLevelsCount);
  600. }
  601. var r = 0,
  602. l = 0,
  603. i = 0,
  604. k = 0;
  605. this.nextPacket = function JpxImage_nextPacket() {
  606. for (; r <= maxDecompositionLevelsCount; r++) {
  607. for (; l < layersCount; l++) {
  608. for (; i < componentsCount; i++) {
  609. var component = tile.components[i];
  610. if (r > component.codingStyleParameters.decompositionLevelsCount) {
  611. continue;
  612. }
  613. var resolution = component.resolutions[r];
  614. var numprecincts = resolution.precinctParameters.numprecincts;
  615. for (; k < numprecincts;) {
  616. var packet = createPacket(resolution, k, l);
  617. k++;
  618. return packet;
  619. }
  620. k = 0;
  621. }
  622. i = 0;
  623. }
  624. l = 0;
  625. }
  626. (0, _util.error)('JPX Error: Out of packets');
  627. };
  628. }
  629. function ResolutionPositionComponentLayerIterator(context) {
  630. var siz = context.SIZ;
  631. var tileIndex = context.currentTile.index;
  632. var tile = context.tiles[tileIndex];
  633. var layersCount = tile.codingStyleDefaultParameters.layersCount;
  634. var componentsCount = siz.Csiz;
  635. var l, r, c, p;
  636. var maxDecompositionLevelsCount = 0;
  637. for (c = 0; c < componentsCount; c++) {
  638. var component = tile.components[c];
  639. maxDecompositionLevelsCount = Math.max(maxDecompositionLevelsCount, component.codingStyleParameters.decompositionLevelsCount);
  640. }
  641. var maxNumPrecinctsInLevel = new Int32Array(maxDecompositionLevelsCount + 1);
  642. for (r = 0; r <= maxDecompositionLevelsCount; ++r) {
  643. var maxNumPrecincts = 0;
  644. for (c = 0; c < componentsCount; ++c) {
  645. var resolutions = tile.components[c].resolutions;
  646. if (r < resolutions.length) {
  647. maxNumPrecincts = Math.max(maxNumPrecincts, resolutions[r].precinctParameters.numprecincts);
  648. }
  649. }
  650. maxNumPrecinctsInLevel[r] = maxNumPrecincts;
  651. }
  652. l = 0;
  653. r = 0;
  654. c = 0;
  655. p = 0;
  656. this.nextPacket = function JpxImage_nextPacket() {
  657. for (; r <= maxDecompositionLevelsCount; r++) {
  658. for (; p < maxNumPrecinctsInLevel[r]; p++) {
  659. for (; c < componentsCount; c++) {
  660. var component = tile.components[c];
  661. if (r > component.codingStyleParameters.decompositionLevelsCount) {
  662. continue;
  663. }
  664. var resolution = component.resolutions[r];
  665. var numprecincts = resolution.precinctParameters.numprecincts;
  666. if (p >= numprecincts) {
  667. continue;
  668. }
  669. for (; l < layersCount;) {
  670. var packet = createPacket(resolution, p, l);
  671. l++;
  672. return packet;
  673. }
  674. l = 0;
  675. }
  676. c = 0;
  677. }
  678. p = 0;
  679. }
  680. (0, _util.error)('JPX Error: Out of packets');
  681. };
  682. }
  683. function PositionComponentResolutionLayerIterator(context) {
  684. var siz = context.SIZ;
  685. var tileIndex = context.currentTile.index;
  686. var tile = context.tiles[tileIndex];
  687. var layersCount = tile.codingStyleDefaultParameters.layersCount;
  688. var componentsCount = siz.Csiz;
  689. var precinctsSizes = getPrecinctSizesInImageScale(tile);
  690. var precinctsIterationSizes = precinctsSizes;
  691. var l = 0,
  692. r = 0,
  693. c = 0,
  694. px = 0,
  695. py = 0;
  696. this.nextPacket = function JpxImage_nextPacket() {
  697. for (; py < precinctsIterationSizes.maxNumHigh; py++) {
  698. for (; px < precinctsIterationSizes.maxNumWide; px++) {
  699. for (; c < componentsCount; c++) {
  700. var component = tile.components[c];
  701. var decompositionLevelsCount = component.codingStyleParameters.decompositionLevelsCount;
  702. for (; r <= decompositionLevelsCount; r++) {
  703. var resolution = component.resolutions[r];
  704. var sizeInImageScale = precinctsSizes.components[c].resolutions[r];
  705. var k = getPrecinctIndexIfExist(px, py, sizeInImageScale, precinctsIterationSizes, resolution);
  706. if (k === null) {
  707. continue;
  708. }
  709. for (; l < layersCount;) {
  710. var packet = createPacket(resolution, k, l);
  711. l++;
  712. return packet;
  713. }
  714. l = 0;
  715. }
  716. r = 0;
  717. }
  718. c = 0;
  719. }
  720. px = 0;
  721. }
  722. (0, _util.error)('JPX Error: Out of packets');
  723. };
  724. }
  725. function ComponentPositionResolutionLayerIterator(context) {
  726. var siz = context.SIZ;
  727. var tileIndex = context.currentTile.index;
  728. var tile = context.tiles[tileIndex];
  729. var layersCount = tile.codingStyleDefaultParameters.layersCount;
  730. var componentsCount = siz.Csiz;
  731. var precinctsSizes = getPrecinctSizesInImageScale(tile);
  732. var l = 0,
  733. r = 0,
  734. c = 0,
  735. px = 0,
  736. py = 0;
  737. this.nextPacket = function JpxImage_nextPacket() {
  738. for (; c < componentsCount; ++c) {
  739. var component = tile.components[c];
  740. var precinctsIterationSizes = precinctsSizes.components[c];
  741. var decompositionLevelsCount = component.codingStyleParameters.decompositionLevelsCount;
  742. for (; py < precinctsIterationSizes.maxNumHigh; py++) {
  743. for (; px < precinctsIterationSizes.maxNumWide; px++) {
  744. for (; r <= decompositionLevelsCount; r++) {
  745. var resolution = component.resolutions[r];
  746. var sizeInImageScale = precinctsIterationSizes.resolutions[r];
  747. var k = getPrecinctIndexIfExist(px, py, sizeInImageScale, precinctsIterationSizes, resolution);
  748. if (k === null) {
  749. continue;
  750. }
  751. for (; l < layersCount;) {
  752. var packet = createPacket(resolution, k, l);
  753. l++;
  754. return packet;
  755. }
  756. l = 0;
  757. }
  758. r = 0;
  759. }
  760. px = 0;
  761. }
  762. py = 0;
  763. }
  764. (0, _util.error)('JPX Error: Out of packets');
  765. };
  766. }
  767. function getPrecinctIndexIfExist(pxIndex, pyIndex, sizeInImageScale, precinctIterationSizes, resolution) {
  768. var posX = pxIndex * precinctIterationSizes.minWidth;
  769. var posY = pyIndex * precinctIterationSizes.minHeight;
  770. if (posX % sizeInImageScale.width !== 0 || posY % sizeInImageScale.height !== 0) {
  771. return null;
  772. }
  773. var startPrecinctRowIndex = posY / sizeInImageScale.width * resolution.precinctParameters.numprecinctswide;
  774. return posX / sizeInImageScale.height + startPrecinctRowIndex;
  775. }
  776. function getPrecinctSizesInImageScale(tile) {
  777. var componentsCount = tile.components.length;
  778. var minWidth = Number.MAX_VALUE;
  779. var minHeight = Number.MAX_VALUE;
  780. var maxNumWide = 0;
  781. var maxNumHigh = 0;
  782. var sizePerComponent = new Array(componentsCount);
  783. for (var c = 0; c < componentsCount; c++) {
  784. var component = tile.components[c];
  785. var decompositionLevelsCount = component.codingStyleParameters.decompositionLevelsCount;
  786. var sizePerResolution = new Array(decompositionLevelsCount + 1);
  787. var minWidthCurrentComponent = Number.MAX_VALUE;
  788. var minHeightCurrentComponent = Number.MAX_VALUE;
  789. var maxNumWideCurrentComponent = 0;
  790. var maxNumHighCurrentComponent = 0;
  791. var scale = 1;
  792. for (var r = decompositionLevelsCount; r >= 0; --r) {
  793. var resolution = component.resolutions[r];
  794. var widthCurrentResolution = scale * resolution.precinctParameters.precinctWidth;
  795. var heightCurrentResolution = scale * resolution.precinctParameters.precinctHeight;
  796. minWidthCurrentComponent = Math.min(minWidthCurrentComponent, widthCurrentResolution);
  797. minHeightCurrentComponent = Math.min(minHeightCurrentComponent, heightCurrentResolution);
  798. maxNumWideCurrentComponent = Math.max(maxNumWideCurrentComponent, resolution.precinctParameters.numprecinctswide);
  799. maxNumHighCurrentComponent = Math.max(maxNumHighCurrentComponent, resolution.precinctParameters.numprecinctshigh);
  800. sizePerResolution[r] = {
  801. width: widthCurrentResolution,
  802. height: heightCurrentResolution
  803. };
  804. scale <<= 1;
  805. }
  806. minWidth = Math.min(minWidth, minWidthCurrentComponent);
  807. minHeight = Math.min(minHeight, minHeightCurrentComponent);
  808. maxNumWide = Math.max(maxNumWide, maxNumWideCurrentComponent);
  809. maxNumHigh = Math.max(maxNumHigh, maxNumHighCurrentComponent);
  810. sizePerComponent[c] = {
  811. resolutions: sizePerResolution,
  812. minWidth: minWidthCurrentComponent,
  813. minHeight: minHeightCurrentComponent,
  814. maxNumWide: maxNumWideCurrentComponent,
  815. maxNumHigh: maxNumHighCurrentComponent
  816. };
  817. }
  818. return {
  819. components: sizePerComponent,
  820. minWidth: minWidth,
  821. minHeight: minHeight,
  822. maxNumWide: maxNumWide,
  823. maxNumHigh: maxNumHigh
  824. };
  825. }
  826. function buildPackets(context) {
  827. var siz = context.SIZ;
  828. var tileIndex = context.currentTile.index;
  829. var tile = context.tiles[tileIndex];
  830. var componentsCount = siz.Csiz;
  831. for (var c = 0; c < componentsCount; c++) {
  832. var component = tile.components[c];
  833. var decompositionLevelsCount = component.codingStyleParameters.decompositionLevelsCount;
  834. var resolutions = [];
  835. var subbands = [];
  836. for (var r = 0; r <= decompositionLevelsCount; r++) {
  837. var blocksDimensions = getBlocksDimensions(context, component, r);
  838. var resolution = {};
  839. var scale = 1 << decompositionLevelsCount - r;
  840. resolution.trx0 = Math.ceil(component.tcx0 / scale);
  841. resolution.try0 = Math.ceil(component.tcy0 / scale);
  842. resolution.trx1 = Math.ceil(component.tcx1 / scale);
  843. resolution.try1 = Math.ceil(component.tcy1 / scale);
  844. resolution.resLevel = r;
  845. buildPrecincts(context, resolution, blocksDimensions);
  846. resolutions.push(resolution);
  847. var subband;
  848. if (r === 0) {
  849. subband = {};
  850. subband.type = 'LL';
  851. subband.tbx0 = Math.ceil(component.tcx0 / scale);
  852. subband.tby0 = Math.ceil(component.tcy0 / scale);
  853. subband.tbx1 = Math.ceil(component.tcx1 / scale);
  854. subband.tby1 = Math.ceil(component.tcy1 / scale);
  855. subband.resolution = resolution;
  856. buildCodeblocks(context, subband, blocksDimensions);
  857. subbands.push(subband);
  858. resolution.subbands = [subband];
  859. } else {
  860. var bscale = 1 << decompositionLevelsCount - r + 1;
  861. var resolutionSubbands = [];
  862. subband = {};
  863. subband.type = 'HL';
  864. subband.tbx0 = Math.ceil(component.tcx0 / bscale - 0.5);
  865. subband.tby0 = Math.ceil(component.tcy0 / bscale);
  866. subband.tbx1 = Math.ceil(component.tcx1 / bscale - 0.5);
  867. subband.tby1 = Math.ceil(component.tcy1 / bscale);
  868. subband.resolution = resolution;
  869. buildCodeblocks(context, subband, blocksDimensions);
  870. subbands.push(subband);
  871. resolutionSubbands.push(subband);
  872. subband = {};
  873. subband.type = 'LH';
  874. subband.tbx0 = Math.ceil(component.tcx0 / bscale);
  875. subband.tby0 = Math.ceil(component.tcy0 / bscale - 0.5);
  876. subband.tbx1 = Math.ceil(component.tcx1 / bscale);
  877. subband.tby1 = Math.ceil(component.tcy1 / bscale - 0.5);
  878. subband.resolution = resolution;
  879. buildCodeblocks(context, subband, blocksDimensions);
  880. subbands.push(subband);
  881. resolutionSubbands.push(subband);
  882. subband = {};
  883. subband.type = 'HH';
  884. subband.tbx0 = Math.ceil(component.tcx0 / bscale - 0.5);
  885. subband.tby0 = Math.ceil(component.tcy0 / bscale - 0.5);
  886. subband.tbx1 = Math.ceil(component.tcx1 / bscale - 0.5);
  887. subband.tby1 = Math.ceil(component.tcy1 / bscale - 0.5);
  888. subband.resolution = resolution;
  889. buildCodeblocks(context, subband, blocksDimensions);
  890. subbands.push(subband);
  891. resolutionSubbands.push(subband);
  892. resolution.subbands = resolutionSubbands;
  893. }
  894. }
  895. component.resolutions = resolutions;
  896. component.subbands = subbands;
  897. }
  898. var progressionOrder = tile.codingStyleDefaultParameters.progressionOrder;
  899. switch (progressionOrder) {
  900. case 0:
  901. tile.packetsIterator = new LayerResolutionComponentPositionIterator(context);
  902. break;
  903. case 1:
  904. tile.packetsIterator = new ResolutionLayerComponentPositionIterator(context);
  905. break;
  906. case 2:
  907. tile.packetsIterator = new ResolutionPositionComponentLayerIterator(context);
  908. break;
  909. case 3:
  910. tile.packetsIterator = new PositionComponentResolutionLayerIterator(context);
  911. break;
  912. case 4:
  913. tile.packetsIterator = new ComponentPositionResolutionLayerIterator(context);
  914. break;
  915. default:
  916. (0, _util.error)('JPX Error: Unsupported progression order ' + progressionOrder);
  917. }
  918. }
  919. function parseTilePackets(context, data, offset, dataLength) {
  920. var position = 0;
  921. var buffer,
  922. bufferSize = 0,
  923. skipNextBit = false;
  924. function readBits(count) {
  925. while (bufferSize < count) {
  926. var b = data[offset + position];
  927. position++;
  928. if (skipNextBit) {
  929. buffer = buffer << 7 | b;
  930. bufferSize += 7;
  931. skipNextBit = false;
  932. } else {
  933. buffer = buffer << 8 | b;
  934. bufferSize += 8;
  935. }
  936. if (b === 0xFF) {
  937. skipNextBit = true;
  938. }
  939. }
  940. bufferSize -= count;
  941. return buffer >>> bufferSize & (1 << count) - 1;
  942. }
  943. function skipMarkerIfEqual(value) {
  944. if (data[offset + position - 1] === 0xFF && data[offset + position] === value) {
  945. skipBytes(1);
  946. return true;
  947. } else if (data[offset + position] === 0xFF && data[offset + position + 1] === value) {
  948. skipBytes(2);
  949. return true;
  950. }
  951. return false;
  952. }
  953. function skipBytes(count) {
  954. position += count;
  955. }
  956. function alignToByte() {
  957. bufferSize = 0;
  958. if (skipNextBit) {
  959. position++;
  960. skipNextBit = false;
  961. }
  962. }
  963. function readCodingpasses() {
  964. if (readBits(1) === 0) {
  965. return 1;
  966. }
  967. if (readBits(1) === 0) {
  968. return 2;
  969. }
  970. var value = readBits(2);
  971. if (value < 3) {
  972. return value + 3;
  973. }
  974. value = readBits(5);
  975. if (value < 31) {
  976. return value + 6;
  977. }
  978. value = readBits(7);
  979. return value + 37;
  980. }
  981. var tileIndex = context.currentTile.index;
  982. var tile = context.tiles[tileIndex];
  983. var sopMarkerUsed = context.COD.sopMarkerUsed;
  984. var ephMarkerUsed = context.COD.ephMarkerUsed;
  985. var packetsIterator = tile.packetsIterator;
  986. while (position < dataLength) {
  987. alignToByte();
  988. if (sopMarkerUsed && skipMarkerIfEqual(0x91)) {
  989. skipBytes(4);
  990. }
  991. var packet = packetsIterator.nextPacket();
  992. if (!readBits(1)) {
  993. continue;
  994. }
  995. var layerNumber = packet.layerNumber;
  996. var queue = [],
  997. codeblock;
  998. for (var i = 0, ii = packet.codeblocks.length; i < ii; i++) {
  999. codeblock = packet.codeblocks[i];
  1000. var precinct = codeblock.precinct;
  1001. var codeblockColumn = codeblock.cbx - precinct.cbxMin;
  1002. var codeblockRow = codeblock.cby - precinct.cbyMin;
  1003. var codeblockIncluded = false;
  1004. var firstTimeInclusion = false;
  1005. var valueReady;
  1006. if (codeblock['included'] !== undefined) {
  1007. codeblockIncluded = !!readBits(1);
  1008. } else {
  1009. precinct = codeblock.precinct;
  1010. var inclusionTree, zeroBitPlanesTree;
  1011. if (precinct['inclusionTree'] !== undefined) {
  1012. inclusionTree = precinct.inclusionTree;
  1013. } else {
  1014. var width = precinct.cbxMax - precinct.cbxMin + 1;
  1015. var height = precinct.cbyMax - precinct.cbyMin + 1;
  1016. inclusionTree = new InclusionTree(width, height, layerNumber);
  1017. zeroBitPlanesTree = new TagTree(width, height);
  1018. precinct.inclusionTree = inclusionTree;
  1019. precinct.zeroBitPlanesTree = zeroBitPlanesTree;
  1020. }
  1021. if (inclusionTree.reset(codeblockColumn, codeblockRow, layerNumber)) {
  1022. while (true) {
  1023. if (readBits(1)) {
  1024. valueReady = !inclusionTree.nextLevel();
  1025. if (valueReady) {
  1026. codeblock.included = true;
  1027. codeblockIncluded = firstTimeInclusion = true;
  1028. break;
  1029. }
  1030. } else {
  1031. inclusionTree.incrementValue(layerNumber);
  1032. break;
  1033. }
  1034. }
  1035. }
  1036. }
  1037. if (!codeblockIncluded) {
  1038. continue;
  1039. }
  1040. if (firstTimeInclusion) {
  1041. zeroBitPlanesTree = precinct.zeroBitPlanesTree;
  1042. zeroBitPlanesTree.reset(codeblockColumn, codeblockRow);
  1043. while (true) {
  1044. if (readBits(1)) {
  1045. valueReady = !zeroBitPlanesTree.nextLevel();
  1046. if (valueReady) {
  1047. break;
  1048. }
  1049. } else {
  1050. zeroBitPlanesTree.incrementValue();
  1051. }
  1052. }
  1053. codeblock.zeroBitPlanes = zeroBitPlanesTree.value;
  1054. }
  1055. var codingpasses = readCodingpasses();
  1056. while (readBits(1)) {
  1057. codeblock.Lblock++;
  1058. }
  1059. var codingpassesLog2 = (0, _util.log2)(codingpasses);
  1060. var bits = (codingpasses < 1 << codingpassesLog2 ? codingpassesLog2 - 1 : codingpassesLog2) + codeblock.Lblock;
  1061. var codedDataLength = readBits(bits);
  1062. queue.push({
  1063. codeblock: codeblock,
  1064. codingpasses: codingpasses,
  1065. dataLength: codedDataLength
  1066. });
  1067. }
  1068. alignToByte();
  1069. if (ephMarkerUsed) {
  1070. skipMarkerIfEqual(0x92);
  1071. }
  1072. while (queue.length > 0) {
  1073. var packetItem = queue.shift();
  1074. codeblock = packetItem.codeblock;
  1075. if (codeblock['data'] === undefined) {
  1076. codeblock.data = [];
  1077. }
  1078. codeblock.data.push({
  1079. data: data,
  1080. start: offset + position,
  1081. end: offset + position + packetItem.dataLength,
  1082. codingpasses: packetItem.codingpasses
  1083. });
  1084. position += packetItem.dataLength;
  1085. }
  1086. }
  1087. return position;
  1088. }
  1089. function copyCoefficients(coefficients, levelWidth, levelHeight, subband, delta, mb, reversible, segmentationSymbolUsed) {
  1090. var x0 = subband.tbx0;
  1091. var y0 = subband.tby0;
  1092. var width = subband.tbx1 - subband.tbx0;
  1093. var codeblocks = subband.codeblocks;
  1094. var right = subband.type.charAt(0) === 'H' ? 1 : 0;
  1095. var bottom = subband.type.charAt(1) === 'H' ? levelWidth : 0;
  1096. for (var i = 0, ii = codeblocks.length; i < ii; ++i) {
  1097. var codeblock = codeblocks[i];
  1098. var blockWidth = codeblock.tbx1_ - codeblock.tbx0_;
  1099. var blockHeight = codeblock.tby1_ - codeblock.tby0_;
  1100. if (blockWidth === 0 || blockHeight === 0) {
  1101. continue;
  1102. }
  1103. if (codeblock['data'] === undefined) {
  1104. continue;
  1105. }
  1106. var bitModel, currentCodingpassType;
  1107. bitModel = new BitModel(blockWidth, blockHeight, codeblock.subbandType, codeblock.zeroBitPlanes, mb);
  1108. currentCodingpassType = 2;
  1109. var data = codeblock.data,
  1110. totalLength = 0,
  1111. codingpasses = 0;
  1112. var j, jj, dataItem;
  1113. for (j = 0, jj = data.length; j < jj; j++) {
  1114. dataItem = data[j];
  1115. totalLength += dataItem.end - dataItem.start;
  1116. codingpasses += dataItem.codingpasses;
  1117. }
  1118. var encodedData = new Uint8Array(totalLength);
  1119. var position = 0;
  1120. for (j = 0, jj = data.length; j < jj; j++) {
  1121. dataItem = data[j];
  1122. var chunk = dataItem.data.subarray(dataItem.start, dataItem.end);
  1123. encodedData.set(chunk, position);
  1124. position += chunk.length;
  1125. }
  1126. var decoder = new _arithmetic_decoder.ArithmeticDecoder(encodedData, 0, totalLength);
  1127. bitModel.setDecoder(decoder);
  1128. for (j = 0; j < codingpasses; j++) {
  1129. switch (currentCodingpassType) {
  1130. case 0:
  1131. bitModel.runSignificancePropagationPass();
  1132. break;
  1133. case 1:
  1134. bitModel.runMagnitudeRefinementPass();
  1135. break;
  1136. case 2:
  1137. bitModel.runCleanupPass();
  1138. if (segmentationSymbolUsed) {
  1139. bitModel.checkSegmentationSymbol();
  1140. }
  1141. break;
  1142. }
  1143. currentCodingpassType = (currentCodingpassType + 1) % 3;
  1144. }
  1145. var offset = codeblock.tbx0_ - x0 + (codeblock.tby0_ - y0) * width;
  1146. var sign = bitModel.coefficentsSign;
  1147. var magnitude = bitModel.coefficentsMagnitude;
  1148. var bitsDecoded = bitModel.bitsDecoded;
  1149. var magnitudeCorrection = reversible ? 0 : 0.5;
  1150. var k, n, nb;
  1151. position = 0;
  1152. var interleave = subband.type !== 'LL';
  1153. for (j = 0; j < blockHeight; j++) {
  1154. var row = offset / width | 0;
  1155. var levelOffset = 2 * row * (levelWidth - width) + right + bottom;
  1156. for (k = 0; k < blockWidth; k++) {
  1157. n = magnitude[position];
  1158. if (n !== 0) {
  1159. n = (n + magnitudeCorrection) * delta;
  1160. if (sign[position] !== 0) {
  1161. n = -n;
  1162. }
  1163. nb = bitsDecoded[position];
  1164. var pos = interleave ? levelOffset + (offset << 1) : offset;
  1165. if (reversible && nb >= mb) {
  1166. coefficients[pos] = n;
  1167. } else {
  1168. coefficients[pos] = n * (1 << mb - nb);
  1169. }
  1170. }
  1171. offset++;
  1172. position++;
  1173. }
  1174. offset += width - blockWidth;
  1175. }
  1176. }
  1177. }
  1178. function transformTile(context, tile, c) {
  1179. var component = tile.components[c];
  1180. var codingStyleParameters = component.codingStyleParameters;
  1181. var quantizationParameters = component.quantizationParameters;
  1182. var decompositionLevelsCount = codingStyleParameters.decompositionLevelsCount;
  1183. var spqcds = quantizationParameters.SPqcds;
  1184. var scalarExpounded = quantizationParameters.scalarExpounded;
  1185. var guardBits = quantizationParameters.guardBits;
  1186. var segmentationSymbolUsed = codingStyleParameters.segmentationSymbolUsed;
  1187. var precision = context.components[c].precision;
  1188. var reversible = codingStyleParameters.reversibleTransformation;
  1189. var transform = reversible ? new ReversibleTransform() : new IrreversibleTransform();
  1190. var subbandCoefficients = [];
  1191. var b = 0;
  1192. for (var i = 0; i <= decompositionLevelsCount; i++) {
  1193. var resolution = component.resolutions[i];
  1194. var width = resolution.trx1 - resolution.trx0;
  1195. var height = resolution.try1 - resolution.try0;
  1196. var coefficients = new Float32Array(width * height);
  1197. for (var j = 0, jj = resolution.subbands.length; j < jj; j++) {
  1198. var mu, epsilon;
  1199. if (!scalarExpounded) {
  1200. mu = spqcds[0].mu;
  1201. epsilon = spqcds[0].epsilon + (i > 0 ? 1 - i : 0);
  1202. } else {
  1203. mu = spqcds[b].mu;
  1204. epsilon = spqcds[b].epsilon;
  1205. b++;
  1206. }
  1207. var subband = resolution.subbands[j];
  1208. var gainLog2 = SubbandsGainLog2[subband.type];
  1209. var delta = reversible ? 1 : Math.pow(2, precision + gainLog2 - epsilon) * (1 + mu / 2048);
  1210. var mb = guardBits + epsilon - 1;
  1211. copyCoefficients(coefficients, width, height, subband, delta, mb, reversible, segmentationSymbolUsed);
  1212. }
  1213. subbandCoefficients.push({
  1214. width: width,
  1215. height: height,
  1216. items: coefficients
  1217. });
  1218. }
  1219. var result = transform.calculate(subbandCoefficients, component.tcx0, component.tcy0);
  1220. return {
  1221. left: component.tcx0,
  1222. top: component.tcy0,
  1223. width: result.width,
  1224. height: result.height,
  1225. items: result.items
  1226. };
  1227. }
  1228. function transformComponents(context) {
  1229. var siz = context.SIZ;
  1230. var components = context.components;
  1231. var componentsCount = siz.Csiz;
  1232. var resultImages = [];
  1233. for (var i = 0, ii = context.tiles.length; i < ii; i++) {
  1234. var tile = context.tiles[i];
  1235. var transformedTiles = [];
  1236. var c;
  1237. for (c = 0; c < componentsCount; c++) {
  1238. transformedTiles[c] = transformTile(context, tile, c);
  1239. }
  1240. var tile0 = transformedTiles[0];
  1241. var out = new Uint8Array(tile0.items.length * componentsCount);
  1242. var result = {
  1243. left: tile0.left,
  1244. top: tile0.top,
  1245. width: tile0.width,
  1246. height: tile0.height,
  1247. items: out
  1248. };
  1249. var shift, offset, max, min, maxK;
  1250. var pos = 0,
  1251. j,
  1252. jj,
  1253. y0,
  1254. y1,
  1255. y2,
  1256. r,
  1257. g,
  1258. b,
  1259. k,
  1260. val;
  1261. if (tile.codingStyleDefaultParameters.multipleComponentTransform) {
  1262. var fourComponents = componentsCount === 4;
  1263. var y0items = transformedTiles[0].items;
  1264. var y1items = transformedTiles[1].items;
  1265. var y2items = transformedTiles[2].items;
  1266. var y3items = fourComponents ? transformedTiles[3].items : null;
  1267. shift = components[0].precision - 8;
  1268. offset = (128 << shift) + 0.5;
  1269. max = 255 * (1 << shift);
  1270. maxK = max * 0.5;
  1271. min = -maxK;
  1272. var component0 = tile.components[0];
  1273. var alpha01 = componentsCount - 3;
  1274. jj = y0items.length;
  1275. if (!component0.codingStyleParameters.reversibleTransformation) {
  1276. for (j = 0; j < jj; j++, pos += alpha01) {
  1277. y0 = y0items[j] + offset;
  1278. y1 = y1items[j];
  1279. y2 = y2items[j];
  1280. r = y0 + 1.402 * y2;
  1281. g = y0 - 0.34413 * y1 - 0.71414 * y2;
  1282. b = y0 + 1.772 * y1;
  1283. out[pos++] = r <= 0 ? 0 : r >= max ? 255 : r >> shift;
  1284. out[pos++] = g <= 0 ? 0 : g >= max ? 255 : g >> shift;
  1285. out[pos++] = b <= 0 ? 0 : b >= max ? 255 : b >> shift;
  1286. }
  1287. } else {
  1288. for (j = 0; j < jj; j++, pos += alpha01) {
  1289. y0 = y0items[j] + offset;
  1290. y1 = y1items[j];
  1291. y2 = y2items[j];
  1292. g = y0 - (y2 + y1 >> 2);
  1293. r = g + y2;
  1294. b = g + y1;
  1295. out[pos++] = r <= 0 ? 0 : r >= max ? 255 : r >> shift;
  1296. out[pos++] = g <= 0 ? 0 : g >= max ? 255 : g >> shift;
  1297. out[pos++] = b <= 0 ? 0 : b >= max ? 255 : b >> shift;
  1298. }
  1299. }
  1300. if (fourComponents) {
  1301. for (j = 0, pos = 3; j < jj; j++, pos += 4) {
  1302. k = y3items[j];
  1303. out[pos] = k <= min ? 0 : k >= maxK ? 255 : k + offset >> shift;
  1304. }
  1305. }
  1306. } else {
  1307. for (c = 0; c < componentsCount; c++) {
  1308. var items = transformedTiles[c].items;
  1309. shift = components[c].precision - 8;
  1310. offset = (128 << shift) + 0.5;
  1311. max = 127.5 * (1 << shift);
  1312. min = -max;
  1313. for (pos = c, j = 0, jj = items.length; j < jj; j++) {
  1314. val = items[j];
  1315. out[pos] = val <= min ? 0 : val >= max ? 255 : val + 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. (0, _util.error)('JPX Error: 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;