dvb-si 12.0.1

ETSI EN 300 468 DVB Service Information parser + builder. MPEG-2 PSI included.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
//! C2 Delivery System Descriptor — ETSI EN 300 468 §6.4.6.1 (tag_extension 0x0D).
use super::*;
use alloc::vec::Vec;

impl ExtensionBodyDef<'_> for C2DeliverySystem {
    const TAG_EXTENSION: u8 = 0x0D;
    const NAME: &'static str = "C2_DELIVERY_SYSTEM";
}

/// C2 system tuning frequency type — ETSI EN 300 468 Table 116.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[cfg_attr(feature = "serde", derive(serde::Serialize))]
#[non_exhaustive]
pub enum C2TuningFrequencyType {
    /// 0b00 — Data Slice tuning frequency.
    DataSliceTuningFrequency,
    /// 0b01 — C2 system centre frequency.
    C2SystemCentreFrequency,
    /// 0b10 — Initial tuning position for a (dependent) Static Data Slice.
    InitialTuningPositionStaticDataSlice,
    /// Reserved / future use.
    Reserved(u8),
}

impl C2TuningFrequencyType {
    #[must_use]
    /// Construct from a raw `u8`; every value maps to a variant (total, lossless).
    pub fn from_u8(v: u8) -> Self {
        match v {
            0 => C2TuningFrequencyType::DataSliceTuningFrequency,
            1 => C2TuningFrequencyType::C2SystemCentreFrequency,
            2 => C2TuningFrequencyType::InitialTuningPositionStaticDataSlice,
            other => C2TuningFrequencyType::Reserved(other),
        }
    }

    #[must_use]
    /// Inverse of `from_u8`; `Self::Reserved` emits its stored value.
    pub const fn to_u8(self) -> u8 {
        match self {
            C2TuningFrequencyType::DataSliceTuningFrequency => 0,
            C2TuningFrequencyType::C2SystemCentreFrequency => 1,
            C2TuningFrequencyType::InitialTuningPositionStaticDataSlice => 2,
            C2TuningFrequencyType::Reserved(v) => v,
        }
    }

    #[must_use]
    /// Human-readable spec name per Table 116.
    pub fn name(self) -> &'static str {
        match self {
            C2TuningFrequencyType::DataSliceTuningFrequency => "Data Slice tuning frequency",
            C2TuningFrequencyType::C2SystemCentreFrequency => "C2 system centre frequency",
            C2TuningFrequencyType::InitialTuningPositionStaticDataSlice => {
                "initial tuning position for a Static Data Slice"
            }
            C2TuningFrequencyType::Reserved(_) => "reserved",
        }
    }
}
broadcast_common::impl_spec_display!(C2TuningFrequencyType, Reserved);

/// Active OFDM symbol duration — ETSI EN 300 468 Table 117.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[cfg_attr(feature = "serde", derive(serde::Serialize))]
#[non_exhaustive]
pub enum ActiveOfdmSymbolDuration {
    /// 448 µs (4k FFT mode for 8 MHz CATV systems).
    Us448,
    /// 597.33 µs (4k FFT mode for 6 MHz CATV systems).
    Us597_33,
    /// Reserved / future use.
    Reserved(u8),
}

impl ActiveOfdmSymbolDuration {
    #[must_use]
    /// Construct from a raw `u8`; every value maps to a variant (total, lossless).
    pub fn from_u8(v: u8) -> Self {
        match v {
            0 => ActiveOfdmSymbolDuration::Us448,
            1 => ActiveOfdmSymbolDuration::Us597_33,
            other => ActiveOfdmSymbolDuration::Reserved(other),
        }
    }

    #[must_use]
    /// Inverse of `from_u8`; `Self::Reserved` emits its stored value.
    pub const fn to_u8(self) -> u8 {
        match self {
            ActiveOfdmSymbolDuration::Us448 => 0,
            ActiveOfdmSymbolDuration::Us597_33 => 1,
            ActiveOfdmSymbolDuration::Reserved(v) => v,
        }
    }

