dvb-si 12.0.1

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
//! Hierarchy Descriptor — ISO/IEC 13818-1 §2.6.6 (tag 0x04).
//!
//! Identifies the hierarchy layer, embedded layer and channel of the
//! associated elementary stream. Scalability flags indicate which
//! scalability modes apply to the embedded layer.

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

/// Descriptor tag for hierarchy_descriptor.
pub const TAG: u8 = 0x04;
const HEADER_LEN: usize = 2;
const BODY_LEN: u8 = 4;

/// `hierarchy_type(4)` field mask inside the scalability-flags byte: bits
/// `[3:0]`; masks the `Reserved11To14(v)` payload so it cannot bleed into
/// the four scalability flags (r03-W2).
const HIERARCHY_TYPE_MASK: u8 = 0x0F;
/// Default of the 2-bit `reserved` above `hierarchy_layer_index` and above
/// `hierarchy_channel` (H.222.0 Table 2-49): clause 2.1 "reserved" = `1` (all
/// 9 editions 07/1995-08/2023, audit §4 row 7 / §5).
pub const RESERVED_2_DEFAULT: u8 = 0b11;
/// Default of the 1-bit `reserved` between `tref_present_flag` and
/// `hierarchy_embedded_layer_index` (same rule; carved from `reserved(2)` in
/// the 06/2012 edition, the remaining bit stays reserved = `1`).
pub const RESERVED_1_DEFAULT: u8 = 0b1;
const RESERVED_2_MASK: u8 = 0x03;
const RESERVED_1_MASK: u8 = 0x01;

/// Hierarchy type — ISO/IEC 13818-1 Table 2-50.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[cfg_attr(feature = "serde", derive(serde::Serialize))]
#[non_exhaustive]
pub enum HierarchyType {
    /// 0 — Reserved.
    Reserved0,
    /// 1 — Spatial Scalability.
    SpatialScalability,
    /// 2 — SNR Scalability.
    SnrScalability,
    /// 3 — Temporal Scalability.
    TemporalScalability,
    /// 4 — Data partitioning.
    DataPartitioning,
    /// 5 — Extension bitstream.
    ExtensionBitstream,
    /// 6 — Private Stream.
    PrivateStream,
    /// 7 — Multi-view Profile.
    MultiViewProfile,
    /// 8 — Combined Scalability or MV-HEVC sub-partition.
    CombinedScalabilityOrMvHevc,
    /// 9 — MVC video sub-bitstream or MVCD video sub-bitstream.
    MvcOrMvcdVideoSubBitstream,
    /// 10 — Auxiliary picture layer (Annex F of Rec. ITU-T H.265).
    AuxiliaryPictureLayer,
    /// 11–14 — Reserved.
    Reserved11To14(u8),
    /// 15 — Base layer or MVC base view sub-bitstream or …
    BaseLayerOrMvcBaseView,
}

impl HierarchyType {
    /// Construct from a raw byte; unknown values preserve the value
    /// for byte-identical round-trip.
    ///
    /// `hierarchy_type` is a 4-bit wire field; any value over 15 is masked
    /// to its low 4 bits rather than panicking (r03-W4: this used to
    /// `unreachable!()` on such a value, a public-API panic reachable by
    /// any caller that passes an unmasked byte).
    #[must_use]
    pub fn from_u8(v: u8) -> Self {
        match v & 0x0F {
            0 => Self::Reserved0,
            1 => Self::SpatialScalability,
            2 => Self::SnrScalability,
            3 => Self::TemporalScalability,
            4 => Self::DataPartitioning,
            5 => Self::ExtensionBitstream,
            6 => Self::PrivateStream,
            7 => Self::MultiViewProfile,
            8 => Self::CombinedScalabilityOrMvHevc,
            9 => Self::MvcOrMvcdVideoSubBitstream,
            10 => Self::AuxiliaryPictureLayer,
            v @ 11..=14 => Self::Reserved11To14(v),
            15 => Self::BaseLayerOrMvcBaseView,
            _ => unreachable!("v & 0x0F is always <= 15"),
        }
    }

    /// Return the raw byte value.
    #[must_use]
    pub const fn to_u8(self) -> u8 {
        match self {
            Self::Reserved0 => 0,
            Self::SpatialScalability => 1,
            Self::SnrScalability => 2,
            Self::TemporalScalability => 3,
            Self::DataPartitioning => 4,
            Self::ExtensionBitstream => 5,
            Self::PrivateStream => 6,
            Self::MultiViewProfile => 7,
            Self::CombinedScalabilityOrMvHevc => 8,
            Self::MvcOrMvcdVideoSubBitstream => 9,
            Self::AuxiliaryPictureLayer => 10,
            Self::Reserved11To14(v) => v,
            Self::BaseLayerOrMvcBaseView => 15,
        }
    }

