1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
use CumulativeDistributionFrequency;

use opus::imported_decode;

use std;

pub struct Reader<R>
where
    R: std::io::Read,
{
    state: imported_decode::ec_dec<R>,
}

impl<R> Reader<R>
where
    R: std::io::Read,
{
    /*
        pub fn from_boxed_slice(mut source: Box<[u8]>) -> Self {
            let state = unsafe {
                let mut state : imported_decode::ec_dec = std::mem::uninitialized();
                imported_decode::ec_dec_init(&mut state, source.as_mut_ptr(), source.len() as u32);
                state
            };
            Reader {
                source,
                state
            }
        }
    */
    pub fn new(input: R) -> Result<Self, std::io::Error> {
        let mut state = imported_decode::ec_dec {
            inp: input,
            // The rest will be initialized by `ec_dec_init`.
            end_window: 0,
            nend_bits: 0,
            nbits_total: 0,
            rng: 0,
            rem: 0,
            val: 0,
            ext: 0,
        };
        unsafe {
            imported_decode::ec_dec_init(&mut state)?;
        }
        Ok(Reader { state })
    }

    /// Decode the next symbol in line.
    pub fn symbol(
        &mut self,
        icdf: &CumulativeDistributionFrequency,
    ) -> Result<u32, std::io::Error> {
        let index = unsafe {
            let frequency = imported_decode::ec_decode(&mut self.state, icdf.width());
            let indexed = icdf.find(frequency).ok_or_else(|| {
                std::io::Error::new(std::io::ErrorKind::InvalidInput, "Invalid probability")
            })?;
            imported_decode::ec_dec_update(
                &mut self.state,
                indexed.segment.low,
                indexed.segment.next,
                icdf.width(),
            )?;
            indexed.index
        };
        Ok(index as u32)
    }

    /*
    // FIXME: I actually don't understand `bits()` well enough
    // to publish it.    /// Encode a sequence of raw bits, without any frequency information.
        pub fn bits(&mut self, size: usize) -> Result<u16, std::io::Error> {
            let result = unsafe {
                let result = imported_decode::ec_dec_bits(&mut self.state,
                    size as u32);
                self.check_status()?;
                result as u16
            };
            Ok(result)
        }
    */

    pub fn done(self) {
        // FIXME: Nothing to do?
    }
}