dvb-ci 0.11.0

DVB Common Interface (EN 50221) — APDU/resource objects, session/transport PDUs, and a CA_PMT builder from a dvb-si PMT.
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
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
//! CA PMT object (`ca_pmt`) — ETSI EN 50221 §8.4.3.4, Table 25 (PDF pp. 30-31).
//!
//! `ca_pmt` (`9F 80 32`, host → app) is a CA-only projection of the MPEG-2 PMT:
//! the host strips every non-CA descriptor and keeps only the `CA_descriptor()`s
//! (ISO/IEC 13818-1 §2.6.16, tag `0x09`) at programme and elementary-stream
//! level, prefixing each surviving descriptor loop with a `ca_pmt_cmd_id` byte.
//!
//! This module carries the surviving CA descriptor loops as their verbatim wire
//! bytes (`&[u8]`); see [`crate::builder`] for the projection from a `dvb-si`
//! `PmtSection`.

use crate::error::{Error, Result};
use crate::reserved::ReservedOnes;
use crate::tag::{self, ApduTag};
use crate::traits::ApduDef;
use alloc::vec::Vec;
use broadcast_common::len::{need_in, need_out};
use broadcast_common::{Parse, Serialize};
use mpeg_ts::pid::Pid;

/// MPEG-2 `CA_descriptor` tag (ISO/IEC 13818-1 §2.6.16); the only descriptor a
/// `ca_pmt` carries.
pub const CA_DESCRIPTOR_TAG: u8 = 0x09;

/// `ca_pmt_list_management` values (Table, p. 31).
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[cfg_attr(feature = "serde", derive(serde::Serialize))]
#[non_exhaustive]
pub enum CaPmtListManagement {
    /// `00` — neither first nor last of the list.
    More,
    /// `01` — first of a new list (replaces previous selections).
    First,
    /// `02` — last of the list.
    Last,
    /// `03` — the list is a single CA PMT.
    Only,
    /// `04` — a newly selected programme; previous selections retained.
    Add,
    /// `05` — a programme already in the list re-sent (version change).
    Update,
    /// Any other value (reserved).
    Reserved(u8),
}

impl CaPmtListManagement {
    /// Decode a `ca_pmt_list_management` byte.
    #[must_use]
    pub fn from_u8(v: u8) -> Self {
        match v {
            0x00 => Self::More,
            0x01 => Self::First,
            0x02 => Self::Last,
            0x03 => Self::Only,
            0x04 => Self::Add,
            0x05 => Self::Update,
            other => Self::Reserved(other),
        }
    }
    /// Wire byte.
    #[must_use]
    pub const fn to_u8(self) -> u8 {
        match self {
            Self::More => 0x00,
            Self::First => 0x01,
            Self::Last => 0x02,
            Self::Only => 0x03,
            Self::Add => 0x04,
            Self::Update => 0x05,
            Self::Reserved(v) => v,
        }
    }
    /// Spec token, or `"reserved"`.
    #[must_use]
    pub fn name(&self) -> &'static str {
        match self {
            Self::More => "more",
            Self::First => "first",
            Self::Last => "last",
            Self::Only => "only",
            Self::Add => "add",
            Self::Update => "update",
            Self::Reserved(_) => "reserved",
        }
    }
}
broadcast_common::impl_spec_display!(CaPmtListManagement, Reserved);

/// `ca_pmt_cmd_id` values (Table, p. 31).
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[cfg_attr(feature = "serde", derive(serde::Serialize))]
#[non_exhaustive]
pub enum CaPmtCmdId {
    /// `01` — application may start descrambling / MMI immediately.
    OkDescrambling,
    /// `02` — application may start MMI but not descrambling yet.
    OkMmi,
    /// `03` — host expects a `ca_pmt_reply`.
    Query,
    /// `04` — host no longer needs this application to descramble.
    NotSelected,
    /// Any other value (RFU).
    Rfu(u8),
}

