forge
Explore
Log in

Don't you dare go Hollow

Merge branch 'simplify/u19' into simplify/w1b

Browse files at this commit

d8990c1088f03796048f29e447ef2e5c2df5f3e9Ahmet Kaan GümüşParent: cbe764c3739e1a
# Conflicts:
#	Cargo.lock

15 changed files +134 -1014

Cargo.lockmodified+0 -7
@@ -1333,13 +1333,6 @@ version = "1.21.4"
1333 source = "registry+https://github.com/rust-lang/crates.io-index"1333 source = "registry+https://github.com/rust-lang/crates.io-index"
1334 checksum = "9f7c3e4beb33f85d45ae3e3a1792185706c8e16d043238c593331cc7cd313b50"1334 checksum = "9f7c3e4beb33f85d45ae3e3a1792185706c8e16d043238c593331cc7cd313b50"
1335 1335
1336-[[package]]
1337-name = "oracle"
1338-version = "0.1.0"
1339-dependencies = [
1340- "ec-testkit",
1341-]
1342-
1343 [[package]]1336 [[package]]
1344 name = "paste"1337 name = "paste"
1345 version = "1.0.15"1338 version = "1.0.15"
Cargo.tomlmodified+1 -1
@@ -1,6 +1,6 @@
1 [workspace]1 [workspace]
2 resolver = "3"2 resolver = "3"
3-members = ["crates/*", "shims/cros-libva", "shims/vk-video-ffi", "tools/ec-bench", "tools/golden", "tools/oracle"]3+members = ["crates/*", "shims/cros-libva", "shims/vk-video-ffi", "tools/ec-bench", "tools/golden"]
4 exclude = ["crates/*/fuzz"]4 exclude = ["crates/*/fuzz"]
5 5
6 [workspace.package]6 [workspace.package]
tools/gen_dts_tables.py → crates/ec-dts/gen_dts_tables.pyrenamed+3 -3
@@ -7,7 +7,7 @@ https://www.etsi.org/deliver/etsi_ts/102100_102199/102114/01.06.01_60/ts_102114v
7 7
8 Usage:8 Usage:
9 pdftotext -layout ts_102114v010601p.pdf ts102114.txt9 pdftotext -layout ts_102114v010601p.pdf ts102114.txt
10- python3 -I tools/gen_dts_tables.py ts102114.txt \10+ python3 -I crates/ec-dts/gen_dts_tables.py ts102114.txt \
11 crates/ec-dts/src/tables_data.rs crates/ec-dts/tests/spec_ts102114_tables.txt11 crates/ec-dts/src/tables_data.rs crates/ec-dts/tests/spec_ts102114_tables.txt
12 12
13 The spec text (decimal commas, "1 926" style thousands separators) is parsed13 The spec text (decimal commas, "1 926" style thousands separators) is parsed
@@ -254,7 +254,7 @@ def main():
254 # ---- write the raw spec numbers254 # ---- write the raw spec numbers
255 with open(out_spec, 'w') as f:255 with open(out_spec, 'w') as f:
256 f.write('# Numbers exactly as printed in ETSI TS 102 114 V1.6.1 (2019-08), Annex D / clause 5.\n')256 f.write('# Numbers exactly as printed in ETSI TS 102 114 V1.6.1 (2019-08), Annex D / clause 5.\n')
257- f.write('# Written by tools/gen_dts_tables.py; decimal commas written as points.\n')257+ f.write('# Written by crates/ec-dts/gen_dts_tables.py; decimal commas written as points.\n')
258 f.write('# table NAME | clause | values... (invalid entries kept as the word "invalid")\n')258 f.write('# table NAME | clause | values... (invalid entries kept as the word "invalid")\n')
259 f.write('# huff TABLE | clause | level:length:code ... (code = value of the code word)\n')259 f.write('# huff TABLE | clause | level:length:code ... (code = value of the code word)\n')
260 for name, cl, vals in raw:260 for name, cl, vals in raw:
@@ -281,7 +281,7 @@ def main():
281 R = {n: v for n, _, v in raw}281 R = {n: v for n, _, v in raw}
282 out.append('//! Constant tables for DTS Coherent Acoustics (ETSI TS 102 114).')282 out.append('//! Constant tables for DTS Coherent Acoustics (ETSI TS 102 114).')
283 out.append('//!')283 out.append('//!')
284- out.append('//! GENERATED by tools/gen_dts_tables.py from the numeric tables of')284+ out.append('//! GENERATED by crates/ec-dts/gen_dts_tables.py from the numeric tables of')
285 out.append('//! ETSI TS 102 114 V1.6.1 (2019-08); the clause of each table is named on')285 out.append('//! ETSI TS 102 114 V1.6.1 (2019-08); the clause of each table is named on')
286 out.append('//! it. The raw printed numbers are committed in')286 out.append('//! it. The raw printed numbers are committed in')
287 out.append('//! tests/spec_ts102114_tables.txt and tests/spec_tables.rs checks every')287 out.append('//! tests/spec_ts102114_tables.txt and tests/spec_tables.rs checks every')
crates/ec-dts/src/lib.rsmodified+1 -1
@@ -29,7 +29,7 @@
29 //! [`Error::Unsupported`] naming what and why. No input panics.29 //! [`Error::Unsupported`] naming what and why. No input panics.
30 //!30 //!
31 //! The constant tables in [`tables_data`] are generated by31 //! The constant tables in [`tables_data`] are generated by
32-//! `tools/gen_dts_tables.py` from the numeric tables printed in ETSI TS 102 11432+//! `crates/ec-dts/gen_dts_tables.py` from the numeric tables printed in ETSI TS 102 114
33 //! V1.6.1 and checked against them by `tests/spec_tables.rs`; the few tables33 //! V1.6.1 and checked against them by `tests/spec_tables.rs`; the few tables
34 //! the standard does not print usably are in `tables_residual.rs`.34 //! the standard does not print usably are in `tables_residual.rs`.
35 35
crates/ec-dts/src/tables_data.rsmodified+1 -1
@@ -1,6 +1,6 @@
1 //! Constant tables for DTS Coherent Acoustics (ETSI TS 102 114).1 //! Constant tables for DTS Coherent Acoustics (ETSI TS 102 114).
2 //!2 //!
3-//! GENERATED by tools/gen_dts_tables.py from the numeric tables of3+//! GENERATED by crates/ec-dts/gen_dts_tables.py from the numeric tables of
4 //! ETSI TS 102 114 V1.6.1 (2019-08); the clause of each table is named on4 //! ETSI TS 102 114 V1.6.1 (2019-08); the clause of each table is named on
5 //! it. The raw printed numbers are committed in5 //! it. The raw printed numbers are committed in
6 //! tests/spec_ts102114_tables.txt and tests/spec_tables.rs checks every6 //! tests/spec_ts102114_tables.txt and tests/spec_tables.rs checks every
crates/ec-dts/tests/spec_tables.rsmodified+1 -1
@@ -1,6 +1,6 @@
1 //! The constant tables in `tables_data.rs` against the numbers printed in1 //! The constant tables in `tables_data.rs` against the numbers printed in
2 //! ETSI TS 102 114 V1.6.1 (2019-08), committed in `spec_ts102114_tables.txt`2 //! ETSI TS 102 114 V1.6.1 (2019-08), committed in `spec_ts102114_tables.txt`
3-//! (written by `tools/gen_dts_tables.py`, with the clause of every table).3+//! (written by `crates/ec-dts/gen_dts_tables.py`, with the clause of every table).
4 //!4 //!
5 //! The conversions from printed number to Rust value are repeated here5 //! The conversions from printed number to Rust value are repeated here
6 //! independently of the generator.6 //! independently of the generator.
crates/ec-dts/tests/spec_ts102114_tables.txtmodified+1 -1
@@ -1,5 +1,5 @@
1 # Numbers exactly as printed in ETSI TS 102 114 V1.6.1 (2019-08), Annex D / clause 5.1 # Numbers exactly as printed in ETSI TS 102 114 V1.6.1 (2019-08), Annex D / clause 5.
2-# Written by tools/gen_dts_tables.py; decimal commas written as points.2+# Written by crates/ec-dts/gen_dts_tables.py; decimal commas written as points.
3 # table NAME | clause | values... (invalid entries kept as the word "invalid")3 # table NAME | clause | values... (invalid entries kept as the word "invalid")
4 # huff TABLE | clause | level:length:code ... (code = value of the code word)4 # huff TABLE | clause | level:length:code ... (code = value of the code word)
5 table QUANT_LEVELS | Table 5-26 | 0 3 5 7 9 13 17 25 32 64 128 256 512 1024 2048 4096 8192 16384 32768 65536 131072 262144 524288 1048576 2097152 4194304 83886085 table QUANT_LEVELS | Table 5-26 | 0 3 5 7 9 13 17 25 32 64 128 256 512 1024 2048 4096 8192 16384 32768 65536 131072 262144 524288 1048576 2097152 4194304 8388608
tools/gen_h263_tables.py → crates/ec-mpeg4/gen_h263_tables.pyrenamed+2 -2
@@ -3,7 +3,7 @@
3 3
4 Usage:4 Usage:
5 pdftotext -layout T-REC-H.263-200501-I!!PDF-E.pdf h263.txt5 pdftotext -layout T-REC-H.263-200501-I!!PDF-E.pdf h263.txt
6- python3 -I tools/gen_h263_tables.py h263.txt crates/ec-mpeg4/src/h263data.rs6+ python3 -I crates/ec-mpeg4/gen_h263_tables.py h263.txt crates/ec-mpeg4/src/h263data.rs
7 rustfmt --edition 2021 crates/ec-mpeg4/src/h263data.rs7 rustfmt --edition 2021 crates/ec-mpeg4/src/h263data.rs
8 8
9 The PDF is freely downloadable from https://www.itu.int/rec/T-REC-H.263 and is the9 The PDF is freely downloadable from https://www.itu.int/rec/T-REC-H.263 and is the
@@ -277,7 +277,7 @@ def arr1(name, ty, a, doc):
277 w(f"pub const {name}: [{ty}; {len(a)}] = [" + ", ".join(str(x) for x in a) + "];\n")277 w(f"pub const {name}: [{ty}; {len(a)}] = [" + ", ".join(str(x) for x in a) + "];\n")
278 278
279 279
280-w("""// Generated by tools/gen_h263_tables.py from the text of ITU-T Rec. H.263 (01/2005)280+w("""// Generated by crates/ec-mpeg4/gen_h263_tables.py from the text of ITU-T Rec. H.263 (01/2005)
281 // (https://www.itu.int/rec/T-REC-H.263). Do not edit by hand.281 // (https://www.itu.int/rec/T-REC-H.263). Do not edit by hand.
282 //282 //
283 // Every table in this file is transcribed from the Recommendation; the clause or table283 // Every table in this file is transcribed from the Recommendation; the clause or table
crates/ec-mpeg4/src/h263data.rsmodified+1 -1
@@ -1,4 +1,4 @@
1-// Generated by tools/gen_h263_tables.py from the text of ITU-T Rec. H.263 (01/2005)1+// Generated by crates/ec-mpeg4/gen_h263_tables.py from the text of ITU-T Rec. H.263 (01/2005)
2 // (https://www.itu.int/rec/T-REC-H.263). Do not edit by hand.2 // (https://www.itu.int/rec/T-REC-H.263). Do not edit by hand.
3 //3 //
4 // Every table in this file is transcribed from the Recommendation; the clause or table4 // Every table in this file is transcribed from the Recommendation; the clause or table
crates/ec-riff/tests/it/wav.rsmodified+0 -5
@@ -1,9 +1,4 @@
1 //! Round-trip, header and tolerance checks, plus the fixtures on disk.1 //! Round-trip, header and tolerance checks, plus the fixtures on disk.
2-//!
3-//! The oracle artifacts this writes into `CARGO_TARGET_TMPDIR/oracle` are the
4-//! ffmpeg half of the story: after `cargo test -p ec-riff`, each `<name>.wav`
5-//! is compared against its `<name>.raw` (the samples that went in, as f32le)
6-//! with `oracle audio-compare <name>.raw <name>.wav`.
7 2
8 use std::io::Cursor;3 use std::io::Cursor;
9 4
tools/ec-bench/Cargo.tomlmodified+3 -1
@@ -19,7 +19,6 @@ ec-h264 = { workspace = true }
19 ec-h265 = { workspace = true }19 ec-h265 = { workspace = true }
20 ec-av1 = { workspace = true }20 ec-av1 = { workspace = true }
21 ec-hw = { workspace = true }21 ec-hw = { workspace = true }
22-ec-va = { workspace = true }
23 ec-probe = { workspace = true }22 ec-probe = { workspace = true }
24 ec-h264-syntax = { workspace = true }23 ec-h264-syntax = { workspace = true }
25 ec-image = { workspace = true }24 ec-image = { workspace = true }
@@ -33,3 +32,6 @@ ec-alac = { workspace = true }
33 ec-ac3 = { workspace = true }32 ec-ac3 = { workspace = true }
34 ec-truehd = { workspace = true }33 ec-truehd = { workspace = true }
35 ec-testkit.workspace = true34 ec-testkit.workspace = true
35+
36+[target.'cfg(target_os = "linux")'.dependencies]
37+ec-va = { workspace = true }
tools/ec-bench/src/main.rsmodified+120 -266
@@ -37,14 +37,35 @@ struct Row {
37 rtf: Option<f64>,37 rtf: Option<f64>,
38 }38 }
39 39
40+impl Row {
41+ fn timed(
42+ component: &'static str,
43+ direction: &'static str,
44+ content: String,
45+ media_s: f64,
46+ wall: f64,
47+ ) -> Row {
48+ Row {
49+ component,
50+ direction,
51+ content,
52+ media: format!("{media_s:.1}s"),
53+ wall_ms: wall * 1000.0,
54+ rtf: (wall > 0.0).then_some(media_s / wall),
55+ }
56+ }
57+}
58+
40 fn main() -> ec_core::Result<()> {59 fn main() -> ec_core::Result<()> {
41 let mut rows = Vec::new();60 let mut rows = Vec::new();
42 61
43 bench_h264(&mut rows)?;62 bench_h264(&mut rows)?;
44 bench_h265_encode(&mut rows);63 bench_h265_encode(&mut rows);
45 bench_av1_encode(&mut rows);64 bench_av1_encode(&mut rows);
46- bench_hw_av1_encode(&mut rows);65+ #[cfg(target_os = "linux")]
47- bench_hw_av1_encode_10bit(&mut rows);66+ bench_hw_av1_encode(&mut rows, false);
67+ #[cfg(target_os = "linux")]
68+ bench_hw_av1_encode(&mut rows, true);
48 bench_audio_decode(&mut rows)?;69 bench_audio_decode(&mut rows)?;
49 bench_audio_encode(&mut rows);70 bench_audio_encode(&mut rows);
50 bench_truehd(&mut rows);71 bench_truehd(&mut rows);
@@ -166,25 +187,20 @@ fn bench_h264(rows: &mut Vec<Row>) -> ec_core::Result<()> {
166 .and_then(|s| parse_ratio(&s))187 .and_then(|s| parse_ratio(&s))
167 .unwrap_or(25.0);188 .unwrap_or(25.0);
168 let media_s = frames as f64 / fps;189 let media_s = frames as f64 / fps;
169- rows.push(Row {190+ rows.push(Row::timed("ec-h264", "decode", format!("{w}x{h} film, {frames} frames"), media_s, wall));
170- component: "ec-h264",
171- direction: "decode",
172- content: format!("{w}x{h} film, {frames} frames"),
173- media: format!("{media_s:.1}s"),
174- wall_ms: wall * 1000.0,
175- rtf: (wall > 0.0).then_some(media_s / wall),
176- });
177 } else {191 } else {
178 rows.push(missing("ec-h264", "decode"));192 rows.push(missing("ec-h264", "decode"));
179 }193 }
180 194
181 // encode: 30 raw yuv420p frames scaled to 640x360 from the same clip.195 // encode: 30 raw yuv420p frames scaled to 640x360 from the same clip.
182- let (planes, ew, eh, n) = extract_yuv420p(&src, 640, 360, 30);196+ let (ew, eh) = (640, 360);
197+ let planes = extract_raw(&src, ew, eh, 30, "yuv420p");
198+ let frame_len = yuv420_frame_len(ew, eh, 1);
199+ let n = (planes.len() / frame_len) as u32;
183 if n > 0 {200 if n > 0 {
184 let mut cfg = H264Config::new(ew, eh);201 let mut cfg = H264Config::new(ew, eh);
185 cfg.threads = 1; // one worker: single-core cost, not a parallelism claim202 cfg.threads = 1; // one worker: single-core cost, not a parallelism claim
186 let mut enc = H264Encoder::new(cfg).expect("h264 encoder");203 let mut enc = H264Encoder::new(cfg).expect("h264 encoder");
187- let frame_len = (ew * eh + 2 * (ew.div_ceil(2) * eh.div_ceil(2))) as usize;
188 let start = Instant::now();204 let start = Instant::now();
189 for frame in planes.chunks_exact(frame_len) {205 for frame in planes.chunks_exact(frame_len) {
190 let (y, rest) = frame.split_at((ew * eh) as usize);206 let (y, rest) = frame.split_at((ew * eh) as usize);
@@ -194,23 +210,20 @@ fn bench_h264(rows: &mut Vec<Row>) -> ec_core::Result<()> {
194 }210 }
195 let wall = start.elapsed().as_secs_f64();211 let wall = start.elapsed().as_secs_f64();
196 let media_s = n as f64 / 30.0;212 let media_s = n as f64 / 30.0;
197- rows.push(Row {213+ rows.push(Row::timed("ec-h264", "encode", format!("{ew}x{eh}, {n} frames, 1 thread"), media_s, wall));
198- component: "ec-h264",
199- direction: "encode",
200- content: format!("{ew}x{eh}, {n} frames, 1 thread"),
201- media: format!("{media_s:.1}s"),
202- wall_ms: wall * 1000.0,
203- rtf: (wall > 0.0).then_some(media_s / wall),
204- });
205 } else {214 } else {
206 rows.push(missing("ec-h264", "encode"));215 rows.push(missing("ec-h264", "encode"));
207 }216 }
208 Ok(())217 Ok(())
209 }218 }
210 219
211-/// `n` progressive frames of raw I420 at `w x h`, scaled and trimmed inside220+fn yuv420_frame_len(w: u32, h: u32, bytes_per_sample: usize) -> usize {
212-/// ffmpeg.221+ (w * h + 2 * (w.div_ceil(2) * h.div_ceil(2))) as usize * bytes_per_sample
213-fn extract_yuv420p(src: &Path, w: u32, h: u32, n: u32) -> (Vec<u8>, u32, u32, u32) {222+}
223+
224+/// Up to `n` progressive frames at `w x h` in `pix_fmt`, scaled and trimmed
225+/// inside ffmpeg from `SEEK_SECONDS` on. Empty when ffmpeg fails.
226+fn extract_raw(src: &Path, w: u32, h: u32, n: u32, pix_fmt: &str) -> Vec<u8> {
214 let out = ec_testkit::ffmpeg()227 let out = ec_testkit::ffmpeg()
215 .args(["-v", "error", "-ss", SEEK_SECONDS, "-i"])228 .args(["-v", "error", "-ss", SEEK_SECONDS, "-i"])
216 .arg(src)229 .arg(src)
@@ -220,19 +233,14 @@ fn extract_yuv420p(src: &Path, w: u32, h: u32, n: u32) -> (Vec<u8>, u32, u32, u3
220 "-frames:v",233 "-frames:v",
221 &n.to_string(),234 &n.to_string(),
222 "-pix_fmt",235 "-pix_fmt",
223- "yuv420p",236+ pix_fmt,
224 "-f",237 "-f",
225 "rawvideo",238 "rawvideo",
226 "-",239 "-",
227 ])240 ])
228 .output()241 .output()
229- .expect("ffmpeg extract yuv420p");242+ .expect("ffmpeg extract raw");
230- if !out.status.success() || out.stdout.is_empty() {243+ if out.status.success() { out.stdout } else { Vec::new() }
231- return (Vec::new(), w, h, 0);
232- }
233- let frame_len = (w * h + 2 * (w.div_ceil(2) * h.div_ceil(2))) as usize;
234- let frames = (out.stdout.len() / frame_len) as u32;
235- (out.stdout, w, h, frames)
236 }244 }
237 245
238 fn parse_ratio(s: &str) -> Option<f64> {246 fn parse_ratio(s: &str) -> Option<f64> {
@@ -251,16 +259,17 @@ fn bench_h265_encode(rows: &mut Vec<Row>) {
251 rows.push(missing("ec-h265", "encode"));259 rows.push(missing("ec-h265", "encode"));
252 return;260 return;
253 };261 };
254- let (planes, w, h, n) = extract_yuv420p(&src, 640, 360, 10);262+ let (w, h) = (640, 360);
263+ let planes = extract_raw(&src, w, h, 10, "yuv420p");
264+ let frame_len = yuv420_frame_len(w, h, 1);
265+ let n = (planes.len() / frame_len) as u32;
255 if n == 0 {266 if n == 0 {
256 rows.push(missing("ec-h265", "encode"));267 rows.push(missing("ec-h265", "encode"));
257 rows.push(missing("ec-h265", "decode"));268 rows.push(missing("ec-h265", "decode"));
258 return;269 return;
259 }270 }
260 let enc = H265Encoder::new(H265Config::new(w, h)).expect("h265 encoder");271 let enc = H265Encoder::new(H265Config::new(w, h)).expect("h265 encoder");
261- let frame_len = (w * h + 2 * (w.div_ceil(2) * h.div_ceil(2))) as usize;
262 let cw = w.div_ceil(2);272 let cw = w.div_ceil(2);
263- let ch = h.div_ceil(2);
264 let mut aus = Vec::new();273 let mut aus = Vec::new();
265 let start = Instant::now();274 let start = Instant::now();
266 for frame in planes.chunks_exact(frame_len) {275 for frame in planes.chunks_exact(frame_len) {
@@ -277,196 +286,115 @@ fn bench_h265_encode(rows: &mut Vec<Row>) {
277 ],286 ],
278 )287 )
279 .expect("i420 frame");288 .expect("i420 frame");
280- let _ = ch; // silence unused if plane_geometry ignores it
281 aus.push(enc.encode_idr(&vf).expect("h265 encode").au);289 aus.push(enc.encode_idr(&vf).expect("h265 encode").au);
282 }290 }
283 let wall = start.elapsed().as_secs_f64();291 let wall = start.elapsed().as_secs_f64();
284 let media_s = n as f64 / 30.0;292 let media_s = n as f64 / 30.0;
285- rows.push(Row {293+ rows.push(Row::timed("ec-h265", "encode", format!("{w}x{h}, {n} frames, IDR-only"), media_s, wall));
286- component: "ec-h265",
287- direction: "encode",
288- content: format!("{w}x{h}, {n} frames, IDR-only"),
289- media: format!("{media_s:.1}s"),
290- wall_ms: wall * 1000.0,
291- rtf: (wall > 0.0).then_some(media_s / wall),
292- });
293 294
294 let start = Instant::now();295 let start = Instant::now();
295 for au in &aus {296 for au in &aus {
296 ec_h265::decode::decode_idr_au(au).expect("h265 decode");297 ec_h265::decode::decode_idr_au(au).expect("h265 decode");
297 }298 }
298 let wall = start.elapsed().as_secs_f64();299 let wall = start.elapsed().as_secs_f64();
299- rows.push(Row {300+ rows.push(Row::timed("ec-h265", "decode", format!("{w}x{h}, {n} frames, own IDR stream"), media_s, wall));
300- component: "ec-h265",
301- direction: "decode",
302- content: format!("{w}x{h}, {n} frames, own IDR stream"),
303- media: format!("{media_s:.1}s"),
304- wall_ms: wall * 1000.0,
305- rtf: (wall > 0.0).then_some(media_s / wall),
306- });
307 }301 }
308 302
309 // ---------------------------------------------------------------------------303 // ---------------------------------------------------------------------------
310-// hardware av1: the GPU encoder, at the size his library is in.304+// hardware av1: the GPU encoder (`ec-hw`, VA-API), at 8 or 10 bits.
311 // ---------------------------------------------------------------------------305 // ---------------------------------------------------------------------------
312 306
313-/// AV1 encode on the GPU (`ec-hw`, VA-API). Skips as a row rather than a307+/// AV1 encode on the GPU. Skips as a row rather than a failure when there is
314-/// failure when there is no VA device or the driver has no AV1 encode308+/// no VA device or the driver has no AV1 encode entrypoint -- a machine
315-/// entrypoint -- a machine without one is not a slow machine.309+/// without one is not a slow machine.
316-fn bench_hw_av1_encode(rows: &mut Vec<Row>) {310+#[cfg(target_os = "linux")]
317- let Some(src) = real_video("h264").or_else(|| real_video("hevc")) else {311+fn bench_hw_av1_encode(rows: &mut Vec<Row>, ten_bit: bool) {
318- rows.push(missing("ec-hw av1", "encode"));312+ let (component, pix_fmt, bytes) = if ten_bit {
319- return;313+ ("ec-hw av1 10-bit", "yuv420p10le", 2)
314+ } else {
315+ ("ec-hw av1", "yuv420p", 1)
320 };316 };
321- let display = match ec_va::open() {317+ let src = if ten_bit {
322- Ok(display) => display,318+ real_video("hevc").or_else(|| real_video("h264"))
323- Err(e) => {319+ } else {
324- rows.push(missing_direction("ec-hw av1", "encode", &format!("no VA display ({e})")));320+ real_video("h264").or_else(|| real_video("hevc"))
325- return;
326- }
327 };321 };
328- let (planes, w, h, n) = extract_yuv420p(&src, 1920, 1080, 30);322+ let Some(src) = src else {
329- if n == 0 {323+ rows.push(missing(component, "encode"));
330- rows.push(missing("ec-hw av1", "encode"));
331- return;
332- }
333- let mut cfg = ec_hw::EncoderConfig::new(ec_hw::EncCodec::Av1, w, h);
334- cfg.rate_control = ec_hw::RateControlMode::ConstantQp { qp: 120 };
335- let mut enc = match ec_hw::Encoder::new(&display, cfg) {
336- Ok(enc) => enc,
337- Err(e) => {
338- rows.push(missing_direction("ec-hw av1", "encode", &format!("driver refused ({e})")));
339- return;
340- }
341- };
342- let (cw, ch) = (w.div_ceil(2), h.div_ceil(2));
343- let frame_len = (w * h + 2 * cw * ch) as usize;
344- let start = Instant::now();
345- let mut coded = 0usize;
346- for (i, frame) in planes.chunks_exact(frame_len).enumerate() {
347- let (y, rest) = frame.split_at((w * h) as usize);
348- let (u, v) = rest.split_at(rest.len() / 2);
349- let picture = ec_hw::I420 {
350- y: y.to_vec(),
351- u: u.to_vec(),
352- v: v.to_vec(),
353- width: w,
354- height: h,
355- };
356- let meta = ec_hw::FrameMetadata {
357- timestamp: i as i64,
358- force_keyframe: false,
359- };
360- match enc.encode(&picture, meta) {
361- Ok(out) => coded += out.data.len(),
362- Err(e) => {
363- rows.push(missing_direction("ec-hw av1", "encode", &format!("encode failed ({e})")));
364- return;
365- }
366- }
367- }
368- let wall = start.elapsed().as_secs_f64();
369- let media_s = n as f64 / 30.0;
370- rows.push(Row {
371- component: "ec-hw av1",
372- direction: "encode",
373- content: format!("{w}x{h}, {n} frames, CQP 120, {} kB", coded / 1000),
374- media: format!("{media_s:.1}s"),
375- wall_ms: wall * 1000.0,
376- rtf: (wall > 0.0).then_some(media_s / wall),
377- });
378-}
379-
380-/// The same row at 10 bits, which is the depth his own AV1 library is stored
381-/// at (`yuv420p10le`, both films). Skips as a row when there is no VA device,
382-/// no AV1 encode entrypoint, or no source to read.
383-fn bench_hw_av1_encode_10bit(rows: &mut Vec<Row>) {
384- let Some(src) = real_video("av1").or_else(|| real_video("hevc")).or_else(|| real_video("h264"))
385- else {
386- rows.push(missing("ec-hw av1 10-bit", "encode"));
387 return;324 return;
388 };325 };
389 let display = match ec_va::open() {326 let display = match ec_va::open() {
390 Ok(display) => display,327 Ok(display) => display,
391 Err(e) => {328 Err(e) => {
392- rows.push(missing_direction("ec-hw av1 10-bit", "encode", &format!("no VA display ({e})")));329+ rows.push(missing_direction(component, "encode", &format!("no VA display ({e})")));
393 return;330 return;
394 }331 }
395 };332 };
396- let (w, h) = (1920u32, 1080u32);333+ let (w, h) = (1920, 1080);
397- let raw = extract_yuv420p10(&src, w, h, 30);334+ let raw = extract_raw(&src, w, h, 30, pix_fmt);
398- let (cw, ch) = (w.div_ceil(2), h.div_ceil(2));335+ let frame_len = yuv420_frame_len(w, h, bytes);
399- let frame_len = ((w * h + 2 * cw * ch) * 2) as usize;
400 let n = (raw.len() / frame_len) as u32;336 let n = (raw.len() / frame_len) as u32;
401 if n == 0 {337 if n == 0 {
402- rows.push(missing("ec-hw av1 10-bit", "encode"));338+ rows.push(missing(component, "encode"));
403 return;339 return;
404 }340 }
405- let mut cfg = ec_hw::EncoderConfig::new(ec_hw::EncCodec::Av1, w, h).ten_bit();341+ let mut cfg = ec_hw::EncoderConfig::new(ec_hw::EncCodec::Av1, w, h);
342+ if ten_bit {
343+ cfg = cfg.ten_bit();
344+ }
406 cfg.rate_control = ec_hw::RateControlMode::ConstantQp { qp: 120 };345 cfg.rate_control = ec_hw::RateControlMode::ConstantQp { qp: 120 };
407 let mut enc = match ec_hw::Encoder::new(&display, cfg) {346 let mut enc = match ec_hw::Encoder::new(&display, cfg) {
408 Ok(enc) => enc,347 Ok(enc) => enc,
409 Err(e) => {348 Err(e) => {
410- rows.push(missing_direction("ec-hw av1 10-bit", "encode", &format!("driver refused ({e})")));349+ rows.push(missing_direction(component, "encode", &format!("driver refused ({e})")));
411 return;350 return;
412 }351 }
413 };352 };
414- let read = |s: &[u8]| -> Vec<u16> {353+ let read16 = |s: &[u8]| -> Vec<u16> {
415 s.as_chunks::<2>().0.iter().map(|p| u16::from_le_bytes([p[0], p[1]])).collect()354 s.as_chunks::<2>().0.iter().map(|p| u16::from_le_bytes([p[0], p[1]])).collect()
416 };355 };
417 let start = Instant::now();356 let start = Instant::now();
418 let mut coded = 0usize;357 let mut coded = 0usize;
419 for (i, frame) in raw.chunks_exact(frame_len).enumerate() {358 for (i, frame) in raw.chunks_exact(frame_len).enumerate() {
420- let (y, rest) = frame.split_at((w * h * 2) as usize);359+ let (y, rest) = frame.split_at((w * h) as usize * bytes);
421 let (u, v) = rest.split_at(rest.len() / 2);360 let (u, v) = rest.split_at(rest.len() / 2);
422- let picture = ec_hw::I420_16 {
423- y: read(y),
424- u: read(u),
425- v: read(v),
426- width: w,
427- height: h,
428- bit_depth: 10,
429- };
430 let meta = ec_hw::FrameMetadata { timestamp: i as i64, force_keyframe: false };361 let meta = ec_hw::FrameMetadata { timestamp: i as i64, force_keyframe: false };
431- match enc.encode_16(&picture, meta) {362+ let result = if ten_bit {
363+ enc.encode_16(
364+ &ec_hw::I420_16 {
365+ y: read16(y),
366+ u: read16(u),
367+ v: read16(v),
368+ width: w,
369+ height: h,
370+ bit_depth: 10,
371+ },
372+ meta,
373+ )
374+ } else {
375+ enc.encode(
376+ &ec_hw::I420 {
377+ y: y.to_vec(),
378+ u: u.to_vec(),
379+ v: v.to_vec(),
380+ width: w,
381+ height: h,
382+ },
383+ meta,
384+ )
385+ };
386+ match result {
432 Ok(out) => coded += out.data.len(),387 Ok(out) => coded += out.data.len(),
433 Err(e) => {388 Err(e) => {
434- rows.push(missing_direction("ec-hw av1 10-bit", "encode", &format!("encode failed ({e})")));389+ rows.push(missing_direction(component, "encode", &format!("encode failed ({e})")));
435 return;390 return;
436 }391 }
437 }392 }
438 }393 }
439 let wall = start.elapsed().as_secs_f64();394 let wall = start.elapsed().as_secs_f64();
440 let media_s = f64::from(n) / 30.0;395 let media_s = f64::from(n) / 30.0;
441- rows.push(Row {396+ let content = format!("{w}x{h} {pix_fmt}, {n} frames, CQP 120, {} kB", coded / 1000);
442- component: "ec-hw av1 10-bit",397+ rows.push(Row::timed(component, "encode", content, media_s, wall));
443- direction: "encode",
444- content: format!("{w}x{h} yuv420p10le, {n} frames from 00:00:30, CQP 120, {} kB", coded / 1000),
445- media: format!("{media_s:.1}s"),
446- wall_ms: wall * 1000.0,
447- rtf: (wall > 0.0).then_some(media_s / wall),
448- });
449-}
450-
451-/// `extract_yuv420p` at ten bits, planar 16-bit little endian, seeked
452-/// into the clip: frame 0 of a film is its black leader, and a black leader codes
453-/// to nothing and benchmarks nothing.
454-fn extract_yuv420p10(src: &Path, w: u32, h: u32, n: u32) -> Vec<u8> {
455- let out = ec_testkit::ffmpeg()
456- .args(["-v", "error", "-ss", SEEK_SECONDS, "-i"])
457- .arg(src)
458- .args([
459- "-vf", &format!("scale={w}:{h}"),
460- "-frames:v", &n.to_string(),
461- "-pix_fmt", "yuv420p10le",
462- "-f", "rawvideo", "-",
463- ])
464- .output()
465- .expect("ffmpeg extract yuv420p10le");
466- if !out.status.success() {
467- return Vec::new();
468- }
469- out.stdout
470 }398 }
471 399
472 // ---------------------------------------------------------------------------400 // ---------------------------------------------------------------------------
@@ -480,7 +408,10 @@ fn bench_av1_encode(rows: &mut Vec<Row>) {
480 return;408 return;
481 };409 };
482 // AV1's block grid is 32x32 superblocks: pick a size already a multiple of it.410 // AV1's block grid is 32x32 superblocks: pick a size already a multiple of it.
483- let (planes, w, h, n) = extract_yuv420p(&src, 640, 384, 10);411+ let (w, h) = (640, 384);
412+ let planes = extract_raw(&src, w, h, 10, "yuv420p");
413+ let frame_len = yuv420_frame_len(w, h, 1);
414+ let n = (planes.len() / frame_len) as u32;
484 if n == 0 {415 if n == 0 {
485 rows.push(missing("ec-av1", "encode"));416 rows.push(missing("ec-av1", "encode"));
486 rows.push(missing("ec-av1", "decode"));417 rows.push(missing("ec-av1", "decode"));
@@ -530,7 +461,6 @@ fn bench_av1_encode(rows: &mut Vec<Row>) {
530 None => Av1Encoder::with_speed(cfg, speed).expect("av1 encoder"),461 None => Av1Encoder::with_speed(cfg, speed).expect("av1 encoder"),
531 Some(p) => Av1Encoder::with_pyramid(cfg, p).expect("av1 encoder"),462 Some(p) => Av1Encoder::with_pyramid(cfg, p).expect("av1 encoder"),
532 };463 };
533- let frame_len = (w * h + 2 * (w.div_ceil(2) * h.div_ceil(2))) as usize;
534 let mut stream = Vec::new();464 let mut stream = Vec::new();
535 let mut hidden = 0usize;465 let mut hidden = 0usize;
536 let start = Instant::now();466 let start = Instant::now();
@@ -571,17 +501,11 @@ fn bench_av1_encode(rows: &mut Vec<Row>) {
571 };501 };
572 let fps = if wall > 0.0 { f64::from(n) / wall } else { 0.0 };502 let fps = if wall > 0.0 { f64::from(n) / wall } else { 0.0 };
573 let bytes_per_frame = stream.len() as f64 / f64::from(n);503 let bytes_per_frame = stream.len() as f64 / f64::from(n);
574- rows.push(Row {504+ let content = format!(
575- component: "ec-av1",505+ "speed {speed} [{levers}], {w}x{h}, {n} frames, gop=10, {coded_under}, \
576- direction: "encode",506+ {hidden} hidden, {fps:.1} fps, {bytes_per_frame:.0} B/frame"
577- content: format!(507+ );
578- "speed {speed} [{levers}], {w}x{h}, {n} frames, gop=10, {coded_under}, \508+ rows.push(Row::timed("ec-av1", "encode", content, media_s, wall));
579- {hidden} hidden, {fps:.1} fps, {bytes_per_frame:.0} B/frame"
580- ),
581- media: format!("{media_s:.1}s"),
582- wall_ms: wall * 1000.0,
583- rtf: (wall > 0.0).then_some(media_s / wall),
584- });
585 if first_stream.is_empty() {509 if first_stream.is_empty() {
586 first_stream = stream;510 first_stream = stream;
587 }511 }
@@ -595,14 +519,7 @@ fn bench_av1_encode(rows: &mut Vec<Row>) {
595 let pictures = ec_av1::stream::decode_stream(&stream).expect("av1 decode_stream");519 let pictures = ec_av1::stream::decode_stream(&stream).expect("av1 decode_stream");
596 let wall = start.elapsed().as_secs_f64();520 let wall = start.elapsed().as_secs_f64();
597 assert_eq!(pictures.len(), n as usize, "decode_stream frame count");521 assert_eq!(pictures.len(), n as usize, "decode_stream frame count");
598- rows.push(Row {522+ rows.push(Row::timed("ec-av1", "decode", format!("{w}x{h}, {n} frames, gop=10"), media_s, wall));
599- component: "ec-av1",
600- direction: "decode",
601- content: format!("{w}x{h}, {n} frames, gop=10"),
602- media: format!("{media_s:.1}s"),
603- wall_ms: wall * 1000.0,
604- rtf: (wall > 0.0).then_some(media_s / wall),
605- });
606 }523 }
607 524
608 // ---------------------------------------------------------------------------525 // ---------------------------------------------------------------------------
@@ -719,14 +636,7 @@ fn bench_audio_encode(rows: &mut Vec<Row>) {
719 .expect("opus encode");636 .expect("opus encode");
720 }637 }
721 let wall = start.elapsed().as_secs_f64();638 let wall = start.elapsed().as_secs_f64();
722- rows.push(Row {639+ rows.push(Row::timed("ec-opus", "encode", content.clone(), media_s, wall));
723- component: "ec-opus",
724- direction: "encode",
725- content: content.clone(),
726- media: format!("{media_s:.1}s"),
727- wall_ms: wall * 1000.0,
728- rtf: (wall > 0.0).then_some(media_s / wall),
729- });
730 }640 }
731 641
732 // vorbis: quality 0.6, the level the oracle tests already encode at.642 // vorbis: quality 0.6, the level the oracle tests already encode at.
@@ -751,14 +661,7 @@ fn bench_audio_encode(rows: &mut Vec<Row>) {
751 }661 }
752 let wall = start.elapsed().as_secs_f64();662 let wall = start.elapsed().as_secs_f64();
753 let _ = n;663 let _ = n;
754- rows.push(Row {664+ rows.push(Row::timed("ec-vorbis", "encode", content.clone(), media_s, wall));
755- component: "ec-vorbis",
756- direction: "encode",
757- content: content.clone(),
758- media: format!("{media_s:.1}s"),
759- wall_ms: wall * 1000.0,
760- rtf: (wall > 0.0).then_some(media_s / wall),
761- });
762 }665 }
763 666
764 // aac: 128 kbit/s, raw (no ADTS wrap) -- the default config.667 // aac: 128 kbit/s, raw (no ADTS wrap) -- the default config.
@@ -769,14 +672,7 @@ fn bench_audio_encode(rows: &mut Vec<Row>) {
769 enc.finish();672 enc.finish();
770 while enc.next_packet().is_ok() {}673 while enc.next_packet().is_ok() {}
771 let wall = start.elapsed().as_secs_f64();674 let wall = start.elapsed().as_secs_f64();
772- rows.push(Row {675+ rows.push(Row::timed("ec-aac", "encode", content.clone(), media_s, wall));
773- component: "ec-aac",
774- direction: "encode",
775- content: content.clone(),
776- media: format!("{media_s:.1}s"),
777- wall_ms: wall * 1000.0,
778- rtf: (wall > 0.0).then_some(media_s / wall),
779- });
780 }676 }
781 677
782 // mp3: CBR 192 kbit/s, the incumbent-matching default the tests gate on.678 // mp3: CBR 192 kbit/s, the incumbent-matching default the tests gate on.
@@ -791,14 +687,7 @@ fn bench_audio_encode(rows: &mut Vec<Row>) {
791 enc.finish();687 enc.finish();
792 while enc.next_packet().is_ok() {}688 while enc.next_packet().is_ok() {}
793 let wall = start.elapsed().as_secs_f64();689 let wall = start.elapsed().as_secs_f64();
794- rows.push(Row {690+ rows.push(Row::timed("ec-mp3", "encode", content.clone(), media_s, wall));
795- component: "ec-mp3",
796- direction: "encode",
797- content: content.clone(),
798- media: format!("{media_s:.1}s"),
799- wall_ms: wall * 1000.0,
800- rtf: (wall > 0.0).then_some(media_s / wall),
801- });
802 }691 }
803 692
804 // flac: single-shot, default config (4096-sample blocks, LPC-12), 16-bit.693 // flac: single-shot, default config (4096-sample blocks, LPC-12), 16-bit.
@@ -811,14 +700,7 @@ fn bench_audio_encode(rows: &mut Vec<Row>) {
811 let start = Instant::now();700 let start = Instant::now();
812 let _ = ec_flac::encode(&cfg, &samples, channels, 16, rate).expect("flac encode");701 let _ = ec_flac::encode(&cfg, &samples, channels, 16, rate).expect("flac encode");
813 let wall = start.elapsed().as_secs_f64();702 let wall = start.elapsed().as_secs_f64();
814- rows.push(Row {703+ rows.push(Row::timed("ec-flac", "encode", content.clone(), media_s, wall));
815- component: "ec-flac",
816- direction: "encode",
817- content: content.clone(),
818- media: format!("{media_s:.1}s"),
819- wall_ms: wall * 1000.0,
820- rtf: (wall > 0.0).then_some(media_s / wall),
821- });
822 }704 }
823 705
824 // alac: 4096-sample frames, 16-bit -- same shape the round-trip tests use.706 // alac: 4096-sample frames, 16-bit -- same shape the round-trip tests use.
@@ -834,14 +716,7 @@ fn bench_audio_encode(rows: &mut Vec<Row>) {
834 enc.encode_frame(chunk).expect("alac frame");716 enc.encode_frame(chunk).expect("alac frame");
835 }717 }
836 let wall = start.elapsed().as_secs_f64();718 let wall = start.elapsed().as_secs_f64();
837- rows.push(Row {719+ rows.push(Row::timed("ec-alac", "encode", content.clone(), media_s, wall));
838- component: "ec-alac",
839- direction: "encode",
840- content: content.clone(),
841- media: format!("{media_s:.1}s"),
842- wall_ms: wall * 1000.0,
843- rtf: (wall > 0.0).then_some(media_s / wall),
844- });
845 }720 }
846 721
847 // ac3: 192 kbit/s -- only if the source's channel count is one A/52 codes.722 // ac3: 192 kbit/s -- only if the source's channel count is one A/52 codes.
@@ -863,14 +738,7 @@ fn bench_audio_encode(rows: &mut Vec<Row>) {
863 }738 }
864 }739 }
865 let wall = start.elapsed().as_secs_f64();740 let wall = start.elapsed().as_secs_f64();
866- rows.push(Row {741+ rows.push(Row::timed("ec-ac3", "encode", content, media_s, wall));
867- component: "ec-ac3",
868- direction: "encode",
869- content,
870- media: format!("{media_s:.1}s"),
871- wall_ms: wall * 1000.0,
872- rtf: (wall > 0.0).then_some(media_s / wall),
873- });
874 } else {742 } else {
875 rows.push(missing_direction(743 rows.push(missing_direction(
876 "ec-ac3",744 "ec-ac3",
@@ -930,14 +798,7 @@ fn bench_truehd(rows: &mut Vec<Row>) {
930 thd.extend_from_slice(&pkt.data);798 thd.extend_from_slice(&pkt.data);
931 }799 }
932 let wall = start.elapsed().as_secs_f64();800 let wall = start.elapsed().as_secs_f64();
933- rows.push(Row {801+ rows.push(Row::timed("ec-truehd", "encode", format!("{media_s:.1}s wav16 stereo @ {rate}Hz"), media_s, wall));
934- component: "ec-truehd",
935- direction: "encode",
936- content: format!("{media_s:.1}s wav16 stereo @ {rate}Hz"),
937- media: format!("{media_s:.1}s"),
938- wall_ms: wall * 1000.0,
939- rtf: (wall > 0.0).then_some(media_s / wall),
940- });
941 802
942 let mut dec = ec_truehd::TrueHdDecoder::new();803 let mut dec = ec_truehd::TrueHdDecoder::new();
943 let start = Instant::now();804 let start = Instant::now();
@@ -957,14 +818,7 @@ fn bench_truehd(rows: &mut Vec<Row>) {
957 }818 }
958 let wall = start.elapsed().as_secs_f64();819 let wall = start.elapsed().as_secs_f64();
959 let media_s = samples as f64 / f64::from(rate);820 let media_s = samples as f64 / f64::from(rate);
960- rows.push(Row {821+ rows.push(Row::timed("ec-truehd", "decode", "own encoded stream, stereo".to_string(), media_s, wall));
961- component: "ec-truehd",
962- direction: "decode",
963- content: "own encoded stream, stereo".to_string(),
964- media: format!("{media_s:.1}s"),
965- wall_ms: wall * 1000.0,
966- rtf: (wall > 0.0).then_some(media_s / wall),
967- });
968 }822 }
969 823
970 // ---------------------------------------------------------------------------824 // ---------------------------------------------------------------------------
tools/oracle/Cargo.tomldeleted+0 -16
@@ -1,16 +0,0 @@
1-[package]
2-name = "oracle"
3-version.workspace = true
4-edition.workspace = true
5-license.workspace = true
6-authors.workspace = true
7-publish = false
8-
9-[[bin]]
10-name = "oracle"
11-path = "src/main.rs"
12-
13-# No dependencies on purpose: the oracle drives ffmpeg/ffprobe through std process
14-# pipes so that comparison tooling can never leak into any ec-* crate's dep graph.
15-[dependencies]
16-ec-testkit.workspace = true
tools/oracle/src/main.rsdeleted+0 -579
@@ -1,579 +0,0 @@
1-//! `oracle` — ffmpeg-backed comparison harness for the edith_codecs family.
2-//!
3-//! ffmpeg/ffprobe are ORACLE tooling: they are driven here through `std::process`
4-//! pipes so no `ec-*` crate ever gains a media dependency, sync or async.
5-//!
6-//! Subcommands:
7-//! `bit-exact <a> <b>` byte-identical check
8-//! `audio-compare <ours.raw> <ref-file>` per-channel correlation + RMS delta
9-//! `video-compare <ours.raw> <ref-file>` per-frame PSNR, min/mean
10-//!
11-//! `<ours.raw>` is our decoder's raw output: interleaved f32 LE for audio, raw
12-//! planar/packed frames in `--pix-fmt` order for video. The reference is any file
13-//! ffmpeg can decode; it is decoded to the same raw layout and compared.
14-//!
15-//! stdout is TSV (every line `type<TAB>...`), stderr is the human summary.
16-//! Exit code: 0 = PASS, 1 = FAIL, 2 = usage/IO error.
17-
18-#![forbid(unsafe_code)]
19-
20-use std::collections::HashMap;
21-use std::process::Stdio;
22-
23-const USAGE: &str = "\
24-oracle — comparison harness (ffmpeg is test tooling only)
25-
26- oracle bit-exact <a> <b>
27- oracle audio-compare <ours.f32le.raw> <ref-file> [--channels N] [--min-corr F] [--max-rms F]
28- oracle video-compare <ours.raw> <ref-file> [--pix-fmt FMT] [--size WxH] [--min-psnr DB]
29-
30-Defaults: --min-corr 0.999 --max-rms 1e-3 --min-psnr 40
31-Missing --channels/--pix-fmt/--size are probed from <ref-file> with ffprobe.
32-";
33-
34-fn main() {
35- let argv: Vec<String> = std::env::args().skip(1).collect();
36- let rc = match argv.first().map(String::as_str) {
37- Some("bit-exact") => run(cmd_bit_exact(&argv[1..])),
38- Some("audio-compare") => run(cmd_audio_compare(&argv[1..])),
39- Some("video-compare") => run(cmd_video_compare(&argv[1..])),
40- Some("-h") | Some("--help") => {
41- print!("{USAGE}");
42- 0
43- }
44- _ => {
45- eprint!("{USAGE}");
46- 2
47- }
48- };
49- std::process::exit(rc);
50-}
51-
52-fn run(r: Result<bool, String>) -> i32 {
53- match r {
54- Ok(true) => 0,
55- Ok(false) => 1,
56- Err(e) => {
57- eprintln!("oracle: {e}");
58- 2
59- }
60- }
61-}
62-
63-// ------------------------------------------------------------------ args ---
64-
65-struct Args {
66- pos: Vec<String>,
67- flags: HashMap<String, String>,
68-}
69-
70-impl Args {
71- fn parse(argv: &[String]) -> Result<Self, String> {
72- let mut pos = Vec::new();
73- let mut flags = HashMap::new();
74- let mut it = argv.iter();
75- while let Some(a) = it.next() {
76- if let Some(key) = a.strip_prefix("--") {
77- let v = it
78- .next()
79- .ok_or_else(|| format!("flag --{key} needs a value"))?;
80- flags.insert(key.to_string(), v.clone());
81- } else {
82- pos.push(a.clone());
83- }
84- }
85- Ok(Self { pos, flags })
86- }
87-
88- fn num<T: std::str::FromStr>(&self, key: &str, default: T) -> Result<T, String> {
89- match self.flags.get(key) {
90- None => Ok(default),
91- Some(v) => v.parse().map_err(|_| format!("bad --{key} value: {v}")),
92- }
93- }
94-}
95-
96-// --------------------------------------------------------------- ffmpeg ----
97-
98-/// Decode `input` with ffmpeg and return the raw bytes it writes to stdout.
99-/// stderr is inherited so a large error log can never deadlock the pipe.
100-fn ffmpeg_raw(input: &str, extra: &[&str]) -> Result<Vec<u8>, String> {
101- let out = ec_testkit::ffmpeg()
102- .args(["-nostdin", "-v", "error", "-i", input])
103- .args(extra)
104- .arg("-")
105- .stdout(Stdio::piped())
106- .stderr(Stdio::inherit())
107- .output()
108- .map_err(|e| format!("spawning ffmpeg: {e}"))?;
109- if !out.status.success() {
110- return Err(format!("ffmpeg failed on {input} ({})", out.status));
111- }
112- if out.stdout.is_empty() {
113- return Err(format!("ffmpeg produced no data for {input}"));
114- }
115- Ok(out.stdout)
116-}
117-
118-/// `ffprobe -show_entries stream=<entries>` as a key -> value map (first stream wins).
119-fn ffprobe(input: &str, select: &str, entries: &str) -> Result<HashMap<String, String>, String> {
120- let out = ec_testkit::ffprobe()
121- .args(["-v", "error", "-select_streams", select, "-show_entries"])
122- .arg(format!("stream={entries}"))
123- .args(["-of", "default=nw=1"])
124- .arg(input)
125- .stderr(Stdio::inherit())
126- .output()
127- .map_err(|e| format!("spawning ffprobe: {e}"))?;
128- if !out.status.success() {
129- return Err(format!("ffprobe failed on {input} ({})", out.status));
130- }
131- let mut map = HashMap::new();
132- for line in String::from_utf8_lossy(&out.stdout).lines() {
133- if let Some((k, v)) = line.split_once('=')
134- && v != "N/A"
135- {
136- map.entry(k.to_string()).or_insert_with(|| v.to_string());
137- }
138- }
139- Ok(map)
140-}
141-
142-fn read_file(path: &str) -> Result<Vec<u8>, String> {
143- std::fs::read(path).map_err(|e| format!("reading {path}: {e}"))
144-}
145-
146-// ------------------------------------------------------------ bit-exact ----
147-
148-fn cmd_bit_exact(argv: &[String]) -> Result<bool, String> {
149- let a = Args::parse(argv)?;
150- if a.pos.len() != 2 {
151- return Err("bit-exact needs exactly two files".into());
152- }
153- let (x, y) = (read_file(&a.pos[0])?, read_file(&a.pos[1])?);
154- let first_diff = x.iter().zip(&y).position(|(p, q)| p != q);
155- let pass = x.len() == y.len() && first_diff.is_none();
156-
157- println!("meta\ta\t{}", a.pos[0]);
158- println!("meta\tb\t{}", a.pos[1]);
159- println!("meta\tlen_a\t{}", x.len());
160- println!("meta\tlen_b\t{}", y.len());
161- match first_diff {
162- Some(off) => println!("diff\tfirst_offset\t{off}"),
163- None => println!("diff\tfirst_offset\t-"),
164- }
165- println!("verdict\t{}", if pass { "PASS" } else { "FAIL" });
166- eprintln!(
167- "bit-exact: {} ({} vs {} bytes, first diff {})",
168- if pass { "PASS" } else { "FAIL" },
169- x.len(),
170- y.len(),
171- first_diff.map_or("-".into(), |o| o.to_string())
172- );
173- Ok(pass)
174-}
175-
176-// -------------------------------------------------------------- audio ------
177-
178-fn deinterleave_f32(buf: &[u8], channels: usize) -> Vec<Vec<f64>> {
179- let frames = buf.len() / 4 / channels;
180- let mut out = vec![Vec::with_capacity(frames); channels];
181- for f in 0..frames {
182- for (c, ch) in out.iter_mut().enumerate() {
183- let i = (f * channels + c) * 4;
184- ch.push(f32::from_le_bytes([buf[i], buf[i + 1], buf[i + 2], buf[i + 3]]) as f64);
185- }
186- }
187- out
188-}
189-
190-/// Pearson correlation. Two constant signals correlate perfectly iff equal.
191-fn corr(a: &[f64], b: &[f64]) -> f64 {
192- let n = a.len().min(b.len());
193- if n == 0 {
194- return 0.0;
195- }
196- let (ma, mb) = (
197- a[..n].iter().sum::<f64>() / n as f64,
198- b[..n].iter().sum::<f64>() / n as f64,
199- );
200- let (mut num, mut da, mut db) = (0.0, 0.0, 0.0);
201- for i in 0..n {
202- let (x, y) = (a[i] - ma, b[i] - mb);
203- num += x * y;
204- da += x * x;
205- db += y * y;
206- }
207- if da == 0.0 || db == 0.0 {
208- return if da == db && (ma - mb).abs() < 1e-12 {
209- 1.0
210- } else {
211- 0.0
212- };
213- }
214- num / (da * db).sqrt()
215-}
216-
217-fn rms_delta(a: &[f64], b: &[f64]) -> (f64, f64) {
218- let n = a.len().min(b.len());
219- if n == 0 {
220- return (f64::INFINITY, f64::INFINITY);
221- }
222- let mut sum = 0.0;
223- let mut peak: f64 = 0.0;
224- for i in 0..n {
225- let d = a[i] - b[i];
226- sum += d * d;
227- peak = peak.max(d.abs());
228- }
229- ((sum / n as f64).sqrt(), peak)
230-}
231-
232-fn cmd_audio_compare(argv: &[String]) -> Result<bool, String> {
233- let a = Args::parse(argv)?;
234- if a.pos.len() != 2 {
235- return Err("audio-compare needs <ours.raw> <ref-file>".into());
236- }
237- let (ours_path, ref_path) = (&a.pos[0], &a.pos[1]);
238- let min_corr: f64 = a.num("min-corr", 0.999)?;
239- let max_rms: f64 = a.num("max-rms", 1e-3)?;
240-
241- let probe = ffprobe(ref_path, "a:0", "channels,sample_rate")?;
242- let channels: usize = match a.flags.get("channels") {
243- Some(v) => v.parse().map_err(|_| "bad --channels".to_string())?,
244- None => probe
245- .get("channels")
246- .ok_or("could not probe channel count; pass --channels")?
247- .parse()
248- .map_err(|_| "bad probed channel count".to_string())?,
249- };
250- if channels == 0 {
251- return Err("channel count is zero".into());
252- }
253- let rate = probe
254- .get("sample_rate")
255- .cloned()
256- .unwrap_or_else(|| "-".into());
257-
258- let ours = read_file(ours_path)?;
259- let reference = ffmpeg_raw(
260- ref_path,
261- &["-map", "0:a:0", "-f", "f32le", "-acodec", "pcm_f32le"],
262- )?;
263- let (na, nb) = (ours.len() / 4 / channels, reference.len() / 4 / channels);
264- let (ca, cb) = (
265- deinterleave_f32(&ours, channels),
266- deinterleave_f32(&reference, channels),
267- );
268-
269- println!("meta\tours\t{ours_path}");
270- println!("meta\tref\t{ref_path}");
271- println!("meta\tchannels\t{channels}");
272- println!("meta\tsample_rate\t{rate}");
273- println!("meta\tframes_ours\t{na}");
274- println!("meta\tframes_ref\t{nb}");
275-
276- // A length gap beyond one percent is a decoder bug (dropped/duplicated
277- // packets), not a comparison detail — it fails on its own.
278- let len_ok = na.abs_diff(nb) as f64 <= 0.01 * na.max(nb) as f64;
279- let mut min_c = f64::INFINITY;
280- let mut max_r: f64 = 0.0;
281- for c in 0..channels {
282- let k = corr(&ca[c], &cb[c]);
283- let (r, p) = rms_delta(&ca[c], &cb[c]);
284- min_c = min_c.min(k);
285- max_r = max_r.max(r);
286- println!("ch\t{c}\tcorr\t{k:.6}\trms\t{r:.8}\tpeak\t{p:.8}");
287- }
288- let pass = len_ok && min_c >= min_corr && max_r <= max_rms;
289- println!(
290- "verdict\t{}\tmin_corr={min_c:.6}\tmax_rms={max_r:.8}\tlen_ok={len_ok}",
291- if pass { "PASS" } else { "FAIL" }
292- );
293- eprintln!(
294- "audio-compare: {} — {channels}ch @{rate}, min corr {min_c:.6} (>= {min_corr}), \
295- max RMS delta {max_r:.8} (<= {max_rms}), lengths {na}/{nb}",
296- if pass { "PASS" } else { "FAIL" }
297- );
298- Ok(pass)
299-}
300-
301-// -------------------------------------------------------------- video ------
302-
303-/// Raw-frame geometry for a pixel format: total samples, luma samples (0 when the
304-/// format is packed and has no contiguous luma plane), bytes per sample, max value.
305-struct PixGeom {
306- samples: usize,
307- luma: usize,
308- bps: usize,
309- max: f64,
310-}
311-
312-fn pix_geom(pix_fmt: &str, w: usize, h: usize) -> Result<PixGeom, String> {
313- let wh = w * h;
314- let g = |samples: usize, luma: usize, bps: usize, max: f64| PixGeom {
315- samples,
316- luma,
317- bps,
318- max,
319- };
320- // Semi-planar formats carry their depth inside the name, so match them first.
321- match pix_fmt {
322- "nv12" | "nv21" => return Ok(g(wh * 3 / 2, wh, 1, 255.0)),
323- "p010le" | "p010be" => return Ok(g(wh * 3 / 2, wh, 2, 1023.0)),
324- "p016le" | "p016be" => return Ok(g(wh * 3 / 2, wh, 2, 65535.0)),
325- _ => {}
326- }
327- let mut base = pix_fmt;
328- let mut bps = 1;
329- let mut max = 255.0;
330- for (suffix, depth) in [("9", 9u32), ("10", 10), ("12", 12), ("14", 14), ("16", 16)] {
331- for endian in ["le", "be"] {
332- let s = format!("{suffix}{endian}");
333- if let Some(b) = pix_fmt.strip_suffix(&s) {
334- base = b;
335- bps = 2;
336- max = ((1u32 << depth) - 1) as f64;
337- }
338- }
339- }
340- let geom = match base {
341- "yuv420p" | "yuvj420p" => g(wh * 3 / 2, wh, bps, max),
342- "yuv422p" | "yuvj422p" => g(wh * 2, wh, bps, max),
343- "yuv444p" | "yuvj444p" | "gbrp" => g(wh * 3, wh, bps, max),
344- "gray" => g(wh, wh, bps, max),
345- // Packed: no contiguous luma plane, so luma PSNR falls back to all-plane.
346- "yuyv422" | "uyvy422" => g(wh * 2, 0, bps, max),
347- "rgb24" | "bgr24" => g(wh * 3, 0, bps, max),
348- "rgba" | "bgra" | "argb" | "abgr" => g(wh * 4, 0, bps, max),
349- _ => return Err(format!("unsupported pix_fmt for raw compare: {pix_fmt}")),
350- };
351- Ok(geom)
352-}
353-
354-fn sample(buf: &[u8], i: usize, bps: usize) -> f64 {
355- if bps == 1 {
356- buf[i] as f64
357- } else {
358- u16::from_le_bytes([buf[2 * i], buf[2 * i + 1]]) as f64
359- }
360-}
361-
362-/// PSNR over `n` samples starting at sample index `off` in both buffers.
363-fn psnr(a: &[u8], b: &[u8], off: usize, n: usize, bps: usize, max: f64) -> f64 {
364- let mut sum = 0.0;
365- for i in off..off + n {
366- let d = sample(a, i, bps) - sample(b, i, bps);
367- sum += d * d;
368- }
369- let mse = sum / n as f64;
370- if mse == 0.0 {
371- f64::INFINITY
372- } else {
373- 10.0 * (max * max / mse).log10()
374- }
375-}
376-
377-fn cmd_video_compare(argv: &[String]) -> Result<bool, String> {
378- let a = Args::parse(argv)?;
379- if a.pos.len() != 2 {
380- return Err("video-compare needs <ours.raw> <ref-file>".into());
381- }
382- let (ours_path, ref_path) = (&a.pos[0], &a.pos[1]);
383- let min_psnr: f64 = a.num("min-psnr", 40.0)?;
384-
385- let probe = ffprobe(ref_path, "v:0", "width,height,pix_fmt")?;
386- let pix = match a.flags.get("pix-fmt") {
387- Some(v) => v.clone(),
388- None => probe
389- .get("pix_fmt")
390- .cloned()
391- .ok_or("could not probe pix_fmt; pass --pix-fmt")?,
392- };
393- let (w, h) = match a.flags.get("size") {
394- Some(s) => {
395- let (ws, hs) = s.split_once('x').ok_or("--size must look like 1920x1080")?;
396- (
397- ws.parse::<usize>().map_err(|_| "bad --size width")?,
398- hs.parse::<usize>().map_err(|_| "bad --size height")?,
399- )
400- }
401- None => (
402- probe
403- .get("width")
404- .ok_or("could not probe width; pass --size")?
405- .parse()
406- .map_err(|_| "bad probed width".to_string())?,
407- probe
408- .get("height")
409- .ok_or("could not probe height; pass --size")?
410- .parse()
411- .map_err(|_| "bad probed height".to_string())?,
412- ),
413- };
414-
415- let geom = pix_geom(&pix, w, h)?;
416- let frame_bytes = geom.samples * geom.bps;
417- if frame_bytes == 0 {
418- return Err("frame size computed as zero".into());
419- }
420-
421- let ours = read_file(ours_path)?;
422- let reference = ffmpeg_raw(
423- ref_path,
424- &["-map", "0:v:0", "-f", "rawvideo", "-pix_fmt", &pix],
425- )?;
426- let (fa, fb) = (ours.len() / frame_bytes, reference.len() / frame_bytes);
427- let frames = fa.min(fb);
428-
429- println!("meta\tours\t{ours_path}");
430- println!("meta\tref\t{ref_path}");
431- println!("meta\tpix_fmt\t{pix}");
432- println!("meta\tdims\t{w}x{h}");
433- println!("meta\tframe_bytes\t{frame_bytes}");
434- println!("meta\tframes_ours\t{fa}");
435- println!("meta\tframes_ref\t{fb}");
436- if frames == 0 {
437- println!("verdict\tFAIL\tno complete frame in common");
438- eprintln!("video-compare: FAIL — no complete frame in common ({fa} vs {fb})");
439- return Ok(false);
440- }
441-
442- let luma_n = if geom.luma == 0 {
443- geom.samples
444- } else {
445- geom.luma
446- };
447- let mut min_y = f64::INFINITY;
448- let mut sum_y = 0.0;
449- let mut min_all = f64::INFINITY;
450- let mut sum_all = 0.0;
451- let mut finite_y = 0usize;
452- let mut finite_all = 0usize;
453- for f in 0..frames {
454- let off = f * geom.samples;
455- let py = psnr(&ours, &reference, off, luma_n, geom.bps, geom.max);
456- let pa = psnr(&ours, &reference, off, geom.samples, geom.bps, geom.max);
457- min_y = min_y.min(py);
458- min_all = min_all.min(pa);
459- if py.is_finite() {
460- sum_y += py;
461- finite_y += 1;
462- }
463- if pa.is_finite() {
464- sum_all += pa;
465- finite_all += 1;
466- }
467- println!("frame\t{f}\tpsnr_y\t{py:.4}\tpsnr_all\t{pa:.4}");
468- }
469- // Mean over finite frames only: identical frames give +inf and would otherwise
470- // poison the average of a run that also contains real differences.
471- let mean_y = if finite_y == 0 {
472- f64::INFINITY
473- } else {
474- sum_y / finite_y as f64
475- };
476- let mean_all = if finite_all == 0 {
477- f64::INFINITY
478- } else {
479- sum_all / finite_all as f64
480- };
481- let len_ok = fa == fb;
482- let pass = len_ok && min_y >= min_psnr;
483- println!("stats\tpsnr_y\tmin\t{min_y:.4}\tmean\t{mean_y:.4}");
484- println!("stats\tpsnr_all\tmin\t{min_all:.4}\tmean\t{mean_all:.4}");
485- println!(
486- "verdict\t{}\tmin_psnr_y={min_y:.4}\tframes={frames}\tlen_ok={len_ok}",
487- if pass { "PASS" } else { "FAIL" }
488- );
489- eprintln!(
490- "video-compare: {} — {frames} frames {w}x{h} {pix}, min luma PSNR {min_y:.4} dB \
491- (>= {min_psnr}), mean {mean_y:.4} dB, frame counts {fa}/{fb}",
492- if pass { "PASS" } else { "FAIL" }
493- );
494- Ok(pass)
495-}
496-
497-#[cfg(test)]
498-mod tests {
499- use super::*;
500-
501- #[test]
502- fn corr_identical_and_inverted() {
503- let a = [0.0, 1.0, -1.0, 0.5, -0.25];
504- let inv: Vec<f64> = a.iter().map(|x| -x).collect();
505- assert!((corr(&a, &a) - 1.0).abs() < 1e-12);
506- assert!((corr(&a, &inv) + 1.0).abs() < 1e-12);
507- // Silence vs silence correlates; silence vs DC offset does not.
508- assert_eq!(corr(&[0.0; 4], &[0.0; 4]), 1.0);
509- assert_eq!(corr(&[0.0; 4], &[1.0; 4]), 0.0);
510- }
511-
512- #[test]
513- fn rms_and_peak_delta() {
514- let (r, p) = rms_delta(&[0.0, 0.0, 0.0], &[0.0, 0.0, 0.0]);
515- assert_eq!((r, p), (0.0, 0.0));
516- let (r, p) = rms_delta(&[1.0, -1.0], &[0.0, 0.0]);
517- assert!((r - 1.0).abs() < 1e-12 && (p - 1.0).abs() < 1e-12);
518- }
519-
520- #[test]
521- fn psnr_identical_is_infinite_and_differing_is_finite() {
522- let a = vec![10u8, 20, 30, 40];
523- assert!(psnr(&a, &a, 0, 4, 1, 255.0).is_infinite());
524- let b = vec![11u8, 21, 31, 41];
525- let p = psnr(&a, &b, 0, 4, 1, 255.0);
526- // MSE 1 over 8-bit range: 10*log10(255^2) = 48.13 dB.
527- assert!((p - 48.1308).abs() < 1e-3, "psnr={p}");
528- // 10-bit path reads little-endian u16 pairs.
529- let x = [0u8, 1, 0, 1];
530- let y = [1u8, 1, 0, 1];
531- assert!(psnr(&x, &y, 0, 2, 2, 1023.0).is_finite());
532- }
533-
534- #[test]
535- fn pix_geom_covers_the_generated_fixture_formats() {
536- let (w, h) = (1920, 1080);
537- let g = pix_geom("yuv420p", w, h).unwrap();
538- assert_eq!(
539- (g.samples, g.luma, g.bps, g.max),
540- (w * h * 3 / 2, w * h, 1, 255.0)
541- );
542- let g = pix_geom("yuv420p10le", w, h).unwrap();
543- assert_eq!(
544- (g.samples, g.luma, g.bps, g.max),
545- (w * h * 3 / 2, w * h, 2, 1023.0)
546- );
547- let g = pix_geom("p010le", w, h).unwrap();
548- assert_eq!((g.samples, g.bps, g.max), (w * h * 3 / 2, 2, 1023.0));
549- assert_eq!(pix_geom("yuv444p", w, h).unwrap().samples, w * h * 3);
550- assert_eq!(pix_geom("yuyv422", w, h).unwrap().luma, 0);
551- assert!(pix_geom("no_such_fmt", w, h).is_err());
552- }
553-
554- #[test]
555- fn deinterleave_splits_channels() {
556- let mut buf = Vec::new();
557- for f in 0..3u32 {
558- for c in 0..2u32 {
559- buf.extend_from_slice(&((f * 10 + c) as f32).to_le_bytes());
560- }
561- }
562- let ch = deinterleave_f32(&buf, 2);
563- assert_eq!(ch[0], vec![0.0, 10.0, 20.0]);
564- assert_eq!(ch[1], vec![1.0, 11.0, 21.0]);
565- }
566-
567- #[test]
568- fn args_parse_flags_and_positionals() {
569- let argv: Vec<String> = ["a.raw", "b.mp4", "--min-corr", "0.5"]
570- .iter()
571- .map(|s| s.to_string())
572- .collect();
573- let a = Args::parse(&argv).unwrap();
574- assert_eq!(a.pos, ["a.raw", "b.mp4"]);
575- assert_eq!(a.num::<f64>("min-corr", 0.999).unwrap(), 0.5);
576- assert_eq!(a.num::<f64>("max-rms", 1e-3).unwrap(), 1e-3);
577- assert!(Args::parse(&["--dangling".to_string()]).is_err());
578- }
579-}
tools/oracle/tests/cli.rsdeleted+0 -129
@@ -1,129 +0,0 @@
1-//! Self-test of the `oracle` CLI itself: drives the built binary the way a codec
2-//! crate's test will, using ffmpeg as both the "our decoder" stand-in and the
3-//! reference. Exercises the PASS and the FAIL path of every subcommand.
4-//!
5-
6-use std::path::{Path, PathBuf};
7-use std::process::{Command, Stdio};
8-
9-// Per-test directory: the test binary runs its cases as threads of one process,
10-// so a pid-only name would let one case delete another's raw files.
11-fn workdir(name: &str) -> PathBuf {
12- let d = std::env::temp_dir().join(format!("oracle-selftest-{}-{name}", std::process::id()));
13- std::fs::create_dir_all(&d).unwrap();
14- d
15-}
16-
17-/// Decode `input` to a raw file with ffmpeg — stands in for "our decoder's output".
18-fn decode_raw(input: &Path, out: &Path, extra: &[&str]) {
19- let f = std::fs::File::create(out).unwrap();
20- let st = ec_testkit::ffmpeg()
21- .args(["-nostdin", "-y", "-v", "error", "-i"])
22- .arg(input)
23- .args(extra)
24- .arg("-")
25- .stdout(Stdio::from(f))
26- .status()
27- .expect("ffmpeg must be installed to run the oracle self-test");
28- assert!(st.success(), "ffmpeg failed decoding {}", input.display());
29-}
30-
31-fn oracle(args: &[&str]) -> i32 {
32- Command::new(env!("CARGO_BIN_EXE_oracle"))
33- .args(args)
34- .status()
35- .expect("oracle binary")
36- .code()
37- .expect("oracle exited by signal")
38-}
39-
40-const F32: &[&str] = &["-map", "0:a:0", "-f", "f32le", "-acodec", "pcm_f32le"];
41-
42-#[test]
43-fn bit_exact_passes_on_same_decode_and_fails_on_a_different_one() {
44- let a = ec_testkit::fixture("audio/flac-stereo-48000.flac");
45- let b = ec_testkit::fixture("audio/flac-mono-48000.flac");
46- let w = workdir("bitexact");
47- let (r1, r2, r3) = (w.join("a1.raw"), w.join("a2.raw"), w.join("b.raw"));
48- decode_raw(&a, &r1, F32);
49- decode_raw(&a, &r2, F32);
50- decode_raw(&b, &r3, F32);
51-
52- assert_eq!(
53- oracle(&["bit-exact", r1.to_str().unwrap(), r2.to_str().unwrap()]),
54- 0,
55- "same file decoded twice must be bit-exact"
56- );
57- assert_eq!(
58- oracle(&["bit-exact", r1.to_str().unwrap(), r3.to_str().unwrap()]),
59- 1,
60- "different fixtures must not be bit-exact"
61- );
62- let _ = std::fs::remove_dir_all(&w);
63-}
64-
65-#[test]
66-fn audio_compare_passes_against_its_own_source_and_fails_across_rates() {
67- let a = ec_testkit::fixture("audio/flac-stereo-48000.flac");
68- let b = ec_testkit::fixture("audio/flac-stereo-44100.flac");
69- let w = workdir("audio");
70- let (ra, rb) = (w.join("a.raw"), w.join("b.raw"));
71- decode_raw(&a, &ra, F32);
72- decode_raw(&b, &rb, F32);
73-
74- assert_eq!(
75- oracle(&["audio-compare", ra.to_str().unwrap(), a.to_str().unwrap()]),
76- 0,
77- "lossless decode vs its own source must correlate at 1.0"
78- );
79- // 44.1 kHz samples against a 48 kHz reference: wrong length and wrong phase.
80- assert_eq!(
81- oracle(&["audio-compare", rb.to_str().unwrap(), a.to_str().unwrap()]),
82- 1,
83- "a different-rate decode must be rejected"
84- );
85- let _ = std::fs::remove_dir_all(&w);
86-}
87-
88-#[test]
89-fn video_compare_passes_against_its_own_source_and_fails_on_frame_count() {
90- let a = ec_testkit::fixture("video/h264-1080p-23.976-8bit.mp4");
91- let b = ec_testkit::fixture("video/h264-1080p-60-8bit.mp4");
92- let w = workdir("video");
93- let raw = w.join("a.raw");
94- decode_raw(
95- &a,
96- &raw,
97- &["-map", "0:v:0", "-f", "rawvideo", "-pix_fmt", "yuv420p"],
98- );
99-
100- assert_eq!(
101- oracle(&[
102- "video-compare",
103- raw.to_str().unwrap(),
104- a.to_str().unwrap(),
105- "--pix-fmt",
106- "yuv420p",
107- ]),
108- 0,
109- "decode vs its own source must be lossless (infinite PSNR)"
110- );
111- assert_eq!(
112- oracle(&[
113- "video-compare",
114- raw.to_str().unwrap(),
115- b.to_str().unwrap(),
116- "--pix-fmt",
117- "yuv420p",
118- ]),
119- 1,
120- "48 frames against a 120-frame reference must fail"
121- );
122- let _ = std::fs::remove_dir_all(&w);
123-}
124-
125-#[test]
126-fn bad_usage_exits_two() {
127- assert_eq!(oracle(&["no-such-subcommand"]), 2);
128- assert_eq!(oracle(&["bit-exact", "only-one-arg"]), 2);
129-}