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
441
442
443
444
445
446
447
448
449
450
451
452
453
//! DOVI_video_stream_descriptor — Dolby Vision MPEG-2 TS carriage of a Dolby
//! Vision configuration record (Dolby Vision Streams Within the MPEG-2
//! Transport Stream Format, Table 3-2, tag `0xB0`), carried in the PMT ES_info
//! loop of a Dolby Vision elementary stream and announced by a
//! `registration_descriptor` whose `format_identifier` is `DOVI` (Table 3-1).
//!
//! Tag `0xB0` lies in the user-defined range, so the descriptor is **private**
//! and is not auto-dispatched by `parse_loop`;
//! [`DoviVideoStreamDescriptor::find`] walks a raw ES_info loop for it. The
//! fields are the descriptor's own: the ISOBMFF `dvcC`/`dvvC` record is a
//! different structure, and `transmux` converts between the two.
//!
//! Source: `private/specs-verified/dolby/vision/dolby-vision-streams-in-mpeg2-ts-v1.2.md`
//! (Tables 3-1 and 3-2).
//!
//! Layout (Table 3-2):
//!
//! ```text
//! descriptor_tag(8)=0xB0 descriptor_length(8)
//! dv_version_major(8) dv_version_minor(8)
//! dv_profile(7) dv_level(6) rpu_present_flag(1) el_present_flag(1) bl_present_flag(1)
//! if bl_present_flag==0: dependency_pid(13) reserved(3)
//! dv_bl_signal_compatibility_id(4) reserved(4)
//! ```
//!
//! The reserved bits and any bytes after the defined syntax are captured on
//! parse and re-emitted verbatim.

use super::{descriptor_body, write_descriptor_header};
use crate::error::{Error, Result};
use alloc::vec::Vec;
use broadcast_core::len::{need_in, need_out};
use broadcast_core::{Parse, Serialize};
use mpeg_ts::descriptor_loop::{DESCRIPTOR_HEADER_LEN, RawDescriptorLoop};

/// Descriptor tag for the DOVI_video_stream_descriptor (Table 3-2).
pub const TAG: u8 = 0xB0;
/// `format_identifier` "DOVI" of the registration descriptor (Table 3-1).
pub const FORMAT_IDENTIFIER: [u8; 4] = *b"DOVI";
/// [`FORMAT_IDENTIFIER`] as the scope value a registry walk opens on that
/// registration.
pub const REGISTRATION_SCOPE: u32 = u32::from_be_bytes(FORMAT_IDENTIFIER);

fn invalid(field: &'static str, value: u64, reason: &'static str) -> Error {
    Error::InvalidValue(broadcast_core::error::InvalidValue::new(
        field, value, reason,
    ))
}

const TS_DESCRIPTOR_BASE_LEN: usize = 5;
const TS_DESCRIPTOR_DEPENDENCY_LEN: usize = 2;
const MAJOR_OFFSET: usize = 0;
const MINOR_OFFSET: usize = 1;
const CONFIG_WORD_OFFSET: usize = 2;
const CCID_OFFSET: usize = 4;
const PID_SHIFT: u32 = 3;
const PID_MAX: u16 = 0x1FFF;
const PROFILE_SHIFT: u32 = 9;
const LEVEL_SHIFT: u32 = 3;
const LEVEL_BITS: u32 = 6;
const LEVEL_MASK: u16 = (1 << LEVEL_BITS) - 1;
const PROFILE_BITS: u32 = u16::BITS - PROFILE_SHIFT;
const RPU_FLAG: u16 = 0b100;
const EL_FLAG: u16 = 0b010;
const BL_FLAG: u16 = 0b001;
const CCID_SHIFT: u32 = 4;
/// Mask of `dv_bl_signal_compatibility_id` and of the 4 reserved bits that
/// close the descriptor.
const NIBBLE_MASK: u8 = 0x0F;
const DEPENDENCY_RESERVED_MASK: u8 = (1 << PID_SHIFT) - 1;

