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