1use super::descriptor_body;
8use crate::error::{Error, Result};
9use alloc::vec::Vec;
10use broadcast_common::{Parse, Serialize};
11
12pub const TAG: u8 = 0x62;
14pub const HEADER_LEN: usize = 2;
16pub const CODING_BYTE_LEN: usize = 1;
18pub const ENTRY_LEN: usize = 4;
20pub const CODING_TYPE_MASK: u8 = 0x03;
22pub const RESERVED_BITS_MASK: u8 = 0xFC;
24
25#[derive(Debug, Clone, Copy, PartialEq, Eq)]
27#[cfg_attr(feature = "serde", derive(serde::Serialize))]
28#[non_exhaustive]
29pub enum CodingType {
30 Undefined,
32 Satellite,
34 Cable,
36 Terrestrial,
38}
39
40impl CodingType {
41 #[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#[derive(Debug, Clone, PartialEq, Eq)]
56#[cfg_attr(feature = "serde", derive(serde::Serialize))]
57pub struct FrequencyListDescriptor {
58 pub coding_type: CodingType,
60 pub centre_frequencies_bcd: Vec<[u8; 4]>,
63}
64
65impl FrequencyListDescriptor {
66 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 #[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 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 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 #[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 #[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 #[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 #[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 #[test]
284 fn parse_extracts_multiple_frequency_entries() {
285 let raw: Vec<u8> = vec![
286 TAG, 0x09, 0xFD, 0x00, 0x30, 0x12, 0x34, 0x00, 0x30, 0x00, 0x00, ];
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 #[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 #[test]
310 fn parse_ignores_reserved_bits() {
311 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 #[test]
320 fn parse_rejects_length_not_1_plus_multiple_of_4() {
321 let raw: Vec<u8> = vec![TAG, 0x03, 0xFC, 0x01, 0x02]; let err = FrequencyListDescriptor::parse(&raw).unwrap_err();
323 assert!(matches!(err, Error::InvalidDescriptor { .. }));
324 }
325
326 #[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 #[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 #[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]], };
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]], };
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 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}