Skip to main content

rtci_rtp/codec/tone/
mod.rs

1//! The `audio/tone` payload format: telephony tones described by their frequencies (RFC 4733
2//! section 4).
3//!
4//! A tone packet stands alone: unlike a telephone event it carries no history, so a tone
5//! longer than one packet is a run of packets whose timestamps follow on from each other
6//! ([`ToneSender`]). [`RedundantToneSender`] adds the rest of the sending procedures of
7//! section 4.4: each packet also carries the previous tone report in RFC 2198 redundancy
8//! (section 4.4.1), and the packetization interval lengthens while receiver reports show loss
9//! ([`ToneIntervalControl`], section 4.4.3).
10
11#[cfg(test)]
12mod tone_test;
13
14use bytes::{BufMut, Bytes, BytesMut};
15use shared::error::{Error, Result};
16
17use super::red::RedEncoder;
18
19/// The default clock rate of `audio/tone` (RFC 4733 section 4.3.4).
20pub const TONE_DEFAULT_CLOCK_RATE: u32 = 8000;
21
22/// The largest modulation frequency, 9 bits (RFC 4733 section 4.3.3).
23const MAX_MODULATION: u16 = 0x01FF;
24/// The largest volume, 6 bits: 0 to -63 dBm0.
25const MAX_VOLUME: u8 = 0x3F;
26/// The largest frequency, 12 bits.
27const MAX_FREQUENCY: u16 = 0x0FFF;
28
29/// One tone report (RFC 4733 section 4.3.3, Figure 2).
30#[derive(Debug, Clone, PartialEq, Eq, Default)]
31pub struct Tone {
32    /// The modulation frequency in Hz, 9 bits; 0 for none.
33    pub modulation: u16,
34    /// Whether the modulation frequency is to be divided by three (the T bit).
35    pub modulation_divided_by_three: bool,
36    /// The power level in dBm0 with the sign dropped, 0 to 63.
37    pub volume: u8,
38    /// How long the tone lasts from the packet's timestamp, in timestamp units. Never 0.
39    pub duration: u16,
40    /// The frequencies added together, in Hz, 12 bits each; 0 is silence, none is a period
41    /// of silence.
42    pub frequencies: Vec<u16>,
43}
44
45impl Tone {
46    /// The payload. The reserved bits before each frequency are zero (section 4.3.3: "The
47    /// sender MUST set it to zero"). A field out of its range, or a duration of 0 ("not
48    /// permitted"), is refused.
49    pub fn marshal(&self) -> Result<Bytes> {
50        if self.modulation > MAX_MODULATION
51            || self.volume > MAX_VOLUME
52            || self.duration == 0
53            || self.frequencies.iter().any(|f| *f > MAX_FREQUENCY)
54        {
55            return Err(Error::Other(format!("not a valid tone: {self:?}")));
56        }
57        let mut out = BytesMut::with_capacity(4 + 2 * self.frequencies.len());
58        out.put_u16(
59            (self.modulation << 7)
60                | (u16::from(self.modulation_divided_by_three) << 6)
61                | u16::from(self.volume),
62        );
63        out.put_u16(self.duration);
64        for frequency in &self.frequencies {
65            out.put_u16(*frequency);
66        }
67        Ok(out.freeze())
68    }
69
70    /// The tone in `payload`, the reserved bits ignored (section 4.3.3: "the receiver MUST
71    /// ignore it"). `None` for a payload too short or of an odd length, and for a tone of
72    /// duration 0, which "SHOULD be ignored".
73    pub fn unmarshal(payload: &[u8]) -> Option<Tone> {
74        if payload.len() < 4 || !payload.len().is_multiple_of(2) {
75            return None;
76        }
77        let first = u16::from_be_bytes([payload[0], payload[1]]);
78        let duration = u16::from_be_bytes([payload[2], payload[3]]);
79        if duration == 0 {
80            return None;
81        }
82        Some(Tone {
83            modulation: first >> 7,
84            modulation_divided_by_three: first & 0x40 != 0,
85            volume: (first & 0x3F) as u8,
86            duration,
87            frequencies: payload[4..]
88                .as_chunks::<2>()
89                .0
90                .iter()
91                .map(|pair| u16::from_be_bytes(*pair) & MAX_FREQUENCY)
92                .collect(),
93        })
94    }
95}
96
97/// One packet of a tone: its RTP timestamp, marker bit and payload.
98#[derive(Debug, Clone, PartialEq, Eq)]
99pub struct TonePacket {
100    /// The RTP timestamp.
101    pub timestamp: u32,
102    /// The marker bit: set on the first packet of a tone.
103    pub marker: bool,
104    /// The payload.
105    pub payload: Bytes,
106}
107
108/// Cuts a tone into packets, without redundancy (RFC 4733 section 4.4.1): "The RTP timestamp MUST be updated for
109/// each packet generated ... the RTP timestamp in each subsequent packet MUST equal the sum of
110/// the timestamp and the duration in the preceding packet"; the first packet has the marker
111/// set and the rest not (section 4.3.2). [`RedundantToneSender`] adds the RFC 2198
112/// combination the same section asks for.
113#[derive(Debug, Clone, Copy)]
114pub struct ToneSender {
115    /// The duration of one packet in timestamp units.
116    pub packet_duration: u16,
117}
118
119impl ToneSender {
120    /// The packets of `tone` lasting `total` timestamp units from `timestamp`: each covers
121    /// `packet_duration` or what is left, and starts where the one before ended.
122    pub fn packets(&self, tone: &Tone, timestamp: u32, total: u32) -> Result<Vec<TonePacket>> {
123        let step = u32::from(self.packet_duration.max(1));
124        let mut packets = vec![];
125        let mut at = 0u32;
126        while at < total {
127            let duration = (total - at).min(step) as u16;
128            let report = Tone {
129                duration,
130                ..tone.clone()
131            };
132            packets.push(TonePacket {
133                timestamp: timestamp.wrapping_add(at),
134                marker: packets.is_empty(),
135                payload: report.marshal()?,
136            });
137            at += u32::from(duration);
138        }
139        Ok(packets)
140    }
141}
142
143/// At or above this RTCP fraction lost (out of 256; 26 is 10.2 %), a receiver report means
144/// congestion and [`ToneIntervalControl`] lengthens the interval. The loss-based controller's
145/// "more than 10 %" (draft-ietf-rmcat-gcc-02 section 6).
146pub const TONE_HIGH_LOSS_FRACTION: u8 = 26;
147/// At or below this RTCP fraction lost (out of 256; 5 is 1.95 %), a receiver report means no
148/// congestion and [`ToneIntervalControl`] shortens the interval again. The loss-based
149/// controller's "less than 2 %" (draft-ietf-rmcat-gcc-02 section 6).
150pub const TONE_LOW_LOSS_FRACTION: u8 = 5;
151
152/// The packetization interval of initial and interim tone reports under congestion (RFC 4733
153/// section 4.4.3): "If the sender determines that packets are being lost due to congestion
154/// (e.g., through RTCP receiver reports), it SHOULD increase the packetization interval for
155/// initial and interim tone reports ... Both the maximum packetization interval and maximum
156/// increase in packetization interval at any one time are therefore a matter of
157/// configuration".
158///
159/// Feed it the fraction lost of each RTCP receiver report about the stream
160/// ([`on_receiver_report`](Self::on_receiver_report)). A report at or above the high
161/// threshold ([`TONE_HIGH_LOSS_FRACTION`] by default) lengthens the interval by at most the
162/// configured increase, up to the configured maximum; one at or below the low threshold
163/// ([`TONE_LOW_LOSS_FRACTION`]) shortens it by the same step, back to the initial interval
164/// (the RFC leaves the way back open); one between leaves it. Durations are in timestamp
165/// units of the tone clock.
166#[derive(Debug, Clone, Copy, PartialEq, Eq)]
167pub struct ToneIntervalControl {
168    initial: u16,
169    maximum: u16,
170    max_increase: u16,
171    high_loss: u8,
172    low_loss: u8,
173    current: u16,
174}
175
176impl ToneIntervalControl {
177    /// Starts at `initial` (at least 1), never above `maximum` (at least `initial`), and
178    /// changes by at most `max_increase` (at least 1) per receiver report.
179    pub fn new(initial: u16, maximum: u16, max_increase: u16) -> Self {
180        let initial = initial.max(1);
181        ToneIntervalControl {
182            initial,
183            maximum: maximum.max(initial),
184            max_increase: max_increase.max(1),
185            high_loss: TONE_HIGH_LOSS_FRACTION,
186            low_loss: TONE_LOW_LOSS_FRACTION,
187            current: initial,
188        }
189    }
190
191    /// The fraction lost (out of 256) at or above which a report means congestion, and the one
192    /// at or below which it means none. The high threshold is tested first.
193    pub fn with_loss_thresholds(mut self, high: u8, low: u8) -> Self {
194        self.high_loss = high;
195        self.low_loss = low;
196        self
197    }
198
199    /// The current packetization interval.
200    pub fn packet_duration(&self) -> u16 {
201        self.current
202    }
203
204    /// Takes the fraction lost (the 8-bit field of an RTCP report block, RFC 3550 section
205    /// 6.4.1) and returns the packetization interval from now on.
206    pub fn on_receiver_report(&mut self, fraction_lost: u8) -> u16 {
207        if fraction_lost >= self.high_loss {
208            self.current = self
209                .current
210                .saturating_add(self.max_increase)
211                .min(self.maximum);
212        } else if fraction_lost <= self.low_loss {
213            self.current = self
214                .current
215                .saturating_sub(self.max_increase)
216                .max(self.initial);
217        }
218        self.current
219    }
220
221    /// A [`ToneSender`] cutting tones at the current interval.
222    pub fn sender(&self) -> ToneSender {
223        ToneSender {
224            packet_duration: self.current,
225        }
226    }
227}
228
229/// The default redundancy of a [`RedundantToneSender`]: each packet carries the tone report of
230/// the packet before (RFC 4733 section 4.4.1: "combine new and old tone reports").
231pub const TONE_DEFAULT_REDUNDANCY: usize = 1;
232/// The default largest RED payload of a [`RedundantToneSender`], in octets.
233pub const TONE_DEFAULT_MAX_PAYLOAD_SIZE: usize = 1000;
234
235/// The sending procedures of RFC 4733 section 4.4, sans-I/O: tones cut into packets as
236/// [`ToneSender`] does, at the interval a [`ToneIntervalControl`] keeps (section 4.4.3), each
237/// payload an RFC 2198 RED payload whose primary is the new tone report and whose redundant
238/// blocks are the reports sent before it (section 4.4.1: "for increased reliability, the
239/// sender SHOULD combine new and old tone reports in the same RTP packet using RFC 2198 audio
240/// redundancy").
241///
242/// The packets it returns are sent with the RED payload type
243/// ([`payload_type`](Self::payload_type)), their timestamp and marker bit; the caller fills in
244/// the sequence number and SSRC. The earlier reports are kept across tones, so the first
245/// packet of a tone also carries the last report of the tone before while its timestamp
246/// offset fits the 14 bits of RFC 2198 (0x3FFF units: an interval longer than that carries no
247/// redundancy).
248#[derive(Debug, Clone)]
249pub struct RedundantToneSender {
250    tone_payload_type: u8,
251    red_payload_type: u8,
252    control: ToneIntervalControl,
253    max_payload_size: usize,
254    red: RedEncoder,
255}
256
257impl RedundantToneSender {
258    /// A sender of `audio/tone` reports under `tone_payload_type`, wrapped in RED sent under
259    /// `red_payload_type` (both negotiated), with [`TONE_DEFAULT_REDUNDANCY`] and the interval
260    /// `control` keeps.
261    ///
262    /// # Errors
263    ///
264    /// Fails on a payload type above 127.
265    pub fn new(
266        tone_payload_type: u8,
267        red_payload_type: u8,
268        control: ToneIntervalControl,
269    ) -> Result<Self> {
270        if tone_payload_type > 0x7F || red_payload_type > 0x7F {
271            return Err(Error::Other(format!(
272                "payload types {tone_payload_type} / {red_payload_type}: more than 127"
273            )));
274        }
275        Ok(RedundantToneSender {
276            tone_payload_type,
277            red_payload_type,
278            control,
279            max_payload_size: TONE_DEFAULT_MAX_PAYLOAD_SIZE,
280            red: RedEncoder::new(TONE_DEFAULT_REDUNDANCY, TONE_DEFAULT_MAX_PAYLOAD_SIZE),
281        })
282    }
283
284    /// Carries up to `levels` earlier reports in each packet (RFC 2198 allows several levels;
285    /// RFC 4733 section 2.6.2 discusses more than one). Forgets the reports kept so far.
286    pub fn with_redundancy(mut self, levels: usize) -> Self {
287        self.red = RedEncoder::new(levels, self.max_payload_size);
288        self
289    }
290
291    /// The RED payload type the packets are sent with.
292    pub fn payload_type(&self) -> u8 {
293        self.red_payload_type
294    }
295
296    /// The interval control.
297    pub fn control(&self) -> &ToneIntervalControl {
298        &self.control
299    }
300
301    /// Passes an RTCP receiver report's fraction lost to the interval control (section 4.4.3)
302    /// and returns the interval from now on.
303    pub fn on_receiver_report(&mut self, fraction_lost: u8) -> u16 {
304        self.control.on_receiver_report(fraction_lost)
305    }
306
307    /// Forgets the earlier reports (a stream restart or a timestamp jump).
308    pub fn reset(&mut self) {
309        self.red.reset();
310    }
311
312    /// The packets of `tone` lasting `total` timestamp units from `timestamp`, as
313    /// [`ToneSender::packets`] at the current interval, each payload a RED payload carrying
314    /// the earlier reports before the new one.
315    ///
316    /// # Errors
317    ///
318    /// As [`ToneSender::packets`] (nothing is remembered then), and for a report that alone
319    /// does not fit [`TONE_DEFAULT_MAX_PAYLOAD_SIZE`].
320    pub fn packets(&mut self, tone: &Tone, timestamp: u32, total: u32) -> Result<Vec<TonePacket>> {
321        let plain = self.control.sender().packets(tone, timestamp, total)?;
322        plain
323            .into_iter()
324            .map(|packet| {
325                Ok(TonePacket {
326                    payload: self.red.encode(
327                        self.tone_payload_type,
328                        packet.timestamp,
329                        packet.payload,
330                    )?,
331                    ..packet
332                })
333            })
334            .collect()
335    }
336}