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`]).
7
8#[cfg(test)]
9mod tone_test;
10
11use bytes::{BufMut, Bytes, BytesMut};
12use shared::error::{Error, Result};
13
14/// The default clock rate of `audio/tone` (RFC 4733 section 4.3.4).
15pub const TONE_DEFAULT_CLOCK_RATE: u32 = 8000;
16
17/// The largest modulation frequency, 9 bits (RFC 4733 section 4.3.3).
18const MAX_MODULATION: u16 = 0x01FF;
19/// The largest volume, 6 bits: 0 to -63 dBm0.
20const MAX_VOLUME: u8 = 0x3F;
21/// The largest frequency, 12 bits.
22const MAX_FREQUENCY: u16 = 0x0FFF;
23
24/// One tone report (RFC 4733 section 4.3.3, Figure 2).
25#[derive(Debug, Clone, PartialEq, Eq, Default)]
26pub struct Tone {
27    /// The modulation frequency in Hz, 9 bits; 0 for none.
28    pub modulation: u16,
29    /// Whether the modulation frequency is to be divided by three (the T bit).
30    pub modulation_divided_by_three: bool,
31    /// The power level in dBm0 with the sign dropped, 0 to 63.
32    pub volume: u8,
33    /// How long the tone lasts from the packet's timestamp, in timestamp units. Never 0.
34    pub duration: u16,
35    /// The frequencies added together, in Hz, 12 bits each; 0 is silence, none is a period
36    /// of silence.
37    pub frequencies: Vec<u16>,
38}
39
40impl Tone {
41    /// The payload. The reserved bits before each frequency are zero (section 4.3.3: "The
42    /// sender MUST set it to zero"). A field out of its range, or a duration of 0 ("not
43    /// permitted"), is refused.
44    pub fn marshal(&self) -> Result<Bytes> {
45        if self.modulation > MAX_MODULATION
46            || self.volume > MAX_VOLUME
47            || self.duration == 0
48            || self.frequencies.iter().any(|f| *f > MAX_FREQUENCY)
49        {
50            return Err(Error::Other(format!("not a valid tone: {self:?}")));
51        }
52        let mut out = BytesMut::with_capacity(4 + 2 * self.frequencies.len());
53        out.put_u16(
54            (self.modulation << 7)
55                | (u16::from(self.modulation_divided_by_three) << 6)
56                | u16::from(self.volume),
57        );
58        out.put_u16(self.duration);
59        for frequency in &self.frequencies {
60            out.put_u16(*frequency);
61        }
62        Ok(out.freeze())
63    }
64
65    /// The tone in `payload`, the reserved bits ignored (section 4.3.3: "the receiver MUST
66    /// ignore it"). `None` for a payload too short or of an odd length, and for a tone of
67    /// duration 0, which "SHOULD be ignored".
68    pub fn unmarshal(payload: &[u8]) -> Option<Tone> {
69        if payload.len() < 4 || !payload.len().is_multiple_of(2) {
70            return None;
71        }
72        let first = u16::from_be_bytes([payload[0], payload[1]]);
73        let duration = u16::from_be_bytes([payload[2], payload[3]]);
74        if duration == 0 {
75            return None;
76        }
77        Some(Tone {
78            modulation: first >> 7,
79            modulation_divided_by_three: first & 0x40 != 0,
80            volume: (first & 0x3F) as u8,
81            duration,
82            frequencies: payload[4..]
83                .as_chunks::<2>()
84                .0
85                .iter()
86                .map(|pair| u16::from_be_bytes(*pair) & MAX_FREQUENCY)
87                .collect(),
88        })
89    }
90}
91
92/// One packet of a tone: its RTP timestamp, marker bit and payload.
93#[derive(Debug, Clone, PartialEq, Eq)]
94pub struct TonePacket {
95    /// The RTP timestamp.
96    pub timestamp: u32,
97    /// The marker bit: set on the first packet of a tone.
98    pub marker: bool,
99    /// The payload.
100    pub payload: Bytes,
101}
102
103/// Cuts a tone into packets (RFC 4733 section 4.4.1): "The RTP timestamp MUST be updated for
104/// each packet generated ... the RTP timestamp in each subsequent packet MUST equal the sum of
105/// the timestamp and the duration in the preceding packet"; the first packet has the marker
106/// set and the rest not (section 4.3.2).
107#[derive(Debug, Clone, Copy)]
108pub struct ToneSender {
109    /// The duration of one packet in timestamp units.
110    pub packet_duration: u16,
111}
112
113impl ToneSender {
114    /// The packets of `tone` lasting `total` timestamp units from `timestamp`: each covers
115    /// `packet_duration` or what is left, and starts where the one before ended.
116    pub fn packets(&self, tone: &Tone, timestamp: u32, total: u32) -> Result<Vec<TonePacket>> {
117        let step = u32::from(self.packet_duration.max(1));
118        let mut packets = vec![];
119        let mut at = 0u32;
120        while at < total {
121            let duration = (total - at).min(step) as u16;
122            let report = Tone {
123                duration,
124                ..tone.clone()
125            };
126            packets.push(TonePacket {
127                timestamp: timestamp.wrapping_add(at),
128                marker: packets.is_empty(),
129                payload: report.marshal()?,
130            });
131            at += u32::from(duration);
132        }
133        Ok(packets)
134    }
135}