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 core::num::NonZeroUsize;
19//! use mpeg_ts::resync::{LOCK_CONFIRMATIONS, PacketStride, ResyncConfig, TsResync, Unlocked};
20//!
21//! let confirmations = NonZeroUsize::new(LOCK_CONFIRMATIONS).expect("non-zero");
22//! let mut r = TsResync::new(ResyncConfig::new(confirmations, &PacketStride::ALL, Unlocked::KeepWindow));
23//! // Feed arbitrary bytes (file chunks, UDP datagrams, etc.).
24//! let packets: Vec<[u8; 188]> = r.feed(b"some raw bytes");
25//! let stats = r.stats();
26//! ```
27
28use alloc::vec::Vec;
29use core::num::NonZeroUsize;
30
31use crate::ts::{TS_PACKET_SIZE, TS_SYNC_BYTE};
32
33/// Reed-Solomon-coded TS packet size: 188-byte payload + 16 parity bytes
34/// (DVB RS outer FEC, ISO/IEC 13818-1 §2.4.3.2 informative note).
35pub const RS_PACKET_SIZE: usize = 204;
36
37/// Number of Reed-Solomon parity bytes appended to a 204-byte packet.
38pub const RS_PARITY_LEN: usize = RS_PACKET_SIZE - TS_PACKET_SIZE;
39
40/// M2TS (BDAV) source packet size: a 4-byte `TP_extra_header`
41/// (copy-permission indicator + arrival time stamp) followed by a 188-byte TS
42/// packet.
43pub const M2TS_PACKET_SIZE: usize = 192;
44
45/// Length of the `TP_extra_header` that precedes each TS packet in M2TS.
46pub const M2TS_EXTRA_HEADER_LEN: usize = M2TS_PACKET_SIZE - TS_PACKET_SIZE;
47
48/// Consecutive sync bytes at the candidate stride that the broadcast capture
49/// readers (files, TCP) require to declare lock; a caller states its own
50/// number in [`ResyncConfig`].
51pub const LOCK_CONFIRMATIONS: usize = 5;
52
53/// What a [`TsResync`] does with bytes received before it has locked.
54#[derive(Debug, Clone, Copy, PartialEq, Eq)]
55#[non_exhaustive]
56pub enum Unlocked {
57    /// Keep up to `confirmations` of the largest stride's packets of
58    /// not-yet-locked bytes in case a lock appears among them, and drop only
59    /// the excess before them.
60    KeepWindow,
61    /// Drop at once every byte that can no longer start a lock; keep only the
62    /// bytes from the first sync byte that more input could still confirm.
63    DropUnalignable,
64}
65
66impl Unlocked {
67    /// The policy's name.
68    #[must_use]
69    pub fn name(&self) -> &'static str {
70        match self {
71            Self::KeepWindow => "keep_window",
72            Self::DropUnalignable => "drop_unalignable",
73        }
74    }
75}
76broadcast_core::impl_spec_display!(Unlocked);
77
78/// What a [`TsResync`] must be told by its caller: how many consecutive sync
79/// bytes declare lock, which packet strides it may lock onto, and what it does
80/// with bytes before the lock. There is no default: a capture reader and a
81/// datagram framer want different values.
82#[derive(Debug, Clone, Copy, PartialEq, Eq)]
83pub struct ResyncConfig {
84    confirmations: NonZeroUsize,
85    strides: &'static [PacketStride],
86    unlocked: Unlocked,
87}
88
89impl ResyncConfig {
90    /// A configuration locking after `confirmations` sync bytes at one of
91    /// `strides`, tried in the given order. `strides` must not be empty.
92    #[must_use]
93    pub const fn new(
94        confirmations: NonZeroUsize,
95        strides: &'static [PacketStride],
96        unlocked: Unlocked,
97    ) -> Self {
98        Self {
99            confirmations,
100            strides,
101            unlocked,
102        }
103    }
104
105    /// What happens to bytes before the lock.
106    #[must_use]
107    pub const fn unlocked(&self) -> Unlocked {
108        self.unlocked
109    }
110
111    /// Sync bytes required to declare lock.
112    #[must_use]
113    pub const fn confirmations(&self) -> NonZeroUsize {
114        self.confirmations
115    }
116
117    /// The strides that may be locked onto, in preference order.
118    #[must_use]
119    pub const fn strides(&self) -> &'static [PacketStride] {
120        self.strides
121    }
122}
123
124/// Detected packet size after locking.
125#[non_exhaustive]
126#[derive(Debug, Clone, Copy, PartialEq, Eq)]
127#[cfg_attr(feature = "serde", derive(serde::Serialize))]
128pub enum PacketStride {
129    /// Standard 188-byte TS packets (ISO/IEC 13818-1 §2.4.3.2).
130    Ts188,
131    /// 204-byte packets (188-byte TS + 16 Reed-Solomon parity bytes).
132    Rs204,
133    /// 192-byte M2TS (BDAV) source packets (4-byte `TP_extra_header` +
134    /// 188-byte TS).
135    M2ts192,
136}
137
138impl PacketStride {
139    /// Every stride, in the order a lock prefers them: 188, 192, 204.
140    pub const ALL: [PacketStride; 3] = [
141        PacketStride::Ts188,
142        PacketStride::M2ts192,
143        PacketStride::Rs204,
144    ];
145
146    /// Only the standard 188-byte stride.
147    pub const TS_ONLY: [PacketStride; 1] = [PacketStride::Ts188];
148
149    /// Short machine-readable label for this stride.
150    pub fn name(&self) -> &'static str {
151        match self {
152            PacketStride::Ts188 => "ts_188",
153            PacketStride::Rs204 => "rs_204",
154            PacketStride::M2ts192 => "m2ts_192",
155        }
156    }
157
158    /// Bytes from one sync byte to the next at this stride.
159    pub fn packet_len(&self) -> usize {
160        match self {
161            PacketStride::Ts188 => TS_PACKET_SIZE,
162            PacketStride::Rs204 => RS_PACKET_SIZE,
163            PacketStride::M2ts192 => M2TS_PACKET_SIZE,
164        }
165    }
166}
167
168broadcast_core::impl_spec_display!(PacketStride);
169
170/// Counters accumulated during resynchronisation.
171#[non_exhaustive]
172#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
173#[cfg_attr(feature = "serde", derive(serde::Serialize))]
174pub struct ResyncStats {
175    /// Total 188-byte TS packets emitted.
176    pub packets: u64,
177    /// Times sync was lost and reacquired.
178    pub resyncs: u64,
179    /// Bytes skipped/dropped (junk before lock + sync-loss bytes).
180    pub dropped_bytes: u64,
181    /// Times a lock was acquired, the first included.
182    pub locks: u64,
183}
184
185/// One span of bytes the resynchroniser discarded: either the bytes before
186/// the first lock (a capture that starts mid-packet or on garbage), a
187/// mid-stream sync loss, or a truncated trailing packet.
188///
189/// Drained with [`TsResync::take_losses`]; one entry per discarded span, so a
190/// caller can report each skipped unit exactly once, and the spans account for
191/// every byte in [`ResyncStats::dropped_bytes`].
192#[non_exhaustive]
193#[derive(Debug, Clone, Copy, PartialEq, Eq)]
194#[cfg_attr(feature = "serde", derive(serde::Serialize))]
195pub struct ResyncLoss {
196    /// Byte offset, from the first byte ever fed, where the discarded span starts.
197    pub offset: u64,
198    /// Length of the discarded span in bytes.
199    pub dropped_bytes: u64,
200    /// Number of whole packets emitted before this loss, i.e. the index the
201    /// next intact packet will carry.
202    pub packet_index: u64,
203    /// `true` when the span is a truncated trailing packet found by
204    /// [`TsResync::finish`] rather than a sync loss in mid-stream.
205    pub truncated_tail: bool,
206}
207
208/// Stateful TS byte-stream resynchroniser (ISO/IEC 13818-1 §2.4.3.2).
209///
210/// Recovers 188-byte MPEG-TS packet alignment from an arbitrary byte stream
211/// that may start mid-packet or contain junk, and detects 204-byte
212/// Reed-Solomon-coded packets (stripping the 16 parity bytes) and 192-byte
213/// M2TS source packets (stripping the 4-byte `TP_extra_header`).
214///
215/// Feed raw bytes with [`feed`](Self::feed); each call returns a `Vec` of
216/// aligned 188-byte TS packets.  Bytes are buffered across calls so that
217/// packet boundaries may span call boundaries freely.
218///
219/// Lock is declared after [`LOCK_CONFIRMATIONS`] consecutive sync bytes are
220/// found at the candidate stride (188, 192 or 204).  On sync loss the resynchroniser
221/// re-scans from the byte after the lost position.
222///
223/// Every discarded byte is reported as a [`ResyncLoss`], including the bytes
224/// before the first lock: a caller that never sees a loss event therefore
225/// never silently dropped input.
226///
227/// # Stats
228///
229/// [`stats`](Self::stats) returns cumulative counters (packets emitted,
230/// resyncs, dropped bytes).
231#[derive(Debug)]
232pub struct TsResync {
233    config: ResyncConfig,
234    buf: Vec<u8>,
235    /// Logical read head into `buf`; compacted periodically.
236    head: usize,
237    stride: Option<PacketStride>,
238    stats: ResyncStats,
239    /// Bytes already compacted away (stream offset of `buf[0]`).
240    consumed: u64,
241    /// Stream offset where the currently open sync loss began.
242    open_loss: Option<u64>,
243    /// Closed losses not yet drained by [`take_losses`](Self::take_losses).
244    losses: Vec<ResyncLoss>,
245    /// Aligned packets recovered by [`finish`](Self::finish), not yet drained
246    /// by [`take_tail_packets`](Self::take_tail_packets).
247    tail: Vec<[u8; TS_PACKET_SIZE]>,
248    /// Bytes of the current stride still to skip after a packet emitted
249    /// before its stride's trailing bytes arrived (M2TS: the next packet's
250    /// `TP_extra_header`).
251    skip: usize,
252    /// Bytes of the open loss already counted in `stats.dropped_bytes` by
253    /// the eager drop of unalignable bytes.
254    eager_dropped: u64,
255}
256
257impl TsResync {
258    /// Create a resynchroniser with an empty internal buffer, locking as
259    /// `config` says.
260    pub fn new(config: ResyncConfig) -> Self {
261        Self {
262            config,
263            buf: Vec::new(),
264            head: 0,
265            stride: None,
266            stats: ResyncStats::default(),
267            consumed: 0,
268            open_loss: None,
269            losses: Vec::new(),
270            tail: Vec::new(),
271            skip: 0,
272            eager_dropped: 0,
273        }
274    }
275
276    /// Feed `data` and emit every newly-aligned 188-byte TS packet.
277    ///
278    /// For a 204-byte stream the 16 Reed-Solomon parity bytes are stripped,
279    /// and for a 192-byte M2TS stream the 4-byte `TP_extra_header`; only the
280    /// 188-byte TS packet is returned.  Bytes that cannot yet form
281    /// a complete packet (or fall before lock) are buffered for the next call.
282    ///
283    /// **Drain [`take_losses`](Self::take_losses).** Every span discarded after
284    /// lock is appended to an internal list (about 32-40 bytes each) that only
285    /// `take_losses` empties; a caller that feeds forever and never drains it
286    /// grows memory linearly with the number of re-locks on a lossy input.
287    pub fn feed(&mut self, data: &[u8]) -> Vec<[u8; TS_PACKET_SIZE]> {
288        let mut emitted = Vec::new();
289        self.feed_into(data, &mut emitted);
290        emitted
291    }
292
293    /// [`feed`](Self::feed) appending to a caller-owned `out` (not cleared),
294    /// so a steady-state caller that reuses one `Vec` allocates nothing per
295    /// call (audit r01-O4). The output capacity is reserved once from the
296    /// buffered byte count instead of growing by doubling.
297    ///
298    /// Returns the number of packets appended.
299    pub fn feed_into(&mut self, data: &[u8], emitted: &mut Vec<[u8; TS_PACKET_SIZE]>) -> usize {
300        self.buf.extend_from_slice(data);
301        let before = emitted.len();
302        emitted.reserve((self.buf.len() - self.head) / TS_PACKET_SIZE);
303
304        loop {
305            match self.stride {
306                None => {
307                    if let Some((offset, s)) = find_sync(&self.buf[self.head..], &self.config) {
308                        self.lock(offset, s);
309                    } else {
310                        match self.config.unlocked {
311                            Unlocked::DropUnalignable => {
312                                let keep_from =
313                                    first_possible_lock(&self.buf[self.head..], &self.config);
314                                if keep_from > 0 {
315                                    self.open_loss
316                                        .get_or_insert(self.consumed + self.head as u64);
317                                    self.head += keep_from;
318                                    self.stats.dropped_bytes += keep_from as u64;
319                                    self.eager_dropped += keep_from as u64;
320                                }
321                            }
322                            Unlocked::KeepWindow => {
323                                let keep = LOCK_CONFIRMATIONS * RS_PACKET_SIZE;
324                                let tail_len = self.buf.len() - self.head;
325                                if tail_len > keep {
326                                    let excess = tail_len - keep;
327                                    self.stats.dropped_bytes += excess as u64;
328                                    self.head += excess;
329                                }
330                            }
331                        }
332                        self.compact();
333                        return emitted.len() - before;
334                    }
335                }
336                Some(stride) => {
337                    let s = stride.packet_len();
338                    let tail_len = self.buf.len() - self.head;
339                    if self.skip > 0 {
340                        let n = self.skip.min(tail_len);
341                        self.head += n;
342                        self.skip -= n;
343                        if self.skip > 0 {
344                            self.compact();
345                            return emitted.len() - before;
346                        }
347                        continue;
348                    }
349                    if tail_len < emit_len(stride) {
350                        self.compact();
351                        return emitted.len() - before;
352                    }
353                    if self.buf[self.head] == TS_SYNC_BYTE {
354                        let mut packet = [0u8; TS_PACKET_SIZE];
355                        packet.copy_from_slice(&self.buf[self.head..self.head + TS_PACKET_SIZE]);
356                        emitted.push(packet);
357                        let advance = s.min(tail_len);
358                        self.head += advance;
359                        self.skip = s - advance;
360                        self.stats.packets += 1;
361                    } else {
362                        // Sync byte missing — record the loss and re-scan.
363                        self.stats.resyncs += 1;
364                        self.stats.dropped_bytes += 1;
365                        self.open_loss
366                            .get_or_insert(self.consumed + self.head as u64);
367                        self.head += 1;
368                        self.stride = None;
369                    }
370                }
371            }
372        }
373    }
374
375    /// Detected packet stride, or [`None`] before the stream has locked.
376    pub fn stride(&self) -> Option<PacketStride> {
377        self.stride
378    }
379
380    /// Drain the sync losses recorded since the last call (see [`ResyncLoss`]).
381    ///
382    /// This is the only thing that empties the internal loss list, which is
383    /// unbounded by design (dropping a loss would hide data loss): call it
384    /// regularly — e.g. after every [`feed`](Self::feed) — or the list grows
385    /// with every re-lock on a lossy input. If you do not need the losses,
386    /// still call it and discard the result.
387    pub fn take_losses(&mut self) -> Vec<ResyncLoss> {
388        core::mem::take(&mut self.losses)
389    }
390
391    fn lock(&mut self, offset: usize, stride: PacketStride) {
392        self.stats.locks += 1;
393        let eager = self.eager_dropped;
394        self.eager_dropped = 0;
395        self.open_loss
396            .get_or_insert(self.consumed + self.head as u64);
397        self.head += offset;
398        self.stride = Some(stride);
399        if let Some(start) = self.open_loss.take() {
400            let end = self.consumed + self.head as u64;
401            if end > start {
402                self.stats.dropped_bytes += (end - start).saturating_sub(eager);
403                self.losses.push(ResyncLoss {
404                    offset: start,
405                    dropped_bytes: end - start,
406                    packet_index: self.stats.packets,
407                    truncated_tail: false,
408                });
409            }
410        }
411    }
412
413    /// Declare end of input. Packets that were still waiting for a full
414    /// [`LOCK_CONFIRMATIONS`] window cannot be confirmed by more bytes, so the
415    /// aligned packets that fill the rest of the input (a stream shorter than
416    /// the window included) are kept; drain them with
417    /// [`take_tail_packets`](Self::take_tail_packets), like
418    /// [`take_losses`](Self::take_losses) for the losses.
419    ///
420    /// Also closes a sync loss that never re-locked and records a truncated
421    /// trailing packet, both retrievable with
422    /// [`take_losses`](Self::take_losses). The buffer is discarded.
423    pub fn finish(&mut self) {
424        if self.stride.is_none()
425            && let Some((offset, s)) = find_tail_sync(&self.buf[self.head..], &self.config)
426        {
427            self.lock(offset, s);
428            let mut emitted = core::mem::take(&mut self.tail);
429            self.feed_into(&[], &mut emitted);
430            self.tail = emitted;
431        }
432        let end = self.consumed + self.buf.len() as u64;
433        if let Some(start) = self.open_loss.take() {
434            self.losses.push(ResyncLoss {
435                offset: start,
436                dropped_bytes: end - start,
437                packet_index: self.stats.packets,
438                truncated_tail: false,
439            });
440        } else if self.stride.is_some() && self.head < self.buf.len() {
441            self.losses.push(ResyncLoss {
442                offset: self.consumed + self.head as u64,
443                dropped_bytes: (self.buf.len() - self.head) as u64,
444                packet_index: self.stats.packets,
445                truncated_tail: true,
446            });
447        }
448        self.stats.dropped_bytes += (self.buf.len() - self.head) as u64;
449        self.eager_dropped = 0;
450        self.head = self.buf.len();
451        self.compact();
452    }
453
454    /// Drain the aligned packets [`finish`](Self::finish) recovered at end of
455    /// input. Call it after `finish` and process the result like the output
456    /// of [`feed`](Self::feed).
457    pub fn take_tail_packets(&mut self) -> Vec<[u8; TS_PACKET_SIZE]> {
458        core::mem::take(&mut self.tail)
459    }
460
461    /// Bytes of the sync loss still open (dropped so far and not yet closed
462    /// by a re-lock), so a caller can account for them without waiting for
463    /// [`take_losses`](Self::take_losses).
464    pub fn open_loss_bytes(&self) -> u64 {
465        self.open_loss
466            .map_or(0, |start| self.consumed + self.head as u64 - start)
467    }
468
469    /// Datagram mode: `data` is one whole datagram, framed on its own. Any
470    /// earlier state is forgotten, the first sync byte is accepted without a
471    /// confirming successor when none fits (a lone `0x47` in a short
472    /// datagram), every consecutive 188-byte packet is emitted, and the rest
473    /// is dropped whole: after a packet whose sync byte is missing, or as a
474    /// truncated tail. Each dropped span is a [`ResyncLoss`]. Only the 188-byte
475    /// stride is framed; the configured strides and confirmations do not
476    /// apply.
477    pub fn feed_datagram(&mut self, data: &[u8]) -> Vec<[u8; TS_PACKET_SIZE]> {
478        let base = self.consumed;
479        self.consumed += data.len() as u64;
480        self.buf.clear();
481        self.head = 0;
482        self.stride = None;
483        self.open_loss = None;
484        self.skip = 0;
485        let mut out = Vec::new();
486        let Some(start) = resync(data) else {
487            self.record_loss(base, data.len(), false);
488            return out;
489        };
490        self.record_loss(base, start, false);
491        self.stats.locks += 1;
492        let mut pos = start;
493        while data.len() - pos >= TS_PACKET_SIZE {
494            if data[pos] != TS_SYNC_BYTE {
495                self.stats.resyncs += 1;
496                self.record_loss(base + pos as u64, data.len() - pos, false);
497                return out;
498            }
499            let mut packet = [0u8; TS_PACKET_SIZE];
500            packet.copy_from_slice(&data[pos..pos + TS_PACKET_SIZE]);
501            out.push(packet);
502            self.stats.packets += 1;
503            pos += TS_PACKET_SIZE;
504        }
505        self.record_loss(base + pos as u64, data.len() - pos, true);
506        out
507    }
508
509    fn record_loss(&mut self, offset: u64, len: usize, truncated_tail: bool) {
510        if len == 0 {
511            return;
512        }
513        self.stats.dropped_bytes += len as u64;
514        self.losses.push(ResyncLoss {
515            offset,
516            dropped_bytes: len as u64,
517            packet_index: self.stats.packets,
518            truncated_tail,
519        });
520    }
521
522    /// Accumulated statistics.
523    pub fn stats(&self) -> ResyncStats {
524        self.stats
525    }
526
527    /// Compact the internal buffer by discarding consumed bytes.
528    fn compact(&mut self) {
529        if self.head > 0 {
530            self.consumed += self.head as u64;
531            self.buf.drain(..self.head);
532            self.head = 0;
533        }
534    }
535}
536
537/// Scan `buf` for the smallest offset `o` such that stride `S` (tried 188
538/// first, then 192, then 204) yields [`LOCK_CONFIRMATIONS`] consecutive sync bytes at
539/// positions `o + k*S` for `k = 0 .. LOCK_CONFIRMATIONS`.
540///
541/// Returns `(offset, stride)` on success, or `None` if no lock is found.
542fn find_sync(buf: &[u8], config: &ResyncConfig) -> Option<(usize, PacketStride)> {
543    for o in 0..buf.len() {
544        if buf[o] != TS_SYNC_BYTE {
545            continue;
546        }
547        if let Some(stride) = config
548            .strides
549            .iter()
550            .copied()
551            .find(|stride| try_stride(buf, o, stride.packet_len(), config.confirmations.get()))
552        {
553            return Some((o, stride));
554        }
555    }
556    None
557}
558
559/// The smallest offset at which a lock might still be confirmed once more
560/// bytes arrive (its sync byte holds at every confirmation position the buffer
561/// already covers, and at least one position lies beyond it), or `buf.len()`
562/// when no offset can lock: everything before it is unalignable.
563fn first_possible_lock(buf: &[u8], config: &ResyncConfig) -> usize {
564    let confirmations = config.confirmations.get();
565    (0..buf.len())
566        .find(|&o| {
567            buf[o] == TS_SYNC_BYTE
568                && config.strides.iter().any(|stride| {
569                    let s = stride.packet_len();
570                    let mut open = false;
571                    for k in 1..confirmations {
572                        let pos = o + k * s;
573                        if pos >= buf.len() {
574                            open = true;
575                            break;
576                        }
577                        if buf[pos] != TS_SYNC_BYTE {
578                            return false;
579                        }
580                    }
581                    open
582                })
583        })
584        .unwrap_or(buf.len())
585}
586
587/// End-of-input counterpart of [`find_sync`]: the smallest offset whose
588/// stride (188 first, then 192, then 204) holds a sync byte at every packet boundary
589/// the buffer still covers, with at least one whole packet.
590fn find_tail_sync(buf: &[u8], config: &ResyncConfig) -> Option<(usize, PacketStride)> {
591    let chain = |o: usize, stride: PacketStride| {
592        let need = emit_len(stride);
593        o + need <= buf.len()
594            && (o..buf.len())
595                .step_by(stride.packet_len())
596                .take_while(|pos| pos + need <= buf.len())
597                .all(|pos| buf[pos] == TS_SYNC_BYTE)
598    };
599    (0..buf.len())
600        .filter(|&o| buf[o] == TS_SYNC_BYTE)
601        .find_map(|o| {
602            config
603                .strides
604                .iter()
605                .copied()
606                .find(|&stride| chain(o, stride))
607                .map(|stride| (o, stride))
608        })
609}
610
611/// Bytes from a sync byte that complete one packet at `stride`: the 204-byte
612/// stride's parity trails its packet, while the 4 bytes after an M2TS packet
613/// belong to the next one.
614fn emit_len(stride: PacketStride) -> usize {
615    match stride {
616        PacketStride::Rs204 => RS_PACKET_SIZE,
617        PacketStride::Ts188 | PacketStride::M2ts192 => TS_PACKET_SIZE,
618    }
619}
620
621/// Return `true` if `confirmations` consecutive sync bytes exist at
622/// stride `s` starting from `offset` (the first is already known to be
623/// [`TS_SYNC_BYTE`]).
624fn try_stride(buf: &[u8], offset: usize, s: usize, confirmations: usize) -> bool {
625    for k in 1..confirmations {
626        let pos = offset + k * s;
627        if pos >= buf.len() || buf[pos] != TS_SYNC_BYTE {
628            return false;
629        }
630    }
631    true
632}
633
634// ── Stateless datagram resync (dvb-stream origin) ───────────────────────────
635
636/// Find the byte offset of the first confirmed `0x47` sync byte in `buf`,
637/// accepting a lone sync byte when the buffer is too small to hold a
638/// confirming packet.
639///
640/// "Confirmed" means either `buf[offset + TS_PACKET_SIZE] == TS_SYNC_BYTE`
641/// (two-packet confirmation), or the buffer is too small for two packets
642/// (best-effort single-sync-byte alignment).
643///
644/// Returns `None` when `buf` contains no `0x47` byte at all.
645#[must_use]
646pub fn resync(buf: &[u8]) -> Option<usize> {
647    let mut i = 0;
648    while i < buf.len() {
649        if buf[i] == TS_SYNC_BYTE {
650            let next = i + TS_PACKET_SIZE;
651            if next < buf.len() {
652                if buf[next] == TS_SYNC_BYTE {
653                    return Some(i);
654                }
655                i += 1;
656                continue;
657            }
658            return Some(i);
659        }
660        i += 1;
661    }
662    None
663}
664
665/// Find the byte offset of the first sync byte in `buf` confirmed by a
666/// second sync byte exactly one packet later. Never accepts a lone sync byte.
667#[must_use]
668pub fn resync_confirmed(buf: &[u8]) -> Option<usize> {
669    (0..buf.len().saturating_sub(TS_PACKET_SIZE))
670        .find(|&i| buf[i] == TS_SYNC_BYTE && buf[i + TS_PACKET_SIZE] == TS_SYNC_BYTE)
671}
672
673/// Offset of the first `0x47` in `buf` that has no room for a confirming
674/// sync byte one packet later.
675#[must_use]
676pub fn unconfirmed_candidate(buf: &[u8]) -> Option<usize> {
677    let from = buf.len().saturating_sub(TS_PACKET_SIZE);
678    buf[from..]
679        .iter()
680        .position(|&b| b == TS_SYNC_BYTE)
681        .map(|i| from + i)
682}
683
684#[cfg(test)]
685mod tests {
686    use super::*;
687
688    fn cfg() -> ResyncConfig {
689        ResyncConfig::new(
690            NonZeroUsize::MIN.saturating_add(LOCK_CONFIRMATIONS - 1),
691            &PacketStride::ALL,
692            Unlocked::KeepWindow,
693        )
694    }
695
696    fn two_ts_only() -> ResyncConfig {
697        ResyncConfig::new(
698            NonZeroUsize::MIN.saturating_add(1),
699            &PacketStride::TS_ONLY,
700            Unlocked::DropUnalignable,
701        )
702    }
703    use alloc::vec;
704    use alloc::vec::Vec;
705    extern crate std;
706
707    /// Build a 188-byte TS packet starting with `TS_SYNC_BYTE` followed by
708    /// `tag` (repeated).  All non-sync bytes are kept away from `0x47` so
709    /// that no false lock occurs in the fixture data.
710    fn ts_packet(tag: u8) -> [u8; TS_PACKET_SIZE] {
711        assert_ne!(tag, TS_SYNC_BYTE, "tag must not equal sync byte");
712        let mut pkt = [tag; TS_PACKET_SIZE];
713        pkt[0] = TS_SYNC_BYTE;
714        pkt
715    }
716
717    /// Build a 204-byte RS-coded packet: 188-byte TS payload (with `ts_tag`)
718    /// plus 16 parity bytes filled with `parity` (must not be `0x47`).
719    fn rs_packet(ts_tag: u8, parity: u8) -> [u8; RS_PACKET_SIZE] {
720        assert_ne!(ts_tag, TS_SYNC_BYTE);
721        assert_ne!(parity, TS_SYNC_BYTE);
722        let mut pkt = [parity; RS_PACKET_SIZE];
723        pkt[0] = TS_SYNC_BYTE;
724        pkt[1..TS_PACKET_SIZE].fill(ts_tag);
725        pkt
726    }
727
728    /// Concatenate several 188-byte packet arrays into a flat `Vec<u8>`.
729    fn concat_ts(packets: &[[u8; TS_PACKET_SIZE]]) -> Vec<u8> {
730        let mut v = Vec::with_capacity(packets.len() * TS_PACKET_SIZE);
731        for p in packets {
732            v.extend_from_slice(p);
733        }
734        v
735    }
736
737    // ------------------------------------------------------------------
738    // Test 1 — aligned 188-byte passthrough
739    // ------------------------------------------------------------------
740    #[test]
741    fn lone_sync_byte_accepted_by_resync_not_confirmed() {
742        let buf = [TS_SYNC_BYTE];
743        assert_eq!(resync(&buf), Some(0));
744        assert_eq!(resync_confirmed(&buf), None);
745    }
746
747    #[test]
748    fn aligned_188_passthrough() {
749        let packets: Vec<_> = (0u8..5).map(|i| ts_packet(i + 1)).collect();
750        let data = concat_ts(&packets);
751
752        let mut r = TsResync::new(cfg());
753        let emitted = r.feed(&data);
754
755        assert_eq!(emitted.len(), 5);
756        for (i, (e, p)) in emitted.iter().zip(packets.iter()).enumerate() {
757            assert_eq!(e, p, "packet {i} mismatch");
758        }
759        assert_eq!(r.stride(), Some(PacketStride::Ts188));
760        let s = r.stats();
761        assert_eq!(s.packets, 5);
762        assert_eq!(s.resyncs, 0);
763        assert_eq!(s.dropped_bytes, 0);
764    }
765
766    // ------------------------------------------------------------------
767    // Test 2 — lock only after LOCK_CONFIRMATIONS sync bytes
768    // ------------------------------------------------------------------
769    #[test]
770    fn requires_n_confirmations_before_lock() {
771        // Pin the default lock window. The hardcoded 4-vs-5 boundary below only
772        // bites the threshold when this is 5 — assert it explicitly so a change
773        // to the default (or to this test's literals) cannot silently pass.
774        assert_eq!(
775            LOCK_CONFIRMATIONS, 5,
776            "this test pins the default lock window of 5"
777        );
778
779        // FOUR confirming, stride-aligned packets are one short of the window:
780        // only four sync bytes sit at the 188-stride boundaries, so the
781        // resynchroniser must NOT lock and must emit nothing (it buffers).
782        let four = concat_ts(&(1u8..=4).map(ts_packet).collect::<Vec<_>>());
783        let mut r = TsResync::new(cfg());
784        assert_eq!(
785            r.feed(&four).len(),
786            0,
787            "4 confirmations (< 5) must not lock or emit"
788        );
789        assert_eq!(r.stride(), None, "stride must remain None below the window");
790
791        // The FIFTH stride-aligned sync byte completes the window → lock.
792        let mut out = r.feed(&ts_packet(5));
793        out.extend(r.feed(&[]));
794        assert!(
795            r.stride().is_some(),
796            "the 5th confirmation must trigger lock"
797        );
798        // Once locked, the buffered packets are emitted (5 fed, all aligned).
799        assert_eq!(out.len(), 5, "all five aligned packets emit once locked");
800    }
801
802    // ------------------------------------------------------------------
803    // Test 3 — junk prefix: leading garbage dropped, correct count returned
804    // ------------------------------------------------------------------
805    #[test]
806    fn junk_prefix_correct_dropped_count() {
807        let pkts: Vec<_> = (0u8..6).map(|i| ts_packet(i + 1)).collect();
808        let stream = concat_ts(&pkts);
809
810        let junk_len = 7usize;
811        let mut data: Vec<u8> = vec![0x00; junk_len];
812        data.extend_from_slice(&stream);
813
814        let mut r = TsResync::new(cfg());
815        let emitted = r.feed(&data);
816
817        assert_eq!(emitted.len(), 6);
818        for (i, (e, p)) in emitted.iter().zip(pkts.iter()).enumerate() {
819            assert_eq!(*e, *p, "packet {i} mismatch after junk prefix");
820        }
821        let s = r.stats();
822        assert_eq!(
823            s.dropped_bytes, junk_len as u64,
824            "dropped bytes must equal junk prefix"
825        );
826        assert_eq!(s.resyncs, 0);
827        assert_eq!(s.packets, 6);
828    }
829
830    // ------------------------------------------------------------------
831    // Test 4 — mid-stream sync loss and reacquisition
832    // ------------------------------------------------------------------
833    #[test]
834    fn midstream_loss_resync() {
835        // Need > LOCK_CONFIRMATIONS clean packets before and after the stray
836        // byte so the stream locks, loses sync, and re-locks.
837        let pkts: Vec<_> = (0u8..14).map(|i| ts_packet(i + 1)).collect();
838        let clean = concat_ts(&pkts);
839
840        // Insert a single stray byte 12 bytes into packet 7.
841        let insert_at = 7 * TS_PACKET_SIZE + 12;
842        let mut data = clean[..insert_at].to_vec();
843        data.push(0x00);
844        data.extend_from_slice(&clean[insert_at..]);
845
846        let mut r = TsResync::new(cfg());
847        let emitted = r.feed(&data);
848
849        let s = r.stats();
850        assert!(
851            s.resyncs >= 1,
852            "mid-stream corruption must trigger a resync, got {}",
853            s.resyncs
854        );
855        assert_eq!(emitted[0], pkts[0], "first emitted packet is P0");
856        assert!(
857            emitted.len() >= 10,
858            "should recover and emit most packets, got {}",
859            emitted.len()
860        );
861    }
862
863    // ------------------------------------------------------------------
864    // Test 5 — 204-byte RS-coded packets detected + RS stripped
865    // ------------------------------------------------------------------
866    #[test]
867    fn rs204_detected_and_stripped() {
868        let mut stream = Vec::new();
869        let mut expected = Vec::new();
870        for i in 0u8..6 {
871            let tag = i + 1;
872            let rs = rs_packet(tag, 0xFF);
873            stream.extend_from_slice(&rs);
874            expected.push(ts_packet(tag));
875        }
876
877        let mut r = TsResync::new(cfg());
878        let emitted = r.feed(&stream);
879
880        assert_eq!(emitted.len(), 6, "RS-coded stream must emit 6 packets");
881        assert_eq!(
882            r.stride(),
883            Some(PacketStride::Rs204),
884            "stride must be Rs204"
885        );
886        for (i, (e, p)) in emitted.iter().zip(expected.iter()).enumerate() {
887            assert_eq!(e, p, "RS-stripped packet {i} mismatch");
888        }
889        // Confirm the emitted 188-byte packets are parseable by TsPacket.
890        for (i, pkt) in emitted.iter().enumerate() {
891            crate::ts::TsPacket::parse(pkt)
892                .unwrap_or_else(|e| panic!("RS-stripped packet {i} TsPacket::parse failed: {e}"));
893        }
894        let s = r.stats();
895        assert_eq!(s.packets, 6);
896        assert_eq!(s.resyncs, 0);
897        assert_eq!(s.dropped_bytes, 0);
898    }
899
900    // ------------------------------------------------------------------
901    // Test 6 — aligned 188 stream yields same packets as plain chunks(188)
902    //   (equivalence: fixture-less variant using synthetic data)
903    // ------------------------------------------------------------------
904    /// The losses are one per discarded span, in stream order: the leading
905    /// garbage (if any) and the mid-stream sync loss or truncated tail.
906    fn assert_one_loss_plus_leading(losses: &[ResyncLoss], leading: u64, expected: ResyncLoss) {
907        let expected_leading = usize::from(leading > 0);
908        assert_eq!(losses.len(), expected_leading + 1, "{losses:?}");
909        if leading > 0 {
910            assert_eq!(losses[0].offset, 0);
911            assert_eq!(losses[0].dropped_bytes, leading);
912            assert!(!losses[0].truncated_tail);
913        }
914        assert_eq!(losses[expected_leading], expected);
915    }
916
917    #[test]
918    fn broken_sync_byte_after_lock_is_one_loss_with_offset() {
919        let mut bytes = Vec::new();
920        for t in 1..=12u8 {
921            bytes.extend_from_slice(&ts_packet(t));
922        }
923        bytes[5 * TS_PACKET_SIZE] = 0x00;
924        let mut r = TsResync::new(cfg());
925        let got = r.feed(&bytes);
926        assert_eq!(got.len(), 11);
927        r.finish();
928        let losses = r.take_losses();
929        assert_one_loss_plus_leading(
930            &losses,
931            0,
932            ResyncLoss {
933                offset: 5 * TS_PACKET_SIZE as u64,
934                dropped_bytes: TS_PACKET_SIZE as u64,
935                packet_index: 5,
936                truncated_tail: false,
937            },
938        );
939    }
940
941    #[test]
942    fn leading_junk_at_the_first_lock_is_a_loss() {
943        let mut bytes = vec![0x11; 30];
944        for t in 1..=8u8 {
945            bytes.extend_from_slice(&ts_packet(t));
946        }
947        let mut r = TsResync::new(cfg());
948        assert_eq!(r.feed(&bytes).len(), 8);
949        let losses = r.take_losses();
950        assert_eq!(losses.len(), 1, "{losses:?}");
951        assert_eq!(losses[0].offset, 0);
952        assert_eq!(losses[0].dropped_bytes, 30);
953        assert_eq!(losses[0].packet_index, 0);
954        assert!(!losses[0].truncated_tail);
955    }
956
957    #[test]
958    fn bulk_discarded_junk_before_lock_is_a_loss() {
959        let junk_len = LOCK_CONFIRMATIONS * RS_PACKET_SIZE + 7;
960        let mut bytes = vec![0x00; junk_len];
961        for t in 1..=8u8 {
962            bytes.extend_from_slice(&ts_packet(t));
963        }
964        let mut r = TsResync::new(cfg());
965        assert_eq!(r.feed(&bytes).len(), 8);
966        let losses = r.take_losses();
967        assert_eq!(losses.len(), 1, "{losses:?}");
968        assert_eq!(losses[0].offset, 0);
969        assert_eq!(losses[0].dropped_bytes, junk_len as u64);
970        assert_eq!(r.stats().dropped_bytes, junk_len as u64);
971    }
972
973    #[test]
974    fn leading_junk_is_a_loss_and_so_is_the_truncated_tail() {
975        let mut bytes = vec![0x11; 30];
976        for t in 1..=8u8 {
977            bytes.extend_from_slice(&ts_packet(t));
978        }
979        bytes.extend_from_slice(&[0x22; 50]);
980        let mut r = TsResync::new(cfg());
981        let _ = r.feed(&bytes);
982        r.finish();
983        let losses = r.take_losses();
984        assert_one_loss_plus_leading(
985            &losses,
986            30,
987            ResyncLoss {
988                offset: 30 + 8 * TS_PACKET_SIZE as u64,
989                dropped_bytes: 50,
990                packet_index: 8,
991                truncated_tail: true,
992            },
993        );
994    }
995
996    #[test]
997    fn aligned_188_matches_plain_chunks() {
998        let pkts: Vec<_> = (0u8..10).map(|i| ts_packet(i + 1)).collect();
999        let data = concat_ts(&pkts);
1000
1001        // Oracle: plain chunks(188) filtered by sync byte.
1002        let oracle: Vec<[u8; TS_PACKET_SIZE]> = data
1003            .chunks_exact(TS_PACKET_SIZE)
1004            .filter(|c| c[0] == TS_SYNC_BYTE)
1005            .map(|c| c.try_into().unwrap())
1006            .collect();
1007
1008        let mut r = TsResync::new(cfg());
1009        let emitted = r.feed(&data);
1010
1011        assert_eq!(emitted.len(), oracle.len(), "count mismatch");
1012        for (i, (e, o)) in emitted.iter().zip(oracle.iter()).enumerate() {
1013            assert_eq!(e, o, "packet {i} differs from chunks-oracle");
1014        }
1015    }
1016
1017    // ------------------------------------------------------------------
1018    // Test 7 — chunked feed equivalence (same result in small increments)
1019    // ------------------------------------------------------------------
1020    #[test]
1021    fn chunked_feed_equivalence() {
1022        let pkts: Vec<_> = (0u8..6).map(|i| ts_packet(i + 1)).collect();
1023        let stream = concat_ts(&pkts);
1024
1025        let whole = {
1026            let mut r = TsResync::new(cfg());
1027            r.feed(&stream)
1028        };
1029
1030        let chunked = {
1031            let mut r = TsResync::new(cfg());
1032            let mut out = Vec::new();
1033            for chunk in stream.chunks(100) {
1034                out.extend(r.feed(chunk));
1035            }
1036            out
1037        };
1038
1039        assert_eq!(whole.len(), chunked.len());
1040        for (i, (w, c)) in whole.iter().zip(chunked.iter()).enumerate() {
1041            assert_eq!(w, c, "packet {i} mismatch");
1042        }
1043    }
1044
1045    // ------------------------------------------------------------------
1046    // Test 8 — fixture-based: m6-single.ts differential
1047    //   feeding the real fixture through TsResync must yield the same
1048    //   188-byte packets as plain chunks_exact(188) + sync-byte filter.
1049    // ------------------------------------------------------------------
1050    #[test]
1051    fn fixture_m6_matches_plain_chunks() {
1052        let path = test_fixtures::path("ts/m6-single.ts");
1053        let data = std::fs::read(path).expect("m6-single.ts fixture not found");
1054
1055        // Oracle: plain aligned 188-byte reads.
1056        let oracle: Vec<[u8; TS_PACKET_SIZE]> = data
1057            .chunks_exact(TS_PACKET_SIZE)
1058            .filter(|c| c[0] == TS_SYNC_BYTE)
1059            .map(|c| c.try_into().unwrap())
1060            .collect();
1061        assert!(!oracle.is_empty(), "oracle empty — fixture empty?");
1062
1063        let mut r = TsResync::new(cfg());
1064        let emitted = r.feed(&data);
1065
1066        assert_eq!(
1067            emitted.len(),
1068            oracle.len(),
1069            "packet count: TsResync={} oracle={}",
1070            emitted.len(),
1071            oracle.len()
1072        );
1073        for (i, (e, o)) in emitted.iter().zip(oracle.iter()).enumerate() {
1074            assert_eq!(e, o, "packet {i} mismatch vs oracle");
1075        }
1076    }
1077
1078    #[test]
1079    fn finish_emits_the_aligned_packets_after_a_corrupt_sync_byte() {
1080        let mut input = Vec::new();
1081        for tag in 1u8..=10 {
1082            input.extend_from_slice(&ts_packet(tag));
1083        }
1084        let mut bad = ts_packet(11);
1085        bad[0] = 0x00;
1086        input.extend_from_slice(&bad);
1087        for tag in 12u8..=14 {
1088            input.extend_from_slice(&ts_packet(tag));
1089        }
1090
1091        let mut r = TsResync::new(cfg());
1092        let mut packets = r.feed(&input);
1093        let tags: Vec<u8> = packets.iter().map(|p| p[1]).collect();
1094        assert_eq!(tags, (1u8..=10).collect::<Vec<_>>());
1095        r.finish();
1096        packets.extend(r.take_tail_packets());
1097        let tags: Vec<u8> = packets.iter().map(|p| p[1]).collect();
1098        assert_eq!(tags, [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 12, 13, 14]);
1099        let stats = r.stats();
1100        assert_eq!(stats.packets, 13);
1101        assert_eq!(stats.dropped_bytes, TS_PACKET_SIZE as u64 + 1);
1102        let losses = r.take_losses();
1103        assert_one_loss_plus_leading(
1104            &losses,
1105            0,
1106            ResyncLoss {
1107                offset: 10 * TS_PACKET_SIZE as u64,
1108                dropped_bytes: TS_PACKET_SIZE as u64,
1109                packet_index: 10,
1110                truncated_tail: false,
1111            },
1112        );
1113    }
1114
1115    #[test]
1116    fn finish_emits_a_stream_shorter_than_the_lock_window() {
1117        let packets: Vec<_> = (1u8..=4).map(ts_packet).collect();
1118        let mut r = TsResync::new(cfg());
1119        assert!(r.feed(&concat_ts(&packets)).is_empty());
1120        r.finish();
1121        assert_eq!(r.take_tail_packets(), packets);
1122        assert!(r.take_tail_packets().is_empty());
1123        assert_eq!(r.stride(), Some(PacketStride::Ts188));
1124        assert_eq!(r.stats().dropped_bytes, 0);
1125    }
1126
1127    #[test]
1128    fn finish_emits_a_short_rs204_stream_stripped() {
1129        let mut stream = Vec::new();
1130        for tag in 1u8..=3 {
1131            stream.extend_from_slice(&rs_packet(tag, 0xFF));
1132        }
1133        let mut r = TsResync::new(cfg());
1134        assert!(r.feed(&stream).is_empty());
1135        r.finish();
1136        let packets = r.take_tail_packets();
1137        assert_eq!(packets, [ts_packet(1), ts_packet(2), ts_packet(3)]);
1138        assert_eq!(r.stride(), Some(PacketStride::Rs204));
1139    }
1140
1141    #[test]
1142    fn finish_does_not_lock_onto_a_stray_sync_byte_without_a_whole_packet() {
1143        let mut junk = vec![0x00u8; 100];
1144        junk[40] = TS_SYNC_BYTE;
1145        let mut r = TsResync::new(cfg());
1146        assert!(r.feed(&junk).is_empty());
1147        r.finish();
1148        assert!(r.take_tail_packets().is_empty());
1149        assert_eq!(r.stats().dropped_bytes, 100);
1150    }
1151
1152    #[test]
1153    fn finish_does_not_emit_a_trailing_partial_packet_starting_with_sync_byte() {
1154        let mut input = Vec::new();
1155        for tag in 1u8..=10 {
1156            input.extend_from_slice(&ts_packet(tag));
1157        }
1158        input.push(TS_SYNC_BYTE);
1159        input.extend_from_slice(&[0x11, 0x22, 0x33, 0x44]);
1160
1161        let mut r = TsResync::new(cfg());
1162        let mut packets = r.feed(&input);
1163        r.finish();
1164        packets.extend(r.take_tail_packets());
1165        let tags: Vec<u8> = packets.iter().map(|p| p[1]).collect();
1166        assert_eq!(tags, (1u8..=10).collect::<Vec<_>>());
1167        assert!(r.take_tail_packets().is_empty());
1168        let losses = r.take_losses();
1169        assert_one_loss_plus_leading(
1170            &losses,
1171            0,
1172            ResyncLoss {
1173                offset: 10 * TS_PACKET_SIZE as u64,
1174                dropped_bytes: 5,
1175                packet_index: 10,
1176                truncated_tail: true,
1177            },
1178        );
1179    }
1180
1181    #[test]
1182    fn the_callers_confirmations_and_strides_decide_the_lock() {
1183        let mut r = TsResync::new(two_ts_only());
1184        let two = concat_ts(&[ts_packet(1), ts_packet(2)]);
1185        assert_eq!(r.feed(&two).len(), 2, "two sync bytes lock a 188 stream");
1186        assert_eq!(r.stats().locks, 1);
1187
1188        let mut rs = TsResync::new(two_ts_only());
1189        let mut stream = Vec::new();
1190        for tag in 1u8..=6 {
1191            stream.extend_from_slice(&rs_packet(tag, 0xFF));
1192        }
1193        assert!(
1194            rs.feed(&stream).is_empty(),
1195            "204 is not a configured stride"
1196        );
1197
1198        let mut five = TsResync::new(cfg());
1199        assert!(
1200            five.feed(&two).is_empty(),
1201            "two sync bytes do not lock a five-confirmation resync"
1202        );
1203    }
1204
1205    #[test]
1206    fn dropping_unalignable_bytes_is_eager_and_counts_in_the_open_loss() {
1207        let mut r = TsResync::new(two_ts_only());
1208        assert!(r.feed(&[0x00u8; 500]).is_empty());
1209        assert_eq!(r.open_loss_bytes(), 500);
1210        assert_eq!(r.stats().locks, 0);
1211        let packets = concat_ts(&[ts_packet(1), ts_packet(2)]);
1212        assert_eq!(r.feed(&packets).len(), 2);
1213        let losses = r.take_losses();
1214        assert_eq!(losses.len(), 1);
1215        assert_eq!(losses[0].dropped_bytes, 500);
1216        assert_eq!(r.open_loss_bytes(), 0);
1217        assert_eq!(r.stats().dropped_bytes, 500);
1218    }
1219
1220    #[test]
1221    fn every_lock_counts_including_the_first_and_each_relock() {
1222        let mut r = TsResync::new(two_ts_only());
1223        let mut stream = concat_ts(&[ts_packet(1), ts_packet(2), ts_packet(3)]);
1224        stream[2 * TS_PACKET_SIZE] = 0x00;
1225        stream.extend_from_slice(&concat_ts(&[ts_packet(4), ts_packet(5), ts_packet(6)]));
1226        r.feed(&stream);
1227        assert_eq!(r.stats().locks, 2);
1228        assert_eq!(r.stats().resyncs, 1);
1229    }
1230
1231    #[test]
1232    fn a_datagram_is_framed_on_its_own() {
1233        let mut r = TsResync::new(two_ts_only());
1234        let mut datagram = vec![0x00u8; 7];
1235        datagram.extend_from_slice(&concat_ts(&[ts_packet(1), ts_packet(2)]));
1236        datagram.extend_from_slice(&[TS_SYNC_BYTE, 1, 2]);
1237        assert_eq!(r.feed_datagram(&datagram).len(), 2);
1238        let losses = r.take_losses();
1239        assert_eq!(losses.len(), 2);
1240        assert_eq!((losses[0].offset, losses[0].dropped_bytes), (0, 7));
1241        assert!(losses[1].truncated_tail);
1242        assert_eq!(losses[1].dropped_bytes, 3);
1243
1244        let mut bad = concat_ts(&[ts_packet(3), ts_packet(4), ts_packet(5), ts_packet(6)]);
1245        bad[2 * TS_PACKET_SIZE] = 0x00;
1246        assert_eq!(r.feed_datagram(&bad).len(), 2);
1247        assert_eq!(r.stats().resyncs, 1);
1248        assert_eq!(r.take_losses()[0].dropped_bytes, 2 * TS_PACKET_SIZE as u64);
1249
1250        assert_eq!(
1251            r.feed_datagram(&[TS_SYNC_BYTE]).len(),
1252            0,
1253            "a lone sync byte is no packet"
1254        );
1255        assert!(r.feed_datagram(&[0x00; 40]).is_empty());
1256        assert_eq!(
1257            r.take_losses().iter().map(|l| l.dropped_bytes).sum::<u64>(),
1258            41
1259        );
1260    }
1261}