    /// Returns a human-readable spec name for this value.
    #[must_use]
    pub fn name(self) -> &'static str {
        match self {
            Self::Reserved0 => "reserved",
            Self::SpatialScalability => "Spatial Scalability",
            Self::SnrScalability => "SNR Scalability",
            Self::TemporalScalability => "Temporal Scalability",
            Self::DataPartitioning => "Data partitioning",
            Self::ExtensionBitstream => "Extension bitstream",
            Self::PrivateStream => "Private Stream",
            Self::MultiViewProfile => "Multi-view Profile",
            Self::CombinedScalabilityOrMvHevc => "Combined Scalability or MV-HEVC sub-partition",
            Self::MvcOrMvcdVideoSubBitstream => {
                "MVC video sub-bitstream or MVCD video sub-bitstream"
            }
            Self::AuxiliaryPictureLayer => {
                "Auxiliary picture layer as defined in Annex F of Rec. ITU-T H.265 | ISO/IEC 23008-2"
            }
            Self::Reserved11To14(_) => "reserved",
            Self::BaseLayerOrMvcBaseView => {
                "Base layer or MVC base view sub-bitstream or AVC video sub-bitstream of MVC or HEVC temporal video sub-bitstream or HEVC base sub-partition or Base layer of MVCD base view sub-bitstream or AVC video sub-bitstream of MVCD or VVC temporal video sub-bitstream or EVC temporal video sub-bitstream"
            }
        }
    }
}
broadcast_common::impl_spec_display!(HierarchyType, Reserved11To14);

/// Hierarchy Descriptor.
#[derive(Debug, Clone, PartialEq, Eq)]
#[cfg_attr(feature = "serde", derive(serde::Serialize))]
#[cfg_attr(feature = "yoke", derive(yoke::Yokeable))]
#[non_exhaustive]
pub struct HierarchyDescriptor {
    /// No view scalability flag.
    pub no_view_scalability_flag: bool,
    /// No temporal scalability flag.
    pub no_temporal_scalability_flag: bool,
    /// No spatial scalability flag.
    pub no_spatial_scalability_flag: bool,
    /// No quality scalability flag.
    pub no_quality_scalability_flag: bool,
    /// Hierarchy type (Table 2-50).
    pub hierarchy_type: HierarchyType,
    /// Hierarchy layer index.
    pub hierarchy_layer_index: u8,
    /// Tref present flag.
    pub tref_present_flag: bool,
    /// Hierarchy embedded layer index.
    pub hierarchy_embedded_layer_index: u8,
    /// Hierarchy channel.
    pub hierarchy_channel: u8,
    /// `reserved(2)` above `hierarchy_layer_index` (2 bits, right-aligned).
    /// Captured on parse, re-emitted verbatim; defaults to
    /// [`RESERVED_2_DEFAULT`].
    pub reserved_layer_index: u8,
    /// `reserved(1)` after `tref_present_flag` (1 bit, right-aligned).
    /// Captured on parse, re-emitted verbatim; defaults to
    /// [`RESERVED_1_DEFAULT`].
    pub reserved_embedded: u8,
    /// `reserved(2)` above `hierarchy_channel` (2 bits, right-aligned).
    /// Captured on parse, re-emitted verbatim; defaults to
    /// [`RESERVED_2_DEFAULT`].
    pub reserved_channel: u8,
}

impl HierarchyDescriptor {
    /// Build with the identifying fields; the four `no_*_scalability_flag`s
    /// and `tref_present_flag` clear and the spec-default reserved bits. Set
    /// the flag fields directly.
    #[must_use]
    pub const fn new(
        hierarchy_type: HierarchyType,
        hierarchy_layer_index: u8,
        hierarchy_embedded_layer_index: u8,
        hierarchy_channel: u8,
    ) -> Self {
        Self {
            no_view_scalability_flag: false,
            no_temporal_scalability_flag: false,
            no_spatial_scalability_flag: false,
            no_quality_scalability_flag: false,
            hierarchy_type,
            hierarchy_layer_index,
            tref_present_flag: false,
            hierarchy_embedded_layer_index,
            hierarchy_channel,
            reserved_layer_index: RESERVED_2_DEFAULT,
            reserved_embedded: RESERVED_1_DEFAULT,
            reserved_channel: RESERVED_2_DEFAULT,
        }
    }
}

