opusic_c/
decoder.rs

1use crate::{sys, mem, ErrorCode, Channels, SampleRate, Bandwidth};
2
3use core::{ptr, num};
4use core::convert::TryInto;
5
6use mem::alloc::vec::Vec;
7
8///OPUS Decoder
9pub struct Decoder {
10    pub(crate) inner: mem::Unique<sys::OpusDecoder>,
11    channels: Channels,
12}
13
14impl Decoder {
15    ///Creates new decoder instance
16    pub fn new(channels: Channels, rate: SampleRate) -> Result<Self, ErrorCode> {
17        let size = unsafe {
18            sys::opus_decoder_get_size(channels as _)
19        };
20
21        if size == 0 {
22            return Err(ErrorCode::Internal);
23        }
24
25        let mut decoder = match mem::Unique::new(size as _) {
26            Some(inner) => Decoder {
27                inner,
28                channels,
29            },
30            None => return Err(ErrorCode::AllocFail)
31        };
32
33        let result = unsafe {
34            sys::opus_decoder_init(decoder.inner.as_mut(), rate as _, channels as _)
35        };
36
37        map_sys_error!(result => decoder)
38    }
39
40    #[inline(always)]
41    ///Returns channels number
42    ///
43    ///When decoding, it is used to determine frame size as `output.len() / channels`
44    pub fn channels(&self) -> Channels {
45        self.channels
46    }
47
48    ///Decodes input packet, returning number of decoded samples.
49    ///
50    ///If more than 1 channel is configured, then input must be interleaved.
51    ///
52    ///Output size must correspond to sampling rate.
53    ///For example, at 48 kHz allowed frame sizes are 120, 240, 480, 960, 1920, and 2880.
54    ///
55    ///Maximum packet duration is 120ms therefore maximum `frame size` must be
56    ///`frame_bytes_size(SampleRate::Hz48000, Channels::Stereo, 120)`
57    ///
58    ///When `input` size is 0, libopus shall treat it as packet loss, in which case `output` size must
59    ///match expected output of next packet to know how much frames is skipped
60    ///
61    ///When `decode_fec` is `true`, requests that any in-band forward error correction data be decoded.
62    ///If no such data is available, the frame is decoded as if it were lost.
63    pub fn decode_to(&mut self, input: &[u8], output: &mut [mem::MaybeUninit<u16>], decode_fec: bool) -> Result<usize, ErrorCode> {
64        let (input_ptr, input_len) = match input.len() {
65            0 => (ptr::null(), 0),
66            len => (input.as_ptr(), len as _)
67        };
68
69        let fec = match decode_fec {
70            true => 1,
71            false => 0,
72        };
73        let result = unsafe {
74            sys::opus_decode(self.inner.as_mut(),
75                             input_ptr, input_len,
76                             output.as_mut_ptr() as _, (output.len() / self.channels as usize) as _,
77                             fec)
78        };
79
80        map_sys_error!(result => result as _)
81    }
82
83    #[inline(always)]
84    ///Decodes input packet, returning number of decoded samples.
85    ///
86    ///Refer to `decode_to` for details
87    pub fn decode_to_slice(&mut self, input: &[u8], output: &mut [u16], decode_fec: bool) -> Result<usize, ErrorCode> {
88        self.decode_to(input, unsafe { mem::transmute(output) }, decode_fec)
89    }
90
91    #[inline(always)]
92    ///Decodes input packet, returning number of decoded samples.
93    ///
94    ///Vector will be written into spare capacity, modifying its length on success.
95    ///
96    ///`decode_len` is used to reserve additional memory and will be passed exactly with this size to `decode_to`
97    ///
98    ///Refer to `decode_to` for details
99    pub fn decode_to_vec(&mut self, input: &[u8], output: &mut Vec<u16>, decode_len: usize, decode_fec: bool) -> Result<usize, ErrorCode> {
100        let initial_len = output.len();
101
102        if output.try_reserve(decode_len).is_err() {
103            return Err(ErrorCode::alloc_fail())
104        }
105
106        let result = self.decode_to(input, &mut output.spare_capacity_mut()[..decode_len], decode_fec)?;
107        unsafe {
108            output.set_len(initial_len + result);
109        }
110        Ok(result)
111    }
112
113    ///Decodes input packet, returning number of decoded samples.
114    ///
115    ///If more than 1 channel is configured, then input must be interleaved.
116    ///
117    ///Output size must correspond to sampling rate.
118    ///For example, at 48 kHz allowed frame sizes are 120, 240, 480, 960, 1920, and 2880.
119    ///
120    ///Maximum packet duration is 120ms therefore maximum `frame size` must be
121    ///`frame_bytes_size(SampleRate::Hz48000, Channels::Stereo, 120)`
122    ///
123    ///When `input` size is 0, libopus shall treat it as packet loss, in which case `output` size must
124    ///match expected output of next packet to know how much frames is skipped
125    ///
126    ///When `decode_fec` is `true`, requests that any in-band forward error correction data be decoded.
127    ///If no such data is available, the frame is decoded as if it were lost.
128    pub fn decode_float_to(&mut self, input: &[u8], output: &mut [mem::MaybeUninit<f32>], decode_fec: bool) -> Result<usize, ErrorCode> {
129        let (input_ptr, input_len) = match input.len() {
130            0 => (ptr::null(), 0),
131            len => (input.as_ptr(), len as _)
132        };
133        let fec = match decode_fec {
134            true => 1,
135            false => 0,
136        };
137
138        let result = unsafe {
139            sys::opus_decode_float(self.inner.as_mut(),
140                                   input_ptr, input_len,
141                                   output.as_mut_ptr() as _, (output.len() / self.channels as usize) as _,
142                                   fec)
143        };
144
145        map_sys_error!(result => result as _)
146    }
147
148    #[inline(always)]
149    ///Decodes input packet, returning number of decoded samples.
150    ///
151    ///Refer to `decode_to` for details
152    pub fn decode_float_to_slice(&mut self, input: &[u8], output: &mut [f32], decode_fec: bool) -> Result<usize, ErrorCode> {
153        self.decode_float_to(input, unsafe { mem::transmute(output) }, decode_fec)
154    }
155
156    #[inline(always)]
157    ///Decodes input packet, returning number of decoded samples.
158    ///
159    ///Vector will be written into spare capacity, modifying its length on success.
160    ///
161    ///`decode_len` is used to reserve additional memory and will be passed exactly with this size to `decode_to`
162    ///
163    ///Refer to `decode_to` for details
164    pub fn decode_float_to_vec(&mut self, input: &[u8], output: &mut Vec<f32>, decode_len: usize, decode_fec: bool) -> Result<usize, ErrorCode> {
165        let initial_len = output.len();
166
167        if output.try_reserve(decode_len).is_err() {
168            return Err(ErrorCode::alloc_fail())
169        }
170
171        let result = self.decode_float_to(input, &mut output.spare_capacity_mut()[..decode_len], decode_fec)?;
172        unsafe {
173            output.set_len(initial_len + result);
174        }
175        Ok(result)
176    }
177
178    ///Gets the number of samples of an Opus packet.
179    pub fn get_nb_samples(&self, input: &[u8]) -> Result<usize, ErrorCode> {
180        let len = match input.len().try_into() {
181            Ok(len) => len,
182            //This is very unlikely if user gets valid packets fed
183            Err(_) => return Err(ErrorCode::invalid_packet()),
184        };
185
186        let result = unsafe {
187            sys::opus_decoder_get_nb_samples(self.inner.as_ptr(), input.as_ptr() as *const _, len)
188        };
189
190        map_sys_error!(result => result as _)
191    }
192
193    #[inline]
194    ///Resets state to initial
195    pub fn reset(&mut self) -> Result<(), ErrorCode> {
196        let result = unsafe {
197            sys::opus_decoder_ctl(self.inner.as_mut(), sys::OPUS_RESET_STATE)
198        };
199
200        map_sys_error!(result => ())
201    }
202
203    #[inline]
204    ///Gets the pitch of the last decoded frame, if available.
205    ///
206    ///This can be used for any post-processing algorithm requiring the use of pitch, e.g. time
207    ///stretching/shortening. If the last frame was not voiced, or if the pitch was not coded in
208    ///the frame, then zero is returned.
209    pub fn get_pitch(&mut self) -> Result<Option<num::NonZeroU32>, ErrorCode> {
210        let mut value: i32 = 0;
211        let result = unsafe {
212            sys::opus_decoder_ctl(self.inner.as_mut(), sys::OPUS_GET_PITCH_REQUEST, &mut value)
213        };
214
215        map_sys_error!(result => num::NonZeroU32::new(result as _))
216    }
217
218    #[inline]
219    ///Gets the duration (in samples) of the last packet successfully decoded or concealed.
220    pub fn get_last_packet_duration(&mut self) -> Result<u32, ErrorCode> {
221        let mut value: i32 = 0;
222        let result = unsafe {
223            sys::opus_decoder_ctl(self.inner.as_mut(), sys::OPUS_GET_LAST_PACKET_DURATION_REQUEST, &mut value)
224        };
225
226        map_sys_error!(result => value as _)
227    }
228
229    #[inline]
230    ///Gets the decoder's gain configuration
231    pub fn get_gain(&mut self) -> Result<i32, ErrorCode> {
232        let mut value: i32 = 0;
233        let result = unsafe {
234            sys::opus_decoder_ctl(self.inner.as_mut(), sys::OPUS_GET_GAIN_REQUEST, &mut value)
235        };
236
237        map_sys_error!(result => value)
238    }
239
240    #[inline]
241    ///Configures decoder gain adjustment.
242    ///
243    ///Scales the decoded output by a factor specified in Q8 dB units.
244    ///This has a maximum range of -32768 to 32767 inclusive, and returns `BadArg` otherwise.
245    ///
246    ///The default is zero indicating no adjustment.
247    ///
248    ///_This setting survives decoder reset_.
249    ///
250    ///Formula:
251    ///
252    ///`gain = pow(10, x/(20.0*256))`
253    pub fn set_gain(&mut self, value: i32) -> Result<(), ErrorCode> {
254        let result = unsafe {
255            sys::opus_decoder_ctl(self.inner.as_mut(), sys::OPUS_SET_GAIN_REQUEST, value)
256        };
257
258        map_sys_error!(result => ())
259    }
260
261    #[cfg(feature = "dred")]
262    #[inline]
263    ///Configures the decoder's computational complexity.
264    ///
265    ///The supported range is 0-10 inclusive with 10 representing the highest complexity.
266    ///Values of 5 or above will use deep packet loss concealment.
267    pub fn set_complexity(&mut self, value: u8) -> Result<(), ErrorCode> {
268        let result = unsafe {
269            sys::opus_decoder_ctl(
270                self.inner.as_mut(),
271                sys::OPUS_SET_COMPLEXITY_REQUEST,
272                value as i32,
273            )
274        };
275
276        map_sys_error!(result => ())
277    }
278
279    #[cfg(feature = "dred")]
280    #[inline]
281    ///Gets the decoder's complexity configuration.
282    pub fn get_complexity(&mut self) -> Result<u8, ErrorCode> {
283        let mut value: i32 = 0;
284        let result = unsafe {
285            sys::opus_decoder_ctl(self.inner.as_mut(), sys::OPUS_GET_COMPLEXITY_REQUEST, &mut value)
286        };
287
288        map_sys_error!(result => value as u8)
289    }
290
291    #[inline]
292    ///Gets the decoder's last bandpass
293    pub fn get_bandwidth(&mut self) -> Result<Bandwidth, ErrorCode> {
294        let mut value: i32 = 0;
295        let result = unsafe {
296            sys::opus_decoder_ctl(self.inner.as_mut(), sys::OPUS_GET_BANDWIDTH_REQUEST, &mut value)
297        };
298
299        map_sys_error!(result => value.into())
300    }
301
302    #[inline]
303    ///Gets configured sample rate of this instance
304    pub fn get_sample_rate(&mut self) -> Result<SampleRate, ErrorCode> {
305        let mut value: i32 = 0;
306        let result = unsafe {
307            sys::opus_decoder_ctl(self.inner.as_mut(), sys::OPUS_GET_SAMPLE_RATE_REQUEST, &mut value)
308        };
309
310        map_sys_error!(result => match value {
311            8000 => SampleRate::Hz8000,
312            12000 => SampleRate::Hz12000,
313            16000 => SampleRate::Hz16000,
314            24000 => SampleRate::Hz24000,
315            48000 => SampleRate::Hz48000,
316            _ => return Err(ErrorCode::unknown())
317        })
318    }
319
320    #[inline]
321    ///Gets the decoder's configured phase inversion status.
322    pub fn get_phase_inversion_disabled(&mut self) -> Result<bool, ErrorCode> {
323        let mut value: i32 = 0;
324        let result = unsafe {
325            sys::opus_decoder_ctl(self.inner.as_mut(), sys::OPUS_GET_PHASE_INVERSION_DISABLED_REQUEST, &mut value)
326        };
327
328        map_sys_error!(result => value == 1)
329    }
330
331    #[inline]
332    ///Configures phase inversion.
333    ///
334    ///If set to `true`, disables the use of phase inversion for intensity stereo, improving the quality
335    ///of mono downmixes, but slightly reducing normal stereo quality.
336    ///
337    ///Disabling phase inversion in the decoder does not comply with RFC 6716, although it does not
338    ///cause any interoperability issue and is expected to become part of the Opus standard once
339    ///RFC 6716 is updated by draft-ietf-codec-opus-update.
340    pub fn set_phase_inversion_disabled(&mut self, value: bool) -> Result<(), ErrorCode> {
341        let value: i32 = match value {
342            true => 1,
343            false => 0,
344        };
345
346        let result = unsafe {
347            sys::opus_decoder_ctl(self.inner.as_mut(), sys::OPUS_SET_PHASE_INVERSION_DISABLED_REQUEST, value)
348        };
349
350        map_sys_error!(result => ())
351    }
352}
353
354unsafe impl Send for Decoder {}