dvb-si 2.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
//! Integration tests for [`dvb_si::tables::AnyTable`] dispatch.
//!
//! Every builder here is self-contained: bytes are constructed from scratch
//! matching the wire format expected by each module's parser.

use dvb_si::tables::AnyTable;

// ── helpers ──────────────────────────────────────────────────────────────────

fn crc32_mpeg2(data: &[u8]) -> u32 {
    dvb_common::crc32_mpeg2::compute(data)
}

/// Append a correct CRC_32 over all bytes already in `v`.
fn push_crc(v: &mut Vec<u8>) {
    let crc = crc32_mpeg2(v);
    v.extend_from_slice(&crc.to_be_bytes());
}

// ── PAT builder ──────────────────────────────────────────────────────────────

fn build_pat(tsid: u16, version: u8, entries: &[(u16, u16)]) -> Vec<u8> {
    let section_length = (5 + entries.len() * 4 + 4) as u16; // ext_hdr(5)+entries+crc(4)
    let mut v = vec![
        0x00u8,
        0xB0 | ((section_length >> 8) as u8 & 0x0F),
        (section_length & 0xFF) as u8,
        (tsid >> 8) as u8,
        (tsid & 0xFF) as u8,
        0xC0 | ((version & 0x1F) << 1) | 0x01,
        0x00,
        0x00,
    ];
    for &(pn, pid) in entries {
        v.extend_from_slice(&pn.to_be_bytes());
        v.push(0xE0 | ((pid >> 8) as u8 & 0x1F));
        v.push((pid & 0xFF) as u8);
    }
    push_crc(&mut v);
    v
}

// ── PMT builder ──────────────────────────────────────────────────────────────

fn build_pmt(program_number: u16, version: u8, pcr_pid: u16) -> Vec<u8> {
    let section_length = (5 + 2 + 2 + 4) as u16; // ext_hdr(5)+pcr_pid(2)+prog_info_len(2)+crc(4)
    let mut v = vec![
        0x02u8,
        0xB0 | ((section_length >> 8) as u8 & 0x0F),
        (section_length & 0xFF) as u8,
        (program_number >> 8) as u8,
        (program_number & 0xFF) as u8,
        0xC0 | ((version & 0x1F) << 1) | 0x01,
        0x00,
        0x00,
        0xE0 | ((pcr_pid >> 8) as u8 & 0x1F),
        (pcr_pid & 0xFF) as u8,
        0xF0, // program_info_length hi nibble
        0x00, // program_info_length = 0
    ];
    push_crc(&mut v);
    v
}

// ── SDT builder ──────────────────────────────────────────────────────────────

fn build_sdt(table_id: u8, tsid: u16, onid: u16) -> Vec<u8> {
    // section_length: ext_hdr(5) + onid(2) + reserved(1) + crc(4) = 12
    let section_length: u16 = 12;
    let mut v = vec![
        table_id,
        0xB0 | ((section_length >> 8) as u8 & 0x0F),
        (section_length & 0xFF) as u8,
        (tsid >> 8) as u8,
        (tsid & 0xFF) as u8,
        0xC0 | 0x01, // version=0, cni=1
        0x00,
        0x00,
        (onid >> 8) as u8,
        (onid & 0xFF) as u8,
        0xFF, // reserved_future_use
    ];
    push_crc(&mut v);
    v
}

// ── EIT builder ──────────────────────────────────────────────────────────────

fn build_eit(table_id: u8, service_id: u16, tsid: u16, onid: u16) -> Vec<u8> {
    // section_length: ext_hdr(5) + tsid(2) + onid(2) + seg_last(1) + last_tid(1) + crc(4) = 15
    let section_length: u16 = 15;
    let mut v = vec![
        table_id,
        0xB0 | ((section_length >> 8) as u8 & 0x0F),
        (section_length & 0xFF) as u8,
        (service_id >> 8) as u8,
        (service_id & 0xFF) as u8,
        0xC0 | 0x01, // version=0, cni=1
        0x00,
        0x00,
        (tsid >> 8) as u8,
        (tsid & 0xFF) as u8,
        (onid >> 8) as u8,
        (onid & 0xFF) as u8,
        0x00,     // segment_last_section_number
        table_id, // last_table_id
    ];
    push_crc(&mut v);
    v
}

