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