diff --git a/crates/engine-hw/src/lib.rs b/crates/engine-hw/src/lib.rs index cd87b04..d0dd015 100644 --- a/crates/engine-hw/src/lib.rs +++ b/crates/engine-hw/src/lib.rs @@ -12,6 +12,7 @@ use std::collections::VecDeque; use std::ffi::{CStr, c_char, c_void}; +use std::os::fd::IntoRawFd; use std::panic::{AssertUnwindSafe, catch_unwind}; use std::path::{Path, PathBuf}; use std::rc::Rc; @@ -49,7 +50,7 @@ use cros_codecs::{Fourcc, FrameLayout, PlaneLayout, Resolution}; use gbm::{BufferObjectFlags, Format as GbmFormat}; use engine::demux::{Codec, Demuxer}; -use engine::hw::{CAP_AV1, CAP_H264, CAP_HEVC, CAP_VP9, VhCaps, VhFrame, VhMeta}; +use engine::hw::{CAP_AV1, CAP_H264, CAP_HEVC, CAP_VP9, VhCaps, VhDma, VhFrame, VhMeta}; type PooledFrame = PooledVideoFrame; type Dec = StatelessDecoder>; @@ -118,6 +119,13 @@ const STALL_LIMIT: u32 = 10_000; /// hears it. const LEADING_LIMIT: u32 = 64; +/// How many pictures handed out as DRM-PRIME buffers stay un-decoded-over, and +/// therefore how many extra buffers the pool reserves the moment a caller asks +/// for one. The export's decode channel is two pictures deep and it encodes the +/// one it is holding, so at most four are ever outstanding; the rest is margin, +/// at ~3 MB of video memory each. +const DMA_HOLD: usize = 6; + struct Session { decoder: Decoder, /// NV12 (or, for a 10-bit stream, P010) descriptor for `vaGetImage`, @@ -146,6 +154,25 @@ struct Session { out: Vec, luma: usize, chroma: usize, + /// What the caller's encoder can read straight off the GPU, asked once per + /// [`vh_next_frame_dma`] call and `None` for every read-back caller. + want: Option, + /// The descriptor the last such call produced, its file descriptor already + /// belonging to the caller. `None` says that picture was read back instead. + dma: Option, + /// Pictures handed out as DRM-PRIME buffers, newest last: the pool takes a + /// buffer back the moment its handle drops, and the decoder would write the + /// next picture straight into the one an encoder is still reading. Bounded + /// by [`Session::hold`], which is what the pool reserved for it. + held: VecDeque, + /// Extra pool buffers reserved for [`Session::held`]: [`DMA_HOLD`] once a + /// caller has asked for a buffer *before* the pool was sized, and 0 + /// otherwise -- a session whose pool is already sized may not hold anything + /// back, because those buffers are the decoder's own. + hold: usize, + /// Whether the pool has been sized, which happens once, at the first + /// `FormatChanged`. + sized: bool, } /// Mesa's GBM cannot allocate an NV12 buffer object at all (measured on @@ -288,6 +315,11 @@ impl Session { out: Vec::new(), luma: 0, chroma: 0, + want: None, + dma: None, + held: VecDeque::new(), + hold: 0, + sized: false, }) } @@ -361,13 +393,18 @@ impl Session { match self.decoder.get().next_event() { Some(DecoderEvent::FrameReady(handle)) => self.ready.push_back(handle), Some(DecoderEvent::FormatChanged) => { - let info = self + let mut info = self .decoder .get() .stream_info() .ok_or("format changed without stream info")? .clone(); + // The buffers a caller may hold on to are *extra*: the + // count the decoder asks for is what it needs to keep + // decoding, and lending one of those out is a stall. + info.min_num_frames += self.hold; self.pool.resize(&info); + self.sized = true; } None => break, } @@ -379,7 +416,7 @@ impl Session { self.skip -= 1; continue; } - self.emit(handle); + self.deliver(handle); // Past the random access point's leading pictures: a decode // error from here on is a real one again. self.leading = LEADING_LIMIT; @@ -448,6 +485,84 @@ impl Session { } } + /// Hands one decoded picture to the caller: as the buffer it was decoded + /// into where that is what the caller asked for and the encoder on the + /// other side can read it, and as read-back I420 everywhere else. + fn deliver(&mut self, handle: Handle) { + self.dma = None; + if self.hold > 0 && let Some(dma) = self.export_dma(&handle) { + self.meta.width = dma.width; + self.meta.height = dma.height; + self.dma = Some(dma); + // Kept out of the pool until the caller is [`DMA_HOLD`] pictures + // past it, by which time nothing is reading it any more. + self.held.push_back(handle); + while self.held.len() > self.hold { + self.held.pop_front(); + } + return; + } + self.emit(handle); + } + + /// This picture's surface as a DRM-PRIME buffer, if it *is* the shape the + /// caller's encoder takes -- one composed two-plane layer in at most two + /// objects, the fourcc and both sizes it asked for. `None` for every other + /// answer, and the caller then gets the pixels it always got rather than a + /// failure. + fn export_dma(&self, handle: &Handle) -> Option { + let want = self.want?; + let res = handle.display_resolution(); + if (res.width, res.height) != (want.width, want.height) { + return None; + } + // Cheap no-op in blocking mode, but the encoder must never read a + // surface the decoder has not finished writing. + let _ = DecodedHandle::sync(handle); + let borrowed = handle.borrow(); + // The *display* surface for the same reason [`Session::emit`] reads it: + // an AV1 picture with film grain is displayed from a second surface. + let mut desc = borrowed.display_surface().export_prime().ok()?; + let layer = desc.layers.first()?; + if desc.layers.len() != 1 + || layer.num_planes != 2 + || desc.fourcc != want.fourcc + || desc.width != want.coded_width + || desc.height != want.coded_height + { + return None; + } + // Whatever the driver says the two planes live in, said back to it + // unchanged on the import: radeonsi answers with an object per plane, + // other drivers with one for both, and neither is ours to reinterpret. + let (offset, stride) = ( + [layer.offset[0], layer.offset[1]], + [layer.pitch[0], layer.pitch[1]], + ); + let planes = [layer.object_index[0] as usize, layer.object_index[1] as usize]; + if planes[0] != 0 || planes[1] > 1 || desc.objects.len() != planes[1] + 1 { + return None; + } + let modifier = desc.objects[0].drm_format_modifier; + // Handed over with the descriptor: the caller closes them. + let second = (planes[1] == 1) + .then(|| desc.objects.pop().map(|object| object.fd.into_raw_fd())) + .flatten() + .unwrap_or(-1); + let first = desc.objects.remove(0).fd.into_raw_fd(); + Some(VhDma { + fd: [first, second], + fourcc: desc.fourcc, + modifier, + coded_width: desc.width, + coded_height: desc.height, + width: res.width, + height: res.height, + offset, + stride, + }) + } + /// Copies a decoded NV12 surface into `self.out` as packed I420. fn emit(&mut self, handle: Handle) { let res = handle.display_resolution(); @@ -668,6 +783,74 @@ pub unsafe extern "C" fn vh_seek(session: *mut c_void, target_sample: u32) -> i3 .unwrap_or(-1) } +/// As [`vh_next_frame`], but hands the picture over *on the GPU* where it can +/// be: `dma` is filled and its `fd` belongs to the caller (who closes it) when +/// the decoded surface is exactly what an encoder of `coded_width` x +/// `coded_height` carrying a `width` x `height` picture reads, and `out` is +/// filled with read-back I420 exactly as [`vh_next_frame`] fills it otherwise. +/// `dma.fd` below zero is what says which happened. +/// +/// The buffer stays out of the decoder's pool for [`DMA_HOLD`] further +/// pictures and no longer: encode it before asking for that many more. Only a +/// session that has never read a frame back may hand buffers over at all -- +/// those extra pool buffers are reserved at the first picture, and a decoder +/// robbed of its own would stall. +/// +/// # Safety +/// `session` must come from [`vh_open_at`]; `out` and `dma` must be writable. +#[unsafe(no_mangle)] +pub unsafe extern "C" fn vh_next_frame_dma( + session: *mut c_void, + out: *mut VhFrame, + dma: *mut VhDma, + coded_width: u32, + coded_height: u32, + width: u32, + height: u32, +) -> i32 { + catch_unwind(AssertUnwindSafe(|| { + if session.is_null() || out.is_null() || dma.is_null() { + return -1; + } + // SAFETY: caller-guaranteed live session and writable destinations. + let session = unsafe { &mut *(session as *mut Session) }; + // SAFETY: as above. + unsafe { *dma = VhDma::default() }; + // A pool sized without the reserve has nothing to lend: this session + // has been read back from, so it stays that way. + if !session.sized || session.hold > 0 { + session.hold = DMA_HOLD; + session.want = Some(VhDma { + fourcc: VA_FOURCC_NV12, + coded_width, + coded_height, + width, + height, + ..VhDma::default() + }); + } + let pumped = session.pump(); + session.want = None; + match pumped { + Ok(true) => { + match session.dma.take() { + // SAFETY: `dma` is non-null and writable per the contract. + Some(desc) => unsafe { *dma = desc }, + // SAFETY: as above, for `out`. + None => session.fill(unsafe { &mut *out }), + } + 1 + } + Ok(false) => 0, + Err(e) => { + eprintln!("engine_hw: {e}"); + -2 + } + } + })) + .unwrap_or(-1) +} + /// Releases a session. Safe to call with null. /// /// # Safety @@ -840,7 +1023,10 @@ fn fix_slice_nal_headers(au: &mut [u8]) { /// One hardware H.264 encode session. /// -/// Input goes through [`enc_depth`] reusable NV12 buffer objects: the caller's +/// Pictures the caller already has on the GPU go straight in +/// ([`EncSession::encode_dma`]) and touch none of what follows. The rest -- +/// pixels in the caller's memory -- go through [`enc_depth`] reusable NV12 +/// buffer objects: the caller's /// I420 planes are interleaved into the next one and the encoder imports it as a /// VA surface. Reuse is safe because a buffer is only written again once the /// access unit coded *from* it has been polled back -- the encoder runs in @@ -1220,6 +1406,85 @@ impl EncSession { Ok(()) } + /// Encodes a picture the decoder left on the GPU: the buffer is imported as + /// a surface of this session's own shape and read there, so nothing of it + /// ever passes through the CPU -- no `vaGetImage` on the way out of the + /// decoder and no interleave on the way in here. + /// + /// The geometry is checked rather than trusted: a buffer of another shape + /// would be coded as garbage, and the caller asked + /// [`vh_enc_dma_geometry`] what this seat takes before the decoder ever + /// handed one over. + /// + /// **No deferred poll here, unlike [`EncSession::encode`].** That one holds + /// [`enc_depth`] pictures in flight to overlap the *next* picture's CPU + /// interleave with this one's encode; a picture arriving on the GPU has no + /// interleave to overlap, so there is nothing to defer for and the access + /// units are collected as soon as they exist. What the depth still buys is + /// the input buffer, and this path uses none of `frames`: the surface is the + /// decoder's, held for us by its own [`DMA_HOLD`] contract, and draining + /// every call is what keeps that hold short. + /// + /// It is counted in `in_flight` all the same, because one session takes both + /// kinds -- an untouched clip hands buffers over while a graded one or a gap + /// goes through the pixel path -- and a submission missing from the count is + /// a `frames` slot the pixel path would believe free one picture too early. + fn encode_dma(&mut self, dma: &VhDma, force_keyframe: bool) -> Result<(), String> { + if dma.fd[0] < 0 + || dma.fourcc != VA_FOURCC_NV12 + || (dma.coded_width, dma.coded_height) != (self.coded.width, self.coded.height) + || (dma.width as usize, dma.height as usize) != (self.width, self.height) + { + return Err(format!( + "imported buffer is {}x{} in {} coded {}x{}, not {}x{} coded {}x{}", + dma.width, + dma.height, + dma.fourcc, + dma.coded_width, + dma.coded_height, + self.width, + self.height, + self.coded.width, + self.coded.height + )); + } + // One object or two, exactly as the decoder's driver described them: + // the buffers stay the caller's, so each is dup'd for the frame below. + let mut files = Vec::new(); + for fd in dma.fd.iter().copied().take_while(|fd| *fd >= 0) { + // SAFETY: the descriptor's handles are the caller's, open for the + // length of the call. + let owned = unsafe { std::os::fd::BorrowedFd::borrow_raw(fd) } + .try_clone_to_owned() + .map_err(|e| format!("dup of the imported buffer failed: {e}"))?; + files.push(std::fs::File::from(owned)); + } + let objects = files.len(); + let layout = FrameLayout { + format: (Fourcc::from(b"NV12"), dma.modifier), + size: self.coded, + planes: (0..2) + .map(|plane| PlaneLayout { + buffer_index: plane.min(objects - 1), + offset: dma.offset[plane] as usize, + stride: dma.stride[plane] as usize, + }) + .collect(), + }; + let frame = GenericDmaVideoFrame::new(files, layout.clone())?; + let meta = FrameMetadata { + timestamp: self.timestamp, + layout, + force_keyframe, + }; + self.timestamp += 1; + self.encoder + .encode(meta, frame) + .map_err(|e| e.to_string())?; + self.in_flight += 1; + self.collect() + } + /// Moves every access unit the encoder has finished into `ready`. fn collect(&mut self) -> Result<(), String> { while self.pull()? {} @@ -1378,6 +1643,67 @@ pub unsafe extern "C" fn vh_enc_frame( .unwrap_or(-1) } +/// What a decoded buffer must look like to reach this encoder without a copy: +/// the surface size it codes in, written to `coded_width`/`coded_height`. 1 on +/// an answer, negative on none. NV12 and the size this session was opened for +/// are the rest of the shape, and the caller already knows both. +/// +/// # Safety +/// `session` must come from [`vh_enc_open`]; both outputs must be writable. +#[unsafe(no_mangle)] +pub unsafe extern "C" fn vh_enc_dma_geometry( + session: *mut c_void, + coded_width: *mut u32, + coded_height: *mut u32, +) -> i32 { + catch_unwind(AssertUnwindSafe(|| { + if session.is_null() || coded_width.is_null() || coded_height.is_null() { + return -1; + } + // SAFETY: caller-guaranteed live session and writable destinations. + unsafe { + let session = &*(session as *const EncSession); + *coded_width = session.coded.width; + *coded_height = session.coded.height; + } + 1 + })) + .unwrap_or(-1) +} + +/// Encodes one picture the decoder left on the GPU, described by `dma` -- whose +/// file descriptor stays the *caller's*, borrowed for the length of the call. +/// Same answer and same lifetime rule as [`vh_enc_frame`]; a buffer of a shape +/// this session cannot read is an error and not a silent re-shape. +/// +/// # Safety +/// `session` must come from [`vh_enc_open`], `dma` must be readable and its +/// descriptor open, and `out`/`out_len` must be writable. +#[unsafe(no_mangle)] +pub unsafe extern "C" fn vh_enc_frame_dma( + session: *mut c_void, + dma: *const VhDma, + force_key: i32, + out: *mut *const u8, + out_len: *mut usize, +) -> i32 { + catch_unwind(AssertUnwindSafe(|| { + if session.is_null() || dma.is_null() || out.is_null() || out_len.is_null() { + return -1; + } + // SAFETY: caller-guaranteed live session and readable descriptor. + let (session, dma) = unsafe { (&mut *(session as *mut EncSession), &*dma) }; + match session.encode_dma(dma, force_key != 0) { + Ok(()) => session.take(out, out_len), + Err(e) => { + eprintln!("engine_hw: {e}"); + -2 + } + } + })) + .unwrap_or(-1) +} + /// Flushes the encoder: 1 while `out`/`out_len` describe another access unit, /// 0 once every picture fed has been handed back, negative on error. Same /// lifetime rule as [`vh_enc_frame`]. diff --git a/crates/engine/src/export.rs b/crates/engine/src/export.rs index a3e84ad..bebe47c 100644 --- a/crates/engine/src/export.rs +++ b/crates/engine/src/export.rs @@ -74,7 +74,7 @@ use oxideav_core::Muxer as _; use crate::audio::{AudioMeta, AudioSession}; use crate::colorspace::{ColorDescription, Matrix, Transfer}; use crate::demux::{Codec, Demuxer, MkvDemuxer, VideoMeta}; -use crate::hw::{HwEncoder, HwSession}; +use crate::hw::{DmaFrame, DmaWant, HwEncoder, HwPicture, HwSession}; use crate::mux::{ AudioParams, Av1Params, CopyParams, HevcParams, MkvMuxer, Mp4Muxer, SubParams, VideoParams, }; @@ -1918,16 +1918,24 @@ fn run( .get(source) .ok_or_else(|| format!("clip names source {source} of {}", sources.len()))?; let (rate, color, _peak) = rates[source]; + let mapper = tone[source].as_ref(); + // Nothing on the way from this span's decoder to the encoder + // touches a sample: no tone map, no matrix remap, no grade -- + // which is what lets the *decoded buffer itself* be encoded, + // never read back and never written out again. The canvas is + // the fourth thing that would touch it, and the decoder answers + // that one: a picture of another size than this file's is one + // the plugin hands back as pixels ([`HwSession::next_frame_dma`]). + let untouched = mapper.is_none() + && remap_into(Some(color), false, out_color.matrix).is_none() + && project + .composite_color_at(span.start) + .is_none_or(|params| params.is_identity()); + let want = untouched.then(|| encoder.dma_want(meta)).flatten(); // Opened at the file's own frame, which is the only place the // file's numbering is used -- the span's are the timeline's. - let pictures = ClipDecoder::open(&entry.path, rate.source_at(in_frame))?; - ( - Some(pictures), - rate, - in_frame, - Some(color), - tone[source].as_ref(), - ) + let pictures = ClipDecoder::open(&entry.path, rate.source_at(in_frame), want)?; + (Some(pictures), rate, in_frame, Some(color), mapper) } // A gap's black is 16/128/128, which is black in every matrix here // and on every curve: nothing to remap and nothing to tone-map, @@ -2028,50 +2036,46 @@ fn run( } } } - None => Some(black.picture()), + None => { + let (y, u, v, width, height) = black.picture(); + Some(Frame::Pixels(y, u, v, width, height)) + } }; - let Some((y, u, v, width, height)) = picture else { + let Some(frame) = picture else { break; // source ran out early; the clip list outlives the file }; - // The planes are borrowed from the decoder (and `Black::picture` - // hands the same slice as both u and v), so a grade cannot be - // applied in place: it goes onto a copy, which the encoder then - // reads instead. - let params = grade.filter(|p| !p.is_identity()); - let (y, u, v) = match (params, remap, mapper) { - (None, None, None) => (y, u, v), - (params, remap, mapper) => { - let (gy, gu, gv) = &mut graded; - gy.clear(); - gy.extend_from_slice(y); - gu.clear(); - gu.extend_from_slice(u); - gv.clear(); - gv.extend_from_slice(v); - // Tone-map first, so the grade is applied to the SDR picture - // the canvas showed and not to HDR codes; then remap the - // graded result. The order playback renders in, and the - // only order in which preview and export agree. - if let Some(mapper) = mapper { - mapper.map(gy, gu, gv, width as usize, height as usize); - } - if let Some(params) = params { - crate::color::apply_yuv(¶ms, gy, gu, gv); - } - if let Some((from, to)) = remap { - crate::colorspace::remap(from, to, gy, gu, gv, width as usize); - } - (&gy[..], &gu[..], &gv[..]) - } + // A picture still on the GPU has nothing waiting for it here: the + // span was opened that way only where none of what follows would + // have touched a sample of it, so it is placed by nobody and goes + // into the encoder as the buffer the decoder wrote. + let placed = match frame { + Frame::Dma(_) => None, + Frame::Pixels(y, u, v, width, height) => Some(place_picture( + y, + u, + v, + width, + height, + grade, + remap, + mapper, + &mut graded, + &mut canvas, + )), }; - // Grade first, place second: the grade is the clip's own pixels - // and the bars around them are not the clip (see `scale::Composer`). - let (y, u, v, width, height) = canvas.place(y, u, v, width, height); // Once per timeline frame this source frame covers: one at real time // and faster, more when the clip is slowed -- the picture is already // graded and placed, so a held frame costs an encode and no decode. for _ in 0..repeats { - if let Some((au, key)) = encoder.encode(y, u, v, width, height)? { + let coded = match &frame { + Frame::Dma(dma) => encoder.encode_dma(dma)?, + Frame::Pixels(..) => { + let (y, u, v, width, height) = + placed.expect("a picture with pixels was placed"); + encoder.encode(y, u, v, width, height)? + } + }; + if let Some((au, key)) = coded { write_video( &mut muxer, out, @@ -2157,6 +2161,60 @@ fn run( Ok(()) } +/// One decoded picture graded, tone-mapped, remapped and placed on the canvas +/// -- everything between a source's own samples and the ones an encoder is fed, +/// which is exactly the work a zero-copy span has none of. +/// +/// `graded` and `canvas` are the span's scratch: the planes come back borrowed +/// from one of them, or from the picture itself where not a byte was touched. +#[expect(clippy::too_many_arguments, reason = "one span's whole picture path")] +fn place_picture<'a>( + y: &'a [u8], + u: &'a [u8], + v: &'a [u8], + width: u32, + height: u32, + grade: Option, + remap: Option<(Matrix, Matrix)>, + mapper: Option<&ToneMapper>, + graded: &'a mut (Vec, Vec, Vec), + canvas: &'a mut Composer, +) -> (&'a [u8], &'a [u8], &'a [u8], u32, u32) { + // The planes are borrowed from the decoder (and `Black::picture` hands the + // same slice as both u and v), so a grade cannot be applied in place: it + // goes onto a copy, which the encoder then reads instead. + let params = grade.filter(|p| !p.is_identity()); + let (y, u, v) = match (params, remap, mapper) { + (None, None, None) => (y, u, v), + (params, remap, mapper) => { + let (gy, gu, gv) = graded; + gy.clear(); + gy.extend_from_slice(y); + gu.clear(); + gu.extend_from_slice(u); + gv.clear(); + gv.extend_from_slice(v); + // Tone-map first, so the grade is applied to the SDR picture the + // canvas showed and not to HDR codes; then remap the graded result. + // The order playback renders in, and the only order in which + // preview and export agree. + if let Some(mapper) = mapper { + mapper.map(gy, gu, gv, width as usize, height as usize); + } + if let Some(params) = params { + crate::color::apply_yuv(¶ms, gy, gu, gv); + } + if let Some((from, to)) = remap { + crate::colorspace::remap(from, to, gy, gu, gv, width as usize); + } + (&gy[..], &gu[..], &gv[..]) + } + }; + // Grade first, place second: the grade is the clip's own pixels and the + // bars around them are not the clip (see `scale::Composer`). + canvas.place(y, u, v, width, height) +} + /// Which matrix pair a span's samples are rewritten by on the way into a file /// whose own matrix is `out` -- `None` when they are already coded against it, /// and for a gap, whose 16/128/128 black is black in every matrix here. @@ -3119,6 +3177,36 @@ impl Enc { } } + /// What a decoded buffer must look like to reach this seat without ever + /// being read back -- `None` for every seat that reads bytes, which is both + /// software encoders and the intra HEVC one. + /// + /// The AV1 hardware seat is left out on purpose: it is opt-in behind + /// `VE_HW_AV1` because the vendored encoder reset this project's GPU + /// ([`Enc::open_av1`]), and a path that cannot be measured is not one to + /// widen. + fn dma_want(&self, meta: &VideoMeta) -> Option { + match self { + Self::Hw(hw) | Self::HevcHw(hw) => hw.dma_want(meta.width, meta.height), + _ => None, + } + } + + /// One picture the decoder left on the GPU in, at most one access unit out. + /// Same answer as [`Enc::encode`], including which units a decoder may be + /// started from, because it is the same encoder -- only the picture took + /// another way in. + fn encode_dma(&mut self, dma: &DmaFrame) -> crate::Result> { + match self { + Self::Hw(hw) => Ok(hw.encode_dma(dma, false)?.map(|au| (au, false))), + // Every picture an IDR here, exactly as in [`Enc::encode`]. + Self::HevcHw(hw) => Ok(hw.encode_dma(dma, true)?.map(|au| (au, true))), + // Unreachable through [`Enc::dma_want`], which is the only thing + // that puts a span's decoder on this path. + _ => Err("this encoder takes pictures as bytes, not as buffers".into()), + } + } + /// End of stream; call until it returns `None`. fn drain(&mut self) -> crate::Result> { match self { @@ -3395,17 +3483,46 @@ impl Drop for DecodeThread { } } -/// One picture, owned, on its way from a decode thread to the encoder. -struct Yuv { - y: Vec, - u: Vec, - v: Vec, - width: u32, - height: u32, +/// One picture on its way from a decode thread to the encoder: its bytes, or +/// the GPU buffer they are still in. +enum Yuv { + Pixels { + y: Vec, + u: Vec, + v: Vec, + width: u32, + height: u32, + }, + /// Never read back and never copied: a DRM-PRIME handle the encoder imports + /// on the other side of the channel. Sending it is sending an integer, and + /// what keeps the buffer from being decoded over is the channel's own depth + /// (see [`crate::hw::HwSession::next_frame_dma`]). + Dma(DmaFrame), +} + +impl Yuv { + /// The decoder's own buffer copied out, which is what it costs to hand a + /// picture to another thread when the pixels have to travel. + fn pixels(y: &[u8], u: &[u8], v: &[u8], width: u32, height: u32) -> Self { + Self::Pixels { + y: y.to_vec(), + u: u.to_vec(), + v: v.to_vec(), + width, + height, + } + } +} + +/// One picture as the export loop sees it: planes to grade and place, or a +/// buffer that goes straight into the encoder. +enum Frame<'a> { + Pixels(&'a [u8], &'a [u8], &'a [u8], u32, u32), + Dma(&'a DmaFrame), } impl ClipDecoder { - fn open(path: &Path, start_frame: u32) -> crate::Result { + fn open(path: &Path, start_frame: u32, want: Option) -> crate::Result { // Before either decoder: an image is not a stream, so `start_frame` // means nothing to it -- every frame of a still span is the same // picture, which is what playback shows for it too. @@ -3416,7 +3533,7 @@ impl ClipDecoder { let (tx, frames) = sync_channel(2); let handle = thread::Builder::new() .name("export-decode".into()) - .spawn(move || decode_stream(&path, start_frame, &tx))?; + .spawn(move || decode_stream(&path, start_frame, want, &tx))?; Ok(Self::Streamed(Streamed { frames, _thread: DecodeThread(Some(handle)), @@ -3425,22 +3542,26 @@ impl ClipDecoder { })) } - /// The next picture as tightly packed I420, borrowed until the call after. - fn next(&mut self) -> crate::Result> { + /// The next picture, borrowed until the call after -- as tightly packed + /// I420, or as the GPU buffer the decoder wrote it into. + fn next(&mut self) -> crate::Result>> { match self { - Self::Still(still) => Ok(Some(still.picture())), + Self::Still(still) => { + let (y, u, v, width, height) = still.picture(); + Ok(Some(Frame::Pixels(y, u, v, width, height))) + } Self::Streamed(stream) if stream.ended => Ok(None), Self::Streamed(stream) => match stream.frames.recv() { - Ok(Ok(Some(frame))) => { - let frame = stream.current.insert(frame); - Ok(Some(( - &frame.y, - &frame.u, - &frame.v, - frame.width, - frame.height, - ))) - } + Ok(Ok(Some(frame))) => Ok(Some(match stream.current.insert(frame) { + Yuv::Pixels { + y, + u, + v, + width, + height, + } => Frame::Pixels(y, u, v, *width, *height), + Yuv::Dma(dma) => Frame::Dma(dma), + })), // The decoder said end of stream in as many words -- a source // shorter than the clip that names it, which the span loop ends // gracefully on. @@ -3473,7 +3594,12 @@ impl ClipDecoder { /// error, or the `Ok(None)` that *is* end of stream. Closing the channel is not /// one of them -- a silent close is a panicked thread, and the receiver treats /// it as the failure it is rather than as a source that ran out. -fn decode_stream(path: &Path, start_frame: u32, tx: &SyncSender>>) { +fn decode_stream( + path: &Path, + start_frame: u32, + want: Option, + tx: &SyncSender>>, +) { let opened = match forced("VE_SW") { false => HwSession::open_at(path, start_frame).map(Pictures::Hw), true => None, @@ -3489,17 +3615,8 @@ fn decode_stream(path: &Path, start_frame: u32, tx: &SyncSender Yuv { - y: y.to_vec(), - u: u.to_vec(), - v: v.to_vec(), - width, - height, - }, + let frame = match decoder.next(want) { + Ok(Some(frame)) => frame, Ok(None) => { let _ = tx.send(Ok(None)); return; @@ -3524,15 +3641,29 @@ enum Pictures { } impl Pictures { - fn next(&mut self) -> crate::Result> { - match self { - Self::Hw(hw) => hw.next_frame(), - Self::Sw(sw) => { + /// The next picture, owned, ready to cross the channel. `want` is what the + /// export's encoder can read straight off the GPU: where the hardware + /// decoder can hand such a buffer over there is no copy here at all, and + /// everything else is the 3 MB memcpy out of the decoder's own buffer that + /// buys the decode and the encode their overlap. + fn next(&mut self, want: Option) -> crate::Result> { + match (self, want) { + (Self::Hw(hw), Some(want)) => Ok(match hw.next_frame_dma(want)? { + Some(HwPicture::Dma(dma)) => Some(Yuv::Dma(dma)), + Some(HwPicture::Pixels(y, u, v, width, height)) => { + Some(Yuv::pixels(y, u, v, width, height)) + } + None => None, + }), + (Self::Hw(hw), None) => Ok(hw + .next_frame()? + .map(|(y, u, v, width, height)| Yuv::pixels(y, u, v, width, height))), + (Self::Sw(sw), _) => { if !sw.advance()? { return Ok(None); } let frame = sw.frame.as_ref().expect("advance stored a picture"); - Ok(Some(( + Ok(Some(Yuv::pixels( &frame.y, &frame.u, &frame.v, @@ -3633,9 +3764,9 @@ mod tests { panic!("decoder died"); }); let mut died = streamed(handle, frames); - let e = died - .next() - .expect_err("a silent death must fail the export, not end the clip"); + let Err(e) = died.next() else { + panic!("a silent death must fail the export, not end the clip") + }; assert!( e.to_string().contains("without a picture or a reason"), "{e}" diff --git a/crates/engine/src/hw.rs b/crates/engine/src/hw.rs index 8a08941..92a9763 100644 --- a/crates/engine/src/hw.rs +++ b/crates/engine/src/hw.rs @@ -16,6 +16,7 @@ //! honest [`crate::demux::Codec::needs_plugin`] refusal covers both. use std::ffi::{CString, c_char, c_void}; +use std::os::fd::FromRawFd; use std::path::{Path, PathBuf}; use std::sync::OnceLock; @@ -62,6 +63,87 @@ impl Default for VhFrame { } } +/// One decoded picture *left on the GPU*: a DRM-PRIME buffer the encoder +/// imports instead of the caller reading the pixels back and writing them out +/// again. All integers, so it crosses a channel to the encoding thread the way +/// a picture's bytes used to. +/// +/// The `fd` belongs to whoever holds this: the plugin hands ownership over with +/// the descriptor and [`DmaFrame`] closes it. What it does *not* own is the +/// buffer's contents -- the decode session keeps the picture from being decoded +/// over for a few frames only (see `vh_next_frame_dma`), which is why nothing +/// but the export's two-deep decode channel may sit between the two calls. +#[repr(C)] +#[derive(Clone, Copy)] +pub struct VhDma { + /// One DRM-PRIME handle per plane, luma then chroma -- which is how the + /// driver hands its own surfaces out (radeonsi exports an NV12 surface as + /// *two* objects into one allocation, measured 2026-08-13), and describing + /// it any other way is guessing at what the second one means. `fd[0]` below + /// zero says this picture is not on the GPU at all; `fd[1]` below zero says + /// both planes live in the first object. + pub fd: [i32; 2], + /// `NV12` and nothing else, today. + pub fourcc: u32, + /// DRM format modifier of the buffer, passed through to the import. + pub modifier: u64, + /// The surface's own size, which is the picture's rounded up to whatever + /// the codec codes in -- what an encoder has to agree with, sample for + /// sample, before it can read this buffer at all. + pub coded_width: u32, + pub coded_height: u32, + /// The picture inside it. + pub width: u32, + pub height: u32, + /// Luma then chroma, each inside its own object above. + pub offset: [u32; 2], + pub stride: [u32; 2], +} + +impl Default for VhDma { + fn default() -> Self { + Self { + fd: [-1, -1], + fourcc: 0, + modifier: 0, + coded_width: 0, + coded_height: 0, + width: 0, + height: 0, + offset: [0; 2], + stride: [0; 2], + } + } +} + +/// A [`VhDma`] with its file descriptor owned: dropping it closes the handle, +/// which is the only thing this side of the ABI has to get right. +pub struct DmaFrame(VhDma); + +impl DmaFrame { + pub fn width(&self) -> u32 { + self.0.width + } + + pub fn height(&self) -> u32 { + self.0.height + } +} + +impl Drop for DmaFrame { + fn drop(&mut self) { + for fd in self.0.fd { + if fd >= 0 { + // SAFETY: the plugin transferred these descriptors to us with + // the frame and nothing else owns them; `DmaFrame` is not + // `Clone`, and the two are distinct handles even where they + // name one allocation. + drop(unsafe { std::os::fd::OwnedFd::from_raw_fd(fd) }); + } + } + } +} + /// What *this machine* takes, as far as the plugin implements it: one bit per /// codec ([`CAP_H264`] and its three neighbours) in each mask, so a caller reads /// "H.264 decodes and encodes here, HEVC only decodes" off three `u32`s. @@ -90,6 +172,12 @@ struct Plugin { open_at: unsafe extern "C" fn(*const c_char, u32) -> *mut c_void, meta: unsafe extern "C" fn(*mut c_void, *mut VhMeta) -> i32, next_frame: unsafe extern "C" fn(*mut c_void, *mut VhFrame) -> i32, + /// The zero-copy door, and optional for the same reason [`Plugin::caps`] is: + /// a plugin built before it decodes exactly as it did, through the read-back + /// above. + next_frame_dma: Option< + unsafe extern "C" fn(*mut c_void, *mut VhFrame, *mut VhDma, u32, u32, u32, u32) -> i32, + >, close: unsafe extern "C" fn(*mut c_void), /// The capability query, and the one symbol of this table that may be /// missing: a plugin built before it exports the four above and not this, @@ -134,6 +222,7 @@ fn load() -> Option { open_at: *lib.get(b"vh_open_at\0").ok()?, meta: *lib.get(b"vh_meta\0").ok()?, next_frame: *lib.get(b"vh_next_frame\0").ok()?, + next_frame_dma: lib.get(b"vh_next_frame_dma\0").ok().map(|s| *s), close: *lib.get(b"vh_close\0").ok()?, caps: lib.get(b"vh_caps\0").ok().map(|s| *s), seek: lib.get(b"vh_seek\0").ok().map(|s| *s), @@ -241,6 +330,55 @@ impl HwSession { 1 => {} code => return Err(format!("hardware decode failed (code {code})").into()), } + self.pixels(&frame).map(Some) + } + + /// The next picture *without reading it back* where the caller's encoder can + /// take the buffer the decoder wrote into -- which is what `want` describes, + /// down to the coded size, because an encoder reads a surface of its own + /// shape or none at all. + /// + /// Anything the plugin cannot hand over that way comes back as pixels + /// instead ([`HwPicture::Pixels`]), so a mismatch costs the read-back it + /// always cost and never a frame. A plugin too old to know the door exists + /// is the same answer. + /// + /// The buffer behind a [`DmaFrame`] is the decoder's, held out of its pool + /// for a few pictures only: encode it before asking this for a few more. + pub fn next_frame_dma(&mut self, want: DmaWant) -> crate::Result>> { + let Some(next_dma) = self.plugin.next_frame_dma else { + return Ok(self.next_frame()?.map(|(y, u, v, w, h)| HwPicture::Pixels(y, u, v, w, h))); + }; + let mut frame = VhFrame::default(); + let mut dma = VhDma::default(); + // SAFETY: as `next_frame`, plus a writable descriptor whose `fd` the + // plugin either hands us ownership of or leaves at -1. + let code = unsafe { + next_dma( + self.handle, + &mut frame, + &mut dma, + want.coded_width, + want.coded_height, + want.width, + want.height, + ) + }; + match code { + 0 => return Ok(None), + 1 => {} + code => return Err(format!("hardware decode failed (code {code})").into()), + } + if dma.fd[0] >= 0 { + return Ok(Some(HwPicture::Dma(DmaFrame(dma)))); + } + let (y, u, v, w, h) = self.pixels(&frame)?; + Ok(Some(HwPicture::Pixels(y, u, v, w, h))) + } + + /// The plugin's plane pointers as slices, checked against the strides it + /// declares -- the one shape this side takes. + fn pixels(&self, frame: &VhFrame) -> crate::Result<(&[u8], &[u8], &[u8], u32, u32)> { let (w, h) = (frame.width as usize, frame.height as usize); let (cw, ch) = (w.div_ceil(2), h.div_ceil(2)); if frame.y.is_null() @@ -255,17 +393,34 @@ impl HwSession { // SAFETY: plane pointers are non-null and the strides just checked above // pin each plane's length; the borrow ends before the next call. unsafe { - Ok(Some(( + Ok(( std::slice::from_raw_parts(frame.y, w * h), std::slice::from_raw_parts(frame.u, cw * ch), std::slice::from_raw_parts(frame.v, cw * ch), frame.width, frame.height, - ))) + )) } } } +/// What an encoder needs a decoded buffer to look like before it can read it +/// without a copy: the surface's coded size and the picture inside it. +#[derive(Clone, Copy)] +pub struct DmaWant { + pub coded_width: u32, + pub coded_height: u32, + pub width: u32, + pub height: u32, +} + +/// One picture out of [`HwSession::next_frame_dma`]: still on the GPU, or read +/// back like every other frame. +pub enum HwPicture<'a> { + Pixels(&'a [u8], &'a [u8], &'a [u8], u32, u32), + Dma(DmaFrame), +} + impl Drop for HwSession { fn drop(&mut self) { // SAFETY: `handle` came from `vh_open_at` and is closed exactly once. @@ -291,6 +446,12 @@ struct EncPlugin { open_hevc: Option *mut c_void>, frame: unsafe extern "C" fn(*mut c_void, *const VhFrame, i32, *mut *const u8, *mut usize) -> i32, + /// The zero-copy pair, both optional together: an older plugin exports + /// neither and every picture reaches it as bytes, which is what it always + /// did. + dma_geometry: Option i32>, + frame_dma: + Option i32>, drain: unsafe extern "C" fn(*mut c_void, *mut *const u8, *mut usize) -> i32, close: unsafe extern "C" fn(*mut c_void), // Never dropped (lives in a static), so the fn pointers above stay valid. @@ -317,6 +478,8 @@ fn load_enc() -> Option { open_av1: lib.get(b"vh_enc_av1_open\0").ok().map(|s| *s), open_hevc: lib.get(b"vh_enc_hevc_open\0").ok().map(|s| *s), frame: *lib.get(b"vh_enc_frame\0").ok()?, + dma_geometry: lib.get(b"vh_enc_dma_geometry\0").ok().map(|s| *s), + frame_dma: lib.get(b"vh_enc_frame_dma\0").ok().map(|s| *s), drain: *lib.get(b"vh_enc_drain\0").ok()?, close: *lib.get(b"vh_enc_close\0").ok()?, _lib: lib, @@ -450,6 +613,41 @@ impl HwEncoder { }) } + /// What a decoded buffer must look like to reach this encoder without a + /// copy -- the surface size it codes in, plus the picture it was opened for + /// -- or `None` where the plugin has no zero-copy door at all. + pub fn dma_want(&self, width: u32, height: u32) -> Option { + let geometry = self.plugin.dma_geometry?; + self.plugin.frame_dma?; + let (mut coded_width, mut coded_height) = (0u32, 0u32); + // SAFETY: `handle` is live and both destinations are writable. + if unsafe { geometry(self.handle, &mut coded_width, &mut coded_height) } != 1 { + return None; + } + Some(DmaWant { + coded_width, + coded_height, + width, + height, + }) + } + + /// Feeds one picture the decoder left on the GPU. Same answer and same + /// lifetime rule as [`HwEncoder::encode`]; an error here is a real one, the + /// caller having asked [`HwEncoder::dma_want`] what this seat takes before + /// the decoder handed the buffer over. + pub fn encode_dma(&mut self, dma: &DmaFrame, force_key: bool) -> crate::Result> { + let Some(frame_dma) = self.plugin.frame_dma else { + return Err("hardware encoder has no zero-copy path".into()); + }; + let desc = dma.0; + // SAFETY: `handle` is live and `desc` outlives the call; the buffer it + // names is the decode session's, held for the caller by contract. + self.take(|_, handle, out, out_len| unsafe { + frame_dma(handle, &desc, force_key as i32, out, out_len) + }) + } + /// Flushes the encoder; call until it returns `Ok(None)`. Same lifetime rule /// as [`HwEncoder::encode`]. pub fn drain(&mut self) -> crate::Result> { diff --git a/crates/engine/tests/hw_encode.rs b/crates/engine/tests/hw_encode.rs index 52dbd1b..94eabda 100644 --- a/crates/engine/tests/hw_encode.rs +++ b/crates/engine/tests/hw_encode.rs @@ -14,7 +14,7 @@ use std::time::{Duration, Instant}; -use engine::hw::{HwEncoder, HwSession}; +use engine::hw::{HwEncoder, HwPicture, HwSession}; const FPS: u32 = 30; const BITRATE: u64 = 4_000_000; @@ -140,6 +140,82 @@ fn round_trips_unaligned_dimensions() { ); } +/// The zero-copy path: a picture the hardware decoder wrote goes into the +/// hardware encoder as the buffer it was decoded into, never read back and never +/// written out again -- which is what makes an export of an untouched clip cost +/// no `vaGetImage`, no colour conversion and no upload per frame. +/// +/// Two things are checked and the second is the one that matters. That the +/// buffers are handed over *at all* (a driver whose export the plugin refuses +/// falls back to pixels, silently and correctly, which would make a speed claim +/// a lie). And that what came out is what went in: the encoded stream is decoded +/// in software and compared against the same file decoded through the read-back +/// path, so a wrong plane offset, a swapped object or an unsynchronised surface +/// -- the ways an imported buffer goes wrong -- fails here instead of shipping +/// as a garbled export. +#[test] +#[ignore = "needs libengine_hw.so and a VA-API driver with H.264 decode and encode"] +fn a_decoded_buffer_is_encoded_without_ever_being_read_back() { + const FRAMES: usize = 24; + let asset = + std::path::PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("../../assets/test_baseline.mp4"); + let (width, height) = (1280u32, 720u32); + let Some(mut encoder) = HwEncoder::open(width, height, FPS, 1, BITRATE) else { + println!("no hardware encoder here -- skipping"); + return; + }; + let Some(want) = encoder.dma_want(width, height) else { + panic!("a hardware encoder that takes no imported buffer at all"); + }; + let mut session = HwSession::open(&asset).expect("hardware decode of the fixture"); + + let mut stream = Vec::new(); + let mut buffers = 0; + for index in 0..FRAMES { + match session.next_frame_dma(want).expect("hardware decode") { + Some(HwPicture::Dma(dma)) => { + assert_eq!((dma.width(), dma.height()), (width, height), "frame {index}"); + buffers += 1; + if let Some(au) = encoder.encode_dma(&dma, false).expect("encode") { + stream.extend_from_slice(au); + } + } + Some(HwPicture::Pixels(..)) => panic!("frame {index} was read back after all"), + None => panic!("the fixture ran out at frame {index}"), + } + } + while let Some(au) = encoder.drain().expect("drain") { + stream.extend_from_slice(au); + } + assert_eq!(buffers, FRAMES, "every picture came over as a buffer"); + + // The same file down the path this one exists to avoid, which is the only + // honest reference for "the encoder read the right pixels". + let mut reference = HwSession::open(&asset).expect("hardware decode of the fixture"); + let coded = decode(&stream); + assert_eq!(coded.len(), FRAMES, "decoded picture count"); + for (index, frame) in coded.iter().enumerate() { + let (y, u, v, w, h) = reference + .next_frame() + .expect("read-back decode") + .expect("the fixture is longer than this"); + assert_eq!((w, h), (width, height), "frame {index}"); + for (plane, (got, want)) in [(&frame.y, y), (&frame.u, u), (&frame.v, v)] + .iter() + .enumerate() + { + // Lossy CBR against the source picture: the same tolerance the + // synthetic round trip above uses, and nowhere near what a swapped + // plane or a stale surface would cost. + let diff = mean_abs_diff(got, want); + assert!( + diff < 6.0, + "frame {index} plane {plane} drifted by {diff:.2}" + ); + } + } +} + /// Decode and encode resolve through two independent symbol tables, so an /// encoder that cannot load must not cost us the decoder (and vice versa). ///