rtci-rtp 0.5.0

RTP packets, header extensions (RFC 3550, RFC 8285) and codec payload formats for WebRTC
Documentation
//! The `audio/tone` payload format: telephony tones described by their frequencies (RFC 4733
//! section 4).
//!
//! A tone packet stands alone: unlike a telephone event it carries no history, so a tone
//! longer than one packet is a run of packets whose timestamps follow on from each other
//! ([`ToneSender`]). [`RedundantToneSender`] adds the rest of the sending procedures of
//! section 4.4: each packet also carries the previous tone report in RFC 2198 redundancy
//! (section 4.4.1), and the packetization interval lengthens while receiver reports show loss
//! ([`ToneIntervalControl`], section 4.4.3).

#[cfg(test)]
mod tone_test;

use bytes::{BufMut, Bytes, BytesMut};
use shared::error::{Error, Result};

use super::red::RedEncoder;

/// The default clock rate of `audio/tone` (RFC 4733 section 4.3.4).
pub const TONE_DEFAULT_CLOCK_RATE: u32 = 8000;

/// The largest modulation frequency, 9 bits (RFC 4733 section 4.3.3).
const MAX_MODULATION: u16 = 0x01FF;
/// The largest volume, 6 bits: 0 to -63 dBm0.
const MAX_VOLUME: u8 = 0x3F;
/// The largest frequency, 12 bits.
const MAX_FREQUENCY: u16 = 0x0FFF;

/// One tone report (RFC 4733 section 4.3.3, Figure 2).
#[derive(Debug, Clone, PartialEq, Eq, Default)]
pub struct Tone {
    /// The modulation frequency in Hz, 9 bits; 0 for none.
    pub modulation: u16,
    /// Whether the modulation frequency is to be divided by three (the T bit).
    pub modulation_divided_by_three: bool,
    /// The power level in dBm0 with the sign dropped, 0 to 63.
    pub volume: u8,
    /// How long the tone lasts from the packet's timestamp, in timestamp units. Never 0.
    pub duration: u16,
    /// The frequencies added together, in Hz, 12 bits each; 0 is silence, none is a period
    /// of silence.
    pub frequencies: Vec<u16>,
}

impl Tone {
    /// The payload. The reserved bits before each frequency are zero (section 4.3.3: "The
    /// sender MUST set it to zero"). A field out of its range, or a duration of 0 ("not
    /// permitted"), is refused.
    pub fn marshal(&self) -> Result<Bytes> {
        if self.modulation > MAX_MODULATION
            || self.volume > MAX_VOLUME
            || self.duration == 0
            || self.frequencies.iter().any(|f| *f > MAX_FREQUENCY)
        {
            return Err(Error::Other(format!("not a valid tone: {self:?}")));
        }
        let mut out = BytesMut::with_capacity(4 + 2 * self.frequencies.len());
        out.put_u16(
            (self.modulation << 7)
                | (u16::from(self.modulation_divided_by_three) << 6)
                | u16::from(self.volume),
        );
        out.put_u16(self.duration);
        for frequency in &self.frequencies {
            out.put_u16(*frequency);
        }
        Ok(out.freeze())
    }

    /// The tone in `payload`, the reserved bits ignored (section 4.3.3: "the receiver MUST
    /// ignore it"). `None` for a payload too short or of an odd length, and for a tone of
    /// duration 0, which "SHOULD be ignored".
    pub fn unmarshal(payload: &[u8]) -> Option<Tone> {
        if payload.len() < 4 || !payload.len().is_multiple_of(2) {
            return None;
        }
        let first = u16::from_be_bytes([payload[0], payload[1]]);
        let duration = u16::from_be_bytes([payload[2], payload[3]]);
        if duration == 0 {
            return None;
        }
        Some(Tone {
            modulation: first >> 7,
            modulation_divided_by_three: first & 0x40 != 0,
            volume: (first & 0x3F) as u8,
            duration,
            frequencies: payload[4..]
                .as_chunks::<2>()
                .0
                .iter()
                .map(|pair| u16::from_be_bytes(*pair) & MAX_FREQUENCY)
                .collect(),
        })
    }
}

/// One packet of a tone: its RTP timestamp, marker bit and payload.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct TonePacket {
    /// The RTP timestamp.
    pub timestamp: u32,
    /// The marker bit: set on the first packet of a tone.
    pub marker: bool,
    /// The payload.
    pub payload: Bytes,
}

