dvb-si 5.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
//! VBI Data Descriptor โ€” ETSI EN 300 468 ยง6.2.47 (tag 0x45).
//!
//! Table 106 (PDF p. 110). Carried in PMT ES_info for an elementary stream
//! carrying VBI data (per ETSI EN 301 775). Body is a loop of entries, each a
//! `data_service_id` byte + an 8-bit `data_service_descriptor_length` + that
//! many service-descriptor bytes.
//!
//! The first loop level (data_service_id + length-delimited service block) is
//! typed. For `data_service_id` values `0x01`โ€“`0x02`, `0x04`โ€“`0x07` (Table 106/107), each
//! service-descriptor byte encodes `reserved(2)|field_parity(1)|line_offset(5)`;
//! other values are kept as raw reserved bytes.

use super::descriptor_body;
use crate::error::{Error, Result};
use dvb_common::{Parse, Serialize};

/// Descriptor tag for VBI_data_descriptor.
pub const TAG: u8 = 0x45;
const HEADER_LEN: usize = 2;
const ENTRY_HEADER_LEN: usize = 2;
const MAX_BODY_LEN: usize = u8::MAX as usize;
const MAX_SERVICE_LEN: usize = u8::MAX as usize;

/// Per-service-descriptor content, keyed by `data_service_id`.
#[derive(Debug, Clone, PartialEq, Eq)]
#[cfg_attr(feature = "serde", derive(serde::Serialize))]
#[cfg_attr(feature = "yoke", derive(yoke::Yokeable))]
#[non_exhaustive]
pub enum VbiService<'a> {
    /// `data_service_id` 0x01โ€“0x02, 0x04โ€“0x07: each byte is
    /// `reserved_future_use(2)|field_parity(1)|line_offset(5)` (Table 106).
    Lines(Vec<VbiLine>),
    /// `data_service_id` 0x00, 0x03, or 0x08+: raw reserved bytes.
    Reserved(&'a [u8]),
}

/// One VBI line entry (Table 106 per-byte layout for ids 0x01โ€“0x07).
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[cfg_attr(feature = "serde", derive(serde::Serialize))]
pub struct VbiLine {
    /// `field_parity` (1 bit) โ€” `[5]` of the service-descriptor byte.
    pub field_parity: bool,
    /// `line_offset` (5 bits) โ€” `[4:0]` of the service-descriptor byte.
    pub line_offset: u8,
}

/// One VBI data service entry.
#[derive(Debug, Clone, PartialEq, Eq)]
#[cfg_attr(feature = "serde", derive(serde::Serialize))]
#[cfg_attr(feature = "yoke", derive(yoke::Yokeable))]
pub struct VbiDataEntry<'a> {
    /// data_service_id (EN 300 468 Table 107): 0x01 = EBU teletext,
    /// 0x02 = inverted teletext, 0x04 = VPS, 0x05 = WSS, 0x06 = closed
    /// captioning, 0x07 = monochrome 4:2:2 samples; others reserved/user.
    pub data_service_id: u8,
    /// Per-service content, typed for ids 0x01โ€“0x02, 0x04โ€“0x07.
    pub service_descriptor: VbiService<'a>,
}

/// VBI Data Descriptor.
#[derive(Debug, Clone, PartialEq, Eq)]
#[cfg_attr(feature = "serde", derive(serde::Serialize))]
#[cfg_attr(feature = "yoke", derive(yoke::Yokeable))]
pub struct VbiDataDescriptor<'a> {
    /// Service entries in wire order.
    pub entries: Vec<VbiDataEntry<'a>>,
}

