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