/// Cuts a tone into packets, without redundancy (RFC 4733 section 4.4.1): "The RTP timestamp MUST be updated for
/// each packet generated ... the RTP timestamp in each subsequent packet MUST equal the sum of
/// the timestamp and the duration in the preceding packet"; the first packet has the marker
/// set and the rest not (section 4.3.2). [`RedundantToneSender`] adds the RFC 2198
/// combination the same section asks for.
#[derive(Debug, Clone, Copy)]
pub struct ToneSender {
    /// The duration of one packet in timestamp units.
    pub packet_duration: u16,
}

impl ToneSender {
    /// The packets of `tone` lasting `total` timestamp units from `timestamp`: each covers
    /// `packet_duration` or what is left, and starts where the one before ended.
    pub fn packets(&self, tone: &Tone, timestamp: u32, total: u32) -> Result<Vec<TonePacket>> {
        let step = u32::from(self.packet_duration.max(1));
        let mut packets = vec![];
        let mut at = 0u32;
        while at < total {
            let duration = (total - at).min(step) as u16;
            let report = Tone {
                duration,
                ..tone.clone()
            };
            packets.push(TonePacket {
                timestamp: timestamp.wrapping_add(at),
                marker: packets.is_empty(),
                payload: report.marshal()?,
            });
            at += u32::from(duration);
        }
        Ok(packets)
    }
}

/// At or above this RTCP fraction lost (out of 256; 26 is 10.2 %), a receiver report means
/// congestion and [`ToneIntervalControl`] lengthens the interval. The loss-based controller's
/// "more than 10 %" (draft-ietf-rmcat-gcc-02 section 6).
pub const TONE_HIGH_LOSS_FRACTION: u8 = 26;
/// At or below this RTCP fraction lost (out of 256; 5 is 1.95 %), a receiver report means no
/// congestion and [`ToneIntervalControl`] shortens the interval again. The loss-based
/// controller's "less than 2 %" (draft-ietf-rmcat-gcc-02 section 6).
pub const TONE_LOW_LOSS_FRACTION: u8 = 5;

/// The packetization interval of initial and interim tone reports under congestion (RFC 4733
/// section 4.4.3): "If the sender determines that packets are being lost due to congestion
/// (e.g., through RTCP receiver reports), it SHOULD increase the packetization interval for
/// initial and interim tone reports ... Both the maximum packetization interval and maximum
/// increase in packetization interval at any one time are therefore a matter of
/// configuration".
///
/// Feed it the fraction lost of each RTCP receiver report about the stream
/// ([`on_receiver_report`](Self::on_receiver_report)). A report at or above the high
/// threshold ([`TONE_HIGH_LOSS_FRACTION`] by default) lengthens the interval by at most the
/// configured increase, up to the configured maximum; one at or below the low threshold
/// ([`TONE_LOW_LOSS_FRACTION`]) shortens it by the same step, back to the initial interval
/// (the RFC leaves the way back open); one between leaves it. Durations are in timestamp
/// units of the tone clock.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct ToneIntervalControl {
    initial: u16,
    maximum: u16,
    max_increase: u16,
    high_loss: u8,
    low_loss: u8,
    current: u16,
}

impl ToneIntervalControl {
    /// Starts at `initial` (at least 1), never above `maximum` (at least `initial`), and
    /// changes by at most `max_increase` (at least 1) per receiver report.
    pub fn new(initial: u16, maximum: u16, max_increase: u16) -> Self {
        let initial = initial.max(1);
        ToneIntervalControl {
            initial,
            maximum: maximum.max(initial),
            max_increase: max_increase.max(1),
            high_loss: TONE_HIGH_LOSS_FRACTION,
            low_loss: TONE_LOW_LOSS_FRACTION,
            current: initial,
        }
    }

    /// The fraction lost (out of 256) at or above which a report means congestion, and the one
    /// at or below which it means none. The high threshold is tested first.
    pub fn with_loss_thresholds(mut self, high: u8, low: u8) -> Self {
        self.high_loss = high;
        self.low_loss = low;
        self
    }

    /// The current packetization interval.
    pub fn packet_duration(&self) -> u16 {
        self.current
    }

    /// Takes the fraction lost (the 8-bit field of an RTCP report block, RFC 3550 section
    /// 6.4.1) and returns the packetization interval from now on.
    pub fn on_receiver_report(&mut self, fraction_lost: u8) -> u16 {
        if fraction_lost >= self.high_loss {
            self.current = self
                .current
                .saturating_add(self.max_increase)
                .min(self.maximum);
        } else if fraction_lost <= self.low_loss {
            self.current = self
                .current
                .saturating_sub(self.max_increase)
                .max(self.initial);
        }
        self.current
    }

