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
#![allow(dead_code)]
//! PTS/DTS timestamp utilities and repair helpers.
//!
//! Provides `PtsDts` for carrying presentation/decode timestamps,
//! `PtsQueue` for reordering packets, and `PtsDtsRepair` for fixing
//! common timestamp pathologies (negative DTS, wrong ordering).
/// Presentation timestamp (PTS) and decode timestamp (DTS) pair.
///
/// Both values are in the container's native time base (e.g. 90 kHz ticks).
/// Either value may be absent (`None`) when not signalled by the container.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct PtsDts {
/// Presentation timestamp.
pub pts: Option<i64>,
/// Decode timestamp.
pub dts: Option<i64>,
}
impl PtsDts {
/// Creates a `PtsDts` with both values present.
#[must_use]
pub const fn new(pts: i64, dts: i64) -> Self {
Self {
pts: Some(pts),
dts: Some(dts),
}
}
/// Creates a `PtsDts` with only a PTS (no DTS field in the stream).
#[must_use]
pub const fn pts_only(pts: i64) -> Self {
Self {
pts: Some(pts),
dts: None,
}
}
/// Creates an empty `PtsDts` (both absent).
#[must_use]
pub const fn none() -> Self {
Self {
pts: None,
dts: None,
}
}
/// Returns `true` when a PTS value is present.
#[must_use]
pub fn has_pts(&self) -> bool {
self.pts.is_some()
}
/// Returns `true` when PTS and DTS are both present and equal.
#[must_use]
pub fn is_pts_dts_equal(&self) -> bool {
match (self.pts, self.dts) {
(Some(p), Some(d)) => p == d,
_ => false,
}
}
/// Returns the effective decode time: DTS when present, else PTS.
#[must_use]
pub fn effective_dts(&self) -> Option<i64> {
self.dts.or(self.pts)
}
/// Returns `true` if the DTS is negative (a common pathology in some muxers).
#[must_use]
pub fn has_negative_dts(&self) -> bool {
self.dts.is_some_and(|d| d < 0)
}
}
/// A packet entry stored in the reorder queue.
#[derive(Debug, Clone)]
pub struct PtsEntry {
/// Sequence number of the packet for stable sorting.
pub seq: u64,
/// Timestamp pair.
pub ts: PtsDts,
/// Arbitrary payload bytes (e.g. compressed frame data).
pub data: Vec<u8>,
}
/// A small reorder queue that sorts packets by their PTS before delivery.
#[derive(Debug, Default)]
pub struct PtsQueue {
entries: Vec<PtsEntry>,
seq_counter: u64,
}
impl PtsQueue {
/// Creates an empty `PtsQueue`.
#[must_use]
pub fn new() -> Self {
Self::default()
}
/// Inserts a packet into the queue.
pub fn push(&mut self, ts: PtsDts, data: Vec<u8>) {
let seq = self.seq_counter;
self.seq_counter += 1;
self.entries.push(PtsEntry { seq, ts, data });
}
/// Returns the number of entries in the queue.
#[must_use]
pub fn len(&self) -> usize {
self.entries.len()
}
/// Returns `true` when the queue is empty.
#[must_use]
pub fn is_empty(&self) -> bool {
self.entries.is_empty()
}
/// Returns a reference to the entry with the earliest PTS (or first
/// inserted when PTS is absent).
#[must_use]
pub fn earliest(&self) -> Option<&PtsEntry> {
self.entries.iter().min_by(|a, b| {
let pa = a.ts.pts.unwrap_or(i64::MAX);
let pb = b.ts.pts.unwrap_or(i64::MAX);
pa.cmp(&pb).then(a.seq.cmp(&b.seq))
})
}
/// Removes and returns the entry with the earliest PTS.
pub fn pop_earliest(&mut self) -> Option<PtsEntry> {
if self.entries.is_empty() {
return None;
}
let idx = self
.entries
.iter()
.enumerate()
.min_by(|(_, a), (_, b)| {
let pa = a.ts.pts.unwrap_or(i64::MAX);
let pb = b.ts.pts.unwrap_or(i64::MAX);
pa.cmp(&pb).then(a.seq.cmp(&b.seq))
})
.map(|(i, _)| i)?;
Some(self.entries.remove(idx))
}
/// Sorts all entries in the queue by PTS and returns them in order,
/// draining the queue.
pub fn reorder(&mut self) -> Vec<PtsEntry> {
let mut out = std::mem::take(&mut self.entries);
out.sort_by(|a, b| {
let pa = a.ts.pts.unwrap_or(i64::MAX);
let pb = b.ts.pts.unwrap_or(i64::MAX);
pa.cmp(&pb).then(a.seq.cmp(&b.seq))
});
out
}
}
/// Repairs common PTS/DTS pathologies in a stream of timestamps.
#[derive(Debug, Default)]
pub struct PtsDtsRepair {
repair_count: u64,
dts_offset: i64,
}
impl PtsDtsRepair {
/// Creates a new `PtsDtsRepair` instance.
#[must_use]
pub fn new() -> Self {
Self::default()
}
/// Returns the number of timestamps that have been repaired.
#[must_use]
pub fn repair_count(&self) -> u64 {
self.repair_count
}
/// Fixes a negative DTS by shifting it to 0 and recording the offset
/// applied for future packets.
///
/// If the DTS is already non-negative the input is returned unchanged.
pub fn fix_negative_dts(&mut self, ts: PtsDts) -> PtsDts {
if let Some(dts) = ts.dts {
if dts < 0 {
let shift = -dts;
self.dts_offset += shift;
self.repair_count += 1;
return PtsDts {
pts: ts.pts.map(|p| p + shift),
dts: Some(0),
};
}
}
ts
}
/// Applies the accumulated DTS offset to a new timestamp pair.
/// Use this after `fix_negative_dts` to keep subsequent packets aligned.
#[must_use]
pub fn apply_offset(&self, ts: PtsDts) -> PtsDts {
if self.dts_offset == 0 {
return ts;
}
PtsDts {
pts: ts.pts.map(|p| p + self.dts_offset),
dts: ts.dts.map(|d| d + self.dts_offset),
}
}
}
// ─── Unit tests ───────────────────────────────────────────────────────────────
#[cfg(test)]
mod tests {
use super::*;
// 1. has_pts – Some
#[test]
fn test_has_pts_some() {
let ts = PtsDts::new(100, 90);
assert!(ts.has_pts());
}
// 2. has_pts – None
#[test]
fn test_has_pts_none() {
let ts = PtsDts::none();
assert!(!ts.has_pts());
}
// 3. is_pts_dts_equal – equal
#[test]
fn test_is_pts_dts_equal_true() {
let ts = PtsDts::new(200, 200);
assert!(ts.is_pts_dts_equal());
}
// 4. is_pts_dts_equal – not equal
#[test]
fn test_is_pts_dts_equal_false() {
let ts = PtsDts::new(200, 180);
assert!(!ts.is_pts_dts_equal());
}
// 5. is_pts_dts_equal – DTS absent
#[test]
fn test_is_pts_dts_equal_no_dts() {
let ts = PtsDts::pts_only(200);
assert!(!ts.is_pts_dts_equal());
}
// 6. effective_dts prefers DTS
#[test]
fn test_effective_dts_prefers_dts() {
let ts = PtsDts::new(200, 180);
assert_eq!(ts.effective_dts(), Some(180));
}
// 7. effective_dts falls back to PTS
#[test]
fn test_effective_dts_falls_back_to_pts() {
let ts = PtsDts::pts_only(200);
assert_eq!(ts.effective_dts(), Some(200));
}
// 8. has_negative_dts
#[test]
fn test_has_negative_dts() {
let ts = PtsDts::new(0, -90);
assert!(ts.has_negative_dts());
}
// 9. PtsQueue empty
#[test]
fn test_queue_empty() {
let q = PtsQueue::new();
assert!(q.is_empty());
assert_eq!(q.len(), 0);
}
// 10. push / len
#[test]
fn test_queue_push_len() {
let mut q = PtsQueue::new();
q.push(PtsDts::new(100, 100), vec![1, 2, 3]);
assert_eq!(q.len(), 1);
}
// 11. earliest returns smallest PTS
#[test]
fn test_queue_earliest() {
let mut q = PtsQueue::new();
q.push(PtsDts::new(300, 300), vec![]);
q.push(PtsDts::new(100, 100), vec![]);
q.push(PtsDts::new(200, 200), vec![]);
assert_eq!(
q.earliest().expect("operation should succeed").ts.pts,
Some(100)
);
}
// 12. reorder drains and sorts
#[test]
fn test_queue_reorder() {
let mut q = PtsQueue::new();
q.push(PtsDts::new(300, 300), vec![]);
q.push(PtsDts::new(100, 100), vec![]);
q.push(PtsDts::new(200, 200), vec![]);
let sorted = q.reorder();
let pts_values: Vec<i64> = sorted
.iter()
.map(|e| e.ts.pts.expect("operation should succeed"))
.collect();
assert_eq!(pts_values, vec![100, 200, 300]);
assert!(q.is_empty());
}
// 13. fix_negative_dts shifts to zero
#[test]
fn test_fix_negative_dts() {
let mut repair = PtsDtsRepair::new();
let ts = PtsDts::new(0, -180);
let fixed = repair.fix_negative_dts(ts);
assert_eq!(fixed.dts, Some(0));
assert_eq!(repair.repair_count(), 1);
}
// 14. fix_negative_dts leaves positive DTS untouched
#[test]
fn test_fix_negative_dts_no_op() {
let mut repair = PtsDtsRepair::new();
let ts = PtsDts::new(100, 90);
let fixed = repair.fix_negative_dts(ts);
assert_eq!(fixed.dts, Some(90));
assert_eq!(repair.repair_count(), 0);
}
}