blob: 76c85883da6a203a2c914fb4184c288bd2d1098d [file] [log] [blame]
Yushin Cho77bba8d2016-11-04 16:36:56 -07001/*
2 * Copyright (c) 2001-2016, Alliance for Open Media. All rights reserved
3 *
4 * This source code is subject to the terms of the BSD 2 Clause License and
5 * the Alliance for Open Media Patent License 1.0. If the BSD 2 Clause License
6 * was not distributed with this source code in the LICENSE file, you can
7 * obtain it at www.aomedia.org/license/software. If the Alliance for Open
8 * Media Patent License 1.0 was not distributed with this source code in the
9 * PATENTS file, you can obtain it at www.aomedia.org/license/patent.
10 */
Nathan E. Egge1078dee2016-03-06 10:59:29 -050011
12#ifdef HAVE_CONFIG_H
Yaowu Xu931bc2a2016-10-14 13:53:51 -070013#include "./config.h"
Nathan E. Egge1078dee2016-03-06 10:59:29 -050014#endif
15
16#include <stdlib.h>
17#include <string.h>
Yaowu Xu931bc2a2016-10-14 13:53:51 -070018#include "aom_dsp/entenc.h"
Nathan E. Egge1078dee2016-03-06 10:59:29 -050019
20/*A range encoder.
21 See entdec.c and the references for implementation details \cite{Mar79,MNW98}.
22
23 @INPROCEEDINGS{Mar79,
24 author="Martin, G.N.N.",
25 title="Range encoding: an algorithm for removing redundancy from a digitised
26 message",
27 booktitle="Video \& Data Recording Conference",
28 year=1979,
29 address="Southampton",
30 month=Jul,
31 URL="http://www.compressconsult.com/rangecoder/rngcod.pdf.gz"
32 }
33 @ARTICLE{MNW98,
34 author="Alistair Moffat and Radford Neal and Ian H. Witten",
35 title="Arithmetic Coding Revisited",
36 journal="{ACM} Transactions on Information Systems",
37 year=1998,
38 volume=16,
39 number=3,
40 pages="256--294",
41 month=Jul,
42 URL="http://researchcommons.waikato.ac.nz/bitstream/handle/10289/78/content.pdf"
43 }*/
44
45/*Takes updated low and range values, renormalizes them so that
46 32768 <= rng < 65536 (flushing bytes from low to the pre-carry buffer if
47 necessary), and stores them back in the encoder context.
48 low: The new value of low.
49 rng: The new value of the range.*/
50static void od_ec_enc_normalize(od_ec_enc *enc, od_ec_window low,
51 unsigned rng) {
52 int d;
53 int c;
54 int s;
55 c = enc->cnt;
56 OD_ASSERT(rng <= 65535U);
57 d = 16 - OD_ILOG_NZ(rng);
58 s = c + d;
59 /*TODO: Right now we flush every time we have at least one byte available.
60 Instead we should use an od_ec_window and flush right before we're about to
61 shift bits off the end of the window.
62 For a 32-bit window this is about the same amount of work, but for a 64-bit
63 window it should be a fair win.*/
64 if (s >= 0) {
65 uint16_t *buf;
66 uint32_t storage;
67 uint32_t offs;
68 unsigned m;
69 buf = enc->precarry_buf;
70 storage = enc->precarry_storage;
71 offs = enc->offs;
72 if (offs + 2 > storage) {
73 storage = 2 * storage + 2;
74 buf = (uint16_t *)realloc(buf, sizeof(*buf) * storage);
75 if (buf == NULL) {
76 enc->error = -1;
77 enc->offs = 0;
78 return;
79 }
80 enc->precarry_buf = buf;
81 enc->precarry_storage = storage;
82 }
83 c += 16;
84 m = (1 << c) - 1;
85 if (s >= 8) {
86 OD_ASSERT(offs < storage);
87 buf[offs++] = (uint16_t)(low >> c);
88 low &= m;
89 c -= 8;
90 m >>= 8;
91 }
92 OD_ASSERT(offs < storage);
93 buf[offs++] = (uint16_t)(low >> c);
94 s = c + d - 24;
95 low &= m;
96 enc->offs = offs;
97 }
98 enc->low = low << d;
99 enc->rng = rng << d;
100 enc->cnt = s;
101}
102
103/*Initializes the encoder.
104 size: The initial size of the buffer, in bytes.*/
105void od_ec_enc_init(od_ec_enc *enc, uint32_t size) {
106 od_ec_enc_reset(enc);
107 enc->buf = (unsigned char *)malloc(sizeof(*enc->buf) * size);
108 enc->storage = size;
109 if (size > 0 && enc->buf == NULL) {
110 enc->storage = 0;
111 enc->error = -1;
112 }
113 enc->precarry_buf = (uint16_t *)malloc(sizeof(*enc->precarry_buf) * size);
114 enc->precarry_storage = size;
115 if (size > 0 && enc->precarry_buf == NULL) {
116 enc->precarry_storage = 0;
117 enc->error = -1;
118 }
119}
120
121/*Reinitializes the encoder.*/
122void od_ec_enc_reset(od_ec_enc *enc) {
123 enc->end_offs = 0;
124 enc->end_window = 0;
125 enc->nend_bits = 0;
126 enc->offs = 0;
127 enc->low = 0;
128 enc->rng = 0x8000;
129 /*This is initialized to -9 so that it crosses zero after we've accumulated
130 one byte + one carry bit.*/
131 enc->cnt = -9;
132 enc->error = 0;
133#if OD_MEASURE_EC_OVERHEAD
134 enc->entropy = 0;
135 enc->nb_symbols = 0;
136#endif
137}
138
139/*Frees the buffers used by the encoder.*/
140void od_ec_enc_clear(od_ec_enc *enc) {
141 free(enc->precarry_buf);
142 free(enc->buf);
143}
144
145/*Encodes a symbol given its scaled frequency information.
146 The frequency information must be discernable by the decoder, assuming it
147 has read only the previous symbols from the stream.
148 You can change the frequency information, or even the entire source alphabet,
149 so long as the decoder can tell from the context of the previously encoded
150 information that it is supposed to do so as well.
151 fl: The cumulative frequency of all symbols that come before the one to be
152 encoded.
153 fh: The cumulative frequency of all symbols up to and including the one to
154 be encoded.
155 Together with fl, this defines the range [fl, fh) in which the decoded
156 value will fall.
157 ft: The sum of the frequencies of all the symbols.
158 This must be at least 16384, and no more than 32768.*/
159static void od_ec_encode(od_ec_enc *enc, unsigned fl, unsigned fh,
160 unsigned ft) {
161 od_ec_window l;
162 unsigned r;
163 int s;
164 unsigned d;
165 unsigned u;
166 unsigned v;
167 OD_ASSERT(fl < fh);
168 OD_ASSERT(fh <= ft);
169 OD_ASSERT(16384 <= ft);
170 OD_ASSERT(ft <= 32768U);
171 l = enc->low;
172 r = enc->rng;
173 OD_ASSERT(ft <= r);
174 s = r - ft >= ft;
175 ft <<= s;
176 fl <<= s;
177 fh <<= s;
178 d = r - ft;
179 OD_ASSERT(d < ft);
180#if OD_EC_REDUCED_OVERHEAD
181 {
182 unsigned e;
183 e = OD_SUBSATU(2 * d, ft);
184 u = fl + OD_MINI(fl, e) + OD_MINI(OD_SUBSATU(fl, e) >> 1, d);
185 v = fh + OD_MINI(fh, e) + OD_MINI(OD_SUBSATU(fh, e) >> 1, d);
186 }
187#else
188 u = fl + OD_MINI(fl, d);
189 v = fh + OD_MINI(fh, d);
190#endif
191 r = v - u;
192 l += u;
193 od_ec_enc_normalize(enc, l, r);
194#if OD_MEASURE_EC_OVERHEAD
195 enc->entropy -= OD_LOG2((double)(fh - fl) / ft);
196 enc->nb_symbols++;
197#endif
198}
199
200/*Encodes a symbol given its frequency in Q15.
201 This is like od_ec_encode() when ft == 32768, but is simpler and has lower
202 overhead.
203 Symbols encoded with this function cannot be properly decoded with
204 od_ec_decode(), and must be decoded with one of the equivalent _q15()
205 functions instead.
206 fl: The cumulative frequency of all symbols that come before the one to be
207 encoded.
208 fh: The cumulative frequency of all symbols up to and including the one to
209 be encoded.*/
210static void od_ec_encode_q15(od_ec_enc *enc, unsigned fl, unsigned fh) {
211 od_ec_window l;
212 unsigned r;
213 unsigned u;
214 unsigned v;
215 OD_ASSERT(fl < fh);
216 OD_ASSERT(fh <= 32768U);
217 l = enc->low;
218 r = enc->rng;
219 OD_ASSERT(32768U <= r);
Timothy B. Terriberryb1c57602017-02-16 10:53:39 -0800220#if CONFIG_EC_SMALLMUL
221 if (fl > 0) {
222 u = (r >> 8) * (uint32_t)(32768U - fl) >> 7;
223 v = (r >> 8) * (uint32_t)(32768U - fh) >> 7;
224 l += r - u;
225 r = u - v;
226 } else {
227 r -= (r >> 8) * (uint32_t)(32768U - fh) >> 7;
228 }
229#else
Nathan E. Egge1078dee2016-03-06 10:59:29 -0500230 u = fl * (uint32_t)r >> 15;
231 v = fh * (uint32_t)r >> 15;
232 r = v - u;
233 l += u;
Timothy B. Terriberryb1c57602017-02-16 10:53:39 -0800234#endif
Nathan E. Egge1078dee2016-03-06 10:59:29 -0500235 od_ec_enc_normalize(enc, l, r);
236#if OD_MEASURE_EC_OVERHEAD
237 enc->entropy -= OD_LOG2((double)(fh - fl) / 32768.);
238 enc->nb_symbols++;
239#endif
240}
241
242/*Encodes a symbol given its frequency information with an arbitrary scale.
243 This operates just like od_ec_encode(), but does not require that ft be at
244 least 16384.
245 fl: The cumulative frequency of all symbols that come before the one to be
246 encoded.
247 fh: The cumulative frequency of all symbols up to and including the one to
248 be encoded.
249 ft: The sum of the frequencies of all the symbols.
250 This must be at least 2 and no more than 32768.*/
251static void od_ec_encode_unscaled(od_ec_enc *enc, unsigned fl, unsigned fh,
252 unsigned ft) {
253 int s;
254 OD_ASSERT(fl < fh);
255 OD_ASSERT(fh <= ft);
256 OD_ASSERT(2 <= ft);
257 OD_ASSERT(ft <= 32768U);
258 s = 15 - OD_ILOG_NZ(ft - 1);
259 od_ec_encode(enc, fl << s, fh << s, ft << s);
260}
261
262/*Encode a bit that has an fz/ft probability of being a zero.
263 val: The value to encode (0 or 1).
264 fz: The probability that val is zero, scaled by ft.
265 ft: The total probability.
266 This must be at least 16384 and no more than 32768.*/
267void od_ec_encode_bool(od_ec_enc *enc, int val, unsigned fz, unsigned ft) {
268 od_ec_window l;
269 unsigned r;
270 int s;
271 unsigned v;
272 OD_ASSERT(0 < fz);
273 OD_ASSERT(fz < ft);
274 OD_ASSERT(16384 <= ft);
275 OD_ASSERT(ft <= 32768U);
276 l = enc->low;
277 r = enc->rng;
278 OD_ASSERT(ft <= r);
279 s = r - ft >= ft;
280 ft <<= s;
281 fz <<= s;
282 OD_ASSERT(r - ft < ft);
283#if OD_EC_REDUCED_OVERHEAD
284 {
285 unsigned d;
286 unsigned e;
287 d = r - ft;
288 e = OD_SUBSATU(2 * d, ft);
289 v = fz + OD_MINI(fz, e) + OD_MINI(OD_SUBSATU(fz, e) >> 1, d);
290 }
291#else
292 v = fz + OD_MINI(fz, r - ft);
293#endif
294 if (val) l += v;
295 r = val ? r - v : v;
296 od_ec_enc_normalize(enc, l, r);
297#if OD_MEASURE_EC_OVERHEAD
298 enc->entropy -= OD_LOG2((double)(val ? ft - fz : fz) / ft);
299 enc->nb_symbols++;
300#endif
301}
302
303/*Encode a bit that has an fz probability of being a zero in Q15.
304 This is a simpler, lower overhead version of od_ec_encode_bool() for use when
305 ft == 32768.
306 Symbols encoded with this function cannot be properly decoded with
307 od_ec_decode(), and must be decoded with one of the equivalent _q15()
308 functions instead.
309 val: The value to encode (0 or 1).
310 fz: The probability that val is zero, scaled by 32768.*/
311void od_ec_encode_bool_q15(od_ec_enc *enc, int val, unsigned fz) {
312 od_ec_window l;
313 unsigned r;
314 unsigned v;
315 OD_ASSERT(0 < fz);
316 OD_ASSERT(fz < 32768U);
317 l = enc->low;
318 r = enc->rng;
319 OD_ASSERT(32768U <= r);
Timothy B. Terriberryb1c57602017-02-16 10:53:39 -0800320#if CONFIG_EC_SMALLMUL
321 v = r - ((r >> 8) * (uint32_t)(32768U - fz) >> 7);
322#else
Nathan E. Egge1078dee2016-03-06 10:59:29 -0500323 v = fz * (uint32_t)r >> 15;
Timothy B. Terriberryb1c57602017-02-16 10:53:39 -0800324#endif
Nathan E. Egge1078dee2016-03-06 10:59:29 -0500325 if (val) l += v;
326 r = val ? r - v : v;
327 od_ec_enc_normalize(enc, l, r);
328#if OD_MEASURE_EC_OVERHEAD
329 enc->entropy -= OD_LOG2((double)(val ? 32768 - fz : fz) / 32768.);
330 enc->nb_symbols++;
331#endif
332}
333
334/*Encodes a symbol given a cumulative distribution function (CDF) table.
335 s: The index of the symbol to encode.
336 cdf: The CDF, such that symbol s falls in the range
337 [s > 0 ? cdf[s - 1] : 0, cdf[s]).
338 The values must be monotonically non-decreasing, and the last value
339 must be at least 16384, and no more than 32768.
340 nsyms: The number of symbols in the alphabet.
341 This should be at most 16.*/
342void od_ec_encode_cdf(od_ec_enc *enc, int s, const uint16_t *cdf, int nsyms) {
343 OD_ASSERT(s >= 0);
344 OD_ASSERT(s < nsyms);
345 od_ec_encode(enc, s > 0 ? cdf[s - 1] : 0, cdf[s], cdf[nsyms - 1]);
346}
347
348/*Encodes a symbol given a cumulative distribution function (CDF) table in Q15.
349 This is a simpler, lower overhead version of od_ec_encode_cdf() for use when
350 cdf[nsyms - 1] == 32768.
351 Symbols encoded with this function cannot be properly decoded with
352 od_ec_decode(), and must be decoded with one of the equivalent _q15()
353 functions instead.
354 s: The index of the symbol to encode.
355 cdf: The CDF, such that symbol s falls in the range
356 [s > 0 ? cdf[s - 1] : 0, cdf[s]).
357 The values must be monotonically non-decreasing, and the last value
358 must be exactly 32768.
359 nsyms: The number of symbols in the alphabet.
360 This should be at most 16.*/
361void od_ec_encode_cdf_q15(od_ec_enc *enc, int s, const uint16_t *cdf,
362 int nsyms) {
363 (void)nsyms;
364 OD_ASSERT(s >= 0);
365 OD_ASSERT(s < nsyms);
366 OD_ASSERT(cdf[nsyms - 1] == 32768U);
367 od_ec_encode_q15(enc, s > 0 ? cdf[s - 1] : 0, cdf[s]);
368}
369
370/*Encodes a symbol given a cumulative distribution function (CDF) table.
371 s: The index of the symbol to encode.
372 cdf: The CDF, such that symbol s falls in the range
373 [s > 0 ? cdf[s - 1] : 0, cdf[s]).
374 The values must be monotonically non-decreasing, and the last value
375 must be at least 2, and no more than 32768.
376 nsyms: The number of symbols in the alphabet.
377 This should be at most 16.*/
378void od_ec_encode_cdf_unscaled(od_ec_enc *enc, int s, const uint16_t *cdf,
379 int nsyms) {
380 OD_ASSERT(s >= 0);
381 OD_ASSERT(s < nsyms);
382 od_ec_encode_unscaled(enc, s > 0 ? cdf[s - 1] : 0, cdf[s], cdf[nsyms - 1]);
383}
384
Nathan E. Egge24f1a902017-02-14 13:29:44 -0500385#if CONFIG_RAWBITS
Nathan E. Egge1078dee2016-03-06 10:59:29 -0500386/*Encodes a sequence of raw bits in the stream.
387 fl: The bits to encode.
388 ftb: The number of bits to encode.
389 This must be between 0 and 25, inclusive.*/
390void od_ec_enc_bits(od_ec_enc *enc, uint32_t fl, unsigned ftb) {
391 od_ec_window end_window;
392 int nend_bits;
393 OD_ASSERT(ftb <= 25);
394 OD_ASSERT(fl < (uint32_t)1 << ftb);
395#if OD_MEASURE_EC_OVERHEAD
396 enc->entropy += ftb;
397#endif
398 end_window = enc->end_window;
399 nend_bits = enc->nend_bits;
400 if (nend_bits + ftb > OD_EC_WINDOW_SIZE) {
401 unsigned char *buf;
402 uint32_t storage;
403 uint32_t end_offs;
404 buf = enc->buf;
405 storage = enc->storage;
406 end_offs = enc->end_offs;
407 if (end_offs + (OD_EC_WINDOW_SIZE >> 3) >= storage) {
408 unsigned char *new_buf;
409 uint32_t new_storage;
410 new_storage = 2 * storage + (OD_EC_WINDOW_SIZE >> 3);
411 new_buf = (unsigned char *)malloc(sizeof(*new_buf) * new_storage);
412 if (new_buf == NULL) {
413 enc->error = -1;
414 enc->end_offs = 0;
415 return;
416 }
417 OD_COPY(new_buf + new_storage - end_offs, buf + storage - end_offs,
418 end_offs);
419 storage = new_storage;
420 free(buf);
421 enc->buf = buf = new_buf;
422 enc->storage = storage;
423 }
424 do {
425 OD_ASSERT(end_offs < storage);
426 buf[storage - ++end_offs] = (unsigned char)end_window;
427 end_window >>= 8;
428 nend_bits -= 8;
429 } while (nend_bits >= 8);
430 enc->end_offs = end_offs;
431 }
432 OD_ASSERT(nend_bits + ftb <= OD_EC_WINDOW_SIZE);
433 end_window |= (od_ec_window)fl << nend_bits;
434 nend_bits += ftb;
435 enc->end_window = end_window;
436 enc->nend_bits = nend_bits;
437}
Nathan E. Egge24f1a902017-02-14 13:29:44 -0500438#endif
Nathan E. Egge1078dee2016-03-06 10:59:29 -0500439
440/*Overwrites a few bits at the very start of an existing stream, after they
441 have already been encoded.
442 This makes it possible to have a few flags up front, where it is easy for
443 decoders to access them without parsing the whole stream, even if their
444 values are not determined until late in the encoding process, without having
445 to buffer all the intermediate symbols in the encoder.
446 In order for this to work, at least nbits bits must have already been encoded
447 using probabilities that are an exact power of two.
448 The encoder can verify the number of encoded bits is sufficient, but cannot
449 check this latter condition.
450 val: The bits to encode (in the least nbits significant bits).
451 They will be decoded in order from most-significant to least.
452 nbits: The number of bits to overwrite.
453 This must be no more than 8.*/
454void od_ec_enc_patch_initial_bits(od_ec_enc *enc, unsigned val, int nbits) {
455 int shift;
456 unsigned mask;
457 OD_ASSERT(nbits >= 0);
458 OD_ASSERT(nbits <= 8);
459 OD_ASSERT(val < 1U << nbits);
460 shift = 8 - nbits;
461 mask = ((1U << nbits) - 1) << shift;
462 if (enc->offs > 0) {
463 /*The first byte has been finalized.*/
464 enc->precarry_buf[0] =
465 (uint16_t)((enc->precarry_buf[0] & ~mask) | val << shift);
466 } else if (9 + enc->cnt + (enc->rng == 0x8000) > nbits) {
467 /*The first byte has yet to be output.*/
468 enc->low = (enc->low & ~((od_ec_window)mask << (16 + enc->cnt))) |
469 (od_ec_window)val << (16 + enc->cnt + shift);
Yaowu Xu931bc2a2016-10-14 13:53:51 -0700470 } else {
471 /*The encoder hasn't even encoded _nbits of data yet.*/
Nathan E. Egge1078dee2016-03-06 10:59:29 -0500472 enc->error = -1;
Yaowu Xu931bc2a2016-10-14 13:53:51 -0700473 }
Nathan E. Egge1078dee2016-03-06 10:59:29 -0500474}
475
476#if OD_MEASURE_EC_OVERHEAD
477#include <stdio.h>
478#endif
479
480/*Indicates that there are no more symbols to encode.
481 All remaining output bytes are flushed to the output buffer.
482 od_ec_enc_reset() should be called before using the encoder again.
483 bytes: Returns the size of the encoded data in the returned buffer.
484 Return: A pointer to the start of the final buffer, or NULL if there was an
485 encoding error.*/
486unsigned char *od_ec_enc_done(od_ec_enc *enc, uint32_t *nbytes) {
487 unsigned char *out;
488 uint32_t storage;
489 uint16_t *buf;
Yaowu Xu88cbc582016-11-16 15:18:13 -0800490 uint32_t offs;
Nathan E. Egge1078dee2016-03-06 10:59:29 -0500491 uint32_t end_offs;
492 int nend_bits;
493 od_ec_window m;
494 od_ec_window e;
495 od_ec_window l;
496 unsigned r;
497 int c;
498 int s;
499 if (enc->error) return NULL;
500#if OD_MEASURE_EC_OVERHEAD
501 {
502 uint32_t tell;
503 /* Don't count the 1 bit we lose to raw bits as overhead. */
504 tell = od_ec_enc_tell(enc) - 1;
505 fprintf(stderr, "overhead: %f%%\n",
506 100 * (tell - enc->entropy) / enc->entropy);
507 fprintf(stderr, "efficiency: %f bits/symbol\n",
508 (double)tell / enc->nb_symbols);
509 }
510#endif
511 /*We output the minimum number of bits that ensures that the symbols encoded
512 thus far will be decoded correctly regardless of the bits that follow.*/
513 l = enc->low;
514 r = enc->rng;
515 c = enc->cnt;
516 s = 9;
517 m = 0x7FFF;
518 e = (l + m) & ~m;
519 while ((e | m) >= l + r) {
520 s++;
521 m >>= 1;
522 e = (l + m) & ~m;
523 }
524 s += c;
525 offs = enc->offs;
526 buf = enc->precarry_buf;
527 if (s > 0) {
528 unsigned n;
529 storage = enc->precarry_storage;
Yaowu Xu88cbc582016-11-16 15:18:13 -0800530 if (offs + ((s + 7) >> 3) > storage) {
Nathan E. Egge1078dee2016-03-06 10:59:29 -0500531 storage = storage * 2 + ((s + 7) >> 3);
532 buf = (uint16_t *)realloc(buf, sizeof(*buf) * storage);
533 if (buf == NULL) {
534 enc->error = -1;
535 return NULL;
536 }
537 enc->precarry_buf = buf;
538 enc->precarry_storage = storage;
539 }
540 n = (1 << (c + 16)) - 1;
541 do {
Yaowu Xu88cbc582016-11-16 15:18:13 -0800542 OD_ASSERT(offs < storage);
Nathan E. Egge1078dee2016-03-06 10:59:29 -0500543 buf[offs++] = (uint16_t)(e >> (c + 16));
544 e &= n;
545 s -= 8;
546 c -= 8;
547 n >>= 8;
548 } while (s > 0);
549 }
550 /*Make sure there's enough room for the entropy-coded bits and the raw
551 bits.*/
552 out = enc->buf;
553 storage = enc->storage;
554 end_offs = enc->end_offs;
555 e = enc->end_window;
556 nend_bits = enc->nend_bits;
557 s = -s;
558 c = OD_MAXI((nend_bits - s + 7) >> 3, 0);
559 if (offs + end_offs + c > storage) {
560 storage = offs + end_offs + c;
561 out = (unsigned char *)realloc(out, sizeof(*out) * storage);
562 if (out == NULL) {
563 enc->error = -1;
564 return NULL;
565 }
566 OD_MOVE(out + storage - end_offs, out + enc->storage - end_offs, end_offs);
567 enc->buf = out;
568 enc->storage = storage;
569 }
570 /*If we have buffered raw bits, flush them as well.*/
571 while (nend_bits > s) {
572 OD_ASSERT(end_offs < storage);
573 out[storage - ++end_offs] = (unsigned char)e;
574 e >>= 8;
575 nend_bits -= 8;
576 }
577 *nbytes = offs + end_offs;
578 /*Perform carry propagation.*/
579 OD_ASSERT(offs + end_offs <= storage);
580 out = out + storage - (offs + end_offs);
581 c = 0;
582 end_offs = offs;
Yaowu Xu88cbc582016-11-16 15:18:13 -0800583 while (offs > 0) {
584 offs--;
Nathan E. Egge1078dee2016-03-06 10:59:29 -0500585 c = buf[offs] + c;
586 out[offs] = (unsigned char)c;
587 c >>= 8;
588 }
589 /*Add any remaining raw bits to the last byte.
590 There is guaranteed to be enough room, because nend_bits <= s.*/
591 OD_ASSERT(nend_bits <= 0 || end_offs > 0);
592 if (nend_bits > 0) out[end_offs - 1] |= (unsigned char)e;
593 /*Note: Unless there's an allocation error, if you keep encoding into the
594 current buffer and call this function again later, everything will work
595 just fine (you won't get a new packet out, but you will get a single
596 buffer with the new data appended to the old).
597 However, this function is O(N) where N is the amount of data coded so far,
598 so calling it more than once for a given packet is a bad idea.*/
599 return out;
600}
601
602/*Returns the number of bits "used" by the encoded symbols so far.
603 This same number can be computed in either the encoder or the decoder, and is
604 suitable for making coding decisions.
605 Warning: The value returned by this function can decrease compared to an
606 earlier call, even after encoding more data, if there is an encoding error
607 (i.e., a failure to allocate enough space for the output buffer).
608 Return: The number of bits.
609 This will always be slightly larger than the exact value (e.g., all
610 rounding error is in the positive direction).*/
Nathan E. Egge19698a72016-08-18 02:34:53 -0400611int od_ec_enc_tell(const od_ec_enc *enc) {
Nathan E. Egge1078dee2016-03-06 10:59:29 -0500612 /*The 10 here counteracts the offset of -9 baked into cnt, and adds 1 extra
613 bit, which we reserve for terminating the stream.*/
614 return (enc->offs + enc->end_offs) * 8 + enc->cnt + enc->nend_bits + 10;
615}
616
617/*Returns the number of bits "used" by the encoded symbols so far.
618 This same number can be computed in either the encoder or the decoder, and is
619 suitable for making coding decisions.
620 Warning: The value returned by this function can decrease compared to an
621 earlier call, even after encoding more data, if there is an encoding error
622 (i.e., a failure to allocate enough space for the output buffer).
623 Return: The number of bits scaled by 2**OD_BITRES.
624 This will always be slightly larger than the exact value (e.g., all
625 rounding error is in the positive direction).*/
Nathan E. Egge19698a72016-08-18 02:34:53 -0400626uint32_t od_ec_enc_tell_frac(const od_ec_enc *enc) {
Nathan E. Egge1078dee2016-03-06 10:59:29 -0500627 return od_ec_tell_frac(od_ec_enc_tell(enc), enc->rng);
628}
629
630/*Saves a entropy coder checkpoint to dst.
631 This allows an encoder to reverse a series of entropy coder
632 decisions if it decides that the information would have been
633 better coded some other way.*/
634void od_ec_enc_checkpoint(od_ec_enc *dst, const od_ec_enc *src) {
635 OD_COPY(dst, src, 1);
636}
637
638/*Restores an entropy coder checkpoint saved by od_ec_enc_checkpoint.
639 This can only be used to restore from checkpoints earlier in the target
640 state's history: you can not switch backwards and forwards or otherwise
641 switch to a state which isn't a casual ancestor of the current state.
642 Restore is also incompatible with patching the initial bits, as the
643 changes will remain in the restored version.*/
644void od_ec_enc_rollback(od_ec_enc *dst, const od_ec_enc *src) {
645 unsigned char *buf;
646 uint32_t storage;
647 uint16_t *precarry_buf;
648 uint32_t precarry_storage;
649 OD_ASSERT(dst->storage >= src->storage);
650 OD_ASSERT(dst->precarry_storage >= src->precarry_storage);
651 buf = dst->buf;
652 storage = dst->storage;
653 precarry_buf = dst->precarry_buf;
654 precarry_storage = dst->precarry_storage;
655 OD_COPY(dst, src, 1);
656 dst->buf = buf;
657 dst->storage = storage;
658 dst->precarry_buf = precarry_buf;
659 dst->precarry_storage = precarry_storage;
660}