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