jbig2.js 59 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158
  1. /**
  2. * @licstart The following is the entire license notice for the
  3. * JavaScript code in this page
  4. *
  5. * Copyright 2022 Mozilla Foundation
  6. *
  7. * Licensed under the Apache License, Version 2.0 (the "License");
  8. * you may not use this file except in compliance with the License.
  9. * You may obtain a copy of the License at
  10. *
  11. * http://www.apache.org/licenses/LICENSE-2.0
  12. *
  13. * Unless required by applicable law or agreed to in writing, software
  14. * distributed under the License is distributed on an "AS IS" BASIS,
  15. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  16. * See the License for the specific language governing permissions and
  17. * limitations under the License.
  18. *
  19. * @licend The above is the entire license notice for the
  20. * JavaScript code in this page
  21. */
  22. "use strict";
  23. Object.defineProperty(exports, "__esModule", {
  24. value: true
  25. });
  26. exports.Jbig2Image = void 0;
  27. var _util = require("../shared/util.js");
  28. var _core_utils = require("./core_utils.js");
  29. var _arithmetic_decoder = require("./arithmetic_decoder.js");
  30. var _ccitt = require("./ccitt.js");
  31. class Jbig2Error extends _util.BaseException {
  32. constructor(msg) {
  33. super(`JBIG2 error: ${msg}`, "Jbig2Error");
  34. }
  35. }
  36. class ContextCache {
  37. getContexts(id) {
  38. if (id in this) {
  39. return this[id];
  40. }
  41. return this[id] = new Int8Array(1 << 16);
  42. }
  43. }
  44. class DecodingContext {
  45. constructor(data, start, end) {
  46. this.data = data;
  47. this.start = start;
  48. this.end = end;
  49. }
  50. get decoder() {
  51. const decoder = new _arithmetic_decoder.ArithmeticDecoder(this.data, this.start, this.end);
  52. return (0, _util.shadow)(this, "decoder", decoder);
  53. }
  54. get contextCache() {
  55. const cache = new ContextCache();
  56. return (0, _util.shadow)(this, "contextCache", cache);
  57. }
  58. }
  59. function decodeInteger(contextCache, procedure, decoder) {
  60. const contexts = contextCache.getContexts(procedure);
  61. let prev = 1;
  62. function readBits(length) {
  63. let v = 0;
  64. for (let i = 0; i < length; i++) {
  65. const bit = decoder.readBit(contexts, prev);
  66. prev = prev < 256 ? prev << 1 | bit : (prev << 1 | bit) & 511 | 256;
  67. v = v << 1 | bit;
  68. }
  69. return v >>> 0;
  70. }
  71. const sign = readBits(1);
  72. const value = readBits(1) ? readBits(1) ? readBits(1) ? readBits(1) ? readBits(1) ? readBits(32) + 4436 : readBits(12) + 340 : readBits(8) + 84 : readBits(6) + 20 : readBits(4) + 4 : readBits(2);
  73. if (sign === 0) {
  74. return value;
  75. } else if (value > 0) {
  76. return -value;
  77. }
  78. return null;
  79. }
  80. function decodeIAID(contextCache, decoder, codeLength) {
  81. const contexts = contextCache.getContexts("IAID");
  82. let prev = 1;
  83. for (let i = 0; i < codeLength; i++) {
  84. const bit = decoder.readBit(contexts, prev);
  85. prev = prev << 1 | bit;
  86. }
  87. if (codeLength < 31) {
  88. return prev & (1 << codeLength) - 1;
  89. }
  90. return prev & 0x7fffffff;
  91. }
  92. const SegmentTypes = ["SymbolDictionary", null, null, null, "IntermediateTextRegion", null, "ImmediateTextRegion", "ImmediateLosslessTextRegion", null, null, null, null, null, null, null, null, "PatternDictionary", null, null, null, "IntermediateHalftoneRegion", null, "ImmediateHalftoneRegion", "ImmediateLosslessHalftoneRegion", null, null, null, null, null, null, null, null, null, null, null, null, "IntermediateGenericRegion", null, "ImmediateGenericRegion", "ImmediateLosslessGenericRegion", "IntermediateGenericRefinementRegion", null, "ImmediateGenericRefinementRegion", "ImmediateLosslessGenericRefinementRegion", null, null, null, null, "PageInformation", "EndOfPage", "EndOfStripe", "EndOfFile", "Profiles", "Tables", null, null, null, null, null, null, null, null, "Extension"];
  93. const CodingTemplates = [[{
  94. x: -1,
  95. y: -2
  96. }, {
  97. x: 0,
  98. y: -2
  99. }, {
  100. x: 1,
  101. y: -2
  102. }, {
  103. x: -2,
  104. y: -1
  105. }, {
  106. x: -1,
  107. y: -1
  108. }, {
  109. x: 0,
  110. y: -1
  111. }, {
  112. x: 1,
  113. y: -1
  114. }, {
  115. x: 2,
  116. y: -1
  117. }, {
  118. x: -4,
  119. y: 0
  120. }, {
  121. x: -3,
  122. y: 0
  123. }, {
  124. x: -2,
  125. y: 0
  126. }, {
  127. x: -1,
  128. y: 0
  129. }], [{
  130. x: -1,
  131. y: -2
  132. }, {
  133. x: 0,
  134. y: -2
  135. }, {
  136. x: 1,
  137. y: -2
  138. }, {
  139. x: 2,
  140. y: -2
  141. }, {
  142. x: -2,
  143. y: -1
  144. }, {
  145. x: -1,
  146. y: -1
  147. }, {
  148. x: 0,
  149. y: -1
  150. }, {
  151. x: 1,
  152. y: -1
  153. }, {
  154. x: 2,
  155. y: -1
  156. }, {
  157. x: -3,
  158. y: 0
  159. }, {
  160. x: -2,
  161. y: 0
  162. }, {
  163. x: -1,
  164. y: 0
  165. }], [{
  166. x: -1,
  167. y: -2
  168. }, {
  169. x: 0,
  170. y: -2
  171. }, {
  172. x: 1,
  173. y: -2
  174. }, {
  175. x: -2,
  176. y: -1
  177. }, {
  178. x: -1,
  179. y: -1
  180. }, {
  181. x: 0,
  182. y: -1
  183. }, {
  184. x: 1,
  185. y: -1
  186. }, {
  187. x: -2,
  188. y: 0
  189. }, {
  190. x: -1,
  191. y: 0
  192. }], [{
  193. x: -3,
  194. y: -1
  195. }, {
  196. x: -2,
  197. y: -1
  198. }, {
  199. x: -1,
  200. y: -1
  201. }, {
  202. x: 0,
  203. y: -1
  204. }, {
  205. x: 1,
  206. y: -1
  207. }, {
  208. x: -4,
  209. y: 0
  210. }, {
  211. x: -3,
  212. y: 0
  213. }, {
  214. x: -2,
  215. y: 0
  216. }, {
  217. x: -1,
  218. y: 0
  219. }]];
  220. const RefinementTemplates = [{
  221. coding: [{
  222. x: 0,
  223. y: -1
  224. }, {
  225. x: 1,
  226. y: -1
  227. }, {
  228. x: -1,
  229. y: 0
  230. }],
  231. reference: [{
  232. x: 0,
  233. y: -1
  234. }, {
  235. x: 1,
  236. y: -1
  237. }, {
  238. x: -1,
  239. y: 0
  240. }, {
  241. x: 0,
  242. y: 0
  243. }, {
  244. x: 1,
  245. y: 0
  246. }, {
  247. x: -1,
  248. y: 1
  249. }, {
  250. x: 0,
  251. y: 1
  252. }, {
  253. x: 1,
  254. y: 1
  255. }]
  256. }, {
  257. coding: [{
  258. x: -1,
  259. y: -1
  260. }, {
  261. x: 0,
  262. y: -1
  263. }, {
  264. x: 1,
  265. y: -1
  266. }, {
  267. x: -1,
  268. y: 0
  269. }],
  270. reference: [{
  271. x: 0,
  272. y: -1
  273. }, {
  274. x: -1,
  275. y: 0
  276. }, {
  277. x: 0,
  278. y: 0
  279. }, {
  280. x: 1,
  281. y: 0
  282. }, {
  283. x: 0,
  284. y: 1
  285. }, {
  286. x: 1,
  287. y: 1
  288. }]
  289. }];
  290. const ReusedContexts = [0x9b25, 0x0795, 0x00e5, 0x0195];
  291. const RefinementReusedContexts = [0x0020, 0x0008];
  292. function decodeBitmapTemplate0(width, height, decodingContext) {
  293. const decoder = decodingContext.decoder;
  294. const contexts = decodingContext.contextCache.getContexts("GB");
  295. const bitmap = [];
  296. let contextLabel, i, j, pixel, row, row1, row2;
  297. const OLD_PIXEL_MASK = 0x7bf7;
  298. for (i = 0; i < height; i++) {
  299. row = bitmap[i] = new Uint8Array(width);
  300. row1 = i < 1 ? row : bitmap[i - 1];
  301. row2 = i < 2 ? row : bitmap[i - 2];
  302. contextLabel = row2[0] << 13 | row2[1] << 12 | row2[2] << 11 | row1[0] << 7 | row1[1] << 6 | row1[2] << 5 | row1[3] << 4;
  303. for (j = 0; j < width; j++) {
  304. row[j] = pixel = decoder.readBit(contexts, contextLabel);
  305. contextLabel = (contextLabel & OLD_PIXEL_MASK) << 1 | (j + 3 < width ? row2[j + 3] << 11 : 0) | (j + 4 < width ? row1[j + 4] << 4 : 0) | pixel;
  306. }
  307. }
  308. return bitmap;
  309. }
  310. function decodeBitmap(mmr, width, height, templateIndex, prediction, skip, at, decodingContext) {
  311. if (mmr) {
  312. const input = new Reader(decodingContext.data, decodingContext.start, decodingContext.end);
  313. return decodeMMRBitmap(input, width, height, false);
  314. }
  315. if (templateIndex === 0 && !skip && !prediction && at.length === 4 && at[0].x === 3 && at[0].y === -1 && at[1].x === -3 && at[1].y === -1 && at[2].x === 2 && at[2].y === -2 && at[3].x === -2 && at[3].y === -2) {
  316. return decodeBitmapTemplate0(width, height, decodingContext);
  317. }
  318. const useskip = !!skip;
  319. const template = CodingTemplates[templateIndex].concat(at);
  320. template.sort(function (a, b) {
  321. return a.y - b.y || a.x - b.x;
  322. });
  323. const templateLength = template.length;
  324. const templateX = new Int8Array(templateLength);
  325. const templateY = new Int8Array(templateLength);
  326. const changingTemplateEntries = [];
  327. let reuseMask = 0,
  328. minX = 0,
  329. maxX = 0,
  330. minY = 0;
  331. let c, k;
  332. for (k = 0; k < templateLength; k++) {
  333. templateX[k] = template[k].x;
  334. templateY[k] = template[k].y;
  335. minX = Math.min(minX, template[k].x);
  336. maxX = Math.max(maxX, template[k].x);
  337. minY = Math.min(minY, template[k].y);
  338. if (k < templateLength - 1 && template[k].y === template[k + 1].y && template[k].x === template[k + 1].x - 1) {
  339. reuseMask |= 1 << templateLength - 1 - k;
  340. } else {
  341. changingTemplateEntries.push(k);
  342. }
  343. }
  344. const changingEntriesLength = changingTemplateEntries.length;
  345. const changingTemplateX = new Int8Array(changingEntriesLength);
  346. const changingTemplateY = new Int8Array(changingEntriesLength);
  347. const changingTemplateBit = new Uint16Array(changingEntriesLength);
  348. for (c = 0; c < changingEntriesLength; c++) {
  349. k = changingTemplateEntries[c];
  350. changingTemplateX[c] = template[k].x;
  351. changingTemplateY[c] = template[k].y;
  352. changingTemplateBit[c] = 1 << templateLength - 1 - k;
  353. }
  354. const sbb_left = -minX;
  355. const sbb_top = -minY;
  356. const sbb_right = width - maxX;
  357. const pseudoPixelContext = ReusedContexts[templateIndex];
  358. let row = new Uint8Array(width);
  359. const bitmap = [];
  360. const decoder = decodingContext.decoder;
  361. const contexts = decodingContext.contextCache.getContexts("GB");
  362. let ltp = 0,
  363. j,
  364. i0,
  365. j0,
  366. contextLabel = 0,
  367. bit,
  368. shift;
  369. for (let i = 0; i < height; i++) {
  370. if (prediction) {
  371. const sltp = decoder.readBit(contexts, pseudoPixelContext);
  372. ltp ^= sltp;
  373. if (ltp) {
  374. bitmap.push(row);
  375. continue;
  376. }
  377. }
  378. row = new Uint8Array(row);
  379. bitmap.push(row);
  380. for (j = 0; j < width; j++) {
  381. if (useskip && skip[i][j]) {
  382. row[j] = 0;
  383. continue;
  384. }
  385. if (j >= sbb_left && j < sbb_right && i >= sbb_top) {
  386. contextLabel = contextLabel << 1 & reuseMask;
  387. for (k = 0; k < changingEntriesLength; k++) {
  388. i0 = i + changingTemplateY[k];
  389. j0 = j + changingTemplateX[k];
  390. bit = bitmap[i0][j0];
  391. if (bit) {
  392. bit = changingTemplateBit[k];
  393. contextLabel |= bit;
  394. }
  395. }
  396. } else {
  397. contextLabel = 0;
  398. shift = templateLength - 1;
  399. for (k = 0; k < templateLength; k++, shift--) {
  400. j0 = j + templateX[k];
  401. if (j0 >= 0 && j0 < width) {
  402. i0 = i + templateY[k];
  403. if (i0 >= 0) {
  404. bit = bitmap[i0][j0];
  405. if (bit) {
  406. contextLabel |= bit << shift;
  407. }
  408. }
  409. }
  410. }
  411. }
  412. const pixel = decoder.readBit(contexts, contextLabel);
  413. row[j] = pixel;
  414. }
  415. }
  416. return bitmap;
  417. }
  418. function decodeRefinement(width, height, templateIndex, referenceBitmap, offsetX, offsetY, prediction, at, decodingContext) {
  419. let codingTemplate = RefinementTemplates[templateIndex].coding;
  420. if (templateIndex === 0) {
  421. codingTemplate = codingTemplate.concat([at[0]]);
  422. }
  423. const codingTemplateLength = codingTemplate.length;
  424. const codingTemplateX = new Int32Array(codingTemplateLength);
  425. const codingTemplateY = new Int32Array(codingTemplateLength);
  426. let k;
  427. for (k = 0; k < codingTemplateLength; k++) {
  428. codingTemplateX[k] = codingTemplate[k].x;
  429. codingTemplateY[k] = codingTemplate[k].y;
  430. }
  431. let referenceTemplate = RefinementTemplates[templateIndex].reference;
  432. if (templateIndex === 0) {
  433. referenceTemplate = referenceTemplate.concat([at[1]]);
  434. }
  435. const referenceTemplateLength = referenceTemplate.length;
  436. const referenceTemplateX = new Int32Array(referenceTemplateLength);
  437. const referenceTemplateY = new Int32Array(referenceTemplateLength);
  438. for (k = 0; k < referenceTemplateLength; k++) {
  439. referenceTemplateX[k] = referenceTemplate[k].x;
  440. referenceTemplateY[k] = referenceTemplate[k].y;
  441. }
  442. const referenceWidth = referenceBitmap[0].length;
  443. const referenceHeight = referenceBitmap.length;
  444. const pseudoPixelContext = RefinementReusedContexts[templateIndex];
  445. const bitmap = [];
  446. const decoder = decodingContext.decoder;
  447. const contexts = decodingContext.contextCache.getContexts("GR");
  448. let ltp = 0;
  449. for (let i = 0; i < height; i++) {
  450. if (prediction) {
  451. const sltp = decoder.readBit(contexts, pseudoPixelContext);
  452. ltp ^= sltp;
  453. if (ltp) {
  454. throw new Jbig2Error("prediction is not supported");
  455. }
  456. }
  457. const row = new Uint8Array(width);
  458. bitmap.push(row);
  459. for (let j = 0; j < width; j++) {
  460. let i0, j0;
  461. let contextLabel = 0;
  462. for (k = 0; k < codingTemplateLength; k++) {
  463. i0 = i + codingTemplateY[k];
  464. j0 = j + codingTemplateX[k];
  465. if (i0 < 0 || j0 < 0 || j0 >= width) {
  466. contextLabel <<= 1;
  467. } else {
  468. contextLabel = contextLabel << 1 | bitmap[i0][j0];
  469. }
  470. }
  471. for (k = 0; k < referenceTemplateLength; k++) {
  472. i0 = i + referenceTemplateY[k] - offsetY;
  473. j0 = j + referenceTemplateX[k] - offsetX;
  474. if (i0 < 0 || i0 >= referenceHeight || j0 < 0 || j0 >= referenceWidth) {
  475. contextLabel <<= 1;
  476. } else {
  477. contextLabel = contextLabel << 1 | referenceBitmap[i0][j0];
  478. }
  479. }
  480. const pixel = decoder.readBit(contexts, contextLabel);
  481. row[j] = pixel;
  482. }
  483. }
  484. return bitmap;
  485. }
  486. function decodeSymbolDictionary(huffman, refinement, symbols, numberOfNewSymbols, numberOfExportedSymbols, huffmanTables, templateIndex, at, refinementTemplateIndex, refinementAt, decodingContext, huffmanInput) {
  487. if (huffman && refinement) {
  488. throw new Jbig2Error("symbol refinement with Huffman is not supported");
  489. }
  490. const newSymbols = [];
  491. let currentHeight = 0;
  492. let symbolCodeLength = (0, _core_utils.log2)(symbols.length + numberOfNewSymbols);
  493. const decoder = decodingContext.decoder;
  494. const contextCache = decodingContext.contextCache;
  495. let tableB1, symbolWidths;
  496. if (huffman) {
  497. tableB1 = getStandardTable(1);
  498. symbolWidths = [];
  499. symbolCodeLength = Math.max(symbolCodeLength, 1);
  500. }
  501. while (newSymbols.length < numberOfNewSymbols) {
  502. const deltaHeight = huffman ? huffmanTables.tableDeltaHeight.decode(huffmanInput) : decodeInteger(contextCache, "IADH", decoder);
  503. currentHeight += deltaHeight;
  504. let currentWidth = 0,
  505. totalWidth = 0;
  506. const firstSymbol = huffman ? symbolWidths.length : 0;
  507. while (true) {
  508. const deltaWidth = huffman ? huffmanTables.tableDeltaWidth.decode(huffmanInput) : decodeInteger(contextCache, "IADW", decoder);
  509. if (deltaWidth === null) {
  510. break;
  511. }
  512. currentWidth += deltaWidth;
  513. totalWidth += currentWidth;
  514. let bitmap;
  515. if (refinement) {
  516. const numberOfInstances = decodeInteger(contextCache, "IAAI", decoder);
  517. if (numberOfInstances > 1) {
  518. bitmap = decodeTextRegion(huffman, refinement, currentWidth, currentHeight, 0, numberOfInstances, 1, symbols.concat(newSymbols), symbolCodeLength, 0, 0, 1, 0, huffmanTables, refinementTemplateIndex, refinementAt, decodingContext, 0, huffmanInput);
  519. } else {
  520. const symbolId = decodeIAID(contextCache, decoder, symbolCodeLength);
  521. const rdx = decodeInteger(contextCache, "IARDX", decoder);
  522. const rdy = decodeInteger(contextCache, "IARDY", decoder);
  523. const symbol = symbolId < symbols.length ? symbols[symbolId] : newSymbols[symbolId - symbols.length];
  524. bitmap = decodeRefinement(currentWidth, currentHeight, refinementTemplateIndex, symbol, rdx, rdy, false, refinementAt, decodingContext);
  525. }
  526. newSymbols.push(bitmap);
  527. } else if (huffman) {
  528. symbolWidths.push(currentWidth);
  529. } else {
  530. bitmap = decodeBitmap(false, currentWidth, currentHeight, templateIndex, false, null, at, decodingContext);
  531. newSymbols.push(bitmap);
  532. }
  533. }
  534. if (huffman && !refinement) {
  535. const bitmapSize = huffmanTables.tableBitmapSize.decode(huffmanInput);
  536. huffmanInput.byteAlign();
  537. let collectiveBitmap;
  538. if (bitmapSize === 0) {
  539. collectiveBitmap = readUncompressedBitmap(huffmanInput, totalWidth, currentHeight);
  540. } else {
  541. const originalEnd = huffmanInput.end;
  542. const bitmapEnd = huffmanInput.position + bitmapSize;
  543. huffmanInput.end = bitmapEnd;
  544. collectiveBitmap = decodeMMRBitmap(huffmanInput, totalWidth, currentHeight, false);
  545. huffmanInput.end = originalEnd;
  546. huffmanInput.position = bitmapEnd;
  547. }
  548. const numberOfSymbolsDecoded = symbolWidths.length;
  549. if (firstSymbol === numberOfSymbolsDecoded - 1) {
  550. newSymbols.push(collectiveBitmap);
  551. } else {
  552. let i,
  553. y,
  554. xMin = 0,
  555. xMax,
  556. bitmapWidth,
  557. symbolBitmap;
  558. for (i = firstSymbol; i < numberOfSymbolsDecoded; i++) {
  559. bitmapWidth = symbolWidths[i];
  560. xMax = xMin + bitmapWidth;
  561. symbolBitmap = [];
  562. for (y = 0; y < currentHeight; y++) {
  563. symbolBitmap.push(collectiveBitmap[y].subarray(xMin, xMax));
  564. }
  565. newSymbols.push(symbolBitmap);
  566. xMin = xMax;
  567. }
  568. }
  569. }
  570. }
  571. const exportedSymbols = [],
  572. flags = [];
  573. let currentFlag = false,
  574. i,
  575. ii;
  576. const totalSymbolsLength = symbols.length + numberOfNewSymbols;
  577. while (flags.length < totalSymbolsLength) {
  578. let runLength = huffman ? tableB1.decode(huffmanInput) : decodeInteger(contextCache, "IAEX", decoder);
  579. while (runLength--) {
  580. flags.push(currentFlag);
  581. }
  582. currentFlag = !currentFlag;
  583. }
  584. for (i = 0, ii = symbols.length; i < ii; i++) {
  585. if (flags[i]) {
  586. exportedSymbols.push(symbols[i]);
  587. }
  588. }
  589. for (let j = 0; j < numberOfNewSymbols; i++, j++) {
  590. if (flags[i]) {
  591. exportedSymbols.push(newSymbols[j]);
  592. }
  593. }
  594. return exportedSymbols;
  595. }
  596. function decodeTextRegion(huffman, refinement, width, height, defaultPixelValue, numberOfSymbolInstances, stripSize, inputSymbols, symbolCodeLength, transposed, dsOffset, referenceCorner, combinationOperator, huffmanTables, refinementTemplateIndex, refinementAt, decodingContext, logStripSize, huffmanInput) {
  597. if (huffman && refinement) {
  598. throw new Jbig2Error("refinement with Huffman is not supported");
  599. }
  600. const bitmap = [];
  601. let i, row;
  602. for (i = 0; i < height; i++) {
  603. row = new Uint8Array(width);
  604. if (defaultPixelValue) {
  605. for (let j = 0; j < width; j++) {
  606. row[j] = defaultPixelValue;
  607. }
  608. }
  609. bitmap.push(row);
  610. }
  611. const decoder = decodingContext.decoder;
  612. const contextCache = decodingContext.contextCache;
  613. let stripT = huffman ? -huffmanTables.tableDeltaT.decode(huffmanInput) : -decodeInteger(contextCache, "IADT", decoder);
  614. let firstS = 0;
  615. i = 0;
  616. while (i < numberOfSymbolInstances) {
  617. const deltaT = huffman ? huffmanTables.tableDeltaT.decode(huffmanInput) : decodeInteger(contextCache, "IADT", decoder);
  618. stripT += deltaT;
  619. const deltaFirstS = huffman ? huffmanTables.tableFirstS.decode(huffmanInput) : decodeInteger(contextCache, "IAFS", decoder);
  620. firstS += deltaFirstS;
  621. let currentS = firstS;
  622. do {
  623. let currentT = 0;
  624. if (stripSize > 1) {
  625. currentT = huffman ? huffmanInput.readBits(logStripSize) : decodeInteger(contextCache, "IAIT", decoder);
  626. }
  627. const t = stripSize * stripT + currentT;
  628. const symbolId = huffman ? huffmanTables.symbolIDTable.decode(huffmanInput) : decodeIAID(contextCache, decoder, symbolCodeLength);
  629. const applyRefinement = refinement && (huffman ? huffmanInput.readBit() : decodeInteger(contextCache, "IARI", decoder));
  630. let symbolBitmap = inputSymbols[symbolId];
  631. let symbolWidth = symbolBitmap[0].length;
  632. let symbolHeight = symbolBitmap.length;
  633. if (applyRefinement) {
  634. const rdw = decodeInteger(contextCache, "IARDW", decoder);
  635. const rdh = decodeInteger(contextCache, "IARDH", decoder);
  636. const rdx = decodeInteger(contextCache, "IARDX", decoder);
  637. const rdy = decodeInteger(contextCache, "IARDY", decoder);
  638. symbolWidth += rdw;
  639. symbolHeight += rdh;
  640. symbolBitmap = decodeRefinement(symbolWidth, symbolHeight, refinementTemplateIndex, symbolBitmap, (rdw >> 1) + rdx, (rdh >> 1) + rdy, false, refinementAt, decodingContext);
  641. }
  642. const offsetT = t - (referenceCorner & 1 ? 0 : symbolHeight - 1);
  643. const offsetS = currentS - (referenceCorner & 2 ? symbolWidth - 1 : 0);
  644. let s2, t2, symbolRow;
  645. if (transposed) {
  646. for (s2 = 0; s2 < symbolHeight; s2++) {
  647. row = bitmap[offsetS + s2];
  648. if (!row) {
  649. continue;
  650. }
  651. symbolRow = symbolBitmap[s2];
  652. const maxWidth = Math.min(width - offsetT, symbolWidth);
  653. switch (combinationOperator) {
  654. case 0:
  655. for (t2 = 0; t2 < maxWidth; t2++) {
  656. row[offsetT + t2] |= symbolRow[t2];
  657. }
  658. break;
  659. case 2:
  660. for (t2 = 0; t2 < maxWidth; t2++) {
  661. row[offsetT + t2] ^= symbolRow[t2];
  662. }
  663. break;
  664. default:
  665. throw new Jbig2Error(`operator ${combinationOperator} is not supported`);
  666. }
  667. }
  668. currentS += symbolHeight - 1;
  669. } else {
  670. for (t2 = 0; t2 < symbolHeight; t2++) {
  671. row = bitmap[offsetT + t2];
  672. if (!row) {
  673. continue;
  674. }
  675. symbolRow = symbolBitmap[t2];
  676. switch (combinationOperator) {
  677. case 0:
  678. for (s2 = 0; s2 < symbolWidth; s2++) {
  679. row[offsetS + s2] |= symbolRow[s2];
  680. }
  681. break;
  682. case 2:
  683. for (s2 = 0; s2 < symbolWidth; s2++) {
  684. row[offsetS + s2] ^= symbolRow[s2];
  685. }
  686. break;
  687. default:
  688. throw new Jbig2Error(`operator ${combinationOperator} is not supported`);
  689. }
  690. }
  691. currentS += symbolWidth - 1;
  692. }
  693. i++;
  694. const deltaS = huffman ? huffmanTables.tableDeltaS.decode(huffmanInput) : decodeInteger(contextCache, "IADS", decoder);
  695. if (deltaS === null) {
  696. break;
  697. }
  698. currentS += deltaS + dsOffset;
  699. } while (true);
  700. }
  701. return bitmap;
  702. }
  703. function decodePatternDictionary(mmr, patternWidth, patternHeight, maxPatternIndex, template, decodingContext) {
  704. const at = [];
  705. if (!mmr) {
  706. at.push({
  707. x: -patternWidth,
  708. y: 0
  709. });
  710. if (template === 0) {
  711. at.push({
  712. x: -3,
  713. y: -1
  714. }, {
  715. x: 2,
  716. y: -2
  717. }, {
  718. x: -2,
  719. y: -2
  720. });
  721. }
  722. }
  723. const collectiveWidth = (maxPatternIndex + 1) * patternWidth;
  724. const collectiveBitmap = decodeBitmap(mmr, collectiveWidth, patternHeight, template, false, null, at, decodingContext);
  725. const patterns = [];
  726. for (let i = 0; i <= maxPatternIndex; i++) {
  727. const patternBitmap = [];
  728. const xMin = patternWidth * i;
  729. const xMax = xMin + patternWidth;
  730. for (let y = 0; y < patternHeight; y++) {
  731. patternBitmap.push(collectiveBitmap[y].subarray(xMin, xMax));
  732. }
  733. patterns.push(patternBitmap);
  734. }
  735. return patterns;
  736. }
  737. function decodeHalftoneRegion(mmr, patterns, template, regionWidth, regionHeight, defaultPixelValue, enableSkip, combinationOperator, gridWidth, gridHeight, gridOffsetX, gridOffsetY, gridVectorX, gridVectorY, decodingContext) {
  738. const skip = null;
  739. if (enableSkip) {
  740. throw new Jbig2Error("skip is not supported");
  741. }
  742. if (combinationOperator !== 0) {
  743. throw new Jbig2Error(`operator "${combinationOperator}" is not supported in halftone region`);
  744. }
  745. const regionBitmap = [];
  746. let i, j, row;
  747. for (i = 0; i < regionHeight; i++) {
  748. row = new Uint8Array(regionWidth);
  749. if (defaultPixelValue) {
  750. for (j = 0; j < regionWidth; j++) {
  751. row[j] = defaultPixelValue;
  752. }
  753. }
  754. regionBitmap.push(row);
  755. }
  756. const numberOfPatterns = patterns.length;
  757. const pattern0 = patterns[0];
  758. const patternWidth = pattern0[0].length,
  759. patternHeight = pattern0.length;
  760. const bitsPerValue = (0, _core_utils.log2)(numberOfPatterns);
  761. const at = [];
  762. if (!mmr) {
  763. at.push({
  764. x: template <= 1 ? 3 : 2,
  765. y: -1
  766. });
  767. if (template === 0) {
  768. at.push({
  769. x: -3,
  770. y: -1
  771. }, {
  772. x: 2,
  773. y: -2
  774. }, {
  775. x: -2,
  776. y: -2
  777. });
  778. }
  779. }
  780. const grayScaleBitPlanes = [];
  781. let mmrInput, bitmap;
  782. if (mmr) {
  783. mmrInput = new Reader(decodingContext.data, decodingContext.start, decodingContext.end);
  784. }
  785. for (i = bitsPerValue - 1; i >= 0; i--) {
  786. if (mmr) {
  787. bitmap = decodeMMRBitmap(mmrInput, gridWidth, gridHeight, true);
  788. } else {
  789. bitmap = decodeBitmap(false, gridWidth, gridHeight, template, false, skip, at, decodingContext);
  790. }
  791. grayScaleBitPlanes[i] = bitmap;
  792. }
  793. let mg, ng, bit, patternIndex, patternBitmap, x, y, patternRow, regionRow;
  794. for (mg = 0; mg < gridHeight; mg++) {
  795. for (ng = 0; ng < gridWidth; ng++) {
  796. bit = 0;
  797. patternIndex = 0;
  798. for (j = bitsPerValue - 1; j >= 0; j--) {
  799. bit ^= grayScaleBitPlanes[j][mg][ng];
  800. patternIndex |= bit << j;
  801. }
  802. patternBitmap = patterns[patternIndex];
  803. x = gridOffsetX + mg * gridVectorY + ng * gridVectorX >> 8;
  804. y = gridOffsetY + mg * gridVectorX - ng * gridVectorY >> 8;
  805. if (x >= 0 && x + patternWidth <= regionWidth && y >= 0 && y + patternHeight <= regionHeight) {
  806. for (i = 0; i < patternHeight; i++) {
  807. regionRow = regionBitmap[y + i];
  808. patternRow = patternBitmap[i];
  809. for (j = 0; j < patternWidth; j++) {
  810. regionRow[x + j] |= patternRow[j];
  811. }
  812. }
  813. } else {
  814. let regionX, regionY;
  815. for (i = 0; i < patternHeight; i++) {
  816. regionY = y + i;
  817. if (regionY < 0 || regionY >= regionHeight) {
  818. continue;
  819. }
  820. regionRow = regionBitmap[regionY];
  821. patternRow = patternBitmap[i];
  822. for (j = 0; j < patternWidth; j++) {
  823. regionX = x + j;
  824. if (regionX >= 0 && regionX < regionWidth) {
  825. regionRow[regionX] |= patternRow[j];
  826. }
  827. }
  828. }
  829. }
  830. }
  831. }
  832. return regionBitmap;
  833. }
  834. function readSegmentHeader(data, start) {
  835. const segmentHeader = {};
  836. segmentHeader.number = (0, _core_utils.readUint32)(data, start);
  837. const flags = data[start + 4];
  838. const segmentType = flags & 0x3f;
  839. if (!SegmentTypes[segmentType]) {
  840. throw new Jbig2Error("invalid segment type: " + segmentType);
  841. }
  842. segmentHeader.type = segmentType;
  843. segmentHeader.typeName = SegmentTypes[segmentType];
  844. segmentHeader.deferredNonRetain = !!(flags & 0x80);
  845. const pageAssociationFieldSize = !!(flags & 0x40);
  846. const referredFlags = data[start + 5];
  847. let referredToCount = referredFlags >> 5 & 7;
  848. const retainBits = [referredFlags & 31];
  849. let position = start + 6;
  850. if (referredFlags === 7) {
  851. referredToCount = (0, _core_utils.readUint32)(data, position - 1) & 0x1fffffff;
  852. position += 3;
  853. let bytes = referredToCount + 7 >> 3;
  854. retainBits[0] = data[position++];
  855. while (--bytes > 0) {
  856. retainBits.push(data[position++]);
  857. }
  858. } else if (referredFlags === 5 || referredFlags === 6) {
  859. throw new Jbig2Error("invalid referred-to flags");
  860. }
  861. segmentHeader.retainBits = retainBits;
  862. let referredToSegmentNumberSize = 4;
  863. if (segmentHeader.number <= 256) {
  864. referredToSegmentNumberSize = 1;
  865. } else if (segmentHeader.number <= 65536) {
  866. referredToSegmentNumberSize = 2;
  867. }
  868. const referredTo = [];
  869. let i, ii;
  870. for (i = 0; i < referredToCount; i++) {
  871. let number;
  872. if (referredToSegmentNumberSize === 1) {
  873. number = data[position];
  874. } else if (referredToSegmentNumberSize === 2) {
  875. number = (0, _core_utils.readUint16)(data, position);
  876. } else {
  877. number = (0, _core_utils.readUint32)(data, position);
  878. }
  879. referredTo.push(number);
  880. position += referredToSegmentNumberSize;
  881. }
  882. segmentHeader.referredTo = referredTo;
  883. if (!pageAssociationFieldSize) {
  884. segmentHeader.pageAssociation = data[position++];
  885. } else {
  886. segmentHeader.pageAssociation = (0, _core_utils.readUint32)(data, position);
  887. position += 4;
  888. }
  889. segmentHeader.length = (0, _core_utils.readUint32)(data, position);
  890. position += 4;
  891. if (segmentHeader.length === 0xffffffff) {
  892. if (segmentType === 38) {
  893. const genericRegionInfo = readRegionSegmentInformation(data, position);
  894. const genericRegionSegmentFlags = data[position + RegionSegmentInformationFieldLength];
  895. const genericRegionMmr = !!(genericRegionSegmentFlags & 1);
  896. const searchPatternLength = 6;
  897. const searchPattern = new Uint8Array(searchPatternLength);
  898. if (!genericRegionMmr) {
  899. searchPattern[0] = 0xff;
  900. searchPattern[1] = 0xac;
  901. }
  902. searchPattern[2] = genericRegionInfo.height >>> 24 & 0xff;
  903. searchPattern[3] = genericRegionInfo.height >> 16 & 0xff;
  904. searchPattern[4] = genericRegionInfo.height >> 8 & 0xff;
  905. searchPattern[5] = genericRegionInfo.height & 0xff;
  906. for (i = position, ii = data.length; i < ii; i++) {
  907. let j = 0;
  908. while (j < searchPatternLength && searchPattern[j] === data[i + j]) {
  909. j++;
  910. }
  911. if (j === searchPatternLength) {
  912. segmentHeader.length = i + searchPatternLength;
  913. break;
  914. }
  915. }
  916. if (segmentHeader.length === 0xffffffff) {
  917. throw new Jbig2Error("segment end was not found");
  918. }
  919. } else {
  920. throw new Jbig2Error("invalid unknown segment length");
  921. }
  922. }
  923. segmentHeader.headerEnd = position;
  924. return segmentHeader;
  925. }
  926. function readSegments(header, data, start, end) {
  927. const segments = [];
  928. let position = start;
  929. while (position < end) {
  930. const segmentHeader = readSegmentHeader(data, position);
  931. position = segmentHeader.headerEnd;
  932. const segment = {
  933. header: segmentHeader,
  934. data
  935. };
  936. if (!header.randomAccess) {
  937. segment.start = position;
  938. position += segmentHeader.length;
  939. segment.end = position;
  940. }
  941. segments.push(segment);
  942. if (segmentHeader.type === 51) {
  943. break;
  944. }
  945. }
  946. if (header.randomAccess) {
  947. for (let i = 0, ii = segments.length; i < ii; i++) {
  948. segments[i].start = position;
  949. position += segments[i].header.length;
  950. segments[i].end = position;
  951. }
  952. }
  953. return segments;
  954. }
  955. function readRegionSegmentInformation(data, start) {
  956. return {
  957. width: (0, _core_utils.readUint32)(data, start),
  958. height: (0, _core_utils.readUint32)(data, start + 4),
  959. x: (0, _core_utils.readUint32)(data, start + 8),
  960. y: (0, _core_utils.readUint32)(data, start + 12),
  961. combinationOperator: data[start + 16] & 7
  962. };
  963. }
  964. const RegionSegmentInformationFieldLength = 17;
  965. function processSegment(segment, visitor) {
  966. const header = segment.header;
  967. const data = segment.data,
  968. end = segment.end;
  969. let position = segment.start;
  970. let args, at, i, atLength;
  971. switch (header.type) {
  972. case 0:
  973. const dictionary = {};
  974. const dictionaryFlags = (0, _core_utils.readUint16)(data, position);
  975. dictionary.huffman = !!(dictionaryFlags & 1);
  976. dictionary.refinement = !!(dictionaryFlags & 2);
  977. dictionary.huffmanDHSelector = dictionaryFlags >> 2 & 3;
  978. dictionary.huffmanDWSelector = dictionaryFlags >> 4 & 3;
  979. dictionary.bitmapSizeSelector = dictionaryFlags >> 6 & 1;
  980. dictionary.aggregationInstancesSelector = dictionaryFlags >> 7 & 1;
  981. dictionary.bitmapCodingContextUsed = !!(dictionaryFlags & 256);
  982. dictionary.bitmapCodingContextRetained = !!(dictionaryFlags & 512);
  983. dictionary.template = dictionaryFlags >> 10 & 3;
  984. dictionary.refinementTemplate = dictionaryFlags >> 12 & 1;
  985. position += 2;
  986. if (!dictionary.huffman) {
  987. atLength = dictionary.template === 0 ? 4 : 1;
  988. at = [];
  989. for (i = 0; i < atLength; i++) {
  990. at.push({
  991. x: (0, _core_utils.readInt8)(data, position),
  992. y: (0, _core_utils.readInt8)(data, position + 1)
  993. });
  994. position += 2;
  995. }
  996. dictionary.at = at;
  997. }
  998. if (dictionary.refinement && !dictionary.refinementTemplate) {
  999. at = [];
  1000. for (i = 0; i < 2; i++) {
  1001. at.push({
  1002. x: (0, _core_utils.readInt8)(data, position),
  1003. y: (0, _core_utils.readInt8)(data, position + 1)
  1004. });
  1005. position += 2;
  1006. }
  1007. dictionary.refinementAt = at;
  1008. }
  1009. dictionary.numberOfExportedSymbols = (0, _core_utils.readUint32)(data, position);
  1010. position += 4;
  1011. dictionary.numberOfNewSymbols = (0, _core_utils.readUint32)(data, position);
  1012. position += 4;
  1013. args = [dictionary, header.number, header.referredTo, data, position, end];
  1014. break;
  1015. case 6:
  1016. case 7:
  1017. const textRegion = {};
  1018. textRegion.info = readRegionSegmentInformation(data, position);
  1019. position += RegionSegmentInformationFieldLength;
  1020. const textRegionSegmentFlags = (0, _core_utils.readUint16)(data, position);
  1021. position += 2;
  1022. textRegion.huffman = !!(textRegionSegmentFlags & 1);
  1023. textRegion.refinement = !!(textRegionSegmentFlags & 2);
  1024. textRegion.logStripSize = textRegionSegmentFlags >> 2 & 3;
  1025. textRegion.stripSize = 1 << textRegion.logStripSize;
  1026. textRegion.referenceCorner = textRegionSegmentFlags >> 4 & 3;
  1027. textRegion.transposed = !!(textRegionSegmentFlags & 64);
  1028. textRegion.combinationOperator = textRegionSegmentFlags >> 7 & 3;
  1029. textRegion.defaultPixelValue = textRegionSegmentFlags >> 9 & 1;
  1030. textRegion.dsOffset = textRegionSegmentFlags << 17 >> 27;
  1031. textRegion.refinementTemplate = textRegionSegmentFlags >> 15 & 1;
  1032. if (textRegion.huffman) {
  1033. const textRegionHuffmanFlags = (0, _core_utils.readUint16)(data, position);
  1034. position += 2;
  1035. textRegion.huffmanFS = textRegionHuffmanFlags & 3;
  1036. textRegion.huffmanDS = textRegionHuffmanFlags >> 2 & 3;
  1037. textRegion.huffmanDT = textRegionHuffmanFlags >> 4 & 3;
  1038. textRegion.huffmanRefinementDW = textRegionHuffmanFlags >> 6 & 3;
  1039. textRegion.huffmanRefinementDH = textRegionHuffmanFlags >> 8 & 3;
  1040. textRegion.huffmanRefinementDX = textRegionHuffmanFlags >> 10 & 3;
  1041. textRegion.huffmanRefinementDY = textRegionHuffmanFlags >> 12 & 3;
  1042. textRegion.huffmanRefinementSizeSelector = !!(textRegionHuffmanFlags & 0x4000);
  1043. }
  1044. if (textRegion.refinement && !textRegion.refinementTemplate) {
  1045. at = [];
  1046. for (i = 0; i < 2; i++) {
  1047. at.push({
  1048. x: (0, _core_utils.readInt8)(data, position),
  1049. y: (0, _core_utils.readInt8)(data, position + 1)
  1050. });
  1051. position += 2;
  1052. }
  1053. textRegion.refinementAt = at;
  1054. }
  1055. textRegion.numberOfSymbolInstances = (0, _core_utils.readUint32)(data, position);
  1056. position += 4;
  1057. args = [textRegion, header.referredTo, data, position, end];
  1058. break;
  1059. case 16:
  1060. const patternDictionary = {};
  1061. const patternDictionaryFlags = data[position++];
  1062. patternDictionary.mmr = !!(patternDictionaryFlags & 1);
  1063. patternDictionary.template = patternDictionaryFlags >> 1 & 3;
  1064. patternDictionary.patternWidth = data[position++];
  1065. patternDictionary.patternHeight = data[position++];
  1066. patternDictionary.maxPatternIndex = (0, _core_utils.readUint32)(data, position);
  1067. position += 4;
  1068. args = [patternDictionary, header.number, data, position, end];
  1069. break;
  1070. case 22:
  1071. case 23:
  1072. const halftoneRegion = {};
  1073. halftoneRegion.info = readRegionSegmentInformation(data, position);
  1074. position += RegionSegmentInformationFieldLength;
  1075. const halftoneRegionFlags = data[position++];
  1076. halftoneRegion.mmr = !!(halftoneRegionFlags & 1);
  1077. halftoneRegion.template = halftoneRegionFlags >> 1 & 3;
  1078. halftoneRegion.enableSkip = !!(halftoneRegionFlags & 8);
  1079. halftoneRegion.combinationOperator = halftoneRegionFlags >> 4 & 7;
  1080. halftoneRegion.defaultPixelValue = halftoneRegionFlags >> 7 & 1;
  1081. halftoneRegion.gridWidth = (0, _core_utils.readUint32)(data, position);
  1082. position += 4;
  1083. halftoneRegion.gridHeight = (0, _core_utils.readUint32)(data, position);
  1084. position += 4;
  1085. halftoneRegion.gridOffsetX = (0, _core_utils.readUint32)(data, position) & 0xffffffff;
  1086. position += 4;
  1087. halftoneRegion.gridOffsetY = (0, _core_utils.readUint32)(data, position) & 0xffffffff;
  1088. position += 4;
  1089. halftoneRegion.gridVectorX = (0, _core_utils.readUint16)(data, position);
  1090. position += 2;
  1091. halftoneRegion.gridVectorY = (0, _core_utils.readUint16)(data, position);
  1092. position += 2;
  1093. args = [halftoneRegion, header.referredTo, data, position, end];
  1094. break;
  1095. case 38:
  1096. case 39:
  1097. const genericRegion = {};
  1098. genericRegion.info = readRegionSegmentInformation(data, position);
  1099. position += RegionSegmentInformationFieldLength;
  1100. const genericRegionSegmentFlags = data[position++];
  1101. genericRegion.mmr = !!(genericRegionSegmentFlags & 1);
  1102. genericRegion.template = genericRegionSegmentFlags >> 1 & 3;
  1103. genericRegion.prediction = !!(genericRegionSegmentFlags & 8);
  1104. if (!genericRegion.mmr) {
  1105. atLength = genericRegion.template === 0 ? 4 : 1;
  1106. at = [];
  1107. for (i = 0; i < atLength; i++) {
  1108. at.push({
  1109. x: (0, _core_utils.readInt8)(data, position),
  1110. y: (0, _core_utils.readInt8)(data, position + 1)
  1111. });
  1112. position += 2;
  1113. }
  1114. genericRegion.at = at;
  1115. }
  1116. args = [genericRegion, data, position, end];
  1117. break;
  1118. case 48:
  1119. const pageInfo = {
  1120. width: (0, _core_utils.readUint32)(data, position),
  1121. height: (0, _core_utils.readUint32)(data, position + 4),
  1122. resolutionX: (0, _core_utils.readUint32)(data, position + 8),
  1123. resolutionY: (0, _core_utils.readUint32)(data, position + 12)
  1124. };
  1125. if (pageInfo.height === 0xffffffff) {
  1126. delete pageInfo.height;
  1127. }
  1128. const pageSegmentFlags = data[position + 16];
  1129. (0, _core_utils.readUint16)(data, position + 17);
  1130. pageInfo.lossless = !!(pageSegmentFlags & 1);
  1131. pageInfo.refinement = !!(pageSegmentFlags & 2);
  1132. pageInfo.defaultPixelValue = pageSegmentFlags >> 2 & 1;
  1133. pageInfo.combinationOperator = pageSegmentFlags >> 3 & 3;
  1134. pageInfo.requiresBuffer = !!(pageSegmentFlags & 32);
  1135. pageInfo.combinationOperatorOverride = !!(pageSegmentFlags & 64);
  1136. args = [pageInfo];
  1137. break;
  1138. case 49:
  1139. break;
  1140. case 50:
  1141. break;
  1142. case 51:
  1143. break;
  1144. case 53:
  1145. args = [header.number, data, position, end];
  1146. break;
  1147. case 62:
  1148. break;
  1149. default:
  1150. throw new Jbig2Error(`segment type ${header.typeName}(${header.type}) is not implemented`);
  1151. }
  1152. const callbackName = "on" + header.typeName;
  1153. if (callbackName in visitor) {
  1154. visitor[callbackName].apply(visitor, args);
  1155. }
  1156. }
  1157. function processSegments(segments, visitor) {
  1158. for (let i = 0, ii = segments.length; i < ii; i++) {
  1159. processSegment(segments[i], visitor);
  1160. }
  1161. }
  1162. function parseJbig2Chunks(chunks) {
  1163. const visitor = new SimpleSegmentVisitor();
  1164. for (let i = 0, ii = chunks.length; i < ii; i++) {
  1165. const chunk = chunks[i];
  1166. const segments = readSegments({}, chunk.data, chunk.start, chunk.end);
  1167. processSegments(segments, visitor);
  1168. }
  1169. return visitor.buffer;
  1170. }
  1171. function parseJbig2(data) {
  1172. throw new Error("Not implemented: parseJbig2");
  1173. }
  1174. class SimpleSegmentVisitor {
  1175. onPageInformation(info) {
  1176. this.currentPageInfo = info;
  1177. const rowSize = info.width + 7 >> 3;
  1178. const buffer = new Uint8ClampedArray(rowSize * info.height);
  1179. if (info.defaultPixelValue) {
  1180. buffer.fill(0xff);
  1181. }
  1182. this.buffer = buffer;
  1183. }
  1184. drawBitmap(regionInfo, bitmap) {
  1185. const pageInfo = this.currentPageInfo;
  1186. const width = regionInfo.width,
  1187. height = regionInfo.height;
  1188. const rowSize = pageInfo.width + 7 >> 3;
  1189. const combinationOperator = pageInfo.combinationOperatorOverride ? regionInfo.combinationOperator : pageInfo.combinationOperator;
  1190. const buffer = this.buffer;
  1191. const mask0 = 128 >> (regionInfo.x & 7);
  1192. let offset0 = regionInfo.y * rowSize + (regionInfo.x >> 3);
  1193. let i, j, mask, offset;
  1194. switch (combinationOperator) {
  1195. case 0:
  1196. for (i = 0; i < height; i++) {
  1197. mask = mask0;
  1198. offset = offset0;
  1199. for (j = 0; j < width; j++) {
  1200. if (bitmap[i][j]) {
  1201. buffer[offset] |= mask;
  1202. }
  1203. mask >>= 1;
  1204. if (!mask) {
  1205. mask = 128;
  1206. offset++;
  1207. }
  1208. }
  1209. offset0 += rowSize;
  1210. }
  1211. break;
  1212. case 2:
  1213. for (i = 0; i < height; i++) {
  1214. mask = mask0;
  1215. offset = offset0;
  1216. for (j = 0; j < width; j++) {
  1217. if (bitmap[i][j]) {
  1218. buffer[offset] ^= mask;
  1219. }
  1220. mask >>= 1;
  1221. if (!mask) {
  1222. mask = 128;
  1223. offset++;
  1224. }
  1225. }
  1226. offset0 += rowSize;
  1227. }
  1228. break;
  1229. default:
  1230. throw new Jbig2Error(`operator ${combinationOperator} is not supported`);
  1231. }
  1232. }
  1233. onImmediateGenericRegion(region, data, start, end) {
  1234. const regionInfo = region.info;
  1235. const decodingContext = new DecodingContext(data, start, end);
  1236. const bitmap = decodeBitmap(region.mmr, regionInfo.width, regionInfo.height, region.template, region.prediction, null, region.at, decodingContext);
  1237. this.drawBitmap(regionInfo, bitmap);
  1238. }
  1239. onImmediateLosslessGenericRegion() {
  1240. this.onImmediateGenericRegion(...arguments);
  1241. }
  1242. onSymbolDictionary(dictionary, currentSegment, referredSegments, data, start, end) {
  1243. let huffmanTables, huffmanInput;
  1244. if (dictionary.huffman) {
  1245. huffmanTables = getSymbolDictionaryHuffmanTables(dictionary, referredSegments, this.customTables);
  1246. huffmanInput = new Reader(data, start, end);
  1247. }
  1248. let symbols = this.symbols;
  1249. if (!symbols) {
  1250. this.symbols = symbols = {};
  1251. }
  1252. const inputSymbols = [];
  1253. for (const referredSegment of referredSegments) {
  1254. const referredSymbols = symbols[referredSegment];
  1255. if (referredSymbols) {
  1256. inputSymbols.push(...referredSymbols);
  1257. }
  1258. }
  1259. const decodingContext = new DecodingContext(data, start, end);
  1260. symbols[currentSegment] = decodeSymbolDictionary(dictionary.huffman, dictionary.refinement, inputSymbols, dictionary.numberOfNewSymbols, dictionary.numberOfExportedSymbols, huffmanTables, dictionary.template, dictionary.at, dictionary.refinementTemplate, dictionary.refinementAt, decodingContext, huffmanInput);
  1261. }
  1262. onImmediateTextRegion(region, referredSegments, data, start, end) {
  1263. const regionInfo = region.info;
  1264. let huffmanTables, huffmanInput;
  1265. const symbols = this.symbols;
  1266. const inputSymbols = [];
  1267. for (const referredSegment of referredSegments) {
  1268. const referredSymbols = symbols[referredSegment];
  1269. if (referredSymbols) {
  1270. inputSymbols.push(...referredSymbols);
  1271. }
  1272. }
  1273. const symbolCodeLength = (0, _core_utils.log2)(inputSymbols.length);
  1274. if (region.huffman) {
  1275. huffmanInput = new Reader(data, start, end);
  1276. huffmanTables = getTextRegionHuffmanTables(region, referredSegments, this.customTables, inputSymbols.length, huffmanInput);
  1277. }
  1278. const decodingContext = new DecodingContext(data, start, end);
  1279. const bitmap = decodeTextRegion(region.huffman, region.refinement, regionInfo.width, regionInfo.height, region.defaultPixelValue, region.numberOfSymbolInstances, region.stripSize, inputSymbols, symbolCodeLength, region.transposed, region.dsOffset, region.referenceCorner, region.combinationOperator, huffmanTables, region.refinementTemplate, region.refinementAt, decodingContext, region.logStripSize, huffmanInput);
  1280. this.drawBitmap(regionInfo, bitmap);
  1281. }
  1282. onImmediateLosslessTextRegion() {
  1283. this.onImmediateTextRegion(...arguments);
  1284. }
  1285. onPatternDictionary(dictionary, currentSegment, data, start, end) {
  1286. let patterns = this.patterns;
  1287. if (!patterns) {
  1288. this.patterns = patterns = {};
  1289. }
  1290. const decodingContext = new DecodingContext(data, start, end);
  1291. patterns[currentSegment] = decodePatternDictionary(dictionary.mmr, dictionary.patternWidth, dictionary.patternHeight, dictionary.maxPatternIndex, dictionary.template, decodingContext);
  1292. }
  1293. onImmediateHalftoneRegion(region, referredSegments, data, start, end) {
  1294. const patterns = this.patterns[referredSegments[0]];
  1295. const regionInfo = region.info;
  1296. const decodingContext = new DecodingContext(data, start, end);
  1297. const bitmap = decodeHalftoneRegion(region.mmr, patterns, region.template, regionInfo.width, regionInfo.height, region.defaultPixelValue, region.enableSkip, region.combinationOperator, region.gridWidth, region.gridHeight, region.gridOffsetX, region.gridOffsetY, region.gridVectorX, region.gridVectorY, decodingContext);
  1298. this.drawBitmap(regionInfo, bitmap);
  1299. }
  1300. onImmediateLosslessHalftoneRegion() {
  1301. this.onImmediateHalftoneRegion(...arguments);
  1302. }
  1303. onTables(currentSegment, data, start, end) {
  1304. let customTables = this.customTables;
  1305. if (!customTables) {
  1306. this.customTables = customTables = {};
  1307. }
  1308. customTables[currentSegment] = decodeTablesSegment(data, start, end);
  1309. }
  1310. }
  1311. class HuffmanLine {
  1312. constructor(lineData) {
  1313. if (lineData.length === 2) {
  1314. this.isOOB = true;
  1315. this.rangeLow = 0;
  1316. this.prefixLength = lineData[0];
  1317. this.rangeLength = 0;
  1318. this.prefixCode = lineData[1];
  1319. this.isLowerRange = false;
  1320. } else {
  1321. this.isOOB = false;
  1322. this.rangeLow = lineData[0];
  1323. this.prefixLength = lineData[1];
  1324. this.rangeLength = lineData[2];
  1325. this.prefixCode = lineData[3];
  1326. this.isLowerRange = lineData[4] === "lower";
  1327. }
  1328. }
  1329. }
  1330. class HuffmanTreeNode {
  1331. constructor(line) {
  1332. this.children = [];
  1333. if (line) {
  1334. this.isLeaf = true;
  1335. this.rangeLength = line.rangeLength;
  1336. this.rangeLow = line.rangeLow;
  1337. this.isLowerRange = line.isLowerRange;
  1338. this.isOOB = line.isOOB;
  1339. } else {
  1340. this.isLeaf = false;
  1341. }
  1342. }
  1343. buildTree(line, shift) {
  1344. const bit = line.prefixCode >> shift & 1;
  1345. if (shift <= 0) {
  1346. this.children[bit] = new HuffmanTreeNode(line);
  1347. } else {
  1348. let node = this.children[bit];
  1349. if (!node) {
  1350. this.children[bit] = node = new HuffmanTreeNode(null);
  1351. }
  1352. node.buildTree(line, shift - 1);
  1353. }
  1354. }
  1355. decodeNode(reader) {
  1356. if (this.isLeaf) {
  1357. if (this.isOOB) {
  1358. return null;
  1359. }
  1360. const htOffset = reader.readBits(this.rangeLength);
  1361. return this.rangeLow + (this.isLowerRange ? -htOffset : htOffset);
  1362. }
  1363. const node = this.children[reader.readBit()];
  1364. if (!node) {
  1365. throw new Jbig2Error("invalid Huffman data");
  1366. }
  1367. return node.decodeNode(reader);
  1368. }
  1369. }
  1370. class HuffmanTable {
  1371. constructor(lines, prefixCodesDone) {
  1372. if (!prefixCodesDone) {
  1373. this.assignPrefixCodes(lines);
  1374. }
  1375. this.rootNode = new HuffmanTreeNode(null);
  1376. for (let i = 0, ii = lines.length; i < ii; i++) {
  1377. const line = lines[i];
  1378. if (line.prefixLength > 0) {
  1379. this.rootNode.buildTree(line, line.prefixLength - 1);
  1380. }
  1381. }
  1382. }
  1383. decode(reader) {
  1384. return this.rootNode.decodeNode(reader);
  1385. }
  1386. assignPrefixCodes(lines) {
  1387. const linesLength = lines.length;
  1388. let prefixLengthMax = 0;
  1389. for (let i = 0; i < linesLength; i++) {
  1390. prefixLengthMax = Math.max(prefixLengthMax, lines[i].prefixLength);
  1391. }
  1392. const histogram = new Uint32Array(prefixLengthMax + 1);
  1393. for (let i = 0; i < linesLength; i++) {
  1394. histogram[lines[i].prefixLength]++;
  1395. }
  1396. let currentLength = 1,
  1397. firstCode = 0,
  1398. currentCode,
  1399. currentTemp,
  1400. line;
  1401. histogram[0] = 0;
  1402. while (currentLength <= prefixLengthMax) {
  1403. firstCode = firstCode + histogram[currentLength - 1] << 1;
  1404. currentCode = firstCode;
  1405. currentTemp = 0;
  1406. while (currentTemp < linesLength) {
  1407. line = lines[currentTemp];
  1408. if (line.prefixLength === currentLength) {
  1409. line.prefixCode = currentCode;
  1410. currentCode++;
  1411. }
  1412. currentTemp++;
  1413. }
  1414. currentLength++;
  1415. }
  1416. }
  1417. }
  1418. function decodeTablesSegment(data, start, end) {
  1419. const flags = data[start];
  1420. const lowestValue = (0, _core_utils.readUint32)(data, start + 1) & 0xffffffff;
  1421. const highestValue = (0, _core_utils.readUint32)(data, start + 5) & 0xffffffff;
  1422. const reader = new Reader(data, start + 9, end);
  1423. const prefixSizeBits = (flags >> 1 & 7) + 1;
  1424. const rangeSizeBits = (flags >> 4 & 7) + 1;
  1425. const lines = [];
  1426. let prefixLength,
  1427. rangeLength,
  1428. currentRangeLow = lowestValue;
  1429. do {
  1430. prefixLength = reader.readBits(prefixSizeBits);
  1431. rangeLength = reader.readBits(rangeSizeBits);
  1432. lines.push(new HuffmanLine([currentRangeLow, prefixLength, rangeLength, 0]));
  1433. currentRangeLow += 1 << rangeLength;
  1434. } while (currentRangeLow < highestValue);
  1435. prefixLength = reader.readBits(prefixSizeBits);
  1436. lines.push(new HuffmanLine([lowestValue - 1, prefixLength, 32, 0, "lower"]));
  1437. prefixLength = reader.readBits(prefixSizeBits);
  1438. lines.push(new HuffmanLine([highestValue, prefixLength, 32, 0]));
  1439. if (flags & 1) {
  1440. prefixLength = reader.readBits(prefixSizeBits);
  1441. lines.push(new HuffmanLine([prefixLength, 0]));
  1442. }
  1443. return new HuffmanTable(lines, false);
  1444. }
  1445. const standardTablesCache = {};
  1446. function getStandardTable(number) {
  1447. let table = standardTablesCache[number];
  1448. if (table) {
  1449. return table;
  1450. }
  1451. let lines;
  1452. switch (number) {
  1453. case 1:
  1454. lines = [[0, 1, 4, 0x0], [16, 2, 8, 0x2], [272, 3, 16, 0x6], [65808, 3, 32, 0x7]];
  1455. break;
  1456. case 2:
  1457. lines = [[0, 1, 0, 0x0], [1, 2, 0, 0x2], [2, 3, 0, 0x6], [3, 4, 3, 0xe], [11, 5, 6, 0x1e], [75, 6, 32, 0x3e], [6, 0x3f]];
  1458. break;
  1459. case 3:
  1460. lines = [[-256, 8, 8, 0xfe], [0, 1, 0, 0x0], [1, 2, 0, 0x2], [2, 3, 0, 0x6], [3, 4, 3, 0xe], [11, 5, 6, 0x1e], [-257, 8, 32, 0xff, "lower"], [75, 7, 32, 0x7e], [6, 0x3e]];
  1461. break;
  1462. case 4:
  1463. lines = [[1, 1, 0, 0x0], [2, 2, 0, 0x2], [3, 3, 0, 0x6], [4, 4, 3, 0xe], [12, 5, 6, 0x1e], [76, 5, 32, 0x1f]];
  1464. break;
  1465. case 5:
  1466. lines = [[-255, 7, 8, 0x7e], [1, 1, 0, 0x0], [2, 2, 0, 0x2], [3, 3, 0, 0x6], [4, 4, 3, 0xe], [12, 5, 6, 0x1e], [-256, 7, 32, 0x7f, "lower"], [76, 6, 32, 0x3e]];
  1467. break;
  1468. case 6:
  1469. lines = [[-2048, 5, 10, 0x1c], [-1024, 4, 9, 0x8], [-512, 4, 8, 0x9], [-256, 4, 7, 0xa], [-128, 5, 6, 0x1d], [-64, 5, 5, 0x1e], [-32, 4, 5, 0xb], [0, 2, 7, 0x0], [128, 3, 7, 0x2], [256, 3, 8, 0x3], [512, 4, 9, 0xc], [1024, 4, 10, 0xd], [-2049, 6, 32, 0x3e, "lower"], [2048, 6, 32, 0x3f]];
  1470. break;
  1471. case 7:
  1472. lines = [[-1024, 4, 9, 0x8], [-512, 3, 8, 0x0], [-256, 4, 7, 0x9], [-128, 5, 6, 0x1a], [-64, 5, 5, 0x1b], [-32, 4, 5, 0xa], [0, 4, 5, 0xb], [32, 5, 5, 0x1c], [64, 5, 6, 0x1d], [128, 4, 7, 0xc], [256, 3, 8, 0x1], [512, 3, 9, 0x2], [1024, 3, 10, 0x3], [-1025, 5, 32, 0x1e, "lower"], [2048, 5, 32, 0x1f]];
  1473. break;
  1474. case 8:
  1475. lines = [[-15, 8, 3, 0xfc], [-7, 9, 1, 0x1fc], [-5, 8, 1, 0xfd], [-3, 9, 0, 0x1fd], [-2, 7, 0, 0x7c], [-1, 4, 0, 0xa], [0, 2, 1, 0x0], [2, 5, 0, 0x1a], [3, 6, 0, 0x3a], [4, 3, 4, 0x4], [20, 6, 1, 0x3b], [22, 4, 4, 0xb], [38, 4, 5, 0xc], [70, 5, 6, 0x1b], [134, 5, 7, 0x1c], [262, 6, 7, 0x3c], [390, 7, 8, 0x7d], [646, 6, 10, 0x3d], [-16, 9, 32, 0x1fe, "lower"], [1670, 9, 32, 0x1ff], [2, 0x1]];
  1476. break;
  1477. case 9:
  1478. lines = [[-31, 8, 4, 0xfc], [-15, 9, 2, 0x1fc], [-11, 8, 2, 0xfd], [-7, 9, 1, 0x1fd], [-5, 7, 1, 0x7c], [-3, 4, 1, 0xa], [-1, 3, 1, 0x2], [1, 3, 1, 0x3], [3, 5, 1, 0x1a], [5, 6, 1, 0x3a], [7, 3, 5, 0x4], [39, 6, 2, 0x3b], [43, 4, 5, 0xb], [75, 4, 6, 0xc], [139, 5, 7, 0x1b], [267, 5, 8, 0x1c], [523, 6, 8, 0x3c], [779, 7, 9, 0x7d], [1291, 6, 11, 0x3d], [-32, 9, 32, 0x1fe, "lower"], [3339, 9, 32, 0x1ff], [2, 0x0]];
  1479. break;
  1480. case 10:
  1481. lines = [[-21, 7, 4, 0x7a], [-5, 8, 0, 0xfc], [-4, 7, 0, 0x7b], [-3, 5, 0, 0x18], [-2, 2, 2, 0x0], [2, 5, 0, 0x19], [3, 6, 0, 0x36], [4, 7, 0, 0x7c], [5, 8, 0, 0xfd], [6, 2, 6, 0x1], [70, 5, 5, 0x1a], [102, 6, 5, 0x37], [134, 6, 6, 0x38], [198, 6, 7, 0x39], [326, 6, 8, 0x3a], [582, 6, 9, 0x3b], [1094, 6, 10, 0x3c], [2118, 7, 11, 0x7d], [-22, 8, 32, 0xfe, "lower"], [4166, 8, 32, 0xff], [2, 0x2]];
  1482. break;
  1483. case 11:
  1484. lines = [[1, 1, 0, 0x0], [2, 2, 1, 0x2], [4, 4, 0, 0xc], [5, 4, 1, 0xd], [7, 5, 1, 0x1c], [9, 5, 2, 0x1d], [13, 6, 2, 0x3c], [17, 7, 2, 0x7a], [21, 7, 3, 0x7b], [29, 7, 4, 0x7c], [45, 7, 5, 0x7d], [77, 7, 6, 0x7e], [141, 7, 32, 0x7f]];
  1485. break;
  1486. case 12:
  1487. lines = [[1, 1, 0, 0x0], [2, 2, 0, 0x2], [3, 3, 1, 0x6], [5, 5, 0, 0x1c], [6, 5, 1, 0x1d], [8, 6, 1, 0x3c], [10, 7, 0, 0x7a], [11, 7, 1, 0x7b], [13, 7, 2, 0x7c], [17, 7, 3, 0x7d], [25, 7, 4, 0x7e], [41, 8, 5, 0xfe], [73, 8, 32, 0xff]];
  1488. break;
  1489. case 13:
  1490. lines = [[1, 1, 0, 0x0], [2, 3, 0, 0x4], [3, 4, 0, 0xc], [4, 5, 0, 0x1c], [5, 4, 1, 0xd], [7, 3, 3, 0x5], [15, 6, 1, 0x3a], [17, 6, 2, 0x3b], [21, 6, 3, 0x3c], [29, 6, 4, 0x3d], [45, 6, 5, 0x3e], [77, 7, 6, 0x7e], [141, 7, 32, 0x7f]];
  1491. break;
  1492. case 14:
  1493. lines = [[-2, 3, 0, 0x4], [-1, 3, 0, 0x5], [0, 1, 0, 0x0], [1, 3, 0, 0x6], [2, 3, 0, 0x7]];
  1494. break;
  1495. case 15:
  1496. lines = [[-24, 7, 4, 0x7c], [-8, 6, 2, 0x3c], [-4, 5, 1, 0x1c], [-2, 4, 0, 0xc], [-1, 3, 0, 0x4], [0, 1, 0, 0x0], [1, 3, 0, 0x5], [2, 4, 0, 0xd], [3, 5, 1, 0x1d], [5, 6, 2, 0x3d], [9, 7, 4, 0x7d], [-25, 7, 32, 0x7e, "lower"], [25, 7, 32, 0x7f]];
  1497. break;
  1498. default:
  1499. throw new Jbig2Error(`standard table B.${number} does not exist`);
  1500. }
  1501. for (let i = 0, ii = lines.length; i < ii; i++) {
  1502. lines[i] = new HuffmanLine(lines[i]);
  1503. }
  1504. table = new HuffmanTable(lines, true);
  1505. standardTablesCache[number] = table;
  1506. return table;
  1507. }
  1508. class Reader {
  1509. constructor(data, start, end) {
  1510. this.data = data;
  1511. this.start = start;
  1512. this.end = end;
  1513. this.position = start;
  1514. this.shift = -1;
  1515. this.currentByte = 0;
  1516. }
  1517. readBit() {
  1518. if (this.shift < 0) {
  1519. if (this.position >= this.end) {
  1520. throw new Jbig2Error("end of data while reading bit");
  1521. }
  1522. this.currentByte = this.data[this.position++];
  1523. this.shift = 7;
  1524. }
  1525. const bit = this.currentByte >> this.shift & 1;
  1526. this.shift--;
  1527. return bit;
  1528. }
  1529. readBits(numBits) {
  1530. let result = 0,
  1531. i;
  1532. for (i = numBits - 1; i >= 0; i--) {
  1533. result |= this.readBit() << i;
  1534. }
  1535. return result;
  1536. }
  1537. byteAlign() {
  1538. this.shift = -1;
  1539. }
  1540. next() {
  1541. if (this.position >= this.end) {
  1542. return -1;
  1543. }
  1544. return this.data[this.position++];
  1545. }
  1546. }
  1547. function getCustomHuffmanTable(index, referredTo, customTables) {
  1548. let currentIndex = 0;
  1549. for (let i = 0, ii = referredTo.length; i < ii; i++) {
  1550. const table = customTables[referredTo[i]];
  1551. if (table) {
  1552. if (index === currentIndex) {
  1553. return table;
  1554. }
  1555. currentIndex++;
  1556. }
  1557. }
  1558. throw new Jbig2Error("can't find custom Huffman table");
  1559. }
  1560. function getTextRegionHuffmanTables(textRegion, referredTo, customTables, numberOfSymbols, reader) {
  1561. const codes = [];
  1562. for (let i = 0; i <= 34; i++) {
  1563. const codeLength = reader.readBits(4);
  1564. codes.push(new HuffmanLine([i, codeLength, 0, 0]));
  1565. }
  1566. const runCodesTable = new HuffmanTable(codes, false);
  1567. codes.length = 0;
  1568. for (let i = 0; i < numberOfSymbols;) {
  1569. const codeLength = runCodesTable.decode(reader);
  1570. if (codeLength >= 32) {
  1571. let repeatedLength, numberOfRepeats, j;
  1572. switch (codeLength) {
  1573. case 32:
  1574. if (i === 0) {
  1575. throw new Jbig2Error("no previous value in symbol ID table");
  1576. }
  1577. numberOfRepeats = reader.readBits(2) + 3;
  1578. repeatedLength = codes[i - 1].prefixLength;
  1579. break;
  1580. case 33:
  1581. numberOfRepeats = reader.readBits(3) + 3;
  1582. repeatedLength = 0;
  1583. break;
  1584. case 34:
  1585. numberOfRepeats = reader.readBits(7) + 11;
  1586. repeatedLength = 0;
  1587. break;
  1588. default:
  1589. throw new Jbig2Error("invalid code length in symbol ID table");
  1590. }
  1591. for (j = 0; j < numberOfRepeats; j++) {
  1592. codes.push(new HuffmanLine([i, repeatedLength, 0, 0]));
  1593. i++;
  1594. }
  1595. } else {
  1596. codes.push(new HuffmanLine([i, codeLength, 0, 0]));
  1597. i++;
  1598. }
  1599. }
  1600. reader.byteAlign();
  1601. const symbolIDTable = new HuffmanTable(codes, false);
  1602. let customIndex = 0,
  1603. tableFirstS,
  1604. tableDeltaS,
  1605. tableDeltaT;
  1606. switch (textRegion.huffmanFS) {
  1607. case 0:
  1608. case 1:
  1609. tableFirstS = getStandardTable(textRegion.huffmanFS + 6);
  1610. break;
  1611. case 3:
  1612. tableFirstS = getCustomHuffmanTable(customIndex, referredTo, customTables);
  1613. customIndex++;
  1614. break;
  1615. default:
  1616. throw new Jbig2Error("invalid Huffman FS selector");
  1617. }
  1618. switch (textRegion.huffmanDS) {
  1619. case 0:
  1620. case 1:
  1621. case 2:
  1622. tableDeltaS = getStandardTable(textRegion.huffmanDS + 8);
  1623. break;
  1624. case 3:
  1625. tableDeltaS = getCustomHuffmanTable(customIndex, referredTo, customTables);
  1626. customIndex++;
  1627. break;
  1628. default:
  1629. throw new Jbig2Error("invalid Huffman DS selector");
  1630. }
  1631. switch (textRegion.huffmanDT) {
  1632. case 0:
  1633. case 1:
  1634. case 2:
  1635. tableDeltaT = getStandardTable(textRegion.huffmanDT + 11);
  1636. break;
  1637. case 3:
  1638. tableDeltaT = getCustomHuffmanTable(customIndex, referredTo, customTables);
  1639. customIndex++;
  1640. break;
  1641. default:
  1642. throw new Jbig2Error("invalid Huffman DT selector");
  1643. }
  1644. if (textRegion.refinement) {
  1645. throw new Jbig2Error("refinement with Huffman is not supported");
  1646. }
  1647. return {
  1648. symbolIDTable,
  1649. tableFirstS,
  1650. tableDeltaS,
  1651. tableDeltaT
  1652. };
  1653. }
  1654. function getSymbolDictionaryHuffmanTables(dictionary, referredTo, customTables) {
  1655. let customIndex = 0,
  1656. tableDeltaHeight,
  1657. tableDeltaWidth;
  1658. switch (dictionary.huffmanDHSelector) {
  1659. case 0:
  1660. case 1:
  1661. tableDeltaHeight = getStandardTable(dictionary.huffmanDHSelector + 4);
  1662. break;
  1663. case 3:
  1664. tableDeltaHeight = getCustomHuffmanTable(customIndex, referredTo, customTables);
  1665. customIndex++;
  1666. break;
  1667. default:
  1668. throw new Jbig2Error("invalid Huffman DH selector");
  1669. }
  1670. switch (dictionary.huffmanDWSelector) {
  1671. case 0:
  1672. case 1:
  1673. tableDeltaWidth = getStandardTable(dictionary.huffmanDWSelector + 2);
  1674. break;
  1675. case 3:
  1676. tableDeltaWidth = getCustomHuffmanTable(customIndex, referredTo, customTables);
  1677. customIndex++;
  1678. break;
  1679. default:
  1680. throw new Jbig2Error("invalid Huffman DW selector");
  1681. }
  1682. let tableBitmapSize, tableAggregateInstances;
  1683. if (dictionary.bitmapSizeSelector) {
  1684. tableBitmapSize = getCustomHuffmanTable(customIndex, referredTo, customTables);
  1685. customIndex++;
  1686. } else {
  1687. tableBitmapSize = getStandardTable(1);
  1688. }
  1689. if (dictionary.aggregationInstancesSelector) {
  1690. tableAggregateInstances = getCustomHuffmanTable(customIndex, referredTo, customTables);
  1691. } else {
  1692. tableAggregateInstances = getStandardTable(1);
  1693. }
  1694. return {
  1695. tableDeltaHeight,
  1696. tableDeltaWidth,
  1697. tableBitmapSize,
  1698. tableAggregateInstances
  1699. };
  1700. }
  1701. function readUncompressedBitmap(reader, width, height) {
  1702. const bitmap = [];
  1703. for (let y = 0; y < height; y++) {
  1704. const row = new Uint8Array(width);
  1705. bitmap.push(row);
  1706. for (let x = 0; x < width; x++) {
  1707. row[x] = reader.readBit();
  1708. }
  1709. reader.byteAlign();
  1710. }
  1711. return bitmap;
  1712. }
  1713. function decodeMMRBitmap(input, width, height, endOfBlock) {
  1714. const params = {
  1715. K: -1,
  1716. Columns: width,
  1717. Rows: height,
  1718. BlackIs1: true,
  1719. EndOfBlock: endOfBlock
  1720. };
  1721. const decoder = new _ccitt.CCITTFaxDecoder(input, params);
  1722. const bitmap = [];
  1723. let currentByte,
  1724. eof = false;
  1725. for (let y = 0; y < height; y++) {
  1726. const row = new Uint8Array(width);
  1727. bitmap.push(row);
  1728. let shift = -1;
  1729. for (let x = 0; x < width; x++) {
  1730. if (shift < 0) {
  1731. currentByte = decoder.readNextChar();
  1732. if (currentByte === -1) {
  1733. currentByte = 0;
  1734. eof = true;
  1735. }
  1736. shift = 7;
  1737. }
  1738. row[x] = currentByte >> shift & 1;
  1739. shift--;
  1740. }
  1741. }
  1742. if (endOfBlock && !eof) {
  1743. const lookForEOFLimit = 5;
  1744. for (let i = 0; i < lookForEOFLimit; i++) {
  1745. if (decoder.readNextChar() === -1) {
  1746. break;
  1747. }
  1748. }
  1749. }
  1750. return bitmap;
  1751. }
  1752. class Jbig2Image {
  1753. parseChunks(chunks) {
  1754. return parseJbig2Chunks(chunks);
  1755. }
  1756. parse(data) {
  1757. throw new Error("Not implemented: Jbig2Image.parse");
  1758. }
  1759. }
  1760. exports.Jbig2Image = Jbig2Image;