/src/serenity/Userland/Libraries/LibGfx/ImageFormats/BooleanDecoder.h
Line | Count | Source |
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 | | |
8 | | #pragma once |
9 | | |
10 | | #include <AK/BitStream.h> |
11 | | #include <AK/Error.h> |
12 | | #include <AK/Optional.h> |
13 | | #include <AK/Types.h> |
14 | | |
15 | | namespace Gfx { |
16 | | |
17 | | // Can decode bitstreams encoded with VP8's and VP9's arithmetic boolean encoder. |
18 | | class BooleanDecoder { |
19 | | public: |
20 | | static ErrorOr<BooleanDecoder> initialize(ReadonlyBytes data); |
21 | | |
22 | | /* (9.2) */ |
23 | | bool read_bool(u8 probability); |
24 | | u8 read_literal(u8 bits); |
25 | | |
26 | | ErrorOr<void> finish_decode(); |
27 | | |
28 | | private: |
29 | | using ValueType = size_t; |
30 | | static constexpr u8 reserve_bytes = sizeof(ValueType) - 1; |
31 | | static constexpr u8 reserve_bits = reserve_bytes * 8; |
32 | | |
33 | | BooleanDecoder(u8 const* data, u64 bytes_left) |
34 | 5.75k | : m_data(data + 1) |
35 | 5.75k | , m_bytes_left(bytes_left - 1) |
36 | 5.75k | , m_range(255) |
37 | 5.75k | , m_value(static_cast<ValueType>(*data) << reserve_bits) |
38 | 5.75k | , m_value_bits_left(8) |
39 | 5.75k | { |
40 | 5.75k | fill_reservoir(); |
41 | 5.75k | } |
42 | | |
43 | | void fill_reservoir(); |
44 | | |
45 | | u8 const* m_data; |
46 | | size_t m_bytes_left { 0 }; |
47 | | bool m_overread { false }; |
48 | | // This value will never exceed 255. If this is a u8, the compiler will generate a truncation in read_bool(). |
49 | | u32 m_range { 0 }; |
50 | | ValueType m_value { 0 }; |
51 | | // Like above, this will never exceed reserve_bits, but will truncate if it is a u8. |
52 | | u32 m_value_bits_left { 0 }; |
53 | | }; |
54 | | |
55 | | } |