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
//! HEVC / VVC / EVC timing and HRD descriptors — Rec. ITU-T H.222.0 (08/2023) §2.6.97, §2.6.131, §2.6.135.
//!
//! `HEVC_timing_and_HRD_descriptor` (Table 2-115, `extension_descriptor_tag`
//! 0x03), `VVC_timing_and_HRD_descriptor` (Table 2-139, 0x15) and
//! `EVC_timing_and_HRD_descriptor` (Table 2-141, 0x16) all carry the same
//! `picture_and_timing_info` block; syntax in
//! `private/specs-verified/dvb/dvb-si/descriptors/iso_13818_1/3f-extension-descriptor-bodies-0x02-0x07.md`
//! and `…-0x0f-0x19.md`.
//!
//! ```text
//! HEVC:  hrd_management_valid_flag(1) target_schedule_idx_not_present_flag(1)
//!        target_schedule_idx(5) picture_and_timing_info_present_flag(1) [info]
//! VVC/EVC: hrd_management_valid_flag(1) reserved(6)
//!        picture_and_timing_info_present_flag(1) [info]
//! info:  90kHz_flag(1) reserved(7) [N(32) K(32) if 90kHz_flag==0] num_units_in_tick(32)
//! ```

use crate::bit_io::{BitReader, BitWriter};
use crate::error::Result;
use alloc::vec::Vec;
use broadcast_core::reserved::ReservedOnes;

/// Default of every `reserved` field of these descriptors (H.222.0 clause 2.1:
/// "reserved" bits are `1`).
const RESERVED_7_DEFAULT: ReservedOnes<RESERVED_AFTER_90KHZ_FLAG_BITS> =
    ReservedOnes::<RESERVED_AFTER_90KHZ_FLAG_BITS>::FILL;
const RESERVED_6_DEFAULT: ReservedOnes<RESERVED_AFTER_HRD_VALID_FLAG_BITS> =
    ReservedOnes::<RESERVED_AFTER_HRD_VALID_FLAG_BITS>::FILL;
const RESERVED_IDX_DEFAULT: u8 = 0x1F;
/// Width of the `reserved(7)` after `90kHz_flag`.
pub const RESERVED_AFTER_90KHZ_FLAG_BITS: u32 = 7;
/// Width of the `reserved(6)` after `hrd_management_valid_flag`.
pub const RESERVED_AFTER_HRD_VALID_FLAG_BITS: u32 = 6;
const TARGET_SCHEDULE_IDX_BITS: usize = 5;
/// Width of a 32-bit wire word, bits.
const WORD_BITS: usize = u32::BITS as usize;

/// `N` / `K` of the time-base mapping `time_scale = N × system_clock_frequency / K`,
/// present only when `90kHz_flag == '0'` (N = 1, K = 300 otherwise).
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[cfg_attr(feature = "serde", derive(serde::Serialize))]
#[non_exhaustive]
pub struct TimeScaleNk {
    /// `N` (32 bits).
    pub n: u32,
    /// `K` (32 bits).
    pub k: u32,
}

impl TimeScaleNk {
    /// Build from `N` and `K`.
    #[must_use]
    pub const fn new(n: u32, k: u32) -> Self {
        Self { n, k }
    }
}

/// The `picture_and_timing_info` block shared by the three descriptors.
#[derive(Debug, Clone, PartialEq, Eq)]
#[cfg_attr(feature = "serde", derive(serde::Serialize))]
#[non_exhaustive]
pub struct PictureAndTimingInfo {
    /// `N`/`K`; `None` means `90kHz_flag == '1'` (N = 1, K = 300).
    pub nk: Option<TimeScaleNk>,
    /// `num_units_in_tick` (32 bits; coded as the codec's VUI field).
    pub num_units_in_tick: u32,
    /// `reserved(7)` after `90kHz_flag`, right-aligned; re-emitted verbatim,
    /// default `0x7F`.
    pub reserved: ReservedOnes<RESERVED_AFTER_90KHZ_FLAG_BITS>,
}

impl PictureAndTimingInfo {
    /// Build with the spec `reserved` fill.
    #[must_use]
    pub const fn new(nk: Option<TimeScaleNk>, num_units_in_tick: u32) -> Self {
        Self {
            nk,
            num_units_in_tick,
            reserved: RESERVED_7_DEFAULT,
        }
    }

