| 1 | |
| 2 | |
| 3 | |
| 4 | |
| 5 | |
| 6 | |
| 7 | |
| 8 | |
| 9 | |
| 10 | |
| 11 | |
| 12 | |
| 13 | |
| 14 | |
| 15 | |
| 16 | use std::fs::File; |
| 17 | use std::io::BufReader; |
| 18 | use std::path::{Path, PathBuf}; |
| 19 | use std::sync::Once; |
| 20 | use std::time::{Duration, Instant}; |
| 21 | |
| 22 | use engine::export::ExportSettings; |
| 23 | use engine::hw::HwEncoder; |
| 24 | use engine::mux::{Mp4Muxer, VideoParams, parameter_sets}; |
| 25 | use engine::project::Lane; |
| 26 | use engine::{DecodeSession, ExportHandle, PlaybackSession, Project}; |
| 27 | |
| 28 | const FPS: f64 = 30.0; |
| 29 | |
| 30 | fn asset(name: &str) -> PathBuf { |
| 31 | PathBuf::from(env!("CARGO_MANIFEST_DIR")) |
| 32 | .join("../../assets") |
| 33 | .join(name) |
| 34 | } |
| 35 | |
| 36 | |
| 37 | |
| 38 | fn out_path(name: &str) -> PathBuf { |
| 39 | let path = std::env::temp_dir().join(format!("ve_export_{name}_{}.mp4", std::process::id())); |
| 40 | let _ = std::fs::remove_file(&path); |
| 41 | let _ = std::fs::remove_file(part_path(&path)); |
| 42 | path |
| 43 | } |
| 44 | |
| 45 | |
| 46 | |
| 47 | fn part_path(out: &Path) -> PathBuf { |
| 48 | PathBuf::from(format!("{}.part", out.display())) |
| 49 | } |
| 50 | |
| 51 | |
| 52 | |
| 53 | fn pin_software() { |
| 54 | static PIN: Once = Once::new(); |
| 55 | PIN.call_once(|| unsafe { |
| 56 | std::env::set_var("VE_SW", "1"); |
| 57 | std::env::set_var("VE_SW_ENC", "1"); |
| 58 | }); |
| 59 | } |
| 60 | |
| 61 | |
| 62 | fn pin_hardware() { |
| 63 | static PIN: Once = Once::new(); |
| 64 | PIN.call_once(|| unsafe { |
| 65 | std::env::remove_var("VE_SW"); |
| 66 | std::env::remove_var("VE_SW_ENC"); |
| 67 | }); |
| 68 | } |
| 69 | |
| 70 | |
| 71 | |
| 72 | fn edited(source: &Path) -> PlaybackSession { |
| 73 | let mut session = PlaybackSession::open(source).expect("open source"); |
| 74 | assert!(session.cut_at(30.0 / FPS), "cut at frame 30"); |
| 75 | assert!(session.cut_at(60.0 / FPS), "cut at frame 60"); |
| 76 | assert!(session.delete_clip(1), "drop the middle clip"); |
| 77 | assert_eq!(session.clip_spans().len(), 2); |
| 78 | session |
| 79 | } |
| 80 | |
| 81 | fn wait(handle: &ExportHandle, limit: Duration) -> engine::Result<()> { |
| 82 | let started = Instant::now(); |
| 83 | while !handle.is_finished() { |
| 84 | assert!( |
| 85 | started.elapsed() < limit, |
| 86 | "export did not finish in {limit:?}" |
| 87 | ); |
| 88 | std::thread::sleep(Duration::from_millis(20)); |
| 89 | } |
| 90 | handle.result().expect("a finished export has an outcome") |
| 91 | } |
| 92 | |
| 93 | |
| 94 | fn decode_all(path: &Path) -> Vec<Vec<u8>> { |
| 95 | let (_, frames) = DecodeSession::open(path).expect("open export"); |
| 96 | frames.into_iter().map(|frame| frame.bgra).collect() |
| 97 | } |
| 98 | |
| 99 | |
| 100 | fn frame_at(path: &Path, index: u32) -> Vec<u8> { |
| 101 | let (_, frames, _) = DecodeSession::open_at(path, index).expect("open source"); |
| 102 | frames.recv().expect("frame present").bgra |
| 103 | } |
| 104 | |
| 105 | fn mean_abs_diff(a: &[u8], b: &[u8]) -> f64 { |
| 106 | assert_eq!(a.len(), b.len(), "frame sizes differ"); |
| 107 | a.iter() |
| 108 | .zip(b) |
| 109 | .map(|(x, y)| f64::from(x.abs_diff(*y))) |
| 110 | .sum::<f64>() |
| 111 | / a.len() as f64 |
| 112 | } |
| 113 | |
| 114 | |
| 115 | |
| 116 | fn round_trip(name: &str, limit: Duration) { |
| 117 | let source = asset("test_baseline.mp4"); |
| 118 | let mut session = edited(&source); |
| 119 | session.pause(); |
| 120 | let out = out_path(name); |
| 121 | |
| 122 | let started = Instant::now(); |
| 123 | let handle = session.export_to(&out); |
| 124 | wait(&handle, limit).expect("export"); |
| 125 | let spent = started.elapsed(); |
| 126 | println!( |
| 127 | "{name}: 120 frames in {:.2} s = {:.2} ms/frame", |
| 128 | spent.as_secs_f64(), |
| 129 | spent.as_secs_f64() * 1000.0 / 120.0 |
| 130 | ); |
| 131 | assert_eq!(handle.progress(), 1.0, "finished at full progress"); |
| 132 | |
| 133 | let (meta, _) = engine::demux::Demuxer::open(&out).expect("reopen export"); |
| 134 | assert_eq!(meta.frame_count, 120, "timeline frames written"); |
| 135 | assert_eq!((meta.width, meta.height), (1280, 720)); |
| 136 | assert_eq!(meta.frame_rate.round(), FPS); |
| 137 | |
| 138 | let file = File::open(&out).unwrap(); |
| 139 | let size = file.metadata().unwrap().len(); |
| 140 | let reader = mp4::Mp4Reader::read_header(BufReader::new(file), size).unwrap(); |
| 141 | let duration = reader.duration().as_secs_f64(); |
| 142 | assert!( |
| 143 | (duration - 120.0 / FPS).abs() <= 1.0 / FPS, |
| 144 | "duration {duration} s is more than a frame off 4.0 s" |
| 145 | ); |
| 146 | |
| 147 | let frames = decode_all(&out); |
| 148 | assert_eq!(frames.len(), 120, "every written frame decodes back"); |
| 149 | |
| 150 | |
| 151 | for (timeline, source_frame) in [(0u32, 0u32), (59, 89), (119, 149)] { |
| 152 | let diff = mean_abs_diff(&frames[timeline as usize], &frame_at(&source, source_frame)); |
| 153 | println!("timeline {timeline} vs source {source_frame}: mean abs diff {diff:.2}"); |
| 154 | assert!( |
| 155 | diff < 6.0, |
| 156 | "timeline frame {timeline} drifted by {diff:.2} from source frame {source_frame}" |
| 157 | ); |
| 158 | } |
| 159 | std::fs::remove_file(&out).unwrap(); |
| 160 | } |
| 161 | |
| 162 | #[test] |
| 163 | fn exports_an_edited_timeline_in_software() { |
| 164 | pin_software(); |
| 165 | round_trip("sw", Duration::from_secs(120)); |
| 166 | } |
| 167 | |
| 168 | |
| 169 | |
| 170 | #[test] |
| 171 | #[ignore] |
| 172 | fn exports_an_edited_timeline_in_hardware() { |
| 173 | pin_hardware(); |
| 174 | round_trip("hw", Duration::from_secs(60)); |
| 175 | } |
| 176 | |
| 177 | |
| 178 | |
| 179 | |
| 180 | fn two_sources() -> Project { |
| 181 | let (av, _) = engine::demux::Demuxer::open(&asset("test_av.mp4")).expect("open test_av"); |
| 182 | let (av2, _) = engine::demux::Demuxer::open(&asset("test_av2.mp4")).expect("open test_av2"); |
| 183 | assert_eq!((av.width, av.height), (av2.width, av2.height), "policy a"); |
| 184 | |
| 185 | let mut project = Project::single(asset("test_av.mp4"), av.frame_count); |
| 186 | let second = project.import(asset("test_av2.mp4")); |
| 187 | assert_eq!(second, 1, "a second file is a second source"); |
| 188 | assert!(project.append_clip(second, av2.frame_count)); |
| 189 | assert!(project.split(120), "cut a second before the end of test_av"); |
| 190 | assert!(project.delete(1), "drop test_av's tail"); |
| 191 | assert_eq!(project.timeline_frames(), 120 + av2.frame_count); |
| 192 | assert_eq!( |
| 193 | project.clips().iter().map(|c| c.source).collect::<Vec<_>>(), |
| 194 | vec![0, 1] |
| 195 | ); |
| 196 | project |
| 197 | } |
| 198 | |
| 199 | |
| 200 | |
| 201 | |
| 202 | fn multi_source_round_trip(name: &str, limit: Duration) { |
| 203 | let project = two_sources(); |
| 204 | let total = project.timeline_frames(); |
| 205 | let (meta, _) = engine::demux::Demuxer::open(&asset("test_av.mp4")).unwrap(); |
| 206 | let out = out_path(name); |
| 207 | |
| 208 | let started = Instant::now(); |
| 209 | let handle = engine::export::start(project.clone(), meta, &out, &ExportSettings::default()); |
| 210 | wait(&handle, limit).expect("export"); |
| 211 | println!( |
| 212 | "{name}: {total} frames of two sources in {:.2} s", |
| 213 | started.elapsed().as_secs_f64() |
| 214 | ); |
| 215 | |
| 216 | let (written, _) = engine::demux::Demuxer::open(&out).expect("reopen export"); |
| 217 | assert_eq!(written.frame_count, total, "timeline frames written"); |
| 218 | assert_eq!((written.width, written.height), (1280, 720)); |
| 219 | |
| 220 | let frames = decode_all(&out); |
| 221 | assert_eq!( |
| 222 | frames.len() as u32, |
| 223 | total, |
| 224 | "every written frame decodes back" |
| 225 | ); |
| 226 | |
| 227 | for (timeline, source, source_frame) in [ |
| 228 | (0u32, "test_av.mp4", 0u32), |
| 229 | (119, "test_av.mp4", 119), |
| 230 | (120, "test_av2.mp4", 0), |
| 231 | (total - 1, "test_av2.mp4", total - 121), |
| 232 | ] { |
| 233 | let diff = mean_abs_diff( |
| 234 | &frames[timeline as usize], |
| 235 | &frame_at(&asset(source), source_frame), |
| 236 | ); |
| 237 | println!("timeline {timeline} vs {source} {source_frame}: mean abs diff {diff:.2}"); |
| 238 | assert!( |
| 239 | diff < 6.0, |
| 240 | "timeline frame {timeline} drifted by {diff:.2} from {source} frame {source_frame}" |
| 241 | ); |
| 242 | } |
| 243 | |
| 244 | |
| 245 | |
| 246 | |
| 247 | |
| 248 | |
| 249 | |
| 250 | let file = File::open(&out).unwrap(); |
| 251 | let size = file.metadata().unwrap().len(); |
| 252 | let reader = mp4::Mp4Reader::read_header(BufReader::new(file), size).unwrap(); |
| 253 | let packets = reader.sample_count(2).expect("audio track"); |
| 254 | assert_eq!(packets, 346, "packet total across the source join"); |
| 255 | let wanted = f64::from(total) / FPS * 44_100.0; |
| 256 | assert!( |
| 257 | (f64::from(packets * 1024) - wanted).abs() < 3.0 * 1024.0, |
| 258 | "audio length {} samples drifted from {wanted}", |
| 259 | packets * 1024 |
| 260 | ); |
| 261 | let (audio, _) = engine::AudioSession::open(&out) |
| 262 | .expect("reopen export audio") |
| 263 | .expect("export has an audio track"); |
| 264 | assert_eq!((audio.sample_rate, audio.channels), (44_100, 2)); |
| 265 | std::fs::remove_file(&out).unwrap(); |
| 266 | } |
| 267 | |
| 268 | #[test] |
| 269 | fn exports_two_sources_as_one_timeline_in_software() { |
| 270 | pin_software(); |
| 271 | multi_source_round_trip("multi_sw", Duration::from_secs(180)); |
| 272 | } |
| 273 | |
| 274 | #[test] |
| 275 | #[ignore] |
| 276 | fn exports_two_sources_as_one_timeline_in_hardware() { |
| 277 | pin_hardware(); |
| 278 | multi_source_round_trip("multi_hw", Duration::from_secs(60)); |
| 279 | } |
| 280 | |
| 281 | |
| 282 | |
| 283 | |
| 284 | |
| 285 | #[test] |
| 286 | fn a_higher_bitrate_writes_a_bigger_file() { |
| 287 | pin_software(); |
| 288 | let mut sizes = Vec::new(); |
| 289 | for bitrate in [1_000_000u64, 4_000_000, 8_000_000] { |
| 290 | let mut session = edited(&asset("test_baseline.mp4")); |
| 291 | session.pause(); |
| 292 | let out = out_path(&format!("bitrate_{bitrate}")); |
| 293 | let settings = ExportSettings { |
| 294 | bitrate: Some(bitrate), |
| 295 | force_sw: true, |
| 296 | }; |
| 297 | let handle = session.export_to_with(&out, &settings); |
| 298 | wait(&handle, Duration::from_secs(180)).expect("export"); |
| 299 | let size = std::fs::metadata(&out).expect("export exists").len(); |
| 300 | println!("{} Mbps: {size} bytes", bitrate / 1_000_000); |
| 301 | sizes.push(size); |
| 302 | std::fs::remove_file(&out).unwrap(); |
| 303 | } |
| 304 | assert!( |
| 305 | sizes[0] < sizes[1] && sizes[1] < sizes[2], |
| 306 | "file sizes {sizes:?} are not strictly growing with the bitrate" |
| 307 | ); |
| 308 | } |
| 309 | |
| 310 | |
| 311 | |
| 312 | |
| 313 | |
| 314 | #[test] |
| 315 | fn a_vanished_source_fails_the_export() { |
| 316 | pin_software(); |
| 317 | let baseline = asset("test_baseline.mp4"); |
| 318 | let doomed = std::env::temp_dir().join("ve_export_vanished_source.mp4"); |
| 319 | std::fs::copy(&baseline, &doomed).expect("copy a second source"); |
| 320 | let (meta, _) = engine::demux::Demuxer::open(&baseline).unwrap(); |
| 321 | |
| 322 | |
| 323 | let mut project = Project::single(&baseline, meta.frame_count); |
| 324 | assert!(project.split(5)); |
| 325 | assert!(project.delete(1)); |
| 326 | let second = project.import(&doomed); |
| 327 | assert!(project.append_clip(second, meta.frame_count)); |
| 328 | assert!(project.split(10)); |
| 329 | assert!(project.delete(2)); |
| 330 | assert_eq!(project.timeline_frames(), 10); |
| 331 | |
| 332 | std::fs::remove_file(&doomed).expect("unlink the second source"); |
| 333 | let out = out_path("vanished"); |
| 334 | let handle = engine::export::start(project, meta, &out, &ExportSettings::default()); |
| 335 | let result = wait(&handle, Duration::from_secs(60)); |
| 336 | let error = result.expect_err("an export of a missing file cannot succeed"); |
| 337 | println!("vanished source: {error}"); |
| 338 | assert!( |
| 339 | !out.exists(), |
| 340 | "a failed export still wrote {}", |
| 341 | out.display() |
| 342 | ); |
| 343 | assert!(!part_path(&out).exists(), "the .part outlived the failure"); |
| 344 | } |
| 345 | |
| 346 | |
| 347 | |
| 348 | #[test] |
| 349 | fn cancelling_leaves_no_file() { |
| 350 | pin_software(); |
| 351 | let mut session = edited(&asset("test_baseline.mp4")); |
| 352 | session.pause(); |
| 353 | let out = out_path("cancel"); |
| 354 | |
| 355 | let handle = session.export_to(&out); |
| 356 | let started = Instant::now(); |
| 357 | while handle.progress() < 0.1 { |
| 358 | assert!( |
| 359 | started.elapsed() < Duration::from_secs(60), |
| 360 | "export never got going" |
| 361 | ); |
| 362 | assert!( |
| 363 | !handle.is_finished(), |
| 364 | "export finished before it was cancelled" |
| 365 | ); |
| 366 | std::thread::sleep(Duration::from_millis(10)); |
| 367 | } |
| 368 | handle.cancel(); |
| 369 | let result = wait(&handle, Duration::from_secs(5)); |
| 370 | assert!(result.is_err(), "a cancelled export is an error"); |
| 371 | assert!(!out.exists(), "no partial file survives a cancel"); |
| 372 | assert!(!part_path(&out).exists(), "the .part is cleaned up too"); |
| 373 | } |
| 374 | |
| 375 | |
| 376 | |
| 377 | |
| 378 | |
| 379 | |
| 380 | |
| 381 | |
| 382 | |
| 383 | #[test] |
| 384 | fn cancelling_after_the_last_frame_leaves_no_file() { |
| 385 | pin_software(); |
| 386 | let out = out_path("late"); |
| 387 | let part = part_path(&out); |
| 388 | for attempt in 1..=5 { |
| 389 | let mut session = edited(&asset("test_baseline.mp4")); |
| 390 | session.pause(); |
| 391 | let handle = session.export_to(&out); |
| 392 | |
| 393 | |
| 394 | let started = Instant::now(); |
| 395 | while handle.progress() < 0.9 && !handle.is_finished() { |
| 396 | assert!( |
| 397 | started.elapsed() < Duration::from_secs(120), |
| 398 | "export stalled" |
| 399 | ); |
| 400 | std::thread::sleep(Duration::from_millis(20)); |
| 401 | } |
| 402 | while handle.progress() < 1.0 && !handle.is_finished() { |
| 403 | std::hint::spin_loop(); |
| 404 | } |
| 405 | handle.cancel(); |
| 406 | |
| 407 | let result = wait(&handle, Duration::from_secs(30)); |
| 408 | assert!(!part.exists(), "attempt {attempt} left a .part behind"); |
| 409 | if result.is_err() { |
| 410 | assert!(!out.exists(), "a late cancel still wrote {}", out.display()); |
| 411 | return; |
| 412 | } |
| 413 | |
| 414 | assert_eq!( |
| 415 | engine::demux::Demuxer::open(&out).unwrap().0.frame_count, |
| 416 | 120 |
| 417 | ); |
| 418 | std::fs::remove_file(&out).unwrap(); |
| 419 | } |
| 420 | panic!("cancel never landed in the drain/audio/finish window"); |
| 421 | } |
| 422 | |
| 423 | |
| 424 | |
| 425 | #[test] |
| 426 | #[ignore] |
| 427 | fn exports_audio_alongside_the_video() { |
| 428 | pin_hardware(); |
| 429 | let source = asset("test_av.mp4"); |
| 430 | let mut session = PlaybackSession::open(&source).expect("open source"); |
| 431 | |
| 432 | |
| 433 | assert!(session.cut_at(2.0)); |
| 434 | session.pause(); |
| 435 | let timeline = session.timeline_duration(); |
| 436 | let out = out_path("av"); |
| 437 | |
| 438 | let handle = session.export_to(&out); |
| 439 | wait(&handle, Duration::from_secs(120)).expect("export"); |
| 440 | |
| 441 | let file = File::open(&out).unwrap(); |
| 442 | let size = file.metadata().unwrap().len(); |
| 443 | let reader = mp4::Mp4Reader::read_header(BufReader::new(file), size).unwrap(); |
| 444 | let packets = reader.sample_count(2).expect("audio track"); |
| 445 | let expected = engine::AudioSession::copy_segments(&source, &[(0.0, 2.0), (2.0, 5.0)]) |
| 446 | .unwrap() |
| 447 | .expect("source has audio") |
| 448 | .1 |
| 449 | .len() as u32; |
| 450 | assert_eq!(packets, expected, "every copied packet reached the file"); |
| 451 | |
| 452 | |
| 453 | let samples = f64::from(packets * 1024); |
| 454 | let wanted = timeline * 44_100.0; |
| 455 | println!("audio: {packets} packets = {samples} samples for {wanted} of timeline"); |
| 456 | assert!( |
| 457 | (samples - wanted).abs() < 3.0 * 1024.0, |
| 458 | "audio length {samples} drifted from {wanted}" |
| 459 | ); |
| 460 | |
| 461 | let (meta, chunks) = engine::AudioSession::open(&out) |
| 462 | .expect("reopen export audio") |
| 463 | .expect("export has an audio track"); |
| 464 | assert_eq!(meta.sample_rate, 44_100); |
| 465 | assert_eq!(meta.channels, 2); |
| 466 | let decoded: usize = chunks.into_iter().map(|c| c.samples.len()).sum(); |
| 467 | assert!( |
| 468 | decoded as f64 / 2.0 > wanted - 3.0 * 1024.0, |
| 469 | "only {decoded} samples decoded back out" |
| 470 | ); |
| 471 | |
| 472 | let (video, _) = engine::demux::Demuxer::open(&out).unwrap(); |
| 473 | assert_eq!(video.frame_count, 150, "video track unaffected by the cut"); |
| 474 | std::fs::remove_file(&out).unwrap(); |
| 475 | } |
| 476 | |
| 477 | |
| 478 | |
| 479 | |
| 480 | #[test] |
| 481 | #[ignore] |
| 482 | fn hardware_access_units_repack_into_mp4() { |
| 483 | let (w, h) = (640u32, 480u32); |
| 484 | let mut encoder = |
| 485 | HwEncoder::open(w, h, 30, 1, 4_000_000).expect("no hardware encode plugin/driver"); |
| 486 | let out = out_path("hwmux"); |
| 487 | let mut muxer: Option<Mp4Muxer> = None; |
| 488 | let mut written = 0; |
| 489 | for index in 0..10u32 { |
| 490 | let (y, u, v) = synthetic(index, w as usize, h as usize); |
| 491 | let Some(au) = encoder.encode(&y, &u, &v, w, h, false).expect("encode") else { |
| 492 | continue; |
| 493 | }; |
| 494 | if muxer.is_none() { |
| 495 | let (sps, pps) = parameter_sets(au).expect("first access unit carries SPS+PPS"); |
| 496 | muxer = Some( |
| 497 | Mp4Muxer::create( |
| 498 | &out, |
| 499 | &VideoParams { |
| 500 | width: w, |
| 501 | height: h, |
| 502 | frame_rate: 30.0, |
| 503 | sps, |
| 504 | pps, |
| 505 | }, |
| 506 | None, |
| 507 | ) |
| 508 | .expect("create"), |
| 509 | ); |
| 510 | } |
| 511 | muxer.as_mut().unwrap().write_video_au(au).expect("write"); |
| 512 | written += 1; |
| 513 | } |
| 514 | while let Some(au) = encoder.drain().expect("drain") { |
| 515 | muxer.as_mut().unwrap().write_video_au(au).expect("write"); |
| 516 | written += 1; |
| 517 | } |
| 518 | muxer.unwrap().finish().expect("finish"); |
| 519 | assert_eq!(written, 10); |
| 520 | |
| 521 | let (meta, mut demuxer) = engine::demux::Demuxer::open(&out).unwrap(); |
| 522 | assert_eq!(meta.frame_count, 10); |
| 523 | let mut decoder = rusty_h264::Decoder::new(); |
| 524 | let mut decoded = 0; |
| 525 | while let Some(au) = demuxer.next_access_unit().unwrap() { |
| 526 | if decoder |
| 527 | .decode(&au) |
| 528 | .expect("software decode of the remuxed stream") |
| 529 | .is_some() |
| 530 | { |
| 531 | decoded += 1; |
| 532 | } |
| 533 | } |
| 534 | assert_eq!(decoded, 10, "every remuxed picture decodes again"); |
| 535 | std::fs::remove_file(&out).unwrap(); |
| 536 | } |
| 537 | |
| 538 | |
| 539 | |
| 540 | fn synthetic(index: u32, width: usize, height: usize) -> (Vec<u8>, Vec<u8>, Vec<u8>) { |
| 541 | let (cw, ch) = (width.div_ceil(2), height.div_ceil(2)); |
| 542 | let mut y = vec![0u8; width * height]; |
| 543 | for row in 0..height { |
| 544 | for col in 0..width { |
| 545 | y[row * width + col] = (row + col + index as usize * 5) as u8; |
| 546 | } |
| 547 | } |
| 548 | ( |
| 549 | y, |
| 550 | vec![64u8.wrapping_add(index as u8); cw * ch], |
| 551 | vec![192u8.wrapping_sub(index as u8); cw * ch], |
| 552 | ) |
| 553 | } |
| 554 | |
| 555 | |
| 556 | |
| 557 | |
| 558 | |
| 559 | |
| 560 | #[test] |
| 561 | fn a_leading_audio_gap_keeps_the_sound_after_it_in_place() { |
| 562 | pin_software(); |
| 563 | let source = asset("test_av.mp4"); |
| 564 | let mut session = PlaybackSession::open(&source).expect("open source"); |
| 565 | assert!(session.cut_at(1.0), "cut at 1 s"); |
| 566 | assert!(session.lift_clip(Lane::Audio, 0), "lift the first second"); |
| 567 | session.pause(); |
| 568 | let out = out_path("leading_gap"); |
| 569 | let handle = session.export_to(&out); |
| 570 | wait(&handle, Duration::from_secs(180)).expect("export"); |
| 571 | |
| 572 | let (_, chunks) = engine::AudioSession::open(&out) |
| 573 | .expect("reopen export audio") |
| 574 | .expect("export has an audio track"); |
| 575 | let mut pcm: Vec<f32> = Vec::new(); |
| 576 | while let Ok(chunk) = chunks.recv_timeout(Duration::from_secs(10)) { |
| 577 | pcm.resize(chunk.start_sample as usize * 2, 0.0); |
| 578 | pcm.extend_from_slice(&chunk.samples); |
| 579 | } |
| 580 | |
| 581 | |
| 582 | |
| 583 | let block = 1024 * 2; |
| 584 | let peak = |b: &[f32]| b.iter().fold(0.0f32, |m, s| m.max(s.abs())); |
| 585 | let loud = peak(&pcm) / 4.0; |
| 586 | let onset = pcm |
| 587 | .chunks(block) |
| 588 | .position(|b| peak(b) > loud) |
| 589 | .expect("the export has no sound at all") as f64 |
| 590 | * 1024.0; |
| 591 | println!("leading gap: sound starts at sample {onset} of an expected 44100"); |
| 592 | assert!( |
| 593 | (onset - 44_100.0).abs() <= 1024.0, |
| 594 | "the sound after the gap is at {onset}, not at the 1 s hole's end" |
| 595 | ); |
| 596 | |
| 597 | let quiet = peak(&pcm[..(0.9 * 44_100.0) as usize * 2]); |
| 598 | assert!(quiet < 1e-3, "the lifted second is not silent: {quiet}"); |
| 599 | |
| 600 | std::fs::remove_file(&out).unwrap(); |
| 601 | } |
| 602 | |
| 603 | |
| 604 | |
| 605 | |
| 606 | |
| 607 | |
| 608 | #[test] |
| 609 | fn exports_a_gapped_timeline_as_black_and_silence() { |
| 610 | pin_software(); |
| 611 | let source = asset("test_av.mp4"); |
| 612 | let mut session = PlaybackSession::open(&source).expect("open source"); |
| 613 | assert!(session.cut_at(1.0), "split at 1 s"); |
| 614 | assert!(session.cut_at(2.0), "split at 2 s"); |
| 615 | |
| 616 | |
| 617 | assert!(session.lift_clip(Lane::Video, 1)); |
| 618 | assert!(session.lift_clip(Lane::Audio, 1)); |
| 619 | session.pause(); |
| 620 | let timeline = session.timeline_duration(); |
| 621 | let frames = (timeline * FPS).round() as u32; |
| 622 | let out = out_path("gapped"); |
| 623 | |
| 624 | let handle = session.export_to(&out); |
| 625 | wait(&handle, Duration::from_secs(180)).expect("export"); |
| 626 | |
| 627 | |
| 628 | let (video, _) = engine::demux::Demuxer::open(&out).unwrap(); |
| 629 | assert_eq!( |
| 630 | video.frame_count, frames, |
| 631 | "a gap is encoded, not skipped: {} frames for a {timeline:.3}s timeline", |
| 632 | video.frame_count |
| 633 | ); |
| 634 | let pictures = decode_all(&out); |
| 635 | assert_eq!(pictures.len() as u32, frames); |
| 636 | let (hole, hole_end) = ((1.0 * FPS) as usize, (2.0 * FPS) as usize); |
| 637 | |
| 638 | |
| 639 | let black = [0u8, 0, 0, 255].repeat(pictures[0].len() / 4); |
| 640 | for (i, picture) in pictures.iter().enumerate() { |
| 641 | let diff = mean_abs_diff(picture, &black); |
| 642 | if (hole..hole_end).contains(&i) { |
| 643 | assert!( |
| 644 | diff < 4.0, |
| 645 | "frame {i} of the gap is not black (MAE {diff:.2})" |
| 646 | ); |
| 647 | } |
| 648 | } |
| 649 | let lit = mean_abs_diff(&pictures[0], &black); |
| 650 | assert!(lit > 4.0, "the clips around the gap came out black too"); |
| 651 | |
| 652 | |
| 653 | |
| 654 | |
| 655 | let file = File::open(&out).unwrap(); |
| 656 | let size = file.metadata().unwrap().len(); |
| 657 | let reader = mp4::Mp4Reader::read_header(BufReader::new(file), size).unwrap(); |
| 658 | let count = reader.sample_count(2).expect("audio track"); |
| 659 | let samples = f64::from(count * 1024); |
| 660 | let wanted = timeline * 44_100.0; |
| 661 | println!("gapped export: {count} packets = {samples} samples for {wanted}"); |
| 662 | assert!( |
| 663 | (samples - wanted).abs() < 3.0 * 1024.0, |
| 664 | "audio length {samples} drifted from {wanted} across the gap" |
| 665 | ); |
| 666 | |
| 667 | |
| 668 | let (_, chunks) = engine::AudioSession::open(&out) |
| 669 | .expect("reopen export audio") |
| 670 | .expect("export has an audio track"); |
| 671 | let mut pcm: Vec<f32> = Vec::new(); |
| 672 | while let Ok(chunk) = chunks.recv_timeout(Duration::from_secs(10)) { |
| 673 | pcm.resize(chunk.start_sample as usize * 2, 0.0); |
| 674 | pcm.extend_from_slice(&chunk.samples); |
| 675 | } |
| 676 | let window = |from: f64, to: f64| { |
| 677 | let (a, b) = ((from * 44_100.0) as usize * 2, (to * 44_100.0) as usize * 2); |
| 678 | pcm[a.min(pcm.len())..b.min(pcm.len())] |
| 679 | .iter() |
| 680 | .fold(0.0f32, |m, s| m.max(s.abs())) |
| 681 | }; |
| 682 | |
| 683 | |
| 684 | let quiet = window(1.2, 1.8); |
| 685 | assert!(quiet < 1e-3, "the gap is not silent: {quiet}"); |
| 686 | assert!(window(0.1, 0.9) > 1e-2, "the sound before it went missing"); |
| 687 | assert!(window(2.2, 4.9) > 1e-2, "the sound after it went missing"); |
| 688 | |
| 689 | std::fs::remove_file(&out).unwrap(); |
| 690 | } |