forge
Explore
Log in

Don't you dare go Hollow

edith

Clone
★ 0

0 watching0 forksRust18.3 MiB8c7bf80Tahinli3 months ago114 commits

lib.rs805 lines, 29.9 KiBHistoryRawDownload
1//! VA-API decode (H.264, HEVC, VP9 and AV1) and H.264 encode, shipped as a
2//! `dlopen`-able plugin so the main binary never gets a DT_NEEDED on
3//! libva/gbm/drm. Every entry point is
4//! `extern "C"`, catches unwinds and reports failure as a null pointer or a
5//! negative code: the caller's contract is "any failure means use the software
6//! codec".
7//!
8//! ponytail: that guarantee rests on `panic = "unwind"`. Building this crate with
9//! `panic = "abort"` would turn a driver bug into a killed app; the upgrade path
10//! is running the decoder in a child process instead of in-process.
11
12use std::collections::VecDeque;
13use std::ffi::{CStr, c_char, c_void};
14use std::panic::{AssertUnwindSafe, catch_unwind};
15use std::path::{Path, PathBuf};
16use std::rc::Rc;
17
18use cros_codecs::backend::vaapi::decoder::VaapiBackend;
19use cros_codecs::backend::vaapi::encoder::VaapiBackend as VaapiEncBackend;
20use cros_codecs::codec::h264::parser::{Level, Profile as H264Profile};
21use cros_codecs::decoder::stateless::av1::Av1;
22use cros_codecs::decoder::stateless::h264::H264;
23use cros_codecs::decoder::stateless::h265::H265;
24use cros_codecs::decoder::stateless::vp9::Vp9;
25use cros_codecs::decoder::stateless::{DecodeError, StatelessDecoder, StatelessVideoDecoder};
26use cros_codecs::decoder::{BlockingMode, DecodedHandle, DecoderEvent, StreamInfo};
27use cros_codecs::encoder::h264::EncoderConfig as H264Config;
28use cros_codecs::encoder::stateless::h264::StatelessEncoder;
29use cros_codecs::encoder::{
30 FrameMetadata, PredictionStructure, RateControl, Tunings, VideoEncoder,
31};
32use cros_codecs::image_processing::nv12_to_i420;
33use cros_codecs::libva::{
34 Display, Image, Surface, VA_FOURCC_NV12, VAEntrypoint, VAImageFormat, VAProfile,
35};
36use cros_codecs::video_frame::VideoFrame;
37use cros_codecs::video_frame::frame_pool::{FramePool, PooledVideoFrame};
38use cros_codecs::video_frame::generic_dma_video_frame::GenericDmaVideoFrame;
39use cros_codecs::video_frame::{UV_PLANE, Y_PLANE};
40use cros_codecs::{Fourcc, FrameLayout, PlaneLayout, Resolution};
41use gbm::{BufferObjectFlags, Format as GbmFormat};
42
43use engine::demux::{Codec, Demuxer};
44use engine::hw::{VhFrame, VhMeta};
45
46type PooledFrame = PooledVideoFrame<GenericDmaVideoFrame>;
47type Dec<C> = StatelessDecoder<C, VaapiBackend<PooledFrame>>;
48type Handle = <Dec<H264> as StatelessVideoDecoder>::Handle;
49
50/// One decoder per codec the demuxer can hand us. They all share the VA-API
51/// backend and therefore the same [`Handle`], so everything past `decode` is
52/// common; which one exists is decided by the container, never by the caller --
53/// which is why the plugin's C ABI is unchanged and an older `libengine_hw.so`
54/// still loads and still decodes H.264 (it simply refuses the newer codecs'
55/// files at `Demuxer`).
56///
57/// ponytail: 8-bit 4:2:0 only -- VP9 profile 0, HEVC Main, AV1 Main. VP9
58/// profile 2, HEVC Main 10 and AV1 Professional decode 10-bit, which the NV12
59/// pool and the `vaGetImage` read-back here cannot carry (`Demuxer` refuses
60/// both HEVC Main 10 and 10-bit AV1 by name); the upgrade path is a P010 pool
61/// selected from the stream info.
62enum Decoder {
63 H264(Dec<H264>),
64 Hevc(Dec<H265>),
65 Vp9(Dec<Vp9>),
66 Av1(Dec<Av1>),
67}
68
69impl Decoder {
70 fn get(&mut self) -> &mut dyn StatelessVideoDecoder<Handle = Handle> {
71 match self {
72 Self::H264(d) => d,
73 Self::Hevc(d) => d,
74 Self::Vp9(d) => d,
75 Self::Av1(d) => d,
76 }
77 }
78}
79
80type Encoder = StatelessEncoder<
81 GenericDmaVideoFrame,
82 VaapiEncBackend<GenericDmaVideoFrame, Surface<GenericDmaVideoFrame>>,
83>;
84
85/// Ceiling on decode/drain iterations that make no progress. VA-API in blocking
86/// mode should always either hand back an event or accept input; this only
87/// exists so a misbehaving driver returns an error instead of hanging the app.
88const STALL_LIMIT: u32 = 10_000;
89
90struct Session {
91 decoder: Decoder,
92 /// NV12 descriptor for `vaGetImage`, queried once at open.
93 nv12_format: VAImageFormat,
94 pool: FramePool<GenericDmaVideoFrame>,
95 demuxer: Demuxer,
96 meta: VhMeta,
97 ready: VecDeque<Handle>,
98 /// Remaining bytes of the access unit currently being fed, if any.
99 pending: Vec<u8>,
100 timestamp: u64,
101 flushed: bool,
102 /// Pictures still to be decoded and thrown away to land on a seek target.
103 skip: u32,
104 /// Tightly packed I420 handed out through [`VhFrame`]; reused every frame,
105 /// which is exactly why the pointers are only valid until the next call.
106 out: Vec<u8>,
107 luma: usize,
108 chroma: usize,
109}
110
111/// Mesa's GBM cannot allocate an NV12 buffer object at all (measured on
112/// radeonsi: every flag/modifier combination returns NULL), so we allocate one
113/// linear single-plane R8 buffer big enough for luma + chroma and describe the
114/// NV12 layout inside it ourselves. VA-API imports it as one DRM-PRIME object
115/// with two planes at known offsets, which is exactly what the descriptor in
116/// `GenericDmaVideoFrame` emits.
117fn alloc_nv12(
118 gbm: &gbm::Device<std::fs::File>,
119 coded: Resolution,
120) -> Result<GenericDmaVideoFrame, String> {
121 let rows = coded.height + coded.height.div_ceil(2);
122 let bo = gbm
123 .create_buffer_object::<()>(coded.width, rows, GbmFormat::R8, BufferObjectFlags::LINEAR)
124 .map_err(|e| format!("gbm R8 {}x{rows} allocation failed: {e}", coded.width))?;
125 let pitch = bo.stride().map_err(|e| e.to_string())? as usize;
126 let fd = bo.fd().map_err(|e| e.to_string())?;
127 GenericDmaVideoFrame::new(vec![std::fs::File::from(fd)], nv12_layout(coded, pitch))
128}
129
130/// Two NV12 planes packed one after the other in a single buffer object.
131fn nv12_layout(coded: Resolution, pitch: usize) -> FrameLayout {
132 FrameLayout {
133 format: (Fourcc::from(b"NV12"), 0 /* DRM_FORMAT_MOD_LINEAR */),
134 size: coded,
135 planes: vec![
136 PlaneLayout {
137 buffer_index: 0,
138 offset: 0,
139 stride: pitch,
140 },
141 PlaneLayout {
142 buffer_index: 0,
143 offset: pitch * coded.height as usize,
144 stride: pitch,
145 },
146 ],
147 }
148}
149
150/// First render node that gives us both a VA display and a GBM device. Which
151/// node is the right one is a per-machine question, so we probe rather than
152/// hardcode renderD128.
153fn open_devices() -> Option<(Rc<Display>, gbm::Device<std::fs::File>)> {
154 let mut nodes: Vec<PathBuf> = std::fs::read_dir("/dev/dri")
155 .ok()?
156 .flatten()
157 .map(|e| e.path())
158 .filter(|p| {
159 p.file_name()
160 .and_then(|n| n.to_str())
161 .is_some_and(|n| n.starts_with("renderD"))
162 })
163 .collect();
164 nodes.sort();
165 nodes.into_iter().find_map(|node| {
166 let display = Display::open_drm_display(&node).ok()?;
167 let file = std::fs::OpenOptions::new()
168 .read(true)
169 .write(true)
170 .open(&node)
171 .ok()?;
172 let gbm = gbm::Device::new(file).ok()?;
173 Some((display, gbm))
174 })
175}
176
177impl Session {
178 fn open(path: &Path) -> Option<Self> {
179 let (meta, demuxer) = Demuxer::open(path).ok()?;
180 let (display, gbm) = open_devices()?;
181 let nv12_format = display
182 .query_image_formats()
183 .ok()?
184 .into_iter()
185 .find(|f| f.fourcc == VA_FOURCC_NV12)?;
186 let decoder = match meta.codec {
187 Codec::H264 => {
188 Decoder::H264(Dec::<H264>::new_vaapi(display, BlockingMode::Blocking).ok()?)
189 }
190 Codec::Hevc => {
191 Decoder::Hevc(Dec::<H265>::new_vaapi(display, BlockingMode::Blocking).ok()?)
192 }
193 Codec::Vp9 => {
194 Decoder::Vp9(Dec::<Vp9>::new_vaapi(display, BlockingMode::Blocking).ok()?)
195 }
196 Codec::Av1 => {
197 Decoder::Av1(Dec::<Av1>::new_vaapi(display, BlockingMode::Blocking).ok()?)
198 }
199 };
200 let pool = FramePool::new(move |info: &StreamInfo| {
201 alloc_nv12(&gbm, info.coded_resolution).expect("output frame allocation failed")
202 });
203 Some(Self {
204 decoder,
205 nv12_format,
206 pool,
207 demuxer,
208 meta: VhMeta {
209 width: meta.width,
210 height: meta.height,
211 frame_rate: meta.frame_rate,
212 frame_count: meta.frame_count,
213 },
214 ready: VecDeque::new(),
215 pending: Vec::new(),
216 timestamp: 0,
217 flushed: false,
218 skip: 0,
219 out: Vec::new(),
220 luma: 0,
221 chroma: 0,
222 })
223 }
224
225 /// As [`Session::open`], but positioned so the first picture handed out is
226 /// sample `target_sample` (1-based): decode restarts at the sync sample at
227 /// or before it and the pictures in between are dropped unread.
228 fn open_at(path: &Path, target_sample: u32) -> Option<Self> {
229 let mut session = Self::open(path)?;
230 // The ABI still speaks 1-based sample ids, the demuxer speaks 0-based
231 // display frames -- and answers with a signed one, since a sync sample
232 // inside what the edit list trims sits before frame 0.
233 let target_frame = target_sample.saturating_sub(1);
234 let first = session.demuxer.seek_to_sync_at_or_before(target_frame);
235 session.skip = (i64::from(target_frame) - first).max(0) as u32;
236 Some(session)
237 }
238
239 /// Pumps the decoder until one picture is ready. `Ok(false)` is clean EOF.
240 fn pump(&mut self) -> Result<bool, String> {
241 let mut stalls = 0u32;
242 loop {
243 // Stop draining as soon as we have a picture: every handle we hold
244 // keeps a pool buffer out of circulation.
245 while self.ready.is_empty() {
246 match self.decoder.get().next_event() {
247 Some(DecoderEvent::FrameReady(handle)) => self.ready.push_back(handle),
248 Some(DecoderEvent::FormatChanged) => {
249 let info = self
250 .decoder
251 .get()
252 .stream_info()
253 .ok_or("format changed without stream info")?
254 .clone();
255 self.pool.resize(&info);
256 }
257 None => break,
258 }
259 }
260 if let Some(handle) = self.ready.pop_front() {
261 // Seek discards: dropping the handle skips the `vaGetImage`
262 // read-back (~1.2 ms/picture) and frees its pool buffer.
263 if self.skip > 0 {
264 self.skip -= 1;
265 continue;
266 }
267 self.emit(handle);
268 return Ok(true);
269 }
270 if self.flushed {
271 return Ok(false);
272 }
273
274 if self.pending.is_empty() {
275 match self.demuxer.next_access_unit() {
276 Ok(Some(au)) => self.pending = au,
277 Ok(None) => {
278 self.decoder.get().flush().map_err(|e| e.to_string())?;
279 self.flushed = true;
280 continue;
281 }
282 Err(e) => return Err(e.to_string()),
283 }
284 }
285
286 let Self {
287 decoder,
288 pool,
289 pending,
290 timestamp,
291 ..
292 } = self;
293 match decoder
294 .get()
295 .decode(*timestamp, pending, &mut || pool.alloc())
296 {
297 Ok(0) => return Err("decoder consumed no input".into()),
298 Ok(n) => {
299 pending.drain(..n.min(pending.len()));
300 if pending.is_empty() {
301 *timestamp += 1;
302 }
303 stalls = 0;
304 }
305 // Both mean "handle pending events, then resubmit the same data".
306 Err(DecodeError::CheckEvents) | Err(DecodeError::NotEnoughOutputBuffers(_)) => {
307 stalls += 1;
308 if stalls > STALL_LIMIT {
309 return Err("decoder stalled waiting for output buffers".into());
310 }
311 }
312 Err(e) => return Err(e.to_string()),
313 }
314 }
315 }
316
317 /// Copies a decoded NV12 surface into `self.out` as packed I420.
318 fn emit(&mut self, handle: Handle) {
319 let res = handle.display_resolution();
320 let (w, h) = (res.width as usize, res.height as usize);
321 let (cw, ch) = (w.div_ceil(2), h.div_ceil(2));
322 if self.luma != w * h || self.chroma != cw * ch {
323 self.luma = w * h;
324 self.chroma = cw * ch;
325 self.out = vec![0u8; self.luma + 2 * self.chroma];
326 }
327 self.meta.width = res.width;
328 self.meta.height = res.height;
329
330 // Read back with vaGetImage rather than mapping our own DMA-BUF: on a
331 // discrete GPU that buffer lives in VRAM and a CPU read of it runs at
332 // ~44 MB/s over the PCIe BAR (measured), which costs 350 ms/frame. The
333 // driver copies into host-visible memory for us instead.
334 // Cheap no-op in blocking mode, but pixels must never be read early.
335 let _ = DecodedHandle::sync(&handle);
336 let borrowed = handle.borrow();
337 let size = (w as u32, h as u32);
338 let image = Image::create_from(borrowed.surface(), self.nv12_format, size, size)
339 .expect("vaGetImage failed");
340 let va = *image.image();
341 let data: &[u8] = image.as_ref();
342
343 let (dst_y, rest) = self.out.split_at_mut(self.luma);
344 let (dst_u, dst_v) = rest.split_at_mut(self.chroma);
345 nv12_to_i420(
346 &data[va.offsets[Y_PLANE] as usize..],
347 va.pitches[Y_PLANE] as usize,
348 dst_y,
349 w,
350 &data[va.offsets[UV_PLANE] as usize..],
351 va.pitches[UV_PLANE] as usize,
352 dst_u,
353 cw,
354 dst_v,
355 cw,
356 w,
357 h,
358 );
359 }
360
361 fn fill(&self, out: &mut VhFrame) {
362 let w = self.meta.width as usize;
363 let cw = w.div_ceil(2);
364 out.y = self.out.as_ptr();
365 // SAFETY: `out` was sized to luma + 2 * chroma just above in `emit`.
366 unsafe {
367 out.u = self.out.as_ptr().add(self.luma);
368 out.v = self.out.as_ptr().add(self.luma + self.chroma);
369 }
370 out.y_stride = w;
371 out.u_stride = cw;
372 out.v_stride = cw;
373 out.width = self.meta.width;
374 out.height = self.meta.height;
375 }
376}
377
378/// Opens `path` for hardware decode, positioned so the first
379/// [`vh_next_frame`] returns sample `target_sample` (1-based; 0 and 1 both mean
380/// the start of the stream). Returns null on any failure at all: no libva
381/// runtime, no render node, unsupported profile, unreadable file.
382///
383/// # Safety
384/// `path` must be a valid NUL-terminated C string.
385#[unsafe(no_mangle)]
386pub unsafe extern "C" fn vh_open_at(path: *const c_char, target_sample: u32) -> *mut c_void {
387 catch_unwind(AssertUnwindSafe(|| {
388 if path.is_null() {
389 return std::ptr::null_mut();
390 }
391 // SAFETY: caller-guaranteed NUL-terminated string, read before return.
392 let path = unsafe { CStr::from_ptr(path) };
393 let Ok(path) = path.to_str() else {
394 return std::ptr::null_mut();
395 };
396 match Session::open_at(Path::new(path), target_sample) {
397 Some(session) => Box::into_raw(Box::new(session)) as *mut c_void,
398 None => std::ptr::null_mut(),
399 }
400 }))
401 .unwrap_or(std::ptr::null_mut())
402}
403
404/// Fills `out` with stream metadata. 0 on success, negative on failure.
405///
406/// # Safety
407/// `session` must come from [`vh_open_at`] and `out` must be writable.
408#[unsafe(no_mangle)]
409pub unsafe extern "C" fn vh_meta(session: *mut c_void, out: *mut VhMeta) -> i32 {
410 catch_unwind(AssertUnwindSafe(|| {
411 if session.is_null() || out.is_null() {
412 return -1;
413 }
414 // SAFETY: caller-guaranteed live session and writable destination.
415 unsafe {
416 let session = &*(session as *const Session);
417 (*out).width = session.meta.width;
418 (*out).height = session.meta.height;
419 (*out).frame_rate = session.meta.frame_rate;
420 (*out).frame_count = session.meta.frame_count;
421 }
422 0
423 }))
424 .unwrap_or(-1)
425}
426
427/// 1 when `out` holds the next picture in display order, 0 at clean end of
428/// stream, negative on error. Plane pointers stay valid until the next call.
429///
430/// # Safety
431/// `session` must come from [`vh_open_at`] and `out` must be writable.
432#[unsafe(no_mangle)]
433pub unsafe extern "C" fn vh_next_frame(session: *mut c_void, out: *mut VhFrame) -> i32 {
434 catch_unwind(AssertUnwindSafe(|| {
435 if session.is_null() || out.is_null() {
436 return -1;
437 }
438 // SAFETY: caller-guaranteed live session and writable destination.
439 let session = unsafe { &mut *(session as *mut Session) };
440 match session.pump() {
441 Ok(true) => {
442 // SAFETY: `out` is non-null and writable per the contract.
443 session.fill(unsafe { &mut *out });
444 1
445 }
446 Ok(false) => 0,
447 Err(e) => {
448 eprintln!("engine_hw: {e}");
449 -2
450 }
451 }
452 }))
453 .unwrap_or(-1)
454}
455
456/// Releases a session. Safe to call with null.
457///
458/// # Safety
459/// `session` must come from [`vh_open_at`] and must not be used afterwards.
460#[unsafe(no_mangle)]
461pub unsafe extern "C" fn vh_close(session: *mut c_void) {
462 let _ = catch_unwind(AssertUnwindSafe(|| {
463 if !session.is_null() {
464 // SAFETY: pointer came from `Box::into_raw` in `vh_open_at`.
465 drop(unsafe { Box::from_raw(session as *mut Session) });
466 }
467 }));
468}
469
470fn align16(v: u32) -> u32 {
471 v.div_ceil(16) * 16
472}
473
474/// Fills in slice NAL header bytes the driver left at zero.
475///
476/// Mesa's radeonsi encoder writes `forbidden_zero_bit`, `nal_ref_idc` and
477/// `nal_unit_type` from state it only ever populates out of a *packed* slice
478/// header, and cros-codecs supplies none (`h264/vaapi.rs` says as much in its
479/// "use packed headers" TODO). Every other bit of the slice is correct, so the
480/// whole damage is one byte per slice: measured on radeonsi, patching it turns
481/// a stream neither ffmpeg nor `rusty_h264` will touch into one both decode.
482///
483/// An all-zero byte after a start code is never valid H.264, so drivers that do
484/// write the header (Intel's, which is what cros-codecs was built against) fall
485/// straight through this.
486///
487/// ponytail: the real fix is a `VAEncPackedHeaderH264_Slice` buffer in the
488/// vendored cros-codecs backend, which means synthesizing the entire slice
489/// header there rather than correcting two fields here.
490fn fix_slice_nal_headers(au: &mut [u8]) {
491 // cros-codecs prepends SPS+PPS to the access unit at every IDR and only
492 // there, so an SPS seen earlier in this unit is what makes the slice one.
493 let mut idr = false;
494 let mut i = 0;
495 while i + 3 < au.len() {
496 if au[i..i + 3] != [0, 0, 1] {
497 i += 1;
498 continue;
499 }
500 let nal = &mut au[i + 3];
501 if *nal == 0 {
502 // nal_ref_idc 3 + IDR, or 2 + non-IDR: every picture this encoder
503 // emits is a short-term reference (no B-frames, no disposables).
504 *nal = if idr { 0x65 } else { 0x41 };
505 } else if *nal & 0x1f == 7 {
506 idr = true;
507 }
508 i += 3;
509 }
510}
511
512/// One hardware H.264 encode session.
513///
514/// Input goes through a single reusable NV12 buffer object: the caller's I420
515/// planes are interleaved into it and the encoder imports it as a VA surface.
516/// Reuse is safe because the encoder runs in blocking mode and every entry
517/// point polls it before returning, so the GPU is finished with the buffer
518/// before the next picture is written into it.
519struct EncSession {
520 encoder: Encoder,
521 /// Owns the DRM node the buffer object below was allocated from.
522 _gbm: gbm::Device<std::fs::File>,
523 frame: GenericDmaVideoFrame,
524 layout: FrameLayout,
525 /// Macroblock-aligned surface size; `width`/`height` are what is encoded.
526 coded: Resolution,
527 width: usize,
528 height: usize,
529 timestamp: u64,
530 drained: bool,
531 /// Coded access units the encoder has finished but the caller has not
532 /// collected yet, in encode order (which is display order: no B-frames).
533 ready: VecDeque<Vec<u8>>,
534 /// The access unit currently handed out, kept alive until the next call.
535 out: Vec<u8>,
536}
537
538impl EncSession {
539 fn open(width: u32, height: u32, fps_num: u32, fps_den: u32, bitrate: u64) -> Option<Self> {
540 // NV12 chroma is half resolution, so odd dimensions have no packing;
541 // and radeonsi refuses encode contexts below 64x64 (measured).
542 if width < 64 || height < 64 || width % 2 != 0 || height % 2 != 0 {
543 return None;
544 }
545 if fps_num == 0 || fps_den == 0 || bitrate == 0 {
546 return None;
547 }
548 let (display, gbm) = open_devices()?;
549 let coded = Resolution {
550 width: align16(width),
551 height: align16(height),
552 };
553 let framerate = ((fps_num as f64 / fps_den as f64).round() as i64).clamp(1, 240) as u32;
554 let low_power = display
555 .query_config_entrypoints(VAProfile::VAProfileH264Main)
556 .ok()?
557 .contains(&VAEntrypoint::VAEntrypointEncSliceLP);
558 let config = H264Config {
559 resolution: Resolution { width, height },
560 profile: H264Profile::Main,
561 level: Level::L4,
562 // No B-frames: coded order stays display order, which is what the
563 // muxer's duration-only timing assumes.
564 pred_structure: PredictionStructure::LowDelay {
565 limit: (framerate * 2) as u16,
566 },
567 initial_tunings: Tunings {
568 rate_control: RateControl::ConstantBitrate(bitrate),
569 framerate,
570 ..Default::default()
571 },
572 };
573 let encoder = Encoder::new_vaapi(
574 display,
575 config,
576 Fourcc::from(b"NV12"),
577 coded,
578 low_power,
579 BlockingMode::Blocking,
580 )
581 .ok()?;
582 // Allocated at the aligned size, so the buffer's pitch is never smaller
583 // than a padded row.
584 let frame = alloc_nv12(&gbm, coded).ok()?;
585 let layout = nv12_layout(coded, frame.get_plane_pitch()[0]);
586 Some(Self {
587 encoder,
588 _gbm: gbm,
589 frame,
590 layout,
591 coded,
592 width: width as usize,
593 height: height as usize,
594 timestamp: 0,
595 drained: false,
596 ready: VecDeque::new(),
597 out: Vec::new(),
598 })
599 }
600
601 /// Interleaves one packed I420 picture into the NV12 input buffer.
602 ///
603 /// # Safety
604 /// `src`'s planes must cover `height` (resp. `height / 2`) rows of their
605 /// declared stride.
606 unsafe fn upload(&mut self, src: &VhFrame) -> Result<(), String> {
607 let (w, h) = (self.width, self.height);
608 let (cw, ch) = (w / 2, h / 2);
609 let (aw, ah) = (self.coded.width as usize, self.coded.height as usize);
610 let pitch = self.frame.get_plane_pitch();
611 let mapping = self.frame.map_mut()?;
612 let planes = mapping.get();
613 {
614 let mut dst = planes[0].borrow_mut();
615 for row in 0..ah {
616 // SAFETY: caller contract; rows past the picture repeat the last.
617 let s = unsafe {
618 std::slice::from_raw_parts(src.y.add(row.min(h - 1) * src.y_stride), w)
619 };
620 let dst = &mut dst[row * pitch[0]..row * pitch[0] + aw];
621 dst[..w].copy_from_slice(s);
622 // Macroblock padding: replicate the edge rather than leave the
623 // buffer's garbage there, which would cost bitrate for nothing.
624 dst[w..].fill(s[w - 1]);
625 }
626 }
627 let mut dst = planes[1].borrow_mut();
628 for row in 0..ah / 2 {
629 let src_row = row.min(ch - 1);
630 // SAFETY: as above, for the two chroma planes.
631 let (u, v) = unsafe {
632 (
633 std::slice::from_raw_parts(src.u.add(src_row * src.u_stride), cw),
634 std::slice::from_raw_parts(src.v.add(src_row * src.v_stride), cw),
635 )
636 };
637 let dst = &mut dst[row * pitch[1]..row * pitch[1] + aw];
638 for x in 0..cw {
639 dst[2 * x] = u[x];
640 dst[2 * x + 1] = v[x];
641 }
642 for x in w..aw {
643 dst[x] = dst[x - 2];
644 }
645 }
646 Ok(())
647 }
648
649 /// # Safety
650 /// As [`EncSession::upload`].
651 unsafe fn encode(&mut self, src: &VhFrame, force_keyframe: bool) -> Result<(), String> {
652 // SAFETY: caller contract, forwarded.
653 unsafe { self.upload(src)? };
654 let meta = FrameMetadata {
655 timestamp: self.timestamp,
656 layout: self.layout.clone(),
657 force_keyframe,
658 };
659 self.timestamp += 1;
660 self.encoder
661 .encode(meta, self.frame.clone())
662 .map_err(|e| e.to_string())?;
663 self.collect()
664 }
665
666 /// Moves every access unit the encoder has finished into `ready`.
667 fn collect(&mut self) -> Result<(), String> {
668 while let Some(coded) = self.encoder.poll().map_err(|e| e.to_string())? {
669 let mut au = coded.bitstream;
670 fix_slice_nal_headers(&mut au);
671 self.ready.push_back(au);
672 }
673 Ok(())
674 }
675
676 /// Hands the oldest finished access unit to the caller, or reports that
677 /// there is none.
678 fn take(&mut self, out: *mut *const u8, out_len: *mut usize) -> i32 {
679 let Some(au) = self.ready.pop_front() else {
680 return 0;
681 };
682 self.out = au;
683 // SAFETY: caller-guaranteed writable destinations.
684 unsafe {
685 *out = self.out.as_ptr();
686 *out_len = self.out.len();
687 }
688 1
689 }
690}
691
692/// Opens a hardware H.264 encoder for `width`x`height` at `fps_num / fps_den`,
693/// constant bitrate `bitrate` bits per second. Returns null on any failure at
694/// all -- no VA-API runtime, no render node, no encode entrypoint, dimensions
695/// the driver will not take -- and the caller falls back to software.
696#[unsafe(no_mangle)]
697pub extern "C" fn vh_enc_open(
698 width: u32,
699 height: u32,
700 fps_num: u32,
701 fps_den: u32,
702 bitrate: u64,
703) -> *mut c_void {
704 catch_unwind(AssertUnwindSafe(|| {
705 match EncSession::open(width, height, fps_num, fps_den, bitrate) {
706 Some(session) => Box::into_raw(Box::new(session)) as *mut c_void,
707 None => std::ptr::null_mut(),
708 }
709 }))
710 .unwrap_or(std::ptr::null_mut())
711}
712
713/// Encodes one tightly-strided I420 picture. 1 when `out`/`out_len` describe one
714/// Annex-B access unit, 0 when the encoder has nothing coded yet, negative on
715/// error. The bytes stay valid until the next call on this session.
716///
717/// # Safety
718/// `session` must come from [`vh_enc_open`], `frame`'s planes must cover the
719/// picture at their declared strides, and `out`/`out_len` must be writable.
720#[unsafe(no_mangle)]
721pub unsafe extern "C" fn vh_enc_frame(
722 session: *mut c_void,
723 frame: *const VhFrame,
724 force_key: i32,
725 out: *mut *const u8,
726 out_len: *mut usize,
727) -> i32 {
728 catch_unwind(AssertUnwindSafe(|| {
729 if session.is_null() || frame.is_null() || out.is_null() || out_len.is_null() {
730 return -1;
731 }
732 // SAFETY: caller-guaranteed live session and readable frame.
733 let (session, frame) = unsafe { (&mut *(session as *mut EncSession), &*frame) };
734 if frame.y.is_null() || frame.u.is_null() || frame.v.is_null() {
735 return -1;
736 }
737 if frame.width as usize != session.width
738 || frame.height as usize != session.height
739 || frame.y_stride < session.width
740 || frame.u_stride < session.width / 2
741 || frame.v_stride < session.width / 2
742 {
743 return -1;
744 }
745 // SAFETY: caller contract on the plane pointers, sizes checked above.
746 match unsafe { session.encode(frame, force_key != 0) } {
747 Ok(()) => session.take(out, out_len),
748 Err(e) => {
749 eprintln!("engine_hw: {e}");
750 -2
751 }
752 }
753 }))
754 .unwrap_or(-1)
755}
756
757/// Flushes the encoder: 1 while `out`/`out_len` describe another access unit,
758/// 0 once every picture fed has been handed back, negative on error. Same
759/// lifetime rule as [`vh_enc_frame`].
760///
761/// # Safety
762/// `session` must come from [`vh_enc_open`]; `out`/`out_len` must be writable.
763#[unsafe(no_mangle)]
764pub unsafe extern "C" fn vh_enc_drain(
765 session: *mut c_void,
766 out: *mut *const u8,
767 out_len: *mut usize,
768) -> i32 {
769 catch_unwind(AssertUnwindSafe(|| {
770 if session.is_null() || out.is_null() || out_len.is_null() {
771 return -1;
772 }
773 // SAFETY: caller-guaranteed live session.
774 let session = unsafe { &mut *(session as *mut EncSession) };
775 if !session.drained {
776 if let Err(e) = session.encoder.drain().map_err(|e| e.to_string()) {
777 eprintln!("engine_hw: {e}");
778 return -2;
779 }
780 session.drained = true;
781 }
782 match session.collect() {
783 Ok(()) => session.take(out, out_len),
784 Err(e) => {
785 eprintln!("engine_hw: {e}");
786 -2
787 }
788 }
789 }))
790 .unwrap_or(-1)
791}
792
793/// Releases an encode session. Safe to call with null.
794///
795/// # Safety
796/// `session` must come from [`vh_enc_open`] and must not be used afterwards.
797#[unsafe(no_mangle)]
798pub unsafe extern "C" fn vh_enc_close(session: *mut c_void) {
799 let _ = catch_unwind(AssertUnwindSafe(|| {
800 if !session.is_null() {
801 // SAFETY: pointer came from `Box::into_raw` in `vh_enc_open`.
802 drop(unsafe { Box::from_raw(session as *mut EncSession) });
803 }
804 }));
805}