/// `DOVI_video_stream_descriptor` (Table 3-2). Owned (`extension` is a
/// `Vec<u8>`) so a track can keep it beyond the PMT it came from.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct DoviVideoStreamDescriptor {
    /// `dv_version_major`.
    pub version_major: u8,
    /// `dv_version_minor`.
    pub version_minor: u8,
    /// `dv_profile` (7 bits).
    pub profile: u8,
    /// `dv_level` (6 bits).
    pub level: u8,
    /// `rpu_present_flag`.
    pub rpu_present: bool,
    /// `el_present_flag` (spelt `el_presnet_flag` in Table 3-2).
    pub el_present: bool,
    /// `bl_present_flag`.
    pub bl_present: bool,
    /// `dependency_pid` (13 bits), present exactly when `bl_present_flag` is 0.
    pub dependency_pid: Option<u16>,
    /// The 3 reserved bits after `dependency_pid` (0 when absent), captured
    /// on parse and re-emitted verbatim.
    pub dependency_reserved: u8,
    /// `dv_bl_signal_compatibility_id` (4 bits).
    pub bl_signal_compatibility_id: u8,
    /// The 4 reserved bits closing the descriptor, captured on parse and
    /// re-emitted verbatim.
    pub reserved: u8,
    /// Bytes after the defined syntax within `descriptor_length`, preserved
    /// verbatim (TS spec Table 3-2 `descriptor_length` counts every byte
    /// following the length field).
    pub extension: Vec<u8>,
}

impl Parse<'_> for DoviVideoStreamDescriptor {
    type Error = Error;

    fn parse(bytes: &[u8]) -> Result<Self> {
        let body = descriptor_body(
            bytes,
            TAG,
            "DOVI_video_stream_descriptor",
            "unexpected tag for DOVI_video_stream_descriptor",
        )?;
        need_in(body, TS_DESCRIPTOR_BASE_LEN, "DOVI_video_stream_descriptor")?;
        let word = broadcast_core::wire::Reader::at(body, CONFIG_WORD_OFFSET).u16("word")?;
        let bl_present = word & BL_FLAG != 0;
        let mut dependency_reserved = 0u8;
        let mut dependency_pid = None;
        let mut tail = CCID_OFFSET;
        if !bl_present {
            need_in(
                body,
                TS_DESCRIPTOR_BASE_LEN + TS_DESCRIPTOR_DEPENDENCY_LEN,
                "DOVI_video_stream_descriptor dependency_pid",
            )?;
            let raw = broadcast_core::wire::Reader::at(body, CCID_OFFSET).u16("raw")?;
            dependency_reserved = body[CCID_OFFSET + 1] & DEPENDENCY_RESERVED_MASK;
            dependency_pid = Some(raw >> PID_SHIFT);
            tail += TS_DESCRIPTOR_DEPENDENCY_LEN;
        }
        need_in(body, tail + 1, "DOVI_video_stream_descriptor")?;
        Ok(Self {
            version_major: body[MAJOR_OFFSET],
            version_minor: body[MINOR_OFFSET],
            profile: (word >> PROFILE_SHIFT) as u8,
            level: ((word >> LEVEL_SHIFT) & LEVEL_MASK) as u8,
            rpu_present: word & RPU_FLAG != 0,
            el_present: word & EL_FLAG != 0,
            bl_present,
            dependency_pid,
            dependency_reserved,
            bl_signal_compatibility_id: body[tail] >> CCID_SHIFT,
            reserved: body[tail] & NIBBLE_MASK,
            extension: body[tail + 1..].to_vec(),
        })
    }
}

impl Serialize for DoviVideoStreamDescriptor {
    type Error = Error;

    fn serialized_len(&self) -> usize {
        DESCRIPTOR_HEADER_LEN + self.body_len()
    }

