Skip to main content

mpeg_ts/
descriptor_loop.rs

1//! The raw `descriptor()` loop of ISO/IEC 13818-1 §2.6 (Tables 2-42 through
2//! 2-45): one tag/length framing walk for every consumer of a PMT `ES_info`
3//! loop, a Program Stream Map loop or any other descriptor region.
4//!
5//! Zero-copy: the loop wraps the wire bytes and keeps every non-conformant
6//! byte verbatim, so a loop whose descriptor bytes no known tag explains still
7//! round-trips. Walk the TLV structure with [`RawDescriptorLoop::entries`], or
8//! decode each entry through a typed registry (for example `dvb-si`'s) with
9//! [`RawDescriptorLoop::parse_with`], where the caller passes the parser.
10
11/// Bytes of a descriptor header: `descriptor_tag` (1) + `descriptor_length`
12/// (1), ISO/IEC 13818-1 §2.6.
13pub const DESCRIPTOR_HEADER_LEN: usize = 2;
14
15/// A `descriptor()` entry: its `descriptor_tag`, the declared
16/// `descriptor_length`, and the `descriptor_body` of that many bytes.
17#[derive(Debug, Clone, Copy, PartialEq, Eq)]
18pub struct DescriptorEntry<'a> {
19    /// `descriptor_tag` (§2.6).
20    pub tag: u8,
21    /// `descriptor_body`, `descriptor_length` bytes verbatim.
22    pub body: &'a [u8],
23    /// The whole `descriptor()`: header and body, verbatim.
24    pub raw: &'a [u8],
25}
26
27/// Frame the `descriptor()` that starts at `offset` in `bytes`: the single
28/// definition of the §2.6 header walk. A header or body that runs past the end
29/// of `bytes` is an `Err` carrying `offset`; an `offset` at or past the end has
30/// no header to read and is `DescriptorHeaderTruncated` with `have == 0`.
31pub fn frame_at(bytes: &[u8], offset: usize) -> crate::Result<DescriptorEntry<'_>> {
32    let Some(rem) = bytes.get(offset..) else {
33        return Err(crate::Error::DescriptorHeaderTruncated {
34            offset,
35            need: DESCRIPTOR_HEADER_LEN,
36            have: 0,
37        });
38    };
39    if rem.len() < DESCRIPTOR_HEADER_LEN {
40        return Err(crate::Error::DescriptorHeaderTruncated {
41            offset,
42            need: DESCRIPTOR_HEADER_LEN,
43            have: rem.len(),
44        });
45    }
46    let tag = rem[0];
47    let len = usize::from(rem[1]);
48    let total = DESCRIPTOR_HEADER_LEN + len;
49    if rem.len() < total {
50        return Err(crate::Error::DescriptorBodyTruncated {
51            offset,
52            tag,
53            declared: len,
54            have: rem.len() - DESCRIPTOR_HEADER_LEN,
55        });
56    }
57    Ok(DescriptorEntry {
58        tag,
59        body: &rem[DESCRIPTOR_HEADER_LEN..total],
60        raw: &rem[..total],
61    })
62}
63
64/// A raw `descriptor()` loop, borrowed from its section. Zero-copy: the bytes a
65/// serializer writes back are [`RawDescriptorLoop::raw`], unchanged.
66#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
67pub struct RawDescriptorLoop<'a>(&'a [u8]);
68
69impl<'a> RawDescriptorLoop<'a> {
70    /// Wrap a raw descriptor loop (the `descriptor()` bytes only, no
71    /// enclosing length field).
72    #[must_use]
73    pub const fn new(raw: &'a [u8]) -> Self {
74        Self(raw)
75    }
76
77    /// The wire bytes of the loop, verbatim.
78    #[must_use]
79    pub const fn raw(&self) -> &'a [u8] {
80        self.0
81    }
82
83    /// Walk the loop's `(tag, body)` pairs by the TLV structure only — never
84    /// decoding a body. An entry whose `descriptor_length` runs past the end
85    /// of the loop is reported as `Err` carrying the loop offset it starts
86    /// at, and iteration stops there; the bytes stay available through
87    /// [`raw`](Self::raw).
88    pub fn entries(&self) -> DescriptorEntryIter<'a> {
89        DescriptorEntryIter {
90            bytes: self.0,
91            pos: 0,
92            fused: false,
93        }
94    }
95
96    /// Walk the loop's `descriptor_tag` bytes by header only: an entry whose
97    /// body runs past the end of the loop still yields its tag, and the walk
98    /// ends where no header remains. For a presence scan that a malformed
99    /// body must not hide.
100    pub fn tags(&self) -> impl Iterator<Item = u8> + 'a {
101        let bytes = self.0;
102        let mut pos = 0usize;
103        core::iter::from_fn(move || {
104            let tag = *bytes.get(pos)?;
105            pos = match bytes.get(pos + 1) {
106                Some(&len) => pos + DESCRIPTOR_HEADER_LEN + usize::from(len),
107                None => bytes.len(),
108            };
109            Some(tag)
110        })
111    }
112
113    /// True when the loop is empty.
114    #[must_use]
115    pub fn is_empty(&self) -> bool {
116        self.0.is_empty()
117    }
118
119    /// Byte length of the loop (a byte count, not an entry count).
120    #[must_use]
121    pub fn len(&self) -> usize {
122        self.0.len()
123    }
124
125    /// Walk the loop through `parse`'s decoder, handing every entry exactly
126    /// the bytes [`entries`](Self::entries) frames for it: `parse` receives
127    /// one entry's `(tag, body)` and returns whatever the caller's typed
128    /// representation of it is. Nothing is decoded here, so an unknown tag is
129    /// the caller's decision (e.g. keep the body verbatim).
130    ///
131    /// A truncated entry ends the walk after its `Err` (the same rule
132    /// [`entries`](Self::entries) uses), so the decoder never sees a partial
133    /// body.
134    pub fn parse_with<T>(
135        &self,
136        parse: impl FnMut(u8, &'a [u8]) -> T,
137    ) -> ParseWith<'a, impl FnMut(u8, &'a [u8]) -> T, T> {
138        ParseWith {
139            inner: self.entries(),
140            parse,
141            out: core::marker::PhantomData,
142        }
143    }
144}
145
146impl<'a> From<&'a [u8]> for RawDescriptorLoop<'a> {
147    fn from(raw: &'a [u8]) -> Self {
148        Self(raw)
149    }
150}
151
152impl core::ops::Deref for RawDescriptorLoop<'_> {
153    /// Derefs to the raw wire bytes — `len()`/indexing are byte counts for
154    /// serialization, not entry counts.
155    type Target = [u8];
156    fn deref(&self) -> &[u8] {
157        self.0
158    }
159}
160
161impl<'a> IntoIterator for &RawDescriptorLoop<'a> {
162    type Item = crate::Result<DescriptorEntry<'a>>;
163    type IntoIter = DescriptorEntryIter<'a>;
164    fn into_iter(self) -> Self::IntoIter {
165        self.entries()
166    }
167}
168
169/// Iterator over a raw descriptor loop with the caller's decoder; see
170/// [`RawDescriptorLoop::parse_with`].
171pub struct ParseWith<'a, F, T> {
172    inner: DescriptorEntryIter<'a>,
173    parse: F,
174    out: core::marker::PhantomData<fn(&'a [u8]) -> T>,
175}
176
177impl<'a, F, T> Iterator for ParseWith<'a, F, T>
178where
179    F: FnMut(u8, &'a [u8]) -> T,
180{
181    type Item = crate::Result<T>;
182
183    fn next(&mut self) -> Option<Self::Item> {
184        let entry = self.inner.next()?;
185        Some(entry.map(|e| (self.parse)(e.tag, e.body)))
186    }
187}
188
189/// Iterator over a raw descriptor loop; see [`RawDescriptorLoop::entries`].
190#[derive(Debug, Clone)]
191pub struct DescriptorEntryIter<'a> {
192    bytes: &'a [u8],
193    pos: usize,
194    fused: bool,
195}
196
197impl<'a> Iterator for DescriptorEntryIter<'a> {
198    type Item = crate::Result<DescriptorEntry<'a>>;
199
200    fn next(&mut self) -> Option<Self::Item> {
201        if self.fused || self.pos >= self.bytes.len() {
202            return None;
203        }
204        let entry = frame_at(self.bytes, self.pos);
205        match &entry {
206            Ok(e) => self.pos += e.raw.len(),
207            Err(_) => self.fused = true,
208        }
209        Some(entry)
210    }
211}
212
213impl core::iter::FusedIterator for DescriptorEntryIter<'_> {}
214
215#[cfg(test)]
216mod tests {
217    use alloc::vec::Vec;
218
219    use super::*;
220
221    #[test]
222    fn an_empty_loop_has_no_entries() {
223        let loop_ = RawDescriptorLoop::new(&[]);
224        assert!(loop_.is_empty());
225        assert_eq!(loop_.entries().count(), 0);
226    }
227
228    #[test]
229    fn entries_carry_tag_and_body_verbatim() {
230        // registration descriptor (0x05) then an unknown tag (0xC0).
231        let raw = [0x05, 0x04, b'H', b'D', b'M', b'V', 0xC0, 0x01, 0x7F];
232        let loop_ = RawDescriptorLoop::new(&raw);
233        let entries: Vec<_> = loop_.entries().map(|e| e.unwrap()).collect();
234        assert_eq!(entries.len(), 2);
235        assert_eq!(entries[0].tag, 0x05);
236        assert_eq!(entries[0].body, b"HDMV");
237        assert_eq!(entries[1].tag, 0xC0);
238        assert_eq!(entries[1].body, &[0x7F]);
239        assert_eq!(loop_.raw(), &raw[..]);
240    }
241
242    #[test]
243    fn a_truncated_header_is_reported_with_its_offset() {
244        let raw = [0x05, 0x01, 0x00, 0x06];
245        let err = RawDescriptorLoop::new(&raw)
246            .entries()
247            .last()
248            .unwrap()
249            .unwrap_err();
250        assert_eq!(
251            err,
252            crate::Error::DescriptorHeaderTruncated {
253                offset: 3,
254                need: DESCRIPTOR_HEADER_LEN,
255                have: 1,
256            }
257        );
258    }
259
260    #[test]
261    fn a_body_running_past_the_loop_is_reported_not_shortened() {
262        let raw = [0x05, 0x06, b'H', b'D'];
263        let err = RawDescriptorLoop::new(&raw)
264            .entries()
265            .last()
266            .unwrap()
267            .unwrap_err();
268        assert_eq!(
269            err,
270            crate::Error::DescriptorBodyTruncated {
271                offset: 0,
272                tag: 0x05,
273                declared: 6,
274                have: 2,
275            }
276        );
277    }
278
279    #[test]
280    fn a_trailing_zero_length_descriptor_is_an_entry() {
281        let raw = [0x05u8, 0x00];
282        let entries: Vec<_> = RawDescriptorLoop::new(&raw)
283            .entries()
284            .map(|e| e.unwrap())
285            .collect();
286        assert_eq!(entries.len(), 1);
287        assert_eq!(entries[0].tag, 0x05);
288        assert!(entries[0].body.is_empty());
289    }
290
291    /// A lone trailing tag byte is a truncated header, not a descriptor:
292    /// `entries` says so, while a header whose body overruns the loop still
293    /// names its tag (#4458).
294    #[test]
295    fn entries_tell_a_lone_tag_byte_from_a_truncated_body() {
296        let lone = [0x05u8, 0x00, 0x6A];
297        let last = RawDescriptorLoop::new(&lone).entries().last().unwrap();
298        assert!(matches!(
299            last,
300            Err(crate::Error::DescriptorHeaderTruncated { offset: 2, .. })
301        ));
302        let overrun = [0x05u8, 0x00, 0x6A, 0x04, 0x00];
303        let last = RawDescriptorLoop::new(&overrun).entries().last().unwrap();
304        assert!(matches!(
305            last,
306            Err(crate::Error::DescriptorBodyTruncated { tag: 0x6A, .. })
307        ));
308    }
309
310    #[test]
311    fn tags_report_a_truncated_entry_and_stop_without_a_header() {
312        let raw = [0x05u8, 0x01, 0xAA, 0x6A, 0x09, 0x01];
313        assert_eq!(
314            RawDescriptorLoop::new(&raw).tags().collect::<Vec<_>>(),
315            [0x05, 0x6A]
316        );
317        let lone_tag = [0x05u8, 0x00, 0x7B];
318        assert_eq!(
319            RawDescriptorLoop::new(&lone_tag).tags().collect::<Vec<_>>(),
320            [0x05, 0x7B]
321        );
322        assert_eq!(RawDescriptorLoop::new(&[]).tags().count(), 0);
323    }
324
325    #[test]
326    fn from_bytes_keeps_the_loop_and_is_empty_tracks_it() {
327        let raw = [0x01u8, 0x00];
328        let loop_ = RawDescriptorLoop::from(&raw[..]);
329        assert!(!loop_.is_empty());
330        assert_eq!(loop_.raw(), &raw[..]);
331        assert_eq!(loop_.len(), 2);
332        assert_eq!(loop_.entries().count(), 1);
333        assert!(RawDescriptorLoop::from(&[][..]).is_empty());
334    }
335
336    #[test]
337    fn a_body_truncated_right_after_its_header_reports_no_body_bytes() {
338        let raw = [0x05u8, 0x03];
339        let err = RawDescriptorLoop::new(&raw)
340            .entries()
341            .last()
342            .unwrap()
343            .unwrap_err();
344        assert_eq!(
345            err,
346            crate::Error::DescriptorBodyTruncated {
347                offset: 0,
348                tag: 0x05,
349                declared: 3,
350                have: 0,
351            }
352        );
353    }
354
355    #[test]
356    fn an_offset_past_the_end_is_a_truncated_header_not_a_panic() {
357        for (len, offset) in [(0usize, 0usize), (0, 1), (3, 4), (3, usize::MAX)] {
358            let bytes = alloc::vec![0x05u8; len];
359            assert_eq!(
360                frame_at(&bytes, offset).unwrap_err(),
361                crate::Error::DescriptorHeaderTruncated {
362                    offset,
363                    need: DESCRIPTOR_HEADER_LEN,
364                    have: 0,
365                }
366            );
367        }
368    }
369
370    #[test]
371    fn parse_with_hands_each_entry_its_own_classification() {
372        // registration descriptor (tag 0x05, "HDMV") then an unknown tag.
373        let raw = [0x05u8, 0x04, b'H', b'D', b'M', b'V', 0xC0, 0x01, 0x7F];
374        let kinds: Vec<_> = RawDescriptorLoop::new(&raw)
375            .parse_with(|tag, _| match tag {
376                0x05 => "registration",
377                0xC0 => "unknown",
378                _ => "other",
379            })
380            .map(|k| k.expect("framed loop"))
381            .collect();
382        assert_eq!(kinds, ["registration", "unknown"]);
383
384        let bodies: Vec<&[u8]> = RawDescriptorLoop::new(&raw)
385            .parse_with(|_, body| body)
386            .map(|b| b.expect("framed loop"))
387            .collect();
388        assert_eq!(bodies, [&b"HDMV"[..], &[0x7F][..]]);
389    }
390}