mpeg-ts 0.11.0

MPEG-2 Transport Stream framing (ITU-T H.222.0 / ISO/IEC 13818-1): TS packet, adaptation field, PCR, PSI section reassembly + packetisation, resync. no_std.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
//! Stateful TS byte-stream resynchroniser — ITU-T H.222.0 §2.4.3.2 (= ISO/IEC 13818-1 §2.4.3.2).
//!
//! Recovers 188-byte MPEG-TS packet alignment from an arbitrary byte stream
//! (file reads, UDP payloads) that may start mid-packet or contain leading
//! garbage.  Also detects 204-byte Reed-Solomon-coded packets (DVB RS-coded
//! outer forward-error-correction layer) and strips the 16 parity bytes, and
//! 192-byte M2TS (BDAV) source packets and strips their 4-byte
//! `TP_extra_header`, yielding standard 188-byte TS packets in every case.
//!
//! # Feature gate
//!
//! This module is only compiled when the `ts` feature is enabled (the
//! default), because it depends on the TS constants in [`crate::ts`].
//!
//! # Example
//!
//! ```
//! use core::num::NonZeroUsize;
//! use mpeg_ts::resync::{LOCK_CONFIRMATIONS, PacketStride, ResyncConfig, TsResync, Unlocked};
//!
//! let confirmations = NonZeroUsize::new(LOCK_CONFIRMATIONS).expect("non-zero");
//! let mut r = TsResync::new(ResyncConfig::new(confirmations, &PacketStride::ALL, Unlocked::KeepWindow));
//! // Feed arbitrary bytes (file chunks, UDP datagrams, etc.).
//! let packets: Vec<[u8; 188]> = r.feed(b"some raw bytes");
//! let stats = r.stats();
//! ```

use alloc::vec::Vec;
use core::num::NonZeroUsize;

use crate::ts::{TS_PACKET_SIZE, TS_SYNC_BYTE};

/// Reed-Solomon-coded TS packet size: 188-byte payload + 16 parity bytes
/// (DVB RS outer FEC, ISO/IEC 13818-1 §2.4.3.2 informative note).
pub const RS_PACKET_SIZE: usize = 204;

/// Number of Reed-Solomon parity bytes appended to a 204-byte packet.
pub const RS_PARITY_LEN: usize = RS_PACKET_SIZE - TS_PACKET_SIZE;

/// M2TS (BDAV) source packet size: a 4-byte `TP_extra_header`
/// (copy-permission indicator + arrival time stamp) followed by a 188-byte TS
/// packet.
pub const M2TS_PACKET_SIZE: usize = 192;

/// Length of the `TP_extra_header` that precedes each TS packet in M2TS.
pub const M2TS_EXTRA_HEADER_LEN: usize = M2TS_PACKET_SIZE - TS_PACKET_SIZE;

/// Consecutive sync bytes at the candidate stride that the broadcast capture
/// readers (files, TCP) require to declare lock; a caller states its own
/// number in [`ResyncConfig`].
pub const LOCK_CONFIRMATIONS: usize = 5;

/// What a [`TsResync`] does with bytes received before it has locked.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[non_exhaustive]
pub enum Unlocked {
    /// Keep up to `confirmations` of the largest stride's packets of
    /// not-yet-locked bytes in case a lock appears among them, and drop only
    /// the excess before them.
    KeepWindow,
    /// Drop at once every byte that can no longer start a lock; keep only the
    /// bytes from the first sync byte that more input could still confirm.
    DropUnalignable,
}

impl Unlocked {
    /// The policy's name.
    #[must_use]
    pub fn name(&self) -> &'static str {
        match self {
            Self::KeepWindow => "keep_window",
            Self::DropUnalignable => "drop_unalignable",
        }
    }
}
broadcast_core::impl_spec_display!(Unlocked);

/// What a [`TsResync`] must be told by its caller: how many consecutive sync
/// bytes declare lock, which packet strides it may lock onto, and what it does
/// with bytes before the lock. There is no default: a capture reader and a
/// datagram framer want different values.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct ResyncConfig {
    confirmations: NonZeroUsize,
    strides: &'static [PacketStride],
    unlocked: Unlocked,
}

impl ResyncConfig {
    /// A configuration locking after `confirmations` sync bytes at one of
    /// `strides`, tried in the given order. `strides` must not be empty.
    #[must_use]
    pub const fn new(
        confirmations: NonZeroUsize,
        strides: &'static [PacketStride],
        unlocked: Unlocked,
    ) -> Self {
        Self {
            confirmations,
            strides,
            unlocked,
        }
    }

    /// What happens to bytes before the lock.
    #[must_use]
    pub const fn unlocked(&self) -> Unlocked {
        self.unlocked
    }

    /// Sync bytes required to declare lock.
    #[must_use]
    pub const fn confirmations(&self) -> NonZeroUsize {
        self.confirmations
    }

    /// The strides that may be locked onto, in preference order.
    #[must_use]
    pub const fn strides(&self) -> &'static [PacketStride] {
        self.strides
    }
}

/// Detected packet size after locking.
#[non_exhaustive]
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[cfg_attr(feature = "serde", derive(serde::Serialize))]
pub enum PacketStride {
    /// Standard 188-byte TS packets (ISO/IEC 13818-1 §2.4.3.2).
    Ts188,
    /// 204-byte packets (188-byte TS + 16 Reed-Solomon parity bytes).
    Rs204,
    /// 192-byte M2TS (BDAV) source packets (4-byte `TP_extra_header` +
    /// 188-byte TS).
    M2ts192,
}

impl PacketStride {
    /// Every stride, in the order a lock prefers them: 188, 192, 204.
    pub const ALL: [PacketStride; 3] = [
        PacketStride::Ts188,
        PacketStride::M2ts192,
        PacketStride::Rs204,
    ];

    /// Only the standard 188-byte stride.
    pub const TS_ONLY: [PacketStride; 1] = [PacketStride::Ts188];

