jpx.js 72 KB

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