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
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
//! AVS2_audio_descriptor — T/AI 109.7-2024 clause 8.2.3.4 (Table 10), tag
//! `0xD3` (211), carried in the PMT ES_info loop of an AVS2 audio elementary
//! stream (`stream_type` 0xD3, see [`crate::tables::pmt::StreamType::Avs2Audio`]).
//!
//! Private descriptor: T/AI 109.7 clause 8.2.3.3 uses a `registration_descriptor`
//! with `format_identifier` 'AVSA' (0x41565341); the registry also accepts a
//! private_data_specifier 'AVSA'. Enable it with
//! [`crate::descriptors::DescriptorRegistry::with_avs2_audio`].
//!
//! ```text
//! descriptor_tag(8)=0xD3 descriptor_length(8)
//! num_channels(8)
//! sample_rate_index(4) avs_version_flag(1) text_present_flag(1) language_present_flag(1) reserved(1)='0'
//! if text_present_flag:     text_length(8) text[text_length](16 each, UCS-2)
//! if language_present_flag: language(24)
//! if avs_version_flag:
//!   audio_codec_id(4) anc_data_index(1) coding_profile(3)
//!   if audio_codec_id==0: bitrate_index(4) bitstream_type(1) reserved(3) raw_frame_length(16)
//!   resolution(2) reserved(6)
//!   if anc_data_index: anc_data_block()
//! addition_info[N](8)
//! ```
//!
//! `anc_data_block()` is defined in GB/T 33475.3-2018 Annex A.2, which is not
//! vendored, so its length is unknown: the bytes following the version block
//! (the `anc_data_block()` when `anc_data_index` is set, then `addition_info`)
//! are kept undivided in [`Avs2AudioDescriptor::trailing`]. The `reserved` bits
//! are captured on parse (the one after `language_present_flag` is printed as
//! `'0'`; the others state no value and default to all ones when hand-built).

use super::{descriptor_body, write_descriptor_header};
use crate::descriptors::lang_text::LANG_LEN;
use crate::error::{Error, Result};
use crate::text::LangCode;
use alloc::vec::Vec;
use broadcast_core::len::{fit_bits, fit_u8, need_out};
use broadcast_core::reserved::{ReservedOnes, ReservedZero};
use broadcast_core::{Parse, Serialize};

/// Descriptor tag for AVS2_audio_descriptor (T/AI 109.7 Table 9: 211).
pub const TAG: u8 = 0xD3;
const HEADER_LEN: usize = 2;
/// Width of `reserved` in the codec-0 block.
pub const RESERVED3_BITS: u32 = 3;
/// Width of `reserved` in the version block.
const RESERVED6_BITS: u32 = 6;
const RESERVED6_ONES: ReservedOnes<RESERVED6_BITS> = ReservedOnes::<RESERVED6_BITS>::FILL;
const RESERVED3_ONES: ReservedOnes<RESERVED3_BITS> = ReservedOnes::<RESERVED3_BITS>::FILL;
/// Shift between the two nibbles of a packed byte.
const NIBBLE_SHIFT: u8 = 4;
/// Width of a 4-bit field, bits.
const NIBBLE_BITS: u32 = 4;
/// Width of one 16-bit text character, bytes.
const TEXT_CHAR_LEN: usize = 2;
/// Mask of `avs_version_flag` in the flags byte.
const AVS_VERSION_FLAG_MASK: u8 = 0x08;
const AVS_VERSION_FLAG_SHIFT: u8 = 3;
/// Mask of `text_present` in the flags byte.
const TEXT_PRESENT_MASK: u8 = 0x04;
const TEXT_PRESENT_SHIFT: u8 = 2;
/// Mask of `language_present` in the flags byte.
const LANGUAGE_PRESENT_MASK: u8 = 0x02;
const LANGUAGE_PRESENT_SHIFT: u8 = 1;
/// Mask of `anc_data_index` in the version byte.
const ANC_DATA_INDEX_MASK: u8 = 0x08;
const ANC_DATA_INDEX_SHIFT: u8 = 3;
/// Mask of `coding_profile` in the version byte.
const CODING_PROFILE_MASK: u8 = 0x07;
const CODING_PROFILE_BITS: u32 = 3;
/// Mask of `bitstream_type` in the codec-0 byte.
const BITSTREAM_TYPE_MASK: u8 = 0x08;
const BITSTREAM_TYPE_SHIFT: u8 = 3;
/// Shift of `resolution` in its byte.
const RESOLUTION_SHIFT: u8 = 6;
const RESOLUTION_BITS: u32 = 2;
/// Highest `audio_codec_id` value.
const AUDIO_CODEC_ID_MAX: u8 = 15;

