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 `Cow<'a, [u8]>`. Full
5//! DSM-CC payload parsing is deliberately out of scope (YAGNI).
6//!
7//! Known limitation: the parser assumes long-form framing (extension header +
8//! trailing CRC_32) regardless of `section_syntax_indicator`. ISO/IEC 13818-6
9//! permits SSI=0 sections whose trailing 4 bytes carry a checksum under a
10//! different rule; those are not distinguished here.
11
12use crate::error::{Error, Result};
13use dvb_common::{Parse, Serialize};
14
15/// First table_id in the DSM-CC section range (inclusive).
16pub const TABLE_ID_FIRST: u8 = 0x3A;
17/// Last table_id in the DSM-CC section range (inclusive).
18pub const TABLE_ID_LAST: u8 = 0x3F;
19/// DSM-CC has no well-known PID.
20pub const PID: u16 = 0x0000;
21
22const MIN_HEADER_LEN: usize = 3;
23const EXTENSION_HEADER_LEN: usize = 5;
24const CRC_LEN: usize = 4;
25const MIN_SECTION_LEN: usize = MIN_HEADER_LEN + EXTENSION_HEADER_LEN + CRC_LEN;
26
27/// A DSM-CC section — minimal wrapper that validates header framing
28/// and carries the raw payload.
29#[derive(Debug, Clone, PartialEq, Eq)]
30#[cfg_attr(feature = "serde", derive(serde::Serialize))]
31#[cfg_attr(feature = "yoke", derive(yoke::Yokeable))]
32pub struct DsmccSection<'a> {
33    /// The table_id byte (0x3A..=0x3F).
34    pub table_id: u8,
35    /// 16-bit table_id_extension.
36    pub extension_id: u16,
37    /// 5-bit version_number.
38    pub version_number: u8,
39    /// current_next_indicator bit.
40    pub current_next_indicator: bool,
41    /// section_number.
42    pub section_number: u8,
43    /// last_section_number.
44    pub last_section_number: u8,
45    /// Raw payload bytes (everything between the extension header and the CRC).
46    pub payload: &'a [u8],
47}
48
49impl<'a> Parse<'a> for DsmccSection<'a> {
50    type Error = crate::error::Error;
51    fn parse(bytes: &'a [u8]) -> Result<Self> {
52        let min_len = MIN_HEADER_LEN + EXTENSION_HEADER_LEN + CRC_LEN;
53        if bytes.len() < min_len {
54            return Err(Error::BufferTooShort {
55                need: min_len,
56                have: bytes.len(),
57                what: "DsmccSection",
58            });
59        }
60
61        let table_id = bytes[0];
62        if !(TABLE_ID_FIRST..=TABLE_ID_LAST).contains(&table_id) {
63            return Err(Error::UnexpectedTableId {
64                table_id,
65                what: "DsmccSection",
66                expected: &[TABLE_ID_FIRST, TABLE_ID_LAST],
67            });
68        }
69
70        let section_length = ((bytes[1] & 0x0F) as u16) << 8 | bytes[2] as u16;
71        let total = super::check_section_length(
72            bytes.len(),
73            MIN_HEADER_LEN,
74            section_length as usize,
75            MIN_SECTION_LEN,
76        )?;
77
78        let extension_id = u16::from_be_bytes([bytes[3], bytes[4]]);
79        let version_number = (bytes[5] >> 1) & 0x1F;
80        let current_next_indicator = (bytes[5] & 0x01) != 0;
81        let section_number = bytes[6];
82        let last_section_number = bytes[7];
83
84        let payload_start = MIN_HEADER_LEN + EXTENSION_HEADER_LEN;
85        let payload_end = total - CRC_LEN;
86        let payload = &bytes[payload_start..payload_end];
87
88        Ok(DsmccSection {
89            table_id,
90            extension_id,
91            version_number,
92            current_next_indicator,
93            section_number,
94            last_section_number,
95            payload,
96        })
97    }
98}
99
100impl Serialize for DsmccSection<'_> {
101    type Error = crate::error::Error;
102    fn serialized_len(&self) -> usize {
103        MIN_HEADER_LEN + EXTENSION_HEADER_LEN + self.payload.len() + CRC_LEN
104    }
105
106    fn serialize_into(&self, buf: &mut [u8]) -> Result<usize> {
107        let len = self.serialized_len();
108        if buf.len() < len {
109            return Err(Error::OutputBufferTooSmall {
110                need: len,
111                have: buf.len(),
112            });
113        }
114
115        let section_length: u16 = (len - MIN_HEADER_LEN) as u16;
116        buf[0] = self.table_id;
117        buf[1] = super::SECTION_B1_FLAGS_PSI | ((section_length >> 8) as u8 & 0x0F);
118        buf[2] = (section_length & 0xFF) as u8;
119        buf[3..5].copy_from_slice(&self.extension_id.to_be_bytes());
120        buf[5] = 0xC0 | ((self.version_number & 0x1F) << 1) | u8::from(self.current_next_indicator);
121        buf[6] = self.section_number;
122        buf[7] = self.last_section_number;
123
124        let payload_start = MIN_HEADER_LEN + EXTENSION_HEADER_LEN;
125        let payload_end = payload_start + self.payload.len();
126        buf[payload_start..payload_end].copy_from_slice(self.payload);
127
128        let crc_pos = len - CRC_LEN;
129        let crc = dvb_common::crc32_mpeg2::compute(&buf[..crc_pos]);
130        buf[crc_pos..len].copy_from_slice(&crc.to_be_bytes());
131        Ok(len)
132    }
133}
134impl<'a> crate::traits::TableDef<'a> for DsmccSection<'a> {
135    /// Full DSM-CC range including `0x3E` (MPE datagram_section). The typed
136    /// [`crate::tables::mpe::MpeDatagramSection`] view of `0x3E` is reachable
137    /// type-keyed only (via `AnyTableSection::parse_as` or
138    /// `MpeDatagramSection::parse`); the default dispatcher routes `0x3E` here.
139    const TABLE_ID_RANGES: &'static [(u8, u8)] = &[(TABLE_ID_FIRST, TABLE_ID_LAST)];
140    const NAME: &'static str = "DSM_CC_SECTION";
141}
142
143#[cfg(test)]
144mod tests {
145    use super::*;
146
147    fn build_dsmcc(table_id: u8, extension_id: u16, version: u8, payload: &[u8]) -> Vec<u8> {
148        let section_length: u16 = (EXTENSION_HEADER_LEN + payload.len() + CRC_LEN) as u16;
149        let mut v = Vec::new();
150        v.push(table_id);
151        v.push(super::super::SECTION_B1_FLAGS_PSI | ((section_length >> 8) as u8 & 0x0F));
152        v.push((section_length & 0xFF) as u8);
153        v.extend_from_slice(&extension_id.to_be_bytes());
154        v.push(0xC0 | ((version & 0x1F) << 1) | 0x01);
155        v.push(0);
156        v.push(0);
157        v.extend_from_slice(payload);
158        v.extend_from_slice(&[0, 0, 0, 0]);
159        v
160    }
161
162    #[test]
163    fn parse_rejects_wrong_table_id() {
164        let mut bytes = build_dsmcc(0x3B, 0x0001, 0, &[]);
165        bytes[0] = 0x00;
166        let err = DsmccSection::parse(&bytes).unwrap_err();
167        assert!(matches!(
168            err,
169            Error::UnexpectedTableId { table_id: 0x00, .. }
170        ));
171    }
172
173    #[test]
174    fn parse_rejects_table_id_below_range() {
175        let bytes = build_dsmcc(0x39, 0x0001, 0, &[]);
176        let err = DsmccSection::parse(&bytes).unwrap_err();
177        assert!(matches!(
178            err,
179            Error::UnexpectedTableId { table_id: 0x39, .. }
180        ));
181    }
182
183    #[test]
184    fn parse_rejects_table_id_above_range() {
185        let bytes = build_dsmcc(0x40, 0x0001, 0, &[]);
186        let err = DsmccSection::parse(&bytes).unwrap_err();
187        assert!(matches!(
188            err,
189            Error::UnexpectedTableId { table_id: 0x40, .. }
190        ));
191    }
192
193    #[test]
194    fn parse_rejects_short_buffer() {
195        let err = DsmccSection::parse(&[0x3B, 0x00]).unwrap_err();
196        assert!(matches!(err, Error::BufferTooShort { .. }));
197    }
198
199    #[test]
200    fn parse_empty_payload() {
201        let bytes = build_dsmcc(0x3B, 0x1234, 5, &[]);
202        let sec = DsmccSection::parse(&bytes).expect("parse");
203        assert_eq!(sec.table_id, 0x3B);
204        assert_eq!(sec.extension_id, 0x1234);
205        assert_eq!(sec.version_number, 5);
206        assert!(sec.current_next_indicator);
207        assert_eq!(sec.section_number, 0);
208        assert_eq!(sec.last_section_number, 0);
209        assert_eq!(sec.payload.len(), 0);
210    }
211
212    #[test]
213    fn parse_0x3c_table_id_accepted() {
214        let bytes = build_dsmcc(0x3C, 0x0001, 0, &[0xAA, 0xBB]);
215        let sec = DsmccSection::parse(&bytes).unwrap();
216        assert_eq!(sec.table_id, 0x3C);
217        assert_eq!(sec.payload, &[0xAA, 0xBB]);
218    }
219
220    #[test]
221    fn parse_payload_preserved() {
222        let payload = vec![0x01, 0x02, 0x03, 0x04, 0x05];
223        let bytes = build_dsmcc(0x3B, 0x0001, 0, &payload);
224        let sec = DsmccSection::parse(&bytes).unwrap();
225        assert_eq!(sec.payload, &payload[..]);
226    }
227
228    #[test]
229    fn serialize_round_trip_empty() {
230        let sec = DsmccSection {
231            table_id: 0x3B,
232            extension_id: 0x0001,
233            version_number: 0,
234            current_next_indicator: true,
235            section_number: 0,
236            last_section_number: 0,
237            payload: &[],
238        };
239        let mut buf = vec![0u8; sec.serialized_len()];
240        sec.serialize_into(&mut buf).unwrap();
241        let reparsed = DsmccSection::parse(&buf).unwrap();
242        assert_eq!(sec, reparsed);
243    }
244
245    #[test]
246    fn serialize_round_trip_with_payload() {
247        let payload: [u8; 5] = [0xDE, 0xAD, 0xBE, 0xEF, 0x00];
248        let sec = DsmccSection {
249            table_id: 0x3C,
250            extension_id: 0xABCD,
251            version_number: 3,
252            current_next_indicator: true,
253            section_number: 1,
254            last_section_number: 2,
255            payload: &payload,
256        };
257        let mut buf = vec![0u8; sec.serialized_len()];
258        sec.serialize_into(&mut buf).unwrap();
259        let reparsed = DsmccSection::parse(&buf).unwrap();
260        assert_eq!(sec, reparsed);
261    }
262
263    #[test]
264    fn parse_rejects_zero_section_length() {
265        let mut buf = vec![0u8; 64];
266        buf[0] = TABLE_ID_FIRST;
267        buf[1] = 0xF0;
268        buf[2] = 0x00;
269        for b in &mut buf[3..] {
270            *b = 0xFF;
271        }
272        assert!(matches!(
273            DsmccSection::parse(&buf).unwrap_err(),
274            Error::SectionLengthOverflow { .. }
275        ));
276    }
277}