dvb-si 12.0.0

ETSI EN 300 468 DVB Service Information parser + builder. MPEG-2 PSI included.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
//! Conditional Access Table โ€” ISO/IEC 13818-1 (H.222.0 08/2023) ยง2.4.4.7.
//!
//! Carried on PID 0x0001 with table_id 0x01. Contains a flat
//! list of CA descriptors (tag 0x09) identifying every CA system
//! in use plus the EMM PID on which Entitlement Management
//! Messages for that system are carried.
//!
//! A single-section table per CAS standard.

use crate::descriptors::DescriptorLoop;
use crate::descriptors::ca::CaDescriptor;
use crate::error::{Error, Result};
use alloc::vec::Vec;
use broadcast_common::{Parse, Serialize};
use mpeg_ts::pid::Pid;

/// CAT table_id (ISO/IEC 13818-1 Table 2-30).
pub const TABLE_ID: u8 = 0x01;
/// CAT well-known PID.
pub const PID: mpeg_ts::pid::Pid = mpeg_ts::pid::Pid::new(0x0001);
/// The 16 reserved bits in place of `table_id_extension` (all ones).
const RESERVED_EXTENSION: u16 = 0xFFFF;

const MIN_HEADER_LEN: usize = 3;
const EXTENSION_HEADER_LEN: usize = 5;
use super::CRC_LEN;
const MIN_SECTION_LEN: usize = MIN_HEADER_LEN + EXTENSION_HEADER_LEN + CRC_LEN;

/// One CA descriptor entry from the CAT, in owned form so it
/// outlives the source section bytes.
#[derive(Debug, Clone, PartialEq, Eq)]
#[cfg_attr(feature = "serde", derive(serde::Serialize))]
pub struct CatCaEntry {
    /// CA System ID โ€” the CAID. e.g. 0x0500 Viaccess, 0x0650
    /// Irdeto ORF-ICE, 0x0100 Seca/Mediaguard.
    pub ca_system_id: u16,
    /// EMM PID for this CA system.
    pub ca_pid: Pid,
    /// Optional private data after the standard CA fields.
    pub private_data: Vec<u8>,
}

/// Conditional Access Table.
#[derive(Debug, Clone, PartialEq, Eq)]
#[cfg_attr(feature = "serde", derive(serde::Serialize))]
#[cfg_attr(feature = "yoke", derive(yoke::Yokeable))]
#[non_exhaustive]
pub struct CatSection<'a> {
    /// 5-bit version_number from the section header.
    pub version_number: u8,
    /// current_next_indicator bit.
    pub current_next_indicator: bool,
    /// section_number in the sub-table sequence (typically 0 โ€” single-section).
    pub section_number: u8,
    /// last_section_number (typically 0).
    pub last_section_number: u8,
    /// Descriptor loop (byte 8 โ†’ CRC), preserved verbatim. ISO/IEC 13818-1
    /// ยง2.4.4.7 permits descriptors other than CA in this loop; keeping the loop
    /// raw makes parse โ†’ serialize identity hold for all of them. Serializes as
    /// the typed descriptor sequence; `.raw()` yields the wire bytes. Use
    /// [`CatSection::ca_descriptors`] for the typed CA (tag 0x09) view.
    pub descriptors: DescriptorLoop<'a>,
    /// Header bit fields (`'0'` after `section_syntax_indicator`, the two
    /// `reserved(2)`; default [`SectionBits::psi`](super::SectionBits::psi)).
    #[cfg_attr(feature = "serde", serde(skip))]
    pub bits: super::SectionBits,
    /// The 16 reserved bits at bytes 3-4 (the `reserved(18)` of `CA_section`,
    /// ISO/IEC 13818-1 ยง2.4.4.7; all ones = `0xFFFF`), preserved from the wire.
    #[cfg_attr(feature = "serde", serde(skip))]
    pub reserved_extension: u16,
}

impl Default for CatSection<'_> {
    fn default() -> Self {
        Self::new(0, false, 0, 0, DescriptorLoop::default())
    }
}

impl<'a> CatSection<'a> {
    /// Construct a CAT section with the spec `reserved` fill.
    #[must_use]
    pub fn new(
        version_number: u8,
        current_next_indicator: bool,
        section_number: u8,
        last_section_number: u8,
        descriptors: DescriptorLoop<'a>,
    ) -> Self {
        Self {
            version_number,
            current_next_indicator,
            section_number,
            last_section_number,
            descriptors,
            bits: super::SectionBits::psi(),
            reserved_extension: RESERVED_EXTENSION,
        }
    }
}

