Skip to main content

dvb_si/tables/
dsmcc.rs

1//! DSM-CC section parser — ISO/IEC 13818-6 + ETSI EN 301 192 §9.
2//!
3//! This is intentionally minimal: header framing, table_id dispatch,
4//! length check, and carrying the payload as `&[u8]`. Full DSM-CC payload
5//! parsing is deliberately out of scope (YAGNI).
6//!
7//! SSI-dependent trailer: when `section_syntax_indicator == 1` the trailing
8//! 4 bytes are a CRC-32 (computed over the whole section); when SSI == 0
9//! they are an ISO/IEC 13818-6 checksum preserved verbatim in
10//! [`DsmccSection::checksum`]. For SSI=1 the serializer recomputes CRC-32;
11//! for SSI=0 the serializer re-emits the preserved checksum bytes.
12
13use crate::error::{Error, Result};
14use dvb_common::{Parse, Serialize};
15
16/// First table_id in the DSM-CC section range (inclusive).
17pub const TABLE_ID_FIRST: u8 = 0x3A;
18/// Last table_id in the DSM-CC section range (inclusive).
19pub const TABLE_ID_LAST: u8 = 0x3F;
20/// DSM-CC has no well-known PID.
21pub const PID: u16 = 0x0000;
22
23const MIN_HEADER_LEN: usize = 3;
24const EXTENSION_HEADER_LEN: usize = 5;
25const CRC_LEN: usize = 4;
26const MIN_SECTION_LEN: usize = MIN_HEADER_LEN + EXTENSION_HEADER_LEN + CRC_LEN;
27
28/// A DSM-CC section — minimal wrapper that validates header framing
29/// and carries the raw payload.
30#[derive(Debug, Clone, Eq)]
31#[cfg_attr(feature = "serde", derive(serde::Serialize))]
32#[cfg_attr(feature = "yoke", derive(yoke::Yokeable))]
33pub struct DsmccSection<'a> {
34    /// The table_id byte (0x3A..=0x3F).
35    pub table_id: u8,
36    /// `section_syntax_indicator` bit. When `true` the trailer is a computed
37    /// CRC-32; when `false` it is an ISO/IEC 13818-6 checksum preserved
38    /// verbatim in [`Self::checksum`].
39    pub section_syntax_indicator: bool,
40    /// `private_indicator` bit (byte 1, bit 6).
41    pub private_indicator: bool,
42    /// 16-bit table_id_extension.
43    pub extension_id: u16,
44    /// 5-bit version_number.
45    pub version_number: u8,
46    /// current_next_indicator bit.
47    pub current_next_indicator: bool,
48    /// section_number.
49    pub section_number: u8,
50    /// last_section_number.
51    pub last_section_number: u8,
52    /// Raw payload bytes (everything between the extension header and the trailer).
53    pub payload: &'a [u8],
54    /// Verbatim trailer bytes when `section_syntax_indicator == false` (an
55    /// ISO/IEC 13818-6 checksum). Ignored when SSI is `true`, where the
56    /// trailer is a computed CRC-32.
57    pub checksum: [u8; 4],
58}
59
60impl PartialEq for DsmccSection<'_> {
61    fn eq(&self, other: &Self) -> bool {
62        self.table_id == other.table_id
63            && self.section_syntax_indicator == other.section_syntax_indicator
64            && self.private_indicator == other.private_indicator
65            && self.extension_id == other.extension_id
66            && self.version_number == other.version_number
67            && self.current_next_indicator == other.current_next_indicator
68            && self.section_number == other.section_number
69            && self.last_section_number == other.last_section_number
70            && self.payload == other.payload
71            && (self.section_syntax_indicator || self.checksum == other.checksum)
72    }
73}
74
75impl<'a> Parse<'a> for DsmccSection<'a> {
76    type Error = crate::error::Error;
77    fn parse(bytes: &'a [u8]) -> Result<Self> {
78        let min_len = MIN_HEADER_LEN + EXTENSION_HEADER_LEN + CRC_LEN;
79        if bytes.len() < min_len {
80            return Err(Error::BufferTooShort {
81                need: min_len,
82                have: bytes.len(),
83                what: "DsmccSection",
84            });
85        }
86
87        let table_id = bytes[0];
88        if !(TABLE_ID_FIRST..=TABLE_ID_LAST).contains(&table_id) {
89            return Err(Error::UnexpectedTableId {
90                table_id,
91                what: "DsmccSection",
92                expected: &[TABLE_ID_FIRST, TABLE_ID_LAST],
93            });
94        }
95
96        let section_syntax_indicator = (bytes[1] & 0x80) != 0;
97        let private_indicator = (bytes[1] & 0x40) != 0;
98        let section_length = ((bytes[1] & 0x0F) as u16) << 8 | bytes[2] as u16;
99        let total = super::check_section_length(
100            bytes.len(),
101            MIN_HEADER_LEN,
102            section_length as usize,
103            MIN_SECTION_LEN,
104        )?;
105
106        let extension_id = u16::from_be_bytes([bytes[3], bytes[4]]);
107        let version_number = (bytes[5] >> 1) & 0x1F;
108        let current_next_indicator = (bytes[5] & 0x01) != 0;
109        let section_number = bytes[6];
110        let last_section_number = bytes[7];
111
112        let payload_start = MIN_HEADER_LEN + EXTENSION_HEADER_LEN;
113        let payload_end = total - CRC_LEN;
114        let payload = &bytes[payload_start..payload_end];
115
116        let trailer_start = total - CRC_LEN;
117        let checksum = [
118            bytes[trailer_start],
119            bytes[trailer_start + 1],
120            bytes[trailer_start + 2],
121            bytes[trailer_start + 3],
122        ];
123
124        Ok(DsmccSection {
125            table_id,
126            section_syntax_indicator,
127            private_indicator,
128            extension_id,
129            version_number,
130            current_next_indicator,
131            section_number,
132            last_section_number,
133            payload,
134            checksum,
135        })
136    }
137}
138
139impl Serialize for DsmccSection<'_> {
140    type Error = crate::error::Error;
141    fn serialized_len(&self) -> usize {
142        MIN_HEADER_LEN + EXTENSION_HEADER_LEN + self.payload.len() + CRC_LEN
143    }
144
145    fn serialize_into(&self, buf: &mut [u8]) -> Result<usize> {
146        let len = self.serialized_len();
147        if buf.len() < len {
148            return Err(Error::OutputBufferTooSmall {
149                need: len,
150                have: buf.len(),
151            });
152        }
153
154        let section_length: u16 = (len - MIN_HEADER_LEN) as u16;
155        buf[0] = self.table_id;
156        buf[1] = if self.section_syntax_indicator {
157            super::SECTION_B1_FLAGS_PSI
158        } else {
159            (u8::from(self.private_indicator) << 6) | super::SECTION_B1_RESERVED_HI
160        } | ((section_length >> 8) as u8 & 0x0F);
161        buf[2] = (section_length & 0xFF) as u8;
162        buf[3..5].copy_from_slice(&self.extension_id.to_be_bytes());
163        buf[5] = 0xC0 | ((self.version_number & 0x1F) << 1) | u8::from(self.current_next_indicator);
164        buf[6] = self.section_number;
165        buf[7] = self.last_section_number;
166
167        let payload_start = MIN_HEADER_LEN + EXTENSION_HEADER_LEN;
168        let payload_end = payload_start + self.payload.len();
169        buf[payload_start..payload_end].copy_from_slice(self.payload);
170
171        let trailer_start = payload_end;
172        if self.section_syntax_indicator {
173            let crc = dvb_common::crc32_mpeg2::compute(&buf[..trailer_start]);
174            buf[trailer_start..len].copy_from_slice(&crc.to_be_bytes());
175        } else {
176            buf[trailer_start..len].copy_from_slice(&self.checksum);
177        }
178        Ok(len)
179    }
180}
181impl<'a> crate::traits::TableDef<'a> for DsmccSection<'a> {
182    /// Full DSM-CC range including `0x3E` (MPE datagram_section). The typed
183    /// [`crate::tables::mpe::MpeDatagramSection`] view of `0x3E` is reachable
184    /// type-keyed only (via `AnyTableSection::parse_as` or
185    /// `MpeDatagramSection::parse`); the default dispatcher routes `0x3E` here.
186    const TABLE_ID_RANGES: &'static [(u8, u8)] = &[(TABLE_ID_FIRST, TABLE_ID_LAST)];
187    const NAME: &'static str = "DSM_CC_SECTION";
188}
189
190#[cfg(test)]
191mod tests {
192    use super::*;
193
194    fn build_dsmcc(table_id: u8, extension_id: u16, version: u8, payload: &[u8]) -> Vec<u8> {
195        let section_length: u16 = (EXTENSION_HEADER_LEN + payload.len() + CRC_LEN) as u16;
196        let mut v = Vec::new();
197        v.push(table_id);
198        v.push(super::super::SECTION_B1_FLAGS_PSI | ((section_length >> 8) as u8 & 0x0F));
199        v.push((section_length & 0xFF) as u8);
200        v.extend_from_slice(&extension_id.to_be_bytes());
201        v.push(0xC0 | ((version & 0x1F) << 1) | 0x01);
202        v.push(0);
203        v.push(0);
204        v.extend_from_slice(payload);
205        v.extend_from_slice(&[0, 0, 0, 0]);
206        v
207    }
208
209    #[test]
210    fn parse_rejects_wrong_table_id() {
211        let mut bytes = build_dsmcc(0x3B, 0x0001, 0, &[]);
212        bytes[0] = 0x00;
213        let err = DsmccSection::parse(&bytes).unwrap_err();
214        assert!(matches!(
215            err,
216            Error::UnexpectedTableId { table_id: 0x00, .. }
217        ));
218    }
219
220    #[test]
221    fn parse_rejects_table_id_below_range() {
222        let bytes = build_dsmcc(0x39, 0x0001, 0, &[]);
223        let err = DsmccSection::parse(&bytes).unwrap_err();
224        assert!(matches!(
225            err,
226            Error::UnexpectedTableId { table_id: 0x39, .. }
227        ));
228    }
229
230    #[test]
231    fn parse_rejects_table_id_above_range() {
232        let bytes = build_dsmcc(0x40, 0x0001, 0, &[]);
233        let err = DsmccSection::parse(&bytes).unwrap_err();
234        assert!(matches!(
235            err,
236            Error::UnexpectedTableId { table_id: 0x40, .. }
237        ));
238    }
239
240    #[test]
241    fn parse_rejects_short_buffer() {
242        let err = DsmccSection::parse(&[0x3B, 0x00]).unwrap_err();
243        assert!(matches!(err, Error::BufferTooShort { .. }));
244    }
245
246    #[test]
247    fn parse_empty_payload() {
248        let bytes = build_dsmcc(0x3B, 0x1234, 5, &[]);
249        let sec = DsmccSection::parse(&bytes).expect("parse");
250        assert_eq!(sec.table_id, 0x3B);
251        assert_eq!(sec.extension_id, 0x1234);
252        assert_eq!(sec.version_number, 5);
253        assert!(sec.current_next_indicator);
254        assert_eq!(sec.section_number, 0);
255        assert_eq!(sec.last_section_number, 0);
256        assert_eq!(sec.payload.len(), 0);
257    }
258
259    #[test]
260    fn parse_0x3c_table_id_accepted() {
261        let bytes = build_dsmcc(0x3C, 0x0001, 0, &[0xAA, 0xBB]);
262        let sec = DsmccSection::parse(&bytes).unwrap();
263        assert_eq!(sec.table_id, 0x3C);
264        assert_eq!(sec.payload, &[0xAA, 0xBB]);
265    }
266
267    #[test]
268    fn parse_payload_preserved() {
269        let payload = vec![0x01, 0x02, 0x03, 0x04, 0x05];
270        let bytes = build_dsmcc(0x3B, 0x0001, 0, &payload);
271        let sec = DsmccSection::parse(&bytes).unwrap();
272        assert_eq!(sec.payload, &payload[..]);
273    }
274
275    #[test]
276    fn serialize_round_trip_empty() {
277        let sec = DsmccSection {
278            table_id: 0x3B,
279            section_syntax_indicator: true,
280            private_indicator: false,
281            extension_id: 0x0001,
282            version_number: 0,
283            current_next_indicator: true,
284            section_number: 0,
285            last_section_number: 0,
286            payload: &[],
287            checksum: [0; 4],
288        };
289        let mut buf = vec![0u8; sec.serialized_len()];
290        sec.serialize_into(&mut buf).unwrap();
291        let reparsed = DsmccSection::parse(&buf).unwrap();
292        assert_eq!(sec, reparsed);
293    }
294
295    #[test]
296    fn serialize_round_trip_with_payload() {
297        let payload: [u8; 5] = [0xDE, 0xAD, 0xBE, 0xEF, 0x00];
298        let sec = DsmccSection {
299            table_id: 0x3C,
300            section_syntax_indicator: true,
301            private_indicator: false,
302            extension_id: 0xABCD,
303            version_number: 3,
304            current_next_indicator: true,
305            section_number: 1,
306            last_section_number: 2,
307            payload: &payload,
308            checksum: [0; 4],
309        };
310        let mut buf = vec![0u8; sec.serialized_len()];
311        sec.serialize_into(&mut buf).unwrap();
312        let reparsed = DsmccSection::parse(&buf).unwrap();
313        assert_eq!(sec, reparsed);
314    }
315
316    #[test]
317    fn serialize_round_trip_ssi_clear_preserves_checksum() {
318        let payload: [u8; 3] = [0x01, 0x02, 0x03];
319        let checksum: [u8; 4] = [0xAA, 0xBB, 0xCC, 0xDD];
320        let sec = DsmccSection {
321            table_id: 0x3B,
322            section_syntax_indicator: false,
323            private_indicator: true,
324            extension_id: 0x5678,
325            version_number: 1,
326            current_next_indicator: true,
327            section_number: 0,
328            last_section_number: 0,
329            payload: &payload,
330            checksum,
331        };
332        let mut buf = vec![0u8; sec.serialized_len()];
333        sec.serialize_into(&mut buf).unwrap();
334        assert_eq!(&buf[buf.len() - 4..], &checksum);
335        let reparsed = DsmccSection::parse(&buf).unwrap();
336        assert_eq!(sec, reparsed);
337        assert_eq!(reparsed.checksum, checksum);
338    }
339
340    #[test]
341    fn parse_rejects_zero_section_length() {
342        let mut buf = vec![0u8; 64];
343        buf[0] = TABLE_ID_FIRST;
344        buf[1] = 0xF0;
345        buf[2] = 0x00;
346        for b in &mut buf[3..] {
347            *b = 0xFF;
348        }
349        assert!(matches!(
350            DsmccSection::parse(&buf).unwrap_err(),
351            Error::SectionLengthOverflow { .. }
352        ));
353    }
354}