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, thiserror::Error)]
241#[error("section interval {interval:?} is below the {min:?} minimum (EN 300 468 §5.1.4.1)")]
242#[non_exhaustive]
243pub struct SectionIntervalTooShort {
244 pub interval: Duration,
246 pub min: Duration,
248}
249
250impl SectionInterval {
251 pub const fn try_new(
256 interval: Duration,
257 ) -> core::result::Result<Self, SectionIntervalTooShort> {
258 if interval.as_nanos() < MIN_SECTION_INTERVAL_NANOS {
260 Err(SectionIntervalTooShort {
261 interval,
262 min: MIN_SECTION_INTERVAL,
263 })
264 } else {
265 Ok(Self(interval))
266 }
267 }
268
269 #[must_use]
276 pub const fn from_const(interval: Duration) -> Self {
277 assert!(
278 interval.as_nanos() >= MIN_SECTION_INTERVAL_NANOS,
279 "named section interval is below the 25 ms minimum (EN 300 468 §5.1.4.1)"
280 );
281 Self(interval)
282 }
283
284 #[must_use]
286 pub const fn duration(self) -> Duration {
287 self.0
288 }
289}
290
291impl TryFrom<Duration> for SectionInterval {
292 type Error = SectionIntervalTooShort;
293 fn try_from(interval: Duration) -> core::result::Result<Self, Self::Error> {
294 Self::try_new(interval)
295 }
296}
297
298impl From<SectionInterval> for Duration {
299 fn from(interval: SectionInterval) -> Self {
300 interval.0
301 }
302}
303
304pub const MIN_SECTION_INTERVAL: Duration = Duration::from_millis(25);
307const MIN_SECTION_INTERVAL_NANOS: u128 = 25_000_000;
309
310pub const PAT_MAX_INTERVAL: SectionInterval =
312 SectionInterval::from_const(Duration::from_millis(100));
313pub const PMT_MAX_INTERVAL: SectionInterval =
315 SectionInterval::from_const(Duration::from_millis(100));
316
317#[non_exhaustive]
327#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
328#[cfg_attr(feature = "serde", derive(serde::Serialize))]
329pub struct SectionKey {
330 pub pid: Pid,
332 pub table_id: u8,
334 pub section_number: u8,
336}
337
338#[non_exhaustive]
345#[derive(Debug, Clone, PartialEq, Eq)]
346#[cfg_attr(feature = "serde", derive(serde::Serialize))]
347pub struct RejectedSection {
348 pub pid: Pid,
350 pub reason: SectionRejection,
352}
353
354#[non_exhaustive]
357#[derive(Debug, Clone, Copy, PartialEq, Eq)]
358#[cfg_attr(feature = "serde", derive(serde::Serialize))]
359pub enum SectionRejection {
360 NotASection,
365 MoreThanOneSection,
368 DuplicateSection,
371 Malformed,
373 WrongTableId {
376 expected: u8,
378 found: Option<u8>,
380 },
381}
382
383impl SectionRejection {
384 #[must_use]
386 pub fn name(&self) -> &'static str {
387 match self {
388 SectionRejection::NotASection => "not_a_section",
389 SectionRejection::MoreThanOneSection => "more_than_one_section",
390 SectionRejection::DuplicateSection => "duplicate_section",
391 SectionRejection::Malformed => "malformed",
392 SectionRejection::WrongTableId { .. } => "wrong_table_id",
393 }
394 }
395}
396
397broadcast_common::impl_spec_display!(SectionRejection);
398
399pub struct SiMux {
426 entries: Vec<Entry>,
427 rejected: Vec<RejectedSection>,
428 packetisers: Vec<SectionPacketiser>,
430}
431
432struct Entry {
433 key: SectionKey,
434 section: Section<'static>,
435 interval: SectionInterval,
436 last_emit: Option<Timestamp>,
437}
438
439fn packetiser_for(packetisers: &mut Vec<SectionPacketiser>, pid: Pid) -> &mut SectionPacketiser {
443 if let Some(idx) = packetisers.iter().position(|p| p.pid() == pid) {
444 &mut packetisers[idx]
445 } else {
446 packetisers.push(SectionPacketiser::new(pid));
447 let last = packetisers.len() - 1;
448 &mut packetisers[last]
449 }
450}
451
452impl SiMux {
453 pub fn new() -> Self {
455 Self {
456 entries: Vec::new(),
457 rejected: Vec::new(),
458 packetisers: Vec::new(),
459 }
460 }
461
462 pub fn upsert(
482 &mut self,
483 pid: Pid,
484 section: Vec<u8>,
485 interval: SectionInterval,
486 ) -> core::result::Result<(), SectionRejection> {
487 let rejection = self.register(pid, section, interval);
488 match rejection {
489 Some(reason) => {
490 self.rejected.push(RejectedSection { pid, reason });
491 Err(reason)
492 }
493 None => Ok(()),
494 }
495 }
496
497 fn register(
500 &mut self,
501 pid: Pid,
502 section: Vec<u8>,
503 interval: SectionInterval,
504 ) -> Option<SectionRejection> {
505 let batch = split_sections(§ion);
506 let owned = match batch.len() {
507 0 => return Some(SectionRejection::NotASection),
508 1 => match Section::parse(batch[0]) {
509 Ok(parsed) => parsed,
510 Err(_) => return Some(SectionRejection::Malformed),
511 },
512 _ => {
513 if !sections_are_distinct(&batch) {
514 return Some(SectionRejection::DuplicateSection);
515 }
516 return Some(SectionRejection::MoreThanOneSection);
517 }
518 };
519 let key = SectionKey {
520 pid,
521 table_id: owned.table_id,
522 section_number: owned.section_number,
523 };
524 let stored = Section::into_owned(owned);
525 if let Some(entry) = self.entries.iter_mut().find(|e| e.key == key) {
526 entry.section = stored;
527 entry.interval = interval;
528 } else {
529 self.entries.push(Entry {
530 key,
531 section: stored,
532 interval,
533 last_emit: None,
534 });
535 }
536 None
537 }
538
539 #[must_use]
544 pub fn rejected(&self) -> &[RejectedSection] {
545 &self.rejected
546 }
547
548 pub fn upsert_pat(&mut self, section: Vec<u8>) -> core::result::Result<(), SectionRejection> {
554 upsert_checked(
555 self,
556 well_known::PAT,
557 section,
558 PAT_MAX_INTERVAL,
559 TABLE_ID_PAT,
560 )
561 }
562
563 pub fn upsert_pmt(
572 &mut self,
573 pid: Pid,
574 section: Vec<u8>,
575 ) -> core::result::Result<(), SectionRejection> {
576 upsert_checked(self, pid, section, PMT_MAX_INTERVAL, TABLE_ID_PMT)
577 }
578
579 pub fn upsert_sdt_actual(
587 &mut self,
588 section: Vec<u8>,
589 ) -> core::result::Result<(), SectionRejection> {
590 upsert_checked(
591 self,
592 well_known::SDT_BAT,
593 section,
594 SDT_ACTUAL_MAX_INTERVAL,
595 TABLE_ID_SDT_ACTUAL,
596 )
597 }
598
599 pub fn upsert_nit(&mut self, section: Vec<u8>) -> core::result::Result<(), SectionRejection> {
605 upsert_checked(
606 self,
607 well_known::NIT,
608 section,
609 NIT_MAX_INTERVAL,
610 TABLE_ID_NIT_ACTUAL,
611 )
612 }
613
614 pub fn upsert_tdt(&mut self, section: Vec<u8>) -> core::result::Result<(), SectionRejection> {
622 upsert_checked(
623 self,
624 well_known::TDT_TOT,
625 section,
626 TDT_MAX_INTERVAL,
627 TABLE_ID_TDT,
628 )
629 }
630
631 pub fn upsert_tot(&mut self, section: Vec<u8>) -> core::result::Result<(), SectionRejection> {
639 upsert_checked(
640 self,
641 well_known::TDT_TOT,
642 section,
643 TOT_MAX_INTERVAL,
644 TABLE_ID_TOT,
645 )
646 }
647
648 pub fn poll_into(&mut self, now: Timestamp, out: &mut Vec<[u8; TS_PACKET_SIZE]>) -> usize {
655 out.clear();
656 let before = out.len();
657
658 let packetisers = &mut self.packetisers;
659 for entry in &mut self.entries {
660 let due = match entry.last_emit {
661 None => true,
662 Some(last) => now.saturating_sub(last) >= entry.interval.duration(),
663 };
664 if due {
665 let mut tmp = Vec::new();
666 if let Ok(bytes) = entry.section.serialize() {
667 let refs: [&[u8]; 1] = [&bytes];
668 let packetiser = packetiser_for(packetisers, entry.key.pid);
669 packetiser.packetise_into(&refs, &mut tmp);
670 }
671 out.append(&mut tmp);
672 entry.last_emit = Some(now);
673 }
674 }
675
676 out.len() - before
677 }
678
679 pub fn poll(&mut self, now: Timestamp) -> Vec<[u8; TS_PACKET_SIZE]> {
681 let mut out = Vec::new();
682 self.poll_into(now, &mut out);
683 out
684 }
685}
686
687fn sections_are_distinct(sections: &[&[u8]]) -> bool {
688 let mut keys: Vec<(u8, u8)> = Vec::with_capacity(sections.len());
689 for bytes in sections {
690 let Ok(section) = Section::parse(bytes) else {
691 return true;
692 };
693 let key = (section.table_id, section.section_number);
694 if keys.contains(&key) {
695 return false;
696 }
697 keys.push(key);
698 }
699 true
700}
701
702fn upsert_checked(
705 mux: &mut SiMux,
706 pid: Pid,
707 section: Vec<u8>,
708 interval: SectionInterval,
709 table_id: u8,
710) -> core::result::Result<(), SectionRejection> {
711 if split_sections(§ion)
712 .first()
713 .is_some_and(|s| s.first().copied() != Some(table_id))
714 {
715 let reason = SectionRejection::WrongTableId {
716 expected: table_id,
717 found: section.first().copied(),
718 };
719 mux.rejected.push(RejectedSection { pid, reason });
720 return Err(reason);
721 }
722 mux.upsert(pid, section, interval)
723}
724
725impl Default for SiMux {
726 fn default() -> Self {
727 Self::new()
728 }
729}
730
731fn split_sections(data: &[u8]) -> Vec<&[u8]> {
737 let mut result = Vec::new();
738 let mut pos = 0;
739 while let Some(end) = crate::ts::section_total_len(&data[pos..]).map(|len| pos + len) {
740 if end > data.len() {
741 break;
742 }
743 result.push(&data[pos..end]);
744 pos = end;
745 }
746 result
747}
748
749#[cfg(test)]
750mod tests {
751 use super::*;
752 use crate::ts::{SectionReassembler, TsPacket};
753 use alloc::vec;
754 use alloc::vec::Vec;
755
756 fn concat_sections(sections: &[Vec<u8>]) -> Vec<u8> {
759 let total: usize = sections.iter().map(|s| s.len()).sum();
760 let mut out = Vec::with_capacity(total);
761 for s in sections {
762 out.extend_from_slice(s);
763 }
764 out
765 }
766
767 fn assert_round_trip(sections: &[Vec<u8>]) {
770 let mut packetiser = SectionPacketiser::new(Pid::from_const(0x0100));
771 let refs: Vec<&[u8]> = sections.iter().map(|s| s.as_slice()).collect();
772 let packets = packetiser.packetise(&refs);
773
774 let mut reasm = SectionReassembler::default();
775 for pkt_raw in &packets {
776 let pkt = TsPacket::parse(pkt_raw).expect("parse generated packet");
777 let payload = pkt.payload.expect("payload present");
778 let pusi = pkt.header.pusi;
779 reasm.feed(payload, pusi);
780 }
781
782 let got: Vec<_> = core::iter::from_fn(|| reasm.pop_section()).collect();
783 assert_eq!(
784 got.len(),
785 sections.len(),
786 "section count mismatch: expected {}, got {}",
787 sections.len(),
788 got.len()
789 );
790 for (i, (orig, round)) in sections.iter().zip(got.iter()).enumerate() {
791 assert_eq!(
792 round.as_ref(),
793 orig.as_slice(),
794 "section {i} round-trip mismatch"
795 );
796 }
797 assert!(reasm.is_empty(), "reassembler should be empty after drain");
798 }
799
800 #[test]
806 fn many_sections_with_boundary_straddling_sizes_round_trip() {
807 let sections: Vec<Vec<u8>> = (0..400usize)
808 .map(|n| {
809 let body: Vec<u8> = (0..n).map(|i| (i % 251) as u8).collect();
810 test_fixtures::psi::short_section((n % 200) as u8, &body)
811 })
812 .collect();
813 assert_round_trip(§ions);
814 }
815
816 #[test]
819 fn split_single_section() {
820 let s = test_fixtures::psi::long_section(0x42, 1, 0, 0, &[0xAA; 5]);
821 let refs = split_sections(&s);
822 assert_eq!(refs.len(), 1);
823 assert_eq!(refs[0], s.as_slice());
824 }
825
826 #[test]
827 fn split_two_sections() {
828 let s1 = test_fixtures::psi::long_section(0x42, 1, 0, 0, &[0x01, 0x02]);
829 let s2 = test_fixtures::psi::long_section(0x46, 1, 0, 0, &[0x03, 0x04, 0x05]);
830 let both = concat_sections(&[s1.clone(), s2.clone()]);
831 let refs = split_sections(&both);
832 assert_eq!(refs.len(), 2);
833 assert_eq!(refs[0], s1.as_slice());
834 assert_eq!(refs[1], s2.as_slice());
835 }
836
837 #[test]
838 fn split_empty_input() {
839 let refs = split_sections(&[]);
840 assert!(refs.is_empty());
841 }
842
843 #[test]
844 fn split_trailing_garbage_ignored() {
845 let s = test_fixtures::psi::long_section(0x42, 1, 0, 0, &[0xAA; 3]);
846 let mut data = s.clone();
847 data.push(0xFF); let refs = split_sections(&data);
849 assert_eq!(refs.len(), 1);
850 assert_eq!(refs[0], s.as_slice());
851 }
852
853 fn cc(v: u8) -> ContinuityCounter {
854 ContinuityCounter::try_new(v).expect("4-bit counter")
855 }
856
857 #[test]
860 fn interval_constants_match_spec() {
861 assert_eq!(NIT_MAX_INTERVAL.duration(), Duration::from_secs(10));
863 assert_eq!(BAT_MAX_INTERVAL.duration(), Duration::from_secs(10));
864 assert_eq!(SDT_ACTUAL_MAX_INTERVAL.duration(), Duration::from_secs(2));
865 assert_eq!(SDT_OTHER_MAX_INTERVAL.duration(), Duration::from_secs(10));
866 assert_eq!(
867 EIT_PF_ACTUAL_MAX_INTERVAL.duration(),
868 Duration::from_secs(2)
869 );
870 assert_eq!(
871 EIT_PF_OTHER_MAX_INTERVAL.duration(),
872 Duration::from_secs(10)
873 );
874 assert_eq!(EIT_SCHED_MAX_INTERVAL.duration(), Duration::from_secs(10));
875 assert_eq!(
876 EIT_SCHED_EXT_MAX_INTERVAL.duration(),
877 Duration::from_secs(30)
878 );
879 assert_eq!(TDT_MAX_INTERVAL.duration(), Duration::from_secs(30));
880 assert_eq!(TOT_MAX_INTERVAL.duration(), Duration::from_secs(30));
881
882 assert_eq!(PAT_MAX_INTERVAL.duration(), Duration::from_millis(100));
884 assert_eq!(PMT_MAX_INTERVAL.duration(), Duration::from_millis(100));
885
886 assert_eq!(MIN_SECTION_INTERVAL, Duration::from_millis(25));
888 }
889
890 #[test]
893 fn new_and_default_simux_are_empty() {
894 for mut mux in [SiMux::new(), SiMux::default()] {
895 let pkts = mux.poll(Timestamp::ZERO);
896 assert!(pkts.is_empty());
897 }
898 }
899
900 #[test]
901 fn first_poll_always_emits() {
902 let s = test_fixtures::psi::long_section(0x42, 1, 0, 0, &[0xAA; 10]);
903 let mut mux = SiMux::new();
904 mux.upsert(
905 Pid::from_const(0x0100),
906 s.clone(),
907 SectionInterval::from_const(Duration::from_millis(100)),
908 )
909 .expect("scheduled section");
910 let pkts = mux.poll(Timestamp::ZERO);
911 assert!(!pkts.is_empty(), "first poll must emit");
912 }
913
914 #[test]
915 fn first_poll_emits_all_entries() {
916 let s1 = test_fixtures::psi::long_section(0x42, 1, 0, 0, &[0x01; 5]);
917 let s2 = test_fixtures::psi::long_section(0x46, 1, 0, 0, &[0x02; 5]);
918 let mut mux = SiMux::new();
919 mux.upsert(
920 Pid::from_const(0x0100),
921 s1.clone(),
922 SectionInterval::from_const(Duration::from_millis(100)),
923 )
924 .expect("scheduled section");
925 mux.upsert(
926 Pid::from_const(0x0200),
927 s2.clone(),
928 SectionInterval::from_const(Duration::from_millis(200)),
929 )
930 .expect("scheduled section");
931 let pkts = mux.poll(Timestamp::ZERO);
932 let pids: Vec<Pid> = pkts
934 .iter()
935 .map(|raw| TsPacket::parse(raw).unwrap().header.pid)
936 .collect();
937 assert!(pids.contains(&Pid::from_const(0x0100)));
938 assert!(pids.contains(&Pid::from_const(0x0200)));
939 }
940
941 #[test]
944 fn entry_emits_only_when_due() {
945 let s = test_fixtures::psi::long_section(0x42, 1, 0, 0, &[0xAA; 10]);
946 let mut mux = SiMux::new();
947 mux.upsert(
948 Pid::from_const(0x0100),
949 s.clone(),
950 SectionInterval::from_const(Duration::from_millis(100)),
951 )
952 .expect("scheduled section");
953
954 let pkts0 = mux.poll(Timestamp::ZERO);
956 assert!(!pkts0.is_empty());
957
958 let pkts50 = mux.poll(Timestamp::from_millis(50));
960 assert!(pkts50.is_empty(), "should not emit at t=50");
961
962 let pkts99 = mux.poll(Timestamp::from_millis(99));
964 assert!(pkts99.is_empty(), "should not emit at t=99");
965
966 let pkts100 = mux.poll(Timestamp::from_millis(100));
968 assert!(!pkts100.is_empty(), "should emit at t=100");
969 }
970
971 #[test]
972 fn two_entries_different_cadence() {
973 let s1 = test_fixtures::psi::long_section(0x42, 1, 0, 0, &[0x01; 5]);
974 let s2 = test_fixtures::psi::long_section(0x46, 1, 0, 0, &[0x02; 5]);
975 let mut mux = SiMux::new();
976 mux.upsert(
977 Pid::from_const(0x0100),
978 concat_sections(&[s1]),
979 SectionInterval::from_const(Duration::from_millis(100)),
980 )
981 .expect("scheduled section");
982 mux.upsert(
983 Pid::from_const(0x0200),
984 concat_sections(&[s2]),
985 SectionInterval::from_const(Duration::from_millis(200)),
986 )
987 .expect("scheduled section");
988
989 let pkts = mux.poll(Timestamp::ZERO);
991 assert!(!pkts.is_empty());
992
993 let pkts100 = mux.poll(Timestamp::from_millis(100));
995 assert!(!pkts100.is_empty());
996 let pids100: Vec<Pid> = pkts100
997 .iter()
998 .map(|raw| TsPacket::parse(raw).unwrap().header.pid)
999 .collect();
1000 assert!(
1001 pids100.contains(&Pid::from_const(0x0100)),
1002 "PID 0x0100 should emit at t=100"
1003 );
1004 assert!(
1005 !pids100.contains(&Pid::from_const(0x0200)),
1006 "PID 0x0200 should NOT emit at t=100"
1007 );
1008
1009 let pkts150 = mux.poll(Timestamp::from_millis(150));
1011 assert!(pkts150.is_empty(), "neither should emit at t=150");
1012
1013 let pkts200 = mux.poll(Timestamp::from_millis(200));
1015 let pids200: Vec<Pid> = pkts200
1016 .iter()
1017 .map(|raw| TsPacket::parse(raw).unwrap().header.pid)
1018 .collect();
1019 assert!(
1020 pids200.contains(&Pid::from_const(0x0100)),
1021 "PID 0x0100 should emit at t=200"
1022 );
1023 assert!(
1024 pids200.contains(&Pid::from_const(0x0200)),
1025 "PID 0x0200 should emit at t=200"
1026 );
1027 }
1028
1029 #[test]
1030 fn entry_emits_again_after_full_interval() {
1031 let s = test_fixtures::psi::long_section(0x42, 1, 0, 0, &[0xAA; 20]);
1032 let mut mux = SiMux::new();
1033 mux.upsert(
1034 Pid::from_const(0x0100),
1035 s,
1036 SectionInterval::from_const(Duration::from_secs(1)),
1037 )
1038 .expect("scheduled section");
1039
1040 let n0 = mux.poll_into(Timestamp::ZERO, &mut Vec::new());
1042 assert!(n0 > 0);
1043
1044 let mut buf = Vec::new();
1046 let n999 = mux.poll_into(Timestamp::from_millis(999), &mut buf);
1047 assert_eq!(n999, 0);
1048
1049 let mut buf2 = Vec::new();
1051 let n1000 = mux.poll_into(Timestamp::from_millis(1000), &mut buf2);
1052 assert!(n1000 > 0);
1053 }
1054
1055 #[test]
1058 fn upsert_updates_existing_entry() {
1059 let s1 = test_fixtures::psi::long_section(0x42, 1, 0, 0, &[0xAA; 5]);
1062 let s2 = test_fixtures::psi::long_section(0x42, 1, 0, 0, &[0xBB; 10]);
1063 let mut mux = SiMux::new();
1064
1065 mux.upsert(
1066 Pid::from_const(0x0100),
1067 s1,
1068 SectionInterval::from_const(Duration::from_millis(100)),
1069 )
1070 .expect("scheduled section");
1071 mux.upsert(
1072 Pid::from_const(0x0100),
1073 s2.clone(),
1074 SectionInterval::from_const(Duration::from_millis(200)),
1075 )
1076 .expect("scheduled section");
1077
1078 let pkts = mux.poll(Timestamp::ZERO);
1079
1080 let mut reasm = SectionReassembler::default();
1082 for raw in &pkts {
1083 let pkt = TsPacket::parse(raw).unwrap();
1084 if pkt.header.pid == Pid::from_const(0x0100) {
1085 reasm.feed(pkt.payload.unwrap(), pkt.header.pusi);
1086 }
1087 }
1088 let got: Vec<_> = core::iter::from_fn(|| reasm.pop_section()).collect();
1089 assert_eq!(got.len(), 1);
1090 assert_eq!(got[0].as_ref(), s2.as_slice());
1091 }
1092
1093 #[test]
1100 fn upsert_tdt_then_tot_both_emitted_with_continuous_cc() {
1101 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();
1104
1105 mux.upsert_tdt(tdt.clone()).expect("scheduled section");
1106 mux.upsert_tot(tot.clone()).expect("scheduled section");
1107
1108 let pkts = mux.poll(Timestamp::ZERO);
1109 assert!(!pkts.is_empty());
1110
1111 let mut table_ids_seen = Vec::new();
1112 let mut reasm = SectionReassembler::default();
1113 let mut prev_cc: Option<ContinuityCounter> = None;
1114 for raw in &pkts {
1115 let pkt = TsPacket::parse(raw).unwrap();
1116 assert_eq!(pkt.header.pid, well_known::TDT_TOT);
1117 if let Some(prev) = prev_cc {
1118 assert_eq!(
1119 pkt.header.continuity_counter.forward_distance_from(prev),
1120 1,
1121 "continuity counter must be continuous across table kinds on one PID"
1122 );
1123 }
1124 prev_cc = Some(pkt.header.continuity_counter);
1125 reasm.feed(pkt.payload.unwrap(), pkt.header.pusi);
1126 }
1127 while let Some(section) = reasm.pop_section() {
1128 table_ids_seen.push(section.as_ref()[0]);
1129 }
1130
1131 assert!(table_ids_seen.contains(&0x70), "TDT missing from output");
1132 assert!(table_ids_seen.contains(&0x73), "TOT missing from output");
1133 }
1134
1135 #[test]
1138 fn upsert_sdt_and_bat_both_emitted() {
1139 let sdt = test_fixtures::psi::long_section(0x42, 1, 0, 0, &[0xCC; 5]);
1140 let bat = test_fixtures::psi::long_section(0x4A, 1, 0, 0, &[0xDD; 6]);
1141 let mut mux = SiMux::new();
1142
1143 mux.upsert_sdt_actual(sdt.clone())
1144 .expect("scheduled section");
1145 mux.upsert(
1146 well_known::SDT_BAT,
1147 bat.clone(),
1148 SectionInterval::from_const(Duration::from_millis(1000)),
1149 )
1150 .expect("scheduled section");
1151
1152 let pkts = mux.poll(Timestamp::ZERO);
1153 let mut table_ids_seen = Vec::new();
1154 let mut reasm = SectionReassembler::default();
1155 for raw in &pkts {
1156 let pkt = TsPacket::parse(raw).unwrap();
1157 reasm.feed(pkt.payload.unwrap(), pkt.header.pusi);
1158 }
1159 while let Some(section) = reasm.pop_section() {
1160 table_ids_seen.push(section.as_ref()[0]);
1161 }
1162
1163 assert!(table_ids_seen.contains(&0x42), "SDT actual missing");
1164 assert!(table_ids_seen.contains(&0x4A), "BAT missing");
1165 }
1166
1167 #[test]
1170 fn upsert_sdt_actual_uses_correct_pid() {
1171 let s = test_fixtures::psi::long_section(0x42, 1, 0, 0, &[0x01]);
1172 let mut mux = SiMux::new();
1173 mux.upsert_sdt_actual(s).expect("scheduled section");
1174 let pkts = mux.poll(Timestamp::ZERO);
1175 let pids: Vec<Pid> = pkts
1176 .iter()
1177 .map(|raw| TsPacket::parse(raw).unwrap().header.pid)
1178 .collect();
1179 assert!(pids.iter().all(|&p| p == well_known::SDT_BAT));
1180 }
1181
1182 #[test]
1183 fn upsert_pat_uses_correct_pid() {
1184 let s = test_fixtures::psi::long_section(0x00, 1, 0, 0, &[0x01, 0x02]);
1185 let mut mux = SiMux::new();
1186 mux.upsert_pat(s).expect("scheduled section");
1187 let pkts = mux.poll(Timestamp::ZERO);
1188 assert!(!pkts.is_empty());
1189 let pids: Vec<Pid> = pkts
1190 .iter()
1191 .map(|raw| TsPacket::parse(raw).unwrap().header.pid)
1192 .collect();
1193 assert!(pids.iter().all(|&p| p == well_known::PAT));
1194 assert!(
1195 mux.poll(Timestamp::from_nanos(
1196 (PAT_MAX_INTERVAL.duration() / 2).as_nanos() as u64
1197 ))
1198 .is_empty()
1199 );
1200 assert!(
1201 !mux.poll(Timestamp::from_nanos(
1202 PAT_MAX_INTERVAL.duration().as_nanos() as u64
1203 ))
1204 .is_empty()
1205 );
1206 }
1207
1208 #[test]
1209 fn upsert_nit_uses_correct_pid() {
1210 let s = test_fixtures::psi::long_section(0x40, 1, 0, 0, &[0x01]);
1211 let mut mux = SiMux::new();
1212 mux.upsert_nit(s).expect("scheduled section");
1213 let pkts = mux.poll(Timestamp::ZERO);
1214 assert!(!pkts.is_empty());
1215 let pids: Vec<Pid> = pkts
1216 .iter()
1217 .map(|raw| TsPacket::parse(raw).unwrap().header.pid)
1218 .collect();
1219 assert!(pids.iter().all(|&p| p == well_known::NIT));
1220 assert!(
1221 mux.poll(Timestamp::from_nanos(
1222 (NIT_MAX_INTERVAL.duration() / 2).as_nanos() as u64
1223 ))
1224 .is_empty()
1225 );
1226 assert!(
1227 !mux.poll(Timestamp::from_nanos(
1228 NIT_MAX_INTERVAL.duration().as_nanos() as u64
1229 ))
1230 .is_empty()
1231 );
1232 }
1233
1234 #[test]
1235 fn upsert_tdt_uses_correct_pid() {
1236 let s = test_fixtures::psi::long_section(0x70, 1, 0, 0, &[0x01]);
1237 let mut mux = SiMux::new();
1238 mux.upsert_tdt(s).expect("scheduled section");
1239 let pkts = mux.poll(Timestamp::ZERO);
1240 let pids: Vec<Pid> = pkts
1241 .iter()
1242 .map(|raw| TsPacket::parse(raw).unwrap().header.pid)
1243 .collect();
1244 assert!(pids.iter().all(|&p| p == well_known::TDT_TOT));
1245 }
1246
1247 #[test]
1248 fn upsert_tot_uses_correct_pid() {
1249 let s = test_fixtures::psi::long_section(0x73, 1, 0, 0, &[0x01]);
1250 let mut mux = SiMux::new();
1251 mux.upsert_tot(s).expect("scheduled section");
1252 let pkts = mux.poll(Timestamp::ZERO);
1253 let pids: Vec<Pid> = pkts
1254 .iter()
1255 .map(|raw| TsPacket::parse(raw).unwrap().header.pid)
1256 .collect();
1257 assert!(pids.iter().all(|&p| p == well_known::TDT_TOT));
1258 }
1259
1260 #[test]
1263 fn upsert_rejects_an_empty_input() {
1264 let mut mux = SiMux::new();
1267 let pat = test_fixtures::psi::pat_section(1, 0, &[(1, 0x1000)]);
1268 mux.upsert_pat(pat.clone()).expect("PAT is schedulable");
1269 assert_eq!(
1270 mux.upsert(well_known::PAT, Vec::new(), PAT_MAX_INTERVAL),
1271 Err(SectionRejection::NotASection)
1272 );
1273 assert_eq!(mux.rejected().len(), 1);
1274 assert_eq!(mux.rejected()[0].pid, well_known::PAT);
1275 let pkts = mux.poll(Timestamp::ZERO);
1276 let mut reasm = SectionReassembler::default();
1277 for raw in &pkts {
1278 let pkt = TsPacket::parse(raw).unwrap();
1279 reasm.feed(pkt.payload.unwrap(), pkt.header.pusi);
1280 }
1281 let got: Vec<_> = core::iter::from_fn(|| reasm.pop_section()).collect();
1282 assert_eq!(got.len(), 1);
1283 assert_eq!(got[0].as_ref(), pat.as_slice());
1284 }
1285
1286 #[test]
1287 fn upsert_rejects_two_sections_that_share_a_key() {
1288 let a = test_fixtures::psi::long_section(0x42, 1, 0, 0, &[0x01]);
1289 let b = test_fixtures::psi::long_section(0x42, 1, 0, 0, &[0x02]);
1290 let mut mux = SiMux::new();
1291 assert_eq!(
1292 mux.upsert(
1293 well_known::SDT_BAT,
1294 concat_sections(&[a, b]),
1295 SDT_ACTUAL_MAX_INTERVAL
1296 ),
1297 Err(SectionRejection::DuplicateSection)
1298 );
1299 }
1300
1301 #[test]
1302 fn upsert_rejects_a_second_section_of_another_table() {
1303 let sdt = test_fixtures::psi::long_section(0x42, 1, 0, 0, &[0x01]);
1304 let bat = test_fixtures::psi::long_section(0x4A, 1, 0, 0, &[0x02]);
1305 let mut mux = SiMux::new();
1306 assert_eq!(
1307 mux.upsert(
1308 well_known::SDT_BAT,
1309 concat_sections(&[sdt, bat]),
1310 SDT_ACTUAL_MAX_INTERVAL
1311 ),
1312 Err(SectionRejection::MoreThanOneSection)
1313 );
1314 }
1315
1316 #[test]
1317 fn upsert_keeps_a_complete_section_and_rejects_a_trailing_fragment() {
1318 let whole = test_fixtures::psi::long_section(0x42, 1, 0, 0, &[0x01]);
1321 let mut with_tail = whole.clone();
1322 with_tail.extend_from_slice(&[0x4A, 0x00]);
1323 let mut mux = SiMux::new();
1324 mux.upsert(well_known::SDT_BAT, with_tail, SDT_ACTUAL_MAX_INTERVAL)
1325 .expect("the complete section is schedulable");
1326 let pkts = mux.poll(Timestamp::ZERO);
1327 let mut reasm = SectionReassembler::default();
1328 for raw in &pkts {
1329 let pkt = TsPacket::parse(raw).unwrap();
1330 reasm.feed(pkt.payload.unwrap(), pkt.header.pusi);
1331 }
1332 let got: Vec<_> = core::iter::from_fn(|| reasm.pop_section()).collect();
1333 assert_eq!(got.len(), 1);
1334 assert_eq!(got[0].as_ref(), whole.as_slice());
1335 }
1336
1337 #[test]
1338 fn sections_of_one_table_are_keyed_by_their_section_number() {
1339 let first = test_fixtures::psi::long_section(0x4E, 1, 0, 0, &[0x01]);
1340 let second = test_fixtures::psi::long_section(0x4E, 1, 0, 1, &[0x02]);
1341 let mut mux = SiMux::new();
1342 let pid = Pid::from_const(0x0012);
1343 mux.upsert(pid, first.clone(), EIT_SCHED_MAX_INTERVAL)
1344 .expect("first section");
1345 mux.upsert(pid, second.clone(), EIT_SCHED_MAX_INTERVAL)
1346 .expect("second section");
1347 let pkts = mux.poll(Timestamp::ZERO);
1348 let mut reasm = SectionReassembler::default();
1349 for raw in &pkts {
1350 let pkt = TsPacket::parse(raw).unwrap();
1351 reasm.feed(pkt.payload.unwrap(), pkt.header.pusi);
1352 }
1353 let got: Vec<_> = core::iter::from_fn(|| reasm.pop_section()).collect();
1354 assert_eq!(got.len(), 2, "both sections of the table must go out");
1355 }
1356
1357 #[test]
1358 fn upsert_pat_rejects_a_section_of_another_table() {
1359 let sdt = test_fixtures::psi::long_section(0x42, 1, 0, 0, &[0x01]);
1360 let mut mux = SiMux::new();
1361 assert_eq!(
1362 mux.upsert_pat(sdt),
1363 Err(SectionRejection::WrongTableId {
1364 expected: TABLE_ID_PAT,
1365 found: Some(0x42),
1366 })
1367 );
1368 assert!(mux.poll(Timestamp::ZERO).is_empty());
1369 }
1370
1371 #[test]
1374 fn simux_round_trip_single_entry() {
1375 let s1 = test_fixtures::psi::long_section(0x42, 1, 0, 0, &[0xAA; 20]);
1376 let interval = SectionInterval::from_const(Duration::from_millis(100));
1377 let mut mux = SiMux::new();
1378 mux.upsert(Pid::from_const(0x0100), s1.clone(), interval)
1379 .expect("scheduled section");
1380
1381 let pkts = mux.poll(Timestamp::ZERO);
1382
1383 let mut reasm = SectionReassembler::default();
1384 for raw in &pkts {
1385 let pkt = TsPacket::parse(raw).unwrap();
1386 if pkt.header.pid == Pid::from_const(0x0100) {
1387 reasm.feed(pkt.payload.unwrap(), pkt.header.pusi);
1388 }
1389 }
1390 let got: Vec<_> = core::iter::from_fn(|| reasm.pop_section()).collect();
1391 assert_eq!(got.len(), 1, "round-trip must recover the section");
1392 assert_eq!(got[0].as_ref(), s1.as_slice());
1393 }
1394
1395 #[test]
1396 fn simux_round_trip_multi_pid() {
1397 let s_a = test_fixtures::psi::long_section(0x42, 1, 0, 0, &[0xA0; 10]);
1398 let s_b = test_fixtures::psi::long_section(0x46, 1, 0, 0, &[0xB0; 10]);
1399 let mut mux = SiMux::new();
1400 mux.upsert(
1401 Pid::from_const(0x0100),
1402 s_a.clone(),
1403 SectionInterval::from_const(Duration::from_millis(100)),
1404 )
1405 .expect("scheduled section");
1406 mux.upsert(
1407 Pid::from_const(0x0200),
1408 s_b.clone(),
1409 SectionInterval::from_const(Duration::from_millis(100)),
1410 )
1411 .expect("scheduled section");
1412
1413 let pkts = mux.poll(Timestamp::ZERO);
1414
1415 let mut reasm_a = SectionReassembler::default();
1416 let mut reasm_b = SectionReassembler::default();
1417 for raw in &pkts {
1418 let pkt = TsPacket::parse(raw).unwrap();
1419 match pkt.header.pid.value() {
1420 0x0100 => reasm_a.feed(pkt.payload.unwrap(), pkt.header.pusi),
1421 0x0200 => reasm_b.feed(pkt.payload.unwrap(), pkt.header.pusi),
1422 _ => {}
1423 }
1424 }
1425 let got_a: Vec<_> = core::iter::from_fn(|| reasm_a.pop_section()).collect();
1426 let got_b: Vec<_> = core::iter::from_fn(|| reasm_b.pop_section()).collect();
1427 assert_eq!(got_a.len(), 1);
1428 assert_eq!(got_b.len(), 1);
1429 assert_eq!(got_a[0].as_ref(), s_a.as_slice());
1430 assert_eq!(got_b[0].as_ref(), s_b.as_slice());
1431 }
1432
1433 #[test]
1436 fn continuity_counter_continuous_across_polls() {
1437 let s = test_fixtures::psi::long_section(0x42, 1, 0, 0, &[0xAA; 250]);
1439 let mut mux = SiMux::new();
1440 mux.upsert(
1441 Pid::from_const(0x0100),
1442 s,
1443 SectionInterval::from_const(Duration::from_millis(100)),
1444 )
1445 .expect("scheduled section");
1446
1447 let pkts1 = mux.poll(Timestamp::ZERO);
1448 assert!(pkts1.len() >= 2, "need ≥2 packets to test CC continuity");
1449
1450 let last_cc_pkts1 = TsPacket::parse(&pkts1[pkts1.len() - 1])
1451 .unwrap()
1452 .header
1453 .continuity_counter;
1454
1455 let pkts2 = mux.poll(Timestamp::from_millis(100));
1456 assert!(!pkts2.is_empty(), "second poll must emit");
1457
1458 let first_cc_pkts2 = TsPacket::parse(&pkts2[0])
1459 .unwrap()
1460 .header
1461 .continuity_counter;
1462
1463 assert_eq!(
1464 first_cc_pkts2.forward_distance_from(last_cc_pkts1),
1465 1,
1466 "CC must continue across poll cycles"
1467 );
1468 }
1469
1470 #[test]
1473 fn poll_into_clears_out_before_appending() {
1474 let s = test_fixtures::psi::long_section(0x42, 1, 0, 0, &[0xAA; 5]);
1475 let mut mux = SiMux::new();
1476 mux.upsert(
1477 Pid::from_const(0x0100),
1478 s,
1479 SectionInterval::from_const(Duration::from_millis(100)),
1480 )
1481 .expect("scheduled section");
1482
1483 let mut out = vec![[0u8; TS_PACKET_SIZE]; 42];
1484 let n = mux.poll_into(Timestamp::ZERO, &mut out);
1485 assert_eq!(n, out.len(), "out must contain only new packets");
1486 }
1487
1488 #[test]
1494 #[should_panic(expected = "25 ms")]
1495 fn named_interval_const_rejects_sub_25ms_interval() {
1496 let _ = SectionInterval::from_const(Duration::from_millis(10));
1497 }
1498
1499 #[test]
1503 fn section_interval_rejects_below_the_25ms_floor() {
1504 for bad in [
1505 Duration::ZERO,
1506 Duration::from_millis(1),
1507 Duration::from_millis(24),
1508 MIN_SECTION_INTERVAL - Duration::from_nanos(1),
1509 ] {
1510 let err = SectionInterval::try_new(bad).unwrap_err();
1511 assert_eq!(err.interval, bad);
1512 assert_eq!(err.min, MIN_SECTION_INTERVAL);
1513 assert!(SectionInterval::try_from(bad).is_err());
1514 }
1515 assert_eq!(
1516 SectionInterval::try_new(MIN_SECTION_INTERVAL)
1517 .expect("the floor itself is valid")
1518 .duration(),
1519 MIN_SECTION_INTERVAL
1520 );
1521 assert_eq!(
1522 Duration::from(SectionInterval::from_const(Duration::from_secs(2))),
1523 Duration::from_secs(2)
1524 );
1525 }
1526
1527 #[test]
1528 fn upsert_accepts_25ms_interval() {
1529 let s = test_fixtures::psi::long_section(0x42, 1, 0, 0, &[0xAA; 5]);
1530 let mut mux = SiMux::new();
1531 mux.upsert(
1532 Pid::from_const(0x0100),
1533 s,
1534 SectionInterval::from_const(MIN_SECTION_INTERVAL),
1535 )
1536 .expect("scheduled section");
1537 let pkts = mux.poll(Timestamp::ZERO);
1538 assert!(!pkts.is_empty());
1539 }
1540
1541 #[test]
1544 fn round_trip_single_short_section() {
1545 let s = test_fixtures::psi::long_section(0x42, 1, 0, 0, &[0xAA; 10]);
1546 assert_round_trip(&[s]);
1547 }
1548
1549 #[test]
1550 fn round_trip_one_byte_body() {
1551 let s = test_fixtures::psi::long_section(0x46, 1, 0, 0, &[0xBB]); assert_round_trip(&[s]);
1553 }
1554
1555 #[test]
1556 fn round_trip_section_exactly_pusi_cap_boundary() {
1557 let body = vec![0xCC; PUSI_PAYLOAD_CAP - 3];
1559 let s = test_fixtures::psi::short_section(0x50, &body);
1560 assert_eq!(s.len(), PUSI_PAYLOAD_CAP);
1561 assert_round_trip(&[s]);
1562 }
1563
1564 #[test]
1565 fn round_trip_section_just_over_pusi_cap() {
1566 let body = vec![0xDD; PUSI_PAYLOAD_CAP - 3 + 1];
1568 let s = test_fixtures::psi::short_section(0x52, &body);
1569 assert_eq!(s.len(), PUSI_PAYLOAD_CAP + 1);
1570 assert_round_trip(&[s]);
1571 }
1572
1573 #[test]
1574 fn round_trip_section_spans_many_packets() {
1575 let body = vec![0xEE; 2000 - 3];
1577 let s = test_fixtures::psi::short_section(0x60, &body);
1578 assert_round_trip(&[s]);
1579 }
1580
1581 #[test]
1582 fn round_trip_section_at_max_size() {
1583 let body = vec![0x11; 4096 - 3];
1588 let s = test_fixtures::psi::short_section(0x80, &body);
1589 assert_eq!(s.len(), 4096);
1590 assert_round_trip(&[s]);
1591 }
1592
1593 #[test]
1594 fn round_trip_multiple_short_sections_in_one_batch() {
1595 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]);
1599 }
1600
1601 #[test]
1602 fn round_trip_section_ends_exactly_at_boundary() {
1603 let body1 = vec![0xA1; PUSI_PAYLOAD_CAP - 3];
1607 let s1 = test_fixtures::psi::short_section(0x50, &body1);
1608 assert_eq!(s1.len(), PUSI_PAYLOAD_CAP);
1609
1610 let s2 = test_fixtures::psi::long_section(0x52, 1, 0, 0, &[0xB1, 0xB2]);
1611 assert_round_trip(&[s1, s2]);
1612 }
1613
1614 #[test]
1615 fn continuation_packet_never_overshoots_next_section_start() {
1616 let body1 = vec![0xA5; 366 - 3];
1623 let s1 = test_fixtures::psi::short_section(0x50, &body1);
1624 assert_eq!(s1.len(), 366);
1625 let s2 = test_fixtures::psi::long_section(0x52, 1, 0, 0, &[0xB1, 0xB2, 0xB3]);
1626
1627 let mut packetiser = SectionPacketiser::new(Pid::from_const(0x0100));
1628 let packets = packetiser.packetise(&[s1.as_slice(), s2.as_slice()]);
1629
1630 for pkt_raw in &packets {
1631 let pkt = TsPacket::parse(pkt_raw).expect("parse generated packet");
1632 let payload = pkt.payload.expect("payload present");
1633 if pkt.header.pusi {
1634 let pointer = payload[0] as usize;
1635 assert!(
1639 pointer < PUSI_PAYLOAD_CAP,
1640 "pointer_field {pointer} leaves no room for a section to \
1641 start within this packet (H.222.0 §2.4.4)"
1642 );
1643 }
1644 }
1645
1646 assert_round_trip(&[s1, s2]);
1647 }
1648
1649 #[test]
1650 fn round_trip_mix_small_large_sections() {
1651 let s1 = test_fixtures::psi::long_section(0x10, 1, 0, 0, &[0xAA; 5]);
1654 let body2 = vec![0xBB; 200];
1655 let s2 = test_fixtures::psi::short_section(0x20, &body2);
1656 let s3 = test_fixtures::psi::long_section(0x30, 1, 0, 0, &[0xCC; 50]);
1657 let body4 = vec![0xDD; 800];
1658 let s4 = test_fixtures::psi::short_section(0x40, &body4);
1659 let s5 = test_fixtures::psi::long_section(0x50, 1, 0, 0, &[0xEE]); assert_round_trip(&[s1, s2, s3, s4, s5]);
1661 }
1662
1663 #[test]
1666 fn continuity_counter_increments_per_packet() {
1667 let body = vec![0xAA; 500];
1669 let section = test_fixtures::psi::short_section(0x42, &body);
1670 let mut p = SectionPacketiser::new(Pid::from_const(0x0100));
1671
1672 let packets = p.packetise(&[§ion]);
1673 assert!(packets.len() >= 3, "need multiple packets to test CC");
1674
1675 let mut last_cc: Option<ContinuityCounter> = None;
1676 for pkt_raw in &packets {
1677 let pkt = TsPacket::parse(pkt_raw).unwrap();
1678 let cc = pkt.header.continuity_counter;
1679 if let Some(last) = last_cc {
1680 assert_eq!(
1681 cc.forward_distance_from(last),
1682 1,
1683 "CC must increment per packet"
1684 );
1685 }
1686 last_cc = Some(cc);
1687 }
1688 }
1689
1690 #[test]
1691 fn continuity_counter_wraps_and_continues_across_calls() {
1692 let mut p = SectionPacketiser::with_continuity(Pid::from_const(0x0100), cc(14));
1693 let body = vec![0xBB; 500];
1695 let s = test_fixtures::psi::short_section(0x42, &body);
1696
1697 let pkts1 = p.packetise(&[&s]);
1699 assert!(pkts1.len() >= 3, "section must span ≥3 packets");
1700 let ccs1: Vec<u8> = pkts1
1701 .iter()
1702 .map(|b| {
1703 TsPacket::parse(b)
1704 .unwrap()
1705 .header
1706 .continuity_counter
1707 .value()
1708 })
1709 .collect();
1710 assert_eq!(ccs1[0], 14);
1711 assert_eq!(ccs1[1], 15);
1712 assert_eq!(ccs1[2], 0);
1713
1714 let previous = ContinuityCounter::try_new(ccs1.last().copied().unwrap_or(0))
1716 .expect("the last emitted counter is 4-bit");
1717 let pkts2 = p.packetise(&[&s]);
1718 let cc_first_pkt2 = TsPacket::parse(&pkts2[0])
1719 .unwrap()
1720 .header
1721 .continuity_counter;
1722 assert_eq!(cc_first_pkt2.forward_distance_from(previous), 1);
1723 }
1724
1725 #[test]
1728 fn pusi_set_when_section_starts() {
1729 let s = test_fixtures::psi::long_section(0x42, 1, 0, 0, &[0xAA; 10]);
1730 let mut p = SectionPacketiser::new(Pid::from_const(0x0100));
1731 let packets = p.packetise(&[&s]);
1732 assert!(!packets.is_empty());
1733 let pkt = TsPacket::parse(&packets[0]).unwrap();
1734 assert!(pkt.header.pusi, "first packet must have PUSI=1");
1735 }
1736
1737 #[test]
1738 fn pusi_not_set_on_mid_section_continuation() {
1739 let body = vec![0xAA; 500];
1740 let s = test_fixtures::psi::short_section(0x42, &body);
1741 let mut p = SectionPacketiser::new(Pid::from_const(0x0100));
1742 let packets = p.packetise(&[&s]);
1743 assert!(packets.len() >= 2);
1744 let pkt1 = TsPacket::parse(&packets[0]).unwrap();
1745 let pkt2 = TsPacket::parse(&packets[1]).unwrap();
1746 assert!(pkt1.header.pusi, "first packet must have PUSI=1");
1747 assert!(
1748 !pkt2.header.pusi,
1749 "second packet is continuation, must have PUSI=0"
1750 );
1751 }
1752
1753 #[test]
1754 fn pointer_field_equals_tail_length_before_new_section() {
1755 let body1 = vec![0xA1; 197]; let s1 = test_fixtures::psi::short_section(0x52, &body1);
1760 assert_eq!(s1.len(), 200);
1761 let s2 = test_fixtures::psi::long_section(0x54, 1, 0, 0, &[0xB1; 38]); assert_eq!(s2.len(), 50);
1763
1764 let mut p = SectionPacketiser::new(Pid::from_const(0x0100));
1765 let packets = p.packetise(&[&s1, &s2]);
1766
1767 let pkt_with_pointer = packets
1769 .iter()
1770 .map(|raw| TsPacket::parse(raw).unwrap())
1771 .find(|pkt| pkt.header.pusi && pkt.payload.is_some_and(|pl| pl.first() != Some(&0)))
1772 .expect("must have a PUSI packet with non-zero pointer");
1773
1774 let payload = pkt_with_pointer.payload.unwrap();
1775 let pointer = payload[0] as usize;
1776 assert!(pointer > 0, "pointer must be non-zero");
1777 let tail_start = s1.len() - pointer;
1779 assert_eq!(&payload[1..1 + pointer], &s1[tail_start..]);
1780 }
1781
1782 #[test]
1785 fn final_packet_unused_tail_is_stuffing() {
1786 let s = test_fixtures::psi::long_section(0x42, 1, 0, 0, &[0xAA; 5]); let mut p = SectionPacketiser::new(Pid::from_const(0x0100));
1788 let packets = p.packetise(&[&s]);
1789
1790 let pkt = TsPacket::parse(&packets[0]).unwrap();
1791 let payload = pkt.payload.unwrap();
1792 assert_eq!(payload[0], 0, "pointer_field should be 0");
1793
1794 let section_end = 1 + s.len(); assert!(
1796 section_end < payload.len(),
1797 "must have stuffing after section"
1798 );
1799 for &b in &payload[section_end..] {
1800 assert_eq!(b, STUFFING_BYTE, "all trailing bytes must be 0xFF");
1801 }
1802 }
1803
1804 #[test]
1805 fn reassembler_discards_stuffing() {
1806 let s1 = test_fixtures::psi::long_section(0x42, 1, 0, 0, &[0xAA; 10]);
1807 let s2 = test_fixtures::psi::long_section(0x46, 1, 0, 0, &[0xBB; 5]);
1808
1809 let mut p = SectionPacketiser::new(Pid::from_const(0x0100));
1810 let packets = p.packetise(&[&s1, &s2]);
1811
1812 let mut reasm = SectionReassembler::default();
1813 for pkt_raw in &packets {
1814 let pkt = TsPacket::parse(pkt_raw).unwrap();
1815 reasm.feed(pkt.payload.unwrap(), pkt.header.pusi);
1816 }
1817
1818 let got: Vec<_> = core::iter::from_fn(|| reasm.pop_section()).collect();
1819 assert_eq!(got.len(), 2);
1820 assert!(
1821 reasm.is_empty(),
1822 "stuffing tail must be discarded, not buffered"
1823 );
1824 }
1825
1826 #[test]
1829 fn empty_batch_produces_no_packets() {
1830 let mut p = SectionPacketiser::new(Pid::from_const(0x0100));
1831 let packets: Vec<[u8; TS_PACKET_SIZE]> = p.packetise(&[]);
1832 assert!(packets.is_empty());
1833 }
1834
1835 #[test]
1836 fn packetise_into_clears_out_first() {
1837 let s = test_fixtures::psi::long_section(0x42, 1, 0, 0, &[0xAA; 5]);
1838 let mut p = SectionPacketiser::new(Pid::from_const(0x0100));
1839
1840 let mut out = vec![[0u8; TS_PACKET_SIZE]; 99]; let n = p.packetise_into(&[&s], &mut out);
1842 assert_eq!(n, out.len(), "out must contain only the new packets");
1843 let mut reasm = SectionReassembler::default();
1845 for pkt_raw in &out {
1846 let pkt = TsPacket::parse(pkt_raw).unwrap();
1847 reasm.feed(pkt.payload.unwrap(), pkt.header.pusi);
1848 }
1849 let got = reasm.pop_section().unwrap();
1850 assert_eq!(got.as_ref(), s.as_slice());
1851 }
1852
1853 #[test]
1854 fn pid_is_correct() {
1855 let p = SectionPacketiser::new(Pid::from_const(0x1234));
1856 assert_eq!(p.pid(), Pid::from_const(0x1234));
1857 }
1858
1859 #[test]
1860 fn with_continuity_masks_to_4_bits() {
1861 let expected = ContinuityCounter::try_new(0x0E).expect("4-bit counter");
1862 let p = SectionPacketiser::with_continuity(Pid::from_const(0x0100), expected);
1863 assert_eq!(p.continuity_counter(), expected);
1864 }
1865
1866 #[test]
1867 fn has_payload_always_true_no_adaptation() {
1868 let s = test_fixtures::psi::long_section(0x42, 1, 0, 0, &[0xAA; 50]);
1869 let mut p = SectionPacketiser::new(Pid::from_const(0x0100));
1870 let packets = p.packetise(&[&s]);
1871 for pkt_raw in &packets {
1872 let pkt = TsPacket::parse(pkt_raw).unwrap();
1873 assert!(pkt.header.has_payload(), "every packet must carry payload");
1874 assert!(
1875 !pkt.header.has_adaptation(),
1876 "no adaptation field is emitted"
1877 );
1878 assert!(!pkt.header.tei, "TEI must be false");
1879 assert_eq!(
1880 pkt.header.scrambling,
1881 ScramblingControl::NotScrambled,
1882 "scrambling must be 0"
1883 );
1884 }
1885 }
1886}