BooleanDecoder.h 1.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455
  1. /*
  2. * Copyright (c) 2021, Hunter Salyer <thefalsehonesty@gmail.com>
  3. * Copyright (c) 2022, Gregory Bertilson <zaggy1024@gmail.com>
  4. *
  5. * SPDX-License-Identifier: BSD-2-Clause
  6. */
  7. #pragma once
  8. #include <AK/BitStream.h>
  9. #include <AK/Error.h>
  10. #include <AK/Optional.h>
  11. #include <AK/Types.h>
  12. namespace Gfx {
  13. // Can decode bitstreams encoded with VP8's and VP9's arithmetic boolean encoder.
  14. class BooleanDecoder {
  15. public:
  16. static ErrorOr<BooleanDecoder> initialize(ReadonlyBytes data);
  17. /* (9.2) */
  18. bool read_bool(u8 probability);
  19. u8 read_literal(u8 bits);
  20. ErrorOr<void> finish_decode();
  21. private:
  22. using ValueType = size_t;
  23. static constexpr u8 reserve_bytes = sizeof(ValueType) - 1;
  24. static constexpr u8 reserve_bits = reserve_bytes * 8;
  25. BooleanDecoder(u8 const* data, u64 bytes_left)
  26. : m_data(data + 1)
  27. , m_bytes_left(bytes_left - 1)
  28. , m_range(255)
  29. , m_value(static_cast<ValueType>(*data) << reserve_bits)
  30. , m_value_bits_left(8)
  31. {
  32. fill_reservoir();
  33. }
  34. void fill_reservoir();
  35. u8 const* m_data;
  36. size_t m_bytes_left { 0 };
  37. bool m_overread { false };
  38. // This value will never exceed 255. If this is a u8, the compiler will generate a truncation in read_bool().
  39. u32 m_range { 0 };
  40. ValueType m_value { 0 };
  41. // Like above, this will never exceed reserve_bits, but will truncate if it is a u8.
  42. u32 m_value_bits_left { 0 };
  43. };
  44. }