1use alloc::boxed::Box;
69use alloc::collections::BTreeMap;
70
71use crate::descriptors::any::AnyDescriptor;
72use crate::descriptors::private_data_specifier::PDS_NORDIG;
73
74broadcast_common::declare_object_trait! {
75 pub trait DescriptorObject, "descriptor"
83}
84
85pub(crate) type CustomParse =
92 Box<dyn for<'a> Fn(&'a [u8]) -> crate::Result<Box<dyn DescriptorObject>> + Send + Sync>;
93
94#[derive(Default)]
124pub struct DescriptorRegistry {
125 custom: BTreeMap<(Option<u32>, u8), CustomParse>,
126 logical_channel: bool,
127 logical_channel_pds: alloc::collections::BTreeSet<u32>,
128}
129
130impl DescriptorRegistry {
131 #[must_use]
133 pub fn new() -> Self {
134 Self::default()
135 }
136
137 pub fn register<T>(&mut self) -> &mut Self
158 where
159 T: for<'a> crate::traits::DescriptorDef<'a> + DescriptorObject + 'static,
160 {
161 let tag = <T as crate::traits::DescriptorDef<'static>>::TAG;
162 self.custom.insert(
163 (None, tag),
164 Box::new(|b| {
165 Ok(Box::new(<T as broadcast_core::Parse>::parse(b)?) as Box<dyn DescriptorObject>)
166 }),
167 );
168 self
169 }
170
171 pub fn register_for_pds<T>(&mut self, pds: u32) -> &mut Self
183 where
184 T: for<'a> crate::traits::DescriptorDef<'a> + DescriptorObject + 'static,
185 {
186 let tag = <T as crate::traits::DescriptorDef<'static>>::TAG;
187 self.custom.insert(
188 (Some(pds), tag),
189 Box::new(|b| {
190 Ok(Box::new(<T as broadcast_core::Parse>::parse(b)?) as Box<dyn DescriptorObject>)
191 }),
192 );
193 self
194 }
195
196 pub fn with_logical_channel(&mut self) -> &mut Self {
202 self.logical_channel = true;
203 self
204 }
205
206 pub fn with_logical_channel_for_pds(&mut self, pds: u32) -> &mut Self {
218 self.logical_channel_pds.insert(pds);
219 self
220 }
221
222 pub fn with_nordig_lcn(&mut self) -> &mut Self {
226 self.register_for_pds::<crate::descriptors::nordig::NordigLogicalChannelV1>(PDS_NORDIG);
227 self.register_for_pds::<crate::descriptors::nordig::NordigLogicalChannelV2>(PDS_NORDIG);
228 self
229 }
230
231 pub fn with_avs3_audio(&mut self) -> &mut Self {
237 self.register_for_pds::<crate::descriptors::avs3_audio::Avs3AudioDescriptor>(
238 crate::descriptors::PDS_AVSA,
239 );
240 self
241 }
242
243 pub fn with_avs3_video(&mut self) -> &mut Self {
250 self.register_for_pds::<crate::descriptors::avs3_video::Avs3VideoDescriptor>(
251 crate::descriptors::PDS_AVSV,
252 );
253 self
254 }
255
256 pub fn with_avs2_video(&mut self) -> &mut Self {
261 self.register_for_pds::<crate::descriptors::avs2_video::Avs2VideoDescriptor>(
262 crate::descriptors::PDS_AVSV,
263 );
264 self
265 }
266
267 pub fn with_avs2_audio(&mut self) -> &mut Self {
271 self.register_for_pds::<crate::descriptors::avs2_audio::Avs2AudioDescriptor>(
272 crate::descriptors::PDS_AVSA,
273 );
274 self
275 }
276
277 pub fn with_tuwa_avs3_video(&mut self) -> &mut Self {
281 self.register::<crate::descriptors::tuwa_avs3_video::TuwaAvs3VideoDescriptor>()
282 }
283
284 pub fn with_dovi_video_stream(&mut self) -> &mut Self {
290 self.register_for_pds::<crate::descriptors::dovi_video_stream::DoviVideoStreamDescriptor>(
291 crate::descriptors::dovi_video_stream::REGISTRATION_SCOPE,
292 );
293 self
294 }
295
296 pub fn with_china_caption_service(&mut self) -> &mut Self {
302 self.register::<crate::descriptors::china_caption_service::ChinaCaptionServiceDescriptor>()
303 }
304
305 pub fn with_atsc_caption_service(&mut self) -> &mut Self {
310 self.register::<crate::descriptors::atsc_caption_service::AtscCaptionServiceDescriptor>()
311 }
312
313 #[must_use]
323 pub fn parse_loop<'r, 'a>(&'r self, bytes: &'a [u8]) -> RegistryIter<'r, 'a> {
324 RegistryIter {
325 registry: self,
326 bytes,
327 pos: 0,
328 fused: false,
329 current_pds: None,
330 }
331 }
332
333 #[must_use]
347 pub fn parse_loop_in_scope<'r, 'a>(
348 &'r self,
349 bytes: &'a [u8],
350 inherited: Option<u32>,
351 ) -> RegistryIter<'r, 'a> {
352 RegistryIter {
353 registry: self,
354 bytes,
355 pos: 0,
356 fused: false,
357 current_pds: inherited,
358 }
359 }
360}
361
362pub struct RegistryIter<'r, 'a> {
370 registry: &'r DescriptorRegistry,
371 bytes: &'a [u8],
372 pos: usize,
373 fused: bool,
374 current_pds: Option<u32>,
375}
376
377pub(crate) fn dispatch_entry<'a>(
383 registry: &DescriptorRegistry,
384 current_pds: Option<u32>,
385 tag: u8,
386 full: &'a [u8],
387) -> crate::Result<AnyDescriptor<'a>> {
388 if let Some(pds) = current_pds
389 && let Some(parse_fn) = registry.custom.get(&(Some(pds), tag))
390 {
391 return parse_fn(full).map(|value| AnyDescriptor::Other { tag, value });
392 }
393 if let Some(parse_fn) = registry.custom.get(&(None, tag)) {
394 return parse_fn(full).map(|value| AnyDescriptor::Other { tag, value });
395 }
396 if let Some(pds) = current_pds
397 && tag == crate::descriptors::logical_channel::TAG
398 && registry.logical_channel_pds.contains(&pds)
399 {
400 use broadcast_core::Parse;
401 return crate::descriptors::logical_channel::LogicalChannelDescriptor::parse(full)
402 .map(AnyDescriptor::LogicalChannel);
403 }
404 if registry.logical_channel && tag == crate::descriptors::logical_channel::TAG {
405 use broadcast_core::Parse;
406 return crate::descriptors::logical_channel::LogicalChannelDescriptor::parse(full)
407 .map(AnyDescriptor::LogicalChannel);
408 }
409 if let Some(res) = AnyDescriptor::dispatch(tag, full) {
410 return res;
411 }
412 Ok(AnyDescriptor::Unknown {
413 tag,
414 body: &full[2..],
415 })
416}
417
418fn update_pds(current: &mut Option<u32>, tag: u8, full: &[u8]) {
419 if tag == crate::descriptors::registration::TAG {
425 use broadcast_core::Parse;
426 if let Ok(reg) = crate::descriptors::registration::RegistrationDescriptor::parse(full) {
427 let id = u32::from_be_bytes(reg.format_identifier);
428 if id == crate::descriptors::PDS_AVSA || id == crate::descriptors::PDS_AVSV {
429 *current = Some(id);
430 }
431 if id == crate::descriptors::dovi_video_stream::REGISTRATION_SCOPE {
432 *current = Some(id);
433 }
434 }
435 }
436 if tag == crate::descriptors::private_data_specifier::TAG {
437 use broadcast_core::Parse;
438 if let Ok(pds) =
439 crate::descriptors::private_data_specifier::PrivateDataSpecifierDescriptor::parse(full)
440 {
441 *current = Some(pds.private_data_specifier);
442 }
443 }
444}
445
446impl RegistryIter<'_, '_> {
447 #[must_use]
453 pub fn avs_scope(&self) -> Option<u32> {
454 self.current_pds
455 .filter(|p| *p == crate::descriptors::PDS_AVSA || *p == crate::descriptors::PDS_AVSV)
456 }
457}
458
459impl<'a> Iterator for RegistryIter<'_, 'a> {
460 type Item = crate::Result<AnyDescriptor<'a>>;
461
462 fn next(&mut self) -> Option<Self::Item> {
463 let (tag, full) = match crate::descriptors::any::next_loop_entry(
464 self.bytes,
465 &mut self.pos,
466 &mut self.fused,
467 )? {
468 Ok(v) => v,
469 Err(e) => return Some(Err(e)),
470 };
471
472 update_pds(&mut self.current_pds, tag, full);
473
474 Some(dispatch_entry(self.registry, self.current_pds, tag, full))
475 }
476}
477
478impl core::iter::FusedIterator for RegistryIter<'_, '_> {}
479
480#[derive(Debug)]
492#[cfg_attr(feature = "serde", derive(serde::Serialize))]
493#[cfg_attr(feature = "serde", serde(rename_all = "camelCase"))]
494#[non_exhaustive]
495pub enum ExtIterItem<'a> {
496 Descriptor(AnyDescriptor<'a>),
498 CustomExtension {
500 tag_extension: u8,
502 #[cfg_attr(
505 feature = "serde",
506 serde(serialize_with = "super::extension::registry::serialize_erased")
507 )]
508 value: Box<dyn super::extension::registry::ExtensionObject>,
509 },
510}
511
512pub struct ExtRegistryIter<'r, 'a> {
522 desc_reg: &'r DescriptorRegistry,
523 ext_reg: &'r super::extension::registry::ExtensionRegistry,
524 bytes: &'a [u8],
525 pos: usize,
526 fused: bool,
527 current_pds: Option<u32>,
528}
529
530impl<'r, 'a> ExtRegistryIter<'r, 'a> {
531 pub(crate) fn new(
532 desc_reg: &'r DescriptorRegistry,
533 ext_reg: &'r super::extension::registry::ExtensionRegistry,
534 bytes: &'a [u8],
535 inherited: Option<u32>,
536 ) -> Self {
537 Self {
538 desc_reg,
539 ext_reg,
540 bytes,
541 pos: 0,
542 fused: false,
543 current_pds: inherited,
544 }
545 }
546
547 #[must_use]
550 pub fn avs_scope(&self) -> Option<u32> {
551 self.current_pds
552 .filter(|p| *p == crate::descriptors::PDS_AVSA || *p == crate::descriptors::PDS_AVSV)
553 }
554}
555
556const DESCRIPTOR_HEADER_LEN: usize = 2;
558const EXTENSION_TAG_OFFSET: usize = DESCRIPTOR_HEADER_LEN;
560const EXTENSION_BODY_OFFSET: usize = DESCRIPTOR_HEADER_LEN + 1;
562
563impl<'a> Iterator for ExtRegistryIter<'_, 'a> {
564 type Item = crate::Result<ExtIterItem<'a>>;
565
566 fn next(&mut self) -> Option<Self::Item> {
567 let (tag, full) = match crate::descriptors::any::next_loop_entry(
568 self.bytes,
569 &mut self.pos,
570 &mut self.fused,
571 )? {
572 Ok(v) => v,
573 Err(e) => return Some(Err(e)),
574 };
575
576 update_pds(&mut self.current_pds, tag, full);
577
578 let len = full.len() - DESCRIPTOR_HEADER_LEN;
579 if tag == crate::descriptors::extension::TAG && len >= 1 {
580 let tag_extension = full[EXTENSION_TAG_OFFSET];
581 if self.ext_reg.has_custom(tag_extension) {
582 return Some(
583 match self
584 .ext_reg
585 .parse_body(tag_extension, &full[EXTENSION_BODY_OFFSET..])
586 {
587 Ok(super::extension::registry::RegisteredExtension::Custom {
588 tag_extension,
589 value,
590 }) => Ok(ExtIterItem::CustomExtension {
591 tag_extension,
592 value,
593 }),
594 Ok(super::extension::registry::RegisteredExtension::Builtin(d)) => {
595 Ok(ExtIterItem::Descriptor(AnyDescriptor::Extension(d)))
596 }
597 Err(e) => Err(e),
598 },
599 );
600 }
601 }
602
603 Some(
604 dispatch_entry(self.desc_reg, self.current_pds, tag, full).map(ExtIterItem::Descriptor),
605 )
606 }
607}
608
609impl core::iter::FusedIterator for ExtRegistryIter<'_, '_> {}
610
611#[cfg(test)]
612mod tests {
613 use super::*;
614 use crate::descriptors::private_data_specifier;
615 use crate::descriptors::private_data_specifier::{PDS_EACEM, PDS_NORDIG};
616 use crate::traits::DescriptorDef;
617 use alloc::{vec, vec::Vec};
618
619 #[test]
620 fn pds_constants_match_the_register() {
621 assert_eq!(
624 private_data_specifier::private_data_specifier_name(PDS_EACEM),
625 Some("EACEM/EICTA")
626 );
627 assert_eq!(
628 private_data_specifier::private_data_specifier_name(PDS_NORDIG),
629 Some("NorDig")
630 );
631 }
632
633 #[derive(Debug, PartialEq, Eq)]
634 #[cfg_attr(feature = "serde", derive(serde::Serialize))]
635 struct PdsEacem {
636 v: u8,
637 }
638
639 impl<'a> broadcast_core::Parse<'a> for PdsEacem {
640 type Error = crate::error::Error;
641 fn parse(bytes: &'a [u8]) -> crate::Result<Self> {
642 if bytes.len() < 3 {
643 return Err(crate::error::Error::BufferTooShort(
644 broadcast_core::error::BufferTooShort::new(3, bytes.len(), "PdsEacem"),
645 ));
646 }
647 Ok(Self { v: bytes[2] })
648 }
649 }
650
651 impl DescriptorDef<'_> for PdsEacem {
652 const TAG: u8 = 0x83;
653 const NAME: &'static str = "PDS_EACEM";
654 }
655
656 #[derive(Debug, PartialEq, Eq)]
657 #[cfg_attr(feature = "serde", derive(serde::Serialize))]
658 struct PdsNordig {
659 w: u8,
660 }
661
662 impl<'a> broadcast_core::Parse<'a> for PdsNordig {
663 type Error = crate::error::Error;
664 fn parse(bytes: &'a [u8]) -> crate::Result<Self> {
665 if bytes.len() < 3 {
666 return Err(crate::error::Error::BufferTooShort(
667 broadcast_core::error::BufferTooShort::new(3, bytes.len(), "PdsNordig"),
668 ));
669 }
670 Ok(Self { w: bytes[2] })
671 }
672 }
673
674 impl DescriptorDef<'_> for PdsNordig {
675 const TAG: u8 = 0x83;
676 const NAME: &'static str = "PDS_NORDIG";
677 }
678
679 #[derive(Debug, PartialEq, Eq)]
680 #[cfg_attr(feature = "serde", derive(serde::Serialize))]
681 struct PdsAgnostic {
682 z: u8,
683 }
684
685 impl<'a> broadcast_core::Parse<'a> for PdsAgnostic {
686 type Error = crate::error::Error;
687 fn parse(bytes: &'a [u8]) -> crate::Result<Self> {
688 if bytes.len() < 3 {
689 return Err(crate::error::Error::BufferTooShort(
690 broadcast_core::error::BufferTooShort::new(3, bytes.len(), "PdsAgnostic"),
691 ));
692 }
693 Ok(Self { z: bytes[2] })
694 }
695 }
696
697 impl DescriptorDef<'_> for PdsAgnostic {
698 const TAG: u8 = 0x84;
699 const NAME: &'static str = "PDS_AGNOSTIC";
700 }
701
702 fn pds_descriptor(pds: u32) -> Vec<u8> {
703 let mut v = vec![private_data_specifier::TAG, 4];
704 v.extend_from_slice(&pds.to_be_bytes());
705 v
706 }
707
708 #[test]
709 fn pds_scoped_same_tag_resolves_by_pds() {
710 let mut reg = DescriptorRegistry::new();
711 reg.register_for_pds::<PdsEacem>(PDS_EACEM);
712 reg.register_for_pds::<PdsNordig>(PDS_NORDIG);
713
714 let mut bytes = Vec::new();
715 bytes.extend_from_slice(&pds_descriptor(PDS_EACEM));
716 bytes.extend_from_slice(&[0x83, 0x01, 0xAA]);
717
718 let items: Vec<_> = reg.parse_loop(&bytes).collect::<Result<_, _>>().unwrap();
719 assert_eq!(items.len(), 2);
720 assert!(matches!(items[0], AnyDescriptor::PrivateDataSpecifier(_)));
721 match &items[1] {
722 AnyDescriptor::Other { tag, value } => {
723 assert_eq!(*tag, 0x83);
724 let c = value.downcast_ref::<PdsEacem>().unwrap();
725 assert_eq!(c.v, 0xAA);
726 }
727 other => panic!("expected Other (PdsEacem), got {other:?}"),
728 }
729
730 let mut bytes2 = Vec::new();
731 bytes2.extend_from_slice(&pds_descriptor(PDS_NORDIG));
732 bytes2.extend_from_slice(&[0x83, 0x01, 0xBB]);
733
734 let items2: Vec<_> = reg.parse_loop(&bytes2).collect::<Result<_, _>>().unwrap();
735 match &items2[1] {
736 AnyDescriptor::Other { tag, value } => {
737 assert_eq!(*tag, 0x83);
738 let c = value.downcast_ref::<PdsNordig>().unwrap();
739 assert_eq!(c.w, 0xBB);
740 }
741 other => panic!("expected Other (PdsNordig), got {other:?}"),
742 }
743 }
744
745 #[test]
746 fn pds_scoped_does_not_match_wrong_pds() {
747 let mut reg = DescriptorRegistry::new();
748 reg.register_for_pds::<PdsEacem>(PDS_EACEM);
749
750 let mut bytes = Vec::new();
751 bytes.extend_from_slice(&pds_descriptor(PDS_NORDIG));
752 bytes.extend_from_slice(&[0x83, 0x01, 0xCC]);
753
754 let items: Vec<_> = reg.parse_loop(&bytes).collect::<Result<_, _>>().unwrap();
755 assert_eq!(items.len(), 2);
756 assert!(matches!(items[0], AnyDescriptor::PrivateDataSpecifier(_)));
757 match &items[1] {
758 AnyDescriptor::Unknown { tag, .. } => assert_eq!(*tag, 0x83),
759 other => panic!("expected Unknown (wrong PDS), got {other:?}"),
760 }
761 }
762
763 #[test]
766 fn avs2_and_tuwa_descriptors_are_scoped() {
767 use crate::descriptors::avs2_audio::Avs2AudioDescriptor;
768 use crate::descriptors::avs2_video::Avs2VideoDescriptor;
769 use crate::descriptors::private_data_specifier::{PDS_AVSA, PDS_AVSV};
770 use crate::descriptors::tuwa_avs3_video::TuwaAvs3VideoDescriptor;
771 let mut reg = DescriptorRegistry::new();
772 reg.with_avs2_video()
773 .with_avs2_audio()
774 .with_tuwa_avs3_video();
775
776 let v = [0x40, 5, 0x20, 0x42, 0x00, 0xA9, 0x5F];
777 let items: Vec<_> = reg.parse_loop(&v).collect::<Result<_, _>>().unwrap();
779 assert!(matches!(items[0], AnyDescriptor::NetworkName(_)));
780 let mut b = vec![0x05, 4, b'A', b'V', b'S', b'V'];
782 b.extend_from_slice(&v);
783 let items: Vec<_> = reg.parse_loop(&b).collect::<Result<_, _>>().unwrap();
784 match &items[1] {
785 AnyDescriptor::Other { tag: 0x40, value } => {
786 assert!(value.downcast_ref::<Avs2VideoDescriptor>().is_some());
787 }
788 other => panic!("expected Avs2Video, got {other:?}"),
789 }
790 let mut b = pds_descriptor(PDS_AVSV);
792 b.extend_from_slice(&v);
793 let items: Vec<_> = reg.parse_loop(&b).collect::<Result<_, _>>().unwrap();
794 assert!(matches!(items[1], AnyDescriptor::Other { tag: 0x40, .. }));
795
796 let a = [0xD3, 2, 6, 0x20];
797 let mut b = vec![0x05, 4, b'A', b'V', b'S', b'A'];
798 b.extend_from_slice(&a);
799 let items: Vec<_> = reg.parse_loop(&b).collect::<Result<_, _>>().unwrap();
800 match &items[1] {
801 AnyDescriptor::Other { tag: 0xD3, value } => {
802 assert!(value.downcast_ref::<Avs2AudioDescriptor>().is_some());
803 }
804 other => panic!("expected Avs2Audio, got {other:?}"),
805 }
806 let mut b = pds_descriptor(PDS_AVSA);
807 b.extend_from_slice(&a);
808 assert!(matches!(
809 reg.parse_loop(&b).collect::<Result<Vec<_>, _>>().unwrap()[1],
810 AnyDescriptor::Other { tag: 0xD3, .. }
811 ));
812 let items: Vec<_> = reg.parse_loop(&a).collect::<Result<_, _>>().unwrap();
814 assert!(matches!(items[0], AnyDescriptor::Unknown { tag: 0xD3, .. }));
815
816 let t = [62, 7, 0x22, 0x42, 0xAA, 0x4F, 9, 14, 9];
818 let items: Vec<_> = reg.parse_loop(&t).collect::<Result<_, _>>().unwrap();
819 match &items[0] {
820 AnyDescriptor::Other { tag: 62, value } => {
821 assert!(value.downcast_ref::<TuwaAvs3VideoDescriptor>().is_some());
822 }
823 other => panic!("expected TuwaAvs3Video, got {other:?}"),
824 }
825 let plain = DescriptorRegistry::new();
826 let items: Vec<_> = plain.parse_loop(&t).collect::<Result<_, _>>().unwrap();
827 assert!(matches!(items[0], AnyDescriptor::Unknown { tag: 62, .. }));
828 }
829
830 #[test]
835 fn program_info_registration_scopes_es_info_descriptors() {
836 use crate::descriptors::avs3_video::Avs3VideoDescriptor;
837 use crate::descriptors::private_data_specifier::PDS_AVSV;
838 let program_info = [0x05, 4, b'A', b'V', b'S', b'V'];
839 let es_info = [0xD1, 8, 0x22, 0x42, 0xAA, 0x4B, 9, 14, 9, 0xFF];
841 let mut reg = DescriptorRegistry::new();
842 reg.with_avs3_video();
843
844 let items: Vec<_> = reg.parse_loop(&es_info).collect::<Result<_, _>>().unwrap();
846 assert!(matches!(items[0], AnyDescriptor::Unknown { tag: 0xD1, .. }));
847
848 let mut pi = reg.parse_loop(&program_info);
850 assert_eq!(pi.avs_scope(), None, "no entry consumed yet");
851 for item in pi.by_ref() {
852 item.unwrap();
853 }
854 let scope = pi.avs_scope();
855 assert_eq!(scope, Some(PDS_AVSV));
856 let items: Vec<_> = reg
857 .parse_loop_in_scope(&es_info, scope)
858 .collect::<Result<_, _>>()
859 .unwrap();
860 match &items[0] {
861 AnyDescriptor::Other { tag: 0xD1, value } => {
862 assert!(value.downcast_ref::<Avs3VideoDescriptor>().is_some());
863 }
864 other => panic!("expected Avs3Video via inherited scope, got {other:?}"),
865 }
866 let hevc = [0x05, 4, b'H', b'E', b'V', b'C'];
868 let mut pi = reg.parse_loop(&hevc);
869 for item in pi.by_ref() {
870 item.unwrap();
871 }
872 assert_eq!(pi.avs_scope(), None);
873 }
874
875 #[test]
878 fn avs3_video_descriptor_scopes() {
879 use crate::descriptors::avs3_video::Avs3VideoDescriptor;
880 use crate::descriptors::private_data_specifier::PDS_AVSV;
881 let desc = [0xD1, 8, 0x22, 0x42, 0xAA, 0x4B, 9, 14, 9, 0xFF];
882 let mut reg = DescriptorRegistry::new();
883 reg.with_avs3_video();
884 let check = |bytes: &[u8], idx: usize| {
885 let items: Vec<_> = reg.parse_loop(bytes).collect::<Result<_, _>>().unwrap();
886 match &items[idx] {
887 AnyDescriptor::Other { tag, value } => {
888 assert_eq!(*tag, 0xD1);
889 assert_eq!(
890 value
891 .downcast_ref::<Avs3VideoDescriptor>()
892 .unwrap()
893 .profile_id,
894 0x22
895 );
896 }
897 other => panic!("expected Other, got {other:?}"),
898 }
899 };
900 let mut pds = pds_descriptor(PDS_AVSV);
901 pds.extend_from_slice(&desc);
902 check(&pds, 1);
903 let mut registration = vec![0x05, 4, b'A', b'V', b'S', b'V'];
904 registration.extend_from_slice(&desc);
905 check(®istration, 1);
906 let items: Vec<_> = reg.parse_loop(&desc).collect::<Result<_, _>>().unwrap();
908 assert!(matches!(items[0], AnyDescriptor::Unknown { tag: 0xD1, .. }));
909 let mut other = vec![0x05, 4, b'A', b'C', b'-', b'3'];
910 other.extend_from_slice(&desc);
911 let items: Vec<_> = reg.parse_loop(&other).collect::<Result<_, _>>().unwrap();
912 assert!(matches!(items[1], AnyDescriptor::Unknown { tag: 0xD1, .. }));
913 let adesc = [0xD2, 2, 0x72, 0x45];
915 let mut areg = DescriptorRegistry::new();
916 areg.with_avs3_audio();
917 let mut b = vec![0x05, 4, b'A', b'V', b'S', b'A'];
918 b.extend_from_slice(&adesc);
919 let items: Vec<_> = areg.parse_loop(&b).collect::<Result<_, _>>().unwrap();
920 assert!(matches!(items[1], AnyDescriptor::Other { tag: 0xD2, .. }));
921 }
922
923 #[test]
926 fn avs3_audio_descriptor_is_pds_scoped() {
927 use crate::descriptors::avs3_audio::Avs3AudioDescriptor;
928 use crate::descriptors::private_data_specifier::PDS_AVSA;
929 let desc = [0xD2, 6, 0x03, 0xAA, 0x95, 0x04, 0x00, 0x6A];
930 let mut reg = DescriptorRegistry::new();
931 reg.with_avs3_audio();
932
933 let mut bytes = Vec::new();
934 bytes.extend_from_slice(&pds_descriptor(PDS_AVSA));
935 bytes.extend_from_slice(&desc);
936 let items: Vec<_> = reg.parse_loop(&bytes).collect::<Result<_, _>>().unwrap();
937 match &items[1] {
938 AnyDescriptor::Other { tag, value } => {
939 assert_eq!(*tag, 0xD2);
940 let d = value.downcast_ref::<Avs3AudioDescriptor>().unwrap();
941 assert_eq!(d.sampling_frequency_index, 3);
942 }
943 other => panic!("expected Other (Avs3AudioDescriptor), got {other:?}"),
944 }
945
946 let items: Vec<_> = reg.parse_loop(&desc).collect::<Result<_, _>>().unwrap();
948 assert!(matches!(items[0], AnyDescriptor::Unknown { tag: 0xD2, .. }));
949 let mut other = Vec::new();
950 other.extend_from_slice(&pds_descriptor(PDS_NORDIG));
951 other.extend_from_slice(&desc);
952 let items: Vec<_> = reg.parse_loop(&other).collect::<Result<_, _>>().unwrap();
953 assert!(matches!(items[1], AnyDescriptor::Unknown { tag: 0xD2, .. }));
954 }
955
956 #[test]
957 fn dovi_video_stream_descriptor_is_scoped_to_the_dovi_registration() {
958 use crate::descriptors::dovi_video_stream::DoviVideoStreamDescriptor;
959 let desc = [0xB0, 5, 0x01, 0x00, 0x10, 0x1D, 0x10];
960 let registration = [0x05, 4, b'D', b'O', b'V', b'I'];
961 let mut reg = DescriptorRegistry::new();
962 reg.with_dovi_video_stream();
963
964 let mut scoped = registration.to_vec();
965 scoped.extend_from_slice(&desc);
966 let items: Vec<_> = reg.parse_loop(&scoped).collect::<Result<_, _>>().unwrap();
967 match &items[1] {
968 AnyDescriptor::Other { tag, value } => {
969 assert_eq!(*tag, 0xB0);
970 let d = value.downcast_ref::<DoviVideoStreamDescriptor>().unwrap();
971 assert_eq!(d.profile, 8);
972 }
973 other => panic!("expected Other (DoviVideoStreamDescriptor), got {other:?}"),
974 }
975
976 let items: Vec<_> = reg.parse_loop(&desc).collect::<Result<_, _>>().unwrap();
977 assert!(matches!(items[0], AnyDescriptor::Unknown { tag: 0xB0, .. }));
978 let mut other = vec![0x05, 4, b'H', b'E', b'V', b'C'];
979 other.extend_from_slice(&desc);
980 let items: Vec<_> = reg.parse_loop(&other).collect::<Result<_, _>>().unwrap();
981 assert!(matches!(items[1], AnyDescriptor::Unknown { tag: 0xB0, .. }));
982 }
983
984 #[test]
987 fn china_caption_service_is_opt_in() {
988 use crate::descriptors::china_caption_service::ChinaCaptionServiceDescriptor;
989 let desc = [
990 0x86, 9, 0xE1, b'c', b'h', b'i', 0xC1, 0xC2, 0xFF, 0xE1, 0x00,
991 ];
992 let plain = DescriptorRegistry::new();
993 let items: Vec<_> = plain.parse_loop(&desc).collect::<Result<_, _>>().unwrap();
994 assert!(matches!(items[0], AnyDescriptor::Unknown { tag: 0x86, .. }));
995 let mut reg = DescriptorRegistry::new();
996 reg.with_china_caption_service();
997 let items: Vec<_> = reg.parse_loop(&desc).collect::<Result<_, _>>().unwrap();
998 match &items[0] {
999 AnyDescriptor::Other { tag, value } => {
1000 assert_eq!(*tag, 0x86);
1001 let d = value
1002 .downcast_ref::<ChinaCaptionServiceDescriptor>()
1003 .unwrap();
1004 assert_eq!(d.services.len(), 1);
1005 }
1006 other => panic!("expected Other, got {other:?}"),
1007 }
1008 }
1009
1010 #[test]
1011 fn atsc_caption_service_is_opt_in() {
1012 use crate::descriptors::atsc_caption_service::AtscCaptionServiceDescriptor;
1013 let desc = [0x86, 7, 0xE1, b'e', b'n', b'g', 0xC1, 0x7F, 0xFF];
1014 let plain = DescriptorRegistry::new();
1015 let items: Vec<_> = plain.parse_loop(&desc).collect::<Result<_, _>>().unwrap();
1016 assert!(matches!(items[0], AnyDescriptor::Unknown { tag: 0x86, .. }));
1017 let mut reg = DescriptorRegistry::new();
1018 reg.with_atsc_caption_service();
1019 let items: Vec<_> = reg.parse_loop(&desc).collect::<Result<_, _>>().unwrap();
1020 match &items[0] {
1021 AnyDescriptor::Other { value, .. } => {
1022 let d = value
1023 .downcast_ref::<AtscCaptionServiceDescriptor>()
1024 .unwrap();
1025 assert_eq!(d.services.len(), 1);
1026 }
1027 other => panic!("expected Other, got {other:?}"),
1028 }
1029 }
1030
1031 #[test]
1032 fn pds_agnostic_matches_without_pds() {
1033 let mut reg = DescriptorRegistry::new();
1034 reg.register::<PdsAgnostic>();
1035
1036 let bytes = [0x84, 0x01, 0xDD];
1037 let items: Vec<_> = reg.parse_loop(&bytes).collect::<Result<_, _>>().unwrap();
1038 assert_eq!(items.len(), 1);
1039 match &items[0] {
1040 AnyDescriptor::Other { tag, value } => {
1041 assert_eq!(*tag, 0x84);
1042 let c = value.downcast_ref::<PdsAgnostic>().unwrap();
1043 assert_eq!(c.z, 0xDD);
1044 }
1045 other => panic!("expected Other, got {other:?}"),
1046 }
1047 }
1048
1049 #[test]
1050 fn pds_scoped_takes_precedence_over_agnostic() {
1051 #[derive(Debug, PartialEq, Eq)]
1055 #[cfg_attr(feature = "serde", derive(serde::Serialize))]
1056 struct Agnostic83 {
1057 a: u8,
1058 }
1059
1060 impl<'a> broadcast_core::Parse<'a> for Agnostic83 {
1061 type Error = crate::error::Error;
1062 fn parse(bytes: &'a [u8]) -> crate::Result<Self> {
1063 if bytes.len() < 3 {
1064 return Err(crate::error::Error::BufferTooShort(
1065 broadcast_core::error::BufferTooShort::new(3, bytes.len(), "Agnostic83"),
1066 ));
1067 }
1068 Ok(Self { a: bytes[2] })
1069 }
1070 }
1071
1072 impl DescriptorDef<'_> for Agnostic83 {
1073 const TAG: u8 = 0x83;
1074 const NAME: &'static str = "AGNOSTIC_83";
1075 }
1076
1077 let mut reg = DescriptorRegistry::new();
1078 reg.register::<Agnostic83>();
1079 reg.register_for_pds::<PdsEacem>(PDS_EACEM);
1080
1081 let items: Vec<_> = reg
1083 .parse_loop(&[0x83, 0x01, 0xEE])
1084 .collect::<Result<_, _>>()
1085 .unwrap();
1086 match &items[0] {
1087 AnyDescriptor::Other { value, .. } => {
1088 assert!(value.downcast_ref::<Agnostic83>().is_some());
1089 assert!(value.downcast_ref::<PdsEacem>().is_none());
1090 }
1091 other => panic!("expected Other, got {other:?}"),
1092 }
1093
1094 let mut bytes = Vec::new();
1096 bytes.extend_from_slice(&pds_descriptor(PDS_EACEM));
1097 bytes.extend_from_slice(&[0x83, 0x01, 0xFF]);
1098 let items: Vec<_> = reg.parse_loop(&bytes).collect::<Result<_, _>>().unwrap();
1099 match &items[1] {
1100 AnyDescriptor::Other { value, .. } => {
1101 assert!(value.downcast_ref::<PdsEacem>().is_some());
1102 assert!(value.downcast_ref::<Agnostic83>().is_none());
1103 }
1104 other => panic!("expected Other, got {other:?}"),
1105 }
1106 }
1107
1108 fn logical_channel_descriptor(service_id: u16, visible: bool, lcn: u16) -> Vec<u8> {
1109 let mut v = vec![crate::descriptors::logical_channel::TAG, 4];
1111 v.extend_from_slice(&service_id.to_be_bytes());
1112 let flags = (u8::from(visible) << 7) | ((lcn >> 8) as u8 & 0x03);
1113 v.push(flags);
1114 v.push((lcn & 0xFF) as u8);
1115 v
1116 }
1117
1118 #[test]
1119 fn logical_channel_pds_scoped_matches_correct_pds() {
1120 let mut reg = DescriptorRegistry::new();
1121 reg.with_logical_channel_for_pds(PDS_EACEM);
1122
1123 let mut bytes = Vec::new();
1124 bytes.extend_from_slice(&pds_descriptor(PDS_EACEM));
1125 bytes.extend_from_slice(&logical_channel_descriptor(0x1234, true, 101));
1126
1127 let items: Vec<_> = reg.parse_loop(&bytes).collect::<Result<_, _>>().unwrap();
1128 assert_eq!(items.len(), 2);
1129 assert!(matches!(items[0], AnyDescriptor::PrivateDataSpecifier(_)));
1130 match &items[1] {
1131 AnyDescriptor::LogicalChannel(lc) => {
1132 assert_eq!(lc.entries.len(), 1);
1133 assert_eq!(lc.entries[0].service_id, 0x1234);
1134 assert!(lc.entries[0].visible_service);
1135 assert_eq!(lc.entries[0].logical_channel_number, 101);
1136 }
1137 other => panic!("expected LogicalChannel, got {other:?}"),
1138 }
1139 }
1140
1141 #[test]
1142 fn logical_channel_pds_scoped_rejects_no_pds() {
1143 let mut reg = DescriptorRegistry::new();
1144 reg.with_logical_channel_for_pds(PDS_EACEM);
1145
1146 let bytes = logical_channel_descriptor(0x1234, true, 101);
1147 let items: Vec<_> = reg.parse_loop(&bytes).collect::<Result<_, _>>().unwrap();
1148 assert_eq!(items.len(), 1);
1149 assert!(matches!(
1150 &items[0],
1151 AnyDescriptor::Unknown { tag: 0x83, .. }
1152 ));
1153 }
1154
1155 #[test]
1156 fn logical_channel_pds_scoped_rejects_wrong_pds() {
1157 let mut reg = DescriptorRegistry::new();
1158 reg.with_logical_channel_for_pds(PDS_EACEM);
1159
1160 let mut bytes = Vec::new();
1161 bytes.extend_from_slice(&pds_descriptor(PDS_NORDIG));
1162 bytes.extend_from_slice(&logical_channel_descriptor(0x1234, true, 101));
1163
1164 let items: Vec<_> = reg.parse_loop(&bytes).collect::<Result<_, _>>().unwrap();
1165 assert_eq!(items.len(), 2);
1166 assert!(matches!(items[0], AnyDescriptor::PrivateDataSpecifier(_)));
1167 assert!(matches!(
1168 &items[1],
1169 AnyDescriptor::Unknown { tag: 0x83, .. }
1170 ));
1171 }
1172
1173 #[test]
1174 fn logical_channel_pds_scoped_multiple_pds() {
1175 let mut reg = DescriptorRegistry::new();
1176 reg.with_logical_channel_for_pds(PDS_EACEM);
1177 reg.with_logical_channel_for_pds(PDS_NORDIG);
1178
1179 let mut bytes = Vec::new();
1181 bytes.extend_from_slice(&pds_descriptor(PDS_EACEM));
1182 bytes.extend_from_slice(&logical_channel_descriptor(0x0001, true, 1));
1183 let items: Vec<_> = reg.parse_loop(&bytes).collect::<Result<_, _>>().unwrap();
1184 assert!(matches!(&items[1], AnyDescriptor::LogicalChannel(_)));
1185
1186 let mut bytes2 = Vec::new();
1188 bytes2.extend_from_slice(&pds_descriptor(PDS_NORDIG));
1189 bytes2.extend_from_slice(&logical_channel_descriptor(0x0002, false, 2));
1190 let items2: Vec<_> = reg.parse_loop(&bytes2).collect::<Result<_, _>>().unwrap();
1191 assert!(matches!(&items2[1], AnyDescriptor::LogicalChannel(_)));
1192 }
1193
1194 #[test]
1196 fn program_info_registration_scopes_es_info_with_extensions() {
1197 use crate::descriptors::any::DescriptorLoop;
1198 use crate::descriptors::avs3_video::Avs3VideoDescriptor;
1199 use crate::descriptors::extension::registry::ExtensionRegistry;
1200 use crate::descriptors::private_data_specifier::PDS_AVSV;
1201 let program_info = [0x05, 4, b'A', b'V', b'S', b'V'];
1202 let es_info = [0xD1, 8, 0x22, 0x42, 0xAA, 0x4B, 9, 14, 9, 0xFF];
1203 let mut reg = DescriptorRegistry::new();
1204 reg.with_avs3_video();
1205 let ext = ExtensionRegistry::new();
1206
1207 let items: Vec<_> = DescriptorLoop::new(&es_info)
1208 .iter_with_extensions(®, &ext)
1209 .collect::<Result<_, _>>()
1210 .unwrap();
1211 assert!(matches!(
1212 &items[0],
1213 ExtIterItem::Descriptor(AnyDescriptor::Unknown { tag: 0xD1, .. })
1214 ));
1215
1216 let mut pi = DescriptorLoop::new(&program_info).iter_with_extensions(®, &ext);
1217 for item in pi.by_ref() {
1218 item.unwrap();
1219 }
1220 let scope = pi.avs_scope();
1221 assert_eq!(scope, Some(PDS_AVSV));
1222 let items: Vec<_> = DescriptorLoop::new(&es_info)
1223 .iter_with_extensions_in_scope(®, &ext, scope)
1224 .collect::<Result<_, _>>()
1225 .unwrap();
1226 match &items[0] {
1227 ExtIterItem::Descriptor(AnyDescriptor::Other { tag: 0xD1, value }) => {
1228 assert!(value.downcast_ref::<Avs3VideoDescriptor>().is_some());
1229 }
1230 other => panic!("expected Avs3Video via inherited scope, got {other:?}"),
1231 }
1232 }
1233
1234 #[test]
1235 fn iter_with_extensions_surfaces_custom_extension() {
1236 use crate::descriptors::any::{AnyDescriptor, DescriptorLoop};
1237 use crate::descriptors::extension::registry::ExtensionRegistry;
1238
1239 #[derive(Debug, PartialEq, Eq)]
1240 #[cfg_attr(feature = "serde", derive(serde::Serialize))]
1241 struct MyCustomExt {
1242 payload: Vec<u8>,
1243 }
1244
1245 impl<'a> broadcast_core::Parse<'a> for MyCustomExt {
1246 type Error = crate::error::Error;
1247 fn parse(sel: &'a [u8]) -> crate::Result<Self> {
1248 Ok(Self {
1249 payload: sel.to_vec(),
1250 })
1251 }
1252 }
1253
1254 impl crate::descriptors::extension::ExtensionBodyDef<'_> for MyCustomExt {
1255 const TAG_EXTENSION: u8 = 0x42;
1256 const NAME: &'static str = "MY_CUSTOM_EXT";
1257 }
1258
1259 let mut ext_reg = ExtensionRegistry::new();
1260 ext_reg.register::<MyCustomExt>();
1261
1262 let desc_reg = DescriptorRegistry::new();
1263
1264 let mut loop_bytes = vec![
1266 0x4D, 0x07, b'e', b'n', b'g', 0x02, b'H', b'i', 0x00, ];
1268 loop_bytes.extend_from_slice(&[0x7F, 0x03, 0x42, 0xAB, 0xCD]);
1270
1271 let dl = DescriptorLoop::new(&loop_bytes);
1272 let items: Vec<_> = dl
1273 .iter_with_extensions(&desc_reg, &ext_reg)
1274 .collect::<Result<_, _>>()
1275 .unwrap();
1276 assert_eq!(items.len(), 2);
1277 assert!(matches!(
1279 &items[0],
1280 ExtIterItem::Descriptor(AnyDescriptor::ShortEvent(_))
1281 ));
1282 match &items[1] {
1284 ExtIterItem::CustomExtension {
1285 tag_extension,
1286 value,
1287 } => {
1288 assert_eq!(*tag_extension, 0x42);
1289 let concrete = value.downcast_ref::<MyCustomExt>().unwrap();
1290 assert_eq!(concrete.payload, &[0xAB, 0xCD]);
1291 }
1292 other => panic!("expected CustomExtension, got {other:?}"),
1293 }
1294 }
1295}