dvb-si 17.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
438
439
440
//! Content Identifier Descriptor — ETSI TS 102 323 §12.1 (tag 0x76).
//!
//! Carries one or more Content Reference Identifier (CRID) entries that
//! uniquely identify TV/radio programmes, series, or recommendations.
//! Each entry specifies a type and a location indicator that determines
//! whether the CRID is carried inline or as a reference.

use super::descriptor_body;
use crate::error::{Error, Result};
use alloc::vec::Vec;
use broadcast_core::len::need_out;
use broadcast_core::{Parse, Serialize};

/// Descriptor tag for content_identifier_descriptor.
pub const TAG: u8 = 0x76;
const HEADER_LEN: usize = 2;
const CRID_TYPE_MASK: u8 = 0xFC;
/// `crid_type(6)` field value mask: bits `[7:2]` of the CRID header byte,
/// masked *before* the shift so a `CridType::Reserved(v)` payload with high
/// bits set cannot bleed into the two `crid_location` bits (r03-W2).
const CRID_TYPE_VALUE_MASK: u8 = 0x3F;
const CRID_LOCATION_MASK: u8 = 0x03;
/// Shift of `crid_type` in the entry header byte.
const CRID_TYPE_SHIFT: u8 = 2;
/// Width of `crid_ref` (an indirect CRID), bytes.
const CRID_REFERENCE_LEN: usize = core::mem::size_of::<u16>();
/// Width of an entry's `crid_type`/`crid_location` header byte.
const CRID_HEADER_LEN: usize = 1;
/// Width of the inline `crid_length` byte.
const CRID_LENGTH_LEN: usize = 1;
/// Offset of `crid_length` in an inline entry.
const CRID_LENGTH_OFFSET: usize = CRID_HEADER_LEN;
/// Offset of the inline `crid` bytes in an entry.
const CRID_DATA_OFFSET: usize = CRID_HEADER_LEN + CRID_LENGTH_LEN;
/// `crid_location` value selecting an indirect (reference) CRID.
const CRID_LOCATION_REFERENCE: u8 = 0x01;

/// CRID type — ETSI TS 102 323 Table 117.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[cfg_attr(feature = "serde", derive(serde::Serialize))]
#[non_exhaustive]
pub enum CridType {
    /// 0x00 — no type defined.
    NoTypeDefined,
    /// 0x01 — CRID references the item of content that this event is an
    /// instance of.
    ItemOfContent,
    /// 0x02 — CRID references a series that this event belongs to.
    Series,
    /// 0x03 — CRID references a recommendation.
    Recommendation,
    /// Reserved/unallocated wire value, preserved verbatim for round-trip.
    Reserved(u8),
}

impl CridType {
    #[must_use]
    /// Creates a value from a wire byte, preserving every possible
    /// byte value for lossless round-trip.
    pub fn from_u8(v: u8) -> Self {
        match v {
            0x00 => Self::NoTypeDefined,
            0x01 => Self::ItemOfContent,
            0x02 => Self::Series,
            0x03 => Self::Recommendation,
            v => Self::Reserved(v),
        }
    }

    #[must_use]
    /// Returns the wire byte for this value.
    pub const fn to_u8(self) -> u8 {
        match self {
            Self::NoTypeDefined => 0x00,
            Self::ItemOfContent => 0x01,
            Self::Series => 0x02,
            Self::Recommendation => 0x03,
            Self::Reserved(v) => v,
        }
    }

    #[must_use]
    /// Returns a human-readable spec name for this value.
    pub fn name(self) -> &'static str {
        match self {
            Self::NoTypeDefined => "no type defined",
            Self::ItemOfContent => "item of content",
            Self::Series => "series",
            Self::Recommendation => "recommendation",
            Self::Reserved(_) => "reserved",
        }
    }
}
broadcast_core::impl_spec_display!(CridType, Reserved);

/// CRID location per TS 102 323 Table 10.
///
/// Only the two defined locations are representable. Locations `0b10`/`0b11`
/// are reserved with no defined payload length, so the parser rejects them
/// (it cannot know how many bytes the entry occupies) rather than producing
/// an un-round-trippable value.
#[derive(Debug, Clone, PartialEq, Eq)]
#[cfg_attr(feature = "serde", derive(serde::Serialize))]
#[non_exhaustive]
pub enum CridLocation<'a> {
    /// Location 0b00 — CRID carried inline as raw ASCII bytes.
    Inline(&'a [u8]),
    /// Location 0b01 — CRID reference (CIT index).
    Reference(u16),
}

