1 // Copyright 2016 The Draco Authors.
2 //
3 // Licensed under the Apache License, Version 2.0 (the "License");
4 // you may not use this file except in compliance with the License.
5 // You may obtain a copy of the License at
6 //
7 //      http://www.apache.org/licenses/LICENSE-2.0
8 //
9 // Unless required by applicable law or agreed to in writing, software
10 // distributed under the License is distributed on an "AS IS" BASIS,
11 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 // See the License for the specific language governing permissions and
13 // limitations under the License.
14 //
15 // File provides direct encoding of bits with arithmetic encoder interface.
16 #ifndef DRACO_COMPRESSION_BIT_CODERS_DIRECT_BIT_DECODER_H_
17 #define DRACO_COMPRESSION_BIT_CODERS_DIRECT_BIT_DECODER_H_
18 
19 #include <vector>
20 
21 #include "draco/core/decoder_buffer.h"
22 
23 namespace draco {
24 
25 class DirectBitDecoder {
26  public:
27   DirectBitDecoder();
28   ~DirectBitDecoder();
29 
30   // Sets |source_buffer| as the buffer to decode bits from.
31   bool StartDecoding(DecoderBuffer *source_buffer);
32 
33   // Decode one bit. Returns true if the bit is a 1, otherwise false.
DecodeNextBit()34   bool DecodeNextBit() {
35     const uint32_t selector = 1 << (31 - num_used_bits_);
36     if (pos_ == bits_.end()) {
37       return false;
38     }
39     const bool bit = *pos_ & selector;
40     ++num_used_bits_;
41     if (num_used_bits_ == 32) {
42       ++pos_;
43       num_used_bits_ = 0;
44     }
45     return bit;
46   }
47 
48   // Decode the next |nbits| and return the sequence in |value|. |nbits| must be
49   // > 0 and <= 32.
DecodeLeastSignificantBits32(int nbits,uint32_t * value)50   void DecodeLeastSignificantBits32(int nbits, uint32_t *value) {
51     DRACO_DCHECK_EQ(true, nbits <= 32);
52     DRACO_DCHECK_EQ(true, nbits > 0);
53     const int remaining = 32 - num_used_bits_;
54     if (nbits <= remaining) {
55       if (pos_ == bits_.end()) {
56         *value = 0;
57         return;
58       }
59       *value = (*pos_ << num_used_bits_) >> (32 - nbits);
60       num_used_bits_ += nbits;
61       if (num_used_bits_ == 32) {
62         ++pos_;
63         num_used_bits_ = 0;
64       }
65     } else {
66       if (pos_ + 1 == bits_.end()) {
67         *value = 0;
68         return;
69       }
70       const uint32_t value_l = ((*pos_) << num_used_bits_);
71       num_used_bits_ = nbits - remaining;
72       ++pos_;
73       const uint32_t value_r = (*pos_) >> (32 - num_used_bits_);
74       *value = (value_l >> (32 - num_used_bits_ - remaining)) | value_r;
75     }
76   }
77 
EndDecoding()78   void EndDecoding() {}
79 
80  private:
81   void Clear();
82 
83   std::vector<uint32_t> bits_;
84   std::vector<uint32_t>::const_iterator pos_;
85   uint32_t num_used_bits_;
86 };
87 
88 }  // namespace draco
89 
90 #endif  // DRACO_COMPRESSION_BIT_CODERS_DIRECT_BIT_DECODER_H_
91