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
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
//! Section → TS packetiser (the byte-exact inverse of
//! [`SectionReassembler::feed`](crate::ts::SectionReassembler::feed)).
//!
//! Per the PSI carriage rules of ITU-T H.222.0 §2.4.4 (= ISO/IEC 13818-1:2007 §2.4.4)
//! (`private/specs-verified/mpeg/mpeg-ts/tables/h222_0/psi_section.md`): sections are packed into 188-byte packets
//! with a `pointer_field` where sections begin, concatenated contiguously, and
//! 0xFF-stuffed at the batch tail.

use alloc::vec::Vec;

use crate::pid::Pid;
use crate::ts::{
    AdaptationFieldControl, ContinuityCounter, ScramblingControl, TS_PACKET_SIZE, TsHeader,
};

/// Maximum data bytes in a PUSI=1 packet (188 − 4 header − 1 pointer_field). §2.4.4.
const PUSI_PAYLOAD_CAP: usize = 183;
/// Maximum data bytes in a continuation packet (188 − 4 header). §2.4.4.
const PAYLOAD_CAP: usize = 184;
use crate::ts::STUFFING_BYTE;

/// Packetises PSI/SI sections into 188-byte TS packets.
///
/// This is the byte-exact inverse of
/// [`SectionReassembler::feed`](crate::ts::SectionReassembler::feed): packets
/// produced here, when fed back through the reassembler, yield the same
/// sections in order.
///
/// ISO/IEC 13818-1:2007 §2.4.4 (`private/specs-verified/mpeg/mpeg-ts/tables/h222_0/psi_section.md`).
pub struct SectionPacketiser {
    pid: Pid,
    continuity_counter: ContinuityCounter,
}

impl SectionPacketiser {
    /// Start a packetiser for `pid` with continuity_counter = 0.
    pub fn new(pid: Pid) -> Self {
        Self {
            pid,
            continuity_counter: ContinuityCounter::ZERO,
        }
    }

    /// Start at a specific continuity_counter — for resuming a stream.
    pub fn with_continuity(pid: Pid, cc: ContinuityCounter) -> Self {
        Self {
            pid,
            continuity_counter: cc,
        }
    }

    /// The PID this packetiser emits packets for.
    pub fn pid(&self) -> Pid {
        self.pid
    }

    /// The continuity_counter for the next emitted packet.
    pub fn continuity_counter(&self) -> ContinuityCounter {
        self.continuity_counter
    }

    /// Packetise a batch of complete sections into 188-byte TS packets,
    /// appended to `out` (cleared first).
    ///
    /// Returns the number of packets appended.
    pub fn packetise_into(
        &mut self,
        sections: &[&[u8]],
        out: &mut Vec<[u8; TS_PACKET_SIZE]>,
    ) -> usize {
        out.clear();

        if sections.is_empty() {
            return 0;
        }

        // Concatenate all sections and record section-start byte offsets.
        let total_len: usize = sections.iter().map(|s| s.len()).sum();
        if total_len == 0 {
            return 0;
        }
        let mut data = Vec::with_capacity(total_len);
        let mut starts = Vec::with_capacity(sections.len());
        for s in sections {
            starts.push(data.len());
            data.extend_from_slice(s);
        }

        let count_before = out.len();
        let mut pos = 0usize;
        // `starts` is ascending and `pos` only advances, so a forward-only
        // cursor finds the smallest section-start offset >= pos in amortised
        // O(1) per packet instead of rescanning from the front (audit
        // r01-O1: O(packets x sections)).
        let mut next_idx = 0usize;

        while pos < data.len() {
            while starts.get(next_idx).is_some_and(|&s| s < pos) {
                next_idx += 1;
            }
            let next_start = starts.get(next_idx).copied();

            let pusi: bool;
            let pointer_field: u8;
            let cap: usize;

            if let Some(ns) = next_start {
                let diff = ns.saturating_sub(pos);
                // W1 (#1074): `diff == PUSI_PAYLOAD_CAP` (183) must NOT take the
                // PUSI branch — a pointer_field of 183 would claim a section
                // starts after all 183 payload bytes, i.e. not within this
                // packet at all (H.222.0 §2.4.4 requires PUSI=1 to mean a
                // section genuinely starts here). The non-PUSI branch's cap
                // must in turn be bounded by `diff`, not just the fixed
                // 184-byte payload size, or a continuation packet at this same
                // boundary copies one byte past the next section's start —
                // the reassembler then silently drops it (it only takes what
                // completes the in-progress section), corrupting the next one.
                if diff < PUSI_PAYLOAD_CAP {
                    pusi = true;
                    pointer_field = diff as u8;
                    cap = PUSI_PAYLOAD_CAP;
                } else {
                    pusi = false;
                    pointer_field = 0;
                    cap = PAYLOAD_CAP.min(diff);
                }
            } else {
                pusi = false;
                pointer_field = 0;
                cap = PAYLOAD_CAP;
            }

            let mut pkt = [0u8; TS_PACKET_SIZE];

            let header = TsHeader {
                tei: false,
                pusi,
                pid: self.pid,
                scrambling: ScramblingControl::NotScrambled,
                adaptation_field_control: AdaptationFieldControl::PayloadOnly,
                continuity_counter: self.continuity_counter,
            };
            pkt[..TsHeader::serialized_len()].copy_from_slice(&header.to_bytes());

            self.continuity_counter = self.continuity_counter.next();

            let mut write_pos = TsHeader::serialized_len();

            if pusi {
                pkt[write_pos] = pointer_field;
                write_pos += 1;
            }

            let remaining = data.len() - pos;
            let to_copy = remaining.min(cap);
            pkt[write_pos..write_pos + to_copy].copy_from_slice(&data[pos..pos + to_copy]);
            pos += to_copy;
            write_pos += to_copy;

            // 0xFF-stuff remaining payload bytes.
            for b in &mut pkt[write_pos..] {
                *b = STUFFING_BYTE;
            }

            out.push(pkt);
        }

        out.len() - count_before
    }