// ── TDT builder ──────────────────────────────────────────────────────────────

fn build_tdt() -> Vec<u8> {
    // Short section: table_id(1) + section_syntax(2) + 5 UTC bytes.
    // Section length must equal 5 (UTC_TIME_LEN).
    vec![0x70, 0x70, 0x05, 0xE4, 0x09, 0x12, 0x34, 0x56]
}

// ── TOT builder ──────────────────────────────────────────────────────────────

fn build_tot() -> Vec<u8> {
    // header(3) + UTC(5) + desc_loop_len(2) + crc(4)
    let section_length: u16 = (5 + 2 + 4) as u16;
    let mut v = vec![
        0x73u8,
        0x70 | ((section_length >> 8) as u8 & 0x0F), // SSI=0 per EN 300 468 §5.2.6
        (section_length & 0xFF) as u8,
        0xE4,
        0x09,
        0x12,
        0x34,
        0x56, // UTC time
        0xF0,
        0x00, // descriptor_loop_length = 0
    ];
    push_crc(&mut v);
    v
}

// ── DSM-CC builder ───────────────────────────────────────────────────────────

fn build_dsmcc(table_id: u8) -> Vec<u8> {
    // section_length: ext_hdr(5) + payload(0) + crc(4) = 9
    let section_length: u16 = 9;
    let mut v = vec![
        table_id,
        0xB0 | ((section_length >> 8) as u8 & 0x0F),
        (section_length & 0xFF) as u8,
        0x00,
        0x01,        // extension_id
        0xC0 | 0x01, // version=0, cni=1
        0x00,        // section_number
        0x00,        // last_section_number
    ];
    push_crc(&mut v);
    v
}

// ── ProtectionMessage builder ─────────────────────────────────────────────────

fn build_protection_message() -> Vec<u8> {
    // Minimal auth-message body (from protection_message.rs test):
    // reference (1) + hash (4)
    let reference = [0x01u8];
    let hash = [0xAAu8, 0xBB, 0xCC, 0xDD];
    let mut hashes_loop: Vec<u8> = vec![(1u8 << 4) | (reference.len() as u8)];
    hashes_loop.extend_from_slice(&reference);
    hashes_loop.extend_from_slice(&hash);
    let loop_len = hashes_loop.len();

    let mut body: Vec<u8> = vec![
        0x00,                                  // section_hash_algorithm_identifier
        hash.len() as u8,                      // section_hash_length
        0x01,                                  // signature_algorithm_identifier
        0xF0 | ((loop_len >> 8) as u8 & 0x0F), // reserved | loop_length hi
        (loop_len & 0xFF) as u8,               // loop_length lo
    ];
    body.extend_from_slice(&hashes_loop);
    body.push(2);
    body.extend_from_slice(&[0xDE, 0xAD]); // extension_bytes
    body.push(3);
    body.extend_from_slice(&[0x11, 0x22, 0x33]); // key identifier
    body.extend_from_slice(&[0x90, 0x91, 0x92, 0x93, 0x94, 0x95]); // signature

    let section_length = (5 + body.len() + 4) as u16; // ext_hdr(5) + body + crc(4)
    let mut v = vec![
        0x7Bu8,
        0xB0 | ((section_length >> 8) as u8 & 0x0F),
        (section_length & 0xFF) as u8,
        0x00,
        0x01,        // extension (message_id)
        0xC0 | 0x01, // version=0, cni=1
        0x00,        // section_number
        0x00,        // last_section_number
    ];
    v.extend_from_slice(&body);
    push_crc(&mut v);
    v
}

// ─────────────────────────────────────────────────────────────────────────────
// Dispatch tests
// ─────────────────────────────────────────────────────────────────────────────

