jpx.js 72 KB

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