1 // Copyright (c) 2012 The Chromium Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file.
5 #include "content/common/gpu/media/h264_bit_reader.h"
6 #include "base/logging.h"
10 H264BitReader::H264BitReader()
11 : data_(NULL), bytes_left_(0), curr_byte_(0),
12 num_remaining_bits_in_curr_byte_(0), prev_two_bytes_(0),
13 emulation_prevention_bytes_(0) {
16 H264BitReader::~H264BitReader() {}
18 bool H264BitReader::Initialize(const uint8* data, off_t size) {
26 num_remaining_bits_in_curr_byte_ = 0;
27 // Initially set to 0xffff to accept all initial two-byte sequences.
28 prev_two_bytes_ = 0xffff;
29 emulation_prevention_bytes_ = 0;
34 bool H264BitReader::UpdateCurrByte() {
38 // Emulation prevention three-byte detection.
39 // If a sequence of 0x000003 is found, skip (ignore) the last byte (0x03).
40 if (*data_ == 0x03 && (prev_two_bytes_ & 0xffff) == 0) {
41 // Detected 0x000003, skip last byte.
44 ++emulation_prevention_bytes_;
45 // Need another full three bytes before we can detect the sequence again.
46 prev_two_bytes_ = 0xffff;
52 // Load a new byte and advance pointers.
53 curr_byte_ = *data_++ & 0xff;
55 num_remaining_bits_in_curr_byte_ = 8;
57 prev_two_bytes_ = (prev_two_bytes_ << 8) | curr_byte_;
62 // Read |num_bits| (1 to 31 inclusive) from the stream and return them
63 // in |out|, with first bit in the stream as MSB in |out| at position
65 bool H264BitReader::ReadBits(int num_bits, int *out) {
66 int bits_left = num_bits;
68 DCHECK(num_bits <= 31);
70 while (num_remaining_bits_in_curr_byte_ < bits_left) {
71 // Take all that's left in current byte, shift to make space for the rest.
72 *out |= (curr_byte_ << (bits_left - num_remaining_bits_in_curr_byte_));
73 bits_left -= num_remaining_bits_in_curr_byte_;
75 if (!UpdateCurrByte())
79 *out |= (curr_byte_ >> (num_remaining_bits_in_curr_byte_ - bits_left));
80 *out &= ((1 << num_bits) - 1);
81 num_remaining_bits_in_curr_byte_ -= bits_left;
86 off_t H264BitReader::NumBitsLeft() {
87 return (num_remaining_bits_in_curr_byte_ + bytes_left_ * 8);
90 bool H264BitReader::HasMoreRBSPData() {
91 // Make sure we have more bits, if we are at 0 bits in current byte
92 // and updating current byte fails, we don't have more data anyway.
93 if (num_remaining_bits_in_curr_byte_ == 0 && !UpdateCurrByte())
100 // Last byte, look for stop bit;
101 // We have more RBSP data if the last non-zero bit we find is not the
102 // first available bit.
104 ((1 << (num_remaining_bits_in_curr_byte_ - 1)) - 1)) != 0;
107 size_t H264BitReader::NumEmulationPreventionBytesRead()
109 return emulation_prevention_bytes_;
112 } // namespace content