Skip to main content

dvb_si/descriptors/
registry.rs

1//! Runtime descriptor registry — open registration of client private tags.
2//!
3//! [`DescriptorRegistry`] is a runtime-configurable walk engine that mirrors
4//! the semantics of the free [`crate::descriptors::parse_loop`] but allows
5//! clients to register their own private descriptor types.  Registered custom
6//! parsers win over built-in dispatch; the 0x83 logical_channel built-in is
7//! opt-in via [`DescriptorRegistry::with_logical_channel`].
8//!
9//! # PDS-scoped registration
10//!
11//! DVB private descriptor tags (`0x80..=0xFE`) are ambiguous without a
12//! preceding [`private_data_specifier_descriptor`][crate::descriptors::private_data_specifier]
13//! (tag `0x5F`) that scopes them.  Use [`register_for_pds`][DescriptorRegistry::register_for_pds]
14//! to register a type that is only dispatched when the active
15//! `private_data_specifier` matches.  A PDS-scoped registration takes precedence
16//! over a PDS-agnostic [`register`][DescriptorRegistry::register] of the same tag when that
17//! PDS is active.
18//!
19//! # Owned types only
20//!
21//! Registered types must be `'static` (i.e. owned — no borrowed slices).
22//! This is required because the parsed value is heap-allocated as a
23//! `Box<dyn DescriptorObject>` whose concrete type is erased; `dyn Any`
24//! downcast demands `'static`.  If your wire layout contains borrowed bytes,
25//! copy them into a `Vec<u8>` in the struct.
26//!
27//! # Example
28//!
29//! ```rust,no_run
30//! use dvb_si::descriptors::{DescriptorRegistry, AnyDescriptor};
31//! use dvb_si::traits::DescriptorDef;
32//! use broadcast_core::Parse;
33//!
34//! // A registered type must be `serde::Serialize` only when the `serde`
35//! // feature is on (that is what `DescriptorObject` requires there).
36//! #[derive(Debug)]
37//! #[cfg_attr(feature = "serde", derive(serde::Serialize))]
38//! struct MyPrivate { x: u8 }
39//!
40//! impl<'a> Parse<'a> for MyPrivate {
41//!     type Error = dvb_si::Error;
42//!     fn parse(bytes: &'a [u8]) -> dvb_si::Result<Self> {
43//!         if bytes.len() < 3 {
44//!             return Err(dvb_si::Error::BufferTooShort(broadcast_core::error::BufferTooShort::new(
45//!                 3, bytes.len(), "MyPrivate",
46//!             )));
47//!         }
48//!         Ok(Self { x: bytes[2] })
49//!     }
50//! }
51//!
52//! impl<'a> DescriptorDef<'a> for MyPrivate {
53//!     const TAG: u8 = 0xA7;
54//!     const NAME: &'static str = "MY_PRIVATE";
55//! }
56//!
57//! let mut reg = DescriptorRegistry::new();
58//! reg.register::<MyPrivate>().with_logical_channel();
59//!
60//! let bytes = [0xA7, 0x01, 0x42u8];
61//! let items: Vec<_> = reg.parse_loop(&bytes).collect::<Result<_, _>>().unwrap();
62//! if let AnyDescriptor::Other { tag, ref value } = items[0] {
63//!     assert_eq!(tag, 0xA7);
64//!     assert_eq!(value.downcast_ref::<MyPrivate>().unwrap().x, 0x42);
65//! }
66//! ```
67
68use 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    /// Object-safe face of a runtime-registered descriptor value.
76    ///
77    /// Registered types must be owned (`'static`) because the `dyn Any` downcast
78    /// path requires it.  See the [module docs][self] for details.
79    ///
80    /// Implemented automatically via the blanket impl for any `T` satisfying the
81    /// supertraits; you do not need to write this by hand.
82    pub trait DescriptorObject, "descriptor"
83}
84
85// ---------------------------------------------------------------------------
86// Internal parse closure type
87// ---------------------------------------------------------------------------
88
89/// A heap-allocated parse closure that takes a full descriptor (header + body)
90/// and returns an owned, type-erased descriptor value.
91pub(crate) type CustomParse =
92    Box<dyn for<'a> Fn(&'a [u8]) -> crate::Result<Box<dyn DescriptorObject>> + Send + Sync>;
93
94// ---------------------------------------------------------------------------
95// DescriptorRegistry
96// ---------------------------------------------------------------------------
97
98/// Runtime-configurable descriptor registry.
99///
100/// By default the registry has no custom parsers and 0x83 logical_channel is
101/// disabled (it is a private tag that requires `private_data_specifier`
102/// context).  Use [`register`][Self::register] and
103/// [`with_logical_channel`][Self::with_logical_channel] to opt in.
104///
105/// Walk a byte slice with [`parse_loop`][Self::parse_loop]; it returns a lazy
106/// [`RegistryIter`] with identical truncation/fuse/error-continue semantics to
107/// the free [`crate::descriptors::parse_loop`].
108///
109/// # Precedence (per entry)
110///
111/// 1. PDS-scoped custom parser (if the current `private_data_specifier` matches
112///    a [`register_for_pds`][Self::register_for_pds] entry) →
113///    [`AnyDescriptor::Other`]
114/// 2. PDS-agnostic custom-registered parser (tag in the [`custom`][Self::register]
115///    map) → [`AnyDescriptor::Other`]
116/// 3. PDS-scoped logical-channel opt-in (tag 0x83 + active PDS in
117///    [`with_logical_channel_for_pds`][Self::with_logical_channel_for_pds])
118///    → [`AnyDescriptor::LogicalChannel`]
119/// 4. Logical-channel opt-in (tag 0x83 + [`with_logical_channel`][Self::with_logical_channel]
120///    enabled) → [`AnyDescriptor::LogicalChannel`]
121/// 5. Built-in dispatch (internal `AnyDescriptor::dispatch`) → typed variant
122/// 6. Unknown → [`AnyDescriptor::Unknown`]
123#[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    /// Create an empty registry (built-in dispatch only; 0x83 disabled).
132    #[must_use]
133    pub fn new() -> Self {
134        Self::default()
135    }
136
137    /// Register an owned custom descriptor type for its
138    /// [`DescriptorDef::TAG`][crate::traits::DescriptorDef::TAG].
139    ///
140    /// # Owned types only
141    ///
142    /// `T` must be `'static` — no borrowed slices.  The registered value is
143    /// type-erased as `Box<dyn DescriptorObject>`; `dyn Any` downcast requires
144    /// the concrete type to be `'static`.
145    ///
146    /// Registering a type whose `TAG` is already used by a built-in **overrides**
147    /// the built-in for that tag.
148    ///
149    /// Re-registering the same tag replaces the prior custom parser (last wins).
150    /// A failing custom parse surfaces the client's `Parse::Error` unwrapped —
151    /// embed identifying context (type/tag) in your error's `what`/`reason` fields.
152    ///
153    /// The registration is PDS-agnostic: it matches the tag regardless of which
154    /// `private_data_specifier` (if any) is active in the loop.  A
155    /// PDS-scoped registration via [`register_for_pds`][Self::register_for_pds]
156    /// takes precedence over this when the matching PDS is active.
157    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    /// Register an owned custom descriptor type scoped to a specific
172    /// `private_data_specifier` value.
173    ///
174    /// The type is only dispatched when a preceding
175    /// [`private_data_specifier_descriptor`][crate::descriptors::private_data_specifier]
176    /// (tag `0x5F`) in the same descriptor loop has set the active PDS to
177    /// `pds`.  A PDS-scoped registration takes precedence over a PDS-agnostic
178    /// [`register`][Self::register] of the same tag when that PDS is active.
179    ///
180    /// Re-registering the same `(pds, tag)` pair replaces the prior custom
181    /// parser (last wins).
182    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    /// Enable the 0x83 logical_channel built-in.
197    ///
198    /// By default 0x83 is not auto-dispatched because it is a private tag
199    /// whose semantics depend on a `private_data_specifier` context.  Call
200    /// this when you know the loop is from an EACEM/NorDig/D-Book stream.
201    pub fn with_logical_channel(&mut self) -> &mut Self {
202        self.logical_channel = true;
203        self
204    }
205
206    /// Enable the 0x83 logical_channel built-in ONLY when the active
207    /// `private_data_specifier` (set by a preceding 0x5F descriptor in the
208    /// same loop) matches `pds`.
209    ///
210    /// This is a safer opt-in than [`with_logical_channel`][Self::with_logical_channel]:
211    /// tag 0x83 under a different (or absent) PDS stays `Unknown`.
212    ///
213    /// Common values are [`crate::descriptors::PDS_EACEM`] and
214    /// [`crate::descriptors::PDS_NORDIG`].  A per-PDS opt-in takes precedence
215    /// over the global [`with_logical_channel`][Self::with_logical_channel]
216    /// opt-in when the matching PDS is active.
217    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    /// Register both NorDig logical channel descriptors (v1 tag 0x83 and
223    /// v2 tag 0x87) for PDS_NORDIG (0x00000029). See
224    /// [`register_for_pds`][Self::register_for_pds].
225    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    /// Register the AVS3_audio_descriptor (tag 0xD2, T/AI 109.7 clause 8.1.3.4)
232    /// for `private_data_specifier` [`crate::descriptors::PDS_AVSA`] ('AVSA',
233    /// `0x41565341`) - the specifier EN 300 468 V1.20.1 Annex O / TS 101 154
234    /// V2.10.1 section 4.1.8.35 require to precede it. Under any other (or
235    /// no) specifier tag 0xD2 stays `Unknown`.
236    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    /// Register the AVS3_video_descriptor (tag 0xD1, T/AI 109.6 clause 9.3.2 /
244    /// GY/T 420 clause 7.3.3.2) for [`crate::descriptors::PDS_AVSV`] ('AVSV',
245    /// `0x41565356`). The scope is established either by a preceding
246    /// `private_data_specifier_descriptor` (ETSI TS 101 154 V2.10.1 section
247    /// 4.1.8) or by a `registration_descriptor` whose `format_identifier` is
248    /// 'AVSV' (the Chinese documents' form). Otherwise tag 0xD1 stays `Unknown`.
249    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    /// Register the AVS2_video_descriptor (tag 0x40, GY/T 420-2025 clause 7.2.3)
257    /// for 'AVSV' (private_data_specifier or `registration_descriptor`
258    /// `format_identifier`, GY/T 420 clause 7.2.2). Tag 0x40 stays the DVB
259    /// `network_name_descriptor` outside that scope.
260    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    /// Register the AVS2_audio_descriptor (tag 0xD3, T/AI 109.7-2024 clause
268    /// 8.2.3.4) for 'AVSA' (private_data_specifier or `registration_descriptor`
269    /// `format_identifier`, clause 8.2.3.3).
270    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    /// Register the older T/UWA 012.2-2023 AVS3 video descriptor (tag 62,
278    /// clause 5.4.1). The standard gives it no private_data_specifier, so this
279    /// is a PDS-agnostic registration of tag 0x3E.
280    pub fn with_tuwa_avs3_video(&mut self) -> &mut Self {
281        self.register::<crate::descriptors::tuwa_avs3_video::TuwaAvs3VideoDescriptor>()
282    }
283
284    /// Register the Dolby Vision `DOVI_video_stream_descriptor` (tag 0xB0)
285    /// for a loop that carries the `registration_descriptor` whose
286    /// `format_identifier` is `DOVI` (Dolby Vision TS specification Table 3-1),
287    /// the scope that spec gives it. Without that registration tag 0xB0 stays
288    /// `Unknown`.
289    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    /// Register the China `caption_service_descriptor` (tag 0x86, GY/T 270-2013
297    /// clause 6.4 Table 8). The standard gives it no private_data_specifier, so
298    /// this is a PDS-agnostic registration of tag 0x86: enable it only for
299    /// Chinese DTV streams (tag 0x86 is the ATSC caption_service_descriptor
300    /// elsewhere, with a different layout).
301    pub fn with_china_caption_service(&mut self) -> &mut Self {
302        self.register::<crate::descriptors::china_caption_service::ChinaCaptionServiceDescriptor>()
303    }
304
305    /// Register the ATSC `caption_service_descriptor` (tag 0x86, ATSC A/65:2013
306    /// §6.9.2 Table 6.26). PDS-agnostic registration of tag 0x86: enable it for
307    /// ATSC streams only, and not together with
308    /// [`Self::with_china_caption_service`], which claims the same tag.
309    pub fn with_atsc_caption_service(&mut self) -> &mut Self {
310        self.register::<crate::descriptors::atsc_caption_service::AtscCaptionServiceDescriptor>()
311    }
312
313    /// Lazily walk a raw descriptor loop using this registry's configuration.
314    ///
315    /// Semantics mirror [`crate::descriptors::parse_loop`]: per-descriptor
316    /// parse errors yield `Err` and iteration continues; a truncated final
317    /// header or body yields one `Err` then fuses.
318    ///
319    /// A `private_data_specifier_descriptor` (tag `0x5F`) in the loop
320    /// automatically updates the iterator's PDS context, scoping subsequent
321    /// private-tag dispatch.
322    #[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    /// Like [`parse_loop`](Self::parse_loop) but starting inside the scope an
334    /// enclosing loop already opened (`inherited`, from
335    /// [`RegistryIter::avs_scope`]).
336    ///
337    /// T/AI 109.7 clause 8.1.3 and GY/T 420 clauses 7.2.2 / 7.3.3.1 / 7.4.3.1
338    /// put the `registration_descriptor` under "Program and program element
339    /// descriptors" and say only that "the PMT shall contain" it, without
340    /// naming the `program_info` or the `ES_info` loop, while the AVS
341    /// descriptors themselves sit in the ES_info loop (T/AI 109.7 clause
342    /// 8.1.3.4, GY/T 420 clause 7.3.1 d). A registration in the `program_info`
343    /// loop therefore has to scope the AVS descriptors of the elementary-stream
344    /// loops that follow: walk `program_info` with `parse_loop`, take the scope
345    /// with `avs_scope`, and walk each ES_info loop with this method.
346    #[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
362// ---------------------------------------------------------------------------
363// RegistryIter
364// ---------------------------------------------------------------------------
365
366/// Lazy iterator over a raw descriptor loop, driven by a [`DescriptorRegistry`].
367///
368/// Returned by [`DescriptorRegistry::parse_loop`].
369pub 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
377/// Shared precedence ladder for both [`RegistryIter`] and [`ExtRegistryIter`].
378///
379/// Returns the [`AnyDescriptor`] that results from applying the six-step
380/// precedence: PDS-scoped custom → PDS-agnostic custom → PDS-scoped
381/// logical-channel → logical-channel opt-in → built-in dispatch → Unknown.
382pub(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    // The Chinese AVS3 documents (T/AI 109.6/109.7, GY/T 420) scope their
420    // descriptors with a registration_descriptor whose format_identifier is the
421    // same four ASCII bytes as the DVB private_data_specifier ('AVSV'/'AVSA'),
422    // so such a registration opens the same scope. Any other registration
423    // leaves the context untouched.
424    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    /// The AVS scope ('AVSV' / 'AVSA') the entries walked so far opened, via a
448    /// `private_data_specifier_descriptor` or a `registration_descriptor`
449    /// `format_identifier`; `None` when no AVS scope is open. Feed it to
450    /// [`DescriptorRegistry::parse_loop_in_scope`] for the elementary-stream
451    /// loops that follow a `program_info` loop.
452    #[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// ---------------------------------------------------------------------------
481// ExtIterItem — item type for iter_with_extensions
482// ---------------------------------------------------------------------------
483
484/// Item produced by [`DescriptorLoop::iter_with_extensions`](super::any::DescriptorLoop::iter_with_extensions).
485///
486/// Extends [`AnyDescriptor`] with a third arm for custom-registered extension
487/// bodies whose `descriptor_tag_extension` is recognised by an
488/// [`ExtensionRegistry`](super::extension::registry::ExtensionRegistry).
489/// The `value` field can be downcast to the concrete type via
490/// `downcast_ref` on the value (see [`ExtensionObject`](super::extension::registry::ExtensionObject))
491#[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    /// A regular descriptor (including built-in extension descriptors).
497    Descriptor(AnyDescriptor<'a>),
498    /// A custom-registered extension body (tag `0x7F`, known `descriptor_tag_extension`).
499    CustomExtension {
500        /// The `descriptor_tag_extension` byte.
501        tag_extension: u8,
502        /// The parsed, type-erased extension body value. Call `downcast_ref`
503        /// on it (see [`ExtensionObject`](super::extension::registry::ExtensionObject)) to recover the concrete type.
504        #[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
512// ---------------------------------------------------------------------------
513// ExtRegistryIter — iterator for iter_with_extensions
514// ---------------------------------------------------------------------------
515
516/// Lazy iterator over a raw descriptor loop, driven by both a
517/// [`DescriptorRegistry`] and an
518/// [`ExtensionRegistry`](super::extension::registry::ExtensionRegistry).
519///
520/// Returned by [`DescriptorLoop::iter_with_extensions`](super::any::DescriptorLoop::iter_with_extensions).
521pub 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    /// The AVS scope ('AVSV' / 'AVSA') the entries walked so far opened; see
548    /// [`RegistryIter::avs_scope`].
549    #[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
556/// Wire header of one descriptor entry: tag + length.
557const DESCRIPTOR_HEADER_LEN: usize = 2;
558/// Offset of `extension_descriptor_tag` within an extension descriptor entry.
559const EXTENSION_TAG_OFFSET: usize = DESCRIPTOR_HEADER_LEN;
560/// Offset of the extension descriptor body within its entry.
561const 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        // Pin the public consts to the vendored TS 101 162 register
622        // (registries/tsPDS.names) so they can't silently drift.
623        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    /// AVS2 descriptors (GY/T 420 / T/AI 109.7) and the T/UWA 012.2 tag-62
764    /// descriptor are opt-in and scoped like the AVS3 ones.
765    #[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        // Unscoped tag 0x40 is still the DVB network_name_descriptor.
778        let items: Vec<_> = reg.parse_loop(&v).collect::<Result<_, _>>().unwrap();
779        assert!(matches!(items[0], AnyDescriptor::NetworkName(_)));
780        // Scoped by an 'AVSV' registration_descriptor it is the AVS2 descriptor.
781        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        // ... or by a private_data_specifier.
791        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        // Without scope tag 0xD3 stays Unknown.
813        let items: Vec<_> = reg.parse_loop(&a).collect::<Result<_, _>>().unwrap();
814        assert!(matches!(items[0], AnyDescriptor::Unknown { tag: 0xD3, .. }));
815
816        // T/UWA 012.2 tag 62: PDS-agnostic opt-in.
817        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    /// The specs say "the PMT shall contain" the 'AVSV'/'AVSA'
831    /// registration_descriptor without naming the loop, and put the AVS
832    /// descriptor in the ES_info loop: a registration in `program_info` must
833    /// scope the ES_info loops that follow (`avs_scope` + `parse_loop_in_scope`).
834    #[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        // ES_info of the stream_type 0xD4 entry: just the AVS3 video descriptor.
840        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        // Per-loop scoping alone never sees the registration: Unknown.
845        let items: Vec<_> = reg.parse_loop(&es_info).collect::<Result<_, _>>().unwrap();
846        assert!(matches!(items[0], AnyDescriptor::Unknown { tag: 0xD1, .. }));
847
848        // Walk program_info, carry the scope into the ES_info walk.
849        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        // A non-AVS program_info registration opens no scope to inherit.
867        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    /// AVS3_video_descriptor (tag 0xD1): scoped by a 'AVSV' private_data_specifier
876    /// (TS 101 154) or a 'AVSV' registration_descriptor (T/AI 109.6 / GY/T 420).
877    #[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(&registration, 1);
906        // No scope, or a different registration ('AC-3'), leaves it Unknown.
907        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        // The audio descriptor also accepts the 'AVSA' registration form.
914        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    /// T/AI 109.7 clause 8.1.3.4 + TS 101 154 V2.10.1 4.1.8.35: tag 0xD2 is the
924    /// AVS3_audio_descriptor only under private_data_specifier 'AVSA'.
925    #[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        // Without the 'AVSA' specifier (or under another) the tag stays Unknown.
947        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    /// GY/T 270-2013 Table 8: tag 0x86 is the China caption_service_descriptor
985    /// once `with_china_caption_service` is enabled, and stays Unknown otherwise.
986    #[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        // Two parsers compete for the SAME tag 0x83: one PDS-agnostic, one
1052        // scoped to EACEM. With no PDS active the agnostic one wins; once an
1053        // EACEM private_data_specifier appears, the scoped one takes over.
1054        #[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        // No PDS → agnostic wins
1082        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        // With PDS EACEM → PDS-scoped wins
1095        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        // One entry: tag=0x83, len=4, entry(4 bytes)
1110        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        // EACEM → LogicalChannel
1180        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        // NorDig → LogicalChannel
1187        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    /// Same program_info-registration layout through `iter_with_extensions`.
1195    #[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(&reg, &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(&reg, &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(&reg, &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        // Build a descriptor loop with a short_event + a 0x7F extension with tag_extension 0x42
1265        let mut loop_bytes = vec![
1266            0x4D, 0x07, b'e', b'n', b'g', 0x02, b'H', b'i', 0x00, // short_event
1267        ];
1268        // extension: tag=0x7F, length=3, tag_extension=0x42, selector=[0xAB, 0xCD]
1269        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        // First item is a regular descriptor
1278        assert!(matches!(
1279            &items[0],
1280            ExtIterItem::Descriptor(AnyDescriptor::ShortEvent(_))
1281        ));
1282        // Second item surfaces the custom extension body (not Raw!)
1283        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}