Skip to main content

dvb_si/tables/
container.rs

1//! Container table section — 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" (`private/specs-verified/dvb/dvb-si/`, §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 broadcast_common::len::{need_in, need_out};
35use broadcast_common::{Parse, Serialize};
36
37/// table_id for the Container table.
38pub const TABLE_ID: u8 = 0x75;
39
40// No fixed PID: this table's PID is signalled (PMT / descriptors). A `PID`
41// constant of `0x0000` used to sit here, which is the real PAT PID, so a
42// caller filtering on it would pick up PAT traffic (audit r02-W15/O12).
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
51use super::CRC_LEN;
52
53/// Minimum total encoded length: header + extension + CRC.
54const MIN_LEN: usize = HEADER_LEN + EXTENSION_HEADER_LEN + CRC_LEN;
55
56/// Container table section parser (ETSI TS 102 323 v1.4.1 §7.3.1.4).
57///
58/// `container_data` borrows the payload region (everything between the extension
59/// header and the CRC-32 trailer) without parsing its internal structure.
60#[derive(Debug, Clone, PartialEq, Eq)]
61#[cfg_attr(feature = "serde", derive(serde::Serialize))]
62#[cfg_attr(feature = "yoke", derive(yoke::Yokeable))]
63#[non_exhaustive]
64pub struct ContainerSection<'a> {
65    /// `section_syntax_indicator` (byte 1 bit 7): `1` for a constructed value,
66    /// whatever the wire carried for a parsed one (parse tolerant, serialize
67    /// preserves).
68    pub section_syntax_indicator: bool,
69    /// `private_indicator` bit from byte 1 (this is a private section).
70    pub private_indicator: bool,
71    /// 16-bit `container_id` (carried in the table_id_extension slot, bytes 3-4).
72    pub container_id: u16,
73    /// 5-bit `version_number`.
74    pub version_number: u8,
75    /// `current_next_indicator` bit.
76    pub current_next_indicator: bool,
77    /// section_number in the sub-table sequence.
78    pub section_number: u8,
79    /// last_section_number in the sub-table sequence.
80    pub last_section_number: u8,
81    /// Raw `container_data` bytes (everything between the extension header and
82    /// the CRC-32 trailer). Internal structure is not parsed.
83    pub container_data: &'a [u8],
84    /// `reserved(2)` in byte 1 bits `[5:4]` (`11`); preserved from the wire.
85    #[cfg_attr(feature = "serde", serde(skip))]
86    pub reserved_b1: u8,
87    /// `reserved(2)` in front of `version_number` (`11`); preserved.
88    #[cfg_attr(feature = "serde", serde(skip))]
89    pub reserved_b5: u8,
90}
91
92impl<'a> ContainerSection<'a> {
93    /// Construct a Container section with the spec `reserved` fill.
94    #[must_use]
95    pub fn new(
96        private_indicator: bool,
97        container_id: u16,
98        version_number: u8,
99        current_next_indicator: bool,
100        section_number: u8,
101        last_section_number: u8,
102        container_data: &'a [u8],
103    ) -> Self {
104        Self {
105            section_syntax_indicator: true,
106            private_indicator,
107            container_id,
108            version_number,
109            current_next_indicator,
110            section_number,
111            last_section_number,
112            container_data,
113            reserved_b1: super::RESERVED_2,
114            reserved_b5: super::RESERVED_2,
115        }
116    }
117}
118
119impl<'a> Parse<'a> for ContainerSection<'a> {
120    type Error = crate::error::Error;
121
122    fn parse(bytes: &'a [u8]) -> Result<Self> {
123        need_in(bytes, MIN_LEN, "ContainerSection")?;
124
125        if bytes[0] != TABLE_ID {
126            return Err(Error::UnexpectedTableId {
127                table_id: bytes[0],
128                what: "ContainerSection",
129                expected: &[TABLE_ID],
130            });
131        }
132
133        // byte 1 = section_syntax_indicator(1) | private_indicator(1)
134        //          | reserved(2) | private_section_length[11:8](4)
135        // byte 2 = private_section_length[7:0]
136        let section_length = super::section_length_of(bytes);
137        let total = super::check_section_length(bytes.len(), HEADER_LEN, section_length, MIN_LEN)?;
138
139        let private_indicator = (bytes[1] & super::SECTION_B1_PRIVATE_INDICATOR) != 0;
140
141        // Extension header (bytes 3..8).
142        let container_id = crate::wire::be_u16(bytes, 3, "container")?;
143        // byte 5: reserved(2) | version_number(5) | current_next_indicator(1)
144        let version_number = super::version_number_of(bytes[5]);
145        let current_next_indicator = super::current_next_of(bytes[5]);
146        let section_number = bytes[6];
147        let last_section_number = bytes[7];
148
149        // container_data: from end of extension header up to (not including) CRC.
150        let data_start = HEADER_LEN + EXTENSION_HEADER_LEN;
151        let data_end = total - CRC_LEN;
152        let container_data = &bytes[data_start..data_end];
153
154        Ok(ContainerSection {
155            section_syntax_indicator: bytes[1] & super::SECTION_B1_SSI != 0,
156            private_indicator,
157            container_id,
158            version_number,
159            current_next_indicator,
160            section_number,
161            last_section_number,
162            container_data,
163            reserved_b1: super::b1_reserved_of(bytes[1]),
164            reserved_b5: super::b5_reserved_of(bytes[5]),
165        })
166    }
167}
168
169impl Serialize for ContainerSection<'_> {
170    type Error = crate::error::Error;
171
172    fn serialized_len(&self) -> usize {
173        HEADER_LEN + EXTENSION_HEADER_LEN + self.container_data.len() + CRC_LEN
174    }
175
176    fn serialize_into(&self, buf: &mut [u8]) -> Result<usize> {
177        let len = self.serialized_len();
178        need_out(buf, len)?;
179
180        // Byte 0: table_id.
181        buf[0] = TABLE_ID;
182        // Byte 1: section_syntax_indicator(1)=1 | private_indicator(1)
183        //         | reserved(2)=11 | private_section_length[11:8](4).
184        buf[1] = super::b1_of(
185            self.section_syntax_indicator,
186            self.private_indicator,
187            self.reserved_b1,
188        )?;
189        // Byte 2: private_section_length[7:0].
190        super::write_section_length(buf, len - HEADER_LEN)?;
191
192        // Extension header.
193        buf[3..5].copy_from_slice(&self.container_id.to_be_bytes());
194        buf[5] = super::b5_of(
195            self.reserved_b5,
196            self.version_number,
197            self.current_next_indicator,
198        )?;
199        buf[6] = self.section_number;
200        buf[7] = self.last_section_number;
201
202        // container_data.
203        let data_start = HEADER_LEN + EXTENSION_HEADER_LEN;
204        let data_end = data_start + self.container_data.len();
205        buf[data_start..data_end].copy_from_slice(self.container_data);
206
207        // CRC-32 over everything up to (but not including) the CRC slot.
208        super::write_crc(buf, data_end);
209
210        Ok(len)
211    }
212}
213impl<'a> crate::traits::TableDef<'a> for ContainerSection<'a> {
214    const TABLE_ID_RANGES: &'static [(u8, u8)] = &[(TABLE_ID, TABLE_ID)];
215    const NAME: &'static str = "CONTAINER";
216}
217
218#[cfg(test)]
219mod tests {
220    use super::*;
221
222    /// Build a syntactically valid Container section. `container_data` is pasted
223    /// verbatim; the CRC slot is filled by the serializer.
224    fn build_container(
225        container_id: u16,
226        version: u8,
227        current_next: bool,
228        section_number: u8,
229        last_section_number: u8,
230        container_data: &[u8],
231    ) -> Vec<u8> {
232        let c = ContainerSection::new(
233            true,
234            container_id,
235            version,
236            current_next,
237            section_number,
238            last_section_number,
239            container_data,
240        );
241        let mut buf = vec![0u8; c.serialized_len()];
242        c.serialize_into(&mut buf).unwrap();
243        buf
244    }
245
246    #[test]
247    fn parse_happy_path() {
248        let data = [0x00u8, 0xDE, 0xAD, 0xBE, 0xEF];
249        let bytes = build_container(0x1234, 7, true, 1, 3, &data);
250        let c = ContainerSection::parse(&bytes).unwrap();
251        assert!(c.private_indicator);
252        assert_eq!(c.container_id, 0x1234);
253        assert_eq!(c.version_number, 7);
254        assert!(c.current_next_indicator);
255        assert_eq!(c.section_number, 1);
256        assert_eq!(c.last_section_number, 3);
257        assert_eq!(c.container_data, &data[..]);
258    }
259
260    #[test]
261    fn parse_empty_container_data() {
262        let bytes = build_container(0x0000, 0, false, 0, 0, &[]);
263        let c = ContainerSection::parse(&bytes).unwrap();
264        assert_eq!(c.container_id, 0x0000);
265        assert_eq!(c.version_number, 0);
266        assert!(!c.current_next_indicator);
267        assert!(c.container_data.is_empty());
268    }
269
270    #[test]
271    fn parse_rejects_wrong_tag() {
272        let mut bytes = build_container(0x0001, 0, true, 0, 0, &[]);
273        bytes[0] = 0x70; // not 0x75
274        assert!(matches!(
275            ContainerSection::parse(&bytes).unwrap_err(),
276            Error::UnexpectedTableId { table_id: 0x70, .. }
277        ));
278    }
279
280    #[test]
281    fn parse_rejects_short_buffer() {
282        assert!(matches!(
283            ContainerSection::parse(&[0x75, 0x80]).unwrap_err(),
284            Error::BufferTooShort(..)
285        ));
286    }
287
288    #[test]
289    fn parse_rejects_section_length_overflow() {
290        let mut bytes = build_container(0x0001, 0, true, 0, 0, &[]);
291        let fake_sl: u16 = (bytes.len() as u16) + 100 - HEADER_LEN as u16;
292        bytes[1] = (bytes[1] & 0xF0) | ((fake_sl >> 8) as u8 & 0x0F);
293        bytes[2] = (fake_sl & 0xFF) as u8;
294        assert!(matches!(
295            ContainerSection::parse(&bytes).unwrap_err(),
296            Error::SectionLengthOverflow { .. }
297        ));
298    }
299
300    #[test]
301    fn serialize_round_trip() {
302        let data = [0x01u8, 0x02, 0x03];
303        let original = ContainerSection::new(false, 0xABCD, 15, false, 2, 4, &data);
304        let mut buf = vec![0u8; original.serialized_len()];
305        original.serialize_into(&mut buf).unwrap();
306        assert_eq!(ContainerSection::parse(&buf).unwrap(), original);
307    }
308
309    #[test]
310    fn serialize_rejects_output_buffer_too_small() {
311        let c = ContainerSection::new(false, 0x0001, 0, true, 0, 0, &[]);
312        let mut buf = vec![0u8; 2];
313        assert!(matches!(
314            c.serialize_into(&mut buf).unwrap_err(),
315            Error::OutputBufferTooSmall(..)
316        ));
317    }
318
319    #[test]
320    fn table_trait_constants() {
321        assert_eq!(TABLE_ID, 0x75);
322    }
323
324    #[test]
325    fn parse_rejects_zero_section_length() {
326        let mut buf = vec![0u8; 64];
327        buf[0] = TABLE_ID;
328        buf[1] = 0xF0;
329        buf[2] = 0x00;
330        for b in &mut buf[3..] {
331            *b = 0xFF;
332        }
333        assert!(matches!(
334            ContainerSection::parse(&buf).unwrap_err(),
335            Error::SectionLengthOverflow { .. }
336        ));
337    }
338
339    /// private_section_length is 12 bits (max 4095 =
340    /// EXTENSION_HEADER_LEN(5) + container_data + CRC_LEN(4), so 4086 is
341    /// the largest container_data that fits).
342    #[test]
343    fn serialize_rejects_container_data_exceeding_section_length() {
344        let data = vec![0xAAu8; 4087];
345        let c = ContainerSection::new(false, 1, 0, true, 0, 0, &data);
346        let mut buf = vec![0u8; c.serialized_len()];
347        assert!(matches!(
348            c.serialize_into(&mut buf).unwrap_err(),
349            Error::FieldOverflow(_)
350        ));
351    }
352
353    #[test]
354    fn serialize_accepts_container_data_at_section_length_boundary() {
355        let data = vec![0xAAu8; 4086];
356        let c = ContainerSection::new(false, 1, 0, true, 0, 0, &data);
357        let mut buf = vec![0u8; c.serialized_len()];
358        c.serialize_into(&mut buf).expect("boundary fits");
359        let reparsed = ContainerSection::parse(&buf).expect("reparse");
360        assert_eq!(c, reparsed);
361    }
362
363    #[cfg(feature = "serde")]
364    #[test]
365    fn serde_json_round_trip() {
366        // `container_data` is a borrowed `&[u8]` (the rnt/cit idiom), so a
367        // deserialize round-trip is not possible — serde encodes a byte slice
368        // as a JSON sequence which cannot be re-borrowed. Mirror the borrowed
369        // tables by asserting serialization yields valid, field-bearing JSON.
370        let data = [0xCAu8, 0xFE];
371        let bytes = build_container(0xBEEF, 9, true, 0, 0, &data);
372        let c = ContainerSection::parse(&bytes).unwrap();
373        let v: serde_json::Value = serde_json::to_value(&c).unwrap();
374        assert_eq!(v["container_id"], 0xBEEF);
375        assert_eq!(v["version_number"], 9);
376        assert_eq!(v["current_next_indicator"], true);
377        assert_eq!(v["container_data"], serde_json::json!([0xCA, 0xFE]));
378    }
379}