| 1 | |
| 2 | |
| 3 | |
| 4 | |
| 5 | |
| 6 | |
| 7 | |
| 8 | |
| 9 | |
| 10 | |
| 11 | |
| 12 | |
| 13 | use std::path::{Path, PathBuf}; |
| 14 | use std::process::Command; |
| 15 | use std::sync::Mutex; |
| 16 | use std::time::{Duration, Instant}; |
| 17 | |
| 18 | use ec_core::frame::Frame as CoreFrame; |
| 19 | use ec_core::registry::{CodecId, CodecParameters, Decoder as _}; |
| 20 | use ec_core::{Packet, TimeBase, VideoFrame}; |
| 21 | use ec_h264::H264Decoder; |
| 22 | use engine::audio::AudioSession; |
| 23 | use engine::decode::DecodeSession; |
| 24 | use engine::demux::Demuxer; |
| 25 | use engine::export::{ExportSettings, Format}; |
| 26 | use engine::PlaybackSession; |
| 27 | |
| 28 | static SW: Mutex<()> = Mutex::new(()); |
| 29 | |
| 30 | fn software<T>(f: impl FnOnce() -> T) -> T { |
| 31 | let _guard = SW.lock().unwrap_or_else(|poisoned| poisoned.into_inner()); |
| 32 | engine::envcfg::set("VE_SW", "1"); |
| 33 | let out = f(); |
| 34 | engine::envcfg::unset("VE_SW"); |
| 35 | out |
| 36 | } |
| 37 | |
| 38 | fn have(encoders: &[&str]) -> bool { |
| 39 | let tool = |t: &str| Command::new(t).arg("-version").output().is_ok_and(|o| o.status.success()); |
| 40 | if !tool("ffmpeg") || !tool("ffprobe") { |
| 41 | eprintln!("no ffmpeg: skipping"); |
| 42 | return false; |
| 43 | } |
| 44 | let list = Command::new("ffmpeg") |
| 45 | .args(["-hide_banner", "-encoders"]) |
| 46 | .output() |
| 47 | .map(|o| String::from_utf8_lossy(&o.stdout).into_owned()) |
| 48 | .unwrap_or_default(); |
| 49 | for e in encoders { |
| 50 | if !list.split_whitespace().any(|w| w == *e) { |
| 51 | eprintln!("ffmpeg has no {e} encoder: skipping"); |
| 52 | return false; |
| 53 | } |
| 54 | } |
| 55 | true |
| 56 | } |
| 57 | |
| 58 | fn scratch(name: &str) -> PathBuf { |
| 59 | let dir = std::env::temp_dir().join(format!("edith-mpegts-{name}-{}", std::process::id())); |
| 60 | let _ = std::fs::remove_dir_all(&dir); |
| 61 | std::fs::create_dir_all(&dir).expect("scratch directory"); |
| 62 | dir |
| 63 | } |
| 64 | |
| 65 | fn ffmpeg(args: &[&str]) { |
| 66 | let out = Command::new("ffmpeg").args(["-v", "error", "-y"]).args(args).output().expect("run ffmpeg"); |
| 67 | assert!(out.status.success(), "ffmpeg {args:?}: {}", String::from_utf8_lossy(&out.stderr)); |
| 68 | } |
| 69 | |
| 70 | fn s(p: &Path) -> &str { |
| 71 | p.to_str().unwrap() |
| 72 | } |
| 73 | |
| 74 | const FPS: f64 = 25.0; |
| 75 | |
| 76 | const CARD: &str = "testsrc2=size=352x288:rate=25:duration=2"; |
| 77 | |
| 78 | const CHIRP: &str = "aevalsrc=exprs='0.5*sin(2*PI*(300+200*t)*t)|0.5*sin(2*PI*(310+200*t)*t)':s=48000:d=2"; |
| 79 | |
| 80 | const FLASH: &str = "color=c=black:s=352x288:r=25:d=2.4,drawbox=x=0:y=0:w=352:h=288:color=white:t=fill:enable='between(t,1,1.2)'"; |
| 81 | |
| 82 | const BEEP: &str = "aevalsrc=exprs='0.8*sin(2*PI*1000*t)*between(t,1,1.2)|0.8*sin(2*PI*1000*t)*between(t,1,1.2)':s=48000:d=2.4"; |
| 83 | |
| 84 | fn ffprobe(path: &Path, entries: &str, select: &str) -> String { |
| 85 | let out = Command::new("ffprobe") |
| 86 | .args(["-v", "error", "-select_streams", select, "-show_entries", entries, "-of", "csv=p=0"]) |
| 87 | .arg(path) |
| 88 | .output() |
| 89 | .expect("ffprobe runs"); |
| 90 | assert!(out.status.success(), "ffprobe reads {}", path.display()); |
| 91 | String::from_utf8_lossy(&out.stdout).trim().to_owned() |
| 92 | } |
| 93 | |
| 94 | fn start_time(path: &Path, select: &str) -> f64 { |
| 95 | ffprobe(path, "stream=start_time", select).lines().next().unwrap().trim_end_matches(',').parse().expect("a start time") |
| 96 | } |
| 97 | |
| 98 | |
| 99 | fn session_frames(path: &Path) -> Vec<engine::decode::Frame> { |
| 100 | software(|| DecodeSession::open(path).expect("open").1.into_iter().collect()) |
| 101 | } |
| 102 | |
| 103 | |
| 104 | fn h264_planes(clip: &Path) -> Vec<u8> { |
| 105 | let (_, mut demuxer) = Demuxer::open(clip).expect("open"); |
| 106 | demuxer.seek_to_sync_at_or_before(0); |
| 107 | let mut decoder = H264Decoder::new(CodecParameters::new(CodecId::H264)).expect("decoder"); |
| 108 | let mut out = Vec::new(); |
| 109 | let take = |decoder: &mut H264Decoder, out: &mut Vec<u8>| { |
| 110 | while let Ok(frame) = decoder.receive_frame() { |
| 111 | if let CoreFrame::Video(VideoFrame { planes, .. }) = frame { |
| 112 | for p in planes { |
| 113 | out.extend_from_slice(&p.data); |
| 114 | } |
| 115 | } |
| 116 | } |
| 117 | }; |
| 118 | while let Some(au) = demuxer.next_access_unit().expect("demux") { |
| 119 | decoder.send_packet(&Packet::new(0, TimeBase::new(1, 1), au)).expect("decode"); |
| 120 | take(&mut decoder, &mut out); |
| 121 | } |
| 122 | decoder.flush().expect("flush"); |
| 123 | take(&mut decoder, &mut out); |
| 124 | out |
| 125 | } |
| 126 | |
| 127 | fn ffmpeg_raw(path: &Path) -> Vec<u8> { |
| 128 | let out = Command::new("ffmpeg") |
| 129 | .args(["-v", "error", "-i"]) |
| 130 | .arg(path) |
| 131 | .args(["-an", "-fps_mode", "passthrough", "-f", "rawvideo", "-pix_fmt", "yuv420p", "-"]) |
| 132 | .output() |
| 133 | .expect("ffmpeg runs"); |
| 134 | assert!(out.status.success(), "ffmpeg: {}", String::from_utf8_lossy(&out.stderr)); |
| 135 | out.stdout |
| 136 | } |
| 137 | |
| 138 | |
| 139 | fn sound(path: &Path, stream: usize, from: f64, frames: usize) -> (u32, usize, Vec<f32>) { |
| 140 | let (meta, rx) = AudioSession::open_multi_streams(&[(path.to_path_buf(), stream)], &[(Some(0), from, f64::INFINITY)]) |
| 141 | .expect("open") |
| 142 | .expect("the file has sound"); |
| 143 | let width = usize::from(meta.channels); |
| 144 | let mut out = Vec::new(); |
| 145 | for chunk in rx { |
| 146 | out.extend_from_slice(&chunk.samples); |
| 147 | if out.len() >= frames * width { |
| 148 | break; |
| 149 | } |
| 150 | } |
| 151 | out.truncate(frames * width); |
| 152 | (meta.sample_rate, width, out) |
| 153 | } |
| 154 | |
| 155 | |
| 156 | fn ffmpeg_sound(path: &Path, index: usize, rate: u32) -> Vec<f32> { |
| 157 | let out = Command::new("ffmpeg") |
| 158 | .args(["-v", "error", "-i"]) |
| 159 | .arg(path) |
| 160 | .args(["-map", &format!("0:a:{index}"), "-vn", "-ac", "2", "-ar", &rate.to_string(), "-f", "f32le", "-"]) |
| 161 | .output() |
| 162 | .expect("ffmpeg runs"); |
| 163 | assert!(out.status.success(), "ffmpeg: {}", String::from_utf8_lossy(&out.stderr)); |
| 164 | out.stdout.as_chunks::<4>().0.iter().map(|b| f32::from_le_bytes(*b)).collect() |
| 165 | } |
| 166 | |
| 167 | |
| 168 | |
| 169 | |
| 170 | fn compare(path: &Path, stream: usize, from: f64, frames: usize, reference: &[f32], offset: i64) -> f32 { |
| 171 | let (rate, width, ours) = sound(path, stream, from, frames); |
| 172 | assert_eq!(width, 2); |
| 173 | let first = (from * f64::from(rate)).round() as i64; |
| 174 | let mut worst = 0f32; |
| 175 | let mut compared = 0; |
| 176 | for frame in 0..ours.len() / 2 { |
| 177 | let at = first + frame as i64 - offset; |
| 178 | |
| 179 | if at < 2048 { |
| 180 | continue; |
| 181 | } |
| 182 | let Some(want) = reference.get(at as usize * 2..at as usize * 2 + 2) else { break }; |
| 183 | worst = worst.max((ours[frame * 2] - want[0]).abs()).max((ours[frame * 2 + 1] - want[1]).abs()); |
| 184 | compared += 1; |
| 185 | } |
| 186 | assert!(compared > frames / 2, "compared {compared} of {frames} frames"); |
| 187 | worst |
| 188 | } |
| 189 | |
| 190 | fn sound_offset(path: &Path, index: usize, rate: u32) -> i64 { |
| 191 | let (v, a) = (start_time(path, "v:0"), start_time(path, &format!("a:{index}"))); |
| 192 | ((a - v) * f64::from(rate)).round() as i64 |
| 193 | } |
| 194 | |
| 195 | |
| 196 | fn first_loud(samples: &[f32], width: usize) -> Option<usize> { |
| 197 | samples.chunks(width).position(|f| f.iter().any(|s| s.abs() > 0.2)) |
| 198 | } |
| 199 | |
| 200 | fn flash_frame(frames: &[engine::decode::Frame]) -> Option<u32> { |
| 201 | frames |
| 202 | .iter() |
| 203 | .find(|f| f.bgra.chunks(4).map(|p| u64::from(p[1])).sum::<u64>() > 128 * (f.bgra.len() as u64 / 4)) |
| 204 | .map(|f| f.index) |
| 205 | } |
| 206 | |
| 207 | |
| 208 | fn export_as(source: &Path, out: &Path, format: Format) { |
| 209 | let session = PlaybackSession::open(source).unwrap_or_else(|e| panic!("open {}: {e}", source.display())); |
| 210 | let settings = ExportSettings { format, ..Default::default() }; |
| 211 | let handle = session.export_to_with(out, &settings); |
| 212 | let started = Instant::now(); |
| 213 | while !handle.is_finished() { |
| 214 | assert!(started.elapsed() < Duration::from_secs(600), "the export did not finish in 600 s"); |
| 215 | std::thread::sleep(Duration::from_millis(20)); |
| 216 | } |
| 217 | handle.result().expect("an outcome").expect("the export"); |
| 218 | } |
| 219 | |
| 220 | |
| 221 | |
| 222 | fn mpeg2_planes(clip: &Path) -> Vec<u8> { |
| 223 | let (_, mut demuxer) = Demuxer::open(clip).expect("open"); |
| 224 | demuxer.seek_to_sync_at_or_before(0); |
| 225 | let mut decoder = ec_mpeg2::Mpeg2Decoder::new(CodecParameters::new(CodecId::Mpeg2Video)).expect("decoder"); |
| 226 | let mut out = Vec::new(); |
| 227 | let take = |decoder: &mut ec_mpeg2::Mpeg2Decoder, out: &mut Vec<u8>| { |
| 228 | while let Ok(frame) = decoder.receive_frame() { |
| 229 | if let CoreFrame::Video(VideoFrame { planes, .. }) = frame { |
| 230 | for p in planes { |
| 231 | out.extend_from_slice(&p.data); |
| 232 | } |
| 233 | } |
| 234 | } |
| 235 | }; |
| 236 | while let Some(au) = demuxer.next_access_unit().expect("demux") { |
| 237 | decoder.send_packet(&Packet::new(0, TimeBase::new(1, 1), au)).expect("decode"); |
| 238 | take(&mut decoder, &mut out); |
| 239 | } |
| 240 | decoder.flush().expect("flush"); |
| 241 | take(&mut decoder, &mut out); |
| 242 | out |
| 243 | } |
| 244 | |
| 245 | fn ffmpeg_raw_as(path: &Path, pix_fmt: &str) -> Vec<u8> { |
| 246 | let out = Command::new("ffmpeg") |
| 247 | .args(["-v", "error", "-i"]) |
| 248 | .arg(path) |
| 249 | .args(["-an", "-fps_mode", "passthrough", "-f", "rawvideo", "-pix_fmt", pix_fmt, "-"]) |
| 250 | .output() |
| 251 | .expect("ffmpeg runs"); |
| 252 | assert!(out.status.success(), "ffmpeg: {}", String::from_utf8_lossy(&out.stderr)); |
| 253 | out.stdout |
| 254 | } |
| 255 | |
| 256 | |
| 257 | const DVD_CARD: &str = "testsrc2=size=720x576:rate=25:duration=2"; |
| 258 | const DVD_TFF: &str = "testsrc2=size=720x576:rate=50:duration=2,interlace=scan=tff"; |
| 259 | const DVD_BFF: &str = "testsrc2=size=720x576:rate=50:duration=2,interlace=scan=bff"; |
| 260 | const DVD_FLASH: &str = "color=c=black:s=720x576:r=25:d=2.4,drawbox=x=0:y=0:w=720:h=576:color=white:t=fill:enable='between(t,1,1.2)'"; |
| 261 | |
| 262 | |
| 263 | const MPEG1: &[&str] = &["-c:v", "mpeg1video", "-b:v", "2M", "-g", "10", "-bf", "2", "-pix_fmt", "yuv420p"]; |
| 264 | |
| 265 | const MPEG2: &[&str] = &["-c:v", "mpeg2video", "-b:v", "4M", "-g", "10", "-bf", "2", "-pix_fmt", "yuv420p"]; |
| 266 | |
| 267 | const DVD_V_TFF: &[&str] = &["-c:v", "mpeg2video", "-b:v", "6M", "-g", "12", "-bf", "2", "-pix_fmt", "yuv420p", "-flags", "+ildct+ilme"]; |
| 268 | const DVD_V_BFF: &[&str] = &["-c:v", "mpeg2video", "-b:v", "6M", "-g", "12", "-bf", "2", "-pix_fmt", "yuv420p", "-flags", "+ildct+ilme"]; |
| 269 | const DVD_V: &[&str] = &["-c:v", "mpeg2video", "-b:v", "6M", "-g", "12", "-bf", "2", "-pix_fmt", "yuv420p"]; |
| 270 | const X264: &[&str] = &["-c:v", "libx264", "-x264-params", "keyint=10:min-keyint=10:bframes=2", "-pix_fmt", "yuv420p", "-strict", "-2"]; |
| 271 | const MP2: &[&str] = &["-c:a", "mp2", "-b:a", "192k"]; |
| 272 | const MP3: &[&str] = &["-c:a", "libmp3lame", "-b:a", "128k"]; |
| 273 | const AC3: &[&str] = &["-c:a", "ac3", "-b:a", "192k"]; |
| 274 | const LPCM16: &[&str] = &["-c:a", "pcm_dvd", "-sample_fmt:a", "s16", "-ar:a", "48000"]; |
| 275 | const LPCM24: &[&str] = &["-c:a", "pcm_dvd", "-sample_fmt:a", "s32", "-ar:a", "48000"]; |
| 276 | |
| 277 | |
| 278 | struct Clip<'a> { |
| 279 | name: &'a str, |
| 280 | video: &'a str, |
| 281 | audio: &'a [(&'a str, &'a [&'a str])], |
| 282 | vcodec: &'a [&'a str], |
| 283 | |
| 284 | |
| 285 | fmt: &'a str, |
| 286 | |
| 287 | offset: f64, |
| 288 | } |
| 289 | |
| 290 | fn clip<'a>(name: &'a str, video: &'a str, audio: &'a [(&'a str, &'a [&'a str])], vcodec: &'a [&'a str], fmt: &'a str) -> Clip<'a> { |
| 291 | Clip { name, video, audio, vcodec, fmt, offset: 0.0 } |
| 292 | } |
| 293 | |
| 294 | |
| 295 | fn try_make(dir: &Path, clip: &Clip) -> Option<PathBuf> { |
| 296 | let out = dir.join(clip.name); |
| 297 | let mut args: Vec<String> = vec!["-v".into(), "error".into(), "-y".into(), "-f".into(), "lavfi".into(), "-i".into(), clip.video.into()]; |
| 298 | for (src, _) in clip.audio { |
| 299 | args.extend(["-f".into(), "lavfi".into(), "-i".into(), (*src).into()]); |
| 300 | } |
| 301 | args.extend(["-map".into(), "0:v".into()]); |
| 302 | args.extend(clip.vcodec.iter().map(|a| (*a).to_string())); |
| 303 | for (i, (_, codec)) in clip.audio.iter().enumerate() { |
| 304 | args.extend(["-map".into(), format!("{}:a", i + 1)]); |
| 305 | let n = i.to_string(); |
| 306 | for pair in codec.chunks(2) { |
| 307 | args.push(format!("{}:{n}", pair[0])); |
| 308 | args.push(pair[1].to_string()); |
| 309 | } |
| 310 | } |
| 311 | args.extend(["-f".into(), clip.fmt.into()]); |
| 312 | if clip.offset != 0.0 { |
| 313 | args.extend(["-output_ts_offset".into(), clip.offset.to_string()]); |
| 314 | } |
| 315 | args.push(out.to_str().unwrap().into()); |
| 316 | let made = Command::new("ffmpeg").args(&args).output().expect("run ffmpeg"); |
| 317 | if !made.status.success() || !out.exists() { |
| 318 | eprintln!("{}: ffmpeg cannot mux this here ({}): skipping", clip.name, String::from_utf8_lossy(&made.stderr).lines().last().unwrap_or("")); |
| 319 | return None; |
| 320 | } |
| 321 | Some(out) |
| 322 | } |
| 323 | |
| 324 | fn make(dir: &Path, clip: &Clip) -> PathBuf { |
| 325 | try_make(dir, clip).unwrap_or_else(|| panic!("ffmpeg could not mux {}", clip.name)) |
| 326 | } |
| 327 | |
| 328 | |
| 329 | |
| 330 | |
| 331 | fn shapes() -> Vec<(Clip<'static>, Option<&'static str>, u32, u32)> { |
| 332 | let mut v = vec![ |
| 333 | (clip("a.mpg", CARD, &[(CHIRP, MP2)], MPEG1, "mpeg"), None, 352, 288), |
| 334 | (clip("b.vob", CARD, &[(CHIRP, AC3)], MPEG2, "vob"), None, 352, 288), |
| 335 | (clip("c.mpeg", CARD, &[(CHIRP, MP2)], MPEG2, "vob"), None, 352, 288), |
| 336 | (clip("d.m2v", CARD, &[], MPEG2, "mpeg2video"), None, 352, 288), |
| 337 | (clip("e.m1v", CARD, &[], MPEG1, "mpeg1video"), None, 352, 288), |
| 338 | (clip("f.vob", DVD_TFF, &[(CHIRP, AC3)], DVD_V_TFF, "dvd"), Some("tff"), 720, 576), |
| 339 | (clip("g.vob", DVD_BFF, &[(CHIRP, MP2)], DVD_V_BFF, "dvd"), Some("bff"), 720, 576), |
| 340 | (clip("h.vob", DVD_CARD, &[(CHIRP, LPCM16)], DVD_V, "dvd"), None, 720, 576), |
| 341 | ]; |
| 342 | let mut off = clip("i.mpg", CARD, &[(CHIRP, MP2)], MPEG1, "mpeg"); |
| 343 | off.offset = 10.0; |
| 344 | v.push((off, None, 352, 288)); |
| 345 | v |
| 346 | } |
| 347 | |
| 348 | |
| 349 | #[test] |
| 350 | fn the_picture_opens_probes_and_decodes_as_ffmpeg_does() { |
| 351 | if !have(&["mpeg1video", "mpeg2video", "mp2", "ac3", "pcm_dvd"]) { |
| 352 | return; |
| 353 | } |
| 354 | let dir = scratch("video"); |
| 355 | for (spec, interlaced, width, height) in shapes() { |
| 356 | let Some(path) = try_make(&dir, &spec) else { continue }; |
| 357 | let facts = engine::probe_media(&path); |
| 358 | let video = facts.video.as_ref().unwrap_or_else(|| panic!("{}: no picture", spec.name)); |
| 359 | assert_eq!((video.width, video.height), (width, height), "{}", spec.name); |
| 360 | assert_eq!(video.codec, engine::demux::Codec::Mpeg2, "{}", spec.name); |
| 361 | assert!((video.frame_rate.unwrap() - FPS).abs() < 0.01, "{}: {:?}", spec.name, video.frame_rate); |
| 362 | assert_eq!(video.interlaced, interlaced, "{}", spec.name); |
| 363 | let secs = facts.duration_secs.expect("a length"); |
| 364 | assert!((secs - 2.0).abs() <= 1.0 / FPS, "{}: {secs} s", spec.name); |
| 365 | let name = facts.container.clone().unwrap_or_default(); |
| 366 | assert!(["mpeg", "mpegvideo", "vob"].contains(&name.as_str()), "{}: container {name}", spec.name); |
| 367 | let (meta, _) = Demuxer::open(&path).expect("open"); |
| 368 | assert_eq!(meta.frame_count, 50, "{}", spec.name); |
| 369 | let want = ffmpeg_raw_as(&path, "yuv420p"); |
| 370 | let got = mpeg2_planes(&path); |
| 371 | assert!(got == want, "{}: pictures differ from ffmpeg's ({} vs {} bytes)", spec.name, got.len(), want.len()); |
| 372 | let frames = session_frames(&path); |
| 373 | assert_eq!(frames.iter().map(|f| f.index).collect::<Vec<_>>(), (0..50).collect::<Vec<_>>(), "{}", spec.name); |
| 374 | if spec.audio.is_empty() { |
| 375 | continue; |
| 376 | } |
| 377 | let streams = AudioSession::probe_streams(&path).expect("streams"); |
| 378 | assert_eq!(streams.len(), 1, "{}: {streams:?}", spec.name); |
| 379 | assert!(streams[0].decodable && streams[0].sample_rate == 48_000, "{}: {streams:?}", spec.name); |
| 380 | } |
| 381 | let _ = std::fs::remove_dir_all(&dir); |
| 382 | } |
| 383 | |
| 384 | |
| 385 | |
| 386 | #[test] |
| 387 | fn mid_gop_seeks_equal_a_sequential_decode() { |
| 388 | if !have(&["mpeg1video", "mpeg2video", "mp2", "ac3"]) { |
| 389 | return; |
| 390 | } |
| 391 | let dir = scratch("seek"); |
| 392 | for (spec, ..) in shapes() { |
| 393 | let Some(path) = try_make(&dir, &spec) else { continue }; |
| 394 | let all = session_frames(&path); |
| 395 | assert_eq!(all.len(), 50, "{}", spec.name); |
| 396 | for target in [0u32, 1, 2, 5, 9, 10, 11, 13, 17, 20, 25, 33, 41, 49] { |
| 397 | let seeked = software(|| { |
| 398 | let (_, rx, _cancel) = DecodeSession::open_at(&path, target).expect("open_at"); |
| 399 | rx.into_iter().next().unwrap_or_else(|| panic!("{}: no frame after seek to {target}", spec.name)) |
| 400 | }); |
| 401 | assert_eq!(seeked.index, target, "{}", spec.name); |
| 402 | assert!(seeked.bgra == all[target as usize].bgra, "{}: seek to {target} differs from sequential", spec.name); |
| 403 | } |
| 404 | let range = software(|| { |
| 405 | let (_, rx, _cancel) = DecodeSession::open_range(&path, 12, 31).expect("open_range"); |
| 406 | rx.into_iter().collect::<Vec<_>>() |
| 407 | }); |
| 408 | assert_eq!(range.iter().map(|f| f.index).collect::<Vec<_>>(), (12..31).collect::<Vec<_>>(), "{}", spec.name); |
| 409 | for f in &range { |
| 410 | assert!(f.bgra == all[f.index as usize].bgra, "{}: range frame {} differs", spec.name, f.index); |
| 411 | } |
| 412 | } |
| 413 | let _ = std::fs::remove_dir_all(&dir); |
| 414 | } |
| 415 | |
| 416 | |
| 417 | |
| 418 | #[test] |
| 419 | fn h264_in_a_program_stream_opens_and_seeks() { |
| 420 | if !have(&["libx264", "ac3"]) { |
| 421 | return; |
| 422 | } |
| 423 | let dir = scratch("h264"); |
| 424 | for (name, fmt, audio) in [("h.vob", "vob", AC3), ("h.mpg", "mpeg", MP2)] { |
| 425 | let Some(path) = try_make(&dir, &clip(name, CARD, &[(CHIRP, audio)], X264, fmt)) else { continue }; |
| 426 | let facts = engine::probe_media(&path); |
| 427 | let Some(video) = facts.video.as_ref() else { |
| 428 | eprintln!("{name}: ffmpeg wrote H.264 in a form the demuxer does not take as a picture: skipping"); |
| 429 | continue; |
| 430 | }; |
| 431 | assert_eq!(video.codec, engine::demux::Codec::H264, "{name}"); |
| 432 | assert_eq!((video.width, video.height), (352, 288), "{name}"); |
| 433 | let (meta, _) = Demuxer::open(&path).expect("open"); |
| 434 | assert_eq!(meta.frame_count, 50, "{name}"); |
| 435 | let want = ffmpeg_raw(&path); |
| 436 | let got = h264_planes(&path); |
| 437 | assert!(got == want, "{name}: pictures differ from ffmpeg's ({} vs {} bytes)", got.len(), want.len()); |
| 438 | let all = session_frames(&path); |
| 439 | assert_eq!(all.len(), 50, "{name}"); |
| 440 | for target in [0u32, 3, 10, 14, 25, 37, 49] { |
| 441 | let seeked = software(|| { |
| 442 | let (_, rx, _cancel) = DecodeSession::open_at(&path, target).expect("open_at"); |
| 443 | rx.into_iter().next().unwrap_or_else(|| panic!("{name}: no frame after seek to {target}")) |
| 444 | }); |
| 445 | assert_eq!(seeked.index, target, "{name}"); |
| 446 | assert!(seeked.bgra == all[target as usize].bgra, "{name}: seek to {target} differs from sequential"); |
| 447 | } |
| 448 | } |
| 449 | let _ = std::fs::remove_dir_all(&dir); |
| 450 | } |
| 451 | |
| 452 | |
| 453 | #[test] |
| 454 | fn an_interlaced_dvd_picture_is_deinterlaced() { |
| 455 | if !have(&["mpeg2video", "ac3"]) { |
| 456 | return; |
| 457 | } |
| 458 | let dir = scratch("deint"); |
| 459 | let tff = make(&dir, &clip("tff.vob", DVD_TFF, &[], DVD_V_TFF, "dvd")); |
| 460 | let woven = ffmpeg_raw_as(&tff, "yuv420p"); |
| 461 | let frames = session_frames(&tff); |
| 462 | let (w, h) = (720usize, 576usize); |
| 463 | let size = w * h; |
| 464 | let luma_comb = |y: &[u8]| -> u64 { y.chunks(w).collect::<Vec<_>>().windows(2).map(|p| p[0].iter().zip(p[1]).map(|(a, b)| u64::from(a.abs_diff(*b))).sum::<u64>()).sum() }; |
| 465 | let bgra_comb = |f: &engine::decode::Frame| -> u64 { |
| 466 | f.bgra.chunks(w * 4).collect::<Vec<_>>().windows(2).map(|p| p[0].iter().zip(p[1]).map(|(a, b)| u64::from(a.abs_diff(*b))).sum::<u64>()).sum() |
| 467 | }; |
| 468 | let (mut woven_total, mut ours_total) = (0u64, 0u64); |
| 469 | for n in 5..45 { |
| 470 | woven_total += luma_comb(&woven[n * size * 3 / 2..n * size * 3 / 2 + size]); |
| 471 | ours_total += bgra_comb(&frames[n]); |
| 472 | } |
| 473 | let (woven_avg, ours_avg) = (woven_total as f64 / size as f64, ours_total as f64 / (size as f64 * 4.0)); |
| 474 | eprintln!("row-to-row difference: woven {woven_avg:.1}, deinterlaced {ours_avg:.1}"); |
| 475 | assert!(woven_total > 0 && ours_avg < woven_avg, "the interlaced picture is not deinterlaced"); |
| 476 | let _ = h; |
| 477 | let _ = std::fs::remove_dir_all(&dir); |
| 478 | } |
| 479 | |
| 480 | |
| 481 | |
| 482 | |
| 483 | |
| 484 | fn best_shift(cut: &[f32], whole: &[f32], at: usize) -> (i64, f32) { |
| 485 | let mut best = (0i64, f32::MAX); |
| 486 | for shift in -1200i64..=1200 { |
| 487 | let start = at as i64 + shift; |
| 488 | if start < 0 || (start as usize) * 2 + cut.len() > whole.len() { |
| 489 | continue; |
| 490 | } |
| 491 | let start = start as usize * 2; |
| 492 | let d = cut.iter().zip(&whole[start..]).map(|(a, b)| (a - b).abs()).fold(0f32, f32::max); |
| 493 | if d < best.1 { |
| 494 | best = (shift, d); |
| 495 | } |
| 496 | } |
| 497 | best |
| 498 | } |
| 499 | |
| 500 | |
| 501 | fn lpcm_shift(path: &Path, stream: usize, from: f64, reference: &[f32], offset: i64) -> (i64, f32) { |
| 502 | let (rate, _, ours) = sound(path, stream, from, 2_000); |
| 503 | let at = (from * f64::from(rate)).round() as i64 - offset; |
| 504 | best_shift(&ours, reference, at.max(0) as usize) |
| 505 | } |
| 506 | |
| 507 | |
| 508 | |
| 509 | #[test] |
| 510 | fn the_sound_is_ffmpegs_at_every_time_and_keeps_its_offset_from_the_picture() { |
| 511 | if !have(&["mpeg1video", "mpeg2video", "mp2", "ac3", "libmp3lame", "pcm_dvd"]) { |
| 512 | return; |
| 513 | } |
| 514 | let dir = scratch("sound"); |
| 515 | let mut cases = vec![ |
| 516 | (clip("mp2.mpg", CARD, &[(CHIRP, MP2)], MPEG1, "mpeg"), 1.5e-3f32), |
| 517 | (clip("mp3.mpg", CARD, &[(CHIRP, MP3)], MPEG1, "mpeg"), 1.5e-3), |
| 518 | (clip("ac3.vob", CARD, &[(CHIRP, AC3)], MPEG2, "vob"), 1.5e-3), |
| 519 | (clip("mp2.vob", CARD, &[(CHIRP, MP2)], MPEG2, "vob"), 1.5e-3), |
| 520 | (clip("dvd-ac3.vob", DVD_CARD, &[(CHIRP, AC3)], DVD_V, "dvd"), 1.5e-3), |
| 521 | (clip("lpcm16.vob", DVD_CARD, &[(CHIRP, LPCM16)], DVD_V, "dvd"), 1e-6), |
| 522 | (clip("lpcm24.vob", DVD_CARD, &[(CHIRP, LPCM24)], DVD_V, "dvd"), 1e-5), |
| 523 | (clip("two.vob", CARD, &[(CHIRP, AC3), (CHIRP, MP2)], MPEG2, "vob"), 1.5e-3), |
| 524 | ]; |
| 525 | let mut off = clip("off.mpg", CARD, &[(CHIRP, MP2)], MPEG1, "mpeg"); |
| 526 | off.offset = 10.0; |
| 527 | cases.push((off, 1.5e-3)); |
| 528 | for (spec, tolerance) in &cases { |
| 529 | let Some(path) = try_make(&dir, spec) else { continue }; |
| 530 | let streams = AudioSession::probe_streams(&path).expect("streams"); |
| 531 | assert_eq!(streams.len(), spec.audio.len(), "{}", spec.name); |
| 532 | for (index, row) in streams.iter().enumerate() { |
| 533 | assert!(row.decodable, "{}: {row:?}", spec.name); |
| 534 | assert_eq!(row.channels, 2, "{}", spec.name); |
| 535 | assert_eq!(row.sample_rate, 48_000, "{}", spec.name); |
| 536 | let reference = ffmpeg_sound(&path, index, 48_000); |
| 537 | let offset = sound_offset(&path, index, 48_000); |
| 538 | |
| 539 | |
| 540 | |
| 541 | let lpcm = row.codec == "pcm_dvd"; |
| 542 | for from in [0.0, 0.4, 1.1, 1.7] { |
| 543 | if lpcm && from > 0.0 { |
| 544 | let (shift, worst) = lpcm_shift(&path, index, from, &reference, offset); |
| 545 | eprintln!("{} stream {index} from {from}s: seek lands {shift} samples off (difference {worst:.6})", spec.name); |
| 546 | assert!(shift.abs() <= 520 && worst <= *tolerance, "{} from {from}s: shift {shift}, difference {worst}", spec.name); |
| 547 | continue; |
| 548 | } |
| 549 | let worst = compare(&path, index, from, 7_200, &reference, offset); |
| 550 | eprintln!("{} stream {index} ({}) from {from}s: worst difference {worst:.6}", spec.name, row.codec); |
| 551 | assert!(worst <= *tolerance, "{} stream {index} from {from}s: {worst}", spec.name); |
| 552 | } |
| 553 | |
| 554 | let (_, _, full) = sound(&path, index, 0.0, 96_000 * 2); |
| 555 | let (_, _, cut) = sound(&path, index, 1.3, 4_800); |
| 556 | let at = (1.3 * 48_000.0) as usize * 2; |
| 557 | if lpcm { |
| 558 | let (shift, worst) = best_shift(&cut, &full, at / 2); |
| 559 | assert!(shift.abs() <= 520 && worst <= 1e-6, "{} stream {index}: a seek is {shift} samples off ({worst})", spec.name); |
| 560 | continue; |
| 561 | } |
| 562 | let worst = cut.iter().zip(&full[at..]).map(|(a, b)| (a - b).abs()).fold(0f32, f32::max); |
| 563 | assert!(worst <= 1e-4, "{} stream {index}: a seek differs from sequential by {worst}", spec.name); |
| 564 | } |
| 565 | } |
| 566 | let _ = std::fs::remove_dir_all(&dir); |
| 567 | } |
| 568 | |
| 569 | |
| 570 | |
| 571 | |
| 572 | |
| 573 | #[test] |
| 574 | fn picture_and_sound_stay_in_sync_from_any_start() { |
| 575 | if !have(&["mpeg1video", "mpeg2video", "mp2", "ac3", "pcm_dvd"]) { |
| 576 | return; |
| 577 | } |
| 578 | let dir = scratch("sync"); |
| 579 | let wrap = (1u64 << 33) as f64 / 90_000.0; |
| 580 | let mut cases = vec![ |
| 581 | (clip("zero.mpg", FLASH, &[(BEEP, MP2)], MPEG1, "mpeg"), 0.0), |
| 582 | (clip("ten.mpg", FLASH, &[(BEEP, MP2)], MPEG1, "mpeg"), 10.0), |
| 583 | (clip("ten.vob", FLASH, &[(BEEP, AC3)], MPEG2, "vob"), 10.0), |
| 584 | (clip("near-wrap.vob", FLASH, &[(BEEP, MP2)], MPEG2, "vob"), wrap - 2.0), |
| 585 | (clip("wrap.vob", FLASH, &[(BEEP, AC3)], MPEG2, "vob"), wrap - 1.1), |
| 586 | (clip("dvd-lpcm.vob", DVD_FLASH, &[(BEEP, LPCM16)], DVD_V, "dvd"), 0.0), |
| 587 | (clip("dvd-ac3.vob", DVD_FLASH, &[(BEEP, AC3)], DVD_V, "dvd"), 0.0), |
| 588 | (clip("dvd-wrap.vob", DVD_FLASH, &[(BEEP, AC3)], DVD_V, "dvd"), wrap - 1.1), |
| 589 | ]; |
| 590 | for (spec, offset) in &mut cases { |
| 591 | spec.offset = *offset; |
| 592 | } |
| 593 | for (spec, _) in &cases { |
| 594 | let Some(path) = try_make(&dir, spec) else { continue }; |
| 595 | let frames = session_frames(&path); |
| 596 | assert_eq!(frames.len(), 60, "{}: {} frames", spec.name, frames.len()); |
| 597 | let flash = flash_frame(&frames).expect("a flash"); |
| 598 | assert_eq!(flash, 25, "{}: the flash is at 1.0 s of the clip", spec.name); |
| 599 | let (rate, width, all) = sound(&path, 0, 0.0, 48_000 * 3); |
| 600 | let beep = first_loud(&all, width).expect("a beep") as f64 / f64::from(rate); |
| 601 | eprintln!("{}: flash at {:.3} s, beep at {beep:.3} s", spec.name, f64::from(flash) / FPS); |
| 602 | assert!(beep > 0.99 && beep < 1.0 + 0.065, "{}: the beep is at {beep:.3} s", spec.name); |
| 603 | |
| 604 | let (_, _, tail) = sound(&path, 0, 0.8, 48_000); |
| 605 | let again = 0.8 + first_loud(&tail, width).expect("a beep after a seek") as f64 / f64::from(rate); |
| 606 | |
| 607 | let slack = if spec.name.contains("lpcm") { 0.015 } else { 0.002 }; |
| 608 | assert!((again - beep).abs() < slack, "{}: {again} vs {beep}", spec.name); |
| 609 | let (_, rx, _) = software(|| DecodeSession::open_at(&path, 25).map(|(m, rx, c)| (m, rx.into_iter().next(), c))).expect("seek"); |
| 610 | assert_eq!(rx.map(|f| f.index), Some(25), "{}", spec.name); |
| 611 | } |
| 612 | let _ = std::fs::remove_dir_all(&dir); |
| 613 | } |
| 614 | |
| 615 | |
| 616 | |
| 617 | |
| 618 | |
| 619 | #[test] |
| 620 | fn two_vobs_joined_by_bytes_play_one_after_the_other() { |
| 621 | if !have(&["mpeg2video", "ac3"]) { |
| 622 | return; |
| 623 | } |
| 624 | let dir = scratch("joined"); |
| 625 | let one = make(&dir, &clip("one.vob", FLASH, &[(BEEP, AC3)], MPEG2, "vob")); |
| 626 | let joined = dir.join("joined.vob"); |
| 627 | let mut bytes = std::fs::read(&one).unwrap(); |
| 628 | bytes.extend(std::fs::read(&one).unwrap()); |
| 629 | std::fs::write(&joined, bytes).unwrap(); |
| 630 | let facts = engine::probe_media(&joined); |
| 631 | let secs = facts.duration_secs.expect("a length"); |
| 632 | |
| 633 | assert!((secs - 4.8).abs() < 0.03, "{secs} s"); |
| 634 | let all = session_frames(&joined); |
| 635 | assert_eq!(all.iter().map(|f| f.index).collect::<Vec<_>>(), (0..all.len() as u32).collect::<Vec<_>>()); |
| 636 | |
| 637 | assert_eq!(all.len(), 120); |
| 638 | assert_eq!(flash_frame(&all), Some(25)); |
| 639 | let second = flash_frame(&all[60..]).expect("a second flash"); |
| 640 | assert_eq!(second, 85); |
| 641 | |
| 642 | for target in [5u32, 33, 59, 60, 66, 70, 80, 119] { |
| 643 | let seeked = software(|| { |
| 644 | let (_, rx, _cancel) = DecodeSession::open_at(&joined, target).expect("open_at"); |
| 645 | rx.into_iter().next().expect("a frame") |
| 646 | }); |
| 647 | assert_eq!(seeked.index, target); |
| 648 | assert!(seeked.bgra == all[target as usize].bgra, "seek to {target} differs from sequential"); |
| 649 | } |
| 650 | let (_, _, beeps) = sound(&joined, 0, 0.0, 48_000 * 4); |
| 651 | let loud = beeps.chunks(2).filter(|f| f[0].abs() > 0.2).count(); |
| 652 | assert!(loud > 2 * 8_000, "both beeps are heard ({loud} loud samples)"); |
| 653 | let _ = std::fs::remove_dir_all(&dir); |
| 654 | } |
| 655 | |
| 656 | |
| 657 | |
| 658 | |
| 659 | #[test] |
| 660 | fn a_dts_track_is_refused_by_name_and_the_picture_still_opens() { |
| 661 | if !have(&["mpeg2video"]) { |
| 662 | return; |
| 663 | } |
| 664 | let dir = scratch("refused"); |
| 665 | let dts: &[&str] = &["-c:a", "dca", "-strict", "-2", "-ac", "2"]; |
| 666 | let Some(path) = try_make(&dir, &clip("dts.vob", CARD, &[(CHIRP, dts)], MPEG2, "vob")) else { |
| 667 | let _ = std::fs::remove_dir_all(&dir); |
| 668 | return; |
| 669 | }; |
| 670 | let (meta, _) = Demuxer::open(&path).expect("the picture opens"); |
| 671 | assert_eq!(meta.frame_count, 50); |
| 672 | let streams = AudioSession::probe_streams(&path).expect("streams"); |
| 673 | assert_eq!(streams.len(), 1, "{streams:?}"); |
| 674 | assert!(!streams[0].decodable && streams[0].codec == "dts", "{:?}", streams[0]); |
| 675 | assert!(AudioSession::open(&path).expect("a silent source, not an error").is_none()); |
| 676 | let why = AudioSession::unsupported(&path).expect("header").expect("a reason"); |
| 677 | assert!(why.to_lowercase().contains("dts") && why.contains("ffmpeg"), "{why}"); |
| 678 | let _ = std::fs::remove_dir_all(&dir); |
| 679 | } |
| 680 | |
| 681 | |
| 682 | #[test] |
| 683 | fn a_program_stream_without_a_picture_says_so() { |
| 684 | if !have(&["mp2"]) { |
| 685 | return; |
| 686 | } |
| 687 | let dir = scratch("nopic"); |
| 688 | let path = dir.join("sound.vob"); |
| 689 | ffmpeg(&["-f", "lavfi", "-i", CHIRP, "-c:a", "mp2", "-f", "vob", s(&path)]); |
| 690 | let err = Demuxer::open(&path).err().expect("no picture").to_string(); |
| 691 | assert!(err.to_lowercase().contains("video"), "{err}"); |
| 692 | let _ = std::fs::remove_dir_all(&dir); |
| 693 | } |
| 694 | |
| 695 | |
| 696 | |
| 697 | |
| 698 | |
| 699 | #[test] |
| 700 | fn a_program_stream_is_sniffed_whatever_it_is_called() { |
| 701 | if !have(&["mpeg1video", "mp2", "mpeg2video"]) { |
| 702 | return; |
| 703 | } |
| 704 | let dir = scratch("sniff"); |
| 705 | let ps = make(&dir, &clip("x.mpg", CARD, &[(CHIRP, MP2)], MPEG1, "mpeg")); |
| 706 | let m2v = make(&dir, &clip("x.m2v", CARD, &[], MPEG2, "mpeg2video")); |
| 707 | for (src, name) in [(&ps, "recording.dat"), (&ps, "clip.mod"), (&ps, "clip.TOD"), (&ps, "clip.m2p"), (&ps, "noext"), (&m2v, "video.dat"), (&m2v, "video.mpv")] { |
| 708 | let odd = dir.join(name); |
| 709 | std::fs::copy(src, &odd).unwrap(); |
| 710 | assert!(engine::demux::is_mpegps(&odd), "{name}"); |
| 711 | assert!(!engine::demux::is_mpegts(&odd), "{name}"); |
| 712 | assert_eq!(Demuxer::open(&odd).expect("opens by content").0.frame_count, 50, "{name}"); |
| 713 | } |
| 714 | |
| 715 | assert!(!engine::is_audio(&ps)); |
| 716 | let song = dir.join("song.mpg"); |
| 717 | ffmpeg(&["-f", "lavfi", "-i", CHIRP, "-c:a", "mp2", "-f", "mp2", s(&song)]); |
| 718 | assert!(engine::is_audio(&song) && !engine::demux::is_mpegps(&song)); |
| 719 | |
| 720 | let module = dir.join("tune.mod"); |
| 721 | std::fs::write(&module, b"Extended Module: not an MPEG stream at all\0\0\0\0").unwrap(); |
| 722 | assert!(!engine::demux::is_mpegps(&module)); |
| 723 | assert!(!engine::demux::is_mpegps(Path::new("/nonexistent/song.mp3"))); |
| 724 | assert!(engine::is_audio(Path::new("/nonexistent/k.mpg"))); |
| 725 | let _ = std::fs::remove_dir_all(&dir); |
| 726 | } |
| 727 | |
| 728 | |
| 729 | |
| 730 | |
| 731 | |
| 732 | #[test] |
| 733 | fn an_export_from_a_program_stream_keeps_its_length_and_its_sync() { |
| 734 | if !have(&["mpeg1video", "mpeg2video", "libx264", "aac", "ac3", "mp2", "pcm_dvd"]) { |
| 735 | return; |
| 736 | } |
| 737 | let dir = scratch("export"); |
| 738 | let mut cases = vec![ |
| 739 | clip("e.mpg", FLASH, &[(BEEP, MP2)], MPEG1, "mpeg"), |
| 740 | clip("e.vob", FLASH, &[(BEEP, AC3)], MPEG2, "vob"), |
| 741 | clip("e-off.vob", FLASH, &[(BEEP, AC3)], MPEG2, "vob"), |
| 742 | clip("e-dvd.vob", DVD_FLASH, &[(BEEP, LPCM16)], DVD_V, "dvd"), |
| 743 | ]; |
| 744 | cases[2].offset = 10.0; |
| 745 | for spec in &cases { |
| 746 | let Some(path) = try_make(&dir, spec) else { continue }; |
| 747 | let name = spec.name; |
| 748 | let out = dir.join(format!("{name}.mp4")); |
| 749 | software(|| export_as(&path, &out, Format::Mp4)); |
| 750 | let secs: f64 = ffprobe(&out, "format=duration", "v:0").parse().unwrap_or(0.0); |
| 751 | assert!((secs - 2.4).abs() < 0.1, "{name}: {secs} s"); |
| 752 | let video = Command::new("ffmpeg") |
| 753 | .args(["-v", "error", "-i"]) |
| 754 | .arg(&out) |
| 755 | .args(["-an", "-vf", "scale=8:8,format=gray", "-fps_mode", "passthrough", "-f", "rawvideo", "-"]) |
| 756 | .output() |
| 757 | .expect("ffmpeg"); |
| 758 | let flash = video.stdout.chunks(64).position(|f| f.iter().map(|&b| u32::from(b)).sum::<u32>() > 128 * 64).expect("a flash"); |
| 759 | let pcm = ffmpeg_sound(&out, 0, 48_000); |
| 760 | let beep = pcm.chunks(2).position(|f| f.iter().any(|s| s.abs() > 0.2)).expect("a beep") as f64 / 48_000.0; |
| 761 | let flash_at = flash as f64 / FPS; |
| 762 | eprintln!("{name}: exported flash at {flash_at:.3} s, beep at {beep:.3} s"); |
| 763 | assert!((flash_at - 1.0).abs() < 0.045, "{name}: flash at {flash_at}"); |
| 764 | assert!((beep - flash_at).abs() < 0.09, "{name}: beep {beep} vs flash {flash_at}"); |
| 765 | } |
| 766 | let _ = std::fs::remove_dir_all(&dir); |
| 767 | } |