    fn read(r: &mut BitReader<'_>) -> Result<Self> {
        let is_90khz = r.flag()?;
        let reserved =
            ReservedOnes::from_bits(u64::from(r.u8(RESERVED_AFTER_90KHZ_FLAG_BITS as usize)?));
        let nk = if is_90khz {
            None
        } else {
            Some(TimeScaleNk {
                n: r.bits(WORD_BITS)?,
                k: r.bits(WORD_BITS)?,
            })
        };
        Ok(Self {
            nk,
            num_units_in_tick: r.bits(WORD_BITS)?,
            reserved,
        })
    }

    fn write(&self, w: &mut BitWriter) -> Result<()> {
        w.flag(self.nk.is_none(), "90kHz_flag")?;
        w.put(
            self.reserved.get(),
            RESERVED_AFTER_90KHZ_FLAG_BITS as usize,
            "reserved",
        )?;
        if let Some(nk) = &self.nk {
            w.put(u64::from(nk.n), WORD_BITS, "N")?;
            w.put(u64::from(nk.k), WORD_BITS, "K")?;
        }
        w.put(
            u64::from(self.num_units_in_tick),
            WORD_BITS,
            "num_units_in_tick",
        )
    }
}

/// `HEVC_timing_and_HRD_descriptor()` — Table 2-115 (`extension_descriptor_tag` 0x03).
#[derive(Debug, Clone, PartialEq, Eq)]
#[cfg_attr(feature = "serde", derive(serde::Serialize))]
#[non_exhaustive]
pub struct HevcTimingAndHrd {
    /// `hrd_management_valid_flag`.
    pub hrd_management_valid_flag: bool,
    /// `target_schedule_idx` (5 bits); `None` means
    /// `target_schedule_idx_not_present_flag == '1'`.
    pub target_schedule_idx: Option<u8>,
    /// The 5 "unspecified" bits that stand in for `target_schedule_idx` when it
    /// is not present (right-aligned, default `0x1F`); ignored otherwise.
    pub unspecified_schedule_bits: u8,
    /// `picture_and_timing_info`, present iff `picture_and_timing_info_present_flag`.
    pub picture_timing: Option<PictureAndTimingInfo>,
    /// Bytes after the syntax, preserved verbatim.
    pub trailing: Vec<u8>,
}

impl HevcTimingAndHrd {
    /// Build with the spec fill and no trailing bytes.
    #[must_use]
    pub fn new(
        hrd_management_valid_flag: bool,
        target_schedule_idx: Option<u8>,
        picture_timing: Option<PictureAndTimingInfo>,
    ) -> Self {
        Self {
            hrd_management_valid_flag,
            target_schedule_idx,
            unspecified_schedule_bits: RESERVED_IDX_DEFAULT,
            picture_timing,
            trailing: Vec::new(),
        }
    }

    pub(crate) fn parse_body(body: &[u8]) -> Result<Self> {
        let mut r = BitReader::new(body, "HevcTimingAndHrd");
        let hrd_management_valid_flag = r.flag()?;
        let not_present = r.flag()?;
        let idx = r.u8(TARGET_SCHEDULE_IDX_BITS)?;
        let info_present = r.flag()?;
        let picture_timing = if info_present {
            Some(PictureAndTimingInfo::read(&mut r)?)
        } else {
            None
        };
        Ok(Self {
            hrd_management_valid_flag,
            target_schedule_idx: (!not_present).then_some(idx),
            unspecified_schedule_bits: if not_present {
                idx
            } else {
                RESERVED_IDX_DEFAULT
            },
            picture_timing,
            trailing: r.rest()?.to_vec(),
        })
    }

    pub(crate) fn write_body(&self) -> Result<Vec<u8>> {
        let mut w = BitWriter::new();
        w.flag(self.hrd_management_valid_flag, "hrd_management_valid_flag")?;
        w.flag(
            self.target_schedule_idx.is_none(),
            "target_schedule_idx_not_present_flag",
        )?;
        let idx = self
            .target_schedule_idx
            .unwrap_or(self.unspecified_schedule_bits);
        w.put(
            u64::from(idx),
            TARGET_SCHEDULE_IDX_BITS,
            "target_schedule_idx",
        )?;
        w.flag(
            self.picture_timing.is_some(),
            "picture_and_timing_info_present_flag",
        )?;
        if let Some(p) = &self.picture_timing {
            p.write(&mut w)?;
        }
        w.bytes(&self.trailing)?;
        Ok(w.into_vec())
    }
}

