forge
Explore
Log in

Don't you dare go Hollow

edith

Clone
★ 0

0 watching0 forksRust18.3 MiBcc667e6Tahinli3 months ago285 commits

lib.rs1126 lines, 42.2 KiBHistoryRawDownload
1//! VA-API decode (H.264, HEVC, VP9 and AV1) and encode (H.264, and AV1 where
2//! the GPU has an entrypoint for it), shipped as a
3//! `dlopen`-able plugin so the main binary never gets a DT_NEEDED on
4//! libva/gbm/drm. Every entry point is
5//! `extern "C"`, catches unwinds and reports failure as a null pointer or a
6//! negative code: the caller's contract is "any failure means use the software
7//! codec".
8//!
9//! ponytail: that guarantee rests on `panic = "unwind"`. Building this crate with
10//! `panic = "abort"` would turn a driver bug into a killed app; the upgrade path
11//! is running the decoder in a child process instead of in-process.
12
13use std::collections::VecDeque;
14use std::ffi::{CStr, c_char, c_void};
15use std::panic::{AssertUnwindSafe, catch_unwind};
16use std::path::{Path, PathBuf};
17use std::rc::Rc;
18
19use cros_codecs::backend::vaapi::decoder::VaapiBackend;
20use cros_codecs::backend::vaapi::encoder::VaapiBackend as VaapiEncBackend;
21use cros_codecs::codec::av1::parser::Profile as Av1Profile;
22use cros_codecs::codec::h264::parser::{Level, Profile as H264Profile};
23use cros_codecs::decoder::stateless::av1::Av1;
24use cros_codecs::decoder::stateless::h264::H264;
25use cros_codecs::decoder::stateless::h265::H265;
26use cros_codecs::decoder::stateless::vp9::Vp9;
27use cros_codecs::decoder::stateless::{DecodeError, StatelessDecoder, StatelessVideoDecoder};
28use cros_codecs::decoder::{BlockingMode, DecodedHandle, DecoderEvent, StreamInfo};
29use cros_codecs::encoder::av1::EncoderConfig as Av1Config;
30use cros_codecs::encoder::h264::EncoderConfig as H264Config;
31use cros_codecs::encoder::stateless::av1::StatelessEncoder as Av1StatelessEncoder;
32use cros_codecs::encoder::stateless::h264::StatelessEncoder;
33use cros_codecs::encoder::{
34 FrameMetadata, PredictionStructure, RateControl, Tunings, VideoEncoder,
35};
36use cros_codecs::image_processing::nv12_to_i420;
37use cros_codecs::libva::{
38 Display, Image, Surface, VA_FOURCC_NV12, VA_FOURCC_P010, VAEntrypoint, VAImageFormat,
39 VAProfile,
40};
41use cros_codecs::video_frame::VideoFrame;
42use cros_codecs::video_frame::frame_pool::{FramePool, PooledVideoFrame};
43use cros_codecs::video_frame::generic_dma_video_frame::GenericDmaVideoFrame;
44use cros_codecs::video_frame::{UV_PLANE, Y_PLANE};
45use cros_codecs::{Fourcc, FrameLayout, PlaneLayout, Resolution};
46use gbm::{BufferObjectFlags, Format as GbmFormat};
47
48use engine::demux::{Codec, Demuxer};
49use engine::hw::{CAP_AV1, CAP_H264, CAP_HEVC, CAP_VP9, VhCaps, VhFrame, VhMeta};
50
51type PooledFrame = PooledVideoFrame<GenericDmaVideoFrame>;
52type Dec<C> = StatelessDecoder<C, VaapiBackend<PooledFrame>>;
53type Handle = <Dec<H264> as StatelessVideoDecoder>::Handle;
54
55/// One decoder per codec the demuxer can hand us. They all share the VA-API
56/// backend and therefore the same [`Handle`], so everything past `decode` is
57/// common; which one exists is decided by the container, never by the caller --
58/// which is why the plugin's C ABI is unchanged and an older `libengine_hw.so`
59/// still loads and still decodes H.264 (it simply refuses the newer codecs'
60/// files at `Demuxer`).
61///
62/// 4:2:0 only, 8- or 10-bit: HEVC Main and Main 10, VP9 profile 0, AV1 Main at
63/// either depth.
64/// A 10-bit stream decodes into a P010 pool and is read back down to the 8-bit
65/// I420 every frame here is ([`Session::emit`]).
66///
67/// ponytail: 10-bit is *carried* 8-bit, because [`VhFrame`] is a byte-per-sample
68/// interface all the way to the renderer. That costs the low two bits of a Main
69/// 10 source; the upgrade path is a 16-bit `VhFrame`, which is a change to every
70/// stage between here and the texture upload, not to this file.
71/// VP9 profile 2 is still refused by `Demuxer`: a VP9 stream does not state its
72/// depth where that reads it (an `av1C` and an `hvcC` both do).
73enum Decoder {
74 H264(Dec<H264>),
75 Hevc(Dec<H265>),
76 Vp9(Dec<Vp9>),
77 Av1(Dec<Av1>),
78}
79
80impl Decoder {
81 fn get(&mut self) -> &mut dyn StatelessVideoDecoder<Handle = Handle> {
82 match self {
83 Self::H264(d) => d,
84 Self::Hevc(d) => d,
85 Self::Vp9(d) => d,
86 Self::Av1(d) => d,
87 }
88 }
89}
90
91type Encoder = StatelessEncoder<
92 GenericDmaVideoFrame,
93 VaapiEncBackend<GenericDmaVideoFrame, Surface<GenericDmaVideoFrame>>,
94>;
95type Av1Encoder = Av1StatelessEncoder<
96 GenericDmaVideoFrame,
97 VaapiEncBackend<GenericDmaVideoFrame, Surface<GenericDmaVideoFrame>>,
98>;
99
100/// Ceiling on decode/drain iterations that make no progress. VA-API in blocking
101/// mode should always either hand back an event or accept input; this only
102/// exists so a misbehaving driver returns an error instead of hanging the app.
103const STALL_LIMIT: u32 = 10_000;
104
105struct Session {
106 decoder: Decoder,
107 /// NV12 (or, for a 10-bit stream, P010) descriptor for `vaGetImage`,
108 /// queried once at open.
109 nv12_format: VAImageFormat,
110 /// Whether the surfaces are P010 rather than NV12, which is the one thing
111 /// the read-back has to do differently.
112 ten_bit: bool,
113 pool: FramePool<GenericDmaVideoFrame>,
114 demuxer: Demuxer,
115 meta: VhMeta,
116 ready: VecDeque<Handle>,
117 /// Remaining bytes of the access unit currently being fed, if any.
118 pending: Vec<u8>,
119 timestamp: u64,
120 flushed: bool,
121 /// Pictures still to be decoded and thrown away to land on a seek target.
122 skip: u32,
123 /// Tightly packed I420 handed out through [`VhFrame`]; reused every frame,
124 /// which is exactly why the pointers are only valid until the next call.
125 out: Vec<u8>,
126 luma: usize,
127 chroma: usize,
128}
129
130/// Mesa's GBM cannot allocate an NV12 buffer object at all (measured on
131/// radeonsi: every flag/modifier combination returns NULL), so we allocate one
132/// linear single-plane R8 buffer big enough for luma + chroma and describe the
133/// NV12 layout inside it ourselves. VA-API imports it as one DRM-PRIME object
134/// with two planes at known offsets, which is exactly what the descriptor in
135/// `GenericDmaVideoFrame` emits.
136///
137/// `ten_bit` asks for the same thing in P010: the very same two-plane 4:2:0
138/// shape with 16-bit samples, so the buffer is simply twice as wide.
139fn alloc_nv12(
140 gbm: &gbm::Device<std::fs::File>,
141 coded: Resolution,
142 ten_bit: bool,
143) -> Result<GenericDmaVideoFrame, String> {
144 let rows = coded.height + coded.height.div_ceil(2);
145 let width = coded.width * if ten_bit { 2 } else { 1 };
146 let bo = gbm
147 .create_buffer_object::<()>(width, rows, GbmFormat::R8, BufferObjectFlags::LINEAR)
148 .map_err(|e| format!("gbm R8 {width}x{rows} allocation failed: {e}"))?;
149 let pitch = bo.stride().map_err(|e| e.to_string())? as usize;
150 let fd = bo.fd().map_err(|e| e.to_string())?;
151 GenericDmaVideoFrame::new(
152 vec![std::fs::File::from(fd)],
153 nv12_layout(coded, pitch, ten_bit),
154 )
155}
156
157/// Two NV12 (or P010) planes packed one after the other in a single buffer
158/// object.
159fn nv12_layout(coded: Resolution, pitch: usize, ten_bit: bool) -> FrameLayout {
160 FrameLayout {
161 format: (
162 Fourcc::from(if ten_bit { b"P010" } else { b"NV12" }),
163 0, /* DRM_FORMAT_MOD_LINEAR */
164 ),
165 size: coded,
166 planes: vec![
167 PlaneLayout {
168 buffer_index: 0,
169 offset: 0,
170 stride: pitch,
171 },
172 PlaneLayout {
173 buffer_index: 0,
174 offset: pitch * coded.height as usize,
175 stride: pitch,
176 },
177 ],
178 }
179}
180
181/// First render node that gives us both a VA display and a GBM device. Which
182/// node is the right one is a per-machine question, so we probe rather than
183/// hardcode renderD128.
184fn open_devices() -> Option<(Rc<Display>, gbm::Device<std::fs::File>)> {
185 let mut nodes: Vec<PathBuf> = std::fs::read_dir("/dev/dri")
186 .ok()?
187 .flatten()
188 .map(|e| e.path())
189 .filter(|p| {
190 p.file_name()
191 .and_then(|n| n.to_str())
192 .is_some_and(|n| n.starts_with("renderD"))
193 })
194 .collect();
195 nodes.sort();
196 nodes.into_iter().find_map(|node| {
197 let display = Display::open_drm_display(&node).ok()?;
198 let file = std::fs::OpenOptions::new()
199 .read(true)
200 .write(true)
201 .open(&node)
202 .ok()?;
203 let gbm = gbm::Device::new(file).ok()?;
204 Some((display, gbm))
205 })
206}
207
208impl Session {
209 fn open(path: &Path) -> Option<Self> {
210 let (meta, demuxer) = Demuxer::open(path).ok()?;
211 let (display, gbm) = open_devices()?;
212 // A 10-bit stream decodes into P010 surfaces and is read back through a
213 // P010 image; a driver that has no such image format is one this cannot
214 // read 10-bit off at all, which is a null session and a software
215 // fallback like any other refusal here.
216 let ten_bit = demuxer.bit_depth() > 8;
217 let want = if ten_bit {
218 VA_FOURCC_P010
219 } else {
220 VA_FOURCC_NV12
221 };
222 let nv12_format = display
223 .query_image_formats()
224 .ok()?
225 .into_iter()
226 .find(|f| f.fourcc == want)?;
227 let decoder = match meta.codec {
228 Codec::H264 => {
229 Decoder::H264(Dec::<H264>::new_vaapi(display, BlockingMode::Blocking).ok()?)
230 }
231 Codec::Hevc => {
232 Decoder::Hevc(Dec::<H265>::new_vaapi(display, BlockingMode::Blocking).ok()?)
233 }
234 Codec::Vp9 => {
235 Decoder::Vp9(Dec::<Vp9>::new_vaapi(display, BlockingMode::Blocking).ok()?)
236 }
237 Codec::Av1 => {
238 Decoder::Av1(Dec::<Av1>::new_vaapi(display, BlockingMode::Blocking).ok()?)
239 }
240 };
241 let pool = FramePool::new(move |info: &StreamInfo| {
242 alloc_nv12(&gbm, info.coded_resolution, ten_bit).expect("output frame allocation failed")
243 });
244 Some(Self {
245 decoder,
246 nv12_format,
247 ten_bit,
248 pool,
249 demuxer,
250 meta: VhMeta {
251 width: meta.width,
252 height: meta.height,
253 frame_rate: meta.frame_rate,
254 frame_count: meta.frame_count,
255 },
256 ready: VecDeque::new(),
257 pending: Vec::new(),
258 timestamp: 0,
259 flushed: false,
260 skip: 0,
261 out: Vec::new(),
262 luma: 0,
263 chroma: 0,
264 })
265 }
266
267 /// As [`Session::open`], but positioned so the first picture handed out is
268 /// sample `target_sample` (1-based): decode restarts at the sync sample at
269 /// or before it and the pictures in between are dropped unread.
270 fn open_at(path: &Path, target_sample: u32) -> Option<Self> {
271 let mut session = Self::open(path)?;
272 // The ABI still speaks 1-based sample ids, the demuxer speaks 0-based
273 // display frames -- and answers with a signed one, since a sync sample
274 // inside what the edit list trims sits before frame 0.
275 let target_frame = target_sample.saturating_sub(1);
276 let first = session.demuxer.seek_to_sync_at_or_before(target_frame);
277 session.skip = (i64::from(target_frame) - first).max(0) as u32;
278 Some(session)
279 }
280
281 /// Pumps the decoder until one picture is ready. `Ok(false)` is clean EOF.
282 fn pump(&mut self) -> Result<bool, String> {
283 let mut stalls = 0u32;
284 loop {
285 // Stop draining as soon as we have a picture: every handle we hold
286 // keeps a pool buffer out of circulation.
287 while self.ready.is_empty() {
288 match self.decoder.get().next_event() {
289 Some(DecoderEvent::FrameReady(handle)) => self.ready.push_back(handle),
290 Some(DecoderEvent::FormatChanged) => {
291 let info = self
292 .decoder
293 .get()
294 .stream_info()
295 .ok_or("format changed without stream info")?
296 .clone();
297 self.pool.resize(&info);
298 }
299 None => break,
300 }
301 }
302 if let Some(handle) = self.ready.pop_front() {
303 // Seek discards: dropping the handle skips the `vaGetImage`
304 // read-back (~1.2 ms/picture) and frees its pool buffer.
305 if self.skip > 0 {
306 self.skip -= 1;
307 continue;
308 }
309 self.emit(handle);
310 return Ok(true);
311 }
312 if self.flushed {
313 return Ok(false);
314 }
315
316 if self.pending.is_empty() {
317 match self.demuxer.next_access_unit() {
318 Ok(Some(au)) => self.pending = au,
319 Ok(None) => {
320 self.decoder.get().flush().map_err(|e| e.to_string())?;
321 self.flushed = true;
322 continue;
323 }
324 Err(e) => return Err(e.to_string()),
325 }
326 }
327
328 let Self {
329 decoder,
330 pool,
331 pending,
332 timestamp,
333 ..
334 } = self;
335 match decoder
336 .get()
337 .decode(*timestamp, pending, &mut || pool.alloc())
338 {
339 Ok(0) => return Err("decoder consumed no input".into()),
340 Ok(n) => {
341 pending.drain(..n.min(pending.len()));
342 if pending.is_empty() {
343 *timestamp += 1;
344 }
345 stalls = 0;
346 }
347 // Both mean "handle pending events, then resubmit the same data".
348 Err(DecodeError::CheckEvents) | Err(DecodeError::NotEnoughOutputBuffers(_)) => {
349 stalls += 1;
350 if stalls > STALL_LIMIT {
351 return Err("decoder stalled waiting for output buffers".into());
352 }
353 }
354 Err(e) => return Err(e.to_string()),
355 }
356 }
357 }
358
359 /// Copies a decoded NV12 surface into `self.out` as packed I420.
360 fn emit(&mut self, handle: Handle) {
361 let res = handle.display_resolution();
362 let (w, h) = (res.width as usize, res.height as usize);
363 let (cw, ch) = (w.div_ceil(2), h.div_ceil(2));
364 if self.luma != w * h || self.chroma != cw * ch {
365 self.luma = w * h;
366 self.chroma = cw * ch;
367 self.out = vec![0u8; self.luma + 2 * self.chroma];
368 }
369 self.meta.width = res.width;
370 self.meta.height = res.height;
371
372 // Read back with vaGetImage rather than mapping our own DMA-BUF: on a
373 // discrete GPU that buffer lives in VRAM and a CPU read of it runs at
374 // ~44 MB/s over the PCIe BAR (measured), which costs 350 ms/frame. The
375 // driver copies into host-visible memory for us instead.
376 // Cheap no-op in blocking mode, but pixels must never be read early.
377 let _ = DecodedHandle::sync(&handle);
378 let borrowed = handle.borrow();
379 let size = (w as u32, h as u32);
380 let image = Image::create_from(borrowed.surface(), self.nv12_format, size, size)
381 .expect("vaGetImage failed");
382 let va = *image.image();
383 let data: &[u8] = image.as_ref();
384
385 let (dst_y, rest) = self.out.split_at_mut(self.luma);
386 let (dst_u, dst_v) = rest.split_at_mut(self.chroma);
387 if self.ten_bit {
388 p010_to_i420(
389 &data[va.offsets[Y_PLANE] as usize..],
390 va.pitches[Y_PLANE] as usize,
391 dst_y,
392 &data[va.offsets[UV_PLANE] as usize..],
393 va.pitches[UV_PLANE] as usize,
394 dst_u,
395 dst_v,
396 w,
397 h,
398 );
399 return;
400 }
401 nv12_to_i420(
402 &data[va.offsets[Y_PLANE] as usize..],
403 va.pitches[Y_PLANE] as usize,
404 dst_y,
405 w,
406 &data[va.offsets[UV_PLANE] as usize..],
407 va.pitches[UV_PLANE] as usize,
408 dst_u,
409 cw,
410 dst_v,
411 cw,
412 w,
413 h,
414 );
415 }
416
417 fn fill(&self, out: &mut VhFrame) {
418 let w = self.meta.width as usize;
419 let cw = w.div_ceil(2);
420 out.y = self.out.as_ptr();
421 // SAFETY: `out` was sized to luma + 2 * chroma just above in `emit`.
422 unsafe {
423 out.u = self.out.as_ptr().add(self.luma);
424 out.v = self.out.as_ptr().add(self.luma + self.chroma);
425 }
426 out.y_stride = w;
427 out.u_stride = cw;
428 out.v_stride = cw;
429 out.width = self.meta.width;
430 out.height = self.meta.height;
431 }
432}
433
434/// One P010 picture down to packed 8-bit I420: [`nv12_to_i420`] for a surface
435/// whose samples are 16-bit little-endian with the value in the **high** bits,
436/// which is what P010 means. The high byte of each pair is therefore the 10-bit
437/// sample shifted down by two, i.e. the 8-bit one -- no rounding, because a
438/// second read of the low byte costs more than the half-bit it would buy.
439fn p010_to_i420(
440 src_y: &[u8],
441 src_y_pitch: usize,
442 dst_y: &mut [u8],
443 src_uv: &[u8],
444 src_uv_pitch: usize,
445 dst_u: &mut [u8],
446 dst_v: &mut [u8],
447 width: usize,
448 height: usize,
449) {
450 for row in 0..height {
451 let src = &src_y[row * src_y_pitch..];
452 let dst = &mut dst_y[row * width..row * width + width];
453 for (x, out) in dst.iter_mut().enumerate() {
454 *out = src[2 * x + 1];
455 }
456 }
457 let (cw, ch) = (width.div_ceil(2), height.div_ceil(2));
458 for row in 0..ch {
459 let src = &src_uv[row * src_uv_pitch..];
460 let (u, v) = (
461 &mut dst_u[row * cw..row * cw + cw],
462 &mut dst_v[row * cw..row * cw + cw],
463 );
464 for x in 0..cw {
465 u[x] = src[4 * x + 1];
466 v[x] = src[4 * x + 3];
467 }
468 }
469}
470
471/// Opens `path` for hardware decode, positioned so the first
472/// [`vh_next_frame`] returns sample `target_sample` (1-based; 0 and 1 both mean
473/// the start of the stream). Returns null on any failure at all: no libva
474/// runtime, no render node, unsupported profile, unreadable file.
475///
476/// # Safety
477/// `path` must be a valid NUL-terminated C string.
478#[unsafe(no_mangle)]
479pub unsafe extern "C" fn vh_open_at(path: *const c_char, target_sample: u32) -> *mut c_void {
480 catch_unwind(AssertUnwindSafe(|| {
481 if path.is_null() {
482 return std::ptr::null_mut();
483 }
484 // SAFETY: caller-guaranteed NUL-terminated string, read before return.
485 let path = unsafe { CStr::from_ptr(path) };
486 let Ok(path) = path.to_str() else {
487 return std::ptr::null_mut();
488 };
489 match Session::open_at(Path::new(path), target_sample) {
490 Some(session) => Box::into_raw(Box::new(session)) as *mut c_void,
491 None => std::ptr::null_mut(),
492 }
493 }))
494 .unwrap_or(std::ptr::null_mut())
495}
496
497/// Fills `out` with stream metadata. 0 on success, negative on failure.
498///
499/// # Safety
500/// `session` must come from [`vh_open_at`] and `out` must be writable.
501#[unsafe(no_mangle)]
502pub unsafe extern "C" fn vh_meta(session: *mut c_void, out: *mut VhMeta) -> i32 {
503 catch_unwind(AssertUnwindSafe(|| {
504 if session.is_null() || out.is_null() {
505 return -1;
506 }
507 // SAFETY: caller-guaranteed live session and writable destination.
508 unsafe {
509 let session = &*(session as *const Session);
510 (*out).width = session.meta.width;
511 (*out).height = session.meta.height;
512 (*out).frame_rate = session.meta.frame_rate;
513 (*out).frame_count = session.meta.frame_count;
514 }
515 0
516 }))
517 .unwrap_or(-1)
518}
519
520/// 1 when `out` holds the next picture in display order, 0 at clean end of
521/// stream, negative on error. Plane pointers stay valid until the next call.
522///
523/// # Safety
524/// `session` must come from [`vh_open_at`] and `out` must be writable.
525#[unsafe(no_mangle)]
526pub unsafe extern "C" fn vh_next_frame(session: *mut c_void, out: *mut VhFrame) -> i32 {
527 catch_unwind(AssertUnwindSafe(|| {
528 if session.is_null() || out.is_null() {
529 return -1;
530 }
531 // SAFETY: caller-guaranteed live session and writable destination.
532 let session = unsafe { &mut *(session as *mut Session) };
533 match session.pump() {
534 Ok(true) => {
535 // SAFETY: `out` is non-null and writable per the contract.
536 session.fill(unsafe { &mut *out });
537 1
538 }
539 Ok(false) => 0,
540 Err(e) => {
541 eprintln!("engine_hw: {e}");
542 -2
543 }
544 }
545 }))
546 .unwrap_or(-1)
547}
548
549/// Releases a session. Safe to call with null.
550///
551/// # Safety
552/// `session` must come from [`vh_open_at`] and must not be used afterwards.
553#[unsafe(no_mangle)]
554pub unsafe extern "C" fn vh_close(session: *mut c_void) {
555 let _ = catch_unwind(AssertUnwindSafe(|| {
556 if !session.is_null() {
557 // SAFETY: pointer came from `Box::into_raw` in `vh_open_at`.
558 drop(unsafe { Box::from_raw(session as *mut Session) });
559 }
560 }));
561}
562
563/// What each codec needs of the driver before this plugin can claim it: the
564/// 8-bit decode profiles, the 10-bit ones, and the profile the *encoder* here
565/// would open -- `None` for the two this plugin has no encoder for at all, so a
566/// GPU with an HEVC or VP9 encode entrypoint is never reported as one edith can
567/// reach. The encode profiles are the very ones [`EncSession::open_codec`]
568/// asks for, which is what keeps this a description of the plugin rather than a
569/// second opinion about it.
570const CAP_TABLE: [(u32, &[VAProfile::Type], &[VAProfile::Type], Option<VAProfile::Type>); 4] = [
571 (
572 CAP_H264,
573 &[
574 VAProfile::VAProfileH264ConstrainedBaseline,
575 VAProfile::VAProfileH264Main,
576 VAProfile::VAProfileH264High,
577 ],
578 &[],
579 Some(VAProfile::VAProfileH264Main),
580 ),
581 (
582 CAP_HEVC,
583 &[VAProfile::VAProfileHEVCMain],
584 &[VAProfile::VAProfileHEVCMain10],
585 None,
586 ),
587 (
588 CAP_VP9,
589 &[VAProfile::VAProfileVP9Profile0],
590 &[VAProfile::VAProfileVP9Profile2],
591 None,
592 ),
593 (
594 CAP_AV1,
595 &[VAProfile::VAProfileAV1Profile0],
596 // AV1 carries 8- and 10-bit in the same profile 0, so the profile bit
597 // is the same one and the P010 read-back is what decides.
598 &[VAProfile::VAProfileAV1Profile0],
599 Some(VAProfile::VAProfileAV1Profile0),
600 ),
601];
602
603/// This machine's decode and encode seats, asked of the driver rather than
604/// assumed: which profiles it has, which entrypoints each of those carries, and
605/// whether a P010 image exists to read a 10-bit picture back through. Only
606/// codecs this plugin actually implements can light up -- `CAP_TABLE` is that
607/// half of the intersection.
608///
609/// `None` when there is no display to ask at all, which is the same "software
610/// only" a missing plugin means.
611fn query_caps() -> Option<VhCaps> {
612 let (display, _gbm) = open_devices()?;
613 let profiles = display.query_config_profiles().ok()?;
614 let p010 = display
615 .query_image_formats()
616 .is_ok_and(|formats| formats.iter().any(|f| f.fourcc == VA_FOURCC_P010));
617 let has = |profile: VAProfile::Type, entrypoint: VAEntrypoint::Type| {
618 profiles.contains(&profile)
619 && display
620 .query_config_entrypoints(profile)
621 .is_ok_and(|e| e.contains(&entrypoint))
622 };
623 let decodes = |list: &[VAProfile::Type]| {
624 list.iter()
625 .any(|&p| has(p, VAEntrypoint::VAEntrypointVLD))
626 };
627 let mut caps = VhCaps::default();
628 for (bit, eight, ten, encode) in CAP_TABLE {
629 if decodes(eight) {
630 caps.decode |= bit;
631 }
632 if p010 && decodes(ten) {
633 caps.decode_10bit |= bit;
634 }
635 // Both entrypoints, exactly as the encoder's own open takes either.
636 if encode.is_some_and(|p| {
637 has(p, VAEntrypoint::VAEntrypointEncSlice) || has(p, VAEntrypoint::VAEntrypointEncSliceLP)
638 }) {
639 caps.encode |= bit;
640 }
641 }
642 Some(caps)
643}
644
645/// Fills `out` with what this machine and this plugin can do together. 0 on
646/// success, negative when there is nothing to report -- an *optional* symbol on
647/// purpose, so the caller resolving it is free to be older or newer than this.
648///
649/// Costs one VA-API init; the caller caches the answer.
650///
651/// # Safety
652/// `out` must be writable.
653#[unsafe(no_mangle)]
654pub unsafe extern "C" fn vh_caps(out: *mut VhCaps) -> i32 {
655 catch_unwind(AssertUnwindSafe(|| {
656 if out.is_null() {
657 return -1;
658 }
659 let Some(caps) = query_caps() else {
660 return -1;
661 };
662 // SAFETY: caller-guaranteed writable destination.
663 unsafe { *out = caps };
664 0
665 }))
666 .unwrap_or(-1)
667}
668
669fn align16(v: u32) -> u32 {
670 v.div_ceil(16) * 16
671}
672
673/// Fills in slice NAL header bytes the driver left at zero.
674///
675/// Mesa's radeonsi encoder writes `forbidden_zero_bit`, `nal_ref_idc` and
676/// `nal_unit_type` from state it only ever populates out of a *packed* slice
677/// header, and cros-codecs supplies none (`h264/vaapi.rs` says as much in its
678/// "use packed headers" TODO). Every other bit of the slice is correct, so the
679/// whole damage is one byte per slice: measured on radeonsi, patching it turns
680/// a stream neither ffmpeg nor `rusty_h264` will touch into one both decode.
681///
682/// An all-zero byte after a start code is never valid H.264, so drivers that do
683/// write the header (Intel's, which is what cros-codecs was built against) fall
684/// straight through this.
685///
686/// ponytail: the real fix is a `VAEncPackedHeaderH264_Slice` buffer in the
687/// vendored cros-codecs backend, which means synthesizing the entire slice
688/// header there rather than correcting two fields here.
689fn fix_slice_nal_headers(au: &mut [u8]) {
690 // cros-codecs prepends SPS+PPS to the access unit at every IDR and only
691 // there, so an SPS seen earlier in this unit is what makes the slice one.
692 let mut idr = false;
693 let mut i = 0;
694 while i + 3 < au.len() {
695 if au[i..i + 3] != [0, 0, 1] {
696 i += 1;
697 continue;
698 }
699 let nal = &mut au[i + 3];
700 if *nal == 0 {
701 // nal_ref_idc 3 + IDR, or 2 + non-IDR: every picture this encoder
702 // emits is a short-term reference (no B-frames, no disposables).
703 *nal = if idr { 0x65 } else { 0x41 };
704 } else if *nal & 0x1f == 7 {
705 idr = true;
706 }
707 i += 3;
708 }
709}
710
711/// One hardware H.264 encode session.
712///
713/// Input goes through a single reusable NV12 buffer object: the caller's I420
714/// planes are interleaved into it and the encoder imports it as a VA surface.
715/// Reuse is safe because the encoder runs in blocking mode and every entry
716/// point polls it before returning, so the GPU is finished with the buffer
717/// before the next picture is written into it.
718struct EncSession {
719 /// Boxed because the two codecs are two types and everything past `encode`
720 /// is the same trait: one session type serves both, which is what keeps the
721 /// C ABI at one new symbol (the open) instead of four.
722 encoder: Box<dyn VideoEncoder<GenericDmaVideoFrame>>,
723 /// H.264 only: the byte the driver leaves at zero is a *NAL* header, and an
724 /// AV1 temporal unit has no such thing.
725 h264: bool,
726 /// Owns the DRM node the buffer object below was allocated from.
727 _gbm: gbm::Device<std::fs::File>,
728 frame: GenericDmaVideoFrame,
729 layout: FrameLayout,
730 /// Macroblock-aligned surface size; `width`/`height` are what is encoded.
731 coded: Resolution,
732 width: usize,
733 height: usize,
734 timestamp: u64,
735 drained: bool,
736 /// Coded access units the encoder has finished but the caller has not
737 /// collected yet, in encode order (which is display order: no B-frames).
738 ready: VecDeque<Vec<u8>>,
739 /// The access unit currently handed out, kept alive until the next call.
740 out: Vec<u8>,
741}
742
743impl EncSession {
744 fn open(width: u32, height: u32, fps_num: u32, fps_den: u32, bitrate: u64) -> Option<Self> {
745 Self::open_codec(width, height, fps_num, fps_den, bitrate, false)
746 }
747
748 fn open_codec(
749 width: u32,
750 height: u32,
751 fps_num: u32,
752 fps_den: u32,
753 bitrate: u64,
754 av1: bool,
755 ) -> Option<Self> {
756 // NV12 chroma is half resolution, so odd dimensions have no packing;
757 // and radeonsi refuses encode contexts below 64x64 (measured).
758 if width < 64 || height < 64 || width % 2 != 0 || height % 2 != 0 {
759 return None;
760 }
761 if fps_num == 0 || fps_den == 0 || bitrate == 0 {
762 return None;
763 }
764 let (display, gbm) = open_devices()?;
765 let coded = Resolution {
766 width: align16(width),
767 height: align16(height),
768 };
769 let framerate = ((fps_num as f64 / fps_den as f64).round() as i64).clamp(1, 240) as u32;
770 let profile = match av1 {
771 true => VAProfile::VAProfileAV1Profile0,
772 false => VAProfile::VAProfileH264Main,
773 };
774 // The driver's own answer to "can you encode this at all": a GPU with no
775 // AV1 encode entrypoint is what makes the caller fall back to `rav1e`,
776 // and asking here is what turns that into a null rather than a failed
777 // encode session halfway through an export.
778 let entrypoints = display.query_config_entrypoints(profile).ok()?;
779 if !entrypoints.contains(&VAEntrypoint::VAEntrypointEncSlice)
780 && !entrypoints.contains(&VAEntrypoint::VAEntrypointEncSliceLP)
781 {
782 return None;
783 }
784 let low_power = entrypoints.contains(&VAEntrypoint::VAEntrypointEncSliceLP);
785 // No B-frames on either codec: coded order stays display order, which is
786 // what both muxers' duration-only timing assumes.
787 let pred_structure = PredictionStructure::LowDelay {
788 limit: (framerate * 2) as u16,
789 };
790 let encoder: Box<dyn VideoEncoder<GenericDmaVideoFrame>> = match av1 {
791 true => {
792 // Constant quality, because that is the only rate control the
793 // vendored AV1 backend takes (`stateless/av1/vaapi.rs` refuses
794 // anything else outright); 128 of 255 is its own reference
795 // value. The caller's bitrate therefore does not reach this
796 // seat -- it reaches `rav1e`, which is the other one.
797 //
798 // ponytail: bitrate-driven AV1 on the GPU needs `VA_RC_CBR`
799 // wired through that backend, which is a change in the vendored
800 // crate rather than here.
801 let config = Av1Config {
802 profile: Av1Profile::Profile0,
803 resolution: Resolution { width, height },
804 pred_structure,
805 initial_tunings: Tunings {
806 rate_control: RateControl::ConstantQuality(128),
807 framerate,
808 ..Default::default()
809 },
810 ..Default::default()
811 };
812 Box::new(
813 Av1Encoder::new_vaapi(
814 display,
815 config,
816 Fourcc::from(b"NV12"),
817 coded,
818 low_power,
819 BlockingMode::Blocking,
820 )
821 .ok()?,
822 )
823 }
824 false => {
825 let config = H264Config {
826 resolution: Resolution { width, height },
827 profile: H264Profile::Main,
828 level: Level::L4,
829 pred_structure,
830 initial_tunings: Tunings {
831 rate_control: RateControl::ConstantBitrate(bitrate),
832 framerate,
833 ..Default::default()
834 },
835 };
836 Box::new(
837 Encoder::new_vaapi(
838 display,
839 config,
840 Fourcc::from(b"NV12"),
841 coded,
842 low_power,
843 BlockingMode::Blocking,
844 )
845 .ok()?,
846 )
847 }
848 };
849 // Allocated at the aligned size, so the buffer's pitch is never smaller
850 // than a padded row.
851 let frame = alloc_nv12(&gbm, coded, false).ok()?;
852 let layout = nv12_layout(coded, frame.get_plane_pitch()[0], false);
853 Some(Self {
854 encoder,
855 h264: !av1,
856 _gbm: gbm,
857 frame,
858 layout,
859 coded,
860 width: width as usize,
861 height: height as usize,
862 timestamp: 0,
863 drained: false,
864 ready: VecDeque::new(),
865 out: Vec::new(),
866 })
867 }
868
869 /// Interleaves one packed I420 picture into the NV12 input buffer.
870 ///
871 /// # Safety
872 /// `src`'s planes must cover `height` (resp. `height / 2`) rows of their
873 /// declared stride.
874 unsafe fn upload(&mut self, src: &VhFrame) -> Result<(), String> {
875 let (w, h) = (self.width, self.height);
876 let (cw, ch) = (w / 2, h / 2);
877 let (aw, ah) = (self.coded.width as usize, self.coded.height as usize);
878 let pitch = self.frame.get_plane_pitch();
879 let mapping = self.frame.map_mut()?;
880 let planes = mapping.get();
881 {
882 let mut dst = planes[0].borrow_mut();
883 for row in 0..ah {
884 // SAFETY: caller contract; rows past the picture repeat the last.
885 let s = unsafe {
886 std::slice::from_raw_parts(src.y.add(row.min(h - 1) * src.y_stride), w)
887 };
888 let dst = &mut dst[row * pitch[0]..row * pitch[0] + aw];
889 dst[..w].copy_from_slice(s);
890 // Macroblock padding: replicate the edge rather than leave the
891 // buffer's garbage there, which would cost bitrate for nothing.
892 dst[w..].fill(s[w - 1]);
893 }
894 }
895 let mut dst = planes[1].borrow_mut();
896 for row in 0..ah / 2 {
897 let src_row = row.min(ch - 1);
898 // SAFETY: as above, for the two chroma planes.
899 let (u, v) = unsafe {
900 (
901 std::slice::from_raw_parts(src.u.add(src_row * src.u_stride), cw),
902 std::slice::from_raw_parts(src.v.add(src_row * src.v_stride), cw),
903 )
904 };
905 let dst = &mut dst[row * pitch[1]..row * pitch[1] + aw];
906 for x in 0..cw {
907 dst[2 * x] = u[x];
908 dst[2 * x + 1] = v[x];
909 }
910 for x in w..aw {
911 dst[x] = dst[x - 2];
912 }
913 }
914 Ok(())
915 }
916
917 /// # Safety
918 /// As [`EncSession::upload`].
919 unsafe fn encode(&mut self, src: &VhFrame, force_keyframe: bool) -> Result<(), String> {
920 // SAFETY: caller contract, forwarded.
921 unsafe { self.upload(src)? };
922 let meta = FrameMetadata {
923 timestamp: self.timestamp,
924 layout: self.layout.clone(),
925 force_keyframe,
926 };
927 self.timestamp += 1;
928 self.encoder
929 .encode(meta, self.frame.clone())
930 .map_err(|e| e.to_string())?;
931 self.collect()
932 }
933
934 /// Moves every access unit the encoder has finished into `ready`.
935 fn collect(&mut self) -> Result<(), String> {
936 while let Some(coded) = self.encoder.poll().map_err(|e| e.to_string())? {
937 let mut au = coded.bitstream;
938 if self.h264 {
939 fix_slice_nal_headers(&mut au);
940 }
941 self.ready.push_back(au);
942 }
943 Ok(())
944 }
945
946 /// Hands the oldest finished access unit to the caller, or reports that
947 /// there is none.
948 fn take(&mut self, out: *mut *const u8, out_len: *mut usize) -> i32 {
949 let Some(au) = self.ready.pop_front() else {
950 return 0;
951 };
952 self.out = au;
953 // SAFETY: caller-guaranteed writable destinations.
954 unsafe {
955 *out = self.out.as_ptr();
956 *out_len = self.out.len();
957 }
958 1
959 }
960}
961
962/// Opens a hardware H.264 encoder for `width`x`height` at `fps_num / fps_den`,
963/// constant bitrate `bitrate` bits per second. Returns null on any failure at
964/// all -- no VA-API runtime, no render node, no encode entrypoint, dimensions
965/// the driver will not take -- and the caller falls back to software.
966#[unsafe(no_mangle)]
967pub extern "C" fn vh_enc_open(
968 width: u32,
969 height: u32,
970 fps_num: u32,
971 fps_den: u32,
972 bitrate: u64,
973) -> *mut c_void {
974 catch_unwind(AssertUnwindSafe(|| {
975 match EncSession::open(width, height, fps_num, fps_den, bitrate) {
976 Some(session) => Box::into_raw(Box::new(session)) as *mut c_void,
977 None => std::ptr::null_mut(),
978 }
979 }))
980 .unwrap_or(std::ptr::null_mut())
981}
982
983/// The same, coding AV1 instead of H.264: null unless this GPU has an AV1
984/// encode entrypoint, which is recent hardware -- the caller then encodes AV1 in
985/// software instead. `bitrate` is not used by this codec (see `EncSession::open`:
986/// the vendored backend is constant-quality only) and is taken all the same, so
987/// the two opens stay one signature.
988///
989/// The session it returns is fed, drained and closed through `vh_enc_frame`,
990/// `vh_enc_drain` and `vh_enc_close` exactly as an H.264 one is; what comes back
991/// out of them is AV1 temporal units rather than Annex-B access units.
992#[unsafe(no_mangle)]
993pub extern "C" fn vh_enc_av1_open(
994 width: u32,
995 height: u32,
996 fps_num: u32,
997 fps_den: u32,
998 bitrate: u64,
999) -> *mut c_void {
1000 catch_unwind(AssertUnwindSafe(|| {
1001 match EncSession::open_codec(width, height, fps_num, fps_den, bitrate, true) {
1002 Some(session) => Box::into_raw(Box::new(session)) as *mut c_void,
1003 None => std::ptr::null_mut(),
1004 }
1005 }))
1006 .unwrap_or(std::ptr::null_mut())
1007}
1008
1009/// Encodes one tightly-strided I420 picture. 1 when `out`/`out_len` describe one
1010/// Annex-B access unit, 0 when the encoder has nothing coded yet, negative on
1011/// error. The bytes stay valid until the next call on this session.
1012///
1013/// # Safety
1014/// `session` must come from [`vh_enc_open`], `frame`'s planes must cover the
1015/// picture at their declared strides, and `out`/`out_len` must be writable.
1016#[unsafe(no_mangle)]
1017pub unsafe extern "C" fn vh_enc_frame(
1018 session: *mut c_void,
1019 frame: *const VhFrame,
1020 force_key: i32,
1021 out: *mut *const u8,
1022 out_len: *mut usize,
1023) -> i32 {
1024 catch_unwind(AssertUnwindSafe(|| {
1025 if session.is_null() || frame.is_null() || out.is_null() || out_len.is_null() {
1026 return -1;
1027 }
1028 // SAFETY: caller-guaranteed live session and readable frame.
1029 let (session, frame) = unsafe { (&mut *(session as *mut EncSession), &*frame) };
1030 if frame.y.is_null() || frame.u.is_null() || frame.v.is_null() {
1031 return -1;
1032 }
1033 if frame.width as usize != session.width
1034 || frame.height as usize != session.height
1035 || frame.y_stride < session.width
1036 || frame.u_stride < session.width / 2
1037 || frame.v_stride < session.width / 2
1038 {
1039 return -1;
1040 }
1041 // SAFETY: caller contract on the plane pointers, sizes checked above.
1042 match unsafe { session.encode(frame, force_key != 0) } {
1043 Ok(()) => session.take(out, out_len),
1044 Err(e) => {
1045 eprintln!("engine_hw: {e}");
1046 -2
1047 }
1048 }
1049 }))
1050 .unwrap_or(-1)
1051}
1052
1053/// Flushes the encoder: 1 while `out`/`out_len` describe another access unit,
1054/// 0 once every picture fed has been handed back, negative on error. Same
1055/// lifetime rule as [`vh_enc_frame`].
1056///
1057/// # Safety
1058/// `session` must come from [`vh_enc_open`]; `out`/`out_len` must be writable.
1059#[unsafe(no_mangle)]
1060pub unsafe extern "C" fn vh_enc_drain(
1061 session: *mut c_void,
1062 out: *mut *const u8,
1063 out_len: *mut usize,
1064) -> i32 {
1065 catch_unwind(AssertUnwindSafe(|| {
1066 if session.is_null() || out.is_null() || out_len.is_null() {
1067 return -1;
1068 }
1069 // SAFETY: caller-guaranteed live session.
1070 let session = unsafe { &mut *(session as *mut EncSession) };
1071 if !session.drained {
1072 if let Err(e) = session.encoder.drain().map_err(|e| e.to_string()) {
1073 eprintln!("engine_hw: {e}");
1074 return -2;
1075 }
1076 session.drained = true;
1077 }
1078 match session.collect() {
1079 Ok(()) => session.take(out, out_len),
1080 Err(e) => {
1081 eprintln!("engine_hw: {e}");
1082 -2
1083 }
1084 }
1085 }))
1086 .unwrap_or(-1)
1087}
1088
1089/// Releases an encode session. Safe to call with null.
1090///
1091/// # Safety
1092/// `session` must come from [`vh_enc_open`] and must not be used afterwards.
1093#[unsafe(no_mangle)]
1094pub unsafe extern "C" fn vh_enc_close(session: *mut c_void) {
1095 let _ = catch_unwind(AssertUnwindSafe(|| {
1096 if !session.is_null() {
1097 // SAFETY: pointer came from `Box::into_raw` in `vh_enc_open`.
1098 drop(unsafe { Box::from_raw(session as *mut EncSession) });
1099 }
1100 }));
1101}
1102
1103#[cfg(test)]
1104mod tests {
1105 use super::*;
1106
1107 /// Runs against whatever GPU this machine has -- and passes on one with no
1108 /// VA-API at all, which is exactly what `None` means here. What it pins is
1109 /// the *shape* of the answer, the contents being the driver's: nothing may
1110 /// be claimed that this plugin cannot actually reach.
1111 #[test]
1112 fn the_caps_query_never_claims_more_than_this_plugin_implements() {
1113 let Some(caps) = query_caps() else {
1114 return;
1115 };
1116 eprintln!("{caps:?}");
1117 // Encode is this plugin's two seats and no others, whatever entrypoints
1118 // the driver has: an HEVC or VP9 EncSlice is not an encoder here.
1119 assert_eq!(caps.encode & !(CAP_H264 | CAP_AV1), 0, "{caps:?}");
1120 // A 10-bit claim is a decode claim -- same profile family, read back
1121 // through P010 -- and there is no 10-bit encode path at all.
1122 assert_eq!(caps.decode_10bit & !caps.decode, 0, "{caps:?}");
1123 // H.264 here is 8-bit 4:2:0; the table has no 10-bit profile for it.
1124 assert_eq!(caps.decode_10bit & CAP_H264, 0, "{caps:?}");
1125 }
1126}