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
//! Application Descriptor — ETSI TS 102 809 §5.3.5.3, Table 20
//! (AIT tag 0x00).
//!
//! Carried in the AIT per-application descriptor loop. Lists the
//! application's profile/version triplets, a visibility/service-bound flags
//! byte, a priority, and a list of transport protocol labels.

use crate::descriptors::descriptor_body;
use crate::error::{Error, Result};
use alloc::vec::Vec;
use broadcast_core::len::need_out;
use broadcast_core::reserved::{FieldValue, ReservedOnes};
use broadcast_core::{Parse, Serialize};

/// Descriptor tag for application_descriptor (AIT namespace).
pub const TAG: u8 = 0x00;
const HEADER_LEN: usize = 2;
const PROFILE_ENTRY_LEN: usize = 5;
const FLAGS_LEN: usize = 1;
const PRIORITY_LEN: usize = 1;
/// Offset of `version_major` in a profile entry.
const VERSION_MAJOR_OFFSET: usize = core::mem::size_of::<u16>();
/// Offset of `version_minor` in a profile entry.
const VERSION_MINOR_OFFSET: usize = VERSION_MAJOR_OFFSET + 1;
/// Offset of `version_micro` in a profile entry.
const VERSION_MICRO_OFFSET: usize = VERSION_MINOR_OFFSET + 1;
/// Mask of the 2-bit `visibility` field.
const VISIBILITY_MASK: u8 = 0x03;
/// Width of the visibility field.
const VISIBILITY_BITS: u32 = 2;
/// Mask of `service_bound_flag` in the flags byte.
const SERVICE_BOUND_FLAG_MASK: u8 = 0x80;
const SERVICE_BOUND_FLAG_SHIFT: u8 = 7;
const VISIBILITY_SHIFT: u8 = 5;
/// Width mask of the 5-bit `reserved_future_use` in the flags byte.
pub const RESERVED_FU_BITS: u32 = 5;

/// Spec default of `reserved_future_use(5)` in the flags byte: all ones
/// (TS 102 809 V1.1.1-V1.3.1 Table 20, clause 5.3.3.2; audit §6.3 class A).
pub const RESERVED_FUTURE_USE_DEFAULT: ReservedOnes<RESERVED_FU_BITS> =
    ReservedOnes::<RESERVED_FU_BITS>::FILL;

/// 2-bit visibility field — ETSI TS 102 809 §5.2.6.1 Table 5.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[cfg_attr(feature = "serde", derive(serde::Serialize))]
#[non_exhaustive]
pub enum Visibility {
    /// 0 — not visible to users or applications.
    NotVisibleAll,
    /// 1 — not visible to users, visible to applications.
    NotVisibleUsers,
    /// 2 — reserved_future_use.
    ReservedFutureUse,
    /// 3 — visible to users and applications.
    VisibleAll,
    /// Catch-all for any other 2-bit value (should not occur).
    Other(FieldValue<VISIBILITY_BITS>),
}

impl Visibility {
    /// Decode from the 2-bit wire value.
    #[must_use]
    pub fn from_u8(v: u8) -> Self {
        match v & VISIBILITY_MASK {
            0 => Self::NotVisibleAll,
            1 => Self::NotVisibleUsers,
            2 => Self::ReservedFutureUse,
            3 => Self::VisibleAll,
            other => Self::Other(FieldValue::from_bits(other)),
        }
    }

    /// Encode to the 2-bit wire value.
    #[must_use]
    pub const fn to_u8(self) -> u8 {
        match self {
            Self::NotVisibleAll => 0,
            Self::NotVisibleUsers => 1,
            Self::ReservedFutureUse => 2,
            Self::VisibleAll => 3,
            Self::Other(v) => v.get(),
        }
    }

    /// Spec name.
    #[must_use]
    pub fn name(self) -> &'static str {
        match self {
            Self::NotVisibleAll => "NOT_VISIBLE_ALL",
            Self::NotVisibleUsers => "NOT_VISIBLE_USERS",
            Self::ReservedFutureUse => "reserved_future_use",
            Self::VisibleAll => "VISIBLE_ALL",
            Self::Other(_) => "reserved",
        }
    }
}
broadcast_core::impl_spec_display!(Visibility, Other);

