1.1 --- /dev/null Thu Jan 01 00:00:00 1970 +0000 1.2 +++ b/content/media/fmp4/demuxer/bit_reader.h Wed Dec 31 06:09:35 2014 +0100 1.3 @@ -0,0 +1,69 @@ 1.4 +// Copyright (c) 2012 The Chromium Authors. All rights reserved. 1.5 +// Use of this source code is governed by a BSD-style license that can be 1.6 +// found in the LICENSE file. 1.7 + 1.8 +#ifndef MEDIA_BASE_BIT_READER_H_ 1.9 +#define MEDIA_BASE_BIT_READER_H_ 1.10 + 1.11 +#include <sys/types.h> 1.12 + 1.13 +#include "mp4_demuxer/basictypes.h" 1.14 + 1.15 +namespace mp4_demuxer { 1.16 + 1.17 +// A class to read bit streams. 1.18 +class BitReader { 1.19 + public: 1.20 + // Initialize the reader to start reading at |data|, |size| being size 1.21 + // of |data| in bytes. 1.22 + BitReader(const uint8_t* data, off_t size); 1.23 + ~BitReader(); 1.24 + 1.25 + // Read |num_bits| next bits from stream and return in |*out|, first bit 1.26 + // from the stream starting at |num_bits| position in |*out|. 1.27 + // |num_bits| cannot be larger than the bits the type can hold. 1.28 + // Return false if the given number of bits cannot be read (not enough 1.29 + // bits in the stream), true otherwise. When return false, the stream will 1.30 + // enter a state where further ReadBits/SkipBits operations will always 1.31 + // return false unless |num_bits| is 0. The type |T| has to be a primitive 1.32 + // integer type. 1.33 + template<typename T> bool ReadBits(int num_bits, T *out) { 1.34 + DCHECK_LE(num_bits, static_cast<int>(sizeof(T) * 8)); 1.35 + uint64_t temp; 1.36 + bool ret = ReadBitsInternal(num_bits, &temp); 1.37 + *out = static_cast<T>(temp); 1.38 + return ret; 1.39 + } 1.40 + 1.41 + // Returns the number of bits available for reading. 1.42 + int bits_available() const; 1.43 + 1.44 + private: 1.45 + // Help function used by ReadBits to avoid inlining the bit reading logic. 1.46 + bool ReadBitsInternal(int num_bits, uint64_t* out); 1.47 + 1.48 + // Advance to the next byte, loading it into curr_byte_. 1.49 + // If the num_remaining_bits_in_curr_byte_ is 0 after this function returns, 1.50 + // the stream has reached the end. 1.51 + void UpdateCurrByte(); 1.52 + 1.53 + // Pointer to the next unread (not in curr_byte_) byte in the stream. 1.54 + const uint8_t* data_; 1.55 + 1.56 + // Bytes left in the stream (without the curr_byte_). 1.57 + off_t bytes_left_; 1.58 + 1.59 + // Contents of the current byte; first unread bit starting at position 1.60 + // 8 - num_remaining_bits_in_curr_byte_ from MSB. 1.61 + uint8_t curr_byte_; 1.62 + 1.63 + // Number of bits remaining in curr_byte_ 1.64 + int num_remaining_bits_in_curr_byte_; 1.65 + 1.66 + private: 1.67 + DISALLOW_COPY_AND_ASSIGN(BitReader); 1.68 +}; 1.69 + 1.70 +} // namespace mp4_demuxer 1.71 + 1.72 +#endif // MEDIA_BASE_BIT_READER_H_