JBIG2Loader.cpp 122 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691
  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<NonnullOwnPtr<BitBuffer>> subbitmap(Gfx::IntRect const& rect) const;
  373. ErrorOr<NonnullRefPtr<Gfx::Bitmap>> to_gfx_bitmap() const;
  374. ErrorOr<ByteBuffer> to_byte_buffer() const;
  375. size_t width() const { return m_width; }
  376. size_t height() const { return m_height; }
  377. private:
  378. BitBuffer(ByteBuffer, size_t width, size_t height, size_t pitch);
  379. ByteBuffer m_bits;
  380. size_t m_width { 0 };
  381. size_t m_height { 0 };
  382. size_t m_pitch { 0 };
  383. };
  384. ErrorOr<NonnullOwnPtr<BitBuffer>> BitBuffer::create(size_t width, size_t height)
  385. {
  386. size_t pitch = ceil_div(width, 8ull);
  387. auto bits = TRY(ByteBuffer::create_uninitialized(pitch * height));
  388. return adopt_nonnull_own_or_enomem(new (nothrow) BitBuffer(move(bits), width, height, pitch));
  389. }
  390. bool BitBuffer::get_bit(size_t x, size_t y) const
  391. {
  392. VERIFY(x < m_width);
  393. VERIFY(y < m_height);
  394. size_t byte_offset = x / 8;
  395. size_t bit_offset = x % 8;
  396. u8 byte = m_bits[y * m_pitch + byte_offset];
  397. byte = (byte >> (8 - 1 - bit_offset)) & 1;
  398. return byte != 0;
  399. }
  400. void BitBuffer::set_bit(size_t x, size_t y, bool b)
  401. {
  402. VERIFY(x < m_width);
  403. VERIFY(y < m_height);
  404. size_t byte_offset = x / 8;
  405. size_t bit_offset = x % 8;
  406. u8 byte = m_bits[y * m_pitch + byte_offset];
  407. u8 mask = 1u << (8 - 1 - bit_offset);
  408. if (b)
  409. byte |= mask;
  410. else
  411. byte &= ~mask;
  412. m_bits[y * m_pitch + byte_offset] = byte;
  413. }
  414. void BitBuffer::fill(bool b)
  415. {
  416. u8 fill_byte = b ? 0xff : 0;
  417. for (auto& byte : m_bits.bytes())
  418. byte = fill_byte;
  419. }
  420. ErrorOr<NonnullOwnPtr<BitBuffer>> BitBuffer::subbitmap(Gfx::IntRect const& rect) const
  421. {
  422. VERIFY(rect.x() >= 0);
  423. VERIFY(rect.width() >= 0);
  424. VERIFY(static_cast<size_t>(rect.right()) <= width());
  425. VERIFY(rect.y() >= 0);
  426. VERIFY(rect.height() >= 0);
  427. VERIFY(static_cast<size_t>(rect.bottom()) <= height());
  428. auto subbitmap = TRY(create(rect.width(), rect.height()));
  429. for (int y = 0; y < rect.height(); ++y)
  430. for (int x = 0; x < rect.width(); ++x)
  431. subbitmap->set_bit(x, y, get_bit(rect.x() + x, rect.y() + y));
  432. return subbitmap;
  433. }
  434. ErrorOr<NonnullRefPtr<Gfx::Bitmap>> BitBuffer::to_gfx_bitmap() const
  435. {
  436. auto bitmap = TRY(Gfx::Bitmap::create(Gfx::BitmapFormat::BGRx8888, { m_width, m_height }));
  437. for (size_t y = 0; y < m_height; ++y) {
  438. for (size_t x = 0; x < m_width; ++x) {
  439. auto color = get_bit(x, y) ? Color::Black : Color::White;
  440. bitmap->set_pixel(x, y, color);
  441. }
  442. }
  443. return bitmap;
  444. }
  445. ErrorOr<ByteBuffer> BitBuffer::to_byte_buffer() const
  446. {
  447. return ByteBuffer::copy(m_bits);
  448. }
  449. BitBuffer::BitBuffer(ByteBuffer bits, size_t width, size_t height, size_t pitch)
  450. : m_bits(move(bits))
  451. , m_width(width)
  452. , m_height(height)
  453. , m_pitch(pitch)
  454. {
  455. }
  456. class Symbol : public RefCounted<Symbol> {
  457. public:
  458. static NonnullRefPtr<Symbol> create(NonnullOwnPtr<BitBuffer> bitmap)
  459. {
  460. return adopt_ref(*new Symbol(move(bitmap)));
  461. }
  462. BitBuffer const& bitmap() const { return *m_bitmap; }
  463. private:
  464. Symbol(NonnullOwnPtr<BitBuffer> bitmap)
  465. : m_bitmap(move(bitmap))
  466. {
  467. }
  468. NonnullOwnPtr<BitBuffer> m_bitmap;
  469. };
  470. struct SegmentData {
  471. SegmentHeader header;
  472. ReadonlyBytes data;
  473. // Set on dictionary segments after they've been decoded.
  474. Optional<Vector<NonnullRefPtr<Symbol>>> symbols;
  475. // Set on pattern segments after they've been decoded.
  476. Optional<Vector<NonnullRefPtr<Symbol>>> patterns;
  477. };
  478. // 7.4.8.5 Page segment flags
  479. enum class CombinationOperator {
  480. Or = 0,
  481. And = 1,
  482. Xor = 2,
  483. XNor = 3,
  484. Replace = 4,
  485. };
  486. static void composite_bitbuffer(BitBuffer& out, BitBuffer const& bitmap, Gfx::IntPoint position, CombinationOperator operator_)
  487. {
  488. size_t start_x = 0, end_x = bitmap.width();
  489. size_t start_y = 0, end_y = bitmap.height();
  490. if (position.x() < 0) {
  491. start_x = -position.x();
  492. position.set_x(0);
  493. }
  494. if (position.y() < 0) {
  495. start_y = -position.y();
  496. position.set_y(0);
  497. }
  498. if (position.x() + bitmap.width() > out.width())
  499. end_x = out.width() - position.x();
  500. if (position.y() + bitmap.height() > out.height())
  501. end_y = out.height() - position.y();
  502. for (size_t y = start_y; y < end_y; ++y) {
  503. for (size_t x = start_x; x < end_x; ++x) {
  504. bool bit = bitmap.get_bit(x, y);
  505. switch (operator_) {
  506. case CombinationOperator::Or:
  507. bit = bit || out.get_bit(position.x() + x, position.y() + y);
  508. break;
  509. case CombinationOperator::And:
  510. bit = bit && out.get_bit(position.x() + x, position.y() + y);
  511. break;
  512. case CombinationOperator::Xor:
  513. bit = bit ^ out.get_bit(position.x() + x, position.y() + y);
  514. break;
  515. case CombinationOperator::XNor:
  516. bit = !(bit ^ out.get_bit(position.x() + x, position.y() + y));
  517. break;
  518. case CombinationOperator::Replace:
  519. // Nothing to do.
  520. break;
  521. }
  522. out.set_bit(position.x() + x, position.y() + y, bit);
  523. }
  524. }
  525. }
  526. struct Page {
  527. IntSize size;
  528. // This is never CombinationOperator::Replace for Pages.
  529. CombinationOperator default_combination_operator { CombinationOperator::Or };
  530. OwnPtr<BitBuffer> bits;
  531. };
  532. struct JBIG2LoadingContext {
  533. enum class State {
  534. NotDecoded = 0,
  535. Error,
  536. Decoded,
  537. };
  538. State state { State::NotDecoded };
  539. Organization organization { Organization::Sequential };
  540. Page page;
  541. Optional<u32> number_of_pages;
  542. Vector<SegmentData> segments;
  543. HashMap<u32, u32> segments_by_number;
  544. };
  545. static ErrorOr<void> decode_jbig2_header(JBIG2LoadingContext& context, ReadonlyBytes data)
  546. {
  547. if (!JBIG2ImageDecoderPlugin::sniff(data))
  548. return Error::from_string_literal("JBIG2LoadingContext: Invalid JBIG2 header");
  549. FixedMemoryStream stream(data.slice(sizeof(id_string)));
  550. // D.4.2 File header flags
  551. u8 header_flags = TRY(stream.read_value<u8>());
  552. if (header_flags & 0b11110000)
  553. return Error::from_string_literal("JBIG2LoadingContext: Invalid header flags");
  554. context.organization = (header_flags & 1) ? Organization::Sequential : Organization::RandomAccess;
  555. dbgln_if(JBIG2_DEBUG, "JBIG2LoadingContext: Organization: {} ({})", (int)context.organization, context.organization == Organization::Sequential ? "Sequential" : "Random-access");
  556. bool has_known_number_of_pages = (header_flags & 2) ? false : true;
  557. bool uses_templates_with_12_AT_pixels = (header_flags & 4) ? true : false;
  558. bool contains_colored_region_segments = (header_flags & 8) ? true : false;
  559. // FIXME: Do something with these?
  560. (void)uses_templates_with_12_AT_pixels;
  561. (void)contains_colored_region_segments;
  562. // D.4.3 Number of pages
  563. if (has_known_number_of_pages) {
  564. context.number_of_pages = TRY(stream.read_value<BigEndian<u32>>());
  565. dbgln_if(JBIG2_DEBUG, "JBIG2LoadingContext: Number of pages: {}", context.number_of_pages.value());
  566. }
  567. return {};
  568. }
  569. static ErrorOr<SegmentHeader> decode_segment_header(SeekableStream& stream)
  570. {
  571. // 7.2.2 Segment number
  572. u32 segment_number = TRY(stream.read_value<BigEndian<u32>>());
  573. dbgln_if(JBIG2_DEBUG, "Segment number: {}", segment_number);
  574. // 7.2.3 Segment header flags
  575. u8 flags = TRY(stream.read_value<u8>());
  576. SegmentType type = static_cast<SegmentType>(flags & 0b11'1111);
  577. dbgln_if(JBIG2_DEBUG, "Segment type: {}", (int)type);
  578. bool segment_page_association_size_is_32_bits = (flags & 0b100'0000) != 0;
  579. bool segment_retained_only_by_itself_and_extension_segments = (flags & 0b1000'00000) != 0;
  580. // FIXME: Do something with this?
  581. (void)segment_retained_only_by_itself_and_extension_segments;
  582. // 7.2.4 Referred-to segment count and retention flags
  583. u8 referred_to_segment_count_and_retention_flags = TRY(stream.read_value<u8>());
  584. u32 count_of_referred_to_segments = referred_to_segment_count_and_retention_flags >> 5;
  585. if (count_of_referred_to_segments == 5 || count_of_referred_to_segments == 6)
  586. return Error::from_string_literal("JBIG2ImageDecoderPlugin: Invalid count_of_referred_to_segments");
  587. u32 extra_count = 0;
  588. if (count_of_referred_to_segments == 7) {
  589. TRY(stream.seek(-1, SeekMode::FromCurrentPosition));
  590. count_of_referred_to_segments = TRY(stream.read_value<BigEndian<u32>>()) & 0x1FFF'FFFF;
  591. extra_count = ceil_div(count_of_referred_to_segments + 1, 8);
  592. TRY(stream.seek(extra_count, SeekMode::FromCurrentPosition));
  593. }
  594. dbgln_if(JBIG2_DEBUG, "Referred-to segment count: {}", count_of_referred_to_segments);
  595. // 7.2.5 Referred-to segment numbers
  596. Vector<u32> referred_to_segment_numbers;
  597. for (u32 i = 0; i < count_of_referred_to_segments; ++i) {
  598. u32 referred_to_segment_number;
  599. if (segment_number <= 256)
  600. referred_to_segment_number = TRY(stream.read_value<u8>());
  601. else if (segment_number <= 65536)
  602. referred_to_segment_number = TRY(stream.read_value<BigEndian<u16>>());
  603. else
  604. referred_to_segment_number = TRY(stream.read_value<BigEndian<u32>>());
  605. referred_to_segment_numbers.append(referred_to_segment_number);
  606. dbgln_if(JBIG2_DEBUG, "Referred-to segment number: {}", referred_to_segment_number);
  607. }
  608. // 7.2.6 Segment page association
  609. u32 segment_page_association;
  610. if (segment_page_association_size_is_32_bits) {
  611. segment_page_association = TRY(stream.read_value<BigEndian<u32>>());
  612. } else {
  613. segment_page_association = TRY(stream.read_value<u8>());
  614. }
  615. dbgln_if(JBIG2_DEBUG, "Segment page association: {}", segment_page_association);
  616. // 7.2.7 Segment data length
  617. u32 data_length = TRY(stream.read_value<BigEndian<u32>>());
  618. dbgln_if(JBIG2_DEBUG, "Segment data length: {}", data_length);
  619. // FIXME: Add some validity checks:
  620. // - check type is valid
  621. // - check referred_to_segment_numbers are smaller than segment_number
  622. // - 7.3.1 Rules for segment references
  623. // - 7.3.2 Rules for page associations
  624. Optional<u32> opt_data_length;
  625. if (data_length != 0xffff'ffff)
  626. opt_data_length = data_length;
  627. else if (type != ImmediateGenericRegion)
  628. return Error::from_string_literal("JBIG2ImageDecoderPlugin: Unknown data length only allowed for ImmediateGenericRegion");
  629. return SegmentHeader { segment_number, type, move(referred_to_segment_numbers), segment_page_association, opt_data_length };
  630. }
  631. static ErrorOr<size_t> scan_for_immediate_generic_region_size(ReadonlyBytes data)
  632. {
  633. // 7.2.7 Segment data length
  634. // "If the segment's type is "Immediate generic region", then the length field may contain the value 0xFFFFFFFF.
  635. // 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 (...).
  636. // In this case, the true length of the segment's data part shall be determined through examination of the data:
  637. // 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.
  638. // 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.
  639. // The form of encoding used by the segment may be determined by examining the eighteenth byte of its segment data part,
  640. // and the end sequences can occur anywhere after that eighteenth byte."
  641. // 7.4.6.4 Decoding a generic region segment
  642. // "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.
  643. // Thus, those sequences cannot occur by chance in the data that is decoded to generate the contents of the generic region."
  644. dbgln_if(JBIG2_DEBUG, "(Unknown data length, computing it)");
  645. if (data.size() < 19 + sizeof(u32))
  646. return Error::from_string_literal("JBIG2ImageDecoderPlugin: Data too short to contain segment data header and end sequence");
  647. // Per 7.4.6.1 Generic region segment data header, this starts with the 17 bytes described in
  648. // 7.4.1 Region segment information field, followed the byte described in 7.4.6.2 Generic region segment flags.
  649. // That byte's lowest bit stores if the segment uses MMR.
  650. u8 flags = data[17];
  651. bool uses_mmr = (flags & 1) != 0;
  652. auto end_sequence = uses_mmr ? to_array<u8>({ 0x00, 0x00 }) : to_array<u8>({ 0xFF, 0xAC });
  653. u8 const* end = static_cast<u8 const*>(memmem(data.data() + 19, data.size() - 19 - sizeof(u32), end_sequence.data(), end_sequence.size()));
  654. if (!end)
  655. return Error::from_string_literal("JBIG2ImageDecoderPlugin: Could not find end sequence in segment data");
  656. size_t size = end - data.data() + end_sequence.size() + sizeof(u32);
  657. dbgln_if(JBIG2_DEBUG, "(Computed size is {})", size);
  658. return size;
  659. }
  660. static ErrorOr<void> decode_segment_headers(JBIG2LoadingContext& context, ReadonlyBytes data)
  661. {
  662. FixedMemoryStream stream(data);
  663. Vector<ReadonlyBytes> segment_datas;
  664. auto store_and_skip_segment_data = [&](SegmentHeader const& segment_header) -> ErrorOr<void> {
  665. size_t start_offset = TRY(stream.tell());
  666. u32 data_length = TRY(segment_header.data_length.try_value_or_lazy_evaluated([&]() {
  667. return scan_for_immediate_generic_region_size(data.slice(start_offset));
  668. }));
  669. if (start_offset + data_length > data.size()) {
  670. dbgln_if(JBIG2_DEBUG, "JBIG2ImageDecoderPlugin: start_offset={}, data_length={}, data.size()={}", start_offset, data_length, data.size());
  671. return Error::from_string_literal("JBIG2ImageDecoderPlugin: Segment data length exceeds file size");
  672. }
  673. ReadonlyBytes segment_data = data.slice(start_offset, data_length);
  674. segment_datas.append(segment_data);
  675. TRY(stream.seek(data_length, SeekMode::FromCurrentPosition));
  676. return {};
  677. };
  678. Vector<SegmentHeader> segment_headers;
  679. while (!stream.is_eof()) {
  680. auto segment_header = TRY(decode_segment_header(stream));
  681. segment_headers.append(segment_header);
  682. if (context.organization != Organization::RandomAccess)
  683. TRY(store_and_skip_segment_data(segment_header));
  684. // Required per spec for files with RandomAccess organization.
  685. if (segment_header.type == SegmentType::EndOfFile)
  686. break;
  687. }
  688. if (context.organization == Organization::RandomAccess) {
  689. for (auto const& segment_header : segment_headers)
  690. TRY(store_and_skip_segment_data(segment_header));
  691. }
  692. if (segment_headers.size() != segment_datas.size())
  693. return Error::from_string_literal("JBIG2ImageDecoderPlugin: Segment headers and segment datas have different sizes");
  694. for (size_t i = 0; i < segment_headers.size(); ++i) {
  695. context.segments.append({ segment_headers[i], segment_datas[i], {}, {} });
  696. context.segments_by_number.set(segment_headers[i].segment_number, context.segments.size() - 1);
  697. }
  698. return {};
  699. }
  700. // 7.4.1 Region segment information field
  701. struct [[gnu::packed]] RegionSegmentInformationField {
  702. BigEndian<u32> width;
  703. BigEndian<u32> height;
  704. BigEndian<u32> x_location;
  705. BigEndian<u32> y_location;
  706. u8 flags;
  707. CombinationOperator external_combination_operator() const
  708. {
  709. VERIFY((flags & 0x7) <= 4);
  710. return static_cast<CombinationOperator>(flags & 0x7);
  711. }
  712. bool is_color_bitmap() const
  713. {
  714. return (flags & 0x8) != 0;
  715. }
  716. };
  717. static_assert(AssertSize<RegionSegmentInformationField, 17>());
  718. static ErrorOr<RegionSegmentInformationField> decode_region_segment_information_field(ReadonlyBytes data)
  719. {
  720. // 7.4.8 Page information segment syntax
  721. if (data.size() < sizeof(RegionSegmentInformationField))
  722. return Error::from_string_literal("JBIG2ImageDecoderPlugin: Invalid region segment information field size");
  723. auto result = *(RegionSegmentInformationField const*)data.data();
  724. if ((result.flags & 0b1111'0000) != 0)
  725. return Error::from_string_literal("JBIG2ImageDecoderPlugin: Invalid region segment information field flags");
  726. if ((result.flags & 0x7) > 4)
  727. return Error::from_string_literal("JBIG2ImageDecoderPlugin: Invalid region segment information field operator");
  728. // NOTE 3 – If the colour extension flag (COLEXTFLAG) is equal to 1, the external combination operator must be REPLACE.
  729. if (result.is_color_bitmap() && result.external_combination_operator() != CombinationOperator::Replace)
  730. return Error::from_string_literal("JBIG2ImageDecoderPlugin: Invalid colored region segment information field operator");
  731. return result;
  732. }
  733. // 7.4.8 Page information segment syntax
  734. struct [[gnu::packed]] PageInformationSegment {
  735. BigEndian<u32> bitmap_width;
  736. BigEndian<u32> bitmap_height;
  737. BigEndian<u32> page_x_resolution; // In pixels/meter.
  738. BigEndian<u32> page_y_resolution; // In pixels/meter.
  739. u8 flags;
  740. BigEndian<u16> striping_information;
  741. };
  742. static_assert(AssertSize<PageInformationSegment, 19>());
  743. static ErrorOr<PageInformationSegment> decode_page_information_segment(ReadonlyBytes data)
  744. {
  745. // 7.4.8 Page information segment syntax
  746. if (data.size() != sizeof(PageInformationSegment))
  747. return Error::from_string_literal("JBIG2ImageDecoderPlugin: Invalid page information segment size");
  748. return *(PageInformationSegment const*)data.data();
  749. }
  750. static ErrorOr<void> scan_for_page_size(JBIG2LoadingContext& context)
  751. {
  752. // We only decode the first page at the moment.
  753. bool found_size = false;
  754. for (auto const& segment : context.segments) {
  755. if (segment.header.type != SegmentType::PageInformation || segment.header.page_association != 1)
  756. continue;
  757. auto page_information = TRY(decode_page_information_segment(segment.data));
  758. // FIXME: We're supposed to compute this from the striping information if it's not set.
  759. if (page_information.bitmap_height == 0xffff'ffff)
  760. return Error::from_string_literal("JBIG2ImageDecoderPlugin: Cannot handle unknown page height yet");
  761. context.page.size = { page_information.bitmap_width, page_information.bitmap_height };
  762. found_size = true;
  763. }
  764. if (!found_size)
  765. return Error::from_string_literal("JBIG2ImageDecoderPlugin: No page information segment found for page 1");
  766. return {};
  767. }
  768. static ErrorOr<void> warn_about_multiple_pages(JBIG2LoadingContext& context)
  769. {
  770. HashTable<u32> seen_pages;
  771. Vector<u32> pages;
  772. for (auto const& segment : context.segments) {
  773. if (segment.header.page_association == 0)
  774. continue;
  775. if (seen_pages.contains(segment.header.page_association))
  776. continue;
  777. seen_pages.set(segment.header.page_association);
  778. pages.append(segment.header.page_association);
  779. }
  780. // scan_for_page_size() already checked that there's a page 1.
  781. VERIFY(seen_pages.contains(1));
  782. if (pages.size() == 1)
  783. return {};
  784. StringBuilder builder;
  785. builder.appendff("JBIG2 file contains {} pages ({}", pages.size(), pages[0]);
  786. size_t i;
  787. for (i = 1; i < min(pages.size(), 10); ++i)
  788. builder.appendff(" {}", pages[i]);
  789. if (i != pages.size())
  790. builder.append(" ..."sv);
  791. builder.append("). We will only render page 1."sv);
  792. dbgln("JBIG2ImageDecoderPlugin: {}", TRY(builder.to_string()));
  793. return {};
  794. }
  795. struct AdaptiveTemplatePixel {
  796. i8 x { 0 };
  797. i8 y { 0 };
  798. };
  799. // Figure 7 – Field to which AT pixel locations are restricted
  800. static ErrorOr<void> check_valid_adaptive_template_pixel(AdaptiveTemplatePixel const& adaptive_template_pixel)
  801. {
  802. // Don't have to check < -127 or > 127: The offsets are stored in an i8, so they can't be out of those bounds.
  803. if (adaptive_template_pixel.y > 0)
  804. return Error::from_string_literal("JBIG2ImageDecoderPlugin: Adaptive pixel y too big");
  805. if (adaptive_template_pixel.y == 0 && adaptive_template_pixel.x > -1)
  806. return Error::from_string_literal("JBIG2ImageDecoderPlugin: Adaptive pixel x too big");
  807. return {};
  808. }
  809. // 6.2.2 Input parameters
  810. // Table 2 – Parameters for the generic region decoding procedure
  811. struct GenericRegionDecodingInputParameters {
  812. bool is_modified_modified_read { false }; // "MMR" in spec.
  813. u32 region_width { 0 }; // "GBW" in spec.
  814. u32 region_height { 0 }; // "GBH" in spec.
  815. u8 gb_template { 0 };
  816. bool is_typical_prediction_used { false }; // "TPGDON" in spec.
  817. bool is_extended_reference_template_used { false }; // "EXTTEMPLATE" in spec.
  818. Optional<NonnullOwnPtr<BitBuffer>> skip_pattern; // "USESKIP", "SKIP" in spec.
  819. Array<AdaptiveTemplatePixel, 12> adaptive_template_pixels; // "GBATX" / "GBATY" in spec.
  820. // FIXME: GBCOLS, GBCOMBOP, COLEXTFLAG
  821. // If is_modified_modified_read is false, generic_region_decoding_procedure() reads data off this decoder.
  822. JBIG2::ArithmeticDecoder* arithmetic_decoder { nullptr };
  823. };
  824. // 6.2 Generic region decoding procedure
  825. static ErrorOr<NonnullOwnPtr<BitBuffer>> generic_region_decoding_procedure(GenericRegionDecodingInputParameters const& inputs, ReadonlyBytes data, Vector<JBIG2::ArithmeticDecoder::Context>& contexts)
  826. {
  827. if (inputs.is_modified_modified_read) {
  828. dbgln_if(JBIG2_DEBUG, "JBIG2ImageDecoderPlugin: MMR image data");
  829. // 6.2.6 Decoding using MMR coding
  830. auto buffer = TRY(CCITT::decode_ccitt_group4(data, inputs.region_width, inputs.region_height));
  831. auto result = TRY(BitBuffer::create(inputs.region_width, inputs.region_height));
  832. size_t bytes_per_row = ceil_div(inputs.region_width, 8);
  833. if (buffer.size() != bytes_per_row * inputs.region_height)
  834. return Error::from_string_literal("JBIG2ImageDecoderPlugin: Decoded MMR data has wrong size");
  835. // FIXME: Could probably just copy the ByteBuffer directly into the BitBuffer's internal ByteBuffer instead.
  836. for (size_t y = 0; y < inputs.region_height; ++y) {
  837. for (size_t x = 0; x < inputs.region_width; ++x) {
  838. bool bit = buffer[y * bytes_per_row + x / 8] & (1 << (7 - x % 8));
  839. result->set_bit(x, y, bit);
  840. }
  841. }
  842. return result;
  843. }
  844. // 6.2.5 Decoding using a template and arithmetic coding
  845. if (inputs.is_extended_reference_template_used)
  846. return Error::from_string_literal("JBIG2ImageDecoderPlugin: Cannot decode EXTTEMPLATE yet");
  847. int number_of_adaptive_template_pixels = inputs.gb_template == 0 ? 4 : 1;
  848. for (int i = 0; i < number_of_adaptive_template_pixels; ++i)
  849. TRY(check_valid_adaptive_template_pixel(inputs.adaptive_template_pixels[i]));
  850. if (inputs.skip_pattern.has_value())
  851. return Error::from_string_literal("JBIG2ImageDecoderPlugin: Cannot decode USESKIP yet");
  852. auto result = TRY(BitBuffer::create(inputs.region_width, inputs.region_height));
  853. static constexpr auto get_pixel = [](NonnullOwnPtr<BitBuffer> const& buffer, int x, int y) -> bool {
  854. if (x < 0 || x >= (int)buffer->width() || y < 0)
  855. return false;
  856. return buffer->get_bit(x, y);
  857. };
  858. // Figure 3(a) – Template when GBTEMPLATE = 0 and EXTTEMPLATE = 0,
  859. constexpr auto compute_context_0 = [](NonnullOwnPtr<BitBuffer> const& buffer, ReadonlySpan<AdaptiveTemplatePixel> adaptive_pixels, int x, int y) -> u16 {
  860. u16 result = 0;
  861. for (int i = 0; i < 4; ++i)
  862. result = (result << 1) | (u16)get_pixel(buffer, x + adaptive_pixels[i].x, y + adaptive_pixels[i].y);
  863. for (int i = 0; i < 3; ++i)
  864. result = (result << 1) | (u16)get_pixel(buffer, x - 1 + i, y - 2);
  865. for (int i = 0; i < 5; ++i)
  866. result = (result << 1) | (u16)get_pixel(buffer, x - 2 + i, y - 1);
  867. for (int i = 0; i < 4; ++i)
  868. result = (result << 1) | (u16)get_pixel(buffer, x - 4 + i, y);
  869. return result;
  870. };
  871. // Figure 4 – Template when GBTEMPLATE = 1
  872. auto compute_context_1 = [](NonnullOwnPtr<BitBuffer> const& buffer, ReadonlySpan<AdaptiveTemplatePixel> adaptive_pixels, int x, int y) -> u16 {
  873. u16 result = 0;
  874. result = (result << 1) | (u16)get_pixel(buffer, x + adaptive_pixels[0].x, y + adaptive_pixels[0].y);
  875. for (int i = 0; i < 4; ++i)
  876. result = (result << 1) | (u16)get_pixel(buffer, x - 1 + i, y - 2);
  877. for (int i = 0; i < 5; ++i)
  878. result = (result << 1) | (u16)get_pixel(buffer, x - 2 + i, y - 1);
  879. for (int i = 0; i < 3; ++i)
  880. result = (result << 1) | (u16)get_pixel(buffer, x - 3 + i, y);
  881. return result;
  882. };
  883. // Figure 5 – Template when GBTEMPLATE = 2
  884. auto compute_context_2 = [](NonnullOwnPtr<BitBuffer> const& buffer, ReadonlySpan<AdaptiveTemplatePixel> adaptive_pixels, int x, int y) -> u16 {
  885. u16 result = 0;
  886. result = (result << 1) | (u16)get_pixel(buffer, x + adaptive_pixels[0].x, y + adaptive_pixels[0].y);
  887. for (int i = 0; i < 3; ++i)
  888. result = (result << 1) | (u16)get_pixel(buffer, x - 1 + i, y - 2);
  889. for (int i = 0; i < 4; ++i)
  890. result = (result << 1) | (u16)get_pixel(buffer, x - 2 + i, y - 1);
  891. for (int i = 0; i < 2; ++i)
  892. result = (result << 1) | (u16)get_pixel(buffer, x - 2 + i, y);
  893. return result;
  894. };
  895. // Figure 6 – Template when GBTEMPLATE = 3
  896. auto compute_context_3 = [](NonnullOwnPtr<BitBuffer> const& buffer, ReadonlySpan<AdaptiveTemplatePixel> adaptive_pixels, int x, int y) -> u16 {
  897. u16 result = 0;
  898. result = (result << 1) | (u16)get_pixel(buffer, x + adaptive_pixels[0].x, y + adaptive_pixels[0].y);
  899. for (int i = 0; i < 5; ++i)
  900. result = (result << 1) | (u16)get_pixel(buffer, x - 3 + i, y - 1);
  901. for (int i = 0; i < 4; ++i)
  902. result = (result << 1) | (u16)get_pixel(buffer, x - 4 + i, y);
  903. return result;
  904. };
  905. u16 (*compute_context)(NonnullOwnPtr<BitBuffer> const&, ReadonlySpan<AdaptiveTemplatePixel>, int, int);
  906. if (inputs.gb_template == 0)
  907. compute_context = compute_context_0;
  908. else if (inputs.gb_template == 1)
  909. compute_context = compute_context_1;
  910. else if (inputs.gb_template == 2)
  911. compute_context = compute_context_2;
  912. else {
  913. VERIFY(inputs.gb_template == 3);
  914. compute_context = compute_context_3;
  915. }
  916. // "The values of the pixels in this neighbourhood define a context. Each context has its own adaptive probability estimate
  917. // used by the arithmetic coder (see Annex E)."
  918. // "* Decode the current pixel by invoking the arithmetic entropy decoding procedure, with CX set to the value formed by
  919. // concatenating the label "GB" and the 10-16 pixel values gathered in CONTEXT."
  920. // Implementor's note: What this is supposed to mean is that we have a bunch of independent contexts, and we pick the
  921. // context for the current pixel based on pixel values in the neighborhood. The "GB" part just means this context is
  922. // independent from other contexts in the spec. They are passed in to this function.
  923. // Figure 8 – Reused context for coding the SLTP value when GBTEMPLATE is 0
  924. constexpr u16 sltp_context_for_template_0 = 0b10011'0110010'0101;
  925. // Figure 9 – Reused context for coding the SLTP value when GBTEMPLATE is 1
  926. constexpr u16 sltp_context_for_template_1 = 0b0011'110010'101;
  927. // Figure 10 – Reused context for coding the SLTP value when GBTEMPLATE is 2
  928. constexpr u16 sltp_context_for_template_2 = 0b001'11001'01;
  929. // Figure 11 – Reused context for coding the SLTP value when GBTEMPLATE is 3
  930. constexpr u16 sltp_context_for_template_3 = 0b011001'0101;
  931. u16 sltp_context = [](u8 gb_template) {
  932. if (gb_template == 0)
  933. return sltp_context_for_template_0;
  934. if (gb_template == 1)
  935. return sltp_context_for_template_1;
  936. if (gb_template == 2)
  937. return sltp_context_for_template_2;
  938. VERIFY(gb_template == 3);
  939. return sltp_context_for_template_3;
  940. }(inputs.gb_template);
  941. // 6.2.5.7 Decoding the bitmap
  942. JBIG2::ArithmeticDecoder& decoder = *inputs.arithmetic_decoder;
  943. bool ltp = false; // "LTP" in spec. "Line (uses) Typical Prediction" maybe?
  944. for (size_t y = 0; y < inputs.region_height; ++y) {
  945. if (inputs.is_typical_prediction_used) {
  946. // "SLTP" in spec. "Swap LTP" or "Switch LTP" maybe?
  947. bool sltp = decoder.get_next_bit(contexts[sltp_context]);
  948. ltp = ltp ^ sltp;
  949. if (ltp) {
  950. for (size_t x = 0; x < inputs.region_width; ++x)
  951. result->set_bit(x, y, get_pixel(result, (int)x, (int)y - 1));
  952. continue;
  953. }
  954. }
  955. for (size_t x = 0; x < inputs.region_width; ++x) {
  956. u16 context = compute_context(result, inputs.adaptive_template_pixels, x, y);
  957. bool bit = decoder.get_next_bit(contexts[context]);
  958. result->set_bit(x, y, bit);
  959. }
  960. }
  961. return result;
  962. }
  963. // 6.3.2 Input parameters
  964. // Table 6 – Parameters for the generic refinement region decoding procedure
  965. struct GenericRefinementRegionDecodingInputParameters {
  966. u32 region_width { 0 }; // "GRW" in spec.
  967. u32 region_height { 0 }; // "GRH" in spec.
  968. u8 gr_template { 0 }; // "GRTEMPLATE" in spec.
  969. BitBuffer const* reference_bitmap { nullptr }; // "GRREFERENCE" in spec.
  970. i32 reference_x_offset { 0 }; // "GRREFERENCEDX" in spec.
  971. i32 reference_y_offset { 0 }; // "GRREFERENCEDY" in spec.
  972. bool is_typical_prediction_used { false }; // "TPGDON" in spec.
  973. Array<AdaptiveTemplatePixel, 2> adaptive_template_pixels; // "GRATX" / "GRATY" in spec.
  974. };
  975. // 6.3 Generic Refinement Region Decoding Procedure
  976. static ErrorOr<NonnullOwnPtr<BitBuffer>> generic_refinement_region_decoding_procedure(GenericRefinementRegionDecodingInputParameters& inputs, JBIG2::ArithmeticDecoder& decoder, Vector<JBIG2::ArithmeticDecoder::Context>& contexts)
  977. {
  978. VERIFY(inputs.gr_template == 0 || inputs.gr_template == 1);
  979. if (inputs.is_typical_prediction_used)
  980. return Error::from_string_literal("JBIG2ImageDecoderPlugin: Cannot decode typical prediction in generic refinement regions yet");
  981. if (inputs.gr_template == 0) {
  982. TRY(check_valid_adaptive_template_pixel(inputs.adaptive_template_pixels[0]));
  983. // inputs.adaptive_template_pixels[1] is allowed to contain any value.
  984. }
  985. // GRTEMPLATE 1 never uses adaptive pixels.
  986. // 6.3.5.3 Fixed templates and adaptive templates
  987. static constexpr auto get_pixel = [](BitBuffer const& buffer, int x, int y) -> bool {
  988. if (x < 0 || x >= (int)buffer.width() || y < 0 || y >= (int)buffer.height())
  989. return false;
  990. return buffer.get_bit(x, y);
  991. };
  992. // Figure 12 – 13-pixel refinement template showing the AT pixels at their nominal locations
  993. constexpr auto compute_context_0 = [](ReadonlySpan<AdaptiveTemplatePixel> adaptive_pixels, BitBuffer const& reference, int reference_x, int reference_y, BitBuffer const& buffer, int x, int y) -> u16 {
  994. u16 result = 0;
  995. for (int dy = -1; dy <= 1; ++dy) {
  996. for (int dx = -1; dx <= 1; ++dx) {
  997. if (dy == -1 && dx == -1)
  998. result = (result << 1) | (u16)get_pixel(reference, reference_x + adaptive_pixels[1].x, reference_y + adaptive_pixels[1].y);
  999. else
  1000. result = (result << 1) | (u16)get_pixel(reference, reference_x + dx, reference_y + dy);
  1001. }
  1002. }
  1003. result = (result << 1) | (u16)get_pixel(buffer, x + adaptive_pixels[0].x, y + adaptive_pixels[0].y);
  1004. for (int i = 0; i < 2; ++i)
  1005. result = (result << 1) | (u16)get_pixel(buffer, x + i, y - 1);
  1006. result = (result << 1) | (u16)get_pixel(buffer, x - 1, y);
  1007. return result;
  1008. };
  1009. // Figure 13 – 10-pixel refinement template
  1010. constexpr auto compute_context_1 = [](ReadonlySpan<AdaptiveTemplatePixel>, BitBuffer const& reference, int reference_x, int reference_y, BitBuffer const& buffer, int x, int y) -> u16 {
  1011. u16 result = 0;
  1012. for (int dy = -1; dy <= 1; ++dy) {
  1013. for (int dx = -1; dx <= 1; ++dx) {
  1014. if ((dy == -1 && (dx == -1 || dx == 1)) || (dy == 1 && dx == -1))
  1015. continue;
  1016. result = (result << 1) | (u16)get_pixel(reference, reference_x + dx, reference_y + dy);
  1017. }
  1018. }
  1019. for (int i = 0; i < 3; ++i)
  1020. result = (result << 1) | (u16)get_pixel(buffer, x - 1 + i, y - 1);
  1021. result = (result << 1) | (u16)get_pixel(buffer, x - 1, y);
  1022. return result;
  1023. };
  1024. auto compute_context = inputs.gr_template == 0 ? compute_context_0 : compute_context_1;
  1025. // 6.3.5.6 Decoding the refinement bitmap
  1026. auto result = TRY(BitBuffer::create(inputs.region_width, inputs.region_height));
  1027. for (size_t y = 0; y < result->height(); ++y) {
  1028. for (size_t x = 0; x < result->width(); ++x) {
  1029. u16 context = compute_context(inputs.adaptive_template_pixels, *inputs.reference_bitmap, x - inputs.reference_x_offset, y - inputs.reference_y_offset, *result, x, y);
  1030. bool bit = decoder.get_next_bit(contexts[context]);
  1031. result->set_bit(x, y, bit);
  1032. }
  1033. }
  1034. return result;
  1035. }
  1036. // 6.4.2 Input parameters
  1037. // Table 9 – Parameters for the text region decoding procedure
  1038. struct TextRegionDecodingInputParameters {
  1039. bool uses_huffman_encoding { false }; // "SBHUFF" in spec.
  1040. bool uses_refinement_coding { false }; // "SBREFINE" in spec.
  1041. u32 region_width { 0 }; // "SBW" in spec.
  1042. u32 region_height { 0 }; // "SBH" in spec.
  1043. u32 number_of_instances { 0 }; // "SBNUMINSTANCES" in spec.
  1044. u32 size_of_symbol_instance_strips { 0 }; // "SBSTRIPS" in spec.
  1045. // "SBNUMSYMS" is `symbols.size()` below.
  1046. // FIXME: SBSYMCODES
  1047. u32 id_symbol_code_length { 0 }; // "SBSYMCODELEN" in spec.
  1048. Vector<NonnullRefPtr<Symbol>> symbols; // "SBNUMSYMS" / "SBSYMS" in spec.
  1049. u8 default_pixel { 0 }; // "SBDEFPIXEL" in spec.
  1050. CombinationOperator operator_ { CombinationOperator::Or }; // "SBCOMBOP" in spec.
  1051. bool is_transposed { false }; // "TRANSPOSED" in spec.
  1052. enum class Corner {
  1053. BottomLeft = 0,
  1054. TopLeft = 1,
  1055. BottomRight = 2,
  1056. TopRight = 3,
  1057. };
  1058. Corner reference_corner { Corner::TopLeft }; // "REFCORNER" in spec.
  1059. i8 delta_s_offset { 0 }; // "SBDSOFFSET" in spec.
  1060. // FIXME: SBHUFFFS, SBHUFFFDS, SBHUFFDT, SBHUFFRDW, SBHUFFRDH, SBHUFFRDX, SBHUFFRDY, SBHUFFRSIZE
  1061. u8 refinement_template { 0 }; // "SBRTEMPLATE" in spec.
  1062. Array<AdaptiveTemplatePixel, 2> refinement_adaptive_template_pixels; // "SBRATX" / "SBRATY" in spec.
  1063. // FIXME: COLEXTFLAG, SBCOLS
  1064. };
  1065. // 6.4 Text Region Decoding Procedure
  1066. static ErrorOr<NonnullOwnPtr<BitBuffer>> text_region_decoding_procedure(TextRegionDecodingInputParameters const& inputs, ReadonlyBytes data)
  1067. {
  1068. if (inputs.uses_huffman_encoding)
  1069. return Error::from_string_literal("JBIG2ImageDecoderPlugin: Cannot decode huffman text regions yet");
  1070. auto decoder = TRY(JBIG2::ArithmeticDecoder::initialize(data));
  1071. // 6.4.6 Strip delta T
  1072. // "If SBHUFF is 1, decode a value using the Huffman table specified by SBHUFFDT and multiply the resulting value by SBSTRIPS.
  1073. // If SBHUFF is 0, decode a value using the IADT integer arithmetic decoding procedure (see Annex A) and multiply the resulting value by SBSTRIPS."
  1074. // FIXME: Implement support for SBHUFF = 1.
  1075. JBIG2::ArithmeticIntegerDecoder delta_t_integer_decoder(decoder);
  1076. auto read_delta_t = [&]() -> ErrorOr<i32> {
  1077. return TRY(delta_t_integer_decoder.decode_non_oob()) * inputs.size_of_symbol_instance_strips;
  1078. };
  1079. // 6.4.7 First symbol instance S coordinate
  1080. // "If SBHUFF is 1, decode a value using the Huffman table specified by SBHUFFFS.
  1081. // If SBHUFF is 0, decode a value using the IAFS integer arithmetic decoding procedure (see Annex A)."
  1082. // FIXME: Implement support for SBHUFF = 1.
  1083. JBIG2::ArithmeticIntegerDecoder first_s_integer_decoder(decoder);
  1084. auto read_first_s = [&]() -> ErrorOr<i32> {
  1085. return first_s_integer_decoder.decode_non_oob();
  1086. };
  1087. // 6.4.8 Subsequent symbol instance S coordinate
  1088. // "If SBHUFF is 1, decode a value using the Huffman table specified by SBHUFFDS.
  1089. // If SBHUFF is 0, decode a value using the IADS integer arithmetic decoding procedure (see Annex A).
  1090. // In either case it is possible that the result of this decoding is the out-of-band value OOB.""
  1091. // FIXME: Implement support for SBHUFF = 1.
  1092. JBIG2::ArithmeticIntegerDecoder subsequent_s_integer_decoder(decoder);
  1093. auto read_subsequent_s = [&]() -> Optional<i32> {
  1094. return subsequent_s_integer_decoder.decode();
  1095. };
  1096. // 6.4.9 Symbol instance T coordinate
  1097. // "If SBSTRIPS == 1, then the value decoded is always zero. Otherwise:
  1098. // • If SBHUFF is 1, decode a value by reading ceil(log2(SBSTRIPS)) bits directly from the bitstream.
  1099. // • If SBHUFF is 0, decode a value using the IAIT integer arithmetic decoding procedure (see Annex A)."
  1100. // FIXME: Implement support for SBHUFF = 1.
  1101. JBIG2::ArithmeticIntegerDecoder instance_t_integer_decoder(decoder);
  1102. auto read_instance_t = [&]() -> ErrorOr<i32> {
  1103. if (inputs.size_of_symbol_instance_strips == 1)
  1104. return 0;
  1105. return instance_t_integer_decoder.decode_non_oob();
  1106. };
  1107. // 6.4.10 Symbol instance symbol ID
  1108. // "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
  1109. // SBSYMCODES. The resulting value, which is IDI, is the index of the entry in SBSYMCODES that is read.
  1110. // If SBHUFF is 0, decode a value using the IAID integer arithmetic decoding procedure (see Annex A). Set IDI to the
  1111. // resulting value.""
  1112. // FIXME: Implement support for SBHUFF = 1.
  1113. JBIG2::ArithmeticIntegerIDDecoder id_decoder(decoder, inputs.id_symbol_code_length);
  1114. // 6.4.11.1 Symbol instance refinement delta width
  1115. // FIXME: Implement support for SBHUFF = 1.
  1116. JBIG2::ArithmeticIntegerDecoder refinement_delta_width_decoder(decoder);
  1117. auto read_refinement_delta_width = [&]() -> ErrorOr<i32> {
  1118. return refinement_delta_width_decoder.decode_non_oob();
  1119. };
  1120. // 6.4.11.2 Symbol instance refinement delta width
  1121. // FIXME: Implement support for SBHUFF = 1.
  1122. JBIG2::ArithmeticIntegerDecoder refinement_delta_height_decoder(decoder);
  1123. auto read_refinement_delta_height = [&]() -> ErrorOr<i32> {
  1124. return refinement_delta_height_decoder.decode_non_oob();
  1125. };
  1126. // 6.4.11.3 Symbol instance refinement X offset
  1127. // FIXME: Implement support for SBHUFF = 1.
  1128. JBIG2::ArithmeticIntegerDecoder refinement_x_offset_decoder(decoder);
  1129. auto read_refinement_x_offset = [&]() -> ErrorOr<i32> {
  1130. return refinement_x_offset_decoder.decode_non_oob();
  1131. };
  1132. // 6.4.11.4 Symbol instance refinement Y offset
  1133. // FIXME: Implement support for SBHUFF = 1.
  1134. JBIG2::ArithmeticIntegerDecoder refinement_y_offset_decoder(decoder);
  1135. auto read_refinement_y_offset = [&]() -> ErrorOr<i32> {
  1136. return refinement_y_offset_decoder.decode_non_oob();
  1137. };
  1138. // 6.4.11 Symbol instance bitmap
  1139. JBIG2::ArithmeticIntegerDecoder has_refinement_image_decoder(decoder);
  1140. Vector<JBIG2::ArithmeticDecoder::Context> refinement_contexts;
  1141. if (inputs.uses_refinement_coding)
  1142. refinement_contexts.resize(1 << (inputs.refinement_template == 0 ? 13 : 10));
  1143. OwnPtr<BitBuffer> refinement_result;
  1144. auto read_bitmap = [&](u32 id) -> ErrorOr<BitBuffer const*> {
  1145. if (id >= inputs.symbols.size())
  1146. return Error::from_string_literal("JBIG2ImageDecoderPlugin: Symbol ID out of range");
  1147. auto const& symbol = inputs.symbols[id]->bitmap();
  1148. bool has_refinement_image = false; // "R_I" in spec.
  1149. if (inputs.uses_refinement_coding) {
  1150. // "• If SBHUFF is 1, then read one bit and set RI to the value of that bit.
  1151. // • If SBHUFF is 0, then decode one bit using the IARI integer arithmetic decoding procedure and set RI to the value of that bit."
  1152. // FIXME: Implement support for SBHUFF = 1.
  1153. has_refinement_image = TRY(has_refinement_image_decoder.decode_non_oob());
  1154. }
  1155. if (!has_refinement_image)
  1156. return &symbol;
  1157. auto refinement_delta_width = TRY(read_refinement_delta_width());
  1158. auto refinement_delta_height = TRY(read_refinement_delta_height());
  1159. auto refinement_x_offset = TRY(read_refinement_x_offset());
  1160. auto refinement_y_offset = TRY(read_refinement_y_offset());
  1161. // FIXME: This is missing some steps needed for the SBHUFF = 1 case.
  1162. 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);
  1163. // Table 12 – Parameters used to decode a symbol instance's bitmap using refinement
  1164. GenericRefinementRegionDecodingInputParameters refinement_inputs;
  1165. refinement_inputs.region_width = symbol.width() + refinement_delta_width;
  1166. refinement_inputs.region_height = symbol.height() + refinement_delta_height;
  1167. refinement_inputs.gr_template = inputs.refinement_template;
  1168. refinement_inputs.reference_bitmap = &symbol;
  1169. refinement_inputs.reference_x_offset = refinement_delta_width / 2 + refinement_x_offset;
  1170. refinement_inputs.reference_y_offset = refinement_delta_height / 2 + refinement_y_offset;
  1171. refinement_inputs.is_typical_prediction_used = false;
  1172. refinement_inputs.adaptive_template_pixels = inputs.refinement_adaptive_template_pixels;
  1173. refinement_result = TRY(generic_refinement_region_decoding_procedure(refinement_inputs, decoder, refinement_contexts));
  1174. return refinement_result.ptr();
  1175. };
  1176. // 6.4.5 Decoding the text region
  1177. // "1) Fill a bitmap SBREG, of the size given by SBW and SBH, with the SBDEFPIXEL value."
  1178. auto result = TRY(BitBuffer::create(inputs.region_width, inputs.region_height));
  1179. if (inputs.default_pixel != 0)
  1180. return Error::from_string_literal("JBIG2ImageDecoderPlugin: Cannot handle SBDEFPIXEL not equal to 0 yet");
  1181. result->fill(inputs.default_pixel != 0);
  1182. // "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.
  1183. // Assign the value 0 to FIRSTS. Assign the value 0 to NINSTANCES."
  1184. i32 strip_t = -TRY(read_delta_t());
  1185. i32 first_s = 0;
  1186. u32 n_instances = 0;
  1187. // "3) If COLEXTFLAG is 1, decode the colour section as described in 6.4.12."
  1188. // FIXME: Implement support for colors one day.
  1189. // "4) Decode each strip as follows:
  1190. // a) If NINSTANCES is equal to SBNUMINSTANCES then there are no more strips to decode,
  1191. // and the process of decoding the text region is complete; proceed to step 4)."
  1192. // Implementor's note. The spec means "proceed to step 5)" at the end of 4a).
  1193. while (n_instances < inputs.number_of_instances) {
  1194. // "b) Decode the strip's delta T value as described in 6.4.6. Let DT be the decoded value. Set:
  1195. // STRIPT = STRIPT + DT"
  1196. i32 delta_t = TRY(read_delta_t());
  1197. strip_t += delta_t;
  1198. i32 cur_s;
  1199. bool is_first_symbol = true;
  1200. while (true) {
  1201. // "c) Decode each symbol instance in the strip as follows:
  1202. // i) If the current symbol instance is the first symbol instance in the strip, then decode the first
  1203. // symbol instance's S coordinate as described in 6.4.7. Let DFS be the decoded value. Set:
  1204. // FIRSTS = FIRSTS + DFS
  1205. // CURS = FIRSTS
  1206. // ii) Otherwise, if the current symbol instance is not the first symbol instance in the strip, decode
  1207. // the symbol instance's S coordinate as described in 6.4.8. If the result of this decoding is OOB
  1208. // then the last symbol instance of the strip has been decoded; proceed to step 3 d). Otherwise, let
  1209. // IDS be the decoded value. Set:
  1210. // CURS = CURS + IDS + SBDSOFFSET"
  1211. // Implementor's note: The spec means "proceed to step 4 d)" in 4c ii).
  1212. if (is_first_symbol) {
  1213. i32 delta_first_s = TRY(read_first_s());
  1214. first_s += delta_first_s;
  1215. cur_s = first_s;
  1216. is_first_symbol = false;
  1217. } else {
  1218. auto subsequent_s = read_subsequent_s();
  1219. if (!subsequent_s.has_value())
  1220. break;
  1221. i32 instance_delta_s = subsequent_s.value();
  1222. cur_s += instance_delta_s + inputs.delta_s_offset;
  1223. }
  1224. // "iii) Decode the symbol instance's T coordinate as described in 6.4.9. Let CURT be the decoded value. Set:
  1225. // TI = STRIPT + CURT"
  1226. i32 cur_t = TRY(read_instance_t());
  1227. i32 t_instance = strip_t + cur_t;
  1228. // "iv) Decode the symbol instance's symbol ID as described in 6.4.10. Let IDI be the decoded value."
  1229. u32 id = id_decoder.decode();
  1230. // "v) Determine the symbol instance's bitmap IBI as described in 6.4.11. The width and height of this
  1231. // bitmap shall be denoted as WI and HI respectively."
  1232. auto const& symbol = *TRY(read_bitmap(id));
  1233. // "vi) Update CURS as follows:
  1234. // • If TRANSPOSED is 0, and REFCORNER is TOPRIGHT or BOTTOMRIGHT, set:
  1235. // CURS = CURS + WI – 1
  1236. // • If TRANSPOSED is 1, and REFCORNER is BOTTOMLEFT or BOTTOMRIGHT, set:
  1237. // CURS = CURS + HI – 1
  1238. // • Otherwise, do not change CURS in this step."
  1239. using enum TextRegionDecodingInputParameters::Corner;
  1240. if (!inputs.is_transposed && (inputs.reference_corner == TopRight || inputs.reference_corner == BottomRight))
  1241. cur_s += symbol.width() - 1;
  1242. if (inputs.is_transposed && (inputs.reference_corner == BottomLeft || inputs.reference_corner == BottomRight))
  1243. cur_s += symbol.height() - 1;
  1244. // "vii) Set:
  1245. // SI = CURS"
  1246. auto s_instance = cur_s;
  1247. // "viii) Determine the location of the symbol instance bitmap with respect to SBREG as follows:
  1248. // • If TRANSPOSED is 0, then:
  1249. // – If REFCORNER is TOPLEFT then the top left pixel of the symbol instance bitmap
  1250. // IBI shall be placed at SBREG[SI, TI].
  1251. // – If REFCORNER is TOPRIGHT then the top right pixel of the symbol instance
  1252. // bitmap IBI shall be placed at SBREG[SI, TI].
  1253. // – If REFCORNER is BOTTOMLEFT then the bottom left pixel of the symbol
  1254. // instance bitmap IBI shall be placed at SBREG[SI, TI].
  1255. // – If REFCORNER is BOTTOMRIGHT then the bottom right pixel of the symbol
  1256. // instance bitmap IBI shall be placed at SBREG[SI, TI].
  1257. // • If TRANSPOSED is 1, then:
  1258. // – If REFCORNER is TOPLEFT then the top left pixel of the symbol instance bitmap
  1259. // IBI shall be placed at SBREG[TI, SI].
  1260. // – If REFCORNER is TOPRIGHT then the top right pixel of the symbol instance
  1261. // bitmap IBI shall be placed at SBREG[TI, SI].
  1262. // – If REFCORNER is BOTTOMLEFT then the bottom left pixel of the symbol
  1263. // instance bitmap IBI shall be placed at SBREG[TI, SI].
  1264. // – If REFCORNER is BOTTOMRIGHT then the bottom right pixel of the symbol
  1265. // instance bitmap IBI shall be placed at SBREG[TI, SI].
  1266. // If any part of IBI, when placed at this location, lies outside the bounds of SBREG, then ignore
  1267. // this part of IBI in step 3 c) ix)."
  1268. // Implementor's note: The spec means "ignore this part of IBI in step 3 c) x)" in 3c viii)'s last sentence.
  1269. if (inputs.is_transposed)
  1270. swap(s_instance, t_instance);
  1271. if (inputs.reference_corner == TopRight || inputs.reference_corner == BottomRight)
  1272. s_instance -= symbol.width() - 1;
  1273. if (inputs.reference_corner == BottomLeft || inputs.reference_corner == BottomRight)
  1274. t_instance -= symbol.height() - 1;
  1275. // "ix) If COLEXTFLAG is 1, set the colour specified by SBCOLS[SBFGCOLID[NINSTANCES]]
  1276. // to the foreground colour of the symbol instance bitmap IBI."
  1277. // FIXME: Implement support for colors one day.
  1278. // "x) Draw IBI into SBREG. Combine each pixel of IBI with the current value of the corresponding
  1279. // pixel in SBREG, using the combination operator specified by SBCOMBOP. Write the results
  1280. // of each combination into that pixel in SBREG."
  1281. dbgln_if(JBIG2_DEBUG, "combining symbol {} ({}x{}) at ({}, {}) with operator {}", id, symbol.width(), symbol.height(), s_instance, t_instance, (int)inputs.operator_);
  1282. composite_bitbuffer(*result, symbol, { s_instance, t_instance }, inputs.operator_);
  1283. // "xi) Update CURS as follows:
  1284. // • If TRANSPOSED is 0, and REFCORNER is TOPLEFT or BOTTOMLEFT, set:
  1285. // CURS = CURS + WI – 1
  1286. // • If TRANSPOSED is 1, and REFCORNER is TOPLEFT or TOPRIGHT, set:
  1287. // CURS = CURS + HI – 1
  1288. // • Otherwise, do not change CURS in this step."
  1289. if (!inputs.is_transposed && (inputs.reference_corner == TopLeft || inputs.reference_corner == BottomLeft))
  1290. cur_s += symbol.width() - 1;
  1291. if (inputs.is_transposed && (inputs.reference_corner == TopLeft || inputs.reference_corner == TopRight))
  1292. cur_s += symbol.height() - 1;
  1293. // "xii) Set:
  1294. // NINSTANCES = NINSTANCES + 1"
  1295. ++n_instances;
  1296. }
  1297. // "d) When the strip has been completely decoded, decode the next strip."
  1298. // (Done in the next loop iteration.)
  1299. }
  1300. // "5) After all the strips have been decoded, the current contents of SBREG are the results that shall be
  1301. // obtained by every decoder, whether it performs this exact sequence of steps or not."
  1302. return result;
  1303. }
  1304. // 6.5.2 Input parameters
  1305. // Table 13 – Parameters for the symbol dictionary decoding procedure
  1306. struct SymbolDictionaryDecodingInputParameters {
  1307. bool uses_huffman_encoding { false }; // "SDHUFF" in spec.
  1308. bool uses_refinement_or_aggregate_coding { false }; // "SDREFAGG" in spec.
  1309. Vector<NonnullRefPtr<Symbol>> input_symbols; // "SDNUMINSYMS", "SDINSYMS" in spec.
  1310. u32 number_of_new_symbols { 0 }; // "SDNUMNEWSYMS" in spec.
  1311. u32 number_of_exported_symbols { 0 }; // "SDNUMEXSYMS" in spec.
  1312. // FIXME: SDHUFFDH, SDHUFFDW, SDHUFFBMSIZE, SDHUFFAGGINST
  1313. u8 symbol_template { 0 }; // "SDTEMPLATE" in spec.
  1314. Array<AdaptiveTemplatePixel, 4> adaptive_template_pixels; // "SDATX" / "SDATY" in spec.
  1315. u8 refinement_template { 0 }; // "SDRTEMPLATE" in spec;
  1316. Array<AdaptiveTemplatePixel, 2> refinement_adaptive_template_pixels; // "SDRATX" / "SDRATY" in spec.
  1317. };
  1318. // 6.5 Symbol Dictionary Decoding Procedure
  1319. static ErrorOr<Vector<NonnullRefPtr<Symbol>>> symbol_dictionary_decoding_procedure(SymbolDictionaryDecodingInputParameters const& inputs, ReadonlyBytes data)
  1320. {
  1321. if (inputs.uses_huffman_encoding)
  1322. return Error::from_string_literal("JBIG2ImageDecoderPlugin: Cannot decode huffman symbol dictionaries yet");
  1323. auto decoder = TRY(JBIG2::ArithmeticDecoder::initialize(data));
  1324. Vector<JBIG2::ArithmeticDecoder::Context> contexts;
  1325. contexts.resize(1 << number_of_context_bits_for_template(inputs.symbol_template));
  1326. // 6.5.6 Height class delta height
  1327. // "If SDHUFF is 1, decode a value using the Huffman table specified by SDHUFFDH.
  1328. // If SDHUFF is 0, decode a value using the IADH integer arithmetic decoding procedure (see Annex A)."
  1329. // FIXME: Implement support for SDHUFF = 1.
  1330. JBIG2::ArithmeticIntegerDecoder delta_height_integer_decoder(decoder);
  1331. auto read_delta_height = [&]() -> ErrorOr<i32> {
  1332. return delta_height_integer_decoder.decode_non_oob();
  1333. };
  1334. // 6.5.7 Delta width
  1335. // "If SDHUFF is 1, decode a value using the Huffman table specified by SDHUFFDW.
  1336. // If SDHUFF is 0, decode a value using the IADW integer arithmetic decoding procedure (see Annex A).
  1337. // In either case it is possible that the result of this decoding is the out-of-band value OOB."
  1338. // FIXME: Implement support for SDHUFF = 1.
  1339. JBIG2::ArithmeticIntegerDecoder delta_width_integer_decoder(decoder);
  1340. auto read_delta_width = [&]() -> Optional<i32> {
  1341. return delta_width_integer_decoder.decode();
  1342. };
  1343. // 6.5.8 Symbol bitmap
  1344. // "This field is only present if SDHUFF = 0 or SDREFAGG = 1. This field takes one of two forms; SDREFAGG
  1345. // determines which form is used."
  1346. // 6.5.8.2.1 Number of symbol instances in aggregation
  1347. // If SDHUFF is 1, decode a value using the Huffman table specified by SDHUFFAGGINST.
  1348. // If SDHUFF is 0, decode a value using the IAAI integer arithmetic decoding procedure (see Annex A).
  1349. // FIXME: Implement support for SDHUFF = 1.
  1350. Optional<JBIG2::ArithmeticIntegerDecoder> number_of_symbol_instances_decoder;
  1351. auto read_number_of_symbol_instances = [&]() -> ErrorOr<i32> {
  1352. if (!number_of_symbol_instances_decoder.has_value())
  1353. number_of_symbol_instances_decoder = JBIG2::ArithmeticIntegerDecoder(decoder);
  1354. return number_of_symbol_instances_decoder->decode_non_oob();
  1355. };
  1356. // 6.5.8.1 Direct-coded symbol bitmap
  1357. Optional<JBIG2::ArithmeticIntegerIDDecoder> id_decoder;
  1358. Optional<JBIG2::ArithmeticIntegerDecoder> refinement_x_offset_decoder;
  1359. Optional<JBIG2::ArithmeticIntegerDecoder> refinement_y_offset_decoder;
  1360. // FIXME: When we implement REFAGGNINST > 1 support, do these need to be shared with
  1361. // text_region_decoding_procedure() then?
  1362. Vector<JBIG2::ArithmeticDecoder::Context> refinement_contexts;
  1363. // This belongs in 6.5.5 1) below, but also needs to be captured by read_bitmap here.
  1364. Vector<NonnullRefPtr<Symbol>> new_symbols;
  1365. auto read_symbol_bitmap = [&](u32 width, u32 height) -> ErrorOr<NonnullOwnPtr<BitBuffer>> {
  1366. // "If SDREFAGG is 0, then decode the symbol's bitmap using a generic region decoding procedure as described in 6.2.
  1367. // Set the parameters to this decoding procedure as shown in Table 16."
  1368. if (!inputs.uses_refinement_or_aggregate_coding) {
  1369. // Table 16 – Parameters used to decode a symbol's bitmap using generic bitmap decoding
  1370. GenericRegionDecodingInputParameters generic_inputs;
  1371. generic_inputs.is_modified_modified_read = false;
  1372. generic_inputs.region_width = width;
  1373. generic_inputs.region_height = height;
  1374. generic_inputs.gb_template = inputs.symbol_template;
  1375. generic_inputs.is_extended_reference_template_used = false; // Missing from spec in table 16.
  1376. for (int i = 0; i < 4; ++i)
  1377. generic_inputs.adaptive_template_pixels[i] = inputs.adaptive_template_pixels[i];
  1378. generic_inputs.arithmetic_decoder = &decoder;
  1379. return generic_region_decoding_procedure(generic_inputs, {}, contexts);
  1380. }
  1381. // 6.5.8.2 Refinement/aggregate-coded symbol bitmap
  1382. // "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."
  1383. auto number_of_symbol_instances = TRY(read_number_of_symbol_instances()); // "REFAGGNINST" in spec.
  1384. dbgln_if(JBIG2_DEBUG, "Number of symbol instances: {}", number_of_symbol_instances);
  1385. if (number_of_symbol_instances > 1) {
  1386. // "2) If REFAGGNINST is greater than one, then decode the bitmap itself using a text region decoding procedure
  1387. // as described in 6.4. Set the parameters to this decoding procedure as shown in Table 17."
  1388. return Error::from_string_literal("JBIG2ImageDecoderPlugin: Cannot decode symbol bitmaps with more than one symbol instance yet");
  1389. }
  1390. // "3) If REFAGGNINST is equal to one, then decode the bitmap as described in 6.5.8.2.2."
  1391. // 6.5.8.2.3 Setting SBSYMCODES and SBSYMCODELEN
  1392. // FIXME: Implement support for SDHUFF = 1
  1393. u32 code_length = ceil(log2(inputs.input_symbols.size() + inputs.number_of_new_symbols));
  1394. // 6.5.8.2.2 Decoding a bitmap when REFAGGNINST = 1
  1395. // FIXME: This is missing some steps for the SDHUFF = 1 case.
  1396. if (number_of_symbol_instances != 1)
  1397. return Error::from_string_literal("JBIG2ImageDecoderPlugin: Unexpected number of symbol instances");
  1398. if (!id_decoder.has_value())
  1399. id_decoder = JBIG2::ArithmeticIntegerIDDecoder(decoder, code_length);
  1400. u32 symbol_id = id_decoder->decode();
  1401. if (!refinement_x_offset_decoder.has_value())
  1402. refinement_x_offset_decoder = JBIG2::ArithmeticIntegerDecoder(decoder);
  1403. i32 refinement_x_offset = TRY(refinement_x_offset_decoder->decode_non_oob());
  1404. if (!refinement_y_offset_decoder.has_value())
  1405. refinement_y_offset_decoder = JBIG2::ArithmeticIntegerDecoder(decoder);
  1406. i32 refinement_y_offset = TRY(refinement_y_offset_decoder->decode_non_oob());
  1407. if (symbol_id >= inputs.input_symbols.size() && symbol_id - inputs.input_symbols.size() >= new_symbols.size())
  1408. return Error::from_string_literal("JBIG2ImageDecoderPlugin: Refinement/aggregate symbol ID out of range");
  1409. auto IBO = (symbol_id < inputs.input_symbols.size()) ? inputs.input_symbols[symbol_id] : new_symbols[symbol_id - inputs.input_symbols.size()];
  1410. // Table 18 – Parameters used to decode a symbol's bitmap when REFAGGNINST = 1
  1411. GenericRefinementRegionDecodingInputParameters refinement_inputs;
  1412. refinement_inputs.region_width = width;
  1413. refinement_inputs.region_height = height;
  1414. refinement_inputs.gr_template = inputs.refinement_template;
  1415. refinement_inputs.reference_bitmap = &IBO->bitmap();
  1416. refinement_inputs.reference_x_offset = refinement_x_offset;
  1417. refinement_inputs.reference_y_offset = refinement_y_offset;
  1418. refinement_inputs.is_typical_prediction_used = false;
  1419. refinement_inputs.adaptive_template_pixels = inputs.refinement_adaptive_template_pixels;
  1420. if (refinement_contexts.is_empty())
  1421. refinement_contexts.resize(1 << (inputs.refinement_template == 0 ? 13 : 10));
  1422. return generic_refinement_region_decoding_procedure(refinement_inputs, decoder, refinement_contexts);
  1423. };
  1424. // 6.5.5 Decoding the symbol dictionary
  1425. // "1) Create an array SDNEWSYMS of bitmaps, having SDNUMNEWSYMS entries."
  1426. // Done above read_symbol_bitmap's definition.
  1427. // "2) If SDHUFF is 1 and SDREFAGG is 0, create an array SDNEWSYMWIDTHS of integers, having SDNUMNEWSYMS entries."
  1428. // FIXME: Implement support for SDHUFF = 1.
  1429. // "3) Set:
  1430. // HCHEIGHT = 0
  1431. // NSYMSDECODED = 0"
  1432. u32 height_class_height = 0;
  1433. u32 number_of_symbols_decoded = 0;
  1434. // "4) Decode each height class as follows:
  1435. // a) If NSYMSDECODED == SDNUMNEWSYMS then all the symbols in the dictionary have been decoded; proceed to step 5)."
  1436. while (number_of_symbols_decoded < inputs.number_of_new_symbols) {
  1437. // "b) Decode the height class delta height as described in 6.5.6. Let HCDH be the decoded value. Set:
  1438. // HCHEIGHT = HCEIGHT + HCDH
  1439. // SYMWIDTH = 0
  1440. // TOTWIDTH = 0
  1441. // HCFIRSTSYM = NSYMSDECODED"
  1442. i32 delta_height = TRY(read_delta_height());
  1443. height_class_height += delta_height;
  1444. u32 symbol_width = 0;
  1445. u32 total_width = 0;
  1446. u32 height_class_first_symbol = number_of_symbols_decoded;
  1447. // "c) Decode each symbol within the height class as follows:"
  1448. while (true) {
  1449. // "i) Decode the delta width for the symbol as described in 6.5.7."
  1450. auto opt_delta_width = read_delta_width();
  1451. // " If the result of this decoding is OOB then all the symbols in this height class have been decoded; proceed to step 4 d)."
  1452. if (!opt_delta_width.has_value())
  1453. break;
  1454. VERIFY(number_of_symbols_decoded < inputs.number_of_new_symbols);
  1455. // " Otherwise let DW be the decoded value and set:"
  1456. // SYMWIDTH = SYMWIDTH + DW
  1457. // TOTWIDTH = TOTWIDTH + SYMWIDTH"
  1458. i32 delta_width = opt_delta_width.value();
  1459. symbol_width += delta_width;
  1460. total_width += symbol_width;
  1461. // "ii) If SDHUFF is 0 or SDREFAGG is 1, then decode the symbol's bitmap as described in 6.5.8.
  1462. // Let BS be the decoded bitmap (this bitmap has width SYMWIDTH and height HCHEIGHT). Set:
  1463. // SDNEWSYMS[NSYMSDECODED] = BS"
  1464. // FIXME: Implement support for SDHUFF = 1.
  1465. // FIXME: Doing this eagerly is pretty wasteful. Decode on demand instead?
  1466. auto bitmap = TRY(read_symbol_bitmap(symbol_width, height_class_height));
  1467. new_symbols.append(Symbol::create(move(bitmap)));
  1468. // "iii) If SDHUFF is 1 and SDREFAGG is 0, then set:
  1469. // SDNEWSYMWIDTHS[NSYMSDECODED] = SYMWIDTH"
  1470. // FIXME: Implement support for SDHUFF = 1.
  1471. (void)total_width;
  1472. (void)height_class_first_symbol;
  1473. // "iv) Set:
  1474. // NSYMSDECODED = NSYMSDECODED + 1"
  1475. number_of_symbols_decoded++;
  1476. }
  1477. // "d) If SDHUFF is 1 and SDREFAGG is 0, [...long text elided...]"
  1478. // FIXME: Implement support for SDHUFF = 1.
  1479. }
  1480. // "5) Determine which symbol bitmaps are exported from this symbol dictionary, as described in 6.5.10. These
  1481. // bitmaps can be drawn from the symbols that are used as input to the symbol dictionary decoding
  1482. // procedure as well as the new symbols produced by the decoding procedure."
  1483. JBIG2::ArithmeticIntegerDecoder export_integer_decoder(decoder);
  1484. // 6.5.10 Exported symbols
  1485. Vector<bool> export_flags;
  1486. export_flags.resize(inputs.input_symbols.size() + inputs.number_of_new_symbols);
  1487. // "1) Set:
  1488. // EXINDEX = 0
  1489. // CUREXFLAG = 0"
  1490. u32 exported_index = 0;
  1491. bool current_export_flag = false;
  1492. do {
  1493. // "2) Decode a value using Table B.1 if SDHUFF is 1, or the IAEX integer arithmetic decoding procedure if
  1494. // SDHUFF is 0. Let EXRUNLENGTH be the decoded value."
  1495. // FIXME: Implement support for SDHUFF = 1.
  1496. i32 export_run_length = TRY(export_integer_decoder.decode_non_oob());
  1497. // "3) Set EXFLAGS[EXINDEX] through EXFLAGS[EXINDEX + EXRUNLENGTH – 1] to CUREXFLAG.
  1498. // If EXRUNLENGTH = 0, then this step does not change any values."
  1499. for (int i = 0; i < export_run_length; ++i)
  1500. export_flags[exported_index + i] = current_export_flag;
  1501. // "4) Set:
  1502. // EXINDEX = EXINDEX + EXRUNLENGTH
  1503. // CUREXFLAG = NOT(CUREXFLAG)"
  1504. exported_index += export_run_length;
  1505. current_export_flag = !current_export_flag;
  1506. // 5) Repeat steps 2) through 4) until EXINDEX == SDNUMINSYMS + SDNUMNEWSYMS.
  1507. } while (exported_index < inputs.input_symbols.size() + inputs.number_of_new_symbols);
  1508. // "6) The array EXFLAGS now contains 1 for each symbol that is exported from the dictionary, and 0 for each
  1509. // symbol that is not exported."
  1510. Vector<NonnullRefPtr<Symbol>> exported_symbols;
  1511. // "7) Set:
  1512. // I = 0
  1513. // J = 0
  1514. // 8) For each value of I from 0 to SDNUMINSYMS + SDNUMNEWSYMS – 1,"
  1515. for (size_t i = 0; i < inputs.input_symbols.size() + inputs.number_of_new_symbols; ++i) {
  1516. // "if EXFLAGS[I] == 1 then perform the following steps:"
  1517. if (!export_flags[i])
  1518. continue;
  1519. // "a) If I < SDNUMINSYMS then set:
  1520. // SDEXSYMS[J] = SDINSYMS[I]
  1521. // J = J + 1"
  1522. if (i < inputs.input_symbols.size())
  1523. exported_symbols.append(inputs.input_symbols[i]);
  1524. // "b) If I >= SDNUMINSYMS then set:
  1525. // SDEXSYMS[J] = SDNEWSYMS[I – SDNUMINSYMS]
  1526. // J = J + 1"
  1527. if (i >= inputs.input_symbols.size())
  1528. exported_symbols.append(move(new_symbols[i - inputs.input_symbols.size()]));
  1529. }
  1530. if (exported_symbols.size() != inputs.number_of_exported_symbols)
  1531. return Error::from_string_literal("JBIG2ImageDecoderPlugin: Unexpected number of exported symbols");
  1532. return exported_symbols;
  1533. }
  1534. // 6.6.2 Input parameters
  1535. struct HalftoneRegionDecodingInputParameters {
  1536. u32 region_width { 0 }; // "HBW" in spec.
  1537. u32 region_height { 0 }; // "HBH" in spec.
  1538. bool uses_mmr { false }; // "HMMR" in spec.
  1539. u8 halftone_template { 0 }; // "HTEMPLATE" in spec.
  1540. Vector<NonnullRefPtr<Symbol>> patterns; // "HNUMPATS" / "HPATS" in spec.
  1541. bool default_pixel_value { false }; // "HDEFPIXEL" in spec.
  1542. CombinationOperator combination_operator { CombinationOperator::Or }; // "HCOMBOP" in spec.
  1543. bool enable_skip { false }; // "HENABLESKIP" in spec.
  1544. u32 grayscale_width { 0 }; // "HGW" in spec.
  1545. u32 grayscale_height { 0 }; // "HGH" in spec.
  1546. i32 grid_origin_x_offset { 0 }; // "HGX" in spec.
  1547. i32 grid_origin_y_offset { 0 }; // "HGY" in spec.
  1548. u16 grid_vector_x { 0 }; // "HRY" in spec.
  1549. u16 grid_vector_y { 0 }; // "HRX" in spec.
  1550. u8 pattern_width { 0 }; // "HPW" in spec.
  1551. u8 pattern_height { 0 }; // "HPH" in spec.
  1552. };
  1553. // 6.6 Halftone Region Decoding Procedure
  1554. static ErrorOr<NonnullOwnPtr<BitBuffer>> halftone_region_decoding_procedure(HalftoneRegionDecodingInputParameters const&, ReadonlyBytes)
  1555. {
  1556. return Error::from_string_literal("JBIG2ImageDecoderPlugin: Halftone region decoding not implemented yet");
  1557. }
  1558. // 6.7.2 Input parameters
  1559. // Table 24 – Parameters for the pattern dictionary decoding procedure
  1560. struct PatternDictionaryDecodingInputParameters {
  1561. bool uses_mmr { false }; // "HDMMR" in spec.
  1562. u32 width { 0 }; // "HDPW" in spec.
  1563. u32 height { 0 }; // "HDPH" in spec.
  1564. u32 gray_max { 0 }; // "GRAYMAX" in spec.
  1565. u8 hd_template { 0 }; // "HDTEMPLATE" in spec.
  1566. };
  1567. // 6.7 Pattern Dictionary Decoding Procedure
  1568. static ErrorOr<Vector<NonnullRefPtr<Symbol>>> pattern_dictionary_decoding_procedure(PatternDictionaryDecodingInputParameters const& inputs, ReadonlyBytes data, Vector<JBIG2::ArithmeticDecoder::Context>& contexts)
  1569. {
  1570. // Table 27 – Parameters used to decode a pattern dictionary's collective bitmap
  1571. GenericRegionDecodingInputParameters generic_inputs;
  1572. generic_inputs.is_modified_modified_read = inputs.uses_mmr;
  1573. generic_inputs.region_width = (inputs.gray_max + 1) * inputs.width;
  1574. generic_inputs.region_height = inputs.height;
  1575. generic_inputs.gb_template = inputs.hd_template;
  1576. generic_inputs.is_typical_prediction_used = false;
  1577. generic_inputs.is_extended_reference_template_used = false; // Missing from spec in table 27.
  1578. generic_inputs.skip_pattern = OptionalNone {};
  1579. generic_inputs.adaptive_template_pixels[0].x = -inputs.width;
  1580. generic_inputs.adaptive_template_pixels[0].y = 0;
  1581. generic_inputs.adaptive_template_pixels[1].x = -3;
  1582. generic_inputs.adaptive_template_pixels[1].y = -1;
  1583. generic_inputs.adaptive_template_pixels[2].x = 2;
  1584. generic_inputs.adaptive_template_pixels[2].y = -2;
  1585. generic_inputs.adaptive_template_pixels[3].x = -2;
  1586. generic_inputs.adaptive_template_pixels[3].y = -2;
  1587. Optional<JBIG2::ArithmeticDecoder> decoder;
  1588. if (!inputs.uses_mmr) {
  1589. decoder = TRY(JBIG2::ArithmeticDecoder::initialize(data));
  1590. generic_inputs.arithmetic_decoder = &decoder.value();
  1591. }
  1592. auto bitmap = TRY(generic_region_decoding_procedure(generic_inputs, data, contexts));
  1593. Vector<NonnullRefPtr<Symbol>> patterns;
  1594. for (u32 gray = 0; gray <= inputs.gray_max; ++gray) {
  1595. int x = gray * inputs.width;
  1596. auto pattern = TRY(bitmap->subbitmap({ x, 0, static_cast<int>(inputs.width), static_cast<int>(inputs.height) }));
  1597. patterns.append(Symbol::create(move(pattern)));
  1598. }
  1599. dbgln_if(JBIG2_DEBUG, "Pattern dictionary: {} patterns", patterns.size());
  1600. return patterns;
  1601. }
  1602. static ErrorOr<void> decode_symbol_dictionary(JBIG2LoadingContext& context, SegmentData& segment)
  1603. {
  1604. // 7.4.2 Symbol dictionary segment syntax
  1605. // 7.4.2.1 Symbol dictionary segment data header
  1606. FixedMemoryStream stream(segment.data);
  1607. // 7.4.2.1.1 Symbol dictionary flags
  1608. u16 flags = TRY(stream.read_value<BigEndian<u16>>());
  1609. bool uses_huffman_encoding = (flags & 1) != 0; // "SDHUFF" in spec.
  1610. bool uses_refinement_or_aggregate_coding = (flags & 2) != 0; // "SDREFAGG" in spec.
  1611. u8 huffman_table_selection_for_height_differences = (flags >> 2) & 0b11; // "SDHUFFDH" in spec.
  1612. if (huffman_table_selection_for_height_differences == 2)
  1613. return Error::from_string_literal("JBIG2ImageDecoderPlugin: Invalid huffman_table_selection_for_height_differences");
  1614. if (!uses_huffman_encoding && huffman_table_selection_for_height_differences != 0)
  1615. return Error::from_string_literal("JBIG2ImageDecoderPlugin: Invalid huffman_table_selection_for_height_differences");
  1616. u8 huffman_table_selection_for_width_differences = (flags >> 4) & 0b11; // "SDHUFFDW" in spec.
  1617. if (huffman_table_selection_for_width_differences == 2)
  1618. return Error::from_string_literal("JBIG2ImageDecoderPlugin: Invalid huffman_table_selection_for_width_differences");
  1619. if (!uses_huffman_encoding && huffman_table_selection_for_width_differences != 0)
  1620. return Error::from_string_literal("JBIG2ImageDecoderPlugin: Invalid huffman_table_selection_for_width_differences");
  1621. bool uses_user_supplied_size_table = (flags >> 6) & 1; // "SDHUFFBMSIZE" in spec.
  1622. if (!uses_huffman_encoding && uses_user_supplied_size_table)
  1623. return Error::from_string_literal("JBIG2ImageDecoderPlugin: Invalid uses_user_supplied_size_table");
  1624. bool uses_user_supplied_aggregate_table = (flags >> 7) & 1; // "SDHUFFAGGINST" in spec.
  1625. if (!uses_huffman_encoding && uses_user_supplied_aggregate_table)
  1626. return Error::from_string_literal("JBIG2ImageDecoderPlugin: Invalid uses_user_supplied_aggregate_table");
  1627. bool bitmap_coding_context_used = (flags >> 8) & 1;
  1628. if (uses_huffman_encoding && !uses_refinement_or_aggregate_coding && bitmap_coding_context_used)
  1629. return Error::from_string_literal("JBIG2ImageDecoderPlugin: Invalid bitmap_coding_context_used");
  1630. bool bitmap_coding_context_retained = (flags >> 9) & 1;
  1631. if (uses_huffman_encoding && !uses_refinement_or_aggregate_coding && bitmap_coding_context_retained)
  1632. return Error::from_string_literal("JBIG2ImageDecoderPlugin: Invalid bitmap_coding_context_retained");
  1633. u8 template_used = (flags >> 10) & 0b11; // "SDTEMPLATE" in spec.
  1634. if (uses_huffman_encoding && template_used != 0)
  1635. return Error::from_string_literal("JBIG2ImageDecoderPlugin: Invalid template_used");
  1636. u8 refinement_template_used = (flags >> 12) & 0b11; // "SDREFTEMPLATE" in spec.
  1637. if (!uses_refinement_or_aggregate_coding && refinement_template_used != 0)
  1638. return Error::from_string_literal("JBIG2ImageDecoderPlugin: Invalid refinement_template_used");
  1639. if (flags & 0b1110'0000'0000'0000)
  1640. return Error::from_string_literal("JBIG2ImageDecoderPlugin: Invalid symbol dictionary flags");
  1641. // 7.4.2.1.2 Symbol dictionary AT flags
  1642. Array<AdaptiveTemplatePixel, 4> adaptive_template {};
  1643. if (!uses_huffman_encoding) {
  1644. int number_of_adaptive_template_pixels = template_used == 0 ? 4 : 1;
  1645. for (int i = 0; i < number_of_adaptive_template_pixels; ++i) {
  1646. adaptive_template[i].x = TRY(stream.read_value<i8>());
  1647. adaptive_template[i].y = TRY(stream.read_value<i8>());
  1648. }
  1649. }
  1650. // 7.4.2.1.3 Symbol dictionary refinement AT flags
  1651. Array<AdaptiveTemplatePixel, 2> adaptive_refinement_template {};
  1652. if (uses_refinement_or_aggregate_coding && refinement_template_used == 0) {
  1653. for (size_t i = 0; i < adaptive_refinement_template.size(); ++i) {
  1654. adaptive_refinement_template[i].x = TRY(stream.read_value<i8>());
  1655. adaptive_refinement_template[i].y = TRY(stream.read_value<i8>());
  1656. }
  1657. }
  1658. // 7.4.2.1.4 Number of exported symbols (SDNUMEXSYMS)
  1659. u32 number_of_exported_symbols = TRY(stream.read_value<BigEndian<u32>>());
  1660. // 7.4.2.1.5 Number of new symbols (SDNUMNEWSYMS)
  1661. u32 number_of_new_symbols = TRY(stream.read_value<BigEndian<u32>>());
  1662. dbgln_if(JBIG2_DEBUG, "Symbol dictionary: uses_huffman_encoding={}", uses_huffman_encoding);
  1663. dbgln_if(JBIG2_DEBUG, "Symbol dictionary: uses_refinement_or_aggregate_coding={}", uses_refinement_or_aggregate_coding);
  1664. dbgln_if(JBIG2_DEBUG, "Symbol dictionary: huffman_table_selection_for_height_differences={}", huffman_table_selection_for_height_differences);
  1665. dbgln_if(JBIG2_DEBUG, "Symbol dictionary: huffman_table_selection_for_width_differences={}", huffman_table_selection_for_width_differences);
  1666. dbgln_if(JBIG2_DEBUG, "Symbol dictionary: uses_user_supplied_size_table={}", uses_user_supplied_size_table);
  1667. dbgln_if(JBIG2_DEBUG, "Symbol dictionary: uses_user_supplied_aggregate_table={}", uses_user_supplied_aggregate_table);
  1668. dbgln_if(JBIG2_DEBUG, "Symbol dictionary: bitmap_coding_context_used={}", bitmap_coding_context_used);
  1669. dbgln_if(JBIG2_DEBUG, "Symbol dictionary: bitmap_coding_context_retained={}", bitmap_coding_context_retained);
  1670. dbgln_if(JBIG2_DEBUG, "Symbol dictionary: template_used={}", template_used);
  1671. dbgln_if(JBIG2_DEBUG, "Symbol dictionary: refinement_template_used={}", refinement_template_used);
  1672. dbgln_if(JBIG2_DEBUG, "Symbol dictionary: number_of_exported_symbols={}", number_of_exported_symbols);
  1673. dbgln_if(JBIG2_DEBUG, "Symbol dictionary: number_of_new_symbols={}", number_of_new_symbols);
  1674. // 7.4.2.1.6 Symbol dictionary segment Huffman table selection
  1675. // FIXME
  1676. // 7.4.2.2 Decoding a symbol dictionary segment
  1677. // "1) Interpret its header, as described in 7.4.2.1."
  1678. // Done!
  1679. // "2) Decode (or retrieve the results of decoding) any referred-to symbol dictionary and tables segments."
  1680. Vector<NonnullRefPtr<Symbol>> symbols;
  1681. for (auto referred_to_segment_number : segment.header.referred_to_segment_numbers) {
  1682. auto opt_referred_to_segment = context.segments_by_number.get(referred_to_segment_number);
  1683. if (!opt_referred_to_segment.has_value())
  1684. return Error::from_string_literal("JBIG2ImageDecoderPlugin: Symbol segment refers to non-existent segment");
  1685. dbgln_if(JBIG2_DEBUG, "Symbol segment refers to segment id {} index {}", referred_to_segment_number, opt_referred_to_segment.value());
  1686. auto const& referred_to_segment = context.segments[opt_referred_to_segment.value()];
  1687. if (!referred_to_segment.symbols.has_value())
  1688. return Error::from_string_literal("JBIG2ImageDecoderPlugin: Symbol segment referred-to segment without symbols");
  1689. symbols.extend(referred_to_segment.symbols.value());
  1690. }
  1691. // "3) If the "bitmap coding context used" bit in the header was 1, ..."
  1692. if (bitmap_coding_context_used)
  1693. return Error::from_string_literal("JBIG2ImageDecoderPlugin: Cannot decode bitmap coding context segment yet");
  1694. // "4) If the "bitmap coding context used" bit in the header was 0, then, as described in E.3.7,
  1695. // reset all the arithmetic coding statistics for the generic region and generic refinement region decoding procedures to zero."
  1696. // Nothing to do.
  1697. // "5) Reset the arithmetic coding statistics for all the contexts of all the arithmetic integer coders to zero."
  1698. // FIXME
  1699. // "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."
  1700. SymbolDictionaryDecodingInputParameters inputs;
  1701. inputs.uses_huffman_encoding = uses_huffman_encoding;
  1702. inputs.uses_refinement_or_aggregate_coding = uses_refinement_or_aggregate_coding;
  1703. inputs.input_symbols = move(symbols);
  1704. inputs.number_of_new_symbols = number_of_new_symbols;
  1705. inputs.number_of_exported_symbols = number_of_exported_symbols;
  1706. // FIXME: SDHUFFDH, SDHUFFDW, SDHUFFBMSIZE, SDHUFFAGGINST
  1707. inputs.symbol_template = template_used;
  1708. inputs.adaptive_template_pixels = adaptive_template;
  1709. inputs.refinement_template = refinement_template_used;
  1710. inputs.refinement_adaptive_template_pixels = adaptive_refinement_template;
  1711. auto result = TRY(symbol_dictionary_decoding_procedure(inputs, segment.data.slice(TRY(stream.tell()))));
  1712. // "7) If the "bitmap coding context retained" bit in the header was 1, then, as described in E.3.8, preserve the current contents
  1713. // of the arithmetic coding statistics for the generic region and generic refinement region decoding procedures."
  1714. if (bitmap_coding_context_retained)
  1715. return Error::from_string_literal("JBIG2ImageDecoderPlugin: Cannot retain bitmap coding context yet");
  1716. segment.symbols = move(result);
  1717. return {};
  1718. }
  1719. static ErrorOr<void> decode_intermediate_text_region(JBIG2LoadingContext&, SegmentData const&)
  1720. {
  1721. return Error::from_string_literal("JBIG2ImageDecoderPlugin: Cannot decode intermediate text region yet");
  1722. }
  1723. static ErrorOr<void> decode_immediate_text_region(JBIG2LoadingContext& context, SegmentData const& segment)
  1724. {
  1725. // 7.4.3 Text region segment syntax
  1726. auto data = segment.data;
  1727. auto information_field = TRY(decode_region_segment_information_field(data));
  1728. data = data.slice(sizeof(information_field));
  1729. 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);
  1730. FixedMemoryStream stream(data);
  1731. // 7.4.3.1.1 Text region segment flags
  1732. u16 text_region_segment_flags = TRY(stream.read_value<BigEndian<u16>>());
  1733. bool uses_huffman_encoding = (text_region_segment_flags & 1) != 0; // "SBHUFF" in spec.
  1734. bool uses_refinement_coding = (text_region_segment_flags >> 1) & 1; // "SBREFINE" in spec.
  1735. u8 log_strip_size = (text_region_segment_flags >> 2) & 3; // "LOGSBSTRIPS" in spec.
  1736. u8 strip_size = 1u << log_strip_size;
  1737. u8 reference_corner = (text_region_segment_flags >> 4) & 3; // "REFCORNER"
  1738. bool is_transposed = (text_region_segment_flags >> 6) & 1; // "TRANSPOSED" in spec.
  1739. u8 combination_operator = (text_region_segment_flags >> 7) & 3; // "SBCOMBOP" in spec.
  1740. if (combination_operator > 4)
  1741. return Error::from_string_literal("JBIG2ImageDecoderPlugin: Invalid text region combination operator");
  1742. u8 default_pixel_value = (text_region_segment_flags >> 9) & 1; // "SBDEFPIXEL" in spec.
  1743. u8 delta_s_offset_value = (text_region_segment_flags >> 10) & 0x1f; // "SBDSOFFSET" in spec.
  1744. i8 delta_s_offset = delta_s_offset_value;
  1745. if (delta_s_offset_value & 0x10) {
  1746. // This is converting a 5-bit two's complement number ot i8.
  1747. // FIXME: There's probably a simpler way to do this? Probably just sign-extend by or-ing in the top 3 bits?
  1748. delta_s_offset_value = (~delta_s_offset_value + 1) & 0x1f;
  1749. delta_s_offset = -delta_s_offset_value;
  1750. }
  1751. u8 refinement_template = (text_region_segment_flags >> 15) != 0; // "SBRTEMPLATE" in spec.
  1752. if (!uses_refinement_coding && refinement_template != 0)
  1753. return Error::from_string_literal("JBIG2ImageDecoderPlugin: Invalid refinement_template");
  1754. // 7.4.3.1.2 Text region segment Huffman flags
  1755. // "This field is only present if SBHUFF is 1."
  1756. // FIXME: Support this eventually.
  1757. if (uses_huffman_encoding)
  1758. return Error::from_string_literal("JBIG2ImageDecoderPlugin: Cannot decode huffman text regions yet");
  1759. // 7.4.3.1.3 Text region refinement AT flags
  1760. // "This field is only present if SBREFINE is 1 and SBRTEMPLATE is 0."
  1761. Array<AdaptiveTemplatePixel, 2> adaptive_refinement_template {};
  1762. if (uses_refinement_coding && refinement_template == 0) {
  1763. for (size_t i = 0; i < adaptive_refinement_template.size(); ++i) {
  1764. adaptive_refinement_template[i].x = TRY(stream.read_value<i8>());
  1765. adaptive_refinement_template[i].y = TRY(stream.read_value<i8>());
  1766. }
  1767. }
  1768. // 7.4.3.1.4 Number of symbol instances (SBNUMINSTANCES)
  1769. u32 number_of_symbol_instances = TRY(stream.read_value<BigEndian<u32>>());
  1770. // 7.4.3.1.5 Text region segment symbol ID Huffman decoding table
  1771. // "It is only present if SBHUFF is 1."
  1772. // FIXME: Support this eventually.
  1773. 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);
  1774. 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);
  1775. dbgln_if(JBIG2_DEBUG, "Text region: number_of_symbol_instances={}", number_of_symbol_instances);
  1776. // 7.4.3.2 Decoding a text region segment
  1777. // "1) Interpret its header, as described in 7.4.3.1."
  1778. // Done!
  1779. // "2) Decode (or retrieve the results of decoding) any referred-to symbol dictionary and tables segments."
  1780. Vector<NonnullRefPtr<Symbol>> symbols;
  1781. for (auto referred_to_segment_number : segment.header.referred_to_segment_numbers) {
  1782. auto opt_referred_to_segment = context.segments_by_number.get(referred_to_segment_number);
  1783. if (!opt_referred_to_segment.has_value())
  1784. return Error::from_string_literal("JBIG2ImageDecoderPlugin: Text segment refers to non-existent segment");
  1785. dbgln_if(JBIG2_DEBUG, "Text segment refers to segment id {} index {}", referred_to_segment_number, opt_referred_to_segment.value());
  1786. auto const& referred_to_segment = context.segments[opt_referred_to_segment.value()];
  1787. if (!referred_to_segment.symbols.has_value())
  1788. return Error::from_string_literal("JBIG2ImageDecoderPlugin: Text segment referred-to segment without symbols");
  1789. symbols.extend(referred_to_segment.symbols.value());
  1790. }
  1791. // "3) As described in E.3.7, reset all the arithmetic coding statistics to zero."
  1792. // FIXME
  1793. // "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."
  1794. TextRegionDecodingInputParameters inputs;
  1795. inputs.uses_huffman_encoding = uses_huffman_encoding;
  1796. inputs.uses_refinement_coding = uses_refinement_coding;
  1797. inputs.default_pixel = default_pixel_value;
  1798. inputs.operator_ = static_cast<CombinationOperator>(combination_operator);
  1799. inputs.is_transposed = is_transposed;
  1800. inputs.reference_corner = static_cast<TextRegionDecodingInputParameters::Corner>(reference_corner);
  1801. inputs.delta_s_offset = delta_s_offset;
  1802. inputs.region_width = information_field.width;
  1803. inputs.region_height = information_field.height;
  1804. inputs.number_of_instances = number_of_symbol_instances;
  1805. inputs.size_of_symbol_instance_strips = strip_size;
  1806. inputs.id_symbol_code_length = ceil(log2(symbols.size()));
  1807. inputs.symbols = move(symbols);
  1808. // FIXME: Huffman tables.
  1809. inputs.refinement_template = refinement_template;
  1810. inputs.refinement_adaptive_template_pixels = adaptive_refinement_template;
  1811. auto result = TRY(text_region_decoding_procedure(inputs, data.slice(TRY(stream.tell()))));
  1812. composite_bitbuffer(*context.page.bits, *result, { information_field.x_location, information_field.y_location }, information_field.external_combination_operator());
  1813. return {};
  1814. }
  1815. static ErrorOr<void> decode_pattern_dictionary(JBIG2LoadingContext&, SegmentData& segment)
  1816. {
  1817. // 7.4.4 Pattern dictionary segment syntax
  1818. FixedMemoryStream stream(segment.data);
  1819. // 7.4.4.1.1 Pattern dictionary flags
  1820. u8 flags = TRY(stream.read_value<u8>());
  1821. bool uses_mmr = flags & 1;
  1822. u8 hd_template = (flags >> 1) & 3;
  1823. if (uses_mmr && hd_template != 0)
  1824. return Error::from_string_literal("JBIG2ImageDecoderPlugin: Invalid hd_template");
  1825. if (flags & 0b1111'1000)
  1826. return Error::from_string_literal("JBIG2ImageDecoderPlugin: Invalid flags");
  1827. // 7.4.4.1.2 Width of the patterns in the pattern dictionary (HDPW)
  1828. u8 width = TRY(stream.read_value<u8>());
  1829. if (width == 0)
  1830. return Error::from_string_literal("JBIG2ImageDecoderPlugin: Invalid width");
  1831. // 7.4.4.1.3 Height of the patterns in the pattern dictionary (HDPH)
  1832. u8 height = TRY(stream.read_value<u8>());
  1833. if (height == 0)
  1834. return Error::from_string_literal("JBIG2ImageDecoderPlugin: Invalid height");
  1835. // 7.4.4.1.4 Largest gray-scale value (GRAYMAX)
  1836. u32 gray_max = TRY(stream.read_value<BigEndian<u32>>());
  1837. // 7.4.4.2 Decoding a pattern dictionary segment
  1838. dbgln_if(JBIG2_DEBUG, "Pattern dictionary: uses_mmr={}, hd_template={}, width={}, height={}, gray_max={}", uses_mmr, hd_template, width, height, gray_max);
  1839. auto data = segment.data.slice(TRY(stream.tell()));
  1840. // "1) Interpret its header, as described in 7.4.4.1."
  1841. // Done!
  1842. // "2) As described in E.3.7, reset all the arithmetic coding statistics to zero."
  1843. Vector<JBIG2::ArithmeticDecoder::Context> contexts;
  1844. if (!uses_mmr)
  1845. contexts.resize(1 << number_of_context_bits_for_template(hd_template));
  1846. // "3) Invoke the pattern dictionary decoding procedure described in 6.7, with the parameters to the pattern
  1847. // dictionary decoding procedure set as shown in Table 35."
  1848. PatternDictionaryDecodingInputParameters inputs;
  1849. inputs.uses_mmr = uses_mmr;
  1850. inputs.width = width;
  1851. inputs.height = height;
  1852. inputs.gray_max = gray_max;
  1853. inputs.hd_template = hd_template;
  1854. auto result = TRY(pattern_dictionary_decoding_procedure(inputs, data, contexts));
  1855. segment.patterns = move(result);
  1856. return {};
  1857. }
  1858. static ErrorOr<void> decode_intermediate_halftone_region(JBIG2LoadingContext&, SegmentData const&)
  1859. {
  1860. return Error::from_string_literal("JBIG2ImageDecoderPlugin: Cannot decode intermediate halftone region yet");
  1861. }
  1862. static ErrorOr<void> decode_immediate_halftone_region(JBIG2LoadingContext& context, SegmentData const& segment)
  1863. {
  1864. // 7.4.5 Halftone region segment syntax
  1865. auto data = segment.data;
  1866. auto information_field = TRY(decode_region_segment_information_field(data));
  1867. data = data.slice(sizeof(information_field));
  1868. dbgln_if(JBIG2_DEBUG, "Halftone region: width={}, height={}, x={}, y={}, flags={:#x}", information_field.width, information_field.height, information_field.x_location, information_field.y_location, information_field.flags);
  1869. FixedMemoryStream stream(data);
  1870. // 7.4.5.1.1 Halftone region segment flags
  1871. u8 flags = TRY(stream.read_value<u8>());
  1872. bool uses_mmr = flags & 1; // "HMMR" in spec.
  1873. u8 template_used = (flags >> 1) & 3; // "HTTEMPLATE" in spec.
  1874. if (uses_mmr && template_used != 0)
  1875. return Error::from_string_literal("JBIG2ImageDecoderPlugin: Invalid template_used");
  1876. bool enable_skip = (flags >> 3) & 1; // "HENABLESKIP" in spec.
  1877. u8 combination_operator = (flags >> 4) & 7; // "HCOMBOP" in spec.
  1878. if (combination_operator > 4)
  1879. return Error::from_string_literal("JBIG2ImageDecoderPlugin: Invalid combination_operator");
  1880. bool default_pixel_value = (flags >> 7) & 1; // "HDEFPIXEL" in spec.
  1881. dbgln_if(JBIG2_DEBUG, "Halftone region: uses_mmr={}, template_used={}, enable_skip={}, combination_operator={}, default_pixel_value={}", uses_mmr, template_used, enable_skip, combination_operator, default_pixel_value);
  1882. // 7.4.5.1.2 Halftone grid position and size
  1883. // 7.4.5.1.2.1 Width of the gray-scale image (HGW)
  1884. u32 gray_width = TRY(stream.read_value<BigEndian<u32>>());
  1885. // 7.4.5.1.2.2 Height of the gray-scale image (HGH)
  1886. u32 gray_height = TRY(stream.read_value<BigEndian<u32>>());
  1887. // 7.4.5.1.2.3 Horizontal offset of the grid (HGX)
  1888. i32 grid_x = TRY(stream.read_value<BigEndian<i32>>());
  1889. // 7.4.5.1.2.4 Vertical offset of the grid (HGY)
  1890. i32 grid_y = TRY(stream.read_value<BigEndian<i32>>());
  1891. // 7.4.5.1.3 Halftone grid vector
  1892. // 7.4.5.1.3.1 Horizontal coordinate of the halftone grid vector (HRX)
  1893. u16 grid_vector_x = TRY(stream.read_value<BigEndian<u16>>());
  1894. // 7.4.5.1.3.2 Vertical coordinate of the halftone grid vector (HRY)
  1895. u16 grid_vector_y = TRY(stream.read_value<BigEndian<u16>>());
  1896. dbgln_if(JBIG2_DEBUG, "Halftone region: gray_width={}, gray_height={}, grid_x={}, grid_y={}, grid_vector_x={}, grid_vector_y={}", gray_width, gray_height, grid_x, grid_y, grid_vector_x, grid_vector_y);
  1897. // 7.4.5.2 Decoding a halftone region segment
  1898. // "1) Interpret its header, as described in 7.4.5.1."
  1899. // Done!
  1900. // "2) Decode (or retrieve the results of decoding) the referred-to pattern dictionary segment."
  1901. if (segment.header.referred_to_segment_numbers.size() != 1)
  1902. return Error::from_string_literal("JBIG2ImageDecoderPlugin: Halftone segment refers to wrong number of segments");
  1903. auto opt_referred_to_segment = context.segments_by_number.get(segment.header.referred_to_segment_numbers[0]);
  1904. if (!opt_referred_to_segment.has_value())
  1905. return Error::from_string_literal("JBIG2ImageDecoderPlugin: Halftone segment refers to non-existent segment");
  1906. dbgln_if(JBIG2_DEBUG, "Halftone segment refers to segment id {} index {}", segment.header.referred_to_segment_numbers[0], opt_referred_to_segment.value());
  1907. auto const& referred_to_segment = context.segments[opt_referred_to_segment.value()];
  1908. if (!referred_to_segment.patterns.has_value())
  1909. return Error::from_string_literal("JBIG2ImageDecoderPlugin: Halftone segment referred-to segment without patterns");
  1910. Vector<NonnullRefPtr<Symbol>> patterns = referred_to_segment.patterns.value();
  1911. if (patterns.is_empty())
  1912. return Error::from_string_literal("JBIG2ImageDecoderPlugin: Halftone segment without patterns");
  1913. // "3) As described in E.3.7, reset all the arithmetic coding statistics to zero."
  1914. // FIXME
  1915. // "4) Invoke the halftone region decoding procedure described in 6.6, with the parameters to the halftone
  1916. // region decoding procedure set as shown in Table 36."
  1917. data = data.slice(TRY(stream.tell()));
  1918. HalftoneRegionDecodingInputParameters inputs;
  1919. inputs.region_width = information_field.width;
  1920. inputs.region_height = information_field.height;
  1921. inputs.uses_mmr = uses_mmr;
  1922. inputs.halftone_template = template_used;
  1923. inputs.enable_skip = enable_skip;
  1924. inputs.combination_operator = static_cast<CombinationOperator>(combination_operator);
  1925. inputs.default_pixel_value = default_pixel_value;
  1926. inputs.grayscale_width = gray_width;
  1927. inputs.grayscale_height = gray_height;
  1928. inputs.grid_origin_x_offset = grid_x;
  1929. inputs.grid_origin_y_offset = grid_y;
  1930. inputs.grid_vector_x = grid_vector_x;
  1931. inputs.grid_vector_y = grid_vector_y;
  1932. inputs.patterns = move(patterns);
  1933. inputs.pattern_width = inputs.patterns[0]->bitmap().width();
  1934. inputs.pattern_height = inputs.patterns[0]->bitmap().height();
  1935. auto result = TRY(halftone_region_decoding_procedure(inputs, data));
  1936. composite_bitbuffer(*context.page.bits, *result, { information_field.x_location, information_field.y_location }, information_field.external_combination_operator());
  1937. return {};
  1938. }
  1939. static ErrorOr<void> decode_immediate_lossless_halftone_region(JBIG2LoadingContext&, SegmentData const&)
  1940. {
  1941. return Error::from_string_literal("JBIG2ImageDecoderPlugin: Cannot decode immediate lossless halftone region yet");
  1942. }
  1943. static ErrorOr<void> decode_intermediate_generic_region(JBIG2LoadingContext&, SegmentData const&)
  1944. {
  1945. return Error::from_string_literal("JBIG2ImageDecoderPlugin: Cannot decode intermediate generic region yet");
  1946. }
  1947. static ErrorOr<void> decode_immediate_generic_region(JBIG2LoadingContext& context, SegmentData const& segment)
  1948. {
  1949. // 7.4.6 Generic region segment syntax
  1950. auto data = segment.data;
  1951. auto information_field = TRY(decode_region_segment_information_field(data));
  1952. data = data.slice(sizeof(information_field));
  1953. 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);
  1954. // 7.4.6.2 Generic region segment flags
  1955. if (data.is_empty())
  1956. return Error::from_string_literal("JBIG2ImageDecoderPlugin: No segment data");
  1957. u8 flags = data[0];
  1958. bool uses_mmr = (flags & 1) != 0;
  1959. u8 arithmetic_coding_template = (flags >> 1) & 3; // "GBTEMPLATE"
  1960. bool typical_prediction_generic_decoding_on = (flags >> 3) & 1; // "TPGDON"; "TPGD" is short for "Typical Prediction for Generic Direct coding"
  1961. bool uses_extended_reference_template = (flags >> 4) & 1; // "EXTTEMPLATE"
  1962. if (flags & 0b1110'0000)
  1963. return Error::from_string_literal("JBIG2ImageDecoderPlugin: Invalid flags");
  1964. data = data.slice(sizeof(flags));
  1965. // 7.4.6.3 Generic region segment AT flags
  1966. Array<AdaptiveTemplatePixel, 12> adaptive_template_pixels {};
  1967. if (!uses_mmr) {
  1968. dbgln_if(JBIG2_DEBUG, "Non-MMR generic region, GBTEMPLATE={} TPGDON={} EXTTEMPLATE={}", arithmetic_coding_template, typical_prediction_generic_decoding_on, uses_extended_reference_template);
  1969. if (arithmetic_coding_template == 0 && uses_extended_reference_template) {
  1970. // This was added in T.88 Amendment 2 (https://www.itu.int/rec/T-REC-T.88-200306-S!Amd2/en) mid-2003.
  1971. // 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,
  1972. // so it's not clear how much data to read.
  1973. return Error::from_string_literal("JBIG2ImageDecoderPlugin: GBTEMPLATE=0 EXTTEMPLATE=1 not yet implemented");
  1974. }
  1975. size_t number_of_adaptive_template_pixels = arithmetic_coding_template == 0 ? 4 : 1;
  1976. if (data.size() < 2 * number_of_adaptive_template_pixels)
  1977. return Error::from_string_literal("JBIG2ImageDecoderPlugin: No adaptive template data");
  1978. for (size_t i = 0; i < number_of_adaptive_template_pixels; ++i) {
  1979. adaptive_template_pixels[i].x = static_cast<i8>(data[2 * i]);
  1980. adaptive_template_pixels[i].y = static_cast<i8>(data[2 * i + 1]);
  1981. }
  1982. data = data.slice(2 * number_of_adaptive_template_pixels);
  1983. }
  1984. // 7.4.6.4 Decoding a generic region segment
  1985. // "1) Interpret its header, as described in 7.4.6.1"
  1986. // Done above.
  1987. // "2) As described in E.3.7, reset all the arithmetic coding statistics to zero."
  1988. Vector<JBIG2::ArithmeticDecoder::Context> contexts;
  1989. if (!uses_mmr)
  1990. contexts.resize(1 << number_of_context_bits_for_template(arithmetic_coding_template));
  1991. // "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."
  1992. GenericRegionDecodingInputParameters inputs;
  1993. inputs.is_modified_modified_read = uses_mmr;
  1994. inputs.region_width = information_field.width;
  1995. inputs.region_height = information_field.height;
  1996. inputs.gb_template = arithmetic_coding_template;
  1997. inputs.is_typical_prediction_used = typical_prediction_generic_decoding_on;
  1998. inputs.is_extended_reference_template_used = uses_extended_reference_template;
  1999. inputs.skip_pattern = OptionalNone {};
  2000. inputs.adaptive_template_pixels = adaptive_template_pixels;
  2001. Optional<JBIG2::ArithmeticDecoder> decoder;
  2002. if (!uses_mmr) {
  2003. decoder = TRY(JBIG2::ArithmeticDecoder::initialize(data));
  2004. inputs.arithmetic_decoder = &decoder.value();
  2005. }
  2006. auto result = TRY(generic_region_decoding_procedure(inputs, data, contexts));
  2007. // 8.2 Page image composition step 5)
  2008. if (information_field.x_location + information_field.width > (u32)context.page.size.width()
  2009. || information_field.y_location + information_field.height > (u32)context.page.size.height()) {
  2010. return Error::from_string_literal("JBIG2ImageDecoderPlugin: Region bounds outsize of page bounds");
  2011. }
  2012. composite_bitbuffer(*context.page.bits, *result, { information_field.x_location, information_field.y_location }, information_field.external_combination_operator());
  2013. return {};
  2014. }
  2015. static ErrorOr<void> decode_intermediate_generic_refinement_region(JBIG2LoadingContext&, SegmentData const&)
  2016. {
  2017. return Error::from_string_literal("JBIG2ImageDecoderPlugin: Cannot decode intermediate generic refinement region yet");
  2018. }
  2019. static ErrorOr<void> decode_immediate_generic_refinement_region(JBIG2LoadingContext&, SegmentData const&)
  2020. {
  2021. return Error::from_string_literal("JBIG2ImageDecoderPlugin: Cannot decode immediate generic refinement region yet");
  2022. }
  2023. static ErrorOr<void> decode_immediate_lossless_generic_refinement_region(JBIG2LoadingContext&, SegmentData const&)
  2024. {
  2025. return Error::from_string_literal("JBIG2ImageDecoderPlugin: Cannot decode immediate lossless generic refinement region yet");
  2026. }
  2027. static ErrorOr<void> decode_page_information(JBIG2LoadingContext& context, SegmentData const& segment)
  2028. {
  2029. // 7.4.8 Page information segment syntax and 8.1 Decoder model steps 1) - 3).
  2030. // "1) Decode the page information segment.""
  2031. auto page_information = TRY(decode_page_information_segment(segment.data));
  2032. bool page_is_striped = (page_information.striping_information & 0x80) != 0;
  2033. if (page_information.bitmap_height == 0xffff'ffff && !page_is_striped)
  2034. return Error::from_string_literal("JBIG2ImageDecoderPlugin: Non-striped bitmaps of indeterminate height not allowed");
  2035. u16 maximum_stripe_height = page_information.striping_information & 0x7F;
  2036. u8 default_color = (page_information.flags >> 2) & 1;
  2037. u8 default_combination_operator = (page_information.flags >> 3) & 3;
  2038. context.page.default_combination_operator = static_cast<CombinationOperator>(default_combination_operator);
  2039. 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);
  2040. // FIXME: Do something with the other fields in page_information.
  2041. // "2) Create the page buffer, of the size given in the page information segment.
  2042. //
  2043. // If the page height is unknown, then this is not possible. However, in this case the page must be striped,
  2044. // and the maximum stripe height specified, and the initial page buffer can be created with height initially
  2045. // equal to this maximum stripe height."
  2046. size_t height = page_information.bitmap_height;
  2047. if (height == 0xffff'ffff)
  2048. height = maximum_stripe_height;
  2049. context.page.bits = TRY(BitBuffer::create(page_information.bitmap_width, height));
  2050. // "3) Fill the page buffer with the page's default pixel value."
  2051. context.page.bits->fill(default_color != 0);
  2052. return {};
  2053. }
  2054. static ErrorOr<void> decode_end_of_page(JBIG2LoadingContext&, SegmentData const& segment)
  2055. {
  2056. // 7.4.9 End of page segment syntax
  2057. if (segment.data.size() != 0)
  2058. return Error::from_string_literal("JBIG2ImageDecoderPlugin: End of page segment has non-zero size");
  2059. // FIXME: If the page had unknown height, check that previous segment was end-of-stripe.
  2060. // FIXME: Maybe mark page as completed and error if we see more segments for it?
  2061. return {};
  2062. }
  2063. static ErrorOr<void> decode_end_of_stripe(JBIG2LoadingContext&, SegmentData const& segment)
  2064. {
  2065. // 7.4.10 End of stripe segment syntax
  2066. // "The segment data of an end of stripe segment consists of one four-byte value, specifying the Y coordinate of the end row."
  2067. if (segment.data.size() != 4)
  2068. return Error::from_string_literal("JBIG2ImageDecoderPlugin: End of strip segment has wrong size");
  2069. // FIXME: Once we implement support for images with initially indeterminate height, we need these values to determine the height at the end.
  2070. u32 y_coordinate = *reinterpret_cast<BigEndian<u32> const*>(segment.data.data());
  2071. dbgln_if(JBIG2_DEBUG, "End of stripe: y={}", y_coordinate);
  2072. return {};
  2073. }
  2074. static ErrorOr<void> decode_end_of_file(JBIG2LoadingContext&, SegmentData const& segment)
  2075. {
  2076. // 7.4.11 End of file segment syntax
  2077. if (segment.data.size() != 0)
  2078. return Error::from_string_literal("JBIG2ImageDecoderPlugin: End of file segment has non-zero size");
  2079. return {};
  2080. }
  2081. static ErrorOr<void> decode_profiles(JBIG2LoadingContext&, SegmentData const&)
  2082. {
  2083. return Error::from_string_literal("JBIG2ImageDecoderPlugin: Cannot decode profiles yet");
  2084. }
  2085. static ErrorOr<void> decode_tables(JBIG2LoadingContext&, SegmentData const&)
  2086. {
  2087. return Error::from_string_literal("JBIG2ImageDecoderPlugin: Cannot decode tables yet");
  2088. }
  2089. static ErrorOr<void> decode_color_palette(JBIG2LoadingContext&, SegmentData const&)
  2090. {
  2091. return Error::from_string_literal("JBIG2ImageDecoderPlugin: Cannot decode color palette yet");
  2092. }
  2093. static ErrorOr<void> decode_extension(JBIG2LoadingContext&, SegmentData const& segment)
  2094. {
  2095. // 7.4.14 Extension segment syntax
  2096. FixedMemoryStream stream { segment.data };
  2097. enum ExtensionType {
  2098. SingleByteCodedComment = 0x20000000,
  2099. MultiByteCodedComment = 0x20000002,
  2100. };
  2101. u32 type = TRY(stream.read_value<BigEndian<u32>>());
  2102. auto read_string = [&]<class T>() -> ErrorOr<Vector<T>> {
  2103. Vector<T> result;
  2104. do {
  2105. result.append(TRY(stream.read_value<BigEndian<T>>()));
  2106. } while (result.last());
  2107. result.take_last();
  2108. return result;
  2109. };
  2110. switch (type) {
  2111. case SingleByteCodedComment: {
  2112. // 7.4.15.1 Single-byte coded comment
  2113. // Pairs of zero-terminated ISO/IEC 8859-1 (latin1) pairs, terminated by another \0.
  2114. while (true) {
  2115. auto first_bytes = TRY(read_string.template operator()<u8>());
  2116. if (first_bytes.is_empty())
  2117. break;
  2118. auto second_bytes = TRY(read_string.template operator()<u8>());
  2119. auto first = TRY(TextCodec::decoder_for("ISO-8859-1"sv)->to_utf8(StringView { first_bytes }));
  2120. auto second = TRY(TextCodec::decoder_for("ISO-8859-1"sv)->to_utf8(StringView { second_bytes }));
  2121. dbgln("JBIG2ImageDecoderPlugin: key '{}', value '{}'", first, second);
  2122. }
  2123. if (!stream.is_eof())
  2124. return Error::from_string_literal("JBIG2ImageDecoderPlugin: Trailing data after SingleByteCodedComment");
  2125. return {};
  2126. }
  2127. case MultiByteCodedComment: {
  2128. // 7.4.15.2 Multi-byte coded comment
  2129. // Pairs of (two-byte-)zero-terminated UCS-2 pairs, terminated by another \0\0.
  2130. while (true) {
  2131. auto first_ucs2 = TRY(read_string.template operator()<u16>());
  2132. if (first_ucs2.is_empty())
  2133. break;
  2134. auto second_ucs2 = TRY(read_string.template operator()<u16>());
  2135. auto first = TRY(Utf16View(first_ucs2).to_utf8());
  2136. auto second = TRY(Utf16View(second_ucs2).to_utf8());
  2137. dbgln("JBIG2ImageDecoderPlugin: key '{}', value '{}'", first, second);
  2138. }
  2139. if (!stream.is_eof())
  2140. return Error::from_string_literal("JBIG2ImageDecoderPlugin: Trailing data after MultiByteCodedComment");
  2141. return {};
  2142. }
  2143. }
  2144. // FIXME: If bit 31 in `type` is not set, the extension isn't necessary, and we could ignore it.
  2145. dbgln("JBIG2ImageDecoderPlugin: Unknown extension type {:#x}", type);
  2146. return Error::from_string_literal("JBIG2ImageDecoderPlugin: Unknown extension type");
  2147. }
  2148. static ErrorOr<void> decode_data(JBIG2LoadingContext& context)
  2149. {
  2150. TRY(warn_about_multiple_pages(context));
  2151. for (size_t i = 0; i < context.segments.size(); ++i) {
  2152. auto& segment = context.segments[i];
  2153. if (segment.header.page_association != 0 && segment.header.page_association != 1)
  2154. continue;
  2155. switch (segment.header.type) {
  2156. case SegmentType::SymbolDictionary:
  2157. TRY(decode_symbol_dictionary(context, segment));
  2158. break;
  2159. case SegmentType::IntermediateTextRegion:
  2160. TRY(decode_intermediate_text_region(context, segment));
  2161. break;
  2162. case SegmentType::ImmediateTextRegion:
  2163. case SegmentType::ImmediateLosslessTextRegion:
  2164. // 7.4.3 Text region segment syntax
  2165. // "The data parts of all three of the text region segment types ("intermediate text region", "immediate text region" and
  2166. // "immediate lossless text region") are coded identically, but are acted upon differently, see 8.2."
  2167. // But 8.2 only describes a difference between intermediate and immediate regions as far as I can tell,
  2168. // and calling the immediate text region handler for immediate lossless text regions seems to do the right thing (?).
  2169. TRY(decode_immediate_text_region(context, segment));
  2170. break;
  2171. case SegmentType::PatternDictionary:
  2172. TRY(decode_pattern_dictionary(context, segment));
  2173. break;
  2174. case SegmentType::IntermediateHalftoneRegion:
  2175. TRY(decode_intermediate_halftone_region(context, segment));
  2176. break;
  2177. case SegmentType::ImmediateHalftoneRegion:
  2178. TRY(decode_immediate_halftone_region(context, segment));
  2179. break;
  2180. case SegmentType::ImmediateLosslessHalftoneRegion:
  2181. TRY(decode_immediate_lossless_halftone_region(context, segment));
  2182. break;
  2183. case SegmentType::IntermediateGenericRegion:
  2184. TRY(decode_intermediate_generic_region(context, segment));
  2185. break;
  2186. case SegmentType::ImmediateGenericRegion:
  2187. case SegmentType::ImmediateLosslessGenericRegion:
  2188. // 7.4.6 Generic region segment syntax
  2189. // "The data parts of all three of the generic region segment types ("intermediate generic region", "immediate generic region" and
  2190. // "immediate lossless generic region") are coded identically, but are acted upon differently, see 8.2."
  2191. // But 8.2 only describes a difference between intermediate and immediate regions as far as I can tell,
  2192. // and calling the immediate generic region handler for immediate generic lossless regions seems to do the right thing (?).
  2193. TRY(decode_immediate_generic_region(context, segment));
  2194. break;
  2195. case SegmentType::IntermediateGenericRefinementRegion:
  2196. TRY(decode_intermediate_generic_refinement_region(context, segment));
  2197. break;
  2198. case SegmentType::ImmediateGenericRefinementRegion:
  2199. TRY(decode_immediate_generic_refinement_region(context, segment));
  2200. break;
  2201. case SegmentType::ImmediateLosslessGenericRefinementRegion:
  2202. TRY(decode_immediate_lossless_generic_refinement_region(context, segment));
  2203. break;
  2204. case SegmentType::PageInformation:
  2205. TRY(decode_page_information(context, segment));
  2206. break;
  2207. case SegmentType::EndOfPage:
  2208. TRY(decode_end_of_page(context, segment));
  2209. break;
  2210. case SegmentType::EndOfStripe:
  2211. TRY(decode_end_of_stripe(context, segment));
  2212. break;
  2213. case SegmentType::EndOfFile:
  2214. TRY(decode_end_of_file(context, segment));
  2215. // "If a file contains an end of file segment, it must be the last segment."
  2216. if (i != context.segments.size() - 1)
  2217. return Error::from_string_literal("JBIG2ImageDecoderPlugin: End of file segment not last segment");
  2218. break;
  2219. case SegmentType::Profiles:
  2220. TRY(decode_profiles(context, segment));
  2221. break;
  2222. case SegmentType::Tables:
  2223. TRY(decode_tables(context, segment));
  2224. break;
  2225. case SegmentType::ColorPalette:
  2226. TRY(decode_color_palette(context, segment));
  2227. break;
  2228. case SegmentType::Extension:
  2229. TRY(decode_extension(context, segment));
  2230. break;
  2231. }
  2232. }
  2233. return {};
  2234. }
  2235. JBIG2ImageDecoderPlugin::JBIG2ImageDecoderPlugin()
  2236. {
  2237. m_context = make<JBIG2LoadingContext>();
  2238. }
  2239. IntSize JBIG2ImageDecoderPlugin::size()
  2240. {
  2241. return m_context->page.size;
  2242. }
  2243. bool JBIG2ImageDecoderPlugin::sniff(ReadonlyBytes data)
  2244. {
  2245. return data.starts_with(id_string);
  2246. }
  2247. ErrorOr<NonnullOwnPtr<ImageDecoderPlugin>> JBIG2ImageDecoderPlugin::create(ReadonlyBytes data)
  2248. {
  2249. auto plugin = TRY(adopt_nonnull_own_or_enomem(new (nothrow) JBIG2ImageDecoderPlugin()));
  2250. TRY(decode_jbig2_header(*plugin->m_context, data));
  2251. data = data.slice(sizeof(id_string) + sizeof(u8) + (plugin->m_context->number_of_pages.has_value() ? sizeof(u32) : 0));
  2252. TRY(decode_segment_headers(*plugin->m_context, data));
  2253. TRY(scan_for_page_size(*plugin->m_context));
  2254. return plugin;
  2255. }
  2256. ErrorOr<ImageFrameDescriptor> JBIG2ImageDecoderPlugin::frame(size_t index, Optional<IntSize>)
  2257. {
  2258. // FIXME: Use this for multi-page JBIG2 files?
  2259. if (index != 0)
  2260. return Error::from_string_literal("JBIG2ImageDecoderPlugin: Invalid frame index");
  2261. if (m_context->state == JBIG2LoadingContext::State::Error)
  2262. return Error::from_string_literal("JBIG2ImageDecoderPlugin: Decoding failed");
  2263. if (m_context->state < JBIG2LoadingContext::State::Decoded) {
  2264. auto result = decode_data(*m_context);
  2265. if (result.is_error()) {
  2266. m_context->state = JBIG2LoadingContext::State::Error;
  2267. return result.release_error();
  2268. }
  2269. m_context->state = JBIG2LoadingContext::State::Decoded;
  2270. }
  2271. auto bitmap = TRY(m_context->page.bits->to_gfx_bitmap());
  2272. return ImageFrameDescriptor { move(bitmap), 0 };
  2273. }
  2274. ErrorOr<ByteBuffer> JBIG2ImageDecoderPlugin::decode_embedded(Vector<ReadonlyBytes> data)
  2275. {
  2276. auto plugin = TRY(adopt_nonnull_own_or_enomem(new (nothrow) JBIG2ImageDecoderPlugin()));
  2277. plugin->m_context->organization = Organization::Embedded;
  2278. for (auto const& segment_data : data)
  2279. TRY(decode_segment_headers(*plugin->m_context, segment_data));
  2280. TRY(scan_for_page_size(*plugin->m_context));
  2281. TRY(decode_data(*plugin->m_context));
  2282. return plugin->m_context->page.bits->to_byte_buffer();
  2283. }
  2284. }