rtci 0.4.0

A sans-I/O WebRTC implementation: peer connections with ICE, DTLS-SRTP, SCTP data channels, RTP/RTCP and JSEP negotiation
Documentation
//! How often the SDES header extensions (MID, RtpStreamId, RepairedRtpStreamId) go out.
//!
//! RFC 7941 section 4.2.3: "The general recommendation is to only send header extensions when
//! needed", with N repetitions for the basic case and, "for point-to-point or small receiver
//! populations", feedback "to determine when the information in the header extensions has
//! reached all receivers and to stop further repetitions" ("The normal RTCP report blocks can
//! also provide an indicator of successful delivery"). Section 4.2.4.1: a new SSRC is sent
//! "with high probability" that every participant gets it; section 4.2.4.3: a changed value
//! "with high probability of delivery". RFC 9143 section 15: the MID extension "SHOULD be
//! included in some RTP packets at the start of the session and whenever the SSRC changes".
//!
//! The policy: `RTCRtpSender::write_rtp` stamps the elements on every packet it writes, and
//! then, before the interceptor chain, each SSRC's packets keep them until a report block for
//! that SSRC (an SR or RR from the peer, read by the interceptor handler) reports an extended
//! highest sequence number at or past the first packet that carried the values it carries now;
//! from then on `write_rtp` takes them out of that SSRC's packets. A new SSRC (a new stream,
//! an SSRC a collision or a clock rate change moved to) starts over, and so does a stream whose
//! values change (section 4.2.4.3): until the receiver has reported on a packet that carried
//! the new values. Deciding before the chain keeps what the chain builds from a packet
//! consistent with the packet as sent: FEC protects the header extension, the NACK responder
//! sends a packet again byte for byte when no RTX is negotiated, and the pacer and the
//! congestion controller count its size.
//!
//! Every packet before the acknowledgement carries the elements, so a report on any of them
//! means the receiver had one that carried them: the margin of section 4.2.4.1 is the
//! receiver's own report. The RTX stream (a new SSRC to the receiver) is not acknowledged
//! here: the NACK responder puts the stream's MID and RepairedRtpStreamId on every RTX packet,
//! also when the packet it repairs went without them.
//!
//! libwebrtc (Chrome, Firefox's and WebKit's senders) stops at the first report block naming
//! the SSRC whatever sequence number it reports (`RTPSender::OnReceivedAckOnSsrc`,
//! `AttachMidAndRid`, modules/rtp_rtcp/source/rtp_sender.cc @ a222406d; `always_send_mid_and_rid`
//! defaults to false in `RtpRtcpInterface::Configuration`), and its receivers keep the SSRC
//! they bound once the elements stop (call/rtp_demuxer.cc `latch_ssrc_id`; Firefox's
//! `MediaPipelineFilter::Filter` and `Update` keep `mRemoteMidBindings`). This policy stops no
//! earlier than libwebrtc does. (libwebrtc also stops on its RTX stream once that SSRC is
//! reported on; here the RTX packets always carry them, a few octets on the repairs only.)
//!
//! `SettingEngineBuilder::with_sdes_header_extensions_on_every_packet(true)` keeps the elements
//! on every packet (libwebrtc's `always_send_mid_and_rid`).

use bytes::Bytes;
use std::collections::HashMap;

use crate::rtp_transceiver::SSRC;

/// How many SSRCs the policy follows. A stream beyond it is not followed and keeps the
/// elements on every packet, as before the policy: the safe side.
pub(crate) const MAX_SDES_SEND_STREAMS: usize = 1024;

/// The ids of the three SDES elements as negotiated, 0 for one that is not.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub(crate) struct SdesExtensionIds {
    pub(crate) mid: u8,
    pub(crate) rid: u8,
    pub(crate) rrid: u8,
}

impl SdesExtensionIds {
    fn ids(&self) -> [u8; 3] {
        [self.mid, self.rid, self.rrid]
    }
}

/// What one SSRC sent of the elements.
#[derive(Debug)]
struct SentSdes {
    /// The values of the elements (MID, RtpStreamId, RepairedRtpStreamId) as last sent.
    values: [Option<Bytes>; 3],
    /// The extended sequence number of the first packet that carried `values`.
    first: i64,
    /// The highest extended sequence number sent on the SSRC.
    highest: i64,
    /// A report block reported a packet at or past `first`.
    acknowledged: bool,
}

/// The extended form of `sequence_number`: the one nearest `reference` (RFC 3550 appendix
/// A.1's unwrapping, against what was sent).
fn extend(reference: i64, sequence_number: u16) -> i64 {
    reference + i64::from(sequence_number.wrapping_sub(reference as u16) as i16)
}

