DASH Media Packaging SDK
 All Classes Namespaces Functions Variables Typedefs
bit_reader.cc
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 #include "packager/media/base/bit_reader.h"
6 
7 #include <algorithm>
8 
9 namespace edash_packager {
10 namespace media {
11 
12 BitReader::BitReader(const uint8_t* data, off_t size)
13  : data_(data), bytes_left_(size), num_remaining_bits_in_curr_byte_(0) {
14  DCHECK(data_ != NULL && bytes_left_ > 0);
15 
16  UpdateCurrByte();
17 }
18 
19 BitReader::~BitReader() {}
20 
21 bool BitReader::SkipBits(int num_bits) {
22  DCHECK_GE(num_bits, 0);
23 
24  // Skip any bits in the current byte waiting to be processed, then
25  // process full bytes until less than 8 bits remaining.
26  if (num_bits > num_remaining_bits_in_curr_byte_) {
27  num_bits -= num_remaining_bits_in_curr_byte_;
28  num_remaining_bits_in_curr_byte_ = 0;
29 
30  int num_bytes = num_bits / 8;
31  num_bits %= 8;
32  if (bytes_left_ < num_bytes) {
33  bytes_left_ = 0;
34  return false;
35  }
36  bytes_left_ -= num_bytes;
37  data_ += num_bytes;
38  UpdateCurrByte();
39 
40  // If there is no more data remaining, only return true if we
41  // skipped all that were requested.
42  if (num_remaining_bits_in_curr_byte_ == 0)
43  return (num_bits == 0);
44  }
45 
46  // Less than 8 bits remaining to skip. Use ReadBitsInternal to verify
47  // that the remaining bits we need exist, and adjust them as necessary
48  // for subsequent operations.
49  uint64_t not_needed;
50  return ReadBitsInternal(num_bits, &not_needed);
51 }
52 
54  return 8 * bytes_left_ + num_remaining_bits_in_curr_byte_;
55 }
56 
57 bool BitReader::ReadBitsInternal(int num_bits, uint64_t* out) {
58  DCHECK_LE(num_bits, 64);
59 
60  *out = 0;
61 
62  while (num_remaining_bits_in_curr_byte_ != 0 && num_bits != 0) {
63  int bits_to_take = std::min(num_remaining_bits_in_curr_byte_, num_bits);
64 
65  *out <<= bits_to_take;
66  *out += curr_byte_ >> (num_remaining_bits_in_curr_byte_ - bits_to_take);
67  num_bits -= bits_to_take;
68  num_remaining_bits_in_curr_byte_ -= bits_to_take;
69  curr_byte_ &= (1 << num_remaining_bits_in_curr_byte_) - 1;
70 
71  if (num_remaining_bits_in_curr_byte_ == 0)
72  UpdateCurrByte();
73  }
74 
75  return num_bits == 0;
76 }
77 
78 void BitReader::UpdateCurrByte() {
79  DCHECK_EQ(num_remaining_bits_in_curr_byte_, 0);
80 
81  if (bytes_left_ == 0)
82  return;
83 
84  // Load a new byte and advance pointers.
85  curr_byte_ = *data_;
86  ++data_;
87  --bytes_left_;
88  num_remaining_bits_in_curr_byte_ = 8;
89 }
90 
91 } // namespace media
92 } // namespace edash_packager
BitReader(const uint8_t *data, off_t size)
Definition: bit_reader.cc:12
bool SkipBits(int num_bits)
Definition: bit_reader.cc:21