dvb-si 12.1.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
//! Target Region Descriptor — ETSI EN 300 468 §6.4.12 (tag_extension 0x09).
use super::*;
use alloc::vec::Vec;

/// Shift of `reserved_future_use(5)` in the per-entry flags byte.
const ENTRY_RESERVED_SHIFT: u8 = 3;
/// Width mask of the 5-bit `reserved_future_use`.
const ENTRY_RESERVED_MASK: u8 = 0x1F;

/// Spec default of the per-entry `reserved_future_use(5)` ahead of
/// `country_code_flag`: all ones (EN 300 468 Table 156; `reserved` in
/// V1.14.1-V1.16.1, `reserved_future_use` in V1.17.1+, value 1 throughout;
/// audit §6.1 class B).
pub const TARGET_REGION_RESERVED_FUTURE_USE_DEFAULT: u8 = 0x1F;

impl ExtensionBodyDef<'_> for TargetRegion {
    const TAG_EXTENSION: u8 = 0x09;
    const NAME: &'static str = "TARGET_REGION";
}
/// target_region body (Table 156, §6.4.12). The region loop is unfolded.
#[derive(Debug, Clone, PartialEq, Eq)]
#[cfg_attr(feature = "serde", derive(serde::Serialize))]
pub struct TargetRegion {
    /// Leading country_code(24).
    pub country_code: LangCode,
    /// Region entries (the loop).
    pub regions: Vec<TargetRegionEntry>,
}

/// An entry in the target_region_descriptor region loop.
#[derive(Debug, Clone, PartialEq, Eq)]
#[cfg_attr(feature = "serde", derive(serde::Serialize))]
#[non_exhaustive]
pub struct TargetRegionEntry {
    /// `reserved_future_use(5)` ahead of `country_code_flag` (5 bits,
    /// right-aligned). Captured on parse, re-emitted verbatim;
    /// [`TargetRegionEntry::new`] defaults to [`TARGET_REGION_RESERVED_FUTURE_USE_DEFAULT`]
    /// (`0x1F`).
    pub reserved_future_use: u8,
    /// Per-entry country_code(24), present iff country_code_flag==1.
    pub country_code: Option<LangCode>,
    /// region_depth and its region codes.
    pub region_codes: RegionCodes,
}

impl TargetRegionEntry {
    /// Build an entry with the spec-default reserved bits.
    #[must_use]
    pub const fn new(country_code: Option<LangCode>, region_codes: RegionCodes) -> Self {
        Self {
            reserved_future_use: TARGET_REGION_RESERVED_FUTURE_USE_DEFAULT,
            country_code,
            region_codes,
        }
    }
}

/// The `region_depth` field and its associated region codes (Table 156, §6.4.12).
#[derive(Debug, Clone, PartialEq, Eq)]
#[cfg_attr(feature = "serde", derive(serde::Serialize))]
#[non_exhaustive]
pub enum RegionCodes {
    /// region_depth == 0.
    None,
    /// region_depth == 1.
    Primary {
        /// primary_region_code(8).
        primary_region_code: u8,
    },
    /// region_depth == 2.
    PrimarySecondary {
        /// primary_region_code(8).
        primary_region_code: u8,
        /// secondary_region_code(8).
        secondary_region_code: u8,
    },
    /// region_depth == 3.
    Full {
        /// primary_region_code(8).
        primary_region_code: u8,
        /// secondary_region_code(8).
        secondary_region_code: u8,
        /// tertiary_region_code(16).
        tertiary_region_code: u16,
    },
}

impl<'a> Parse<'a> for TargetRegion {
    type Error = crate::error::Error;
    fn parse(sel: &'a [u8]) -> Result<Self> {
        if sel.len() < ISO_639_LEN {
            return Err(Error::BufferTooShort {
                need: ISO_639_LEN,
                have: sel.len(),
                what: "target_region body",
            });
        }
        let country_code = LangCode([sel[0], sel[1], sel[2]]);
        let regions = parse_region_entries(sel, ISO_639_LEN)?;
        Ok(TargetRegion {
            country_code,
            regions,
        })
    }
}

