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