    /// Allocating convenience wrapper over [`packetise_into`](Self::packetise_into).
    pub fn packetise(&mut self, sections: &[&[u8]]) -> Vec<[u8; TS_PACKET_SIZE]> {
        let mut out = Vec::new();
        self.packetise_into(sections, &mut out);
        out
    }
}

/// Split concatenated complete-section bytes into individual `&[u8]` slices.
///
/// Walks the PSI/SI section headers: byte 0 = table_id, bytes 1-2 =
/// section_length (12 bits). Each slice is 3 + section_length bytes long.
/// Trailing bytes that don't form a complete section header are discarded.
/// The section scheduler in `dvb-si` registers one section per call and
/// checks a caller's slice with this.
pub fn split_sections(data: &[u8]) -> Vec<&[u8]> {
    let mut result = Vec::new();
    let mut pos = 0;
    while let Some(end) = crate::ts::section_total_len(&data[pos..]).map(|len| pos + len) {
        if end > data.len() {
            break;
        }
        result.push(&data[pos..end]);
        pos = end;
    }
    result
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::ts::{SectionReassembler, TsPacket};
    use alloc::vec;
    use alloc::vec::Vec;

    // ── helpers ──────────────────────────────────────────────────────────────

    fn concat_sections(sections: &[Vec<u8>]) -> Vec<u8> {
        let total: usize = sections.iter().map(|s| s.len()).sum();
        let mut out = Vec::with_capacity(total);
        for s in sections {
            out.extend_from_slice(s);
        }
        out
    }

    /// Round-trip `sections` through packetise → reassembler, asserting
    /// byte-identical output in order and no leftovers.
    fn assert_round_trip(sections: &[Vec<u8>]) {
        let mut packetiser = SectionPacketiser::new(Pid::from_const(0x0100));
        let refs: Vec<&[u8]> = sections.iter().map(|s| s.as_slice()).collect();
        let packets = packetiser.packetise(&refs);

        let mut reasm = SectionReassembler::default();
        for pkt_raw in &packets {
            let pkt = TsPacket::parse(pkt_raw).expect("parse generated packet");
            let payload = pkt.payload.expect("payload present");
            let pusi = pkt.header.pusi;
            reasm.feed(payload, pusi);
        }

        let got: Vec<_> = core::iter::from_fn(|| reasm.pop_section()).collect();
        assert_eq!(
            got.len(),
            sections.len(),
            "section count mismatch: expected {}, got {}",
            sections.len(),
            got.len()
        );
        for (i, (orig, round)) in sections.iter().zip(got.iter()).enumerate() {
            assert_eq!(
                round.as_ref(),
                orig.as_slice(),
                "section {i} round-trip mismatch"
            );
        }
        assert!(reasm.is_empty(), "reassembler should be empty after drain");
    }

    /// 400 sections whose sizes sweep 0..=399 body bytes (so section starts
    /// land on every offset around the 183/184-byte packet boundaries)
    /// round-trip byte-identically through packetise -> reassemble (audit
    /// r01-O1: the section-start lookup is now a forward cursor; this is the
    /// independent oracle that the rewrite chose the same boundaries).
    #[test]
    fn many_sections_with_boundary_straddling_sizes_round_trip() {
        let sections: Vec<Vec<u8>> = (0..400usize)
            .map(|n| {
                let body: Vec<u8> = (0..n).map(|i| (i % 251) as u8).collect();
                test_fixtures::psi::short_section((n % 200) as u8, &body)
            })
            .collect();
        assert_round_trip(&sections);
    }

    // ── split_sections ──────────────────────────────────────────────────────

    #[test]
    fn split_single_section() {
        let s = test_fixtures::psi::long_section(0x42, 1, 0, 0, &[0xAA; 5]);
        let refs = split_sections(&s);
        assert_eq!(refs.len(), 1);
        assert_eq!(refs[0], s.as_slice());
    }

    #[test]
    fn split_two_sections() {
        let s1 = test_fixtures::psi::long_section(0x42, 1, 0, 0, &[0x01, 0x02]);
        let s2 = test_fixtures::psi::long_section(0x46, 1, 0, 0, &[0x03, 0x04, 0x05]);
        let both = concat_sections(&[s1.clone(), s2.clone()]);
        let refs = split_sections(&both);
        assert_eq!(refs.len(), 2);
        assert_eq!(refs[0], s1.as_slice());
        assert_eq!(refs[1], s2.as_slice());
    }

    #[test]
    fn split_empty_input() {
        let refs = split_sections(&[]);
        assert!(refs.is_empty());
    }

    #[test]
    fn split_trailing_garbage_ignored() {
        let s = test_fixtures::psi::long_section(0x42, 1, 0, 0, &[0xAA; 3]);
        let mut data = s.clone();
        data.push(0xFF); // trailing byte that doesn't complete a header
        let refs = split_sections(&data);
        assert_eq!(refs.len(), 1);
        assert_eq!(refs[0], s.as_slice());
    }

    fn cc(v: u8) -> ContinuityCounter {
        ContinuityCounter::try_new(v).expect("4-bit counter")
    }

    // ── round-trip property (the mandatory acceptance oracle) ────────────────

    #[test]
    fn round_trip_single_short_section() {
        let s = test_fixtures::psi::long_section(0x42, 1, 0, 0, &[0xAA; 10]);
        assert_round_trip(&[s]);
    }

    #[test]
    fn round_trip_one_byte_body() {
        let s = test_fixtures::psi::long_section(0x46, 1, 0, 0, &[0xBB]); // 4 bytes total
        assert_round_trip(&[s]);
    }

    #[test]
    fn round_trip_section_exactly_pusi_cap_boundary() {
        // A section whose total length is exactly PUSI_PAYLOAD_CAP (183).
        let body = vec![0xCC; PUSI_PAYLOAD_CAP - 3];
        let s = test_fixtures::psi::short_section(0x50, &body);
        assert_eq!(s.len(), PUSI_PAYLOAD_CAP);
        assert_round_trip(&[s]);
    }

    #[test]
    fn round_trip_section_just_over_pusi_cap() {
        // One byte more than fits in a PUSI packet → must span to continuation.
        let body = vec![0xDD; PUSI_PAYLOAD_CAP - 3 + 1];
        let s = test_fixtures::psi::short_section(0x52, &body);
        assert_eq!(s.len(), PUSI_PAYLOAD_CAP + 1);
        assert_round_trip(&[s]);
    }

    #[test]
    fn round_trip_section_spans_many_packets() {
        // A 2000-byte section spans ~11 packets.
        let body = vec![0xEE; 2000 - 3];
        let s = test_fixtures::psi::short_section(0x60, &body);
        assert_round_trip(&[s]);
    }

    #[test]
    fn round_trip_section_at_max_size() {
        // The maximum section (4096 total, the long-form ceiling), whose final
        // continuation packet carries the tail followed by 0xFF stuffing. Since
        // #148 the reassembler ignores that trailing stuffing instead of
        // counting it toward MAX_SECTION_SIZE, so a full-size section round-trips.
        let body = vec![0x11; 4096 - 3];
        let s = test_fixtures::psi::short_section(0x80, &body);
        assert_eq!(s.len(), 4096);
        assert_round_trip(&[s]);
    }

    #[test]
    fn round_trip_multiple_short_sections_in_one_batch() {
        let s1 = test_fixtures::psi::long_section(0x42, 1, 0, 0, &[0x01, 0x02]); // 5 bytes
        let s2 = test_fixtures::psi::long_section(0x46, 1, 0, 0, &[0x03]); // 4 bytes
        let s3 = test_fixtures::psi::long_section(0x4A, 1, 0, 0, &[0x04, 0x05, 0x06]); // 6 bytes
        assert_round_trip(&[s1, s2, s3]);
    }

    #[test]
    fn round_trip_section_ends_exactly_at_boundary() {
        // First section is exactly PUSI_PAYLOAD_CAP bytes — ends at packet
        // boundary.  Second section starts fresh in the next packet with
        // PUSI=1, pointer_field=0.
        let body1 = vec![0xA1; PUSI_PAYLOAD_CAP - 3];
        let s1 = test_fixtures::psi::short_section(0x50, &body1);
        assert_eq!(s1.len(), PUSI_PAYLOAD_CAP);

        let s2 = test_fixtures::psi::long_section(0x52, 1, 0, 0, &[0xB1, 0xB2]);
        assert_round_trip(&[s1, s2]);
    }

    #[test]
    fn continuation_packet_never_overshoots_next_section_start() {
        // First section is 366 bytes total: it fills the first (PUSI) packet's
        // 183-byte payload exactly, then the *second* packet (a continuation,
        // starting at pos=183) is exactly 183 bytes short of the next
        // section's start (183 + 183 = 366) — the mid-stream analogue of
        // `round_trip_section_ends_exactly_at_boundary` above, which only
        // exercises the boundary at pos=0.
        let body1 = vec![0xA5; 366 - 3];
        let s1 = test_fixtures::psi::short_section(0x50, &body1);
        assert_eq!(s1.len(), 366);
        let s2 = test_fixtures::psi::long_section(0x52, 1, 0, 0, &[0xB1, 0xB2, 0xB3]);

        let mut packetiser = SectionPacketiser::new(Pid::from_const(0x0100));
        let packets = packetiser.packetise(&[s1.as_slice(), s2.as_slice()]);

        for pkt_raw in &packets {
            let pkt = TsPacket::parse(pkt_raw).expect("parse generated packet");
            let payload = pkt.payload.expect("payload present");
            if pkt.header.pusi {
                let pointer = payload[0] as usize;
                // W1 (#1074): pre-fix this was 183 — a pointer_field pointing
                // past the packet's own payload, so no section byte actually
                // starts within it.
                assert!(
                    pointer < PUSI_PAYLOAD_CAP,
                    "pointer_field {pointer} leaves no room for a section to \
                     start within this packet (H.222.0 §2.4.4)"
                );
            }
        }

        assert_round_trip(&[s1, s2]);
    }

    #[test]
    fn round_trip_mix_small_large_sections() {
        // Mix of small and spanning sections that stress pointer_field and
        // concatenation.
        let s1 = test_fixtures::psi::long_section(0x10, 1, 0, 0, &[0xAA; 5]);
        let body2 = vec![0xBB; 200];
        let s2 = test_fixtures::psi::short_section(0x20, &body2);
        let s3 = test_fixtures::psi::long_section(0x30, 1, 0, 0, &[0xCC; 50]);
        let body4 = vec![0xDD; 800];
        let s4 = test_fixtures::psi::short_section(0x40, &body4);
        let s5 = test_fixtures::psi::long_section(0x50, 1, 0, 0, &[0xEE]); // 1-byte body
        assert_round_trip(&[s1, s2, s3, s4, s5]);
    }

    // ── continuity counter ───────────────────────────────────────────────────

    #[test]
    fn continuity_counter_increments_per_packet() {
        // Use a section large enough to span several packets.
        let body = vec![0xAA; 500];
        let section = test_fixtures::psi::short_section(0x42, &body);
        let mut p = SectionPacketiser::new(Pid::from_const(0x0100));

        let packets = p.packetise(&[&section]);
        assert!(packets.len() >= 3, "need multiple packets to test CC");

        let mut last_cc: Option<ContinuityCounter> = None;
        for pkt_raw in &packets {
            let pkt = TsPacket::parse(pkt_raw).unwrap();
            let cc = pkt.header.continuity_counter;
            if let Some(last) = last_cc {
                assert_eq!(
                    cc.forward_distance_from(last),
                    1,
                    "CC must increment per packet"
                );
            }
            last_cc = Some(cc);
        }
    }

    #[test]
    fn continuity_counter_wraps_and_continues_across_calls() {
        let mut p = SectionPacketiser::with_continuity(Pid::from_const(0x0100), cc(14));
        // Section large enough to span at least 3 packets.
        let body = vec![0xBB; 500];
        let s = test_fixtures::psi::short_section(0x42, &body);

        // First call: CC 14, 15, 0, …
        let pkts1 = p.packetise(&[&s]);
        assert!(pkts1.len() >= 3, "section must span ≥3 packets");
        let ccs1: Vec<u8> = pkts1
            .iter()
            .map(|b| {
                TsPacket::parse(b)
                    .unwrap()
                    .header
                    .continuity_counter
                    .value()
            })
            .collect();
        assert_eq!(ccs1[0], 14);
        assert_eq!(ccs1[1], 15);
        assert_eq!(ccs1[2], 0);

        // Second call: CC continues from where first left off.
        let previous = ContinuityCounter::try_new(ccs1.last().copied().unwrap_or(0))
            .expect("the last emitted counter is 4-bit");
        let pkts2 = p.packetise(&[&s]);
        let cc_first_pkt2 = TsPacket::parse(&pkts2[0])
            .unwrap()
            .header
            .continuity_counter;
        assert_eq!(cc_first_pkt2.forward_distance_from(previous), 1);
    }

    // ── PUSI placement ──────────────────────────────────────────────────────

    #[test]
    fn pusi_set_when_section_starts() {
        let s = test_fixtures::psi::long_section(0x42, 1, 0, 0, &[0xAA; 10]);
        let mut p = SectionPacketiser::new(Pid::from_const(0x0100));
        let packets = p.packetise(&[&s]);
        assert!(!packets.is_empty());
        let pkt = TsPacket::parse(&packets[0]).unwrap();
        assert!(pkt.header.pusi, "first packet must have PUSI=1");
    }

    #[test]
    fn pusi_not_set_on_mid_section_continuation() {
        let body = vec![0xAA; 500];
        let s = test_fixtures::psi::short_section(0x42, &body);
        let mut p = SectionPacketiser::new(Pid::from_const(0x0100));
        let packets = p.packetise(&[&s]);
        assert!(packets.len() >= 2);
        let pkt1 = TsPacket::parse(&packets[0]).unwrap();
        let pkt2 = TsPacket::parse(&packets[1]).unwrap();
        assert!(pkt1.header.pusi, "first packet must have PUSI=1");
        assert!(
            !pkt2.header.pusi,
            "second packet is continuation, must have PUSI=0"
        );
    }

    #[test]
    fn pointer_field_equals_tail_length_before_new_section() {
        // Section1 = 200 bytes.  Section2 = 50 bytes.
        // Packet 1: PUSI=1, pointer=0, section1 head.
        // Packet 2: PUSI=1, pointer > 0 (tail of section1 before section2).
        let body1 = vec![0xA1; 197]; // 200-byte section
        let s1 = test_fixtures::psi::short_section(0x52, &body1);
        assert_eq!(s1.len(), 200);
        let s2 = test_fixtures::psi::long_section(0x54, 1, 0, 0, &[0xB1; 38]); // 50-byte section
        assert_eq!(s2.len(), 50);

        let mut p = SectionPacketiser::new(Pid::from_const(0x0100));
        let packets = p.packetise(&[&s1, &s2]);

        // Find the packet where PUSI=1 and pointer>0.
        let pkt_with_pointer = packets
            .iter()
            .map(|raw| TsPacket::parse(raw).unwrap())
            .find(|pkt| pkt.header.pusi && pkt.payload.is_some_and(|pl| pl.first() != Some(&0)))
            .expect("must have a PUSI packet with non-zero pointer");

        let payload = pkt_with_pointer.payload.unwrap();
        let pointer = payload[0] as usize;
        assert!(pointer > 0, "pointer must be non-zero");
        // The tail bytes should be from the end of section1.
        let tail_start = s1.len() - pointer;
        assert_eq!(&payload[1..1 + pointer], &s1[tail_start..]);
    }

    // ── stuffing ─────────────────────────────────────────────────────────────

    #[test]
    fn final_packet_unused_tail_is_stuffing() {
        let s = test_fixtures::psi::long_section(0x42, 1, 0, 0, &[0xAA; 5]); // 8 bytes total
        let mut p = SectionPacketiser::new(Pid::from_const(0x0100));
        let packets = p.packetise(&[&s]);

        let pkt = TsPacket::parse(&packets[0]).unwrap();
        let payload = pkt.payload.unwrap();
        assert_eq!(payload[0], 0, "pointer_field should be 0");

        let section_end = 1 + s.len(); // after pointer + section
        assert!(
            section_end < payload.len(),
            "must have stuffing after section"
        );
        for &b in &payload[section_end..] {
            assert_eq!(b, STUFFING_BYTE, "all trailing bytes must be 0xFF");
        }
    }

    #[test]
    fn reassembler_discards_stuffing() {
        let s1 = test_fixtures::psi::long_section(0x42, 1, 0, 0, &[0xAA; 10]);
        let s2 = test_fixtures::psi::long_section(0x46, 1, 0, 0, &[0xBB; 5]);

        let mut p = SectionPacketiser::new(Pid::from_const(0x0100));
        let packets = p.packetise(&[&s1, &s2]);

        let mut reasm = SectionReassembler::default();
        for pkt_raw in &packets {
            let pkt = TsPacket::parse(pkt_raw).unwrap();
            reasm.feed(pkt.payload.unwrap(), pkt.header.pusi);
        }

        let got: Vec<_> = core::iter::from_fn(|| reasm.pop_section()).collect();
        assert_eq!(got.len(), 2);
        assert!(
            reasm.is_empty(),
            "stuffing tail must be discarded, not buffered"
        );
    }

    // ── misc ─────────────────────────────────────────────────────────────────

    #[test]
    fn empty_batch_produces_no_packets() {
        let mut p = SectionPacketiser::new(Pid::from_const(0x0100));
        let packets: Vec<[u8; TS_PACKET_SIZE]> = p.packetise(&[]);
        assert!(packets.is_empty());
    }

    #[test]
    fn packetise_into_clears_out_first() {
        let s = test_fixtures::psi::long_section(0x42, 1, 0, 0, &[0xAA; 5]);
        let mut p = SectionPacketiser::new(Pid::from_const(0x0100));

        let mut out = vec![[0u8; TS_PACKET_SIZE]; 99]; // pre-existing junk
        let n = p.packetise_into(&[&s], &mut out);
        assert_eq!(n, out.len(), "out must contain only the new packets");
        // Verify the output is correct (round-trip).
        let mut reasm = SectionReassembler::default();
        for pkt_raw in &out {
            let pkt = TsPacket::parse(pkt_raw).unwrap();
            reasm.feed(pkt.payload.unwrap(), pkt.header.pusi);
        }
        let got = reasm.pop_section().unwrap();
        assert_eq!(got.as_ref(), s.as_slice());
    }

    #[test]
    fn pid_is_correct() {
        let p = SectionPacketiser::new(Pid::from_const(0x1234));
        assert_eq!(p.pid(), Pid::from_const(0x1234));
    }

    #[test]
    fn with_continuity_masks_to_4_bits() {
        let expected = ContinuityCounter::try_new(0x0E).expect("4-bit counter");
        let p = SectionPacketiser::with_continuity(Pid::from_const(0x0100), expected);
        assert_eq!(p.continuity_counter(), expected);
    }

    #[test]
    fn has_payload_always_true_no_adaptation() {
        let s = test_fixtures::psi::long_section(0x42, 1, 0, 0, &[0xAA; 50]);
        let mut p = SectionPacketiser::new(Pid::from_const(0x0100));
        let packets = p.packetise(&[&s]);
        for pkt_raw in &packets {
            let pkt = TsPacket::parse(pkt_raw).unwrap();
            assert!(pkt.header.has_payload(), "every packet must carry payload");
            assert!(
                !pkt.header.has_adaptation(),
                "no adaptation field is emitted"
            );
            assert!(!pkt.header.tei, "TEI must be false");
            assert_eq!(
                pkt.header.scrambling,
                ScramblingControl::NotScrambled,
                "scrambling must be 0"
            );
        }
    }
}