/// Parse the region entry loop (the variable-length sequence of entries
/// starting at byte offset `start` in `sel`). Shared by
/// [`TargetRegion::parse`] and
/// [`ServiceProminence`](super::service_prominence::ServiceProminence)
/// target_region sub-loop parsing.
pub(crate) fn parse_region_entries(sel: &[u8], start: usize) -> Result<Vec<TargetRegionEntry>> {
    let mut regions = Vec::new();
    let mut pos = start;
    while pos < sel.len() {
        let flags = sel[pos];
        pos += 1;
        let reserved_future_use = flags >> ENTRY_RESERVED_SHIFT;
        let country_code_flag = (flags >> 2) & 1;
        let region_depth = flags & 0x03;
        let country_code = if country_code_flag == 1 {
            if pos + ISO_639_LEN > sel.len() {
                return Err(Error::BufferTooShort {
                    need: pos + ISO_639_LEN,
                    have: sel.len(),
                    what: "target_region body",
                });
            }
            let cc = LangCode([sel[pos], sel[pos + 1], sel[pos + 2]]);
            pos += ISO_639_LEN;
            Some(cc)
        } else {
            None
        };
        let region_codes = match region_depth {
            0 => RegionCodes::None,
            1 => {
                if pos >= sel.len() {
                    return Err(Error::BufferTooShort {
                        need: pos + 1,
                        have: sel.len(),
                        what: "target_region body",
                    });
                }
                let primary = sel[pos];
                pos += 1;
                RegionCodes::Primary {
                    primary_region_code: primary,
                }
            }
            2 => {
                if pos + 1 >= sel.len() {
                    return Err(Error::BufferTooShort {
                        need: pos + 2,
                        have: sel.len(),
                        what: "target_region body",
                    });
                }
                let primary = sel[pos];
                let secondary = sel[pos + 1];
                pos += 2;
                RegionCodes::PrimarySecondary {
                    primary_region_code: primary,
                    secondary_region_code: secondary,
                }
            }
            3 => {
                if pos + 3 >= sel.len() {
                    return Err(Error::BufferTooShort {
                        need: pos + 4,
                        have: sel.len(),
                        what: "target_region body",
                    });
                }
                let primary = sel[pos];
                let secondary = sel[pos + 1];
                let (tert_bytes, _) =
                    sel[pos + 2..]
                        .split_first_chunk::<2>()
                        .ok_or(Error::BufferTooShort {
                            need: pos + 4,
                            have: sel.len(),
                            what: "target_region body",
                        })?;
                let tertiary = u16::from_be_bytes(*tert_bytes);
                pos += 4;
                RegionCodes::Full {
                    primary_region_code: primary,
                    secondary_region_code: secondary,
                    tertiary_region_code: tertiary,
                }
            }
            _ => return Err(invalid("target_region: invalid region_depth")),
        };
        regions.push(TargetRegionEntry {
            reserved_future_use,
            country_code,
            region_codes,
        });
    }
    Ok(regions)
}

/// Byte length of the serialized region entry loop (without the leading
/// `country_code` of a `target_region_descriptor` body).
pub(crate) fn region_entries_serialized_len(entries: &[TargetRegionEntry]) -> usize {
    entries
        .iter()
        .map(|r| {
            1 + if r.country_code.is_some() {
                ISO_639_LEN
            } else {
                0
            } + match &r.region_codes {
                RegionCodes::None => 0,
                RegionCodes::Primary { .. } => 1,
                RegionCodes::PrimarySecondary { .. } => 2,
                RegionCodes::Full { .. } => 4,
            }
        })
        .sum()
}

/// Write the region entry loop into `buf` starting at `pos`. Returns the
/// number of bytes written.
pub(crate) fn write_region_entries(
    entries: &[TargetRegionEntry],
    buf: &mut [u8],
    mut pos: usize,
) -> Result<usize> {
    let start = pos;
    for region in entries {
        let depth = match &region.region_codes {
            RegionCodes::None => 0u8,
            RegionCodes::Primary { .. } => 1,
            RegionCodes::PrimarySecondary { .. } => 2,
            RegionCodes::Full { .. } => 3,
        };
        buf[pos] = (broadcast_common::len::fit_mask(
            region.reserved_future_use,
            ENTRY_RESERVED_MASK,
            "reserved_future_use",
        )? << ENTRY_RESERVED_SHIFT)
            | ((region.country_code.is_some() as u8) << 2)
            | depth;
        pos += 1;
        if let Some(cc) = &region.country_code {
            buf[pos..pos + ISO_639_LEN].copy_from_slice(&cc.0);
            pos += ISO_639_LEN;
        }
        match &region.region_codes {
            RegionCodes::None => {}
            RegionCodes::Primary {
                primary_region_code,
            } => {
                buf[pos] = *primary_region_code;
                pos += 1;
            }
            RegionCodes::PrimarySecondary {
                primary_region_code,
                secondary_region_code,
            } => {
                buf[pos] = *primary_region_code;
                buf[pos + 1] = *secondary_region_code;
                pos += 2;
            }
            RegionCodes::Full {
                primary_region_code,
                secondary_region_code,
                tertiary_region_code,
            } => {
                buf[pos] = *primary_region_code;
                buf[pos + 1] = *secondary_region_code;
                buf[pos + 2..pos + 4].copy_from_slice(&tertiary_region_code.to_be_bytes());
                pos += 4;
            }
        }
    }
    Ok(pos - start)
}

impl Serialize for TargetRegion {
    type Error = crate::error::Error;
    fn serialized_len(&self) -> usize {
        ISO_639_LEN + region_entries_serialized_len(&self.regions)
    }
    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[..ISO_639_LEN].copy_from_slice(&self.country_code.0);
        write_region_entries(&self.regions, buf, ISO_639_LEN)?;
        Ok(len)
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::descriptors::extension::test_support::*;
    use crate::descriptors::extension::{ExtensionBody, ExtensionDescriptor};
    use crate::text::LangCode;

