5 #include <packager/media/codecs/h26x_bit_reader.h>
7 #include <absl/log/check.h>
8 #include <absl/log/log.h>
15 bool CheckAnyBitsSet(
int byte,
int valid_bits) {
16 return (
byte & ((1 << valid_bits) - 1)) != 0;
21 H26xBitReader::H26xBitReader()
25 num_remaining_bits_in_curr_byte_(0),
27 emulation_prevention_bytes_(0) {}
29 H26xBitReader::~H26xBitReader() {}
31 bool H26xBitReader::Initialize(
const uint8_t* data, off_t size) {
39 num_remaining_bits_in_curr_byte_ = 0;
41 prev_two_bytes_ = 0xffff;
42 emulation_prevention_bytes_ = 0;
47 bool H26xBitReader::UpdateCurrByte() {
53 if (*data_ == 0x03 && (prev_two_bytes_ & 0xffff) == 0) {
57 ++emulation_prevention_bytes_;
59 prev_two_bytes_ = 0xffff;
66 curr_byte_ = *data_++ & 0xff;
68 num_remaining_bits_in_curr_byte_ = 8;
70 prev_two_bytes_ = (prev_two_bytes_ << 8) | curr_byte_;
78 bool H26xBitReader::ReadBits(
int num_bits,
int* out) {
79 int bits_left = num_bits;
81 DCHECK(num_bits <= 31);
83 while (num_remaining_bits_in_curr_byte_ < bits_left) {
85 *out |= (curr_byte_ << (bits_left - num_remaining_bits_in_curr_byte_));
86 bits_left -= num_remaining_bits_in_curr_byte_;
88 if (!UpdateCurrByte())
92 *out |= (curr_byte_ >> (num_remaining_bits_in_curr_byte_ - bits_left));
93 *out &= ((1 << num_bits) - 1);
94 num_remaining_bits_in_curr_byte_ -= bits_left;
99 bool H26xBitReader::SkipBits(
int num_bits) {
100 int bits_left = num_bits;
101 while (num_remaining_bits_in_curr_byte_ < bits_left) {
102 bits_left -= num_remaining_bits_in_curr_byte_;
103 if (!UpdateCurrByte())
107 num_remaining_bits_in_curr_byte_ -= bits_left;
111 bool H26xBitReader::ReadUE(
int* val) {
118 if (!ReadBits(1, &bit))
127 *val = (1 << num_bits) - 1;
130 if (!ReadBits(num_bits, &rest))
138 bool H26xBitReader::ReadSE(
int* val) {
153 off_t H26xBitReader::NumBitsLeft() {
154 return (num_remaining_bits_in_curr_byte_ + bytes_left_ * 8);
157 bool H26xBitReader::HasMoreRBSPData() {
160 if (num_remaining_bits_in_curr_byte_ == 0 && !UpdateCurrByte())
167 if (CheckAnyBitsSet(curr_byte_, num_remaining_bits_in_curr_byte_ - 1))
174 for (off_t i = 0; i < bytes_left_; i++) {
183 size_t H26xBitReader::NumEmulationPreventionBytesRead() {
184 return emulation_prevention_bytes_;
All the methods that are virtual are virtual for mocking.