| 1 | |
| 2 | |
| 3 | |
| 4 | |
| 5 | |
| 6 | |
| 7 | |
| 8 | |
| 9 | |
| 10 | use crate::seat; |
| 11 | |
| 12 | use std::path::{Path, PathBuf}; |
| 13 | use std::process::Command; |
| 14 | use std::time::{Duration, Instant}; |
| 15 | |
| 16 | use engine::demux::{Codec, Demuxer}; |
| 17 | use engine::export::{EncoderSeat, ExportSettings, Format}; |
| 18 | use engine::project::{Clip, Lane}; |
| 19 | use engine::scratch::Scratch; |
| 20 | use engine::{DecodeSession, PlaybackSession}; |
| 21 | |
| 22 | const W: u32 = 256; |
| 23 | const H: u32 = 144; |
| 24 | const FPS: u32 = 30; |
| 25 | const FRAMES: u32 = 60; |
| 26 | |
| 27 | const GOP: u32 = 20; |
| 28 | const IN_POINT: u32 = 27; |
| 29 | const KEPT: u32 = 24; |
| 30 | |
| 31 | fn ffmpeg_ok(args: &[String]) -> bool { |
| 32 | Command::new("ffmpeg") |
| 33 | .args(["-y", "-v", "error"]) |
| 34 | .args(args) |
| 35 | .status() |
| 36 | .is_ok_and(|s| s.success()) |
| 37 | } |
| 38 | |
| 39 | fn encoder() -> Option<&'static str> { |
| 40 | let out = Command::new("ffmpeg") |
| 41 | .args(["-hide_banner", "-encoders"]) |
| 42 | .output() |
| 43 | .ok()?; |
| 44 | let text = String::from_utf8_lossy(&out.stdout).into_owned(); |
| 45 | ["libaom-av1", "libsvtav1"] |
| 46 | .into_iter() |
| 47 | .find(|e| text.contains(e)) |
| 48 | } |
| 49 | |
| 50 | |
| 51 | fn make_av1(dir: &Path, name: &str, ext: &str, ten_bit: bool, hz: u32) -> Option<PathBuf> { |
| 52 | let enc = encoder()?; |
| 53 | let out = dir.join(format!("{name}.{ext}")); |
| 54 | let pix = if ten_bit { "yuv420p10le" } else { "yuv420p" }; |
| 55 | let mut args: Vec<String> = [ |
| 56 | "-f", |
| 57 | "lavfi", |
| 58 | "-i", |
| 59 | &format!("testsrc2=size={W}x{H}:rate={FPS}:duration={}", FRAMES / FPS), |
| 60 | "-f", |
| 61 | "lavfi", |
| 62 | "-i", |
| 63 | &format!("sine=frequency={hz}:sample_rate=48000:duration={}", FRAMES / FPS), |
| 64 | "-c:v", |
| 65 | enc, |
| 66 | "-pix_fmt", |
| 67 | pix, |
| 68 | "-g", |
| 69 | &GOP.to_string(), |
| 70 | "-keyint_min", |
| 71 | &GOP.to_string(), |
| 72 | "-c:a", |
| 73 | "aac", |
| 74 | "-shortest", |
| 75 | ] |
| 76 | .iter() |
| 77 | .map(|s| s.to_string()) |
| 78 | .collect(); |
| 79 | match enc { |
| 80 | "libaom-av1" => args.extend( |
| 81 | ["-cpu-used", "8", "-crf", "20", "-b:v", "0", "-lag-in-frames", "0"] |
| 82 | .map(String::from), |
| 83 | ), |
| 84 | _ => args.extend(["-preset", "10", "-crf", "20"].map(String::from)), |
| 85 | } |
| 86 | args.push(out.display().to_string()); |
| 87 | ffmpeg_ok(&args).then_some(out) |
| 88 | } |
| 89 | |
| 90 | |
| 91 | fn keep_from(session: &mut PlaybackSession, from: u32, len: u32) { |
| 92 | let fps = f64::from(FPS); |
| 93 | assert!(session.cut_at(f64::from(from) / fps), "cut at the in point"); |
| 94 | assert!(session.delete_clip(Lane::V1, 0), "drop the head"); |
| 95 | assert!(session.cut_at(f64::from(len) / fps), "cut at the out point"); |
| 96 | assert!(session.delete_clip(Lane::V1, 1), "drop the tail"); |
| 97 | assert_eq!(session.lane_clips(Lane::V1).len(), 1); |
| 98 | } |
| 99 | |
| 100 | fn settings() -> ExportSettings { |
| 101 | ExportSettings { |
| 102 | format: Format::Mp4, |
| 103 | seat: EncoderSeat::Software, |
| 104 | bitrate: Some(20_000_000), |
| 105 | ..Default::default() |
| 106 | } |
| 107 | } |
| 108 | |
| 109 | fn wait(handle: &engine::ExportHandle, limit: Duration) -> engine::Result<()> { |
| 110 | let started = Instant::now(); |
| 111 | while !handle.is_finished() { |
| 112 | assert!(started.elapsed() < limit, "export did not finish in {limit:?}"); |
| 113 | std::thread::sleep(Duration::from_millis(20)); |
| 114 | } |
| 115 | handle.result().expect("a finished export has an outcome") |
| 116 | } |
| 117 | |
| 118 | fn psnr(a: &[u8], b: &[u8]) -> f64 { |
| 119 | assert_eq!(a.len(), b.len()); |
| 120 | let mut sq = 0f64; |
| 121 | for (p, q) in a.chunks(4).zip(b.chunks(4)) { |
| 122 | for c in 0..3 { |
| 123 | let d = f64::from(p[c]) - f64::from(q[c]); |
| 124 | sq += d * d; |
| 125 | } |
| 126 | } |
| 127 | let mse = sq / (a.len() / 4 * 3) as f64; |
| 128 | if mse == 0.0 { |
| 129 | 99.0 |
| 130 | } else { |
| 131 | 10.0 * (255.0f64 * 255.0 / mse).log10() |
| 132 | } |
| 133 | } |
| 134 | |
| 135 | fn source_frame(path: &Path, n: u32) -> Vec<u8> { |
| 136 | let (_, rx, _c) = DecodeSession::open_range(path, n, n + 1).expect("open_range"); |
| 137 | let f = rx.into_iter().next().expect("a source frame"); |
| 138 | assert_eq!(f.index, n); |
| 139 | f.bgra |
| 140 | } |
| 141 | |
| 142 | |
| 143 | fn ffmpeg_frame(path: &Path, n: u32) -> Option<Vec<u8>> { |
| 144 | let out = Command::new("ffmpeg") |
| 145 | .args(["-v", "error", "-i"]) |
| 146 | .arg(path) |
| 147 | .args([ |
| 148 | "-vf", |
| 149 | &format!("select=eq(n\\,{n})"), |
| 150 | "-frames:v", |
| 151 | "1", |
| 152 | "-f", |
| 153 | "rawvideo", |
| 154 | "-pix_fmt", |
| 155 | "bgra", |
| 156 | "-", |
| 157 | ]) |
| 158 | .output() |
| 159 | .ok()?; |
| 160 | (out.stdout.len() == (W * H * 4) as usize).then_some(out.stdout) |
| 161 | } |
| 162 | |
| 163 | fn probe_duration(path: &Path, stream: &str) -> Option<f64> { |
| 164 | let out = Command::new("ffprobe") |
| 165 | .args(["-v", "error", "-select_streams", stream, "-show_entries", "stream=duration"]) |
| 166 | .args(["-of", "csv=p=0"]) |
| 167 | .arg(path) |
| 168 | .output() |
| 169 | .ok()?; |
| 170 | String::from_utf8_lossy(&out.stdout).trim().parse().ok() |
| 171 | } |
| 172 | |
| 173 | fn export_ok(session: &PlaybackSession, name: &str) -> Scratch { |
| 174 | let out = Scratch::file(&format!("ve_av1x_{name}"), "mp4"); |
| 175 | let handle = session.export_to_with(&out, &settings()); |
| 176 | wait(&handle, Duration::from_secs(600)).expect("the AV1 source exports with no plugin"); |
| 177 | assert!(out.exists(), "the export wrote its file"); |
| 178 | out |
| 179 | } |
| 180 | |
| 181 | |
| 182 | fn one_clip(ext: &str, ten_bit: bool) { |
| 183 | let _seat = seat::software(); |
| 184 | let dir = Scratch::dir("ve_av1x_src"); |
| 185 | let name = format!("src_{ext}_{}", if ten_bit { 10 } else { 8 }); |
| 186 | let Some(src) = make_av1(&dir, &name, ext, ten_bit, 440) else { |
| 187 | eprintln!("no AV1 encoder in ffmpeg here: skipped"); |
| 188 | return; |
| 189 | }; |
| 190 | assert_eq!(Demuxer::open(&src).expect("demux").0.codec, Codec::Av1); |
| 191 | let mut session = PlaybackSession::open(&src).expect("open the AV1 source"); |
| 192 | keep_from(&mut session, IN_POINT, KEPT); |
| 193 | let clip = session.lane_clips(Lane::V1)[0].clone(); |
| 194 | assert_eq!((clip.start, clip.in_frame), (0, IN_POINT), "the in point is mid-GOP"); |
| 195 | |
| 196 | let out = export_ok(&session, &name); |
| 197 | let (meta, _) = Demuxer::open(&out).expect("reopen"); |
| 198 | assert_eq!(meta.frame_count, KEPT, "{name}: frame count"); |
| 199 | let (_, rx) = DecodeSession::open(&out).expect("decode export"); |
| 200 | let got: Vec<_> = rx.into_iter().collect(); |
| 201 | assert_eq!(got.len() as u32, KEPT, "{name}: frames decode back"); |
| 202 | |
| 203 | |
| 204 | |
| 205 | let want = source_frame(&src, IN_POINT); |
| 206 | let p = psnr(&got[0].bgra, &want); |
| 207 | assert!(p >= 38.0, "{name}: first picture vs source frame {IN_POINT}: {p:.1} dB"); |
| 208 | |
| 209 | for off in [IN_POINT - 1, IN_POINT + 1] { |
| 210 | let q = psnr(&got[0].bgra, &source_frame(&src, off)); |
| 211 | assert!(p > q + 3.0, "{name}: frame {IN_POINT} ({p:.1}) is not clearly nearer than {off} ({q:.1})"); |
| 212 | } |
| 213 | |
| 214 | for k in [1u32, KEPT / 2, KEPT - 1] { |
| 215 | let p = psnr(&got[k as usize].bgra, &source_frame(&src, IN_POINT + k)); |
| 216 | assert!(p >= 38.0, "{name}: frame +{k} drifted: {p:.1} dB"); |
| 217 | } |
| 218 | |
| 219 | if let Some(reference) = ffmpeg_frame(&src, IN_POINT) { |
| 220 | let p = psnr(&source_frame(&src, IN_POINT), &reference); |
| 221 | assert!(p >= 30.0, "{name}: engine decode vs ffmpeg decode of frame {IN_POINT}: {p:.1} dB"); |
| 222 | } |
| 223 | |
| 224 | let (v, a) = (probe_duration(&out, "v:0"), probe_duration(&out, "a:0")); |
| 225 | if let (Some(v), Some(a)) = (v, a) { |
| 226 | let want = f64::from(KEPT) / f64::from(FPS); |
| 227 | assert!((v - want).abs() < 0.05, "{name}: picture {v:.3}s, want {want:.3}s"); |
| 228 | assert!((a - v).abs() < 0.06, "{name}: sound {a:.3}s vs picture {v:.3}s"); |
| 229 | } |
| 230 | std::fs::remove_file(&out).ok(); |
| 231 | } |
| 232 | |
| 233 | #[test] |
| 234 | fn av1_mp4_8bit_exports_from_a_mid_gop_in_point_with_no_plugin() { |
| 235 | one_clip("mp4", false); |
| 236 | } |
| 237 | |
| 238 | #[test] |
| 239 | fn av1_mp4_10bit_exports_from_a_mid_gop_in_point_with_no_plugin() { |
| 240 | one_clip("mp4", true); |
| 241 | } |
| 242 | |
| 243 | #[test] |
| 244 | fn av1_mkv_8bit_exports_from_a_mid_gop_in_point_with_no_plugin() { |
| 245 | one_clip("mkv", false); |
| 246 | } |
| 247 | |
| 248 | #[test] |
| 249 | fn av1_mkv_10bit_exports_from_a_mid_gop_in_point_with_no_plugin() { |
| 250 | one_clip("mkv", true); |
| 251 | } |
| 252 | |
| 253 | |
| 254 | #[test] |
| 255 | fn two_av1_clips_back_to_back_export_in_order() { |
| 256 | let _seat = seat::software(); |
| 257 | let dir = Scratch::dir("ve_av1x_two"); |
| 258 | let (Some(a), Some(b)) = ( |
| 259 | make_av1(&dir, "a", "mkv", false, 440), |
| 260 | make_av1(&dir, "b", "mp4", true, 880), |
| 261 | ) else { |
| 262 | eprintln!("no AV1 encoder in ffmpeg here: skipped"); |
| 263 | return; |
| 264 | }; |
| 265 | let mut session = PlaybackSession::open(&a).expect("open a"); |
| 266 | keep_from(&mut session, IN_POINT, KEPT); |
| 267 | session.import(&b).expect("import b"); |
| 268 | let second = Clip::source_range(1, 10, 10 + KEPT); |
| 269 | assert!(session.place_at(Lane::V1, f64::from(KEPT) / f64::from(FPS), second), "place b after a"); |
| 270 | let clips = session.lane_clips(Lane::V1).to_vec(); |
| 271 | assert_eq!(clips.len(), 2, "both clips on the lane"); |
| 272 | let total: u32 = clips.iter().map(|c| c.out_frame - c.in_frame).sum(); |
| 273 | |
| 274 | let out = export_ok(&session, "two"); |
| 275 | let (meta, _) = Demuxer::open(&out).expect("reopen"); |
| 276 | assert_eq!(meta.frame_count, total, "frame count is the sum of the clips"); |
| 277 | let (_, rx) = DecodeSession::open(&out).expect("decode export"); |
| 278 | let got: Vec<_> = rx.into_iter().collect(); |
| 279 | assert_eq!(got.len() as u32, total); |
| 280 | let first = clips[0].out_frame - clips[0].in_frame; |
| 281 | let p0 = psnr(&got[0].bgra, &source_frame(&a, IN_POINT)); |
| 282 | let p1 = psnr(&got[first as usize].bgra, &source_frame(&b, clips[1].in_frame)); |
| 283 | assert!(p0 >= 38.0, "first clip's first picture: {p0:.1} dB"); |
| 284 | assert!(p1 >= 38.0, "second clip's first picture: {p1:.1} dB"); |
| 285 | std::fs::remove_file(&out).ok(); |
| 286 | } |
| 287 | |
| 288 | |
| 289 | #[test] |
| 290 | fn cancelling_an_av1_source_export_leaves_no_file() { |
| 291 | let _seat = seat::software(); |
| 292 | let dir = Scratch::dir("ve_av1x_cancel"); |
| 293 | let Some(src) = make_av1(&dir, "c", "mkv", false, 440) else { |
| 294 | eprintln!("no AV1 encoder in ffmpeg here: skipped"); |
| 295 | return; |
| 296 | }; |
| 297 | let session = PlaybackSession::open(&src).expect("open"); |
| 298 | let out = Scratch::file("ve_av1x_cancel_out", "mp4"); |
| 299 | let handle = session.export_to_with(&out, &settings()); |
| 300 | let started = Instant::now(); |
| 301 | while handle.progress() < 0.05 { |
| 302 | assert!(started.elapsed() < Duration::from_secs(120), "export never got going"); |
| 303 | assert!(!handle.is_finished(), "export finished before it was cancelled"); |
| 304 | std::thread::sleep(Duration::from_millis(10)); |
| 305 | } |
| 306 | handle.cancel(); |
| 307 | let result = wait(&handle, Duration::from_secs(60)); |
| 308 | assert!(result.is_err(), "a cancelled export is an error"); |
| 309 | assert!(!out.exists(), "no partial file survives a cancel"); |
| 310 | assert!( |
| 311 | !PathBuf::from(format!("{}.part", out.display())).exists(), |
| 312 | "the .part is cleaned up too" |
| 313 | ); |
| 314 | } |