    #[test]
    fn parse_target_region_structured() {
        let sel = [b'g', b'b', b'r', 0xF9, 0x12];
        let bytes = wrap(0x09, &sel);
        let d = ExtensionDescriptor::parse(&bytes).unwrap();
        match &d.body {
            ExtensionBody::TargetRegion(b) => {
                assert_eq!(b.country_code, LangCode(*b"gbr"));
                assert_eq!(b.regions.len(), 1);
                assert_eq!(b.regions[0].country_code, None);
                assert_eq!(
                    b.regions[0].region_codes,
                    RegionCodes::Primary {
                        primary_region_code: 0x12
                    }
                );
            }
            other => panic!("expected TargetRegion, got {other:?}"),
        }
        round_trip(&d);
    }

    #[test]
    fn target_region_tsduck_empty() {
        let bytes = from_hex("7f0409666f6f");
        let d = ExtensionDescriptor::parse(&bytes).unwrap();
        match &d.body {
            ExtensionBody::TargetRegion(b) => {
                assert_eq!(b.country_code, LangCode(*b"foo"));
                assert!(b.regions.is_empty());
            }
            other => panic!("expected TargetRegion, got {other:?}"),
        }
        let mut buf = vec![0u8; d.serialized_len()];
        d.serialize_into(&mut buf).unwrap();
        assert_eq!(buf, bytes);
    }

    #[test]
    fn target_region_tsduck_full() {
        let bytes = from_hex("7f1509626172f8fd666f6f12fa3456ff616263789abcde");
        let d = ExtensionDescriptor::parse(&bytes).unwrap();
        match &d.body {
            ExtensionBody::TargetRegion(b) => {
                assert_eq!(b.country_code, LangCode(*b"bar"));
                assert_eq!(b.regions.len(), 4);
                // [0] cc=None, RegionCodes::None
                assert_eq!(b.regions[0].country_code, None);
                assert_eq!(b.regions[0].region_codes, RegionCodes::None);
                // [1] cc=Some("foo"), Primary{primary:0x12}
                assert_eq!(b.regions[1].country_code, Some(LangCode(*b"foo")));
                assert_eq!(
                    b.regions[1].region_codes,
                    RegionCodes::Primary {
                        primary_region_code: 0x12
                    }
                );
                // [2] cc=None, PrimarySecondary{primary:0x34,secondary:0x56}
                assert_eq!(b.regions[2].country_code, None);
                assert_eq!(
                    b.regions[2].region_codes,
                    RegionCodes::PrimarySecondary {
                        primary_region_code: 0x34,
                        secondary_region_code: 0x56,
                    }
                );
                // [3] cc=Some("abc"), Full{primary:0x78,secondary:0x9A,tertiary:0xBCDE}
                assert_eq!(b.regions[3].country_code, Some(LangCode(*b"abc")));
                assert_eq!(
                    b.regions[3].region_codes,
                    RegionCodes::Full {
                        primary_region_code: 0x78,
                        secondary_region_code: 0x9A,
                        tertiary_region_code: 0xBCDE,
                    }
                );
            }
            other => panic!("expected TargetRegion, got {other:?}"),
        }
        let mut buf = vec![0u8; d.serialized_len()];
        d.serialize_into(&mut buf).unwrap();
        assert_eq!(buf, bytes);
    }

    /// Every per-entry `reserved_future_use(5)` value re-serializes
    /// byte-identically (spec value is all ones).
    #[test]
    fn reserved_preserved() {
        for r in 0u8..=0x1F {
            let sel = [b'g', b'b', b'r', (r << 3) | 0x01, 0x12];
            let bytes = wrap(0x09, &sel);
            let d = ExtensionDescriptor::parse(&bytes).unwrap();
            match &d.body {
                ExtensionBody::TargetRegion(b) => assert_eq!(b.regions[0].reserved_future_use, r),
                other => panic!("expected TargetRegion, got {other:?}"),
            }
            let mut buf = vec![0u8; d.serialized_len()];
            d.serialize_into(&mut buf).unwrap();
            assert_eq!(buf, bytes, "r {r:#x}");
        }
    }

    /// `TargetRegionEntry::new` serializes the spec value (all ones).
    #[test]
    fn default_reserved_is_spec_value() {
        let t = TargetRegion {
            country_code: LangCode(*b"gbr"),
            regions: vec![TargetRegionEntry::new(
                None,
                RegionCodes::Primary {
                    primary_region_code: 0x12,
                },
            )],
        };
        let mut buf = vec![0u8; t.serialized_len()];
        t.serialize_into(&mut buf).unwrap();
        assert_eq!(buf, [b'g', b'b', b'r', 0xF9, 0x12]);
    }
}