| 1 | |
| 2 | |
| 3 | |
| 4 | |
| 5 | |
| 6 | |
| 7 | |
| 8 | |
| 9 | |
| 10 | |
| 11 | |
| 12 | |
| 13 | |
| 14 | use std::path::{Path, PathBuf}; |
| 15 | use std::sync::mpsc::Receiver; |
| 16 | |
| 17 | use engine::audio::{AudioChunk, AudioSession}; |
| 18 | use engine::edith; |
| 19 | use engine::project::{Lane, LaneKind, Source, Speed}; |
| 20 | use engine::scale::FitPolicy; |
| 21 | use engine::scratch::Scratch; |
| 22 | use engine::voice::{self, NoiseReduction, VoiceFx}; |
| 23 | use engine::{Clip, Project}; |
| 24 | |
| 25 | |
| 26 | const RATES: [(&str, f64); 6] = [ |
| 27 | ("23.976", 24000.0 / 1001.0), |
| 28 | ("25", 25.0), |
| 29 | ("29.97", 30000.0 / 1001.0), |
| 30 | ("30", 30.0), |
| 31 | ("59.94", 60000.0 / 1001.0), |
| 32 | ("60", 60.0), |
| 33 | ]; |
| 34 | |
| 35 | |
| 36 | fn write_clicks(path: &Path, rate: u32, secs: u32) { |
| 37 | let frames = rate * secs; |
| 38 | let period = rate / 50; |
| 39 | let data_len = frames * 2; |
| 40 | let mut out = Vec::with_capacity(44 + data_len as usize); |
| 41 | out.extend_from_slice(b"RIFF"); |
| 42 | out.extend_from_slice(&(36 + data_len).to_le_bytes()); |
| 43 | out.extend_from_slice(b"WAVEfmt "); |
| 44 | out.extend_from_slice(&16u32.to_le_bytes()); |
| 45 | out.extend_from_slice(&1u16.to_le_bytes()); |
| 46 | out.extend_from_slice(&1u16.to_le_bytes()); |
| 47 | out.extend_from_slice(&rate.to_le_bytes()); |
| 48 | out.extend_from_slice(&(rate * 2).to_le_bytes()); |
| 49 | out.extend_from_slice(&2u16.to_le_bytes()); |
| 50 | out.extend_from_slice(&16u16.to_le_bytes()); |
| 51 | out.extend_from_slice(b"data"); |
| 52 | out.extend_from_slice(&data_len.to_le_bytes()); |
| 53 | for n in 0..frames { |
| 54 | let v: i16 = if n % period == 0 { 29_491 } else { 0 }; |
| 55 | out.extend_from_slice(&v.to_le_bytes()); |
| 56 | } |
| 57 | std::fs::write(path, out).expect("write clicks"); |
| 58 | } |
| 59 | |
| 60 | |
| 61 | |
| 62 | #[derive(Clone, Copy, Debug)] |
| 63 | struct Shot { |
| 64 | start: u32, |
| 65 | in_frame: u32, |
| 66 | out_frame: u32, |
| 67 | source: usize, |
| 68 | |
| 69 | speed: u16, |
| 70 | } |
| 71 | |
| 72 | fn clip(shot: Shot) -> Clip { |
| 73 | Clip { |
| 74 | opacity_keys: Vec::new(), |
| 75 | color_keys: Vec::new(), |
| 76 | effects: Vec::new(), |
| 77 | transition_kind: Default::default(), |
| 78 | speed_keys: Vec::new(), |
| 79 | reversed: false, |
| 80 | stabilise: None, deinterlace: Default::default(), mark: Default::default(), |
| 81 | angle: Default::default(), |
| 82 | fade_in: 0, |
| 83 | fade_out: 0, |
| 84 | transition_out: 0, |
| 85 | visualizer: 0, |
| 86 | viz_paint: 0, |
| 87 | gain_db: 0.0, |
| 88 | gain_keys: Vec::new(), |
| 89 | pan: 0, |
| 90 | pitch: 0.0, |
| 91 | transform_keys: Vec::new(), |
| 92 | start: shot.start, |
| 93 | in_frame: shot.in_frame, |
| 94 | out_frame: shot.out_frame, |
| 95 | source: shot.source, |
| 96 | link: None, |
| 97 | eq: None, |
| 98 | color: None, |
| 99 | fit: FitPolicy::default(), |
| 100 | speed: Speed::from_permille(shot.speed), |
| 101 | transform: None, |
| 102 | } |
| 103 | } |
| 104 | |
| 105 | |
| 106 | |
| 107 | fn shots(total: u32, fps: f64, src_secs: f64, sources: usize, max_len: u32, seed: u64) -> Vec<Shot> { |
| 108 | let mut state = seed; |
| 109 | let mut next = move |n: u32| { |
| 110 | state = state |
| 111 | .wrapping_mul(6_364_136_223_846_793_005) |
| 112 | .wrapping_add(1_442_695_040_888_963_407); |
| 113 | ((state >> 33) % u64::from(n)) as u32 |
| 114 | }; |
| 115 | let src_frames = (src_secs * fps) as u32; |
| 116 | let mut out = Vec::new(); |
| 117 | let mut at = 0; |
| 118 | while at < total { |
| 119 | let len = (1 + next(max_len)).min(total - at); |
| 120 | let in_frame = next(src_frames - len); |
| 121 | out.push(Shot { |
| 122 | start: at, |
| 123 | in_frame, |
| 124 | out_frame: in_frame + len, |
| 125 | source: next(sources as u32) as usize, |
| 126 | speed: 1000, |
| 127 | }); |
| 128 | at += len; |
| 129 | } |
| 130 | out |
| 131 | } |
| 132 | |
| 133 | |
| 134 | |
| 135 | struct Heard { |
| 136 | rate: u32, |
| 137 | clicks: Vec<f64>, |
| 138 | samples: u64, |
| 139 | } |
| 140 | |
| 141 | |
| 142 | |
| 143 | fn hear(rx: Receiver<AudioChunk>, channels: usize, rate: u32) -> Heard { |
| 144 | let mut clicks = Vec::new(); |
| 145 | let mut run: Option<(u64, f32)> = None; |
| 146 | let mut base = None; |
| 147 | let mut samples = 0; |
| 148 | for chunk in rx { |
| 149 | let base = *base.get_or_insert(chunk.start_sample); |
| 150 | for (i, frame) in chunk.samples.chunks(channels).enumerate() { |
| 151 | let n = chunk.start_sample - base + i as u64; |
| 152 | samples = n + 1; |
| 153 | let v = frame[0].abs(); |
| 154 | match (run, v > 0.3) { |
| 155 | (None, true) => run = Some((n, v)), |
| 156 | (Some((_, best)), true) if v > best => run = Some((n, v)), |
| 157 | (Some((at, _)), false) => { |
| 158 | clicks.push(at as f64); |
| 159 | run = None; |
| 160 | } |
| 161 | _ => {} |
| 162 | } |
| 163 | } |
| 164 | } |
| 165 | Heard { |
| 166 | rate, |
| 167 | clicks, |
| 168 | samples, |
| 169 | } |
| 170 | } |
| 171 | |
| 172 | |
| 173 | |
| 174 | fn expected(shots: &[Shot], fps: f64, src_rates: &[u32], out_rate: u32) -> Vec<f64> { |
| 175 | let mut out = Vec::new(); |
| 176 | for s in shots.iter().filter(|s| s.speed == 1000) { |
| 177 | let src_rate = src_rates[s.source]; |
| 178 | let period = u64::from(src_rate / 50); |
| 179 | |
| 180 | |
| 181 | let at = |frame: u32| (f64::from(frame) / fps * f64::from(src_rate) - 1e-6).ceil() as u64; |
| 182 | let (lo, hi) = (at(s.in_frame), at(s.out_frame)); |
| 183 | let mut k = lo.div_ceil(period) * period; |
| 184 | while k < hi { |
| 185 | let secs = f64::from(s.start) / fps |
| 186 | + (k as f64 / f64::from(src_rate) - f64::from(s.in_frame) / fps); |
| 187 | out.push(secs * f64::from(out_rate)); |
| 188 | k += period; |
| 189 | } |
| 190 | } |
| 191 | out |
| 192 | } |
| 193 | |
| 194 | |
| 195 | fn project_for(sources: &[PathBuf], shots: &[Shot]) -> Project { |
| 196 | Project::from_parts( |
| 197 | sources |
| 198 | .iter() |
| 199 | .map(|p| Source::new(p.clone(), 0)) |
| 200 | .collect(), |
| 201 | vec![(LaneKind::Audio, shots.iter().map(|&s| clip(s)).collect())], |
| 202 | Vec::new(), |
| 203 | Vec::new(), |
| 204 | Vec::new(), |
| 205 | ) |
| 206 | .expect("an audio project over its sources") |
| 207 | } |
| 208 | |
| 209 | |
| 210 | fn mix(project: &Project, fps: f64) -> Heard { |
| 211 | let (meta, rx) = AudioSession::open_mixed_streams_master_at_fade( |
| 212 | &project.audio_sources(), |
| 213 | &project.audio_segments_from(0, fps), |
| 214 | &project.audio_eqs_from(0, fps), |
| 215 | &project.audio_speeds_from(0, fps), |
| 216 | &project.audio_fades_from(0, fps), |
| 217 | fps, |
| 218 | &project.audio_gains(), |
| 219 | &project.audio_ducks(), |
| 220 | &project.audio_voices(), |
| 221 | project.limiter(), |
| 222 | None, |
| 223 | ) |
| 224 | .expect("open the timeline's audio") |
| 225 | .expect("the timeline has audio"); |
| 226 | hear(rx, usize::from(meta.channels), meta.sample_rate) |
| 227 | } |
| 228 | |
| 229 | |
| 230 | #[derive(Debug, Default)] |
| 231 | struct Report { |
| 232 | |
| 233 | missing: usize, |
| 234 | |
| 235 | extra: usize, |
| 236 | |
| 237 | worst: f64, |
| 238 | } |
| 239 | |
| 240 | |
| 241 | |
| 242 | |
| 243 | const MATCH: f64 = 4.0; |
| 244 | |
| 245 | fn report(got: &[f64], want: &[f64]) -> Report { |
| 246 | let mut r = Report::default(); |
| 247 | for w in want { |
| 248 | let j = got.partition_point(|g| g < w); |
| 249 | let near = [j.checked_sub(1), Some(j)] |
| 250 | .into_iter() |
| 251 | .flatten() |
| 252 | .filter_map(|k| got.get(k).map(|g| g - w)) |
| 253 | .min_by(|a, b| a.abs().total_cmp(&b.abs())); |
| 254 | match near { |
| 255 | Some(d) if d.abs() <= MATCH => r.worst = r.worst.max(d.abs()), |
| 256 | _ => r.missing += 1, |
| 257 | } |
| 258 | } |
| 259 | r.extra = got |
| 260 | .iter() |
| 261 | .filter(|g| { |
| 262 | let j = want.partition_point(|w| w < *g); |
| 263 | [j.checked_sub(1), Some(j)] |
| 264 | .into_iter() |
| 265 | .flatten() |
| 266 | .filter_map(|k| want.get(k)) |
| 267 | .all(|w| (**g - w).abs() > MATCH) |
| 268 | }) |
| 269 | .count(); |
| 270 | r |
| 271 | } |
| 272 | |
| 273 | |
| 274 | fn measure(label: &str, shots: &[Shot], fps: f64, src_rates: &[u32]) -> Report { |
| 275 | let sources: Vec<Scratch> = src_rates |
| 276 | .iter() |
| 277 | .enumerate() |
| 278 | .map(|(i, &rate)| { |
| 279 | let file = Scratch::file(&format!("av_sync_{label}_{i}"), "wav"); |
| 280 | write_clicks(&file, rate, 30); |
| 281 | file |
| 282 | }) |
| 283 | .collect(); |
| 284 | let paths: Vec<PathBuf> = sources.iter().map(|s| s.to_path_buf()).collect(); |
| 285 | let project = project_for(&paths, shots); |
| 286 | let heard = mix(&project, fps); |
| 287 | let want = expected(shots, fps, src_rates, heard.rate); |
| 288 | let r = report(&heard.clicks, &want); |
| 289 | eprintln!("{label}: {r:?}"); |
| 290 | r |
| 291 | } |
| 292 | |
| 293 | |
| 294 | |
| 295 | fn edge_budget(shots: usize) -> usize { |
| 296 | shots / 500 |
| 297 | } |
| 298 | |
| 299 | |
| 300 | fn hour_at_each_rate(src_rates: &[u32], seed: u64) -> Vec<String> { |
| 301 | let mut failures = Vec::new(); |
| 302 | for (name, fps) in RATES { |
| 303 | let total = (3600.0 * fps).round() as u32; |
| 304 | let shots = shots(total, fps, 30.0, src_rates.len(), 45, seed); |
| 305 | let r = measure(&format!("hour_{name}"), &shots, fps, src_rates); |
| 306 | if r.missing + r.extra > edge_budget(shots.len()) { |
| 307 | failures.push(format!( |
| 308 | "{name}: {} clicks lost and {} invented over {} cuts", |
| 309 | r.missing, |
| 310 | r.extra, |
| 311 | shots.len() |
| 312 | )); |
| 313 | } |
| 314 | if r.worst > 1.0 { |
| 315 | failures.push(format!("{name}: worst click {:.2} samples off", r.worst)); |
| 316 | } |
| 317 | } |
| 318 | failures |
| 319 | } |
| 320 | |
| 321 | #[test] |
| 322 | fn an_hour_of_short_cuts_holds_the_picture_clock_at_every_frame_rate() { |
| 323 | let failures = hour_at_each_rate(&[48_000], 1); |
| 324 | assert!(failures.is_empty(), "48 kHz source: {failures:#?}"); |
| 325 | } |
| 326 | |
| 327 | #[test] |
| 328 | fn the_same_hour_from_a_44_1_khz_source_holds_too() { |
| 329 | let failures = hour_at_each_rate(&[44_100], 2); |
| 330 | assert!(failures.is_empty(), "44.1 kHz source: {failures:#?}"); |
| 331 | } |
| 332 | |
| 333 | #[test] |
| 334 | fn cuts_from_44_1_and_48_khz_sources_mixed_hold_within_resampling_error() { |
| 335 | |
| 336 | |
| 337 | let mut failures = Vec::new(); |
| 338 | for (name, fps) in RATES { |
| 339 | let total = (1200.0 * fps).round() as u32; |
| 340 | let shots = shots(total, fps, 30.0, 2, 45, 3); |
| 341 | let r = measure(&format!("mixed_{name}"), &shots, fps, &[44_100, 48_000]); |
| 342 | if r.worst > 2.0 || r.missing + r.extra > edge_budget(shots.len()) { |
| 343 | failures.push(format!("{name}: worst {:.2}, lost {}, invented {}", r.worst, r.missing, r.extra)); |
| 344 | } |
| 345 | } |
| 346 | assert!(failures.is_empty(), "{failures:#?}"); |
| 347 | } |
| 348 | |
| 349 | #[test] |
| 350 | fn the_voice_chain_keeps_every_click_on_its_sample() { |
| 351 | |
| 352 | |
| 353 | |
| 354 | let mut fx = VoiceFx { |
| 355 | nr: NoiseReduction { on: true, strength: 1.0, floor_db: -18.0, profile: vec![-200.0; voice::PROFILE_BANDS] }, |
| 356 | ..VoiceFx::default() |
| 357 | }; |
| 358 | fx.comp.on = true; |
| 359 | fx.deess.on = true; |
| 360 | let source = Scratch::file("av_sync_voice", "wav"); |
| 361 | write_clicks(&source, 48_000, 30); |
| 362 | let mut failures = Vec::new(); |
| 363 | for (name, fps) in RATES { |
| 364 | let total = (120.0 * fps).round() as u32; |
| 365 | let shots = shots(total, fps, 30.0, 1, 45, 4); |
| 366 | let mut project = project_for(&[source.to_path_buf()], &shots); |
| 367 | assert!(project.set_lane_voice(Lane::A1, fx.clone()), "the chain goes on"); |
| 368 | let heard = mix(&project, fps); |
| 369 | let want = (total as f64 * f64::from(heard.rate) / fps).round() as u64; |
| 370 | let r = report(&heard.clicks, &expected(&shots, fps, &[48_000], heard.rate)); |
| 371 | if r.worst > 1.0 || r.missing + r.extra > edge_budget(shots.len()) || heard.samples.abs_diff(want) > 1 { |
| 372 | failures.push(format!("{name}: {r:?}, {} samples of {want}", heard.samples)); |
| 373 | } |
| 374 | } |
| 375 | assert!(failures.is_empty(), "{failures:#?}"); |
| 376 | } |
| 377 | |
| 378 | #[test] |
| 379 | fn the_mix_length_is_the_timeline_length_at_every_speed() { |
| 380 | |
| 381 | |
| 382 | let fps = 30000.0 / 1001.0; |
| 383 | let source = Scratch::file("av_sync_speeds", "wav"); |
| 384 | write_clicks(&source, 48_000, 30); |
| 385 | let mut shots = Vec::new(); |
| 386 | let mut at = 0; |
| 387 | let speeds = [500u16, 1500, 2000, 1000, 750, 1250]; |
| 388 | for (i, &speed) in speeds.iter().cycle().take(60).enumerate() { |
| 389 | let len = 20 + (i as u32 * 7) % 40; |
| 390 | let shot = Shot { |
| 391 | start: at, |
| 392 | in_frame: 0, |
| 393 | out_frame: len, |
| 394 | source: 0, |
| 395 | speed, |
| 396 | }; |
| 397 | at += clip(shot).frames(); |
| 398 | shots.push(shot); |
| 399 | } |
| 400 | |
| 401 | let project = project_for(&[source.to_path_buf()], &shots); |
| 402 | let heard = mix(&project, fps); |
| 403 | let want = (at as f64 * f64::from(heard.rate) / fps).round() as u64; |
| 404 | assert!( |
| 405 | heard.samples.abs_diff(want) <= 1, |
| 406 | "{} samples for {at} timeline frames, want {want}", |
| 407 | heard.samples |
| 408 | ); |
| 409 | } |
| 410 | |
| 411 | #[test] |
| 412 | fn a_saved_and_reloaded_timeline_mixes_exactly_as_before() { |
| 413 | let fps = 59.94_f64; |
| 414 | let total = (600.0 * fps).round() as u32; |
| 415 | let shots = shots(total, fps, 30.0, 1, 45, 4); |
| 416 | let source = Scratch::file("av_sync_reload_src", "wav"); |
| 417 | write_clicks(&source, 44_100, 30); |
| 418 | let project = project_for(&[source.to_path_buf()], &shots); |
| 419 | let before = mix(&project, fps); |
| 420 | |
| 421 | let file = Scratch::file("av_sync_reload", "edith"); |
| 422 | edith::save( |
| 423 | &file, |
| 424 | project.sources(), |
| 425 | &[(LaneKind::Audio, project.lane(Lane::A1).to_vec())], |
| 426 | &[0.0], |
| 427 | &[Vec::new()], |
| 428 | &[], |
| 429 | &[], |
| 430 | &[], |
| 431 | &[], |
| 432 | (1280, 720), |
| 433 | Some(fps), |
| 434 | engine::tonemap::Preset::default(), |
| 435 | false, |
| 436 | false, |
| 437 | engine::export::EncoderSeat::default(), |
| 438 | project.limiter(), |
| 439 | None, |
| 440 | 0, |
| 441 | ) |
| 442 | .expect("the timeline saves"); |
| 443 | let doc = edith::load(&file).expect("the timeline reloads"); |
| 444 | let reloaded = Project::from_parts(doc.sources, doc.lanes, doc.eq, doc.color, doc.transform) |
| 445 | .expect("the reloaded timeline"); |
| 446 | let loaded_fps = doc.fps.expect("the frame rate is saved"); |
| 447 | assert_eq!(loaded_fps, fps, "the saved frame rate reads back exact"); |
| 448 | |
| 449 | let after = mix(&reloaded, loaded_fps); |
| 450 | assert_eq!(after.samples, before.samples, "reload changed the length"); |
| 451 | let r = report(&after.clicks, &before.clicks); |
| 452 | assert_eq!((r.missing, r.extra), (0, 0), "reload moved clicks: {r:?}"); |
| 453 | assert!(r.worst <= 1e-6, "reload moved a click by {} samples", r.worst); |
| 454 | } |
| 455 | |
| 456 | |
| 457 | |
| 458 | |
| 459 | |
| 460 | const FLASH_W: usize = 160; |
| 461 | const FLASH_H: usize = 90; |
| 462 | const FLASH_RATE: (&str, f64) = ("24000/1001", 24000.0 / 1001.0); |
| 463 | const AUDIO_RATE: u32 = 48_000; |
| 464 | |
| 465 | |
| 466 | |
| 467 | fn flash_frames(secs: u32, fps: f64) -> Vec<usize> { |
| 468 | (1..secs) |
| 469 | .map(|k| (f64::from(k) * fps).ceil() as usize) |
| 470 | .collect() |
| 471 | } |
| 472 | |
| 473 | |
| 474 | |
| 475 | fn make_flash_source(dir: &Path, secs: u32) -> PathBuf { |
| 476 | let fps = FLASH_RATE.1; |
| 477 | let frames = (f64::from(secs) * fps).ceil() as usize; |
| 478 | let flashes = flash_frames(secs, fps); |
| 479 | let audio = dir.join("beeps.s16"); |
| 480 | let mut pcm = vec![0i16; secs as usize * AUDIO_RATE as usize]; |
| 481 | for &n in &flashes { |
| 482 | let start = (n as f64 / fps * f64::from(AUDIO_RATE)).round() as usize; |
| 483 | for i in 0..(AUDIO_RATE as usize / 20) { |
| 484 | let t = i as f64 / f64::from(AUDIO_RATE); |
| 485 | let env = (i as f64 / 48.0).min(1.0); |
| 486 | let v = 0.5 * env * (2.0 * std::f64::consts::PI * 1000.0 * t).sin(); |
| 487 | if let Some(slot) = pcm.get_mut(start + i) { |
| 488 | *slot = (v * 32767.0) as i16; |
| 489 | } |
| 490 | } |
| 491 | } |
| 492 | let bytes: Vec<u8> = pcm.iter().flat_map(|s| s.to_le_bytes()).collect(); |
| 493 | std::fs::write(&audio, bytes).expect("write beeps"); |
| 494 | |
| 495 | let out = dir.join("flash.mp4"); |
| 496 | let mut ff = std::process::Command::new("ffmpeg") |
| 497 | .args(["-v", "error", "-y", "-f", "rawvideo", "-pix_fmt", "gray"]) |
| 498 | .args(["-s", &format!("{FLASH_W}x{FLASH_H}"), "-r", FLASH_RATE.0, "-i", "-"]) |
| 499 | .args(["-f", "s16le", "-ar", "48000", "-ac", "1", "-i"]) |
| 500 | .arg(&audio) |
| 501 | .args(["-map", "0:v", "-map", "1:a", "-t", &secs.to_string()]) |
| 502 | .args(["-c:v", "libx264", "-preset", "ultrafast", "-crf", "16", "-pix_fmt", "yuv420p"]) |
| 503 | .args(["-c:a", "aac", "-b:a", "192k"]) |
| 504 | .arg(&out) |
| 505 | .stdin(std::process::Stdio::piped()) |
| 506 | .spawn() |
| 507 | .expect("ffmpeg runs"); |
| 508 | { |
| 509 | let stdin = ff.stdin.as_mut().expect("piped stdin"); |
| 510 | let flash_set: std::collections::HashSet<usize> = flashes.into_iter().collect(); |
| 511 | for n in 0..frames { |
| 512 | let v = if flash_set.contains(&n) { 255u8 } else { 0u8 }; |
| 513 | std::io::Write::write_all(stdin, &vec![v; FLASH_W * FLASH_H]).expect("frame"); |
| 514 | } |
| 515 | } |
| 516 | assert!(ff.wait().expect("ffmpeg ends").success(), "the source encodes"); |
| 517 | out |
| 518 | } |
| 519 | |
| 520 | |
| 521 | fn decode(file: &Path, dir: &Path) -> (Vec<u8>, Vec<f32>) { |
| 522 | let video = dir.join("out.gray"); |
| 523 | let audio = dir.join("out.f32"); |
| 524 | for (args, out) in [ |
| 525 | (vec!["-an", "-f", "rawvideo", "-pix_fmt", "gray"], &video), |
| 526 | (vec!["-vn", "-f", "f32le", "-ac", "1", "-ar", "48000"], &audio), |
| 527 | ] { |
| 528 | let status = std::process::Command::new("ffmpeg") |
| 529 | .args(["-v", "error", "-y", "-i"]) |
| 530 | .arg(file) |
| 531 | .args(args) |
| 532 | .arg(out) |
| 533 | .status() |
| 534 | .expect("ffmpeg runs"); |
| 535 | assert!(status.success(), "ffmpeg decodes the export"); |
| 536 | } |
| 537 | let picture = std::fs::read(&video).expect("decoded picture"); |
| 538 | let sound: Vec<f32> = std::fs::read(&audio) |
| 539 | .expect("decoded sound") |
| 540 | .as_chunks::<4>() |
| 541 | .0 |
| 542 | .iter() |
| 543 | .map(|b| f32::from_le_bytes(*b)) |
| 544 | .collect(); |
| 545 | (picture, sound) |
| 546 | } |
| 547 | |
| 548 | |
| 549 | |
| 550 | fn export_cuts(frames: u32, fps: f64, src_secs: f64, seed: u64) -> Vec<Shot> { |
| 551 | shots(frames, fps, src_secs, 1, 24, seed) |
| 552 | } |
| 553 | |
| 554 | #[test] |
| 555 | fn a_ranged_export_after_many_cuts_keeps_each_flash_on_its_beep() { |
| 556 | if std::process::Command::new("ffmpeg") |
| 557 | .arg("-version") |
| 558 | .output() |
| 559 | .is_err() |
| 560 | { |
| 561 | eprintln!("no ffmpeg CLI: the export read-back is skipped"); |
| 562 | return; |
| 563 | } |
| 564 | let fps = FLASH_RATE.1; |
| 565 | let dir = Scratch::dir("av_sync_export"); |
| 566 | let source = make_flash_source(&dir, 60); |
| 567 | |
| 568 | |
| 569 | |
| 570 | let cuts = export_cuts((120.0 * fps).round() as u32, fps, 60.0, 9); |
| 571 | let video: Vec<Clip> = cuts.iter().map(|&s| clip(s)).collect(); |
| 572 | let audio = video.clone(); |
| 573 | let project_file = dir.join("timeline.edith"); |
| 574 | edith::save( |
| 575 | &project_file, |
| 576 | &[Source::new(source.clone(), 0)], |
| 577 | &[(LaneKind::Video, video), (LaneKind::Audio, audio)], |
| 578 | &[0.0, 0.0], |
| 579 | &[Vec::new(), Vec::new()], |
| 580 | &[], |
| 581 | &[], |
| 582 | &[], |
| 583 | &[], |
| 584 | (FLASH_W as u32, FLASH_H as u32), |
| 585 | Some(fps), |
| 586 | engine::tonemap::Preset::default(), |
| 587 | false, |
| 588 | false, |
| 589 | engine::export::EncoderSeat::Software, |
| 590 | engine::limiter::Limiter::default(), |
| 591 | None, |
| 592 | 0, |
| 593 | ) |
| 594 | .expect("the timeline saves"); |
| 595 | let session = engine::PlaybackSession::open_project(&project_file).expect("the timeline opens"); |
| 596 | |
| 597 | let range = ((40.0 * fps).round() as u32, (55.0 * fps).round() as u32); |
| 598 | let out = dir.join("export.mp4"); |
| 599 | let settings = engine::export::ExportSettings { |
| 600 | format: engine::export::Format::Mp4, |
| 601 | seat: engine::export::EncoderSeat::Software, |
| 602 | range: Some(range), |
| 603 | ..Default::default() |
| 604 | }; |
| 605 | let handle = session.export_to_with(&out, &settings); |
| 606 | let started = std::time::Instant::now(); |
| 607 | while !handle.is_finished() { |
| 608 | assert!(started.elapsed() < std::time::Duration::from_secs(300), "the export hangs"); |
| 609 | std::thread::sleep(std::time::Duration::from_millis(20)); |
| 610 | } |
| 611 | handle.result().expect("an outcome").expect("the export"); |
| 612 | |
| 613 | let (picture, sound) = decode(&out, &dir); |
| 614 | let frame = FLASH_W * FLASH_H; |
| 615 | let flashes: Vec<f64> = (0..picture.len() / frame) |
| 616 | .filter(|&i| { |
| 617 | let mean = picture[i * frame..(i + 1) * frame].iter().map(|&v| u64::from(v)).sum::<u64>() as f64 / frame as f64; |
| 618 | mean > 128.0 |
| 619 | }) |
| 620 | .filter(|&i| i == 0 || { |
| 621 | let prev = &picture[(i - 1) * frame..i * frame]; |
| 622 | let mean = prev.iter().map(|&v| u64::from(v)).sum::<u64>() as f64 / frame as f64; |
| 623 | mean <= 128.0 |
| 624 | }) |
| 625 | .map(|i| i as f64 / fps) |
| 626 | .collect(); |
| 627 | |
| 628 | assert!(flashes.len() >= 10, "only {} flashes in the 15 s export", flashes.len()); |
| 629 | |
| 630 | |
| 631 | |
| 632 | |
| 633 | let mut worst = 0.0f64; |
| 634 | for &t in &flashes { |
| 635 | let from = ((t - 0.02) * f64::from(AUDIO_RATE)).max(0.0) as usize; |
| 636 | let to = (((t + 0.1) * f64::from(AUDIO_RATE)) as usize).min(sound.len()); |
| 637 | let beep = (from..to) |
| 638 | .find(|&i| sound[i].abs() > 0.2) |
| 639 | .map(|i| i as f64 / f64::from(AUDIO_RATE)) |
| 640 | .unwrap_or_else(|| panic!("no beep within 100 ms of the flash at {t:.3} s")); |
| 641 | let offset = (beep - t) * fps; |
| 642 | worst = worst.max(offset.abs()); |
| 643 | assert!(offset.abs() < 1.0, "flash at {t:.3} s is {offset:.2} frames from its beep"); |
| 644 | } |
| 645 | eprintln!( |
| 646 | "export: {} flashes, worst offset {worst:.3} frames", |
| 647 | flashes.len() |
| 648 | ); |
| 649 | } |