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
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
//! One reassembler for a payload unit carried across TS packets: a PSI
//! section (ISO/IEC 13818-1 §2.4.4), a T2-MI packet (ETSI TS 102 773 §6.1.1)
//! or a ULE SNDU (RFC 4326 §3, §6, §7) all travel as a byte stream cut into
//! TS payloads, with `payload_unit_start_indicator` and a one-byte pointer
//! naming where the first unit of the packet starts.
//!
//! [`UnitReassembler`] is that shared core: PUSI plus `pointer_field`, the
//! legal-duplicate discard of ISO/IEC 13818-1 §2.4.3.3, a synced flag (nothing
//! is accepted before the first PUSI) and a caller-supplied maximum unit
//! size. What differs per format is a [`Framing`] (how long the unit that
//! starts at the front of the buffer is, and when the rest of a payload is
//! stuffing) and three typed options: [`AfterContinuation`], [`PointerCheck`]
//! and the maximum size.
//!
//! The rules each format's specification states, and which option follows
//! (T2-MI: `private/specs-verified/dvb/dvb-t2mi/ts-102-773-6-1-1-ts-carriage.md`, which
//! also records that the duplicate discard is ISO/IEC 13818-1's, not clause
//! 6.1.1's):
//! - *Duplicate packets* (ISO/IEC 13818-1 §2.4.3.3: exactly two consecutive
//!   packets of one PID with the same counter and the same bytes): a legal
//!   repeat carries nothing new, so all three discard it. ULE had no such rule
//!   in its reassembler; sections discarded on the counter alone and only a
//!   continuation ([`Duplicates::ContinuationOnly`]).
//! - *Stuffing*: PSI allows `0xFF` after the last section of a payload
//!   (§2.4.4); ULE pads with `0xFF`/End Indicator (RFC 4326 §3, §4.3); T2-MI
//!   has "no need for unnecessary stuffing" in the payload and pads in the
//!   adaptation field instead (TS 102 773 §6.1.1). This is the [`Framing`]'s [`UnitLength::Stuffing`].
//! - *Where a unit may start*: only at the pointer of a PUSI packet for PSI
//!   and ULE ([`AfterContinuation::DiscardRest`]); T2-MI packets are packed
//!   back to back and a lenient receiver keeps parsing after one ends inside
//!   a continuation ([`AfterContinuation::ParseRest`]).
//! - *Pointer consistency*: RFC 4326 §7.2.1 requires the pointer to equal the
//!   bytes the unit in progress still needs ([`PointerCheck::MatchRemaining`]);
//!   PSI and T2-MI treat the pointer as authoritative and the bytes before it
//!   as the tail of the unit in progress ([`PointerCheck::Authoritative`]).

use alloc::collections::VecDeque;
use alloc::vec::Vec;
use core::num::NonZeroUsize;

use bytes::{Bytes, BytesMut};

use crate::ts::ContinuityCounter;

/// What [`UnitReassembler::feed`] did with a payload.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[non_exhaustive]
pub enum Fed {
    /// The payload was processed.
    Accepted,
    /// The payload repeated the previous packet and was discarded.
    Duplicate,
}

impl Fed {
    /// The outcome's name.
    #[must_use]
    pub fn name(&self) -> &'static str {
        match self {
            Self::Accepted => "accepted",
            Self::Duplicate => "duplicate",
        }
    }
}
broadcast_core::impl_spec_display!(Fed);

/// What a [`Framing`] knows about the unit starting at the front of a buffer.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[non_exhaustive]
pub enum UnitLength {
    /// The unit is this many bytes in all, header included.
    Total(usize),
    /// Too few bytes to know yet.
    NeedMore,
    /// The buffer starts with stuffing: the rest of the payload carries no
    /// unit.
    Stuffing,
}

