Skip to main content

dvb_si/descriptors/
ecm_repetition_rate.rs

1//! ECM Repetition Rate Descriptor — ETSI EN 301 192 §9.9, Table 44 (tag 0x78).
2//!
3//! Carried in the PMT to advertise the maximum interval between ECMs for a
4//! given CA system. Per en_301_192.md "Table 44 — ECM repetition rate
5//! descriptor" (PDF p. 56) the body is: CA_system_ID(16) +
6//! ECM_repetition_rate(16) + trailing private_data_byte run.
7
8use crate::error::{Error, Result};
9use crate::traits::Descriptor;
10use dvb_common::{Parse, Serialize};
11
12/// Descriptor tag for ECM_repetition_rate_descriptor.
13pub const TAG: u8 = 0x78;
14const HEADER_LEN: usize = 2;
15const FIXED_LEN: usize = 4;
16
17/// ECM Repetition Rate Descriptor.
18#[derive(Debug, Clone, PartialEq, Eq)]
19#[cfg_attr(feature = "serde", derive(serde::Serialize))]
20pub struct EcmRepetitionRateDescriptor<'a> {
21    /// 16-bit CA_system_ID this rate applies to.
22    pub ca_system_id: u16,
23    /// 16-bit ECM_repetition_rate (max ms between successive ECMs).
24    pub ecm_repetition_rate: u16,
25    /// Trailing private_data bytes.
26    pub private_data: &'a [u8],
27}
28
29impl<'a> Parse<'a> for EcmRepetitionRateDescriptor<'a> {
30    type Error = crate::error::Error;
31    fn parse(bytes: &'a [u8]) -> Result<Self> {
32        if bytes.len() < HEADER_LEN {
33            return Err(Error::BufferTooShort {
34                need: HEADER_LEN,
35                have: bytes.len(),
36                what: "EcmRepetitionRateDescriptor header",
37            });
38        }
39        if bytes[0] != TAG {
40            return Err(Error::InvalidDescriptor {
41                tag: bytes[0],
42                reason: "unexpected tag for ECM_repetition_rate_descriptor",
43            });
44        }
45        let length = bytes[1] as usize;
46        let end = HEADER_LEN + length;
47        if bytes.len() < end {
48            return Err(Error::BufferTooShort {
49                need: end,
50                have: bytes.len(),
51                what: "EcmRepetitionRateDescriptor body",
52            });
53        }
54        if length < FIXED_LEN {
55            return Err(Error::InvalidDescriptor {
56                tag: TAG,
57                reason: "ECM_repetition_rate_descriptor body shorter than 4 bytes",
58            });
59        }
60        let body = &bytes[HEADER_LEN..end];
61        let ca_system_id = u16::from_be_bytes([body[0], body[1]]);
62        let ecm_repetition_rate = u16::from_be_bytes([body[2], body[3]]);
63        let private_data = &body[FIXED_LEN..];
64        Ok(Self {
65            ca_system_id,
66            ecm_repetition_rate,
67            private_data,
68        })
69    }
70}
71
72impl Serialize for EcmRepetitionRateDescriptor<'_> {
73    type Error = crate::error::Error;
74    fn serialized_len(&self) -> usize {
75        HEADER_LEN + FIXED_LEN + self.private_data.len()
76    }
77
78    fn serialize_into(&self, buf: &mut [u8]) -> Result<usize> {
79        if FIXED_LEN + self.private_data.len() > u8::MAX as usize {
80            return Err(Error::InvalidDescriptor {
81                tag: TAG,
82                reason: "ECM_repetition_rate_descriptor body exceeds 255 bytes",
83            });
84        }
85        let len = self.serialized_len();
86        if buf.len() < len {
87            return Err(Error::OutputBufferTooSmall {
88                need: len,
89                have: buf.len(),
90            });
91        }
92        buf[0] = TAG;
93        buf[1] = (FIXED_LEN + self.private_data.len()) as u8;
94        buf[2..4].copy_from_slice(&self.ca_system_id.to_be_bytes());
95        buf[4..6].copy_from_slice(&self.ecm_repetition_rate.to_be_bytes());
96        buf[HEADER_LEN + FIXED_LEN..len].copy_from_slice(self.private_data);
97        Ok(len)
98    }
99}
100
101impl<'a> Descriptor<'a> for EcmRepetitionRateDescriptor<'a> {
102    const TAG: u8 = TAG;
103    fn descriptor_length(&self) -> u8 {
104        (FIXED_LEN + self.private_data.len()) as u8
105    }
106}
107
108impl<'a> crate::traits::DescriptorDef<'a> for EcmRepetitionRateDescriptor<'a> {
109    const TAG: u8 = TAG;
110    const NAME: &'static str = "ECM_REPETITION_RATE";
111}
112
113#[cfg(test)]
114mod tests {
115    use super::*;
116
117    #[test]
118    fn parse_no_private_data() {
119        let bytes = [TAG, 4, 0x06, 0x48, 0x01, 0xF4];
120        let d = EcmRepetitionRateDescriptor::parse(&bytes).unwrap();
121        assert_eq!(d.ca_system_id, 0x0648);
122        assert_eq!(d.ecm_repetition_rate, 500);
123        assert!(d.private_data.is_empty());
124    }
125
126    #[test]
127    fn parse_with_private_data() {
128        let bytes = [TAG, 6, 0x05, 0x00, 0x00, 0xC8, 0xAA, 0xBB];
129        let d = EcmRepetitionRateDescriptor::parse(&bytes).unwrap();
130        assert_eq!(d.ca_system_id, 0x0500);
131        assert_eq!(d.ecm_repetition_rate, 200);
132        assert_eq!(d.private_data, &[0xAA, 0xBB]);
133    }
134
135    #[test]
136    fn parse_rejects_wrong_tag() {
137        assert!(matches!(
138            EcmRepetitionRateDescriptor::parse(&[0x77, 4, 0, 0, 0, 0]).unwrap_err(),
139            Error::InvalidDescriptor { tag: 0x77, .. }
140        ));
141    }
142
143    #[test]
144    fn parse_rejects_body_too_short() {
145        let bytes = [TAG, 3, 0, 0, 0];
146        assert!(matches!(
147            EcmRepetitionRateDescriptor::parse(&bytes).unwrap_err(),
148            Error::InvalidDescriptor { .. }
149        ));
150    }
151
152    #[test]
153    fn parse_rejects_length_overrunning_buffer() {
154        let bytes = [TAG, 6, 0, 0, 0, 0];
155        assert!(matches!(
156            EcmRepetitionRateDescriptor::parse(&bytes).unwrap_err(),
157            Error::BufferTooShort { .. }
158        ));
159    }
160
161    #[test]
162    fn serialize_round_trip() {
163        let d = EcmRepetitionRateDescriptor {
164            ca_system_id: 0x0B00,
165            ecm_repetition_rate: 1000,
166            private_data: &[0x01, 0x02],
167        };
168        let mut buf = vec![0u8; d.serialized_len()];
169        d.serialize_into(&mut buf).unwrap();
170        assert_eq!(EcmRepetitionRateDescriptor::parse(&buf).unwrap(), d);
171    }
172
173    #[test]
174    fn serialize_rejects_too_small_buffer() {
175        let d = EcmRepetitionRateDescriptor {
176            ca_system_id: 0,
177            ecm_repetition_rate: 0,
178            private_data: &[],
179        };
180        let mut buf = vec![0u8; 3];
181        assert!(matches!(
182            d.serialize_into(&mut buf).unwrap_err(),
183            Error::OutputBufferTooSmall { .. }
184        ));
185    }
186
187    #[cfg(feature = "serde")]
188    #[test]
189    fn serde_serializes_to_stable_json() {
190        // Borrowed `&[u8]` cannot deserialize from a JSON number array, so we
191        // assert the Serialize impl is wired and emits stable JSON.
192        let d = EcmRepetitionRateDescriptor {
193            ca_system_id: 0x0648,
194            ecm_repetition_rate: 480,
195            private_data: &[0xFE],
196        };
197        let j = serde_json::to_string(&d).unwrap();
198        // Valid, re-parseable JSON (key order is map-defined, so we do not
199        // assert byte-for-byte string stability).
200        let _v: serde_json::Value = serde_json::from_str(&j).unwrap();
201        assert!(j.contains("ca_system_id"));
202    }
203}