mpeg-ts 0.11.0

MPEG-2 Transport Stream framing (ITU-T H.222.0 / ISO/IEC 13818-1): TS packet, adaptation field, PCR, PSI section reassembly + packetisation, resync. no_std.
Documentation
//! The raw `descriptor()` loop of ISO/IEC 13818-1 §2.6 (Tables 2-42 through
//! 2-45): one tag/length framing walk for every consumer of a PMT `ES_info`
//! loop, a Program Stream Map loop or any other descriptor region.
//!
//! Zero-copy: the loop wraps the wire bytes and keeps every non-conformant
//! byte verbatim, so a loop whose descriptor bytes no known tag explains still
//! round-trips. Walk the TLV structure with [`RawDescriptorLoop::entries`], or
//! decode each entry through a typed registry (for example `dvb-si`'s) with
//! [`RawDescriptorLoop::parse_with`], where the caller passes the parser.

/// Bytes of a descriptor header: `descriptor_tag` (1) + `descriptor_length`
/// (1), ISO/IEC 13818-1 §2.6.
pub const DESCRIPTOR_HEADER_LEN: usize = 2;

/// A `descriptor()` entry: its `descriptor_tag`, the declared
/// `descriptor_length`, and the `descriptor_body` of that many bytes.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct DescriptorEntry<'a> {
    /// `descriptor_tag` (§2.6).
    pub tag: u8,
    /// `descriptor_body`, `descriptor_length` bytes verbatim.
    pub body: &'a [u8],
    /// The whole `descriptor()`: header and body, verbatim.
    pub raw: &'a [u8],
}

/// Frame the `descriptor()` that starts at `offset` in `bytes`: the single
/// definition of the §2.6 header walk. A header or body that runs past the end
/// of `bytes` is an `Err` carrying `offset`; an `offset` at or past the end has
/// no header to read and is `DescriptorHeaderTruncated` with `have == 0`.
pub fn frame_at(bytes: &[u8], offset: usize) -> crate::Result<DescriptorEntry<'_>> {
    let Some(rem) = bytes.get(offset..) else {
        return Err(crate::Error::DescriptorHeaderTruncated {
            offset,
            need: DESCRIPTOR_HEADER_LEN,
            have: 0,
        });
    };
    if rem.len() < DESCRIPTOR_HEADER_LEN {
        return Err(crate::Error::DescriptorHeaderTruncated {
            offset,
            need: DESCRIPTOR_HEADER_LEN,
            have: rem.len(),
        });
    }
    let tag = rem[0];
    let len = usize::from(rem[1]);
    let total = DESCRIPTOR_HEADER_LEN + len;
    if rem.len() < total {
        return Err(crate::Error::DescriptorBodyTruncated {
            offset,
            tag,
            declared: len,
            have: rem.len() - DESCRIPTOR_HEADER_LEN,
        });
    }
    Ok(DescriptorEntry {
        tag,
        body: &rem[DESCRIPTOR_HEADER_LEN..total],
        raw: &rem[..total],
    })
}

/// A raw `descriptor()` loop, borrowed from its section. Zero-copy: the bytes a
/// serializer writes back are [`RawDescriptorLoop::raw`], unchanged.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub struct RawDescriptorLoop<'a>(&'a [u8]);

impl<'a> RawDescriptorLoop<'a> {
    /// Wrap a raw descriptor loop (the `descriptor()` bytes only, no
    /// enclosing length field).
    #[must_use]
    pub const fn new(raw: &'a [u8]) -> Self {
        Self(raw)
    }

    /// The wire bytes of the loop, verbatim.
    #[must_use]
    pub const fn raw(&self) -> &'a [u8] {
        self.0
    }

    /// Walk the loop's `(tag, body)` pairs by the TLV structure only — never
    /// decoding a body. An entry whose `descriptor_length` runs past the end
    /// of the loop is reported as `Err` carrying the loop offset it starts
    /// at, and iteration stops there; the bytes stay available through
    /// [`raw`](Self::raw).
    pub fn entries(&self) -> DescriptorEntryIter<'a> {
        DescriptorEntryIter {
            bytes: self.0,
            pos: 0,
            fused: false,
        }
    }

    /// Walk the loop's `descriptor_tag` bytes by header only: an entry whose
    /// body runs past the end of the loop still yields its tag, and the walk
    /// ends where no header remains. For a presence scan that a malformed
    /// body must not hide.
    pub fn tags(&self) -> impl Iterator<Item = u8> + 'a {
        let bytes = self.0;
        let mut pos = 0usize;
        core::iter::from_fn(move || {
            let tag = *bytes.get(pos)?;
            pos = match bytes.get(pos + 1) {
                Some(&len) => pos + DESCRIPTOR_HEADER_LEN + usize::from(len),
                None => bytes.len(),
            };
            Some(tag)
        })
    }

    /// True when the loop is empty.
    #[must_use]
    pub fn is_empty(&self) -> bool {
        self.0.is_empty()
    }

    /// Byte length of the loop (a byte count, not an entry count).
    #[must_use]
    pub fn len(&self) -> usize {
        self.0.len()
    }

    /// Walk the loop through `parse`'s decoder, handing every entry exactly
    /// the bytes [`entries`](Self::entries) frames for it: `parse` receives
    /// one entry's `(tag, body)` and returns whatever the caller's typed
    /// representation of it is. Nothing is decoded here, so an unknown tag is
    /// the caller's decision (e.g. keep the body verbatim).
    ///
    /// A truncated entry ends the walk after its `Err` (the same rule
    /// [`entries`](Self::entries) uses), so the decoder never sees a partial
    /// body.
    pub fn parse_with<T>(
        &self,
        parse: impl FnMut(u8, &'a [u8]) -> T,
    ) -> ParseWith<'a, impl FnMut(u8, &'a [u8]) -> T, T> {
        ParseWith {
            inner: self.entries(),
            parse,
            out: core::marker::PhantomData,
        }
    }
}

