Skip to main content

dvb_si/descriptors/extension/
mod.rs

1//! Extension descriptor — ETSI EN 300 468 §6.2.18.1 (tag `0x7F`).
2//!
3//! The extension descriptor is a container whose first payload byte,
4//! `descriptor_tag_extension`, selects one of a large family of sub-descriptors
5//! (EN 300 468 §6.4.0, Table 109 "Possible locations of extended descriptors").
6//! The framing is Table 54:
7//!
8//! ```text
9//!  byte 0      descriptor_tag           (0x7F)
10//!  byte 1      descriptor_length
11//!  byte 2      descriptor_tag_extension (the discriminant)
12//!  byte 3..    selector_byte[]          (the sub-descriptor body)
13//! ```
14//!
15//! This type mirrors the SAT precedent (`tables/sat.rs`): a typed discriminant
16//! ([`ExtensionDescriptor::tag_extension`], a plain `u8` so unknown values
17//! round-trip) plus a typed body enum ([`ExtensionBody`]) with a
18//! [`ExtensionBody::Raw`] fall-through. [`ExtensionTag`] names the known
19//! discriminant constants but is deliberately NOT used as the stored field type
20//! — unknown tags must survive a parse→serialize round-trip, which a
21//! `TryFromPrimitive` enum could not guarantee.
22//!
23//! # Typed vs. raw bodies
24//!
25//! A body variant is typed only when its syntax table is vendored under
26//! `dvb-si/docs/`. Loop-heavy descriptors have the first fixed level typed and
27//! any variable-length inner loop that has no defined syntax kept as a raw
28//! slice (e.g. service_prominence target_region loop is raw). Per-variant
29//! section comments cite the governing table + clause.
30//!
31//! Typed (syntax table vendored in `en_300_468.md`, except TTML in
32//! `en_303_560_ttml.md`):
33//! - `0x00` image_icon (Table 145, §6.4.7) — fully typed; icon TransportMode per
34//!   Table 146, coordinate_system per Table 147.
35//! - `0x04` T2_delivery_system (Table 133, §6.4.6.3) — cell loop unfolded.
36//! - `0x05` SH_delivery_system (Table 119, §6.4.6.2) — fully typed modulation loop.
37//! - `0x06` supplementary_audio (Table 153, §6.4.11).
38//! - `0x07` network_change_notify (Table 149, §6.4.9) — cell/change loop unfolded.
39//! - `0x08` message (Table 148, §6.4.9).
40//! - `0x09` target_region (Table 156, §6.4.12) — region loop unfolded.
41//! - `0x0A` target_region_name (Table 157, §6.4.13) — region loop unfolded.
42//! - `0x0B` service_relocated (Table 152, §6.4.10).
43//! - `0x0C` XAIT_PID (TS 102 727 §10.17.3) — 13-bit PID.
44//! - `0x0D` C2_delivery_system (Table 115, §6.4.6.1).
45//! - `0x10` video_depth_range (Table 160, §6.4.16.1) — fully typed range loop.
46//! - `0x11` T2MI (Table 158, §6.4.14).
47//! - `0x13` URI_linkage (Table 159, §6.4.16.1) — uri/private split typed.
48//! - `0x15` AC-4 (annex D syntax table, §D.5) — first level; toc/extra raw.
49//! - `0x16` C2_bundle_delivery_system (Table 139, §6.4.6.4) — full fixed loop.
50//! - `0x17` S2X_satellite_delivery_system (Table 140, §6.4.6.5.2) — primary
51//!   channel + channel-bond entries typed; reserved_tail raw.
52//! - `0x19` audio_preselection (Table 110, §6.4.1) — preselection loop unfolded.
53//! - `0x20` TTML_subtitling (`en_303_560_ttml.md` Table 1, §5.2.1.1).
54//! - `0x22` service_prominence (Table 162c, §6.4.18) — SOGI loop typed; target_region loop raw.
55//! - `0x23` vvc_subpictures (Table 162a, §6.4.17) — fully typed.
56//! - `0x24` S2Xv2_satellite_delivery_system (Tables 144a–144c, §6.4.6.5.3) — fully typed.
57//!
58//! Kept [`ExtensionBody::Raw`] (tag value preserved) — spec PDF not vendored;
59//! will be typed once the governing spec is transcribed into `dvb-si/docs/`:
60//! - `0x01` cpcm_delivery_signalling — spec not vendored (ETSI TS 102 825).
61//! - `0x02` CP / `0x03` CP_identifier — spec not vendored (ETSI TS 102 825).
62//! - `0x0E` DTS-HD / `0x0F` DTS_Neural / `0x21` DTS-UHD — spec not vendored (annex G/L).
63//! - `0x14` CI_ancillary_data — spec not vendored (ETSI TS 103 205).
64//! - `0x18` protection_message — spec not vendored (ETSI TS 102 809).
65//! - any other value (incl. `0x80`..=`0xFF` user-defined) — unknown; preserved.
66
67use crate::error::{Error, Result};
68use crate::text::{DvbText, LangCode};
69use dvb_common::{Parse, Serialize};
70
71mod ac4;
72mod audio_preselection;
73mod c2_bundle_delivery_system;
74mod c2_delivery_system;
75mod ci_ancillary_data;
76mod cp;
77mod cp_identifier;
78mod image_icon;
79mod message;
80mod network_change_notify;
81pub mod registry;
82mod s2x_satellite_delivery_system;
83mod s2xv2_satellite_delivery_system;
84mod service_prominence;
85mod service_relocated;
86mod sh_delivery_system;
87mod supplementary_audio;
88mod t2_delivery_system;
89mod t2mi;
90mod target_region;
91mod target_region_name;
92mod ttml_subtitling;
93mod uri_linkage;
94mod video_depth_range;
95mod vvc_subpictures;
96mod xait_pid;
97
98#[cfg(test)]
99mod test_support;
100
101pub use ac4::*;
102pub use audio_preselection::*;
103pub use c2_bundle_delivery_system::*;
104pub use c2_delivery_system::*;
105pub use ci_ancillary_data::*;
106pub use cp::*;
107pub use cp_identifier::*;
108pub use image_icon::*;
109pub use message::*;
110pub use network_change_notify::*;
111pub use s2x_satellite_delivery_system::*;
112pub use s2xv2_satellite_delivery_system::*;
113pub use service_prominence::*;
114pub use service_relocated::*;
115pub use sh_delivery_system::*;
116pub use supplementary_audio::*;
117pub use t2_delivery_system::*;
118pub use t2mi::*;
119pub use target_region::*;
120pub use target_region_name::*;
121pub use ttml_subtitling::*;
122pub use uri_linkage::*;
123pub use video_depth_range::*;
124pub use vvc_subpictures::*;
125pub use xait_pid::*;
126
127/// Descriptor tag for extension_descriptor (EN 300 468 Table 54, §6.2.18.1).
128pub const TAG: u8 = 0x7F;
129pub(crate) const HEADER_LEN: usize = 2;
130/// `descriptor_tag_extension` occupies one byte immediately after the header.
131pub(crate) const TAG_EXTENSION_LEN: usize = 1;
132/// Minimum body length: just the `descriptor_tag_extension` byte.
133pub(crate) const MIN_BODY_LEN: usize = TAG_EXTENSION_LEN;
134/// `descriptor_length` is a single byte; a serialized body may not exceed this.
135pub(crate) const MAX_DESCRIPTOR_LENGTH: usize = 0xFF;
136
137// Per-variant fixed lengths (bytes after `descriptor_tag_extension`).
138pub(crate) const ISO_639_LEN: usize = 3;
139pub(crate) const T2_FIXED_PREFIX_LEN: usize = 3; // plp_id(1) + T2_system_id(2)
140pub(crate) const T2_FLAGS_BLOCK_LEN: usize = 2; // SISO_MISO..tfs_flag, packed in 2 bytes
141pub(crate) const C2_LEN: usize = 7; // plp + data_slice + freq(4) + 1 packed byte
142pub(crate) const C2_BUNDLE_ENTRY_LEN: usize = 8; // plp + data_slice + freq(4) + 1 packed + 1 (primary(1)+reserved_zero(7))
143pub(crate) const SERVICE_RELOCATED_LEN: usize = 6; // 3 × u16
144/// S2X primary-channel block after the 2 flags bytes (excl. scrambling/ISI/timeslice):
145/// frequency(4) + orbital_position(2) + 1 packed byte + symbol_rate(4 bytes).
146pub(crate) const S2X_PRIMARY_LEN: usize = 11;
147pub(crate) const S2X_SCRAMBLING_LEN: usize = 3;
148pub(crate) const TTML_FIXED_LEN: usize = ISO_639_LEN + 2; // ISO_639(3) + 2 packed bytes
149/// Minimum T2MI selector length (Table 158 §6.4.14): 3 fixed bytes before the reserved tail.
150pub(crate) const T2MI_MIN_LEN: usize = 3;
151/// Range header bytes per depth-range entry (Table 160): `range_type` + `range_length`.
152pub(crate) const VD_RANGE_HDR_LEN: usize = 2;
153/// Production disparity hint body length (Table 162): 3 bytes — two 12-bit signed values.
154pub(crate) const VD_DISPARITY_LEN: usize = 3;
155
156/// Known `descriptor_tag_extension` values (EN 300 468 Table 109, §6.4.0).
157///
158/// This is a *naming* aid for callers and parser dispatch; the stored
159/// discriminant is the raw [`ExtensionDescriptor::tag_extension`] `u8` so that
160/// unknown / reserved / user-defined tags round-trip unchanged.
161#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
162#[cfg_attr(feature = "serde", derive(serde::Serialize))]
163#[non_exhaustive]
164#[repr(u8)]
165pub enum ExtensionTag {
166    /// image_icon_descriptor (Table 145, §6.4.7).
167    ImageIcon = 0x00,
168    /// CP_descriptor (Table 113, §6.4.3).
169    Cp = 0x02,
170    /// CP_identifier_descriptor (Table 114, §6.4.6.1).
171    CpIdentifier = 0x03,
172    /// T2_delivery_system_descriptor.
173    T2DeliverySystem = 0x04,
174    /// SH_delivery_system_descriptor (Table 119, §6.4.6.2).
175    ShDeliverySystem = 0x05,
176    /// supplementary_audio_descriptor.
177    SupplementaryAudio = 0x06,
178    /// network_change_notify_descriptor.
179    NetworkChangeNotify = 0x07,
180    /// message_descriptor.
181    Message = 0x08,
182    /// target_region_descriptor.
183    TargetRegion = 0x09,
184    /// target_region_name_descriptor.
185    TargetRegionName = 0x0A,
186    /// service_relocated_descriptor.
187    ServiceRelocated = 0x0B,
188    /// xait_pid_descriptor (TS 102 727 §10.17.3).
189    XaitPid = 0x0C,
190    /// C2_delivery_system_descriptor.
191    C2DeliverySystem = 0x0D,
192    /// video_depth_range_descriptor (Table 160, §6.4.16.1).
193    VideoDepthRange = 0x10,
194    /// T2-MI_descriptor (Table 158, §6.4.14).
195    T2mi = 0x11,
196    /// URI_linkage_descriptor.
197    UriLinkage = 0x13,
198    /// CI_ancillary_data_descriptor (Table 112, §6.4.3).
199    CiAncillaryData = 0x14,
200    /// AC-4_descriptor (annex D).
201    Ac4 = 0x15,
202    /// C2_bundle_delivery_system_descriptor.
203    C2BundleDeliverySystem = 0x16,
204    /// S2X_satellite_delivery_system_descriptor.
205    S2XSatelliteDeliverySystem = 0x17,
206    /// audio_preselection_descriptor.
207    AudioPreselection = 0x19,
208    /// TTML_subtitling_descriptor (ETSI EN 303 560).
209    TtmlSubtitling = 0x20,
210    /// service_prominence_descriptor (Table 162c, §6.4.18).
211    ServiceProminence = 0x22,
212    /// vvc_subpictures_descriptor (Table 162a, §6.4.17).
213    VvcSubpictures = 0x23,
214    /// S2Xv2_satellite_delivery_system_descriptor (Tables 144a–144c, §6.4.6.5.3).
215    S2Xv2SatelliteDeliverySystem = 0x24,
216}
217
218/// Generates the extension-body dispatch from one list (ADR-0001): the
219/// [`ExtensionBody`] enum (+ a `Raw` fall-through), the `parse_body`
220/// dispatcher, the `selector_len`/`write_selector` serialize delegation, and
221/// a drift test pinning each `descriptor_tag_extension` literal to the body
222/// type's [`ExtensionBodyDef::TAG_EXTENSION`] and its [`ExtensionTag`] variant.
223/// One line per typed body — the single source of truth for the sub-dispatch.
224macro_rules! declare_extension_bodies {
225    (
226        $lt:lifetime;
227        $( $(#[doc = $doc:literal])* $variant:ident = $tag:literal => $($path:ident)::+ $(<$plt:lifetime>)? ),+ $(,)?
228    ) => {
229        /// Typed body of an extension descriptor, keyed on `descriptor_tag_extension`.
230        ///
231        /// Unrecognised or not-yet-typed discriminants land in [`ExtensionBody::Raw`],
232        /// which carries the selector bytes verbatim so the descriptor round-trips.
233        #[derive(Debug, Clone, PartialEq, Eq)]
234        #[cfg_attr(feature = "serde", derive(serde::Serialize))]
235        #[cfg_attr(feature = "serde", serde(rename_all = "camelCase"))]
236        #[non_exhaustive]
237        pub enum ExtensionBody<$lt> {
238            $(
239                $(#[doc = $doc])*
240                $variant($($path)::+ $(<$plt>)?),
241            )+
242            /// Any not-yet-typed / unknown / user-defined discriminant: selector bytes verbatim.
243            Raw(&$lt [u8]),
244        }
245
246        /// Parse the selector bytes (everything after `descriptor_tag_extension`)
247        /// into a typed body, falling through to [`ExtensionBody::Raw`].
248        fn parse_body(tag_extension: u8, sel: &[u8]) -> Result<ExtensionBody<'_>> {
249            Ok(match tag_extension {
250                $(
251                    $tag => ExtensionBody::$variant(<$($path)::+>::parse(sel)?),
252                )+
253                _ => ExtensionBody::Raw(sel),
254            })
255        }
256
257        impl ExtensionBody<'_> {
258            /// Selector-byte length (everything after `descriptor_tag_extension`).
259            fn selector_len(&self) -> usize {
260                match self {
261                    $(
262                        ExtensionBody::$variant(b) => b.serialized_len(),
263                    )+
264                    ExtensionBody::Raw(s) => s.len(),
265                }
266            }
267
268            /// Write the selector bytes into `out` (assumed `>= selector_len()`).
269            fn write_selector(&self, out: &mut [u8]) {
270                match self {
271                    $(
272                        ExtensionBody::$variant(b) => {
273                            // `ExtensionDescriptor::serialize_into` sizes `out` from
274                            // `selector_len()`, so `serialize_into` cannot fail.
275                            b.serialize_into(out)
276                                .expect("caller pre-sizes out to selector_len");
277                        }
278                    )+
279                    ExtensionBody::Raw(s) => out[..s.len()].copy_from_slice(s),
280                }
281            }
282        }
283
284        /// Map a `descriptor_tag_extension` byte to its known [`ExtensionTag`].
285        fn kind_from_tag(tag_extension: u8) -> Option<ExtensionTag> {
286            Some(match tag_extension {
287                $(
288                    $tag => ExtensionTag::$variant,
289                )+
290                _ => return None,
291            })
292        }
293
294        #[cfg(test)]
295        mod dispatch_drift {
296            use super::*;
297
298            /// The macro list is the single source of truth: each tag literal must
299            /// equal the body's `ExtensionBodyDef::TAG_EXTENSION`, its `NAME` must be
300            /// non-empty, and `kind()` must map the tag to the matching `ExtensionTag`.
301            #[test]
302            fn ext_dispatch_single_source() {
303                $(
304                    assert_eq!(
305                        $tag,
306                        <$($path)::+ as ExtensionBodyDef<'_>>::TAG_EXTENSION,
307                        concat!("TAG_EXTENSION drift for ", stringify!($variant)),
308                    );
309                    assert!(
310                        !<$($path)::+ as ExtensionBodyDef<'_>>::NAME.is_empty(),
311                        concat!("empty NAME for ", stringify!($variant)),
312                    );
313                    assert_eq!(
314                        ExtensionDescriptor {
315                            tag_extension: $tag,
316                            body: ExtensionBody::Raw(&[]),
317                        }
318                        .kind(),
319                        Some(ExtensionTag::$variant),
320                        concat!("kind() drift for ", stringify!($variant)),
321                    );
322                )+
323            }
324        }
325    };
326}
327
328declare_extension_bodies! {'a;
329    /// `0x00` — image_icon (Table 145, §6.4.7; icon_transport_mode Table 146, §6.4.8;
330    /// coordinate_system Table 147, §6.4.8).
331    ImageIcon = 0x00 => ImageIcon<'a>,
332    /// `0x02` — CP (Table 113, §6.4.3).
333    Cp = 0x02 => Cp<'a>,
334    /// `0x03` — CP_identifier (Table 114, §6.4.6.1).
335    CpIdentifier = 0x03 => CpIdentifier,
336    /// `0x04` — T2_delivery_system (Table 133, §6.4.6.3).
337    T2DeliverySystem = 0x04 => T2DeliverySystem,
338    /// `0x05` — SH_delivery_system (Table 119, §6.4.6.2).
339    ShDeliverySystem = 0x05 => ShDeliverySystem,
340    /// `0x06` — supplementary_audio (Table 153, §6.4.11).
341    SupplementaryAudio = 0x06 => SupplementaryAudio<'a>,
342    /// `0x07` — network_change_notify (Table 149, §6.4.9).
343    NetworkChangeNotify = 0x07 => NetworkChangeNotify,
344    /// `0x08` — message (Table 148, §6.4.9).
345    Message = 0x08 => Message<'a>,
346    /// `0x09` — target_region (Table 156, §6.4.12).
347    TargetRegion = 0x09 => TargetRegion,
348    /// `0x0A` — target_region_name (Table 157, §6.4.13).
349    TargetRegionName = 0x0A => TargetRegionName<'a>,
350    /// `0x0B` — service_relocated (Table 152, §6.4.10).
351    ServiceRelocated = 0x0B => ServiceRelocated,
352    /// `0x0C` — xait_pid (TS 102 727 §10.17.3).
353    XaitPid = 0x0C => XaitPid,
354    /// `0x0D` — C2_delivery_system (Table 115, §6.4.6.1).
355    C2DeliverySystem = 0x0D => C2DeliverySystem,
356    /// `0x10` — video_depth_range (Table 160, §6.4.16.1).
357    VideoDepthRange = 0x10 => VideoDepthRange<'a>,
358    /// `0x11` — T2-MI (Table 158, §6.4.14).
359    T2mi = 0x11 => T2mi<'a>,
360    /// `0x13` — URI_linkage (Table 159, §6.4.16.1).
361    UriLinkage = 0x13 => UriLinkage<'a>,
362    /// `0x14` — CI_ancillary_data (Table 112, §6.4.3).
363    CiAncillaryData = 0x14 => CiAncillaryData<'a>,
364    /// `0x15` — AC-4 (annex D).
365    Ac4 = 0x15 => Ac4<'a>,
366    /// `0x16` — C2_bundle_delivery_system (Table 139, §6.4.6.4).
367    C2BundleDeliverySystem = 0x16 => C2BundleDeliverySystem,
368    /// `0x17` — S2X_satellite_delivery_system (Table 140, §6.4.6.5.2).
369    S2XSatelliteDeliverySystem = 0x17 => S2XSatelliteDeliverySystem<'a>,
370    /// `0x19` — audio_preselection (Table 110, §6.4.1).
371    AudioPreselection = 0x19 => AudioPreselection<'a>,
372    /// `0x20` — TTML_subtitling (EN 303 560 Table 1, §5.2.1.1).
373    TtmlSubtitling = 0x20 => TtmlSubtitling<'a>,
374    /// `0x22` — service_prominence (Table 162c, §6.4.18).
375    ServiceProminence = 0x22 => ServiceProminence<'a>,
376    /// `0x23` — vvc_subpictures (Table 162a, §6.4.17).
377    VvcSubpictures = 0x23 => VvcSubpictures<'a>,
378    /// `0x24` — S2Xv2_satellite_delivery_system (Tables 144a–144c, §6.4.6.5.3).
379    S2Xv2SatelliteDeliverySystem = 0x24 => S2Xv2SatelliteDeliverySystem<'a>,
380}
381
382/// Per-body metadata for the extension-descriptor sub-dispatch — the
383/// `descriptor_tag_extension` value and a diagnostic name. Mirrors
384/// [`crate::traits::DescriptorDef`] for the second dispatch level (ADR-0001).
385pub trait ExtensionBodyDef<'a>: dvb_common::Parse<'a, Error = crate::error::Error> {
386    /// The `descriptor_tag_extension` value this body is selected by.
387    const TAG_EXTENSION: u8;
388    /// SCREAMING_SNAKE diagnostic name, suffix-free.
389    const NAME: &'static str;
390}
391
392/// Extension descriptor (EN 300 468 Table 54, §6.2.18.1).
393#[derive(Debug, Clone, PartialEq, Eq)]
394#[cfg_attr(feature = "serde", derive(serde::Serialize))]
395#[cfg_attr(feature = "yoke", derive(yoke::Yokeable))]
396pub struct ExtensionDescriptor<'a> {
397    /// `descriptor_tag_extension` (raw `u8`; see [`ExtensionTag`] for names).
398    pub tag_extension: u8,
399    /// Typed body, or [`ExtensionBody::Raw`] for not-yet-typed discriminants.
400    pub body: ExtensionBody<'a>,
401}
402
403impl ExtensionDescriptor<'_> {
404    /// Typed view of [`Self::tag_extension`], or `None` if not a known tag.
405    #[must_use]
406    pub fn kind(&self) -> Option<ExtensionTag> {
407        kind_from_tag(self.tag_extension)
408    }
409}
410
411// ---------------------------------------------------------------------------
412//  Body parsers (each consumes the selector bytes after descriptor_tag_extension)
413// ---------------------------------------------------------------------------
414
415pub(crate) fn invalid(reason: &'static str) -> Error {
416    Error::InvalidDescriptor { tag: TAG, reason }
417}
418
419/// Validate an extension_descriptor header and split into (tag_extension, selector).
420/// Shared by [`ExtensionDescriptor::parse`] and [`ExtensionRegistry::parse`].
421pub(crate) fn validate_and_split(bytes: &[u8]) -> Result<(u8, &[u8])> {
422    if bytes.len() < HEADER_LEN {
423        return Err(Error::BufferTooShort {
424            need: HEADER_LEN,
425            have: bytes.len(),
426            what: "ExtensionDescriptor header",
427        });
428    }
429    if bytes[0] != TAG {
430        return Err(Error::InvalidDescriptor {
431            tag: bytes[0],
432            reason: "unexpected tag for extension_descriptor",
433        });
434    }
435    let length = bytes[1] as usize;
436    let end = HEADER_LEN + length;
437    if bytes.len() < end {
438        return Err(Error::BufferTooShort {
439            need: end,
440            have: bytes.len(),
441            what: "ExtensionDescriptor body",
442        });
443    }
444    if length < MIN_BODY_LEN {
445        return Err(Error::InvalidDescriptor {
446            tag: TAG,
447            reason: "body must contain at least the descriptor_tag_extension byte",
448        });
449    }
450    let tag_extension = bytes[HEADER_LEN];
451    let sel = &bytes[HEADER_LEN + TAG_EXTENSION_LEN..end];
452    Ok((tag_extension, sel))
453}
454
455impl<'a> Parse<'a> for ExtensionDescriptor<'a> {
456    type Error = crate::error::Error;
457    fn parse(bytes: &'a [u8]) -> Result<Self> {
458        let (tag_extension, sel) = validate_and_split(bytes)?;
459        let body = parse_body(tag_extension, sel)?;
460        Ok(Self {
461            tag_extension,
462            body,
463        })
464    }
465}
466
467impl Serialize for ExtensionDescriptor<'_> {
468    type Error = crate::error::Error;
469    fn serialized_len(&self) -> usize {
470        HEADER_LEN + TAG_EXTENSION_LEN + self.body.selector_len()
471    }
472
473    fn serialize_into(&self, buf: &mut [u8]) -> Result<usize> {
474        let len = self.serialized_len();
475        if buf.len() < len {
476            return Err(Error::OutputBufferTooSmall {
477                need: len,
478                have: buf.len(),
479            });
480        }
481        let body_len = len - HEADER_LEN;
482        if body_len > MAX_DESCRIPTOR_LENGTH {
483            return Err(Error::InvalidDescriptor {
484                tag: TAG,
485                reason: "descriptor_length exceeds 255 bytes",
486            });
487        }
488        buf[0] = TAG;
489        buf[1] = body_len as u8;
490        buf[HEADER_LEN] = self.tag_extension;
491        self.body
492            .write_selector(&mut buf[HEADER_LEN + TAG_EXTENSION_LEN..len]);
493        Ok(len)
494    }
495}
496impl<'a> crate::traits::DescriptorDef<'a> for ExtensionDescriptor<'a> {
497    const TAG: u8 = TAG;
498    const NAME: &'static str = "EXTENSION";
499}
500
501#[cfg(test)]
502mod tests {
503    use super::test_support::*;
504    use super::*;
505
506    #[test]
507    fn parse_rejects_wrong_tag() {
508        let raw = [0x43, 1, 0x04];
509        assert!(matches!(
510            ExtensionDescriptor::parse(&raw).unwrap_err(),
511            Error::InvalidDescriptor { tag: 0x43, .. }
512        ));
513    }
514
515    #[test]
516    fn parse_rejects_empty_body() {
517        let raw = [TAG, 0];
518        assert!(matches!(
519            ExtensionDescriptor::parse(&raw).unwrap_err(),
520            Error::InvalidDescriptor { tag: TAG, .. }
521        ));
522    }
523
524    #[test]
525    fn parse_rejects_truncated_body() {
526        // declares length 3 but only 1 body byte present
527        let raw = [TAG, 3, 0x08];
528        assert!(matches!(
529            ExtensionDescriptor::parse(&raw).unwrap_err(),
530            Error::BufferTooShort { .. }
531        ));
532    }
533
534    #[test]
535    fn unknown_tag_round_trips_as_raw() {
536        // 0x42 is reserved/unknown — must survive as Raw with bytes preserved.
537        let sel = [0xDE, 0xAD, 0xBE, 0xEF];
538        let bytes = wrap(0x42, &sel);
539        let d = ExtensionDescriptor::parse(&bytes).unwrap();
540        assert_eq!(d.tag_extension, 0x42);
541        assert_eq!(d.kind(), None);
542        assert!(matches!(d.body, ExtensionBody::Raw(b) if b == sel));
543        round_trip(&d);
544    }
545
546    #[test]
547    fn user_defined_tag_preserved() {
548        let bytes = wrap(0x90, &[0x01, 0x02]);
549        let d = ExtensionDescriptor::parse(&bytes).unwrap();
550        assert_eq!(d.tag_extension, 0x90);
551        assert!(matches!(d.body, ExtensionBody::Raw(_)));
552        round_trip(&d);
553    }
554
555    #[test]
556    fn serialize_rejects_too_small_buffer() {
557        let d = ExtensionDescriptor {
558            tag_extension: 0x0B,
559            body: ExtensionBody::ServiceRelocated(ServiceRelocated {
560                old_original_network_id: 1,
561                old_transport_stream_id: 2,
562                old_service_id: 3,
563            }),
564        };
565        let mut tiny = [0u8; 2];
566        assert!(matches!(
567            d.serialize_into(&mut tiny).unwrap_err(),
568            Error::OutputBufferTooSmall { .. }
569        ));
570    }
571
572    #[test]
573    fn descriptor_length_matches_body() {
574        let d = ExtensionDescriptor {
575            tag_extension: 0x08,
576            body: ExtensionBody::Message(Message {
577                message_id: 1,
578                iso_639_language_code: LangCode(*b"eng"),
579                text: DvbText::new(b"hello"),
580            }),
581        };
582        // tag_ext(1) + message_id(1) + iso(3) + text(5) = 10
583        assert_eq!(d.serialized_len() - 2, 10);
584    }
585
586    /// Serialization is deterministic for an all-owned typed body (no borrowed
587    /// slices). `ExtensionDescriptor` is serialize-only because
588    /// `ExtensionBody::Message` contains `DvbText` which is serialize-only; we
589    /// therefore assert serialize stability rather than a round-trip.
590    #[cfg(feature = "serde")]
591    #[test]
592    fn serde_serialize_is_stable_owned_body() {
593        let typed = ExtensionDescriptor {
594            tag_extension: 0x0D,
595            body: ExtensionBody::C2DeliverySystem(C2DeliverySystem {
596                plp_id: 1,
597                data_slice_id: 2,
598                c2_system_tuning_frequency: 0xDEAD_BEEF,
599                c2_system_tuning_frequency_type: C2TuningFrequencyType::C2SystemCentreFrequency,
600                active_ofdm_symbol_duration: ActiveOfdmSymbolDuration::Reserved(2),
601                guard_interval: C2GuardInterval::Reserved(3),
602            }),
603        };
604        let json = serde_json::to_string(&typed).unwrap();
605        assert_eq!(json, serde_json::to_string(&typed.clone()).unwrap());
606        assert!(json.contains("\"tag_extension\":13"));
607        assert!(json.contains("\"c2DeliverySystem\""));
608    }
609
610    /// Borrowed bodies (Raw, Message, …) serialize cleanly; the discriminant +
611    /// tag survive the JSON encoding.
612    #[cfg(feature = "serde")]
613    #[test]
614    fn serde_serializes_borrowed_body() {
615        let raw = ExtensionDescriptor {
616            tag_extension: 0x42,
617            body: ExtensionBody::Raw(&[0x01, 0x02, 0x03]),
618        };
619        let json = serde_json::to_string(&raw).unwrap();
620        assert!(json.contains("\"tag_extension\":66"));
621        assert!(json.contains("\"raw\""));
622
623        let msg = ExtensionDescriptor {
624            tag_extension: 0x08,
625            body: ExtensionBody::Message(Message {
626                message_id: 7,
627                iso_639_language_code: LangCode(*b"eng"),
628                text: DvbText::new(b"hi"),
629            }),
630        };
631        let json = serde_json::to_string(&msg).unwrap();
632        assert!(json.contains("\"message_id\":7"));
633    }
634
635    /// Cross-implementation conformance: exact extension-descriptor bytes
636    /// compiled by TSDuck (github.com/tsduck/tsduck-test, reference tests 015
637    /// and 115). Parsing then re-serializing must reproduce each descriptor
638    /// verbatim — this validates our wire layout (including
639    /// `reserved_future_use` bits = 1, per the DVB convention) against an
640    /// independent encoder, which a self-round-trip cannot.
641    #[test]
642    fn tsduck_reference_round_trip_byte_exact() {
643        let vectors = [
644            // service_prominence (test-115)
645            (
646                "7f20221a300c04d2f000092911fc465241fd47425211fa0102fb0b0c000ddeadbeef",
647                ExtensionTag::ServiceProminence,
648            ),
649            ("7f0a22000011223344556677", ExtensionTag::ServiceProminence),
650            (
651                "7f0d220b700e092906fe4742520102",
652                ExtensionTag::ServiceProminence,
653            ),
654            // image_icon (test-015)
655            (
656                "7f1a000cfc2b3e71c809696d6167652f706e67080123456789abcdef",
657                ExtensionTag::ImageIcon,
658            ),
659            (
660                "7f220007fe5f0a696d6167652f6a70656712687474703a2f2f666f6f2f6261722e6a7067",
661                ExtensionTag::ImageIcon,
662            ),
663            ("7f090033fe050123456789", ExtensionTag::ImageIcon),
664            // SH_delivery_system (test-015)
665            ("7f02055f", ExtensionTag::ShDeliverySystem),
666            (
667                "7f0d05afff94ac175f68831d8d99ad",
668                ExtensionTag::ShDeliverySystem,
669            ),
670        ];
671        for (hex, ext) in vectors {
672            let bytes = from_hex(hex);
673            let d =
674                ExtensionDescriptor::parse(&bytes).unwrap_or_else(|e| panic!("parse {hex}: {e:?}"));
675            assert_eq!(d.kind(), Some(ext), "kind for {hex}");
676            let mut out = vec![0u8; d.serialized_len()];
677            let n = d.serialize_into(&mut out).unwrap();
678            assert_eq!(out[..n], bytes[..], "byte-exact re-serialize for {hex}");
679        }
680
681        // Decoded-field spot checks (prove we interpret TSDuck's known values,
682        // not merely round-trip our own): the rich image_icon and the rich
683        // service_prominence from the XML sources of tests 015 / 115.
684        let icon = from_hex("7f1a000cfc2b3e71c809696d6167652f706e67080123456789abcdef");
685        match &ExtensionDescriptor::parse(&icon).unwrap().body {
686            ExtensionBody::ImageIcon(b) => {
687                assert_eq!(b.descriptor_number, 0);
688                assert_eq!(b.last_descriptor_number, 12);
689                assert_eq!(b.icon_id, 4);
690                match &b.body {
691                    ImageIconBody::First(f) => {
692                        assert_eq!(f.icon_transport_mode, IconTransportMode::InlineData);
693                        let p = f.position.as_ref().unwrap();
694                        assert_eq!(p.coordinate_system, 2);
695                        assert_eq!(p.icon_horizontal_origin, 999);
696                        assert_eq!(p.icon_vertical_origin, 456);
697                        assert_eq!(f.icon_type.decode(), "image/png");
698                        match &f.payload {
699                            IconLocation::Data(d) => {
700                                assert_eq!(*d, &[0x01, 0x23, 0x45, 0x67, 0x89, 0xAB, 0xCD, 0xEF])
701                            }
702                            other => panic!("expected Data, got {other:?}"),
703                        }
704                    }
705                    other => panic!("expected First, got {other:?}"),
706                }
707            }
708            other => panic!("expected ImageIcon, got {other:?}"),
709        }
710
711        let sp = from_hex("7f20221a300c04d2f000092911fc465241fd47425211fa0102fb0b0c000ddeadbeef");
712        match &ExtensionDescriptor::parse(&sp).unwrap().body {
713            ExtensionBody::ServiceProminence(b) => {
714                assert_eq!(b.sogi_list.len(), 2);
715                assert_eq!(b.sogi_list[0].sogi_priority, 12);
716                assert_eq!(b.sogi_list[0].service_id, Some(1234));
717                assert!(b.sogi_list[1].sogi_flag);
718                assert_eq!(b.sogi_list[1].service_id, Some(2345));
719                assert!(b.sogi_list[1].target_region_loop.is_some());
720                assert_eq!(b.private_data, &[0xDE, 0xAD, 0xBE, 0xEF]);
721            }
722            other => panic!("expected ServiceProminence, got {other:?}"),
723        }
724    }
725}