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 crate::traits::Table;
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;
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))]
31pub struct DsmccSection<'a> {
32    /// The table_id byte (0x3A..=0x3F).
33    pub table_id: u8,
34    /// 16-bit table_id_extension.
35    pub extension_id: u16,
36    /// 5-bit version_number.
37    pub version_number: u8,
38    /// current_next_indicator bit.
39    pub current_next_indicator: bool,
40    /// section_number.
41    pub section_number: u8,
42    /// last_section_number.
43    pub last_section_number: u8,
44    /// Raw payload bytes (everything between the extension header and the CRC).
45    pub payload: &'a [u8],
46}
47
48impl<'a> Parse<'a> for DsmccSection<'a> {
49    type Error = crate::error::Error;
50    fn parse(bytes: &'a [u8]) -> Result<Self> {
51        let min_len = MIN_HEADER_LEN + EXTENSION_HEADER_LEN + CRC_LEN;
52        if bytes.len() < min_len {
53            return Err(Error::BufferTooShort {
54                need: min_len,
55                have: bytes.len(),
56                what: "DsmccSection",
57            });
58        }
59
60        let table_id = bytes[0];
61        if !(TABLE_ID_FIRST..=TABLE_ID_LAST).contains(&table_id) {
62            return Err(Error::UnexpectedTableId {
63                table_id,
64                what: "DsmccSection",
65                expected: &[TABLE_ID_FIRST, TABLE_ID_LAST],
66            });
67        }
68
69        let section_length = ((bytes[1] & 0x0F) as u16) << 8 | bytes[2] as u16;
70        let total = MIN_HEADER_LEN + section_length as usize;
71        if bytes.len() < total {
72            return Err(Error::SectionLengthOverflow {
73                declared: section_length as usize,
74                available: bytes.len() - MIN_HEADER_LEN,
75            });
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] = 0xB0 | ((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}
134
135impl<'a> Table<'a> for DsmccSection<'a> {
136    const TABLE_ID: u8 = TABLE_ID_FIRST;
137    const PID: u16 = PID;
138}
139
140impl<'a> crate::traits::TableDef<'a> for DsmccSection<'a> {
141    /// Full DSM-CC range including `0x3E` (MPE datagram_section). The typed
142    /// [`crate::tables::mpe::MpeDatagramSection`] view of `0x3E` is reachable
143    /// type-keyed only (via `AnyTable::parse_as` or
144    /// `MpeDatagramSection::parse`); the default dispatcher routes `0x3E` here.
145    const TABLE_ID_RANGES: &'static [(u8, u8)] = &[(TABLE_ID_FIRST, TABLE_ID_LAST)];
146    const NAME: &'static str = "DSM_CC_SECTION";
147}
148
149#[cfg(test)]
150mod tests {
151    use super::*;
152
153    fn build_dsmcc(table_id: u8, extension_id: u16, version: u8, payload: &[u8]) -> Vec<u8> {
154        let section_length: u16 = (EXTENSION_HEADER_LEN + payload.len() + CRC_LEN) as u16;
155        let mut v = Vec::new();
156        v.push(table_id);
157        v.push(0xB0 | ((section_length >> 8) as u8 & 0x0F));
158        v.push((section_length & 0xFF) as u8);
159        v.extend_from_slice(&extension_id.to_be_bytes());
160        v.push(0xC0 | ((version & 0x1F) << 1) | 0x01);
161        v.push(0);
162        v.push(0);
163        v.extend_from_slice(payload);
164        v.extend_from_slice(&[0, 0, 0, 0]);
165        v
166    }
167
168    #[test]
169    fn parse_rejects_wrong_table_id() {
170        let mut bytes = build_dsmcc(0x3B, 0x0001, 0, &[]);
171        bytes[0] = 0x00;
172        let err = DsmccSection::parse(&bytes).unwrap_err();
173        assert!(matches!(
174            err,
175            Error::UnexpectedTableId { table_id: 0x00, .. }
176        ));
177    }
178
179    #[test]
180    fn parse_rejects_table_id_below_range() {
181        let bytes = build_dsmcc(0x39, 0x0001, 0, &[]);
182        let err = DsmccSection::parse(&bytes).unwrap_err();
183        assert!(matches!(
184            err,
185            Error::UnexpectedTableId { table_id: 0x39, .. }
186        ));
187    }
188
189    #[test]
190    fn parse_rejects_table_id_above_range() {
191        let bytes = build_dsmcc(0x40, 0x0001, 0, &[]);
192        let err = DsmccSection::parse(&bytes).unwrap_err();
193        assert!(matches!(
194            err,
195            Error::UnexpectedTableId { table_id: 0x40, .. }
196        ));
197    }
198
199    #[test]
200    fn parse_rejects_short_buffer() {
201        let err = DsmccSection::parse(&[0x3B, 0x00]).unwrap_err();
202        assert!(matches!(err, Error::BufferTooShort { .. }));
203    }
204
205    #[test]
206    fn parse_empty_payload() {
207        let bytes = build_dsmcc(0x3B, 0x1234, 5, &[]);
208        let sec = DsmccSection::parse(&bytes).expect("parse");
209        assert_eq!(sec.table_id, 0x3B);
210        assert_eq!(sec.extension_id, 0x1234);
211        assert_eq!(sec.version_number, 5);
212        assert!(sec.current_next_indicator);
213        assert_eq!(sec.section_number, 0);
214        assert_eq!(sec.last_section_number, 0);
215        assert_eq!(sec.payload.len(), 0);
216    }
217
218    #[test]
219    fn parse_0x3c_table_id_accepted() {
220        let bytes = build_dsmcc(0x3C, 0x0001, 0, &[0xAA, 0xBB]);
221        let sec = DsmccSection::parse(&bytes).unwrap();
222        assert_eq!(sec.table_id, 0x3C);
223        assert_eq!(sec.payload, &[0xAA, 0xBB]);
224    }
225
226    #[test]
227    fn parse_payload_preserved() {
228        let payload = vec![0x01, 0x02, 0x03, 0x04, 0x05];
229        let bytes = build_dsmcc(0x3B, 0x0001, 0, &payload);
230        let sec = DsmccSection::parse(&bytes).unwrap();
231        assert_eq!(sec.payload, &payload[..]);
232    }
233
234    #[test]
235    fn serialize_round_trip_empty() {
236        let sec = DsmccSection {
237            table_id: 0x3B,
238            extension_id: 0x0001,
239            version_number: 0,
240            current_next_indicator: true,
241            section_number: 0,
242            last_section_number: 0,
243            payload: &[],
244        };
245        let mut buf = vec![0u8; sec.serialized_len()];
246        sec.serialize_into(&mut buf).unwrap();
247        let reparsed = DsmccSection::parse(&buf).unwrap();
248        assert_eq!(sec, reparsed);
249    }
250
251    #[test]
252    fn serialize_round_trip_with_payload() {
253        let payload: [u8; 5] = [0xDE, 0xAD, 0xBE, 0xEF, 0x00];
254        let sec = DsmccSection {
255            table_id: 0x3C,
256            extension_id: 0xABCD,
257            version_number: 3,
258            current_next_indicator: true,
259            section_number: 1,
260            last_section_number: 2,
261            payload: &payload,
262        };
263        let mut buf = vec![0u8; sec.serialized_len()];
264        sec.serialize_into(&mut buf).unwrap();
265        let reparsed = DsmccSection::parse(&buf).unwrap();
266        assert_eq!(sec, reparsed);
267    }
268}