Skip to main content

mpeg_ts/
unit.rs

1//! One reassembler for a payload unit carried across TS packets: a PSI
2//! section (ISO/IEC 13818-1 §2.4.4), a T2-MI packet (ETSI TS 102 773 §6.1.1)
3//! or a ULE SNDU (RFC 4326 §3, §6, §7) all travel as a byte stream cut into
4//! TS payloads, with `payload_unit_start_indicator` and a one-byte pointer
5//! naming where the first unit of the packet starts.
6//!
7//! [`UnitReassembler`] is that shared core: PUSI plus `pointer_field`, the
8//! legal-duplicate discard of ISO/IEC 13818-1 §2.4.3.3, a synced flag (nothing
9//! is accepted before the first PUSI) and a caller-supplied maximum unit
10//! size. What differs per format is a [`Framing`] (how long the unit that
11//! starts at the front of the buffer is, and when the rest of a payload is
12//! stuffing) and three typed options: [`AfterContinuation`], [`PointerCheck`]
13//! and the maximum size.
14//!
15//! The rules each format's specification states, and which option follows
16//! (T2-MI: `private/specs-verified/dvb/dvb-t2mi/ts-102-773-6-1-1-ts-carriage.md`, which
17//! also records that the duplicate discard is ISO/IEC 13818-1's, not clause
18//! 6.1.1's):
19//! - *Duplicate packets* (ISO/IEC 13818-1 §2.4.3.3: exactly two consecutive
20//!   packets of one PID with the same counter and the same bytes): a legal
21//!   repeat carries nothing new, so all three discard it. ULE had no such rule
22//!   in its reassembler; sections discarded on the counter alone and only a
23//!   continuation ([`Duplicates::ContinuationOnly`]).
24//! - *Stuffing*: PSI allows `0xFF` after the last section of a payload
25//!   (§2.4.4); ULE pads with `0xFF`/End Indicator (RFC 4326 §3, §4.3); T2-MI
26//!   has "no need for unnecessary stuffing" in the payload and pads in the
27//!   adaptation field instead (TS 102 773 §6.1.1). This is the [`Framing`]'s [`UnitLength::Stuffing`].
28//! - *Where a unit may start*: only at the pointer of a PUSI packet for PSI
29//!   and ULE ([`AfterContinuation::DiscardRest`]); T2-MI packets are packed
30//!   back to back and a lenient receiver keeps parsing after one ends inside
31//!   a continuation ([`AfterContinuation::ParseRest`]).
32//! - *Pointer consistency*: RFC 4326 §7.2.1 requires the pointer to equal the
33//!   bytes the unit in progress still needs ([`PointerCheck::MatchRemaining`]);
34//!   PSI and T2-MI treat the pointer as authoritative and the bytes before it
35//!   as the tail of the unit in progress ([`PointerCheck::Authoritative`]).
36
37use alloc::collections::VecDeque;
38use alloc::vec::Vec;
39use core::num::NonZeroUsize;
40
41use bytes::{Bytes, BytesMut};
42
43use crate::ts::ContinuityCounter;
44
45/// What [`UnitReassembler::feed`] did with a payload.
46#[derive(Debug, Clone, Copy, PartialEq, Eq)]
47#[non_exhaustive]
48pub enum Fed {
49    /// The payload was processed.
50    Accepted,
51    /// The payload repeated the previous packet and was discarded.
52    Duplicate,
53}
54
55impl Fed {
56    /// The outcome's name.
57    #[must_use]
58    pub fn name(&self) -> &'static str {
59        match self {
60            Self::Accepted => "accepted",
61            Self::Duplicate => "duplicate",
62        }
63    }
64}
65broadcast_core::impl_spec_display!(Fed);
66
67/// What a [`Framing`] knows about the unit starting at the front of a buffer.
68#[derive(Debug, Clone, Copy, PartialEq, Eq)]
69#[non_exhaustive]
70pub enum UnitLength {
71    /// The unit is this many bytes in all, header included.
72    Total(usize),
73    /// Too few bytes to know yet.
74    NeedMore,
75    /// The buffer starts with stuffing: the rest of the payload carries no
76    /// unit.
77    Stuffing,
78}
79
80impl UnitLength {
81    /// The variant's name.
82    #[must_use]
83    pub fn name(&self) -> &'static str {
84        match self {
85            Self::Total(_) => "total",
86            Self::NeedMore => "need_more",
87            Self::Stuffing => "stuffing",
88        }
89    }
90}
91broadcast_core::impl_spec_display!(UnitLength);
92
93/// How one format delimits its units.
94pub trait Framing {
95    /// The unit that starts at `buf[0]`; `buf` is never empty.
96    fn length(&self, buf: &[u8]) -> UnitLength;
97}
98
99/// Whether a continuation (non-PUSI) packet may start a unit: the bytes left
100/// after the unit in progress completes, or the whole payload when none is in
101/// progress.
102#[derive(Debug, Clone, Copy, PartialEq, Eq)]
103#[non_exhaustive]
104pub enum AfterContinuation {
105    /// No: only a PUSI packet's pointer starts a unit; the rest is stuffing.
106    DiscardRest,
107    /// Yes: keep parsing units back to back, also from a continuation that
108    /// arrives with no unit in progress.
109    ParseRest,
110}
111
112impl AfterContinuation {
113    /// The option's name.
114    #[must_use]
115    pub fn name(&self) -> &'static str {
116        match self {
117            Self::DiscardRest => "discard_rest",
118            Self::ParseRest => "parse_rest",
119        }
120    }
121}
122broadcast_core::impl_spec_display!(AfterContinuation);
123
124/// How a PUSI packet's pointer is judged against the unit in progress.
125#[derive(Debug, Clone, Copy, PartialEq, Eq)]
126#[non_exhaustive]
127pub enum PointerCheck {
128    /// The pointer is authoritative: the bytes before it are the tail of the
129    /// unit in progress.
130    Authoritative,
131    /// The pointer must equal the bytes the unit in progress still needs when
132    /// its length is known; otherwise the partial unit is discarded.
133    MatchRemaining,
134}
135
136impl PointerCheck {
137    /// The option's name.
138    #[must_use]
139    pub fn name(&self) -> &'static str {
140        match self {
141            Self::Authoritative => "authoritative",
142            Self::MatchRemaining => "match_remaining",
143        }
144    }
145}
146broadcast_core::impl_spec_display!(PointerCheck);
147
148/// Which legal duplicates (ISO/IEC 13818-1 §2.4.3.3) are discarded.
149#[derive(Debug, Clone, Copy, PartialEq, Eq)]
150#[non_exhaustive]
151pub enum Duplicates {
152    /// Every duplicate packet.
153    Any,
154    /// Only a duplicate continuation (non-PUSI) packet: a repeated unit start
155    /// is processed again, which is harmless where a repeated whole unit is
156    /// (PSI sections are version-gated downstream) and keeps a looping or
157    /// synthetic source that repeats a start packet working.
158    ContinuationOnly,
159}
160
161impl Duplicates {
162    /// The option's name.
163    #[must_use]
164    pub fn name(&self) -> &'static str {
165        match self {
166            Self::Any => "any",
167            Self::ContinuationOnly => "continuation_only",
168        }
169    }
170}
171broadcast_core::impl_spec_display!(Duplicates);
172
173/// A packet's continuity information, for the duplicate discard.
174#[derive(Debug, Clone, Copy, PartialEq, Eq)]
175pub struct Continuity {
176    counter: ContinuityCounter,
177    discontinuity: bool,
178}
179
180impl Continuity {
181    /// The packet's `continuity_counter` and its adaptation-field
182    /// `discontinuity_indicator` (an unchanged counter is legal when set).
183    #[must_use]
184    pub const fn new(counter: ContinuityCounter, discontinuity: bool) -> Self {
185        Self {
186            counter,
187            discontinuity,
188        }
189    }
190}
191
192/// The reassembler's per-format settings.
193#[derive(Debug, Clone, Copy, PartialEq, Eq)]
194pub struct UnitOptions {
195    after_continuation: AfterContinuation,
196    pointer_check: PointerCheck,
197    duplicates: Duplicates,
198    max_unit_size: NonZeroUsize,
199}
200
201impl UnitOptions {
202    /// Settings for a format; `max_unit_size` is the largest unit (header
203    /// included) the format can carry, so the buffer is bounded by it.
204    #[must_use]
205    pub const fn new(
206        after_continuation: AfterContinuation,
207        pointer_check: PointerCheck,
208        duplicates: Duplicates,
209        max_unit_size: NonZeroUsize,
210    ) -> Self {
211        Self {
212            after_continuation,
213            pointer_check,
214            duplicates,
215            max_unit_size,
216        }
217    }
218}
219
220/// Reassembles units of one format from the payloads of one PID's packets.
221#[derive(Debug)]
222pub struct UnitReassembler<F> {
223    framing: F,
224    options: UnitOptions,
225    buf: BytesMut,
226    ready: VecDeque<Bytes>,
227    synced: bool,
228    last: Option<(ContinuityCounter, Vec<u8>)>,
229}
230
231impl<F: Framing> UnitReassembler<F> {
232    /// A reassembler for `framing` with the caller's `options`.
233    #[must_use]
234    pub fn new(framing: F, options: UnitOptions) -> Self {
235        Self {
236            framing,
237            options,
238            buf: BytesMut::new(),
239            ready: VecDeque::new(),
240            synced: false,
241            last: None,
242        }
243    }
244
245    /// Feed one packet's payload and its PUSI flag. With `continuity`, a legal
246    /// duplicate of the previous payload (same counter, identical bytes, no
247    /// discontinuity) is discarded.
248    pub fn feed(&mut self, payload: &[u8], pusi: bool, continuity: Option<Continuity>) -> Fed {
249        match continuity {
250            Some(c) => {
251                let duplicate = !c.discontinuity
252                    && self
253                        .last
254                        .as_ref()
255                        .is_some_and(|(counter, bytes)| *counter == c.counter && bytes == payload);
256                self.last = Some((c.counter, payload.to_vec()));
257                if duplicate && (!pusi || self.options.duplicates == Duplicates::Any) {
258                    return Fed::Duplicate;
259                }
260            }
261            None => self.last = None,
262        }
263        if pusi {
264            self.feed_start(payload);
265        } else {
266            self.feed_continuation(payload);
267        }
268        Fed::Accepted
269    }
270
271    fn feed_start(&mut self, payload: &[u8]) {
272        let Some((&pointer, rest)) = payload.split_first() else {
273            self.buf.clear();
274            self.synced = false;
275            return;
276        };
277        let pointer = usize::from(pointer);
278        if self.synced && !self.buf.is_empty() && pointer > 0 {
279            let consistent = match self.options.pointer_check {
280                PointerCheck::Authoritative => true,
281                PointerCheck::MatchRemaining => match self.framing.length(&self.buf) {
282                    UnitLength::Total(total) => {
283                        let remaining = total.saturating_sub(self.buf.len());
284                        remaining == 0 || remaining == pointer
285                    }
286                    _ => true,
287                },
288            };
289            if !consistent {
290                self.buf.clear();
291            } else {
292                let tail = pointer.min(rest.len());
293                if self.buf.len() + tail > self.options.max_unit_size.get() {
294                    self.buf.clear();
295                } else {
296                    self.buf.extend_from_slice(&rest[..tail]);
297                    self.drain();
298                }
299            }
300        }
301        self.buf.clear();
302        if pointer > rest.len() {
303            self.synced = false;
304            return;
305        }
306        self.synced = true;
307        let fresh = &rest[pointer..];
308        if fresh.len() > self.options.max_unit_size.get() {
309            self.synced = false;
310            return;
311        }
312        self.buf.extend_from_slice(fresh);
313        self.drain();
314    }
315
316    fn feed_continuation(&mut self, payload: &[u8]) {
317        if !self.synced
318            || (self.buf.is_empty()
319                && self.options.after_continuation == AfterContinuation::DiscardRest)
320        {
321            return;
322        }
323        let max = self.options.max_unit_size.get();
324        let take = match self.options.after_continuation {
325            AfterContinuation::ParseRest => payload.len(),
326            AfterContinuation::DiscardRest => match self.framing.length(&self.buf) {
327                UnitLength::Total(total) => total.saturating_sub(self.buf.len()),
328                _ => max.saturating_sub(self.buf.len()),
329            }
330            .min(payload.len()),
331        };
332        if self.buf.len() + take > max {
333            self.buf.clear();
334            self.synced = false;
335            return;
336        }
337        self.buf.extend_from_slice(&payload[..take]);
338        self.drain();
339    }
340
341    fn drain(&mut self) {
342        let max = self.options.max_unit_size.get();
343        while !self.buf.is_empty() {
344            match self.framing.length(&self.buf) {
345                UnitLength::NeedMore => break,
346                UnitLength::Stuffing => {
347                    self.buf.clear();
348                    break;
349                }
350                UnitLength::Total(total) => {
351                    if total == 0 || total > max {
352                        self.buf.clear();
353                        self.synced = false;
354                        break;
355                    }
356                    if self.buf.len() < total {
357                        break;
358                    }
359                    let unit = self.buf.split_to(total).freeze();
360                    self.ready.push_back(unit);
361                }
362            }
363        }
364    }
365
366    /// The next complete unit.
367    pub fn pop(&mut self) -> Option<Bytes> {
368        self.ready.pop_front()
369    }
370
371    /// Bytes buffered for the unit in progress.
372    #[must_use]
373    pub fn len(&self) -> usize {
374        self.buf.len()
375    }
376
377    /// Whether no unit is in progress.
378    #[must_use]
379    pub fn is_empty(&self) -> bool {
380        self.buf.is_empty()
381    }
382
383    /// Whether a PUSI has been seen and framing is trusted.
384    #[must_use]
385    pub fn is_synced(&self) -> bool {
386        self.synced
387    }
388
389    /// Forget the unit in progress and the sync state: nothing is accepted
390    /// again until the next PUSI.
391    pub fn reset(&mut self) {
392        self.buf.clear();
393        self.synced = false;
394    }
395
396    /// Take the bytes of the unit in progress, leaving the sync state alone.
397    pub fn take_buffered(&mut self) -> Bytes {
398        self.buf.split().freeze()
399    }
400
401    /// Discard the bytes of the unit in progress, leaving the sync state
402    /// alone.
403    pub fn drop_buffered(&mut self) {
404        self.buf.clear();
405    }
406}
407
408#[cfg(test)]
409mod tests {
410    use super::*;
411    use alloc::vec;
412
413    /// Units of `1 + n` bytes: first byte `n`, `0xFF` is stuffing.
414    struct Lengthed;
415
416    impl Framing for Lengthed {
417        fn length(&self, buf: &[u8]) -> UnitLength {
418            match buf[0] {
419                0xFF => UnitLength::Stuffing,
420                n => UnitLength::Total(usize::from(n) + 1),
421            }
422        }
423    }
424
425    fn reasm(after: AfterContinuation, check: PointerCheck) -> UnitReassembler<Lengthed> {
426        UnitReassembler::new(
427            Lengthed,
428            UnitOptions::new(
429                after,
430                check,
431                Duplicates::Any,
432                NonZeroUsize::MIN.saturating_add(63),
433            ),
434        )
435    }
436
437    fn cc(v: u8) -> Option<Continuity> {
438        Some(Continuity::new(
439            ContinuityCounter::try_new(v).expect("4-bit counter"),
440            false,
441        ))
442    }
443
444    fn drain(r: &mut UnitReassembler<Lengthed>) -> Vec<Vec<u8>> {
445        core::iter::from_fn(|| r.pop())
446            .map(|b| b.to_vec())
447            .collect()
448    }
449
450    #[test]
451    fn nothing_is_accepted_before_the_first_pusi() {
452        let mut r = reasm(AfterContinuation::DiscardRest, PointerCheck::Authoritative);
453        r.feed(&[2, 1, 2], false, None);
454        assert!(drain(&mut r).is_empty());
455        r.feed(&[0, 2, 1, 2], true, None);
456        assert_eq!(drain(&mut r), [[2, 1, 2]]);
457    }
458
459    #[test]
460    fn a_legal_duplicate_continuation_is_discarded_once() {
461        for after in [AfterContinuation::DiscardRest, AfterContinuation::ParseRest] {
462            let mut r = reasm(after, PointerCheck::Authoritative);
463            r.feed(&[0, 8, 1, 2], true, cc(0));
464            r.feed(&[3, 4], false, cc(1));
465            let repeat = r.feed(&[3, 4], false, cc(1));
466            assert_eq!(repeat, Fed::Duplicate);
467            r.feed(&[5, 6, 7, 8], false, cc(2));
468            assert_eq!(drain(&mut r), [[8, 1, 2, 3, 4, 5, 6, 7, 8]], "{after}");
469        }
470    }
471
472    #[test]
473    fn a_repeated_counter_with_different_bytes_is_not_a_duplicate() {
474        let mut r = reasm(AfterContinuation::DiscardRest, PointerCheck::Authoritative);
475        r.feed(&[0, 4, 1], true, cc(0));
476        r.feed(&[2], false, cc(1));
477        r.feed(&[3, 4], false, cc(1));
478        assert_eq!(drain(&mut r), [[4, 1, 2, 3, 4]]);
479    }
480
481    #[test]
482    fn a_discontinuity_makes_a_repeated_counter_legal_new_data() {
483        let mut r = reasm(AfterContinuation::DiscardRest, PointerCheck::Authoritative);
484        r.feed(&[0, 3, 1], true, cc(0));
485        let flagged = Some(Continuity::new(
486            ContinuityCounter::try_new(0).expect("4-bit counter"),
487            true,
488        ));
489        r.feed(&[1], false, flagged);
490        assert!(drain(&mut r).is_empty());
491        assert_eq!(r.len(), 3);
492    }
493
494    #[test]
495    fn stuffing_after_a_unit_ends_the_payload() {
496        let mut r = reasm(AfterContinuation::DiscardRest, PointerCheck::Authoritative);
497        r.feed(&[0, 1, 9, 0xFF, 0xFF, 0xFF], true, None);
498        assert_eq!(drain(&mut r), [[1, 9]]);
499        assert!(r.is_empty());
500    }
501
502    #[test]
503    fn the_pointer_tail_completes_the_unit_in_progress_before_new_units_start() {
504        let mut r = reasm(AfterContinuation::DiscardRest, PointerCheck::Authoritative);
505        r.feed(&[0, 3, 1], true, None);
506        r.feed(&[2, 2, 3, 1, 7], true, None);
507        assert_eq!(drain(&mut r), [vec![3, 1, 2, 3], vec![1, 7]]);
508    }
509
510    #[test]
511    fn match_remaining_discards_a_partial_unit_whose_pointer_disagrees() {
512        let mut strict = reasm(AfterContinuation::DiscardRest, PointerCheck::MatchRemaining);
513        strict.feed(&[0, 5, 1], true, None);
514        strict.feed(&[1, 2, 1, 8], true, None);
515        assert_eq!(drain(&mut strict), [[1, 8]], "the partial unit is dropped");
516
517        let mut lax = reasm(AfterContinuation::DiscardRest, PointerCheck::Authoritative);
518        lax.feed(&[0, 5, 1], true, None);
519        lax.feed(&[1, 2, 1, 8], true, None);
520        assert_eq!(
521            drain(&mut lax),
522            [[1, 8]],
523            "an incomplete tail is dropped too"
524        );
525
526        let mut agrees = reasm(AfterContinuation::DiscardRest, PointerCheck::MatchRemaining);
527        agrees.feed(&[0, 5, 1], true, None);
528        agrees.feed(&[4, 2, 3, 4, 5, 1, 8], true, None);
529        assert_eq!(drain(&mut agrees), [vec![5, 1, 2, 3, 4, 5], vec![1, 8]]);
530    }
531
532    #[test]
533    fn units_after_a_continuation_end_follow_the_option() {
534        let mut discard = reasm(AfterContinuation::DiscardRest, PointerCheck::Authoritative);
535        discard.feed(&[0, 3, 1], true, None);
536        discard.feed(&[2, 3, 1, 9], false, None);
537        assert_eq!(drain(&mut discard), [[3, 1, 2, 3]]);
538
539        let mut parse = reasm(AfterContinuation::ParseRest, PointerCheck::Authoritative);
540        parse.feed(&[0, 3, 1], true, None);
541        parse.feed(&[2, 3, 1, 9], false, None);
542        assert_eq!(drain(&mut parse), [vec![3, 1, 2, 3], vec![1, 9]]);
543        parse.feed(&[1, 4], false, None);
544        assert_eq!(
545            drain(&mut parse),
546            [[1, 4]],
547            "a unit may start in a continuation"
548        );
549        discard.feed(&[1, 4], false, None);
550        assert!(drain(&mut discard).is_empty());
551    }
552
553    #[test]
554    fn a_pointer_past_the_payload_drops_sync_and_a_unit_over_the_cap_is_refused() {
555        let mut r = reasm(AfterContinuation::DiscardRest, PointerCheck::Authoritative);
556        r.feed(&[9, 1], true, None);
557        assert!(!r.is_synced());
558        r.feed(&[0, 200, 1], true, None);
559        assert!(drain(&mut r).is_empty());
560        assert!(!r.is_synced());
561    }
562}