/// One application profile entry — Table 4.
#[derive(Debug, Clone, PartialEq, Eq)]
#[cfg_attr(feature = "serde", derive(serde::Serialize))]
pub struct ApplicationProfile {
    /// 16-bit application profile identifier.
    pub profile: u16,
    /// Major version.
    pub version_major: u8,
    /// Minor version.
    pub version_minor: u8,
    /// Micro version.
    pub version_micro: u8,
}

/// Application Descriptor (AIT tag 0x00).
#[derive(Debug, Clone, PartialEq, Eq)]
#[cfg_attr(feature = "serde", derive(serde::Serialize))]
#[non_exhaustive]
pub struct ApplicationDescriptor {
    /// Profile/version entries.
    pub profiles: Vec<ApplicationProfile>,
    /// 1-bit service_bound_flag.
    pub service_bound_flag: bool,
    /// 2-bit visibility (Table 5).
    pub visibility: Visibility,
    /// `reserved_future_use(5)` after `visibility` (5 bits, right-aligned).
    /// Captured on parse and re-emitted verbatim;
    /// [`ApplicationDescriptor::new`] defaults to
    /// [`RESERVED_FUTURE_USE_DEFAULT`] (`0x1F`).
    pub reserved_future_use: ReservedOnes<RESERVED_FU_BITS>,
    /// Application priority.
    pub application_priority: u8,
    /// Transport protocol labels (one per transport protocol descriptor).
    pub transport_protocol_labels: Vec<u8>,
}

impl ApplicationDescriptor {
    /// Build a descriptor with the spec-default reserved bits.
    #[must_use]
    pub const fn new(
        profiles: Vec<ApplicationProfile>,
        service_bound_flag: bool,
        visibility: Visibility,
        application_priority: u8,
        transport_protocol_labels: Vec<u8>,
    ) -> Self {
        Self {
            profiles,
            service_bound_flag,
            visibility,
            reserved_future_use: RESERVED_FUTURE_USE_DEFAULT,
            application_priority,
            transport_protocol_labels,
        }
    }
}

impl<'a> Parse<'a> for ApplicationDescriptor {
    type Error = crate::error::Error;
    fn parse(bytes: &'a [u8]) -> Result<Self> {
        let body = descriptor_body(
            bytes,
            TAG,
            "ApplicationDescriptor",
            "unexpected tag for application_descriptor",
        )?;
        if body.is_empty() {
            return Err(Error::InvalidDescriptor {
                tag: TAG,
                reason: "application_descriptor body is empty",
            });
        }
        let profiles_length = body[0] as usize;
        let profiles_end = 1 + profiles_length;
        if profiles_end > body.len() {
            return Err(Error::InvalidDescriptor {
                tag: TAG,
                reason: "application_profiles_length runs past descriptor end",
            });
        }
        if !profiles_length.is_multiple_of(PROFILE_ENTRY_LEN) {
            return Err(Error::InvalidDescriptor {
                tag: TAG,
                reason: "application_profiles_length not a multiple of 5",
            });
        }
        let mut profiles = Vec::with_capacity(profiles_length / PROFILE_ENTRY_LEN);
        let mut pos = 1;
        while pos < profiles_end {
            let profile = crate::wire::be_u16(body, pos, "profile")?;
            let version_major = body[pos + VERSION_MAJOR_OFFSET];
            let version_minor = body[pos + VERSION_MINOR_OFFSET];
            let version_micro = body[pos + VERSION_MICRO_OFFSET];
            profiles.push(ApplicationProfile {
                profile,
                version_major,
                version_minor,
                version_micro,
            });
            pos += PROFILE_ENTRY_LEN;
        }
        if profiles_end + FLAGS_LEN + PRIORITY_LEN > body.len() {
            return Err(Error::InvalidDescriptor {
                tag: TAG,
                reason: "flags/priority bytes missing after profiles",
            });
        }
        let flags_byte = body[profiles_end];
        let service_bound_flag = (flags_byte & SERVICE_BOUND_FLAG_MASK) != 0;
        let visibility = Visibility::from_u8((flags_byte >> VISIBILITY_SHIFT) & VISIBILITY_MASK);
        let reserved_future_use = ReservedOnes::from_bits(u64::from(flags_byte));
        let application_priority = body[profiles_end + FLAGS_LEN];
        let labels_start = profiles_end + FLAGS_LEN + PRIORITY_LEN;
        let transport_protocol_labels = body[labels_start..].to_vec();
        Ok(Self {
            profiles,
            service_bound_flag,
            visibility,
            reserved_future_use,
            application_priority,
            transport_protocol_labels,
        })
    }
}

