JBIG2Loader.cpp 101 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299
  1. /*
  2. * Copyright (c) 2024, Nico Weber <thakis@chromium.org>
  3. *
  4. * SPDX-License-Identifier: BSD-2-Clause
  5. */
  6. #include <AK/Debug.h>
  7. #include <AK/Utf16View.h>
  8. #include <LibGfx/ImageFormats/CCITTDecoder.h>
  9. #include <LibGfx/ImageFormats/JBIG2Loader.h>
  10. #include <LibTextCodec/Decoder.h>
  11. // Spec: ITU-T_T_88__08_2018.pdf in the zip file here:
  12. // https://www.itu.int/rec/T-REC-T.88-201808-I
  13. // Annex H has a datastream example.
  14. namespace Gfx {
  15. namespace JBIG2 {
  16. // Table E.1 – Qe values and probability estimation process
  17. // See also E.1.2 Coding conventions and approximations
  18. // and E.2.5 Probability estimation.
  19. struct QeEntry {
  20. u16 qe; // Sub-interval for the less probable symbol.
  21. u16 nmps; // Next index if the more probable symbol is decoded
  22. u16 nlps; // Next index if the less probable symbol is decoded
  23. u16 switch_flag; // See second-to-last paragraph in E.1.2.
  24. };
  25. constexpr auto qe_table = to_array<QeEntry>({
  26. { 0x5601, 1, 1, 1 },
  27. { 0x3401, 2, 6, 0 },
  28. { 0x1801, 3, 9, 0 },
  29. { 0x0AC1, 4, 12, 0 },
  30. { 0x0521, 5, 29, 0 },
  31. { 0x0221, 38, 33, 0 },
  32. { 0x5601, 7, 6, 1 },
  33. { 0x5401, 8, 14, 0 },
  34. { 0x4801, 9, 14, 0 },
  35. { 0x3801, 10, 14, 0 },
  36. { 0x3001, 11, 17, 0 },
  37. { 0x2401, 12, 18, 0 },
  38. { 0x1C01, 13, 20, 0 },
  39. { 0x1601, 29, 21, 0 },
  40. { 0x5601, 15, 14, 1 },
  41. { 0x5401, 16, 14, 0 },
  42. { 0x5101, 17, 15, 0 },
  43. { 0x4801, 18, 16, 0 },
  44. { 0x3801, 19, 17, 0 },
  45. { 0x3401, 20, 18, 0 },
  46. { 0x3001, 21, 19, 0 },
  47. { 0x2801, 22, 19, 0 },
  48. { 0x2401, 23, 20, 0 },
  49. { 0x2201, 24, 21, 0 },
  50. { 0x1C01, 25, 22, 0 },
  51. { 0x1801, 26, 23, 0 },
  52. { 0x1601, 27, 24, 0 },
  53. { 0x1401, 28, 25, 0 },
  54. { 0x1201, 29, 26, 0 },
  55. { 0x1101, 30, 27, 0 },
  56. { 0x0AC1, 31, 28, 0 },
  57. { 0x09C1, 32, 29, 0 },
  58. { 0x08A1, 33, 30, 0 },
  59. { 0x0521, 34, 31, 0 },
  60. { 0x0441, 35, 32, 0 },
  61. { 0x02A1, 36, 33, 0 },
  62. { 0x0221, 37, 34, 0 },
  63. { 0x0141, 38, 35, 0 },
  64. { 0x0111, 39, 36, 0 },
  65. { 0x0085, 40, 37, 0 },
  66. { 0x0049, 41, 38, 0 },
  67. { 0x0025, 42, 39, 0 },
  68. { 0x0015, 43, 40, 0 },
  69. { 0x0009, 44, 41, 0 },
  70. { 0x0005, 45, 42, 0 },
  71. { 0x0001, 45, 43, 0 },
  72. { 0x5601, 46, 46, 0 },
  73. });
  74. ErrorOr<ArithmeticDecoder> ArithmeticDecoder::initialize(ReadonlyBytes data)
  75. {
  76. ArithmeticDecoder decoder { data };
  77. decoder.INITDEC();
  78. return decoder;
  79. }
  80. bool ArithmeticDecoder::get_next_bit(Context& context)
  81. {
  82. CX = &context;
  83. // Useful for comparing to Table H.1 – Encoder and decoder trace data.
  84. // dbg("I={} MPS={} A={:#x} C={:#x} CT={} B={:#x}", I(CX), MPS(CX), A, C, CT, B());
  85. u8 D = DECODE();
  86. // dbgln(" -> D={}", D);
  87. return D;
  88. }
  89. u16 ArithmeticDecoder::Qe(u16 index) { return qe_table[index].qe; }
  90. u8 ArithmeticDecoder::NMPS(u16 index) { return qe_table[index].nmps; }
  91. u8 ArithmeticDecoder::NLPS(u16 index) { return qe_table[index].nlps; }
  92. u8 ArithmeticDecoder::SWITCH(u16 index) { return qe_table[index].switch_flag; }
  93. u8 ArithmeticDecoder::B(size_t offset) const
  94. {
  95. // E.2.10 Minimization of the compressed data
  96. // "the convention is used in the decoder that when a marker code is encountered,
  97. // 1-bits (without bit stuffing) are supplied to the decoder until the coding interval is complete."
  98. if (BP + offset >= m_data.size())
  99. return 0xFF;
  100. return m_data[BP + offset];
  101. }
  102. void ArithmeticDecoder::INITDEC()
  103. {
  104. // E.3.5 Initialization of the decoder (INITDEC)
  105. // Figure G.1 – Initialization of the software conventions decoder
  106. // "BP, the pointer to the compressed data, is initialized to BPST (pointing to the first compressed byte)."
  107. auto const BPST = 0;
  108. BP = BPST;
  109. C = (B() ^ 0xFF) << 16;
  110. BYTEIN();
  111. C = C << 7;
  112. CT = CT - 7;
  113. A = 0x8000;
  114. }
  115. u8 ArithmeticDecoder::DECODE()
  116. {
  117. // E.3.2 Decoding a decision (DECODE)
  118. // Figure G.2 – Decoding an MPS or an LPS in the software-conventions decoder
  119. u8 D;
  120. A = A - Qe(I(CX));
  121. if (C < ((u32)A << 16)) { // `(C_high < A)` in spec
  122. if ((A & 0x8000) == 0) {
  123. D = MPS_EXCHANGE();
  124. RENORMD();
  125. } else {
  126. D = MPS(CX);
  127. }
  128. } else {
  129. C = C - ((u32)A << 16); // `C_high = C_high - A` in spec
  130. D = LPS_EXCHANGE();
  131. RENORMD();
  132. }
  133. return D;
  134. }
  135. u8 ArithmeticDecoder::MPS_EXCHANGE()
  136. {
  137. // Figure E.16 – Decoder MPS path conditional exchange procedure
  138. u8 D;
  139. if (A < Qe(I(CX))) {
  140. D = 1 - MPS(CX);
  141. if (SWITCH(I(CX)) == 1) {
  142. MPS(CX) = 1 - MPS(CX);
  143. }
  144. I(CX) = NLPS(I(CX));
  145. } else {
  146. D = MPS(CX);
  147. I(CX) = NMPS(I(CX));
  148. }
  149. return D;
  150. }
  151. u8 ArithmeticDecoder::LPS_EXCHANGE()
  152. {
  153. // Figure E.17 – Decoder LPS path conditional exchange procedure
  154. u8 D;
  155. if (A < Qe(I(CX))) {
  156. A = Qe(I(CX));
  157. D = MPS(CX);
  158. I(CX) = NMPS(I(CX));
  159. } else {
  160. A = Qe(I(CX));
  161. D = 1 - MPS(CX);
  162. if (SWITCH(I(CX)) == 1) {
  163. MPS(CX) = 1 - MPS(CX);
  164. }
  165. I(CX) = NLPS(I(CX));
  166. }
  167. return D;
  168. }
  169. void ArithmeticDecoder::RENORMD()
  170. {
  171. // E.3.3 Renormalization in the decoder (RENORMD)
  172. // Figure E.18 – Decoder renormalization procedure
  173. do {
  174. if (CT == 0)
  175. BYTEIN();
  176. A = A << 1;
  177. C = C << 1;
  178. CT = CT - 1;
  179. } while ((A & 0x8000) == 0);
  180. }
  181. void ArithmeticDecoder::BYTEIN()
  182. {
  183. // E.3.4 Compressed data input (BYTEIN)
  184. // Figure G.3 – Inserting a new byte into the C register in the software-conventions decoder
  185. if (B() == 0xFF) {
  186. if (B(1) > 0x8F) {
  187. CT = 8;
  188. } else {
  189. BP = BP + 1;
  190. C = C + 0xFE00 - (B() << 9);
  191. CT = 7;
  192. }
  193. } else {
  194. BP = BP + 1;
  195. C = C + 0xFF00 - (B() << 8);
  196. CT = 8;
  197. }
  198. }
  199. // Annex A, Arithmetic integer decoding procedure
  200. class ArithmeticIntegerDecoder {
  201. public:
  202. ArithmeticIntegerDecoder(ArithmeticDecoder&);
  203. // A.2 Procedure for decoding values (except IAID)
  204. // Returns OptionalNone for OOB.
  205. Optional<i32> decode();
  206. private:
  207. ArithmeticDecoder& m_decoder;
  208. u16 PREV { 0 };
  209. Vector<ArithmeticDecoder::Context> contexts;
  210. };
  211. ArithmeticIntegerDecoder::ArithmeticIntegerDecoder(ArithmeticDecoder& decoder)
  212. : m_decoder(decoder)
  213. {
  214. contexts.resize(1 << 9);
  215. }
  216. Optional<int> ArithmeticIntegerDecoder::decode()
  217. {
  218. // A.2 Procedure for decoding values (except IAID)
  219. // "1) Set:
  220. // PREV = 1"
  221. u16 PREV = 1;
  222. // "2) Follow the flowchart in Figure A.1. Decode each bit with CX equal to "IAx + PREV" where "IAx" represents the identifier
  223. // of the current arithmetic integer decoding procedure, "+" represents concatenation, and the rightmost 9 bits of PREV are used."
  224. auto decode_bit = [&]() {
  225. bool D = m_decoder.get_next_bit(contexts[PREV & 0x1FF]);
  226. // "3) After each bit is decoded:
  227. // If PREV < 256 set:
  228. // PREV = (PREV << 1) OR D
  229. // Otherwise set:
  230. // PREV = (((PREV << 1) OR D) AND 511) OR 256
  231. // where D represents the value of the just-decoded bit.
  232. if (PREV < 256)
  233. PREV = (PREV << 1) | (u16)D;
  234. else
  235. PREV = (((PREV << 1) | (u16)D) & 511) | 256;
  236. return D;
  237. };
  238. auto decode_bits = [&](int n) {
  239. u32 result = 0;
  240. for (int i = 0; i < n; ++i)
  241. result = (result << 1) | decode_bit();
  242. return result;
  243. };
  244. // Figure A.1 – Flowchart for the integer arithmetic decoding procedures (except IAID)
  245. u8 S = decode_bit();
  246. u32 V;
  247. if (!decode_bit())
  248. V = decode_bits(2);
  249. else if (!decode_bit())
  250. V = decode_bits(4) + 4;
  251. else if (!decode_bit())
  252. V = decode_bits(6) + 20;
  253. else if (!decode_bit())
  254. V = decode_bits(8) + 84;
  255. else if (!decode_bit())
  256. V = decode_bits(12) + 340;
  257. else
  258. V = decode_bits(32) + 4436;
  259. // "4) The sequence of bits decoded, interpreted according to Table A.1, gives the value that is the result of this invocation
  260. // of the integer arithmetic decoding procedure."
  261. if (S == 1 && V == 0)
  262. return {};
  263. return S ? -V : V;
  264. }
  265. }
  266. static u8 number_of_context_bits_for_template(u8 template_)
  267. {
  268. if (template_ == 0)
  269. return 16;
  270. if (template_ == 1)
  271. return 13;
  272. VERIFY(template_ == 2 || template_ == 3);
  273. return 10;
  274. }
  275. // JBIG2 spec, Annex D, D.4.1 ID string
  276. static constexpr u8 id_string[] = { 0x97, 0x4A, 0x42, 0x32, 0x0D, 0x0A, 0x1A, 0x0A };
  277. // 7.3 Segment types
  278. enum SegmentType {
  279. SymbolDictionary = 0,
  280. IntermediateTextRegion = 4,
  281. ImmediateTextRegion = 6,
  282. ImmediateLosslessTextRegion = 7,
  283. PatternDictionary = 16,
  284. IntermediateHalftoneRegion = 20,
  285. ImmediateHalftoneRegion = 22,
  286. ImmediateLosslessHalftoneRegion = 23,
  287. IntermediateGenericRegion = 36,
  288. ImmediateGenericRegion = 38,
  289. ImmediateLosslessGenericRegion = 39,
  290. IntermediateGenericRefinementRegion = 40,
  291. ImmediateGenericRefinementRegion = 42,
  292. ImmediateLosslessGenericRefinementRegion = 43,
  293. PageInformation = 48,
  294. EndOfPage = 49,
  295. EndOfStripe = 50,
  296. EndOfFile = 51,
  297. Profiles = 52,
  298. Tables = 53,
  299. ColorPalette = 54,
  300. Extension = 62,
  301. };
  302. // Annex D
  303. enum class Organization {
  304. // D.1 Sequential organization
  305. Sequential,
  306. // D.2 Random-access organization
  307. RandomAccess,
  308. // D.3 Embedded organization
  309. Embedded,
  310. };
  311. struct SegmentHeader {
  312. u32 segment_number { 0 };
  313. SegmentType type { SegmentType::Extension };
  314. Vector<u32> referred_to_segment_numbers;
  315. // 7.2.6 Segment page association
  316. // "The first page must be numbered "1". This field may contain a value of zero; this value indicates that this segment is not associated with any page."
  317. u32 page_association { 0 };
  318. Optional<u32> data_length;
  319. };
  320. class BitBuffer {
  321. public:
  322. static ErrorOr<NonnullOwnPtr<BitBuffer>> create(size_t width, size_t height);
  323. bool get_bit(size_t x, size_t y) const;
  324. void set_bit(size_t x, size_t y, bool b);
  325. void fill(bool b);
  326. ErrorOr<NonnullRefPtr<Gfx::Bitmap>> to_gfx_bitmap() const;
  327. ErrorOr<ByteBuffer> to_byte_buffer() const;
  328. size_t width() const { return m_width; }
  329. size_t height() const { return m_height; }
  330. private:
  331. BitBuffer(ByteBuffer, size_t width, size_t height, size_t pitch);
  332. ByteBuffer m_bits;
  333. size_t m_width { 0 };
  334. size_t m_height { 0 };
  335. size_t m_pitch { 0 };
  336. };
  337. ErrorOr<NonnullOwnPtr<BitBuffer>> BitBuffer::create(size_t width, size_t height)
  338. {
  339. size_t pitch = ceil_div(width, 8ull);
  340. auto bits = TRY(ByteBuffer::create_uninitialized(pitch * height));
  341. return adopt_nonnull_own_or_enomem(new (nothrow) BitBuffer(move(bits), width, height, pitch));
  342. }
  343. bool BitBuffer::get_bit(size_t x, size_t y) const
  344. {
  345. VERIFY(x < m_width);
  346. VERIFY(y < m_height);
  347. size_t byte_offset = x / 8;
  348. size_t bit_offset = x % 8;
  349. u8 byte = m_bits[y * m_pitch + byte_offset];
  350. byte = (byte >> (8 - 1 - bit_offset)) & 1;
  351. return byte != 0;
  352. }
  353. void BitBuffer::set_bit(size_t x, size_t y, bool b)
  354. {
  355. VERIFY(x < m_width);
  356. VERIFY(y < m_height);
  357. size_t byte_offset = x / 8;
  358. size_t bit_offset = x % 8;
  359. u8 byte = m_bits[y * m_pitch + byte_offset];
  360. u8 mask = 1u << (8 - 1 - bit_offset);
  361. if (b)
  362. byte |= mask;
  363. else
  364. byte &= ~mask;
  365. m_bits[y * m_pitch + byte_offset] = byte;
  366. }
  367. void BitBuffer::fill(bool b)
  368. {
  369. u8 fill_byte = b ? 0xff : 0;
  370. for (auto& byte : m_bits.bytes())
  371. byte = fill_byte;
  372. }
  373. ErrorOr<NonnullRefPtr<Gfx::Bitmap>> BitBuffer::to_gfx_bitmap() const
  374. {
  375. auto bitmap = TRY(Gfx::Bitmap::create(Gfx::BitmapFormat::BGRx8888, { m_width, m_height }));
  376. for (size_t y = 0; y < m_height; ++y) {
  377. for (size_t x = 0; x < m_width; ++x) {
  378. auto color = get_bit(x, y) ? Color::Black : Color::White;
  379. bitmap->set_pixel(x, y, color);
  380. }
  381. }
  382. return bitmap;
  383. }
  384. ErrorOr<ByteBuffer> BitBuffer::to_byte_buffer() const
  385. {
  386. return ByteBuffer::copy(m_bits);
  387. }
  388. BitBuffer::BitBuffer(ByteBuffer bits, size_t width, size_t height, size_t pitch)
  389. : m_bits(move(bits))
  390. , m_width(width)
  391. , m_height(height)
  392. , m_pitch(pitch)
  393. {
  394. }
  395. class Symbol : public RefCounted<Symbol> {
  396. public:
  397. static NonnullRefPtr<Symbol> create(NonnullOwnPtr<BitBuffer> bitmap)
  398. {
  399. return adopt_ref(*new Symbol(move(bitmap)));
  400. }
  401. BitBuffer const& bitmap() const { return *m_bitmap; }
  402. private:
  403. Symbol(NonnullOwnPtr<BitBuffer> bitmap)
  404. : m_bitmap(move(bitmap))
  405. {
  406. }
  407. NonnullOwnPtr<BitBuffer> m_bitmap;
  408. };
  409. struct SegmentData {
  410. SegmentHeader header;
  411. ReadonlyBytes data;
  412. // Set on dictionary segments after they've been decoded.
  413. Optional<Vector<NonnullRefPtr<Symbol>>> symbols;
  414. };
  415. // 7.4.8.5 Page segment flags
  416. enum class CombinationOperator {
  417. Or = 0,
  418. And = 1,
  419. Xor = 2,
  420. XNor = 3,
  421. Replace = 4,
  422. };
  423. static void composite_bitbuffer(BitBuffer& out, BitBuffer const& bitmap, Gfx::IntPoint position, CombinationOperator operator_)
  424. {
  425. size_t start_x = 0, end_x = bitmap.width();
  426. size_t start_y = 0, end_y = bitmap.height();
  427. if (position.x() < 0) {
  428. start_x = -position.x();
  429. position.set_x(0);
  430. }
  431. if (position.y() < 0) {
  432. start_y = -position.y();
  433. position.set_y(0);
  434. }
  435. if (position.x() + bitmap.width() > out.width())
  436. end_x = out.width() - position.x();
  437. if (position.y() + bitmap.height() > out.height())
  438. end_y = out.height() - position.y();
  439. for (size_t y = start_y; y < end_y; ++y) {
  440. for (size_t x = start_x; x < end_x; ++x) {
  441. bool bit = bitmap.get_bit(x, y);
  442. switch (operator_) {
  443. case CombinationOperator::Or:
  444. bit = bit || out.get_bit(position.x() + x, position.y() + y);
  445. break;
  446. case CombinationOperator::And:
  447. bit = bit && out.get_bit(position.x() + x, position.y() + y);
  448. break;
  449. case CombinationOperator::Xor:
  450. bit = bit ^ out.get_bit(position.x() + x, position.y() + y);
  451. break;
  452. case CombinationOperator::XNor:
  453. bit = !(bit ^ out.get_bit(position.x() + x, position.y() + y));
  454. break;
  455. case CombinationOperator::Replace:
  456. // Nothing to do.
  457. break;
  458. }
  459. out.set_bit(position.x() + x, position.y() + y, bit);
  460. }
  461. }
  462. }
  463. struct Page {
  464. IntSize size;
  465. // This is never CombinationOperator::Replace for Pages.
  466. CombinationOperator default_combination_operator { CombinationOperator::Or };
  467. OwnPtr<BitBuffer> bits;
  468. };
  469. struct JBIG2LoadingContext {
  470. enum class State {
  471. NotDecoded = 0,
  472. Error,
  473. Decoded,
  474. };
  475. State state { State::NotDecoded };
  476. Organization organization { Organization::Sequential };
  477. Page page;
  478. Optional<u32> number_of_pages;
  479. Vector<SegmentData> segments;
  480. HashMap<u32, u32> segments_by_number;
  481. };
  482. static ErrorOr<void> decode_jbig2_header(JBIG2LoadingContext& context, ReadonlyBytes data)
  483. {
  484. if (!JBIG2ImageDecoderPlugin::sniff(data))
  485. return Error::from_string_literal("JBIG2LoadingContext: Invalid JBIG2 header");
  486. FixedMemoryStream stream(data.slice(sizeof(id_string)));
  487. // D.4.2 File header flags
  488. u8 header_flags = TRY(stream.read_value<u8>());
  489. if (header_flags & 0b11110000)
  490. return Error::from_string_literal("JBIG2LoadingContext: Invalid header flags");
  491. context.organization = (header_flags & 1) ? Organization::Sequential : Organization::RandomAccess;
  492. dbgln_if(JBIG2_DEBUG, "JBIG2LoadingContext: Organization: {} ({})", (int)context.organization, context.organization == Organization::Sequential ? "Sequential" : "Random-access");
  493. bool has_known_number_of_pages = (header_flags & 2) ? false : true;
  494. bool uses_templates_with_12_AT_pixels = (header_flags & 4) ? true : false;
  495. bool contains_colored_region_segments = (header_flags & 8) ? true : false;
  496. // FIXME: Do something with these?
  497. (void)uses_templates_with_12_AT_pixels;
  498. (void)contains_colored_region_segments;
  499. // D.4.3 Number of pages
  500. if (has_known_number_of_pages) {
  501. context.number_of_pages = TRY(stream.read_value<BigEndian<u32>>());
  502. dbgln_if(JBIG2_DEBUG, "JBIG2LoadingContext: Number of pages: {}", context.number_of_pages.value());
  503. }
  504. return {};
  505. }
  506. static ErrorOr<SegmentHeader> decode_segment_header(SeekableStream& stream)
  507. {
  508. // 7.2.2 Segment number
  509. u32 segment_number = TRY(stream.read_value<BigEndian<u32>>());
  510. dbgln_if(JBIG2_DEBUG, "Segment number: {}", segment_number);
  511. // 7.2.3 Segment header flags
  512. u8 flags = TRY(stream.read_value<u8>());
  513. SegmentType type = static_cast<SegmentType>(flags & 0b11'1111);
  514. dbgln_if(JBIG2_DEBUG, "Segment type: {}", (int)type);
  515. bool segment_page_association_size_is_32_bits = (flags & 0b100'0000) != 0;
  516. bool segment_retained_only_by_itself_and_extension_segments = (flags & 0b1000'00000) != 0;
  517. // FIXME: Do something with these.
  518. (void)segment_page_association_size_is_32_bits;
  519. (void)segment_retained_only_by_itself_and_extension_segments;
  520. // 7.2.4 Referred-to segment count and retention flags
  521. u8 referred_to_segment_count_and_retention_flags = TRY(stream.read_value<u8>());
  522. u32 count_of_referred_to_segments = referred_to_segment_count_and_retention_flags >> 5;
  523. if (count_of_referred_to_segments == 5 || count_of_referred_to_segments == 6)
  524. return Error::from_string_literal("JBIG2ImageDecoderPlugin: Invalid count_of_referred_to_segments");
  525. u32 extra_count = 0;
  526. if (count_of_referred_to_segments == 7) {
  527. TRY(stream.seek(-1, SeekMode::FromCurrentPosition));
  528. count_of_referred_to_segments = TRY(stream.read_value<BigEndian<u32>>()) & 0x1FFF'FFFF;
  529. extra_count = ceil_div(count_of_referred_to_segments + 1, 8);
  530. TRY(stream.seek(extra_count, SeekMode::FromCurrentPosition));
  531. }
  532. dbgln_if(JBIG2_DEBUG, "Referred-to segment count: {}", count_of_referred_to_segments);
  533. // 7.2.5 Referred-to segment numbers
  534. Vector<u32> referred_to_segment_numbers;
  535. for (u32 i = 0; i < count_of_referred_to_segments; ++i) {
  536. u32 referred_to_segment_number;
  537. if (segment_number <= 256)
  538. referred_to_segment_number = TRY(stream.read_value<u8>());
  539. else if (segment_number <= 65536)
  540. referred_to_segment_number = TRY(stream.read_value<BigEndian<u16>>());
  541. else
  542. referred_to_segment_number = TRY(stream.read_value<BigEndian<u32>>());
  543. referred_to_segment_numbers.append(referred_to_segment_number);
  544. dbgln_if(JBIG2_DEBUG, "Referred-to segment number: {}", referred_to_segment_number);
  545. }
  546. // 7.2.6 Segment page association
  547. u32 segment_page_association;
  548. if (segment_page_association_size_is_32_bits) {
  549. segment_page_association = TRY(stream.read_value<BigEndian<u32>>());
  550. } else {
  551. segment_page_association = TRY(stream.read_value<u8>());
  552. }
  553. dbgln_if(JBIG2_DEBUG, "Segment page association: {}", segment_page_association);
  554. // 7.2.7 Segment data length
  555. u32 data_length = TRY(stream.read_value<BigEndian<u32>>());
  556. dbgln_if(JBIG2_DEBUG, "Segment data length: {}", data_length);
  557. // FIXME: Add some validity checks:
  558. // - check type is valid
  559. // - check referred_to_segment_numbers are smaller than segment_number
  560. // - 7.3.1 Rules for segment references
  561. // - 7.3.2 Rules for page associations
  562. Optional<u32> opt_data_length;
  563. if (data_length != 0xffff'ffff)
  564. opt_data_length = data_length;
  565. else if (type != ImmediateGenericRegion)
  566. return Error::from_string_literal("JBIG2ImageDecoderPlugin: Unknown data length only allowed for ImmediateGenericRegion");
  567. return SegmentHeader { segment_number, type, move(referred_to_segment_numbers), segment_page_association, opt_data_length };
  568. }
  569. static ErrorOr<size_t> scan_for_immediate_generic_region_size(ReadonlyBytes data)
  570. {
  571. // 7.2.7 Segment data length
  572. // "If the segment's type is "Immediate generic region", then the length field may contain the value 0xFFFFFFFF.
  573. // This value is intended to mean that the length of the segment's data part is unknown at the time that the segment header is written (...).
  574. // In this case, the true length of the segment's data part shall be determined through examination of the data:
  575. // if the segment uses template-based arithmetic coding, then the segment's data part ends with the two-byte sequence 0xFF 0xAC followed by a four-byte row count.
  576. // If the segment uses MMR coding, then the segment's data part ends with the two-byte sequence 0x00 0x00 followed by a four-byte row count.
  577. // The form of encoding used by the segment may be determined by examining the eighteenth byte of its segment data part,
  578. // and the end sequences can occur anywhere after that eighteenth byte."
  579. // 7.4.6.4 Decoding a generic region segment
  580. // "NOTE – The sequence 0x00 0x00 cannot occur within MMR-encoded data; the sequence 0xFF 0xAC can occur only at the end of arithmetically-coded data.
  581. // Thus, those sequences cannot occur by chance in the data that is decoded to generate the contents of the generic region."
  582. dbgln_if(JBIG2_DEBUG, "(Unknown data length, computing it)");
  583. if (data.size() < 19 + sizeof(u32))
  584. return Error::from_string_literal("JBIG2ImageDecoderPlugin: Data too short to contain segment data header and end sequence");
  585. // Per 7.4.6.1 Generic region segment data header, this starts with the 17 bytes described in
  586. // 7.4.1 Region segment information field, followed the byte described in 7.4.6.2 Generic region segment flags.
  587. // That byte's lowest bit stores if the segment uses MMR.
  588. u8 flags = data[17];
  589. bool uses_mmr = (flags & 1) != 0;
  590. auto end_sequence = uses_mmr ? to_array<u8>({ 0x00, 0x00 }) : to_array<u8>({ 0xFF, 0xAC });
  591. u8 const* end = static_cast<u8 const*>(memmem(data.data() + 19, data.size() - 19 - sizeof(u32), end_sequence.data(), end_sequence.size()));
  592. if (!end)
  593. return Error::from_string_literal("JBIG2ImageDecoderPlugin: Could not find end sequence in segment data");
  594. size_t size = end - data.data() + end_sequence.size() + sizeof(u32);
  595. dbgln_if(JBIG2_DEBUG, "(Computed size is {})", size);
  596. return size;
  597. }
  598. static ErrorOr<void> decode_segment_headers(JBIG2LoadingContext& context, ReadonlyBytes data)
  599. {
  600. FixedMemoryStream stream(data);
  601. Vector<ReadonlyBytes> segment_datas;
  602. auto store_and_skip_segment_data = [&](SegmentHeader const& segment_header) -> ErrorOr<void> {
  603. size_t start_offset = TRY(stream.tell());
  604. u32 data_length = TRY(segment_header.data_length.try_value_or_lazy_evaluated([&]() {
  605. return scan_for_immediate_generic_region_size(data.slice(start_offset));
  606. }));
  607. if (start_offset + data_length > data.size()) {
  608. dbgln_if(JBIG2_DEBUG, "JBIG2ImageDecoderPlugin: start_offset={}, data_length={}, data.size()={}", start_offset, data_length, data.size());
  609. return Error::from_string_literal("JBIG2ImageDecoderPlugin: Segment data length exceeds file size");
  610. }
  611. ReadonlyBytes segment_data = data.slice(start_offset, data_length);
  612. segment_datas.append(segment_data);
  613. TRY(stream.seek(data_length, SeekMode::FromCurrentPosition));
  614. return {};
  615. };
  616. Vector<SegmentHeader> segment_headers;
  617. while (!stream.is_eof()) {
  618. auto segment_header = TRY(decode_segment_header(stream));
  619. segment_headers.append(segment_header);
  620. if (context.organization != Organization::RandomAccess)
  621. TRY(store_and_skip_segment_data(segment_header));
  622. // Required per spec for files with RandomAccess organization.
  623. if (segment_header.type == SegmentType::EndOfFile)
  624. break;
  625. }
  626. if (context.organization == Organization::RandomAccess) {
  627. for (auto const& segment_header : segment_headers)
  628. TRY(store_and_skip_segment_data(segment_header));
  629. }
  630. if (segment_headers.size() != segment_datas.size())
  631. return Error::from_string_literal("JBIG2ImageDecoderPlugin: Segment headers and segment datas have different sizes");
  632. for (size_t i = 0; i < segment_headers.size(); ++i) {
  633. context.segments.append({ segment_headers[i], segment_datas[i], {} });
  634. context.segments_by_number.set(segment_headers[i].segment_number, context.segments.size() - 1);
  635. }
  636. return {};
  637. }
  638. // 7.4.1 Region segment information field
  639. struct [[gnu::packed]] RegionSegmentInformationField {
  640. BigEndian<u32> width;
  641. BigEndian<u32> height;
  642. BigEndian<u32> x_location;
  643. BigEndian<u32> y_location;
  644. u8 flags;
  645. CombinationOperator external_combination_operator() const
  646. {
  647. VERIFY((flags & 0x7) <= 4);
  648. return static_cast<CombinationOperator>(flags & 0x7);
  649. }
  650. bool is_color_bitmap() const
  651. {
  652. return (flags & 0x8) != 0;
  653. }
  654. };
  655. static_assert(AssertSize<RegionSegmentInformationField, 17>());
  656. static ErrorOr<RegionSegmentInformationField> decode_region_segment_information_field(ReadonlyBytes data)
  657. {
  658. // 7.4.8 Page information segment syntax
  659. if (data.size() < sizeof(RegionSegmentInformationField))
  660. return Error::from_string_literal("JBIG2ImageDecoderPlugin: Invalid region segment information field size");
  661. auto result = *(RegionSegmentInformationField const*)data.data();
  662. if ((result.flags & 0b1111'0000) != 0)
  663. return Error::from_string_literal("JBIG2ImageDecoderPlugin: Invalid region segment information field flags");
  664. if ((result.flags & 0x7) > 4)
  665. return Error::from_string_literal("JBIG2ImageDecoderPlugin: Invalid region segment information field operator");
  666. // NOTE 3 – If the colour extension flag (COLEXTFLAG) is equal to 1, the external combination operator must be REPLACE.
  667. if (result.is_color_bitmap() && result.external_combination_operator() != CombinationOperator::Replace)
  668. return Error::from_string_literal("JBIG2ImageDecoderPlugin: Invalid colored region segment information field operator");
  669. return result;
  670. }
  671. // 7.4.8 Page information segment syntax
  672. struct [[gnu::packed]] PageInformationSegment {
  673. BigEndian<u32> bitmap_width;
  674. BigEndian<u32> bitmap_height;
  675. BigEndian<u32> page_x_resolution; // In pixels/meter.
  676. BigEndian<u32> page_y_resolution; // In pixels/meter.
  677. u8 flags;
  678. BigEndian<u16> striping_information;
  679. };
  680. static_assert(AssertSize<PageInformationSegment, 19>());
  681. static ErrorOr<PageInformationSegment> decode_page_information_segment(ReadonlyBytes data)
  682. {
  683. // 7.4.8 Page information segment syntax
  684. if (data.size() != sizeof(PageInformationSegment))
  685. return Error::from_string_literal("JBIG2ImageDecoderPlugin: Invalid page information segment size");
  686. return *(PageInformationSegment const*)data.data();
  687. }
  688. static ErrorOr<void> scan_for_page_size(JBIG2LoadingContext& context)
  689. {
  690. // We only decode the first page at the moment.
  691. bool found_size = false;
  692. for (auto const& segment : context.segments) {
  693. if (segment.header.type != SegmentType::PageInformation || segment.header.page_association != 1)
  694. continue;
  695. auto page_information = TRY(decode_page_information_segment(segment.data));
  696. // FIXME: We're supposed to compute this from the striping information if it's not set.
  697. if (page_information.bitmap_height == 0xffff'ffff)
  698. return Error::from_string_literal("JBIG2ImageDecoderPlugin: Cannot handle unknown page height yet");
  699. context.page.size = { page_information.bitmap_width, page_information.bitmap_height };
  700. found_size = true;
  701. }
  702. if (!found_size)
  703. return Error::from_string_literal("JBIG2ImageDecoderPlugin: No page information segment found for page 1");
  704. return {};
  705. }
  706. static ErrorOr<void> warn_about_multiple_pages(JBIG2LoadingContext& context)
  707. {
  708. HashTable<u32> seen_pages;
  709. Vector<u32> pages;
  710. for (auto const& segment : context.segments) {
  711. if (segment.header.page_association == 0)
  712. continue;
  713. if (seen_pages.contains(segment.header.page_association))
  714. continue;
  715. seen_pages.set(segment.header.page_association);
  716. pages.append(segment.header.page_association);
  717. }
  718. // scan_for_page_size() already checked that there's a page 1.
  719. VERIFY(seen_pages.contains(1));
  720. if (pages.size() == 1)
  721. return {};
  722. StringBuilder builder;
  723. builder.appendff("JBIG2 file contains {} pages ({}", pages.size(), pages[0]);
  724. size_t i;
  725. for (i = 1; i < min(pages.size(), 10); ++i)
  726. builder.appendff(" {}", pages[i]);
  727. if (i != pages.size())
  728. builder.append(" ..."sv);
  729. builder.append("). We will only render page 1."sv);
  730. dbgln("JBIG2ImageDecoderPlugin: {}", TRY(builder.to_string()));
  731. return {};
  732. }
  733. struct AdaptiveTemplatePixel {
  734. i8 x { 0 };
  735. i8 y { 0 };
  736. };
  737. // 6.2.2 Input parameters
  738. // Table 2 – Parameters for the generic region decoding procedure
  739. struct GenericRegionDecodingInputParameters {
  740. bool is_modified_modified_read { false }; // "MMR" in spec.
  741. u32 region_width { 0 }; // "GBW" in spec.
  742. u32 region_height { 0 }; // "GBH" in spec.
  743. u8 gb_template { 0 };
  744. bool is_typical_prediction_used { false }; // "TPGDON" in spec.
  745. bool is_extended_reference_template_used { false }; // "EXTTEMPLATE" in spec.
  746. Optional<NonnullOwnPtr<BitBuffer>> skip_pattern; // "USESKIP", "SKIP" in spec.
  747. Array<AdaptiveTemplatePixel, 12> adaptive_template_pixels; // "GBATX" / "GBATY" in spec.
  748. // FIXME: GBCOLS, GBCOMBOP, COLEXTFLAG
  749. // If is_modified_modified_read is false, generic_region_decoding_procedure() reads data off this decoder.
  750. JBIG2::ArithmeticDecoder* arithmetic_decoder { nullptr };
  751. };
  752. // 6.2 Generic region decoding procedure
  753. static ErrorOr<NonnullOwnPtr<BitBuffer>> generic_region_decoding_procedure(GenericRegionDecodingInputParameters const& inputs, ReadonlyBytes data, Vector<JBIG2::ArithmeticDecoder::Context>& contexts)
  754. {
  755. if (inputs.is_modified_modified_read) {
  756. dbgln_if(JBIG2_DEBUG, "JBIG2ImageDecoderPlugin: MMR image data");
  757. // 6.2.6 Decoding using MMR coding
  758. auto buffer = TRY(CCITT::decode_ccitt_group4(data, inputs.region_width, inputs.region_height));
  759. auto result = TRY(BitBuffer::create(inputs.region_width, inputs.region_height));
  760. size_t bytes_per_row = ceil_div(inputs.region_width, 8);
  761. if (buffer.size() != bytes_per_row * inputs.region_height)
  762. return Error::from_string_literal("JBIG2ImageDecoderPlugin: Decoded MMR data has wrong size");
  763. // FIXME: Could probably just copy the ByteBuffer directly into the BitBuffer's internal ByteBuffer instead.
  764. for (size_t y = 0; y < inputs.region_height; ++y) {
  765. for (size_t x = 0; x < inputs.region_width; ++x) {
  766. bool bit = buffer[y * bytes_per_row + x / 8] & (1 << (7 - x % 8));
  767. result->set_bit(x, y, bit);
  768. }
  769. }
  770. return result;
  771. }
  772. // 6.2.5 Decoding using a template and arithmetic coding
  773. if (inputs.is_extended_reference_template_used)
  774. return Error::from_string_literal("JBIG2ImageDecoderPlugin: Cannot decode EXTTEMPLATE yet");
  775. if (inputs.gb_template == 0) {
  776. if (inputs.adaptive_template_pixels[0].x != 3 || inputs.adaptive_template_pixels[0].y != -1
  777. || inputs.adaptive_template_pixels[1].x != -3 || inputs.adaptive_template_pixels[1].y != -1
  778. || inputs.adaptive_template_pixels[2].x != 2 || inputs.adaptive_template_pixels[2].y != -2
  779. || inputs.adaptive_template_pixels[3].x != -2 || inputs.adaptive_template_pixels[3].y != -2)
  780. return Error::from_string_literal("JBIG2ImageDecoderPlugin: Cannot handle custom adaptive pixels yet");
  781. } else if (inputs.gb_template == 1) {
  782. if (inputs.adaptive_template_pixels[0].x != 3 || inputs.adaptive_template_pixels[0].y != -1)
  783. return Error::from_string_literal("JBIG2ImageDecoderPlugin: Cannot handle custom adaptive pixels yet");
  784. } else {
  785. VERIFY(inputs.gb_template == 2 || inputs.gb_template == 3);
  786. if (inputs.adaptive_template_pixels[0].x != 2 || inputs.adaptive_template_pixels[0].y != -1)
  787. return Error::from_string_literal("JBIG2ImageDecoderPlugin: Cannot handle custom adaptive pixels yet");
  788. }
  789. if (inputs.skip_pattern.has_value())
  790. return Error::from_string_literal("JBIG2ImageDecoderPlugin: Cannot decode USESKIP yet");
  791. auto result = TRY(BitBuffer::create(inputs.region_width, inputs.region_height));
  792. auto get_pixel = [&inputs](NonnullOwnPtr<BitBuffer> const& buffer, int x, int y) -> bool {
  793. if (x < 0 || x >= (int)inputs.region_width || y < 0)
  794. return false;
  795. return buffer->get_bit(x, y);
  796. };
  797. // Figure 3(a) – Template when GBTEMPLATE = 0 and EXTTEMPLATE = 0,
  798. auto compute_context_0 = [&get_pixel](NonnullOwnPtr<BitBuffer> const& buffer, int x, int y) -> u16 {
  799. u16 result = 0;
  800. for (int i = 0; i < 5; ++i)
  801. result = (result << 1) | (u16)get_pixel(buffer, x - 2 + i, y - 2);
  802. for (int i = 0; i < 7; ++i)
  803. result = (result << 1) | (u16)get_pixel(buffer, x - 3 + i, y - 1);
  804. for (int i = 0; i < 4; ++i)
  805. result = (result << 1) | (u16)get_pixel(buffer, x - 4 + i, y);
  806. return result;
  807. };
  808. // Figure 4 – Template when GBTEMPLATE = 1
  809. auto compute_context_1 = [&get_pixel](NonnullOwnPtr<BitBuffer> const& buffer, int x, int y) -> u16 {
  810. u16 result = 0;
  811. for (int i = 0; i < 4; ++i)
  812. result = (result << 1) | (u16)get_pixel(buffer, x - 1 + i, y - 2);
  813. for (int i = 0; i < 6; ++i)
  814. result = (result << 1) | (u16)get_pixel(buffer, x - 2 + i, y - 1);
  815. for (int i = 0; i < 3; ++i)
  816. result = (result << 1) | (u16)get_pixel(buffer, x - 3 + i, y);
  817. return result;
  818. };
  819. // Figure 5 – Template when GBTEMPLATE = 2
  820. auto compute_context_2 = [&get_pixel](NonnullOwnPtr<BitBuffer> const& buffer, int x, int y) -> u16 {
  821. u16 result = 0;
  822. for (int i = 0; i < 3; ++i)
  823. result = (result << 1) | (u16)get_pixel(buffer, x - 1 + i, y - 2);
  824. for (int i = 0; i < 5; ++i)
  825. result = (result << 1) | (u16)get_pixel(buffer, x - 2 + i, y - 1);
  826. for (int i = 0; i < 2; ++i)
  827. result = (result << 1) | (u16)get_pixel(buffer, x - 2 + i, y);
  828. return result;
  829. };
  830. // Figure 6 – Template when GBTEMPLATE = 3
  831. auto compute_context_3 = [&get_pixel](NonnullOwnPtr<BitBuffer> const& buffer, int x, int y) -> u16 {
  832. u16 result = 0;
  833. for (int i = 0; i < 6; ++i)
  834. result = (result << 1) | (u16)get_pixel(buffer, x - 3 + i, y - 1);
  835. for (int i = 0; i < 4; ++i)
  836. result = (result << 1) | (u16)get_pixel(buffer, x - 4 + i, y);
  837. return result;
  838. };
  839. auto compute_context = [&inputs, &compute_context_0, &compute_context_1, &compute_context_2, &compute_context_3](NonnullOwnPtr<BitBuffer> const& buffer, int x, int y) -> u16 {
  840. if (inputs.gb_template == 0)
  841. return compute_context_0(buffer, x, y);
  842. if (inputs.gb_template == 1)
  843. return compute_context_1(buffer, x, y);
  844. if (inputs.gb_template == 2)
  845. return compute_context_2(buffer, x, y);
  846. VERIFY(inputs.gb_template == 3);
  847. return compute_context_3(buffer, x, y);
  848. };
  849. // "The values of the pixels in this neighbourhood define a context. Each context has its own adaptive probability estimate
  850. // used by the arithmetic coder (see Annex E)."
  851. // "* Decode the current pixel by invoking the arithmetic entropy decoding procedure, with CX set to the value formed by
  852. // concatenating the label "GB" and the 10-16 pixel values gathered in CONTEXT."
  853. // Implementor's note: What this is supposed to mean is that we have a bunch of independent contexts, and we pick the
  854. // context for the current pixel based on pixel values in the neighborhood. The "GB" part just means this context is
  855. // independent from other contexts in the spec. They are passed in to this function.
  856. // Figure 8 – Reused context for coding the SLTP value when GBTEMPLATE is 0
  857. constexpr u16 sltp_context_for_template_0 = 0b10011'0110010'0101;
  858. // Figure 9 – Reused context for coding the SLTP value when GBTEMPLATE is 1
  859. constexpr u16 sltp_context_for_template_1 = 0b0011'110010'101;
  860. // Figure 10 – Reused context for coding the SLTP value when GBTEMPLATE is 2
  861. constexpr u16 sltp_context_for_template_2 = 0b001'11001'01;
  862. // Figure 11 – Reused context for coding the SLTP value when GBTEMPLATE is 3
  863. constexpr u16 sltp_context_for_template_3 = 0b011001'0101;
  864. u16 sltp_context = [](u8 gb_template) {
  865. if (gb_template == 0)
  866. return sltp_context_for_template_0;
  867. if (gb_template == 1)
  868. return sltp_context_for_template_1;
  869. if (gb_template == 2)
  870. return sltp_context_for_template_2;
  871. VERIFY(gb_template == 3);
  872. return sltp_context_for_template_3;
  873. }(inputs.gb_template);
  874. // 6.2.5.7 Decoding the bitmap
  875. JBIG2::ArithmeticDecoder& decoder = *inputs.arithmetic_decoder;
  876. bool ltp = false; // "LTP" in spec. "Line (uses) Typical Prediction" maybe?
  877. for (size_t y = 0; y < inputs.region_height; ++y) {
  878. if (inputs.is_typical_prediction_used) {
  879. // "SLTP" in spec. "Swap LTP" or "Switch LTP" maybe?
  880. bool sltp = decoder.get_next_bit(contexts[sltp_context]);
  881. ltp = ltp ^ sltp;
  882. if (ltp) {
  883. for (size_t x = 0; x < inputs.region_width; ++x)
  884. result->set_bit(x, y, get_pixel(result, (int)x, (int)y - 1));
  885. continue;
  886. }
  887. }
  888. for (size_t x = 0; x < inputs.region_width; ++x) {
  889. u16 context = compute_context(result, x, y);
  890. bool bit = decoder.get_next_bit(contexts[context]);
  891. result->set_bit(x, y, bit);
  892. }
  893. }
  894. return result;
  895. }
  896. // 6.3.2 Input parameters
  897. // Table 6 – Parameters for the generic refinement region decoding procedure
  898. struct GenericRefinementRegionDecodingInputParameters {
  899. u32 region_width; // "GRW" in spec.
  900. u32 region_height; // "GRH" in spec.
  901. u8 gr_template; // "GRTEMPLATE" in spec.
  902. BitBuffer const* reference_bitmap; // "GRREFERENCE" in spec.
  903. i32 reference_x_offset; // "GRREFERENCEDX" in spec.
  904. i32 reference_y_offset; // "GRREFERENCEDY" in spec.
  905. bool is_typical_prediction_used; // "TPGDON" in spec.
  906. Array<AdaptiveTemplatePixel, 2> adaptive_template_pixels; // "GRATX" / "GRATY" in spec.
  907. };
  908. // 6.3 Generic Refinement Region Decoding Procedure
  909. static ErrorOr<NonnullOwnPtr<BitBuffer>> generic_refinement_region_decoding_procedure(GenericRefinementRegionDecodingInputParameters& inputs, JBIG2::ArithmeticDecoder& decoder, Vector<JBIG2::ArithmeticDecoder::Context>& contexts)
  910. {
  911. VERIFY(inputs.gr_template == 0 || inputs.gr_template == 1);
  912. if (inputs.is_typical_prediction_used)
  913. return Error::from_string_literal("JBIG2ImageDecoderPlugin: Cannot decode typical prediction in generic refinement regions yet");
  914. if (inputs.gr_template == 0) {
  915. if (inputs.adaptive_template_pixels[0].x != -1 || inputs.adaptive_template_pixels[0].y != -1
  916. || inputs.adaptive_template_pixels[1].x != -1 || inputs.adaptive_template_pixels[1].y != -1)
  917. return Error::from_string_literal("JBIG2ImageDecoderPlugin: Cannot handle custom adaptive pixels in refinement regions yet");
  918. }
  919. // GRTEMPLATE 1 never uses adaptive pixels.
  920. if (inputs.gr_template == 1)
  921. return Error::from_string_literal("JBIG2ImageDecoderPlugin: Cannot decode GRTEMPLATE 1 yet");
  922. // 6.3.5.3 Fixed templates and adaptive templates
  923. static constexpr auto get_pixel = [](BitBuffer const& buffer, int x, int y) -> bool {
  924. if (x < 0 || x >= (int)buffer.width() || y < 0 || y >= (int)buffer.height())
  925. return false;
  926. return buffer.get_bit(x, y);
  927. };
  928. // Figure 12 – 13-pixel refinement template showing the AT pixels at their nominal locations
  929. constexpr auto compute_context = [](BitBuffer const& reference, int reference_x, int reference_y, BitBuffer const& buffer, int x, int y) -> u16 {
  930. u16 result = 0;
  931. for (int dy = -1; dy <= 1; ++dy)
  932. for (int dx = -1; dx <= 1; ++dx)
  933. result = (result << 1) | (u16)get_pixel(reference, reference_x + dx, reference_y + dy);
  934. for (int i = 0; i < 3; ++i)
  935. result = (result << 1) | (u16)get_pixel(buffer, x - 1 + i, y - 1);
  936. result = (result << 1) | (u16)get_pixel(buffer, x - 1, y);
  937. return result;
  938. };
  939. // 6.3.5.6 Decoding the refinement bitmap
  940. auto result = TRY(BitBuffer::create(inputs.region_width, inputs.region_height));
  941. for (size_t y = 0; y < result->height(); ++y) {
  942. for (size_t x = 0; x < result->width(); ++x) {
  943. u16 context = compute_context(*inputs.reference_bitmap, x - inputs.reference_x_offset, y - inputs.reference_y_offset, *result, x, y);
  944. bool bit = decoder.get_next_bit(contexts[context]);
  945. result->set_bit(x, y, bit);
  946. }
  947. }
  948. return result;
  949. }
  950. // 6.4.2 Input parameters
  951. // Table 9 – Parameters for the text region decoding procedure
  952. struct TextRegionDecodingInputParameters {
  953. bool uses_huffman_encoding { false }; // "SBHUFF" in spec.
  954. bool uses_refinement_coding { false }; // "SBREFINE" in spec.
  955. u32 region_width { 0 }; // "SBW" in spec.
  956. u32 region_height { 0 }; // "SBH" in spec.
  957. u32 number_of_instances { 0 }; // "SBNUMINSTANCES" in spec.
  958. u32 size_of_symbol_instance_strips { 0 }; // "SBSTRIPS" in spec.
  959. // "SBNUMSYMS" is `symbols.size()` below.
  960. // FIXME: SBSYMCODES
  961. u32 id_symbol_code_length { 0 }; // "SBSYMCODELEN" in spec.
  962. Vector<NonnullRefPtr<Symbol>> symbols; // "SBNUMSYMS" / "SBSYMS" in spec.
  963. u8 default_pixel { 0 }; // "SBDEFPIXEL" in spec.
  964. CombinationOperator operator_ { CombinationOperator::Or }; // "SBCOMBOP" in spec.
  965. bool is_transposed { false }; // "TRANSPOSED" in spec.
  966. enum class Corner {
  967. BottomLeft = 0,
  968. TopLeft = 1,
  969. BottomRight = 2,
  970. TopRight = 3,
  971. };
  972. Corner reference_corner { Corner::TopLeft }; // "REFCORNER" in spec.
  973. i8 delta_s_offset { 0 }; // "SBDSOFFSET" in spec.
  974. // FIXME: SBHUFFFS, SBHUFFFDS, SBHUFFDT, SBHUFFRDW, SBHUFFRDH, SBHUFFRDX, SBHUFFRDY, SBHUFFRSIZE
  975. u8 refinement_template { 0 }; // "SBRTEMPLATE" in spec.
  976. Array<AdaptiveTemplatePixel, 2> refinement_adaptive_template_pixels; // "SBRATX" / "SBRATY" in spec.
  977. // FIXME: COLEXTFLAG, SBCOLS
  978. };
  979. // 6.4 Text Region Decoding Procedure
  980. static ErrorOr<NonnullOwnPtr<BitBuffer>> text_region_decoding_procedure(TextRegionDecodingInputParameters const& inputs, ReadonlyBytes data)
  981. {
  982. if (inputs.uses_huffman_encoding)
  983. return Error::from_string_literal("JBIG2ImageDecoderPlugin: Cannot decode huffman text regions yet");
  984. if (inputs.is_transposed)
  985. return Error::from_string_literal("JBIG2ImageDecoderPlugin: Cannot decode transposed text regions yet");
  986. auto decoder = TRY(JBIG2::ArithmeticDecoder::initialize(data));
  987. // 6.4.6 Strip delta T
  988. // "If SBHUFF is 1, decode a value using the Huffman table specified by SBHUFFDT and multiply the resulting value by SBSTRIPS.
  989. // If SBHUFF is 0, decode a value using the IADT integer arithmetic decoding procedure (see Annex A) and multiply the resulting value by SBSTRIPS."
  990. // FIXME: Implement support for SBHUFF = 1.
  991. JBIG2::ArithmeticIntegerDecoder delta_t_integer_decoder(decoder);
  992. auto read_delta_t = [&]() -> i32 {
  993. return delta_t_integer_decoder.decode().value() * inputs.size_of_symbol_instance_strips;
  994. };
  995. // 6.4.7 First symbol instance S coordinate
  996. // "If SBHUFF is 1, decode a value using the Huffman table specified by SBHUFFFS.
  997. // If SBHUFF is 0, decode a value using the IAFS integer arithmetic decoding procedure (see Annex A)."
  998. // FIXME: Implement support for SBHUFF = 1.
  999. JBIG2::ArithmeticIntegerDecoder first_s_integer_decoder(decoder);
  1000. auto read_first_s = [&]() -> i32 {
  1001. return first_s_integer_decoder.decode().value();
  1002. };
  1003. // 6.4.8 Subsequent symbol instance S coordinate
  1004. // "If SBHUFF is 1, decode a value using the Huffman table specified by SBHUFFDS.
  1005. // If SBHUFF is 0, decode a value using the IADS integer arithmetic decoding procedure (see Annex A).
  1006. // In either case it is possible that the result of this decoding is the out-of-band value OOB.""
  1007. // FIXME: Implement support for SBHUFF = 1.
  1008. JBIG2::ArithmeticIntegerDecoder subsequent_s_integer_decoder(decoder);
  1009. auto read_subsequent_s = [&]() -> Optional<i32> {
  1010. return subsequent_s_integer_decoder.decode();
  1011. };
  1012. // 6.4.9 Symbol instance T coordinate
  1013. // "If SBSTRIPS == 1, then the value decoded is always zero. Otherwise:
  1014. // • If SBHUFF is 1, decode a value by reading ceil(log2(SBSTRIPS)) bits directly from the bitstream.
  1015. // • If SBHUFF is 0, decode a value using the IAIT integer arithmetic decoding procedure (see Annex A)."
  1016. // FIXME: Implement support for SBHUFF = 1.
  1017. JBIG2::ArithmeticIntegerDecoder instance_t_integer_decoder(decoder);
  1018. auto read_instance_t = [&]() -> i32 {
  1019. if (inputs.size_of_symbol_instance_strips == 1)
  1020. return 0;
  1021. return instance_t_integer_decoder.decode().value();
  1022. };
  1023. // 6.4.10 Symbol instance symbol ID
  1024. // "If SBHUFF is 1, decode a value by reading one bit at a time until the resulting bit string is equal to one of the entries in
  1025. // SBSYMCODES. The resulting value, which is IDI, is the index of the entry in SBSYMCODES that is read.
  1026. // If SBHUFF is 0, decode a value using the IAID integer arithmetic decoding procedure (see Annex A). Set IDI to the
  1027. // resulting value.""
  1028. // FIXME: Implement support for SBHUFF = 1.
  1029. Vector<JBIG2::ArithmeticDecoder::Context> id_contexts;
  1030. id_contexts.resize(1 << (inputs.id_symbol_code_length + 1));
  1031. auto read_id = [&]() -> u32 {
  1032. // A.3 The IAID decoding procedure
  1033. u32 prev = 1;
  1034. for (u8 i = 0; i < inputs.id_symbol_code_length; ++i) {
  1035. bool bit = decoder.get_next_bit(id_contexts[prev]);
  1036. prev = (prev << 1) | bit;
  1037. }
  1038. prev = prev - (1 << inputs.id_symbol_code_length);
  1039. return prev;
  1040. };
  1041. // 6.4.11.1 Symbol instance refinement delta width
  1042. // FIXME: Implement support for SBHUFF = 1.
  1043. JBIG2::ArithmeticIntegerDecoder refinement_delta_width_decoder(decoder);
  1044. auto read_refinement_delta_width = [&]() -> i32 {
  1045. return refinement_delta_width_decoder.decode().value();
  1046. };
  1047. // 6.4.11.2 Symbol instance refinement delta width
  1048. // FIXME: Implement support for SBHUFF = 1.
  1049. JBIG2::ArithmeticIntegerDecoder refinement_delta_height_decoder(decoder);
  1050. auto read_refinement_delta_height = [&]() -> i32 {
  1051. return refinement_delta_height_decoder.decode().value();
  1052. };
  1053. // 6.4.11.3 Symbol instance refinement X offset
  1054. // FIXME: Implement support for SBHUFF = 1.
  1055. JBIG2::ArithmeticIntegerDecoder refinement_x_offset_decoder(decoder);
  1056. auto read_refinement_x_offset = [&]() -> i32 {
  1057. return refinement_x_offset_decoder.decode().value();
  1058. };
  1059. // 6.4.11.4 Symbol instance refinement Y offset
  1060. // FIXME: Implement support for SBHUFF = 1.
  1061. JBIG2::ArithmeticIntegerDecoder refinement_y_offset_decoder(decoder);
  1062. auto read_refinement_y_offset = [&]() -> i32 {
  1063. return refinement_y_offset_decoder.decode().value();
  1064. };
  1065. // 6.4.11 Symbol instance bitmap
  1066. JBIG2::ArithmeticIntegerDecoder has_refinement_image_decoder(decoder);
  1067. Vector<JBIG2::ArithmeticDecoder::Context> refinement_contexts;
  1068. if (inputs.uses_refinement_coding)
  1069. refinement_contexts.resize(1 << 13);
  1070. OwnPtr<BitBuffer> refinement_result;
  1071. auto read_bitmap = [&](u32 id) -> ErrorOr<BitBuffer const*> {
  1072. if (id >= inputs.symbols.size())
  1073. return Error::from_string_literal("JBIG2ImageDecoderPlugin: Symbol ID out of range");
  1074. auto const& symbol = inputs.symbols[id]->bitmap();
  1075. bool has_refinement_image = false; // "R_I" in spec.
  1076. if (inputs.uses_refinement_coding) {
  1077. // "• If SBHUFF is 1, then read one bit and set RI to the value of that bit.
  1078. // • If SBHUFF is 0, then decode one bit using the IARI integer arithmetic decoding procedure and set RI to the value of that bit."
  1079. // FIXME: Implement support for SBHUFF = 1.
  1080. has_refinement_image = has_refinement_image_decoder.decode().value();
  1081. }
  1082. if (!has_refinement_image)
  1083. return &symbol;
  1084. auto refinement_delta_width = read_refinement_delta_width();
  1085. auto refinement_delta_height = read_refinement_delta_height();
  1086. auto refinement_x_offset = read_refinement_x_offset();
  1087. auto refinement_y_offset = read_refinement_y_offset();
  1088. // FIXME: This is missing some steps needed for the SBHUFF = 1 case.
  1089. dbgln_if(JBIG2_DEBUG, "refinement delta width: {}, refinement delta height: {}, refinement x offset: {}, refinement y offset: {}", refinement_delta_width, refinement_delta_height, refinement_x_offset, refinement_y_offset);
  1090. // Table 12 – Parameters used to decode a symbol instance's bitmap using refinement
  1091. GenericRefinementRegionDecodingInputParameters refinement_inputs;
  1092. refinement_inputs.region_width = symbol.width() + refinement_delta_width;
  1093. refinement_inputs.region_height = symbol.height() + refinement_delta_height;
  1094. refinement_inputs.gr_template = inputs.refinement_template;
  1095. refinement_inputs.reference_bitmap = &symbol;
  1096. refinement_inputs.reference_x_offset = refinement_delta_width / 2 + refinement_x_offset;
  1097. refinement_inputs.reference_y_offset = refinement_delta_height / 2 + refinement_y_offset;
  1098. refinement_inputs.is_typical_prediction_used = false;
  1099. refinement_inputs.adaptive_template_pixels = inputs.refinement_adaptive_template_pixels;
  1100. refinement_result = TRY(generic_refinement_region_decoding_procedure(refinement_inputs, decoder, refinement_contexts));
  1101. return refinement_result.ptr();
  1102. };
  1103. // 6.4.5 Decoding the text region
  1104. // "1) Fill a bitmap SBREG, of the size given by SBW and SBH, with the SBDEFPIXEL value."
  1105. auto result = TRY(BitBuffer::create(inputs.region_width, inputs.region_height));
  1106. if (inputs.default_pixel != 0)
  1107. return Error::from_string_literal("JBIG2ImageDecoderPlugin: Cannot handle SBDEFPIXEL not equal to 0 yet");
  1108. result->fill(inputs.default_pixel != 0);
  1109. // "2) Decode the initial STRIPT value as described in 6.4.6. Negate the decoded value and assign this negated value to the variable STRIPT.
  1110. // Assign the value 0 to FIRSTS. Assign the value 0 to NINSTANCES."
  1111. i32 strip_t = -read_delta_t();
  1112. i32 first_s = 0;
  1113. u32 n_instances = 0;
  1114. // "3) If COLEXTFLAG is 1, decode the colour section as described in 6.4.12."
  1115. // FIXME: Implement support for colors one day.
  1116. // "4) Decode each strip as follows:
  1117. // a) If NINSTANCES is equal to SBNUMINSTANCES then there are no more strips to decode,
  1118. // and the process of decoding the text region is complete; proceed to step 4)."
  1119. // Implementor's note. The spec means "proceed to step 5)" at the end of 4a).
  1120. while (n_instances < inputs.number_of_instances) {
  1121. // "b) Decode the strip's delta T value as described in 6.4.6. Let DT be the decoded value. Set:
  1122. // STRIPT = STRIPT + DT"
  1123. i32 delta_t = read_delta_t();
  1124. strip_t += delta_t;
  1125. i32 cur_s;
  1126. bool is_first_symbol = true;
  1127. while (true) {
  1128. // "c) Decode each symbol instance in the strip as follows:
  1129. // i) If the current symbol instance is the first symbol instance in the strip, then decode the first
  1130. // symbol instance's S coordinate as described in 6.4.7. Let DFS be the decoded value. Set:
  1131. // FIRSTS = FIRSTS + DFS
  1132. // CURS = FIRSTS
  1133. // ii) Otherwise, if the current symbol instance is not the first symbol instance in the strip, decode
  1134. // the symbol instance's S coordinate as described in 6.4.8. If the result of this decoding is OOB
  1135. // then the last symbol instance of the strip has been decoded; proceed to step 3 d). Otherwise, let
  1136. // IDS be the decoded value. Set:
  1137. // CURS = CURS + IDS + SBDSOFFSET"
  1138. // Implementor's note: The spec means "proceed to step 4 d)" in 4c ii).
  1139. if (is_first_symbol) {
  1140. i32 delta_first_s = read_first_s();
  1141. first_s += delta_first_s;
  1142. cur_s = first_s;
  1143. is_first_symbol = false;
  1144. } else {
  1145. auto subsequent_s = read_subsequent_s();
  1146. if (!subsequent_s.has_value())
  1147. break;
  1148. i32 instance_delta_s = subsequent_s.value();
  1149. cur_s += instance_delta_s + inputs.delta_s_offset;
  1150. }
  1151. // "iii) Decode the symbol instance's T coordinate as described in 6.4.9. Let CURT be the decoded value. Set:
  1152. // TI = STRIPT + CURT"
  1153. i32 cur_t = read_instance_t();
  1154. i32 t_instance = strip_t + cur_t;
  1155. // "iv) Decode the symbol instance's symbol ID as described in 6.4.10. Let IDI be the decoded value."
  1156. u32 id = read_id();
  1157. // "v) Determine the symbol instance's bitmap IBI as described in 6.4.11. The width and height of this
  1158. // bitmap shall be denoted as WI and HI respectively."
  1159. auto const& symbol = *TRY(read_bitmap(id));
  1160. // "vi) Update CURS as follows:
  1161. // • If TRANSPOSED is 0, and REFCORNER is TOPRIGHT or BOTTOMRIGHT, set:
  1162. // CURS = CURS + WI – 1
  1163. // • If TRANSPOSED is 1, and REFCORNER is BOTTOMLEFT or BOTTOMRIGHT, set:
  1164. // CURS = CURS + HI –1
  1165. // • Otherwise, do not change CURS in this step."
  1166. using enum TextRegionDecodingInputParameters::Corner;
  1167. if (!inputs.is_transposed && (inputs.reference_corner == TopRight || inputs.reference_corner == BottomRight))
  1168. cur_s += symbol.width() - 1;
  1169. if (inputs.is_transposed && (inputs.reference_corner == BottomLeft || inputs.reference_corner == BottomRight))
  1170. cur_s += symbol.height() - 1;
  1171. // "vii) Set:
  1172. // SI = CURS"
  1173. auto s_instance = cur_s;
  1174. // "viii) Determine the location of the symbol instance bitmap with respect to SBREG as follows:
  1175. // • If TRANSPOSED is 0, then:
  1176. // – If REFCORNER is TOPLEFT then the top left pixel of the symbol instance bitmap
  1177. // IBI shall be placed at SBREG[SI, TI].
  1178. // – If REFCORNER is TOPRIGHT then the top right pixel of the symbol instance
  1179. // bitmap IBI shall be placed at SBREG[SI, TI].
  1180. // – If REFCORNER is BOTTOMLEFT then the bottom left pixel of the symbol
  1181. // instance bitmap IBI shall be placed at SBREG[SI, TI].
  1182. // – If REFCORNER is BOTTOMRIGHT then the bottom right pixel of the symbol
  1183. // instance bitmap IBI shall be placed at SBREG[SI, TI].
  1184. // • If TRANSPOSED is 1, then:
  1185. // – If REFCORNER is TOPLEFT then the top left pixel of the symbol instance bitmap
  1186. // IBI shall be placed at SBREG[TI, SI].
  1187. // – If REFCORNER is TOPRIGHT then the top right pixel of the symbol instance
  1188. // bitmap IBI shall be placed at SBREG[TI, SI].
  1189. // – If REFCORNER is BOTTOMLEFT then the bottom left pixel of the symbol
  1190. // instance bitmap IBI shall be placed at SBREG[TI, SI].
  1191. // – If REFCORNER is BOTTOMRIGHT then the bottom right pixel of the symbol
  1192. // instance bitmap IBI shall be placed at SBREG[TI, SI].
  1193. // If any part of IBI, when placed at this location, lies outside the bounds of SBREG, then ignore
  1194. // this part of IBI in step 3 c) ix)."
  1195. // Implementor's note: The spec means "ignore this part of IBI in step 3 c) x)" in 3c viii)'s last sentence.
  1196. // FIXME: Support all reference corners and transpose values.
  1197. if (!inputs.is_transposed) {
  1198. switch (inputs.reference_corner) {
  1199. case TopLeft:
  1200. break;
  1201. case TopRight:
  1202. s_instance -= symbol.width() - 1;
  1203. break;
  1204. case BottomLeft:
  1205. t_instance -= symbol.height() - 1;
  1206. break;
  1207. case BottomRight:
  1208. s_instance -= symbol.width() - 1;
  1209. t_instance -= symbol.height() - 1;
  1210. break;
  1211. }
  1212. } else {
  1213. TODO();
  1214. }
  1215. // "ix) If COLEXTFLAG is 1, set the colour specified by SBCOLS[SBFGCOLID[NINSTANCES]]
  1216. // to the foreground colour of the symbol instance bitmap IBI."
  1217. // FIXME: Implement support for colors one day.
  1218. // "x) Draw IBI into SBREG. Combine each pixel of IBI with the current value of the corresponding
  1219. // pixel in SBREG, using the combination operator specified by SBCOMBOP. Write the results
  1220. // of each combination into that pixel in SBREG."
  1221. composite_bitbuffer(*result, symbol, { s_instance, t_instance }, inputs.operator_);
  1222. // "xi) Update CURS as follows:
  1223. // • If TRANSPOSED is 0, and REFCORNER is TOPLEFT or BOTTOMLEFT, set:
  1224. // CURS = CURS + WI –1
  1225. // • If TRANSPOSED is 1, and REFCORNER is TOPLEFT or TOPRIGHT, set:
  1226. // CURS = CURS + HI –1
  1227. // • Otherwise, do not change CURS in this step."
  1228. if (!inputs.is_transposed && (inputs.reference_corner == TopLeft || inputs.reference_corner == BottomLeft))
  1229. cur_s += symbol.width() - 1;
  1230. if (inputs.is_transposed && (inputs.reference_corner == TopLeft || inputs.reference_corner == TopRight))
  1231. cur_s += symbol.height() - 1;
  1232. // "xii) Set:
  1233. // NINSTANCES = NINSTANCES + 1"
  1234. ++n_instances;
  1235. }
  1236. // "d) When the strip has been completely decoded, decode the next strip."
  1237. // (Done in the next loop iteration.)
  1238. }
  1239. // "5) After all the strips have been decoded, the current contents of SBREG are the results that shall be
  1240. // obtained by every decoder, whether it performs this exact sequence of steps or not."
  1241. return result;
  1242. }
  1243. // 6.5.2 Input parameters
  1244. // Table 13 – Parameters for the symbol dictionary decoding procedure
  1245. struct SymbolDictionaryDecodingInputParameters {
  1246. bool uses_huffman_encoding { false }; // "SDHUFF" in spec.
  1247. bool uses_refinement_or_aggregate_coding { false }; // "SDREFAGG" in spec.
  1248. Vector<NonnullRefPtr<Symbol>> input_symbols; // "SDNUMINSYMS", "SDINSYMS" in spec.
  1249. u32 number_of_new_symbols { 0 }; // "SDNUMNEWSYMS" in spec.
  1250. u32 number_of_exported_symbols { 0 }; // "SDNUMEXSYMS" in spec.
  1251. // FIXME: SDHUFFDH, SDHUFFDW, SDHUFFBMSIZE, SDHUFFAGGINST
  1252. u8 symbol_template { 0 }; // "SDTEMPLATE" in spec.
  1253. Array<AdaptiveTemplatePixel, 4> adaptive_template_pixels; // "SDATX" / "SDATY" in spec.
  1254. u8 refinement_template { 0 }; // "SDRTEMPLATE" in spec;
  1255. Array<AdaptiveTemplatePixel, 2> refinement_adaptive_template_pixels; // "SDRATX" / "SDRATY" in spec.
  1256. };
  1257. // 6.5 Symbol Dictionary Decoding Procedure
  1258. static ErrorOr<Vector<NonnullRefPtr<Symbol>>> symbol_dictionary_decoding_procedure(SymbolDictionaryDecodingInputParameters const& inputs, ReadonlyBytes data)
  1259. {
  1260. if (inputs.uses_huffman_encoding)
  1261. return Error::from_string_literal("JBIG2ImageDecoderPlugin: Cannot decode huffman symbol dictionaries yet");
  1262. if (inputs.uses_refinement_or_aggregate_coding)
  1263. return Error::from_string_literal("JBIG2ImageDecoderPlugin: Cannot decode SDREFAGG symbol dictionaries yet");
  1264. auto decoder = TRY(JBIG2::ArithmeticDecoder::initialize(data));
  1265. Vector<JBIG2::ArithmeticDecoder::Context> contexts;
  1266. contexts.resize(1 << number_of_context_bits_for_template(inputs.symbol_template));
  1267. // 6.5.6 Height class delta height
  1268. // "If SDHUFF is 1, decode a value using the Huffman table specified by SDHUFFDH.
  1269. // If SDHUFF is 0, decode a value using the IADH integer arithmetic decoding procedure (see Annex A)."
  1270. // FIXME: Implement support for SDHUFF = 1.
  1271. JBIG2::ArithmeticIntegerDecoder delta_height_integer_decoder(decoder);
  1272. auto read_delta_height = [&]() -> i32 {
  1273. // No OOB values for delta height.
  1274. return delta_height_integer_decoder.decode().value();
  1275. };
  1276. // 6.5.7 Delta width
  1277. // "If SDHUFF is 1, decode a value using the Huffman table specified by SDHUFFDW.
  1278. // If SDHUFF is 0, decode a value using the IADW integer arithmetic decoding procedure (see Annex A).
  1279. // In either case it is possible that the result of this decoding is the out-of-band value OOB."
  1280. // FIXME: Implement support for SDHUFF = 1.
  1281. JBIG2::ArithmeticIntegerDecoder delta_width_integer_decoder(decoder);
  1282. auto read_delta_width = [&]() -> Optional<i32> {
  1283. return delta_width_integer_decoder.decode();
  1284. };
  1285. // 6.5.8 Symbol bitmap
  1286. // "This field is only present if SDHUFF = 0 or SDREFAGG = 1. This field takes one of two forms; SDREFAGG
  1287. // determines which form is used."
  1288. // FIXME: Add support for SDEFRAG = 1.
  1289. // 6.5.8.1 Direct-coded symbol bitmap
  1290. // "If SDREFAGG is 0, then decode the symbol's bitmap using a generic region decoding procedure as described in 6.2.
  1291. // Set the parameters to this decoding procedure as shown in Table 16."
  1292. auto read_bitmap = [&](u32 width, u32 height) {
  1293. GenericRegionDecodingInputParameters generic_inputs;
  1294. generic_inputs.is_modified_modified_read = false;
  1295. generic_inputs.region_width = width;
  1296. generic_inputs.region_height = height;
  1297. generic_inputs.gb_template = inputs.symbol_template;
  1298. for (int i = 0; i < 4; ++i)
  1299. generic_inputs.adaptive_template_pixels[i] = inputs.adaptive_template_pixels[i];
  1300. generic_inputs.arithmetic_decoder = &decoder;
  1301. return generic_region_decoding_procedure(generic_inputs, {}, contexts);
  1302. };
  1303. // 6.5.5 Decoding the symbol dictionary
  1304. // "1) Create an array SDNEWSYMS of bitmaps, having SDNUMNEWSYMS entries."
  1305. Vector<NonnullRefPtr<Symbol>> new_symbols;
  1306. // "2) If SDHUFF is 1 and SDREFAGG is 0, create an array SDNEWSYMWIDTHS of integers, having SDNUMNEWSYMS entries."
  1307. // FIXME: Implement support for SDHUFF = 1.
  1308. // "3) Set:
  1309. // HCHEIGHT = 0
  1310. // NSYMSDECODED = 0"
  1311. u32 height_class_height = 0;
  1312. u32 number_of_symbols_decoded = 0;
  1313. // "4) Decode each height class as follows:
  1314. // a) If NSYMSDECODED == SDNUMNEWSYMS then all the symbols in the dictionary have been decoded; proceed to step 5)."
  1315. while (number_of_symbols_decoded < inputs.number_of_new_symbols) {
  1316. // "b) Decode the height class delta height as described in 6.5.6. Let HCDH be the decoded value. Set:
  1317. // HCHEIGHT = HCEIGHT + HCDH
  1318. // SYMWIDTH = 0
  1319. // TOTWIDTH = 0
  1320. // HCFIRSTSYM = NSYMSDECODED"
  1321. i32 delta_height = read_delta_height();
  1322. height_class_height += delta_height;
  1323. u32 symbol_width = 0;
  1324. u32 total_width = 0;
  1325. u32 height_class_first_symbol = number_of_symbols_decoded;
  1326. // "c) Decode each symbol within the height class as follows:"
  1327. while (true) {
  1328. // "i) Decode the delta width for the symbol as described in 6.5.7."
  1329. auto opt_delta_width = read_delta_width();
  1330. // " If the result of this decoding is OOB then all the symbols in this height class have been decoded; proceed to step 4 d)."
  1331. if (!opt_delta_width.has_value())
  1332. break;
  1333. VERIFY(number_of_symbols_decoded < inputs.number_of_new_symbols);
  1334. // " Otherwise let DW be the decoded value and set:"
  1335. // SYMWIDTH = SYMWIDTH + DW
  1336. // TOTWIDTH = TOTWIDTH + SYMWIDTH"
  1337. i32 delta_width = opt_delta_width.value();
  1338. symbol_width += delta_width;
  1339. total_width += symbol_width;
  1340. // "ii) If SDHUFF is 0 or SDREFAGG is 1, then decode the symbol's bitmap as described in 6.5.8.
  1341. // Let BS be the decoded bitmap (this bitmap has width SYMWIDTH and height HCHEIGHT). Set:
  1342. // SDNEWSYMS[NSYMSDECODED] = BS"
  1343. // FIXME: Implement support for SDHUFF = 1.
  1344. // FIXME: Doing this eagerly is pretty wasteful. Decode on demand instead?
  1345. auto bitmap = TRY(read_bitmap(symbol_width, height_class_height));
  1346. new_symbols.append(Symbol::create(move(bitmap)));
  1347. // "iii) If SDHUFF is 1 and SDREFAGG is 0, then set:
  1348. // SDNEWSYMWIDTHS[NSYMSDECODED] = SYMWIDTH"
  1349. // FIXME: Implement support for SDHUFF = 1.
  1350. (void)total_width;
  1351. (void)height_class_first_symbol;
  1352. // "iv) Set:
  1353. // NSYMSDECODED = NSYMSDECODED + 1"
  1354. number_of_symbols_decoded++;
  1355. }
  1356. // d) If SDHUFF is 1 and SDREFAGG is 0, [...long text elided...]
  1357. // FIXME: Implement support for SDHUFF = 1.
  1358. }
  1359. // 5) Determine which symbol bitmaps are exported from this symbol dictionary, as described in 6.5.10. These
  1360. // bitmaps can be drawn from the symbols that are used as input to the symbol dictionary decoding
  1361. // procedure as well as the new symbols produced by the decoding procedure."
  1362. JBIG2::ArithmeticIntegerDecoder export_integer_decoder(decoder);
  1363. // 6.5.10 Exported symbols
  1364. Vector<bool> export_flags;
  1365. export_flags.resize(inputs.input_symbols.size() + inputs.number_of_new_symbols);
  1366. // "1) Set:
  1367. // EXINDEX = 0
  1368. // CUREXFLAG = 0"
  1369. u32 exported_index = 0;
  1370. bool current_export_flag = false;
  1371. do {
  1372. // "2) Decode a value using Table B.1 if SDHUFF is 1, or the IAEX integer arithmetic decoding procedure if
  1373. // SDHUFF is 0. Let EXRUNLENGTH be the decoded value."
  1374. // FIXME: Implement support for SDHUFF = 1.
  1375. i32 export_run_length = export_integer_decoder.decode().value(); // No OOB value.
  1376. // "3) Set EXFLAGS[EXINDEX] through EXFLAGS[EXINDEX + EXRUNLENGTH – 1] to CUREXFLAG.
  1377. // If EXRUNLENGTH = 0, then this step does not change any values."
  1378. for (int i = 0; i < export_run_length; ++i)
  1379. export_flags[exported_index + i] = current_export_flag;
  1380. // "4) Set:
  1381. // EXINDEX = EXINDEX + EXRUNLENGTH
  1382. // CUREXFLAG = NOT(CUREXFLAG)"
  1383. exported_index += export_run_length;
  1384. current_export_flag = !current_export_flag;
  1385. // 5) Repeat steps 2) through 4) until EXINDEX == SDNUMINSYMS + SDNUMNEWSYMS.
  1386. } while (exported_index < inputs.input_symbols.size() + inputs.number_of_new_symbols);
  1387. // "6) The array EXFLAGS now contains 1 for each symbol that is exported from the dictionary, and 0 for each
  1388. // symbol that is not exported."
  1389. Vector<NonnullRefPtr<Symbol>> exported_symbols;
  1390. // "7) Set:
  1391. // I = 0
  1392. // J = 0
  1393. // 8) For each value of I from 0 to SDNUMINSYMS + SDNUMNEWSYMS – 1,"
  1394. for (size_t i = 0; i < inputs.input_symbols.size() + inputs.number_of_new_symbols; ++i) {
  1395. // "if EXFLAGS[I] == 1 then perform the following steps:"
  1396. if (!export_flags[i])
  1397. continue;
  1398. // "a) If I < SDNUMINSYMS then set:
  1399. // SDEXSYMS[J] = SDINSYMS[I]
  1400. // J = J + 1"
  1401. if (i < inputs.input_symbols.size())
  1402. exported_symbols.append(inputs.input_symbols[i]);
  1403. // "b) If I >= SDNUMINSYMS then set:
  1404. // SDEXSYMS[J] = SDNEWSYMS[I – SDNUMINSYMS]
  1405. // J = J + 1"
  1406. if (i >= inputs.input_symbols.size())
  1407. exported_symbols.append(move(new_symbols[i - inputs.input_symbols.size()]));
  1408. }
  1409. if (exported_symbols.size() != inputs.number_of_exported_symbols)
  1410. return Error::from_string_literal("JBIG2ImageDecoderPlugin: Unexpected number of exported symbols");
  1411. return exported_symbols;
  1412. }
  1413. static ErrorOr<void> decode_symbol_dictionary(JBIG2LoadingContext&, SegmentData& segment)
  1414. {
  1415. // 7.4.2 Symbol dictionary segment syntax
  1416. // 7.4.2.1 Symbol dictionary segment data header
  1417. FixedMemoryStream stream(segment.data);
  1418. // 7.4.2.1.1 Symbol dictionary flags
  1419. u16 flags = TRY(stream.read_value<BigEndian<u16>>());
  1420. bool uses_huffman_encoding = (flags & 1) != 0; // "SDHUFF" in spec.
  1421. bool uses_refinement_or_aggregate_coding = (flags & 2) != 0; // "SDREFAGG" in spec.
  1422. u8 huffman_table_selection_for_height_differences = (flags >> 2) & 0b11; // "SDHUFFDH" in spec.
  1423. if (huffman_table_selection_for_height_differences == 2)
  1424. return Error::from_string_literal("JBIG2ImageDecoderPlugin: Invalid huffman_table_selection_for_height_differences");
  1425. if (!uses_huffman_encoding && huffman_table_selection_for_height_differences != 0)
  1426. return Error::from_string_literal("JBIG2ImageDecoderPlugin: Invalid huffman_table_selection_for_height_differences");
  1427. u8 huffman_table_selection_for_width_differences = (flags >> 4) & 0b11; // "SDHUFFDW" in spec.
  1428. if (huffman_table_selection_for_width_differences == 2)
  1429. return Error::from_string_literal("JBIG2ImageDecoderPlugin: Invalid huffman_table_selection_for_width_differences");
  1430. if (!uses_huffman_encoding && huffman_table_selection_for_width_differences != 0)
  1431. return Error::from_string_literal("JBIG2ImageDecoderPlugin: Invalid huffman_table_selection_for_width_differences");
  1432. bool uses_user_supplied_size_table = (flags >> 6) & 1; // "SDHUFFBMSIZE" in spec.
  1433. if (!uses_huffman_encoding && uses_user_supplied_size_table)
  1434. return Error::from_string_literal("JBIG2ImageDecoderPlugin: Invalid uses_user_supplied_size_table");
  1435. bool uses_user_supplied_aggregate_table = (flags >> 7) & 1; // "SDHUFFAGGINST" in spec.
  1436. if (!uses_huffman_encoding && uses_user_supplied_aggregate_table)
  1437. return Error::from_string_literal("JBIG2ImageDecoderPlugin: Invalid uses_user_supplied_aggregate_table");
  1438. bool bitmap_coding_context_used = (flags >> 8) & 1;
  1439. if (uses_huffman_encoding && !uses_refinement_or_aggregate_coding && bitmap_coding_context_used)
  1440. return Error::from_string_literal("JBIG2ImageDecoderPlugin: Invalid bitmap_coding_context_used");
  1441. bool bitmap_coding_context_retained = (flags >> 9) & 1;
  1442. if (uses_huffman_encoding && !uses_refinement_or_aggregate_coding && bitmap_coding_context_retained)
  1443. return Error::from_string_literal("JBIG2ImageDecoderPlugin: Invalid bitmap_coding_context_retained");
  1444. u8 template_used = (flags >> 10) & 0b11; // "SDTEMPLATE" in spec.
  1445. if (uses_huffman_encoding && template_used != 0)
  1446. return Error::from_string_literal("JBIG2ImageDecoderPlugin: Invalid template_used");
  1447. u8 refinement_template_used = (flags >> 12) & 0b11; // "SDREFTEMPLATE" in spec.
  1448. if (!uses_refinement_or_aggregate_coding && refinement_template_used != 0)
  1449. return Error::from_string_literal("JBIG2ImageDecoderPlugin: Invalid refinement_template_used");
  1450. if (flags & 0b1110'0000'0000'0000)
  1451. return Error::from_string_literal("JBIG2ImageDecoderPlugin: Invalid symbol dictionary flags");
  1452. // 7.4.2.1.2 Symbol dictionary AT flags
  1453. Array<AdaptiveTemplatePixel, 4> adaptive_template {};
  1454. if (!uses_huffman_encoding) {
  1455. int number_of_adaptive_template_pixels = template_used == 0 ? 4 : 1;
  1456. for (int i = 0; i < number_of_adaptive_template_pixels; ++i) {
  1457. adaptive_template[i].x = TRY(stream.read_value<i8>());
  1458. adaptive_template[i].y = TRY(stream.read_value<i8>());
  1459. }
  1460. }
  1461. // 7.4.2.1.3 Symbol dictionary refinement AT flags
  1462. Array<AdaptiveTemplatePixel, 2> adaptive_refinement_template {};
  1463. if (uses_refinement_or_aggregate_coding && refinement_template_used == 0) {
  1464. for (size_t i = 0; i < adaptive_refinement_template.size(); ++i) {
  1465. adaptive_refinement_template[i].x = TRY(stream.read_value<i8>());
  1466. adaptive_refinement_template[i].y = TRY(stream.read_value<i8>());
  1467. }
  1468. }
  1469. // 7.4.2.1.4 Number of exported symbols (SDNUMEXSYMS)
  1470. u32 number_of_exported_symbols = TRY(stream.read_value<BigEndian<u32>>());
  1471. // 7.4.2.1.5 Number of new symbols (SDNUMNEWSYMS)
  1472. u32 number_of_new_symbols = TRY(stream.read_value<BigEndian<u32>>());
  1473. dbgln_if(JBIG2_DEBUG, "Symbol dictionary: uses_huffman_encoding={}", uses_huffman_encoding);
  1474. dbgln_if(JBIG2_DEBUG, "Symbol dictionary: uses_refinement_or_aggregate_coding={}", uses_refinement_or_aggregate_coding);
  1475. dbgln_if(JBIG2_DEBUG, "Symbol dictionary: huffman_table_selection_for_height_differences={}", huffman_table_selection_for_height_differences);
  1476. dbgln_if(JBIG2_DEBUG, "Symbol dictionary: huffman_table_selection_for_width_differences={}", huffman_table_selection_for_width_differences);
  1477. dbgln_if(JBIG2_DEBUG, "Symbol dictionary: uses_user_supplied_size_table={}", uses_user_supplied_size_table);
  1478. dbgln_if(JBIG2_DEBUG, "Symbol dictionary: uses_user_supplied_aggregate_table={}", uses_user_supplied_aggregate_table);
  1479. dbgln_if(JBIG2_DEBUG, "Symbol dictionary: bitmap_coding_context_used={}", bitmap_coding_context_used);
  1480. dbgln_if(JBIG2_DEBUG, "Symbol dictionary: bitmap_coding_context_retained={}", bitmap_coding_context_retained);
  1481. dbgln_if(JBIG2_DEBUG, "Symbol dictionary: template_used={}", template_used);
  1482. dbgln_if(JBIG2_DEBUG, "Symbol dictionary: refinement_template_used={}", refinement_template_used);
  1483. dbgln_if(JBIG2_DEBUG, "Symbol dictionary: number_of_exported_symbols={}", number_of_exported_symbols);
  1484. dbgln_if(JBIG2_DEBUG, "Symbol dictionary: number_of_new_symbols={}", number_of_new_symbols);
  1485. // 7.4.2.1.6 Symbol dictionary segment Huffman table selection
  1486. // FIXME
  1487. // 7.4.2.2 Decoding a symbol dictionary segment
  1488. // "1) Interpret its header, as described in 7.4.2.1."
  1489. // Done!
  1490. // "2) Decode (or retrieve the results of decoding) any referred-to symbol dictionary and tables segments."
  1491. if (segment.header.referred_to_segment_numbers.size() != 0)
  1492. return Error::from_string_literal("JBIG2ImageDecoderPlugin: Cannot decode referred-to symbol dictionary segments yet");
  1493. // "3) If the "bitmap coding context used" bit in the header was 1, ..."
  1494. if (bitmap_coding_context_used)
  1495. return Error::from_string_literal("JBIG2ImageDecoderPlugin: Cannot decode bitmap coding context segment yet");
  1496. // "4) If the "bitmap coding context used" bit in the header was 0, then, as described in E.3.7,
  1497. // reset all the arithmetic coding statistics for the generic region and generic refinement region decoding procedures to zero."
  1498. // Nothing to do.
  1499. // "5) Reset the arithmetic coding statistics for all the contexts of all the arithmetic integer coders to zero."
  1500. // FIXME
  1501. // "6) Invoke the symbol dictionary decoding procedure described in 6.5, with the parameters to the symbol dictionary decoding procedure set as shown in Table 31."
  1502. SymbolDictionaryDecodingInputParameters inputs;
  1503. inputs.uses_huffman_encoding = uses_huffman_encoding;
  1504. inputs.uses_refinement_or_aggregate_coding = uses_refinement_or_aggregate_coding;
  1505. inputs.input_symbols = {};
  1506. inputs.number_of_new_symbols = number_of_new_symbols;
  1507. inputs.number_of_exported_symbols = number_of_exported_symbols;
  1508. // FIXME: SDHUFFDH, SDHUFFDW, SDHUFFBMSIZE, SDHUFFAGGINST
  1509. inputs.symbol_template = template_used;
  1510. inputs.adaptive_template_pixels = adaptive_template;
  1511. inputs.refinement_template = refinement_template_used;
  1512. inputs.refinement_adaptive_template_pixels = adaptive_refinement_template;
  1513. auto result = TRY(symbol_dictionary_decoding_procedure(inputs, segment.data.slice(TRY(stream.tell()))));
  1514. // "7) If the "bitmap coding context retained" bit in the header was 1, then, as described in E.3.8, preserve the current contents
  1515. // of the arithmetic coding statistics for the generic region and generic refinement region decoding procedures."
  1516. if (bitmap_coding_context_retained)
  1517. return Error::from_string_literal("JBIG2ImageDecoderPlugin: Cannot retain bitmap coding context yet");
  1518. segment.symbols = move(result);
  1519. return {};
  1520. }
  1521. static ErrorOr<void> decode_intermediate_text_region(JBIG2LoadingContext&, SegmentData const&)
  1522. {
  1523. return Error::from_string_literal("JBIG2ImageDecoderPlugin: Cannot decode intermediate text region yet");
  1524. }
  1525. static ErrorOr<void> decode_immediate_text_region(JBIG2LoadingContext& context, SegmentData const& segment)
  1526. {
  1527. // 7.4.3 Text region segment syntax
  1528. auto data = segment.data;
  1529. auto information_field = TRY(decode_region_segment_information_field(data));
  1530. data = data.slice(sizeof(information_field));
  1531. dbgln_if(JBIG2_DEBUG, "Text region: width={}, height={}, x={}, y={}, flags={:#x}", information_field.width, information_field.height, information_field.x_location, information_field.y_location, information_field.flags);
  1532. FixedMemoryStream stream(data);
  1533. // 7.4.3.1.1 Text region segment flags
  1534. u16 text_region_segment_flags = TRY(stream.read_value<BigEndian<u16>>());
  1535. bool uses_huffman_encoding = (text_region_segment_flags & 1) != 0; // "SBHUFF" in spec.
  1536. bool uses_refinement_coding = (text_region_segment_flags >> 1) & 1; // "SBREFINE" in spec.
  1537. u8 log_strip_size = (text_region_segment_flags >> 2) & 3; // "LOGSBSTRIPS" in spec.
  1538. u8 strip_size = 1u << log_strip_size;
  1539. u8 reference_corner = (text_region_segment_flags >> 4) & 3; // "REFCORNER"
  1540. bool is_transposed = (text_region_segment_flags >> 6) & 1; // "TRANSPOSED" in spec.
  1541. u8 combination_operator = (text_region_segment_flags >> 7) & 3; // "SBCOMBOP" in spec.
  1542. if (combination_operator > 4)
  1543. return Error::from_string_literal("JBIG2ImageDecoderPlugin: Invalid text region combination operator");
  1544. u8 default_pixel_value = (text_region_segment_flags >> 9) & 1; // "SBDEFPIXEL" in spec.
  1545. u8 delta_s_offset_value = (text_region_segment_flags >> 10) & 0x1f; // "SBDSOFFSET" in spec.
  1546. i8 delta_s_offset = delta_s_offset_value;
  1547. if (delta_s_offset_value & 0x10) {
  1548. // This is converting a 5-bit two's complement number ot i8.
  1549. // FIXME: There's probably a simpler way to do this? Probably just sign-extend by or-ing in the top 3 bits?
  1550. delta_s_offset_value = (~delta_s_offset_value + 1) & 0x1f;
  1551. delta_s_offset = -delta_s_offset_value;
  1552. }
  1553. u8 refinement_template = (text_region_segment_flags >> 15) != 0; // "SBRTEMPLATE" in spec.
  1554. if (!uses_refinement_coding && refinement_template != 0)
  1555. return Error::from_string_literal("JBIG2ImageDecoderPlugin: Invalid refinement_template");
  1556. // 7.4.3.1.2 Text region segment Huffman flags
  1557. // "This field is only present if SBHUFF is 1."
  1558. // FIXME: Support this eventually.
  1559. if (uses_huffman_encoding)
  1560. return Error::from_string_literal("JBIG2ImageDecoderPlugin: Cannot decode huffman text regions yet");
  1561. // 7.4.3.1.3 Text region refinement AT flags
  1562. // "This field is only present if SBREFINE is 1 and SBRTEMPLATE is 0."
  1563. Array<AdaptiveTemplatePixel, 2> adaptive_refinement_template {};
  1564. if (uses_refinement_coding && refinement_template == 0) {
  1565. for (size_t i = 0; i < adaptive_refinement_template.size(); ++i) {
  1566. adaptive_refinement_template[i].x = TRY(stream.read_value<i8>());
  1567. adaptive_refinement_template[i].y = TRY(stream.read_value<i8>());
  1568. }
  1569. }
  1570. // 7.4.3.1.4 Number of symbol instances (SBNUMINSTANCES)
  1571. u32 number_of_symbol_instances = TRY(stream.read_value<BigEndian<u32>>());
  1572. // 7.4.3.1.5 Text region segment symbol ID Huffman decoding table
  1573. // "It is only present if SBHUFF is 1."
  1574. // FIXME: Support this eventually.
  1575. // 7.4.3.2 Decoding a text region segment
  1576. // "1) Interpret its header, as described in 7.4.3.1."
  1577. // Done!
  1578. // "2) Decode (or retrieve the results of decoding) any referred-to symbol dictionary and tables segments."
  1579. Vector<NonnullRefPtr<Symbol>> symbols;
  1580. for (auto referred_to_segment_number : segment.header.referred_to_segment_numbers) {
  1581. auto opt_referred_to_segment = context.segments_by_number.get(referred_to_segment_number);
  1582. if (!opt_referred_to_segment.has_value())
  1583. return Error::from_string_literal("JBIG2ImageDecoderPlugin: Text segment refers to non-existent segment");
  1584. dbgln_if(JBIG2_DEBUG, "Text segment refers to segment id {} index {}", referred_to_segment_number, opt_referred_to_segment.value());
  1585. auto const& referred_to_segment = context.segments[opt_referred_to_segment.value()];
  1586. if (!referred_to_segment.symbols.has_value())
  1587. return Error::from_string_literal("JBIG2ImageDecoderPlugin: Text segment referred-to segment without symbols");
  1588. symbols.extend(referred_to_segment.symbols.value());
  1589. }
  1590. // "3) As described in E.3.7, reset all the arithmetic coding statistics to zero."
  1591. // FIXME
  1592. // "4) Invoke the text region decoding procedure described in 6.4, with the parameters to the text region decoding procedure set as shown in Table 34."
  1593. TextRegionDecodingInputParameters inputs;
  1594. inputs.uses_huffman_encoding = uses_huffman_encoding;
  1595. inputs.uses_refinement_coding = uses_refinement_coding;
  1596. inputs.default_pixel = default_pixel_value;
  1597. inputs.operator_ = static_cast<CombinationOperator>(combination_operator);
  1598. inputs.is_transposed = is_transposed;
  1599. inputs.reference_corner = static_cast<TextRegionDecodingInputParameters::Corner>(reference_corner);
  1600. inputs.delta_s_offset = delta_s_offset;
  1601. inputs.region_width = information_field.width;
  1602. inputs.region_height = information_field.height;
  1603. inputs.number_of_instances = number_of_symbol_instances;
  1604. inputs.size_of_symbol_instance_strips = strip_size;
  1605. inputs.id_symbol_code_length = ceil(log2(symbols.size()));
  1606. inputs.symbols = move(symbols);
  1607. // FIXME: Huffman tables.
  1608. inputs.refinement_template = refinement_template;
  1609. inputs.refinement_adaptive_template_pixels = adaptive_refinement_template;
  1610. auto result = TRY(text_region_decoding_procedure(inputs, data.slice(TRY(stream.tell()))));
  1611. composite_bitbuffer(*context.page.bits, *result, { information_field.x_location, information_field.y_location }, information_field.external_combination_operator());
  1612. return {};
  1613. }
  1614. static ErrorOr<void> decode_pattern_dictionary(JBIG2LoadingContext&, SegmentData const&)
  1615. {
  1616. return Error::from_string_literal("JBIG2ImageDecoderPlugin: Cannot decode pattern dictionary yet");
  1617. }
  1618. static ErrorOr<void> decode_intermediate_halftone_region(JBIG2LoadingContext&, SegmentData const&)
  1619. {
  1620. return Error::from_string_literal("JBIG2ImageDecoderPlugin: Cannot decode intermediate halftone region yet");
  1621. }
  1622. static ErrorOr<void> decode_immediate_halftone_region(JBIG2LoadingContext&, SegmentData const&)
  1623. {
  1624. return Error::from_string_literal("JBIG2ImageDecoderPlugin: Cannot decode immediate halftone region yet");
  1625. }
  1626. static ErrorOr<void> decode_immediate_lossless_halftone_region(JBIG2LoadingContext&, SegmentData const&)
  1627. {
  1628. return Error::from_string_literal("JBIG2ImageDecoderPlugin: Cannot decode immediate lossless halftone region yet");
  1629. }
  1630. static ErrorOr<void> decode_intermediate_generic_region(JBIG2LoadingContext&, SegmentData const&)
  1631. {
  1632. return Error::from_string_literal("JBIG2ImageDecoderPlugin: Cannot decode intermediate generic region yet");
  1633. }
  1634. static ErrorOr<void> decode_immediate_generic_region(JBIG2LoadingContext& context, SegmentData const& segment)
  1635. {
  1636. // 7.4.6 Generic region segment syntax
  1637. auto data = segment.data;
  1638. auto information_field = TRY(decode_region_segment_information_field(data));
  1639. data = data.slice(sizeof(information_field));
  1640. dbgln_if(JBIG2_DEBUG, "Generic region: width={}, height={}, x={}, y={}, flags={:#x}", information_field.width, information_field.height, information_field.x_location, information_field.y_location, information_field.flags);
  1641. // 7.4.6.2 Generic region segment flags
  1642. if (data.is_empty())
  1643. return Error::from_string_literal("JBIG2ImageDecoderPlugin: No segment data");
  1644. u8 flags = data[0];
  1645. bool uses_mmr = (flags & 1) != 0;
  1646. u8 arithmetic_coding_template = (flags >> 1) & 3; // "GBTEMPLATE"
  1647. bool typical_prediction_generic_decoding_on = (flags >> 3) & 1; // "TPGDON"; "TPGD" is short for "Typical Prediction for Generic Direct coding"
  1648. bool uses_extended_reference_template = (flags >> 4) & 1; // "EXTTEMPLATE"
  1649. if (flags & 0b1110'0000)
  1650. return Error::from_string_literal("JBIG2ImageDecoderPlugin: Invalid flags");
  1651. data = data.slice(sizeof(flags));
  1652. // 7.4.6.3 Generic region segment AT flags
  1653. Array<AdaptiveTemplatePixel, 12> adaptive_template_pixels {};
  1654. if (!uses_mmr) {
  1655. dbgln_if(JBIG2_DEBUG, "Non-MMR generic region, GBTEMPLATE={} TPGDON={} EXTTEMPLATE={}", arithmetic_coding_template, typical_prediction_generic_decoding_on, uses_extended_reference_template);
  1656. if (arithmetic_coding_template == 0 && uses_extended_reference_template) {
  1657. // This was added in T.88 Amendment 2 (https://www.itu.int/rec/T-REC-T.88-200306-S!Amd2/en) mid-2003.
  1658. // I haven't seen it being used in the wild, and the spec says "32-byte field as shown below" and then shows 24 bytes,
  1659. // so it's not clear how much data to read.
  1660. return Error::from_string_literal("JBIG2ImageDecoderPlugin: GBTEMPLATE=0 EXTTEMPLATE=1 not yet implemented");
  1661. }
  1662. size_t number_of_adaptive_template_pixels = arithmetic_coding_template == 0 ? 4 : 1;
  1663. if (data.size() < 2 * number_of_adaptive_template_pixels)
  1664. return Error::from_string_literal("JBIG2ImageDecoderPlugin: No adaptive template data");
  1665. for (size_t i = 0; i < number_of_adaptive_template_pixels; ++i) {
  1666. adaptive_template_pixels[i].x = static_cast<i8>(data[2 * i]);
  1667. adaptive_template_pixels[i].y = static_cast<i8>(data[2 * i + 1]);
  1668. }
  1669. data = data.slice(2 * number_of_adaptive_template_pixels);
  1670. }
  1671. // 7.4.6.4 Decoding a generic region segment
  1672. // "1) Interpret its header, as described in 7.4.6.1"
  1673. // Done above.
  1674. // "2) As described in E.3.7, reset all the arithmetic coding statistics to zero."
  1675. Vector<JBIG2::ArithmeticDecoder::Context> contexts;
  1676. contexts.resize(1 << number_of_context_bits_for_template(arithmetic_coding_template));
  1677. // "3) Invoke the generic region decoding procedure described in 6.2, with the parameters to the generic region decoding procedure set as shown in Table 37."
  1678. GenericRegionDecodingInputParameters inputs;
  1679. inputs.is_modified_modified_read = uses_mmr;
  1680. inputs.region_width = information_field.width;
  1681. inputs.region_height = information_field.height;
  1682. inputs.gb_template = arithmetic_coding_template;
  1683. inputs.is_typical_prediction_used = typical_prediction_generic_decoding_on;
  1684. inputs.is_extended_reference_template_used = uses_extended_reference_template;
  1685. inputs.skip_pattern = OptionalNone {};
  1686. inputs.adaptive_template_pixels = adaptive_template_pixels;
  1687. Optional<JBIG2::ArithmeticDecoder> decoder;
  1688. if (!uses_mmr) {
  1689. decoder = TRY(JBIG2::ArithmeticDecoder::initialize(data));
  1690. inputs.arithmetic_decoder = &decoder.value();
  1691. }
  1692. auto result = TRY(generic_region_decoding_procedure(inputs, data, contexts));
  1693. // 8.2 Page image composition step 5)
  1694. if (information_field.x_location + information_field.width > (u32)context.page.size.width()
  1695. || information_field.y_location + information_field.height > (u32)context.page.size.height()) {
  1696. return Error::from_string_literal("JBIG2ImageDecoderPlugin: Region bounds outsize of page bounds");
  1697. }
  1698. composite_bitbuffer(*context.page.bits, *result, { information_field.x_location, information_field.y_location }, information_field.external_combination_operator());
  1699. return {};
  1700. }
  1701. static ErrorOr<void> decode_intermediate_generic_refinement_region(JBIG2LoadingContext&, SegmentData const&)
  1702. {
  1703. return Error::from_string_literal("JBIG2ImageDecoderPlugin: Cannot decode intermediate generic refinement region yet");
  1704. }
  1705. static ErrorOr<void> decode_immediate_generic_refinement_region(JBIG2LoadingContext&, SegmentData const&)
  1706. {
  1707. return Error::from_string_literal("JBIG2ImageDecoderPlugin: Cannot decode immediate generic refinement region yet");
  1708. }
  1709. static ErrorOr<void> decode_immediate_lossless_generic_refinement_region(JBIG2LoadingContext&, SegmentData const&)
  1710. {
  1711. return Error::from_string_literal("JBIG2ImageDecoderPlugin: Cannot decode immediate lossless generic refinement region yet");
  1712. }
  1713. static ErrorOr<void> decode_page_information(JBIG2LoadingContext& context, SegmentData const& segment)
  1714. {
  1715. // 7.4.8 Page information segment syntax and 8.1 Decoder model steps 1) - 3).
  1716. // "1) Decode the page information segment.""
  1717. auto page_information = TRY(decode_page_information_segment(segment.data));
  1718. bool page_is_striped = (page_information.striping_information & 0x80) != 0;
  1719. if (page_information.bitmap_height == 0xffff'ffff && !page_is_striped)
  1720. return Error::from_string_literal("JBIG2ImageDecoderPlugin: Non-striped bitmaps of indeterminate height not allowed");
  1721. u16 maximum_stripe_height = page_information.striping_information & 0x7F;
  1722. u8 default_color = (page_information.flags >> 2) & 1;
  1723. u8 default_combination_operator = (page_information.flags >> 3) & 3;
  1724. context.page.default_combination_operator = static_cast<CombinationOperator>(default_combination_operator);
  1725. dbgln_if(JBIG2_DEBUG, "Page information: width={}, height={}, is_striped={}, max_stripe_height={}, default_color={}, default_combination_operator={}", page_information.bitmap_width, page_information.bitmap_height, page_is_striped, maximum_stripe_height, default_color, default_combination_operator);
  1726. // FIXME: Do something with the other fields in page_information.
  1727. // "2) Create the page buffer, of the size given in the page information segment.
  1728. //
  1729. // If the page height is unknown, then this is not possible. However, in this case the page must be striped,
  1730. // and the maximum stripe height specified, and the initial page buffer can be created with height initially
  1731. // equal to this maximum stripe height."
  1732. size_t height = page_information.bitmap_height;
  1733. if (height == 0xffff'ffff)
  1734. height = maximum_stripe_height;
  1735. context.page.bits = TRY(BitBuffer::create(page_information.bitmap_width, height));
  1736. // "3) Fill the page buffer with the page's default pixel value."
  1737. context.page.bits->fill(default_color != 0);
  1738. return {};
  1739. }
  1740. static ErrorOr<void> decode_end_of_page(JBIG2LoadingContext&, SegmentData const& segment)
  1741. {
  1742. // 7.4.9 End of page segment syntax
  1743. if (segment.data.size() != 0)
  1744. return Error::from_string_literal("JBIG2ImageDecoderPlugin: End of page segment has non-zero size");
  1745. // FIXME: If the page had unknown height, check that previous segment was end-of-stripe.
  1746. // FIXME: Maybe mark page as completed and error if we see more segments for it?
  1747. return {};
  1748. }
  1749. static ErrorOr<void> decode_end_of_stripe(JBIG2LoadingContext&, SegmentData const&)
  1750. {
  1751. return Error::from_string_literal("JBIG2ImageDecoderPlugin: Cannot decode end of stripe yet");
  1752. }
  1753. static ErrorOr<void> decode_end_of_file(JBIG2LoadingContext&, SegmentData const& segment)
  1754. {
  1755. // 7.4.11 End of file segment syntax
  1756. if (segment.data.size() != 0)
  1757. return Error::from_string_literal("JBIG2ImageDecoderPlugin: End of file segment has non-zero size");
  1758. return {};
  1759. }
  1760. static ErrorOr<void> decode_profiles(JBIG2LoadingContext&, SegmentData const&)
  1761. {
  1762. return Error::from_string_literal("JBIG2ImageDecoderPlugin: Cannot decode profiles yet");
  1763. }
  1764. static ErrorOr<void> decode_tables(JBIG2LoadingContext&, SegmentData const&)
  1765. {
  1766. return Error::from_string_literal("JBIG2ImageDecoderPlugin: Cannot decode tables yet");
  1767. }
  1768. static ErrorOr<void> decode_color_palette(JBIG2LoadingContext&, SegmentData const&)
  1769. {
  1770. return Error::from_string_literal("JBIG2ImageDecoderPlugin: Cannot decode color palette yet");
  1771. }
  1772. static ErrorOr<void> decode_extension(JBIG2LoadingContext&, SegmentData const& segment)
  1773. {
  1774. // 7.4.14 Extension segment syntax
  1775. FixedMemoryStream stream { segment.data };
  1776. enum ExtensionType {
  1777. SingleByteCodedComment = 0x20000000,
  1778. MultiByteCodedComment = 0x20000002,
  1779. };
  1780. u32 type = TRY(stream.read_value<BigEndian<u32>>());
  1781. auto read_string = [&]<class T>() -> ErrorOr<Vector<T>> {
  1782. Vector<T> result;
  1783. do {
  1784. result.append(TRY(stream.read_value<BigEndian<T>>()));
  1785. } while (result.last());
  1786. result.take_last();
  1787. return result;
  1788. };
  1789. switch (type) {
  1790. case SingleByteCodedComment: {
  1791. // 7.4.15.1 Single-byte coded comment
  1792. // Pairs of zero-terminated ISO/IEC 8859-1 (latin1) pairs, terminated by another \0.
  1793. while (true) {
  1794. auto first_bytes = TRY(read_string.template operator()<u8>());
  1795. if (first_bytes.is_empty())
  1796. break;
  1797. auto second_bytes = TRY(read_string.template operator()<u8>());
  1798. auto first = TRY(TextCodec::decoder_for("ISO-8859-1"sv)->to_utf8(StringView { first_bytes }));
  1799. auto second = TRY(TextCodec::decoder_for("ISO-8859-1"sv)->to_utf8(StringView { second_bytes }));
  1800. dbgln("JBIG2ImageDecoderPlugin: key '{}', value '{}'", first, second);
  1801. }
  1802. if (!stream.is_eof())
  1803. return Error::from_string_literal("JBIG2ImageDecoderPlugin: Trailing data after SingleByteCodedComment");
  1804. return {};
  1805. }
  1806. case MultiByteCodedComment: {
  1807. // 7.4.15.2 Multi-byte coded comment
  1808. // Pairs of (two-byte-)zero-terminated UCS-2 pairs, terminated by another \0\0.
  1809. while (true) {
  1810. auto first_ucs2 = TRY(read_string.template operator()<u16>());
  1811. if (first_ucs2.is_empty())
  1812. break;
  1813. auto second_ucs2 = TRY(read_string.template operator()<u16>());
  1814. auto first = TRY(Utf16View(first_ucs2).to_utf8());
  1815. auto second = TRY(Utf16View(second_ucs2).to_utf8());
  1816. dbgln("JBIG2ImageDecoderPlugin: key '{}', value '{}'", first, second);
  1817. }
  1818. if (!stream.is_eof())
  1819. return Error::from_string_literal("JBIG2ImageDecoderPlugin: Trailing data after MultiByteCodedComment");
  1820. return {};
  1821. }
  1822. }
  1823. // FIXME: If bit 31 in `type` is not set, the extension isn't necessary, and we could ignore it.
  1824. dbgln("JBIG2ImageDecoderPlugin: Unknown extension type {:#x}", type);
  1825. return Error::from_string_literal("JBIG2ImageDecoderPlugin: Unknown extension type");
  1826. }
  1827. static ErrorOr<void> decode_data(JBIG2LoadingContext& context)
  1828. {
  1829. TRY(warn_about_multiple_pages(context));
  1830. for (size_t i = 0; i < context.segments.size(); ++i) {
  1831. auto& segment = context.segments[i];
  1832. if (segment.header.page_association != 0 && segment.header.page_association != 1)
  1833. continue;
  1834. switch (segment.header.type) {
  1835. case SegmentType::SymbolDictionary:
  1836. TRY(decode_symbol_dictionary(context, segment));
  1837. break;
  1838. case SegmentType::IntermediateTextRegion:
  1839. TRY(decode_intermediate_text_region(context, segment));
  1840. break;
  1841. case SegmentType::ImmediateTextRegion:
  1842. case SegmentType::ImmediateLosslessTextRegion:
  1843. // 7.4.3 Text region segment syntax
  1844. // "The data parts of all three of the text region segment types ("intermediate text region", "immediate text region" and
  1845. // "immediate lossless text region") are coded identically, but are acted upon differently, see 8.2."
  1846. // But 8.2 only describes a difference between intermediate and immediate regions as far as I can tell,
  1847. // and calling the immediate text region handler for immediate lossless text regions seems to do the right thing (?).
  1848. TRY(decode_immediate_text_region(context, segment));
  1849. break;
  1850. case SegmentType::PatternDictionary:
  1851. TRY(decode_pattern_dictionary(context, segment));
  1852. break;
  1853. case SegmentType::IntermediateHalftoneRegion:
  1854. TRY(decode_intermediate_halftone_region(context, segment));
  1855. break;
  1856. case SegmentType::ImmediateHalftoneRegion:
  1857. TRY(decode_immediate_halftone_region(context, segment));
  1858. break;
  1859. case SegmentType::ImmediateLosslessHalftoneRegion:
  1860. TRY(decode_immediate_lossless_halftone_region(context, segment));
  1861. break;
  1862. case SegmentType::IntermediateGenericRegion:
  1863. TRY(decode_intermediate_generic_region(context, segment));
  1864. break;
  1865. case SegmentType::ImmediateGenericRegion:
  1866. case SegmentType::ImmediateLosslessGenericRegion:
  1867. // 7.4.6 Generic region segment syntax
  1868. // "The data parts of all three of the generic region segment types ("intermediate generic region", "immediate generic region" and
  1869. // "immediate lossless generic region") are coded identically, but are acted upon differently, see 8.2."
  1870. // But 8.2 only describes a difference between intermediate and immediate regions as far as I can tell,
  1871. // and calling the immediate generic region handler for immediate generic lossless regions seems to do the right thing (?).
  1872. TRY(decode_immediate_generic_region(context, segment));
  1873. break;
  1874. case SegmentType::IntermediateGenericRefinementRegion:
  1875. TRY(decode_intermediate_generic_refinement_region(context, segment));
  1876. break;
  1877. case SegmentType::ImmediateGenericRefinementRegion:
  1878. TRY(decode_immediate_generic_refinement_region(context, segment));
  1879. break;
  1880. case SegmentType::ImmediateLosslessGenericRefinementRegion:
  1881. TRY(decode_immediate_lossless_generic_refinement_region(context, segment));
  1882. break;
  1883. case SegmentType::PageInformation:
  1884. TRY(decode_page_information(context, segment));
  1885. break;
  1886. case SegmentType::EndOfPage:
  1887. TRY(decode_end_of_page(context, segment));
  1888. break;
  1889. case SegmentType::EndOfStripe:
  1890. TRY(decode_end_of_stripe(context, segment));
  1891. break;
  1892. case SegmentType::EndOfFile:
  1893. TRY(decode_end_of_file(context, segment));
  1894. // "If a file contains an end of file segment, it must be the last segment."
  1895. if (i != context.segments.size() - 1)
  1896. return Error::from_string_literal("JBIG2ImageDecoderPlugin: End of file segment not last segment");
  1897. break;
  1898. case SegmentType::Profiles:
  1899. TRY(decode_profiles(context, segment));
  1900. break;
  1901. case SegmentType::Tables:
  1902. TRY(decode_tables(context, segment));
  1903. break;
  1904. case SegmentType::ColorPalette:
  1905. TRY(decode_color_palette(context, segment));
  1906. break;
  1907. case SegmentType::Extension:
  1908. TRY(decode_extension(context, segment));
  1909. break;
  1910. }
  1911. }
  1912. return {};
  1913. }
  1914. JBIG2ImageDecoderPlugin::JBIG2ImageDecoderPlugin()
  1915. {
  1916. m_context = make<JBIG2LoadingContext>();
  1917. }
  1918. IntSize JBIG2ImageDecoderPlugin::size()
  1919. {
  1920. return m_context->page.size;
  1921. }
  1922. bool JBIG2ImageDecoderPlugin::sniff(ReadonlyBytes data)
  1923. {
  1924. return data.starts_with(id_string);
  1925. }
  1926. ErrorOr<NonnullOwnPtr<ImageDecoderPlugin>> JBIG2ImageDecoderPlugin::create(ReadonlyBytes data)
  1927. {
  1928. auto plugin = TRY(adopt_nonnull_own_or_enomem(new (nothrow) JBIG2ImageDecoderPlugin()));
  1929. TRY(decode_jbig2_header(*plugin->m_context, data));
  1930. data = data.slice(sizeof(id_string) + sizeof(u8) + (plugin->m_context->number_of_pages.has_value() ? sizeof(u32) : 0));
  1931. TRY(decode_segment_headers(*plugin->m_context, data));
  1932. TRY(scan_for_page_size(*plugin->m_context));
  1933. return plugin;
  1934. }
  1935. ErrorOr<ImageFrameDescriptor> JBIG2ImageDecoderPlugin::frame(size_t index, Optional<IntSize>)
  1936. {
  1937. // FIXME: Use this for multi-page JBIG2 files?
  1938. if (index != 0)
  1939. return Error::from_string_literal("JBIG2ImageDecoderPlugin: Invalid frame index");
  1940. if (m_context->state == JBIG2LoadingContext::State::Error)
  1941. return Error::from_string_literal("JBIG2ImageDecoderPlugin: Decoding failed");
  1942. if (m_context->state < JBIG2LoadingContext::State::Decoded) {
  1943. auto result = decode_data(*m_context);
  1944. if (result.is_error()) {
  1945. m_context->state = JBIG2LoadingContext::State::Error;
  1946. return result.release_error();
  1947. }
  1948. m_context->state = JBIG2LoadingContext::State::Decoded;
  1949. }
  1950. auto bitmap = TRY(m_context->page.bits->to_gfx_bitmap());
  1951. return ImageFrameDescriptor { move(bitmap), 0 };
  1952. }
  1953. ErrorOr<ByteBuffer> JBIG2ImageDecoderPlugin::decode_embedded(Vector<ReadonlyBytes> data)
  1954. {
  1955. auto plugin = TRY(adopt_nonnull_own_or_enomem(new (nothrow) JBIG2ImageDecoderPlugin()));
  1956. plugin->m_context->organization = Organization::Embedded;
  1957. for (auto const& segment_data : data)
  1958. TRY(decode_segment_headers(*plugin->m_context, segment_data));
  1959. TRY(scan_for_page_size(*plugin->m_context));
  1960. TRY(decode_data(*plugin->m_context));
  1961. return plugin->m_context->page.bits->to_byte_buffer();
  1962. }
  1963. }