    /// A [`ToneSender`] cutting tones at the current interval.
    pub fn sender(&self) -> ToneSender {
        ToneSender {
            packet_duration: self.current,
        }
    }
}

/// The default redundancy of a [`RedundantToneSender`]: each packet carries the tone report of
/// the packet before (RFC 4733 section 4.4.1: "combine new and old tone reports").
pub const TONE_DEFAULT_REDUNDANCY: usize = 1;
/// The default largest RED payload of a [`RedundantToneSender`], in octets.
pub const TONE_DEFAULT_MAX_PAYLOAD_SIZE: usize = 1000;

/// The sending procedures of RFC 4733 section 4.4, sans-I/O: tones cut into packets as
/// [`ToneSender`] does, at the interval a [`ToneIntervalControl`] keeps (section 4.4.3), each
/// payload an RFC 2198 RED payload whose primary is the new tone report and whose redundant
/// blocks are the reports sent before it (section 4.4.1: "for increased reliability, the
/// sender SHOULD combine new and old tone reports in the same RTP packet using RFC 2198 audio
/// redundancy").
///
/// The packets it returns are sent with the RED payload type
/// ([`payload_type`](Self::payload_type)), their timestamp and marker bit; the caller fills in
/// the sequence number and SSRC. The earlier reports are kept across tones, so the first
/// packet of a tone also carries the last report of the tone before while its timestamp
/// offset fits the 14 bits of RFC 2198 (0x3FFF units: an interval longer than that carries no
/// redundancy).
#[derive(Debug, Clone)]
pub struct RedundantToneSender {
    tone_payload_type: u8,
    red_payload_type: u8,
    control: ToneIntervalControl,
    max_payload_size: usize,
    red: RedEncoder,
}

impl RedundantToneSender {
    /// A sender of `audio/tone` reports under `tone_payload_type`, wrapped in RED sent under
    /// `red_payload_type` (both negotiated), with [`TONE_DEFAULT_REDUNDANCY`] and the interval
    /// `control` keeps.
    ///
    /// # Errors
    ///
    /// Fails on a payload type above 127.
    pub fn new(
        tone_payload_type: u8,
        red_payload_type: u8,
        control: ToneIntervalControl,
    ) -> Result<Self> {
        if tone_payload_type > 0x7F || red_payload_type > 0x7F {
            return Err(Error::Other(format!(
                "payload types {tone_payload_type} / {red_payload_type}: more than 127"
            )));
        }
        Ok(RedundantToneSender {
            tone_payload_type,
            red_payload_type,
            control,
            max_payload_size: TONE_DEFAULT_MAX_PAYLOAD_SIZE,
            red: RedEncoder::new(TONE_DEFAULT_REDUNDANCY, TONE_DEFAULT_MAX_PAYLOAD_SIZE),
        })
    }

    /// Carries up to `levels` earlier reports in each packet (RFC 2198 allows several levels;
    /// RFC 4733 section 2.6.2 discusses more than one). Forgets the reports kept so far.
    pub fn with_redundancy(mut self, levels: usize) -> Self {
        self.red = RedEncoder::new(levels, self.max_payload_size);
        self
    }

    /// The RED payload type the packets are sent with.
    pub fn payload_type(&self) -> u8 {
        self.red_payload_type
    }

    /// The interval control.
    pub fn control(&self) -> &ToneIntervalControl {
        &self.control
    }

    /// Passes an RTCP receiver report's fraction lost to the interval control (section 4.4.3)
    /// and returns the interval from now on.
    pub fn on_receiver_report(&mut self, fraction_lost: u8) -> u16 {
        self.control.on_receiver_report(fraction_lost)
    }

    /// Forgets the earlier reports (a stream restart or a timestamp jump).
    pub fn reset(&mut self) {
        self.red.reset();
    }

    /// The packets of `tone` lasting `total` timestamp units from `timestamp`, as
    /// [`ToneSender::packets`] at the current interval, each payload a RED payload carrying
    /// the earlier reports before the new one.
    ///
    /// # Errors
    ///
    /// As [`ToneSender::packets`] (nothing is remembered then), and for a report that alone
    /// does not fit [`TONE_DEFAULT_MAX_PAYLOAD_SIZE`].
    pub fn packets(&mut self, tone: &Tone, timestamp: u32, total: u32) -> Result<Vec<TonePacket>> {
        let plain = self.control.sender().packets(tone, timestamp, total)?;
        plain
            .into_iter()
            .map(|packet| {
                Ok(TonePacket {
                    payload: self.red.encode(
                        self.tone_payload_type,
                        packet.timestamp,
                        packet.payload,
                    )?,
                    ..packet
                })
            })
            .collect()
    }
}