/// `audio_codec_id == 0` body of the version block.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[cfg_attr(feature = "serde", derive(serde::Serialize))]
#[non_exhaustive]
pub struct Avs2AudioCodec0 {
    /// `bitrate_index` (4 bits, GB/T 33475.3 Annex A.2).
    pub bitrate_index: u8,
    /// `bitstream_type` (1 bit).
    pub bitstream_type: bool,
    /// `reserved` (3 bits).
    pub reserved: ReservedOnes<RESERVED3_BITS>,
    /// `raw_frame_length` (16 bits).
    pub raw_frame_length: u16,
}

impl Avs2AudioCodec0 {
    /// Build with the all-ones reserved default.
    #[must_use]
    pub const fn new(bitrate_index: u8, bitstream_type: bool, raw_frame_length: u16) -> Self {
        Self {
            bitrate_index,
            bitstream_type,
            reserved: RESERVED3_ONES,
            raw_frame_length,
        }
    }
}

/// The block present iff `avs_version_flag == 1`.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[cfg_attr(feature = "serde", derive(serde::Serialize))]
#[non_exhaustive]
pub struct Avs2AudioVersion {
    /// `audio_codec_id` (4 bits).
    pub audio_codec_id: u8,
    /// `anc_data_index` (1 bit): an `anc_data_block()` follows in `trailing`.
    pub anc_data_index: bool,
    /// `coding_profile` (3 bits).
    pub coding_profile: u8,
    /// Present iff `audio_codec_id == 0`.
    pub codec0: Option<Avs2AudioCodec0>,
    /// `resolution` (2 bits).
    pub resolution: u8,
    /// `reserved` (6 bits) after `resolution`.
    pub reserved: ReservedOnes<6>,
}

impl Avs2AudioVersion {
    /// Build with the all-ones reserved default.
    #[must_use]
    pub const fn new(
        audio_codec_id: u8,
        anc_data_index: bool,
        coding_profile: u8,
        codec0: Option<Avs2AudioCodec0>,
        resolution: u8,
    ) -> Self {
        Self {
            audio_codec_id,
            anc_data_index,
            coding_profile,
            codec0,
            resolution,
            reserved: RESERVED6_ONES,
        }
    }
}

/// AVS2_audio_descriptor (T/AI 109.7-2024 Table 10).
#[derive(Debug, Clone, PartialEq, Eq)]
#[cfg_attr(feature = "serde", derive(serde::Serialize))]
#[non_exhaustive]
pub struct Avs2AudioDescriptor {
    /// `num_channels` (8 bits).
    pub num_channels: u8,
    /// `sample_rate_index` (4 bits, GB/T 33475.3 Annex A.2).
    pub sample_rate_index: u8,
    /// `reserved` (1 bit) after `language_present_flag`; printed as `'0'`.
    pub reserved: ReservedZero<1>,
    /// `text[]`: 16-bit Unicode units, present iff `text_present_flag`.
    pub text: Option<Vec<u16>>,
    /// `language` (24 bits, GB/T 4880.2-2000), present iff `language_present_flag`.
    pub language: Option<LangCode>,
    /// The version block, present iff `avs_version_flag`.
    pub version: Option<Avs2AudioVersion>,
    /// Bytes after the version block: `anc_data_block()` (when `anc_data_index`
    /// is set; GB/T 33475.3 Annex A.2, length unknown here) followed by the
    /// optional `addition_info[]`.
    pub trailing: Vec<u8>,
}

impl Avs2AudioDescriptor {
    /// Build a descriptor with no text, language, version block or trailer.
    #[must_use]
    pub const fn new(num_channels: u8, sample_rate_index: u8) -> Self {
        Self {
            num_channels,
            sample_rate_index,
            reserved: ReservedZero::<1>::FILL,
            text: None,
            language: None,
            version: None,
            trailing: Vec::new(),
        }
    }
}