impl UnitLength {
    /// The variant's name.
    #[must_use]
    pub fn name(&self) -> &'static str {
        match self {
            Self::Total(_) => "total",
            Self::NeedMore => "need_more",
            Self::Stuffing => "stuffing",
        }
    }
}
broadcast_core::impl_spec_display!(UnitLength);

/// How one format delimits its units.
pub trait Framing {
    /// The unit that starts at `buf[0]`; `buf` is never empty.
    fn length(&self, buf: &[u8]) -> UnitLength;
}

/// Whether a continuation (non-PUSI) packet may start a unit: the bytes left
/// after the unit in progress completes, or the whole payload when none is in
/// progress.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[non_exhaustive]
pub enum AfterContinuation {
    /// No: only a PUSI packet's pointer starts a unit; the rest is stuffing.
    DiscardRest,
    /// Yes: keep parsing units back to back, also from a continuation that
    /// arrives with no unit in progress.
    ParseRest,
}

impl AfterContinuation {
    /// The option's name.
    #[must_use]
    pub fn name(&self) -> &'static str {
        match self {
            Self::DiscardRest => "discard_rest",
            Self::ParseRest => "parse_rest",
        }
    }
}
broadcast_core::impl_spec_display!(AfterContinuation);

/// How a PUSI packet's pointer is judged against the unit in progress.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[non_exhaustive]
pub enum PointerCheck {
    /// The pointer is authoritative: the bytes before it are the tail of the
    /// unit in progress.
    Authoritative,
    /// The pointer must equal the bytes the unit in progress still needs when
    /// its length is known; otherwise the partial unit is discarded.
    MatchRemaining,
}

impl PointerCheck {
    /// The option's name.
    #[must_use]
    pub fn name(&self) -> &'static str {
        match self {
            Self::Authoritative => "authoritative",
            Self::MatchRemaining => "match_remaining",
        }
    }
}
broadcast_core::impl_spec_display!(PointerCheck);

/// Which legal duplicates (ISO/IEC 13818-1 §2.4.3.3) are discarded.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[non_exhaustive]
pub enum Duplicates {
    /// Every duplicate packet.
    Any,
    /// Only a duplicate continuation (non-PUSI) packet: a repeated unit start
    /// is processed again, which is harmless where a repeated whole unit is
    /// (PSI sections are version-gated downstream) and keeps a looping or
    /// synthetic source that repeats a start packet working.
    ContinuationOnly,
}

impl Duplicates {
    /// The option's name.
    #[must_use]
    pub fn name(&self) -> &'static str {
        match self {
            Self::Any => "any",
            Self::ContinuationOnly => "continuation_only",
        }
    }
}
broadcast_core::impl_spec_display!(Duplicates);

/// A packet's continuity information, for the duplicate discard.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct Continuity {
    counter: ContinuityCounter,
    discontinuity: bool,
}

impl Continuity {
    /// The packet's `continuity_counter` and its adaptation-field
    /// `discontinuity_indicator` (an unchanged counter is legal when set).
    #[must_use]
    pub const fn new(counter: ContinuityCounter, discontinuity: bool) -> Self {
        Self {
            counter,
            discontinuity,
        }
    }
}

/// The reassembler's per-format settings.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct UnitOptions {
    after_continuation: AfterContinuation,
    pointer_check: PointerCheck,
    duplicates: Duplicates,
    max_unit_size: NonZeroUsize,
}

impl UnitOptions {
    /// Settings for a format; `max_unit_size` is the largest unit (header
    /// included) the format can carry, so the buffer is bounded by it.
    #[must_use]
    pub const fn new(
        after_continuation: AfterContinuation,
        pointer_check: PointerCheck,
        duplicates: Duplicates,
        max_unit_size: NonZeroUsize,
    ) -> Self {
        Self {
            after_continuation,
            pointer_check,
            duplicates,
            max_unit_size,
        }
    }
}

/// Reassembles units of one format from the payloads of one PID's packets.
#[derive(Debug)]
pub struct UnitReassembler<F> {
    framing: F,
    options: UnitOptions,
    buf: BytesMut,
    ready: VecDeque<Bytes>,
    synced: bool,
    last: Option<(ContinuityCounter, Vec<u8>)>,
}

