1 /*
2  * Copyright (c) 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  */
11 
12 #include <string.h>
13 
14 #include "aom_dsp/buf_ans.h"
15 #include "aom_mem/aom_mem.h"
16 #include "aom/internal/aom_codec_internal.h"
17 
aom_buf_ans_alloc(struct BufAnsCoder * c,struct aom_internal_error_info * error)18 void aom_buf_ans_alloc(struct BufAnsCoder *c,
19                        struct aom_internal_error_info *error) {
20   c->error = error;
21   assert(c->size > 1);
22   AOM_CHECK_MEM_ERROR(error, c->buf, aom_malloc(c->size * sizeof(*c->buf)));
23   // Initialize to overfull to trigger the assert in write.
24   c->offset = c->size + 1;
25 }
26 
aom_buf_ans_free(struct BufAnsCoder * c)27 void aom_buf_ans_free(struct BufAnsCoder *c) {
28   aom_free(c->buf);
29   c->buf = NULL;
30   c->size = 0;
31 }
32 
33 #if !ANS_MAX_SYMBOLS
aom_buf_ans_grow(struct BufAnsCoder * c)34 void aom_buf_ans_grow(struct BufAnsCoder *c) {
35   struct buffered_ans_symbol *new_buf = NULL;
36   int new_size = c->size * 2;
37   AOM_CHECK_MEM_ERROR(c->error, new_buf,
38                       aom_malloc(new_size * sizeof(*new_buf)));
39   memcpy(new_buf, c->buf, c->size * sizeof(*c->buf));
40   aom_free(c->buf);
41   c->buf = new_buf;
42   c->size = new_size;
43 }
44 #endif
45 
aom_buf_ans_flush(struct BufAnsCoder * const c)46 void aom_buf_ans_flush(struct BufAnsCoder *const c) {
47   int offset;
48 #if ANS_MAX_SYMBOLS
49   if (c->offset == 0) return;
50 #endif
51   assert(c->offset > 0);
52   offset = c->offset - 1;
53   // Code the first symbol such that it brings the state to the smallest normal
54   // state from an initial state that would have been a subnormal/refill state.
55   if (c->buf[offset].method == ANS_METHOD_RANS) {
56     c->ans.state += c->buf[offset].val_start;
57   } else {
58     c->ans.state += c->buf[offset].val_start ? c->buf[offset].prob : 0;
59   }
60   for (offset = offset - 1; offset >= 0; --offset) {
61     if (c->buf[offset].method == ANS_METHOD_RANS) {
62       rans_write(&c->ans, c->buf[offset].val_start, c->buf[offset].prob);
63     } else {
64       rabs_write(&c->ans, (uint8_t)c->buf[offset].val_start,
65                  (AnsP8)c->buf[offset].prob);
66     }
67   }
68   c->offset = 0;
69   c->output_bytes += ans_write_end(&c->ans);
70 }
71