range_encoding/opus/
encode.rs

1
2use ::{ CumulativeDistributionFrequency };
3
4use opus::imported_encode;
5
6use std;
7
8pub struct Writer<W> where W: std::io::Write {
9    state: imported_encode::ec_enc<W>,
10}
11
12impl<W> Writer<W> where W: std::io::Write {
13    pub fn new(out: W) -> Self {
14        Self {
15            state: imported_encode::ec_enc {
16                out,
17                end_window: 0,
18                nend_bits: 0,
19                nbits_total: 33,
20                offs: 0,
21                rng: std::u32::MAX / 2 + 1,
22                rem: -1,
23                val: 0,
24                ext: 0,
25                end_buffer: vec![],
26            }
27        }
28    }
29
30    /// Encode the next symbol in line.
31    pub fn symbol(&mut self, index: usize, icdf: &CumulativeDistributionFrequency) -> Result<(), std::io::Error> {
32        let width = icdf.width();
33        let segment = icdf.at_index(index).ok_or_else(|| {
34            std::io::Error::new(std::io::ErrorKind::InvalidInput, "Invalid symbol")
35        })?;
36        unsafe {
37            imported_encode::ec_encode(&mut self.state, segment.low, segment.next, width)?;
38        };
39        Ok(())
40    }
41
42/*
43// FIXME: I actually don't understand `bits()` well enough
44// to publish it.    /// Encode a sequence of raw bits, without any frequency information.
45    pub fn bits(&mut self, bits: u16, size: usize) -> Result<(), std::io::Error> {
46        unsafe {
47            imported_encode::ec_enc_bits(&mut self.state,
48                bits as u32,
49                size as u32);
50            self.check_status()?;
51        }
52        Ok(())
53    }
54*/
55
56    /// Flush and return the underlying stream.
57    pub fn done(mut self) -> Result<W, std::io::Error> {
58        unsafe {
59            imported_encode::ec_enc_done(&mut self.state)?;
60        };
61        Ok(self.state.out)
62    }
63}