1use crate::error::{Error, Result};
4use crate::pid::Pid;
5use broadcast_common::len::{need_in, need_out};
6
7pub const TS_PACKET_SIZE: usize = 188;
9pub const TS_SYNC_BYTE: u8 = 0x47;
11pub const MAX_DATAGRAM_PAYLOAD: usize = 1472;
17pub const TS_PACKETS_PER_DATAGRAM: usize = 7;
24pub const TS_BYTES_PER_DATAGRAM: usize = TS_PACKETS_PER_DATAGRAM * TS_PACKET_SIZE;
27const MAX_SECTION_SIZE: usize = 4098;
32const SECTION_HEADER_LEN: usize = 3;
36pub(crate) const SECTION_LENGTH_HI_MASK: u8 = 0x0F;
40
41pub(crate) const STUFFING_BYTE: u8 = 0xFF;
43
44pub(crate) fn section_total_len(bytes: &[u8]) -> Option<usize> {
53 if bytes.len() < SECTION_HEADER_LEN {
54 return None;
55 }
56 let section_length = ((bytes[1] & SECTION_LENGTH_HI_MASK) as usize) << 8 | bytes[2] as usize;
57 Some(SECTION_HEADER_LEN + section_length)
58}
59
60#[non_exhaustive]
69#[derive(Debug, Clone, Copy, PartialEq, Eq)]
70#[cfg_attr(feature = "serde", derive(serde::Serialize))]
71pub enum ScramblingControl {
72 NotScrambled,
74 Reserved,
76 EvenKey,
79 OddKey,
82}
83
84impl ScramblingControl {
85 pub fn from_bits(bits: u8) -> Self {
87 match bits & 0b11 {
88 0b00 => Self::NotScrambled,
89 0b01 => Self::Reserved,
90 0b10 => Self::EvenKey,
91 _ => Self::OddKey,
92 }
93 }
94
95 pub fn to_bits(self) -> u8 {
100 match self {
101 Self::NotScrambled => 0b00,
102 Self::Reserved => 0b01,
103 Self::EvenKey => 0b10,
104 Self::OddKey => 0b11,
105 }
106 }
107
108 pub fn name(&self) -> &'static str {
110 match self {
111 Self::NotScrambled => "not_scrambled",
112 Self::Reserved => "reserved",
113 Self::EvenKey => "even_key",
114 Self::OddKey => "odd_key",
115 }
116 }
117}
118
119broadcast_common::impl_spec_display!(ScramblingControl);
120
121#[non_exhaustive]
128#[derive(Debug, Clone, Copy, PartialEq, Eq)]
129#[cfg_attr(feature = "serde", derive(serde::Serialize))]
130pub enum AdaptationFieldControl {
131 Reserved,
133 PayloadOnly,
135 AdaptationOnly,
137 AdaptationAndPayload,
139}
140
141impl AdaptationFieldControl {
142 pub fn from_flags(has_adaptation: bool, has_payload: bool) -> Self {
144 match (has_adaptation, has_payload) {
145 (false, false) => Self::Reserved,
146 (false, true) => Self::PayloadOnly,
147 (true, false) => Self::AdaptationOnly,
148 (true, true) => Self::AdaptationAndPayload,
149 }
150 }
151
152 pub fn to_flags(self) -> (bool, bool) {
155 match self {
156 Self::Reserved => (false, false),
157 Self::PayloadOnly => (false, true),
158 Self::AdaptationOnly => (true, false),
159 Self::AdaptationAndPayload => (true, true),
160 }
161 }
162
163 pub fn to_bits(self) -> u8 {
169 match self {
170 Self::Reserved => 0b00,
171 Self::PayloadOnly => 0b01,
172 Self::AdaptationOnly => 0b10,
173 Self::AdaptationAndPayload => 0b11,
174 }
175 }
176
177 pub fn name(&self) -> &'static str {
179 match self {
180 Self::Reserved => "reserved",
181 Self::PayloadOnly => "payload_only",
182 Self::AdaptationOnly => "adaptation_only",
183 Self::AdaptationAndPayload => "adaptation_and_payload",
184 }
185 }
186}
187
188broadcast_common::impl_spec_display!(AdaptationFieldControl);
189
190const TEI_MASK: u8 = 0x80;
192const PUSI_MASK: u8 = 0x40;
194pub const PID_MASK_HI: u8 = 0x1F;
196pub const SCRAMBLING_MASK: u8 = 0xC0;
198const SCRAMBLING_SHIFT: u32 = 6;
200const ADAPTATION_SHIFT: u32 = 4;
202const ADAPTATION_CONTROL_MASK: u8 = 0b11;
204pub const ADAPTATION_FLAG: u8 = 0x20;
206pub const PAYLOAD_FLAG: u8 = 0x10;
208pub const CC_MASK: u8 = 0x0F;
210
211#[derive(Clone, Copy, Default, PartialEq, Eq, PartialOrd, Ord, Hash)]
217#[cfg_attr(feature = "serde", derive(serde::Serialize))]
218#[cfg_attr(feature = "serde", serde(transparent))]
219pub struct ContinuityCounter(u8);
220
221impl ContinuityCounter {
222 pub const ZERO: Self = Self(0);
224
225 #[must_use]
227 pub const fn next(self) -> Self {
228 Self((self.0 + 1) % COUNT_MODULUS)
229 }
230
231 #[must_use]
233 pub const fn value(self) -> u8 {
234 self.0
235 }
236
237 #[must_use]
241 pub const fn forward_distance_from(self, from: Self) -> u8 {
242 (self.0 + COUNT_MODULUS - from.0) % COUNT_MODULUS
243 }
244
245 pub const fn try_new(value: u8) -> core::result::Result<Self, ContinuityCounterOutOfRange> {
250 if value > CC_MASK {
251 Err(ContinuityCounterOutOfRange { value })
252 } else {
253 Ok(Self(value))
254 }
255 }
256
257 #[must_use]
261 pub const fn from_wire_masked(value: u8) -> Self {
262 Self(value & CC_MASK)
263 }
264}
265
266const COUNT_MODULUS: u8 = CC_MASK + 1;
268
269impl From<ContinuityCounter> for u8 {
270 fn from(cc: ContinuityCounter) -> Self {
271 cc.0
272 }
273}
274
275impl TryFrom<u8> for ContinuityCounter {
276 type Error = ContinuityCounterOutOfRange;
277 fn try_from(value: u8) -> core::result::Result<Self, Self::Error> {
278 Self::try_new(value)
279 }
280}
281
282impl core::fmt::Debug for ContinuityCounter {
283 fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
284 write!(f, "ContinuityCounter({})", self.0)
285 }
286}
287
288impl core::fmt::Display for ContinuityCounter {
289 fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
290 write!(f, "{}", self.0)
291 }
292}
293
294#[derive(Debug, Clone, Copy, PartialEq, Eq)]
297#[non_exhaustive]
298pub struct ContinuityCounterOutOfRange {
299 pub value: u8,
301}
302
303impl core::fmt::Display for ContinuityCounterOutOfRange {
304 fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
305 write!(
306 f,
307 "continuity_counter {} exceeds the 4-bit range 0..=15",
308 self.value
309 )
310 }
311}
312
313impl core::error::Error for ContinuityCounterOutOfRange {}
314
315#[derive(Clone, Debug, PartialEq, Eq)]
317#[cfg_attr(feature = "serde", derive(serde::Serialize))]
318pub struct TsHeader {
319 pub tei: bool,
322 pub pusi: bool,
325 pub pid: Pid,
327 pub scrambling: ScramblingControl,
330 #[cfg_attr(feature = "serde", serde(rename = "adaptation"))]
336 pub adaptation_field_control: AdaptationFieldControl,
337 pub continuity_counter: ContinuityCounter,
339}
340
341#[derive(Clone, Debug)]
347#[cfg_attr(feature = "serde", derive(serde::Serialize))]
348pub struct TsPacket<'a> {
349 pub header: TsHeader,
351 pub payload: Option<&'a [u8]>,
355 #[cfg_attr(feature = "serde", serde(skip))]
358 adaptation: Option<&'a [u8]>,
359 #[cfg_attr(feature = "serde", serde(skip))]
361 pub raw: &'a [u8; TS_PACKET_SIZE],
362}
363
364impl TsHeader {
365 pub fn parse(raw4: &[u8]) -> Result<Self> {
367 need_in(raw4, 4, "TsHeader")?;
368 let b1 = raw4[1];
369 let b2 = raw4[2];
370 let b3 = raw4[3];
371
372 let tei = (b1 & TEI_MASK) != 0;
373 let pusi = (b1 & PUSI_MASK) != 0;
374 let pid = Pid::from_wire_masked((u16::from(b1 & PID_MASK_HI) << 8) | u16::from(b2));
375 let has_adaptation = (b3 & ADAPTATION_FLAG) != 0;
376 let has_payload = (b3 & PAYLOAD_FLAG) != 0;
377
378 Ok(Self {
379 tei,
380 pusi,
381 pid,
382 scrambling: ScramblingControl::from_bits(b3 >> SCRAMBLING_SHIFT),
383 adaptation_field_control: AdaptationFieldControl::from_flags(
384 has_adaptation,
385 has_payload,
386 ),
387 continuity_counter: ContinuityCounter::from_wire_masked(b3),
388 })
389 }
390
391 pub const fn serialized_len() -> usize {
393 4
394 }
395
396 #[must_use]
398 pub fn to_bytes(&self) -> [u8; 4] {
399 let mut b = [0u8; 4];
400 b[0] = TS_SYNC_BYTE;
401 if self.tei {
402 b[1] |= TEI_MASK;
403 }
404 if self.pusi {
405 b[1] |= PUSI_MASK;
406 }
407 let pid = self.pid.value();
408 b[1] |= ((pid >> 8) as u8) & PID_MASK_HI;
409 b[2] = pid.to_be_bytes()[1];
410 b[3] = (self.scrambling.to_bits() << SCRAMBLING_SHIFT)
411 | ((self.adaptation_field_control.to_bits() & ADAPTATION_CONTROL_MASK)
412 << ADAPTATION_SHIFT)
413 | self.continuity_counter.value();
414 b
415 }
416
417 pub fn serialize_into(&self, buf: &mut [u8]) -> Result<usize> {
419 need_out(buf, 4)?;
420 buf[..4].copy_from_slice(&self.to_bytes());
421 Ok(4)
422 }
423
424 pub fn has_adaptation(&self) -> bool {
427 self.adaptation_field_control.to_flags().0
428 }
429
430 pub fn has_payload(&self) -> bool {
433 self.adaptation_field_control.to_flags().1
434 }
435}
436
437impl<'a> broadcast_common::Parse<'a> for TsHeader {
438 type Error = Error;
439
440 fn parse(bytes: &'a [u8]) -> Result<Self> {
441 TsHeader::parse(bytes)
442 }
443}
444
445impl broadcast_common::Serialize for TsHeader {
446 type Error = Error;
447
448 fn serialized_len(&self) -> usize {
449 TsHeader::serialized_len()
450 }
451
452 fn serialize_into(&self, buf: &mut [u8]) -> Result<usize> {
453 TsHeader::serialize_into(self, buf)
454 }
455}
456
457pub(crate) fn adaptation_field_body_range(
467 pkt: &[u8],
468 has_adaptation: bool,
469) -> Option<core::ops::Range<usize>> {
470 if !has_adaptation || pkt.len() <= AF_LEN_BYTE {
471 return None;
472 }
473 let af_len = pkt[AF_LEN_BYTE] as usize;
474 if af_len == 0 {
475 return None;
476 }
477 let start = AF_FLAGS_BYTE;
478 let end = start + af_len;
479 if end > pkt.len() {
480 return None;
481 }
482 Some(start..end)
483}
484
485fn adaptation_field_skip(pkt: &[u8], has_adaptation: bool) -> usize {
491 if !has_adaptation || pkt.len() <= AF_LEN_BYTE {
492 return 0;
493 }
494 1 + pkt[AF_LEN_BYTE] as usize
495}
496
497pub(crate) enum ClockReferenceSlot {
502 Field(core::ops::Range<usize>),
504 NoAdaptationField,
506 TooShort {
508 need: usize,
510 have: usize,
512 },
513 FlagClear,
515 Truncated {
517 need: usize,
519 have: usize,
521 },
522}
523
524pub(crate) fn clock_reference_slot(pkt: &[u8], flag: u8) -> ClockReferenceSlot {
528 if pkt.len() <= AF_LEN_BYTE || pkt[3] & ADAPTATION_FLAG == 0 {
529 return ClockReferenceSlot::NoAdaptationField;
530 }
531 let af_len = pkt[AF_LEN_BYTE] as usize;
532 if af_len == 0 {
533 return ClockReferenceSlot::NoAdaptationField;
534 }
535 let preceding = if flag == AF_OPCR_FLAG {
538 PCR_FIELD_LEN
539 } else {
540 0
541 };
542 let need = 1 + preceding + PCR_FIELD_LEN;
543 if af_len < need {
544 return ClockReferenceSlot::TooShort { need, have: af_len };
545 }
546 if pkt.len() <= AF_FLAGS_BYTE || pkt[AF_FLAGS_BYTE] & flag == 0 {
547 return ClockReferenceSlot::FlagClear;
548 }
549 let start = CLOCK_REFERENCE_START + preceding;
550 let end = start + PCR_FIELD_LEN;
551 if end > pkt.len() {
552 return ClockReferenceSlot::Truncated {
553 need: end,
554 have: pkt.len(),
555 };
556 }
557 ClockReferenceSlot::Field(start..end)
558}
559
560impl<'a> TsPacket<'a> {
561 pub fn parse(buf: &'a [u8]) -> Result<Self> {
567 need_in(buf, TS_PACKET_SIZE, "TsPacket")?;
568 if buf[0] != TS_SYNC_BYTE {
569 return Err(Error::InvalidSync(broadcast_common::error::InvalidSync {
570 what: "TS sync byte",
571 expected: u32::from(TS_SYNC_BYTE),
572 found: u32::from(buf[0]),
573 }));
574 }
575
576 let raw: &[u8; TS_PACKET_SIZE] = buf[..TS_PACKET_SIZE].try_into().map_err(|_| {
577 Error::BufferTooShort(broadcast_common::error::BufferTooShort {
578 need: TS_PACKET_SIZE,
579 have: buf.len(),
580 what: "TsPacket::parse (array conversion)",
581 })
582 })?;
583
584 let header = TsHeader::parse(&raw[..4])?;
585
586 let mut cursor = 4usize;
587 let mut payload = None;
588
589 let adaptation = adaptation_field_body_range(raw, header.has_adaptation()).map(|r| &raw[r]);
602 cursor += adaptation_field_skip(raw, header.has_adaptation());
607
608 if header.has_payload() && cursor < TS_PACKET_SIZE {
609 payload = Some(&raw[cursor..]);
610 }
611
612 Ok(TsPacket {
613 header,
614 payload,
615 adaptation,
616 raw,
617 })
618 }
619
620 pub fn adaptation_field(&self) -> Option<crate::Result<AdaptationField<'a>>> {
626 self.adaptation.map(AdaptationField::parse)
627 }
628}
629
630pub(crate) const AF_DISCONTINUITY: u8 = 0x80;
632pub(crate) const AF_RANDOM_ACCESS: u8 = 0x40;
633pub(crate) const AF_ES_PRIORITY: u8 = 0x20;
634pub const AF_PCR_FLAG: u8 = 0x10;
636pub(crate) const AF_OPCR_FLAG: u8 = 0x08;
637pub(crate) const AF_SPLICING_FLAG: u8 = 0x04;
638pub(crate) const AF_TRANSPORT_PRIVATE_DATA_FLAG: u8 = 0x02;
639pub(crate) const AF_EXTENSION_FLAG: u8 = 0x01;
640pub(crate) const PCR_RESERVED_BITS: u8 = 0x7E;
643const PCR_RESERVED_BITS_COUNT: u32 = 6;
645pub(crate) const PCR_RESERVED_SHIFT: u32 = 1;
647pub(crate) const PCR_RESERVED_BYTE_OFFSET: usize = 4;
649const PCR_RESERVED_VALUE: u8 = 0x3F;
651pub(crate) const PCR_FIELD_LEN: usize = 6;
653
654pub(crate) const AF_LEN_BYTE: usize = 4;
657pub(crate) const AF_FLAGS_BYTE: usize = 5;
660pub(crate) const CLOCK_REFERENCE_START: usize = AF_FLAGS_BYTE + 1;
663
664#[derive(Clone, Copy, Debug, PartialEq, Eq)]
677#[cfg_attr(feature = "serde", derive(serde::Serialize))]
678pub struct Pcr(broadcast_common::clock33::Clock27);
679
680impl Pcr {
681 pub fn from_parts(base: u64, extension: u16) -> Result<Self> {
686 Ok(Self(broadcast_common::clock33::Clock27::from_parts(
687 base, extension,
688 )?))
689 }
690
691 pub fn from_27mhz(ticks: u64) -> Result<Self> {
696 Ok(Self(broadcast_common::clock33::Clock27::from_27mhz(ticks)?))
697 }
698
699 pub fn to_clock27(self) -> Result<broadcast_common::clock33::Clock27> {
705 Ok(self.0.to_clock27()?)
706 }
707
708 #[must_use]
711 pub const fn clock(self) -> broadcast_common::clock33::Clock27 {
712 self.0
713 }
714
715 #[must_use]
717 pub const fn base(self) -> u64 {
718 self.0.base.ticks()
719 }
720
721 #[must_use]
724 pub const fn extension(self) -> u16 {
725 self.0.ext
726 }
727
728 #[must_use]
734 pub fn as_27mhz(self) -> u64 {
735 self.0.ticks()
736 }
737
738 #[must_use]
748 pub fn to_field_bytes(self) -> [u8; PCR_FIELD_LEN] {
749 let b = self.0.base.ticks();
750 let e = u64::from(self.0.ext);
751 [
752 ((b >> 25) & 0xFF) as u8,
753 ((b >> 17) & 0xFF) as u8,
754 ((b >> 9) & 0xFF) as u8,
755 ((b >> 1) & 0xFF) as u8,
756 (((b & 0x01) as u8) << 7) | PCR_RESERVED_BITS | ((e >> 8) as u8 & 0x01),
758 (e & 0xFF) as u8,
759 ]
760 }
761
762 pub fn to_field_bytes_with_reserved(self, reserved: u8) -> Result<[u8; PCR_FIELD_LEN]> {
769 let mut field = self.to_field_bytes();
770 set_pcr_reserved(&mut field, reserved)?;
771 Ok(field)
772 }
773
774 pub(crate) fn parse(buf: &[u8], from: usize) -> Result<Self> {
781 let end = from + PCR_FIELD_LEN;
782 let b: &[u8; PCR_FIELD_LEN] =
783 buf.get(from..end)
784 .and_then(|s| s.try_into().ok())
785 .ok_or(Error::BufferTooShort(
786 broadcast_common::error::BufferTooShort {
787 need: end,
788 have: buf.len(),
789 what: "adaptation_field PCR",
790 },
791 ))?;
792 let base = ((b[0] as u64) << 25)
793 | ((b[1] as u64) << 17)
794 | ((b[2] as u64) << 9)
795 | ((b[3] as u64) << 1)
796 | (u64::from(b[4]) >> 7);
797 let extension = ((b[4] & 0x01) as u16) << 8 | u16::from(b[5]);
798 Ok(Self(broadcast_common::clock33::Clock27::from_wire_parts(
799 base, extension,
800 )))
801 }
802}
803
804#[derive(Clone, Copy, Debug, PartialEq, Eq)]
811#[cfg_attr(feature = "serde", derive(serde::Serialize))]
812pub struct Ltw {
813 pub ltw_valid_flag: bool,
815 pub ltw_offset: LtwOffset,
816}
817
818#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
824#[cfg_attr(feature = "serde", derive(serde::Serialize))]
825#[cfg_attr(feature = "serde", serde(transparent))]
826pub struct LtwOffset(u16);
827
828const LTW_OFFSET_BITS: u32 = 15;
830
831impl LtwOffset {
832 pub const MAX: Self = Self((1 << LTW_OFFSET_BITS) - 1);
834
835 pub const ZERO: Self = Self(0);
837
838 pub fn new(value: u16) -> Result<Self> {
840 let fitted =
841 broadcast_common::len::fit_bits(u64::from(value), LTW_OFFSET_BITS, "ltw_offset")?;
842 Ok(Self(fitted as u16))
843 }
844
845 #[must_use]
850 pub(crate) fn from_wire_masked(high: u8, low: u8) -> Self {
851 Self((u16::from(high & LTW_OFFSET_HI_MASK) << 8) | u16::from(low))
852 }
853
854 #[must_use]
856 pub fn get(self) -> u16 {
857 self.0
858 }
859}
860
861impl From<LtwOffset> for u16 {
862 fn from(value: LtwOffset) -> Self {
863 value.0
864 }
865}
866
867impl core::fmt::Display for LtwOffset {
868 fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
869 write!(f, "{}", self.0)
870 }
871}
872
873#[non_exhaustive]
882#[derive(Clone, Copy, Debug, PartialEq, Eq)]
883#[cfg_attr(feature = "serde", derive(serde::Serialize))]
884pub struct SeamlessSplice {
885 pub splice_type: u8,
887 pub dts_next_au: u64,
889 pub marker_bits: u8,
894}
895
896const SPLICE_TYPE_BITS: u32 = 4;
898const DTS_NEXT_AU_BITS: u32 = 33;
900const SPLICE_MARKER_BITS: u32 = 3;
902
903impl SeamlessSplice {
904 #[must_use]
906 pub const fn new(splice_type: u8, dts_next_au: u64) -> Self {
907 Self {
908 splice_type,
909 dts_next_au,
910 marker_bits: SPLICE_MARKERS_VALUE,
911 }
912 }
913
914 pub const DTS_NEXT_AU_BITS: u32 = DTS_NEXT_AU_BITS;
916
917 #[must_use]
919 pub(crate) fn from_marked_field(field: &[u8; 5]) -> Self {
920 let m = broadcast_common::clock33::unpack_marked(field);
921 Self {
922 splice_type: m.prefix,
923 dts_next_au: m.timestamp,
924 marker_bits: m.markers,
925 }
926 }
927
928 pub fn to_marked_field(&self) -> Result<[u8; 5]> {
931 broadcast_common::len::fit_bits(
932 u64::from(self.splice_type),
933 SPLICE_TYPE_BITS,
934 "seamless_splice.splice_type",
935 )?;
936 broadcast_common::len::fit_bits(
937 self.dts_next_au,
938 DTS_NEXT_AU_BITS,
939 "seamless_splice.DTS_next_AU",
940 )?;
941 broadcast_common::len::fit_bits(
942 u64::from(self.marker_bits),
943 SPLICE_MARKER_BITS,
944 "seamless_splice.marker_bit",
945 )?;
946 Ok(broadcast_common::clock33::pack_marked_with(
947 self.dts_next_au,
948 self.splice_type,
949 self.marker_bits,
950 ))
951 }
952}
953
954const SPLICE_MARKERS_VALUE: u8 = 0x07;
958const AFE_LTW_FLAG: u8 = 0x80;
959const AFE_PIECEWISE_RATE_FLAG: u8 = 0x40;
960const AFE_SEAMLESS_SPLICE_FLAG: u8 = 0x20;
961const LTW_OFFSET_HI_MASK: u8 = 0x7F;
963const PIECEWISE_RATE_HI_MASK: u8 = 0x3F;
965const AFE_AF_DESCRIPTOR_NOT_PRESENT_FLAG: u8 = 0x10;
967const AFE_RESERVED_FLAGS_MASK: u8 = 0x0F;
969const AFE_RESERVED_FLAGS_VALUE: u8 = 0x0F;
971const PIECEWISE_RATE_RESERVED_SHIFT: u32 = 6;
973const PIECEWISE_RATE_RESERVED_VALUE: u8 = 0x03;
975const PIECEWISE_RATE_BITS: u32 = 22;
977
978#[non_exhaustive]
998#[derive(Clone, Copy, Debug, PartialEq, Eq)]
999#[cfg_attr(feature = "serde", derive(serde::Serialize))]
1000pub struct AdaptationFieldExtension<'a> {
1001 pub ltw: Option<Ltw>,
1003 pub piecewise_rate: Option<PiecewiseRate>,
1005 pub piecewise_rate_reserved: u8,
1008 pub seamless_splice: Option<SeamlessSplice>,
1010 pub af_descriptor_not_present_flag: bool,
1014 pub reserved_flags: u8,
1016 pub trailing: &'a [u8],
1020}
1021
1022impl Default for AdaptationFieldExtension<'_> {
1023 fn default() -> Self {
1024 Self::new()
1025 }
1026}
1027
1028#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
1034#[cfg_attr(feature = "serde", derive(serde::Serialize))]
1035#[cfg_attr(feature = "serde", serde(transparent))]
1036pub struct PiecewiseRate(u32);
1037
1038impl PiecewiseRate {
1039 pub const MAX: Self = Self((1 << PIECEWISE_RATE_BITS) - 1);
1041
1042 pub fn new(value: u32) -> Result<Self> {
1044 let fitted = broadcast_common::len::fit_bits(
1045 u64::from(value),
1046 PIECEWISE_RATE_BITS,
1047 "piecewise_rate",
1048 )?;
1049 Ok(Self(fitted as u32))
1050 }
1051
1052 #[must_use]
1057 pub(crate) fn from_wire_masked(high: u8, mid: u8, low: u8) -> Self {
1058 Self(
1059 (u32::from(high & PIECEWISE_RATE_HI_MASK) << 16)
1060 | (u32::from(mid) << 8)
1061 | u32::from(low),
1062 )
1063 }
1064
1065 #[must_use]
1067 pub fn get(self) -> u32 {
1068 self.0
1069 }
1070}
1071
1072impl From<PiecewiseRate> for u32 {
1073 fn from(value: PiecewiseRate) -> Self {
1074 value.0
1075 }
1076}
1077
1078impl core::fmt::Display for PiecewiseRate {
1079 fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
1080 write!(f, "{}", self.0)
1081 }
1082}
1083
1084impl<'a> AdaptationFieldExtension<'a> {
1085 #[must_use]
1088 pub const fn new() -> Self {
1089 Self {
1090 ltw: None,
1091 piecewise_rate: None,
1092 piecewise_rate_reserved: PIECEWISE_RATE_RESERVED_VALUE,
1093 seamless_splice: None,
1094 af_descriptor_not_present_flag: true,
1095 reserved_flags: AFE_RESERVED_FLAGS_VALUE,
1096 trailing: &[],
1097 }
1098 }
1099
1100 fn parse(data: &'a [u8]) -> Result<Self> {
1103 need_in(data, 1, "adaptation_field_extension_length")?;
1104 let ext_len = data[0] as usize;
1105 if data.len() < 1 + ext_len || ext_len < 1 {
1107 return Err(Error::BufferTooShort(
1108 broadcast_common::error::BufferTooShort {
1109 need: 2.max(1 + ext_len),
1110 have: data.len(),
1111 what: "adaptation_field_extension body",
1112 },
1113 ));
1114 }
1115 let ext = &data[1..1 + ext_len]; let flags = ext[0];
1117 let mut cursor = 1usize;
1118
1119 let ltw = if flags & AFE_LTW_FLAG != 0 {
1120 need_in(ext, cursor + 2, "ltw_offset")?;
1121 let w0 = ext[cursor];
1122 let w1 = ext[cursor + 1];
1123 cursor += 2;
1124 Some(Ltw {
1125 ltw_valid_flag: (w0 & AFE_LTW_FLAG) != 0,
1126 ltw_offset: LtwOffset::from_wire_masked(w0, w1),
1127 })
1128 } else {
1129 None
1130 };
1131
1132 let mut piecewise_rate_reserved = PIECEWISE_RATE_RESERVED_VALUE;
1133 let piecewise_rate = if flags & AFE_PIECEWISE_RATE_FLAG != 0 {
1134 need_in(ext, cursor + 3, "piecewise_rate")?;
1135 piecewise_rate_reserved = ext[cursor] >> PIECEWISE_RATE_RESERVED_SHIFT;
1136 let r = PiecewiseRate::from_wire_masked(ext[cursor], ext[cursor + 1], ext[cursor + 2]);
1137 cursor += 3;
1138 Some(r)
1139 } else {
1140 None
1141 };
1142
1143 let seamless_splice = if flags & AFE_SEAMLESS_SPLICE_FLAG != 0 {
1145 need_in(ext, cursor + 5, "seamless_splice DTS_next_AU")?;
1146 let field = [
1147 ext[cursor],
1148 ext[cursor + 1],
1149 ext[cursor + 2],
1150 ext[cursor + 3],
1151 ext[cursor + 4],
1152 ];
1153 let splice = SeamlessSplice::from_marked_field(&field);
1156 cursor += 5;
1157 Some(splice)
1158 } else {
1159 None
1160 };
1161
1162 Ok(AdaptationFieldExtension {
1163 ltw,
1164 piecewise_rate,
1165 piecewise_rate_reserved,
1166 seamless_splice,
1167 af_descriptor_not_present_flag: flags & AFE_AF_DESCRIPTOR_NOT_PRESENT_FLAG != 0,
1168 reserved_flags: flags & AFE_RESERVED_FLAGS_MASK,
1169 trailing: &ext[cursor..],
1170 })
1171 }
1172
1173 #[must_use]
1176 pub fn serialized_len(&self) -> usize {
1177 let body = 1 + self.ltw.map_or(0, |_| 2)
1179 + self.piecewise_rate.map_or(0, |_| 3)
1180 + self.seamless_splice.map_or(0, |_| 5)
1181 + self.trailing.len();
1182 1 + body }
1184
1185 pub fn serialize_into(&self, buf: &mut [u8]) -> Result<usize> {
1187 let need = self.serialized_len();
1188 need_out(buf, need)?;
1189 buf[0] = broadcast_common::len::fit_u8(need - 1, "adaptation_field_extension_length")?;
1190
1191 let mut flags = broadcast_common::len::fit_mask(
1192 self.reserved_flags,
1193 AFE_RESERVED_FLAGS_MASK,
1194 "adaptation_field_extension.reserved",
1195 )?;
1196 if self.ltw.is_some() {
1197 flags |= AFE_LTW_FLAG;
1198 }
1199 if self.piecewise_rate.is_some() {
1200 flags |= AFE_PIECEWISE_RATE_FLAG;
1201 }
1202 if self.seamless_splice.is_some() {
1203 flags |= AFE_SEAMLESS_SPLICE_FLAG;
1204 }
1205 if self.af_descriptor_not_present_flag {
1206 flags |= AFE_AF_DESCRIPTOR_NOT_PRESENT_FLAG;
1207 }
1208 buf[1] = flags;
1209 let mut cursor = 2usize;
1210
1211 if let Some(ltw) = self.ltw {
1212 let ltw_valid = if ltw.ltw_valid_flag { AFE_LTW_FLAG } else { 0 };
1213 let offset = broadcast_common::len::fit_bits(
1214 u64::from(ltw.ltw_offset.get()),
1215 LTW_OFFSET_BITS,
1216 "ltw_offset",
1217 )?;
1218 buf[cursor] = ltw_valid | ((offset >> 8) as u8 & LTW_OFFSET_HI_MASK);
1219 buf[cursor + 1] = (offset & 0xFF) as u8;
1220 cursor += 2;
1221 }
1222 if let Some(rate) = self.piecewise_rate {
1223 let rate = broadcast_common::len::fit_bits(
1224 u64::from(rate.get()),
1225 PIECEWISE_RATE_BITS,
1226 "piecewise_rate",
1227 )?;
1228 buf[cursor] = (broadcast_common::len::fit_mask(
1230 self.piecewise_rate_reserved,
1231 PIECEWISE_RATE_RESERVED_VALUE,
1232 "piecewise_rate.reserved",
1233 )? << PIECEWISE_RATE_RESERVED_SHIFT)
1234 | ((rate >> 16) as u8 & PIECEWISE_RATE_HI_MASK);
1235 buf[cursor + 1] = (rate >> 8) as u8;
1236 buf[cursor + 2] = rate as u8;
1237 cursor += 3;
1238 }
1239 if let Some(ss) = self.seamless_splice {
1240 buf[cursor..cursor + 5].copy_from_slice(&ss.to_marked_field()?);
1242 cursor += 5;
1243 }
1244 buf[cursor..cursor + self.trailing.len()].copy_from_slice(self.trailing);
1245 cursor += self.trailing.len();
1246 Ok(cursor)
1247 }
1248}
1249
1250#[non_exhaustive]
1259#[derive(Clone, Debug, PartialEq, Eq)]
1260#[cfg_attr(feature = "serde", derive(serde::Serialize))]
1261pub struct AdaptationField<'a> {
1262 pub discontinuity_indicator: bool,
1264 pub random_access_indicator: bool,
1266 pub elementary_stream_priority_indicator: bool,
1268 pub pcr: Option<Pcr>,
1270 pub opcr: Option<Pcr>,
1272 pub splice_countdown: Option<i8>,
1274 pub transport_private_data: Option<&'a [u8]>,
1279 pub extension: Option<AdaptationFieldExtension<'a>>,
1281 pub pcr_reserved: u8,
1287 pub opcr_reserved: u8,
1289 pub stuffing: &'a [u8],
1299}
1300
1301impl Default for AdaptationField<'_> {
1302 fn default() -> Self {
1303 Self::new()
1304 }
1305}
1306
1307pub(crate) fn set_pcr_reserved(field: &mut [u8], reserved: u8) -> Result<()> {
1309 let reserved = broadcast_common::len::fit_bits(
1310 u64::from(reserved),
1311 PCR_RESERVED_BITS_COUNT,
1312 "pcr_reserved",
1313 )?;
1314 field[4] = (field[4] & !PCR_RESERVED_BITS)
1315 | (((reserved as u8) << PCR_RESERVED_SHIFT) & PCR_RESERVED_BITS);
1316 Ok(())
1317}
1318
1319impl<'a> AdaptationField<'a> {
1320 #[must_use]
1324 pub const fn new() -> Self {
1325 Self {
1326 discontinuity_indicator: false,
1327 random_access_indicator: false,
1328 elementary_stream_priority_indicator: false,
1329 pcr: None,
1330 opcr: None,
1331 splice_countdown: None,
1332 transport_private_data: None,
1333 extension: None,
1334 pcr_reserved: PCR_RESERVED_VALUE,
1335 opcr_reserved: PCR_RESERVED_VALUE,
1336 stuffing: &[],
1337 }
1338 }
1339
1340 pub(crate) fn parse(af: &'a [u8]) -> Result<Self> {
1347 let flags = *af.first().ok_or(Error::BufferTooShort(
1348 broadcast_common::error::BufferTooShort {
1349 need: 1,
1350 have: 0,
1351 what: "adaptation_field flags",
1352 },
1353 ))?;
1354 let mut cursor = 1usize;
1355
1356 let mut pcr_reserved = PCR_RESERVED_VALUE;
1357 let mut opcr_reserved = PCR_RESERVED_VALUE;
1358 let pcr = if flags & AF_PCR_FLAG != 0 {
1359 let p = Pcr::parse(af, cursor)?;
1360 pcr_reserved = (af[cursor + 4] & PCR_RESERVED_BITS) >> PCR_RESERVED_SHIFT;
1361 cursor += PCR_FIELD_LEN;
1362 Some(p)
1363 } else {
1364 None
1365 };
1366 let opcr = if flags & AF_OPCR_FLAG != 0 {
1367 let p = Pcr::parse(af, cursor)?;
1368 opcr_reserved = (af[cursor + 4] & PCR_RESERVED_BITS) >> PCR_RESERVED_SHIFT;
1369 cursor += PCR_FIELD_LEN;
1370 Some(p)
1371 } else {
1372 None
1373 };
1374 let splice_countdown = if flags & AF_SPLICING_FLAG != 0 {
1375 let b = *af.get(cursor).ok_or(Error::BufferTooShort(
1376 broadcast_common::error::BufferTooShort {
1377 need: cursor + 1,
1378 have: af.len(),
1379 what: "adaptation_field splice_countdown",
1380 },
1381 ))?;
1382 cursor += 1;
1383 Some(b as i8)
1384 } else {
1385 None
1386 };
1387
1388 let transport_private_data = if flags & AF_TRANSPORT_PRIVATE_DATA_FLAG != 0 {
1391 let tpd_len = *af.get(cursor).ok_or(Error::BufferTooShort(
1392 broadcast_common::error::BufferTooShort {
1393 need: cursor + 1,
1394 have: af.len(),
1395 what: "transport_private_data_length",
1396 },
1397 ))? as usize;
1398 cursor += 1;
1399 let end = cursor + tpd_len;
1400 let slice = af.get(cursor..end).ok_or(Error::BufferTooShort(
1401 broadcast_common::error::BufferTooShort {
1402 need: end,
1403 have: af.len(),
1404 what: "transport_private_data",
1405 },
1406 ))?;
1407 cursor = end;
1408 Some(slice)
1409 } else {
1410 None
1411 };
1412
1413 let extension = if flags & AF_EXTENSION_FLAG != 0 {
1415 let ext_data = af.get(cursor..).ok_or(Error::BufferTooShort(
1416 broadcast_common::error::BufferTooShort {
1417 need: cursor + 1,
1418 have: af.len(),
1419 what: "adaptation_field_extension",
1420 },
1421 ))?;
1422 let ext = AdaptationFieldExtension::parse(ext_data)?;
1423 if !ext_data.is_empty() {
1425 let _ext_len = ext_data[0] as usize;
1426 cursor += 1 + _ext_len;
1427 }
1428 Some(ext)
1429 } else {
1430 None
1431 };
1432
1433 let stuffing = af.get(cursor..).unwrap_or(&[]);
1437
1438 Ok(AdaptationField {
1439 discontinuity_indicator: flags & AF_DISCONTINUITY != 0,
1440 random_access_indicator: flags & AF_RANDOM_ACCESS != 0,
1441 elementary_stream_priority_indicator: flags & AF_ES_PRIORITY != 0,
1442 pcr,
1443 opcr,
1444 splice_countdown,
1445 transport_private_data,
1446 extension,
1447 pcr_reserved,
1448 opcr_reserved,
1449 stuffing,
1450 })
1451 }
1452
1453 #[must_use]
1459 pub fn serialized_len(&self) -> usize {
1460 let mut n = 1usize; if self.pcr.is_some() {
1462 n += PCR_FIELD_LEN;
1463 }
1464 if self.opcr.is_some() {
1465 n += PCR_FIELD_LEN;
1466 }
1467 if self.splice_countdown.is_some() {
1468 n += 1;
1469 }
1470 if let Some(tpd) = self.transport_private_data {
1471 n += 1 + tpd.len(); }
1473 if let Some(ref ext) = self.extension {
1474 n += ext.serialized_len();
1475 }
1476 n += self.stuffing.len();
1477 n
1478 }
1479
1480 pub fn serialize_into(&self, buf: &mut [u8]) -> Result<usize> {
1491 let need = self.serialized_len();
1492 need_out(buf, need)?;
1493
1494 let mut flags = 0u8;
1496 if self.discontinuity_indicator {
1497 flags |= AF_DISCONTINUITY;
1498 }
1499 if self.random_access_indicator {
1500 flags |= AF_RANDOM_ACCESS;
1501 }
1502 if self.elementary_stream_priority_indicator {
1503 flags |= AF_ES_PRIORITY;
1504 }
1505 if self.pcr.is_some() {
1506 flags |= AF_PCR_FLAG;
1507 }
1508 if self.opcr.is_some() {
1509 flags |= AF_OPCR_FLAG;
1510 }
1511 if self.splice_countdown.is_some() {
1512 flags |= AF_SPLICING_FLAG;
1513 }
1514 if self.transport_private_data.is_some() {
1515 flags |= AF_TRANSPORT_PRIVATE_DATA_FLAG;
1516 }
1517 if self.extension.is_some() {
1518 flags |= AF_EXTENSION_FLAG;
1519 }
1520 buf[0] = flags;
1521
1522 let mut cursor = 1usize;
1523 if let Some(pcr) = self.pcr {
1524 buf[cursor..cursor + PCR_FIELD_LEN].copy_from_slice(&pcr.to_field_bytes());
1525 set_pcr_reserved(&mut buf[cursor..cursor + PCR_FIELD_LEN], self.pcr_reserved)?;
1526 cursor += PCR_FIELD_LEN;
1527 }
1528 if let Some(opcr) = self.opcr {
1529 buf[cursor..cursor + PCR_FIELD_LEN].copy_from_slice(&opcr.to_field_bytes());
1530 set_pcr_reserved(&mut buf[cursor..cursor + PCR_FIELD_LEN], self.opcr_reserved)?;
1531 cursor += PCR_FIELD_LEN;
1532 }
1533 if let Some(sc) = self.splice_countdown {
1534 buf[cursor] = sc as u8;
1535 cursor += 1;
1536 }
1537 if let Some(tpd) = self.transport_private_data {
1538 buf[cursor] = broadcast_common::len::fit_u8(
1539 tpd.len(),
1540 "adaptation_field.transport_private_data_length",
1541 )?;
1542 cursor += 1;
1543 buf[cursor..cursor + tpd.len()].copy_from_slice(tpd);
1544 cursor += tpd.len();
1545 }
1546 if let Some(ref ext) = self.extension {
1547 let written = ext.serialize_into(&mut buf[cursor..])?;
1548 cursor += written;
1549 }
1550
1551 buf[cursor..cursor + self.stuffing.len()].copy_from_slice(self.stuffing);
1554 cursor += self.stuffing.len();
1555
1556 Ok(cursor)
1557 }
1558}
1559
1560#[derive(Default)]
1565pub struct SectionReassembler {
1566 buf: bytes::BytesMut,
1567 ready: alloc::collections::VecDeque<bytes::Bytes>,
1568 last_continuity_counter: Option<ContinuityCounter>,
1569}
1570
1571impl SectionReassembler {
1572 pub fn feed(&mut self, payload: &[u8], pusi: bool) {
1580 self.last_continuity_counter = None;
1581 self.feed_payload(payload, pusi);
1582 }
1583
1584 pub fn feed_with_continuity(
1598 &mut self,
1599 payload: &[u8],
1600 pusi: bool,
1601 continuity_counter: ContinuityCounter,
1602 discontinuity: bool,
1603 ) {
1604 let duplicate = !discontinuity && self.last_continuity_counter == Some(continuity_counter);
1605 self.last_continuity_counter = Some(continuity_counter);
1606 if duplicate && !pusi {
1607 return;
1608 }
1609 self.feed_payload(payload, pusi);
1610 }
1611
1612 fn feed_payload(&mut self, payload: &[u8], pusi: bool) {
1613 if pusi {
1614 if payload.is_empty() {
1617 self.buf.clear();
1618 return;
1619 }
1620 let pointer = payload[0] as usize;
1621
1622 if !self.buf.is_empty() && pointer > 0 {
1630 let avail = payload.len() - 1;
1631 let tail_len = pointer.min(avail);
1632 if self.buf.len() + tail_len > MAX_SECTION_SIZE {
1633 self.buf.clear();
1634 } else {
1635 self.buf.extend_from_slice(&payload[1..1 + tail_len]);
1636 self.drain_complete_sections();
1637 }
1638 }
1639
1640 self.buf.clear();
1643
1644 let start = 1 + pointer;
1645 if start >= payload.len() {
1646 return;
1648 }
1649 let new_data = &payload[start..];
1650 if new_data.len() > MAX_SECTION_SIZE {
1651 return;
1652 }
1653 self.buf.extend_from_slice(new_data);
1654 } else {
1655 if self.buf.is_empty() {
1656 return;
1657 }
1658 let take = if let Some(exp) = section_total_len(&self.buf) {
1668 exp.saturating_sub(self.buf.len()).min(payload.len())
1669 } else {
1670 payload.len().min(MAX_SECTION_SIZE - self.buf.len())
1674 };
1675 self.buf.extend_from_slice(&payload[..take]);
1676 }
1677
1678 self.drain_complete_sections();
1679 }
1680
1681 fn drain_complete_sections(&mut self) {
1692 loop {
1693 if self.buf.len() < SECTION_HEADER_LEN {
1694 break;
1697 }
1698 if self.buf[0] == STUFFING_BYTE {
1699 self.buf.clear();
1701 break;
1702 }
1703 let Some(exp) = section_total_len(&self.buf) else {
1706 break;
1707 };
1708 if self.buf.len() >= exp {
1709 let section = self.buf.split_to(exp).freeze();
1710 self.ready.push_back(section);
1711 } else {
1712 break;
1714 }
1715 }
1716 }
1717
1718 pub fn pop_section(&mut self) -> Option<bytes::Bytes> {
1720 self.ready.pop_front()
1721 }
1722
1723 pub fn len(&self) -> usize {
1725 self.buf.len()
1726 }
1727
1728 pub fn is_empty(&self) -> bool {
1730 self.buf.is_empty()
1731 }
1732}
1733
1734pub fn iter_packets(buf: &[u8]) -> impl Iterator<Item = TsPacket<'_>> {
1752 buf.chunks_exact(TS_PACKET_SIZE)
1753 .filter_map(|chunk| TsPacket::parse(chunk).ok())
1754}
1755
1756pub fn extract_ts_payload(pkt: &[u8]) -> Option<&[u8]> {
1766 if pkt.len() < 4 {
1767 return None;
1768 }
1769 let header = TsHeader::parse(&pkt[..4]).ok()?;
1770 if !header.has_payload() {
1771 return None;
1772 }
1773 let cursor = 4 + adaptation_field_skip(pkt, header.has_adaptation());
1774 if cursor < pkt.len() {
1775 Some(&pkt[cursor..])
1776 } else {
1777 None
1778 }
1779}
1780
1781#[cfg(test)]
1782mod tests {
1783 use super::*;
1784
1785 fn cc(v: u8) -> ContinuityCounter {
1786 ContinuityCounter::try_new(v).expect("4-bit counter")
1787 }
1788 use alloc::string::ToString;
1789 use alloc::vec;
1790 use alloc::vec::Vec;
1791
1792 fn make_packet(b1: u8, b2: u8, b3: u8, payload_data: &[u8]) -> [u8; TS_PACKET_SIZE] {
1794 let mut pkt = [0u8; TS_PACKET_SIZE];
1795 pkt[0] = TS_SYNC_BYTE;
1796 pkt[1] = b1;
1797 pkt[2] = b2;
1798 pkt[3] = b3;
1799 let payload_start = 4;
1800 let end = (payload_start + payload_data.len()).min(TS_PACKET_SIZE);
1801 let len = (end - payload_start).min(payload_data.len());
1802 pkt[payload_start..payload_start + len].copy_from_slice(&payload_data[..len]);
1803 pkt
1804 }
1805
1806 #[test]
1807 fn parse_rejects_non_0x47_sync_byte() {
1808 let mut pkt = [0u8; TS_PACKET_SIZE];
1809 pkt[0] = 0x46; let err = TsPacket::parse(&pkt).unwrap_err();
1811 match err {
1812 Error::InvalidSync(e) => assert_eq!(e.found, 0x46),
1813 other => panic!("expected InvalidSyncByte, got {other:?}"),
1814 }
1815 }
1816
1817 #[test]
1818 fn ts_header_round_trip() {
1819 let cases = [
1822 TsHeader {
1823 tei: false,
1824 pusi: true,
1825 pid: Pid::from_const(0x0000),
1826 scrambling: ScramblingControl::NotScrambled,
1827 adaptation_field_control: AdaptationFieldControl::PayloadOnly,
1828 continuity_counter: ContinuityCounter::ZERO,
1829 },
1830 TsHeader {
1831 tei: true,
1832 pusi: false,
1833 pid: Pid::from_const(0x1FFF),
1834 scrambling: ScramblingControl::OddKey,
1835 adaptation_field_control: AdaptationFieldControl::AdaptationAndPayload,
1836 continuity_counter: ContinuityCounter::try_new(0x0F).expect("4-bit counter"),
1837 },
1838 TsHeader {
1839 tei: false,
1840 pusi: false,
1841 pid: Pid::from_const(0x0100),
1842 scrambling: ScramblingControl::EvenKey,
1843 adaptation_field_control: AdaptationFieldControl::AdaptationOnly,
1844 continuity_counter: ContinuityCounter::try_new(7).expect("4-bit counter"),
1845 },
1846 ];
1847 for h in cases {
1848 let mut buf = [0u8; 4];
1849 assert_eq!(h.serialize_into(&mut buf).unwrap(), 4);
1850 assert_eq!(TsHeader::parse(&buf).unwrap(), h, "round-trip mismatch");
1851 }
1852 }
1853
1854 #[test]
1855 fn parse_extracts_pid_and_continuity_counter() {
1856 let pkt = make_packet(0x12, 0x34, 0x05, &[]);
1862 let pkt = TsPacket::parse(&pkt).unwrap();
1863 assert_eq!(pkt.header.pid, Pid::from_const(0x1234));
1864 assert_eq!(pkt.header.continuity_counter.value(), 5);
1865 }
1866
1867 #[test]
1868 fn payload_unit_start_indicator_flag_extracted() {
1869 let pkt1 = make_packet(0x40, 0x00, 0x00, &[]);
1871 let pkt1 = TsPacket::parse(&pkt1).unwrap();
1872 assert!(pkt1.header.pusi);
1873
1874 let pkt2 = make_packet(0x00, 0x00, 0x00, &[]);
1876 let pkt2 = TsPacket::parse(&pkt2).unwrap();
1877 assert!(!pkt2.header.pusi);
1878 }
1879
1880 fn build_pusi_payload(pointer_field: u8, previous_tail: &[u8], section: &[u8]) -> Vec<u8> {
1885 assert_eq!(pointer_field as usize, previous_tail.len());
1886 let mut v = Vec::with_capacity(1 + previous_tail.len() + section.len());
1887 v.push(pointer_field);
1888 v.extend_from_slice(previous_tail);
1889 v.extend_from_slice(section);
1890 v
1891 }
1892
1893 #[test]
1899 fn reassembler_accumulates_multi_packet_section() {
1900 let body = vec![0xAAu8; 197];
1902 let section = test_fixtures::psi::short_section(0x02, &body);
1903 assert_eq!(section.len(), 200);
1904
1905 let first_chunk = 100;
1906 let payload1 = build_pusi_payload(0, &[], §ion[..first_chunk]);
1907 let payload2 = section[first_chunk..].to_vec();
1908
1909 let mut reasm = SectionReassembler::default();
1910 reasm.feed(&payload1, true);
1911 reasm.feed(&payload2, false);
1912
1913 let out = reasm.pop_section().expect("section should be ready");
1914 assert_eq!(out.len(), 200);
1915 assert_eq!(out.as_ref(), §ion[..]);
1916 }
1917
1918 #[test]
1919 fn reassembler_yields_complete_section_once_length_satisfied() {
1920 let section = test_fixtures::psi::short_section(0x42, &[0xAA]);
1922 assert_eq!(section.len(), 4);
1923 let payload = build_pusi_payload(0, &[], §ion);
1924
1925 let mut reasm = SectionReassembler::default();
1926 reasm.feed(&payload, true);
1927
1928 let out = reasm
1929 .pop_section()
1930 .expect("single-packet section should pop");
1931 assert_eq!(out.as_ref(), §ion[..]);
1932 }
1933
1934 #[test]
1935 fn reassembler_extracts_all_concatenated_sections_in_one_payload() {
1936 let s1 = test_fixtures::psi::short_section(0x42, &[0x11, 0x22]); let s2 = test_fixtures::psi::short_section(0x46, &[0x33]); let s3 = test_fixtures::psi::short_section(0x4A, &[0x44, 0x55, 0x66]); let mut concat = Vec::new();
1945 concat.extend_from_slice(&s1);
1946 concat.extend_from_slice(&s2);
1947 concat.extend_from_slice(&s3);
1948 let payload = build_pusi_payload(0, &[], &concat);
1949
1950 let mut reasm = SectionReassembler::default();
1951 reasm.feed(&payload, true);
1952
1953 let got: Vec<_> = core::iter::from_fn(|| reasm.pop_section()).collect();
1955 assert_eq!(got.len(), 3, "all three concatenated sections must pop");
1956 assert_eq!(got[0].as_ref(), &s1[..]);
1957 assert_eq!(got[1].as_ref(), &s2[..]);
1958 assert_eq!(got[2].as_ref(), &s3[..]);
1959 }
1960
1961 #[test]
1962 fn reassembler_stops_at_stuffing_after_concatenated_sections() {
1963 let s1 = test_fixtures::psi::short_section(0x42, &[0xAA]); let s2 = test_fixtures::psi::short_section(0x46, &[0xBB, 0xCC]); let mut concat = Vec::new();
1969 concat.extend_from_slice(&s1);
1970 concat.extend_from_slice(&s2);
1971 concat.extend_from_slice(&[0xFF, 0xFF, 0xFF, 0xFF]); let payload = build_pusi_payload(0, &[], &concat);
1973
1974 let mut reasm = SectionReassembler::default();
1975 reasm.feed(&payload, true);
1976
1977 let got: Vec<_> = core::iter::from_fn(|| reasm.pop_section()).collect();
1978 assert_eq!(got.len(), 2);
1979 assert_eq!(got[0].as_ref(), &s1[..]);
1980 assert_eq!(got[1].as_ref(), &s2[..]);
1981 assert!(
1982 reasm.is_empty(),
1983 "stuffing tail must be discarded, not buffered"
1984 );
1985 }
1986
1987 #[test]
1988 fn reassembler_concatenated_then_spanning_tail() {
1989 let s1 = test_fixtures::psi::short_section(0x42, &[0x01, 0x02]); let s2 = test_fixtures::psi::short_section(0x46, &[0x09u8; 60]); let split = 30;
1995
1996 let mut head = Vec::new();
1997 head.extend_from_slice(&s1);
1998 head.extend_from_slice(&s2[..split]);
1999 let payload1 = build_pusi_payload(0, &[], &head);
2000 let payload2 = s2[split..].to_vec();
2001
2002 let mut reasm = SectionReassembler::default();
2003 reasm.feed(&payload1, true);
2004 let first = reasm.pop_section().expect("first section pops at once");
2005 assert_eq!(first.as_ref(), &s1[..]);
2006 assert!(reasm.pop_section().is_none(), "second is still partial");
2007
2008 reasm.feed(&payload2, false);
2009 let second = reasm.pop_section().expect("second pops after continuation");
2010 assert_eq!(second.as_ref(), &s2[..]);
2011 }
2012
2013 #[test]
2014 fn reassembler_completes_section_spanning_into_pusi_packet() {
2015 let spanning = test_fixtures::psi::short_section(0x42, &[0x5Au8; 62]); let head = 41;
2023 let tail = &spanning[head..]; assert_eq!(tail.len(), 24);
2025
2026 let next = test_fixtures::psi::short_section(0x46, &[0x77, 0x88]); let payload_a = build_pusi_payload(0, &[], &spanning[..head]);
2031 let payload_b = build_pusi_payload(24, tail, &next);
2033
2034 let mut reasm = SectionReassembler::default();
2035 reasm.feed(&payload_a, true);
2036 assert!(reasm.pop_section().is_none(), "head alone is incomplete");
2037
2038 reasm.feed(&payload_b, true);
2039 let got: Vec<_> = core::iter::from_fn(|| reasm.pop_section()).collect();
2040 assert_eq!(got.len(), 2, "spanning section + new section must both pop");
2041 assert_eq!(
2042 got[0].as_ref(),
2043 &spanning[..],
2044 "spanning section completed from B's pointer tail"
2045 );
2046 assert_eq!(got[1].as_ref(), &next[..]);
2047 }
2048
2049 #[test]
2050 fn reassembler_pusi_pointer_spans_whole_payload() {
2051 let spanning = test_fixtures::psi::short_section(0x42, &[0x33u8; 40]); let head = 20;
2056 let payload_a = build_pusi_payload(0, &[], &spanning[..head]);
2057 let tail = &spanning[head..]; let mut reasm = SectionReassembler::default();
2060 reasm.feed(&payload_a, true);
2061 reasm.feed(&build_pusi_payload_pointer_spanning_all(tail), true);
2063
2064 let out = reasm.pop_section().expect("spanning section completes");
2065 assert_eq!(out.as_ref(), &spanning[..]);
2066 assert!(reasm.pop_section().is_none());
2067 }
2068
2069 fn build_pusi_payload_pointer_spanning_all(tail: &[u8]) -> Vec<u8> {
2072 let mut v = Vec::with_capacity(1 + tail.len());
2073 v.push(tail.len() as u8);
2074 v.extend_from_slice(tail);
2075 v
2076 }
2077
2078 #[test]
2079 fn reassembler_discards_a_retransmitted_continuation_packet() {
2080 let mut section = vec![0x4Eu8, 0xB0, 0x00];
2081 section.resize(300, 0x5A);
2082 section[1] = 0xB0 | (((300 - 3) >> 8) as u8);
2083 section[2] = ((300 - 3) & 0xFF) as u8;
2084 let mut first = vec![0x00u8];
2085 first.extend_from_slice(§ion[..183]);
2086
2087 let mut reasm = SectionReassembler::default();
2088 reasm.feed_with_continuity(&first, true, cc(0), false);
2089 reasm.feed_with_continuity(§ion[183..250], false, cc(1), false);
2090 reasm.feed_with_continuity(§ion[183..250], false, cc(1), false);
2091 reasm.feed_with_continuity(§ion[250..], false, cc(2), false);
2092
2093 let out = reasm.pop_section().expect("section survives the duplicate");
2094 assert_eq!(out.as_ref(), §ion[..]);
2095 assert!(reasm.pop_section().is_none());
2096 }
2097
2098 #[test]
2099 fn a_packet_after_a_discontinuity_with_an_unchanged_counter_is_not_a_duplicate() {
2100 let mut section = vec![0x4Eu8, 0xB0, 0x00];
2101 section.resize(300, 0x5A);
2102 section[1] = 0xB0 | (((300 - 3) >> 8) as u8);
2103 section[2] = ((300 - 3) & 0xFF) as u8;
2104 let mut first = vec![0x00u8];
2105 first.extend_from_slice(§ion[..183]);
2106
2107 let mut reasm = SectionReassembler::default();
2108 reasm.feed_with_continuity(&first, true, cc(0), false);
2109 reasm.feed_with_continuity(§ion[183..250], false, cc(0), true);
2110 reasm.feed_with_continuity(§ion[250..], false, cc(1), false);
2111
2112 let out = reasm
2113 .pop_section()
2114 .expect("section survives the discontinuity");
2115 assert_eq!(out.as_ref(), §ion[..]);
2116 assert!(reasm.pop_section().is_none());
2117 }
2118
2119 #[test]
2120 fn reassembler_completes_max_length_section_and_stays_usable() {
2121 let mut section = Vec::with_capacity(MAX_SECTION_SIZE);
2127 section.push(0x00); section.push(0xB0 | ((4095u16 >> 8) as u8 & 0x0F));
2129 section.push(0xFF); section.resize(MAX_SECTION_SIZE, 0u8);
2131 assert_eq!(section.len(), MAX_SECTION_SIZE);
2132
2133 let mut reasm = SectionReassembler::default();
2134 let mut first = vec![0x00u8]; first.extend_from_slice(§ion[..183]);
2136 reasm.feed(&first, true);
2137 assert!(
2138 reasm.pop_section().is_none(),
2139 "incomplete until the declared length arrives"
2140 );
2141
2142 for chunk in section[183..].chunks(184) {
2143 reasm.feed(chunk, false);
2144 }
2145 let out = reasm
2146 .pop_section()
2147 .expect("max-length section completes at its declared length");
2148 assert_eq!(out.len(), MAX_SECTION_SIZE);
2149 assert_eq!(out.as_ref(), §ion[..]);
2150 assert!(reasm.is_empty());
2151
2152 reasm.feed(&[0u8; 184], false);
2156 assert!(reasm.pop_section().is_none());
2157
2158 let valid_section = test_fixtures::psi::short_section(0x00, &[0xAA]);
2160 let payload2 = build_pusi_payload(0, &[], &valid_section);
2161 reasm.feed(&payload2, true);
2162 let out = reasm
2163 .pop_section()
2164 .expect("fresh section should pop after reset");
2165 assert_eq!(out.as_ref(), &valid_section[..]);
2166 }
2167
2168 #[test]
2169 fn reassembler_handles_pusi_with_nonzero_pointer_field() {
2170 let prior_tail = vec![0x11, 0x22, 0x33];
2172 let new_section = test_fixtures::psi::short_section(0x02, &[0xBB]);
2173 assert_eq!(new_section.len(), 4);
2174 let payload = build_pusi_payload(3, &prior_tail, &new_section);
2175
2176 let mut reasm = SectionReassembler::default();
2177 reasm.feed(&payload, true);
2178
2179 let out = reasm
2180 .pop_section()
2181 .expect("section after pointer_field skip should pop");
2182 assert_eq!(out.as_ref(), &new_section[..]);
2183 }
2184
2185 #[test]
2186 fn reassembler_ignores_continuation_before_pusi() {
2187 let pkt = make_packet(0x00, 0x00, PAYLOAD_FLAG, &[0xAA, 0xBB, 0xCC]);
2190
2191 let mut reasm = SectionReassembler::default();
2192 reasm.feed(&pkt[4..], false); assert!(
2195 reasm.pop_section().is_none(),
2196 "no section should appear without prior PUSI"
2197 );
2198 assert!(
2199 reasm.pop_section().is_none(),
2200 "second pop should also be none"
2201 );
2202 }
2203
2204 #[test]
2207 fn reassembler_empty_pusi_payload_does_not_panic() {
2208 let mut reasm = SectionReassembler::default();
2209 reasm.feed(&[], true);
2210 assert!(reasm.pop_section().is_none());
2211 let payload = vec![0x00u8, 0x72, 0x70, 0x01, 0x00];
2213 reasm.feed(&payload, true);
2214 assert!(reasm.pop_section().is_some());
2215 }
2216
2217 #[test]
2221 fn reassembler_accepts_maximal_private_section() {
2222 let mut section = vec![0x80u8, 0x7F, 0xFF]; section.resize(3 + 0xFFF, 0xAB);
2224
2225 let mut reasm = SectionReassembler::default();
2226 let mut first = vec![0x00];
2228 first.extend_from_slice(§ion[..183]);
2229 reasm.feed(&first, true);
2230 for chunk in section[183..].chunks(184) {
2231 reasm.feed(chunk, false);
2232 }
2233 let out = reasm.pop_section().expect("4098-byte section should pop");
2234 assert_eq!(out.len(), 4098);
2235 assert_eq!(out.as_ref(), §ion[..]);
2236 }
2237
2238 #[test]
2243 fn reassembler_completes_large_section_with_trailing_stuffing() {
2244 let body = vec![0x5Au8; 4096 - 3];
2245 let section = test_fixtures::psi::short_section(0x50, &body); assert_eq!(section.len(), 4096);
2247
2248 let mut reasm = SectionReassembler::default();
2249 let mut first = vec![0x00u8];
2251 first.extend_from_slice(§ion[..183]);
2252 reasm.feed(&first, true);
2253
2254 let mut pos = 183usize;
2258 while pos < section.len() {
2259 let take = (section.len() - pos).min(184);
2260 let mut payload = section[pos..pos + take].to_vec();
2261 if take < 184 {
2262 payload.resize(184, 0xFF); }
2264 reasm.feed(&payload, false);
2265 pos += take;
2266 }
2267
2268 let out = reasm
2269 .pop_section()
2270 .expect("4096-byte section must complete despite trailing stuffing (#148)");
2271 assert_eq!(out.len(), 4096);
2272 assert_eq!(out.as_ref(), §ion[..]);
2273 assert!(reasm.is_empty(), "stuffing tail must be discarded");
2274 }
2275
2276 #[test]
2279 fn pcr_as_27mhz_known_value() {
2280 assert_eq!(
2281 Pcr::from_parts(10_000, 0).expect("in range").as_27mhz(),
2282 3_000_000
2283 );
2284 assert_eq!(Pcr::from_parts(1, 100).expect("in range").as_27mhz(), 400);
2286 }
2287
2288 #[test]
2289 fn pcr_decode_from_bytes() {
2290 let af = [0x10u8, 0x00, 0x00, 0x13, 0x88, 0x7E, 0x00];
2292 let pcr = Pcr::parse(&af, 1).expect("6 bytes present");
2293 assert_eq!(pcr, Pcr::from_parts(10_000, 0).expect("in range"));
2294 assert_eq!((pcr.base(), pcr.extension()), (10_000, 0));
2295 assert_eq!(pcr.as_27mhz(), 3_000_000);
2296 }
2297
2298 #[test]
2299 fn adaptation_field_flags_and_pcr() {
2300 let mut raw = [0xAAu8; TS_PACKET_SIZE];
2301 raw[0] = TS_SYNC_BYTE;
2302 raw[1] = 0x01; raw[2] = 0x00;
2304 raw[3] = ADAPTATION_FLAG | PAYLOAD_FLAG;
2305 raw[4] = 7; raw[5] = AF_DISCONTINUITY | AF_PCR_FLAG;
2307 raw[6..12].copy_from_slice(&[0x00, 0x00, 0x13, 0x88, 0x7E, 0x00]);
2308 let pkt = TsPacket::parse(&raw).expect("valid packet");
2311 let af = pkt
2312 .adaptation_field()
2313 .expect("has adaptation field")
2314 .expect("adaptation field parses");
2315 assert!(af.discontinuity_indicator);
2316 assert!(!af.random_access_indicator);
2317 assert_eq!(af.pcr, Some(Pcr::from_parts(10_000, 0).expect("in range")));
2318 assert_eq!(af.pcr.unwrap().as_27mhz(), 3_000_000);
2319 assert!(af.opcr.is_none());
2320 assert!(af.splice_countdown.is_none());
2321 let payload = pkt.payload.expect("payload present");
2323 assert_eq!(payload.len(), TS_PACKET_SIZE - 12);
2324 assert_eq!(payload[0], 0xAA);
2325 }
2326
2327 #[test]
2333 fn clock_reference_slot_locates_pcr_then_opcr_and_rejects_unreached_fields() {
2334 let mut raw = [0xAAu8; TS_PACKET_SIZE];
2335 raw[0] = TS_SYNC_BYTE;
2336 raw[3] = ADAPTATION_FLAG | PAYLOAD_FLAG;
2337 raw[4] = (1 + 2 * PCR_FIELD_LEN) as u8; raw[5] = AF_PCR_FLAG | AF_OPCR_FLAG;
2339
2340 assert!(matches!(
2342 clock_reference_slot(&raw, AF_PCR_FLAG),
2343 ClockReferenceSlot::Field(r) if r == (CLOCK_REFERENCE_START..CLOCK_REFERENCE_START + PCR_FIELD_LEN)
2344 ));
2345 assert!(matches!(
2346 clock_reference_slot(&raw, AF_OPCR_FLAG),
2347 ClockReferenceSlot::Field(r) if r == (CLOCK_REFERENCE_START + PCR_FIELD_LEN..CLOCK_REFERENCE_START + 2 * PCR_FIELD_LEN)
2348 ));
2349
2350 raw[4] = (1 + PCR_FIELD_LEN) as u8;
2353 assert!(matches!(
2354 clock_reference_slot(&raw, AF_OPCR_FLAG),
2355 ClockReferenceSlot::TooShort { need, have }
2356 if need == 1 + 2 * PCR_FIELD_LEN && have == 1 + PCR_FIELD_LEN
2357 ));
2358
2359 let payload_only = {
2361 let mut p = raw;
2362 p[3] = PAYLOAD_FLAG;
2363 p
2364 };
2365 assert!(matches!(
2366 clock_reference_slot(&payload_only, AF_PCR_FLAG),
2367 ClockReferenceSlot::NoAdaptationField
2368 ));
2369
2370 raw[4] = (1 + PCR_FIELD_LEN) as u8;
2372 raw[5] = AF_OPCR_FLAG;
2373 assert!(matches!(
2374 clock_reference_slot(&raw, AF_PCR_FLAG),
2375 ClockReferenceSlot::FlagClear
2376 ));
2377
2378 raw[5] = AF_PCR_FLAG;
2382 let truncated = &raw[..8];
2383 assert!(matches!(
2384 clock_reference_slot(truncated, AF_PCR_FLAG),
2385 ClockReferenceSlot::Truncated { need, have } if need == 12 && have == 8
2386 ));
2387 }
2388
2389 #[test]
2390 fn oversized_adaptation_field_length_is_rejected_not_truncated() {
2391 let mut raw = [0xAAu8; TS_PACKET_SIZE];
2397 raw[0] = TS_SYNC_BYTE;
2398 raw[1] = 0x01;
2399 raw[2] = 0x00;
2400 raw[3] = ADAPTATION_FLAG; raw[4] = 200; let pkt = TsPacket::parse(&raw).expect("header + af_len byte still parse");
2404 assert!(
2405 pkt.adaptation_field().is_none(),
2406 "an over-long adaptation field must be rejected, not truncated"
2407 );
2408 assert!(pkt.payload.is_none());
2409
2410 let owned = crate::owned::OwnedTsPacket::parse(raw).unwrap();
2412 assert!(owned.adaptation_field().is_none());
2413 }
2414
2415 #[test]
2416 fn no_adaptation_returns_none() {
2417 let mut raw = [0x00u8; TS_PACKET_SIZE];
2418 raw[0] = TS_SYNC_BYTE;
2419 raw[1] = 0x01;
2420 raw[3] = PAYLOAD_FLAG; let pkt = TsPacket::parse(&raw).expect("valid");
2422 assert!(pkt.adaptation_field().is_none());
2423 assert!(pkt.adaptation.is_none());
2424 }
2425
2426 #[test]
2427 fn adaptation_field_splice_countdown_negative() {
2428 let mut raw = [0xAAu8; TS_PACKET_SIZE];
2429 raw[0] = TS_SYNC_BYTE;
2430 raw[1] = 0x01;
2431 raw[2] = 0x00;
2432 raw[3] = ADAPTATION_FLAG | PAYLOAD_FLAG;
2433 raw[4] = 2; raw[5] = AF_SPLICING_FLAG;
2435 raw[6] = 0xFB; let pkt = TsPacket::parse(&raw).expect("valid");
2437 let af = pkt.adaptation_field().unwrap().unwrap();
2438 assert_eq!(af.splice_countdown, Some(-5));
2439 assert!(af.pcr.is_none());
2440 }
2441
2442 #[test]
2445 fn scrambling_control_all_values() {
2446 assert_eq!(
2447 ScramblingControl::from_bits(0b00),
2448 ScramblingControl::NotScrambled
2449 );
2450 assert_eq!(
2451 ScramblingControl::from_bits(0b01),
2452 ScramblingControl::Reserved
2453 );
2454 assert_eq!(
2455 ScramblingControl::from_bits(0b10),
2456 ScramblingControl::EvenKey
2457 );
2458 assert_eq!(
2459 ScramblingControl::from_bits(0b11),
2460 ScramblingControl::OddKey
2461 );
2462 assert_eq!(ScramblingControl::NotScrambled.name(), "not_scrambled");
2464 assert_eq!(ScramblingControl::Reserved.name(), "reserved");
2465 assert_eq!(ScramblingControl::EvenKey.name(), "even_key");
2466 assert_eq!(ScramblingControl::OddKey.name(), "odd_key");
2467 assert_eq!(ScramblingControl::NotScrambled.to_string(), "not_scrambled");
2469 assert_eq!(ScramblingControl::OddKey.to_string(), "odd_key");
2470 assert_eq!(
2472 ScramblingControl::from_bits(0xFF),
2473 ScramblingControl::OddKey
2474 );
2475 }
2476
2477 #[test]
2478 fn adaptation_field_control_all_values() {
2479 assert_eq!(
2480 AdaptationFieldControl::from_flags(false, false),
2481 AdaptationFieldControl::Reserved
2482 );
2483 assert_eq!(
2484 AdaptationFieldControl::from_flags(false, true),
2485 AdaptationFieldControl::PayloadOnly
2486 );
2487 assert_eq!(
2488 AdaptationFieldControl::from_flags(true, false),
2489 AdaptationFieldControl::AdaptationOnly
2490 );
2491 assert_eq!(
2492 AdaptationFieldControl::from_flags(true, true),
2493 AdaptationFieldControl::AdaptationAndPayload
2494 );
2495 assert_eq!(AdaptationFieldControl::Reserved.name(), "reserved");
2497 assert_eq!(AdaptationFieldControl::PayloadOnly.name(), "payload_only");
2498 assert_eq!(
2499 AdaptationFieldControl::AdaptationOnly.name(),
2500 "adaptation_only"
2501 );
2502 assert_eq!(
2503 AdaptationFieldControl::AdaptationAndPayload.name(),
2504 "adaptation_and_payload"
2505 );
2506 assert_eq!(
2508 AdaptationFieldControl::PayloadOnly.to_string(),
2509 "payload_only"
2510 );
2511 }
2512
2513 #[test]
2514 fn ts_header_field_types_carry_the_decoded_values() {
2515 let hdr = TsHeader {
2516 tei: false,
2517 pusi: false,
2518 pid: Pid::from_const(0x0100),
2519 scrambling: ScramblingControl::EvenKey,
2520 adaptation_field_control: AdaptationFieldControl::PayloadOnly,
2521 continuity_counter: ContinuityCounter::ZERO,
2522 };
2523 assert_eq!(hdr.scrambling, ScramblingControl::EvenKey);
2524 assert_eq!(
2525 hdr.adaptation_field_control,
2526 AdaptationFieldControl::PayloadOnly
2527 );
2528 assert!(hdr.has_payload());
2529 assert!(!hdr.has_adaptation());
2530
2531 let hdr_both = TsHeader {
2532 adaptation_field_control: AdaptationFieldControl::AdaptationAndPayload,
2533 ..hdr
2534 };
2535 assert_eq!(
2536 hdr_both.adaptation_field_control,
2537 AdaptationFieldControl::AdaptationAndPayload
2538 );
2539 assert!(hdr_both.has_adaptation() && hdr_both.has_payload());
2540 }
2541
2542 #[test]
2543 fn reserved_adaptation_field_control_is_preserved_through_parse_and_serialize() {
2544 let bytes = [TS_SYNC_BYTE, 0x00, 0x00, 0x05];
2547 let hdr = TsHeader::parse(&bytes).expect("parse");
2548 assert_eq!(
2549 hdr.adaptation_field_control,
2550 AdaptationFieldControl::Reserved
2551 );
2552 assert!(!hdr.has_adaptation() && !hdr.has_payload());
2553 let mut out = [0u8; 4];
2554 hdr.serialize_into(&mut out).expect("serialize");
2555 assert_eq!(out, bytes);
2556 }
2557
2558 #[test]
2561 fn iter_packets_yields_valid_and_skips_bad_sync() {
2562 let pkt1 = make_packet(0x00, 0x00, PAYLOAD_FLAG, &[0xAA; 10]);
2564 let pkt2 = make_packet(0x40, 0x64, PAYLOAD_FLAG, &[0xBB; 10]);
2565 let mut bad = [0u8; TS_PACKET_SIZE];
2566 bad[0] = 0x00; let mut buf = Vec::new();
2569 buf.extend_from_slice(&pkt1);
2570 buf.extend_from_slice(&pkt2);
2571 buf.extend_from_slice(&bad);
2572
2573 let pkts: Vec<_> = super::iter_packets(&buf).collect();
2574 assert_eq!(pkts.len(), 2, "bad sync packet must be skipped");
2575 assert_eq!(pkts[0].header.pid, Pid::from_const(0x0000));
2576 assert_eq!(pkts[1].header.pid, Pid::from_const(0x0064));
2577 }
2578
2579 #[test]
2580 fn extract_ts_payload_payload_only() {
2581 let pkt = make_packet(0x00, 0x00, PAYLOAD_FLAG, &[0xABu8; 10]);
2582 let p = super::extract_ts_payload(&pkt).expect("payload present");
2583 assert_eq!(p[0], 0xAB);
2584 assert_eq!(p.len(), TS_PACKET_SIZE - 4);
2585 }
2586
2587 #[test]
2588 fn extract_ts_payload_adaptation_only_returns_none() {
2589 let pkt = make_packet(0x00, 0x00, ADAPTATION_FLAG, &[]);
2590 assert!(super::extract_ts_payload(&pkt).is_none());
2591 }
2592
2593 #[test]
2598 fn pcr_from_27mhz_round_trips() {
2599 for &ticks in &[0u64, 1, 300, 27_000_000, u64::from(u32::MAX), 8_589_934_591] {
2600 let pcr = Pcr::from_27mhz(ticks).expect("in range");
2601 assert_eq!(pcr.as_27mhz(), ticks, "ticks={ticks}");
2602 }
2603 }
2604
2605 #[test]
2611 fn pcr_to_field_bytes_round_trips_parse() {
2612 let cases = [
2613 Pcr::from_parts(0, 0).expect("in range"),
2614 Pcr::from_parts(10_000, 0).expect("in range"),
2615 Pcr::from_parts(1, 100).expect("in range"),
2616 Pcr::from_parts(0x1_FFFF_FFFF, 299).expect("in range"),
2617 ];
2618 for pcr in cases {
2619 let bytes = pcr.to_field_bytes();
2620 let mut af = [0u8; 7];
2623 af[1..7].copy_from_slice(&bytes);
2624 let decoded = Pcr::parse(&af, 1).expect("parse round-trip");
2625 assert_eq!(decoded, pcr, "round-trip failed for {pcr:?}");
2626 }
2627 }
2628
2629 #[test]
2631 fn pcr_full_width_extension_round_trips_the_field() {
2632 let pcr = Pcr::from_parts(0x1_FFFF_FFFF, 299).expect("in range");
2633 assert_eq!(pcr.to_field_bytes(), [0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0x2B]);
2635 assert_eq!(Pcr::parse(&pcr.to_field_bytes(), 0).expect("parse"), pcr);
2636 assert_eq!(
2637 pcr.as_27mhz(),
2638 broadcast_common::clock33::PCR_WRAP_27MHZ - 1
2639 );
2640 }
2641
2642 #[test]
2646 fn pcr_off_clock_wire_extension_parses_losslessly_and_reports() {
2647 let mut bytes = Pcr::from_parts(5, 0).expect("in range").to_field_bytes();
2648 bytes[4] |= 0x01; bytes[5] = 0x2C; let pcr = Pcr::parse(&bytes, 0).expect("a wire-legal field parses");
2651 assert_eq!((pcr.base(), pcr.extension()), (5, 300));
2652 assert_eq!(
2653 pcr.to_field_bytes(),
2654 bytes,
2655 "re-serializes byte-identically"
2656 );
2657 assert!(!pcr.clock().is_valid());
2658 assert!(matches!(
2659 pcr.to_clock27(),
2660 Err(Error::ClockOutOfRange(
2661 broadcast_common::clock33::ClockOutOfRange {
2662 field: "27 MHz extension",
2663 value: 300,
2664 ..
2665 }
2666 ))
2667 ));
2668 for ext in 0u16..512 {
2670 let mut bytes = Pcr::from_parts(0x1_2345_6789 & ((1 << 33) - 1), 0)
2671 .expect("in range")
2672 .to_field_bytes();
2673 bytes[4] = (bytes[4] & !0x01) | ((ext >> 8) as u8 & 0x01);
2674 bytes[5] = (ext & 0xFF) as u8;
2675 let decoded = Pcr::parse(&bytes, 0).expect("extension is 9 bits on the wire");
2676 assert_eq!(decoded.extension(), ext);
2677 assert_eq!(decoded.to_field_bytes(), bytes);
2678 assert_eq!(decoded.to_clock27().is_ok(), ext < 300);
2679 }
2680 }
2681
2682 #[test]
2685 fn pcr_to_field_bytes_known_vector() {
2686 let pcr = Pcr::from_parts(10_000, 0).expect("in range");
2687 let bytes = pcr.to_field_bytes();
2688 assert_eq!(bytes, [0x00, 0x00, 0x13, 0x88, 0x7E, 0x00]);
2689 }
2690
2691 #[test]
2694 fn scrambling_control_to_bits_inverse_of_from_bits() {
2695 for bits in 0u8..=3 {
2696 let sc = ScramblingControl::from_bits(bits);
2697 assert_eq!(sc.to_bits(), bits, "to_bits() != from_bits() for {bits}");
2698 }
2699 }
2700
2701 #[test]
2704 fn adaptation_field_control_to_bits_inverse_of_from_flags() {
2705 let cases = [
2706 (false, false, 0b00u8),
2707 (false, true, 0b01),
2708 (true, false, 0b10),
2709 (true, true, 0b11),
2710 ];
2711 for (has_af, has_pl, expected_bits) in cases {
2712 let afc = AdaptationFieldControl::from_flags(has_af, has_pl);
2713 assert_eq!(afc.to_bits(), expected_bits);
2714 assert_eq!(afc.to_flags(), (has_af, has_pl));
2715 }
2716 }
2717
2718 #[test]
2722 fn adaptation_field_serialize_round_trip_with_pcr() {
2723 let original = AdaptationField {
2724 discontinuity_indicator: true,
2725 random_access_indicator: false,
2726 elementary_stream_priority_indicator: false,
2727 pcr: Some(Pcr::from_parts(10_000, 0).expect("in range")),
2728 opcr: None,
2729 splice_countdown: None,
2730 transport_private_data: None,
2731 extension: None,
2732 stuffing: &[],
2733 pcr_reserved: PCR_RESERVED_VALUE,
2734 opcr_reserved: PCR_RESERVED_VALUE,
2735 };
2736 let len = original.serialized_len();
2737 assert_eq!(len, 7); let mut buf = vec![0u8; len];
2739 let written = original.serialize_into(&mut buf).expect("serialize");
2740 assert_eq!(written, len);
2741 let decoded = AdaptationField::parse(&buf).expect("parse round-trip");
2742 assert_eq!(decoded, original);
2743 }
2744
2745 #[test]
2749 fn transport_private_data_over_255_bytes_rejected_not_wrapped() {
2750 let data = vec![0u8; 256];
2751 let af = AdaptationField {
2752 discontinuity_indicator: false,
2753 random_access_indicator: false,
2754 elementary_stream_priority_indicator: false,
2755 pcr: None,
2756 opcr: None,
2757 splice_countdown: None,
2758 transport_private_data: Some(&data),
2759 extension: None,
2760 stuffing: &[],
2761 pcr_reserved: PCR_RESERVED_VALUE,
2762 opcr_reserved: PCR_RESERVED_VALUE,
2763 };
2764 let mut buf = vec![0u8; af.serialized_len()];
2765 assert!(matches!(
2766 &(af.serialize_into(&mut buf)),
2767 Err(crate::error::Error::FieldOverflow(_))
2768 ));
2769 }
2770
2771 #[test]
2773 fn adaptation_field_serialize_produces_known_bytes() {
2774 let af = AdaptationField {
2778 discontinuity_indicator: true,
2779 random_access_indicator: false,
2780 elementary_stream_priority_indicator: false,
2781 pcr: Some(Pcr::from_parts(10_000, 0).expect("in range")),
2782 opcr: None,
2783 splice_countdown: None,
2784 transport_private_data: None,
2785 extension: None,
2786 stuffing: &[],
2787 pcr_reserved: PCR_RESERVED_VALUE,
2788 opcr_reserved: PCR_RESERVED_VALUE,
2789 };
2790 let mut buf = [0u8; 7];
2791 af.serialize_into(&mut buf).unwrap();
2792 assert_eq!(buf[0], AF_DISCONTINUITY | AF_PCR_FLAG);
2793 assert_eq!(&buf[1..7], &[0x00, 0x00, 0x13, 0x88, 0x7E, 0x00]);
2794 }
2795
2796 #[test]
2798 fn adaptation_field_serialize_round_trip_opcr_and_splice() {
2799 let original = AdaptationField {
2800 discontinuity_indicator: false,
2801 random_access_indicator: true,
2802 elementary_stream_priority_indicator: true,
2803 pcr: Some(Pcr::from_parts(1, 100).expect("in range")),
2804 opcr: Some(Pcr::from_parts(999, 5).expect("in range")),
2805 splice_countdown: Some(-3),
2806 transport_private_data: None,
2807 extension: None,
2808 stuffing: &[],
2809 pcr_reserved: PCR_RESERVED_VALUE,
2810 opcr_reserved: PCR_RESERVED_VALUE,
2811 };
2812 let len = original.serialized_len();
2813 assert_eq!(len, 1 + 6 + 6 + 1); let mut buf = vec![0u8; len];
2815 original.serialize_into(&mut buf).unwrap();
2816 let decoded = AdaptationField::parse(&buf).expect("parse");
2817 assert_eq!(decoded, original);
2818 }
2819
2820 #[test]
2822 fn adaptation_field_serialize_flags_only() {
2823 let af = AdaptationField {
2824 discontinuity_indicator: false,
2825 random_access_indicator: true,
2826 elementary_stream_priority_indicator: false,
2827 pcr: None,
2828 opcr: None,
2829 splice_countdown: None,
2830 transport_private_data: None,
2831 extension: None,
2832 stuffing: &[],
2833 pcr_reserved: PCR_RESERVED_VALUE,
2834 opcr_reserved: PCR_RESERVED_VALUE,
2835 };
2836 assert_eq!(af.serialized_len(), 1);
2837 let mut buf = [0u8; 1];
2838 af.serialize_into(&mut buf).unwrap();
2839 assert_eq!(buf[0], AF_RANDOM_ACCESS);
2840 let decoded = AdaptationField::parse(&buf).unwrap();
2841 assert_eq!(decoded, af);
2842 }
2843
2844 #[test]
2846 fn adaptation_field_serialize_rejects_small_buffer() {
2847 let af = AdaptationField {
2848 discontinuity_indicator: false,
2849 random_access_indicator: false,
2850 elementary_stream_priority_indicator: false,
2851 pcr: Some(Pcr::from_parts(0, 0).expect("in range")),
2852 opcr: None,
2853 splice_countdown: None,
2854 transport_private_data: None,
2855 extension: None,
2856 stuffing: &[],
2857 pcr_reserved: PCR_RESERVED_VALUE,
2858 opcr_reserved: PCR_RESERVED_VALUE,
2859 };
2860 let mut buf = [0u8; 3]; assert!(matches!(
2862 af.serialize_into(&mut buf),
2863 Err(Error::OutputBufferTooSmall(..))
2864 ));
2865 }
2866
2867 #[test]
2871 fn adaptation_field_extension_ltw_round_trip() {
2872 let ext = AdaptationFieldExtension {
2873 ltw: Some(Ltw {
2874 ltw_valid_flag: true,
2875 ltw_offset: LtwOffset::new(0x1234).expect("in range"),
2876 }),
2877 piecewise_rate: None,
2878 seamless_splice: None,
2879 ..AdaptationFieldExtension::new()
2880 };
2881 let mut buf = vec![0u8; ext.serialized_len()];
2882 ext.serialize_into(&mut buf).unwrap();
2883 let af = AdaptationField {
2886 discontinuity_indicator: false,
2887 random_access_indicator: false,
2888 elementary_stream_priority_indicator: false,
2889 pcr: None,
2890 opcr: None,
2891 splice_countdown: None,
2892 transport_private_data: None,
2893 extension: Some(ext),
2894 stuffing: &[],
2895 pcr_reserved: PCR_RESERVED_VALUE,
2896 opcr_reserved: PCR_RESERVED_VALUE,
2897 };
2898 let len = af.serialized_len();
2899 let mut abuf = vec![0u8; len];
2900 af.serialize_into(&mut abuf).unwrap();
2901 let decoded = AdaptationField::parse(&abuf).unwrap();
2902 assert_eq!(decoded.extension, Some(ext));
2903 }
2904
2905 #[test]
2907 fn adaptation_field_extension_piecewise_rate_round_trip() {
2908 let af = AdaptationField {
2909 discontinuity_indicator: false,
2910 random_access_indicator: false,
2911 elementary_stream_priority_indicator: false,
2912 pcr: None,
2913 opcr: None,
2914 splice_countdown: None,
2915 transport_private_data: None,
2916 extension: Some(AdaptationFieldExtension {
2917 ltw: None,
2918 piecewise_rate: Some(PiecewiseRate::MAX),
2919 seamless_splice: None,
2920 ..AdaptationFieldExtension::new()
2921 }),
2922 stuffing: &[],
2923 pcr_reserved: PCR_RESERVED_VALUE,
2924 opcr_reserved: PCR_RESERVED_VALUE,
2925 };
2926 let mut buf = vec![0u8; af.serialized_len()];
2927 af.serialize_into(&mut buf).unwrap();
2928 let decoded = AdaptationField::parse(&buf).unwrap();
2929 assert_eq!(
2930 decoded.extension.unwrap().piecewise_rate,
2931 Some(PiecewiseRate::MAX)
2932 );
2933 }
2934
2935 #[test]
2937 fn adaptation_field_extension_seamless_splice_round_trip() {
2938 let af = AdaptationField {
2939 discontinuity_indicator: false,
2940 random_access_indicator: false,
2941 elementary_stream_priority_indicator: false,
2942 pcr: None,
2943 opcr: None,
2944 splice_countdown: None,
2945 transport_private_data: None,
2946 extension: Some(AdaptationFieldExtension {
2947 ltw: None,
2948 piecewise_rate: None,
2949 seamless_splice: Some(SeamlessSplice::new(0xA, 0x1_2345_6789)),
2950 ..AdaptationFieldExtension::new()
2951 }),
2952 stuffing: &[],
2953 pcr_reserved: PCR_RESERVED_VALUE,
2954 opcr_reserved: PCR_RESERVED_VALUE,
2955 };
2956 let mut buf = vec![0u8; af.serialized_len()];
2957 af.serialize_into(&mut buf).unwrap();
2958 let decoded = AdaptationField::parse(&buf).unwrap();
2959 let ss = decoded.extension.unwrap().seamless_splice.unwrap();
2960 assert_eq!(ss.splice_type, 0xA);
2961 assert_eq!(ss.dts_next_au, 0x1_2345_6789);
2962 }
2963
2964 #[test]
2968 fn adaptation_field_extension_seamless_splice_rejects_over_range_fields() {
2969 let mut ss = SeamlessSplice::new(0xA, 0x1_2345_6789);
2970 ss.dts_next_au = 1 << SeamlessSplice::DTS_NEXT_AU_BITS;
2971 assert!(matches!(ss.to_marked_field(), Err(Error::FieldOverflow(_))));
2972 ss.dts_next_au = (1 << SeamlessSplice::DTS_NEXT_AU_BITS) - 1;
2973 assert!(ss.to_marked_field().is_ok());
2974
2975 let mut ss = SeamlessSplice::new(0x10, 0x1_2345_6789);
2976 assert!(matches!(ss.to_marked_field(), Err(Error::FieldOverflow(_))));
2977 ss.splice_type = 0x0F;
2978 ss.marker_bits = SPLICE_MARKERS_VALUE + 1;
2979 assert!(matches!(ss.to_marked_field(), Err(Error::FieldOverflow(_))));
2980 ss.marker_bits = SPLICE_MARKERS_VALUE;
2981 assert!(ss.to_marked_field().is_ok());
2982 }
2983
2984 #[test]
2988 fn adaptation_field_extension_rejects_over_range_ltw_and_rate() {
2989 assert!(matches!(
2990 LtwOffset::new(0x8000),
2991 Err(Error::FieldOverflow(_))
2992 ));
2993 assert_eq!(LtwOffset::new(LtwOffset::MAX.get()), Ok(LtwOffset::MAX));
2994 assert!(matches!(
2995 PiecewiseRate::new(0x40_0000),
2996 Err(Error::FieldOverflow(_))
2997 ));
2998 assert_eq!(PiecewiseRate::new(0x3F_FFFF), Ok(PiecewiseRate::MAX));
2999
3000 let mut ext = AdaptationFieldExtension::new();
3001 ext.ltw = Some(Ltw {
3002 ltw_valid_flag: true,
3003 ltw_offset: LtwOffset::MAX,
3004 });
3005 ext.piecewise_rate = Some(PiecewiseRate::MAX);
3006 let mut buf = vec![0u8; ext.serialized_len()];
3007 ext.serialize_into(&mut buf).unwrap();
3008 assert_eq!(buf[1..3], [0xDF, 0xFF]);
3009 assert_eq!(buf[3..6], [0xFF, 0xFF, 0xFF]);
3010 assert_eq!(AdaptationFieldExtension::parse(&buf).unwrap(), ext);
3011 }
3012
3013 #[test]
3016 fn adaptation_field_serialize_rejects_over_range_reserved_bits() {
3017 let mut af = AdaptationField::new();
3018 af.pcr = Some(Pcr::from_parts(0, 0).expect("in range"));
3019 let mut ok = [0u8; 7];
3020 af.serialize_into(&mut ok).unwrap();
3021 assert_eq!(&ok[1..6], &[0x00, 0x00, 0x00, 0x00, 0x7E]);
3022
3023 af.pcr_reserved = PCR_RESERVED_VALUE + 1;
3024 let mut buf = [0u8; 7];
3025 assert!(matches!(
3026 af.serialize_into(&mut buf),
3027 Err(Error::FieldOverflow(_))
3028 ));
3029 }
3030
3031 #[test]
3033 fn adaptation_field_transport_private_data_round_trip() {
3034 let tpd = [0xDE, 0xAD, 0xBE, 0xEF];
3035 let af = AdaptationField {
3036 discontinuity_indicator: false,
3037 random_access_indicator: false,
3038 elementary_stream_priority_indicator: false,
3039 pcr: None,
3040 opcr: None,
3041 splice_countdown: None,
3042 transport_private_data: Some(&tpd),
3043 extension: None,
3044 stuffing: &[],
3045 pcr_reserved: PCR_RESERVED_VALUE,
3046 opcr_reserved: PCR_RESERVED_VALUE,
3047 };
3048 let mut buf = vec![0u8; af.serialized_len()];
3049 af.serialize_into(&mut buf).unwrap();
3050 let decoded = AdaptationField::parse(&buf).unwrap();
3051 assert_eq!(decoded.transport_private_data, Some(tpd.as_slice()));
3052 }
3053
3054 #[test]
3057 fn adaptation_field_stuffing_round_trip() {
3058 let af = AdaptationField {
3059 discontinuity_indicator: false,
3060 random_access_indicator: false,
3061 elementary_stream_priority_indicator: false,
3062 pcr: Some(Pcr::from_parts(12_345, 7).expect("in range")),
3063 opcr: None,
3064 splice_countdown: None,
3065 transport_private_data: None,
3066 extension: None,
3067 stuffing: &[0xFF; 20],
3068 pcr_reserved: PCR_RESERVED_VALUE,
3069 opcr_reserved: PCR_RESERVED_VALUE,
3070 };
3071 assert_eq!(af.serialized_len(), 27);
3073 let mut buf = vec![0u8; af.serialized_len()];
3074 af.serialize_into(&mut buf).unwrap();
3075 assert!(buf[7..27].iter().all(|&b| b == 0xFF));
3077 let decoded = AdaptationField::parse(&buf).unwrap();
3078 assert_eq!(decoded.stuffing.len(), 20);
3079 assert_eq!(decoded, af);
3080 let pure = AdaptationField {
3082 discontinuity_indicator: false,
3083 random_access_indicator: false,
3084 elementary_stream_priority_indicator: false,
3085 pcr: None,
3086 opcr: None,
3087 splice_countdown: None,
3088 transport_private_data: None,
3089 extension: None,
3090 stuffing: &[0xFF; 5],
3091 pcr_reserved: PCR_RESERVED_VALUE,
3092 opcr_reserved: PCR_RESERVED_VALUE,
3093 };
3094 let mut pbuf = vec![0u8; pure.serialized_len()];
3095 pure.serialize_into(&mut pbuf).unwrap();
3096 assert_eq!(pbuf, vec![0x00, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF]);
3097 assert_eq!(AdaptationField::parse(&pbuf).unwrap(), pure);
3098 }
3099
3100 #[test]
3102 fn adaptation_field_all_fields_round_trip() {
3103 let tpd = [0x01u8, 0x02, 0x03];
3104 let af = AdaptationField {
3105 discontinuity_indicator: true,
3106 random_access_indicator: false,
3107 elementary_stream_priority_indicator: false,
3108 pcr: Some(Pcr::from_parts(90_000, 50).expect("in range")),
3109 opcr: None,
3110 splice_countdown: Some(10),
3111 transport_private_data: Some(&tpd),
3112 extension: Some(AdaptationFieldExtension {
3113 ltw: Some(Ltw {
3114 ltw_valid_flag: false,
3115 ltw_offset: LtwOffset::new(500).expect("in range"),
3116 }),
3117 piecewise_rate: Some(PiecewiseRate::new(12345).expect("in range")),
3118 seamless_splice: None,
3119 ..AdaptationFieldExtension::new()
3120 }),
3121 stuffing: &[],
3122 pcr_reserved: PCR_RESERVED_VALUE,
3123 opcr_reserved: PCR_RESERVED_VALUE,
3124 };
3125 let len = af.serialized_len();
3126 let mut buf = vec![0u8; len];
3127 af.serialize_into(&mut buf).unwrap();
3128 let decoded = AdaptationField::parse(&buf).unwrap();
3129 assert_eq!(decoded.pcr, af.pcr);
3130 assert_eq!(decoded.splice_countdown, af.splice_countdown);
3131 assert_eq!(decoded.transport_private_data, af.transport_private_data);
3132 assert_eq!(decoded.extension, af.extension);
3133 assert!(decoded.discontinuity_indicator);
3134 }
3135
3136 #[test]
3139 fn adaptation_field_serialize_from_real_packet_bytes() {
3140 let mut raw = [0xAAu8; TS_PACKET_SIZE];
3142 raw[0] = TS_SYNC_BYTE;
3143 raw[1] = 0x01;
3144 raw[2] = 0x00;
3145 raw[3] = ADAPTATION_FLAG | PAYLOAD_FLAG;
3146 raw[4] = 7;
3147 raw[5] = AF_DISCONTINUITY | AF_PCR_FLAG;
3148 raw[6..12].copy_from_slice(&[0x00, 0x00, 0x13, 0x88, 0x7E, 0x00]);
3149
3150 let pkt = TsPacket::parse(&raw).unwrap();
3151 let af = pkt.adaptation_field().unwrap().unwrap();
3152
3153 let mut ser = vec![0u8; af.serialized_len()];
3155 af.serialize_into(&mut ser).unwrap();
3156 let decoded = AdaptationField::parse(&ser).unwrap();
3157 assert_eq!(
3158 decoded.pcr,
3159 Some(Pcr::from_parts(10_000, 0).expect("in range"))
3160 );
3161 assert!(decoded.discontinuity_indicator);
3162 }
3163}