/// `hrd_management_valid_flag(1) reserved(6) picture_and_timing_info_present_flag(1)
/// [picture_and_timing_info]` — identical in Tables 2-139 and 2-141.
fn read_flag_block(
    r: &mut BitReader<'_>,
) -> Result<(
    bool,
    ReservedOnes<RESERVED_AFTER_HRD_VALID_FLAG_BITS>,
    Option<PictureAndTimingInfo>,
)> {
    let hrd_management_valid_flag = r.flag()?;
    let reserved = ReservedOnes::from_bits(u64::from(
        r.u8(RESERVED_AFTER_HRD_VALID_FLAG_BITS as usize)?,
    ));
    let picture_timing = if r.flag()? {
        Some(PictureAndTimingInfo::read(r)?)
    } else {
        None
    };
    Ok((hrd_management_valid_flag, reserved, picture_timing))
}

fn write_flag_block(
    w: &mut BitWriter,
    hrd_management_valid_flag: bool,
    reserved: ReservedOnes<RESERVED_AFTER_HRD_VALID_FLAG_BITS>,
    picture_timing: Option<&PictureAndTimingInfo>,
) -> Result<()> {
    w.flag(hrd_management_valid_flag, "hrd_management_valid_flag")?;
    w.put(
        reserved.get(),
        RESERVED_AFTER_HRD_VALID_FLAG_BITS as usize,
        "reserved",
    )?;
    w.flag(
        picture_timing.is_some(),
        "picture_and_timing_info_present_flag",
    )?;
    if let Some(p) = picture_timing {
        p.write(w)?;
    }
    Ok(())
}

/// `VVC_timing_and_HRD_descriptor()` — Table 2-139 (`extension_descriptor_tag` 0x15).
#[derive(Debug, Clone, PartialEq, Eq)]
#[cfg_attr(feature = "serde", derive(serde::Serialize))]
#[non_exhaustive]
pub struct VvcTimingAndHrd {
    /// `hrd_management_valid_flag`.
    pub hrd_management_valid_flag: bool,
    /// `reserved(6)` after the flag, right-aligned; re-emitted verbatim,
    /// default `0x3F`.
    pub reserved: ReservedOnes<RESERVED_AFTER_HRD_VALID_FLAG_BITS>,
    /// `picture_and_timing_info`, present iff `picture_and_timing_info_present_flag`.
    pub picture_timing: Option<PictureAndTimingInfo>,
    /// Bytes after the syntax, preserved verbatim.
    pub trailing: Vec<u8>,
}

impl VvcTimingAndHrd {
    /// Build with the spec `reserved` fill and no trailing bytes.
    #[must_use]
    pub fn new(
        hrd_management_valid_flag: bool,
        picture_timing: Option<PictureAndTimingInfo>,
    ) -> Self {
        Self {
            hrd_management_valid_flag,
            reserved: RESERVED_6_DEFAULT,
            picture_timing,
            trailing: Vec::new(),
        }
    }

    pub(crate) fn parse_body(body: &[u8]) -> Result<Self> {
        let mut r = BitReader::new(body, "VvcTimingAndHrd");
        let (hrd_management_valid_flag, reserved, picture_timing) = read_flag_block(&mut r)?;
        Ok(Self {
            hrd_management_valid_flag,
            reserved,
            picture_timing,
            trailing: r.rest()?.to_vec(),
        })
    }

    pub(crate) fn write_body(&self) -> Result<Vec<u8>> {
        let mut w = BitWriter::new();
        write_flag_block(
            &mut w,
            self.hrd_management_valid_flag,
            self.reserved,
            self.picture_timing.as_ref(),
        )?;
        w.bytes(&self.trailing)?;
        Ok(w.into_vec())
    }
}

/// `EVC_timing_and_HRD_descriptor()` — Table 2-141 (`extension_descriptor_tag` 0x16).
#[derive(Debug, Clone, PartialEq, Eq)]
#[cfg_attr(feature = "serde", derive(serde::Serialize))]
#[non_exhaustive]
pub struct EvcTimingAndHrd {
    /// `hrd_management_valid_flag`.
    pub hrd_management_valid_flag: bool,
    /// `reserved(6)` after the flag, right-aligned; re-emitted verbatim,
    /// default `0x3F`.
    pub reserved: ReservedOnes<RESERVED_AFTER_HRD_VALID_FLAG_BITS>,
    /// `picture_and_timing_info`, present iff `picture_and_timing_info_present_flag`.
    pub picture_timing: Option<PictureAndTimingInfo>,
    /// Bytes after the syntax, preserved verbatim.
    pub trailing: Vec<u8>,
}

