Skip to main content

TsHeader

Struct TsHeader 

Source
pub struct TsHeader {
    pub tei: bool,
    pub pusi: bool,
    pub pid: Pid,
    pub scrambling: ScramblingControl,
    pub adaptation_field_control: AdaptationFieldControl,
    pub continuity_counter: ContinuityCounter,
}
Expand description

Parsed TS header — the 4-byte transport header fields.

Fields§

§tei: bool

Transport Error Indicator — set by the demodulator when an uncorrectable error is present in the packet.

§pusi: bool

Payload Unit Start Indicator — first byte of the payload is a new PES packet or PSI section header when set.

§pid: Pid

13-bit Packet Identifier.

§scrambling: ScramblingControl

2-bit transport_scrambling_control (ISO/IEC 13818-1 Table 2-4; DVB assigns 01/10/11, see ScramblingControl).

§adaptation_field_control: AdaptationFieldControl

2-bit adaptation_field_control (ISO/IEC 13818-1 Table 2-5): whether the adaptation field and/or the payload follow the header.

The enum, not a pair of flags: the reserved 00 state is a named variant and swapping the two flags is no longer possible.

§continuity_counter: ContinuityCounter

4-bit continuity_counter (wraps 0..=15 per PID).

Implementations§

Source§

impl TsHeader

Source

pub fn parse(raw4: &[u8]) -> Result<Self>

Parse a 4-byte TS transport header.

Examples found in repository?
examples/edit_packet.rs (line 102)
31fn main() {
32    // ── 1) Build a PCR-bearing packet ───────────────────────────────────────
33    let orig_pcr = Pcr::from_parts(10_000, 0).expect("in range");
34    let mut pkt_raw = build_pcr_packet(
35        Pid::from_const(0x0100),
36        ContinuityCounter::try_new(5).expect("4-bit counter"),
37        orig_pcr,
38    );
39
40    // Verify via parse
41    let pkt = TsPacket::parse(&pkt_raw).unwrap();
42    let af = pkt.adaptation_field().unwrap().unwrap();
43    assert_eq!(af.pcr, Some(orig_pcr));
44    assert_eq!(pkt.header.pid, Pid::from_const(0x0100));
45    assert_eq!(pkt.header.continuity_counter.value(), 5);
46    println!("--- PCR-bearing packet ---");
47    println!(
48        "original PCR  : base={} ext={}  ({} ticks @ 27 MHz)",
49        orig_pcr.base(),
50        orig_pcr.extension(),
51        orig_pcr.as_27mhz()
52    );
53
54    // ── 2) Set PCR to a shifted value ───────────────────────────────────────
55    let shifted_pcr = Pcr::from_27mhz(orig_pcr.as_27mhz() + 27_000_000).expect("in range");
56    OwnedTsPacket::set_pcr(&mut pkt_raw, shifted_pcr).expect("set_pcr");
57
58    let re_pkt = TsPacket::parse(&pkt_raw).unwrap();
59    let re_af = re_pkt.adaptation_field().unwrap().unwrap();
60    let re_pcr = re_af.pcr.unwrap();
61    assert_eq!(re_pcr, shifted_pcr);
62    println!(
63        "shifted PCR   : base={} ext={}  ({} ticks @ 27 MHz)",
64        re_pcr.base(),
65        re_pcr.extension(),
66        re_pcr.as_27mhz()
67    );
68    assert_eq!(re_pcr.as_27mhz() - orig_pcr.as_27mhz(), 27_000_000);
69
70    // ── 3) set_continuity_counter on a packet ──────────────────────────────
71    let mut cc_raw: [u8; TS_PACKET_SIZE] = OwnedTsPacket::serialize_with_payload(
72        Pid::from_const(0x0200),
73        true,
74        ContinuityCounter::ZERO,
75        &[],
76    )
77    .unwrap();
78    let orig_cc = TsPacket::parse(&cc_raw).unwrap().header.continuity_counter;
79    OwnedTsPacket::set_continuity_counter(
80        &mut cc_raw,
81        ContinuityCounter::try_new(15).expect("4-bit counter"),
82    );
83    let new_cc = TsPacket::parse(&cc_raw).unwrap().header.continuity_counter;
84    assert_eq!(new_cc.value(), 15);
85    println!("\n--- continuity_counter mutation ---");
86    println!("original CC: {orig_cc}  →  after set_continuity_counter: {new_cc}");
87
88    // ── 4) Build a null_packet and verify PID ───────────────────────────────
89    let null_raw =
90        OwnedTsPacket::null_packet(ContinuityCounter::try_new(7).expect("4-bit counter"));
91    let null_pkt = TsPacket::parse(&null_raw).unwrap();
92    assert_eq!(null_pkt.header.pid, Pid::from_const(0x1FFF));
93    assert_eq!(null_pkt.header.continuity_counter.value(), 7);
94    println!("\n--- null packet ---");
95    println!(
96        "null packet PID = 0x{:04X}  (expect 0x1FFF), CC = {}",
97        null_pkt.header.pid.value(),
98        null_pkt.header.continuity_counter.value()
99    );
100
101    // ── 5) Round-trip a TsHeader ────────────────────────────────────────────
102    let orig_hdr = TsHeader::parse(&[0x47, 0x40, 0x00, 0x10]).unwrap();
103    let mut hdr_buf = [0u8; 4];
104    orig_hdr.serialize_into(&mut hdr_buf).unwrap();
105    let re_hdr = TsHeader::parse(&hdr_buf).unwrap();
106    assert_eq!(re_hdr.pid, orig_hdr.pid);
107    assert_eq!(re_hdr.pusi, orig_hdr.pusi);
108    assert_eq!(re_hdr.continuity_counter, orig_hdr.continuity_counter);
109    println!("\n--- round-trip (TsHeader) ---");
110    println!(
111        "TsHeader parse → serialize_into → parse: pid=0x{:04X}, pusi={}, cc={}",
112        re_hdr.pid.value(),
113        re_hdr.pusi,
114        re_hdr.continuity_counter.value()
115    );
116
117    // ── 6) Round-trip an OwnedTsPacket ──────────────────────────────────────
118    let owned = OwnedTsPacket::parse(
119        OwnedTsPacket::serialize_with_payload(
120            Pid::from_const(0x0100),
121            true,
122            ContinuityCounter::try_new(3).expect("4-bit counter"),
123            &[0xAA, 0xBB],
124        )
125        .unwrap(),
126    )
127    .unwrap();
128    assert_eq!(owned.pid(), Pid::from_const(0x0100));
129    assert_eq!(owned.continuity_counter().value(), 3);
130    assert!(owned.payload().is_some());
131    assert_eq!(owned.payload().unwrap().len(), 184); // full payload area (serialize_with_payload fills the rest with 0xFF)
132    assert_eq!(owned.payload().unwrap()[..2], [0xAA, 0xBB]);
133    println!(
134        "OwnedTsPacket serialize_with_payload → parse → fields match: pid=0x{:04X}, pusi={}, cc={}",
135        owned.pid().value(),
136        owned.pusi(),
137        owned.continuity_counter().value()
138    );
139
140    println!("\nAll write/edit operations completed successfully.");
141}
Source