impl CatSection<'_> {
    /// Typed view of the CA descriptors (tag 0x09) in the descriptor loop.
    /// Non-CA descriptors are skipped; a truncated trailing descriptor returns
    /// an error.
    pub fn ca_descriptors(&self) -> Result<Vec<CatCaEntry>> {
        let mut out = Vec::new();
        let mut pos = 0;
        while pos + 2 <= self.descriptors.len() {
            let tag = self.descriptors[pos];
            let length = self.descriptors[pos + 1] as usize;
            let end = pos + 2 + length;
            if end > self.descriptors.len() {
                return Err(Error::BufferTooShort {
                    need: end - pos,
                    have: self.descriptors.len() - pos,
                    what: "CatSection ca_descriptors truncated descriptor",
                });
            }
            if tag == crate::descriptors::ca::TAG
                && let Ok(ca) = CaDescriptor::parse(&self.descriptors[pos..end])
            {
                out.push(CatCaEntry {
                    ca_system_id: ca.ca_system_id,
                    ca_pid: ca.ca_pid,
                    private_data: ca.private_data.to_vec(),
                });
            }
            pos = end;
        }
        Ok(out)
    }
}

impl<'a> Parse<'a> for CatSection<'a> {
    type Error = Error;

    fn parse(bytes: &'a [u8]) -> Result<Self> {
        if bytes.len() < MIN_HEADER_LEN + EXTENSION_HEADER_LEN + CRC_LEN {
            return Err(Error::BufferTooShort {
                need: MIN_HEADER_LEN + EXTENSION_HEADER_LEN + CRC_LEN,
                have: bytes.len(),
                what: "CatSection",
            });
        }

        if bytes[0] != TABLE_ID {
            return Err(Error::UnexpectedTableId {
                table_id: bytes[0],
                what: "CatSection",
                expected: &[TABLE_ID],
            });
        }

        let section_length = super::section_length_of(bytes);
        let total = super::check_section_length(
            bytes.len(),
            MIN_HEADER_LEN,
            section_length,
            MIN_SECTION_LEN,
        )?;

        // Skip the 2-byte reserved + extension (bytes 3-4), read version+cni at 5,
        // section/last_section at 6,7. CAT's "table_id_extension" (bytes 3-4) is
        // reserved per spec โ€” we don't expose it.
        let version_number = super::version_number_of(bytes[5]);
        let current_next_indicator = super::current_next_of(bytes[5]);
        let section_number = bytes[6];
        let last_section_number = bytes[7];

        // Descriptor loop runs from byte 8 up to (but not including) the 4-byte
        // CRC. Kept raw โ€” see the field doc; typed CA view via ca_descriptors().
        let descriptors_end = total - CRC_LEN;

        Ok(CatSection {
            version_number,
            current_next_indicator,
            section_number,
            last_section_number,
            descriptors: DescriptorLoop::new(&bytes[8..descriptors_end]),
            bits: super::SectionBits::parse(bytes[1], Some(bytes[5])),
            reserved_extension: crate::wire::be_u16(bytes, 3, "cat")?,
        })
    }
}

impl Serialize for CatSection<'_> {
    type Error = Error;

    fn serialized_len(&self) -> usize {
        MIN_HEADER_LEN + EXTENSION_HEADER_LEN + self.descriptors.len() + CRC_LEN
    }

    fn serialize_into(&self, buf: &mut [u8]) -> Result<usize> {
        let len = self.serialized_len();
        if buf.len() < len {
            return Err(Error::OutputBufferTooSmall {
                need: len,
                have: buf.len(),
            });
        }
        let section_length = len - MIN_HEADER_LEN;
        buf[0] = TABLE_ID;
        buf[1] = self.bits.b1()?;
        super::write_section_length(buf, section_length)?;
        buf[3..5].copy_from_slice(&self.reserved_extension.to_be_bytes());
        buf[5] = self
            .bits
            .b5(self.version_number, self.current_next_indicator)?;
        buf[6] = self.section_number;
        buf[7] = self.last_section_number;
        let desc_start = MIN_HEADER_LEN + EXTENSION_HEADER_LEN;
        buf[desc_start..desc_start + self.descriptors.len()]
            .copy_from_slice(self.descriptors.raw());
        let crc_pos = len - CRC_LEN;
        super::write_crc(buf, crc_pos);
        Ok(len)
    }
}
impl<'a> crate::traits::TableDef<'a> for CatSection<'a> {
    const TABLE_ID_RANGES: &'static [(u8, u8)] = &[(TABLE_ID, TABLE_ID)];
    const NAME: &'static str = "CONDITIONAL_ACCESS";
}

