JBIG2Loader.h 2.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596
  1. /*
  2. * Copyright (c) 2024, Nico Weber <thakis@chromium.org>
  3. *
  4. * SPDX-License-Identifier: BSD-2-Clause
  5. */
  6. #pragma once
  7. #include <AK/MemoryStream.h>
  8. #include <AK/OwnPtr.h>
  9. #include <LibGfx/ImageFormats/ImageDecoder.h>
  10. namespace Gfx {
  11. struct JBIG2LoadingContext;
  12. namespace JBIG2 {
  13. // E.3 Arithmetic decoding procedure, but with the changes described in
  14. // Annex G Arithmetic decoding procedure (software conventions).
  15. // Exposed for testing.
  16. class ArithmeticDecoder {
  17. public:
  18. struct Context {
  19. u8 I { 0 }; // Index I stored for context CX (E.2.4)
  20. u8 is_mps { 0 }; // "More probable symbol" (E.1.1). 0 or 1.
  21. };
  22. static ErrorOr<ArithmeticDecoder> initialize(ReadonlyBytes data);
  23. bool get_next_bit(Context& context);
  24. private:
  25. ArithmeticDecoder(ReadonlyBytes data)
  26. : m_data(data)
  27. {
  28. }
  29. ReadonlyBytes m_data;
  30. // The code below uses names from the spec, so that the algorithms look exactly like the flowcharts in the spec.
  31. // Abbreviations:
  32. // "CX": "Context" (E.1)
  33. // "D": "Decision" (as in "encoder input" / "decoder output") (E.1)
  34. // "I(CX)": "Index I stored for context CX" (E.2.4)
  35. // "MPS": "More probable symbol" (E.1.1)
  36. // "LPS": "Less probable symbol" (E.1.1)
  37. void INITDEC();
  38. u8 DECODE(); // Returns a single decoded bit.
  39. u8 MPS_EXCHANGE();
  40. u8 LPS_EXCHANGE();
  41. void RENORMD();
  42. void BYTEIN();
  43. u8 B(size_t offset = 0) const; // Byte pointed to by BP.
  44. size_t BP { 0 }; // Pointer into compressed data.
  45. // E.3.1 Decoder code register conventions
  46. u32 C { 0 }; // Consists of u16 C_high, C_low.
  47. u16 A { 0 }; // Current value of the fraction. Fixed precision; 0x8000 is equivalent to 0.75.
  48. u8 CT { 0 }; // Count of the number of bits in C.
  49. Context* CX { nullptr };
  50. static u8& I(Context* cx) { return cx->I; }
  51. static u8& MPS(Context* cx) { return cx->is_mps; }
  52. static u16 Qe(u16);
  53. static u8 NMPS(u16);
  54. static u8 NLPS(u16);
  55. static u8 SWITCH(u16);
  56. };
  57. }
  58. class JBIG2ImageDecoderPlugin : public ImageDecoderPlugin {
  59. public:
  60. static bool sniff(ReadonlyBytes);
  61. static ErrorOr<NonnullOwnPtr<ImageDecoderPlugin>> create(ReadonlyBytes);
  62. virtual ~JBIG2ImageDecoderPlugin() override = default;
  63. virtual IntSize size() override;
  64. virtual ErrorOr<ImageFrameDescriptor> frame(size_t index, Optional<IntSize> ideal_size = {}) override;
  65. static ErrorOr<ByteBuffer> decode_embedded(Vector<ReadonlyBytes>);
  66. private:
  67. JBIG2ImageDecoderPlugin();
  68. OwnPtr<JBIG2LoadingContext> m_context;
  69. };
  70. }