1use super::descriptor_body;
8use crate::error::{Error, Result};
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
38impl CodingType {
39 #[must_use]
41 pub fn name(self) -> &'static str {
42 match self {
43 Self::Undefined => "not defined",
44 Self::Satellite => "satellite",
45 Self::Cable => "cable",
46 Self::Terrestrial => "terrestrial",
47 }
48 }
49}
50dvb_common::impl_spec_display!(CodingType);
51
52#[derive(Debug, Clone, PartialEq, Eq)]
54#[cfg_attr(feature = "serde", derive(serde::Serialize))]
55pub struct FrequencyListDescriptor {
56 pub coding_type: CodingType,
58 pub centre_frequencies_bcd: Vec<[u8; 4]>,
61}
62
63impl FrequencyListDescriptor {
64 fn hz_per_unit_bcd(&self) -> Option<u64> {
67 match self.coding_type {
68 CodingType::Satellite => Some(10_000),
69 CodingType::Cable => Some(100),
70 CodingType::Terrestrial | CodingType::Undefined => None,
71 }
72 }
73
74 #[must_use]
78 pub fn centre_frequencies_hz(&self) -> Vec<Option<u64>> {
79 match self.coding_type {
80 CodingType::Satellite | CodingType::Cable => {
81 let scale = self.hz_per_unit_bcd().unwrap();
82 self.centre_frequencies_bcd
83 .iter()
84 .map(|b| {
85 let value =
86 dvb_common::bcd::bcd_to_decimal(u64::from(u32::from_be_bytes(*b)), 8)?;
87 Some(value * scale)
88 })
89 .collect()
90 }
91 CodingType::Terrestrial => self
92 .centre_frequencies_bcd
93 .iter()
94 .map(|b| Some(u64::from(u32::from_be_bytes(*b)) * 10))
95 .collect(),
96 CodingType::Undefined => self.centre_frequencies_bcd.iter().map(|_| None).collect(),
97 }
98 }
99
100 pub fn set_centre_frequencies_hz(&mut self, frequencies_hz: &[u64]) -> crate::Result<()> {
108 match self.coding_type {
109 CodingType::Satellite | CodingType::Cable => {
110 let scale = self
111 .hz_per_unit_bcd()
112 .ok_or(crate::Error::ValueOutOfRange {
113 field: "FrequencyListDescriptor::centre_frequency",
114 reason: "coding_type is Undefined; cannot encode frequencies",
115 })?;
116 let mut out = Vec::with_capacity(frequencies_hz.len());
117 for &hz in frequencies_hz {
118 let bcd = super::encode_bcd_field(
119 hz / scale,
120 8,
121 "FrequencyListDescriptor::centre_frequency",
122 )?;
123 out.push((bcd as u32).to_be_bytes());
124 }
125 self.centre_frequencies_bcd = out;
126 Ok(())
127 }
128 CodingType::Terrestrial => {
129 let mut out = Vec::with_capacity(frequencies_hz.len());
130 for &hz in frequencies_hz {
131 let units = hz / 10;
132 if units > u64::from(u32::MAX) {
133 return Err(Error::ValueOutOfRange {
134 field: "frequency_list centre_frequency",
135 reason: "terrestrial frequency exceeds the 32-bit (×10 Hz) wire field",
136 });
137 }
138 out.push((units as u32).to_be_bytes());
139 }
140 self.centre_frequencies_bcd = out;
141 Ok(())
142 }
143 CodingType::Undefined => Err(crate::Error::ValueOutOfRange {
144 field: "FrequencyListDescriptor::centre_frequency",
145 reason: "coding_type is Undefined; cannot encode frequencies",
146 }),
147 }
148 }
149}
150
151impl<'a> Parse<'a> for FrequencyListDescriptor {
152 type Error = crate::error::Error;
153 fn parse(bytes: &'a [u8]) -> Result<Self> {
154 let body = descriptor_body(bytes, TAG, "FrequencyListDescriptor", "expected tag 0x62")?;
155
156 if body.len() < CODING_BYTE_LEN {
157 return Err(Error::InvalidDescriptor {
158 tag: TAG,
159 reason: "body too short (need at least coding_type byte)",
160 });
161 }
162
163 if (body.len() - CODING_BYTE_LEN) % ENTRY_LEN != 0 {
164 return Err(Error::InvalidDescriptor {
165 tag: TAG,
166 reason: "body length minus coding byte must be multiple of 4",
167 });
168 }
169
170 let coding_byte = body[0];
171 let coding_type_value = coding_byte & CODING_TYPE_MASK;
174 let coding_type = match coding_type_value {
175 0b00 => CodingType::Undefined,
176 0b01 => CodingType::Satellite,
177 0b10 => CodingType::Cable,
178 _ => CodingType::Terrestrial,
179 };
180
181 let entry_count = (body.len() - CODING_BYTE_LEN) / ENTRY_LEN;
182 let mut centre_frequencies_bcd = Vec::with_capacity(entry_count);
183
184 let mut offset = CODING_BYTE_LEN;
185 for _ in 0..entry_count {
186 let mut entry = [0u8; ENTRY_LEN];
187 entry.copy_from_slice(&body[offset..offset + ENTRY_LEN]);
188 centre_frequencies_bcd.push(entry);
189 offset += ENTRY_LEN;
190 }
191
192 Ok(FrequencyListDescriptor {
193 coding_type,
194 centre_frequencies_bcd,
195 })
196 }
197}
198
199impl Serialize for FrequencyListDescriptor {
200 type Error = crate::error::Error;
201 fn serialized_len(&self) -> usize {
202 HEADER_LEN + CODING_BYTE_LEN + self.centre_frequencies_bcd.len() * ENTRY_LEN
203 }
204
205 fn serialize_into(&self, buf: &mut [u8]) -> Result<usize> {
206 let need = self.serialized_len();
207 if buf.len() < need {
208 return Err(Error::OutputBufferTooSmall {
209 need,
210 have: buf.len(),
211 });
212 }
213
214 let coding_type_bits = match self.coding_type {
215 CodingType::Undefined => 0b00,
216 CodingType::Satellite => 0b01,
217 CodingType::Cable => 0b10,
218 CodingType::Terrestrial => 0b11,
219 };
220
221 let body_length = CODING_BYTE_LEN + self.centre_frequencies_bcd.len() * ENTRY_LEN;
222
223 buf[0] = TAG;
224 buf[1] = body_length as u8;
225 buf[HEADER_LEN] = RESERVED_BITS_MASK | coding_type_bits;
226
227 let mut offset = HEADER_LEN + CODING_BYTE_LEN;
228 for entry in &self.centre_frequencies_bcd {
229 buf[offset..offset + ENTRY_LEN].copy_from_slice(entry);
230 offset += ENTRY_LEN;
231 }
232
233 Ok(need)
234 }
235}
236impl<'a> crate::traits::DescriptorDef<'a> for FrequencyListDescriptor {
237 const TAG: u8 = TAG;
238 const NAME: &'static str = "FREQUENCY_LIST";
239}
240
241#[cfg(test)]
242mod tests {
243 use super::*;
244
245 #[test]
247 fn parse_empty_entries_is_valid() {
248 let raw: Vec<u8> = vec![TAG, 0x01, 0xFC];
249 let desc = FrequencyListDescriptor::parse(&raw).unwrap();
250 assert!(desc.centre_frequencies_bcd.is_empty());
251 assert!(matches!(desc.coding_type, CodingType::Undefined));
252 }
253
254 #[test]
256 fn parse_extracts_coding_type_satellite() {
257 let raw: Vec<u8> = vec![TAG, 0x01, 0xFD];
258 let desc = FrequencyListDescriptor::parse(&raw).unwrap();
259 assert!(matches!(desc.coding_type, CodingType::Satellite));
260 }
261
262 #[test]
264 fn parse_extracts_coding_type_cable() {
265 let raw: Vec<u8> = vec![TAG, 0x01, 0xFE];
266 let desc = FrequencyListDescriptor::parse(&raw).unwrap();
267 assert!(matches!(desc.coding_type, CodingType::Cable));
268 }
269
270 #[test]
272 fn parse_extracts_coding_type_terrestrial() {
273 let raw: Vec<u8> = vec![TAG, 0x01, 0xFF];
274 let desc = FrequencyListDescriptor::parse(&raw).unwrap();
275 assert!(matches!(desc.coding_type, CodingType::Terrestrial));
276 }
277
278 #[test]
280 fn parse_extracts_multiple_frequency_entries() {
281 let raw: Vec<u8> = vec![
282 TAG, 0x09, 0xFD, 0x00, 0x30, 0x12, 0x34, 0x00, 0x30, 0x00, 0x00, ];
287 let desc = FrequencyListDescriptor::parse(&raw).unwrap();
288 assert_eq!(desc.centre_frequencies_bcd.len(), 2);
289 assert_eq!(desc.centre_frequencies_bcd[0], [0x00, 0x30, 0x12, 0x34]);
290 assert_eq!(desc.centre_frequencies_bcd[1], [0x00, 0x30, 0x00, 0x00]);
291 }
292
293 #[test]
295 fn parse_rejects_wrong_tag() {
296 let raw: Vec<u8> = vec![0x63, 0x01, 0xFC];
297 let err = FrequencyListDescriptor::parse(&raw).unwrap_err();
298 assert!(
299 matches!(err, Error::InvalidDescriptor { tag: 0x63, .. }),
300 "expected InvalidDescriptor(tag=0x63), got {err:?}"
301 );
302 }
303
304 #[test]
306 fn parse_ignores_reserved_bits() {
307 let raw: Vec<u8> = vec![TAG, 0x01, 0x03];
309 let d = FrequencyListDescriptor::parse(&raw).unwrap();
310 assert_eq!(d.coding_type, CodingType::Terrestrial);
311 assert!(d.centre_frequencies_bcd.is_empty());
312 }
313
314 #[test]
316 fn parse_rejects_length_not_1_plus_multiple_of_4() {
317 let raw: Vec<u8> = vec![TAG, 0x03, 0xFC, 0x01, 0x02]; let err = FrequencyListDescriptor::parse(&raw).unwrap_err();
319 assert!(matches!(err, Error::InvalidDescriptor { .. }));
320 }
321
322 #[test]
324 fn parse_rejects_truncated_buffer() {
325 let raw: &[u8] = &[TAG];
326 let err = FrequencyListDescriptor::parse(raw).unwrap_err();
327 assert!(matches!(err, Error::BufferTooShort { need: 2, .. }));
328 }
329
330 #[test]
332 fn serialize_round_trip_empty() {
333 let desc = FrequencyListDescriptor {
334 coding_type: CodingType::Satellite,
335 centre_frequencies_bcd: vec![],
336 };
337 let raw: Vec<u8> = vec![TAG, 0x01, 0xFD];
338 let mut buf = vec![0u8; desc.serialized_len()];
339 let written = desc.serialize_into(&mut buf).unwrap();
340 assert_eq!(written, raw.len());
341 assert_eq!(buf, raw);
342
343 let reparsed = FrequencyListDescriptor::parse(&buf).unwrap();
344 assert_eq!(desc.coding_type, reparsed.coding_type);
345 assert_eq!(desc.centre_frequencies_bcd, reparsed.centre_frequencies_bcd);
346 }
347
348 #[test]
350 fn serialize_round_trip_many_entries() {
351 let desc = FrequencyListDescriptor {
352 coding_type: CodingType::Cable,
353 centre_frequencies_bcd: vec![
354 [0x03, 0x46, 0x00, 0x00],
355 [0x04, 0x74, 0x00, 0x10],
356 [0x01, 0x15, 0x50, 0x00],
357 [0x04, 0x90, 0x25, 0x00],
358 ],
359 };
360 let mut buf = vec![0u8; desc.serialized_len()];
361 desc.serialize_into(&mut buf).unwrap();
362 let reparsed = FrequencyListDescriptor::parse(&buf).unwrap();
363 assert_eq!(desc.coding_type, reparsed.coding_type);
364 assert_eq!(desc.centre_frequencies_bcd, reparsed.centre_frequencies_bcd);
365 }
366
367 #[test]
368 fn satellite_frequency_hz_decodes_correctly() {
369 let desc = FrequencyListDescriptor {
370 coding_type: CodingType::Satellite,
371 centre_frequencies_bcd: vec![[0x01, 0x17, 0x25, 0x00]], };
373 assert_eq!(desc.centre_frequencies_hz(), vec![Some(11_725_000_000)]);
374 }
375
376 #[test]
377 fn cable_frequency_hz_decodes_correctly() {
378 let desc = FrequencyListDescriptor {
379 coding_type: CodingType::Cable,
380 centre_frequencies_bcd: vec![[0x03, 0x46, 0x00, 0x00]], };
382 assert_eq!(desc.centre_frequencies_hz(), vec![Some(346_000_000)]);
383 }
384
385 #[test]
386 fn terrestrial_frequency_hz_decodes_binary() {
387 let desc = FrequencyListDescriptor {
388 coding_type: CodingType::Terrestrial,
389 centre_frequencies_bcd: vec![[0x04, 0xA8, 0x58, 0xF0]],
391 };
392 assert_eq!(desc.centre_frequencies_hz(), vec![Some(781_416_800)]);
393 }
394
395 #[test]
396 fn set_satellite_frequencies_hz_round_trips() {
397 let mut desc = FrequencyListDescriptor {
398 coding_type: CodingType::Satellite,
399 centre_frequencies_bcd: vec![],
400 };
401 desc.set_centre_frequencies_hz(&[11_725_000_000]).unwrap();
402 assert_eq!(desc.centre_frequencies_hz(), vec![Some(11_725_000_000)]);
403 assert_eq!(desc.centre_frequencies_bcd[0], [0x01, 0x17, 0x25, 0x00]);
404 }
405
406 #[test]
407 fn set_terrestrial_frequencies_hz_round_trips() {
408 let mut desc = FrequencyListDescriptor {
409 coding_type: CodingType::Terrestrial,
410 centre_frequencies_bcd: vec![],
411 };
412 desc.set_centre_frequencies_hz(&[781_416_800]).unwrap();
413 assert_eq!(desc.centre_frequencies_hz(), vec![Some(781_416_800)]);
414 assert_eq!(desc.centre_frequencies_bcd[0], [0x04, 0xA8, 0x58, 0xF0]);
415 }
416
417 #[test]
418 fn set_cable_frequencies_hz_round_trips() {
419 let mut desc = FrequencyListDescriptor {
420 coding_type: CodingType::Cable,
421 centre_frequencies_bcd: vec![],
422 };
423 desc.set_centre_frequencies_hz(&[346_000_000]).unwrap();
424 assert_eq!(desc.centre_frequencies_hz(), vec![Some(346_000_000)]);
425 }
426}