impl Default for HierarchyDescriptor {
    fn default() -> Self {
        Self::new(HierarchyType::Reserved0, 0, 0, 0)
    }
}

impl<'a> Parse<'a> for HierarchyDescriptor {
    type Error = crate::error::Error;

    fn parse(bytes: &'a [u8]) -> Result<Self> {
        let body = descriptor_body(
            bytes,
            TAG,
            "HierarchyDescriptor",
            "unexpected tag for hierarchy_descriptor",
        )?;
        if body.len() != BODY_LEN as usize {
            return Err(Error::InvalidDescriptor {
                tag: TAG,
                reason: "hierarchy_descriptor length must equal 4",
            });
        }
        let b0 = body[0];
        let no_view_scalability_flag = (b0 & 0x80) != 0;
        let no_temporal_scalability_flag = (b0 & 0x40) != 0;
        let no_spatial_scalability_flag = (b0 & 0x20) != 0;
        let no_quality_scalability_flag = (b0 & 0x10) != 0;
        let hierarchy_type = HierarchyType::from_u8(b0 & 0x0F);
        let b1 = body[1];
        let hierarchy_layer_index = b1 & 0x3F;
        let b2 = body[2];
        let tref_present_flag = (b2 & 0x80) != 0;
        let hierarchy_embedded_layer_index = b2 & 0x3F;
        let b3 = body[3];
        let hierarchy_channel = b3 & 0x3F;
        Ok(Self {
            no_view_scalability_flag,
            no_temporal_scalability_flag,
            no_spatial_scalability_flag,
            no_quality_scalability_flag,
            hierarchy_type,
            hierarchy_layer_index,
            tref_present_flag,
            hierarchy_embedded_layer_index,
            hierarchy_channel,
            reserved_layer_index: (b1 >> 6) & RESERVED_2_MASK,
            reserved_embedded: (b2 >> 6) & RESERVED_1_MASK,
            reserved_channel: (b3 >> 6) & RESERVED_2_MASK,
        })
    }
}

impl Serialize for HierarchyDescriptor {
    type Error = crate::error::Error;

