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