jpx.js 72 KB

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