rtci-interceptor 0.5.0

Sans-I/O RTP/RTCP interceptor pipeline for WebRTC: RTCP reports, NACK, TWCC, congestion control, pacing, FEC
Documentation
//! The temporal layer of an outgoing video packet, read from its payload, for FEC that protects
//! base-layer frames only.
//!
//! RFC 8854 section 8: "When using FEC with layered codecs, e.g., [RFC6386], where only base
//! layer frames are critical to the decoding of future frames, implementations SHOULD only apply
//! FEC to these base layer frames." A frame of a temporal layer above the base is referenced by no
//! frame of a lower layer, so losing it costs that frame and the frames of its own layer up to
//! the next base-layer frame, never the base layer.
//!
//! The layer is the temporal layer index each payload format carries:
//!
//! * VP8, RFC 7741 section 4.2: `TID` when the `T` bit is set;
//! * VP9, RFC 9628 section 4.2: `TID` of the layer indices when the `L` bit is set;
//! * H.265, RFC 7798 section 1.1.4: `TID` of the payload header, `TemporalId + 1`;
//! * AV1, the AV1 RTP specification sections 4.4 and 4.5: the `temporal_id` of the OBU extension header of
//!   the packet's first OBU element (no extension header: layer 0); a packet whose first element
//!   continues an OBU of the packet before (`Z`) takes that packet's layer.
//!
//! Any other format, or a packet whose descriptor names no layer, counts as base layer: it is
//! protected.

/// The payload formats whose temporal layer is read.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum LayeredFormat {
    Vp8,
    Vp9,
    H265,
    Av1,
}

/// Reads the temporal layer of one stream's packets.
#[derive(Debug, Clone, Default)]
pub(crate) struct LayerReader {
    format: Option<LayeredFormat>,
    /// AV1: the layer of the newest packet, for one that continues its OBU.
    av1_layer: u8,
}

impl LayerReader {
    /// A reader for a stream of `mime_type` (`video/VP8`, ...).
    pub(crate) fn for_mime_type(mime_type: &str) -> Self {
        let subtype = mime_type
            .rsplit_once('/')
            .map_or(mime_type, |(_, subtype)| subtype);
        let format = if subtype.eq_ignore_ascii_case("vp8") {
            Some(LayeredFormat::Vp8)
        } else if subtype.eq_ignore_ascii_case("vp9") {
            Some(LayeredFormat::Vp9)
        } else if subtype.eq_ignore_ascii_case("h265") {
            Some(LayeredFormat::H265)
        } else if subtype.eq_ignore_ascii_case("av1") {
            Some(LayeredFormat::Av1)
        } else {
            None
        };
        Self {
            format,
            av1_layer: 0,
        }
    }

    /// The temporal layer `payload` belongs to, when its format names one.
    pub(crate) fn temporal_layer(&mut self, payload: &[u8]) -> Option<u8> {
        match self.format? {
            LayeredFormat::Vp8 => vp8_temporal_layer(payload),
            LayeredFormat::Vp9 => vp9_temporal_layer(payload),
            LayeredFormat::H265 => h265_temporal_layer(payload),
            LayeredFormat::Av1 => {
                let layer = av1_temporal_layer(payload, self.av1_layer)?;
                self.av1_layer = layer;
                Some(layer)
            }
        }
    }

    /// Whether `payload` belongs to a temporal layer above the base.
    pub(crate) fn is_enhancement(&mut self, payload: &[u8]) -> bool {
        self.temporal_layer(payload).is_some_and(|layer| layer > 0)
    }
}

/// RFC 7741 section 4.2: `X|R|N|S|R|PID`, then (X) `I|L|T|K|RSV`, then (I) a 7- or 15-bit
/// picture ID, (L) `TL0PICIDX`, (T or K) `TID|Y|KEYIDX`.
fn vp8_temporal_layer(payload: &[u8]) -> Option<u8> {
    let first = *payload.first()?;
    if first & 0x80 == 0 {
        return None;
    }
    let extension = *payload.get(1)?;
    let mut at = 2;
    if extension & 0x80 != 0 {
        at += if *payload.get(at)? & 0x80 != 0 { 2 } else { 1 };
    }
    if extension & 0x40 != 0 {
        at += 1;
    }
    if extension & 0x20 != 0 {
        return Some(*payload.get(at)? >> 6);
    }
    None
}

/// RFC 9628 section 4.2: `I|P|L|F|B|E|V|Z`, then (I) a 7- or 15-bit picture ID, then (L)
/// `TID|U|SID|D`.
fn vp9_temporal_layer(payload: &[u8]) -> Option<u8> {
    let first = *payload.first()?;
    let mut at = 1;
    if first & 0x80 != 0 {
        at += if *payload.get(at)? & 0x80 != 0 { 2 } else { 1 };
    }
    if first & 0x20 != 0 {
        return Some(*payload.get(at)? >> 5);
    }
    None
}

