Skip to main content

dvb_si/descriptors/
satellite_delivery_system.rs

1//! Satellite Delivery System Descriptor — ETSI EN 300 468 §6.2.13.2 (tag 0x43).
2//!
3//! Carried inside the NIT's `transport_stream_loop`'s second descriptor loop.
4//! Conveys carrier tuning parameters for a DVB-S / DVB-S2 transponder.
5
6use super::cable_delivery_system::FecInner;
7use super::descriptor_body;
8use crate::error::{Error, Result};
9use dvb_common::{Parse, Serialize};
10
11/// Descriptor tag for satellite_delivery_system_descriptor.
12pub const TAG: u8 = 0x43;
13const HEADER_LEN: usize = 2;
14const BODY_LEN: u8 = 11;
15
16/// Polarization (§6.2.13.2 Table 38).
17#[derive(Debug, Clone, Copy, PartialEq, Eq)]
18#[cfg_attr(feature = "serde", derive(serde::Serialize))]
19#[non_exhaustive]
20pub enum Polarization {
21    /// Linear horizontal.
22    LinearHorizontal,
23    /// Linear vertical.
24    LinearVertical,
25    /// Circular left.
26    CircularLeft,
27    /// Circular right.
28    CircularRight,
29}
30
31impl Polarization {
32    /// Human-readable spec label (ETSI EN 300 468 §6.2.13.2 Table 38).
33    #[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    /// Construct from a raw `u8`; every value maps to a variant (total, lossless).
45    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    /// Inverse of `from_u8`; `Self::Reserved` emits its stored value.
56    pub 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}
65dvb_common::impl_spec_display!(Polarization);
66
67/// Modulation system (§6.2.13.2 Table 40: DVB-S or DVB-S2).
68#[derive(Debug, Clone, Copy, PartialEq, Eq)]
69#[cfg_attr(feature = "serde", derive(serde::Serialize))]
70#[non_exhaustive]
71pub enum ModulationSystem {
72    /// DVB-S (first generation).
73    DvbS,
74    /// DVB-S2 (second generation).
75    DvbS2,
76}
77
78impl ModulationSystem {
79    /// Human-readable spec label (ETSI EN 300 468 §6.2.13.2 Table 40).
80    #[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}
88dvb_common::impl_spec_display!(ModulationSystem);
89
90/// Modulation type (§6.2.13.2 Table 41).
91#[derive(Debug, Clone, Copy, PartialEq, Eq)]
92#[cfg_attr(feature = "serde", derive(serde::Serialize))]
93#[non_exhaustive]
94pub enum ModulationType {
95    /// Auto-detect.
96    Auto,
97    /// QPSK.
98    Qpsk,
99    /// 8PSK.
100    Psk8,
101    /// 16QAM.
102    Qam16,
103}
104
105impl ModulationType {
106    /// Human-readable spec label (ETSI EN 300 468 §6.2.13.2 Table 41).
107    #[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}
117dvb_common::impl_spec_display!(ModulationType);
118
119/// Roll-off factor (§6.2.13.2 Table 39, DVB-S2 only; also used by S2X
120/// with extended values per Table 144).
121#[derive(Debug, Clone, Copy, PartialEq, Eq)]
122#[cfg_attr(feature = "serde", derive(serde::Serialize))]
123#[non_exhaustive]
124pub enum RollOff {
125    /// 0.35 (DVB-S default).
126    Alpha035,
127    /// 0.25 (DVB-S2 common).
128    Alpha025,
129    /// 0.20 (DVB-S2 narrow).
130    Alpha020,
131    /// Reserved — carries the raw value for forward compatibility (2-bit for
132    /// DVB-S/S2, 3-bit for S2X).
133    Reserved(u8),
134}
135
136impl RollOff {
137    #[must_use]
138    /// Construct from a raw `u8`; every value maps to a variant (total, lossless).
139    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    /// Inverse of `from_u8`; `Self::Reserved` emits its stored value.
150    pub 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    /// Human-readable spec label (ETSI EN 300 468 §6.2.13.2 Table 39).
160    #[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}
170dvb_common::impl_spec_display!(RollOff, Reserved);
171
172/// Satellite Delivery System Descriptor.
173#[derive(Debug, Clone, PartialEq, Eq)]
174#[cfg_attr(feature = "serde", derive(serde::Serialize))]
175pub struct SatelliteDeliverySystemDescriptor {
176    /// 32-bit BCD frequency in GHz (e.g. `0x01172500` = 11.72500 GHz = 11_725_000_000 Hz).
177    pub frequency_bcd: u32,
178    /// 16-bit BCD orbital position tenths of a degree (e.g. 0x1920 = 192.0°).
179    pub orbital_position_bcd: u16,
180    /// False = west, true = east.
181    pub east: bool,
182    /// Polarization.
183    pub polarization: Polarization,
184    /// DVB-S2 roll-off factor. Meaningful only when `modulation_system` is
185    /// DVB-S2 (Table 37); for DVB-S the bits are reserved_zero_future_use and
186    /// serialize emits them as 0 regardless of this field.
187    pub roll_off: RollOff,
188    /// Modulation system.
189    pub modulation_system: ModulationSystem,
190    /// Modulation type.
191    pub modulation_type: ModulationType,
192    /// 28-bit BCD symbol rate in Msym/s (e.g. 0x0275_000 = 27.500 Msym/s).
193    pub symbol_rate_bcd: u32,
194    /// 4-bit FEC inner code — ETSI EN 300 468 Table 36.
195    pub fec_inner: FecInner,
196}
197
198impl SatelliteDeliverySystemDescriptor {
199    /// Decode the 32-bit BCD `frequency` to Hz (10 kHz field resolution,
200    /// EN 300 468 §6.2.13.2). `None` if the BCD nibbles are out of range.
201    ///
202    /// e.g. `0x0117_2500` → `11_725_000_000` Hz (11.72500 GHz).
203    #[must_use]
204    pub fn frequency_hz(&self) -> Option<u64> {
205        dvb_common::bcd::bcd_to_decimal(u64::from(self.frequency_bcd), 8).map(|v| v * 10_000)
206    }
207
208    /// Set `frequency` from Hz, encoding to the 8-digit BCD field at the field's
209    /// 10 kHz resolution (sub-10 kHz precision is truncated).
210    ///
211    /// # Errors
212    /// [`ValueOutOfRange`](crate::Error::ValueOutOfRange) if the value
213    /// exceeds the 8-digit BCD field.
214    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    /// Decode the 28-bit BCD `symbol_rate` to symbols/second (100 sym/s
224    /// resolution). `None` if the BCD nibbles are out of range.
225    ///
226    /// e.g. `0x027_5000` → `27_500_000` (27.5 Msym/s).
227    #[must_use]
228    pub fn symbol_rate_sps(&self) -> Option<u64> {
229        dvb_common::bcd::bcd_to_decimal(u64::from(self.symbol_rate_bcd), 7).map(|v| v * 100)
230    }
231
232    /// Set `symbol_rate` from symbols/second (100 sym/s field resolution).
233    ///
234    /// # Errors
235    /// [`ValueOutOfRange`](crate::Error::ValueOutOfRange) on overflow of
236    /// the 7-digit BCD field.
237    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    /// Decode the 16-bit BCD `orbital_position` to degrees (tenths resolution).
247    /// `None` if the BCD nibbles are out of range. e.g. `0x1920` → `192.0`.
248    #[must_use]
249    pub fn orbital_position_deg(&self) -> Option<f64> {
250        dvb_common::bcd::bcd_to_decimal(u64::from(self.orbital_position_bcd), 4)
251            .map(|tenths| tenths as f64 / 10.0)
252    }
253
254    /// Set `orbital_position` in degrees, rounded to the field's tenth-degree
255    /// resolution. The east/west `east` flag is a separate field.
256    ///
257    /// # Errors
258    /// [`ValueOutOfRange`](crate::Error::ValueOutOfRange) if negative or
259    /// beyond the 4-digit BCD field.
260    pub fn set_orbital_position_deg(&mut self, deg: f64) -> crate::Result<()> {
261        if !(0.0..=6_553.5).contains(&deg) {
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        // Frequency: 4 bytes BCD (GHz.MMMM)
295        let frequency_bcd = u32::from_be_bytes([body[0], body[1], body[2], body[3]]);
296
297        // Orbital position: 2 bytes BCD (tenths of a degree)
298        let orbital_position_bcd = u16::from_be_bytes([body[4], body[5]]);
299
300        // Flags byte 6: bit 7 = west_east_flag, bits 5-6 = polarization,
301        // bits 3-4 = roll_off, bit 2 = modulation_system, bits 1-0 = modulation_type
302        let flags = body[6];
303        let east = (flags & 0x80) != 0;
304
305        let pol_raw = (flags >> 5) & 0x03;
306        let polarization = match pol_raw {
307            0 => Polarization::LinearHorizontal,
308            1 => Polarization::LinearVertical,
309            2 => Polarization::CircularLeft,
310            _ => Polarization::CircularRight,
311        };
312
313        let roll_raw = (flags >> 3) & 0x03;
314        let roll_off = match roll_raw {
315            0 => RollOff::Alpha035,
316            1 => RollOff::Alpha025,
317            2 => RollOff::Alpha020,
318            v => RollOff::Reserved(v),
319        };
320
321        let mod_sys_raw = (flags >> 2) & 0x01;
322        let modulation_system = match mod_sys_raw {
323            0 => ModulationSystem::DvbS,
324            _ => ModulationSystem::DvbS2,
325        };
326
327        let mod_type_raw = flags & 0x03;
328        let modulation_type = match mod_type_raw {
329            0 => ModulationType::Auto,
330            1 => ModulationType::Qpsk,
331            2 => ModulationType::Psk8,
332            _ => ModulationType::Qam16,
333        };
334
335        // Symbol rate: 28-bit BCD packed into 4 bytes (3.5 bytes + 4-bit FEC)
336        let symbol_rate_and_fec = u32::from_be_bytes([body[7], body[8], body[9], body[10]]);
337        let symbol_rate_bcd = symbol_rate_and_fec >> 4;
338        let fec_inner = FecInner::from_u8((symbol_rate_and_fec & 0x0F) as u8);
339
340        Ok(SatelliteDeliverySystemDescriptor {
341            frequency_bcd,
342            orbital_position_bcd,
343            east,
344            polarization,
345            roll_off,
346            modulation_system,
347            modulation_type,
348            symbol_rate_bcd,
349            fec_inner,
350        })
351    }
352}
353
354impl Serialize for SatelliteDeliverySystemDescriptor {
355    type Error = crate::error::Error;
356    fn serialized_len(&self) -> usize {
357        HEADER_LEN + BODY_LEN as usize
358    }
359
360    fn serialize_into(&self, buf: &mut [u8]) -> Result<usize> {
361        let len = self.serialized_len();
362        if buf.len() < len {
363            return Err(Error::OutputBufferTooSmall {
364                need: len,
365                have: buf.len(),
366            });
367        }
368
369        buf[0] = TAG;
370        buf[1] = BODY_LEN;
371
372        // Frequency: 4 bytes BCD
373        let freq_bytes = self.frequency_bcd.to_be_bytes();
374        buf[2..6].copy_from_slice(&freq_bytes);
375
376        // Orbital position: 2 bytes BCD
377        let orb_bytes = self.orbital_position_bcd.to_be_bytes();
378        buf[6..8].copy_from_slice(&orb_bytes);
379
380        // Flags byte: combine west_east, polarization, roll_off, modulation_system, modulation_type
381        let mut flags: u8 = 0;
382        if self.east {
383            flags |= 0x80;
384        }
385        flags |= match self.polarization {
386            Polarization::LinearHorizontal => 0x00,
387            Polarization::LinearVertical => 0x20,
388            Polarization::CircularLeft => 0x40,
389            Polarization::CircularRight => 0x60,
390        };
391        // Table 37: roll_off exists only when modulation_system == DVB-S2;
392        // for DVB-S those 2 bits are reserved_zero_future_use and SHALL be 0.
393        if self.modulation_system == ModulationSystem::DvbS2 {
394            flags |= match self.roll_off {
395                RollOff::Alpha035 => 0x00,
396                RollOff::Alpha025 => 0x08,
397                RollOff::Alpha020 => 0x10,
398                RollOff::Reserved(v) => (v & 0x03) << 3,
399            };
400        }
401        flags |= match self.modulation_system {
402            ModulationSystem::DvbS => 0x00,
403            ModulationSystem::DvbS2 => 0x04,
404        };
405        flags |= match self.modulation_type {
406            ModulationType::Auto => 0x00,
407            ModulationType::Qpsk => 0x01,
408            ModulationType::Psk8 => 0x02,
409            ModulationType::Qam16 => 0x03,
410        };
411        buf[8] = flags;
412
413        // Symbol rate + FEC_inner: 28-bit BCD shifted left 4 bits, then OR with FEC.
414        // Mask to 28 bits so an over-range value can't spill past the field.
415        let sym_freq = ((self.symbol_rate_bcd & 0x0FFF_FFFF) << 4)
416            | (u32::from(self.fec_inner.to_u8()) & 0x0F);
417        let sym_bytes = sym_freq.to_be_bytes();
418        buf[9..13].copy_from_slice(&sym_bytes);
419
420        Ok(len)
421    }
422}
423impl<'a> crate::traits::DescriptorDef<'a> for SatelliteDeliverySystemDescriptor {
424    const TAG: u8 = TAG;
425    const NAME: &'static str = "SATELLITE_DELIVERY_SYSTEM";
426}
427
428#[cfg(test)]
429mod tests {
430    use super::*;
431
432    /// Build a valid 13-byte descriptor (2 header + 11 body) and confirm
433    /// parse extracts frequency and orbital position correctly.
434    #[test]
435    fn parse_extracts_frequency_and_orbital_position() {
436        // frequency: 11.72500 GHz → BCD 0x01 0x17 0x25 0x00 (§6.2.13.2)
437        // orbital: 192.0° → BCD 0x19 0x20
438        let raw: Vec<u8> = vec![
439            TAG, BODY_LEN, 0x01, 0x17, 0x25, 0x00, // frequency
440            0x19, 0x20, // orbital position
441            0x00, // flags (all defaults: west, linear-h, alpha-035, DVB-S, auto)
442            0x02, 0x75, 0x00, 0x00, // symbol rate 27.500 Msym/s, FEC 0
443        ];
444        let desc = SatelliteDeliverySystemDescriptor::parse(&raw).unwrap();
445        assert_eq!(desc.frequency_bcd, 0x01172500);
446        assert_eq!(desc.orbital_position_bcd, 0x1920);
447    }
448
449    /// Flags byte bit 7 encodes west/east direction.
450    #[test]
451    fn parse_extracts_west_east_flag() {
452        // East: bit 7 = 1
453        let raw_east: Vec<u8> = vec![
454            TAG, BODY_LEN, 0x01, 0x17, 0x25, 0x00, 0x19, 0x20,
455            0x80, // east flag set, everything else zero
456            0x02, 0x75, 0x00, 0x00,
457        ];
458        let desc_east = SatelliteDeliverySystemDescriptor::parse(&raw_east).unwrap();
459        assert!(desc_east.east, "east should be true when bit 7 is set");
460
461        // West: bit 7 = 0
462        let raw_west: Vec<u8> = vec![
463            TAG, BODY_LEN, 0x01, 0x17, 0x25, 0x00, 0x19, 0x20, 0x00, // east flag clear
464            0x02, 0x75, 0x00, 0x00,
465        ];
466        let desc_west = SatelliteDeliverySystemDescriptor::parse(&raw_west).unwrap();
467        assert!(!desc_west.east, "east should be false when bit 7 is clear");
468    }
469
470    /// All four polarization values are extracted correctly from bits 5-6.
471    #[test]
472    fn parse_extracts_polarization_variants() {
473        let pol_pairs: [(u8, Polarization); 4] = [
474            (0x00, Polarization::LinearHorizontal),
475            (0x20, Polarization::LinearVertical),
476            (0x40, Polarization::CircularLeft),
477            (0x60, Polarization::CircularRight),
478        ];
479
480        for (offset, expected_pol) in pol_pairs {
481            let raw: Vec<u8> = vec![
482                TAG, BODY_LEN, 0x01, 0x17, 0x25, 0x00, 0x19, 0x20,
483                offset, // polarization bits
484                0x02, 0x75, 0x00, 0x00,
485            ];
486            let desc = SatelliteDeliverySystemDescriptor::parse(&raw).unwrap();
487            assert_eq!(
488                desc.polarization, expected_pol,
489                "polarization mismatch for offset 0x{:02x}",
490                offset
491            );
492        }
493    }
494
495    /// Modulation system (bit 2) and modulation type (bits 1-0) are extracted.
496    #[test]
497    fn parse_extracts_modulation_system_and_type() {
498        // DVB-S (bit 2 = 0), QPSK (bits 1-0 = 01)
499        let raw: Vec<u8> = vec![
500            TAG, BODY_LEN, 0x01, 0x17, 0x25, 0x00, 0x19, 0x20, 0x01, // DVB-S, QPSK
501            0x02, 0x75, 0x00, 0x00,
502        ];
503        let desc = SatelliteDeliverySystemDescriptor::parse(&raw).unwrap();
504        assert_eq!(desc.modulation_system, ModulationSystem::DvbS);
505        assert_eq!(desc.modulation_type, ModulationType::Qpsk);
506
507        // DVB-S2 (bit 2 = 1), 8PSK (bits 1-0 = 10)
508        let raw2: Vec<u8> = vec![
509            TAG, BODY_LEN, 0x01, 0x17, 0x25, 0x00, 0x19, 0x20,
510            0x06, // DVB-S2 (0x04) + 8PSK (0x02)
511            0x02, 0x75, 0x00, 0x00,
512        ];
513        let desc2 = SatelliteDeliverySystemDescriptor::parse(&raw2).unwrap();
514        assert_eq!(desc2.modulation_system, ModulationSystem::DvbS2);
515        assert_eq!(desc2.modulation_type, ModulationType::Psk8);
516    }
517
518    /// Roll-off codes (bits 3-4) are extracted correctly.
519    #[test]
520    fn parse_extracts_roll_off() {
521        let roll_pairs: [(u8, RollOff); 4] = [
522            (0x00, RollOff::Alpha035),
523            (0x08, RollOff::Alpha025),
524            (0x10, RollOff::Alpha020),
525            (0x18, RollOff::Reserved(3)),
526        ];
527
528        for (offset, expected_roll) in roll_pairs {
529            let raw: Vec<u8> = vec![
530                TAG, BODY_LEN, 0x01, 0x17, 0x25, 0x00, 0x19, 0x20, offset, // roll-off bits
531                0x02, 0x75, 0x00, 0x00,
532            ];
533            let desc = SatelliteDeliverySystemDescriptor::parse(&raw).unwrap();
534            assert_eq!(desc.roll_off, expected_roll);
535        }
536    }
537
538    /// Symbol rate (28-bit BCD) and FEC inner (4 bits) are extracted from
539    /// the last 4 bytes.
540    #[test]
541    fn parse_extracts_symbol_rate_and_fec() {
542        // symbol_rate: 27.500 Msym/s → BCD 0x027500, FEC: 5/6 → 0x4
543        let raw: Vec<u8> = vec![
544            TAG, BODY_LEN, 0x01, 0x17, 0x25, 0x00, 0x19, 0x20, 0x00, 0x02, 0x75, 0x00,
545            0x04, // symbol_rate_bcd = 0x027500, fec_inner = 4 (Rate5_6)
546        ];
547        let desc = SatelliteDeliverySystemDescriptor::parse(&raw).unwrap();
548        assert_eq!(desc.symbol_rate_bcd, 0x0275000);
549        assert_eq!(desc.fec_inner, FecInner::Rate5_6);
550
551        // FEC = 0x0F (NoConvCoding)
552        let raw2: Vec<u8> = vec![
553            TAG, BODY_LEN, 0x01, 0x17, 0x25, 0x00, 0x19, 0x20, 0x00, 0x02, 0x75, 0x00,
554            0x0F, // FEC = 0x0F
555        ];
556        let desc2 = SatelliteDeliverySystemDescriptor::parse(&raw2).unwrap();
557        assert_eq!(desc2.fec_inner, FecInner::NoConvCoding);
558    }
559
560    /// Wrong tag byte should return InvalidDescriptor.
561    #[test]
562    fn parse_rejects_wrong_tag() {
563        let raw: Vec<u8> = vec![
564            0x44, // wrong tag (cable delivery system)
565            BODY_LEN, 0x01, 0x17, 0x25, 0x00, 0x19, 0x20, 0x00, 0x02, 0x75, 0x00, 0x00,
566        ];
567        let err = SatelliteDeliverySystemDescriptor::parse(&raw).unwrap_err();
568        assert!(
569            matches!(err, Error::InvalidDescriptor { tag: 0x44, .. }),
570            "expected InvalidDescriptor(tag=0x44), got {err:?}"
571        );
572    }
573
574    /// Body length must be exactly 11. Wrong length returns InvalidDescriptor.
575    #[test]
576    fn parse_rejects_wrong_length() {
577        let raw: Vec<u8> = vec![
578            TAG, 0x05, // wrong length (should be 11)
579            0x11, 0x72, 0x50, 0x00, 0x19, 0x20,
580        ];
581        let err = SatelliteDeliverySystemDescriptor::parse(&raw).unwrap_err();
582        assert!(
583            matches!(
584                err,
585                Error::InvalidDescriptor {
586                    reason: "descriptor_length must equal 11",
587                    ..
588                }
589            ),
590            "expected InvalidDescriptor about length, got {err:?}"
591        );
592    }
593
594    /// Parse → serialize → re-parse should yield an equal struct and
595    /// identical bytes.
596    #[test]
597    fn serialize_round_trip() {
598        let desc = SatelliteDeliverySystemDescriptor {
599            frequency_bcd: 0x01172500,
600            orbital_position_bcd: 0x1920,
601            east: true,
602            polarization: Polarization::CircularRight,
603            roll_off: RollOff::Alpha025,
604            modulation_system: ModulationSystem::DvbS2,
605            modulation_type: ModulationType::Psk8,
606            symbol_rate_bcd: 0x027500,
607            fec_inner: FecInner::Rate5_6,
608        };
609
610        let mut buf = vec![0u8; desc.serialized_len()];
611        let written = desc.serialize_into(&mut buf).unwrap();
612        assert_eq!(written, desc.serialized_len());
613
614        let reparsed = SatelliteDeliverySystemDescriptor::parse(&buf).unwrap();
615        assert_eq!(desc, reparsed);
616    }
617
618    /// Reserved roll-off value round-trips with its raw 2-bit value preserved.
619    #[test]
620    fn reserved_roll_off_round_trips() {
621        let desc = SatelliteDeliverySystemDescriptor {
622            frequency_bcd: 0x01172500,
623            orbital_position_bcd: 0x1920,
624            east: true,
625            polarization: Polarization::CircularRight,
626            roll_off: RollOff::Reserved(3),
627            modulation_system: ModulationSystem::DvbS2,
628            modulation_type: ModulationType::Psk8,
629            symbol_rate_bcd: 0x027500,
630            fec_inner: FecInner::Rate5_6,
631        };
632
633        let mut buf = vec![0u8; desc.serialized_len()];
634        desc.serialize_into(&mut buf).unwrap();
635        assert_eq!(buf[8] & 0x18, 0x18); // roll_off bits = 0b11
636
637        let reparsed = SatelliteDeliverySystemDescriptor::parse(&buf).unwrap();
638        assert_eq!(reparsed.roll_off, RollOff::Reserved(3));
639    }
640
641    #[test]
642    fn frequency_hz_round_trip() {
643        let mut desc = SatelliteDeliverySystemDescriptor {
644            frequency_bcd: 0,
645            orbital_position_bcd: 0x1920,
646            east: true,
647            polarization: Polarization::LinearHorizontal,
648            roll_off: RollOff::Alpha035,
649            modulation_system: ModulationSystem::DvbS,
650            modulation_type: ModulationType::Auto,
651            symbol_rate_bcd: 0x027500,
652            fec_inner: FecInner::Rate5_6,
653        };
654        desc.set_frequency_hz(11_725_000_000).unwrap();
655        assert_eq!(desc.frequency_hz(), Some(11_725_000_000));
656        assert_eq!(desc.frequency_bcd, 0x01172500);
657    }
658}