/// The send policy of the SDES header extensions, per SSRC.
#[derive(Debug, Default)]
pub(crate) struct SdesSendPolicy {
    every_packet: bool,
    streams: HashMap<SSRC, SentSdes>,
}

impl SdesSendPolicy {
    /// `every_packet`: `SettingEngineBuilder::with_sdes_header_extensions_on_every_packet`.
    pub(crate) fn new(every_packet: bool) -> Self {
        Self {
            every_packet,
            streams: HashMap::new(),
        }
    }

    /// An RTP packet on its way to the transport: its SDES elements are taken out when its
    /// SSRC's receiver has acknowledged the values they carry. Returns whether it took any.
    pub(crate) fn on_send(&mut self, header: &mut rtp::Header, ids: SdesExtensionIds) -> bool {
        if self.every_packet || !header.extension {
            return false;
        }
        let values = ids
            .ids()
            .map(|id| (id != 0).then(|| header.get_extension(id)).flatten());
        if values.iter().all(Option::is_none) {
            return false;
        }

        let ssrc = header.ssrc;
        let sequence_number = header.sequence_number;
        if !self.streams.contains_key(&ssrc) {
            if self.streams.len() >= MAX_SDES_SEND_STREAMS {
                return false;
            }
            let first = (1i64 << 32) + i64::from(sequence_number);
            self.streams.insert(
                ssrc,
                SentSdes {
                    values,
                    first,
                    highest: first,
                    acknowledged: false,
                },
            );
            return false;
        }
        let Some(stream) = self.streams.get_mut(&ssrc) else {
            return false;
        };
        let extended = extend(stream.highest, sequence_number);
        stream.highest = stream.highest.max(extended);
        if stream.values != values {
            // RFC 7941 section 4.2.4.3: new values go out until they are acknowledged.
            stream.values = values;
            stream.first = extended;
            stream.acknowledged = false;
            return false;
        }
        if !stream.acknowledged {
            return false;
        }
        let mut taken = false;
        for id in ids.ids() {
            if id != 0 && header.get_extension(id).is_some() {
                taken |= header.del_extension(id).is_ok();
            }
        }
        taken
    }

    /// A report block (RFC 3550 section 6.4) the peer sent about `ssrc`, with the extended
    /// highest sequence number it received.
    pub(crate) fn on_report_block(&mut self, ssrc: SSRC, extended_highest: u32) {
        let Some(stream) = self.streams.get_mut(&ssrc) else {
            return;
        };
        let reported = extend(stream.highest, extended_highest as u16);
        if reported >= stream.first {
            stream.acknowledged = true;
        }
    }

    /// A negotiation completed (an answer applied, either role): every stream starts over,
    /// as a new SSRC does (RFC 7941 section 4.2.4.1; RFC 9143 section 15: "at the start of the
    /// session"). A receiver may rebuild its demultiplexing at a new description and need the
    /// MID again: Firefox builds its MID filter only for a section in a BUNDLE group
    /// (`RTCRtpReceiver::UpdateTransport`, dom/media/webrtc/jsapi/RTCRtpReceiver.cpp at
    /// mozilla-firefox/firefox 924ba8a8, `HasBundleLevel`), so a section that joins a group by
    /// renegotiation starts with no MID binding for an SSRC it was receiving unbundled.
    pub(crate) fn restart(&mut self) {
        self.streams.clear();
    }

    /// Whether the receiver of `ssrc` has acknowledged its current values.
    #[cfg(test)]
    pub(crate) fn acknowledged(&self, ssrc: SSRC) -> bool {
        self.streams
            .get(&ssrc)
            .is_some_and(|stream| stream.acknowledged)
    }

    /// The report blocks of the SRs and RRs in a compound RTCP packet the peer sent.
    pub(crate) fn on_rtcp(&mut self, packets: &[Box<dyn rtcp::Packet>]) {
        if self.every_packet || self.streams.is_empty() {
            return;
        }
        for packet in packets {
            let any = packet.as_any();
            let reports = if let Some(sr) = any.downcast_ref::<rtcp::sender_report::SenderReport>()
            {
                &sr.reports
            } else if let Some(rr) = any.downcast_ref::<rtcp::receiver_report::ReceiverReport>() {
                &rr.reports
            } else {
                continue;
            };
            for report in reports {
                self.on_report_block(report.ssrc, report.last_sequence_number);
            }
        }
    }
}

#[cfg(test)]
#[path = "sdes_send_policy_test.rs"]
mod sdes_send_policy_test;