impl<'a> From<&'a [u8]> for RawDescriptorLoop<'a> {
    fn from(raw: &'a [u8]) -> Self {
        Self(raw)
    }
}

impl core::ops::Deref for RawDescriptorLoop<'_> {
    /// Derefs to the raw wire bytes — `len()`/indexing are byte counts for
    /// serialization, not entry counts.
    type Target = [u8];
    fn deref(&self) -> &[u8] {
        self.0
    }
}

impl<'a> IntoIterator for &RawDescriptorLoop<'a> {
    type Item = crate::Result<DescriptorEntry<'a>>;
    type IntoIter = DescriptorEntryIter<'a>;
    fn into_iter(self) -> Self::IntoIter {
        self.entries()
    }
}

/// Iterator over a raw descriptor loop with the caller's decoder; see
/// [`RawDescriptorLoop::parse_with`].
pub struct ParseWith<'a, F, T> {
    inner: DescriptorEntryIter<'a>,
    parse: F,
    out: core::marker::PhantomData<fn(&'a [u8]) -> T>,
}

impl<'a, F, T> Iterator for ParseWith<'a, F, T>
where
    F: FnMut(u8, &'a [u8]) -> T,
{
    type Item = crate::Result<T>;

    fn next(&mut self) -> Option<Self::Item> {
        let entry = self.inner.next()?;
        Some(entry.map(|e| (self.parse)(e.tag, e.body)))
    }
}

/// Iterator over a raw descriptor loop; see [`RawDescriptorLoop::entries`].
#[derive(Debug, Clone)]
pub struct DescriptorEntryIter<'a> {
    bytes: &'a [u8],
    pos: usize,
    fused: bool,
}

impl<'a> Iterator for DescriptorEntryIter<'a> {
    type Item = crate::Result<DescriptorEntry<'a>>;

    fn next(&mut self) -> Option<Self::Item> {
        if self.fused || self.pos >= self.bytes.len() {
            return None;
        }
        let entry = frame_at(self.bytes, self.pos);
        match &entry {
            Ok(e) => self.pos += e.raw.len(),
            Err(_) => self.fused = true,
        }
        Some(entry)
    }
}

impl core::iter::FusedIterator for DescriptorEntryIter<'_> {}

#[cfg(test)]
mod tests {
    use alloc::vec::Vec;

    use super::*;

    #[test]
    fn an_empty_loop_has_no_entries() {
        let loop_ = RawDescriptorLoop::new(&[]);
        assert!(loop_.is_empty());
        assert_eq!(loop_.entries().count(), 0);
    }

    #[test]
    fn entries_carry_tag_and_body_verbatim() {
        // registration descriptor (0x05) then an unknown tag (0xC0).
        let raw = [0x05, 0x04, b'H', b'D', b'M', b'V', 0xC0, 0x01, 0x7F];
        let loop_ = RawDescriptorLoop::new(&raw);
        let entries: Vec<_> = loop_.entries().map(|e| e.unwrap()).collect();
        assert_eq!(entries.len(), 2);
        assert_eq!(entries[0].tag, 0x05);
        assert_eq!(entries[0].body, b"HDMV");
        assert_eq!(entries[1].tag, 0xC0);
        assert_eq!(entries[1].body, &[0x7F]);
        assert_eq!(loop_.raw(), &raw[..]);
    }

    #[test]
    fn a_truncated_header_is_reported_with_its_offset() {
        let raw = [0x05, 0x01, 0x00, 0x06];
        let err = RawDescriptorLoop::new(&raw)
            .entries()
            .last()
            .unwrap()
            .unwrap_err();
        assert_eq!(
            err,
            crate::Error::DescriptorHeaderTruncated {
                offset: 3,
                need: DESCRIPTOR_HEADER_LEN,
                have: 1,
            }
        );
    }

