DASH Media Packaging SDK
 All Classes Namespaces Functions Variables Typedefs Enumerator
bit_reader.h
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.
4 
5 #ifndef MEDIA_BASE_BIT_READER_H_
6 #define MEDIA_BASE_BIT_READER_H_
7 
8 #include <stdint.h>
9 #include <sys/types.h>
10 
11 #include "packager/base/logging.h"
12 
13 namespace edash_packager {
14 namespace media {
15 
17 class BitReader {
18  public:
22  BitReader(const uint8_t* data, off_t size);
23  ~BitReader();
24 
34  template <typename T>
35  bool ReadBits(int num_bits, T* out) {
36  DCHECK_LE(num_bits, static_cast<int>(sizeof(T) * 8));
37  uint64_t temp;
38  bool ret = ReadBitsInternal(num_bits, &temp);
39  *out = static_cast<T>(temp);
40  return ret;
41  }
42 
49  bool SkipBits(int num_bits);
50 
60  bool SkipBitsConditional(bool condition, int num_bits) {
61  bool condition_read = true;
62  if (!ReadBits(1, &condition_read))
63  return false;
64  return condition_read == condition ? SkipBits(num_bits) : true;
65  }
66 
73  bool SkipBytes(int num_bytes);
74 
76  int bits_available() const {
77  return 8 * bytes_left_ + num_remaining_bits_in_curr_byte_;
78  }
79 
81  int bit_position() const { return 8 * initial_size_ - bits_available(); }
82 
83  private:
84  // Help function used by ReadBits to avoid inlining the bit reading logic.
85  bool ReadBitsInternal(int num_bits, uint64_t* out);
86 
87  // Advance to the next byte, loading it into curr_byte_.
88  // If the num_remaining_bits_in_curr_byte_ is 0 after this function returns,
89  // the stream has reached the end.
90  void UpdateCurrByte();
91 
92  // Pointer to the next unread (not in curr_byte_) byte in the stream.
93  const uint8_t* data_;
94 
95  // Initial size of the input data.
96  // TODO(kqyang): Use size_t instead of off_t instead.
97  off_t initial_size_;
98 
99  // Bytes left in the stream (without the curr_byte_).
100  off_t bytes_left_;
101 
102  // Contents of the current byte; first unread bit starting at position
103  // 8 - num_remaining_bits_in_curr_byte_ from MSB.
104  uint8_t curr_byte_;
105 
106  // Number of bits remaining in curr_byte_
107  int num_remaining_bits_in_curr_byte_;
108 
109  private:
110  DISALLOW_COPY_AND_ASSIGN(BitReader);
111 };
112 
113 } // namespace media
114 } // namespace edash_packager
115 
116 #endif // MEDIA_BASE_BIT_READER_H_
BitReader(const uint8_t *data, off_t size)
Definition: bit_reader.cc:12
bool ReadBits(int num_bits, T *out)
Definition: bit_reader.h:35
A class to read bit streams.
Definition: bit_reader.h:17
bool SkipBits(int num_bits)
Definition: bit_reader.cc:24
bool SkipBitsConditional(bool condition, int num_bits)
Definition: bit_reader.h:60
bool SkipBytes(int num_bytes)
Definition: bit_reader.cc:56