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