impl<F: Framing> UnitReassembler<F> {
    /// A reassembler for `framing` with the caller's `options`.
    #[must_use]
    pub fn new(framing: F, options: UnitOptions) -> Self {
        Self {
            framing,
            options,
            buf: BytesMut::new(),
            ready: VecDeque::new(),
            synced: false,
            last: None,
        }
    }

    /// Feed one packet's payload and its PUSI flag. With `continuity`, a legal
    /// duplicate of the previous payload (same counter, identical bytes, no
    /// discontinuity) is discarded.
    pub fn feed(&mut self, payload: &[u8], pusi: bool, continuity: Option<Continuity>) -> Fed {
        match continuity {
            Some(c) => {
                let duplicate = !c.discontinuity
                    && self
                        .last
                        .as_ref()
                        .is_some_and(|(counter, bytes)| *counter == c.counter && bytes == payload);
                self.last = Some((c.counter, payload.to_vec()));
                if duplicate && (!pusi || self.options.duplicates == Duplicates::Any) {
                    return Fed::Duplicate;
                }
            }
            None => self.last = None,
        }
        if pusi {
            self.feed_start(payload);
        } else {
            self.feed_continuation(payload);
        }
        Fed::Accepted
    }

    fn feed_start(&mut self, payload: &[u8]) {
        let Some((&pointer, rest)) = payload.split_first() else {
            self.buf.clear();
            self.synced = false;
            return;
        };
        let pointer = usize::from(pointer);
        if self.synced && !self.buf.is_empty() && pointer > 0 {
            let consistent = match self.options.pointer_check {
                PointerCheck::Authoritative => true,
                PointerCheck::MatchRemaining => match self.framing.length(&self.buf) {
                    UnitLength::Total(total) => {
                        let remaining = total.saturating_sub(self.buf.len());
                        remaining == 0 || remaining == pointer
                    }
                    _ => true,
                },
            };
            if !consistent {
                self.buf.clear();
            } else {
                let tail = pointer.min(rest.len());
                if self.buf.len() + tail > self.options.max_unit_size.get() {
                    self.buf.clear();
                } else {
                    self.buf.extend_from_slice(&rest[..tail]);
                    self.drain();
                }
            }
        }
        self.buf.clear();
        if pointer > rest.len() {
            self.synced = false;
            return;
        }
        self.synced = true;
        let fresh = &rest[pointer..];
        if fresh.len() > self.options.max_unit_size.get() {
            self.synced = false;
            return;
        }
        self.buf.extend_from_slice(fresh);
        self.drain();
    }

    fn feed_continuation(&mut self, payload: &[u8]) {
        if !self.synced
            || (self.buf.is_empty()
                && self.options.after_continuation == AfterContinuation::DiscardRest)
        {
            return;
        }
        let max = self.options.max_unit_size.get();
        let take = match self.options.after_continuation {
            AfterContinuation::ParseRest => payload.len(),
            AfterContinuation::DiscardRest => match self.framing.length(&self.buf) {
                UnitLength::Total(total) => total.saturating_sub(self.buf.len()),
                _ => max.saturating_sub(self.buf.len()),
            }
            .min(payload.len()),
        };
        if self.buf.len() + take > max {
            self.buf.clear();
            self.synced = false;
            return;
        }
        self.buf.extend_from_slice(&payload[..take]);
        self.drain();
    }

    fn drain(&mut self) {
        let max = self.options.max_unit_size.get();
        while !self.buf.is_empty() {
            match self.framing.length(&self.buf) {
                UnitLength::NeedMore => break,
                UnitLength::Stuffing => {
                    self.buf.clear();
                    break;
                }
                UnitLength::Total(total) => {
                    if total == 0 || total > max {
                        self.buf.clear();
                        self.synced = false;
                        break;
                    }
                    if self.buf.len() < total {
                        break;
                    }
                    let unit = self.buf.split_to(total).freeze();
                    self.ready.push_back(unit);
                }
            }
        }
    }

