xref: /aosp_15_r20/external/libaom/aom_dsp/entenc.c (revision 77c1e3ccc04c968bd2bc212e87364f250e820521)
1*77c1e3ccSAndroid Build Coastguard Worker /*
2*77c1e3ccSAndroid Build Coastguard Worker  * Copyright (c) 2001-2016, Alliance for Open Media. All rights reserved.
3*77c1e3ccSAndroid Build Coastguard Worker  *
4*77c1e3ccSAndroid Build Coastguard Worker  * This source code is subject to the terms of the BSD 2 Clause License and
5*77c1e3ccSAndroid Build Coastguard Worker  * the Alliance for Open Media Patent License 1.0. If the BSD 2 Clause License
6*77c1e3ccSAndroid Build Coastguard Worker  * was not distributed with this source code in the LICENSE file, you can
7*77c1e3ccSAndroid Build Coastguard Worker  * obtain it at www.aomedia.org/license/software. If the Alliance for Open
8*77c1e3ccSAndroid Build Coastguard Worker  * Media Patent License 1.0 was not distributed with this source code in the
9*77c1e3ccSAndroid Build Coastguard Worker  * PATENTS file, you can obtain it at www.aomedia.org/license/patent.
10*77c1e3ccSAndroid Build Coastguard Worker  */
11*77c1e3ccSAndroid Build Coastguard Worker 
12*77c1e3ccSAndroid Build Coastguard Worker #include <stdlib.h>
13*77c1e3ccSAndroid Build Coastguard Worker #include <string.h>
14*77c1e3ccSAndroid Build Coastguard Worker #include <math.h>
15*77c1e3ccSAndroid Build Coastguard Worker #include <assert.h>
16*77c1e3ccSAndroid Build Coastguard Worker #include "aom_dsp/entenc.h"
17*77c1e3ccSAndroid Build Coastguard Worker #include "aom_dsp/prob.h"
18*77c1e3ccSAndroid Build Coastguard Worker 
19*77c1e3ccSAndroid Build Coastguard Worker #if OD_MEASURE_EC_OVERHEAD
20*77c1e3ccSAndroid Build Coastguard Worker #if !defined(M_LOG2E)
21*77c1e3ccSAndroid Build Coastguard Worker #define M_LOG2E (1.4426950408889634073599246810019)
22*77c1e3ccSAndroid Build Coastguard Worker #endif
23*77c1e3ccSAndroid Build Coastguard Worker #define OD_LOG2(x) (M_LOG2E * log(x))
24*77c1e3ccSAndroid Build Coastguard Worker #endif  // OD_MEASURE_EC_OVERHEAD
25*77c1e3ccSAndroid Build Coastguard Worker 
26*77c1e3ccSAndroid Build Coastguard Worker /*A range encoder.
27*77c1e3ccSAndroid Build Coastguard Worker   See entdec.c and the references for implementation details \cite{Mar79,MNW98}.
28*77c1e3ccSAndroid Build Coastguard Worker 
29*77c1e3ccSAndroid Build Coastguard Worker   @INPROCEEDINGS{Mar79,
30*77c1e3ccSAndroid Build Coastguard Worker    author="Martin, G.N.N.",
31*77c1e3ccSAndroid Build Coastguard Worker    title="Range encoding: an algorithm for removing redundancy from a digitised
32*77c1e3ccSAndroid Build Coastguard Worker     message",
33*77c1e3ccSAndroid Build Coastguard Worker    booktitle="Video \& Data Recording Conference",
34*77c1e3ccSAndroid Build Coastguard Worker    year=1979,
35*77c1e3ccSAndroid Build Coastguard Worker    address="Southampton",
36*77c1e3ccSAndroid Build Coastguard Worker    month=Jul,
37*77c1e3ccSAndroid Build Coastguard Worker    URL="http://www.compressconsult.com/rangecoder/rngcod.pdf.gz"
38*77c1e3ccSAndroid Build Coastguard Worker   }
39*77c1e3ccSAndroid Build Coastguard Worker   @ARTICLE{MNW98,
40*77c1e3ccSAndroid Build Coastguard Worker    author="Alistair Moffat and Radford Neal and Ian H. Witten",
41*77c1e3ccSAndroid Build Coastguard Worker    title="Arithmetic Coding Revisited",
42*77c1e3ccSAndroid Build Coastguard Worker    journal="{ACM} Transactions on Information Systems",
43*77c1e3ccSAndroid Build Coastguard Worker    year=1998,
44*77c1e3ccSAndroid Build Coastguard Worker    volume=16,
45*77c1e3ccSAndroid Build Coastguard Worker    number=3,
46*77c1e3ccSAndroid Build Coastguard Worker    pages="256--294",
47*77c1e3ccSAndroid Build Coastguard Worker    month=Jul,
48*77c1e3ccSAndroid Build Coastguard Worker    URL="http://researchcommons.waikato.ac.nz/bitstream/handle/10289/78/content.pdf"
49*77c1e3ccSAndroid Build Coastguard Worker   }*/
50*77c1e3ccSAndroid Build Coastguard Worker 
51*77c1e3ccSAndroid Build Coastguard Worker /*Takes updated low and range values, renormalizes them so that
52*77c1e3ccSAndroid Build Coastguard Worker    32768 <= rng < 65536 (flushing bytes from low to the output buffer if
53*77c1e3ccSAndroid Build Coastguard Worker    necessary), and stores them back in the encoder context.
54*77c1e3ccSAndroid Build Coastguard Worker   low: The new value of low.
55*77c1e3ccSAndroid Build Coastguard Worker   rng: The new value of the range.*/
od_ec_enc_normalize(od_ec_enc * enc,od_ec_enc_window low,unsigned rng)56*77c1e3ccSAndroid Build Coastguard Worker static void od_ec_enc_normalize(od_ec_enc *enc, od_ec_enc_window low,
57*77c1e3ccSAndroid Build Coastguard Worker                                 unsigned rng) {
58*77c1e3ccSAndroid Build Coastguard Worker   int d;
59*77c1e3ccSAndroid Build Coastguard Worker   int c;
60*77c1e3ccSAndroid Build Coastguard Worker   int s;
61*77c1e3ccSAndroid Build Coastguard Worker   if (enc->error) return;
62*77c1e3ccSAndroid Build Coastguard Worker   c = enc->cnt;
63*77c1e3ccSAndroid Build Coastguard Worker   assert(rng <= 65535U);
64*77c1e3ccSAndroid Build Coastguard Worker   /*The number of leading zeros in the 16-bit binary representation of rng.*/
65*77c1e3ccSAndroid Build Coastguard Worker   d = 16 - OD_ILOG_NZ(rng);
66*77c1e3ccSAndroid Build Coastguard Worker   s = c + d;
67*77c1e3ccSAndroid Build Coastguard Worker 
68*77c1e3ccSAndroid Build Coastguard Worker   /* We flush every time "low" cannot safely and efficiently accommodate any
69*77c1e3ccSAndroid Build Coastguard Worker      more data. Overall, c must not exceed 63 at the time of byte flush out. To
70*77c1e3ccSAndroid Build Coastguard Worker      facilitate this, "s" cannot exceed 56-bits because we have to keep 1 byte
71*77c1e3ccSAndroid Build Coastguard Worker      for carry. Also, we need to subtract 16 because we want to keep room for
72*77c1e3ccSAndroid Build Coastguard Worker      the next symbol worth "d"-bits (max 15). An alternate condition would be if
73*77c1e3ccSAndroid Build Coastguard Worker      (e < d), where e = number of leading zeros in "low", indicating there is
74*77c1e3ccSAndroid Build Coastguard Worker      not enough rooom to accommodate "rng" worth of "d"-bits in "low". However,
75*77c1e3ccSAndroid Build Coastguard Worker      this approach needs additional computations: (i) compute "e", (ii) push
76*77c1e3ccSAndroid Build Coastguard Worker      the leading 0x00's as a special case.
77*77c1e3ccSAndroid Build Coastguard Worker   */
78*77c1e3ccSAndroid Build Coastguard Worker   if (s >= 40) {  // 56 - 16
79*77c1e3ccSAndroid Build Coastguard Worker     unsigned char *out = enc->buf;
80*77c1e3ccSAndroid Build Coastguard Worker     uint32_t storage = enc->storage;
81*77c1e3ccSAndroid Build Coastguard Worker     uint32_t offs = enc->offs;
82*77c1e3ccSAndroid Build Coastguard Worker     if (offs + 8 > storage) {
83*77c1e3ccSAndroid Build Coastguard Worker       storage = 2 * storage + 8;
84*77c1e3ccSAndroid Build Coastguard Worker       out = (unsigned char *)realloc(out, sizeof(*out) * storage);
85*77c1e3ccSAndroid Build Coastguard Worker       if (out == NULL) {
86*77c1e3ccSAndroid Build Coastguard Worker         enc->error = -1;
87*77c1e3ccSAndroid Build Coastguard Worker         return;
88*77c1e3ccSAndroid Build Coastguard Worker       }
89*77c1e3ccSAndroid Build Coastguard Worker       enc->buf = out;
90*77c1e3ccSAndroid Build Coastguard Worker       enc->storage = storage;
91*77c1e3ccSAndroid Build Coastguard Worker     }
92*77c1e3ccSAndroid Build Coastguard Worker     // Need to add 1 byte here since enc->cnt always counts 1 byte less
93*77c1e3ccSAndroid Build Coastguard Worker     // (enc->cnt = -9) to ensure correct operation
94*77c1e3ccSAndroid Build Coastguard Worker     uint8_t num_bytes_ready = (s >> 3) + 1;
95*77c1e3ccSAndroid Build Coastguard Worker 
96*77c1e3ccSAndroid Build Coastguard Worker     // Update "c" to contain the number of non-ready bits in "low". Since "low"
97*77c1e3ccSAndroid Build Coastguard Worker     // has 64-bit capacity, we need to add the (64 - 40) cushion bits and take
98*77c1e3ccSAndroid Build Coastguard Worker     // off the number of ready bits.
99*77c1e3ccSAndroid Build Coastguard Worker     c += 24 - (num_bytes_ready << 3);
100*77c1e3ccSAndroid Build Coastguard Worker 
101*77c1e3ccSAndroid Build Coastguard Worker     // Prepare "output" and update "low"
102*77c1e3ccSAndroid Build Coastguard Worker     uint64_t output = low >> c;
103*77c1e3ccSAndroid Build Coastguard Worker     low = low & (((uint64_t)1 << c) - 1);
104*77c1e3ccSAndroid Build Coastguard Worker 
105*77c1e3ccSAndroid Build Coastguard Worker     // Prepare data and carry mask
106*77c1e3ccSAndroid Build Coastguard Worker     uint64_t mask = (uint64_t)1 << (num_bytes_ready << 3);
107*77c1e3ccSAndroid Build Coastguard Worker     uint64_t carry = output & mask;
108*77c1e3ccSAndroid Build Coastguard Worker 
109*77c1e3ccSAndroid Build Coastguard Worker     mask = mask - 0x01;
110*77c1e3ccSAndroid Build Coastguard Worker     output = output & mask;
111*77c1e3ccSAndroid Build Coastguard Worker 
112*77c1e3ccSAndroid Build Coastguard Worker     // Write data in a single operation
113*77c1e3ccSAndroid Build Coastguard Worker     write_enc_data_to_out_buf(out, offs, output, carry, &enc->offs,
114*77c1e3ccSAndroid Build Coastguard Worker                               num_bytes_ready);
115*77c1e3ccSAndroid Build Coastguard Worker 
116*77c1e3ccSAndroid Build Coastguard Worker     // Update state of the encoder: enc->cnt to contain the number of residual
117*77c1e3ccSAndroid Build Coastguard Worker     // bits
118*77c1e3ccSAndroid Build Coastguard Worker     s = c + d - 24;
119*77c1e3ccSAndroid Build Coastguard Worker   }
120*77c1e3ccSAndroid Build Coastguard Worker   enc->low = low << d;
121*77c1e3ccSAndroid Build Coastguard Worker   enc->rng = rng << d;
122*77c1e3ccSAndroid Build Coastguard Worker   enc->cnt = s;
123*77c1e3ccSAndroid Build Coastguard Worker }
124*77c1e3ccSAndroid Build Coastguard Worker 
125*77c1e3ccSAndroid Build Coastguard Worker /*Initializes the encoder.
126*77c1e3ccSAndroid Build Coastguard Worker   size: The initial size of the buffer, in bytes.*/
od_ec_enc_init(od_ec_enc * enc,uint32_t size)127*77c1e3ccSAndroid Build Coastguard Worker void od_ec_enc_init(od_ec_enc *enc, uint32_t size) {
128*77c1e3ccSAndroid Build Coastguard Worker   od_ec_enc_reset(enc);
129*77c1e3ccSAndroid Build Coastguard Worker   enc->buf = (unsigned char *)malloc(sizeof(*enc->buf) * size);
130*77c1e3ccSAndroid Build Coastguard Worker   enc->storage = size;
131*77c1e3ccSAndroid Build Coastguard Worker   if (size > 0 && enc->buf == NULL) {
132*77c1e3ccSAndroid Build Coastguard Worker     enc->storage = 0;
133*77c1e3ccSAndroid Build Coastguard Worker     enc->error = -1;
134*77c1e3ccSAndroid Build Coastguard Worker   }
135*77c1e3ccSAndroid Build Coastguard Worker }
136*77c1e3ccSAndroid Build Coastguard Worker 
137*77c1e3ccSAndroid Build Coastguard Worker /*Reinitializes the encoder.*/
od_ec_enc_reset(od_ec_enc * enc)138*77c1e3ccSAndroid Build Coastguard Worker void od_ec_enc_reset(od_ec_enc *enc) {
139*77c1e3ccSAndroid Build Coastguard Worker   enc->offs = 0;
140*77c1e3ccSAndroid Build Coastguard Worker   enc->low = 0;
141*77c1e3ccSAndroid Build Coastguard Worker   enc->rng = 0x8000;
142*77c1e3ccSAndroid Build Coastguard Worker   /*This is initialized to -9 so that it crosses zero after we've accumulated
143*77c1e3ccSAndroid Build Coastguard Worker      one byte + one carry bit.*/
144*77c1e3ccSAndroid Build Coastguard Worker   enc->cnt = -9;
145*77c1e3ccSAndroid Build Coastguard Worker   enc->error = 0;
146*77c1e3ccSAndroid Build Coastguard Worker #if OD_MEASURE_EC_OVERHEAD
147*77c1e3ccSAndroid Build Coastguard Worker   enc->entropy = 0;
148*77c1e3ccSAndroid Build Coastguard Worker   enc->nb_symbols = 0;
149*77c1e3ccSAndroid Build Coastguard Worker #endif
150*77c1e3ccSAndroid Build Coastguard Worker }
151*77c1e3ccSAndroid Build Coastguard Worker 
152*77c1e3ccSAndroid Build Coastguard Worker /*Frees the buffers used by the encoder.*/
od_ec_enc_clear(od_ec_enc * enc)153*77c1e3ccSAndroid Build Coastguard Worker void od_ec_enc_clear(od_ec_enc *enc) { free(enc->buf); }
154*77c1e3ccSAndroid Build Coastguard Worker 
155*77c1e3ccSAndroid Build Coastguard Worker /*Encodes a symbol given its frequency in Q15.
156*77c1e3ccSAndroid Build Coastguard Worker   fl: CDF_PROB_TOP minus the cumulative frequency of all symbols that come
157*77c1e3ccSAndroid Build Coastguard Worker   before the one to be encoded.
158*77c1e3ccSAndroid Build Coastguard Worker   fh: CDF_PROB_TOP minus the cumulative frequency of all symbols up to and
159*77c1e3ccSAndroid Build Coastguard Worker   including the one to be encoded.*/
od_ec_encode_q15(od_ec_enc * enc,unsigned fl,unsigned fh,int s,int nsyms)160*77c1e3ccSAndroid Build Coastguard Worker static void od_ec_encode_q15(od_ec_enc *enc, unsigned fl, unsigned fh, int s,
161*77c1e3ccSAndroid Build Coastguard Worker                              int nsyms) {
162*77c1e3ccSAndroid Build Coastguard Worker   od_ec_enc_window l;
163*77c1e3ccSAndroid Build Coastguard Worker   unsigned r;
164*77c1e3ccSAndroid Build Coastguard Worker   unsigned u;
165*77c1e3ccSAndroid Build Coastguard Worker   unsigned v;
166*77c1e3ccSAndroid Build Coastguard Worker   l = enc->low;
167*77c1e3ccSAndroid Build Coastguard Worker   r = enc->rng;
168*77c1e3ccSAndroid Build Coastguard Worker   assert(32768U <= r);
169*77c1e3ccSAndroid Build Coastguard Worker   assert(fh <= fl);
170*77c1e3ccSAndroid Build Coastguard Worker   assert(fl <= 32768U);
171*77c1e3ccSAndroid Build Coastguard Worker   assert(7 - EC_PROB_SHIFT >= 0);
172*77c1e3ccSAndroid Build Coastguard Worker   const int N = nsyms - 1;
173*77c1e3ccSAndroid Build Coastguard Worker   if (fl < CDF_PROB_TOP) {
174*77c1e3ccSAndroid Build Coastguard Worker     u = ((r >> 8) * (uint32_t)(fl >> EC_PROB_SHIFT) >> (7 - EC_PROB_SHIFT)) +
175*77c1e3ccSAndroid Build Coastguard Worker         EC_MIN_PROB * (N - (s - 1));
176*77c1e3ccSAndroid Build Coastguard Worker     v = ((r >> 8) * (uint32_t)(fh >> EC_PROB_SHIFT) >> (7 - EC_PROB_SHIFT)) +
177*77c1e3ccSAndroid Build Coastguard Worker         EC_MIN_PROB * (N - (s + 0));
178*77c1e3ccSAndroid Build Coastguard Worker     l += r - u;
179*77c1e3ccSAndroid Build Coastguard Worker     r = u - v;
180*77c1e3ccSAndroid Build Coastguard Worker   } else {
181*77c1e3ccSAndroid Build Coastguard Worker     r -= ((r >> 8) * (uint32_t)(fh >> EC_PROB_SHIFT) >> (7 - EC_PROB_SHIFT)) +
182*77c1e3ccSAndroid Build Coastguard Worker          EC_MIN_PROB * (N - (s + 0));
183*77c1e3ccSAndroid Build Coastguard Worker   }
184*77c1e3ccSAndroid Build Coastguard Worker   od_ec_enc_normalize(enc, l, r);
185*77c1e3ccSAndroid Build Coastguard Worker #if OD_MEASURE_EC_OVERHEAD
186*77c1e3ccSAndroid Build Coastguard Worker   enc->entropy -= OD_LOG2((double)(OD_ICDF(fh) - OD_ICDF(fl)) / CDF_PROB_TOP.);
187*77c1e3ccSAndroid Build Coastguard Worker   enc->nb_symbols++;
188*77c1e3ccSAndroid Build Coastguard Worker #endif
189*77c1e3ccSAndroid Build Coastguard Worker }
190*77c1e3ccSAndroid Build Coastguard Worker 
191*77c1e3ccSAndroid Build Coastguard Worker /*Encode a single binary value.
192*77c1e3ccSAndroid Build Coastguard Worker   val: The value to encode (0 or 1).
193*77c1e3ccSAndroid Build Coastguard Worker   f: The probability that the val is one, scaled by 32768.*/
od_ec_encode_bool_q15(od_ec_enc * enc,int val,unsigned f)194*77c1e3ccSAndroid Build Coastguard Worker void od_ec_encode_bool_q15(od_ec_enc *enc, int val, unsigned f) {
195*77c1e3ccSAndroid Build Coastguard Worker   od_ec_enc_window l;
196*77c1e3ccSAndroid Build Coastguard Worker   unsigned r;
197*77c1e3ccSAndroid Build Coastguard Worker   unsigned v;
198*77c1e3ccSAndroid Build Coastguard Worker   assert(0 < f);
199*77c1e3ccSAndroid Build Coastguard Worker   assert(f < 32768U);
200*77c1e3ccSAndroid Build Coastguard Worker   l = enc->low;
201*77c1e3ccSAndroid Build Coastguard Worker   r = enc->rng;
202*77c1e3ccSAndroid Build Coastguard Worker   assert(32768U <= r);
203*77c1e3ccSAndroid Build Coastguard Worker   v = ((r >> 8) * (uint32_t)(f >> EC_PROB_SHIFT) >> (7 - EC_PROB_SHIFT));
204*77c1e3ccSAndroid Build Coastguard Worker   v += EC_MIN_PROB;
205*77c1e3ccSAndroid Build Coastguard Worker   if (val) l += r - v;
206*77c1e3ccSAndroid Build Coastguard Worker   r = val ? v : r - v;
207*77c1e3ccSAndroid Build Coastguard Worker   od_ec_enc_normalize(enc, l, r);
208*77c1e3ccSAndroid Build Coastguard Worker #if OD_MEASURE_EC_OVERHEAD
209*77c1e3ccSAndroid Build Coastguard Worker   enc->entropy -= OD_LOG2((double)(val ? f : (32768 - f)) / 32768.);
210*77c1e3ccSAndroid Build Coastguard Worker   enc->nb_symbols++;
211*77c1e3ccSAndroid Build Coastguard Worker #endif
212*77c1e3ccSAndroid Build Coastguard Worker }
213*77c1e3ccSAndroid Build Coastguard Worker 
214*77c1e3ccSAndroid Build Coastguard Worker /*Encodes a symbol given a cumulative distribution function (CDF) table in Q15.
215*77c1e3ccSAndroid Build Coastguard Worker   s: The index of the symbol to encode.
216*77c1e3ccSAndroid Build Coastguard Worker   icdf: 32768 minus the CDF, such that symbol s falls in the range
217*77c1e3ccSAndroid Build Coastguard Worker          [s > 0 ? (32768 - icdf[s - 1]) : 0, 32768 - icdf[s]).
218*77c1e3ccSAndroid Build Coastguard Worker         The values must be monotonically decreasing, and icdf[nsyms - 1] must
219*77c1e3ccSAndroid Build Coastguard Worker          be 0.
220*77c1e3ccSAndroid Build Coastguard Worker   nsyms: The number of symbols in the alphabet.
221*77c1e3ccSAndroid Build Coastguard Worker          This should be at most 16.*/
od_ec_encode_cdf_q15(od_ec_enc * enc,int s,const uint16_t * icdf,int nsyms)222*77c1e3ccSAndroid Build Coastguard Worker void od_ec_encode_cdf_q15(od_ec_enc *enc, int s, const uint16_t *icdf,
223*77c1e3ccSAndroid Build Coastguard Worker                           int nsyms) {
224*77c1e3ccSAndroid Build Coastguard Worker   (void)nsyms;
225*77c1e3ccSAndroid Build Coastguard Worker   assert(s >= 0);
226*77c1e3ccSAndroid Build Coastguard Worker   assert(s < nsyms);
227*77c1e3ccSAndroid Build Coastguard Worker   assert(icdf[nsyms - 1] == OD_ICDF(CDF_PROB_TOP));
228*77c1e3ccSAndroid Build Coastguard Worker   od_ec_encode_q15(enc, s > 0 ? icdf[s - 1] : OD_ICDF(0), icdf[s], s, nsyms);
229*77c1e3ccSAndroid Build Coastguard Worker }
230*77c1e3ccSAndroid Build Coastguard Worker 
231*77c1e3ccSAndroid Build Coastguard Worker /*Overwrites a few bits at the very start of an existing stream, after they
232*77c1e3ccSAndroid Build Coastguard Worker    have already been encoded.
233*77c1e3ccSAndroid Build Coastguard Worker   This makes it possible to have a few flags up front, where it is easy for
234*77c1e3ccSAndroid Build Coastguard Worker    decoders to access them without parsing the whole stream, even if their
235*77c1e3ccSAndroid Build Coastguard Worker    values are not determined until late in the encoding process, without having
236*77c1e3ccSAndroid Build Coastguard Worker    to buffer all the intermediate symbols in the encoder.
237*77c1e3ccSAndroid Build Coastguard Worker   In order for this to work, at least nbits bits must have already been encoded
238*77c1e3ccSAndroid Build Coastguard Worker    using probabilities that are an exact power of two.
239*77c1e3ccSAndroid Build Coastguard Worker   The encoder can verify the number of encoded bits is sufficient, but cannot
240*77c1e3ccSAndroid Build Coastguard Worker    check this latter condition.
241*77c1e3ccSAndroid Build Coastguard Worker   val: The bits to encode (in the least nbits significant bits).
242*77c1e3ccSAndroid Build Coastguard Worker        They will be decoded in order from most-significant to least.
243*77c1e3ccSAndroid Build Coastguard Worker   nbits: The number of bits to overwrite.
244*77c1e3ccSAndroid Build Coastguard Worker          This must be no more than 8.*/
od_ec_enc_patch_initial_bits(od_ec_enc * enc,unsigned val,int nbits)245*77c1e3ccSAndroid Build Coastguard Worker void od_ec_enc_patch_initial_bits(od_ec_enc *enc, unsigned val, int nbits) {
246*77c1e3ccSAndroid Build Coastguard Worker   int shift;
247*77c1e3ccSAndroid Build Coastguard Worker   unsigned mask;
248*77c1e3ccSAndroid Build Coastguard Worker   assert(nbits >= 0);
249*77c1e3ccSAndroid Build Coastguard Worker   assert(nbits <= 8);
250*77c1e3ccSAndroid Build Coastguard Worker   assert(val < 1U << nbits);
251*77c1e3ccSAndroid Build Coastguard Worker   shift = 8 - nbits;
252*77c1e3ccSAndroid Build Coastguard Worker   mask = ((1U << nbits) - 1) << shift;
253*77c1e3ccSAndroid Build Coastguard Worker   if (enc->offs > 0) {
254*77c1e3ccSAndroid Build Coastguard Worker     /*The first byte has been finalized.*/
255*77c1e3ccSAndroid Build Coastguard Worker     enc->buf[0] = (unsigned char)((enc->buf[0] & ~mask) | val << shift);
256*77c1e3ccSAndroid Build Coastguard Worker   } else if (9 + enc->cnt + (enc->rng == 0x8000) > nbits) {
257*77c1e3ccSAndroid Build Coastguard Worker     /*The first byte has yet to be output.*/
258*77c1e3ccSAndroid Build Coastguard Worker     enc->low = (enc->low & ~((od_ec_enc_window)mask << (16 + enc->cnt))) |
259*77c1e3ccSAndroid Build Coastguard Worker                (od_ec_enc_window)val << (16 + enc->cnt + shift);
260*77c1e3ccSAndroid Build Coastguard Worker   } else {
261*77c1e3ccSAndroid Build Coastguard Worker     /*The encoder hasn't even encoded _nbits of data yet.*/
262*77c1e3ccSAndroid Build Coastguard Worker     enc->error = -1;
263*77c1e3ccSAndroid Build Coastguard Worker   }
264*77c1e3ccSAndroid Build Coastguard Worker }
265*77c1e3ccSAndroid Build Coastguard Worker 
266*77c1e3ccSAndroid Build Coastguard Worker #if OD_MEASURE_EC_OVERHEAD
267*77c1e3ccSAndroid Build Coastguard Worker #include <stdio.h>
268*77c1e3ccSAndroid Build Coastguard Worker #endif
269*77c1e3ccSAndroid Build Coastguard Worker 
270*77c1e3ccSAndroid Build Coastguard Worker /*Indicates that there are no more symbols to encode.
271*77c1e3ccSAndroid Build Coastguard Worker   All remaining output bytes are flushed to the output buffer.
272*77c1e3ccSAndroid Build Coastguard Worker   od_ec_enc_reset() should be called before using the encoder again.
273*77c1e3ccSAndroid Build Coastguard Worker   bytes: Returns the size of the encoded data in the returned buffer.
274*77c1e3ccSAndroid Build Coastguard Worker   Return: A pointer to the start of the final buffer, or NULL if there was an
275*77c1e3ccSAndroid Build Coastguard Worker            encoding error.*/
od_ec_enc_done(od_ec_enc * enc,uint32_t * nbytes)276*77c1e3ccSAndroid Build Coastguard Worker unsigned char *od_ec_enc_done(od_ec_enc *enc, uint32_t *nbytes) {
277*77c1e3ccSAndroid Build Coastguard Worker   unsigned char *out;
278*77c1e3ccSAndroid Build Coastguard Worker   uint32_t storage;
279*77c1e3ccSAndroid Build Coastguard Worker   uint32_t offs;
280*77c1e3ccSAndroid Build Coastguard Worker   od_ec_enc_window m;
281*77c1e3ccSAndroid Build Coastguard Worker   od_ec_enc_window e;
282*77c1e3ccSAndroid Build Coastguard Worker   od_ec_enc_window l;
283*77c1e3ccSAndroid Build Coastguard Worker   int c;
284*77c1e3ccSAndroid Build Coastguard Worker   int s;
285*77c1e3ccSAndroid Build Coastguard Worker   if (enc->error) return NULL;
286*77c1e3ccSAndroid Build Coastguard Worker #if OD_MEASURE_EC_OVERHEAD
287*77c1e3ccSAndroid Build Coastguard Worker   {
288*77c1e3ccSAndroid Build Coastguard Worker     uint32_t tell;
289*77c1e3ccSAndroid Build Coastguard Worker     /* Don't count the 1 bit we lose to raw bits as overhead. */
290*77c1e3ccSAndroid Build Coastguard Worker     tell = od_ec_enc_tell(enc) - 1;
291*77c1e3ccSAndroid Build Coastguard Worker     fprintf(stderr, "overhead: %f%%\n",
292*77c1e3ccSAndroid Build Coastguard Worker             100 * (tell - enc->entropy) / enc->entropy);
293*77c1e3ccSAndroid Build Coastguard Worker     fprintf(stderr, "efficiency: %f bits/symbol\n",
294*77c1e3ccSAndroid Build Coastguard Worker             (double)tell / enc->nb_symbols);
295*77c1e3ccSAndroid Build Coastguard Worker   }
296*77c1e3ccSAndroid Build Coastguard Worker #endif
297*77c1e3ccSAndroid Build Coastguard Worker 
298*77c1e3ccSAndroid Build Coastguard Worker   l = enc->low;
299*77c1e3ccSAndroid Build Coastguard Worker   c = enc->cnt;
300*77c1e3ccSAndroid Build Coastguard Worker   s = 10;
301*77c1e3ccSAndroid Build Coastguard Worker   m = 0x3FFF;
302*77c1e3ccSAndroid Build Coastguard Worker   e = ((l + m) & ~m) | (m + 1);
303*77c1e3ccSAndroid Build Coastguard Worker   s += c;
304*77c1e3ccSAndroid Build Coastguard Worker   offs = enc->offs;
305*77c1e3ccSAndroid Build Coastguard Worker 
306*77c1e3ccSAndroid Build Coastguard Worker   /*Make sure there's enough room for the entropy-coded bits.*/
307*77c1e3ccSAndroid Build Coastguard Worker   out = enc->buf;
308*77c1e3ccSAndroid Build Coastguard Worker   storage = enc->storage;
309*77c1e3ccSAndroid Build Coastguard Worker   const int s_bits = (s + 7) >> 3;
310*77c1e3ccSAndroid Build Coastguard Worker   int b = OD_MAXI(s_bits, 0);
311*77c1e3ccSAndroid Build Coastguard Worker   if (offs + b > storage) {
312*77c1e3ccSAndroid Build Coastguard Worker     storage = offs + b;
313*77c1e3ccSAndroid Build Coastguard Worker     out = (unsigned char *)realloc(out, sizeof(*out) * storage);
314*77c1e3ccSAndroid Build Coastguard Worker     if (out == NULL) {
315*77c1e3ccSAndroid Build Coastguard Worker       enc->error = -1;
316*77c1e3ccSAndroid Build Coastguard Worker       return NULL;
317*77c1e3ccSAndroid Build Coastguard Worker     }
318*77c1e3ccSAndroid Build Coastguard Worker     enc->buf = out;
319*77c1e3ccSAndroid Build Coastguard Worker     enc->storage = storage;
320*77c1e3ccSAndroid Build Coastguard Worker   }
321*77c1e3ccSAndroid Build Coastguard Worker 
322*77c1e3ccSAndroid Build Coastguard Worker   /*We output the minimum number of bits that ensures that the symbols encoded
323*77c1e3ccSAndroid Build Coastguard Worker      thus far will be decoded correctly regardless of the bits that follow.*/
324*77c1e3ccSAndroid Build Coastguard Worker   if (s > 0) {
325*77c1e3ccSAndroid Build Coastguard Worker     uint64_t n;
326*77c1e3ccSAndroid Build Coastguard Worker     n = ((uint64_t)1 << (c + 16)) - 1;
327*77c1e3ccSAndroid Build Coastguard Worker     do {
328*77c1e3ccSAndroid Build Coastguard Worker       assert(offs < storage);
329*77c1e3ccSAndroid Build Coastguard Worker       uint16_t val = (uint16_t)(e >> (c + 16));
330*77c1e3ccSAndroid Build Coastguard Worker       out[offs] = (unsigned char)(val & 0x00FF);
331*77c1e3ccSAndroid Build Coastguard Worker       if (val & 0x0100) {
332*77c1e3ccSAndroid Build Coastguard Worker         assert(offs > 0);
333*77c1e3ccSAndroid Build Coastguard Worker         propagate_carry_bwd(out, offs - 1);
334*77c1e3ccSAndroid Build Coastguard Worker       }
335*77c1e3ccSAndroid Build Coastguard Worker       offs++;
336*77c1e3ccSAndroid Build Coastguard Worker 
337*77c1e3ccSAndroid Build Coastguard Worker       e &= n;
338*77c1e3ccSAndroid Build Coastguard Worker       s -= 8;
339*77c1e3ccSAndroid Build Coastguard Worker       c -= 8;
340*77c1e3ccSAndroid Build Coastguard Worker       n >>= 8;
341*77c1e3ccSAndroid Build Coastguard Worker     } while (s > 0);
342*77c1e3ccSAndroid Build Coastguard Worker   }
343*77c1e3ccSAndroid Build Coastguard Worker   *nbytes = offs;
344*77c1e3ccSAndroid Build Coastguard Worker 
345*77c1e3ccSAndroid Build Coastguard Worker   return out;
346*77c1e3ccSAndroid Build Coastguard Worker }
347*77c1e3ccSAndroid Build Coastguard Worker 
348*77c1e3ccSAndroid Build Coastguard Worker /*Returns the number of bits "used" by the encoded symbols so far.
349*77c1e3ccSAndroid Build Coastguard Worker   This same number can be computed in either the encoder or the decoder, and is
350*77c1e3ccSAndroid Build Coastguard Worker    suitable for making coding decisions.
351*77c1e3ccSAndroid Build Coastguard Worker   Warning: The value returned by this function can decrease compared to an
352*77c1e3ccSAndroid Build Coastguard Worker    earlier call, even after encoding more data, if there is an encoding error
353*77c1e3ccSAndroid Build Coastguard Worker    (i.e., a failure to allocate enough space for the output buffer).
354*77c1e3ccSAndroid Build Coastguard Worker   Return: The number of bits.
355*77c1e3ccSAndroid Build Coastguard Worker           This will always be slightly larger than the exact value (e.g., all
356*77c1e3ccSAndroid Build Coastguard Worker            rounding error is in the positive direction).*/
od_ec_enc_tell(const od_ec_enc * enc)357*77c1e3ccSAndroid Build Coastguard Worker int od_ec_enc_tell(const od_ec_enc *enc) {
358*77c1e3ccSAndroid Build Coastguard Worker   /*The 10 here counteracts the offset of -9 baked into cnt, and adds 1 extra
359*77c1e3ccSAndroid Build Coastguard Worker      bit, which we reserve for terminating the stream.*/
360*77c1e3ccSAndroid Build Coastguard Worker   return (enc->cnt + 10) + enc->offs * 8;
361*77c1e3ccSAndroid Build Coastguard Worker }
362*77c1e3ccSAndroid Build Coastguard Worker 
363*77c1e3ccSAndroid Build Coastguard Worker /*Returns the number of bits "used" by the encoded symbols so far.
364*77c1e3ccSAndroid Build Coastguard Worker   This same number can be computed in either the encoder or the decoder, and is
365*77c1e3ccSAndroid Build Coastguard Worker    suitable for making coding decisions.
366*77c1e3ccSAndroid Build Coastguard Worker   Warning: The value returned by this function can decrease compared to an
367*77c1e3ccSAndroid Build Coastguard Worker    earlier call, even after encoding more data, if there is an encoding error
368*77c1e3ccSAndroid Build Coastguard Worker    (i.e., a failure to allocate enough space for the output buffer).
369*77c1e3ccSAndroid Build Coastguard Worker   Return: The number of bits scaled by 2**OD_BITRES.
370*77c1e3ccSAndroid Build Coastguard Worker           This will always be slightly larger than the exact value (e.g., all
371*77c1e3ccSAndroid Build Coastguard Worker            rounding error is in the positive direction).*/
od_ec_enc_tell_frac(const od_ec_enc * enc)372*77c1e3ccSAndroid Build Coastguard Worker uint32_t od_ec_enc_tell_frac(const od_ec_enc *enc) {
373*77c1e3ccSAndroid Build Coastguard Worker   return od_ec_tell_frac(od_ec_enc_tell(enc), enc->rng);
374*77c1e3ccSAndroid Build Coastguard Worker }
375