struct Cursor<'a> {
    body: &'a [u8],
    pos: usize,
}

impl Cursor<'_> {
    fn take(&mut self, n: usize) -> Result<&[u8]> {
        let end = self.pos + n;
        let s = self.body.get(self.pos..end).ok_or(Error::BufferTooShort(
            broadcast_core::error::BufferTooShort::new(end, self.body.len(), "Avs2AudioDescriptor"),
        ))?;
        self.pos = end;
        Ok(s)
    }
    fn u8(&mut self) -> Result<u8> {
        Ok(self.take(1)?[0])
    }
}

impl<'a> Parse<'a> for Avs2AudioDescriptor {
    type Error = crate::error::Error;
    fn parse(bytes: &'a [u8]) -> Result<Self> {
        let body = descriptor_body(
            bytes,
            TAG,
            "Avs2AudioDescriptor",
            "unexpected tag for AVS2_audio_descriptor",
        )?;
        let mut c = Cursor { body, pos: 0 };
        let num_channels = c.u8()?;
        let b1 = c.u8()?;
        let avs_version_flag = b1 & AVS_VERSION_FLAG_MASK != 0;
        let text_present = b1 & TEXT_PRESENT_MASK != 0;
        let language_present = b1 & LANGUAGE_PRESENT_MASK != 0;
        let text = if text_present {
            let n = usize::from(c.u8()?);
            let raw = c.take(n * TEXT_CHAR_LEN)?;
            Some(
                raw.chunks_exact(TEXT_CHAR_LEN)
                    .map(|p| u16::from_be_bytes([p[0], p[1]]))
                    .collect(),
            )
        } else {
            None
        };
        let language = if language_present {
            let l = c.take(LANG_LEN)?;
            let mut code = [0u8; LANG_LEN];
            code.copy_from_slice(l);
            Some(LangCode::new(code))
        } else {
            None
        };
        let version = if avs_version_flag {
            let v0 = c.u8()?;
            let audio_codec_id = v0 >> NIBBLE_SHIFT;
            let codec0 = if audio_codec_id == 0 {
                let x = c.u8()?;
                let hi = c.u8()?;
                let lo = c.u8()?;
                Some(Avs2AudioCodec0 {
                    bitrate_index: x >> NIBBLE_SHIFT,
                    bitstream_type: x & BITSTREAM_TYPE_MASK != 0,
                    reserved: ReservedOnes::from_bits(u64::from(x)),
                    raw_frame_length: u16::from_be_bytes([hi, lo]),
                })
            } else {
                None
            };
            let r = c.u8()?;
            Some(Avs2AudioVersion {
                audio_codec_id,
                anc_data_index: v0 & ANC_DATA_INDEX_MASK != 0,
                coding_profile: v0 & CODING_PROFILE_MASK,
                codec0,
                resolution: r >> RESOLUTION_SHIFT,
                reserved: ReservedOnes::from_bits(u64::from(r)),
            })
        } else {
            None
        };
        Ok(Self {
            num_channels,
            sample_rate_index: b1 >> NIBBLE_SHIFT,
            reserved: ReservedZero::from_bits(u64::from(b1)),
            text,
            language,
            version,
            trailing: body[c.pos..].to_vec(),
        })
    }
}