    #[must_use]
    /// Human-readable spec name per the governing Table.
    pub fn name(self) -> &'static str {
        match self {
            ActiveOfdmSymbolDuration::Us448 => "448 µs (4k FFT, 8 MHz)",
            ActiveOfdmSymbolDuration::Us597_33 => "597.33 µs (4k FFT, 6 MHz)",
            ActiveOfdmSymbolDuration::Reserved(_) => "reserved",
        }
    }
}
broadcast_common::impl_spec_display!(ActiveOfdmSymbolDuration, Reserved);

/// C2 guard interval — ETSI EN 300 468 Table 118.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[cfg_attr(feature = "serde", derive(serde::Serialize))]
#[non_exhaustive]
pub enum C2GuardInterval {
    /// 1/128.
    G1_128,
    /// 1/64.
    G1_64,
    /// Reserved / future use.
    Reserved(u8),
}

impl C2GuardInterval {
    #[must_use]
    /// Construct from a raw `u8`; every value maps to a variant (total, lossless).
    pub fn from_u8(v: u8) -> Self {
        match v {
            0 => C2GuardInterval::G1_128,
            1 => C2GuardInterval::G1_64,
            other => C2GuardInterval::Reserved(other),
        }
    }

    #[must_use]
    /// Inverse of `from_u8`; `Self::Reserved` emits its stored value.
    pub const fn to_u8(self) -> u8 {
        match self {
            C2GuardInterval::G1_128 => 0,
            C2GuardInterval::G1_64 => 1,
            C2GuardInterval::Reserved(v) => v,
        }
    }

    #[must_use]
    /// Human-readable spec name per the governing Table.
    pub fn name(self) -> &'static str {
        match self {
            C2GuardInterval::G1_128 => "1/128",
            C2GuardInterval::G1_64 => "1/64",
            C2GuardInterval::Reserved(_) => "reserved",
        }
    }
}
broadcast_common::impl_spec_display!(C2GuardInterval, Reserved);

/// C2_delivery_system body (Table 115) — fully typed, fixed 7 bytes with no
/// reserved bits in any edition (audit §6.1 class E). Bytes after the 7 defined
/// ones (non-conformant, tolerated) are kept in [`trailing`](Self::trailing).
#[derive(Debug, Clone, PartialEq, Eq)]
#[cfg_attr(feature = "serde", derive(serde::Serialize))]
#[non_exhaustive]
pub struct C2DeliverySystem {
    /// plp_id(8).
    pub plp_id: u8,
    /// data_slice_id(8).
    pub data_slice_id: u8,
    /// C2_System_tuning_frequency(32).
    pub c2_system_tuning_frequency: u32,
    /// C2_System_tuning_frequency_type(2) — Table 116.
    pub c2_system_tuning_frequency_type: C2TuningFrequencyType,
    /// active_OFDM_symbol_duration(3) — Table 117.
    pub active_ofdm_symbol_duration: ActiveOfdmSymbolDuration,
    /// guard_interval(3) — Table 118.
    pub guard_interval: C2GuardInterval,
    /// Body bytes after the 7 defined ones; empty for a conformant
    /// descriptor, re-emitted verbatim otherwise.
    pub trailing: Vec<u8>,
}

impl C2DeliverySystem {
    /// Build a body (no trailing bytes).
    #[must_use]
    pub const fn new(
        plp_id: u8,
        data_slice_id: u8,
        c2_system_tuning_frequency: u32,
        c2_system_tuning_frequency_type: C2TuningFrequencyType,
        active_ofdm_symbol_duration: ActiveOfdmSymbolDuration,
        guard_interval: C2GuardInterval,
    ) -> Self {
        Self {
            plp_id,
            data_slice_id,
            c2_system_tuning_frequency,
            c2_system_tuning_frequency_type,
            active_ofdm_symbol_duration,
            guard_interval,
            trailing: Vec::new(),
        }
    }
}

