forge
Explore
Log in

Don't you dare go Hollow

Merge branch 'simplify/w0-m7' into simplify/w0

Browse files at this commit

74f088cf329227a2014b792183d5f2d4ecc06894Ahmet Kaan GümüşParent: 2a46476ff7eb39

45 changed files +303 -2175

Cargo.lockmodified+6 -0
@@ -576,6 +576,7 @@ dependencies = [
576576 "ec-core",
577577 "ec-inflate",
578578 "ec-mp4",
579+ "ec-testkit",
579580 ]
580581
581582 [[package]]
@@ -604,6 +605,7 @@ name = "ec-mp4"
604605 version = "0.1.0"
605606 dependencies = [
606607 "ec-core",
608+ "ec-testkit",
607609 ]
608610
609611 [[package]]
@@ -633,6 +635,7 @@ dependencies = [
633635 "ec-dvdsub",
634636 "ec-h264-syntax",
635637 "ec-h265-syntax",
638+ "ec-testkit",
636639 "ec-truehd",
637640 ]
638641
@@ -641,6 +644,7 @@ name = "ec-ogg"
641644 version = "0.1.0"
642645 dependencies = [
643646 "ec-core",
647+ "ec-testkit",
644648 ]
645649
646650 [[package]]
@@ -691,6 +695,7 @@ dependencies = [
691695 "ec-opus",
692696 "ec-pcm-ext",
693697 "ec-riff",
698+ "ec-testkit",
694699 "ec-truehd",
695700 "ec-vorbis",
696701 ]
@@ -715,6 +720,7 @@ dependencies = [
715720 "ec-dv",
716721 "ec-mjpeg",
717722 "ec-mp4",
723+ "ec-testkit",
718724 ]
719725
720726 [[package]]
crates/ec-matroska/Cargo.tomlmodified+1 -0
@@ -11,6 +11,7 @@ ec-core.workspace = true
1111 ec-inflate.workspace = true
1212
1313 [dev-dependencies]
14+ec-testkit.workspace = true
1415 ec-mp4.workspace = true
1516 ec-aac.workspace = true
1617 ec-ac3.workspace = true
crates/ec-matroska/fuzz/seed.shmodified+5 -3
@@ -11,9 +11,11 @@
1111 # Corpus lives under fuzz/corpus, which is git-ignored.
1212 set -euo pipefail
1313
14+FF=${EC_FFMPEG:-$HOME/.cache/ec-ffmpeg/ffmpeg}
15+
1416 FUZZ_DIR=$(cd -- "$(dirname -- "$0")" && pwd)
15-FIXTURES=$(cd -- "$FUZZ_DIR/../../.." && pwd)/fixtures
16-[ -d "$FIXTURES/audio" ] || { echo "seed.sh: $FIXTURES/audio missing; run scripts/link-fixtures.sh" >&2; exit 2; }
17+FIXTURES=${EC_FIXTURES:-$(cd -- "$FUZZ_DIR/../../.." && pwd)/fixtures}
18+[ -d "$FIXTURES/audio" ] || { echo "seed.sh: $FIXTURES/audio missing; run scripts/fixtures.sh" >&2; exit 2; }
1719
1820 OPEN_DIR="$FUZZ_DIR/corpus/open_tracks"
1921 DEMUX_DIR="$FUZZ_DIR/corpus/demux_packets"
@@ -32,7 +34,7 @@ for src in "$FIXTURES"/audio/*.mka "$FIXTURES"/audio/*.mkv "$FIXTURES"/video/*.m
3234 if [ "$(stat -c %s "$src")" -le "$MAX" ]; then
3335 cp "$src" "$SCRATCH/$stem.mkv"
3436 else
35- ffmpeg -v error -y -t 0.2 -i "$src" -c copy "$SCRATCH/$stem.mkv"
37+ "$FF" -v error -y -t 0.2 -i "$src" -c copy "$SCRATCH/$stem.mkv"
3638 fi
3739 seed="$SCRATCH/$stem.mkv"
3840 size=$(stat -c %s "$seed")
crates/ec-matroska/tests/dts.rsmodified+5 -16
@@ -4,23 +4,18 @@
44
55 use std::io::Cursor;
66 use std::path::PathBuf;
7-use std::process::Command;
87
98 use ec_core::{CodecId, Demuxer, MediaParameters, Muxer};
109 use ec_matroska::{MatroskaDemuxer, MatroskaMuxer};
1110
12-fn required() -> bool {
13- std::env::var_os("EC_REQUIRE_FIXTURES").is_some_and(|v| !v.is_empty() && v != "0")
14-}
15-
1611 /// A DTS stream muxed by ffmpeg into `ext`'s container, plus the raw frames.
17-fn ffmpeg_dts(ext: &str, channels: &str) -> Option<(Vec<u8>, Vec<u8>)> {
12+fn ffmpeg_dts(ext: &str, channels: &str) -> (Vec<u8>, Vec<u8>) {
1813 let dir: PathBuf = std::env::temp_dir().join("ec-matroska-dts");
1914 std::fs::create_dir_all(&dir).unwrap();
2015 let out = dir.join(format!("{}-{channels}.{ext}", std::process::id()));
2116 let raw = dir.join(format!("{}-{channels}.dts", std::process::id()));
2217 let run = |args: &[&str]| {
23- Command::new("ffmpeg")
18+ ec_testkit::ffmpeg()
2419 .args(["-v", "error", "-y"])
2520 .args(args)
2621 .output()
@@ -45,15 +40,11 @@ fn ffmpeg_dts(ext: &str, channels: &str) -> Option<(Vec<u8>, Vec<u8>)> {
4540 "copy",
4641 raw.to_str().unwrap(),
4742 ]);
48- if !ok {
49- assert!(!required(), "ffmpeg cannot make a DTS fixture");
50- eprintln!("skip: no ffmpeg with the dca encoder");
51- return None;
52- }
43+ assert!(ok, "ffmpeg cannot make a DTS fixture");
5344 let pair = (std::fs::read(&out).unwrap(), std::fs::read(&raw).unwrap());
5445 let _ = std::fs::remove_file(out);
5546 let _ = std::fs::remove_file(raw);
56- Some(pair)
47+ pair
5748 }
5849
5950 fn demux_all(bytes: Vec<u8>) -> (MatroskaDemuxer<Cursor<Vec<u8>>>, Vec<ec_core::Packet>) {
@@ -66,9 +57,7 @@ fn demux_all(bytes: Vec<u8>) -> (MatroskaDemuxer<Cursor<Vec<u8>>>, Vec<ec_core::
6657 }
6758
6859 fn check(channels: &str, want: usize) {
69- let Some((mkv, raw)) = ffmpeg_dts("mkv", channels) else {
70- return;
71- };
60+ let (mkv, raw) = ffmpeg_dts("mkv", channels);
7261 let (d, pkts) = demux_all(mkv);
7362 let s = &d.streams()[0];
7463 assert_eq!(s.params.codec, CodecId::Dts);
crates/ec-matroska/tests/field_order.rsmodified+7 -29
@@ -3,42 +3,27 @@
33 //! because ffmpeg's HEVC decoder cannot derive it from the bitstream and
44 //! reports `unknown` without them.
55 //!
6-//! Sources are synthetic (ffmpeg `testsrc2`). A case skips where ffmpeg lacks
7-//! the encoder, unless `EC_REQUIRE_FIXTURES` is set.
86
97 use std::fs::File;
108 use std::io::{BufReader, BufWriter};
119 use std::path::{Path, PathBuf};
12-use std::process::Command;
1310
1411 use ec_core::{Demuxer, Error, Interlace, Muxer, Packet, StreamInfo};
1512 use ec_matroska::{MatroskaDemuxer, MatroskaMuxer};
1613 use ec_mp4::{Mp4Demuxer, Mp4Muxer};
1714
18-fn skip(why: &str) -> bool {
19- assert!(
20- std::env::var_os("EC_REQUIRE_FIXTURES").is_none(),
21- "EC_REQUIRE_FIXTURES set but: {why}"
22- );
23- eprintln!("skip: {why}");
24- true
25-}
26-
27-fn source(name: &str, encoder: &str) -> Option<(PathBuf, Vec<StreamInfo>, Vec<Packet>)> {
28- let enc = Command::new("ffmpeg")
15+fn source(name: &str, encoder: &str) -> (PathBuf, Vec<StreamInfo>, Vec<Packet>) {
16+ let enc = ec_testkit::ffmpeg()
2917 .args(["-hide_banner", "-encoders"])
3018 .output();
3119 let have =
3220 enc.is_ok_and(|o| String::from_utf8_lossy(&o.stdout).contains(&format!(" {encoder} ")));
33- if !have {
34- skip(&format!("no ffmpeg or no {encoder}"));
35- return None;
36- }
21+ assert!(have, "ffmpeg has no {encoder} encoder");
3722 let dir = std::env::temp_dir().join(format!("ec-field-order-{name}-{}", std::process::id()));
3823 let _ = std::fs::remove_dir_all(&dir);
3924 std::fs::create_dir_all(&dir).unwrap();
4025 let src = dir.join("src.mp4");
41- let ok = Command::new("ffmpeg")
26+ let ok = ec_testkit::ffmpeg()
4227 .args(["-hide_banner", "-v", "error", "-y", "-f", "lavfi", "-i"])
4328 .arg("testsrc2=size=320x240:rate=25:duration=1")
4429 .args(["-c:v", encoder, "-pix_fmt", "yuv420p", "-f", "mp4"])
@@ -56,7 +41,7 @@ fn source(name: &str, encoder: &str) -> Option<(PathBuf, Vec<StreamInfo>, Vec<Pa
5641 Err(e) => panic!("{e}"),
5742 }
5843 }
59- Some((dir, streams, packets))
44+ (dir, streams, packets)
6045 }
6146
6247 fn mux_mp4(dst: &Path, s: &[StreamInfo], p: &[Packet], order: Option<Option<Interlace>>) {
@@ -88,7 +73,7 @@ fn mux_mkv(dst: &Path, s: &[StreamInfo], p: &[Packet], order: Option<Option<Inte
8873 }
8974
9075 fn probe(path: &Path) -> String {
91- let out = Command::new("ffprobe")
76+ let out = ec_testkit::ffprobe()
9277 .args(["-v", "error", "-select_streams", "v:0", "-show_entries"])
9378 .arg("stream=field_order")
9479 .args(["-of", "csv=p=0"])
@@ -111,14 +96,7 @@ fn mkv_order(path: &Path) -> Option<Interlace> {
11196 }
11297
11398 fn run(name: &str, encoder: &str, unstated: &str) {
114- let Some((dir, s, p)) = source(name, encoder) else {
115- return;
116- };
117- let ffprobe = Command::new("ffprobe").arg("-version").output().is_ok();
118- if !ffprobe {
119- skip("no ffprobe");
120- return;
121- }
99+ let (dir, s, p) = source(name, encoder);
122100 let cases = [
123101 (None, "progressive", Some(Interlace::Progressive)),
124102 (
crates/ec-matroska/tests/hdr_metadata.rsmodified+7 -14
@@ -5,7 +5,6 @@
55 use std::fs::File;
66 use std::io::{BufReader, BufWriter};
77 use std::path::Path;
8-use std::process::Command;
98
109 use ec_core::{ContentLight, Demuxer, Error, MasteringPrimaries, Muxer, Packet, StreamInfo};
1110 use ec_matroska::{MatroskaDemuxer, MatroskaMuxer};
@@ -45,23 +44,17 @@ fn mux(dst: &Path, s: &[StreamInfo], p: &[Packet], light: Option<ContentLight>)
4544
4645 #[test]
4746 fn hevc_main10_mastering_metadata_in_mkv() {
48- let enc = Command::new("ffmpeg").args(["-hide_banner", "-encoders"]).output();
49- if !enc.is_ok_and(|o| String::from_utf8_lossy(&o.stdout).contains(" libx265 "))
50- || Command::new("ffprobe").arg("-version").output().is_err()
51- {
52- assert!(
53- std::env::var_os("EC_REQUIRE_FIXTURES").is_none(),
54- "EC_REQUIRE_FIXTURES set but no ffmpeg with libx265"
55- );
56- eprintln!("skip: no ffmpeg/ffprobe/libx265");
57- return;
58- }
47+ let enc = ec_testkit::ffmpeg().args(["-hide_banner", "-encoders"]).output();
48+ assert!(
49+ enc.is_ok_and(|o| String::from_utf8_lossy(&o.stdout).contains(" libx265 ")),
50+ "ffmpeg has no libx265 encoder"
51+ );
5952 let dir = std::env::temp_dir().join(format!("ec-mkv-hdr-{}", std::process::id()));
6053 let _ = std::fs::remove_dir_all(&dir);
6154 std::fs::create_dir_all(&dir).unwrap();
6255 let src = dir.join("src.mp4");
6356 assert!(
64- Command::new("ffmpeg")
57+ ec_testkit::ffmpeg()
6558 .args(["-v", "error", "-y", "-f", "lavfi", "-i", "testsrc2=size=320x240:rate=25:duration=1"])
6659 .args(["-c:v", "libx265", "-pix_fmt", "yuv420p10le", "-tag:v", "hvc1"])
6760 .args(["-x265-params", "log-level=error:colorprim=bt2020:transfer=smpte2084:colormatrix=bt2020nc"])
@@ -89,7 +82,7 @@ fn hevc_main10_mastering_metadata_in_mkv() {
8982
9083 let dst = dir.join("hdr.mkv");
9184 mux(&dst, &streams, &packets, Some(light()));
92- let out = Command::new("ffprobe")
85+ let out = ec_testkit::ffprobe()
9386 .args(["-v", "error", "-show_streams", "-show_frames", "-read_intervals", "%+#1", "-of", "json"])
9487 .arg(&dst)
9588 .output()
crates/ec-matroska/tests/matroska.rsmodified+7 -790
@@ -6,10 +6,9 @@
66 use std::fs::File;
77 use std::io::{BufReader, Cursor};
88 use std::path::{Path, PathBuf};
9-use std::process::Command;
109
1110 use ec_core::{
12- CodecId, Demuxer, Error, MediaParameters, MediaType, Muxer, Packet, SeekMode, StreamInfo,
11+ CodecId, Demuxer, Error, MediaParameters, Muxer, Packet, SeekMode, StreamInfo,
1312 TimeBase, Timestamp,
1413 };
1514 use ec_matroska::{MatroskaDemuxer, MatroskaMuxer};
@@ -89,7 +88,7 @@ fn truehd_codec_id_round_trips_through_remux() {
8988 }
9089
9190 fn fixtures() -> PathBuf {
92- Path::new(env!("CARGO_MANIFEST_DIR")).join("../../fixtures")
91+ ec_testkit::root()
9392 }
9493
9594 fn work() -> PathBuf {
@@ -103,7 +102,7 @@ fn work() -> PathBuf {
103102 /// this crate claims are exactly the ones that have to be exercised.
104103 fn matroska_fixtures() -> Vec<PathBuf> {
105104 let mut files: Vec<PathBuf> = std::fs::read_dir(fixtures().join("video"))
106- .expect("fixtures/video (run scripts/gen-fixtures.sh)")
105+ .expect("fixtures/video (run scripts/fixtures.sh)")
107106 .filter_map(|e| e.ok().map(|e| e.path()))
108107 .filter(|p| {
109108 let name = p.to_string_lossy();
@@ -217,7 +216,7 @@ fn make_derived(dst: &Path, args: &[&str]) -> bool {
217216 return true;
218217 }
219218 let tmp = dst.with_file_name(format!("tmp-{}-{name}", std::process::id()));
220- let ok = Command::new("ffmpeg")
219+ let ok = ec_testkit::ffmpeg()
221220 .args(["-v", "error", "-y"])
222221 .args(args)
223222 .arg(&tmp)
@@ -233,7 +232,7 @@ fn make_derived(dst: &Path, args: &[&str]) -> bool {
233232
234233 /// The fields a remux must not change, as ffprobe reads them back.
235234 fn probe(path: &Path) -> String {
236- let out = Command::new("ffprobe")
235+ let out = ec_testkit::ffprobe()
237236 .args([
238237 "-v",
239238 "error",
@@ -256,7 +255,7 @@ fn probe(path: &Path) -> String {
256255 }
257256
258257 fn duration(path: &Path) -> f64 {
259- let out = Command::new("ffprobe")
258+ let out = ec_testkit::ffprobe()
260259 .args([
261260 "-v",
262261 "error",
@@ -456,7 +455,7 @@ fn every_fixture_remuxes_into_a_file_ffprobe_and_ffmpeg_agree_with() {
456455 a_seek_to_the_beginning_lands_on_the_first_packet(&dst);
457456
458457 // ...and it decodes, which is the only claim a field compare cannot make.
459- let decode = Command::new("ffmpeg")
458+ let decode = ec_testkit::ffmpeg()
460459 .args(["-v", "error", "-i"])
461460 .arg(&dst)
462461 .args(["-f", "null", "-"])
@@ -556,178 +555,6 @@ fn a_hundred_random_seeks_land_at_or_before_their_target_on_one_reader() {
556555 println!("{}", table.join("\n"));
557556 }
558557
559-/// A sweep of the real library: ten films, one per directory so a 60-episode
560-/// series counts once, each demuxed end to end and its packet counts compared
561-/// with ffprobe's. Ignored by default because it reads tens of gigabytes.
562-///
563-/// Run it with `cargo test -p ec-matroska --release --test matroska -- --ignored
564-/// --nocapture`.
565-#[test]
566-#[ignore = "reads the real library end to end"]
567-fn real_library_spot_sweep() {
568- let manifest = std::fs::read_to_string(fixtures().join("real-library-manifest.tsv"))
569- .expect("fixtures/real-library-manifest.tsv");
570- let mut seen: Vec<String> = Vec::new();
571- let mut files: Vec<PathBuf> = Vec::new();
572- for line in manifest.lines().skip(1) {
573- let mut cols = line.split('\t');
574- let (Some(path), Some(container)) = (cols.next(), cols.next()) else {
575- continue;
576- };
577- let path = PathBuf::from(path);
578- if !container.contains("matroska") || !path.exists() {
579- continue;
580- }
581- // One per directory: a series of sixty episodes is one shape, not sixty.
582- let dir = path
583- .parent()
584- .unwrap_or(Path::new("/"))
585- .to_string_lossy()
586- .into_owned();
587- if seen.contains(&dir) {
588- continue;
589- }
590- seen.push(dir);
591- files.push(path);
592- }
593- assert!(
594- files.len() >= 10,
595- "only {} Matroska directories",
596- files.len()
597- );
598- let step = (files.len() / 10).max(1);
599- let picked: Vec<PathBuf> = files.into_iter().step_by(step).take(10).collect();
600-
601- let mut table = Vec::new();
602- for path in &picked {
603- let mut demuxer =
604- MatroskaDemuxer::new(BufReader::new(File::open(path).expect("film opens")))
605- .expect("demuxes");
606- let streams: Vec<String> = demuxer
607- .streams()
608- .iter()
609- .map(|s| s.params.codec.name().to_string())
610- .collect();
611- let text: Vec<u32> = demuxer
612- .streams()
613- .iter()
614- .filter(|s| {
615- matches!(
616- s.params.codec,
617- ec_core::CodecId::Srt | ec_core::CodecId::Ass | ec_core::CodecId::WebVtt
618- )
619- })
620- .map(|s| s.index)
621- .collect();
622- let mut counts = vec![0usize; streams.len()];
623- let mut checked = Vec::new();
624- loop {
625- match demuxer.next_packet() {
626- Ok(p) => {
627- counts[p.stream as usize] += 1;
628- // A text track under `ContentEncodings` that came back
629- // still compressed is not UTF-8, which is the cheapest
630- // proof the zlib path ran.
631- if text.contains(&p.stream) && !checked.contains(&p.stream) {
632- checked.push(p.stream);
633- assert!(
634- std::str::from_utf8(&p.data).is_ok(),
635- "{}: stream {} is not text",
636- path.display(),
637- p.stream
638- );
639- }
640- }
641- Err(Error::Eof) => break,
642- Err(e) => panic!("{}: {e}", path.display()),
643- }
644- }
645- // ffprobe counts the same packets on the same file; the picture track is
646- // first in both and is the one compared exactly.
647- let out = Command::new("ffprobe")
648- .args([
649- "-v",
650- "error",
651- "-count_packets",
652- "-show_entries",
653- "stream=nb_read_packets",
654- "-of",
655- "csv=p=0",
656- ])
657- .arg(path)
658- .output()
659- .expect("ffprobe runs");
660- let theirs: Vec<usize> = String::from_utf8_lossy(&out.stdout)
661- .lines()
662- // ffprobe leaves a trailing separator on a row whose fields it
663- // padded; the count is the first number on the line.
664- .filter_map(|l| l.trim().trim_end_matches(',').parse().ok())
665- .collect();
666- assert_eq!(
667- counts.first(),
668- theirs.first(),
669- "{}: picture packet count",
670- path.display()
671- );
672- assert!(counts.iter().sum::<usize>() > 0);
673-
674- // ...and twenty seeks spread over the film, on one more reader, each
675- // landing on a random-access point at or before its target. A film is
676- // where a cue table is worth having: the fixtures are two seconds long
677- // and every one of their clusters is a keyframe.
678- let mut demuxer =
679- MatroskaDemuxer::new(BufReader::new(File::open(path).expect("film opens")))
680- .expect("demuxes");
681- let stream = demuxer.streams()[0].index;
682- // Where the picture actually starts: a film whose video track begins at
683- // 83 ms has nothing earlier to land on, and that is not a failed seek.
684- let first = loop {
685- let packet = demuxer.next_packet().expect("a first keyframe");
686- if packet.stream == stream && packet.flags.keyframe {
687- break packet.time_base.rescale(
688- packet.pts.unwrap_or(0),
689- TimeBase::MILLIS,
690- ec_core::Rounding::Down,
691- );
692- }
693- };
694- let secs = duration(path).max(1.0);
695- for i in 0..20 {
696- let target_ms = (secs * 1000.0 * f64::from(i) / 20.0) as i64;
697- demuxer
698- .seek(
699- stream,
700- Timestamp::new(target_ms, TimeBase::MILLIS),
701- SeekMode::SyncBefore,
702- )
703- .unwrap_or_else(|e| panic!("{}: seek to {target_ms}ms: {e}", path.display()));
704- let packet = loop {
705- match demuxer.next_packet() {
706- Ok(p) if p.stream == stream => break p,
707- Ok(_) => continue,
708- Err(e) => panic!("{}: after seek: {e}", path.display()),
709- }
710- };
711- let ms = packet.time_base.rescale(
712- packet.pts.unwrap_or(0),
713- TimeBase::MILLIS,
714- ec_core::Rounding::Down,
715- );
716- assert!(
717- packet.flags.keyframe && (ms <= target_ms || ms == first),
718- "{}: seek to {target_ms}ms landed at {ms}ms, key {}",
719- path.display(),
720- packet.flags.keyframe
721- );
722- }
723- table.push(format!(
724- "{:<64} {streams:?} ours {counts:?} ffprobe {theirs:?}",
725- path.file_name().unwrap().to_string_lossy()
726- ));
727- }
728- println!("{}", table.join("\n"));
729-}
730-
731558 /// A file whose *first* cluster holds only sound: seeking its audio track to
732559 /// the beginning lands on that block, not on the first cue.
733560 ///
@@ -857,616 +684,6 @@ fn matroska_prefix_class(data: &[u8]) -> (&'static str, u64) {
857684 }
858685 }
859686
860-/// Where our own demuxer's seek lands on a real 5.1 E-AC-3 Matroska, in
861-/// *timestamp* -- split from decode, per the round's charter: this measures
862-/// only [`MatroskaDemuxer::seek`] plus the first packet's `pts`, against what
863-/// `ffprobe` reports for the same track near the same instant. If this lands
864-/// exact, the +0.145 s the consumer measured is downstream of the demuxer
865-/// (the AC-3 decoder or its frame-count bookkeeping in `engine`), not here.
866-///
867-/// Skipped, not failed, without the film: a claim about his library cannot be
868-/// made by a machine that does not have it.
869-#[test]
870-fn seek_landing_on_his_eac3_film_matches_ffprobe() {
871- same_class_sweep(
872- "/home/user/Downloads/reeld/reeld.mkv",
873- &[600.0, 610.0],
874- 40.0,
875- );
876- // Same-class sweep (round charter task 3): an Opus 5.1 Matroska, a codec
877- // that already goes through this crate's demuxer -- if this lands as
878- // tight as the E-AC-3 one, the demuxer's seek is not codec-specific and
879- // the +0.145 s the consumer measured on the E-AC-3 path is downstream of
880- // it either way.
881- same_class_sweep(
882- "/home/user/Downloads/reelb.mkv",
883- &[600.0, 610.0],
884- 20.0,
885- );
886-}
887-
888-/// `A_OPUS` with no `DefaultDuration` and 8-frame laces (ReelC, seeAlso
889-/// `demux.rs::codec_frame_ticks`): a `SyncBefore` landing mid-lace has to
890-/// report the true pts of the frame it lands on -- base-pts-for-every-frame-
891-/// in-the-lace collapsed every mid-lace landing onto the lace's first frame,
892-/// up to 140 ms early.
893-#[test]
894-fn seek_lands_on_the_true_frame_in_a_laced_opus_track() {
895- same_class_sweep(
896- "/home/user/Videos/Films/reelc.mkv",
897- &[123.4, 600.0, 1800.0, 4500.0],
898- 20.0,
899- );
900-}
901-
902-/// Where our own demuxer's seek lands on `path`, in *timestamp* -- split from
903-/// decode, per the round's charter: this measures only
904-/// [`MatroskaDemuxer::seek`] plus the first packet's `pts`, against what
905-/// `ffprobe` reports for the same track near the same instant.
906-///
907-/// Skipped, not failed, without the film: a claim about his library cannot be
908-/// made by a machine that does not have it.
909-fn same_class_sweep(path: &str, wants: &[f64], tolerance_ms: f64) {
910- let film = Path::new(path);
911- if !film.exists() {
912- eprintln!("skipped: {path} is not present");
913- return;
914- }
915- let mut demux =
916- MatroskaDemuxer::new(BufReader::new(File::open(film).expect("opens"))).expect("demuxes");
917- let audio = demux
918- .streams()
919- .iter()
920- .find(|s| s.params.codec.media_type() == MediaType::Audio)
921- .expect("the film has an audio stream")
922- .clone();
923-
924- for &want in wants {
925- let target = Timestamp::new(
926- (want * audio.time_base.den() as f64 / audio.time_base.num() as f64).round() as i64,
927- audio.time_base,
928- );
929- demux
930- .seek(audio.index, target, SeekMode::SyncBefore)
931- .expect("seek");
932- let landed = loop {
933- let packet = demux.next_packet().expect("a packet after the seek");
934- if packet.stream == audio.index {
935- break packet.pts.expect("audio packet carries a pts");
936- }
937- };
938- let our_secs = landed as f64 * audio.time_base.num() as f64 / audio.time_base.den() as f64;
939- // `SyncBefore`'s own contract: the landed frame is at or before the
940- // target, and no further before it than a lace's worth of drift.
941- assert!(
942- our_secs <= want + 1e-6,
943- "{path}: SyncBefore landed at {our_secs:.3}s, after the {want}s it was asked for"
944- );
945- assert!(
946- want - our_secs <= tolerance_ms / 1000.0,
947- "{path}: wanted {want}s, landed {our_secs:.3}s -- {:.1} ms short, over the {tolerance_ms} ms budget",
948- (want - our_secs) * 1000.0
949- );
950-
951- let ffprobe = Command::new("ffprobe")
952- .args([
953- "-v",
954- "error",
955- "-select_streams",
956- "a:0",
957- "-show_entries",
958- "packet=pts_time",
959- "-of",
960- "csv=p=0",
961- "-read_intervals",
962- ])
963- .arg(format!("{want}%+#1"))
964- .arg(film)
965- .output();
966- let Ok(ffprobe) = ffprobe else {
967- eprintln!("skipped ffprobe cross-check: ffprobe not runnable");
968- eprintln!("want {want}s, our demuxer landed at {our_secs:.3}s (pts {landed})");
969- continue;
970- };
971- let reference: f64 = String::from_utf8_lossy(&ffprobe.stdout)
972- .lines()
973- .next()
974- .unwrap_or("")
975- .trim()
976- .parse()
977- .unwrap_or(f64::NAN);
978- eprintln!(
979- "want {want}s: our demuxer landed {our_secs:.3}s (pts {landed}), ffprobe's own packet at {reference:.3}s"
980- );
981- }
982-}
983-
984-/// Same-class sweep (round charter task, "same-class sweep" line): every
985-/// Matroska in his real library whose audio is one of the laced-frame
986-/// families this round's fix touches (Opus, AAC, FLAC, Vorbis), landed on at
987-/// two points each and printed as a table. `SyncBefore`'s own contract --
988-/// never land after the target -- is the one thing asserted for every file;
989-/// how close under it a codec this round did not give a bitstream-derived
990-/// duration to (FLAC, Vorbis) lands is reported, not enforced, since those
991-/// two still fall back to the pre-fix `DefaultDuration`-or-zero step.
992-///
993-/// Ignored: 79 files, two seeks and an `ffprobe`-free landing check each --
994-/// slow enough that it does not belong in the default run, real enough that
995-/// it should not be skipped either.
996-#[test]
997-#[ignore = "sweeps his real library, run manually with --ignored"]
998-fn laced_audio_sweep_across_his_library() {
999- // lane-h264reallib: `fixtures()` like every sibling, instead of a
1000- // hardcoded absolute path into the primary checkout. The absolute form
1001- // silently defeated worktree isolation: a run in a worktree or a gate tree
1002- // read the MAIN checkout's manifest, so this test measured a different
1003- // tree's library than the one it was compiled from.
1004- let manifest = &fixtures().join("real-library-manifest.tsv");
1005- let Ok(rows) = std::fs::read_to_string(manifest) else {
1006- eprintln!("skipped: {} not present", manifest.display());
1007- return;
1008- };
1009- for line in rows.lines().skip(1) {
1010- let cols: Vec<&str> = line.split('\t').collect();
1011- let [path, container, _v, _w, _h, _pf, _bd, acodecs, duration, ..] = cols[..] else {
1012- continue;
1013- };
1014- if container != "matroska,webm"
1015- || !["opus", "aac", "flac", "vorbis"]
1016- .iter()
1017- .any(|c| acodecs.contains(c))
1018- {
1019- continue;
1020- }
1021- let Ok(duration) = duration.parse::<f64>() else {
1022- continue;
1023- };
1024- let film = Path::new(path);
1025- if !film.exists() {
1026- continue;
1027- }
1028- let Ok(mut demux) = MatroskaDemuxer::new(BufReader::new(File::open(film).expect("opens")))
1029- else {
1030- eprintln!("{path}: failed to open");
1031- continue;
1032- };
1033- let Some(audio) = demux
1034- .streams()
1035- .iter()
1036- .find(|s| s.params.codec.media_type() == MediaType::Audio)
1037- .cloned()
1038- else {
1039- continue;
1040- };
1041- for frac in [0.3, 0.7] {
1042- let want = duration * frac;
1043- let target = Timestamp::new(
1044- (want * audio.time_base.den() as f64 / audio.time_base.num() as f64).round() as i64,
1045- audio.time_base,
1046- );
1047- if demux
1048- .seek(audio.index, target, SeekMode::SyncBefore)
1049- .is_err()
1050- {
1051- eprintln!("{path} ({acodecs}) @ {want:.1}s: seek failed");
1052- continue;
1053- }
1054- let landed = loop {
1055- match demux.next_packet() {
1056- Ok(packet) if packet.stream == audio.index => break packet.pts,
1057- Ok(_) => continue,
1058- Err(_) => break None,
1059- }
1060- };
1061- let our_secs = landed.map(|pts| {
1062- pts as f64 * audio.time_base.num() as f64 / audio.time_base.den() as f64
1063- });
1064- // Not asserted here (unlike the two targeted tests above): a want
1065- // that falls before this file's first audio packet legitimately
1066- // lands after it -- `seek`'s own documented fallback, "nothing
1067- // earlier to decode from" -- so an after-target landing is
1068- // reported, not failed, for a sweep that does not hand-pick times
1069- // deep inside each file's audio.
1070- eprintln!(
1071- "{path} ({acodecs}) @ {want:.1}s: landed {:.3}",
1072- our_secs.unwrap_or(f64::NAN)
1073- );
1074- }
1075- }
1076-}
1077-
1078-/// `ffprobe` reports MaxCLL 1230 / MaxFALL 419 for this real HDR10 film, but
1079-/// that reading comes from `[SIDE_DATA]` on the first *frame* (a
1080-/// `content_light_level_information` HEVC SEI message inside the bitstream),
1081-/// not from the container's own `Colour` element. This file's `Colour`
1082-/// element genuinely carries no `MaxCLL`/`MaxFALL`/`MasteringMetadata`
1083-/// children (checked with `ffprobe -show_entries stream=side_data_list`,
1084-/// which comes back empty) — so a demuxer-only reader is correct to return
1085-/// `None` here, and the consumer's brightness-metadata gap is downstream, in
1086-/// whether anything reads the HEVC SEI (`ec_core::color::hevc_sei_light`
1087-/// exists and round-trips in `ec-h265-syntax`, but nothing in this workspace
1088-/// calls it from a real decode path yet).
1089-#[test]
1090-#[ignore = "reads a real local file, not a CI fixture"]
1091-fn real_hdr_film_container_states_no_light_metadata() {
1092- use ec_core::{Demuxer, MediaParameters};
1093- use ec_matroska::MatroskaDemuxer;
1094- let path = "/home/user/Downloads/reeld/reeld.mkv";
1095- if !std::path::Path::new(path).exists() {
1096- eprintln!("skipped: film not present");
1097- return;
1098- }
1099- let f = std::fs::File::open(path).expect("open");
1100- let demux = MatroskaDemuxer::new(f).expect("demux opens");
1101- let mut checked = false;
1102- for s in demux.streams() {
1103- if let MediaParameters::Video(v) = &s.params.media {
1104- println!("color = {:?}", v.color);
1105- println!("light = {:?}", v.light);
1106- // BT.2020 non-constant luminance, PQ transfer, BT.2020 primaries —
1107- // this much the Colour element does carry, and it must match
1108- // ffprobe's color_space/color_primaries/color_transfer.
1109- assert_eq!(v.color.matrix, 9, "expected bt2020nc");
1110- assert_eq!(v.color.transfer, 16, "expected smpte2084 (PQ)");
1111- assert_eq!(v.color.primaries, 9, "expected bt2020");
1112- assert_eq!(
1113- v.light,
1114- ec_core::color::ContentLight::default(),
1115- "the Colour element has no light metadata for this file — a \
1116- non-default reading here would mean either ffprobe or this \
1117- reader started finding it in the container and the doc \
1118- comment above is stale"
1119- );
1120- checked = true;
1121- }
1122- }
1123- assert!(checked, "no video stream found");
1124-}
1125-
1126-// ===== mkv-vs-mp4 audio A/B (mkv-audio-timing) =====
1127-//
1128-// The consumer sweep found: same OBS recording's `.mkv` leg scores far below
1129-// its sibling `.mp4` leg on channel-0 correlation from t=0, and 5.1 AC-3/E-AC-3
1130-// tracks that are only ever carried in Matroska score near zero. These tests
1131-// isolate whether that is packet delivery out of `ec-matroska` (order,
1132-// duplication, pts) or the shared decoder crate, and which physical channel
1133-// our 5.1 decode calls "channel 0".
1134-
1135-use ec_aac::AacDecoder;
1136-use ec_ac3::Ac3Decoder;
1137-
1138-/// Opens whichever container `path` actually is — both crates implement the
1139-/// same `Demuxer` trait, so the rest of the harness never has to know which.
1140-fn open_any(path: &Path) -> Box<dyn Demuxer> {
1141- use std::io::Read;
1142- let mut head = [0u8; 12];
1143- File::open(path)
1144- .expect("open")
1145- .read_exact(&mut head)
1146- .expect("read head");
1147- if ec_mp4::is_mp4(&head) {
1148- Box::new(
1149- ec_mp4::Mp4Demuxer::new(BufReader::new(File::open(path).expect("open")))
1150- .expect("mp4 opens"),
1151- )
1152- } else {
1153- Box::new(
1154- MatroskaDemuxer::new(BufReader::new(File::open(path).expect("open")))
1155- .expect("mkv opens"),
1156- )
1157- }
1158-}
1159-
1160-/// The first stream of `codec`'s extradata plus its packets, `(pts, data)`,
1161-/// in the order the container's own demuxer hands them back — capped so a
1162-/// multi-gigabyte recording does not have to be decoded whole.
1163-/// The track's CodecPrivate, sample rate, and its (timestamp, payload) packets.
1164-type AudioTrack = (Option<Vec<u8>>, u32, Vec<(i64, Vec<u8>)>);
1165-
1166-fn audio_track(path: &Path, codec: CodecId) -> Option<AudioTrack> {
1167- let mut d = open_any(path);
1168- let s = d.streams().iter().find(|s| s.params.codec == codec)?;
1169- let idx = s.index;
1170- let extradata = s.params.extradata.as_ref().map(|b| b.to_vec());
1171- let rate = s.params.audio()?.sample_rate;
1172- let mut pkts = Vec::new();
1173- loop {
1174- match d.next_packet() {
1175- Ok(p) if p.stream == idx => {
1176- pkts.push((p.pts.unwrap_or(0), p.data.to_vec()));
1177- if pkts.len() >= 2_000 {
1178- break;
1179- }
1180- }
1181- Ok(_) => continue,
1182- Err(_) => break,
1183- }
1184- }
1185- Some((extradata, rate, pkts))
1186-}
1187-
1188-/// Our AAC decode of a container's access units, interleaved-to-planar.
1189-fn decode_aac(extradata: &[u8], pkts: &[(i64, Vec<u8>)]) -> Vec<Vec<f32>> {
1190- let mut decoder = AacDecoder::with_config_bytes(extradata).expect("AudioSpecificConfig parses");
1191- let mut planes: Vec<Vec<f32>> = Vec::new();
1192- for (_, au) in pkts {
1193- let Ok(frame) = decoder.decode(au, None) else {
1194- continue;
1195- };
1196- let ch = usize::from(frame.channels);
1197- if ch == 0 {
1198- continue;
1199- }
1200- if planes.is_empty() {
1201- planes = vec![Vec::new(); ch];
1202- }
1203- for (i, v) in frame.samples.iter().enumerate() {
1204- planes[i % ch].push(*v);
1205- }
1206- }
1207- planes
1208-}
1209-
1210-/// Our AC-3/E-AC-3 decode of a container's frames, interleaved-to-planar.
1211-fn decode_ac3(pkts: &[(i64, Vec<u8>)]) -> Vec<Vec<f32>> {
1212- let mut decoder = Ac3Decoder::new();
1213- let mut planes: Vec<Vec<f32>> = Vec::new();
1214- for (_, data) in pkts {
1215- let Ok(frame) = decoder.decode_frame(data) else {
1216- continue;
1217- };
1218- let ch = frame.channels();
1219- if ch == 0 {
1220- continue;
1221- }
1222- if planes.is_empty() {
1223- planes = vec![Vec::new(); ch];
1224- }
1225- let samples: Vec<f32> = frame.data[0]
1226- .as_chunks::<4>()
1227- .0
1228- .iter()
1229- .map(|c| f32::from_le_bytes(*c))
1230- .collect();
1231- for (i, v) in samples.iter().enumerate() {
1232- planes[i % ch].push(*v);
1233- }
1234- }
1235- planes
1236-}
1237-
1238-fn have_ffmpeg() -> bool {
1239- Command::new("ffmpeg")
1240- .arg("-version")
1241- .output()
1242- .is_ok_and(|o| o.status.success())
1243-}
1244-
1245-/// ffmpeg's decode of a file's first audio stream, planar by channel.
1246-fn ffmpeg_decode_planar(path: &Path, channels: usize) -> Vec<Vec<f32>> {
1247- let out = Command::new("ffmpeg")
1248- .args(["-v", "error", "-i"])
1249- .arg(path)
1250- .args([
1251- "-map",
1252- "0:a:0",
1253- "-t",
1254- "20",
1255- "-f",
1256- "f32le",
1257- "-acodec",
1258- "pcm_f32le",
1259- "-",
1260- ])
1261- .output()
1262- .expect("ffmpeg runs");
1263- assert!(
1264- out.status.success(),
1265- "ffmpeg decode failed: {}",
1266- String::from_utf8_lossy(&out.stderr)
1267- );
1268- let samples: Vec<f32> = out
1269- .stdout
1270- .as_chunks::<4>()
1271- .0
1272- .iter()
1273- .map(|c| f32::from_le_bytes(*c))
1274- .collect();
1275- let mut planes = vec![Vec::with_capacity(samples.len() / channels.max(1)); channels];
1276- for (i, v) in samples.iter().enumerate() {
1277- planes[i % channels].push(*v);
1278- }
1279- planes
1280-}
1281-
1282-fn correlation(a: &[f32], b: &[f32]) -> f64 {
1283- let n = a.len().min(b.len());
1284- if n < 1024 {
1285- return 0.0;
1286- }
1287- let (a, b) = (&a[..n], &b[..n]);
1288- let ma = a.iter().map(|v| f64::from(*v)).sum::<f64>() / n as f64;
1289- let mb = b.iter().map(|v| f64::from(*v)).sum::<f64>() / n as f64;
1290- let (mut num, mut da, mut db) = (0.0f64, 0.0f64, 0.0f64);
1291- for i in 0..n {
1292- let (x, y) = (f64::from(a[i]) - ma, f64::from(b[i]) - mb);
1293- num += x * y;
1294- da += x * x;
1295- db += y * y;
1296- }
1297- let den = (da * db).sqrt();
1298- if den == 0.0 { 0.0 } else { num / den }
1299-}
1300-
1301-/// Best correlation over a bounded lag search from the start of both
1302-/// streams — the whole point here is t=0 alignment, so no whole-file window
1303-/// slide is needed, just enough lag to absorb container/codec delay.
1304-const LAG_MAX: i64 = 4_000;
1305-const WINDOW: usize = 100_000;
1306-
1307-fn best_lag_correlation(ours: &[f32], theirs: &[f32]) -> (i64, f64) {
1308- let mut best_abs = -1.0f64;
1309- let mut best = (0i64, 0.0f64);
1310- for lag in -LAG_MAX..=LAG_MAX {
1311- let (oa, ob) = if lag >= 0 {
1312- (0usize, lag as usize)
1313- } else {
1314- ((-lag) as usize, 0usize)
1315- };
1316- let len = WINDOW
1317- .min(ours.len().saturating_sub(oa))
1318- .min(theirs.len().saturating_sub(ob));
1319- if len < 1024 {
1320- continue;
1321- }
1322- let c = correlation(&ours[oa..oa + len], &theirs[ob..ob + len]);
1323- if c.abs() > best_abs {
1324- best_abs = c.abs();
1325- best = (lag, c);
1326- }
1327- }
1328- best
1329-}
1330-
1331-/// mkv vs mp4: the same recording's AAC stream, decoded through each
1332-/// container's own demux path, ours-vs-ours and each vs ffmpeg. Isolates the
1333-/// consumer sweep's "same channel 0, same track, `.mkv` corr 0.06-0.34 but
1334-/// sibling `.mp4` 0.76-0.92" finding to this crate's packet delivery or to
1335-/// the shared AAC decoder.
1336-///
1337-/// Run with `cargo test -p ec-matroska --test matroska mkv_vs_mp4_aac_pipeline -- --ignored --nocapture`.
1338-#[test]
1339-#[ignore = "reads the real library, mkv-audio-timing A/B"]
1340-fn mkv_vs_mp4_aac_pipeline() {
1341- if !have_ffmpeg() {
1342- eprintln!("skipped: no ffmpeg");
1343- return;
1344- }
1345- let obs = Path::new("/home/user/Videos/OBS");
1346- let stems = [
1347- "2026-07-25 02-09-04",
1348- "2026-08-17 01-57-17",
1349- "2026-08-17 11-01-56",
1350- ];
1351- let mut any = false;
1352- for stem in stems {
1353- let mkv = obs.join(format!("{stem}.mkv"));
1354- let mp4 = obs.join(format!("{stem}.mp4"));
1355- if !mkv.exists() || !mp4.exists() {
1356- continue;
1357- }
1358- any = true;
1359- println!("=== {stem} ===");
1360- let (mkv_asc, mkv_rate, mkv_pkts) = audio_track(&mkv, CodecId::Aac).expect("mkv aac track");
1361- let (mp4_asc, mp4_rate, mp4_pkts) = audio_track(&mp4, CodecId::Aac).expect("mp4 aac track");
1362- println!(
1363- "mkv asc={:02x?} rate={mkv_rate} packets={} bytes={}",
1364- mkv_asc,
1365- mkv_pkts.len(),
1366- mkv_pkts.iter().map(|(_, d)| d.len()).sum::<usize>()
1367- );
1368- println!(
1369- "mp4 asc={:02x?} rate={mp4_rate} packets={} bytes={}",
1370- mp4_asc,
1371- mp4_pkts.len(),
1372- mp4_pkts.iter().map(|(_, d)| d.len()).sum::<usize>()
1373- );
1374- println!(
1375- "mkv first5 pts = {:?}",
1376- mkv_pkts.iter().take(5).map(|(p, _)| *p).collect::<Vec<_>>()
1377- );
1378- println!(
1379- "mp4 first5 pts = {:?}",
1380- mp4_pkts.iter().take(5).map(|(p, _)| *p).collect::<Vec<_>>()
1381- );
1382- let (mut out_of_order, mut dup) = (0, 0);
1383- for w in mkv_pkts.windows(2) {
1384- if w[1].0 < w[0].0 {
1385- out_of_order += 1;
1386- }
1387- if w[1].0 == w[0].0 {
1388- dup += 1;
1389- }
1390- }
1391- println!("mkv out_of_order={out_of_order} dup_pts={dup}");
1392-
1393- let mkv_planes = decode_aac(mkv_asc.as_deref().unwrap_or(&[]), &mkv_pkts);
1394- let mp4_planes = decode_aac(mp4_asc.as_deref().unwrap_or(&[]), &mp4_pkts);
1395- assert!(
1396- !mkv_planes.is_empty() && !mp4_planes.is_empty(),
1397- "{stem}: decode produced no channels (mkv {} ch, mp4 {} ch)",
1398- mkv_planes.len(),
1399- mp4_planes.len()
1400- );
1401-
1402- let (lag, c_mm) = best_lag_correlation(&mkv_planes[0], &mp4_planes[0]);
1403- let mkv_ff = ffmpeg_decode_planar(&mkv, mkv_planes.len());
1404- let mp4_ff = ffmpeg_decode_planar(&mp4, mp4_planes.len());
1405- let (_, c_mkv_ff) = best_lag_correlation(&mkv_planes[0], &mkv_ff[0]);
1406- let (_, c_mp4_ff) = best_lag_correlation(&mp4_planes[0], &mp4_ff[0]);
1407- println!(
1408- "{stem}: mkv-vs-mp4(ours) corr={c_mm:.4} lag={lag}; mkv-vs-ffmpeg corr={c_mkv_ff:.4}; mp4-vs-ffmpeg corr={c_mp4_ff:.4}"
1409- );
1410- }
1411- assert!(any, "no OBS mkv/mp4 pairs present");
1412-}
1413-
1414-/// The two mkv-only 5.1 real-library rows the consumer sweep flagged
1415-/// (E-AC-3 and AC-3): our decode of every channel against ffmpeg's channel
1416-/// 0, so a channel-order mismatch (mkv hands a different physical channel
1417-/// first than ffmpeg calls "channel 0") shows up as a non-zero-index best
1418-/// match instead of a flat near-zero across all of them.
1419-///
1420-/// Run with `cargo test -p ec-matroska --test matroska mkv_51_channel_order -- --ignored --nocapture`.
1421-#[test]
1422-#[ignore = "reads the real library, mkv-audio-timing A/B"]
1423-fn mkv_51_channel_order() {
1424- if !have_ffmpeg() {
1425- eprintln!("skipped: no ffmpeg");
1426- return;
1427- }
1428- let files: [(&str, CodecId); 2] = [
1429- (
1430- "/home/user/Downloads/reelf/reelf.mkv",
1431- CodecId::EAc3,
1432- ),
1433- (
1434- "/home/user/Downloads/reelg/reelg.mkv",
1435- CodecId::Ac3,
1436- ),
1437- ];
1438- let mut any = false;
1439- for (path, codec) in files {
1440- let path = Path::new(path);
1441- if !path.exists() {
1442- eprintln!("skipped: {} absent", path.display());
1443- continue;
1444- }
1445- any = true;
1446- let (_, _rate, pkts) = audio_track(path, codec).expect("audio track");
1447- println!(
1448- "{}: first5 pts = {:?}",
1449- path.file_name().unwrap().to_string_lossy(),
1450- pkts.iter().take(5).map(|(p, _)| *p).collect::<Vec<_>>()
1451- );
1452- let planes = decode_ac3(&pkts);
1453- assert!(
1454- !planes.is_empty(),
1455- "{}: no channels decoded",
1456- path.display()
1457- );
1458- let ffref = ffmpeg_decode_planar(path, planes.len());
1459- for (i, ch) in planes.iter().enumerate() {
1460- let (lag, c) = best_lag_correlation(ch, &ffref[0]);
1461- println!(
1462- "{}: our ch{i} vs ffmpeg ch0 corr={c:.4} lag={lag}",
1463- path.file_name().unwrap().to_string_lossy()
1464- );
1465- }
1466- }
1467- assert!(any, "no 5.1 mkv fixtures present");
1468-}
1469-
1470687 /// An EBML element with its size written in eight bytes.
1471688 fn ebml_el(id: &[u8], body: &[u8]) -> Vec<u8> {
1472689 let mut out = id.to_vec();
crates/ec-mp4/Cargo.tomlmodified+3 -0
@@ -8,3 +8,6 @@ authors.workspace = true
88
99 [dependencies]
1010 ec-core.workspace = true
11+
12+[dev-dependencies]
13+ec-testkit.workspace = true
crates/ec-mp4/fuzz/seed.shmodified+6 -4
@@ -11,10 +11,12 @@
1111 # Corpus lives under fuzz/corpus, which is git-ignored.
1212 set -euo pipefail
1313
14+FF=${EC_FFMPEG:-$HOME/.cache/ec-ffmpeg/ffmpeg}
15+
1416 FUZZ_DIR=$(cd -- "$(dirname -- "$0")" && pwd)
15-FIXTURES=$(cd -- "$FUZZ_DIR/../../.." && pwd)/fixtures
16-[ -d "$FIXTURES" ] || { echo "seed.sh: $FIXTURES missing; run scripts/link-fixtures.sh" >&2; exit 2; }
17-command -v ffmpeg >/dev/null || { echo "seed.sh: ffmpeg needed for the small video seeds" >&2; exit 2; }
17+FIXTURES=${EC_FIXTURES:-$(cd -- "$FUZZ_DIR/../../.." && pwd)/fixtures}
18+[ -d "$FIXTURES" ] || { echo "seed.sh: $FIXTURES missing; run scripts/fixtures.sh" >&2; exit 2; }
19+[ -x "$FF" ] || { echo "seed.sh: ffmpeg needed for the small video seeds" >&2; exit 2; }
1820
1921 MP4_DIR="$FUZZ_DIR/corpus/demux_mp4"
2022 ESDS_DIR="$FUZZ_DIR/corpus/esds_parse"
@@ -34,7 +36,7 @@ for src in "$FIXTURES"/audio/*.mp4 "$FIXTURES"/audio/*.m4a "$FIXTURES"/audio/*.m
3436 # Shorten until it fits: a 4K intra frame alone can be most of a megabyte.
3537 cut=""
3638 for secs in 0.2 0.05 0.01; do
37- ffmpeg -v error -y -t "$secs" -i "$src" -c copy -map 0 -movflags +faststart "$TMP/$stem.mp4" \
39+ "$FF" -v error -y -t "$secs" -i "$src" -c copy -map 0 -movflags +faststart "$TMP/$stem.mp4" \
3840 || { echo "seed.sh: ffmpeg could not cut $src" >&2; exit 2; }
3941 if [ "$(stat -c %s "$TMP/$stem.mp4")" -le "$LIMIT" ]; then cut=1; break; fi
4042 done
crates/ec-mp4/tests/data/gen.shmodified+6 -2
@@ -18,15 +18,19 @@
1818 # Usage: crates/ec-mp4/tests/data/gen.sh
1919 set -euo pipefail
2020
21+FF=${EC_FFMPEG:-$HOME/.cache/ec-ffmpeg/ffmpeg}
22+FP=$(dirname "$FF")/ffprobe
23+export FF FP
24+
2125 here=$(cd -- "$(dirname -- "$0")" && pwd)
2226 src=$(mktemp --suffix=.mp4)
2327 trap 'rm -f -- "$src"' EXIT
2428
25-ffmpeg -nostdin -y -v error -f lavfi \
29+"$FF" -nostdin -y -v error -f lavfi \
2630 -i "testsrc2=size=320x240:rate=24:duration=1" \
2731 -c:v libx264 -profile:v baseline -pix_fmt yuv420p "$src"
2832
2933 for deg in 0 90 180 270 45; do
30- ffmpeg -nostdin -y -v error -display_rotation "$deg" -i "$src" \
34+ "$FF" -nostdin -y -v error -display_rotation "$deg" -i "$src" \
3135 -c copy "$here/rot$deg.mp4"
3236 done
crates/ec-mp4/tests/it/chapters.rsmodified+2 -3
@@ -4,7 +4,6 @@
44
55 use std::io::Cursor;
66 use std::path::PathBuf;
7-use std::process::Command;
87
98 use ec_core::{
109 AudioParameters, Buf, ChannelLayout, CodecId, CodecParameters, Demuxer, MediaParameters, Muxer, Packet,
@@ -43,11 +42,11 @@ fn ffprobe_chapters(bytes: &[u8], name: &str) -> Vec<(i64, String)> {
4342 std::fs::create_dir_all(&dir).unwrap();
4443 let path: PathBuf = dir.join(name);
4544 std::fs::write(&path, bytes).unwrap();
46- let out = Command::new("ffprobe")
45+ let out = ec_testkit::ffprobe()
4746 .args(["-v", "error", "-show_chapters", "-of", "default"])
4847 .arg(&path)
4948 .output()
50- .expect("ffprobe on PATH");
49+ .expect("ffprobe runs");
5150 assert!(out.status.success(), "ffprobe failed: {:?}", out.stderr);
5251 let text = String::from_utf8_lossy(&out.stdout);
5352 let mut chapters = Vec::new();
crates/ec-mp4/tests/it/dts.rsmodified+6 -19
@@ -3,32 +3,23 @@
33 //! rate and channels the `ddts` box states; the writer round-trips `dtsc`.
44
55 use std::io::Cursor;
6-use std::process::Command;
76
87 use ec_core::{Buf, CodecId, Demuxer, MediaParameters, Muxer};
98 use ec_mp4::{Mp4Demuxer, Mp4Muxer};
109
11-fn required() -> bool {
12- std::env::var_os("EC_REQUIRE_FIXTURES").is_some_and(|v| !v.is_empty() && v != "0")
13-}
14-
15-fn ffmpeg_mp4(tag: &str) -> Option<Vec<u8>> {
10+fn ffmpeg_mp4(tag: &str) -> Vec<u8> {
1611 let out = std::env::temp_dir().join(format!("ec-mp4-dts-{tag}-{}.mp4", std::process::id()));
17- let ok = Command::new("ffmpeg")
12+ let ok = ec_testkit::ffmpeg()
1813 .args(["-v", "error", "-y", "-f", "lavfi", "-i"])
1914 .arg("sine=frequency=440:sample_rate=48000:duration=0.5")
2015 .args(["-ac", "2", "-c:a", "dca", "-strict", "-2"])
2116 .arg(&out)
2217 .output()
2318 .is_ok_and(|o| o.status.success());
24- if !ok {
25- assert!(!required(), "ffmpeg cannot make a DTS mp4");
26- eprintln!("skip: no ffmpeg with the dca encoder");
27- return None;
28- }
19+ assert!(ok, "ffmpeg cannot make a DTS mp4");
2920 let bytes = std::fs::read(&out).unwrap();
3021 let _ = std::fs::remove_file(out);
31- Some(bytes)
22+ bytes
3223 }
3324
3425 fn packets(d: &mut Mp4Demuxer<Cursor<Vec<u8>>>) -> Vec<ec_core::Packet> {
@@ -56,9 +47,7 @@ fn ddts(rate: u32, mask: u16) -> Vec<u8> {
5647
5748 #[test]
5849 fn ffmpeg_dts_in_mp4a_is_dts() {
59- let Some(bytes) = ffmpeg_mp4("a") else {
60- return;
61- };
50+ let bytes = ffmpeg_mp4("a");
6251 let mut d = Mp4Demuxer::new(Cursor::new(bytes)).unwrap();
6352 assert_eq!(d.streams()[0].params.codec, CodecId::Dts);
6453 assert_eq!(audio(&d), (48_000, 2));
@@ -67,9 +56,7 @@ fn ffmpeg_dts_in_mp4a_is_dts() {
6756
6857 #[test]
6958 fn dtsc_entry_round_trips_with_ddts_rate_and_channels() {
70- let Some(bytes) = ffmpeg_mp4("b") else {
71- return;
72- };
59+ let bytes = ffmpeg_mp4("b");
7360 let mut d = Mp4Demuxer::new(Cursor::new(bytes)).unwrap();
7461 let pkts = packets(&mut d);
7562 let mut info = d.streams()[0].clone();
crates/ec-mp4/tests/it/edit_trim.rsmodified+29 -38
@@ -50,18 +50,18 @@ fn default_output() -> Vec<u8> {
5050 muxer.into_inner().into_inner()
5151 }
5252
53-/// The MD5 of `bytes`, from the `md5sum` tool. A missing tool skips the check.
54-fn md5_of(bytes: &[u8]) -> Option<String> {
53+fn md5_of(bytes: &[u8]) -> String {
5554 let dir = std::env::temp_dir().join("ec-mp4-edit-trim");
56- std::fs::create_dir_all(&dir).ok()?;
55+ std::fs::create_dir_all(&dir).expect("work dir");
5756 let path = dir.join(format!("md5-{}.mp4", std::process::id()));
58- std::fs::write(&path, bytes).ok()?;
59- let out = Command::new("md5sum").arg(&path).output().ok()?;
57+ std::fs::write(&path, bytes).expect("write");
58+ let out = Command::new("md5sum").arg(&path).output().expect("md5sum runs");
6059 let _ = std::fs::remove_file(&path);
6160 String::from_utf8_lossy(&out.stdout)
6261 .split_whitespace()
6362 .next()
64- .map(str::to_string)
63+ .expect("md5sum output")
64+ .to_string()
6565 }
6666
6767 /// Pinned before `set_edit` was added: the default output of the AAC priming
@@ -70,11 +70,11 @@ const DEFAULT_AAC_PRIMING_MD5: &str = "2ba0fd44a7dfa3b69cb60d7aceb71753";
7070
7171 #[test]
7272 fn default_aac_priming_output_is_byte_identical() {
73- let bytes = default_output();
74- match md5_of(&bytes) {
75- Some(sum) => assert_eq!(sum, DEFAULT_AAC_PRIMING_MD5, "default output changed"),
76- None => eprintln!("skip: md5sum is not installed"),
77- }
73+ assert_eq!(
74+ md5_of(&default_output()),
75+ DEFAULT_AAC_PRIMING_MD5,
76+ "default output changed"
77+ );
7878 }
7979
8080 /// The big-endian `u32` at `offset` into the payload of the first `kind` box in
@@ -85,10 +85,8 @@ fn payload_u32(bytes: &[u8], kind: &[u8; 4], offset: usize) -> Option<u32> {
8585 Some(u32::from_be_bytes([raw[0], raw[1], raw[2], raw[3]]))
8686 }
8787
88-/// `key=value` lines from `ffprobe`, keyed by name. `None` where ffprobe is not
89-/// installed, which skips the check.
90-fn ffprobe_fields(path: &Path, select: &str, entries: &str) -> Option<Vec<(String, String)>> {
91- let out = Command::new("ffprobe")
88+fn ffprobe_fields(path: &Path, select: &str, entries: &str) -> Vec<(String, String)> {
89+ let out = ec_testkit::ffprobe()
9290 .args([
9391 "-v",
9492 "error",
@@ -100,14 +98,12 @@ fn ffprobe_fields(path: &Path, select: &str, entries: &str) -> Option<Vec<(Strin
10098 .args(["-of", "default=nw=1"])
10199 .arg(path)
102100 .output()
103- .ok()?;
104- let text = String::from_utf8_lossy(&out.stdout);
105- Some(
106- text.lines()
107- .filter_map(|line| line.split_once('='))
108- .map(|(k, v)| (k.to_string(), v.to_string()))
109- .collect(),
110- )
101+ .expect("ffprobe runs");
102+ String::from_utf8_lossy(&out.stdout)
103+ .lines()
104+ .filter_map(|line| line.split_once('='))
105+ .map(|(k, v)| (k.to_string(), v.to_string()))
106+ .collect()
111107 }
112108
113109 fn field(fields: &[(String, String)], key: &str) -> f64 {
@@ -164,20 +160,15 @@ fn set_edit_trims_the_audio_edit_to_its_stated_length() {
164160 .join(format!("trim-{}.mp4", std::process::id()));
165161 std::fs::create_dir_all(path.parent().expect("dir")).expect("work dir");
166162 std::fs::write(&path, &bytes).expect("write");
167- let stream_fields = ffprobe_fields(&path, "a:0", "stream=start_time,duration");
168- if let Some(fields) = stream_fields {
169- let frame = 1024.0 / 48_000.0;
170- let want = f64::from(PICTURE) / 48_000.0;
171- let duration = field(&fields, "duration");
172- let start = field(&fields, "start_time");
173- eprintln!("ffprobe a:0 start_time {start} duration {duration} (picture {want})");
174- assert!(
175- (duration - want).abs() <= frame,
176- "stream duration {duration} against the picture's {want}"
177- );
178- assert!(start.abs() < 1e-6, "start_time {start} is not zero");
179- } else {
180- eprintln!("skip ffprobe: not installed");
181- }
163+ let fields = ffprobe_fields(&path, "a:0", "stream=start_time,duration");
164+ let frame = 1024.0 / 48_000.0;
165+ let want = f64::from(PICTURE) / 48_000.0;
166+ let duration = field(&fields, "duration");
167+ let start = field(&fields, "start_time");
168+ assert!(
169+ (duration - want).abs() <= frame,
170+ "stream duration {duration} against the picture's {want}"
171+ );
172+ assert!(start.abs() < 1e-6, "start_time {start} is not zero");
182173 let _ = std::fs::remove_file(&path);
183174 }
crates/ec-mp4/tests/it/edith_parity.rsmodified+6 -44
@@ -3,15 +3,6 @@
33 //! for field. This is the swap criterion for edith's `mp4::` demuxer: identical
44 //! packet bytes, identical timestamps, identical stream metadata.
55 //!
6-//! The corpus is three sets, each optional where it is not in the checkout:
7-//!
8-//! - `fixtures/` (video, audio and the derived shapes): always, through the
9-//! usual `../../fixtures` symlink.
10-//! - edith's `assets/*.mp4|mov|m4a` when `EC_EDITH_ASSETS` names the directory
11-//! (default `/home/user/Documents/Code/Rust/edith/assets`; skipped with a
12-//! note when absent).
13-//! - the generated cases from `scripts/gen-mp4-parity-corpus.sh` when
14-//! `EC_MP4_PARITY_CORPUS` names its output directory.
156 //!
167 //! Per track, the comparison is: codec, coded size, sample rate, channels,
178 //! timebase, rotation, and per sample the byte offset, size, presentation time
@@ -29,7 +20,6 @@ use std::collections::HashMap;
2920 use std::fs::File;
3021 use std::io::BufReader;
3122 use std::path::{Path, PathBuf};
32-use std::process::Command;
3323
3424 use ec_core::{CodecId, Demuxer, MediaParameters};
3525 use ec_mp4::{Mp4Demuxer, Sample};
@@ -58,7 +48,7 @@ fn records(text: &str, first: &str) -> Vec<Record> {
5848 }
5949
6050 fn ffprobe(path: &Path, entries: &str, first: &str) -> Vec<Record> {
61- let out = Command::new("ffprobe")
51+ let out = ec_testkit::ffprobe()
6252 .args(["-v", "error", "-show_entries", entries, "-of", "default=nw=1"])
6353 .arg(path)
6454 .output()
@@ -129,7 +119,7 @@ fn probe_streams(path: &Path, rotations: &HashMap<u32, i32>) -> Vec<ProbeStream>
129119 /// stream dump. The `side_data=rotation` entry query is not used: on a 2 GB film
130120 /// ffprobe spends minutes decoding for it, while the JSON dump is immediate.
131121 fn rotations(path: &Path) -> HashMap<u32, i32> {
132- let out = Command::new("ffprobe")
122+ let out = ec_testkit::ffprobe()
133123 .args(["-v", "error", "-show_streams", "-of", "json"])
134124 .arg(path)
135125 .output()
@@ -354,33 +344,7 @@ fn collect(dir: &Path, files: &mut Vec<PathBuf>) {
354344
355345 fn corpus() -> Vec<PathBuf> {
356346 let mut files = Vec::new();
357- collect(&Path::new(env!("CARGO_MANIFEST_DIR")).join("../../fixtures"), &mut files);
358- let assets = std::env::var("EC_EDITH_ASSETS")
359- .unwrap_or_else(|_| "/home/user/Documents/Code/Rust/edith/assets".into());
360- if Path::new(&assets).is_dir() {
361- collect(Path::new(&assets), &mut files);
362- } else {
363- eprintln!("edith_parity: no edith assets at {assets}; skipped");
364- }
365- // The real library: the local films the scan recorded as mp4-family, when
366- // they are still on this machine. A missing file is skipped, as the scan does.
367- if let Ok(manifest) = std::fs::read_to_string(
368- Path::new(env!("CARGO_MANIFEST_DIR")).join("../../fixtures/real-library-manifest.tsv"),
369- ) {
370- for line in manifest.lines().skip(1) {
371- let mut fields = line.split('\t');
372- let (Some(path), Some(container)) = (fields.next(), fields.next()) else {
373- continue;
374- };
375- if container.contains("mp4") && Path::new(path).is_file() {
376- files.push(PathBuf::from(path));
377- }
378- }
379- }
380- match std::env::var("EC_MP4_PARITY_CORPUS") {
381- Ok(dir) => collect(Path::new(&dir), &mut files),
382- Err(_) => eprintln!("edith_parity: EC_MP4_PARITY_CORPUS unset; generated cases skipped"),
383- }
347+ collect(&ec_testkit::root().join("mp4corpus"), &mut files);
384348 files.sort();
385349 files.dedup();
386350 files
@@ -389,7 +353,7 @@ fn corpus() -> Vec<PathBuf> {
389353 #[test]
390354 fn every_corpus_file_matches_ffprobe_sample_for_sample() {
391355 let files = corpus();
392- assert!(!files.is_empty(), "no mp4/mov corpus; run scripts/link-fixtures.sh");
356+ assert!(!files.is_empty(), "no mp4/mov corpus; run scripts/fixtures.sh");
393357 let mut report = Vec::new();
394358 let mut failures = Vec::new();
395359 for path in &files {
@@ -415,16 +379,14 @@ fn every_corpus_file_matches_ffprobe_sample_for_sample() {
415379 /// order.
416380 #[test]
417381 fn edith_trim_and_display_order_read_the_known_fixtures() {
418- let aac = Path::new(env!("CARGO_MANIFEST_DIR"))
419- .join("../../fixtures/audio/aac-mp4-stereo-48000.mp4");
382+ let aac = ec_testkit::fixture("audio/aac-mp4-stereo-48000.mp4");
420383 let demuxer = Mp4Demuxer::new(BufReader::new(File::open(&aac).expect("fixture")))
421384 .expect("the fixture demuxes");
422385 assert_eq!(demuxer.presentation_trim(0), Some(1024));
423386 assert_eq!(demuxer.first_frame_sample(0), 2, "the trim lands on packet 2");
424387 assert!(demuxer.sync_in_display_order(0).is_empty(), "no ctts, no reorder");
425388
426- let gop = Path::new(env!("CARGO_MANIFEST_DIR"))
427- .join("../../fixtures/video/h264-open-gop.mp4");
389+ let gop = ec_testkit::fixture("video/h264-open-gop.mp4");
428390 let demuxer = Mp4Demuxer::new(BufReader::new(File::open(&gop).expect("fixture")))
429391 .expect("the fixture demuxes");
430392 let syncs = demuxer.sync_in_display_order(0);
crates/ec-mp4/tests/it/mp4.rsmodified+10 -168
@@ -7,7 +7,6 @@
77 use std::fs::File;
88 use std::io::{BufReader, BufWriter, Cursor};
99 use std::path::{Path, PathBuf};
10-use std::process::Command;
1110
1211 use ec_core::{
1312 Buf, CodecId, Demuxer, Error, MediaParameters, Muxer, Packet, SeekMode, StreamInfo, TimeBase,
@@ -18,7 +17,7 @@ use ec_mp4::{Mp4Demuxer, Mp4Muxer};
1817 use crate::common::ffmpeg_name;
1918
2019 fn fixtures() -> PathBuf {
21- Path::new(env!("CARGO_MANIFEST_DIR")).join("../../fixtures")
20+ ec_testkit::root()
2221 }
2322
2423 fn work() -> PathBuf {
@@ -48,7 +47,7 @@ fn riff_avi_is_not_reported_as_a_truncated_mp4() {
4847
4948 /// One ffprobe field per stream, in stream order.
5049 fn probe_field(path: &Path, entries: &str) -> Vec<String> {
51- let out = Command::new("ffprobe")
50+ let out = ec_testkit::ffprobe()
5251 .args(["-v", "error", "-show_entries", entries, "-of", "csv=p=0"])
5352 .arg(path)
5453 .output()
@@ -111,7 +110,7 @@ fn mp4_fixtures() -> Vec<PathBuf> {
111110 .iter()
112111 .flat_map(|dir| {
113112 std::fs::read_dir(fixtures().join(dir))
114- .expect("fixtures (run scripts/gen-fixtures.sh)")
113+ .expect("fixtures (run scripts/fixtures.sh)")
115114 .filter_map(|e| e.ok().map(|e| e.path()))
116115 })
117116 .filter(|p| {
@@ -185,7 +184,7 @@ fn make_derived(dst: &Path, args: &[&str]) -> bool {
185184 return true;
186185 }
187186 let tmp = dst.with_file_name(format!("tmp-{}-{name}", std::process::id()));
188- let ok = Command::new("ffmpeg")
187+ let ok = ec_testkit::ffmpeg()
189188 .args(["-v", "error", "-y"])
190189 .args(args)
191190 .arg(&tmp)
@@ -326,7 +325,7 @@ fn every_fixture_remuxes_into_a_file_ffprobe_and_ffmpeg_agree_with() {
326325 );
327326
328327 // ...and it decodes, which is the only claim a field compare cannot make.
329- let decode = Command::new("ffmpeg")
328+ let decode = ec_testkit::ffmpeg()
330329 .args(["-v", "error", "-i"])
331330 .arg(&dst)
332331 .args(["-f", "null", "-"])
@@ -411,7 +410,7 @@ fn the_hand_written_extensions_come_out_as_ffprobe_reads_them() {
411410 "colr nclx read back"
412411 );
413412 let side = String::from_utf8_lossy(
414- &Command::new("ffprobe")
413+ &ec_testkit::ffprobe()
415414 .args(["-v", "error", "-show_streams", "-of", "json"])
416415 .arg(&dst)
417416 .output()
@@ -470,7 +469,7 @@ fn the_hand_written_extensions_come_out_as_ffprobe_reads_them() {
470469 assert_eq!(probe_field(&dst, "stream=codec_name"), vec!["mov_text"]);
471470 assert_eq!(probe_field(&dst, "stream_tags=language"), vec!["tur"]);
472471 let text = String::from_utf8_lossy(
473- &Command::new("ffmpeg")
472+ &ec_testkit::ffmpeg()
474473 .args(["-v", "error", "-i"])
475474 .arg(&dst)
476475 .args(["-f", "srt", "-"])
@@ -527,7 +526,7 @@ fn an_aac_tracks_audio_specific_config_survives_as_bytes() {
527526 fn a_non_aac_mp4a_entry_is_not_dropped() {
528527 let dst = work().join("mp3-in-mp4.mp4");
529528 let src = fixtures().join("audio/mp3-stereo-44100.mp3");
530- let ok = Command::new("ffmpeg")
529+ let ok = ec_testkit::ffmpeg()
531530 .args(["-v", "error", "-y", "-i"])
532531 .arg(&src)
533532 .args(["-c", "copy"])
@@ -653,11 +652,7 @@ fn a_truncated_file_is_need_more() {
653652
654653 #[test]
655654 fn truncated_prefixes_are_need_more_or_eof() {
656- let mut paths = vec![fixtures().join("audio/aac-mp4-stereo-48000.mp4")];
657- let real = PathBuf::from("/home/user/Downloads/reelj (11).mp4");
658- if real.exists() {
659- paths.push(real);
660- }
655+ let paths = [fixtures().join("audio/aac-mp4-stereo-48000.mp4")];
661656
662657 for path in paths {
663658 let data = std::fs::read(&path).unwrap_or_else(|e| panic!("{}: {e}", path.display()));
@@ -789,114 +784,6 @@ fn aac_priming_round_trips_through_an_elst() {
789784 );
790785 }
791786
792-/// The real library, end to end: every mp4-family file the manifest lists
793-/// demuxes to EOF with the packet counts ffprobe counts.
794-///
795-/// Ignored by default because it reads eleven gigabytes. Run it with
796-/// `cargo test -p ec-mp4 --release --test it mp4::the_real_library -- --ignored --nocapture`.
797-#[test]
798-#[ignore = "reads the real library end to end"]
799-fn the_real_library_demuxes_to_eof() {
800- let manifest = std::fs::read_to_string(fixtures().join("real-library-manifest.tsv"))
801- .expect("the real-library manifest (run scripts/scan-real-library.sh)");
802- let files: Vec<&str> = manifest
803- .lines()
804- .skip(1)
805- .filter_map(|line| {
806- let mut fields = line.split('\t');
807- let path = fields.next()?;
808- fields.next()?.contains("mp4").then_some(path)
809- })
810- .collect();
811- assert!(!files.is_empty(), "no mp4-family files in the manifest");
812-
813- let mut table = Vec::new();
814- let mut failed = Vec::new();
815- for path in files {
816- let path = Path::new(path);
817- if !path.exists() {
818- table.push(format!("{:<58} GONE", name_of(path)));
819- continue;
820- }
821- let mut demuxer = open(path);
822- let kinds: Vec<CodecId> = demuxer.streams().iter().map(|s| s.params.codec).collect();
823- let mut ours = vec![0u64; kinds.len()];
824- loop {
825- match demuxer.next_packet() {
826- Ok(packet) => ours[packet.stream as usize] += 1,
827- Err(Error::Eof) => break,
828- Err(e) => {
829- failed.push(format!("{}: {e}", name_of(path)));
830- break;
831- }
832- }
833- }
834- // ffprobe counts the same packets on the same file. Two shapes are not
835- // a disagreement: cover art, which ffmpeg lists as an attached-picture
836- // video stream and which is metadata rather than a track; and a track
837- // whose last sample ffmpeg hands out one fewer of than its sample table
838- // states (`nb_frames`) — where ours equals the table, the table is what
839- // the file says.
840- let counted = Command::new("ffprobe")
841- .args([
842- "-v",
843- "error",
844- "-count_packets",
845- "-show_entries",
846- "stream=codec_type,nb_read_packets,nb_frames:stream_disposition=attached_pic",
847- "-of",
848- "csv=p=0",
849- ])
850- .arg(path)
851- .output()
852- .expect("ffprobe runs");
853- // One line a stream: type, packets counted, frames the sample table
854- // states, and whether it is cover art.
855- let rows: Vec<Vec<String>> = String::from_utf8_lossy(&counted.stdout)
856- .lines()
857- .map(|l| {
858- l.split(',')
859- .map(|f| f.trim().to_string())
860- .collect::<Vec<String>>()
861- })
862- .filter(|row| {
863- matches!(
864- row.first().map(String::as_str),
865- Some("video" | "audio" | "subtitle")
866- ) && row.get(3).map(String::as_str) != Some("1")
867- })
868- .collect();
869- let theirs: Vec<u64> = rows
870- .iter()
871- .map(|r| r.get(1).and_then(|n| n.parse().ok()).unwrap_or(0))
872- .collect();
873- let tables: Vec<u64> = rows
874- .iter()
875- .map(|r| r.get(2).and_then(|n| n.parse().ok()).unwrap_or(0))
876- .collect();
877- let same = ours == theirs;
878- let by_table = !same && ours == tables;
879- if !same && !by_table {
880- failed.push(format!(
881- "{}: ours {ours:?} against ffprobe {theirs:?}",
882- name_of(path)
883- ));
884- }
885- table.push(format!(
886- "{:<58} {:<18} ours {ours:?} ffprobe {theirs:?} {}",
887- name_of(path),
888- kinds.iter().map(|c| c.name()).collect::<Vec<_>>().join("+"),
889- match (same, by_table) {
890- (true, _) => "PASS".to_string(),
891- (_, true) => format!("PASS (sample table {tables:?})"),
892- _ => "FAIL".to_string(),
893- }
894- ));
895- }
896- println!("{}", table.join("\n"));
897- assert!(failed.is_empty(), "{}", failed.join("\n"));
898-}
899-
900787 fn name_of(path: &Path) -> String {
901788 let name = path.file_name().unwrap_or_default().to_string_lossy();
902789 name.chars().take(56).collect()
@@ -905,7 +792,7 @@ fn name_of(path: &Path) -> String {
905792 /// The extradata ffprobe reads out of a stream, as bytes: its `-show_data`
906793 /// hexdump, which is the only place it prints the octets themselves.
907794 fn probe_extradata(path: &Path, stream: &str) -> Vec<u8> {
908- let out = Command::new("ffprobe")
795+ let out = ec_testkit::ffprobe()
909796 .args([
910797 "-v",
911798 "error",
@@ -992,51 +879,6 @@ fn quicktime_sound_description_states_its_esds_inside_wave() {
992879 assert_eq!(got, iso_extra, "QuickTime and ISO read different extradata");
993880 }
994881
995-/// The real exports this shape was found in: set `EC_MP4_QT_MOV` to a
996-/// colon-separated list of `.mov` files to check this crate against ffprobe on
997-/// files that are not in the corpus.
998-#[test]
999-fn real_quicktime_exports_demux_like_ffprobe_says() {
1000- let Ok(list) = std::env::var("EC_MP4_QT_MOV") else {
1001- return;
1002- };
1003- for path in list.split(':').filter(|p| !p.is_empty()).map(Path::new) {
1004- assert!(path.exists(), "{}: not there", path.display());
1005- let want = probe_extradata(path, "a:0");
1006- let demuxer = open(path);
1007- let audio = demuxer
1008- .streams()
1009- .iter()
1010- .find(|s| matches!(s.params.media, MediaParameters::Audio(_)))
1011- .unwrap_or_else(|| panic!("{}: no sound track", path.display()));
1012- let MediaParameters::Audio(params) = &audio.params.media else {
1013- unreachable!()
1014- };
1015- let rate = probe_field(path, "stream=sample_rate")
1016- .into_iter()
1017- .find(|f| !f.is_empty() && f != "N/A")
1018- .and_then(|f| f.trim().parse::<u32>().ok())
1019- .expect("ffprobe states a sample rate");
1020- assert_eq!(audio.params.codec, CodecId::Aac, "{}", path.display());
1021- assert_eq!(params.sample_rate, rate, "{}", path.display());
1022- let got = audio
1023- .params
1024- .extradata
1025- .as_ref()
1026- .map(|b| b.as_ref().to_vec())
1027- .unwrap_or_default();
1028- assert_eq!(got, want, "{}: extradata", path.display());
1029- println!(
1030- "{}: {:?} {} Hz {} ch, extradata {}",
1031- path.display(),
1032- audio.params.codec,
1033- params.sample_rate,
1034- params.layout.channel_count(),
1035- got.len()
1036- );
1037- }
1038-}
1039-
1040882 /// A box with a four-character type and its payload, sized the way ISOBMFF sizes it.
1041883 fn boxed(kind: &[u8; 4], payload: &[u8]) -> Vec<u8> {
1042884 let mut out = ((payload.len() + 8) as u32).to_be_bytes().to_vec();
crates/ec-mp4/tests/it/mux_entries.rsmodified+14 -49
@@ -4,14 +4,10 @@
44 //! our file to the same samples as the source, since the packets are the same
55 //! bytes. This crate's own demuxer reads our file back to the same packets with
66 //! the same timestamps and keyframe flags.
7-//!
8-//! A case is skipped, not failed, where ffmpeg or the encoder it needs is not
9-//! built in, the way the other ffmpeg-backed tests skip.
107
118 use std::fs::File;
129 use std::io::{BufReader, BufWriter};
1310 use std::path::{Path, PathBuf};
14-use std::process::Command;
1511
1612 use ec_core::{Demuxer, Error, Muxer, Packet};
1713 use ec_mp4::{Mp4Demuxer, Mp4Muxer};
@@ -197,33 +193,21 @@ fn work(case: &Case) -> PathBuf {
197193 dir
198194 }
199195
200-/// Whether `tool` runs at all.
201-fn have(tool: &str) -> bool {
202- Command::new(tool)
203- .arg("-version")
204- .output()
205- .is_ok_and(|o| o.status.success())
206-}
207-
208196 /// Whether ffmpeg was built with `encoder`.
209197 fn has_encoder(encoder: &str) -> bool {
210- Command::new("ffmpeg")
198+ ec_testkit::ffmpeg()
211199 .args(["-hide_banner", "-encoders"])
212200 .output()
213201 .is_ok_and(|o| String::from_utf8_lossy(&o.stdout).contains(&format!(" {encoder} ")))
214202 }
215203
216-/// Makes the source for `case` at `path`, or says why it cannot. `false` is a
217-/// skip.
218-fn make_source(case: &Case, path: &Path) -> bool {
219- if !has_encoder(case.encoder) {
220- eprintln!(
221- "skip {}: ffmpeg has no {} encoder",
222- case.entry, case.encoder
223- );
224- return false;
225- }
226- let ok = Command::new("ffmpeg")
204+fn make_source(case: &Case, path: &Path) {
205+ assert!(
206+ has_encoder(case.encoder),
207+ "ffmpeg has no {} encoder",
208+ case.encoder
209+ );
210+ let ok = ec_testkit::ffmpeg()
227211 .args(["-hide_banner", "-v", "error", "-y"])
228212 .args(case.args)
229213 .args(["-f", "mp4"])
@@ -232,7 +216,6 @@ fn make_source(case: &Case, path: &Path) -> bool {
232216 .expect("ffmpeg runs")
233217 .success();
234218 assert!(ok, "ffmpeg could not make the {} source", case.entry);
235- true
236219 }
237220
238221 /// Every packet of `path`, and the streams it declares.
@@ -306,7 +289,7 @@ fn remux(src: &Path, dst: &Path) {
306289
307290 /// ffprobe's stderr for `path`, with the full-decode check ffmpeg runs over it.
308291 fn ffprobe_stderr(path: &Path) -> String {
309- let out = Command::new("ffprobe")
292+ let out = ec_testkit::ffprobe()
310293 .args(["-v", "error", "-show_streams", "-show_format"])
311294 .arg(path)
312295 .output()
@@ -316,7 +299,7 @@ fn ffprobe_stderr(path: &Path) -> String {
316299
317300 /// One ffprobe CSV field list per stream, for `entries` (`stream=...`).
318301 fn probe_lines(path: &Path, entries: &str) -> Vec<String> {
319- let out = Command::new("ffprobe")
302+ let out = ec_testkit::ffprobe()
320303 .args(["-v", "error", "-show_entries", entries, "-of", "csv=p=0"])
321304 .arg(path)
322305 .output()
@@ -339,7 +322,7 @@ fn duration(path: &Path) -> f64 {
339322 /// `MD5=...`. Any stderr from the decode is returned too: a clean file says
340323 /// nothing.
341324 fn decoded_md5(path: &Path, map: &str) -> (String, String) {
342- let out = Command::new("ffmpeg")
325+ let out = ec_testkit::ffmpeg()
343326 .args(["-hide_banner", "-v", "error", "-i"])
344327 .arg(path)
345328 .args(["-map", map, "-f", "md5", "-"])
@@ -352,16 +335,10 @@ fn decoded_md5(path: &Path, map: &str) -> (String, String) {
352335 }
353336
354337 fn run_case(case: &Case) {
355- if !have("ffmpeg") || !have("ffprobe") {
356- eprintln!("skip {}: ffmpeg or ffprobe is not installed", case.entry);
357- return;
358- }
359338 let dir = work(case);
360339 let src = dir.join("source.mp4");
361340 let out = dir.join("ours.mp4");
362- if !make_source(case, &src) {
363- return;
364- }
341+ make_source(case, &src);
365342 remux(&src, &out);
366343
367344 // (a) ffprobe reads our file cleanly and states what the source states.
@@ -468,16 +445,10 @@ fn every_entry_is_ffprobe_clean_decodes_equal_and_round_trips() {
468445 #[test]
469446 fn opus_pre_skip_is_written_without_a_caller_asking() {
470447 let case = &CASES[7];
471- if !have("ffmpeg") || !have("ffprobe") {
472- eprintln!("skip {}: ffmpeg or ffprobe is not installed", case.entry);
473- return;
474- }
475448 let dir = work(case);
476449 let src = dir.join("source.mp4");
477450 let out = dir.join("bare.mp4");
478- if !make_source(case, &src) {
479- return;
480- }
451+ make_source(case, &src);
481452 let (streams, packets) = read_all(&src);
482453 let shifts = Vec::new();
483454 write_out(&out, &streams, &packets, &shifts, false);
@@ -500,16 +471,10 @@ fn opus_pre_skip_is_written_without_a_caller_asking() {
500471 #[test]
501472 fn alac_bare_cookie_is_written_inside_an_alac_box() {
502473 let case = &CASES[6];
503- if !have("ffmpeg") || !have("ffprobe") {
504- eprintln!("skip {}: ffmpeg or ffprobe is not installed", case.entry);
505- return;
506- }
507474 let dir = work(case);
508475 let src = dir.join("source.mp4");
509476 let out = dir.join("bare-cookie.mp4");
510- if !make_source(case, &src) {
511- return;
512- }
477+ make_source(case, &src);
513478 let (mut streams, packets) = read_all(&src);
514479 let boxed = streams[0]
515480 .params
crates/ec-mp4/tests/it/prores_entries.rsmodified+3 -9
@@ -1,17 +1,14 @@
11 //! The ProRes sample entries (`apco apcs apcn apch ap4h ap4x`) read as `CodecId::ProRes`. Each
2-//! source is a one-frame ffmpeg `prores_ks` mov written at test time; skipped where ffmpeg or the
3-//! encoder is missing, unless `EC_REQUIRE_FIXTURES` is set.
42
53 use std::fs::File;
64 use std::io::BufReader;
7-use std::process::Command;
85
96 use ec_core::registry::CodecId;
107 use ec_core::Demuxer;
118 use ec_mp4::Mp4Demuxer;
129
1310 fn has_prores_ks() -> bool {
14- Command::new("ffmpeg")
11+ ec_testkit::ffmpeg()
1512 .args(["-hide_banner", "-encoders"])
1613 .output()
1714 .map(|o| String::from_utf8_lossy(&o.stdout).contains("prores_ks"))
@@ -20,10 +17,7 @@ fn has_prores_ks() -> bool {
2017
2118 #[test]
2219 fn prores_fourccs_are_recognised() {
23- if !has_prores_ks() {
24- assert!(std::env::var_os("EC_REQUIRE_FIXTURES").is_none(), "ffmpeg prores_ks required");
25- return;
26- }
20+ assert!(has_prores_ks(), "ffmpeg prores_ks required");
2721 let dir = std::env::temp_dir().join(format!("ec-mp4-prores-{}", std::process::id()));
2822 std::fs::create_dir_all(&dir).unwrap();
2923 for (profile, fmt, fourcc) in [
@@ -35,7 +29,7 @@ fn prores_fourccs_are_recognised() {
3529 ("5", "yuv444p10le", "ap4x"),
3630 ] {
3731 let path = dir.join(format!("{fourcc}.mov"));
38- let ok = Command::new("ffmpeg")
32+ let ok = ec_testkit::ffmpeg()
3933 .args(["-v", "error", "-y", "-f", "lavfi", "-i", "testsrc2=size=64x48:rate=25", "-frames:v", "1"])
4034 .args(["-c:v", "prores_ks", "-profile", profile, "-pix_fmt", fmt])
4135 .arg(&path)
crates/ec-mp4/tests/it/qt_pcm_hdr.rsmodified+15 -31
@@ -1,33 +1,23 @@
11 //! QuickTime PCM sound descriptions (`in24`, `in32`, `fl32` with `wave/enda`
22 //! and `chan`) and the HDR `mdcv`/`clli` boxes, checked against ffmpeg.
33 //!
4-//! Sources are synthetic (ffmpeg `sine`, `testsrc2`). A case skips where
5-//! ffmpeg or an encoder is missing, unless `EC_REQUIRE_FIXTURES` is set.
64
75 use std::fs::File;
86 use std::io::{BufReader, BufWriter};
97 use std::path::{Path, PathBuf};
10-use std::process::Command;
118
129 use ec_core::{ContentLight, Demuxer, Error, MasteringPrimaries, Muxer, Packet, StreamInfo};
1310 use ec_mp4::{Mp4Demuxer, Mp4Muxer};
1411
15-fn skip(why: &str) -> bool {
12+fn require_encoder(encoder: &str) {
13+ let out = ec_testkit::ffmpeg()
14+ .args(["-hide_banner", "-encoders"])
15+ .output()
16+ .expect("ffmpeg runs");
1617 assert!(
17- std::env::var_os("EC_REQUIRE_FIXTURES").is_none(),
18- "EC_REQUIRE_FIXTURES set but: {why}"
18+ String::from_utf8_lossy(&out.stdout).contains(&format!(" {encoder} ")),
19+ "ffmpeg has no {encoder} encoder"
1920 );
20- eprintln!("skip: {why}");
21- true
22-}
23-
24-fn have_ffmpeg(encoder: &str) -> bool {
25- let out = Command::new("ffmpeg")
26- .args(["-hide_banner", "-encoders"])
27- .output();
28- let ok = out.is_ok_and(|o| String::from_utf8_lossy(&o.stdout).contains(&format!(" {encoder} ")))
29- && Command::new("ffprobe").arg("-version").output().is_ok();
30- ok || !skip(&format!("no ffmpeg/ffprobe or no {encoder}"))
3121 }
3222
3323 fn dir(name: &str) -> PathBuf {
@@ -72,7 +62,7 @@ fn entry(path: &Path, fourcc: &[u8; 4]) -> Option<Vec<u8>> {
7262 }
7363
7464 fn probe(path: &Path, args: &[&str]) -> String {
75- let out = Command::new("ffprobe")
65+ let out = ec_testkit::ffprobe()
7666 .args(["-v", "error"])
7767 .args(args)
7868 .arg(path)
@@ -83,7 +73,7 @@ fn probe(path: &Path, args: &[&str]) -> String {
8373 }
8474
8575 fn decoded_md5(path: &Path) -> String {
86- let out = Command::new("ffmpeg")
76+ let out = ec_testkit::ffmpeg()
8777 .args(["-v", "error", "-i"])
8878 .arg(path)
8979 .args(["-map", "0:a:0", "-f", "md5", "-"])
@@ -93,12 +83,10 @@ fn decoded_md5(path: &Path) -> String {
9383 }
9484
9585 fn pcm_case(name: &str, codec: &str, channels: u32, fourcc: &[u8; 4], layout_box: bool) {
96- if !have_ffmpeg(codec) {
97- return;
98- }
86+ require_encoder(codec);
9987 let d = dir(name);
10088 let src = d.join("src.mov");
101- let ok = Command::new("ffmpeg")
89+ let ok = ec_testkit::ffmpeg()
10290 .args(["-v", "error", "-y", "-f", "lavfi", "-i", "sine=d=0.5:sample_rate=48000"])
10391 .args(["-ac", &channels.to_string(), "-c:a", codec])
10492 .arg(&src)
@@ -169,12 +157,10 @@ fn pcm_sample_entries_are_ffprobe_clean_and_byte_equal() {
169157 /// (no `chan`), and one that does gets ffmpeg's.
170158 #[test]
171159 fn sowt_gets_chan_only_when_asked() {
172- if !have_ffmpeg("pcm_s16le") {
173- return;
174- }
160+ require_encoder("pcm_s16le");
175161 let d = dir("sowt");
176162 let src = d.join("src.mov");
177- assert!(Command::new("ffmpeg")
163+ assert!(ec_testkit::ffmpeg()
178164 .args(["-v", "error", "-y", "-f", "lavfi", "-i", "sine=d=0.2:sample_rate=48000", "-ac", "2", "-c:a", "pcm_s16le"])
179165 .arg(&src)
180166 .status()
@@ -203,12 +189,10 @@ fn light() -> ContentLight {
203189 /// Main 10 HEVC, remuxed with `mdcv` and `clli`.
204190 #[test]
205191 fn hevc_main10_mdcv_clli_in_mp4() {
206- if !have_ffmpeg("libx265") {
207- return;
208- }
192+ require_encoder("libx265");
209193 let d = dir("hdr");
210194 let src = d.join("src.mp4");
211- assert!(Command::new("ffmpeg")
195+ assert!(ec_testkit::ffmpeg()
212196 .args(["-v", "error", "-y", "-f", "lavfi", "-i", "testsrc2=size=320x240:rate=25:duration=1"])
213197 .args(["-c:v", "libx265", "-pix_fmt", "yuv420p10le", "-tag:v", "hvc1"])
214198 .args(["-x265-params", "log-level=error:colorprim=bt2020:transfer=smpte2084:colormatrix=bt2020nc"])
crates/ec-mpegts/Cargo.tomlmodified+3 -0
@@ -12,3 +12,6 @@ ec-dvdsub.workspace = true
1212 ec-h264-syntax.workspace = true
1313 ec-h265-syntax.workspace = true
1414 ec-truehd.workspace = true
15+
16+[dev-dependencies]
17+ec-testkit.workspace = true
crates/ec-mpegts/tests/data/gen.shmodified+13 -9
@@ -4,17 +4,21 @@
44 # expected.txt: <file> <stream-index-in-ffmpeg> <codec> <packets> <bytes> <fnv1a64 of ffmpeg's bytes>
55 # LPCM is hashed over ffmpeg's s16be decode, which is what the demuxer's packets are.
66 set -euo pipefail
7+
8+FF=${EC_FFMPEG:-$HOME/.cache/ec-ffmpeg/ffmpeg}
9+FP=$(dirname "$FF")/ffprobe
10+export FF FP
711 cd "$(dirname "$0")"
812 V=(-f lavfi -i testsrc2=size=160x120:rate=25:duration=0.6)
913 A=(-f lavfi -i sine=frequency=440:sample_rate=48000:duration=0.6)
1014 X=(-c:v libx264 -preset ultrafast -g 12 -bf 2)
11-ffmpeg -v error -y "${V[@]}" "${A[@]}" "${X[@]}" -c:a aac -f mpegts tiny_h264_aac.ts
12-ffmpeg -v error -y "${V[@]}" "${A[@]}" "${X[@]}" -c:a ac3 -f mpegts -mpegts_m2ts_mode 1 tiny_h264_ac3.m2ts
13-ffmpeg -v error -y "${V[@]}" "${A[@]}" "${X[@]}" -c:a eac3 -f mpegts tiny_h264_eac3.ts
14-ffmpeg -v error -y -f lavfi -i testsrc2=size=160x120:rate=25:duration=0.3 -f lavfi -i sine=frequency=440:sample_rate=48000:duration=0.3 "${X[@]}" -c:a pcm_bluray -f mpegts -mpegts_m2ts_mode 1 tiny_h264_lpcm.m2ts
15-ffmpeg -v error -y "${V[@]}" "${A[@]}" -c:v libx265 -preset ultrafast -g 12 -x265-params log-level=none -c:a aac -f mpegts tiny_hevc_aac.ts
15+"$FF" -v error -y "${V[@]}" "${A[@]}" "${X[@]}" -c:a aac -f mpegts tiny_h264_aac.ts
16+"$FF" -v error -y "${V[@]}" "${A[@]}" "${X[@]}" -c:a ac3 -f mpegts -mpegts_m2ts_mode 1 tiny_h264_ac3.m2ts
17+"$FF" -v error -y "${V[@]}" "${A[@]}" "${X[@]}" -c:a eac3 -f mpegts tiny_h264_eac3.ts
18+"$FF" -v error -y -f lavfi -i testsrc2=size=160x120:rate=25:duration=0.3 -f lavfi -i sine=frequency=440:sample_rate=48000:duration=0.3 "${X[@]}" -c:a pcm_bluray -f mpegts -mpegts_m2ts_mode 1 tiny_h264_lpcm.m2ts
19+"$FF" -v error -y "${V[@]}" "${A[@]}" -c:v libx265 -preset ultrafast -g 12 -x265-params log-level=none -c:a aac -f mpegts tiny_hevc_aac.ts
1620 python3 -I - <<'PY'
17-import subprocess
21+import os, subprocess
1822 def fnv(b):
1923 h = 0xcbf29ce484222325
2024 for x in b:
@@ -24,10 +28,10 @@ rows = []
2428 for f in ["tiny_h264_aac.ts", "tiny_h264_ac3.m2ts", "tiny_h264_eac3.ts", "tiny_h264_lpcm.m2ts", "tiny_hevc_aac.ts"]:
2529 for idx, codec in enumerate(["video", "audio"]):
2630 if codec == "audio" and "lpcm" in f:
27- data = subprocess.run(["ffmpeg","-v","error","-i",f,"-map","0:1","-f","s16be","-"],capture_output=True,check=True).stdout
31+ data = subprocess.run([os.environ["FF"],"-v","error","-i",f,"-map","0:1","-f","s16be","-"],capture_output=True,check=True).stdout
2832 else:
29- data = subprocess.run(["ffmpeg","-v","error","-i",f,"-map",f"0:{idx}","-c","copy","-f","data","-"],capture_output=True,check=True).stdout
30- pk = subprocess.run(["ffprobe","-v","error","-select_streams",str(idx),"-show_entries","packet=pts","-of","csv=p=0",f],capture_output=True,check=True).stdout.split()
33+ data = subprocess.run([os.environ["FF"],"-v","error","-i",f,"-map",f"0:{idx}","-c","copy","-f","data","-"],capture_output=True,check=True).stdout
34+ pk = subprocess.run([os.environ["FP"],"-v","error","-select_streams",str(idx),"-show_entries","packet=pts","-of","csv=p=0",f],capture_output=True,check=True).stdout.split()
3135 rows.append(f"{f} {idx} {len(pk)} {len(data)} {fnv(data):016x}")
3236 open("expected.txt","w").write("\n".join(rows) + "\n")
3337 PY
crates/ec-mpegts/tests/data/gen_ps.shmodified+12 -8
@@ -3,15 +3,19 @@
33 # sources (testsrc2 and sine only). Needs ffmpeg with mpeg2video, mpeg1video, ac3, mp2.
44 # expected_ps.txt: <file> <stream-index-in-ffmpeg> <packets> <bytes> <fnv1a64 of ffmpeg's bytes>
55 set -euo pipefail
6+
7+FF=${EC_FFMPEG:-$HOME/.cache/ec-ffmpeg/ffmpeg}
8+FP=$(dirname "$FF")/ffprobe
9+export FF FP
610 cd "$(dirname "$0")"
711 V=(-f lavfi -i testsrc2=size=128x96:rate=25:duration=0.5)
812 A=(-f lavfi -i sine=frequency=440:sample_rate=48000:duration=0.5)
9-ffmpeg -v error -y "${V[@]}" "${A[@]}" -c:v mpeg2video -g 12 -bf 2 -b:v 150k -c:a ac3 -b:a 96k -f vob ps_mpeg2_ac3.vob
10-ffmpeg -v error -y "${V[@]}" "${A[@]}" -c:v mpeg1video -g 9 -bf 2 -b:v 120k -c:a mp2 -b:a 96k -f mpeg ps_mpeg1_mp2.mpg
11-ffmpeg -v error -y "${V[@]}" -c:v mpeg2video -g 12 -bf 2 -b:v 150k -f mpeg2video ps_mpeg2.m2v
12-ffmpeg -v error -y "${V[@]}" -f lavfi -i sine=frequency=440:sample_rate=48000:duration=0.5 -c:v mpeg2video -g 12 -b:v 150k -c:a pcm_dvd -f vob ps_pcm_dvd.vob
13+"$FF" -v error -y "${V[@]}" "${A[@]}" -c:v mpeg2video -g 12 -bf 2 -b:v 150k -c:a ac3 -b:a 96k -f vob ps_mpeg2_ac3.vob
14+"$FF" -v error -y "${V[@]}" "${A[@]}" -c:v mpeg1video -g 9 -bf 2 -b:v 120k -c:a mp2 -b:a 96k -f mpeg ps_mpeg1_mp2.mpg
15+"$FF" -v error -y "${V[@]}" -c:v mpeg2video -g 12 -bf 2 -b:v 150k -f mpeg2video ps_mpeg2.m2v
16+"$FF" -v error -y "${V[@]}" -f lavfi -i sine=frequency=440:sample_rate=48000:duration=0.5 -c:v mpeg2video -g 12 -b:v 150k -c:a pcm_dvd -f vob ps_pcm_dvd.vob
1317 python3 -I - <<'PY'
14-import subprocess
18+import os, subprocess
1519 def fnv(b):
1620 h = 0xcbf29ce484222325
1721 for x in b:
@@ -20,10 +24,10 @@ def fnv(b):
2024 rows = []
2125 for f, streams in [("ps_mpeg2_ac3.vob", 2), ("ps_mpeg1_mp2.mpg", 2), ("ps_mpeg2.m2v", 1), ("ps_pcm_dvd.vob", 2)]:
2226 for idx in range(streams):
23- data = subprocess.run(["ffmpeg","-v","error","-i",f,"-map",f"0:{idx}","-c","copy","-f","data","-"],capture_output=True,check=True).stdout
27+ data = subprocess.run([os.environ["FF"],"-v","error","-i",f,"-map",f"0:{idx}","-c","copy","-f","data","-"],capture_output=True,check=True).stdout
2428 if "pcm_dvd" in f and idx == 1:
25- data = subprocess.run(["ffmpeg","-v","error","-i",f,"-map","0:1","-f","s16be","-"],capture_output=True,check=True).stdout
26- pk = subprocess.run(["ffprobe","-v","error","-select_streams",str(idx),"-show_entries","packet=pts","-of","csv=p=0",f],capture_output=True,check=True).stdout.split()
29+ data = subprocess.run([os.environ["FF"],"-v","error","-i",f,"-map","0:1","-f","s16be","-"],capture_output=True,check=True).stdout
30+ pk = subprocess.run([os.environ["FP"],"-v","error","-select_streams",str(idx),"-show_entries","packet=pts","-of","csv=p=0",f],capture_output=True,check=True).stdout.split()
2731 rows.append(f"{f} {idx} {len(pk)} {len(data)} {fnv(data):016x}")
2832 open("expected_ps.txt","w").write("\n".join(rows) + "\n")
2933 PY
crates/ec-mpegts/tests/it/common.rsmodified+11 -51
@@ -1,43 +1,14 @@
1-//! Shared helpers: ffmpeg/ffprobe fixtures, packet dumps and the skip convention
2-//! (`EC_REQUIRE_FIXTURES` turns a skip into a failure).
31 #![allow(dead_code)]
42
53 use std::collections::HashMap;
64 use std::fs::File;
75 use std::io::BufReader;
86 use std::path::{Path, PathBuf};
9-use std::process::Command;
107 use std::sync::OnceLock;
118
129 use ec_core::registry::Demuxer;
1310 use ec_mpegts::TsDemuxer;
1411
15-pub fn required() -> bool {
16- std::env::var_os("EC_REQUIRE_FIXTURES").is_some_and(|v| !v.is_empty() && v != "0")
17-}
18-
19-/// True when ffmpeg and ffprobe can be run; otherwise prints a skip note (or panics
20-/// when fixtures are required).
21-pub fn have_ffmpeg() -> bool {
22- static OK: OnceLock<bool> = OnceLock::new();
23- let ok = *OK.get_or_init(|| {
24- ["ffmpeg", "ffprobe"].iter().all(|t| {
25- Command::new(t)
26- .arg("-version")
27- .output()
28- .is_ok_and(|o| o.status.success())
29- })
30- });
31- if !ok {
32- assert!(
33- !required(),
34- "EC_REQUIRE_FIXTURES is set but ffmpeg/ffprobe are missing"
35- );
36- eprintln!("skip: ffmpeg/ffprobe not available");
37- }
38- ok
39-}
40-
4112 pub fn fixture_dir() -> PathBuf {
4213 static DIR: OnceLock<PathBuf> = OnceLock::new();
4314 DIR.get_or_init(|| {
@@ -61,9 +32,8 @@ pub const AUDIO_SRC: &[&str] = &[
6132 "sine=frequency=440:sample_rate=48000:duration=3",
6233 ];
6334
64-/// Runs ffmpeg; `Err` carries stderr. Unavailable encoders are a skip.
6535 pub fn ffmpeg(args: &[&str], out: &Path) -> Result<(), String> {
66- let o = Command::new("ffmpeg")
36+ let o = ec_testkit::ffmpeg()
6737 .args(["-v", "error", "-y"])
6838 .args(args)
6939 .arg(out)
@@ -76,30 +46,20 @@ pub fn ffmpeg(args: &[&str], out: &Path) -> Result<(), String> {
7646 }
7747 }
7848
79-/// Generates `name` with `args` (input options included) or returns `None` on skip.
80-pub fn fixture(name: &str, args: &[&str]) -> Option<PathBuf> {
81- if !have_ffmpeg() {
82- return None;
83- }
49+pub fn fixture(name: &str, args: &[&str]) -> PathBuf {
8450 // Tests run on threads of one process: one generates a given file at a time.
8551 static LOCK: std::sync::Mutex<()> = std::sync::Mutex::new(());
8652 let _guard = LOCK.lock().unwrap_or_else(|e| e.into_inner());
8753 let out = fixture_dir().join(name);
8854 if out.exists() {
89- return Some(out);
55+ return out;
9056 }
9157 let tmp = fixture_dir().join(format!("{name}.{}.tmp", std::process::id()));
92- match ffmpeg(args, &tmp) {
93- Ok(()) => {
94- std::fs::rename(&tmp, &out).unwrap();
95- Some(out)
96- }
97- Err(e) => {
98- assert!(!required(), "ffmpeg failed for {name}: {e}");
99- eprintln!("skip {name}: {e}");
100- None
101- }
58+ if let Err(e) = ffmpeg(args, &tmp) {
59+ panic!("ffmpeg failed for {name}: {e}");
10260 }
61+ std::fs::rename(&tmp, &out).unwrap();
62+ out
10363 }
10464
10565 pub fn open(path: &Path) -> TsDemuxer<BufReader<File>> {
@@ -143,7 +103,7 @@ pub struct Row {
143103 }
144104
145105 pub fn ffprobe_rows(path: &Path) -> HashMap<u16, (u32, Vec<Row>)> {
146- let streams = Command::new("ffprobe")
106+ let streams = ec_testkit::ffprobe()
147107 .args([
148108 "-v",
149109 "error",
@@ -167,7 +127,7 @@ pub fn ffprobe_rows(path: &Path) -> HashMap<u16, (u32, Vec<Row>)> {
167127 pid_of.insert(i, p);
168128 }
169129 }
170- let pk = Command::new("ffprobe")
130+ let pk = ec_testkit::ffprobe()
171131 .args([
172132 "-v",
173133 "error",
@@ -204,7 +164,7 @@ pub fn ffprobe_rows(path: &Path) -> HashMap<u16, (u32, Vec<Row>)> {
204164
205165 /// ffmpeg's stream copy of stream `index`, as one byte string.
206166 pub fn ffmpeg_bytes(path: &Path, index: u32) -> Vec<u8> {
207- let o = Command::new("ffmpeg")
167+ let o = ec_testkit::ffmpeg()
208168 .args(["-v", "error", "-i"])
209169 .arg(path)
210170 .args([
@@ -223,7 +183,7 @@ pub fn ffmpeg_bytes(path: &Path, index: u32) -> Vec<u8> {
223183
224184 /// ffmpeg's decode of an LPCM stream as big-endian 16-bit samples.
225185 pub fn ffmpeg_pcm_s16be(path: &Path, index: u32) -> Vec<u8> {
226- Command::new("ffmpeg")
186+ ec_testkit::ffmpeg()
227187 .args(["-v", "error", "-i"])
228188 .arg(path)
229189 .args(["-map", &format!("0:{index}"), "-f", "s16be", "-"])
crates/ec-mpegts/tests/it/dts.rsmodified+3 -7
@@ -7,7 +7,7 @@ use ec_core::CodecId;
77 use ec_core::registry::{Demuxer, MediaParameters};
88 use ec_mpegts::StreamKind;
99
10-fn dts_ts(name: &str, channels: &str) -> Option<std::path::PathBuf> {
10+fn dts_ts(name: &str, channels: &str) -> std::path::PathBuf {
1111 fixture(
1212 name,
1313 &[
@@ -28,9 +28,7 @@ fn dts_ts(name: &str, channels: &str) -> Option<std::path::PathBuf> {
2828 }
2929
3030 fn check(name: &str, channels: &str, want: usize) {
31- let Some(p) = dts_ts(name, channels) else {
32- return;
33- };
31+ let p = dts_ts(name, channels);
3432 let mut d = open(&p);
3533 let streams = d.streams().to_vec();
3634 assert_eq!(streams.len(), 1);
@@ -98,9 +96,7 @@ fn rewrite_pmt(ts: &[u8], stream_type: u8, descriptors: &[u8]) -> Vec<u8> {
9896
9997 #[test]
10098 fn dts_hd_stream_types_and_descriptors_map_to_dts() {
101- let Some(p) = dts_ts("dts_retag.ts", "2") else {
102- return;
103- };
99+ let p = dts_ts("dts_retag.ts", "2");
104100 let ts = std::fs::read(&p).unwrap();
105101 let cases: [(&str, u8, Vec<u8>); 5] = [
106102 ("0x82", 0x82, vec![]),
crates/ec-mpegts/tests/it/ffmpeg_parity.rsmodified+14 -27
@@ -2,14 +2,13 @@
22 //! bytes, sizes, timestamps, keyframe flags, duration, plus seek exactness.
33 //!
44 //! Fixtures are generated at test time from synthetic sources (testsrc2, sine). The
5-//! tests skip, saying so, when ffmpeg is absent and fail instead when
6-//! `EC_REQUIRE_FIXTURES` is set.
5+
76
87 use crate::common::*;
98 use ec_core::registry::{Demuxer, SeekMode};
109 use ec_core::{CodecId, TimeBase, Timestamp};
1110
12-fn v264(name: &str, extra: &[&str], mux: &[&str]) -> Option<std::path::PathBuf> {
11+fn v264(name: &str, extra: &[&str], mux: &[&str]) -> std::path::PathBuf {
1312 let mut a: Vec<&str> = VIDEO_SRC.to_vec();
1413 a.extend_from_slice(AUDIO_SRC);
1514 a.extend_from_slice(&[
@@ -191,7 +190,7 @@ fn cleanup_none() {}
191190 /// One test over a table so every case runs and all failures are named.
192191 #[test]
193192 fn parity_cases() {
194- type Case = (&'static str, fn() -> Option<std::path::PathBuf>);
193+ type Case = (&'static str, fn() -> std::path::PathBuf);
195194 const CASES: &[Case] = &[
196195 ("h264_aac_ts", || {
197196 v264("h264_aac.ts", &["-c:a", "aac"], &["-f", "mpegts"])
@@ -243,7 +242,7 @@ fn parity_cases() {
243242 let mut failures = Vec::new();
244243 for &(name, make) in CASES {
245244 let ran = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
246- let Some(p) = make() else { return };
245+ let p = make();
247246 parity(&p);
248247 duration_ok(&p);
249248 seek_exact(&p);
@@ -257,9 +256,7 @@ fn parity_cases() {
257256
258257 #[test]
259258 fn mp2_in_ts_is_exposed_as_mp2() {
260- let Some(p) = v264("h264_mp2.ts", &["-c:a", "mp2"], &["-f", "mpegts"]) else {
261- return;
262- };
259+ let p = v264("h264_mp2.ts", &["-c:a", "mp2"], &["-f", "mpegts"]);
263260 let d = open(&p);
264261 let audio: Vec<_> = d
265262 .streams()
@@ -273,7 +270,7 @@ fn mp2_in_ts_is_exposed_as_mp2() {
273270 );
274271 assert!(d.tracks().iter().all(|t| t.refusal.is_none()));
275272 }
276-fn audio_only(name: &str, codec: &str, rate: &str, extra: &[&str]) -> Option<std::path::PathBuf> {
273+fn audio_only(name: &str, codec: &str, rate: &str, extra: &[&str]) -> std::path::PathBuf {
277274 let mut a: Vec<&str> = vec![
278275 "-f",
279276 "lavfi",
@@ -293,9 +290,7 @@ fn audio_only(name: &str, codec: &str, rate: &str, extra: &[&str]) -> Option<std
293290
294291 #[test]
295292 fn audio_only_aac_44100() {
296- let Some(p) = audio_only("audio_aac.ts", "aac", "44100", &[]) else {
297- return;
298- };
293+ let p = audio_only("audio_aac.ts", "aac", "44100", &[]);
299294 parity_slack(&p, 8);
300295 seek_exact(&p);
301296 duration_ok(&p);
@@ -315,16 +310,14 @@ fn ac3_family_sizes() {
315310 ("eac3", "48000", "384k"),
316311 ] {
317312 let name = format!("audio_{codec}_{rate}_{br}.ts");
318- let Some(p) = audio_only(&name, codec, rate, &["-b:a", br]) else {
319- return;
320- };
313+ let p = audio_only(&name, codec, rate, &["-b:a", br]);
321314 parity_slack(&p, 8);
322315 seek_exact(&p);
323316 duration_ok(&p);
324317 }
325318 }
326319
327-fn hevc(name: &str, audio: &str) -> Option<std::path::PathBuf> {
320+fn hevc(name: &str, audio: &str) -> std::path::PathBuf {
328321 let mut a: Vec<&str> = VIDEO_SRC.to_vec();
329322 a.extend_from_slice(AUDIO_SRC);
330323 a.extend_from_slice(&[
@@ -346,9 +339,7 @@ fn hevc(name: &str, audio: &str) -> Option<std::path::PathBuf> {
346339
347340 #[test]
348341 fn codecs_and_extradata() {
349- let Some(p) = v264("h264_aac.ts", &["-c:a", "aac"], &["-f", "mpegts"]) else {
350- return;
351- };
342+ let p = v264("h264_aac.ts", &["-c:a", "aac"], &["-f", "mpegts"]);
352343 let d = open(&p);
353344 let s = d.streams();
354345 assert_eq!(s[0].params.codec, CodecId::H264);
@@ -363,7 +354,7 @@ fn codecs_and_extradata() {
363354 assert_eq!(s[1].params.audio().unwrap().sample_rate, 48000);
364355 }
365356
366-fn two_programs() -> Option<std::path::PathBuf> {
357+fn two_programs() -> std::path::PathBuf {
367358 let mut a: Vec<&str> = VIDEO_SRC.to_vec();
368359 a.extend_from_slice(AUDIO_SRC);
369360 a.extend_from_slice(&[
@@ -397,7 +388,7 @@ fn two_programs() -> Option<std::path::PathBuf> {
397388
398389 #[test]
399390 fn multiple_programs() {
400- let Some(p) = two_programs() else { return };
391+ let p = two_programs();
401392 let d = open(&p);
402393 let progs = d.programs();
403394 assert_eq!(progs.len(), 2, "{progs:?}");
@@ -437,9 +428,7 @@ fn pts_wrap_is_unwrapped() {
437428 "-f",
438429 "mpegts",
439430 ]);
440- let Some(p) = fixture("wrap.ts", &a) else {
441- return;
442- };
431+ let p = fixture("wrap.ts", &a);
443432 let mut d = open(&p);
444433 let pkts = read_all(&mut d);
445434 for s in d.streams() {
@@ -470,9 +459,7 @@ fn pts_wrap_is_unwrapped() {
470459 /// packet not flagged corrupt is one the intact file has.
471460 #[test]
472461 fn corrupted_and_truncated() {
473- let Some(p) = v264("h264_aac.ts", &["-c:a", "aac"], &["-f", "mpegts"]) else {
474- return;
475- };
462+ let p = v264("h264_aac.ts", &["-c:a", "aac"], &["-f", "mpegts"]);
476463 let good = std::fs::read(&p).unwrap();
477464 let mut d = open(&p);
478465 let want = read_all(&mut d);
crates/ec-mpegts/tests/it/mpeg2.rsmodified+3 -7
@@ -1,6 +1,5 @@
11 //! MPEG-1/2 video in transport streams: exposed as `CodecId::Mpeg2Video`, one
22 //! packet per coded picture, parameters from the sequence header. Fixtures come from
3-//! ffmpeg's synthetic testsrc2 and skip (fail under `EC_REQUIRE_FIXTURES`) without it.
43
54 use crate::common::*;
65 use ec_core::registry::Demuxer;
@@ -15,7 +14,7 @@ fn pictures(d: &[u8]) -> Vec<u8> {
1514 }
1615
1716 fn check(codec: &str, name: &str, mpeg2: bool) {
18- let Some(ts) = fixture(
17+ let ts = fixture(
1918 name,
2019 &[
2120 "-f",
@@ -33,16 +32,13 @@ fn check(codec: &str, name: &str, mpeg2: bool) {
3332 "-f",
3433 "mpegts",
3534 ],
36- ) else {
37- return;
38- };
35+ );
3936 let es = fixture_dir().join(format!("{name}.m2v"));
4037 if let Err(e) = ffmpeg(
4138 &["-i", ts.to_str().unwrap(), "-c", "copy", "-f", codec],
4239 &es,
4340 ) {
44- assert!(!required(), "es extraction failed: {e}");
45- return;
41+ panic!("es extraction failed: {e}");
4642 }
4743 let want = std::fs::read(&es).unwrap();
4844 let mut d = open(&ts);
crates/ec-mpegts/tests/it/ps.rsmodified+24 -46
@@ -2,8 +2,6 @@
22 //! ffmpeg's demux on ffmpeg-made files (bytes, sizes, timestamps, key flags),
33 //! duration, seek exactness, SCR resets, PTS wraps and damaged files.
44 //!
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`.
75
86 use std::fs::File;
97 use std::io::BufReader;
@@ -61,7 +59,7 @@ fn src(extra_audio: &[&str]) -> Vec<&'static str> {
6159 a
6260 }
6361
64-fn mkps(name: &str, video: &[&str], audio: &[&str], mux: &[&str]) -> Option<PathBuf> {
62+fn mkps(name: &str, video: &[&str], audio: &[&str], mux: &[&str]) -> PathBuf {
6563 let mut a = src(audio);
6664 a.extend_from_slice(video);
6765 a.extend_from_slice(audio);
@@ -153,7 +151,7 @@ fn parity(path: &Path, slack: i64) {
153151 }
154152
155153 fn raw_rows(path: &Path) -> Vec<Row> {
156- let o = std::process::Command::new("ffprobe")
154+ let o = ec_testkit::ffprobe()
157155 .args([
158156 "-v",
159157 "error",
@@ -182,7 +180,7 @@ fn raw_rows(path: &Path) -> Vec<Row> {
182180 }
183181
184182 fn ffmpeg_pcm(path: &Path, index: u32, fmt: &str) -> Vec<u8> {
185- std::process::Command::new("ffmpeg")
183+ ec_testkit::ffmpeg()
186184 .args(["-v", "error", "-i"])
187185 .arg(path)
188186 .args(["-map", &format!("0:{index}"), "-f", fmt, "-"])
@@ -318,7 +316,7 @@ fn seek_exact(path: &Path) {
318316 /// exactness). One test over a table: every case runs and all failures are named.
319317 #[test]
320318 fn ps_parity_cases() {
321- type Case = (&'static str, fn() -> Option<std::path::PathBuf>);
319+ type Case = (&'static str, fn() -> std::path::PathBuf);
322320 const CASES: &[Case] = &[
323321 ("mpeg1_system_mp2", || {
324322 mkps(
@@ -466,7 +464,7 @@ fn ps_parity_cases() {
466464 let mut failures = Vec::new();
467465 for &(name, make) in CASES {
468466 let ran = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
469- let Some(p) = make() else { return };
467+ let p = make();
470468 parity(&p, 0);
471469 duration_ok(&p);
472470 seek_exact(&p);
@@ -482,28 +480,24 @@ fn ps_parity_cases() {
482480 // mid-stream cannot know the phase: no seek-exactness check for it.
483481 #[test]
484482 fn pcm_dvd_24() {
485- let Some(p) = mkps(
483+ let p = mkps(
486484 "lpcm24.vob",
487485 V2,
488486 &["-c:a", "pcm_dvd", "-sample_fmt", "s32"],
489487 &["-f", "vob"],
490- ) else {
491- return;
492- };
488+ );
493489 parity(&p, 0);
494490 duration_ok(&p);
495491 }
496492
497493 #[test]
498494 fn dts_is_refused_by_name() {
499- let Some(p) = mkps(
495+ let p = mkps(
500496 "dts.vob",
501497 V2,
502498 &["-c:a", "dca", "-strict", "-2"],
503499 &["-f", "vob"],
504- ) else {
505- return;
506- };
500+ );
507501 let d = open_ps(&p);
508502 assert_eq!(d.streams().len(), 1);
509503 let t = d.tracks();
@@ -636,7 +630,7 @@ fn concatenated_vobs_keep_time_monotonic() {
636630
637631 #[test]
638632 fn concatenated_dvd_files_with_nav_packets() {
639- let Some(p) = mkps(
633+ let p = mkps(
640634 "dvd2.vob",
641635 &[
642636 "-vf",
@@ -652,17 +646,13 @@ fn concatenated_dvd_files_with_nav_packets() {
652646 ],
653647 &["-c:a", "ac3", "-ar", "48000"],
654648 &["-f", "dvd"],
655- ) else {
656- return;
657- };
649+ );
658650 check_concat(&std::fs::read(p).unwrap(), 2, None);
659651 }
660652
661653 #[test]
662654 fn starts_mid_gop() {
663- let Some(p) = mkps("v_ac3.vob", V2, &["-c:a", "ac3"], &["-f", "vob"]) else {
664- return;
665- };
655+ let p = mkps("v_ac3.vob", V2, &["-c:a", "ac3"], &["-f", "vob"]);
666656 let orig_bytes = std::fs::read(&p).unwrap();
667657 let mut o = open_ps(&p);
668658 let orig = read_ps(&mut o);
@@ -883,14 +873,12 @@ fn mutated_files_never_panic() {
883873
884874 #[test]
885875 fn pts_wrap_is_unwrapped() {
886- let Some(p) = mkps(
876+ let p = mkps(
887877 "wrap.vob",
888878 V2,
889879 &["-c:a", "ac3"],
890880 &["-output_ts_offset", "95442", "-f", "vob"],
891- ) else {
892- return;
893- };
881+ );
894882 let mut d = open_ps(&p);
895883 let v = read_ps(&mut d);
896884 let pts: Vec<i64> = v
@@ -950,7 +938,7 @@ fn video_index(d: &D) -> u32 {
950938 }
951939
952940 fn frames_by_ffprobe(path: &Path) -> usize {
953- let o = std::process::Command::new("ffprobe")
941+ let o = ec_testkit::ffprobe()
954942 .args(["-v", "error", "-count_frames", "-select_streams", "v:0"])
955943 .args(["-show_entries", "stream=nb_read_frames", "-of", "csv=p=0"])
956944 .arg(path)
@@ -994,9 +982,7 @@ fn tail_picture_without_a_timestamp_is_counted() {
994982 a.extend_from_slice(&[
995983 "-pix_fmt", "yuv420p", "-map", "1:a", "-c:a", "mp2", "-f", "mpeg",
996984 ]);
997- if let Some(p) = fixture(name, &a) {
998- cases.push(p);
999- }
985+ cases.push(fixture(name, &a));
1000986 }
1001987 for path in cases {
1002988 let mut d = open_ps(&path);
@@ -1026,7 +1012,7 @@ fn tail_picture_without_a_timestamp_is_counted() {
10261012 }
10271013
10281014 /// Two VOBs of 2.4 s joined by bytes: SCR and PTS restart at the join.
1029-fn joined_vob() -> Option<(PathBuf, u64)> {
1015+fn joined_vob() -> (PathBuf, u64) {
10301016 let mk = |name: &str, vf: &str, hz: &str| {
10311017 let video = format!("testsrc2=size=352x288:rate=25:duration=2.4{vf}");
10321018 let audio = format!("sine=frequency={hz}:sample_rate=48000:duration=2.4");
@@ -1062,8 +1048,8 @@ fn joined_vob() -> Option<(PathBuf, u64)> {
10621048 ];
10631049 fixture(name, &a)
10641050 };
1065- let a = mk("pstail-a.vob", "", "440")?;
1066- let b = mk("pstail-b.vob", ",negate", "880")?;
1051+ let a = mk("pstail-a.vob", "", "440");
1052+ let b = mk("pstail-b.vob", ",negate", "880");
10671053 let out = fixture_dir().join("pstail-join.vob");
10681054 let alen = std::fs::metadata(&a).unwrap().len();
10691055 if !out.exists() {
@@ -1074,14 +1060,12 @@ fn joined_vob() -> Option<(PathBuf, u64)> {
10741060 std::fs::write(&tmp, bytes).unwrap();
10751061 std::fs::rename(&tmp, &out).unwrap();
10761062 }
1077- Some((out, alen))
1063+ (out, alen)
10781064 }
10791065
10801066 #[test]
10811067 fn joined_vobs_have_the_summed_duration() {
1082- let Some((path, _)) = joined_vob() else {
1083- return;
1084- };
1068+ let (path, _) = joined_vob();
10851069 let d = open_ps(&path);
10861070 let single = open_ps(&fixture_dir().join("pstail-a.vob"));
10871071 let v = video_index(&d) as usize;
@@ -1115,9 +1099,7 @@ fn joined_vobs_have_the_summed_duration() {
11151099
11161100 #[test]
11171101 fn seeks_on_both_sides_of_a_join_equal_the_sequential_decode() {
1118- let Some((path, _)) = joined_vob() else {
1119- return;
1120- };
1102+ let (path, _) = joined_vob();
11211103 let mut d = open_ps(&path);
11221104 let v = video_index(&d);
11231105 let all = read_ps(&mut d);
@@ -1166,9 +1148,7 @@ fn seeks_on_both_sides_of_a_join_equal_the_sequential_decode() {
11661148
11671149 #[test]
11681150 fn audio_keeps_its_offset_to_the_video_after_a_join() {
1169- let Some((path, alen)) = joined_vob() else {
1170- return;
1171- };
1151+ let (path, alen) = joined_vob();
11721152 let mut d = open_ps(&path);
11731153 let v = video_index(&d);
11741154 let a = d
@@ -1216,9 +1196,7 @@ fn ts_tail_picture_is_counted() {
12161196 "-f", "lavfi", "-i", FLASH_SRC, "-c:v", codec, "-b:v", "2M", "-g", "10", "-bf", "2",
12171197 "-pix_fmt", "yuv420p", "-f", "mpegts",
12181198 ];
1219- let Some(path) = fixture(name, &a) else {
1220- continue;
1221- };
1199+ let path = fixture(name, &a);
12221200 let mut d = open(&path);
12231201 let v = d
12241202 .streams()
crates/ec-mpegts/tests/it/truehd.rsmodified+8 -26
@@ -2,11 +2,8 @@
22 //! through `ec-truehd` to the PCM ffmpeg decodes from the same file, sample for sample.
33 //!
44 //! The fixture is made at test time by ffmpeg's own TrueHD encoder (a 440 Hz sine,
5-//! lavfi, no external media). The test skips, saying so, when ffmpeg is absent and
6-//! fails instead when `EC_REQUIRE_FIXTURES` is set.
75
86 use std::path::Path;
9-use std::process::Command;
107
118 use crate::common::*;
129 use ec_core::registry::Demuxer;
@@ -14,7 +11,7 @@ use ec_core::{CodecId, MediaParameters};
1411 use ec_truehd::{AccessUnitHeader, TrueHdDecoder};
1512
1613 /// Stereo 48 kHz TrueHD in M2TS-style TS, as ffmpeg writes it (stream type 0x83).
17-fn truehd_ts(name: &str, channels: &str) -> Option<std::path::PathBuf> {
14+fn truehd_ts(name: &str, channels: &str) -> std::path::PathBuf {
1815 let a = [
1916 "-f",
2017 "lavfi",
@@ -36,7 +33,7 @@ fn truehd_ts(name: &str, channels: &str) -> Option<std::path::PathBuf> {
3633
3734 /// ffmpeg's decode of the first audio stream as interleaved S32 little-endian.
3835 fn ffmpeg_s32le(path: &Path) -> Vec<i32> {
39- let out = Command::new("ffmpeg")
36+ let out = ec_testkit::ffmpeg()
4037 .args(["-v", "error", "-nostdin", "-i"])
4138 .arg(path)
4239 .args(["-map", "0:a:0", "-f", "s32le", "-"])
@@ -62,13 +59,8 @@ fn s32le(bytes: &[u8]) -> Vec<i32> {
6259
6360 #[test]
6461 fn truehd_in_ts_decodes_sample_exact_to_ffmpeg() {
65- if !have_ffmpeg() {
66- return;
67- }
68- for (name, channels, want) in [("truehd_sine_2ch.ts", "2", 2usize)] {
69- let Some(path) = truehd_ts(name, channels) else {
70- return;
71- };
62+ for (name, channels, want) in [("truehd_sine_2ch.ts", "2", 2usize)] {
63+ let path = truehd_ts(name, channels);
7264 let mut d = open(&path);
7365 let all = read_all(&mut d);
7466 let stream = d
@@ -123,12 +115,7 @@ fn truehd_in_ts_decodes_sample_exact_to_ffmpeg() {
123115 fn truehd_packets_match_the_container_packet_form() {
124116 // The access units in the TS are the same bytes ffmpeg's stream copy writes out
125117 // (the MP4 and Matroska demuxers hand over the same form).
126- if !have_ffmpeg() {
127- return;
128- }
129- let Some(path) = truehd_ts("truehd_sine_2ch.ts", "2") else {
130- return;
131- };
118+ let path = truehd_ts("truehd_sine_2ch.ts", "2");
132119 let mut d = open(&path);
133120 let all = read_all(&mut d);
134121 let stream = d
@@ -142,7 +129,7 @@ fn truehd_packets_match_the_container_packet_form() {
142129 .filter(|p| p.stream == stream)
143130 .flat_map(|p| p.data)
144131 .collect();
145- let o = Command::new("ffmpeg")
132+ let o = ec_testkit::ffmpeg()
146133 .args(["-v", "error", "-nostdin", "-i"])
147134 .arg(&path)
148135 .args(["-map", "0:a:0", "-c", "copy", "-f", "truehd", "-"])
@@ -263,10 +250,7 @@ fn ts5(prefix: u8, v: u64) -> [u8; 5] {
263250
264251 #[test]
265252 fn ac3_core_interleaved_in_the_truehd_pid_is_dropped() {
266- if !have_ffmpeg() {
267- return;
268- }
269- let Some(raw) = fixture(
253+ let raw = fixture(
270254 "truehd_sine_2ch.thd",
271255 &[
272256 "-f",
@@ -284,9 +268,7 @@ fn ac3_core_interleaved_in_the_truehd_pid_is_dropped() {
284268 "-f",
285269 "truehd",
286270 ],
287- ) else {
288- return;
289- };
271+ );
290272 let aus = split_aus(&std::fs::read(&raw).unwrap());
291273 assert!(aus.len() > 8, "enough access units");
292274
crates/ec-ogg/Cargo.tomlmodified+3 -0
@@ -8,3 +8,6 @@ authors.workspace = true
88
99 [dependencies]
1010 ec-core.workspace = true
11+
12+[dev-dependencies]
13+ec-testkit.workspace = true
crates/ec-ogg/fuzz/seed.shmodified+3 -3
@@ -14,9 +14,9 @@ set -euo pipefail
1414
1515 FUZZ_DIR=$(cd -- "$(dirname -- "$0")" && pwd)
1616 ROOT=$(cd -- "$FUZZ_DIR/../../.." && pwd)
17-AUDIO="$ROOT/fixtures/audio"
18-VORBIS="$ROOT/fixtures/vectors/vorbis-xiph"
19-[ -d "$AUDIO" ] || { echo "seed.sh: $AUDIO missing; run scripts/link-fixtures.sh" >&2; exit 2; }
17+AUDIO="${EC_FIXTURES:-$ROOT/fixtures}/audio"
18+VORBIS="${EC_FIXTURES:-$ROOT/fixtures}/vectors/vorbis-xiph"
19+[ -d "$AUDIO" ] || { echo "seed.sh: $AUDIO missing; run scripts/fixtures.sh" >&2; exit 2; }
2020
2121 CORPUS="$FUZZ_DIR/corpus"
2222 mkdir -p "$CORPUS"/{page_parse,demux,demux_raw,mapping,roundtrip}
crates/ec-ogg/tests/ogg.rsmodified+13 -37
@@ -11,7 +11,6 @@
1111
1212 use std::io::Cursor;
1313 use std::path::{Path, PathBuf};
14-use std::process::Command;
1514
1615 use ec_core::{
1716 Buf, CodecId, CodecParameters, Demuxer, MediaParameters, Muxer, Packet, PacketFlags, SeekMode,
@@ -29,7 +28,7 @@ fn name_of(p: &std::path::Path) -> String {
2928 }
3029
3130 fn fixtures() -> PathBuf {
32- Path::new(env!("CARGO_MANIFEST_DIR")).join("../../fixtures/audio")
31+ ec_testkit::root().join("audio")
3332 }
3433
3534 /// Working directory keyed by test name: these tests are threads of one
@@ -43,9 +42,7 @@ fn workdir(test: &str) -> PathBuf {
4342
4443 /// Every Ogg fixture on disk, sorted so the table reads the same every run.
4544 fn ogg_fixtures() -> Vec<PathBuf> {
46- let Ok(entries) = std::fs::read_dir(fixtures()) else {
47- return Vec::new();
48- };
45+ let entries = std::fs::read_dir(fixtures()).expect("fixtures/audio (run scripts/fixtures.sh)");
4946 let mut out: Vec<PathBuf> = entries
5047 .flatten()
5148 .map(|e| e.path())
@@ -63,7 +60,7 @@ fn ogg_fixtures() -> Vec<PathBuf> {
6360 /// Audio packets ffprobe counts in a file — header packets excluded, which is
6461 /// also what this demuxer hands out.
6562 fn ffprobe_packets(path: &Path) -> u64 {
66- let out = Command::new("ffprobe")
63+ let out = ec_testkit::ffprobe()
6764 .args([
6865 "-v",
6966 "error",
@@ -86,7 +83,7 @@ fn ffprobe_packets(path: &Path) -> u64 {
8683
8784 /// ffprobe's own duration for the file, in seconds.
8885 fn ffprobe_duration(path: &Path) -> f64 {
89- let out = Command::new("ffprobe")
86+ let out = ec_testkit::ffprobe()
9087 .args([
9188 "-v",
9289 "error",
@@ -104,7 +101,7 @@ fn ffprobe_duration(path: &Path) -> f64 {
104101 /// Decode a file to raw 32-bit float samples with ffmpeg. Errors are fatal: an
105102 /// unreadable file is the failure being tested for.
106103 fn decode_pcm(path: &Path) -> Vec<u8> {
107- let out = Command::new("ffmpeg")
104+ let out = ec_testkit::ffmpeg()
108105 .args(["-v", "error", "-i"])
109106 .arg(path)
110107 .args(["-f", "f32le", "-"])
@@ -121,7 +118,7 @@ fn decode_pcm(path: &Path) -> Vec<u8> {
121118
122119 /// ffprobe with errors escalated: the structural verdict on a file we wrote.
123120 fn ffprobe_clean(path: &Path) -> String {
124- let out = Command::new("ffprobe")
121+ let out = ec_testkit::ffprobe()
125122 .args([
126123 "-v",
127124 "error",
@@ -161,10 +158,6 @@ fn demux_all(path: &Path) -> (Vec<StreamInfo>, Vec<Packet>, u64) {
161158 #[test]
162159 fn demuxes_every_fixture_to_eof() {
163160 let files = ogg_fixtures();
164- if files.is_empty() {
165- eprintln!("fixtures/audio absent (gitignored) — skipping");
166- return;
167- }
168161 println!(
169162 "{:<28} {:>8} {:>8} {:>10} {:>10}",
170163 "file", "ours", "ffprobe", "dur", "ffprobe"
@@ -320,10 +313,6 @@ fn remux_case(path: &Path, page_target: Option<usize>) {
320313 #[test]
321314 fn remuxes_every_fixture_bit_identically() {
322315 let files = ogg_fixtures();
323- if files.is_empty() {
324- eprintln!("fixtures/audio absent (gitignored) — skipping");
325- return;
326- }
327316 for path in &files {
328317 remux_case(path, None);
329318 }
@@ -334,13 +323,10 @@ fn remuxes_every_fixture_bit_identically() {
334323 #[test]
335324 fn page_size_does_not_change_the_audio() {
336325 let files = ogg_fixtures();
337- let Some(path) = files
326+ let path = files
338327 .iter()
339328 .find(|p| name_of(p).contains("vorbis-ogg-stereo-48000"))
340- else {
341- eprintln!("fixtures absent — skipping");
342- return;
343- };
329+ .expect("ogg fixture");
344330 remux_case(path, Some(1));
345331 remux_case(path, Some(1 << 20));
346332 }
@@ -348,13 +334,10 @@ fn page_size_does_not_change_the_audio() {
348334 #[test]
349335 fn damage_costs_one_page_and_no_more() {
350336 let files = ogg_fixtures();
351- let Some(path) = files
337+ let path = files
352338 .iter()
353339 .find(|p| name_of(p).contains("vorbis-ogg-stereo-44100"))
354- else {
355- eprintln!("fixtures absent — skipping");
356- return;
357- };
340+ .expect("ogg fixture");
358341 let (_, clean, _) = demux_all(path);
359342 let bytes = std::fs::read(path).unwrap();
360343
@@ -407,10 +390,6 @@ fn damage_costs_one_page_and_no_more() {
407390 #[test]
408391 fn seeks_land_at_or_before_the_target() {
409392 let files = ogg_fixtures();
410- if files.is_empty() {
411- eprintln!("fixtures absent — skipping");
412- return;
413- }
414393 for path in files.iter().filter(|p| {
415394 let n = p.to_string_lossy().to_string();
416395 n.contains("stereo-48000") || n.contains("5.1-44100")
@@ -465,15 +444,12 @@ fn seeks_land_at_or_before_the_target() {
465444 #[test]
466445 fn reads_flac_in_ogg() {
467446 let files = ogg_fixtures();
468- let Some(source) = files
447+ let source = files
469448 .iter()
470449 .find(|p| name_of(p).contains("vorbis-ogg-stereo-44100"))
471- else {
472- eprintln!("fixtures absent — skipping");
473- return;
474- };
450+ .expect("ogg fixture");
475451 let path = workdir("flac").join("flac-in.ogg");
476- let made = Command::new("ffmpeg")
452+ let made = ec_testkit::ffmpeg()
477453 .args(["-v", "error", "-y", "-i"])
478454 .arg(source)
479455 .args(["-c:a", "flac", "-f", "ogg"])
crates/ec-ogg/tests/real_library.rsmodified+8 -110
@@ -1,6 +1,3 @@
1-//! The personal media library, Ogg half: every `ogg` row of
2-//! `fixtures/real-library-manifest.tsv` whose audio is Vorbis or Opus is read
3-//! by [`OggDemuxer`] end to end and compared with ffmpeg/ffprobe.
41 //!
52 //! Per file the oracle checks:
63 //! - packet count and every packet's size (ffprobe, audio stream 0);
@@ -31,25 +28,12 @@
3128 //!
3229 //! Scope: demux only. The decoded PCM is not compared here.
3330 //!
34-//! Each file either matches, is refused by name (no logical stream with a
35-//! known mapping), or fails. A refusal is reported, not counted as a failure.
36-//!
37-//! LOCAL ONLY and ignored: the manifest is generated from the user's own media
38-//! by `scripts/scan-real-library.sh` and is gitignored, so no other host has it.
39-//! cargo test -p ec-ogg --test real_library -- --ignored --nocapture
4031
41-use std::path::{Path, PathBuf};
42-use std::process::{Command, Stdio};
32+use std::path::Path;
4333
4434 use ec_core::Demuxer;
4535 use ec_ogg::{Mapping, OggDemuxer, granule_of};
4636
47-/// One manifest row: the columns the sweep reads.
48-struct Entry {
49- path: PathBuf,
50- acodecs: String,
51-}
52-
5337 /// One packet as ffprobe reports it.
5438 struct Probed {
5539 pts: Option<i64>,
@@ -64,40 +48,6 @@ enum Verdict {
6448 Failed(String),
6549 }
6650
67-fn have(tool: &str) -> bool {
68- Command::new(tool)
69- .arg("-version")
70- .stdout(Stdio::null())
71- .stderr(Stdio::null())
72- .status()
73- .is_ok_and(|s| s.success())
74-}
75-
76-/// The manifest's Ogg rows with Vorbis or Opus audio, or `None` when the
77-/// manifest itself is absent.
78-fn manifest_ogg_entries() -> Option<Vec<Entry>> {
79- let manifest =
80- Path::new(env!("CARGO_MANIFEST_DIR")).join("../../fixtures/real-library-manifest.tsv");
81- let text = std::fs::read_to_string(&manifest).ok()?;
82- let mut out = Vec::new();
83- for line in text.lines().skip(1) {
84- let f: Vec<&str> = line.split('\t').collect();
85- if f.len() < 8 || f[1] != "ogg" || !Path::new(f[0]).is_file() {
86- continue;
87- }
88- // The first audio stream decides the mapping this file is checked as.
89- let first = f[7].split(',').next().unwrap_or_default();
90- if first != "vorbis" && first != "opus" {
91- continue;
92- }
93- out.push(Entry {
94- path: PathBuf::from(f[0]),
95- acodecs: f[7].to_string(),
96- });
97- }
98- Some(out)
99-}
100-
10151 /// Parses an ffprobe csv cell: `N/A` and blanks are absent.
10252 fn cell(s: &str) -> Option<i64> {
10353 let s = s.trim();
@@ -110,7 +60,7 @@ fn cell(s: &str) -> Option<i64> {
11060
11161 /// Audio stream 0's packets: header packets are not among them, as with ours.
11262 fn ffprobe_packets(path: &Path) -> Result<Vec<Probed>, String> {
113- let out = Command::new("ffprobe")
63+ let out = ec_testkit::ffprobe()
11464 .args([
11565 "-v",
11666 "error",
@@ -145,7 +95,7 @@ fn ffprobe_packets(path: &Path) -> Result<Vec<Probed>, String> {
14595
14696 /// ffprobe's stated extradata size for audio stream 0.
14797 fn ffprobe_extradata_size(path: &Path) -> Result<usize, String> {
148- let out = Command::new("ffprobe")
98+ let out = ec_testkit::ffprobe()
14999 .args([
150100 "-v",
151101 "error",
@@ -168,7 +118,7 @@ fn ffprobe_extradata_size(path: &Path) -> Result<usize, String> {
168118
169119 /// ffmpeg's concatenated audio packet payloads, copied and not decoded.
170120 fn ffmpeg_payload(path: &Path) -> Result<Vec<u8>, String> {
171- let out = Command::new("ffmpeg")
121+ let out = ec_testkit::ffmpeg()
172122 .args(["-v", "error", "-i"])
173123 .arg(path)
174124 .args(["-map", "0:a:0", "-c", "copy", "-f", "data", "-"])
@@ -355,63 +305,11 @@ fn vorbis_header_problem(block: &[u8]) -> Option<String> {
355305 None
356306 }
357307
358-fn short_name(path: &Path) -> String {
359- path.file_name()
360- .map(|n| n.to_string_lossy().chars().take(38).collect())
361- .unwrap_or_default()
362-}
363-
364308 #[test]
365-#[ignore = "sweeps the PERSONAL media library (fixtures/real-library-manifest.tsv, ogg rows) through ffmpeg; local only: run with --ignored."]
366309 fn real_library_ogg_streams_match_ffmpeg() {
367- if !have("ffmpeg") || !have("ffprobe") {
368- eprintln!("skipped: ffmpeg and ffprobe are required to sweep the library");
369- return;
370- }
371- let Some(entries) = manifest_ogg_entries() else {
372- eprintln!(
373- "skipped: no fixtures/real-library-manifest.tsv; generate it with \
374- scripts/scan-real-library.sh on the machine that holds the media"
375- );
376- return;
377- };
378- if entries.is_empty() {
379- eprintln!("skipped: the manifest lists no ogg rows with vorbis or opus audio");
380- return;
310+ let path = ec_testkit::fixture("open/sintel_trailer-480p.ogv");
311+ match check_file(&path) {
312+ Verdict::Match(s) => eprintln!("{}: match: {s}", path.display()),
313+ Verdict::Refused(e) | Verdict::Failed(e) => panic!("{}: {e}", path.display()),
381314 }
382-
383- let mut table = String::new();
384- let mut checked = 0usize;
385- let mut refused = 0usize;
386- let mut failures = Vec::new();
387- for entry in &entries {
388- let name = short_name(&entry.path);
389- let codec = entry.acodecs.split(',').next().unwrap_or_default();
390- let verdict = check_file(&entry.path);
391- let line = match verdict {
392- Verdict::Match(s) => {
393- checked += 1;
394- format!("{name:<38} {codec:<7} match: {s}\n")
395- }
396- Verdict::Refused(e) => {
397- refused += 1;
398- format!("{name:<38} {codec:<7} refused: {e}\n")
399- }
400- Verdict::Failed(e) => {
401- failures.push(format!("{name}: {e}"));
402- format!("{name:<38} {codec:<7} FAILED {e}\n")
403- }
404- };
405- table.push_str(&line);
406- }
407- eprintln!("{table}");
408- eprintln!(
409- "real library ogg: {checked} match, {refused} refused by name, {} failed",
410- failures.len()
411- );
412- assert!(failures.is_empty(), "{failures:#?}");
413- assert!(
414- checked + refused >= 1 && checked >= 1,
415- "no real Ogg file was checked end to end"
416- );
417315 }
crates/ec-probe/Cargo.tomlmodified+3 -0
@@ -22,3 +22,6 @@ ec-opus = { workspace = true }
2222 ec-riff = { workspace = true }
2323 ec-truehd = { workspace = true }
2424 ec-vorbis = { workspace = true }
25+
26+[dev-dependencies]
27+ec-testkit.workspace = true
crates/ec-probe/src/lib.rsmodified+1 -6
@@ -1327,12 +1327,7 @@ mod tests {
13271327 /// s: `1024` samples read straight off as `1024` one-millisecond ticks).
13281328 #[test]
13291329 fn duration_converts_initial_padding_out_of_sample_units() {
1330- let path = Path::new(env!("CARGO_MANIFEST_DIR"))
1331- .join("../../fixtures/audio/aac-mka-stereo-48000.mka");
1332- if !path.exists() {
1333- return; // fixtures are generated, not checked in
1334- }
1335- let reader = Reader::open(&path).unwrap();
1330+ let reader = Reader::open(ec_testkit::fixture("audio/aac-mka-stereo-48000.mka")).unwrap();
13361331 let d = reader.duration().expect("a stated duration").as_secs_f64();
13371332 assert!((d - 3.0).abs() < 0.1, "duration {d}, want ~3.0s");
13381333 }
crates/ec-probe/tests/dts.rsmodified+7 -22
@@ -4,17 +4,12 @@
44 //! and channels, and hand back the stream's bytes frame by frame.
55
66 use std::path::{Path, PathBuf};
7-use std::process::Command;
87
98 use ec_core::CodecId;
109 use ec_core::registry::{MediaType, SeekMode};
1110 use ec_core::timebase::{TimeBase, Timestamp};
1211 use ec_probe::{Format, Reader};
1312
14-fn required() -> bool {
15- std::env::var_os("EC_REQUIRE_FIXTURES").is_some_and(|v| !v.is_empty() && v != "0")
16-}
17-
1813 fn work() -> PathBuf {
1914 let d = std::env::temp_dir().join(format!("ec-probe-dts-{}", std::process::id()));
2015 std::fs::create_dir_all(&d).unwrap();
@@ -22,7 +17,7 @@ fn work() -> PathBuf {
2217 }
2318
2419 fn ffmpeg(args: &[&str], out: &Path) -> bool {
25- Command::new("ffmpeg")
20+ ec_testkit::ffmpeg()
2621 .args(["-v", "error", "-y"])
2722 .args(args)
2823 .arg(out)
@@ -31,7 +26,7 @@ fn ffmpeg(args: &[&str], out: &Path) -> bool {
3126 }
3227
3328 /// A raw DTS stream of `channels` channels, 0.5 s at 48 kHz.
34-fn raw_dts(channels: &str) -> Option<Vec<u8>> {
29+fn raw_dts(channels: &str) -> Vec<u8> {
3530 static LOCK: std::sync::Mutex<()> = std::sync::Mutex::new(());
3631 let _guard = LOCK.lock().unwrap_or_else(|e| e.into_inner());
3732 let path = work().join(format!("{channels}.dts"));
@@ -50,12 +45,8 @@ fn raw_dts(channels: &str) -> Option<Vec<u8>> {
5045 ],
5146 &path,
5247 );
53- if !ok {
54- assert!(!required(), "ffmpeg cannot make a DTS fixture");
55- eprintln!("skip: no ffmpeg with the dca encoder");
56- return None;
57- }
58- std::fs::read(&path).ok()
48+ assert!(ok, "ffmpeg cannot make a DTS fixture");
49+ std::fs::read(&path).unwrap()
5950 }
6051
6152 fn wav_pcm_tagged(dts: &[u8], rate: u32) -> Vec<u8> {
@@ -109,9 +100,7 @@ fn check(bytes: &[u8], file: &str, format: Format, channels: usize, want: &[u8])
109100 #[test]
110101 fn raw_dts_stereo_and_51() {
111102 for (ch, n) in [("2", 2), ("6", 6)] {
112- let Some(raw) = raw_dts(ch) else {
113- return;
114- };
103+ let raw = raw_dts(ch);
115104 assert_eq!(&raw[..4], &[0x7F, 0xFE, 0x80, 0x01]);
116105 check(&raw, &format!("raw{ch}.dts"), Format::Dts, n, &raw);
117106 }
@@ -119,9 +108,7 @@ fn raw_dts_stereo_and_51() {
119108
120109 #[test]
121110 fn raw_dts_little_endian() {
122- let Some(raw) = raw_dts("2") else {
123- return;
124- };
111+ let raw = raw_dts("2");
125112 let mut le = raw.clone();
126113 for p in le.as_chunks_mut::<2>().0.iter_mut() {
127114 p.swap(0, 1);
@@ -131,9 +118,7 @@ fn raw_dts_little_endian() {
131118
132119 #[test]
133120 fn dts_in_wav_pcm_tag_and_2001_tag() {
134- let Some(raw) = raw_dts("2") else {
135- return;
136- };
121+ let raw = raw_dts("2");
137122 check(
138123 &wav_pcm_tagged(&raw, 48_000),
139124 "pcm.wav",
crates/ec-probe/tests/legacy_audio.rsmodified+2 -8
@@ -1,19 +1,13 @@
11 //! IMA/MS ADPCM and G.711 through the probe (Reader + AudioDecoder) from
22 //! ffmpeg-made WAV, AVI and MOV files, compared with ffmpeg's s16 decode.
3-//! Skips without ffmpeg unless `EC_REQUIRE_FIXTURES=1`.
43
54 use std::path::PathBuf;
6-use std::process::Command;
75
86 use ec_core::registry::MediaType;
97 use ec_probe::{AudioDecoder, Reader};
108
119 #[test]
1210 fn legacy_audio_decodes_through_the_probe() {
13- if Command::new("ffmpeg").arg("-version").output().is_err() {
14- assert!(std::env::var_os("EC_REQUIRE_FIXTURES").is_none(), "ffmpeg missing");
15- return;
16- }
1711 let dir: PathBuf = std::env::temp_dir().join(format!("ec-probe-legacy-{}", std::process::id()));
1812 std::fs::create_dir_all(&dir).expect("tmp");
1913 let mut n = 0;
@@ -30,7 +24,7 @@ fn legacy_audio_decodes_through_the_probe() {
3024 ] {
3125 for ch in ["1", "2"] {
3226 let path = dir.join(format!("{enc}-{ch}.{ext}"));
33- let o = Command::new("ffmpeg")
27+ let o = ec_testkit::ffmpeg()
3428 .args(["-nostdin", "-y", "-v", "error", "-f", "lavfi", "-i"])
3529 .arg("aevalsrc='0.6*sin(2*PI*440*t)+0.2*sin(2*PI*3000*t*t)':s=16000:d=1.1")
3630 .args(["-ac", ch, "-c:a", enc])
@@ -38,7 +32,7 @@ fn legacy_audio_decodes_through_the_probe() {
3832 .output()
3933 .expect("ffmpeg");
4034 assert!(o.status.success(), "{}", String::from_utf8_lossy(&o.stderr));
41- let want = Command::new("ffmpeg")
35+ let want = ec_testkit::ffmpeg()
4236 .args(["-nostdin", "-v", "error", "-i"])
4337 .arg(&path)
4438 .args(["-f", "f32le", "-"])
crates/ec-probe/tests/library.rsmodified+14 -436
@@ -1,14 +1,7 @@
1-//! His library, not fixtures: open, list, decode and seek real files, and
2-//! compare what the probe says against ffprobe file by file.
3-//!
4-//! Driven by `fixtures/real-library-manifest.tsv` (written by
5-//! `scripts/scan-real-library.sh`). Files that have since moved are skipped and
6-//! reported, never failed — the manifest is a snapshot of a moving library.
71
82 use std::fs::File;
93 use std::io::{Read, Seek, SeekFrom};
10-use std::path::{Path, PathBuf};
11-use std::process::Command;
4+use std::path::Path;
125 use std::sync::{
136 Arc,
147 atomic::{AtomicU64, Ordering},
@@ -19,55 +12,6 @@ use ec_core::registry::{CodecId, MediaType, SeekMode};
1912 use ec_core::timebase::{TimeBase, Timestamp};
2013 use ec_probe::Reader;
2114
22-fn manifest() -> Vec<(PathBuf, String, String, f64)> {
23- let path =
24- Path::new(env!("CARGO_MANIFEST_DIR")).join("../../fixtures/real-library-manifest.tsv");
25- let Ok(text) = std::fs::read_to_string(path) else {
26- return Vec::new();
27- };
28- text.lines()
29- .skip(1)
30- .filter_map(|line| {
31- let f: Vec<&str> = line.split('\t').collect();
32- let path = PathBuf::from(f.first()?);
33- let acodecs = f
34- .get(7)
35- .filter(|s| **s != "-")
36- .map_or_else(String::new, |s| (*s).to_string());
37- Some((
38- path,
39- (*f.get(1)?).to_string(),
40- acodecs,
41- f.get(8)?.parse().unwrap_or(0.0),
42- ))
43- })
44- .collect()
45-}
46-
47-/// Decode `secs` of audio from the current position; answers sample frames.
48-fn decode_some(reader: &mut Reader, stream: u32, secs: f64) -> Result<u64, String> {
49- let mut decoder = reader.make_decoder(stream).map_err(|e| e.to_string())?;
50- let rate = f64::from(decoder.sample_rate().max(1));
51- let want = (secs * rate) as u64;
52- let mut out = Vec::new();
53- let mut frames = 0u64;
54- while frames < want {
55- let packet = match reader.next_packet() {
56- Ok(p) => p,
57- Err(e) if e.is_eof() => break,
58- Err(e) => return Err(format!("demux: {e}")),
59- };
60- if packet.stream != stream {
61- continue;
62- }
63- decoder
64- .decode(&packet, &mut out)
65- .map_err(|e| format!("decode: {e}"))?;
66- frames += (out.len() / decoder.channels().max(1)) as u64;
67- }
68- Ok(frames)
69-}
70-
7115 fn decode_window(reader: &mut Reader, stream: u32, secs: f64) -> Result<Vec<f32>, String> {
7216 let mut decoder = reader.make_decoder(stream).map_err(|e| e.to_string())?;
7317 let channels = decoder.channels().max(1);
@@ -93,7 +37,7 @@ fn decode_window(reader: &mut Reader, stream: u32, secs: f64) -> Result<Vec<f32>
9337 }
9438
9539 fn reference_seek_window(path: &Path, at: f64) -> Vec<f32> {
96- let out = Command::new("ffmpeg")
40+ let out = ec_testkit::ffmpeg()
9741 .args(["-v", "error", "-ss", &format!("{at:.6}"), "-i"])
9842 .arg(path)
9943 .args([
@@ -139,35 +83,6 @@ impl Seek for CountedFile {
13983 }
14084 }
14185
142-fn hive_avi_files() -> Vec<PathBuf> {
143- let root = Path::new("/home/user/Downloads");
144- let Ok(entries) = std::fs::read_dir(root) else {
145- return Vec::new();
146- };
147- let mut files = Vec::new();
148- for entry in entries.flatten() {
149- let path = entry.path();
150- if !path
151- .file_name()
152- .and_then(|n| n.to_str())
153- .is_some_and(|n| n.contains("Hive-CM8"))
154- {
155- continue;
156- }
157- let Ok(children) = std::fs::read_dir(path) else {
158- continue;
159- };
160- for child in children.flatten() {
161- let path = child.path();
162- if path.extension().and_then(|e| e.to_str()) == Some("avi") {
163- files.push(path);
164- }
165- }
166- }
167- files.sort_by_key(|p| std::fs::metadata(p).map(|m| m.len()).unwrap_or(u64::MAX));
168- files
169-}
170-
17186 fn assert_avi_index_is_bounded(path: &Path) {
17287 let file_size = std::fs::metadata(path).expect("AVI metadata").len();
17388 let index_len = ec_riff::AviReader::new(File::open(path).expect("open AVI"))
@@ -408,356 +323,23 @@ fn assert_avi_seeks_match_reference(path: &Path) {
408323 }
409324 }
410325
411-fn synthetic_mp3_avi() -> Option<PathBuf> {
412- if !Command::new("ffmpeg")
413- .args(["-version"])
414- .output()
415- .is_ok_and(|out| out.status.success())
416- {
417- eprintln!("reference encoder/decoder absent, skipping synthetic AVI");
418- return None;
419- }
420- let root = PathBuf::from(std::env::var_os("HOME").expect("HOME")).join(".cache/aviseek");
421- std::fs::create_dir_all(&root).expect("create scratch directory");
422- let path = root.join(format!("seek-oracle-{}.avi", std::process::id()));
423- let out = Command::new("ffmpeg")
424- .args([
425- "-v",
426- "error",
427- "-f",
428- "lavfi",
429- "-i",
430- "sine=frequency=997:sample_rate=48000:duration=30",
431- "-c:a",
432- "libmp3lame",
433- "-f",
434- "avi",
435- "-y",
436- ])
437- .arg(&path)
438- .output()
439- .expect("reference encoder runs");
440- assert!(
441- out.status.success(),
442- "{}",
443- String::from_utf8_lossy(&out.stderr)
444- );
445- Some(path)
446-}
447-
448-/// Ten files with sound, standalone audio first, then Matroska — opened,
449-/// decoded and seeked, with a per-file row in the report.
450326 #[test]
451-fn a_real_library_sweep() {
452- let files = manifest();
453- if files.is_empty() {
454- eprintln!("no manifest — run scripts/scan-real-library.sh");
455- return;
456- }
457- // Half standalone audio, half Matroska: the two paths this crate owns, and
458- // one row per distinct audio codec the library actually holds rather than
459- // ten copies of the same aac remux.
460- let standalone = |p: &Path| {
461- let ext = p.extension().and_then(|e| e.to_str()).unwrap_or("");
462- [
463- "mp3", "flac", "wav", "ogg", "opus", "m4a", "aac", "mp4", "mov",
464- ]
465- .contains(&ext)
466- };
467- let mut chosen: Vec<_> = Vec::new();
468- let mut seen = Vec::new();
469- for want_mkv in [false, true] {
470- let mut taken = 0;
471- for f in &files {
472- let (p, container, acodecs, _) = f;
473- if acodecs.is_empty() || !p.exists() || taken >= 5 {
474- continue;
475- }
476- let is_mkv = container.contains("matroska");
477- if is_mkv != want_mkv || (!is_mkv && !standalone(p)) {
478- continue;
479- }
480- // One file per (container, codec set): variety beats repetition.
481- let key = format!("{is_mkv}:{acodecs}");
482- if seen.contains(&key) {
483- continue;
484- }
485- seen.push(key);
486- chosen.push(f);
487- taken += 1;
488- }
489- }
490- // lane-h264reallib: NOT an `assert!` here. The file's own header, lines
491- // 5-6, is the spec: "Files that have since moved are skipped and
492- // reported, never failed -- the manifest is a snapshot of a moving
493- // library." An empty `chosen` IS the moved-files case, so failing on it
494- // contradicted the contract this file declares. It was also red on any
495- // host whose manifest paths no longer resolve, for a reason that had
496- // nothing to do with the probe. Reported and returned, which is what
497- // "skipped and reported, never failed" asks for.
498- if chosen.is_empty() {
499- eprintln!(
500- "skipped: no readable file in the manifest (every row has moved or is unreadable)"
501- );
502- return;
503- }
504-
505- let mut rows = Vec::new();
506- let mut failures = Vec::new();
507- for (path, container, acodecs, duration) in &chosen {
508- let name = path.file_name().unwrap().to_string_lossy().to_string();
509- let mut reader = match Reader::open(path) {
510- Ok(r) => r,
511- Err(e) => {
512- failures.push(format!("{name}: open failed: {e}"));
513- continue;
514- }
515- };
516- // The first audio stream that actually decodes, which is what a player
517- // plays; the ones that do not are named below rather than skipped over.
518- let audio = reader
519- .streams()
520- .iter()
521- .find(|s| {
522- s.params.codec.media_type() == MediaType::Audio
523- && reader.make_decoder(s.index).is_ok()
524- })
525- .or_else(|| reader.default_stream(MediaType::Audio))
526- .cloned();
527- let Some(audio) = audio else {
528- failures.push(format!("{name}: no audio stream, ffprobe says {acodecs}"));
529- continue;
530- };
531- let unsupported = reader.unsupported();
532- // Every codec ffprobe lists is either decodable here or named as not.
533- let listed: Vec<String> = reader
534- .streams()
535- .iter()
536- .filter(|s| s.params.codec.media_type() == MediaType::Audio)
537- .map(|s| s.params.codec.name().to_string())
538- .collect();
539- let decoded = decode_some(&mut reader, audio.index, 1.0);
540- let rate = audio.params.audio().map_or(0, |a| a.sample_rate).max(1);
541- let landing = if *duration > 4.0 {
542- let ticks = (duration / 2.0 * f64::from(rate)) as i64;
543- reader
544- .seek(
545- audio.index,
546- Timestamp::new(ticks, TimeBase::from_rate(rate)),
547- SeekMode::SyncBefore,
548- )
549- .map(|t| t.as_secs_f64())
550- .map_err(|e| e.to_string())
551- } else {
552- Ok(0.0)
553- };
554- let after_seek = landing
555- .as_ref()
556- .ok()
557- .map(|_| decode_some(&mut reader, audio.index, 0.5));
558-
559- let ok = decoded.is_ok()
560- && landing.is_ok()
561- && matches!(after_seek, Some(Ok(n)) if n > 0)
562- && listed.iter().any(|c| acodecs.split(',').any(|a| a == c));
563- if !ok {
564- failures.push(format!(
565- "{name}: decode {decoded:?} seek {landing:?} after {after_seek:?} \
566- codecs {listed:?} vs ffprobe {acodecs}"
567- ));
568- }
569- rows.push(format!(
570- "{:<52} {:<16} {:<14} {:>7} frames seek->{:>8} {}",
571- name.chars().take(52).collect::<String>(),
572- container.split(',').next().unwrap_or(container),
573- listed.join(","),
574- decoded.clone().unwrap_or(0),
575- landing
576- .as_ref()
577- .map(|s| format!("{s:.2}s"))
578- .unwrap_or_else(|e| e.clone()),
579- match unsupported.is_empty() {
580- true => "all decodable".to_string(),
581- false => unsupported
582- .iter()
583- .map(|u| format!("unsupported: {} ({})", u.codec.name(), u.reason))
584- .collect::<Vec<_>>()
585- .join("; "),
586- }
587- ));
588- }
589- eprintln!(
590- "real-library sweep ({} files):\n{}",
591- rows.len(),
592- rows.join("\n")
593- );
594- assert!(failures.is_empty(), "{}", failures.join("\n"));
595-}
596-
597-#[test]
598-fn avi_audio_chunks_end_cleanly_on_real_files() {
599- let files = [
600- "/home/user/Downloads/reele/reele.avi",
601- "/home/user/Downloads/reele/sample.avi",
602- ];
603- let mut present = 0;
604- for path in files {
605- let path = Path::new(path);
606- if !path.exists() {
607- continue;
608- }
609- present += 1;
610- let mut reader = Reader::open(path).expect("AVI opens");
611- let audio = reader
612- .default_stream(MediaType::Audio)
613- .expect("AVI audio stream")
614- .index;
615- let (packets, frames, _) =
616- decode_stream_to_eof(&mut reader, audio, false).unwrap_or_else(|e| {
617- panic!("{}: {e}", path.display());
618- });
619- eprintln!(
620- "{}: open ok, packets {packets}, decode-to-EOF {frames} frames",
621- path.display()
622- );
623- assert!(packets > 0, "{}: no audio packets", path.display());
624- assert!(frames > 0, "{}: no decoded audio", path.display());
625- }
626- if present == 0 {
627- // The library is his, so a file can leave it; the sibling AVI tests
628- // skip the same way rather than failing a run on a deleted download.
629- eprintln!("AVI files absent, skipping");
630- }
631-}
632-
633-#[test]
634-fn avi_ac3_matches_reference_decoder_on_real_sample() {
635- let path = Path::new(
636- "/home/user/Downloads/reele/sample.avi",
637- );
638- if !path.exists() {
639- eprintln!("file not present, skipping");
640- return;
641- }
642-
643- let mut reader = Reader::open(path).expect("AVI opens");
327+fn avi_audio_chunks_end_cleanly() {
328+ let path = ec_testkit::fixture("derived/sintel720.avi");
329+ let mut reader = Reader::open(&path).expect("AVI opens");
644330 let audio = reader
645331 .default_stream(MediaType::Audio)
646332 .expect("AVI audio stream")
647333 .index;
648- let (packets, frames, ours) =
649- decode_stream_to_eof(&mut reader, audio, true).expect("AVI decodes to EOF");
650- assert!(packets > 0, "no packets");
651- assert!(frames > 0, "no decoded frames");
652-
653- let out = Command::new("ffmpeg")
654- .args(["-v", "error", "-i"])
655- .arg(path)
656- .args(["-map", "0:a:0", "-f", "f32le", "-acodec", "pcm_f32le", "-"])
657- .output()
658- .expect("reference decoder runs");
659- assert!(
660- out.status.success(),
661- "{}",
662- String::from_utf8_lossy(&out.stderr)
663- );
664- let theirs: Vec<f32> = out
665- .stdout
666- .as_chunks::<4>().0.iter()
667- .map(|c| f32::from_le_bytes([c[0], c[1], c[2], c[3]]))
668- .collect();
669- let score = corr(&ours, &theirs);
670- eprintln!(
671- "{}: open ok, packets {packets}, decode-to-EOF {frames} frames, corr {score:.6}",
672- path.display()
673- );
674- assert!(score > 0.999, "corr vs reference decoder = {score}");
675-}
676-
677-#[test]
678-fn avi_seek_matches_reference_decoder_on_real_files() {
679- let files = hive_avi_files();
680- if files.is_empty() {
681- eprintln!("AVI files absent, skipping");
682- return;
683- }
684- for path in files {
685- assert_avi_seeks_match_reference(&path);
686- }
334+ let (packets, frames, _) = decode_stream_to_eof(&mut reader, audio, false)
335+ .unwrap_or_else(|e| panic!("{}: {e}", path.display()));
336+ assert!(packets > 0, "{}: no audio packets", path.display());
337+ assert!(frames > 0, "{}: no decoded audio", path.display());
687338 }
688339
689340 #[test]
690-fn avi_seek_matches_reference_decoder_on_synthetic_mp3() {
691- let Some(path) = synthetic_mp3_avi() else {
692- return;
693- };
694- assert_avi_seeks_match_reference(&path);
695- std::fs::remove_file(path).expect("remove synthetic AVI");
696-}
697-
698-/// The TrueHD remux in his library: the track decodes through the unified
699-/// reader, 7.1 at 48 kHz, with the AC-3 track beside it still decoding too.
700-#[test]
701-fn a_truehd_track_decodes() {
702- let Some((path, ..)) = manifest()
703- .into_iter()
704- .find(|(p, _, acodecs, _)| acodecs.contains("truehd") && p.exists())
705- else {
706- eprintln!("no TrueHD file in the manifest — skipping");
707- return;
708- };
709- let mut reader = Reader::open(&path).expect("open");
710- let truehd = reader
711- .streams()
712- .iter()
713- .find(|s| s.params.codec.name() == "truehd")
714- .cloned()
715- .expect("the TrueHD track is listed");
716- let decoder = reader.make_decoder(truehd.index).expect("truehd decoder");
717- assert_eq!(decoder.channels(), 8, "7.1 TrueHD is 8 channels");
718- assert_eq!(decoder.sample_rate(), 48_000);
719- let frames = decode_some(&mut reader, truehd.index, 1.0).expect("decode");
720- assert!(frames > 0, "no TrueHD audio came out");
721- // ...and the AC-3 track beside it still decodes.
722- let decodable: Vec<_> = reader
723- .streams()
724- .iter()
725- .filter(|s| s.params.codec.media_type() == MediaType::Audio)
726- .filter(|s| reader.make_decoder(s.index).is_ok())
727- .map(|s| s.params.codec.name())
728- .collect();
729- assert!(
730- decodable.contains(&"ac3") || decodable.contains(&"truehd"),
731- "a file with a TrueHD track and an AC-3 one came out with nothing to play: {decodable:?}"
732- );
733- eprintln!(
734- "{}: truehd decoded {frames} frames, tracks {decodable:?}",
735- path.file_name().unwrap().to_string_lossy(),
736- );
737-}
738-
739-/// ffprobe's stream count for the same file, as a cross-check that nothing is
740-/// being hidden.
741-#[allow(dead_code)]
742-fn ffprobe_audio_codecs(path: &Path) -> Vec<String> {
743- let out = Command::new("ffprobe")
744- .args([
745- "-v",
746- "error",
747- "-select_streams",
748- "a",
749- "-show_entries",
750- "stream=codec_name",
751- "-of",
752- "default=nw=1:nk=1",
753- ])
754- .arg(path)
755- .output()
756- .expect("ffprobe");
757- String::from_utf8_lossy(&out.stdout)
758- .lines()
759- .map(|l| l.trim().to_string())
760- .collect()
341+fn avi_seek_matches_reference_decoder() {
342+ assert_avi_seeks_match_reference(&ec_testkit::fixture("derived/sintel720.avi"));
761343 }
762344
763345 /// Cover-art (`APIC`) ID3v2 tags shipped by real rippers/taggers put a whole
@@ -767,12 +349,8 @@ fn ffprobe_audio_codecs(path: &Path) -> Vec<String> {
767349 /// the same first second, not just "it opened".
768350 #[test]
769351 fn a_cover_art_tagged_mp3_opens() {
770- let path = Path::new("/home/user/Music/reeli.mp3");
771- if !path.exists() {
772- eprintln!("file not present, skipping");
773- return;
774- }
775- let mut reader = Reader::open(path).expect("open");
352+ let path = ec_testkit::fixture("audio/cover-mp3-stereo-44100.mp3");
353+ let mut reader = Reader::open(&path).expect("open");
776354 let audio = reader
777355 .default_stream(MediaType::Audio)
778356 .cloned()
@@ -804,7 +382,7 @@ fn a_cover_art_tagged_mp3_opens() {
804382 let ours = &ours[lead_in as usize..];
805383 assert!(ours.len() as u32 >= rate / 2, "decoded too little audio");
806384
807- let out = Command::new("ffmpeg")
385+ let out = ec_testkit::ffmpeg()
808386 .args(["-v", "error", "-t", "1", "-i"])
809387 .arg(path)
810388 .args(["-map", "0:a:0", "-f", "f32le", "-acodec", "pcm_f32le", "-"])
crates/ec-probe/tests/matrix.rsmodified+7 -28
@@ -3,23 +3,20 @@
33 //! where it says it does after a hundred random seeks — on one reader.
44 //!
55 //! Oracle is ffmpeg/ffprobe (labelled as such: this is not a conformance
6-//! claim). A missing fixture skips its row rather than failing the suite, so a
7-//! checkout without generated fixtures still builds and runs.
86
97 use std::path::{Path, PathBuf};
10-use std::process::Command;
118
129 use ec_core::registry::{MediaType, SeekMode};
1310 use ec_core::timebase::{TimeBase, Timestamp};
1411 use ec_probe::{Format, Reader};
1512
1613 fn fixtures() -> PathBuf {
17- Path::new(env!("CARGO_MANIFEST_DIR")).join("../../fixtures/audio")
14+ ec_testkit::root().join("audio")
1815 }
1916
2017 /// `ffprobe` on one entry of the first audio stream.
2118 fn probe(path: &Path, args: &[&str]) -> String {
22- let out = Command::new("ffprobe")
19+ let out = ec_testkit::ffprobe()
2320 .args(["-v", "error", "-select_streams", "a:0"])
2421 .args(args)
2522 .args(["-of", "default=nw=1:nk=1"])
@@ -49,7 +46,7 @@ fn ffprobe_packets(path: &Path) -> u64 {
4946
5047 /// Sample frames ffmpeg decodes out of the first audio stream.
5148 fn ffmpeg_frames(path: &Path, channels: usize) -> u64 {
52- let out = Command::new("ffmpeg")
49+ let out = ec_testkit::ffmpeg()
5350 .args(["-nostdin", "-v", "error", "-i"])
5451 .arg(path)
5552 .args(["-map", "0:a:0", "-f", "f32le", "-"])
@@ -116,9 +113,6 @@ fn every_fixture_probes_decodes_and_counts() {
116113 let mut rows = Vec::new();
117114 for &(name, format, codec) in MATRIX {
118115 let path = fixtures().join(name);
119- if !path.exists() {
120- continue;
121- }
122116 let mut reader = Reader::open(&path).unwrap_or_else(|e| panic!("{name}: {e}"));
123117 assert_eq!(reader.format(), format, "{name}: format");
124118 let audio = reader
@@ -164,7 +158,7 @@ fn every_fixture_probes_decodes_and_counts() {
164158 }
165159 assert!(
166160 checked > 0,
167- "no fixtures found — run scripts/gen-fixtures.sh"
161+ "no fixtures found — run scripts/fixtures.sh"
168162 );
169163 eprintln!("probe matrix ({checked} files):\n{}", rows.join("\n"));
170164 }
@@ -176,9 +170,6 @@ fn a_hundred_random_seeks_land_where_they_say() {
176170 let mut checked = 0;
177171 for &(name, _, codec) in MATRIX {
178172 let path = fixtures().join(name);
179- if !path.exists() {
180- continue;
181- }
182173 let mut reader = Reader::open(&path).expect("open");
183174 let audio = reader
184175 .default_stream(MediaType::Audio)
@@ -247,7 +238,7 @@ fn a_hundred_random_seeks_land_where_they_say() {
247238 }
248239 assert!(
249240 checked > 0,
250- "no fixtures found — run scripts/gen-fixtures.sh"
241+ "no fixtures found — run scripts/fixtures.sh"
251242 );
252243 eprintln!("100 random seeks each on {checked} files, one reader per file");
253244 }
@@ -259,9 +250,6 @@ fn cover_art_is_never_a_video_track() {
259250 let mut checked = 0;
260251 for name in ["cover-mp3-stereo-44100.mp3", "cover-mp4-stereo-44100.m4a"] {
261252 let path = fixtures().join(name);
262- if !path.exists() {
263- continue;
264- }
265253 let reader = Reader::open(&path).expect("open");
266254 let video: Vec<_> = reader
267255 .streams()
@@ -278,16 +266,13 @@ fn cover_art_is_never_a_video_track() {
278266 );
279267 checked += 1;
280268 }
281- assert!(checked > 0, "no cover-art fixtures — run gen-fixtures.sh");
269+ assert!(checked > 0, "no cover-art fixtures — run scripts/fixtures.sh");
282270 }
283271
284272 /// The tags an ID3v2-tagged file carries come back off it.
285273 #[test]
286274 fn id3_tags_come_off_a_real_file() {
287275 let path = fixtures().join("cover-mp3-stereo-44100.mp3");
288- if !path.exists() {
289- return;
290- }
291276 let reader = Reader::open(&path).expect("open");
292277 assert_eq!(reader.tags().title.as_deref(), Some("A Tone"));
293278 assert_eq!(reader.tags().artist.as_deref(), Some("edith_codecs"));
@@ -298,9 +283,6 @@ fn id3_tags_come_off_a_real_file() {
298283 #[test]
299284 fn a_mislabelled_file_opens_as_what_it_is() {
300285 let src = fixtures().join("flac-stereo-48000.flac");
301- if !src.exists() {
302- return;
303- }
304286 let liar = std::env::temp_dir().join("ec-probe-liar.mp3");
305287 std::fs::copy(&src, &liar).expect("copy");
306288 let reader = Reader::open(&liar).expect("open");
@@ -322,9 +304,6 @@ fn the_head_of_a_file_is_exact() {
322304 let mut checked = 0;
323305 for &(name, _, codec) in MATRIX {
324306 let path = fixtures().join(name);
325- if !path.exists() {
326- continue;
327- }
328307 let mut reader = Reader::open(&path).expect("open");
329308 let audio = reader
330309 .default_stream(MediaType::Audio)
@@ -370,6 +349,6 @@ fn the_head_of_a_file_is_exact() {
370349 }
371350 assert!(
372351 checked > 0,
373- "no fixtures found — run scripts/gen-fixtures.sh"
352+ "no fixtures found — run scripts/fixtures.sh"
374353 );
375354 }
crates/ec-riff/Cargo.tomlmodified+1 -0
@@ -11,5 +11,6 @@ ec-core.workspace = true
1111 ec-dv = { path = "../ec-dv", version = "0.1.0" }
1212
1313 [dev-dependencies]
14+ec-testkit.workspace = true
1415 ec-mjpeg.workspace = true
1516 ec-mp4.workspace = true
crates/ec-riff/fuzz/seed.shmodified+2 -2
@@ -11,8 +11,8 @@
1111 set -euo pipefail
1212
1313 FUZZ_DIR=$(cd -- "$(dirname -- "$0")" && pwd)
14-FIXTURES=$(cd -- "$FUZZ_DIR/../../.." && pwd)/fixtures/audio
15-[ -d "$FIXTURES" ] || { echo "seed.sh: $FIXTURES missing; run scripts/link-fixtures.sh" >&2; exit 2; }
14+FIXTURES=${EC_FIXTURES:-$(cd -- "$FUZZ_DIR/../../.." && pwd)/fixtures}/audio
15+[ -d "$FIXTURES" ] || { echo "seed.sh: $FIXTURES missing; run scripts/fixtures.sh" >&2; exit 2; }
1616
1717 WAVS=("$FIXTURES"/*.wav)
1818 [ -e "${WAVS[0]}" ] || { echo "seed.sh: no *.wav fixtures in $FIXTURES" >&2; exit 2; }
crates/ec-riff/tests/it/avi_raw_dv.rsmodified+2 -28
@@ -1,28 +1,14 @@
11 //! Uncompressed video in AVI and DV type-1 AVI (`iavs`). Media is synthetic, written by ffmpeg
22 //! at test time; ffmpeg cannot write type-1 AVI, so that wrapper is built here from a `.dv`
3-//! file. Without ffmpeg the tests skip unless `EC_REQUIRE_FIXTURES` is set.
43
54 use std::io::Cursor;
65 use std::path::PathBuf;
7-use std::process::Command;
86
97 use ec_core::frame::Frame;
108 use ec_core::registry::{CodecId, Decoder, Demuxer, MediaType, SeekMode};
119 use ec_core::{Error, Timestamp};
1210 use ec_riff::{AviDemuxer, RawVideoDecoder};
13-use crate::common::{ffmpeg, frame_bytes, tool_ok};
14-
15-fn oracle() -> bool {
16- if tool_ok("ffmpeg") {
17- return true;
18- }
19- assert!(
20- std::env::var_os("EC_REQUIRE_FIXTURES").is_none(),
21- "ffmpeg missing and EC_REQUIRE_FIXTURES is set"
22- );
23- eprintln!("SKIP: no ffmpeg");
24- false
25-}
11+use crate::common::{ffmpeg, frame_bytes};
2612
2713 fn scratch(tag: &str) -> PathBuf {
2814 let base = std::env::var_os("TMPDIR")
@@ -34,7 +20,7 @@ fn scratch(tag: &str) -> PathBuf {
3420 }
3521
3622 fn ffmpeg_out(args: &[&str]) -> Vec<u8> {
37- let o = Command::new("ffmpeg")
23+ let o = ec_testkit::ffmpeg()
3824 .args(["-v", "error", "-nostdin"])
3925 .args(args)
4026 .output()
@@ -104,9 +90,6 @@ fn expect_parity(path: &std::path::Path, bytes: Vec<u8>, ff_pix: &str) {
10490
10591 #[test]
10692 fn raw_rgb_and_yuv_match_ffmpeg() {
107- if !oracle() {
108- return;
109- }
11093 for (tag, size, pix, vtag, ff) in [
11194 ("bgr24", "98x66", "bgr24", None, "bgr24"),
11295 ("bgr24odd", "97x65", "bgr24", None, "bgr24"),
@@ -157,9 +140,6 @@ fn patch_chunks(bytes: &mut [u8], mut f: impl FnMut(&mut [u8])) {
157140
158141 #[test]
159142 fn both_row_orders_are_upright() {
160- if !oracle() {
161- return;
162- }
163143 let (path, bytes) = make_raw("topdown", "98x66", "bgr24", None);
164144 let mut td = bytes.clone();
165145 let strf = td.windows(4).position(|w| w == b"strf").unwrap() + 8;
@@ -363,17 +343,11 @@ fn dv_case(
363343
364344 #[test]
365345 fn dv_type1_pal_splits_video_and_audio() {
366- if !oracle() {
367- return;
368- }
369346 dv_case("dvpal", "720x576", "25", (1, 25), b"dvsd", "yuv420p");
370347 }
371348
372349 #[test]
373350 fn dv_type1_ntsc_splits_video_and_audio() {
374- if !oracle() {
375- return;
376- }
377351 dv_case(
378352 "dvntsc",
379353 "720x480",
crates/ec-riff/tests/it/avi_video.rsmodified+2 -46
@@ -1,31 +1,14 @@
11 //! AVI audio+video demuxer tests. Real files are synthetic, written by ffmpeg at test time and
22 //! checked against `ffprobe -show_packets`; the OpenDML, scan and vprp cases are hand-built
3-//! byte by byte. Without ffmpeg the ffmpeg-backed tests skip unless `EC_REQUIRE_FIXTURES` is set.
43
54 use std::io::Cursor;
65 use std::path::PathBuf;
7-use std::process::Command;
86
97 use ec_core::frame::{Interlace, VideoFrame};
108 use ec_core::registry::{CodecId, Demuxer, MediaType, SeekMode};
119 use ec_core::{Error, TimeBase, Timestamp};
1210 use ec_riff::{AviDemuxer, AviIndexKind, is_avi};
13-use crate::common::{chunk, ffmpeg, list, tool_ok};
14-
15-// ---------------------------------------------------------------------------------------------
16-// ffmpeg plumbing
17-
18-fn oracle() -> bool {
19- if tool_ok("ffmpeg") && tool_ok("ffprobe") {
20- return true;
21- }
22- assert!(
23- std::env::var_os("EC_REQUIRE_FIXTURES").is_none(),
24- "ffmpeg missing and EC_REQUIRE_FIXTURES is set"
25- );
26- eprintln!("SKIP: no ffmpeg");
27- false
28-}
11+use crate::common::{chunk, ffmpeg, list};
2912
3013 fn scratch(tag: &str) -> PathBuf {
3114 let base = std::env::var_os("TMPDIR")
@@ -62,7 +45,7 @@ struct Probe {
6245 }
6346
6447 fn probe(path: &PathBuf) -> Vec<Probe> {
65- let out = Command::new("ffprobe")
48+ let out = ec_testkit::ffprobe()
6649 .args(["-v", "error", "-show_packets", "-show_data_hash", "adler32", "-of", "compact=p=0"])
6750 .arg(path)
6851 .output()
@@ -162,9 +145,6 @@ fn assert_interleaved(got: &[Got]) {
162145
163146 #[test]
164147 fn mjpeg_pcm() {
165- if !oracle() {
166- return;
167- }
168148 let (path, bytes) = make("mjpeg-pcm", &["-c:v", "mjpeg", "-q:v", "3"], &["-c:a", "pcm_s16le"]);
169149 assert!(is_avi(&bytes));
170150 let mut d = AviDemuxer::new(Cursor::new(bytes.clone())).unwrap();
@@ -212,9 +192,6 @@ fn compare_video_only(path: &PathBuf, bytes: &[u8]) -> Vec<Got> {
212192
213193 #[test]
214194 fn mjpeg_mp3() {
215- if !oracle() {
216- return;
217- }
218195 let (path, bytes) = make("mjpeg-mp3", &["-c:v", "mjpeg"], &["-c:a", "libmp3lame"]);
219196 let d = AviDemuxer::new(Cursor::new(bytes.clone())).unwrap();
220197 assert_eq!(d.streams()[1].params.codec, CodecId::Mp3);
@@ -227,9 +204,6 @@ fn mjpeg_mp3() {
227204
228205 #[test]
229206 fn h264_no_bframes_aac() {
230- if !oracle() {
231- return;
232- }
233207 let (path, bytes) = make(
234208 "h264",
235209 &["-c:v", "libx264", "-bf", "0", "-g", "10", "-preset", "ultrafast"],
@@ -275,9 +249,6 @@ fn h264_no_bframes_aac() {
275249
276250 #[test]
277251 fn h264_bframes_decode_order() {
278- if !oracle() {
279- return;
280- }
281252 let (path, bytes) = make(
282253 "h264b",
283254 &["-c:v", "libx264", "-bf", "2", "-g", "12", "-preset", "ultrafast"],
@@ -294,9 +265,6 @@ fn h264_bframes_decode_order() {
294265
295266 #[test]
296267 fn mpeg2_mp2() {
297- if !oracle() {
298- return;
299- }
300268 let (path, bytes) = make("mpeg2", &["-c:v", "mpeg2video", "-g", "10", "-bf", "0"], &["-c:a", "mp2"]);
301269 let d = AviDemuxer::new(Cursor::new(bytes.clone())).unwrap();
302270 assert_eq!(d.streams()[0].params.codec, CodecId::Mpeg2Video);
@@ -307,9 +275,6 @@ fn mpeg2_mp2() {
307275
308276 #[test]
309277 fn raw_video_is_carried_and_unknown_layouts_refused_by_name() {
310- if !oracle() {
311- return;
312- }
313278 for (tag, fmt) in [("yuyv", "yuyv422"), ("bgr24", "bgr24")] {
314279 let (_, bytes) = make(tag, &["-c:v", "rawvideo", "-pix_fmt", fmt], &["-c:a", "pcm_s16le"]);
315280 let d = AviDemuxer::new(Cursor::new(bytes)).unwrap();
@@ -327,9 +292,6 @@ fn raw_video_is_carried_and_unknown_layouts_refused_by_name() {
327292
328293 #[test]
329294 fn mpeg4_part2_and_ms_mpeg4_fourccs_map() {
330- if !oracle() {
331- return;
332- }
333295 for tag in ["XVID", "xvid", "DIVX", "DX50", "FMP4", "mp4v"] {
334296 let path = scratch("mp4v").join(format!("v-{tag}.avi"));
335297 let mut args: Vec<&str> = Vec::new();
@@ -357,9 +319,6 @@ fn mpeg4_part2_and_ms_mpeg4_fourccs_map() {
357319
358320 #[test]
359321 fn truncated_file_without_idx1_scans() {
360- if !oracle() {
361- return;
362- }
363322 let (path, bytes) = make("trunc", &["-c:v", "mjpeg"], &["-c:a", "pcm_s16le"]);
364323 let full = compare_video_only(&path, &bytes);
365324 // Cut in the middle of movi: idx1 is gone, the RIFF and movi sizes lie.
@@ -381,9 +340,6 @@ fn truncated_file_without_idx1_scans() {
381340
382341 #[test]
383342 fn mjpeg_frames_decode_like_ffmpeg() {
384- if !oracle() {
385- return;
386- }
387343 let (path, bytes) = make("mjpeg-dec", &["-c:v", "mjpeg", "-q:v", "2"], &["-c:a", "pcm_s16le"]);
388344 let raw = scratch("mjpeg-dec").join("o.yuv");
389345 ffmpeg(&[
crates/ec-riff/tests/it/common.rsmodified+1 -10
@@ -1,6 +1,5 @@
11 //! Helpers shared by the integration-test modules in this binary.
22
3-use std::process::Command;
43
54 use ec_core::frame::VideoFrame;
65
@@ -20,16 +19,8 @@ pub(crate) fn list(kind: &[u8; 4], body: &[u8]) -> Vec<u8> {
2019 chunk(b"LIST", &b)
2120 }
2221
23-pub(crate) fn tool_ok(name: &str) -> bool {
24- Command::new(name)
25- .arg("-version")
26- .output()
27- .map(|o| o.status.success())
28- .unwrap_or(false)
29-}
30-
3122 pub(crate) fn ffmpeg(args: &[&str]) {
32- let ok = Command::new("ffmpeg")
23+ let ok = ec_testkit::ffmpeg()
3324 .args(["-v", "error", "-y", "-nostdin"])
3425 .args(args)
3526 .status()
crates/ec-riff/tests/it/dts.rsmodified+2 -10
@@ -1,7 +1,6 @@
11 //! DTS in AVI: the `0x2001` audio format tag is `CodecId::Dts`.
22
33 use std::io::Cursor;
4-use std::process::Command;
54
65 use ec_core::{CodecId, Demuxer, MediaParameters};
76 use ec_riff::AviDemuxer;
@@ -9,21 +8,14 @@ use ec_riff::AviDemuxer;
98 #[test]
109 fn avi_tag_0x2001_is_dts() {
1110 let out = std::env::temp_dir().join(format!("ec-riff-dts-{}.avi", std::process::id()));
12- let ok = Command::new("ffmpeg")
11+ let ok = ec_testkit::ffmpeg()
1312 .args(["-v", "error", "-y", "-f", "lavfi", "-i"])
1413 .arg("sine=frequency=440:sample_rate=48000:duration=0.5")
1514 .args(["-ac", "2", "-c:a", "dca", "-strict", "-2"])
1615 .arg(&out)
1716 .output()
1817 .is_ok_and(|o| o.status.success());
19- if !ok {
20- assert!(
21- std::env::var_os("EC_REQUIRE_FIXTURES").is_none_or(|v| v.is_empty() || v == "0"),
22- "ffmpeg cannot make a DTS avi"
23- );
24- eprintln!("skip: no ffmpeg with the dca encoder");
25- return;
26- }
18+ assert!(ok, "ffmpeg cannot make a DTS avi");
2719 let bytes = std::fs::read(&out).unwrap();
2820 let _ = std::fs::remove_file(out);
2921 let d = AviDemuxer::new(Cursor::new(bytes)).unwrap();
crates/ec-riff/tests/it/mov_raw.rsmodified+1 -24
@@ -1,32 +1,12 @@
11 //! Uncompressed video in QuickTime (`raw `, `2vuy`, `yuv2`, `v210`, `v410`, `b16g`), compared
2-//! with ffmpeg's decode of the same .mov. Media is synthetic. Without ffmpeg the tests skip
3-//! unless `EC_REQUIRE_FIXTURES` is set.
42
53 use std::path::PathBuf;
6-use std::process::Command;
74
85 use ec_core::frame::Frame;
96 use ec_core::registry::{CodecId, Decoder, Demuxer};
107 use ec_riff::RawVideoDecoder;
118 use crate::common::frame_bytes;
129
13-fn oracle() -> bool {
14- if Command::new("ffmpeg")
15- .arg("-version")
16- .output()
17- .map(|o| o.status.success())
18- .unwrap_or(false)
19- {
20- return true;
21- }
22- assert!(
23- std::env::var_os("EC_REQUIRE_FIXTURES").is_none(),
24- "ffmpeg missing and EC_REQUIRE_FIXTURES is set"
25- );
26- eprintln!("SKIP: no ffmpeg");
27- false
28-}
29-
3010 fn scratch(tag: &str) -> PathBuf {
3111 let base = std::env::var_os("TMPDIR")
3212 .map(PathBuf::from)
@@ -37,7 +17,7 @@ fn scratch(tag: &str) -> PathBuf {
3717 }
3818
3919 fn ffmpeg(args: &[&str]) -> Vec<u8> {
40- let o = Command::new("ffmpeg")
20+ let o = ec_testkit::ffmpeg()
4121 .args(["-v", "error", "-y", "-nostdin"])
4222 .args(args)
4323 .output()
@@ -52,9 +32,6 @@ fn ffmpeg(args: &[&str]) -> Vec<u8> {
5232
5333 #[test]
5434 fn mov_raw_layouts_match_ffmpeg() {
55- if !oracle() {
56- return;
57- }
5835 // (tag, size, ffmpeg codec, source pix_fmt, expected sample entry, pix_fmt we compare in)
5936 for (tag, size, codec, pix, entry, ff) in [
6037 ("rgb24", "98x66", "rawvideo", "rgb24", b"raw ", "rgb24"),
crates/ec-riff/tests/it/wav.rsmodified+2 -5
@@ -429,11 +429,8 @@ fn refusals_name_a_real_absence() {
429429
430430 #[test]
431431 fn reads_every_wav_fixture() {
432- let dir = concat!(env!("CARGO_MANIFEST_DIR"), "/../../fixtures/audio");
433- let Ok(entries) = std::fs::read_dir(dir) else {
434- eprintln!("fixtures/audio absent (gitignored) — skipping");
435- return;
436- };
432+ let entries = std::fs::read_dir(ec_testkit::root().join("audio"))
433+ .expect("fixtures/audio (run scripts/fixtures.sh)");
437434 let mut seen = 0;
438435 for e in entries.flatten() {
439436 let path = e.path();