forge
Explore
Log in

Don't you dare go Hollow

edith_codecs

Clone
★ 0

0 watching0 forksRust370.3 MiB9b67700Tahinli3 days ago4021 commits

bench.rs392 lines, 13.2 KiBHistoryRawDownload
1//! VA-API bench for ec-hw (lane benchhw, DONE.md gate G6). Local GPU only.
2//!
3//! Drives the same public API engine-hw's callers use: `Decoder::new` /
4//! `decode` / `next_frame` / `flush`, and `Encoder::new` / `encode`.
5//!
6//! ```text
7//! bench dec <h264|hevc|vp9|av1> <stream> [--out FILE] [--runs N]
8//! bench enc <h264|hevc> <raw-yuv420p> <width> <height> <frames> <bitrate> [--out FILE] [--runs N]
9//! ```
10//!
11//! `dec` splits an elementary stream (Annex B for H.264/HEVC, IVF for VP9/AV1) into access
12//! units. Each timed run decodes the whole stream and waits for the GPU on every picture
13//! (`Surface::sync`) before dropping it, so the time covers the GPU work and not only the
14//! submission. The readback is not timed. With `--out`, one extra untimed pass writes every
15//! picture as planar I420 (8-bit bytes, or 10-bit little-endian u16) for the md5 check.
16//!
17//! `enc` reads `frames` pictures from a raw 8-bit 4:2:0 file. Only the `encode` calls are
18//! timed. `--out` writes the coded stream of the last run.
19//!
20//! Each run prints one `key=value` line; the best run is the one with the least time.
21
22use std::fs::File;
23use std::io::{BufWriter, Read, Write};
24use std::process::ExitCode;
25use std::time::{Duration, Instant};
26
27use ec_hw::{
28 Codec, Decoder, EncCodec, Encoder, EncoderConfig, FrameMetadata, I420, RateControlMode,
29};
30use ec_va::Display;
31
32/// Media seconds per frame: every clip in the bench is 30 pictures per second.
33const FPS: f64 = 30.0;
34
35fn main() -> ExitCode {
36 match run() {
37 Ok(()) => ExitCode::SUCCESS,
38 Err(e) => {
39 eprintln!("bench: {e}");
40 ExitCode::FAILURE
41 }
42 }
43}
44
45fn run() -> Result<(), String> {
46 let args: Vec<String> = std::env::args().skip(1).collect();
47 let (pos, opts) = split_args(&args)?;
48 let runs: usize = opts.runs.unwrap_or(5);
49 let display = ec_va::open().map_err(|e| format!("no VA display: {e}"))?;
50 match pos.first().map(String::as_str) {
51 Some("dec") if pos.len() == 3 => {
52 let codec = parse_codec(&pos[1])?;
53 let data = std::fs::read(&pos[2]).map_err(|e| format!("{}: {e}", pos[2]))?;
54 bench_dec(&display, codec, &data, runs, opts.out.as_deref())
55 }
56 Some("enc") if pos.len() == 7 => {
57 let codec = match pos[1].as_str() {
58 "h264" => EncCodec::H264,
59 "hevc" => EncCodec::H265,
60 other => return Err(format!("encode codec {other}: want h264 or hevc")),
61 };
62 let num = |i: usize| -> Result<u32, String> {
63 pos[i].parse().map_err(|_| format!("bad number {}", pos[i]))
64 };
65 let (w, h, frames, bitrate) = (num(3)?, num(4)?, num(5)? as usize, num(6)?);
66 bench_enc(
67 &display,
68 codec,
69 &pos[2],
70 w,
71 h,
72 frames,
73 bitrate,
74 runs,
75 opts.out.as_deref(),
76 )
77 }
78 _ => Err(usage()),
79 }
80}
81
82fn usage() -> String {
83 "usage: bench dec <h264|hevc|vp9|av1> <stream> [--out FILE] [--runs N]\n \
84 bench enc <h264|hevc> <raw-yuv420p> <w> <h> <frames> <bitrate> [--out FILE] [--runs N]"
85 .to_string()
86}
87
88#[derive(Default)]
89struct Opts {
90 out: Option<String>,
91 runs: Option<usize>,
92}
93
94fn split_args(args: &[String]) -> Result<(Vec<String>, Opts), String> {
95 let mut pos = Vec::new();
96 let mut opts = Opts::default();
97 let mut it = args.iter();
98 while let Some(a) = it.next() {
99 match a.as_str() {
100 "--out" => opts.out = Some(it.next().ok_or("--out needs a path")?.clone()),
101 "--runs" => {
102 let v = it.next().ok_or("--runs needs a number")?;
103 opts.runs = Some(v.parse().map_err(|_| format!("bad --runs {v}"))?);
104 }
105 _ => pos.push(a.clone()),
106 }
107 }
108 Ok((pos, opts))
109}
110
111fn parse_codec(s: &str) -> Result<Codec, String> {
112 match s {
113 "h264" => Ok(Codec::H264),
114 "hevc" => Ok(Codec::H265),
115 "vp9" => Ok(Codec::Vp9),
116 "av1" => Ok(Codec::Av1),
117 other => Err(format!("unknown codec {other}")),
118 }
119}
120
121// ---------------------------------------------------------------------------------------------
122// Decode
123// ---------------------------------------------------------------------------------------------
124
125/// Decode the whole stream once, waiting on the GPU for each picture. Returns the picture count
126/// and the time spent (demux splitting is excluded).
127fn decode_timed(
128 display: &std::rc::Rc<Display>,
129 codec: Codec,
130 units: &[&[u8]],
131) -> Result<(usize, Duration), String> {
132 let mut decoder = Decoder::new(display, codec).map_err(|e| e.to_string())?;
133 let mut count = 0usize;
134 let start = Instant::now();
135 for (i, unit) in units.iter().enumerate() {
136 decoder
137 .decode(unit, i as i64)
138 .map_err(|e| format!("decode unit {i}: {e}"))?;
139 while let Some(frame) = decoder.next_frame() {
140 frame.surface().sync().map_err(|e| e.to_string())?;
141 count += 1;
142 }
143 }
144 decoder.flush().map_err(|e| e.to_string())?;
145 while let Some(frame) = decoder.next_frame() {
146 frame.surface().sync().map_err(|e| e.to_string())?;
147 count += 1;
148 }
149 Ok((count, start.elapsed()))
150}
151
152/// Decode with readback and write every picture as planar I420 (the check output).
153fn decode_dump(
154 display: &std::rc::Rc<Display>,
155 codec: Codec,
156 units: &[&[u8]],
157 out: &str,
158) -> Result<usize, String> {
159 let mut decoder = Decoder::new(display, codec).map_err(|e| e.to_string())?;
160 let mut file = BufWriter::new(File::create(out).map_err(|e| format!("{out}: {e}"))?);
161 let mut count = 0usize;
162 let emit = |frame: ec_hw::Frame, file: &mut BufWriter<File>| -> Result<(), String> {
163 if frame.bit_depth == 10 {
164 let p = frame.to_i420_16().map_err(|e| e.to_string())?;
165 for plane in [&p.y, &p.u, &p.v] {
166 for s in plane.iter() {
167 file.write_all(&s.to_le_bytes())
168 .map_err(|e| e.to_string())?;
169 }
170 }
171 } else {
172 let p = frame.to_i420().map_err(|e| e.to_string())?;
173 for plane in [&p.y, &p.u, &p.v] {
174 file.write_all(plane).map_err(|e| e.to_string())?;
175 }
176 }
177 Ok(())
178 };
179 for (i, unit) in units.iter().enumerate() {
180 decoder
181 .decode(unit, i as i64)
182 .map_err(|e| format!("decode unit {i}: {e}"))?;
183 while let Some(frame) = decoder.next_frame() {
184 emit(frame, &mut file)?;
185 count += 1;
186 }
187 }
188 decoder.flush().map_err(|e| e.to_string())?;
189 while let Some(frame) = decoder.next_frame() {
190 emit(frame, &mut file)?;
191 count += 1;
192 }
193 file.flush().map_err(|e| e.to_string())?;
194 Ok(count)
195}
196
197fn bench_dec(
198 display: &std::rc::Rc<Display>,
199 codec: Codec,
200 data: &[u8],
201 runs: usize,
202 out: Option<&str>,
203) -> Result<(), String> {
204 let units: Vec<&[u8]> = match codec {
205 Codec::H264 | Codec::H265 => split_access_units(data, codec),
206 Codec::Vp9 | Codec::Av1 => split_ivf(data),
207 };
208 if units.is_empty() {
209 return Err("no access units in the stream".into());
210 }
211 let mut best: Option<(usize, Duration)> = None;
212 let mut times = Vec::new();
213 for run in 1..=runs {
214 let (n, t) = decode_timed(display, codec, &units)?;
215 let s = t.as_secs_f64();
216 println!(
217 "RUN|dec|run={run} pictures={n} secs={s:.4} fps={:.2}",
218 n as f64 / s
219 );
220 times.push(s);
221 if best.is_none_or(|(_, b)| t < b) {
222 best = Some((n, t));
223 }
224 }
225 let (n, t) = best.ok_or("no runs")?;
226 let s = t.as_secs_f64();
227 let media = n as f64 / FPS;
228 println!(
229 "BEST|dec|pictures={n} best_s={s:.4} fps={:.2} x_realtime={:.2} runs={runs} units={} stream_bytes={}",
230 n as f64 / s,
231 media / s,
232 units.len(),
233 data.len()
234 );
235 if let Some(path) = out {
236 let written = decode_dump(display, codec, &units, path)?;
237 println!("DUMP|dec|pictures={written} file={path}");
238 }
239 Ok(())
240}
241
242/// Split an Annex B stream into access units: a new one starts at the first VCL NAL of a
243/// picture (a slice whose first-slice flag is set, after an earlier slice of the same picture).
244fn split_access_units(data: &[u8], codec: Codec) -> Vec<&[u8]> {
245 let mut starts: Vec<usize> = Vec::new();
246 let mut seen_slice = false;
247 let mut i = 0usize;
248 while i + 3 < data.len() {
249 if data[i] != 0 || data[i + 1] != 0 || data[i + 2] != 1 {
250 i += 1;
251 continue;
252 }
253 let nal = i + 3;
254 let (is_vcl, first_slice) = match codec {
255 Codec::H264 => {
256 let t = data[nal] & 0x1f;
257 let first = data.get(nal + 1).is_some_and(|&b| b & 0x80 != 0);
258 ((1..=5).contains(&t), first)
259 }
260 _ => {
261 let t = (data[nal] >> 1) & 0x3f;
262 let first = data.get(nal + 2).is_some_and(|&b| b & 0x80 != 0);
263 (t <= 31, first)
264 }
265 };
266 if is_vcl {
267 if seen_slice && first_slice {
268 starts.push(i);
269 seen_slice = false;
270 }
271 if first_slice {
272 seen_slice = true;
273 }
274 }
275 i = nal + 1;
276 }
277 let mut out = Vec::new();
278 let mut prev = 0usize;
279 for &start in &starts {
280 out.push(&data[prev..start]);
281 prev = start;
282 }
283 if prev < data.len() {
284 out.push(&data[prev..]);
285 }
286 out
287}
288
289/// Split an IVF file into its frames.
290fn split_ivf(data: &[u8]) -> Vec<&[u8]> {
291 let mut out = Vec::new();
292 if data.len() < 32 || &data[..4] != b"DKIF" {
293 return out;
294 }
295 let header = u16::from_le_bytes([data[6], data[7]]) as usize;
296 let mut pos = header.max(32);
297 while pos + 12 <= data.len() {
298 let size =
299 u32::from_le_bytes([data[pos], data[pos + 1], data[pos + 2], data[pos + 3]]) as usize;
300 pos += 12;
301 if pos + size > data.len() {
302 break;
303 }
304 out.push(&data[pos..pos + size]);
305 pos += size;
306 }
307 out
308}
309
310// ---------------------------------------------------------------------------------------------
311// Encode
312// ---------------------------------------------------------------------------------------------
313
314#[allow(clippy::too_many_arguments)]
315fn bench_enc(
316 display: &std::rc::Rc<Display>,
317 codec: EncCodec,
318 raw: &str,
319 width: u32,
320 height: u32,
321 frames: usize,
322 bitrate: u32,
323 runs: usize,
324 out: Option<&str>,
325) -> Result<(), String> {
326 let (w, h) = (width as usize, height as usize);
327 let (cw, ch) = (w.div_ceil(2), h.div_ceil(2));
328 let frame_bytes = w * h + 2 * cw * ch;
329 let mut file = File::open(raw).map_err(|e| format!("{raw}: {e}"))?;
330 let mut buf = vec![0u8; frame_bytes];
331 let mut best: Option<(usize, Duration, usize, usize)> = None;
332 let mut last_stream: Vec<u8> = Vec::new();
333 for run in 1..=runs {
334 use std::io::Seek;
335 file.rewind().map_err(|e| e.to_string())?;
336 let mut cfg = EncoderConfig::new(codec, width, height);
337 cfg.framerate = (30, 1);
338 cfg.gop_size = 30;
339 cfg.bitrate = bitrate;
340 cfg.rate_control = RateControlMode::ConstantBitrate;
341 let mut enc = Encoder::new(display, cfg).map_err(|e| e.to_string())?;
342 let mut stream = Vec::new();
343 let mut keyframes = 0usize;
344 let mut spent = Duration::ZERO;
345 for t in 0..frames {
346 file.read_exact(&mut buf)
347 .map_err(|e| format!("frame {t}: {e}"))?;
348 let picture = I420 {
349 y: buf[..w * h].to_vec(),
350 u: buf[w * h..w * h + cw * ch].to_vec(),
351 v: buf[w * h + cw * ch..].to_vec(),
352 width,
353 height,
354 };
355 let meta = FrameMetadata {
356 timestamp: t as i64,
357 force_keyframe: false,
358 };
359 let start = Instant::now();
360 let coded = enc
361 .encode(&picture, meta)
362 .map_err(|e| format!("encode frame {t}: {e}"))?;
363 spent += start.elapsed();
364 keyframes += usize::from(coded.is_keyframe);
365 stream.extend_from_slice(&coded.data);
366 }
367 let s = spent.as_secs_f64();
368 println!(
369 "RUN|enc|run={run} pictures={frames} secs={s:.4} fps={:.2} bytes={} keyframes={keyframes}",
370 frames as f64 / s,
371 stream.len()
372 );
373 if best.is_none_or(|(_, b, _, _)| spent < b) {
374 best = Some((frames, spent, stream.len(), keyframes));
375 }
376 last_stream = stream;
377 }
378 let (n, t, bytes, keyframes) = best.ok_or("no runs")?;
379 let s = t.as_secs_f64();
380 let media = n as f64 / FPS;
381 println!(
382 "BEST|enc|pictures={n} best_s={s:.4} fps={:.2} x_realtime={:.2} runs={runs} bytes={bytes} kbps={:.1} keyframes={keyframes}",
383 n as f64 / s,
384 media / s,
385 bytes as f64 * 8.0 / media / 1000.0
386 );
387 if let Some(path) = out {
388 std::fs::write(path, &last_stream).map_err(|e| format!("{path}: {e}"))?;
389 println!("DUMP|enc|file={path} bytes={}", last_stream.len());
390 }
391 Ok(())
392}