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/adaptive_rans_bit_encoder.h"
16 
17 #include "draco/compression/bit_coders/adaptive_rans_bit_coding_shared.h"
18 
19 namespace draco {
20 
AdaptiveRAnsBitEncoder()21 AdaptiveRAnsBitEncoder::AdaptiveRAnsBitEncoder() {}
22 
~AdaptiveRAnsBitEncoder()23 AdaptiveRAnsBitEncoder::~AdaptiveRAnsBitEncoder() { Clear(); }
24 
StartEncoding()25 void AdaptiveRAnsBitEncoder::StartEncoding() { Clear(); }
26 
EndEncoding(EncoderBuffer * target_buffer)27 void AdaptiveRAnsBitEncoder::EndEncoding(EncoderBuffer *target_buffer) {
28   // Buffer for ans to write.
29   std::vector<uint8_t> buffer(bits_.size() + 16);
30   AnsCoder ans_coder;
31   ans_write_init(&ans_coder, buffer.data());
32 
33   // Unfortunately we have to encode the bits in reversed order, while the
34   // probabilities that should be given are those of the forward sequence.
35   double p0_f = 0.5;
36   std::vector<uint8_t> p0s;
37   p0s.reserve(bits_.size());
38   for (bool b : bits_) {
39     p0s.push_back(clamp_probability(p0_f));
40     p0_f = update_probability(p0_f, b);
41   }
42   auto bit = bits_.rbegin();
43   auto pit = p0s.rbegin();
44   while (bit != bits_.rend()) {
45     rabs_write(&ans_coder, *bit, *pit);
46     ++bit;
47     ++pit;
48   }
49 
50   const uint32_t size_in_bytes = ans_write_end(&ans_coder);
51   target_buffer->Encode(size_in_bytes);
52   target_buffer->Encode(buffer.data(), size_in_bytes);
53 
54   Clear();
55 }
56 
Clear()57 void AdaptiveRAnsBitEncoder::Clear() { bits_.clear(); }
58 
59 }  // namespace draco
60