mpeg_ts/owned.rs
1//! Owned 188-byte TS packet with pre-parsed header fields.
2//!
3//! [`OwnedTsPacket`] complements the zero-copy [`crate::ts::TsPacket`] (which holds
4//! a borrowed `&[u8; 188]`) with an **owned** `[u8; 188]` suitable for queuing,
5//! cloning, and in-place mutation — e.g. for mux pipelines that must rewrite the
6//! continuity counter or splice in a new payload.
7//!
8//! Header parsing delegates to [`crate::ts::TsHeader::parse`]; no bit-twiddling
9//! is duplicated here.
10
11use crate::error::{Error, Result};
12use crate::ts::{
13 ADAPTATION_FLAG, AF_PCR_FLAG, AdaptationField, AdaptationFieldControl, CC_MASK, PCR_FIELD_LEN,
14 Pcr, ScramblingControl, TS_PACKET_SIZE, TS_SYNC_BYTE, TsHeader,
15};
16
17/// The 13-bit PID value used for null packets — `0x1FFF`
18/// (ISO/IEC 13818-1 §2.4.3.3, Table 2-3).
19const NULL_PID: u16 = 0x1FFF;
20
21/// Owned 188-byte TS packet with pre-parsed header fields.
22///
23/// The raw bytes are stored privately; the parsed flags (`pid`, `pusi`, etc.)
24/// are pre-extracted at construction time so hot paths avoid repeated byte
25/// masking. The fields are **private** (audit r01-W8, #1074): a public copy
26/// of a header field that a caller could assign would silently drift from
27/// the bytes that [`raw`](Self::raw) serialises. Read them through the
28/// getters; the only mutation entry points are the associated functions that
29/// edit a raw `[u8; 188]` (`set_pcr`, `set_continuity_counter`) followed by a
30/// re-[`parse`](Self::parse).
31///
32/// # Payload access
33///
34/// Use [`payload`](Self::payload) / [`payload_mut`](Self::payload_mut) to obtain
35/// a slice that correctly skips the 4-byte header **and** any adaptation field.
36///
37/// # Building packets
38///
39/// [`serialize_with_payload`](Self::serialize_with_payload) constructs a plain
40/// payload-only packet (no adaptation field) filled with 0xFF stuffing.
41#[derive(Clone, Debug)]
42#[cfg_attr(feature = "serde", derive(serde::Serialize))]
43pub struct OwnedTsPacket {
44 /// The raw 188 bytes (serialized as a byte sequence).
45 #[cfg_attr(feature = "serde", serde(serialize_with = "serialize_raw_bytes"))]
46 raw: [u8; TS_PACKET_SIZE],
47 /// 13-bit PID extracted from bytes 1–2.
48 pid: u16,
49 /// Payload Unit Start Indicator (byte 1 bit 6).
50 pusi: bool,
51 /// Adaptation field present flag (byte 3 bit 5).
52 has_adaptation: bool,
53 /// Payload present flag (byte 3 bit 4).
54 has_payload: bool,
55 /// Transport Error Indicator (byte 1 bit 7).
56 tei: bool,
57 /// 2-bit transport_scrambling_control (byte 3 bits 7–6).
58 scrambling: u8,
59 /// 4-bit continuity_counter (byte 3 bits 3–0).
60 continuity_counter: u8,
61 /// Discontinuity flag: `true` if the adaptation-field `discontinuity_indicator`
62 /// was set in the source packet, or if the caller marks this as a
63 /// continuity-counter discontinuity boundary. Defaults to `false` on parse.
64 pub discontinuity: bool,
65}
66
67/// Serialize a `[u8; N]` as a variable-length byte sequence so serde's
68/// blanket impls (only up to `[u8; 32]`) are not required.
69#[cfg(feature = "serde")]
70fn serialize_raw_bytes<S: serde::Serializer>(
71 bytes: &[u8; TS_PACKET_SIZE],
72 s: S,
73) -> core::result::Result<S::Ok, S::Error> {
74 use serde::ser::SerializeSeq;
75 let mut seq = s.serialize_seq(Some(bytes.len()))?;
76 for b in bytes {
77 seq.serialize_element(b)?;
78 }
79 seq.end()
80}
81
82impl OwnedTsPacket {
83 /// The raw 188 bytes.
84 pub fn raw(&self) -> &[u8; TS_PACKET_SIZE] {
85 &self.raw
86 }
87
88 /// Consume the packet, returning its raw 188 bytes.
89 pub fn into_raw(self) -> [u8; TS_PACKET_SIZE] {
90 self.raw
91 }
92
93 /// 13-bit PID (bytes 1–2).
94 pub fn pid(&self) -> u16 {
95 self.pid
96 }
97
98 /// Payload Unit Start Indicator (byte 1 bit 6).
99 pub fn pusi(&self) -> bool {
100 self.pusi
101 }
102
103 /// Adaptation field present flag (byte 3 bit 5).
104 pub fn has_adaptation(&self) -> bool {
105 self.has_adaptation
106 }
107
108 /// Payload present flag (byte 3 bit 4).
109 pub fn has_payload(&self) -> bool {
110 self.has_payload
111 }
112
113 /// Transport Error Indicator (byte 1 bit 7).
114 pub fn tei(&self) -> bool {
115 self.tei
116 }
117
118 /// Raw 2-bit `transport_scrambling_control` (byte 3 bits 7–6); see
119 /// [`scrambling_control`](Self::scrambling_control) for the typed view.
120 pub fn scrambling(&self) -> u8 {
121 self.scrambling
122 }
123
124 /// 4-bit continuity_counter (byte 3 bits 3–0).
125 pub fn continuity_counter(&self) -> u8 {
126 self.continuity_counter
127 }
128
129 /// Parse a 188-byte owned TS packet.
130 ///
131 /// Returns [`Error::InvalidSyncByte`] if `raw[0] != 0x47`.
132 /// Header bit-parsing is delegated to [`TsHeader::parse`].
133 /// The `discontinuity` field defaults to `false`; set it manually if needed.
134 pub fn parse(raw: [u8; TS_PACKET_SIZE]) -> Result<Self> {
135 if raw[0] != TS_SYNC_BYTE {
136 return Err(Error::InvalidSyncByte { found: raw[0] });
137 }
138 let hdr = TsHeader::parse(&raw[..4])?;
139 Ok(Self {
140 raw,
141 pid: hdr.pid,
142 pusi: hdr.pusi,
143 has_adaptation: hdr.has_adaptation,
144 has_payload: hdr.has_payload,
145 tei: hdr.tei,
146 scrambling: hdr.scrambling,
147 continuity_counter: hdr.continuity_counter,
148 discontinuity: false,
149 })
150 }
151
152 /// Typed view of the 2-bit `transport_scrambling_control` field.
153 ///
154 /// See [`ScramblingControl`] for the spec citation (H.222.0 Table 2-4 +
155 /// ETSI TS 100 289 §5.1 Table 1).
156 pub fn scrambling_control(&self) -> ScramblingControl {
157 ScramblingControl::from_bits(self.scrambling)
158 }
159
160 /// Typed view of the `adaptation_field_control` 2-bit field, derived from the
161 /// stored `has_adaptation`/`has_payload` booleans.
162 ///
163 /// See [`AdaptationFieldControl`] for the spec citation (H.222.0 Table 2-5).
164 pub fn adaptation_field_control(&self) -> AdaptationFieldControl {
165 AdaptationFieldControl::from_flags(self.has_adaptation, self.has_payload)
166 }
167
168 /// Return the payload bytes (after the 4-byte header and any adaptation field).
169 ///
170 /// Returns `None` when [`has_payload`](Self::has_payload) is `false` or the
171 /// adaptation field consumed all remaining bytes.
172 pub fn payload(&self) -> Option<&[u8]> {
173 if !self.has_payload {
174 return None;
175 }
176 let offset = self.payload_offset();
177 if offset < TS_PACKET_SIZE {
178 Some(&self.raw[offset..])
179 } else {
180 None
181 }
182 }
183
184 /// Return a mutable slice of the payload bytes.
185 ///
186 /// Returns `None` when [`has_payload`](Self::has_payload) is `false` or the
187 /// adaptation field consumed all remaining bytes.
188 pub fn payload_mut(&mut self) -> Option<&mut [u8]> {
189 if !self.has_payload {
190 return None;
191 }
192 let offset = self.payload_offset();
193 if offset < TS_PACKET_SIZE {
194 Some(&mut self.raw[offset..])
195 } else {
196 None
197 }
198 }
199
200 /// Compute the byte offset of the first payload byte inside `raw`.
201 ///
202 /// The 4-byte header is always present; if `has_adaptation` is set, the next
203 /// byte is the adaptation-field length, and the payload starts after those
204 /// `1 + af_len` bytes.
205 #[inline]
206 fn payload_offset(&self) -> usize {
207 let mut offset = 4;
208 if self.has_adaptation {
209 // raw[4] is the adaptation_field_length byte
210 let af_len = self.raw[4] as usize;
211 offset += 1 + af_len;
212 }
213 offset
214 }
215
216 /// Maximum payload bytes a plain (no-adaptation-field) TS packet can carry:
217 /// 188 bytes minus the 4-byte header.
218 pub const MAX_PAYLOAD_LEN: usize = TS_PACKET_SIZE - 4;
219
220 /// Build a 188-byte payload-only TS packet (no adaptation field).
221 ///
222 /// The packet is initialised to `0xFF` (MPEG-TS stuffing), the 4-byte header
223 /// is written via [`TsHeader::serialize_into`], then `payload` is copied
224 /// starting at byte 4. Any unfilled bytes remain `0xFF`.
225 ///
226 /// Returns [`Error::PayloadTooLarge`] if `payload` is longer than
227 /// [`MAX_PAYLOAD_LEN`](Self::MAX_PAYLOAD_LEN) (184 bytes) — the fixed
228 /// per-packet payload capacity would previously be silently truncated
229 /// (#1129).
230 ///
231 /// # Panics
232 ///
233 /// Never panics — serializing a 4-byte header into a 188-byte buffer cannot
234 /// fail.
235 pub fn serialize_with_payload(
236 pid: u16,
237 pusi: bool,
238 cc: u8,
239 payload: &[u8],
240 ) -> Result<[u8; TS_PACKET_SIZE]> {
241 if payload.len() > Self::MAX_PAYLOAD_LEN {
242 return Err(Error::PayloadTooLarge {
243 len: payload.len(),
244 max: Self::MAX_PAYLOAD_LEN,
245 });
246 }
247 let mut pkt = [0xFFu8; TS_PACKET_SIZE];
248 let hdr = TsHeader {
249 tei: false,
250 pusi,
251 pid,
252 scrambling: 0,
253 has_adaptation: false,
254 has_payload: true,
255 continuity_counter: cc & CC_MASK,
256 };
257 // Cannot fail: buf is 188 bytes, need 4.
258 hdr.serialize_into(&mut pkt)
259 .expect("serialize TsHeader into 188-byte buf");
260 pkt[4..4 + payload.len()].copy_from_slice(payload);
261 Ok(pkt)
262 }
263
264 /// Build a 188-byte null packet (PID `0x1FFF`) with `0xFF`-stuffed payload.
265 ///
266 /// Null packets carry PID `0x1FFF` and have no meaningful payload
267 /// (ISO/IEC 13818-1 §2.4.1). The continuity counter `cc` is masked to 4
268 /// bits. Transport scrambling is `00` (not scrambled).
269 ///
270 /// # Example
271 ///
272 /// ```
273 /// use mpeg_ts::OwnedTsPacket;
274 /// use mpeg_ts::ts::{TsPacket, TS_PACKET_SIZE};
275 /// let raw = OwnedTsPacket::null_packet(3);
276 /// assert_eq!(raw.len(), TS_PACKET_SIZE);
277 /// let pkt = TsPacket::parse(&raw).unwrap();
278 /// assert_eq!(pkt.header.pid, 0x1FFF);
279 /// assert_eq!(pkt.header.continuity_counter, 3);
280 /// ```
281 #[must_use]
282 pub fn null_packet(cc: u8) -> [u8; TS_PACKET_SIZE] {
283 // Cannot fail: an empty payload never exceeds MAX_PAYLOAD_LEN.
284 Self::serialize_with_payload(NULL_PID, false, cc, &[])
285 .expect("empty payload always fits a TS packet")
286 }
287
288 /// Overwrite the `continuity_counter` field in `packet` without re-parsing.
289 ///
290 /// Writes the low 4 bits of `cc` into byte 3 bits `[3:0]` in place
291 /// (ISO/IEC 13818-1 §2.4.3.3). The other bits of byte 3 are preserved.
292 ///
293 /// # Example
294 ///
295 /// ```
296 /// use mpeg_ts::OwnedTsPacket;
297 /// use mpeg_ts::ts::TsPacket;
298 /// let mut raw = OwnedTsPacket::serialize_with_payload(0x0100, false, 0, &[]).unwrap();
299 /// OwnedTsPacket::set_continuity_counter(&mut raw, 7);
300 /// let pkt = TsPacket::parse(&raw).unwrap();
301 /// assert_eq!(pkt.header.continuity_counter, 7);
302 /// ```
303 pub fn set_continuity_counter(packet: &mut [u8; TS_PACKET_SIZE], cc: u8) {
304 // Byte 3 bits [3:0] = continuity_counter (ISO/IEC 13818-1 §2.4.3.3).
305 packet[3] = (packet[3] & !CC_MASK) | (cc & CC_MASK);
306 }
307
308 /// Overwrite the PCR value in an existing adaptation field in `packet`.
309 ///
310 /// The packet must already have `adaptation_field_control` with adaptation
311 /// present (`has_adaptation == true`) and the PCR flag set in the adaptation
312 /// field flags byte. This function locates the 6-byte PCR field and
313 /// overwrites it with the encoding of `pcr`.
314 ///
315 /// # Errors
316 ///
317 /// - [`Error::BufferTooShort`] — the adaptation field does not contain a
318 /// PCR slot (no adaptation field, zero-length field, or PCR flag not set).
319 ///
320 /// # Example
321 ///
322 /// ```
323 /// use mpeg_ts::ts::{AdaptationField, AF_PCR_FLAG, Pcr, TsPacket,
324 /// TS_PACKET_SIZE, TS_SYNC_BYTE,
325 /// ADAPTATION_FLAG, PAYLOAD_FLAG};
326 /// use mpeg_ts::OwnedTsPacket;
327 ///
328 /// // Build a packet that has a PCR slot (adaptation_field_length = 7).
329 /// let mut raw = [0xAAu8; TS_PACKET_SIZE];
330 /// raw[0] = TS_SYNC_BYTE;
331 /// raw[1] = 0x00; raw[2] = 0x64; // PID = 100
332 /// raw[3] = ADAPTATION_FLAG | PAYLOAD_FLAG;
333 /// raw[4] = 7; // adaptation_field_length
334 /// raw[5] = AF_PCR_FLAG;
335 /// raw[6..12].copy_from_slice(&[0u8; 6]);
336 ///
337 /// let new_pcr = Pcr { base: 10_000, extension: 0 };
338 /// OwnedTsPacket::set_pcr(&mut raw, new_pcr).unwrap();
339 ///
340 /// let pkt = TsPacket::parse(&raw).unwrap();
341 /// let af = pkt.adaptation_field().unwrap().unwrap();
342 /// assert_eq!(af.pcr, Some(new_pcr));
343 /// ```
344 pub fn set_pcr(packet: &mut [u8; TS_PACKET_SIZE], pcr: Pcr) -> Result<()> {
345 // Byte 3: check adaptation_field_control has adaptation bit set
346 // (ADAPTATION_FLAG = bit 5, ISO/IEC 13818-1 §2.4.3.3).
347 if packet[3] & ADAPTATION_FLAG == 0 {
348 return Err(Error::BufferTooShort {
349 need: 6,
350 have: 0,
351 what: "set_pcr: no adaptation field",
352 });
353 }
354 let af_len = packet[4] as usize;
355 // W7 (#1074): the flags byte (1) + PCR field (PCR_FIELD_LEN = 6) must
356 // both fit inside `af_len`, not just the flags byte. A malformed
357 // adaptation field with `af_len` between 1 and 6 (PCR flag set
358 // anyway) previously passed this check and then wrote 6 PCR bytes at
359 // a fixed offset — 5 of which land past what `af_len` declares as
360 // the adaptation field, i.e. into the payload.
361 const REQUIRED_AF_LEN: usize = 1 + PCR_FIELD_LEN;
362 if af_len < REQUIRED_AF_LEN {
363 return Err(Error::BufferTooShort {
364 need: REQUIRED_AF_LEN,
365 have: af_len,
366 what: "set_pcr: adaptation field too short for flags byte + PCR",
367 });
368 }
369 // Byte 5: adaptation field flags byte (AF_PCR_FLAG = 0x10, §2.4.3.4).
370 if packet[5] & AF_PCR_FLAG == 0 {
371 return Err(Error::BufferTooShort {
372 need: 6,
373 have: 0,
374 what: "set_pcr: PCR flag not set in adaptation field",
375 });
376 }
377 // PCR occupies the 6 bytes starting at offset 6 (after header + af_len byte + flags byte).
378 let pcr_start = 6usize;
379 let pcr_end = pcr_start + PCR_FIELD_LEN;
380 packet[pcr_start..pcr_end].copy_from_slice(&pcr.to_field_bytes());
381 Ok(())
382 }
383
384 /// Decode the adaptation field from this packet, if present.
385 ///
386 /// Returns `None` when no adaptation field is present, and
387 /// `Some(Err(..))` when the adaptation field bytes are malformed.
388 /// The returned [`AdaptationField`] borrows from `self.raw`.
389 pub fn adaptation_field(&self) -> Option<crate::Result<AdaptationField<'_>>> {
390 if self.raw[3] & ADAPTATION_FLAG == 0 {
391 return None;
392 }
393 let af_len = self.raw[4] as usize;
394 if af_len == 0 || 5 + af_len > TS_PACKET_SIZE {
395 return None;
396 }
397 Some(AdaptationField::parse(&self.raw[5..5 + af_len]))
398 }
399}
400
401#[cfg(test)]
402mod tests {
403 use super::*;
404
405 /// The getters decode the header bytes literally (H.222.0 §2.4.3.2): a
406 /// hand-built header 0x47 | TEI=1 PUSI=1 prio=0 PID=0x1ABC | scr=0b10
407 /// afc=0b01 cc=0xC.
408 #[test]
409 fn getters_report_the_raw_header_fields() {
410 let mut raw = [0xFFu8; TS_PACKET_SIZE];
411 raw[0] = TS_SYNC_BYTE;
412 raw[1] = 0b1101_1010; // TEI=1, PUSI=1, priority=0, PID[12:8]=0b11010
413 raw[2] = 0xBC;
414 raw[3] = 0b1001_1100; // scrambling=0b10, afc=0b01 (payload only), cc=0xC
415 let pkt = OwnedTsPacket::parse(raw).unwrap();
416 assert!(pkt.tei());
417 assert!(pkt.pusi());
418 assert_eq!(pkt.pid(), 0x1ABC);
419 assert_eq!(pkt.scrambling(), 0b10);
420 assert!(!pkt.has_adaptation());
421 assert!(pkt.has_payload());
422 assert_eq!(pkt.continuity_counter(), 0xC);
423 assert_eq!(pkt.raw(), &raw);
424 assert_eq!(pkt.into_raw(), raw);
425 }
426
427 #[test]
428 fn owned_round_trip_and_payload_mut() {
429 let payload = [0xAAu8; 184];
430 let mut pkt = OwnedTsPacket::parse(
431 OwnedTsPacket::serialize_with_payload(0x0100, true, 7, &payload).unwrap(),
432 )
433 .unwrap();
434 assert_eq!(pkt.pid(), 0x0100);
435 assert!(pkt.pusi);
436 assert_eq!(pkt.continuity_counter, 7);
437 assert_eq!(pkt.payload().unwrap()[..184], payload[..]);
438 pkt.payload_mut().unwrap()[0] = 0x55;
439 assert_eq!(pkt.payload().unwrap()[0], 0x55);
440 // discontinuity defaults to false
441 assert!(!pkt.discontinuity);
442 }
443
444 /// W9 (#1129): `serialize_with_payload` used to silently truncate a
445 /// payload over 184 bytes (`payload.len().min(184)`) instead of
446 /// erroring, dropping data with no signal.
447 #[test]
448 fn oversized_payload_is_rejected_not_truncated() {
449 let payload = [0xAAu8; 185];
450 assert!(OwnedTsPacket::serialize_with_payload(0x0100, true, 0, &payload).is_err());
451 }
452
453 /// The boundary: exactly 184 bytes (the fixed payload capacity) still
454 /// serializes and round-trips.
455 #[test]
456 fn max_payload_len_round_trips() {
457 let payload = [0xBBu8; OwnedTsPacket::MAX_PAYLOAD_LEN];
458 let raw = OwnedTsPacket::serialize_with_payload(0x0100, true, 0, &payload).unwrap();
459 let pkt = OwnedTsPacket::parse(raw).unwrap();
460 assert_eq!(pkt.payload().unwrap(), &payload[..]);
461 }
462
463 #[test]
464 fn owned_scrambling_control_accessor() {
465 let make = |scrambling_bits: u8| -> OwnedTsPacket {
466 let mut raw = OwnedTsPacket::serialize_with_payload(0x0100, false, 0, &[]).unwrap();
467 // byte 3 bits [7:6] = scrambling
468 raw[3] = (raw[3] & 0x3F) | (scrambling_bits << 6);
469 OwnedTsPacket::parse(raw).unwrap()
470 };
471 assert_eq!(
472 make(0b00).scrambling_control(),
473 ScramblingControl::NotScrambled
474 );
475 assert_eq!(make(0b01).scrambling_control(), ScramblingControl::Reserved);
476 assert_eq!(make(0b10).scrambling_control(), ScramblingControl::EvenKey);
477 assert_eq!(make(0b11).scrambling_control(), ScramblingControl::OddKey);
478 }
479
480 #[test]
481 fn owned_adaptation_field_control_accessor() {
482 let make = |afc_bits: u8| -> OwnedTsPacket {
483 let mut raw = [0xFFu8; TS_PACKET_SIZE];
484 raw[0] = TS_SYNC_BYTE;
485 raw[1] = 0x00;
486 raw[2] = 0x00;
487 raw[3] = (afc_bits << 4) & 0x30;
488 if afc_bits & 0b10 != 0 {
489 raw[4] = 0; // adaptation_field_length = 0
490 }
491 OwnedTsPacket::parse(raw).unwrap()
492 };
493 assert_eq!(
494 make(0b00).adaptation_field_control(),
495 AdaptationFieldControl::Reserved
496 );
497 assert_eq!(
498 make(0b01).adaptation_field_control(),
499 AdaptationFieldControl::PayloadOnly
500 );
501 assert_eq!(
502 make(0b10).adaptation_field_control(),
503 AdaptationFieldControl::AdaptationOnly
504 );
505 assert_eq!(
506 make(0b11).adaptation_field_control(),
507 AdaptationFieldControl::AdaptationAndPayload
508 );
509 }
510
511 /// W7 (#1074): `set_pcr` only checked `af_len >= 1` (room for the flags
512 /// byte), not `af_len >= 1 + PCR_FIELD_LEN` (room for the PCR itself). A
513 /// malformed adaptation field with `af_len` between 1 and 6 but the PCR
514 /// flag set anyway let `set_pcr` write its fixed 6-byte PCR field 6 bytes
515 /// past the header regardless — spilling into whatever follows the
516 /// (too-short) declared adaptation field, i.e. the payload.
517 #[test]
518 fn set_pcr_rejects_adaptation_field_too_short_for_pcr() {
519 let mut raw = [0xFFu8; TS_PACKET_SIZE];
520 raw[0] = TS_SYNC_BYTE;
521 raw[1] = 0x00;
522 raw[2] = 0x00;
523 raw[3] = ADAPTATION_FLAG | crate::ts::PAYLOAD_FLAG;
524 raw[4] = 1; // adaptation_field_length: only room for the flags byte
525 raw[5] = AF_PCR_FLAG; // PCR flag set anyway (malformed: no room for PCR)
526 // raw[6..] is payload (0xFF stuffing here).
527 let payload_before = raw[6..].to_vec();
528
529 let pcr = Pcr {
530 base: 10_000,
531 extension: 0,
532 };
533 let err = OwnedTsPacket::set_pcr(&mut raw, pcr).unwrap_err();
534 assert!(matches!(err, Error::BufferTooShort { .. }));
535 assert_eq!(
536 &raw[6..],
537 payload_before.as_slice(),
538 "payload must be untouched"
539 );
540 }
541}