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 #include "draco/compression/bit_coders/rans_bit_decoder.h"
16
17 #include "draco/compression/config/compression_shared.h"
18 #include "draco/core/bit_utils.h"
19 #include "draco/core/varint_decoding.h"
20
21 namespace draco {
22
RAnsBitDecoder()23 RAnsBitDecoder::RAnsBitDecoder() : prob_zero_(0) {}
24
~RAnsBitDecoder()25 RAnsBitDecoder::~RAnsBitDecoder() { Clear(); }
26
StartDecoding(DecoderBuffer * source_buffer)27 bool RAnsBitDecoder::StartDecoding(DecoderBuffer *source_buffer) {
28 Clear();
29
30 if (!source_buffer->Decode(&prob_zero_))
31 return false;
32
33 uint32_t size_in_bytes;
34 #ifdef DRACO_BACKWARDS_COMPATIBILITY_SUPPORTED
35 if (source_buffer->bitstream_version() < DRACO_BITSTREAM_VERSION(2, 2)) {
36 if (!source_buffer->Decode(&size_in_bytes))
37 return false;
38
39 } else
40 #endif
41 {
42 if (!DecodeVarint(&size_in_bytes, source_buffer))
43 return false;
44 }
45
46 if (size_in_bytes > source_buffer->remaining_size())
47 return false;
48
49 if (ans_read_init(&ans_decoder_,
50 reinterpret_cast<uint8_t *>(
51 const_cast<char *>(source_buffer->data_head())),
52 size_in_bytes) != 0)
53 return false;
54 source_buffer->Advance(size_in_bytes);
55 return true;
56 }
57
DecodeNextBit()58 bool RAnsBitDecoder::DecodeNextBit() {
59 const uint8_t bit = rabs_read(&ans_decoder_, prob_zero_);
60 return bit > 0;
61 }
62
DecodeLeastSignificantBits32(int nbits,uint32_t * value)63 void RAnsBitDecoder::DecodeLeastSignificantBits32(int nbits, uint32_t *value) {
64 DRACO_DCHECK_EQ(true, nbits <= 32);
65 DRACO_DCHECK_EQ(true, nbits > 0);
66
67 uint32_t result = 0;
68 while (nbits) {
69 result = (result << 1) + DecodeNextBit();
70 --nbits;
71 }
72 *value = result;
73 }
74
Clear()75 void RAnsBitDecoder::Clear() { ans_read_end(&ans_decoder_); }
76
77 } // namespace draco
78