1use alloc::vec::Vec;
10
11use crate::pid::Pid;
12use crate::ts::{
13 AdaptationFieldControl, ContinuityCounter, ScramblingControl, TS_PACKET_SIZE, TsHeader,
14};
15
16const PUSI_PAYLOAD_CAP: usize = 183;
18const PAYLOAD_CAP: usize = 184;
20use crate::ts::STUFFING_BYTE;
21
22pub struct SectionPacketiser {
31 pid: Pid,
32 continuity_counter: ContinuityCounter,
33}
34
35impl SectionPacketiser {
36 pub fn new(pid: Pid) -> Self {
38 Self {
39 pid,
40 continuity_counter: ContinuityCounter::ZERO,
41 }
42 }
43
44 pub fn with_continuity(pid: Pid, cc: ContinuityCounter) -> Self {
46 Self {
47 pid,
48 continuity_counter: cc,
49 }
50 }
51
52 pub fn pid(&self) -> Pid {
54 self.pid
55 }
56
57 pub fn continuity_counter(&self) -> ContinuityCounter {
59 self.continuity_counter
60 }
61
62 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 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 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 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 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 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
180pub 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 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 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 #[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(§ions);
265 }
266
267 #[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); 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 #[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]); assert_round_trip(&[s]);
320 }
321
322 #[test]
323 fn round_trip_section_exactly_pusi_cap_boundary() {
324 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 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 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 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]); let s2 = test_fixtures::psi::long_section(0x46, 1, 0, 0, &[0x03]); let s3 = test_fixtures::psi::long_section(0x4A, 1, 0, 0, &[0x04, 0x05, 0x06]); assert_round_trip(&[s1, s2, s3]);
366 }
367
368 #[test]
369 fn round_trip_section_ends_exactly_at_boundary() {
370 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 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 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 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]); assert_round_trip(&[s1, s2, s3, s4, s5]);
428 }
429
430 #[test]
433 fn continuity_counter_increments_per_packet() {
434 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(&[§ion]);
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 let body = vec![0xBB; 500];
462 let s = test_fixtures::psi::short_section(0x42, &body);
463
464 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 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 #[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 let body1 = vec![0xA1; 197]; 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]); 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 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 let tail_start = s1.len() - pointer;
546 assert_eq!(&payload[1..1 + pointer], &s1[tail_start..]);
547 }
548
549 #[test]
552 fn final_packet_unused_tail_is_stuffing() {
553 let s = test_fixtures::psi::long_section(0x42, 1, 0, 0, &[0xAA; 5]); 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(); 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 #[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]; let n = p.packetise_into(&[&s], &mut out);
609 assert_eq!(n, out.len(), "out must contain only the new packets");
610 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}