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