forge
Explore
Log in

Don't you dare go Hollow

edith

Clone
★ 0

0 watching0 forksRust18.3 MiBff99ad6Tahinli6 days ago1055 commits

avi.rs533 lines, 24.7 KiBHistoryRawDownload
1//! AVI (`.avi`, `.divx`) end to end: probe, decode, seek, sound, A/V sync, export and the
2//! streams that are refused.
3//!
4//! Every clip is synthetic (`testsrc2`, a flash on black, a chirp, a beep) made by ffmpeg into
5//! a scratch directory; without ffmpeg and the encoders a test needs, it says so and passes,
6//! as `mpegts` does. `VE_SW` is process-wide, so tests that pin it hold [`SW`].
7//!
8//! The pictures of B-frame streams are checked against the stream they were remuxed from
9//! (an mp4 for H.264, a transport stream for MPEG-2): an AVI has no timestamps, so this is
10//! the proof that decode order and display order come out right. MJPEG pictures go through
11//! the MJPEG decode seat (another lane); until it exists the picture check says so and
12//! passes, and the demux-level checks (packets, probe, seek, field order) carry the case.
13//!
14//! ```text
15//! cargo test -p engine --release --test avi
16//! ```
17
18use std::path::{Path, PathBuf};
19use std::process::Command;
20use std::sync::Mutex;
21use std::time::{Duration, Instant};
22
23use engine::audio::AudioSession;
24use engine::decode::DecodeSession;
25use engine::demux::{Codec, Demuxer};
26use engine::export::{ExportSettings, Format};
27use engine::PlaybackSession;
28
29static SW: Mutex<()> = Mutex::new(());
30
31fn software<T>(f: impl FnOnce() -> T) -> T {
32 let _guard = SW.lock().unwrap_or_else(|poisoned| poisoned.into_inner());
33 engine::envcfg::set("VE_SW", "1");
34 let out = f();
35 engine::envcfg::unset("VE_SW");
36 out
37}
38
39fn have(encoders: &[&str]) -> bool {
40 let tool = |t: &str| Command::new(t).arg("-version").output().is_ok_and(|o| o.status.success());
41 if !tool("ffmpeg") || !tool("ffprobe") {
42 eprintln!("no ffmpeg: skipping");
43 return false;
44 }
45 let list = Command::new("ffmpeg")
46 .args(["-hide_banner", "-encoders"])
47 .output()
48 .map(|o| String::from_utf8_lossy(&o.stdout).into_owned())
49 .unwrap_or_default();
50 for e in encoders {
51 if !list.split_whitespace().any(|w| w == *e) {
52 eprintln!("ffmpeg has no {e} encoder: skipping");
53 return false;
54 }
55 }
56 true
57}
58
59fn scratch(name: &str) -> PathBuf {
60 let dir = std::env::temp_dir().join(format!("edith-avi-{name}-{}", std::process::id()));
61 let _ = std::fs::remove_dir_all(&dir);
62 std::fs::create_dir_all(&dir).expect("scratch directory");
63 dir
64}
65
66fn ffmpeg(args: &[&str]) {
67 let out = Command::new("ffmpeg").args(["-v", "error", "-y"]).args(args).output().expect("run ffmpeg");
68 assert!(out.status.success(), "ffmpeg {args:?}: {}", String::from_utf8_lossy(&out.stderr));
69}
70
71fn s(p: &Path) -> &str {
72 p.to_str().unwrap()
73}
74
75const FPS: f64 = 25.0;
76const CARD: &str = "testsrc2=size=352x288:rate=25:duration=2";
77const 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";
78const 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)'";
79const 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";
80
81const X264: &[&str] = &["-c:v", "libx264", "-x264-params", "keyint=10:min-keyint=10:bframes=2", "-pix_fmt", "yuv420p"];
82/// Open GOPs: the keyframe is a non-IDR I picture with B pictures behind it that are shown first.
83const X264_OPEN: &[&str] =
84 &["-c:v", "libx264", "-x264-params", "keyint=10:min-keyint=10:bframes=2:open-gop=1", "-pix_fmt", "yuv420p"];
85const MPEG2: &[&str] = &["-c:v", "mpeg2video", "-b:v", "4M", "-g", "10", "-bf", "2", "-pix_fmt", "yuv420p"];
86const MJPEG: &[&str] = &["-c:v", "mjpeg", "-q:v", "3", "-pix_fmt", "yuvj420p"];
87const MP3: &[&str] = &["-c:a", "libmp3lame", "-b:a", "128k"];
88const MP2: &[&str] = &["-c:a", "mp2", "-b:a", "192k"];
89const PCM: &[&str] = &["-c:a", "pcm_s16le"];
90const AAC: &[&str] = &["-c:a", "aac", "-b:a", "128k"];
91const AC3: &[&str] = &["-c:a", "ac3", "-b:a", "192k"];
92
93/// Muxes `video` (+ `audio`) with `vcodec`/`acodec` into `dir/name`, in the container the
94/// name's extension says.
95fn make(dir: &Path, name: &str, video: &str, audio: Option<&str>, vcodec: &[&str], acodec: &[&str]) -> PathBuf {
96 let out = dir.join(name);
97 let mut args: Vec<&str> = vec!["-f", "lavfi", "-i", video];
98 if let Some(a) = audio {
99 args.extend(["-f", "lavfi", "-i", a]);
100 }
101 args.extend(["-map", "0:v"]);
102 args.extend(vcodec);
103 if audio.is_some() {
104 args.extend(["-map", "1:a"]);
105 args.extend(acodec);
106 }
107 args.push(s(&out));
108 ffmpeg(&args);
109 out
110}
111
112/// `src` copied (no re-encode) into a file called `name` of `dir`; an mp4's H.264 is turned
113/// into the Annex B an AVI carries.
114fn remux(dir: &Path, src: &Path, name: &str) -> PathBuf {
115 let out = dir.join(name);
116 // `-r`: the source's timescale (1/12800, 1/90000) would otherwise become the AVI's rate.
117 let mut args = vec!["-i", s(src), "-map", "0", "-c", "copy", "-r", "25"];
118 if src.extension().is_some_and(|e| e == "mp4") {
119 args.extend(["-bsf:v", "h264_mp4toannexb"]);
120 }
121 args.push(s(&out));
122 ffmpeg(&args);
123 out
124}
125
126fn ffprobe(path: &Path, entries: &str, select: &str) -> String {
127 let out = Command::new("ffprobe")
128 .args(["-v", "error", "-select_streams", select, "-show_entries", entries, "-of", "csv=p=0"])
129 .arg(path)
130 .output()
131 .expect("ffprobe runs");
132 assert!(out.status.success(), "ffprobe reads {}", path.display());
133 String::from_utf8_lossy(&out.stdout).trim().to_owned()
134}
135
136fn session_frames(path: &Path) -> Vec<engine::decode::Frame> {
137 software(|| DecodeSession::open(path).expect("open").1.into_iter().collect())
138}
139
140// ------------------------------------------------------------------ pictures
141
142/// Probe, frame count, every picture against the stream the AVI was remuxed from, and a seek
143/// to any frame against the sequential decode: H.264 (IDR and open GOPs) and MPEG-2, with
144/// B pictures, whose AVI carries decode order and no timestamps.
145#[test]
146fn b_frame_pictures_probe_decode_and_seek_as_their_source_does() {
147 if !have(&["libx264", "mpeg2video", "libmp3lame", "mp2"]) {
148 return;
149 }
150 let dir = scratch("pictures");
151 #[allow(clippy::type_complexity)]
152 let cases: [(&str, &[&str], &[&str], &str, Codec, &str); 3] = [
153 ("h264", X264, MP3, "mp4", Codec::H264, "h264"),
154 ("h264-open", X264_OPEN, MP3, "mp4", Codec::H264, "h264"),
155 ("mpeg2", MPEG2, MP2, "ts", Codec::Mpeg2, "mpeg2video"),
156 ];
157 for (name, vcodec, acodec, via, codec, ffname) in cases {
158 let origin = make(&dir, &format!("{name}.{via}"), CARD, Some(CHIRP), vcodec, acodec);
159 let path = remux(&dir, &origin, &format!("{name}.avi"));
160 assert!(engine::demux::is_avi(&path), "{name}");
161 let facts = engine::probe_media(&path);
162 assert_eq!(facts.container.as_deref(), Some("avi"), "{name}");
163 let video = facts.video.as_ref().unwrap_or_else(|| panic!("{name}: no picture: {:?}", Demuxer::open(&path).err().map(|e| e.to_string())));
164 assert_eq!((video.width, video.height), (352, 288), "{name}");
165 assert_eq!(video.codec, codec, "{name}");
166 assert!((video.frame_rate.unwrap() - FPS).abs() < 0.01, "{name}: {:?}", video.frame_rate);
167 assert!(video.bit_depth.is_none_or(|d| d == 8), "{name}: {:?}", video.bit_depth);
168 assert_eq!(video.interlaced, None, "{name}");
169 let secs = facts.duration_secs.expect("a length");
170 assert!((secs - 2.0).abs() <= 1.0 / FPS, "{name}: {secs} s");
171 let kinds: Vec<_> = facts.streams.iter().map(|f| f.codec_id.clone().unwrap_or_default()).collect();
172 assert_eq!(kinds.first().map(String::as_str), Some(ffname), "{name}: {kinds:?}");
173 assert!(kinds.iter().any(|k| k == if name == "mpeg2" { "mp2" } else { "mp3" }), "{name}: {kinds:?}");
174 let (meta, _) = Demuxer::open(&path).expect("open");
175 assert_eq!(meta.frame_count, 50, "{name}");
176
177 let all = session_frames(&path);
178 let reference = session_frames(&origin);
179 assert_eq!(all.len(), 50, "{name}");
180 assert_eq!(all.iter().map(|f| f.index).collect::<Vec<_>>(), (0..50).collect::<Vec<_>>(), "{name}");
181 assert_eq!(reference.len(), 50, "{name}");
182 for (a, b) in all.iter().zip(&reference) {
183 assert!(a.bgra == b.bgra, "{name}: frame {} differs from the {via} it was remuxed from", a.index);
184 }
185 for target in [0u32, 1, 2, 5, 9, 10, 11, 13, 17, 20, 25, 33, 41, 49] {
186 let seeked = software(|| {
187 let (_, rx, _cancel) = DecodeSession::open_at(&path, target).expect("open_at");
188 rx.into_iter().next().unwrap_or_else(|| panic!("{name}: no frame after seek to {target}"))
189 });
190 assert_eq!(seeked.index, target, "{name}");
191 assert!(seeked.bgra == all[target as usize].bgra, "{name}: seek to {target} differs from sequential");
192 }
193 let range = software(|| {
194 let (_, rx, _cancel) = DecodeSession::open_range(&path, 12, 31).expect("open_range");
195 rx.into_iter().collect::<Vec<_>>()
196 });
197 assert_eq!(range.iter().map(|f| f.index).collect::<Vec<_>>(), (12..31).collect::<Vec<_>>(), "{name}");
198 for f in &range {
199 assert!(f.bgra == all[f.index as usize].bgra, "{name}: range frame {} differs", f.index);
200 }
201 }
202 let _ = std::fs::remove_dir_all(&dir);
203}
204
205/// MJPEG + PCM: at the demux level the packets are ffmpeg's, the probe states the stream,
206/// a seek lands on the frame asked for, and the field order is the AVI convention. The
207/// pictures themselves are compared with ffmpeg's decode once the MJPEG seat exists.
208#[test]
209fn mjpeg_and_pcm_demux_probe_seek_and_decode() {
210 if !have(&["mjpeg", "pcm_s16le"]) {
211 return;
212 }
213 let dir = scratch("mjpeg");
214 let path = make(&dir, "m.avi", CARD, Some(CHIRP), MJPEG, PCM);
215 let facts = engine::probe_media(&path);
216 assert_eq!(facts.container.as_deref(), Some("avi"));
217 let video = facts.video.as_ref().expect("a picture");
218 assert_eq!((video.width, video.height), (352, 288));
219 assert_eq!(video.codec, Codec::Mjpeg);
220 assert!((video.frame_rate.unwrap() - FPS).abs() < 0.01);
221 assert_eq!(video.interlaced, None);
222 let secs = facts.duration_secs.expect("a length");
223 assert!((secs - 2.0).abs() <= 1.0 / FPS, "{secs} s");
224 let codecs: Vec<_> = facts.streams.iter().map(|f| (f.codec_id.clone().unwrap_or_default(), f.bit_depth)).collect();
225 assert_eq!(codecs[0].0, "mjpeg", "{codecs:?}");
226 assert_eq!(codecs[1], ("pcm_s16le".to_string(), Some(16)), "{codecs:?}");
227 let streams = AudioSession::probe_streams(&path).expect("streams");
228 assert_eq!((streams.len(), streams[0].decodable, streams[0].channels, streams[0].sample_rate), (1, true, 2, 48_000));
229 assert_eq!(streams[0].bit_depth, Some(16));
230
231 let (meta, mut demuxer) = Demuxer::open(&path).expect("open");
232 assert_eq!((meta.codec, meta.frame_count, meta.width, meta.height), (Codec::Mjpeg, 50, 352, 288));
233 assert_eq!(demuxer.field_order(), Some(ec_core::frame::Interlace::BottomFieldFirst));
234 // Every packet equals ffmpeg's, byte for byte.
235 let want = Command::new("ffmpeg")
236 .args(["-v", "error", "-i"])
237 .arg(&path)
238 .args(["-an", "-c:v", "copy", "-f", "mjpeg", "-"])
239 .output()
240 .expect("ffmpeg")
241 .stdout;
242 demuxer.seek_to_sync_at_or_before(0);
243 let mut packets = Vec::new();
244 while let Some(au) = demuxer.next_access_unit().expect("demux") {
245 packets.push(au);
246 }
247 assert_eq!(packets.len(), 50);
248 assert!(packets.concat() == want, "the demuxed packets are not ffmpeg's");
249 // Every frame is a keyframe: a seek lands on the frame asked for and hands out its packet.
250 for target in [0u32, 1, 24, 25, 49] {
251 assert_eq!(demuxer.seek_to_sync_at_or_before(target), i64::from(target));
252 assert!(demuxer.next_access_unit().unwrap().unwrap() == packets[target as usize], "seek to {target}");
253 }
254
255 // The pictures: PSNR against ffmpeg's own decode (full-range BT.601 to BGRA).
256 let frames = session_frames_or_none(&path);
257 let Some(frames) = frames else {
258 eprintln!("no MJPEG decode seat yet: pictures not compared");
259 let _ = std::fs::remove_dir_all(&dir);
260 return;
261 };
262 assert_eq!(frames.len(), 50);
263 let raw = Command::new("ffmpeg")
264 .args(["-v", "error", "-i"])
265 .arg(&path)
266 .args(["-an", "-fps_mode", "passthrough", "-f", "rawvideo", "-pix_fmt", "bgra", "-"])
267 .output()
268 .expect("ffmpeg")
269 .stdout;
270 let size = 352 * 288 * 4;
271 for f in &frames {
272 let theirs = &raw[f.index as usize * size..(f.index as usize + 1) * size];
273 let mse = f.bgra.iter().zip(theirs).map(|(a, b)| (f64::from(*a) - f64::from(*b)).powi(2)).sum::<f64>() / size as f64;
274 let psnr = 10.0 * (255.0f64 * 255.0 / mse.max(1e-9)).log10();
275 assert!(psnr > 30.0, "frame {}: PSNR {psnr:.1} dB against ffmpeg", f.index);
276 }
277 let _ = std::fs::remove_dir_all(&dir);
278}
279
280/// Every picture the session releases, or `None` when the codec has no decode seat yet.
281fn session_frames_or_none(path: &Path) -> Option<Vec<engine::decode::Frame>> {
282 let frames = session_frames(path);
283 (!frames.is_empty()).then_some(frames)
284}
285
286// ------------------------------------------------------------------ sound
287
288fn sound(path: &Path, stream: usize, from: f64, frames: usize) -> (u32, usize, Vec<f32>) {
289 let (meta, rx) = AudioSession::open_multi_streams(&[(path.to_path_buf(), stream)], &[(Some(0), from, f64::INFINITY)])
290 .expect("open")
291 .expect("the file has sound");
292 let width = usize::from(meta.channels);
293 let mut out = Vec::new();
294 for chunk in rx {
295 out.extend_from_slice(&chunk.samples);
296 if out.len() >= frames * width {
297 break;
298 }
299 }
300 out.truncate(frames * width);
301 (meta.sample_rate, width, out)
302}
303
304fn ffmpeg_sound(path: &Path, rate: u32) -> Vec<f32> {
305 let out = Command::new("ffmpeg")
306 .args(["-v", "error", "-i"])
307 .arg(path)
308 .args(["-map", "0:a:0", "-vn", "-ac", "2", "-ar", &rate.to_string(), "-f", "f32le", "-"])
309 .output()
310 .expect("ffmpeg runs");
311 assert!(out.status.success(), "ffmpeg: {}", String::from_utf8_lossy(&out.stderr));
312 out.stdout.as_chunks::<4>().0.iter().map(|b| f32::from_le_bytes(*b)).collect()
313}
314
315/// Our samples (`from` seconds in) against ffmpeg's decode; the largest difference.
316fn compare(path: &Path, from: f64, frames: usize, reference: &[f32]) -> f32 {
317 let (rate, width, ours) = sound(path, 0, from, frames);
318 assert_eq!(width, 2);
319 let first = (from * f64::from(rate)).round() as i64;
320 let mut worst = 0f32;
321 let mut compared = 0;
322 for frame in 0..ours.len() / 2 {
323 let at = first + frame as i64;
324 // Not the first stretch of the sound: a decoder's start-up is its own business.
325 if at < 2048 {
326 continue;
327 }
328 let Some(want) = reference.get(at as usize * 2..at as usize * 2 + 2) else { break };
329 worst = worst.max((ours[frame * 2] - want[0]).abs()).max((ours[frame * 2 + 1] - want[1]).abs());
330 compared += 1;
331 }
332 assert!(compared > frames / 2, "compared {compared} of {frames} frames");
333 worst
334}
335
336/// Every audio codec an AVI carries against ffmpeg's decode, from the top and from the
337/// middle; a seek is the sequential decode's samples; the probe row states the track.
338#[test]
339fn the_sound_is_ffmpegs_at_every_time() {
340 if !have(&["mjpeg", "libmp3lame", "mp2", "aac", "ac3", "pcm_s16le"]) {
341 return;
342 }
343 let dir = scratch("sound");
344 let cases: [(&str, &[&str], &str, f32); 5] = [
345 ("pcm", PCM, "pcm_s16le", 1e-6),
346 ("mp3", MP3, "mp3", 1.5e-3),
347 ("mp2", MP2, "mp2", 1.5e-3),
348 ("aac", AAC, "aac", 1.5e-3),
349 ("ac3", AC3, "ac3", 1.5e-3),
350 ];
351 for (name, acodec, codec, tolerance) in cases {
352 let path = make(&dir, &format!("{name}.avi"), CARD, Some(CHIRP), MJPEG, acodec);
353 let streams = AudioSession::probe_streams(&path).expect("streams");
354 assert_eq!(streams.len(), 1, "{name}");
355 let row = &streams[0];
356 assert!(row.decodable, "{name}: {row:?}");
357 assert_eq!((row.codec.as_str(), row.channels, row.sample_rate), (codec, 2, 48_000), "{name}");
358 let reference = ffmpeg_sound(&path, 48_000);
359 for from in [0.0, 0.4, 1.1, 1.7] {
360 let worst = compare(&path, from, 7_200, &reference);
361 eprintln!("{name} from {from}s: worst difference {worst:.6}");
362 assert!(worst <= tolerance, "{name} from {from}s: {worst}");
363 }
364 let (_, _, full) = sound(&path, 0, 0.0, 96_000 * 2);
365 let (_, _, cut) = sound(&path, 0, 1.3, 4_800);
366 let at = (1.3 * 48_000.0) as usize * 2;
367 let worst = cut.iter().zip(&full[at..]).map(|(a, b)| (a - b).abs()).fold(0f32, f32::max);
368 assert!(worst <= 1e-4, "{name}: a seek differs from sequential by {worst}");
369 }
370 let _ = std::fs::remove_dir_all(&dir);
371}
372
373fn first_loud(samples: &[f32], width: usize) -> Option<usize> {
374 samples.chunks(width).position(|f| f.iter().any(|s| s.abs() > 0.2))
375}
376
377fn flash_frame(frames: &[engine::decode::Frame]) -> Option<u32> {
378 frames
379 .iter()
380 .find(|f| f.bgra.chunks(4).map(|p| u64::from(p[1])).sum::<u64>() > 128 * (f.bgra.len() as u64 / 4))
381 .map(|f| f.index)
382}
383
384/// The flash is at 1.0 s in the picture and the beep at 1.0 s in the sound, after the open
385/// and after a seek, for the two B-frame codecs; the beep alone for MJPEG + PCM.
386#[test]
387fn picture_and_sound_stay_in_sync_from_any_start() {
388 if !have(&["libx264", "libmp3lame", "mpeg2video", "mp2", "mjpeg", "pcm_s16le"]) {
389 return;
390 }
391 let dir = scratch("sync");
392 let cases: [(&str, &[&str], &[&str]); 3] = [("h264", X264, MP3), ("mpeg2", MPEG2, MP2), ("mjpeg", MJPEG, PCM)];
393 for (name, vcodec, acodec) in cases {
394 let path = make(&dir, &format!("{name}.avi"), FLASH, Some(BEEP), vcodec, acodec);
395 let (rate, width, all) = sound(&path, 0, 0.0, 48_000 * 3);
396 let beep = first_loud(&all, width).expect("a beep") as f64 / f64::from(rate);
397 assert!(beep > 0.99 && beep < 1.0 + 0.065, "{name}: the beep is at {beep:.3} s");
398 let (_, _, tail) = sound(&path, 0, 0.8, 48_000);
399 let again = 0.8 + first_loud(&tail, width).expect("a beep after a seek") as f64 / f64::from(rate);
400 assert!((again - beep).abs() < 0.002, "{name}: {again} vs {beep}");
401 if name == "mjpeg" {
402 continue;
403 }
404 let frames = session_frames(&path);
405 assert_eq!(frames.len(), 60, "{name}");
406 let flash = flash_frame(&frames).expect("a flash");
407 assert_eq!(flash, 25, "{name}: the flash is at 1.0 s of the clip");
408 let (_, rx, _) = software(|| DecodeSession::open_at(&path, 25).map(|(m, rx, c)| (m, rx.into_iter().next(), c))).expect("seek");
409 assert_eq!(rx.map(|f| f.index), Some(25), "{name}");
410 }
411 let _ = std::fs::remove_dir_all(&dir);
412}
413
414// ------------------------------------------------------------------ export
415
416fn export_as(source: &Path, out: &Path, format: Format) {
417 let session = PlaybackSession::open(source).unwrap_or_else(|e| panic!("open {}: {e}", source.display()));
418 let settings = ExportSettings { format, ..Default::default() };
419 let handle = session.export_to_with(out, &settings);
420 let started = Instant::now();
421 while !handle.is_finished() {
422 assert!(started.elapsed() < Duration::from_secs(600), "the export did not finish in 600 s");
423 std::thread::sleep(Duration::from_millis(20));
424 }
425 handle.result().expect("an outcome").expect("the export");
426}
427
428/// An export of an AVI re-encodes, keeps its length and its frame count, and keeps the flash
429/// and the beep together.
430#[test]
431fn an_export_from_an_avi_keeps_its_length_its_frames_and_its_sync() {
432 if !have(&["libx264", "libmp3lame", "mpeg2video", "mp2"]) {
433 return;
434 }
435 let dir = scratch("export");
436 for (name, vcodec, acodec) in [("h264", X264, MP3), ("mpeg2", MPEG2, MP2)] {
437 let path = make(&dir, &format!("{name}.avi"), FLASH, Some(BEEP), vcodec, acodec);
438 let out = dir.join(format!("{name}.mp4"));
439 software(|| export_as(&path, &out, Format::Mp4));
440 let secs: f64 = ffprobe(&out, "format=duration", "v:0").parse().unwrap_or(0.0);
441 assert!((secs - 2.4).abs() < 0.1, "{name}: {secs} s");
442 let count: u32 = ffprobe(&out, "stream=nb_frames", "v:0").parse().unwrap_or(0);
443 assert!(count.abs_diff(60) <= 1, "{name}: {count} frames");
444 let video = Command::new("ffmpeg")
445 .args(["-v", "error", "-i"])
446 .arg(&out)
447 .args(["-an", "-vf", "scale=8:8,format=gray", "-fps_mode", "passthrough", "-f", "rawvideo", "-"])
448 .output()
449 .expect("ffmpeg");
450 let flash = video.stdout.chunks(64).position(|f| f.iter().map(|&b| u32::from(b)).sum::<u32>() > 128 * 64).expect("a flash");
451 let pcm = ffmpeg_sound(&out, 48_000);
452 let beep = pcm.chunks(2).position(|f| f.iter().any(|s| s.abs() > 0.2)).expect("a beep") as f64 / 48_000.0;
453 let flash_at = flash as f64 / FPS;
454 assert!((flash_at - 1.0).abs() < 0.045, "{name}: flash at {flash_at}");
455 assert!((beep - flash_at).abs() < 0.09, "{name}: beep {beep} vs flash {flash_at}");
456 }
457 let _ = std::fs::remove_dir_all(&dir);
458}
459
460// ------------------------------------------------------------------ refusals and sniffing
461
462/// What the crates refuse is still refused by name with the ffmpeg line, in the open error and
463/// in the probe: raw layouts `ec-riff` does not carry (1 bpp) and MS-MPEG4 version 1 (`MPG4`);
464/// with sound beside them the sound still opens. (DV, MPEG-4 Part 2, MS-MPEG4 version 2 and 3
465/// and the common raw layouts have decode seats: `tests/dvmpeg4.rs`, `tests/oldavi.rs`.)
466#[test]
467fn unreadable_raw_and_msmpeg4_v1_are_refused_by_name_and_the_sound_still_opens() {
468 if !have(&["rawvideo", "msmpeg4", "pcm_s16le"]) {
469 return;
470 }
471 let dir = scratch("refused");
472 // ffmpeg has no version 1 encoder: a version 3 file with its FourCC rewritten (in the
473 // stream header and the format chunk) is the same bitstream under the version 1 name.
474 let v1 = |from: &Path, name: &str| {
475 let mut bytes = std::fs::read(from).unwrap();
476 for at in 0..bytes.len().saturating_sub(4) {
477 if &bytes[at..at + 4] == b"DIV3" && at < 4096 {
478 bytes[at..at + 4].copy_from_slice(b"MPG4");
479 }
480 }
481 let out = dir.join(name);
482 std::fs::write(&out, bytes).unwrap();
483 out
484 };
485 let cases: [(&str, &[&str], &str); 2] = [
486 ("raw", &["-c:v", "rawvideo", "-pix_fmt", "monow"], "rawvideo"),
487 ("msmpeg4v1", &["-c:v", "msmpeg4", "-vtag", "DIV3"], "msmpeg4v1"),
488 ];
489 for (name, vcodec, word) in cases {
490 let mut silent = make(&dir, &format!("{name}.avi"), CARD, None, vcodec, &[]);
491 let mut with = make(&dir, &format!("{name}-pcm.avi"), CARD, Some(CHIRP), vcodec, PCM);
492 if name == "msmpeg4v1" {
493 silent = v1(&silent, "v1.avi");
494 with = v1(&with, "v1-pcm.avi");
495 }
496 let err = Demuxer::open(&silent).err().unwrap_or_else(|| panic!("{name}: opened")).to_string();
497 assert!(err.contains("ffmpeg -i") && err.contains("convert"), "{name}: {err}");
498 let why = engine::demux::picture_refusal(&silent).expect("a reason");
499 assert!(why.contains("ffmpeg"), "{name}: {why}");
500
501 let err = Demuxer::open(&with).err().unwrap_or_else(|| panic!("{name}: opened")).to_string();
502 assert!(err.contains("ffmpeg -i"), "{name}: {err}");
503 let facts = engine::probe_media(&with);
504 assert!(facts.video.is_none(), "{name}");
505 let first = facts.streams.first().expect("the refused picture is listed");
506 assert_eq!(first.codec_id.as_deref(), Some(word), "{name}: {:?}", facts.streams);
507 let streams = AudioSession::probe_streams(&with).expect("streams");
508 assert!(streams.len() == 1 && streams[0].decodable, "{name}: {streams:?}");
509 assert!(AudioSession::open(&with).expect("opens").is_some(), "{name}: the sound opens");
510 }
511 let _ = std::fs::remove_dir_all(&dir);
512}
513
514/// An AVI is recognised by its bytes under any name, and `.divx` by its name.
515#[test]
516fn an_avi_is_sniffed_whatever_it_is_called() {
517 if !have(&["mjpeg"]) {
518 return;
519 }
520 let dir = scratch("sniff");
521 let path = make(&dir, "x.avi", CARD, None, MJPEG, &[]);
522 let odd = dir.join("recording.dat");
523 std::fs::copy(&path, &odd).unwrap();
524 let divx = dir.join("clip.divx");
525 std::fs::copy(&path, &divx).unwrap();
526 assert!(engine::demux::is_avi(&path) && engine::demux::is_avi(&odd) && engine::demux::is_avi(&divx));
527 assert_eq!(Demuxer::open(&odd).expect("opens by content").0.frame_count, 50);
528 assert!(!engine::demux::is_avi(Path::new("/nonexistent/song.mp3")));
529 let wav = dir.join("x.wav");
530 ffmpeg(&["-f", "lavfi", "-i", CHIRP, s(&wav)]);
531 assert!(!engine::demux::is_avi(&wav));
532 let _ = std::fs::remove_dir_all(&dir);
533}