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
60impl<'a> Parse<'a> for FrequencyListDescriptor {
61    type Error = crate::error::Error;
62    fn parse(bytes: &'a [u8]) -> Result<Self> {
63        if bytes.len() < HEADER_LEN {
64            return Err(Error::BufferTooShort {
65                need: HEADER_LEN,
66                have: bytes.len(),
67                what: "FrequencyListDescriptor header",
68            });
69        }
70
71        let tag = bytes[0];
72        if tag != TAG {
73            return Err(Error::InvalidDescriptor {
74                tag,
75                reason: "expected tag 0x62",
76            });
77        }
78
79        let body_length = bytes[1] as usize;
80
81        if body_length < CODING_BYTE_LEN {
82            return Err(Error::InvalidDescriptor {
83                tag: TAG,
84                reason: "body too short (need at least coding_type byte)",
85            });
86        }
87
88        if (body_length - CODING_BYTE_LEN) % ENTRY_LEN != 0 {
89            return Err(Error::InvalidDescriptor {
90                tag: TAG,
91                reason: "body length minus coding byte must be multiple of 4",
92            });
93        }
94
95        let body_start = HEADER_LEN;
96        let total_needed = body_start + body_length;
97        if bytes.len() < total_needed {
98            return Err(Error::BufferTooShort {
99                need: total_needed,
100                have: bytes.len(),
101                what: "FrequencyListDescriptor body",
102            });
103        }
104
105        let coding_byte = bytes[body_start];
106        // Top 6 bits are reserved_future_use — ignored on parse
107        // (EN 300 468 §5.1: decoders shall ignore reserved bits).
108        let coding_type_value = coding_byte & CODING_TYPE_MASK;
109        let coding_type = match coding_type_value {
110            0b00 => CodingType::Undefined,
111            0b01 => CodingType::Satellite,
112            0b10 => CodingType::Cable,
113            _ => CodingType::Terrestrial,
114        };
115
116        let entry_count = (body_length - CODING_BYTE_LEN) / ENTRY_LEN;
117        let mut centre_frequencies_bcd = Vec::with_capacity(entry_count);
118
119        let mut offset = body_start + CODING_BYTE_LEN;
120        for _ in 0..entry_count {
121            let mut entry = [0u8; ENTRY_LEN];
122            entry.copy_from_slice(&bytes[offset..offset + ENTRY_LEN]);
123            centre_frequencies_bcd.push(entry);
124            offset += ENTRY_LEN;
125        }
126
127        Ok(FrequencyListDescriptor {
128            coding_type,
129            centre_frequencies_bcd,
130        })
131    }
132}
133
134impl Serialize for FrequencyListDescriptor {
135    type Error = crate::error::Error;
136    fn serialized_len(&self) -> usize {
137        HEADER_LEN + CODING_BYTE_LEN + self.centre_frequencies_bcd.len() * ENTRY_LEN
138    }
139
140    fn serialize_into(&self, buf: &mut [u8]) -> Result<usize> {
141        let need = self.serialized_len();
142        if buf.len() < need {
143            return Err(Error::OutputBufferTooSmall {
144                need,
145                have: buf.len(),
146            });
147        }
148
149        let coding_type_bits = match self.coding_type {
150            CodingType::Undefined => 0b00,
151            CodingType::Satellite => 0b01,
152            CodingType::Cable => 0b10,
153            CodingType::Terrestrial => 0b11,
154        };
155
156        let body_length = CODING_BYTE_LEN + self.centre_frequencies_bcd.len() * ENTRY_LEN;
157
158        buf[0] = TAG;
159        buf[1] = body_length as u8;
160        buf[HEADER_LEN] = RESERVED_BITS_MASK | coding_type_bits;
161
162        let mut offset = HEADER_LEN + CODING_BYTE_LEN;
163        for entry in &self.centre_frequencies_bcd {
164            buf[offset..offset + ENTRY_LEN].copy_from_slice(entry);
165            offset += ENTRY_LEN;
166        }
167
168        Ok(need)
169    }
170}
171
172impl<'a> Descriptor<'a> for FrequencyListDescriptor {
173    const TAG: u8 = TAG;
174
175    fn descriptor_length(&self) -> u8 {
176        (self.serialized_len() - HEADER_LEN) as u8
177    }
178}
179
180impl<'a> crate::traits::DescriptorDef<'a> for FrequencyListDescriptor {
181    const TAG: u8 = TAG;
182    const NAME: &'static str = "FREQUENCY_LIST";
183}
184
185#[cfg(test)]
186mod tests {
187    use super::*;
188
189    /// [TAG, 1, 0xFC] → zero entries, coding=Undefined
190    #[test]
191    fn parse_empty_entries_is_valid() {
192        let raw: Vec<u8> = vec![TAG, 0x01, 0xFC];
193        let desc = FrequencyListDescriptor::parse(&raw).unwrap();
194        assert!(desc.centre_frequencies_bcd.is_empty());
195        assert!(matches!(desc.coding_type, CodingType::Undefined));
196    }
197
198    /// coding_type byte 0xFD → Satellite (0xFC | 0b01)
199    #[test]
200    fn parse_extracts_coding_type_satellite() {
201        let raw: Vec<u8> = vec![TAG, 0x01, 0xFD];
202        let desc = FrequencyListDescriptor::parse(&raw).unwrap();
203        assert!(matches!(desc.coding_type, CodingType::Satellite));
204    }
205
206    /// coding_type byte 0xFE → Cable (0xFC | 0b10)
207    #[test]
208    fn parse_extracts_coding_type_cable() {
209        let raw: Vec<u8> = vec![TAG, 0x01, 0xFE];
210        let desc = FrequencyListDescriptor::parse(&raw).unwrap();
211        assert!(matches!(desc.coding_type, CodingType::Cable));
212    }
213
214    /// coding_type byte 0xFF → Terrestrial (0xFC | 0b11)
215    #[test]
216    fn parse_extracts_coding_type_terrestrial() {
217        let raw: Vec<u8> = vec![TAG, 0x01, 0xFF];
218        let desc = FrequencyListDescriptor::parse(&raw).unwrap();
219        assert!(matches!(desc.coding_type, CodingType::Terrestrial));
220    }
221
222    /// Multiple 4-byte entries parsed correctly.
223    #[test]
224    fn parse_extracts_multiple_frequency_entries() {
225        let raw: Vec<u8> = vec![
226            TAG, 0x09, // body length = 9 (1 coding byte + 2 entries × 4)
227            0xFD, // satellite
228            0x02, 0x75, 0x00, 0x00, // 27.50000 GHz
229            0x03, 0x00, 0x00, 0x00, // 30.00000 GHz
230        ];
231        let desc = FrequencyListDescriptor::parse(&raw).unwrap();
232        assert_eq!(desc.centre_frequencies_bcd.len(), 2);
233        assert_eq!(desc.centre_frequencies_bcd[0], [0x02, 0x75, 0x00, 0x00]);
234        assert_eq!(desc.centre_frequencies_bcd[1], [0x03, 0x00, 0x00, 0x00]);
235    }
236
237    /// Wrong tag byte should return InvalidDescriptor.
238    #[test]
239    fn parse_rejects_wrong_tag() {
240        let raw: Vec<u8> = vec![0x63, 0x01, 0xFC];
241        let err = FrequencyListDescriptor::parse(&raw).unwrap_err();
242        assert!(
243            matches!(err, Error::InvalidDescriptor { tag: 0x63, .. }),
244            "expected InvalidDescriptor(tag=0x63), got {err:?}"
245        );
246    }
247
248    /// Reserved bits set to zero must be ignored, not rejected (EN 300 468 §5.1).
249    #[test]
250    fn parse_ignores_reserved_bits() {
251        // coding byte 0x03: top 6 reserved bits = 0, coding_type = 0b11 (terrestrial).
252        let raw: Vec<u8> = vec![TAG, 0x01, 0x03];
253        let d = FrequencyListDescriptor::parse(&raw).unwrap();
254        assert_eq!(d.coding_type, CodingType::Terrestrial);
255        assert!(d.centre_frequencies_bcd.is_empty());
256    }
257
258    /// Body length not 1 + multiple of 4 → InvalidDescriptor
259    #[test]
260    fn parse_rejects_length_not_1_plus_multiple_of_4() {
261        let raw: Vec<u8> = vec![TAG, 0x03, 0xFC, 0x01, 0x02]; // body=3, need 1+4K
262        let err = FrequencyListDescriptor::parse(&raw).unwrap_err();
263        assert!(matches!(err, Error::InvalidDescriptor { .. }));
264    }
265
266    /// Buffer shorter than the 2-byte header → BufferTooShort
267    #[test]
268    fn parse_rejects_truncated_buffer() {
269        let raw: &[u8] = &[TAG];
270        let err = FrequencyListDescriptor::parse(raw).unwrap_err();
271        assert!(matches!(err, Error::BufferTooShort { need: 2, .. }));
272    }
273
274    /// Serialize a descriptor with zero entries, re-parse, compare.
275    #[test]
276    fn serialize_round_trip_empty() {
277        let desc = FrequencyListDescriptor {
278            coding_type: CodingType::Satellite,
279            centre_frequencies_bcd: vec![],
280        };
281        let raw: Vec<u8> = vec![TAG, 0x01, 0xFD];
282        let mut buf = vec![0u8; desc.serialized_len()];
283        let written = desc.serialize_into(&mut buf).unwrap();
284        assert_eq!(written, raw.len());
285        assert_eq!(buf, raw);
286
287        let reparsed = FrequencyListDescriptor::parse(&buf).unwrap();
288        assert_eq!(desc.coding_type, reparsed.coding_type);
289        assert_eq!(desc.centre_frequencies_bcd, reparsed.centre_frequencies_bcd);
290    }
291
292    /// Serialize a descriptor with many entries, re-parse, compare.
293    #[test]
294    fn serialize_round_trip_many_entries() {
295        let desc = FrequencyListDescriptor {
296            coding_type: CodingType::Cable,
297            centre_frequencies_bcd: vec![
298                [0x02, 0x75, 0x00, 0x00],
299                [0x03, 0x00, 0x00, 0x00],
300                [0x01, 0x15, 0x50, 0x00],
301                [0x04, 0x90, 0x25, 0x00],
302            ],
303        };
304        let mut buf = vec![0u8; desc.serialized_len()];
305        desc.serialize_into(&mut buf).unwrap();
306        let reparsed = FrequencyListDescriptor::parse(&buf).unwrap();
307        assert_eq!(desc.coding_type, reparsed.coding_type);
308        assert_eq!(desc.centre_frequencies_bcd, reparsed.centre_frequencies_bcd);
309    }
310}