mpeg-ts 0.11.0

MPEG-2 Transport Stream framing (ITU-T H.222.0 / ISO/IEC 13818-1): TS packet, adaptation field, PCR, PSI section reassembly + packetisation, resync. no_std.
Documentation
//! Streaming TS packet framing over any [`std::io::Read`].
//!
//! [`PacketReader`] turns a byte stream into its 188-byte transport-stream
//! packets, resynchronising through [`TsResync`] as
//! the stream arrives, so a multi-gigabyte capture is framed in bounded
//! memory instead of being read whole.
//!
//! ```no_run
//! use std::fs::File;
//! use std::num::NonZeroUsize;
//! use mpeg_ts::reader::PacketReader;
//! use mpeg_ts::resync::{PacketStride, ResyncConfig, Unlocked};
//!
//! let mut packets = PacketReader::new(File::open("capture.ts")?, NonZeroUsize::new(1 << 20).unwrap(), ResyncConfig::new(NonZeroUsize::new(5).unwrap(), &PacketStride::ALL, Unlocked::KeepWindow));
//! while let Some(packet) = packets.next() {
//!     let packet = packet?;
//!     // one aligned 188-byte TS packet
//!     let _ = packet.len();
//! }
//! # Ok::<(), Box<dyn std::error::Error>>(())
//! ```

use core::num::NonZeroUsize;
use std::io::{self, Read};

use alloc::vec::Vec;

use crate::resync::{ResyncConfig, ResyncStats, TsResync};
use crate::ts::TS_PACKET_SIZE;

/// The aligned 188-byte packets of a byte stream, read in bounded chunks.
///
/// A capture that begins mid-packet, carries a corrupted sync byte, or is
/// 204-byte RS-coded is resynchronised rather than rejected. A read error ends
/// the iteration and is returned once; a short trailing packet is dropped, as
/// [`TsResync::finish`](crate::resync::TsResync::finish) reports it as a loss.
pub struct PacketReader<R> {
    reader: R,
    resync: TsResync,
    chunk: Vec<u8>,
    pending: alloc::vec::IntoIter<[u8; TS_PACKET_SIZE]>,
    done: bool,
}

impl<R: Read> PacketReader<R> {
    /// Frame the packets of `reader`, reading `chunk_len` bytes at a time:
    /// the caller's trade between syscall cost and memory, which stays at
    /// `chunk_len` however long the input is. `resync` says how the stream
    /// locks.
    pub fn new(reader: R, chunk_len: NonZeroUsize, resync: ResyncConfig) -> Self {
        Self {
            reader,
            resync: TsResync::new(resync),
            chunk: alloc::vec![0u8; chunk_len.get()],
            pending: Vec::new().into_iter(),
            done: false,
        }
    }

    /// The resynchroniser's counters so far: packets framed, sync losses and
    /// bytes dropped. Each discarded span is counted here as it happens, so
    /// the reader keeps no per-loss list.
    #[must_use]
    pub fn resync_stats(&self) -> ResyncStats {
        self.resync.stats()
    }

    /// One `read`, retried on [`io::ErrorKind::Interrupted`].
    fn read_chunk(&mut self) -> io::Result<usize> {
        loop {
            match self.reader.read(&mut self.chunk) {
                Err(e) if e.kind() == io::ErrorKind::Interrupted => continue,
                other => return other,
            }
        }
    }
}

impl<R: Read> Iterator for PacketReader<R> {
    type Item = io::Result<[u8; TS_PACKET_SIZE]>;

