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
//! Extended Event Descriptor — ETSI EN 300 468 V1.20.1 §6.2.15 (tag 0x4E).
//!
//! Carried inside EIT. Provides the full event description split across
//! descriptor_number / last_descriptor_number fragments. Each fragment
//! contributes text plus an optional list of (item_description, item) pairs.

use super::descriptor_body;
use crate::descriptors::lang_text::LANG_LEN;
use crate::error::{Error, Result};
use crate::text::{DvbText, LangCode};
use alloc::vec::Vec;
use broadcast_core::len::{need_in, need_out};
use broadcast_core::{Parse, Serialize};

/// Descriptor tag for extended_event_descriptor.
pub const TAG: u8 = 0x4E;
const HEADER_LEN: usize = 2;
const NUMBERS_LEN: usize = 1;
const ITEMS_LEN_FIELD: usize = 1;
const TEXT_LEN_FIELD: usize = 1;
const FIXED_PREFIX_LEN: usize = NUMBERS_LEN + LANG_LEN + ITEMS_LEN_FIELD + TEXT_LEN_FIELD;
/// Shift of `descriptor_number` in the numbers byte.
const DESCRIPTOR_NUMBER_SHIFT: u8 = 4;
/// Mask of the two 4-bit number fields in the numbers byte.
const NUMBER_MASK: u8 = 0x0F;
/// Offset of `length_of_items` in the descriptor body.
const ITEMS_LEN_OFFSET: usize = NUMBERS_LEN + LANG_LEN;

/// One (description, value) item — e.g. "Director" → "Alice Smith".
#[derive(Debug, Clone, PartialEq, Eq)]
#[cfg_attr(feature = "serde", derive(serde::Serialize))]
#[cfg_attr(feature = "yoke", derive(yoke::Yokeable))]
pub struct ExtendedEventItem<'a> {
    /// DVB Annex-A encoded item description.
    pub description: DvbText<'a>,
    /// DVB Annex-A encoded item value.
    pub value: DvbText<'a>,
}

/// Extended Event Descriptor.
#[derive(Debug, Clone, PartialEq, Eq)]
#[cfg_attr(feature = "serde", derive(serde::Serialize))]
#[cfg_attr(feature = "yoke", derive(yoke::Yokeable))]
pub struct ExtendedEventDescriptor<'a> {
    /// 0-based fragment index within the extended event series.
    pub descriptor_number: u8,
    /// Index of the final fragment in the series (0-based).
    pub last_descriptor_number: u8,
    /// ISO 639-2 language code.
    pub language_code: LangCode,
    /// Item list.
    pub items: Vec<ExtendedEventItem<'a>>,
    /// DVB Annex-A encoded extended text.
    pub text: DvbText<'a>,
}

impl<'a> Parse<'a> for ExtendedEventDescriptor<'a> {
    type Error = crate::error::Error;
    fn parse(bytes: &'a [u8]) -> Result<Self> {
        let min_len = HEADER_LEN + NUMBERS_LEN + LANG_LEN + ITEMS_LEN_FIELD + TEXT_LEN_FIELD;
        need_in(bytes, min_len, "ExtendedEventDescriptor header")?;
        let body = descriptor_body(
            bytes,
            TAG,
            "ExtendedEventDescriptor",
            "unexpected tag for extended_event_descriptor",
        )?;
        need_in(body, FIXED_PREFIX_LEN, "ExtendedEventDescriptor body")?;
        let numbers_byte = body[0];
        let descriptor_number = numbers_byte >> DESCRIPTOR_NUMBER_SHIFT;
        let last_descriptor_number = numbers_byte & NUMBER_MASK;
        let mut language_bytes = [0u8; LANG_LEN];
        language_bytes.copy_from_slice(&body[NUMBERS_LEN..ITEMS_LEN_OFFSET]);
        let language_code = LangCode::new(language_bytes);

        let items_len_pos = ITEMS_LEN_OFFSET;
        let items_length = body[items_len_pos] as usize;
        let items_start = items_len_pos + ITEMS_LEN_FIELD;
        let items_end = items_start + items_length;
        if items_end + TEXT_LEN_FIELD > body.len() {
            return Err(Error::InvalidDescriptor {
                tag: TAG,
                reason: "length_of_items runs past descriptor end",
            });
        }

        let mut items = Vec::new();
        let mut pos = items_start;
        while pos < items_end {
            let desc_len = body[pos] as usize;
            let desc_start = pos + 1;
            let desc_end = desc_start + desc_len;
            if desc_end + 1 > items_end {
                return Err(Error::InvalidDescriptor {
                    tag: TAG,
                    reason: "item_description_length runs past items loop",
                });
            }
            let value_len = body[desc_end] as usize;
            let value_start = desc_end + 1;
            let value_end = value_start + value_len;
            if value_end > items_end {
                return Err(Error::InvalidDescriptor {
                    tag: TAG,
                    reason: "item_length runs past items loop",
                });
            }
            items.push(ExtendedEventItem {
                description: DvbText::new(&body[desc_start..desc_end]),
                value: DvbText::new(&body[value_start..value_end]),
            });
            pos = value_end;
        }

        let text_len = body[items_end] as usize;
        let text_start = items_end + TEXT_LEN_FIELD;
        let text_end = text_start + text_len;
        if text_end > body.len() {
            return Err(Error::InvalidDescriptor {
                tag: TAG,
                reason: "text_length runs past descriptor end",
            });
        }
        let text = DvbText::new(&body[text_start..text_end]);
        if text_end != body.len() {
            // text_length closes the descriptor (EN 300 468 §6.2.15); trailing
            // bytes used to be dropped on re-serialize (r03-W9).
            return Err(Error::InvalidDescriptor {
                tag: TAG,
                reason: "extended_event_descriptor has trailing bytes after text",
            });
        }

        Ok(Self {
            descriptor_number,
            last_descriptor_number,
            language_code,
            items,
            text,
        })
    }
}

