Skip to main content

mpeg_ts/
resync.rs

1//! Stateful TS byte-stream resynchroniser — ITU-T H.222.0 §2.4.3.2 (= ISO/IEC 13818-1 §2.4.3.2).
2//!
3//! Recovers 188-byte MPEG-TS packet alignment from an arbitrary byte stream
4//! (file reads, UDP payloads) that may start mid-packet or contain leading
5//! garbage.  Also detects 204-byte Reed-Solomon-coded packets (DVB RS-coded
6//! outer forward-error-correction layer) and strips the 16 parity bytes, and
7//! 192-byte M2TS (BDAV) source packets and strips their 4-byte
8//! `TP_extra_header`, yielding standard 188-byte TS packets in every case.
9//!
10//! # Feature gate
11//!
12//! This module is only compiled when the `ts` feature is enabled (the
13//! default), because it depends on the TS constants in [`crate::ts`].
14//!
15//! # Example
16//!
17//! ```
18//! use mpeg_ts::resync::TsResync;
19//!
20//! let mut r = TsResync::new();
21//! // Feed arbitrary bytes (file chunks, UDP datagrams, etc.).
22//! let packets: Vec<[u8; 188]> = r.feed(b"some raw bytes");
23//! let stats = r.stats();
24//! ```
25
26use alloc::vec::Vec;
27
28use crate::ts::{TS_PACKET_SIZE, TS_SYNC_BYTE};
29
30/// Reed-Solomon-coded TS packet size: 188-byte payload + 16 parity bytes
31/// (DVB RS outer FEC, ISO/IEC 13818-1 §2.4.3.2 informative note).
32pub const RS_PACKET_SIZE: usize = 204;
33
34/// Number of Reed-Solomon parity bytes appended to a 204-byte packet.
35pub const RS_PARITY_LEN: usize = RS_PACKET_SIZE - TS_PACKET_SIZE;
36
37/// M2TS (BDAV) source packet size: a 4-byte `TP_extra_header`
38/// (copy-permission indicator + arrival time stamp) followed by a 188-byte TS
39/// packet.
40pub const M2TS_PACKET_SIZE: usize = 192;
41
42/// Length of the `TP_extra_header` that precedes each TS packet in M2TS.
43pub const M2TS_EXTRA_HEADER_LEN: usize = M2TS_PACKET_SIZE - TS_PACKET_SIZE;
44
45/// Consecutive sync bytes at the candidate stride required to declare lock.
46pub const LOCK_CONFIRMATIONS: usize = 5;
47
48/// Detected packet size after locking.
49#[non_exhaustive]
50#[derive(Debug, Clone, Copy, PartialEq, Eq)]
51#[cfg_attr(feature = "serde", derive(serde::Serialize))]
52pub enum PacketStride {
53    /// Standard 188-byte TS packets (ISO/IEC 13818-1 §2.4.3.2).
54    Ts188,
55    /// 204-byte packets (188-byte TS + 16 Reed-Solomon parity bytes).
56    Rs204,
57    /// 192-byte M2TS (BDAV) source packets (4-byte `TP_extra_header` +
58    /// 188-byte TS).
59    M2ts192,
60}
61
62impl PacketStride {
63    /// Short machine-readable label for this stride.
64    pub fn name(&self) -> &'static str {
65        match self {
66            PacketStride::Ts188 => "ts_188",
67            PacketStride::Rs204 => "rs_204",
68            PacketStride::M2ts192 => "m2ts_192",
69        }
70    }
71
72    /// Bytes from one sync byte to the next at this stride.
73    pub fn packet_len(&self) -> usize {
74        match self {
75            PacketStride::Ts188 => TS_PACKET_SIZE,
76            PacketStride::Rs204 => RS_PACKET_SIZE,
77            PacketStride::M2ts192 => M2TS_PACKET_SIZE,
78        }
79    }
80}
81
82broadcast_common::impl_spec_display!(PacketStride);
83
84/// Counters accumulated during resynchronisation.
85#[non_exhaustive]
86#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
87#[cfg_attr(feature = "serde", derive(serde::Serialize))]
88pub struct ResyncStats {
89    /// Total 188-byte TS packets emitted.
90    pub packets: u64,
91    /// Times sync was lost and reacquired.
92    pub resyncs: u64,
93    /// Bytes skipped/dropped (junk before lock + sync-loss bytes).
94    pub dropped_bytes: u64,
95}
96
97/// One span of bytes the resynchroniser discarded: either the bytes before
98/// the first lock (a capture that starts mid-packet or on garbage), a
99/// mid-stream sync loss, or a truncated trailing packet.
100///
101/// Drained with [`TsResync::take_losses`]; one entry per discarded span, so a
102/// caller can report each skipped unit exactly once, and the spans account for
103/// every byte in [`ResyncStats::dropped_bytes`].
104#[non_exhaustive]
105#[derive(Debug, Clone, Copy, PartialEq, Eq)]
106#[cfg_attr(feature = "serde", derive(serde::Serialize))]
107pub struct ResyncLoss {
108    /// Byte offset, from the first byte ever fed, where the discarded span starts.
109    pub offset: u64,
110    /// Length of the discarded span in bytes.
111    pub dropped_bytes: u64,
112    /// Number of whole packets emitted before this loss, i.e. the index the
113    /// next intact packet will carry.
114    pub packet_index: u64,
115    /// `true` when the span is a truncated trailing packet found by
116    /// [`TsResync::finish`] rather than a sync loss in mid-stream.
117    pub truncated_tail: bool,
118}
119
120/// Stateful TS byte-stream resynchroniser (ISO/IEC 13818-1 §2.4.3.2).
121///
122/// Recovers 188-byte MPEG-TS packet alignment from an arbitrary byte stream
123/// that may start mid-packet or contain junk, and detects 204-byte
124/// Reed-Solomon-coded packets (stripping the 16 parity bytes) and 192-byte
125/// M2TS source packets (stripping the 4-byte `TP_extra_header`).
126///
127/// Feed raw bytes with [`feed`](Self::feed); each call returns a `Vec` of
128/// aligned 188-byte TS packets.  Bytes are buffered across calls so that
129/// packet boundaries may span call boundaries freely.
130///
131/// Lock is declared after [`LOCK_CONFIRMATIONS`] consecutive sync bytes are
132/// found at the candidate stride (188, 192 or 204).  On sync loss the resynchroniser
133/// re-scans from the byte after the lost position.
134///
135/// Every discarded byte is reported as a [`ResyncLoss`], including the bytes
136/// before the first lock: a caller that never sees a loss event therefore
137/// never silently dropped input.
138///
139/// # Stats
140///
141/// [`stats`](Self::stats) returns cumulative counters (packets emitted,
142/// resyncs, dropped bytes).
143#[derive(Debug, Default)]
144pub struct TsResync {
145    buf: Vec<u8>,
146    /// Logical read head into `buf`; compacted periodically.
147    head: usize,
148    stride: Option<PacketStride>,
149    stats: ResyncStats,
150    /// Bytes already compacted away (stream offset of `buf[0]`).
151    consumed: u64,
152    /// Stream offset where the currently open sync loss began.
153    open_loss: Option<u64>,
154    /// Closed losses not yet drained by [`take_losses`](Self::take_losses).
155    losses: Vec<ResyncLoss>,
156    /// Aligned packets recovered by [`finish`](Self::finish), not yet drained
157    /// by [`take_tail_packets`](Self::take_tail_packets).
158    tail: Vec<[u8; TS_PACKET_SIZE]>,
159    /// Bytes of the current stride still to skip after a packet emitted
160    /// before its stride's trailing bytes arrived (M2TS: the next packet's
161    /// `TP_extra_header`).
162    skip: usize,
163}
164
165impl TsResync {
166    /// Create a new resynchroniser with an empty internal buffer.
167    pub fn new() -> Self {
168        Self::default()
169    }
170
171    /// Feed `data` and emit every newly-aligned 188-byte TS packet.
172    ///
173    /// For a 204-byte stream the 16 Reed-Solomon parity bytes are stripped,
174    /// and for a 192-byte M2TS stream the 4-byte `TP_extra_header`; only the
175    /// 188-byte TS packet is returned.  Bytes that cannot yet form
176    /// a complete packet (or fall before lock) are buffered for the next call.
177    ///
178    /// **Drain [`take_losses`](Self::take_losses).** Every span discarded after
179    /// lock is appended to an internal list (about 32-40 bytes each) that only
180    /// `take_losses` empties; a caller that feeds forever and never drains it
181    /// grows memory linearly with the number of re-locks on a lossy input.
182    pub fn feed(&mut self, data: &[u8]) -> Vec<[u8; TS_PACKET_SIZE]> {
183        let mut emitted = Vec::new();
184        self.feed_into(data, &mut emitted);
185        emitted
186    }
187
188    /// [`feed`](Self::feed) appending to a caller-owned `out` (not cleared),
189    /// so a steady-state caller that reuses one `Vec` allocates nothing per
190    /// call (audit r01-O4). The output capacity is reserved once from the
191    /// buffered byte count instead of growing by doubling.
192    ///
193    /// Returns the number of packets appended.
194    pub fn feed_into(&mut self, data: &[u8], emitted: &mut Vec<[u8; TS_PACKET_SIZE]>) -> usize {
195        self.buf.extend_from_slice(data);
196        let before = emitted.len();
197        emitted.reserve((self.buf.len() - self.head) / TS_PACKET_SIZE);
198
199        loop {
200            match self.stride {
201                None => {
202                    if let Some((offset, s)) = find_sync(&self.buf[self.head..]) {
203                        self.lock(offset, s);
204                    } else {
205                        // Keep at most enough bytes to detect a future lock.
206                        let keep = LOCK_CONFIRMATIONS * RS_PACKET_SIZE;
207                        let tail_len = self.buf.len() - self.head;
208                        if tail_len > keep {
209                            let excess = tail_len - keep;
210                            self.stats.dropped_bytes += excess as u64;
211                            self.head += excess;
212                        }
213                        self.compact();
214                        return emitted.len() - before;
215                    }
216                }
217                Some(stride) => {
218                    let s = stride.packet_len();
219                    let tail_len = self.buf.len() - self.head;
220                    if self.skip > 0 {
221                        let n = self.skip.min(tail_len);
222                        self.head += n;
223                        self.skip -= n;
224                        if self.skip > 0 {
225                            self.compact();
226                            return emitted.len() - before;
227                        }
228                        continue;
229                    }
230                    if tail_len < emit_len(stride) {
231                        self.compact();
232                        return emitted.len() - before;
233                    }
234                    if self.buf[self.head] == TS_SYNC_BYTE {
235                        let mut packet = [0u8; TS_PACKET_SIZE];
236                        packet.copy_from_slice(&self.buf[self.head..self.head + TS_PACKET_SIZE]);
237                        emitted.push(packet);
238                        let advance = s.min(tail_len);
239                        self.head += advance;
240                        self.skip = s - advance;
241                        self.stats.packets += 1;
242                    } else {
243                        // Sync byte missing — record the loss and re-scan.
244                        self.stats.resyncs += 1;
245                        self.stats.dropped_bytes += 1;
246                        self.open_loss
247                            .get_or_insert(self.consumed + self.head as u64);
248                        self.head += 1;
249                        self.stride = None;
250                    }
251                }
252            }
253        }
254    }
255
256    /// Detected packet stride, or [`None`] before the stream has locked.
257    pub fn stride(&self) -> Option<PacketStride> {
258        self.stride
259    }
260
261    /// Drain the sync losses recorded since the last call (see [`ResyncLoss`]).
262    ///
263    /// This is the only thing that empties the internal loss list, which is
264    /// unbounded by design (dropping a loss would hide data loss): call it
265    /// regularly — e.g. after every [`feed`](Self::feed) — or the list grows
266    /// with every re-lock on a lossy input. If you do not need the losses,
267    /// still call it and discard the result.
268    pub fn take_losses(&mut self) -> Vec<ResyncLoss> {
269        core::mem::take(&mut self.losses)
270    }
271
272    fn lock(&mut self, offset: usize, stride: PacketStride) {
273        self.open_loss
274            .get_or_insert(self.consumed + self.head as u64);
275        self.head += offset;
276        self.stride = Some(stride);
277        if let Some(start) = self.open_loss.take() {
278            let end = self.consumed + self.head as u64;
279            if end > start {
280                self.stats.dropped_bytes += end - start;
281                self.losses.push(ResyncLoss {
282                    offset: start,
283                    dropped_bytes: end - start,
284                    packet_index: self.stats.packets,
285                    truncated_tail: false,
286                });
287            }
288        }
289    }
290
291    /// Declare end of input. Packets that were still waiting for a full
292    /// [`LOCK_CONFIRMATIONS`] window cannot be confirmed by more bytes, so the
293    /// aligned packets that fill the rest of the input (a stream shorter than
294    /// the window included) are kept; drain them with
295    /// [`take_tail_packets`](Self::take_tail_packets), like
296    /// [`take_losses`](Self::take_losses) for the losses.
297    ///
298    /// Also closes a sync loss that never re-locked and records a truncated
299    /// trailing packet, both retrievable with
300    /// [`take_losses`](Self::take_losses). The buffer is discarded.
301    pub fn finish(&mut self) {
302        if self.stride.is_none()
303            && let Some((offset, s)) = find_tail_sync(&self.buf[self.head..])
304        {
305            self.lock(offset, s);
306            let mut emitted = core::mem::take(&mut self.tail);
307            self.feed_into(&[], &mut emitted);
308            self.tail = emitted;
309        }
310        let end = self.consumed + self.buf.len() as u64;
311        if let Some(start) = self.open_loss.take() {
312            self.losses.push(ResyncLoss {
313                offset: start,
314                dropped_bytes: end - start,
315                packet_index: self.stats.packets,
316                truncated_tail: false,
317            });
318        } else if self.stride.is_some() && self.head < self.buf.len() {
319            self.losses.push(ResyncLoss {
320                offset: self.consumed + self.head as u64,
321                dropped_bytes: (self.buf.len() - self.head) as u64,
322                packet_index: self.stats.packets,
323                truncated_tail: true,
324            });
325        }
326        self.stats.dropped_bytes += (self.buf.len() - self.head) as u64;
327        self.head = self.buf.len();
328        self.compact();
329    }
330
331    /// Drain the aligned packets [`finish`](Self::finish) recovered at end of
332    /// input. Call it after `finish` and process the result like the output
333    /// of [`feed`](Self::feed).
334    pub fn take_tail_packets(&mut self) -> Vec<[u8; TS_PACKET_SIZE]> {
335        core::mem::take(&mut self.tail)
336    }
337
338    /// Accumulated statistics.
339    pub fn stats(&self) -> ResyncStats {
340        self.stats
341    }
342
343    /// Compact the internal buffer by discarding consumed bytes.
344    fn compact(&mut self) {
345        if self.head > 0 {
346            self.consumed += self.head as u64;
347            self.buf.drain(..self.head);
348            self.head = 0;
349        }
350    }
351}
352
353/// Scan `buf` for the smallest offset `o` such that stride `S` (tried 188
354/// first, then 192, then 204) yields [`LOCK_CONFIRMATIONS`] consecutive sync bytes at
355/// positions `o + k*S` for `k = 0 .. LOCK_CONFIRMATIONS`.
356///
357/// Returns `(offset, stride)` on success, or `None` if no lock is found.
358fn find_sync(buf: &[u8]) -> Option<(usize, PacketStride)> {
359    for o in 0..buf.len() {
360        if buf[o] != TS_SYNC_BYTE {
361            continue;
362        }
363        if let Some(stride) = STRIDES
364            .into_iter()
365            .find(|stride| try_stride(buf, o, stride.packet_len()))
366        {
367            return Some((o, stride));
368        }
369    }
370    None
371}
372
373/// The strides [`find_sync`] and [`find_tail_sync`] try, in order.
374const STRIDES: [PacketStride; 3] = [
375    PacketStride::Ts188,
376    PacketStride::M2ts192,
377    PacketStride::Rs204,
378];
379
380/// End-of-input counterpart of [`find_sync`]: the smallest offset whose
381/// stride (188 first, then 192, then 204) holds a sync byte at every packet boundary
382/// the buffer still covers, with at least one whole packet.
383fn find_tail_sync(buf: &[u8]) -> Option<(usize, PacketStride)> {
384    let chain = |o: usize, stride: PacketStride| {
385        let need = emit_len(stride);
386        o + need <= buf.len()
387            && (o..buf.len())
388                .step_by(stride.packet_len())
389                .take_while(|pos| pos + need <= buf.len())
390                .all(|pos| buf[pos] == TS_SYNC_BYTE)
391    };
392    (0..buf.len())
393        .filter(|&o| buf[o] == TS_SYNC_BYTE)
394        .find_map(|o| {
395            STRIDES
396                .into_iter()
397                .find(|&stride| chain(o, stride))
398                .map(|stride| (o, stride))
399        })
400}
401
402/// Bytes from a sync byte that complete one packet at `stride`: the 204-byte
403/// stride's parity trails its packet, while the 4 bytes after an M2TS packet
404/// belong to the next one.
405fn emit_len(stride: PacketStride) -> usize {
406    match stride {
407        PacketStride::Rs204 => RS_PACKET_SIZE,
408        PacketStride::Ts188 | PacketStride::M2ts192 => TS_PACKET_SIZE,
409    }
410}
411
412/// Return `true` if `LOCK_CONFIRMATIONS` consecutive sync bytes exist at
413/// stride `s` starting from `offset` (the first is already known to be
414/// [`TS_SYNC_BYTE`]).
415fn try_stride(buf: &[u8], offset: usize, s: usize) -> bool {
416    for k in 1..LOCK_CONFIRMATIONS {
417        let pos = offset + k * s;
418        if pos >= buf.len() || buf[pos] != TS_SYNC_BYTE {
419            return false;
420        }
421    }
422    true
423}
424
425// ── Stateless datagram resync (dvb-stream origin) ───────────────────────────
426
427/// Find the byte offset of the first confirmed `0x47` sync byte in `buf`,
428/// accepting a lone sync byte when the buffer is too small to hold a
429/// confirming packet.
430///
431/// "Confirmed" means either `buf[offset + TS_PACKET_SIZE] == TS_SYNC_BYTE`
432/// (two-packet confirmation), or the buffer is too small for two packets
433/// (best-effort single-sync-byte alignment).
434///
435/// Returns `None` when `buf` contains no `0x47` byte at all.
436#[must_use]
437pub fn resync(buf: &[u8]) -> Option<usize> {
438    let mut i = 0;
439    while i < buf.len() {
440        if buf[i] == TS_SYNC_BYTE {
441            let next = i + TS_PACKET_SIZE;
442            if next < buf.len() {
443                if buf[next] == TS_SYNC_BYTE {
444                    return Some(i);
445                }
446                i += 1;
447                continue;
448            }
449            return Some(i);
450        }
451        i += 1;
452    }
453    None
454}
455
456/// Find the byte offset of the first sync byte in `buf` confirmed by a
457/// second sync byte exactly one packet later. Never accepts a lone sync byte.
458#[must_use]
459pub fn resync_confirmed(buf: &[u8]) -> Option<usize> {
460    (0..buf.len().saturating_sub(TS_PACKET_SIZE))
461        .find(|&i| buf[i] == TS_SYNC_BYTE && buf[i + TS_PACKET_SIZE] == TS_SYNC_BYTE)
462}
463
464/// Offset of the first `0x47` in `buf` that has no room for a confirming
465/// sync byte one packet later.
466#[must_use]
467pub fn unconfirmed_candidate(buf: &[u8]) -> Option<usize> {
468    let from = buf.len().saturating_sub(TS_PACKET_SIZE);
469    buf[from..]
470        .iter()
471        .position(|&b| b == TS_SYNC_BYTE)
472        .map(|i| from + i)
473}
474
475#[cfg(test)]
476mod tests {
477    use super::*;
478    use alloc::vec;
479    use alloc::vec::Vec;
480    extern crate std;
481
482    /// Build a 188-byte TS packet starting with `TS_SYNC_BYTE` followed by
483    /// `tag` (repeated).  All non-sync bytes are kept away from `0x47` so
484    /// that no false lock occurs in the fixture data.
485    fn ts_packet(tag: u8) -> [u8; TS_PACKET_SIZE] {
486        assert_ne!(tag, TS_SYNC_BYTE, "tag must not equal sync byte");
487        let mut pkt = [tag; TS_PACKET_SIZE];
488        pkt[0] = TS_SYNC_BYTE;
489        pkt
490    }
491
492    /// Build a 204-byte RS-coded packet: 188-byte TS payload (with `ts_tag`)
493    /// plus 16 parity bytes filled with `parity` (must not be `0x47`).
494    fn rs_packet(ts_tag: u8, parity: u8) -> [u8; RS_PACKET_SIZE] {
495        assert_ne!(ts_tag, TS_SYNC_BYTE);
496        assert_ne!(parity, TS_SYNC_BYTE);
497        let mut pkt = [parity; RS_PACKET_SIZE];
498        pkt[0] = TS_SYNC_BYTE;
499        pkt[1..TS_PACKET_SIZE].fill(ts_tag);
500        pkt
501    }
502
503    /// Concatenate several 188-byte packet arrays into a flat `Vec<u8>`.
504    fn concat_ts(packets: &[[u8; TS_PACKET_SIZE]]) -> Vec<u8> {
505        let mut v = Vec::with_capacity(packets.len() * TS_PACKET_SIZE);
506        for p in packets {
507            v.extend_from_slice(p);
508        }
509        v
510    }
511
512    // ------------------------------------------------------------------
513    // Test 1 — aligned 188-byte passthrough
514    // ------------------------------------------------------------------
515    #[test]
516    fn lone_sync_byte_accepted_by_resync_not_confirmed() {
517        let buf = [TS_SYNC_BYTE];
518        assert_eq!(resync(&buf), Some(0));
519        assert_eq!(resync_confirmed(&buf), None);
520    }
521
522    #[test]
523    fn aligned_188_passthrough() {
524        let packets: Vec<_> = (0u8..5).map(|i| ts_packet(i + 1)).collect();
525        let data = concat_ts(&packets);
526
527        let mut r = TsResync::new();
528        let emitted = r.feed(&data);
529
530        assert_eq!(emitted.len(), 5);
531        for (i, (e, p)) in emitted.iter().zip(packets.iter()).enumerate() {
532            assert_eq!(e, p, "packet {i} mismatch");
533        }
534        assert_eq!(r.stride(), Some(PacketStride::Ts188));
535        let s = r.stats();
536        assert_eq!(s.packets, 5);
537        assert_eq!(s.resyncs, 0);
538        assert_eq!(s.dropped_bytes, 0);
539    }
540
541    // ------------------------------------------------------------------
542    // Test 2 — lock only after LOCK_CONFIRMATIONS sync bytes
543    // ------------------------------------------------------------------
544    #[test]
545    fn requires_n_confirmations_before_lock() {
546        // Pin the default lock window. The hardcoded 4-vs-5 boundary below only
547        // bites the threshold when this is 5 — assert it explicitly so a change
548        // to the default (or to this test's literals) cannot silently pass.
549        assert_eq!(
550            LOCK_CONFIRMATIONS, 5,
551            "this test pins the default lock window of 5"
552        );
553
554        // FOUR confirming, stride-aligned packets are one short of the window:
555        // only four sync bytes sit at the 188-stride boundaries, so the
556        // resynchroniser must NOT lock and must emit nothing (it buffers).
557        let four = concat_ts(&(1u8..=4).map(ts_packet).collect::<Vec<_>>());
558        let mut r = TsResync::new();
559        assert_eq!(
560            r.feed(&four).len(),
561            0,
562            "4 confirmations (< 5) must not lock or emit"
563        );
564        assert_eq!(r.stride(), None, "stride must remain None below the window");
565
566        // The FIFTH stride-aligned sync byte completes the window → lock.
567        let mut out = r.feed(&ts_packet(5));
568        out.extend(r.feed(&[]));
569        assert!(
570            r.stride().is_some(),
571            "the 5th confirmation must trigger lock"
572        );
573        // Once locked, the buffered packets are emitted (5 fed, all aligned).
574        assert_eq!(out.len(), 5, "all five aligned packets emit once locked");
575    }
576
577    // ------------------------------------------------------------------
578    // Test 3 — junk prefix: leading garbage dropped, correct count returned
579    // ------------------------------------------------------------------
580    #[test]
581    fn junk_prefix_correct_dropped_count() {
582        let pkts: Vec<_> = (0u8..6).map(|i| ts_packet(i + 1)).collect();
583        let stream = concat_ts(&pkts);
584
585        let junk_len = 7usize;
586        let mut data: Vec<u8> = vec![0x00; junk_len];
587        data.extend_from_slice(&stream);
588
589        let mut r = TsResync::new();
590        let emitted = r.feed(&data);
591
592        assert_eq!(emitted.len(), 6);
593        for (i, (e, p)) in emitted.iter().zip(pkts.iter()).enumerate() {
594            assert_eq!(*e, *p, "packet {i} mismatch after junk prefix");
595        }
596        let s = r.stats();
597        assert_eq!(
598            s.dropped_bytes, junk_len as u64,
599            "dropped bytes must equal junk prefix"
600        );
601        assert_eq!(s.resyncs, 0);
602        assert_eq!(s.packets, 6);
603    }
604
605    // ------------------------------------------------------------------
606    // Test 4 — mid-stream sync loss and reacquisition
607    // ------------------------------------------------------------------
608    #[test]
609    fn midstream_loss_resync() {
610        // Need > LOCK_CONFIRMATIONS clean packets before and after the stray
611        // byte so the stream locks, loses sync, and re-locks.
612        let pkts: Vec<_> = (0u8..14).map(|i| ts_packet(i + 1)).collect();
613        let clean = concat_ts(&pkts);
614
615        // Insert a single stray byte 12 bytes into packet 7.
616        let insert_at = 7 * TS_PACKET_SIZE + 12;
617        let mut data = clean[..insert_at].to_vec();
618        data.push(0x00);
619        data.extend_from_slice(&clean[insert_at..]);
620
621        let mut r = TsResync::new();
622        let emitted = r.feed(&data);
623
624        let s = r.stats();
625        assert!(
626            s.resyncs >= 1,
627            "mid-stream corruption must trigger a resync, got {}",
628            s.resyncs
629        );
630        assert_eq!(emitted[0], pkts[0], "first emitted packet is P0");
631        assert!(
632            emitted.len() >= 10,
633            "should recover and emit most packets, got {}",
634            emitted.len()
635        );
636    }
637
638    // ------------------------------------------------------------------
639    // Test 5 — 204-byte RS-coded packets detected + RS stripped
640    // ------------------------------------------------------------------
641    #[test]
642    fn rs204_detected_and_stripped() {
643        let mut stream = Vec::new();
644        let mut expected = Vec::new();
645        for i in 0u8..6 {
646            let tag = i + 1;
647            let rs = rs_packet(tag, 0xFF);
648            stream.extend_from_slice(&rs);
649            expected.push(ts_packet(tag));
650        }
651
652        let mut r = TsResync::new();
653        let emitted = r.feed(&stream);
654
655        assert_eq!(emitted.len(), 6, "RS-coded stream must emit 6 packets");
656        assert_eq!(
657            r.stride(),
658            Some(PacketStride::Rs204),
659            "stride must be Rs204"
660        );
661        for (i, (e, p)) in emitted.iter().zip(expected.iter()).enumerate() {
662            assert_eq!(e, p, "RS-stripped packet {i} mismatch");
663        }
664        // Confirm the emitted 188-byte packets are parseable by TsPacket.
665        for (i, pkt) in emitted.iter().enumerate() {
666            crate::ts::TsPacket::parse(pkt)
667                .unwrap_or_else(|e| panic!("RS-stripped packet {i} TsPacket::parse failed: {e}"));
668        }
669        let s = r.stats();
670        assert_eq!(s.packets, 6);
671        assert_eq!(s.resyncs, 0);
672        assert_eq!(s.dropped_bytes, 0);
673    }
674
675    // ------------------------------------------------------------------
676    // Test 6 — aligned 188 stream yields same packets as plain chunks(188)
677    //   (equivalence: fixture-less variant using synthetic data)
678    // ------------------------------------------------------------------
679    /// The losses are one per discarded span, in stream order: the leading
680    /// garbage (if any) and the mid-stream sync loss or truncated tail.
681    fn assert_one_loss_plus_leading(losses: &[ResyncLoss], leading: u64, expected: ResyncLoss) {
682        let expected_leading = usize::from(leading > 0);
683        assert_eq!(losses.len(), expected_leading + 1, "{losses:?}");
684        if leading > 0 {
685            assert_eq!(losses[0].offset, 0);
686            assert_eq!(losses[0].dropped_bytes, leading);
687            assert!(!losses[0].truncated_tail);
688        }
689        assert_eq!(losses[expected_leading], expected);
690    }
691
692    #[test]
693    fn broken_sync_byte_after_lock_is_one_loss_with_offset() {
694        let mut bytes = Vec::new();
695        for t in 1..=12u8 {
696            bytes.extend_from_slice(&ts_packet(t));
697        }
698        bytes[5 * TS_PACKET_SIZE] = 0x00;
699        let mut r = TsResync::new();
700        let got = r.feed(&bytes);
701        assert_eq!(got.len(), 11);
702        r.finish();
703        let losses = r.take_losses();
704        assert_one_loss_plus_leading(
705            &losses,
706            0,
707            ResyncLoss {
708                offset: 5 * TS_PACKET_SIZE as u64,
709                dropped_bytes: TS_PACKET_SIZE as u64,
710                packet_index: 5,
711                truncated_tail: false,
712            },
713        );
714    }
715
716    #[test]
717    fn leading_junk_at_the_first_lock_is_a_loss() {
718        let mut bytes = vec![0x11; 30];
719        for t in 1..=8u8 {
720            bytes.extend_from_slice(&ts_packet(t));
721        }
722        let mut r = TsResync::new();
723        assert_eq!(r.feed(&bytes).len(), 8);
724        let losses = r.take_losses();
725        assert_eq!(losses.len(), 1, "{losses:?}");
726        assert_eq!(losses[0].offset, 0);
727        assert_eq!(losses[0].dropped_bytes, 30);
728        assert_eq!(losses[0].packet_index, 0);
729        assert!(!losses[0].truncated_tail);
730    }
731
732    #[test]
733    fn bulk_discarded_junk_before_lock_is_a_loss() {
734        let junk_len = LOCK_CONFIRMATIONS * RS_PACKET_SIZE + 7;
735        let mut bytes = vec![0x00; junk_len];
736        for t in 1..=8u8 {
737            bytes.extend_from_slice(&ts_packet(t));
738        }
739        let mut r = TsResync::new();
740        assert_eq!(r.feed(&bytes).len(), 8);
741        let losses = r.take_losses();
742        assert_eq!(losses.len(), 1, "{losses:?}");
743        assert_eq!(losses[0].offset, 0);
744        assert_eq!(losses[0].dropped_bytes, junk_len as u64);
745        assert_eq!(r.stats().dropped_bytes, junk_len as u64);
746    }
747
748    #[test]
749    fn leading_junk_is_a_loss_and_so_is_the_truncated_tail() {
750        let mut bytes = vec![0x11; 30];
751        for t in 1..=8u8 {
752            bytes.extend_from_slice(&ts_packet(t));
753        }
754        bytes.extend_from_slice(&[0x22; 50]);
755        let mut r = TsResync::new();
756        let _ = r.feed(&bytes);
757        r.finish();
758        let losses = r.take_losses();
759        assert_one_loss_plus_leading(
760            &losses,
761            30,
762            ResyncLoss {
763                offset: 30 + 8 * TS_PACKET_SIZE as u64,
764                dropped_bytes: 50,
765                packet_index: 8,
766                truncated_tail: true,
767            },
768        );
769    }
770
771    #[test]
772    fn aligned_188_matches_plain_chunks() {
773        let pkts: Vec<_> = (0u8..10).map(|i| ts_packet(i + 1)).collect();
774        let data = concat_ts(&pkts);
775
776        // Oracle: plain chunks(188) filtered by sync byte.
777        let oracle: Vec<[u8; TS_PACKET_SIZE]> = data
778            .chunks_exact(TS_PACKET_SIZE)
779            .filter(|c| c[0] == TS_SYNC_BYTE)
780            .map(|c| c.try_into().unwrap())
781            .collect();
782
783        let mut r = TsResync::new();
784        let emitted = r.feed(&data);
785
786        assert_eq!(emitted.len(), oracle.len(), "count mismatch");
787        for (i, (e, o)) in emitted.iter().zip(oracle.iter()).enumerate() {
788            assert_eq!(e, o, "packet {i} differs from chunks-oracle");
789        }
790    }
791
792    // ------------------------------------------------------------------
793    // Test 7 — chunked feed equivalence (same result in small increments)
794    // ------------------------------------------------------------------
795    #[test]
796    fn chunked_feed_equivalence() {
797        let pkts: Vec<_> = (0u8..6).map(|i| ts_packet(i + 1)).collect();
798        let stream = concat_ts(&pkts);
799
800        let whole = {
801            let mut r = TsResync::new();
802            r.feed(&stream)
803        };
804
805        let chunked = {
806            let mut r = TsResync::new();
807            let mut out = Vec::new();
808            for chunk in stream.chunks(100) {
809                out.extend(r.feed(chunk));
810            }
811            out
812        };
813
814        assert_eq!(whole.len(), chunked.len());
815        for (i, (w, c)) in whole.iter().zip(chunked.iter()).enumerate() {
816            assert_eq!(w, c, "packet {i} mismatch");
817        }
818    }
819
820    // ------------------------------------------------------------------
821    // Test 8 — fixture-based: m6-single.ts differential
822    //   feeding the real fixture through TsResync must yield the same
823    //   188-byte packets as plain chunks_exact(188) + sync-byte filter.
824    // ------------------------------------------------------------------
825    #[test]
826    fn fixture_m6_matches_plain_chunks() {
827        let path = test_fixtures::path("ts/m6-single.ts");
828        let data = std::fs::read(path).expect("m6-single.ts fixture not found");
829
830        // Oracle: plain aligned 188-byte reads.
831        let oracle: Vec<[u8; TS_PACKET_SIZE]> = data
832            .chunks_exact(TS_PACKET_SIZE)
833            .filter(|c| c[0] == TS_SYNC_BYTE)
834            .map(|c| c.try_into().unwrap())
835            .collect();
836        assert!(!oracle.is_empty(), "oracle empty — fixture empty?");
837
838        let mut r = TsResync::new();
839        let emitted = r.feed(&data);
840
841        assert_eq!(
842            emitted.len(),
843            oracle.len(),
844            "packet count: TsResync={} oracle={}",
845            emitted.len(),
846            oracle.len()
847        );
848        for (i, (e, o)) in emitted.iter().zip(oracle.iter()).enumerate() {
849            assert_eq!(e, o, "packet {i} mismatch vs oracle");
850        }
851    }
852
853    #[test]
854    fn finish_emits_the_aligned_packets_after_a_corrupt_sync_byte() {
855        let mut input = Vec::new();
856        for tag in 1u8..=10 {
857            input.extend_from_slice(&ts_packet(tag));
858        }
859        let mut bad = ts_packet(11);
860        bad[0] = 0x00;
861        input.extend_from_slice(&bad);
862        for tag in 12u8..=14 {
863            input.extend_from_slice(&ts_packet(tag));
864        }
865
866        let mut r = TsResync::new();
867        let mut packets = r.feed(&input);
868        let tags: Vec<u8> = packets.iter().map(|p| p[1]).collect();
869        assert_eq!(tags, (1u8..=10).collect::<Vec<_>>());
870        r.finish();
871        packets.extend(r.take_tail_packets());
872        let tags: Vec<u8> = packets.iter().map(|p| p[1]).collect();
873        assert_eq!(tags, [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 12, 13, 14]);
874        let stats = r.stats();
875        assert_eq!(stats.packets, 13);
876        assert_eq!(stats.dropped_bytes, TS_PACKET_SIZE as u64 + 1);
877        let losses = r.take_losses();
878        assert_one_loss_plus_leading(
879            &losses,
880            0,
881            ResyncLoss {
882                offset: 10 * TS_PACKET_SIZE as u64,
883                dropped_bytes: TS_PACKET_SIZE as u64,
884                packet_index: 10,
885                truncated_tail: false,
886            },
887        );
888    }
889
890    #[test]
891    fn finish_emits_a_stream_shorter_than_the_lock_window() {
892        let packets: Vec<_> = (1u8..=4).map(ts_packet).collect();
893        let mut r = TsResync::new();
894        assert!(r.feed(&concat_ts(&packets)).is_empty());
895        r.finish();
896        assert_eq!(r.take_tail_packets(), packets);
897        assert!(r.take_tail_packets().is_empty());
898        assert_eq!(r.stride(), Some(PacketStride::Ts188));
899        assert_eq!(r.stats().dropped_bytes, 0);
900    }
901
902    #[test]
903    fn finish_emits_a_short_rs204_stream_stripped() {
904        let mut stream = Vec::new();
905        for tag in 1u8..=3 {
906            stream.extend_from_slice(&rs_packet(tag, 0xFF));
907        }
908        let mut r = TsResync::new();
909        assert!(r.feed(&stream).is_empty());
910        r.finish();
911        let packets = r.take_tail_packets();
912        assert_eq!(packets, [ts_packet(1), ts_packet(2), ts_packet(3)]);
913        assert_eq!(r.stride(), Some(PacketStride::Rs204));
914    }
915
916    #[test]
917    fn finish_does_not_lock_onto_a_stray_sync_byte_without_a_whole_packet() {
918        let mut junk = vec![0x00u8; 100];
919        junk[40] = TS_SYNC_BYTE;
920        let mut r = TsResync::new();
921        assert!(r.feed(&junk).is_empty());
922        r.finish();
923        assert!(r.take_tail_packets().is_empty());
924        assert_eq!(r.stats().dropped_bytes, 100);
925    }
926
927    #[test]
928    fn finish_does_not_emit_a_trailing_partial_packet_starting_with_sync_byte() {
929        let mut input = Vec::new();
930        for tag in 1u8..=10 {
931            input.extend_from_slice(&ts_packet(tag));
932        }
933        input.push(TS_SYNC_BYTE);
934        input.extend_from_slice(&[0x11, 0x22, 0x33, 0x44]);
935
936        let mut r = TsResync::new();
937        let mut packets = r.feed(&input);
938        r.finish();
939        packets.extend(r.take_tail_packets());
940        let tags: Vec<u8> = packets.iter().map(|p| p[1]).collect();
941        assert_eq!(tags, (1u8..=10).collect::<Vec<_>>());
942        assert!(r.take_tail_packets().is_empty());
943        let losses = r.take_losses();
944        assert_one_loss_plus_leading(
945            &losses,
946            0,
947            ResyncLoss {
948                offset: 10 * TS_PACKET_SIZE as u64,
949                dropped_bytes: 5,
950                packet_index: 10,
951                truncated_tail: true,
952            },
953        );
954    }
955}