Skip to main content

mpeg_ts/
reader.rs

1//! Streaming TS packet framing over any [`std::io::Read`].
2//!
3//! [`PacketReader`] turns a byte stream into its 188-byte transport-stream
4//! packets, resynchronising through [`TsResync`] as
5//! the stream arrives, so a multi-gigabyte capture is framed in bounded
6//! memory instead of being read whole.
7//!
8//! ```no_run
9//! use std::fs::File;
10//! use std::num::NonZeroUsize;
11//! use mpeg_ts::reader::PacketReader;
12//! use mpeg_ts::resync::{PacketStride, ResyncConfig, Unlocked};
13//!
14//! let mut packets = PacketReader::new(File::open("capture.ts")?, NonZeroUsize::new(1 << 20).unwrap(), ResyncConfig::new(NonZeroUsize::new(5).unwrap(), &PacketStride::ALL, Unlocked::KeepWindow));
15//! while let Some(packet) = packets.next() {
16//!     let packet = packet?;
17//!     // one aligned 188-byte TS packet
18//!     let _ = packet.len();
19//! }
20//! # Ok::<(), Box<dyn std::error::Error>>(())
21//! ```
22
23use core::num::NonZeroUsize;
24use std::io::{self, Read};
25
26use alloc::vec::Vec;
27
28use crate::resync::{ResyncConfig, ResyncStats, TsResync};
29use crate::ts::TS_PACKET_SIZE;
30
31/// The aligned 188-byte packets of a byte stream, read in bounded chunks.
32///
33/// A capture that begins mid-packet, carries a corrupted sync byte, or is
34/// 204-byte RS-coded is resynchronised rather than rejected. A read error ends
35/// the iteration and is returned once; a short trailing packet is dropped, as
36/// [`TsResync::finish`](crate::resync::TsResync::finish) reports it as a loss.
37pub struct PacketReader<R> {
38    reader: R,
39    resync: TsResync,
40    chunk: Vec<u8>,
41    pending: alloc::vec::IntoIter<[u8; TS_PACKET_SIZE]>,
42    done: bool,
43}
44
45impl<R: Read> PacketReader<R> {
46    /// Frame the packets of `reader`, reading `chunk_len` bytes at a time:
47    /// the caller's trade between syscall cost and memory, which stays at
48    /// `chunk_len` however long the input is. `resync` says how the stream
49    /// locks.
50    pub fn new(reader: R, chunk_len: NonZeroUsize, resync: ResyncConfig) -> Self {
51        Self {
52            reader,
53            resync: TsResync::new(resync),
54            chunk: alloc::vec![0u8; chunk_len.get()],
55            pending: Vec::new().into_iter(),
56            done: false,
57        }
58    }
59
60    /// The resynchroniser's counters so far: packets framed, sync losses and
61    /// bytes dropped. Each discarded span is counted here as it happens, so
62    /// the reader keeps no per-loss list.
63    #[must_use]
64    pub fn resync_stats(&self) -> ResyncStats {
65        self.resync.stats()
66    }
67
68    /// One `read`, retried on [`io::ErrorKind::Interrupted`].
69    fn read_chunk(&mut self) -> io::Result<usize> {
70        loop {
71            match self.reader.read(&mut self.chunk) {
72                Err(e) if e.kind() == io::ErrorKind::Interrupted => continue,
73                other => return other,
74            }
75        }
76    }
77}
78
79impl<R: Read> Iterator for PacketReader<R> {
80    type Item = io::Result<[u8; TS_PACKET_SIZE]>;
81
82    fn next(&mut self) -> Option<Self::Item> {
83        loop {
84            if let Some(packet) = self.pending.next() {
85                return Some(Ok(packet));
86            }
87            if self.done {
88                return None;
89            }
90            match self.read_chunk() {
91                Ok(0) => {
92                    self.resync.finish();
93                    drop(self.resync.take_losses());
94                    self.pending = self.resync.take_tail_packets().into_iter();
95                    self.done = true;
96                }
97                Ok(read) => {
98                    self.pending = self.resync.feed(&self.chunk[..read]).into_iter();
99                    drop(self.resync.take_losses());
100                }
101                Err(e) => {
102                    self.done = true;
103                    return Some(Err(e));
104                }
105            }
106        }
107    }
108}
109
110#[cfg(test)]
111mod tests {
112    use super::*;
113
114    const CHUNK: NonZeroUsize = NonZeroUsize::MIN.saturating_add(4095);
115
116    fn resync_config() -> ResyncConfig {
117        ResyncConfig::new(
118            NonZeroUsize::MIN.saturating_add(crate::resync::LOCK_CONFIRMATIONS - 1),
119            &crate::resync::PacketStride::ALL,
120            crate::resync::Unlocked::KeepWindow,
121        )
122    }
123
124    /// A source that hands out its bytes `step` at a time, so a packet
125    /// boundary can fall anywhere.
126    struct Chunked {
127        data: Vec<u8>,
128        offset: usize,
129        step: usize,
130    }
131
132    impl Read for Chunked {
133        fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> {
134            let remaining = self.data.len() - self.offset;
135            let count = remaining.min(buf.len()).min(self.step);
136            buf[..count].copy_from_slice(&self.data[self.offset..self.offset + count]);
137            self.offset += count;
138            Ok(count)
139        }
140    }
141
142    fn packet(fill: u8) -> [u8; TS_PACKET_SIZE] {
143        let mut packet = [fill; TS_PACKET_SIZE];
144        packet[0] = crate::ts::TS_SYNC_BYTE;
145        packet
146    }
147
148    /// Every packet is yielded whatever the read boundaries are, and a
149    /// trailing partial packet is dropped.
150    #[test]
151    fn packets_survive_any_chunk_boundary() {
152        let mut data = Vec::new();
153        for fill in 0u8..8 {
154            data.extend_from_slice(&packet(fill));
155        }
156        data.extend_from_slice(&[0x47, 0x00, 0x00]);
157        let expected: Vec<[u8; TS_PACKET_SIZE]> = (0u8..8).map(packet).collect();
158
159        for step in [1usize, 7, 188, 500] {
160            let reader = Chunked {
161                data: data.clone(),
162                offset: 0,
163                step,
164            };
165            let mut seen = Vec::new();
166            for result in PacketReader::new(reader, CHUNK, resync_config()) {
167                seen.push(result.expect("an in-memory source cannot fail"));
168            }
169            assert_eq!(seen, expected, "step {step}");
170        }
171    }
172
173    /// A capture that begins mid-packet still yields whole packets.
174    #[test]
175    fn a_mid_packet_start_is_resynchronised() {
176        let mut data = alloc::vec![0x00u8; 7];
177        for fill in 1u8..8 {
178            data.extend_from_slice(&packet(fill));
179        }
180        let reader = Chunked {
181            data,
182            offset: 0,
183            step: 64,
184        };
185        let mut seen = Vec::new();
186        for result in PacketReader::new(reader, CHUNK, resync_config()) {
187            seen.push(result.expect("an in-memory source cannot fail"));
188        }
189        let expected: Vec<[u8; TS_PACKET_SIZE]> = (1u8..8).map(packet).collect();
190        assert_eq!(seen, expected);
191    }
192
193    /// The read size is the caller's: no read asks for more than it.
194    #[test]
195    fn reads_are_at_most_the_callers_chunk_length() {
196        struct Spy(usize, usize);
197        impl Read for Spy {
198            fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> {
199                self.1 = self.1.max(buf.len());
200                let count = buf.len().min(self.0);
201                buf[..count].fill(0);
202                self.0 -= count;
203                Ok(count)
204            }
205        }
206        let mut reader = PacketReader::new(
207            Spy(10_000, 0),
208            NonZeroUsize::MIN.saturating_add(255),
209            resync_config(),
210        );
211        while reader.next().is_some() {}
212        assert_eq!(reader.reader.1, 256);
213    }
214
215    /// A lossy input leaves no per-loss list behind: the reader drains the
216    /// resynchroniser's losses itself and keeps only the counters.
217    #[test]
218    fn a_lossy_input_does_not_accumulate_loss_records() {
219        let mut data = Vec::new();
220        for tag in 1u8..=200 {
221            let mut p = packet(tag);
222            if tag % 20 == 0 {
223                p[0] = 0x00;
224            }
225            data.extend_from_slice(&p);
226        }
227        let reader = Chunked {
228            data,
229            offset: 0,
230            step: 500,
231        };
232        let mut packets = PacketReader::new(reader, CHUNK, resync_config());
233        for _ in 0..150 {
234            assert!(packets.next().is_some());
235        }
236        assert!(packets.resync.take_losses().is_empty());
237        assert!(packets.resync_stats().resyncs > 3, "the input was lossy");
238    }
239}