impl Avs2AudioDescriptor {
    fn body_bytes(&self) -> Result<Vec<u8>> {
        let mut out = Vec::new();
        out.push(self.num_channels);
        let sri = fit_bits(
            u64::from(self.sample_rate_index),
            NIBBLE_BITS,
            "sample_rate_index",
        )? as u8;
        let rsv = self.reserved.get() as u8;
        out.push(
            (sri << NIBBLE_SHIFT)
                | (u8::from(self.version.is_some()) << AVS_VERSION_FLAG_SHIFT)
                | (u8::from(self.text.is_some()) << TEXT_PRESENT_SHIFT)
                | (u8::from(self.language.is_some()) << LANGUAGE_PRESENT_SHIFT)
                | rsv,
        );
        if let Some(text) = &self.text {
            out.push(fit_u8(text.len(), "text_length")?);
            for u in text {
                out.extend_from_slice(&u.to_be_bytes());
            }
        }
        if let Some(l) = &self.language {
            out.extend_from_slice(&l.get());
        }
        if let Some(v) = &self.version {
            let id = fit_bits(u64::from(v.audio_codec_id), NIBBLE_BITS, "audio_codec_id")? as u8;
            let prof = fit_bits(
                u64::from(v.coding_profile),
                CODING_PROFILE_BITS,
                "coding_profile",
            )? as u8;
            out.push(
                (id << NIBBLE_SHIFT) | (u8::from(v.anc_data_index) << ANC_DATA_INDEX_SHIFT) | prof,
            );
            match (id, &v.codec0) {
                (0, Some(c)) => {
                    let br =
                        fit_bits(u64::from(c.bitrate_index), NIBBLE_BITS, "bitrate_index")? as u8;
                    let rs = c.reserved.get() as u8;
                    out.push(
                        (br << NIBBLE_SHIFT)
                            | (u8::from(c.bitstream_type) << BITSTREAM_TYPE_SHIFT)
                            | rs,
                    );
                    out.extend_from_slice(&c.raw_frame_length.to_be_bytes());
                }
                (0, None) | (1..=AUDIO_CODEC_ID_MAX, Some(_)) => {
                    return Err(Error::ValueOutOfRange {
                        field: "codec0",
                        reason: "present iff audio_codec_id == 0",
                    });
                }
                _ => {}
            }
            let res = fit_bits(u64::from(v.resolution), RESOLUTION_BITS, "resolution")? as u8;
            let rs6 = v.reserved.get() as u8;
            out.push((res << RESOLUTION_SHIFT) | rs6);
        }
        out.extend_from_slice(&self.trailing);
        Ok(out)
    }
}

impl Serialize for Avs2AudioDescriptor {
    type Error = crate::error::Error;
    fn serialized_len(&self) -> usize {
        self.body_bytes()
            .map_or(HEADER_LEN, |b| HEADER_LEN + b.len())
    }

    fn serialize_into(&self, buf: &mut [u8]) -> Result<usize> {
        let body = self.body_bytes()?;
        let len = HEADER_LEN + body.len();
        need_out(buf, len, "Avs2AudioDescriptor")?;
        write_descriptor_header(buf, TAG, body.len())?;
        buf[HEADER_LEN..len].copy_from_slice(&body);
        Ok(len)
    }
}