/// One CRID entry within a Content Identifier Descriptor.
#[derive(Debug, Clone, PartialEq, Eq)]
#[cfg_attr(feature = "serde", derive(serde::Serialize))]
#[cfg_attr(feature = "yoke", derive(yoke::Yokeable))]
pub struct CridEntry<'a> {
    /// crid_type — identifies what the entry references (TS 102 323 Table 117).
    pub crid_type: CridType,
    /// crid_location and its payload.
    pub location: CridLocation<'a>,
}

/// Content Identifier Descriptor.
///
/// Holds a sequence of CRID entries that identify programme content
/// for recording, scheduling, or recommendation purposes.
#[derive(Debug, Clone, PartialEq, Eq)]
#[cfg_attr(feature = "serde", derive(serde::Serialize))]
#[cfg_attr(feature = "yoke", derive(yoke::Yokeable))]
pub struct ContentIdentifierDescriptor<'a> {
    /// Entries in wire order.
    pub entries: Vec<CridEntry<'a>>,
}

impl<'a> Parse<'a> for ContentIdentifierDescriptor<'a> {
    type Error = crate::error::Error;
    fn parse(bytes: &'a [u8]) -> Result<Self> {
        let body = descriptor_body(
            bytes,
            TAG,
            "ContentIdentifierDescriptor",
            "unexpected tag for ContentIdentifierDescriptor",
        )?;
        if body.is_empty() {
            return Ok(Self {
                entries: Vec::new(),
            });
        }
        let mut entries = Vec::new();
        let mut pos = 0;
        while pos < body.len() {
            let header_byte = body[pos];
            pos += 1;
            let crid_type = CridType::from_u8((header_byte & CRID_TYPE_MASK) >> CRID_TYPE_SHIFT);
            let crid_location = header_byte & CRID_LOCATION_MASK;
            let location = match crid_location {
                0x00 => {
                    if pos >= body.len() {
                        return Err(Error::InvalidDescriptor {
                            tag: TAG,
                            reason: "inline CRID length byte missing",
                        });
                    }
                    let crid_length = body[pos] as usize;
                    pos += 1;
                    if pos + crid_length > body.len() {
                        return Err(Error::InvalidDescriptor {
                            tag: TAG,
                            reason: "inline CRID length exceeds descriptor body",
                        });
                    }
                    let crid_bytes = &body[pos..pos + crid_length];
                    pos += crid_length;
                    CridLocation::Inline(crid_bytes)
                }
                0x01 => {
                    if pos + CRID_REFERENCE_LEN > body.len() {
                        return Err(Error::InvalidDescriptor {
                            tag: TAG,
                            reason: "CRID reference truncated",
                        });
                    }
                    let (ref_bytes, _) = body
                        .get(pos..)
                        .and_then(|s| s.split_first_chunk::<CRID_REFERENCE_LEN>())
                        .ok_or(Error::InvalidDescriptor {
                            tag: TAG,
                            reason: "CRID reference truncated",
                        })?;
                    let crid_ref = u16::from_be_bytes(*ref_bytes);
                    pos += CRID_REFERENCE_LEN;
                    CridLocation::Reference(crid_ref)
                }
                _ => {
                    return Err(Error::InvalidDescriptor {
                        tag: TAG,
                        reason: "reserved crid_location value",
                    });
                }
            };
            entries.push(CridEntry {
                crid_type,
                location,
            });
        }
        Ok(Self { entries })
    }
}

