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
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 centre_frequency entries in wire order. Interpretation
45    /// depends on `coding_type`: BCD for Satellite/Cable, binary for Terrestrial.
46    pub centre_frequencies_bcd: Vec<[u8; 4]>,
47}
48
49impl FrequencyListDescriptor {
50    /// Hz per BCD-decoded unit for Satellite or Cable, or `None` for
51    /// Undefined / Terrestrial (Terrestrial uses binary encoding, not BCD).
52    fn hz_per_unit_bcd(&self) -> Option<u64> {
53        match self.coding_type {
54            CodingType::Satellite => Some(10_000),
55            CodingType::Cable => Some(100),
56            CodingType::Terrestrial | CodingType::Undefined => None,
57        }
58    }
59
60    /// Decode every `centre_frequencies_bcd` entry to Hz, interpreted per
61    /// `coding_type`. Each element is `None` if `coding_type` is `Undefined`
62    /// or a BCD nibble is invalid (Satellite/Cable).
63    #[must_use]
64    pub fn centre_frequencies_hz(&self) -> Vec<Option<u64>> {
65        match self.coding_type {
66            CodingType::Satellite | CodingType::Cable => {
67                let scale = self.hz_per_unit_bcd().unwrap();
68                self.centre_frequencies_bcd
69                    .iter()
70                    .map(|b| {
71                        let value =
72                            dvb_common::bcd::bcd_to_decimal(u64::from(u32::from_be_bytes(*b)), 8)?;
73                        Some(value * scale)
74                    })
75                    .collect()
76            }
77            CodingType::Terrestrial => self
78                .centre_frequencies_bcd
79                .iter()
80                .map(|b| Some(u64::from(u32::from_be_bytes(*b)) * 10))
81                .collect(),
82            CodingType::Undefined => self.centre_frequencies_bcd.iter().map(|_| None).collect(),
83        }
84    }
85
86    /// Replace the entries by encoding each Hz value per `coding_type`
87    /// (values truncate to the field's resolution).
88    ///
89    /// # Errors
90    /// [`ValueOutOfRange`](crate::Error::ValueOutOfRange) if `coding_type`
91    /// is `Undefined`, a BCD value exceeds 8 digits (Satellite/Cable), or
92    /// a binary value exceeds 32 bits (Terrestrial).
93    pub fn set_centre_frequencies_hz(&mut self, frequencies_hz: &[u64]) -> crate::Result<()> {
94        match self.coding_type {
95            CodingType::Satellite | CodingType::Cable => {
96                let scale = self
97                    .hz_per_unit_bcd()
98                    .ok_or(crate::Error::ValueOutOfRange {
99                        field: "FrequencyListDescriptor::centre_frequency",
100                        reason: "coding_type is Undefined; cannot encode frequencies",
101                    })?;
102                let mut out = Vec::with_capacity(frequencies_hz.len());
103                for &hz in frequencies_hz {
104                    let bcd = super::encode_bcd_field(
105                        hz / scale,
106                        8,
107                        "FrequencyListDescriptor::centre_frequency",
108                    )?;
109                    out.push((bcd as u32).to_be_bytes());
110                }
111                self.centre_frequencies_bcd = out;
112                Ok(())
113            }
114            CodingType::Terrestrial => {
115                let mut out = Vec::with_capacity(frequencies_hz.len());
116                for &hz in frequencies_hz {
117                    let units = hz / 10;
118                    if units > u64::from(u32::MAX) {
119                        return Err(Error::ValueOutOfRange {
120                            field: "frequency_list centre_frequency",
121                            reason: "terrestrial frequency exceeds the 32-bit (×10 Hz) wire field",
122                        });
123                    }
124                    out.push((units as u32).to_be_bytes());
125                }
126                self.centre_frequencies_bcd = out;
127                Ok(())
128            }
129            CodingType::Undefined => Err(crate::Error::ValueOutOfRange {
130                field: "FrequencyListDescriptor::centre_frequency",
131                reason: "coding_type is Undefined; cannot encode frequencies",
132            }),
133        }
134    }
135}
136
137impl<'a> Parse<'a> for FrequencyListDescriptor {
138    type Error = crate::error::Error;
139    fn parse(bytes: &'a [u8]) -> Result<Self> {
140        let body = descriptor_body(bytes, TAG, "FrequencyListDescriptor", "expected tag 0x62")?;
141
142        if body.len() < CODING_BYTE_LEN {
143            return Err(Error::InvalidDescriptor {
144                tag: TAG,
145                reason: "body too short (need at least coding_type byte)",
146            });
147        }
148
149        if (body.len() - CODING_BYTE_LEN) % ENTRY_LEN != 0 {
150            return Err(Error::InvalidDescriptor {
151                tag: TAG,
152                reason: "body length minus coding byte must be multiple of 4",
153            });
154        }
155
156        let coding_byte = body[0];
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.len() - CODING_BYTE_LEN) / ENTRY_LEN;
168        let mut centre_frequencies_bcd = Vec::with_capacity(entry_count);
169
170        let mut offset = CODING_BYTE_LEN;
171        for _ in 0..entry_count {
172            let mut entry = [0u8; ENTRY_LEN];
173            entry.copy_from_slice(&body[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}
222impl<'a> crate::traits::DescriptorDef<'a> for FrequencyListDescriptor {
223    const TAG: u8 = TAG;
224    const NAME: &'static str = "FREQUENCY_LIST";
225}
226
227#[cfg(test)]
228mod tests {
229    use super::*;
230
231    /// [TAG, 1, 0xFC] → zero entries, coding=Undefined
232    #[test]
233    fn parse_empty_entries_is_valid() {
234        let raw: Vec<u8> = vec![TAG, 0x01, 0xFC];
235        let desc = FrequencyListDescriptor::parse(&raw).unwrap();
236        assert!(desc.centre_frequencies_bcd.is_empty());
237        assert!(matches!(desc.coding_type, CodingType::Undefined));
238    }
239
240    /// coding_type byte 0xFD → Satellite (0xFC | 0b01)
241    #[test]
242    fn parse_extracts_coding_type_satellite() {
243        let raw: Vec<u8> = vec![TAG, 0x01, 0xFD];
244        let desc = FrequencyListDescriptor::parse(&raw).unwrap();
245        assert!(matches!(desc.coding_type, CodingType::Satellite));
246    }
247
248    /// coding_type byte 0xFE → Cable (0xFC | 0b10)
249    #[test]
250    fn parse_extracts_coding_type_cable() {
251        let raw: Vec<u8> = vec![TAG, 0x01, 0xFE];
252        let desc = FrequencyListDescriptor::parse(&raw).unwrap();
253        assert!(matches!(desc.coding_type, CodingType::Cable));
254    }
255
256    /// coding_type byte 0xFF → Terrestrial (0xFC | 0b11)
257    #[test]
258    fn parse_extracts_coding_type_terrestrial() {
259        let raw: Vec<u8> = vec![TAG, 0x01, 0xFF];
260        let desc = FrequencyListDescriptor::parse(&raw).unwrap();
261        assert!(matches!(desc.coding_type, CodingType::Terrestrial));
262    }
263
264    /// Multiple 4-byte entries parsed correctly.
265    #[test]
266    fn parse_extracts_multiple_frequency_entries() {
267        let raw: Vec<u8> = vec![
268            TAG, 0x09, // body length = 9 (1 coding byte + 2 entries × 4)
269            0xFD, // satellite
270            0x00, 0x30, 0x12, 0x34, // BCD 00301234 → 3_012_340 kHz = 30_123_400_000 Hz
271            0x00, 0x30, 0x00, 0x00, // BCD 00300000 → 3_000_000 kHz = 30_000_000_000 Hz
272        ];
273        let desc = FrequencyListDescriptor::parse(&raw).unwrap();
274        assert_eq!(desc.centre_frequencies_bcd.len(), 2);
275        assert_eq!(desc.centre_frequencies_bcd[0], [0x00, 0x30, 0x12, 0x34]);
276        assert_eq!(desc.centre_frequencies_bcd[1], [0x00, 0x30, 0x00, 0x00]);
277    }
278
279    /// Wrong tag byte should return InvalidDescriptor.
280    #[test]
281    fn parse_rejects_wrong_tag() {
282        let raw: Vec<u8> = vec![0x63, 0x01, 0xFC];
283        let err = FrequencyListDescriptor::parse(&raw).unwrap_err();
284        assert!(
285            matches!(err, Error::InvalidDescriptor { tag: 0x63, .. }),
286            "expected InvalidDescriptor(tag=0x63), got {err:?}"
287        );
288    }
289
290    /// Reserved bits set to zero must be ignored, not rejected (EN 300 468 §5.1).
291    #[test]
292    fn parse_ignores_reserved_bits() {
293        // coding byte 0x03: top 6 reserved bits = 0, coding_type = 0b11 (terrestrial).
294        let raw: Vec<u8> = vec![TAG, 0x01, 0x03];
295        let d = FrequencyListDescriptor::parse(&raw).unwrap();
296        assert_eq!(d.coding_type, CodingType::Terrestrial);
297        assert!(d.centre_frequencies_bcd.is_empty());
298    }
299
300    /// Body length not 1 + multiple of 4 → InvalidDescriptor
301    #[test]
302    fn parse_rejects_length_not_1_plus_multiple_of_4() {
303        let raw: Vec<u8> = vec![TAG, 0x03, 0xFC, 0x01, 0x02]; // body=3, need 1+4K
304        let err = FrequencyListDescriptor::parse(&raw).unwrap_err();
305        assert!(matches!(err, Error::InvalidDescriptor { .. }));
306    }
307
308    /// Buffer shorter than the 2-byte header → BufferTooShort
309    #[test]
310    fn parse_rejects_truncated_buffer() {
311        let raw: &[u8] = &[TAG];
312        let err = FrequencyListDescriptor::parse(raw).unwrap_err();
313        assert!(matches!(err, Error::BufferTooShort { need: 2, .. }));
314    }
315
316    /// Serialize a descriptor with zero entries, re-parse, compare.
317    #[test]
318    fn serialize_round_trip_empty() {
319        let desc = FrequencyListDescriptor {
320            coding_type: CodingType::Satellite,
321            centre_frequencies_bcd: vec![],
322        };
323        let raw: Vec<u8> = vec![TAG, 0x01, 0xFD];
324        let mut buf = vec![0u8; desc.serialized_len()];
325        let written = desc.serialize_into(&mut buf).unwrap();
326        assert_eq!(written, raw.len());
327        assert_eq!(buf, raw);
328
329        let reparsed = FrequencyListDescriptor::parse(&buf).unwrap();
330        assert_eq!(desc.coding_type, reparsed.coding_type);
331        assert_eq!(desc.centre_frequencies_bcd, reparsed.centre_frequencies_bcd);
332    }
333
334    /// Serialize a descriptor with many entries, re-parse, compare.
335    #[test]
336    fn serialize_round_trip_many_entries() {
337        let desc = FrequencyListDescriptor {
338            coding_type: CodingType::Cable,
339            centre_frequencies_bcd: vec![
340                [0x03, 0x46, 0x00, 0x00],
341                [0x04, 0x74, 0x00, 0x10],
342                [0x01, 0x15, 0x50, 0x00],
343                [0x04, 0x90, 0x25, 0x00],
344            ],
345        };
346        let mut buf = vec![0u8; desc.serialized_len()];
347        desc.serialize_into(&mut buf).unwrap();
348        let reparsed = FrequencyListDescriptor::parse(&buf).unwrap();
349        assert_eq!(desc.coding_type, reparsed.coding_type);
350        assert_eq!(desc.centre_frequencies_bcd, reparsed.centre_frequencies_bcd);
351    }
352
353    #[test]
354    fn satellite_frequency_hz_decodes_correctly() {
355        let desc = FrequencyListDescriptor {
356            coding_type: CodingType::Satellite,
357            centre_frequencies_bcd: vec![[0x01, 0x17, 0x25, 0x00]], // 11.72500 GHz
358        };
359        assert_eq!(desc.centre_frequencies_hz(), vec![Some(11_725_000_000)]);
360    }
361
362    #[test]
363    fn cable_frequency_hz_decodes_correctly() {
364        let desc = FrequencyListDescriptor {
365            coding_type: CodingType::Cable,
366            centre_frequencies_bcd: vec![[0x03, 0x46, 0x00, 0x00]], // 346.0000 MHz
367        };
368        assert_eq!(desc.centre_frequencies_hz(), vec![Some(346_000_000)]);
369    }
370
371    #[test]
372    fn terrestrial_frequency_hz_decodes_binary() {
373        let desc = FrequencyListDescriptor {
374            coding_type: CodingType::Terrestrial,
375            // binary 0x04A858F0 = 78_141_680 × 10 Hz = 781_416_800 Hz
376            centre_frequencies_bcd: vec![[0x04, 0xA8, 0x58, 0xF0]],
377        };
378        assert_eq!(desc.centre_frequencies_hz(), vec![Some(781_416_800)]);
379    }
380
381    #[test]
382    fn set_satellite_frequencies_hz_round_trips() {
383        let mut desc = FrequencyListDescriptor {
384            coding_type: CodingType::Satellite,
385            centre_frequencies_bcd: vec![],
386        };
387        desc.set_centre_frequencies_hz(&[11_725_000_000]).unwrap();
388        assert_eq!(desc.centre_frequencies_hz(), vec![Some(11_725_000_000)]);
389        assert_eq!(desc.centre_frequencies_bcd[0], [0x01, 0x17, 0x25, 0x00]);
390    }
391
392    #[test]
393    fn set_terrestrial_frequencies_hz_round_trips() {
394        let mut desc = FrequencyListDescriptor {
395            coding_type: CodingType::Terrestrial,
396            centre_frequencies_bcd: vec![],
397        };
398        desc.set_centre_frequencies_hz(&[781_416_800]).unwrap();
399        assert_eq!(desc.centre_frequencies_hz(), vec![Some(781_416_800)]);
400        assert_eq!(desc.centre_frequencies_bcd[0], [0x04, 0xA8, 0x58, 0xF0]);
401    }
402
403    #[test]
404    fn set_cable_frequencies_hz_round_trips() {
405        let mut desc = FrequencyListDescriptor {
406            coding_type: CodingType::Cable,
407            centre_frequencies_bcd: vec![],
408        };
409        desc.set_centre_frequencies_hz(&[346_000_000]).unwrap();
410        assert_eq!(desc.centre_frequencies_hz(), vec![Some(346_000_000)]);
411    }
412}