dvb-si 13.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
430
431
432
433
434
435
436
437
//! DSM-CC section parser โ€” ISO/IEC 13818-6 + ETSI EN 301 192 ยง9.
//!
//! This is intentionally minimal: header framing, table_id dispatch,
//! length check, and carrying the payload as `&[u8]`. Full DSM-CC payload
//! parsing is deliberately out of scope (YAGNI).
//!
//! SSI-dependent trailer: when `section_syntax_indicator == 1` the trailing
//! 4 bytes are a CRC-32 (computed over the whole section); when SSI == 0
//! they are an ISO/IEC 13818-6 checksum preserved verbatim in
//! [`DsmccSection::checksum`]. For SSI=1 the serializer recomputes CRC-32;
//! for SSI=0 the serializer re-emits the preserved checksum bytes.

use crate::error::{Error, Result};
use broadcast_common::len::{need_in, need_out};
use broadcast_common::{Parse, Serialize};

/// First table_id in the DSM-CC section range (inclusive).
pub const TABLE_ID_FIRST: u8 = 0x3A;
/// Last table_id in the DSM-CC section range (inclusive).
pub const TABLE_ID_LAST: u8 = 0x3F;
// DSM-CC has no well-known PID. A `PID` constant used to sit here as
// `0x0000`, but that value equals the real PAT PID, so any caller filtering
// on it would silently pick up PAT traffic instead (r02-W15) โ€” removed.

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;

/// A DSM-CC section โ€” minimal wrapper that validates header framing
/// and carries the raw payload.
#[derive(Debug, Clone, Eq)]
#[cfg_attr(feature = "serde", derive(serde::Serialize))]
#[cfg_attr(feature = "yoke", derive(yoke::Yokeable))]
#[non_exhaustive]
pub struct DsmccSection<'a> {
    /// The table_id byte (0x3A..=0x3F).
    pub table_id: u8,
    /// `section_syntax_indicator` bit. When `true` the trailer is a computed
    /// CRC-32; when `false` it is an ISO/IEC 13818-6 checksum preserved
    /// verbatim in [`Self::checksum`].
    pub section_syntax_indicator: bool,
    /// `private_indicator` bit (byte 1, bit 6).
    pub private_indicator: bool,
    /// 16-bit table_id_extension.
    pub extension_id: u16,
    /// 5-bit version_number.
    pub version_number: u8,
    /// current_next_indicator bit.
    pub current_next_indicator: bool,
    /// section_number.
    pub section_number: u8,
    /// last_section_number.
    pub last_section_number: u8,
    /// Raw payload bytes (everything between the extension header and the trailer).
    pub payload: &'a [u8],
    /// Verbatim trailer bytes when `section_syntax_indicator == false` (an
    /// ISO/IEC 13818-6 checksum). Ignored when SSI is `true`, where the
    /// trailer is a computed CRC-32.
    pub checksum: [u8; 4],
    /// `reserved(2)` in byte 1 bits `[5:4]` (`11`); preserved from the wire.
    #[cfg_attr(feature = "serde", serde(skip))]
    pub reserved_b1: u8,
    /// `reserved(2)` in front of `version_number` (`11`); preserved.
    #[cfg_attr(feature = "serde", serde(skip))]
    pub reserved_b5: u8,
}

impl<'a> DsmccSection<'a> {
    /// Construct a CRC-protected (`section_syntax_indicator` = 1,
    /// `private_indicator` = 0) DSM-CC section with the spec `reserved` fill.
    #[must_use]
    pub fn new(
        table_id: u8,
        extension_id: u16,
        version_number: u8,
        current_next_indicator: bool,
        section_number: u8,
        last_section_number: u8,
        payload: &'a [u8],
    ) -> Self {
        Self {
            table_id,
            section_syntax_indicator: true,
            private_indicator: false,
            extension_id,
            version_number,
            current_next_indicator,
            section_number,
            last_section_number,
            payload,
            checksum: [0; 4],
            reserved_b1: super::RESERVED_2,
            reserved_b5: super::RESERVED_2,
        }
    }
}

