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