JBIG2Loader.cpp 108 KB

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