pub const fn serialized_len() -> usize

Number of bytes written by serialize_into.

Source

pub fn to_bytes(&self) -> [u8; 4]

The 4 header bytes, infallibly encoded.

Source

pub fn serialize_into(&self, buf: &mut [u8]) -> Result<usize>

Serialize this header into the first 4 bytes of buf.

Examples found in repository?
examples/edit_packet.rs (line 104)
31fn main() {
32    // ── 1) Build a PCR-bearing packet ───────────────────────────────────────
33    let orig_pcr = Pcr::from_parts(10_000, 0).expect("in range");
34    let mut pkt_raw = build_pcr_packet(
35        Pid::from_const(0x0100),
36        ContinuityCounter::try_new(5).expect("4-bit counter"),
37        orig_pcr,
38    );
39
40    // Verify via parse
41    let pkt = TsPacket::parse(&pkt_raw).unwrap();
42    let af = pkt.adaptation_field().unwrap().unwrap();
43    assert_eq!(af.pcr, Some(orig_pcr));
44    assert_eq!(pkt.header.pid, Pid::from_const(0x0100));
45    assert_eq!(pkt.header.continuity_counter.value(), 5);
46    println!("--- PCR-bearing packet ---");
47    println!(
48        "original PCR  : base={} ext={}  ({} ticks @ 27 MHz)",
49        orig_pcr.base(),
50        orig_pcr.extension(),
51        orig_pcr.as_27mhz()
52    );
53
54    // ── 2) Set PCR to a shifted value ───────────────────────────────────────
55    let shifted_pcr = Pcr::from_27mhz(orig_pcr.as_27mhz() + 27_000_000).expect("in range");
56    OwnedTsPacket::set_pcr(&mut pkt_raw, shifted_pcr).expect("set_pcr");
57
58    let re_pkt = TsPacket::parse(&pkt_raw).unwrap();
59    let re_af = re_pkt.adaptation_field().unwrap().unwrap();
60    let re_pcr = re_af.pcr.unwrap();
61    assert_eq!(re_pcr, shifted_pcr);
62    println!(
63        "shifted PCR   : base={} ext={}  ({} ticks @ 27 MHz)",
64        re_pcr.base(),
65        re_pcr.extension(),
66        re_pcr.as_27mhz()
67    );
68    assert_eq!(re_pcr.as_27mhz() - orig_pcr.as_27mhz(), 27_000_000);
69
70    // ── 3) set_continuity_counter on a packet ──────────────────────────────
71    let mut cc_raw: [u8; TS_PACKET_SIZE] = OwnedTsPacket::serialize_with_payload(
72        Pid::from_const(0x0200),
73        true,
74        ContinuityCounter::ZERO,
75        &[],
76    )
77    .unwrap();
78    let orig_cc = TsPacket::parse(&cc_raw).unwrap().header.continuity_counter;
79    OwnedTsPacket::set_continuity_counter(
80        &mut cc_raw,
81        ContinuityCounter::try_new(15).expect("4-bit counter"),
82    );
83    let new_cc = TsPacket::parse(&cc_raw).unwrap().header.continuity_counter;
84    assert_eq!(new_cc.value(), 15);
85    println!("\n--- continuity_counter mutation ---");
86    println!("original CC: {orig_cc}  →  after set_continuity_counter: {new_cc}");
87
88    // ── 4) Build a null_packet and verify PID ───────────────────────────────
89    let null_raw =
90        OwnedTsPacket::null_packet(ContinuityCounter::try_new(7).expect("4-bit counter"));
91    let null_pkt = TsPacket::parse(&null_raw).unwrap();
92    assert_eq!(null_pkt.header.pid, Pid::from_const(0x1FFF));
93    assert_eq!(null_pkt.header.continuity_counter.value(), 7);
94    println!("\n--- null packet ---");
95    println!(
96        "null packet PID = 0x{:04X}  (expect 0x1FFF), CC = {}",
97        null_pkt.header.pid.value(),
98        null_pkt.header.continuity_counter.value()
99    );
100
101    // ── 5) Round-trip a TsHeader ────────────────────────────────────────────
102    let orig_hdr = TsHeader::parse(&[0x47, 0x40, 0x00, 0x10]).unwrap();
103    let mut hdr_buf = [0u8; 4];
104    orig_hdr.serialize_into(&mut hdr_buf).unwrap();
105    let re_hdr = TsHeader::parse(&hdr_buf).unwrap();
106    assert_eq!(re_hdr.pid, orig_hdr.pid);
107    assert_eq!(re_hdr.pusi, orig_hdr.pusi);
108    assert_eq!(re_hdr.continuity_counter, orig_hdr.continuity_counter);
109    println!("\n--- round-trip (TsHeader) ---");
110    println!(
111        "TsHeader parse → serialize_into → parse: pid=0x{:04X}, pusi={}, cc={}",
112        re_hdr.pid.value(),
113        re_hdr.pusi,
114        re_hdr.continuity_counter.value()
115    );
116
117    // ── 6) Round-trip an OwnedTsPacket ──────────────────────────────────────
118    let owned = OwnedTsPacket::parse(
119        OwnedTsPacket::serialize_with_payload(
120            Pid::from_const(0x0100),
121            true,
122            ContinuityCounter::try_new(3).expect("4-bit counter"),
123            &[0xAA, 0xBB],
124        )
125        .unwrap(),
126    )
127    .unwrap();
128    assert_eq!(owned.pid(), Pid::from_const(0x0100));
129    assert_eq!(owned.continuity_counter().value(), 3);
130    assert!(owned.payload().is_some());
131    assert_eq!(owned.payload().unwrap().len(), 184); // full payload area (serialize_with_payload fills the rest with 0xFF)
132    assert_eq!(owned.payload().unwrap()[..2], [0xAA, 0xBB]);
133    println!(
134        "OwnedTsPacket serialize_with_payload → parse → fields match: pid=0x{:04X}, pusi={}, cc={}",
135        owned.pid().value(),
136        owned.pusi(),
137        owned.continuity_counter().value()
138    );
139
140    println!("\nAll write/edit operations completed successfully.");
141}
Source

