Skip to main content

rtci_rtp/codec/comfort_noise/
mod.rs

1//! Comfort noise payload format ([RFC 3389]).
2//!
3//! A CN payload is a noise level byte followed by `M` quantised reflection coefficients of an
4//! all-pole noise model (any model order, `M = 0` included):
5//!
6//! ```text
7//!   Byte    1      2    3    ...   M+1
8//!        +-----+-----+-----+-----+-----+
9//!        |level|  N1 |  N2 | ... |  NM |
10//!        +-----+-----+-----+-----+-----+
11//! ```
12//!
13//! RTP usage (section 4): the static payload type `CN_STATIC_PAYLOAD_TYPE` (13) is CN at
14//! `CN_STATIC_CLOCK_RATE` (8000 Hz); any other clock rate MUST use a dynamic payload type.
15//! The RTP timestamp is the start of the noise period, the marker bit SHOULD NOT be set on CN
16//! packets, and each packet carries exactly one CN payload per channel, every channel with the
17//! same model order (`unmarshal_channels`, `marshal_channels`).
18//!
19//! Noise analysis and synthesis are the codec's job; this module only carries the parameters.
20//!
21//! [RFC 3389]: https://datatracker.ietf.org/doc/html/rfc3389
22#[cfg(test)]
23mod comfort_noise_test;
24
25use crate::packetizer::{Depacketizer, MarkerRule, Payloader};
26use bytes::{Buf, BufMut, Bytes, BytesMut};
27use shared::error::{Error, Result};
28use shared::marshal::{Marshal, MarshalSize, Unmarshal};
29
30/// The static RTP payload type of CN at 8000 Hz (RFC 3389 section 4, RFC 3551).
31pub const CN_STATIC_PAYLOAD_TYPE: u8 = 13;
32/// Clock rate of [`CN_STATIC_PAYLOAD_TYPE`]. Other rates use dynamic payload types.
33pub const CN_STATIC_CLOCK_RATE: u32 = 8000;
34/// The largest noise level, in -dBov (section 3.1).
35pub const CN_MAX_LEVEL: u8 = 127;
36/// The largest valid quantised reflection coefficient index; 255 is reserved (section 3.2).
37pub const CN_MAX_COEFFICIENT_INDEX: u8 = 254;
38/// The quantised index of a zero reflection coefficient: `k(127) = 0`.
39pub const CN_ZERO_COEFFICIENT_INDEX: u8 = 127;
40
41/// One comfort-noise payload (sections 3.1 to 3.3).
42#[derive(PartialEq, Eq, Debug, Default, Clone)]
43pub struct ComfortNoise {
44    /// Noise level in -dBov, 0 to 127 (0 to -127 dBov).
45    pub level: u8,
46    /// Quantised reflection coefficients `N_1 ... N_M`, ascending order; the model order `M`
47    /// is their count.
48    pub coefficients: Bytes,
49}
50
51impl ComfortNoise {
52    /// The model order `M`.
53    pub fn model_order(&self) -> usize {
54        self.coefficients.len()
55    }
56
57    /// The quantised coefficients a decoder of model order `order` uses: extra coefficients
58    /// are ignored and missing ones are zero (section 3.2), a zero coefficient being index
59    /// [`CN_ZERO_COEFFICIENT_INDEX`].
60    pub fn coefficients_for_order(&self, order: usize) -> Vec<u8> {
61        let mut out: Vec<u8> = self.coefficients.iter().copied().take(order).collect();
62        out.resize(order, CN_ZERO_COEFFICIENT_INDEX);
63        out
64    }
65
66    /// The reflection coefficients `k_1 ... k_order` (extra ignored, missing ones 0.0). A
67    /// reserved index (255) is taken as 0.0.
68    pub fn reflection_coefficients(&self, order: usize) -> Vec<f64> {
69        self.coefficients_for_order(order)
70            .into_iter()
71            .map(|n| reflection_coefficient(n).unwrap_or(0.0))
72            .collect()
73    }
74}
75
76/// The reflection coefficient of a quantised index (section 3.2):
77/// `k_i = 258 * (N_i - 127) / 32768`. `None` for the reserved index 255.
78pub fn reflection_coefficient(index: u8) -> Option<f64> {
79    if index > CN_MAX_COEFFICIENT_INDEX {
80        return None;
81    }
82    Some(258.0 * (f64::from(index) - 127.0) / 32768.0)
83}
84
85/// The quantised index of a reflection coefficient, the inverse of
86/// [`reflection_coefficient`]: `N_i = round(k_i * 32768 / 258) + 127`, clamped to 0..=254.
87/// A NaN maps to the zero coefficient.
88pub fn quantize_reflection_coefficient(k: f64) -> u8 {
89    if k.is_nan() {
90        return CN_ZERO_COEFFICIENT_INDEX;
91    }
92    let n = (k * 32768.0 / 258.0).round() + 127.0;
93    n.clamp(0.0, f64::from(CN_MAX_COEFFICIENT_INDEX)) as u8
94}
95
96impl MarshalSize for ComfortNoise {
97    fn marshal_size(&self) -> usize {
98        1 + self.coefficients.len()
99    }
100}
101
102impl Marshal for ComfortNoise {
103    /// Writes the level byte (MSB zero) and the coefficients. Fails on a level above 127.
104    fn marshal_to(&self, mut buf: &mut [u8]) -> Result<usize> {
105        let size = self.marshal_size();
106        if buf.remaining_mut() < size {
107            return Err(Error::ErrBufferTooSmall);
108        }
109        if self.level > CN_MAX_LEVEL {
110            return Err(Error::Other(format!(
111                "comfort-noise level {} exceeds {CN_MAX_LEVEL}",
112                self.level
113            )));
114        }
115        buf.put_u8(self.level);
116        buf.put_slice(&self.coefficients);
117        Ok(size)
118    }
119}
120
121impl Unmarshal for ComfortNoise {
122    /// Reads a whole CN payload: everything remaining in `buf`.
123    ///
124    /// Receiver-lenient on the level byte: section 3.1 says its MSB is "unused and always set
125    /// to 0", so a set MSB is masked off rather than rejected (the level is the seven low
126    /// bits). The sender side ([`Marshal`]) never sets it. Coefficient bytes are kept as
127    /// received, the reserved index 255 included.
128    ///
129    /// Fails on an empty payload.
130    fn unmarshal<B>(buf: &mut B) -> Result<Self>
131    where
132        Self: Sized,
133        B: Buf,
134    {
135        if !buf.has_remaining() {
136            return Err(Error::ErrShortPacket);
137        }
138        let level = buf.get_u8() & 0x7F;
139        let coefficients = buf.copy_to_bytes(buf.remaining());
140        Ok(ComfortNoise {
141            level,
142            coefficients,
143        })
144    }
145}
146
147/// Splits a packet's payload into one CN payload per channel (section 4).
148///
149/// All channels have the same model order, so the payload length must be a non-zero multiple
150/// of `channels`.
151///
152/// # Errors
153///
154/// Fails with zero channels, an empty payload, or a length that does not divide evenly.
155pub fn unmarshal_channels(payload: &Bytes, channels: usize) -> Result<Vec<ComfortNoise>> {
156    if channels == 0 {
157        return Err(Error::Other(
158            "comfort noise needs at least one channel".into(),
159        ));
160    }
161    if payload.is_empty() || !payload.len().is_multiple_of(channels) {
162        return Err(Error::ErrShortPacket);
163    }
164    let per_channel = payload.len() / channels;
165    (0..channels)
166        .map(|i| {
167            let mut chunk = payload.slice(i * per_channel..(i + 1) * per_channel);
168            ComfortNoise::unmarshal(&mut chunk)
169        })
170        .collect()
171}
172
173/// Concatenates one CN payload per channel, channel order as given (section 4).
174///
175/// # Errors
176///
177/// Fails on an empty list, channels whose model orders differ, or a level above 127.
178pub fn marshal_channels(channels: &[ComfortNoise]) -> Result<Bytes> {
179    let Some(first) = channels.first() else {
180        return Err(Error::Other(
181            "comfort noise needs at least one channel".into(),
182        ));
183    };
184    let order = first.model_order();
185    if channels.iter().any(|c| c.model_order() != order) {
186        return Err(Error::Other(
187            "every comfort-noise channel must use the same model order".into(),
188        ));
189    }
190    let mut out = BytesMut::zeroed(channels.len() * (order + 1));
191    for (i, channel) in channels.iter().enumerate() {
192        let start = i * (order + 1);
193        channel.marshal_to(&mut out[start..start + order + 1])?;
194    }
195    Ok(out.freeze())
196}
197
198/// Payloads CN: one CN payload per RTP packet, never fragmented.
199///
200/// CN packets do not have the marker bit set (RFC 3389 section 4): the payloader's
201/// [`marker_rule`](Payloader::marker_rule) is [`MarkerRule::Never`], which is what a
202/// [`Packetizer`](crate::packetizer::Packetizer) built on it follows.
203#[derive(Default, Debug, Copy, Clone)]
204pub struct ComfortNoisePayloader;
205
206impl Payloader for ComfortNoisePayloader {
207    fn payload(&mut self, mtu: usize, payload: &Bytes) -> Result<Vec<Bytes>> {
208        if payload.is_empty() || mtu == 0 {
209            return Ok(vec![]);
210        }
211        Ok(vec![payload.clone()])
212    }
213
214    fn marker_rule(&self) -> MarkerRule {
215        MarkerRule::Never
216    }
217
218    fn clone_to(&self) -> Box<dyn Payloader> {
219        Box::new(*self)
220    }
221}
222
223/// Depacketizes CN: the payload is one CN payload (or one per channel), returned as is.
224#[derive(PartialEq, Eq, Debug, Default, Clone)]
225pub struct ComfortNoisePacket;
226
227impl Depacketizer for ComfortNoisePacket {
228    fn depacketize(&mut self, packet: &Bytes) -> Result<Bytes> {
229        if packet.is_empty() {
230            Err(Error::ErrShortPacket)
231        } else {
232            Ok(packet.clone())
233        }
234    }
235
236    fn is_partition_head(&self, _payload: &Bytes) -> bool {
237        true
238    }
239
240    fn is_partition_tail(&self, _marker: bool, _payload: &Bytes) -> bool {
241        true
242    }
243}