    #[test]
    fn a_body_running_past_the_loop_is_reported_not_shortened() {
        let raw = [0x05, 0x06, b'H', b'D'];
        let err = RawDescriptorLoop::new(&raw)
            .entries()
            .last()
            .unwrap()
            .unwrap_err();
        assert_eq!(
            err,
            crate::Error::DescriptorBodyTruncated {
                offset: 0,
                tag: 0x05,
                declared: 6,
                have: 2,
            }
        );
    }

    #[test]
    fn a_trailing_zero_length_descriptor_is_an_entry() {
        let raw = [0x05u8, 0x00];
        let entries: Vec<_> = RawDescriptorLoop::new(&raw)
            .entries()
            .map(|e| e.unwrap())
            .collect();
        assert_eq!(entries.len(), 1);
        assert_eq!(entries[0].tag, 0x05);
        assert!(entries[0].body.is_empty());
    }

    /// A lone trailing tag byte is a truncated header, not a descriptor:
    /// `entries` says so, while a header whose body overruns the loop still
    /// names its tag (#4458).
    #[test]
    fn entries_tell_a_lone_tag_byte_from_a_truncated_body() {
        let lone = [0x05u8, 0x00, 0x6A];
        let last = RawDescriptorLoop::new(&lone).entries().last().unwrap();
        assert!(matches!(
            last,
            Err(crate::Error::DescriptorHeaderTruncated { offset: 2, .. })
        ));
        let overrun = [0x05u8, 0x00, 0x6A, 0x04, 0x00];
        let last = RawDescriptorLoop::new(&overrun).entries().last().unwrap();
        assert!(matches!(
            last,
            Err(crate::Error::DescriptorBodyTruncated { tag: 0x6A, .. })
        ));
    }

    #[test]
    fn tags_report_a_truncated_entry_and_stop_without_a_header() {
        let raw = [0x05u8, 0x01, 0xAA, 0x6A, 0x09, 0x01];
        assert_eq!(
            RawDescriptorLoop::new(&raw).tags().collect::<Vec<_>>(),
            [0x05, 0x6A]
        );
        let lone_tag = [0x05u8, 0x00, 0x7B];
        assert_eq!(
            RawDescriptorLoop::new(&lone_tag).tags().collect::<Vec<_>>(),
            [0x05, 0x7B]
        );
        assert_eq!(RawDescriptorLoop::new(&[]).tags().count(), 0);
    }

    #[test]
    fn from_bytes_keeps_the_loop_and_is_empty_tracks_it() {
        let raw = [0x01u8, 0x00];
        let loop_ = RawDescriptorLoop::from(&raw[..]);
        assert!(!loop_.is_empty());
        assert_eq!(loop_.raw(), &raw[..]);
        assert_eq!(loop_.len(), 2);
        assert_eq!(loop_.entries().count(), 1);
        assert!(RawDescriptorLoop::from(&[][..]).is_empty());
    }

    #[test]
    fn a_body_truncated_right_after_its_header_reports_no_body_bytes() {
        let raw = [0x05u8, 0x03];
        let err = RawDescriptorLoop::new(&raw)
            .entries()
            .last()
            .unwrap()
            .unwrap_err();
        assert_eq!(
            err,
            crate::Error::DescriptorBodyTruncated {
                offset: 0,
                tag: 0x05,
                declared: 3,
                have: 0,
            }
        );
    }

    #[test]
    fn an_offset_past_the_end_is_a_truncated_header_not_a_panic() {
        for (len, offset) in [(0usize, 0usize), (0, 1), (3, 4), (3, usize::MAX)] {
            let bytes = alloc::vec![0x05u8; len];
            assert_eq!(
                frame_at(&bytes, offset).unwrap_err(),
                crate::Error::DescriptorHeaderTruncated {
                    offset,
                    need: DESCRIPTOR_HEADER_LEN,
                    have: 0,
                }
            );
        }
    }

    #[test]
    fn parse_with_hands_each_entry_its_own_classification() {
        // registration descriptor (tag 0x05, "HDMV") then an unknown tag.
        let raw = [0x05u8, 0x04, b'H', b'D', b'M', b'V', 0xC0, 0x01, 0x7F];
        let kinds: Vec<_> = RawDescriptorLoop::new(&raw)
            .parse_with(|tag, _| match tag {
                0x05 => "registration",
                0xC0 => "unknown",
                _ => "other",
            })
            .map(|k| k.expect("framed loop"))
            .collect();
        assert_eq!(kinds, ["registration", "unknown"]);

        let bodies: Vec<&[u8]> = RawDescriptorLoop::new(&raw)
            .parse_with(|_, body| body)
            .map(|b| b.expect("framed loop"))
            .collect();
        assert_eq!(bodies, [&b"HDMV"[..], &[0x7F][..]]);
    }
}