1use alloc::collections::BTreeMap;
16use alloc::sync::Arc;
17use alloc::vec;
18use alloc::vec::Vec;
19use core::num::NonZeroUsize;
20use mpeg_ts::pid::Pid;
21
22use crate::descriptors::{AnyDescriptor, DescriptorLoop, DescriptorRegistry};
23use crate::sub_table::SubTableQualifier;
24use broadcast_core::Parse;
25use mpeg_ts::section::Section;
26
27mod bat;
28mod eit;
29mod nit;
30mod sdt;
31
32pub use bat::*;
33pub use eit::*;
34pub use nit::*;
35pub use sdt::*;
36
37#[derive(Debug)]
39#[non_exhaustive]
40pub struct CompleteTransportStream<'a> {
41 pub transport_stream_id: u16,
43 pub original_network_id: u16,
45 pub descriptors: ParsedDescriptorLoop<'a>,
47}
48
49impl<'a> CompleteTransportStream<'a> {
50 pub(crate) fn collect<I>(entries: I, registry: Option<&'a DescriptorRegistry>) -> Vec<Self>
51 where
52 I: IntoIterator<Item = (u16, u16, DescriptorLoop<'a>)>,
53 {
54 entries
55 .into_iter()
56 .map(
57 |(transport_stream_id, original_network_id, descriptors)| Self {
58 transport_stream_id,
59 original_network_id,
60 descriptors: ParsedDescriptorLoop::parse(descriptors, registry),
61 },
62 )
63 .collect()
64 }
65}
66
67pub type CollectResult<T> = core::result::Result<T, CollectError>;
69
70#[derive(Debug, thiserror::Error, Clone, PartialEq, Eq)]
76#[non_exhaustive]
77pub enum CollectError {
78 #[error("section parse failed: {0}")]
80 Section(#[from] crate::Error),
81
82 #[error(
84 "table_id {table_id:#04x} is a short-form section and cannot be multi-section collected"
85 )]
86 #[non_exhaustive]
87 ShortFormSection {
88 table_id: u8,
90 },
91
92 #[error(
94 "section_number {section_number} exceeds last_section_number {last_section_number} for table_id {table_id:#04x}"
95 )]
96 #[non_exhaustive]
97 SectionNumberOutOfRange {
98 table_id: u8,
100 section_number: u8,
102 last_section_number: u8,
104 },
105
106 #[error("conflicting bytes for table_id {table_id:#04x} section {section_number}")]
108 #[non_exhaustive]
109 ConflictingSection {
110 table_id: u8,
112 section_number: u8,
114 },
115
116 #[error(
118 "EIT schedule table_id {table_id:#04x} is outside advertised range {first_table_id:#04x}..={last_table_id:#04x}"
119 )]
120 #[non_exhaustive]
121 EitTableIdOutOfRange {
122 table_id: u8,
124 first_table_id: u8,
126 last_table_id: u8,
128 },
129}
130
131impl CollectError {
132 #[must_use]
134 pub fn conflicting_section(table_id: u8, section_number: u8) -> Self {
135 Self::ConflictingSection {
136 table_id,
137 section_number,
138 }
139 }
140
141 #[must_use]
143 pub fn eit_table_id_out_of_range(table_id: u8, first_table_id: u8, last_table_id: u8) -> Self {
144 Self::EitTableIdOutOfRange {
145 table_id,
146 first_table_id,
147 last_table_id,
148 }
149 }
150
151 #[must_use]
153 pub fn section_number_out_of_range(
154 table_id: u8,
155 section_number: u8,
156 last_section_number: u8,
157 ) -> Self {
158 Self::SectionNumberOutOfRange {
159 table_id,
160 section_number,
161 last_section_number,
162 }
163 }
164
165 #[must_use]
167 pub fn short_form_section(table_id: u8) -> Self {
168 Self::ShortFormSection { table_id }
169 }
170}
171
172impl From<mpeg_ts::Error> for CollectError {
173 fn from(e: mpeg_ts::Error) -> Self {
174 CollectError::Section(crate::Error::from(e))
175 }
176}
177
178#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord)]
183#[non_exhaustive]
184pub struct SectionSetKey {
185 pub pid: Option<Pid>,
187 pub table_id: u8,
189 pub extension_id: u16,
191 pub current_next_indicator: bool,
193 pub qualifier: Option<SubTableQualifier>,
197}
198
199#[derive(Debug, Clone, Copy, PartialEq, Eq)]
201#[non_exhaustive]
202pub struct SectionSetMeta {
203 pub key: SectionSetKey,
205 pub version_number: u8,
207 pub last_section_number: u8,
209}
210
211#[derive(Debug)]
212struct PartialSectionSet {
213 meta: SectionSetMeta,
214 slots: Vec<Option<Arc<[u8]>>>,
215 filled: usize,
216 emitted: bool,
217 last_touch: u64,
221}
222
223impl PartialSectionSet {
224 fn new(meta: SectionSetMeta) -> Self {
225 let len = meta.last_section_number as usize + 1;
226 Self {
227 meta,
228 slots: vec![None; len],
229 filled: 0,
230 emitted: false,
231 last_touch: 0,
232 }
233 }
234
235 fn reset(&mut self, meta: SectionSetMeta) {
236 let last_touch = self.last_touch;
237 *self = Self::new(meta);
238 self.last_touch = last_touch;
239 }
240
241 fn insert(&mut self, section_number: u8, bytes: &[u8]) -> CollectResult<bool> {
242 let index = section_number as usize;
243 if let Some(existing) = &self.slots[index] {
244 if existing.as_ref() == bytes {
245 return Ok(false);
246 }
247 return Err(CollectError::ConflictingSection {
248 table_id: self.meta.key.table_id,
249 section_number,
250 });
251 }
252
253 self.slots[index] = Some(Arc::from(bytes));
257 self.filled += 1;
258 self.emitted = false;
259 Ok(true)
260 }
261
262 fn complete(&self) -> bool {
263 self.filled == self.slots.len()
264 }
265
266 fn to_complete(&self) -> Option<CompleteSectionSet> {
267 if !self.complete() || self.emitted {
268 return None;
269 }
270
271 let sections = self
272 .slots
273 .iter()
274 .map(|slot| slot.as_ref().expect("complete set has no holes").clone())
275 .collect();
276 Some(CompleteSectionSet {
277 meta: self.meta,
278 sections,
279 })
280 }
281}
282
283#[derive(Debug)]
307pub struct SectionSetCollector {
308 partial: BTreeMap<SectionSetKey, PartialSectionSet>,
309 touch_order: BTreeMap<u64, SectionSetKey>,
311 tick: u64,
312 max_partial_keys: usize,
313 evicted_for_capacity: u64,
314}
315
316impl SectionSetCollector {
317 #[must_use]
321 pub fn new(max_partial_keys: NonZeroUsize) -> Self {
322 Self {
323 partial: BTreeMap::new(),
324 touch_order: BTreeMap::new(),
325 tick: 0,
326 max_partial_keys: max_partial_keys.get(),
327 evicted_for_capacity: 0,
328 }
329 }
330
331 #[must_use]
336 pub fn evicted_for_capacity(&self) -> u64 {
337 self.evicted_for_capacity
338 }
339
340 fn touch_or_evict(&mut self, key: SectionSetKey) -> bool {
345 self.tick = self.tick.wrapping_add(1).max(1);
346 if !self.partial.contains_key(&key) && self.partial.len() >= self.max_partial_keys {
347 let oldest = self.touch_order.keys().next().copied();
348 match oldest {
349 Some(oldest_tick) => {
350 if let Some(oldest_key) = self.touch_order.remove(&oldest_tick) {
351 self.partial.remove(&oldest_key);
352 self.evicted_for_capacity += 1;
353 }
354 }
355 None => return false,
356 }
357 }
358 true
359 }
360
361 pub fn push_section(
371 &mut self,
372 bytes: impl AsRef<[u8]>,
373 ) -> CollectResult<Option<CompleteSectionSet>> {
374 self.push_section_with_pid(None, bytes)
375 }
376
377 pub fn push_section_with_pid(
382 &mut self,
383 pid: Option<Pid>,
384 bytes: impl AsRef<[u8]>,
385 ) -> CollectResult<Option<CompleteSectionSet>> {
386 let raw = bytes.as_ref();
387 let section = Section::parse(raw)?;
388 if !section.section_syntax_indicator {
389 return Err(CollectError::ShortFormSection {
390 table_id: section.table_id,
391 });
392 }
393 if section.section_number > section.last_section_number {
394 return Err(CollectError::SectionNumberOutOfRange {
395 table_id: section.table_id,
396 section_number: section.section_number,
397 last_section_number: section.last_section_number,
398 });
399 }
400 mpeg_ts::section::validate_crc(raw)?;
401
402 let key = SectionSetKey {
403 pid,
404 table_id: section.table_id,
405 extension_id: section.extension_id,
406 current_next_indicator: section.current_next_indicator,
407 qualifier: SubTableQualifier::of(section.table_id, section.payload),
408 };
409 let meta = SectionSetMeta {
410 key,
411 version_number: section.version_number,
412 last_section_number: section.last_section_number,
413 };
414 if !self.touch_or_evict(key) {
415 return Ok(None);
416 }
417 let now = self.tick;
418
419 let partial = self
420 .partial
421 .entry(key)
422 .or_insert_with(|| PartialSectionSet::new(meta));
423
424 if partial.meta.version_number != meta.version_number
425 || partial.meta.last_section_number != meta.last_section_number
426 {
427 partial.reset(meta);
428 }
429
430 self.touch_order.remove(&partial.last_touch);
434 partial.last_touch = now;
435 self.touch_order.insert(now, key);
436
437 partial.insert(section.section_number, raw)?;
438 let complete = partial.to_complete();
439 if complete.is_some() {
440 partial.emitted = true;
441 }
442 Ok(complete)
443 }
444
445 pub fn clear(&mut self) {
447 self.partial.clear();
448 self.touch_order.clear();
449 }
450
451 #[must_use]
453 pub fn len(&self) -> usize {
454 self.partial.len()
455 }
456
457 #[must_use]
459 pub fn is_empty(&self) -> bool {
460 self.partial.is_empty()
461 }
462}
463
464#[derive(Debug, Clone)]
467pub struct CompleteSectionSet {
468 meta: SectionSetMeta,
469 sections: Vec<Arc<[u8]>>,
470}
471
472#[derive(Debug)]
480pub struct CompleteTable<T> {
481 meta: SectionSetMeta,
482 sections: Vec<T>,
483}
484
485impl<T> CompleteTable<T> {
486 #[must_use]
488 pub const fn meta(&self) -> SectionSetMeta {
489 self.meta
490 }
491
492 #[must_use]
494 pub fn sections(&self) -> &[T] {
495 &self.sections
496 }
497
498 #[must_use]
500 pub fn into_sections(self) -> Vec<T> {
501 self.sections
502 }
503}
504
505impl CompleteSectionSet {
506 #[must_use]
508 pub const fn meta(&self) -> SectionSetMeta {
509 self.meta
510 }
511
512 #[must_use]
514 pub fn section_bytes(&self) -> impl ExactSizeIterator<Item = &[u8]> {
515 self.sections.iter().map(AsRef::as_ref)
516 }
517
518 pub fn parse_sections<'a, T>(&'a self) -> crate::Result<Vec<T>>
523 where
524 T: Parse<'a, Error = crate::Error>,
525 {
526 self.section_bytes().map(T::parse).collect()
527 }
528
529 pub fn table<'a, T>(&'a self) -> crate::Result<CompleteTable<T>>
534 where
535 T: Parse<'a, Error = crate::Error>,
536 {
537 Ok(CompleteTable {
538 meta: self.meta,
539 sections: self.parse_sections()?,
540 })
541 }
542
543 pub fn nit(&self) -> crate::Result<CompleteNit<'_>> {
545 CompleteNit::parse(self, None)
546 }
547
548 pub fn nit_with_registry<'a>(
550 &'a self,
551 registry: &'a DescriptorRegistry,
552 ) -> crate::Result<CompleteNit<'a>> {
553 CompleteNit::parse(self, Some(registry))
554 }
555
556 pub fn bat(&self) -> crate::Result<CompleteBat<'_>> {
558 CompleteBat::parse(self, None)
559 }
560
561 pub fn bat_with_registry<'a>(
563 &'a self,
564 registry: &'a DescriptorRegistry,
565 ) -> crate::Result<CompleteBat<'a>> {
566 CompleteBat::parse(self, Some(registry))
567 }
568
569 pub fn sdt(&self) -> crate::Result<CompleteSdt<'_>> {
571 CompleteSdt::parse(self, None)
572 }
573
574 pub fn sdt_with_registry<'a>(
576 &'a self,
577 registry: &'a DescriptorRegistry,
578 ) -> crate::Result<CompleteSdt<'a>> {
579 CompleteSdt::parse(self, Some(registry))
580 }
581
582 pub fn eit(&self) -> crate::Result<CompleteEit<'_>> {
584 CompleteEit::parse(self, None)
585 }
586
587 pub fn eit_with_registry<'a>(
589 &'a self,
590 registry: &'a DescriptorRegistry,
591 ) -> crate::Result<CompleteEit<'a>> {
592 CompleteEit::parse(self, Some(registry))
593 }
594}
595
596#[derive(Debug)]
606pub struct ParsedDescriptorLoop<'a> {
607 raw: Vec<DescriptorLoop<'a>>,
608 descriptors: Vec<crate::Result<AnyDescriptor<'a>>>,
609}
610
611impl<'a> ParsedDescriptorLoop<'a> {
612 pub(crate) fn parse(raw: DescriptorLoop<'a>, registry: Option<&'a DescriptorRegistry>) -> Self {
613 Self::parse_all(core::iter::once(raw), registry)
614 }
615
616 pub(crate) fn parse_all(
619 raws: impl IntoIterator<Item = DescriptorLoop<'a>>,
620 registry: Option<&'a DescriptorRegistry>,
621 ) -> Self {
622 let raw: Vec<DescriptorLoop<'a>> = raws.into_iter().collect();
623 let mut descriptors = Vec::new();
624 for loop_ in &raw {
625 match registry {
626 Some(registry) => descriptors.extend(registry.parse_loop(loop_.raw())),
627 None => descriptors.extend(loop_.iter()),
628 }
629 }
630 Self { raw, descriptors }
631 }
632
633 #[must_use]
639 pub fn raw(&self) -> &[DescriptorLoop<'a>] {
640 &self.raw
641 }
642
643 pub fn descriptors(&self) -> &[crate::Result<AnyDescriptor<'a>>] {
646 &self.descriptors
647 }
648}
649
650#[cfg(test)]
651mod tests {
652 const TEST_MAX_PARTIAL_KEYS: core::num::NonZeroUsize =
653 core::num::NonZeroUsize::MIN.saturating_add(255);
654
655 use super::*;
656
657 const TEST_TABLE_ID: u8 = 0x42;
658
659 fn min_section(extension_id: u16) -> Vec<u8> {
660 let section_length: u16 = 9; let mut buf = vec![0u8; 12];
662 buf[0] = TEST_TABLE_ID;
663 buf[1] = 0xB0 | ((section_length >> 8) as u8 & 0x0F);
664 buf[2] = (section_length & 0xFF) as u8;
665 buf[3..5].copy_from_slice(&extension_id.to_be_bytes());
666 buf[5] = 0xC1;
667 buf[6] = 0;
668 buf[7] = 0;
669 let crc = broadcast_common::crc32_mpeg2::compute(&buf[..8]);
670 buf[8..12].copy_from_slice(&crc.to_be_bytes());
671 buf
672 }
673
674 #[test]
675 fn collect_single_section_is_complete() {
676 let mut c = SectionSetCollector::new(TEST_MAX_PARTIAL_KEYS);
677 let sec = min_section(0);
678 let result = c.push_section(&sec).unwrap();
679 assert!(result.is_some());
680 assert_eq!(c.len(), 1);
681 }
682
683 #[test]
690 fn new_key_beyond_cap_evicts_least_recently_touched_completed_entry() {
691 let mut c = SectionSetCollector::new(NonZeroUsize::MIN.saturating_add(2));
692
693 for eid in 0..3u16 {
695 let sec = min_section(eid);
696 let result = c.push_section(&sec).unwrap();
697 assert!(
698 result.is_some(),
699 "single-section set for eid {eid} completes"
700 );
701 }
702 assert_eq!(c.len(), 3);
703 assert_eq!(c.evicted_for_capacity(), 0);
704
705 let sec4 = min_section(3);
708 let result = c.push_section(&sec4).unwrap();
709 assert!(
710 result.is_some(),
711 "new key beyond cap must evict, not be skipped"
712 );
713 assert_eq!(c.len(), 3, "cap stays honored, not just grown");
714 assert_eq!(c.evicted_for_capacity(), 1);
715
716 let sec0_again = min_section(0);
719 let result = c.push_section(&sec0_again).unwrap();
720 assert!(result.is_some(), "evicted key re-admits like a fresh one");
721
722 c.clear();
724 assert!(c.is_empty());
725 let result = c.push_section(&sec4).unwrap();
726 assert!(result.is_some());
727 assert_eq!(c.len(), 1);
728 }
729
730 #[test]
731 fn partial_keys_cap_does_not_skip_existing_key() {
732 let mut c = SectionSetCollector::new(NonZeroUsize::MIN);
733
734 let sec0 = {
736 let mut buf = min_section(0xAB);
737 buf[7] = 1;
739 let crc = broadcast_common::crc32_mpeg2::compute(&buf[..8]);
741 buf[8..12].copy_from_slice(&crc.to_be_bytes());
742 buf
743 };
744 let result = c.push_section(&sec0).unwrap();
745 assert!(result.is_none(), "incomplete section set yields None");
746
747 let mut sec1 = min_section(0xAB);
750 sec1[6] = 1; sec1[7] = 1; let crc = broadcast_common::crc32_mpeg2::compute(&sec1[..8]);
753 sec1[8..12].copy_from_slice(&crc.to_be_bytes());
754
755 let result = c.push_section(&sec1).unwrap();
756 assert!(
757 result.is_some(),
758 "existing key must NOT be skipped when cap full"
759 );
760 assert_eq!(c.len(), 1);
761 }
762
763 fn long_section(table_id: u8, ext: u16, payload: &[u8]) -> Vec<u8> {
764 let section_length = (5 + payload.len() + 4) as u16;
765 let mut buf = vec![0u8; 3 + section_length as usize];
766 buf[0] = table_id;
767 buf[1] = 0xB0 | ((section_length >> 8) as u8 & 0x0F);
768 buf[2] = (section_length & 0xFF) as u8;
769 buf[3..5].copy_from_slice(&ext.to_be_bytes());
770 buf[5] = 0xC1;
771 buf[8..8 + payload.len()].copy_from_slice(payload);
772 let crc_off = buf.len() - 4;
773 let crc = broadcast_common::crc32_mpeg2::compute(&buf[..crc_off]);
774 buf[crc_off..].copy_from_slice(&crc.to_be_bytes());
775 buf
776 }
777
778 fn complete_set(section: &[u8]) -> CompleteSectionSet {
779 SectionSetCollector::new(TEST_MAX_PARTIAL_KEYS)
780 .push_section(section)
781 .unwrap()
782 .unwrap()
783 }
784
785 const LCN_DESCRIPTOR: [u8; 6] = [0x83, 4, 0x00, 0x01, 0xFC, 0x05];
786
787 fn only_descriptor<'a, 'b>(loop_: &'b ParsedDescriptorLoop<'a>) -> &'b AnyDescriptor<'a> {
788 assert_eq!(loop_.descriptors().len(), 1);
789 loop_.descriptors()[0].as_ref().unwrap()
790 }
791
792 fn lcn_registry() -> DescriptorRegistry {
793 let mut registry = DescriptorRegistry::new();
794 registry.with_logical_channel();
795 registry
796 }
797
798 #[test]
799 fn bat_with_registry_types_the_opted_in_private_descriptor() {
800 let mut payload = vec![0xF0, LCN_DESCRIPTOR.len() as u8];
801 payload.extend_from_slice(&LCN_DESCRIPTOR);
802 payload.extend_from_slice(&[0xF0, 0x00]);
803 let set = complete_set(&long_section(0x4A, 0x1234, &payload));
804 let registry = lcn_registry();
805 let with = set.bat_with_registry(®istry).unwrap();
806 assert_eq!(with.bouquet_id, 0x1234);
807 assert!(matches!(
808 only_descriptor(&with.bouquet_descriptors),
809 AnyDescriptor::LogicalChannel(_)
810 ));
811 let plain = set.bat().unwrap();
812 assert!(matches!(
813 only_descriptor(&plain.bouquet_descriptors),
814 AnyDescriptor::Unknown { tag: 0x83, .. }
815 ));
816 }
817
818 #[test]
819 fn sdt_with_registry_types_the_opted_in_private_descriptor() {
820 let mut payload = vec![
821 0,
822 1,
823 0xFF,
824 0x00,
825 0x07,
826 0xFC,
827 0x80,
828 LCN_DESCRIPTOR.len() as u8,
829 ];
830 payload.extend_from_slice(&LCN_DESCRIPTOR);
831 let set = complete_set(&long_section(0x42, 7, &payload));
832 let registry = lcn_registry();
833 let with = set.sdt_with_registry(®istry).unwrap();
834 assert_eq!(with.original_network_id, 1);
835 assert_eq!(with.services.len(), 1);
836 assert_eq!(with.services[0].service_id, 7);
837 assert!(matches!(
838 only_descriptor(&with.services[0].descriptors),
839 AnyDescriptor::LogicalChannel(_)
840 ));
841 let plain = set.sdt().unwrap();
842 assert!(matches!(
843 only_descriptor(&plain.services[0].descriptors),
844 AnyDescriptor::Unknown { tag: 0x83, .. }
845 ));
846 }
847
848 #[test]
849 fn eit_with_registry_types_the_opted_in_private_descriptor() {
850 let mut payload = vec![
851 0,
852 1,
853 0,
854 2,
855 0,
856 0x4E,
857 0x00,
858 0x09,
859 0xE4,
860 0x09,
861 0x12,
862 0x34,
863 0x56,
864 0x00,
865 0x01,
866 0x00,
867 0x80,
868 LCN_DESCRIPTOR.len() as u8,
869 ];
870 payload.extend_from_slice(&LCN_DESCRIPTOR);
871 let set = complete_set(&long_section(0x4E, 100, &payload));
872 let registry = lcn_registry();
873 let with = set.eit_with_registry(®istry).unwrap();
874 assert_eq!(with.service_id, 100);
875 assert_eq!(with.events.len(), 1);
876 assert_eq!(with.events[0].event_id, 9);
877 assert!(matches!(
878 only_descriptor(&with.events[0].descriptors),
879 AnyDescriptor::LogicalChannel(_)
880 ));
881 let plain = set.eit().unwrap();
882 assert!(matches!(
883 only_descriptor(&plain.events[0].descriptors),
884 AnyDescriptor::Unknown { tag: 0x83, .. }
885 ));
886 }
887
888 #[test]
889 fn into_sections_returns_every_parsed_section() {
890 let set = complete_set(&long_section(0x4A, 9, &[0xF0, 0, 0xF0, 0]));
891 let table = set.table::<crate::tables::bat::BatSection>().unwrap();
892 assert_eq!(table.sections().len(), 1);
893 let sections = table.into_sections();
894 assert_eq!(sections.len(), 1);
895 assert_eq!(sections[0].bouquet_id, 9);
896 }
897}