impl CaPmtCmdId {
    /// Decode a `ca_pmt_cmd_id` byte.
    #[must_use]
    pub fn from_u8(v: u8) -> Self {
        match v {
            0x01 => Self::OkDescrambling,
            0x02 => Self::OkMmi,
            0x03 => Self::Query,
            0x04 => Self::NotSelected,
            other => Self::Rfu(other),
        }
    }
    /// Wire byte.
    #[must_use]
    pub const fn to_u8(self) -> u8 {
        match self {
            Self::OkDescrambling => 0x01,
            Self::OkMmi => 0x02,
            Self::Query => 0x03,
            Self::NotSelected => 0x04,
            Self::Rfu(v) => v,
        }
    }
    /// Spec token, or `"reserved"`.
    #[must_use]
    pub fn name(&self) -> &'static str {
        match self {
            Self::OkDescrambling => "ok_descrambling",
            Self::OkMmi => "ok_mmi",
            Self::Query => "query",
            Self::NotSelected => "not_selected",
            Self::Rfu(_) => "reserved",
        }
    }
}
broadcast_common::impl_spec_display!(CaPmtCmdId, Rfu);

/// One elementary-stream entry in a `ca_pmt`.
#[derive(Debug, Clone, PartialEq, Eq)]
#[cfg_attr(feature = "serde", derive(serde::Serialize))]
pub struct CaPmtStream<'a> {
    /// MPEG-2 `stream_type`.
    pub stream_type: u8,
    /// 13-bit `elementary_PID`.
    pub elementary_pid: Pid,
    /// `ca_pmt_cmd_id` for this ES — present only when the ES has CA info
    /// (i.e. when `ca_descriptors` is non-empty), per the `ES_info_length != 0`
    /// guard in Table 25.
    pub cmd_id: Option<CaPmtCmdId>,
    /// The ES-level `CA_descriptor()` loop, verbatim wire bytes (no `cmd_id`).
    #[cfg_attr(feature = "serde", serde(borrow, with = "super::bytes_serde"))]
    pub ca_descriptors: &'a [u8],
    /// The 3-bit `reserved` field in front of `elementary_PID` as received,
    /// preserved so the object re-serializes byte-for-byte; `0b111` when
    /// hand-built.
    #[cfg_attr(feature = "serde", serde(skip))]
    pub reserved_pid: ReservedOnes<3>,
    /// The 4-bit `reserved` field in front of `ES_info_length` as received
    /// (see [`CaPmtStream::reserved_pid`]); `0b1111` when hand-built.
    #[cfg_attr(feature = "serde", serde(skip))]
    pub reserved_es_info: ReservedOnes<4>,
}

/// `ca_pmt()` object (Table 25).
#[derive(Debug, Clone, PartialEq, Eq)]
#[cfg_attr(feature = "serde", derive(serde::Serialize))]
pub struct CaPmt<'a> {
    /// How the `length_field` was coded on the wire: a non-minimal long form
    /// (e.g. `82 00 09`) is preserved so the object re-serializes
    /// byte-for-byte; [`LengthForm::Minimal`](crate::length::LengthForm::Minimal) for a hand-built value.
    #[cfg_attr(feature = "serde", serde(skip))]
    pub length_form: crate::length::LengthForm,

    /// `ca_pmt_list_management`.
    pub list_management: CaPmtListManagement,
    /// `program_number`.
    pub program_number: u16,
    /// 5-bit `version_number`.
    pub version_number: u8,
    /// `current_next_indicator`.
    pub current_next_indicator: bool,
    /// Programme-level `ca_pmt_cmd_id` — present only when there is programme-level
    /// CA info (`program_info_length != 0`).
    pub cmd_id: Option<CaPmtCmdId>,
    /// Programme-level `CA_descriptor()` loop, verbatim wire bytes (no `cmd_id`).
    #[cfg_attr(feature = "serde", serde(borrow, with = "super::bytes_serde"))]
    pub program_ca_descriptors: &'a [u8],
    /// Elementary streams in wire order.
    pub streams: Vec<CaPmtStream<'a>>,
    /// The 2-bit `reserved` field in front of `version_number` as received,
    /// preserved so the object re-serializes byte-for-byte; `0b11` (the all-ones
    /// fill) when hand-built.
    #[cfg_attr(feature = "serde", serde(skip))]
    pub reserved_version: ReservedOnes<2>,
    /// The 4-bit `reserved` field in front of `program_info_length` as
    /// received (see [`CaPmt::reserved_version`]); `0b1111` when hand-built.
    #[cfg_attr(feature = "serde", serde(skip))]
    pub reserved_program_info: ReservedOnes<4>,
}

// Fixed prefix after the header: list_management(1) + program_number(2) +
// reserved/version/cni(1) + reserved/program_info_length(2).
const CA_PMT_PREFIX: usize = 6;
// Per-ES fixed prefix: stream_type(1) + reserved/elem_pid(2) +
// reserved/ES_info_length(2).
const ES_PREFIX: usize = 5;