    /// Short machine-readable label for this stride.
    pub fn name(&self) -> &'static str {
        match self {
            PacketStride::Ts188 => "ts_188",
            PacketStride::Rs204 => "rs_204",
            PacketStride::M2ts192 => "m2ts_192",
        }
    }

    /// Bytes from one sync byte to the next at this stride.
    pub fn packet_len(&self) -> usize {
        match self {
            PacketStride::Ts188 => TS_PACKET_SIZE,
            PacketStride::Rs204 => RS_PACKET_SIZE,
            PacketStride::M2ts192 => M2TS_PACKET_SIZE,
        }
    }
}

broadcast_core::impl_spec_display!(PacketStride);

/// Counters accumulated during resynchronisation.
#[non_exhaustive]
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
#[cfg_attr(feature = "serde", derive(serde::Serialize))]
pub struct ResyncStats {
    /// Total 188-byte TS packets emitted.
    pub packets: u64,
    /// Times sync was lost and reacquired.
    pub resyncs: u64,
    /// Bytes skipped/dropped (junk before lock + sync-loss bytes).
    pub dropped_bytes: u64,
    /// Times a lock was acquired, the first included.
    pub locks: u64,
}

/// One span of bytes the resynchroniser discarded: either the bytes before
/// the first lock (a capture that starts mid-packet or on garbage), a
/// mid-stream sync loss, or a truncated trailing packet.
///
/// Drained with [`TsResync::take_losses`]; one entry per discarded span, so a
/// caller can report each skipped unit exactly once, and the spans account for
/// every byte in [`ResyncStats::dropped_bytes`].
#[non_exhaustive]
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[cfg_attr(feature = "serde", derive(serde::Serialize))]
pub struct ResyncLoss {
    /// Byte offset, from the first byte ever fed, where the discarded span starts.
    pub offset: u64,
    /// Length of the discarded span in bytes.
    pub dropped_bytes: u64,
    /// Number of whole packets emitted before this loss, i.e. the index the
    /// next intact packet will carry.
    pub packet_index: u64,
    /// `true` when the span is a truncated trailing packet found by
    /// [`TsResync::finish`] rather than a sync loss in mid-stream.
    pub truncated_tail: bool,
}

/// Stateful TS byte-stream resynchroniser (ISO/IEC 13818-1 §2.4.3.2).
///
/// Recovers 188-byte MPEG-TS packet alignment from an arbitrary byte stream
/// that may start mid-packet or contain junk, and detects 204-byte
/// Reed-Solomon-coded packets (stripping the 16 parity bytes) and 192-byte
/// M2TS source packets (stripping the 4-byte `TP_extra_header`).
///
/// Feed raw bytes with [`feed`](Self::feed); each call returns a `Vec` of
/// aligned 188-byte TS packets.  Bytes are buffered across calls so that
/// packet boundaries may span call boundaries freely.
///
/// Lock is declared after [`LOCK_CONFIRMATIONS`] consecutive sync bytes are
/// found at the candidate stride (188, 192 or 204).  On sync loss the resynchroniser
/// re-scans from the byte after the lost position.
///
/// Every discarded byte is reported as a [`ResyncLoss`], including the bytes
/// before the first lock: a caller that never sees a loss event therefore
/// never silently dropped input.
///
/// # Stats
///
/// [`stats`](Self::stats) returns cumulative counters (packets emitted,
/// resyncs, dropped bytes).
#[derive(Debug)]
pub struct TsResync {
    config: ResyncConfig,
    buf: Vec<u8>,
    /// Logical read head into `buf`; compacted periodically.
    head: usize,
    stride: Option<PacketStride>,
    stats: ResyncStats,
    /// Bytes already compacted away (stream offset of `buf[0]`).
    consumed: u64,
    /// Stream offset where the currently open sync loss began.
    open_loss: Option<u64>,
    /// Closed losses not yet drained by [`take_losses`](Self::take_losses).
    losses: Vec<ResyncLoss>,
    /// Aligned packets recovered by [`finish`](Self::finish), not yet drained
    /// by [`take_tail_packets`](Self::take_tail_packets).
    tail: Vec<[u8; TS_PACKET_SIZE]>,
    /// Bytes of the current stride still to skip after a packet emitted
    /// before its stride's trailing bytes arrived (M2TS: the next packet's
    /// `TP_extra_header`).
    skip: usize,
    /// Bytes of the open loss already counted in `stats.dropped_bytes` by
    /// the eager drop of unalignable bytes.
    eager_dropped: u64,
}

impl TsResync {
    /// Create a resynchroniser with an empty internal buffer, locking as
    /// `config` says.
    pub fn new(config: ResyncConfig) -> Self {
        Self {
            config,
            buf: Vec::new(),
            head: 0,
            stride: None,
            stats: ResyncStats::default(),
            consumed: 0,
            open_loss: None,
            losses: Vec::new(),
            tail: Vec::new(),
            skip: 0,
            eager_dropped: 0,
        }
    }

    /// Feed `data` and emit every newly-aligned 188-byte TS packet.
    ///
    /// For a 204-byte stream the 16 Reed-Solomon parity bytes are stripped,
    /// and for a 192-byte M2TS stream the 4-byte `TP_extra_header`; only the
    /// 188-byte TS packet is returned.  Bytes that cannot yet form
    /// a complete packet (or fall before lock) are buffered for the next call.
    ///
    /// **Drain [`take_losses`](Self::take_losses).** Every span discarded after
    /// lock is appended to an internal list (about 32-40 bytes each) that only
    /// `take_losses` empties; a caller that feeds forever and never drains it
    /// grows memory linearly with the number of re-locks on a lossy input.
    pub fn feed(&mut self, data: &[u8]) -> Vec<[u8; TS_PACKET_SIZE]> {
        let mut emitted = Vec::new();
        self.feed_into(data, &mut emitted);
        emitted
    }

