| 1 | |
| 2 | |
| 3 | |
| 4 | |
| 5 | |
| 6 | |
| 7 | |
| 8 | |
| 9 | |
| 10 | |
| 11 | |
| 12 | |
| 13 | |
| 14 | |
| 15 | |
| 16 | |
| 17 | |
| 18 | |
| 19 | |
| 20 | |
| 21 | use std::fs::File; |
| 22 | use std::io::BufReader; |
| 23 | use std::path::{Path, PathBuf}; |
| 24 | use std::sync::{Mutex, Once}; |
| 25 | use std::time::{Duration, Instant}; |
| 26 | |
| 27 | |
| 28 | |
| 29 | |
| 30 | static PROXY_FILM: Mutex<()> = Mutex::new(()); |
| 31 | |
| 32 | use ec_core::registry::{CodecId, CodecParameters, Decoder as _}; |
| 33 | use ec_core::{Packet, TimeBase}; |
| 34 | use ec_h264::H264Decoder; |
| 35 | use engine::export::ExportSettings; |
| 36 | use engine::hw::HwEncoder; |
| 37 | use engine::mux::{parameter_sets, AudioParams, Mp4Muxer, VideoParams}; |
| 38 | use engine::project::{Lane, Source, Speed}; |
| 39 | use engine::scale::FitPolicy; |
| 40 | use engine::scratch::Scratch; |
| 41 | use engine::{DecodeSession, ExportHandle, PlaybackSession, Project, Rotation}; |
| 42 | |
| 43 | const FPS: f64 = 30.0; |
| 44 | |
| 45 | fn asset(name: &str) -> PathBuf { |
| 46 | PathBuf::from(env!("CARGO_MANIFEST_DIR")) |
| 47 | .join("../../assets") |
| 48 | .join(name) |
| 49 | } |
| 50 | |
| 51 | |
| 52 | |
| 53 | |
| 54 | fn out_path(name: &str) -> Scratch { |
| 55 | Scratch::file(&format!("ve_export_{name}"), "mp4") |
| 56 | } |
| 57 | |
| 58 | |
| 59 | |
| 60 | fn part_path(out: &Path) -> PathBuf { |
| 61 | PathBuf::from(format!("{}.part", out.display())) |
| 62 | } |
| 63 | |
| 64 | |
| 65 | |
| 66 | |
| 67 | |
| 68 | |
| 69 | |
| 70 | |
| 71 | |
| 72 | |
| 73 | |
| 74 | |
| 75 | static SEAT: std::sync::RwLock<()> = std::sync::RwLock::new(()); |
| 76 | |
| 77 | type Shared = std::sync::RwLockReadGuard<'static, ()>; |
| 78 | |
| 79 | |
| 80 | |
| 81 | |
| 82 | |
| 83 | #[must_use = "the seat pin holds only while its guard is alive"] |
| 84 | fn pin_software() -> Shared { |
| 85 | let borrowed = SEAT.read().unwrap_or_else(|poisoned| poisoned.into_inner()); |
| 86 | static PIN: Once = Once::new(); |
| 87 | PIN.call_once(|| unsafe { |
| 88 | std::env::set_var("VE_SW", "1"); |
| 89 | std::env::set_var("VE_SW_ENC", "1"); |
| 90 | }); |
| 91 | borrowed |
| 92 | } |
| 93 | |
| 94 | |
| 95 | |
| 96 | |
| 97 | #[must_use = "the seat pin holds only while its guard is alive"] |
| 98 | fn pin_hardware() -> Shared { |
| 99 | let borrowed = SEAT.read().unwrap_or_else(|poisoned| poisoned.into_inner()); |
| 100 | static PIN: Once = Once::new(); |
| 101 | PIN.call_once(|| unsafe { |
| 102 | std::env::remove_var("VE_SW"); |
| 103 | std::env::remove_var("VE_SW_ENC"); |
| 104 | }); |
| 105 | borrowed |
| 106 | } |
| 107 | |
| 108 | |
| 109 | |
| 110 | fn edited(source: &Path) -> PlaybackSession { |
| 111 | let mut session = PlaybackSession::open(source).expect("open source"); |
| 112 | assert!(session.cut_at(30.0 / FPS), "cut at frame 30"); |
| 113 | assert!(session.cut_at(60.0 / FPS), "cut at frame 60"); |
| 114 | assert!(session.delete_clip(Lane::V1, 1), "drop the middle clip"); |
| 115 | assert_eq!(session.clip_spans().len(), 2); |
| 116 | session |
| 117 | } |
| 118 | |
| 119 | fn wait(handle: &ExportHandle, limit: Duration) -> engine::Result<()> { |
| 120 | let started = Instant::now(); |
| 121 | while !handle.is_finished() { |
| 122 | assert!( |
| 123 | started.elapsed() < limit, |
| 124 | "export did not finish in {limit:?}" |
| 125 | ); |
| 126 | std::thread::sleep(Duration::from_millis(20)); |
| 127 | } |
| 128 | handle.result().expect("a finished export has an outcome") |
| 129 | } |
| 130 | |
| 131 | |
| 132 | fn decode_all(path: &Path) -> Vec<Vec<u8>> { |
| 133 | let (_, frames) = DecodeSession::open(path).expect("open export"); |
| 134 | frames.into_iter().map(|frame| frame.bgra).collect() |
| 135 | } |
| 136 | |
| 137 | |
| 138 | |
| 139 | |
| 140 | |
| 141 | fn ffmpeg_complaints(path: &Path) -> Option<String> { |
| 142 | let said = std::process::Command::new("ffmpeg") |
| 143 | .args(["-v", "error", "-i"]) |
| 144 | .arg(path) |
| 145 | .args(["-f", "null", "-"]) |
| 146 | .output() |
| 147 | .ok()?; |
| 148 | Some(String::from_utf8_lossy(&said.stderr).trim().to_string()) |
| 149 | } |
| 150 | |
| 151 | |
| 152 | fn frame_at(path: &Path, index: u32) -> Vec<u8> { |
| 153 | let (_, frames, _) = DecodeSession::open_at(path, index).expect("open source"); |
| 154 | frames.recv().expect("frame present").bgra |
| 155 | } |
| 156 | |
| 157 | fn mean_abs_diff(a: &[u8], b: &[u8]) -> f64 { |
| 158 | assert_eq!(a.len(), b.len(), "frame sizes differ"); |
| 159 | a.iter() |
| 160 | .zip(b) |
| 161 | .map(|(x, y)| f64::from(x.abs_diff(*y))) |
| 162 | .sum::<f64>() |
| 163 | / a.len() as f64 |
| 164 | } |
| 165 | |
| 166 | |
| 167 | |
| 168 | fn round_trip(name: &str, limit: Duration) { |
| 169 | let source = asset("test_baseline.mp4"); |
| 170 | let mut session = edited(&source); |
| 171 | session.pause(); |
| 172 | let out = out_path(name); |
| 173 | |
| 174 | let started = Instant::now(); |
| 175 | let handle = session.export_to(&out); |
| 176 | wait(&handle, limit).expect("export"); |
| 177 | let spent = started.elapsed(); |
| 178 | println!( |
| 179 | "{name}: 120 frames in {:.2} s = {:.2} ms/frame", |
| 180 | spent.as_secs_f64(), |
| 181 | spent.as_secs_f64() * 1000.0 / 120.0 |
| 182 | ); |
| 183 | assert_eq!(handle.progress(), 1.0, "finished at full progress"); |
| 184 | |
| 185 | let (meta, _) = engine::demux::Demuxer::open(&out).expect("reopen export"); |
| 186 | assert_eq!(meta.frame_count, 120, "timeline frames written"); |
| 187 | assert_eq!((meta.width, meta.height), (1280, 720)); |
| 188 | assert_eq!(meta.frame_rate.round(), FPS); |
| 189 | |
| 190 | let file = File::open(&out).unwrap(); |
| 191 | let size = file.metadata().unwrap().len(); |
| 192 | let reader = mp4::Mp4Reader::read_header(BufReader::new(file), size).unwrap(); |
| 193 | let duration = reader.duration().as_secs_f64(); |
| 194 | assert!( |
| 195 | (duration - 120.0 / FPS).abs() <= 1.0 / FPS, |
| 196 | "duration {duration} s is more than a frame off 4.0 s" |
| 197 | ); |
| 198 | |
| 199 | let frames = decode_all(&out); |
| 200 | assert_eq!(frames.len(), 120, "every written frame decodes back"); |
| 201 | |
| 202 | |
| 203 | for (timeline, source_frame) in [(0u32, 0u32), (59, 89), (119, 149)] { |
| 204 | let diff = mean_abs_diff(&frames[timeline as usize], &frame_at(&source, source_frame)); |
| 205 | println!("timeline {timeline} vs source {source_frame}: mean abs diff {diff:.2}"); |
| 206 | assert!( |
| 207 | diff < 6.0, |
| 208 | "timeline frame {timeline} drifted by {diff:.2} from source frame {source_frame}" |
| 209 | ); |
| 210 | } |
| 211 | std::fs::remove_file(&out).unwrap(); |
| 212 | } |
| 213 | |
| 214 | #[test] |
| 215 | fn exports_an_edited_timeline_in_software() { |
| 216 | let _seat = pin_software(); |
| 217 | round_trip("sw", Duration::from_secs(600)); |
| 218 | } |
| 219 | |
| 220 | |
| 221 | |
| 222 | #[test] |
| 223 | #[ignore] |
| 224 | fn exports_an_edited_timeline_in_hardware() { |
| 225 | let _seat = pin_hardware(); |
| 226 | round_trip("hw", Duration::from_secs(60)); |
| 227 | } |
| 228 | |
| 229 | |
| 230 | |
| 231 | |
| 232 | |
| 233 | |
| 234 | |
| 235 | |
| 236 | #[test] |
| 237 | fn exports_at_the_project_resolution_with_the_watched_geometry() { |
| 238 | let _seat = pin_software(); |
| 239 | let clip = |source: usize, start: u32| engine::Clip { |
| 240 | fade_in: 0, |
| 241 | fade_out: 0, |
| 242 | transition_out: 0, |
| 243 | visualizer: 0, |
| 244 | viz_paint: 0, |
| 245 | start, |
| 246 | in_frame: 0, |
| 247 | out_frame: 10, |
| 248 | source, |
| 249 | link: Some(source as u32), |
| 250 | eq: None, |
| 251 | color: None, |
| 252 | transform: None, |
| 253 | fit: FitPolicy::default(), |
| 254 | speed: Speed::NORMAL, |
| 255 | }; |
| 256 | let clips = vec![clip(0, 0), clip(1, 10)]; |
| 257 | let project = Project::from_parts( |
| 258 | vec![ |
| 259 | Source::new(asset("test_baseline.mp4"), 0), |
| 260 | Source::new(asset("test_mismatch.mp4"), 0), |
| 261 | ], |
| 262 | vec![ |
| 263 | (engine::project::LaneKind::Video, clips.clone()), |
| 264 | (engine::project::LaneKind::Audio, clips), |
| 265 | ], |
| 266 | Vec::new(), |
| 267 | Vec::new(), |
| 268 | Vec::new(), |
| 269 | ) |
| 270 | .expect("a two-source project"); |
| 271 | |
| 272 | |
| 273 | let meta = engine::VideoMeta { |
| 274 | width: 960, |
| 275 | height: 720, |
| 276 | frame_rate: FPS, |
| 277 | frame_count: 20, |
| 278 | codec: engine::Codec::H264, |
| 279 | color: Default::default(), |
| 280 | rotation: Rotation::None, |
| 281 | |
| 282 | |
| 283 | coded_width: 960, |
| 284 | coded_height: 720, |
| 285 | pixel_aspect: engine::demux::PixelAspect::SQUARE, |
| 286 | }; |
| 287 | let out = out_path("mixed"); |
| 288 | let handle = engine::export::start(project, meta, &out, &ExportSettings::default(), None); |
| 289 | wait(&handle, Duration::from_secs(600)).expect("export"); |
| 290 | |
| 291 | let (written, _) = engine::demux::Demuxer::open(&out).expect("reopen export"); |
| 292 | assert_eq!( |
| 293 | (written.width, written.height), |
| 294 | (960, 720), |
| 295 | "an export is the project's size, not any source's" |
| 296 | ); |
| 297 | assert_eq!(written.frame_count, 20); |
| 298 | |
| 299 | let frames = decode_all(&out); |
| 300 | assert_eq!(frames.len(), 20); |
| 301 | |
| 302 | |
| 303 | |
| 304 | let mean = |frame: &[u8], y: usize| { |
| 305 | frame[y * 960 * 4..][..960 * 4] |
| 306 | .chunks_exact(4) |
| 307 | .flat_map(|px| [px[0], px[1], px[2]]) |
| 308 | .map(f64::from) |
| 309 | .sum::<f64>() |
| 310 | / (960.0 * 3.0) |
| 311 | }; |
| 312 | for (at, what) in [(5usize, "the 1280x720 clip"), (15, "the 640x360 clip")] { |
| 313 | let frame = &frames[at]; |
| 314 | assert!(mean(frame, 2) < 8.0, "{what}: top bar is not black"); |
| 315 | assert!(mean(frame, 717) < 8.0, "{what}: bottom bar is not black"); |
| 316 | assert!( |
| 317 | mean(frame, 360) > 20.0, |
| 318 | "{what}: the picture area is black, so nothing was composed" |
| 319 | ); |
| 320 | } |
| 321 | std::fs::remove_file(&out).unwrap(); |
| 322 | } |
| 323 | |
| 324 | |
| 325 | |
| 326 | |
| 327 | |
| 328 | |
| 329 | #[test] |
| 330 | fn exports_the_audio_stream_the_timeline_plays() { |
| 331 | let _seat = pin_software(); |
| 332 | let multi = asset("test_multiaudio.mp4"); |
| 333 | let (meta, _) = engine::demux::Demuxer::open(&multi).expect("open the fixture"); |
| 334 | let whole = engine::Clip { |
| 335 | fade_in: 0, |
| 336 | fade_out: 0, |
| 337 | transition_out: 0, |
| 338 | visualizer: 0, |
| 339 | viz_paint: 0, |
| 340 | start: 0, |
| 341 | in_frame: 0, |
| 342 | out_frame: meta.frame_count, |
| 343 | source: 0, |
| 344 | link: Some(0), |
| 345 | eq: None, |
| 346 | color: None, |
| 347 | transform: None, |
| 348 | fit: FitPolicy::default(), |
| 349 | speed: Speed::NORMAL, |
| 350 | }; |
| 351 | |
| 352 | |
| 353 | |
| 354 | let project = Project::from_parts( |
| 355 | vec![Source { |
| 356 | path: multi.clone(), |
| 357 | audio_stream: 1, |
| 358 | }], |
| 359 | vec![ |
| 360 | (engine::project::LaneKind::Video, vec![whole]), |
| 361 | (engine::project::LaneKind::Audio, vec![whole]), |
| 362 | ], |
| 363 | Vec::new(), |
| 364 | Vec::new(), |
| 365 | Vec::new(), |
| 366 | ) |
| 367 | .expect("a one-source project on stream 1"); |
| 368 | let out = out_path("stream1"); |
| 369 | let handle = engine::export::start(project, meta, &out, &ExportSettings::default(), None); |
| 370 | wait(&handle, Duration::from_secs(600)).expect("export"); |
| 371 | |
| 372 | let (audio, _) = engine::AudioSession::open(&out) |
| 373 | .expect("reopen export audio") |
| 374 | .expect("the export has audio"); |
| 375 | assert_eq!( |
| 376 | (audio.sample_rate, audio.channels), |
| 377 | (22_050, 1), |
| 378 | "the export carries stream 0's parameters, not the stream that played" |
| 379 | ); |
| 380 | |
| 381 | |
| 382 | |
| 383 | |
| 384 | let segs = [(Some(0), 0.0, f64::from(meta.frame_count) / FPS)]; |
| 385 | let copy = |stream| { |
| 386 | engine::AudioSession::copy_multi_streams(&[(multi.clone(), stream)], &segs) |
| 387 | .expect("copy") |
| 388 | .expect("has audio") |
| 389 | .1 |
| 390 | .into_iter() |
| 391 | .map(|p| p.bytes) |
| 392 | .collect::<Vec<_>>() |
| 393 | }; |
| 394 | let (one, zero) = (copy(1), copy(0)); |
| 395 | assert_ne!(one, zero, "the two streams are not the same bytes"); |
| 396 | |
| 397 | let file = File::open(&out).unwrap(); |
| 398 | let size = file.metadata().unwrap().len(); |
| 399 | let mut reader = mp4::Mp4Reader::read_header(BufReader::new(file), size).unwrap(); |
| 400 | let track = *reader |
| 401 | .tracks() |
| 402 | .keys() |
| 403 | .find(|id| reader.sample_count(**id).unwrap_or(0) as usize == one.len()) |
| 404 | .unwrap_or(&2); |
| 405 | let written: Vec<Vec<u8>> = (1..=reader.sample_count(track).expect("audio track")) |
| 406 | .map(|id| { |
| 407 | reader |
| 408 | .read_sample(track, id) |
| 409 | .expect("sample") |
| 410 | .expect("present") |
| 411 | .bytes |
| 412 | .to_vec() |
| 413 | }) |
| 414 | .collect(); |
| 415 | assert_eq!(written, one, "the exported packets are stream 1's"); |
| 416 | std::fs::remove_file(&out).unwrap(); |
| 417 | } |
| 418 | |
| 419 | |
| 420 | |
| 421 | |
| 422 | fn two_sources() -> Project { |
| 423 | let (av, _) = engine::demux::Demuxer::open(&asset("test_av.mp4")).expect("open test_av"); |
| 424 | let (av2, _) = engine::demux::Demuxer::open(&asset("test_av2.mp4")).expect("open test_av2"); |
| 425 | assert_eq!((av.width, av.height), (av2.width, av2.height), "policy a"); |
| 426 | |
| 427 | let mut project = Project::single(asset("test_av.mp4"), av.frame_count); |
| 428 | let second = project.import(asset("test_av2.mp4"), 0); |
| 429 | assert_eq!(second, 1, "a second file is a second source"); |
| 430 | assert!(project.append_clip(second, av2.frame_count)); |
| 431 | assert!(project.split(120), "cut a second before the end of test_av"); |
| 432 | assert!(project.delete(1), "drop test_av's tail"); |
| 433 | assert_eq!(project.timeline_frames(), 120 + av2.frame_count); |
| 434 | assert_eq!( |
| 435 | project.clips().iter().map(|c| c.source).collect::<Vec<_>>(), |
| 436 | vec![0, 1] |
| 437 | ); |
| 438 | project |
| 439 | } |
| 440 | |
| 441 | |
| 442 | |
| 443 | |
| 444 | fn multi_source_round_trip(name: &str, limit: Duration) { |
| 445 | let project = two_sources(); |
| 446 | let total = project.timeline_frames(); |
| 447 | let (meta, _) = engine::demux::Demuxer::open(&asset("test_av.mp4")).unwrap(); |
| 448 | let out = out_path(name); |
| 449 | |
| 450 | let started = Instant::now(); |
| 451 | let handle = engine::export::start( |
| 452 | project.clone(), |
| 453 | meta, |
| 454 | &out, |
| 455 | &ExportSettings::default(), |
| 456 | None, |
| 457 | ); |
| 458 | wait(&handle, limit).expect("export"); |
| 459 | println!( |
| 460 | "{name}: {total} frames of two sources in {:.2} s", |
| 461 | started.elapsed().as_secs_f64() |
| 462 | ); |
| 463 | |
| 464 | let (written, _) = engine::demux::Demuxer::open(&out).expect("reopen export"); |
| 465 | assert_eq!(written.frame_count, total, "timeline frames written"); |
| 466 | assert_eq!((written.width, written.height), (1280, 720)); |
| 467 | |
| 468 | let frames = decode_all(&out); |
| 469 | assert_eq!( |
| 470 | frames.len() as u32, |
| 471 | total, |
| 472 | "every written frame decodes back" |
| 473 | ); |
| 474 | |
| 475 | for (timeline, source, source_frame) in [ |
| 476 | (0u32, "test_av.mp4", 0u32), |
| 477 | (119, "test_av.mp4", 119), |
| 478 | (120, "test_av2.mp4", 0), |
| 479 | (total - 1, "test_av2.mp4", total - 121), |
| 480 | ] { |
| 481 | let diff = mean_abs_diff( |
| 482 | &frames[timeline as usize], |
| 483 | &frame_at(&asset(source), source_frame), |
| 484 | ); |
| 485 | println!("timeline {timeline} vs {source} {source_frame}: mean abs diff {diff:.2}"); |
| 486 | assert!( |
| 487 | diff < 6.0, |
| 488 | "timeline frame {timeline} drifted by {diff:.2} from {source} frame {source_frame}" |
| 489 | ); |
| 490 | } |
| 491 | |
| 492 | |
| 493 | |
| 494 | |
| 495 | |
| 496 | |
| 497 | |
| 498 | let file = File::open(&out).unwrap(); |
| 499 | let size = file.metadata().unwrap().len(); |
| 500 | let reader = mp4::Mp4Reader::read_header(BufReader::new(file), size).unwrap(); |
| 501 | let packets = reader.sample_count(2).expect("audio track"); |
| 502 | assert_eq!(packets, 346, "packet total across the source join"); |
| 503 | let wanted = f64::from(total) / FPS * 44_100.0; |
| 504 | assert!( |
| 505 | (f64::from(packets * 1024) - wanted).abs() < 3.0 * 1024.0, |
| 506 | "audio length {} samples drifted from {wanted}", |
| 507 | packets * 1024 |
| 508 | ); |
| 509 | let (audio, _) = engine::AudioSession::open(&out) |
| 510 | .expect("reopen export audio") |
| 511 | .expect("export has an audio track"); |
| 512 | assert_eq!((audio.sample_rate, audio.channels), (44_100, 2)); |
| 513 | std::fs::remove_file(&out).unwrap(); |
| 514 | } |
| 515 | |
| 516 | #[test] |
| 517 | fn exports_two_sources_as_one_timeline_in_software() { |
| 518 | let _seat = pin_software(); |
| 519 | multi_source_round_trip("multi_sw", Duration::from_secs(900)); |
| 520 | } |
| 521 | |
| 522 | #[test] |
| 523 | #[ignore] |
| 524 | fn exports_two_sources_as_one_timeline_in_hardware() { |
| 525 | let _seat = pin_hardware(); |
| 526 | multi_source_round_trip("multi_hw", Duration::from_secs(60)); |
| 527 | } |
| 528 | |
| 529 | |
| 530 | |
| 531 | |
| 532 | |
| 533 | #[test] |
| 534 | fn a_higher_bitrate_writes_a_bigger_file() { |
| 535 | let _seat = pin_software(); |
| 536 | let mut sizes = Vec::new(); |
| 537 | for bitrate in [1_000_000u64, 4_000_000, 8_000_000] { |
| 538 | let mut session = edited(&asset("test_baseline.mp4")); |
| 539 | session.pause(); |
| 540 | let out = out_path(&format!("bitrate_{bitrate}")); |
| 541 | let settings = ExportSettings { |
| 542 | bitrate: Some(bitrate), |
| 543 | seat: engine::export::EncoderSeat::Software, |
| 544 | ..Default::default() |
| 545 | }; |
| 546 | let handle = session.export_to_with(&out, &settings); |
| 547 | wait(&handle, Duration::from_secs(900)).expect("export"); |
| 548 | let size = std::fs::metadata(&out).expect("export exists").len(); |
| 549 | println!("{} Mbps: {size} bytes", bitrate / 1_000_000); |
| 550 | sizes.push(size); |
| 551 | std::fs::remove_file(&out).unwrap(); |
| 552 | } |
| 553 | assert!( |
| 554 | sizes[0] < sizes[1] && sizes[1] < sizes[2], |
| 555 | "file sizes {sizes:?} are not strictly growing with the bitrate" |
| 556 | ); |
| 557 | } |
| 558 | |
| 559 | |
| 560 | |
| 561 | |
| 562 | |
| 563 | #[test] |
| 564 | fn a_vanished_source_fails_the_export() { |
| 565 | let _seat = pin_software(); |
| 566 | let baseline = asset("test_baseline.mp4"); |
| 567 | let doomed = Scratch::file("ve_export_vanished_source", "mp4"); |
| 568 | std::fs::copy(&baseline, &doomed).expect("copy a second source"); |
| 569 | let (meta, _) = engine::demux::Demuxer::open(&baseline).unwrap(); |
| 570 | |
| 571 | |
| 572 | let mut project = Project::single(&baseline, meta.frame_count); |
| 573 | assert!(project.split(5)); |
| 574 | assert!(project.delete(1)); |
| 575 | let second = project.import(&doomed, 0); |
| 576 | assert!(project.append_clip(second, meta.frame_count)); |
| 577 | assert!(project.split(10)); |
| 578 | assert!(project.delete(2)); |
| 579 | assert_eq!(project.timeline_frames(), 10); |
| 580 | |
| 581 | std::fs::remove_file(&doomed).expect("unlink the second source"); |
| 582 | let out = out_path("vanished"); |
| 583 | let handle = engine::export::start(project, meta, &out, &ExportSettings::default(), None); |
| 584 | let result = wait(&handle, Duration::from_secs(60)); |
| 585 | let error = result.expect_err("an export of a missing file cannot succeed"); |
| 586 | println!("vanished source: {error}"); |
| 587 | assert!( |
| 588 | !out.exists(), |
| 589 | "a failed export still wrote {}", |
| 590 | out.display() |
| 591 | ); |
| 592 | assert!(!part_path(&out).exists(), "the .part outlived the failure"); |
| 593 | } |
| 594 | |
| 595 | |
| 596 | |
| 597 | #[test] |
| 598 | fn cancelling_leaves_no_file() { |
| 599 | let _seat = pin_software(); |
| 600 | let mut session = edited(&asset("test_baseline.mp4")); |
| 601 | session.pause(); |
| 602 | let out = out_path("cancel"); |
| 603 | |
| 604 | let handle = session.export_to(&out); |
| 605 | let started = Instant::now(); |
| 606 | while handle.progress() < 0.1 { |
| 607 | assert!( |
| 608 | started.elapsed() < Duration::from_secs(60), |
| 609 | "export never got going" |
| 610 | ); |
| 611 | assert!( |
| 612 | !handle.is_finished(), |
| 613 | "export finished before it was cancelled" |
| 614 | ); |
| 615 | std::thread::sleep(Duration::from_millis(10)); |
| 616 | } |
| 617 | handle.cancel(); |
| 618 | |
| 619 | |
| 620 | |
| 621 | |
| 622 | let result = wait(&handle, Duration::from_secs(60)); |
| 623 | assert!(result.is_err(), "a cancelled export is an error"); |
| 624 | assert!(!out.exists(), "no partial file survives a cancel"); |
| 625 | assert!(!part_path(&out).exists(), "the .part is cleaned up too"); |
| 626 | } |
| 627 | |
| 628 | |
| 629 | |
| 630 | |
| 631 | |
| 632 | |
| 633 | |
| 634 | |
| 635 | |
| 636 | #[test] |
| 637 | fn cancelling_after_the_last_frame_leaves_no_file() { |
| 638 | let _seat = pin_software(); |
| 639 | let out = out_path("late"); |
| 640 | let part = part_path(&out); |
| 641 | for attempt in 1..=5 { |
| 642 | let mut session = edited(&asset("test_baseline.mp4")); |
| 643 | session.pause(); |
| 644 | let handle = session.export_to(&out); |
| 645 | |
| 646 | |
| 647 | let started = Instant::now(); |
| 648 | while handle.progress() < 0.9 && !handle.is_finished() { |
| 649 | assert!( |
| 650 | started.elapsed() < Duration::from_secs(600), |
| 651 | "export stalled" |
| 652 | ); |
| 653 | std::thread::sleep(Duration::from_millis(20)); |
| 654 | } |
| 655 | while handle.progress() < 1.0 && !handle.is_finished() { |
| 656 | std::hint::spin_loop(); |
| 657 | } |
| 658 | handle.cancel(); |
| 659 | |
| 660 | let result = wait(&handle, Duration::from_secs(120)); |
| 661 | assert!(!part.exists(), "attempt {attempt} left a .part behind"); |
| 662 | if result.is_err() { |
| 663 | assert!(!out.exists(), "a late cancel still wrote {}", out.display()); |
| 664 | return; |
| 665 | } |
| 666 | |
| 667 | assert_eq!( |
| 668 | engine::demux::Demuxer::open(&out).unwrap().0.frame_count, |
| 669 | 120 |
| 670 | ); |
| 671 | std::fs::remove_file(&out).unwrap(); |
| 672 | } |
| 673 | panic!("cancel never landed in the drain/audio/finish window"); |
| 674 | } |
| 675 | |
| 676 | |
| 677 | |
| 678 | #[test] |
| 679 | #[ignore] |
| 680 | fn exports_audio_alongside_the_video() { |
| 681 | let _seat = pin_hardware(); |
| 682 | let source = asset("test_av.mp4"); |
| 683 | let mut session = PlaybackSession::open(&source).expect("open source"); |
| 684 | |
| 685 | |
| 686 | assert!(session.cut_at(2.0)); |
| 687 | session.pause(); |
| 688 | let timeline = session.timeline_duration(); |
| 689 | let out = out_path("av"); |
| 690 | |
| 691 | let handle = session.export_to(&out); |
| 692 | wait(&handle, Duration::from_secs(600)).expect("export"); |
| 693 | |
| 694 | let file = File::open(&out).unwrap(); |
| 695 | let size = file.metadata().unwrap().len(); |
| 696 | let reader = mp4::Mp4Reader::read_header(BufReader::new(file), size).unwrap(); |
| 697 | let packets = reader.sample_count(2).expect("audio track"); |
| 698 | let expected = engine::AudioSession::copy_segments(&source, &[(0.0, 2.0), (2.0, 5.0)]) |
| 699 | .unwrap() |
| 700 | .expect("source has audio") |
| 701 | .1 |
| 702 | .len() as u32; |
| 703 | assert_eq!(packets, expected, "every copied packet reached the file"); |
| 704 | |
| 705 | |
| 706 | let samples = f64::from(packets * 1024); |
| 707 | let wanted = timeline * 44_100.0; |
| 708 | println!("audio: {packets} packets = {samples} samples for {wanted} of timeline"); |
| 709 | assert!( |
| 710 | (samples - wanted).abs() < 3.0 * 1024.0, |
| 711 | "audio length {samples} drifted from {wanted}" |
| 712 | ); |
| 713 | |
| 714 | let (meta, chunks) = engine::AudioSession::open(&out) |
| 715 | .expect("reopen export audio") |
| 716 | .expect("export has an audio track"); |
| 717 | assert_eq!(meta.sample_rate, 44_100); |
| 718 | assert_eq!(meta.channels, 2); |
| 719 | let decoded: usize = chunks.into_iter().map(|c| c.samples.len()).sum(); |
| 720 | assert!( |
| 721 | decoded as f64 / 2.0 > wanted - 3.0 * 1024.0, |
| 722 | "only {decoded} samples decoded back out" |
| 723 | ); |
| 724 | |
| 725 | let (video, _) = engine::demux::Demuxer::open(&out).unwrap(); |
| 726 | assert_eq!(video.frame_count, 150, "video track unaffected by the cut"); |
| 727 | std::fs::remove_file(&out).unwrap(); |
| 728 | } |
| 729 | |
| 730 | |
| 731 | |
| 732 | |
| 733 | #[test] |
| 734 | #[ignore] |
| 735 | fn hardware_access_units_repack_into_mp4() { |
| 736 | let (w, h) = (640u32, 480u32); |
| 737 | let mut encoder = |
| 738 | HwEncoder::open(w, h, 30, 1, 4_000_000).expect("no hardware encode plugin/driver"); |
| 739 | let out = out_path("hwmux"); |
| 740 | let mut muxer: Option<Mp4Muxer> = None; |
| 741 | let mut written = 0; |
| 742 | for index in 0..10u32 { |
| 743 | let (y, u, v) = synthetic(index, w as usize, h as usize); |
| 744 | let Some(au) = encoder.encode(&y, &u, &v, w, h, false).expect("encode") else { |
| 745 | continue; |
| 746 | }; |
| 747 | if muxer.is_none() { |
| 748 | let (sps, pps) = parameter_sets(au).expect("first access unit carries SPS+PPS"); |
| 749 | muxer = Some( |
| 750 | Mp4Muxer::create( |
| 751 | &out, |
| 752 | &VideoParams { |
| 753 | width: w, |
| 754 | height: h, |
| 755 | frame_rate: 30.0, |
| 756 | sps, |
| 757 | pps, |
| 758 | }, |
| 759 | None, |
| 760 | ) |
| 761 | .expect("create"), |
| 762 | ); |
| 763 | } |
| 764 | muxer.as_mut().unwrap().write_video_au(au).expect("write"); |
| 765 | written += 1; |
| 766 | } |
| 767 | while let Some(au) = encoder.drain().expect("drain") { |
| 768 | muxer.as_mut().unwrap().write_video_au(au).expect("write"); |
| 769 | written += 1; |
| 770 | } |
| 771 | muxer.unwrap().finish().expect("finish"); |
| 772 | assert_eq!(written, 10); |
| 773 | |
| 774 | let (meta, mut demuxer) = engine::demux::Demuxer::open(&out).unwrap(); |
| 775 | assert_eq!(meta.frame_count, 10); |
| 776 | let mut decoder = H264Decoder::new(CodecParameters::new(CodecId::H264)) |
| 777 | .expect("ec-h264 takes its own codec id"); |
| 778 | let mut decoded = 0; |
| 779 | while let Some(au) = demuxer.next_access_unit().unwrap() { |
| 780 | decoder |
| 781 | .send_packet(&Packet::new(0, TimeBase::new(1, 1), au)) |
| 782 | .expect("software decode of the remuxed stream"); |
| 783 | while let Ok(frame) = decoder.receive_frame() { |
| 784 | let ec_core::frame::Frame::Video(_) = frame else { |
| 785 | continue; |
| 786 | }; |
| 787 | decoded += 1; |
| 788 | } |
| 789 | } |
| 790 | decoder.flush().expect("flush of the remuxed stream"); |
| 791 | while let Ok(frame) = decoder.receive_frame() { |
| 792 | let ec_core::frame::Frame::Video(_) = frame else { |
| 793 | continue; |
| 794 | }; |
| 795 | decoded += 1; |
| 796 | } |
| 797 | assert_eq!(decoded, 10, "every remuxed picture decodes again"); |
| 798 | std::fs::remove_file(&out).unwrap(); |
| 799 | } |
| 800 | |
| 801 | |
| 802 | |
| 803 | fn synthetic(index: u32, width: usize, height: usize) -> (Vec<u8>, Vec<u8>, Vec<u8>) { |
| 804 | let (cw, ch) = (width.div_ceil(2), height.div_ceil(2)); |
| 805 | let mut y = vec![0u8; width * height]; |
| 806 | for row in 0..height { |
| 807 | for col in 0..width { |
| 808 | y[row * width + col] = (row + col + index as usize * 5) as u8; |
| 809 | } |
| 810 | } |
| 811 | ( |
| 812 | y, |
| 813 | vec![64u8.wrapping_add(index as u8); cw * ch], |
| 814 | vec![192u8.wrapping_sub(index as u8); cw * ch], |
| 815 | ) |
| 816 | } |
| 817 | |
| 818 | |
| 819 | |
| 820 | |
| 821 | fn fake_au(n: u8) -> Vec<u8> { |
| 822 | vec![0, 0, 1, 0x65, n, n.wrapping_add(1), 0xA5] |
| 823 | } |
| 824 | |
| 825 | |
| 826 | |
| 827 | |
| 828 | |
| 829 | |
| 830 | |
| 831 | |
| 832 | |
| 833 | |
| 834 | |
| 835 | |
| 836 | #[test] |
| 837 | fn mp4_interleaves_a_mix_that_lands_early_under_the_rest_of_the_picture() { |
| 838 | let out = out_path("interleave"); |
| 839 | let (width, height, fps) = (64u32, 64u32, 30.0); |
| 840 | let (sps, pps) = ([0x67, 0x42, 0x00, 0x1E], [0x68, 0xCE, 0x3C, 0x80]); |
| 841 | let mut muxer = Mp4Muxer::create( |
| 842 | &out, |
| 843 | &VideoParams { |
| 844 | width, |
| 845 | height, |
| 846 | frame_rate: fps, |
| 847 | sps: &sps, |
| 848 | pps: &pps, |
| 849 | }, |
| 850 | None, |
| 851 | ) |
| 852 | .expect("create"); |
| 853 | |
| 854 | |
| 855 | |
| 856 | |
| 857 | for i in 0..15u8 { |
| 858 | muxer.write_video_au(&fake_au(i)).expect("write video"); |
| 859 | } |
| 860 | muxer |
| 861 | .add_audio_track(&AudioParams { |
| 862 | freq_index: 3, |
| 863 | chan_conf: 2, |
| 864 | sample_rate: 48_000, |
| 865 | opus_pre_skip: None, |
| 866 | }) |
| 867 | .expect("declare audio"); |
| 868 | |
| 869 | |
| 870 | |
| 871 | |
| 872 | let silence = [0x21, 0x10, 0x04, 0x60, 0x8c, 0x1c]; |
| 873 | for _ in 0..200u32 { |
| 874 | muxer.write_audio_packet(&silence).expect("write audio"); |
| 875 | } |
| 876 | |
| 877 | |
| 878 | for i in 15..150u8 { |
| 879 | muxer.write_video_au(&fake_au(i)).expect("write video"); |
| 880 | } |
| 881 | muxer.write_subtitles(&[]).expect("no subtitles"); |
| 882 | muxer.finish().expect("finish"); |
| 883 | |
| 884 | assert_no_single_stream_span_over(&out, 2.0); |
| 885 | std::fs::remove_file(&out).unwrap(); |
| 886 | } |
| 887 | |
| 888 | |
| 889 | |
| 890 | |
| 891 | |
| 892 | fn assert_no_single_stream_span_over(path: &Path, seconds: f64) { |
| 893 | let output = std::process::Command::new("ffprobe") |
| 894 | .args([ |
| 895 | "-v", |
| 896 | "error", |
| 897 | "-show_entries", |
| 898 | "packet=stream_index,pts_time,pos", |
| 899 | "-of", |
| 900 | "csv=p=0", |
| 901 | ]) |
| 902 | .arg(path) |
| 903 | .output() |
| 904 | .expect("run ffprobe"); |
| 905 | assert!( |
| 906 | output.status.success(), |
| 907 | "ffprobe failed: {}", |
| 908 | String::from_utf8_lossy(&output.stderr) |
| 909 | ); |
| 910 | let text = String::from_utf8_lossy(&output.stdout); |
| 911 | let mut packets: Vec<(i64, u32, f64)> = text |
| 912 | .lines() |
| 913 | .filter(|line| !line.is_empty()) |
| 914 | .map(|line| { |
| 915 | let mut fields = line.split(','); |
| 916 | let stream: u32 = fields.next().unwrap().parse().unwrap(); |
| 917 | let pts: f64 = fields.next().unwrap().parse().unwrap(); |
| 918 | let pos: i64 = fields.next().unwrap().parse().unwrap(); |
| 919 | (pos, stream, pts) |
| 920 | }) |
| 921 | .collect(); |
| 922 | assert!( |
| 923 | packets.len() > 10, |
| 924 | "ffprobe saw only {} packets", |
| 925 | packets.len() |
| 926 | ); |
| 927 | packets.sort_by_key(|&(pos, ..)| pos); |
| 928 | |
| 929 | let streams: std::collections::HashSet<u32> = packets.iter().map(|&(_, s, _)| s).collect(); |
| 930 | assert_eq!( |
| 931 | streams.len(), |
| 932 | 2, |
| 933 | "expected one video and one audio stream, ffprobe saw {streams:?}" |
| 934 | ); |
| 935 | |
| 936 | let (mut run_stream, mut run_start) = (packets[0].1, packets[0].2); |
| 937 | for &(_, stream, pts) in &packets[1..] { |
| 938 | if stream != run_stream { |
| 939 | run_stream = stream; |
| 940 | run_start = pts; |
| 941 | continue; |
| 942 | } |
| 943 | let span = pts - run_start; |
| 944 | assert!( |
| 945 | span <= seconds, |
| 946 | "a run of stream {run_stream} packets alone spans {span:.2} s (from {run_start:.2} s) -- over the {seconds} s bound" |
| 947 | ); |
| 948 | } |
| 949 | } |
| 950 | |
| 951 | |
| 952 | |
| 953 | |
| 954 | |
| 955 | fn first_pts(path: &Path, select: &str) -> f64 { |
| 956 | let output = std::process::Command::new("ffprobe") |
| 957 | .args([ |
| 958 | "-v", |
| 959 | "error", |
| 960 | "-select_streams", |
| 961 | select, |
| 962 | "-show_entries", |
| 963 | "packet=pts_time", |
| 964 | "-of", |
| 965 | "csv=p=0", |
| 966 | ]) |
| 967 | .arg(path) |
| 968 | .output() |
| 969 | .expect("run ffprobe"); |
| 970 | assert!( |
| 971 | output.status.success(), |
| 972 | "ffprobe failed: {}", |
| 973 | String::from_utf8_lossy(&output.stderr) |
| 974 | ); |
| 975 | String::from_utf8_lossy(&output.stdout) |
| 976 | .lines() |
| 977 | .find(|line| !line.is_empty()) |
| 978 | .expect("stream has at least one packet") |
| 979 | .parse() |
| 980 | .expect("pts_time") |
| 981 | } |
| 982 | |
| 983 | |
| 984 | |
| 985 | |
| 986 | |
| 987 | |
| 988 | |
| 989 | |
| 990 | #[test] |
| 991 | fn mp4_audio_interleaves_with_the_picture() { |
| 992 | let _seat = pin_software(); |
| 993 | let source = asset("test_av.mp4"); |
| 994 | let mut session = PlaybackSession::open(&source).expect("open source"); |
| 995 | |
| 996 | |
| 997 | |
| 998 | |
| 999 | assert!(session.cut_at(2.0)); |
| 1000 | session.pause(); |
| 1001 | let timeline = session.timeline_duration(); |
| 1002 | let out = out_path("interleave-e2e"); |
| 1003 | |
| 1004 | let handle = session.export_to(&out); |
| 1005 | wait(&handle, Duration::from_secs(600)).expect("export"); |
| 1006 | |
| 1007 | |
| 1008 | |
| 1009 | |
| 1010 | assert_eq!( |
| 1011 | first_pts(&out, "a"), |
| 1012 | 0.0, |
| 1013 | "first audio pts is media time zero" |
| 1014 | ); |
| 1015 | |
| 1016 | assert_no_single_stream_span_over(&out, 2.0); |
| 1017 | |
| 1018 | |
| 1019 | |
| 1020 | let (video_meta, _) = engine::demux::Demuxer::open(&out).unwrap(); |
| 1021 | assert_eq!( |
| 1022 | video_meta.frame_count, 150, |
| 1023 | "video track unaffected by interleaving" |
| 1024 | ); |
| 1025 | let (audio_meta, chunks) = engine::AudioSession::open(&out) |
| 1026 | .unwrap() |
| 1027 | .expect("export has an audio track"); |
| 1028 | assert_eq!((audio_meta.sample_rate, audio_meta.channels), (44_100, 2)); |
| 1029 | let decoded: usize = chunks.into_iter().map(|c| c.samples.len()).sum(); |
| 1030 | let wanted = timeline * f64::from(audio_meta.sample_rate); |
| 1031 | assert!( |
| 1032 | (decoded as f64 / f64::from(audio_meta.channels) - wanted).abs() < 3.0 * 1024.0, |
| 1033 | "audio length {decoded} drifted from {wanted} samples of timeline" |
| 1034 | ); |
| 1035 | |
| 1036 | std::fs::remove_file(&out).unwrap(); |
| 1037 | } |
| 1038 | |
| 1039 | |
| 1040 | |
| 1041 | |
| 1042 | |
| 1043 | |
| 1044 | #[test] |
| 1045 | fn a_leading_audio_gap_keeps_the_sound_after_it_in_place() { |
| 1046 | let _seat = pin_software(); |
| 1047 | let source = asset("test_av.mp4"); |
| 1048 | let mut session = PlaybackSession::open(&source).expect("open source"); |
| 1049 | assert!(session.cut_at(1.0), "cut at 1 s"); |
| 1050 | assert!(session.lift_clip(Lane::A1, 0), "lift the first second"); |
| 1051 | session.pause(); |
| 1052 | let out = out_path("leading_gap"); |
| 1053 | let handle = session.export_to(&out); |
| 1054 | wait(&handle, Duration::from_secs(900)).expect("export"); |
| 1055 | |
| 1056 | let (_, chunks) = engine::AudioSession::open(&out) |
| 1057 | .expect("reopen export audio") |
| 1058 | .expect("export has an audio track"); |
| 1059 | let mut pcm: Vec<f32> = Vec::new(); |
| 1060 | while let Ok(chunk) = chunks.recv_timeout(Duration::from_secs(10)) { |
| 1061 | pcm.resize(chunk.start_sample as usize * 2, 0.0); |
| 1062 | pcm.extend_from_slice(&chunk.samples); |
| 1063 | } |
| 1064 | |
| 1065 | |
| 1066 | |
| 1067 | let block = 1024 * 2; |
| 1068 | let peak = |b: &[f32]| b.iter().fold(0.0f32, |m, s| m.max(s.abs())); |
| 1069 | let loud = peak(&pcm) / 4.0; |
| 1070 | let onset = pcm |
| 1071 | .chunks(block) |
| 1072 | .position(|b| peak(b) > loud) |
| 1073 | .expect("the export has no sound at all") as f64 |
| 1074 | * 1024.0; |
| 1075 | println!("leading gap: sound starts at sample {onset} of an expected 44100"); |
| 1076 | assert!( |
| 1077 | (onset - 44_100.0).abs() <= 1024.0, |
| 1078 | "the sound after the gap is at {onset}, not at the 1 s hole's end" |
| 1079 | ); |
| 1080 | |
| 1081 | let quiet = peak(&pcm[..(0.9 * 44_100.0) as usize * 2]); |
| 1082 | assert!(quiet < 1e-3, "the lifted second is not silent: {quiet}"); |
| 1083 | |
| 1084 | std::fs::remove_file(&out).unwrap(); |
| 1085 | } |
| 1086 | |
| 1087 | |
| 1088 | |
| 1089 | |
| 1090 | |
| 1091 | |
| 1092 | #[test] |
| 1093 | fn exports_a_gapped_timeline_as_black_and_silence() { |
| 1094 | let _seat = pin_software(); |
| 1095 | let source = asset("test_av.mp4"); |
| 1096 | let mut session = PlaybackSession::open(&source).expect("open source"); |
| 1097 | assert!(session.cut_at(1.0), "split at 1 s"); |
| 1098 | assert!(session.cut_at(2.0), "split at 2 s"); |
| 1099 | |
| 1100 | |
| 1101 | assert!(session.lift_clip(Lane::V1, 1)); |
| 1102 | assert!(session.lift_clip(Lane::A1, 1)); |
| 1103 | session.pause(); |
| 1104 | let timeline = session.timeline_duration(); |
| 1105 | let frames = (timeline * FPS).round() as u32; |
| 1106 | let out = out_path("gapped"); |
| 1107 | |
| 1108 | let handle = session.export_to(&out); |
| 1109 | wait(&handle, Duration::from_secs(900)).expect("export"); |
| 1110 | |
| 1111 | |
| 1112 | let (video, _) = engine::demux::Demuxer::open(&out).unwrap(); |
| 1113 | assert_eq!( |
| 1114 | video.frame_count, frames, |
| 1115 | "a gap is encoded, not skipped: {} frames for a {timeline:.3}s timeline", |
| 1116 | video.frame_count |
| 1117 | ); |
| 1118 | let pictures = decode_all(&out); |
| 1119 | assert_eq!(pictures.len() as u32, frames); |
| 1120 | let (hole, hole_end) = ((1.0 * FPS) as usize, (2.0 * FPS) as usize); |
| 1121 | |
| 1122 | |
| 1123 | let black = [0u8, 0, 0, 255].repeat(pictures[0].len() / 4); |
| 1124 | for (i, picture) in pictures.iter().enumerate() { |
| 1125 | let diff = mean_abs_diff(picture, &black); |
| 1126 | if (hole..hole_end).contains(&i) { |
| 1127 | assert!( |
| 1128 | diff < 4.0, |
| 1129 | "frame {i} of the gap is not black (MAE {diff:.2})" |
| 1130 | ); |
| 1131 | } |
| 1132 | } |
| 1133 | let lit = mean_abs_diff(&pictures[0], &black); |
| 1134 | assert!(lit > 4.0, "the clips around the gap came out black too"); |
| 1135 | |
| 1136 | |
| 1137 | |
| 1138 | |
| 1139 | let file = File::open(&out).unwrap(); |
| 1140 | let size = file.metadata().unwrap().len(); |
| 1141 | let reader = mp4::Mp4Reader::read_header(BufReader::new(file), size).unwrap(); |
| 1142 | let count = reader.sample_count(2).expect("audio track"); |
| 1143 | let samples = f64::from(count * 1024); |
| 1144 | let wanted = timeline * 44_100.0; |
| 1145 | println!("gapped export: {count} packets = {samples} samples for {wanted}"); |
| 1146 | assert!( |
| 1147 | (samples - wanted).abs() < 3.0 * 1024.0, |
| 1148 | "audio length {samples} drifted from {wanted} across the gap" |
| 1149 | ); |
| 1150 | |
| 1151 | |
| 1152 | let (_, chunks) = engine::AudioSession::open(&out) |
| 1153 | .expect("reopen export audio") |
| 1154 | .expect("export has an audio track"); |
| 1155 | let mut pcm: Vec<f32> = Vec::new(); |
| 1156 | while let Ok(chunk) = chunks.recv_timeout(Duration::from_secs(10)) { |
| 1157 | pcm.resize(chunk.start_sample as usize * 2, 0.0); |
| 1158 | pcm.extend_from_slice(&chunk.samples); |
| 1159 | } |
| 1160 | let window = |from: f64, to: f64| { |
| 1161 | let (a, b) = ((from * 44_100.0) as usize * 2, (to * 44_100.0) as usize * 2); |
| 1162 | pcm[a.min(pcm.len())..b.min(pcm.len())] |
| 1163 | .iter() |
| 1164 | .fold(0.0f32, |m, s| m.max(s.abs())) |
| 1165 | }; |
| 1166 | |
| 1167 | |
| 1168 | let quiet = window(1.2, 1.8); |
| 1169 | assert!(quiet < 1e-3, "the gap is not silent: {quiet}"); |
| 1170 | assert!(window(0.1, 0.9) > 1e-2, "the sound before it went missing"); |
| 1171 | assert!(window(2.2, 4.9) > 1e-2, "the sound after it went missing"); |
| 1172 | |
| 1173 | std::fs::remove_file(&out).unwrap(); |
| 1174 | } |
| 1175 | |
| 1176 | |
| 1177 | |
| 1178 | |
| 1179 | |
| 1180 | |
| 1181 | |
| 1182 | #[test] |
| 1183 | fn a_proxy_is_picture_only_every_frame_a_starting_point_and_cached() { |
| 1184 | let _film = PROXY_FILM.lock().unwrap_or_else(|e| e.into_inner()); |
| 1185 | let _seat = pin_software(); |
| 1186 | let source = asset("test_av.mp4"); |
| 1187 | let out = engine::proxy::path_for(&source).expect("a cache directory"); |
| 1188 | |
| 1189 | |
| 1190 | |
| 1191 | let _ = std::fs::remove_file(&out); |
| 1192 | |
| 1193 | let job = engine::proxy::generate(&source).expect("start the proxy"); |
| 1194 | assert_eq!(job.path(), out, "the job writes where the key says"); |
| 1195 | let started = Instant::now(); |
| 1196 | while !job.is_finished() { |
| 1197 | assert!( |
| 1198 | started.elapsed() < Duration::from_secs(900), |
| 1199 | "the proxy did not finish: {:.0}% in", |
| 1200 | job.progress() * 100.0 |
| 1201 | ); |
| 1202 | std::thread::sleep(Duration::from_millis(20)); |
| 1203 | } |
| 1204 | let made = job |
| 1205 | .outcome() |
| 1206 | .expect("a finished job has an outcome") |
| 1207 | .expect("the proxy"); |
| 1208 | assert_eq!(made, out); |
| 1209 | assert_eq!(job.progress(), 1.0, "finished at full progress"); |
| 1210 | |
| 1211 | let (source_meta, _) = engine::demux::Demuxer::open(&source).expect("open the fixture"); |
| 1212 | let (meta, _) = engine::demux::Demuxer::open(&made).expect("open the proxy"); |
| 1213 | assert_eq!( |
| 1214 | (meta.width, meta.height), |
| 1215 | engine::proxy::size_for(&source_meta), |
| 1216 | "the proxy is coded at the size the rule picked" |
| 1217 | ); |
| 1218 | assert_eq!(meta.codec, engine::Codec::H264, "proxies are H.264"); |
| 1219 | assert_eq!( |
| 1220 | meta.frame_count, source_meta.frame_count, |
| 1221 | "a stand-in as long as the film, or every cut lands elsewhere" |
| 1222 | ); |
| 1223 | |
| 1224 | |
| 1225 | |
| 1226 | let syncs = engine::demux::sync_points(&made); |
| 1227 | assert_eq!( |
| 1228 | syncs.len() as u32, |
| 1229 | meta.frame_count, |
| 1230 | "{} of {} frames are starting points -- the proxy is not intra-only", |
| 1231 | syncs.len(), |
| 1232 | meta.frame_count |
| 1233 | ); |
| 1234 | |
| 1235 | |
| 1236 | assert!( |
| 1237 | engine::AudioSession::open(&made) |
| 1238 | .expect("probe the proxy for sound") |
| 1239 | .is_none(), |
| 1240 | "a proxy carries no audio track" |
| 1241 | ); |
| 1242 | |
| 1243 | |
| 1244 | let session = PlaybackSession::open(&made).expect("play the proxy"); |
| 1245 | assert_eq!(session.meta().frame_count, source_meta.frame_count); |
| 1246 | |
| 1247 | |
| 1248 | |
| 1249 | |
| 1250 | let mut session = PlaybackSession::open(&source).expect("open the film"); |
| 1251 | |
| 1252 | |
| 1253 | |
| 1254 | let film = session.sources()[0].path.clone(); |
| 1255 | assert_eq!(session.picture_path(0), film, "off: the film itself"); |
| 1256 | session.set_proxies(true); |
| 1257 | assert!(session.proxies()); |
| 1258 | assert_eq!(session.picture_path(0), made, "on: the stand-in"); |
| 1259 | assert_eq!( |
| 1260 | session.sources()[0].path, |
| 1261 | film, |
| 1262 | "the project still names the film, and that is what an export reads" |
| 1263 | ); |
| 1264 | |
| 1265 | |
| 1266 | let started = Instant::now(); |
| 1267 | while session.try_frame().is_none() { |
| 1268 | assert!( |
| 1269 | started.elapsed() < Duration::from_secs(60), |
| 1270 | "no picture after switching to the stand-in" |
| 1271 | ); |
| 1272 | std::thread::sleep(Duration::from_millis(10)); |
| 1273 | } |
| 1274 | session.set_proxies(false); |
| 1275 | assert_eq!(session.picture_path(0), film, "and back again"); |
| 1276 | |
| 1277 | |
| 1278 | |
| 1279 | let project = Scratch::file("ve_proxy_switch", "edith"); |
| 1280 | session.set_proxies(true); |
| 1281 | session.save_project(&project).expect("save"); |
| 1282 | let text = std::fs::read_to_string(&project).expect("read the project back"); |
| 1283 | assert!(text.starts_with("edith 23\n"), "{text}"); |
| 1284 | assert!(text.contains("\nproxy on\n"), "{text}"); |
| 1285 | let reopened = PlaybackSession::open_project(&project).expect("load"); |
| 1286 | assert!(reopened.proxies(), "the switch came back on"); |
| 1287 | assert_eq!(reopened.picture_path(0), made, "and it is substituting"); |
| 1288 | |
| 1289 | |
| 1290 | let again = engine::proxy::generate(&source).expect("ask again"); |
| 1291 | assert!(again.is_finished(), "a cached proxy is done on the spot"); |
| 1292 | assert_eq!( |
| 1293 | again |
| 1294 | .outcome() |
| 1295 | .expect("cached outcome") |
| 1296 | .expect("cached path"), |
| 1297 | out |
| 1298 | ); |
| 1299 | assert_eq!(engine::proxy::cached(&source), Some(out.clone())); |
| 1300 | |
| 1301 | std::fs::remove_file(&out).expect("clean the cache entry up"); |
| 1302 | assert_eq!(engine::proxy::cached(&source), None); |
| 1303 | } |
| 1304 | |
| 1305 | |
| 1306 | |
| 1307 | |
| 1308 | |
| 1309 | |
| 1310 | |
| 1311 | |
| 1312 | |
| 1313 | |
| 1314 | |
| 1315 | |
| 1316 | |
| 1317 | |
| 1318 | |
| 1319 | |
| 1320 | |
| 1321 | #[test] |
| 1322 | fn a_stopped_proxy_leaves_neither_a_stand_in_nor_half_of_one() { |
| 1323 | let _film = PROXY_FILM.lock().unwrap_or_else(|e| e.into_inner()); |
| 1324 | let _seat = pin_software(); |
| 1325 | let source = asset("test_av.mp4"); |
| 1326 | let out = engine::proxy::path_for(&source).expect("a cache directory"); |
| 1327 | let part = part_path(&out); |
| 1328 | |
| 1329 | |
| 1330 | let _ = std::fs::remove_file(&out); |
| 1331 | let _ = std::fs::remove_file(&part); |
| 1332 | |
| 1333 | let job = engine::proxy::generate(&source).expect("start the proxy"); |
| 1334 | |
| 1335 | |
| 1336 | |
| 1337 | |
| 1338 | let opening = Instant::now(); |
| 1339 | while job.encoder().is_none() && !job.is_finished() { |
| 1340 | assert!( |
| 1341 | opening.elapsed() < Duration::from_secs(600), |
| 1342 | "the encoder never opened" |
| 1343 | ); |
| 1344 | std::thread::sleep(Duration::from_millis(10)); |
| 1345 | } |
| 1346 | assert!( |
| 1347 | !job.is_finished(), |
| 1348 | "the fixture finished before it could be stopped: this test needs a film \ |
| 1349 | the software seat takes a moment over" |
| 1350 | ); |
| 1351 | |
| 1352 | job.cancel(); |
| 1353 | job.cancel(); |
| 1354 | let stopping = Instant::now(); |
| 1355 | while !job.is_finished() { |
| 1356 | assert!( |
| 1357 | stopping.elapsed() < Duration::from_secs(120), |
| 1358 | "the worker kept encoding after the stop: {:.0}% in", |
| 1359 | job.progress() * 100. |
| 1360 | ); |
| 1361 | std::thread::sleep(Duration::from_millis(20)); |
| 1362 | } |
| 1363 | let refusal = job |
| 1364 | .outcome() |
| 1365 | .expect("a settled job has an outcome") |
| 1366 | .err() |
| 1367 | .expect("a stopped proxy is not a proxy"); |
| 1368 | assert!( |
| 1369 | refusal.to_string().contains("cancelled"), |
| 1370 | "not the cancellation: {refusal}" |
| 1371 | ); |
| 1372 | assert!( |
| 1373 | !out.exists(), |
| 1374 | "a stopped proxy left {} behind, and the cache is looked up by existence", |
| 1375 | out.display() |
| 1376 | ); |
| 1377 | assert!( |
| 1378 | !part.exists(), |
| 1379 | "a stopped proxy left the half-written {} behind", |
| 1380 | part.display() |
| 1381 | ); |
| 1382 | assert_eq!( |
| 1383 | engine::proxy::cached(&source), |
| 1384 | None, |
| 1385 | "the cache offers a stand-in that was never finished" |
| 1386 | ); |
| 1387 | |
| 1388 | job.cancel(); |
| 1389 | assert!(job.outcome().is_none(), "the outcome came out twice"); |
| 1390 | assert!(!out.exists()); |
| 1391 | |
| 1392 | |
| 1393 | |
| 1394 | |
| 1395 | |
| 1396 | std::fs::write(&out, b"a stand-in that is already written").expect("seed the cache"); |
| 1397 | let hit = engine::proxy::generate(&source).expect("ask again"); |
| 1398 | assert!(hit.is_finished(), "a cached stand-in is done on the spot"); |
| 1399 | hit.cancel(); |
| 1400 | assert!( |
| 1401 | out.is_file(), |
| 1402 | "a stop deleted a finished stand-in the switch was playing" |
| 1403 | ); |
| 1404 | assert_eq!(engine::proxy::cached(&source), Some(out.clone())); |
| 1405 | assert_eq!( |
| 1406 | hit.outcome().expect("cached outcome").expect("cached path"), |
| 1407 | out, |
| 1408 | "the stop turned a finished stand-in into a failure" |
| 1409 | ); |
| 1410 | |
| 1411 | std::fs::remove_file(&out).expect("clean the cache entry up"); |
| 1412 | } |
| 1413 | |
| 1414 | |
| 1415 | |
| 1416 | |
| 1417 | |
| 1418 | |
| 1419 | |
| 1420 | |
| 1421 | |
| 1422 | |
| 1423 | |
| 1424 | |
| 1425 | |
| 1426 | |
| 1427 | |
| 1428 | #[test] |
| 1429 | #[ignore = "needs the VA-API plugin"] |
| 1430 | fn a_hardware_proxy_is_every_frame_a_starting_point_too() { |
| 1431 | let _seat = pin_hardware(); |
| 1432 | let source = asset("test_av.mp4"); |
| 1433 | let out = engine::proxy::path_for(&source).expect("a cache directory"); |
| 1434 | let _ = std::fs::remove_file(&out); |
| 1435 | let job = engine::proxy::generate(&source).expect("start the proxy"); |
| 1436 | let started = Instant::now(); |
| 1437 | while !job.is_finished() { |
| 1438 | assert!( |
| 1439 | started.elapsed() < Duration::from_secs(900), |
| 1440 | "the proxy did not finish" |
| 1441 | ); |
| 1442 | std::thread::sleep(Duration::from_millis(20)); |
| 1443 | } |
| 1444 | let made = job |
| 1445 | .outcome() |
| 1446 | .expect("a finished job has an outcome") |
| 1447 | .expect("the proxy"); |
| 1448 | let seat = job.encoder().unwrap_or_default(); |
| 1449 | println!("hardware proxy seat: {seat}"); |
| 1450 | |
| 1451 | |
| 1452 | assert!( |
| 1453 | seat.contains("HW encode"), |
| 1454 | "not the hardware seat ({seat}): LD_LIBRARY_PATH must name the plugin" |
| 1455 | ); |
| 1456 | let (meta, _) = engine::demux::Demuxer::open(&made).expect("open the proxy"); |
| 1457 | let syncs = engine::demux::sync_points(&made); |
| 1458 | println!( |
| 1459 | "{} of {} frames are starting points", |
| 1460 | syncs.len(), |
| 1461 | meta.frame_count |
| 1462 | ); |
| 1463 | assert_eq!( |
| 1464 | syncs.len() as u32, |
| 1465 | meta.frame_count, |
| 1466 | "the hardware seat wrote {} starting points in {} frames", |
| 1467 | syncs.len(), |
| 1468 | meta.frame_count |
| 1469 | ); |
| 1470 | |
| 1471 | |
| 1472 | |
| 1473 | |
| 1474 | |
| 1475 | let frames = decode_all(&made); |
| 1476 | println!( |
| 1477 | "decoded back {} of {} pictures", |
| 1478 | frames.len(), |
| 1479 | meta.frame_count |
| 1480 | ); |
| 1481 | assert_eq!( |
| 1482 | frames.len() as u32, |
| 1483 | meta.frame_count, |
| 1484 | "the proxy demuxes but does not decode" |
| 1485 | ); |
| 1486 | assert!( |
| 1487 | frames.iter().all(|f| f.iter().any(|&b| b != 0)), |
| 1488 | "a decoded picture came back empty" |
| 1489 | ); |
| 1490 | match ffmpeg_complaints(&made) { |
| 1491 | Some(said) => assert!(said.is_empty(), "ffmpeg read the proxy and said:\n{said}"), |
| 1492 | None => eprintln!("no ffmpeg: skipping the outside decoder's word on the proxy"), |
| 1493 | } |
| 1494 | std::fs::remove_file(&out).expect("clean the cache entry up"); |
| 1495 | } |
| 1496 | |
| 1497 | |
| 1498 | |
| 1499 | |
| 1500 | |
| 1501 | |
| 1502 | |
| 1503 | |
| 1504 | |
| 1505 | |
| 1506 | |
| 1507 | |
| 1508 | |
| 1509 | #[test] |
| 1510 | #[ignore = "needs the VA-API plugin and a real library"] |
| 1511 | fn a_proxy_of_real_4k_film_is_made_faster_than_it_plays() { |
| 1512 | let _seat = pin_hardware(); |
| 1513 | let Some(film) = engine::real_library::film("hevc_4k_hdr") else { |
| 1514 | return; |
| 1515 | }; |
| 1516 | let out = engine::proxy::path_for(&film).expect("a cache directory"); |
| 1517 | let _ = std::fs::remove_file(&out); |
| 1518 | let (meta, _) = engine::demux::Demuxer::open(&film).expect("open the film"); |
| 1519 | let duration = f64::from(meta.frame_count) / meta.frame_rate; |
| 1520 | println!( |
| 1521 | "film: {}x{} {:.3} fps, {duration:.0}s", |
| 1522 | meta.width, meta.height, meta.frame_rate |
| 1523 | ); |
| 1524 | |
| 1525 | let job = engine::proxy::generate(&film).expect("start the proxy"); |
| 1526 | let window = Duration::from_secs(60); |
| 1527 | let started = Instant::now(); |
| 1528 | while started.elapsed() < window && !job.is_finished() { |
| 1529 | std::thread::sleep(Duration::from_millis(200)); |
| 1530 | } |
| 1531 | let elapsed = started.elapsed().as_secs_f64(); |
| 1532 | let made = f64::from(job.progress()) * duration; |
| 1533 | let seat = job.encoder().unwrap_or_default(); |
| 1534 | println!( |
| 1535 | "proxy: {made:.0}s of film in {elapsed:.0}s = {:.2}x realtime, seat {seat}", |
| 1536 | made / elapsed |
| 1537 | ); |
| 1538 | |
| 1539 | |
| 1540 | assert!( |
| 1541 | seat.contains("HW encode"), |
| 1542 | "not the hardware seat ({seat}): LD_LIBRARY_PATH must name the plugin" |
| 1543 | ); |
| 1544 | |
| 1545 | |
| 1546 | |
| 1547 | |
| 1548 | |
| 1549 | |
| 1550 | assert!( |
| 1551 | made / elapsed >= 2.0, |
| 1552 | "{:.2}x realtime is under the 2x floor this shipped at", |
| 1553 | made / elapsed |
| 1554 | ); |
| 1555 | |
| 1556 | |
| 1557 | |
| 1558 | job.cancel(); |
| 1559 | let stopped = Instant::now(); |
| 1560 | while !job.is_finished() { |
| 1561 | assert!( |
| 1562 | stopped.elapsed() < Duration::from_secs(120), |
| 1563 | "the proxy did not stop when cancelled" |
| 1564 | ); |
| 1565 | std::thread::sleep(Duration::from_millis(50)); |
| 1566 | } |
| 1567 | assert!(job.outcome().expect("an outcome").is_err(), "cancelled"); |
| 1568 | assert!( |
| 1569 | !out.exists(), |
| 1570 | "a cancelled proxy left {} behind", |
| 1571 | out.display() |
| 1572 | ); |
| 1573 | assert!( |
| 1574 | !part_path(&out).exists(), |
| 1575 | "a cancelled proxy left its .part" |
| 1576 | ); |
| 1577 | assert_eq!(engine::proxy::cached(&film), None); |
| 1578 | } |
| 1579 | |
| 1580 | |
| 1581 | |
| 1582 | |
| 1583 | |
| 1584 | |
| 1585 | |
| 1586 | |
| 1587 | |
| 1588 | |
| 1589 | |
| 1590 | |
| 1591 | |
| 1592 | |
| 1593 | |
| 1594 | |
| 1595 | |
| 1596 | |
| 1597 | |
| 1598 | |
| 1599 | |
| 1600 | |
| 1601 | |
| 1602 | |
| 1603 | |
| 1604 | |
| 1605 | |
| 1606 | fn injected<T>(abort: Option<&str>, hang: Option<&str>, body: impl FnOnce() -> T) -> T { |
| 1607 | |
| 1608 | |
| 1609 | injected_with(abort, hang, Some("1500"), body) |
| 1610 | } |
| 1611 | |
| 1612 | |
| 1613 | |
| 1614 | |
| 1615 | fn injected_with<T>( |
| 1616 | abort: Option<&str>, |
| 1617 | hang: Option<&str>, |
| 1618 | timeout_ms: Option<&str>, |
| 1619 | body: impl FnOnce() -> T, |
| 1620 | ) -> T { |
| 1621 | let _exclusive = SEAT |
| 1622 | .write() |
| 1623 | .unwrap_or_else(|poisoned| poisoned.into_inner()); |
| 1624 | let restore = std::env::var_os("VE_SW_ENC"); |
| 1625 | unsafe { |
| 1626 | std::env::set_var("VE_SW", "1"); |
| 1627 | std::env::remove_var("VE_SW_ENC"); |
| 1628 | std::env::set_var("VE_HW_TEST_FAKE", "1"); |
| 1629 | std::env::set_var("VE_HW_CHILD_BIN", env!("CARGO_BIN_EXE_hw-encode-child")); |
| 1630 | match timeout_ms { |
| 1631 | Some(ms) => std::env::set_var("VE_HW_TIMEOUT_MS", ms), |
| 1632 | None => std::env::remove_var("VE_HW_TIMEOUT_MS"), |
| 1633 | } |
| 1634 | match abort { |
| 1635 | Some(at) => std::env::set_var("VE_HW_TEST_ABORT", at), |
| 1636 | None => std::env::remove_var("VE_HW_TEST_ABORT"), |
| 1637 | } |
| 1638 | match hang { |
| 1639 | Some(at) => std::env::set_var("VE_HW_TEST_HANG", at), |
| 1640 | None => std::env::remove_var("VE_HW_TEST_HANG"), |
| 1641 | } |
| 1642 | } |
| 1643 | let out = std::panic::catch_unwind(std::panic::AssertUnwindSafe(body)); |
| 1644 | unsafe { |
| 1645 | for var in [ |
| 1646 | "VE_HW_TEST_FAKE", |
| 1647 | "VE_HW_CHILD_BIN", |
| 1648 | "VE_HW_TIMEOUT_MS", |
| 1649 | "VE_HW_TEST_ABORT", |
| 1650 | "VE_HW_TEST_HANG", |
| 1651 | ] { |
| 1652 | std::env::remove_var(var); |
| 1653 | } |
| 1654 | |
| 1655 | |
| 1656 | |
| 1657 | if let Some(pinned) = restore { |
| 1658 | std::env::set_var("VE_SW_ENC", pinned); |
| 1659 | } |
| 1660 | } |
| 1661 | match out { |
| 1662 | Ok(value) => value, |
| 1663 | Err(panic) => std::panic::resume_unwind(panic), |
| 1664 | } |
| 1665 | } |
| 1666 | |
| 1667 | |
| 1668 | |
| 1669 | fn short_edit(source: &Path, frames: u32) -> (Project, engine::VideoMeta) { |
| 1670 | let (meta, _) = engine::demux::Demuxer::open(source).expect("open source"); |
| 1671 | let mut project = Project::single(source, meta.frame_count); |
| 1672 | assert!(project.split(frames)); |
| 1673 | assert!(project.delete(1)); |
| 1674 | assert_eq!(project.timeline_frames(), frames); |
| 1675 | (project, meta) |
| 1676 | } |
| 1677 | |
| 1678 | |
| 1679 | |
| 1680 | |
| 1681 | |
| 1682 | |
| 1683 | |
| 1684 | |
| 1685 | #[test] |
| 1686 | fn a_hardware_encoder_killed_mid_export_costs_the_file_nothing() { |
| 1687 | let source = asset("test_baseline.mp4"); |
| 1688 | let (project, meta) = short_edit(&source, 20); |
| 1689 | let out = out_path("hw_child_abort"); |
| 1690 | |
| 1691 | injected(Some("3"), None, || { |
| 1692 | |
| 1693 | |
| 1694 | let handle = engine::export::start(project, meta, &out, &ExportSettings::default(), None); |
| 1695 | wait(&handle, Duration::from_secs(180)).expect("the export survived its encoder"); |
| 1696 | }); |
| 1697 | |
| 1698 | let (written, _) = engine::demux::Demuxer::open(&out).expect("the export is a file"); |
| 1699 | assert_eq!(written.frame_count, 20, "every timeline frame was written"); |
| 1700 | assert_eq!(decode_all(&out).len(), 20, "and every one of them decodes"); |
| 1701 | if let Some(said) = ffmpeg_complaints(&out) { |
| 1702 | assert!( |
| 1703 | said.is_empty(), |
| 1704 | "ffmpeg read the fallback's file badly: {said}" |
| 1705 | ); |
| 1706 | } |
| 1707 | assert!(!part_path(&out).exists(), "the .part outlived the export"); |
| 1708 | std::fs::remove_file(&out).unwrap(); |
| 1709 | } |
| 1710 | |
| 1711 | |
| 1712 | |
| 1713 | |
| 1714 | |
| 1715 | #[test] |
| 1716 | fn a_hardware_encoder_killed_mid_export_never_pulls_the_bar_backwards() { |
| 1717 | let source = asset("test_baseline.mp4"); |
| 1718 | let (project, meta) = short_edit(&source, 20); |
| 1719 | let out = out_path("hw_child_abort_progress"); |
| 1720 | |
| 1721 | let seen = injected(Some("3"), None, || { |
| 1722 | let handle = engine::export::start(project, meta, &out, &ExportSettings::default(), None); |
| 1723 | |
| 1724 | |
| 1725 | let started = Instant::now(); |
| 1726 | let mut seen = vec![handle.progress()]; |
| 1727 | while !handle.is_finished() { |
| 1728 | assert!( |
| 1729 | started.elapsed() < Duration::from_secs(180), |
| 1730 | "export did not finish" |
| 1731 | ); |
| 1732 | let now = handle.progress(); |
| 1733 | if now != *seen.last().unwrap() { |
| 1734 | seen.push(now); |
| 1735 | } |
| 1736 | std::thread::sleep(Duration::from_millis(1)); |
| 1737 | } |
| 1738 | handle |
| 1739 | .result() |
| 1740 | .expect("a finished export has an outcome") |
| 1741 | .expect("the export survived its encoder"); |
| 1742 | seen.push(handle.progress()); |
| 1743 | seen |
| 1744 | }); |
| 1745 | |
| 1746 | assert!( |
| 1747 | seen.windows(2).all(|pair| pair[1] >= pair[0]), |
| 1748 | "the bar went backwards across the fallback: {seen:?}" |
| 1749 | ); |
| 1750 | assert_eq!( |
| 1751 | seen.last().copied(), |
| 1752 | Some(1.0), |
| 1753 | "a finished export leaves a full bar: {seen:?}" |
| 1754 | ); |
| 1755 | std::fs::remove_file(&out).unwrap(); |
| 1756 | } |
| 1757 | |
| 1758 | |
| 1759 | |
| 1760 | |
| 1761 | |
| 1762 | |
| 1763 | fn audio_pass_threads() -> usize { |
| 1764 | std::fs::read_dir("/proc/self/task") |
| 1765 | .into_iter() |
| 1766 | .flatten() |
| 1767 | .flatten() |
| 1768 | .filter(|thread| { |
| 1769 | std::fs::read_to_string(thread.path().join("comm")) |
| 1770 | .is_ok_and(|name| name.trim() == "export-audio") |
| 1771 | }) |
| 1772 | .count() |
| 1773 | } |
| 1774 | |
| 1775 | |
| 1776 | fn busiest_audio_pass(project: Project, meta: engine::VideoMeta, out: &Path) -> usize { |
| 1777 | let handle = engine::export::start(project, meta, out, &ExportSettings::default(), None); |
| 1778 | let started = Instant::now(); |
| 1779 | let mut most = 0; |
| 1780 | while !handle.is_finished() { |
| 1781 | assert!( |
| 1782 | started.elapsed() < Duration::from_secs(180), |
| 1783 | "export did not finish" |
| 1784 | ); |
| 1785 | most = most.max(audio_pass_threads()); |
| 1786 | std::thread::sleep(Duration::from_millis(1)); |
| 1787 | } |
| 1788 | handle |
| 1789 | .result() |
| 1790 | .expect("a finished export has an outcome") |
| 1791 | .expect("the export was written"); |
| 1792 | most |
| 1793 | } |
| 1794 | |
| 1795 | |
| 1796 | |
| 1797 | |
| 1798 | |
| 1799 | |
| 1800 | |
| 1801 | #[test] |
| 1802 | fn a_hardware_encoder_killed_mid_export_leaves_no_audio_pass_behind() { |
| 1803 | |
| 1804 | |
| 1805 | let source = asset("test_ac3.mp4"); |
| 1806 | let out = out_path("hw_child_abort_audio"); |
| 1807 | |
| 1808 | let (project, meta) = short_edit(&source, 40); |
| 1809 | let alone = { |
| 1810 | let _seat = pin_software(); |
| 1811 | busiest_audio_pass(project, meta, &out) |
| 1812 | }; |
| 1813 | std::fs::remove_file(&out).unwrap(); |
| 1814 | |
| 1815 | let (project, meta) = short_edit(&source, 40); |
| 1816 | let across = injected(Some("3"), None, || busiest_audio_pass(project, meta, &out)); |
| 1817 | |
| 1818 | println!("audio pass threads: {alone} alone, {across} across the fallback"); |
| 1819 | assert!( |
| 1820 | across <= alone, |
| 1821 | "the fallback ran {across} audio-pass threads where one pass runs {alone}" |
| 1822 | ); |
| 1823 | let (written, _) = engine::demux::Demuxer::open(&out).expect("the export is a file"); |
| 1824 | assert_eq!(written.frame_count, 40, "every timeline frame was written"); |
| 1825 | std::fs::remove_file(&out).unwrap(); |
| 1826 | } |
| 1827 | |
| 1828 | |
| 1829 | |
| 1830 | |
| 1831 | |
| 1832 | |
| 1833 | |
| 1834 | |
| 1835 | |
| 1836 | |
| 1837 | #[test] |
| 1838 | fn a_wedged_child_is_waited_out_by_its_own_measure_not_the_ceiling() { |
| 1839 | let (width, height) = (320u32, 240u32); |
| 1840 | |
| 1841 | injected_with(None, Some("10"), None, || { |
| 1842 | let mut encoder = |
| 1843 | HwEncoder::open(width, height, 30, 1, 1_000_000).expect("the stand-in seat opened"); |
| 1844 | let (y, u, v) = synthetic(0, width as usize, height as usize); |
| 1845 | for frame in 0..10 { |
| 1846 | assert!( |
| 1847 | encoder.encode(&y, &u, &v, width, height, false).is_ok(), |
| 1848 | "picture {frame} is before the wedge" |
| 1849 | ); |
| 1850 | } |
| 1851 | let started = Instant::now(); |
| 1852 | let wedged = encoder |
| 1853 | .encode(&y, &u, &v, width, height, false) |
| 1854 | .expect_err("a child that stops answering is not an encode"); |
| 1855 | let waited = started.elapsed(); |
| 1856 | println!("wedge at the shipping default: contained in {waited:.2?}"); |
| 1857 | assert!(engine::hwproc::is_lost(&wedged), "{wedged}"); |
| 1858 | assert!( |
| 1859 | waited < Duration::from_secs(6), |
| 1860 | "waited {waited:.2?} on a wedged child at the shipping default" |
| 1861 | ); |
| 1862 | |
| 1863 | |
| 1864 | |
| 1865 | assert!(waited >= Duration::from_secs(2), "waited only {waited:.2?}"); |
| 1866 | }); |
| 1867 | } |
| 1868 | |
| 1869 | |
| 1870 | |
| 1871 | |
| 1872 | #[test] |
| 1873 | fn a_hardware_encoder_killed_at_its_open_is_simply_no_seat() { |
| 1874 | let source = asset("test_baseline.mp4"); |
| 1875 | let (project, meta) = short_edit(&source, 12); |
| 1876 | let out = out_path("hw_child_abort_init"); |
| 1877 | |
| 1878 | injected(Some("init"), None, || { |
| 1879 | let handle = engine::export::start(project, meta, &out, &ExportSettings::default(), None); |
| 1880 | wait(&handle, Duration::from_secs(180)).expect("the export survived the open"); |
| 1881 | }); |
| 1882 | |
| 1883 | let (written, _) = engine::demux::Demuxer::open(&out).expect("the export is a file"); |
| 1884 | assert_eq!(written.frame_count, 12); |
| 1885 | std::fs::remove_file(&out).unwrap(); |
| 1886 | } |
| 1887 | |
| 1888 | |
| 1889 | |
| 1890 | #[test] |
| 1891 | fn a_hardware_encoder_killed_at_the_drain_costs_the_file_nothing() { |
| 1892 | let source = asset("test_baseline.mp4"); |
| 1893 | let (project, meta) = short_edit(&source, 12); |
| 1894 | let out = out_path("hw_child_abort_drain"); |
| 1895 | |
| 1896 | injected(Some("drain"), None, || { |
| 1897 | let handle = engine::export::start(project, meta, &out, &ExportSettings::default(), None); |
| 1898 | wait(&handle, Duration::from_secs(180)).expect("the export survived the drain"); |
| 1899 | }); |
| 1900 | |
| 1901 | let (written, _) = engine::demux::Demuxer::open(&out).expect("the export is a file"); |
| 1902 | assert_eq!(written.frame_count, 12); |
| 1903 | assert_eq!(decode_all(&out).len(), 12); |
| 1904 | std::fs::remove_file(&out).unwrap(); |
| 1905 | } |
| 1906 | |
| 1907 | |
| 1908 | |
| 1909 | |
| 1910 | |
| 1911 | |
| 1912 | #[test] |
| 1913 | fn a_hardware_encoder_that_stops_answering_is_killed_and_replaced() { |
| 1914 | let source = asset("test_baseline.mp4"); |
| 1915 | let (project, meta) = short_edit(&source, 12); |
| 1916 | let out = out_path("hw_child_hang"); |
| 1917 | |
| 1918 | let started = Instant::now(); |
| 1919 | injected(None, Some("2"), || { |
| 1920 | let handle = engine::export::start(project, meta, &out, &ExportSettings::default(), None); |
| 1921 | wait(&handle, Duration::from_secs(180)).expect("the export outlived the wedge"); |
| 1922 | }); |
| 1923 | println!( |
| 1924 | "hung child: contained in {:.2} s", |
| 1925 | started.elapsed().as_secs_f64() |
| 1926 | ); |
| 1927 | |
| 1928 | let (written, _) = engine::demux::Demuxer::open(&out).expect("the export is a file"); |
| 1929 | assert_eq!(written.frame_count, 12); |
| 1930 | assert_eq!(decode_all(&out).len(), 12); |
| 1931 | std::fs::remove_file(&out).unwrap(); |
| 1932 | } |
| 1933 | |
| 1934 | |
| 1935 | |
| 1936 | |
| 1937 | |
| 1938 | |
| 1939 | |
| 1940 | |
| 1941 | |
| 1942 | |
| 1943 | #[test] |
| 1944 | fn an_export_that_asked_for_the_gpu_by_name_refuses_instead_of_falling_back() { |
| 1945 | let source = asset("test_baseline.mp4"); |
| 1946 | let (project, meta) = short_edit(&source, 12); |
| 1947 | let out = out_path("hw_child_named_seat"); |
| 1948 | |
| 1949 | let error = injected(Some("2"), None, || { |
| 1950 | let settings = ExportSettings { |
| 1951 | seat: engine::export::EncoderSeat::Hardware, |
| 1952 | ..Default::default() |
| 1953 | }; |
| 1954 | let handle = engine::export::start(project, meta, &out, &settings, None); |
| 1955 | wait(&handle, Duration::from_secs(180)) |
| 1956 | .expect_err("a named hardware seat that died is not written again in software") |
| 1957 | }); |
| 1958 | |
| 1959 | println!("named hardware seat: {error}"); |
| 1960 | assert!( |
| 1961 | engine::hwproc::is_lost(&error), |
| 1962 | "the refusal has to name the hardware failure: {error}" |
| 1963 | ); |
| 1964 | assert!( |
| 1965 | !out.exists(), |
| 1966 | "a refused export still wrote {}", |
| 1967 | out.display() |
| 1968 | ); |
| 1969 | assert!(!part_path(&out).exists(), "the .part outlived the refusal"); |
| 1970 | } |
| 1971 | |
| 1972 | |
| 1973 | |
| 1974 | |
| 1975 | |
| 1976 | |
| 1977 | #[test] |
| 1978 | fn a_dead_encoder_answers_every_later_call_the_same_way() { |
| 1979 | let (width, height) = (320u32, 240u32); |
| 1980 | injected(Some("1"), None, || { |
| 1981 | let mut encoder = |
| 1982 | HwEncoder::open(width, height, 30, 1, 1_000_000).expect("the stand-in seat opened"); |
| 1983 | let (y, u, v) = synthetic(0, width as usize, height as usize); |
| 1984 | assert!( |
| 1985 | encoder.encode(&y, &u, &v, width, height, false).is_ok(), |
| 1986 | "the first picture is before the injection point" |
| 1987 | ); |
| 1988 | let died = encoder |
| 1989 | .encode(&y, &u, &v, width, height, false) |
| 1990 | .expect_err("the second picture kills the child"); |
| 1991 | assert!( |
| 1992 | engine::hwproc::is_lost(&died), |
| 1993 | "an encoder death must say so: {died}" |
| 1994 | ); |
| 1995 | |
| 1996 | |
| 1997 | let again = Instant::now(); |
| 1998 | let repeat = encoder.drain().expect_err("the seat stays dead"); |
| 1999 | assert!(engine::hwproc::is_lost(&repeat), "{repeat}"); |
| 2000 | assert!( |
| 2001 | again.elapsed() < Duration::from_millis(500), |
| 2002 | "a dead seat answered only after waiting" |
| 2003 | ); |
| 2004 | }); |
| 2005 | } |
| 2006 | |
| 2007 | |
| 2008 | |
| 2009 | |
| 2010 | fn one_source_clip(source: &Path, fade_in: u32, out_frame: u32) -> (Project, engine::VideoMeta) { |
| 2011 | let (meta, _) = engine::demux::Demuxer::open(source).expect("open the fixture"); |
| 2012 | let whole = engine::Clip { |
| 2013 | fade_in, |
| 2014 | fade_out: 0, |
| 2015 | transition_out: 0, |
| 2016 | visualizer: 0, |
| 2017 | viz_paint: 0, |
| 2018 | start: 0, |
| 2019 | in_frame: 0, |
| 2020 | out_frame, |
| 2021 | source: 0, |
| 2022 | link: Some(0), |
| 2023 | eq: None, |
| 2024 | color: None, |
| 2025 | transform: None, |
| 2026 | fit: FitPolicy::default(), |
| 2027 | speed: Speed::NORMAL, |
| 2028 | }; |
| 2029 | let project = Project::from_parts( |
| 2030 | vec![Source { |
| 2031 | path: source.to_path_buf(), |
| 2032 | audio_stream: 0, |
| 2033 | }], |
| 2034 | vec![ |
| 2035 | (engine::project::LaneKind::Video, vec![whole.clone()]), |
| 2036 | (engine::project::LaneKind::Audio, vec![whole]), |
| 2037 | ], |
| 2038 | Vec::new(), |
| 2039 | Vec::new(), |
| 2040 | Vec::new(), |
| 2041 | ) |
| 2042 | .expect("a one-source project"); |
| 2043 | (project, meta) |
| 2044 | } |
| 2045 | |
| 2046 | |
| 2047 | fn rms(samples: &[f32]) -> f64 { |
| 2048 | let sum: f64 = samples |
| 2049 | .chunks_exact(2) |
| 2050 | .map(|c| f64::from(c[0]) * f64::from(c[0]) + f64::from(c[1]) * f64::from(c[1])) |
| 2051 | .sum(); |
| 2052 | (sum / samples.len().max(1) as f64).sqrt() |
| 2053 | } |
| 2054 | |
| 2055 | |
| 2056 | |
| 2057 | |
| 2058 | |
| 2059 | #[test] |
| 2060 | fn a_faded_clip_encodes_and_the_fade_reaches_the_file() { |
| 2061 | let _seat = pin_software(); |
| 2062 | let source = asset("test_multiaudio.mp4"); |
| 2063 | let (project, meta) = |
| 2064 | one_source_clip(&source, (FPS * 3.0 / 2.0) as u32, meta_frame_count(&source)); |
| 2065 | let out = out_path("faded"); |
| 2066 | let handle = engine::export::start(project, meta, &out, &ExportSettings::default(), None); |
| 2067 | wait(&handle, Duration::from_secs(600)).expect("export"); |
| 2068 | |
| 2069 | let line = handle.encoders().expect("the seats were published"); |
| 2070 | assert!( |
| 2071 | line.contains("ec-aac"), |
| 2072 | "the sound left through the copy, not the encode: {line}" |
| 2073 | ); |
| 2074 | |
| 2075 | let (audio, rx) = engine::AudioSession::open(&out) |
| 2076 | .expect("reopen export audio") |
| 2077 | .expect("the export has audio"); |
| 2078 | |
| 2079 | |
| 2080 | |
| 2081 | |
| 2082 | let quarter = audio.sample_rate as usize * 2 / 4; |
| 2083 | let mut samples = Vec::new(); |
| 2084 | for chunk in rx { |
| 2085 | samples.extend_from_slice(&chunk.samples); |
| 2086 | } |
| 2087 | let envelope: Vec<f64> = samples.chunks_exact(quarter).take(6).map(rms).collect(); |
| 2088 | let flat = rms(&samples[samples.len() - quarter..]); |
| 2089 | assert!( |
| 2090 | flat > 0.05, |
| 2091 | "the fixture's own tone is not in the file at all: tail rms {flat}" |
| 2092 | ); |
| 2093 | assert!( |
| 2094 | envelope[0] < 0.4 * flat, |
| 2095 | "the fade-in is absent -- a copy writes the source flat: {envelope:?} against {flat}" |
| 2096 | ); |
| 2097 | assert!( |
| 2098 | envelope[0] > 0.02 * flat, |
| 2099 | "the head is silence, so what is missing is the sound, not the fade: {envelope:?}" |
| 2100 | ); |
| 2101 | assert!( |
| 2102 | envelope[..4].windows(2).all(|w| w[1] > w[0]), |
| 2103 | "the level does not ramp through the fade's own 1.5 s: {envelope:?}" |
| 2104 | ); |
| 2105 | assert!( |
| 2106 | (envelope[4] - flat).abs() < 0.15 * flat && (envelope[5] - flat).abs() < 0.15 * flat, |
| 2107 | "the ramp never reaches unity past the fade, so this is not it: {envelope:?} against {flat}" |
| 2108 | ); |
| 2109 | std::fs::remove_file(&out).unwrap(); |
| 2110 | } |
| 2111 | |
| 2112 | fn meta_frame_count(source: &Path) -> u32 { |
| 2113 | engine::demux::Demuxer::open(source) |
| 2114 | .expect("open the fixture") |
| 2115 | .0 |
| 2116 | .frame_count |
| 2117 | } |
| 2118 | |
| 2119 | |
| 2120 | |
| 2121 | |
| 2122 | #[test] |
| 2123 | fn a_clip_that_outlives_its_source_says_so_on_the_card() { |
| 2124 | let _seat = pin_software(); |
| 2125 | let source = asset("test_multiaudio.mp4"); |
| 2126 | let count = meta_frame_count(&source); |
| 2127 | let (project, meta) = one_source_clip(&source, 0, count + 40); |
| 2128 | let out = out_path("truncated"); |
| 2129 | let handle = engine::export::start(project, meta, &out, &ExportSettings::default(), None); |
| 2130 | wait(&handle, Duration::from_secs(600)).expect("export"); |
| 2131 | let line = handle.encoders().expect("the seats were published"); |
| 2132 | assert!( |
| 2133 | line.contains("40 frames of the edit past the last picture"), |
| 2134 | "the truncation is silent: {line}" |
| 2135 | ); |
| 2136 | std::fs::remove_file(&out).unwrap(); |
| 2137 | } |
| 2138 | |
| 2139 | |
| 2140 | |
| 2141 | |
| 2142 | |
| 2143 | fn two_clip_edit(source: &Path, first: u32, second: u32) -> (Project, engine::VideoMeta) { |
| 2144 | let (meta, _) = engine::demux::Demuxer::open(source).expect("open the fixture"); |
| 2145 | let clip = |start: u32, out_frame: u32| engine::Clip { |
| 2146 | fade_in: 0, |
| 2147 | fade_out: 0, |
| 2148 | transition_out: 0, |
| 2149 | visualizer: 0, |
| 2150 | viz_paint: 0, |
| 2151 | start, |
| 2152 | in_frame: 0, |
| 2153 | out_frame, |
| 2154 | source: 0, |
| 2155 | link: None, |
| 2156 | eq: None, |
| 2157 | color: None, |
| 2158 | transform: None, |
| 2159 | fit: FitPolicy::default(), |
| 2160 | speed: Speed::NORMAL, |
| 2161 | }; |
| 2162 | let clips = vec![clip(0, first), clip(first, second)]; |
| 2163 | let project = Project::from_parts( |
| 2164 | vec![Source { |
| 2165 | path: source.to_path_buf(), |
| 2166 | audio_stream: 0, |
| 2167 | }], |
| 2168 | vec![ |
| 2169 | (engine::project::LaneKind::Video, clips.clone()), |
| 2170 | (engine::project::LaneKind::Audio, clips), |
| 2171 | ], |
| 2172 | Vec::new(), |
| 2173 | Vec::new(), |
| 2174 | Vec::new(), |
| 2175 | ) |
| 2176 | .expect("a two-clip project"); |
| 2177 | (project, meta) |
| 2178 | } |
| 2179 | |
| 2180 | |
| 2181 | |
| 2182 | |
| 2183 | |
| 2184 | #[test] |
| 2185 | fn a_two_clip_timeline_reports_only_the_pictures_that_were_skipped() { |
| 2186 | let _seat = pin_software(); |
| 2187 | let source = asset("test_multiaudio.mp4"); |
| 2188 | let count = meta_frame_count(&source); |
| 2189 | |
| 2190 | |
| 2191 | let (project, meta) = two_clip_edit(&source, count + 40, count); |
| 2192 | let out = out_path("truncated_two_clip"); |
| 2193 | let handle = engine::export::start(project, meta, &out, &ExportSettings::default(), None); |
| 2194 | wait(&handle, Duration::from_secs(900)).expect("export"); |
| 2195 | let line = handle.encoders().expect("the seats were published"); |
| 2196 | assert!( |
| 2197 | line.contains("40 frames of the edit past the last picture"), |
| 2198 | "the notice counts more than the file lost: {line}" |
| 2199 | ); |
| 2200 | |
| 2201 | |
| 2202 | |
| 2203 | assert_eq!( |
| 2204 | decode_all(&out).len(), |
| 2205 | (count * 2) as usize, |
| 2206 | "the span after the break was not written" |
| 2207 | ); |
| 2208 | std::fs::remove_file(&out).unwrap(); |
| 2209 | } |
| 2210 | |
| 2211 | |
| 2212 | |
| 2213 | #[test] |
| 2214 | fn a_healthy_two_clip_timeline_carries_no_truncation_notice() { |
| 2215 | let _seat = pin_software(); |
| 2216 | let source = asset("test_multiaudio.mp4"); |
| 2217 | let count = meta_frame_count(&source); |
| 2218 | let (project, meta) = two_clip_edit(&source, count, count); |
| 2219 | let out = out_path("truncated_control"); |
| 2220 | let handle = engine::export::start(project, meta, &out, &ExportSettings::default(), None); |
| 2221 | wait(&handle, Duration::from_secs(900)).expect("export"); |
| 2222 | let line = handle.encoders().expect("the seats were published"); |
| 2223 | let notice = line.contains("past the last picture"); |
| 2224 | assert_eq!( |
| 2225 | notice, false, |
| 2226 | "a whole export says it was truncated: {line}" |
| 2227 | ); |
| 2228 | assert_eq!( |
| 2229 | decode_all(&out).len(), |
| 2230 | (count * 2) as usize, |
| 2231 | "both spans were written" |
| 2232 | ); |
| 2233 | std::fs::remove_file(&out).unwrap(); |
| 2234 | } |
| 2235 | |
| 2236 | |
| 2237 | |
| 2238 | |
| 2239 | |
| 2240 | #[test] |
| 2241 | fn a_panicking_worker_deletes_the_part_file() { |
| 2242 | let _exclusive = SEAT.write().unwrap_or_else(|p| p.into_inner()); |
| 2243 | let source = asset("test_baseline.mp4"); |
| 2244 | let (project, meta) = short_edit(&source, 20); |
| 2245 | let out = out_path("panic"); |
| 2246 | let part = part_path(&out); |
| 2247 | unsafe { |
| 2248 | std::env::set_var("VE_EXPORT_TEST_PANIC", part.as_os_str().to_owned()); |
| 2249 | } |
| 2250 | let handle = engine::export::start(project, meta, &out, &ExportSettings::default(), None); |
| 2251 | let result = wait(&handle, Duration::from_secs(120)); |
| 2252 | unsafe { |
| 2253 | std::env::remove_var("VE_EXPORT_TEST_PANIC"); |
| 2254 | } |
| 2255 | let error = result.expect_err("the injected panic is the outcome"); |
| 2256 | assert!( |
| 2257 | error.to_string().contains("export worker panicked"), |
| 2258 | "the panic is the outcome: {error}" |
| 2259 | ); |
| 2260 | assert!(!out.exists(), "a panicked export wrote {}", out.display()); |
| 2261 | assert!(!part.exists(), "the .part outlived the panic"); |
| 2262 | } |