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