impl<'a> Parse<'a> for VbiDataDescriptor<'a> {
    type Error = crate::error::Error;
    fn parse(bytes: &'a [u8]) -> Result<Self> {
        let body = descriptor_body(
            bytes,
            TAG,
            "VbiDataDescriptor",
            "unexpected tag for VBI_data_descriptor",
        )?;
        let mut entries = Vec::new();
        let mut pos = 0;
        while pos < body.len() {
            if pos + ENTRY_HEADER_LEN > body.len() {
                return Err(Error::InvalidDescriptor {
                    tag: TAG,
                    reason: "truncated VBI data entry header",
                });
            }
            let data_service_id = body[pos];
            let svc_len = body[pos + 1] as usize;
            pos += ENTRY_HEADER_LEN;
            if pos + svc_len > body.len() {
                return Err(Error::InvalidDescriptor {
                    tag: TAG,
                    reason: "data_service_descriptor_length exceeds descriptor body",
                });
            }
            let svc_bytes = &body[pos..pos + svc_len];
            pos += svc_len;
            let service_descriptor = if matches!(data_service_id, 0x01 | 0x02 | 0x04..=0x07) {
                let lines = svc_bytes
                    .iter()
                    .map(|&b| VbiLine {
                        field_parity: (b & 0x20) != 0,
                        line_offset: b & 0x1F,
                    })
                    .collect();
                VbiService::Lines(lines)
            } else {
                VbiService::Reserved(svc_bytes)
            };
            entries.push(VbiDataEntry {
                data_service_id,
                service_descriptor,
            });
        }
        Ok(Self { entries })
    }
}

