Skip to main content

dvb_si/descriptors/extension/
t2_delivery_system.rs

1//! T2 Delivery System Descriptor — ETSI EN 300 468 §6.4.6.3 (tag_extension 0x04).
2use super::*;
3use alloc::vec;
4use alloc::vec::Vec;
5
6impl<'a> ExtensionBodyDef<'a> for T2DeliverySystem {
7    const TAG_EXTENSION: u8 = 0x04;
8    const NAME: &'static str = "T2_DELIVERY_SYSTEM";
9}
10
11// ---------------------------------------------------------------------------
12//  T2-specific enums (Tables 134-137)
13// ---------------------------------------------------------------------------
14
15/// SISO/MISO mode — ETSI EN 300 468 Table 134.
16#[derive(Debug, Clone, Copy, PartialEq, Eq)]
17#[cfg_attr(feature = "serde", derive(serde::Serialize))]
18#[non_exhaustive]
19pub enum T2SisoMiso {
20    /// Single Input, Single Output (SISO).
21    Siso,
22    /// Multiple Input, Single Output (MISO).
23    Miso,
24    /// Reserved / future use.
25    Reserved(u8),
26}
27
28impl T2SisoMiso {
29    #[must_use]
30    /// Construct from a raw `u8`; every value maps to a variant (total, lossless).
31    pub fn from_u8(v: u8) -> Self {
32        match v {
33            0 => T2SisoMiso::Siso,
34            1 => T2SisoMiso::Miso,
35            other => T2SisoMiso::Reserved(other),
36        }
37    }
38
39    #[must_use]
40    /// Inverse of `from_u8`; `Self::Reserved` emits its stored value.
41    pub fn to_u8(self) -> u8 {
42        match self {
43            T2SisoMiso::Siso => 0,
44            T2SisoMiso::Miso => 1,
45            T2SisoMiso::Reserved(v) => v,
46        }
47    }
48
49    #[must_use]
50    /// Human-readable spec name per the governing Table.
51    pub fn name(self) -> &'static str {
52        match self {
53            T2SisoMiso::Siso => "SISO",
54            T2SisoMiso::Miso => "MISO",
55            T2SisoMiso::Reserved(_) => "reserved",
56        }
57    }
58}
59dvb_common::impl_spec_display!(T2SisoMiso, Reserved);
60
61/// Bandwidth — ETSI EN 300 468 Table 135.
62#[derive(Debug, Clone, Copy, PartialEq, Eq)]
63#[cfg_attr(feature = "serde", derive(serde::Serialize))]
64#[non_exhaustive]
65pub enum T2Bandwidth {
66    /// 8 MHz.
67    Mhz8,
68    /// 7 MHz.
69    Mhz7,
70    /// 6 MHz.
71    Mhz6,
72    /// 5 MHz.
73    Mhz5,
74    /// 10 MHz.
75    Mhz10,
76    /// 1.712 MHz.
77    Mhz1_712,
78    /// Reserved / future use.
79    Reserved(u8),
80}
81
82impl T2Bandwidth {
83    #[must_use]
84    /// Construct from a raw `u8`; every value maps to a variant (total, lossless).
85    pub fn from_u8(v: u8) -> Self {
86        match v {
87            0 => T2Bandwidth::Mhz8,
88            1 => T2Bandwidth::Mhz7,
89            2 => T2Bandwidth::Mhz6,
90            3 => T2Bandwidth::Mhz5,
91            4 => T2Bandwidth::Mhz10,
92            5 => T2Bandwidth::Mhz1_712,
93            other => T2Bandwidth::Reserved(other),
94        }
95    }
96
97    #[must_use]
98    /// Inverse of `from_u8`; `Self::Reserved` emits its stored value.
99    pub fn to_u8(self) -> u8 {
100        match self {
101            T2Bandwidth::Mhz8 => 0,
102            T2Bandwidth::Mhz7 => 1,
103            T2Bandwidth::Mhz6 => 2,
104            T2Bandwidth::Mhz5 => 3,
105            T2Bandwidth::Mhz10 => 4,
106            T2Bandwidth::Mhz1_712 => 5,
107            T2Bandwidth::Reserved(v) => v,
108        }
109    }
110
111    #[must_use]
112    /// Human-readable spec name per the governing Table.
113    pub fn name(self) -> &'static str {
114        match self {
115            T2Bandwidth::Mhz8 => "8 MHz",
116            T2Bandwidth::Mhz7 => "7 MHz",
117            T2Bandwidth::Mhz6 => "6 MHz",
118            T2Bandwidth::Mhz5 => "5 MHz",
119            T2Bandwidth::Mhz10 => "10 MHz",
120            T2Bandwidth::Mhz1_712 => "1.712 MHz",
121            T2Bandwidth::Reserved(_) => "reserved",
122        }
123    }
124}
125dvb_common::impl_spec_display!(T2Bandwidth, Reserved);
126
127/// Guard interval — ETSI EN 300 468 Table 136.
128#[derive(Debug, Clone, Copy, PartialEq, Eq)]
129#[cfg_attr(feature = "serde", derive(serde::Serialize))]
130#[non_exhaustive]
131pub enum T2GuardInterval {
132    /// 1/32.
133    G1_32,
134    /// 1/16.
135    G1_16,
136    /// 1/8.
137    G1_8,
138    /// 1/4.
139    G1_4,
140    /// 1/128.
141    G1_128,
142    /// 19/128.
143    G19_128,
144    /// 19/256.
145    G19_256,
146    /// Reserved / future use.
147    Reserved(u8),
148}
149
150impl T2GuardInterval {
151    #[must_use]
152    /// Construct from a raw `u8`; every value maps to a variant (total, lossless).
153    pub fn from_u8(v: u8) -> Self {
154        match v {
155            0 => T2GuardInterval::G1_32,
156            1 => T2GuardInterval::G1_16,
157            2 => T2GuardInterval::G1_8,
158            3 => T2GuardInterval::G1_4,
159            4 => T2GuardInterval::G1_128,
160            5 => T2GuardInterval::G19_128,
161            6 => T2GuardInterval::G19_256,
162            other => T2GuardInterval::Reserved(other),
163        }
164    }
165
166    #[must_use]
167    /// Inverse of `from_u8`; `Self::Reserved` emits its stored value.
168    pub fn to_u8(self) -> u8 {
169        match self {
170            T2GuardInterval::G1_32 => 0,
171            T2GuardInterval::G1_16 => 1,
172            T2GuardInterval::G1_8 => 2,
173            T2GuardInterval::G1_4 => 3,
174            T2GuardInterval::G1_128 => 4,
175            T2GuardInterval::G19_128 => 5,
176            T2GuardInterval::G19_256 => 6,
177            T2GuardInterval::Reserved(v) => v,
178        }
179    }
180
181    #[must_use]
182    /// Human-readable spec name per the governing Table.
183    pub fn name(self) -> &'static str {
184        match self {
185            T2GuardInterval::G1_32 => "1/32",
186            T2GuardInterval::G1_16 => "1/16",
187            T2GuardInterval::G1_8 => "1/8",
188            T2GuardInterval::G1_4 => "1/4",
189            T2GuardInterval::G1_128 => "1/128",
190            T2GuardInterval::G19_128 => "19/128",
191            T2GuardInterval::G19_256 => "19/256",
192            T2GuardInterval::Reserved(_) => "reserved",
193        }
194    }
195}
196dvb_common::impl_spec_display!(T2GuardInterval, Reserved);
197
198/// Transmission mode — ETSI EN 300 468 Table 137.
199#[derive(Debug, Clone, Copy, PartialEq, Eq)]
200#[cfg_attr(feature = "serde", derive(serde::Serialize))]
201#[non_exhaustive]
202pub enum T2TransmissionMode {
203    /// 2k mode.
204    Mode2k,
205    /// 8k mode.
206    Mode8k,
207    /// 4k mode.
208    Mode4k,
209    /// 1k mode.
210    Mode1k,
211    /// 16k mode.
212    Mode16k,
213    /// 32k mode.
214    Mode32k,
215    /// Reserved / future use.
216    Reserved(u8),
217}
218
219impl T2TransmissionMode {
220    #[must_use]
221    /// Construct from a raw `u8`; every value maps to a variant (total, lossless).
222    pub fn from_u8(v: u8) -> Self {
223        match v {
224            0 => T2TransmissionMode::Mode2k,
225            1 => T2TransmissionMode::Mode8k,
226            2 => T2TransmissionMode::Mode4k,
227            3 => T2TransmissionMode::Mode1k,
228            4 => T2TransmissionMode::Mode16k,
229            5 => T2TransmissionMode::Mode32k,
230            other => T2TransmissionMode::Reserved(other),
231        }
232    }
233
234    #[must_use]
235    /// Inverse of `from_u8`; `Self::Reserved` emits its stored value.
236    pub fn to_u8(self) -> u8 {
237        match self {
238            T2TransmissionMode::Mode2k => 0,
239            T2TransmissionMode::Mode8k => 1,
240            T2TransmissionMode::Mode4k => 2,
241            T2TransmissionMode::Mode1k => 3,
242            T2TransmissionMode::Mode16k => 4,
243            T2TransmissionMode::Mode32k => 5,
244            T2TransmissionMode::Reserved(v) => v,
245        }
246    }
247
248    #[must_use]
249    /// Human-readable spec name per the governing Table.
250    pub fn name(self) -> &'static str {
251        match self {
252            T2TransmissionMode::Mode2k => "2k",
253            T2TransmissionMode::Mode8k => "8k",
254            T2TransmissionMode::Mode4k => "4k",
255            T2TransmissionMode::Mode1k => "1k",
256            T2TransmissionMode::Mode16k => "16k",
257            T2TransmissionMode::Mode32k => "32k",
258            T2TransmissionMode::Reserved(_) => "reserved",
259        }
260    }
261}
262dvb_common::impl_spec_display!(T2TransmissionMode, Reserved);
263
264// ---------------------------------------------------------------------------
265//  Structs
266// ---------------------------------------------------------------------------
267
268/// One T2 cell (Table 133 inner `for`).
269#[derive(Debug, Clone, PartialEq, Eq)]
270#[cfg_attr(feature = "serde", derive(serde::Serialize))]
271pub struct T2Cell {
272    /// cell_id(16).
273    pub cell_id: u16,
274    /// centre_frequency list. When tfs_flag, the length-prefixed loop;
275    /// otherwise exactly one frequency.
276    pub centre_frequencies: Vec<u32>,
277    /// subcell entries.
278    pub subcells: Vec<T2Subcell>,
279}
280
281impl T2Cell {
282    /// Decode all centre_frequencies to Hz (×10 Hz field resolution).
283    #[must_use]
284    pub fn centre_frequencies_hz(&self) -> Vec<u64> {
285        self.centre_frequencies
286            .iter()
287            .map(|&f| u64::from(f) * 10)
288            .collect()
289    }
290}
291
292/// One T2 subcell (Table 133 innermost `for`).
293#[derive(Debug, Clone, Copy, PartialEq, Eq)]
294#[cfg_attr(feature = "serde", derive(serde::Serialize))]
295pub struct T2Subcell {
296    /// cell_id_extension(8).
297    pub cell_id_extension: u8,
298    /// transposer_frequency(32) — ×10 Hz units.
299    pub transposer_frequency: u32,
300}
301
302impl T2Subcell {
303    /// Decode transposer_frequency to Hz (×10 Hz field resolution).
304    #[must_use]
305    pub fn transposer_frequency_hz(&self) -> u64 {
306        u64::from(self.transposer_frequency) * 10
307    }
308}
309
310/// T2_delivery_system body (Table 133). The cell loop is unfolded.
311#[derive(Debug, Clone, PartialEq, Eq)]
312#[cfg_attr(feature = "serde", derive(serde::Serialize))]
313pub struct T2DeliverySystem {
314    /// PLP identifier.
315    pub plp_id: u8,
316    /// T2 system identifier.
317    pub t2_system_id: u16,
318    /// SISO_MISO, present iff `descriptor_length > 4` (flags block present).
319    pub siso_miso: Option<T2SisoMiso>,
320    /// bandwidth, present with `siso_miso`.
321    pub bandwidth: Option<T2Bandwidth>,
322    /// guard_interval, present with `siso_miso`.
323    pub guard_interval: Option<T2GuardInterval>,
324    /// transmission_mode, present with `siso_miso`.
325    pub transmission_mode: Option<T2TransmissionMode>,
326    /// other_frequency_flag, present with `siso_miso`.
327    pub other_frequency_flag: Option<bool>,
328    /// tfs_flag, present with `siso_miso`.
329    pub tfs_flag: Option<bool>,
330    /// Cell loop entries (present only when flags block is present).
331    pub cells: Vec<T2Cell>,
332}
333
334impl<'a> Parse<'a> for T2DeliverySystem {
335    type Error = crate::error::Error;
336    fn parse(sel: &'a [u8]) -> Result<Self> {
337        if sel.len() < T2_FIXED_PREFIX_LEN {
338            return Err(Error::BufferTooShort {
339                need: T2_FIXED_PREFIX_LEN,
340                have: sel.len(),
341                what: "T2_delivery_system body",
342            });
343        }
344        let plp_id = sel[0];
345        let (t2_id_bytes, _) = sel[1..]
346            .split_first_chunk::<2>()
347            .ok_or(Error::BufferTooShort {
348                need: T2_FIXED_PREFIX_LEN,
349                have: sel.len(),
350                what: "T2_delivery_system body",
351            })?;
352        let t2_system_id = u16::from_be_bytes(*t2_id_bytes);
353        let mut pos = T2_FIXED_PREFIX_LEN;
354        let (
355            siso_miso,
356            bandwidth,
357            guard_interval,
358            transmission_mode,
359            other_frequency_flag,
360            tfs_flag,
361        ) = if sel.len() > T2_FIXED_PREFIX_LEN {
362            if sel.len() < T2_FIXED_PREFIX_LEN + T2_FLAGS_BLOCK_LEN {
363                return Err(Error::BufferTooShort {
364                    need: T2_FIXED_PREFIX_LEN + T2_FLAGS_BLOCK_LEN,
365                    have: sel.len(),
366                    what: "T2_delivery_system body",
367                });
368            }
369            let b0 = sel[pos];
370            let b1 = sel[pos + 1];
371            pos += T2_FLAGS_BLOCK_LEN;
372            (
373                Some(T2SisoMiso::from_u8(b0 >> 6)),
374                Some(T2Bandwidth::from_u8((b0 >> 2) & 0x0F)),
375                Some(T2GuardInterval::from_u8(b1 >> 5)),
376                Some(T2TransmissionMode::from_u8((b1 >> 2) & 0x07)),
377                Some((b1 & 0x02) != 0),
378                Some((b1 & 0x01) != 0),
379            )
380        } else {
381            (None, None, None, None, None, None)
382        };
383        let cells =
384            if siso_miso.is_some() {
385                let tfs = tfs_flag.unwrap();
386                let mut cells = Vec::new();
387                while pos < sel.len() {
388                    if pos + 2 > sel.len() {
389                        return Err(Error::BufferTooShort {
390                            need: pos + 2,
391                            have: sel.len(),
392                            what: "T2_delivery_system body",
393                        });
394                    }
395                    let (cell_id_bytes, _) =
396                        sel[pos..]
397                            .split_first_chunk::<2>()
398                            .ok_or(Error::BufferTooShort {
399                                need: pos + 2,
400                                have: sel.len(),
401                                what: "T2_delivery_system body",
402                            })?;
403                    let cell_id = u16::from_be_bytes(*cell_id_bytes);
404                    pos += 2;
405                    let centre_frequencies = if tfs {
406                        if pos >= sel.len() {
407                            return Err(Error::BufferTooShort {
408                                need: pos + 1,
409                                have: sel.len(),
410                                what: "T2_delivery_system body",
411                            });
412                        }
413                        let freq_loop_len = sel[pos] as usize;
414                        pos += 1;
415                        if freq_loop_len % 4 != 0 {
416                            return Err(invalid(
417                                "T2_delivery_system: frequency_loop_length not a multiple of 4",
418                            ));
419                        }
420                        if pos + freq_loop_len > sel.len() {
421                            return Err(Error::BufferTooShort {
422                                need: pos + freq_loop_len,
423                                have: sel.len(),
424                                what: "T2_delivery_system body",
425                            });
426                        }
427                        let end = pos + freq_loop_len;
428                        let mut freqs = Vec::with_capacity(freq_loop_len / 4);
429                        while pos < end {
430                            let (fb, _) = sel[pos..].split_first_chunk::<4>().ok_or(
431                                Error::BufferTooShort {
432                                    need: pos + 4,
433                                    have: sel.len(),
434                                    what: "T2_delivery_system body",
435                                },
436                            )?;
437                            freqs.push(u32::from_be_bytes(*fb));
438                            pos += 4;
439                        }
440                        freqs
441                    } else {
442                        if pos + 4 > sel.len() {
443                            return Err(Error::BufferTooShort {
444                                need: pos + 4,
445                                have: sel.len(),
446                                what: "T2_delivery_system body",
447                            });
448                        }
449                        let (freq_bytes, _) =
450                            sel[pos..]
451                                .split_first_chunk::<4>()
452                                .ok_or(Error::BufferTooShort {
453                                    need: pos + 4,
454                                    have: sel.len(),
455                                    what: "T2_delivery_system body",
456                                })?;
457                        let freq = u32::from_be_bytes(*freq_bytes);
458                        pos += 4;
459                        vec![freq]
460                    };
461                    if pos >= sel.len() {
462                        return Err(Error::BufferTooShort {
463                            need: pos + 1,
464                            have: sel.len(),
465                            what: "T2_delivery_system body",
466                        });
467                    }
468                    let subcell_loop_len = sel[pos] as usize;
469                    pos += 1;
470                    if subcell_loop_len % 5 != 0 {
471                        return Err(invalid(
472                            "T2_delivery_system: subcell_info_loop_length not a multiple of 5",
473                        ));
474                    }
475                    if pos + subcell_loop_len > sel.len() {
476                        return Err(Error::BufferTooShort {
477                            need: pos + subcell_loop_len,
478                            have: sel.len(),
479                            what: "T2_delivery_system body",
480                        });
481                    }
482                    let end = pos + subcell_loop_len;
483                    let mut subcells = Vec::with_capacity(subcell_loop_len / 5);
484                    while pos < end {
485                        let (tf_bytes, _) = sel[pos + 1..].split_first_chunk::<4>().ok_or(
486                            Error::BufferTooShort {
487                                need: pos + 5,
488                                have: sel.len(),
489                                what: "T2_delivery_system body",
490                            },
491                        )?;
492                        subcells.push(T2Subcell {
493                            cell_id_extension: sel[pos],
494                            transposer_frequency: u32::from_be_bytes(*tf_bytes),
495                        });
496                        pos += 5;
497                    }
498                    cells.push(T2Cell {
499                        cell_id,
500                        centre_frequencies,
501                        subcells,
502                    });
503                }
504                cells
505            } else {
506                Vec::new()
507            };
508        Ok(T2DeliverySystem {
509            plp_id,
510            t2_system_id,
511            siso_miso,
512            bandwidth,
513            guard_interval,
514            transmission_mode,
515            other_frequency_flag,
516            tfs_flag,
517            cells,
518        })
519    }
520}
521
522impl Serialize for T2DeliverySystem {
523    type Error = crate::error::Error;
524    fn serialized_len(&self) -> usize {
525        let mut len = T2_FIXED_PREFIX_LEN;
526        if self.siso_miso.is_some() {
527            len += T2_FLAGS_BLOCK_LEN;
528            let tfs = self.tfs_flag.unwrap_or(false);
529            for cell in &self.cells {
530                len += 2; // cell_id
531                if tfs {
532                    len += 1 + cell.centre_frequencies.len() * 4;
533                } else {
534                    len += 4;
535                }
536                len += 1 + cell.subcells.len() * 5;
537            }
538        }
539        len
540    }
541    fn serialize_into(&self, buf: &mut [u8]) -> Result<usize> {
542        let len = self.serialized_len();
543        if buf.len() < len {
544            return Err(Error::OutputBufferTooSmall {
545                need: len,
546                have: buf.len(),
547            });
548        }
549        buf[0] = self.plp_id;
550        buf[1..3].copy_from_slice(&self.t2_system_id.to_be_bytes());
551        let mut p = T2_FIXED_PREFIX_LEN;
552        if let (Some(sm), Some(bw), Some(gi), Some(tm), Some(off), Some(tfs)) = (
553            self.siso_miso,
554            self.bandwidth,
555            self.guard_interval,
556            self.transmission_mode,
557            self.other_frequency_flag,
558            self.tfs_flag,
559        ) {
560            buf[p] = (sm.to_u8() << 6) | ((bw.to_u8() & 0x0F) << 2) | 0x03;
561            buf[p + 1] = (gi.to_u8() << 5)
562                | ((tm.to_u8() & 0x07) << 2)
563                | (u8::from(off) << 1)
564                | u8::from(tfs);
565            p += T2_FLAGS_BLOCK_LEN;
566            for cell in &self.cells {
567                buf[p..p + 2].copy_from_slice(&cell.cell_id.to_be_bytes());
568                p += 2;
569                if tfs {
570                    let freq_len = (cell.centre_frequencies.len() * 4) as u8;
571                    buf[p] = freq_len;
572                    p += 1;
573                    for &freq in &cell.centre_frequencies {
574                        buf[p..p + 4].copy_from_slice(&freq.to_be_bytes());
575                        p += 4;
576                    }
577                } else {
578                    let freq = cell.centre_frequencies.first().copied().unwrap_or(0);
579                    buf[p..p + 4].copy_from_slice(&freq.to_be_bytes());
580                    p += 4;
581                }
582                let subcell_len = (cell.subcells.len() * 5) as u8;
583                buf[p] = subcell_len;
584                p += 1;
585                for sc in &cell.subcells {
586                    buf[p] = sc.cell_id_extension;
587                    buf[p + 1..p + 5].copy_from_slice(&sc.transposer_frequency.to_be_bytes());
588                    p += 5;
589                }
590            }
591        }
592        Ok(len)
593    }
594}
595
596#[cfg(test)]
597mod tests {
598    use super::*;
599    use crate::descriptors::extension::test_support::*;
600    use crate::descriptors::extension::{ExtensionBody, ExtensionDescriptor};
601
602    #[test]
603    fn t2_bandwidth_roundtrip() {
604        for b in 0..=0xFFu8 {
605            assert_eq!(T2Bandwidth::from_u8(b).to_u8(), b);
606        }
607    }
608
609    #[test]
610    fn t2_guard_interval_roundtrip() {
611        for b in 0..=0xFFu8 {
612            assert_eq!(T2GuardInterval::from_u8(b).to_u8(), b);
613        }
614    }
615
616    #[test]
617    fn t2_transmission_mode_roundtrip() {
618        for b in 0..=0xFFu8 {
619            assert_eq!(T2TransmissionMode::from_u8(b).to_u8(), b);
620        }
621    }
622
623    #[test]
624    fn parse_t2_minimal() {
625        // body = plp + system_id = 3 bytes => no flags block
626        let sel = [0x07, 0x12, 0x34];
627        let bytes = wrap(0x04, &sel);
628        let d = ExtensionDescriptor::parse(&bytes).unwrap();
629        match &d.body {
630            ExtensionBody::T2DeliverySystem(b) => {
631                assert_eq!(b.plp_id, 0x07);
632                assert_eq!(b.t2_system_id, 0x1234);
633                assert_eq!(b.siso_miso, None);
634                assert!(b.cells.is_empty());
635            }
636            other => panic!("expected T2DeliverySystem, got {other:?}"),
637        }
638        round_trip(&d);
639    }
640
641    #[test]
642    fn parse_t2_structured_flags_and_cells() {
643        // prefix + flags block (siso=0, bw=4(10MHz), gi=6(19/256), tm=3(1k), off=0, tfs=1)
644        // + 2 cells: one empty, one with 3 freqs + 2 subcells
645        let b0: u8 = ((0x04 & 0x0F) << 2) | 0x03; // siso_miso=0, bandwidth=4, reserved=11
646        let b1: u8 = (0x06 << 5) | ((0x03 & 0x07) << 2) | (u8::from(false) << 1) | u8::from(true);
647        // cell 1: cell_id=0x1234, freq_len=0, subcell_len=0
648        let cell1 = [0x12, 0x34, 0x00, 0x00];
649        // cell 2: cell_id=0x5678, freq_len=12 (3 freqs), three freqs, subcell_len=10 (2 subcells), two subcells
650        let f1 = 0x01020304u32;
651        let f2 = 0x05060708u32;
652        let f3 = 0x090A0B0Cu32;
653        let sc1_id = 0x10u8;
654        let sc1_freq = 0x11121314u32;
655        let sc2_id = 0x20u8;
656        let sc2_freq = 0x21222324u32;
657        let mut cell2 = Vec::new();
658        cell2.extend_from_slice(&0x5678u16.to_be_bytes());
659        cell2.push(12);
660        cell2.extend_from_slice(&f1.to_be_bytes());
661        cell2.extend_from_slice(&f2.to_be_bytes());
662        cell2.extend_from_slice(&f3.to_be_bytes());
663        cell2.push(10);
664        cell2.push(sc1_id);
665        cell2.extend_from_slice(&sc1_freq.to_be_bytes());
666        cell2.push(sc2_id);
667        cell2.extend_from_slice(&sc2_freq.to_be_bytes());
668        let mut sel = vec![0x07, 0x12, 0x34, b0, b1];
669        sel.extend_from_slice(&cell1);
670        sel.extend_from_slice(&cell2);
671        let bytes = wrap(0x04, &sel);
672        let d = ExtensionDescriptor::parse(&bytes).unwrap();
673        match &d.body {
674            ExtensionBody::T2DeliverySystem(b) => {
675                assert_eq!(b.plp_id, 0x07);
676                assert_eq!(b.t2_system_id, 0x1234);
677                assert_eq!(b.siso_miso, Some(T2SisoMiso::Siso));
678                assert_eq!(b.bandwidth, Some(T2Bandwidth::Mhz10));
679                assert_eq!(b.guard_interval, Some(T2GuardInterval::G19_256));
680                assert_eq!(b.transmission_mode, Some(T2TransmissionMode::Mode1k));
681                assert_eq!(b.other_frequency_flag, Some(false));
682                assert_eq!(b.tfs_flag, Some(true));
683                assert_eq!(b.cells.len(), 2);
684                // cell 0: empty
685                assert_eq!(b.cells[0].cell_id, 0x1234);
686                assert!(b.cells[0].centre_frequencies.is_empty());
687                assert!(b.cells[0].subcells.is_empty());
688                // cell 1: 3 freqs + 2 subcells
689                assert_eq!(b.cells[1].cell_id, 0x5678);
690                assert_eq!(b.cells[1].centre_frequencies, vec![f1, f2, f3]);
691                assert_eq!(b.cells[1].subcells.len(), 2);
692                assert_eq!(b.cells[1].subcells[0].cell_id_extension, sc1_id);
693                assert_eq!(b.cells[1].subcells[0].transposer_frequency, sc1_freq);
694                assert_eq!(b.cells[1].subcells[1].cell_id_extension, sc2_id);
695                assert_eq!(b.cells[1].subcells[1].transposer_frequency, sc2_freq);
696
697                // Accessor tests
698                assert_eq!(
699                    b.cells[1].subcells[0].transposer_frequency_hz(),
700                    u64::from(sc1_freq) * 10
701                );
702                assert_eq!(
703                    b.cells[1].centre_frequencies_hz(),
704                    vec![u64::from(f1) * 10, u64::from(f2) * 10, u64::from(f3) * 10]
705                );
706            }
707            other => panic!("expected T2DeliverySystem, got {other:?}"),
708        }
709        round_trip(&d);
710    }
711
712    #[test]
713    fn tsduck_t2_reference() {
714        let bytes = from_hex(
715            "7f240456789a13cd12340000678a0c075bcd1505e30a780fd22c320a1217ea6406fa0aa9fc59",
716        );
717        let d = ExtensionDescriptor::parse(&bytes).unwrap();
718        match &d.body {
719            ExtensionBody::T2DeliverySystem(b) => {
720                assert_eq!(b.plp_id, 0x56);
721                assert_eq!(b.t2_system_id, 0x789A);
722                assert_eq!(b.siso_miso, Some(T2SisoMiso::Siso));
723                assert_eq!(b.bandwidth, Some(T2Bandwidth::Mhz10));
724                assert_eq!(b.guard_interval, Some(T2GuardInterval::G19_256));
725                assert_eq!(b.transmission_mode, Some(T2TransmissionMode::Mode1k));
726                assert_eq!(b.other_frequency_flag, Some(false));
727                assert_eq!(b.tfs_flag, Some(true));
728                assert_eq!(b.cells.len(), 2);
729
730                assert_eq!(b.cells[0].cell_id, 0x1234);
731                assert!(b.cells[0].centre_frequencies.is_empty());
732                assert!(b.cells[0].subcells.is_empty());
733
734                assert_eq!(b.cells[1].cell_id, 0x678A);
735                assert_eq!(
736                    b.cells[1].centre_frequencies,
737                    vec![0x075BCD15, 0x05E30A78, 0x0FD22C32]
738                );
739                assert_eq!(b.cells[1].subcells.len(), 2);
740                assert_eq!(b.cells[1].subcells[0].cell_id_extension, 0x12);
741                assert_eq!(b.cells[1].subcells[0].transposer_frequency, 0x17EA6406);
742                assert_eq!(b.cells[1].subcells[1].cell_id_extension, 0xFA);
743                assert_eq!(b.cells[1].subcells[1].transposer_frequency, 0x0AA9FC59);
744            }
745            other => panic!("expected T2DeliverySystem, got {other:?}"),
746        }
747        let mut out = vec![0u8; d.serialized_len()];
748        let n = d.serialize_into(&mut out).unwrap();
749        assert_eq!(
750            out[..n],
751            bytes[..],
752            "byte-exact re-serialize for tsduck T2 reference"
753        );
754    }
755}