    /// [`feed`](Self::feed) appending to a caller-owned `out` (not cleared),
    /// so a steady-state caller that reuses one `Vec` allocates nothing per
    /// call (audit r01-O4). The output capacity is reserved once from the
    /// buffered byte count instead of growing by doubling.
    ///
    /// Returns the number of packets appended.
    pub fn feed_into(&mut self, data: &[u8], emitted: &mut Vec<[u8; TS_PACKET_SIZE]>) -> usize {
        self.buf.extend_from_slice(data);
        let before = emitted.len();
        emitted.reserve((self.buf.len() - self.head) / TS_PACKET_SIZE);

        loop {
            match self.stride {
                None => {
                    if let Some((offset, s)) = find_sync(&self.buf[self.head..], &self.config) {
                        self.lock(offset, s);
                    } else {
                        match self.config.unlocked {
                            Unlocked::DropUnalignable => {
                                let keep_from =
                                    first_possible_lock(&self.buf[self.head..], &self.config);
                                if keep_from > 0 {
                                    self.open_loss
                                        .get_or_insert(self.consumed + self.head as u64);
                                    self.head += keep_from;
                                    self.stats.dropped_bytes += keep_from as u64;
                                    self.eager_dropped += keep_from as u64;
                                }
                            }
                            Unlocked::KeepWindow => {
                                let keep = LOCK_CONFIRMATIONS * RS_PACKET_SIZE;
                                let tail_len = self.buf.len() - self.head;
                                if tail_len > keep {
                                    let excess = tail_len - keep;
                                    self.stats.dropped_bytes += excess as u64;
                                    self.head += excess;
                                }
                            }
                        }
                        self.compact();
                        return emitted.len() - before;
                    }
                }
                Some(stride) => {
                    let s = stride.packet_len();
                    let tail_len = self.buf.len() - self.head;
                    if self.skip > 0 {
                        let n = self.skip.min(tail_len);
                        self.head += n;
                        self.skip -= n;
                        if self.skip > 0 {
                            self.compact();
                            return emitted.len() - before;
                        }
                        continue;
                    }
                    if tail_len < emit_len(stride) {
                        self.compact();
                        return emitted.len() - before;
                    }
                    if self.buf[self.head] == TS_SYNC_BYTE {
                        let mut packet = [0u8; TS_PACKET_SIZE];
                        packet.copy_from_slice(&self.buf[self.head..self.head + TS_PACKET_SIZE]);
                        emitted.push(packet);
                        let advance = s.min(tail_len);
                        self.head += advance;
                        self.skip = s - advance;
                        self.stats.packets += 1;
                    } else {
                        // Sync byte missing — record the loss and re-scan.
                        self.stats.resyncs += 1;
                        self.stats.dropped_bytes += 1;
                        self.open_loss
                            .get_or_insert(self.consumed + self.head as u64);
                        self.head += 1;
                        self.stride = None;
                    }
                }
            }
        }
    }

    /// Detected packet stride, or [`None`] before the stream has locked.
    pub fn stride(&self) -> Option<PacketStride> {
        self.stride
    }

    /// Drain the sync losses recorded since the last call (see [`ResyncLoss`]).
    ///
    /// This is the only thing that empties the internal loss list, which is
    /// unbounded by design (dropping a loss would hide data loss): call it
    /// regularly — e.g. after every [`feed`](Self::feed) — or the list grows
    /// with every re-lock on a lossy input. If you do not need the losses,
    /// still call it and discard the result.
    pub fn take_losses(&mut self) -> Vec<ResyncLoss> {
        core::mem::take(&mut self.losses)
    }

    fn lock(&mut self, offset: usize, stride: PacketStride) {
        self.stats.locks += 1;
        let eager = self.eager_dropped;
        self.eager_dropped = 0;
        self.open_loss
            .get_or_insert(self.consumed + self.head as u64);
        self.head += offset;
        self.stride = Some(stride);
        if let Some(start) = self.open_loss.take() {
            let end = self.consumed + self.head as u64;
            if end > start {
                self.stats.dropped_bytes += (end - start).saturating_sub(eager);
                self.losses.push(ResyncLoss {
                    offset: start,
                    dropped_bytes: end - start,
                    packet_index: self.stats.packets,
                    truncated_tail: false,
                });
            }
        }
    }

    /// Declare end of input. Packets that were still waiting for a full
    /// [`LOCK_CONFIRMATIONS`] window cannot be confirmed by more bytes, so the
    /// aligned packets that fill the rest of the input (a stream shorter than
    /// the window included) are kept; drain them with
    /// [`take_tail_packets`](Self::take_tail_packets), like
    /// [`take_losses`](Self::take_losses) for the losses.
    ///
    /// Also closes a sync loss that never re-locked and records a truncated
    /// trailing packet, both retrievable with
    /// [`take_losses`](Self::take_losses). The buffer is discarded.
    pub fn finish(&mut self) {
        if self.stride.is_none()
            && let Some((offset, s)) = find_tail_sync(&self.buf[self.head..], &self.config)
        {
            self.lock(offset, s);
            let mut emitted = core::mem::take(&mut self.tail);
            self.feed_into(&[], &mut emitted);
            self.tail = emitted;
        }
        let end = self.consumed + self.buf.len() as u64;
        if let Some(start) = self.open_loss.take() {
            self.losses.push(ResyncLoss {
                offset: start,
                dropped_bytes: end - start,
                packet_index: self.stats.packets,
                truncated_tail: false,
            });
        } else if self.stride.is_some() && self.head < self.buf.len() {
            self.losses.push(ResyncLoss {
                offset: self.consumed + self.head as u64,
                dropped_bytes: (self.buf.len() - self.head) as u64,
                packet_index: self.stats.packets,
                truncated_tail: true,
            });
        }
        self.stats.dropped_bytes += (self.buf.len() - self.head) as u64;
        self.eager_dropped = 0;
        self.head = self.buf.len();
        self.compact();
    }

    /// Drain the aligned packets [`finish`](Self::finish) recovered at end of
    /// input. Call it after `finish` and process the result like the output
    /// of [`feed`](Self::feed).
    pub fn take_tail_packets(&mut self) -> Vec<[u8; TS_PACKET_SIZE]> {
        core::mem::take(&mut self.tail)
    }

    /// Bytes of the sync loss still open (dropped so far and not yet closed
    /// by a re-lock), so a caller can account for them without waiting for
    /// [`take_losses`](Self::take_losses).
    pub fn open_loss_bytes(&self) -> u64 {
        self.open_loss
            .map_or(0, |start| self.consumed + self.head as u64 - start)
    }

