| 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, Source, Speed}; |
| 26 | use engine::scale::FitPolicy; |
| 27 | use engine::scratch::Scratch; |
| 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 | |
| 41 | fn out_path(name: &str) -> Scratch { |
| 42 | Scratch::file(&format!("ve_export_{name}"), "mp4") |
| 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(Lane::V1, 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 | |
| 181 | |
| 182 | |
| 183 | |
| 184 | #[test] |
| 185 | fn exports_at_the_project_resolution_with_the_watched_geometry() { |
| 186 | pin_software(); |
| 187 | let clip = |source: usize, start: u32| engine::Clip { |
| 188 | start, |
| 189 | in_frame: 0, |
| 190 | out_frame: 10, |
| 191 | source, |
| 192 | link: Some(source as u32), |
| 193 | eq: None, |
| 194 | color: None, |
| 195 | fit: FitPolicy::default(), |
| 196 | speed: Speed::NORMAL, |
| 197 | }; |
| 198 | let clips = vec![clip(0, 0), clip(1, 10)]; |
| 199 | let project = Project::from_parts( |
| 200 | vec![ |
| 201 | Source::new(asset("test_baseline.mp4"), 0), |
| 202 | Source::new(asset("test_mismatch.mp4"), 0), |
| 203 | ], |
| 204 | vec![ |
| 205 | (engine::project::LaneKind::Video, clips.clone()), |
| 206 | (engine::project::LaneKind::Audio, clips), |
| 207 | ], |
| 208 | Vec::new(), |
| 209 | Vec::new(), |
| 210 | ) |
| 211 | .expect("a two-source project"); |
| 212 | |
| 213 | |
| 214 | let meta = engine::VideoMeta { |
| 215 | width: 960, |
| 216 | height: 720, |
| 217 | frame_rate: FPS, |
| 218 | frame_count: 20, |
| 219 | codec: engine::Codec::H264, |
| 220 | color: Default::default(), |
| 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 | speed: Speed::NORMAL, |
| 279 | }; |
| 280 | |
| 281 | |
| 282 | |
| 283 | let project = Project::from_parts( |
| 284 | vec![Source { |
| 285 | path: multi.clone(), |
| 286 | audio_stream: 1, |
| 287 | }], |
| 288 | vec![ |
| 289 | (engine::project::LaneKind::Video, vec![whole]), |
| 290 | (engine::project::LaneKind::Audio, vec![whole]), |
| 291 | ], |
| 292 | Vec::new(), |
| 293 | Vec::new(), |
| 294 | ) |
| 295 | .expect("a one-source project on stream 1"); |
| 296 | let out = out_path("stream1"); |
| 297 | let handle = engine::export::start(project, meta, &out, &ExportSettings::default()); |
| 298 | wait(&handle, Duration::from_secs(120)).expect("export"); |
| 299 | |
| 300 | let (audio, _) = engine::AudioSession::open(&out) |
| 301 | .expect("reopen export audio") |
| 302 | .expect("the export has audio"); |
| 303 | assert_eq!( |
| 304 | (audio.sample_rate, audio.channels), |
| 305 | (22_050, 1), |
| 306 | "the export carries stream 0's parameters, not the stream that played" |
| 307 | ); |
| 308 | |
| 309 | |
| 310 | |
| 311 | |
| 312 | let segs = [(Some(0), 0.0, f64::from(meta.frame_count) / FPS)]; |
| 313 | let copy = |stream| { |
| 314 | engine::AudioSession::copy_multi_streams(&[(multi.clone(), stream)], &segs) |
| 315 | .expect("copy") |
| 316 | .expect("has audio") |
| 317 | .1 |
| 318 | .into_iter() |
| 319 | .map(|p| p.bytes) |
| 320 | .collect::<Vec<_>>() |
| 321 | }; |
| 322 | let (one, zero) = (copy(1), copy(0)); |
| 323 | assert_ne!(one, zero, "the two streams are not the same bytes"); |
| 324 | |
| 325 | let file = File::open(&out).unwrap(); |
| 326 | let size = file.metadata().unwrap().len(); |
| 327 | let mut reader = mp4::Mp4Reader::read_header(BufReader::new(file), size).unwrap(); |
| 328 | let track = *reader |
| 329 | .tracks() |
| 330 | .keys() |
| 331 | .find(|id| reader.sample_count(**id).unwrap_or(0) as usize == one.len()) |
| 332 | .unwrap_or(&2); |
| 333 | let written: Vec<Vec<u8>> = (1..=reader.sample_count(track).expect("audio track")) |
| 334 | .map(|id| { |
| 335 | reader |
| 336 | .read_sample(track, id) |
| 337 | .expect("sample") |
| 338 | .expect("present") |
| 339 | .bytes |
| 340 | .to_vec() |
| 341 | }) |
| 342 | .collect(); |
| 343 | assert_eq!(written, one, "the exported packets are stream 1's"); |
| 344 | std::fs::remove_file(&out).unwrap(); |
| 345 | } |
| 346 | |
| 347 | |
| 348 | |
| 349 | |
| 350 | fn two_sources() -> Project { |
| 351 | let (av, _) = engine::demux::Demuxer::open(&asset("test_av.mp4")).expect("open test_av"); |
| 352 | let (av2, _) = engine::demux::Demuxer::open(&asset("test_av2.mp4")).expect("open test_av2"); |
| 353 | assert_eq!((av.width, av.height), (av2.width, av2.height), "policy a"); |
| 354 | |
| 355 | let mut project = Project::single(asset("test_av.mp4"), av.frame_count); |
| 356 | let second = project.import(asset("test_av2.mp4"), 0); |
| 357 | assert_eq!(second, 1, "a second file is a second source"); |
| 358 | assert!(project.append_clip(second, av2.frame_count)); |
| 359 | assert!(project.split(120), "cut a second before the end of test_av"); |
| 360 | assert!(project.delete(1), "drop test_av's tail"); |
| 361 | assert_eq!(project.timeline_frames(), 120 + av2.frame_count); |
| 362 | assert_eq!( |
| 363 | project.clips().iter().map(|c| c.source).collect::<Vec<_>>(), |
| 364 | vec![0, 1] |
| 365 | ); |
| 366 | project |
| 367 | } |
| 368 | |
| 369 | |
| 370 | |
| 371 | |
| 372 | fn multi_source_round_trip(name: &str, limit: Duration) { |
| 373 | let project = two_sources(); |
| 374 | let total = project.timeline_frames(); |
| 375 | let (meta, _) = engine::demux::Demuxer::open(&asset("test_av.mp4")).unwrap(); |
| 376 | let out = out_path(name); |
| 377 | |
| 378 | let started = Instant::now(); |
| 379 | let handle = engine::export::start(project.clone(), meta, &out, &ExportSettings::default()); |
| 380 | wait(&handle, limit).expect("export"); |
| 381 | println!( |
| 382 | "{name}: {total} frames of two sources in {:.2} s", |
| 383 | started.elapsed().as_secs_f64() |
| 384 | ); |
| 385 | |
| 386 | let (written, _) = engine::demux::Demuxer::open(&out).expect("reopen export"); |
| 387 | assert_eq!(written.frame_count, total, "timeline frames written"); |
| 388 | assert_eq!((written.width, written.height), (1280, 720)); |
| 389 | |
| 390 | let frames = decode_all(&out); |
| 391 | assert_eq!( |
| 392 | frames.len() as u32, |
| 393 | total, |
| 394 | "every written frame decodes back" |
| 395 | ); |
| 396 | |
| 397 | for (timeline, source, source_frame) in [ |
| 398 | (0u32, "test_av.mp4", 0u32), |
| 399 | (119, "test_av.mp4", 119), |
| 400 | (120, "test_av2.mp4", 0), |
| 401 | (total - 1, "test_av2.mp4", total - 121), |
| 402 | ] { |
| 403 | let diff = mean_abs_diff( |
| 404 | &frames[timeline as usize], |
| 405 | &frame_at(&asset(source), source_frame), |
| 406 | ); |
| 407 | println!("timeline {timeline} vs {source} {source_frame}: mean abs diff {diff:.2}"); |
| 408 | assert!( |
| 409 | diff < 6.0, |
| 410 | "timeline frame {timeline} drifted by {diff:.2} from {source} frame {source_frame}" |
| 411 | ); |
| 412 | } |
| 413 | |
| 414 | |
| 415 | |
| 416 | |
| 417 | |
| 418 | |
| 419 | |
| 420 | let file = File::open(&out).unwrap(); |
| 421 | let size = file.metadata().unwrap().len(); |
| 422 | let reader = mp4::Mp4Reader::read_header(BufReader::new(file), size).unwrap(); |
| 423 | let packets = reader.sample_count(2).expect("audio track"); |
| 424 | assert_eq!(packets, 346, "packet total across the source join"); |
| 425 | let wanted = f64::from(total) / FPS * 44_100.0; |
| 426 | assert!( |
| 427 | (f64::from(packets * 1024) - wanted).abs() < 3.0 * 1024.0, |
| 428 | "audio length {} samples drifted from {wanted}", |
| 429 | packets * 1024 |
| 430 | ); |
| 431 | let (audio, _) = engine::AudioSession::open(&out) |
| 432 | .expect("reopen export audio") |
| 433 | .expect("export has an audio track"); |
| 434 | assert_eq!((audio.sample_rate, audio.channels), (44_100, 2)); |
| 435 | std::fs::remove_file(&out).unwrap(); |
| 436 | } |
| 437 | |
| 438 | #[test] |
| 439 | fn exports_two_sources_as_one_timeline_in_software() { |
| 440 | pin_software(); |
| 441 | multi_source_round_trip("multi_sw", Duration::from_secs(180)); |
| 442 | } |
| 443 | |
| 444 | #[test] |
| 445 | #[ignore] |
| 446 | fn exports_two_sources_as_one_timeline_in_hardware() { |
| 447 | pin_hardware(); |
| 448 | multi_source_round_trip("multi_hw", Duration::from_secs(60)); |
| 449 | } |
| 450 | |
| 451 | |
| 452 | |
| 453 | |
| 454 | |
| 455 | #[test] |
| 456 | fn a_higher_bitrate_writes_a_bigger_file() { |
| 457 | pin_software(); |
| 458 | let mut sizes = Vec::new(); |
| 459 | for bitrate in [1_000_000u64, 4_000_000, 8_000_000] { |
| 460 | let mut session = edited(&asset("test_baseline.mp4")); |
| 461 | session.pause(); |
| 462 | let out = out_path(&format!("bitrate_{bitrate}")); |
| 463 | let settings = ExportSettings { |
| 464 | bitrate: Some(bitrate), |
| 465 | force_sw: true, |
| 466 | ..Default::default() |
| 467 | }; |
| 468 | let handle = session.export_to_with(&out, &settings); |
| 469 | wait(&handle, Duration::from_secs(180)).expect("export"); |
| 470 | let size = std::fs::metadata(&out).expect("export exists").len(); |
| 471 | println!("{} Mbps: {size} bytes", bitrate / 1_000_000); |
| 472 | sizes.push(size); |
| 473 | std::fs::remove_file(&out).unwrap(); |
| 474 | } |
| 475 | assert!( |
| 476 | sizes[0] < sizes[1] && sizes[1] < sizes[2], |
| 477 | "file sizes {sizes:?} are not strictly growing with the bitrate" |
| 478 | ); |
| 479 | } |
| 480 | |
| 481 | |
| 482 | |
| 483 | |
| 484 | |
| 485 | #[test] |
| 486 | fn a_vanished_source_fails_the_export() { |
| 487 | pin_software(); |
| 488 | let baseline = asset("test_baseline.mp4"); |
| 489 | let doomed = Scratch::file("ve_export_vanished_source", "mp4"); |
| 490 | std::fs::copy(&baseline, &doomed).expect("copy a second source"); |
| 491 | let (meta, _) = engine::demux::Demuxer::open(&baseline).unwrap(); |
| 492 | |
| 493 | |
| 494 | let mut project = Project::single(&baseline, meta.frame_count); |
| 495 | assert!(project.split(5)); |
| 496 | assert!(project.delete(1)); |
| 497 | let second = project.import(&doomed, 0); |
| 498 | assert!(project.append_clip(second, meta.frame_count)); |
| 499 | assert!(project.split(10)); |
| 500 | assert!(project.delete(2)); |
| 501 | assert_eq!(project.timeline_frames(), 10); |
| 502 | |
| 503 | std::fs::remove_file(&doomed).expect("unlink the second source"); |
| 504 | let out = out_path("vanished"); |
| 505 | let handle = engine::export::start(project, meta, &out, &ExportSettings::default()); |
| 506 | let result = wait(&handle, Duration::from_secs(60)); |
| 507 | let error = result.expect_err("an export of a missing file cannot succeed"); |
| 508 | println!("vanished source: {error}"); |
| 509 | assert!( |
| 510 | !out.exists(), |
| 511 | "a failed export still wrote {}", |
| 512 | out.display() |
| 513 | ); |
| 514 | assert!(!part_path(&out).exists(), "the .part outlived the failure"); |
| 515 | } |
| 516 | |
| 517 | |
| 518 | |
| 519 | #[test] |
| 520 | fn cancelling_leaves_no_file() { |
| 521 | pin_software(); |
| 522 | let mut session = edited(&asset("test_baseline.mp4")); |
| 523 | session.pause(); |
| 524 | let out = out_path("cancel"); |
| 525 | |
| 526 | let handle = session.export_to(&out); |
| 527 | let started = Instant::now(); |
| 528 | while handle.progress() < 0.1 { |
| 529 | assert!( |
| 530 | started.elapsed() < Duration::from_secs(60), |
| 531 | "export never got going" |
| 532 | ); |
| 533 | assert!( |
| 534 | !handle.is_finished(), |
| 535 | "export finished before it was cancelled" |
| 536 | ); |
| 537 | std::thread::sleep(Duration::from_millis(10)); |
| 538 | } |
| 539 | handle.cancel(); |
| 540 | let result = wait(&handle, Duration::from_secs(5)); |
| 541 | assert!(result.is_err(), "a cancelled export is an error"); |
| 542 | assert!(!out.exists(), "no partial file survives a cancel"); |
| 543 | assert!(!part_path(&out).exists(), "the .part is cleaned up too"); |
| 544 | } |
| 545 | |
| 546 | |
| 547 | |
| 548 | |
| 549 | |
| 550 | |
| 551 | |
| 552 | |
| 553 | |
| 554 | #[test] |
| 555 | fn cancelling_after_the_last_frame_leaves_no_file() { |
| 556 | pin_software(); |
| 557 | let out = out_path("late"); |
| 558 | let part = part_path(&out); |
| 559 | for attempt in 1..=5 { |
| 560 | let mut session = edited(&asset("test_baseline.mp4")); |
| 561 | session.pause(); |
| 562 | let handle = session.export_to(&out); |
| 563 | |
| 564 | |
| 565 | let started = Instant::now(); |
| 566 | while handle.progress() < 0.9 && !handle.is_finished() { |
| 567 | assert!( |
| 568 | started.elapsed() < Duration::from_secs(120), |
| 569 | "export stalled" |
| 570 | ); |
| 571 | std::thread::sleep(Duration::from_millis(20)); |
| 572 | } |
| 573 | while handle.progress() < 1.0 && !handle.is_finished() { |
| 574 | std::hint::spin_loop(); |
| 575 | } |
| 576 | handle.cancel(); |
| 577 | |
| 578 | let result = wait(&handle, Duration::from_secs(30)); |
| 579 | assert!(!part.exists(), "attempt {attempt} left a .part behind"); |
| 580 | if result.is_err() { |
| 581 | assert!(!out.exists(), "a late cancel still wrote {}", out.display()); |
| 582 | return; |
| 583 | } |
| 584 | |
| 585 | assert_eq!( |
| 586 | engine::demux::Demuxer::open(&out).unwrap().0.frame_count, |
| 587 | 120 |
| 588 | ); |
| 589 | std::fs::remove_file(&out).unwrap(); |
| 590 | } |
| 591 | panic!("cancel never landed in the drain/audio/finish window"); |
| 592 | } |
| 593 | |
| 594 | |
| 595 | |
| 596 | #[test] |
| 597 | #[ignore] |
| 598 | fn exports_audio_alongside_the_video() { |
| 599 | pin_hardware(); |
| 600 | let source = asset("test_av.mp4"); |
| 601 | let mut session = PlaybackSession::open(&source).expect("open source"); |
| 602 | |
| 603 | |
| 604 | assert!(session.cut_at(2.0)); |
| 605 | session.pause(); |
| 606 | let timeline = session.timeline_duration(); |
| 607 | let out = out_path("av"); |
| 608 | |
| 609 | let handle = session.export_to(&out); |
| 610 | wait(&handle, Duration::from_secs(120)).expect("export"); |
| 611 | |
| 612 | let file = File::open(&out).unwrap(); |
| 613 | let size = file.metadata().unwrap().len(); |
| 614 | let reader = mp4::Mp4Reader::read_header(BufReader::new(file), size).unwrap(); |
| 615 | let packets = reader.sample_count(2).expect("audio track"); |
| 616 | let expected = engine::AudioSession::copy_segments(&source, &[(0.0, 2.0), (2.0, 5.0)]) |
| 617 | .unwrap() |
| 618 | .expect("source has audio") |
| 619 | .1 |
| 620 | .len() as u32; |
| 621 | assert_eq!(packets, expected, "every copied packet reached the file"); |
| 622 | |
| 623 | |
| 624 | let samples = f64::from(packets * 1024); |
| 625 | let wanted = timeline * 44_100.0; |
| 626 | println!("audio: {packets} packets = {samples} samples for {wanted} of timeline"); |
| 627 | assert!( |
| 628 | (samples - wanted).abs() < 3.0 * 1024.0, |
| 629 | "audio length {samples} drifted from {wanted}" |
| 630 | ); |
| 631 | |
| 632 | let (meta, chunks) = engine::AudioSession::open(&out) |
| 633 | .expect("reopen export audio") |
| 634 | .expect("export has an audio track"); |
| 635 | assert_eq!(meta.sample_rate, 44_100); |
| 636 | assert_eq!(meta.channels, 2); |
| 637 | let decoded: usize = chunks.into_iter().map(|c| c.samples.len()).sum(); |
| 638 | assert!( |
| 639 | decoded as f64 / 2.0 > wanted - 3.0 * 1024.0, |
| 640 | "only {decoded} samples decoded back out" |
| 641 | ); |
| 642 | |
| 643 | let (video, _) = engine::demux::Demuxer::open(&out).unwrap(); |
| 644 | assert_eq!(video.frame_count, 150, "video track unaffected by the cut"); |
| 645 | std::fs::remove_file(&out).unwrap(); |
| 646 | } |
| 647 | |
| 648 | |
| 649 | |
| 650 | |
| 651 | #[test] |
| 652 | #[ignore] |
| 653 | fn hardware_access_units_repack_into_mp4() { |
| 654 | let (w, h) = (640u32, 480u32); |
| 655 | let mut encoder = |
| 656 | HwEncoder::open(w, h, 30, 1, 4_000_000).expect("no hardware encode plugin/driver"); |
| 657 | let out = out_path("hwmux"); |
| 658 | let mut muxer: Option<Mp4Muxer> = None; |
| 659 | let mut written = 0; |
| 660 | for index in 0..10u32 { |
| 661 | let (y, u, v) = synthetic(index, w as usize, h as usize); |
| 662 | let Some(au) = encoder.encode(&y, &u, &v, w, h, false).expect("encode") else { |
| 663 | continue; |
| 664 | }; |
| 665 | if muxer.is_none() { |
| 666 | let (sps, pps) = parameter_sets(au).expect("first access unit carries SPS+PPS"); |
| 667 | muxer = Some( |
| 668 | Mp4Muxer::create( |
| 669 | &out, |
| 670 | &VideoParams { |
| 671 | width: w, |
| 672 | height: h, |
| 673 | frame_rate: 30.0, |
| 674 | sps, |
| 675 | pps, |
| 676 | }, |
| 677 | None, |
| 678 | ) |
| 679 | .expect("create"), |
| 680 | ); |
| 681 | } |
| 682 | muxer.as_mut().unwrap().write_video_au(au).expect("write"); |
| 683 | written += 1; |
| 684 | } |
| 685 | while let Some(au) = encoder.drain().expect("drain") { |
| 686 | muxer.as_mut().unwrap().write_video_au(au).expect("write"); |
| 687 | written += 1; |
| 688 | } |
| 689 | muxer.unwrap().finish().expect("finish"); |
| 690 | assert_eq!(written, 10); |
| 691 | |
| 692 | let (meta, mut demuxer) = engine::demux::Demuxer::open(&out).unwrap(); |
| 693 | assert_eq!(meta.frame_count, 10); |
| 694 | let mut decoder = rusty_h264::Decoder::new(); |
| 695 | let mut decoded = 0; |
| 696 | while let Some(au) = demuxer.next_access_unit().unwrap() { |
| 697 | if decoder |
| 698 | .decode(&au) |
| 699 | .expect("software decode of the remuxed stream") |
| 700 | .is_some() |
| 701 | { |
| 702 | decoded += 1; |
| 703 | } |
| 704 | } |
| 705 | assert_eq!(decoded, 10, "every remuxed picture decodes again"); |
| 706 | std::fs::remove_file(&out).unwrap(); |
| 707 | } |
| 708 | |
| 709 | |
| 710 | |
| 711 | fn synthetic(index: u32, width: usize, height: usize) -> (Vec<u8>, Vec<u8>, Vec<u8>) { |
| 712 | let (cw, ch) = (width.div_ceil(2), height.div_ceil(2)); |
| 713 | let mut y = vec![0u8; width * height]; |
| 714 | for row in 0..height { |
| 715 | for col in 0..width { |
| 716 | y[row * width + col] = (row + col + index as usize * 5) as u8; |
| 717 | } |
| 718 | } |
| 719 | ( |
| 720 | y, |
| 721 | vec![64u8.wrapping_add(index as u8); cw * ch], |
| 722 | vec![192u8.wrapping_sub(index as u8); cw * ch], |
| 723 | ) |
| 724 | } |
| 725 | |
| 726 | |
| 727 | |
| 728 | |
| 729 | |
| 730 | |
| 731 | #[test] |
| 732 | fn a_leading_audio_gap_keeps_the_sound_after_it_in_place() { |
| 733 | pin_software(); |
| 734 | let source = asset("test_av.mp4"); |
| 735 | let mut session = PlaybackSession::open(&source).expect("open source"); |
| 736 | assert!(session.cut_at(1.0), "cut at 1 s"); |
| 737 | assert!(session.lift_clip(Lane::A1, 0), "lift the first second"); |
| 738 | session.pause(); |
| 739 | let out = out_path("leading_gap"); |
| 740 | let handle = session.export_to(&out); |
| 741 | wait(&handle, Duration::from_secs(180)).expect("export"); |
| 742 | |
| 743 | let (_, chunks) = engine::AudioSession::open(&out) |
| 744 | .expect("reopen export audio") |
| 745 | .expect("export has an audio track"); |
| 746 | let mut pcm: Vec<f32> = Vec::new(); |
| 747 | while let Ok(chunk) = chunks.recv_timeout(Duration::from_secs(10)) { |
| 748 | pcm.resize(chunk.start_sample as usize * 2, 0.0); |
| 749 | pcm.extend_from_slice(&chunk.samples); |
| 750 | } |
| 751 | |
| 752 | |
| 753 | |
| 754 | let block = 1024 * 2; |
| 755 | let peak = |b: &[f32]| b.iter().fold(0.0f32, |m, s| m.max(s.abs())); |
| 756 | let loud = peak(&pcm) / 4.0; |
| 757 | let onset = pcm |
| 758 | .chunks(block) |
| 759 | .position(|b| peak(b) > loud) |
| 760 | .expect("the export has no sound at all") as f64 |
| 761 | * 1024.0; |
| 762 | println!("leading gap: sound starts at sample {onset} of an expected 44100"); |
| 763 | assert!( |
| 764 | (onset - 44_100.0).abs() <= 1024.0, |
| 765 | "the sound after the gap is at {onset}, not at the 1 s hole's end" |
| 766 | ); |
| 767 | |
| 768 | let quiet = peak(&pcm[..(0.9 * 44_100.0) as usize * 2]); |
| 769 | assert!(quiet < 1e-3, "the lifted second is not silent: {quiet}"); |
| 770 | |
| 771 | std::fs::remove_file(&out).unwrap(); |
| 772 | } |
| 773 | |
| 774 | |
| 775 | |
| 776 | |
| 777 | |
| 778 | |
| 779 | #[test] |
| 780 | fn exports_a_gapped_timeline_as_black_and_silence() { |
| 781 | pin_software(); |
| 782 | let source = asset("test_av.mp4"); |
| 783 | let mut session = PlaybackSession::open(&source).expect("open source"); |
| 784 | assert!(session.cut_at(1.0), "split at 1 s"); |
| 785 | assert!(session.cut_at(2.0), "split at 2 s"); |
| 786 | |
| 787 | |
| 788 | assert!(session.lift_clip(Lane::V1, 1)); |
| 789 | assert!(session.lift_clip(Lane::A1, 1)); |
| 790 | session.pause(); |
| 791 | let timeline = session.timeline_duration(); |
| 792 | let frames = (timeline * FPS).round() as u32; |
| 793 | let out = out_path("gapped"); |
| 794 | |
| 795 | let handle = session.export_to(&out); |
| 796 | wait(&handle, Duration::from_secs(180)).expect("export"); |
| 797 | |
| 798 | |
| 799 | let (video, _) = engine::demux::Demuxer::open(&out).unwrap(); |
| 800 | assert_eq!( |
| 801 | video.frame_count, frames, |
| 802 | "a gap is encoded, not skipped: {} frames for a {timeline:.3}s timeline", |
| 803 | video.frame_count |
| 804 | ); |
| 805 | let pictures = decode_all(&out); |
| 806 | assert_eq!(pictures.len() as u32, frames); |
| 807 | let (hole, hole_end) = ((1.0 * FPS) as usize, (2.0 * FPS) as usize); |
| 808 | |
| 809 | |
| 810 | let black = [0u8, 0, 0, 255].repeat(pictures[0].len() / 4); |
| 811 | for (i, picture) in pictures.iter().enumerate() { |
| 812 | let diff = mean_abs_diff(picture, &black); |
| 813 | if (hole..hole_end).contains(&i) { |
| 814 | assert!( |
| 815 | diff < 4.0, |
| 816 | "frame {i} of the gap is not black (MAE {diff:.2})" |
| 817 | ); |
| 818 | } |
| 819 | } |
| 820 | let lit = mean_abs_diff(&pictures[0], &black); |
| 821 | assert!(lit > 4.0, "the clips around the gap came out black too"); |
| 822 | |
| 823 | |
| 824 | |
| 825 | |
| 826 | let file = File::open(&out).unwrap(); |
| 827 | let size = file.metadata().unwrap().len(); |
| 828 | let reader = mp4::Mp4Reader::read_header(BufReader::new(file), size).unwrap(); |
| 829 | let count = reader.sample_count(2).expect("audio track"); |
| 830 | let samples = f64::from(count * 1024); |
| 831 | let wanted = timeline * 44_100.0; |
| 832 | println!("gapped export: {count} packets = {samples} samples for {wanted}"); |
| 833 | assert!( |
| 834 | (samples - wanted).abs() < 3.0 * 1024.0, |
| 835 | "audio length {samples} drifted from {wanted} across the gap" |
| 836 | ); |
| 837 | |
| 838 | |
| 839 | let (_, chunks) = engine::AudioSession::open(&out) |
| 840 | .expect("reopen export audio") |
| 841 | .expect("export has an audio track"); |
| 842 | let mut pcm: Vec<f32> = Vec::new(); |
| 843 | while let Ok(chunk) = chunks.recv_timeout(Duration::from_secs(10)) { |
| 844 | pcm.resize(chunk.start_sample as usize * 2, 0.0); |
| 845 | pcm.extend_from_slice(&chunk.samples); |
| 846 | } |
| 847 | let window = |from: f64, to: f64| { |
| 848 | let (a, b) = ((from * 44_100.0) as usize * 2, (to * 44_100.0) as usize * 2); |
| 849 | pcm[a.min(pcm.len())..b.min(pcm.len())] |
| 850 | .iter() |
| 851 | .fold(0.0f32, |m, s| m.max(s.abs())) |
| 852 | }; |
| 853 | |
| 854 | |
| 855 | let quiet = window(1.2, 1.8); |
| 856 | assert!(quiet < 1e-3, "the gap is not silent: {quiet}"); |
| 857 | assert!(window(0.1, 0.9) > 1e-2, "the sound before it went missing"); |
| 858 | assert!(window(2.2, 4.9) > 1e-2, "the sound after it went missing"); |
| 859 | |
| 860 | std::fs::remove_file(&out).unwrap(); |
| 861 | } |