1use crate::error::{Error, Result};
4use crate::pid::Pid;
5use broadcast_core::len::{need_in, need_out};
6
7pub const TS_PACKET_SIZE: usize = 188;
9pub const TS_SYNC_BYTE: u8 = 0x47;
11pub const TS_PACKETS_PER_DATAGRAM: usize = 7;
18pub const TS_BYTES_PER_DATAGRAM: usize = TS_PACKETS_PER_DATAGRAM * TS_PACKET_SIZE;
21const MAX_SECTION_SIZE: usize = 4098;
26const SECTION_HEADER_LEN: usize = 3;
30const SECTION_TABLE_ID_OFFSET: usize = 0;
32const SECTION_FLAGS_OFFSET: usize = SECTION_TABLE_ID_OFFSET + 1;
33const SECTION_LENGTH_LO_OFFSET: usize = SECTION_FLAGS_OFFSET + 1;
34pub(crate) const SECTION_LENGTH_HI_MASK: u8 = 0x0F;
38
39pub(crate) const STUFFING_BYTE: u8 = 0xFF;
41
42const HIGH_BYTE_SHIFT: u32 = 8;
44
45pub(crate) fn section_total_len(bytes: &[u8]) -> Option<usize> {
54 if bytes.len() < SECTION_HEADER_LEN {
55 return None;
56 }
57 let section_length = ((bytes[SECTION_FLAGS_OFFSET] & SECTION_LENGTH_HI_MASK) as usize)
58 << HIGH_BYTE_SHIFT
59 | bytes[SECTION_LENGTH_LO_OFFSET] as usize;
60 Some(SECTION_HEADER_LEN + section_length)
61}
62
63#[non_exhaustive]
72#[derive(Debug, Clone, Copy, PartialEq, Eq)]
73#[cfg_attr(feature = "serde", derive(serde::Serialize))]
74pub enum ScramblingControl {
75 NotScrambled,
77 Reserved,
79 EvenKey,
82 OddKey,
85}
86
87impl ScramblingControl {
88 pub fn from_bits(bits: u8) -> Self {
90 match bits & SCRAMBLING_BITS {
91 0b00 => Self::NotScrambled,
92 0b01 => Self::Reserved,
93 0b10 => Self::EvenKey,
94 _ => Self::OddKey,
95 }
96 }
97
98 pub fn to_bits(self) -> u8 {
103 match self {
104 Self::NotScrambled => 0b00,
105 Self::Reserved => 0b01,
106 Self::EvenKey => 0b10,
107 Self::OddKey => 0b11,
108 }
109 }
110
111 pub fn name(&self) -> &'static str {
113 match self {
114 Self::NotScrambled => "not_scrambled",
115 Self::Reserved => "reserved",
116 Self::EvenKey => "even_key",
117 Self::OddKey => "odd_key",
118 }
119 }
120}
121
122broadcast_core::impl_spec_display!(ScramblingControl);
123
124#[non_exhaustive]
131#[derive(Debug, Clone, Copy, PartialEq, Eq)]
132#[cfg_attr(feature = "serde", derive(serde::Serialize))]
133pub enum AdaptationFieldControl {
134 Reserved,
136 PayloadOnly,
138 AdaptationOnly,
140 AdaptationAndPayload,
142}
143
144impl AdaptationFieldControl {
145 pub fn from_flags(has_adaptation: bool, has_payload: bool) -> Self {
147 match (has_adaptation, has_payload) {
148 (false, false) => Self::Reserved,
149 (false, true) => Self::PayloadOnly,
150 (true, false) => Self::AdaptationOnly,
151 (true, true) => Self::AdaptationAndPayload,
152 }
153 }
154
155 pub fn to_flags(self) -> (bool, bool) {
158 match self {
159 Self::Reserved => (false, false),
160 Self::PayloadOnly => (false, true),
161 Self::AdaptationOnly => (true, false),
162 Self::AdaptationAndPayload => (true, true),
163 }
164 }
165
166 pub fn to_bits(self) -> u8 {
172 match self {
173 Self::Reserved => 0b00,
174 Self::PayloadOnly => 0b01,
175 Self::AdaptationOnly => 0b10,
176 Self::AdaptationAndPayload => 0b11,
177 }
178 }
179
180 pub fn name(&self) -> &'static str {
182 match self {
183 Self::Reserved => "reserved",
184 Self::PayloadOnly => "payload_only",
185 Self::AdaptationOnly => "adaptation_only",
186 Self::AdaptationAndPayload => "adaptation_and_payload",
187 }
188 }
189}
190
191broadcast_core::impl_spec_display!(AdaptationFieldControl);
192
193const TEI_MASK: u8 = 0x80;
195const PUSI_MASK: u8 = 0x40;
197pub const PID_MASK_HI: u8 = 0x1F;
199pub const SCRAMBLING_MASK: u8 = 0xC0;
201const SCRAMBLING_SHIFT: u32 = 6;
203const SCRAMBLING_BITS: u8 = SCRAMBLING_MASK >> SCRAMBLING_SHIFT;
205const ADAPTATION_SHIFT: u32 = 4;
207const ADAPTATION_CONTROL_MASK: u8 = 0b11;
209pub const ADAPTATION_FLAG: u8 = 0x20;
211pub const PAYLOAD_FLAG: u8 = 0x10;
213pub const CC_MASK: u8 = 0x0F;
215
216const TEI_PUSI_PID_HI_OFFSET: usize = 1;
219const PID_LO_OFFSET: usize = 2;
221pub(crate) const SCRAMBLING_AFC_CC_OFFSET: usize = 3;
224
225#[derive(Clone, Copy, Default, PartialEq, Eq, PartialOrd, Ord, Hash)]
231#[cfg_attr(feature = "serde", derive(serde::Serialize))]
232#[cfg_attr(feature = "serde", serde(transparent))]
233pub struct ContinuityCounter(u8);
234
235impl ContinuityCounter {
236 pub const ZERO: Self = Self(0);
238
239 #[must_use]
241 pub const fn next(self) -> Self {
242 Self((self.0 + 1) % COUNT_MODULUS)
243 }
244
245 #[must_use]
247 pub const fn value(self) -> u8 {
248 self.0
249 }
250
251 #[must_use]
255 pub const fn forward_distance_from(self, from: Self) -> u8 {
256 (self.0 + COUNT_MODULUS - from.0) % COUNT_MODULUS
257 }
258
259 pub const fn try_new(value: u8) -> core::result::Result<Self, ContinuityCounterOutOfRange> {
264 if value > CC_MASK {
265 Err(ContinuityCounterOutOfRange { value })
266 } else {
267 Ok(Self(value))
268 }
269 }
270
271 #[must_use]
275 pub const fn from_wire_masked(value: u8) -> Self {
276 Self(value & CC_MASK)
277 }
278}
279
280const COUNT_MODULUS: u8 = CC_MASK + 1;
282
283impl From<ContinuityCounter> for u8 {
284 fn from(cc: ContinuityCounter) -> Self {
285 cc.0
286 }
287}
288
289impl TryFrom<u8> for ContinuityCounter {
290 type Error = ContinuityCounterOutOfRange;
291 fn try_from(value: u8) -> core::result::Result<Self, Self::Error> {
292 Self::try_new(value)
293 }
294}
295
296impl core::fmt::Debug for ContinuityCounter {
297 fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
298 write!(f, "ContinuityCounter({})", self.0)
299 }
300}
301
302impl core::fmt::Display for ContinuityCounter {
303 fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
304 write!(f, "{}", self.0)
305 }
306}
307
308#[derive(Debug, Clone, Copy, PartialEq, Eq, thiserror::Error)]
311#[error("continuity_counter {value} exceeds the 4-bit range 0..=15")]
312#[non_exhaustive]
313pub struct ContinuityCounterOutOfRange {
314 pub value: u8,
316}
317
318#[derive(Clone, Debug, PartialEq, Eq)]
320#[cfg_attr(feature = "serde", derive(serde::Serialize))]
321pub struct TsHeader {
322 pub tei: bool,
325 pub pusi: bool,
328 pub pid: Pid,
330 pub scrambling: ScramblingControl,
333 #[cfg_attr(feature = "serde", serde(rename = "adaptation"))]
339 pub adaptation_field_control: AdaptationFieldControl,
340 pub continuity_counter: ContinuityCounter,
342}
343
344#[derive(Clone, Debug)]
350#[cfg_attr(feature = "serde", derive(serde::Serialize))]
351pub struct TsPacket<'a> {
352 pub header: TsHeader,
354 pub payload: Option<&'a [u8]>,
358 #[cfg_attr(feature = "serde", serde(skip))]
361 adaptation: Option<&'a [u8]>,
362 #[cfg_attr(feature = "serde", serde(skip))]
364 pub raw: &'a [u8; TS_PACKET_SIZE],
365}
366
367impl TsHeader {
368 pub fn parse(raw4: &[u8]) -> Result<Self> {
370 need_in(raw4, TsHeader::serialized_len(), "TsHeader")?;
371 let b1 = raw4[TEI_PUSI_PID_HI_OFFSET];
372 let b2 = raw4[PID_LO_OFFSET];
373 let b3 = raw4[SCRAMBLING_AFC_CC_OFFSET];
374
375 let tei = (b1 & TEI_MASK) != 0;
376 let pusi = (b1 & PUSI_MASK) != 0;
377 let pid =
378 Pid::from_wire_masked((u16::from(b1 & PID_MASK_HI) << HIGH_BYTE_SHIFT) | u16::from(b2));
379 let has_adaptation = (b3 & ADAPTATION_FLAG) != 0;
380 let has_payload = (b3 & PAYLOAD_FLAG) != 0;
381
382 Ok(Self {
383 tei,
384 pusi,
385 pid,
386 scrambling: ScramblingControl::from_bits(b3 >> SCRAMBLING_SHIFT),
387 adaptation_field_control: AdaptationFieldControl::from_flags(
388 has_adaptation,
389 has_payload,
390 ),
391 continuity_counter: ContinuityCounter::from_wire_masked(b3),
392 })
393 }
394
395 pub const fn serialized_len() -> usize {
397 4
398 }
399
400 #[must_use]
402 pub fn to_bytes(&self) -> [u8; 4] {
403 let mut b = [0u8; 4];
404 b[0] = TS_SYNC_BYTE;
405 if self.tei {
406 b[1] |= TEI_MASK;
407 }
408 if self.pusi {
409 b[1] |= PUSI_MASK;
410 }
411 let pid = self.pid.value();
412 b[TEI_PUSI_PID_HI_OFFSET] |= ((pid >> HIGH_BYTE_SHIFT) as u8) & PID_MASK_HI;
413 b[PID_LO_OFFSET] = pid.to_be_bytes()[1];
414 b[SCRAMBLING_AFC_CC_OFFSET] = (self.scrambling.to_bits() << SCRAMBLING_SHIFT)
415 | ((self.adaptation_field_control.to_bits() & ADAPTATION_CONTROL_MASK)
416 << ADAPTATION_SHIFT)
417 | self.continuity_counter.value();
418 b
419 }
420
421 pub fn serialize_into(&self, buf: &mut [u8]) -> Result<usize> {
423 need_out(buf, TsHeader::serialized_len(), "TsHeader")?;
424 buf[..TsHeader::serialized_len()].copy_from_slice(&self.to_bytes());
425 Ok(TsHeader::serialized_len())
426 }
427
428 pub fn has_adaptation(&self) -> bool {
431 self.adaptation_field_control.to_flags().0
432 }
433
434 pub fn has_payload(&self) -> bool {
437 self.adaptation_field_control.to_flags().1
438 }
439}
440
441impl<'a> broadcast_core::Parse<'a> for TsHeader {
442 type Error = Error;
443
444 fn parse(bytes: &'a [u8]) -> Result<Self> {
445 TsHeader::parse(bytes)
446 }
447}
448
449impl broadcast_core::Serialize for TsHeader {
450 type Error = Error;
451
452 fn serialized_len(&self) -> usize {
453 TsHeader::serialized_len()
454 }
455
456 fn serialize_into(&self, buf: &mut [u8]) -> Result<usize> {
457 TsHeader::serialize_into(self, buf)
458 }
459}
460
461pub(crate) fn adaptation_field_body_range(
471 pkt: &[u8],
472 has_adaptation: bool,
473) -> Option<core::ops::Range<usize>> {
474 if !has_adaptation || pkt.len() <= AF_LEN_BYTE {
475 return None;
476 }
477 let af_len = pkt[AF_LEN_BYTE] as usize;
478 if af_len == 0 {
479 return None;
480 }
481 let start = AF_FLAGS_BYTE;
482 let end = start + af_len;
483 if end > pkt.len() {
484 return None;
485 }
486 Some(start..end)
487}
488
489fn adaptation_field_skip(pkt: &[u8], has_adaptation: bool) -> usize {
495 if !has_adaptation || pkt.len() <= AF_LEN_BYTE {
496 return 0;
497 }
498 1 + pkt[AF_LEN_BYTE] as usize
499}
500
501pub(crate) enum ClockReferenceSlot {
506 Field(core::ops::Range<usize>),
508 NoAdaptationField,
510 TooShort {
512 need: usize,
514 have: usize,
516 },
517 FlagClear,
519 Truncated {
521 need: usize,
523 have: usize,
525 },
526}
527
528pub(crate) fn clock_reference_slot(pkt: &[u8], flag: u8) -> ClockReferenceSlot {
532 if pkt.len() <= AF_LEN_BYTE || pkt[SCRAMBLING_AFC_CC_OFFSET] & ADAPTATION_FLAG == 0 {
533 return ClockReferenceSlot::NoAdaptationField;
534 }
535 let af_len = pkt[AF_LEN_BYTE] as usize;
536 if af_len == 0 {
537 return ClockReferenceSlot::NoAdaptationField;
538 }
539 let preceding = if flag == AF_OPCR_FLAG {
542 PCR_FIELD_LEN
543 } else {
544 0
545 };
546 let need = 1 + preceding + PCR_FIELD_LEN;
547 if af_len < need {
548 return ClockReferenceSlot::TooShort { need, have: af_len };
549 }
550 if pkt.len() <= AF_FLAGS_BYTE || pkt[AF_FLAGS_BYTE] & flag == 0 {
551 return ClockReferenceSlot::FlagClear;
552 }
553 let start = CLOCK_REFERENCE_START + preceding;
554 let end = start + PCR_FIELD_LEN;
555 if end > pkt.len() {
556 return ClockReferenceSlot::Truncated {
557 need: end,
558 have: pkt.len(),
559 };
560 }
561 ClockReferenceSlot::Field(start..end)
562}
563
564#[must_use]
570pub fn payload_range(raw: &[u8; TS_PACKET_SIZE]) -> Option<core::ops::Range<usize>> {
571 let header = TsHeader::parse(&raw[..TsHeader::serialized_len()]).ok()?;
572 if !header.has_payload() {
573 return None;
574 }
575 let start = TsHeader::serialized_len() + adaptation_field_skip(raw, header.has_adaptation());
576 (start < TS_PACKET_SIZE).then_some(start..TS_PACKET_SIZE)
577}
578
579impl<'a> TsPacket<'a> {
580 pub fn parse(buf: &'a [u8]) -> Result<Self> {
586 need_in(buf, TS_PACKET_SIZE, "TsPacket")?;
587 if buf[0] != TS_SYNC_BYTE {
588 return Err(Error::InvalidSync(broadcast_core::error::InvalidSync::new(
589 "TS sync byte",
590 u32::from(TS_SYNC_BYTE),
591 u32::from(buf[0]),
592 )));
593 }
594
595 let raw: &[u8; TS_PACKET_SIZE] = buf[..TS_PACKET_SIZE].try_into().map_err(|_| {
596 Error::BufferTooShort(broadcast_core::error::BufferTooShort::new(
597 TS_PACKET_SIZE,
598 buf.len(),
599 "TsPacket::parse (array conversion)",
600 ))
601 })?;
602
603 let header = TsHeader::parse(&raw[..TsHeader::serialized_len()])?;
604
605 let mut payload = None;
606
607 let adaptation = adaptation_field_body_range(raw, header.has_adaptation()).map(|r| &raw[r]);
620 if let Some(range) = payload_range(raw) {
621 payload = Some(&raw[range]);
622 }
623
624 Ok(TsPacket {
625 header,
626 payload,
627 adaptation,
628 raw,
629 })
630 }
631
632 pub fn adaptation_field(&self) -> Option<crate::Result<AdaptationField<'a>>> {
638 self.adaptation.map(AdaptationField::parse)
639 }
640}
641
642pub const AF_DISCONTINUITY: u8 = 0x80;
645pub(crate) const AF_RANDOM_ACCESS: u8 = 0x40;
646pub(crate) const AF_ES_PRIORITY: u8 = 0x20;
647pub const AF_PCR_FLAG: u8 = 0x10;
649pub(crate) const AF_OPCR_FLAG: u8 = 0x08;
650pub(crate) const AF_SPLICING_FLAG: u8 = 0x04;
651pub(crate) const AF_TRANSPORT_PRIVATE_DATA_FLAG: u8 = 0x02;
652pub(crate) const AF_EXTENSION_FLAG: u8 = 0x01;
653pub(crate) const PCR_RESERVED_BITS: u8 = 0x7E;
656const PCR_RESERVED_BITS_COUNT: u32 = 6;
658pub(crate) const PCR_RESERVED_SHIFT: u32 = 1;
660pub(crate) const PCR_RESERVED_BYTE_OFFSET: usize = 4;
662const PCR_RESERVED_VALUE: u8 = 0x3F;
664pub(crate) const PCR_FIELD_LEN: usize = 6;
666const PCR_FIELD_BYTE_MASK: u64 = 0xFF;
668const PCR_BASE_SHIFT_HI: u32 = 25;
671const PCR_BASE_SHIFT_HI_MID: u32 = 17;
672const PCR_BASE_SHIFT_LO_MID: u32 = 9;
673const PCR_BASE_SHIFT_LO: u32 = 1;
674const PCR_BASE_LSB_SHIFT: u32 = 7;
676const PCR_BASE_LSB_MASK: u64 = 0x01;
678const PCR_EXTENSION_HI_SHIFT: u32 = 8;
681const PCR_EXTENSION_HI_MASK: u8 = 0x01;
683
684pub(crate) const AF_LEN_BYTE: usize = 4;
687pub(crate) const AF_FLAGS_BYTE: usize = 5;
690pub(crate) const CLOCK_REFERENCE_START: usize = AF_FLAGS_BYTE + 1;
693
694#[derive(Clone, Copy, Debug, PartialEq, Eq)]
707#[cfg_attr(feature = "serde", derive(serde::Serialize))]
708pub struct Pcr(broadcast_common::clock33::Clock27);
709
710impl Pcr {
711 pub fn from_parts(base: u64, extension: u16) -> Result<Self> {
716 Ok(Self(broadcast_common::clock33::Clock27::from_parts(
717 base, extension,
718 )?))
719 }
720
721 pub fn from_27mhz(ticks: u64) -> Result<Self> {
726 Ok(Self(broadcast_common::clock33::Clock27::from_27mhz(ticks)?))
727 }
728
729 pub fn to_clock27(self) -> Result<broadcast_common::clock33::Clock27> {
735 Ok(self.0.to_clock27()?)
736 }
737
738 #[must_use]
741 pub const fn clock(self) -> broadcast_common::clock33::Clock27 {
742 self.0
743 }
744
745 #[must_use]
747 pub const fn base(self) -> u64 {
748 self.0.base.ticks()
749 }
750
751 #[must_use]
754 pub const fn extension(self) -> u16 {
755 self.0.ext
756 }
757
758 #[must_use]
764 pub fn as_27mhz(self) -> u64 {
765 self.0.ticks()
766 }
767
768 #[must_use]
778 pub fn to_field_bytes(self) -> [u8; PCR_FIELD_LEN] {
779 let b = self.0.base.ticks();
780 let e = u64::from(self.0.ext);
781 [
782 ((b >> PCR_BASE_SHIFT_HI) & PCR_FIELD_BYTE_MASK) as u8,
783 ((b >> PCR_BASE_SHIFT_HI_MID) & PCR_FIELD_BYTE_MASK) as u8,
784 ((b >> PCR_BASE_SHIFT_LO_MID) & PCR_FIELD_BYTE_MASK) as u8,
785 ((b >> PCR_BASE_SHIFT_LO) & PCR_FIELD_BYTE_MASK) as u8,
786 (((b & PCR_BASE_LSB_MASK) as u8) << PCR_BASE_LSB_SHIFT)
788 | PCR_RESERVED_BITS
789 | ((e >> PCR_EXTENSION_HI_SHIFT) as u8 & PCR_EXTENSION_HI_MASK),
790 (e & PCR_FIELD_BYTE_MASK) as u8,
791 ]
792 }
793
794 pub fn to_field_bytes_with_reserved(self, reserved: u8) -> Result<[u8; PCR_FIELD_LEN]> {
801 let mut field = self.to_field_bytes();
802 set_pcr_reserved(&mut field, reserved)?;
803 Ok(field)
804 }
805
806 pub(crate) fn parse(buf: &[u8], from: usize) -> Result<Self> {
813 let end = from + PCR_FIELD_LEN;
814 let b: &[u8; PCR_FIELD_LEN] =
815 buf.get(from..end)
816 .and_then(|s| s.try_into().ok())
817 .ok_or(Error::BufferTooShort(
818 broadcast_core::error::BufferTooShort::new(
819 end,
820 buf.len(),
821 "adaptation_field PCR",
822 ),
823 ))?;
824 let [b0, b1, b2, b3, b4, b5] = *b;
825 let base = (u64::from(b0) << PCR_BASE_SHIFT_HI)
826 | (u64::from(b1) << PCR_BASE_SHIFT_HI_MID)
827 | (u64::from(b2) << PCR_BASE_SHIFT_LO_MID)
828 | (u64::from(b3) << PCR_BASE_SHIFT_LO)
829 | (u64::from(b4) >> PCR_BASE_LSB_SHIFT);
830 let extension =
831 (u16::from(b4 & PCR_EXTENSION_HI_MASK) << PCR_EXTENSION_HI_SHIFT) | u16::from(b5);
832 Ok(Self(broadcast_common::clock33::Clock27::from_wire_parts(
833 base, extension,
834 )))
835 }
836}
837
838#[derive(Clone, Copy, Debug, PartialEq, Eq)]
845#[cfg_attr(feature = "serde", derive(serde::Serialize))]
846pub struct Ltw {
847 pub ltw_valid_flag: bool,
849 pub ltw_offset: LtwOffset,
853}
854
855#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
861#[cfg_attr(feature = "serde", derive(serde::Serialize))]
862#[cfg_attr(feature = "serde", serde(transparent))]
863pub struct LtwOffset(u16);
864
865const LTW_OFFSET_BITS: u32 = 15;
867
868impl LtwOffset {
869 pub const MAX: Self = Self((1 << LTW_OFFSET_BITS) - 1);
871
872 pub const ZERO: Self = Self(0);
874
875 pub fn new(value: u16) -> Result<Self> {
877 let fitted =
878 broadcast_core::len::fit_bits(u64::from(value), LTW_OFFSET_BITS, "ltw_offset")?;
879 Ok(Self(fitted as u16))
880 }
881
882 #[must_use]
887 pub(crate) fn from_wire_masked(high: u8, low: u8) -> Self {
888 Self((u16::from(high & LTW_OFFSET_HI_MASK) << HIGH_BYTE_SHIFT) | u16::from(low))
889 }
890
891 #[must_use]
893 pub fn get(self) -> u16 {
894 self.0
895 }
896}
897
898impl From<LtwOffset> for u16 {
899 fn from(value: LtwOffset) -> Self {
900 value.0
901 }
902}
903
904impl core::fmt::Display for LtwOffset {
905 fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
906 write!(f, "{}", self.0)
907 }
908}
909
910#[non_exhaustive]
919#[derive(Clone, Copy, Debug, PartialEq, Eq)]
920#[cfg_attr(feature = "serde", derive(serde::Serialize))]
921pub struct SeamlessSplice {
922 pub splice_type: u8,
924 pub dts_next_au: u64,
926 pub marker_bits: u8,
931}
932
933const SPLICE_TYPE_BITS: u32 = 4;
935const DTS_NEXT_AU_BITS: u32 = 33;
937const SPLICE_MARKER_BITS: u32 = 3;
939
940impl SeamlessSplice {
941 #[must_use]
943 pub const fn new(splice_type: u8, dts_next_au: u64) -> Self {
944 Self {
945 splice_type,
946 dts_next_au,
947 marker_bits: SPLICE_MARKERS_VALUE,
948 }
949 }
950
951 pub const DTS_NEXT_AU_BITS: u32 = DTS_NEXT_AU_BITS;
953
954 #[must_use]
956 pub(crate) fn from_marked_field(field: &[u8; DTS_NEXT_AU_FIELD_LEN]) -> Self {
957 let m = broadcast_common::clock33::unpack_marked(field);
958 Self {
959 splice_type: m.prefix,
960 dts_next_au: m.timestamp,
961 marker_bits: m.markers,
962 }
963 }
964
965 pub fn to_marked_field(&self) -> Result<[u8; DTS_NEXT_AU_FIELD_LEN]> {
968 broadcast_core::len::fit_bits(
969 u64::from(self.splice_type),
970 SPLICE_TYPE_BITS,
971 "seamless_splice.splice_type",
972 )?;
973 broadcast_core::len::fit_bits(
974 self.dts_next_au,
975 DTS_NEXT_AU_BITS,
976 "seamless_splice.DTS_next_AU",
977 )?;
978 broadcast_core::len::fit_bits(
979 u64::from(self.marker_bits),
980 SPLICE_MARKER_BITS,
981 "seamless_splice.marker_bit",
982 )?;
983 Ok(broadcast_common::clock33::pack_marked_with(
984 self.dts_next_au,
985 self.splice_type,
986 self.marker_bits,
987 ))
988 }
989}
990
991const SPLICE_MARKERS_VALUE: u8 = 0x07;
995const AFE_LTW_FLAG: u8 = 0x80;
996const AFE_PIECEWISE_RATE_FLAG: u8 = 0x40;
997const AFE_SEAMLESS_SPLICE_FLAG: u8 = 0x20;
998const LTW_OFFSET_HI_MASK: u8 = 0x7F;
1000const PIECEWISE_RATE_HI_MASK: u8 = 0x3F;
1002const AFE_AF_DESCRIPTOR_NOT_PRESENT_FLAG: u8 = 0x10;
1004const AFE_RESERVED_FLAGS_MASK: u8 = 0x0F;
1006const AFE_RESERVED_FLAGS_VALUE: u8 = 0x0F;
1008const PIECEWISE_RATE_RESERVED_SHIFT: u32 = 6;
1010const PIECEWISE_RATE_RESERVED_VALUE: u8 = 0x03;
1012const PIECEWISE_RATE_BITS: u32 = 22;
1014const LTW_FIELD_LEN: usize = 2;
1017const PIECEWISE_RATE_FIELD_LEN: usize = 3;
1019const PIECEWISE_RATE_HI_OFFSET: usize = 0;
1021const PIECEWISE_RATE_MID_OFFSET: usize = PIECEWISE_RATE_HI_OFFSET + 1;
1022const PIECEWISE_RATE_LO_OFFSET: usize = PIECEWISE_RATE_MID_OFFSET + 1;
1023const PIECEWISE_RATE_HI_SHIFT: u32 = 16;
1025pub const DTS_NEXT_AU_FIELD_LEN: usize = 5;
1028const AFE_PREFIX_LEN: usize = 2;
1031
1032#[non_exhaustive]
1052#[derive(Clone, Copy, Debug, PartialEq, Eq)]
1053#[cfg_attr(feature = "serde", derive(serde::Serialize))]
1054pub struct AdaptationFieldExtension<'a> {
1055 pub ltw: Option<Ltw>,
1057 pub piecewise_rate: Option<PiecewiseRate>,
1059 pub piecewise_rate_reserved: u8,
1062 pub seamless_splice: Option<SeamlessSplice>,
1064 pub af_descriptor_not_present_flag: bool,
1068 pub reserved_flags: u8,
1070 pub trailing: &'a [u8],
1074}
1075
1076impl Default for AdaptationFieldExtension<'_> {
1077 fn default() -> Self {
1078 Self::new()
1079 }
1080}
1081
1082#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
1088#[cfg_attr(feature = "serde", derive(serde::Serialize))]
1089#[cfg_attr(feature = "serde", serde(transparent))]
1090pub struct PiecewiseRate(u32);
1091
1092impl PiecewiseRate {
1093 pub const MAX: Self = Self((1 << PIECEWISE_RATE_BITS) - 1);
1095
1096 pub fn new(value: u32) -> Result<Self> {
1098 let fitted =
1099 broadcast_core::len::fit_bits(u64::from(value), PIECEWISE_RATE_BITS, "piecewise_rate")?;
1100 Ok(Self(fitted as u32))
1101 }
1102
1103 #[must_use]
1108 pub(crate) fn from_wire_masked(high: u8, mid: u8, low: u8) -> Self {
1109 Self(
1110 (u32::from(high & PIECEWISE_RATE_HI_MASK) << PIECEWISE_RATE_HI_SHIFT)
1111 | (u32::from(mid) << HIGH_BYTE_SHIFT)
1112 | u32::from(low),
1113 )
1114 }
1115
1116 #[must_use]
1118 pub fn get(self) -> u32 {
1119 self.0
1120 }
1121}
1122
1123impl From<PiecewiseRate> for u32 {
1124 fn from(value: PiecewiseRate) -> Self {
1125 value.0
1126 }
1127}
1128
1129impl core::fmt::Display for PiecewiseRate {
1130 fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
1131 write!(f, "{}", self.0)
1132 }
1133}
1134
1135impl<'a> AdaptationFieldExtension<'a> {
1136 #[must_use]
1139 pub const fn new() -> Self {
1140 Self {
1141 ltw: None,
1142 piecewise_rate: None,
1143 piecewise_rate_reserved: PIECEWISE_RATE_RESERVED_VALUE,
1144 seamless_splice: None,
1145 af_descriptor_not_present_flag: true,
1146 reserved_flags: AFE_RESERVED_FLAGS_VALUE,
1147 trailing: &[],
1148 }
1149 }
1150
1151 fn parse(data: &'a [u8]) -> Result<Self> {
1154 need_in(data, 1, "adaptation_field_extension_length")?;
1155 let ext_len = data[0] as usize;
1156 if data.len() < 1 + ext_len || ext_len < 1 {
1158 return Err(Error::BufferTooShort(
1159 broadcast_core::error::BufferTooShort::new(
1160 2.max(1 + ext_len),
1161 data.len(),
1162 "adaptation_field_extension body",
1163 ),
1164 ));
1165 }
1166 let ext = &data[1..1 + ext_len]; let flags = ext[0];
1168 let mut cursor = 1usize;
1169
1170 let ltw = if flags & AFE_LTW_FLAG != 0 {
1171 need_in(ext, cursor + LTW_FIELD_LEN, "ltw_offset")?;
1172 let w0 = ext[cursor];
1173 let w1 = ext[cursor + 1];
1174 cursor += LTW_FIELD_LEN;
1175 Some(Ltw {
1176 ltw_valid_flag: (w0 & AFE_LTW_FLAG) != 0,
1177 ltw_offset: LtwOffset::from_wire_masked(w0, w1),
1178 })
1179 } else {
1180 None
1181 };
1182
1183 let mut piecewise_rate_reserved = PIECEWISE_RATE_RESERVED_VALUE;
1184 let piecewise_rate = if flags & AFE_PIECEWISE_RATE_FLAG != 0 {
1185 need_in(ext, cursor + PIECEWISE_RATE_FIELD_LEN, "piecewise_rate")?;
1186 piecewise_rate_reserved = ext[cursor] >> PIECEWISE_RATE_RESERVED_SHIFT;
1187 let r = PiecewiseRate::from_wire_masked(
1188 ext[cursor + PIECEWISE_RATE_HI_OFFSET],
1189 ext[cursor + PIECEWISE_RATE_MID_OFFSET],
1190 ext[cursor + PIECEWISE_RATE_LO_OFFSET],
1191 );
1192 cursor += PIECEWISE_RATE_FIELD_LEN;
1193 Some(r)
1194 } else {
1195 None
1196 };
1197
1198 let seamless_splice = if flags & AFE_SEAMLESS_SPLICE_FLAG != 0 {
1200 need_in(
1201 ext,
1202 cursor + DTS_NEXT_AU_FIELD_LEN,
1203 "seamless_splice DTS_next_AU",
1204 )?;
1205 let mut field = [0_u8; DTS_NEXT_AU_FIELD_LEN];
1206 field.copy_from_slice(&ext[cursor..cursor + DTS_NEXT_AU_FIELD_LEN]);
1207 let splice = SeamlessSplice::from_marked_field(&field);
1210 cursor += DTS_NEXT_AU_FIELD_LEN;
1211 Some(splice)
1212 } else {
1213 None
1214 };
1215
1216 Ok(AdaptationFieldExtension {
1217 ltw,
1218 piecewise_rate,
1219 piecewise_rate_reserved,
1220 seamless_splice,
1221 af_descriptor_not_present_flag: flags & AFE_AF_DESCRIPTOR_NOT_PRESENT_FLAG != 0,
1222 reserved_flags: flags & AFE_RESERVED_FLAGS_MASK,
1223 trailing: &ext[cursor..],
1224 })
1225 }
1226
1227 #[must_use]
1230 pub fn serialized_len(&self) -> usize {
1231 let body = 1 + self.ltw.map_or(0, |_| LTW_FIELD_LEN)
1233 + self.piecewise_rate.map_or(0, |_| PIECEWISE_RATE_FIELD_LEN)
1234 + self.seamless_splice.map_or(0, |_| DTS_NEXT_AU_FIELD_LEN)
1235 + self.trailing.len();
1236 1 + body }
1238
1239 pub fn serialize_into(&self, buf: &mut [u8]) -> Result<usize> {
1241 let need = self.serialized_len();
1242 need_out(buf, need, "AdaptationFieldExtension")?;
1243 buf[0] = broadcast_core::len::fit_u8(need - 1, "adaptation_field_extension_length")?;
1244
1245 let mut flags = broadcast_core::len::fit_mask(
1246 self.reserved_flags,
1247 AFE_RESERVED_FLAGS_MASK,
1248 "adaptation_field_extension.reserved",
1249 )?;
1250 if self.ltw.is_some() {
1251 flags |= AFE_LTW_FLAG;
1252 }
1253 if self.piecewise_rate.is_some() {
1254 flags |= AFE_PIECEWISE_RATE_FLAG;
1255 }
1256 if self.seamless_splice.is_some() {
1257 flags |= AFE_SEAMLESS_SPLICE_FLAG;
1258 }
1259 if self.af_descriptor_not_present_flag {
1260 flags |= AFE_AF_DESCRIPTOR_NOT_PRESENT_FLAG;
1261 }
1262 buf[1] = flags;
1263 let mut cursor = AFE_PREFIX_LEN;
1264
1265 if let Some(ltw) = self.ltw {
1266 let ltw_valid = if ltw.ltw_valid_flag { AFE_LTW_FLAG } else { 0 };
1267 let offset = broadcast_core::len::fit_bits(
1268 u64::from(ltw.ltw_offset.get()),
1269 LTW_OFFSET_BITS,
1270 "ltw_offset",
1271 )?;
1272 buf[cursor] = ltw_valid | ((offset >> HIGH_BYTE_SHIFT) as u8 & LTW_OFFSET_HI_MASK);
1273 buf[cursor + 1] = offset as u8;
1274 cursor += LTW_FIELD_LEN;
1275 }
1276 if let Some(rate) = self.piecewise_rate {
1277 let rate = broadcast_core::len::fit_bits(
1278 u64::from(rate.get()),
1279 PIECEWISE_RATE_BITS,
1280 "piecewise_rate",
1281 )?;
1282 buf[cursor] = (broadcast_core::len::fit_mask(
1284 self.piecewise_rate_reserved,
1285 PIECEWISE_RATE_RESERVED_VALUE,
1286 "piecewise_rate.reserved",
1287 )? << PIECEWISE_RATE_RESERVED_SHIFT)
1288 | ((rate >> PIECEWISE_RATE_HI_SHIFT) as u8 & PIECEWISE_RATE_HI_MASK);
1289 buf[cursor + 1] = (rate >> HIGH_BYTE_SHIFT) as u8;
1290 buf[cursor + PIECEWISE_RATE_LO_OFFSET] = rate as u8;
1291 cursor += PIECEWISE_RATE_FIELD_LEN;
1292 }
1293 if let Some(ss) = self.seamless_splice {
1294 buf[cursor..cursor + DTS_NEXT_AU_FIELD_LEN].copy_from_slice(&ss.to_marked_field()?);
1296 cursor += DTS_NEXT_AU_FIELD_LEN;
1297 }
1298 buf[cursor..cursor + self.trailing.len()].copy_from_slice(self.trailing);
1299 cursor += self.trailing.len();
1300 Ok(cursor)
1301 }
1302}
1303
1304#[non_exhaustive]
1313#[derive(Clone, Debug, PartialEq, Eq)]
1314#[cfg_attr(feature = "serde", derive(serde::Serialize))]
1315pub struct AdaptationField<'a> {
1316 pub discontinuity_indicator: bool,
1318 pub random_access_indicator: bool,
1320 pub elementary_stream_priority_indicator: bool,
1322 pub pcr: Option<Pcr>,
1324 pub opcr: Option<Pcr>,
1326 pub splice_countdown: Option<i8>,
1328 pub transport_private_data: Option<&'a [u8]>,
1333 pub extension: Option<AdaptationFieldExtension<'a>>,
1335 pub pcr_reserved: u8,
1341 pub opcr_reserved: u8,
1343 pub stuffing: &'a [u8],
1353}
1354
1355impl Default for AdaptationField<'_> {
1356 fn default() -> Self {
1357 Self::new()
1358 }
1359}
1360
1361pub(crate) fn set_pcr_reserved(field: &mut [u8], reserved: u8) -> Result<()> {
1363 let reserved = broadcast_core::len::fit_bits(
1364 u64::from(reserved),
1365 PCR_RESERVED_BITS_COUNT,
1366 "pcr_reserved",
1367 )?;
1368 field[PCR_RESERVED_BYTE_OFFSET] = (field[PCR_RESERVED_BYTE_OFFSET] & !PCR_RESERVED_BITS)
1369 | (((reserved as u8) << PCR_RESERVED_SHIFT) & PCR_RESERVED_BITS);
1370 Ok(())
1371}
1372
1373impl<'a> AdaptationField<'a> {
1374 #[must_use]
1378 pub const fn new() -> Self {
1379 Self {
1380 discontinuity_indicator: false,
1381 random_access_indicator: false,
1382 elementary_stream_priority_indicator: false,
1383 pcr: None,
1384 opcr: None,
1385 splice_countdown: None,
1386 transport_private_data: None,
1387 extension: None,
1388 pcr_reserved: PCR_RESERVED_VALUE,
1389 opcr_reserved: PCR_RESERVED_VALUE,
1390 stuffing: &[],
1391 }
1392 }
1393
1394 pub(crate) fn parse(af: &'a [u8]) -> Result<Self> {
1401 let flags = *af.first().ok_or(Error::BufferTooShort(
1402 broadcast_core::error::BufferTooShort::new(1, 0, "adaptation_field flags"),
1403 ))?;
1404 let mut cursor = 1usize;
1405
1406 let mut pcr_reserved = PCR_RESERVED_VALUE;
1407 let mut opcr_reserved = PCR_RESERVED_VALUE;
1408 let pcr = if flags & AF_PCR_FLAG != 0 {
1409 let p = Pcr::parse(af, cursor)?;
1410 pcr_reserved =
1411 (af[cursor + PCR_RESERVED_BYTE_OFFSET] & PCR_RESERVED_BITS) >> PCR_RESERVED_SHIFT;
1412 cursor += PCR_FIELD_LEN;
1413 Some(p)
1414 } else {
1415 None
1416 };
1417 let opcr = if flags & AF_OPCR_FLAG != 0 {
1418 let p = Pcr::parse(af, cursor)?;
1419 opcr_reserved =
1420 (af[cursor + PCR_RESERVED_BYTE_OFFSET] & PCR_RESERVED_BITS) >> PCR_RESERVED_SHIFT;
1421 cursor += PCR_FIELD_LEN;
1422 Some(p)
1423 } else {
1424 None
1425 };
1426 let splice_countdown = if flags & AF_SPLICING_FLAG != 0 {
1427 let b = *af.get(cursor).ok_or(Error::BufferTooShort(
1428 broadcast_core::error::BufferTooShort::new(
1429 cursor + 1,
1430 af.len(),
1431 "adaptation_field splice_countdown",
1432 ),
1433 ))?;
1434 cursor += 1;
1435 Some(b as i8)
1436 } else {
1437 None
1438 };
1439
1440 let transport_private_data = if flags & AF_TRANSPORT_PRIVATE_DATA_FLAG != 0 {
1443 let tpd_len = *af.get(cursor).ok_or(Error::BufferTooShort(
1444 broadcast_core::error::BufferTooShort::new(
1445 cursor + 1,
1446 af.len(),
1447 "transport_private_data_length",
1448 ),
1449 ))? as usize;
1450 cursor += 1;
1451 let end = cursor + tpd_len;
1452 let slice = af.get(cursor..end).ok_or(Error::BufferTooShort(
1453 broadcast_core::error::BufferTooShort::new(end, af.len(), "transport_private_data"),
1454 ))?;
1455 cursor = end;
1456 Some(slice)
1457 } else {
1458 None
1459 };
1460
1461 let extension = if flags & AF_EXTENSION_FLAG != 0 {
1463 let ext_data = af.get(cursor..).ok_or(Error::BufferTooShort(
1464 broadcast_core::error::BufferTooShort::new(
1465 cursor + 1,
1466 af.len(),
1467 "adaptation_field_extension",
1468 ),
1469 ))?;
1470 let ext = AdaptationFieldExtension::parse(ext_data)?;
1471 if !ext_data.is_empty() {
1473 let _ext_len = ext_data[0] as usize;
1474 cursor += 1 + _ext_len;
1475 }
1476 Some(ext)
1477 } else {
1478 None
1479 };
1480
1481 let stuffing = af.get(cursor..).unwrap_or(&[]);
1485
1486 Ok(AdaptationField {
1487 discontinuity_indicator: flags & AF_DISCONTINUITY != 0,
1488 random_access_indicator: flags & AF_RANDOM_ACCESS != 0,
1489 elementary_stream_priority_indicator: flags & AF_ES_PRIORITY != 0,
1490 pcr,
1491 opcr,
1492 splice_countdown,
1493 transport_private_data,
1494 extension,
1495 pcr_reserved,
1496 opcr_reserved,
1497 stuffing,
1498 })
1499 }
1500
1501 #[must_use]
1507 pub fn serialized_len(&self) -> usize {
1508 let mut n = 1usize; if self.pcr.is_some() {
1510 n += PCR_FIELD_LEN;
1511 }
1512 if self.opcr.is_some() {
1513 n += PCR_FIELD_LEN;
1514 }
1515 if self.splice_countdown.is_some() {
1516 n += 1;
1517 }
1518 if let Some(tpd) = self.transport_private_data {
1519 n += 1 + tpd.len(); }
1521 if let Some(ref ext) = self.extension {
1522 n += ext.serialized_len();
1523 }
1524 n += self.stuffing.len();
1525 n
1526 }
1527
1528 pub fn serialize_into(&self, buf: &mut [u8]) -> Result<usize> {
1539 let need = self.serialized_len();
1540 need_out(buf, need, "AdaptationField")?;
1541
1542 let mut flags = 0u8;
1544 if self.discontinuity_indicator {
1545 flags |= AF_DISCONTINUITY;
1546 }
1547 if self.random_access_indicator {
1548 flags |= AF_RANDOM_ACCESS;
1549 }
1550 if self.elementary_stream_priority_indicator {
1551 flags |= AF_ES_PRIORITY;
1552 }
1553 if self.pcr.is_some() {
1554 flags |= AF_PCR_FLAG;
1555 }
1556 if self.opcr.is_some() {
1557 flags |= AF_OPCR_FLAG;
1558 }
1559 if self.splice_countdown.is_some() {
1560 flags |= AF_SPLICING_FLAG;
1561 }
1562 if self.transport_private_data.is_some() {
1563 flags |= AF_TRANSPORT_PRIVATE_DATA_FLAG;
1564 }
1565 if self.extension.is_some() {
1566 flags |= AF_EXTENSION_FLAG;
1567 }
1568 buf[0] = flags;
1569
1570 let mut cursor = 1usize;
1571 if let Some(pcr) = self.pcr {
1572 buf[cursor..cursor + PCR_FIELD_LEN].copy_from_slice(&pcr.to_field_bytes());
1573 set_pcr_reserved(&mut buf[cursor..cursor + PCR_FIELD_LEN], self.pcr_reserved)?;
1574 cursor += PCR_FIELD_LEN;
1575 }
1576 if let Some(opcr) = self.opcr {
1577 buf[cursor..cursor + PCR_FIELD_LEN].copy_from_slice(&opcr.to_field_bytes());
1578 set_pcr_reserved(&mut buf[cursor..cursor + PCR_FIELD_LEN], self.opcr_reserved)?;
1579 cursor += PCR_FIELD_LEN;
1580 }
1581 if let Some(sc) = self.splice_countdown {
1582 buf[cursor] = sc as u8;
1583 cursor += 1;
1584 }
1585 if let Some(tpd) = self.transport_private_data {
1586 buf[cursor] = broadcast_core::len::fit_u8(
1587 tpd.len(),
1588 "adaptation_field.transport_private_data_length",
1589 )?;
1590 cursor += 1;
1591 buf[cursor..cursor + tpd.len()].copy_from_slice(tpd);
1592 cursor += tpd.len();
1593 }
1594 if let Some(ref ext) = self.extension {
1595 let written = ext.serialize_into(&mut buf[cursor..])?;
1596 cursor += written;
1597 }
1598
1599 buf[cursor..cursor + self.stuffing.len()].copy_from_slice(self.stuffing);
1602 cursor += self.stuffing.len();
1603
1604 Ok(cursor)
1605 }
1606}
1607
1608struct SectionFraming;
1612
1613impl crate::unit::Framing for SectionFraming {
1614 fn length(&self, buf: &[u8]) -> crate::unit::UnitLength {
1615 match section_total_len(buf) {
1616 None => crate::unit::UnitLength::NeedMore,
1617 Some(_) if buf[0] == STUFFING_BYTE => crate::unit::UnitLength::Stuffing,
1618 Some(total) => crate::unit::UnitLength::Total(total),
1619 }
1620 }
1621}
1622
1623pub struct SectionReassembler {
1629 inner: alloc::boxed::Box<crate::unit::UnitReassembler<SectionFraming>>,
1630}
1631
1632impl Default for SectionReassembler {
1633 fn default() -> Self {
1634 Self {
1635 inner: alloc::boxed::Box::new(crate::unit::UnitReassembler::new(
1636 SectionFraming,
1637 crate::unit::UnitOptions::new(
1638 crate::unit::AfterContinuation::DiscardRest,
1639 crate::unit::PointerCheck::Authoritative,
1640 crate::unit::Duplicates::ContinuationOnly,
1641 core::num::NonZeroUsize::MIN.saturating_add(MAX_SECTION_SIZE - 1),
1642 ),
1643 )),
1644 }
1645 }
1646}
1647
1648impl SectionReassembler {
1649 pub fn feed(&mut self, payload: &[u8], pusi: bool) {
1657 let _ = self.inner.feed(payload, pusi, None);
1658 }
1659
1660 pub fn feed_with_continuity(
1675 &mut self,
1676 payload: &[u8],
1677 pusi: bool,
1678 continuity_counter: ContinuityCounter,
1679 discontinuity: bool,
1680 ) {
1681 let _ = self.inner.feed(
1682 payload,
1683 pusi,
1684 Some(crate::unit::Continuity::new(
1685 continuity_counter,
1686 discontinuity,
1687 )),
1688 );
1689 }
1690
1691 pub fn pop_section(&mut self) -> Option<bytes::Bytes> {
1693 self.inner.pop()
1694 }
1695
1696 pub fn len(&self) -> usize {
1698 self.inner.len()
1699 }
1700
1701 pub fn is_empty(&self) -> bool {
1703 self.inner.is_empty()
1704 }
1705}
1706
1707pub fn iter_packets(buf: &[u8]) -> impl Iterator<Item = TsPacket<'_>> {
1725 buf.chunks_exact(TS_PACKET_SIZE)
1726 .filter_map(|chunk| TsPacket::parse(chunk).ok())
1727}
1728
1729pub fn extract_ts_payload(pkt: &[u8]) -> Option<&[u8]> {
1739 if pkt.len() < TsHeader::serialized_len() {
1740 return None;
1741 }
1742 let header = TsHeader::parse(&pkt[..TsHeader::serialized_len()]).ok()?;
1743 if !header.has_payload() {
1744 return None;
1745 }
1746 let cursor = TsHeader::serialized_len() + adaptation_field_skip(pkt, header.has_adaptation());
1747 if cursor < pkt.len() {
1748 Some(&pkt[cursor..])
1749 } else {
1750 None
1751 }
1752}
1753
1754#[cfg(test)]
1755mod tests {
1756 use super::*;
1757
1758 #[test]
1759 fn payload_range_never_panics_for_any_adaptation_field_length() {
1760 for control in 0u8..=3 {
1761 for length in 0u8..=u8::MAX {
1762 let mut raw = [0xFFu8; TS_PACKET_SIZE];
1763 raw[0] = TS_SYNC_BYTE;
1764 raw[1] = 0;
1765 raw[2] = 0;
1766 raw[3] = control << 4;
1767 raw[4] = length;
1768 if let Some(range) = payload_range(&raw) {
1769 assert!(range.start < range.end && range.end <= TS_PACKET_SIZE);
1770 }
1771 }
1772 }
1773 }
1774
1775 #[test]
1776 fn payload_range_follows_adaptation_field_control() {
1777 let mut raw = [0u8; TS_PACKET_SIZE];
1778 raw[0] = TS_SYNC_BYTE;
1779 raw[3] = 0x10;
1780 assert_eq!(payload_range(&raw), Some(4..TS_PACKET_SIZE));
1781 raw[3] = 0x20;
1782 assert_eq!(payload_range(&raw), None);
1783 raw[3] = 0x30;
1784 raw[4] = 7;
1785 assert_eq!(payload_range(&raw), Some(12..TS_PACKET_SIZE));
1786 raw[4] = 183;
1787 assert_eq!(payload_range(&raw), None);
1788 raw[4] = 0;
1789 assert_eq!(payload_range(&raw), Some(5..TS_PACKET_SIZE));
1790 raw[3] = 0x00;
1791 assert_eq!(payload_range(&raw), None);
1792 }
1793
1794 #[test]
1795 fn payload_range_agrees_with_the_parsed_payload() {
1796 let mut raw = [0x55u8; TS_PACKET_SIZE];
1797 raw[0] = TS_SYNC_BYTE;
1798 for control in [0x10u8, 0x20, 0x30] {
1799 for af_len in [0u8, 1, 50, 182, 183, 184, 255] {
1800 raw[3] = control;
1801 raw[4] = af_len;
1802 let parsed = TsPacket::parse(&raw).expect("sync byte present");
1803 let expected = parsed
1804 .payload
1805 .map(|p| TS_PACKET_SIZE - p.len()..TS_PACKET_SIZE);
1806 assert_eq!(payload_range(&raw), expected, "{control:#x}/{af_len}");
1807 }
1808 }
1809 }
1810
1811 fn cc(v: u8) -> ContinuityCounter {
1812 ContinuityCounter::try_new(v).expect("4-bit counter")
1813 }
1814 use alloc::string::ToString;
1815 use alloc::vec;
1816 use alloc::vec::Vec;
1817
1818 fn make_packet(b1: u8, b2: u8, b3: u8, payload_data: &[u8]) -> [u8; TS_PACKET_SIZE] {
1820 let mut pkt = [0u8; TS_PACKET_SIZE];
1821 pkt[0] = TS_SYNC_BYTE;
1822 pkt[1] = b1;
1823 pkt[2] = b2;
1824 pkt[3] = b3;
1825 let payload_start = 4;
1826 let end = (payload_start + payload_data.len()).min(TS_PACKET_SIZE);
1827 let len = (end - payload_start).min(payload_data.len());
1828 pkt[payload_start..payload_start + len].copy_from_slice(&payload_data[..len]);
1829 pkt
1830 }
1831
1832 #[test]
1833 fn parse_rejects_non_0x47_sync_byte() {
1834 let mut pkt = [0u8; TS_PACKET_SIZE];
1835 pkt[0] = 0x46; let err = TsPacket::parse(&pkt).unwrap_err();
1837 match err {
1838 Error::InvalidSync(e) => assert_eq!(e.found, 0x46),
1839 other => panic!("expected InvalidSyncByte, got {other:?}"),
1840 }
1841 }
1842
1843 #[test]
1844 fn ts_header_round_trip() {
1845 let cases = [
1848 TsHeader {
1849 tei: false,
1850 pusi: true,
1851 pid: Pid::from_const(0x0000),
1852 scrambling: ScramblingControl::NotScrambled,
1853 adaptation_field_control: AdaptationFieldControl::PayloadOnly,
1854 continuity_counter: ContinuityCounter::ZERO,
1855 },
1856 TsHeader {
1857 tei: true,
1858 pusi: false,
1859 pid: Pid::from_const(0x1FFF),
1860 scrambling: ScramblingControl::OddKey,
1861 adaptation_field_control: AdaptationFieldControl::AdaptationAndPayload,
1862 continuity_counter: ContinuityCounter::try_new(0x0F).expect("4-bit counter"),
1863 },
1864 TsHeader {
1865 tei: false,
1866 pusi: false,
1867 pid: Pid::from_const(0x0100),
1868 scrambling: ScramblingControl::EvenKey,
1869 adaptation_field_control: AdaptationFieldControl::AdaptationOnly,
1870 continuity_counter: ContinuityCounter::try_new(7).expect("4-bit counter"),
1871 },
1872 ];
1873 for h in cases {
1874 let mut buf = [0u8; 4];
1875 assert_eq!(h.serialize_into(&mut buf).unwrap(), 4);
1876 assert_eq!(TsHeader::parse(&buf).unwrap(), h, "round-trip mismatch");
1877 }
1878 }
1879
1880 #[test]
1881 fn parse_extracts_pid_and_continuity_counter() {
1882 let pkt = make_packet(0x12, 0x34, 0x05, &[]);
1888 let pkt = TsPacket::parse(&pkt).unwrap();
1889 assert_eq!(pkt.header.pid, Pid::from_const(0x1234));
1890 assert_eq!(pkt.header.continuity_counter.value(), 5);
1891 }
1892
1893 #[test]
1894 fn payload_unit_start_indicator_flag_extracted() {
1895 let pkt1 = make_packet(0x40, 0x00, 0x00, &[]);
1897 let pkt1 = TsPacket::parse(&pkt1).unwrap();
1898 assert!(pkt1.header.pusi);
1899
1900 let pkt2 = make_packet(0x00, 0x00, 0x00, &[]);
1902 let pkt2 = TsPacket::parse(&pkt2).unwrap();
1903 assert!(!pkt2.header.pusi);
1904 }
1905
1906 fn build_pusi_payload(pointer_field: u8, previous_tail: &[u8], section: &[u8]) -> Vec<u8> {
1911 assert_eq!(pointer_field as usize, previous_tail.len());
1912 let mut v = Vec::with_capacity(1 + previous_tail.len() + section.len());
1913 v.push(pointer_field);
1914 v.extend_from_slice(previous_tail);
1915 v.extend_from_slice(section);
1916 v
1917 }
1918
1919 #[test]
1925 fn reassembler_accumulates_multi_packet_section() {
1926 let body = vec![0xAAu8; 197];
1928 let section = test_fixtures::psi::short_section(0x02, &body);
1929 assert_eq!(section.len(), 200);
1930
1931 let first_chunk = 100;
1932 let payload1 = build_pusi_payload(0, &[], §ion[..first_chunk]);
1933 let payload2 = section[first_chunk..].to_vec();
1934
1935 let mut reasm = SectionReassembler::default();
1936 reasm.feed(&payload1, true);
1937 reasm.feed(&payload2, false);
1938
1939 let out = reasm.pop_section().expect("section should be ready");
1940 assert_eq!(out.len(), 200);
1941 assert_eq!(out.as_ref(), §ion[..]);
1942 }
1943
1944 #[test]
1945 fn reassembler_yields_complete_section_once_length_satisfied() {
1946 let section = test_fixtures::psi::short_section(0x42, &[0xAA]);
1948 assert_eq!(section.len(), 4);
1949 let payload = build_pusi_payload(0, &[], §ion);
1950
1951 let mut reasm = SectionReassembler::default();
1952 reasm.feed(&payload, true);
1953
1954 let out = reasm
1955 .pop_section()
1956 .expect("single-packet section should pop");
1957 assert_eq!(out.as_ref(), §ion[..]);
1958 }
1959
1960 #[test]
1964 fn a_maximum_section_length_holds_only_the_bytes_supplied() {
1965 let head = [0x00u8, 0xB0, 0xFF, 0x00, 0x00];
1967 let payload = build_pusi_payload(0, &[], &head);
1968 let mut reasm = SectionReassembler::default();
1969 reasm.feed(&payload, true);
1970 assert_eq!(reasm.len(), head.len(), "only the bytes fed");
1971 assert!(reasm.pop_section().is_none(), "the section is incomplete");
1972
1973 let continuation = [0xAAu8; 16];
1974 reasm.feed(&continuation, false);
1975 assert_eq!(reasm.len(), head.len() + continuation.len());
1976 assert!(reasm.len() <= MAX_SECTION_SIZE);
1977 }
1978
1979 #[test]
1980 fn reassembler_extracts_all_concatenated_sections_in_one_payload() {
1981 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();
1990 concat.extend_from_slice(&s1);
1991 concat.extend_from_slice(&s2);
1992 concat.extend_from_slice(&s3);
1993 let payload = build_pusi_payload(0, &[], &concat);
1994
1995 let mut reasm = SectionReassembler::default();
1996 reasm.feed(&payload, true);
1997
1998 let got: Vec<_> = core::iter::from_fn(|| reasm.pop_section()).collect();
2000 assert_eq!(got.len(), 3, "all three concatenated sections must pop");
2001 assert_eq!(got[0].as_ref(), &s1[..]);
2002 assert_eq!(got[1].as_ref(), &s2[..]);
2003 assert_eq!(got[2].as_ref(), &s3[..]);
2004 }
2005
2006 #[test]
2007 fn reassembler_stops_at_stuffing_after_concatenated_sections() {
2008 let s1 = test_fixtures::psi::short_section(0x42, &[0xAA]); let s2 = test_fixtures::psi::short_section(0x46, &[0xBB, 0xCC]); let mut concat = Vec::new();
2014 concat.extend_from_slice(&s1);
2015 concat.extend_from_slice(&s2);
2016 concat.extend_from_slice(&[0xFF, 0xFF, 0xFF, 0xFF]); let payload = build_pusi_payload(0, &[], &concat);
2018
2019 let mut reasm = SectionReassembler::default();
2020 reasm.feed(&payload, true);
2021
2022 let got: Vec<_> = core::iter::from_fn(|| reasm.pop_section()).collect();
2023 assert_eq!(got.len(), 2);
2024 assert_eq!(got[0].as_ref(), &s1[..]);
2025 assert_eq!(got[1].as_ref(), &s2[..]);
2026 assert!(
2027 reasm.is_empty(),
2028 "stuffing tail must be discarded, not buffered"
2029 );
2030 }
2031
2032 #[test]
2033 fn reassembler_concatenated_then_spanning_tail() {
2034 let s1 = test_fixtures::psi::short_section(0x42, &[0x01, 0x02]); let s2 = test_fixtures::psi::short_section(0x46, &[0x09u8; 60]); let split = 30;
2040
2041 let mut head = Vec::new();
2042 head.extend_from_slice(&s1);
2043 head.extend_from_slice(&s2[..split]);
2044 let payload1 = build_pusi_payload(0, &[], &head);
2045 let payload2 = s2[split..].to_vec();
2046
2047 let mut reasm = SectionReassembler::default();
2048 reasm.feed(&payload1, true);
2049 let first = reasm.pop_section().expect("first section pops at once");
2050 assert_eq!(first.as_ref(), &s1[..]);
2051 assert!(reasm.pop_section().is_none(), "second is still partial");
2052
2053 reasm.feed(&payload2, false);
2054 let second = reasm.pop_section().expect("second pops after continuation");
2055 assert_eq!(second.as_ref(), &s2[..]);
2056 }
2057
2058 #[test]
2059 fn reassembler_completes_section_spanning_into_pusi_packet() {
2060 let spanning = test_fixtures::psi::short_section(0x42, &[0x5Au8; 62]); let head = 41;
2068 let tail = &spanning[head..]; assert_eq!(tail.len(), 24);
2070
2071 let next = test_fixtures::psi::short_section(0x46, &[0x77, 0x88]); let payload_a = build_pusi_payload(0, &[], &spanning[..head]);
2076 let payload_b = build_pusi_payload(24, tail, &next);
2078
2079 let mut reasm = SectionReassembler::default();
2080 reasm.feed(&payload_a, true);
2081 assert!(reasm.pop_section().is_none(), "head alone is incomplete");
2082
2083 reasm.feed(&payload_b, true);
2084 let got: Vec<_> = core::iter::from_fn(|| reasm.pop_section()).collect();
2085 assert_eq!(got.len(), 2, "spanning section + new section must both pop");
2086 assert_eq!(
2087 got[0].as_ref(),
2088 &spanning[..],
2089 "spanning section completed from B's pointer tail"
2090 );
2091 assert_eq!(got[1].as_ref(), &next[..]);
2092 }
2093
2094 #[test]
2095 fn reassembler_pusi_pointer_spans_whole_payload() {
2096 let spanning = test_fixtures::psi::short_section(0x42, &[0x33u8; 40]); let head = 20;
2101 let payload_a = build_pusi_payload(0, &[], &spanning[..head]);
2102 let tail = &spanning[head..]; let mut reasm = SectionReassembler::default();
2105 reasm.feed(&payload_a, true);
2106 reasm.feed(&build_pusi_payload_pointer_spanning_all(tail), true);
2108
2109 let out = reasm.pop_section().expect("spanning section completes");
2110 assert_eq!(out.as_ref(), &spanning[..]);
2111 assert!(reasm.pop_section().is_none());
2112 }
2113
2114 fn build_pusi_payload_pointer_spanning_all(tail: &[u8]) -> Vec<u8> {
2117 let mut v = Vec::with_capacity(1 + tail.len());
2118 v.push(tail.len() as u8);
2119 v.extend_from_slice(tail);
2120 v
2121 }
2122
2123 #[test]
2124 fn reassembler_discards_a_retransmitted_continuation_packet() {
2125 let mut section = vec![0x4Eu8, 0xB0, 0x00];
2126 section.resize(300, 0x5A);
2127 section[1] = 0xB0 | (((300 - 3) >> 8) as u8);
2128 section[2] = ((300 - 3) & 0xFF) as u8;
2129 let mut first = vec![0x00u8];
2130 first.extend_from_slice(§ion[..183]);
2131
2132 let mut reasm = SectionReassembler::default();
2133 reasm.feed_with_continuity(&first, true, cc(0), false);
2134 reasm.feed_with_continuity(§ion[183..250], false, cc(1), false);
2135 reasm.feed_with_continuity(§ion[183..250], false, cc(1), false);
2136 reasm.feed_with_continuity(§ion[250..], false, cc(2), false);
2137
2138 let out = reasm.pop_section().expect("section survives the duplicate");
2139 assert_eq!(out.as_ref(), §ion[..]);
2140 assert!(reasm.pop_section().is_none());
2141 }
2142
2143 #[test]
2144 fn a_packet_after_a_discontinuity_with_an_unchanged_counter_is_not_a_duplicate() {
2145 let mut section = vec![0x4Eu8, 0xB0, 0x00];
2146 section.resize(300, 0x5A);
2147 section[1] = 0xB0 | (((300 - 3) >> 8) as u8);
2148 section[2] = ((300 - 3) & 0xFF) as u8;
2149 let mut first = vec![0x00u8];
2150 first.extend_from_slice(§ion[..183]);
2151
2152 let mut reasm = SectionReassembler::default();
2153 reasm.feed_with_continuity(&first, true, cc(0), false);
2154 reasm.feed_with_continuity(§ion[183..250], false, cc(0), true);
2155 reasm.feed_with_continuity(§ion[250..], false, cc(1), false);
2156
2157 let out = reasm
2158 .pop_section()
2159 .expect("section survives the discontinuity");
2160 assert_eq!(out.as_ref(), §ion[..]);
2161 assert!(reasm.pop_section().is_none());
2162 }
2163
2164 #[test]
2165 fn reassembler_completes_max_length_section_and_stays_usable() {
2166 let mut section = Vec::with_capacity(MAX_SECTION_SIZE);
2172 section.push(0x00); section.push(0xB0 | ((4095u16 >> 8) as u8 & 0x0F));
2174 section.push(0xFF); section.resize(MAX_SECTION_SIZE, 0u8);
2176 assert_eq!(section.len(), MAX_SECTION_SIZE);
2177
2178 let mut reasm = SectionReassembler::default();
2179 let mut first = vec![0x00u8]; first.extend_from_slice(§ion[..183]);
2181 reasm.feed(&first, true);
2182 assert!(
2183 reasm.pop_section().is_none(),
2184 "incomplete until the declared length arrives"
2185 );
2186
2187 for chunk in section[183..].chunks(184) {
2188 reasm.feed(chunk, false);
2189 }
2190 let out = reasm
2191 .pop_section()
2192 .expect("max-length section completes at its declared length");
2193 assert_eq!(out.len(), MAX_SECTION_SIZE);
2194 assert_eq!(out.as_ref(), §ion[..]);
2195 assert!(reasm.is_empty());
2196
2197 reasm.feed(&[0u8; 184], false);
2201 assert!(reasm.pop_section().is_none());
2202
2203 let valid_section = test_fixtures::psi::short_section(0x00, &[0xAA]);
2205 let payload2 = build_pusi_payload(0, &[], &valid_section);
2206 reasm.feed(&payload2, true);
2207 let out = reasm
2208 .pop_section()
2209 .expect("fresh section should pop after reset");
2210 assert_eq!(out.as_ref(), &valid_section[..]);
2211 }
2212
2213 #[test]
2214 fn reassembler_handles_pusi_with_nonzero_pointer_field() {
2215 let prior_tail = vec![0x11, 0x22, 0x33];
2217 let new_section = test_fixtures::psi::short_section(0x02, &[0xBB]);
2218 assert_eq!(new_section.len(), 4);
2219 let payload = build_pusi_payload(3, &prior_tail, &new_section);
2220
2221 let mut reasm = SectionReassembler::default();
2222 reasm.feed(&payload, true);
2223
2224 let out = reasm
2225 .pop_section()
2226 .expect("section after pointer_field skip should pop");
2227 assert_eq!(out.as_ref(), &new_section[..]);
2228 }
2229
2230 #[test]
2231 fn reassembler_ignores_continuation_before_pusi() {
2232 let pkt = make_packet(0x00, 0x00, PAYLOAD_FLAG, &[0xAA, 0xBB, 0xCC]);
2235
2236 let mut reasm = SectionReassembler::default();
2237 reasm.feed(&pkt[4..], false); assert!(
2240 reasm.pop_section().is_none(),
2241 "no section should appear without prior PUSI"
2242 );
2243 assert!(
2244 reasm.pop_section().is_none(),
2245 "second pop should also be none"
2246 );
2247 }
2248
2249 #[test]
2252 fn reassembler_empty_pusi_payload_does_not_panic() {
2253 let mut reasm = SectionReassembler::default();
2254 reasm.feed(&[], true);
2255 assert!(reasm.pop_section().is_none());
2256 let payload = vec![0x00u8, 0x72, 0x70, 0x01, 0x00];
2258 reasm.feed(&payload, true);
2259 assert!(reasm.pop_section().is_some());
2260 }
2261
2262 #[test]
2266 fn reassembler_accepts_maximal_private_section() {
2267 let mut section = vec![0x80u8, 0x7F, 0xFF]; section.resize(3 + 0xFFF, 0xAB);
2269
2270 let mut reasm = SectionReassembler::default();
2271 let mut first = vec![0x00];
2273 first.extend_from_slice(§ion[..183]);
2274 reasm.feed(&first, true);
2275 for chunk in section[183..].chunks(184) {
2276 reasm.feed(chunk, false);
2277 }
2278 let out = reasm.pop_section().expect("4098-byte section should pop");
2279 assert_eq!(out.len(), 4098);
2280 assert_eq!(out.as_ref(), §ion[..]);
2281 }
2282
2283 #[test]
2288 fn reassembler_completes_large_section_with_trailing_stuffing() {
2289 let body = vec![0x5Au8; 4096 - 3];
2290 let section = test_fixtures::psi::short_section(0x50, &body); assert_eq!(section.len(), 4096);
2292
2293 let mut reasm = SectionReassembler::default();
2294 let mut first = vec![0x00u8];
2296 first.extend_from_slice(§ion[..183]);
2297 reasm.feed(&first, true);
2298
2299 let mut pos = 183usize;
2303 while pos < section.len() {
2304 let take = (section.len() - pos).min(184);
2305 let mut payload = section[pos..pos + take].to_vec();
2306 if take < 184 {
2307 payload.resize(184, 0xFF); }
2309 reasm.feed(&payload, false);
2310 pos += take;
2311 }
2312
2313 let out = reasm
2314 .pop_section()
2315 .expect("4096-byte section must complete despite trailing stuffing (#148)");
2316 assert_eq!(out.len(), 4096);
2317 assert_eq!(out.as_ref(), §ion[..]);
2318 assert!(reasm.is_empty(), "stuffing tail must be discarded");
2319 }
2320
2321 #[test]
2324 fn pcr_as_27mhz_known_value() {
2325 assert_eq!(
2326 Pcr::from_parts(10_000, 0).expect("in range").as_27mhz(),
2327 3_000_000
2328 );
2329 assert_eq!(Pcr::from_parts(1, 100).expect("in range").as_27mhz(), 400);
2331 }
2332
2333 #[test]
2334 fn pcr_decode_from_bytes() {
2335 let af = [0x10u8, 0x00, 0x00, 0x13, 0x88, 0x7E, 0x00];
2337 let pcr = Pcr::parse(&af, 1).expect("6 bytes present");
2338 assert_eq!(pcr, Pcr::from_parts(10_000, 0).expect("in range"));
2339 assert_eq!((pcr.base(), pcr.extension()), (10_000, 0));
2340 assert_eq!(pcr.as_27mhz(), 3_000_000);
2341 }
2342
2343 #[test]
2344 fn adaptation_field_flags_and_pcr() {
2345 let mut raw = [0xAAu8; TS_PACKET_SIZE];
2346 raw[0] = TS_SYNC_BYTE;
2347 raw[1] = 0x01; raw[2] = 0x00;
2349 raw[3] = ADAPTATION_FLAG | PAYLOAD_FLAG;
2350 raw[4] = 7; raw[5] = AF_DISCONTINUITY | AF_PCR_FLAG;
2352 raw[6..12].copy_from_slice(&[0x00, 0x00, 0x13, 0x88, 0x7E, 0x00]);
2353 let pkt = TsPacket::parse(&raw).expect("valid packet");
2356 let af = pkt
2357 .adaptation_field()
2358 .expect("has adaptation field")
2359 .expect("adaptation field parses");
2360 assert!(af.discontinuity_indicator);
2361 assert!(!af.random_access_indicator);
2362 assert_eq!(af.pcr, Some(Pcr::from_parts(10_000, 0).expect("in range")));
2363 assert_eq!(af.pcr.unwrap().as_27mhz(), 3_000_000);
2364 assert!(af.opcr.is_none());
2365 assert!(af.splice_countdown.is_none());
2366 let payload = pkt.payload.expect("payload present");
2368 assert_eq!(payload.len(), TS_PACKET_SIZE - 12);
2369 assert_eq!(payload[0], 0xAA);
2370 }
2371
2372 #[test]
2378 fn clock_reference_slot_locates_pcr_then_opcr_and_rejects_unreached_fields() {
2379 let mut raw = [0xAAu8; TS_PACKET_SIZE];
2380 raw[0] = TS_SYNC_BYTE;
2381 raw[3] = ADAPTATION_FLAG | PAYLOAD_FLAG;
2382 raw[4] = (1 + 2 * PCR_FIELD_LEN) as u8; raw[5] = AF_PCR_FLAG | AF_OPCR_FLAG;
2384
2385 assert!(matches!(
2387 clock_reference_slot(&raw, AF_PCR_FLAG),
2388 ClockReferenceSlot::Field(r) if r == (CLOCK_REFERENCE_START..CLOCK_REFERENCE_START + PCR_FIELD_LEN)
2389 ));
2390 assert!(matches!(
2391 clock_reference_slot(&raw, AF_OPCR_FLAG),
2392 ClockReferenceSlot::Field(r) if r == (CLOCK_REFERENCE_START + PCR_FIELD_LEN..CLOCK_REFERENCE_START + 2 * PCR_FIELD_LEN)
2393 ));
2394
2395 raw[4] = (1 + PCR_FIELD_LEN) as u8;
2398 assert!(matches!(
2399 clock_reference_slot(&raw, AF_OPCR_FLAG),
2400 ClockReferenceSlot::TooShort { need, have }
2401 if need == 1 + 2 * PCR_FIELD_LEN && have == 1 + PCR_FIELD_LEN
2402 ));
2403
2404 let payload_only = {
2406 let mut p = raw;
2407 p[3] = PAYLOAD_FLAG;
2408 p
2409 };
2410 assert!(matches!(
2411 clock_reference_slot(&payload_only, AF_PCR_FLAG),
2412 ClockReferenceSlot::NoAdaptationField
2413 ));
2414
2415 raw[4] = (1 + PCR_FIELD_LEN) as u8;
2417 raw[5] = AF_OPCR_FLAG;
2418 assert!(matches!(
2419 clock_reference_slot(&raw, AF_PCR_FLAG),
2420 ClockReferenceSlot::FlagClear
2421 ));
2422
2423 raw[5] = AF_PCR_FLAG;
2427 let truncated = &raw[..8];
2428 assert!(matches!(
2429 clock_reference_slot(truncated, AF_PCR_FLAG),
2430 ClockReferenceSlot::Truncated { need, have } if need == 12 && have == 8
2431 ));
2432 }
2433
2434 #[test]
2435 fn oversized_adaptation_field_length_is_rejected_not_truncated() {
2436 let mut raw = [0xAAu8; TS_PACKET_SIZE];
2442 raw[0] = TS_SYNC_BYTE;
2443 raw[1] = 0x01;
2444 raw[2] = 0x00;
2445 raw[3] = ADAPTATION_FLAG; raw[4] = 200; let pkt = TsPacket::parse(&raw).expect("header + af_len byte still parse");
2449 assert!(
2450 pkt.adaptation_field().is_none(),
2451 "an over-long adaptation field must be rejected, not truncated"
2452 );
2453 assert!(pkt.payload.is_none());
2454
2455 let owned = crate::owned::OwnedTsPacket::parse(raw).unwrap();
2457 assert!(owned.adaptation_field().is_none());
2458 }
2459
2460 #[test]
2461 fn no_adaptation_returns_none() {
2462 let mut raw = [0x00u8; TS_PACKET_SIZE];
2463 raw[0] = TS_SYNC_BYTE;
2464 raw[1] = 0x01;
2465 raw[3] = PAYLOAD_FLAG; let pkt = TsPacket::parse(&raw).expect("valid");
2467 assert!(pkt.adaptation_field().is_none());
2468 assert!(pkt.adaptation.is_none());
2469 }
2470
2471 #[test]
2472 fn adaptation_field_splice_countdown_negative() {
2473 let mut raw = [0xAAu8; TS_PACKET_SIZE];
2474 raw[0] = TS_SYNC_BYTE;
2475 raw[1] = 0x01;
2476 raw[2] = 0x00;
2477 raw[3] = ADAPTATION_FLAG | PAYLOAD_FLAG;
2478 raw[4] = 2; raw[5] = AF_SPLICING_FLAG;
2480 raw[6] = 0xFB; let pkt = TsPacket::parse(&raw).expect("valid");
2482 let af = pkt.adaptation_field().unwrap().unwrap();
2483 assert_eq!(af.splice_countdown, Some(-5));
2484 assert!(af.pcr.is_none());
2485 }
2486
2487 #[test]
2490 fn scrambling_control_all_values() {
2491 assert_eq!(
2492 ScramblingControl::from_bits(0b00),
2493 ScramblingControl::NotScrambled
2494 );
2495 assert_eq!(
2496 ScramblingControl::from_bits(0b01),
2497 ScramblingControl::Reserved
2498 );
2499 assert_eq!(
2500 ScramblingControl::from_bits(0b10),
2501 ScramblingControl::EvenKey
2502 );
2503 assert_eq!(
2504 ScramblingControl::from_bits(0b11),
2505 ScramblingControl::OddKey
2506 );
2507 assert_eq!(ScramblingControl::NotScrambled.name(), "not_scrambled");
2509 assert_eq!(ScramblingControl::Reserved.name(), "reserved");
2510 assert_eq!(ScramblingControl::EvenKey.name(), "even_key");
2511 assert_eq!(ScramblingControl::OddKey.name(), "odd_key");
2512 assert_eq!(ScramblingControl::NotScrambled.to_string(), "not_scrambled");
2514 assert_eq!(ScramblingControl::OddKey.to_string(), "odd_key");
2515 assert_eq!(
2517 ScramblingControl::from_bits(0xFF),
2518 ScramblingControl::OddKey
2519 );
2520 }
2521
2522 #[test]
2523 fn adaptation_field_control_all_values() {
2524 assert_eq!(
2525 AdaptationFieldControl::from_flags(false, false),
2526 AdaptationFieldControl::Reserved
2527 );
2528 assert_eq!(
2529 AdaptationFieldControl::from_flags(false, true),
2530 AdaptationFieldControl::PayloadOnly
2531 );
2532 assert_eq!(
2533 AdaptationFieldControl::from_flags(true, false),
2534 AdaptationFieldControl::AdaptationOnly
2535 );
2536 assert_eq!(
2537 AdaptationFieldControl::from_flags(true, true),
2538 AdaptationFieldControl::AdaptationAndPayload
2539 );
2540 assert_eq!(AdaptationFieldControl::Reserved.name(), "reserved");
2542 assert_eq!(AdaptationFieldControl::PayloadOnly.name(), "payload_only");
2543 assert_eq!(
2544 AdaptationFieldControl::AdaptationOnly.name(),
2545 "adaptation_only"
2546 );
2547 assert_eq!(
2548 AdaptationFieldControl::AdaptationAndPayload.name(),
2549 "adaptation_and_payload"
2550 );
2551 assert_eq!(
2553 AdaptationFieldControl::PayloadOnly.to_string(),
2554 "payload_only"
2555 );
2556 }
2557
2558 #[test]
2559 fn ts_header_field_types_carry_the_decoded_values() {
2560 let hdr = TsHeader {
2561 tei: false,
2562 pusi: false,
2563 pid: Pid::from_const(0x0100),
2564 scrambling: ScramblingControl::EvenKey,
2565 adaptation_field_control: AdaptationFieldControl::PayloadOnly,
2566 continuity_counter: ContinuityCounter::ZERO,
2567 };
2568 assert_eq!(hdr.scrambling, ScramblingControl::EvenKey);
2569 assert_eq!(
2570 hdr.adaptation_field_control,
2571 AdaptationFieldControl::PayloadOnly
2572 );
2573 assert!(hdr.has_payload());
2574 assert!(!hdr.has_adaptation());
2575
2576 let hdr_both = TsHeader {
2577 adaptation_field_control: AdaptationFieldControl::AdaptationAndPayload,
2578 ..hdr
2579 };
2580 assert_eq!(
2581 hdr_both.adaptation_field_control,
2582 AdaptationFieldControl::AdaptationAndPayload
2583 );
2584 assert!(hdr_both.has_adaptation() && hdr_both.has_payload());
2585 }
2586
2587 #[test]
2588 fn reserved_adaptation_field_control_is_preserved_through_parse_and_serialize() {
2589 let bytes = [TS_SYNC_BYTE, 0x00, 0x00, 0x05];
2592 let hdr = TsHeader::parse(&bytes).expect("parse");
2593 assert_eq!(
2594 hdr.adaptation_field_control,
2595 AdaptationFieldControl::Reserved
2596 );
2597 assert!(!hdr.has_adaptation() && !hdr.has_payload());
2598 let mut out = [0u8; 4];
2599 hdr.serialize_into(&mut out).expect("serialize");
2600 assert_eq!(out, bytes);
2601 }
2602
2603 #[test]
2606 fn iter_packets_yields_valid_and_skips_bad_sync() {
2607 let pkt1 = make_packet(0x00, 0x00, PAYLOAD_FLAG, &[0xAA; 10]);
2609 let pkt2 = make_packet(0x40, 0x64, PAYLOAD_FLAG, &[0xBB; 10]);
2610 let mut bad = [0u8; TS_PACKET_SIZE];
2611 bad[0] = 0x00; let mut buf = Vec::new();
2614 buf.extend_from_slice(&pkt1);
2615 buf.extend_from_slice(&pkt2);
2616 buf.extend_from_slice(&bad);
2617
2618 let pkts: Vec<_> = super::iter_packets(&buf).collect();
2619 assert_eq!(pkts.len(), 2, "bad sync packet must be skipped");
2620 assert_eq!(pkts[0].header.pid, Pid::from_const(0x0000));
2621 assert_eq!(pkts[1].header.pid, Pid::from_const(0x0064));
2622 }
2623
2624 #[test]
2625 fn extract_ts_payload_payload_only() {
2626 let pkt = make_packet(0x00, 0x00, PAYLOAD_FLAG, &[0xABu8; 10]);
2627 let p = super::extract_ts_payload(&pkt).expect("payload present");
2628 assert_eq!(p[0], 0xAB);
2629 assert_eq!(p.len(), TS_PACKET_SIZE - 4);
2630 }
2631
2632 #[test]
2633 fn extract_ts_payload_adaptation_only_returns_none() {
2634 let pkt = make_packet(0x00, 0x00, ADAPTATION_FLAG, &[]);
2635 assert!(super::extract_ts_payload(&pkt).is_none());
2636 }
2637
2638 #[test]
2643 fn pcr_from_27mhz_round_trips() {
2644 for &ticks in &[0u64, 1, 300, 27_000_000, u64::from(u32::MAX), 8_589_934_591] {
2645 let pcr = Pcr::from_27mhz(ticks).expect("in range");
2646 assert_eq!(pcr.as_27mhz(), ticks, "ticks={ticks}");
2647 }
2648 }
2649
2650 #[test]
2656 fn pcr_to_field_bytes_round_trips_parse() {
2657 let cases = [
2658 Pcr::from_parts(0, 0).expect("in range"),
2659 Pcr::from_parts(10_000, 0).expect("in range"),
2660 Pcr::from_parts(1, 100).expect("in range"),
2661 Pcr::from_parts(0x1_FFFF_FFFF, 299).expect("in range"),
2662 ];
2663 for pcr in cases {
2664 let bytes = pcr.to_field_bytes();
2665 let mut af = [0u8; 7];
2668 af[1..7].copy_from_slice(&bytes);
2669 let decoded = Pcr::parse(&af, 1).expect("parse round-trip");
2670 assert_eq!(decoded, pcr, "round-trip failed for {pcr:?}");
2671 }
2672 }
2673
2674 #[test]
2676 fn pcr_full_width_extension_round_trips_the_field() {
2677 let pcr = Pcr::from_parts(0x1_FFFF_FFFF, 299).expect("in range");
2678 assert_eq!(pcr.to_field_bytes(), [0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0x2B]);
2680 assert_eq!(Pcr::parse(&pcr.to_field_bytes(), 0).expect("parse"), pcr);
2681 assert_eq!(
2682 pcr.as_27mhz(),
2683 broadcast_common::clock33::PCR_WRAP_27MHZ - 1
2684 );
2685 }
2686
2687 #[test]
2691 fn pcr_off_clock_wire_extension_parses_losslessly_and_reports() {
2692 let mut bytes = Pcr::from_parts(5, 0).expect("in range").to_field_bytes();
2693 bytes[4] |= 0x01; bytes[5] = 0x2C; let pcr = Pcr::parse(&bytes, 0).expect("a wire-legal field parses");
2696 assert_eq!((pcr.base(), pcr.extension()), (5, 300));
2697 assert_eq!(
2698 pcr.to_field_bytes(),
2699 bytes,
2700 "re-serializes byte-identically"
2701 );
2702 assert!(!pcr.clock().is_valid());
2703 assert!(matches!(
2704 pcr.to_clock27(),
2705 Err(Error::ClockOutOfRange(
2706 broadcast_common::clock33::ClockOutOfRange {
2707 field: "27 MHz extension",
2708 value: 300,
2709 ..
2710 }
2711 ))
2712 ));
2713 for ext in 0u16..512 {
2715 let mut bytes = Pcr::from_parts(0x1_2345_6789 & ((1 << 33) - 1), 0)
2716 .expect("in range")
2717 .to_field_bytes();
2718 bytes[4] = (bytes[4] & !0x01) | ((ext >> 8) as u8 & 0x01);
2719 bytes[5] = (ext & 0xFF) as u8;
2720 let decoded = Pcr::parse(&bytes, 0).expect("extension is 9 bits on the wire");
2721 assert_eq!(decoded.extension(), ext);
2722 assert_eq!(decoded.to_field_bytes(), bytes);
2723 assert_eq!(decoded.to_clock27().is_ok(), ext < 300);
2724 }
2725 }
2726
2727 #[test]
2730 fn pcr_to_field_bytes_known_vector() {
2731 let pcr = Pcr::from_parts(10_000, 0).expect("in range");
2732 let bytes = pcr.to_field_bytes();
2733 assert_eq!(bytes, [0x00, 0x00, 0x13, 0x88, 0x7E, 0x00]);
2734 }
2735
2736 #[test]
2739 fn scrambling_control_to_bits_inverse_of_from_bits() {
2740 for bits in 0u8..=3 {
2741 let sc = ScramblingControl::from_bits(bits);
2742 assert_eq!(sc.to_bits(), bits, "to_bits() != from_bits() for {bits}");
2743 }
2744 }
2745
2746 #[test]
2749 fn adaptation_field_control_to_bits_inverse_of_from_flags() {
2750 let cases = [
2751 (false, false, 0b00u8),
2752 (false, true, 0b01),
2753 (true, false, 0b10),
2754 (true, true, 0b11),
2755 ];
2756 for (has_af, has_pl, expected_bits) in cases {
2757 let afc = AdaptationFieldControl::from_flags(has_af, has_pl);
2758 assert_eq!(afc.to_bits(), expected_bits);
2759 assert_eq!(afc.to_flags(), (has_af, has_pl));
2760 }
2761 }
2762
2763 #[test]
2767 fn adaptation_field_serialize_round_trip_with_pcr() {
2768 let original = AdaptationField {
2769 discontinuity_indicator: true,
2770 random_access_indicator: false,
2771 elementary_stream_priority_indicator: false,
2772 pcr: Some(Pcr::from_parts(10_000, 0).expect("in range")),
2773 opcr: None,
2774 splice_countdown: None,
2775 transport_private_data: None,
2776 extension: None,
2777 stuffing: &[],
2778 pcr_reserved: PCR_RESERVED_VALUE,
2779 opcr_reserved: PCR_RESERVED_VALUE,
2780 };
2781 let len = original.serialized_len();
2782 assert_eq!(len, 7); let mut buf = vec![0u8; len];
2784 let written = original.serialize_into(&mut buf).expect("serialize");
2785 assert_eq!(written, len);
2786 let decoded = AdaptationField::parse(&buf).expect("parse round-trip");
2787 assert_eq!(decoded, original);
2788 }
2789
2790 #[test]
2794 fn transport_private_data_over_255_bytes_rejected_not_wrapped() {
2795 let data = vec![0u8; 256];
2796 let af = AdaptationField {
2797 discontinuity_indicator: false,
2798 random_access_indicator: false,
2799 elementary_stream_priority_indicator: false,
2800 pcr: None,
2801 opcr: None,
2802 splice_countdown: None,
2803 transport_private_data: Some(&data),
2804 extension: None,
2805 stuffing: &[],
2806 pcr_reserved: PCR_RESERVED_VALUE,
2807 opcr_reserved: PCR_RESERVED_VALUE,
2808 };
2809 let mut buf = vec![0u8; af.serialized_len()];
2810 assert!(matches!(
2811 &(af.serialize_into(&mut buf)),
2812 Err(crate::error::Error::FieldOverflow(_))
2813 ));
2814 }
2815
2816 #[test]
2818 fn adaptation_field_serialize_produces_known_bytes() {
2819 let af = AdaptationField {
2823 discontinuity_indicator: true,
2824 random_access_indicator: false,
2825 elementary_stream_priority_indicator: false,
2826 pcr: Some(Pcr::from_parts(10_000, 0).expect("in range")),
2827 opcr: None,
2828 splice_countdown: None,
2829 transport_private_data: None,
2830 extension: None,
2831 stuffing: &[],
2832 pcr_reserved: PCR_RESERVED_VALUE,
2833 opcr_reserved: PCR_RESERVED_VALUE,
2834 };
2835 let mut buf = [0u8; 7];
2836 af.serialize_into(&mut buf).unwrap();
2837 assert_eq!(buf[0], AF_DISCONTINUITY | AF_PCR_FLAG);
2838 assert_eq!(&buf[1..7], &[0x00, 0x00, 0x13, 0x88, 0x7E, 0x00]);
2839 }
2840
2841 #[test]
2843 fn adaptation_field_serialize_round_trip_opcr_and_splice() {
2844 let original = AdaptationField {
2845 discontinuity_indicator: false,
2846 random_access_indicator: true,
2847 elementary_stream_priority_indicator: true,
2848 pcr: Some(Pcr::from_parts(1, 100).expect("in range")),
2849 opcr: Some(Pcr::from_parts(999, 5).expect("in range")),
2850 splice_countdown: Some(-3),
2851 transport_private_data: None,
2852 extension: None,
2853 stuffing: &[],
2854 pcr_reserved: PCR_RESERVED_VALUE,
2855 opcr_reserved: PCR_RESERVED_VALUE,
2856 };
2857 let len = original.serialized_len();
2858 assert_eq!(len, 1 + 6 + 6 + 1); let mut buf = vec![0u8; len];
2860 original.serialize_into(&mut buf).unwrap();
2861 let decoded = AdaptationField::parse(&buf).expect("parse");
2862 assert_eq!(decoded, original);
2863 }
2864
2865 #[test]
2867 fn adaptation_field_serialize_flags_only() {
2868 let af = AdaptationField {
2869 discontinuity_indicator: false,
2870 random_access_indicator: true,
2871 elementary_stream_priority_indicator: false,
2872 pcr: None,
2873 opcr: None,
2874 splice_countdown: None,
2875 transport_private_data: None,
2876 extension: None,
2877 stuffing: &[],
2878 pcr_reserved: PCR_RESERVED_VALUE,
2879 opcr_reserved: PCR_RESERVED_VALUE,
2880 };
2881 assert_eq!(af.serialized_len(), 1);
2882 let mut buf = [0u8; 1];
2883 af.serialize_into(&mut buf).unwrap();
2884 assert_eq!(buf[0], AF_RANDOM_ACCESS);
2885 let decoded = AdaptationField::parse(&buf).unwrap();
2886 assert_eq!(decoded, af);
2887 }
2888
2889 #[test]
2891 fn adaptation_field_serialize_rejects_small_buffer() {
2892 let af = AdaptationField {
2893 discontinuity_indicator: false,
2894 random_access_indicator: false,
2895 elementary_stream_priority_indicator: false,
2896 pcr: Some(Pcr::from_parts(0, 0).expect("in range")),
2897 opcr: None,
2898 splice_countdown: None,
2899 transport_private_data: None,
2900 extension: None,
2901 stuffing: &[],
2902 pcr_reserved: PCR_RESERVED_VALUE,
2903 opcr_reserved: PCR_RESERVED_VALUE,
2904 };
2905 let mut buf = [0u8; 3]; assert!(matches!(
2907 af.serialize_into(&mut buf),
2908 Err(Error::OutputBufferTooSmall(..))
2909 ));
2910 }
2911
2912 #[test]
2916 fn adaptation_field_extension_ltw_round_trip() {
2917 let ext = AdaptationFieldExtension {
2918 ltw: Some(Ltw {
2919 ltw_valid_flag: true,
2920 ltw_offset: LtwOffset::new(0x1234).expect("in range"),
2921 }),
2922 piecewise_rate: None,
2923 seamless_splice: None,
2924 ..AdaptationFieldExtension::new()
2925 };
2926 let mut buf = vec![0u8; ext.serialized_len()];
2927 ext.serialize_into(&mut buf).unwrap();
2928 let af = AdaptationField {
2931 discontinuity_indicator: false,
2932 random_access_indicator: false,
2933 elementary_stream_priority_indicator: false,
2934 pcr: None,
2935 opcr: None,
2936 splice_countdown: None,
2937 transport_private_data: None,
2938 extension: Some(ext),
2939 stuffing: &[],
2940 pcr_reserved: PCR_RESERVED_VALUE,
2941 opcr_reserved: PCR_RESERVED_VALUE,
2942 };
2943 let len = af.serialized_len();
2944 let mut abuf = vec![0u8; len];
2945 af.serialize_into(&mut abuf).unwrap();
2946 let decoded = AdaptationField::parse(&abuf).unwrap();
2947 assert_eq!(decoded.extension, Some(ext));
2948 }
2949
2950 #[test]
2952 fn adaptation_field_extension_piecewise_rate_round_trip() {
2953 let af = AdaptationField {
2954 discontinuity_indicator: false,
2955 random_access_indicator: false,
2956 elementary_stream_priority_indicator: false,
2957 pcr: None,
2958 opcr: None,
2959 splice_countdown: None,
2960 transport_private_data: None,
2961 extension: Some(AdaptationFieldExtension {
2962 ltw: None,
2963 piecewise_rate: Some(PiecewiseRate::MAX),
2964 seamless_splice: None,
2965 ..AdaptationFieldExtension::new()
2966 }),
2967 stuffing: &[],
2968 pcr_reserved: PCR_RESERVED_VALUE,
2969 opcr_reserved: PCR_RESERVED_VALUE,
2970 };
2971 let mut buf = vec![0u8; af.serialized_len()];
2972 af.serialize_into(&mut buf).unwrap();
2973 let decoded = AdaptationField::parse(&buf).unwrap();
2974 assert_eq!(
2975 decoded.extension.unwrap().piecewise_rate,
2976 Some(PiecewiseRate::MAX)
2977 );
2978 }
2979
2980 #[test]
2982 fn adaptation_field_extension_seamless_splice_round_trip() {
2983 let af = AdaptationField {
2984 discontinuity_indicator: false,
2985 random_access_indicator: false,
2986 elementary_stream_priority_indicator: false,
2987 pcr: None,
2988 opcr: None,
2989 splice_countdown: None,
2990 transport_private_data: None,
2991 extension: Some(AdaptationFieldExtension {
2992 ltw: None,
2993 piecewise_rate: None,
2994 seamless_splice: Some(SeamlessSplice::new(0xA, 0x1_2345_6789)),
2995 ..AdaptationFieldExtension::new()
2996 }),
2997 stuffing: &[],
2998 pcr_reserved: PCR_RESERVED_VALUE,
2999 opcr_reserved: PCR_RESERVED_VALUE,
3000 };
3001 let mut buf = vec![0u8; af.serialized_len()];
3002 af.serialize_into(&mut buf).unwrap();
3003 let decoded = AdaptationField::parse(&buf).unwrap();
3004 let ss = decoded.extension.unwrap().seamless_splice.unwrap();
3005 assert_eq!(ss.splice_type, 0xA);
3006 assert_eq!(ss.dts_next_au, 0x1_2345_6789);
3007 }
3008
3009 #[test]
3013 fn adaptation_field_extension_seamless_splice_rejects_over_range_fields() {
3014 let mut ss = SeamlessSplice::new(0xA, 0x1_2345_6789);
3015 ss.dts_next_au = 1 << SeamlessSplice::DTS_NEXT_AU_BITS;
3016 assert!(matches!(ss.to_marked_field(), Err(Error::FieldOverflow(_))));
3017 ss.dts_next_au = (1 << SeamlessSplice::DTS_NEXT_AU_BITS) - 1;
3018 assert!(ss.to_marked_field().is_ok());
3019
3020 let mut ss = SeamlessSplice::new(0x10, 0x1_2345_6789);
3021 assert!(matches!(ss.to_marked_field(), Err(Error::FieldOverflow(_))));
3022 ss.splice_type = 0x0F;
3023 ss.marker_bits = SPLICE_MARKERS_VALUE + 1;
3024 assert!(matches!(ss.to_marked_field(), Err(Error::FieldOverflow(_))));
3025 ss.marker_bits = SPLICE_MARKERS_VALUE;
3026 assert!(ss.to_marked_field().is_ok());
3027 }
3028
3029 #[test]
3033 fn adaptation_field_extension_rejects_over_range_ltw_and_rate() {
3034 assert!(matches!(
3035 LtwOffset::new(0x8000),
3036 Err(Error::FieldOverflow(_))
3037 ));
3038 assert_eq!(LtwOffset::new(LtwOffset::MAX.get()), Ok(LtwOffset::MAX));
3039 assert!(matches!(
3040 PiecewiseRate::new(0x40_0000),
3041 Err(Error::FieldOverflow(_))
3042 ));
3043 assert_eq!(PiecewiseRate::new(0x3F_FFFF), Ok(PiecewiseRate::MAX));
3044
3045 let mut ext = AdaptationFieldExtension::new();
3046 ext.ltw = Some(Ltw {
3047 ltw_valid_flag: true,
3048 ltw_offset: LtwOffset::MAX,
3049 });
3050 ext.piecewise_rate = Some(PiecewiseRate::MAX);
3051 let mut buf = vec![0u8; ext.serialized_len()];
3052 ext.serialize_into(&mut buf).unwrap();
3053 assert_eq!(buf[1..3], [0xDF, 0xFF]);
3054 assert_eq!(buf[3..6], [0xFF, 0xFF, 0xFF]);
3055 assert_eq!(AdaptationFieldExtension::parse(&buf).unwrap(), ext);
3056 }
3057
3058 #[test]
3061 fn adaptation_field_serialize_rejects_over_range_reserved_bits() {
3062 let mut af = AdaptationField::new();
3063 af.pcr = Some(Pcr::from_parts(0, 0).expect("in range"));
3064 let mut ok = [0u8; 7];
3065 af.serialize_into(&mut ok).unwrap();
3066 assert_eq!(&ok[1..6], &[0x00, 0x00, 0x00, 0x00, 0x7E]);
3067
3068 af.pcr_reserved = PCR_RESERVED_VALUE + 1;
3069 let mut buf = [0u8; 7];
3070 assert!(matches!(
3071 af.serialize_into(&mut buf),
3072 Err(Error::FieldOverflow(_))
3073 ));
3074 }
3075
3076 #[test]
3078 fn adaptation_field_transport_private_data_round_trip() {
3079 let tpd = [0xDE, 0xAD, 0xBE, 0xEF];
3080 let af = AdaptationField {
3081 discontinuity_indicator: false,
3082 random_access_indicator: false,
3083 elementary_stream_priority_indicator: false,
3084 pcr: None,
3085 opcr: None,
3086 splice_countdown: None,
3087 transport_private_data: Some(&tpd),
3088 extension: None,
3089 stuffing: &[],
3090 pcr_reserved: PCR_RESERVED_VALUE,
3091 opcr_reserved: PCR_RESERVED_VALUE,
3092 };
3093 let mut buf = vec![0u8; af.serialized_len()];
3094 af.serialize_into(&mut buf).unwrap();
3095 let decoded = AdaptationField::parse(&buf).unwrap();
3096 assert_eq!(decoded.transport_private_data, Some(tpd.as_slice()));
3097 }
3098
3099 #[test]
3102 fn adaptation_field_stuffing_round_trip() {
3103 let af = AdaptationField {
3104 discontinuity_indicator: false,
3105 random_access_indicator: false,
3106 elementary_stream_priority_indicator: false,
3107 pcr: Some(Pcr::from_parts(12_345, 7).expect("in range")),
3108 opcr: None,
3109 splice_countdown: None,
3110 transport_private_data: None,
3111 extension: None,
3112 stuffing: &[0xFF; 20],
3113 pcr_reserved: PCR_RESERVED_VALUE,
3114 opcr_reserved: PCR_RESERVED_VALUE,
3115 };
3116 assert_eq!(af.serialized_len(), 27);
3118 let mut buf = vec![0u8; af.serialized_len()];
3119 af.serialize_into(&mut buf).unwrap();
3120 assert!(buf[7..27].iter().all(|&b| b == 0xFF));
3122 let decoded = AdaptationField::parse(&buf).unwrap();
3123 assert_eq!(decoded.stuffing.len(), 20);
3124 assert_eq!(decoded, af);
3125 let pure = AdaptationField {
3127 discontinuity_indicator: false,
3128 random_access_indicator: false,
3129 elementary_stream_priority_indicator: false,
3130 pcr: None,
3131 opcr: None,
3132 splice_countdown: None,
3133 transport_private_data: None,
3134 extension: None,
3135 stuffing: &[0xFF; 5],
3136 pcr_reserved: PCR_RESERVED_VALUE,
3137 opcr_reserved: PCR_RESERVED_VALUE,
3138 };
3139 let mut pbuf = vec![0u8; pure.serialized_len()];
3140 pure.serialize_into(&mut pbuf).unwrap();
3141 assert_eq!(pbuf, vec![0x00, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF]);
3142 assert_eq!(AdaptationField::parse(&pbuf).unwrap(), pure);
3143 }
3144
3145 #[test]
3147 fn adaptation_field_all_fields_round_trip() {
3148 let tpd = [0x01u8, 0x02, 0x03];
3149 let af = AdaptationField {
3150 discontinuity_indicator: true,
3151 random_access_indicator: false,
3152 elementary_stream_priority_indicator: false,
3153 pcr: Some(Pcr::from_parts(90_000, 50).expect("in range")),
3154 opcr: None,
3155 splice_countdown: Some(10),
3156 transport_private_data: Some(&tpd),
3157 extension: Some(AdaptationFieldExtension {
3158 ltw: Some(Ltw {
3159 ltw_valid_flag: false,
3160 ltw_offset: LtwOffset::new(500).expect("in range"),
3161 }),
3162 piecewise_rate: Some(PiecewiseRate::new(12345).expect("in range")),
3163 seamless_splice: None,
3164 ..AdaptationFieldExtension::new()
3165 }),
3166 stuffing: &[],
3167 pcr_reserved: PCR_RESERVED_VALUE,
3168 opcr_reserved: PCR_RESERVED_VALUE,
3169 };
3170 let len = af.serialized_len();
3171 let mut buf = vec![0u8; len];
3172 af.serialize_into(&mut buf).unwrap();
3173 let decoded = AdaptationField::parse(&buf).unwrap();
3174 assert_eq!(decoded.pcr, af.pcr);
3175 assert_eq!(decoded.splice_countdown, af.splice_countdown);
3176 assert_eq!(decoded.transport_private_data, af.transport_private_data);
3177 assert_eq!(decoded.extension, af.extension);
3178 assert!(decoded.discontinuity_indicator);
3179 }
3180
3181 #[test]
3184 fn adaptation_field_serialize_from_real_packet_bytes() {
3185 let mut raw = [0xAAu8; TS_PACKET_SIZE];
3187 raw[0] = TS_SYNC_BYTE;
3188 raw[1] = 0x01;
3189 raw[2] = 0x00;
3190 raw[3] = ADAPTATION_FLAG | PAYLOAD_FLAG;
3191 raw[4] = 7;
3192 raw[5] = AF_DISCONTINUITY | AF_PCR_FLAG;
3193 raw[6..12].copy_from_slice(&[0x00, 0x00, 0x13, 0x88, 0x7E, 0x00]);
3194
3195 let pkt = TsPacket::parse(&raw).unwrap();
3196 let af = pkt.adaptation_field().unwrap().unwrap();
3197
3198 let mut ser = vec![0u8; af.serialized_len()];
3200 af.serialize_into(&mut ser).unwrap();
3201 let decoded = AdaptationField::parse(&ser).unwrap();
3202 assert_eq!(
3203 decoded.pcr,
3204 Some(Pcr::from_parts(10_000, 0).expect("in range"))
3205 );
3206 assert!(decoded.discontinuity_indicator);
3207 }
3208}