impl Serialize for VbiDataDescriptor<'_> {
    type Error = crate::error::Error;
    fn serialized_len(&self) -> usize {
        HEADER_LEN
            + self
                .entries
                .iter()
                .map(|e| {
                    ENTRY_HEADER_LEN
                        + match &e.service_descriptor {
                            VbiService::Lines(lines) => lines.len(),
                            VbiService::Reserved(b) => b.len(),
                        }
                })
                .sum::<usize>()
    }

    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 body_len = len - HEADER_LEN;
        if body_len > MAX_BODY_LEN {
            return Err(Error::InvalidDescriptor {
                tag: TAG,
                reason: "VBI_data_descriptor body exceeds 255 bytes",
            });
        }
        buf[0] = TAG;
        buf[1] = body_len as u8;
        let mut pos = HEADER_LEN;
        for e in &self.entries {
            let svc_len = match &e.service_descriptor {
                VbiService::Lines(lines) => lines.len(),
                VbiService::Reserved(b) => b.len(),
            };
            if svc_len > MAX_SERVICE_LEN {
                return Err(Error::InvalidDescriptor {
                    tag: TAG,
                    reason: "service_descriptor exceeds 255 bytes (8-bit length field)",
                });
            }
            buf[pos] = e.data_service_id;
            buf[pos + 1] = svc_len as u8;
            pos += ENTRY_HEADER_LEN;
            match &e.service_descriptor {
                VbiService::Lines(lines) => {
                    for line in lines {
                        buf[pos] =
                            0xC0 | (u8::from(line.field_parity) << 5) | (line.line_offset & 0x1F);
                        pos += 1;
                    }
                }
                VbiService::Reserved(b) => {
                    buf[pos..pos + b.len()].copy_from_slice(b);
                    pos += b.len();
                }
            }
        }
        Ok(len)
    }
}
impl<'a> crate::traits::DescriptorDef<'a> for VbiDataDescriptor<'a> {
    const TAG: u8 = TAG;
    const NAME: &'static str = "VBI_DATA";
}

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

    #[test]
    fn parse_single_entry() {
        // data_service_id=0x01 (EBU teletext), 2 line bytes: 0xC1, 0xC2
        // 0xC1 = reserved(2)=11 | field_parity=0 | line_offset=00001 โ†’ fp=false, lo=1
        // 0xC2 = reserved(2)=11 | field_parity=0 | line_offset=00010 โ†’ fp=false, lo=2
        let bytes = [TAG, 4, 0x01, 0x02, 0xC1, 0xC2];
        let d = VbiDataDescriptor::parse(&bytes).unwrap();
        assert_eq!(d.entries.len(), 1);
        assert_eq!(d.entries[0].data_service_id, 0x01);
        match &d.entries[0].service_descriptor {
            VbiService::Lines(lines) => {
                assert_eq!(lines.len(), 2);
                assert!(!lines[0].field_parity);
                assert_eq!(lines[0].line_offset, 0x01);
                assert!(!lines[1].field_parity);
                assert_eq!(lines[1].line_offset, 0x02);
            }
            other => panic!("expected Lines, got {other:?}"),
        }
    }

    #[test]
    fn parse_multiple_entries() {
        // 0xAA = 10_1_01010 โ†’ fp=true, lo=0x0A=10
        // 0xBB = 10_1_11011 โ†’ fp=true, lo=0x1B=27
        // 0xCC = 11_0_01100 โ†’ fp=false, lo=0x0C=12
        let bytes = [TAG, 7, 0x04, 0x01, 0xAA, 0x05, 0x02, 0xBB, 0xCC];
        let d = VbiDataDescriptor::parse(&bytes).unwrap();
        assert_eq!(d.entries.len(), 2);
        assert_eq!(d.entries[0].data_service_id, 0x04);
        match &d.entries[0].service_descriptor {
            VbiService::Lines(lines) => {
                assert_eq!(lines.len(), 1);
                assert!(lines[0].field_parity);
                assert_eq!(lines[0].line_offset, 0x0A);
            }
            other => panic!("expected Lines, got {other:?}"),
        }
        assert_eq!(d.entries[1].data_service_id, 0x05);
        match &d.entries[1].service_descriptor {
            VbiService::Lines(lines) => {
                assert_eq!(lines.len(), 2);
                assert!(lines[0].field_parity);
                assert_eq!(lines[0].line_offset, 0x1B);
                assert!(!lines[1].field_parity);
                assert_eq!(lines[1].line_offset, 0x0C);
            }
            other => panic!("expected Lines, got {other:?}"),
        }
    }

    #[test]
    fn parse_entry_with_empty_service_block() {
        let bytes = [TAG, 2, 0x06, 0x00];
        let d = VbiDataDescriptor::parse(&bytes).unwrap();
        assert_eq!(d.entries.len(), 1);
        match &d.entries[0].service_descriptor {
            VbiService::Lines(lines) => assert!(lines.is_empty()),
            other => panic!("expected Lines, got {other:?}"),
        }
    }

    #[test]
    fn parse_reserved_data_service_id() {
        let bytes = [TAG, 4, 0x00, 0x02, 0xDE, 0xAD];
        let d = VbiDataDescriptor::parse(&bytes).unwrap();
        assert_eq!(d.entries.len(), 1);
        assert_eq!(d.entries[0].data_service_id, 0x00);
        match &d.entries[0].service_descriptor {
            VbiService::Reserved(b) => assert_eq!(*b, &[0xDE, 0xAD]),
            other => panic!("expected Reserved, got {other:?}"),
        }
    }

    #[test]
    fn parse_rejects_wrong_tag() {
        assert!(matches!(
            VbiDataDescriptor::parse(&[0x46, 0]).unwrap_err(),
            Error::InvalidDescriptor { tag: 0x46, .. }
        ));
    }

    #[test]
    fn parse_rejects_short_buffer() {
        // declares 4 body bytes, only 2 present
        let bytes = [TAG, 4, 0x01, 0x02];
        assert!(matches!(
            VbiDataDescriptor::parse(&bytes).unwrap_err(),
            Error::BufferTooShort { .. }
        ));
    }

    #[test]
    fn parse_rejects_inner_length_overrun() {
        // entry declares 5 service bytes but only 1 remains in body
        let bytes = [TAG, 3, 0x01, 0x05, 0xAA];
        assert!(matches!(
            VbiDataDescriptor::parse(&bytes).unwrap_err(),
            Error::InvalidDescriptor { tag: TAG, .. }
        ));
    }

    #[test]
    fn empty_descriptor_valid() {
        let d = VbiDataDescriptor::parse(&[TAG, 0]).unwrap();
        assert!(d.entries.is_empty());
    }

    #[test]
    fn serialize_round_trip() {
        let d = VbiDataDescriptor {
            entries: vec![
                VbiDataEntry {
                    data_service_id: 0x01,
                    service_descriptor: VbiService::Lines(vec![
                        VbiLine {
                            field_parity: false,
                            line_offset: 0x01,
                        },
                        VbiLine {
                            field_parity: false,
                            line_offset: 0x02,
                        },
                        VbiLine {
                            field_parity: false,
                            line_offset: 0x03,
                        },
                    ]),
                },
                VbiDataEntry {
                    data_service_id: 0x04,
                    service_descriptor: VbiService::Lines(vec![]),
                },
            ],
        };
        let mut buf = vec![0u8; d.serialized_len()];
        d.serialize_into(&mut buf).unwrap();
        assert_eq!(VbiDataDescriptor::parse(&buf).unwrap(), d);
    }

    #[test]
    fn serialize_round_trip_reserved() {
        let d = VbiDataDescriptor {
            entries: vec![VbiDataEntry {
                data_service_id: 0x80,
                service_descriptor: VbiService::Reserved(&[0xDE, 0xAD]),
            }],
        };
        let mut buf = vec![0u8; d.serialized_len()];
        d.serialize_into(&mut buf).unwrap();
        assert_eq!(VbiDataDescriptor::parse(&buf).unwrap(), d);
    }

    #[test]
    fn byte_identity_with_reserved_bits() {
        let bytes = [TAG, 4, 0x01, 0x02, 0xC1, 0xC2];
        let d = VbiDataDescriptor::parse(&bytes).unwrap();
        let mut buf = vec![0u8; d.serialized_len()];
        d.serialize_into(&mut buf).unwrap();
        assert_eq!(buf, bytes);
    }

    #[test]
    fn data_service_id_0x03_is_reserved() {
        let bytes = [TAG, 3, 0x03, 0x01, 0xAA];
        let d = VbiDataDescriptor::parse(&bytes).unwrap();
        assert_eq!(d.entries[0].data_service_id, 0x03);
        match &d.entries[0].service_descriptor {
            VbiService::Reserved(b) => assert_eq!(*b, &[0xAA]),
            other => panic!("expected Reserved for id 0x03, got {other:?}"),
        }
    }

    #[test]
    fn serialize_rejects_small_buffer() {
        let d = VbiDataDescriptor {
            entries: vec![VbiDataEntry {
                data_service_id: 0x01,
                service_descriptor: VbiService::Lines(vec![VbiLine {
                    field_parity: false,
                    line_offset: 0x0A,
                }]),
            }],
        };
        let mut tiny = [0u8; 3];
        assert!(matches!(
            d.serialize_into(&mut tiny).unwrap_err(),
            Error::OutputBufferTooSmall { .. }
        ));
    }

    #[cfg(feature = "serde")]
    #[test]
    fn serde_serialize_stable() {
        // Borrowed-byte fields cannot deserialize from a JSON array (serde_json
        // requires a borrowed-str for &[u8]); assert the Serialize half is
        // stable, matching the other borrowed descriptors (e.g.
        // content_identifier) in this crate.
        let make = || VbiDataDescriptor {
            entries: vec![VbiDataEntry {
                data_service_id: 0x01,
                service_descriptor: VbiService::Lines(vec![
                    VbiLine {
                        field_parity: false,
                        line_offset: 0x01,
                    },
                    VbiLine {
                        field_parity: false,
                        line_offset: 0x02,
                    },
                ]),
            }],
        };
        let json = serde_json::to_string(&make()).unwrap();
        assert!(json.contains("data_service_id"));
        assert_eq!(json, serde_json::to_string(&make()).unwrap());
    }
}