]> granicus.if.org Git - libvpx/blob - vpx_dsp/vp9_reader.c
Move bit reader files to vpx_dsp
[libvpx] / vpx_dsp / vp9_reader.c
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 #include "./vp9_prob.h"
11 #include "./vp9_reader.h"
12
13 #include "vpx_ports/mem.h"
14 #include "vpx_mem/vpx_mem.h"
15
16 int vp9_reader_init(vp9_reader *r,
17                     const uint8_t *buffer,
18                     size_t size,
19                     vpx_decrypt_cb decrypt_cb,
20                     void *decrypt_state) {
21   if (size && !buffer) {
22     return 1;
23   } else {
24     r->buffer_end = buffer + size;
25     r->buffer = buffer;
26     r->value = 0;
27     r->count = -8;
28     r->range = 255;
29     r->decrypt_cb = decrypt_cb;
30     r->decrypt_state = decrypt_state;
31     vp9_reader_fill(r);
32     return vp9_read_bit(r) != 0;  // marker bit
33   }
34 }
35
36 void vp9_reader_fill(vp9_reader *r) {
37   const uint8_t *const buffer_end = r->buffer_end;
38   const uint8_t *buffer = r->buffer;
39   const uint8_t *buffer_start = buffer;
40   BD_VALUE value = r->value;
41   int count = r->count;
42   int shift = BD_VALUE_SIZE - CHAR_BIT - (count + CHAR_BIT);
43   int loop_end = 0;
44   const size_t bytes_left = buffer_end - buffer;
45   const size_t bits_left = bytes_left * CHAR_BIT;
46   const int x = (int)(shift + CHAR_BIT - bits_left);
47
48   if (r->decrypt_cb) {
49     size_t n = MIN(sizeof(r->clear_buffer), bytes_left);
50     r->decrypt_cb(r->decrypt_state, buffer, r->clear_buffer, (int)n);
51     buffer = r->clear_buffer;
52     buffer_start = r->clear_buffer;
53   }
54
55   if (x >= 0) {
56     count += LOTS_OF_BITS;
57     loop_end = x;
58   }
59
60   if (x < 0 || bits_left) {
61     while (shift >= loop_end) {
62       count += CHAR_BIT;
63       value |= (BD_VALUE)*buffer++ << shift;
64       shift -= CHAR_BIT;
65     }
66   }
67
68   // NOTE: Variable 'buffer' may not relate to 'r->buffer' after decryption,
69   // so we increase 'r->buffer' by the amount that 'buffer' moved, rather than
70   // assign 'buffer' to 'r->buffer'.
71   r->buffer += buffer - buffer_start;
72   r->value = value;
73   r->count = count;
74 }
75
76 const uint8_t *vp9_reader_find_end(vp9_reader *r) {
77   // Find the end of the coded buffer
78   while (r->count > CHAR_BIT && r->count < BD_VALUE_SIZE) {
79     r->count -= CHAR_BIT;
80     r->buffer--;
81   }
82   return r->buffer;
83 }