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 crate::error::{Error, Result};
8use crate::traits::Descriptor;
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 BCD frequency.
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 in 1/100 MHz (GHz.MMMM).
31    Satellite,
32    /// Cable — 8 BCD digits in 100 Hz units.
33    Cable,
34    /// Terrestrial — 8 BCD digits in 100 Hz units.
35    Terrestrial,
36}
37
38/// Frequency List Descriptor.
39#[derive(Debug, Clone, PartialEq, Eq)]
40#[cfg_attr(feature = "serde", derive(serde::Serialize))]
41pub struct FrequencyListDescriptor {
42    /// Interpretation of every `centre_frequencies_bcd` entry.
43    pub coding_type: CodingType,
44    /// Raw 4-byte BCD centre_frequency entries in wire order.
45    pub centre_frequencies_bcd: Vec<[u8; 4]>,
46}
47
48impl FrequencyListDescriptor {
49    /// Convenience: all entries as a single `Vec<u32>` of the BCD bytes
50    /// big-endian decoded (callers can interpret per `coding_type`).
51    #[must_use]
52    pub fn centre_frequencies_be(&self) -> Vec<u32> {
53        self.centre_frequencies_bcd
54            .iter()
55            .map(|b| u32::from_be_bytes(*b))
56            .collect()
57    }
58
59    /// Hz per BCD-decoded unit for the current `coding_type`, or `None` for
60    /// `Undefined`. Satellite entries decode like
61    /// [`SatelliteDeliverySystemDescriptor`](super::satellite_delivery_system::SatelliteDeliverySystemDescriptor)
62    /// (1 kHz units); cable/terrestrial entries are 100 Hz units.
63    fn hz_per_unit(&self) -> Option<u64> {
64        match self.coding_type {
65            CodingType::Satellite => Some(1_000),
66            CodingType::Cable | CodingType::Terrestrial => Some(100),
67            CodingType::Undefined => None,
68        }
69    }
70
71    /// Decode every `centre_frequencies_bcd` entry to Hz, interpreted per
72    /// `coding_type`. Each element is `None` if its BCD is invalid or
73    /// `coding_type` is `Undefined`.
74    #[must_use]
75    pub fn centre_frequencies_hz(&self) -> Vec<Option<u64>> {
76        let scale = self.hz_per_unit();
77        self.centre_frequencies_bcd
78            .iter()
79            .map(|b| {
80                let value = dvb_common::bcd::bcd_to_decimal(u64::from(u32::from_be_bytes(*b)), 8)?;
81                Some(value * scale?)
82            })
83            .collect()
84    }
85
86    /// Replace the entries by encoding each Hz value to a 4-byte BCD entry per
87    /// `coding_type` (values truncate to the field's resolution).
88    ///
89    /// # Errors
90    /// [`ValueOutOfRange`](crate::Error::ValueOutOfRange) if `coding_type`
91    /// is `Undefined` or a value exceeds the 8-digit BCD entry.
92    pub fn set_centre_frequencies_hz(&mut self, frequencies_hz: &[u64]) -> crate::Result<()> {
93        let scale = self.hz_per_unit().ok_or(crate::Error::ValueOutOfRange {
94            field: "FrequencyListDescriptor::centre_frequency",
95            reason: "coding_type is Undefined; cannot encode frequencies",
96        })?;
97        let mut out = Vec::with_capacity(frequencies_hz.len());
98        for &hz in frequencies_hz {
99            let bcd = super::encode_bcd_field(
100                hz / scale,
101                8,
102                "FrequencyListDescriptor::centre_frequency",
103            )?;
104            out.push((bcd as u32).to_be_bytes());
105        }
106        self.centre_frequencies_bcd = out;
107        Ok(())
108    }
109}
110
111impl<'a> Parse<'a> for FrequencyListDescriptor {
112    type Error = crate::error::Error;
113    fn parse(bytes: &'a [u8]) -> Result<Self> {
114        if bytes.len() < HEADER_LEN {
115            return Err(Error::BufferTooShort {
116                need: HEADER_LEN,
117                have: bytes.len(),
118                what: "FrequencyListDescriptor header",
119            });
120        }
121
122        let tag = bytes[0];
123        if tag != TAG {
124            return Err(Error::InvalidDescriptor {
125                tag,
126                reason: "expected tag 0x62",
127            });
128        }
129
130        let body_length = bytes[1] as usize;
131
132        if body_length < CODING_BYTE_LEN {
133            return Err(Error::InvalidDescriptor {
134                tag: TAG,
135                reason: "body too short (need at least coding_type byte)",
136            });
137        }
138
139        if (body_length - CODING_BYTE_LEN) % ENTRY_LEN != 0 {
140            return Err(Error::InvalidDescriptor {
141                tag: TAG,
142                reason: "body length minus coding byte must be multiple of 4",
143            });
144        }
145
146        let body_start = HEADER_LEN;
147        let total_needed = body_start + body_length;
148        if bytes.len() < total_needed {
149            return Err(Error::BufferTooShort {
150                need: total_needed,
151                have: bytes.len(),
152                what: "FrequencyListDescriptor body",
153            });
154        }
155
156        let coding_byte = bytes[body_start];
157        // Top 6 bits are reserved_future_use — ignored on parse
158        // (EN 300 468 §5.1: decoders shall ignore reserved bits).
159        let coding_type_value = coding_byte & CODING_TYPE_MASK;
160        let coding_type = match coding_type_value {
161            0b00 => CodingType::Undefined,
162            0b01 => CodingType::Satellite,
163            0b10 => CodingType::Cable,
164            _ => CodingType::Terrestrial,
165        };
166
167        let entry_count = (body_length - CODING_BYTE_LEN) / ENTRY_LEN;
168        let mut centre_frequencies_bcd = Vec::with_capacity(entry_count);
169
170        let mut offset = body_start + CODING_BYTE_LEN;
171        for _ in 0..entry_count {
172            let mut entry = [0u8; ENTRY_LEN];
173            entry.copy_from_slice(&bytes[offset..offset + ENTRY_LEN]);
174            centre_frequencies_bcd.push(entry);
175            offset += ENTRY_LEN;
176        }
177
178        Ok(FrequencyListDescriptor {
179            coding_type,
180            centre_frequencies_bcd,
181        })
182    }
183}
184
185impl Serialize for FrequencyListDescriptor {
186    type Error = crate::error::Error;
187    fn serialized_len(&self) -> usize {
188        HEADER_LEN + CODING_BYTE_LEN + self.centre_frequencies_bcd.len() * ENTRY_LEN
189    }
190
191    fn serialize_into(&self, buf: &mut [u8]) -> Result<usize> {
192        let need = self.serialized_len();
193        if buf.len() < need {
194            return Err(Error::OutputBufferTooSmall {
195                need,
196                have: buf.len(),
197            });
198        }
199
200        let coding_type_bits = match self.coding_type {
201            CodingType::Undefined => 0b00,
202            CodingType::Satellite => 0b01,
203            CodingType::Cable => 0b10,
204            CodingType::Terrestrial => 0b11,
205        };
206
207        let body_length = CODING_BYTE_LEN + self.centre_frequencies_bcd.len() * ENTRY_LEN;
208
209        buf[0] = TAG;
210        buf[1] = body_length as u8;
211        buf[HEADER_LEN] = RESERVED_BITS_MASK | coding_type_bits;
212
213        let mut offset = HEADER_LEN + CODING_BYTE_LEN;
214        for entry in &self.centre_frequencies_bcd {
215            buf[offset..offset + ENTRY_LEN].copy_from_slice(entry);
216            offset += ENTRY_LEN;
217        }
218
219        Ok(need)
220    }
221}
222
223impl<'a> Descriptor<'a> for FrequencyListDescriptor {
224    const TAG: u8 = TAG;
225
226    fn descriptor_length(&self) -> u8 {
227        (self.serialized_len() - HEADER_LEN) as u8
228    }
229}
230
231impl<'a> crate::traits::DescriptorDef<'a> for FrequencyListDescriptor {
232    const TAG: u8 = TAG;
233    const NAME: &'static str = "FREQUENCY_LIST";
234}
235
236#[cfg(test)]
237mod tests {
238    use super::*;
239
240    /// [TAG, 1, 0xFC] → zero entries, coding=Undefined
241    #[test]
242    fn parse_empty_entries_is_valid() {
243        let raw: Vec<u8> = vec![TAG, 0x01, 0xFC];
244        let desc = FrequencyListDescriptor::parse(&raw).unwrap();
245        assert!(desc.centre_frequencies_bcd.is_empty());
246        assert!(matches!(desc.coding_type, CodingType::Undefined));
247    }
248
249    /// coding_type byte 0xFD → Satellite (0xFC | 0b01)
250    #[test]
251    fn parse_extracts_coding_type_satellite() {
252        let raw: Vec<u8> = vec![TAG, 0x01, 0xFD];
253        let desc = FrequencyListDescriptor::parse(&raw).unwrap();
254        assert!(matches!(desc.coding_type, CodingType::Satellite));
255    }
256
257    /// coding_type byte 0xFE → Cable (0xFC | 0b10)
258    #[test]
259    fn parse_extracts_coding_type_cable() {
260        let raw: Vec<u8> = vec![TAG, 0x01, 0xFE];
261        let desc = FrequencyListDescriptor::parse(&raw).unwrap();
262        assert!(matches!(desc.coding_type, CodingType::Cable));
263    }
264
265    /// coding_type byte 0xFF → Terrestrial (0xFC | 0b11)
266    #[test]
267    fn parse_extracts_coding_type_terrestrial() {
268        let raw: Vec<u8> = vec![TAG, 0x01, 0xFF];
269        let desc = FrequencyListDescriptor::parse(&raw).unwrap();
270        assert!(matches!(desc.coding_type, CodingType::Terrestrial));
271    }
272
273    /// Multiple 4-byte entries parsed correctly.
274    #[test]
275    fn parse_extracts_multiple_frequency_entries() {
276        let raw: Vec<u8> = vec![
277            TAG, 0x09, // body length = 9 (1 coding byte + 2 entries × 4)
278            0xFD, // satellite
279            0x02, 0x75, 0x00, 0x00, // 27.50000 GHz
280            0x03, 0x00, 0x00, 0x00, // 30.00000 GHz
281        ];
282        let desc = FrequencyListDescriptor::parse(&raw).unwrap();
283        assert_eq!(desc.centre_frequencies_bcd.len(), 2);
284        assert_eq!(desc.centre_frequencies_bcd[0], [0x02, 0x75, 0x00, 0x00]);
285        assert_eq!(desc.centre_frequencies_bcd[1], [0x03, 0x00, 0x00, 0x00]);
286    }
287
288    /// Wrong tag byte should return InvalidDescriptor.
289    #[test]
290    fn parse_rejects_wrong_tag() {
291        let raw: Vec<u8> = vec![0x63, 0x01, 0xFC];
292        let err = FrequencyListDescriptor::parse(&raw).unwrap_err();
293        assert!(
294            matches!(err, Error::InvalidDescriptor { tag: 0x63, .. }),
295            "expected InvalidDescriptor(tag=0x63), got {err:?}"
296        );
297    }
298
299    /// Reserved bits set to zero must be ignored, not rejected (EN 300 468 §5.1).
300    #[test]
301    fn parse_ignores_reserved_bits() {
302        // coding byte 0x03: top 6 reserved bits = 0, coding_type = 0b11 (terrestrial).
303        let raw: Vec<u8> = vec![TAG, 0x01, 0x03];
304        let d = FrequencyListDescriptor::parse(&raw).unwrap();
305        assert_eq!(d.coding_type, CodingType::Terrestrial);
306        assert!(d.centre_frequencies_bcd.is_empty());
307    }
308
309    /// Body length not 1 + multiple of 4 → InvalidDescriptor
310    #[test]
311    fn parse_rejects_length_not_1_plus_multiple_of_4() {
312        let raw: Vec<u8> = vec![TAG, 0x03, 0xFC, 0x01, 0x02]; // body=3, need 1+4K
313        let err = FrequencyListDescriptor::parse(&raw).unwrap_err();
314        assert!(matches!(err, Error::InvalidDescriptor { .. }));
315    }
316
317    /// Buffer shorter than the 2-byte header → BufferTooShort
318    #[test]
319    fn parse_rejects_truncated_buffer() {
320        let raw: &[u8] = &[TAG];
321        let err = FrequencyListDescriptor::parse(raw).unwrap_err();
322        assert!(matches!(err, Error::BufferTooShort { need: 2, .. }));
323    }
324
325    /// Serialize a descriptor with zero entries, re-parse, compare.
326    #[test]
327    fn serialize_round_trip_empty() {
328        let desc = FrequencyListDescriptor {
329            coding_type: CodingType::Satellite,
330            centre_frequencies_bcd: vec![],
331        };
332        let raw: Vec<u8> = vec![TAG, 0x01, 0xFD];
333        let mut buf = vec![0u8; desc.serialized_len()];
334        let written = desc.serialize_into(&mut buf).unwrap();
335        assert_eq!(written, raw.len());
336        assert_eq!(buf, raw);
337
338        let reparsed = FrequencyListDescriptor::parse(&buf).unwrap();
339        assert_eq!(desc.coding_type, reparsed.coding_type);
340        assert_eq!(desc.centre_frequencies_bcd, reparsed.centre_frequencies_bcd);
341    }
342
343    /// Serialize a descriptor with many entries, re-parse, compare.
344    #[test]
345    fn serialize_round_trip_many_entries() {
346        let desc = FrequencyListDescriptor {
347            coding_type: CodingType::Cable,
348            centre_frequencies_bcd: vec![
349                [0x02, 0x75, 0x00, 0x00],
350                [0x03, 0x00, 0x00, 0x00],
351                [0x01, 0x15, 0x50, 0x00],
352                [0x04, 0x90, 0x25, 0x00],
353            ],
354        };
355        let mut buf = vec![0u8; desc.serialized_len()];
356        desc.serialize_into(&mut buf).unwrap();
357        let reparsed = FrequencyListDescriptor::parse(&buf).unwrap();
358        assert_eq!(desc.coding_type, reparsed.coding_type);
359        assert_eq!(desc.centre_frequencies_bcd, reparsed.centre_frequencies_bcd);
360    }
361}