Skip to main content

dvb_si/tables/
cit.rs

1//! Content Identifier Table — ETSI TS 102 323 v1.4.1 §12.2.
2//!
3//! The CIT maps content reference identifiers (CRIDs) to events for a given
4//! service. Carried on PID 0x0012 (shared with the EIT) with table_id 0x77.
5//! Structure: fixed header + prepend-string block + raw CRID entry loop + CRC-32.
6
7use crate::error::{Error, Result};
8use crate::traits::Table;
9use dvb_common::{Parse, Serialize};
10
11/// table_id for Content Identifier Table.
12pub const TABLE_ID: u8 = 0x77;
13
14/// PID on which CIT sections are carried.
15///
16/// Note: PID 0x0012 is shared with the EIT family; demultiplexers must filter
17/// by table_id in addition to PID to isolate CIT sections.
18pub const PID: u16 = 0x0012;
19
20// ── length constants ──────────────────────────────────────────────────────────
21
22/// Bytes 0-2: table_id (1) + flags+section_length (2).
23const HEADER_LEN: usize = 3;
24
25/// Bytes 3-12: service_id(2) + flags+version+cni(1) + section_number(1)
26/// + last_section_number(1) + transport_stream_id(2) + original_network_id(2)
27/// + prepend_strings_length(1).
28const EXTENSION_LEN: usize = 10;
29
30/// Minimum total encoded length: header + extension + CRC.
31const MIN_SECTION_LEN: usize = HEADER_LEN + EXTENSION_LEN + CRC_LEN;
32
33/// Bytes occupied by the trailing CRC-32 field.
34const CRC_LEN: usize = 4;
35
36// ── struct ────────────────────────────────────────────────────────────────────
37
38/// Content Identifier Table (ETSI TS 102 323 v1.4.1 §12.2).
39///
40/// Variable-length fields are kept as raw byte slices borrowing from the source
41/// buffer. Callers that need to iterate CRID entries may walk `crid_entries`
42/// directly per the wire format:
43///
44/// ```text
45/// for each entry:
46///   crid_ref             (2 bytes, u16 big-endian)
47///   prepend_string_index (1 byte)
48///   unique_string_length (1 byte)
49///   unique_string_bytes  (unique_string_length bytes)
50/// ```
51#[derive(Debug, Clone, PartialEq, Eq)]
52#[cfg_attr(feature = "serde", derive(serde::Serialize))]
53pub struct Cit<'a> {
54    /// `private_indicator` bit from byte 1.
55    pub private_indicator: bool,
56
57    /// `service_id` — identifies the container this section belongs to
58    /// (table_id_extension, bytes 3-4).
59    pub service_id: u16,
60
61    /// 5-bit `version_number`.
62    pub version_number: u8,
63
64    /// `current_next_indicator` bit.
65    pub current_next_indicator: bool,
66
67    /// Section counter within the sub-table.
68    pub section_number: u8,
69
70    /// Final section number in the sub-table.
71    pub last_section_number: u8,
72
73    /// `transport_stream_id` of the carrying TS.
74    pub transport_stream_id: u16,
75
76    /// `original_network_id` of the originating network.
77    pub original_network_id: u16,
78
79    /// Raw prepend-string block. The wire `prepend_strings_length` byte is
80    /// derived from `prepend_strings.len()` on serialize (≤ 255). Entries are
81    /// null-terminated ASCII/DVB-text fragments; addressed by index from the
82    /// CRID loop.
83    pub prepend_strings: &'a [u8],
84
85    /// Raw CRID entry loop (everything between the prepend-string block and the
86    /// CRC-32). Walk per the format documented on the struct.
87    pub crid_entries: &'a [u8],
88}
89
90// ── Parse ─────────────────────────────────────────────────────────────────────
91
92impl<'a> Parse<'a> for Cit<'a> {
93    type Error = crate::error::Error;
94
95    fn parse(bytes: &'a [u8]) -> Result<Self> {
96        // Minimum-length guard.
97        if bytes.len() < MIN_SECTION_LEN {
98            return Err(Error::BufferTooShort {
99                need: MIN_SECTION_LEN,
100                have: bytes.len(),
101                what: "Cit",
102            });
103        }
104
105        // table_id check.
106        if bytes[0] != TABLE_ID {
107            return Err(Error::UnexpectedTableId {
108                table_id: bytes[0],
109                what: "Cit",
110                expected: &[TABLE_ID],
111            });
112        }
113
114        // section_length: lower 4 bits of byte 1 || byte 2 (12 bits total).
115        let section_length = (((bytes[1] & 0x0F) as usize) << 8) | bytes[2] as usize;
116        let total = HEADER_LEN + section_length;
117        if bytes.len() < total {
118            return Err(Error::SectionLengthOverflow {
119                declared: section_length,
120                available: bytes.len() - HEADER_LEN,
121            });
122        }
123
124        // private_indicator: bit 6 of byte 1 (section_syntax_indicator is bit 7).
125        let private_indicator = (bytes[1] & 0x40) != 0;
126
127        // Extension header (bytes 3..13).
128        let service_id = u16::from_be_bytes([bytes[3], bytes[4]]);
129        // byte 5: reserved(2) | version_number(5) | current_next_indicator(1)
130        let version_number = (bytes[5] >> 1) & 0x1F;
131        let current_next_indicator = (bytes[5] & 0x01) != 0;
132        let section_number = bytes[6];
133        let last_section_number = bytes[7];
134        let transport_stream_id = u16::from_be_bytes([bytes[8], bytes[9]]);
135        let original_network_id = u16::from_be_bytes([bytes[10], bytes[11]]);
136        let prepend_strings_length = bytes[12];
137
138        // Prepend-string block.
139        let ps_start = HEADER_LEN + EXTENSION_LEN;
140        let ps_end = ps_start + prepend_strings_length as usize;
141
142        // Ensure prepend_strings block fits before the CRC.
143        let payload_end = total - CRC_LEN;
144        if ps_end > payload_end {
145            return Err(Error::SectionLengthOverflow {
146                declared: prepend_strings_length as usize,
147                available: payload_end.saturating_sub(ps_start),
148            });
149        }
150
151        let prepend_strings = &bytes[ps_start..ps_end];
152
153        // Raw CRID entry loop: everything between prepend_strings and the CRC.
154        let crid_entries = &bytes[ps_end..payload_end];
155
156        Ok(Cit {
157            private_indicator,
158            service_id,
159            version_number,
160            current_next_indicator,
161            section_number,
162            last_section_number,
163            transport_stream_id,
164            original_network_id,
165            prepend_strings,
166            crid_entries,
167        })
168    }
169}
170
171// ── Serialize ─────────────────────────────────────────────────────────────────
172
173impl Serialize for Cit<'_> {
174    type Error = crate::error::Error;
175
176    fn serialized_len(&self) -> usize {
177        HEADER_LEN + EXTENSION_LEN + self.prepend_strings.len() + self.crid_entries.len() + CRC_LEN
178    }
179
180    fn serialize_into(&self, buf: &mut [u8]) -> Result<usize> {
181        let len = self.serialized_len();
182        if buf.len() < len {
183            return Err(Error::OutputBufferTooSmall {
184                need: len,
185                have: buf.len(),
186            });
187        }
188
189        // prepend_strings_length is an 8-bit wire field, derived from the slice.
190        if self.prepend_strings.len() > u8::MAX as usize {
191            return Err(Error::SectionLengthOverflow {
192                declared: self.prepend_strings.len(),
193                available: u8::MAX as usize,
194            });
195        }
196
197        let section_length = (len - HEADER_LEN) as u16;
198
199        // Byte 0: table_id.
200        buf[0] = TABLE_ID;
201
202        // Byte 1: section_syntax_indicator(1) | private_indicator(1) | reserved(2) | section_length[11:8](4).
203        // section_syntax_indicator = 1 (long-form section per DVB convention).
204        buf[1] = 0x80
205            | (u8::from(self.private_indicator) << 6)
206            | 0x30 // reserved bits set
207            | ((section_length >> 8) as u8 & 0x0F);
208
209        // Byte 2: section_length[7:0].
210        buf[2] = (section_length & 0xFF) as u8;
211
212        // Extension header.
213        buf[3..5].copy_from_slice(&self.service_id.to_be_bytes());
214        buf[5] = 0xC0 // reserved(2) = 11
215            | ((self.version_number & 0x1F) << 1)
216            | u8::from(self.current_next_indicator);
217        buf[6] = self.section_number;
218        buf[7] = self.last_section_number;
219        buf[8..10].copy_from_slice(&self.transport_stream_id.to_be_bytes());
220        buf[10..12].copy_from_slice(&self.original_network_id.to_be_bytes());
221        buf[12] = self.prepend_strings.len() as u8;
222
223        // Prepend strings.
224        let ps_start = HEADER_LEN + EXTENSION_LEN;
225        let ps_end = ps_start + self.prepend_strings.len();
226        buf[ps_start..ps_end].copy_from_slice(self.prepend_strings);
227
228        // CRID entries.
229        let crid_end = ps_end + self.crid_entries.len();
230        buf[ps_end..crid_end].copy_from_slice(self.crid_entries);
231
232        // CRC-32: compute over everything up to (but not including) the CRC slot.
233        let crc = dvb_common::crc32_mpeg2::compute(&buf[..crid_end]);
234        buf[crid_end..len].copy_from_slice(&crc.to_be_bytes());
235
236        Ok(len)
237    }
238}
239
240// ── Table impl ────────────────────────────────────────────────────────────────
241
242impl<'a> Table<'a> for Cit<'a> {
243    const TABLE_ID: u8 = TABLE_ID;
244    const PID: u16 = PID;
245}
246
247impl<'a> crate::traits::TableDef<'a> for Cit<'a> {
248    const TABLE_ID_RANGES: &'static [(u8, u8)] = &[(TABLE_ID, TABLE_ID)];
249    const NAME: &'static str = "CONTENT_IDENTIFIER";
250}
251
252// ── tests ─────────────────────────────────────────────────────────────────────
253
254#[cfg(test)]
255mod tests {
256    use super::*;
257
258    /// Build a syntactically valid CIT section from its constituent fields.
259    ///
260    /// `prepend_strings` and `crid_entries` are raw byte slices; CRC is zeroed
261    /// (matching the serializer convention).
262    #[allow(clippy::too_many_arguments)]
263    fn build_cit(
264        service_id: u16,
265        version: u8,
266        current_next: bool,
267        section_number: u8,
268        last_section_number: u8,
269        transport_stream_id: u16,
270        original_network_id: u16,
271        prepend_strings: &[u8],
272        crid_entries: &[u8],
273    ) -> Vec<u8> {
274        let cit = Cit {
275            private_indicator: false,
276            service_id,
277            version_number: version,
278            current_next_indicator: current_next,
279            section_number,
280            last_section_number,
281            transport_stream_id,
282            original_network_id,
283            prepend_strings,
284            crid_entries,
285        };
286        let mut buf = vec![0u8; cit.serialized_len()];
287        cit.serialize_into(&mut buf).unwrap();
288        buf
289    }
290
291    #[test]
292    fn parse_happy_path_no_crid_entries() {
293        // A CIT section with no prepend strings and no CRID entries is the
294        // minimal valid form; commonly seen on transponders that carry the CIT
295        // structure but have no current programme mapping.
296        let prepend = b"CRID://example.com\x00";
297        let bytes = build_cit(0x1234, 3, true, 0, 0, 0x0064, 0x0002, prepend, &[]);
298        let cit = Cit::parse(&bytes).unwrap();
299
300        assert_eq!(cit.service_id, 0x1234);
301        assert_eq!(cit.version_number, 3);
302        assert!(cit.current_next_indicator);
303        assert_eq!(cit.section_number, 0);
304        assert_eq!(cit.last_section_number, 0);
305        assert_eq!(cit.transport_stream_id, 0x0064);
306        assert_eq!(cit.original_network_id, 0x0002);
307        assert_eq!(cit.prepend_strings, prepend);
308        assert_eq!(cit.crid_entries, &[] as &[u8]);
309    }
310
311    #[test]
312    fn parse_happy_path_with_crid_entries() {
313        // Two synthetic CRID entries:
314        //   entry 0: crid_ref=0x0001, prepend_string_index=0x00, unique="ep1"
315        //   entry 1: crid_ref=0x0002, prepend_string_index=0xFF (full CRID in unique), unique="crid://bbc.co.uk/EV-1"
316        let prepend = b"crid://bbc.co.uk/\x00";
317        let mut crid_entries: Vec<u8> = Vec::new();
318        // Entry 0
319        crid_entries.extend_from_slice(&0x0001u16.to_be_bytes()); // crid_ref
320        crid_entries.push(0x00); // prepend_string_index
321        let unique0 = b"ep1";
322        crid_entries.push(unique0.len() as u8); // unique_string_length
323        crid_entries.extend_from_slice(unique0);
324        // Entry 1
325        crid_entries.extend_from_slice(&0x0002u16.to_be_bytes());
326        crid_entries.push(0xFF); // no prepend
327        let unique1 = b"crid://bbc.co.uk/EV-1";
328        crid_entries.push(unique1.len() as u8);
329        crid_entries.extend_from_slice(unique1);
330
331        let bytes = build_cit(
332            0xABCD,
333            7,
334            true,
335            1,
336            3,
337            0x01F4,
338            0x0028,
339            prepend,
340            &crid_entries,
341        );
342        let cit = Cit::parse(&bytes).unwrap();
343
344        assert_eq!(cit.service_id, 0xABCD);
345        assert_eq!(cit.version_number, 7);
346        assert_eq!(cit.section_number, 1);
347        assert_eq!(cit.last_section_number, 3);
348        assert_eq!(cit.transport_stream_id, 0x01F4);
349        assert_eq!(cit.original_network_id, 0x0028);
350        assert_eq!(cit.prepend_strings, prepend);
351        assert_eq!(cit.crid_entries, crid_entries.as_slice());
352    }
353
354    #[test]
355    fn parse_rejects_wrong_table_id() {
356        let mut bytes = build_cit(0x0001, 0, true, 0, 0, 0x0001, 0x0001, &[], &[]);
357        bytes[0] = 0x40; // Not 0x77.
358        assert!(matches!(
359            Cit::parse(&bytes).unwrap_err(),
360            Error::UnexpectedTableId { table_id: 0x40, .. }
361        ));
362    }
363
364    #[test]
365    fn parse_rejects_buffer_too_short() {
366        // Hand-craft a buffer that is shorter than MIN_SECTION_LEN.
367        let short = [TABLE_ID, 0x00];
368        assert!(matches!(
369            Cit::parse(&short).unwrap_err(),
370            Error::BufferTooShort { .. }
371        ));
372    }
373
374    #[test]
375    fn parse_rejects_section_length_overflow() {
376        let mut bytes = build_cit(0x0001, 0, true, 0, 0, 0x0001, 0x0001, &[], &[]);
377        // Inflate the declared section_length to exceed actual buffer size.
378        let fake_sl: u16 = (bytes.len() as u16) + 100 - HEADER_LEN as u16;
379        bytes[1] = (bytes[1] & 0xF0) | ((fake_sl >> 8) as u8 & 0x0F);
380        bytes[2] = (fake_sl & 0xFF) as u8;
381        assert!(matches!(
382            Cit::parse(&bytes).unwrap_err(),
383            Error::SectionLengthOverflow { .. }
384        ));
385    }
386
387    #[test]
388    fn serialize_round_trip() {
389        let prepend = b"crid://example.com/\x00";
390        let crid_entries = {
391            let mut v: Vec<u8> = Vec::new();
392            v.extend_from_slice(&0x0042u16.to_be_bytes());
393            v.push(0x00);
394            let unique = b"episode42";
395            v.push(unique.len() as u8);
396            v.extend_from_slice(unique);
397            v
398        };
399
400        let original = Cit {
401            private_indicator: true,
402            service_id: 0x4321,
403            version_number: 15,
404            current_next_indicator: false,
405            section_number: 2,
406            last_section_number: 4,
407            transport_stream_id: 0x03E8,
408            original_network_id: 0x0050,
409            prepend_strings: prepend,
410            crid_entries: &crid_entries,
411        };
412
413        let mut buf = vec![0u8; original.serialized_len()];
414        original.serialize_into(&mut buf).unwrap();
415        let parsed = Cit::parse(&buf).unwrap();
416
417        assert_eq!(parsed.private_indicator, original.private_indicator);
418        assert_eq!(parsed.service_id, original.service_id);
419        assert_eq!(parsed.version_number, original.version_number);
420        assert_eq!(
421            parsed.current_next_indicator,
422            original.current_next_indicator
423        );
424        assert_eq!(parsed.section_number, original.section_number);
425        assert_eq!(parsed.last_section_number, original.last_section_number);
426        assert_eq!(parsed.transport_stream_id, original.transport_stream_id);
427        assert_eq!(parsed.original_network_id, original.original_network_id);
428        assert_eq!(parsed.prepend_strings, original.prepend_strings);
429        assert_eq!(parsed.crid_entries, original.crid_entries);
430    }
431
432    #[test]
433    fn serialize_rejects_output_buffer_too_small() {
434        let cit = Cit {
435            private_indicator: false,
436            service_id: 0x0001,
437            version_number: 0,
438            current_next_indicator: true,
439            section_number: 0,
440            last_section_number: 0,
441            transport_stream_id: 0x0001,
442            original_network_id: 0x0001,
443            prepend_strings: &[],
444            crid_entries: &[],
445        };
446        let mut buf = vec![0u8; 2]; // Far too small.
447        assert!(matches!(
448            cit.serialize_into(&mut buf).unwrap_err(),
449            Error::OutputBufferTooSmall { .. }
450        ));
451    }
452}