1use super::cable_delivery_system::FecInner;
7use super::descriptor_body;
8use crate::error::{Error, Result};
9use broadcast_common::{Parse, Serialize};
10
11pub const TAG: u8 = 0x43;
13const HEADER_LEN: usize = 2;
14const BODY_LEN: u8 = 11;
15
16#[derive(Debug, Clone, Copy, PartialEq, Eq)]
18#[cfg_attr(feature = "serde", derive(serde::Serialize))]
19#[non_exhaustive]
20pub enum Polarization {
21 LinearHorizontal,
23 LinearVertical,
25 CircularLeft,
27 CircularRight,
29}
30
31impl Polarization {
32 #[must_use]
34 pub fn name(self) -> &'static str {
35 match self {
36 Self::LinearHorizontal => "linear horizontal",
37 Self::LinearVertical => "linear vertical",
38 Self::CircularLeft => "circular left",
39 Self::CircularRight => "circular right",
40 }
41 }
42
43 #[must_use]
44 pub fn from_u8(v: u8) -> Self {
46 match v & 0x03 {
47 0 => Polarization::LinearHorizontal,
48 1 => Polarization::LinearVertical,
49 2 => Polarization::CircularLeft,
50 _ => Polarization::CircularRight,
51 }
52 }
53
54 #[must_use]
55 pub const fn to_u8(self) -> u8 {
57 match self {
58 Polarization::LinearHorizontal => 0,
59 Polarization::LinearVertical => 1,
60 Polarization::CircularLeft => 2,
61 Polarization::CircularRight => 3,
62 }
63 }
64}
65broadcast_common::impl_spec_display!(Polarization);
66
67#[derive(Debug, Clone, Copy, PartialEq, Eq)]
69#[cfg_attr(feature = "serde", derive(serde::Serialize))]
70#[non_exhaustive]
71pub enum ModulationSystem {
72 DvbS,
74 DvbS2,
76}
77
78impl ModulationSystem {
79 #[must_use]
81 pub fn name(self) -> &'static str {
82 match self {
83 Self::DvbS => "DVB-S",
84 Self::DvbS2 => "DVB-S2",
85 }
86 }
87}
88broadcast_common::impl_spec_display!(ModulationSystem);
89
90#[derive(Debug, Clone, Copy, PartialEq, Eq)]
92#[cfg_attr(feature = "serde", derive(serde::Serialize))]
93#[non_exhaustive]
94pub enum ModulationType {
95 Auto,
97 Qpsk,
99 Psk8,
101 Qam16,
103}
104
105impl ModulationType {
106 #[must_use]
108 pub fn name(self) -> &'static str {
109 match self {
110 Self::Auto => "Auto",
111 Self::Qpsk => "QPSK",
112 Self::Psk8 => "8PSK",
113 Self::Qam16 => "16-QAM",
114 }
115 }
116}
117broadcast_common::impl_spec_display!(ModulationType);
118
119#[derive(Debug, Clone, Copy, PartialEq, Eq)]
122#[cfg_attr(feature = "serde", derive(serde::Serialize))]
123#[non_exhaustive]
124pub enum RollOff {
125 Alpha035,
127 Alpha025,
129 Alpha020,
131 Reserved(u8),
134}
135
136impl RollOff {
137 #[must_use]
138 pub fn from_u8(v: u8) -> Self {
140 match v {
141 0 => RollOff::Alpha035,
142 1 => RollOff::Alpha025,
143 2 => RollOff::Alpha020,
144 other => RollOff::Reserved(other),
145 }
146 }
147
148 #[must_use]
149 pub const fn to_u8(self) -> u8 {
151 match self {
152 RollOff::Alpha035 => 0,
153 RollOff::Alpha025 => 1,
154 RollOff::Alpha020 => 2,
155 RollOff::Reserved(v) => v,
156 }
157 }
158
159 #[must_use]
161 pub fn name(self) -> &'static str {
162 match self {
163 Self::Alpha035 => "α=0.35",
164 Self::Alpha025 => "α=0.25",
165 Self::Alpha020 => "α=0.20",
166 Self::Reserved(_) => "reserved",
167 }
168 }
169}
170broadcast_common::impl_spec_display!(RollOff, Reserved);
171
172#[derive(Debug, Clone, PartialEq, Eq)]
174#[cfg_attr(feature = "serde", derive(serde::Serialize))]
175pub struct SatelliteDeliverySystemDescriptor {
176 pub frequency_bcd: u32,
178 pub orbital_position_bcd: u16,
180 pub east: bool,
182 pub polarization: Polarization,
184 pub roll_off: RollOff,
188 pub modulation_system: ModulationSystem,
190 pub modulation_type: ModulationType,
192 pub symbol_rate_bcd: u32,
194 pub fec_inner: FecInner,
196}
197
198impl SatelliteDeliverySystemDescriptor {
199 #[must_use]
204 pub fn frequency_hz(&self) -> Option<u64> {
205 broadcast_common::bcd::bcd_to_decimal(u64::from(self.frequency_bcd), 8).map(|v| v * 10_000)
206 }
207
208 pub fn set_frequency_hz(&mut self, hz: u64) -> crate::Result<()> {
215 self.frequency_bcd = super::encode_bcd_field(
216 hz / 10_000,
217 8,
218 "SatelliteDeliverySystemDescriptor::frequency",
219 )? as u32;
220 Ok(())
221 }
222
223 #[must_use]
228 pub fn symbol_rate_sps(&self) -> Option<u64> {
229 broadcast_common::bcd::bcd_to_decimal(u64::from(self.symbol_rate_bcd), 7).map(|v| v * 100)
230 }
231
232 pub fn set_symbol_rate_sps(&mut self, sps: u64) -> crate::Result<()> {
238 self.symbol_rate_bcd = super::encode_bcd_field(
239 sps / 100,
240 7,
241 "SatelliteDeliverySystemDescriptor::symbol_rate",
242 )? as u32;
243 Ok(())
244 }
245
246 #[must_use]
249 pub fn orbital_position_deg(&self) -> Option<f64> {
250 broadcast_common::bcd::bcd_to_decimal(u64::from(self.orbital_position_bcd), 4)
251 .map(|tenths| tenths as f64 / 10.0)
252 }
253
254 pub fn set_orbital_position_deg(&mut self, deg: f64) -> crate::Result<()> {
261 if !(0.0..=6_553.5).contains(°) {
262 return Err(crate::Error::ValueOutOfRange {
263 field: "SatelliteDeliverySystemDescriptor::orbital_position",
264 reason: "degrees must be in 0.0..=6553.5",
265 });
266 }
267 let tenths = libm::round(deg * 10.0) as u64;
268 self.orbital_position_bcd = super::encode_bcd_field(
269 tenths,
270 4,
271 "SatelliteDeliverySystemDescriptor::orbital_position",
272 )? as u16;
273 Ok(())
274 }
275}
276
277impl<'a> Parse<'a> for SatelliteDeliverySystemDescriptor {
278 type Error = crate::error::Error;
279 fn parse(bytes: &'a [u8]) -> Result<Self> {
280 let body = descriptor_body(
281 bytes,
282 TAG,
283 "SatelliteDeliverySystemDescriptor",
284 "expected tag 0x43",
285 )?;
286
287 if body.len() != BODY_LEN as usize {
288 return Err(Error::InvalidDescriptor {
289 tag: TAG,
290 reason: "descriptor_length must equal 11",
291 });
292 }
293
294 let (hdr, _) = body
295 .split_first_chunk::<11>()
296 .ok_or(Error::InvalidDescriptor {
297 tag: TAG,
298 reason: "descriptor_length must equal 11",
299 })?;
300
301 let frequency_bcd = u32::from_be_bytes([hdr[0], hdr[1], hdr[2], hdr[3]]);
303
304 let orbital_position_bcd = u16::from_be_bytes([hdr[4], hdr[5]]);
306
307 let flags = hdr[6];
310 let east = (flags & 0x80) != 0;
311
312 let pol_raw = (flags >> 5) & 0x03;
313 let polarization = match pol_raw {
314 0 => Polarization::LinearHorizontal,
315 1 => Polarization::LinearVertical,
316 2 => Polarization::CircularLeft,
317 _ => Polarization::CircularRight,
318 };
319
320 let roll_raw = (flags >> 3) & 0x03;
321 let roll_off = match roll_raw {
322 0 => RollOff::Alpha035,
323 1 => RollOff::Alpha025,
324 2 => RollOff::Alpha020,
325 v => RollOff::Reserved(v),
326 };
327
328 let mod_sys_raw = (flags >> 2) & 0x01;
329 let modulation_system = match mod_sys_raw {
330 0 => ModulationSystem::DvbS,
331 _ => ModulationSystem::DvbS2,
332 };
333
334 let mod_type_raw = flags & 0x03;
335 let modulation_type = match mod_type_raw {
336 0 => ModulationType::Auto,
337 1 => ModulationType::Qpsk,
338 2 => ModulationType::Psk8,
339 _ => ModulationType::Qam16,
340 };
341
342 let symbol_rate_and_fec = u32::from_be_bytes([hdr[7], hdr[8], hdr[9], hdr[10]]);
344 let symbol_rate_bcd = symbol_rate_and_fec >> 4;
345 let fec_inner = FecInner::from_u8((symbol_rate_and_fec & 0x0F) as u8);
346
347 Ok(SatelliteDeliverySystemDescriptor {
348 frequency_bcd,
349 orbital_position_bcd,
350 east,
351 polarization,
352 roll_off,
353 modulation_system,
354 modulation_type,
355 symbol_rate_bcd,
356 fec_inner,
357 })
358 }
359}
360
361impl Serialize for SatelliteDeliverySystemDescriptor {
362 type Error = crate::error::Error;
363 fn serialized_len(&self) -> usize {
364 HEADER_LEN + BODY_LEN as usize
365 }
366
367 fn serialize_into(&self, buf: &mut [u8]) -> Result<usize> {
368 let len = self.serialized_len();
369 if buf.len() < len {
370 return Err(Error::OutputBufferTooSmall {
371 need: len,
372 have: buf.len(),
373 });
374 }
375
376 buf[0] = TAG;
377 buf[1] = BODY_LEN;
378
379 let freq_bytes = self.frequency_bcd.to_be_bytes();
381 buf[2..6].copy_from_slice(&freq_bytes);
382
383 let orb_bytes = self.orbital_position_bcd.to_be_bytes();
385 buf[6..8].copy_from_slice(&orb_bytes);
386
387 let mut flags: u8 = 0;
389 if self.east {
390 flags |= 0x80;
391 }
392 flags |= match self.polarization {
393 Polarization::LinearHorizontal => 0x00,
394 Polarization::LinearVertical => 0x20,
395 Polarization::CircularLeft => 0x40,
396 Polarization::CircularRight => 0x60,
397 };
398 if self.modulation_system == ModulationSystem::DvbS2 {
401 flags |= match self.roll_off {
402 RollOff::Alpha035 => 0x00,
403 RollOff::Alpha025 => 0x08,
404 RollOff::Alpha020 => 0x10,
405 RollOff::Reserved(v) => (v & 0x03) << 3,
406 };
407 }
408 flags |= match self.modulation_system {
409 ModulationSystem::DvbS => 0x00,
410 ModulationSystem::DvbS2 => 0x04,
411 };
412 flags |= match self.modulation_type {
413 ModulationType::Auto => 0x00,
414 ModulationType::Qpsk => 0x01,
415 ModulationType::Psk8 => 0x02,
416 ModulationType::Qam16 => 0x03,
417 };
418 buf[8] = flags;
419
420 let sym_freq = ((self.symbol_rate_bcd & 0x0FFF_FFFF) << 4)
423 | (u32::from(self.fec_inner.to_u8()) & 0x0F);
424 let sym_bytes = sym_freq.to_be_bytes();
425 buf[9..13].copy_from_slice(&sym_bytes);
426
427 Ok(len)
428 }
429}
430impl crate::traits::DescriptorDef<'_> for SatelliteDeliverySystemDescriptor {
431 const TAG: u8 = TAG;
432 const NAME: &'static str = "SATELLITE_DELIVERY_SYSTEM";
433}
434
435#[cfg(test)]
436mod tests {
437 use super::*;
438
439 #[test]
442 fn parse_extracts_frequency_and_orbital_position() {
443 let raw: Vec<u8> = vec![
446 TAG, BODY_LEN, 0x01, 0x17, 0x25, 0x00, 0x19, 0x20, 0x00, 0x02, 0x75, 0x00, 0x00, ];
451 let desc = SatelliteDeliverySystemDescriptor::parse(&raw).unwrap();
452 assert_eq!(desc.frequency_bcd, 0x01172500);
453 assert_eq!(desc.orbital_position_bcd, 0x1920);
454 }
455
456 #[test]
458 fn parse_extracts_west_east_flag() {
459 let raw_east: Vec<u8> = vec![
461 TAG, BODY_LEN, 0x01, 0x17, 0x25, 0x00, 0x19, 0x20,
462 0x80, 0x02, 0x75, 0x00, 0x00,
464 ];
465 let desc_east = SatelliteDeliverySystemDescriptor::parse(&raw_east).unwrap();
466 assert!(desc_east.east, "east should be true when bit 7 is set");
467
468 let raw_west: Vec<u8> = vec![
470 TAG, BODY_LEN, 0x01, 0x17, 0x25, 0x00, 0x19, 0x20, 0x00, 0x02, 0x75, 0x00, 0x00,
472 ];
473 let desc_west = SatelliteDeliverySystemDescriptor::parse(&raw_west).unwrap();
474 assert!(!desc_west.east, "east should be false when bit 7 is clear");
475 }
476
477 #[test]
479 fn parse_extracts_polarization_variants() {
480 let pol_pairs: [(u8, Polarization); 4] = [
481 (0x00, Polarization::LinearHorizontal),
482 (0x20, Polarization::LinearVertical),
483 (0x40, Polarization::CircularLeft),
484 (0x60, Polarization::CircularRight),
485 ];
486
487 for (offset, expected_pol) in pol_pairs {
488 let raw: Vec<u8> = vec![
489 TAG, BODY_LEN, 0x01, 0x17, 0x25, 0x00, 0x19, 0x20,
490 offset, 0x02, 0x75, 0x00, 0x00,
492 ];
493 let desc = SatelliteDeliverySystemDescriptor::parse(&raw).unwrap();
494 assert_eq!(
495 desc.polarization, expected_pol,
496 "polarization mismatch for offset 0x{offset:02x}"
497 );
498 }
499 }
500
501 #[test]
503 fn parse_extracts_modulation_system_and_type() {
504 let raw: Vec<u8> = vec![
506 TAG, BODY_LEN, 0x01, 0x17, 0x25, 0x00, 0x19, 0x20, 0x01, 0x02, 0x75, 0x00, 0x00,
508 ];
509 let desc = SatelliteDeliverySystemDescriptor::parse(&raw).unwrap();
510 assert_eq!(desc.modulation_system, ModulationSystem::DvbS);
511 assert_eq!(desc.modulation_type, ModulationType::Qpsk);
512
513 let raw2: Vec<u8> = vec![
515 TAG, BODY_LEN, 0x01, 0x17, 0x25, 0x00, 0x19, 0x20,
516 0x06, 0x02, 0x75, 0x00, 0x00,
518 ];
519 let desc2 = SatelliteDeliverySystemDescriptor::parse(&raw2).unwrap();
520 assert_eq!(desc2.modulation_system, ModulationSystem::DvbS2);
521 assert_eq!(desc2.modulation_type, ModulationType::Psk8);
522 }
523
524 #[test]
526 fn parse_extracts_roll_off() {
527 let roll_pairs: [(u8, RollOff); 4] = [
528 (0x00, RollOff::Alpha035),
529 (0x08, RollOff::Alpha025),
530 (0x10, RollOff::Alpha020),
531 (0x18, RollOff::Reserved(3)),
532 ];
533
534 for (offset, expected_roll) in roll_pairs {
535 let raw: Vec<u8> = vec![
536 TAG, BODY_LEN, 0x01, 0x17, 0x25, 0x00, 0x19, 0x20, offset, 0x02, 0x75, 0x00, 0x00,
538 ];
539 let desc = SatelliteDeliverySystemDescriptor::parse(&raw).unwrap();
540 assert_eq!(desc.roll_off, expected_roll);
541 }
542 }
543
544 #[test]
547 fn parse_extracts_symbol_rate_and_fec() {
548 let raw: Vec<u8> = vec![
550 TAG, BODY_LEN, 0x01, 0x17, 0x25, 0x00, 0x19, 0x20, 0x00, 0x02, 0x75, 0x00,
551 0x04, ];
553 let desc = SatelliteDeliverySystemDescriptor::parse(&raw).unwrap();
554 assert_eq!(desc.symbol_rate_bcd, 0x0275000);
555 assert_eq!(desc.fec_inner, FecInner::Rate5_6);
556
557 let raw2: Vec<u8> = vec![
559 TAG, BODY_LEN, 0x01, 0x17, 0x25, 0x00, 0x19, 0x20, 0x00, 0x02, 0x75, 0x00,
560 0x0F, ];
562 let desc2 = SatelliteDeliverySystemDescriptor::parse(&raw2).unwrap();
563 assert_eq!(desc2.fec_inner, FecInner::NoConvCoding);
564 }
565
566 #[test]
568 fn parse_rejects_wrong_tag() {
569 let raw: Vec<u8> = vec![
570 0x44, BODY_LEN, 0x01, 0x17, 0x25, 0x00, 0x19, 0x20, 0x00, 0x02, 0x75, 0x00, 0x00,
572 ];
573 let err = SatelliteDeliverySystemDescriptor::parse(&raw).unwrap_err();
574 assert!(
575 matches!(err, Error::InvalidDescriptor { tag: 0x44, .. }),
576 "expected InvalidDescriptor(tag=0x44), got {err:?}"
577 );
578 }
579
580 #[test]
582 fn parse_rejects_wrong_length() {
583 let raw: Vec<u8> = vec![
584 TAG, 0x05, 0x11, 0x72, 0x50, 0x00, 0x19, 0x20,
586 ];
587 let err = SatelliteDeliverySystemDescriptor::parse(&raw).unwrap_err();
588 assert!(
589 matches!(
590 err,
591 Error::InvalidDescriptor {
592 reason: "descriptor_length must equal 11",
593 ..
594 }
595 ),
596 "expected InvalidDescriptor about length, got {err:?}"
597 );
598 }
599
600 #[test]
603 fn serialize_round_trip() {
604 let desc = SatelliteDeliverySystemDescriptor {
605 frequency_bcd: 0x01172500,
606 orbital_position_bcd: 0x1920,
607 east: true,
608 polarization: Polarization::CircularRight,
609 roll_off: RollOff::Alpha025,
610 modulation_system: ModulationSystem::DvbS2,
611 modulation_type: ModulationType::Psk8,
612 symbol_rate_bcd: 0x027500,
613 fec_inner: FecInner::Rate5_6,
614 };
615
616 let mut buf = vec![0u8; desc.serialized_len()];
617 let written = desc.serialize_into(&mut buf).unwrap();
618 assert_eq!(written, desc.serialized_len());
619
620 let reparsed = SatelliteDeliverySystemDescriptor::parse(&buf).unwrap();
621 assert_eq!(desc, reparsed);
622 }
623
624 #[test]
626 fn reserved_roll_off_round_trips() {
627 let desc = SatelliteDeliverySystemDescriptor {
628 frequency_bcd: 0x01172500,
629 orbital_position_bcd: 0x1920,
630 east: true,
631 polarization: Polarization::CircularRight,
632 roll_off: RollOff::Reserved(3),
633 modulation_system: ModulationSystem::DvbS2,
634 modulation_type: ModulationType::Psk8,
635 symbol_rate_bcd: 0x027500,
636 fec_inner: FecInner::Rate5_6,
637 };
638
639 let mut buf = vec![0u8; desc.serialized_len()];
640 desc.serialize_into(&mut buf).unwrap();
641 assert_eq!(buf[8] & 0x18, 0x18); let reparsed = SatelliteDeliverySystemDescriptor::parse(&buf).unwrap();
644 assert_eq!(reparsed.roll_off, RollOff::Reserved(3));
645 }
646
647 #[test]
648 fn frequency_hz_round_trip() {
649 let mut desc = SatelliteDeliverySystemDescriptor {
650 frequency_bcd: 0,
651 orbital_position_bcd: 0x1920,
652 east: true,
653 polarization: Polarization::LinearHorizontal,
654 roll_off: RollOff::Alpha035,
655 modulation_system: ModulationSystem::DvbS,
656 modulation_type: ModulationType::Auto,
657 symbol_rate_bcd: 0x027500,
658 fec_inner: FecInner::Rate5_6,
659 };
660 desc.set_frequency_hz(11_725_000_000).unwrap();
661 assert_eq!(desc.frequency_hz(), Some(11_725_000_000));
662 assert_eq!(desc.frequency_bcd, 0x01172500);
663 }
664}