forge
Explore
Log in

Don't you dare go Hollow

edith

Clone
★ 0

0 watching0 forksRust18.3 MiB7f487c1Tahinli3 months ago659 commits

lib.rs2166 lines, 91.7 KiBHistoryRawDownload
1//! VA-API decode (H.264, HEVC, VP9 and AV1) and encode (H.264 and HEVC, and AV1
2//! where 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//! That guarantee rests on `panic = "unwind"`, and it has a floor it can never
10//! reach whatever the panic strategy is: Mesa runs its own C worker threads and
11//! calls libc `abort()` from them when the video ring resets (measured
12//! 2026-08-13, `vcn_unified_0`, mesa 26.1.6). No `catch_unwind` can see a
13//! foreign thread's `abort`. So no *encode* entry point of this plugin is
14//! called in the editor's process any more: the editor still `dlopen`s the
15//! library to see whether the `vh_enc_*` symbols are there at all, which opens
16//! no VA-API display and starts no driver thread, and every call through them is
17//! made by the `hw-encode-child` helper, one process per session. A driver that
18//! aborts now costs an export its seat rather than costing a person their
19//! session ([`engine::hwproc`](../engine/hwproc/index.html)).
20//!
21//! corner-cut: *decode* is still in the editor's own address space, where the
22//! same abort would still be fatal -- and the same ring hangs it (mmhub page
23//! faults, this box, 2026-08-13). The upgrade path is the seam that already
24//! exists: give `vh_open_at`/`vh_next_frame` the message tags `vh_enc_*` have in
25//! `hwproc` and let the same helper hold both.
26
27use std::collections::VecDeque;
28use std::ffi::{CStr, c_char, c_void};
29use std::os::fd::IntoRawFd;
30use std::panic::{AssertUnwindSafe, catch_unwind};
31use std::path::{Path, PathBuf};
32use std::rc::Rc;
33
34use cros_codecs::backend::vaapi::decoder::VaapiBackend;
35use cros_codecs::backend::vaapi::encoder::VaapiBackend as VaapiEncBackend;
36use cros_codecs::codec::av1::parser::Profile as Av1Profile;
37use cros_codecs::codec::h264::parser::{Level, Profile as H264Profile};
38use cros_codecs::codec::h265::parser::{Level as H265Level, Profile as H265Profile};
39use cros_codecs::decoder::stateless::av1::Av1;
40use cros_codecs::decoder::stateless::h264::H264;
41use cros_codecs::decoder::stateless::h265::H265;
42use cros_codecs::decoder::stateless::vp9::Vp9;
43use cros_codecs::decoder::stateless::{DecodeError, StatelessDecoder, StatelessVideoDecoder};
44use cros_codecs::decoder::{BlockingMode, DecodedHandle, DecoderEvent, StreamInfo};
45use cros_codecs::encoder::av1::EncoderConfig as Av1Config;
46use cros_codecs::encoder::h264::EncoderConfig as H264Config;
47use cros_codecs::encoder::h265::ColourDescription as H265Colour;
48use cros_codecs::encoder::h265::EncoderConfig as H265Config;
49use cros_codecs::encoder::stateless::av1::StatelessEncoder as Av1StatelessEncoder;
50use cros_codecs::encoder::stateless::h264::StatelessEncoder;
51use cros_codecs::encoder::stateless::h265::StatelessEncoder as H265StatelessEncoder;
52use cros_codecs::encoder::{
53 FrameMetadata, PredictionStructure, RateControl, Tunings, VideoEncoder,
54};
55use cros_codecs::image_processing::nv12_to_i420;
56use cros_codecs::libva::{
57 Display, Image, Surface, VA_FOURCC_NV12, VA_FOURCC_P010, VAEntrypoint, VAImageFormat,
58 VAProfile,
59};
60use cros_codecs::video_frame::VideoFrame;
61use cros_codecs::video_frame::frame_pool::{FramePool, PooledVideoFrame};
62use cros_codecs::video_frame::generic_dma_video_frame::GenericDmaVideoFrame;
63use cros_codecs::video_frame::{UV_PLANE, Y_PLANE};
64use cros_codecs::{Fourcc, FrameLayout, PlaneLayout, Resolution};
65use gbm::{BufferObjectFlags, Format as GbmFormat};
66
67use engine::demux::{Codec, Demuxer};
68use engine::hw::{CAP_AV1, CAP_H264, CAP_HEVC, CAP_VP9, VhCaps, VhDma, VhFrame, VhMeta};
69
70type PooledFrame = PooledVideoFrame<GenericDmaVideoFrame>;
71type Dec<C> = StatelessDecoder<C, VaapiBackend<PooledFrame>>;
72type Handle = <Dec<H264> as StatelessVideoDecoder>::Handle;
73
74/// One decoder per codec the demuxer can hand us. They all share the VA-API
75/// backend and therefore the same [`Handle`], so everything past `decode` is
76/// common; which one exists is decided by the container, never by the caller --
77/// which is why the plugin's C ABI is unchanged and an older `libengine_hw.so`
78/// still loads and still decodes H.264 (it simply refuses the newer codecs'
79/// files at `Demuxer`).
80///
81/// 4:2:0 only, 8- or 10-bit: HEVC Main and Main 10, VP9 profile 0 and 2, AV1
82/// Main at either depth.
83/// A 10-bit stream decodes into a P010 pool and is read back down to the 8-bit
84/// I420 every frame here is ([`Session::emit`]).
85///
86/// corner-cut: 10-bit is *carried* 8-bit, because [`VhFrame`] is a byte-per-sample
87/// interface all the way to the renderer. That costs the low two bits of a Main
88/// 10 source; the upgrade path is a 16-bit `VhFrame`, which is a change to every
89/// stage between here and the texture upload, not to this file.
90/// VP9 profile 2 reaches the P010 pool like the rest: a VP9 stream states its
91/// depth in no container record the way an `av1C` or an `hvcC` does, so
92/// `Demuxer` reads it off the first keyframe's uncompressed header
93/// (`demux::vp9_bit_depth`) rather than assuming the 8 bits of profile 0.
94enum Decoder {
95 H264(Dec<H264>),
96 Hevc(Dec<H265>),
97 Vp9(Dec<Vp9>),
98 Av1(Dec<Av1>),
99}
100
101impl Decoder {
102 fn get(&mut self) -> &mut dyn StatelessVideoDecoder<Handle = Handle> {
103 match self {
104 Self::H264(d) => d,
105 Self::Hevc(d) => d,
106 Self::Vp9(d) => d,
107 Self::Av1(d) => d,
108 }
109 }
110}
111
112type Encoder = StatelessEncoder<
113 GenericDmaVideoFrame,
114 VaapiEncBackend<GenericDmaVideoFrame, Surface<GenericDmaVideoFrame>>,
115>;
116type Av1Encoder = Av1StatelessEncoder<
117 GenericDmaVideoFrame,
118 VaapiEncBackend<GenericDmaVideoFrame, Surface<GenericDmaVideoFrame>>,
119>;
120type HevcEncoder = H265StatelessEncoder<
121 GenericDmaVideoFrame,
122 VaapiEncBackend<GenericDmaVideoFrame, Surface<GenericDmaVideoFrame>>,
123>;
124
125/// Ceiling on decode/drain iterations that make no progress. VA-API in blocking
126/// mode should always either hand back an event or accept input; this only
127/// exists so a misbehaving driver returns an error instead of hanging the app.
128const STALL_LIMIT: u32 = 10_000;
129
130/// How many undecodable access units a seek may drop before the session gives
131/// up and calls the stream broken. An open GOP's leading pictures are a handful
132/// (a Blu-ray remux's are 8-16); a file that keeps failing past this is not one
133/// we restarted in the middle of, so the error is real and the caller still
134/// hears it.
135const LEADING_LIMIT: u32 = 64;
136
137/// How many pictures handed out as DRM-PRIME buffers stay un-decoded-over, and
138/// therefore how many extra buffers the pool reserves the moment a caller asks
139/// for one. The export's decode channel is two pictures deep and it encodes the
140/// one it is holding, so at most four are ever outstanding; the rest is margin,
141/// at ~3 MB of video memory each.
142const DMA_HOLD: usize = 6;
143
144/// How far ahead of the decode position [`Session::seek_to`] walks forward
145/// rather than flushing, in seconds of the stream's own frames. A silence cut
146/// lands the next span ahead of the decoder by the length of what it removed
147/// -- tenths of a second -- and walking that forward costs only the decode of
148/// the frames in between, dropped without the read-back ([`Session::pump`]'s
149/// skip path) with the decoder's reference chain and pipeline depth left
150/// standing. The flush it replaces costs a decoder reset, a demuxer seek to
151/// the random access point, up to a group of skip-decoded pictures behind it,
152/// and a full re-prime before the first frame is out again (~178 ms measured
153/// at 4K, which is longer than the clips a silence cut leaves); past half a
154/// second of walking, the skip-decode run alone approaches that bill and a
155/// real seek wins.
156const FORWARD_SECS: f64 = 0.5;
157
158/// The forward reach in frames: [`FORWARD_SECS`] at the stream's own rate.
159/// `0` for a rate the stream does not really state, which is "never forward"
160/// -- exactly the flush every reposition did before this distinction existed.
161fn forward_limit(frame_rate: f64) -> u32 {
162 (FORWARD_SECS * frame_rate).round().max(0.) as u32
163}
164
165/// How a reposition to `target` (a 0-based display frame) is reached from
166/// `position`, the frame the session would hand out next. Pure arithmetic,
167/// so every shape of the answer is testable without a GPU.
168#[derive(Debug, PartialEq, Eq, Clone, Copy)]
169enum Reposition {
170 /// Decode forward from where the session stands, dropping this many
171 /// pictures on the way: no flush, no demuxer seek, no re-prime.
172 Forward(u32),
173 /// Flush the decoder and seek the demuxer to the random access point at
174 /// or before `target`.
175 Flush,
176}
177
178fn reposition(position: i64, target: i64, frame_count: u32, limit: u32) -> Reposition {
179 // A decoder cannot walk backwards, and a target at or past the last frame
180 // is not one decoding forward can hand out -- both take the seek that has
181 // always handled them, EOF included.
182 if target < position || target >= i64::from(frame_count) {
183 return Reposition::Flush;
184 }
185 match u32::try_from(target - position) {
186 Ok(ahead) if ahead <= limit => Reposition::Forward(ahead),
187 _ => Reposition::Flush,
188 }
189}
190
191/// The skip a forward reposition leaves standing: `ahead` itself, replacing
192/// whatever skip was undrained -- `_standing` is read by no one, on purpose.
193/// [`Session::pump`] advances `position` for every handle it pops, dropped
194/// and delivered alike, so the next picture delivered is always
195/// `position + skip`: only a replacement keeps that on the target. An
196/// accumulate would land `ahead` frames past it -- and silently, because the
197/// pictures keep arriving (a stacked reseek before the first drains, or a
198/// flush whose RAP skip is still standing when a forward span is asked).
199fn forward_skip(_standing: u32, ahead: u32) -> u32 {
200 ahead
201}
202
203struct Session {
204 decoder: Decoder,
205 /// NV12 (or, for a 10-bit stream, P010) descriptor for `vaGetImage`,
206 /// queried once at open.
207 nv12_format: VAImageFormat,
208 /// Whether the surfaces are P010 rather than NV12, which is the one thing
209 /// the read-back has to do differently.
210 ten_bit: bool,
211 pool: FramePool<GenericDmaVideoFrame>,
212 demuxer: Demuxer,
213 meta: VhMeta,
214 ready: VecDeque<Handle>,
215 /// Remaining bytes of the access unit currently being fed, if any.
216 pending: Vec<u8>,
217 timestamp: u64,
218 flushed: bool,
219 /// Pictures still to be decoded and thrown away to land on a seek target.
220 skip: u32,
221 /// The display frame the next `pump` would hand out, however it gets
222 /// there: one further along for every handle taken off `ready`, skipped
223 /// past and delivered alike. The one thing that can tell a reposition
224 /// *ahead* of the decoder from one behind it ([`Session::seek_to`]).
225 position: i64,
226 /// Access units dropped because they referenced pictures this session never
227 /// decoded -- see [`Session::pump`]. Counted rather than flagged so the
228 /// tolerance ends somewhere, and raised to [`LEADING_LIMIT`] the moment a
229 /// picture is handed out, which is where the window closes.
230 leading: u32,
231 /// Tightly packed I420 handed out through [`VhFrame`]; reused every frame,
232 /// which is exactly why the pointers are only valid until the next call.
233 out: Vec<u8>,
234 luma: usize,
235 chroma: usize,
236 /// What the caller's encoder can read straight off the GPU, asked once per
237 /// [`vh_next_frame_dma`] call and `None` for every read-back caller.
238 want: Option<VhDma>,
239 /// The descriptor the last such call produced, its file descriptor already
240 /// belonging to the caller. `None` says that picture was read back instead.
241 dma: Option<VhDma>,
242 /// Pictures handed out as DRM-PRIME buffers, newest last: the pool takes a
243 /// buffer back the moment its handle drops, and the decoder would write the
244 /// next picture straight into the one an encoder is still reading. Bounded
245 /// by [`Session::hold`], which is what the pool reserved for it.
246 held: VecDeque<Handle>,
247 /// Extra pool buffers reserved for [`Session::held`]: [`DMA_HOLD`] once a
248 /// caller has asked for a buffer *before* the pool was sized, and 0
249 /// otherwise -- a session whose pool is already sized may not hold anything
250 /// back, because those buffers are the decoder's own.
251 hold: usize,
252 /// Whether the pool has been sized, which happens once, at the first
253 /// `FormatChanged`.
254 sized: bool,
255}
256
257/// Mesa's GBM cannot allocate an NV12 buffer object at all (measured on
258/// radeonsi: every flag/modifier combination returns NULL), so we allocate one
259/// linear single-plane R8 buffer big enough for luma + chroma and describe the
260/// NV12 layout inside it ourselves. VA-API imports it as one DRM-PRIME object
261/// with two planes at known offsets, which is exactly what the descriptor in
262/// `GenericDmaVideoFrame` emits.
263///
264/// `ten_bit` asks for the same thing in P010: the very same two-plane 4:2:0
265/// shape with 16-bit samples, so the buffer is simply twice as wide.
266fn alloc_nv12(
267 gbm: &gbm::Device<std::fs::File>,
268 coded: Resolution,
269 ten_bit: bool,
270) -> Result<GenericDmaVideoFrame, String> {
271 let rows = coded.height + coded.height.div_ceil(2);
272 let width = coded.width * if ten_bit { 2 } else { 1 };
273 let bo = gbm
274 .create_buffer_object::<()>(width, rows, GbmFormat::R8, BufferObjectFlags::LINEAR)
275 .map_err(|e| format!("gbm R8 {width}x{rows} allocation failed: {e}"))?;
276 let pitch = bo.stride().map_err(|e| e.to_string())? as usize;
277 let fd = bo.fd().map_err(|e| e.to_string())?;
278 GenericDmaVideoFrame::new(
279 vec![std::fs::File::from(fd)],
280 nv12_layout(coded, pitch, ten_bit),
281 )
282}
283
284/// Two NV12 (or P010) planes packed one after the other in a single buffer
285/// object.
286fn nv12_layout(coded: Resolution, pitch: usize, ten_bit: bool) -> FrameLayout {
287 FrameLayout {
288 format: (
289 Fourcc::from(if ten_bit { b"P010" } else { b"NV12" }),
290 0, /* DRM_FORMAT_MOD_LINEAR */
291 ),
292 size: coded,
293 planes: vec![
294 PlaneLayout {
295 buffer_index: 0,
296 offset: 0,
297 stride: pitch,
298 },
299 PlaneLayout {
300 buffer_index: 0,
301 offset: pitch * coded.height as usize,
302 stride: pitch,
303 },
304 ],
305 }
306}
307
308/// First render node that gives us both a VA display and a GBM device. Which
309/// node is the right one is a per-machine question, so we probe rather than
310/// hardcode renderD128.
311fn open_devices() -> Option<(Rc<Display>, gbm::Device<std::fs::File>)> {
312 let mut nodes: Vec<PathBuf> = std::fs::read_dir("/dev/dri")
313 .ok()?
314 .flatten()
315 .map(|e| e.path())
316 .filter(|p| {
317 p.file_name()
318 .and_then(|n| n.to_str())
319 .is_some_and(|n| n.starts_with("renderD"))
320 })
321 .collect();
322 nodes.sort();
323 nodes.into_iter().find_map(|node| {
324 let display = Display::open_drm_display(&node).ok()?;
325 let file = std::fs::OpenOptions::new()
326 .read(true)
327 .write(true)
328 .open(&node)
329 .ok()?;
330 let gbm = gbm::Device::new(file).ok()?;
331 Some((display, gbm))
332 })
333}
334
335impl Session {
336 fn open(path: &Path) -> Option<Self> {
337 let (meta, demuxer) = Demuxer::open(path).ok()?;
338 let (display, gbm) = open_devices()?;
339 // A 10-bit stream decodes into P010 surfaces and is read back through a
340 // P010 image; a driver that has no such image format is one this cannot
341 // read 10-bit off at all, which is a null session and a software
342 // fallback like any other refusal here.
343 let ten_bit = demuxer.bit_depth() > 8;
344 let want = if ten_bit {
345 VA_FOURCC_P010
346 } else {
347 VA_FOURCC_NV12
348 };
349 let nv12_format = display
350 .query_image_formats()
351 .ok()?
352 .into_iter()
353 .find(|f| f.fourcc == want)?;
354 let decoder = match meta.codec {
355 Codec::H264 => {
356 Decoder::H264(Dec::<H264>::new_vaapi(display, BlockingMode::Blocking).ok()?)
357 }
358 Codec::Hevc => {
359 Decoder::Hevc(Dec::<H265>::new_vaapi(display, BlockingMode::Blocking).ok()?)
360 }
361 Codec::Vp9 => {
362 Decoder::Vp9(Dec::<Vp9>::new_vaapi(display, BlockingMode::Blocking).ok()?)
363 }
364 Codec::Av1 => {
365 Decoder::Av1(Dec::<Av1>::new_vaapi(display, BlockingMode::Blocking).ok()?)
366 }
367 };
368 let pool = FramePool::new(move |info: &StreamInfo| {
369 alloc_nv12(&gbm, info.coded_resolution, ten_bit).expect("output frame allocation failed")
370 });
371 Some(Self {
372 decoder,
373 nv12_format,
374 ten_bit,
375 pool,
376 demuxer,
377 meta: VhMeta {
378 width: meta.width,
379 height: meta.height,
380 frame_rate: meta.frame_rate,
381 frame_count: meta.frame_count,
382 },
383 ready: VecDeque::new(),
384 pending: Vec::new(),
385 timestamp: 0,
386 flushed: false,
387 skip: 0,
388 position: 0,
389 // A stream read from its own beginning has no missing references
390 // and therefore no leading pictures to forgive: the window opens
391 // only for a session positioned somewhere else ([`Session::open_at`]),
392 // so a file whose first picture will not decode is still refused at
393 // the door rather than opening onto nothing.
394 leading: LEADING_LIMIT,
395 out: Vec::new(),
396 luma: 0,
397 chroma: 0,
398 want: None,
399 dma: None,
400 held: VecDeque::new(),
401 hold: 0,
402 sized: false,
403 })
404 }
405
406 /// As [`Session::open`], but positioned so the first picture handed out is
407 /// sample `target_sample` (1-based): decode restarts at the sync sample at
408 /// or before it and the pictures in between are dropped unread.
409 fn open_at(path: &Path, target_sample: u32) -> Option<Self> {
410 let mut session = Self::open(path)?;
411 // The ABI still speaks 1-based sample ids, the demuxer speaks 0-based
412 // display frames -- and answers with a signed one, since a sync sample
413 // inside what the edit list trims sits before frame 0.
414 let target_frame = target_sample.saturating_sub(1);
415 let first = session.demuxer.seek_to_sync_at_or_before(target_frame);
416 session.skip = (i64::from(target_frame) - first).max(0) as u32;
417 session.position = first;
418 if target_frame > 0 {
419 session.leading = 0;
420 }
421 Some(session)
422 }
423
424 /// Repositions an **open** session, exactly as [`Session::open_at`] positions
425 /// a new one: the next [`Session::pump`] hands back sample `target_sample`.
426 ///
427 /// This is what a seek costs when the session is kept, and most of it is
428 /// skippable: a target *ahead* of where the decoder stands, within
429 /// [`FORWARD_SECS`] of it, is reached by decoding on and dropping the
430 /// pictures in between ([`reposition`]) -- no flush, no demuxer seek, no
431 /// re-prime -- which is the landing a silence cut leaves at every boundary
432 /// it cuts to, a fraction of a second ahead of the clip that just ended.
433 /// Everything else pays the demuxer seek and the decoder flush, and *not*
434 /// the VA-API initialisation (~90 ms measured), the render node probe, the
435 /// container parse and the surface pool that opening one again pays for.
436 ///
437 /// The flush is the whole of the decoder's reset: cros-codecs finishes what
438 /// is in flight and goes to `Reset`, from where it resumes on the next
439 /// parameter set or key frame -- and every sync sample this demuxer hands
440 /// out carries the parameter sets in front of it (`demux`'s `is_sync`
441 /// re-injection), which is exactly where a seek lands. The pictures the
442 /// flush makes ready are dropped with `ready`: they belong to where the
443 /// session *was*.
444 fn seek_to(&mut self, target_sample: u32) -> Result<(), String> {
445 // The same arithmetic `open_at` does, for the same reason.
446 let target_frame = target_sample.saturating_sub(1);
447 if let Reposition::Forward(ahead) = reposition(
448 self.position,
449 i64::from(target_frame),
450 self.meta.frame_count,
451 forward_limit(self.meta.frame_rate),
452 ) {
453 // Nothing about the session moves but the skip: not the decoder,
454 // not the access unit half-fed to it, not the pictures already
455 // waiting in `ready` -- the skip walks past all of them exactly
456 // as it walks past the ones still to decode, one `position` step
457 // per handle either way. It *replaces* whatever skip was
458 // standing, never adds to it: `position` already counts every
459 // handle popped, dropped ones included, so the picture delivered
460 // is always `position + skip` ([`forward_skip`]) -- an accumulate
461 // would land `ahead` frames past the target, silently.
462 self.skip = forward_skip(self.skip, ahead);
463 return Ok(());
464 }
465 self.decoder.get().flush().map_err(|e| e.to_string())?;
466 // Drain what the flush completed, dropping every handle: each one holds
467 // a pool buffer out of circulation, and none of them is ours to show.
468 while let Some(event) = self.decoder.get().next_event() {
469 if let DecoderEvent::FormatChanged = event {
470 let info = self
471 .decoder
472 .get()
473 .stream_info()
474 .ok_or("format changed without stream info")?
475 .clone();
476 self.pool.resize(&info);
477 }
478 }
479 self.ready.clear();
480 self.pending.clear();
481 self.flushed = false;
482 let first = self.demuxer.seek_to_sync_at_or_before(target_frame);
483 self.skip = (i64::from(target_frame) - first).max(0) as u32;
484 self.position = first;
485 // ...and the same open-GOP window: a session positioned anywhere but the
486 // start may meet leading pictures that reference what it never decoded.
487 self.leading = if target_frame > 0 { 0 } else { LEADING_LIMIT };
488 Ok(())
489 }
490
491 /// Pumps the decoder until one picture is ready. `Ok(false)` is clean EOF.
492 fn pump(&mut self) -> Result<bool, String> {
493 let mut stalls = 0u32;
494 loop {
495 // Stop draining as soon as we have a picture: every handle we hold
496 // keeps a pool buffer out of circulation.
497 while self.ready.is_empty() {
498 match self.decoder.get().next_event() {
499 Some(DecoderEvent::FrameReady(handle)) => self.ready.push_back(handle),
500 Some(DecoderEvent::FormatChanged) => {
501 let mut info = self
502 .decoder
503 .get()
504 .stream_info()
505 .ok_or("format changed without stream info")?
506 .clone();
507 // The buffers a caller may hold on to are *extra*: the
508 // count the decoder asks for is what it needs to keep
509 // decoding, and lending one of those out is a stall.
510 info.min_num_frames += self.hold;
511 self.pool.resize(&info);
512 self.sized = true;
513 }
514 None => break,
515 }
516 }
517 if let Some(handle) = self.ready.pop_front() {
518 // One picture further along, shown or skipped past alike:
519 // this is the only place [`Session::position`] walks.
520 self.position += 1;
521 // Seek discards: dropping the handle skips the `vaGetImage`
522 // read-back (~1.2 ms/picture) and frees its pool buffer.
523 if self.skip > 0 {
524 self.skip -= 1;
525 continue;
526 }
527 self.deliver(handle);
528 // Past the random access point's leading pictures: a decode
529 // error from here on is a real one again.
530 self.leading = LEADING_LIMIT;
531 return Ok(true);
532 }
533 if self.flushed {
534 return Ok(false);
535 }
536
537 if self.pending.is_empty() {
538 match self.demuxer.next_access_unit() {
539 Ok(Some(au)) => self.pending = au,
540 Ok(None) => {
541 self.decoder.get().flush().map_err(|e| e.to_string())?;
542 self.flushed = true;
543 continue;
544 }
545 Err(e) => return Err(e.to_string()),
546 }
547 }
548
549 let Self {
550 decoder,
551 pool,
552 pending,
553 timestamp,
554 leading,
555 ..
556 } = self;
557 match decoder
558 .get()
559 .decode(*timestamp, pending, &mut || pool.alloc())
560 {
561 Ok(0) => return Err("decoder consumed no input".into()),
562 Ok(n) => {
563 pending.drain(..n.min(pending.len()));
564 if pending.is_empty() {
565 *timestamp += 1;
566 }
567 stalls = 0;
568 }
569 // Both mean "handle pending events, then resubmit the same data".
570 Err(DecodeError::CheckEvents) | Err(DecodeError::NotEnoughOutputBuffers(_)) => {
571 stalls += 1;
572 if stalls > STALL_LIMIT {
573 return Err("decoder stalled waiting for output buffers".into());
574 }
575 }
576 // A picture that references pictures we never decoded, which is
577 // what an open GOP's leading pictures are after a seek: they
578 // display *before* the random access point we restarted at, so
579 // they are not ours to show and the stream is not broken. Drop
580 // the rest of the access unit (they are picture-aligned) and
581 // walk on -- failing here is what used to make a Blu-ray remux
582 // fall back to software on 17 seeks out of 20.
583 Err(e) if *leading < LEADING_LIMIT => {
584 if *leading == 0 {
585 eprintln!("engine_hw: skipping leading pictures after seek ({e})");
586 }
587 *leading += 1;
588 pending.clear();
589 *timestamp += 1;
590 }
591 Err(e) => return Err(e.to_string()),
592 }
593 }
594 }
595
596 /// Hands one decoded picture to the caller: as the buffer it was decoded
597 /// into where that is what the caller asked for and the encoder on the
598 /// other side can read it, and as read-back I420 everywhere else.
599 fn deliver(&mut self, handle: Handle) {
600 self.dma = None;
601 if self.hold > 0 && let Some(dma) = self.export_dma(&handle) {
602 self.meta.width = dma.width;
603 self.meta.height = dma.height;
604 self.dma = Some(dma);
605 // Kept out of the pool until the caller is [`DMA_HOLD`] pictures
606 // past it, by which time nothing is reading it any more.
607 self.held.push_back(handle);
608 while self.held.len() > self.hold {
609 self.held.pop_front();
610 }
611 return;
612 }
613 self.emit(handle);
614 }
615
616 /// This picture's surface as a DRM-PRIME buffer, if it *is* the shape the
617 /// caller's encoder takes -- one composed two-plane layer in at most two
618 /// objects, the fourcc and both sizes it asked for. `None` for every other
619 /// answer, and the caller then gets the pixels it always got rather than a
620 /// failure.
621 fn export_dma(&self, handle: &Handle) -> Option<VhDma> {
622 let want = self.want?;
623 let res = handle.display_resolution();
624 if (res.width, res.height) != (want.width, want.height) {
625 return None;
626 }
627 // Cheap no-op in blocking mode, but the encoder must never read a
628 // surface the decoder has not finished writing.
629 let _ = DecodedHandle::sync(handle);
630 let borrowed = handle.borrow();
631 // The *display* surface for the same reason [`Session::emit`] reads it:
632 // an AV1 picture with film grain is displayed from a second surface.
633 let mut desc = borrowed.display_surface().export_prime().ok()?;
634 let layer = desc.layers.first()?;
635 if desc.layers.len() != 1
636 || layer.num_planes != 2
637 || desc.fourcc != want.fourcc
638 || desc.width != want.coded_width
639 || desc.height != want.coded_height
640 {
641 return None;
642 }
643 // Whatever the driver says the two planes live in, said back to it
644 // unchanged on the import: radeonsi answers with an object per plane,
645 // other drivers with one for both, and neither is ours to reinterpret.
646 let (offset, stride) = (
647 [layer.offset[0], layer.offset[1]],
648 [layer.pitch[0], layer.pitch[1]],
649 );
650 let planes = [layer.object_index[0] as usize, layer.object_index[1] as usize];
651 if planes[0] != 0 || planes[1] > 1 || desc.objects.len() != planes[1] + 1 {
652 return None;
653 }
654 let modifier = desc.objects[0].drm_format_modifier;
655 // Handed over with the descriptor: the caller closes them.
656 let second = (planes[1] == 1)
657 .then(|| desc.objects.pop().map(|object| object.fd.into_raw_fd()))
658 .flatten()
659 .unwrap_or(-1);
660 let first = desc.objects.remove(0).fd.into_raw_fd();
661 Some(VhDma {
662 fd: [first, second],
663 fourcc: desc.fourcc,
664 modifier,
665 coded_width: desc.width,
666 coded_height: desc.height,
667 width: res.width,
668 height: res.height,
669 offset,
670 stride,
671 })
672 }
673
674 /// Copies a decoded NV12 surface into `self.out` as packed I420.
675 fn emit(&mut self, handle: Handle) {
676 let res = handle.display_resolution();
677 let (w, h) = (res.width as usize, res.height as usize);
678 let (cw, ch) = (w.div_ceil(2), h.div_ceil(2));
679 if self.luma != w * h || self.chroma != cw * ch {
680 self.luma = w * h;
681 self.chroma = cw * ch;
682 self.out = vec![0u8; self.luma + 2 * self.chroma];
683 }
684 self.meta.width = res.width;
685 self.meta.height = res.height;
686
687 // Read back with vaGetImage rather than mapping our own DMA-BUF: on a
688 // discrete GPU that buffer lives in VRAM and a CPU read of it runs at
689 // ~44 MB/s over the PCIe BAR (measured), which costs 350 ms/frame. The
690 // driver copies into host-visible memory for us instead.
691 // Cheap no-op in blocking mode, but pixels must never be read early.
692 let _ = DecodedHandle::sync(&handle);
693 let borrowed = handle.borrow();
694 let size = (w as u32, h as u32);
695 // The *display* surface, which is the reconstructed picture for every
696 // codec here but the second, grain-synthesized one for an AV1 frame that
697 // asks for film grain -- reading the reconstructed surface of such a
698 // frame would show the film with its grain stripped off.
699 let image = Image::create_from(borrowed.display_surface(), self.nv12_format, size, size)
700 .expect("vaGetImage failed");
701 let va = *image.image();
702 let data: &[u8] = image.as_ref();
703
704 let (dst_y, rest) = self.out.split_at_mut(self.luma);
705 let (dst_u, dst_v) = rest.split_at_mut(self.chroma);
706 if self.ten_bit {
707 p010_to_i420(
708 &data[va.offsets[Y_PLANE] as usize..],
709 va.pitches[Y_PLANE] as usize,
710 dst_y,
711 &data[va.offsets[UV_PLANE] as usize..],
712 va.pitches[UV_PLANE] as usize,
713 dst_u,
714 dst_v,
715 w,
716 h,
717 );
718 return;
719 }
720 nv12_to_i420(
721 &data[va.offsets[Y_PLANE] as usize..],
722 va.pitches[Y_PLANE] as usize,
723 dst_y,
724 w,
725 &data[va.offsets[UV_PLANE] as usize..],
726 va.pitches[UV_PLANE] as usize,
727 dst_u,
728 cw,
729 dst_v,
730 cw,
731 w,
732 h,
733 );
734 }
735
736 fn fill(&self, out: &mut VhFrame) {
737 let w = self.meta.width as usize;
738 let cw = w.div_ceil(2);
739 out.y = self.out.as_ptr();
740 // SAFETY: `out` was sized to luma + 2 * chroma just above in `emit`.
741 unsafe {
742 out.u = self.out.as_ptr().add(self.luma);
743 out.v = self.out.as_ptr().add(self.luma + self.chroma);
744 }
745 out.y_stride = w;
746 out.u_stride = cw;
747 out.v_stride = cw;
748 out.width = self.meta.width;
749 out.height = self.meta.height;
750 }
751}
752
753/// One P010 picture down to packed 8-bit I420: [`nv12_to_i420`] for a surface
754/// whose samples are 16-bit little-endian with the value in the **high** bits,
755/// which is what P010 means. The high byte of each pair is therefore the 10-bit
756/// sample shifted down by two, i.e. the 8-bit one -- no rounding, because a
757/// second read of the low byte costs more than the half-bit it would buy.
758fn p010_to_i420(
759 src_y: &[u8],
760 src_y_pitch: usize,
761 dst_y: &mut [u8],
762 src_uv: &[u8],
763 src_uv_pitch: usize,
764 dst_u: &mut [u8],
765 dst_v: &mut [u8],
766 width: usize,
767 height: usize,
768) {
769 for row in 0..height {
770 let src = &src_y[row * src_y_pitch..];
771 let dst = &mut dst_y[row * width..row * width + width];
772 for (x, out) in dst.iter_mut().enumerate() {
773 *out = src[2 * x + 1];
774 }
775 }
776 let (cw, ch) = (width.div_ceil(2), height.div_ceil(2));
777 for row in 0..ch {
778 let src = &src_uv[row * src_uv_pitch..];
779 let (u, v) = (
780 &mut dst_u[row * cw..row * cw + cw],
781 &mut dst_v[row * cw..row * cw + cw],
782 );
783 for x in 0..cw {
784 u[x] = src[4 * x + 1];
785 v[x] = src[4 * x + 3];
786 }
787 }
788}
789
790/// Opens `path` for hardware decode, positioned so the first
791/// [`vh_next_frame`] returns sample `target_sample` (1-based; 0 and 1 both mean
792/// the start of the stream). Returns null on any failure at all: no libva
793/// runtime, no render node, unsupported profile, unreadable file.
794///
795/// # Safety
796/// `path` must be a valid NUL-terminated C string.
797#[unsafe(no_mangle)]
798pub unsafe extern "C" fn vh_open_at(path: *const c_char, target_sample: u32) -> *mut c_void {
799 catch_unwind(AssertUnwindSafe(|| {
800 if path.is_null() {
801 return std::ptr::null_mut();
802 }
803 // SAFETY: caller-guaranteed NUL-terminated string, read before return.
804 let path = unsafe { CStr::from_ptr(path) };
805 let Ok(path) = path.to_str() else {
806 return std::ptr::null_mut();
807 };
808 match Session::open_at(Path::new(path), target_sample) {
809 Some(session) => Box::into_raw(Box::new(session)) as *mut c_void,
810 None => std::ptr::null_mut(),
811 }
812 }))
813 .unwrap_or(std::ptr::null_mut())
814}
815
816/// Fills `out` with stream metadata. 0 on success, negative on failure.
817///
818/// # Safety
819/// `session` must come from [`vh_open_at`] and `out` must be writable.
820#[unsafe(no_mangle)]
821pub unsafe extern "C" fn vh_meta(session: *mut c_void, out: *mut VhMeta) -> i32 {
822 catch_unwind(AssertUnwindSafe(|| {
823 if session.is_null() || out.is_null() {
824 return -1;
825 }
826 // SAFETY: caller-guaranteed live session and writable destination.
827 unsafe {
828 let session = &*(session as *const Session);
829 (*out).width = session.meta.width;
830 (*out).height = session.meta.height;
831 (*out).frame_rate = session.meta.frame_rate;
832 (*out).frame_count = session.meta.frame_count;
833 }
834 0
835 }))
836 .unwrap_or(-1)
837}
838
839/// 1 when `out` holds the next picture in display order, 0 at clean end of
840/// stream, negative on error. Plane pointers stay valid until the next call.
841///
842/// # Safety
843/// `session` must come from [`vh_open_at`] and `out` must be writable.
844#[unsafe(no_mangle)]
845pub unsafe extern "C" fn vh_next_frame(session: *mut c_void, out: *mut VhFrame) -> i32 {
846 catch_unwind(AssertUnwindSafe(|| {
847 if session.is_null() || out.is_null() {
848 return -1;
849 }
850 // SAFETY: caller-guaranteed live session and writable destination.
851 let session = unsafe { &mut *(session as *mut Session) };
852 match session.pump() {
853 Ok(true) => {
854 // SAFETY: `out` is non-null and writable per the contract.
855 session.fill(unsafe { &mut *out });
856 1
857 }
858 Ok(false) => 0,
859 Err(e) => {
860 eprintln!("engine_hw: {e}");
861 -2
862 }
863 }
864 }))
865 .unwrap_or(-1)
866}
867
868/// Repositions an open session so the next [`vh_next_frame`] returns sample
869/// `target_sample` (1-based, as [`vh_open_at`]). 0 on success, negative on
870/// failure -- and a caller that gets one closes the session and opens another,
871/// which is what it did for every seek before this symbol existed.
872///
873/// # Safety
874/// `session` must come from [`vh_open_at`] and still be open.
875#[unsafe(no_mangle)]
876pub unsafe extern "C" fn vh_seek(session: *mut c_void, target_sample: u32) -> i32 {
877 catch_unwind(AssertUnwindSafe(|| {
878 if session.is_null() {
879 return -1;
880 }
881 // SAFETY: caller-guaranteed live session.
882 let session = unsafe { &mut *(session as *mut Session) };
883 match session.seek_to(target_sample) {
884 Ok(()) => 0,
885 Err(e) => {
886 eprintln!("engine_hw: seek failed: {e}");
887 -2
888 }
889 }
890 }))
891 .unwrap_or(-1)
892}
893
894/// As [`vh_next_frame`], but hands the picture over *on the GPU* where it can
895/// be: `dma` is filled and its `fd` belongs to the caller (who closes it) when
896/// the decoded surface is exactly what an encoder of `coded_width` x
897/// `coded_height` carrying a `width` x `height` picture reads, and `out` is
898/// filled with read-back I420 exactly as [`vh_next_frame`] fills it otherwise.
899/// `dma.fd` below zero is what says which happened.
900///
901/// The buffer stays out of the decoder's pool for [`DMA_HOLD`] further
902/// pictures and no longer: encode it before asking for that many more. Only a
903/// session that has never read a frame back may hand buffers over at all --
904/// those extra pool buffers are reserved at the first picture, and a decoder
905/// robbed of its own would stall.
906///
907/// # Safety
908/// `session` must come from [`vh_open_at`]; `out` and `dma` must be writable.
909#[unsafe(no_mangle)]
910pub unsafe extern "C" fn vh_next_frame_dma(
911 session: *mut c_void,
912 out: *mut VhFrame,
913 dma: *mut VhDma,
914 coded_width: u32,
915 coded_height: u32,
916 width: u32,
917 height: u32,
918) -> i32 {
919 catch_unwind(AssertUnwindSafe(|| {
920 if session.is_null() || out.is_null() || dma.is_null() {
921 return -1;
922 }
923 // SAFETY: caller-guaranteed live session and writable destinations.
924 let session = unsafe { &mut *(session as *mut Session) };
925 // SAFETY: as above.
926 unsafe { *dma = VhDma::default() };
927 // A pool sized without the reserve has nothing to lend: this session
928 // has been read back from, so it stays that way.
929 if !session.sized || session.hold > 0 {
930 session.hold = DMA_HOLD;
931 session.want = Some(VhDma {
932 fourcc: VA_FOURCC_NV12,
933 coded_width,
934 coded_height,
935 width,
936 height,
937 ..VhDma::default()
938 });
939 }
940 let pumped = session.pump();
941 session.want = None;
942 match pumped {
943 Ok(true) => {
944 match session.dma.take() {
945 // SAFETY: `dma` is non-null and writable per the contract.
946 Some(desc) => unsafe { *dma = desc },
947 // SAFETY: as above, for `out`.
948 None => session.fill(unsafe { &mut *out }),
949 }
950 1
951 }
952 Ok(false) => 0,
953 Err(e) => {
954 eprintln!("engine_hw: {e}");
955 -2
956 }
957 }
958 }))
959 .unwrap_or(-1)
960}
961
962/// Releases a session. Safe to call with null.
963///
964/// # Safety
965/// `session` must come from [`vh_open_at`] and must not be used afterwards.
966#[unsafe(no_mangle)]
967pub unsafe extern "C" fn vh_close(session: *mut c_void) {
968 let _ = catch_unwind(AssertUnwindSafe(|| {
969 if !session.is_null() {
970 // SAFETY: pointer came from `Box::into_raw` in `vh_open_at`.
971 drop(unsafe { Box::from_raw(session as *mut Session) });
972 }
973 }));
974}
975
976/// What each codec needs of the driver before this plugin can claim it: the
977/// 8-bit decode profiles, the 10-bit ones, and the profile the *encoder* here
978/// would open -- `None` for the one this plugin has no encoder for at all, so a
979/// GPU with a VP9 encode entrypoint is never reported as one edith can
980/// reach. The encode profiles are the very ones [`EncSession::open_codec`]
981/// asks for, which is what keeps this a description of the plugin rather than a
982/// second opinion about it.
983const CAP_TABLE: [(u32, &[VAProfile::Type], &[VAProfile::Type], Option<VAProfile::Type>); 4] = [
984 (
985 CAP_H264,
986 &[
987 VAProfile::VAProfileH264ConstrainedBaseline,
988 VAProfile::VAProfileH264Main,
989 VAProfile::VAProfileH264High,
990 ],
991 &[],
992 Some(VAProfile::VAProfileH264Main),
993 ),
994 (
995 CAP_HEVC,
996 &[VAProfile::VAProfileHEVCMain],
997 &[VAProfile::VAProfileHEVCMain10],
998 // 8-bit Main only: the encoder here opens Main whatever the source was,
999 // so a Main 10 entrypoint is a *decode* claim on this line and nothing
1000 // more. Main 10 encode would be a second profile here and a 10-bit input
1001 // buffer in `EncSession`, neither of which exists yet.
1002 Some(VAProfile::VAProfileHEVCMain),
1003 ),
1004 (
1005 CAP_VP9,
1006 &[VAProfile::VAProfileVP9Profile0],
1007 &[VAProfile::VAProfileVP9Profile2],
1008 None,
1009 ),
1010 (
1011 CAP_AV1,
1012 &[VAProfile::VAProfileAV1Profile0],
1013 // AV1 carries 8- and 10-bit in the same profile 0, so the profile bit
1014 // is the same one and the P010 read-back is what decides.
1015 &[VAProfile::VAProfileAV1Profile0],
1016 Some(VAProfile::VAProfileAV1Profile0),
1017 ),
1018];
1019
1020/// This machine's decode and encode seats, asked of the driver rather than
1021/// assumed: which profiles it has, which entrypoints each of those carries, and
1022/// whether a P010 image exists to read a 10-bit picture back through. Only
1023/// codecs this plugin actually implements can light up -- `CAP_TABLE` is that
1024/// half of the intersection.
1025///
1026/// `None` when there is no display to ask at all, which is the same "software
1027/// only" a missing plugin means.
1028fn query_caps() -> Option<VhCaps> {
1029 let (display, _gbm) = open_devices()?;
1030 let profiles = display.query_config_profiles().ok()?;
1031 let p010 = display
1032 .query_image_formats()
1033 .is_ok_and(|formats| formats.iter().any(|f| f.fourcc == VA_FOURCC_P010));
1034 let has = |profile: VAProfile::Type, entrypoint: VAEntrypoint::Type| {
1035 profiles.contains(&profile)
1036 && display
1037 .query_config_entrypoints(profile)
1038 .is_ok_and(|e| e.contains(&entrypoint))
1039 };
1040 let decodes = |list: &[VAProfile::Type]| {
1041 list.iter()
1042 .any(|&p| has(p, VAEntrypoint::VAEntrypointVLD))
1043 };
1044 let mut caps = VhCaps::default();
1045 for (bit, eight, ten, encode) in CAP_TABLE {
1046 if decodes(eight) {
1047 caps.decode |= bit;
1048 }
1049 if p010 && decodes(ten) {
1050 caps.decode_10bit |= bit;
1051 }
1052 // Both entrypoints, exactly as the encoder's own open takes either.
1053 if encode.is_some_and(|p| {
1054 has(p, VAEntrypoint::VAEntrypointEncSlice) || has(p, VAEntrypoint::VAEntrypointEncSliceLP)
1055 }) {
1056 caps.encode |= bit;
1057 }
1058 }
1059 Some(caps)
1060}
1061
1062/// Fills `out` with what this machine and this plugin can do together. 0 on
1063/// success, negative when there is nothing to report -- an *optional* symbol on
1064/// purpose, so the caller resolving it is free to be older or newer than this.
1065///
1066/// Costs one VA-API init; the caller caches the answer.
1067///
1068/// # Safety
1069/// `out` must be writable.
1070#[unsafe(no_mangle)]
1071pub unsafe extern "C" fn vh_caps(out: *mut VhCaps) -> i32 {
1072 catch_unwind(AssertUnwindSafe(|| {
1073 if out.is_null() {
1074 return -1;
1075 }
1076 let Some(caps) = query_caps() else {
1077 return -1;
1078 };
1079 // SAFETY: caller-guaranteed writable destination.
1080 unsafe { *out = caps };
1081 0
1082 }))
1083 .unwrap_or(-1)
1084}
1085
1086/// How many pictures a group of them holds -- the low-delay predictor's
1087/// `limit`, which is the *only* thing that decides whether a picture is an IDR.
1088///
1089/// One for an intra-only seat, and that is not a tuning: the predictor counts
1090/// `counter % limit`, so a limit of one pins the counter at zero, every picture
1091/// takes the keyframe branch with `idr` set, and every access unit carries a
1092/// fresh SPS and PPS
1093/// (`cros-codecs/encoder/stateless/predictor.rs:107`, `h264/predictor.rs:139`).
1094/// Two seconds otherwise, which is what a seek may land on in an ordinary file.
1095///
1096/// Forcing a key frame per picture is a different thing and does *not* make an
1097/// intra file: that path passes `idr = false`, writes no parameter sets, and
1098/// [`fix_slice_nal_headers`] then marks the slice non-IDR -- how a 60-picture
1099/// "all-intra" hardware proxy came out with one sync point in it.
1100fn gop_limit(framerate: u32, intra_only: bool) -> u16 {
1101 match intra_only {
1102 true => 1,
1103 // Saturating and clamped: the caller pins the rate to 1..240 before it
1104 // gets here, and a limit that wrapped to zero would divide by zero in
1105 // the predictor -- a guard costs nothing next to that.
1106 false => framerate.saturating_mul(2).clamp(1, u16::MAX as u32) as u16,
1107 }
1108}
1109
1110fn align16(v: u32) -> u32 {
1111 v.div_ceil(16) * 16
1112}
1113
1114fn align64(v: u32) -> u32 {
1115 v.div_ceil(64) * 64
1116}
1117
1118/// Fills in slice NAL header bytes the driver left at zero.
1119///
1120/// Mesa's radeonsi encoder writes `forbidden_zero_bit`, `nal_ref_idc` and
1121/// `nal_unit_type` from state it only ever populates out of a *packed* slice
1122/// header, and cros-codecs supplies none (`h264/vaapi.rs` says as much in its
1123/// "use packed headers" TODO). Every other bit of the slice is correct, so the
1124/// whole damage is one byte per slice: measured on radeonsi, patching it turns
1125/// a stream neither ffmpeg nor `rusty_h264` will touch into one both decode.
1126///
1127/// An all-zero byte after a start code is never valid H.264, so drivers that do
1128/// write the header (Intel's, which is what cros-codecs was built against) fall
1129/// straight through this.
1130///
1131/// corner-cut: the real fix is a `VAEncPackedHeaderH264_Slice` buffer in the
1132/// vendored cros-codecs backend, which means synthesizing the entire slice
1133/// header there rather than correcting two fields here.
1134fn fix_slice_nal_headers(au: &mut [u8]) {
1135 // cros-codecs prepends SPS+PPS to the access unit at every IDR and only
1136 // there, so an SPS seen earlier in this unit is what makes the slice one.
1137 let mut idr = false;
1138 let mut i = 0;
1139 while i + 3 < au.len() {
1140 if au[i..i + 3] != [0, 0, 1] {
1141 i += 1;
1142 continue;
1143 }
1144 let nal = &mut au[i + 3];
1145 if *nal == 0 {
1146 // nal_ref_idc 3 + IDR, or 2 + non-IDR: every picture this encoder
1147 // emits is a short-term reference (no B-frames, no disposables).
1148 *nal = if idr { 0x65 } else { 0x41 };
1149 } else if *nal & 0x1f == 7 {
1150 idr = true;
1151 }
1152 i += 3;
1153 }
1154}
1155
1156/// One hardware H.264 encode session.
1157///
1158/// Pictures the caller already has on the GPU go straight in
1159/// ([`EncSession::encode_dma`]) and touch none of what follows. The rest --
1160/// pixels in the caller's memory -- go through [`enc_depth`] reusable NV12
1161/// buffer objects: the caller's
1162/// I420 planes are interleaved into the next one and the encoder imports it as a
1163/// VA surface. Reuse is safe because a buffer is only written again once the
1164/// access unit coded *from* it has been polled back -- the encoder runs in
1165/// blocking mode and a coded unit in hand means the GPU has finished reading its
1166/// input -- and [`EncSession::encode`] holds exactly that many pictures in
1167/// flight, no more.
1168///
1169/// **Why more than one.** With a single buffer the picture had to be coded
1170/// before the next one could be written into it, so a frame cost the CPU's
1171/// interleave *plus* the GPU's encode end to end (6.7 ms + 2.5 ms at 1080p on
1172/// radeonsi, measured 2026-08-13). With two, the interleave of the next picture
1173/// runs while the GPU codes this one and the frame costs the longer of them.
1174struct EncSession {
1175 /// Boxed because the three codecs are three types and everything past
1176 /// `encode` is the same trait: one session type serves them all, which is
1177 /// what keeps the C ABI at one new symbol per codec (the open) instead of
1178 /// four.
1179 encoder: Box<dyn VideoEncoder<GenericDmaVideoFrame>>,
1180 /// Which codec the open picked, kept because one thing past it still
1181 /// differs: the H.264 driver leaves a *NAL* header byte at zero, and
1182 /// neither an HEVC access unit nor an AV1 temporal unit has that one.
1183 codec: EncCodec,
1184 /// Owns the DRM node the buffer objects below were allocated from.
1185 _gbm: gbm::Device<std::fs::File>,
1186 /// [`enc_depth`] input buffers, used round-robin.
1187 frames: Vec<GenericDmaVideoFrame>,
1188 /// How many of them there are, which is how many pictures may be in the
1189 /// encoder at once.
1190 depth: usize,
1191 /// Which of them the next picture is written into.
1192 slot: usize,
1193 /// Pictures submitted whose access unit has not been polled back yet, which
1194 /// is what says whether the buffer about to be written is free.
1195 in_flight: usize,
1196 layout: FrameLayout,
1197 /// Macroblock-aligned surface size; `width`/`height` are what is encoded.
1198 coded: Resolution,
1199 width: usize,
1200 height: usize,
1201 timestamp: u64,
1202 drained: bool,
1203 /// Coded access units the encoder has finished but the caller has not
1204 /// collected yet, in encode order (which is display order: no B-frames).
1205 ready: VecDeque<Vec<u8>>,
1206 /// The access unit currently handed out, kept alive until the next call.
1207 out: Vec<u8>,
1208 /// One padded output row, staged in ordinary memory and copied across whole
1209 /// -- [`EncSession::upload`] says why.
1210 row: Vec<u8>,
1211}
1212
1213/// How many pictures may be in the encoder at once. Two is what it takes to
1214/// overlap the CPU's interleave with the GPU's encode; more would buy nothing,
1215/// since the interleave is the longer of the two and a third buffer would only
1216/// hold a picture waiting for a lane that is never idle.
1217const ENC_DEPTH: usize = 2;
1218
1219/// How many pictures *this* seat may hold, which is [`ENC_DEPTH`] for H.264 and
1220/// one for the other two.
1221///
1222/// Depth 2 means a submitted picture must hand its access unit back on the next
1223/// poll, and [`EncSession::encode`] treats a seat that does not as an error --
1224/// it cannot write into a buffer the GPU may still be reading. That contract
1225/// was measured on the H.264 seat and only there. HEVC and AV1 on this plugin
1226/// are intra-only and go through the same driver, so they very probably behave
1227/// the same way; "very probably" is not what a hard error should rest on, and
1228/// the GPU has been unavailable since the measurement was possible. They keep
1229/// the old one-buffer behaviour -- the picture coded before the next is
1230/// written, exactly as every seat did before -- until someone measures them.
1231///
1232/// The intra-only seat ([`vh_enc_open_intra`]) is keyed by codec like any other
1233/// and therefore takes the two, which is the answer and not an oversight: it is
1234/// the same H.264 entrypoint with every inter dependency removed, so a picture
1235/// there is finished no later than one on the seat the two was measured on.
1236fn enc_depth(codec: EncCodec) -> usize {
1237 match codec {
1238 EncCodec::H264 => ENC_DEPTH,
1239 EncCodec::Hevc | EncCodec::Av1 => 1,
1240 }
1241}
1242
1243/// Which codec an [`EncSession`] was opened for. Decided once, at the open, the
1244/// way the H.264 seat's dimensions are -- everything after it is one trait.
1245#[derive(Clone, Copy, PartialEq, Eq)]
1246enum EncCodec {
1247 H264,
1248 Hevc,
1249 Av1,
1250}
1251
1252impl EncSession {
1253 fn open(width: u32, height: u32, fps_num: u32, fps_den: u32, bitrate: u64) -> Option<Self> {
1254 Self::open_codec(width, height, fps_num, fps_den, bitrate, EncCodec::H264)
1255 }
1256
1257 fn open_codec(
1258 width: u32,
1259 height: u32,
1260 fps_num: u32,
1261 fps_den: u32,
1262 bitrate: u64,
1263 codec: EncCodec,
1264 ) -> Option<Self> {
1265 Self::open_seat(width, height, fps_num, fps_den, bitrate, codec, false, None)
1266 }
1267
1268 #[allow(clippy::too_many_arguments)]
1269 fn open_seat(
1270 width: u32,
1271 height: u32,
1272 fps_num: u32,
1273 fps_den: u32,
1274 bitrate: u64,
1275 codec: EncCodec,
1276 intra_only: bool,
1277 colour: Option<H265Colour>,
1278 ) -> Option<Self> {
1279 // NV12 chroma is half resolution, so odd dimensions have no packing;
1280 // and radeonsi refuses encode contexts below 64x64 (measured).
1281 if width < 64 || height < 64 || width % 2 != 0 || height % 2 != 0 {
1282 return None;
1283 }
1284 // The HEVC entrypoint's own floor, which is a different number: the same
1285 // driver that takes a 128x128 H.264 context answers `VaError(19)` to an
1286 // HEVC one below 384x384 (measured 2026-08-13 on radeonsi). Said here so
1287 // a small export falls back to software at the open rather than through
1288 // a driver refusal, and so the C ABI never claims a seat it has not got.
1289 if codec == EncCodec::Hevc && (width < 384 || height < 384) {
1290 return None;
1291 }
1292 if fps_num == 0 || fps_den == 0 || bitrate == 0 {
1293 return None;
1294 }
1295 let (display, gbm) = open_devices()?;
1296 // A macroblock is 16 wide; an HEVC coding tree block is 64, and that
1297 // seat's parameter sets declare the picture at coding-tree size (see the
1298 // vendored `h265/predictor.rs`), so the surface has to carry every row
1299 // those sets promise.
1300 let align = match codec {
1301 EncCodec::Hevc => align64,
1302 _ => align16,
1303 };
1304 let coded = Resolution {
1305 width: align(width),
1306 height: align(height),
1307 };
1308 let framerate = ((fps_num as f64 / fps_den as f64).round() as i64).clamp(1, 240) as u32;
1309 let profile = match codec {
1310 EncCodec::Av1 => VAProfile::VAProfileAV1Profile0,
1311 EncCodec::Hevc => VAProfile::VAProfileHEVCMain,
1312 EncCodec::H264 => VAProfile::VAProfileH264Main,
1313 };
1314 // The driver's own answer to "can you encode this at all": a GPU with no
1315 // AV1 encode entrypoint is what makes the caller fall back to `rav1e`,
1316 // and asking here is what turns that into a null rather than a failed
1317 // encode session halfway through an export.
1318 let entrypoints = display.query_config_entrypoints(profile).ok()?;
1319 if !entrypoints.contains(&VAEntrypoint::VAEntrypointEncSlice)
1320 && !entrypoints.contains(&VAEntrypoint::VAEntrypointEncSliceLP)
1321 {
1322 return None;
1323 }
1324 let low_power = entrypoints.contains(&VAEntrypoint::VAEntrypointEncSliceLP);
1325 // No B-frames on either codec: coded order stays display order, which is
1326 // what both muxers' duration-only timing assumes.
1327 //
1328 // A limit of **1** is what makes a seat intra-only, and it is the whole
1329 // mechanism: the low-delay predictor counts `counter % limit`, so with a
1330 // limit of one that counter is always zero, every picture takes the
1331 // keyframe branch *with `idr` set*, and each access unit is therefore an
1332 // IDR carrying a fresh SPS and PPS
1333 // (`cros-codecs/encoder/stateless/predictor.rs:107` and
1334 // `h264/predictor.rs:139-163`). Forcing a key frame per picture is not
1335 // the same thing and does not do it: `force_keyframe` takes the same
1336 // branch with `idr` **false**, so no parameter sets are written, and a
1337 // driver that leaves the NAL header byte at zero then gets its slices
1338 // marked non-IDR by [`fix_slice_nal_headers`] -- which is exactly how a
1339 // 60-frame "all-intra" hardware proxy came out with one sync point in it.
1340 let pred_structure = PredictionStructure::LowDelay {
1341 limit: gop_limit(framerate, intra_only),
1342 };
1343 let encoder: Box<dyn VideoEncoder<GenericDmaVideoFrame>> = match codec {
1344 EncCodec::Av1 => {
1345 // Constant quality, because that is the only rate control the
1346 // vendored AV1 backend takes (`stateless/av1/vaapi.rs` refuses
1347 // anything else outright); 128 of 255 is its own reference
1348 // value. The caller's bitrate therefore does not reach this
1349 // seat -- it reaches `rav1e`, which is the other one.
1350 //
1351 // corner-cut: bitrate-driven AV1 on the GPU needs `VA_RC_CBR`
1352 // wired through that backend, which is a change in the vendored
1353 // crate rather than here.
1354 let config = Av1Config {
1355 profile: Av1Profile::Profile0,
1356 resolution: Resolution { width, height },
1357 pred_structure,
1358 initial_tunings: Tunings {
1359 rate_control: RateControl::ConstantQuality(128),
1360 framerate,
1361 ..Default::default()
1362 },
1363 ..Default::default()
1364 };
1365 Box::new(
1366 Av1Encoder::new_vaapi(
1367 display,
1368 config,
1369 Fourcc::from(b"NV12"),
1370 coded,
1371 low_power,
1372 BlockingMode::Blocking,
1373 )
1374 .ok()?,
1375 )
1376 }
1377 EncCodec::Hevc => {
1378 // **Every picture an IDR**, which is the one place this seat
1379 // does not mirror the H.264 one. A GOP's P slices come out of
1380 // this driver undecodable: the slice segment headers are the
1381 // *driver's* to write (as they are for H.264) and radeonsi
1382 // writes a constant picture order count into every one of them,
1383 // so a decoder sees frame after frame claiming to be the same
1384 // output picture. Measured 2026-08-13: with the default GOP,
1385 // only the leading IDR of each group decodes.
1386 //
1387 // So the hardware seat is intra-only exactly as the software one
1388 // is (`export::Enc::open_hevc`), and an HEVC export is an
1389 // intraframe master either way -- the same file, coded by the
1390 // GPU instead of by twelve cores.
1391 //
1392 // corner-cut: inter HEVC on this GPU needs the slice segment
1393 // header written here rather than by the driver
1394 // (`VAEncPackedHeaderSlice`), which is a change in the vendored
1395 // backend; upgrade path is that, or a driver that writes a
1396 // correct POC.
1397 let config = H265Config {
1398 resolution: Resolution { width, height },
1399 profile: H265Profile::Main,
1400 level: H265Level::L4,
1401 pred_structure: PredictionStructure::LowDelay { limit: 1 },
1402 initial_tunings: Tunings {
1403 rate_control: RateControl::ConstantBitrate(bitrate),
1404 framerate,
1405 ..Default::default()
1406 },
1407 // What the SPS tells a decoder the samples mean. Without it
1408 // libavcodec reads this stream's colour as "unspecified" and
1409 // renders it BT.601 whatever the container says -- the HEVC
1410 // decoder takes the bitstream's answer and overwrites the
1411 // container's with it, so an untagged 709 export is a
1412 // visible shift (`engine::export::video_signal_type` writes
1413 // the same three code points on the software seat).
1414 colour,
1415 };
1416 Box::new(
1417 HevcEncoder::new_vaapi(
1418 display,
1419 config,
1420 Fourcc::from(b"NV12"),
1421 coded,
1422 low_power,
1423 BlockingMode::Blocking,
1424 )
1425 .ok()?,
1426 )
1427 }
1428 EncCodec::H264 => {
1429 let config = H264Config {
1430 resolution: Resolution { width, height },
1431 profile: H264Profile::Main,
1432 level: Level::L4,
1433 pred_structure,
1434 initial_tunings: Tunings {
1435 rate_control: RateControl::ConstantBitrate(bitrate),
1436 framerate,
1437 ..Default::default()
1438 },
1439 };
1440 Box::new(
1441 Encoder::new_vaapi(
1442 display,
1443 config,
1444 Fourcc::from(b"NV12"),
1445 coded,
1446 low_power,
1447 BlockingMode::Blocking,
1448 )
1449 .ok()?,
1450 )
1451 }
1452 };
1453 // Allocated at the aligned size, so the buffer's pitch is never smaller
1454 // than a padded row.
1455 let depth = enc_depth(codec);
1456 let frames: Vec<_> = (0..depth)
1457 .map(|_| alloc_nv12(&gbm, coded, false))
1458 .collect::<Result<_, _>>()
1459 .ok()?;
1460 let layout = nv12_layout(coded, frames[0].get_plane_pitch()[0], false);
1461 Some(Self {
1462 encoder,
1463 codec,
1464 _gbm: gbm,
1465 frames,
1466 depth,
1467 slot: 0,
1468 in_flight: 0,
1469 layout,
1470 coded,
1471 width: width as usize,
1472 height: height as usize,
1473 timestamp: 0,
1474 drained: false,
1475 ready: VecDeque::new(),
1476 out: Vec::new(),
1477 row: Vec::new(),
1478 })
1479 }
1480
1481 /// Interleaves one packed I420 picture into the NV12 input buffer `slot`.
1482 ///
1483 /// **Row at a time, through ordinary memory.** The mapping below is the
1484 /// GPU's own buffer, which is write-combining: a store of a byte or two
1485 /// costs a partial-buffer flush, while one `memcpy` of a whole row costs a
1486 /// burst. Interleaving the chroma directly into it was 8.2 ms a picture at
1487 /// 1080p against 6.7 ms staged (measured 2026-08-13 on radeonsi, alternating
1488 /// the two paths frame by frame inside one export so the machine's load
1489 /// weighed on both), and the picture is four fifths of what a hardware
1490 /// export spends per frame. The padding is written the same way and for the
1491 /// same reason: it used to be a four-byte second store per row.
1492 ///
1493 /// # Safety
1494 /// `src`'s planes must cover `height` (resp. `height / 2`) rows of their
1495 /// declared stride.
1496 unsafe fn upload(&mut self, src: &VhFrame, slot: usize) -> Result<(), String> {
1497 let (w, h) = (self.width, self.height);
1498 let (cw, ch) = (w / 2, h / 2);
1499 let (aw, ah) = (self.coded.width as usize, self.coded.height as usize);
1500 // Two fields at once: the buffer is mapped for writing while the staging
1501 // row is written into, and they are not the same field.
1502 let Self { frames, row, .. } = self;
1503 let frame = &mut frames[slot];
1504 let pitch = frame.get_plane_pitch();
1505 let mapping = frame.map_mut()?;
1506 let planes = mapping.get();
1507 row.resize(aw, 0);
1508 let row_buf = &mut row[..];
1509 {
1510 let mut dst = planes[0].borrow_mut();
1511 for row in 0..ah {
1512 // SAFETY: caller contract; rows past the picture repeat the last.
1513 let s = unsafe {
1514 std::slice::from_raw_parts(src.y.add(row.min(h - 1) * src.y_stride), w)
1515 };
1516 row_buf[..w].copy_from_slice(s);
1517 // Macroblock padding: replicate the edge rather than leave the
1518 // buffer's garbage there, which would cost bitrate for nothing.
1519 row_buf[w..].fill(s[w - 1]);
1520 dst[row * pitch[0]..row * pitch[0] + aw].copy_from_slice(row_buf);
1521 }
1522 }
1523 let mut dst = planes[1].borrow_mut();
1524 for row in 0..ah / 2 {
1525 let src_row = row.min(ch - 1);
1526 // SAFETY: as above, for the two chroma planes.
1527 let (u, v) = unsafe {
1528 (
1529 std::slice::from_raw_parts(src.u.add(src_row * src.u_stride), cw),
1530 std::slice::from_raw_parts(src.v.add(src_row * src.v_stride), cw),
1531 )
1532 };
1533 for x in 0..cw {
1534 row_buf[2 * x] = u[x];
1535 row_buf[2 * x + 1] = v[x];
1536 }
1537 for x in w..aw {
1538 row_buf[x] = row_buf[x - 2];
1539 }
1540 dst[row * pitch[1]..row * pitch[1] + aw].copy_from_slice(row_buf);
1541 }
1542 Ok(())
1543 }
1544
1545 /// # Safety
1546 /// As [`EncSession::upload`].
1547 unsafe fn encode(&mut self, src: &VhFrame, force_keyframe: bool) -> Result<(), String> {
1548 // The buffer this picture is written into is the one whose own access
1549 // unit is already in hand -- `in_flight` is held below `depth` at the
1550 // end of every call, so the round-robin never catches the GPU up. At
1551 // depth 1 that is the picture just coded, which is the one-buffer
1552 // behaviour every seat had before ([`enc_depth`]).
1553 let slot = self.slot;
1554 // SAFETY: caller contract, forwarded.
1555 unsafe { self.upload(src, slot)? };
1556 self.slot = (self.slot + 1) % self.depth;
1557 let meta = FrameMetadata {
1558 timestamp: self.timestamp,
1559 layout: self.layout.clone(),
1560 force_keyframe,
1561 };
1562 self.timestamp += 1;
1563 self.encoder
1564 .encode(meta, self.frames[slot].clone())
1565 .map_err(|e| e.to_string())?;
1566 self.in_flight += 1;
1567 // ...and the picture before it is collected here rather than this one:
1568 // that is the whole overlap, the GPU coding what was just submitted
1569 // while the caller decodes and interleaves the next picture.
1570 while self.in_flight >= self.depth {
1571 if !self.pull()? {
1572 // Blocking mode: a picture accepted and no coded unit for the
1573 // one before it means the encoder is not answering, and the
1574 // next upload would overwrite a buffer the GPU still reads.
1575 return Err("the encoder took a picture and returned nothing coded".into());
1576 }
1577 }
1578 Ok(())
1579 }
1580
1581 /// Encodes a picture the decoder left on the GPU: the buffer is imported as
1582 /// a surface of this session's own shape and read there, so nothing of it
1583 /// ever passes through the CPU -- no `vaGetImage` on the way out of the
1584 /// decoder and no interleave on the way in here.
1585 ///
1586 /// The geometry is checked rather than trusted: a buffer of another shape
1587 /// would be coded as garbage, and the caller asked
1588 /// [`vh_enc_dma_geometry`] what this seat takes before the decoder ever
1589 /// handed one over.
1590 ///
1591 /// **No deferred poll here, unlike [`EncSession::encode`].** That one holds
1592 /// [`enc_depth`] pictures in flight to overlap the *next* picture's CPU
1593 /// interleave with this one's encode; a picture arriving on the GPU has no
1594 /// interleave to overlap, so there is nothing to defer for and the access
1595 /// units are collected as soon as they exist. What the depth still buys is
1596 /// the input buffer, and this path uses none of `frames`: the surface is the
1597 /// decoder's, held for us by its own [`DMA_HOLD`] contract, and draining
1598 /// every call is what keeps that hold short.
1599 ///
1600 /// It is counted in `in_flight` all the same, because one session takes both
1601 /// kinds -- an untouched clip hands buffers over while a graded one or a gap
1602 /// goes through the pixel path -- and a submission missing from the count is
1603 /// a `frames` slot the pixel path would believe free one picture too early.
1604 fn encode_dma(&mut self, dma: &VhDma, force_keyframe: bool) -> Result<(), String> {
1605 if dma.fd[0] < 0
1606 || dma.fourcc != VA_FOURCC_NV12
1607 || (dma.coded_width, dma.coded_height) != (self.coded.width, self.coded.height)
1608 || (dma.width as usize, dma.height as usize) != (self.width, self.height)
1609 {
1610 return Err(format!(
1611 "imported buffer is {}x{} in {} coded {}x{}, not {}x{} coded {}x{}",
1612 dma.width,
1613 dma.height,
1614 dma.fourcc,
1615 dma.coded_width,
1616 dma.coded_height,
1617 self.width,
1618 self.height,
1619 self.coded.width,
1620 self.coded.height
1621 ));
1622 }
1623 // One object or two, exactly as the decoder's driver described them:
1624 // the buffers stay the caller's, so each is dup'd for the frame below.
1625 let mut files = Vec::new();
1626 for fd in dma.fd.iter().copied().take_while(|fd| *fd >= 0) {
1627 // SAFETY: the descriptor's handles are the caller's, open for the
1628 // length of the call.
1629 let owned = unsafe { std::os::fd::BorrowedFd::borrow_raw(fd) }
1630 .try_clone_to_owned()
1631 .map_err(|e| format!("dup of the imported buffer failed: {e}"))?;
1632 files.push(std::fs::File::from(owned));
1633 }
1634 let objects = files.len();
1635 let layout = FrameLayout {
1636 format: (Fourcc::from(b"NV12"), dma.modifier),
1637 size: self.coded,
1638 planes: (0..2)
1639 .map(|plane| PlaneLayout {
1640 buffer_index: plane.min(objects - 1),
1641 offset: dma.offset[plane] as usize,
1642 stride: dma.stride[plane] as usize,
1643 })
1644 .collect(),
1645 };
1646 let frame = GenericDmaVideoFrame::new(files, layout.clone())?;
1647 let meta = FrameMetadata {
1648 timestamp: self.timestamp,
1649 layout,
1650 force_keyframe,
1651 };
1652 self.timestamp += 1;
1653 self.encoder
1654 .encode(meta, frame)
1655 .map_err(|e| e.to_string())?;
1656 self.in_flight += 1;
1657 self.collect()
1658 }
1659
1660 /// Moves every access unit the encoder has finished into `ready`.
1661 fn collect(&mut self) -> Result<(), String> {
1662 while self.pull()? {}
1663 Ok(())
1664 }
1665
1666 /// One finished access unit into `ready`; `false` where the encoder has
1667 /// none to give.
1668 fn pull(&mut self) -> Result<bool, String> {
1669 let Some(coded) = self.encoder.poll().map_err(|e| e.to_string())? else {
1670 return Ok(false);
1671 };
1672 let mut au = coded.bitstream;
1673 if self.codec == EncCodec::H264 {
1674 fix_slice_nal_headers(&mut au);
1675 }
1676 self.ready.push_back(au);
1677 self.in_flight = self.in_flight.saturating_sub(1);
1678 Ok(true)
1679 }
1680
1681 /// Hands the oldest finished access unit to the caller, or reports that
1682 /// there is none.
1683 fn take(&mut self, out: *mut *const u8, out_len: *mut usize) -> i32 {
1684 let Some(au) = self.ready.pop_front() else {
1685 return 0;
1686 };
1687 self.out = au;
1688 // SAFETY: caller-guaranteed writable destinations.
1689 unsafe {
1690 *out = self.out.as_ptr();
1691 *out_len = self.out.len();
1692 }
1693 1
1694 }
1695}
1696
1697/// Opens a hardware H.264 encoder for `width`x`height` at `fps_num / fps_den`,
1698/// constant bitrate `bitrate` bits per second. Returns null on any failure at
1699/// all -- no VA-API runtime, no render node, no encode entrypoint, dimensions
1700/// the driver will not take -- and the caller falls back to software.
1701#[unsafe(no_mangle)]
1702pub extern "C" fn vh_enc_open(
1703 width: u32,
1704 height: u32,
1705 fps_num: u32,
1706 fps_den: u32,
1707 bitrate: u64,
1708) -> *mut c_void {
1709 catch_unwind(AssertUnwindSafe(|| {
1710 match EncSession::open(width, height, fps_num, fps_den, bitrate) {
1711 Some(session) => Box::into_raw(Box::new(session)) as *mut c_void,
1712 None => std::ptr::null_mut(),
1713 }
1714 }))
1715 .unwrap_or(std::ptr::null_mut())
1716}
1717
1718/// The same H.264 seat, **intra-only**: every access unit it hands back is an
1719/// IDR carrying its own SPS and PPS, so every frame of the file is a frame a
1720/// decoder may be started from. What a proxy is coded with
1721/// (`engine::proxy`), and never a delivery -- the file is much bigger for it.
1722///
1723/// A symbol of its own rather than a flag on [`vh_enc_open`], so that a plugin
1724/// built before this existed simply has no intra seat and the caller falls back
1725/// to the software encoder (whose `gop_size = 1` says the same thing) instead of
1726/// being handed a long-GOP file that claims to be all-intra. The session it
1727/// returns is fed, drained and closed through the very same three entry points.
1728#[unsafe(no_mangle)]
1729pub extern "C" fn vh_enc_open_intra(
1730 width: u32,
1731 height: u32,
1732 fps_num: u32,
1733 fps_den: u32,
1734 bitrate: u64,
1735) -> *mut c_void {
1736 catch_unwind(AssertUnwindSafe(|| {
1737 match EncSession::open_seat(
1738 width,
1739 height,
1740 fps_num,
1741 fps_den,
1742 bitrate,
1743 EncCodec::H264,
1744 true,
1745 None,
1746 ) {
1747 Some(session) => Box::into_raw(Box::new(session)) as *mut c_void,
1748 None => std::ptr::null_mut(),
1749 }
1750 }))
1751 .unwrap_or(std::ptr::null_mut())
1752}
1753
1754/// The same, coding AV1 instead of H.264: null unless this GPU has an AV1
1755/// encode entrypoint, which is recent hardware -- the caller then encodes AV1 in
1756/// software instead. `bitrate` is not used by this codec (see `EncSession::open`:
1757/// the vendored backend is constant-quality only) and is taken all the same, so
1758/// the two opens stay one signature.
1759///
1760/// The session it returns is fed, drained and closed through `vh_enc_frame`,
1761/// `vh_enc_drain` and `vh_enc_close` exactly as an H.264 one is; what comes back
1762/// out of them is AV1 temporal units rather than Annex-B access units.
1763#[unsafe(no_mangle)]
1764pub extern "C" fn vh_enc_av1_open(
1765 width: u32,
1766 height: u32,
1767 fps_num: u32,
1768 fps_den: u32,
1769 bitrate: u64,
1770) -> *mut c_void {
1771 catch_unwind(AssertUnwindSafe(|| {
1772 match EncSession::open_codec(width, height, fps_num, fps_den, bitrate, EncCodec::Av1) {
1773 Some(session) => Box::into_raw(Box::new(session)) as *mut c_void,
1774 None => std::ptr::null_mut(),
1775 }
1776 }))
1777 .unwrap_or(std::ptr::null_mut())
1778}
1779
1780/// The same, coding HEVC: null unless this GPU has an HEVC encode entrypoint and
1781/// the picture is at least 384x384 ([`EncSession::open_codec`] states that floor
1782/// and where it was measured), and the caller then encodes HEVC in software
1783/// instead.
1784///
1785/// **Intra-only**: every picture it hands back is an IDR carrying its own VPS,
1786/// SPS and PPS, which is what makes the file decodable at all on this driver --
1787/// see the `EncCodec::Hevc` arm of [`EncSession::open_codec`]. `bitrate` is the
1788/// constant bitrate the GPU codes at, as the H.264 seat's is.
1789///
1790/// The session it returns is fed, drained and closed through `vh_enc_frame`,
1791/// `vh_enc_drain` and `vh_enc_close` exactly as an H.264 one is; what comes back
1792/// out of them is Annex-B HEVC access units.
1793///
1794/// The last four arguments are what the SPS says the samples mean -- the three
1795/// H.273 code points and the range flag -- and they are part of the *symbol*
1796/// rather than a later setter because the parameter sets are built when the
1797/// sequence starts. A seat that signalled nothing is read back as "unspecified"
1798/// and rendered BT.601, the container's own tag notwithstanding, which is why
1799/// this replaced the colourless `vh_enc_hevc_open`: an engine older than this
1800/// symbol finds none and takes the software intra seat, which has always
1801/// written the VUI.
1802#[unsafe(no_mangle)]
1803pub extern "C" fn vh_enc_hevc_open_colour(
1804 width: u32,
1805 height: u32,
1806 fps_num: u32,
1807 fps_den: u32,
1808 bitrate: u64,
1809 colour_primaries: u32,
1810 transfer_characteristics: u32,
1811 matrix_coeffs: u32,
1812 full_range: i32,
1813) -> *mut c_void {
1814 catch_unwind(AssertUnwindSafe(|| {
1815 match EncSession::open_seat(
1816 width,
1817 height,
1818 fps_num,
1819 fps_den,
1820 bitrate,
1821 EncCodec::Hevc,
1822 false,
1823 Some(H265Colour {
1824 colour_primaries,
1825 transfer_characteristics,
1826 matrix_coeffs,
1827 full_range: full_range != 0,
1828 }),
1829 ) {
1830 Some(session) => Box::into_raw(Box::new(session)) as *mut c_void,
1831 None => std::ptr::null_mut(),
1832 }
1833 }))
1834 .unwrap_or(std::ptr::null_mut())
1835}
1836
1837/// Encodes one tightly-strided I420 picture. 1 when `out`/`out_len` describe one
1838/// Annex-B access unit, 0 when the encoder has nothing coded yet, negative on
1839/// error. The bytes stay valid until the next call on this session.
1840///
1841/// # Safety
1842/// `session` must come from [`vh_enc_open`], `frame`'s planes must cover the
1843/// picture at their declared strides, and `out`/`out_len` must be writable.
1844#[unsafe(no_mangle)]
1845pub unsafe extern "C" fn vh_enc_frame(
1846 session: *mut c_void,
1847 frame: *const VhFrame,
1848 force_key: i32,
1849 out: *mut *const u8,
1850 out_len: *mut usize,
1851) -> i32 {
1852 catch_unwind(AssertUnwindSafe(|| {
1853 if session.is_null() || frame.is_null() || out.is_null() || out_len.is_null() {
1854 return -1;
1855 }
1856 // SAFETY: caller-guaranteed live session and readable frame.
1857 let (session, frame) = unsafe { (&mut *(session as *mut EncSession), &*frame) };
1858 if frame.y.is_null() || frame.u.is_null() || frame.v.is_null() {
1859 return -1;
1860 }
1861 if frame.width as usize != session.width
1862 || frame.height as usize != session.height
1863 || frame.y_stride < session.width
1864 || frame.u_stride < session.width / 2
1865 || frame.v_stride < session.width / 2
1866 {
1867 return -1;
1868 }
1869 // SAFETY: caller contract on the plane pointers, sizes checked above.
1870 match unsafe { session.encode(frame, force_key != 0) } {
1871 Ok(()) => session.take(out, out_len),
1872 Err(e) => {
1873 eprintln!("engine_hw: {e}");
1874 -2
1875 }
1876 }
1877 }))
1878 .unwrap_or(-1)
1879}
1880
1881/// What a decoded buffer must look like to reach this encoder without a copy:
1882/// the surface size it codes in, written to `coded_width`/`coded_height`. 1 on
1883/// an answer, negative on none. NV12 and the size this session was opened for
1884/// are the rest of the shape, and the caller already knows both.
1885///
1886/// # Safety
1887/// `session` must come from [`vh_enc_open`]; both outputs must be writable.
1888#[unsafe(no_mangle)]
1889pub unsafe extern "C" fn vh_enc_dma_geometry(
1890 session: *mut c_void,
1891 coded_width: *mut u32,
1892 coded_height: *mut u32,
1893) -> i32 {
1894 catch_unwind(AssertUnwindSafe(|| {
1895 if session.is_null() || coded_width.is_null() || coded_height.is_null() {
1896 return -1;
1897 }
1898 // SAFETY: caller-guaranteed live session and writable destinations.
1899 unsafe {
1900 let session = &*(session as *const EncSession);
1901 *coded_width = session.coded.width;
1902 *coded_height = session.coded.height;
1903 }
1904 1
1905 }))
1906 .unwrap_or(-1)
1907}
1908
1909/// Encodes one picture the decoder left on the GPU, described by `dma` -- whose
1910/// file descriptor stays the *caller's*, borrowed for the length of the call.
1911/// Same answer and same lifetime rule as [`vh_enc_frame`]; a buffer of a shape
1912/// this session cannot read is an error and not a silent re-shape.
1913///
1914/// # Safety
1915/// `session` must come from [`vh_enc_open`], `dma` must be readable and its
1916/// descriptor open, and `out`/`out_len` must be writable.
1917#[unsafe(no_mangle)]
1918pub unsafe extern "C" fn vh_enc_frame_dma(
1919 session: *mut c_void,
1920 dma: *const VhDma,
1921 force_key: i32,
1922 out: *mut *const u8,
1923 out_len: *mut usize,
1924) -> i32 {
1925 catch_unwind(AssertUnwindSafe(|| {
1926 if session.is_null() || dma.is_null() || out.is_null() || out_len.is_null() {
1927 return -1;
1928 }
1929 // SAFETY: caller-guaranteed live session and readable descriptor.
1930 let (session, dma) = unsafe { (&mut *(session as *mut EncSession), &*dma) };
1931 match session.encode_dma(dma, force_key != 0) {
1932 Ok(()) => session.take(out, out_len),
1933 Err(e) => {
1934 eprintln!("engine_hw: {e}");
1935 -2
1936 }
1937 }
1938 }))
1939 .unwrap_or(-1)
1940}
1941
1942/// Flushes the encoder: 1 while `out`/`out_len` describe another access unit,
1943/// 0 once every picture fed has been handed back, negative on error. Same
1944/// lifetime rule as [`vh_enc_frame`].
1945///
1946/// # Safety
1947/// `session` must come from [`vh_enc_open`]; `out`/`out_len` must be writable.
1948#[unsafe(no_mangle)]
1949pub unsafe extern "C" fn vh_enc_drain(
1950 session: *mut c_void,
1951 out: *mut *const u8,
1952 out_len: *mut usize,
1953) -> i32 {
1954 catch_unwind(AssertUnwindSafe(|| {
1955 if session.is_null() || out.is_null() || out_len.is_null() {
1956 return -1;
1957 }
1958 // SAFETY: caller-guaranteed live session.
1959 let session = unsafe { &mut *(session as *mut EncSession) };
1960 if !session.drained {
1961 if let Err(e) = session.encoder.drain().map_err(|e| e.to_string()) {
1962 eprintln!("engine_hw: {e}");
1963 return -2;
1964 }
1965 session.drained = true;
1966 }
1967 match session.collect() {
1968 Ok(()) => session.take(out, out_len),
1969 Err(e) => {
1970 eprintln!("engine_hw: {e}");
1971 -2
1972 }
1973 }
1974 }))
1975 .unwrap_or(-1)
1976}
1977
1978/// Releases an encode session. Safe to call with null.
1979///
1980/// # Safety
1981/// `session` must come from [`vh_enc_open`] and must not be used afterwards.
1982#[unsafe(no_mangle)]
1983pub unsafe extern "C" fn vh_enc_close(session: *mut c_void) {
1984 let _ = catch_unwind(AssertUnwindSafe(|| {
1985 if !session.is_null() {
1986 // SAFETY: pointer came from `Box::into_raw` in `vh_enc_open`.
1987 drop(unsafe { Box::from_raw(session as *mut EncSession) });
1988 }
1989 }));
1990}
1991
1992#[cfg(test)]
1993mod tests {
1994 use super::*;
1995
1996 /// The one number that decides whether a hardware file is intra-only, and
1997 /// the one this seat got wrong: a proxy asks for a group of one picture, so
1998 /// every picture is an IDR with its own parameter sets. Needs no GPU --
1999 /// which is the point, since the seat itself cannot be opened without one.
2000 #[test]
2001 fn an_intra_seat_asks_for_a_group_of_one_picture() {
2002 assert_eq!(gop_limit(30, true), 1, "a proxy is every frame a start");
2003 assert_eq!(gop_limit(24, true), 1);
2004 // ...and an ordinary export keeps its two seconds between them.
2005 assert_eq!(gop_limit(30, false), 60);
2006 assert_eq!(gop_limit(24, false), 48);
2007 // A rate no file has, and the clamp that keeps the limit a `u16`
2008 // rather than a wrapped one: `0` would divide by zero in the predictor.
2009 assert_eq!(gop_limit(0, false), 1);
2010 assert_eq!(gop_limit(u32::MAX, false), u16::MAX);
2011 }
2012
2013 /// What that group of one writes into the sequence header, which is the
2014 /// half that shipped broken: the predictor hands the limit straight to
2015 /// `SpsBuilder::max_frame_num` (`h264/predictor.rs:89`), and `1.ilog2()`
2016 /// is 0, so the old `0u8 - 4u8` wrapped to 252 in release. Every intra-only
2017 /// hardware file then carried `log2_max_frame_num_minus4 = 252` -- outside
2018 /// the spec's 0..=12 -- and no decoder would parse it. Zero is the right
2019 /// answer, not merely a legal one: `frame_num` never leaves 0 when every
2020 /// picture is an IDR. No GPU: this is the bitstream side of the seat.
2021 #[test]
2022 fn an_intra_seat_writes_a_sequence_header_a_decoder_can_read() {
2023 use cros_codecs::codec::h264::parser::SpsBuilder;
2024
2025 let limit = u32::from(gop_limit(30, true));
2026 let sps = SpsBuilder::new().max_frame_num(limit).max_pic_order_cnt_lsb(limit * 2).build();
2027 assert_eq!(sps.log2_max_frame_num_minus4, 0, "252 is what a wrap looks like");
2028 assert_eq!(sps.log2_max_pic_order_cnt_lsb_minus4, 0);
2029 // The ordinary export's limit is untouched by the saturation, and a
2030 // limit at the top of the `u16` stays inside the spec's 0..=12.
2031 let long = u32::from(gop_limit(30, false));
2032 assert_eq!(SpsBuilder::new().max_frame_num(long).build().log2_max_frame_num_minus4, 1);
2033 assert!(
2034 SpsBuilder::new().max_frame_num(u32::MAX).build().log2_max_frame_num_minus4 <= 12
2035 );
2036 }
2037
2038 /// The other half of the same fault: a slice is marked IDR only where the
2039 /// access unit carries an SPS, so a "forced key frame" that writes no
2040 /// parameter sets reads back as an ordinary I picture -- no decoder starts
2041 /// there, and `sync_points` does not count it.
2042 #[test]
2043 fn only_a_unit_carrying_parameter_sets_is_marked_idr() {
2044 // SPS (0x67) + PPS (0x68) + a slice the driver left at zero.
2045 let mut with_sets = vec![0, 0, 1, 0x67, 9, 0, 0, 1, 0x68, 9, 0, 0, 1, 0x00, 9];
2046 fix_slice_nal_headers(&mut with_sets);
2047 assert_eq!(with_sets[13], 0x65, "IDR slice after an SPS");
2048 // The same unit without them: a key frame the encoder was merely asked
2049 // for, which is what the hardware proxy used to be full of.
2050 let mut bare = vec![0, 0, 1, 0x00, 9];
2051 fix_slice_nal_headers(&mut bare);
2052 assert_eq!(bare[3], 0x41, "no parameter sets, no IDR");
2053 }
2054
2055 /// Runs against whatever GPU this machine has -- and passes on one with no
2056 /// VA-API at all, which is exactly what `None` means here. What it pins is
2057 /// the *shape* of the answer, the contents being the driver's: nothing may
2058 /// be claimed that this plugin cannot actually reach.
2059 #[test]
2060 fn the_caps_query_never_claims_more_than_this_plugin_implements() {
2061 let Some(caps) = query_caps() else {
2062 return;
2063 };
2064 eprintln!("{caps:?}");
2065 // Encode is this plugin's three seats and no others, whatever
2066 // entrypoints the driver has: a VP9 EncSlice is not an encoder here.
2067 assert_eq!(
2068 caps.encode & !(CAP_H264 | CAP_HEVC | CAP_AV1),
2069 0,
2070 "{caps:?}"
2071 );
2072 // A 10-bit claim is a decode claim -- same profile family, read back
2073 // through P010 -- and there is no 10-bit encode path at all.
2074 assert_eq!(caps.decode_10bit & !caps.decode, 0, "{caps:?}");
2075 // H.264 here is 8-bit 4:2:0; the table has no 10-bit profile for it.
2076 assert_eq!(caps.decode_10bit & CAP_H264, 0, "{caps:?}");
2077 }
2078
2079 /// Every shape of the forward-or-flush decision a reposition makes, with
2080 /// no GPU in sight: the boundary a silence cut leaves is a target a few
2081 /// frames *ahead* of the decoder and that is the walk; behind it, past the
2082 /// reach, and past the end of the stream are the flush.
2083 #[test]
2084 fn a_target_ahead_within_the_reach_walks_forward() {
2085 use Reposition::{Flush, Forward};
2086 // A 30 fps stream, so the reach is [`FORWARD_SECS`] of it.
2087 let (count, limit) = (10_000u32, forward_limit(30.0));
2088 assert_eq!(forward_limit(30.0), 15);
2089 // The boundary a 0.3 s silence cut leaves: 9 frames ahead, dropped
2090 // unread on the way to exactly the target.
2091 assert_eq!(reposition(120, 129, count, limit), Forward(9));
2092 // Exactly at the reach, and a reseek to exactly where the decoder
2093 // stands (a superseded span's landing): nothing to do but not flush.
2094 assert_eq!(reposition(120, 135, count, limit), Forward(15));
2095 assert_eq!(reposition(120, 120, count, limit), Forward(0));
2096 // One frame past either end of the walk is the flush's.
2097 assert_eq!(reposition(120, 136, count, limit), Flush);
2098 assert_eq!(reposition(120, 119, count, limit), Flush);
2099 assert_eq!(reposition(120, 0, count, limit), Flush);
2100 // The last frame of the stream is a frame like any other...
2101 assert_eq!(reposition(9_995, 9_999, count, limit), Forward(4));
2102 // ...while a target at or past the end is not one decoding forward
2103 // can hand out: EOF falls back to the seek that always handled it.
2104 assert_eq!(reposition(9_995, 10_000, count, limit), Flush);
2105 assert_eq!(reposition(9_995, 60_000, count, limit), Flush);
2106 // From the end itself -- everything delivered, `pump` at clean EOF --
2107 // even a target inside the stream is behind.
2108 assert_eq!(reposition(10_000, 9_999, count, limit), Flush);
2109 }
2110
2111 /// The reach is time, carried at the stream's own rate, and a stream that
2112 /// states no rate gets none of it: such a session keeps the behaviour
2113 /// every reposition had, rather than a skip of nonsense frames.
2114 #[test]
2115 fn the_reach_is_half_a_second_at_the_streams_own_rate() {
2116 assert_eq!(forward_limit(23.976), 12);
2117 assert_eq!(forward_limit(24.0), 12);
2118 assert_eq!(forward_limit(60.0), 30);
2119 assert_eq!(forward_limit(0.0), 0);
2120 assert_eq!(forward_limit(f64::NAN), 0);
2121 assert_eq!(forward_limit(-30.0), 0);
2122 }
2123
2124 /// The drain machine's one law, held across *stacked* repositions: the
2125 /// picture delivered is `position + skip`, `position` advancing one per
2126 /// handle popped ([`Session::pump`]). A second forward reseek before the
2127 /// first's skip has drained must land on its own target -- the skip is
2128 /// replaced ([`forward_skip`]), never added to, or every reseek inside
2129 /// another's window walks its predecessor's frames past the target and
2130 /// the pictures keep arriving, only wrong.
2131 #[test]
2132 fn stacked_forward_reseeks_land_exactly_on_their_target() {
2133 use Reposition::Forward;
2134 let (count, limit) = (10_000u32, forward_limit(30.0));
2135 let land = |position: i64, skip: u32| position + i64::from(skip);
2136 let (mut position, mut skip) = (100i64, 0u32);
2137 let Forward(ahead) = reposition(position, 110, count, limit) else {
2138 panic!("110 is within the reach of 100")
2139 };
2140 skip = forward_skip(skip, ahead);
2141 let Forward(ahead) = reposition(position, 114, count, limit) else {
2142 panic!("114 is within the reach of 100")
2143 };
2144 skip = forward_skip(skip, ahead);
2145 assert_eq!(land(position, skip), 114, "the second target, exactly");
2146
2147 // A flush whose RAP skip is still undrained when a forward span is
2148 // asked: the flush stood at its RAP with `skip` toward its own
2149 // target, and the forward reseek through that window replaces it.
2150 position = 200;
2151 skip = 12;
2152 let Forward(ahead) = reposition(position, 208, count, limit) else {
2153 panic!("208 is within the reach of 200")
2154 };
2155 skip = forward_skip(skip, ahead);
2156 assert_eq!(land(position, skip), 208, "a flush's undrained skip does not compound");
2157
2158 // ...and a reseek to exactly where the decoder stands cancels
2159 // whatever was standing: the next handle is shown, not skipped past.
2160 let Forward(ahead) = reposition(position, position, count, limit) else {
2161 panic!("a session's own position is within its reach")
2162 };
2163 skip = forward_skip(skip, ahead);
2164 assert_eq!((ahead, land(position, skip)), (0, position));
2165 }
2166}