impl Serialize for ExtendedEventDescriptor<'_> {
    type Error = crate::error::Error;
    fn serialized_len(&self) -> usize {
        let items_bytes: usize = self
            .items
            .iter()
            .map(|i| 1 + i.description.len() + 1 + i.value.len())
            .sum();
        HEADER_LEN
            + NUMBERS_LEN
            + LANG_LEN
            + ITEMS_LEN_FIELD
            + items_bytes
            + TEXT_LEN_FIELD
            + self.text.len()
    }

    fn serialize_into(&self, buf: &mut [u8]) -> Result<usize> {
        let len = self.serialized_len();
        need_out(buf, len, "ExtendedEventDescriptor")?;
        crate::descriptors::write_descriptor_header(buf, TAG, len - HEADER_LEN)?;
        buf[HEADER_LEN] = (broadcast_core::len::fit_mask(
            self.descriptor_number,
            NUMBER_MASK,
            "descriptor_number",
        )? << DESCRIPTOR_NUMBER_SHIFT)
            | broadcast_core::len::fit_mask(
                self.last_descriptor_number,
                NUMBER_MASK,
                "last_descriptor_number",
            )?;
        buf[HEADER_LEN + NUMBERS_LEN..HEADER_LEN + ITEMS_LEN_OFFSET]
            .copy_from_slice(&self.language_code.get());

        let items_bytes: usize = self
            .items
            .iter()
            .map(|i| 1 + i.description.len() + 1 + i.value.len())
            .sum();
        buf[HEADER_LEN + ITEMS_LEN_OFFSET] =
            broadcast_core::len::fit_u8(items_bytes, "length_of_items")?;

        let mut pos = HEADER_LEN + ITEMS_LEN_OFFSET + ITEMS_LEN_FIELD;
        for item in &self.items {
            buf[pos] =
                broadcast_core::len::fit_u8(item.description.len(), "item_description_length")?;
            let d_start = pos + 1;
            let d_end = d_start + item.description.len();
            buf[d_start..d_end].copy_from_slice(item.description.raw());
            buf[d_end] = broadcast_core::len::fit_u8(item.value.len(), "item_length")?;
            let v_start = d_end + 1;
            let v_end = v_start + item.value.len();
            buf[v_start..v_end].copy_from_slice(item.value.raw());
            pos = v_end;
        }
        buf[pos] = broadcast_core::len::fit_u8(self.text.len(), "text_length")?;
        buf[pos + 1..pos + 1 + self.text.len()].copy_from_slice(self.text.raw());
        Ok(len)
    }
}
impl<'a> crate::traits::DescriptorDef<'a> for ExtendedEventDescriptor<'a> {
    const TAG: u8 = TAG;
    const NAME: &'static str = "EXTENDED_EVENT";
}

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

    fn build(
        descriptor_number: u8,
        last_descriptor_number: u8,
        lang: [u8; 3],
        items: &[(&[u8], &[u8])],
        text: &[u8],
    ) -> Vec<u8> {
        let items_bytes: Vec<u8> = items
            .iter()
            .flat_map(|(d, v)| {
                let mut x = Vec::with_capacity(2 + d.len() + v.len());
                x.push(d.len() as u8);
                x.extend_from_slice(d);
                x.push(v.len() as u8);
                x.extend_from_slice(v);
                x
            })
            .collect();
        let body_len = NUMBERS_LEN
            + LANG_LEN
            + ITEMS_LEN_FIELD
            + items_bytes.len()
            + TEXT_LEN_FIELD
            + text.len();
        let mut v = Vec::with_capacity(HEADER_LEN + body_len);
        v.push(TAG);
        v.push(body_len as u8);
        v.push(((descriptor_number & 0x0F) << 4) | (last_descriptor_number & 0x0F));
        v.extend_from_slice(&lang);
        v.push(items_bytes.len() as u8);
        v.extend_from_slice(&items_bytes);
        v.push(text.len() as u8);
        v.extend_from_slice(text);
        v
    }

    #[test]
    fn parse_extracts_numbers_language_and_text() {
        let bytes = build(2, 3, *b"fra", &[], b"Hello");
        let d = ExtendedEventDescriptor::parse(&bytes).unwrap();
        assert_eq!(d.descriptor_number, 2);
        assert_eq!(d.last_descriptor_number, 3);
        assert_eq!(d.language_code, LangCode::new(*b"fra"));
        assert_eq!(d.text.raw(), b"Hello");
        assert_eq!(d.items.len(), 0);
    }

    #[test]
    fn parse_extracts_item_list() {
        let items: [(&[u8], &[u8]); 2] = [(b"Director", b"Alice"), (b"Year", b"2023")];
        let bytes = build(0, 0, *b"eng", &items, b"");
        let d = ExtendedEventDescriptor::parse(&bytes).unwrap();
        assert_eq!(d.items.len(), 2);
        assert_eq!(d.items[0].description.raw(), b"Director");
        assert_eq!(d.items[0].value.raw(), b"Alice");
        assert_eq!(d.items[1].description.raw(), b"Year");
        assert_eq!(d.items[1].value.raw(), b"2023");
    }

    #[test]
    fn parse_rejects_wrong_tag() {
        // Full 8-byte descriptor with the wrong tag — must fail with tag mismatch.
        let bytes = [0x4D, 6, 0x00, b'e', b'n', b'g', 0, 0];
        assert!(matches!(
            ExtendedEventDescriptor::parse(&bytes).unwrap_err(),
            Error::InvalidDescriptor { tag: 0x4D, .. }
        ));
    }

    #[test]
    fn parse_rejects_short_header() {
        assert!(matches!(
            ExtendedEventDescriptor::parse(&[TAG, 2, 0, 0]).unwrap_err(),
            Error::BufferTooShort(..)
        ));
    }

    #[test]
    fn parse_rejects_item_length_overrun() {
        // items_length=10 but body only 6 bytes after the items_length field.
        let bytes = [
            TAG, 11, 0x00, b'e', b'n', b'g', 10, // items_length claims 10 bytes
            0, 0, 0, 0, 0, // only 5 bytes of items
            0, // text_length (partially unreachable)
        ];
        assert!(matches!(
            ExtendedEventDescriptor::parse(&bytes).unwrap_err(),
            Error::InvalidDescriptor { .. }
        ));
    }

    #[test]
    fn parse_rejects_text_length_overrun() {
        // body=6: numbers + lang + items_length=0 + text_length=5 but no text bytes.
        let bytes = [TAG, 6, 0x00, b'e', b'n', b'g', 0, 5];
        assert!(matches!(
            ExtendedEventDescriptor::parse(&bytes).unwrap_err(),
            Error::InvalidDescriptor { .. }
        ));
    }

    #[test]
    fn empty_items_and_text_valid() {
        let bytes = build(0, 0, *b"eng", &[], b"");
        let d = ExtendedEventDescriptor::parse(&bytes).unwrap();
        assert_eq!(d.items.len(), 0);
        assert_eq!(d.text.raw(), b"");
    }

    #[test]
    fn serialize_round_trip_with_items_and_text() {
        let items: [(&[u8], &[u8]); 1] = [(b"Genre", b"Drama")];
        let bytes = build(1, 2, *b"eng", &items, b"Plot summary.");
        let parsed = ExtendedEventDescriptor::parse(&bytes).unwrap();
        let mut buf = vec![0u8; parsed.serialized_len()];
        parsed.serialize_into(&mut buf).unwrap();
        assert_eq!(buf, bytes);
        let re = ExtendedEventDescriptor::parse(&buf).unwrap();
        assert_eq!(parsed, re);
    }

    #[test]
    fn serialize_round_trip_without_items() {
        let bytes = build(3, 3, *b"fra", &[], b"Plot.");
        let parsed = ExtendedEventDescriptor::parse(&bytes).unwrap();
        let mut buf = vec![0u8; parsed.serialized_len()];
        parsed.serialize_into(&mut buf).unwrap();
        assert_eq!(buf, bytes);
    }

    #[test]
    fn parse_rejects_short_declared_body() {
        // Declared length byte = 0, body is empty — must reject with
        // BufferTooShort before indexing into it.
        let bytes = &[0x4E, 0x00, 0, 0, 0, 0, 0, 0];
        assert!(matches!(
            ExtendedEventDescriptor::parse(bytes).unwrap_err(),
            Error::BufferTooShort(broadcast_core::error::BufferTooShort {
                what: "ExtendedEventDescriptor body",
                ..
            })
        ));
    }

    #[test]
    fn parse_rejects_trailing_bytes_after_text() {
        let mut bytes = build(0, 0, *b"eng", &[], b"hi");
        bytes.push(0xFF);
        bytes[1] += 1;
        assert!(matches!(
            ExtendedEventDescriptor::parse(&bytes).unwrap_err(),
            Error::InvalidDescriptor { tag: TAG, .. }
        ));
    }

    #[test]
    fn parse_rejects_four_byte_body_without_indexing_past_it() {
        let bytes = [TAG, 0x04, 0x00, b'e', b'n', b'g', 0xAA, 0xAA, 0xAA, 0xAA];
        assert!(matches!(
            ExtendedEventDescriptor::parse(&bytes).unwrap_err(),
            Error::BufferTooShort(..)
        ));
    }

    #[test]
    fn parse_rejects_five_byte_body_as_too_short() {
        let bytes = [TAG, 0x05, 0x00, b'e', b'n', b'g', 0xAA, 0xFF];
        assert!(matches!(
            ExtendedEventDescriptor::parse(&bytes).unwrap_err(),
            Error::BufferTooShort(..)
        ));
    }

    #[test]
    fn parse_reports_item_description_overrun_exactly() {
        let bytes = [TAG, 0x08, 0x00, b'e', b'n', b'g', 0x02, 0x01, b'X', 0x00];
        assert!(matches!(
            ExtendedEventDescriptor::parse(&bytes).unwrap_err(),
            Error::InvalidDescriptor {
                tag: TAG,
                reason: "item_description_length runs past items loop",
            }
        ));
    }

    #[test]
    fn parse_rejects_items_ending_at_body_end() {
        let bytes = [TAG, 0x07, 0x00, b'e', b'n', b'g', 0x02, 0x00, 0x00];
        assert!(matches!(
            ExtendedEventDescriptor::parse(&bytes).unwrap_err(),
            Error::InvalidDescriptor { tag: TAG, .. }
        ));
    }

    #[test]
    fn parse_rejects_description_overrunning_items_loop() {
        let bytes = [
            TAG, 0x0A, 0x00, b'e', b'n', b'g', 0x04, 0x04, 0x00, 0x00, 0x00, 0x00,
        ];
        assert!(matches!(
            ExtendedEventDescriptor::parse(&bytes).unwrap_err(),
            Error::InvalidDescriptor { tag: TAG, .. }
        ));
    }

    #[test]
    fn parse_accepts_empty_value_as_last_item() {
        let items: [(&[u8], &[u8]); 1] = [(b"Dir", b"")];
        let bytes = build(0, 0, *b"eng", &items, b"");
        let d = ExtendedEventDescriptor::parse(&bytes).unwrap();
        assert_eq!(d.items.len(), 1);
        assert_eq!(d.items[0].description.raw(), b"Dir");
        assert_eq!(d.items[0].value.raw(), b"");
        let mut buf = vec![0u8; d.serialized_len()];
        d.serialize_into(&mut buf).unwrap();
        assert_eq!(buf, bytes);
    }
}