    fn next(&mut self) -> Option<Self::Item> {
        loop {
            if let Some(packet) = self.pending.next() {
                return Some(Ok(packet));
            }
            if self.done {
                return None;
            }
            match self.read_chunk() {
                Ok(0) => {
                    self.resync.finish();
                    drop(self.resync.take_losses());
                    self.pending = self.resync.take_tail_packets().into_iter();
                    self.done = true;
                }
                Ok(read) => {
                    self.pending = self.resync.feed(&self.chunk[..read]).into_iter();
                    drop(self.resync.take_losses());
                }
                Err(e) => {
                    self.done = true;
                    return Some(Err(e));
                }
            }
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    const CHUNK: NonZeroUsize = NonZeroUsize::MIN.saturating_add(4095);

    fn resync_config() -> ResyncConfig {
        ResyncConfig::new(
            NonZeroUsize::MIN.saturating_add(crate::resync::LOCK_CONFIRMATIONS - 1),
            &crate::resync::PacketStride::ALL,
            crate::resync::Unlocked::KeepWindow,
        )
    }

    /// A source that hands out its bytes `step` at a time, so a packet
    /// boundary can fall anywhere.
    struct Chunked {
        data: Vec<u8>,
        offset: usize,
        step: usize,
    }

    impl Read for Chunked {
        fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> {
            let remaining = self.data.len() - self.offset;
            let count = remaining.min(buf.len()).min(self.step);
            buf[..count].copy_from_slice(&self.data[self.offset..self.offset + count]);
            self.offset += count;
            Ok(count)
        }
    }

    fn packet(fill: u8) -> [u8; TS_PACKET_SIZE] {
        let mut packet = [fill; TS_PACKET_SIZE];
        packet[0] = crate::ts::TS_SYNC_BYTE;
        packet
    }

    /// Every packet is yielded whatever the read boundaries are, and a
    /// trailing partial packet is dropped.
    #[test]
    fn packets_survive_any_chunk_boundary() {
        let mut data = Vec::new();
        for fill in 0u8..8 {
            data.extend_from_slice(&packet(fill));
        }
        data.extend_from_slice(&[0x47, 0x00, 0x00]);
        let expected: Vec<[u8; TS_PACKET_SIZE]> = (0u8..8).map(packet).collect();

        for step in [1usize, 7, 188, 500] {
            let reader = Chunked {
                data: data.clone(),
                offset: 0,
                step,
            };
            let mut seen = Vec::new();
            for result in PacketReader::new(reader, CHUNK, resync_config()) {
                seen.push(result.expect("an in-memory source cannot fail"));
            }
            assert_eq!(seen, expected, "step {step}");
        }
    }

    /// A capture that begins mid-packet still yields whole packets.
    #[test]
    fn a_mid_packet_start_is_resynchronised() {
        let mut data = alloc::vec![0x00u8; 7];
        for fill in 1u8..8 {
            data.extend_from_slice(&packet(fill));
        }
        let reader = Chunked {
            data,
            offset: 0,
            step: 64,
        };
        let mut seen = Vec::new();
        for result in PacketReader::new(reader, CHUNK, resync_config()) {
            seen.push(result.expect("an in-memory source cannot fail"));
        }
        let expected: Vec<[u8; TS_PACKET_SIZE]> = (1u8..8).map(packet).collect();
        assert_eq!(seen, expected);
    }

    /// The read size is the caller's: no read asks for more than it.
    #[test]
    fn reads_are_at_most_the_callers_chunk_length() {
        struct Spy(usize, usize);
        impl Read for Spy {
            fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> {
                self.1 = self.1.max(buf.len());
                let count = buf.len().min(self.0);
                buf[..count].fill(0);
                self.0 -= count;
                Ok(count)
            }
        }
        let mut reader = PacketReader::new(
            Spy(10_000, 0),
            NonZeroUsize::MIN.saturating_add(255),
            resync_config(),
        );
        while reader.next().is_some() {}
        assert_eq!(reader.reader.1, 256);
    }

    /// A lossy input leaves no per-loss list behind: the reader drains the
    /// resynchroniser's losses itself and keeps only the counters.
    #[test]
    fn a_lossy_input_does_not_accumulate_loss_records() {
        let mut data = Vec::new();
        for tag in 1u8..=200 {
            let mut p = packet(tag);
            if tag % 20 == 0 {
                p[0] = 0x00;
            }
            data.extend_from_slice(&p);
        }
        let reader = Chunked {
            data,
            offset: 0,
            step: 500,
        };
        let mut packets = PacketReader::new(reader, CHUNK, resync_config());
        for _ in 0..150 {
            assert!(packets.next().is_some());
        }
        assert!(packets.resync.take_losses().is_empty());
        assert!(packets.resync_stats().resyncs > 3, "the input was lossy");
    }
}