Skip to main content

dvb_si/descriptors/
frequency_list.rs

1//! Frequency List Descriptor — ETSI EN 300 468 §6.2.17 (tag 0x62).
2//!
3//! Carried inside the NIT's transport_stream_loop second descriptor loop.
4//! Enumerates alternative centre frequencies on which the TS can be found,
5//! for handover when coverage changes.
6
7use super::descriptor_body;
8use crate::error::{Error, Result};
9use dvb_common::{Parse, Serialize};
10
11/// Descriptor tag for frequency_list_descriptor.
12pub const TAG: u8 = 0x62;
13/// Length of the header (tag byte + length byte).
14pub const HEADER_LEN: usize = 2;
15/// Length of the coding_type byte inside the descriptor body.
16pub const CODING_BYTE_LEN: usize = 1;
17/// Length of a single frequency entry in bytes.
18pub const ENTRY_LEN: usize = 4;
19/// Mask for the coding_type bits (bottom 2 bits); the top 6 bits are reserved.
20pub const CODING_TYPE_MASK: u8 = 0x03;
21/// Reserved bits (top 6 of the coding byte). Ignored on parse, set to 1 on serialize.
22pub const RESERVED_BITS_MASK: u8 = 0xFC;
23
24/// Coding type selects the interpretation of each 4-byte frequency entry.
25#[derive(Debug, Clone, Copy, PartialEq, Eq)]
26#[cfg_attr(feature = "serde", derive(serde::Serialize))]
27pub enum CodingType {
28    /// Not defined (coding_type = 0b00).
29    Undefined,
30    /// Satellite — 8 BCD digits, 10 kHz resolution (§6.2.13.2).
31    Satellite,
32    /// Cable — 8 BCD digits, 100 Hz resolution (§6.2.13.3).
33    Cable,
34    /// Terrestrial — binary uimsbf 32-bit, 10 Hz resolution (§6.2.13.4).
35    Terrestrial,
36}
37
38impl CodingType {
39    /// Human-readable spec label (ETSI EN 300 468 §6.2.17).
40    #[must_use]
41    pub fn name(self) -> &'static str {
42        match self {
43            Self::Undefined => "not defined",
44            Self::Satellite => "satellite",
45            Self::Cable => "cable",
46            Self::Terrestrial => "terrestrial",
47        }
48    }
49}
50dvb_common::impl_spec_display!(CodingType);
51
52/// Frequency List Descriptor.
53#[derive(Debug, Clone, PartialEq, Eq)]
54#[cfg_attr(feature = "serde", derive(serde::Serialize))]
55pub struct FrequencyListDescriptor {
56    /// Interpretation of every `centre_frequencies_bcd` entry.
57    pub coding_type: CodingType,
58    /// Raw 4-byte centre_frequency entries in wire order. Interpretation
59    /// depends on `coding_type`: BCD for Satellite/Cable, binary for Terrestrial.
60    pub centre_frequencies_bcd: Vec<[u8; 4]>,
61}
62
63impl FrequencyListDescriptor {
64    /// Hz per BCD-decoded unit for Satellite or Cable, or `None` for
65    /// Undefined / Terrestrial (Terrestrial uses binary encoding, not BCD).
66    fn hz_per_unit_bcd(&self) -> Option<u64> {
67        match self.coding_type {
68            CodingType::Satellite => Some(10_000),
69            CodingType::Cable => Some(100),
70            CodingType::Terrestrial | CodingType::Undefined => None,
71        }
72    }
73
74    /// Decode every `centre_frequencies_bcd` entry to Hz, interpreted per
75    /// `coding_type`. Each element is `None` if `coding_type` is `Undefined`
76    /// or a BCD nibble is invalid (Satellite/Cable).
77    #[must_use]
78    pub fn centre_frequencies_hz(&self) -> Vec<Option<u64>> {
79        match self.coding_type {
80            CodingType::Satellite | CodingType::Cable => {
81                let scale = self.hz_per_unit_bcd().unwrap();
82                self.centre_frequencies_bcd
83                    .iter()
84                    .map(|b| {
85                        let value =
86                            dvb_common::bcd::bcd_to_decimal(u64::from(u32::from_be_bytes(*b)), 8)?;
87                        Some(value * scale)
88                    })
89                    .collect()
90            }
91            CodingType::Terrestrial => self
92                .centre_frequencies_bcd
93                .iter()
94                .map(|b| Some(u64::from(u32::from_be_bytes(*b)) * 10))
95                .collect(),
96            CodingType::Undefined => self.centre_frequencies_bcd.iter().map(|_| None).collect(),
97        }
98    }
99
100    /// Replace the entries by encoding each Hz value per `coding_type`
101    /// (values truncate to the field's resolution).
102    ///
103    /// # Errors
104    /// [`ValueOutOfRange`](crate::Error::ValueOutOfRange) if `coding_type`
105    /// is `Undefined`, a BCD value exceeds 8 digits (Satellite/Cable), or
106    /// a binary value exceeds 32 bits (Terrestrial).
107    pub fn set_centre_frequencies_hz(&mut self, frequencies_hz: &[u64]) -> crate::Result<()> {
108        match self.coding_type {
109            CodingType::Satellite | CodingType::Cable => {
110                let scale = self
111                    .hz_per_unit_bcd()
112                    .ok_or(crate::Error::ValueOutOfRange {
113                        field: "FrequencyListDescriptor::centre_frequency",
114                        reason: "coding_type is Undefined; cannot encode frequencies",
115                    })?;
116                let mut out = Vec::with_capacity(frequencies_hz.len());
117                for &hz in frequencies_hz {
118                    let bcd = super::encode_bcd_field(
119                        hz / scale,
120                        8,
121                        "FrequencyListDescriptor::centre_frequency",
122                    )?;
123                    out.push((bcd as u32).to_be_bytes());
124                }
125                self.centre_frequencies_bcd = out;
126                Ok(())
127            }
128            CodingType::Terrestrial => {
129                let mut out = Vec::with_capacity(frequencies_hz.len());
130                for &hz in frequencies_hz {
131                    let units = hz / 10;
132                    if units > u64::from(u32::MAX) {
133                        return Err(Error::ValueOutOfRange {
134                            field: "frequency_list centre_frequency",
135                            reason: "terrestrial frequency exceeds the 32-bit (×10 Hz) wire field",
136                        });
137                    }
138                    out.push((units as u32).to_be_bytes());
139                }
140                self.centre_frequencies_bcd = out;
141                Ok(())
142            }
143            CodingType::Undefined => Err(crate::Error::ValueOutOfRange {
144                field: "FrequencyListDescriptor::centre_frequency",
145                reason: "coding_type is Undefined; cannot encode frequencies",
146            }),
147        }
148    }
149}
150
151impl<'a> Parse<'a> for FrequencyListDescriptor {
152    type Error = crate::error::Error;
153    fn parse(bytes: &'a [u8]) -> Result<Self> {
154        let body = descriptor_body(bytes, TAG, "FrequencyListDescriptor", "expected tag 0x62")?;
155
156        if body.len() < CODING_BYTE_LEN {
157            return Err(Error::InvalidDescriptor {
158                tag: TAG,
159                reason: "body too short (need at least coding_type byte)",
160            });
161        }
162
163        if (body.len() - CODING_BYTE_LEN) % ENTRY_LEN != 0 {
164            return Err(Error::InvalidDescriptor {
165                tag: TAG,
166                reason: "body length minus coding byte must be multiple of 4",
167            });
168        }
169
170        let coding_byte = body[0];
171        // Top 6 bits are reserved_future_use — ignored on parse
172        // (EN 300 468 §5.1: decoders shall ignore reserved bits).
173        let coding_type_value = coding_byte & CODING_TYPE_MASK;
174        let coding_type = match coding_type_value {
175            0b00 => CodingType::Undefined,
176            0b01 => CodingType::Satellite,
177            0b10 => CodingType::Cable,
178            _ => CodingType::Terrestrial,
179        };
180
181        let entry_count = (body.len() - CODING_BYTE_LEN) / ENTRY_LEN;
182        let mut centre_frequencies_bcd = Vec::with_capacity(entry_count);
183
184        let mut offset = CODING_BYTE_LEN;
185        for _ in 0..entry_count {
186            let mut entry = [0u8; ENTRY_LEN];
187            entry.copy_from_slice(&body[offset..offset + ENTRY_LEN]);
188            centre_frequencies_bcd.push(entry);
189            offset += ENTRY_LEN;
190        }
191
192        Ok(FrequencyListDescriptor {
193            coding_type,
194            centre_frequencies_bcd,
195        })
196    }
197}
198
199impl Serialize for FrequencyListDescriptor {
200    type Error = crate::error::Error;
201    fn serialized_len(&self) -> usize {
202        HEADER_LEN + CODING_BYTE_LEN + self.centre_frequencies_bcd.len() * ENTRY_LEN
203    }
204
205    fn serialize_into(&self, buf: &mut [u8]) -> Result<usize> {
206        let need = self.serialized_len();
207        if buf.len() < need {
208            return Err(Error::OutputBufferTooSmall {
209                need,
210                have: buf.len(),
211            });
212        }
213
214        let coding_type_bits = match self.coding_type {
215            CodingType::Undefined => 0b00,
216            CodingType::Satellite => 0b01,
217            CodingType::Cable => 0b10,
218            CodingType::Terrestrial => 0b11,
219        };
220
221        let body_length = CODING_BYTE_LEN + self.centre_frequencies_bcd.len() * ENTRY_LEN;
222
223        buf[0] = TAG;
224        buf[1] = body_length as u8;
225        buf[HEADER_LEN] = RESERVED_BITS_MASK | coding_type_bits;
226
227        let mut offset = HEADER_LEN + CODING_BYTE_LEN;
228        for entry in &self.centre_frequencies_bcd {
229            buf[offset..offset + ENTRY_LEN].copy_from_slice(entry);
230            offset += ENTRY_LEN;
231        }
232
233        Ok(need)
234    }
235}
236impl<'a> crate::traits::DescriptorDef<'a> for FrequencyListDescriptor {
237    const TAG: u8 = TAG;
238    const NAME: &'static str = "FREQUENCY_LIST";
239}
240
241#[cfg(test)]
242mod tests {
243    use super::*;
244
245    /// [TAG, 1, 0xFC] → zero entries, coding=Undefined
246    #[test]
247    fn parse_empty_entries_is_valid() {
248        let raw: Vec<u8> = vec![TAG, 0x01, 0xFC];
249        let desc = FrequencyListDescriptor::parse(&raw).unwrap();
250        assert!(desc.centre_frequencies_bcd.is_empty());
251        assert!(matches!(desc.coding_type, CodingType::Undefined));
252    }
253
254    /// coding_type byte 0xFD → Satellite (0xFC | 0b01)
255    #[test]
256    fn parse_extracts_coding_type_satellite() {
257        let raw: Vec<u8> = vec![TAG, 0x01, 0xFD];
258        let desc = FrequencyListDescriptor::parse(&raw).unwrap();
259        assert!(matches!(desc.coding_type, CodingType::Satellite));
260    }
261
262    /// coding_type byte 0xFE → Cable (0xFC | 0b10)
263    #[test]
264    fn parse_extracts_coding_type_cable() {
265        let raw: Vec<u8> = vec![TAG, 0x01, 0xFE];
266        let desc = FrequencyListDescriptor::parse(&raw).unwrap();
267        assert!(matches!(desc.coding_type, CodingType::Cable));
268    }
269
270    /// coding_type byte 0xFF → Terrestrial (0xFC | 0b11)
271    #[test]
272    fn parse_extracts_coding_type_terrestrial() {
273        let raw: Vec<u8> = vec![TAG, 0x01, 0xFF];
274        let desc = FrequencyListDescriptor::parse(&raw).unwrap();
275        assert!(matches!(desc.coding_type, CodingType::Terrestrial));
276    }
277
278    /// Multiple 4-byte entries parsed correctly.
279    #[test]
280    fn parse_extracts_multiple_frequency_entries() {
281        let raw: Vec<u8> = vec![
282            TAG, 0x09, // body length = 9 (1 coding byte + 2 entries × 4)
283            0xFD, // satellite
284            0x00, 0x30, 0x12, 0x34, // BCD 00301234 → 3_012_340 kHz = 30_123_400_000 Hz
285            0x00, 0x30, 0x00, 0x00, // BCD 00300000 → 3_000_000 kHz = 30_000_000_000 Hz
286        ];
287        let desc = FrequencyListDescriptor::parse(&raw).unwrap();
288        assert_eq!(desc.centre_frequencies_bcd.len(), 2);
289        assert_eq!(desc.centre_frequencies_bcd[0], [0x00, 0x30, 0x12, 0x34]);
290        assert_eq!(desc.centre_frequencies_bcd[1], [0x00, 0x30, 0x00, 0x00]);
291    }
292
293    /// Wrong tag byte should return InvalidDescriptor.
294    #[test]
295    fn parse_rejects_wrong_tag() {
296        let raw: Vec<u8> = vec![0x63, 0x01, 0xFC];
297        let err = FrequencyListDescriptor::parse(&raw).unwrap_err();
298        assert!(
299            matches!(err, Error::InvalidDescriptor { tag: 0x63, .. }),
300            "expected InvalidDescriptor(tag=0x63), got {err:?}"
301        );
302    }
303
304    /// Reserved bits set to zero must be ignored, not rejected (EN 300 468 §5.1).
305    #[test]
306    fn parse_ignores_reserved_bits() {
307        // coding byte 0x03: top 6 reserved bits = 0, coding_type = 0b11 (terrestrial).
308        let raw: Vec<u8> = vec![TAG, 0x01, 0x03];
309        let d = FrequencyListDescriptor::parse(&raw).unwrap();
310        assert_eq!(d.coding_type, CodingType::Terrestrial);
311        assert!(d.centre_frequencies_bcd.is_empty());
312    }
313
314    /// Body length not 1 + multiple of 4 → InvalidDescriptor
315    #[test]
316    fn parse_rejects_length_not_1_plus_multiple_of_4() {
317        let raw: Vec<u8> = vec![TAG, 0x03, 0xFC, 0x01, 0x02]; // body=3, need 1+4K
318        let err = FrequencyListDescriptor::parse(&raw).unwrap_err();
319        assert!(matches!(err, Error::InvalidDescriptor { .. }));
320    }
321
322    /// Buffer shorter than the 2-byte header → BufferTooShort
323    #[test]
324    fn parse_rejects_truncated_buffer() {
325        let raw: &[u8] = &[TAG];
326        let err = FrequencyListDescriptor::parse(raw).unwrap_err();
327        assert!(matches!(err, Error::BufferTooShort { need: 2, .. }));
328    }
329
330    /// Serialize a descriptor with zero entries, re-parse, compare.
331    #[test]
332    fn serialize_round_trip_empty() {
333        let desc = FrequencyListDescriptor {
334            coding_type: CodingType::Satellite,
335            centre_frequencies_bcd: vec![],
336        };
337        let raw: Vec<u8> = vec![TAG, 0x01, 0xFD];
338        let mut buf = vec![0u8; desc.serialized_len()];
339        let written = desc.serialize_into(&mut buf).unwrap();
340        assert_eq!(written, raw.len());
341        assert_eq!(buf, raw);
342
343        let reparsed = FrequencyListDescriptor::parse(&buf).unwrap();
344        assert_eq!(desc.coding_type, reparsed.coding_type);
345        assert_eq!(desc.centre_frequencies_bcd, reparsed.centre_frequencies_bcd);
346    }
347
348    /// Serialize a descriptor with many entries, re-parse, compare.
349    #[test]
350    fn serialize_round_trip_many_entries() {
351        let desc = FrequencyListDescriptor {
352            coding_type: CodingType::Cable,
353            centre_frequencies_bcd: vec![
354                [0x03, 0x46, 0x00, 0x00],
355                [0x04, 0x74, 0x00, 0x10],
356                [0x01, 0x15, 0x50, 0x00],
357                [0x04, 0x90, 0x25, 0x00],
358            ],
359        };
360        let mut buf = vec![0u8; desc.serialized_len()];
361        desc.serialize_into(&mut buf).unwrap();
362        let reparsed = FrequencyListDescriptor::parse(&buf).unwrap();
363        assert_eq!(desc.coding_type, reparsed.coding_type);
364        assert_eq!(desc.centre_frequencies_bcd, reparsed.centre_frequencies_bcd);
365    }
366
367    #[test]
368    fn satellite_frequency_hz_decodes_correctly() {
369        let desc = FrequencyListDescriptor {
370            coding_type: CodingType::Satellite,
371            centre_frequencies_bcd: vec![[0x01, 0x17, 0x25, 0x00]], // 11.72500 GHz
372        };
373        assert_eq!(desc.centre_frequencies_hz(), vec![Some(11_725_000_000)]);
374    }
375
376    #[test]
377    fn cable_frequency_hz_decodes_correctly() {
378        let desc = FrequencyListDescriptor {
379            coding_type: CodingType::Cable,
380            centre_frequencies_bcd: vec![[0x03, 0x46, 0x00, 0x00]], // 346.0000 MHz
381        };
382        assert_eq!(desc.centre_frequencies_hz(), vec![Some(346_000_000)]);
383    }
384
385    #[test]
386    fn terrestrial_frequency_hz_decodes_binary() {
387        let desc = FrequencyListDescriptor {
388            coding_type: CodingType::Terrestrial,
389            // binary 0x04A858F0 = 78_141_680 × 10 Hz = 781_416_800 Hz
390            centre_frequencies_bcd: vec![[0x04, 0xA8, 0x58, 0xF0]],
391        };
392        assert_eq!(desc.centre_frequencies_hz(), vec![Some(781_416_800)]);
393    }
394
395    #[test]
396    fn set_satellite_frequencies_hz_round_trips() {
397        let mut desc = FrequencyListDescriptor {
398            coding_type: CodingType::Satellite,
399            centre_frequencies_bcd: vec![],
400        };
401        desc.set_centre_frequencies_hz(&[11_725_000_000]).unwrap();
402        assert_eq!(desc.centre_frequencies_hz(), vec![Some(11_725_000_000)]);
403        assert_eq!(desc.centre_frequencies_bcd[0], [0x01, 0x17, 0x25, 0x00]);
404    }
405
406    #[test]
407    fn set_terrestrial_frequencies_hz_round_trips() {
408        let mut desc = FrequencyListDescriptor {
409            coding_type: CodingType::Terrestrial,
410            centre_frequencies_bcd: vec![],
411        };
412        desc.set_centre_frequencies_hz(&[781_416_800]).unwrap();
413        assert_eq!(desc.centre_frequencies_hz(), vec![Some(781_416_800)]);
414        assert_eq!(desc.centre_frequencies_bcd[0], [0x04, 0xA8, 0x58, 0xF0]);
415    }
416
417    #[test]
418    fn set_cable_frequencies_hz_round_trips() {
419        let mut desc = FrequencyListDescriptor {
420            coding_type: CodingType::Cable,
421            centre_frequencies_bcd: vec![],
422        };
423        desc.set_centre_frequencies_hz(&[346_000_000]).unwrap();
424        assert_eq!(desc.centre_frequencies_hz(), vec![Some(346_000_000)]);
425    }
426}