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))]
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    pub container_data: &'a [u8],
79}
80
81impl<'a> Parse<'a> for Container<'a> {
82    type Error = crate::error::Error;
83
84    fn parse(bytes: &'a [u8]) -> Result<Self> {
85        if bytes.len() < MIN_LEN {
86            return Err(Error::BufferTooShort {
87                need: MIN_LEN,
88                have: bytes.len(),
89                what: "Container",
90            });
91        }
92
93        if bytes[0] != TABLE_ID {
94            return Err(Error::UnexpectedTableId {
95                table_id: bytes[0],
96                what: "Container",
97                expected: &[TABLE_ID],
98            });
99        }
100
101        // byte 1 = section_syntax_indicator(1) | private_indicator(1)
102        //          | reserved(2) | private_section_length[11:8](4)
103        // byte 2 = private_section_length[7:0]
104        let section_length = (((bytes[1] & 0x0F) as usize) << 8) | bytes[2] as usize;
105        let total = HEADER_LEN + section_length;
106        if bytes.len() < total {
107            return Err(Error::SectionLengthOverflow {
108                declared: section_length,
109                available: bytes.len() - HEADER_LEN,
110            });
111        }
112
113        let private_indicator = (bytes[1] & 0x40) != 0;
114
115        // Extension header (bytes 3..8).
116        let container_id = u16::from_be_bytes([bytes[3], bytes[4]]);
117        // byte 5: reserved(2) | version_number(5) | current_next_indicator(1)
118        let version_number = (bytes[5] >> 1) & 0x1F;
119        let current_next_indicator = (bytes[5] & 0x01) != 0;
120        let section_number = bytes[6];
121        let last_section_number = bytes[7];
122
123        // container_data: from end of extension header up to (not including) CRC.
124        let data_start = HEADER_LEN + EXTENSION_HEADER_LEN;
125        let data_end = total - CRC_LEN;
126        let container_data = &bytes[data_start..data_end];
127
128        Ok(Container {
129            private_indicator,
130            container_id,
131            version_number,
132            current_next_indicator,
133            section_number,
134            last_section_number,
135            container_data,
136        })
137    }
138}
139
140impl Serialize for Container<'_> {
141    type Error = crate::error::Error;
142
143    fn serialized_len(&self) -> usize {
144        HEADER_LEN + EXTENSION_HEADER_LEN + self.container_data.len() + CRC_LEN
145    }
146
147    fn serialize_into(&self, buf: &mut [u8]) -> Result<usize> {
148        let len = self.serialized_len();
149        if buf.len() < len {
150            return Err(Error::OutputBufferTooSmall {
151                need: len,
152                have: buf.len(),
153            });
154        }
155
156        let section_length = (len - HEADER_LEN) as u16;
157
158        // Byte 0: table_id.
159        buf[0] = TABLE_ID;
160        // Byte 1: section_syntax_indicator(1)=1 | private_indicator(1)
161        //         | reserved(2)=11 | private_section_length[11:8](4).
162        buf[1] = 0x80
163            | (u8::from(self.private_indicator) << 6)
164            | 0x30
165            | ((section_length >> 8) as u8 & 0x0F);
166        // Byte 2: private_section_length[7:0].
167        buf[2] = (section_length & 0xFF) as u8;
168
169        // Extension header.
170        buf[3..5].copy_from_slice(&self.container_id.to_be_bytes());
171        buf[5] = 0xC0 // reserved(2) = 11
172            | ((self.version_number & 0x1F) << 1)
173            | u8::from(self.current_next_indicator);
174        buf[6] = self.section_number;
175        buf[7] = self.last_section_number;
176
177        // container_data.
178        let data_start = HEADER_LEN + EXTENSION_HEADER_LEN;
179        let data_end = data_start + self.container_data.len();
180        buf[data_start..data_end].copy_from_slice(self.container_data);
181
182        // CRC-32 over everything up to (but not including) the CRC slot.
183        let crc = dvb_common::crc32_mpeg2::compute(&buf[..data_end]);
184        buf[data_end..len].copy_from_slice(&crc.to_be_bytes());
185
186        Ok(len)
187    }
188}
189
190impl<'a> Table<'a> for Container<'a> {
191    const TABLE_ID: u8 = TABLE_ID;
192    const PID: u16 = PID;
193}
194
195impl<'a> crate::traits::TableDef<'a> for Container<'a> {
196    const TABLE_ID_RANGES: &'static [(u8, u8)] = &[(TABLE_ID, TABLE_ID)];
197    const NAME: &'static str = "CONTAINER";
198}
199
200#[cfg(test)]
201mod tests {
202    use super::*;
203
204    /// Build a syntactically valid Container section. `container_data` is pasted
205    /// verbatim; the CRC slot is filled by the serializer.
206    fn build_container(
207        container_id: u16,
208        version: u8,
209        current_next: bool,
210        section_number: u8,
211        last_section_number: u8,
212        container_data: &[u8],
213    ) -> Vec<u8> {
214        let c = Container {
215            private_indicator: true,
216            container_id,
217            version_number: version,
218            current_next_indicator: current_next,
219            section_number,
220            last_section_number,
221            container_data,
222        };
223        let mut buf = vec![0u8; c.serialized_len()];
224        c.serialize_into(&mut buf).unwrap();
225        buf
226    }
227
228    #[test]
229    fn parse_happy_path() {
230        let data = [0x00u8, 0xDE, 0xAD, 0xBE, 0xEF];
231        let bytes = build_container(0x1234, 7, true, 1, 3, &data);
232        let c = Container::parse(&bytes).unwrap();
233        assert!(c.private_indicator);
234        assert_eq!(c.container_id, 0x1234);
235        assert_eq!(c.version_number, 7);
236        assert!(c.current_next_indicator);
237        assert_eq!(c.section_number, 1);
238        assert_eq!(c.last_section_number, 3);
239        assert_eq!(c.container_data, &data[..]);
240    }
241
242    #[test]
243    fn parse_empty_container_data() {
244        let bytes = build_container(0x0000, 0, false, 0, 0, &[]);
245        let c = Container::parse(&bytes).unwrap();
246        assert_eq!(c.container_id, 0x0000);
247        assert_eq!(c.version_number, 0);
248        assert!(!c.current_next_indicator);
249        assert!(c.container_data.is_empty());
250    }
251
252    #[test]
253    fn parse_rejects_wrong_tag() {
254        let mut bytes = build_container(0x0001, 0, true, 0, 0, &[]);
255        bytes[0] = 0x70; // not 0x75
256        assert!(matches!(
257            Container::parse(&bytes).unwrap_err(),
258            Error::UnexpectedTableId { table_id: 0x70, .. }
259        ));
260    }
261
262    #[test]
263    fn parse_rejects_short_buffer() {
264        assert!(matches!(
265            Container::parse(&[0x75, 0x80]).unwrap_err(),
266            Error::BufferTooShort { .. }
267        ));
268    }
269
270    #[test]
271    fn parse_rejects_section_length_overflow() {
272        let mut bytes = build_container(0x0001, 0, true, 0, 0, &[]);
273        let fake_sl: u16 = (bytes.len() as u16) + 100 - HEADER_LEN as u16;
274        bytes[1] = (bytes[1] & 0xF0) | ((fake_sl >> 8) as u8 & 0x0F);
275        bytes[2] = (fake_sl & 0xFF) as u8;
276        assert!(matches!(
277            Container::parse(&bytes).unwrap_err(),
278            Error::SectionLengthOverflow { .. }
279        ));
280    }
281
282    #[test]
283    fn serialize_round_trip() {
284        let data = [0x01u8, 0x02, 0x03];
285        let original = Container {
286            private_indicator: false,
287            container_id: 0xABCD,
288            version_number: 15,
289            current_next_indicator: false,
290            section_number: 2,
291            last_section_number: 4,
292            container_data: &data,
293        };
294        let mut buf = vec![0u8; original.serialized_len()];
295        original.serialize_into(&mut buf).unwrap();
296        assert_eq!(Container::parse(&buf).unwrap(), original);
297    }
298
299    #[test]
300    fn serialize_rejects_output_buffer_too_small() {
301        let c = Container {
302            private_indicator: false,
303            container_id: 0x0001,
304            version_number: 0,
305            current_next_indicator: true,
306            section_number: 0,
307            last_section_number: 0,
308            container_data: &[],
309        };
310        let mut buf = vec![0u8; 2];
311        assert!(matches!(
312            c.serialize_into(&mut buf).unwrap_err(),
313            Error::OutputBufferTooSmall { .. }
314        ));
315    }
316
317    #[test]
318    fn table_trait_constants() {
319        assert_eq!(<Container as Table>::TABLE_ID, 0x75);
320        assert_eq!(<Container as Table>::PID, 0x0000);
321    }
322
323    #[cfg(feature = "serde")]
324    #[test]
325    fn serde_json_round_trip() {
326        // `container_data` is a borrowed `&[u8]` (the rnt/cit idiom), so a
327        // deserialize round-trip is not possible — serde encodes a byte slice
328        // as a JSON sequence which cannot be re-borrowed. Mirror the borrowed
329        // tables by asserting serialization yields valid, field-bearing JSON.
330        let data = [0xCAu8, 0xFE];
331        let bytes = build_container(0xBEEF, 9, true, 0, 0, &data);
332        let c = Container::parse(&bytes).unwrap();
333        let v: serde_json::Value = serde_json::to_value(&c).unwrap();
334        assert_eq!(v["container_id"], 0xBEEF);
335        assert_eq!(v["version_number"], 9);
336        assert_eq!(v["current_next_indicator"], true);
337        assert_eq!(v["container_data"], serde_json::json!([0xCA, 0xFE]));
338    }
339}