1use crate::error::{Error, Result};
8use crate::traits::Descriptor;
9use dvb_common::{Parse, Serialize};
10
11pub const TAG: u8 = 0x62;
13pub const HEADER_LEN: usize = 2;
15pub const CODING_BYTE_LEN: usize = 1;
17pub const ENTRY_LEN: usize = 4;
19pub const CODING_TYPE_MASK: u8 = 0x03;
21pub const RESERVED_BITS_MASK: u8 = 0xFC;
23
24#[derive(Debug, Clone, Copy, PartialEq, Eq)]
26#[cfg_attr(feature = "serde", derive(serde::Serialize))]
27pub enum CodingType {
28 Undefined,
30 Satellite,
32 Cable,
34 Terrestrial,
36}
37
38#[derive(Debug, Clone, PartialEq, Eq)]
40#[cfg_attr(feature = "serde", derive(serde::Serialize))]
41pub struct FrequencyListDescriptor {
42 pub coding_type: CodingType,
44 pub centre_frequencies_bcd: Vec<[u8; 4]>,
46}
47
48impl FrequencyListDescriptor {
49 #[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 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 #[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 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 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 #[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 #[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 #[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 #[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 #[test]
275 fn parse_extracts_multiple_frequency_entries() {
276 let raw: Vec<u8> = vec![
277 TAG, 0x09, 0xFD, 0x02, 0x75, 0x00, 0x00, 0x03, 0x00, 0x00, 0x00, ];
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 #[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 #[test]
301 fn parse_ignores_reserved_bits() {
302 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 #[test]
311 fn parse_rejects_length_not_1_plus_multiple_of_4() {
312 let raw: Vec<u8> = vec![TAG, 0x03, 0xFC, 0x01, 0x02]; let err = FrequencyListDescriptor::parse(&raw).unwrap_err();
314 assert!(matches!(err, Error::InvalidDescriptor { .. }));
315 }
316
317 #[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 #[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 #[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}