impl<'a> Parse<'a> for CaPmt<'a> {
    type Error = Error;
    fn parse(bytes: &'a [u8]) -> Result<Self> {
        let (length_form, body) = super::parse_apdu_header(bytes, tag::CA_PMT, "ca_pmt")?;
        need_in(body, CA_PMT_PREFIX, "ca_pmt prefix")?;
        let list_management = CaPmtListManagement::from_u8(body[0]);
        let program_number = u16::from_be_bytes([body[1], body[2]]);
        let version_number = (body[3] >> 1) & 0x1F;
        let current_next_indicator = (body[3] & 0x01) != 0;
        let program_info_length = (((body[4] & 0x0F) as usize) << 8) | body[5] as usize;

        let mut pos = CA_PMT_PREFIX;
        let (cmd_id, program_ca_descriptors) =
            parse_cmd_and_descriptors(body, &mut pos, program_info_length, "ca_pmt program_info")?;

        let streams = parse_streams(body, pos, "ca_pmt ES prefix", "ca_pmt ES_info")?;

        Ok(Self {
            length_form,
            list_management,
            program_number,
            version_number,
            current_next_indicator,
            cmd_id,
            program_ca_descriptors,
            streams,
            reserved_version: ReservedOnes::from_bits(body[3] >> 6),
            reserved_program_info: ReservedOnes::from_bits(body[4] >> 4),
        })
    }
}

/// Read an `info_length`-byte block at `*pos`: when non-zero it starts with a
/// `ca_pmt_cmd_id` byte followed by `info_length - 1` descriptor bytes. Advances
/// `*pos` past the block.
pub(crate) fn parse_cmd_and_descriptors<'a>(
    body: &'a [u8],
    pos: &mut usize,
    info_length: usize,
    what: &'static str,
) -> Result<(Option<CaPmtCmdId>, &'a [u8])> {
    if info_length == 0 {
        return Ok((None, &body[..0]));
    }
    let end = *pos + info_length;
    if end > body.len() {
        return Err(Error::LengthMismatch(
            broadcast_common::error::LengthMismatch {
                what,
                declared: info_length,
                actual: body.len().saturating_sub(*pos),
            },
        ));
    }
    let cmd_id = CaPmtCmdId::from_u8(body[*pos]);
    let descriptors = &body[*pos + 1..end];
    *pos = end;
    Ok((Some(cmd_id), descriptors))
}

/// Wire length of an info block (cmd_id + descriptors), or 0 when neither is
/// present.
pub(crate) fn info_block_len(cmd_id: Option<CaPmtCmdId>, descriptors: &[u8]) -> usize {
    if cmd_id.is_some() || !descriptors.is_empty() {
        1 + descriptors.len()
    } else {
        0
    }
}

/// Parse the elementary-stream loop of a `ca_pmt` body starting at `pos`.
pub(crate) fn parse_streams<'a>(
    body: &'a [u8],
    mut pos: usize,
    prefix_what: &'static str,
    info_what: &'static str,
) -> Result<Vec<CaPmtStream<'a>>> {
    let mut streams = Vec::new();
    while pos < body.len() {
        need_in(body, pos + ES_PREFIX, prefix_what)?;
        let stream_type = body[pos];
        let reserved_pid = ReservedOnes::from_bits(body[pos + 1] >> 5);
        let reserved_es_info = ReservedOnes::from_bits(body[pos + 3] >> 4);
        let elementary_pid =
            Pid::new((((body[pos + 1] & 0x1F) as u16) << 8) | body[pos + 2] as u16);
        let es_info_length = (((body[pos + 3] & 0x0F) as usize) << 8) | body[pos + 4] as usize;
        pos += ES_PREFIX;
        let (cmd_id, ca_descriptors) =
            parse_cmd_and_descriptors(body, &mut pos, es_info_length, info_what)?;
        streams.push(CaPmtStream {
            stream_type,
            elementary_pid,
            cmd_id,
            ca_descriptors,
            reserved_pid,
            reserved_es_info,
        });
    }
    Ok(streams)
}

