JBIG2Loader.cpp 110 KB

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