JBIG2Loader.cpp 110 KB

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