Skip to main content

mpeg_ts/
mux.rs

1//! Section → TS packetiser (the byte-exact inverse of
2//! [`SectionReassembler::feed`](crate::ts::SectionReassembler::feed)).
3//!
4//! Per the PSI carriage rules of ITU-T H.222.0 §2.4.4 (= ISO/IEC 13818-1:2007 §2.4.4)
5//! (`private/specs-verified/mpeg/mpeg-ts/tables/h222_0/psi_section.md`): sections are packed into 188-byte packets
6//! with a `pointer_field` where sections begin, concatenated contiguously, and
7//! 0xFF-stuffed at the batch tail.
8
9use alloc::vec::Vec;
10
11use crate::pid::Pid;
12use crate::ts::{
13    AdaptationFieldControl, ContinuityCounter, ScramblingControl, TS_PACKET_SIZE, TsHeader,
14};
15
16/// Maximum data bytes in a PUSI=1 packet (188 − 4 header − 1 pointer_field). §2.4.4.
17const PUSI_PAYLOAD_CAP: usize = 183;
18/// Maximum data bytes in a continuation packet (188 − 4 header). §2.4.4.
19const PAYLOAD_CAP: usize = 184;
20use crate::ts::STUFFING_BYTE;
21
22/// Packetises PSI/SI sections into 188-byte TS packets.
23///
24/// This is the byte-exact inverse of
25/// [`SectionReassembler::feed`](crate::ts::SectionReassembler::feed): packets
26/// produced here, when fed back through the reassembler, yield the same
27/// sections in order.
28///
29/// ISO/IEC 13818-1:2007 §2.4.4 (`private/specs-verified/mpeg/mpeg-ts/tables/h222_0/psi_section.md`).
30pub struct SectionPacketiser {
31    pid: Pid,
32    continuity_counter: ContinuityCounter,
33}
34
35impl SectionPacketiser {
36    /// Start a packetiser for `pid` with continuity_counter = 0.
37    pub fn new(pid: Pid) -> Self {
38        Self {
39            pid,
40            continuity_counter: ContinuityCounter::ZERO,
41        }
42    }
43
44    /// Start at a specific continuity_counter — for resuming a stream.
45    pub fn with_continuity(pid: Pid, cc: ContinuityCounter) -> Self {
46        Self {
47            pid,
48            continuity_counter: cc,
49        }
50    }
51
52    /// The PID this packetiser emits packets for.
53    pub fn pid(&self) -> Pid {
54        self.pid
55    }
56
57    /// The continuity_counter for the next emitted packet.
58    pub fn continuity_counter(&self) -> ContinuityCounter {
59        self.continuity_counter
60    }
61
62    /// Packetise a batch of complete sections into 188-byte TS packets,
63    /// appended to `out` (cleared first).
64    ///
65    /// Returns the number of packets appended.
66    pub fn packetise_into(
67        &mut self,
68        sections: &[&[u8]],
69        out: &mut Vec<[u8; TS_PACKET_SIZE]>,
70    ) -> usize {
71        out.clear();
72
73        if sections.is_empty() {
74            return 0;
75        }
76
77        // Concatenate all sections and record section-start byte offsets.
78        let total_len: usize = sections.iter().map(|s| s.len()).sum();
79        if total_len == 0 {
80            return 0;
81        }
82        let mut data = Vec::with_capacity(total_len);
83        let mut starts = Vec::with_capacity(sections.len());
84        for s in sections {
85            starts.push(data.len());
86            data.extend_from_slice(s);
87        }
88
89        let count_before = out.len();
90        let mut pos = 0usize;
91        // `starts` is ascending and `pos` only advances, so a forward-only
92        // cursor finds the smallest section-start offset >= pos in amortised
93        // O(1) per packet instead of rescanning from the front (audit
94        // r01-O1: O(packets x sections)).
95        let mut next_idx = 0usize;
96
97        while pos < data.len() {
98            while starts.get(next_idx).is_some_and(|&s| s < pos) {
99                next_idx += 1;
100            }
101            let next_start = starts.get(next_idx).copied();
102
103            let pusi: bool;
104            let pointer_field: u8;
105            let cap: usize;
106
107            if let Some(ns) = next_start {
108                let diff = ns.saturating_sub(pos);
109                // W1 (#1074): `diff == PUSI_PAYLOAD_CAP` (183) must NOT take the
110                // PUSI branch — a pointer_field of 183 would claim a section
111                // starts after all 183 payload bytes, i.e. not within this
112                // packet at all (H.222.0 §2.4.4 requires PUSI=1 to mean a
113                // section genuinely starts here). The non-PUSI branch's cap
114                // must in turn be bounded by `diff`, not just the fixed
115                // 184-byte payload size, or a continuation packet at this same
116                // boundary copies one byte past the next section's start —
117                // the reassembler then silently drops it (it only takes what
118                // completes the in-progress section), corrupting the next one.
119                if diff < PUSI_PAYLOAD_CAP {
120                    pusi = true;
121                    pointer_field = diff as u8;
122                    cap = PUSI_PAYLOAD_CAP;
123                } else {
124                    pusi = false;
125                    pointer_field = 0;
126                    cap = PAYLOAD_CAP.min(diff);
127                }
128            } else {
129                pusi = false;
130                pointer_field = 0;
131                cap = PAYLOAD_CAP;
132            }
133
134            let mut pkt = [0u8; TS_PACKET_SIZE];
135
136            let header = TsHeader {
137                tei: false,
138                pusi,
139                pid: self.pid,
140                scrambling: ScramblingControl::NotScrambled,
141                adaptation_field_control: AdaptationFieldControl::PayloadOnly,
142                continuity_counter: self.continuity_counter,
143            };
144            pkt[..TsHeader::serialized_len()].copy_from_slice(&header.to_bytes());
145
146            self.continuity_counter = self.continuity_counter.next();
147
148            let mut write_pos = TsHeader::serialized_len();
149
150            if pusi {
151                pkt[write_pos] = pointer_field;
152                write_pos += 1;
153            }
154
155            let remaining = data.len() - pos;
156            let to_copy = remaining.min(cap);
157            pkt[write_pos..write_pos + to_copy].copy_from_slice(&data[pos..pos + to_copy]);
158            pos += to_copy;
159            write_pos += to_copy;
160
161            // 0xFF-stuff remaining payload bytes.
162            for b in &mut pkt[write_pos..] {
163                *b = STUFFING_BYTE;
164            }
165
166            out.push(pkt);
167        }
168
169        out.len() - count_before
170    }
171
172    /// Allocating convenience wrapper over [`packetise_into`](Self::packetise_into).
173    pub fn packetise(&mut self, sections: &[&[u8]]) -> Vec<[u8; TS_PACKET_SIZE]> {
174        let mut out = Vec::new();
175        self.packetise_into(sections, &mut out);
176        out
177    }
178}
179
180/// Split concatenated complete-section bytes into individual `&[u8]` slices.
181///
182/// Walks the PSI/SI section headers: byte 0 = table_id, bytes 1-2 =
183/// section_length (12 bits). Each slice is 3 + section_length bytes long.
184/// Trailing bytes that don't form a complete section header are discarded.
185/// The section scheduler in `dvb-si` registers one section per call and
186/// checks a caller's slice with this.
187pub fn split_sections(data: &[u8]) -> Vec<&[u8]> {
188    let mut result = Vec::new();
189    let mut pos = 0;
190    while let Some(end) = crate::ts::section_total_len(&data[pos..]).map(|len| pos + len) {
191        if end > data.len() {
192            break;
193        }
194        result.push(&data[pos..end]);
195        pos = end;
196    }
197    result
198}
199
200#[cfg(test)]
201mod tests {
202    use super::*;
203    use crate::ts::{SectionReassembler, TsPacket};
204    use alloc::vec;
205    use alloc::vec::Vec;
206
207    // ── helpers ──────────────────────────────────────────────────────────────
208
209    fn concat_sections(sections: &[Vec<u8>]) -> Vec<u8> {
210        let total: usize = sections.iter().map(|s| s.len()).sum();
211        let mut out = Vec::with_capacity(total);
212        for s in sections {
213            out.extend_from_slice(s);
214        }
215        out
216    }
217
218    /// Round-trip `sections` through packetise → reassembler, asserting
219    /// byte-identical output in order and no leftovers.
220    fn assert_round_trip(sections: &[Vec<u8>]) {
221        let mut packetiser = SectionPacketiser::new(Pid::from_const(0x0100));
222        let refs: Vec<&[u8]> = sections.iter().map(|s| s.as_slice()).collect();
223        let packets = packetiser.packetise(&refs);
224
225        let mut reasm = SectionReassembler::default();
226        for pkt_raw in &packets {
227            let pkt = TsPacket::parse(pkt_raw).expect("parse generated packet");
228            let payload = pkt.payload.expect("payload present");
229            let pusi = pkt.header.pusi;
230            reasm.feed(payload, pusi);
231        }
232
233        let got: Vec<_> = core::iter::from_fn(|| reasm.pop_section()).collect();
234        assert_eq!(
235            got.len(),
236            sections.len(),
237            "section count mismatch: expected {}, got {}",
238            sections.len(),
239            got.len()
240        );
241        for (i, (orig, round)) in sections.iter().zip(got.iter()).enumerate() {
242            assert_eq!(
243                round.as_ref(),
244                orig.as_slice(),
245                "section {i} round-trip mismatch"
246            );
247        }
248        assert!(reasm.is_empty(), "reassembler should be empty after drain");
249    }
250
251    /// 400 sections whose sizes sweep 0..=399 body bytes (so section starts
252    /// land on every offset around the 183/184-byte packet boundaries)
253    /// round-trip byte-identically through packetise -> reassemble (audit
254    /// r01-O1: the section-start lookup is now a forward cursor; this is the
255    /// independent oracle that the rewrite chose the same boundaries).
256    #[test]
257    fn many_sections_with_boundary_straddling_sizes_round_trip() {
258        let sections: Vec<Vec<u8>> = (0..400usize)
259            .map(|n| {
260                let body: Vec<u8> = (0..n).map(|i| (i % 251) as u8).collect();
261                test_fixtures::psi::short_section((n % 200) as u8, &body)
262            })
263            .collect();
264        assert_round_trip(&sections);
265    }
266
267    // ── split_sections ──────────────────────────────────────────────────────
268
269    #[test]
270    fn split_single_section() {
271        let s = test_fixtures::psi::long_section(0x42, 1, 0, 0, &[0xAA; 5]);
272        let refs = split_sections(&s);
273        assert_eq!(refs.len(), 1);
274        assert_eq!(refs[0], s.as_slice());
275    }
276
277    #[test]
278    fn split_two_sections() {
279        let s1 = test_fixtures::psi::long_section(0x42, 1, 0, 0, &[0x01, 0x02]);
280        let s2 = test_fixtures::psi::long_section(0x46, 1, 0, 0, &[0x03, 0x04, 0x05]);
281        let both = concat_sections(&[s1.clone(), s2.clone()]);
282        let refs = split_sections(&both);
283        assert_eq!(refs.len(), 2);
284        assert_eq!(refs[0], s1.as_slice());
285        assert_eq!(refs[1], s2.as_slice());
286    }
287
288    #[test]
289    fn split_empty_input() {
290        let refs = split_sections(&[]);
291        assert!(refs.is_empty());
292    }
293
294    #[test]
295    fn split_trailing_garbage_ignored() {
296        let s = test_fixtures::psi::long_section(0x42, 1, 0, 0, &[0xAA; 3]);
297        let mut data = s.clone();
298        data.push(0xFF); // trailing byte that doesn't complete a header
299        let refs = split_sections(&data);
300        assert_eq!(refs.len(), 1);
301        assert_eq!(refs[0], s.as_slice());
302    }
303
304    fn cc(v: u8) -> ContinuityCounter {
305        ContinuityCounter::try_new(v).expect("4-bit counter")
306    }
307
308    // ── round-trip property (the mandatory acceptance oracle) ────────────────
309
310    #[test]
311    fn round_trip_single_short_section() {
312        let s = test_fixtures::psi::long_section(0x42, 1, 0, 0, &[0xAA; 10]);
313        assert_round_trip(&[s]);
314    }
315
316    #[test]
317    fn round_trip_one_byte_body() {
318        let s = test_fixtures::psi::long_section(0x46, 1, 0, 0, &[0xBB]); // 4 bytes total
319        assert_round_trip(&[s]);
320    }
321
322    #[test]
323    fn round_trip_section_exactly_pusi_cap_boundary() {
324        // A section whose total length is exactly PUSI_PAYLOAD_CAP (183).
325        let body = vec![0xCC; PUSI_PAYLOAD_CAP - 3];
326        let s = test_fixtures::psi::short_section(0x50, &body);
327        assert_eq!(s.len(), PUSI_PAYLOAD_CAP);
328        assert_round_trip(&[s]);
329    }
330
331    #[test]
332    fn round_trip_section_just_over_pusi_cap() {
333        // One byte more than fits in a PUSI packet → must span to continuation.
334        let body = vec![0xDD; PUSI_PAYLOAD_CAP - 3 + 1];
335        let s = test_fixtures::psi::short_section(0x52, &body);
336        assert_eq!(s.len(), PUSI_PAYLOAD_CAP + 1);
337        assert_round_trip(&[s]);
338    }
339
340    #[test]
341    fn round_trip_section_spans_many_packets() {
342        // A 2000-byte section spans ~11 packets.
343        let body = vec![0xEE; 2000 - 3];
344        let s = test_fixtures::psi::short_section(0x60, &body);
345        assert_round_trip(&[s]);
346    }
347
348    #[test]
349    fn round_trip_section_at_max_size() {
350        // The maximum section (4096 total, the long-form ceiling), whose final
351        // continuation packet carries the tail followed by 0xFF stuffing. Since
352        // #148 the reassembler ignores that trailing stuffing instead of
353        // counting it toward MAX_SECTION_SIZE, so a full-size section round-trips.
354        let body = vec![0x11; 4096 - 3];
355        let s = test_fixtures::psi::short_section(0x80, &body);
356        assert_eq!(s.len(), 4096);
357        assert_round_trip(&[s]);
358    }
359
360    #[test]
361    fn round_trip_multiple_short_sections_in_one_batch() {
362        let s1 = test_fixtures::psi::long_section(0x42, 1, 0, 0, &[0x01, 0x02]); // 5 bytes
363        let s2 = test_fixtures::psi::long_section(0x46, 1, 0, 0, &[0x03]); // 4 bytes
364        let s3 = test_fixtures::psi::long_section(0x4A, 1, 0, 0, &[0x04, 0x05, 0x06]); // 6 bytes
365        assert_round_trip(&[s1, s2, s3]);
366    }
367
368    #[test]
369    fn round_trip_section_ends_exactly_at_boundary() {
370        // First section is exactly PUSI_PAYLOAD_CAP bytes — ends at packet
371        // boundary.  Second section starts fresh in the next packet with
372        // PUSI=1, pointer_field=0.
373        let body1 = vec![0xA1; PUSI_PAYLOAD_CAP - 3];
374        let s1 = test_fixtures::psi::short_section(0x50, &body1);
375        assert_eq!(s1.len(), PUSI_PAYLOAD_CAP);
376
377        let s2 = test_fixtures::psi::long_section(0x52, 1, 0, 0, &[0xB1, 0xB2]);
378        assert_round_trip(&[s1, s2]);
379    }
380
381    #[test]
382    fn continuation_packet_never_overshoots_next_section_start() {
383        // First section is 366 bytes total: it fills the first (PUSI) packet's
384        // 183-byte payload exactly, then the *second* packet (a continuation,
385        // starting at pos=183) is exactly 183 bytes short of the next
386        // section's start (183 + 183 = 366) — the mid-stream analogue of
387        // `round_trip_section_ends_exactly_at_boundary` above, which only
388        // exercises the boundary at pos=0.
389        let body1 = vec![0xA5; 366 - 3];
390        let s1 = test_fixtures::psi::short_section(0x50, &body1);
391        assert_eq!(s1.len(), 366);
392        let s2 = test_fixtures::psi::long_section(0x52, 1, 0, 0, &[0xB1, 0xB2, 0xB3]);
393
394        let mut packetiser = SectionPacketiser::new(Pid::from_const(0x0100));
395        let packets = packetiser.packetise(&[s1.as_slice(), s2.as_slice()]);
396
397        for pkt_raw in &packets {
398            let pkt = TsPacket::parse(pkt_raw).expect("parse generated packet");
399            let payload = pkt.payload.expect("payload present");
400            if pkt.header.pusi {
401                let pointer = payload[0] as usize;
402                // W1 (#1074): pre-fix this was 183 — a pointer_field pointing
403                // past the packet's own payload, so no section byte actually
404                // starts within it.
405                assert!(
406                    pointer < PUSI_PAYLOAD_CAP,
407                    "pointer_field {pointer} leaves no room for a section to \
408                     start within this packet (H.222.0 §2.4.4)"
409                );
410            }
411        }
412
413        assert_round_trip(&[s1, s2]);
414    }
415
416    #[test]
417    fn round_trip_mix_small_large_sections() {
418        // Mix of small and spanning sections that stress pointer_field and
419        // concatenation.
420        let s1 = test_fixtures::psi::long_section(0x10, 1, 0, 0, &[0xAA; 5]);
421        let body2 = vec![0xBB; 200];
422        let s2 = test_fixtures::psi::short_section(0x20, &body2);
423        let s3 = test_fixtures::psi::long_section(0x30, 1, 0, 0, &[0xCC; 50]);
424        let body4 = vec![0xDD; 800];
425        let s4 = test_fixtures::psi::short_section(0x40, &body4);
426        let s5 = test_fixtures::psi::long_section(0x50, 1, 0, 0, &[0xEE]); // 1-byte body
427        assert_round_trip(&[s1, s2, s3, s4, s5]);
428    }
429
430    // ── continuity counter ───────────────────────────────────────────────────
431
432    #[test]
433    fn continuity_counter_increments_per_packet() {
434        // Use a section large enough to span several packets.
435        let body = vec![0xAA; 500];
436        let section = test_fixtures::psi::short_section(0x42, &body);
437        let mut p = SectionPacketiser::new(Pid::from_const(0x0100));
438
439        let packets = p.packetise(&[&section]);
440        assert!(packets.len() >= 3, "need multiple packets to test CC");
441
442        let mut last_cc: Option<ContinuityCounter> = None;
443        for pkt_raw in &packets {
444            let pkt = TsPacket::parse(pkt_raw).unwrap();
445            let cc = pkt.header.continuity_counter;
446            if let Some(last) = last_cc {
447                assert_eq!(
448                    cc.forward_distance_from(last),
449                    1,
450                    "CC must increment per packet"
451                );
452            }
453            last_cc = Some(cc);
454        }
455    }
456
457    #[test]
458    fn continuity_counter_wraps_and_continues_across_calls() {
459        let mut p = SectionPacketiser::with_continuity(Pid::from_const(0x0100), cc(14));
460        // Section large enough to span at least 3 packets.
461        let body = vec![0xBB; 500];
462        let s = test_fixtures::psi::short_section(0x42, &body);
463
464        // First call: CC 14, 15, 0, …
465        let pkts1 = p.packetise(&[&s]);
466        assert!(pkts1.len() >= 3, "section must span ≥3 packets");
467        let ccs1: Vec<u8> = pkts1
468            .iter()
469            .map(|b| {
470                TsPacket::parse(b)
471                    .unwrap()
472                    .header
473                    .continuity_counter
474                    .value()
475            })
476            .collect();
477        assert_eq!(ccs1[0], 14);
478        assert_eq!(ccs1[1], 15);
479        assert_eq!(ccs1[2], 0);
480
481        // Second call: CC continues from where first left off.
482        let previous = ContinuityCounter::try_new(ccs1.last().copied().unwrap_or(0))
483            .expect("the last emitted counter is 4-bit");
484        let pkts2 = p.packetise(&[&s]);
485        let cc_first_pkt2 = TsPacket::parse(&pkts2[0])
486            .unwrap()
487            .header
488            .continuity_counter;
489        assert_eq!(cc_first_pkt2.forward_distance_from(previous), 1);
490    }
491
492    // ── PUSI placement ──────────────────────────────────────────────────────
493
494    #[test]
495    fn pusi_set_when_section_starts() {
496        let s = test_fixtures::psi::long_section(0x42, 1, 0, 0, &[0xAA; 10]);
497        let mut p = SectionPacketiser::new(Pid::from_const(0x0100));
498        let packets = p.packetise(&[&s]);
499        assert!(!packets.is_empty());
500        let pkt = TsPacket::parse(&packets[0]).unwrap();
501        assert!(pkt.header.pusi, "first packet must have PUSI=1");
502    }
503
504    #[test]
505    fn pusi_not_set_on_mid_section_continuation() {
506        let body = vec![0xAA; 500];
507        let s = test_fixtures::psi::short_section(0x42, &body);
508        let mut p = SectionPacketiser::new(Pid::from_const(0x0100));
509        let packets = p.packetise(&[&s]);
510        assert!(packets.len() >= 2);
511        let pkt1 = TsPacket::parse(&packets[0]).unwrap();
512        let pkt2 = TsPacket::parse(&packets[1]).unwrap();
513        assert!(pkt1.header.pusi, "first packet must have PUSI=1");
514        assert!(
515            !pkt2.header.pusi,
516            "second packet is continuation, must have PUSI=0"
517        );
518    }
519
520    #[test]
521    fn pointer_field_equals_tail_length_before_new_section() {
522        // Section1 = 200 bytes.  Section2 = 50 bytes.
523        // Packet 1: PUSI=1, pointer=0, section1 head.
524        // Packet 2: PUSI=1, pointer > 0 (tail of section1 before section2).
525        let body1 = vec![0xA1; 197]; // 200-byte section
526        let s1 = test_fixtures::psi::short_section(0x52, &body1);
527        assert_eq!(s1.len(), 200);
528        let s2 = test_fixtures::psi::long_section(0x54, 1, 0, 0, &[0xB1; 38]); // 50-byte section
529        assert_eq!(s2.len(), 50);
530
531        let mut p = SectionPacketiser::new(Pid::from_const(0x0100));
532        let packets = p.packetise(&[&s1, &s2]);
533
534        // Find the packet where PUSI=1 and pointer>0.
535        let pkt_with_pointer = packets
536            .iter()
537            .map(|raw| TsPacket::parse(raw).unwrap())
538            .find(|pkt| pkt.header.pusi && pkt.payload.is_some_and(|pl| pl.first() != Some(&0)))
539            .expect("must have a PUSI packet with non-zero pointer");
540
541        let payload = pkt_with_pointer.payload.unwrap();
542        let pointer = payload[0] as usize;
543        assert!(pointer > 0, "pointer must be non-zero");
544        // The tail bytes should be from the end of section1.
545        let tail_start = s1.len() - pointer;
546        assert_eq!(&payload[1..1 + pointer], &s1[tail_start..]);
547    }
548
549    // ── stuffing ─────────────────────────────────────────────────────────────
550
551    #[test]
552    fn final_packet_unused_tail_is_stuffing() {
553        let s = test_fixtures::psi::long_section(0x42, 1, 0, 0, &[0xAA; 5]); // 8 bytes total
554        let mut p = SectionPacketiser::new(Pid::from_const(0x0100));
555        let packets = p.packetise(&[&s]);
556
557        let pkt = TsPacket::parse(&packets[0]).unwrap();
558        let payload = pkt.payload.unwrap();
559        assert_eq!(payload[0], 0, "pointer_field should be 0");
560
561        let section_end = 1 + s.len(); // after pointer + section
562        assert!(
563            section_end < payload.len(),
564            "must have stuffing after section"
565        );
566        for &b in &payload[section_end..] {
567            assert_eq!(b, STUFFING_BYTE, "all trailing bytes must be 0xFF");
568        }
569    }
570
571    #[test]
572    fn reassembler_discards_stuffing() {
573        let s1 = test_fixtures::psi::long_section(0x42, 1, 0, 0, &[0xAA; 10]);
574        let s2 = test_fixtures::psi::long_section(0x46, 1, 0, 0, &[0xBB; 5]);
575
576        let mut p = SectionPacketiser::new(Pid::from_const(0x0100));
577        let packets = p.packetise(&[&s1, &s2]);
578
579        let mut reasm = SectionReassembler::default();
580        for pkt_raw in &packets {
581            let pkt = TsPacket::parse(pkt_raw).unwrap();
582            reasm.feed(pkt.payload.unwrap(), pkt.header.pusi);
583        }
584
585        let got: Vec<_> = core::iter::from_fn(|| reasm.pop_section()).collect();
586        assert_eq!(got.len(), 2);
587        assert!(
588            reasm.is_empty(),
589            "stuffing tail must be discarded, not buffered"
590        );
591    }
592
593    // ── misc ─────────────────────────────────────────────────────────────────
594
595    #[test]
596    fn empty_batch_produces_no_packets() {
597        let mut p = SectionPacketiser::new(Pid::from_const(0x0100));
598        let packets: Vec<[u8; TS_PACKET_SIZE]> = p.packetise(&[]);
599        assert!(packets.is_empty());
600    }
601
602    #[test]
603    fn packetise_into_clears_out_first() {
604        let s = test_fixtures::psi::long_section(0x42, 1, 0, 0, &[0xAA; 5]);
605        let mut p = SectionPacketiser::new(Pid::from_const(0x0100));
606
607        let mut out = vec![[0u8; TS_PACKET_SIZE]; 99]; // pre-existing junk
608        let n = p.packetise_into(&[&s], &mut out);
609        assert_eq!(n, out.len(), "out must contain only the new packets");
610        // Verify the output is correct (round-trip).
611        let mut reasm = SectionReassembler::default();
612        for pkt_raw in &out {
613            let pkt = TsPacket::parse(pkt_raw).unwrap();
614            reasm.feed(pkt.payload.unwrap(), pkt.header.pusi);
615        }
616        let got = reasm.pop_section().unwrap();
617        assert_eq!(got.as_ref(), s.as_slice());
618    }
619
620    #[test]
621    fn pid_is_correct() {
622        let p = SectionPacketiser::new(Pid::from_const(0x1234));
623        assert_eq!(p.pid(), Pid::from_const(0x1234));
624    }
625
626    #[test]
627    fn with_continuity_masks_to_4_bits() {
628        let expected = ContinuityCounter::try_new(0x0E).expect("4-bit counter");
629        let p = SectionPacketiser::with_continuity(Pid::from_const(0x0100), expected);
630        assert_eq!(p.continuity_counter(), expected);
631    }
632
633    #[test]
634    fn has_payload_always_true_no_adaptation() {
635        let s = test_fixtures::psi::long_section(0x42, 1, 0, 0, &[0xAA; 50]);
636        let mut p = SectionPacketiser::new(Pid::from_const(0x0100));
637        let packets = p.packetise(&[&s]);
638        for pkt_raw in &packets {
639            let pkt = TsPacket::parse(pkt_raw).unwrap();
640            assert!(pkt.header.has_payload(), "every packet must carry payload");
641            assert!(
642                !pkt.header.has_adaptation(),
643                "no adaptation field is emitted"
644            );
645            assert!(!pkt.header.tei, "TEI must be false");
646            assert_eq!(
647                pkt.header.scrambling,
648                ScramblingControl::NotScrambled,
649                "scrambling must be 0"
650            );
651        }
652    }
653}