#[cfg(test)]
mod tests {
    use super::*;

    /// Build a CAT section with the given CA descriptors and placeholder CRC.
    fn build_cat(version: u8, descriptors: &[u8]) -> Vec<u8> {
        let section_length: u16 =
            (EXTENSION_HEADER_LEN as u16) + descriptors.len() as u16 + (CRC_LEN as u16);
        let mut v = Vec::new();
        v.push(TABLE_ID);
        crate::tables::push_section_header(
            &mut v,
            crate::tables::SECTION_B1_FLAGS_PSI,
            section_length as usize,
        );
        // table_id_extension (reserved for CAT) โ€” typically 0xFFFF in the wild.
        v.extend_from_slice(&[0xFF, 0xFF]);
        v.push(crate::tables::version_byte(version, true));
        v.push(0x00); // section_number
        v.push(0x00); // last_section_number
        v.extend_from_slice(descriptors);
        v.extend_from_slice(&[0, 0, 0, 0]); // placeholder CRC
        v
    }

    fn ca_descriptor(ca_system_id: u16, ca_pid: u16) -> [u8; 6] {
        [
            0x09,
            0x04,
            (ca_system_id >> 8) as u8,
            (ca_system_id & 0xFF) as u8,
            0xE0 | ((ca_pid >> 8) as u8 & 0x1F),
            (ca_pid & 0xFF) as u8,
        ]
    }

    #[test]
    fn parse_empty_cat_zero_descriptors() {
        let bytes = build_cat(5, &[]);
        let cat = CatSection::parse(&bytes).expect("parse");
        assert_eq!(cat.version_number, 5);
        assert!(cat.current_next_indicator);
        assert!(cat.descriptors.is_empty());
        assert_eq!(cat.ca_descriptors().unwrap().len(), 0);
    }

    #[test]
    fn parse_single_ca_descriptor_extracts_caid_and_pid() {
        let mut desc = Vec::new();
        desc.extend_from_slice(&ca_descriptor(0x0500, 0x0050));
        let bytes = build_cat(0, &desc);
        let cat = CatSection::parse(&bytes).unwrap();
        let cas = cat.ca_descriptors().unwrap();
        assert_eq!(cas.len(), 1);
        assert_eq!(cas[0].ca_system_id, 0x0500);
        assert_eq!(cas[0].ca_pid, Pid::new(0x0050));
        assert!(cas[0].private_data.is_empty());
    }

    #[test]
    fn parse_multiple_ca_descriptors_preserves_order() {
        let mut desc = Vec::new();
        desc.extend_from_slice(&ca_descriptor(0x0500, 0x0050));
        desc.extend_from_slice(&ca_descriptor(0x0650, 0x0062));
        desc.extend_from_slice(&ca_descriptor(0x0100, 0x0080));
        let bytes = build_cat(2, &desc);
        let cat = CatSection::parse(&bytes).unwrap();
        let cas = cat.ca_descriptors().unwrap();
        assert_eq!(cas.len(), 3);
        assert_eq!(cas[0].ca_system_id, 0x0500);
        assert_eq!(cas[1].ca_system_id, 0x0650);
        assert_eq!(cas[2].ca_system_id, 0x0100);
        assert_eq!(cas[1].ca_pid, Pid::new(0x0062));
    }

    #[test]
    fn parse_rejects_wrong_table_id() {
        let mut bytes = build_cat(0, &[]);
        bytes[0] = 0x02; // PMT table_id
        let err = CatSection::parse(&bytes).unwrap_err();
        assert!(matches!(
            err,
            Error::UnexpectedTableId { table_id: 0x02, .. }
        ));
    }

    #[test]
    fn parse_rejects_short_buffer() {
        let err = CatSection::parse(&[0x01, 0x00]).unwrap_err();
        assert!(matches!(err, Error::BufferTooShort { .. }));
    }

