BooleanDecoder.cpp 2.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182
  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. #include <AK/BuiltinWrappers.h>
  8. #include "BooleanDecoder.h"
  9. namespace Gfx {
  10. /* 9.2.1 */
  11. ErrorOr<BooleanDecoder> BooleanDecoder::initialize(MaybeOwned<BigEndianInputBitStream> bit_stream, size_t size_in_bytes)
  12. {
  13. VERIFY(bit_stream->is_aligned_to_byte_boundary());
  14. auto value = TRY(bit_stream->read_value<u8>());
  15. u8 range = 255;
  16. u64 bits_left = (8 * size_in_bytes) - 8;
  17. BooleanDecoder decoder { move(bit_stream), value, range, bits_left };
  18. if (TRY(decoder.read_bool(128)))
  19. return Error::from_string_literal("Range decoder marker was non-zero");
  20. return decoder;
  21. }
  22. /* 9.2.2 */
  23. ErrorOr<bool> BooleanDecoder::read_bool(u8 probability)
  24. {
  25. auto split = 1u + (((m_range - 1u) * probability) >> 8u);
  26. bool return_bool;
  27. if (m_value < split) {
  28. m_range = split;
  29. return_bool = false;
  30. } else {
  31. m_range -= split;
  32. m_value -= split;
  33. return_bool = true;
  34. }
  35. if (m_range < 128) {
  36. u8 bits_to_shift_into_range = count_leading_zeroes(m_range);
  37. if (bits_to_shift_into_range > m_bits_left)
  38. return Error::from_string_literal("Range decoder is out of data");
  39. m_range <<= bits_to_shift_into_range;
  40. m_value = (m_value << bits_to_shift_into_range) | TRY(m_bit_stream->read_bits<u8>(bits_to_shift_into_range));
  41. m_bits_left -= bits_to_shift_into_range;
  42. }
  43. return return_bool;
  44. }
  45. ErrorOr<u8> BooleanDecoder::read_literal(u8 bits)
  46. {
  47. u8 return_value = 0;
  48. for (size_t i = 0; i < bits; i++) {
  49. return_value = (2 * return_value) + TRY(read_bool(128));
  50. }
  51. return return_value;
  52. }
  53. /* 9.2.3 */
  54. ErrorOr<void> BooleanDecoder::finish_decode()
  55. {
  56. while (m_bits_left > 0) {
  57. auto padding_read_size = min(m_bits_left, 64);
  58. auto padding_bits = TRY(m_bit_stream->read_bits(padding_read_size));
  59. m_bits_left -= padding_read_size;
  60. if (padding_bits != 0)
  61. return Error::from_string_literal("Range decoder has non-zero padding element");
  62. }
  63. // FIXME: It is a requirement of bitstream conformance that enough padding bits are inserted to ensure that the final coded byte of a frame is not equal to a superframe marker.
  64. // A byte b is equal to a superframe marker if and only if (b & 0xe0)is equal to 0xc0, i.e. if the most significant 3 bits are equal to 0b110.
  65. return {};
  66. }
  67. }