| 1 | |
| 2 | |
| 3 | |
| 4 | |
| 5 | |
| 6 | |
| 7 | |
| 8 | |
| 9 | |
| 10 | |
| 11 | |
| 12 | |
| 13 | |
| 14 | use std::path::{Path, PathBuf}; |
| 15 | use std::time::{Duration, Instant}; |
| 16 | |
| 17 | use engine::export::{ExportSettings, Format}; |
| 18 | use engine::project::LaneKind; |
| 19 | use engine::project::Source; |
| 20 | use engine::scale::FitPolicy; |
| 21 | use engine::{AudioSession, Clip, ExportHandle, Project}; |
| 22 | |
| 23 | const RATE: u32 = 44_100; |
| 24 | |
| 25 | fn asset(name: &str) -> PathBuf { |
| 26 | PathBuf::from(env!("CARGO_MANIFEST_DIR")) |
| 27 | .join("../../assets") |
| 28 | .join(name) |
| 29 | } |
| 30 | |
| 31 | |
| 32 | |
| 33 | fn out_path(name: &str, ext: &str) -> PathBuf { |
| 34 | let path = std::env::temp_dir().join(format!("ve_audio_{name}_{}.{ext}", std::process::id())); |
| 35 | let _ = std::fs::remove_file(&path); |
| 36 | let _ = std::fs::remove_file(part_path(&path)); |
| 37 | path |
| 38 | } |
| 39 | |
| 40 | fn part_path(out: &Path) -> PathBuf { |
| 41 | PathBuf::from(format!("{}.part", out.display())) |
| 42 | } |
| 43 | |
| 44 | fn wait(handle: &ExportHandle, limit: Duration) -> engine::Result<()> { |
| 45 | let started = Instant::now(); |
| 46 | while !handle.is_finished() { |
| 47 | assert!( |
| 48 | started.elapsed() < limit, |
| 49 | "export did not finish in {limit:?}" |
| 50 | ); |
| 51 | std::thread::sleep(Duration::from_millis(10)); |
| 52 | } |
| 53 | handle.result().expect("a finished export has an outcome") |
| 54 | } |
| 55 | |
| 56 | |
| 57 | |
| 58 | |
| 59 | |
| 60 | |
| 61 | fn mixed_project() -> Project { |
| 62 | let clip = |start, source| Clip { |
| 63 | start, |
| 64 | in_frame: 0, |
| 65 | out_frame: 30, |
| 66 | source, |
| 67 | link: None, |
| 68 | eq: None, |
| 69 | color: None, |
| 70 | fit: FitPolicy::default(), |
| 71 | }; |
| 72 | Project::from_parts( |
| 73 | vec![ |
| 74 | Source::new(asset("test_av.mp4"), 0), |
| 75 | Source::new(asset("test_tone.mp3"), 0), |
| 76 | ], |
| 77 | |
| 78 | |
| 79 | |
| 80 | vec![ |
| 81 | ( |
| 82 | LaneKind::Video, |
| 83 | vec![Clip { |
| 84 | start: 0, |
| 85 | in_frame: 0, |
| 86 | out_frame: 90, |
| 87 | source: 0, |
| 88 | link: None, |
| 89 | eq: None, |
| 90 | color: None, |
| 91 | fit: FitPolicy::default(), |
| 92 | }], |
| 93 | ), |
| 94 | (LaneKind::Audio, vec![clip(0, 0), clip(60, 1)]), |
| 95 | ], |
| 96 | Vec::new(), |
| 97 | Vec::new(), |
| 98 | ) |
| 99 | .expect("a two-source project with a hole in the audio lane") |
| 100 | } |
| 101 | |
| 102 | fn meta() -> engine::VideoMeta { |
| 103 | engine::demux::Demuxer::open(&asset("test_av.mp4")) |
| 104 | .expect("open test_av") |
| 105 | .0 |
| 106 | } |
| 107 | |
| 108 | |
| 109 | |
| 110 | |
| 111 | fn decode(path: &Path) -> (engine::AudioMeta, Vec<f32>) { |
| 112 | let (meta, chunks) = AudioSession::open(path) |
| 113 | .expect("reopen the export") |
| 114 | .expect("the export has audio"); |
| 115 | let mut samples = Vec::new(); |
| 116 | for chunk in chunks { |
| 117 | samples.extend(chunk.samples); |
| 118 | } |
| 119 | (meta, samples) |
| 120 | } |
| 121 | |
| 122 | |
| 123 | fn rms(samples: &[f32], channels: usize, from: f64, to: f64) -> f64 { |
| 124 | let at = |secs: f64| (secs * f64::from(RATE)) as usize * channels; |
| 125 | let window = &samples[at(from).min(samples.len())..at(to).min(samples.len())]; |
| 126 | assert!(!window.is_empty(), "no samples in [{from}, {to})"); |
| 127 | (window |
| 128 | .iter() |
| 129 | .map(|s| f64::from(*s) * f64::from(*s)) |
| 130 | .sum::<f64>() |
| 131 | / window.len() as f64) |
| 132 | .sqrt() |
| 133 | } |
| 134 | |
| 135 | |
| 136 | |
| 137 | |
| 138 | |
| 139 | fn assert_timeline_shape(meta: &engine::AudioMeta, samples: &[f32]) { |
| 140 | assert_eq!((meta.sample_rate, meta.channels), (RATE, 2), "as decoded"); |
| 141 | let channels = usize::from(meta.channels); |
| 142 | |
| 143 | |
| 144 | |
| 145 | let frames = (3.0 * f64::from(RATE)) as usize; |
| 146 | assert_eq!( |
| 147 | samples.len(), |
| 148 | frames * channels, |
| 149 | "timeline length in samples" |
| 150 | ); |
| 151 | |
| 152 | |
| 153 | let av = rms(samples, channels, 0.05, 0.95); |
| 154 | let tone = rms(samples, channels, 2.05, 2.95); |
| 155 | |
| 156 | |
| 157 | let gap = rms(samples, channels, 1.0, 2.0); |
| 158 | println!("rms: av {av:.4} gap {gap:.6} mp3 {tone:.4}"); |
| 159 | assert!(av > 0.01, "the first second is audible"); |
| 160 | assert!(tone > 0.01, "the mp3 second is audible"); |
| 161 | assert_eq!(gap, 0.0, "the gap is exact silence"); |
| 162 | |
| 163 | |
| 164 | |
| 165 | let peak = rms(samples, channels, 0.2, 0.3); |
| 166 | let dip = rms(samples, channels, 0.7, 0.8); |
| 167 | println!( |
| 168 | "pulse: peak {peak:.4} dip {dip:.4} ratio {:.1}", |
| 169 | peak / dip |
| 170 | ); |
| 171 | assert!( |
| 172 | peak > dip * 4.0, |
| 173 | "the 1 Hz pulse survived: peak {peak:.4} vs dip {dip:.4}" |
| 174 | ); |
| 175 | } |
| 176 | |
| 177 | |
| 178 | |
| 179 | |
| 180 | fn assert_wav_header(path: &Path, frames: usize) { |
| 181 | let bytes = std::fs::read(path).expect("read the wav back"); |
| 182 | let u16_at = |i: usize| u16::from_le_bytes([bytes[i], bytes[i + 1]]); |
| 183 | let u32_at = |
| 184 | |i: usize| u32::from_le_bytes([bytes[i], bytes[i + 1], bytes[i + 2], bytes[i + 3]]); |
| 185 | assert_eq!(&bytes[0..4], b"RIFF"); |
| 186 | assert_eq!(&bytes[8..12], b"WAVE"); |
| 187 | assert_eq!(&bytes[12..16], b"fmt "); |
| 188 | assert_eq!(u32_at(4) as usize, bytes.len() - 8, "RIFF size"); |
| 189 | assert_eq!(u16_at(20), 1, "PCM, not a float or a compressed tag"); |
| 190 | assert_eq!(u16_at(22), 2, "stereo"); |
| 191 | assert_eq!(u32_at(24), RATE, "sample rate"); |
| 192 | assert_eq!(u32_at(28), RATE * 2 * 2, "byte rate = rate * channels * 2"); |
| 193 | assert_eq!(u16_at(32), 4, "block align"); |
| 194 | assert_eq!(u16_at(34), 16, "bits per sample"); |
| 195 | |
| 196 | |
| 197 | let data = bytes |
| 198 | .windows(4) |
| 199 | .position(|w| w == b"data") |
| 200 | .expect("a data chunk"); |
| 201 | assert_eq!(u32_at(data + 4) as usize, frames * 2 * 2, "data chunk size"); |
| 202 | } |
| 203 | |
| 204 | #[test] |
| 205 | fn exports_the_timeline_as_a_wav() { |
| 206 | let out = out_path("wav", "wav"); |
| 207 | let handle = engine::export::start( |
| 208 | mixed_project(), |
| 209 | meta(), |
| 210 | &out, |
| 211 | &ExportSettings { |
| 212 | format: Format::Wav, |
| 213 | ..Default::default() |
| 214 | }, |
| 215 | ); |
| 216 | wait(&handle, Duration::from_secs(60)).expect("wav export"); |
| 217 | assert_eq!(handle.progress(), 1.0, "finished at full progress"); |
| 218 | assert!(!part_path(&out).exists(), "the .part was renamed away"); |
| 219 | |
| 220 | let (meta, samples) = decode(&out); |
| 221 | assert_timeline_shape(&meta, &samples); |
| 222 | assert_wav_header(&out, samples.len() / usize::from(meta.channels)); |
| 223 | std::fs::remove_file(&out).unwrap(); |
| 224 | } |
| 225 | |
| 226 | #[test] |
| 227 | fn exports_the_timeline_as_a_flac() { |
| 228 | let out = out_path("flac", "flac"); |
| 229 | let handle = engine::export::start( |
| 230 | mixed_project(), |
| 231 | meta(), |
| 232 | &out, |
| 233 | &ExportSettings { |
| 234 | format: Format::Flac, |
| 235 | ..Default::default() |
| 236 | }, |
| 237 | ); |
| 238 | wait(&handle, Duration::from_secs(60)).expect("flac export"); |
| 239 | assert_eq!(handle.progress(), 1.0, "finished at full progress"); |
| 240 | |
| 241 | let bytes = std::fs::read(&out).expect("read the flac back"); |
| 242 | assert_eq!(&bytes[0..4], b"fLaC", "a FLAC stream, by its own magic"); |
| 243 | |
| 244 | |
| 245 | let (meta, samples) = decode(&out); |
| 246 | assert_timeline_shape(&meta, &samples); |
| 247 | |
| 248 | let pcm = samples.len() * 2; |
| 249 | println!("flac {} bytes for {pcm} bytes of PCM", bytes.len()); |
| 250 | assert!(bytes.len() < pcm, "compressed"); |
| 251 | std::fs::remove_file(&out).unwrap(); |
| 252 | } |
| 253 | |
| 254 | |
| 255 | |
| 256 | |
| 257 | #[test] |
| 258 | fn a_cancelled_audio_export_leaves_no_file() { |
| 259 | let source = asset("test_av.mp4"); |
| 260 | let (meta, _) = engine::demux::Demuxer::open(&source).expect("open test_av"); |
| 261 | let mut project = Project::single(&source, meta.frame_count); |
| 262 | for _ in 0..11 { |
| 263 | assert!(project.append_clip(0, meta.frame_count), "a minute of it"); |
| 264 | } |
| 265 | let out = out_path("cancel", "wav"); |
| 266 | let handle = engine::export::start( |
| 267 | project, |
| 268 | meta, |
| 269 | &out, |
| 270 | &ExportSettings { |
| 271 | format: Format::Wav, |
| 272 | ..Default::default() |
| 273 | }, |
| 274 | ); |
| 275 | handle.cancel(); |
| 276 | let outcome = wait(&handle, Duration::from_secs(120)); |
| 277 | let text = outcome.expect_err("a cancelled export fails").to_string(); |
| 278 | assert!(text.contains("cancelled"), "{text}"); |
| 279 | assert!(!out.exists(), "no output file"); |
| 280 | assert!(!part_path(&out).exists(), "no half-written .part either"); |
| 281 | } |
| 282 | |
| 283 | |
| 284 | |
| 285 | #[test] |
| 286 | fn a_silent_timeline_refuses_an_audio_export() { |
| 287 | let source = asset("test_mismatch.mp4"); |
| 288 | let (meta, _) = engine::demux::Demuxer::open(&source).expect("open the fixture"); |
| 289 | let out = out_path("silent", "wav"); |
| 290 | let handle = engine::export::start( |
| 291 | Project::single(&source, meta.frame_count), |
| 292 | meta, |
| 293 | &out, |
| 294 | &ExportSettings { |
| 295 | format: Format::Wav, |
| 296 | ..Default::default() |
| 297 | }, |
| 298 | ); |
| 299 | let text = wait(&handle, Duration::from_secs(60)) |
| 300 | .expect_err("no audio to export") |
| 301 | .to_string(); |
| 302 | assert!(text.contains("no audio"), "{text}"); |
| 303 | assert!( |
| 304 | !out.exists() && !part_path(&out).exists(), |
| 305 | "nothing written" |
| 306 | ); |
| 307 | } |
| 308 | |
| 309 | |
| 310 | |
| 311 | |
| 312 | #[test] |
| 313 | fn a_51_ac3_source_round_trips_through_a_wav() { |
| 314 | let source = asset("test_ac3_51.mp4"); |
| 315 | let project = Project::from_parts( |
| 316 | vec![Source::new(source.clone(), 0)], |
| 317 | vec![( |
| 318 | LaneKind::Audio, |
| 319 | vec![Clip { |
| 320 | start: 0, |
| 321 | in_frame: 0, |
| 322 | out_frame: 30, |
| 323 | source: 0, |
| 324 | link: None, |
| 325 | eq: None, |
| 326 | color: None, |
| 327 | fit: FitPolicy::default(), |
| 328 | }], |
| 329 | )], |
| 330 | Vec::new(), |
| 331 | Vec::new(), |
| 332 | ) |
| 333 | .expect("a one-source AC-3 project"); |
| 334 | let video = engine::demux::Demuxer::open(&source).expect("open the fixture").0; |
| 335 | |
| 336 | let out = out_path("ac3", "wav"); |
| 337 | let handle = engine::export::start( |
| 338 | project, |
| 339 | video, |
| 340 | &out, |
| 341 | &ExportSettings { |
| 342 | format: Format::Wav, |
| 343 | ..Default::default() |
| 344 | }, |
| 345 | ); |
| 346 | wait(&handle, Duration::from_secs(60)).expect("wav export of an AC-3 source"); |
| 347 | |
| 348 | let (meta, samples) = decode(&out); |
| 349 | assert_eq!( |
| 350 | (meta.sample_rate, meta.channels), |
| 351 | (48_000, 2), |
| 352 | "the §7.8 downmix is what reaches the file" |
| 353 | ); |
| 354 | let secs = (samples.len() / 2) as f64 / 48_000.; |
| 355 | assert!((0.9..1.1).contains(&secs), "one second of clip, got {secs:.3}s"); |
| 356 | let energy = (samples.iter().map(|s| f64::from(*s) * f64::from(*s)).sum::<f64>() |
| 357 | / samples.len() as f64) |
| 358 | .sqrt(); |
| 359 | assert!(energy > 0.005, "the exported AC-3 is silence: RMS {energy:.6}"); |
| 360 | std::fs::remove_file(&out).unwrap(); |
| 361 | } |