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 VPX_VPX_DSP_BITWRITER_H_
12 #define VPX_VPX_DSP_BITWRITER_H_
13
14 #define INLINE __inline
15
16 #include <stdint.h>
17 #include "prob.h"
18
19 #ifdef __cplusplus
20 extern "C" {
21 #endif
22
23 typedef struct VpxWriter {
24 unsigned int lowvalue;
25 unsigned int range;
26 int count;
27 unsigned int pos;
28 uint8_t *buffer;
29 } VpxWriter;
30
31 void eb_vp9_start_encode(VpxWriter *bc, uint8_t *buffer);
32 void eb_vp9_stop_encode(VpxWriter *bc);
33
vpx_write(VpxWriter * br,int bit,int probability)34 static INLINE void vpx_write(VpxWriter *br, int bit, int probability) {
35 unsigned int split;
36 int count = br->count;
37 unsigned int range = br->range;
38 unsigned int lowvalue = br->lowvalue;
39 int shift;
40
41 split = 1 + (((range - 1) * probability) >> 8);
42
43 range = split;
44
45 if (bit) {
46 lowvalue += split;
47 range = br->range - split;
48 }
49
50 shift = eb_vp9_norm[range];
51
52 range <<= shift;
53 count += shift;
54
55 if (count >= 0) {
56 int offset = shift - count;
57
58 if ((lowvalue << (offset - 1)) & 0x80000000) {
59 int x = br->pos - 1;
60
61 while (x >= 0 && br->buffer[x] == 0xff) {
62 br->buffer[x] = 0;
63 x--;
64 }
65
66 br->buffer[x] += 1;
67 }
68
69 br->buffer[br->pos++] = (uint8_t)((lowvalue >> (24 - offset)));
70 lowvalue <<= offset;
71 shift = count;
72 lowvalue &= 0xffffff;
73 count -= 8;
74 }
75
76 lowvalue <<= shift;
77 br->count = count;
78 br->lowvalue = lowvalue;
79 br->range = range;
80 }
81
vpx_write_bit(VpxWriter * w,int bit)82 static INLINE void vpx_write_bit(VpxWriter *w, int bit) {
83 vpx_write(w, bit, 128); // vpx_prob_half
84 }
85
vpx_write_literal(VpxWriter * w,int data,int bits)86 static INLINE void vpx_write_literal(VpxWriter *w, int data, int bits) {
87 int bit;
88
89 for (bit = bits - 1; bit >= 0; bit--) vpx_write_bit(w, 1 & (data >> bit));
90 }
91
92 #define vpx_write_prob(w, v) vpx_write_literal((w), (v), 8)
93
94 #ifdef __cplusplus
95 } // extern "C"
96 #endif
97
98 #endif // VPX_VPX_DSP_BITWRITER_H_
99