jpx.js 64 KB

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