    fn serialized_len(&self) -> usize {
        HEADER_LEN + (BODY_LEN as 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(),
            });
        }
        buf[0] = TAG;
        buf[1] = BODY_LEN;
        buf[HEADER_LEN] = ((self.no_view_scalability_flag as u8) << 7)
            | ((self.no_temporal_scalability_flag as u8) << 6)
            | ((self.no_spatial_scalability_flag as u8) << 5)
            | ((self.no_quality_scalability_flag as u8) << 4)
            | broadcast_common::len::fit_mask(
                self.hierarchy_type.to_u8(),
                HIERARCHY_TYPE_MASK,
                "hierarchy_type",
            )?;
        buf[HEADER_LEN + 1] = (broadcast_common::len::fit_mask(
            self.reserved_layer_index,
            RESERVED_2_MASK,
            "reserved_layer_index",
        )? << 6)
            | broadcast_common::len::fit_mask(
                self.hierarchy_layer_index,
                0x3F,
                "hierarchy_layer_index",
            )?;
        buf[HEADER_LEN + 2] = ((self.tref_present_flag as u8) << 7)
            | (broadcast_common::len::fit_mask(
                self.reserved_embedded,
                RESERVED_1_MASK,
                "reserved_embedded",
            )? << 6)
            | broadcast_common::len::fit_mask(
                self.hierarchy_embedded_layer_index,
                0x3F,
                "hierarchy_embedded_layer_index",
            )?;
        buf[HEADER_LEN + 3] = (broadcast_common::len::fit_mask(
            self.reserved_channel,
            RESERVED_2_MASK,
            "reserved_channel",
        )? << 6)
            | broadcast_common::len::fit_mask(self.hierarchy_channel, 0x3F, "hierarchy_channel")?;
        Ok(len)
    }
}
impl crate::traits::DescriptorDef<'_> for HierarchyDescriptor {
    const TAG: u8 = TAG;
    const NAME: &'static str = "HIERARCHY";
}

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

    #[test]
    fn parse() {
        let bytes = [
            TAG,
            4,
            0b1010_0011, // view=1, temporal=0, spatial=1, quality=0, type=3
            0x05,        // reserved(2) | hierarchy_layer_index(6)
            0b1001_0011, // tref=1, reserved=0(1b), embedded=19 (6b=010011)
            0b00_110010, // reserved(2) | channel(6)
        ];
        let d = HierarchyDescriptor::parse(&bytes).unwrap();
        assert!(d.no_view_scalability_flag);
        assert!(!d.no_temporal_scalability_flag);
        assert!(d.no_spatial_scalability_flag);
        assert!(!d.no_quality_scalability_flag);
        assert_eq!(d.hierarchy_type, HierarchyType::TemporalScalability);
        assert_eq!(d.hierarchy_layer_index, 5);
        assert!(d.tref_present_flag);
        assert_eq!(d.hierarchy_embedded_layer_index, 19);
        assert_eq!(d.hierarchy_channel, 50);
    }

    #[test]
    fn serialize_round_trip() {
        let mut d = HierarchyDescriptor::new(HierarchyType::DataPartitioning, 42, 7, 63);
        d.no_temporal_scalability_flag = true;
        d.no_quality_scalability_flag = true;
        let mut buf = vec![0u8; d.serialized_len()];
        d.serialize_into(&mut buf).unwrap();
        let reparsed = HierarchyDescriptor::parse(&buf).unwrap();
        assert_eq!(d, reparsed);
    }

    /// Regression for r03-W4: `from_u8` used to `unreachable!()` (panic) for
    /// any value over 15, even though it's a public function a caller can
    /// call with an unmasked byte.
    #[test]
    fn from_u8_masks_rather_than_panics_above_4_bits() {
        for v in 16u8..=255 {
            assert_eq!(HierarchyType::from_u8(v), HierarchyType::from_u8(v & 0x0F));
        }
    }

    #[test]
    fn hierarchy_type_round_trip() {
        for v in 0u8..=15 {
            assert_eq!(
                HierarchyType::from_u8(v).to_u8(),
                v,
                "round-trip failed for {v:#04x}"
            );
        }
    }

    #[test]
    fn hierarchy_type_name() {
        assert_eq!(
            HierarchyType::SpatialScalability.name(),
            "Spatial Scalability"
        );
        assert_eq!(
            HierarchyType::BaseLayerOrMvcBaseView.name(),
            "Base layer or MVC base view sub-bitstream or AVC video sub-bitstream of MVC or HEVC temporal video sub-bitstream or HEVC base sub-partition or Base layer of MVCD base view sub-bitstream or AVC video sub-bitstream of MVCD or VVC temporal video sub-bitstream or EVC temporal video sub-bitstream"
        );
    }

    #[test]
    fn parse_rejects_wrong_tag() {
        let err = HierarchyDescriptor::parse(&[0x05, 4, 0, 0, 0, 0]).unwrap_err();
        assert!(matches!(err, Error::InvalidDescriptor { tag: 0x05, .. }));
    }

    #[test]
    fn parse_rejects_wrong_length() {
        let err = HierarchyDescriptor::parse(&[TAG, 3, 0, 0, 0]).unwrap_err();
        assert!(matches!(err, Error::InvalidDescriptor { tag: TAG, .. }));
    }

    #[test]
    fn serialize_rejects_small_buffer() {
        let d = HierarchyDescriptor::default();
        let mut tiny = vec![0u8; 3];
        let err = d.serialize_into(&mut tiny).unwrap_err();
        assert!(matches!(err, Error::OutputBufferTooSmall { .. }));
    }

    /// H.222.0 Table 2-49. All three reserved regions are preserved verbatim.
    #[test]
    fn hierarchy_reserved_preserved() {
        for r_layer in 0u8..=3 {
            for r_emb in 0u8..=1 {
                for r_chan in 0u8..=3 {
                    let bytes = [
                        TAG,
                        4,
                        0b1010_0011,
                        (r_layer << 6) | 0x05,
                        0x80 | (r_emb << 6) | 0x13,
                        (r_chan << 6) | 0x32,
                    ];
                    let d = HierarchyDescriptor::parse(&bytes).unwrap();
                    assert_eq!(
                        (
                            d.reserved_layer_index,
                            d.reserved_embedded,
                            d.reserved_channel
                        ),
                        (r_layer, r_emb, r_chan)
                    );
                    let mut out = vec![0u8; d.serialized_len()];
                    d.serialize_into(&mut out).unwrap();
                    assert_eq!(out, bytes);
                }
            }
        }
    }

    #[test]
    fn hierarchy_default_is_spec_value() {
        let d = HierarchyDescriptor::new(HierarchyType::TemporalScalability, 5, 19, 50);
        let mut out = vec![0u8; d.serialized_len()];
        d.serialize_into(&mut out).unwrap();
        assert_eq!(out, [TAG, 4, 0b0000_0011, 0xC5, 0x53, 0xF2]);
    }
}