impl crate::traits::DescriptorDef<'_> for Avs2AudioDescriptor {
    const TAG: u8 = TAG;
    const NAME: &'static str = "AVS2_AUDIO";
}

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

    fn round_trip(bytes: &[u8]) -> Avs2AudioDescriptor {
        let d = Avs2AudioDescriptor::parse(bytes).unwrap();
        let mut out = vec![0u8; d.serialized_len()];
        let n = d.serialize_into(&mut out).unwrap();
        assert_eq!(&out[..n], bytes, "byte-exact round trip");
        d
    }

    /// Table 10, minimal form: only `num_channels`/`sample_rate_index`
    /// (2 bytes, the stated minimum descriptor_length); all flags clear.
    #[test]
    fn minimal_two_byte_form() {
        let bytes = [TAG, 2, 6, 0x20];
        let d = round_trip(&bytes);
        assert_eq!((d.num_channels, d.sample_rate_index), (6, 2));
        assert!(d.text.is_none() && d.language.is_none() && d.version.is_none());
        assert!(d.trailing.is_empty());
    }

    /// All optional parts: text "AB" (2 x UCS-2), language 'chi', version block
    /// with audio_codec_id 0 (bitrate_index 5, bitstream_type 1, raw_frame_length
    /// 0x0400, resolution 1) and addition_info.
    #[test]
    fn full_form_with_version_block() {
        // sri=3, avs_version=1, text=1, lang=1, reserved=0
        let b1 = (3 << 4) | 0b1110;
        let bytes = [
            TAG, 16, 2, b1, 2, 0x00, 0x41, 0x00, 0x42, b'c', b'h', b'i',
            0x02, // codec 0, anc 0, profile 2
            0x5F, 0x04, 0x00, 0x7F, 0xAB,
        ];
        let v = bytes.to_vec();
        let d = round_trip(&v);
        assert_eq!(d.text.as_deref(), Some(&[0x41u16, 0x42][..]));
        assert_eq!(d.language, Some(LangCode::new(*b"chi")));
        let ver = d.version.unwrap();
        assert_eq!((ver.audio_codec_id, ver.coding_profile), (0, 2));
        let c0 = ver.codec0.unwrap();
        assert_eq!(
            (c0.bitrate_index, c0.bitstream_type, c0.raw_frame_length),
            (5, true, 0x0400)
        );
        assert_eq!((ver.resolution, ver.reserved.get()), (1, 0x3F));
        assert_eq!(d.trailing, [0xAB]);
    }

    #[test]
    fn nonzero_codec_id_has_no_codec0_block() {
        // sri=1, version only; audio_codec_id 1, anc 0, profile 3; resolution 2.
        let bytes = [TAG, 5, 2, 0x18, 0x13, 0xBF, 0xEE];
        let d = round_trip(&bytes);
        let ver = d.version.unwrap();
        assert_eq!(ver.audio_codec_id, 1);
        assert!(ver.codec0.is_none());
        assert_eq!(d.trailing, [0xEE]);
    }

    #[test]
    fn rejects_wrong_tag_and_truncation() {
        assert!(matches!(
            Avs2AudioDescriptor::parse(&[0xD2, 2, 6, 0x20]),
            Err(Error::InvalidDescriptor { tag: 0xD2, .. })
        ));
        assert!(matches!(
            Avs2AudioDescriptor::parse(&[TAG, 1, 6]),
            Err(Error::BufferTooShort(..))
        ));
        // text_present but text_length claims more than present
        assert!(matches!(
            Avs2AudioDescriptor::parse(&[TAG, 4, 2, 0x04, 5, 0]),
            Err(Error::BufferTooShort(..))
        ));
        // language_present but no language bytes
        assert!(matches!(
            Avs2AudioDescriptor::parse(&[TAG, 2, 2, 0x02]),
            Err(Error::BufferTooShort(..))
        ));
        // version flag but no version block
        assert!(matches!(
            Avs2AudioDescriptor::parse(&[TAG, 2, 2, 0x08]),
            Err(Error::BufferTooShort(..))
        ));
    }

    #[test]
    fn serialize_rejects_inconsistent_and_overwide_fields() {
        let mut d = Avs2AudioDescriptor::new(2, 16);
        assert!(matches!(
            &(d.serialize_into(&mut [0u8; 8])),
            Err(crate::error::Error::FieldOverflow(_))
        ));
        d.sample_rate_index = 1;
        d.version = Some(Avs2AudioVersion::new(0, false, 1, None, 1));
        assert!(
            matches!(
                &(d.serialize_into(&mut [0u8; 16])),
                Err(crate::error::Error::ValueOutOfRange { .. })
            ),
            "codec id 0 needs codec0"
        );
        d.version = Some(Avs2AudioVersion::new(
            1,
            false,
            1,
            Some(Avs2AudioCodec0::new(1, false, 1)),
            1,
        ));
        assert!(
            matches!(
                &(d.serialize_into(&mut [0u8; 16])),
                Err(crate::error::Error::ValueOutOfRange { .. })
            ),
            "codec0 only for id 0"
        );
        d.version = Some(Avs2AudioVersion::new(1, false, 8, None, 1));
        assert!(matches!(
            &(d.serialize_into(&mut [0u8; 16])),
            Err(crate::error::Error::FieldOverflow(_))
        ));
    }

    /// `serialized_len` must be exactly the count `serialize_into` writes, so
    /// a caller that pre-sizes a buffer with it gets a correct length.
    #[test]
    fn serialized_len_matches_the_bytes_written() {
        let bytes = [
            TAG, 16, 2, 0b1110, 2, 0x00, 0x41, 0x00, 0x42, b'c', b'h', b'i', 0x02, 0x5F, 0x04,
            0x00, 0x7F, 0xAB,
        ];
        let d = Avs2AudioDescriptor::parse(&bytes).unwrap();
        let mut out = vec![0u8; d.serialized_len()];
        let n = d.serialize_into(&mut out).unwrap();
        assert_eq!(d.serialized_len(), n);
        assert_eq!(n, bytes.len());
    }
}