    /// Datagram mode: `data` is one whole datagram, framed on its own. Any
    /// earlier state is forgotten, the first sync byte is accepted without a
    /// confirming successor when none fits (a lone `0x47` in a short
    /// datagram), every consecutive 188-byte packet is emitted, and the rest
    /// is dropped whole: after a packet whose sync byte is missing, or as a
    /// truncated tail. Each dropped span is a [`ResyncLoss`]. Only the 188-byte
    /// stride is framed; the configured strides and confirmations do not
    /// apply.
    pub fn feed_datagram(&mut self, data: &[u8]) -> Vec<[u8; TS_PACKET_SIZE]> {
        let base = self.consumed;
        self.consumed += data.len() as u64;
        self.buf.clear();
        self.head = 0;
        self.stride = None;
        self.open_loss = None;
        self.skip = 0;
        let mut out = Vec::new();
        let Some(start) = resync(data) else {
            self.record_loss(base, data.len(), false);
            return out;
        };
        self.record_loss(base, start, false);
        self.stats.locks += 1;
        let mut pos = start;
        while data.len() - pos >= TS_PACKET_SIZE {
            if data[pos] != TS_SYNC_BYTE {
                self.stats.resyncs += 1;
                self.record_loss(base + pos as u64, data.len() - pos, false);
                return out;
            }
            let mut packet = [0u8; TS_PACKET_SIZE];
            packet.copy_from_slice(&data[pos..pos + TS_PACKET_SIZE]);
            out.push(packet);
            self.stats.packets += 1;
            pos += TS_PACKET_SIZE;
        }
        self.record_loss(base + pos as u64, data.len() - pos, true);
        out
    }

    fn record_loss(&mut self, offset: u64, len: usize, truncated_tail: bool) {
        if len == 0 {
            return;
        }
        self.stats.dropped_bytes += len as u64;
        self.losses.push(ResyncLoss {
            offset,
            dropped_bytes: len as u64,
            packet_index: self.stats.packets,
            truncated_tail,
        });
    }

    /// Accumulated statistics.
    pub fn stats(&self) -> ResyncStats {
        self.stats
    }

    /// Compact the internal buffer by discarding consumed bytes.
    fn compact(&mut self) {
        if self.head > 0 {
            self.consumed += self.head as u64;
            self.buf.drain(..self.head);
            self.head = 0;
        }
    }
}

/// Scan `buf` for the smallest offset `o` such that stride `S` (tried 188
/// first, then 192, then 204) yields [`LOCK_CONFIRMATIONS`] consecutive sync bytes at
/// positions `o + k*S` for `k = 0 .. LOCK_CONFIRMATIONS`.
///
/// Returns `(offset, stride)` on success, or `None` if no lock is found.
fn find_sync(buf: &[u8], config: &ResyncConfig) -> Option<(usize, PacketStride)> {
    for o in 0..buf.len() {
        if buf[o] != TS_SYNC_BYTE {
            continue;
        }
        if let Some(stride) = config
            .strides
            .iter()
            .copied()
            .find(|stride| try_stride(buf, o, stride.packet_len(), config.confirmations.get()))
        {
            return Some((o, stride));
        }
    }
    None
}

/// The smallest offset at which a lock might still be confirmed once more
/// bytes arrive (its sync byte holds at every confirmation position the buffer
/// already covers, and at least one position lies beyond it), or `buf.len()`
/// when no offset can lock: everything before it is unalignable.
fn first_possible_lock(buf: &[u8], config: &ResyncConfig) -> usize {
    let confirmations = config.confirmations.get();
    (0..buf.len())
        .find(|&o| {
            buf[o] == TS_SYNC_BYTE
                && config.strides.iter().any(|stride| {
                    let s = stride.packet_len();
                    let mut open = false;
                    for k in 1..confirmations {
                        let pos = o + k * s;
                        if pos >= buf.len() {
                            open = true;
                            break;
                        }
                        if buf[pos] != TS_SYNC_BYTE {
                            return false;
                        }
                    }
                    open
                })
        })
        .unwrap_or(buf.len())
}

/// End-of-input counterpart of [`find_sync`]: the smallest offset whose
/// stride (188 first, then 192, then 204) holds a sync byte at every packet boundary
/// the buffer still covers, with at least one whole packet.
fn find_tail_sync(buf: &[u8], config: &ResyncConfig) -> Option<(usize, PacketStride)> {
    let chain = |o: usize, stride: PacketStride| {
        let need = emit_len(stride);
        o + need <= buf.len()
            && (o..buf.len())
                .step_by(stride.packet_len())
                .take_while(|pos| pos + need <= buf.len())
                .all(|pos| buf[pos] == TS_SYNC_BYTE)
    };
    (0..buf.len())
        .filter(|&o| buf[o] == TS_SYNC_BYTE)
        .find_map(|o| {
            config
                .strides
                .iter()
                .copied()
                .find(|&stride| chain(o, stride))
                .map(|stride| (o, stride))
        })
}

/// Bytes from a sync byte that complete one packet at `stride`: the 204-byte
/// stride's parity trails its packet, while the 4 bytes after an M2TS packet
/// belong to the next one.
fn emit_len(stride: PacketStride) -> usize {
    match stride {
        PacketStride::Rs204 => RS_PACKET_SIZE,
        PacketStride::Ts188 | PacketStride::M2ts192 => TS_PACKET_SIZE,
    }
}

/// Return `true` if `confirmations` consecutive sync bytes exist at
/// stride `s` starting from `offset` (the first is already known to be
/// [`TS_SYNC_BYTE`]).
fn try_stride(buf: &[u8], offset: usize, s: usize, confirmations: usize) -> bool {
    for k in 1..confirmations {
        let pos = offset + k * s;
        if pos >= buf.len() || buf[pos] != TS_SYNC_BYTE {
            return false;
        }
    }
    true
}

// ── Stateless datagram resync (dvb-stream origin) ───────────────────────────

