forge
Explore
Log in

Don't you dare go Hollow

edith_codecs

Clone
★ 0

0 watching0 forksRust370.3 MiB9b67700Tahinli3 days ago4021 commits

hw_parity.rs466 lines, 14.6 KiBHistoryRawDownload
1//! Vulkan Video against VA-API on the same clips: H.264, HEVC and AV1 encode at three CQP and three CBR points, reporting bytes, kbps, PSNR-Y against the source and encode ms/frame; then decode ms/frame of the CBR 3 Mb/s streams with both decoders.
2//!
3//! Every encode and decode runs in a child process of this binary, because the driver's state outlives a display: within one process the same encode lands at different sizes depending on what ran before it.
4//!
5//! ```text
6//! cargo run --release -p ec-hw --example hw_parity -- <scratch dir>
7//! ```
8
9use std::fmt::Display;
10use std::fs;
11use std::os::unix::fs::FileExt;
12use std::path::{Path, PathBuf};
13use std::process::Command;
14use std::time::Instant;
15
16use ec_hw::{
17 Backend, Codec, EncCodec, EncoderConfig, FrameMetadata, HwDecoder, HwEncoder, I420,
18 RateControlMode,
19};
20
21const FRAMES: usize = 60;
22const FPS: u32 = 30;
23const GOP: u32 = 30;
24const SIZES: [(u32, u32); 2] = [(1280, 720), (1920, 1080)];
25const SOURCES: [&str; 2] = ["testsrc2", "mandelbrot"];
26const CBR: [u32; 3] = [1_000_000, 3_000_000, 6_000_000];
27const DECODE_BITRATE: u32 = 3_000_000;
28const JOB: &str = "HW_PARITY_JOB";
29
30#[derive(Clone, Copy)]
31enum Mode {
32 Cqp(u32),
33 Cbr(u32),
34}
35
36impl Mode {
37 fn label(self) -> String {
38 match self {
39 Mode::Cqp(qp) => format!("CQP {qp}"),
40 Mode::Cbr(bps) => format!("CBR {}M", bps / 1_000_000),
41 }
42 }
43
44 fn env(self) -> (&'static str, u32) {
45 match self {
46 Mode::Cqp(qp) => ("cqp", qp),
47 Mode::Cbr(bps) => ("cbr", bps),
48 }
49 }
50}
51
52#[derive(Clone, Copy)]
53struct Spec {
54 name: &'static str,
55 key: &'static str,
56 format: &'static str,
57 enc: EncCodec,
58 dec: Codec,
59}
60
61const SPECS: [Spec; 3] = [
62 Spec {
63 name: "H.264",
64 key: "h264",
65 format: "h264",
66 enc: EncCodec::H264,
67 dec: Codec::H264,
68 },
69 Spec {
70 name: "HEVC",
71 key: "hevc",
72 format: "hevc",
73 enc: EncCodec::H265,
74 dec: Codec::H265,
75 },
76 Spec {
77 name: "AV1",
78 key: "av1",
79 format: "obu",
80 enc: EncCodec::Av1,
81 dec: Codec::Av1,
82 },
83];
84
85fn modes(spec: Spec) -> Vec<Mode> {
86 let qps = if spec.key == "av1" {
87 [110, 135, 160]
88 } else {
89 [22, 27, 32]
90 };
91 qps.into_iter()
92 .map(Mode::Cqp)
93 .chain(CBR.into_iter().map(Mode::Cbr))
94 .collect()
95}
96
97fn backend_key(backend: Backend) -> &'static str {
98 match backend {
99 Backend::Vk => "vk",
100 Backend::Va => "va",
101 }
102}
103
104fn backend_from_key(key: &str) -> Backend {
105 match key {
106 "vk" => Backend::Vk,
107 _ => Backend::Va,
108 }
109}
110
111fn spec_from_key(key: &str) -> Spec {
112 *SPECS.iter().find(|s| s.key == key).expect("known codec key")
113}
114
115fn make_source(dir: &Path, source: &str, w: u32, h: u32) -> PathBuf {
116 let path = dir.join(format!("{source}-{w}x{h}.yuv"));
117 if !path.exists() {
118 let status = Command::new("ffmpeg")
119 .args(["-nostdin", "-v", "error", "-y", "-f", "lavfi", "-i"])
120 .arg(format!("{source}=size={w}x{h}:rate={FPS}"))
121 .args(["-frames:v", &FRAMES.to_string(), "-pix_fmt", "yuv420p", "-f", "rawvideo"])
122 .arg(&path)
123 .status()
124 .expect("run ffmpeg");
125 assert!(status.success(), "ffmpeg cannot generate {source}");
126 }
127 path
128}
129
130fn read_frames(path: &Path, w: u32, h: u32) -> Vec<I420> {
131 let (wu, hu) = (w as usize, h as usize);
132 let (cw, ch) = (wu / 2, hu / 2);
133 let file = fs::File::open(path).expect("source clip");
134 (0..FRAMES as u64)
135 .map(|t| {
136 let len = wu * hu + 2 * cw * ch;
137 let mut buf = vec![0u8; len];
138 file.read_exact_at(&mut buf, t * len as u64)
139 .expect("read picture");
140 let (y, rest) = buf.split_at(wu * hu);
141 let (u, v) = rest.split_at(cw * ch);
142 I420 {
143 y: y.to_vec(),
144 u: u.to_vec(),
145 v: v.to_vec(),
146 width: w,
147 height: h,
148 }
149 })
150 .collect()
151}
152
153fn write_aus(path: &Path, aus: &[Vec<u8>]) {
154 let mut out = Vec::new();
155 for au in aus {
156 out.extend_from_slice(&(au.len() as u32).to_le_bytes());
157 out.extend_from_slice(au);
158 }
159 fs::write(path, out).expect("write access units");
160}
161
162fn read_aus(path: &Path) -> Vec<Vec<u8>> {
163 let data = fs::read(path).expect("read access units");
164 let mut aus = Vec::new();
165 let mut at = 0;
166 while at + 4 <= data.len() {
167 let len = u32::from_le_bytes(data[at..at + 4].try_into().expect("4 bytes")) as usize;
168 aus.push(data[at + 4..at + 4 + len].to_vec());
169 at += 4 + len;
170 }
171 aus
172}
173
174fn or_exit<T, E: Display>(result: Result<T, E>) -> T {
175 match result {
176 Ok(value) => value,
177 Err(e) => {
178 println!("ERR {e}");
179 std::process::exit(3)
180 }
181 }
182}
183
184fn encode_job() {
185 let env = |k: &str| std::env::var(k).expect("job variable");
186 let num = |k: &str| env(k).parse::<u32>().expect("job number");
187 let spec = spec_from_key(&env("CODEC"));
188 let (w, h) = (num("W"), num("H"));
189 let backend = backend_from_key(&env("BACKEND"));
190 let value = num("VALUE");
191 let mode = if env("MODE") == "cqp" {
192 Mode::Cqp(value)
193 } else {
194 Mode::Cbr(value)
195 };
196 let frames = read_frames(Path::new(&env("SOURCE")), w, h);
197 let mut config = EncoderConfig::new(spec.enc, w, h);
198 config.framerate = (FPS, 1);
199 config.gop_size = GOP;
200 match mode {
201 Mode::Cqp(qp) => config.rate_control = RateControlMode::ConstantQp { qp },
202 Mode::Cbr(bps) => {
203 config.bitrate = bps;
204 config.rate_control = RateControlMode::ConstantBitrate;
205 }
206 }
207 let mut encoder = or_exit(HwEncoder::open(config, Some(backend)));
208 let mut aus = Vec::with_capacity(frames.len());
209 let start = Instant::now();
210 for (t, frame) in frames.iter().enumerate() {
211 let coded = or_exit(encoder.encode(
212 frame,
213 FrameMetadata {
214 timestamp: t as i64,
215 force_keyframe: false,
216 },
217 ));
218 aus.push(coded.data);
219 }
220 let ms = start.elapsed().as_secs_f64() * 1000.0 / frames.len() as f64;
221 write_aus(Path::new(&env("OUT")), &aus);
222 println!("ENC ms={ms:.3} backend={:?}", encoder.backend());
223}
224
225fn decode_job() {
226 let env = |k: &str| std::env::var(k).expect("job variable");
227 let spec = spec_from_key(&env("CODEC"));
228 let backend = backend_from_key(&env("BACKEND"));
229 let aus = read_aus(Path::new(&env("AUS")));
230 let mut frames = 0usize;
231 let elapsed = match backend {
232 Backend::Vk => {
233 let mut decoder = or_exit(HwDecoder::open(spec.dec));
234 if decoder.backend() != Backend::Vk {
235 println!("ERR opened on {:?}", decoder.backend());
236 std::process::exit(3)
237 }
238 let start = Instant::now();
239 for (t, au) in aus.iter().enumerate() {
240 or_exit(decoder.decode(au, t as i64));
241 while or_exit(decoder.next_frame()).is_some() {
242 frames += 1;
243 }
244 }
245 or_exit(decoder.flush());
246 while or_exit(decoder.next_frame()).is_some() {
247 frames += 1;
248 }
249 start.elapsed()
250 }
251 Backend::Va => {
252 let display = or_exit(ec_va::open());
253 let mut decoder = or_exit(ec_hw::Decoder::new(&display, spec.dec));
254 let start = Instant::now();
255 for (t, au) in aus.iter().enumerate() {
256 or_exit(decoder.decode(au, t as i64));
257 while let Some(frame) = decoder.next_frame() {
258 or_exit(frame.to_i420());
259 frames += 1;
260 }
261 }
262 or_exit(decoder.flush());
263 while let Some(frame) = decoder.next_frame() {
264 or_exit(frame.to_i420());
265 frames += 1;
266 }
267 start.elapsed()
268 }
269 };
270 if frames != FRAMES {
271 println!("ERR decoded {frames} of {FRAMES} frames");
272 std::process::exit(3)
273 }
274 println!("DEC ms={:.3}", elapsed.as_secs_f64() * 1000.0 / FRAMES as f64);
275}
276
277fn run_job(me: &Path, envs: &[(&str, String)]) -> Result<String, String> {
278 let output = Command::new(me)
279 .envs(envs.iter().map(|(k, v)| (*k, v.as_str())))
280 .output()
281 .expect("run child job");
282 let stdout = String::from_utf8_lossy(&output.stdout).into_owned();
283 if output.status.success() {
284 Ok(stdout)
285 } else {
286 let reason = stdout
287 .lines()
288 .rev()
289 .find(|l| l.starts_with("ERR"))
290 .unwrap_or("child failed")
291 .to_string();
292 Err(reason)
293 }
294}
295
296fn field(out: &str, key: &str) -> Option<f64> {
297 out.lines()
298 .find_map(|l| l.strip_prefix(key))
299 .and_then(|rest| rest.split_whitespace().next())
300 .and_then(|v| v.parse().ok())
301}
302
303fn psnr_y(stream: &Path, format: &str, source: &Path, (w, h): (u32, u32)) -> Option<f64> {
304 let rate = FPS.to_string();
305 let size = format!("{w}x{h}");
306 let out = Command::new("ffmpeg")
307 .args(["-nostdin", "-v", "info", "-f", format, "-r", &rate, "-i"])
308 .arg(stream)
309 .args(["-f", "rawvideo", "-pix_fmt", "yuv420p", "-s", &size, "-r", &rate, "-i"])
310 .arg(source)
311 .args(["-lavfi", "psnr", "-f", "null", "-"])
312 .output()
313 .ok()?;
314 let text = String::from_utf8_lossy(&out.stderr);
315 let at = text.rfind("PSNR y:")?;
316 text[at + "PSNR y:".len()..]
317 .split_whitespace()
318 .next()?
319 .parse::<f64>()
320 .ok()
321 .filter(|v| !v.is_nan())
322}
323
324struct Row {
325 bytes: usize,
326 ms: f64,
327 psnr: Option<f64>,
328}
329
330fn encode_row(
331 me: &Path,
332 dir: &Path,
333 tag: &str,
334 raw: &Path,
335 (w, h): (u32, u32),
336 spec: Spec,
337 mode: Mode,
338 backend: Backend,
339) -> Result<(Row, PathBuf), String> {
340 let (mode_key, value) = mode.env();
341 let aus_path = dir.join(format!("{tag}.aus"));
342 let out = run_job(
343 me,
344 &[
345 (JOB, "enc".to_string()),
346 ("CODEC", spec.key.to_string()),
347 ("W", w.to_string()),
348 ("H", h.to_string()),
349 ("BACKEND", backend_key(backend).to_string()),
350 ("MODE", mode_key.to_string()),
351 ("VALUE", value.to_string()),
352 ("SOURCE", raw.display().to_string()),
353 ("OUT", aus_path.display().to_string()),
354 ],
355 )?;
356 let ms = field(&out, "ENC ms=").ok_or("no timing from encode job")?;
357 let aus = read_aus(&aus_path);
358 let stream = dir.join(format!("{tag}.{}", spec.format));
359 fs::write(&stream, aus.concat()).expect("write stream");
360 let row = Row {
361 bytes: aus.iter().map(Vec::len).sum(),
362 ms,
363 psnr: psnr_y(&stream, spec.format, raw, (w, h)),
364 };
365 Ok((row, aus_path))
366}
367
368fn decode_ms(me: &Path, aus: &Path, spec: Spec, backend: Backend) -> Result<f64, String> {
369 let out = run_job(
370 me,
371 &[
372 (JOB, "dec".to_string()),
373 ("CODEC", spec.key.to_string()),
374 ("BACKEND", backend_key(backend).to_string()),
375 ("AUS", aus.display().to_string()),
376 ],
377 )?;
378 field(&out, "DEC ms=").ok_or_else(|| "no timing from decode job".to_string())
379}
380
381fn cell(v: Option<f64>, digits: usize) -> String {
382 match v {
383 Some(v) => format!("{v:.digits$}"),
384 None => "n/a".to_string(),
385 }
386}
387
388fn main() {
389 if let Ok(job) = std::env::var(JOB) {
390 match job.as_str() {
391 "enc" => encode_job(),
392 _ => decode_job(),
393 }
394 return;
395 }
396 let dir = PathBuf::from(std::env::args().nth(1).expect("scratch dir argument"));
397 let me = std::env::current_exe().expect("own path");
398 let mut decode_inputs: Vec<(&'static str, (u32, u32), Spec, Backend, PathBuf)> = Vec::new();
399
400 for source in SOURCES {
401 for (w, h) in SIZES {
402 let raw = make_source(&dir, source, w, h);
403 println!("== {source} {w}x{h}, {FRAMES} frames at {FPS} fps ==");
404 println!(
405 "{:<6} {:<8} {:<4} {:>9} {:>7} {:>8} {:>9}",
406 "codec", "rc", "enc", "bytes", "kbps", "PSNR-Y", "ms/frame"
407 );
408 for spec in SPECS {
409 for mode in modes(spec) {
410 for backend in [Backend::Vk, Backend::Va] {
411 let tag = format!(
412 "{source}-{w}x{h}-{}-{}-{}",
413 spec.key,
414 mode.label().replace(' ', ""),
415 backend_key(backend)
416 );
417 let label = mode.label();
418 let name = format!("{backend:?}");
419 match encode_row(&me, &dir, &tag, &raw, (w, h), spec, mode, backend) {
420 Ok((row, aus)) => {
421 let kbps = row.bytes as f64 * 8.0 * f64::from(FPS) / FRAMES as f64 / 1000.0;
422 println!(
423 "{:<6} {:<8} {:<4} {:>9} {:>7.0} {:>8} {:>9.2}",
424 spec.name,
425 label,
426 name,
427 row.bytes,
428 kbps,
429 cell(row.psnr, 2),
430 row.ms
431 );
432 if matches!(mode, Mode::Cbr(b) if b == DECODE_BITRATE) {
433 decode_inputs.push((source, (w, h), spec, backend, aus));
434 }
435 }
436 Err(reason) => println!(
437 "{:<6} {:<8} {:<4} n/a: {reason}",
438 spec.name, label, name
439 ),
440 }
441 }
442 }
443 }
444 println!();
445 }
446 }
447
448 println!("== decode, CBR {}M streams, ms/frame ==", DECODE_BITRATE / 1_000_000);
449 println!(
450 "{:<6} {:<10} {:<9} {:<4} {:>10} {:>10}",
451 "codec", "source", "res", "enc", "Vk dec", "VA dec"
452 );
453 for (source, (w, h), spec, enc_backend, aus) in &decode_inputs {
454 let vk = decode_ms(&me, aus, *spec, Backend::Vk);
455 let va = decode_ms(&me, aus, *spec, Backend::Va);
456 println!(
457 "{:<6} {:<10} {:<9} {:<4} {:>10} {:>10}",
458 spec.name,
459 source,
460 format!("{w}x{h}"),
461 format!("{enc_backend:?}"),
462 cell(vk.ok(), 2),
463 cell(va.ok(), 2)
464 );
465 }
466}