impl Serialize for ApplicationDescriptor {
    type Error = crate::error::Error;
    fn serialized_len(&self) -> usize {
        HEADER_LEN
            + 1
            + self.profiles.len() * PROFILE_ENTRY_LEN
            + FLAGS_LEN
            + PRIORITY_LEN
            + self.transport_protocol_labels.len()
    }

    fn serialize_into(&self, buf: &mut [u8]) -> Result<usize> {
        let profiles_length = self.profiles.len() * PROFILE_ENTRY_LEN;
        if profiles_length > u8::MAX as usize {
            return Err(Error::InvalidDescriptor {
                tag: TAG,
                reason: "application_profiles_length exceeds 255 bytes",
            });
        }
        let len = self.serialized_len();
        let body_len = len - HEADER_LEN;
        if body_len > u8::MAX as usize {
            return Err(Error::InvalidDescriptor {
                tag: TAG,
                reason: "application_descriptor body exceeds 255 bytes",
            });
        }
        need_out(buf, len, "ApplicationDescriptor")?;
        crate::descriptors::write_descriptor_header(buf, TAG, body_len)?;
        buf[HEADER_LEN] = profiles_length as u8;
        let mut pos = HEADER_LEN + 1;
        for p in &self.profiles {
            buf[pos..pos + VERSION_MAJOR_OFFSET].copy_from_slice(&p.profile.to_be_bytes());
            buf[pos + VERSION_MAJOR_OFFSET] = p.version_major;
            buf[pos + VERSION_MINOR_OFFSET] = p.version_minor;
            buf[pos + VERSION_MICRO_OFFSET] = p.version_micro;
            pos += PROFILE_ENTRY_LEN;
        }
        let flags_byte = (u8::from(self.service_bound_flag) << SERVICE_BOUND_FLAG_SHIFT)
            | (broadcast_core::len::fit_mask(
                self.visibility.to_u8(),
                VISIBILITY_MASK,
                "visibility",
            )? << VISIBILITY_SHIFT)
            | self.reserved_future_use.get() as u8;
        buf[pos] = flags_byte;
        buf[pos + 1] = self.application_priority;
        pos += FLAGS_LEN + PRIORITY_LEN;
        for (i, &label) in self.transport_protocol_labels.iter().enumerate() {
            buf[pos + i] = label;
        }
        Ok(len)
    }
}

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

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

    #[test]
    fn visibility_encodes_exactly_the_two_bit_value_it_decodes() {
        for byte in 0..=u8::MAX {
            assert_eq!(Visibility::from_u8(byte).to_u8(), byte & VISIBILITY_MASK);
        }
    }

    /// Body layout: profiles_length(1) + 1 profile(5) + flags(1) + priority(1) + 2 labels(2) = 10.
    fn build_single_profile_two_labels() -> [u8; 12] {
        [
            TAG, 10, // header
            5,  // profiles_length = 1 entry × 5
            0x00, 0x01, // profile = 1
            2, 3, 4,    // major=2, minor=3, micro=4
            0x9F, // service_bound=1, visibility=NOT_VISIBLE_ALL(0), rfu=11111
            0x0A, // priority=10
            0x01, 0x02, // two transport labels
        ]
    }

    #[test]
    fn parse_single_profile_with_labels() {
        let bytes = build_single_profile_two_labels();
        let d = ApplicationDescriptor::parse(&bytes).unwrap();
        assert_eq!(d.profiles.len(), 1);
        assert_eq!(d.profiles[0].profile, 1);
        assert_eq!(d.profiles[0].version_major, 2);
        assert_eq!(d.profiles[0].version_minor, 3);
        assert_eq!(d.profiles[0].version_micro, 4);
        assert!(d.service_bound_flag);
        assert_eq!(d.visibility, Visibility::NotVisibleAll);
        assert_eq!(d.application_priority, 0x0A);
        assert_eq!(d.transport_protocol_labels, [0x01, 0x02]);
    }

    #[test]
    fn parse_visible_all() {
        // Body: profiles_length(1) + 1 profile(5) + flags(1) + priority(1) + 1 label(1) = 9.
        let bytes = [
            TAG, 9, 5, 0x00, 0x10, 1, 0, 0,
            0x6F, // service_bound=0, visibility=VISIBLE_ALL(3), rfu=11111
            0xFF, // priority
            0x42,
        ];
        let d = ApplicationDescriptor::parse(&bytes).unwrap();
        assert!(!d.service_bound_flag);
        assert_eq!(d.visibility, Visibility::VisibleAll);
    }

    #[test]
    fn parse_rejects_short_body() {
        let err = ApplicationDescriptor::parse(&[TAG]).unwrap_err();
        assert!(matches!(err, Error::BufferTooShort(..)));
    }

    #[test]
    fn serialize_round_trip() {
        let d = ApplicationDescriptor::new(
            alloc::vec![ApplicationProfile {
                profile: 0x0010,
                version_major: 1,
                version_minor: 2,
                version_micro: 3,
            }],
            true,
            Visibility::VisibleAll,
            5,
            alloc::vec![0x01],
        );
        let mut buf = vec![0u8; d.serialized_len()];
        d.serialize_into(&mut buf).unwrap();
        let re = ApplicationDescriptor::parse(&buf).unwrap();
        assert_eq!(d, re);
        assert_eq!(buf[0], TAG);
    }

    #[test]
    fn serialize_byte_identical() {
        let bytes = build_single_profile_two_labels();
        let d = ApplicationDescriptor::parse(&bytes).unwrap();
        let mut buf = vec![0u8; d.serialized_len()];
        d.serialize_into(&mut buf).unwrap();
        assert_eq!(buf.as_slice(), &bytes[..]);
    }

    #[test]
    fn visibility_round_trip() {
        for v in [
            Visibility::NotVisibleAll,
            Visibility::NotVisibleUsers,
            Visibility::ReservedFutureUse,
            Visibility::VisibleAll,
        ] {
            assert_eq!(Visibility::from_u8(v.to_u8()), v);
        }
    }

    /// Every `reserved_future_use(5)` value re-serializes byte-identically
    /// (real senders write non-ones here).
    #[test]
    fn reserved_preserved() {
        for r in 0u8..=0x1F {
            let bytes = [TAG, 9, 5, 0x00, 0x10, 1, 0, 0, 0x60 | r, 0x07, 0x42];
            let d = ApplicationDescriptor::parse(&bytes).unwrap();
            assert_eq!(
                d.reserved_future_use,
                ReservedOnes::<RESERVED_FU_BITS>::from_bits(u64::from(r))
            );
            let mut buf = vec![0u8; d.serialized_len()];
            d.serialize_into(&mut buf).unwrap();
            assert_eq!(buf, bytes, "r {r:#x}");
        }
    }

    /// `new()` serializes the spec value (all ones).
    #[test]
    fn default_reserved_is_spec_value() {
        let d =
            ApplicationDescriptor::new(Vec::new(), false, Visibility::VisibleAll, 1, Vec::new());
        let mut buf = vec![0u8; d.serialized_len()];
        d.serialize_into(&mut buf).unwrap();
        assert_eq!(buf, [TAG, 3, 0, 0x7F, 1]);
    }
}