impl PartialEq for DsmccSection<'_> {
    fn eq(&self, other: &Self) -> bool {
        self.table_id == other.table_id
            && self.section_syntax_indicator == other.section_syntax_indicator
            && self.private_indicator == other.private_indicator
            && self.extension_id == other.extension_id
            && self.version_number == other.version_number
            && self.current_next_indicator == other.current_next_indicator
            && self.section_number == other.section_number
            && self.last_section_number == other.last_section_number
            && self.payload == other.payload
            && self.reserved_b1 == other.reserved_b1
            && self.reserved_b5 == other.reserved_b5
            && (self.section_syntax_indicator || self.checksum == other.checksum)
    }
}

impl<'a> Parse<'a> for DsmccSection<'a> {
    type Error = crate::error::Error;
    fn parse(bytes: &'a [u8]) -> Result<Self> {
        let min_len = MIN_HEADER_LEN + EXTENSION_HEADER_LEN + CRC_LEN;
        need_in(bytes, min_len, "DsmccSection")?;

        let table_id = bytes[0];
        if !(TABLE_ID_FIRST..=TABLE_ID_LAST).contains(&table_id) {
            return Err(Error::UnexpectedTableId {
                table_id,
                what: "DsmccSection",
                expected: &[TABLE_ID_FIRST, TABLE_ID_LAST],
            });
        }

        let section_syntax_indicator = (bytes[1] & super::SECTION_B1_SSI) != 0;
        let private_indicator = (bytes[1] & super::SECTION_B1_PRIVATE_INDICATOR) != 0;
        let section_length = super::section_length_of(bytes);
        let total = super::check_section_length(
            bytes.len(),
            MIN_HEADER_LEN,
            section_length,
            MIN_SECTION_LEN,
        )?;

        let extension_id = crate::wire::be_u16(bytes, 3, "dsmcc")?;
        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];

        let payload_start = MIN_HEADER_LEN + EXTENSION_HEADER_LEN;
        let payload_end = total - CRC_LEN;
        let payload = &bytes[payload_start..payload_end];

        let trailer_start = total - CRC_LEN;
        let checksum = [
            bytes[trailer_start],
            bytes[trailer_start + 1],
            bytes[trailer_start + 2],
            bytes[trailer_start + 3],
        ];

        Ok(DsmccSection {
            table_id,
            section_syntax_indicator,
            private_indicator,
            extension_id,
            version_number,
            current_next_indicator,
            section_number,
            last_section_number,
            payload,
            checksum,
            reserved_b1: super::b1_reserved_of(bytes[1]),
            reserved_b5: super::b5_reserved_of(bytes[5]),
        })
    }
}

