forge
Explore
Log in

Don't you dare go Hollow

edith

Clone
★ 0

0 watching0 forksRust18.3 MiBff99ad6Tahinli6 days ago1055 commits

h264_high10.rs258 lines, 10.8 KiBHistoryRawDownload
1//! H.264 High 10 (4:2:0 progressive, 10-bit) end to end: what the container
2//! probe reports, that `ec-h264`'s I010 pictures are ffmpeg's `yuv420p10le`
3//! byte for byte, that a software seek lands on the bytes a linear decode gave,
4//! and that a 10-bit export of such a source stays 10-bit. (4:4:4 and
5//! monochrome live in `h264_hi444.rs`.)
6//!
7//! The clips are synthetic (`testsrc2`) and encoded by ffmpeg's libx264 into the
8//! temp dir; without ffmpeg and libx264 each test says so and passes.
9//!
10//! `VE_SW` is process-wide, so every test that pins it holds [`SW`].
11
12use std::path::{Path, PathBuf};
13use std::process::Command;
14use std::sync::Mutex;
15use std::time::{Duration, Instant};
16
17use ec_core::registry::{CodecId, CodecParameters, Decoder as _};
18use ec_core::{Packet, TimeBase};
19use ec_h264::H264Decoder;
20use engine::PlaybackSession;
21use engine::decode::{Backend, DecodeSession, probe};
22use engine::demux::{Codec, Demuxer};
23use engine::export::{ExportSettings, Format};
24
25const W: usize = 352;
26const H: usize = 288;
27const FRAMES: u32 = 30;
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_x264() -> bool {
40 let tool = |t: &str, a: &str| Command::new(t).arg(a).output().is_ok_and(|o| o.status.success());
41 if !tool("ffmpeg", "-version") || !tool("ffprobe", "-version") {
42 return false;
43 }
44 Command::new("ffmpeg")
45 .args(["-hide_banner", "-encoders"])
46 .output()
47 .is_ok_and(|o| String::from_utf8_lossy(&o.stdout).contains("libx264"))
48}
49
50fn scratch(name: &str) -> PathBuf {
51 let dir = std::env::temp_dir().join(format!("edith-{name}-{}", std::process::id()));
52 let _ = std::fs::remove_dir_all(&dir);
53 std::fs::create_dir_all(&dir).expect("scratch directory");
54 dir
55}
56
57/// A 30-frame libx264 clip of `pix_fmt` at `profile`, with B pictures and a sync
58/// point every 10 pictures, so a seek lands mid-GOP.
59fn make(dir: &Path, name: &str, source: &str, profile: &str, pix_fmt: &str) -> PathBuf {
60 let path = dir.join(name);
61 let out = Command::new("ffmpeg")
62 .args(["-v", "error", "-y", "-f", "lavfi", "-i"])
63 .arg(format!("{source}=size={W}x{H}:rate=30"))
64 .args(["-frames:v", "30", "-c:v", "libx264", "-profile:v", profile])
65 .args(["-pix_fmt", pix_fmt, "-x264-params", "keyint=10:min-keyint=10:bframes=2"])
66 .arg(&path)
67 .output()
68 .expect("run ffmpeg");
69 assert!(out.status.success(), "ffmpeg: {}", String::from_utf8_lossy(&out.stderr));
70 path
71}
72
73fn ffprobe_field(path: &Path, field: &str) -> String {
74 let out = Command::new("ffprobe")
75 .args(["-v", "error", "-select_streams", "v:0", "-show_entries"])
76 .arg(format!("stream={field}"))
77 .args(["-of", "csv=p=0"])
78 .arg(path)
79 .output()
80 .expect("ffprobe runs");
81 assert!(out.status.success(), "ffprobe reads {}", path.display());
82 String::from_utf8_lossy(&out.stdout).trim().to_owned()
83}
84
85fn ffmpeg_raw(path: &Path, pix_fmt: &str) -> Vec<u8> {
86 let out = Command::new("ffmpeg")
87 .args(["-v", "error", "-i"])
88 .arg(path)
89 .args(["-an", "-fps_mode", "passthrough", "-f", "rawvideo", "-pix_fmt", pix_fmt, "-"])
90 .output()
91 .expect("ffmpeg runs");
92 assert!(out.status.success(), "ffmpeg: {}", String::from_utf8_lossy(&out.stderr));
93 out.stdout
94}
95
96fn clips(dir: &Path) -> Vec<(PathBuf, &'static str)> {
97 vec![
98 (make(dir, "t.mp4", "testsrc2", "high10", "yuv420p10le"), "testsrc2 mp4"),
99 (make(dir, "t.mkv", "testsrc2", "high10", "yuv420p10le"), "testsrc2 mkv"),
100 (make(dir, "m.mp4", "mandelbrot", "high10", "yuv420p10le"), "mandelbrot mp4"),
101 (make(dir, "m.mkv", "mandelbrot", "high10", "yuv420p10le"), "mandelbrot mkv"),
102 ]
103}
104
105#[test]
106fn high_10_opens_and_probes_at_ten_bits() {
107 if !have_x264() {
108 eprintln!("no ffmpeg with libx264: skipping");
109 return;
110 }
111 let dir = scratch("h264hi10-probe");
112 for (clip, what) in clips(&dir) {
113 let (meta, demuxer) = Demuxer::open(&clip).unwrap_or_else(|e| panic!("{what}: {e}"));
114 assert_eq!(meta.codec, Codec::H264, "{what}");
115 assert_eq!((meta.width as usize, meta.height as usize), (W, H), "{what}");
116 assert_eq!(meta.frame_count, FRAMES, "{what}");
117 assert_eq!(demuxer.bit_depth(), 10, "{what}: bit depth off the SPS");
118 assert_eq!(demuxer.profile(), Some("High 10"), "{what}");
119 // The GPU has no High 10 profile: the probe names the software seat even
120 // with the plugin free to take it.
121 let (codec, backend) = probe(&clip).expect("probe");
122 assert_eq!((codec, backend), (Some(Codec::H264), Backend::Software), "{what}");
123 let facts = engine::demux::probe_media(&clip).video.map(|f| f.bit_depth);
124 assert_eq!(facts, Some(Some(10)), "{what}: the media facts say 10 bits");
125 }
126 let _ = std::fs::remove_dir_all(&dir);
127}
128
129#[test]
130fn ec_h264_pictures_are_ffmpegs_yuv420p10le_exactly() {
131 if !have_x264() {
132 eprintln!("no ffmpeg with libx264: skipping");
133 return;
134 }
135 let dir = scratch("h264hi10-exact");
136 for (clip, what) in clips(&dir) {
137 let want = ffmpeg_raw(&clip, "yuv420p10le");
138 let (_, mut demuxer) = Demuxer::open(&clip).expect("open");
139 demuxer.seek_to_sync_at_or_before(0);
140 let mut decoder = H264Decoder::new(CodecParameters::new(CodecId::H264)).expect("decoder");
141 let mut got = Vec::new();
142 let take = |decoder: &mut H264Decoder, got: &mut Vec<u8>| {
143 while let Ok(frame) = decoder.receive_frame() {
144 let ec_core::frame::Frame::Video(pic) = frame else { continue };
145 assert_eq!(pic.format, ec_core::frame::PixelFormat::I010, "{what}");
146 for plane in &pic.planes {
147 got.extend_from_slice(&plane.data);
148 }
149 }
150 };
151 while let Some(au) = demuxer.next_access_unit().expect("demux") {
152 decoder.send_packet(&Packet::new(0, TimeBase::new(1, 1), au)).expect("decode");
153 take(&mut decoder, &mut got);
154 }
155 decoder.flush().expect("flush");
156 take(&mut decoder, &mut got);
157 assert_eq!(got.len(), want.len(), "{what}: every picture");
158 assert!(got == want, "{what}: pictures differ from ffmpeg's yuv420p10le");
159 }
160 let _ = std::fs::remove_dir_all(&dir);
161}
162
163#[test]
164fn software_seeks_land_on_the_bytes_of_a_sequential_decode() {
165 if !have_x264() {
166 eprintln!("no ffmpeg with libx264: skipping");
167 return;
168 }
169 let dir = scratch("h264hi10-seek");
170 for (clip, what) in clips(&dir) {
171 let (meta, all) = software(|| {
172 let (meta, rx) = DecodeSession::open(&clip).expect("open");
173 (meta, rx.into_iter().collect::<Vec<_>>())
174 });
175 assert_eq!(meta.codec, Codec::H264, "{what}");
176 assert_eq!(
177 all.iter().map(|f| f.index).collect::<Vec<_>>(),
178 (0..FRAMES).collect::<Vec<_>>(),
179 "{what}: display order"
180 );
181 let first = &all[0].bgra;
182 assert!(
183 first.as_chunks::<4>().0.iter().any(|px| px[..] != first[..4]),
184 "{what}: frame 0 is a single colour"
185 );
186 for target in [1, 5, 9, 10, 13, 17, 25, FRAMES - 1] {
187 let seeked = software(|| {
188 let (_, rx, _cancel) = DecodeSession::open_at(&clip, target).expect("open_at");
189 rx.into_iter().next().unwrap_or_else(|| panic!("{what}: no frame after seek to {target}"))
190 });
191 assert_eq!(seeked.index, target, "{what}");
192 assert!(seeked.bgra == all[target as usize].bgra, "{what}: seek to {target} differs");
193 }
194 }
195 let _ = std::fs::remove_dir_all(&dir);
196}
197
198fn psnr_10(a: &[u8], b: &[u8]) -> f64 {
199 assert_eq!(a.len(), b.len(), "the same number of samples");
200 let mut squared = 0f64;
201 for (x, y) in a.as_chunks::<2>().0.iter().zip(b.as_chunks::<2>().0) {
202 let d = f64::from(u16::from_le_bytes(*x)) - f64::from(u16::from_le_bytes(*y));
203 squared += d * d;
204 }
205 if squared == 0.0 {
206 return f64::INFINITY;
207 }
208 10.0 * (1023.0f64 * 1023.0 * (a.len() / 2) as f64 / squared).log10()
209}
210
211fn export_as(source: &Path, out: &Path, format: Format, depth: Option<u8>) {
212 let session = PlaybackSession::open(source).unwrap_or_else(|e| panic!("open {}: {e}", source.display()));
213 let settings = ExportSettings { format, video_bit_depth: depth, ..Default::default() };
214 let handle = session.export_to_with(out, &settings);
215 let started = Instant::now();
216 while !handle.is_finished() {
217 assert!(started.elapsed() < Duration::from_secs(600), "the export did not finish in 600 s");
218 std::thread::sleep(Duration::from_millis(20));
219 }
220 handle.result().expect("an outcome").expect("the export");
221}
222
223#[test]
224fn a_high_10_source_exports_ten_bit() {
225 if !have_x264() {
226 eprintln!("no ffmpeg with libx264: skipping");
227 return;
228 }
229 let dir = scratch("h264hi10-export");
230 let frame_bytes = W * H * 3;
231 for (src, source_ext) in [("t.mp4", "mp4"), ("t.mkv", "mkv")] {
232 let source = make(&dir, src, "testsrc2", "high10", "yuv420p10le");
233 let reference = ffmpeg_raw(&source, "yuv420p10le");
234 for (format, ext) in [(Format::Hevc, "mkv"), (Format::HevcMp4, "mp4")] {
235 let ten = dir.join(format!("ten-{source_ext}.{ext}"));
236 export_as(&source, &ten, format, Some(10));
237 assert_eq!(ffprobe_field(&ten, "pix_fmt"), "yuv420p10le", "{source_ext}->{ext}: 10-bit");
238 let ten_decoded = ffmpeg_raw(&ten, "yuv420p10le");
239 assert_eq!(ten_decoded.len(), reference.len(), "{source_ext}->{ext}: every picture");
240 assert_eq!(ten_decoded.len() / frame_bytes, FRAMES as usize);
241 let psnr_ten = psnr_10(&reference, &ten_decoded);
242
243 let eight = dir.join(format!("eight-{source_ext}.{ext}"));
244 export_as(&source, &eight, format, Some(8));
245 assert_eq!(ffprobe_field(&eight, "pix_fmt"), "yuv420p", "{source_ext}->{ext}: 8-bit");
246 let psnr_eight = psnr_10(&reference, &ffmpeg_raw(&eight, "yuv420p10le"));
247 eprintln!("h264 high10 {source_ext}->{ext}: 10-bit {psnr_ten:.2} dB, 8-bit {psnr_eight:.2} dB");
248 assert!(psnr_ten > 30.0, "{source_ext}->{ext}: {psnr_ten:.2} dB against the source");
249 assert!(psnr_ten > psnr_eight, "{source_ext}->{ext}: 10-bit {psnr_ten:.2} <= 8-bit {psnr_eight:.2}");
250
251 // Unset: the source's own depth decides.
252 let auto = dir.join(format!("auto-{source_ext}.{ext}"));
253 export_as(&source, &auto, format, None);
254 assert_eq!(ffprobe_field(&auto, "pix_fmt"), "yuv420p10le", "{source_ext}->{ext}: default follows the source");
255 }
256 }
257 let _ = std::fs::remove_dir_all(&dir);
258}