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