Skip to main content

dvb_si/tables/
container.rs

1//! Container Table — ETSI TS 102 323 v1.4.1 §7.3.1.4 (table_id 0x75).
2//!
3//! The container section carries TV-Anytime container data (an MHP object
4//! carousel file fragment, after optional compression). Syntax per "Table 20 —
5//! Container section" (`dvb-si/docs/ts_102_323_tva.md`, §7.3.1.4, PDF p. 36):
6//!
7//! ```text
8//! container_section() {
9//!   table_id                 8   (0x75)
10//!   section_syntax_indicator 1
11//!   private_indicator        1
12//!   reserved                 2
13//!   private_section_length  12
14//!   container_id            16   (table_id_extension)
15//!   reserved                 2
16//!   version_number           5
17//!   current_next_indicator   1
18//!   section_number           8
19//!   last_section_number      8
20//!   container_data()        N*8
21//!   CRC_32                  32
22//! }
23//! ```
24//!
25//! This is a private section (the spec's byte-1 bit 6 is `private_indicator`),
26//! so it is handled with the same idiom as [`crate::tables::cit`]. The
27//! `container_data` payload is kept as a borrowed raw slice; its internal
28//! structure (compression_wrapper / object-carousel fragments) is out of scope.
29//!
30//! Carriage is signalled via descriptors (no well-known PID), following the
31//! [`crate::tables::dsmcc`] precedent of `PID = 0x0000`.
32
33use crate::error::{Error, Result};
34use crate::traits::Table;
35use dvb_common::{Parse, Serialize};
36
37/// table_id for the Container Table.
38pub const TABLE_ID: u8 = 0x75;
39
40/// The Container Table has no well-known PID — its carriage is signalled via
41/// descriptors. `0x0000` is a placeholder following the DSM-CC precedent.
42pub const PID: u16 = 0x0000;
43
44/// Bytes 0-2: table_id (1) + flags + private_section_length (2).
45const HEADER_LEN: usize = 3;
46
47/// Bytes 3-7: container_id(2) + reserved/version/cni(1) + section_number(1)
48/// + last_section_number(1).
49const EXTENSION_HEADER_LEN: usize = 5;
50
51/// Bytes occupied by the trailing CRC-32 field.
52const CRC_LEN: usize = 4;
53
54/// Minimum total encoded length: header + extension + CRC.
55const MIN_LEN: usize = HEADER_LEN + EXTENSION_HEADER_LEN + CRC_LEN;
56
57/// Container Table (ETSI TS 102 323 v1.4.1 §7.3.1.4).
58///
59/// `container_data` borrows the payload region (everything between the extension
60/// header and the CRC-32 trailer) without parsing its internal structure.
61#[derive(Debug, Clone, PartialEq, Eq)]
62#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
63pub struct Container<'a> {
64    /// `private_indicator` bit from byte 1 (this is a private section).
65    pub private_indicator: bool,
66    /// 16-bit `container_id` (carried in the table_id_extension slot, bytes 3-4).
67    pub container_id: u16,
68    /// 5-bit `version_number`.
69    pub version_number: u8,
70    /// `current_next_indicator` bit.
71    pub current_next_indicator: bool,
72    /// section_number in the sub-table sequence.
73    pub section_number: u8,
74    /// last_section_number in the sub-table sequence.
75    pub last_section_number: u8,
76    /// Raw `container_data` bytes (everything between the extension header and
77    /// the CRC-32 trailer). Internal structure is not parsed.
78    #[cfg_attr(feature = "serde", serde(borrow))]
79    pub container_data: &'a [u8],
80}
81
82impl<'a> Parse<'a> for Container<'a> {
83    type Error = crate::error::Error;
84
85    fn parse(bytes: &'a [u8]) -> Result<Self> {
86        if bytes.len() < MIN_LEN {
87            return Err(Error::BufferTooShort {
88                need: MIN_LEN,
89                have: bytes.len(),
90                what: "Container",
91            });
92        }
93
94        if bytes[0] != TABLE_ID {
95            return Err(Error::UnexpectedTableId {
96                table_id: bytes[0],
97                what: "Container",
98                expected: &[TABLE_ID],
99            });
100        }
101
102        // byte 1 = section_syntax_indicator(1) | private_indicator(1)
103        //          | reserved(2) | private_section_length[11:8](4)
104        // byte 2 = private_section_length[7:0]
105        let section_length = (((bytes[1] & 0x0F) as usize) << 8) | bytes[2] as usize;
106        let total = HEADER_LEN + section_length;
107        if bytes.len() < total {
108            return Err(Error::SectionLengthOverflow {
109                declared: section_length,
110                available: bytes.len() - HEADER_LEN,
111            });
112        }
113
114        let private_indicator = (bytes[1] & 0x40) != 0;
115
116        // Extension header (bytes 3..8).
117        let container_id = u16::from_be_bytes([bytes[3], bytes[4]]);
118        // byte 5: reserved(2) | version_number(5) | current_next_indicator(1)
119        let version_number = (bytes[5] >> 1) & 0x1F;
120        let current_next_indicator = (bytes[5] & 0x01) != 0;
121        let section_number = bytes[6];
122        let last_section_number = bytes[7];
123
124        // container_data: from end of extension header up to (not including) CRC.
125        let data_start = HEADER_LEN + EXTENSION_HEADER_LEN;
126        let data_end = total - CRC_LEN;
127        let container_data = &bytes[data_start..data_end];
128
129        Ok(Container {
130            private_indicator,
131            container_id,
132            version_number,
133            current_next_indicator,
134            section_number,
135            last_section_number,
136            container_data,
137        })
138    }
139}
140
141impl Serialize for Container<'_> {
142    type Error = crate::error::Error;
143
144    fn serialized_len(&self) -> usize {
145        HEADER_LEN + EXTENSION_HEADER_LEN + self.container_data.len() + CRC_LEN
146    }
147
148    fn serialize_into(&self, buf: &mut [u8]) -> Result<usize> {
149        let len = self.serialized_len();
150        if buf.len() < len {
151            return Err(Error::OutputBufferTooSmall {
152                need: len,
153                have: buf.len(),
154            });
155        }
156
157        let section_length = (len - HEADER_LEN) as u16;
158
159        // Byte 0: table_id.
160        buf[0] = TABLE_ID;
161        // Byte 1: section_syntax_indicator(1)=1 | private_indicator(1)
162        //         | reserved(2)=11 | private_section_length[11:8](4).
163        buf[1] = 0x80
164            | (u8::from(self.private_indicator) << 6)
165            | 0x30
166            | ((section_length >> 8) as u8 & 0x0F);
167        // Byte 2: private_section_length[7:0].
168        buf[2] = (section_length & 0xFF) as u8;
169
170        // Extension header.
171        buf[3..5].copy_from_slice(&self.container_id.to_be_bytes());
172        buf[5] = 0xC0 // reserved(2) = 11
173            | ((self.version_number & 0x1F) << 1)
174            | u8::from(self.current_next_indicator);
175        buf[6] = self.section_number;
176        buf[7] = self.last_section_number;
177
178        // container_data.
179        let data_start = HEADER_LEN + EXTENSION_HEADER_LEN;
180        let data_end = data_start + self.container_data.len();
181        buf[data_start..data_end].copy_from_slice(self.container_data);
182
183        // CRC-32 over everything up to (but not including) the CRC slot.
184        let crc = dvb_common::crc32_mpeg2::compute(&buf[..data_end]);
185        buf[data_end..len].copy_from_slice(&crc.to_be_bytes());
186
187        Ok(len)
188    }
189}
190
191impl<'a> Table<'a> for Container<'a> {
192    const TABLE_ID: u8 = TABLE_ID;
193    const PID: u16 = PID;
194}
195
196impl<'a> crate::traits::TableDef<'a> for Container<'a> {
197    const TABLE_ID_RANGES: &'static [(u8, u8)] = &[(TABLE_ID, TABLE_ID)];
198    const NAME: &'static str = "CONTAINER";
199}
200
201#[cfg(test)]
202mod tests {
203    use super::*;
204
205    /// Build a syntactically valid Container section. `container_data` is pasted
206    /// verbatim; the CRC slot is filled by the serializer.
207    fn build_container(
208        container_id: u16,
209        version: u8,
210        current_next: bool,
211        section_number: u8,
212        last_section_number: u8,
213        container_data: &[u8],
214    ) -> Vec<u8> {
215        let c = Container {
216            private_indicator: true,
217            container_id,
218            version_number: version,
219            current_next_indicator: current_next,
220            section_number,
221            last_section_number,
222            container_data,
223        };
224        let mut buf = vec![0u8; c.serialized_len()];
225        c.serialize_into(&mut buf).unwrap();
226        buf
227    }
228
229    #[test]
230    fn parse_happy_path() {
231        let data = [0x00u8, 0xDE, 0xAD, 0xBE, 0xEF];
232        let bytes = build_container(0x1234, 7, true, 1, 3, &data);
233        let c = Container::parse(&bytes).unwrap();
234        assert!(c.private_indicator);
235        assert_eq!(c.container_id, 0x1234);
236        assert_eq!(c.version_number, 7);
237        assert!(c.current_next_indicator);
238        assert_eq!(c.section_number, 1);
239        assert_eq!(c.last_section_number, 3);
240        assert_eq!(c.container_data, &data[..]);
241    }
242
243    #[test]
244    fn parse_empty_container_data() {
245        let bytes = build_container(0x0000, 0, false, 0, 0, &[]);
246        let c = Container::parse(&bytes).unwrap();
247        assert_eq!(c.container_id, 0x0000);
248        assert_eq!(c.version_number, 0);
249        assert!(!c.current_next_indicator);
250        assert!(c.container_data.is_empty());
251    }
252
253    #[test]
254    fn parse_rejects_wrong_tag() {
255        let mut bytes = build_container(0x0001, 0, true, 0, 0, &[]);
256        bytes[0] = 0x70; // not 0x75
257        assert!(matches!(
258            Container::parse(&bytes).unwrap_err(),
259            Error::UnexpectedTableId { table_id: 0x70, .. }
260        ));
261    }
262
263    #[test]
264    fn parse_rejects_short_buffer() {
265        assert!(matches!(
266            Container::parse(&[0x75, 0x80]).unwrap_err(),
267            Error::BufferTooShort { .. }
268        ));
269    }
270
271    #[test]
272    fn parse_rejects_section_length_overflow() {
273        let mut bytes = build_container(0x0001, 0, true, 0, 0, &[]);
274        let fake_sl: u16 = (bytes.len() as u16) + 100 - HEADER_LEN as u16;
275        bytes[1] = (bytes[1] & 0xF0) | ((fake_sl >> 8) as u8 & 0x0F);
276        bytes[2] = (fake_sl & 0xFF) as u8;
277        assert!(matches!(
278            Container::parse(&bytes).unwrap_err(),
279            Error::SectionLengthOverflow { .. }
280        ));
281    }
282
283    #[test]
284    fn serialize_round_trip() {
285        let data = [0x01u8, 0x02, 0x03];
286        let original = Container {
287            private_indicator: false,
288            container_id: 0xABCD,
289            version_number: 15,
290            current_next_indicator: false,
291            section_number: 2,
292            last_section_number: 4,
293            container_data: &data,
294        };
295        let mut buf = vec![0u8; original.serialized_len()];
296        original.serialize_into(&mut buf).unwrap();
297        assert_eq!(Container::parse(&buf).unwrap(), original);
298    }
299
300    #[test]
301    fn serialize_rejects_output_buffer_too_small() {
302        let c = Container {
303            private_indicator: false,
304            container_id: 0x0001,
305            version_number: 0,
306            current_next_indicator: true,
307            section_number: 0,
308            last_section_number: 0,
309            container_data: &[],
310        };
311        let mut buf = vec![0u8; 2];
312        assert!(matches!(
313            c.serialize_into(&mut buf).unwrap_err(),
314            Error::OutputBufferTooSmall { .. }
315        ));
316    }
317
318    #[test]
319    fn table_trait_constants() {
320        assert_eq!(<Container as Table>::TABLE_ID, 0x75);
321        assert_eq!(<Container as Table>::PID, 0x0000);
322    }
323
324    #[cfg(feature = "serde")]
325    #[test]
326    fn serde_json_round_trip() {
327        // `container_data` is a borrowed `&[u8]` (the rnt/cit idiom), so a
328        // deserialize round-trip is not possible — serde encodes a byte slice
329        // as a JSON sequence which cannot be re-borrowed. Mirror the borrowed
330        // tables by asserting serialization yields valid, field-bearing JSON.
331        let data = [0xCAu8, 0xFE];
332        let bytes = build_container(0xBEEF, 9, true, 0, 0, &data);
333        let c = Container::parse(&bytes).unwrap();
334        let v: serde_json::Value = serde_json::to_value(&c).unwrap();
335        assert_eq!(v["container_id"], 0xBEEF);
336        assert_eq!(v["version_number"], 9);
337        assert_eq!(v["current_next_indicator"], true);
338        assert_eq!(v["container_data"], serde_json::json!([0xCA, 0xFE]));
339    }
340}