sew-str0m 0.25.6

Fork of str0m (https://github.com/algesten/str0m) with Sew's patches. WebRTC library in Sans-IO style
Documentation
// Changed by Alakazam Labs for sew-str0m; the fork's patches are listed in its README.
use std::time::Duration;
use std::time::Instant;

use crate::io::DATAGRAM_MAX_PACKET_SIZE;
use crate::rtp_::SeqNo;

use crate::rtp_::RtpHeader;

use super::RtpPacket;
use super::rtx_cache_buf::EvictingBuffer;

const RTX_CACHE_SIZE_QUANTIZER: usize = 25;
const RTX_CACHE_QUANTIZE_SLOTS: usize = DATAGRAM_MAX_PACKET_SIZE / RTX_CACHE_SIZE_QUANTIZER;

/// Per-packet NACK bookkeeping kept next to each cached packet (see [`NackState`]).
#[derive(Debug)]
struct CachedPacket {
    packet: RtpPacket,
    nack: NackState,
    /// The unprotected bytes of the packet's first transmission, kept when the packet may be
    /// resent on its original SSRC and sequence number (see [`SentWire`]).
    wire: Option<SentWire>,
}

/// The exact unprotected bytes (RTP header and payload) of a packet's first transmission.
///
/// A resend on the original SSRC and sequence number repeats the original packet exactly.
#[derive(Debug, Clone, PartialEq, Eq)]
pub(crate) struct SentWire {
    /// RTP header followed by the payload.
    pub bytes: Box<[u8]>,
    /// The header as written at the start of `bytes` (`header_len` set).
    pub header: RtpHeader,
}

/// How often a cached packet has been resent in answer to NACKs, and when.
#[derive(Debug, Clone, Copy)]
pub(crate) struct NackState {
    /// Resends answered for this packet so far.
    pub resends: u8,
    /// When the packet was last resent (or first sent), for the minimum resend interval.
    pub last_at: Instant,
    /// The packet's PT has no RTX PT: it can only be resent in-band on the main SSRC.
    pub in_band: bool,
}

#[derive(Debug)]
pub(crate) struct RtxCache {
    // Data, new additions here probably need to be cleared in [`clear`].
    packet_by_seq_no: EvictingBuffer<CachedPacket>,

    // Technically we want [Option<SeqNo>; X] to indicate the absence of
    // a SeqNo. However We can half the storage space by using the sentinel
    // values SeqNo::MAX to indicate None
    seq_no_by_quantized_size: [SeqNo; RTX_CACHE_QUANTIZE_SLOTS],
}

impl RtxCache {
    pub fn new(max_packet_count: usize, max_packet_age: Duration) -> Self {
        Self {
            packet_by_seq_no: EvictingBuffer::new(10, max_packet_age, max_packet_count),
            seq_no_by_quantized_size: [SeqNo::MAX; RTX_CACHE_QUANTIZE_SLOTS],
        }
    }

    /// Caches a sent packet. An `in_band` packet (its PT has no RTX PT) can only be resent
    /// in-band, so it is never offered as a spurious (RTX) padding resend.
    #[cfg(test)]
    pub fn cache_sent_packet(&mut self, packet: RtpPacket, now: Instant, in_band: bool) {
        self.cache_sent_packet_with_wire(packet, now, in_band, None);
    }

    /// Like [`RtxCache::cache_sent_packet`], also keeping the bytes the packet was first sent
    /// with, which a resend on the original SSRC and sequence number repeats verbatim.
    pub fn cache_sent_packet_with_wire(
        &mut self,
        packet: RtpPacket,
        now: Instant,
        in_band: bool,
        wire: Option<SentWire>,
    ) {
        assert!(packet.nackable);
        let seq_no = packet.seq_no;
        let quantized_size = packet.payload.len() / RTX_CACHE_SIZE_QUANTIZER;
        let nack = NackState {
            resends: 0,
            last_at: now,
            in_band,
        };
        self.packet_by_seq_no
            .push(*seq_no, now, CachedPacket { packet, nack, wire });
        if !in_band {
            self.seq_no_by_quantized_size[quantized_size] = seq_no;
        }
        self.remove_old_packets(now);
    }

    pub fn last_cached_seq_no(&self) -> Option<SeqNo> {
        Some(self.packet_by_seq_no.last_position()?.into())
    }

    pub fn get_cached_packet_by_seq_no(&mut self, seq_no: SeqNo) -> Option<&mut RtpPacket> {
        self.packet_by_seq_no
            .get_mut(*seq_no)
            .map(|c| &mut c.packet)
    }

    /// The bytes a cached packet was first sent with, if they were kept.
    pub fn sent_wire(&self, seq_no: SeqNo) -> Option<&SentWire> {
        self.packet_by_seq_no.get(*seq_no)?.wire.as_ref()
    }

    /// The NACK bookkeeping of a cached packet, with its payload size.
    pub fn nack_state_mut(&mut self, seq_no: SeqNo) -> Option<(&mut NackState, usize)> {
        self.packet_by_seq_no
            .get_mut(*seq_no)
            .map(|c| (&mut c.nack, c.packet.payload.len()))
    }

    pub fn get_cached_packet_smaller_than(&mut self, max_size: usize) -> Option<&mut RtpPacket> {
        let quantized_size = max_size / RTX_CACHE_SIZE_QUANTIZER;

        let seq_no = self.seq_no_by_quantized_size[..quantized_size]
            .iter()
            .rev()
            .filter(|seq_no| !seq_no.is_max())
            .find(|seq_no| self.packet_by_seq_no.contains(***seq_no))?;

        self.get_cached_packet_by_seq_no(*seq_no)
    }

    fn remove_old_packets(&mut self, now: Instant) {
        self.packet_by_seq_no.maybe_evict(now);
    }

    pub(crate) fn last_packet(&self) -> Option<&[u8]> {
        let cached = self.packet_by_seq_no.last()?;
        Some(cached.packet.payload.as_ref())
    }

    pub(crate) fn clear(&mut self) {
        self.packet_by_seq_no.clear();
        self.seq_no_by_quantized_size = [SeqNo::MAX; RTX_CACHE_QUANTIZE_SLOTS];
    }
}

#[cfg(test)]
mod test {
    use crate::rtp_::MediaTime;
    use crate::rtp_::RtpHeader;

    use super::*;

    fn after(now: Instant, millis: u64) -> Instant {
        now + Duration::from_millis(millis)
    }

    fn packet(now: Instant, seq_no: u64, millis: u64) -> RtpPacket {
        RtpPacket {
            header: RtpHeader::default(),
            seq_no: seq_no.into(),
            time: MediaTime::from_90khz(0),
            payload: millis.to_be_bytes().into(),
            vp8_patch: None,
            timestamp: after(now, millis),
            last_sender_info: None,
            nackable: true,
        }
    }

    #[test]
    fn rtx_cache_0_sized() {
        let now = Instant::now();
        let mut rtx_cache = RtxCache::new(0, Duration::from_secs(3));
        rtx_cache.cache_sent_packet(packet(now, 1, 10), after(now, 10), false);
        assert_eq!(
            Some(&mut packet(now, 1, 10)),
            rtx_cache.get_cached_packet_by_seq_no(1.into())
        );
        assert_eq!(
            Some(&mut packet(now, 1, 10)),
            rtx_cache.get_cached_packet_smaller_than(1000)
        );
    }

    #[test]
    fn rtx_cache_0_duration() {
        let now = Instant::now();
        let mut rtx_cache = RtxCache::new(10, Duration::from_secs(0));
        rtx_cache.cache_sent_packet(packet(now, 1, 10), after(now, 10), false);
        assert_eq!(None, rtx_cache.get_cached_packet_by_seq_no(1.into()));
        assert_eq!(None, rtx_cache.get_cached_packet_smaller_than(1000));
    }

    #[test]
    fn rtx_cache_1_sized() {
        let now = Instant::now();
        let mut rtx_cache = RtxCache::new(1, Duration::from_secs(3));
        rtx_cache.cache_sent_packet(packet(now, 1, 10), after(now, 10), false);
        assert_eq!(
            Some(&mut packet(now, 1, 10)),
            rtx_cache.get_cached_packet_by_seq_no(1.into())
        );
        assert_eq!(
            Some(&mut packet(now, 1, 10)),
            rtx_cache.get_cached_packet_smaller_than(1000)
        );
        assert_eq!(
            Some(&mut packet(now, 1, 10)),
            rtx_cache.get_cached_packet_smaller_than(25)
        );
        assert_eq!(None, rtx_cache.get_cached_packet_smaller_than(24));
        rtx_cache.cache_sent_packet(packet(now, 2, 20), after(now, 20), false);
        assert_eq!(
            Some(&mut packet(now, 2, 20)),
            rtx_cache.get_cached_packet_by_seq_no(2.into())
        );
    }

    #[test]
    fn rtx_cache_100_sized_backwards() {
        let now = Instant::now();
        let mut rtx_cache = RtxCache::new(100, Duration::from_secs(3));

        for i in 1..=200 {
            let seq_no = 201 - i;
            let pkt = packet(now, seq_no, (201 - i) * 10);
            let now = after(now, i * 10);
            rtx_cache.cache_sent_packet(pkt, now, false);
        }

        assert_eq!(
            Some(&mut packet(now, 200, 2000)),
            rtx_cache.get_cached_packet_by_seq_no(200.into())
        );
        assert_eq!(None, rtx_cache.get_cached_packet_by_seq_no(100.into()));
        assert_eq!(None, rtx_cache.get_cached_packet_by_seq_no(101.into()));
    }

    #[test]
    fn rtx_cache_eviction() {
        let now = Instant::now();
        // Cache can take all entries
        let mut rtx_cache = RtxCache::new(400, Duration::from_secs(1));
        for i in 1..=200 {
            let seq_no = i;
            let pkt = packet(now, seq_no, i * 10);
            let now = after(now, i * 10);
            rtx_cache.cache_sent_packet(pkt, now, false);
        }

        assert_eq!(None, rtx_cache.get_cached_packet_by_seq_no(99.into()));

        assert_eq!(
            Some(&mut packet(now, 100, 1000)),
            rtx_cache.get_cached_packet_by_seq_no(100.into())
        );
        assert_eq!(
            Some(&mut packet(now, 200, 2000)),
            rtx_cache.get_cached_packet_by_seq_no(200.into())
        );
    }
}