    fn serialize_into(&self, buf: &mut [u8]) -> Result<usize> {
        let need = self.serialized_len();
        need_out(buf, need, "DoviVideoStreamDescriptor")?;
        if u16::from(self.level) > LEVEL_MASK || self.profile >= 1 << PROFILE_BITS {
            return Err(invalid(
                "DOVI_video_stream_descriptor",
                u64::from(self.level),
                "field does not fit its bit width",
            ));
        }
        write_descriptor_header(buf, TAG, self.body_len())?;
        let b = &mut buf[DESCRIPTOR_HEADER_LEN..need];
        b[MAJOR_OFFSET] = self.version_major;
        b[MINOR_OFFSET] = self.version_minor;
        let word = (u16::from(self.profile) << PROFILE_SHIFT)
            | (u16::from(self.level) << LEVEL_SHIFT)
            | if self.rpu_present { RPU_FLAG } else { 0 }
            | if self.el_present { EL_FLAG } else { 0 }
            | if self.bl_present { BL_FLAG } else { 0 };
        b[CONFIG_WORD_OFFSET..CCID_OFFSET].copy_from_slice(&word.to_be_bytes());
        let tail = match (self.bl_present, self.dependency_pid) {
            (true, None) => CCID_OFFSET,
            (false, Some(pid)) if pid <= PID_MAX => {
                if self.dependency_reserved > DEPENDENCY_RESERVED_MASK {
                    return Err(invalid(
                        "dependency_reserved",
                        u64::from(self.dependency_reserved),
                        "does not fit 3 bits",
                    ));
                }
                b[CCID_OFFSET..CCID_OFFSET + TS_DESCRIPTOR_DEPENDENCY_LEN].copy_from_slice(
                    &((pid << PID_SHIFT) | u16::from(self.dependency_reserved)).to_be_bytes(),
                );
                CCID_OFFSET + TS_DESCRIPTOR_DEPENDENCY_LEN
            }
            _ => {
                return Err(invalid(
                    "dependency_pid",
                    self.dependency_pid.map_or(0, u64::from),
                    "present exactly when bl_present_flag is 0, and 13 bits",
                ));
            }
        };
        if self.reserved > NIBBLE_MASK {
            return Err(invalid(
                "DOVI_video_stream_descriptor.reserved",
                u64::from(self.reserved),
                "does not fit 4 bits",
            ));
        }
        let ccid = broadcast_core::len::fit_mask(
            self.bl_signal_compatibility_id,
            NIBBLE_MASK,
            "dv_bl_signal_compatibility_id",
        )?;
        b[tail] = (ccid << CCID_SHIFT) | self.reserved;
        b[tail + 1..].copy_from_slice(&self.extension);
        Ok(need)
    }
}

impl DoviVideoStreamDescriptor {
    fn body_len(&self) -> usize {
        TS_DESCRIPTOR_BASE_LEN
            + if self.bl_present {
                0
            } else {
                TS_DESCRIPTOR_DEPENDENCY_LEN
            }
            + self.extension.len()
    }

    /// The first `DOVI_video_stream_descriptor` of a PMT ES_info loop that
    /// parses, found by the raw tag/length walk.
    #[must_use]
    pub fn find(es_info: &[u8]) -> Option<Self> {
        RawDescriptorLoop::new(es_info)
            .entries()
            .map_while(core::result::Result::ok)
            .find(|e| e.tag == TAG)
            .and_then(|e| Self::parse(e.raw).ok())
    }

    /// Whether an ES_info loop carries the `registration_descriptor` whose
    /// `format_identifier` is `DOVI`.
    #[must_use]
    pub fn is_registered(es_info: &[u8]) -> bool {
        RawDescriptorLoop::new(es_info)
            .entries()
            .map_while(core::result::Result::ok)
            .any(|e| e.tag == super::registration::TAG && e.body.starts_with(&FORMAT_IDENTIFIER))
    }
}

impl<'a> crate::traits::DescriptorDef<'a> for DoviVideoStreamDescriptor {
    const TAG: u8 = TAG;
    const NAME: &'static str = "DOVI_VIDEO_STREAM";
}

