JBIG2Loader.cpp 49 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243
  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. }
  200. // JBIG2 spec, Annex D, D.4.1 ID string
  201. static constexpr u8 id_string[] = { 0x97, 0x4A, 0x42, 0x32, 0x0D, 0x0A, 0x1A, 0x0A };
  202. // 7.3 Segment types
  203. enum SegmentType {
  204. SymbolDictionary = 0,
  205. IntermediateTextRegion = 4,
  206. ImmediateTextRegion = 6,
  207. ImmediateLosslessTextRegion = 7,
  208. PatternDictionary = 16,
  209. IntermediateHalftoneRegion = 20,
  210. ImmediateHalftoneRegion = 22,
  211. ImmediateLosslessHalftoneRegion = 23,
  212. IntermediateGenericRegion = 36,
  213. ImmediateGenericRegion = 38,
  214. ImmediateLosslessGenericRegion = 39,
  215. IntermediateGenericRefinementRegion = 40,
  216. ImmediateGenericRefinementRegion = 42,
  217. ImmediateLosslessGenericRefinementRegion = 43,
  218. PageInformation = 48,
  219. EndOfPage = 49,
  220. EndOfStripe = 50,
  221. EndOfFile = 51,
  222. Profiles = 52,
  223. Tables = 53,
  224. ColorPalette = 54,
  225. Extension = 62,
  226. };
  227. // Annex D
  228. enum class Organization {
  229. // D.1 Sequential organization
  230. Sequential,
  231. // D.2 Random-access organization
  232. RandomAccess,
  233. // D.3 Embedded organization
  234. Embedded,
  235. };
  236. struct SegmentHeader {
  237. u32 segment_number { 0 };
  238. SegmentType type { SegmentType::Extension };
  239. Vector<u32> referred_to_segment_numbers;
  240. // 7.2.6 Segment page association
  241. // "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."
  242. u32 page_association { 0 };
  243. Optional<u32> data_length;
  244. };
  245. struct SegmentData {
  246. SegmentHeader header;
  247. ReadonlyBytes data;
  248. };
  249. class BitBuffer {
  250. public:
  251. static ErrorOr<NonnullOwnPtr<BitBuffer>> create(size_t width, size_t height);
  252. bool get_bit(size_t x, size_t y) const;
  253. void set_bit(size_t x, size_t y, bool b);
  254. void fill(bool b);
  255. ErrorOr<NonnullRefPtr<Gfx::Bitmap>> to_gfx_bitmap() const;
  256. ErrorOr<ByteBuffer> to_byte_buffer() const;
  257. private:
  258. BitBuffer(ByteBuffer, size_t width, size_t height, size_t pitch);
  259. ByteBuffer m_bits;
  260. size_t m_width { 0 };
  261. size_t m_height { 0 };
  262. size_t m_pitch { 0 };
  263. };
  264. ErrorOr<NonnullOwnPtr<BitBuffer>> BitBuffer::create(size_t width, size_t height)
  265. {
  266. size_t pitch = ceil_div(width, 8ull);
  267. auto bits = TRY(ByteBuffer::create_uninitialized(pitch * height));
  268. return adopt_nonnull_own_or_enomem(new (nothrow) BitBuffer(move(bits), width, height, pitch));
  269. }
  270. bool BitBuffer::get_bit(size_t x, size_t y) const
  271. {
  272. VERIFY(x < m_width);
  273. VERIFY(y < m_height);
  274. size_t byte_offset = x / 8;
  275. size_t bit_offset = x % 8;
  276. u8 byte = m_bits[y * m_pitch + byte_offset];
  277. byte = (byte >> (8 - 1 - bit_offset)) & 1;
  278. return byte != 0;
  279. }
  280. void BitBuffer::set_bit(size_t x, size_t y, bool b)
  281. {
  282. VERIFY(x < m_width);
  283. VERIFY(y < m_height);
  284. size_t byte_offset = x / 8;
  285. size_t bit_offset = x % 8;
  286. u8 byte = m_bits[y * m_pitch + byte_offset];
  287. u8 mask = 1u << (8 - 1 - bit_offset);
  288. if (b)
  289. byte |= mask;
  290. else
  291. byte &= ~mask;
  292. m_bits[y * m_pitch + byte_offset] = byte;
  293. }
  294. void BitBuffer::fill(bool b)
  295. {
  296. u8 fill_byte = b ? 0xff : 0;
  297. for (auto& byte : m_bits.bytes())
  298. byte = fill_byte;
  299. }
  300. ErrorOr<NonnullRefPtr<Gfx::Bitmap>> BitBuffer::to_gfx_bitmap() const
  301. {
  302. auto bitmap = TRY(Gfx::Bitmap::create(Gfx::BitmapFormat::BGRx8888, { m_width, m_height }));
  303. for (size_t y = 0; y < m_height; ++y) {
  304. for (size_t x = 0; x < m_width; ++x) {
  305. auto color = get_bit(x, y) ? Color::Black : Color::White;
  306. bitmap->set_pixel(x, y, color);
  307. }
  308. }
  309. return bitmap;
  310. }
  311. ErrorOr<ByteBuffer> BitBuffer::to_byte_buffer() const
  312. {
  313. return ByteBuffer::copy(m_bits);
  314. }
  315. BitBuffer::BitBuffer(ByteBuffer bits, size_t width, size_t height, size_t pitch)
  316. : m_bits(move(bits))
  317. , m_width(width)
  318. , m_height(height)
  319. , m_pitch(pitch)
  320. {
  321. }
  322. // 7.4.8.5 Page segment flags
  323. enum class CombinationOperator {
  324. Or = 0,
  325. And = 1,
  326. Xor = 2,
  327. XNor = 3,
  328. };
  329. struct Page {
  330. IntSize size;
  331. CombinationOperator default_combination_operator { CombinationOperator::Or };
  332. OwnPtr<BitBuffer> bits;
  333. };
  334. struct JBIG2LoadingContext {
  335. enum class State {
  336. NotDecoded = 0,
  337. Error,
  338. Decoded,
  339. };
  340. State state { State::NotDecoded };
  341. Organization organization { Organization::Sequential };
  342. Page page;
  343. Optional<u32> number_of_pages;
  344. Vector<SegmentData> segments;
  345. };
  346. static ErrorOr<void> decode_jbig2_header(JBIG2LoadingContext& context, ReadonlyBytes data)
  347. {
  348. if (!JBIG2ImageDecoderPlugin::sniff(data))
  349. return Error::from_string_literal("JBIG2LoadingContext: Invalid JBIG2 header");
  350. FixedMemoryStream stream(data.slice(sizeof(id_string)));
  351. // D.4.2 File header flags
  352. u8 header_flags = TRY(stream.read_value<u8>());
  353. if (header_flags & 0b11110000)
  354. return Error::from_string_literal("JBIG2LoadingContext: Invalid header flags");
  355. context.organization = (header_flags & 1) ? Organization::Sequential : Organization::RandomAccess;
  356. dbgln_if(JBIG2_DEBUG, "JBIG2LoadingContext: Organization: {} ({})", (int)context.organization, context.organization == Organization::Sequential ? "Sequential" : "Random-access");
  357. bool has_known_number_of_pages = (header_flags & 2) ? false : true;
  358. bool uses_templates_with_12_AT_pixels = (header_flags & 4) ? true : false;
  359. bool contains_colored_region_segments = (header_flags & 8) ? true : false;
  360. // FIXME: Do something with these?
  361. (void)uses_templates_with_12_AT_pixels;
  362. (void)contains_colored_region_segments;
  363. // D.4.3 Number of pages
  364. if (has_known_number_of_pages) {
  365. context.number_of_pages = TRY(stream.read_value<BigEndian<u32>>());
  366. dbgln_if(JBIG2_DEBUG, "JBIG2LoadingContext: Number of pages: {}", context.number_of_pages.value());
  367. }
  368. return {};
  369. }
  370. static ErrorOr<SegmentHeader> decode_segment_header(SeekableStream& stream)
  371. {
  372. // 7.2.2 Segment number
  373. u32 segment_number = TRY(stream.read_value<BigEndian<u32>>());
  374. dbgln_if(JBIG2_DEBUG, "Segment number: {}", segment_number);
  375. // 7.2.3 Segment header flags
  376. u8 flags = TRY(stream.read_value<u8>());
  377. SegmentType type = static_cast<SegmentType>(flags & 0b11'1111);
  378. dbgln_if(JBIG2_DEBUG, "Segment type: {}", (int)type);
  379. bool segment_page_association_size_is_32_bits = (flags & 0b100'0000) != 0;
  380. bool segment_retained_only_by_itself_and_extension_segments = (flags & 0b1000'00000) != 0;
  381. // FIXME: Do something with these.
  382. (void)segment_page_association_size_is_32_bits;
  383. (void)segment_retained_only_by_itself_and_extension_segments;
  384. // 7.2.4 Referred-to segment count and retention flags
  385. u8 referred_to_segment_count_and_retention_flags = TRY(stream.read_value<u8>());
  386. u32 count_of_referred_to_segments = referred_to_segment_count_and_retention_flags >> 5;
  387. if (count_of_referred_to_segments == 5 || count_of_referred_to_segments == 6)
  388. return Error::from_string_literal("JBIG2ImageDecoderPlugin: Invalid count_of_referred_to_segments");
  389. u32 extra_count = 0;
  390. if (count_of_referred_to_segments == 7) {
  391. TRY(stream.seek(-1, SeekMode::FromCurrentPosition));
  392. count_of_referred_to_segments = TRY(stream.read_value<BigEndian<u32>>()) & 0x1FFF'FFFF;
  393. extra_count = ceil_div(count_of_referred_to_segments + 1, 8);
  394. TRY(stream.seek(extra_count, SeekMode::FromCurrentPosition));
  395. }
  396. dbgln_if(JBIG2_DEBUG, "Referred-to segment count: {}", count_of_referred_to_segments);
  397. // 7.2.5 Referred-to segment numbers
  398. Vector<u32> referred_to_segment_numbers;
  399. for (u32 i = 0; i < count_of_referred_to_segments; ++i) {
  400. u32 referred_to_segment_number;
  401. if (segment_number <= 256)
  402. referred_to_segment_number = TRY(stream.read_value<u8>());
  403. else if (segment_number <= 65536)
  404. referred_to_segment_number = TRY(stream.read_value<BigEndian<u16>>());
  405. else
  406. referred_to_segment_number = TRY(stream.read_value<BigEndian<u32>>());
  407. referred_to_segment_numbers.append(referred_to_segment_number);
  408. dbgln_if(JBIG2_DEBUG, "Referred-to segment number: {}", referred_to_segment_number);
  409. }
  410. // 7.2.6 Segment page association
  411. u32 segment_page_association;
  412. if (segment_page_association_size_is_32_bits) {
  413. segment_page_association = TRY(stream.read_value<BigEndian<u32>>());
  414. } else {
  415. segment_page_association = TRY(stream.read_value<u8>());
  416. }
  417. dbgln_if(JBIG2_DEBUG, "Segment page association: {}", segment_page_association);
  418. // 7.2.7 Segment data length
  419. u32 data_length = TRY(stream.read_value<BigEndian<u32>>());
  420. dbgln_if(JBIG2_DEBUG, "Segment data length: {}", data_length);
  421. // FIXME: Add some validity checks:
  422. // - check type is valid
  423. // - check referred_to_segment_numbers are smaller than segment_number
  424. // - 7.3.1 Rules for segment references
  425. // - 7.3.2 Rules for page associations
  426. Optional<u32> opt_data_length;
  427. if (data_length != 0xffff'ffff)
  428. opt_data_length = data_length;
  429. else if (type != ImmediateGenericRegion)
  430. return Error::from_string_literal("JBIG2ImageDecoderPlugin: Unknown data length only allowed for ImmediateGenericRegion");
  431. return SegmentHeader { segment_number, type, move(referred_to_segment_numbers), segment_page_association, opt_data_length };
  432. }
  433. static ErrorOr<size_t> scan_for_immediate_generic_region_size(ReadonlyBytes data)
  434. {
  435. // 7.2.7 Segment data length
  436. // "If the segment's type is "Immediate generic region", then the length field may contain the value 0xFFFFFFFF.
  437. // 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 (...).
  438. // In this case, the true length of the segment's data part shall be determined through examination of the data:
  439. // 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.
  440. // 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.
  441. // The form of encoding used by the segment may be determined by examining the eighteenth byte of its segment data part,
  442. // and the end sequences can occur anywhere after that eighteenth byte."
  443. // 7.4.6.4 Decoding a generic region segment
  444. // "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.
  445. // Thus, those sequences cannot occur by chance in the data that is decoded to generate the contents of the generic region."
  446. dbgln_if(JBIG2_DEBUG, "(Unknown data length, computing it)");
  447. if (data.size() < 19 + sizeof(u32))
  448. return Error::from_string_literal("JBIG2ImageDecoderPlugin: Data too short to contain segment data header and end sequence");
  449. // Per 7.4.6.1 Generic region segment data header, this starts with the 17 bytes described in
  450. // 7.4.1 Region segment information field, followed the byte described in 7.4.6.2 Generic region segment flags.
  451. // That byte's lowest bit stores if the segment uses MMR.
  452. u8 flags = data[17];
  453. bool uses_mmr = (flags & 1) != 0;
  454. auto end_sequence = uses_mmr ? to_array<u8>({ 0x00, 0x00 }) : to_array<u8>({ 0xFF, 0xAC });
  455. u8 const* end = static_cast<u8 const*>(memmem(data.data() + 19, data.size() - 19 - sizeof(u32), end_sequence.data(), end_sequence.size()));
  456. if (!end)
  457. return Error::from_string_literal("JBIG2ImageDecoderPlugin: Could not find end sequence in segment data");
  458. size_t size = end - data.data() + end_sequence.size() + sizeof(u32);
  459. dbgln_if(JBIG2_DEBUG, "(Computed size is {})", size);
  460. return size;
  461. }
  462. static ErrorOr<void> decode_segment_headers(JBIG2LoadingContext& context, ReadonlyBytes data)
  463. {
  464. FixedMemoryStream stream(data);
  465. Vector<ReadonlyBytes> segment_datas;
  466. auto store_and_skip_segment_data = [&](SegmentHeader const& segment_header) -> ErrorOr<void> {
  467. size_t start_offset = TRY(stream.tell());
  468. u32 data_length = TRY(segment_header.data_length.try_value_or_lazy_evaluated([&]() {
  469. return scan_for_immediate_generic_region_size(data.slice(start_offset));
  470. }));
  471. if (start_offset + data_length > data.size()) {
  472. dbgln_if(JBIG2_DEBUG, "JBIG2ImageDecoderPlugin: start_offset={}, data_length={}, data.size()={}", start_offset, data_length, data.size());
  473. return Error::from_string_literal("JBIG2ImageDecoderPlugin: Segment data length exceeds file size");
  474. }
  475. ReadonlyBytes segment_data = data.slice(start_offset, data_length);
  476. segment_datas.append(segment_data);
  477. TRY(stream.seek(data_length, SeekMode::FromCurrentPosition));
  478. return {};
  479. };
  480. Vector<SegmentHeader> segment_headers;
  481. while (!stream.is_eof()) {
  482. auto segment_header = TRY(decode_segment_header(stream));
  483. segment_headers.append(segment_header);
  484. if (context.organization != Organization::RandomAccess)
  485. TRY(store_and_skip_segment_data(segment_header));
  486. // Required per spec for files with RandomAccess organization.
  487. if (segment_header.type == SegmentType::EndOfFile)
  488. break;
  489. }
  490. if (context.organization == Organization::RandomAccess) {
  491. for (auto const& segment_header : segment_headers)
  492. TRY(store_and_skip_segment_data(segment_header));
  493. }
  494. if (segment_headers.size() != segment_datas.size())
  495. return Error::from_string_literal("JBIG2ImageDecoderPlugin: Segment headers and segment datas have different sizes");
  496. for (size_t i = 0; i < segment_headers.size(); ++i)
  497. context.segments.append({ segment_headers[i], segment_datas[i] });
  498. return {};
  499. }
  500. // 7.4.1 Region segment information field
  501. struct [[gnu::packed]] RegionSegmentInformationField {
  502. BigEndian<u32> width;
  503. BigEndian<u32> height;
  504. BigEndian<u32> x_location;
  505. BigEndian<u32> y_location;
  506. u8 flags;
  507. // FIXME: Or have just ::CombinationOperator represent both page and segment operators?
  508. enum class CombinationOperator {
  509. Or = 0,
  510. And = 1,
  511. Xor = 2,
  512. XNor = 3,
  513. Replace = 4,
  514. };
  515. CombinationOperator external_combination_operator() const
  516. {
  517. VERIFY((flags & 0x7) <= 4);
  518. return static_cast<CombinationOperator>(flags & 0x7);
  519. }
  520. bool is_color_bitmap() const
  521. {
  522. return (flags & 0x8) != 0;
  523. }
  524. };
  525. static_assert(AssertSize<RegionSegmentInformationField, 17>());
  526. static ErrorOr<RegionSegmentInformationField> decode_region_segment_information_field(ReadonlyBytes data)
  527. {
  528. // 7.4.8 Page information segment syntax
  529. if (data.size() < sizeof(RegionSegmentInformationField))
  530. return Error::from_string_literal("JBIG2ImageDecoderPlugin: Invalid region segment information field size");
  531. auto result = *(RegionSegmentInformationField const*)data.data();
  532. if ((result.flags & 0b1111'0000) != 0)
  533. return Error::from_string_literal("JBIG2ImageDecoderPlugin: Invalid region segment information field flags");
  534. if ((result.flags & 0x7) > 4)
  535. return Error::from_string_literal("JBIG2ImageDecoderPlugin: Invalid region segment information field operator");
  536. // NOTE 3 – If the colour extension flag (COLEXTFLAG) is equal to 1, the external combination operator must be REPLACE.
  537. if (result.is_color_bitmap() && result.external_combination_operator() != RegionSegmentInformationField::CombinationOperator::Replace)
  538. return Error::from_string_literal("JBIG2ImageDecoderPlugin: Invalid colored region segment information field operator");
  539. return result;
  540. }
  541. // 7.4.8 Page information segment syntax
  542. struct [[gnu::packed]] PageInformationSegment {
  543. BigEndian<u32> bitmap_width;
  544. BigEndian<u32> bitmap_height;
  545. BigEndian<u32> page_x_resolution; // In pixels/meter.
  546. BigEndian<u32> page_y_resolution; // In pixels/meter.
  547. u8 flags;
  548. BigEndian<u16> striping_information;
  549. };
  550. static_assert(AssertSize<PageInformationSegment, 19>());
  551. static ErrorOr<PageInformationSegment> decode_page_information_segment(ReadonlyBytes data)
  552. {
  553. // 7.4.8 Page information segment syntax
  554. if (data.size() != sizeof(PageInformationSegment))
  555. return Error::from_string_literal("JBIG2ImageDecoderPlugin: Invalid page information segment size");
  556. return *(PageInformationSegment const*)data.data();
  557. }
  558. static ErrorOr<void> scan_for_page_size(JBIG2LoadingContext& context)
  559. {
  560. // We only decode the first page at the moment.
  561. bool found_size = false;
  562. for (auto const& segment : context.segments) {
  563. if (segment.header.type != SegmentType::PageInformation || segment.header.page_association != 1)
  564. continue;
  565. auto page_information = TRY(decode_page_information_segment(segment.data));
  566. // FIXME: We're supposed to compute this from the striping information if it's not set.
  567. if (page_information.bitmap_height == 0xffff'ffff)
  568. return Error::from_string_literal("JBIG2ImageDecoderPlugin: Cannot handle unknown page height yet");
  569. context.page.size = { page_information.bitmap_width, page_information.bitmap_height };
  570. found_size = true;
  571. }
  572. if (!found_size)
  573. return Error::from_string_literal("JBIG2ImageDecoderPlugin: No page information segment found for page 1");
  574. return {};
  575. }
  576. static ErrorOr<void> warn_about_multiple_pages(JBIG2LoadingContext& context)
  577. {
  578. HashTable<u32> seen_pages;
  579. Vector<u32> pages;
  580. for (auto const& segment : context.segments) {
  581. if (segment.header.page_association == 0)
  582. continue;
  583. if (seen_pages.contains(segment.header.page_association))
  584. continue;
  585. seen_pages.set(segment.header.page_association);
  586. pages.append(segment.header.page_association);
  587. }
  588. // scan_for_page_size() already checked that there's a page 1.
  589. VERIFY(seen_pages.contains(1));
  590. if (pages.size() == 1)
  591. return {};
  592. StringBuilder builder;
  593. builder.appendff("JBIG2 file contains {} pages ({}", pages.size(), pages[0]);
  594. size_t i;
  595. for (i = 1; i < min(pages.size(), 10); ++i)
  596. builder.appendff(" {}", pages[i]);
  597. if (i != pages.size())
  598. builder.append(" ..."sv);
  599. builder.append("). We will only render page 1."sv);
  600. dbgln("JBIG2ImageDecoderPlugin: {}", TRY(builder.to_string()));
  601. return {};
  602. }
  603. // 6.2.2 Input parameters
  604. struct GenericRegionDecodingInputParameters {
  605. bool is_modified_modified_read { false }; // "MMR" in spec.
  606. u32 region_width { 0 }; // "GBW" in spec.
  607. u32 region_height { 0 }; // "GBH" in spec.
  608. u8 gb_template { 0 };
  609. bool is_typical_prediction_used { false }; // "TPGDON" in spec.
  610. bool is_extended_reference_template_used { false }; // "EXTTEMPLATE" in spec.
  611. Optional<NonnullOwnPtr<BitBuffer>> skip_pattern; // "USESKIP", "SKIP" in spec.
  612. struct AdaptiveTemplatePixel {
  613. i8 x { 0 };
  614. i8 y { 0 };
  615. };
  616. Array<AdaptiveTemplatePixel, 12> adaptive_template_pixels; // "GBATX" / "GBATY" in spec.
  617. // FIXME: GBCOLS, GBCOMBOP, COLEXTFLAG
  618. };
  619. // 6.2 Generic region decoding procedure
  620. static ErrorOr<NonnullOwnPtr<BitBuffer>> generic_region_decoding_procedure(GenericRegionDecodingInputParameters const& inputs, ReadonlyBytes data)
  621. {
  622. if (inputs.is_modified_modified_read) {
  623. dbgln_if(JBIG2_DEBUG, "JBIG2ImageDecoderPlugin: MMR image data");
  624. // 6.2.6 Decoding using MMR coding
  625. auto buffer = TRY(CCITT::decode_ccitt_group4(data, inputs.region_width, inputs.region_height));
  626. auto result = TRY(BitBuffer::create(inputs.region_width, inputs.region_height));
  627. size_t bytes_per_row = ceil_div(inputs.region_width, 8);
  628. if (buffer.size() != bytes_per_row * inputs.region_height)
  629. return Error::from_string_literal("JBIG2ImageDecoderPlugin: Decoded MMR data has wrong size");
  630. // FIXME: Could probably just copy the ByteBuffer directly into the BitBuffer's internal ByteBuffer instead.
  631. for (size_t y = 0; y < inputs.region_height; ++y) {
  632. for (size_t x = 0; x < inputs.region_width; ++x) {
  633. bool bit = buffer[y * bytes_per_row + x / 8] & (1 << (7 - x % 8));
  634. result->set_bit(x, y, bit);
  635. }
  636. }
  637. return result;
  638. }
  639. // 6.2.5 Decoding using a template and arithmetic coding
  640. if (inputs.gb_template != 0)
  641. return Error::from_string_literal("JBIG2ImageDecoderPlugin: Cannot decode GBTEMPLATE != 0 yet");
  642. if (inputs.adaptive_template_pixels[0].x != 3 || inputs.adaptive_template_pixels[0].y != -1
  643. || inputs.adaptive_template_pixels[1].x != -3 || inputs.adaptive_template_pixels[1].y != -1
  644. || inputs.adaptive_template_pixels[2].x != 2 || inputs.adaptive_template_pixels[2].y != -2
  645. || inputs.adaptive_template_pixels[3].x != -2 || inputs.adaptive_template_pixels[3].y != -2)
  646. return Error::from_string_literal("JBIG2ImageDecoderPlugin: Cannot handle custom adaptive pixels yet");
  647. if (inputs.is_extended_reference_template_used)
  648. return Error::from_string_literal("JBIG2ImageDecoderPlugin: Cannot decode EXTTEMPLATE yet");
  649. if (inputs.skip_pattern.has_value())
  650. return Error::from_string_literal("JBIG2ImageDecoderPlugin: Cannot decode USESKIP yet");
  651. auto result = TRY(BitBuffer::create(inputs.region_width, inputs.region_height));
  652. auto decoder = MUST(JBIG2::ArithmeticDecoder::initialize(data));
  653. auto get_pixel = [&inputs](NonnullOwnPtr<BitBuffer> const& buffer, int x, int y) -> bool {
  654. if (x < 0 || x >= (int)inputs.region_width || y < 0)
  655. return false;
  656. return buffer->get_bit(x, y);
  657. };
  658. // Figure 3(a) – Template when GBTEMPLATE = 0 and EXTTEMPLATE = 0,
  659. auto compute_context = [&get_pixel](NonnullOwnPtr<BitBuffer> const& buffer, int x, int y) -> u16 {
  660. u16 result = 0;
  661. for (int i = 0; i < 5; ++i)
  662. result = (result << 1) | (u16)get_pixel(buffer, x - 2 + i, y - 2);
  663. for (int i = 0; i < 7; ++i)
  664. result = (result << 1) | (u16)get_pixel(buffer, x - 3 + i, y - 1);
  665. for (int i = 0; i < 4; ++i)
  666. result = (result << 1) | (u16)get_pixel(buffer, x - 4 + i, y);
  667. return result;
  668. };
  669. // "The values of the pixels in this neighbourhood define a context. Each context has its own adaptive probability estimate
  670. // used by the arithmetic coder (see Annex E)."
  671. // "* Decode the current pixel by invoking the arithmetic entropy decoding procedure, with CX set to the value formed by
  672. // concatenating the label "GB" and the 10-16 pixel values gathered in CONTEXT."
  673. // Implementor's note: What this is supposed to mean is that we have a bunch of independent contexts, and we pick the
  674. // context for the current pixel based on pixel values in the neighborhood. The "GB" part just means this context is
  675. // independent from other contexts in the spec. At the moment, these are the only contexts we have, so we just
  676. // create them on demand here.
  677. // I can't find where the spec says this, but the contexts all start out zero-initialized.
  678. Vector<JBIG2::ArithmeticDecoder::Context> contexts;
  679. contexts.resize(1 << 16);
  680. // Figure 8 – Reused context for coding the SLTP value when GBTEMPLATE is 0
  681. constexpr u16 sltp_context_for_template_0 = 0b10011'0110010'0101;
  682. // 6.2.5.7 Decoding the bitmap
  683. bool ltp = false; // "LTP" in spec. "Line (uses) Typical Prediction" maybe?
  684. for (size_t y = 0; y < inputs.region_height; ++y) {
  685. if (inputs.is_typical_prediction_used) {
  686. // "SLTP" in spec. "Swap LTP" or "Switch LTP" maybe?
  687. bool sltp = decoder.get_next_bit(contexts[sltp_context_for_template_0]);
  688. ltp = ltp ^ sltp;
  689. if (ltp) {
  690. for (size_t x = 0; x < inputs.region_width; ++x)
  691. result->set_bit(x, y, get_pixel(result, (int)x, (int)y - 1));
  692. continue;
  693. }
  694. }
  695. for (size_t x = 0; x < inputs.region_width; ++x) {
  696. u16 context = compute_context(result, x, y);
  697. bool bit = decoder.get_next_bit(contexts[context]);
  698. result->set_bit(x, y, bit);
  699. }
  700. }
  701. return result;
  702. }
  703. static ErrorOr<void> decode_symbol_dictionary(JBIG2LoadingContext&, SegmentData const&)
  704. {
  705. return Error::from_string_literal("JBIG2ImageDecoderPlugin: Cannot decode symbol dictionary yet");
  706. }
  707. static ErrorOr<void> decode_intermediate_text_region(JBIG2LoadingContext&, SegmentData const&)
  708. {
  709. return Error::from_string_literal("JBIG2ImageDecoderPlugin: Cannot decode intermediate text region yet");
  710. }
  711. static ErrorOr<void> decode_immediate_text_region(JBIG2LoadingContext&, SegmentData const&)
  712. {
  713. return Error::from_string_literal("JBIG2ImageDecoderPlugin: Cannot decode immediate text region yet");
  714. }
  715. static ErrorOr<void> decode_immediate_lossless_text_region(JBIG2LoadingContext&, SegmentData const&)
  716. {
  717. return Error::from_string_literal("JBIG2ImageDecoderPlugin: Cannot decode immediate lossless text region yet");
  718. }
  719. static ErrorOr<void> decode_pattern_dictionary(JBIG2LoadingContext&, SegmentData const&)
  720. {
  721. return Error::from_string_literal("JBIG2ImageDecoderPlugin: Cannot decode pattern dictionary yet");
  722. }
  723. static ErrorOr<void> decode_intermediate_halftone_region(JBIG2LoadingContext&, SegmentData const&)
  724. {
  725. return Error::from_string_literal("JBIG2ImageDecoderPlugin: Cannot decode intermediate halftone region yet");
  726. }
  727. static ErrorOr<void> decode_immediate_halftone_region(JBIG2LoadingContext&, SegmentData const&)
  728. {
  729. return Error::from_string_literal("JBIG2ImageDecoderPlugin: Cannot decode immediate halftone region yet");
  730. }
  731. static ErrorOr<void> decode_immediate_lossless_halftone_region(JBIG2LoadingContext&, SegmentData const&)
  732. {
  733. return Error::from_string_literal("JBIG2ImageDecoderPlugin: Cannot decode immediate lossless halftone region yet");
  734. }
  735. static ErrorOr<void> decode_intermediate_generic_region(JBIG2LoadingContext&, SegmentData const&)
  736. {
  737. return Error::from_string_literal("JBIG2ImageDecoderPlugin: Cannot decode intermediate generic region yet");
  738. }
  739. static ErrorOr<void> decode_immediate_generic_region(JBIG2LoadingContext& context, SegmentData const& segment)
  740. {
  741. // 7.4.6 Generic region segment syntax
  742. auto data = segment.data;
  743. auto information_field = TRY(decode_region_segment_information_field(data));
  744. data = data.slice(sizeof(information_field));
  745. 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);
  746. // 7.4.6.2 Generic region segment flags
  747. if (data.is_empty())
  748. return Error::from_string_literal("JBIG2ImageDecoderPlugin: No segment data");
  749. u8 flags = data[0];
  750. bool uses_mmr = (flags & 1) != 0;
  751. u8 arithmetic_coding_template = (flags >> 1) & 3; // "GBTEMPLATE"
  752. bool typical_prediction_generic_decoding_on = (flags >> 3) & 1; // "TPGDON"; "TPGD" is short for "Typical Prediction for Generic Direct coding"
  753. bool uses_extended_reference_template = (flags >> 4) & 1; // "EXTTEMPLATE"
  754. if (flags & 0b1110'0000)
  755. return Error::from_string_literal("JBIG2ImageDecoderPlugin: Invalid flags");
  756. data = data.slice(sizeof(flags));
  757. // 7.4.6.3 Generic region segment AT flags
  758. Array<GenericRegionDecodingInputParameters::AdaptiveTemplatePixel, 12> adaptive_template_pixels {};
  759. if (!uses_mmr) {
  760. dbgln_if(JBIG2_DEBUG, "Non-MMR generic region, GBTEMPLATE={} TPGDON={} EXTTEMPLATE={}", arithmetic_coding_template, typical_prediction_generic_decoding_on, uses_extended_reference_template);
  761. if (arithmetic_coding_template == 0 && uses_extended_reference_template) {
  762. // This was added in T.88 Amendment 2 (https://www.itu.int/rec/T-REC-T.88-200306-S!Amd2/en) mid-2003.
  763. // 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,
  764. // so it's not clear how much data to read.
  765. return Error::from_string_literal("JBIG2ImageDecoderPlugin: GBTEMPLATE=0 EXTTEMPLATE=1 not yet implemented");
  766. }
  767. size_t number_of_adaptive_template_pixels = arithmetic_coding_template == 0 ? 4 : 1;
  768. if (data.size() < 2 * number_of_adaptive_template_pixels)
  769. return Error::from_string_literal("JBIG2ImageDecoderPlugin: No adaptive template data");
  770. for (size_t i = 0; i < number_of_adaptive_template_pixels; ++i) {
  771. adaptive_template_pixels[i].x = static_cast<i8>(data[2 * i]);
  772. adaptive_template_pixels[i].y = static_cast<i8>(data[2 * i + 1]);
  773. }
  774. data = data.slice(2 * number_of_adaptive_template_pixels);
  775. }
  776. // 7.4.6.4 Decoding a generic region segment
  777. // "1) Interpret its header, as described in 7.4.6.1"
  778. // Done above.
  779. // "2) As described in E.3.7, reset all the arithmetic coding statistics to zero."
  780. // FIXME: Implement this once we support arithmetic coding.
  781. // "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."
  782. GenericRegionDecodingInputParameters inputs;
  783. inputs.is_modified_modified_read = uses_mmr;
  784. inputs.region_width = information_field.width;
  785. inputs.region_height = information_field.height;
  786. inputs.gb_template = arithmetic_coding_template;
  787. inputs.is_typical_prediction_used = typical_prediction_generic_decoding_on;
  788. inputs.is_extended_reference_template_used = uses_extended_reference_template;
  789. inputs.skip_pattern = OptionalNone {};
  790. inputs.adaptive_template_pixels = adaptive_template_pixels;
  791. auto result = TRY(generic_region_decoding_procedure(inputs, data));
  792. // 8.2 Page image composition step 5)
  793. if (information_field.x_location + information_field.width > (u32)context.page.size.width()
  794. || information_field.y_location + information_field.height > (u32)context.page.size.height()) {
  795. return Error::from_string_literal("JBIG2ImageDecoderPlugin: Region bounds outsize of page bounds");
  796. }
  797. if (information_field.external_combination_operator() != RegionSegmentInformationField::CombinationOperator::Or
  798. && information_field.external_combination_operator() != RegionSegmentInformationField::CombinationOperator::Xor
  799. && information_field.external_combination_operator() != RegionSegmentInformationField::CombinationOperator::Replace)
  800. return Error::from_string_literal("JBIG2ImageDecoderPlugin: Cannot handle external combination operator other than OR, XOR, and REPLACE yet");
  801. for (size_t y = 0; y < information_field.height; ++y) {
  802. for (size_t x = 0; x < information_field.width; ++x) {
  803. // FIXME: Honor segment's combination operator instead of just copying.
  804. context.page.bits->set_bit(information_field.x_location + x, information_field.y_location + y, result->get_bit(x, y));
  805. }
  806. }
  807. return {};
  808. }
  809. static ErrorOr<void> decode_intermediate_generic_refinement_region(JBIG2LoadingContext&, SegmentData const&)
  810. {
  811. return Error::from_string_literal("JBIG2ImageDecoderPlugin: Cannot decode intermediate generic refinement region yet");
  812. }
  813. static ErrorOr<void> decode_immediate_generic_refinement_region(JBIG2LoadingContext&, SegmentData const&)
  814. {
  815. return Error::from_string_literal("JBIG2ImageDecoderPlugin: Cannot decode immediate generic refinement region yet");
  816. }
  817. static ErrorOr<void> decode_immediate_lossless_generic_refinement_region(JBIG2LoadingContext&, SegmentData const&)
  818. {
  819. return Error::from_string_literal("JBIG2ImageDecoderPlugin: Cannot decode immediate lossless generic refinement region yet");
  820. }
  821. static ErrorOr<void> decode_page_information(JBIG2LoadingContext& context, SegmentData const& segment)
  822. {
  823. // 7.4.8 Page information segment syntax and 8.1 Decoder model steps 1) - 3).
  824. // "1) Decode the page information segment.""
  825. auto page_information = TRY(decode_page_information_segment(segment.data));
  826. bool page_is_striped = (page_information.striping_information & 0x80) != 0;
  827. if (page_information.bitmap_height == 0xffff'ffff && !page_is_striped)
  828. return Error::from_string_literal("JBIG2ImageDecoderPlugin: Non-striped bitmaps of indeterminate height not allowed");
  829. u8 default_color = (page_information.flags >> 2) & 1;
  830. u8 default_combination_operator = (page_information.flags >> 3) & 3;
  831. context.page.default_combination_operator = static_cast<CombinationOperator>(default_combination_operator);
  832. // FIXME: Do something with the other fields in page_information.
  833. // "2) Create the page buffer, of the size given in the page information segment.
  834. //
  835. // If the page height is unknown, then this is not possible. However, in this case the page must be striped,
  836. // and the maximum stripe height specified, and the initial page buffer can be created with height initially
  837. // equal to this maximum stripe height."
  838. size_t height = page_information.bitmap_height;
  839. if (height == 0xffff'ffff)
  840. height = page_information.striping_information & 0x7F;
  841. context.page.bits = TRY(BitBuffer::create(page_information.bitmap_width, height));
  842. // "3) Fill the page buffer with the page's default pixel value."
  843. if (default_color == 1)
  844. return Error::from_string_literal("JBIG2ImageDecoderPlugin: Can only handle white default color for now");
  845. context.page.bits->fill(default_color != 0);
  846. return {};
  847. }
  848. static ErrorOr<void> decode_end_of_page(JBIG2LoadingContext&, SegmentData const& segment)
  849. {
  850. // 7.4.9 End of page segment syntax
  851. if (segment.data.size() != 0)
  852. return Error::from_string_literal("JBIG2ImageDecoderPlugin: End of page segment has non-zero size");
  853. // FIXME: If the page had unknown height, check that previous segment was end-of-stripe.
  854. // FIXME: Maybe mark page as completed and error if we see more segments for it?
  855. return {};
  856. }
  857. static ErrorOr<void> decode_end_of_stripe(JBIG2LoadingContext&, SegmentData const&)
  858. {
  859. return Error::from_string_literal("JBIG2ImageDecoderPlugin: Cannot decode end of stripe yet");
  860. }
  861. static ErrorOr<void> decode_end_of_file(JBIG2LoadingContext&, SegmentData const& segment)
  862. {
  863. // 7.4.11 End of file segment syntax
  864. if (segment.data.size() != 0)
  865. return Error::from_string_literal("JBIG2ImageDecoderPlugin: End of file segment has non-zero size");
  866. return {};
  867. }
  868. static ErrorOr<void> decode_profiles(JBIG2LoadingContext&, SegmentData const&)
  869. {
  870. return Error::from_string_literal("JBIG2ImageDecoderPlugin: Cannot decode profiles yet");
  871. }
  872. static ErrorOr<void> decode_tables(JBIG2LoadingContext&, SegmentData const&)
  873. {
  874. return Error::from_string_literal("JBIG2ImageDecoderPlugin: Cannot decode tables yet");
  875. }
  876. static ErrorOr<void> decode_color_palette(JBIG2LoadingContext&, SegmentData const&)
  877. {
  878. return Error::from_string_literal("JBIG2ImageDecoderPlugin: Cannot decode color palette yet");
  879. }
  880. static ErrorOr<void> decode_extension(JBIG2LoadingContext&, SegmentData const& segment)
  881. {
  882. // 7.4.14 Extension segment syntax
  883. FixedMemoryStream stream { segment.data };
  884. enum ExtensionType {
  885. SingleByteCodedComment = 0x20000000,
  886. MultiByteCodedComment = 0x20000002,
  887. };
  888. u32 type = TRY(stream.read_value<BigEndian<u32>>());
  889. auto read_string = [&]<class T>() -> ErrorOr<Vector<T>> {
  890. Vector<T> result;
  891. do {
  892. result.append(TRY(stream.read_value<BigEndian<T>>()));
  893. } while (result.last());
  894. result.take_last();
  895. return result;
  896. };
  897. switch (type) {
  898. case SingleByteCodedComment: {
  899. // 7.4.15.1 Single-byte coded comment
  900. // Pairs of zero-terminated ISO/IEC 8859-1 (latin1) pairs, terminated by another \0.
  901. while (true) {
  902. auto first_bytes = TRY(read_string.template operator()<u8>());
  903. if (first_bytes.is_empty())
  904. break;
  905. auto second_bytes = TRY(read_string.template operator()<u8>());
  906. auto first = TRY(TextCodec::decoder_for("ISO-8859-1"sv)->to_utf8(StringView { first_bytes }));
  907. auto second = TRY(TextCodec::decoder_for("ISO-8859-1"sv)->to_utf8(StringView { second_bytes }));
  908. dbgln("JBIG2ImageDecoderPlugin: key '{}', value '{}'", first, second);
  909. }
  910. if (!stream.is_eof())
  911. return Error::from_string_literal("JBIG2ImageDecoderPlugin: Trailing data after SingleByteCodedComment");
  912. return {};
  913. }
  914. case MultiByteCodedComment: {
  915. // 7.4.15.2 Multi-byte coded comment
  916. // Pairs of (two-byte-)zero-terminated UCS-2 pairs, terminated by another \0\0.
  917. while (true) {
  918. auto first_ucs2 = TRY(read_string.template operator()<u16>());
  919. if (first_ucs2.is_empty())
  920. break;
  921. auto second_ucs2 = TRY(read_string.template operator()<u16>());
  922. auto first = TRY(Utf16View(first_ucs2).to_utf8());
  923. auto second = TRY(Utf16View(second_ucs2).to_utf8());
  924. dbgln("JBIG2ImageDecoderPlugin: key '{}', value '{}'", first, second);
  925. }
  926. if (!stream.is_eof())
  927. return Error::from_string_literal("JBIG2ImageDecoderPlugin: Trailing data after MultiByteCodedComment");
  928. return {};
  929. }
  930. }
  931. // FIXME: If bit 31 in `type` is not set, the extension isn't necessary, and we could ignore it.
  932. dbgln("JBIG2ImageDecoderPlugin: Unknown extension type {:#x}", type);
  933. return Error::from_string_literal("JBIG2ImageDecoderPlugin: Unknown extension type");
  934. }
  935. static ErrorOr<void> decode_data(JBIG2LoadingContext& context)
  936. {
  937. TRY(warn_about_multiple_pages(context));
  938. for (size_t i = 0; i < context.segments.size(); ++i) {
  939. auto const& segment = context.segments[i];
  940. if (segment.header.page_association != 0 && segment.header.page_association != 1)
  941. continue;
  942. switch (segment.header.type) {
  943. case SegmentType::SymbolDictionary:
  944. TRY(decode_symbol_dictionary(context, segment));
  945. break;
  946. case SegmentType::IntermediateTextRegion:
  947. TRY(decode_intermediate_text_region(context, segment));
  948. break;
  949. case SegmentType::ImmediateTextRegion:
  950. TRY(decode_immediate_text_region(context, segment));
  951. break;
  952. case SegmentType::ImmediateLosslessTextRegion:
  953. TRY(decode_immediate_lossless_text_region(context, segment));
  954. break;
  955. case SegmentType::PatternDictionary:
  956. TRY(decode_pattern_dictionary(context, segment));
  957. break;
  958. case SegmentType::IntermediateHalftoneRegion:
  959. TRY(decode_intermediate_halftone_region(context, segment));
  960. break;
  961. case SegmentType::ImmediateHalftoneRegion:
  962. TRY(decode_immediate_halftone_region(context, segment));
  963. break;
  964. case SegmentType::ImmediateLosslessHalftoneRegion:
  965. TRY(decode_immediate_lossless_halftone_region(context, segment));
  966. break;
  967. case SegmentType::IntermediateGenericRegion:
  968. TRY(decode_intermediate_generic_region(context, segment));
  969. break;
  970. case SegmentType::ImmediateGenericRegion:
  971. case SegmentType::ImmediateLosslessGenericRegion:
  972. // 7.4.6 Generic region segment syntax
  973. // "The data parts of all three of the generic region segment types ("intermediate generic region", "immediate generic region" and
  974. // "immediate lossless generic region") are coded identically, but are acted upon differently, see 8.2."
  975. // But 8.2 only describes a difference between intermediate and immediate regions as far as I can tell,
  976. // and calling the immediate generic region handler for immediate generic lossless regions seems to do the right thing (?).
  977. TRY(decode_immediate_generic_region(context, segment));
  978. break;
  979. case SegmentType::IntermediateGenericRefinementRegion:
  980. TRY(decode_intermediate_generic_refinement_region(context, segment));
  981. break;
  982. case SegmentType::ImmediateGenericRefinementRegion:
  983. TRY(decode_immediate_generic_refinement_region(context, segment));
  984. break;
  985. case SegmentType::ImmediateLosslessGenericRefinementRegion:
  986. TRY(decode_immediate_lossless_generic_refinement_region(context, segment));
  987. break;
  988. case SegmentType::PageInformation:
  989. TRY(decode_page_information(context, segment));
  990. break;
  991. case SegmentType::EndOfPage:
  992. TRY(decode_end_of_page(context, segment));
  993. break;
  994. case SegmentType::EndOfStripe:
  995. TRY(decode_end_of_stripe(context, segment));
  996. break;
  997. case SegmentType::EndOfFile:
  998. TRY(decode_end_of_file(context, segment));
  999. // "If a file contains an end of file segment, it must be the last segment."
  1000. if (i != context.segments.size() - 1)
  1001. return Error::from_string_literal("JBIG2ImageDecoderPlugin: End of file segment not last segment");
  1002. break;
  1003. case SegmentType::Profiles:
  1004. TRY(decode_profiles(context, segment));
  1005. break;
  1006. case SegmentType::Tables:
  1007. TRY(decode_tables(context, segment));
  1008. break;
  1009. case SegmentType::ColorPalette:
  1010. TRY(decode_color_palette(context, segment));
  1011. break;
  1012. case SegmentType::Extension:
  1013. TRY(decode_extension(context, segment));
  1014. break;
  1015. }
  1016. }
  1017. return {};
  1018. }
  1019. JBIG2ImageDecoderPlugin::JBIG2ImageDecoderPlugin()
  1020. {
  1021. m_context = make<JBIG2LoadingContext>();
  1022. }
  1023. IntSize JBIG2ImageDecoderPlugin::size()
  1024. {
  1025. return m_context->page.size;
  1026. }
  1027. bool JBIG2ImageDecoderPlugin::sniff(ReadonlyBytes data)
  1028. {
  1029. return data.starts_with(id_string);
  1030. }
  1031. ErrorOr<NonnullOwnPtr<ImageDecoderPlugin>> JBIG2ImageDecoderPlugin::create(ReadonlyBytes data)
  1032. {
  1033. auto plugin = TRY(adopt_nonnull_own_or_enomem(new (nothrow) JBIG2ImageDecoderPlugin()));
  1034. TRY(decode_jbig2_header(*plugin->m_context, data));
  1035. data = data.slice(sizeof(id_string) + sizeof(u8) + (plugin->m_context->number_of_pages.has_value() ? sizeof(u32) : 0));
  1036. TRY(decode_segment_headers(*plugin->m_context, data));
  1037. TRY(scan_for_page_size(*plugin->m_context));
  1038. return plugin;
  1039. }
  1040. ErrorOr<ImageFrameDescriptor> JBIG2ImageDecoderPlugin::frame(size_t index, Optional<IntSize>)
  1041. {
  1042. // FIXME: Use this for multi-page JBIG2 files?
  1043. if (index != 0)
  1044. return Error::from_string_literal("JBIG2ImageDecoderPlugin: Invalid frame index");
  1045. if (m_context->state == JBIG2LoadingContext::State::Error)
  1046. return Error::from_string_literal("JBIG2ImageDecoderPlugin: Decoding failed");
  1047. if (m_context->state < JBIG2LoadingContext::State::Decoded) {
  1048. auto result = decode_data(*m_context);
  1049. if (result.is_error()) {
  1050. m_context->state = JBIG2LoadingContext::State::Error;
  1051. return result.release_error();
  1052. }
  1053. m_context->state = JBIG2LoadingContext::State::Decoded;
  1054. }
  1055. auto bitmap = TRY(m_context->page.bits->to_gfx_bitmap());
  1056. return ImageFrameDescriptor { move(bitmap), 0 };
  1057. }
  1058. ErrorOr<ByteBuffer> JBIG2ImageDecoderPlugin::decode_embedded(Vector<ReadonlyBytes> data)
  1059. {
  1060. auto plugin = TRY(adopt_nonnull_own_or_enomem(new (nothrow) JBIG2ImageDecoderPlugin()));
  1061. plugin->m_context->organization = Organization::Embedded;
  1062. for (auto const& segment_data : data)
  1063. TRY(decode_segment_headers(*plugin->m_context, segment_data));
  1064. TRY(scan_for_page_size(*plugin->m_context));
  1065. TRY(decode_data(*plugin->m_context));
  1066. return plugin->m_context->page.bits->to_byte_buffer();
  1067. }
  1068. }