impl Serialize for ContentIdentifierDescriptor<'_> {
    type Error = crate::error::Error;
    fn serialized_len(&self) -> usize {
        let body_len: usize = self
            .entries
            .iter()
            .map(|e| match &e.location {
                CridLocation::Inline(data) => CRID_DATA_OFFSET + data.len(),
                CridLocation::Reference(_) => CRID_HEADER_LEN + CRID_REFERENCE_LEN,
            })
            .sum();
        HEADER_LEN + body_len
    }

    fn serialize_into(&self, buf: &mut [u8]) -> Result<usize> {
        let len = self.serialized_len();
        need_out(buf, len, "ContentIdentifierDescriptor")?;
        crate::descriptors::write_descriptor_header(buf, TAG, len - HEADER_LEN)?;
        let mut pos = HEADER_LEN;
        for entry in &self.entries {
            let header = broadcast_core::len::fit_mask(
                entry.crid_type.to_u8(),
                CRID_TYPE_VALUE_MASK,
                "crid_type",
            )? << CRID_TYPE_SHIFT;
            match &entry.location {
                CridLocation::Inline(data) => {
                    buf[pos] = header;
                    buf[pos + CRID_LENGTH_OFFSET] =
                        broadcast_core::len::fit_u8(data.len(), "crid_length")?;
                    buf[pos + CRID_DATA_OFFSET..pos + CRID_DATA_OFFSET + data.len()]
                        .copy_from_slice(data);
                    pos += CRID_DATA_OFFSET + data.len();
                }
                CridLocation::Reference(val) => {
                    buf[pos] = header | CRID_LOCATION_REFERENCE;
                    let bytes = val.to_be_bytes();
                    buf[pos + CRID_HEADER_LEN] = bytes[0];
                    buf[pos + CRID_HEADER_LEN + 1] = bytes[1];
                    pos += CRID_HEADER_LEN + CRID_REFERENCE_LEN;
                }
            }
        }
        Ok(len)
    }
}
impl<'a> crate::traits::DescriptorDef<'a> for ContentIdentifierDescriptor<'a> {
    const TAG: u8 = TAG;
    const NAME: &'static str = "CONTENT_IDENTIFIER";
}

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

    #[test]
    fn parse_single_inline_crid() {
        let data = b"DVB/CRID/EPG123";
        let mut buf = vec![TAG, (data.len() + 2) as u8, 0x01 << 2, data.len() as u8];
        buf.extend_from_slice(data);
        let d = ContentIdentifierDescriptor::parse(&buf).unwrap();
        assert_eq!(d.entries.len(), 1);
        assert_eq!(d.entries[0].crid_type, CridType::ItemOfContent);
        match &d.entries[0].location {
            CridLocation::Inline(bytes) => assert_eq!(*bytes, data.as_slice()),
            _ => panic!("expected Inline"),
        }
    }

    #[test]
    fn parse_single_reference_crid() {
        let buf = [TAG, 0x03, (0x02 << 2) | 0x01, 0x00, 0x42];
        let d = ContentIdentifierDescriptor::parse(&buf).unwrap();
        assert_eq!(d.entries.len(), 1);
        assert_eq!(d.entries[0].crid_type, CridType::Series);
        match d.entries[0].location {
            CridLocation::Reference(val) => assert_eq!(val, 0x0042),
            _ => panic!("expected Reference"),
        }
    }

    #[test]
    fn parse_multiple_entries() {
        let inline_data = b"EPG/EPG123";
        let ref_val: u16 = 0x0100;
        let mut buf = vec![TAG, 0x00, 0x01 << 2, inline_data.len() as u8];
        buf.extend_from_slice(inline_data);
        buf.push((0x03 << 2) | 0x01);
        buf.extend_from_slice(&ref_val.to_be_bytes());
        let body_len = buf.len() - HEADER_LEN;
        buf[1] = body_len as u8;

        let d = ContentIdentifierDescriptor::parse(&buf).unwrap();
        assert_eq!(d.entries.len(), 2);
        assert_eq!(d.entries[0].crid_type, CridType::ItemOfContent);
        match &d.entries[0].location {
            CridLocation::Inline(bytes) => assert_eq!(*bytes, inline_data.as_slice()),
            _ => panic!("expected Inline for first entry"),
        }
        assert_eq!(d.entries[1].crid_type, CridType::Recommendation);
        match d.entries[1].location {
            CridLocation::Reference(val) => assert_eq!(val, ref_val),
            _ => panic!("expected Reference for second entry"),
        }
    }

    #[test]
    fn parse_rejects_wrong_tag() {
        let buf = [0x7A, 0x03, 0x04, 0x00, 0x42];
        assert!(matches!(
            ContentIdentifierDescriptor::parse(&buf).unwrap_err(),
            Error::InvalidDescriptor { tag: 0x7A, .. }
        ));
    }

    #[test]
    fn parse_rejects_inline_length_overrun() {
        let buf = [TAG, 4, 0x01 << 2, 10, 0xAA, 0xBB];
        assert!(matches!(
            ContentIdentifierDescriptor::parse(&buf).unwrap_err(),
            Error::InvalidDescriptor { tag: TAG, .. }
        ));
    }

    #[test]
    fn parse_rejects_reference_truncated() {
        let buf = [TAG, 2, (0x02 << 2) | 0x01, 0xAA];
        assert!(matches!(
            ContentIdentifierDescriptor::parse(&buf).unwrap_err(),
            Error::InvalidDescriptor { tag: TAG, .. }
        ));
    }

    #[test]
    fn parse_rejects_reserved_location() {
        let buf = [TAG, 0x01, (0x01 << 2) | 0x02];
        assert!(matches!(
            ContentIdentifierDescriptor::parse(&buf).unwrap_err(),
            Error::InvalidDescriptor { tag: TAG, .. }
        ));
        let buf = [TAG, 0x01, (0x01 << 2) | 0x03];
        assert!(matches!(
            ContentIdentifierDescriptor::parse(&buf).unwrap_err(),
            Error::InvalidDescriptor { tag: TAG, .. }
        ));
    }

    #[test]
    fn empty_descriptor_valid() {
        let buf = [TAG, 0x00];
        let d = ContentIdentifierDescriptor::parse(&buf).unwrap();
        assert_eq!(d.entries.len(), 0);
    }

    #[test]
    fn serialize_round_trip_inline_and_reference() {
        let inline_data = b"DVB/CRID/TEST456";
        let ref_val: u16 = 789;
        let desc = ContentIdentifierDescriptor {
            entries: vec![
                CridEntry {
                    crid_type: CridType::ItemOfContent,
                    location: CridLocation::Inline(inline_data.as_slice()),
                },
                CridEntry {
                    crid_type: CridType::Recommendation,
                    location: CridLocation::Reference(ref_val),
                },
            ],
        };
        let mut buf = vec![0u8; desc.serialized_len()];
        desc.serialize_into(&mut buf).unwrap();
        let parsed = ContentIdentifierDescriptor::parse(&buf).unwrap();
        assert_eq!(parsed.entries.len(), desc.entries.len());
        match &parsed.entries[0].location {
            CridLocation::Inline(bytes) => assert_eq!(*bytes, inline_data.as_slice()),
            _ => panic!("expected Inline"),
        }
        assert_eq!(parsed.entries[0].crid_type, CridType::ItemOfContent);
        match parsed.entries[1].location {
            CridLocation::Reference(val) => assert_eq!(val, ref_val),
            _ => panic!("expected Reference"),
        }
        assert_eq!(parsed.entries[1].crid_type, CridType::Recommendation);
    }

    #[test]
    fn crid_type_full_range_round_trip() {
        for b in 0..=0xFF_u8 {
            let ct = CridType::from_u8(b);
            assert_eq!(ct.to_u8(), b, "round-trip failed for byte 0x{b:02X}");
        }
    }

    #[test]
    fn crid_type_name_for_known() {
        assert_eq!(CridType::NoTypeDefined.name(), "no type defined");
        assert_eq!(CridType::ItemOfContent.name(), "item of content");
        assert_eq!(CridType::Series.name(), "series");
        assert_eq!(CridType::Recommendation.name(), "recommendation");
        assert_eq!(CridType::Reserved(0x55).name(), "reserved");
    }

    /// A reference CRID followed by another entry: the presence of later bytes
    /// must not be mistaken for a truncated reference.
    #[test]
    fn reference_followed_by_another_crid_parses() {
        // Series reference 0x0042, then ItemOfContent inline "AB".
        let bytes = [
            TAG,
            7,
            (0x02 << 2) | 0x01,
            0x00,
            0x42,
            0x01 << 2,
            0x02,
            b'A',
            b'B',
        ];
        let d = ContentIdentifierDescriptor::parse(&bytes).unwrap();
        assert_eq!(d.entries.len(), 2);
        assert_eq!(d.entries[0].crid_type, CridType::Series);
        assert_eq!(d.entries[0].location, CridLocation::Reference(0x0042));
        assert_eq!(d.entries[1].crid_type, CridType::ItemOfContent);
        assert_eq!(d.entries[1].location, CridLocation::Inline(b"AB"));
        let mut buf = vec![0u8; d.serialized_len()];
        d.serialize_into(&mut buf).unwrap();
        assert_eq!(buf, bytes);
    }
}