Skip to main content

dvb_si/descriptors/
cable_delivery_system.rs

1//! Cable Delivery System Descriptor — ETSI EN 300 468 §6.2.13.1 (tag 0x44).
2//!
3//! Carried inside NIT transport_stream_loop second descriptor loop for
4//! DVB-C transponders.
5
6use super::descriptor_body;
7use crate::error::{Error, Result};
8use dvb_common::{Parse, Serialize};
9
10/// Descriptor tag for cable_delivery_system_descriptor.
11pub const TAG: u8 = 0x44;
12const HEADER_LEN: usize = 2;
13const BODY_LEN: u8 = 11;
14
15/// Reserved future use bits (top 12 bits of bytes 6+7 in the descriptor body).
16const RESERVED_FU_MASK: u16 = 0xFFF0;
17
18/// FEC outer coding scheme — ETSI EN 300 468 Table 34.
19#[derive(Debug, Clone, Copy, PartialEq, Eq)]
20#[cfg_attr(feature = "serde", derive(serde::Serialize))]
21#[non_exhaustive]
22pub enum FecOuter {
23    /// Not defined.
24    NotDefined,
25    /// No outer FEC coding.
26    NoOuterFec,
27    /// Reed-Solomon (204, 188).
28    ReedSolomon204_188,
29    /// Reserved / future use.
30    Reserved(u8),
31}
32
33impl FecOuter {
34    /// Human-readable spec label (ETSI EN 300 468 Table 34).
35    #[must_use]
36    pub fn name(self) -> &'static str {
37        match self {
38            Self::NotDefined => "not defined",
39            Self::NoOuterFec => "no outer FEC coding",
40            Self::ReedSolomon204_188 => "Reed-Solomon (204, 188)",
41            Self::Reserved(_) => "reserved",
42        }
43    }
44}
45dvb_common::impl_spec_display!(FecOuter, Reserved);
46
47/// Modulation scheme — ETSI EN 300 468 Table 35.
48#[derive(Debug, Clone, Copy, PartialEq, Eq)]
49#[cfg_attr(feature = "serde", derive(serde::Serialize))]
50#[non_exhaustive]
51pub enum Modulation {
52    /// Not defined.
53    NotDefined,
54    /// 16-QAM.
55    Qam16,
56    /// 32-QAM.
57    Qam32,
58    /// 64-QAM.
59    Qam64,
60    /// 128-QAM.
61    Qam128,
62    /// 256-QAM.
63    Qam256,
64    /// Reserved / future use.
65    Reserved(u8),
66}
67
68impl Modulation {
69    /// Human-readable spec label (ETSI EN 300 468 Table 35).
70    #[must_use]
71    pub fn name(self) -> &'static str {
72        match self {
73            Self::NotDefined => "not defined",
74            Self::Qam16 => "16-QAM",
75            Self::Qam32 => "32-QAM",
76            Self::Qam64 => "64-QAM",
77            Self::Qam128 => "128-QAM",
78            Self::Qam256 => "256-QAM",
79            Self::Reserved(_) => "reserved",
80        }
81    }
82}
83dvb_common::impl_spec_display!(Modulation, Reserved);
84
85/// FEC inner convolutional code rate — ETSI EN 300 468 Table 36.
86#[derive(Debug, Clone, Copy, PartialEq, Eq)]
87#[cfg_attr(feature = "serde", derive(serde::Serialize))]
88#[non_exhaustive]
89pub enum FecInner {
90    /// Not defined.
91    NotDefined,
92    /// Code rate 1/2.
93    Rate1_2,
94    /// Code rate 2/3.
95    Rate2_3,
96    /// Code rate 3/4.
97    Rate3_4,
98    /// Code rate 5/6.
99    Rate5_6,
100    /// Code rate 7/8.
101    Rate7_8,
102    /// Code rate 8/9.
103    Rate8_9,
104    /// Code rate 3/5.
105    Rate3_5,
106    /// Code rate 4/5.
107    Rate4_5,
108    /// Code rate 9/10.
109    Rate9_10,
110    /// No convolutional coding.
111    NoConvCoding,
112    /// Reserved / future use.
113    Reserved(u8),
114}
115
116impl FecInner {
117    /// Every 4-bit value maps to a variant (lossless).
118    #[must_use]
119    pub fn from_u8(v: u8) -> Self {
120        match v {
121            0x00 => FecInner::NotDefined,
122            0x01 => FecInner::Rate1_2,
123            0x02 => FecInner::Rate2_3,
124            0x03 => FecInner::Rate3_4,
125            0x04 => FecInner::Rate5_6,
126            0x05 => FecInner::Rate7_8,
127            0x06 => FecInner::Rate8_9,
128            0x07 => FecInner::Rate3_5,
129            0x08 => FecInner::Rate4_5,
130            0x09 => FecInner::Rate9_10,
131            0x0F => FecInner::NoConvCoding,
132            other => FecInner::Reserved(other),
133        }
134    }
135
136    /// Inverse of `from_u8`; `FecInner::Reserved(v)` emits `v`.
137    #[must_use]
138    pub const fn to_u8(self) -> u8 {
139        match self {
140            FecInner::NotDefined => 0x00,
141            FecInner::Rate1_2 => 0x01,
142            FecInner::Rate2_3 => 0x02,
143            FecInner::Rate3_4 => 0x03,
144            FecInner::Rate5_6 => 0x04,
145            FecInner::Rate7_8 => 0x05,
146            FecInner::Rate8_9 => 0x06,
147            FecInner::Rate3_5 => 0x07,
148            FecInner::Rate4_5 => 0x08,
149            FecInner::Rate9_10 => 0x09,
150            FecInner::NoConvCoding => 0x0F,
151            FecInner::Reserved(v) => v,
152        }
153    }
154
155    /// Human-readable name per Table 36.
156    #[must_use]
157    pub fn name(self) -> &'static str {
158        match self {
159            FecInner::NotDefined => "not defined",
160            FecInner::Rate1_2 => "1/2",
161            FecInner::Rate2_3 => "2/3",
162            FecInner::Rate3_4 => "3/4",
163            FecInner::Rate5_6 => "5/6",
164            FecInner::Rate7_8 => "7/8",
165            FecInner::Rate8_9 => "8/9",
166            FecInner::Rate3_5 => "3/5",
167            FecInner::Rate4_5 => "4/5",
168            FecInner::Rate9_10 => "9/10",
169            FecInner::NoConvCoding => "no convolutional coding",
170            FecInner::Reserved(_) => "reserved",
171        }
172    }
173}
174dvb_common::impl_spec_display!(FecInner, Reserved);
175
176/// Cable Delivery System Descriptor.
177#[derive(Debug, Clone, Copy, PartialEq, Eq)]
178#[cfg_attr(feature = "serde", derive(serde::Serialize))]
179pub struct CableDeliverySystemDescriptor {
180    /// 32-bit BCD frequency in 100 kHz (e.g. 0x03460000 = 346.0000 MHz).
181    pub frequency_bcd: u32,
182    /// FEC outer coding scheme.
183    pub fec_outer: FecOuter,
184    /// Modulation scheme.
185    pub modulation: Modulation,
186    /// 28-bit BCD symbol rate in Msym/s (value stored in low 28 bits of u32).
187    pub symbol_rate_bcd: u32,
188    /// FEC inner code rate.
189    pub fec_inner: FecInner,
190}
191
192impl CableDeliverySystemDescriptor {
193    /// Decode the 32-bit BCD `frequency` to Hz (100 Hz field resolution).
194    /// `None` if the BCD nibbles are out of range.
195    ///
196    /// e.g. `0x0346_0000` → `346_000_000` Hz (346.0000 MHz).
197    #[must_use]
198    pub fn frequency_hz(&self) -> Option<u64> {
199        dvb_common::bcd::bcd_to_decimal(u64::from(self.frequency_bcd), 8).map(|v| v * 100)
200    }
201
202    /// Set `frequency` from Hz, encoding to the 8-digit BCD field at the field's
203    /// 100 Hz resolution (finer precision is truncated).
204    ///
205    /// # Errors
206    /// [`ValueOutOfRange`](crate::Error::ValueOutOfRange) on overflow of
207    /// the 8-digit BCD field.
208    pub fn set_frequency_hz(&mut self, hz: u64) -> crate::Result<()> {
209        self.frequency_bcd =
210            super::encode_bcd_field(hz / 100, 8, "CableDeliverySystemDescriptor::frequency")?
211                as u32;
212        Ok(())
213    }
214
215    /// Decode the 28-bit BCD `symbol_rate` to symbols/second (100 sym/s
216    /// resolution). `None` if the BCD nibbles are out of range.
217    #[must_use]
218    pub fn symbol_rate_sps(&self) -> Option<u64> {
219        dvb_common::bcd::bcd_to_decimal(u64::from(self.symbol_rate_bcd), 7).map(|v| v * 100)
220    }
221
222    /// Set `symbol_rate` from symbols/second (100 sym/s field resolution).
223    ///
224    /// # Errors
225    /// [`ValueOutOfRange`](crate::Error::ValueOutOfRange) on overflow of
226    /// the 7-digit BCD field.
227    pub fn set_symbol_rate_sps(&mut self, sps: u64) -> crate::Result<()> {
228        self.symbol_rate_bcd =
229            super::encode_bcd_field(sps / 100, 7, "CableDeliverySystemDescriptor::symbol_rate")?
230                as u32;
231        Ok(())
232    }
233}
234
235fn parse_fec_outer(raw: u8) -> FecOuter {
236    match raw {
237        0x00 => FecOuter::NotDefined,
238        0x01 => FecOuter::NoOuterFec,
239        0x02 => FecOuter::ReedSolomon204_188,
240        other => FecOuter::Reserved(other),
241    }
242}
243
244fn parse_modulation(raw: u8) -> Modulation {
245    match raw {
246        0x00 => Modulation::NotDefined,
247        0x01 => Modulation::Qam16,
248        0x02 => Modulation::Qam32,
249        0x03 => Modulation::Qam64,
250        0x04 => Modulation::Qam128,
251        0x05 => Modulation::Qam256,
252        other => Modulation::Reserved(other),
253    }
254}
255
256fn parse_fec_inner(raw: u8) -> FecInner {
257    FecInner::from_u8(raw)
258}
259
260fn serialize_fec_outer(fec: FecOuter) -> u8 {
261    match fec {
262        FecOuter::NotDefined => 0x00,
263        FecOuter::NoOuterFec => 0x01,
264        FecOuter::ReedSolomon204_188 => 0x02,
265        FecOuter::Reserved(v) => v,
266    }
267}
268
269fn serialize_modulation(m: Modulation) -> u8 {
270    match m {
271        Modulation::NotDefined => 0x00,
272        Modulation::Qam16 => 0x01,
273        Modulation::Qam32 => 0x02,
274        Modulation::Qam64 => 0x03,
275        Modulation::Qam128 => 0x04,
276        Modulation::Qam256 => 0x05,
277        Modulation::Reserved(v) => v,
278    }
279}
280
281fn serialize_fec_inner(fec: FecInner) -> u8 {
282    fec.to_u8()
283}
284
285impl<'a> Parse<'a> for CableDeliverySystemDescriptor {
286    type Error = crate::error::Error;
287    fn parse(bytes: &'a [u8]) -> Result<Self> {
288        let body = descriptor_body(
289            bytes,
290            TAG,
291            "CableDeliverySystemDescriptor",
292            "unexpected tag for cable_delivery_system_descriptor",
293        )?;
294        if body.len() != BODY_LEN as usize {
295            return Err(Error::InvalidDescriptor {
296                tag: TAG,
297                reason: "body length must equal 11",
298            });
299        }
300
301        let (hdr, _) = body
302            .split_first_chunk::<11>()
303            .ok_or(Error::InvalidDescriptor {
304                tag: TAG,
305                reason: "body length must equal 11",
306            })?;
307
308        let frequency_bcd = u32::from_be_bytes([hdr[0], hdr[1], hdr[2], hdr[3]]);
309
310        let bytes_4_5 = u16::from_be_bytes([hdr[4], hdr[5]]);
311        let fec_outer_raw = (bytes_4_5 & !RESERVED_FU_MASK) as u8;
312
313        let modulation_byte = hdr[6];
314
315        let spec_value = u32::from_be_bytes([0, hdr[7], hdr[8], hdr[9]]);
316        let symbol_rate_bcd = (spec_value << 4) | ((hdr[10] >> 4) & 0x0F) as u32;
317
318        let fec_inner_raw = hdr[10] & 0x0F;
319
320        Ok(Self {
321            frequency_bcd,
322            fec_outer: parse_fec_outer(fec_outer_raw),
323            modulation: parse_modulation(modulation_byte),
324            symbol_rate_bcd,
325            fec_inner: parse_fec_inner(fec_inner_raw),
326        })
327    }
328}
329
330impl Serialize for CableDeliverySystemDescriptor {
331    type Error = crate::error::Error;
332    fn serialized_len(&self) -> usize {
333        HEADER_LEN + BODY_LEN as usize
334    }
335
336    fn serialize_into(&self, buf: &mut [u8]) -> Result<usize> {
337        let len = self.serialized_len();
338        if buf.len() < len {
339            return Err(Error::OutputBufferTooSmall {
340                need: len,
341                have: buf.len(),
342            });
343        }
344
345        buf[0] = TAG;
346        buf[1] = BODY_LEN;
347
348        buf[2..6].copy_from_slice(&self.frequency_bcd.to_be_bytes());
349
350        let reserved_fu = RESERVED_FU_MASK;
351        let fec_outer_byte = reserved_fu | serialize_fec_outer(self.fec_outer) as u16;
352        let [fu_hi, fec_lo] = fec_outer_byte.to_be_bytes();
353        buf[6] = fu_hi;
354        buf[7] = fec_lo;
355
356        buf[8] = serialize_modulation(self.modulation);
357
358        let spec_value = self.symbol_rate_bcd >> 4;
359        buf[9] = (spec_value >> 16) as u8;
360        buf[10] = (spec_value >> 8) as u8;
361        buf[11] = spec_value as u8;
362
363        buf[12] = ((self.symbol_rate_bcd & 0x0F) as u8) << 4 | serialize_fec_inner(self.fec_inner);
364
365        Ok(len)
366    }
367}
368impl<'a> crate::traits::DescriptorDef<'a> for CableDeliverySystemDescriptor {
369    const TAG: u8 = TAG;
370    const NAME: &'static str = "CABLE_DELIVERY_SYSTEM";
371}
372
373#[cfg(test)]
374mod tests {
375    use super::*;
376
377    #[test]
378    fn fec_inner_from_u8_to_u8_roundtrip() {
379        for b in 0..=0xFFu8 {
380            assert_eq!(
381                FecInner::from_u8(b).to_u8(),
382                b,
383                "round-trip fail for {b:#04x}"
384            );
385        }
386    }
387
388    #[test]
389    fn parse_extracts_frequency_bcd() {
390        let raw: [u8; 13] = [
391            TAG, BODY_LEN, 0x03, 0x46, 0x00, 0x00, 0xFF, 0xF1, 0x05, 0x00, 0x00, 0x00, 0x03,
392        ];
393        let d = CableDeliverySystemDescriptor::parse(&raw).unwrap();
394        assert_eq!(d.frequency_bcd, 0x03460000);
395    }
396
397    #[test]
398    fn parse_extracts_modulation_qam256() {
399        let raw: [u8; 13] = [
400            TAG, BODY_LEN, 0x00, 0x00, 0x00, 0x00, 0xFF, 0xF0, 0x05, 0x00, 0x00, 0x00, 0x00,
401        ];
402        let d = CableDeliverySystemDescriptor::parse(&raw).unwrap();
403        assert_eq!(d.modulation, Modulation::Qam256);
404    }
405
406    #[test]
407    fn parse_extracts_fec_outer_reed_solomon() {
408        let raw: [u8; 13] = [
409            TAG, BODY_LEN, 0x00, 0x00, 0x00, 0x00, 0xFF, 0xF2, 0x00, 0x00, 0x00, 0x00, 0x00,
410        ];
411        let d = CableDeliverySystemDescriptor::parse(&raw).unwrap();
412        assert_eq!(d.fec_outer, FecOuter::ReedSolomon204_188);
413    }
414
415    #[test]
416    fn parse_extracts_fec_inner_rate_3_4() {
417        let raw: [u8; 13] = [
418            TAG, BODY_LEN, 0x00, 0x00, 0x00, 0x00, 0xFF, 0xF0, 0x00, 0x00, 0x00, 0x00, 0x03,
419        ];
420        let d = CableDeliverySystemDescriptor::parse(&raw).unwrap();
421        assert_eq!(d.fec_inner, FecInner::Rate3_4);
422    }
423
424    #[test]
425    fn parse_extracts_symbol_rate_bcd() {
426        let raw: [u8; 13] = [
427            TAG, BODY_LEN, 0x00, 0x00, 0x00, 0x00, 0xFF, 0xF0, 0x00, 0x06, 0x87, 0x50, 0x00,
428        ];
429        let d = CableDeliverySystemDescriptor::parse(&raw).unwrap();
430        assert_eq!(d.symbol_rate_bcd, 0x0687500);
431    }
432
433    #[test]
434    fn parse_preserves_reserved_modulation_in_reserved_variant() {
435        let raw: [u8; 13] = [
436            TAG, BODY_LEN, 0x00, 0x00, 0x00, 0x00, 0xFF, 0xF0, 0x0A, 0x00, 0x00, 0x00, 0x00,
437        ];
438        let d = CableDeliverySystemDescriptor::parse(&raw).unwrap();
439        assert_eq!(d.modulation, Modulation::Reserved(0x0A));
440    }
441
442    #[test]
443    fn parse_rejects_wrong_tag() {
444        let raw: [u8; 13] = [
445            0x5B, BODY_LEN, 0x00, 0x00, 0x00, 0x00, 0xFF, 0xF0, 0x00, 0x00, 0x00, 0x00, 0x00,
446        ];
447        assert!(matches!(
448            CableDeliverySystemDescriptor::parse(&raw).unwrap_err(),
449            Error::InvalidDescriptor { tag: 0x5B, .. }
450        ));
451    }
452
453    #[test]
454    fn parse_rejects_wrong_length() {
455        // Declared length (12) exceeds available bytes → descriptor_body floors first.
456        let raw: [u8; 13] = [
457            TAG, 12, 0x00, 0x00, 0x00, 0x00, 0xFF, 0xF0, 0x00, 0x00, 0x00, 0x00, 0x00,
458        ];
459        let err = CableDeliverySystemDescriptor::parse(&raw).unwrap_err();
460        assert!(matches!(err, Error::BufferTooShort { .. }));
461
462        // Declared length fits the buffer but is not 11 → the body-length check bites.
463        let raw: [u8; 12] = [TAG, 10, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0];
464        let err = CableDeliverySystemDescriptor::parse(&raw).unwrap_err();
465        assert!(matches!(
466            err,
467            Error::InvalidDescriptor {
468                tag: TAG,
469                reason: "body length must equal 11"
470            }
471        ));
472    }
473
474    #[test]
475    fn serialize_round_trip() {
476        let d = CableDeliverySystemDescriptor {
477            frequency_bcd: 0x03460000,
478            fec_outer: FecOuter::ReedSolomon204_188,
479            modulation: Modulation::Qam256,
480            symbol_rate_bcd: 0x0687500,
481            fec_inner: FecInner::Rate3_4,
482        };
483        let mut buf = vec![0u8; d.serialized_len()];
484        d.serialize_into(&mut buf).unwrap();
485        let parsed = CableDeliverySystemDescriptor::parse(&buf).unwrap();
486        assert_eq!(parsed, d);
487    }
488
489    #[test]
490    fn enum_round_trip_covers_every_defined_variant() {
491        for fec_outer in [
492            FecOuter::NotDefined,
493            FecOuter::NoOuterFec,
494            FecOuter::ReedSolomon204_188,
495        ] {
496            let v = serialize_fec_outer(fec_outer);
497            assert_eq!(parse_fec_outer(v), fec_outer);
498        }
499
500        for mod_ in [
501            Modulation::NotDefined,
502            Modulation::Qam16,
503            Modulation::Qam32,
504            Modulation::Qam64,
505            Modulation::Qam128,
506            Modulation::Qam256,
507        ] {
508            let v = serialize_modulation(mod_);
509            assert_eq!(parse_modulation(v), mod_);
510        }
511
512        for fec_inner in [
513            FecInner::NotDefined,
514            FecInner::Rate1_2,
515            FecInner::Rate2_3,
516            FecInner::Rate3_4,
517            FecInner::Rate5_6,
518            FecInner::Rate7_8,
519            FecInner::Rate8_9,
520            FecInner::Rate3_5,
521            FecInner::Rate4_5,
522            FecInner::Rate9_10,
523            FecInner::NoConvCoding,
524        ] {
525            let v = serialize_fec_inner(fec_inner);
526            assert_eq!(parse_fec_inner(v), fec_inner);
527        }
528    }
529}