2
0

jbig2.js 60 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215
  1. /**
  2. * @licstart The following is the entire license notice for the
  3. * Javascript code in this page
  4. *
  5. * Copyright 2021 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}`);
  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. const end = data.length;
  1173. let position = 0;
  1174. if (data[position] !== 0x97 || data[position + 1] !== 0x4a || data[position + 2] !== 0x42 || data[position + 3] !== 0x32 || data[position + 4] !== 0x0d || data[position + 5] !== 0x0a || data[position + 6] !== 0x1a || data[position + 7] !== 0x0a) {
  1175. throw new Jbig2Error("parseJbig2 - invalid header.");
  1176. }
  1177. const header = Object.create(null);
  1178. position += 8;
  1179. const flags = data[position++];
  1180. header.randomAccess = !(flags & 1);
  1181. if (!(flags & 2)) {
  1182. header.numberOfPages = (0, _core_utils.readUint32)(data, position);
  1183. position += 4;
  1184. }
  1185. const segments = readSegments(header, data, position, end);
  1186. const visitor = new SimpleSegmentVisitor();
  1187. processSegments(segments, visitor);
  1188. const {
  1189. width,
  1190. height
  1191. } = visitor.currentPageInfo;
  1192. const bitPacked = visitor.buffer;
  1193. const imgData = new Uint8ClampedArray(width * height);
  1194. let q = 0,
  1195. k = 0;
  1196. for (let i = 0; i < height; i++) {
  1197. let mask = 0,
  1198. buffer;
  1199. for (let j = 0; j < width; j++) {
  1200. if (!mask) {
  1201. mask = 128;
  1202. buffer = bitPacked[k++];
  1203. }
  1204. imgData[q++] = buffer & mask ? 0 : 255;
  1205. mask >>= 1;
  1206. }
  1207. }
  1208. return {
  1209. imgData,
  1210. width,
  1211. height
  1212. };
  1213. }
  1214. class SimpleSegmentVisitor {
  1215. onPageInformation(info) {
  1216. this.currentPageInfo = info;
  1217. const rowSize = info.width + 7 >> 3;
  1218. const buffer = new Uint8ClampedArray(rowSize * info.height);
  1219. if (info.defaultPixelValue) {
  1220. for (let i = 0, ii = buffer.length; i < ii; i++) {
  1221. buffer[i] = 0xff;
  1222. }
  1223. }
  1224. this.buffer = buffer;
  1225. }
  1226. drawBitmap(regionInfo, bitmap) {
  1227. const pageInfo = this.currentPageInfo;
  1228. const width = regionInfo.width,
  1229. height = regionInfo.height;
  1230. const rowSize = pageInfo.width + 7 >> 3;
  1231. const combinationOperator = pageInfo.combinationOperatorOverride ? regionInfo.combinationOperator : pageInfo.combinationOperator;
  1232. const buffer = this.buffer;
  1233. const mask0 = 128 >> (regionInfo.x & 7);
  1234. let offset0 = regionInfo.y * rowSize + (regionInfo.x >> 3);
  1235. let i, j, mask, offset;
  1236. switch (combinationOperator) {
  1237. case 0:
  1238. for (i = 0; i < height; i++) {
  1239. mask = mask0;
  1240. offset = offset0;
  1241. for (j = 0; j < width; j++) {
  1242. if (bitmap[i][j]) {
  1243. buffer[offset] |= mask;
  1244. }
  1245. mask >>= 1;
  1246. if (!mask) {
  1247. mask = 128;
  1248. offset++;
  1249. }
  1250. }
  1251. offset0 += rowSize;
  1252. }
  1253. break;
  1254. case 2:
  1255. for (i = 0; i < height; i++) {
  1256. mask = mask0;
  1257. offset = offset0;
  1258. for (j = 0; j < width; j++) {
  1259. if (bitmap[i][j]) {
  1260. buffer[offset] ^= mask;
  1261. }
  1262. mask >>= 1;
  1263. if (!mask) {
  1264. mask = 128;
  1265. offset++;
  1266. }
  1267. }
  1268. offset0 += rowSize;
  1269. }
  1270. break;
  1271. default:
  1272. throw new Jbig2Error(`operator ${combinationOperator} is not supported`);
  1273. }
  1274. }
  1275. onImmediateGenericRegion(region, data, start, end) {
  1276. const regionInfo = region.info;
  1277. const decodingContext = new DecodingContext(data, start, end);
  1278. const bitmap = decodeBitmap(region.mmr, regionInfo.width, regionInfo.height, region.template, region.prediction, null, region.at, decodingContext);
  1279. this.drawBitmap(regionInfo, bitmap);
  1280. }
  1281. onImmediateLosslessGenericRegion() {
  1282. this.onImmediateGenericRegion.apply(this, arguments);
  1283. }
  1284. onSymbolDictionary(dictionary, currentSegment, referredSegments, data, start, end) {
  1285. let huffmanTables, huffmanInput;
  1286. if (dictionary.huffman) {
  1287. huffmanTables = getSymbolDictionaryHuffmanTables(dictionary, referredSegments, this.customTables);
  1288. huffmanInput = new Reader(data, start, end);
  1289. }
  1290. let symbols = this.symbols;
  1291. if (!symbols) {
  1292. this.symbols = symbols = {};
  1293. }
  1294. let inputSymbols = [];
  1295. for (let i = 0, ii = referredSegments.length; i < ii; i++) {
  1296. const referredSymbols = symbols[referredSegments[i]];
  1297. if (referredSymbols) {
  1298. inputSymbols = inputSymbols.concat(referredSymbols);
  1299. }
  1300. }
  1301. const decodingContext = new DecodingContext(data, start, end);
  1302. symbols[currentSegment] = decodeSymbolDictionary(dictionary.huffman, dictionary.refinement, inputSymbols, dictionary.numberOfNewSymbols, dictionary.numberOfExportedSymbols, huffmanTables, dictionary.template, dictionary.at, dictionary.refinementTemplate, dictionary.refinementAt, decodingContext, huffmanInput);
  1303. }
  1304. onImmediateTextRegion(region, referredSegments, data, start, end) {
  1305. const regionInfo = region.info;
  1306. let huffmanTables, huffmanInput;
  1307. const symbols = this.symbols;
  1308. let inputSymbols = [];
  1309. for (let i = 0, ii = referredSegments.length; i < ii; i++) {
  1310. const referredSymbols = symbols[referredSegments[i]];
  1311. if (referredSymbols) {
  1312. inputSymbols = inputSymbols.concat(referredSymbols);
  1313. }
  1314. }
  1315. const symbolCodeLength = (0, _core_utils.log2)(inputSymbols.length);
  1316. if (region.huffman) {
  1317. huffmanInput = new Reader(data, start, end);
  1318. huffmanTables = getTextRegionHuffmanTables(region, referredSegments, this.customTables, inputSymbols.length, huffmanInput);
  1319. }
  1320. const decodingContext = new DecodingContext(data, start, end);
  1321. 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);
  1322. this.drawBitmap(regionInfo, bitmap);
  1323. }
  1324. onImmediateLosslessTextRegion() {
  1325. this.onImmediateTextRegion.apply(this, arguments);
  1326. }
  1327. onPatternDictionary(dictionary, currentSegment, data, start, end) {
  1328. let patterns = this.patterns;
  1329. if (!patterns) {
  1330. this.patterns = patterns = {};
  1331. }
  1332. const decodingContext = new DecodingContext(data, start, end);
  1333. patterns[currentSegment] = decodePatternDictionary(dictionary.mmr, dictionary.patternWidth, dictionary.patternHeight, dictionary.maxPatternIndex, dictionary.template, decodingContext);
  1334. }
  1335. onImmediateHalftoneRegion(region, referredSegments, data, start, end) {
  1336. const patterns = this.patterns[referredSegments[0]];
  1337. const regionInfo = region.info;
  1338. const decodingContext = new DecodingContext(data, start, end);
  1339. 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);
  1340. this.drawBitmap(regionInfo, bitmap);
  1341. }
  1342. onImmediateLosslessHalftoneRegion() {
  1343. this.onImmediateHalftoneRegion.apply(this, arguments);
  1344. }
  1345. onTables(currentSegment, data, start, end) {
  1346. let customTables = this.customTables;
  1347. if (!customTables) {
  1348. this.customTables = customTables = {};
  1349. }
  1350. customTables[currentSegment] = decodeTablesSegment(data, start, end);
  1351. }
  1352. }
  1353. class HuffmanLine {
  1354. constructor(lineData) {
  1355. if (lineData.length === 2) {
  1356. this.isOOB = true;
  1357. this.rangeLow = 0;
  1358. this.prefixLength = lineData[0];
  1359. this.rangeLength = 0;
  1360. this.prefixCode = lineData[1];
  1361. this.isLowerRange = false;
  1362. } else {
  1363. this.isOOB = false;
  1364. this.rangeLow = lineData[0];
  1365. this.prefixLength = lineData[1];
  1366. this.rangeLength = lineData[2];
  1367. this.prefixCode = lineData[3];
  1368. this.isLowerRange = lineData[4] === "lower";
  1369. }
  1370. }
  1371. }
  1372. class HuffmanTreeNode {
  1373. constructor(line) {
  1374. this.children = [];
  1375. if (line) {
  1376. this.isLeaf = true;
  1377. this.rangeLength = line.rangeLength;
  1378. this.rangeLow = line.rangeLow;
  1379. this.isLowerRange = line.isLowerRange;
  1380. this.isOOB = line.isOOB;
  1381. } else {
  1382. this.isLeaf = false;
  1383. }
  1384. }
  1385. buildTree(line, shift) {
  1386. const bit = line.prefixCode >> shift & 1;
  1387. if (shift <= 0) {
  1388. this.children[bit] = new HuffmanTreeNode(line);
  1389. } else {
  1390. let node = this.children[bit];
  1391. if (!node) {
  1392. this.children[bit] = node = new HuffmanTreeNode(null);
  1393. }
  1394. node.buildTree(line, shift - 1);
  1395. }
  1396. }
  1397. decodeNode(reader) {
  1398. if (this.isLeaf) {
  1399. if (this.isOOB) {
  1400. return null;
  1401. }
  1402. const htOffset = reader.readBits(this.rangeLength);
  1403. return this.rangeLow + (this.isLowerRange ? -htOffset : htOffset);
  1404. }
  1405. const node = this.children[reader.readBit()];
  1406. if (!node) {
  1407. throw new Jbig2Error("invalid Huffman data");
  1408. }
  1409. return node.decodeNode(reader);
  1410. }
  1411. }
  1412. class HuffmanTable {
  1413. constructor(lines, prefixCodesDone) {
  1414. if (!prefixCodesDone) {
  1415. this.assignPrefixCodes(lines);
  1416. }
  1417. this.rootNode = new HuffmanTreeNode(null);
  1418. for (let i = 0, ii = lines.length; i < ii; i++) {
  1419. const line = lines[i];
  1420. if (line.prefixLength > 0) {
  1421. this.rootNode.buildTree(line, line.prefixLength - 1);
  1422. }
  1423. }
  1424. }
  1425. decode(reader) {
  1426. return this.rootNode.decodeNode(reader);
  1427. }
  1428. assignPrefixCodes(lines) {
  1429. const linesLength = lines.length;
  1430. let prefixLengthMax = 0;
  1431. for (let i = 0; i < linesLength; i++) {
  1432. prefixLengthMax = Math.max(prefixLengthMax, lines[i].prefixLength);
  1433. }
  1434. const histogram = new Uint32Array(prefixLengthMax + 1);
  1435. for (let i = 0; i < linesLength; i++) {
  1436. histogram[lines[i].prefixLength]++;
  1437. }
  1438. let currentLength = 1,
  1439. firstCode = 0,
  1440. currentCode,
  1441. currentTemp,
  1442. line;
  1443. histogram[0] = 0;
  1444. while (currentLength <= prefixLengthMax) {
  1445. firstCode = firstCode + histogram[currentLength - 1] << 1;
  1446. currentCode = firstCode;
  1447. currentTemp = 0;
  1448. while (currentTemp < linesLength) {
  1449. line = lines[currentTemp];
  1450. if (line.prefixLength === currentLength) {
  1451. line.prefixCode = currentCode;
  1452. currentCode++;
  1453. }
  1454. currentTemp++;
  1455. }
  1456. currentLength++;
  1457. }
  1458. }
  1459. }
  1460. function decodeTablesSegment(data, start, end) {
  1461. const flags = data[start];
  1462. const lowestValue = (0, _core_utils.readUint32)(data, start + 1) & 0xffffffff;
  1463. const highestValue = (0, _core_utils.readUint32)(data, start + 5) & 0xffffffff;
  1464. const reader = new Reader(data, start + 9, end);
  1465. const prefixSizeBits = (flags >> 1 & 7) + 1;
  1466. const rangeSizeBits = (flags >> 4 & 7) + 1;
  1467. const lines = [];
  1468. let prefixLength,
  1469. rangeLength,
  1470. currentRangeLow = lowestValue;
  1471. do {
  1472. prefixLength = reader.readBits(prefixSizeBits);
  1473. rangeLength = reader.readBits(rangeSizeBits);
  1474. lines.push(new HuffmanLine([currentRangeLow, prefixLength, rangeLength, 0]));
  1475. currentRangeLow += 1 << rangeLength;
  1476. } while (currentRangeLow < highestValue);
  1477. prefixLength = reader.readBits(prefixSizeBits);
  1478. lines.push(new HuffmanLine([lowestValue - 1, prefixLength, 32, 0, "lower"]));
  1479. prefixLength = reader.readBits(prefixSizeBits);
  1480. lines.push(new HuffmanLine([highestValue, prefixLength, 32, 0]));
  1481. if (flags & 1) {
  1482. prefixLength = reader.readBits(prefixSizeBits);
  1483. lines.push(new HuffmanLine([prefixLength, 0]));
  1484. }
  1485. return new HuffmanTable(lines, false);
  1486. }
  1487. const standardTablesCache = {};
  1488. function getStandardTable(number) {
  1489. let table = standardTablesCache[number];
  1490. if (table) {
  1491. return table;
  1492. }
  1493. let lines;
  1494. switch (number) {
  1495. case 1:
  1496. lines = [[0, 1, 4, 0x0], [16, 2, 8, 0x2], [272, 3, 16, 0x6], [65808, 3, 32, 0x7]];
  1497. break;
  1498. case 2:
  1499. 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]];
  1500. break;
  1501. case 3:
  1502. 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]];
  1503. break;
  1504. case 4:
  1505. 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]];
  1506. break;
  1507. case 5:
  1508. 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]];
  1509. break;
  1510. case 6:
  1511. 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]];
  1512. break;
  1513. case 7:
  1514. 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]];
  1515. break;
  1516. case 8:
  1517. 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]];
  1518. break;
  1519. case 9:
  1520. 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]];
  1521. break;
  1522. case 10:
  1523. 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]];
  1524. break;
  1525. case 11:
  1526. 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]];
  1527. break;
  1528. case 12:
  1529. 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]];
  1530. break;
  1531. case 13:
  1532. 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]];
  1533. break;
  1534. case 14:
  1535. lines = [[-2, 3, 0, 0x4], [-1, 3, 0, 0x5], [0, 1, 0, 0x0], [1, 3, 0, 0x6], [2, 3, 0, 0x7]];
  1536. break;
  1537. case 15:
  1538. 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]];
  1539. break;
  1540. default:
  1541. throw new Jbig2Error(`standard table B.${number} does not exist`);
  1542. }
  1543. for (let i = 0, ii = lines.length; i < ii; i++) {
  1544. lines[i] = new HuffmanLine(lines[i]);
  1545. }
  1546. table = new HuffmanTable(lines, true);
  1547. standardTablesCache[number] = table;
  1548. return table;
  1549. }
  1550. class Reader {
  1551. constructor(data, start, end) {
  1552. this.data = data;
  1553. this.start = start;
  1554. this.end = end;
  1555. this.position = start;
  1556. this.shift = -1;
  1557. this.currentByte = 0;
  1558. }
  1559. readBit() {
  1560. if (this.shift < 0) {
  1561. if (this.position >= this.end) {
  1562. throw new Jbig2Error("end of data while reading bit");
  1563. }
  1564. this.currentByte = this.data[this.position++];
  1565. this.shift = 7;
  1566. }
  1567. const bit = this.currentByte >> this.shift & 1;
  1568. this.shift--;
  1569. return bit;
  1570. }
  1571. readBits(numBits) {
  1572. let result = 0,
  1573. i;
  1574. for (i = numBits - 1; i >= 0; i--) {
  1575. result |= this.readBit() << i;
  1576. }
  1577. return result;
  1578. }
  1579. byteAlign() {
  1580. this.shift = -1;
  1581. }
  1582. next() {
  1583. if (this.position >= this.end) {
  1584. return -1;
  1585. }
  1586. return this.data[this.position++];
  1587. }
  1588. }
  1589. function getCustomHuffmanTable(index, referredTo, customTables) {
  1590. let currentIndex = 0;
  1591. for (let i = 0, ii = referredTo.length; i < ii; i++) {
  1592. const table = customTables[referredTo[i]];
  1593. if (table) {
  1594. if (index === currentIndex) {
  1595. return table;
  1596. }
  1597. currentIndex++;
  1598. }
  1599. }
  1600. throw new Jbig2Error("can't find custom Huffman table");
  1601. }
  1602. function getTextRegionHuffmanTables(textRegion, referredTo, customTables, numberOfSymbols, reader) {
  1603. const codes = [];
  1604. for (let i = 0; i <= 34; i++) {
  1605. const codeLength = reader.readBits(4);
  1606. codes.push(new HuffmanLine([i, codeLength, 0, 0]));
  1607. }
  1608. const runCodesTable = new HuffmanTable(codes, false);
  1609. codes.length = 0;
  1610. for (let i = 0; i < numberOfSymbols;) {
  1611. const codeLength = runCodesTable.decode(reader);
  1612. if (codeLength >= 32) {
  1613. let repeatedLength, numberOfRepeats, j;
  1614. switch (codeLength) {
  1615. case 32:
  1616. if (i === 0) {
  1617. throw new Jbig2Error("no previous value in symbol ID table");
  1618. }
  1619. numberOfRepeats = reader.readBits(2) + 3;
  1620. repeatedLength = codes[i - 1].prefixLength;
  1621. break;
  1622. case 33:
  1623. numberOfRepeats = reader.readBits(3) + 3;
  1624. repeatedLength = 0;
  1625. break;
  1626. case 34:
  1627. numberOfRepeats = reader.readBits(7) + 11;
  1628. repeatedLength = 0;
  1629. break;
  1630. default:
  1631. throw new Jbig2Error("invalid code length in symbol ID table");
  1632. }
  1633. for (j = 0; j < numberOfRepeats; j++) {
  1634. codes.push(new HuffmanLine([i, repeatedLength, 0, 0]));
  1635. i++;
  1636. }
  1637. } else {
  1638. codes.push(new HuffmanLine([i, codeLength, 0, 0]));
  1639. i++;
  1640. }
  1641. }
  1642. reader.byteAlign();
  1643. const symbolIDTable = new HuffmanTable(codes, false);
  1644. let customIndex = 0,
  1645. tableFirstS,
  1646. tableDeltaS,
  1647. tableDeltaT;
  1648. switch (textRegion.huffmanFS) {
  1649. case 0:
  1650. case 1:
  1651. tableFirstS = getStandardTable(textRegion.huffmanFS + 6);
  1652. break;
  1653. case 3:
  1654. tableFirstS = getCustomHuffmanTable(customIndex, referredTo, customTables);
  1655. customIndex++;
  1656. break;
  1657. default:
  1658. throw new Jbig2Error("invalid Huffman FS selector");
  1659. }
  1660. switch (textRegion.huffmanDS) {
  1661. case 0:
  1662. case 1:
  1663. case 2:
  1664. tableDeltaS = getStandardTable(textRegion.huffmanDS + 8);
  1665. break;
  1666. case 3:
  1667. tableDeltaS = getCustomHuffmanTable(customIndex, referredTo, customTables);
  1668. customIndex++;
  1669. break;
  1670. default:
  1671. throw new Jbig2Error("invalid Huffman DS selector");
  1672. }
  1673. switch (textRegion.huffmanDT) {
  1674. case 0:
  1675. case 1:
  1676. case 2:
  1677. tableDeltaT = getStandardTable(textRegion.huffmanDT + 11);
  1678. break;
  1679. case 3:
  1680. tableDeltaT = getCustomHuffmanTable(customIndex, referredTo, customTables);
  1681. customIndex++;
  1682. break;
  1683. default:
  1684. throw new Jbig2Error("invalid Huffman DT selector");
  1685. }
  1686. if (textRegion.refinement) {
  1687. throw new Jbig2Error("refinement with Huffman is not supported");
  1688. }
  1689. return {
  1690. symbolIDTable,
  1691. tableFirstS,
  1692. tableDeltaS,
  1693. tableDeltaT
  1694. };
  1695. }
  1696. function getSymbolDictionaryHuffmanTables(dictionary, referredTo, customTables) {
  1697. let customIndex = 0,
  1698. tableDeltaHeight,
  1699. tableDeltaWidth;
  1700. switch (dictionary.huffmanDHSelector) {
  1701. case 0:
  1702. case 1:
  1703. tableDeltaHeight = getStandardTable(dictionary.huffmanDHSelector + 4);
  1704. break;
  1705. case 3:
  1706. tableDeltaHeight = getCustomHuffmanTable(customIndex, referredTo, customTables);
  1707. customIndex++;
  1708. break;
  1709. default:
  1710. throw new Jbig2Error("invalid Huffman DH selector");
  1711. }
  1712. switch (dictionary.huffmanDWSelector) {
  1713. case 0:
  1714. case 1:
  1715. tableDeltaWidth = getStandardTable(dictionary.huffmanDWSelector + 2);
  1716. break;
  1717. case 3:
  1718. tableDeltaWidth = getCustomHuffmanTable(customIndex, referredTo, customTables);
  1719. customIndex++;
  1720. break;
  1721. default:
  1722. throw new Jbig2Error("invalid Huffman DW selector");
  1723. }
  1724. let tableBitmapSize, tableAggregateInstances;
  1725. if (dictionary.bitmapSizeSelector) {
  1726. tableBitmapSize = getCustomHuffmanTable(customIndex, referredTo, customTables);
  1727. customIndex++;
  1728. } else {
  1729. tableBitmapSize = getStandardTable(1);
  1730. }
  1731. if (dictionary.aggregationInstancesSelector) {
  1732. tableAggregateInstances = getCustomHuffmanTable(customIndex, referredTo, customTables);
  1733. } else {
  1734. tableAggregateInstances = getStandardTable(1);
  1735. }
  1736. return {
  1737. tableDeltaHeight,
  1738. tableDeltaWidth,
  1739. tableBitmapSize,
  1740. tableAggregateInstances
  1741. };
  1742. }
  1743. function readUncompressedBitmap(reader, width, height) {
  1744. const bitmap = [];
  1745. for (let y = 0; y < height; y++) {
  1746. const row = new Uint8Array(width);
  1747. bitmap.push(row);
  1748. for (let x = 0; x < width; x++) {
  1749. row[x] = reader.readBit();
  1750. }
  1751. reader.byteAlign();
  1752. }
  1753. return bitmap;
  1754. }
  1755. function decodeMMRBitmap(input, width, height, endOfBlock) {
  1756. const params = {
  1757. K: -1,
  1758. Columns: width,
  1759. Rows: height,
  1760. BlackIs1: true,
  1761. EndOfBlock: endOfBlock
  1762. };
  1763. const decoder = new _ccitt.CCITTFaxDecoder(input, params);
  1764. const bitmap = [];
  1765. let currentByte,
  1766. eof = false;
  1767. for (let y = 0; y < height; y++) {
  1768. const row = new Uint8Array(width);
  1769. bitmap.push(row);
  1770. let shift = -1;
  1771. for (let x = 0; x < width; x++) {
  1772. if (shift < 0) {
  1773. currentByte = decoder.readNextChar();
  1774. if (currentByte === -1) {
  1775. currentByte = 0;
  1776. eof = true;
  1777. }
  1778. shift = 7;
  1779. }
  1780. row[x] = currentByte >> shift & 1;
  1781. shift--;
  1782. }
  1783. }
  1784. if (endOfBlock && !eof) {
  1785. const lookForEOFLimit = 5;
  1786. for (let i = 0; i < lookForEOFLimit; i++) {
  1787. if (decoder.readNextChar() === -1) {
  1788. break;
  1789. }
  1790. }
  1791. }
  1792. return bitmap;
  1793. }
  1794. class Jbig2Image {
  1795. parseChunks(chunks) {
  1796. return parseJbig2Chunks(chunks);
  1797. }
  1798. parse(data) {
  1799. const {
  1800. imgData,
  1801. width,
  1802. height
  1803. } = parseJbig2(data);
  1804. this.width = width;
  1805. this.height = height;
  1806. return imgData;
  1807. }
  1808. }
  1809. exports.Jbig2Image = Jbig2Image;