pub fn has_adaptation(&self) -> bool

Whether an adaptation field follows the header (adaptation_field_control bit 1, ISO/IEC 13818-1 Table 2-5).

Source

pub fn has_payload(&self) -> bool

Whether a payload follows the header/adaptation field (adaptation_field_control bit 0, ISO/IEC 13818-1 Table 2-5).

Examples found in repository?
examples/demux.rs (line 51)
45fn main() {
46    let pkt = TsPacket::parse(&PAT_PACKET).expect("hardcoded packet must parse");
47    println!(
48        "TS packet: pid=0x{:04X} pusi={} has_payload={}",
49        pkt.header.pid.value(),
50        pkt.header.pusi,
51        pkt.header.has_payload()
52    );
53    assert_eq!(pkt.header.pid, well_known::PAT);
54
55    let mut reasm = SectionReassembler::default();
56
57    if let Some(payload) = pkt.payload {
58        reasm.feed(payload, pkt.header.pusi);
59    }
60
61    let mut units = UnitReassembler::new(
62        PatFraming,
63        UnitOptions::new(
64            AfterContinuation::DiscardRest,
65            PointerCheck::Authoritative,
66            Duplicates::Any,
67            std::num::NonZeroUsize::new(1024).unwrap(),
68        ),
69    );
70
71    while let Some(section) = reasm.pop_section() {
72        let mut packets = Vec::new();
73        let count =
74            SectionPacketiser::new(well_known::PAT).packetise_into(&[&section], &mut packets);
75        println!(
76            "re-packetised {count} PAT packet(s), section: {} bytes, table_id=0x{:02X}",
77            section.len(),
78            section[0]
79        );
80        // The PAT section bytes: table_id=0x00, transport_stream_id at bytes 3-4.
81        if section.len() >= 5 {
82            let ts_id = u16::from_be_bytes([section[3], section[4]]);
83            println!("  transport_stream_id={ts_id}");
84        }
85        if let Some(payload) = pkt.payload {
86            units.feed(payload, pkt.header.pusi, None);
87            if let Some(unit) = units.pop() {
88                println!("  unit reassembled: {} bytes", unit.len());
89            }
90        }
91    }
92}

