1 // Copyright 2014 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. 4 // 5 // This file contains an implementation of an H264 Annex-B video stream parser. 6 7 #ifndef H264_BIT_READER_H_ 8 #define H264_BIT_READER_H_ 9 10 #include <stddef.h> 11 #include <stdint.h> 12 #include <sys/types.h> 13 14 #include "base/macros.h" 15 16 namespace media { 17 18 // A class to provide bit-granularity reading of H.264 streams. 19 // This is not a generic bit reader class, as it takes into account 20 // H.264 stream-specific constraints, such as skipping emulation-prevention 21 // bytes and stop bits. See spec for more details. 22 class H264BitReader { 23 public: 24 H264BitReader(); 25 ~H264BitReader(); 26 27 // Initialize the reader to start reading at |data|, |size| being size 28 // of |data| in bytes. 29 // Return false on insufficient size of stream.. 30 // TODO(posciak,fischman): consider replacing Initialize() with 31 // heap-allocating and creating bit readers on demand instead. 32 bool Initialize(const uint8_t* data, off_t size); 33 34 // Read |num_bits| next bits from stream and return in |*out|, first bit 35 // from the stream starting at |num_bits| position in |*out|. 36 // |num_bits| may be 1-32, inclusive. 37 // Return false if the given number of bits cannot be read (not enough 38 // bits in the stream), true otherwise. 39 bool ReadBits(int num_bits, int* out); 40 41 // Return the number of bits left in the stream. 42 off_t NumBitsLeft(); 43 44 // See the definition of more_rbsp_data() in spec. 45 bool HasMoreRBSPData(); 46 47 // Return the number of emulation prevention bytes already read. 48 size_t NumEmulationPreventionBytesRead(); 49 50 private: 51 // Advance to the next byte, loading it into curr_byte_. 52 // Return false on end of stream. 53 bool UpdateCurrByte(); 54 55 // Pointer to the next unread (not in curr_byte_) byte in the stream. 56 const uint8_t* data_; 57 58 // Bytes left in the stream (without the curr_byte_). 59 off_t bytes_left_; 60 61 // Contents of the current byte; first unread bit starting at position 62 // 8 - num_remaining_bits_in_curr_byte_ from MSB. 63 int curr_byte_; 64 65 // Number of bits remaining in curr_byte_ 66 int num_remaining_bits_in_curr_byte_; 67 68 // Used in emulation prevention three byte detection (see spec). 69 // Initially set to 0xffff to accept all initial two-byte sequences. 70 int prev_two_bytes_; 71 72 // Number of emulation preventation bytes (0x000003) we met. 73 size_t emulation_prevention_bytes_; 74 75 DISALLOW_COPY_AND_ASSIGN(H264BitReader); 76 }; 77 78 } // namespace media 79 80 #endif // H264_BIT_READER_H_ 81