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 = [
576 "ec-core",576 "ec-core",
577 "ec-inflate",577 "ec-inflate",
578 "ec-mp4",578 "ec-mp4",
579+ "ec-testkit",
579 ]580 ]
580 581
581 [[package]]582 [[package]]
@@ -604,6 +605,7 @@ name = "ec-mp4"
604 version = "0.1.0"605 version = "0.1.0"
605 dependencies = [606 dependencies = [
606 "ec-core",607 "ec-core",
608+ "ec-testkit",
607 ]609 ]
608 610
609 [[package]]611 [[package]]
@@ -633,6 +635,7 @@ dependencies = [
633 "ec-dvdsub",635 "ec-dvdsub",
634 "ec-h264-syntax",636 "ec-h264-syntax",
635 "ec-h265-syntax",637 "ec-h265-syntax",
638+ "ec-testkit",
636 "ec-truehd",639 "ec-truehd",
637 ]640 ]
638 641
@@ -641,6 +644,7 @@ name = "ec-ogg"
641 version = "0.1.0"644 version = "0.1.0"
642 dependencies = [645 dependencies = [
643 "ec-core",646 "ec-core",
647+ "ec-testkit",
644 ]648 ]
645 649
646 [[package]]650 [[package]]
@@ -691,6 +695,7 @@ dependencies = [
691 "ec-opus",695 "ec-opus",
692 "ec-pcm-ext",696 "ec-pcm-ext",
693 "ec-riff",697 "ec-riff",
698+ "ec-testkit",
694 "ec-truehd",699 "ec-truehd",
695 "ec-vorbis",700 "ec-vorbis",
696 ]701 ]
@@ -715,6 +720,7 @@ dependencies = [
715 "ec-dv",720 "ec-dv",
716 "ec-mjpeg",721 "ec-mjpeg",
717 "ec-mp4",722 "ec-mp4",
723+ "ec-testkit",
718 ]724 ]
719 725
720 [[package]]726 [[package]]
crates/ec-matroska/Cargo.tomlmodified+1 -0
@@ -11,6 +11,7 @@ ec-core.workspace = true
11 ec-inflate.workspace = true11 ec-inflate.workspace = true
12 12
13 [dev-dependencies]13 [dev-dependencies]
14+ec-testkit.workspace = true
14 ec-mp4.workspace = true15 ec-mp4.workspace = true
15 ec-aac.workspace = true16 ec-aac.workspace = true
16 ec-ac3.workspace = true17 ec-ac3.workspace = true
crates/ec-matroska/fuzz/seed.shmodified+5 -3
@@ -11,9 +11,11 @@
11 # Corpus lives under fuzz/corpus, which is git-ignored.11 # Corpus lives under fuzz/corpus, which is git-ignored.
12 set -euo pipefail12 set -euo pipefail
13 13
14+FF=${EC_FFMPEG:-$HOME/.cache/ec-ffmpeg/ffmpeg}
15+
14 FUZZ_DIR=$(cd -- "$(dirname -- "$0")" && pwd)16 FUZZ_DIR=$(cd -- "$(dirname -- "$0")" && pwd)
15-FIXTURES=$(cd -- "$FUZZ_DIR/../../.." && pwd)/fixtures17+FIXTURES=${EC_FIXTURES:-$(cd -- "$FUZZ_DIR/../../.." && pwd)/fixtures}
16-[ -d "$FIXTURES/audio" ] || { echo "seed.sh: $FIXTURES/audio missing; run scripts/link-fixtures.sh" >&2; exit 2; }18+[ -d "$FIXTURES/audio" ] || { echo "seed.sh: $FIXTURES/audio missing; run scripts/fixtures.sh" >&2; exit 2; }
17 19
18 OPEN_DIR="$FUZZ_DIR/corpus/open_tracks"20 OPEN_DIR="$FUZZ_DIR/corpus/open_tracks"
19 DEMUX_DIR="$FUZZ_DIR/corpus/demux_packets"21 DEMUX_DIR="$FUZZ_DIR/corpus/demux_packets"
@@ -32,7 +34,7 @@ for src in "$FIXTURES"/audio/*.mka "$FIXTURES"/audio/*.mkv "$FIXTURES"/video/*.m
32 if [ "$(stat -c %s "$src")" -le "$MAX" ]; then34 if [ "$(stat -c %s "$src")" -le "$MAX" ]; then
33 cp "$src" "$SCRATCH/$stem.mkv"35 cp "$src" "$SCRATCH/$stem.mkv"
34 else36 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"
36 fi38 fi
37 seed="$SCRATCH/$stem.mkv"39 seed="$SCRATCH/$stem.mkv"
38 size=$(stat -c %s "$seed")40 size=$(stat -c %s "$seed")
crates/ec-matroska/tests/dts.rsmodified+5 -16
@@ -4,23 +4,18 @@
4 4
5 use std::io::Cursor;5 use std::io::Cursor;
6 use std::path::PathBuf;6 use std::path::PathBuf;
7-use std::process::Command;
8 7
9 use ec_core::{CodecId, Demuxer, MediaParameters, Muxer};8 use ec_core::{CodecId, Demuxer, MediaParameters, Muxer};
10 use ec_matroska::{MatroskaDemuxer, MatroskaMuxer};9 use ec_matroska::{MatroskaDemuxer, MatroskaMuxer};
11 10
12-fn required() -> bool {
13- std::env::var_os("EC_REQUIRE_FIXTURES").is_some_and(|v| !v.is_empty() && v != "0")
14-}
15-
16 /// A DTS stream muxed by ffmpeg into `ext`'s container, plus the raw frames.11 /// 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>) {
18 let dir: PathBuf = std::env::temp_dir().join("ec-matroska-dts");13 let dir: PathBuf = std::env::temp_dir().join("ec-matroska-dts");
19 std::fs::create_dir_all(&dir).unwrap();14 std::fs::create_dir_all(&dir).unwrap();
20 let out = dir.join(format!("{}-{channels}.{ext}", std::process::id()));15 let out = dir.join(format!("{}-{channels}.{ext}", std::process::id()));
21 let raw = dir.join(format!("{}-{channels}.dts", std::process::id()));16 let raw = dir.join(format!("{}-{channels}.dts", std::process::id()));
22 let run = |args: &[&str]| {17 let run = |args: &[&str]| {
23- Command::new("ffmpeg")18+ ec_testkit::ffmpeg()
24 .args(["-v", "error", "-y"])19 .args(["-v", "error", "-y"])
25 .args(args)20 .args(args)
26 .output()21 .output()
@@ -45,15 +40,11 @@ fn ffmpeg_dts(ext: &str, channels: &str) -> Option<(Vec<u8>, Vec<u8>)> {
45 "copy",40 "copy",
46 raw.to_str().unwrap(),41 raw.to_str().unwrap(),
47 ]);42 ]);
48- if !ok {43+ assert!(ok, "ffmpeg cannot make a DTS fixture");
49- assert!(!required(), "ffmpeg cannot make a DTS fixture");
50- eprintln!("skip: no ffmpeg with the dca encoder");
51- return None;
52- }
53 let pair = (std::fs::read(&out).unwrap(), std::fs::read(&raw).unwrap());44 let pair = (std::fs::read(&out).unwrap(), std::fs::read(&raw).unwrap());
54 let _ = std::fs::remove_file(out);45 let _ = std::fs::remove_file(out);
55 let _ = std::fs::remove_file(raw);46 let _ = std::fs::remove_file(raw);
56- Some(pair)47+ pair
57 }48 }
58 49
59 fn demux_all(bytes: Vec<u8>) -> (MatroskaDemuxer<Cursor<Vec<u8>>>, Vec<ec_core::Packet>) {50 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::
66 }57 }
67 58
68 fn check(channels: &str, want: usize) {59 fn check(channels: &str, want: usize) {
69- let Some((mkv, raw)) = ffmpeg_dts("mkv", channels) else {60+ let (mkv, raw) = ffmpeg_dts("mkv", channels);
70- return;
71- };
72 let (d, pkts) = demux_all(mkv);61 let (d, pkts) = demux_all(mkv);
73 let s = &d.streams()[0];62 let s = &d.streams()[0];
74 assert_eq!(s.params.codec, CodecId::Dts);63 assert_eq!(s.params.codec, CodecId::Dts);
crates/ec-matroska/tests/field_order.rsmodified+7 -29
@@ -3,42 +3,27 @@
3 //! because ffmpeg's HEVC decoder cannot derive it from the bitstream and3 //! because ffmpeg's HEVC decoder cannot derive it from the bitstream and
4 //! reports `unknown` without them.4 //! reports `unknown` without them.
5 //!5 //!
6-//! Sources are synthetic (ffmpeg `testsrc2`). A case skips where ffmpeg lacks
7-//! the encoder, unless `EC_REQUIRE_FIXTURES` is set.
8 6
9 use std::fs::File;7 use std::fs::File;
10 use std::io::{BufReader, BufWriter};8 use std::io::{BufReader, BufWriter};
11 use std::path::{Path, PathBuf};9 use std::path::{Path, PathBuf};
12-use std::process::Command;
13 10
14 use ec_core::{Demuxer, Error, Interlace, Muxer, Packet, StreamInfo};11 use ec_core::{Demuxer, Error, Interlace, Muxer, Packet, StreamInfo};
15 use ec_matroska::{MatroskaDemuxer, MatroskaMuxer};12 use ec_matroska::{MatroskaDemuxer, MatroskaMuxer};
16 use ec_mp4::{Mp4Demuxer, Mp4Muxer};13 use ec_mp4::{Mp4Demuxer, Mp4Muxer};
17 14
18-fn skip(why: &str) -> bool {15+fn source(name: &str, encoder: &str) -> (PathBuf, Vec<StreamInfo>, Vec<Packet>) {
19- assert!(16+ let enc = ec_testkit::ffmpeg()
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")
29 .args(["-hide_banner", "-encoders"])17 .args(["-hide_banner", "-encoders"])
30 .output();18 .output();
31 let have =19 let have =
32 enc.is_ok_and(|o| String::from_utf8_lossy(&o.stdout).contains(&format!(" {encoder} ")));20 enc.is_ok_and(|o| String::from_utf8_lossy(&o.stdout).contains(&format!(" {encoder} ")));
33- if !have {21+ assert!(have, "ffmpeg has no {encoder} encoder");
34- skip(&format!("no ffmpeg or no {encoder}"));
35- return None;
36- }
37 let dir = std::env::temp_dir().join(format!("ec-field-order-{name}-{}", std::process::id()));22 let dir = std::env::temp_dir().join(format!("ec-field-order-{name}-{}", std::process::id()));
38 let _ = std::fs::remove_dir_all(&dir);23 let _ = std::fs::remove_dir_all(&dir);
39 std::fs::create_dir_all(&dir).unwrap();24 std::fs::create_dir_all(&dir).unwrap();
40 let src = dir.join("src.mp4");25 let src = dir.join("src.mp4");
41- let ok = Command::new("ffmpeg")26+ let ok = ec_testkit::ffmpeg()
42 .args(["-hide_banner", "-v", "error", "-y", "-f", "lavfi", "-i"])27 .args(["-hide_banner", "-v", "error", "-y", "-f", "lavfi", "-i"])
43 .arg("testsrc2=size=320x240:rate=25:duration=1")28 .arg("testsrc2=size=320x240:rate=25:duration=1")
44 .args(["-c:v", encoder, "-pix_fmt", "yuv420p", "-f", "mp4"])29 .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
56 Err(e) => panic!("{e}"),41 Err(e) => panic!("{e}"),
57 }42 }
58 }43 }
59- Some((dir, streams, packets))44+ (dir, streams, packets)
60 }45 }
61 46
62 fn mux_mp4(dst: &Path, s: &[StreamInfo], p: &[Packet], order: Option<Option<Interlace>>) {47 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
88 }73 }
89 74
90 fn probe(path: &Path) -> String {75 fn probe(path: &Path) -> String {
91- let out = Command::new("ffprobe")76+ let out = ec_testkit::ffprobe()
92 .args(["-v", "error", "-select_streams", "v:0", "-show_entries"])77 .args(["-v", "error", "-select_streams", "v:0", "-show_entries"])
93 .arg("stream=field_order")78 .arg("stream=field_order")
94 .args(["-of", "csv=p=0"])79 .args(["-of", "csv=p=0"])
@@ -111,14 +96,7 @@ fn mkv_order(path: &Path) -> Option<Interlace> {
111 }96 }
112 97
113 fn run(name: &str, encoder: &str, unstated: &str) {98 fn run(name: &str, encoder: &str, unstated: &str) {
114- let Some((dir, s, p)) = source(name, encoder) else {99+ let (dir, s, p) = source(name, encoder);
115- return;
116- };
117- let ffprobe = Command::new("ffprobe").arg("-version").output().is_ok();
118- if !ffprobe {
119- skip("no ffprobe");
120- return;
121- }
122 let cases = [100 let cases = [
123 (None, "progressive", Some(Interlace::Progressive)),101 (None, "progressive", Some(Interlace::Progressive)),
124 (102 (
crates/ec-matroska/tests/hdr_metadata.rsmodified+7 -14
@@ -5,7 +5,6 @@
5 use std::fs::File;5 use std::fs::File;
6 use std::io::{BufReader, BufWriter};6 use std::io::{BufReader, BufWriter};
7 use std::path::Path;7 use std::path::Path;
8-use std::process::Command;
9 8
10 use ec_core::{ContentLight, Demuxer, Error, MasteringPrimaries, Muxer, Packet, StreamInfo};9 use ec_core::{ContentLight, Demuxer, Error, MasteringPrimaries, Muxer, Packet, StreamInfo};
11 use ec_matroska::{MatroskaDemuxer, MatroskaMuxer};10 use ec_matroska::{MatroskaDemuxer, MatroskaMuxer};
@@ -45,23 +44,17 @@ fn mux(dst: &Path, s: &[StreamInfo], p: &[Packet], light: Option<ContentLight>)
45 44
46 #[test]45 #[test]
47 fn hevc_main10_mastering_metadata_in_mkv() {46 fn hevc_main10_mastering_metadata_in_mkv() {
48- let enc = Command::new("ffmpeg").args(["-hide_banner", "-encoders"]).output();47+ let enc = ec_testkit::ffmpeg().args(["-hide_banner", "-encoders"]).output();
49- if !enc.is_ok_and(|o| String::from_utf8_lossy(&o.stdout).contains(" libx265 "))48+ assert!(
50- || Command::new("ffprobe").arg("-version").output().is_err()49+ enc.is_ok_and(|o| String::from_utf8_lossy(&o.stdout).contains(" libx265 ")),
51- {50+ "ffmpeg has no libx265 encoder"
52- assert!(51+ );
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- }
59 let dir = std::env::temp_dir().join(format!("ec-mkv-hdr-{}", std::process::id()));52 let dir = std::env::temp_dir().join(format!("ec-mkv-hdr-{}", std::process::id()));
60 let _ = std::fs::remove_dir_all(&dir);53 let _ = std::fs::remove_dir_all(&dir);
61 std::fs::create_dir_all(&dir).unwrap();54 std::fs::create_dir_all(&dir).unwrap();
62 let src = dir.join("src.mp4");55 let src = dir.join("src.mp4");
63 assert!(56 assert!(
64- Command::new("ffmpeg")57+ ec_testkit::ffmpeg()
65 .args(["-v", "error", "-y", "-f", "lavfi", "-i", "testsrc2=size=320x240:rate=25:duration=1"])58 .args(["-v", "error", "-y", "-f", "lavfi", "-i", "testsrc2=size=320x240:rate=25:duration=1"])
66 .args(["-c:v", "libx265", "-pix_fmt", "yuv420p10le", "-tag:v", "hvc1"])59 .args(["-c:v", "libx265", "-pix_fmt", "yuv420p10le", "-tag:v", "hvc1"])
67 .args(["-x265-params", "log-level=error:colorprim=bt2020:transfer=smpte2084:colormatrix=bt2020nc"])60 .args(["-x265-params", "log-level=error:colorprim=bt2020:transfer=smpte2084:colormatrix=bt2020nc"])
@@ -89,7 +82,7 @@ fn hevc_main10_mastering_metadata_in_mkv() {
89 82
90 let dst = dir.join("hdr.mkv");83 let dst = dir.join("hdr.mkv");
91 mux(&dst, &streams, &packets, Some(light()));84 mux(&dst, &streams, &packets, Some(light()));
92- let out = Command::new("ffprobe")85+ let out = ec_testkit::ffprobe()
93 .args(["-v", "error", "-show_streams", "-show_frames", "-read_intervals", "%+#1", "-of", "json"])86 .args(["-v", "error", "-show_streams", "-show_frames", "-read_intervals", "%+#1", "-of", "json"])
94 .arg(&dst)87 .arg(&dst)
95 .output()88 .output()
crates/ec-matroska/tests/matroska.rsmodified+7 -790
@@ -6,10 +6,9 @@
6 use std::fs::File;6 use std::fs::File;
7 use std::io::{BufReader, Cursor};7 use std::io::{BufReader, Cursor};
8 use std::path::{Path, PathBuf};8 use std::path::{Path, PathBuf};
9-use std::process::Command;
10 9
11 use ec_core::{10 use ec_core::{
12- CodecId, Demuxer, Error, MediaParameters, MediaType, Muxer, Packet, SeekMode, StreamInfo,11+ CodecId, Demuxer, Error, MediaParameters, Muxer, Packet, SeekMode, StreamInfo,
13 TimeBase, Timestamp,12 TimeBase, Timestamp,
14 };13 };
15 use ec_matroska::{MatroskaDemuxer, MatroskaMuxer};14 use ec_matroska::{MatroskaDemuxer, MatroskaMuxer};
@@ -89,7 +88,7 @@ fn truehd_codec_id_round_trips_through_remux() {
89 }88 }
90 89
91 fn fixtures() -> PathBuf {90 fn fixtures() -> PathBuf {
92- Path::new(env!("CARGO_MANIFEST_DIR")).join("../../fixtures")91+ ec_testkit::root()
93 }92 }
94 93
95 fn work() -> PathBuf {94 fn work() -> PathBuf {
@@ -103,7 +102,7 @@ fn work() -> PathBuf {
103 /// this crate claims are exactly the ones that have to be exercised.102 /// this crate claims are exactly the ones that have to be exercised.
104 fn matroska_fixtures() -> Vec<PathBuf> {103 fn matroska_fixtures() -> Vec<PathBuf> {
105 let mut files: Vec<PathBuf> = std::fs::read_dir(fixtures().join("video"))104 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)")
107 .filter_map(|e| e.ok().map(|e| e.path()))106 .filter_map(|e| e.ok().map(|e| e.path()))
108 .filter(|p| {107 .filter(|p| {
109 let name = p.to_string_lossy();108 let name = p.to_string_lossy();
@@ -217,7 +216,7 @@ fn make_derived(dst: &Path, args: &[&str]) -> bool {
217 return true;216 return true;
218 }217 }
219 let tmp = dst.with_file_name(format!("tmp-{}-{name}", std::process::id()));218 let tmp = dst.with_file_name(format!("tmp-{}-{name}", std::process::id()));
220- let ok = Command::new("ffmpeg")219+ let ok = ec_testkit::ffmpeg()
221 .args(["-v", "error", "-y"])220 .args(["-v", "error", "-y"])
222 .args(args)221 .args(args)
223 .arg(&tmp)222 .arg(&tmp)
@@ -233,7 +232,7 @@ fn make_derived(dst: &Path, args: &[&str]) -> bool {
233 232
234 /// The fields a remux must not change, as ffprobe reads them back.233 /// The fields a remux must not change, as ffprobe reads them back.
235 fn probe(path: &Path) -> String {234 fn probe(path: &Path) -> String {
236- let out = Command::new("ffprobe")235+ let out = ec_testkit::ffprobe()
237 .args([236 .args([
238 "-v",237 "-v",
239 "error",238 "error",
@@ -256,7 +255,7 @@ fn probe(path: &Path) -> String {
256 }255 }
257 256
258 fn duration(path: &Path) -> f64 {257 fn duration(path: &Path) -> f64 {
259- let out = Command::new("ffprobe")258+ let out = ec_testkit::ffprobe()
260 .args([259 .args([
261 "-v",260 "-v",
262 "error",261 "error",
@@ -456,7 +455,7 @@ fn every_fixture_remuxes_into_a_file_ffprobe_and_ffmpeg_agree_with() {
456 a_seek_to_the_beginning_lands_on_the_first_packet(&dst);455 a_seek_to_the_beginning_lands_on_the_first_packet(&dst);
457 456
458 // ...and it decodes, which is the only claim a field compare cannot make.457 // ...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()
460 .args(["-v", "error", "-i"])459 .args(["-v", "error", "-i"])
461 .arg(&dst)460 .arg(&dst)
462 .args(["-f", "null", "-"])461 .args(["-f", "null", "-"])
@@ -556,178 +555,6 @@ fn a_hundred_random_seeks_land_at_or_before_their_target_on_one_reader() {
556 println!("{}", table.join("\n"));555 println!("{}", table.join("\n"));
557 }556 }
558 557
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-
731 /// A file whose *first* cluster holds only sound: seeking its audio track to558 /// A file whose *first* cluster holds only sound: seeking its audio track to
732 /// the beginning lands on that block, not on the first cue.559 /// the beginning lands on that block, not on the first cue.
733 ///560 ///
@@ -857,616 +684,6 @@ fn matroska_prefix_class(data: &[u8]) -> (&'static str, u64) {
857 }684 }
858 }685 }
859 686
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-
1470 /// An EBML element with its size written in eight bytes.687 /// An EBML element with its size written in eight bytes.
1471 fn ebml_el(id: &[u8], body: &[u8]) -> Vec<u8> {688 fn ebml_el(id: &[u8], body: &[u8]) -> Vec<u8> {
1472 let mut out = id.to_vec();689 let mut out = id.to_vec();
crates/ec-mp4/Cargo.tomlmodified+3 -0
@@ -8,3 +8,6 @@ authors.workspace = true
8 8
9 [dependencies]9 [dependencies]
10 ec-core.workspace = true10 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 @@
11 # Corpus lives under fuzz/corpus, which is git-ignored.11 # Corpus lives under fuzz/corpus, which is git-ignored.
12 set -euo pipefail12 set -euo pipefail
13 13
14+FF=${EC_FFMPEG:-$HOME/.cache/ec-ffmpeg/ffmpeg}
15+
14 FUZZ_DIR=$(cd -- "$(dirname -- "$0")" && pwd)16 FUZZ_DIR=$(cd -- "$(dirname -- "$0")" && pwd)
15-FIXTURES=$(cd -- "$FUZZ_DIR/../../.." && pwd)/fixtures17+FIXTURES=${EC_FIXTURES:-$(cd -- "$FUZZ_DIR/../../.." && pwd)/fixtures}
16-[ -d "$FIXTURES" ] || { echo "seed.sh: $FIXTURES missing; run scripts/link-fixtures.sh" >&2; exit 2; }18+[ -d "$FIXTURES" ] || { echo "seed.sh: $FIXTURES missing; run scripts/fixtures.sh" >&2; exit 2; }
17-command -v ffmpeg >/dev/null || { echo "seed.sh: ffmpeg needed for the small video seeds" >&2; exit 2; }19+[ -x "$FF" ] || { echo "seed.sh: ffmpeg needed for the small video seeds" >&2; exit 2; }
18 20
19 MP4_DIR="$FUZZ_DIR/corpus/demux_mp4"21 MP4_DIR="$FUZZ_DIR/corpus/demux_mp4"
20 ESDS_DIR="$FUZZ_DIR/corpus/esds_parse"22 ESDS_DIR="$FUZZ_DIR/corpus/esds_parse"
@@ -34,7 +36,7 @@ for src in "$FIXTURES"/audio/*.mp4 "$FIXTURES"/audio/*.m4a "$FIXTURES"/audio/*.m
34 # Shorten until it fits: a 4K intra frame alone can be most of a megabyte.36 # Shorten until it fits: a 4K intra frame alone can be most of a megabyte.
35 cut=""37 cut=""
36 for secs in 0.2 0.05 0.01; do38 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" \
38 || { echo "seed.sh: ffmpeg could not cut $src" >&2; exit 2; }40 || { echo "seed.sh: ffmpeg could not cut $src" >&2; exit 2; }
39 if [ "$(stat -c %s "$TMP/$stem.mp4")" -le "$LIMIT" ]; then cut=1; break; fi41 if [ "$(stat -c %s "$TMP/$stem.mp4")" -le "$LIMIT" ]; then cut=1; break; fi
40 done42 done
crates/ec-mp4/tests/data/gen.shmodified+6 -2
@@ -18,15 +18,19 @@
18 # Usage: crates/ec-mp4/tests/data/gen.sh18 # Usage: crates/ec-mp4/tests/data/gen.sh
19 set -euo pipefail19 set -euo pipefail
20 20
21+FF=${EC_FFMPEG:-$HOME/.cache/ec-ffmpeg/ffmpeg}
22+FP=$(dirname "$FF")/ffprobe
23+export FF FP
24+
21 here=$(cd -- "$(dirname -- "$0")" && pwd)25 here=$(cd -- "$(dirname -- "$0")" && pwd)
22 src=$(mktemp --suffix=.mp4)26 src=$(mktemp --suffix=.mp4)
23 trap 'rm -f -- "$src"' EXIT27 trap 'rm -f -- "$src"' EXIT
24 28
25-ffmpeg -nostdin -y -v error -f lavfi \29+"$FF" -nostdin -y -v error -f lavfi \
26 -i "testsrc2=size=320x240:rate=24:duration=1" \30 -i "testsrc2=size=320x240:rate=24:duration=1" \
27 -c:v libx264 -profile:v baseline -pix_fmt yuv420p "$src"31 -c:v libx264 -profile:v baseline -pix_fmt yuv420p "$src"
28 32
29 for deg in 0 90 180 270 45; do33 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" \
31 -c copy "$here/rot$deg.mp4"35 -c copy "$here/rot$deg.mp4"
32 done36 done
crates/ec-mp4/tests/it/chapters.rsmodified+2 -3
@@ -4,7 +4,6 @@
4 4
5 use std::io::Cursor;5 use std::io::Cursor;
6 use std::path::PathBuf;6 use std::path::PathBuf;
7-use std::process::Command;
8 7
9 use ec_core::{8 use ec_core::{
10 AudioParameters, Buf, ChannelLayout, CodecId, CodecParameters, Demuxer, MediaParameters, Muxer, Packet,9 AudioParameters, Buf, ChannelLayout, CodecId, CodecParameters, Demuxer, MediaParameters, Muxer, Packet,
@@ -43,11 +42,11 @@ fn ffprobe_chapters(bytes: &[u8], name: &str) -> Vec<(i64, String)> {
43 std::fs::create_dir_all(&dir).unwrap();42 std::fs::create_dir_all(&dir).unwrap();
44 let path: PathBuf = dir.join(name);43 let path: PathBuf = dir.join(name);
45 std::fs::write(&path, bytes).unwrap();44 std::fs::write(&path, bytes).unwrap();
46- let out = Command::new("ffprobe")45+ let out = ec_testkit::ffprobe()
47 .args(["-v", "error", "-show_chapters", "-of", "default"])46 .args(["-v", "error", "-show_chapters", "-of", "default"])
48 .arg(&path)47 .arg(&path)
49 .output()48 .output()
50- .expect("ffprobe on PATH");49+ .expect("ffprobe runs");
51 assert!(out.status.success(), "ffprobe failed: {:?}", out.stderr);50 assert!(out.status.success(), "ffprobe failed: {:?}", out.stderr);
52 let text = String::from_utf8_lossy(&out.stdout);51 let text = String::from_utf8_lossy(&out.stdout);
53 let mut chapters = Vec::new();52 let mut chapters = Vec::new();
crates/ec-mp4/tests/it/dts.rsmodified+6 -19
@@ -3,32 +3,23 @@
3 //! rate and channels the `ddts` box states; the writer round-trips `dtsc`.3 //! rate and channels the `ddts` box states; the writer round-trips `dtsc`.
4 4
5 use std::io::Cursor;5 use std::io::Cursor;
6-use std::process::Command;
7 6
8 use ec_core::{Buf, CodecId, Demuxer, MediaParameters, Muxer};7 use ec_core::{Buf, CodecId, Demuxer, MediaParameters, Muxer};
9 use ec_mp4::{Mp4Demuxer, Mp4Muxer};8 use ec_mp4::{Mp4Demuxer, Mp4Muxer};
10 9
11-fn required() -> bool {10+fn ffmpeg_mp4(tag: &str) -> Vec<u8> {
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>> {
16 let out = std::env::temp_dir().join(format!("ec-mp4-dts-{tag}-{}.mp4", std::process::id()));11 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()
18 .args(["-v", "error", "-y", "-f", "lavfi", "-i"])13 .args(["-v", "error", "-y", "-f", "lavfi", "-i"])
19 .arg("sine=frequency=440:sample_rate=48000:duration=0.5")14 .arg("sine=frequency=440:sample_rate=48000:duration=0.5")
20 .args(["-ac", "2", "-c:a", "dca", "-strict", "-2"])15 .args(["-ac", "2", "-c:a", "dca", "-strict", "-2"])
21 .arg(&out)16 .arg(&out)
22 .output()17 .output()
23 .is_ok_and(|o| o.status.success());18 .is_ok_and(|o| o.status.success());
24- if !ok {19+ assert!(ok, "ffmpeg cannot make a DTS mp4");
25- assert!(!required(), "ffmpeg cannot make a DTS mp4");
26- eprintln!("skip: no ffmpeg with the dca encoder");
27- return None;
28- }
29 let bytes = std::fs::read(&out).unwrap();20 let bytes = std::fs::read(&out).unwrap();
30 let _ = std::fs::remove_file(out);21 let _ = std::fs::remove_file(out);
31- Some(bytes)22+ bytes
32 }23 }
33 24
34 fn packets(d: &mut Mp4Demuxer<Cursor<Vec<u8>>>) -> Vec<ec_core::Packet> {25 fn packets(d: &mut Mp4Demuxer<Cursor<Vec<u8>>>) -> Vec<ec_core::Packet> {
@@ -56,9 +47,7 @@ fn ddts(rate: u32, mask: u16) -> Vec<u8> {
56 47
57 #[test]48 #[test]
58 fn ffmpeg_dts_in_mp4a_is_dts() {49 fn ffmpeg_dts_in_mp4a_is_dts() {
59- let Some(bytes) = ffmpeg_mp4("a") else {50+ let bytes = ffmpeg_mp4("a");
60- return;
61- };
62 let mut d = Mp4Demuxer::new(Cursor::new(bytes)).unwrap();51 let mut d = Mp4Demuxer::new(Cursor::new(bytes)).unwrap();
63 assert_eq!(d.streams()[0].params.codec, CodecId::Dts);52 assert_eq!(d.streams()[0].params.codec, CodecId::Dts);
64 assert_eq!(audio(&d), (48_000, 2));53 assert_eq!(audio(&d), (48_000, 2));
@@ -67,9 +56,7 @@ fn ffmpeg_dts_in_mp4a_is_dts() {
67 56
68 #[test]57 #[test]
69 fn dtsc_entry_round_trips_with_ddts_rate_and_channels() {58 fn dtsc_entry_round_trips_with_ddts_rate_and_channels() {
70- let Some(bytes) = ffmpeg_mp4("b") else {59+ let bytes = ffmpeg_mp4("b");
71- return;
72- };
73 let mut d = Mp4Demuxer::new(Cursor::new(bytes)).unwrap();60 let mut d = Mp4Demuxer::new(Cursor::new(bytes)).unwrap();
74 let pkts = packets(&mut d);61 let pkts = packets(&mut d);
75 let mut info = d.streams()[0].clone();62 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> {
50 muxer.into_inner().into_inner()50 muxer.into_inner().into_inner()
51 }51 }
52 52
53-/// The MD5 of `bytes`, from the `md5sum` tool. A missing tool skips the check.53+fn md5_of(bytes: &[u8]) -> String {
54-fn md5_of(bytes: &[u8]) -> Option<String> {
55 let dir = std::env::temp_dir().join("ec-mp4-edit-trim");54 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");
57 let path = dir.join(format!("md5-{}.mp4", std::process::id()));56 let path = dir.join(format!("md5-{}.mp4", std::process::id()));
58- std::fs::write(&path, bytes).ok()?;57+ std::fs::write(&path, bytes).expect("write");
59- let out = Command::new("md5sum").arg(&path).output().ok()?;58+ let out = Command::new("md5sum").arg(&path).output().expect("md5sum runs");
60 let _ = std::fs::remove_file(&path);59 let _ = std::fs::remove_file(&path);
61 String::from_utf8_lossy(&out.stdout)60 String::from_utf8_lossy(&out.stdout)
62 .split_whitespace()61 .split_whitespace()
63 .next()62 .next()
64- .map(str::to_string)63+ .expect("md5sum output")
64+ .to_string()
65 }65 }
66 66
67 /// Pinned before `set_edit` was added: the default output of the AAC priming67 /// Pinned before `set_edit` was added: the default output of the AAC priming
@@ -70,11 +70,11 @@ const DEFAULT_AAC_PRIMING_MD5: &str = "2ba0fd44a7dfa3b69cb60d7aceb71753";
70 70
71 #[test]71 #[test]
72 fn default_aac_priming_output_is_byte_identical() {72 fn default_aac_priming_output_is_byte_identical() {
73- let bytes = default_output();73+ assert_eq!(
74- match md5_of(&bytes) {74+ md5_of(&default_output()),
75- Some(sum) => assert_eq!(sum, DEFAULT_AAC_PRIMING_MD5, "default output changed"),75+ DEFAULT_AAC_PRIMING_MD5,
76- None => eprintln!("skip: md5sum is not installed"),76+ "default output changed"
77- }77+ );
78 }78 }
79 79
80 /// The big-endian `u32` at `offset` into the payload of the first `kind` box in80 /// 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> {
85 Some(u32::from_be_bytes([raw[0], raw[1], raw[2], raw[3]]))85 Some(u32::from_be_bytes([raw[0], raw[1], raw[2], raw[3]]))
86 }86 }
87 87
88-/// `key=value` lines from `ffprobe`, keyed by name. `None` where ffprobe is not88+fn ffprobe_fields(path: &Path, select: &str, entries: &str) -> Vec<(String, String)> {
89-/// installed, which skips the check.89+ let out = ec_testkit::ffprobe()
90-fn ffprobe_fields(path: &Path, select: &str, entries: &str) -> Option<Vec<(String, String)>> {
91- let out = Command::new("ffprobe")
92 .args([90 .args([
93 "-v",91 "-v",
94 "error",92 "error",
@@ -100,14 +98,12 @@ fn ffprobe_fields(path: &Path, select: &str, entries: &str) -> Option<Vec<(Strin
100 .args(["-of", "default=nw=1"])98 .args(["-of", "default=nw=1"])
101 .arg(path)99 .arg(path)
102 .output()100 .output()
103- .ok()?;101+ .expect("ffprobe runs");
104- let text = String::from_utf8_lossy(&out.stdout);102+ String::from_utf8_lossy(&out.stdout)
105- Some(103+ .lines()
106- text.lines()104+ .filter_map(|line| line.split_once('='))
107- .filter_map(|line| line.split_once('='))105+ .map(|(k, v)| (k.to_string(), v.to_string()))
108- .map(|(k, v)| (k.to_string(), v.to_string()))106+ .collect()
109- .collect(),
110- )
111 }107 }
112 108
113 fn field(fields: &[(String, String)], key: &str) -> f64 {109 fn field(fields: &[(String, String)], key: &str) -> f64 {
@@ -164,20 +160,15 @@ fn set_edit_trims_the_audio_edit_to_its_stated_length() {
164 .join(format!("trim-{}.mp4", std::process::id()));160 .join(format!("trim-{}.mp4", std::process::id()));
165 std::fs::create_dir_all(path.parent().expect("dir")).expect("work dir");161 std::fs::create_dir_all(path.parent().expect("dir")).expect("work dir");
166 std::fs::write(&path, &bytes).expect("write");162 std::fs::write(&path, &bytes).expect("write");
167- let stream_fields = ffprobe_fields(&path, "a:0", "stream=start_time,duration");163+ let fields = ffprobe_fields(&path, "a:0", "stream=start_time,duration");
168- if let Some(fields) = stream_fields {164+ let frame = 1024.0 / 48_000.0;
169- let frame = 1024.0 / 48_000.0;165+ let want = f64::from(PICTURE) / 48_000.0;
170- let want = f64::from(PICTURE) / 48_000.0;166+ let duration = field(&fields, "duration");
171- let duration = field(&fields, "duration");167+ let start = field(&fields, "start_time");
172- let start = field(&fields, "start_time");168+ assert!(
173- eprintln!("ffprobe a:0 start_time {start} duration {duration} (picture {want})");169+ (duration - want).abs() <= frame,
174- assert!(170+ "stream duration {duration} against the picture's {want}"
175- (duration - want).abs() <= frame,171+ );
176- "stream duration {duration} against the picture's {want}"172+ assert!(start.abs() < 1e-6, "start_time {start} is not zero");
177- );
178- assert!(start.abs() < 1e-6, "start_time {start} is not zero");
179- } else {
180- eprintln!("skip ffprobe: not installed");
181- }
182 let _ = std::fs::remove_file(&path);173 let _ = std::fs::remove_file(&path);
183 }174 }
crates/ec-mp4/tests/it/edith_parity.rsmodified+6 -44
@@ -3,15 +3,6 @@
3 //! for field. This is the swap criterion for edith's `mp4::` demuxer: identical3 //! for field. This is the swap criterion for edith's `mp4::` demuxer: identical
4 //! packet bytes, identical timestamps, identical stream metadata.4 //! packet bytes, identical timestamps, identical stream metadata.
5 //!5 //!
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.
15 //!6 //!
16 //! Per track, the comparison is: codec, coded size, sample rate, channels,7 //! Per track, the comparison is: codec, coded size, sample rate, channels,
17 //! timebase, rotation, and per sample the byte offset, size, presentation time8 //! timebase, rotation, and per sample the byte offset, size, presentation time
@@ -29,7 +20,6 @@ use std::collections::HashMap;
29 use std::fs::File;20 use std::fs::File;
30 use std::io::BufReader;21 use std::io::BufReader;
31 use std::path::{Path, PathBuf};22 use std::path::{Path, PathBuf};
32-use std::process::Command;
33 23
34 use ec_core::{CodecId, Demuxer, MediaParameters};24 use ec_core::{CodecId, Demuxer, MediaParameters};
35 use ec_mp4::{Mp4Demuxer, Sample};25 use ec_mp4::{Mp4Demuxer, Sample};
@@ -58,7 +48,7 @@ fn records(text: &str, first: &str) -> Vec<Record> {
58 }48 }
59 49
60 fn ffprobe(path: &Path, entries: &str, first: &str) -> Vec<Record> {50 fn ffprobe(path: &Path, entries: &str, first: &str) -> Vec<Record> {
61- let out = Command::new("ffprobe")51+ let out = ec_testkit::ffprobe()
62 .args(["-v", "error", "-show_entries", entries, "-of", "default=nw=1"])52 .args(["-v", "error", "-show_entries", entries, "-of", "default=nw=1"])
63 .arg(path)53 .arg(path)
64 .output()54 .output()
@@ -129,7 +119,7 @@ fn probe_streams(path: &Path, rotations: &HashMap<u32, i32>) -> Vec<ProbeStream>
129 /// stream dump. The `side_data=rotation` entry query is not used: on a 2 GB film119 /// stream dump. The `side_data=rotation` entry query is not used: on a 2 GB film
130 /// ffprobe spends minutes decoding for it, while the JSON dump is immediate.120 /// ffprobe spends minutes decoding for it, while the JSON dump is immediate.
131 fn rotations(path: &Path) -> HashMap<u32, i32> {121 fn rotations(path: &Path) -> HashMap<u32, i32> {
132- let out = Command::new("ffprobe")122+ let out = ec_testkit::ffprobe()
133 .args(["-v", "error", "-show_streams", "-of", "json"])123 .args(["-v", "error", "-show_streams", "-of", "json"])
134 .arg(path)124 .arg(path)
135 .output()125 .output()
@@ -354,33 +344,7 @@ fn collect(dir: &Path, files: &mut Vec<PathBuf>) {
354 344
355 fn corpus() -> Vec<PathBuf> {345 fn corpus() -> Vec<PathBuf> {
356 let mut files = Vec::new();346 let mut files = Vec::new();
357- collect(&Path::new(env!("CARGO_MANIFEST_DIR")).join("../../fixtures"), &mut files);347+ collect(&ec_testkit::root().join("mp4corpus"), &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- }
384 files.sort();348 files.sort();
385 files.dedup();349 files.dedup();
386 files350 files
@@ -389,7 +353,7 @@ fn corpus() -> Vec<PathBuf> {
389 #[test]353 #[test]
390 fn every_corpus_file_matches_ffprobe_sample_for_sample() {354 fn every_corpus_file_matches_ffprobe_sample_for_sample() {
391 let files = corpus();355 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");
393 let mut report = Vec::new();357 let mut report = Vec::new();
394 let mut failures = Vec::new();358 let mut failures = Vec::new();
395 for path in &files {359 for path in &files {
@@ -415,16 +379,14 @@ fn every_corpus_file_matches_ffprobe_sample_for_sample() {
415 /// order.379 /// order.
416 #[test]380 #[test]
417 fn edith_trim_and_display_order_read_the_known_fixtures() {381 fn edith_trim_and_display_order_read_the_known_fixtures() {
418- let aac = Path::new(env!("CARGO_MANIFEST_DIR"))382+ let aac = ec_testkit::fixture("audio/aac-mp4-stereo-48000.mp4");
419- .join("../../fixtures/audio/aac-mp4-stereo-48000.mp4");
420 let demuxer = Mp4Demuxer::new(BufReader::new(File::open(&aac).expect("fixture")))383 let demuxer = Mp4Demuxer::new(BufReader::new(File::open(&aac).expect("fixture")))
421 .expect("the fixture demuxes");384 .expect("the fixture demuxes");
422 assert_eq!(demuxer.presentation_trim(0), Some(1024));385 assert_eq!(demuxer.presentation_trim(0), Some(1024));
423 assert_eq!(demuxer.first_frame_sample(0), 2, "the trim lands on packet 2");386 assert_eq!(demuxer.first_frame_sample(0), 2, "the trim lands on packet 2");
424 assert!(demuxer.sync_in_display_order(0).is_empty(), "no ctts, no reorder");387 assert!(demuxer.sync_in_display_order(0).is_empty(), "no ctts, no reorder");
425 388
426- let gop = Path::new(env!("CARGO_MANIFEST_DIR"))389+ let gop = ec_testkit::fixture("video/h264-open-gop.mp4");
427- .join("../../fixtures/video/h264-open-gop.mp4");
428 let demuxer = Mp4Demuxer::new(BufReader::new(File::open(&gop).expect("fixture")))390 let demuxer = Mp4Demuxer::new(BufReader::new(File::open(&gop).expect("fixture")))
429 .expect("the fixture demuxes");391 .expect("the fixture demuxes");
430 let syncs = demuxer.sync_in_display_order(0);392 let syncs = demuxer.sync_in_display_order(0);
crates/ec-mp4/tests/it/mp4.rsmodified+10 -168
@@ -7,7 +7,6 @@
7 use std::fs::File;7 use std::fs::File;
8 use std::io::{BufReader, BufWriter, Cursor};8 use std::io::{BufReader, BufWriter, Cursor};
9 use std::path::{Path, PathBuf};9 use std::path::{Path, PathBuf};
10-use std::process::Command;
11 10
12 use ec_core::{11 use ec_core::{
13 Buf, CodecId, Demuxer, Error, MediaParameters, Muxer, Packet, SeekMode, StreamInfo, TimeBase,12 Buf, CodecId, Demuxer, Error, MediaParameters, Muxer, Packet, SeekMode, StreamInfo, TimeBase,
@@ -18,7 +17,7 @@ use ec_mp4::{Mp4Demuxer, Mp4Muxer};
18 use crate::common::ffmpeg_name;17 use crate::common::ffmpeg_name;
19 18
20 fn fixtures() -> PathBuf {19 fn fixtures() -> PathBuf {
21- Path::new(env!("CARGO_MANIFEST_DIR")).join("../../fixtures")20+ ec_testkit::root()
22 }21 }
23 22
24 fn work() -> PathBuf {23 fn work() -> PathBuf {
@@ -48,7 +47,7 @@ fn riff_avi_is_not_reported_as_a_truncated_mp4() {
48 47
49 /// One ffprobe field per stream, in stream order.48 /// One ffprobe field per stream, in stream order.
50 fn probe_field(path: &Path, entries: &str) -> Vec<String> {49 fn probe_field(path: &Path, entries: &str) -> Vec<String> {
51- let out = Command::new("ffprobe")50+ let out = ec_testkit::ffprobe()
52 .args(["-v", "error", "-show_entries", entries, "-of", "csv=p=0"])51 .args(["-v", "error", "-show_entries", entries, "-of", "csv=p=0"])
53 .arg(path)52 .arg(path)
54 .output()53 .output()
@@ -111,7 +110,7 @@ fn mp4_fixtures() -> Vec<PathBuf> {
111 .iter()110 .iter()
112 .flat_map(|dir| {111 .flat_map(|dir| {
113 std::fs::read_dir(fixtures().join(dir))112 std::fs::read_dir(fixtures().join(dir))
114- .expect("fixtures (run scripts/gen-fixtures.sh)")113+ .expect("fixtures (run scripts/fixtures.sh)")
115 .filter_map(|e| e.ok().map(|e| e.path()))114 .filter_map(|e| e.ok().map(|e| e.path()))
116 })115 })
117 .filter(|p| {116 .filter(|p| {
@@ -185,7 +184,7 @@ fn make_derived(dst: &Path, args: &[&str]) -> bool {
185 return true;184 return true;
186 }185 }
187 let tmp = dst.with_file_name(format!("tmp-{}-{name}", std::process::id()));186 let tmp = dst.with_file_name(format!("tmp-{}-{name}", std::process::id()));
188- let ok = Command::new("ffmpeg")187+ let ok = ec_testkit::ffmpeg()
189 .args(["-v", "error", "-y"])188 .args(["-v", "error", "-y"])
190 .args(args)189 .args(args)
191 .arg(&tmp)190 .arg(&tmp)
@@ -326,7 +325,7 @@ fn every_fixture_remuxes_into_a_file_ffprobe_and_ffmpeg_agree_with() {
326 );325 );
327 326
328 // ...and it decodes, which is the only claim a field compare cannot make.327 // ...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()
330 .args(["-v", "error", "-i"])329 .args(["-v", "error", "-i"])
331 .arg(&dst)330 .arg(&dst)
332 .args(["-f", "null", "-"])331 .args(["-f", "null", "-"])
@@ -411,7 +410,7 @@ fn the_hand_written_extensions_come_out_as_ffprobe_reads_them() {
411 "colr nclx read back"410 "colr nclx read back"
412 );411 );
413 let side = String::from_utf8_lossy(412 let side = String::from_utf8_lossy(
414- &Command::new("ffprobe")413+ &ec_testkit::ffprobe()
415 .args(["-v", "error", "-show_streams", "-of", "json"])414 .args(["-v", "error", "-show_streams", "-of", "json"])
416 .arg(&dst)415 .arg(&dst)
417 .output()416 .output()
@@ -470,7 +469,7 @@ fn the_hand_written_extensions_come_out_as_ffprobe_reads_them() {
470 assert_eq!(probe_field(&dst, "stream=codec_name"), vec!["mov_text"]);469 assert_eq!(probe_field(&dst, "stream=codec_name"), vec!["mov_text"]);
471 assert_eq!(probe_field(&dst, "stream_tags=language"), vec!["tur"]);470 assert_eq!(probe_field(&dst, "stream_tags=language"), vec!["tur"]);
472 let text = String::from_utf8_lossy(471 let text = String::from_utf8_lossy(
473- &Command::new("ffmpeg")472+ &ec_testkit::ffmpeg()
474 .args(["-v", "error", "-i"])473 .args(["-v", "error", "-i"])
475 .arg(&dst)474 .arg(&dst)
476 .args(["-f", "srt", "-"])475 .args(["-f", "srt", "-"])
@@ -527,7 +526,7 @@ fn an_aac_tracks_audio_specific_config_survives_as_bytes() {
527 fn a_non_aac_mp4a_entry_is_not_dropped() {526 fn a_non_aac_mp4a_entry_is_not_dropped() {
528 let dst = work().join("mp3-in-mp4.mp4");527 let dst = work().join("mp3-in-mp4.mp4");
529 let src = fixtures().join("audio/mp3-stereo-44100.mp3");528 let src = fixtures().join("audio/mp3-stereo-44100.mp3");
530- let ok = Command::new("ffmpeg")529+ let ok = ec_testkit::ffmpeg()
531 .args(["-v", "error", "-y", "-i"])530 .args(["-v", "error", "-y", "-i"])
532 .arg(&src)531 .arg(&src)
533 .args(["-c", "copy"])532 .args(["-c", "copy"])
@@ -653,11 +652,7 @@ fn a_truncated_file_is_need_more() {
653 652
654 #[test]653 #[test]
655 fn truncated_prefixes_are_need_more_or_eof() {654 fn truncated_prefixes_are_need_more_or_eof() {
656- let mut paths = vec![fixtures().join("audio/aac-mp4-stereo-48000.mp4")];655+ let paths = [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- }
661 656
662 for path in paths {657 for path in paths {
663 let data = std::fs::read(&path).unwrap_or_else(|e| panic!("{}: {e}", path.display()));658 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() {
789 );784 );
790 }785 }
791 786
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-
900 fn name_of(path: &Path) -> String {787 fn name_of(path: &Path) -> String {
901 let name = path.file_name().unwrap_or_default().to_string_lossy();788 let name = path.file_name().unwrap_or_default().to_string_lossy();
902 name.chars().take(56).collect()789 name.chars().take(56).collect()
@@ -905,7 +792,7 @@ fn name_of(path: &Path) -> String {
905 /// The extradata ffprobe reads out of a stream, as bytes: its `-show_data`792 /// The extradata ffprobe reads out of a stream, as bytes: its `-show_data`
906 /// hexdump, which is the only place it prints the octets themselves.793 /// hexdump, which is the only place it prints the octets themselves.
907 fn probe_extradata(path: &Path, stream: &str) -> Vec<u8> {794 fn probe_extradata(path: &Path, stream: &str) -> Vec<u8> {
908- let out = Command::new("ffprobe")795+ let out = ec_testkit::ffprobe()
909 .args([796 .args([
910 "-v",797 "-v",
911 "error",798 "error",
@@ -992,51 +879,6 @@ fn quicktime_sound_description_states_its_esds_inside_wave() {
992 assert_eq!(got, iso_extra, "QuickTime and ISO read different extradata");879 assert_eq!(got, iso_extra, "QuickTime and ISO read different extradata");
993 }880 }
994 881
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-
1040 /// A box with a four-character type and its payload, sized the way ISOBMFF sizes it.882 /// A box with a four-character type and its payload, sized the way ISOBMFF sizes it.
1041 fn boxed(kind: &[u8; 4], payload: &[u8]) -> Vec<u8> {883 fn boxed(kind: &[u8; 4], payload: &[u8]) -> Vec<u8> {
1042 let mut out = ((payload.len() + 8) as u32).to_be_bytes().to_vec();884 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 @@
4 //! our file to the same samples as the source, since the packets are the same4 //! our file to the same samples as the source, since the packets are the same
5 //! bytes. This crate's own demuxer reads our file back to the same packets with5 //! bytes. This crate's own demuxer reads our file back to the same packets with
6 //! the same timestamps and keyframe flags.6 //! 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.
10 7
11 use std::fs::File;8 use std::fs::File;
12 use std::io::{BufReader, BufWriter};9 use std::io::{BufReader, BufWriter};
13 use std::path::{Path, PathBuf};10 use std::path::{Path, PathBuf};
14-use std::process::Command;
15 11
16 use ec_core::{Demuxer, Error, Muxer, Packet};12 use ec_core::{Demuxer, Error, Muxer, Packet};
17 use ec_mp4::{Mp4Demuxer, Mp4Muxer};13 use ec_mp4::{Mp4Demuxer, Mp4Muxer};
@@ -197,33 +193,21 @@ fn work(case: &Case) -> PathBuf {
197 dir193 dir
198 }194 }
199 195
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-
208 /// Whether ffmpeg was built with `encoder`.196 /// Whether ffmpeg was built with `encoder`.
209 fn has_encoder(encoder: &str) -> bool {197 fn has_encoder(encoder: &str) -> bool {
210- Command::new("ffmpeg")198+ ec_testkit::ffmpeg()
211 .args(["-hide_banner", "-encoders"])199 .args(["-hide_banner", "-encoders"])
212 .output()200 .output()
213 .is_ok_and(|o| String::from_utf8_lossy(&o.stdout).contains(&format!(" {encoder} ")))201 .is_ok_and(|o| String::from_utf8_lossy(&o.stdout).contains(&format!(" {encoder} ")))
214 }202 }
215 203
216-/// Makes the source for `case` at `path`, or says why it cannot. `false` is a204+fn make_source(case: &Case, path: &Path) {
217-/// skip.205+ assert!(
218-fn make_source(case: &Case, path: &Path) -> bool {206+ has_encoder(case.encoder),
219- if !has_encoder(case.encoder) {207+ "ffmpeg has no {} encoder",
220- eprintln!(208+ case.encoder
221- "skip {}: ffmpeg has no {} encoder",209+ );
222- case.entry, case.encoder210+ let ok = ec_testkit::ffmpeg()
223- );
224- return false;
225- }
226- let ok = Command::new("ffmpeg")
227 .args(["-hide_banner", "-v", "error", "-y"])211 .args(["-hide_banner", "-v", "error", "-y"])
228 .args(case.args)212 .args(case.args)
229 .args(["-f", "mp4"])213 .args(["-f", "mp4"])
@@ -232,7 +216,6 @@ fn make_source(case: &Case, path: &Path) -> bool {
232 .expect("ffmpeg runs")216 .expect("ffmpeg runs")
233 .success();217 .success();
234 assert!(ok, "ffmpeg could not make the {} source", case.entry);218 assert!(ok, "ffmpeg could not make the {} source", case.entry);
235- true
236 }219 }
237 220
238 /// Every packet of `path`, and the streams it declares.221 /// Every packet of `path`, and the streams it declares.
@@ -306,7 +289,7 @@ fn remux(src: &Path, dst: &Path) {
306 289
307 /// ffprobe's stderr for `path`, with the full-decode check ffmpeg runs over it.290 /// ffprobe's stderr for `path`, with the full-decode check ffmpeg runs over it.
308 fn ffprobe_stderr(path: &Path) -> String {291 fn ffprobe_stderr(path: &Path) -> String {
309- let out = Command::new("ffprobe")292+ let out = ec_testkit::ffprobe()
310 .args(["-v", "error", "-show_streams", "-show_format"])293 .args(["-v", "error", "-show_streams", "-show_format"])
311 .arg(path)294 .arg(path)
312 .output()295 .output()
@@ -316,7 +299,7 @@ fn ffprobe_stderr(path: &Path) -> String {
316 299
317 /// One ffprobe CSV field list per stream, for `entries` (`stream=...`).300 /// One ffprobe CSV field list per stream, for `entries` (`stream=...`).
318 fn probe_lines(path: &Path, entries: &str) -> Vec<String> {301 fn probe_lines(path: &Path, entries: &str) -> Vec<String> {
319- let out = Command::new("ffprobe")302+ let out = ec_testkit::ffprobe()
320 .args(["-v", "error", "-show_entries", entries, "-of", "csv=p=0"])303 .args(["-v", "error", "-show_entries", entries, "-of", "csv=p=0"])
321 .arg(path)304 .arg(path)
322 .output()305 .output()
@@ -339,7 +322,7 @@ fn duration(path: &Path) -> f64 {
339 /// `MD5=...`. Any stderr from the decode is returned too: a clean file says322 /// `MD5=...`. Any stderr from the decode is returned too: a clean file says
340 /// nothing.323 /// nothing.
341 fn decoded_md5(path: &Path, map: &str) -> (String, String) {324 fn decoded_md5(path: &Path, map: &str) -> (String, String) {
342- let out = Command::new("ffmpeg")325+ let out = ec_testkit::ffmpeg()
343 .args(["-hide_banner", "-v", "error", "-i"])326 .args(["-hide_banner", "-v", "error", "-i"])
344 .arg(path)327 .arg(path)
345 .args(["-map", map, "-f", "md5", "-"])328 .args(["-map", map, "-f", "md5", "-"])
@@ -352,16 +335,10 @@ fn decoded_md5(path: &Path, map: &str) -> (String, String) {
352 }335 }
353 336
354 fn run_case(case: &Case) {337 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- }
359 let dir = work(case);338 let dir = work(case);
360 let src = dir.join("source.mp4");339 let src = dir.join("source.mp4");
361 let out = dir.join("ours.mp4");340 let out = dir.join("ours.mp4");
362- if !make_source(case, &src) {341+ make_source(case, &src);
363- return;
364- }
365 remux(&src, &out);342 remux(&src, &out);
366 343
367 // (a) ffprobe reads our file cleanly and states what the source states.344 // (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() {
468 #[test]445 #[test]
469 fn opus_pre_skip_is_written_without_a_caller_asking() {446 fn opus_pre_skip_is_written_without_a_caller_asking() {
470 let case = &CASES[7];447 let case = &CASES[7];
471- if !have("ffmpeg") || !have("ffprobe") {
472- eprintln!("skip {}: ffmpeg or ffprobe is not installed", case.entry);
473- return;
474- }
475 let dir = work(case);448 let dir = work(case);
476 let src = dir.join("source.mp4");449 let src = dir.join("source.mp4");
477 let out = dir.join("bare.mp4");450 let out = dir.join("bare.mp4");
478- if !make_source(case, &src) {451+ make_source(case, &src);
479- return;
480- }
481 let (streams, packets) = read_all(&src);452 let (streams, packets) = read_all(&src);
482 let shifts = Vec::new();453 let shifts = Vec::new();
483 write_out(&out, &streams, &packets, &shifts, false);454 write_out(&out, &streams, &packets, &shifts, false);
@@ -500,16 +471,10 @@ fn opus_pre_skip_is_written_without_a_caller_asking() {
500 #[test]471 #[test]
501 fn alac_bare_cookie_is_written_inside_an_alac_box() {472 fn alac_bare_cookie_is_written_inside_an_alac_box() {
502 let case = &CASES[6];473 let case = &CASES[6];
503- if !have("ffmpeg") || !have("ffprobe") {
504- eprintln!("skip {}: ffmpeg or ffprobe is not installed", case.entry);
505- return;
506- }
507 let dir = work(case);474 let dir = work(case);
508 let src = dir.join("source.mp4");475 let src = dir.join("source.mp4");
509 let out = dir.join("bare-cookie.mp4");476 let out = dir.join("bare-cookie.mp4");
510- if !make_source(case, &src) {477+ make_source(case, &src);
511- return;
512- }
513 let (mut streams, packets) = read_all(&src);478 let (mut streams, packets) = read_all(&src);
514 let boxed = streams[0]479 let boxed = streams[0]
515 .params480 .params
crates/ec-mp4/tests/it/prores_entries.rsmodified+3 -9
@@ -1,17 +1,14 @@
1 //! The ProRes sample entries (`apco apcs apcn apch ap4h ap4x`) read as `CodecId::ProRes`. Each1 //! 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.
4 2
5 use std::fs::File;3 use std::fs::File;
6 use std::io::BufReader;4 use std::io::BufReader;
7-use std::process::Command;
8 5
9 use ec_core::registry::CodecId;6 use ec_core::registry::CodecId;
10 use ec_core::Demuxer;7 use ec_core::Demuxer;
11 use ec_mp4::Mp4Demuxer;8 use ec_mp4::Mp4Demuxer;
12 9
13 fn has_prores_ks() -> bool {10 fn has_prores_ks() -> bool {
14- Command::new("ffmpeg")11+ ec_testkit::ffmpeg()
15 .args(["-hide_banner", "-encoders"])12 .args(["-hide_banner", "-encoders"])
16 .output()13 .output()
17 .map(|o| String::from_utf8_lossy(&o.stdout).contains("prores_ks"))14 .map(|o| String::from_utf8_lossy(&o.stdout).contains("prores_ks"))
@@ -20,10 +17,7 @@ fn has_prores_ks() -> bool {
20 17
21 #[test]18 #[test]
22 fn prores_fourccs_are_recognised() {19 fn prores_fourccs_are_recognised() {
23- if !has_prores_ks() {20+ assert!(has_prores_ks(), "ffmpeg prores_ks required");
24- assert!(std::env::var_os("EC_REQUIRE_FIXTURES").is_none(), "ffmpeg prores_ks required");
25- return;
26- }
27 let dir = std::env::temp_dir().join(format!("ec-mp4-prores-{}", std::process::id()));21 let dir = std::env::temp_dir().join(format!("ec-mp4-prores-{}", std::process::id()));
28 std::fs::create_dir_all(&dir).unwrap();22 std::fs::create_dir_all(&dir).unwrap();
29 for (profile, fmt, fourcc) in [23 for (profile, fmt, fourcc) in [
@@ -35,7 +29,7 @@ fn prores_fourccs_are_recognised() {
35 ("5", "yuv444p10le", "ap4x"),29 ("5", "yuv444p10le", "ap4x"),
36 ] {30 ] {
37 let path = dir.join(format!("{fourcc}.mov"));31 let path = dir.join(format!("{fourcc}.mov"));
38- let ok = Command::new("ffmpeg")32+ let ok = ec_testkit::ffmpeg()
39 .args(["-v", "error", "-y", "-f", "lavfi", "-i", "testsrc2=size=64x48:rate=25", "-frames:v", "1"])33 .args(["-v", "error", "-y", "-f", "lavfi", "-i", "testsrc2=size=64x48:rate=25", "-frames:v", "1"])
40 .args(["-c:v", "prores_ks", "-profile", profile, "-pix_fmt", fmt])34 .args(["-c:v", "prores_ks", "-profile", profile, "-pix_fmt", fmt])
41 .arg(&path)35 .arg(&path)
crates/ec-mp4/tests/it/qt_pcm_hdr.rsmodified+15 -31
@@ -1,33 +1,23 @@
1 //! QuickTime PCM sound descriptions (`in24`, `in32`, `fl32` with `wave/enda`1 //! QuickTime PCM sound descriptions (`in24`, `in32`, `fl32` with `wave/enda`
2 //! and `chan`) and the HDR `mdcv`/`clli` boxes, checked against ffmpeg.2 //! and `chan`) and the HDR `mdcv`/`clli` boxes, checked against ffmpeg.
3 //!3 //!
4-//! Sources are synthetic (ffmpeg `sine`, `testsrc2`). A case skips where
5-//! ffmpeg or an encoder is missing, unless `EC_REQUIRE_FIXTURES` is set.
6 4
7 use std::fs::File;5 use std::fs::File;
8 use std::io::{BufReader, BufWriter};6 use std::io::{BufReader, BufWriter};
9 use std::path::{Path, PathBuf};7 use std::path::{Path, PathBuf};
10-use std::process::Command;
11 8
12 use ec_core::{ContentLight, Demuxer, Error, MasteringPrimaries, Muxer, Packet, StreamInfo};9 use ec_core::{ContentLight, Demuxer, Error, MasteringPrimaries, Muxer, Packet, StreamInfo};
13 use ec_mp4::{Mp4Demuxer, Mp4Muxer};10 use ec_mp4::{Mp4Demuxer, Mp4Muxer};
14 11
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");
16 assert!(17 assert!(
17- std::env::var_os("EC_REQUIRE_FIXTURES").is_none(),18+ String::from_utf8_lossy(&out.stdout).contains(&format!(" {encoder} ")),
18- "EC_REQUIRE_FIXTURES set but: {why}"19+ "ffmpeg has no {encoder} encoder"
19 );20 );
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}"))
31 }21 }
32 22
33 fn dir(name: &str) -> PathBuf {23 fn dir(name: &str) -> PathBuf {
@@ -72,7 +62,7 @@ fn entry(path: &Path, fourcc: &[u8; 4]) -> Option<Vec<u8>> {
72 }62 }
73 63
74 fn probe(path: &Path, args: &[&str]) -> String {64 fn probe(path: &Path, args: &[&str]) -> String {
75- let out = Command::new("ffprobe")65+ let out = ec_testkit::ffprobe()
76 .args(["-v", "error"])66 .args(["-v", "error"])
77 .args(args)67 .args(args)
78 .arg(path)68 .arg(path)
@@ -83,7 +73,7 @@ fn probe(path: &Path, args: &[&str]) -> String {
83 }73 }
84 74
85 fn decoded_md5(path: &Path) -> String {75 fn decoded_md5(path: &Path) -> String {
86- let out = Command::new("ffmpeg")76+ let out = ec_testkit::ffmpeg()
87 .args(["-v", "error", "-i"])77 .args(["-v", "error", "-i"])
88 .arg(path)78 .arg(path)
89 .args(["-map", "0:a:0", "-f", "md5", "-"])79 .args(["-map", "0:a:0", "-f", "md5", "-"])
@@ -93,12 +83,10 @@ fn decoded_md5(path: &Path) -> String {
93 }83 }
94 84
95 fn pcm_case(name: &str, codec: &str, channels: u32, fourcc: &[u8; 4], layout_box: bool) {85 fn pcm_case(name: &str, codec: &str, channels: u32, fourcc: &[u8; 4], layout_box: bool) {
96- if !have_ffmpeg(codec) {86+ require_encoder(codec);
97- return;
98- }
99 let d = dir(name);87 let d = dir(name);
100 let src = d.join("src.mov");88 let src = d.join("src.mov");
101- let ok = Command::new("ffmpeg")89+ let ok = ec_testkit::ffmpeg()
102 .args(["-v", "error", "-y", "-f", "lavfi", "-i", "sine=d=0.5:sample_rate=48000"])90 .args(["-v", "error", "-y", "-f", "lavfi", "-i", "sine=d=0.5:sample_rate=48000"])
103 .args(["-ac", &channels.to_string(), "-c:a", codec])91 .args(["-ac", &channels.to_string(), "-c:a", codec])
104 .arg(&src)92 .arg(&src)
@@ -169,12 +157,10 @@ fn pcm_sample_entries_are_ffprobe_clean_and_byte_equal() {
169 /// (no `chan`), and one that does gets ffmpeg's.157 /// (no `chan`), and one that does gets ffmpeg's.
170 #[test]158 #[test]
171 fn sowt_gets_chan_only_when_asked() {159 fn sowt_gets_chan_only_when_asked() {
172- if !have_ffmpeg("pcm_s16le") {160+ require_encoder("pcm_s16le");
173- return;
174- }
175 let d = dir("sowt");161 let d = dir("sowt");
176 let src = d.join("src.mov");162 let src = d.join("src.mov");
177- assert!(Command::new("ffmpeg")163+ assert!(ec_testkit::ffmpeg()
178 .args(["-v", "error", "-y", "-f", "lavfi", "-i", "sine=d=0.2:sample_rate=48000", "-ac", "2", "-c:a", "pcm_s16le"])164 .args(["-v", "error", "-y", "-f", "lavfi", "-i", "sine=d=0.2:sample_rate=48000", "-ac", "2", "-c:a", "pcm_s16le"])
179 .arg(&src)165 .arg(&src)
180 .status()166 .status()
@@ -203,12 +189,10 @@ fn light() -> ContentLight {
203 /// Main 10 HEVC, remuxed with `mdcv` and `clli`.189 /// Main 10 HEVC, remuxed with `mdcv` and `clli`.
204 #[test]190 #[test]
205 fn hevc_main10_mdcv_clli_in_mp4() {191 fn hevc_main10_mdcv_clli_in_mp4() {
206- if !have_ffmpeg("libx265") {192+ require_encoder("libx265");
207- return;
208- }
209 let d = dir("hdr");193 let d = dir("hdr");
210 let src = d.join("src.mp4");194 let src = d.join("src.mp4");
211- assert!(Command::new("ffmpeg")195+ assert!(ec_testkit::ffmpeg()
212 .args(["-v", "error", "-y", "-f", "lavfi", "-i", "testsrc2=size=320x240:rate=25:duration=1"])196 .args(["-v", "error", "-y", "-f", "lavfi", "-i", "testsrc2=size=320x240:rate=25:duration=1"])
213 .args(["-c:v", "libx265", "-pix_fmt", "yuv420p10le", "-tag:v", "hvc1"])197 .args(["-c:v", "libx265", "-pix_fmt", "yuv420p10le", "-tag:v", "hvc1"])
214 .args(["-x265-params", "log-level=error:colorprim=bt2020:transfer=smpte2084:colormatrix=bt2020nc"])198 .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
12 ec-h264-syntax.workspace = true12 ec-h264-syntax.workspace = true
13 ec-h265-syntax.workspace = true13 ec-h265-syntax.workspace = true
14 ec-truehd.workspace = true14 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 @@
4 # expected.txt: <file> <stream-index-in-ffmpeg> <codec> <packets> <bytes> <fnv1a64 of ffmpeg's bytes>4 # expected.txt: <file> <stream-index-in-ffmpeg> <codec> <packets> <bytes> <fnv1a64 of ffmpeg's bytes>
5 # LPCM is hashed over ffmpeg's s16be decode, which is what the demuxer's packets are.5 # LPCM is hashed over ffmpeg's s16be decode, which is what the demuxer's packets are.
6 set -euo pipefail6 set -euo pipefail
7+
8+FF=${EC_FFMPEG:-$HOME/.cache/ec-ffmpeg/ffmpeg}
9+FP=$(dirname "$FF")/ffprobe
10+export FF FP
7 cd "$(dirname "$0")"11 cd "$(dirname "$0")"
8 V=(-f lavfi -i testsrc2=size=160x120:rate=25:duration=0.6)12 V=(-f lavfi -i testsrc2=size=160x120:rate=25:duration=0.6)
9 A=(-f lavfi -i sine=frequency=440:sample_rate=48000:duration=0.6)13 A=(-f lavfi -i sine=frequency=440:sample_rate=48000:duration=0.6)
10 X=(-c:v libx264 -preset ultrafast -g 12 -bf 2)14 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.ts15+"$FF" -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.m2ts16+"$FF" -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.ts17+"$FF" -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.m2ts18+"$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
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.ts19+"$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
16 python3 -I - <<'PY'20 python3 -I - <<'PY'
17-import subprocess21+import os, subprocess
18 def fnv(b):22 def fnv(b):
19 h = 0xcbf29ce48422232523 h = 0xcbf29ce484222325
20 for x in b:24 for x in b:
@@ -24,10 +28,10 @@ rows = []
24 for f in ["tiny_h264_aac.ts", "tiny_h264_ac3.m2ts", "tiny_h264_eac3.ts", "tiny_h264_lpcm.m2ts", "tiny_hevc_aac.ts"]:28 for f in ["tiny_h264_aac.ts", "tiny_h264_ac3.m2ts", "tiny_h264_eac3.ts", "tiny_h264_lpcm.m2ts", "tiny_hevc_aac.ts"]:
25 for idx, codec in enumerate(["video", "audio"]):29 for idx, codec in enumerate(["video", "audio"]):
26 if codec == "audio" and "lpcm" in f:30 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).stdout31+ data = subprocess.run([os.environ["FF"],"-v","error","-i",f,"-map","0:1","-f","s16be","-"],capture_output=True,check=True).stdout
28 else:32 else:
29- data = subprocess.run(["ffmpeg","-v","error","-i",f,"-map",f"0:{idx}","-c","copy","-f","data","-"],capture_output=True,check=True).stdout33+ data = subprocess.run([os.environ["FF"],"-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()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()
31 rows.append(f"{f} {idx} {len(pk)} {len(data)} {fnv(data):016x}")35 rows.append(f"{f} {idx} {len(pk)} {len(data)} {fnv(data):016x}")
32 open("expected.txt","w").write("\n".join(rows) + "\n")36 open("expected.txt","w").write("\n".join(rows) + "\n")
33 PY37 PY
crates/ec-mpegts/tests/data/gen_ps.shmodified+12 -8
@@ -3,15 +3,19 @@
3 # sources (testsrc2 and sine only). Needs ffmpeg with mpeg2video, mpeg1video, ac3, mp2.3 # sources (testsrc2 and sine only). Needs ffmpeg with mpeg2video, mpeg1video, ac3, mp2.
4 # expected_ps.txt: <file> <stream-index-in-ffmpeg> <packets> <bytes> <fnv1a64 of ffmpeg's bytes>4 # expected_ps.txt: <file> <stream-index-in-ffmpeg> <packets> <bytes> <fnv1a64 of ffmpeg's bytes>
5 set -euo pipefail5 set -euo pipefail
6+
7+FF=${EC_FFMPEG:-$HOME/.cache/ec-ffmpeg/ffmpeg}
8+FP=$(dirname "$FF")/ffprobe
9+export FF FP
6 cd "$(dirname "$0")"10 cd "$(dirname "$0")"
7 V=(-f lavfi -i testsrc2=size=128x96:rate=25:duration=0.5)11 V=(-f lavfi -i testsrc2=size=128x96:rate=25:duration=0.5)
8 A=(-f lavfi -i sine=frequency=440:sample_rate=48000:duration=0.5)12 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.vob13+"$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
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.mpg14+"$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
11-ffmpeg -v error -y "${V[@]}" -c:v mpeg2video -g 12 -bf 2 -b:v 150k -f mpeg2video ps_mpeg2.m2v15+"$FF" -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.vob16+"$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
13 python3 -I - <<'PY'17 python3 -I - <<'PY'
14-import subprocess18+import os, subprocess
15 def fnv(b):19 def fnv(b):
16 h = 0xcbf29ce48422232520 h = 0xcbf29ce484222325
17 for x in b:21 for x in b:
@@ -20,10 +24,10 @@ def fnv(b):
20 rows = []24 rows = []
21 for f, streams in [("ps_mpeg2_ac3.vob", 2), ("ps_mpeg1_mp2.mpg", 2), ("ps_mpeg2.m2v", 1), ("ps_pcm_dvd.vob", 2)]:25 for f, streams in [("ps_mpeg2_ac3.vob", 2), ("ps_mpeg1_mp2.mpg", 2), ("ps_mpeg2.m2v", 1), ("ps_pcm_dvd.vob", 2)]:
22 for idx in range(streams):26 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).stdout27+ data = subprocess.run([os.environ["FF"],"-v","error","-i",f,"-map",f"0:{idx}","-c","copy","-f","data","-"],capture_output=True,check=True).stdout
24 if "pcm_dvd" in f and idx == 1:28 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).stdout29+ data = subprocess.run([os.environ["FF"],"-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()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()
27 rows.append(f"{f} {idx} {len(pk)} {len(data)} {fnv(data):016x}")31 rows.append(f"{f} {idx} {len(pk)} {len(data)} {fnv(data):016x}")
28 open("expected_ps.txt","w").write("\n".join(rows) + "\n")32 open("expected_ps.txt","w").write("\n".join(rows) + "\n")
29 PY33 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).
3 #![allow(dead_code)]1 #![allow(dead_code)]
4 2
5 use std::collections::HashMap;3 use std::collections::HashMap;
6 use std::fs::File;4 use std::fs::File;
7 use std::io::BufReader;5 use std::io::BufReader;
8 use std::path::{Path, PathBuf};6 use std::path::{Path, PathBuf};
9-use std::process::Command;
10 use std::sync::OnceLock;7 use std::sync::OnceLock;
11 8
12 use ec_core::registry::Demuxer;9 use ec_core::registry::Demuxer;
13 use ec_mpegts::TsDemuxer;10 use ec_mpegts::TsDemuxer;
14 11
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-
41 pub fn fixture_dir() -> PathBuf {12 pub fn fixture_dir() -> PathBuf {
42 static DIR: OnceLock<PathBuf> = OnceLock::new();13 static DIR: OnceLock<PathBuf> = OnceLock::new();
43 DIR.get_or_init(|| {14 DIR.get_or_init(|| {
@@ -61,9 +32,8 @@ pub const AUDIO_SRC: &[&str] = &[
61 "sine=frequency=440:sample_rate=48000:duration=3",32 "sine=frequency=440:sample_rate=48000:duration=3",
62 ];33 ];
63 34
64-/// Runs ffmpeg; `Err` carries stderr. Unavailable encoders are a skip.
65 pub fn ffmpeg(args: &[&str], out: &Path) -> Result<(), String> {35 pub fn ffmpeg(args: &[&str], out: &Path) -> Result<(), String> {
66- let o = Command::new("ffmpeg")36+ let o = ec_testkit::ffmpeg()
67 .args(["-v", "error", "-y"])37 .args(["-v", "error", "-y"])
68 .args(args)38 .args(args)
69 .arg(out)39 .arg(out)
@@ -76,30 +46,20 @@ pub fn ffmpeg(args: &[&str], out: &Path) -> Result<(), String> {
76 }46 }
77 }47 }
78 48
79-/// Generates `name` with `args` (input options included) or returns `None` on skip.49+pub fn fixture(name: &str, args: &[&str]) -> PathBuf {
80-pub fn fixture(name: &str, args: &[&str]) -> Option<PathBuf> {
81- if !have_ffmpeg() {
82- return None;
83- }
84 // Tests run on threads of one process: one generates a given file at a time.50 // Tests run on threads of one process: one generates a given file at a time.
85 static LOCK: std::sync::Mutex<()> = std::sync::Mutex::new(());51 static LOCK: std::sync::Mutex<()> = std::sync::Mutex::new(());
86 let _guard = LOCK.lock().unwrap_or_else(|e| e.into_inner());52 let _guard = LOCK.lock().unwrap_or_else(|e| e.into_inner());
87 let out = fixture_dir().join(name);53 let out = fixture_dir().join(name);
88 if out.exists() {54 if out.exists() {
89- return Some(out);55+ return out;
90 }56 }
91 let tmp = fixture_dir().join(format!("{name}.{}.tmp", std::process::id()));57 let tmp = fixture_dir().join(format!("{name}.{}.tmp", std::process::id()));
92- match ffmpeg(args, &tmp) {58+ if let Err(e) = ffmpeg(args, &tmp) {
93- Ok(()) => {59+ panic!("ffmpeg failed for {name}: {e}");
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- }
102 }60 }
61+ std::fs::rename(&tmp, &out).unwrap();
62+ out
103 }63 }
104 64
105 pub fn open(path: &Path) -> TsDemuxer<BufReader<File>> {65 pub fn open(path: &Path) -> TsDemuxer<BufReader<File>> {
@@ -143,7 +103,7 @@ pub struct Row {
143 }103 }
144 104
145 pub fn ffprobe_rows(path: &Path) -> HashMap<u16, (u32, Vec<Row>)> {105 pub fn ffprobe_rows(path: &Path) -> HashMap<u16, (u32, Vec<Row>)> {
146- let streams = Command::new("ffprobe")106+ let streams = ec_testkit::ffprobe()
147 .args([107 .args([
148 "-v",108 "-v",
149 "error",109 "error",
@@ -167,7 +127,7 @@ pub fn ffprobe_rows(path: &Path) -> HashMap<u16, (u32, Vec<Row>)> {
167 pid_of.insert(i, p);127 pid_of.insert(i, p);
168 }128 }
169 }129 }
170- let pk = Command::new("ffprobe")130+ let pk = ec_testkit::ffprobe()
171 .args([131 .args([
172 "-v",132 "-v",
173 "error",133 "error",
@@ -204,7 +164,7 @@ pub fn ffprobe_rows(path: &Path) -> HashMap<u16, (u32, Vec<Row>)> {
204 164
205 /// ffmpeg's stream copy of stream `index`, as one byte string.165 /// ffmpeg's stream copy of stream `index`, as one byte string.
206 pub fn ffmpeg_bytes(path: &Path, index: u32) -> Vec<u8> {166 pub fn ffmpeg_bytes(path: &Path, index: u32) -> Vec<u8> {
207- let o = Command::new("ffmpeg")167+ let o = ec_testkit::ffmpeg()
208 .args(["-v", "error", "-i"])168 .args(["-v", "error", "-i"])
209 .arg(path)169 .arg(path)
210 .args([170 .args([
@@ -223,7 +183,7 @@ pub fn ffmpeg_bytes(path: &Path, index: u32) -> Vec<u8> {
223 183
224 /// ffmpeg's decode of an LPCM stream as big-endian 16-bit samples.184 /// ffmpeg's decode of an LPCM stream as big-endian 16-bit samples.
225 pub fn ffmpeg_pcm_s16be(path: &Path, index: u32) -> Vec<u8> {185 pub fn ffmpeg_pcm_s16be(path: &Path, index: u32) -> Vec<u8> {
226- Command::new("ffmpeg")186+ ec_testkit::ffmpeg()
227 .args(["-v", "error", "-i"])187 .args(["-v", "error", "-i"])
228 .arg(path)188 .arg(path)
229 .args(["-map", &format!("0:{index}"), "-f", "s16be", "-"])189 .args(["-map", &format!("0:{index}"), "-f", "s16be", "-"])
crates/ec-mpegts/tests/it/dts.rsmodified+3 -7
@@ -7,7 +7,7 @@ use ec_core::CodecId;
7 use ec_core::registry::{Demuxer, MediaParameters};7 use ec_core::registry::{Demuxer, MediaParameters};
8 use ec_mpegts::StreamKind;8 use ec_mpegts::StreamKind;
9 9
10-fn dts_ts(name: &str, channels: &str) -> Option<std::path::PathBuf> {10+fn dts_ts(name: &str, channels: &str) -> std::path::PathBuf {
11 fixture(11 fixture(
12 name,12 name,
13 &[13 &[
@@ -28,9 +28,7 @@ fn dts_ts(name: &str, channels: &str) -> Option<std::path::PathBuf> {
28 }28 }
29 29
30 fn check(name: &str, channels: &str, want: usize) {30 fn check(name: &str, channels: &str, want: usize) {
31- let Some(p) = dts_ts(name, channels) else {31+ let p = dts_ts(name, channels);
32- return;
33- };
34 let mut d = open(&p);32 let mut d = open(&p);
35 let streams = d.streams().to_vec();33 let streams = d.streams().to_vec();
36 assert_eq!(streams.len(), 1);34 assert_eq!(streams.len(), 1);
@@ -98,9 +96,7 @@ fn rewrite_pmt(ts: &[u8], stream_type: u8, descriptors: &[u8]) -> Vec<u8> {
98 96
99 #[test]97 #[test]
100 fn dts_hd_stream_types_and_descriptors_map_to_dts() {98 fn dts_hd_stream_types_and_descriptors_map_to_dts() {
101- let Some(p) = dts_ts("dts_retag.ts", "2") else {99+ let p = dts_ts("dts_retag.ts", "2");
102- return;
103- };
104 let ts = std::fs::read(&p).unwrap();100 let ts = std::fs::read(&p).unwrap();
105 let cases: [(&str, u8, Vec<u8>); 5] = [101 let cases: [(&str, u8, Vec<u8>); 5] = [
106 ("0x82", 0x82, vec![]),102 ("0x82", 0x82, vec![]),
crates/ec-mpegts/tests/it/ffmpeg_parity.rsmodified+14 -27
@@ -2,14 +2,13 @@
2 //! bytes, sizes, timestamps, keyframe flags, duration, plus seek exactness.2 //! bytes, sizes, timestamps, keyframe flags, duration, plus seek exactness.
3 //!3 //!
4 //! Fixtures are generated at test time from synthetic sources (testsrc2, sine). The4 //! Fixtures are generated at test time from synthetic sources (testsrc2, sine). The
5-//! tests skip, saying so, when ffmpeg is absent and fail instead when5+
6-//! `EC_REQUIRE_FIXTURES` is set.
7 6
8 use crate::common::*;7 use crate::common::*;
9 use ec_core::registry::{Demuxer, SeekMode};8 use ec_core::registry::{Demuxer, SeekMode};
10 use ec_core::{CodecId, TimeBase, Timestamp};9 use ec_core::{CodecId, TimeBase, Timestamp};
11 10
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 {
13 let mut a: Vec<&str> = VIDEO_SRC.to_vec();12 let mut a: Vec<&str> = VIDEO_SRC.to_vec();
14 a.extend_from_slice(AUDIO_SRC);13 a.extend_from_slice(AUDIO_SRC);
15 a.extend_from_slice(&[14 a.extend_from_slice(&[
@@ -191,7 +190,7 @@ fn cleanup_none() {}
191 /// One test over a table so every case runs and all failures are named.190 /// One test over a table so every case runs and all failures are named.
192 #[test]191 #[test]
193 fn parity_cases() {192 fn parity_cases() {
194- type Case = (&'static str, fn() -> Option<std::path::PathBuf>);193+ type Case = (&'static str, fn() -> std::path::PathBuf);
195 const CASES: &[Case] = &[194 const CASES: &[Case] = &[
196 ("h264_aac_ts", || {195 ("h264_aac_ts", || {
197 v264("h264_aac.ts", &["-c:a", "aac"], &["-f", "mpegts"])196 v264("h264_aac.ts", &["-c:a", "aac"], &["-f", "mpegts"])
@@ -243,7 +242,7 @@ fn parity_cases() {
243 let mut failures = Vec::new();242 let mut failures = Vec::new();
244 for &(name, make) in CASES {243 for &(name, make) in CASES {
245 let ran = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {244 let ran = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
246- let Some(p) = make() else { return };245+ let p = make();
247 parity(&p);246 parity(&p);
248 duration_ok(&p);247 duration_ok(&p);
249 seek_exact(&p);248 seek_exact(&p);
@@ -257,9 +256,7 @@ fn parity_cases() {
257 256
258 #[test]257 #[test]
259 fn mp2_in_ts_is_exposed_as_mp2() {258 fn mp2_in_ts_is_exposed_as_mp2() {
260- let Some(p) = v264("h264_mp2.ts", &["-c:a", "mp2"], &["-f", "mpegts"]) else {259+ let p = v264("h264_mp2.ts", &["-c:a", "mp2"], &["-f", "mpegts"]);
261- return;
262- };
263 let d = open(&p);260 let d = open(&p);
264 let audio: Vec<_> = d261 let audio: Vec<_> = d
265 .streams()262 .streams()
@@ -273,7 +270,7 @@ fn mp2_in_ts_is_exposed_as_mp2() {
273 );270 );
274 assert!(d.tracks().iter().all(|t| t.refusal.is_none()));271 assert!(d.tracks().iter().all(|t| t.refusal.is_none()));
275 }272 }
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 {
277 let mut a: Vec<&str> = vec![274 let mut a: Vec<&str> = vec![
278 "-f",275 "-f",
279 "lavfi",276 "lavfi",
@@ -293,9 +290,7 @@ fn audio_only(name: &str, codec: &str, rate: &str, extra: &[&str]) -> Option<std
293 290
294 #[test]291 #[test]
295 fn audio_only_aac_44100() {292 fn audio_only_aac_44100() {
296- let Some(p) = audio_only("audio_aac.ts", "aac", "44100", &[]) else {293+ let p = audio_only("audio_aac.ts", "aac", "44100", &[]);
297- return;
298- };
299 parity_slack(&p, 8);294 parity_slack(&p, 8);
300 seek_exact(&p);295 seek_exact(&p);
301 duration_ok(&p);296 duration_ok(&p);
@@ -315,16 +310,14 @@ fn ac3_family_sizes() {
315 ("eac3", "48000", "384k"),310 ("eac3", "48000", "384k"),
316 ] {311 ] {
317 let name = format!("audio_{codec}_{rate}_{br}.ts");312 let name = format!("audio_{codec}_{rate}_{br}.ts");
318- let Some(p) = audio_only(&name, codec, rate, &["-b:a", br]) else {313+ let p = audio_only(&name, codec, rate, &["-b:a", br]);
319- return;
320- };
321 parity_slack(&p, 8);314 parity_slack(&p, 8);
322 seek_exact(&p);315 seek_exact(&p);
323 duration_ok(&p);316 duration_ok(&p);
324 }317 }
325 }318 }
326 319
327-fn hevc(name: &str, audio: &str) -> Option<std::path::PathBuf> {320+fn hevc(name: &str, audio: &str) -> std::path::PathBuf {
328 let mut a: Vec<&str> = VIDEO_SRC.to_vec();321 let mut a: Vec<&str> = VIDEO_SRC.to_vec();
329 a.extend_from_slice(AUDIO_SRC);322 a.extend_from_slice(AUDIO_SRC);
330 a.extend_from_slice(&[323 a.extend_from_slice(&[
@@ -346,9 +339,7 @@ fn hevc(name: &str, audio: &str) -> Option<std::path::PathBuf> {
346 339
347 #[test]340 #[test]
348 fn codecs_and_extradata() {341 fn codecs_and_extradata() {
349- let Some(p) = v264("h264_aac.ts", &["-c:a", "aac"], &["-f", "mpegts"]) else {342+ let p = v264("h264_aac.ts", &["-c:a", "aac"], &["-f", "mpegts"]);
350- return;
351- };
352 let d = open(&p);343 let d = open(&p);
353 let s = d.streams();344 let s = d.streams();
354 assert_eq!(s[0].params.codec, CodecId::H264);345 assert_eq!(s[0].params.codec, CodecId::H264);
@@ -363,7 +354,7 @@ fn codecs_and_extradata() {
363 assert_eq!(s[1].params.audio().unwrap().sample_rate, 48000);354 assert_eq!(s[1].params.audio().unwrap().sample_rate, 48000);
364 }355 }
365 356
366-fn two_programs() -> Option<std::path::PathBuf> {357+fn two_programs() -> std::path::PathBuf {
367 let mut a: Vec<&str> = VIDEO_SRC.to_vec();358 let mut a: Vec<&str> = VIDEO_SRC.to_vec();
368 a.extend_from_slice(AUDIO_SRC);359 a.extend_from_slice(AUDIO_SRC);
369 a.extend_from_slice(&[360 a.extend_from_slice(&[
@@ -397,7 +388,7 @@ fn two_programs() -> Option<std::path::PathBuf> {
397 388
398 #[test]389 #[test]
399 fn multiple_programs() {390 fn multiple_programs() {
400- let Some(p) = two_programs() else { return };391+ let p = two_programs();
401 let d = open(&p);392 let d = open(&p);
402 let progs = d.programs();393 let progs = d.programs();
403 assert_eq!(progs.len(), 2, "{progs:?}");394 assert_eq!(progs.len(), 2, "{progs:?}");
@@ -437,9 +428,7 @@ fn pts_wrap_is_unwrapped() {
437 "-f",428 "-f",
438 "mpegts",429 "mpegts",
439 ]);430 ]);
440- let Some(p) = fixture("wrap.ts", &a) else {431+ let p = fixture("wrap.ts", &a);
441- return;
442- };
443 let mut d = open(&p);432 let mut d = open(&p);
444 let pkts = read_all(&mut d);433 let pkts = read_all(&mut d);
445 for s in d.streams() {434 for s in d.streams() {
@@ -470,9 +459,7 @@ fn pts_wrap_is_unwrapped() {
470 /// packet not flagged corrupt is one the intact file has.459 /// packet not flagged corrupt is one the intact file has.
471 #[test]460 #[test]
472 fn corrupted_and_truncated() {461 fn corrupted_and_truncated() {
473- let Some(p) = v264("h264_aac.ts", &["-c:a", "aac"], &["-f", "mpegts"]) else {462+ let p = v264("h264_aac.ts", &["-c:a", "aac"], &["-f", "mpegts"]);
474- return;
475- };
476 let good = std::fs::read(&p).unwrap();463 let good = std::fs::read(&p).unwrap();
477 let mut d = open(&p);464 let mut d = open(&p);
478 let want = read_all(&mut d);465 let want = read_all(&mut d);
crates/ec-mpegts/tests/it/mpeg2.rsmodified+3 -7
@@ -1,6 +1,5 @@
1 //! MPEG-1/2 video in transport streams: exposed as `CodecId::Mpeg2Video`, one1 //! MPEG-1/2 video in transport streams: exposed as `CodecId::Mpeg2Video`, one
2 //! packet per coded picture, parameters from the sequence header. Fixtures come from2 //! 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.
4 3
5 use crate::common::*;4 use crate::common::*;
6 use ec_core::registry::Demuxer;5 use ec_core::registry::Demuxer;
@@ -15,7 +14,7 @@ fn pictures(d: &[u8]) -> Vec<u8> {
15 }14 }
16 15
17 fn check(codec: &str, name: &str, mpeg2: bool) {16 fn check(codec: &str, name: &str, mpeg2: bool) {
18- let Some(ts) = fixture(17+ let ts = fixture(
19 name,18 name,
20 &[19 &[
21 "-f",20 "-f",
@@ -33,16 +32,13 @@ fn check(codec: &str, name: &str, mpeg2: bool) {
33 "-f",32 "-f",
34 "mpegts",33 "mpegts",
35 ],34 ],
36- ) else {35+ );
37- return;
38- };
39 let es = fixture_dir().join(format!("{name}.m2v"));36 let es = fixture_dir().join(format!("{name}.m2v"));
40 if let Err(e) = ffmpeg(37 if let Err(e) = ffmpeg(
41 &["-i", ts.to_str().unwrap(), "-c", "copy", "-f", codec],38 &["-i", ts.to_str().unwrap(), "-c", "copy", "-f", codec],
42 &es,39 &es,
43 ) {40 ) {
44- assert!(!required(), "es extraction failed: {e}");41+ panic!("es extraction failed: {e}");
45- return;
46 }42 }
47 let want = std::fs::read(&es).unwrap();43 let want = std::fs::read(&es).unwrap();
48 let mut d = open(&ts);44 let mut d = open(&ts);
crates/ec-mpegts/tests/it/ps.rsmodified+24 -46
@@ -2,8 +2,6 @@
2 //! ffmpeg's demux on ffmpeg-made files (bytes, sizes, timestamps, key flags),2 //! ffmpeg's demux on ffmpeg-made files (bytes, sizes, timestamps, key flags),
3 //! duration, seek exactness, SCR resets, PTS wraps and damaged files.3 //! duration, seek exactness, SCR resets, PTS wraps and damaged files.
4 //!4 //!
5-//! Fixtures are generated at test time from synthetic sources; the tests skip when
6-//! ffmpeg is missing and fail instead under `EC_REQUIRE_FIXTURES`.
7 5
8 use std::fs::File;6 use std::fs::File;
9 use std::io::BufReader;7 use std::io::BufReader;
@@ -61,7 +59,7 @@ fn src(extra_audio: &[&str]) -> Vec<&'static str> {
61 a59 a
62 }60 }
63 61
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 {
65 let mut a = src(audio);63 let mut a = src(audio);
66 a.extend_from_slice(video);64 a.extend_from_slice(video);
67 a.extend_from_slice(audio);65 a.extend_from_slice(audio);
@@ -153,7 +151,7 @@ fn parity(path: &Path, slack: i64) {
153 }151 }
154 152
155 fn raw_rows(path: &Path) -> Vec<Row> {153 fn raw_rows(path: &Path) -> Vec<Row> {
156- let o = std::process::Command::new("ffprobe")154+ let o = ec_testkit::ffprobe()
157 .args([155 .args([
158 "-v",156 "-v",
159 "error",157 "error",
@@ -182,7 +180,7 @@ fn raw_rows(path: &Path) -> Vec<Row> {
182 }180 }
183 181
184 fn ffmpeg_pcm(path: &Path, index: u32, fmt: &str) -> Vec<u8> {182 fn ffmpeg_pcm(path: &Path, index: u32, fmt: &str) -> Vec<u8> {
185- std::process::Command::new("ffmpeg")183+ ec_testkit::ffmpeg()
186 .args(["-v", "error", "-i"])184 .args(["-v", "error", "-i"])
187 .arg(path)185 .arg(path)
188 .args(["-map", &format!("0:{index}"), "-f", fmt, "-"])186 .args(["-map", &format!("0:{index}"), "-f", fmt, "-"])
@@ -318,7 +316,7 @@ fn seek_exact(path: &Path) {
318 /// exactness). One test over a table: every case runs and all failures are named.316 /// exactness). One test over a table: every case runs and all failures are named.
319 #[test]317 #[test]
320 fn ps_parity_cases() {318 fn ps_parity_cases() {
321- type Case = (&'static str, fn() -> Option<std::path::PathBuf>);319+ type Case = (&'static str, fn() -> std::path::PathBuf);
322 const CASES: &[Case] = &[320 const CASES: &[Case] = &[
323 ("mpeg1_system_mp2", || {321 ("mpeg1_system_mp2", || {
324 mkps(322 mkps(
@@ -466,7 +464,7 @@ fn ps_parity_cases() {
466 let mut failures = Vec::new();464 let mut failures = Vec::new();
467 for &(name, make) in CASES {465 for &(name, make) in CASES {
468 let ran = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {466 let ran = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
469- let Some(p) = make() else { return };467+ let p = make();
470 parity(&p, 0);468 parity(&p, 0);
471 duration_ok(&p);469 duration_ok(&p);
472 seek_exact(&p);470 seek_exact(&p);
@@ -482,28 +480,24 @@ fn ps_parity_cases() {
482 // mid-stream cannot know the phase: no seek-exactness check for it.480 // mid-stream cannot know the phase: no seek-exactness check for it.
483 #[test]481 #[test]
484 fn pcm_dvd_24() {482 fn pcm_dvd_24() {
485- let Some(p) = mkps(483+ let p = mkps(
486 "lpcm24.vob",484 "lpcm24.vob",
487 V2,485 V2,
488 &["-c:a", "pcm_dvd", "-sample_fmt", "s32"],486 &["-c:a", "pcm_dvd", "-sample_fmt", "s32"],
489 &["-f", "vob"],487 &["-f", "vob"],
490- ) else {488+ );
491- return;
492- };
493 parity(&p, 0);489 parity(&p, 0);
494 duration_ok(&p);490 duration_ok(&p);
495 }491 }
496 492
497 #[test]493 #[test]
498 fn dts_is_refused_by_name() {494 fn dts_is_refused_by_name() {
499- let Some(p) = mkps(495+ let p = mkps(
500 "dts.vob",496 "dts.vob",
501 V2,497 V2,
502 &["-c:a", "dca", "-strict", "-2"],498 &["-c:a", "dca", "-strict", "-2"],
503 &["-f", "vob"],499 &["-f", "vob"],
504- ) else {500+ );
505- return;
506- };
507 let d = open_ps(&p);501 let d = open_ps(&p);
508 assert_eq!(d.streams().len(), 1);502 assert_eq!(d.streams().len(), 1);
509 let t = d.tracks();503 let t = d.tracks();
@@ -636,7 +630,7 @@ fn concatenated_vobs_keep_time_monotonic() {
636 630
637 #[test]631 #[test]
638 fn concatenated_dvd_files_with_nav_packets() {632 fn concatenated_dvd_files_with_nav_packets() {
639- let Some(p) = mkps(633+ let p = mkps(
640 "dvd2.vob",634 "dvd2.vob",
641 &[635 &[
642 "-vf",636 "-vf",
@@ -652,17 +646,13 @@ fn concatenated_dvd_files_with_nav_packets() {
652 ],646 ],
653 &["-c:a", "ac3", "-ar", "48000"],647 &["-c:a", "ac3", "-ar", "48000"],
654 &["-f", "dvd"],648 &["-f", "dvd"],
655- ) else {649+ );
656- return;
657- };
658 check_concat(&std::fs::read(p).unwrap(), 2, None);650 check_concat(&std::fs::read(p).unwrap(), 2, None);
659 }651 }
660 652
661 #[test]653 #[test]
662 fn starts_mid_gop() {654 fn starts_mid_gop() {
663- let Some(p) = mkps("v_ac3.vob", V2, &["-c:a", "ac3"], &["-f", "vob"]) else {655+ let p = mkps("v_ac3.vob", V2, &["-c:a", "ac3"], &["-f", "vob"]);
664- return;
665- };
666 let orig_bytes = std::fs::read(&p).unwrap();656 let orig_bytes = std::fs::read(&p).unwrap();
667 let mut o = open_ps(&p);657 let mut o = open_ps(&p);
668 let orig = read_ps(&mut o);658 let orig = read_ps(&mut o);
@@ -883,14 +873,12 @@ fn mutated_files_never_panic() {
883 873
884 #[test]874 #[test]
885 fn pts_wrap_is_unwrapped() {875 fn pts_wrap_is_unwrapped() {
886- let Some(p) = mkps(876+ let p = mkps(
887 "wrap.vob",877 "wrap.vob",
888 V2,878 V2,
889 &["-c:a", "ac3"],879 &["-c:a", "ac3"],
890 &["-output_ts_offset", "95442", "-f", "vob"],880 &["-output_ts_offset", "95442", "-f", "vob"],
891- ) else {881+ );
892- return;
893- };
894 let mut d = open_ps(&p);882 let mut d = open_ps(&p);
895 let v = read_ps(&mut d);883 let v = read_ps(&mut d);
896 let pts: Vec<i64> = v884 let pts: Vec<i64> = v
@@ -950,7 +938,7 @@ fn video_index(d: &D) -> u32 {
950 }938 }
951 939
952 fn frames_by_ffprobe(path: &Path) -> usize {940 fn frames_by_ffprobe(path: &Path) -> usize {
953- let o = std::process::Command::new("ffprobe")941+ let o = ec_testkit::ffprobe()
954 .args(["-v", "error", "-count_frames", "-select_streams", "v:0"])942 .args(["-v", "error", "-count_frames", "-select_streams", "v:0"])
955 .args(["-show_entries", "stream=nb_read_frames", "-of", "csv=p=0"])943 .args(["-show_entries", "stream=nb_read_frames", "-of", "csv=p=0"])
956 .arg(path)944 .arg(path)
@@ -994,9 +982,7 @@ fn tail_picture_without_a_timestamp_is_counted() {
994 a.extend_from_slice(&[982 a.extend_from_slice(&[
995 "-pix_fmt", "yuv420p", "-map", "1:a", "-c:a", "mp2", "-f", "mpeg",983 "-pix_fmt", "yuv420p", "-map", "1:a", "-c:a", "mp2", "-f", "mpeg",
996 ]);984 ]);
997- if let Some(p) = fixture(name, &a) {985+ cases.push(fixture(name, &a));
998- cases.push(p);
999- }
1000 }986 }
1001 for path in cases {987 for path in cases {
1002 let mut d = open_ps(&path);988 let mut d = open_ps(&path);
@@ -1026,7 +1012,7 @@ fn tail_picture_without_a_timestamp_is_counted() {
1026 }1012 }
1027 1013
1028 /// Two VOBs of 2.4 s joined by bytes: SCR and PTS restart at the join.1014 /// 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) {
1030 let mk = |name: &str, vf: &str, hz: &str| {1016 let mk = |name: &str, vf: &str, hz: &str| {
1031 let video = format!("testsrc2=size=352x288:rate=25:duration=2.4{vf}");1017 let video = format!("testsrc2=size=352x288:rate=25:duration=2.4{vf}");
1032 let audio = format!("sine=frequency={hz}:sample_rate=48000:duration=2.4");1018 let audio = format!("sine=frequency={hz}:sample_rate=48000:duration=2.4");
@@ -1062,8 +1048,8 @@ fn joined_vob() -> Option<(PathBuf, u64)> {
1062 ];1048 ];
1063 fixture(name, &a)1049 fixture(name, &a)
1064 };1050 };
1065- let a = mk("pstail-a.vob", "", "440")?;1051+ let a = mk("pstail-a.vob", "", "440");
1066- let b = mk("pstail-b.vob", ",negate", "880")?;1052+ let b = mk("pstail-b.vob", ",negate", "880");
1067 let out = fixture_dir().join("pstail-join.vob");1053 let out = fixture_dir().join("pstail-join.vob");
1068 let alen = std::fs::metadata(&a).unwrap().len();1054 let alen = std::fs::metadata(&a).unwrap().len();
1069 if !out.exists() {1055 if !out.exists() {
@@ -1074,14 +1060,12 @@ fn joined_vob() -> Option<(PathBuf, u64)> {
1074 std::fs::write(&tmp, bytes).unwrap();1060 std::fs::write(&tmp, bytes).unwrap();
1075 std::fs::rename(&tmp, &out).unwrap();1061 std::fs::rename(&tmp, &out).unwrap();
1076 }1062 }
1077- Some((out, alen))1063+ (out, alen)
1078 }1064 }
1079 1065
1080 #[test]1066 #[test]
1081 fn joined_vobs_have_the_summed_duration() {1067 fn joined_vobs_have_the_summed_duration() {
1082- let Some((path, _)) = joined_vob() else {1068+ let (path, _) = joined_vob();
1083- return;
1084- };
1085 let d = open_ps(&path);1069 let d = open_ps(&path);
1086 let single = open_ps(&fixture_dir().join("pstail-a.vob"));1070 let single = open_ps(&fixture_dir().join("pstail-a.vob"));
1087 let v = video_index(&d) as usize;1071 let v = video_index(&d) as usize;
@@ -1115,9 +1099,7 @@ fn joined_vobs_have_the_summed_duration() {
1115 1099
1116 #[test]1100 #[test]
1117 fn seeks_on_both_sides_of_a_join_equal_the_sequential_decode() {1101 fn seeks_on_both_sides_of_a_join_equal_the_sequential_decode() {
1118- let Some((path, _)) = joined_vob() else {1102+ let (path, _) = joined_vob();
1119- return;
1120- };
1121 let mut d = open_ps(&path);1103 let mut d = open_ps(&path);
1122 let v = video_index(&d);1104 let v = video_index(&d);
1123 let all = read_ps(&mut d);1105 let all = read_ps(&mut d);
@@ -1166,9 +1148,7 @@ fn seeks_on_both_sides_of_a_join_equal_the_sequential_decode() {
1166 1148
1167 #[test]1149 #[test]
1168 fn audio_keeps_its_offset_to_the_video_after_a_join() {1150 fn audio_keeps_its_offset_to_the_video_after_a_join() {
1169- let Some((path, alen)) = joined_vob() else {1151+ let (path, alen) = joined_vob();
1170- return;
1171- };
1172 let mut d = open_ps(&path);1152 let mut d = open_ps(&path);
1173 let v = video_index(&d);1153 let v = video_index(&d);
1174 let a = d1154 let a = d
@@ -1216,9 +1196,7 @@ fn ts_tail_picture_is_counted() {
1216 "-f", "lavfi", "-i", FLASH_SRC, "-c:v", codec, "-b:v", "2M", "-g", "10", "-bf", "2",1196 "-f", "lavfi", "-i", FLASH_SRC, "-c:v", codec, "-b:v", "2M", "-g", "10", "-bf", "2",
1217 "-pix_fmt", "yuv420p", "-f", "mpegts",1197 "-pix_fmt", "yuv420p", "-f", "mpegts",
1218 ];1198 ];
1219- let Some(path) = fixture(name, &a) else {1199+ let path = fixture(name, &a);
1220- continue;
1221- };
1222 let mut d = open(&path);1200 let mut d = open(&path);
1223 let v = d1201 let v = d
1224 .streams()1202 .streams()
crates/ec-mpegts/tests/it/truehd.rsmodified+8 -26
@@ -2,11 +2,8 @@
2 //! through `ec-truehd` to the PCM ffmpeg decodes from the same file, sample for sample.2 //! through `ec-truehd` to the PCM ffmpeg decodes from the same file, sample for sample.
3 //!3 //!
4 //! The fixture is made at test time by ffmpeg's own TrueHD encoder (a 440 Hz sine,4 //! 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.
7 5
8 use std::path::Path;6 use std::path::Path;
9-use std::process::Command;
10 7
11 use crate::common::*;8 use crate::common::*;
12 use ec_core::registry::Demuxer;9 use ec_core::registry::Demuxer;
@@ -14,7 +11,7 @@ use ec_core::{CodecId, MediaParameters};
14 use ec_truehd::{AccessUnitHeader, TrueHdDecoder};11 use ec_truehd::{AccessUnitHeader, TrueHdDecoder};
15 12
16 /// Stereo 48 kHz TrueHD in M2TS-style TS, as ffmpeg writes it (stream type 0x83).13 /// 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 {
18 let a = [15 let a = [
19 "-f",16 "-f",
20 "lavfi",17 "lavfi",
@@ -36,7 +33,7 @@ fn truehd_ts(name: &str, channels: &str) -> Option<std::path::PathBuf> {
36 33
37 /// ffmpeg's decode of the first audio stream as interleaved S32 little-endian.34 /// ffmpeg's decode of the first audio stream as interleaved S32 little-endian.
38 fn ffmpeg_s32le(path: &Path) -> Vec<i32> {35 fn ffmpeg_s32le(path: &Path) -> Vec<i32> {
39- let out = Command::new("ffmpeg")36+ let out = ec_testkit::ffmpeg()
40 .args(["-v", "error", "-nostdin", "-i"])37 .args(["-v", "error", "-nostdin", "-i"])
41 .arg(path)38 .arg(path)
42 .args(["-map", "0:a:0", "-f", "s32le", "-"])39 .args(["-map", "0:a:0", "-f", "s32le", "-"])
@@ -62,13 +59,8 @@ fn s32le(bytes: &[u8]) -> Vec<i32> {
62 59
63 #[test]60 #[test]
64 fn truehd_in_ts_decodes_sample_exact_to_ffmpeg() {61 fn truehd_in_ts_decodes_sample_exact_to_ffmpeg() {
65- if !have_ffmpeg() {62+ for (name, channels, want) in [("truehd_sine_2ch.ts", "2", 2usize)] {
66- return;63+ let path = truehd_ts(name, channels);
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- };
72 let mut d = open(&path);64 let mut d = open(&path);
73 let all = read_all(&mut d);65 let all = read_all(&mut d);
74 let stream = d66 let stream = d
@@ -123,12 +115,7 @@ fn truehd_in_ts_decodes_sample_exact_to_ffmpeg() {
123 fn truehd_packets_match_the_container_packet_form() {115 fn truehd_packets_match_the_container_packet_form() {
124 // The access units in the TS are the same bytes ffmpeg's stream copy writes out116 // The access units in the TS are the same bytes ffmpeg's stream copy writes out
125 // (the MP4 and Matroska demuxers hand over the same form).117 // (the MP4 and Matroska demuxers hand over the same form).
126- if !have_ffmpeg() {118+ let path = truehd_ts("truehd_sine_2ch.ts", "2");
127- return;
128- }
129- let Some(path) = truehd_ts("truehd_sine_2ch.ts", "2") else {
130- return;
131- };
132 let mut d = open(&path);119 let mut d = open(&path);
133 let all = read_all(&mut d);120 let all = read_all(&mut d);
134 let stream = d121 let stream = d
@@ -142,7 +129,7 @@ fn truehd_packets_match_the_container_packet_form() {
142 .filter(|p| p.stream == stream)129 .filter(|p| p.stream == stream)
143 .flat_map(|p| p.data)130 .flat_map(|p| p.data)
144 .collect();131 .collect();
145- let o = Command::new("ffmpeg")132+ let o = ec_testkit::ffmpeg()
146 .args(["-v", "error", "-nostdin", "-i"])133 .args(["-v", "error", "-nostdin", "-i"])
147 .arg(&path)134 .arg(&path)
148 .args(["-map", "0:a:0", "-c", "copy", "-f", "truehd", "-"])135 .args(["-map", "0:a:0", "-c", "copy", "-f", "truehd", "-"])
@@ -263,10 +250,7 @@ fn ts5(prefix: u8, v: u64) -> [u8; 5] {
263 250
264 #[test]251 #[test]
265 fn ac3_core_interleaved_in_the_truehd_pid_is_dropped() {252 fn ac3_core_interleaved_in_the_truehd_pid_is_dropped() {
266- if !have_ffmpeg() {253+ let raw = fixture(
267- return;
268- }
269- let Some(raw) = fixture(
270 "truehd_sine_2ch.thd",254 "truehd_sine_2ch.thd",
271 &[255 &[
272 "-f",256 "-f",
@@ -284,9 +268,7 @@ fn ac3_core_interleaved_in_the_truehd_pid_is_dropped() {
284 "-f",268 "-f",
285 "truehd",269 "truehd",
286 ],270 ],
287- ) else {271+ );
288- return;
289- };
290 let aus = split_aus(&std::fs::read(&raw).unwrap());272 let aus = split_aus(&std::fs::read(&raw).unwrap());
291 assert!(aus.len() > 8, "enough access units");273 assert!(aus.len() > 8, "enough access units");
292 274
crates/ec-ogg/Cargo.tomlmodified+3 -0
@@ -8,3 +8,6 @@ authors.workspace = true
8 8
9 [dependencies]9 [dependencies]
10 ec-core.workspace = true10 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
14 14
15 FUZZ_DIR=$(cd -- "$(dirname -- "$0")" && pwd)15 FUZZ_DIR=$(cd -- "$(dirname -- "$0")" && pwd)
16 ROOT=$(cd -- "$FUZZ_DIR/../../.." && pwd)16 ROOT=$(cd -- "$FUZZ_DIR/../../.." && pwd)
17-AUDIO="$ROOT/fixtures/audio"17+AUDIO="${EC_FIXTURES:-$ROOT/fixtures}/audio"
18-VORBIS="$ROOT/fixtures/vectors/vorbis-xiph"18+VORBIS="${EC_FIXTURES:-$ROOT/fixtures}/vectors/vorbis-xiph"
19-[ -d "$AUDIO" ] || { echo "seed.sh: $AUDIO missing; run scripts/link-fixtures.sh" >&2; exit 2; }19+[ -d "$AUDIO" ] || { echo "seed.sh: $AUDIO missing; run scripts/fixtures.sh" >&2; exit 2; }
20 20
21 CORPUS="$FUZZ_DIR/corpus"21 CORPUS="$FUZZ_DIR/corpus"
22 mkdir -p "$CORPUS"/{page_parse,demux,demux_raw,mapping,roundtrip}22 mkdir -p "$CORPUS"/{page_parse,demux,demux_raw,mapping,roundtrip}
crates/ec-ogg/tests/ogg.rsmodified+13 -37
@@ -11,7 +11,6 @@
11 11
12 use std::io::Cursor;12 use std::io::Cursor;
13 use std::path::{Path, PathBuf};13 use std::path::{Path, PathBuf};
14-use std::process::Command;
15 14
16 use ec_core::{15 use ec_core::{
17 Buf, CodecId, CodecParameters, Demuxer, MediaParameters, Muxer, Packet, PacketFlags, SeekMode,16 Buf, CodecId, CodecParameters, Demuxer, MediaParameters, Muxer, Packet, PacketFlags, SeekMode,
@@ -29,7 +28,7 @@ fn name_of(p: &std::path::Path) -> String {
29 }28 }
30 29
31 fn fixtures() -> PathBuf {30 fn fixtures() -> PathBuf {
32- Path::new(env!("CARGO_MANIFEST_DIR")).join("../../fixtures/audio")31+ ec_testkit::root().join("audio")
33 }32 }
34 33
35 /// Working directory keyed by test name: these tests are threads of one34 /// Working directory keyed by test name: these tests are threads of one
@@ -43,9 +42,7 @@ fn workdir(test: &str) -> PathBuf {
43 42
44 /// Every Ogg fixture on disk, sorted so the table reads the same every run.43 /// Every Ogg fixture on disk, sorted so the table reads the same every run.
45 fn ogg_fixtures() -> Vec<PathBuf> {44 fn ogg_fixtures() -> Vec<PathBuf> {
46- let Ok(entries) = std::fs::read_dir(fixtures()) else {45+ let entries = std::fs::read_dir(fixtures()).expect("fixtures/audio (run scripts/fixtures.sh)");
47- return Vec::new();
48- };
49 let mut out: Vec<PathBuf> = entries46 let mut out: Vec<PathBuf> = entries
50 .flatten()47 .flatten()
51 .map(|e| e.path())48 .map(|e| e.path())
@@ -63,7 +60,7 @@ fn ogg_fixtures() -> Vec<PathBuf> {
63 /// Audio packets ffprobe counts in a file — header packets excluded, which is60 /// Audio packets ffprobe counts in a file — header packets excluded, which is
64 /// also what this demuxer hands out.61 /// also what this demuxer hands out.
65 fn ffprobe_packets(path: &Path) -> u64 {62 fn ffprobe_packets(path: &Path) -> u64 {
66- let out = Command::new("ffprobe")63+ let out = ec_testkit::ffprobe()
67 .args([64 .args([
68 "-v",65 "-v",
69 "error",66 "error",
@@ -86,7 +83,7 @@ fn ffprobe_packets(path: &Path) -> u64 {
86 83
87 /// ffprobe's own duration for the file, in seconds.84 /// ffprobe's own duration for the file, in seconds.
88 fn ffprobe_duration(path: &Path) -> f64 {85 fn ffprobe_duration(path: &Path) -> f64 {
89- let out = Command::new("ffprobe")86+ let out = ec_testkit::ffprobe()
90 .args([87 .args([
91 "-v",88 "-v",
92 "error",89 "error",
@@ -104,7 +101,7 @@ fn ffprobe_duration(path: &Path) -> f64 {
104 /// Decode a file to raw 32-bit float samples with ffmpeg. Errors are fatal: an101 /// Decode a file to raw 32-bit float samples with ffmpeg. Errors are fatal: an
105 /// unreadable file is the failure being tested for.102 /// unreadable file is the failure being tested for.
106 fn decode_pcm(path: &Path) -> Vec<u8> {103 fn decode_pcm(path: &Path) -> Vec<u8> {
107- let out = Command::new("ffmpeg")104+ let out = ec_testkit::ffmpeg()
108 .args(["-v", "error", "-i"])105 .args(["-v", "error", "-i"])
109 .arg(path)106 .arg(path)
110 .args(["-f", "f32le", "-"])107 .args(["-f", "f32le", "-"])
@@ -121,7 +118,7 @@ fn decode_pcm(path: &Path) -> Vec<u8> {
121 118
122 /// ffprobe with errors escalated: the structural verdict on a file we wrote.119 /// ffprobe with errors escalated: the structural verdict on a file we wrote.
123 fn ffprobe_clean(path: &Path) -> String {120 fn ffprobe_clean(path: &Path) -> String {
124- let out = Command::new("ffprobe")121+ let out = ec_testkit::ffprobe()
125 .args([122 .args([
126 "-v",123 "-v",
127 "error",124 "error",
@@ -161,10 +158,6 @@ fn demux_all(path: &Path) -> (Vec<StreamInfo>, Vec<Packet>, u64) {
161 #[test]158 #[test]
162 fn demuxes_every_fixture_to_eof() {159 fn demuxes_every_fixture_to_eof() {
163 let files = ogg_fixtures();160 let files = ogg_fixtures();
164- if files.is_empty() {
165- eprintln!("fixtures/audio absent (gitignored) — skipping");
166- return;
167- }
168 println!(161 println!(
169 "{:<28} {:>8} {:>8} {:>10} {:>10}",162 "{:<28} {:>8} {:>8} {:>10} {:>10}",
170 "file", "ours", "ffprobe", "dur", "ffprobe"163 "file", "ours", "ffprobe", "dur", "ffprobe"
@@ -320,10 +313,6 @@ fn remux_case(path: &Path, page_target: Option<usize>) {
320 #[test]313 #[test]
321 fn remuxes_every_fixture_bit_identically() {314 fn remuxes_every_fixture_bit_identically() {
322 let files = ogg_fixtures();315 let files = ogg_fixtures();
323- if files.is_empty() {
324- eprintln!("fixtures/audio absent (gitignored) — skipping");
325- return;
326- }
327 for path in &files {316 for path in &files {
328 remux_case(path, None);317 remux_case(path, None);
329 }318 }
@@ -334,13 +323,10 @@ fn remuxes_every_fixture_bit_identically() {
334 #[test]323 #[test]
335 fn page_size_does_not_change_the_audio() {324 fn page_size_does_not_change_the_audio() {
336 let files = ogg_fixtures();325 let files = ogg_fixtures();
337- let Some(path) = files326+ let path = files
338 .iter()327 .iter()
339 .find(|p| name_of(p).contains("vorbis-ogg-stereo-48000"))328 .find(|p| name_of(p).contains("vorbis-ogg-stereo-48000"))
340- else {329+ .expect("ogg fixture");
341- eprintln!("fixtures absent — skipping");
342- return;
343- };
344 remux_case(path, Some(1));330 remux_case(path, Some(1));
345 remux_case(path, Some(1 << 20));331 remux_case(path, Some(1 << 20));
346 }332 }
@@ -348,13 +334,10 @@ fn page_size_does_not_change_the_audio() {
348 #[test]334 #[test]
349 fn damage_costs_one_page_and_no_more() {335 fn damage_costs_one_page_and_no_more() {
350 let files = ogg_fixtures();336 let files = ogg_fixtures();
351- let Some(path) = files337+ let path = files
352 .iter()338 .iter()
353 .find(|p| name_of(p).contains("vorbis-ogg-stereo-44100"))339 .find(|p| name_of(p).contains("vorbis-ogg-stereo-44100"))
354- else {340+ .expect("ogg fixture");
355- eprintln!("fixtures absent — skipping");
356- return;
357- };
358 let (_, clean, _) = demux_all(path);341 let (_, clean, _) = demux_all(path);
359 let bytes = std::fs::read(path).unwrap();342 let bytes = std::fs::read(path).unwrap();
360 343
@@ -407,10 +390,6 @@ fn damage_costs_one_page_and_no_more() {
407 #[test]390 #[test]
408 fn seeks_land_at_or_before_the_target() {391 fn seeks_land_at_or_before_the_target() {
409 let files = ogg_fixtures();392 let files = ogg_fixtures();
410- if files.is_empty() {
411- eprintln!("fixtures absent — skipping");
412- return;
413- }
414 for path in files.iter().filter(|p| {393 for path in files.iter().filter(|p| {
415 let n = p.to_string_lossy().to_string();394 let n = p.to_string_lossy().to_string();
416 n.contains("stereo-48000") || n.contains("5.1-44100")395 n.contains("stereo-48000") || n.contains("5.1-44100")
@@ -465,15 +444,12 @@ fn seeks_land_at_or_before_the_target() {
465 #[test]444 #[test]
466 fn reads_flac_in_ogg() {445 fn reads_flac_in_ogg() {
467 let files = ogg_fixtures();446 let files = ogg_fixtures();
468- let Some(source) = files447+ let source = files
469 .iter()448 .iter()
470 .find(|p| name_of(p).contains("vorbis-ogg-stereo-44100"))449 .find(|p| name_of(p).contains("vorbis-ogg-stereo-44100"))
471- else {450+ .expect("ogg fixture");
472- eprintln!("fixtures absent — skipping");
473- return;
474- };
475 let path = workdir("flac").join("flac-in.ogg");451 let path = workdir("flac").join("flac-in.ogg");
476- let made = Command::new("ffmpeg")452+ let made = ec_testkit::ffmpeg()
477 .args(["-v", "error", "-y", "-i"])453 .args(["-v", "error", "-y", "-i"])
478 .arg(source)454 .arg(source)
479 .args(["-c:a", "flac", "-f", "ogg"])455 .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.
4 //!1 //!
5 //! Per file the oracle checks:2 //! Per file the oracle checks:
6 //! - packet count and every packet's size (ffprobe, audio stream 0);3 //! - packet count and every packet's size (ffprobe, audio stream 0);
@@ -31,25 +28,12 @@
31 //!28 //!
32 //! Scope: demux only. The decoded PCM is not compared here.29 //! Scope: demux only. The decoded PCM is not compared here.
33 //!30 //!
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
40 31
41-use std::path::{Path, PathBuf};32+use std::path::Path;
42-use std::process::{Command, Stdio};
43 33
44 use ec_core::Demuxer;34 use ec_core::Demuxer;
45 use ec_ogg::{Mapping, OggDemuxer, granule_of};35 use ec_ogg::{Mapping, OggDemuxer, granule_of};
46 36
47-/// One manifest row: the columns the sweep reads.
48-struct Entry {
49- path: PathBuf,
50- acodecs: String,
51-}
52-
53 /// One packet as ffprobe reports it.37 /// One packet as ffprobe reports it.
54 struct Probed {38 struct Probed {
55 pts: Option<i64>,39 pts: Option<i64>,
@@ -64,40 +48,6 @@ enum Verdict {
64 Failed(String),48 Failed(String),
65 }49 }
66 50
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-
101 /// Parses an ffprobe csv cell: `N/A` and blanks are absent.51 /// Parses an ffprobe csv cell: `N/A` and blanks are absent.
102 fn cell(s: &str) -> Option<i64> {52 fn cell(s: &str) -> Option<i64> {
103 let s = s.trim();53 let s = s.trim();
@@ -110,7 +60,7 @@ fn cell(s: &str) -> Option<i64> {
110 60
111 /// Audio stream 0's packets: header packets are not among them, as with ours.61 /// Audio stream 0's packets: header packets are not among them, as with ours.
112 fn ffprobe_packets(path: &Path) -> Result<Vec<Probed>, String> {62 fn ffprobe_packets(path: &Path) -> Result<Vec<Probed>, String> {
113- let out = Command::new("ffprobe")63+ let out = ec_testkit::ffprobe()
114 .args([64 .args([
115 "-v",65 "-v",
116 "error",66 "error",
@@ -145,7 +95,7 @@ fn ffprobe_packets(path: &Path) -> Result<Vec<Probed>, String> {
145 95
146 /// ffprobe's stated extradata size for audio stream 0.96 /// ffprobe's stated extradata size for audio stream 0.
147 fn ffprobe_extradata_size(path: &Path) -> Result<usize, String> {97 fn ffprobe_extradata_size(path: &Path) -> Result<usize, String> {
148- let out = Command::new("ffprobe")98+ let out = ec_testkit::ffprobe()
149 .args([99 .args([
150 "-v",100 "-v",
151 "error",101 "error",
@@ -168,7 +118,7 @@ fn ffprobe_extradata_size(path: &Path) -> Result<usize, String> {
168 118
169 /// ffmpeg's concatenated audio packet payloads, copied and not decoded.119 /// ffmpeg's concatenated audio packet payloads, copied and not decoded.
170 fn ffmpeg_payload(path: &Path) -> Result<Vec<u8>, String> {120 fn ffmpeg_payload(path: &Path) -> Result<Vec<u8>, String> {
171- let out = Command::new("ffmpeg")121+ let out = ec_testkit::ffmpeg()
172 .args(["-v", "error", "-i"])122 .args(["-v", "error", "-i"])
173 .arg(path)123 .arg(path)
174 .args(["-map", "0:a:0", "-c", "copy", "-f", "data", "-"])124 .args(["-map", "0:a:0", "-c", "copy", "-f", "data", "-"])
@@ -355,63 +305,11 @@ fn vorbis_header_problem(block: &[u8]) -> Option<String> {
355 None305 None
356 }306 }
357 307
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-
364 #[test]308 #[test]
365-#[ignore = "sweeps the PERSONAL media library (fixtures/real-library-manifest.tsv, ogg rows) through ffmpeg; local only: run with --ignored."]
366 fn real_library_ogg_streams_match_ffmpeg() {309 fn real_library_ogg_streams_match_ffmpeg() {
367- if !have("ffmpeg") || !have("ffprobe") {310+ let path = ec_testkit::fixture("open/sintel_trailer-480p.ogv");
368- eprintln!("skipped: ffmpeg and ffprobe are required to sweep the library");311+ match check_file(&path) {
369- return;312+ Verdict::Match(s) => eprintln!("{}: match: {s}", path.display()),
370- }313+ Verdict::Refused(e) | Verdict::Failed(e) => panic!("{}: {e}", path.display()),
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;
381 }314 }
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- );
417 }315 }
crates/ec-probe/Cargo.tomlmodified+3 -0
@@ -22,3 +22,6 @@ ec-opus = { workspace = true }
22 ec-riff = { workspace = true }22 ec-riff = { workspace = true }
23 ec-truehd = { workspace = true }23 ec-truehd = { workspace = true }
24 ec-vorbis = { workspace = true }24 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 {
1327 /// s: `1024` samples read straight off as `1024` one-millisecond ticks).1327 /// s: `1024` samples read straight off as `1024` one-millisecond ticks).
1328 #[test]1328 #[test]
1329 fn duration_converts_initial_padding_out_of_sample_units() {1329 fn duration_converts_initial_padding_out_of_sample_units() {
1330- let path = Path::new(env!("CARGO_MANIFEST_DIR"))1330+ let reader = Reader::open(ec_testkit::fixture("audio/aac-mka-stereo-48000.mka")).unwrap();
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();
1336 let d = reader.duration().expect("a stated duration").as_secs_f64();1331 let d = reader.duration().expect("a stated duration").as_secs_f64();
1337 assert!((d - 3.0).abs() < 0.1, "duration {d}, want ~3.0s");1332 assert!((d - 3.0).abs() < 0.1, "duration {d}, want ~3.0s");
1338 }1333 }
crates/ec-probe/tests/dts.rsmodified+7 -22
@@ -4,17 +4,12 @@
4 //! and channels, and hand back the stream's bytes frame by frame.4 //! and channels, and hand back the stream's bytes frame by frame.
5 5
6 use std::path::{Path, PathBuf};6 use std::path::{Path, PathBuf};
7-use std::process::Command;
8 7
9 use ec_core::CodecId;8 use ec_core::CodecId;
10 use ec_core::registry::{MediaType, SeekMode};9 use ec_core::registry::{MediaType, SeekMode};
11 use ec_core::timebase::{TimeBase, Timestamp};10 use ec_core::timebase::{TimeBase, Timestamp};
12 use ec_probe::{Format, Reader};11 use ec_probe::{Format, Reader};
13 12
14-fn required() -> bool {
15- std::env::var_os("EC_REQUIRE_FIXTURES").is_some_and(|v| !v.is_empty() && v != "0")
16-}
17-
18 fn work() -> PathBuf {13 fn work() -> PathBuf {
19 let d = std::env::temp_dir().join(format!("ec-probe-dts-{}", std::process::id()));14 let d = std::env::temp_dir().join(format!("ec-probe-dts-{}", std::process::id()));
20 std::fs::create_dir_all(&d).unwrap();15 std::fs::create_dir_all(&d).unwrap();
@@ -22,7 +17,7 @@ fn work() -> PathBuf {
22 }17 }
23 18
24 fn ffmpeg(args: &[&str], out: &Path) -> bool {19 fn ffmpeg(args: &[&str], out: &Path) -> bool {
25- Command::new("ffmpeg")20+ ec_testkit::ffmpeg()
26 .args(["-v", "error", "-y"])21 .args(["-v", "error", "-y"])
27 .args(args)22 .args(args)
28 .arg(out)23 .arg(out)
@@ -31,7 +26,7 @@ fn ffmpeg(args: &[&str], out: &Path) -> bool {
31 }26 }
32 27
33 /// A raw DTS stream of `channels` channels, 0.5 s at 48 kHz.28 /// 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> {
35 static LOCK: std::sync::Mutex<()> = std::sync::Mutex::new(());30 static LOCK: std::sync::Mutex<()> = std::sync::Mutex::new(());
36 let _guard = LOCK.lock().unwrap_or_else(|e| e.into_inner());31 let _guard = LOCK.lock().unwrap_or_else(|e| e.into_inner());
37 let path = work().join(format!("{channels}.dts"));32 let path = work().join(format!("{channels}.dts"));
@@ -50,12 +45,8 @@ fn raw_dts(channels: &str) -> Option<Vec<u8>> {
50 ],45 ],
51 &path,46 &path,
52 );47 );
53- if !ok {48+ assert!(ok, "ffmpeg cannot make a DTS fixture");
54- assert!(!required(), "ffmpeg cannot make a DTS fixture");49+ std::fs::read(&path).unwrap()
55- eprintln!("skip: no ffmpeg with the dca encoder");
56- return None;
57- }
58- std::fs::read(&path).ok()
59 }50 }
60 51
61 fn wav_pcm_tagged(dts: &[u8], rate: u32) -> Vec<u8> {52 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])
109 #[test]100 #[test]
110 fn raw_dts_stereo_and_51() {101 fn raw_dts_stereo_and_51() {
111 for (ch, n) in [("2", 2), ("6", 6)] {102 for (ch, n) in [("2", 2), ("6", 6)] {
112- let Some(raw) = raw_dts(ch) else {103+ let raw = raw_dts(ch);
113- return;
114- };
115 assert_eq!(&raw[..4], &[0x7F, 0xFE, 0x80, 0x01]);104 assert_eq!(&raw[..4], &[0x7F, 0xFE, 0x80, 0x01]);
116 check(&raw, &format!("raw{ch}.dts"), Format::Dts, n, &raw);105 check(&raw, &format!("raw{ch}.dts"), Format::Dts, n, &raw);
117 }106 }
@@ -119,9 +108,7 @@ fn raw_dts_stereo_and_51() {
119 108
120 #[test]109 #[test]
121 fn raw_dts_little_endian() {110 fn raw_dts_little_endian() {
122- let Some(raw) = raw_dts("2") else {111+ let raw = raw_dts("2");
123- return;
124- };
125 let mut le = raw.clone();112 let mut le = raw.clone();
126 for p in le.as_chunks_mut::<2>().0.iter_mut() {113 for p in le.as_chunks_mut::<2>().0.iter_mut() {
127 p.swap(0, 1);114 p.swap(0, 1);
@@ -131,9 +118,7 @@ fn raw_dts_little_endian() {
131 118
132 #[test]119 #[test]
133 fn dts_in_wav_pcm_tag_and_2001_tag() {120 fn dts_in_wav_pcm_tag_and_2001_tag() {
134- let Some(raw) = raw_dts("2") else {121+ let raw = raw_dts("2");
135- return;
136- };
137 check(122 check(
138 &wav_pcm_tagged(&raw, 48_000),123 &wav_pcm_tagged(&raw, 48_000),
139 "pcm.wav",124 "pcm.wav",
crates/ec-probe/tests/legacy_audio.rsmodified+2 -8
@@ -1,19 +1,13 @@
1 //! IMA/MS ADPCM and G.711 through the probe (Reader + AudioDecoder) from1 //! IMA/MS ADPCM and G.711 through the probe (Reader + AudioDecoder) from
2 //! ffmpeg-made WAV, AVI and MOV files, compared with ffmpeg's s16 decode.2 //! ffmpeg-made WAV, AVI and MOV files, compared with ffmpeg's s16 decode.
3-//! Skips without ffmpeg unless `EC_REQUIRE_FIXTURES=1`.
4 3
5 use std::path::PathBuf;4 use std::path::PathBuf;
6-use std::process::Command;
7 5
8 use ec_core::registry::MediaType;6 use ec_core::registry::MediaType;
9 use ec_probe::{AudioDecoder, Reader};7 use ec_probe::{AudioDecoder, Reader};
10 8
11 #[test]9 #[test]
12 fn legacy_audio_decodes_through_the_probe() {10 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- }
17 let dir: PathBuf = std::env::temp_dir().join(format!("ec-probe-legacy-{}", std::process::id()));11 let dir: PathBuf = std::env::temp_dir().join(format!("ec-probe-legacy-{}", std::process::id()));
18 std::fs::create_dir_all(&dir).expect("tmp");12 std::fs::create_dir_all(&dir).expect("tmp");
19 let mut n = 0;13 let mut n = 0;
@@ -30,7 +24,7 @@ fn legacy_audio_decodes_through_the_probe() {
30 ] {24 ] {
31 for ch in ["1", "2"] {25 for ch in ["1", "2"] {
32 let path = dir.join(format!("{enc}-{ch}.{ext}"));26 let path = dir.join(format!("{enc}-{ch}.{ext}"));
33- let o = Command::new("ffmpeg")27+ let o = ec_testkit::ffmpeg()
34 .args(["-nostdin", "-y", "-v", "error", "-f", "lavfi", "-i"])28 .args(["-nostdin", "-y", "-v", "error", "-f", "lavfi", "-i"])
35 .arg("aevalsrc='0.6*sin(2*PI*440*t)+0.2*sin(2*PI*3000*t*t)':s=16000:d=1.1")29 .arg("aevalsrc='0.6*sin(2*PI*440*t)+0.2*sin(2*PI*3000*t*t)':s=16000:d=1.1")
36 .args(["-ac", ch, "-c:a", enc])30 .args(["-ac", ch, "-c:a", enc])
@@ -38,7 +32,7 @@ fn legacy_audio_decodes_through_the_probe() {
38 .output()32 .output()
39 .expect("ffmpeg");33 .expect("ffmpeg");
40 assert!(o.status.success(), "{}", String::from_utf8_lossy(&o.stderr));34 assert!(o.status.success(), "{}", String::from_utf8_lossy(&o.stderr));
41- let want = Command::new("ffmpeg")35+ let want = ec_testkit::ffmpeg()
42 .args(["-nostdin", "-v", "error", "-i"])36 .args(["-nostdin", "-v", "error", "-i"])
43 .arg(&path)37 .arg(&path)
44 .args(["-f", "f32le", "-"])38 .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.
7 1
8 use std::fs::File;2 use std::fs::File;
9 use std::io::{Read, Seek, SeekFrom};3 use std::io::{Read, Seek, SeekFrom};
10-use std::path::{Path, PathBuf};4+use std::path::Path;
11-use std::process::Command;
12 use std::sync::{5 use std::sync::{
13 Arc,6 Arc,
14 atomic::{AtomicU64, Ordering},7 atomic::{AtomicU64, Ordering},
@@ -19,55 +12,6 @@ use ec_core::registry::{CodecId, MediaType, SeekMode};
19 use ec_core::timebase::{TimeBase, Timestamp};12 use ec_core::timebase::{TimeBase, Timestamp};
20 use ec_probe::Reader;13 use ec_probe::Reader;
21 14
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-
71 fn decode_window(reader: &mut Reader, stream: u32, secs: f64) -> Result<Vec<f32>, String> {15 fn decode_window(reader: &mut Reader, stream: u32, secs: f64) -> Result<Vec<f32>, String> {
72 let mut decoder = reader.make_decoder(stream).map_err(|e| e.to_string())?;16 let mut decoder = reader.make_decoder(stream).map_err(|e| e.to_string())?;
73 let channels = decoder.channels().max(1);17 let channels = decoder.channels().max(1);
@@ -93,7 +37,7 @@ fn decode_window(reader: &mut Reader, stream: u32, secs: f64) -> Result<Vec<f32>
93 }37 }
94 38
95 fn reference_seek_window(path: &Path, at: f64) -> Vec<f32> {39 fn reference_seek_window(path: &Path, at: f64) -> Vec<f32> {
96- let out = Command::new("ffmpeg")40+ let out = ec_testkit::ffmpeg()
97 .args(["-v", "error", "-ss", &format!("{at:.6}"), "-i"])41 .args(["-v", "error", "-ss", &format!("{at:.6}"), "-i"])
98 .arg(path)42 .arg(path)
99 .args([43 .args([
@@ -139,35 +83,6 @@ impl Seek for CountedFile {
139 }83 }
140 }84 }
141 85
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-
171 fn assert_avi_index_is_bounded(path: &Path) {86 fn assert_avi_index_is_bounded(path: &Path) {
172 let file_size = std::fs::metadata(path).expect("AVI metadata").len();87 let file_size = std::fs::metadata(path).expect("AVI metadata").len();
173 let index_len = ec_riff::AviReader::new(File::open(path).expect("open AVI"))88 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) {
408 }323 }
409 }324 }
410 325
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.
450 #[test]326 #[test]
451-fn a_real_library_sweep() {327+fn avi_audio_chunks_end_cleanly() {
452- let files = manifest();328+ let path = ec_testkit::fixture("derived/sintel720.avi");
453- if files.is_empty() {329+ let mut reader = Reader::open(&path).expect("AVI opens");
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");
644 let audio = reader330 let audio = reader
645 .default_stream(MediaType::Audio)331 .default_stream(MediaType::Audio)
646 .expect("AVI audio stream")332 .expect("AVI audio stream")
647 .index;333 .index;
648- let (packets, frames, ours) =334+ let (packets, frames, _) = decode_stream_to_eof(&mut reader, audio, false)
649- decode_stream_to_eof(&mut reader, audio, true).expect("AVI decodes to EOF");335+ .unwrap_or_else(|e| panic!("{}: {e}", path.display()));
650- assert!(packets > 0, "no packets");336+ assert!(packets > 0, "{}: no audio packets", path.display());
651- assert!(frames > 0, "no decoded frames");337+ assert!(frames > 0, "{}: no decoded audio", path.display());
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- }
687 }338 }
688 339
689 #[test]340 #[test]
690-fn avi_seek_matches_reference_decoder_on_synthetic_mp3() {341+fn avi_seek_matches_reference_decoder() {
691- let Some(path) = synthetic_mp3_avi() else {342+ assert_avi_seeks_match_reference(&ec_testkit::fixture("derived/sintel720.avi"));
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()
761 }343 }
762 344
763 /// Cover-art (`APIC`) ID3v2 tags shipped by real rippers/taggers put a whole345 /// 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> {
767 /// the same first second, not just "it opened".349 /// the same first second, not just "it opened".
768 #[test]350 #[test]
769 fn a_cover_art_tagged_mp3_opens() {351 fn a_cover_art_tagged_mp3_opens() {
770- let path = Path::new("/home/user/Music/reeli.mp3");352+ let path = ec_testkit::fixture("audio/cover-mp3-stereo-44100.mp3");
771- if !path.exists() {353+ let mut reader = Reader::open(&path).expect("open");
772- eprintln!("file not present, skipping");
773- return;
774- }
775- let mut reader = Reader::open(path).expect("open");
776 let audio = reader354 let audio = reader
777 .default_stream(MediaType::Audio)355 .default_stream(MediaType::Audio)
778 .cloned()356 .cloned()
@@ -804,7 +382,7 @@ fn a_cover_art_tagged_mp3_opens() {
804 let ours = &ours[lead_in as usize..];382 let ours = &ours[lead_in as usize..];
805 assert!(ours.len() as u32 >= rate / 2, "decoded too little audio");383 assert!(ours.len() as u32 >= rate / 2, "decoded too little audio");
806 384
807- let out = Command::new("ffmpeg")385+ let out = ec_testkit::ffmpeg()
808 .args(["-v", "error", "-t", "1", "-i"])386 .args(["-v", "error", "-t", "1", "-i"])
809 .arg(path)387 .arg(path)
810 .args(["-map", "0:a:0", "-f", "f32le", "-acodec", "pcm_f32le", "-"])388 .args(["-map", "0:a:0", "-f", "f32le", "-acodec", "pcm_f32le", "-"])
crates/ec-probe/tests/matrix.rsmodified+7 -28
@@ -3,23 +3,20 @@
3 //! where it says it does after a hundred random seeks — on one reader.3 //! where it says it does after a hundred random seeks — on one reader.
4 //!4 //!
5 //! Oracle is ffmpeg/ffprobe (labelled as such: this is not a conformance5 //! 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.
8 6
9 use std::path::{Path, PathBuf};7 use std::path::{Path, PathBuf};
10-use std::process::Command;
11 8
12 use ec_core::registry::{MediaType, SeekMode};9 use ec_core::registry::{MediaType, SeekMode};
13 use ec_core::timebase::{TimeBase, Timestamp};10 use ec_core::timebase::{TimeBase, Timestamp};
14 use ec_probe::{Format, Reader};11 use ec_probe::{Format, Reader};
15 12
16 fn fixtures() -> PathBuf {13 fn fixtures() -> PathBuf {
17- Path::new(env!("CARGO_MANIFEST_DIR")).join("../../fixtures/audio")14+ ec_testkit::root().join("audio")
18 }15 }
19 16
20 /// `ffprobe` on one entry of the first audio stream.17 /// `ffprobe` on one entry of the first audio stream.
21 fn probe(path: &Path, args: &[&str]) -> String {18 fn probe(path: &Path, args: &[&str]) -> String {
22- let out = Command::new("ffprobe")19+ let out = ec_testkit::ffprobe()
23 .args(["-v", "error", "-select_streams", "a:0"])20 .args(["-v", "error", "-select_streams", "a:0"])
24 .args(args)21 .args(args)
25 .args(["-of", "default=nw=1:nk=1"])22 .args(["-of", "default=nw=1:nk=1"])
@@ -49,7 +46,7 @@ fn ffprobe_packets(path: &Path) -> u64 {
49 46
50 /// Sample frames ffmpeg decodes out of the first audio stream.47 /// Sample frames ffmpeg decodes out of the first audio stream.
51 fn ffmpeg_frames(path: &Path, channels: usize) -> u64 {48 fn ffmpeg_frames(path: &Path, channels: usize) -> u64 {
52- let out = Command::new("ffmpeg")49+ let out = ec_testkit::ffmpeg()
53 .args(["-nostdin", "-v", "error", "-i"])50 .args(["-nostdin", "-v", "error", "-i"])
54 .arg(path)51 .arg(path)
55 .args(["-map", "0:a:0", "-f", "f32le", "-"])52 .args(["-map", "0:a:0", "-f", "f32le", "-"])
@@ -116,9 +113,6 @@ fn every_fixture_probes_decodes_and_counts() {
116 let mut rows = Vec::new();113 let mut rows = Vec::new();
117 for &(name, format, codec) in MATRIX {114 for &(name, format, codec) in MATRIX {
118 let path = fixtures().join(name);115 let path = fixtures().join(name);
119- if !path.exists() {
120- continue;
121- }
122 let mut reader = Reader::open(&path).unwrap_or_else(|e| panic!("{name}: {e}"));116 let mut reader = Reader::open(&path).unwrap_or_else(|e| panic!("{name}: {e}"));
123 assert_eq!(reader.format(), format, "{name}: format");117 assert_eq!(reader.format(), format, "{name}: format");
124 let audio = reader118 let audio = reader
@@ -164,7 +158,7 @@ fn every_fixture_probes_decodes_and_counts() {
164 }158 }
165 assert!(159 assert!(
166 checked > 0,160 checked > 0,
167- "no fixtures found — run scripts/gen-fixtures.sh"161+ "no fixtures found — run scripts/fixtures.sh"
168 );162 );
169 eprintln!("probe matrix ({checked} files):\n{}", rows.join("\n"));163 eprintln!("probe matrix ({checked} files):\n{}", rows.join("\n"));
170 }164 }
@@ -176,9 +170,6 @@ fn a_hundred_random_seeks_land_where_they_say() {
176 let mut checked = 0;170 let mut checked = 0;
177 for &(name, _, codec) in MATRIX {171 for &(name, _, codec) in MATRIX {
178 let path = fixtures().join(name);172 let path = fixtures().join(name);
179- if !path.exists() {
180- continue;
181- }
182 let mut reader = Reader::open(&path).expect("open");173 let mut reader = Reader::open(&path).expect("open");
183 let audio = reader174 let audio = reader
184 .default_stream(MediaType::Audio)175 .default_stream(MediaType::Audio)
@@ -247,7 +238,7 @@ fn a_hundred_random_seeks_land_where_they_say() {
247 }238 }
248 assert!(239 assert!(
249 checked > 0,240 checked > 0,
250- "no fixtures found — run scripts/gen-fixtures.sh"241+ "no fixtures found — run scripts/fixtures.sh"
251 );242 );
252 eprintln!("100 random seeks each on {checked} files, one reader per file");243 eprintln!("100 random seeks each on {checked} files, one reader per file");
253 }244 }
@@ -259,9 +250,6 @@ fn cover_art_is_never_a_video_track() {
259 let mut checked = 0;250 let mut checked = 0;
260 for name in ["cover-mp3-stereo-44100.mp3", "cover-mp4-stereo-44100.m4a"] {251 for name in ["cover-mp3-stereo-44100.mp3", "cover-mp4-stereo-44100.m4a"] {
261 let path = fixtures().join(name);252 let path = fixtures().join(name);
262- if !path.exists() {
263- continue;
264- }
265 let reader = Reader::open(&path).expect("open");253 let reader = Reader::open(&path).expect("open");
266 let video: Vec<_> = reader254 let video: Vec<_> = reader
267 .streams()255 .streams()
@@ -278,16 +266,13 @@ fn cover_art_is_never_a_video_track() {
278 );266 );
279 checked += 1;267 checked += 1;
280 }268 }
281- assert!(checked > 0, "no cover-art fixtures — run gen-fixtures.sh");269+ assert!(checked > 0, "no cover-art fixtures — run scripts/fixtures.sh");
282 }270 }
283 271
284 /// The tags an ID3v2-tagged file carries come back off it.272 /// The tags an ID3v2-tagged file carries come back off it.
285 #[test]273 #[test]
286 fn id3_tags_come_off_a_real_file() {274 fn id3_tags_come_off_a_real_file() {
287 let path = fixtures().join("cover-mp3-stereo-44100.mp3");275 let path = fixtures().join("cover-mp3-stereo-44100.mp3");
288- if !path.exists() {
289- return;
290- }
291 let reader = Reader::open(&path).expect("open");276 let reader = Reader::open(&path).expect("open");
292 assert_eq!(reader.tags().title.as_deref(), Some("A Tone"));277 assert_eq!(reader.tags().title.as_deref(), Some("A Tone"));
293 assert_eq!(reader.tags().artist.as_deref(), Some("edith_codecs"));278 assert_eq!(reader.tags().artist.as_deref(), Some("edith_codecs"));
@@ -298,9 +283,6 @@ fn id3_tags_come_off_a_real_file() {
298 #[test]283 #[test]
299 fn a_mislabelled_file_opens_as_what_it_is() {284 fn a_mislabelled_file_opens_as_what_it_is() {
300 let src = fixtures().join("flac-stereo-48000.flac");285 let src = fixtures().join("flac-stereo-48000.flac");
301- if !src.exists() {
302- return;
303- }
304 let liar = std::env::temp_dir().join("ec-probe-liar.mp3");286 let liar = std::env::temp_dir().join("ec-probe-liar.mp3");
305 std::fs::copy(&src, &liar).expect("copy");287 std::fs::copy(&src, &liar).expect("copy");
306 let reader = Reader::open(&liar).expect("open");288 let reader = Reader::open(&liar).expect("open");
@@ -322,9 +304,6 @@ fn the_head_of_a_file_is_exact() {
322 let mut checked = 0;304 let mut checked = 0;
323 for &(name, _, codec) in MATRIX {305 for &(name, _, codec) in MATRIX {
324 let path = fixtures().join(name);306 let path = fixtures().join(name);
325- if !path.exists() {
326- continue;
327- }
328 let mut reader = Reader::open(&path).expect("open");307 let mut reader = Reader::open(&path).expect("open");
329 let audio = reader308 let audio = reader
330 .default_stream(MediaType::Audio)309 .default_stream(MediaType::Audio)
@@ -370,6 +349,6 @@ fn the_head_of_a_file_is_exact() {
370 }349 }
371 assert!(350 assert!(
372 checked > 0,351 checked > 0,
373- "no fixtures found — run scripts/gen-fixtures.sh"352+ "no fixtures found — run scripts/fixtures.sh"
374 );353 );
375 }354 }
crates/ec-riff/Cargo.tomlmodified+1 -0
@@ -11,5 +11,6 @@ ec-core.workspace = true
11 ec-dv = { path = "../ec-dv", version = "0.1.0" }11 ec-dv = { path = "../ec-dv", version = "0.1.0" }
12 12
13 [dev-dependencies]13 [dev-dependencies]
14+ec-testkit.workspace = true
14 ec-mjpeg.workspace = true15 ec-mjpeg.workspace = true
15 ec-mp4.workspace = true16 ec-mp4.workspace = true
crates/ec-riff/fuzz/seed.shmodified+2 -2
@@ -11,8 +11,8 @@
11 set -euo pipefail11 set -euo pipefail
12 12
13 FUZZ_DIR=$(cd -- "$(dirname -- "$0")" && pwd)13 FUZZ_DIR=$(cd -- "$(dirname -- "$0")" && pwd)
14-FIXTURES=$(cd -- "$FUZZ_DIR/../../.." && pwd)/fixtures/audio14+FIXTURES=${EC_FIXTURES:-$(cd -- "$FUZZ_DIR/../../.." && pwd)/fixtures}/audio
15-[ -d "$FIXTURES" ] || { echo "seed.sh: $FIXTURES missing; run scripts/link-fixtures.sh" >&2; exit 2; }15+[ -d "$FIXTURES" ] || { echo "seed.sh: $FIXTURES missing; run scripts/fixtures.sh" >&2; exit 2; }
16 16
17 WAVS=("$FIXTURES"/*.wav)17 WAVS=("$FIXTURES"/*.wav)
18 [ -e "${WAVS[0]}" ] || { echo "seed.sh: no *.wav fixtures in $FIXTURES" >&2; exit 2; }18 [ -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 @@
1 //! Uncompressed video in AVI and DV type-1 AVI (`iavs`). Media is synthetic, written by ffmpeg1 //! Uncompressed video in AVI and DV type-1 AVI (`iavs`). Media is synthetic, written by ffmpeg
2 //! at test time; ffmpeg cannot write type-1 AVI, so that wrapper is built here from a `.dv`2 //! 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.
4 3
5 use std::io::Cursor;4 use std::io::Cursor;
6 use std::path::PathBuf;5 use std::path::PathBuf;
7-use std::process::Command;
8 6
9 use ec_core::frame::Frame;7 use ec_core::frame::Frame;
10 use ec_core::registry::{CodecId, Decoder, Demuxer, MediaType, SeekMode};8 use ec_core::registry::{CodecId, Decoder, Demuxer, MediaType, SeekMode};
11 use ec_core::{Error, Timestamp};9 use ec_core::{Error, Timestamp};
12 use ec_riff::{AviDemuxer, RawVideoDecoder};10 use ec_riff::{AviDemuxer, RawVideoDecoder};
13-use crate::common::{ffmpeg, frame_bytes, tool_ok};11+use crate::common::{ffmpeg, frame_bytes};
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-}
26 12
27 fn scratch(tag: &str) -> PathBuf {13 fn scratch(tag: &str) -> PathBuf {
28 let base = std::env::var_os("TMPDIR")14 let base = std::env::var_os("TMPDIR")
@@ -34,7 +20,7 @@ fn scratch(tag: &str) -> PathBuf {
34 }20 }
35 21
36 fn ffmpeg_out(args: &[&str]) -> Vec<u8> {22 fn ffmpeg_out(args: &[&str]) -> Vec<u8> {
37- let o = Command::new("ffmpeg")23+ let o = ec_testkit::ffmpeg()
38 .args(["-v", "error", "-nostdin"])24 .args(["-v", "error", "-nostdin"])
39 .args(args)25 .args(args)
40 .output()26 .output()
@@ -104,9 +90,6 @@ fn expect_parity(path: &std::path::Path, bytes: Vec<u8>, ff_pix: &str) {
104 90
105 #[test]91 #[test]
106 fn raw_rgb_and_yuv_match_ffmpeg() {92 fn raw_rgb_and_yuv_match_ffmpeg() {
107- if !oracle() {
108- return;
109- }
110 for (tag, size, pix, vtag, ff) in [93 for (tag, size, pix, vtag, ff) in [
111 ("bgr24", "98x66", "bgr24", None, "bgr24"),94 ("bgr24", "98x66", "bgr24", None, "bgr24"),
112 ("bgr24odd", "97x65", "bgr24", None, "bgr24"),95 ("bgr24odd", "97x65", "bgr24", None, "bgr24"),
@@ -157,9 +140,6 @@ fn patch_chunks(bytes: &mut [u8], mut f: impl FnMut(&mut [u8])) {
157 140
158 #[test]141 #[test]
159 fn both_row_orders_are_upright() {142 fn both_row_orders_are_upright() {
160- if !oracle() {
161- return;
162- }
163 let (path, bytes) = make_raw("topdown", "98x66", "bgr24", None);143 let (path, bytes) = make_raw("topdown", "98x66", "bgr24", None);
164 let mut td = bytes.clone();144 let mut td = bytes.clone();
165 let strf = td.windows(4).position(|w| w == b"strf").unwrap() + 8;145 let strf = td.windows(4).position(|w| w == b"strf").unwrap() + 8;
@@ -363,17 +343,11 @@ fn dv_case(
363 343
364 #[test]344 #[test]
365 fn dv_type1_pal_splits_video_and_audio() {345 fn dv_type1_pal_splits_video_and_audio() {
366- if !oracle() {
367- return;
368- }
369 dv_case("dvpal", "720x576", "25", (1, 25), b"dvsd", "yuv420p");346 dv_case("dvpal", "720x576", "25", (1, 25), b"dvsd", "yuv420p");
370 }347 }
371 348
372 #[test]349 #[test]
373 fn dv_type1_ntsc_splits_video_and_audio() {350 fn dv_type1_ntsc_splits_video_and_audio() {
374- if !oracle() {
375- return;
376- }
377 dv_case(351 dv_case(
378 "dvntsc",352 "dvntsc",
379 "720x480",353 "720x480",
crates/ec-riff/tests/it/avi_video.rsmodified+2 -46
@@ -1,31 +1,14 @@
1 //! AVI audio+video demuxer tests. Real files are synthetic, written by ffmpeg at test time and1 //! AVI audio+video demuxer tests. Real files are synthetic, written by ffmpeg at test time and
2 //! checked against `ffprobe -show_packets`; the OpenDML, scan and vprp cases are hand-built2 //! 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.
4 3
5 use std::io::Cursor;4 use std::io::Cursor;
6 use std::path::PathBuf;5 use std::path::PathBuf;
7-use std::process::Command;
8 6
9 use ec_core::frame::{Interlace, VideoFrame};7 use ec_core::frame::{Interlace, VideoFrame};
10 use ec_core::registry::{CodecId, Demuxer, MediaType, SeekMode};8 use ec_core::registry::{CodecId, Demuxer, MediaType, SeekMode};
11 use ec_core::{Error, TimeBase, Timestamp};9 use ec_core::{Error, TimeBase, Timestamp};
12 use ec_riff::{AviDemuxer, AviIndexKind, is_avi};10 use ec_riff::{AviDemuxer, AviIndexKind, is_avi};
13-use crate::common::{chunk, ffmpeg, list, tool_ok};11+use crate::common::{chunk, ffmpeg, list};
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-}
29 12
30 fn scratch(tag: &str) -> PathBuf {13 fn scratch(tag: &str) -> PathBuf {
31 let base = std::env::var_os("TMPDIR")14 let base = std::env::var_os("TMPDIR")
@@ -62,7 +45,7 @@ struct Probe {
62 }45 }
63 46
64 fn probe(path: &PathBuf) -> Vec<Probe> {47 fn probe(path: &PathBuf) -> Vec<Probe> {
65- let out = Command::new("ffprobe")48+ let out = ec_testkit::ffprobe()
66 .args(["-v", "error", "-show_packets", "-show_data_hash", "adler32", "-of", "compact=p=0"])49 .args(["-v", "error", "-show_packets", "-show_data_hash", "adler32", "-of", "compact=p=0"])
67 .arg(path)50 .arg(path)
68 .output()51 .output()
@@ -162,9 +145,6 @@ fn assert_interleaved(got: &[Got]) {
162 145
163 #[test]146 #[test]
164 fn mjpeg_pcm() {147 fn mjpeg_pcm() {
165- if !oracle() {
166- return;
167- }
168 let (path, bytes) = make("mjpeg-pcm", &["-c:v", "mjpeg", "-q:v", "3"], &["-c:a", "pcm_s16le"]);148 let (path, bytes) = make("mjpeg-pcm", &["-c:v", "mjpeg", "-q:v", "3"], &["-c:a", "pcm_s16le"]);
169 assert!(is_avi(&bytes));149 assert!(is_avi(&bytes));
170 let mut d = AviDemuxer::new(Cursor::new(bytes.clone())).unwrap();150 let mut d = AviDemuxer::new(Cursor::new(bytes.clone())).unwrap();
@@ -212,9 +192,6 @@ fn compare_video_only(path: &PathBuf, bytes: &[u8]) -> Vec<Got> {
212 192
213 #[test]193 #[test]
214 fn mjpeg_mp3() {194 fn mjpeg_mp3() {
215- if !oracle() {
216- return;
217- }
218 let (path, bytes) = make("mjpeg-mp3", &["-c:v", "mjpeg"], &["-c:a", "libmp3lame"]);195 let (path, bytes) = make("mjpeg-mp3", &["-c:v", "mjpeg"], &["-c:a", "libmp3lame"]);
219 let d = AviDemuxer::new(Cursor::new(bytes.clone())).unwrap();196 let d = AviDemuxer::new(Cursor::new(bytes.clone())).unwrap();
220 assert_eq!(d.streams()[1].params.codec, CodecId::Mp3);197 assert_eq!(d.streams()[1].params.codec, CodecId::Mp3);
@@ -227,9 +204,6 @@ fn mjpeg_mp3() {
227 204
228 #[test]205 #[test]
229 fn h264_no_bframes_aac() {206 fn h264_no_bframes_aac() {
230- if !oracle() {
231- return;
232- }
233 let (path, bytes) = make(207 let (path, bytes) = make(
234 "h264",208 "h264",
235 &["-c:v", "libx264", "-bf", "0", "-g", "10", "-preset", "ultrafast"],209 &["-c:v", "libx264", "-bf", "0", "-g", "10", "-preset", "ultrafast"],
@@ -275,9 +249,6 @@ fn h264_no_bframes_aac() {
275 249
276 #[test]250 #[test]
277 fn h264_bframes_decode_order() {251 fn h264_bframes_decode_order() {
278- if !oracle() {
279- return;
280- }
281 let (path, bytes) = make(252 let (path, bytes) = make(
282 "h264b",253 "h264b",
283 &["-c:v", "libx264", "-bf", "2", "-g", "12", "-preset", "ultrafast"],254 &["-c:v", "libx264", "-bf", "2", "-g", "12", "-preset", "ultrafast"],
@@ -294,9 +265,6 @@ fn h264_bframes_decode_order() {
294 265
295 #[test]266 #[test]
296 fn mpeg2_mp2() {267 fn mpeg2_mp2() {
297- if !oracle() {
298- return;
299- }
300 let (path, bytes) = make("mpeg2", &["-c:v", "mpeg2video", "-g", "10", "-bf", "0"], &["-c:a", "mp2"]);268 let (path, bytes) = make("mpeg2", &["-c:v", "mpeg2video", "-g", "10", "-bf", "0"], &["-c:a", "mp2"]);
301 let d = AviDemuxer::new(Cursor::new(bytes.clone())).unwrap();269 let d = AviDemuxer::new(Cursor::new(bytes.clone())).unwrap();
302 assert_eq!(d.streams()[0].params.codec, CodecId::Mpeg2Video);270 assert_eq!(d.streams()[0].params.codec, CodecId::Mpeg2Video);
@@ -307,9 +275,6 @@ fn mpeg2_mp2() {
307 275
308 #[test]276 #[test]
309 fn raw_video_is_carried_and_unknown_layouts_refused_by_name() {277 fn raw_video_is_carried_and_unknown_layouts_refused_by_name() {
310- if !oracle() {
311- return;
312- }
313 for (tag, fmt) in [("yuyv", "yuyv422"), ("bgr24", "bgr24")] {278 for (tag, fmt) in [("yuyv", "yuyv422"), ("bgr24", "bgr24")] {
314 let (_, bytes) = make(tag, &["-c:v", "rawvideo", "-pix_fmt", fmt], &["-c:a", "pcm_s16le"]);279 let (_, bytes) = make(tag, &["-c:v", "rawvideo", "-pix_fmt", fmt], &["-c:a", "pcm_s16le"]);
315 let d = AviDemuxer::new(Cursor::new(bytes)).unwrap();280 let d = AviDemuxer::new(Cursor::new(bytes)).unwrap();
@@ -327,9 +292,6 @@ fn raw_video_is_carried_and_unknown_layouts_refused_by_name() {
327 292
328 #[test]293 #[test]
329 fn mpeg4_part2_and_ms_mpeg4_fourccs_map() {294 fn mpeg4_part2_and_ms_mpeg4_fourccs_map() {
330- if !oracle() {
331- return;
332- }
333 for tag in ["XVID", "xvid", "DIVX", "DX50", "FMP4", "mp4v"] {295 for tag in ["XVID", "xvid", "DIVX", "DX50", "FMP4", "mp4v"] {
334 let path = scratch("mp4v").join(format!("v-{tag}.avi"));296 let path = scratch("mp4v").join(format!("v-{tag}.avi"));
335 let mut args: Vec<&str> = Vec::new();297 let mut args: Vec<&str> = Vec::new();
@@ -357,9 +319,6 @@ fn mpeg4_part2_and_ms_mpeg4_fourccs_map() {
357 319
358 #[test]320 #[test]
359 fn truncated_file_without_idx1_scans() {321 fn truncated_file_without_idx1_scans() {
360- if !oracle() {
361- return;
362- }
363 let (path, bytes) = make("trunc", &["-c:v", "mjpeg"], &["-c:a", "pcm_s16le"]);322 let (path, bytes) = make("trunc", &["-c:v", "mjpeg"], &["-c:a", "pcm_s16le"]);
364 let full = compare_video_only(&path, &bytes);323 let full = compare_video_only(&path, &bytes);
365 // Cut in the middle of movi: idx1 is gone, the RIFF and movi sizes lie.324 // 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() {
381 340
382 #[test]341 #[test]
383 fn mjpeg_frames_decode_like_ffmpeg() {342 fn mjpeg_frames_decode_like_ffmpeg() {
384- if !oracle() {
385- return;
386- }
387 let (path, bytes) = make("mjpeg-dec", &["-c:v", "mjpeg", "-q:v", "2"], &["-c:a", "pcm_s16le"]);343 let (path, bytes) = make("mjpeg-dec", &["-c:v", "mjpeg", "-q:v", "2"], &["-c:a", "pcm_s16le"]);
388 let raw = scratch("mjpeg-dec").join("o.yuv");344 let raw = scratch("mjpeg-dec").join("o.yuv");
389 ffmpeg(&[345 ffmpeg(&[
crates/ec-riff/tests/it/common.rsmodified+1 -10
@@ -1,6 +1,5 @@
1 //! Helpers shared by the integration-test modules in this binary.1 //! Helpers shared by the integration-test modules in this binary.
2 2
3-use std::process::Command;
4 3
5 use ec_core::frame::VideoFrame;4 use ec_core::frame::VideoFrame;
6 5
@@ -20,16 +19,8 @@ pub(crate) fn list(kind: &[u8; 4], body: &[u8]) -> Vec<u8> {
20 chunk(b"LIST", &b)19 chunk(b"LIST", &b)
21 }20 }
22 21
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-
31 pub(crate) fn ffmpeg(args: &[&str]) {22 pub(crate) fn ffmpeg(args: &[&str]) {
32- let ok = Command::new("ffmpeg")23+ let ok = ec_testkit::ffmpeg()
33 .args(["-v", "error", "-y", "-nostdin"])24 .args(["-v", "error", "-y", "-nostdin"])
34 .args(args)25 .args(args)
35 .status()26 .status()
crates/ec-riff/tests/it/dts.rsmodified+2 -10
@@ -1,7 +1,6 @@
1 //! DTS in AVI: the `0x2001` audio format tag is `CodecId::Dts`.1 //! DTS in AVI: the `0x2001` audio format tag is `CodecId::Dts`.
2 2
3 use std::io::Cursor;3 use std::io::Cursor;
4-use std::process::Command;
5 4
6 use ec_core::{CodecId, Demuxer, MediaParameters};5 use ec_core::{CodecId, Demuxer, MediaParameters};
7 use ec_riff::AviDemuxer;6 use ec_riff::AviDemuxer;
@@ -9,21 +8,14 @@ use ec_riff::AviDemuxer;
9 #[test]8 #[test]
10 fn avi_tag_0x2001_is_dts() {9 fn avi_tag_0x2001_is_dts() {
11 let out = std::env::temp_dir().join(format!("ec-riff-dts-{}.avi", std::process::id()));10 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()
13 .args(["-v", "error", "-y", "-f", "lavfi", "-i"])12 .args(["-v", "error", "-y", "-f", "lavfi", "-i"])
14 .arg("sine=frequency=440:sample_rate=48000:duration=0.5")13 .arg("sine=frequency=440:sample_rate=48000:duration=0.5")
15 .args(["-ac", "2", "-c:a", "dca", "-strict", "-2"])14 .args(["-ac", "2", "-c:a", "dca", "-strict", "-2"])
16 .arg(&out)15 .arg(&out)
17 .output()16 .output()
18 .is_ok_and(|o| o.status.success());17 .is_ok_and(|o| o.status.success());
19- if !ok {18+ assert!(ok, "ffmpeg cannot make a DTS avi");
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- }
27 let bytes = std::fs::read(&out).unwrap();19 let bytes = std::fs::read(&out).unwrap();
28 let _ = std::fs::remove_file(out);20 let _ = std::fs::remove_file(out);
29 let d = AviDemuxer::new(Cursor::new(bytes)).unwrap();21 let d = AviDemuxer::new(Cursor::new(bytes)).unwrap();
crates/ec-riff/tests/it/mov_raw.rsmodified+1 -24
@@ -1,32 +1,12 @@
1 //! Uncompressed video in QuickTime (`raw `, `2vuy`, `yuv2`, `v210`, `v410`, `b16g`), compared1 //! 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.
4 2
5 use std::path::PathBuf;3 use std::path::PathBuf;
6-use std::process::Command;
7 4
8 use ec_core::frame::Frame;5 use ec_core::frame::Frame;
9 use ec_core::registry::{CodecId, Decoder, Demuxer};6 use ec_core::registry::{CodecId, Decoder, Demuxer};
10 use ec_riff::RawVideoDecoder;7 use ec_riff::RawVideoDecoder;
11 use crate::common::frame_bytes;8 use crate::common::frame_bytes;
12 9
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-
30 fn scratch(tag: &str) -> PathBuf {10 fn scratch(tag: &str) -> PathBuf {
31 let base = std::env::var_os("TMPDIR")11 let base = std::env::var_os("TMPDIR")
32 .map(PathBuf::from)12 .map(PathBuf::from)
@@ -37,7 +17,7 @@ fn scratch(tag: &str) -> PathBuf {
37 }17 }
38 18
39 fn ffmpeg(args: &[&str]) -> Vec<u8> {19 fn ffmpeg(args: &[&str]) -> Vec<u8> {
40- let o = Command::new("ffmpeg")20+ let o = ec_testkit::ffmpeg()
41 .args(["-v", "error", "-y", "-nostdin"])21 .args(["-v", "error", "-y", "-nostdin"])
42 .args(args)22 .args(args)
43 .output()23 .output()
@@ -52,9 +32,6 @@ fn ffmpeg(args: &[&str]) -> Vec<u8> {
52 32
53 #[test]33 #[test]
54 fn mov_raw_layouts_match_ffmpeg() {34 fn mov_raw_layouts_match_ffmpeg() {
55- if !oracle() {
56- return;
57- }
58 // (tag, size, ffmpeg codec, source pix_fmt, expected sample entry, pix_fmt we compare in)35 // (tag, size, ffmpeg codec, source pix_fmt, expected sample entry, pix_fmt we compare in)
59 for (tag, size, codec, pix, entry, ff) in [36 for (tag, size, codec, pix, entry, ff) in [
60 ("rgb24", "98x66", "rawvideo", "rgb24", b"raw ", "rgb24"),37 ("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() {
429 429
430 #[test]430 #[test]
431 fn reads_every_wav_fixture() {431 fn reads_every_wav_fixture() {
432- let dir = concat!(env!("CARGO_MANIFEST_DIR"), "/../../fixtures/audio");432+ let entries = std::fs::read_dir(ec_testkit::root().join("audio"))
433- let Ok(entries) = std::fs::read_dir(dir) else {433+ .expect("fixtures/audio (run scripts/fixtures.sh)");
434- eprintln!("fixtures/audio absent (gitignored) — skipping");
435- return;
436- };
437 let mut seen = 0;434 let mut seen = 0;
438 for e in entries.flatten() {435 for e in entries.flatten() {
439 let path = e.path();436 let path = e.path();