    /// ยง2.4.4.7 permits non-CA descriptors in the CAT loop: the typed view
    /// skips them, but parse โ†’ serialize MUST preserve them byte-for-byte.
    #[test]
    fn non_ca_descriptors_skipped_by_view_but_round_trip() {
        let mut desc = Vec::new();
        desc.extend_from_slice(&ca_descriptor(0x0500, 0x0050));
        desc.extend_from_slice(&[0x12, 0x02, 0xAA, 0xBB]); // unknown tag 0x12, len 2
        desc.extend_from_slice(&ca_descriptor(0x0650, 0x0062));
        let bytes = build_cat(0, &desc);
        let cat = CatSection::parse(&bytes).unwrap();
        let cas = cat.ca_descriptors().unwrap();
        assert_eq!(cas.len(), 2);
        assert_eq!(cas[0].ca_system_id, 0x0500);
        assert_eq!(cas[1].ca_system_id, 0x0650);
        // The unknown descriptor survives the round trip verbatim.
        assert_eq!(cat.descriptors.raw(), desc);
        let mut buf = vec![0u8; cat.serialized_len()];
        cat.serialize_into(&mut buf).unwrap();
        let re = CatSection::parse(&buf).unwrap();
        assert_eq!(re.descriptors.raw(), desc);
    }

    #[test]
    fn serialize_round_trip() {
        let mut desc = Vec::new();
        desc.extend_from_slice(&ca_descriptor(0x0500, 0x0050));
        desc.extend_from_slice(&ca_descriptor(0x0650, 0x0062));
        let bytes = build_cat(3, &desc);
        let cat = CatSection::parse(&bytes).unwrap();
        let mut buf = vec![0u8; cat.serialized_len()];
        cat.serialize_into(&mut buf).unwrap();
        assert_eq!(CatSection::parse(&buf).unwrap(), cat);
    }

    #[test]
    fn table_trait_constants() {
        assert_eq!(TABLE_ID, 0x01);
        assert_eq!(PID.value(), 0x0001);
    }

    /// CAT borrows its descriptor loop (3.0): the loop serializes as the
    /// typed descriptor sequence and the struct is serialize-only. Verify the
    /// CA descriptor decodes inside the JSON.
    #[cfg(feature = "serde")]
    #[test]
    fn serde_json_serializes_typed_loop() {
        let bytes = build_cat(1, &ca_descriptor(0x0500, 0x0050));
        let cat = CatSection::parse(&bytes).unwrap();
        let v = serde_json::to_value(&cat).unwrap();
        let loop_ = v["descriptors"]
            .as_array()
            .expect("typed descriptor sequence");
        assert_eq!(loop_.len(), 1);
        assert_eq!(loop_[0]["ca"]["ca_system_id"], 0x0500);
        assert_eq!(loop_[0]["ca"]["ca_pid"], 0x0050);
    }

    /// section_length is 12 bits (max 4095). A descriptor loop that pushes
    /// the section past that must be rejected, not silently wrapped.
    #[test]
    fn serialize_rejects_descriptor_loop_exceeding_section_length() {
        let raw = vec![0xAAu8; 4091]; // + 9 header/crc bytes > 4095
        let cat = CatSection::new(0, true, 0, 0, DescriptorLoop::from(raw.as_slice()));
        let mut buf = vec![0u8; cat.serialized_len()];
        assert!(matches!(
            cat.serialize_into(&mut buf).unwrap_err(),
            Error::FieldOverflow(_)
        ));
    }

    #[test]
    fn serialize_accepts_descriptor_loop_at_section_length_boundary() {
        // section_length = EXTENSION_HEADER_LEN(5) + loop_len + CRC_LEN(4);
        // 4086 is the largest loop that keeps it at the 12-bit max, 4095.
        let raw = vec![0xAAu8; 4086];
        let cat = CatSection::new(0, true, 0, 0, DescriptorLoop::from(raw.as_slice()));
        let mut buf = vec![0u8; cat.serialized_len()];
        cat.serialize_into(&mut buf).expect("boundary fits");
        let reparsed = CatSection::parse(&buf).expect("reparse");
        assert_eq!(cat.descriptors.raw(), reparsed.descriptors.raw());
    }

    #[test]
    fn parse_rejects_zero_section_length() {
        let mut buf = vec![0u8; 64];
        buf[0] = TABLE_ID;
        buf[1] = 0xF0;
        buf[2] = 0x00;
        for b in &mut buf[3..] {
            *b = 0xFF;
        }
        assert!(matches!(
            CatSection::parse(&buf).unwrap_err(),
            Error::SectionLengthOverflow { .. }
        ));
    }

    #[test]
    fn ca_descriptors_rejects_truncated_descriptor() {
        let mut desc = Vec::new();
        desc.extend_from_slice(&ca_descriptor(0x0500, 0x0050));
        desc.push(0x09);
        desc.push(0x10);
        let bytes = build_cat(0, &desc);
        let cat = CatSection::parse(&bytes).unwrap();
        assert!(matches!(
            cat.ca_descriptors().unwrap_err(),
            Error::BufferTooShort {
                what: "CatSection ca_descriptors truncated descriptor",
                ..
            }
        ));
    }
}