forge
Explore
Log in

Don't you dare go Hollow

edith_codecs

Clone
★ 0

0 watching0 forksRust370.3 MiB9b67700Tahinli3 days ago4021 commits

ps.rs1238 lines, 40.2 KiBHistoryRawDownload
1//! Program streams, system streams and raw video: packet-for-packet parity with
2//! ffmpeg's demux on ffmpeg-made files (bytes, sizes, timestamps, key flags),
3//! duration, seek exactness, SCR resets, PTS wraps and damaged files.
4//!
5//! Fixtures are generated at test time from synthetic sources; the tests skip when
6//! ffmpeg is missing and fail instead under `EC_REQUIRE_FIXTURES`.
7
8use std::fs::File;
9use std::io::BufReader;
10use std::path::{Path, PathBuf};
11
12use crate::common::*;
13use ec_core::registry::{Demuxer, SeekMode};
14use ec_core::{CodecId, TimeBase, Timestamp};
15use ec_mpegts::{PsDemuxer, PsKind};
16
17type D = PsDemuxer<BufReader<File>>;
18
19fn open_ps(path: &Path) -> D {
20 PsDemuxer::new(BufReader::new(File::open(path).unwrap())).unwrap()
21}
22
23fn read_ps(d: &mut D) -> Vec<Pkt> {
24 let mut v = Vec::new();
25 while let Ok(p) = d.next_packet() {
26 v.push(Pkt {
27 stream: p.stream,
28 pts: p.pts,
29 dts: p.dts,
30 key: p.flags.keyframe,
31 off: d.last_packet_offset(),
32 data: p.data.to_vec(),
33 });
34 }
35 v
36}
37
38/// ffprobe's stream `id` for our (stream_id, substream) key.
39fn ffid(key: u16) -> u16 {
40 match (key >> 8) as u8 {
41 0xBD => key & 0xFF,
42 id => 0x100 | u16::from(id),
43 }
44}
45
46const V2: &[&str] = &[
47 "-c:v",
48 "mpeg2video",
49 "-g",
50 "12",
51 "-bf",
52 "2",
53 "-b:v",
54 "1500k",
55];
56
57fn src(extra_audio: &[&str]) -> Vec<&'static str> {
58 let mut a: Vec<&str> = VIDEO_SRC.to_vec();
59 a.extend_from_slice(AUDIO_SRC);
60 let _ = extra_audio;
61 a
62}
63
64fn mkps(name: &str, video: &[&str], audio: &[&str], mux: &[&str]) -> Option<PathBuf> {
65 let mut a = src(audio);
66 a.extend_from_slice(video);
67 a.extend_from_slice(audio);
68 a.extend_from_slice(mux);
69 fixture(name, &a)
70}
71
72/// Parity of every exposed stream with ffprobe/ffmpeg. `raw` files (no container
73/// timestamps) compare sizes, flags and bytes only.
74fn parity(path: &Path, slack: i64) {
75 let mut d = open_ps(path);
76 let raw = d.kind() == PsKind::VideoElementary;
77 let pkts = read_ps(&mut d);
78 let mut rows = ffprobe_rows(path);
79 if raw {
80 // A raw stream has no ids: its one stream is stream 0.
81 rows.insert(ffid(d.stream_key(0).unwrap()), (0, raw_rows(path)));
82 }
83 assert!(!d.streams().is_empty(), "{path:?}: no streams");
84 for s in d.streams() {
85 let key = d.stream_key(s.index).unwrap();
86 let (si, rows) = rows
87 .get(&ffid(key))
88 .unwrap_or_else(|| panic!("{path:?}: ffprobe lacks id {:#x}", ffid(key)));
89 let mine: Vec<&Pkt> = pkts.iter().filter(|p| p.stream == s.index).collect();
90 let name = s.params.codec.name();
91 let pcm = matches!(s.params.codec, CodecId::PcmS16Be | CodecId::PcmS24Le);
92 if !pcm {
93 assert_eq!(mine.len(), rows.len(), "{path:?} {name} packet count");
94 }
95 if !pcm && !raw {
96 let md0 = mine[0].dts.or(mine[0].pts).unwrap();
97 let rd0 = rows[0].dts.or(rows[0].pts).unwrap();
98 for (i, (m, r)) in mine.iter().zip(rows).enumerate() {
99 assert_eq!(m.data.len(), r.size, "{path:?} {name} #{i} size");
100 // ffmpeg leaves the pts of a picture without a timestamp unknown; the
101 // demuxer derives it from the temporal reference.
102 let near = |a: Option<i64>, b: Option<i64>| match (a, b) {
103 (Some(a), Some(b)) => (a - b).abs() <= if m.dts.is_none() { slack } else { 0 },
104 (Some(_), None) => true,
105 (a, b) => a == b,
106 };
107 let (mp, rp) = (m.pts.map(|v| v - md0), r.pts.map(|v| v - rd0));
108 assert!(near(mp, rp), "{path:?} {name} #{i} pts {mp:?} vs {rp:?}");
109 let (mdt, rdt) = (
110 m.dts.or(m.pts).map(|v| v - md0),
111 r.dts.or(r.pts).map(|v| v - rd0),
112 );
113 assert!(
114 near(mdt, rdt),
115 "{path:?} {name} #{i} dts {mdt:?} vs {rdt:?}"
116 );
117 assert_eq!(m.key, r.key, "{path:?} {name} #{i} keyframe");
118 }
119 } else if raw {
120 for (i, (m, r)) in mine.iter().zip(rows).enumerate() {
121 assert_eq!(m.data.len(), r.size, "{path:?} {name} #{i} size");
122 assert_eq!(m.key, r.key, "{path:?} {name} #{i} keyframe");
123 }
124 }
125 let bytes: Vec<u8> = mine.iter().flat_map(|p| p.data.iter().copied()).collect();
126 let theirs = match s.params.codec {
127 CodecId::PcmS16Be => ffmpeg_pcm_s16be(path, *si),
128 CodecId::PcmS24Le => ffmpeg_pcm(path, *si, "s24le"),
129 _ => ffmpeg_bytes(path, *si),
130 };
131 eprintln!(
132 "{} {name}: {} packets, {} bytes",
133 path.file_name().unwrap().to_string_lossy(),
134 mine.len(),
135 bytes.len()
136 );
137 // DVD LPCM: ffmpeg rounds the last packet's partial block up.
138 let theirs = if s.params.codec == CodecId::PcmS24Le
139 && theirs.len() >= bytes.len()
140 && theirs.len() - bytes.len() <= 12
141 {
142 theirs[..bytes.len()].to_vec()
143 } else {
144 theirs
145 };
146 assert!(
147 bytes == theirs,
148 "{path:?} {name}: bytes differ ({} vs {})",
149 bytes.len(),
150 theirs.len()
151 );
152 }
153}
154
155fn raw_rows(path: &Path) -> Vec<Row> {
156 let o = std::process::Command::new("ffprobe")
157 .args([
158 "-v",
159 "error",
160 "-show_entries",
161 "packet=size,flags",
162 "-of",
163 "csv=p=0",
164 ])
165 .arg(path)
166 .output()
167 .unwrap();
168 String::from_utf8_lossy(&o.stdout)
169 .lines()
170 .map(|l| {
171 let f: Vec<&str> = l.split(',').collect();
172 Row {
173 pid: 0,
174 pts: None,
175 dts: None,
176 dur: None,
177 size: f[0].parse().unwrap(),
178 key: f[1].starts_with('K'),
179 }
180 })
181 .collect()
182}
183
184fn ffmpeg_pcm(path: &Path, index: u32, fmt: &str) -> Vec<u8> {
185 std::process::Command::new("ffmpeg")
186 .args(["-v", "error", "-i"])
187 .arg(path)
188 .args(["-map", &format!("0:{index}"), "-f", fmt, "-"])
189 .output()
190 .unwrap()
191 .stdout
192}
193
194/// Duration against ffprobe's packet extents, within one video frame.
195fn duration_ok(path: &Path) {
196 let d = open_ps(path);
197 let got = d.duration_secs().expect("duration");
198 let rows = ffprobe_rows(path);
199 let mut want = 0f64;
200 for s in d.streams() {
201 let Some((_, r)) = rows.get(&ffid(d.stream_key(s.index).unwrap())) else {
202 continue;
203 };
204 let first = r.iter().filter_map(|x| x.pts).min();
205 let end = r
206 .iter()
207 .filter_map(|x| x.pts.map(|p| p + x.dur.unwrap_or(0)))
208 .max();
209 if let (Some(f), Some(e)) = (first, end) {
210 want = want.max((e - f) as f64 / 90_000.0);
211 }
212 }
213 if d.kind() == PsKind::VideoElementary {
214 return;
215 }
216 assert!(
217 (got - want).abs() <= 0.045,
218 "{path:?}: duration {got} vs {want}"
219 );
220}
221
222/// Seek (every mode, several targets) then read equals the sequential read from the landing offset.
223fn seek_exact(path: &Path) {
224 let mut d = open_ps(path);
225 let all = read_ps(&mut d);
226 let vid = d
227 .streams()
228 .iter()
229 .find(|s| s.params.video().is_some())
230 .map(|s| s.index);
231 let base = d
232 .streams()
233 .iter()
234 .filter_map(|s| s.start_time)
235 .min()
236 .unwrap();
237 let dur = d.duration_secs().unwrap_or(3.0);
238 let tb = TimeBase::new(1, 90_000);
239 for frac in [0.0, 0.1, 0.33, 0.5, 0.77, 0.97, 1.5] {
240 let target = base + (frac * dur * 90_000.0) as i64;
241 for mode in [SeekMode::SyncBefore, SeekMode::Exact, SeekMode::SyncAfter] {
242 let mut d = open_ps(path);
243 let sk = vid.unwrap_or(0);
244 match d.seek(sk, Timestamp::new(target, tb), mode) {
245 Ok(()) => {}
246 Err(ec_core::Error::Eof) if mode == SeekMode::SyncAfter => continue,
247 Err(e) => panic!("{path:?} seek: {e}"),
248 }
249 let landing = d.last_packet_offset();
250 let got = read_ps(&mut d);
251 let mut want: Vec<&Pkt> = all.iter().filter(|p| p.off >= landing).collect();
252 // Pictures that share the landing packet but precede the keyframe are dropped.
253 if let Some(v) = vid
254 && let Some(f) = got.iter().find(|p| p.stream == v)
255 {
256 let at = want
257 .iter()
258 .position(|p| {
259 p.stream == v && p.pts == f.pts && p.dts == f.dts && p.data == f.data
260 })
261 .expect("first video packet after the seek is in the sequential read");
262 let mut i = 0;
263 want.retain(|p| {
264 let drop = i < at && p.stream == v && p.off == landing;
265 i += 1;
266 !drop
267 });
268 }
269 assert_eq!(
270 got.len(),
271 want.len(),
272 "{path:?} seek {frac} {mode:?}: count"
273 );
274 for (g, w) in got.iter().zip(&want) {
275 assert!(
276 g.stream == w.stream
277 && g.pts == w.pts
278 && g.dts == w.dts
279 && g.key == w.key
280 && g.data == w.data,
281 "{path:?} seek {frac} {mode:?}: packet differs at off {}: s{} pts {:?}/{:?} dts {:?}/{:?} key {}/{} len {}/{}",
282 w.off,
283 w.stream,
284 g.pts,
285 w.pts,
286 g.dts,
287 w.dts,
288 g.key,
289 w.key,
290 g.data.len(),
291 w.data.len()
292 );
293 }
294 if let (Some(v), SeekMode::SyncBefore) = (vid, mode) {
295 let first = got.iter().find(|p| p.stream == v).unwrap();
296 let key_before = all
297 .iter()
298 .any(|p| p.stream == v && p.key && p.pts.is_some_and(|t| t <= target));
299 assert!(
300 first.key || !key_before,
301 "{path:?} seek {frac}: lands on a keyframe"
302 );
303 let fp = first.pts.unwrap();
304 assert!(
305 fp <= target.max(base) || frac == 0.0 || !key_before,
306 "{path:?} seek {frac}: {fp} > {target}"
307 );
308 let better = all.iter().any(|p| {
309 p.stream == v && p.key && p.pts.is_some_and(|x| x > fp && x <= target)
310 });
311 assert!(!better, "{path:?} seek {frac}: a closer keyframe exists");
312 }
313 }
314 }
315}
316
317/// The fixture cases that get the full check set (parity, duration, seek
318/// exactness). One test over a table: every case runs and all failures are named.
319#[test]
320fn ps_parity_cases() {
321 type Case = (&'static str, fn() -> Option<std::path::PathBuf>);
322 const CASES: &[Case] = &[
323 ("mpeg1_system_mp2", || {
324 mkps(
325 "m1.mpg",
326 &["-c:v", "mpeg1video", "-g", "12", "-bf", "2"],
327 &["-c:a", "mp2"],
328 &["-f", "mpeg"],
329 )
330 }),
331 ("vob_mpeg2_ac3", || {
332 mkps("v_ac3.vob", V2, &["-c:a", "ac3"], &["-f", "vob"])
333 }),
334 ("vob_mpeg2_mp2", || {
335 mkps("v_mp2.vob", V2, &["-c:a", "mp2"], &["-f", "vob"])
336 }),
337 ("mpeg2_ps_mpeg_muxer", || {
338 mkps("m2.mpg", V2, &["-c:a", "mp2"], &["-f", "mpeg"])
339 }),
340 ("dvd_with_nav_packets", || {
341 mkps(
342 "dvd.vob",
343 &[
344 "-vf",
345 "scale=720:576",
346 "-c:v",
347 "mpeg2video",
348 "-g",
349 "12",
350 "-bf",
351 "2",
352 "-b:v",
353 "3000k",
354 ],
355 &["-c:a", "ac3", "-ar", "48000"],
356 &["-f", "dvd"],
357 )
358 }),
359 ("interlaced_mpeg2", || {
360 mkps(
361 "ilace.vob",
362 &[
363 "-c:v",
364 "mpeg2video",
365 "-g",
366 "12",
367 "-bf",
368 "2",
369 "-flags",
370 "+ildct+ilme",
371 "-top",
372 "1",
373 ],
374 &["-c:a", "ac3"],
375 &["-f", "vob"],
376 )
377 }),
378 ("pcm_dvd_16", || {
379 mkps("lpcm16.vob", V2, &["-c:a", "pcm_dvd"], &["-f", "vob"])
380 }),
381 ("raw_m2v", || {
382 fixture("a.m2v", &[VIDEO_SRC, V2, &["-f", "mpeg2video"]].concat())
383 }),
384 ("pts_wrap", || {
385 mkps(
386 "wrap.vob",
387 V2,
388 &["-c:a", "ac3"],
389 &["-output_ts_offset", "95442", "-f", "vob"],
390 )
391 }),
392 ("h264_mp3_mpeg_muxer", || {
393 mkps(
394 "h264.mpg",
395 &[
396 "-c:v",
397 "libx264",
398 "-preset",
399 "ultrafast",
400 "-g",
401 "25",
402 "-bf",
403 "2",
404 ],
405 &["-c:a", "mp3"],
406 &["-f", "mpeg"],
407 )
408 }),
409 ("pcm_dvd_96k_16", || {
410 mkps(
411 "lpcm96.vob",
412 V2,
413 &["-c:a", "pcm_dvd", "-ar", "96000"],
414 &["-f", "vob"],
415 )
416 }),
417 ("mpeg1_video_only", || {
418 fixture(
419 "v1.mpg",
420 &[
421 VIDEO_SRC,
422 &["-c:v", "mpeg1video", "-g", "9", "-bf", "2", "-f", "mpeg"],
423 ]
424 .concat(),
425 )
426 }),
427 ("raw_m2v_without_b_frames", || {
428 fixture(
429 "nb.m2v",
430 &[
431 VIDEO_SRC,
432 &[
433 "-c:v",
434 "mpeg2video",
435 "-g",
436 "10",
437 "-bf",
438 "0",
439 "-f",
440 "mpeg2video",
441 ],
442 ]
443 .concat(),
444 )
445 }),
446 ("raw_mpeg1_video", || {
447 fixture(
448 "a1.m1v",
449 &[
450 VIDEO_SRC,
451 &[
452 "-c:v",
453 "mpeg1video",
454 "-g",
455 "9",
456 "-bf",
457 "2",
458 "-f",
459 "mpeg1video",
460 ],
461 ]
462 .concat(),
463 )
464 }),
465 ];
466 let mut failures = Vec::new();
467 for &(name, make) in CASES {
468 let ran = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
469 let Some(p) = make() else { return };
470 parity(&p, 0);
471 duration_ok(&p);
472 seek_exact(&p);
473 }));
474 if ran.is_err() {
475 failures.push(name);
476 }
477 }
478 assert!(failures.is_empty(), "failed cases: {failures:?}");
479}
480
481// 20 and 24 bit DVD LPCM groups straddle ffmpeg's packet cuts, so a read that starts
482// mid-stream cannot know the phase: no seek-exactness check for it.
483#[test]
484fn pcm_dvd_24() {
485 let Some(p) = mkps(
486 "lpcm24.vob",
487 V2,
488 &["-c:a", "pcm_dvd", "-sample_fmt", "s32"],
489 &["-f", "vob"],
490 ) else {
491 return;
492 };
493 parity(&p, 0);
494 duration_ok(&p);
495}
496
497#[test]
498fn dts_is_refused_by_name() {
499 let Some(p) = mkps(
500 "dts.vob",
501 V2,
502 &["-c:a", "dca", "-strict", "-2"],
503 &["-f", "vob"],
504 ) else {
505 return;
506 };
507 let d = open_ps(&p);
508 assert_eq!(d.streams().len(), 1);
509 let t = d.tracks();
510 let dts = t
511 .iter()
512 .find(|t| t.stream.is_none())
513 .expect("a refused track");
514 assert!(
515 dts.refusal.as_deref().unwrap().starts_with("dts"),
516 "{dts:?}"
517 );
518}
519
520// ---------------------------------------------------------------------------
521// Committed fixtures: SCR resets, damaged files, injected streams
522// ---------------------------------------------------------------------------
523
524fn committed(name: &str) -> Vec<u8> {
525 std::fs::read(
526 PathBuf::from(env!("CARGO_MANIFEST_DIR"))
527 .join("tests/data")
528 .join(name),
529 )
530 .unwrap()
531}
532
533/// A file name no other call in this process uses: tests run as threads of one
534/// process, so the pid alone does not separate them.
535fn unique_name(name: &str) -> String {
536 static N: std::sync::atomic::AtomicUsize = std::sync::atomic::AtomicUsize::new(0);
537 let n = N.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
538 format!("{}-{n}-{name}", std::process::id())
539}
540
541fn tmpfile(name: &str, bytes: &[u8]) -> PathBuf {
542 let p = fixture_dir().join(unique_name(name));
543 std::fs::write(&p, bytes).unwrap();
544 p
545}
546
547fn open_bytes(b: Vec<u8>) -> ec_core::Result<PsDemuxer<std::io::Cursor<Vec<u8>>>> {
548 PsDemuxer::new(std::io::Cursor::new(b))
549}
550
551fn per_stream(p: &[Pkt]) -> Vec<Vec<&Pkt>> {
552 let n = p
553 .iter()
554 .map(|x| x.stream)
555 .max()
556 .map_or(0, |m| m as usize + 1);
557 (0..n)
558 .map(|s| p.iter().filter(|x| x.stream as usize == s).collect())
559 .collect()
560}
561
562/// `copies` of a file back to back: the SCR (and the PTS) restart in each.
563fn check_concat(bytes: &[u8], copies: usize, walk_limit: Option<u64>) {
564 let cat: Vec<u8> = (0..copies).flat_map(|_| bytes.iter().copied()).collect();
565 let path = tmpfile("concat.vob", &cat);
566 let open = |p: &Path| {
567 let f = BufReader::new(File::open(p).unwrap());
568 match walk_limit {
569 Some(l) => PsDemuxer::with_walk_limit(f, l).unwrap(),
570 None => PsDemuxer::new(f).unwrap(),
571 }
572 };
573 let single = {
574 let mut d = open_bytes(bytes.to_vec()).unwrap();
575 let mut v = Vec::new();
576 while let Ok(p) = d.next_packet() {
577 v.push((p.stream, p.pts, p.dts, p.data.to_vec()));
578 }
579 v
580 };
581 let mut d = open(&path);
582 assert_eq!(d.epoch_count(), copies, "SCR resets found at open");
583 let all = read_ps(&mut d);
584 assert_eq!(d.stats().discontinuities, copies as u64 - 1);
585 assert_eq!(all.len(), single.len() * copies);
586 let ps = per_stream(&all);
587 let mut shift = None;
588 for (s, list) in ps.iter().enumerate() {
589 let k = list.len() / copies;
590 assert!(k > 0);
591 for c in 1..copies {
592 for i in 0..k {
593 let (a, b) = (list[i + (c - 1) * k], list[i + c * k]);
594 assert_eq!(a.data, b.data, "stream {s} copy {c} #{i}");
595 let dp = b.pts.unwrap() - a.pts.unwrap();
596 let sh = *shift.get_or_insert(dp);
597 assert_eq!(
598 dp, sh,
599 "stream {s} copy {c} #{i}: one shift for every stream"
600 );
601 if let (Some(x), Some(y)) = (a.dts, b.dts) {
602 assert_eq!(y - x, sh);
603 }
604 }
605 }
606 // Decode (or presentation) time never goes backwards across the joins.
607 let t: Vec<i64> = list.iter().map(|p| p.dts.or(p.pts).unwrap()).collect();
608 assert!(
609 t.windows(2).all(|w| w[1] >= w[0]),
610 "stream {s}: time steps back"
611 );
612 }
613 // The shift is about one copy's length of SCR.
614 let sh = shift.unwrap();
615 let first_dur = open_bytes(bytes.to_vec()).unwrap().duration_secs().unwrap();
616 assert!(
617 sh > 0 && (sh as f64 / 90_000.0) < first_dur + 1.0,
618 "shift {sh} vs {first_dur}"
619 );
620 let dur = d.duration_secs().unwrap();
621 assert!(
622 dur > first_dur * copies as f64 * 0.8 && dur < (first_dur + 1.0) * copies as f64,
623 "{dur}"
624 );
625 seek_exact(&path);
626}
627
628#[test]
629fn concatenated_vobs_keep_time_monotonic() {
630 let b = committed("ps_mpeg2_ac3.vob");
631 check_concat(&b, 3, None);
632 // The same through the sampling check used for big files.
633 check_concat(&b, 3, Some(1));
634 check_concat(&committed("ps_mpeg1_mp2.mpg"), 2, None);
635}
636
637#[test]
638fn concatenated_dvd_files_with_nav_packets() {
639 let Some(p) = mkps(
640 "dvd2.vob",
641 &[
642 "-vf",
643 "scale=720:576",
644 "-c:v",
645 "mpeg2video",
646 "-g",
647 "12",
648 "-bf",
649 "2",
650 "-b:v",
651 "3000k",
652 ],
653 &["-c:a", "ac3", "-ar", "48000"],
654 &["-f", "dvd"],
655 ) else {
656 return;
657 };
658 check_concat(&std::fs::read(p).unwrap(), 2, None);
659}
660
661#[test]
662fn starts_mid_gop() {
663 let Some(p) = mkps("v_ac3.vob", V2, &["-c:a", "ac3"], &["-f", "vob"]) else {
664 return;
665 };
666 let orig_bytes = std::fs::read(&p).unwrap();
667 let mut o = open_ps(&p);
668 let orig = read_ps(&mut o);
669 // Start at a pack boundary a few GOPs in and not on a keyframe.
670 let cut = 2048 * 90;
671 let path = tmpfile("midgop.vob", &orig_bytes[cut..]);
672 let mut d = open_ps(&path);
673 assert_eq!(d.streams().len(), 2);
674 assert_eq!(d.streams()[0].params.codec, CodecId::Mpeg2Video);
675 let got = read_ps(&mut d);
676 let (gv, ov) = (
677 got.iter().filter(|p| p.stream == 0).collect::<Vec<_>>(),
678 orig.iter().filter(|p| p.stream == 0).collect::<Vec<_>>(),
679 );
680 // Pictures before the first keyframe are delivered (not keys); from the first key on
681 // every picture is ffmpeg-identical to the full file's.
682 let k = gv.iter().position(|p| p.key).expect("a keyframe");
683 let at = ov
684 .iter()
685 .position(|p| p.key && p.data == gv[k].data)
686 .expect("same keyframe");
687 assert!(k < 12, "{k}");
688 for (g, w) in gv[k..].iter().zip(&ov[at..]) {
689 assert_eq!((g.data.len(), g.pts, g.key), (w.data.len(), w.pts, w.key));
690 assert!(g.data == w.data);
691 }
692 assert_eq!(gv.len() - k, ov.len() - at);
693 // Audio: a suffix of the full file's, same timestamps.
694 let (ga, oa) = (
695 got.iter().filter(|p| p.stream == 1).collect::<Vec<_>>(),
696 orig.iter().filter(|p| p.stream == 1).collect::<Vec<_>>(),
697 );
698 let tail = &oa[oa.len() - ga.len()..];
699 for (g, w) in ga.iter().zip(tail) {
700 assert!(g.data == w.data && g.pts == w.pts);
701 }
702 seek_exact(&path);
703}
704
705/// A VobSub PES injected after the first pack: a refused track named for what it is, and
706/// the other streams unchanged. Also private_stream_2 (nav) and padding in the mix.
707#[test]
708fn dvd_subpictures_nav_and_padding() {
709 let b = committed("ps_mpeg2_ac3.vob");
710 let mut d0 = open_bytes(b.clone()).unwrap();
711 let mut base = Vec::new();
712 while let Ok(p) = d0.next_packet() {
713 base.push((p.stream, p.pts, p.data.to_vec()));
714 }
715 // After the first pack header + system header.
716 let at = b.windows(4).position(|w| w == [0, 0, 1, 0xBB]).unwrap();
717 let at = at + 6 + usize::from(u16::from_be_bytes([b[at + 4], b[at + 5]]));
718 let pes = |id: u8, body: &[u8]| {
719 let mut v = vec![0, 0, 1, id];
720 v.extend_from_slice(&(body.len() as u16).to_be_bytes());
721 v.extend_from_slice(body);
722 v
723 };
724 let mut inj = pes(0xBF, &[0u8; 100]);
725 inj.extend(pes(0xBE, &[0xFF; 40]));
726 let mut sub = vec![0x81, 0x80, 5, 0x21, 0, 1, 0, 1];
727 sub.extend_from_slice(&[0x20, 1, 2, 3, 4]);
728 inj.extend(pes(0xBD, &sub));
729 let mut dts = vec![0x88, 0, 0, 0]; // DTS substream
730 dts.extend_from_slice(&[0x7F, 0xFE, 0x80, 0x01, 0, 0]);
731 let mut dtspes = vec![0x81, 0x00, 0];
732 dtspes.extend_from_slice(&dts);
733 inj.extend(pes(0xBD, &dtspes));
734 let mut m = b[..at].to_vec();
735 m.extend_from_slice(&inj);
736 m.extend_from_slice(&b[at..]);
737 let mut d = open_bytes(m).unwrap();
738 let t = d.tracks();
739 let sp = t
740 .iter()
741 .find(|t| t.pid == 0xBD20)
742 .expect("subpicture track");
743 // The subpicture is a DvdSub stream now; this unit never completes, so it yields no packet.
744 assert!(sp.stream.is_some() && sp.refusal.is_none(), "{sp:?}");
745 let dtst = t.iter().find(|t| t.pid == 0xBD88).expect("dts track");
746 assert!(dtst.refusal.as_deref().unwrap().starts_with("dts"));
747 assert_eq!(d.streams().len(), 3);
748 let mut got = Vec::new();
749 while let Ok(p) = d.next_packet() {
750 got.push((p.stream, p.pts, p.data.to_vec()));
751 }
752 // The new subpicture stream may shift later stream numbers; the packets themselves are the same.
753 let strip = |v: &[(u32, Option<i64>, Vec<u8>)]| -> Vec<(Option<i64>, Vec<u8>)> {
754 v.iter().map(|x| (x.1, x.2.clone())).collect()
755 };
756 assert!(
757 strip(&got) == strip(&base),
758 "refused and ignored elements change nothing"
759 );
760}
761
762#[test]
763fn truncated_files_give_a_prefix() {
764 for name in [
765 "ps_mpeg2_ac3.vob",
766 "ps_mpeg1_mp2.mpg",
767 "ps_pcm_dvd.vob",
768 "ps_mpeg2.m2v",
769 ] {
770 let b = committed(name);
771 let mut d = open_bytes(b.clone()).unwrap();
772 let mut full: Vec<Vec<Vec<u8>>> = vec![Vec::new(); 2];
773 while let Ok(p) = d.next_packet() {
774 full[p.stream as usize].push(p.data.to_vec());
775 }
776 let step = (b.len() / 61).max(1);
777 for len in (0..64).chain((64..b.len()).step_by(step)) {
778 let Ok(mut d) = open_bytes(b[..len].to_vec()) else {
779 continue;
780 };
781 let mut got: Vec<Vec<(Vec<u8>, bool)>> = vec![Vec::new(); 8];
782 while let Ok(p) = d.next_packet() {
783 got[p.stream as usize].push((p.data.to_vec(), p.flags.corrupt));
784 }
785 for (s, g) in got.iter().enumerate() {
786 if g.is_empty() {
787 continue;
788 }
789 assert!(
790 g.len() <= full[s].len(),
791 "{name} cut {len}: stream {s} has more packets"
792 );
793 // All but the last are whole packets of the full read.
794 for (i, (data, bad)) in g.iter().enumerate().take(g.len().saturating_sub(1)) {
795 if *bad {
796 continue;
797 }
798 assert!(*data == full[s][i], "{name} cut {len}: stream {s} #{i}");
799 }
800 }
801 }
802 }
803}
804
805fn exercise(bytes: Vec<u8>) {
806 let Ok(mut d) = open_bytes(bytes) else {
807 return;
808 };
809 let _ = (d.tracks(), d.duration_secs(), d.stats(), d.epoch_count());
810 for round in 0..2 {
811 if round == 1 {
812 d.set_video_framing(ec_mpegts::VideoFraming::LengthPrefixed);
813 }
814 while d.next_packet().is_ok() {}
815 for s in 0..d.streams().len() as u32 {
816 for t in [0i64, 20_000, 1 << 33, -1] {
817 for mode in [SeekMode::SyncBefore, SeekMode::SyncAfter, SeekMode::Exact] {
818 let _ = d.seek(s, Timestamp::new(t, TimeBase::new(1, 90_000)), mode);
819 for _ in 0..20 {
820 if d.next_packet().is_err() {
821 break;
822 }
823 }
824 }
825 }
826 }
827 }
828}
829
830#[test]
831fn mutated_files_never_panic() {
832 let mut rng = Rng(0x9E37_79B9_7F4A_7C15);
833 for name in [
834 "ps_mpeg2_ac3.vob",
835 "ps_mpeg1_mp2.mpg",
836 "ps_pcm_dvd.vob",
837 "ps_mpeg2.m2v",
838 ] {
839 let base = committed(name);
840 for round in 0..60 {
841 let mut b = base.clone();
842 for _ in 0..1 + rng.below(6) {
843 let at = rng.below(b.len());
844 match rng.below(6) {
845 0 => b[at] ^= 1 << rng.below(8),
846 1 => b.truncate(at.max(1)),
847 2 => {
848 let n = rng.below(300).min(b.len() - at);
849 b.drain(at..at + n);
850 }
851 3 => {
852 let n = rng.below(200);
853 let junk: Vec<u8> = (0..n).map(|_| rng.next() as u8).collect();
854 b.splice(at..at, junk);
855 }
856 4 => {
857 let n = rng.below(2000).min(b.len() - at);
858 b[at..at + n].fill(if round % 2 == 0 { 0 } else { 0xFF });
859 }
860 _ => {
861 let n = rng.below(4000).min(b.len() - at);
862 let chunk = b[at..at + n].to_vec();
863 b.splice(at..at, chunk);
864 }
865 }
866 if b.is_empty() {
867 break;
868 }
869 }
870 exercise(b);
871 }
872 // Start codes with absurd lengths everywhere.
873 let mut b = base.clone();
874 for w in 0..b.len().saturating_sub(6) {
875 if b[w..w + 3] == [0, 0, 1] && b[w + 3] >= 0xB9 && w % 3 == 0 {
876 b[w + 4] = 0xFF;
877 b[w + 5] = 0xFF;
878 }
879 }
880 exercise(b);
881 }
882}
883
884#[test]
885fn pts_wrap_is_unwrapped() {
886 let Some(p) = mkps(
887 "wrap.vob",
888 V2,
889 &["-c:a", "ac3"],
890 &["-output_ts_offset", "95442", "-f", "vob"],
891 ) else {
892 return;
893 };
894 let mut d = open_ps(&p);
895 let v = read_ps(&mut d);
896 let pts: Vec<i64> = v
897 .iter()
898 .filter(|x| x.stream == 0)
899 .filter_map(|x| x.pts)
900 .collect();
901 let m = 1i64 << 33;
902 assert!(
903 pts.iter().any(|&x| x < m) && pts.iter().any(|&x| x > m),
904 "the clock crosses 2^33"
905 );
906 let mut sorted = pts.clone();
907 sorted.sort_unstable();
908 assert!(
909 sorted.windows(2).all(|w| w[1] - w[0] == 3600),
910 "uniform after unwrapping"
911 );
912 let dur = d.duration_secs().unwrap();
913 assert!((dur - 3.0).abs() < 0.1, "{dur}");
914}
915
916#[test]
917fn raw_stream_timestamps_follow_the_frame_rate() {
918 let b = committed("ps_mpeg2.m2v");
919 let mut d = open_bytes(b).unwrap();
920 assert_eq!(d.kind(), PsKind::VideoElementary);
921 let mut pkts = Vec::new();
922 while let Ok(p) = d.next_packet() {
923 pkts.push((p.pts.unwrap(), p.dts.unwrap(), p.flags.keyframe));
924 }
925 assert_eq!(pkts.len(), 13);
926 let mut pts: Vec<i64> = pkts.iter().map(|p| p.0).collect();
927 pts.sort_unstable();
928 assert!(pts.windows(2).all(|w| w[1] - w[0] == 3600), "{pts:?}");
929 assert_eq!(pts[0], 0);
930 assert!(pkts.iter().all(|p| p.1 <= p.0), "dts never after pts");
931 assert!(
932 pkts.windows(2).all(|w| w[1].1 - w[0].1 == 3600),
933 "dts one frame apart"
934 );
935 assert!((d.duration_secs().unwrap() - 0.52).abs() < 1e-9);
936}
937
938// ---------------------------------------------------------------------------
939// Tail picture without a PES timestamp; byte-joined VOBs
940// ---------------------------------------------------------------------------
941
942const FLASH_SRC: &str = "color=c=black:s=352x288:r=25:d=2.4,drawbox=x=0:y=0:w=352:h=288:color=white:t=fill:enable='between(t,1,1.2)'";
943
944fn video_index(d: &D) -> u32 {
945 d.streams()
946 .iter()
947 .find(|s| s.params.video().is_some())
948 .unwrap()
949 .index
950}
951
952fn frames_by_ffprobe(path: &Path) -> usize {
953 let o = std::process::Command::new("ffprobe")
954 .args(["-v", "error", "-count_frames", "-select_streams", "v:0"])
955 .args(["-show_entries", "stream=nb_read_frames", "-of", "csv=p=0"])
956 .arg(path)
957 .output()
958 .unwrap();
959 String::from_utf8_lossy(&o.stdout)
960 .lines()
961 .map(|l| l.trim().trim_end_matches(','))
962 .find(|l| !l.is_empty())
963 .unwrap()
964 .parse()
965 .unwrap()
966}
967
968/// The last picture of an MPEG-1 `-f mpeg` file carries no PES timestamp: it is still
969/// emitted with a derived time and counted in the stream length.
970#[test]
971fn tail_picture_without_a_timestamp_is_counted() {
972 let mut cases = Vec::new();
973 for (name, video) in [
974 ("pstail-flash.mpg", FLASH_SRC),
975 (
976 "pstail-card.mpg",
977 "testsrc2=size=352x288:rate=25:duration=2.4",
978 ),
979 ] {
980 let mut a: Vec<&str> = vec!["-f", "lavfi", "-i", video, "-f", "lavfi", "-i"];
981 a.push("sine=frequency=440:sample_rate=48000:duration=2.4");
982 a.extend_from_slice(&[
983 "-map",
984 "0:v",
985 "-c:v",
986 "mpeg1video",
987 "-b:v",
988 "2M",
989 "-g",
990 "10",
991 "-bf",
992 "2",
993 ]);
994 a.extend_from_slice(&[
995 "-pix_fmt", "yuv420p", "-map", "1:a", "-c:a", "mp2", "-f", "mpeg",
996 ]);
997 if let Some(p) = fixture(name, &a) {
998 cases.push(p);
999 }
1000 }
1001 for path in cases {
1002 let mut d = open_ps(&path);
1003 let v = video_index(&d);
1004 let pkts = read_ps(&mut d);
1005 let mine: Vec<&Pkt> = pkts.iter().filter(|p| p.stream == v).collect();
1006 let want = frames_by_ffprobe(&path);
1007 assert_eq!(mine.len(), want, "{path:?}: packets");
1008 assert_eq!(want, 60);
1009 // Every picture has a presentation time; they tile the timeline one frame apart.
1010 let mut pts: Vec<i64> = mine
1011 .iter()
1012 .map(|p| p.pts.expect("a pts on every picture"))
1013 .collect();
1014 pts.sort_unstable();
1015 assert!(
1016 pts.windows(2).all(|w| w[1] - w[0] == 3600),
1017 "{path:?}: {pts:?}"
1018 );
1019 let s = &d.streams()[v as usize];
1020 assert_eq!(
1021 s.duration,
1022 Some(60 * 3600),
1023 "{path:?}: video duration is 60 frames"
1024 );
1025 }
1026}
1027
1028/// Two VOBs of 2.4 s joined by bytes: SCR and PTS restart at the join.
1029fn joined_vob() -> Option<(PathBuf, u64)> {
1030 let mk = |name: &str, vf: &str, hz: &str| {
1031 let video = format!("testsrc2=size=352x288:rate=25:duration=2.4{vf}");
1032 let audio = format!("sine=frequency={hz}:sample_rate=48000:duration=2.4");
1033 let a = [
1034 "-f",
1035 "lavfi",
1036 "-i",
1037 &video,
1038 "-f",
1039 "lavfi",
1040 "-i",
1041 &audio,
1042 "-map",
1043 "0:v",
1044 "-c:v",
1045 "mpeg2video",
1046 "-b:v",
1047 "4M",
1048 "-g",
1049 "10",
1050 "-bf",
1051 "2",
1052 "-pix_fmt",
1053 "yuv420p",
1054 "-map",
1055 "1:a",
1056 "-c:a",
1057 "mp2",
1058 "-b:a",
1059 "192k",
1060 "-f",
1061 "vob",
1062 ];
1063 fixture(name, &a)
1064 };
1065 let a = mk("pstail-a.vob", "", "440")?;
1066 let b = mk("pstail-b.vob", ",negate", "880")?;
1067 let out = fixture_dir().join("pstail-join.vob");
1068 let alen = std::fs::metadata(&a).unwrap().len();
1069 if !out.exists() {
1070 let mut bytes = std::fs::read(&a).unwrap();
1071 bytes.extend(std::fs::read(&b).unwrap());
1072 // Three tests build this file in parallel: each writes its own temporary file.
1073 let tmp = fixture_dir().join(unique_name("pstail-join.tmp"));
1074 std::fs::write(&tmp, bytes).unwrap();
1075 std::fs::rename(&tmp, &out).unwrap();
1076 }
1077 Some((out, alen))
1078}
1079
1080#[test]
1081fn joined_vobs_have_the_summed_duration() {
1082 let Some((path, _)) = joined_vob() else {
1083 return;
1084 };
1085 let d = open_ps(&path);
1086 let single = open_ps(&fixture_dir().join("pstail-a.vob"));
1087 let v = video_index(&d) as usize;
1088 let one = single.streams()[video_index(&single) as usize]
1089 .duration
1090 .unwrap();
1091 assert_eq!(
1092 d.streams()[v].duration,
1093 Some(2 * one),
1094 "video stream duration"
1095 );
1096 assert!(
1097 (d.duration_secs().unwrap() - 4.8).abs() < 0.03,
1098 "{:?}",
1099 d.duration_secs()
1100 );
1101 let mut d = d;
1102 let pkts = read_ps(&mut d);
1103 let mut pts: Vec<i64> = pkts
1104 .iter()
1105 .filter(|p| p.stream == v as u32)
1106 .filter_map(|p| p.pts)
1107 .collect();
1108 assert_eq!(pts.len(), 120);
1109 pts.sort_unstable();
1110 assert!(
1111 pts.windows(2).all(|w| w[1] - w[0] == 3600),
1112 "continuous display times"
1113 );
1114}
1115
1116#[test]
1117fn seeks_on_both_sides_of_a_join_equal_the_sequential_decode() {
1118 let Some((path, _)) = joined_vob() else {
1119 return;
1120 };
1121 let mut d = open_ps(&path);
1122 let v = video_index(&d);
1123 let all = read_ps(&mut d);
1124 let tb = TimeBase::new(1, 90_000);
1125 let vid: Vec<&Pkt> = all.iter().filter(|p| p.stream == v).collect();
1126 let mut shown: Vec<i64> = vid.iter().map(|p| p.pts.unwrap()).collect();
1127 shown.sort_unstable();
1128 // Frames well before, at, and after the join (frame 60), and the last.
1129 for n in [3usize, 29, 57, 58, 59, 60, 61, 62, 65, 90, 119] {
1130 let target = shown[n];
1131 for mode in [SeekMode::Exact, SeekMode::SyncBefore] {
1132 let mut d = open_ps(&path);
1133 d.seek(v, Timestamp::new(target, tb), mode).unwrap();
1134 let got = read_ps(&mut d);
1135 let first = got.iter().find(|p| p.stream == v).unwrap();
1136 // The expected landing from the sequential read.
1137 let want = match mode {
1138 SeekMode::Exact => vid.iter().rfind(|p| p.dts.or(p.pts).unwrap() <= target),
1139 _ => vid.iter().rfind(|p| {
1140 p.key && p.pts.unwrap() <= target && p.dts.or(p.pts).unwrap() <= target
1141 }),
1142 }
1143 .unwrap();
1144 assert_eq!(
1145 (first.pts, first.dts, &first.data),
1146 (want.pts, want.dts, &want.data),
1147 "frame {n} {mode:?}: landing"
1148 );
1149 // And the rest of the video equals the sequential read from there.
1150 let at = vid
1151 .iter()
1152 .position(|p| p.off == want.off && p.pts == want.pts)
1153 .unwrap();
1154 let rest: Vec<_> = vid[at..].iter().map(|p| (p.pts, p.dts, &p.data)).collect();
1155 let mine: Vec<_> = got
1156 .iter()
1157 .filter(|p| p.stream == v)
1158 .map(|p| (p.pts, p.dts, &p.data))
1159 .collect();
1160 assert_eq!(mine, rest, "frame {n} {mode:?}: packets after the seek");
1161 }
1162 }
1163 // The generic check over many fractions, as for any other file.
1164 seek_exact(&path);
1165}
1166
1167#[test]
1168fn audio_keeps_its_offset_to_the_video_after_a_join() {
1169 let Some((path, alen)) = joined_vob() else {
1170 return;
1171 };
1172 let mut d = open_ps(&path);
1173 let v = video_index(&d);
1174 let a = d
1175 .streams()
1176 .iter()
1177 .find(|s| s.params.audio().is_some())
1178 .unwrap()
1179 .index;
1180 let all = read_ps(&mut d);
1181 let first = |stream: u32, after: bool| {
1182 all.iter()
1183 .filter(|p| p.stream == stream && (p.off >= alen) == after)
1184 .filter_map(|p| p.pts)
1185 .min()
1186 .unwrap()
1187 };
1188 let before = first(a, false) - first(v, false);
1189 let after = first(a, true) - first(v, true);
1190 // One MP2 frame is 1152 samples (2160 ticks).
1191 assert!(
1192 (after - before).abs() <= 2160,
1193 "offset {before} before, {after} after the join"
1194 );
1195 // The audio of the second half starts where the first half's ends.
1196 let mut apts: Vec<i64> = all
1197 .iter()
1198 .filter(|p| p.stream == a)
1199 .filter_map(|p| p.pts)
1200 .collect();
1201 apts.sort_unstable();
1202 assert!(
1203 apts.windows(2).all(|w| (w[1] - w[0] - 2160).abs() <= 2160),
1204 "audio is continuous"
1205 );
1206}
1207
1208/// The TS path emits every picture too (its PES packets carry one picture each).
1209#[test]
1210fn ts_tail_picture_is_counted() {
1211 for (name, codec) in [
1212 ("pstail-flash1.ts", "mpeg1video"),
1213 ("pstail-flash2.ts", "mpeg2video"),
1214 ] {
1215 let a = [
1216 "-f", "lavfi", "-i", FLASH_SRC, "-c:v", codec, "-b:v", "2M", "-g", "10", "-bf", "2",
1217 "-pix_fmt", "yuv420p", "-f", "mpegts",
1218 ];
1219 let Some(path) = fixture(name, &a) else {
1220 continue;
1221 };
1222 let mut d = open(&path);
1223 let v = d
1224 .streams()
1225 .iter()
1226 .find(|s| s.params.video().is_some())
1227 .unwrap()
1228 .index;
1229 let pkts = read_all(&mut d);
1230 let mine: Vec<&Pkt> = pkts.iter().filter(|p| p.stream == v).collect();
1231 assert_eq!(mine.len(), frames_by_ffprobe(&path), "{name}");
1232 assert!(
1233 mine.iter().all(|p| p.pts.is_some()),
1234 "{name}: every picture has a pts"
1235 );
1236 assert_eq!(d.streams()[v as usize].duration, Some(60 * 3600), "{name}");
1237 }
1238}