JBIG2Loader.cpp 115 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575
  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.7.2 Input parameters
  1535. // Table 24 – Parameters for the pattern dictionary decoding procedure
  1536. struct PatternDictionaryDecodingInputParameters {
  1537. bool uses_mmr { false }; // "HDMMR" in spec.
  1538. u32 width { 0 }; // "HDPW" in spec.
  1539. u32 height { 0 }; // "HDPH" in spec.
  1540. u32 gray_max { 0 }; // "GRAYMAX" in spec.
  1541. u8 hd_template { 0 }; // "HDTEMPLATE" in spec.
  1542. };
  1543. // 6.7 Pattern Dictionary Decoding Procedure
  1544. static ErrorOr<Vector<NonnullRefPtr<Symbol>>> pattern_dictionary_decoding_procedure(PatternDictionaryDecodingInputParameters const& inputs, ReadonlyBytes data, Vector<JBIG2::ArithmeticDecoder::Context>& contexts)
  1545. {
  1546. // Table 27 – Parameters used to decode a pattern dictionary's collective bitmap
  1547. GenericRegionDecodingInputParameters generic_inputs;
  1548. generic_inputs.is_modified_modified_read = inputs.uses_mmr;
  1549. generic_inputs.region_width = (inputs.gray_max + 1) * inputs.width;
  1550. generic_inputs.region_height = inputs.height;
  1551. generic_inputs.gb_template = inputs.hd_template;
  1552. generic_inputs.is_typical_prediction_used = false;
  1553. generic_inputs.is_extended_reference_template_used = false; // Missing from spec in table 27.
  1554. generic_inputs.skip_pattern = OptionalNone {};
  1555. generic_inputs.adaptive_template_pixels[0].x = -inputs.width;
  1556. generic_inputs.adaptive_template_pixels[0].y = 0;
  1557. generic_inputs.adaptive_template_pixels[1].x = -3;
  1558. generic_inputs.adaptive_template_pixels[1].y = -1;
  1559. generic_inputs.adaptive_template_pixels[2].x = 2;
  1560. generic_inputs.adaptive_template_pixels[2].y = -2;
  1561. generic_inputs.adaptive_template_pixels[3].x = -2;
  1562. generic_inputs.adaptive_template_pixels[3].y = -2;
  1563. Optional<JBIG2::ArithmeticDecoder> decoder;
  1564. if (!inputs.uses_mmr) {
  1565. decoder = TRY(JBIG2::ArithmeticDecoder::initialize(data));
  1566. generic_inputs.arithmetic_decoder = &decoder.value();
  1567. }
  1568. auto bitmap = TRY(generic_region_decoding_procedure(generic_inputs, data, contexts));
  1569. Vector<NonnullRefPtr<Symbol>> patterns;
  1570. for (u32 gray = 0; gray <= inputs.gray_max; ++gray) {
  1571. int x = gray * inputs.width;
  1572. auto pattern = TRY(bitmap->subbitmap({ x, 0, static_cast<int>(inputs.width), static_cast<int>(inputs.height) }));
  1573. patterns.append(Symbol::create(move(pattern)));
  1574. }
  1575. dbgln_if(JBIG2_DEBUG, "Pattern dictionary: {} patterns", patterns.size());
  1576. return patterns;
  1577. }
  1578. static ErrorOr<void> decode_symbol_dictionary(JBIG2LoadingContext& context, SegmentData& segment)
  1579. {
  1580. // 7.4.2 Symbol dictionary segment syntax
  1581. // 7.4.2.1 Symbol dictionary segment data header
  1582. FixedMemoryStream stream(segment.data);
  1583. // 7.4.2.1.1 Symbol dictionary flags
  1584. u16 flags = TRY(stream.read_value<BigEndian<u16>>());
  1585. bool uses_huffman_encoding = (flags & 1) != 0; // "SDHUFF" in spec.
  1586. bool uses_refinement_or_aggregate_coding = (flags & 2) != 0; // "SDREFAGG" in spec.
  1587. u8 huffman_table_selection_for_height_differences = (flags >> 2) & 0b11; // "SDHUFFDH" in spec.
  1588. if (huffman_table_selection_for_height_differences == 2)
  1589. return Error::from_string_literal("JBIG2ImageDecoderPlugin: Invalid huffman_table_selection_for_height_differences");
  1590. if (!uses_huffman_encoding && huffman_table_selection_for_height_differences != 0)
  1591. return Error::from_string_literal("JBIG2ImageDecoderPlugin: Invalid huffman_table_selection_for_height_differences");
  1592. u8 huffman_table_selection_for_width_differences = (flags >> 4) & 0b11; // "SDHUFFDW" in spec.
  1593. if (huffman_table_selection_for_width_differences == 2)
  1594. return Error::from_string_literal("JBIG2ImageDecoderPlugin: Invalid huffman_table_selection_for_width_differences");
  1595. if (!uses_huffman_encoding && huffman_table_selection_for_width_differences != 0)
  1596. return Error::from_string_literal("JBIG2ImageDecoderPlugin: Invalid huffman_table_selection_for_width_differences");
  1597. bool uses_user_supplied_size_table = (flags >> 6) & 1; // "SDHUFFBMSIZE" in spec.
  1598. if (!uses_huffman_encoding && uses_user_supplied_size_table)
  1599. return Error::from_string_literal("JBIG2ImageDecoderPlugin: Invalid uses_user_supplied_size_table");
  1600. bool uses_user_supplied_aggregate_table = (flags >> 7) & 1; // "SDHUFFAGGINST" in spec.
  1601. if (!uses_huffman_encoding && uses_user_supplied_aggregate_table)
  1602. return Error::from_string_literal("JBIG2ImageDecoderPlugin: Invalid uses_user_supplied_aggregate_table");
  1603. bool bitmap_coding_context_used = (flags >> 8) & 1;
  1604. if (uses_huffman_encoding && !uses_refinement_or_aggregate_coding && bitmap_coding_context_used)
  1605. return Error::from_string_literal("JBIG2ImageDecoderPlugin: Invalid bitmap_coding_context_used");
  1606. bool bitmap_coding_context_retained = (flags >> 9) & 1;
  1607. if (uses_huffman_encoding && !uses_refinement_or_aggregate_coding && bitmap_coding_context_retained)
  1608. return Error::from_string_literal("JBIG2ImageDecoderPlugin: Invalid bitmap_coding_context_retained");
  1609. u8 template_used = (flags >> 10) & 0b11; // "SDTEMPLATE" in spec.
  1610. if (uses_huffman_encoding && template_used != 0)
  1611. return Error::from_string_literal("JBIG2ImageDecoderPlugin: Invalid template_used");
  1612. u8 refinement_template_used = (flags >> 12) & 0b11; // "SDREFTEMPLATE" in spec.
  1613. if (!uses_refinement_or_aggregate_coding && refinement_template_used != 0)
  1614. return Error::from_string_literal("JBIG2ImageDecoderPlugin: Invalid refinement_template_used");
  1615. if (flags & 0b1110'0000'0000'0000)
  1616. return Error::from_string_literal("JBIG2ImageDecoderPlugin: Invalid symbol dictionary flags");
  1617. // 7.4.2.1.2 Symbol dictionary AT flags
  1618. Array<AdaptiveTemplatePixel, 4> adaptive_template {};
  1619. if (!uses_huffman_encoding) {
  1620. int number_of_adaptive_template_pixels = template_used == 0 ? 4 : 1;
  1621. for (int i = 0; i < number_of_adaptive_template_pixels; ++i) {
  1622. adaptive_template[i].x = TRY(stream.read_value<i8>());
  1623. adaptive_template[i].y = TRY(stream.read_value<i8>());
  1624. }
  1625. }
  1626. // 7.4.2.1.3 Symbol dictionary refinement AT flags
  1627. Array<AdaptiveTemplatePixel, 2> adaptive_refinement_template {};
  1628. if (uses_refinement_or_aggregate_coding && refinement_template_used == 0) {
  1629. for (size_t i = 0; i < adaptive_refinement_template.size(); ++i) {
  1630. adaptive_refinement_template[i].x = TRY(stream.read_value<i8>());
  1631. adaptive_refinement_template[i].y = TRY(stream.read_value<i8>());
  1632. }
  1633. }
  1634. // 7.4.2.1.4 Number of exported symbols (SDNUMEXSYMS)
  1635. u32 number_of_exported_symbols = TRY(stream.read_value<BigEndian<u32>>());
  1636. // 7.4.2.1.5 Number of new symbols (SDNUMNEWSYMS)
  1637. u32 number_of_new_symbols = TRY(stream.read_value<BigEndian<u32>>());
  1638. dbgln_if(JBIG2_DEBUG, "Symbol dictionary: uses_huffman_encoding={}", uses_huffman_encoding);
  1639. dbgln_if(JBIG2_DEBUG, "Symbol dictionary: uses_refinement_or_aggregate_coding={}", uses_refinement_or_aggregate_coding);
  1640. dbgln_if(JBIG2_DEBUG, "Symbol dictionary: huffman_table_selection_for_height_differences={}", huffman_table_selection_for_height_differences);
  1641. dbgln_if(JBIG2_DEBUG, "Symbol dictionary: huffman_table_selection_for_width_differences={}", huffman_table_selection_for_width_differences);
  1642. dbgln_if(JBIG2_DEBUG, "Symbol dictionary: uses_user_supplied_size_table={}", uses_user_supplied_size_table);
  1643. dbgln_if(JBIG2_DEBUG, "Symbol dictionary: uses_user_supplied_aggregate_table={}", uses_user_supplied_aggregate_table);
  1644. dbgln_if(JBIG2_DEBUG, "Symbol dictionary: bitmap_coding_context_used={}", bitmap_coding_context_used);
  1645. dbgln_if(JBIG2_DEBUG, "Symbol dictionary: bitmap_coding_context_retained={}", bitmap_coding_context_retained);
  1646. dbgln_if(JBIG2_DEBUG, "Symbol dictionary: template_used={}", template_used);
  1647. dbgln_if(JBIG2_DEBUG, "Symbol dictionary: refinement_template_used={}", refinement_template_used);
  1648. dbgln_if(JBIG2_DEBUG, "Symbol dictionary: number_of_exported_symbols={}", number_of_exported_symbols);
  1649. dbgln_if(JBIG2_DEBUG, "Symbol dictionary: number_of_new_symbols={}", number_of_new_symbols);
  1650. // 7.4.2.1.6 Symbol dictionary segment Huffman table selection
  1651. // FIXME
  1652. // 7.4.2.2 Decoding a symbol dictionary segment
  1653. // "1) Interpret its header, as described in 7.4.2.1."
  1654. // Done!
  1655. // "2) Decode (or retrieve the results of decoding) any referred-to symbol dictionary and tables segments."
  1656. Vector<NonnullRefPtr<Symbol>> symbols;
  1657. for (auto referred_to_segment_number : segment.header.referred_to_segment_numbers) {
  1658. auto opt_referred_to_segment = context.segments_by_number.get(referred_to_segment_number);
  1659. if (!opt_referred_to_segment.has_value())
  1660. return Error::from_string_literal("JBIG2ImageDecoderPlugin: Symbol segment refers to non-existent segment");
  1661. dbgln_if(JBIG2_DEBUG, "Symbol segment refers to segment id {} index {}", referred_to_segment_number, opt_referred_to_segment.value());
  1662. auto const& referred_to_segment = context.segments[opt_referred_to_segment.value()];
  1663. if (!referred_to_segment.symbols.has_value())
  1664. return Error::from_string_literal("JBIG2ImageDecoderPlugin: Symbol segment referred-to segment without symbols");
  1665. symbols.extend(referred_to_segment.symbols.value());
  1666. }
  1667. // "3) If the "bitmap coding context used" bit in the header was 1, ..."
  1668. if (bitmap_coding_context_used)
  1669. return Error::from_string_literal("JBIG2ImageDecoderPlugin: Cannot decode bitmap coding context segment yet");
  1670. // "4) If the "bitmap coding context used" bit in the header was 0, then, as described in E.3.7,
  1671. // reset all the arithmetic coding statistics for the generic region and generic refinement region decoding procedures to zero."
  1672. // Nothing to do.
  1673. // "5) Reset the arithmetic coding statistics for all the contexts of all the arithmetic integer coders to zero."
  1674. // FIXME
  1675. // "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."
  1676. SymbolDictionaryDecodingInputParameters inputs;
  1677. inputs.uses_huffman_encoding = uses_huffman_encoding;
  1678. inputs.uses_refinement_or_aggregate_coding = uses_refinement_or_aggregate_coding;
  1679. inputs.input_symbols = move(symbols);
  1680. inputs.number_of_new_symbols = number_of_new_symbols;
  1681. inputs.number_of_exported_symbols = number_of_exported_symbols;
  1682. // FIXME: SDHUFFDH, SDHUFFDW, SDHUFFBMSIZE, SDHUFFAGGINST
  1683. inputs.symbol_template = template_used;
  1684. inputs.adaptive_template_pixels = adaptive_template;
  1685. inputs.refinement_template = refinement_template_used;
  1686. inputs.refinement_adaptive_template_pixels = adaptive_refinement_template;
  1687. auto result = TRY(symbol_dictionary_decoding_procedure(inputs, segment.data.slice(TRY(stream.tell()))));
  1688. // "7) If the "bitmap coding context retained" bit in the header was 1, then, as described in E.3.8, preserve the current contents
  1689. // of the arithmetic coding statistics for the generic region and generic refinement region decoding procedures."
  1690. if (bitmap_coding_context_retained)
  1691. return Error::from_string_literal("JBIG2ImageDecoderPlugin: Cannot retain bitmap coding context yet");
  1692. segment.symbols = move(result);
  1693. return {};
  1694. }
  1695. static ErrorOr<void> decode_intermediate_text_region(JBIG2LoadingContext&, SegmentData const&)
  1696. {
  1697. return Error::from_string_literal("JBIG2ImageDecoderPlugin: Cannot decode intermediate text region yet");
  1698. }
  1699. static ErrorOr<void> decode_immediate_text_region(JBIG2LoadingContext& context, SegmentData const& segment)
  1700. {
  1701. // 7.4.3 Text region segment syntax
  1702. auto data = segment.data;
  1703. auto information_field = TRY(decode_region_segment_information_field(data));
  1704. data = data.slice(sizeof(information_field));
  1705. 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);
  1706. FixedMemoryStream stream(data);
  1707. // 7.4.3.1.1 Text region segment flags
  1708. u16 text_region_segment_flags = TRY(stream.read_value<BigEndian<u16>>());
  1709. bool uses_huffman_encoding = (text_region_segment_flags & 1) != 0; // "SBHUFF" in spec.
  1710. bool uses_refinement_coding = (text_region_segment_flags >> 1) & 1; // "SBREFINE" in spec.
  1711. u8 log_strip_size = (text_region_segment_flags >> 2) & 3; // "LOGSBSTRIPS" in spec.
  1712. u8 strip_size = 1u << log_strip_size;
  1713. u8 reference_corner = (text_region_segment_flags >> 4) & 3; // "REFCORNER"
  1714. bool is_transposed = (text_region_segment_flags >> 6) & 1; // "TRANSPOSED" in spec.
  1715. u8 combination_operator = (text_region_segment_flags >> 7) & 3; // "SBCOMBOP" in spec.
  1716. if (combination_operator > 4)
  1717. return Error::from_string_literal("JBIG2ImageDecoderPlugin: Invalid text region combination operator");
  1718. u8 default_pixel_value = (text_region_segment_flags >> 9) & 1; // "SBDEFPIXEL" in spec.
  1719. u8 delta_s_offset_value = (text_region_segment_flags >> 10) & 0x1f; // "SBDSOFFSET" in spec.
  1720. i8 delta_s_offset = delta_s_offset_value;
  1721. if (delta_s_offset_value & 0x10) {
  1722. // This is converting a 5-bit two's complement number ot i8.
  1723. // FIXME: There's probably a simpler way to do this? Probably just sign-extend by or-ing in the top 3 bits?
  1724. delta_s_offset_value = (~delta_s_offset_value + 1) & 0x1f;
  1725. delta_s_offset = -delta_s_offset_value;
  1726. }
  1727. u8 refinement_template = (text_region_segment_flags >> 15) != 0; // "SBRTEMPLATE" in spec.
  1728. if (!uses_refinement_coding && refinement_template != 0)
  1729. return Error::from_string_literal("JBIG2ImageDecoderPlugin: Invalid refinement_template");
  1730. // 7.4.3.1.2 Text region segment Huffman flags
  1731. // "This field is only present if SBHUFF is 1."
  1732. // FIXME: Support this eventually.
  1733. if (uses_huffman_encoding)
  1734. return Error::from_string_literal("JBIG2ImageDecoderPlugin: Cannot decode huffman text regions yet");
  1735. // 7.4.3.1.3 Text region refinement AT flags
  1736. // "This field is only present if SBREFINE is 1 and SBRTEMPLATE is 0."
  1737. Array<AdaptiveTemplatePixel, 2> adaptive_refinement_template {};
  1738. if (uses_refinement_coding && refinement_template == 0) {
  1739. for (size_t i = 0; i < adaptive_refinement_template.size(); ++i) {
  1740. adaptive_refinement_template[i].x = TRY(stream.read_value<i8>());
  1741. adaptive_refinement_template[i].y = TRY(stream.read_value<i8>());
  1742. }
  1743. }
  1744. // 7.4.3.1.4 Number of symbol instances (SBNUMINSTANCES)
  1745. u32 number_of_symbol_instances = TRY(stream.read_value<BigEndian<u32>>());
  1746. // 7.4.3.1.5 Text region segment symbol ID Huffman decoding table
  1747. // "It is only present if SBHUFF is 1."
  1748. // FIXME: Support this eventually.
  1749. 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);
  1750. 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);
  1751. dbgln_if(JBIG2_DEBUG, "Text region: number_of_symbol_instances={}", number_of_symbol_instances);
  1752. // 7.4.3.2 Decoding a text region segment
  1753. // "1) Interpret its header, as described in 7.4.3.1."
  1754. // Done!
  1755. // "2) Decode (or retrieve the results of decoding) any referred-to symbol dictionary and tables segments."
  1756. Vector<NonnullRefPtr<Symbol>> symbols;
  1757. for (auto referred_to_segment_number : segment.header.referred_to_segment_numbers) {
  1758. auto opt_referred_to_segment = context.segments_by_number.get(referred_to_segment_number);
  1759. if (!opt_referred_to_segment.has_value())
  1760. return Error::from_string_literal("JBIG2ImageDecoderPlugin: Text segment refers to non-existent segment");
  1761. dbgln_if(JBIG2_DEBUG, "Text segment refers to segment id {} index {}", referred_to_segment_number, opt_referred_to_segment.value());
  1762. auto const& referred_to_segment = context.segments[opt_referred_to_segment.value()];
  1763. if (!referred_to_segment.symbols.has_value())
  1764. return Error::from_string_literal("JBIG2ImageDecoderPlugin: Text segment referred-to segment without symbols");
  1765. symbols.extend(referred_to_segment.symbols.value());
  1766. }
  1767. // "3) As described in E.3.7, reset all the arithmetic coding statistics to zero."
  1768. // FIXME
  1769. // "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."
  1770. TextRegionDecodingInputParameters inputs;
  1771. inputs.uses_huffman_encoding = uses_huffman_encoding;
  1772. inputs.uses_refinement_coding = uses_refinement_coding;
  1773. inputs.default_pixel = default_pixel_value;
  1774. inputs.operator_ = static_cast<CombinationOperator>(combination_operator);
  1775. inputs.is_transposed = is_transposed;
  1776. inputs.reference_corner = static_cast<TextRegionDecodingInputParameters::Corner>(reference_corner);
  1777. inputs.delta_s_offset = delta_s_offset;
  1778. inputs.region_width = information_field.width;
  1779. inputs.region_height = information_field.height;
  1780. inputs.number_of_instances = number_of_symbol_instances;
  1781. inputs.size_of_symbol_instance_strips = strip_size;
  1782. inputs.id_symbol_code_length = ceil(log2(symbols.size()));
  1783. inputs.symbols = move(symbols);
  1784. // FIXME: Huffman tables.
  1785. inputs.refinement_template = refinement_template;
  1786. inputs.refinement_adaptive_template_pixels = adaptive_refinement_template;
  1787. auto result = TRY(text_region_decoding_procedure(inputs, data.slice(TRY(stream.tell()))));
  1788. composite_bitbuffer(*context.page.bits, *result, { information_field.x_location, information_field.y_location }, information_field.external_combination_operator());
  1789. return {};
  1790. }
  1791. static ErrorOr<void> decode_pattern_dictionary(JBIG2LoadingContext&, SegmentData& segment)
  1792. {
  1793. // 7.4.4 Pattern dictionary segment syntax
  1794. FixedMemoryStream stream(segment.data);
  1795. // 7.4.4.1.1 Pattern dictionary flags
  1796. u8 flags = TRY(stream.read_value<u8>());
  1797. bool uses_mmr = flags & 1;
  1798. u8 hd_template = (flags >> 1) & 3;
  1799. if (uses_mmr && hd_template != 0)
  1800. return Error::from_string_literal("JBIG2ImageDecoderPlugin: Invalid hd_template");
  1801. if (flags & 0b1111'1000)
  1802. return Error::from_string_literal("JBIG2ImageDecoderPlugin: Invalid flags");
  1803. // 7.4.4.1.2 Width of the patterns in the pattern dictionary (HDPW)
  1804. u8 width = TRY(stream.read_value<u8>());
  1805. if (width == 0)
  1806. return Error::from_string_literal("JBIG2ImageDecoderPlugin: Invalid width");
  1807. // 7.4.4.1.3 Height of the patterns in the pattern dictionary (HDPH)
  1808. u8 height = TRY(stream.read_value<u8>());
  1809. if (height == 0)
  1810. return Error::from_string_literal("JBIG2ImageDecoderPlugin: Invalid height");
  1811. // 7.4.4.1.4 Largest gray-scale value (GRAYMAX)
  1812. u32 gray_max = TRY(stream.read_value<BigEndian<u32>>());
  1813. // 7.4.4.2 Decoding a pattern dictionary segment
  1814. dbgln_if(JBIG2_DEBUG, "Pattern dictionary: uses_mmr={}, hd_template={}, width={}, height={}, gray_max={}", uses_mmr, hd_template, width, height, gray_max);
  1815. auto data = segment.data.slice(TRY(stream.tell()));
  1816. // "1) Interpret its header, as described in 7.4.4.1."
  1817. // Done!
  1818. // "2) As described in E.3.7, reset all the arithmetic coding statistics to zero."
  1819. Vector<JBIG2::ArithmeticDecoder::Context> contexts;
  1820. if (!uses_mmr)
  1821. contexts.resize(1 << number_of_context_bits_for_template(hd_template));
  1822. // "3) Invoke the pattern dictionary decoding procedure described in 6.7, with the parameters to the pattern
  1823. // dictionary decoding procedure set as shown in Table 35."
  1824. PatternDictionaryDecodingInputParameters inputs;
  1825. inputs.uses_mmr = uses_mmr;
  1826. inputs.width = width;
  1827. inputs.height = height;
  1828. inputs.gray_max = gray_max;
  1829. inputs.hd_template = hd_template;
  1830. auto result = TRY(pattern_dictionary_decoding_procedure(inputs, data, contexts));
  1831. segment.patterns = move(result);
  1832. return {};
  1833. }
  1834. static ErrorOr<void> decode_intermediate_halftone_region(JBIG2LoadingContext&, SegmentData const&)
  1835. {
  1836. return Error::from_string_literal("JBIG2ImageDecoderPlugin: Cannot decode intermediate halftone region yet");
  1837. }
  1838. static ErrorOr<void> decode_immediate_halftone_region(JBIG2LoadingContext&, SegmentData const&)
  1839. {
  1840. return Error::from_string_literal("JBIG2ImageDecoderPlugin: Cannot decode immediate halftone region yet");
  1841. }
  1842. static ErrorOr<void> decode_immediate_lossless_halftone_region(JBIG2LoadingContext&, SegmentData const&)
  1843. {
  1844. return Error::from_string_literal("JBIG2ImageDecoderPlugin: Cannot decode immediate lossless halftone region yet");
  1845. }
  1846. static ErrorOr<void> decode_intermediate_generic_region(JBIG2LoadingContext&, SegmentData const&)
  1847. {
  1848. return Error::from_string_literal("JBIG2ImageDecoderPlugin: Cannot decode intermediate generic region yet");
  1849. }
  1850. static ErrorOr<void> decode_immediate_generic_region(JBIG2LoadingContext& context, SegmentData const& segment)
  1851. {
  1852. // 7.4.6 Generic region segment syntax
  1853. auto data = segment.data;
  1854. auto information_field = TRY(decode_region_segment_information_field(data));
  1855. data = data.slice(sizeof(information_field));
  1856. 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);
  1857. // 7.4.6.2 Generic region segment flags
  1858. if (data.is_empty())
  1859. return Error::from_string_literal("JBIG2ImageDecoderPlugin: No segment data");
  1860. u8 flags = data[0];
  1861. bool uses_mmr = (flags & 1) != 0;
  1862. u8 arithmetic_coding_template = (flags >> 1) & 3; // "GBTEMPLATE"
  1863. bool typical_prediction_generic_decoding_on = (flags >> 3) & 1; // "TPGDON"; "TPGD" is short for "Typical Prediction for Generic Direct coding"
  1864. bool uses_extended_reference_template = (flags >> 4) & 1; // "EXTTEMPLATE"
  1865. if (flags & 0b1110'0000)
  1866. return Error::from_string_literal("JBIG2ImageDecoderPlugin: Invalid flags");
  1867. data = data.slice(sizeof(flags));
  1868. // 7.4.6.3 Generic region segment AT flags
  1869. Array<AdaptiveTemplatePixel, 12> adaptive_template_pixels {};
  1870. if (!uses_mmr) {
  1871. dbgln_if(JBIG2_DEBUG, "Non-MMR generic region, GBTEMPLATE={} TPGDON={} EXTTEMPLATE={}", arithmetic_coding_template, typical_prediction_generic_decoding_on, uses_extended_reference_template);
  1872. if (arithmetic_coding_template == 0 && uses_extended_reference_template) {
  1873. // This was added in T.88 Amendment 2 (https://www.itu.int/rec/T-REC-T.88-200306-S!Amd2/en) mid-2003.
  1874. // 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,
  1875. // so it's not clear how much data to read.
  1876. return Error::from_string_literal("JBIG2ImageDecoderPlugin: GBTEMPLATE=0 EXTTEMPLATE=1 not yet implemented");
  1877. }
  1878. size_t number_of_adaptive_template_pixels = arithmetic_coding_template == 0 ? 4 : 1;
  1879. if (data.size() < 2 * number_of_adaptive_template_pixels)
  1880. return Error::from_string_literal("JBIG2ImageDecoderPlugin: No adaptive template data");
  1881. for (size_t i = 0; i < number_of_adaptive_template_pixels; ++i) {
  1882. adaptive_template_pixels[i].x = static_cast<i8>(data[2 * i]);
  1883. adaptive_template_pixels[i].y = static_cast<i8>(data[2 * i + 1]);
  1884. }
  1885. data = data.slice(2 * number_of_adaptive_template_pixels);
  1886. }
  1887. // 7.4.6.4 Decoding a generic region segment
  1888. // "1) Interpret its header, as described in 7.4.6.1"
  1889. // Done above.
  1890. // "2) As described in E.3.7, reset all the arithmetic coding statistics to zero."
  1891. Vector<JBIG2::ArithmeticDecoder::Context> contexts;
  1892. if (!uses_mmr)
  1893. contexts.resize(1 << number_of_context_bits_for_template(arithmetic_coding_template));
  1894. // "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."
  1895. GenericRegionDecodingInputParameters inputs;
  1896. inputs.is_modified_modified_read = uses_mmr;
  1897. inputs.region_width = information_field.width;
  1898. inputs.region_height = information_field.height;
  1899. inputs.gb_template = arithmetic_coding_template;
  1900. inputs.is_typical_prediction_used = typical_prediction_generic_decoding_on;
  1901. inputs.is_extended_reference_template_used = uses_extended_reference_template;
  1902. inputs.skip_pattern = OptionalNone {};
  1903. inputs.adaptive_template_pixels = adaptive_template_pixels;
  1904. Optional<JBIG2::ArithmeticDecoder> decoder;
  1905. if (!uses_mmr) {
  1906. decoder = TRY(JBIG2::ArithmeticDecoder::initialize(data));
  1907. inputs.arithmetic_decoder = &decoder.value();
  1908. }
  1909. auto result = TRY(generic_region_decoding_procedure(inputs, data, contexts));
  1910. // 8.2 Page image composition step 5)
  1911. if (information_field.x_location + information_field.width > (u32)context.page.size.width()
  1912. || information_field.y_location + information_field.height > (u32)context.page.size.height()) {
  1913. return Error::from_string_literal("JBIG2ImageDecoderPlugin: Region bounds outsize of page bounds");
  1914. }
  1915. composite_bitbuffer(*context.page.bits, *result, { information_field.x_location, information_field.y_location }, information_field.external_combination_operator());
  1916. return {};
  1917. }
  1918. static ErrorOr<void> decode_intermediate_generic_refinement_region(JBIG2LoadingContext&, SegmentData const&)
  1919. {
  1920. return Error::from_string_literal("JBIG2ImageDecoderPlugin: Cannot decode intermediate generic refinement region yet");
  1921. }
  1922. static ErrorOr<void> decode_immediate_generic_refinement_region(JBIG2LoadingContext&, SegmentData const&)
  1923. {
  1924. return Error::from_string_literal("JBIG2ImageDecoderPlugin: Cannot decode immediate generic refinement region yet");
  1925. }
  1926. static ErrorOr<void> decode_immediate_lossless_generic_refinement_region(JBIG2LoadingContext&, SegmentData const&)
  1927. {
  1928. return Error::from_string_literal("JBIG2ImageDecoderPlugin: Cannot decode immediate lossless generic refinement region yet");
  1929. }
  1930. static ErrorOr<void> decode_page_information(JBIG2LoadingContext& context, SegmentData const& segment)
  1931. {
  1932. // 7.4.8 Page information segment syntax and 8.1 Decoder model steps 1) - 3).
  1933. // "1) Decode the page information segment.""
  1934. auto page_information = TRY(decode_page_information_segment(segment.data));
  1935. bool page_is_striped = (page_information.striping_information & 0x80) != 0;
  1936. if (page_information.bitmap_height == 0xffff'ffff && !page_is_striped)
  1937. return Error::from_string_literal("JBIG2ImageDecoderPlugin: Non-striped bitmaps of indeterminate height not allowed");
  1938. u16 maximum_stripe_height = page_information.striping_information & 0x7F;
  1939. u8 default_color = (page_information.flags >> 2) & 1;
  1940. u8 default_combination_operator = (page_information.flags >> 3) & 3;
  1941. context.page.default_combination_operator = static_cast<CombinationOperator>(default_combination_operator);
  1942. 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);
  1943. // FIXME: Do something with the other fields in page_information.
  1944. // "2) Create the page buffer, of the size given in the page information segment.
  1945. //
  1946. // If the page height is unknown, then this is not possible. However, in this case the page must be striped,
  1947. // and the maximum stripe height specified, and the initial page buffer can be created with height initially
  1948. // equal to this maximum stripe height."
  1949. size_t height = page_information.bitmap_height;
  1950. if (height == 0xffff'ffff)
  1951. height = maximum_stripe_height;
  1952. context.page.bits = TRY(BitBuffer::create(page_information.bitmap_width, height));
  1953. // "3) Fill the page buffer with the page's default pixel value."
  1954. context.page.bits->fill(default_color != 0);
  1955. return {};
  1956. }
  1957. static ErrorOr<void> decode_end_of_page(JBIG2LoadingContext&, SegmentData const& segment)
  1958. {
  1959. // 7.4.9 End of page segment syntax
  1960. if (segment.data.size() != 0)
  1961. return Error::from_string_literal("JBIG2ImageDecoderPlugin: End of page segment has non-zero size");
  1962. // FIXME: If the page had unknown height, check that previous segment was end-of-stripe.
  1963. // FIXME: Maybe mark page as completed and error if we see more segments for it?
  1964. return {};
  1965. }
  1966. static ErrorOr<void> decode_end_of_stripe(JBIG2LoadingContext&, SegmentData const& segment)
  1967. {
  1968. // 7.4.10 End of stripe segment syntax
  1969. // "The segment data of an end of stripe segment consists of one four-byte value, specifying the Y coordinate of the end row."
  1970. if (segment.data.size() != 4)
  1971. return Error::from_string_literal("JBIG2ImageDecoderPlugin: End of strip segment has wrong size");
  1972. // FIXME: Once we implement support for images with initially indeterminate height, we need these values to determine the height at the end.
  1973. u32 y_coordinate = *reinterpret_cast<BigEndian<u32> const*>(segment.data.data());
  1974. dbgln_if(JBIG2_DEBUG, "End of stripe: y={}", y_coordinate);
  1975. return {};
  1976. }
  1977. static ErrorOr<void> decode_end_of_file(JBIG2LoadingContext&, SegmentData const& segment)
  1978. {
  1979. // 7.4.11 End of file segment syntax
  1980. if (segment.data.size() != 0)
  1981. return Error::from_string_literal("JBIG2ImageDecoderPlugin: End of file segment has non-zero size");
  1982. return {};
  1983. }
  1984. static ErrorOr<void> decode_profiles(JBIG2LoadingContext&, SegmentData const&)
  1985. {
  1986. return Error::from_string_literal("JBIG2ImageDecoderPlugin: Cannot decode profiles yet");
  1987. }
  1988. static ErrorOr<void> decode_tables(JBIG2LoadingContext&, SegmentData const&)
  1989. {
  1990. return Error::from_string_literal("JBIG2ImageDecoderPlugin: Cannot decode tables yet");
  1991. }
  1992. static ErrorOr<void> decode_color_palette(JBIG2LoadingContext&, SegmentData const&)
  1993. {
  1994. return Error::from_string_literal("JBIG2ImageDecoderPlugin: Cannot decode color palette yet");
  1995. }
  1996. static ErrorOr<void> decode_extension(JBIG2LoadingContext&, SegmentData const& segment)
  1997. {
  1998. // 7.4.14 Extension segment syntax
  1999. FixedMemoryStream stream { segment.data };
  2000. enum ExtensionType {
  2001. SingleByteCodedComment = 0x20000000,
  2002. MultiByteCodedComment = 0x20000002,
  2003. };
  2004. u32 type = TRY(stream.read_value<BigEndian<u32>>());
  2005. auto read_string = [&]<class T>() -> ErrorOr<Vector<T>> {
  2006. Vector<T> result;
  2007. do {
  2008. result.append(TRY(stream.read_value<BigEndian<T>>()));
  2009. } while (result.last());
  2010. result.take_last();
  2011. return result;
  2012. };
  2013. switch (type) {
  2014. case SingleByteCodedComment: {
  2015. // 7.4.15.1 Single-byte coded comment
  2016. // Pairs of zero-terminated ISO/IEC 8859-1 (latin1) pairs, terminated by another \0.
  2017. while (true) {
  2018. auto first_bytes = TRY(read_string.template operator()<u8>());
  2019. if (first_bytes.is_empty())
  2020. break;
  2021. auto second_bytes = TRY(read_string.template operator()<u8>());
  2022. auto first = TRY(TextCodec::decoder_for("ISO-8859-1"sv)->to_utf8(StringView { first_bytes }));
  2023. auto second = TRY(TextCodec::decoder_for("ISO-8859-1"sv)->to_utf8(StringView { second_bytes }));
  2024. dbgln("JBIG2ImageDecoderPlugin: key '{}', value '{}'", first, second);
  2025. }
  2026. if (!stream.is_eof())
  2027. return Error::from_string_literal("JBIG2ImageDecoderPlugin: Trailing data after SingleByteCodedComment");
  2028. return {};
  2029. }
  2030. case MultiByteCodedComment: {
  2031. // 7.4.15.2 Multi-byte coded comment
  2032. // Pairs of (two-byte-)zero-terminated UCS-2 pairs, terminated by another \0\0.
  2033. while (true) {
  2034. auto first_ucs2 = TRY(read_string.template operator()<u16>());
  2035. if (first_ucs2.is_empty())
  2036. break;
  2037. auto second_ucs2 = TRY(read_string.template operator()<u16>());
  2038. auto first = TRY(Utf16View(first_ucs2).to_utf8());
  2039. auto second = TRY(Utf16View(second_ucs2).to_utf8());
  2040. dbgln("JBIG2ImageDecoderPlugin: key '{}', value '{}'", first, second);
  2041. }
  2042. if (!stream.is_eof())
  2043. return Error::from_string_literal("JBIG2ImageDecoderPlugin: Trailing data after MultiByteCodedComment");
  2044. return {};
  2045. }
  2046. }
  2047. // FIXME: If bit 31 in `type` is not set, the extension isn't necessary, and we could ignore it.
  2048. dbgln("JBIG2ImageDecoderPlugin: Unknown extension type {:#x}", type);
  2049. return Error::from_string_literal("JBIG2ImageDecoderPlugin: Unknown extension type");
  2050. }
  2051. static ErrorOr<void> decode_data(JBIG2LoadingContext& context)
  2052. {
  2053. TRY(warn_about_multiple_pages(context));
  2054. for (size_t i = 0; i < context.segments.size(); ++i) {
  2055. auto& segment = context.segments[i];
  2056. if (segment.header.page_association != 0 && segment.header.page_association != 1)
  2057. continue;
  2058. switch (segment.header.type) {
  2059. case SegmentType::SymbolDictionary:
  2060. TRY(decode_symbol_dictionary(context, segment));
  2061. break;
  2062. case SegmentType::IntermediateTextRegion:
  2063. TRY(decode_intermediate_text_region(context, segment));
  2064. break;
  2065. case SegmentType::ImmediateTextRegion:
  2066. case SegmentType::ImmediateLosslessTextRegion:
  2067. // 7.4.3 Text region segment syntax
  2068. // "The data parts of all three of the text region segment types ("intermediate text region", "immediate text region" and
  2069. // "immediate lossless text region") are coded identically, but are acted upon differently, see 8.2."
  2070. // But 8.2 only describes a difference between intermediate and immediate regions as far as I can tell,
  2071. // and calling the immediate text region handler for immediate lossless text regions seems to do the right thing (?).
  2072. TRY(decode_immediate_text_region(context, segment));
  2073. break;
  2074. case SegmentType::PatternDictionary:
  2075. TRY(decode_pattern_dictionary(context, segment));
  2076. break;
  2077. case SegmentType::IntermediateHalftoneRegion:
  2078. TRY(decode_intermediate_halftone_region(context, segment));
  2079. break;
  2080. case SegmentType::ImmediateHalftoneRegion:
  2081. TRY(decode_immediate_halftone_region(context, segment));
  2082. break;
  2083. case SegmentType::ImmediateLosslessHalftoneRegion:
  2084. TRY(decode_immediate_lossless_halftone_region(context, segment));
  2085. break;
  2086. case SegmentType::IntermediateGenericRegion:
  2087. TRY(decode_intermediate_generic_region(context, segment));
  2088. break;
  2089. case SegmentType::ImmediateGenericRegion:
  2090. case SegmentType::ImmediateLosslessGenericRegion:
  2091. // 7.4.6 Generic region segment syntax
  2092. // "The data parts of all three of the generic region segment types ("intermediate generic region", "immediate generic region" and
  2093. // "immediate lossless generic region") are coded identically, but are acted upon differently, see 8.2."
  2094. // But 8.2 only describes a difference between intermediate and immediate regions as far as I can tell,
  2095. // and calling the immediate generic region handler for immediate generic lossless regions seems to do the right thing (?).
  2096. TRY(decode_immediate_generic_region(context, segment));
  2097. break;
  2098. case SegmentType::IntermediateGenericRefinementRegion:
  2099. TRY(decode_intermediate_generic_refinement_region(context, segment));
  2100. break;
  2101. case SegmentType::ImmediateGenericRefinementRegion:
  2102. TRY(decode_immediate_generic_refinement_region(context, segment));
  2103. break;
  2104. case SegmentType::ImmediateLosslessGenericRefinementRegion:
  2105. TRY(decode_immediate_lossless_generic_refinement_region(context, segment));
  2106. break;
  2107. case SegmentType::PageInformation:
  2108. TRY(decode_page_information(context, segment));
  2109. break;
  2110. case SegmentType::EndOfPage:
  2111. TRY(decode_end_of_page(context, segment));
  2112. break;
  2113. case SegmentType::EndOfStripe:
  2114. TRY(decode_end_of_stripe(context, segment));
  2115. break;
  2116. case SegmentType::EndOfFile:
  2117. TRY(decode_end_of_file(context, segment));
  2118. // "If a file contains an end of file segment, it must be the last segment."
  2119. if (i != context.segments.size() - 1)
  2120. return Error::from_string_literal("JBIG2ImageDecoderPlugin: End of file segment not last segment");
  2121. break;
  2122. case SegmentType::Profiles:
  2123. TRY(decode_profiles(context, segment));
  2124. break;
  2125. case SegmentType::Tables:
  2126. TRY(decode_tables(context, segment));
  2127. break;
  2128. case SegmentType::ColorPalette:
  2129. TRY(decode_color_palette(context, segment));
  2130. break;
  2131. case SegmentType::Extension:
  2132. TRY(decode_extension(context, segment));
  2133. break;
  2134. }
  2135. }
  2136. return {};
  2137. }
  2138. JBIG2ImageDecoderPlugin::JBIG2ImageDecoderPlugin()
  2139. {
  2140. m_context = make<JBIG2LoadingContext>();
  2141. }
  2142. IntSize JBIG2ImageDecoderPlugin::size()
  2143. {
  2144. return m_context->page.size;
  2145. }
  2146. bool JBIG2ImageDecoderPlugin::sniff(ReadonlyBytes data)
  2147. {
  2148. return data.starts_with(id_string);
  2149. }
  2150. ErrorOr<NonnullOwnPtr<ImageDecoderPlugin>> JBIG2ImageDecoderPlugin::create(ReadonlyBytes data)
  2151. {
  2152. auto plugin = TRY(adopt_nonnull_own_or_enomem(new (nothrow) JBIG2ImageDecoderPlugin()));
  2153. TRY(decode_jbig2_header(*plugin->m_context, data));
  2154. data = data.slice(sizeof(id_string) + sizeof(u8) + (plugin->m_context->number_of_pages.has_value() ? sizeof(u32) : 0));
  2155. TRY(decode_segment_headers(*plugin->m_context, data));
  2156. TRY(scan_for_page_size(*plugin->m_context));
  2157. return plugin;
  2158. }
  2159. ErrorOr<ImageFrameDescriptor> JBIG2ImageDecoderPlugin::frame(size_t index, Optional<IntSize>)
  2160. {
  2161. // FIXME: Use this for multi-page JBIG2 files?
  2162. if (index != 0)
  2163. return Error::from_string_literal("JBIG2ImageDecoderPlugin: Invalid frame index");
  2164. if (m_context->state == JBIG2LoadingContext::State::Error)
  2165. return Error::from_string_literal("JBIG2ImageDecoderPlugin: Decoding failed");
  2166. if (m_context->state < JBIG2LoadingContext::State::Decoded) {
  2167. auto result = decode_data(*m_context);
  2168. if (result.is_error()) {
  2169. m_context->state = JBIG2LoadingContext::State::Error;
  2170. return result.release_error();
  2171. }
  2172. m_context->state = JBIG2LoadingContext::State::Decoded;
  2173. }
  2174. auto bitmap = TRY(m_context->page.bits->to_gfx_bitmap());
  2175. return ImageFrameDescriptor { move(bitmap), 0 };
  2176. }
  2177. ErrorOr<ByteBuffer> JBIG2ImageDecoderPlugin::decode_embedded(Vector<ReadonlyBytes> data)
  2178. {
  2179. auto plugin = TRY(adopt_nonnull_own_or_enomem(new (nothrow) JBIG2ImageDecoderPlugin()));
  2180. plugin->m_context->organization = Organization::Embedded;
  2181. for (auto const& segment_data : data)
  2182. TRY(decode_segment_headers(*plugin->m_context, segment_data));
  2183. TRY(scan_for_page_size(*plugin->m_context));
  2184. TRY(decode_data(*plugin->m_context));
  2185. return plugin->m_context->page.bits->to_byte_buffer();
  2186. }
  2187. }