    /// The next complete unit.
    pub fn pop(&mut self) -> Option<Bytes> {
        self.ready.pop_front()
    }

    /// Bytes buffered for the unit in progress.
    #[must_use]
    pub fn len(&self) -> usize {
        self.buf.len()
    }

    /// Whether no unit is in progress.
    #[must_use]
    pub fn is_empty(&self) -> bool {
        self.buf.is_empty()
    }

    /// Whether a PUSI has been seen and framing is trusted.
    #[must_use]
    pub fn is_synced(&self) -> bool {
        self.synced
    }

    /// Forget the unit in progress and the sync state: nothing is accepted
    /// again until the next PUSI.
    pub fn reset(&mut self) {
        self.buf.clear();
        self.synced = false;
    }

    /// Take the bytes of the unit in progress, leaving the sync state alone.
    pub fn take_buffered(&mut self) -> Bytes {
        self.buf.split().freeze()
    }

    /// Discard the bytes of the unit in progress, leaving the sync state
    /// alone.
    pub fn drop_buffered(&mut self) {
        self.buf.clear();
    }
}

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

    /// Units of `1 + n` bytes: first byte `n`, `0xFF` is stuffing.
    struct Lengthed;

    impl Framing for Lengthed {
        fn length(&self, buf: &[u8]) -> UnitLength {
            match buf[0] {
                0xFF => UnitLength::Stuffing,
                n => UnitLength::Total(usize::from(n) + 1),
            }
        }
    }

    fn reasm(after: AfterContinuation, check: PointerCheck) -> UnitReassembler<Lengthed> {
        UnitReassembler::new(
            Lengthed,
            UnitOptions::new(
                after,
                check,
                Duplicates::Any,
                NonZeroUsize::MIN.saturating_add(63),
            ),
        )
    }

    fn cc(v: u8) -> Option<Continuity> {
        Some(Continuity::new(
            ContinuityCounter::try_new(v).expect("4-bit counter"),
            false,
        ))
    }

    fn drain(r: &mut UnitReassembler<Lengthed>) -> Vec<Vec<u8>> {
        core::iter::from_fn(|| r.pop())
            .map(|b| b.to_vec())
            .collect()
    }

    #[test]
    fn nothing_is_accepted_before_the_first_pusi() {
        let mut r = reasm(AfterContinuation::DiscardRest, PointerCheck::Authoritative);
        r.feed(&[2, 1, 2], false, None);
        assert!(drain(&mut r).is_empty());
        r.feed(&[0, 2, 1, 2], true, None);
        assert_eq!(drain(&mut r), [[2, 1, 2]]);
    }

    #[test]
    fn a_legal_duplicate_continuation_is_discarded_once() {
        for after in [AfterContinuation::DiscardRest, AfterContinuation::ParseRest] {
            let mut r = reasm(after, PointerCheck::Authoritative);
            r.feed(&[0, 8, 1, 2], true, cc(0));
            r.feed(&[3, 4], false, cc(1));
            let repeat = r.feed(&[3, 4], false, cc(1));
            assert_eq!(repeat, Fed::Duplicate);
            r.feed(&[5, 6, 7, 8], false, cc(2));
            assert_eq!(drain(&mut r), [[8, 1, 2, 3, 4, 5, 6, 7, 8]], "{after}");
        }
    }

    #[test]
    fn a_repeated_counter_with_different_bytes_is_not_a_duplicate() {
        let mut r = reasm(AfterContinuation::DiscardRest, PointerCheck::Authoritative);
        r.feed(&[0, 4, 1], true, cc(0));
        r.feed(&[2], false, cc(1));
        r.feed(&[3, 4], false, cc(1));
        assert_eq!(drain(&mut r), [[4, 1, 2, 3, 4]]);
    }

    #[test]
    fn a_discontinuity_makes_a_repeated_counter_legal_new_data() {
        let mut r = reasm(AfterContinuation::DiscardRest, PointerCheck::Authoritative);
        r.feed(&[0, 3, 1], true, cc(0));
        let flagged = Some(Continuity::new(
            ContinuityCounter::try_new(0).expect("4-bit counter"),
            true,
        ));
        r.feed(&[1], false, flagged);
        assert!(drain(&mut r).is_empty());
        assert_eq!(r.len(), 3);
    }

    #[test]
    fn stuffing_after_a_unit_ends_the_payload() {
        let mut r = reasm(AfterContinuation::DiscardRest, PointerCheck::Authoritative);
        r.feed(&[0, 1, 9, 0xFF, 0xFF, 0xFF], true, None);
        assert_eq!(drain(&mut r), [[1, 9]]);
        assert!(r.is_empty());
    }

    #[test]
    fn the_pointer_tail_completes_the_unit_in_progress_before_new_units_start() {
        let mut r = reasm(AfterContinuation::DiscardRest, PointerCheck::Authoritative);
        r.feed(&[0, 3, 1], true, None);
        r.feed(&[2, 2, 3, 1, 7], true, None);
        assert_eq!(drain(&mut r), [vec![3, 1, 2, 3], vec![1, 7]]);
    }

    #[test]
    fn match_remaining_discards_a_partial_unit_whose_pointer_disagrees() {
        let mut strict = reasm(AfterContinuation::DiscardRest, PointerCheck::MatchRemaining);
        strict.feed(&[0, 5, 1], true, None);
        strict.feed(&[1, 2, 1, 8], true, None);
        assert_eq!(drain(&mut strict), [[1, 8]], "the partial unit is dropped");

        let mut lax = reasm(AfterContinuation::DiscardRest, PointerCheck::Authoritative);
        lax.feed(&[0, 5, 1], true, None);
        lax.feed(&[1, 2, 1, 8], true, None);
        assert_eq!(
            drain(&mut lax),
            [[1, 8]],
            "an incomplete tail is dropped too"
        );

        let mut agrees = reasm(AfterContinuation::DiscardRest, PointerCheck::MatchRemaining);
        agrees.feed(&[0, 5, 1], true, None);
        agrees.feed(&[4, 2, 3, 4, 5, 1, 8], true, None);
        assert_eq!(drain(&mut agrees), [vec![5, 1, 2, 3, 4, 5], vec![1, 8]]);
    }

    #[test]
    fn units_after_a_continuation_end_follow_the_option() {
        let mut discard = reasm(AfterContinuation::DiscardRest, PointerCheck::Authoritative);
        discard.feed(&[0, 3, 1], true, None);
        discard.feed(&[2, 3, 1, 9], false, None);
        assert_eq!(drain(&mut discard), [[3, 1, 2, 3]]);

        let mut parse = reasm(AfterContinuation::ParseRest, PointerCheck::Authoritative);
        parse.feed(&[0, 3, 1], true, None);
        parse.feed(&[2, 3, 1, 9], false, None);
        assert_eq!(drain(&mut parse), [vec![3, 1, 2, 3], vec![1, 9]]);
        parse.feed(&[1, 4], false, None);
        assert_eq!(
            drain(&mut parse),
            [[1, 4]],
            "a unit may start in a continuation"
        );
        discard.feed(&[1, 4], false, None);
        assert!(drain(&mut discard).is_empty());
    }

    #[test]
    fn a_pointer_past_the_payload_drops_sync_and_a_unit_over_the_cap_is_refused() {
        let mut r = reasm(AfterContinuation::DiscardRest, PointerCheck::Authoritative);
        r.feed(&[9, 1], true, None);
        assert!(!r.is_synced());
        r.feed(&[0, 200, 1], true, None);
        assert!(drain(&mut r).is_empty());
        assert!(!r.is_synced());
    }
}