#[cfg(feature = "serde")]
impl serde::Serialize for DoviVideoStreamDescriptor {
    fn serialize<S: serde::Serializer>(
        &self,
        serializer: S,
    ) -> core::result::Result<S::Ok, S::Error> {
        use serde::ser::SerializeStruct;
        let mut st = serializer.serialize_struct("DoviVideoStreamDescriptor", SERDE_FIELDS)?;
        st.serialize_field("version_major", &self.version_major)?;
        st.serialize_field("version_minor", &self.version_minor)?;
        st.serialize_field("profile", &self.profile)?;
        st.serialize_field("level", &self.level)?;
        st.serialize_field("rpu_present", &self.rpu_present)?;
        st.serialize_field("el_present", &self.el_present)?;
        st.serialize_field("bl_present", &self.bl_present)?;
        st.serialize_field(
            "bl_signal_compatibility_id",
            &self.bl_signal_compatibility_id,
        )?;
        st.serialize_field("dependency_pid", &self.dependency_pid)?;
        st.serialize_field("dependency_reserved", &self.dependency_reserved)?;
        st.serialize_field("reserved", &self.reserved)?;
        st.serialize_field("extension", &self.extension)?;
        st.end()
    }
}

#[cfg(feature = "serde")]
const SERDE_FIELDS: usize = 12;

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

    fn framed(body: &[u8]) -> Vec<u8> {
        let mut out = alloc::vec![TAG, body.len() as u8];
        out.extend_from_slice(body);
        out
    }

    fn single_layer() -> DoviVideoStreamDescriptor {
        DoviVideoStreamDescriptor::parse(&framed(&[0x01, 0x00, 0x10, 0x1D, 0x10])).unwrap()
    }

    #[test]
    fn single_layer_profile_8_1_fields() {
        let d = single_layer();
        assert_eq!((d.version_major, d.version_minor), (1, 0));
        assert_eq!((d.profile, d.level), (8, 3));
        assert!(d.rpu_present && !d.el_present && d.bl_present);
        assert_eq!(d.dependency_pid, None);
        assert_eq!(d.bl_signal_compatibility_id, 1);
    }

    #[test]
    fn descriptor_reserved_bits_are_preserved_byte_exact() {
        let with_pid = [0x01, 0x00, 0x0E, 0x1A, 0x12, 0x37, 0x4B];
        let d = DoviVideoStreamDescriptor::parse(&framed(&with_pid)).unwrap();
        assert_eq!(d.dependency_pid, Some(0x246));
        assert_eq!(d.dependency_reserved, 0x7);
        assert_eq!(d.reserved, 0xB);
        assert_eq!(d.try_to_bytes().unwrap(), framed(&with_pid));
        let single = [0x01, 0x00, 0x10, 0x1D, 0x1F];
        let d = DoviVideoStreamDescriptor::parse(&framed(&single)).unwrap();
        assert_eq!(d.reserved, 0xF);
        assert_eq!(d.bl_signal_compatibility_id, 1);
        assert_eq!(d.try_to_bytes().unwrap(), framed(&single));
    }

    #[test]
    fn extension_bytes_round_trip() {
        let body = [0x01, 0x00, 0x10, 0x1D, 0x10, 0xAA, 0xBB];
        let d = DoviVideoStreamDescriptor::parse(&framed(&body)).unwrap();
        assert_eq!(d.extension, [0xAA, 0xBB]);
        assert_eq!(d.try_to_bytes().unwrap(), framed(&body));
    }

    #[test]
    fn descriptor_with_dependency_pid_round_trips() {
        let d = DoviVideoStreamDescriptor {
            version_major: 1,
            version_minor: 0,
            profile: 7,
            level: 6,
            rpu_present: true,
            el_present: true,
            bl_present: false,
            dependency_pid: Some(0x1234),
            dependency_reserved: 0,
            bl_signal_compatibility_id: 6,
            reserved: 0,
            extension: Vec::new(),
        };
        let bytes = d.try_to_bytes().unwrap();
        assert_eq!(bytes.len(), 9);
        assert_eq!(DoviVideoStreamDescriptor::parse(&bytes).unwrap(), d);
    }

    #[test]
    fn descriptor_without_base_layer_cut_before_its_pid_is_short() {
        let body = [0x01, 0x00, 0x0E, 0x1A, 0x00];
        assert!(matches!(
            DoviVideoStreamDescriptor::parse(&framed(&body)),
            Err(Error::BufferTooShort(..))
        ));
    }

    #[test]
    fn descriptor_cut_before_the_compatibility_id_is_short() {
        let body = [0x01, 0x00, 0x10, 0x1D];
        assert!(matches!(
            DoviVideoStreamDescriptor::parse(&framed(&body)),
            Err(Error::BufferTooShort(..))
        ));
    }

    #[test]
    fn field_maxima_serialize_and_overflow_is_rejected() {
        let mut d = single_layer();
        d.level = 63;
        d.bl_signal_compatibility_id = 15;
        d.profile = 127;
        let bytes = d.try_to_bytes().unwrap();
        assert_eq!(DoviVideoStreamDescriptor::parse(&bytes).unwrap(), d);
        for mutate in [
            (|d: &mut DoviVideoStreamDescriptor| d.level = 64) as fn(&mut _),
            |d| d.bl_signal_compatibility_id = 16,
            |d| d.profile = 128,
            |d| d.reserved = 16,
        ] {
            let mut bad = single_layer();
            mutate(&mut bad);
            assert!(bad.try_to_bytes().is_err());
        }
    }

    fn without_base_layer(pid: Option<u16>) -> DoviVideoStreamDescriptor {
        let mut d = single_layer();
        d.bl_present = false;
        d.dependency_pid = pid;
        d
    }

    #[test]
    fn descriptor_dependency_pid_accepts_its_13_bit_maximum() {
        let bytes = without_base_layer(Some(0x1FFF)).try_to_bytes().unwrap();
        assert_eq!(&bytes[6..8], &[0xFF, 0xF8]);
        assert_eq!(
            DoviVideoStreamDescriptor::parse(&bytes)
                .unwrap()
                .dependency_pid,
            Some(0x1FFF)
        );
    }

    #[test]
    fn descriptor_rejects_a_dependency_pid_above_13_bits() {
        assert!(matches!(
            without_base_layer(Some(0x2000)).try_to_bytes(),
            Err(Error::InvalidValue(..))
        ));
    }

    #[test]
    fn dependency_pid_must_match_the_base_layer_flag() {
        assert!(matches!(
            without_base_layer(None).try_to_bytes(),
            Err(Error::InvalidValue(..))
        ));
        let mut d = single_layer();
        d.dependency_pid = Some(0x100);
        assert!(matches!(d.try_to_bytes(), Err(Error::InvalidValue(..))));
    }

    #[test]
    fn find_walks_an_es_info_loop() {
        let mut es = alloc::vec![0x05, 4, b'D', b'O', b'V', b'I'];
        es.extend_from_slice(&framed(&[0x01, 0x00, 0x10, 0x1D, 0x10]));
        assert!(DoviVideoStreamDescriptor::is_registered(&es));
        assert_eq!(DoviVideoStreamDescriptor::find(&es).unwrap().profile, 8);
        assert!(!DoviVideoStreamDescriptor::is_registered(&es[6..]));
    }

    #[test]
    fn the_dovi_registration_descriptor_is_recognised_by_tag_and_body() {
        assert!(DoviVideoStreamDescriptor::is_registered(&[
            0x05, 0x04, b'D', b'O', b'V', b'I'
        ]));
        assert!(!DoviVideoStreamDescriptor::is_registered(&[
            0x05, 0x04, b'H', b'E', b'V', b'C'
        ]));
        assert!(!DoviVideoStreamDescriptor::is_registered(&[
            0x06, 0x04, b'D', b'O', b'V', b'I'
        ]));
        assert!(!DoviVideoStreamDescriptor::is_registered(&[]));
    }
}