1use alloc::vec::Vec;
10use core::time::Duration;
11
12use broadcast_common::Parse;
13use broadcast_common::stage::Timestamp;
14
15use crate::pid::{Pid, well_known};
16use crate::section::Section;
17use crate::ts::{
18 AdaptationFieldControl, ContinuityCounter, ScramblingControl, TS_PACKET_SIZE, TsHeader,
19};
20
21pub const TABLE_ID_PAT: u8 = 0x00;
23pub const TABLE_ID_PMT: u8 = 0x02;
25pub const TABLE_ID_NIT_ACTUAL: u8 = 0x40;
27pub const TABLE_ID_SDT_ACTUAL: u8 = 0x42;
29pub const TABLE_ID_TDT: u8 = 0x70;
31pub const TABLE_ID_TOT: u8 = 0x73;
33
34const PUSI_PAYLOAD_CAP: usize = 183;
36const PAYLOAD_CAP: usize = 184;
38use crate::ts::STUFFING_BYTE;
39
40pub struct SectionPacketiser {
49 pid: Pid,
50 continuity_counter: ContinuityCounter,
51}
52
53impl SectionPacketiser {
54 pub fn new(pid: Pid) -> Self {
56 Self {
57 pid,
58 continuity_counter: ContinuityCounter::ZERO,
59 }
60 }
61
62 pub fn with_continuity(pid: Pid, cc: ContinuityCounter) -> Self {
64 Self {
65 pid,
66 continuity_counter: cc,
67 }
68 }
69
70 pub fn pid(&self) -> Pid {
72 self.pid
73 }
74
75 pub fn continuity_counter(&self) -> ContinuityCounter {
77 self.continuity_counter
78 }
79
80 pub fn packetise_into(
85 &mut self,
86 sections: &[&[u8]],
87 out: &mut Vec<[u8; TS_PACKET_SIZE]>,
88 ) -> usize {
89 out.clear();
90
91 if sections.is_empty() {
92 return 0;
93 }
94
95 let total_len: usize = sections.iter().map(|s| s.len()).sum();
97 if total_len == 0 {
98 return 0;
99 }
100 let mut data = Vec::with_capacity(total_len);
101 let mut starts = Vec::with_capacity(sections.len());
102 for s in sections {
103 starts.push(data.len());
104 data.extend_from_slice(s);
105 }
106
107 let count_before = out.len();
108 let mut pos = 0usize;
109 let mut next_idx = 0usize;
114
115 while pos < data.len() {
116 while starts.get(next_idx).is_some_and(|&s| s < pos) {
117 next_idx += 1;
118 }
119 let next_start = starts.get(next_idx).copied();
120
121 let pusi: bool;
122 let pointer_field: u8;
123 let cap: usize;
124
125 if let Some(ns) = next_start {
126 let diff = ns.saturating_sub(pos);
127 if diff < PUSI_PAYLOAD_CAP {
138 pusi = true;
139 pointer_field = diff as u8;
140 cap = PUSI_PAYLOAD_CAP;
141 } else {
142 pusi = false;
143 pointer_field = 0;
144 cap = PAYLOAD_CAP.min(diff);
145 }
146 } else {
147 pusi = false;
148 pointer_field = 0;
149 cap = PAYLOAD_CAP;
150 }
151
152 let mut pkt = [0u8; TS_PACKET_SIZE];
153
154 let header = TsHeader {
155 tei: false,
156 pusi,
157 pid: self.pid,
158 scrambling: ScramblingControl::NotScrambled,
159 adaptation_field_control: AdaptationFieldControl::PayloadOnly,
160 continuity_counter: self.continuity_counter,
161 };
162 pkt[..4].copy_from_slice(&header.to_bytes());
163
164 self.continuity_counter = self.continuity_counter.next();
165
166 let mut write_pos = 4usize;
167
168 if pusi {
169 pkt[write_pos] = pointer_field;
170 write_pos += 1;
171 }
172
173 let remaining = data.len() - pos;
174 let to_copy = remaining.min(cap);
175 pkt[write_pos..write_pos + to_copy].copy_from_slice(&data[pos..pos + to_copy]);
176 pos += to_copy;
177 write_pos += to_copy;
178
179 for b in &mut pkt[write_pos..] {
181 *b = STUFFING_BYTE;
182 }
183
184 out.push(pkt);
185 }
186
187 out.len() - count_before
188 }
189
190 pub fn packetise(&mut self, sections: &[&[u8]]) -> Vec<[u8; TS_PACKET_SIZE]> {
192 let mut out = Vec::new();
193 self.packetise_into(sections, &mut out);
194 out
195 }
196}
197
198pub const NIT_MAX_INTERVAL: SectionInterval = SectionInterval::from_const(Duration::from_secs(10));
202pub const BAT_MAX_INTERVAL: SectionInterval = SectionInterval::from_const(Duration::from_secs(10));
204pub const SDT_ACTUAL_MAX_INTERVAL: SectionInterval =
206 SectionInterval::from_const(Duration::from_secs(2));
207pub const SDT_OTHER_MAX_INTERVAL: SectionInterval =
209 SectionInterval::from_const(Duration::from_secs(10));
210pub const EIT_PF_ACTUAL_MAX_INTERVAL: SectionInterval =
212 SectionInterval::from_const(Duration::from_secs(2));
213pub const EIT_PF_OTHER_MAX_INTERVAL: SectionInterval =
216 SectionInterval::from_const(Duration::from_secs(10));
217pub const EIT_SCHED_MAX_INTERVAL: SectionInterval =
219 SectionInterval::from_const(Duration::from_secs(10));
220pub const EIT_SCHED_EXT_MAX_INTERVAL: SectionInterval =
222 SectionInterval::from_const(Duration::from_secs(30));
223pub const TDT_MAX_INTERVAL: SectionInterval = SectionInterval::from_const(Duration::from_secs(30));
225pub const TOT_MAX_INTERVAL: SectionInterval = SectionInterval::from_const(Duration::from_secs(30));
227
228#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
235#[cfg_attr(feature = "serde", derive(serde::Serialize))]
236#[cfg_attr(feature = "serde", serde(transparent))]
237pub struct SectionInterval(Duration);
238
239#[derive(Debug, Clone, Copy, PartialEq, Eq)]
241#[non_exhaustive]
242pub struct SectionIntervalTooShort {
243 pub interval: Duration,
245 pub min: Duration,
247}
248
249impl core::fmt::Display for SectionIntervalTooShort {
250 fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
251 write!(
252 f,
253 "section interval {:?} is below the {:?} minimum (EN 300 468 §5.1.4.1)",
254 self.interval, self.min
255 )
256 }
257}
258
259impl core::error::Error for SectionIntervalTooShort {}
260
261impl SectionInterval {
262 pub const fn try_new(
267 interval: Duration,
268 ) -> core::result::Result<Self, SectionIntervalTooShort> {
269 if interval.as_nanos() < MIN_SECTION_INTERVAL_NANOS {
271 Err(SectionIntervalTooShort {
272 interval,
273 min: MIN_SECTION_INTERVAL,
274 })
275 } else {
276 Ok(Self(interval))
277 }
278 }
279
280 #[must_use]
287 pub const fn from_const(interval: Duration) -> Self {
288 assert!(
289 interval.as_nanos() >= MIN_SECTION_INTERVAL_NANOS,
290 "named section interval is below the 25 ms minimum (EN 300 468 §5.1.4.1)"
291 );
292 Self(interval)
293 }
294
295 #[must_use]
297 pub const fn duration(self) -> Duration {
298 self.0
299 }
300}
301
302impl TryFrom<Duration> for SectionInterval {
303 type Error = SectionIntervalTooShort;
304 fn try_from(interval: Duration) -> core::result::Result<Self, Self::Error> {
305 Self::try_new(interval)
306 }
307}
308
309impl From<SectionInterval> for Duration {
310 fn from(interval: SectionInterval) -> Self {
311 interval.0
312 }
313}
314
315pub const MIN_SECTION_INTERVAL: Duration = Duration::from_millis(25);
318const MIN_SECTION_INTERVAL_NANOS: u128 = 25_000_000;
320
321pub const PAT_MAX_INTERVAL: SectionInterval =
323 SectionInterval::from_const(Duration::from_millis(100));
324pub const PMT_MAX_INTERVAL: SectionInterval =
326 SectionInterval::from_const(Duration::from_millis(100));
327
328#[non_exhaustive]
338#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
339#[cfg_attr(feature = "serde", derive(serde::Serialize))]
340pub struct SectionKey {
341 pub pid: Pid,
343 pub table_id: u8,
345 pub section_number: u8,
347}
348
349#[non_exhaustive]
356#[derive(Debug, Clone, PartialEq, Eq)]
357#[cfg_attr(feature = "serde", derive(serde::Serialize))]
358pub struct RejectedSection {
359 pub pid: Pid,
361 pub reason: SectionRejection,
363}
364
365#[non_exhaustive]
368#[derive(Debug, Clone, Copy, PartialEq, Eq)]
369#[cfg_attr(feature = "serde", derive(serde::Serialize))]
370pub enum SectionRejection {
371 NotASection,
376 MoreThanOneSection,
379 DuplicateSection,
382 Malformed,
384 WrongTableId {
387 expected: u8,
389 found: Option<u8>,
391 },
392}
393
394impl SectionRejection {
395 #[must_use]
397 pub fn name(&self) -> &'static str {
398 match self {
399 SectionRejection::NotASection => "not_a_section",
400 SectionRejection::MoreThanOneSection => "more_than_one_section",
401 SectionRejection::DuplicateSection => "duplicate_section",
402 SectionRejection::Malformed => "malformed",
403 SectionRejection::WrongTableId { .. } => "wrong_table_id",
404 }
405 }
406}
407
408broadcast_common::impl_spec_display!(SectionRejection);
409
410pub struct SiMux {
437 entries: Vec<Entry>,
438 rejected: Vec<RejectedSection>,
439 packetisers: Vec<SectionPacketiser>,
441}
442
443struct Entry {
444 key: SectionKey,
445 section: Section<'static>,
446 interval: SectionInterval,
447 last_emit: Option<Timestamp>,
448}
449
450fn packetiser_for(packetisers: &mut Vec<SectionPacketiser>, pid: Pid) -> &mut SectionPacketiser {
454 if let Some(idx) = packetisers.iter().position(|p| p.pid() == pid) {
455 &mut packetisers[idx]
456 } else {
457 packetisers.push(SectionPacketiser::new(pid));
458 let last = packetisers.len() - 1;
459 &mut packetisers[last]
460 }
461}
462
463impl SiMux {
464 pub fn new() -> Self {
466 Self {
467 entries: Vec::new(),
468 rejected: Vec::new(),
469 packetisers: Vec::new(),
470 }
471 }
472
473 pub fn upsert(
493 &mut self,
494 pid: Pid,
495 section: Vec<u8>,
496 interval: SectionInterval,
497 ) -> core::result::Result<(), SectionRejection> {
498 let rejection = self.register(pid, section, interval);
499 match rejection {
500 Some(reason) => {
501 self.rejected.push(RejectedSection { pid, reason });
502 Err(reason)
503 }
504 None => Ok(()),
505 }
506 }
507
508 fn register(
511 &mut self,
512 pid: Pid,
513 section: Vec<u8>,
514 interval: SectionInterval,
515 ) -> Option<SectionRejection> {
516 let batch = split_sections(§ion);
517 let owned = match batch.len() {
518 0 => return Some(SectionRejection::NotASection),
519 1 => match Section::parse(batch[0]) {
520 Ok(parsed) => parsed,
521 Err(_) => return Some(SectionRejection::Malformed),
522 },
523 _ => {
524 if !sections_are_distinct(&batch) {
525 return Some(SectionRejection::DuplicateSection);
526 }
527 return Some(SectionRejection::MoreThanOneSection);
528 }
529 };
530 let key = SectionKey {
531 pid,
532 table_id: owned.table_id,
533 section_number: owned.section_number,
534 };
535 let stored = Section::into_owned(owned);
536 if let Some(entry) = self.entries.iter_mut().find(|e| e.key == key) {
537 entry.section = stored;
538 entry.interval = interval;
539 } else {
540 self.entries.push(Entry {
541 key,
542 section: stored,
543 interval,
544 last_emit: None,
545 });
546 }
547 None
548 }
549
550 #[must_use]
555 pub fn rejected(&self) -> &[RejectedSection] {
556 &self.rejected
557 }
558
559 pub fn upsert_pat(&mut self, section: Vec<u8>) -> core::result::Result<(), SectionRejection> {
565 upsert_checked(
566 self,
567 well_known::PAT,
568 section,
569 PAT_MAX_INTERVAL,
570 TABLE_ID_PAT,
571 )
572 }
573
574 pub fn upsert_pmt(
583 &mut self,
584 pid: Pid,
585 section: Vec<u8>,
586 ) -> core::result::Result<(), SectionRejection> {
587 upsert_checked(self, pid, section, PMT_MAX_INTERVAL, TABLE_ID_PMT)
588 }
589
590 pub fn upsert_sdt_actual(
598 &mut self,
599 section: Vec<u8>,
600 ) -> core::result::Result<(), SectionRejection> {
601 upsert_checked(
602 self,
603 well_known::SDT_BAT,
604 section,
605 SDT_ACTUAL_MAX_INTERVAL,
606 TABLE_ID_SDT_ACTUAL,
607 )
608 }
609
610 pub fn upsert_nit(&mut self, section: Vec<u8>) -> core::result::Result<(), SectionRejection> {
616 upsert_checked(
617 self,
618 well_known::NIT,
619 section,
620 NIT_MAX_INTERVAL,
621 TABLE_ID_NIT_ACTUAL,
622 )
623 }
624
625 pub fn upsert_tdt(&mut self, section: Vec<u8>) -> core::result::Result<(), SectionRejection> {
633 upsert_checked(
634 self,
635 well_known::TDT_TOT,
636 section,
637 TDT_MAX_INTERVAL,
638 TABLE_ID_TDT,
639 )
640 }
641
642 pub fn upsert_tot(&mut self, section: Vec<u8>) -> core::result::Result<(), SectionRejection> {
650 upsert_checked(
651 self,
652 well_known::TDT_TOT,
653 section,
654 TOT_MAX_INTERVAL,
655 TABLE_ID_TOT,
656 )
657 }
658
659 pub fn poll_into(&mut self, now: Timestamp, out: &mut Vec<[u8; TS_PACKET_SIZE]>) -> usize {
666 out.clear();
667 let before = out.len();
668
669 let packetisers = &mut self.packetisers;
670 for entry in &mut self.entries {
671 let due = match entry.last_emit {
672 None => true,
673 Some(last) => now.saturating_sub(last) >= entry.interval.duration(),
674 };
675 if due {
676 let mut tmp = Vec::new();
677 if let Ok(bytes) = entry.section.serialize() {
678 let refs: [&[u8]; 1] = [&bytes];
679 let packetiser = packetiser_for(packetisers, entry.key.pid);
680 packetiser.packetise_into(&refs, &mut tmp);
681 }
682 out.append(&mut tmp);
683 entry.last_emit = Some(now);
684 }
685 }
686
687 out.len() - before
688 }
689
690 pub fn poll(&mut self, now: Timestamp) -> Vec<[u8; TS_PACKET_SIZE]> {
692 let mut out = Vec::new();
693 self.poll_into(now, &mut out);
694 out
695 }
696}
697
698fn sections_are_distinct(sections: &[&[u8]]) -> bool {
699 let mut keys: Vec<(u8, u8)> = Vec::with_capacity(sections.len());
700 for bytes in sections {
701 let Ok(section) = Section::parse(bytes) else {
702 return true;
703 };
704 let key = (section.table_id, section.section_number);
705 if keys.contains(&key) {
706 return false;
707 }
708 keys.push(key);
709 }
710 true
711}
712
713fn upsert_checked(
716 mux: &mut SiMux,
717 pid: Pid,
718 section: Vec<u8>,
719 interval: SectionInterval,
720 table_id: u8,
721) -> core::result::Result<(), SectionRejection> {
722 if split_sections(§ion)
723 .first()
724 .is_some_and(|s| s.first().copied() != Some(table_id))
725 {
726 let reason = SectionRejection::WrongTableId {
727 expected: table_id,
728 found: section.first().copied(),
729 };
730 mux.rejected.push(RejectedSection { pid, reason });
731 return Err(reason);
732 }
733 mux.upsert(pid, section, interval)
734}
735
736impl Default for SiMux {
737 fn default() -> Self {
738 Self::new()
739 }
740}
741
742fn split_sections(data: &[u8]) -> Vec<&[u8]> {
748 let mut result = Vec::new();
749 let mut pos = 0;
750 while let Some(end) = crate::ts::section_total_len(&data[pos..]).map(|len| pos + len) {
751 if end > data.len() {
752 break;
753 }
754 result.push(&data[pos..end]);
755 pos = end;
756 }
757 result
758}
759
760#[cfg(test)]
761mod tests {
762 use super::*;
763 use crate::ts::{SectionReassembler, TsPacket};
764 use alloc::vec;
765 use alloc::vec::Vec;
766
767 fn concat_sections(sections: &[Vec<u8>]) -> Vec<u8> {
770 let total: usize = sections.iter().map(|s| s.len()).sum();
771 let mut out = Vec::with_capacity(total);
772 for s in sections {
773 out.extend_from_slice(s);
774 }
775 out
776 }
777
778 fn assert_round_trip(sections: &[Vec<u8>]) {
781 let mut packetiser = SectionPacketiser::new(Pid::from_const(0x0100));
782 let refs: Vec<&[u8]> = sections.iter().map(|s| s.as_slice()).collect();
783 let packets = packetiser.packetise(&refs);
784
785 let mut reasm = SectionReassembler::default();
786 for pkt_raw in &packets {
787 let pkt = TsPacket::parse(pkt_raw).expect("parse generated packet");
788 let payload = pkt.payload.expect("payload present");
789 let pusi = pkt.header.pusi;
790 reasm.feed(payload, pusi);
791 }
792
793 let got: Vec<_> = core::iter::from_fn(|| reasm.pop_section()).collect();
794 assert_eq!(
795 got.len(),
796 sections.len(),
797 "section count mismatch: expected {}, got {}",
798 sections.len(),
799 got.len()
800 );
801 for (i, (orig, round)) in sections.iter().zip(got.iter()).enumerate() {
802 assert_eq!(
803 round.as_ref(),
804 orig.as_slice(),
805 "section {i} round-trip mismatch"
806 );
807 }
808 assert!(reasm.is_empty(), "reassembler should be empty after drain");
809 }
810
811 #[test]
817 fn many_sections_with_boundary_straddling_sizes_round_trip() {
818 let sections: Vec<Vec<u8>> = (0..400usize)
819 .map(|n| {
820 let body: Vec<u8> = (0..n).map(|i| (i % 251) as u8).collect();
821 test_fixtures::psi::short_section((n % 200) as u8, &body)
822 })
823 .collect();
824 assert_round_trip(§ions);
825 }
826
827 #[test]
830 fn split_single_section() {
831 let s = test_fixtures::psi::long_section(0x42, 1, 0, 0, &[0xAA; 5]);
832 let refs = split_sections(&s);
833 assert_eq!(refs.len(), 1);
834 assert_eq!(refs[0], s.as_slice());
835 }
836
837 #[test]
838 fn split_two_sections() {
839 let s1 = test_fixtures::psi::long_section(0x42, 1, 0, 0, &[0x01, 0x02]);
840 let s2 = test_fixtures::psi::long_section(0x46, 1, 0, 0, &[0x03, 0x04, 0x05]);
841 let both = concat_sections(&[s1.clone(), s2.clone()]);
842 let refs = split_sections(&both);
843 assert_eq!(refs.len(), 2);
844 assert_eq!(refs[0], s1.as_slice());
845 assert_eq!(refs[1], s2.as_slice());
846 }
847
848 #[test]
849 fn split_empty_input() {
850 let refs = split_sections(&[]);
851 assert!(refs.is_empty());
852 }
853
854 #[test]
855 fn split_trailing_garbage_ignored() {
856 let s = test_fixtures::psi::long_section(0x42, 1, 0, 0, &[0xAA; 3]);
857 let mut data = s.clone();
858 data.push(0xFF); let refs = split_sections(&data);
860 assert_eq!(refs.len(), 1);
861 assert_eq!(refs[0], s.as_slice());
862 }
863
864 fn cc(v: u8) -> ContinuityCounter {
865 ContinuityCounter::try_new(v).expect("4-bit counter")
866 }
867
868 #[test]
871 fn interval_constants_match_spec() {
872 assert_eq!(NIT_MAX_INTERVAL.duration(), Duration::from_secs(10));
874 assert_eq!(BAT_MAX_INTERVAL.duration(), Duration::from_secs(10));
875 assert_eq!(SDT_ACTUAL_MAX_INTERVAL.duration(), Duration::from_secs(2));
876 assert_eq!(SDT_OTHER_MAX_INTERVAL.duration(), Duration::from_secs(10));
877 assert_eq!(
878 EIT_PF_ACTUAL_MAX_INTERVAL.duration(),
879 Duration::from_secs(2)
880 );
881 assert_eq!(
882 EIT_PF_OTHER_MAX_INTERVAL.duration(),
883 Duration::from_secs(10)
884 );
885 assert_eq!(EIT_SCHED_MAX_INTERVAL.duration(), Duration::from_secs(10));
886 assert_eq!(
887 EIT_SCHED_EXT_MAX_INTERVAL.duration(),
888 Duration::from_secs(30)
889 );
890 assert_eq!(TDT_MAX_INTERVAL.duration(), Duration::from_secs(30));
891 assert_eq!(TOT_MAX_INTERVAL.duration(), Duration::from_secs(30));
892
893 assert_eq!(PAT_MAX_INTERVAL.duration(), Duration::from_millis(100));
895 assert_eq!(PMT_MAX_INTERVAL.duration(), Duration::from_millis(100));
896
897 assert_eq!(MIN_SECTION_INTERVAL, Duration::from_millis(25));
899 }
900
901 #[test]
904 fn new_and_default_simux_are_empty() {
905 for mut mux in [SiMux::new(), SiMux::default()] {
906 let pkts = mux.poll(Timestamp::ZERO);
907 assert!(pkts.is_empty());
908 }
909 }
910
911 #[test]
912 fn first_poll_always_emits() {
913 let s = test_fixtures::psi::long_section(0x42, 1, 0, 0, &[0xAA; 10]);
914 let mut mux = SiMux::new();
915 mux.upsert(
916 Pid::from_const(0x0100),
917 s.clone(),
918 SectionInterval::from_const(Duration::from_millis(100)),
919 )
920 .expect("scheduled section");
921 let pkts = mux.poll(Timestamp::ZERO);
922 assert!(!pkts.is_empty(), "first poll must emit");
923 }
924
925 #[test]
926 fn first_poll_emits_all_entries() {
927 let s1 = test_fixtures::psi::long_section(0x42, 1, 0, 0, &[0x01; 5]);
928 let s2 = test_fixtures::psi::long_section(0x46, 1, 0, 0, &[0x02; 5]);
929 let mut mux = SiMux::new();
930 mux.upsert(
931 Pid::from_const(0x0100),
932 s1.clone(),
933 SectionInterval::from_const(Duration::from_millis(100)),
934 )
935 .expect("scheduled section");
936 mux.upsert(
937 Pid::from_const(0x0200),
938 s2.clone(),
939 SectionInterval::from_const(Duration::from_millis(200)),
940 )
941 .expect("scheduled section");
942 let pkts = mux.poll(Timestamp::ZERO);
943 let pids: Vec<Pid> = pkts
945 .iter()
946 .map(|raw| TsPacket::parse(raw).unwrap().header.pid)
947 .collect();
948 assert!(pids.contains(&Pid::from_const(0x0100)));
949 assert!(pids.contains(&Pid::from_const(0x0200)));
950 }
951
952 #[test]
955 fn entry_emits_only_when_due() {
956 let s = test_fixtures::psi::long_section(0x42, 1, 0, 0, &[0xAA; 10]);
957 let mut mux = SiMux::new();
958 mux.upsert(
959 Pid::from_const(0x0100),
960 s.clone(),
961 SectionInterval::from_const(Duration::from_millis(100)),
962 )
963 .expect("scheduled section");
964
965 let pkts0 = mux.poll(Timestamp::ZERO);
967 assert!(!pkts0.is_empty());
968
969 let pkts50 = mux.poll(Timestamp::from_millis(50));
971 assert!(pkts50.is_empty(), "should not emit at t=50");
972
973 let pkts99 = mux.poll(Timestamp::from_millis(99));
975 assert!(pkts99.is_empty(), "should not emit at t=99");
976
977 let pkts100 = mux.poll(Timestamp::from_millis(100));
979 assert!(!pkts100.is_empty(), "should emit at t=100");
980 }
981
982 #[test]
983 fn two_entries_different_cadence() {
984 let s1 = test_fixtures::psi::long_section(0x42, 1, 0, 0, &[0x01; 5]);
985 let s2 = test_fixtures::psi::long_section(0x46, 1, 0, 0, &[0x02; 5]);
986 let mut mux = SiMux::new();
987 mux.upsert(
988 Pid::from_const(0x0100),
989 concat_sections(&[s1]),
990 SectionInterval::from_const(Duration::from_millis(100)),
991 )
992 .expect("scheduled section");
993 mux.upsert(
994 Pid::from_const(0x0200),
995 concat_sections(&[s2]),
996 SectionInterval::from_const(Duration::from_millis(200)),
997 )
998 .expect("scheduled section");
999
1000 let pkts = mux.poll(Timestamp::ZERO);
1002 assert!(!pkts.is_empty());
1003
1004 let pkts100 = mux.poll(Timestamp::from_millis(100));
1006 assert!(!pkts100.is_empty());
1007 let pids100: Vec<Pid> = pkts100
1008 .iter()
1009 .map(|raw| TsPacket::parse(raw).unwrap().header.pid)
1010 .collect();
1011 assert!(
1012 pids100.contains(&Pid::from_const(0x0100)),
1013 "PID 0x0100 should emit at t=100"
1014 );
1015 assert!(
1016 !pids100.contains(&Pid::from_const(0x0200)),
1017 "PID 0x0200 should NOT emit at t=100"
1018 );
1019
1020 let pkts150 = mux.poll(Timestamp::from_millis(150));
1022 assert!(pkts150.is_empty(), "neither should emit at t=150");
1023
1024 let pkts200 = mux.poll(Timestamp::from_millis(200));
1026 let pids200: Vec<Pid> = pkts200
1027 .iter()
1028 .map(|raw| TsPacket::parse(raw).unwrap().header.pid)
1029 .collect();
1030 assert!(
1031 pids200.contains(&Pid::from_const(0x0100)),
1032 "PID 0x0100 should emit at t=200"
1033 );
1034 assert!(
1035 pids200.contains(&Pid::from_const(0x0200)),
1036 "PID 0x0200 should emit at t=200"
1037 );
1038 }
1039
1040 #[test]
1041 fn entry_emits_again_after_full_interval() {
1042 let s = test_fixtures::psi::long_section(0x42, 1, 0, 0, &[0xAA; 20]);
1043 let mut mux = SiMux::new();
1044 mux.upsert(
1045 Pid::from_const(0x0100),
1046 s,
1047 SectionInterval::from_const(Duration::from_secs(1)),
1048 )
1049 .expect("scheduled section");
1050
1051 let n0 = mux.poll_into(Timestamp::ZERO, &mut Vec::new());
1053 assert!(n0 > 0);
1054
1055 let mut buf = Vec::new();
1057 let n999 = mux.poll_into(Timestamp::from_millis(999), &mut buf);
1058 assert_eq!(n999, 0);
1059
1060 let mut buf2 = Vec::new();
1062 let n1000 = mux.poll_into(Timestamp::from_millis(1000), &mut buf2);
1063 assert!(n1000 > 0);
1064 }
1065
1066 #[test]
1069 fn upsert_updates_existing_entry() {
1070 let s1 = test_fixtures::psi::long_section(0x42, 1, 0, 0, &[0xAA; 5]);
1073 let s2 = test_fixtures::psi::long_section(0x42, 1, 0, 0, &[0xBB; 10]);
1074 let mut mux = SiMux::new();
1075
1076 mux.upsert(
1077 Pid::from_const(0x0100),
1078 s1,
1079 SectionInterval::from_const(Duration::from_millis(100)),
1080 )
1081 .expect("scheduled section");
1082 mux.upsert(
1083 Pid::from_const(0x0100),
1084 s2.clone(),
1085 SectionInterval::from_const(Duration::from_millis(200)),
1086 )
1087 .expect("scheduled section");
1088
1089 let pkts = mux.poll(Timestamp::ZERO);
1090
1091 let mut reasm = SectionReassembler::default();
1093 for raw in &pkts {
1094 let pkt = TsPacket::parse(raw).unwrap();
1095 if pkt.header.pid == Pid::from_const(0x0100) {
1096 reasm.feed(pkt.payload.unwrap(), pkt.header.pusi);
1097 }
1098 }
1099 let got: Vec<_> = core::iter::from_fn(|| reasm.pop_section()).collect();
1100 assert_eq!(got.len(), 1);
1101 assert_eq!(got[0].as_ref(), s2.as_slice());
1102 }
1103
1104 #[test]
1111 fn upsert_tdt_then_tot_both_emitted_with_continuous_cc() {
1112 let tdt = test_fixtures::psi::long_section(0x70, 1, 0, 0, &[0xAA; 5]); let tot = test_fixtures::psi::long_section(0x73, 1, 0, 0, &[0xBB; 8]); let mut mux = SiMux::new();
1115
1116 mux.upsert_tdt(tdt.clone()).expect("scheduled section");
1117 mux.upsert_tot(tot.clone()).expect("scheduled section");
1118
1119 let pkts = mux.poll(Timestamp::ZERO);
1120 assert!(!pkts.is_empty());
1121
1122 let mut table_ids_seen = Vec::new();
1123 let mut reasm = SectionReassembler::default();
1124 let mut prev_cc: Option<ContinuityCounter> = None;
1125 for raw in &pkts {
1126 let pkt = TsPacket::parse(raw).unwrap();
1127 assert_eq!(pkt.header.pid, well_known::TDT_TOT);
1128 if let Some(prev) = prev_cc {
1129 assert_eq!(
1130 pkt.header.continuity_counter.forward_distance_from(prev),
1131 1,
1132 "continuity counter must be continuous across table kinds on one PID"
1133 );
1134 }
1135 prev_cc = Some(pkt.header.continuity_counter);
1136 reasm.feed(pkt.payload.unwrap(), pkt.header.pusi);
1137 }
1138 while let Some(section) = reasm.pop_section() {
1139 table_ids_seen.push(section.as_ref()[0]);
1140 }
1141
1142 assert!(table_ids_seen.contains(&0x70), "TDT missing from output");
1143 assert!(table_ids_seen.contains(&0x73), "TOT missing from output");
1144 }
1145
1146 #[test]
1149 fn upsert_sdt_and_bat_both_emitted() {
1150 let sdt = test_fixtures::psi::long_section(0x42, 1, 0, 0, &[0xCC; 5]);
1151 let bat = test_fixtures::psi::long_section(0x4A, 1, 0, 0, &[0xDD; 6]);
1152 let mut mux = SiMux::new();
1153
1154 mux.upsert_sdt_actual(sdt.clone())
1155 .expect("scheduled section");
1156 mux.upsert(
1157 well_known::SDT_BAT,
1158 bat.clone(),
1159 SectionInterval::from_const(Duration::from_millis(1000)),
1160 )
1161 .expect("scheduled section");
1162
1163 let pkts = mux.poll(Timestamp::ZERO);
1164 let mut table_ids_seen = Vec::new();
1165 let mut reasm = SectionReassembler::default();
1166 for raw in &pkts {
1167 let pkt = TsPacket::parse(raw).unwrap();
1168 reasm.feed(pkt.payload.unwrap(), pkt.header.pusi);
1169 }
1170 while let Some(section) = reasm.pop_section() {
1171 table_ids_seen.push(section.as_ref()[0]);
1172 }
1173
1174 assert!(table_ids_seen.contains(&0x42), "SDT actual missing");
1175 assert!(table_ids_seen.contains(&0x4A), "BAT missing");
1176 }
1177
1178 #[test]
1181 fn upsert_sdt_actual_uses_correct_pid() {
1182 let s = test_fixtures::psi::long_section(0x42, 1, 0, 0, &[0x01]);
1183 let mut mux = SiMux::new();
1184 mux.upsert_sdt_actual(s).expect("scheduled section");
1185 let pkts = mux.poll(Timestamp::ZERO);
1186 let pids: Vec<Pid> = pkts
1187 .iter()
1188 .map(|raw| TsPacket::parse(raw).unwrap().header.pid)
1189 .collect();
1190 assert!(pids.iter().all(|&p| p == well_known::SDT_BAT));
1191 }
1192
1193 #[test]
1194 fn upsert_pat_uses_correct_pid() {
1195 let s = test_fixtures::psi::long_section(0x00, 1, 0, 0, &[0x01, 0x02]);
1196 let mut mux = SiMux::new();
1197 mux.upsert_pat(s).expect("scheduled section");
1198 let pkts = mux.poll(Timestamp::ZERO);
1199 assert!(!pkts.is_empty());
1200 let pids: Vec<Pid> = pkts
1201 .iter()
1202 .map(|raw| TsPacket::parse(raw).unwrap().header.pid)
1203 .collect();
1204 assert!(pids.iter().all(|&p| p == well_known::PAT));
1205 assert!(
1206 mux.poll(Timestamp::from_nanos(
1207 (PAT_MAX_INTERVAL.duration() / 2).as_nanos() as u64
1208 ))
1209 .is_empty()
1210 );
1211 assert!(
1212 !mux.poll(Timestamp::from_nanos(
1213 PAT_MAX_INTERVAL.duration().as_nanos() as u64
1214 ))
1215 .is_empty()
1216 );
1217 }
1218
1219 #[test]
1220 fn upsert_nit_uses_correct_pid() {
1221 let s = test_fixtures::psi::long_section(0x40, 1, 0, 0, &[0x01]);
1222 let mut mux = SiMux::new();
1223 mux.upsert_nit(s).expect("scheduled section");
1224 let pkts = mux.poll(Timestamp::ZERO);
1225 assert!(!pkts.is_empty());
1226 let pids: Vec<Pid> = pkts
1227 .iter()
1228 .map(|raw| TsPacket::parse(raw).unwrap().header.pid)
1229 .collect();
1230 assert!(pids.iter().all(|&p| p == well_known::NIT));
1231 assert!(
1232 mux.poll(Timestamp::from_nanos(
1233 (NIT_MAX_INTERVAL.duration() / 2).as_nanos() as u64
1234 ))
1235 .is_empty()
1236 );
1237 assert!(
1238 !mux.poll(Timestamp::from_nanos(
1239 NIT_MAX_INTERVAL.duration().as_nanos() as u64
1240 ))
1241 .is_empty()
1242 );
1243 }
1244
1245 #[test]
1246 fn upsert_tdt_uses_correct_pid() {
1247 let s = test_fixtures::psi::long_section(0x70, 1, 0, 0, &[0x01]);
1248 let mut mux = SiMux::new();
1249 mux.upsert_tdt(s).expect("scheduled section");
1250 let pkts = mux.poll(Timestamp::ZERO);
1251 let pids: Vec<Pid> = pkts
1252 .iter()
1253 .map(|raw| TsPacket::parse(raw).unwrap().header.pid)
1254 .collect();
1255 assert!(pids.iter().all(|&p| p == well_known::TDT_TOT));
1256 }
1257
1258 #[test]
1259 fn upsert_tot_uses_correct_pid() {
1260 let s = test_fixtures::psi::long_section(0x73, 1, 0, 0, &[0x01]);
1261 let mut mux = SiMux::new();
1262 mux.upsert_tot(s).expect("scheduled section");
1263 let pkts = mux.poll(Timestamp::ZERO);
1264 let pids: Vec<Pid> = pkts
1265 .iter()
1266 .map(|raw| TsPacket::parse(raw).unwrap().header.pid)
1267 .collect();
1268 assert!(pids.iter().all(|&p| p == well_known::TDT_TOT));
1269 }
1270
1271 #[test]
1274 fn upsert_rejects_an_empty_input() {
1275 let mut mux = SiMux::new();
1278 let pat = test_fixtures::psi::pat_section(1, 0, &[(1, 0x1000)]);
1279 mux.upsert_pat(pat.clone()).expect("PAT is schedulable");
1280 assert_eq!(
1281 mux.upsert(well_known::PAT, Vec::new(), PAT_MAX_INTERVAL),
1282 Err(SectionRejection::NotASection)
1283 );
1284 assert_eq!(mux.rejected().len(), 1);
1285 assert_eq!(mux.rejected()[0].pid, well_known::PAT);
1286 let pkts = mux.poll(Timestamp::ZERO);
1287 let mut reasm = SectionReassembler::default();
1288 for raw in &pkts {
1289 let pkt = TsPacket::parse(raw).unwrap();
1290 reasm.feed(pkt.payload.unwrap(), pkt.header.pusi);
1291 }
1292 let got: Vec<_> = core::iter::from_fn(|| reasm.pop_section()).collect();
1293 assert_eq!(got.len(), 1);
1294 assert_eq!(got[0].as_ref(), pat.as_slice());
1295 }
1296
1297 #[test]
1298 fn upsert_rejects_two_sections_that_share_a_key() {
1299 let a = test_fixtures::psi::long_section(0x42, 1, 0, 0, &[0x01]);
1300 let b = test_fixtures::psi::long_section(0x42, 1, 0, 0, &[0x02]);
1301 let mut mux = SiMux::new();
1302 assert_eq!(
1303 mux.upsert(
1304 well_known::SDT_BAT,
1305 concat_sections(&[a, b]),
1306 SDT_ACTUAL_MAX_INTERVAL
1307 ),
1308 Err(SectionRejection::DuplicateSection)
1309 );
1310 }
1311
1312 #[test]
1313 fn upsert_rejects_a_second_section_of_another_table() {
1314 let sdt = test_fixtures::psi::long_section(0x42, 1, 0, 0, &[0x01]);
1315 let bat = test_fixtures::psi::long_section(0x4A, 1, 0, 0, &[0x02]);
1316 let mut mux = SiMux::new();
1317 assert_eq!(
1318 mux.upsert(
1319 well_known::SDT_BAT,
1320 concat_sections(&[sdt, bat]),
1321 SDT_ACTUAL_MAX_INTERVAL
1322 ),
1323 Err(SectionRejection::MoreThanOneSection)
1324 );
1325 }
1326
1327 #[test]
1328 fn upsert_keeps_a_complete_section_and_rejects_a_trailing_fragment() {
1329 let whole = test_fixtures::psi::long_section(0x42, 1, 0, 0, &[0x01]);
1332 let mut with_tail = whole.clone();
1333 with_tail.extend_from_slice(&[0x4A, 0x00]);
1334 let mut mux = SiMux::new();
1335 mux.upsert(well_known::SDT_BAT, with_tail, SDT_ACTUAL_MAX_INTERVAL)
1336 .expect("the complete section is schedulable");
1337 let pkts = mux.poll(Timestamp::ZERO);
1338 let mut reasm = SectionReassembler::default();
1339 for raw in &pkts {
1340 let pkt = TsPacket::parse(raw).unwrap();
1341 reasm.feed(pkt.payload.unwrap(), pkt.header.pusi);
1342 }
1343 let got: Vec<_> = core::iter::from_fn(|| reasm.pop_section()).collect();
1344 assert_eq!(got.len(), 1);
1345 assert_eq!(got[0].as_ref(), whole.as_slice());
1346 }
1347
1348 #[test]
1349 fn sections_of_one_table_are_keyed_by_their_section_number() {
1350 let first = test_fixtures::psi::long_section(0x4E, 1, 0, 0, &[0x01]);
1351 let second = test_fixtures::psi::long_section(0x4E, 1, 0, 1, &[0x02]);
1352 let mut mux = SiMux::new();
1353 let pid = Pid::from_const(0x0012);
1354 mux.upsert(pid, first.clone(), EIT_SCHED_MAX_INTERVAL)
1355 .expect("first section");
1356 mux.upsert(pid, second.clone(), EIT_SCHED_MAX_INTERVAL)
1357 .expect("second section");
1358 let pkts = mux.poll(Timestamp::ZERO);
1359 let mut reasm = SectionReassembler::default();
1360 for raw in &pkts {
1361 let pkt = TsPacket::parse(raw).unwrap();
1362 reasm.feed(pkt.payload.unwrap(), pkt.header.pusi);
1363 }
1364 let got: Vec<_> = core::iter::from_fn(|| reasm.pop_section()).collect();
1365 assert_eq!(got.len(), 2, "both sections of the table must go out");
1366 }
1367
1368 #[test]
1369 fn upsert_pat_rejects_a_section_of_another_table() {
1370 let sdt = test_fixtures::psi::long_section(0x42, 1, 0, 0, &[0x01]);
1371 let mut mux = SiMux::new();
1372 assert_eq!(
1373 mux.upsert_pat(sdt),
1374 Err(SectionRejection::WrongTableId {
1375 expected: TABLE_ID_PAT,
1376 found: Some(0x42),
1377 })
1378 );
1379 assert!(mux.poll(Timestamp::ZERO).is_empty());
1380 }
1381
1382 #[test]
1385 fn simux_round_trip_single_entry() {
1386 let s1 = test_fixtures::psi::long_section(0x42, 1, 0, 0, &[0xAA; 20]);
1387 let interval = SectionInterval::from_const(Duration::from_millis(100));
1388 let mut mux = SiMux::new();
1389 mux.upsert(Pid::from_const(0x0100), s1.clone(), interval)
1390 .expect("scheduled section");
1391
1392 let pkts = mux.poll(Timestamp::ZERO);
1393
1394 let mut reasm = SectionReassembler::default();
1395 for raw in &pkts {
1396 let pkt = TsPacket::parse(raw).unwrap();
1397 if pkt.header.pid == Pid::from_const(0x0100) {
1398 reasm.feed(pkt.payload.unwrap(), pkt.header.pusi);
1399 }
1400 }
1401 let got: Vec<_> = core::iter::from_fn(|| reasm.pop_section()).collect();
1402 assert_eq!(got.len(), 1, "round-trip must recover the section");
1403 assert_eq!(got[0].as_ref(), s1.as_slice());
1404 }
1405
1406 #[test]
1407 fn simux_round_trip_multi_pid() {
1408 let s_a = test_fixtures::psi::long_section(0x42, 1, 0, 0, &[0xA0; 10]);
1409 let s_b = test_fixtures::psi::long_section(0x46, 1, 0, 0, &[0xB0; 10]);
1410 let mut mux = SiMux::new();
1411 mux.upsert(
1412 Pid::from_const(0x0100),
1413 s_a.clone(),
1414 SectionInterval::from_const(Duration::from_millis(100)),
1415 )
1416 .expect("scheduled section");
1417 mux.upsert(
1418 Pid::from_const(0x0200),
1419 s_b.clone(),
1420 SectionInterval::from_const(Duration::from_millis(100)),
1421 )
1422 .expect("scheduled section");
1423
1424 let pkts = mux.poll(Timestamp::ZERO);
1425
1426 let mut reasm_a = SectionReassembler::default();
1427 let mut reasm_b = SectionReassembler::default();
1428 for raw in &pkts {
1429 let pkt = TsPacket::parse(raw).unwrap();
1430 match pkt.header.pid.value() {
1431 0x0100 => reasm_a.feed(pkt.payload.unwrap(), pkt.header.pusi),
1432 0x0200 => reasm_b.feed(pkt.payload.unwrap(), pkt.header.pusi),
1433 _ => {}
1434 }
1435 }
1436 let got_a: Vec<_> = core::iter::from_fn(|| reasm_a.pop_section()).collect();
1437 let got_b: Vec<_> = core::iter::from_fn(|| reasm_b.pop_section()).collect();
1438 assert_eq!(got_a.len(), 1);
1439 assert_eq!(got_b.len(), 1);
1440 assert_eq!(got_a[0].as_ref(), s_a.as_slice());
1441 assert_eq!(got_b[0].as_ref(), s_b.as_slice());
1442 }
1443
1444 #[test]
1447 fn continuity_counter_continuous_across_polls() {
1448 let s = test_fixtures::psi::long_section(0x42, 1, 0, 0, &[0xAA; 250]);
1450 let mut mux = SiMux::new();
1451 mux.upsert(
1452 Pid::from_const(0x0100),
1453 s,
1454 SectionInterval::from_const(Duration::from_millis(100)),
1455 )
1456 .expect("scheduled section");
1457
1458 let pkts1 = mux.poll(Timestamp::ZERO);
1459 assert!(pkts1.len() >= 2, "need ≥2 packets to test CC continuity");
1460
1461 let last_cc_pkts1 = TsPacket::parse(&pkts1[pkts1.len() - 1])
1462 .unwrap()
1463 .header
1464 .continuity_counter;
1465
1466 let pkts2 = mux.poll(Timestamp::from_millis(100));
1467 assert!(!pkts2.is_empty(), "second poll must emit");
1468
1469 let first_cc_pkts2 = TsPacket::parse(&pkts2[0])
1470 .unwrap()
1471 .header
1472 .continuity_counter;
1473
1474 assert_eq!(
1475 first_cc_pkts2.forward_distance_from(last_cc_pkts1),
1476 1,
1477 "CC must continue across poll cycles"
1478 );
1479 }
1480
1481 #[test]
1484 fn poll_into_clears_out_before_appending() {
1485 let s = test_fixtures::psi::long_section(0x42, 1, 0, 0, &[0xAA; 5]);
1486 let mut mux = SiMux::new();
1487 mux.upsert(
1488 Pid::from_const(0x0100),
1489 s,
1490 SectionInterval::from_const(Duration::from_millis(100)),
1491 )
1492 .expect("scheduled section");
1493
1494 let mut out = vec![[0u8; TS_PACKET_SIZE]; 42];
1495 let n = mux.poll_into(Timestamp::ZERO, &mut out);
1496 assert_eq!(n, out.len(), "out must contain only new packets");
1497 }
1498
1499 #[test]
1505 #[should_panic(expected = "25 ms")]
1506 fn named_interval_const_rejects_sub_25ms_interval() {
1507 let _ = SectionInterval::from_const(Duration::from_millis(10));
1508 }
1509
1510 #[test]
1514 fn section_interval_rejects_below_the_25ms_floor() {
1515 for bad in [
1516 Duration::ZERO,
1517 Duration::from_millis(1),
1518 Duration::from_millis(24),
1519 MIN_SECTION_INTERVAL - Duration::from_nanos(1),
1520 ] {
1521 let err = SectionInterval::try_new(bad).unwrap_err();
1522 assert_eq!(err.interval, bad);
1523 assert_eq!(err.min, MIN_SECTION_INTERVAL);
1524 assert!(SectionInterval::try_from(bad).is_err());
1525 }
1526 assert_eq!(
1527 SectionInterval::try_new(MIN_SECTION_INTERVAL)
1528 .expect("the floor itself is valid")
1529 .duration(),
1530 MIN_SECTION_INTERVAL
1531 );
1532 assert_eq!(
1533 Duration::from(SectionInterval::from_const(Duration::from_secs(2))),
1534 Duration::from_secs(2)
1535 );
1536 }
1537
1538 #[test]
1539 fn upsert_accepts_25ms_interval() {
1540 let s = test_fixtures::psi::long_section(0x42, 1, 0, 0, &[0xAA; 5]);
1541 let mut mux = SiMux::new();
1542 mux.upsert(
1543 Pid::from_const(0x0100),
1544 s,
1545 SectionInterval::from_const(MIN_SECTION_INTERVAL),
1546 )
1547 .expect("scheduled section");
1548 let pkts = mux.poll(Timestamp::ZERO);
1549 assert!(!pkts.is_empty());
1550 }
1551
1552 #[test]
1555 fn round_trip_single_short_section() {
1556 let s = test_fixtures::psi::long_section(0x42, 1, 0, 0, &[0xAA; 10]);
1557 assert_round_trip(&[s]);
1558 }
1559
1560 #[test]
1561 fn round_trip_one_byte_body() {
1562 let s = test_fixtures::psi::long_section(0x46, 1, 0, 0, &[0xBB]); assert_round_trip(&[s]);
1564 }
1565
1566 #[test]
1567 fn round_trip_section_exactly_pusi_cap_boundary() {
1568 let body = vec![0xCC; PUSI_PAYLOAD_CAP - 3];
1570 let s = test_fixtures::psi::short_section(0x50, &body);
1571 assert_eq!(s.len(), PUSI_PAYLOAD_CAP);
1572 assert_round_trip(&[s]);
1573 }
1574
1575 #[test]
1576 fn round_trip_section_just_over_pusi_cap() {
1577 let body = vec![0xDD; PUSI_PAYLOAD_CAP - 3 + 1];
1579 let s = test_fixtures::psi::short_section(0x52, &body);
1580 assert_eq!(s.len(), PUSI_PAYLOAD_CAP + 1);
1581 assert_round_trip(&[s]);
1582 }
1583
1584 #[test]
1585 fn round_trip_section_spans_many_packets() {
1586 let body = vec![0xEE; 2000 - 3];
1588 let s = test_fixtures::psi::short_section(0x60, &body);
1589 assert_round_trip(&[s]);
1590 }
1591
1592 #[test]
1593 fn round_trip_section_at_max_size() {
1594 let body = vec![0x11; 4096 - 3];
1599 let s = test_fixtures::psi::short_section(0x80, &body);
1600 assert_eq!(s.len(), 4096);
1601 assert_round_trip(&[s]);
1602 }
1603
1604 #[test]
1605 fn round_trip_multiple_short_sections_in_one_batch() {
1606 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]);
1610 }
1611
1612 #[test]
1613 fn round_trip_section_ends_exactly_at_boundary() {
1614 let body1 = vec![0xA1; PUSI_PAYLOAD_CAP - 3];
1618 let s1 = test_fixtures::psi::short_section(0x50, &body1);
1619 assert_eq!(s1.len(), PUSI_PAYLOAD_CAP);
1620
1621 let s2 = test_fixtures::psi::long_section(0x52, 1, 0, 0, &[0xB1, 0xB2]);
1622 assert_round_trip(&[s1, s2]);
1623 }
1624
1625 #[test]
1626 fn continuation_packet_never_overshoots_next_section_start() {
1627 let body1 = vec![0xA5; 366 - 3];
1634 let s1 = test_fixtures::psi::short_section(0x50, &body1);
1635 assert_eq!(s1.len(), 366);
1636 let s2 = test_fixtures::psi::long_section(0x52, 1, 0, 0, &[0xB1, 0xB2, 0xB3]);
1637
1638 let mut packetiser = SectionPacketiser::new(Pid::from_const(0x0100));
1639 let packets = packetiser.packetise(&[s1.as_slice(), s2.as_slice()]);
1640
1641 for pkt_raw in &packets {
1642 let pkt = TsPacket::parse(pkt_raw).expect("parse generated packet");
1643 let payload = pkt.payload.expect("payload present");
1644 if pkt.header.pusi {
1645 let pointer = payload[0] as usize;
1646 assert!(
1650 pointer < PUSI_PAYLOAD_CAP,
1651 "pointer_field {pointer} leaves no room for a section to \
1652 start within this packet (H.222.0 §2.4.4)"
1653 );
1654 }
1655 }
1656
1657 assert_round_trip(&[s1, s2]);
1658 }
1659
1660 #[test]
1661 fn round_trip_mix_small_large_sections() {
1662 let s1 = test_fixtures::psi::long_section(0x10, 1, 0, 0, &[0xAA; 5]);
1665 let body2 = vec![0xBB; 200];
1666 let s2 = test_fixtures::psi::short_section(0x20, &body2);
1667 let s3 = test_fixtures::psi::long_section(0x30, 1, 0, 0, &[0xCC; 50]);
1668 let body4 = vec![0xDD; 800];
1669 let s4 = test_fixtures::psi::short_section(0x40, &body4);
1670 let s5 = test_fixtures::psi::long_section(0x50, 1, 0, 0, &[0xEE]); assert_round_trip(&[s1, s2, s3, s4, s5]);
1672 }
1673
1674 #[test]
1677 fn continuity_counter_increments_per_packet() {
1678 let body = vec![0xAA; 500];
1680 let section = test_fixtures::psi::short_section(0x42, &body);
1681 let mut p = SectionPacketiser::new(Pid::from_const(0x0100));
1682
1683 let packets = p.packetise(&[§ion]);
1684 assert!(packets.len() >= 3, "need multiple packets to test CC");
1685
1686 let mut last_cc: Option<ContinuityCounter> = None;
1687 for pkt_raw in &packets {
1688 let pkt = TsPacket::parse(pkt_raw).unwrap();
1689 let cc = pkt.header.continuity_counter;
1690 if let Some(last) = last_cc {
1691 assert_eq!(
1692 cc.forward_distance_from(last),
1693 1,
1694 "CC must increment per packet"
1695 );
1696 }
1697 last_cc = Some(cc);
1698 }
1699 }
1700
1701 #[test]
1702 fn continuity_counter_wraps_and_continues_across_calls() {
1703 let mut p = SectionPacketiser::with_continuity(Pid::from_const(0x0100), cc(14));
1704 let body = vec![0xBB; 500];
1706 let s = test_fixtures::psi::short_section(0x42, &body);
1707
1708 let pkts1 = p.packetise(&[&s]);
1710 assert!(pkts1.len() >= 3, "section must span ≥3 packets");
1711 let ccs1: Vec<u8> = pkts1
1712 .iter()
1713 .map(|b| {
1714 TsPacket::parse(b)
1715 .unwrap()
1716 .header
1717 .continuity_counter
1718 .value()
1719 })
1720 .collect();
1721 assert_eq!(ccs1[0], 14);
1722 assert_eq!(ccs1[1], 15);
1723 assert_eq!(ccs1[2], 0);
1724
1725 let previous = ContinuityCounter::try_new(ccs1.last().copied().unwrap_or(0))
1727 .expect("the last emitted counter is 4-bit");
1728 let pkts2 = p.packetise(&[&s]);
1729 let cc_first_pkt2 = TsPacket::parse(&pkts2[0])
1730 .unwrap()
1731 .header
1732 .continuity_counter;
1733 assert_eq!(cc_first_pkt2.forward_distance_from(previous), 1);
1734 }
1735
1736 #[test]
1739 fn pusi_set_when_section_starts() {
1740 let s = test_fixtures::psi::long_section(0x42, 1, 0, 0, &[0xAA; 10]);
1741 let mut p = SectionPacketiser::new(Pid::from_const(0x0100));
1742 let packets = p.packetise(&[&s]);
1743 assert!(!packets.is_empty());
1744 let pkt = TsPacket::parse(&packets[0]).unwrap();
1745 assert!(pkt.header.pusi, "first packet must have PUSI=1");
1746 }
1747
1748 #[test]
1749 fn pusi_not_set_on_mid_section_continuation() {
1750 let body = vec![0xAA; 500];
1751 let s = test_fixtures::psi::short_section(0x42, &body);
1752 let mut p = SectionPacketiser::new(Pid::from_const(0x0100));
1753 let packets = p.packetise(&[&s]);
1754 assert!(packets.len() >= 2);
1755 let pkt1 = TsPacket::parse(&packets[0]).unwrap();
1756 let pkt2 = TsPacket::parse(&packets[1]).unwrap();
1757 assert!(pkt1.header.pusi, "first packet must have PUSI=1");
1758 assert!(
1759 !pkt2.header.pusi,
1760 "second packet is continuation, must have PUSI=0"
1761 );
1762 }
1763
1764 #[test]
1765 fn pointer_field_equals_tail_length_before_new_section() {
1766 let body1 = vec![0xA1; 197]; let s1 = test_fixtures::psi::short_section(0x52, &body1);
1771 assert_eq!(s1.len(), 200);
1772 let s2 = test_fixtures::psi::long_section(0x54, 1, 0, 0, &[0xB1; 38]); assert_eq!(s2.len(), 50);
1774
1775 let mut p = SectionPacketiser::new(Pid::from_const(0x0100));
1776 let packets = p.packetise(&[&s1, &s2]);
1777
1778 let pkt_with_pointer = packets
1780 .iter()
1781 .map(|raw| TsPacket::parse(raw).unwrap())
1782 .find(|pkt| pkt.header.pusi && pkt.payload.is_some_and(|pl| pl.first() != Some(&0)))
1783 .expect("must have a PUSI packet with non-zero pointer");
1784
1785 let payload = pkt_with_pointer.payload.unwrap();
1786 let pointer = payload[0] as usize;
1787 assert!(pointer > 0, "pointer must be non-zero");
1788 let tail_start = s1.len() - pointer;
1790 assert_eq!(&payload[1..1 + pointer], &s1[tail_start..]);
1791 }
1792
1793 #[test]
1796 fn final_packet_unused_tail_is_stuffing() {
1797 let s = test_fixtures::psi::long_section(0x42, 1, 0, 0, &[0xAA; 5]); let mut p = SectionPacketiser::new(Pid::from_const(0x0100));
1799 let packets = p.packetise(&[&s]);
1800
1801 let pkt = TsPacket::parse(&packets[0]).unwrap();
1802 let payload = pkt.payload.unwrap();
1803 assert_eq!(payload[0], 0, "pointer_field should be 0");
1804
1805 let section_end = 1 + s.len(); assert!(
1807 section_end < payload.len(),
1808 "must have stuffing after section"
1809 );
1810 for &b in &payload[section_end..] {
1811 assert_eq!(b, STUFFING_BYTE, "all trailing bytes must be 0xFF");
1812 }
1813 }
1814
1815 #[test]
1816 fn reassembler_discards_stuffing() {
1817 let s1 = test_fixtures::psi::long_section(0x42, 1, 0, 0, &[0xAA; 10]);
1818 let s2 = test_fixtures::psi::long_section(0x46, 1, 0, 0, &[0xBB; 5]);
1819
1820 let mut p = SectionPacketiser::new(Pid::from_const(0x0100));
1821 let packets = p.packetise(&[&s1, &s2]);
1822
1823 let mut reasm = SectionReassembler::default();
1824 for pkt_raw in &packets {
1825 let pkt = TsPacket::parse(pkt_raw).unwrap();
1826 reasm.feed(pkt.payload.unwrap(), pkt.header.pusi);
1827 }
1828
1829 let got: Vec<_> = core::iter::from_fn(|| reasm.pop_section()).collect();
1830 assert_eq!(got.len(), 2);
1831 assert!(
1832 reasm.is_empty(),
1833 "stuffing tail must be discarded, not buffered"
1834 );
1835 }
1836
1837 #[test]
1840 fn empty_batch_produces_no_packets() {
1841 let mut p = SectionPacketiser::new(Pid::from_const(0x0100));
1842 let packets: Vec<[u8; TS_PACKET_SIZE]> = p.packetise(&[]);
1843 assert!(packets.is_empty());
1844 }
1845
1846 #[test]
1847 fn packetise_into_clears_out_first() {
1848 let s = test_fixtures::psi::long_section(0x42, 1, 0, 0, &[0xAA; 5]);
1849 let mut p = SectionPacketiser::new(Pid::from_const(0x0100));
1850
1851 let mut out = vec![[0u8; TS_PACKET_SIZE]; 99]; let n = p.packetise_into(&[&s], &mut out);
1853 assert_eq!(n, out.len(), "out must contain only the new packets");
1854 let mut reasm = SectionReassembler::default();
1856 for pkt_raw in &out {
1857 let pkt = TsPacket::parse(pkt_raw).unwrap();
1858 reasm.feed(pkt.payload.unwrap(), pkt.header.pusi);
1859 }
1860 let got = reasm.pop_section().unwrap();
1861 assert_eq!(got.as_ref(), s.as_slice());
1862 }
1863
1864 #[test]
1865 fn pid_is_correct() {
1866 let p = SectionPacketiser::new(Pid::from_const(0x1234));
1867 assert_eq!(p.pid(), Pid::from_const(0x1234));
1868 }
1869
1870 #[test]
1871 fn with_continuity_masks_to_4_bits() {
1872 let expected = ContinuityCounter::try_new(0x0E).expect("4-bit counter");
1873 let p = SectionPacketiser::with_continuity(Pid::from_const(0x0100), expected);
1874 assert_eq!(p.continuity_counter(), expected);
1875 }
1876
1877 #[test]
1878 fn has_payload_always_true_no_adaptation() {
1879 let s = test_fixtures::psi::long_section(0x42, 1, 0, 0, &[0xAA; 50]);
1880 let mut p = SectionPacketiser::new(Pid::from_const(0x0100));
1881 let packets = p.packetise(&[&s]);
1882 for pkt_raw in &packets {
1883 let pkt = TsPacket::parse(pkt_raw).unwrap();
1884 assert!(pkt.header.has_payload(), "every packet must carry payload");
1885 assert!(
1886 !pkt.header.has_adaptation(),
1887 "no adaptation field is emitted"
1888 );
1889 assert!(!pkt.header.tei, "TEI must be false");
1890 assert_eq!(
1891 pkt.header.scrambling,
1892 ScramblingControl::NotScrambled,
1893 "scrambling must be 0"
1894 );
1895 }
1896 }
1897}