/// Find the byte offset of the first confirmed `0x47` sync byte in `buf`,
/// accepting a lone sync byte when the buffer is too small to hold a
/// confirming packet.
///
/// "Confirmed" means either `buf[offset + TS_PACKET_SIZE] == TS_SYNC_BYTE`
/// (two-packet confirmation), or the buffer is too small for two packets
/// (best-effort single-sync-byte alignment).
///
/// Returns `None` when `buf` contains no `0x47` byte at all.
#[must_use]
pub fn resync(buf: &[u8]) -> Option<usize> {
    let mut i = 0;
    while i < buf.len() {
        if buf[i] == TS_SYNC_BYTE {
            let next = i + TS_PACKET_SIZE;
            if next < buf.len() {
                if buf[next] == TS_SYNC_BYTE {
                    return Some(i);
                }
                i += 1;
                continue;
            }
            return Some(i);
        }
        i += 1;
    }
    None
}

/// Find the byte offset of the first sync byte in `buf` confirmed by a
/// second sync byte exactly one packet later. Never accepts a lone sync byte.
#[must_use]
pub fn resync_confirmed(buf: &[u8]) -> Option<usize> {
    (0..buf.len().saturating_sub(TS_PACKET_SIZE))
        .find(|&i| buf[i] == TS_SYNC_BYTE && buf[i + TS_PACKET_SIZE] == TS_SYNC_BYTE)
}

