Skip to main content

opus_codec/
constants.rs

1//! Crate-wide constants and small helpers
2
3use crate::types::SampleRate;
4
5/// Maximum samples per channel in a single Opus frame at 48 kHz.
6///
7/// 120 ms at 48 kHz = 0.120 * 48000 = 5760 samples.
8pub const MAX_FRAME_SAMPLES_48KHZ: usize = 5760;
9
10/// Maximum packet duration in milliseconds.
11pub const MAX_PACKET_DURATION_MS: usize = 120;
12
13/// Compute the maximum samples per channel for a frame at the given `sample_rate`.
14#[must_use]
15pub const fn max_frame_samples_for(sample_rate: SampleRate) -> usize {
16    // Scale linearly from the 48 kHz base.
17    // sample_rate.as_i32() is always positive given valid SampleRate enum values
18    (MAX_FRAME_SAMPLES_48KHZ * (sample_rate as usize)) / 48_000
19}
20
21/// Number of samples per channel in a 2.5 ms frame at the given `sample_rate`.
22///
23/// libopus requires PLC/FEC and DRED frame sizes to be multiples of this value.
24#[must_use]
25pub const fn samples_per_2_5ms(sample_rate: SampleRate) -> usize {
26    (sample_rate as usize) / 400
27}
28
29/// Returns `true` when `frame_size` is a multiple of 2.5 ms at `sample_rate`.
30#[must_use]
31pub const fn is_frame_size_2_5ms_aligned(frame_size: usize, sample_rate: SampleRate) -> bool {
32    let quant = samples_per_2_5ms(sample_rate);
33    quant > 0 && frame_size.is_multiple_of(quant)
34}