#[test]
fn dispatch_pat_table_id_0x00() {
    let bytes = build_pat(0x1234, 0, &[(1, 0x0100)]);
    let parsed = AnyTable::parse(&bytes).unwrap();
    assert!(
        matches!(parsed, AnyTable::Pat(_)),
        "expected Pat, got {parsed:?}"
    );
}

#[test]
fn dispatch_pmt_table_id_0x02() {
    let bytes = build_pmt(42, 0, 0x0100);
    let parsed = AnyTable::parse(&bytes).unwrap();
    assert!(
        matches!(parsed, AnyTable::Pmt(_)),
        "expected Pmt, got {parsed:?}"
    );
}

#[test]
fn dispatch_sdt_actual_table_id_0x42() {
    let bytes = build_sdt(0x42, 1, 0x0020);
    let parsed = AnyTable::parse(&bytes).unwrap();
    assert!(
        matches!(parsed, AnyTable::Sdt(_)),
        "expected Sdt, got {parsed:?}"
    );
}

#[test]
fn dispatch_sdt_other_table_id_0x46() {
    let bytes = build_sdt(0x46, 1, 0x0020);
    let parsed = AnyTable::parse(&bytes).unwrap();
    assert!(
        matches!(parsed, AnyTable::Sdt(_)),
        "expected Sdt (other), got {parsed:?}"
    );
}

#[test]
fn dispatch_eit_pf_actual_0x4e() {
    let bytes = build_eit(0x4E, 100, 1, 0x0020);
    let parsed = AnyTable::parse(&bytes).unwrap();
    assert!(
        matches!(parsed, AnyTable::Eit(_)),
        "expected Eit (p/f actual), got {parsed:?}"
    );
}

#[test]
fn dispatch_eit_schedule_segment_0x50() {
    let bytes = build_eit(0x50, 100, 1, 0x0020);
    let parsed = AnyTable::parse(&bytes).unwrap();
    assert!(
        matches!(parsed, AnyTable::Eit(_)),
        "expected Eit (schedule 0x50), got {parsed:?}"
    );
}

#[test]
fn dispatch_tdt_short_section_0x70() {
    let bytes = build_tdt();
    let parsed = AnyTable::parse(&bytes).unwrap();
    assert!(
        matches!(parsed, AnyTable::Tdt(_)),
        "expected Tdt, got {parsed:?}"
    );
}

#[test]
fn dispatch_tot_0x73() {
    let bytes = build_tot();
    let parsed = AnyTable::parse(&bytes).unwrap();
    assert!(
        matches!(parsed, AnyTable::Tot(_)),
        "expected Tot, got {parsed:?}"
    );
}

#[test]
fn dispatch_dsmcc_0x3b() {
    let bytes = build_dsmcc(0x3B);
    let parsed = AnyTable::parse(&bytes).unwrap();
    assert!(
        matches!(parsed, AnyTable::DsmccSection(_)),
        "expected DsmccSection, got {parsed:?}"
    );
}

/// 0x3E is routed to DsmccSection (NOT MpeDatagram) by the default dispatcher.
#[test]
fn dispatch_0x3e_routes_to_dsmcc_not_mpe() {
    let bytes = build_dsmcc(0x3E);
    let parsed = AnyTable::parse(&bytes).unwrap();
    assert!(
        matches!(parsed, AnyTable::DsmccSection(_)),
        "0x3E should dispatch to DsmccSection, got {parsed:?}"
    );
    // Must NOT be MpeDatagram via the default dispatcher.
    assert!(
        !matches!(parsed, AnyTable::MpeDatagram(_)),
        "0x3E must not auto-dispatch to MpeDatagram"
    );
}

#[test]
fn dispatch_protection_message_0x7b() {
    let bytes = build_protection_message();
    let parsed = AnyTable::parse(&bytes).unwrap();
    assert!(
        matches!(parsed, AnyTable::ProtectionMessage(_)),
        "expected ProtectionMessage, got {parsed:?}"
    );
}