impl Serialize for DsmccSection<'_> {
    type Error = crate::error::Error;
    fn serialized_len(&self) -> usize {
        MIN_HEADER_LEN + EXTENSION_HEADER_LEN + self.payload.len() + CRC_LEN
    }

    fn serialize_into(&self, buf: &mut [u8]) -> Result<usize> {
        let len = self.serialized_len();
        need_out(buf, len)?;

        let section_length = len - MIN_HEADER_LEN;
        buf[0] = self.table_id;
        // `private_indicator` is parsed independently of
        // `section_syntax_indicator` (both are just bits of byte 1) and must
        // round-trip the same way โ€” unlike PAT/PMT/etc, DSM-CC sections can
        // have SSI=1 with `private_indicator` set (r02-W9: this used to
        // silently force it to 0 whenever SSI was true).
        buf[1] = super::b1_of(
            self.section_syntax_indicator,
            self.private_indicator,
            self.reserved_b1,
        )?;
        super::write_section_length(buf, section_length)?;
        buf[3..5].copy_from_slice(&self.extension_id.to_be_bytes());
        buf[5] = super::b5_of(
            self.reserved_b5,
            self.version_number,
            self.current_next_indicator,
        )?;
        buf[6] = self.section_number;
        buf[7] = self.last_section_number;

        let payload_start = MIN_HEADER_LEN + EXTENSION_HEADER_LEN;
        let payload_end = payload_start + self.payload.len();
        buf[payload_start..payload_end].copy_from_slice(self.payload);

        let trailer_start = payload_end;
        if self.section_syntax_indicator {
            super::write_crc(buf, trailer_start);
        } else {
            buf[trailer_start..len].copy_from_slice(&self.checksum);
        }
        Ok(len)
    }
}
impl<'a> crate::traits::TableDef<'a> for DsmccSection<'a> {
    /// Full DSM-CC range including `0x3E` (MPE datagram_section). The typed
    /// [`crate::tables::mpe::MpeDatagramSection`] view of `0x3E` is reachable
    /// type-keyed only (via `AnyTableSection::parse_as` or
    /// `MpeDatagramSection::parse`); the default dispatcher routes `0x3E` here.
    const TABLE_ID_RANGES: &'static [(u8, u8)] = &[(TABLE_ID_FIRST, TABLE_ID_LAST)];
    const NAME: &'static str = "DSM_CC_SECTION";
}

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

    fn build_dsmcc(table_id: u8, extension_id: u16, version: u8, payload: &[u8]) -> Vec<u8> {
        let section_length: u16 = (EXTENSION_HEADER_LEN + payload.len() + CRC_LEN) as u16;
        let mut v = Vec::new();
        v.push(table_id);
        v.push(super::super::SECTION_B1_FLAGS_PSI | ((section_length >> 8) as u8 & 0x0F));
        v.push((section_length & 0xFF) as u8);
        v.extend_from_slice(&extension_id.to_be_bytes());
        v.push(0xC0 | ((version & 0x1F) << 1) | 0x01);
        v.push(0);
        v.push(0);
        v.extend_from_slice(payload);
        v.extend_from_slice(&[0, 0, 0, 0]);
        v
    }

    #[test]
    fn parse_rejects_wrong_table_id() {
        let mut bytes = build_dsmcc(0x3B, 0x0001, 0, &[]);
        bytes[0] = 0x00;
        let err = DsmccSection::parse(&bytes).unwrap_err();
        assert!(matches!(
            err,
            Error::UnexpectedTableId { table_id: 0x00, .. }
        ));
    }

    #[test]
    fn parse_rejects_table_id_below_range() {
        let bytes = build_dsmcc(0x39, 0x0001, 0, &[]);
        let err = DsmccSection::parse(&bytes).unwrap_err();
        assert!(matches!(
            err,
            Error::UnexpectedTableId { table_id: 0x39, .. }
        ));
    }

    #[test]
    fn parse_rejects_table_id_above_range() {
        let bytes = build_dsmcc(0x40, 0x0001, 0, &[]);
        let err = DsmccSection::parse(&bytes).unwrap_err();
        assert!(matches!(
            err,
            Error::UnexpectedTableId { table_id: 0x40, .. }
        ));
    }

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

    /// Regression for r02-W9: `private_indicator` is an independent bit of
    /// byte 1 from `section_syntax_indicator` and must round-trip even when
    /// SSI=1 โ€” previously the serializer forced it to 0 whenever SSI was
    /// true, dropping a set `private_indicator` on re-serialize.
    #[test]
    fn private_indicator_round_trips_when_ssi_is_true() {
        let mut bytes = build_dsmcc(0x3B, 0x1234, 5, &[0xAB]);
        bytes[1] |= 0x40; // set private_indicator (SSI stays 1)
        let sec = DsmccSection::parse(&bytes).expect("parse");
        assert!(sec.section_syntax_indicator);
        assert!(sec.private_indicator);

        let mut out = vec![0u8; sec.serialized_len()];
        sec.serialize_into(&mut out).unwrap();
        assert_eq!(
            out[1] & 0x40,
            0x40,
            "private_indicator bit must be set in the serialized byte 1 when SSI=1"
        );
        let reparsed = DsmccSection::parse(&out).expect("reparse");
        assert!(reparsed.private_indicator);
    }

    #[test]
    fn parse_empty_payload() {
        let bytes = build_dsmcc(0x3B, 0x1234, 5, &[]);
        let sec = DsmccSection::parse(&bytes).expect("parse");
        assert_eq!(sec.table_id, 0x3B);
        assert_eq!(sec.extension_id, 0x1234);
        assert_eq!(sec.version_number, 5);
        assert!(sec.current_next_indicator);
        assert_eq!(sec.section_number, 0);
        assert_eq!(sec.last_section_number, 0);
        assert_eq!(sec.payload.len(), 0);
    }

    #[test]
    fn parse_0x3c_table_id_accepted() {
        let bytes = build_dsmcc(0x3C, 0x0001, 0, &[0xAA, 0xBB]);
        let sec = DsmccSection::parse(&bytes).unwrap();
        assert_eq!(sec.table_id, 0x3C);
        assert_eq!(sec.payload, &[0xAA, 0xBB]);
    }

    #[test]
    fn parse_payload_preserved() {
        let payload = vec![0x01, 0x02, 0x03, 0x04, 0x05];
        let bytes = build_dsmcc(0x3B, 0x0001, 0, &payload);
        let sec = DsmccSection::parse(&bytes).unwrap();
        assert_eq!(sec.payload, &payload[..]);
    }

    #[test]
    fn serialize_round_trip_empty() {
        let sec = {
            let mut __v = DsmccSection::new(0x3B, 0x0001, 0, true, 0, 0, &[]);
            __v.section_syntax_indicator = true;
            __v.private_indicator = false;
            __v.checksum = [0; 4];
            __v
        };
        let mut buf = vec![0u8; sec.serialized_len()];
        sec.serialize_into(&mut buf).unwrap();
        let reparsed = DsmccSection::parse(&buf).unwrap();
        assert_eq!(sec, reparsed);
    }

    #[test]
    fn serialize_round_trip_with_payload() {
        let payload: [u8; 5] = [0xDE, 0xAD, 0xBE, 0xEF, 0x00];
        let sec = {
            let mut __v = DsmccSection::new(0x3C, 0xABCD, 3, true, 1, 2, &payload);
            __v.section_syntax_indicator = true;
            __v.private_indicator = false;
            __v.checksum = [0; 4];
            __v
        };
        let mut buf = vec![0u8; sec.serialized_len()];
        sec.serialize_into(&mut buf).unwrap();
        let reparsed = DsmccSection::parse(&buf).unwrap();
        assert_eq!(sec, reparsed);
    }

    #[test]
    fn serialize_round_trip_ssi_clear_preserves_checksum() {
        let payload: [u8; 3] = [0x01, 0x02, 0x03];
        let checksum: [u8; 4] = [0xAA, 0xBB, 0xCC, 0xDD];
        let sec = {
            let mut __v = DsmccSection::new(0x3B, 0x5678, 1, true, 0, 0, &payload);
            __v.section_syntax_indicator = false;
            __v.private_indicator = true;
            __v.checksum = checksum;
            __v
        };
        let mut buf = vec![0u8; sec.serialized_len()];
        sec.serialize_into(&mut buf).unwrap();
        assert_eq!(&buf[buf.len() - 4..], &checksum);
        let reparsed = DsmccSection::parse(&buf).unwrap();
        assert_eq!(sec, reparsed);
        assert_eq!(reparsed.checksum, checksum);
    }

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

    /// section_length is 12 bits (max 4095 = EXTENSION_HEADER_LEN(5) +
    /// payload + CRC_LEN(4), so 4086 is the largest payload that fits).
    #[test]
    fn serialize_rejects_payload_exceeding_section_length() {
        let payload = vec![0xAAu8; 4087];
        let sec = {
            let mut __v = DsmccSection::new(0x3B, 1, 0, true, 0, 0, &payload);
            __v.section_syntax_indicator = true;
            __v.private_indicator = false;
            __v.checksum = [0; 4];
            __v
        };
        let mut buf = vec![0u8; sec.serialized_len()];
        assert!(matches!(
            sec.serialize_into(&mut buf).unwrap_err(),
            Error::FieldOverflow(_)
        ));
    }

    #[test]
    fn serialize_accepts_payload_at_section_length_boundary() {
        let payload = vec![0xAAu8; 4086];
        let sec = {
            let mut __v = DsmccSection::new(0x3B, 1, 0, true, 0, 0, &payload);
            __v.section_syntax_indicator = true;
            __v.private_indicator = false;
            __v.checksum = [0; 4];
            __v
        };
        let mut buf = vec![0u8; sec.serialized_len()];
        sec.serialize_into(&mut buf).expect("boundary fits");
        let reparsed = DsmccSection::parse(&buf).expect("reparse");
        assert_eq!(sec, reparsed);
    }
}