opusic_c/
utils.rs

1//! Utility functions
2
3use crate::{sys, mem, SampleRate, Channels, ErrorCode};
4
5#[inline]
6///Gets the number of frames in an Opus packet.
7pub fn get_nb_frames(input: &[u8]) -> Result<usize, ErrorCode> {
8    let result = unsafe {
9        sys::opus_packet_get_nb_frames(input.as_ptr(), input.len() as _)
10    };
11
12    map_sys_error!(result => result as _)
13}
14
15#[inline]
16///Gets the number of samples of an Opus packet.
17pub fn get_nb_samples(input: &[u8], rate: SampleRate) -> Result<usize, ErrorCode> {
18    let result = unsafe {
19        sys::opus_packet_get_nb_samples(input.as_ptr(), input.len() as _, rate as _)
20    };
21
22    map_sys_error!(result => result as _)
23}
24
25#[inline]
26///Applies soft-clipping to bring a float signal within the [-1,1] range.
27///
28///If the signal is already in that range, nothing is done.
29///
30///If there are values outside of [-1,1],
31///then the signal is clipped as smoothly as possible to both fit in the range and
32///avoid creating excessive distortion in the process.
33pub fn soft_clip(input: &mut [f32], channels: Channels) {
34    let mut soft_clip_mem = mem::MaybeUninit::<[f32; 2]>::uninit();
35    unsafe {
36        sys::opus_pcm_soft_clip(
37            input.as_mut_ptr(), (input.len() / channels as usize) as _,
38            channels as _,
39            soft_clip_mem.as_mut_ptr() as _
40        )
41    }
42}