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