/// Offset of the first `0x47` in `buf` that has no room for a confirming
/// sync byte one packet later.
#[must_use]
pub fn unconfirmed_candidate(buf: &[u8]) -> Option<usize> {
    let from = buf.len().saturating_sub(TS_PACKET_SIZE);
    buf[from..]
        .iter()
        .position(|&b| b == TS_SYNC_BYTE)
        .map(|i| from + i)
}

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

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

    fn two_ts_only() -> ResyncConfig {
        ResyncConfig::new(
            NonZeroUsize::MIN.saturating_add(1),
            &PacketStride::TS_ONLY,
            Unlocked::DropUnalignable,
        )
    }
    use alloc::vec;
    use alloc::vec::Vec;
    extern crate std;

    /// Build a 188-byte TS packet starting with `TS_SYNC_BYTE` followed by
    /// `tag` (repeated).  All non-sync bytes are kept away from `0x47` so
    /// that no false lock occurs in the fixture data.
    fn ts_packet(tag: u8) -> [u8; TS_PACKET_SIZE] {
        assert_ne!(tag, TS_SYNC_BYTE, "tag must not equal sync byte");
        let mut pkt = [tag; TS_PACKET_SIZE];
        pkt[0] = TS_SYNC_BYTE;
        pkt
    }

    /// Build a 204-byte RS-coded packet: 188-byte TS payload (with `ts_tag`)
    /// plus 16 parity bytes filled with `parity` (must not be `0x47`).
    fn rs_packet(ts_tag: u8, parity: u8) -> [u8; RS_PACKET_SIZE] {
        assert_ne!(ts_tag, TS_SYNC_BYTE);
        assert_ne!(parity, TS_SYNC_BYTE);
        let mut pkt = [parity; RS_PACKET_SIZE];
        pkt[0] = TS_SYNC_BYTE;
        pkt[1..TS_PACKET_SIZE].fill(ts_tag);
        pkt
    }

    /// Concatenate several 188-byte packet arrays into a flat `Vec<u8>`.
    fn concat_ts(packets: &[[u8; TS_PACKET_SIZE]]) -> Vec<u8> {
        let mut v = Vec::with_capacity(packets.len() * TS_PACKET_SIZE);
        for p in packets {
            v.extend_from_slice(p);
        }
        v
    }

    // ------------------------------------------------------------------
    // Test 1 — aligned 188-byte passthrough
    // ------------------------------------------------------------------
    #[test]
    fn lone_sync_byte_accepted_by_resync_not_confirmed() {
        let buf = [TS_SYNC_BYTE];
        assert_eq!(resync(&buf), Some(0));
        assert_eq!(resync_confirmed(&buf), None);
    }

    #[test]
    fn aligned_188_passthrough() {
        let packets: Vec<_> = (0u8..5).map(|i| ts_packet(i + 1)).collect();
        let data = concat_ts(&packets);

        let mut r = TsResync::new(cfg());
        let emitted = r.feed(&data);

        assert_eq!(emitted.len(), 5);
        for (i, (e, p)) in emitted.iter().zip(packets.iter()).enumerate() {
            assert_eq!(e, p, "packet {i} mismatch");
        }
        assert_eq!(r.stride(), Some(PacketStride::Ts188));
        let s = r.stats();
        assert_eq!(s.packets, 5);
        assert_eq!(s.resyncs, 0);
        assert_eq!(s.dropped_bytes, 0);
    }

    // ------------------------------------------------------------------
    // Test 2 — lock only after LOCK_CONFIRMATIONS sync bytes
    // ------------------------------------------------------------------
    #[test]
    fn requires_n_confirmations_before_lock() {
        // Pin the default lock window. The hardcoded 4-vs-5 boundary below only
        // bites the threshold when this is 5 — assert it explicitly so a change
        // to the default (or to this test's literals) cannot silently pass.
        assert_eq!(
            LOCK_CONFIRMATIONS, 5,
            "this test pins the default lock window of 5"
        );

        // FOUR confirming, stride-aligned packets are one short of the window:
        // only four sync bytes sit at the 188-stride boundaries, so the
        // resynchroniser must NOT lock and must emit nothing (it buffers).
        let four = concat_ts(&(1u8..=4).map(ts_packet).collect::<Vec<_>>());
        let mut r = TsResync::new(cfg());
        assert_eq!(
            r.feed(&four).len(),
            0,
            "4 confirmations (< 5) must not lock or emit"
        );
        assert_eq!(r.stride(), None, "stride must remain None below the window");

        // The FIFTH stride-aligned sync byte completes the window → lock.
        let mut out = r.feed(&ts_packet(5));
        out.extend(r.feed(&[]));
        assert!(
            r.stride().is_some(),
            "the 5th confirmation must trigger lock"
        );
        // Once locked, the buffered packets are emitted (5 fed, all aligned).
        assert_eq!(out.len(), 5, "all five aligned packets emit once locked");
    }

    // ------------------------------------------------------------------
    // Test 3 — junk prefix: leading garbage dropped, correct count returned
    // ------------------------------------------------------------------
    #[test]
    fn junk_prefix_correct_dropped_count() {
        let pkts: Vec<_> = (0u8..6).map(|i| ts_packet(i + 1)).collect();
        let stream = concat_ts(&pkts);

        let junk_len = 7usize;
        let mut data: Vec<u8> = vec![0x00; junk_len];
        data.extend_from_slice(&stream);

        let mut r = TsResync::new(cfg());
        let emitted = r.feed(&data);

        assert_eq!(emitted.len(), 6);
        for (i, (e, p)) in emitted.iter().zip(pkts.iter()).enumerate() {
            assert_eq!(*e, *p, "packet {i} mismatch after junk prefix");
        }
        let s = r.stats();
        assert_eq!(
            s.dropped_bytes, junk_len as u64,
            "dropped bytes must equal junk prefix"
        );
        assert_eq!(s.resyncs, 0);
        assert_eq!(s.packets, 6);
    }

    // ------------------------------------------------------------------
    // Test 4 — mid-stream sync loss and reacquisition
    // ------------------------------------------------------------------
    #[test]
    fn midstream_loss_resync() {
        // Need > LOCK_CONFIRMATIONS clean packets before and after the stray
        // byte so the stream locks, loses sync, and re-locks.
        let pkts: Vec<_> = (0u8..14).map(|i| ts_packet(i + 1)).collect();
        let clean = concat_ts(&pkts);

        // Insert a single stray byte 12 bytes into packet 7.
        let insert_at = 7 * TS_PACKET_SIZE + 12;
        let mut data = clean[..insert_at].to_vec();
        data.push(0x00);
        data.extend_from_slice(&clean[insert_at..]);

        let mut r = TsResync::new(cfg());
        let emitted = r.feed(&data);

        let s = r.stats();
        assert!(
            s.resyncs >= 1,
            "mid-stream corruption must trigger a resync, got {}",
            s.resyncs
        );
        assert_eq!(emitted[0], pkts[0], "first emitted packet is P0");
        assert!(
            emitted.len() >= 10,
            "should recover and emit most packets, got {}",
            emitted.len()
        );
    }

    // ------------------------------------------------------------------
    // Test 5 — 204-byte RS-coded packets detected + RS stripped
    // ------------------------------------------------------------------
    #[test]
    fn rs204_detected_and_stripped() {
        let mut stream = Vec::new();
        let mut expected = Vec::new();
        for i in 0u8..6 {
            let tag = i + 1;
            let rs = rs_packet(tag, 0xFF);
            stream.extend_from_slice(&rs);
            expected.push(ts_packet(tag));
        }

        let mut r = TsResync::new(cfg());
        let emitted = r.feed(&stream);

        assert_eq!(emitted.len(), 6, "RS-coded stream must emit 6 packets");
        assert_eq!(
            r.stride(),
            Some(PacketStride::Rs204),
            "stride must be Rs204"
        );
        for (i, (e, p)) in emitted.iter().zip(expected.iter()).enumerate() {
            assert_eq!(e, p, "RS-stripped packet {i} mismatch");
        }
        // Confirm the emitted 188-byte packets are parseable by TsPacket.
        for (i, pkt) in emitted.iter().enumerate() {
            crate::ts::TsPacket::parse(pkt)
                .unwrap_or_else(|e| panic!("RS-stripped packet {i} TsPacket::parse failed: {e}"));
        }
        let s = r.stats();
        assert_eq!(s.packets, 6);
        assert_eq!(s.resyncs, 0);
        assert_eq!(s.dropped_bytes, 0);
    }

    // ------------------------------------------------------------------
    // Test 6 — aligned 188 stream yields same packets as plain chunks(188)
    //   (equivalence: fixture-less variant using synthetic data)
    // ------------------------------------------------------------------
    /// The losses are one per discarded span, in stream order: the leading
    /// garbage (if any) and the mid-stream sync loss or truncated tail.
    fn assert_one_loss_plus_leading(losses: &[ResyncLoss], leading: u64, expected: ResyncLoss) {
        let expected_leading = usize::from(leading > 0);
        assert_eq!(losses.len(), expected_leading + 1, "{losses:?}");
        if leading > 0 {
            assert_eq!(losses[0].offset, 0);
            assert_eq!(losses[0].dropped_bytes, leading);
            assert!(!losses[0].truncated_tail);
        }
        assert_eq!(losses[expected_leading], expected);
    }

    #[test]
    fn broken_sync_byte_after_lock_is_one_loss_with_offset() {
        let mut bytes = Vec::new();
        for t in 1..=12u8 {
            bytes.extend_from_slice(&ts_packet(t));
        }
        bytes[5 * TS_PACKET_SIZE] = 0x00;
        let mut r = TsResync::new(cfg());
        let got = r.feed(&bytes);
        assert_eq!(got.len(), 11);
        r.finish();
        let losses = r.take_losses();
        assert_one_loss_plus_leading(
            &losses,
            0,
            ResyncLoss {
                offset: 5 * TS_PACKET_SIZE as u64,
                dropped_bytes: TS_PACKET_SIZE as u64,
                packet_index: 5,
                truncated_tail: false,
            },
        );
    }

    #[test]
    fn leading_junk_at_the_first_lock_is_a_loss() {
        let mut bytes = vec![0x11; 30];
        for t in 1..=8u8 {
            bytes.extend_from_slice(&ts_packet(t));
        }
        let mut r = TsResync::new(cfg());
        assert_eq!(r.feed(&bytes).len(), 8);
        let losses = r.take_losses();
        assert_eq!(losses.len(), 1, "{losses:?}");
        assert_eq!(losses[0].offset, 0);
        assert_eq!(losses[0].dropped_bytes, 30);
        assert_eq!(losses[0].packet_index, 0);
        assert!(!losses[0].truncated_tail);
    }

    #[test]
    fn bulk_discarded_junk_before_lock_is_a_loss() {
        let junk_len = LOCK_CONFIRMATIONS * RS_PACKET_SIZE + 7;
        let mut bytes = vec![0x00; junk_len];
        for t in 1..=8u8 {
            bytes.extend_from_slice(&ts_packet(t));
        }
        let mut r = TsResync::new(cfg());
        assert_eq!(r.feed(&bytes).len(), 8);
        let losses = r.take_losses();
        assert_eq!(losses.len(), 1, "{losses:?}");
        assert_eq!(losses[0].offset, 0);
        assert_eq!(losses[0].dropped_bytes, junk_len as u64);
        assert_eq!(r.stats().dropped_bytes, junk_len as u64);
    }

    #[test]
    fn leading_junk_is_a_loss_and_so_is_the_truncated_tail() {
        let mut bytes = vec![0x11; 30];
        for t in 1..=8u8 {
            bytes.extend_from_slice(&ts_packet(t));
        }
        bytes.extend_from_slice(&[0x22; 50]);
        let mut r = TsResync::new(cfg());
        let _ = r.feed(&bytes);
        r.finish();
        let losses = r.take_losses();
        assert_one_loss_plus_leading(
            &losses,
            30,
            ResyncLoss {
                offset: 30 + 8 * TS_PACKET_SIZE as u64,
                dropped_bytes: 50,
                packet_index: 8,
                truncated_tail: true,
            },
        );
    }

    #[test]
    fn aligned_188_matches_plain_chunks() {
        let pkts: Vec<_> = (0u8..10).map(|i| ts_packet(i + 1)).collect();
        let data = concat_ts(&pkts);

        // Oracle: plain chunks(188) filtered by sync byte.
        let oracle: Vec<[u8; TS_PACKET_SIZE]> = data
            .chunks_exact(TS_PACKET_SIZE)
            .filter(|c| c[0] == TS_SYNC_BYTE)
            .map(|c| c.try_into().unwrap())
            .collect();

        let mut r = TsResync::new(cfg());
        let emitted = r.feed(&data);

        assert_eq!(emitted.len(), oracle.len(), "count mismatch");
        for (i, (e, o)) in emitted.iter().zip(oracle.iter()).enumerate() {
            assert_eq!(e, o, "packet {i} differs from chunks-oracle");
        }
    }

    // ------------------------------------------------------------------
    // Test 7 — chunked feed equivalence (same result in small increments)
    // ------------------------------------------------------------------
    #[test]
    fn chunked_feed_equivalence() {
        let pkts: Vec<_> = (0u8..6).map(|i| ts_packet(i + 1)).collect();
        let stream = concat_ts(&pkts);

        let whole = {
            let mut r = TsResync::new(cfg());
            r.feed(&stream)
        };

        let chunked = {
            let mut r = TsResync::new(cfg());
            let mut out = Vec::new();
            for chunk in stream.chunks(100) {
                out.extend(r.feed(chunk));
            }
            out
        };

        assert_eq!(whole.len(), chunked.len());
        for (i, (w, c)) in whole.iter().zip(chunked.iter()).enumerate() {
            assert_eq!(w, c, "packet {i} mismatch");
        }
    }

    // ------------------------------------------------------------------
    // Test 8 — fixture-based: m6-single.ts differential
    //   feeding the real fixture through TsResync must yield the same
    //   188-byte packets as plain chunks_exact(188) + sync-byte filter.
    // ------------------------------------------------------------------
    #[test]
    fn fixture_m6_matches_plain_chunks() {
        let path = test_fixtures::path("ts/m6-single.ts");
        let data = std::fs::read(path).expect("m6-single.ts fixture not found");

        // Oracle: plain aligned 188-byte reads.
        let oracle: Vec<[u8; TS_PACKET_SIZE]> = data
            .chunks_exact(TS_PACKET_SIZE)
            .filter(|c| c[0] == TS_SYNC_BYTE)
            .map(|c| c.try_into().unwrap())
            .collect();
        assert!(!oracle.is_empty(), "oracle empty — fixture empty?");

        let mut r = TsResync::new(cfg());
        let emitted = r.feed(&data);

        assert_eq!(
            emitted.len(),
            oracle.len(),
            "packet count: TsResync={} oracle={}",
            emitted.len(),
            oracle.len()
        );
        for (i, (e, o)) in emitted.iter().zip(oracle.iter()).enumerate() {
            assert_eq!(e, o, "packet {i} mismatch vs oracle");
        }
    }

    #[test]
    fn finish_emits_the_aligned_packets_after_a_corrupt_sync_byte() {
        let mut input = Vec::new();
        for tag in 1u8..=10 {
            input.extend_from_slice(&ts_packet(tag));
        }
        let mut bad = ts_packet(11);
        bad[0] = 0x00;
        input.extend_from_slice(&bad);
        for tag in 12u8..=14 {
            input.extend_from_slice(&ts_packet(tag));
        }

        let mut r = TsResync::new(cfg());
        let mut packets = r.feed(&input);
        let tags: Vec<u8> = packets.iter().map(|p| p[1]).collect();
        assert_eq!(tags, (1u8..=10).collect::<Vec<_>>());
        r.finish();
        packets.extend(r.take_tail_packets());
        let tags: Vec<u8> = packets.iter().map(|p| p[1]).collect();
        assert_eq!(tags, [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 12, 13, 14]);
        let stats = r.stats();
        assert_eq!(stats.packets, 13);
        assert_eq!(stats.dropped_bytes, TS_PACKET_SIZE as u64 + 1);
        let losses = r.take_losses();
        assert_one_loss_plus_leading(
            &losses,
            0,
            ResyncLoss {
                offset: 10 * TS_PACKET_SIZE as u64,
                dropped_bytes: TS_PACKET_SIZE as u64,
                packet_index: 10,
                truncated_tail: false,
            },
        );
    }

    #[test]
    fn finish_emits_a_stream_shorter_than_the_lock_window() {
        let packets: Vec<_> = (1u8..=4).map(ts_packet).collect();
        let mut r = TsResync::new(cfg());
        assert!(r.feed(&concat_ts(&packets)).is_empty());
        r.finish();
        assert_eq!(r.take_tail_packets(), packets);
        assert!(r.take_tail_packets().is_empty());
        assert_eq!(r.stride(), Some(PacketStride::Ts188));
        assert_eq!(r.stats().dropped_bytes, 0);
    }

    #[test]
    fn finish_emits_a_short_rs204_stream_stripped() {
        let mut stream = Vec::new();
        for tag in 1u8..=3 {
            stream.extend_from_slice(&rs_packet(tag, 0xFF));
        }
        let mut r = TsResync::new(cfg());
        assert!(r.feed(&stream).is_empty());
        r.finish();
        let packets = r.take_tail_packets();
        assert_eq!(packets, [ts_packet(1), ts_packet(2), ts_packet(3)]);
        assert_eq!(r.stride(), Some(PacketStride::Rs204));
    }

    #[test]
    fn finish_does_not_lock_onto_a_stray_sync_byte_without_a_whole_packet() {
        let mut junk = vec![0x00u8; 100];
        junk[40] = TS_SYNC_BYTE;
        let mut r = TsResync::new(cfg());
        assert!(r.feed(&junk).is_empty());
        r.finish();
        assert!(r.take_tail_packets().is_empty());
        assert_eq!(r.stats().dropped_bytes, 100);
    }

    #[test]
    fn finish_does_not_emit_a_trailing_partial_packet_starting_with_sync_byte() {
        let mut input = Vec::new();
        for tag in 1u8..=10 {
            input.extend_from_slice(&ts_packet(tag));
        }
        input.push(TS_SYNC_BYTE);
        input.extend_from_slice(&[0x11, 0x22, 0x33, 0x44]);

        let mut r = TsResync::new(cfg());
        let mut packets = r.feed(&input);
        r.finish();
        packets.extend(r.take_tail_packets());
        let tags: Vec<u8> = packets.iter().map(|p| p[1]).collect();
        assert_eq!(tags, (1u8..=10).collect::<Vec<_>>());
        assert!(r.take_tail_packets().is_empty());
        let losses = r.take_losses();
        assert_one_loss_plus_leading(
            &losses,
            0,
            ResyncLoss {
                offset: 10 * TS_PACKET_SIZE as u64,
                dropped_bytes: 5,
                packet_index: 10,
                truncated_tail: true,
            },
        );
    }

    #[test]
    fn the_callers_confirmations_and_strides_decide_the_lock() {
        let mut r = TsResync::new(two_ts_only());
        let two = concat_ts(&[ts_packet(1), ts_packet(2)]);
        assert_eq!(r.feed(&two).len(), 2, "two sync bytes lock a 188 stream");
        assert_eq!(r.stats().locks, 1);

        let mut rs = TsResync::new(two_ts_only());
        let mut stream = Vec::new();
        for tag in 1u8..=6 {
            stream.extend_from_slice(&rs_packet(tag, 0xFF));
        }
        assert!(
            rs.feed(&stream).is_empty(),
            "204 is not a configured stride"
        );

        let mut five = TsResync::new(cfg());
        assert!(
            five.feed(&two).is_empty(),
            "two sync bytes do not lock a five-confirmation resync"
        );
    }

    #[test]
    fn dropping_unalignable_bytes_is_eager_and_counts_in_the_open_loss() {
        let mut r = TsResync::new(two_ts_only());
        assert!(r.feed(&[0x00u8; 500]).is_empty());
        assert_eq!(r.open_loss_bytes(), 500);
        assert_eq!(r.stats().locks, 0);
        let packets = concat_ts(&[ts_packet(1), ts_packet(2)]);
        assert_eq!(r.feed(&packets).len(), 2);
        let losses = r.take_losses();
        assert_eq!(losses.len(), 1);
        assert_eq!(losses[0].dropped_bytes, 500);
        assert_eq!(r.open_loss_bytes(), 0);
        assert_eq!(r.stats().dropped_bytes, 500);
    }

    #[test]
    fn every_lock_counts_including_the_first_and_each_relock() {
        let mut r = TsResync::new(two_ts_only());
        let mut stream = concat_ts(&[ts_packet(1), ts_packet(2), ts_packet(3)]);
        stream[2 * TS_PACKET_SIZE] = 0x00;
        stream.extend_from_slice(&concat_ts(&[ts_packet(4), ts_packet(5), ts_packet(6)]));
        r.feed(&stream);
        assert_eq!(r.stats().locks, 2);
        assert_eq!(r.stats().resyncs, 1);
    }

    #[test]
    fn a_datagram_is_framed_on_its_own() {
        let mut r = TsResync::new(two_ts_only());
        let mut datagram = vec![0x00u8; 7];
        datagram.extend_from_slice(&concat_ts(&[ts_packet(1), ts_packet(2)]));
        datagram.extend_from_slice(&[TS_SYNC_BYTE, 1, 2]);
        assert_eq!(r.feed_datagram(&datagram).len(), 2);
        let losses = r.take_losses();
        assert_eq!(losses.len(), 2);
        assert_eq!((losses[0].offset, losses[0].dropped_bytes), (0, 7));
        assert!(losses[1].truncated_tail);
        assert_eq!(losses[1].dropped_bytes, 3);

        let mut bad = concat_ts(&[ts_packet(3), ts_packet(4), ts_packet(5), ts_packet(6)]);
        bad[2 * TS_PACKET_SIZE] = 0x00;
        assert_eq!(r.feed_datagram(&bad).len(), 2);
        assert_eq!(r.stats().resyncs, 1);
        assert_eq!(r.take_losses()[0].dropped_bytes, 2 * TS_PACKET_SIZE as u64);

        assert_eq!(
            r.feed_datagram(&[TS_SYNC_BYTE]).len(),
            0,
            "a lone sync byte is no packet"
        );
        assert!(r.feed_datagram(&[0x00; 40]).is_empty());
        assert_eq!(
            r.take_losses().iter().map(|l| l.dropped_bytes).sum::<u64>(),
            41
        );
    }
}