Skip to main content

sipx_audio/
l16.rs

1//! L16 linear 16-bit RTP audio (RFC 3551 ยง4.5.11).
2
3/// Encode signed samples in RTP's network byte order.
4#[must_use]
5pub fn encode(samples: &[i16]) -> Vec<u8> {
6    let mut encoded = Vec::with_capacity(samples.len().saturating_mul(2));
7    for sample in samples {
8        encoded.extend_from_slice(&sample.to_be_bytes());
9    }
10    encoded
11}
12
13/// Decode complete signed network-order samples.
14///
15/// # Errors
16///
17/// Returns [`L16Error::OddLength`] when a trailing byte cannot form a sample.
18pub fn decode(payload: &[u8]) -> Result<Vec<i16>, L16Error> {
19    if !payload.len().is_multiple_of(2) {
20        return Err(L16Error::OddLength(payload.len()));
21    }
22    Ok(payload
23        .chunks_exact(2)
24        .map(|word| i16::from_be_bytes(word.try_into().unwrap_or_default()))
25        .collect())
26}
27
28/// A malformed L16 payload.
29#[derive(Debug, Clone, Copy, PartialEq, Eq, thiserror::Error)]
30#[non_exhaustive]
31pub enum L16Error {
32    /// A signed 16-bit word is incomplete.
33    #[error("L16 payload has odd length {0}")]
34    OddLength(usize),
35}