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