/// Total wire length of an elementary-stream loop.
pub(crate) fn streams_len(streams: &[CaPmtStream<'_>]) -> usize {
    streams
        .iter()
        .map(|s| ES_PREFIX + info_block_len(s.cmd_id, s.ca_descriptors))
        .sum()
}

/// Range-check every `ES_info_length` and return the loop's wire length.
pub(crate) fn checked_streams_len(
    streams: &[CaPmtStream<'_>],
    length_what: &'static str,
) -> Result<usize> {
    for s in streams {
        super::fit_bits(
            info_block_len(s.cmd_id, s.ca_descriptors) as u64,
            12,
            length_what,
        )?;
    }
    Ok(streams_len(streams))
}

/// Write an elementary-stream loop at `buf[pos..]`, returning the new position.
pub(crate) fn write_streams(
    buf: &mut [u8],
    mut pos: usize,
    streams: &[CaPmtStream<'_>],
) -> Result<usize> {
    for s in streams {
        let es_info_length = info_block_len(s.cmd_id, s.ca_descriptors);
        buf[pos] = s.stream_type;
        buf[pos + 1] = (s.reserved_pid.get() << 5) | (s.elementary_pid.value() >> 8) as u8;
        buf[pos + 2] = s.elementary_pid.value() as u8;
        buf[pos + 3] = (s.reserved_es_info.get() << 4) | (es_info_length >> 8) as u8;
        buf[pos + 4] = es_info_length as u8;
        pos += ES_PREFIX;
        pos += write_info_block(s.cmd_id, s.ca_descriptors, &mut buf[pos..])?;
    }
    Ok(pos)
}

impl Serialize for CaPmt<'_> {
    type Error = Error;
    fn serialized_len(&self) -> usize {
        let body = CA_PMT_PREFIX
            + info_block_len(self.cmd_id, self.program_ca_descriptors)
            + streams_len(&self.streams);
        super::apdu_len(body, self.length_form)
    }

    fn serialize_into(&self, buf: &mut [u8]) -> Result<usize> {
        super::fit_bits(u64::from(self.version_number), 5, "ca_pmt version_number")?;
        let program_info_length = info_block_len(self.cmd_id, self.program_ca_descriptors);
        super::fit_bits(program_info_length as u64, 12, "ca_pmt program_info_length")?;
        let body = CA_PMT_PREFIX
            + program_info_length
            + checked_streams_len(&self.streams, "ca_pmt ES_info_length")?;
        let mut pos = super::write_apdu_header(tag::CA_PMT, body, self.length_form, buf)?;

        buf[pos] = self.list_management.to_u8();
        buf[pos + 1..pos + 3].copy_from_slice(&self.program_number.to_be_bytes());
        // reserved(2)='11', version(5), current_next(1). version_number was
        // range-checked above, so no mask is needed to fit the field.
        buf[pos + 3] = (self.reserved_version.get() << 6)
            | (self.version_number << 1)
            | u8::from(self.current_next_indicator);
        // reserved(4)='1111', program_info_length(12). Range-checked above.
        buf[pos + 4] = (self.reserved_program_info.get() << 4) | (program_info_length >> 8) as u8;
        buf[pos + 5] = program_info_length as u8;
        pos += CA_PMT_PREFIX;
        pos += write_info_block(self.cmd_id, self.program_ca_descriptors, &mut buf[pos..])?;

        write_streams(buf, pos, &self.streams)
    }
}

pub(crate) fn write_info_block(
    cmd_id: Option<CaPmtCmdId>,
    descriptors: &[u8],
    buf: &mut [u8],
) -> Result<usize> {
    let len = info_block_len(cmd_id, descriptors);
    if len == 0 {
        return Ok(0);
    }
    need_out(buf, len)?;
    // Table 25: `ca_pmt_cmd_id` is present exactly when the info block is
    // (`program_info_length`/`ES_info_length != 0`, which is why `len > 0`
    // here). A caller that hand-builds a non-empty descriptor loop without a
    // `cmd_id` has an object the wire format cannot express — reject it
    // rather than fabricate a command the caller never chose (previously
    // silently defaulted to `OkDescrambling`).
    let Some(cmd_id) = cmd_id else {
        return Err(Error::InvalidObject {
            what: "ca_pmt info block",
            reason: "CA_descriptor loop present without a ca_pmt_cmd_id",
        });
    };
    buf[0] = cmd_id.to_u8();
    buf[1..len].copy_from_slice(descriptors);
    Ok(len)
}

impl<'a> ApduDef<'a> for CaPmt<'a> {
    const TAG: ApduTag = tag::CA_PMT;
    const NAME: &'static str = "CA_PMT";
}

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

    fn sample_ca_descriptor(ca_system_id: u16, pid: u16) -> [u8; 6] {
        // CA_descriptor: tag 0x09, len 4, CA_system_id(2), reserved(3)+CA_PID(13).
        [
            CA_DESCRIPTOR_TAG,
            0x04,
            (ca_system_id >> 8) as u8,
            ca_system_id as u8,
            0xE0 | ((pid >> 8) as u8 & 0x1F),
            pid as u8,
        ]
    }

    /// r10-W-6: a non-empty `CA_descriptor` loop with no `cmd_id` must be
    /// rejected, not silently serialized under a fabricated
    /// `OkDescrambling`. Table 25 ties `ca_pmt_cmd_id`'s presence to a
    /// non-zero info-block length, so this combination has no valid wire
    /// encoding at all.
    #[test]
    fn missing_cmd_id_with_descriptors_is_rejected() {
        let desc = sample_ca_descriptor(0x0500, 0x0100);
        let pmt = CaPmt {
            reserved_program_info: Default::default(),
            reserved_version: Default::default(),
            length_form: crate::length::LengthForm::Minimal,
            list_management: CaPmtListManagement::Only,
            program_number: 0x1234,
            version_number: 5,
            current_next_indicator: true,
            cmd_id: None,
            program_ca_descriptors: &desc,
            streams: Vec::new(),
        };
        assert!(matches!(
            pmt.try_to_bytes(),
            Err(Error::InvalidObject { .. })
        ));

        // Same defect at ES level.
        let pmt = CaPmt {
            reserved_program_info: Default::default(),
            reserved_version: Default::default(),
            length_form: crate::length::LengthForm::Minimal,
            list_management: CaPmtListManagement::Only,
            program_number: 0x1234,
            version_number: 5,
            current_next_indicator: true,
            cmd_id: Some(CaPmtCmdId::OkDescrambling),
            program_ca_descriptors: &[],
            streams: alloc::vec![CaPmtStream {
                reserved_es_info: Default::default(),
                reserved_pid: Default::default(),
                stream_type: 0x02,
                elementary_pid: Pid::new(0x0101),
                cmd_id: None,
                ca_descriptors: &desc,
            }],
        };
        assert!(matches!(
            pmt.try_to_bytes(),
            Err(Error::InvalidObject { .. })
        ));
    }

    #[test]
    fn empty_ca_pmt_round_trips() {
        let pmt = CaPmt {
            reserved_program_info: Default::default(),
            reserved_version: Default::default(),
            length_form: crate::length::LengthForm::Minimal,
            list_management: CaPmtListManagement::Only,
            program_number: 0x1234,
            version_number: 5,
            current_next_indicator: true,
            cmd_id: None,
            program_ca_descriptors: &[],
            streams: Vec::new(),
        };
        let bytes = pmt.try_to_bytes().unwrap();
        assert_eq!(&bytes[..4], &[0x9F, 0x80, 0x32, 0x06]);
        assert_eq!(CaPmt::parse(&bytes).unwrap(), pmt);
    }

    #[test]
    fn multi_es_round_trips_and_bites() {
        let prog_desc = sample_ca_descriptor(0x0500, 0x0100);
        let es0_desc = sample_ca_descriptor(0x0500, 0x0101);
        let es1_desc = sample_ca_descriptor(0x0B00, 0x0201);
        let pmt = CaPmt {
            reserved_program_info: Default::default(),
            reserved_version: Default::default(),
            length_form: crate::length::LengthForm::Minimal,
            list_management: CaPmtListManagement::Only,
            program_number: 0x0001,
            version_number: 1,
            current_next_indicator: true,
            cmd_id: Some(CaPmtCmdId::OkDescrambling),
            program_ca_descriptors: &prog_desc,
            streams: alloc::vec![
                CaPmtStream {
                    reserved_es_info: Default::default(),
                    reserved_pid: Default::default(),
                    stream_type: 0x02,
                    elementary_pid: Pid::new(0x0200),
                    cmd_id: Some(CaPmtCmdId::OkDescrambling),
                    ca_descriptors: &es0_desc,
                },
                CaPmtStream {
                    reserved_es_info: Default::default(),
                    reserved_pid: Default::default(),
                    stream_type: 0x03,
                    elementary_pid: Pid::new(0x0201),
                    cmd_id: Some(CaPmtCmdId::OkDescrambling),
                    ca_descriptors: &es1_desc,
                },
            ],
        };
        let bytes = pmt.try_to_bytes().unwrap();
        let parsed = CaPmt::parse(&bytes).unwrap();
        assert_eq!(parsed, pmt);
        assert_eq!(parsed.streams.len(), 2);
        assert_eq!(parsed.list_management.name(), "only");

        // bite: mutate the program_number.
        let mut other = pmt.clone();
        other.program_number = 0x0002;
        assert_ne!(bytes, other.try_to_bytes().unwrap());

        // bite: mutate a stream's pid.
        let mut other2 = pmt.clone();
        other2.streams[0].elementary_pid = Pid::new(0x0300);
        assert_ne!(bytes, other2.try_to_bytes().unwrap());
    }

    #[test]
    fn es_without_ca_info_omits_cmd_id() {
        let pmt = CaPmt {
            reserved_program_info: Default::default(),
            reserved_version: Default::default(),
            length_form: crate::length::LengthForm::Minimal,
            list_management: CaPmtListManagement::Add,
            program_number: 7,
            version_number: 0,
            current_next_indicator: true,
            cmd_id: None,
            program_ca_descriptors: &[],
            streams: alloc::vec![CaPmtStream {
                reserved_es_info: Default::default(),
                reserved_pid: Default::default(),
                stream_type: 0x1B,
                elementary_pid: Pid::new(0x00FF),
                cmd_id: None,
                ca_descriptors: &[],
            }],
        };
        let bytes = pmt.try_to_bytes().unwrap();
        let parsed = CaPmt::parse(&bytes).unwrap();
        assert_eq!(parsed, pmt);
        assert!(parsed.streams[0].cmd_id.is_none());
    }

    #[test]
    fn oversized_elementary_pid_is_unrepresentable() {
        // The 13-bit field is now a `Pid`: a value that would previously have
        // been rejected at serialize time is refused at construction.
        let err = Pid::try_new(0x2100).unwrap_err();
        assert_eq!(err.value, 0x2100);
        assert!(Pid::try_new(0x1FFF).is_ok());
    }

    #[test]
    fn max_pid_still_serializes_and_round_trips() {
        let pmt = CaPmt {
            reserved_program_info: Default::default(),
            reserved_version: Default::default(),
            length_form: crate::length::LengthForm::Minimal,
            list_management: CaPmtListManagement::Only,
            program_number: 1,
            version_number: 0,
            current_next_indicator: true,
            cmd_id: None,
            program_ca_descriptors: &[],
            streams: alloc::vec![CaPmtStream {
                reserved_es_info: Default::default(),
                reserved_pid: Default::default(),
                stream_type: 0x02,
                elementary_pid: Pid::new(0x1FFF), // the 13-bit maximum
                cmd_id: None,
                ca_descriptors: &[],
            }],
        };
        let bytes = pmt.try_to_bytes().unwrap();
        assert_eq!(CaPmt::parse(&bytes).unwrap(), pmt);
    }

    #[test]
    fn oversized_program_info_length_is_rejected() {
        // A program_info block of 4096+ bytes exceeds the 12-bit
        // program_info_length field (max 0x0FFF).
        let big = alloc::vec![0u8; 4096];
        let pmt = CaPmt {
            reserved_program_info: Default::default(),
            reserved_version: Default::default(),
            length_form: crate::length::LengthForm::Minimal,
            list_management: CaPmtListManagement::Only,
            program_number: 1,
            version_number: 0,
            current_next_indicator: true,
            cmd_id: Some(CaPmtCmdId::OkDescrambling),
            program_ca_descriptors: &big,
            streams: Vec::new(),
        };
        let mut buf = alloc::vec![0u8; 4200];
        assert!(matches!(
            pmt.serialize_into(&mut buf),
            Err(Error::InvalidObject { .. })
        ));
    }

    #[test]
    fn oversized_version_number_is_rejected() {
        let pmt = CaPmt {
            reserved_program_info: Default::default(),
            reserved_version: Default::default(),
            length_form: crate::length::LengthForm::Minimal,
            list_management: CaPmtListManagement::Only,
            program_number: 1,
            version_number: 0x20, // exceeds the 5-bit field (max 0x1F)
            current_next_indicator: true,
            cmd_id: None,
            program_ca_descriptors: &[],
            streams: Vec::new(),
        };
        let mut buf = [0u8; 16];
        assert!(matches!(
            pmt.serialize_into(&mut buf),
            Err(Error::InvalidObject { .. })
        ));
    }
}