1 /*
2 * Copyright (c) 2010 The WebM project authors. All Rights Reserved.
3 *
4 * Use of this source code is governed by a BSD-style license
5 * that can be found in the LICENSE file in the root of the source
6 * tree. An additional intellectual property rights grant can be found
7 * in the file PATENTS. All contributing project authors may
8 * be found in the AUTHORS file in the root of the source tree.
9 */
10
11 #ifndef VP9_DECODER_VP9_READER_H_
12 #define VP9_DECODER_VP9_READER_H_
13
14 #include <stddef.h>
15 #include <limits.h>
16
17 #include "./vpx_config.h"
18 #include "vpx_ports/mem.h"
19 #include "vpx/vp8dx.h"
20 #include "vpx/vpx_integer.h"
21
22 #include "vp9/common/vp9_prob.h"
23
24 #ifdef __cplusplus
25 extern "C" {
26 #endif
27
28 typedef size_t BD_VALUE;
29
30 #define BD_VALUE_SIZE ((int)sizeof(BD_VALUE) * CHAR_BIT)
31
32 typedef struct {
33 const uint8_t *buffer_end;
34 const uint8_t *buffer;
35 uint8_t clear_buffer[sizeof(BD_VALUE) + 1];
36 BD_VALUE value;
37 int count;
38 unsigned int range;
39 vpx_decrypt_cb decrypt_cb;
40 void *decrypt_state;
41 } vp9_reader;
42
43 int vp9_reader_init(vp9_reader *r,
44 const uint8_t *buffer,
45 size_t size,
46 vpx_decrypt_cb decrypt_cb,
47 void *decrypt_state);
48
49 void vp9_reader_fill(vp9_reader *r);
50
51 int vp9_reader_has_error(vp9_reader *r);
52
53 const uint8_t *vp9_reader_find_end(vp9_reader *r);
54
vp9_read(vp9_reader * r,int prob)55 static INLINE int vp9_read(vp9_reader *r, int prob) {
56 unsigned int bit = 0;
57 BD_VALUE value;
58 BD_VALUE bigsplit;
59 int count;
60 unsigned int range;
61 unsigned int split = (r->range * prob + (256 - prob)) >> CHAR_BIT;
62
63 if (r->count < 0)
64 vp9_reader_fill(r);
65
66 value = r->value;
67 count = r->count;
68
69 bigsplit = (BD_VALUE)split << (BD_VALUE_SIZE - CHAR_BIT);
70
71 range = split;
72
73 if (value >= bigsplit) {
74 range = r->range - split;
75 value = value - bigsplit;
76 bit = 1;
77 }
78
79 {
80 register unsigned int shift = vp9_norm[range];
81 range <<= shift;
82 value <<= shift;
83 count -= shift;
84 }
85 r->value = value;
86 r->count = count;
87 r->range = range;
88
89 return bit;
90 }
91
vp9_read_bit(vp9_reader * r)92 static INLINE int vp9_read_bit(vp9_reader *r) {
93 return vp9_read(r, 128); // vp9_prob_half
94 }
95
vp9_read_literal(vp9_reader * r,int bits)96 static INLINE int vp9_read_literal(vp9_reader *r, int bits) {
97 int literal = 0, bit;
98
99 for (bit = bits - 1; bit >= 0; bit--)
100 literal |= vp9_read_bit(r) << bit;
101
102 return literal;
103 }
104
vp9_read_tree(vp9_reader * r,const vp9_tree_index * tree,const vp9_prob * probs)105 static INLINE int vp9_read_tree(vp9_reader *r, const vp9_tree_index *tree,
106 const vp9_prob *probs) {
107 vp9_tree_index i = 0;
108
109 while ((i = tree[i + vp9_read(r, probs[i >> 1])]) > 0)
110 continue;
111
112 return -i;
113 }
114
115 #ifdef __cplusplus
116 } // extern "C"
117 #endif
118
119 #endif // VP9_DECODER_VP9_READER_H_
120