impl<'a> Parse<'a> for C2DeliverySystem {
    type Error = crate::error::Error;
    fn parse(sel: &'a [u8]) -> Result<Self> {
        if sel.len() < C2_LEN {
            return Err(Error::BufferTooShort {
                need: C2_LEN,
                have: sel.len(),
                what: "C2_delivery_system body",
            });
        }
        let packed = sel[6];
        let (freq_bytes, _) = sel[2..]
            .split_first_chunk::<4>()
            .ok_or(Error::BufferTooShort {
                need: C2_LEN,
                have: sel.len(),
                what: "C2_delivery_system body",
            })?;
        Ok(C2DeliverySystem {
            plp_id: sel[0],
            data_slice_id: sel[1],
            c2_system_tuning_frequency: u32::from_be_bytes(*freq_bytes),
            c2_system_tuning_frequency_type: C2TuningFrequencyType::from_u8(packed >> 6),
            active_ofdm_symbol_duration: ActiveOfdmSymbolDuration::from_u8((packed >> 3) & 0x07),
            guard_interval: C2GuardInterval::from_u8(packed & 0x07),
            trailing: sel[C2_LEN..].to_vec(),
        })
    }
}

impl Serialize for C2DeliverySystem {
    type Error = crate::error::Error;
    fn serialized_len(&self) -> usize {
        C2_LEN + self.trailing.len()
    }
    fn serialize_into(&self, buf: &mut [u8]) -> Result<usize> {
        let len = self.serialized_len();
        if buf.len() < len {
            return Err(Error::OutputBufferTooSmall {
                need: len,
                have: buf.len(),
            });
        }
        buf[0] = self.plp_id;
        buf[1] = self.data_slice_id;
        buf[2..6].copy_from_slice(&self.c2_system_tuning_frequency.to_be_bytes());
        buf[6] = (broadcast_common::len::fit_mask(
            self.c2_system_tuning_frequency_type.to_u8(),
            0x03,
            "c2_system_tuning_frequency_type",
        )? << 6)
            | (broadcast_common::len::fit_mask(
                self.active_ofdm_symbol_duration.to_u8(),
                0x07,
                "active_ofdm_symbol_duration",
            )? << 3)
            | broadcast_common::len::fit_mask(self.guard_interval.to_u8(), 0x07, "guard_interval")?;
        buf[C2_LEN..len].copy_from_slice(&self.trailing);
        Ok(len)
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::descriptors::extension::test_support::*;
    use crate::descriptors::extension::{ExtensionBody, ExtensionDescriptor};

    #[test]
    fn c2_tuning_frequency_type_roundtrip() {
        for b in 0..=0xFFu8 {
            assert_eq!(C2TuningFrequencyType::from_u8(b).to_u8(), b);
        }
    }

    #[test]
    fn c2_tuning_frequency_type_name() {
        assert_eq!(
            C2TuningFrequencyType::DataSliceTuningFrequency.name(),
            "Data Slice tuning frequency"
        );
        assert_eq!(
            C2TuningFrequencyType::C2SystemCentreFrequency.name(),
            "C2 system centre frequency"
        );
        assert_eq!(
            C2TuningFrequencyType::InitialTuningPositionStaticDataSlice.name(),
            "initial tuning position for a Static Data Slice"
        );
        assert_eq!(C2TuningFrequencyType::Reserved(3).name(), "reserved");
    }

    #[test]
    fn active_ofdm_symbol_duration_roundtrip() {
        for b in 0..=0xFFu8 {
            assert_eq!(ActiveOfdmSymbolDuration::from_u8(b).to_u8(), b);
        }
    }

    #[test]
    fn c2_guard_interval_roundtrip() {
        for b in 0..=0xFFu8 {
            assert_eq!(C2GuardInterval::from_u8(b).to_u8(), b);
        }
    }

    #[test]
    fn parse_c2_delivery_system() {
        let packed = (0x01u8 << 3) | 0x01;
        let sel = [0x05, 0x09, 0x12, 0x34, 0x56, 0x78, packed];
        let bytes = wrap(0x0D, &sel);
        let d = ExtensionDescriptor::parse(&bytes).unwrap();
        match &d.body {
            ExtensionBody::C2DeliverySystem(b) => {
                assert_eq!(b.plp_id, 0x05);
                assert_eq!(b.data_slice_id, 0x09);
                assert_eq!(b.c2_system_tuning_frequency, 0x1234_5678);
                assert_eq!(
                    b.c2_system_tuning_frequency_type,
                    C2TuningFrequencyType::DataSliceTuningFrequency
                );
                assert_eq!(
                    b.active_ofdm_symbol_duration,
                    ActiveOfdmSymbolDuration::Us597_33
                );
                assert_eq!(b.guard_interval, C2GuardInterval::G1_64);
            }
            other => panic!("expected C2DeliverySystem, got {other:?}"),
        }
        round_trip(&d);
    }

    #[test]
    fn parse_c2_delivery_system_centre_frequency() {
        let packed = 0x01u8 << 6;
        let sel = [0x05, 0x09, 0x12, 0x34, 0x56, 0x78, packed];
        let bytes = wrap(0x0D, &sel);
        let d = ExtensionDescriptor::parse(&bytes).unwrap();
        match &d.body {
            ExtensionBody::C2DeliverySystem(b) => {
                assert_eq!(
                    b.c2_system_tuning_frequency_type,
                    C2TuningFrequencyType::C2SystemCentreFrequency
                );
            }
            other => panic!("expected C2DeliverySystem, got {other:?}"),
        }
        round_trip(&d);
    }

    #[test]
    fn parse_c2_delivery_system_initial_tuning() {
        let packed = 0x02u8 << 6;
        let sel = [0x05, 0x09, 0x12, 0x34, 0x56, 0x78, packed];
        let bytes = wrap(0x0D, &sel);
        let d = ExtensionDescriptor::parse(&bytes).unwrap();
        match &d.body {
            ExtensionBody::C2DeliverySystem(b) => {
                assert_eq!(
                    b.c2_system_tuning_frequency_type,
                    C2TuningFrequencyType::InitialTuningPositionStaticDataSlice
                );
            }
            other => panic!("expected C2DeliverySystem, got {other:?}"),
        }
        round_trip(&d);
    }

    #[test]
    fn parse_c2_delivery_system_reserved_values() {
        let packed = (0x03u8 << 6) | (0x07u8 << 3) | 0x07;
        let sel = [0x00, 0x00, 0x00, 0x00, 0x00, 0x00, packed];
        let bytes = wrap(0x0D, &sel);
        let d = ExtensionDescriptor::parse(&bytes).unwrap();
        match &d.body {
            ExtensionBody::C2DeliverySystem(b) => {
                assert_eq!(
                    b.c2_system_tuning_frequency_type,
                    C2TuningFrequencyType::Reserved(3)
                );
                assert_eq!(
                    b.active_ofdm_symbol_duration,
                    ActiveOfdmSymbolDuration::Reserved(7)
                );
                assert_eq!(b.guard_interval, C2GuardInterval::Reserved(7));
            }
            other => panic!("expected C2DeliverySystem, got {other:?}"),
        }
        round_trip(&d);
    }

    /// Bytes past the 7 defined ones are kept and re-emitted.
    #[test]
    fn trailing_bytes_preserved() {
        let sel = [0x05, 0x09, 0x12, 0x34, 0x56, 0x78, 0x41, 0xDE, 0xAD];
        let bytes = wrap(0x0D, &sel);
        let d = ExtensionDescriptor::parse(&bytes).unwrap();
        match &d.body {
            ExtensionBody::C2DeliverySystem(b) => assert_eq!(b.trailing, [0xDE, 0xAD]),
            other => panic!("expected C2DeliverySystem, got {other:?}"),
        }
        let mut buf = vec![0u8; d.serialized_len()];
        d.serialize_into(&mut buf).unwrap();
        assert_eq!(buf, bytes);
    }
}