/// RFC 7798 section 1.1.4: `F|Type|LayerId|TID`, `TID` the temporal ID plus one (zero is not
/// allowed).
fn h265_temporal_layer(payload: &[u8]) -> Option<u8> {
    (*payload.get(1)? & 0x07).checked_sub(1)
}

/// The AV1 RTP specification sections 4.4 and 4.5: the aggregation header `Z|Y|W|N|-`, then the
/// OBU elements, each but the last of `W` (all when `W` is 0) preceded by its LEB128 length; an OBU
/// header `F|type|X|S|R`, then (X) `temporal_id|spatial_id|reserved`.
fn av1_temporal_layer(payload: &[u8], previous: u8) -> Option<u8> {
    let aggregation = *payload.first()?;
    if aggregation & 0x80 != 0 {
        return Some(previous);
    }
    let elements = (aggregation >> 4) & 0x03;
    let mut at = 1;
    if elements != 1 {
        // The first element's length: LEB128, at most eight octets.
        let mut octets = 0;
        loop {
            let octet = *payload.get(at)?;
            at += 1;
            octets += 1;
            if octet & 0x80 == 0 {
                break;
            }
            if octets == 8 {
                return None;
            }
        }
    }
    let header = *payload.get(at)?;
    if header & 0x04 == 0 {
        return Some(0);
    }
    Some(*payload.get(at + 1)? >> 5)
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn vp8_reads_the_tid_when_the_t_bit_is_set() {
        let mut reader = LayerReader::for_mime_type("video/VP8");
        // X, then I|L|T, a 15-bit picture ID, TL0PICIDX, TID 2.
        assert_eq!(
            reader.temporal_layer(&[0x90, 0xE0, 0x80, 0x01, 0x07, 0x80, 0xAA]),
            Some(2)
        );
        // X, then T only: TID 0.
        assert_eq!(reader.temporal_layer(&[0x90, 0x20, 0x20, 0xAA]), Some(0));
        // No extension: no layer.
        assert_eq!(reader.temporal_layer(&[0x10, 0xAA]), None);
        // K without T: the TID field is not used.
        assert_eq!(reader.temporal_layer(&[0x90, 0x10, 0xC0, 0xAA]), None);
        assert!(reader.is_enhancement(&[0x90, 0x20, 0x40, 0xAA]));
        assert!(!reader.is_enhancement(&[0x90, 0x20, 0x00, 0xAA]));
    }

    #[test]
    fn vp9_reads_the_tid_of_the_layer_indices() {
        let mut reader = LayerReader::for_mime_type("video/vp9");
        // I|L, a 7-bit picture ID, TID 1 SID 0.
        assert_eq!(reader.temporal_layer(&[0xA0, 0x05, 0x20, 0xAA]), Some(1));
        // L only, TID 3.
        assert_eq!(reader.temporal_layer(&[0x20, 0x60, 0xAA]), Some(3));
        // No layer indices.
        assert_eq!(reader.temporal_layer(&[0x80, 0x05, 0xAA]), None);
    }

    #[test]
    fn h265_reads_the_tid_of_the_payload_header() {
        let mut reader = LayerReader::for_mime_type("video/H265");
        // Type 1 (TRAIL_R), LayerId 0, TID 1 (TemporalId 0).
        assert_eq!(reader.temporal_layer(&[0x02, 0x01, 0xAA]), Some(0));
        // TID 3: TemporalId 2.
        assert_eq!(reader.temporal_layer(&[0x02, 0x03, 0xAA]), Some(2));
        // TID 0 is not allowed: no layer.
        assert_eq!(reader.temporal_layer(&[0x02, 0x00, 0xAA]), None);
    }

    #[test]
    fn av1_reads_the_first_obu_extension_and_a_continuation_keeps_it() {
        let mut reader = LayerReader::for_mime_type("video/AV1");
        // W=1: the one element has no length; OBU header with X, extension temporal_id 2.
        assert_eq!(reader.temporal_layer(&[0x10, 0x34, 0x40, 0xAA]), Some(2));
        // Z: continues the OBU of the packet before.
        assert_eq!(reader.temporal_layer(&[0x80, 0xAA]), Some(2));
        // W=0: the element's length first; no extension: layer 0.
        assert_eq!(reader.temporal_layer(&[0x00, 0x02, 0x30, 0xAA]), Some(0));
        assert_eq!(reader.temporal_layer(&[0x80, 0xAA]), Some(0));
        // W=2: a length first, then the OBU header with X, temporal_id 1.
        assert_eq!(
            reader.temporal_layer(&[0x20, 0x03, 0x34, 0x20, 0xAA]),
            Some(1)
        );
    }

    #[test]
    fn other_formats_and_short_payloads_name_no_layer() {
        let mut reader = LayerReader::for_mime_type("video/H264");
        assert_eq!(reader.temporal_layer(&[0x90, 0x20, 0x40]), None);
        let mut reader = LayerReader::for_mime_type("video/VP8");
        assert_eq!(reader.temporal_layer(&[0x90, 0xE0]), None);
        assert_eq!(reader.temporal_layer(&[]), None);
    }
}