#[test]
fn dispatch_unknown_table_id_0x90() {
    // 0x90 is not defined; should produce Unknown.
    let bytes = [0x90u8, 0x01, 0x00]; // minimal: header + 1 section_length byte
    let parsed = AnyTable::parse(&bytes).unwrap();
    match parsed {
        AnyTable::Unknown { table_id, raw } => {
            assert_eq!(table_id, 0x90);
            assert_eq!(raw, &[0x90u8, 0x01, 0x00]);
        }
        other => panic!("expected Unknown, got {other:?}"),
    }
}

#[test]
fn dispatch_empty_input_returns_buffer_too_short() {
    let err = AnyTable::parse(&[]).unwrap_err();
    assert!(
        matches!(err, dvb_si::error::Error::BufferTooShort { .. }),
        "expected BufferTooShort, got {err:?}"
    );
}

/// DISPATCHED_RANGES must be contiguous (none overlap). The drift test in the
/// macro already checks this; this is an integration-level sanity check.
#[test]
fn dispatched_ranges_are_sorted_and_disjoint() {
    let ranges = AnyTable::DISPATCHED_RANGES;
    // Each range must be well-formed (lo <= hi).
    for &(lo, hi) in ranges {
        assert!(lo <= hi, "malformed range ({lo:#04x}, {hi:#04x})");
    }
    // Sorted and non-overlapping (same algorithm as the macro-internal test).
    let mut sorted = ranges.to_vec();
    sorted.sort_by_key(|r| r.0);
    for w in sorted.windows(2) {
        let (_, prev_hi) = w[0];
        let (next_lo, _) = w[1];
        assert!(next_lo > prev_hi, "overlapping dispatch ranges: {w:?}");
    }
}

/// `parse_as` bypasses dispatch and lets callers get the typed MPE view for
/// a `0x3E` section.
#[test]
fn parse_as_mpe_datagram_for_0x3e() {
    use dvb_si::tables::mpe::MpeDatagramSection;

    // Build a minimal valid MPE datagram_section (table_id=0x3E).
    // header(3) + extension(9) + payload(0) + trailer(4) = 16 bytes.
    // SSI=0 (private-section framing), private=1, reserved=11.
    let section_length = 9u16 + 4; // extension(9) + trailer(4), no payload
    let mut v = vec![
        0x3Eu8,
        0x70 | ((section_length >> 8) as u8 & 0x0F), // SSI=0, private=1, reserved=11
        (section_length & 0xFF) as u8,
        0xAA, // MAC_address_6 (LSB)
        0xBB, // MAC_address_5
        0xC1, // reserved=11 | payload_sc=0 | address_sc=0 | llc_snap=0 | cni=1
        0x00, // section_number
        0x00, // last_section_number
        0x11, // MAC_address_4
        0x22, // MAC_address_3
        0x33, // MAC_address_2
        0x44, // MAC_address_1 (MSB)
    ];
    // Verbatim checksum (SSI=0 path: trailer bytes are preserved as-is).
    v.extend_from_slice(&[0xDE, 0xAD, 0xBE, 0xEF]);

    let mpe = AnyTable::parse_as::<MpeDatagramSection>(&v).expect("valid MPE section must parse");
    // MAC is reassembled network-order: MAC_1..MAC_6
    assert_eq!(mpe.mac_address, [0x44, 0x33, 0x22, 0x11, 0xBB, 0xAA]);
    assert!(mpe.payload.is_empty());
}

/// Every `TableId` variant maps to a byte covered by `AnyTable::DISPATCHED_RANGES`.
#[test]
fn every_table_id_variant_is_dispatched() {
    let ranges = dvb_si::tables::AnyTable::DISPATCHED_RANGES;
    for b in 0u8..=0xFF {
        if dvb_si::TableId::try_from(b).is_ok() {
            let covered = ranges.iter().any(|&(lo, hi)| b >= lo && b <= hi);
            assert!(
                covered,
                "TableId byte {b:#04x} is a known variant but is not covered by \
                 AnyTable::DISPATCHED_RANGES"
            );
        }
    }
}