impl EvcTimingAndHrd {
    /// Build with the spec `reserved` fill and no trailing bytes.
    #[must_use]
    pub fn new(
        hrd_management_valid_flag: bool,
        picture_timing: Option<PictureAndTimingInfo>,
    ) -> Self {
        Self {
            hrd_management_valid_flag,
            reserved: RESERVED_6_DEFAULT,
            picture_timing,
            trailing: Vec::new(),
        }
    }

    pub(crate) fn parse_body(body: &[u8]) -> Result<Self> {
        let mut r = BitReader::new(body, "EvcTimingAndHrd");
        let (hrd_management_valid_flag, reserved, picture_timing) = read_flag_block(&mut r)?;
        Ok(Self {
            hrd_management_valid_flag,
            reserved,
            picture_timing,
            trailing: r.rest()?.to_vec(),
        })
    }

    pub(crate) fn write_body(&self) -> Result<Vec<u8>> {
        let mut w = BitWriter::new();
        write_flag_block(
            &mut w,
            self.hrd_management_valid_flag,
            self.reserved,
            self.picture_timing.as_ref(),
        )?;
        w.bytes(&self.trailing)?;
        Ok(w.into_vec())
    }
}

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

    #[test]
    fn hevc_90khz_and_nk_round_trip() {
        // hrd=1, not_present=1, idx(unspecified)=0x1F, info_present=1 -> 0xFF; 90kHz=1,reserved=7F -> 0xFF; ticks
        let b = [0xFF, 0xFF, 0x00, 0x00, 0x03, 0xE9];
        let d = HevcTimingAndHrd::parse_body(&b).unwrap();
        assert!(d.hrd_management_valid_flag);
        assert_eq!(d.target_schedule_idx, None);
        let p = d.picture_timing.as_ref().unwrap();
        assert_eq!(p.nk, None);
        assert_eq!(p.num_units_in_tick, 1001);
        assert_eq!(d.write_body().unwrap(), b);
        // 90kHz=0 -> N and K on the wire, schedule idx present (= 3)
        let b2 = [0b1000_0111, 0x7F, 0, 0, 0, 1, 0, 0, 1, 0x2C, 0, 0, 0, 0x64];
        let d2 = HevcTimingAndHrd::parse_body(&b2).unwrap();
        assert_eq!(d2.target_schedule_idx, Some(3));
        let nk = d2.picture_timing.as_ref().unwrap().nk.unwrap();
        assert_eq!((nk.n, nk.k), (1, 300));
        assert_eq!(d2.write_body().unwrap(), b2);
    }

    #[test]
    fn hevc_truncated_and_overflow() {
        assert!(matches!(
            &(HevcTimingAndHrd::parse_body(&[0xFF, 0x7F])),
            Err(crate::error::Error::BufferTooShort(..))
        ));
        let mut d = HevcTimingAndHrd::new(true, Some(0x20), None);
        assert!(matches!(
            d.write_body(),
            Err(crate::Error::FieldOverflow(..))
        ));
        d.target_schedule_idx = Some(0x1F);
        assert!(d.write_body().is_ok());
    }

    #[test]
    fn vvc_and_evc_round_trip_with_reserved_and_trailing() {
        let b = [0b0111_1110, 0xAA, 0xBB];
        let v = VvcTimingAndHrd::parse_body(&b).unwrap();
        assert!(v.picture_timing.is_none());
        assert_eq!(v.trailing, [0xAA, 0xBB]);
        assert_eq!(v.write_body().unwrap(), b);
        // non-default reserved bits survive
        let b = [0b1000_0001, 0x80, 0, 0, 0, 7];
        let e = EvcTimingAndHrd::parse_body(&b).unwrap();
        assert_eq!(e.reserved.get(), 0);
        assert_eq!(e.picture_timing.as_ref().unwrap().reserved.get(), 0);
        assert_eq!(e.write_body().unwrap(), b);
    }
}