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, thiserror::Error)]
297#[error("continuity_counter {value} exceeds the 4-bit range 0..=15")]
298#[non_exhaustive]
299pub struct ContinuityCounterOutOfRange {
300 pub value: u8,
302}
303
304#[derive(Clone, Debug, PartialEq, Eq)]
306#[cfg_attr(feature = "serde", derive(serde::Serialize))]
307pub struct TsHeader {
308 pub tei: bool,
311 pub pusi: bool,
314 pub pid: Pid,
316 pub scrambling: ScramblingControl,
319 #[cfg_attr(feature = "serde", serde(rename = "adaptation"))]
325 pub adaptation_field_control: AdaptationFieldControl,
326 pub continuity_counter: ContinuityCounter,
328}
329
330#[derive(Clone, Debug)]
336#[cfg_attr(feature = "serde", derive(serde::Serialize))]
337pub struct TsPacket<'a> {
338 pub header: TsHeader,
340 pub payload: Option<&'a [u8]>,
344 #[cfg_attr(feature = "serde", serde(skip))]
347 adaptation: Option<&'a [u8]>,
348 #[cfg_attr(feature = "serde", serde(skip))]
350 pub raw: &'a [u8; TS_PACKET_SIZE],
351}
352
353impl TsHeader {
354 pub fn parse(raw4: &[u8]) -> Result<Self> {
356 need_in(raw4, 4, "TsHeader")?;
357 let b1 = raw4[1];
358 let b2 = raw4[2];
359 let b3 = raw4[3];
360
361 let tei = (b1 & TEI_MASK) != 0;
362 let pusi = (b1 & PUSI_MASK) != 0;
363 let pid = Pid::from_wire_masked((u16::from(b1 & PID_MASK_HI) << 8) | u16::from(b2));
364 let has_adaptation = (b3 & ADAPTATION_FLAG) != 0;
365 let has_payload = (b3 & PAYLOAD_FLAG) != 0;
366
367 Ok(Self {
368 tei,
369 pusi,
370 pid,
371 scrambling: ScramblingControl::from_bits(b3 >> SCRAMBLING_SHIFT),
372 adaptation_field_control: AdaptationFieldControl::from_flags(
373 has_adaptation,
374 has_payload,
375 ),
376 continuity_counter: ContinuityCounter::from_wire_masked(b3),
377 })
378 }
379
380 pub const fn serialized_len() -> usize {
382 4
383 }
384
385 #[must_use]
387 pub fn to_bytes(&self) -> [u8; 4] {
388 let mut b = [0u8; 4];
389 b[0] = TS_SYNC_BYTE;
390 if self.tei {
391 b[1] |= TEI_MASK;
392 }
393 if self.pusi {
394 b[1] |= PUSI_MASK;
395 }
396 let pid = self.pid.value();
397 b[1] |= ((pid >> 8) as u8) & PID_MASK_HI;
398 b[2] = pid.to_be_bytes()[1];
399 b[3] = (self.scrambling.to_bits() << SCRAMBLING_SHIFT)
400 | ((self.adaptation_field_control.to_bits() & ADAPTATION_CONTROL_MASK)
401 << ADAPTATION_SHIFT)
402 | self.continuity_counter.value();
403 b
404 }
405
406 pub fn serialize_into(&self, buf: &mut [u8]) -> Result<usize> {
408 need_out(buf, 4)?;
409 buf[..4].copy_from_slice(&self.to_bytes());
410 Ok(4)
411 }
412
413 pub fn has_adaptation(&self) -> bool {
416 self.adaptation_field_control.to_flags().0
417 }
418
419 pub fn has_payload(&self) -> bool {
422 self.adaptation_field_control.to_flags().1
423 }
424}
425
426impl<'a> broadcast_common::Parse<'a> for TsHeader {
427 type Error = Error;
428
429 fn parse(bytes: &'a [u8]) -> Result<Self> {
430 TsHeader::parse(bytes)
431 }
432}
433
434impl broadcast_common::Serialize for TsHeader {
435 type Error = Error;
436
437 fn serialized_len(&self) -> usize {
438 TsHeader::serialized_len()
439 }
440
441 fn serialize_into(&self, buf: &mut [u8]) -> Result<usize> {
442 TsHeader::serialize_into(self, buf)
443 }
444}
445
446pub(crate) fn adaptation_field_body_range(
456 pkt: &[u8],
457 has_adaptation: bool,
458) -> Option<core::ops::Range<usize>> {
459 if !has_adaptation || pkt.len() <= AF_LEN_BYTE {
460 return None;
461 }
462 let af_len = pkt[AF_LEN_BYTE] as usize;
463 if af_len == 0 {
464 return None;
465 }
466 let start = AF_FLAGS_BYTE;
467 let end = start + af_len;
468 if end > pkt.len() {
469 return None;
470 }
471 Some(start..end)
472}
473
474fn adaptation_field_skip(pkt: &[u8], has_adaptation: bool) -> usize {
480 if !has_adaptation || pkt.len() <= AF_LEN_BYTE {
481 return 0;
482 }
483 1 + pkt[AF_LEN_BYTE] as usize
484}
485
486pub(crate) enum ClockReferenceSlot {
491 Field(core::ops::Range<usize>),
493 NoAdaptationField,
495 TooShort {
497 need: usize,
499 have: usize,
501 },
502 FlagClear,
504 Truncated {
506 need: usize,
508 have: usize,
510 },
511}
512
513pub(crate) fn clock_reference_slot(pkt: &[u8], flag: u8) -> ClockReferenceSlot {
517 if pkt.len() <= AF_LEN_BYTE || pkt[3] & ADAPTATION_FLAG == 0 {
518 return ClockReferenceSlot::NoAdaptationField;
519 }
520 let af_len = pkt[AF_LEN_BYTE] as usize;
521 if af_len == 0 {
522 return ClockReferenceSlot::NoAdaptationField;
523 }
524 let preceding = if flag == AF_OPCR_FLAG {
527 PCR_FIELD_LEN
528 } else {
529 0
530 };
531 let need = 1 + preceding + PCR_FIELD_LEN;
532 if af_len < need {
533 return ClockReferenceSlot::TooShort { need, have: af_len };
534 }
535 if pkt.len() <= AF_FLAGS_BYTE || pkt[AF_FLAGS_BYTE] & flag == 0 {
536 return ClockReferenceSlot::FlagClear;
537 }
538 let start = CLOCK_REFERENCE_START + preceding;
539 let end = start + PCR_FIELD_LEN;
540 if end > pkt.len() {
541 return ClockReferenceSlot::Truncated {
542 need: end,
543 have: pkt.len(),
544 };
545 }
546 ClockReferenceSlot::Field(start..end)
547}
548
549impl<'a> TsPacket<'a> {
550 pub fn parse(buf: &'a [u8]) -> Result<Self> {
556 need_in(buf, TS_PACKET_SIZE, "TsPacket")?;
557 if buf[0] != TS_SYNC_BYTE {
558 return Err(Error::InvalidSync(broadcast_common::error::InvalidSync {
559 what: "TS sync byte",
560 expected: u32::from(TS_SYNC_BYTE),
561 found: u32::from(buf[0]),
562 }));
563 }
564
565 let raw: &[u8; TS_PACKET_SIZE] = buf[..TS_PACKET_SIZE].try_into().map_err(|_| {
566 Error::BufferTooShort(broadcast_common::error::BufferTooShort {
567 need: TS_PACKET_SIZE,
568 have: buf.len(),
569 what: "TsPacket::parse (array conversion)",
570 })
571 })?;
572
573 let header = TsHeader::parse(&raw[..4])?;
574
575 let mut cursor = 4usize;
576 let mut payload = None;
577
578 let adaptation = adaptation_field_body_range(raw, header.has_adaptation()).map(|r| &raw[r]);
591 cursor += adaptation_field_skip(raw, header.has_adaptation());
596
597 if header.has_payload() && cursor < TS_PACKET_SIZE {
598 payload = Some(&raw[cursor..]);
599 }
600
601 Ok(TsPacket {
602 header,
603 payload,
604 adaptation,
605 raw,
606 })
607 }
608
609 pub fn adaptation_field(&self) -> Option<crate::Result<AdaptationField<'a>>> {
615 self.adaptation.map(AdaptationField::parse)
616 }
617}
618
619pub(crate) const AF_DISCONTINUITY: u8 = 0x80;
621pub(crate) const AF_RANDOM_ACCESS: u8 = 0x40;
622pub(crate) const AF_ES_PRIORITY: u8 = 0x20;
623pub const AF_PCR_FLAG: u8 = 0x10;
625pub(crate) const AF_OPCR_FLAG: u8 = 0x08;
626pub(crate) const AF_SPLICING_FLAG: u8 = 0x04;
627pub(crate) const AF_TRANSPORT_PRIVATE_DATA_FLAG: u8 = 0x02;
628pub(crate) const AF_EXTENSION_FLAG: u8 = 0x01;
629pub(crate) const PCR_RESERVED_BITS: u8 = 0x7E;
632const PCR_RESERVED_BITS_COUNT: u32 = 6;
634pub(crate) const PCR_RESERVED_SHIFT: u32 = 1;
636pub(crate) const PCR_RESERVED_BYTE_OFFSET: usize = 4;
638const PCR_RESERVED_VALUE: u8 = 0x3F;
640pub(crate) const PCR_FIELD_LEN: usize = 6;
642
643pub(crate) const AF_LEN_BYTE: usize = 4;
646pub(crate) const AF_FLAGS_BYTE: usize = 5;
649pub(crate) const CLOCK_REFERENCE_START: usize = AF_FLAGS_BYTE + 1;
652
653#[derive(Clone, Copy, Debug, PartialEq, Eq)]
666#[cfg_attr(feature = "serde", derive(serde::Serialize))]
667pub struct Pcr(broadcast_common::clock33::Clock27);
668
669impl Pcr {
670 pub fn from_parts(base: u64, extension: u16) -> Result<Self> {
675 Ok(Self(broadcast_common::clock33::Clock27::from_parts(
676 base, extension,
677 )?))
678 }
679
680 pub fn from_27mhz(ticks: u64) -> Result<Self> {
685 Ok(Self(broadcast_common::clock33::Clock27::from_27mhz(ticks)?))
686 }
687
688 pub fn to_clock27(self) -> Result<broadcast_common::clock33::Clock27> {
694 Ok(self.0.to_clock27()?)
695 }
696
697 #[must_use]
700 pub const fn clock(self) -> broadcast_common::clock33::Clock27 {
701 self.0
702 }
703
704 #[must_use]
706 pub const fn base(self) -> u64 {
707 self.0.base.ticks()
708 }
709
710 #[must_use]
713 pub const fn extension(self) -> u16 {
714 self.0.ext
715 }
716
717 #[must_use]
723 pub fn as_27mhz(self) -> u64 {
724 self.0.ticks()
725 }
726
727 #[must_use]
737 pub fn to_field_bytes(self) -> [u8; PCR_FIELD_LEN] {
738 let b = self.0.base.ticks();
739 let e = u64::from(self.0.ext);
740 [
741 ((b >> 25) & 0xFF) as u8,
742 ((b >> 17) & 0xFF) as u8,
743 ((b >> 9) & 0xFF) as u8,
744 ((b >> 1) & 0xFF) as u8,
745 (((b & 0x01) as u8) << 7) | PCR_RESERVED_BITS | ((e >> 8) as u8 & 0x01),
747 (e & 0xFF) as u8,
748 ]
749 }
750
751 pub fn to_field_bytes_with_reserved(self, reserved: u8) -> Result<[u8; PCR_FIELD_LEN]> {
758 let mut field = self.to_field_bytes();
759 set_pcr_reserved(&mut field, reserved)?;
760 Ok(field)
761 }
762
763 pub(crate) fn parse(buf: &[u8], from: usize) -> Result<Self> {
770 let end = from + PCR_FIELD_LEN;
771 let b: &[u8; PCR_FIELD_LEN] =
772 buf.get(from..end)
773 .and_then(|s| s.try_into().ok())
774 .ok_or(Error::BufferTooShort(
775 broadcast_common::error::BufferTooShort {
776 need: end,
777 have: buf.len(),
778 what: "adaptation_field PCR",
779 },
780 ))?;
781 let base = ((b[0] as u64) << 25)
782 | ((b[1] as u64) << 17)
783 | ((b[2] as u64) << 9)
784 | ((b[3] as u64) << 1)
785 | (u64::from(b[4]) >> 7);
786 let extension = ((b[4] & 0x01) as u16) << 8 | u16::from(b[5]);
787 Ok(Self(broadcast_common::clock33::Clock27::from_wire_parts(
788 base, extension,
789 )))
790 }
791}
792
793#[derive(Clone, Copy, Debug, PartialEq, Eq)]
800#[cfg_attr(feature = "serde", derive(serde::Serialize))]
801pub struct Ltw {
802 pub ltw_valid_flag: bool,
804 pub ltw_offset: LtwOffset,
805}
806
807#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
813#[cfg_attr(feature = "serde", derive(serde::Serialize))]
814#[cfg_attr(feature = "serde", serde(transparent))]
815pub struct LtwOffset(u16);
816
817const LTW_OFFSET_BITS: u32 = 15;
819
820impl LtwOffset {
821 pub const MAX: Self = Self((1 << LTW_OFFSET_BITS) - 1);
823
824 pub const ZERO: Self = Self(0);
826
827 pub fn new(value: u16) -> Result<Self> {
829 let fitted =
830 broadcast_common::len::fit_bits(u64::from(value), LTW_OFFSET_BITS, "ltw_offset")?;
831 Ok(Self(fitted as u16))
832 }
833
834 #[must_use]
839 pub(crate) fn from_wire_masked(high: u8, low: u8) -> Self {
840 Self((u16::from(high & LTW_OFFSET_HI_MASK) << 8) | u16::from(low))
841 }
842
843 #[must_use]
845 pub fn get(self) -> u16 {
846 self.0
847 }
848}
849
850impl From<LtwOffset> for u16 {
851 fn from(value: LtwOffset) -> Self {
852 value.0
853 }
854}
855
856impl core::fmt::Display for LtwOffset {
857 fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
858 write!(f, "{}", self.0)
859 }
860}
861
862#[non_exhaustive]
871#[derive(Clone, Copy, Debug, PartialEq, Eq)]
872#[cfg_attr(feature = "serde", derive(serde::Serialize))]
873pub struct SeamlessSplice {
874 pub splice_type: u8,
876 pub dts_next_au: u64,
878 pub marker_bits: u8,
883}
884
885const SPLICE_TYPE_BITS: u32 = 4;
887const DTS_NEXT_AU_BITS: u32 = 33;
889const SPLICE_MARKER_BITS: u32 = 3;
891
892impl SeamlessSplice {
893 #[must_use]
895 pub const fn new(splice_type: u8, dts_next_au: u64) -> Self {
896 Self {
897 splice_type,
898 dts_next_au,
899 marker_bits: SPLICE_MARKERS_VALUE,
900 }
901 }
902
903 pub const DTS_NEXT_AU_BITS: u32 = DTS_NEXT_AU_BITS;
905
906 #[must_use]
908 pub(crate) fn from_marked_field(field: &[u8; 5]) -> Self {
909 let m = broadcast_common::clock33::unpack_marked(field);
910 Self {
911 splice_type: m.prefix,
912 dts_next_au: m.timestamp,
913 marker_bits: m.markers,
914 }
915 }
916
917 pub fn to_marked_field(&self) -> Result<[u8; 5]> {
920 broadcast_common::len::fit_bits(
921 u64::from(self.splice_type),
922 SPLICE_TYPE_BITS,
923 "seamless_splice.splice_type",
924 )?;
925 broadcast_common::len::fit_bits(
926 self.dts_next_au,
927 DTS_NEXT_AU_BITS,
928 "seamless_splice.DTS_next_AU",
929 )?;
930 broadcast_common::len::fit_bits(
931 u64::from(self.marker_bits),
932 SPLICE_MARKER_BITS,
933 "seamless_splice.marker_bit",
934 )?;
935 Ok(broadcast_common::clock33::pack_marked_with(
936 self.dts_next_au,
937 self.splice_type,
938 self.marker_bits,
939 ))
940 }
941}
942
943const SPLICE_MARKERS_VALUE: u8 = 0x07;
947const AFE_LTW_FLAG: u8 = 0x80;
948const AFE_PIECEWISE_RATE_FLAG: u8 = 0x40;
949const AFE_SEAMLESS_SPLICE_FLAG: u8 = 0x20;
950const LTW_OFFSET_HI_MASK: u8 = 0x7F;
952const PIECEWISE_RATE_HI_MASK: u8 = 0x3F;
954const AFE_AF_DESCRIPTOR_NOT_PRESENT_FLAG: u8 = 0x10;
956const AFE_RESERVED_FLAGS_MASK: u8 = 0x0F;
958const AFE_RESERVED_FLAGS_VALUE: u8 = 0x0F;
960const PIECEWISE_RATE_RESERVED_SHIFT: u32 = 6;
962const PIECEWISE_RATE_RESERVED_VALUE: u8 = 0x03;
964const PIECEWISE_RATE_BITS: u32 = 22;
966
967#[non_exhaustive]
987#[derive(Clone, Copy, Debug, PartialEq, Eq)]
988#[cfg_attr(feature = "serde", derive(serde::Serialize))]
989pub struct AdaptationFieldExtension<'a> {
990 pub ltw: Option<Ltw>,
992 pub piecewise_rate: Option<PiecewiseRate>,
994 pub piecewise_rate_reserved: u8,
997 pub seamless_splice: Option<SeamlessSplice>,
999 pub af_descriptor_not_present_flag: bool,
1003 pub reserved_flags: u8,
1005 pub trailing: &'a [u8],
1009}
1010
1011impl Default for AdaptationFieldExtension<'_> {
1012 fn default() -> Self {
1013 Self::new()
1014 }
1015}
1016
1017#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
1023#[cfg_attr(feature = "serde", derive(serde::Serialize))]
1024#[cfg_attr(feature = "serde", serde(transparent))]
1025pub struct PiecewiseRate(u32);
1026
1027impl PiecewiseRate {
1028 pub const MAX: Self = Self((1 << PIECEWISE_RATE_BITS) - 1);
1030
1031 pub fn new(value: u32) -> Result<Self> {
1033 let fitted = broadcast_common::len::fit_bits(
1034 u64::from(value),
1035 PIECEWISE_RATE_BITS,
1036 "piecewise_rate",
1037 )?;
1038 Ok(Self(fitted as u32))
1039 }
1040
1041 #[must_use]
1046 pub(crate) fn from_wire_masked(high: u8, mid: u8, low: u8) -> Self {
1047 Self(
1048 (u32::from(high & PIECEWISE_RATE_HI_MASK) << 16)
1049 | (u32::from(mid) << 8)
1050 | u32::from(low),
1051 )
1052 }
1053
1054 #[must_use]
1056 pub fn get(self) -> u32 {
1057 self.0
1058 }
1059}
1060
1061impl From<PiecewiseRate> for u32 {
1062 fn from(value: PiecewiseRate) -> Self {
1063 value.0
1064 }
1065}
1066
1067impl core::fmt::Display for PiecewiseRate {
1068 fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
1069 write!(f, "{}", self.0)
1070 }
1071}
1072
1073impl<'a> AdaptationFieldExtension<'a> {
1074 #[must_use]
1077 pub const fn new() -> Self {
1078 Self {
1079 ltw: None,
1080 piecewise_rate: None,
1081 piecewise_rate_reserved: PIECEWISE_RATE_RESERVED_VALUE,
1082 seamless_splice: None,
1083 af_descriptor_not_present_flag: true,
1084 reserved_flags: AFE_RESERVED_FLAGS_VALUE,
1085 trailing: &[],
1086 }
1087 }
1088
1089 fn parse(data: &'a [u8]) -> Result<Self> {
1092 need_in(data, 1, "adaptation_field_extension_length")?;
1093 let ext_len = data[0] as usize;
1094 if data.len() < 1 + ext_len || ext_len < 1 {
1096 return Err(Error::BufferTooShort(
1097 broadcast_common::error::BufferTooShort {
1098 need: 2.max(1 + ext_len),
1099 have: data.len(),
1100 what: "adaptation_field_extension body",
1101 },
1102 ));
1103 }
1104 let ext = &data[1..1 + ext_len]; let flags = ext[0];
1106 let mut cursor = 1usize;
1107
1108 let ltw = if flags & AFE_LTW_FLAG != 0 {
1109 need_in(ext, cursor + 2, "ltw_offset")?;
1110 let w0 = ext[cursor];
1111 let w1 = ext[cursor + 1];
1112 cursor += 2;
1113 Some(Ltw {
1114 ltw_valid_flag: (w0 & AFE_LTW_FLAG) != 0,
1115 ltw_offset: LtwOffset::from_wire_masked(w0, w1),
1116 })
1117 } else {
1118 None
1119 };
1120
1121 let mut piecewise_rate_reserved = PIECEWISE_RATE_RESERVED_VALUE;
1122 let piecewise_rate = if flags & AFE_PIECEWISE_RATE_FLAG != 0 {
1123 need_in(ext, cursor + 3, "piecewise_rate")?;
1124 piecewise_rate_reserved = ext[cursor] >> PIECEWISE_RATE_RESERVED_SHIFT;
1125 let r = PiecewiseRate::from_wire_masked(ext[cursor], ext[cursor + 1], ext[cursor + 2]);
1126 cursor += 3;
1127 Some(r)
1128 } else {
1129 None
1130 };
1131
1132 let seamless_splice = if flags & AFE_SEAMLESS_SPLICE_FLAG != 0 {
1134 need_in(ext, cursor + 5, "seamless_splice DTS_next_AU")?;
1135 let field = [
1136 ext[cursor],
1137 ext[cursor + 1],
1138 ext[cursor + 2],
1139 ext[cursor + 3],
1140 ext[cursor + 4],
1141 ];
1142 let splice = SeamlessSplice::from_marked_field(&field);
1145 cursor += 5;
1146 Some(splice)
1147 } else {
1148 None
1149 };
1150
1151 Ok(AdaptationFieldExtension {
1152 ltw,
1153 piecewise_rate,
1154 piecewise_rate_reserved,
1155 seamless_splice,
1156 af_descriptor_not_present_flag: flags & AFE_AF_DESCRIPTOR_NOT_PRESENT_FLAG != 0,
1157 reserved_flags: flags & AFE_RESERVED_FLAGS_MASK,
1158 trailing: &ext[cursor..],
1159 })
1160 }
1161
1162 #[must_use]
1165 pub fn serialized_len(&self) -> usize {
1166 let body = 1 + self.ltw.map_or(0, |_| 2)
1168 + self.piecewise_rate.map_or(0, |_| 3)
1169 + self.seamless_splice.map_or(0, |_| 5)
1170 + self.trailing.len();
1171 1 + body }
1173
1174 pub fn serialize_into(&self, buf: &mut [u8]) -> Result<usize> {
1176 let need = self.serialized_len();
1177 need_out(buf, need)?;
1178 buf[0] = broadcast_common::len::fit_u8(need - 1, "adaptation_field_extension_length")?;
1179
1180 let mut flags = broadcast_common::len::fit_mask(
1181 self.reserved_flags,
1182 AFE_RESERVED_FLAGS_MASK,
1183 "adaptation_field_extension.reserved",
1184 )?;
1185 if self.ltw.is_some() {
1186 flags |= AFE_LTW_FLAG;
1187 }
1188 if self.piecewise_rate.is_some() {
1189 flags |= AFE_PIECEWISE_RATE_FLAG;
1190 }
1191 if self.seamless_splice.is_some() {
1192 flags |= AFE_SEAMLESS_SPLICE_FLAG;
1193 }
1194 if self.af_descriptor_not_present_flag {
1195 flags |= AFE_AF_DESCRIPTOR_NOT_PRESENT_FLAG;
1196 }
1197 buf[1] = flags;
1198 let mut cursor = 2usize;
1199
1200 if let Some(ltw) = self.ltw {
1201 let ltw_valid = if ltw.ltw_valid_flag { AFE_LTW_FLAG } else { 0 };
1202 let offset = broadcast_common::len::fit_bits(
1203 u64::from(ltw.ltw_offset.get()),
1204 LTW_OFFSET_BITS,
1205 "ltw_offset",
1206 )?;
1207 buf[cursor] = ltw_valid | ((offset >> 8) as u8 & LTW_OFFSET_HI_MASK);
1208 buf[cursor + 1] = (offset & 0xFF) as u8;
1209 cursor += 2;
1210 }
1211 if let Some(rate) = self.piecewise_rate {
1212 let rate = broadcast_common::len::fit_bits(
1213 u64::from(rate.get()),
1214 PIECEWISE_RATE_BITS,
1215 "piecewise_rate",
1216 )?;
1217 buf[cursor] = (broadcast_common::len::fit_mask(
1219 self.piecewise_rate_reserved,
1220 PIECEWISE_RATE_RESERVED_VALUE,
1221 "piecewise_rate.reserved",
1222 )? << PIECEWISE_RATE_RESERVED_SHIFT)
1223 | ((rate >> 16) as u8 & PIECEWISE_RATE_HI_MASK);
1224 buf[cursor + 1] = (rate >> 8) as u8;
1225 buf[cursor + 2] = rate as u8;
1226 cursor += 3;
1227 }
1228 if let Some(ss) = self.seamless_splice {
1229 buf[cursor..cursor + 5].copy_from_slice(&ss.to_marked_field()?);
1231 cursor += 5;
1232 }
1233 buf[cursor..cursor + self.trailing.len()].copy_from_slice(self.trailing);
1234 cursor += self.trailing.len();
1235 Ok(cursor)
1236 }
1237}
1238
1239#[non_exhaustive]
1248#[derive(Clone, Debug, PartialEq, Eq)]
1249#[cfg_attr(feature = "serde", derive(serde::Serialize))]
1250pub struct AdaptationField<'a> {
1251 pub discontinuity_indicator: bool,
1253 pub random_access_indicator: bool,
1255 pub elementary_stream_priority_indicator: bool,
1257 pub pcr: Option<Pcr>,
1259 pub opcr: Option<Pcr>,
1261 pub splice_countdown: Option<i8>,
1263 pub transport_private_data: Option<&'a [u8]>,
1268 pub extension: Option<AdaptationFieldExtension<'a>>,
1270 pub pcr_reserved: u8,
1276 pub opcr_reserved: u8,
1278 pub stuffing: &'a [u8],
1288}
1289
1290impl Default for AdaptationField<'_> {
1291 fn default() -> Self {
1292 Self::new()
1293 }
1294}
1295
1296pub(crate) fn set_pcr_reserved(field: &mut [u8], reserved: u8) -> Result<()> {
1298 let reserved = broadcast_common::len::fit_bits(
1299 u64::from(reserved),
1300 PCR_RESERVED_BITS_COUNT,
1301 "pcr_reserved",
1302 )?;
1303 field[4] = (field[4] & !PCR_RESERVED_BITS)
1304 | (((reserved as u8) << PCR_RESERVED_SHIFT) & PCR_RESERVED_BITS);
1305 Ok(())
1306}
1307
1308impl<'a> AdaptationField<'a> {
1309 #[must_use]
1313 pub const fn new() -> Self {
1314 Self {
1315 discontinuity_indicator: false,
1316 random_access_indicator: false,
1317 elementary_stream_priority_indicator: false,
1318 pcr: None,
1319 opcr: None,
1320 splice_countdown: None,
1321 transport_private_data: None,
1322 extension: None,
1323 pcr_reserved: PCR_RESERVED_VALUE,
1324 opcr_reserved: PCR_RESERVED_VALUE,
1325 stuffing: &[],
1326 }
1327 }
1328
1329 pub(crate) fn parse(af: &'a [u8]) -> Result<Self> {
1336 let flags = *af.first().ok_or(Error::BufferTooShort(
1337 broadcast_common::error::BufferTooShort {
1338 need: 1,
1339 have: 0,
1340 what: "adaptation_field flags",
1341 },
1342 ))?;
1343 let mut cursor = 1usize;
1344
1345 let mut pcr_reserved = PCR_RESERVED_VALUE;
1346 let mut opcr_reserved = PCR_RESERVED_VALUE;
1347 let pcr = if flags & AF_PCR_FLAG != 0 {
1348 let p = Pcr::parse(af, cursor)?;
1349 pcr_reserved = (af[cursor + 4] & PCR_RESERVED_BITS) >> PCR_RESERVED_SHIFT;
1350 cursor += PCR_FIELD_LEN;
1351 Some(p)
1352 } else {
1353 None
1354 };
1355 let opcr = if flags & AF_OPCR_FLAG != 0 {
1356 let p = Pcr::parse(af, cursor)?;
1357 opcr_reserved = (af[cursor + 4] & PCR_RESERVED_BITS) >> PCR_RESERVED_SHIFT;
1358 cursor += PCR_FIELD_LEN;
1359 Some(p)
1360 } else {
1361 None
1362 };
1363 let splice_countdown = if flags & AF_SPLICING_FLAG != 0 {
1364 let b = *af.get(cursor).ok_or(Error::BufferTooShort(
1365 broadcast_common::error::BufferTooShort {
1366 need: cursor + 1,
1367 have: af.len(),
1368 what: "adaptation_field splice_countdown",
1369 },
1370 ))?;
1371 cursor += 1;
1372 Some(b as i8)
1373 } else {
1374 None
1375 };
1376
1377 let transport_private_data = if flags & AF_TRANSPORT_PRIVATE_DATA_FLAG != 0 {
1380 let tpd_len = *af.get(cursor).ok_or(Error::BufferTooShort(
1381 broadcast_common::error::BufferTooShort {
1382 need: cursor + 1,
1383 have: af.len(),
1384 what: "transport_private_data_length",
1385 },
1386 ))? as usize;
1387 cursor += 1;
1388 let end = cursor + tpd_len;
1389 let slice = af.get(cursor..end).ok_or(Error::BufferTooShort(
1390 broadcast_common::error::BufferTooShort {
1391 need: end,
1392 have: af.len(),
1393 what: "transport_private_data",
1394 },
1395 ))?;
1396 cursor = end;
1397 Some(slice)
1398 } else {
1399 None
1400 };
1401
1402 let extension = if flags & AF_EXTENSION_FLAG != 0 {
1404 let ext_data = af.get(cursor..).ok_or(Error::BufferTooShort(
1405 broadcast_common::error::BufferTooShort {
1406 need: cursor + 1,
1407 have: af.len(),
1408 what: "adaptation_field_extension",
1409 },
1410 ))?;
1411 let ext = AdaptationFieldExtension::parse(ext_data)?;
1412 if !ext_data.is_empty() {
1414 let _ext_len = ext_data[0] as usize;
1415 cursor += 1 + _ext_len;
1416 }
1417 Some(ext)
1418 } else {
1419 None
1420 };
1421
1422 let stuffing = af.get(cursor..).unwrap_or(&[]);
1426
1427 Ok(AdaptationField {
1428 discontinuity_indicator: flags & AF_DISCONTINUITY != 0,
1429 random_access_indicator: flags & AF_RANDOM_ACCESS != 0,
1430 elementary_stream_priority_indicator: flags & AF_ES_PRIORITY != 0,
1431 pcr,
1432 opcr,
1433 splice_countdown,
1434 transport_private_data,
1435 extension,
1436 pcr_reserved,
1437 opcr_reserved,
1438 stuffing,
1439 })
1440 }
1441
1442 #[must_use]
1448 pub fn serialized_len(&self) -> usize {
1449 let mut n = 1usize; if self.pcr.is_some() {
1451 n += PCR_FIELD_LEN;
1452 }
1453 if self.opcr.is_some() {
1454 n += PCR_FIELD_LEN;
1455 }
1456 if self.splice_countdown.is_some() {
1457 n += 1;
1458 }
1459 if let Some(tpd) = self.transport_private_data {
1460 n += 1 + tpd.len(); }
1462 if let Some(ref ext) = self.extension {
1463 n += ext.serialized_len();
1464 }
1465 n += self.stuffing.len();
1466 n
1467 }
1468
1469 pub fn serialize_into(&self, buf: &mut [u8]) -> Result<usize> {
1480 let need = self.serialized_len();
1481 need_out(buf, need)?;
1482
1483 let mut flags = 0u8;
1485 if self.discontinuity_indicator {
1486 flags |= AF_DISCONTINUITY;
1487 }
1488 if self.random_access_indicator {
1489 flags |= AF_RANDOM_ACCESS;
1490 }
1491 if self.elementary_stream_priority_indicator {
1492 flags |= AF_ES_PRIORITY;
1493 }
1494 if self.pcr.is_some() {
1495 flags |= AF_PCR_FLAG;
1496 }
1497 if self.opcr.is_some() {
1498 flags |= AF_OPCR_FLAG;
1499 }
1500 if self.splice_countdown.is_some() {
1501 flags |= AF_SPLICING_FLAG;
1502 }
1503 if self.transport_private_data.is_some() {
1504 flags |= AF_TRANSPORT_PRIVATE_DATA_FLAG;
1505 }
1506 if self.extension.is_some() {
1507 flags |= AF_EXTENSION_FLAG;
1508 }
1509 buf[0] = flags;
1510
1511 let mut cursor = 1usize;
1512 if let Some(pcr) = self.pcr {
1513 buf[cursor..cursor + PCR_FIELD_LEN].copy_from_slice(&pcr.to_field_bytes());
1514 set_pcr_reserved(&mut buf[cursor..cursor + PCR_FIELD_LEN], self.pcr_reserved)?;
1515 cursor += PCR_FIELD_LEN;
1516 }
1517 if let Some(opcr) = self.opcr {
1518 buf[cursor..cursor + PCR_FIELD_LEN].copy_from_slice(&opcr.to_field_bytes());
1519 set_pcr_reserved(&mut buf[cursor..cursor + PCR_FIELD_LEN], self.opcr_reserved)?;
1520 cursor += PCR_FIELD_LEN;
1521 }
1522 if let Some(sc) = self.splice_countdown {
1523 buf[cursor] = sc as u8;
1524 cursor += 1;
1525 }
1526 if let Some(tpd) = self.transport_private_data {
1527 buf[cursor] = broadcast_common::len::fit_u8(
1528 tpd.len(),
1529 "adaptation_field.transport_private_data_length",
1530 )?;
1531 cursor += 1;
1532 buf[cursor..cursor + tpd.len()].copy_from_slice(tpd);
1533 cursor += tpd.len();
1534 }
1535 if let Some(ref ext) = self.extension {
1536 let written = ext.serialize_into(&mut buf[cursor..])?;
1537 cursor += written;
1538 }
1539
1540 buf[cursor..cursor + self.stuffing.len()].copy_from_slice(self.stuffing);
1543 cursor += self.stuffing.len();
1544
1545 Ok(cursor)
1546 }
1547}
1548
1549#[derive(Default)]
1554pub struct SectionReassembler {
1555 buf: bytes::BytesMut,
1556 ready: alloc::collections::VecDeque<bytes::Bytes>,
1557 last_continuity_counter: Option<ContinuityCounter>,
1558}
1559
1560impl SectionReassembler {
1561 pub fn feed(&mut self, payload: &[u8], pusi: bool) {
1569 self.last_continuity_counter = None;
1570 self.feed_payload(payload, pusi);
1571 }
1572
1573 pub fn feed_with_continuity(
1587 &mut self,
1588 payload: &[u8],
1589 pusi: bool,
1590 continuity_counter: ContinuityCounter,
1591 discontinuity: bool,
1592 ) {
1593 let duplicate = !discontinuity && self.last_continuity_counter == Some(continuity_counter);
1594 self.last_continuity_counter = Some(continuity_counter);
1595 if duplicate && !pusi {
1596 return;
1597 }
1598 self.feed_payload(payload, pusi);
1599 }
1600
1601 fn feed_payload(&mut self, payload: &[u8], pusi: bool) {
1602 if pusi {
1603 if payload.is_empty() {
1606 self.buf.clear();
1607 return;
1608 }
1609 let pointer = payload[0] as usize;
1610
1611 if !self.buf.is_empty() && pointer > 0 {
1619 let avail = payload.len() - 1;
1620 let tail_len = pointer.min(avail);
1621 if self.buf.len() + tail_len > MAX_SECTION_SIZE {
1622 self.buf.clear();
1623 } else {
1624 self.buf.extend_from_slice(&payload[1..1 + tail_len]);
1625 self.drain_complete_sections();
1626 }
1627 }
1628
1629 self.buf.clear();
1632
1633 let start = 1 + pointer;
1634 if start >= payload.len() {
1635 return;
1637 }
1638 let new_data = &payload[start..];
1639 if new_data.len() > MAX_SECTION_SIZE {
1640 return;
1641 }
1642 self.buf.extend_from_slice(new_data);
1643 } else {
1644 if self.buf.is_empty() {
1645 return;
1646 }
1647 let take = if let Some(exp) = section_total_len(&self.buf) {
1657 exp.saturating_sub(self.buf.len()).min(payload.len())
1658 } else {
1659 payload.len().min(MAX_SECTION_SIZE - self.buf.len())
1663 };
1664 self.buf.extend_from_slice(&payload[..take]);
1665 }
1666
1667 self.drain_complete_sections();
1668 }
1669
1670 fn drain_complete_sections(&mut self) {
1681 loop {
1682 if self.buf.len() < SECTION_HEADER_LEN {
1683 break;
1686 }
1687 if self.buf[0] == STUFFING_BYTE {
1688 self.buf.clear();
1690 break;
1691 }
1692 let Some(exp) = section_total_len(&self.buf) else {
1695 break;
1696 };
1697 if self.buf.len() >= exp {
1698 let section = self.buf.split_to(exp).freeze();
1699 self.ready.push_back(section);
1700 } else {
1701 break;
1703 }
1704 }
1705 }
1706
1707 pub fn pop_section(&mut self) -> Option<bytes::Bytes> {
1709 self.ready.pop_front()
1710 }
1711
1712 pub fn len(&self) -> usize {
1714 self.buf.len()
1715 }
1716
1717 pub fn is_empty(&self) -> bool {
1719 self.buf.is_empty()
1720 }
1721}
1722
1723pub fn iter_packets(buf: &[u8]) -> impl Iterator<Item = TsPacket<'_>> {
1741 buf.chunks_exact(TS_PACKET_SIZE)
1742 .filter_map(|chunk| TsPacket::parse(chunk).ok())
1743}
1744
1745pub fn extract_ts_payload(pkt: &[u8]) -> Option<&[u8]> {
1755 if pkt.len() < 4 {
1756 return None;
1757 }
1758 let header = TsHeader::parse(&pkt[..4]).ok()?;
1759 if !header.has_payload() {
1760 return None;
1761 }
1762 let cursor = 4 + adaptation_field_skip(pkt, header.has_adaptation());
1763 if cursor < pkt.len() {
1764 Some(&pkt[cursor..])
1765 } else {
1766 None
1767 }
1768}
1769
1770#[cfg(test)]
1771mod tests {
1772 use super::*;
1773
1774 fn cc(v: u8) -> ContinuityCounter {
1775 ContinuityCounter::try_new(v).expect("4-bit counter")
1776 }
1777 use alloc::string::ToString;
1778 use alloc::vec;
1779 use alloc::vec::Vec;
1780
1781 fn make_packet(b1: u8, b2: u8, b3: u8, payload_data: &[u8]) -> [u8; TS_PACKET_SIZE] {
1783 let mut pkt = [0u8; TS_PACKET_SIZE];
1784 pkt[0] = TS_SYNC_BYTE;
1785 pkt[1] = b1;
1786 pkt[2] = b2;
1787 pkt[3] = b3;
1788 let payload_start = 4;
1789 let end = (payload_start + payload_data.len()).min(TS_PACKET_SIZE);
1790 let len = (end - payload_start).min(payload_data.len());
1791 pkt[payload_start..payload_start + len].copy_from_slice(&payload_data[..len]);
1792 pkt
1793 }
1794
1795 #[test]
1796 fn parse_rejects_non_0x47_sync_byte() {
1797 let mut pkt = [0u8; TS_PACKET_SIZE];
1798 pkt[0] = 0x46; let err = TsPacket::parse(&pkt).unwrap_err();
1800 match err {
1801 Error::InvalidSync(e) => assert_eq!(e.found, 0x46),
1802 other => panic!("expected InvalidSyncByte, got {other:?}"),
1803 }
1804 }
1805
1806 #[test]
1807 fn ts_header_round_trip() {
1808 let cases = [
1811 TsHeader {
1812 tei: false,
1813 pusi: true,
1814 pid: Pid::from_const(0x0000),
1815 scrambling: ScramblingControl::NotScrambled,
1816 adaptation_field_control: AdaptationFieldControl::PayloadOnly,
1817 continuity_counter: ContinuityCounter::ZERO,
1818 },
1819 TsHeader {
1820 tei: true,
1821 pusi: false,
1822 pid: Pid::from_const(0x1FFF),
1823 scrambling: ScramblingControl::OddKey,
1824 adaptation_field_control: AdaptationFieldControl::AdaptationAndPayload,
1825 continuity_counter: ContinuityCounter::try_new(0x0F).expect("4-bit counter"),
1826 },
1827 TsHeader {
1828 tei: false,
1829 pusi: false,
1830 pid: Pid::from_const(0x0100),
1831 scrambling: ScramblingControl::EvenKey,
1832 adaptation_field_control: AdaptationFieldControl::AdaptationOnly,
1833 continuity_counter: ContinuityCounter::try_new(7).expect("4-bit counter"),
1834 },
1835 ];
1836 for h in cases {
1837 let mut buf = [0u8; 4];
1838 assert_eq!(h.serialize_into(&mut buf).unwrap(), 4);
1839 assert_eq!(TsHeader::parse(&buf).unwrap(), h, "round-trip mismatch");
1840 }
1841 }
1842
1843 #[test]
1844 fn parse_extracts_pid_and_continuity_counter() {
1845 let pkt = make_packet(0x12, 0x34, 0x05, &[]);
1851 let pkt = TsPacket::parse(&pkt).unwrap();
1852 assert_eq!(pkt.header.pid, Pid::from_const(0x1234));
1853 assert_eq!(pkt.header.continuity_counter.value(), 5);
1854 }
1855
1856 #[test]
1857 fn payload_unit_start_indicator_flag_extracted() {
1858 let pkt1 = make_packet(0x40, 0x00, 0x00, &[]);
1860 let pkt1 = TsPacket::parse(&pkt1).unwrap();
1861 assert!(pkt1.header.pusi);
1862
1863 let pkt2 = make_packet(0x00, 0x00, 0x00, &[]);
1865 let pkt2 = TsPacket::parse(&pkt2).unwrap();
1866 assert!(!pkt2.header.pusi);
1867 }
1868
1869 fn build_pusi_payload(pointer_field: u8, previous_tail: &[u8], section: &[u8]) -> Vec<u8> {
1874 assert_eq!(pointer_field as usize, previous_tail.len());
1875 let mut v = Vec::with_capacity(1 + previous_tail.len() + section.len());
1876 v.push(pointer_field);
1877 v.extend_from_slice(previous_tail);
1878 v.extend_from_slice(section);
1879 v
1880 }
1881
1882 #[test]
1888 fn reassembler_accumulates_multi_packet_section() {
1889 let body = vec![0xAAu8; 197];
1891 let section = test_fixtures::psi::short_section(0x02, &body);
1892 assert_eq!(section.len(), 200);
1893
1894 let first_chunk = 100;
1895 let payload1 = build_pusi_payload(0, &[], §ion[..first_chunk]);
1896 let payload2 = section[first_chunk..].to_vec();
1897
1898 let mut reasm = SectionReassembler::default();
1899 reasm.feed(&payload1, true);
1900 reasm.feed(&payload2, false);
1901
1902 let out = reasm.pop_section().expect("section should be ready");
1903 assert_eq!(out.len(), 200);
1904 assert_eq!(out.as_ref(), §ion[..]);
1905 }
1906
1907 #[test]
1908 fn reassembler_yields_complete_section_once_length_satisfied() {
1909 let section = test_fixtures::psi::short_section(0x42, &[0xAA]);
1911 assert_eq!(section.len(), 4);
1912 let payload = build_pusi_payload(0, &[], §ion);
1913
1914 let mut reasm = SectionReassembler::default();
1915 reasm.feed(&payload, true);
1916
1917 let out = reasm
1918 .pop_section()
1919 .expect("single-packet section should pop");
1920 assert_eq!(out.as_ref(), §ion[..]);
1921 }
1922
1923 #[test]
1924 fn reassembler_extracts_all_concatenated_sections_in_one_payload() {
1925 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();
1934 concat.extend_from_slice(&s1);
1935 concat.extend_from_slice(&s2);
1936 concat.extend_from_slice(&s3);
1937 let payload = build_pusi_payload(0, &[], &concat);
1938
1939 let mut reasm = SectionReassembler::default();
1940 reasm.feed(&payload, true);
1941
1942 let got: Vec<_> = core::iter::from_fn(|| reasm.pop_section()).collect();
1944 assert_eq!(got.len(), 3, "all three concatenated sections must pop");
1945 assert_eq!(got[0].as_ref(), &s1[..]);
1946 assert_eq!(got[1].as_ref(), &s2[..]);
1947 assert_eq!(got[2].as_ref(), &s3[..]);
1948 }
1949
1950 #[test]
1951 fn reassembler_stops_at_stuffing_after_concatenated_sections() {
1952 let s1 = test_fixtures::psi::short_section(0x42, &[0xAA]); let s2 = test_fixtures::psi::short_section(0x46, &[0xBB, 0xCC]); let mut concat = Vec::new();
1958 concat.extend_from_slice(&s1);
1959 concat.extend_from_slice(&s2);
1960 concat.extend_from_slice(&[0xFF, 0xFF, 0xFF, 0xFF]); let payload = build_pusi_payload(0, &[], &concat);
1962
1963 let mut reasm = SectionReassembler::default();
1964 reasm.feed(&payload, true);
1965
1966 let got: Vec<_> = core::iter::from_fn(|| reasm.pop_section()).collect();
1967 assert_eq!(got.len(), 2);
1968 assert_eq!(got[0].as_ref(), &s1[..]);
1969 assert_eq!(got[1].as_ref(), &s2[..]);
1970 assert!(
1971 reasm.is_empty(),
1972 "stuffing tail must be discarded, not buffered"
1973 );
1974 }
1975
1976 #[test]
1977 fn reassembler_concatenated_then_spanning_tail() {
1978 let s1 = test_fixtures::psi::short_section(0x42, &[0x01, 0x02]); let s2 = test_fixtures::psi::short_section(0x46, &[0x09u8; 60]); let split = 30;
1984
1985 let mut head = Vec::new();
1986 head.extend_from_slice(&s1);
1987 head.extend_from_slice(&s2[..split]);
1988 let payload1 = build_pusi_payload(0, &[], &head);
1989 let payload2 = s2[split..].to_vec();
1990
1991 let mut reasm = SectionReassembler::default();
1992 reasm.feed(&payload1, true);
1993 let first = reasm.pop_section().expect("first section pops at once");
1994 assert_eq!(first.as_ref(), &s1[..]);
1995 assert!(reasm.pop_section().is_none(), "second is still partial");
1996
1997 reasm.feed(&payload2, false);
1998 let second = reasm.pop_section().expect("second pops after continuation");
1999 assert_eq!(second.as_ref(), &s2[..]);
2000 }
2001
2002 #[test]
2003 fn reassembler_completes_section_spanning_into_pusi_packet() {
2004 let spanning = test_fixtures::psi::short_section(0x42, &[0x5Au8; 62]); let head = 41;
2012 let tail = &spanning[head..]; assert_eq!(tail.len(), 24);
2014
2015 let next = test_fixtures::psi::short_section(0x46, &[0x77, 0x88]); let payload_a = build_pusi_payload(0, &[], &spanning[..head]);
2020 let payload_b = build_pusi_payload(24, tail, &next);
2022
2023 let mut reasm = SectionReassembler::default();
2024 reasm.feed(&payload_a, true);
2025 assert!(reasm.pop_section().is_none(), "head alone is incomplete");
2026
2027 reasm.feed(&payload_b, true);
2028 let got: Vec<_> = core::iter::from_fn(|| reasm.pop_section()).collect();
2029 assert_eq!(got.len(), 2, "spanning section + new section must both pop");
2030 assert_eq!(
2031 got[0].as_ref(),
2032 &spanning[..],
2033 "spanning section completed from B's pointer tail"
2034 );
2035 assert_eq!(got[1].as_ref(), &next[..]);
2036 }
2037
2038 #[test]
2039 fn reassembler_pusi_pointer_spans_whole_payload() {
2040 let spanning = test_fixtures::psi::short_section(0x42, &[0x33u8; 40]); let head = 20;
2045 let payload_a = build_pusi_payload(0, &[], &spanning[..head]);
2046 let tail = &spanning[head..]; let mut reasm = SectionReassembler::default();
2049 reasm.feed(&payload_a, true);
2050 reasm.feed(&build_pusi_payload_pointer_spanning_all(tail), true);
2052
2053 let out = reasm.pop_section().expect("spanning section completes");
2054 assert_eq!(out.as_ref(), &spanning[..]);
2055 assert!(reasm.pop_section().is_none());
2056 }
2057
2058 fn build_pusi_payload_pointer_spanning_all(tail: &[u8]) -> Vec<u8> {
2061 let mut v = Vec::with_capacity(1 + tail.len());
2062 v.push(tail.len() as u8);
2063 v.extend_from_slice(tail);
2064 v
2065 }
2066
2067 #[test]
2068 fn reassembler_discards_a_retransmitted_continuation_packet() {
2069 let mut section = vec![0x4Eu8, 0xB0, 0x00];
2070 section.resize(300, 0x5A);
2071 section[1] = 0xB0 | (((300 - 3) >> 8) as u8);
2072 section[2] = ((300 - 3) & 0xFF) as u8;
2073 let mut first = vec![0x00u8];
2074 first.extend_from_slice(§ion[..183]);
2075
2076 let mut reasm = SectionReassembler::default();
2077 reasm.feed_with_continuity(&first, true, cc(0), false);
2078 reasm.feed_with_continuity(§ion[183..250], false, cc(1), false);
2079 reasm.feed_with_continuity(§ion[183..250], false, cc(1), false);
2080 reasm.feed_with_continuity(§ion[250..], false, cc(2), false);
2081
2082 let out = reasm.pop_section().expect("section survives the duplicate");
2083 assert_eq!(out.as_ref(), §ion[..]);
2084 assert!(reasm.pop_section().is_none());
2085 }
2086
2087 #[test]
2088 fn a_packet_after_a_discontinuity_with_an_unchanged_counter_is_not_a_duplicate() {
2089 let mut section = vec![0x4Eu8, 0xB0, 0x00];
2090 section.resize(300, 0x5A);
2091 section[1] = 0xB0 | (((300 - 3) >> 8) as u8);
2092 section[2] = ((300 - 3) & 0xFF) as u8;
2093 let mut first = vec![0x00u8];
2094 first.extend_from_slice(§ion[..183]);
2095
2096 let mut reasm = SectionReassembler::default();
2097 reasm.feed_with_continuity(&first, true, cc(0), false);
2098 reasm.feed_with_continuity(§ion[183..250], false, cc(0), true);
2099 reasm.feed_with_continuity(§ion[250..], false, cc(1), false);
2100
2101 let out = reasm
2102 .pop_section()
2103 .expect("section survives the discontinuity");
2104 assert_eq!(out.as_ref(), §ion[..]);
2105 assert!(reasm.pop_section().is_none());
2106 }
2107
2108 #[test]
2109 fn reassembler_completes_max_length_section_and_stays_usable() {
2110 let mut section = Vec::with_capacity(MAX_SECTION_SIZE);
2116 section.push(0x00); section.push(0xB0 | ((4095u16 >> 8) as u8 & 0x0F));
2118 section.push(0xFF); section.resize(MAX_SECTION_SIZE, 0u8);
2120 assert_eq!(section.len(), MAX_SECTION_SIZE);
2121
2122 let mut reasm = SectionReassembler::default();
2123 let mut first = vec![0x00u8]; first.extend_from_slice(§ion[..183]);
2125 reasm.feed(&first, true);
2126 assert!(
2127 reasm.pop_section().is_none(),
2128 "incomplete until the declared length arrives"
2129 );
2130
2131 for chunk in section[183..].chunks(184) {
2132 reasm.feed(chunk, false);
2133 }
2134 let out = reasm
2135 .pop_section()
2136 .expect("max-length section completes at its declared length");
2137 assert_eq!(out.len(), MAX_SECTION_SIZE);
2138 assert_eq!(out.as_ref(), §ion[..]);
2139 assert!(reasm.is_empty());
2140
2141 reasm.feed(&[0u8; 184], false);
2145 assert!(reasm.pop_section().is_none());
2146
2147 let valid_section = test_fixtures::psi::short_section(0x00, &[0xAA]);
2149 let payload2 = build_pusi_payload(0, &[], &valid_section);
2150 reasm.feed(&payload2, true);
2151 let out = reasm
2152 .pop_section()
2153 .expect("fresh section should pop after reset");
2154 assert_eq!(out.as_ref(), &valid_section[..]);
2155 }
2156
2157 #[test]
2158 fn reassembler_handles_pusi_with_nonzero_pointer_field() {
2159 let prior_tail = vec![0x11, 0x22, 0x33];
2161 let new_section = test_fixtures::psi::short_section(0x02, &[0xBB]);
2162 assert_eq!(new_section.len(), 4);
2163 let payload = build_pusi_payload(3, &prior_tail, &new_section);
2164
2165 let mut reasm = SectionReassembler::default();
2166 reasm.feed(&payload, true);
2167
2168 let out = reasm
2169 .pop_section()
2170 .expect("section after pointer_field skip should pop");
2171 assert_eq!(out.as_ref(), &new_section[..]);
2172 }
2173
2174 #[test]
2175 fn reassembler_ignores_continuation_before_pusi() {
2176 let pkt = make_packet(0x00, 0x00, PAYLOAD_FLAG, &[0xAA, 0xBB, 0xCC]);
2179
2180 let mut reasm = SectionReassembler::default();
2181 reasm.feed(&pkt[4..], false); assert!(
2184 reasm.pop_section().is_none(),
2185 "no section should appear without prior PUSI"
2186 );
2187 assert!(
2188 reasm.pop_section().is_none(),
2189 "second pop should also be none"
2190 );
2191 }
2192
2193 #[test]
2196 fn reassembler_empty_pusi_payload_does_not_panic() {
2197 let mut reasm = SectionReassembler::default();
2198 reasm.feed(&[], true);
2199 assert!(reasm.pop_section().is_none());
2200 let payload = vec![0x00u8, 0x72, 0x70, 0x01, 0x00];
2202 reasm.feed(&payload, true);
2203 assert!(reasm.pop_section().is_some());
2204 }
2205
2206 #[test]
2210 fn reassembler_accepts_maximal_private_section() {
2211 let mut section = vec![0x80u8, 0x7F, 0xFF]; section.resize(3 + 0xFFF, 0xAB);
2213
2214 let mut reasm = SectionReassembler::default();
2215 let mut first = vec![0x00];
2217 first.extend_from_slice(§ion[..183]);
2218 reasm.feed(&first, true);
2219 for chunk in section[183..].chunks(184) {
2220 reasm.feed(chunk, false);
2221 }
2222 let out = reasm.pop_section().expect("4098-byte section should pop");
2223 assert_eq!(out.len(), 4098);
2224 assert_eq!(out.as_ref(), §ion[..]);
2225 }
2226
2227 #[test]
2232 fn reassembler_completes_large_section_with_trailing_stuffing() {
2233 let body = vec![0x5Au8; 4096 - 3];
2234 let section = test_fixtures::psi::short_section(0x50, &body); assert_eq!(section.len(), 4096);
2236
2237 let mut reasm = SectionReassembler::default();
2238 let mut first = vec![0x00u8];
2240 first.extend_from_slice(§ion[..183]);
2241 reasm.feed(&first, true);
2242
2243 let mut pos = 183usize;
2247 while pos < section.len() {
2248 let take = (section.len() - pos).min(184);
2249 let mut payload = section[pos..pos + take].to_vec();
2250 if take < 184 {
2251 payload.resize(184, 0xFF); }
2253 reasm.feed(&payload, false);
2254 pos += take;
2255 }
2256
2257 let out = reasm
2258 .pop_section()
2259 .expect("4096-byte section must complete despite trailing stuffing (#148)");
2260 assert_eq!(out.len(), 4096);
2261 assert_eq!(out.as_ref(), §ion[..]);
2262 assert!(reasm.is_empty(), "stuffing tail must be discarded");
2263 }
2264
2265 #[test]
2268 fn pcr_as_27mhz_known_value() {
2269 assert_eq!(
2270 Pcr::from_parts(10_000, 0).expect("in range").as_27mhz(),
2271 3_000_000
2272 );
2273 assert_eq!(Pcr::from_parts(1, 100).expect("in range").as_27mhz(), 400);
2275 }
2276
2277 #[test]
2278 fn pcr_decode_from_bytes() {
2279 let af = [0x10u8, 0x00, 0x00, 0x13, 0x88, 0x7E, 0x00];
2281 let pcr = Pcr::parse(&af, 1).expect("6 bytes present");
2282 assert_eq!(pcr, Pcr::from_parts(10_000, 0).expect("in range"));
2283 assert_eq!((pcr.base(), pcr.extension()), (10_000, 0));
2284 assert_eq!(pcr.as_27mhz(), 3_000_000);
2285 }
2286
2287 #[test]
2288 fn adaptation_field_flags_and_pcr() {
2289 let mut raw = [0xAAu8; TS_PACKET_SIZE];
2290 raw[0] = TS_SYNC_BYTE;
2291 raw[1] = 0x01; raw[2] = 0x00;
2293 raw[3] = ADAPTATION_FLAG | PAYLOAD_FLAG;
2294 raw[4] = 7; raw[5] = AF_DISCONTINUITY | AF_PCR_FLAG;
2296 raw[6..12].copy_from_slice(&[0x00, 0x00, 0x13, 0x88, 0x7E, 0x00]);
2297 let pkt = TsPacket::parse(&raw).expect("valid packet");
2300 let af = pkt
2301 .adaptation_field()
2302 .expect("has adaptation field")
2303 .expect("adaptation field parses");
2304 assert!(af.discontinuity_indicator);
2305 assert!(!af.random_access_indicator);
2306 assert_eq!(af.pcr, Some(Pcr::from_parts(10_000, 0).expect("in range")));
2307 assert_eq!(af.pcr.unwrap().as_27mhz(), 3_000_000);
2308 assert!(af.opcr.is_none());
2309 assert!(af.splice_countdown.is_none());
2310 let payload = pkt.payload.expect("payload present");
2312 assert_eq!(payload.len(), TS_PACKET_SIZE - 12);
2313 assert_eq!(payload[0], 0xAA);
2314 }
2315
2316 #[test]
2322 fn clock_reference_slot_locates_pcr_then_opcr_and_rejects_unreached_fields() {
2323 let mut raw = [0xAAu8; TS_PACKET_SIZE];
2324 raw[0] = TS_SYNC_BYTE;
2325 raw[3] = ADAPTATION_FLAG | PAYLOAD_FLAG;
2326 raw[4] = (1 + 2 * PCR_FIELD_LEN) as u8; raw[5] = AF_PCR_FLAG | AF_OPCR_FLAG;
2328
2329 assert!(matches!(
2331 clock_reference_slot(&raw, AF_PCR_FLAG),
2332 ClockReferenceSlot::Field(r) if r == (CLOCK_REFERENCE_START..CLOCK_REFERENCE_START + PCR_FIELD_LEN)
2333 ));
2334 assert!(matches!(
2335 clock_reference_slot(&raw, AF_OPCR_FLAG),
2336 ClockReferenceSlot::Field(r) if r == (CLOCK_REFERENCE_START + PCR_FIELD_LEN..CLOCK_REFERENCE_START + 2 * PCR_FIELD_LEN)
2337 ));
2338
2339 raw[4] = (1 + PCR_FIELD_LEN) as u8;
2342 assert!(matches!(
2343 clock_reference_slot(&raw, AF_OPCR_FLAG),
2344 ClockReferenceSlot::TooShort { need, have }
2345 if need == 1 + 2 * PCR_FIELD_LEN && have == 1 + PCR_FIELD_LEN
2346 ));
2347
2348 let payload_only = {
2350 let mut p = raw;
2351 p[3] = PAYLOAD_FLAG;
2352 p
2353 };
2354 assert!(matches!(
2355 clock_reference_slot(&payload_only, AF_PCR_FLAG),
2356 ClockReferenceSlot::NoAdaptationField
2357 ));
2358
2359 raw[4] = (1 + PCR_FIELD_LEN) as u8;
2361 raw[5] = AF_OPCR_FLAG;
2362 assert!(matches!(
2363 clock_reference_slot(&raw, AF_PCR_FLAG),
2364 ClockReferenceSlot::FlagClear
2365 ));
2366
2367 raw[5] = AF_PCR_FLAG;
2371 let truncated = &raw[..8];
2372 assert!(matches!(
2373 clock_reference_slot(truncated, AF_PCR_FLAG),
2374 ClockReferenceSlot::Truncated { need, have } if need == 12 && have == 8
2375 ));
2376 }
2377
2378 #[test]
2379 fn oversized_adaptation_field_length_is_rejected_not_truncated() {
2380 let mut raw = [0xAAu8; TS_PACKET_SIZE];
2386 raw[0] = TS_SYNC_BYTE;
2387 raw[1] = 0x01;
2388 raw[2] = 0x00;
2389 raw[3] = ADAPTATION_FLAG; raw[4] = 200; let pkt = TsPacket::parse(&raw).expect("header + af_len byte still parse");
2393 assert!(
2394 pkt.adaptation_field().is_none(),
2395 "an over-long adaptation field must be rejected, not truncated"
2396 );
2397 assert!(pkt.payload.is_none());
2398
2399 let owned = crate::owned::OwnedTsPacket::parse(raw).unwrap();
2401 assert!(owned.adaptation_field().is_none());
2402 }
2403
2404 #[test]
2405 fn no_adaptation_returns_none() {
2406 let mut raw = [0x00u8; TS_PACKET_SIZE];
2407 raw[0] = TS_SYNC_BYTE;
2408 raw[1] = 0x01;
2409 raw[3] = PAYLOAD_FLAG; let pkt = TsPacket::parse(&raw).expect("valid");
2411 assert!(pkt.adaptation_field().is_none());
2412 assert!(pkt.adaptation.is_none());
2413 }
2414
2415 #[test]
2416 fn adaptation_field_splice_countdown_negative() {
2417 let mut raw = [0xAAu8; TS_PACKET_SIZE];
2418 raw[0] = TS_SYNC_BYTE;
2419 raw[1] = 0x01;
2420 raw[2] = 0x00;
2421 raw[3] = ADAPTATION_FLAG | PAYLOAD_FLAG;
2422 raw[4] = 2; raw[5] = AF_SPLICING_FLAG;
2424 raw[6] = 0xFB; let pkt = TsPacket::parse(&raw).expect("valid");
2426 let af = pkt.adaptation_field().unwrap().unwrap();
2427 assert_eq!(af.splice_countdown, Some(-5));
2428 assert!(af.pcr.is_none());
2429 }
2430
2431 #[test]
2434 fn scrambling_control_all_values() {
2435 assert_eq!(
2436 ScramblingControl::from_bits(0b00),
2437 ScramblingControl::NotScrambled
2438 );
2439 assert_eq!(
2440 ScramblingControl::from_bits(0b01),
2441 ScramblingControl::Reserved
2442 );
2443 assert_eq!(
2444 ScramblingControl::from_bits(0b10),
2445 ScramblingControl::EvenKey
2446 );
2447 assert_eq!(
2448 ScramblingControl::from_bits(0b11),
2449 ScramblingControl::OddKey
2450 );
2451 assert_eq!(ScramblingControl::NotScrambled.name(), "not_scrambled");
2453 assert_eq!(ScramblingControl::Reserved.name(), "reserved");
2454 assert_eq!(ScramblingControl::EvenKey.name(), "even_key");
2455 assert_eq!(ScramblingControl::OddKey.name(), "odd_key");
2456 assert_eq!(ScramblingControl::NotScrambled.to_string(), "not_scrambled");
2458 assert_eq!(ScramblingControl::OddKey.to_string(), "odd_key");
2459 assert_eq!(
2461 ScramblingControl::from_bits(0xFF),
2462 ScramblingControl::OddKey
2463 );
2464 }
2465
2466 #[test]
2467 fn adaptation_field_control_all_values() {
2468 assert_eq!(
2469 AdaptationFieldControl::from_flags(false, false),
2470 AdaptationFieldControl::Reserved
2471 );
2472 assert_eq!(
2473 AdaptationFieldControl::from_flags(false, true),
2474 AdaptationFieldControl::PayloadOnly
2475 );
2476 assert_eq!(
2477 AdaptationFieldControl::from_flags(true, false),
2478 AdaptationFieldControl::AdaptationOnly
2479 );
2480 assert_eq!(
2481 AdaptationFieldControl::from_flags(true, true),
2482 AdaptationFieldControl::AdaptationAndPayload
2483 );
2484 assert_eq!(AdaptationFieldControl::Reserved.name(), "reserved");
2486 assert_eq!(AdaptationFieldControl::PayloadOnly.name(), "payload_only");
2487 assert_eq!(
2488 AdaptationFieldControl::AdaptationOnly.name(),
2489 "adaptation_only"
2490 );
2491 assert_eq!(
2492 AdaptationFieldControl::AdaptationAndPayload.name(),
2493 "adaptation_and_payload"
2494 );
2495 assert_eq!(
2497 AdaptationFieldControl::PayloadOnly.to_string(),
2498 "payload_only"
2499 );
2500 }
2501
2502 #[test]
2503 fn ts_header_field_types_carry_the_decoded_values() {
2504 let hdr = TsHeader {
2505 tei: false,
2506 pusi: false,
2507 pid: Pid::from_const(0x0100),
2508 scrambling: ScramblingControl::EvenKey,
2509 adaptation_field_control: AdaptationFieldControl::PayloadOnly,
2510 continuity_counter: ContinuityCounter::ZERO,
2511 };
2512 assert_eq!(hdr.scrambling, ScramblingControl::EvenKey);
2513 assert_eq!(
2514 hdr.adaptation_field_control,
2515 AdaptationFieldControl::PayloadOnly
2516 );
2517 assert!(hdr.has_payload());
2518 assert!(!hdr.has_adaptation());
2519
2520 let hdr_both = TsHeader {
2521 adaptation_field_control: AdaptationFieldControl::AdaptationAndPayload,
2522 ..hdr
2523 };
2524 assert_eq!(
2525 hdr_both.adaptation_field_control,
2526 AdaptationFieldControl::AdaptationAndPayload
2527 );
2528 assert!(hdr_both.has_adaptation() && hdr_both.has_payload());
2529 }
2530
2531 #[test]
2532 fn reserved_adaptation_field_control_is_preserved_through_parse_and_serialize() {
2533 let bytes = [TS_SYNC_BYTE, 0x00, 0x00, 0x05];
2536 let hdr = TsHeader::parse(&bytes).expect("parse");
2537 assert_eq!(
2538 hdr.adaptation_field_control,
2539 AdaptationFieldControl::Reserved
2540 );
2541 assert!(!hdr.has_adaptation() && !hdr.has_payload());
2542 let mut out = [0u8; 4];
2543 hdr.serialize_into(&mut out).expect("serialize");
2544 assert_eq!(out, bytes);
2545 }
2546
2547 #[test]
2550 fn iter_packets_yields_valid_and_skips_bad_sync() {
2551 let pkt1 = make_packet(0x00, 0x00, PAYLOAD_FLAG, &[0xAA; 10]);
2553 let pkt2 = make_packet(0x40, 0x64, PAYLOAD_FLAG, &[0xBB; 10]);
2554 let mut bad = [0u8; TS_PACKET_SIZE];
2555 bad[0] = 0x00; let mut buf = Vec::new();
2558 buf.extend_from_slice(&pkt1);
2559 buf.extend_from_slice(&pkt2);
2560 buf.extend_from_slice(&bad);
2561
2562 let pkts: Vec<_> = super::iter_packets(&buf).collect();
2563 assert_eq!(pkts.len(), 2, "bad sync packet must be skipped");
2564 assert_eq!(pkts[0].header.pid, Pid::from_const(0x0000));
2565 assert_eq!(pkts[1].header.pid, Pid::from_const(0x0064));
2566 }
2567
2568 #[test]
2569 fn extract_ts_payload_payload_only() {
2570 let pkt = make_packet(0x00, 0x00, PAYLOAD_FLAG, &[0xABu8; 10]);
2571 let p = super::extract_ts_payload(&pkt).expect("payload present");
2572 assert_eq!(p[0], 0xAB);
2573 assert_eq!(p.len(), TS_PACKET_SIZE - 4);
2574 }
2575
2576 #[test]
2577 fn extract_ts_payload_adaptation_only_returns_none() {
2578 let pkt = make_packet(0x00, 0x00, ADAPTATION_FLAG, &[]);
2579 assert!(super::extract_ts_payload(&pkt).is_none());
2580 }
2581
2582 #[test]
2587 fn pcr_from_27mhz_round_trips() {
2588 for &ticks in &[0u64, 1, 300, 27_000_000, u64::from(u32::MAX), 8_589_934_591] {
2589 let pcr = Pcr::from_27mhz(ticks).expect("in range");
2590 assert_eq!(pcr.as_27mhz(), ticks, "ticks={ticks}");
2591 }
2592 }
2593
2594 #[test]
2600 fn pcr_to_field_bytes_round_trips_parse() {
2601 let cases = [
2602 Pcr::from_parts(0, 0).expect("in range"),
2603 Pcr::from_parts(10_000, 0).expect("in range"),
2604 Pcr::from_parts(1, 100).expect("in range"),
2605 Pcr::from_parts(0x1_FFFF_FFFF, 299).expect("in range"),
2606 ];
2607 for pcr in cases {
2608 let bytes = pcr.to_field_bytes();
2609 let mut af = [0u8; 7];
2612 af[1..7].copy_from_slice(&bytes);
2613 let decoded = Pcr::parse(&af, 1).expect("parse round-trip");
2614 assert_eq!(decoded, pcr, "round-trip failed for {pcr:?}");
2615 }
2616 }
2617
2618 #[test]
2620 fn pcr_full_width_extension_round_trips_the_field() {
2621 let pcr = Pcr::from_parts(0x1_FFFF_FFFF, 299).expect("in range");
2622 assert_eq!(pcr.to_field_bytes(), [0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0x2B]);
2624 assert_eq!(Pcr::parse(&pcr.to_field_bytes(), 0).expect("parse"), pcr);
2625 assert_eq!(
2626 pcr.as_27mhz(),
2627 broadcast_common::clock33::PCR_WRAP_27MHZ - 1
2628 );
2629 }
2630
2631 #[test]
2635 fn pcr_off_clock_wire_extension_parses_losslessly_and_reports() {
2636 let mut bytes = Pcr::from_parts(5, 0).expect("in range").to_field_bytes();
2637 bytes[4] |= 0x01; bytes[5] = 0x2C; let pcr = Pcr::parse(&bytes, 0).expect("a wire-legal field parses");
2640 assert_eq!((pcr.base(), pcr.extension()), (5, 300));
2641 assert_eq!(
2642 pcr.to_field_bytes(),
2643 bytes,
2644 "re-serializes byte-identically"
2645 );
2646 assert!(!pcr.clock().is_valid());
2647 assert!(matches!(
2648 pcr.to_clock27(),
2649 Err(Error::ClockOutOfRange(
2650 broadcast_common::clock33::ClockOutOfRange {
2651 field: "27 MHz extension",
2652 value: 300,
2653 ..
2654 }
2655 ))
2656 ));
2657 for ext in 0u16..512 {
2659 let mut bytes = Pcr::from_parts(0x1_2345_6789 & ((1 << 33) - 1), 0)
2660 .expect("in range")
2661 .to_field_bytes();
2662 bytes[4] = (bytes[4] & !0x01) | ((ext >> 8) as u8 & 0x01);
2663 bytes[5] = (ext & 0xFF) as u8;
2664 let decoded = Pcr::parse(&bytes, 0).expect("extension is 9 bits on the wire");
2665 assert_eq!(decoded.extension(), ext);
2666 assert_eq!(decoded.to_field_bytes(), bytes);
2667 assert_eq!(decoded.to_clock27().is_ok(), ext < 300);
2668 }
2669 }
2670
2671 #[test]
2674 fn pcr_to_field_bytes_known_vector() {
2675 let pcr = Pcr::from_parts(10_000, 0).expect("in range");
2676 let bytes = pcr.to_field_bytes();
2677 assert_eq!(bytes, [0x00, 0x00, 0x13, 0x88, 0x7E, 0x00]);
2678 }
2679
2680 #[test]
2683 fn scrambling_control_to_bits_inverse_of_from_bits() {
2684 for bits in 0u8..=3 {
2685 let sc = ScramblingControl::from_bits(bits);
2686 assert_eq!(sc.to_bits(), bits, "to_bits() != from_bits() for {bits}");
2687 }
2688 }
2689
2690 #[test]
2693 fn adaptation_field_control_to_bits_inverse_of_from_flags() {
2694 let cases = [
2695 (false, false, 0b00u8),
2696 (false, true, 0b01),
2697 (true, false, 0b10),
2698 (true, true, 0b11),
2699 ];
2700 for (has_af, has_pl, expected_bits) in cases {
2701 let afc = AdaptationFieldControl::from_flags(has_af, has_pl);
2702 assert_eq!(afc.to_bits(), expected_bits);
2703 assert_eq!(afc.to_flags(), (has_af, has_pl));
2704 }
2705 }
2706
2707 #[test]
2711 fn adaptation_field_serialize_round_trip_with_pcr() {
2712 let original = AdaptationField {
2713 discontinuity_indicator: true,
2714 random_access_indicator: false,
2715 elementary_stream_priority_indicator: false,
2716 pcr: Some(Pcr::from_parts(10_000, 0).expect("in range")),
2717 opcr: None,
2718 splice_countdown: None,
2719 transport_private_data: None,
2720 extension: None,
2721 stuffing: &[],
2722 pcr_reserved: PCR_RESERVED_VALUE,
2723 opcr_reserved: PCR_RESERVED_VALUE,
2724 };
2725 let len = original.serialized_len();
2726 assert_eq!(len, 7); let mut buf = vec![0u8; len];
2728 let written = original.serialize_into(&mut buf).expect("serialize");
2729 assert_eq!(written, len);
2730 let decoded = AdaptationField::parse(&buf).expect("parse round-trip");
2731 assert_eq!(decoded, original);
2732 }
2733
2734 #[test]
2738 fn transport_private_data_over_255_bytes_rejected_not_wrapped() {
2739 let data = vec![0u8; 256];
2740 let af = AdaptationField {
2741 discontinuity_indicator: false,
2742 random_access_indicator: false,
2743 elementary_stream_priority_indicator: false,
2744 pcr: None,
2745 opcr: None,
2746 splice_countdown: None,
2747 transport_private_data: Some(&data),
2748 extension: None,
2749 stuffing: &[],
2750 pcr_reserved: PCR_RESERVED_VALUE,
2751 opcr_reserved: PCR_RESERVED_VALUE,
2752 };
2753 let mut buf = vec![0u8; af.serialized_len()];
2754 assert!(matches!(
2755 &(af.serialize_into(&mut buf)),
2756 Err(crate::error::Error::FieldOverflow(_))
2757 ));
2758 }
2759
2760 #[test]
2762 fn adaptation_field_serialize_produces_known_bytes() {
2763 let af = AdaptationField {
2767 discontinuity_indicator: true,
2768 random_access_indicator: false,
2769 elementary_stream_priority_indicator: false,
2770 pcr: Some(Pcr::from_parts(10_000, 0).expect("in range")),
2771 opcr: None,
2772 splice_countdown: None,
2773 transport_private_data: None,
2774 extension: None,
2775 stuffing: &[],
2776 pcr_reserved: PCR_RESERVED_VALUE,
2777 opcr_reserved: PCR_RESERVED_VALUE,
2778 };
2779 let mut buf = [0u8; 7];
2780 af.serialize_into(&mut buf).unwrap();
2781 assert_eq!(buf[0], AF_DISCONTINUITY | AF_PCR_FLAG);
2782 assert_eq!(&buf[1..7], &[0x00, 0x00, 0x13, 0x88, 0x7E, 0x00]);
2783 }
2784
2785 #[test]
2787 fn adaptation_field_serialize_round_trip_opcr_and_splice() {
2788 let original = AdaptationField {
2789 discontinuity_indicator: false,
2790 random_access_indicator: true,
2791 elementary_stream_priority_indicator: true,
2792 pcr: Some(Pcr::from_parts(1, 100).expect("in range")),
2793 opcr: Some(Pcr::from_parts(999, 5).expect("in range")),
2794 splice_countdown: Some(-3),
2795 transport_private_data: None,
2796 extension: None,
2797 stuffing: &[],
2798 pcr_reserved: PCR_RESERVED_VALUE,
2799 opcr_reserved: PCR_RESERVED_VALUE,
2800 };
2801 let len = original.serialized_len();
2802 assert_eq!(len, 1 + 6 + 6 + 1); let mut buf = vec![0u8; len];
2804 original.serialize_into(&mut buf).unwrap();
2805 let decoded = AdaptationField::parse(&buf).expect("parse");
2806 assert_eq!(decoded, original);
2807 }
2808
2809 #[test]
2811 fn adaptation_field_serialize_flags_only() {
2812 let af = AdaptationField {
2813 discontinuity_indicator: false,
2814 random_access_indicator: true,
2815 elementary_stream_priority_indicator: false,
2816 pcr: None,
2817 opcr: None,
2818 splice_countdown: None,
2819 transport_private_data: None,
2820 extension: None,
2821 stuffing: &[],
2822 pcr_reserved: PCR_RESERVED_VALUE,
2823 opcr_reserved: PCR_RESERVED_VALUE,
2824 };
2825 assert_eq!(af.serialized_len(), 1);
2826 let mut buf = [0u8; 1];
2827 af.serialize_into(&mut buf).unwrap();
2828 assert_eq!(buf[0], AF_RANDOM_ACCESS);
2829 let decoded = AdaptationField::parse(&buf).unwrap();
2830 assert_eq!(decoded, af);
2831 }
2832
2833 #[test]
2835 fn adaptation_field_serialize_rejects_small_buffer() {
2836 let af = AdaptationField {
2837 discontinuity_indicator: false,
2838 random_access_indicator: false,
2839 elementary_stream_priority_indicator: false,
2840 pcr: Some(Pcr::from_parts(0, 0).expect("in range")),
2841 opcr: None,
2842 splice_countdown: None,
2843 transport_private_data: None,
2844 extension: None,
2845 stuffing: &[],
2846 pcr_reserved: PCR_RESERVED_VALUE,
2847 opcr_reserved: PCR_RESERVED_VALUE,
2848 };
2849 let mut buf = [0u8; 3]; assert!(matches!(
2851 af.serialize_into(&mut buf),
2852 Err(Error::OutputBufferTooSmall(..))
2853 ));
2854 }
2855
2856 #[test]
2860 fn adaptation_field_extension_ltw_round_trip() {
2861 let ext = AdaptationFieldExtension {
2862 ltw: Some(Ltw {
2863 ltw_valid_flag: true,
2864 ltw_offset: LtwOffset::new(0x1234).expect("in range"),
2865 }),
2866 piecewise_rate: None,
2867 seamless_splice: None,
2868 ..AdaptationFieldExtension::new()
2869 };
2870 let mut buf = vec![0u8; ext.serialized_len()];
2871 ext.serialize_into(&mut buf).unwrap();
2872 let af = AdaptationField {
2875 discontinuity_indicator: false,
2876 random_access_indicator: false,
2877 elementary_stream_priority_indicator: false,
2878 pcr: None,
2879 opcr: None,
2880 splice_countdown: None,
2881 transport_private_data: None,
2882 extension: Some(ext),
2883 stuffing: &[],
2884 pcr_reserved: PCR_RESERVED_VALUE,
2885 opcr_reserved: PCR_RESERVED_VALUE,
2886 };
2887 let len = af.serialized_len();
2888 let mut abuf = vec![0u8; len];
2889 af.serialize_into(&mut abuf).unwrap();
2890 let decoded = AdaptationField::parse(&abuf).unwrap();
2891 assert_eq!(decoded.extension, Some(ext));
2892 }
2893
2894 #[test]
2896 fn adaptation_field_extension_piecewise_rate_round_trip() {
2897 let af = AdaptationField {
2898 discontinuity_indicator: false,
2899 random_access_indicator: false,
2900 elementary_stream_priority_indicator: false,
2901 pcr: None,
2902 opcr: None,
2903 splice_countdown: None,
2904 transport_private_data: None,
2905 extension: Some(AdaptationFieldExtension {
2906 ltw: None,
2907 piecewise_rate: Some(PiecewiseRate::MAX),
2908 seamless_splice: None,
2909 ..AdaptationFieldExtension::new()
2910 }),
2911 stuffing: &[],
2912 pcr_reserved: PCR_RESERVED_VALUE,
2913 opcr_reserved: PCR_RESERVED_VALUE,
2914 };
2915 let mut buf = vec![0u8; af.serialized_len()];
2916 af.serialize_into(&mut buf).unwrap();
2917 let decoded = AdaptationField::parse(&buf).unwrap();
2918 assert_eq!(
2919 decoded.extension.unwrap().piecewise_rate,
2920 Some(PiecewiseRate::MAX)
2921 );
2922 }
2923
2924 #[test]
2926 fn adaptation_field_extension_seamless_splice_round_trip() {
2927 let af = AdaptationField {
2928 discontinuity_indicator: false,
2929 random_access_indicator: false,
2930 elementary_stream_priority_indicator: false,
2931 pcr: None,
2932 opcr: None,
2933 splice_countdown: None,
2934 transport_private_data: None,
2935 extension: Some(AdaptationFieldExtension {
2936 ltw: None,
2937 piecewise_rate: None,
2938 seamless_splice: Some(SeamlessSplice::new(0xA, 0x1_2345_6789)),
2939 ..AdaptationFieldExtension::new()
2940 }),
2941 stuffing: &[],
2942 pcr_reserved: PCR_RESERVED_VALUE,
2943 opcr_reserved: PCR_RESERVED_VALUE,
2944 };
2945 let mut buf = vec![0u8; af.serialized_len()];
2946 af.serialize_into(&mut buf).unwrap();
2947 let decoded = AdaptationField::parse(&buf).unwrap();
2948 let ss = decoded.extension.unwrap().seamless_splice.unwrap();
2949 assert_eq!(ss.splice_type, 0xA);
2950 assert_eq!(ss.dts_next_au, 0x1_2345_6789);
2951 }
2952
2953 #[test]
2957 fn adaptation_field_extension_seamless_splice_rejects_over_range_fields() {
2958 let mut ss = SeamlessSplice::new(0xA, 0x1_2345_6789);
2959 ss.dts_next_au = 1 << SeamlessSplice::DTS_NEXT_AU_BITS;
2960 assert!(matches!(ss.to_marked_field(), Err(Error::FieldOverflow(_))));
2961 ss.dts_next_au = (1 << SeamlessSplice::DTS_NEXT_AU_BITS) - 1;
2962 assert!(ss.to_marked_field().is_ok());
2963
2964 let mut ss = SeamlessSplice::new(0x10, 0x1_2345_6789);
2965 assert!(matches!(ss.to_marked_field(), Err(Error::FieldOverflow(_))));
2966 ss.splice_type = 0x0F;
2967 ss.marker_bits = SPLICE_MARKERS_VALUE + 1;
2968 assert!(matches!(ss.to_marked_field(), Err(Error::FieldOverflow(_))));
2969 ss.marker_bits = SPLICE_MARKERS_VALUE;
2970 assert!(ss.to_marked_field().is_ok());
2971 }
2972
2973 #[test]
2977 fn adaptation_field_extension_rejects_over_range_ltw_and_rate() {
2978 assert!(matches!(
2979 LtwOffset::new(0x8000),
2980 Err(Error::FieldOverflow(_))
2981 ));
2982 assert_eq!(LtwOffset::new(LtwOffset::MAX.get()), Ok(LtwOffset::MAX));
2983 assert!(matches!(
2984 PiecewiseRate::new(0x40_0000),
2985 Err(Error::FieldOverflow(_))
2986 ));
2987 assert_eq!(PiecewiseRate::new(0x3F_FFFF), Ok(PiecewiseRate::MAX));
2988
2989 let mut ext = AdaptationFieldExtension::new();
2990 ext.ltw = Some(Ltw {
2991 ltw_valid_flag: true,
2992 ltw_offset: LtwOffset::MAX,
2993 });
2994 ext.piecewise_rate = Some(PiecewiseRate::MAX);
2995 let mut buf = vec![0u8; ext.serialized_len()];
2996 ext.serialize_into(&mut buf).unwrap();
2997 assert_eq!(buf[1..3], [0xDF, 0xFF]);
2998 assert_eq!(buf[3..6], [0xFF, 0xFF, 0xFF]);
2999 assert_eq!(AdaptationFieldExtension::parse(&buf).unwrap(), ext);
3000 }
3001
3002 #[test]
3005 fn adaptation_field_serialize_rejects_over_range_reserved_bits() {
3006 let mut af = AdaptationField::new();
3007 af.pcr = Some(Pcr::from_parts(0, 0).expect("in range"));
3008 let mut ok = [0u8; 7];
3009 af.serialize_into(&mut ok).unwrap();
3010 assert_eq!(&ok[1..6], &[0x00, 0x00, 0x00, 0x00, 0x7E]);
3011
3012 af.pcr_reserved = PCR_RESERVED_VALUE + 1;
3013 let mut buf = [0u8; 7];
3014 assert!(matches!(
3015 af.serialize_into(&mut buf),
3016 Err(Error::FieldOverflow(_))
3017 ));
3018 }
3019
3020 #[test]
3022 fn adaptation_field_transport_private_data_round_trip() {
3023 let tpd = [0xDE, 0xAD, 0xBE, 0xEF];
3024 let af = AdaptationField {
3025 discontinuity_indicator: false,
3026 random_access_indicator: false,
3027 elementary_stream_priority_indicator: false,
3028 pcr: None,
3029 opcr: None,
3030 splice_countdown: None,
3031 transport_private_data: Some(&tpd),
3032 extension: None,
3033 stuffing: &[],
3034 pcr_reserved: PCR_RESERVED_VALUE,
3035 opcr_reserved: PCR_RESERVED_VALUE,
3036 };
3037 let mut buf = vec![0u8; af.serialized_len()];
3038 af.serialize_into(&mut buf).unwrap();
3039 let decoded = AdaptationField::parse(&buf).unwrap();
3040 assert_eq!(decoded.transport_private_data, Some(tpd.as_slice()));
3041 }
3042
3043 #[test]
3046 fn adaptation_field_stuffing_round_trip() {
3047 let af = AdaptationField {
3048 discontinuity_indicator: false,
3049 random_access_indicator: false,
3050 elementary_stream_priority_indicator: false,
3051 pcr: Some(Pcr::from_parts(12_345, 7).expect("in range")),
3052 opcr: None,
3053 splice_countdown: None,
3054 transport_private_data: None,
3055 extension: None,
3056 stuffing: &[0xFF; 20],
3057 pcr_reserved: PCR_RESERVED_VALUE,
3058 opcr_reserved: PCR_RESERVED_VALUE,
3059 };
3060 assert_eq!(af.serialized_len(), 27);
3062 let mut buf = vec![0u8; af.serialized_len()];
3063 af.serialize_into(&mut buf).unwrap();
3064 assert!(buf[7..27].iter().all(|&b| b == 0xFF));
3066 let decoded = AdaptationField::parse(&buf).unwrap();
3067 assert_eq!(decoded.stuffing.len(), 20);
3068 assert_eq!(decoded, af);
3069 let pure = AdaptationField {
3071 discontinuity_indicator: false,
3072 random_access_indicator: false,
3073 elementary_stream_priority_indicator: false,
3074 pcr: None,
3075 opcr: None,
3076 splice_countdown: None,
3077 transport_private_data: None,
3078 extension: None,
3079 stuffing: &[0xFF; 5],
3080 pcr_reserved: PCR_RESERVED_VALUE,
3081 opcr_reserved: PCR_RESERVED_VALUE,
3082 };
3083 let mut pbuf = vec![0u8; pure.serialized_len()];
3084 pure.serialize_into(&mut pbuf).unwrap();
3085 assert_eq!(pbuf, vec![0x00, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF]);
3086 assert_eq!(AdaptationField::parse(&pbuf).unwrap(), pure);
3087 }
3088
3089 #[test]
3091 fn adaptation_field_all_fields_round_trip() {
3092 let tpd = [0x01u8, 0x02, 0x03];
3093 let af = AdaptationField {
3094 discontinuity_indicator: true,
3095 random_access_indicator: false,
3096 elementary_stream_priority_indicator: false,
3097 pcr: Some(Pcr::from_parts(90_000, 50).expect("in range")),
3098 opcr: None,
3099 splice_countdown: Some(10),
3100 transport_private_data: Some(&tpd),
3101 extension: Some(AdaptationFieldExtension {
3102 ltw: Some(Ltw {
3103 ltw_valid_flag: false,
3104 ltw_offset: LtwOffset::new(500).expect("in range"),
3105 }),
3106 piecewise_rate: Some(PiecewiseRate::new(12345).expect("in range")),
3107 seamless_splice: None,
3108 ..AdaptationFieldExtension::new()
3109 }),
3110 stuffing: &[],
3111 pcr_reserved: PCR_RESERVED_VALUE,
3112 opcr_reserved: PCR_RESERVED_VALUE,
3113 };
3114 let len = af.serialized_len();
3115 let mut buf = vec![0u8; len];
3116 af.serialize_into(&mut buf).unwrap();
3117 let decoded = AdaptationField::parse(&buf).unwrap();
3118 assert_eq!(decoded.pcr, af.pcr);
3119 assert_eq!(decoded.splice_countdown, af.splice_countdown);
3120 assert_eq!(decoded.transport_private_data, af.transport_private_data);
3121 assert_eq!(decoded.extension, af.extension);
3122 assert!(decoded.discontinuity_indicator);
3123 }
3124
3125 #[test]
3128 fn adaptation_field_serialize_from_real_packet_bytes() {
3129 let mut raw = [0xAAu8; TS_PACKET_SIZE];
3131 raw[0] = TS_SYNC_BYTE;
3132 raw[1] = 0x01;
3133 raw[2] = 0x00;
3134 raw[3] = ADAPTATION_FLAG | PAYLOAD_FLAG;
3135 raw[4] = 7;
3136 raw[5] = AF_DISCONTINUITY | AF_PCR_FLAG;
3137 raw[6..12].copy_from_slice(&[0x00, 0x00, 0x13, 0x88, 0x7E, 0x00]);
3138
3139 let pkt = TsPacket::parse(&raw).unwrap();
3140 let af = pkt.adaptation_field().unwrap().unwrap();
3141
3142 let mut ser = vec![0u8; af.serialized_len()];
3144 af.serialize_into(&mut ser).unwrap();
3145 let decoded = AdaptationField::parse(&ser).unwrap();
3146 assert_eq!(
3147 decoded.pcr,
3148 Some(Pcr::from_parts(10_000, 0).expect("in range"))
3149 );
3150 assert!(decoded.discontinuity_indicator);
3151 }
3152}