Trait Implementations§

Source§

impl Clone for TsHeader

Source§

fn clone(&self) -> Self

Returns a duplicate of the value. Read more
1.0.0 (const: unstable) · Source§

fn clone_from(&mut self, source: &Self)

Performs copy-assignment from source. Read more
Source§

impl Debug for TsHeader

Source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more
Source§

impl Eq for TsHeader

Source§

impl<'a> Parse<'a> for TsHeader

Source§

type Error = Error

The error type this implementer returns. Typically the enclosing crate’s Error enum.
Source§

fn parse(bytes: &'a [u8]) -> Result<Self>

Parse bytes as Self. Returns Err(Self::Error) on any protocol violation or buffer underrun. Read more
Source§

impl PartialEq for TsHeader

Source§

fn eq(&self, other: &Self) -> bool

Equality operator ==. Read more
1.0.0 (const: unstable) · Source§

fn ne(&self, other: &Rhs) -> bool

Inequality operator !=. Read more
Source§

impl Serialize for TsHeader

Available on crate feature serde only.
Source§

fn serialize<__S>(&self, __serializer: __S) -> Result<__S::Ok, __S::Error>
where __S: Serializer,

Serialize this value into the given Serde serializer. Read more
Source§

impl Serialize for TsHeader

Source§

type Error = Error

The error type this implementer returns (usually the same as the corresponding Parse impl, but need not be).
Source§

fn serialized_len(&self) -> usize

Number of bytes serialize_into will write.
Source§

fn serialize_into(&self, buf: &mut [u8]) -> Result<usize>

Write the serialised form into buf. Returns the number of bytes written (always equal to serialized_len()).
Source§

fn try_to_bytes(&self) -> Result<Vec<u8>, Self::Error>

Allocate a Vec and serialize into it, returning the serializer’s error instead of panicking. This is the only allocate-and-serialize entry point: there is deliberately no panicking to_bytes (hand-built values, or values assembled from damaged wire data, can violate a wire constraint, so the error must reach the caller).
Source§

fn serialize_append(&self, out: &mut Vec<u8>) -> Result<usize, Self::Error>

Append the serialised form to out, returning the number of bytes appended. out is left unchanged when the serializer fails.
Source§

impl StructuralPartialEq for TsHeader

Auto Trait Implementations§

Blanket Implementations§

Source§

impl<T> Any for T
where T: 'static + ?Sized,

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
Source§

impl<T> Borrow<T> for T
where T: ?Sized,

Source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
Source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

Source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
Source§

impl<T> CloneToUninit for T
where T: Clone,

Source§

unsafe fn clone_to_uninit(&self, dest: *mut u8)

🔬This is a nightly-only experimental API. (clone_to_uninit)
Performs copy-assignment from self to dest. Read more
Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

Source§

impl<T, U> Into<U> for T
where U: From<T>,

Source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

Source§

impl<T> Serialize for T
where T: Serialize + ?Sized,

Source§

fn erased_serialize(&self, serializer: &mut dyn Serializer) -> Result<(), Error>

Source§

fn do_erased_serialize( &self, serializer: &mut dyn Serializer, ) -> Result<(), ErrorImpl>

Source§

impl<T> ToOwned for T
where T: Clone,

Source§

type Owned = T

The resulting type after obtaining ownership.
Source§

fn to_owned(&self) -> T

Creates owned data from borrowed data, usually by cloning. Read more
Source§

fn clone_into(&self, target: &mut T)

Uses borrowed data to replace owned data, usually by cloning. Read more
Source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

Source§

type Error = !

The type returned in the event of a conversion error.
Source§

fn try_from(value: U) -> Result<T, !>

Performs the conversion.
Source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

Source§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
Source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.