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
12#include "dboolhuff.h"
13#include "vp8/common/common.h"
14#include "vpx_dsp/vpx_dsp_common.h"
15
16int vp8dx_start_decode(BOOL_DECODER *br,
17                       const unsigned char *source,
18                       unsigned int source_sz,
19                       vpx_decrypt_cb decrypt_cb,
20                       void *decrypt_state)
21{
22    br->user_buffer_end = source+source_sz;
23    br->user_buffer     = source;
24    br->value    = 0;
25    br->count    = -8;
26    br->range    = 255;
27    br->decrypt_cb = decrypt_cb;
28    br->decrypt_state = decrypt_state;
29
30    if (source_sz && !source)
31        return 1;
32
33    /* Populate the buffer */
34    vp8dx_bool_decoder_fill(br);
35
36    return 0;
37}
38
39void vp8dx_bool_decoder_fill(BOOL_DECODER *br)
40{
41    const unsigned char *bufptr = br->user_buffer;
42    VP8_BD_VALUE value = br->value;
43    int count = br->count;
44    int shift = VP8_BD_VALUE_SIZE - CHAR_BIT - (count + CHAR_BIT);
45    size_t bytes_left = br->user_buffer_end - bufptr;
46    size_t bits_left = bytes_left * CHAR_BIT;
47    int x = (int)(shift + CHAR_BIT - bits_left);
48    int loop_end = 0;
49    unsigned char decrypted[sizeof(VP8_BD_VALUE) + 1];
50
51    if (br->decrypt_cb) {
52        size_t n = VPXMIN(sizeof(decrypted), bytes_left);
53        br->decrypt_cb(br->decrypt_state, bufptr, decrypted, (int)n);
54        bufptr = decrypted;
55    }
56
57    if(x >= 0)
58    {
59        count += VP8_LOTS_OF_BITS;
60        loop_end = x;
61    }
62
63    if (x < 0 || bits_left)
64    {
65        while(shift >= loop_end)
66        {
67            count += CHAR_BIT;
68            value |= (VP8_BD_VALUE)*bufptr << shift;
69            ++bufptr;
70            ++br->user_buffer;
71            shift -= CHAR_BIT;
72        }
73    }
74
75    br->value = value;
76    br->count = count;
77}
78