forge
Explore
Log in

Don't you dare go Hollow

🔀 merge(engine-hw): the encoder that skips the CPU keeps the two it holds

Browse files at this commit

97171516feea73f1539035be8701048bb6bb134fAhmet Kaan GümüşParent: 1cb74a4366171b
Lane E4's zero-copy encode path meets lane E's two-picture encoder. Both
touched the same file at the same place and neither knew of the other.

* `vh_seek` and `vh_next_frame_dma` were the textual conflict and nothing
  more: two different symbols added at one spot. Both kept.
* `EncSession::encode_dma` submits a picture like `encode` does, so it
  counts one in `in_flight` -- one session takes both kinds of picture
  (an untouched clip hands buffers over while a graded one or a gap goes
  through the pixel path), and a submission missing from that count is an
  input buffer the pixel path would believe free one picture too early.
* No deferred poll on the dma path, said in a comment where it would go:
  the depth exists to overlap the *next* picture's CPU interleave with
  this one's encode, and a picture arriving on the GPU has no interleave
  to overlap. Draining every call is also what keeps the decoder's own
  hold on the buffer short.
* Per-codec `enc_depth` therefore governs both kinds: the pixel gate is
  the only one there is, and the dma path leaves `in_flight` at its floor.

`nm -D libengine_hw.so` lists both lanes' optional symbols: vh_seek,
vh_next_frame_dma, vh_enc_dma_geometry, vh_enc_frame_dma. The refusal
fallback is untouched -- a buffer the plugin cannot hand over comes back
as pixels, never as a failure.

The dma path itself is read, not run: every test that would exercise it
is hardware-gated and the GPU is wedged.
crates/engine-hw/src/lib.rsmodified+330 -4
@@ -12,6 +12,7 @@
12 12
13 use std::collections::VecDeque;13 use std::collections::VecDeque;
14 use std::ffi::{CStr, c_char, c_void};14 use std::ffi::{CStr, c_char, c_void};
15+use std::os::fd::IntoRawFd;
15 use std::panic::{AssertUnwindSafe, catch_unwind};16 use std::panic::{AssertUnwindSafe, catch_unwind};
16 use std::path::{Path, PathBuf};17 use std::path::{Path, PathBuf};
17 use std::rc::Rc;18 use std::rc::Rc;
@@ -49,7 +50,7 @@ use cros_codecs::{Fourcc, FrameLayout, PlaneLayout, Resolution};
49 use gbm::{BufferObjectFlags, Format as GbmFormat};50 use gbm::{BufferObjectFlags, Format as GbmFormat};
50 51
51 use engine::demux::{Codec, Demuxer};52 use engine::demux::{Codec, Demuxer};
52-use engine::hw::{CAP_AV1, CAP_H264, CAP_HEVC, CAP_VP9, VhCaps, VhFrame, VhMeta};53+use engine::hw::{CAP_AV1, CAP_H264, CAP_HEVC, CAP_VP9, VhCaps, VhDma, VhFrame, VhMeta};
53 54
54 type PooledFrame = PooledVideoFrame<GenericDmaVideoFrame>;55 type PooledFrame = PooledVideoFrame<GenericDmaVideoFrame>;
55 type Dec<C> = StatelessDecoder<C, VaapiBackend<PooledFrame>>;56 type Dec<C> = StatelessDecoder<C, VaapiBackend<PooledFrame>>;
@@ -118,6 +119,13 @@ const STALL_LIMIT: u32 = 10_000;
118 /// hears it.119 /// hears it.
119 const LEADING_LIMIT: u32 = 64;120 const LEADING_LIMIT: u32 = 64;
120 121
122+/// How many pictures handed out as DRM-PRIME buffers stay un-decoded-over, and
123+/// therefore how many extra buffers the pool reserves the moment a caller asks
124+/// for one. The export's decode channel is two pictures deep and it encodes the
125+/// one it is holding, so at most four are ever outstanding; the rest is margin,
126+/// at ~3 MB of video memory each.
127+const DMA_HOLD: usize = 6;
128+
121 struct Session {129 struct Session {
122 decoder: Decoder,130 decoder: Decoder,
123 /// NV12 (or, for a 10-bit stream, P010) descriptor for `vaGetImage`,131 /// NV12 (or, for a 10-bit stream, P010) descriptor for `vaGetImage`,
@@ -146,6 +154,25 @@ struct Session {
146 out: Vec<u8>,154 out: Vec<u8>,
147 luma: usize,155 luma: usize,
148 chroma: usize,156 chroma: usize,
157+ /// What the caller's encoder can read straight off the GPU, asked once per
158+ /// [`vh_next_frame_dma`] call and `None` for every read-back caller.
159+ want: Option<VhDma>,
160+ /// The descriptor the last such call produced, its file descriptor already
161+ /// belonging to the caller. `None` says that picture was read back instead.
162+ dma: Option<VhDma>,
163+ /// Pictures handed out as DRM-PRIME buffers, newest last: the pool takes a
164+ /// buffer back the moment its handle drops, and the decoder would write the
165+ /// next picture straight into the one an encoder is still reading. Bounded
166+ /// by [`Session::hold`], which is what the pool reserved for it.
167+ held: VecDeque<Handle>,
168+ /// Extra pool buffers reserved for [`Session::held`]: [`DMA_HOLD`] once a
169+ /// caller has asked for a buffer *before* the pool was sized, and 0
170+ /// otherwise -- a session whose pool is already sized may not hold anything
171+ /// back, because those buffers are the decoder's own.
172+ hold: usize,
173+ /// Whether the pool has been sized, which happens once, at the first
174+ /// `FormatChanged`.
175+ sized: bool,
149 }176 }
150 177
151 /// Mesa's GBM cannot allocate an NV12 buffer object at all (measured on178 /// Mesa's GBM cannot allocate an NV12 buffer object at all (measured on
@@ -288,6 +315,11 @@ impl Session {
288 out: Vec::new(),315 out: Vec::new(),
289 luma: 0,316 luma: 0,
290 chroma: 0,317 chroma: 0,
318+ want: None,
319+ dma: None,
320+ held: VecDeque::new(),
321+ hold: 0,
322+ sized: false,
291 })323 })
292 }324 }
293 325
@@ -361,13 +393,18 @@ impl Session {
361 match self.decoder.get().next_event() {393 match self.decoder.get().next_event() {
362 Some(DecoderEvent::FrameReady(handle)) => self.ready.push_back(handle),394 Some(DecoderEvent::FrameReady(handle)) => self.ready.push_back(handle),
363 Some(DecoderEvent::FormatChanged) => {395 Some(DecoderEvent::FormatChanged) => {
364- let info = self396+ let mut info = self
365 .decoder397 .decoder
366 .get()398 .get()
367 .stream_info()399 .stream_info()
368 .ok_or("format changed without stream info")?400 .ok_or("format changed without stream info")?
369 .clone();401 .clone();
402+ // The buffers a caller may hold on to are *extra*: the
403+ // count the decoder asks for is what it needs to keep
404+ // decoding, and lending one of those out is a stall.
405+ info.min_num_frames += self.hold;
370 self.pool.resize(&info);406 self.pool.resize(&info);
407+ self.sized = true;
371 }408 }
372 None => break,409 None => break,
373 }410 }
@@ -379,7 +416,7 @@ impl Session {
379 self.skip -= 1;416 self.skip -= 1;
380 continue;417 continue;
381 }418 }
382- self.emit(handle);419+ self.deliver(handle);
383 // Past the random access point's leading pictures: a decode420 // Past the random access point's leading pictures: a decode
384 // error from here on is a real one again.421 // error from here on is a real one again.
385 self.leading = LEADING_LIMIT;422 self.leading = LEADING_LIMIT;
@@ -448,6 +485,84 @@ impl Session {
448 }485 }
449 }486 }
450 487
488+ /// Hands one decoded picture to the caller: as the buffer it was decoded
489+ /// into where that is what the caller asked for and the encoder on the
490+ /// other side can read it, and as read-back I420 everywhere else.
491+ fn deliver(&mut self, handle: Handle) {
492+ self.dma = None;
493+ if self.hold > 0 && let Some(dma) = self.export_dma(&handle) {
494+ self.meta.width = dma.width;
495+ self.meta.height = dma.height;
496+ self.dma = Some(dma);
497+ // Kept out of the pool until the caller is [`DMA_HOLD`] pictures
498+ // past it, by which time nothing is reading it any more.
499+ self.held.push_back(handle);
500+ while self.held.len() > self.hold {
501+ self.held.pop_front();
502+ }
503+ return;
504+ }
505+ self.emit(handle);
506+ }
507+
508+ /// This picture's surface as a DRM-PRIME buffer, if it *is* the shape the
509+ /// caller's encoder takes -- one composed two-plane layer in at most two
510+ /// objects, the fourcc and both sizes it asked for. `None` for every other
511+ /// answer, and the caller then gets the pixels it always got rather than a
512+ /// failure.
513+ fn export_dma(&self, handle: &Handle) -> Option<VhDma> {
514+ let want = self.want?;
515+ let res = handle.display_resolution();
516+ if (res.width, res.height) != (want.width, want.height) {
517+ return None;
518+ }
519+ // Cheap no-op in blocking mode, but the encoder must never read a
520+ // surface the decoder has not finished writing.
521+ let _ = DecodedHandle::sync(handle);
522+ let borrowed = handle.borrow();
523+ // The *display* surface for the same reason [`Session::emit`] reads it:
524+ // an AV1 picture with film grain is displayed from a second surface.
525+ let mut desc = borrowed.display_surface().export_prime().ok()?;
526+ let layer = desc.layers.first()?;
527+ if desc.layers.len() != 1
528+ || layer.num_planes != 2
529+ || desc.fourcc != want.fourcc
530+ || desc.width != want.coded_width
531+ || desc.height != want.coded_height
532+ {
533+ return None;
534+ }
535+ // Whatever the driver says the two planes live in, said back to it
536+ // unchanged on the import: radeonsi answers with an object per plane,
537+ // other drivers with one for both, and neither is ours to reinterpret.
538+ let (offset, stride) = (
539+ [layer.offset[0], layer.offset[1]],
540+ [layer.pitch[0], layer.pitch[1]],
541+ );
542+ let planes = [layer.object_index[0] as usize, layer.object_index[1] as usize];
543+ if planes[0] != 0 || planes[1] > 1 || desc.objects.len() != planes[1] + 1 {
544+ return None;
545+ }
546+ let modifier = desc.objects[0].drm_format_modifier;
547+ // Handed over with the descriptor: the caller closes them.
548+ let second = (planes[1] == 1)
549+ .then(|| desc.objects.pop().map(|object| object.fd.into_raw_fd()))
550+ .flatten()
551+ .unwrap_or(-1);
552+ let first = desc.objects.remove(0).fd.into_raw_fd();
553+ Some(VhDma {
554+ fd: [first, second],
555+ fourcc: desc.fourcc,
556+ modifier,
557+ coded_width: desc.width,
558+ coded_height: desc.height,
559+ width: res.width,
560+ height: res.height,
561+ offset,
562+ stride,
563+ })
564+ }
565+
451 /// Copies a decoded NV12 surface into `self.out` as packed I420.566 /// Copies a decoded NV12 surface into `self.out` as packed I420.
452 fn emit(&mut self, handle: Handle) {567 fn emit(&mut self, handle: Handle) {
453 let res = handle.display_resolution();568 let res = handle.display_resolution();
@@ -668,6 +783,74 @@ pub unsafe extern "C" fn vh_seek(session: *mut c_void, target_sample: u32) -> i3
668 .unwrap_or(-1)783 .unwrap_or(-1)
669 }784 }
670 785
786+/// As [`vh_next_frame`], but hands the picture over *on the GPU* where it can
787+/// be: `dma` is filled and its `fd` belongs to the caller (who closes it) when
788+/// the decoded surface is exactly what an encoder of `coded_width` x
789+/// `coded_height` carrying a `width` x `height` picture reads, and `out` is
790+/// filled with read-back I420 exactly as [`vh_next_frame`] fills it otherwise.
791+/// `dma.fd` below zero is what says which happened.
792+///
793+/// The buffer stays out of the decoder's pool for [`DMA_HOLD`] further
794+/// pictures and no longer: encode it before asking for that many more. Only a
795+/// session that has never read a frame back may hand buffers over at all --
796+/// those extra pool buffers are reserved at the first picture, and a decoder
797+/// robbed of its own would stall.
798+///
799+/// # Safety
800+/// `session` must come from [`vh_open_at`]; `out` and `dma` must be writable.
801+#[unsafe(no_mangle)]
802+pub unsafe extern "C" fn vh_next_frame_dma(
803+ session: *mut c_void,
804+ out: *mut VhFrame,
805+ dma: *mut VhDma,
806+ coded_width: u32,
807+ coded_height: u32,
808+ width: u32,
809+ height: u32,
810+) -> i32 {
811+ catch_unwind(AssertUnwindSafe(|| {
812+ if session.is_null() || out.is_null() || dma.is_null() {
813+ return -1;
814+ }
815+ // SAFETY: caller-guaranteed live session and writable destinations.
816+ let session = unsafe { &mut *(session as *mut Session) };
817+ // SAFETY: as above.
818+ unsafe { *dma = VhDma::default() };
819+ // A pool sized without the reserve has nothing to lend: this session
820+ // has been read back from, so it stays that way.
821+ if !session.sized || session.hold > 0 {
822+ session.hold = DMA_HOLD;
823+ session.want = Some(VhDma {
824+ fourcc: VA_FOURCC_NV12,
825+ coded_width,
826+ coded_height,
827+ width,
828+ height,
829+ ..VhDma::default()
830+ });
831+ }
832+ let pumped = session.pump();
833+ session.want = None;
834+ match pumped {
835+ Ok(true) => {
836+ match session.dma.take() {
837+ // SAFETY: `dma` is non-null and writable per the contract.
838+ Some(desc) => unsafe { *dma = desc },
839+ // SAFETY: as above, for `out`.
840+ None => session.fill(unsafe { &mut *out }),
841+ }
842+ 1
843+ }
844+ Ok(false) => 0,
845+ Err(e) => {
846+ eprintln!("engine_hw: {e}");
847+ -2
848+ }
849+ }
850+ }))
851+ .unwrap_or(-1)
852+}
853+
671 /// Releases a session. Safe to call with null.854 /// Releases a session. Safe to call with null.
672 ///855 ///
673 /// # Safety856 /// # Safety
@@ -840,7 +1023,10 @@ fn fix_slice_nal_headers(au: &mut [u8]) {
840 1023
841 /// One hardware H.264 encode session.1024 /// One hardware H.264 encode session.
842 ///1025 ///
843-/// Input goes through [`enc_depth`] reusable NV12 buffer objects: the caller's1026+/// Pictures the caller already has on the GPU go straight in
1027+/// ([`EncSession::encode_dma`]) and touch none of what follows. The rest --
1028+/// pixels in the caller's memory -- go through [`enc_depth`] reusable NV12
1029+/// buffer objects: the caller's
844 /// I420 planes are interleaved into the next one and the encoder imports it as a1030 /// I420 planes are interleaved into the next one and the encoder imports it as a
845 /// VA surface. Reuse is safe because a buffer is only written again once the1031 /// VA surface. Reuse is safe because a buffer is only written again once the
846 /// access unit coded *from* it has been polled back -- the encoder runs in1032 /// access unit coded *from* it has been polled back -- the encoder runs in
@@ -1220,6 +1406,85 @@ impl EncSession {
1220 Ok(())1406 Ok(())
1221 }1407 }
1222 1408
1409+ /// Encodes a picture the decoder left on the GPU: the buffer is imported as
1410+ /// a surface of this session's own shape and read there, so nothing of it
1411+ /// ever passes through the CPU -- no `vaGetImage` on the way out of the
1412+ /// decoder and no interleave on the way in here.
1413+ ///
1414+ /// The geometry is checked rather than trusted: a buffer of another shape
1415+ /// would be coded as garbage, and the caller asked
1416+ /// [`vh_enc_dma_geometry`] what this seat takes before the decoder ever
1417+ /// handed one over.
1418+ ///
1419+ /// **No deferred poll here, unlike [`EncSession::encode`].** That one holds
1420+ /// [`enc_depth`] pictures in flight to overlap the *next* picture's CPU
1421+ /// interleave with this one's encode; a picture arriving on the GPU has no
1422+ /// interleave to overlap, so there is nothing to defer for and the access
1423+ /// units are collected as soon as they exist. What the depth still buys is
1424+ /// the input buffer, and this path uses none of `frames`: the surface is the
1425+ /// decoder's, held for us by its own [`DMA_HOLD`] contract, and draining
1426+ /// every call is what keeps that hold short.
1427+ ///
1428+ /// It is counted in `in_flight` all the same, because one session takes both
1429+ /// kinds -- an untouched clip hands buffers over while a graded one or a gap
1430+ /// goes through the pixel path -- and a submission missing from the count is
1431+ /// a `frames` slot the pixel path would believe free one picture too early.
1432+ fn encode_dma(&mut self, dma: &VhDma, force_keyframe: bool) -> Result<(), String> {
1433+ if dma.fd[0] < 0
1434+ || dma.fourcc != VA_FOURCC_NV12
1435+ || (dma.coded_width, dma.coded_height) != (self.coded.width, self.coded.height)
1436+ || (dma.width as usize, dma.height as usize) != (self.width, self.height)
1437+ {
1438+ return Err(format!(
1439+ "imported buffer is {}x{} in {} coded {}x{}, not {}x{} coded {}x{}",
1440+ dma.width,
1441+ dma.height,
1442+ dma.fourcc,
1443+ dma.coded_width,
1444+ dma.coded_height,
1445+ self.width,
1446+ self.height,
1447+ self.coded.width,
1448+ self.coded.height
1449+ ));
1450+ }
1451+ // One object or two, exactly as the decoder's driver described them:
1452+ // the buffers stay the caller's, so each is dup'd for the frame below.
1453+ let mut files = Vec::new();
1454+ for fd in dma.fd.iter().copied().take_while(|fd| *fd >= 0) {
1455+ // SAFETY: the descriptor's handles are the caller's, open for the
1456+ // length of the call.
1457+ let owned = unsafe { std::os::fd::BorrowedFd::borrow_raw(fd) }
1458+ .try_clone_to_owned()
1459+ .map_err(|e| format!("dup of the imported buffer failed: {e}"))?;
1460+ files.push(std::fs::File::from(owned));
1461+ }
1462+ let objects = files.len();
1463+ let layout = FrameLayout {
1464+ format: (Fourcc::from(b"NV12"), dma.modifier),
1465+ size: self.coded,
1466+ planes: (0..2)
1467+ .map(|plane| PlaneLayout {
1468+ buffer_index: plane.min(objects - 1),
1469+ offset: dma.offset[plane] as usize,
1470+ stride: dma.stride[plane] as usize,
1471+ })
1472+ .collect(),
1473+ };
1474+ let frame = GenericDmaVideoFrame::new(files, layout.clone())?;
1475+ let meta = FrameMetadata {
1476+ timestamp: self.timestamp,
1477+ layout,
1478+ force_keyframe,
1479+ };
1480+ self.timestamp += 1;
1481+ self.encoder
1482+ .encode(meta, frame)
1483+ .map_err(|e| e.to_string())?;
1484+ self.in_flight += 1;
1485+ self.collect()
1486+ }
1487+
1223 /// Moves every access unit the encoder has finished into `ready`.1488 /// Moves every access unit the encoder has finished into `ready`.
1224 fn collect(&mut self) -> Result<(), String> {1489 fn collect(&mut self) -> Result<(), String> {
1225 while self.pull()? {}1490 while self.pull()? {}
@@ -1378,6 +1643,67 @@ pub unsafe extern "C" fn vh_enc_frame(
1378 .unwrap_or(-1)1643 .unwrap_or(-1)
1379 }1644 }
1380 1645
1646+/// What a decoded buffer must look like to reach this encoder without a copy:
1647+/// the surface size it codes in, written to `coded_width`/`coded_height`. 1 on
1648+/// an answer, negative on none. NV12 and the size this session was opened for
1649+/// are the rest of the shape, and the caller already knows both.
1650+///
1651+/// # Safety
1652+/// `session` must come from [`vh_enc_open`]; both outputs must be writable.
1653+#[unsafe(no_mangle)]
1654+pub unsafe extern "C" fn vh_enc_dma_geometry(
1655+ session: *mut c_void,
1656+ coded_width: *mut u32,
1657+ coded_height: *mut u32,
1658+) -> i32 {
1659+ catch_unwind(AssertUnwindSafe(|| {
1660+ if session.is_null() || coded_width.is_null() || coded_height.is_null() {
1661+ return -1;
1662+ }
1663+ // SAFETY: caller-guaranteed live session and writable destinations.
1664+ unsafe {
1665+ let session = &*(session as *const EncSession);
1666+ *coded_width = session.coded.width;
1667+ *coded_height = session.coded.height;
1668+ }
1669+ 1
1670+ }))
1671+ .unwrap_or(-1)
1672+}
1673+
1674+/// Encodes one picture the decoder left on the GPU, described by `dma` -- whose
1675+/// file descriptor stays the *caller's*, borrowed for the length of the call.
1676+/// Same answer and same lifetime rule as [`vh_enc_frame`]; a buffer of a shape
1677+/// this session cannot read is an error and not a silent re-shape.
1678+///
1679+/// # Safety
1680+/// `session` must come from [`vh_enc_open`], `dma` must be readable and its
1681+/// descriptor open, and `out`/`out_len` must be writable.
1682+#[unsafe(no_mangle)]
1683+pub unsafe extern "C" fn vh_enc_frame_dma(
1684+ session: *mut c_void,
1685+ dma: *const VhDma,
1686+ force_key: i32,
1687+ out: *mut *const u8,
1688+ out_len: *mut usize,
1689+) -> i32 {
1690+ catch_unwind(AssertUnwindSafe(|| {
1691+ if session.is_null() || dma.is_null() || out.is_null() || out_len.is_null() {
1692+ return -1;
1693+ }
1694+ // SAFETY: caller-guaranteed live session and readable descriptor.
1695+ let (session, dma) = unsafe { (&mut *(session as *mut EncSession), &*dma) };
1696+ match session.encode_dma(dma, force_key != 0) {
1697+ Ok(()) => session.take(out, out_len),
1698+ Err(e) => {
1699+ eprintln!("engine_hw: {e}");
1700+ -2
1701+ }
1702+ }
1703+ }))
1704+ .unwrap_or(-1)
1705+}
1706+
1381 /// Flushes the encoder: 1 while `out`/`out_len` describe another access unit,1707 /// Flushes the encoder: 1 while `out`/`out_len` describe another access unit,
1382 /// 0 once every picture fed has been handed back, negative on error. Same1708 /// 0 once every picture fed has been handed back, negative on error. Same
1383 /// lifetime rule as [`vh_enc_frame`].1709 /// lifetime rule as [`vh_enc_frame`].
crates/engine/src/export.rsmodified+218 -87
@@ -74,7 +74,7 @@ use oxideav_core::Muxer as _;
74 use crate::audio::{AudioMeta, AudioSession};74 use crate::audio::{AudioMeta, AudioSession};
75 use crate::colorspace::{ColorDescription, Matrix, Transfer};75 use crate::colorspace::{ColorDescription, Matrix, Transfer};
76 use crate::demux::{Codec, Demuxer, MkvDemuxer, VideoMeta};76 use crate::demux::{Codec, Demuxer, MkvDemuxer, VideoMeta};
77-use crate::hw::{HwEncoder, HwSession};77+use crate::hw::{DmaFrame, DmaWant, HwEncoder, HwPicture, HwSession};
78 use crate::mux::{78 use crate::mux::{
79 AudioParams, Av1Params, CopyParams, HevcParams, MkvMuxer, Mp4Muxer, SubParams, VideoParams,79 AudioParams, Av1Params, CopyParams, HevcParams, MkvMuxer, Mp4Muxer, SubParams, VideoParams,
80 };80 };
@@ -1918,16 +1918,24 @@ fn run(
1918 .get(source)1918 .get(source)
1919 .ok_or_else(|| format!("clip names source {source} of {}", sources.len()))?;1919 .ok_or_else(|| format!("clip names source {source} of {}", sources.len()))?;
1920 let (rate, color, _peak) = rates[source];1920 let (rate, color, _peak) = rates[source];
1921+ let mapper = tone[source].as_ref();
1922+ // Nothing on the way from this span's decoder to the encoder
1923+ // touches a sample: no tone map, no matrix remap, no grade --
1924+ // which is what lets the *decoded buffer itself* be encoded,
1925+ // never read back and never written out again. The canvas is
1926+ // the fourth thing that would touch it, and the decoder answers
1927+ // that one: a picture of another size than this file's is one
1928+ // the plugin hands back as pixels ([`HwSession::next_frame_dma`]).
1929+ let untouched = mapper.is_none()
1930+ && remap_into(Some(color), false, out_color.matrix).is_none()
1931+ && project
1932+ .composite_color_at(span.start)
1933+ .is_none_or(|params| params.is_identity());
1934+ let want = untouched.then(|| encoder.dma_want(meta)).flatten();
1921 // Opened at the file's own frame, which is the only place the1935 // Opened at the file's own frame, which is the only place the
1922 // file's numbering is used -- the span's are the timeline's.1936 // file's numbering is used -- the span's are the timeline's.
1923- let pictures = ClipDecoder::open(&entry.path, rate.source_at(in_frame))?;1937+ let pictures = ClipDecoder::open(&entry.path, rate.source_at(in_frame), want)?;
1924- (1938+ (Some(pictures), rate, in_frame, Some(color), mapper)
1925- Some(pictures),
1926- rate,
1927- in_frame,
1928- Some(color),
1929- tone[source].as_ref(),
1930- )
1931 }1939 }
1932 // A gap's black is 16/128/128, which is black in every matrix here1940 // A gap's black is 16/128/128, which is black in every matrix here
1933 // and on every curve: nothing to remap and nothing to tone-map,1941 // and on every curve: nothing to remap and nothing to tone-map,
@@ -2028,50 +2036,46 @@ fn run(
2028 }2036 }
2029 }2037 }
2030 }2038 }
2031- None => Some(black.picture()),2039+ None => {
2040+ let (y, u, v, width, height) = black.picture();
2041+ Some(Frame::Pixels(y, u, v, width, height))
2042+ }
2032 };2043 };
2033- let Some((y, u, v, width, height)) = picture else {2044+ let Some(frame) = picture else {
2034 break; // source ran out early; the clip list outlives the file2045 break; // source ran out early; the clip list outlives the file
2035 };2046 };
2036- // The planes are borrowed from the decoder (and `Black::picture`2047+ // A picture still on the GPU has nothing waiting for it here: the
2037- // hands the same slice as both u and v), so a grade cannot be2048+ // span was opened that way only where none of what follows would
2038- // applied in place: it goes onto a copy, which the encoder then2049+ // have touched a sample of it, so it is placed by nobody and goes
2039- // reads instead.2050+ // into the encoder as the buffer the decoder wrote.
2040- let params = grade.filter(|p| !p.is_identity());2051+ let placed = match frame {
2041- let (y, u, v) = match (params, remap, mapper) {2052+ Frame::Dma(_) => None,
2042- (None, None, None) => (y, u, v),2053+ Frame::Pixels(y, u, v, width, height) => Some(place_picture(
2043- (params, remap, mapper) => {2054+ y,
2044- let (gy, gu, gv) = &mut graded;2055+ u,
2045- gy.clear();2056+ v,
2046- gy.extend_from_slice(y);2057+ width,
2047- gu.clear();2058+ height,
2048- gu.extend_from_slice(u);2059+ grade,
2049- gv.clear();2060+ remap,
2050- gv.extend_from_slice(v);2061+ mapper,
2051- // Tone-map first, so the grade is applied to the SDR picture2062+ &mut graded,
2052- // the canvas showed and not to HDR codes; then remap the2063+ &mut canvas,
2053- // graded result. The order playback renders in, and the2064+ )),
2054- // only order in which preview and export agree.
2055- if let Some(mapper) = mapper {
2056- mapper.map(gy, gu, gv, width as usize, height as usize);
2057- }
2058- if let Some(params) = params {
2059- crate::color::apply_yuv(&params, gy, gu, gv);
2060- }
2061- if let Some((from, to)) = remap {
2062- crate::colorspace::remap(from, to, gy, gu, gv, width as usize);
2063- }
2064- (&gy[..], &gu[..], &gv[..])
2065- }
2066 };2065 };
2067- // Grade first, place second: the grade is the clip's own pixels
2068- // and the bars around them are not the clip (see `scale::Composer`).
2069- let (y, u, v, width, height) = canvas.place(y, u, v, width, height);
2070 // Once per timeline frame this source frame covers: one at real time2066 // Once per timeline frame this source frame covers: one at real time
2071 // and faster, more when the clip is slowed -- the picture is already2067 // and faster, more when the clip is slowed -- the picture is already
2072 // graded and placed, so a held frame costs an encode and no decode.2068 // graded and placed, so a held frame costs an encode and no decode.
2073 for _ in 0..repeats {2069 for _ in 0..repeats {
2074- if let Some((au, key)) = encoder.encode(y, u, v, width, height)? {2070+ let coded = match &frame {
2071+ Frame::Dma(dma) => encoder.encode_dma(dma)?,
2072+ Frame::Pixels(..) => {
2073+ let (y, u, v, width, height) =
2074+ placed.expect("a picture with pixels was placed");
2075+ encoder.encode(y, u, v, width, height)?
2076+ }
2077+ };
2078+ if let Some((au, key)) = coded {
2075 write_video(2079 write_video(
2076 &mut muxer,2080 &mut muxer,
2077 out,2081 out,
@@ -2157,6 +2161,60 @@ fn run(
2157 Ok(())2161 Ok(())
2158 }2162 }
2159 2163
2164+/// One decoded picture graded, tone-mapped, remapped and placed on the canvas
2165+/// -- everything between a source's own samples and the ones an encoder is fed,
2166+/// which is exactly the work a zero-copy span has none of.
2167+///
2168+/// `graded` and `canvas` are the span's scratch: the planes come back borrowed
2169+/// from one of them, or from the picture itself where not a byte was touched.
2170+#[expect(clippy::too_many_arguments, reason = "one span's whole picture path")]
2171+fn place_picture<'a>(
2172+ y: &'a [u8],
2173+ u: &'a [u8],
2174+ v: &'a [u8],
2175+ width: u32,
2176+ height: u32,
2177+ grade: Option<crate::color::ColorParams>,
2178+ remap: Option<(Matrix, Matrix)>,
2179+ mapper: Option<&ToneMapper>,
2180+ graded: &'a mut (Vec<u8>, Vec<u8>, Vec<u8>),
2181+ canvas: &'a mut Composer,
2182+) -> (&'a [u8], &'a [u8], &'a [u8], u32, u32) {
2183+ // The planes are borrowed from the decoder (and `Black::picture` hands the
2184+ // same slice as both u and v), so a grade cannot be applied in place: it
2185+ // goes onto a copy, which the encoder then reads instead.
2186+ let params = grade.filter(|p| !p.is_identity());
2187+ let (y, u, v) = match (params, remap, mapper) {
2188+ (None, None, None) => (y, u, v),
2189+ (params, remap, mapper) => {
2190+ let (gy, gu, gv) = graded;
2191+ gy.clear();
2192+ gy.extend_from_slice(y);
2193+ gu.clear();
2194+ gu.extend_from_slice(u);
2195+ gv.clear();
2196+ gv.extend_from_slice(v);
2197+ // Tone-map first, so the grade is applied to the SDR picture the
2198+ // canvas showed and not to HDR codes; then remap the graded result.
2199+ // The order playback renders in, and the only order in which
2200+ // preview and export agree.
2201+ if let Some(mapper) = mapper {
2202+ mapper.map(gy, gu, gv, width as usize, height as usize);
2203+ }
2204+ if let Some(params) = params {
2205+ crate::color::apply_yuv(&params, gy, gu, gv);
2206+ }
2207+ if let Some((from, to)) = remap {
2208+ crate::colorspace::remap(from, to, gy, gu, gv, width as usize);
2209+ }
2210+ (&gy[..], &gu[..], &gv[..])
2211+ }
2212+ };
2213+ // Grade first, place second: the grade is the clip's own pixels and the
2214+ // bars around them are not the clip (see `scale::Composer`).
2215+ canvas.place(y, u, v, width, height)
2216+}
2217+
2160 /// Which matrix pair a span's samples are rewritten by on the way into a file2218 /// Which matrix pair a span's samples are rewritten by on the way into a file
2161 /// whose own matrix is `out` -- `None` when they are already coded against it,2219 /// whose own matrix is `out` -- `None` when they are already coded against it,
2162 /// and for a gap, whose 16/128/128 black is black in every matrix here.2220 /// and for a gap, whose 16/128/128 black is black in every matrix here.
@@ -3119,6 +3177,36 @@ impl Enc {
3119 }3177 }
3120 }3178 }
3121 3179
3180+ /// What a decoded buffer must look like to reach this seat without ever
3181+ /// being read back -- `None` for every seat that reads bytes, which is both
3182+ /// software encoders and the intra HEVC one.
3183+ ///
3184+ /// The AV1 hardware seat is left out on purpose: it is opt-in behind
3185+ /// `VE_HW_AV1` because the vendored encoder reset this project's GPU
3186+ /// ([`Enc::open_av1`]), and a path that cannot be measured is not one to
3187+ /// widen.
3188+ fn dma_want(&self, meta: &VideoMeta) -> Option<crate::hw::DmaWant> {
3189+ match self {
3190+ Self::Hw(hw) | Self::HevcHw(hw) => hw.dma_want(meta.width, meta.height),
3191+ _ => None,
3192+ }
3193+ }
3194+
3195+ /// One picture the decoder left on the GPU in, at most one access unit out.
3196+ /// Same answer as [`Enc::encode`], including which units a decoder may be
3197+ /// started from, because it is the same encoder -- only the picture took
3198+ /// another way in.
3199+ fn encode_dma(&mut self, dma: &DmaFrame) -> crate::Result<Option<(&[u8], bool)>> {
3200+ match self {
3201+ Self::Hw(hw) => Ok(hw.encode_dma(dma, false)?.map(|au| (au, false))),
3202+ // Every picture an IDR here, exactly as in [`Enc::encode`].
3203+ Self::HevcHw(hw) => Ok(hw.encode_dma(dma, true)?.map(|au| (au, true))),
3204+ // Unreachable through [`Enc::dma_want`], which is the only thing
3205+ // that puts a span's decoder on this path.
3206+ _ => Err("this encoder takes pictures as bytes, not as buffers".into()),
3207+ }
3208+ }
3209+
3122 /// End of stream; call until it returns `None`.3210 /// End of stream; call until it returns `None`.
3123 fn drain(&mut self) -> crate::Result<Option<(&[u8], bool)>> {3211 fn drain(&mut self) -> crate::Result<Option<(&[u8], bool)>> {
3124 match self {3212 match self {
@@ -3395,17 +3483,46 @@ impl Drop for DecodeThread {
3395 }3483 }
3396 }3484 }
3397 3485
3398-/// One picture, owned, on its way from a decode thread to the encoder.3486+/// One picture on its way from a decode thread to the encoder: its bytes, or
3399-struct Yuv {3487+/// the GPU buffer they are still in.
3400- y: Vec<u8>,3488+enum Yuv {
3401- u: Vec<u8>,3489+ Pixels {
3402- v: Vec<u8>,3490+ y: Vec<u8>,
3403- width: u32,3491+ u: Vec<u8>,
3404- height: u32,3492+ v: Vec<u8>,
3493+ width: u32,
3494+ height: u32,
3495+ },
3496+ /// Never read back and never copied: a DRM-PRIME handle the encoder imports
3497+ /// on the other side of the channel. Sending it is sending an integer, and
3498+ /// what keeps the buffer from being decoded over is the channel's own depth
3499+ /// (see [`crate::hw::HwSession::next_frame_dma`]).
3500+ Dma(DmaFrame),
3501+}
3502+
3503+impl Yuv {
3504+ /// The decoder's own buffer copied out, which is what it costs to hand a
3505+ /// picture to another thread when the pixels have to travel.
3506+ fn pixels(y: &[u8], u: &[u8], v: &[u8], width: u32, height: u32) -> Self {
3507+ Self::Pixels {
3508+ y: y.to_vec(),
3509+ u: u.to_vec(),
3510+ v: v.to_vec(),
3511+ width,
3512+ height,
3513+ }
3514+ }
3515+}
3516+
3517+/// One picture as the export loop sees it: planes to grade and place, or a
3518+/// buffer that goes straight into the encoder.
3519+enum Frame<'a> {
3520+ Pixels(&'a [u8], &'a [u8], &'a [u8], u32, u32),
3521+ Dma(&'a DmaFrame),
3405 }3522 }
3406 3523
3407 impl ClipDecoder {3524 impl ClipDecoder {
3408- fn open(path: &Path, start_frame: u32) -> crate::Result<Self> {3525+ fn open(path: &Path, start_frame: u32, want: Option<DmaWant>) -> crate::Result<Self> {
3409 // Before either decoder: an image is not a stream, so `start_frame`3526 // Before either decoder: an image is not a stream, so `start_frame`
3410 // means nothing to it -- every frame of a still span is the same3527 // means nothing to it -- every frame of a still span is the same
3411 // picture, which is what playback shows for it too.3528 // picture, which is what playback shows for it too.
@@ -3416,7 +3533,7 @@ impl ClipDecoder {
3416 let (tx, frames) = sync_channel(2);3533 let (tx, frames) = sync_channel(2);
3417 let handle = thread::Builder::new()3534 let handle = thread::Builder::new()
3418 .name("export-decode".into())3535 .name("export-decode".into())
3419- .spawn(move || decode_stream(&path, start_frame, &tx))?;3536+ .spawn(move || decode_stream(&path, start_frame, want, &tx))?;
3420 Ok(Self::Streamed(Streamed {3537 Ok(Self::Streamed(Streamed {
3421 frames,3538 frames,
3422 _thread: DecodeThread(Some(handle)),3539 _thread: DecodeThread(Some(handle)),
@@ -3425,22 +3542,26 @@ impl ClipDecoder {
3425 }))3542 }))
3426 }3543 }
3427 3544
3428- /// The next picture as tightly packed I420, borrowed until the call after.3545+ /// The next picture, borrowed until the call after -- as tightly packed
3429- fn next(&mut self) -> crate::Result<Option<(&[u8], &[u8], &[u8], u32, u32)>> {3546+ /// I420, or as the GPU buffer the decoder wrote it into.
3547+ fn next(&mut self) -> crate::Result<Option<Frame<'_>>> {
3430 match self {3548 match self {
3431- Self::Still(still) => Ok(Some(still.picture())),3549+ Self::Still(still) => {
3550+ let (y, u, v, width, height) = still.picture();
3551+ Ok(Some(Frame::Pixels(y, u, v, width, height)))
3552+ }
3432 Self::Streamed(stream) if stream.ended => Ok(None),3553 Self::Streamed(stream) if stream.ended => Ok(None),
3433 Self::Streamed(stream) => match stream.frames.recv() {3554 Self::Streamed(stream) => match stream.frames.recv() {
3434- Ok(Ok(Some(frame))) => {3555+ Ok(Ok(Some(frame))) => Ok(Some(match stream.current.insert(frame) {
3435- let frame = stream.current.insert(frame);3556+ Yuv::Pixels {
3436- Ok(Some((3557+ y,
3437- &frame.y,3558+ u,
3438- &frame.u,3559+ v,
3439- &frame.v,3560+ width,
3440- frame.width,3561+ height,
3441- frame.height,3562+ } => Frame::Pixels(y, u, v, *width, *height),
3442- )))3563+ Yuv::Dma(dma) => Frame::Dma(dma),
3443- }3564+ })),
3444 // The decoder said end of stream in as many words -- a source3565 // The decoder said end of stream in as many words -- a source
3445 // shorter than the clip that names it, which the span loop ends3566 // shorter than the clip that names it, which the span loop ends
3446 // gracefully on.3567 // gracefully on.
@@ -3473,7 +3594,12 @@ impl ClipDecoder {
3473 /// error, or the `Ok(None)` that *is* end of stream. Closing the channel is not3594 /// error, or the `Ok(None)` that *is* end of stream. Closing the channel is not
3474 /// one of them -- a silent close is a panicked thread, and the receiver treats3595 /// one of them -- a silent close is a panicked thread, and the receiver treats
3475 /// it as the failure it is rather than as a source that ran out.3596 /// it as the failure it is rather than as a source that ran out.
3476-fn decode_stream(path: &Path, start_frame: u32, tx: &SyncSender<crate::Result<Option<Yuv>>>) {3597+fn decode_stream(
3598+ path: &Path,
3599+ start_frame: u32,
3600+ want: Option<DmaWant>,
3601+ tx: &SyncSender<crate::Result<Option<Yuv>>>,
3602+) {
3477 let opened = match forced("VE_SW") {3603 let opened = match forced("VE_SW") {
3478 false => HwSession::open_at(path, start_frame).map(Pictures::Hw),3604 false => HwSession::open_at(path, start_frame).map(Pictures::Hw),
3479 true => None,3605 true => None,
@@ -3489,17 +3615,8 @@ fn decode_stream(path: &Path, start_frame: u32, tx: &SyncSender<crate::Result<Op
3489 },3615 },
3490 };3616 };
3491 loop {3617 loop {
3492- // Copied out of the decoder's own buffer, which it reuses for the next3618+ let frame = match decoder.next(want) {
3493- // picture: one 3 MB memcpy per frame against the decode and the encode3619+ Ok(Some(frame)) => frame,
3494- // it lets overlap.
3495- let frame = match decoder.next() {
3496- Ok(Some((y, u, v, width, height))) => Yuv {
3497- y: y.to_vec(),
3498- u: u.to_vec(),
3499- v: v.to_vec(),
3500- width,
3501- height,
3502- },
3503 Ok(None) => {3620 Ok(None) => {
3504 let _ = tx.send(Ok(None));3621 let _ = tx.send(Ok(None));
3505 return;3622 return;
@@ -3524,15 +3641,29 @@ enum Pictures {
3524 }3641 }
3525 3642
3526 impl Pictures {3643 impl Pictures {
3527- fn next(&mut self) -> crate::Result<Option<(&[u8], &[u8], &[u8], u32, u32)>> {3644+ /// The next picture, owned, ready to cross the channel. `want` is what the
3528- match self {3645+ /// export's encoder can read straight off the GPU: where the hardware
3529- Self::Hw(hw) => hw.next_frame(),3646+ /// decoder can hand such a buffer over there is no copy here at all, and
3530- Self::Sw(sw) => {3647+ /// everything else is the 3 MB memcpy out of the decoder's own buffer that
3648+ /// buys the decode and the encode their overlap.
3649+ fn next(&mut self, want: Option<DmaWant>) -> crate::Result<Option<Yuv>> {
3650+ match (self, want) {
3651+ (Self::Hw(hw), Some(want)) => Ok(match hw.next_frame_dma(want)? {
3652+ Some(HwPicture::Dma(dma)) => Some(Yuv::Dma(dma)),
3653+ Some(HwPicture::Pixels(y, u, v, width, height)) => {
3654+ Some(Yuv::pixels(y, u, v, width, height))
3655+ }
3656+ None => None,
3657+ }),
3658+ (Self::Hw(hw), None) => Ok(hw
3659+ .next_frame()?
3660+ .map(|(y, u, v, width, height)| Yuv::pixels(y, u, v, width, height))),
3661+ (Self::Sw(sw), _) => {
3531 if !sw.advance()? {3662 if !sw.advance()? {
3532 return Ok(None);3663 return Ok(None);
3533 }3664 }
3534 let frame = sw.frame.as_ref().expect("advance stored a picture");3665 let frame = sw.frame.as_ref().expect("advance stored a picture");
3535- Ok(Some((3666+ Ok(Some(Yuv::pixels(
3536 &frame.y,3667 &frame.y,
3537 &frame.u,3668 &frame.u,
3538 &frame.v,3669 &frame.v,
@@ -3633,9 +3764,9 @@ mod tests {
3633 panic!("decoder died");3764 panic!("decoder died");
3634 });3765 });
3635 let mut died = streamed(handle, frames);3766 let mut died = streamed(handle, frames);
3636- let e = died3767+ let Err(e) = died.next() else {
3637- .next()3768+ panic!("a silent death must fail the export, not end the clip")
3638- .expect_err("a silent death must fail the export, not end the clip");3769+ };
3639 assert!(3770 assert!(
3640 e.to_string().contains("without a picture or a reason"),3771 e.to_string().contains("without a picture or a reason"),
3641 "{e}"3772 "{e}"
crates/engine/src/hw.rsmodified+200 -2
@@ -16,6 +16,7 @@
16 //! honest [`crate::demux::Codec::needs_plugin`] refusal covers both.16 //! honest [`crate::demux::Codec::needs_plugin`] refusal covers both.
17 17
18 use std::ffi::{CString, c_char, c_void};18 use std::ffi::{CString, c_char, c_void};
19+use std::os::fd::FromRawFd;
19 use std::path::{Path, PathBuf};20 use std::path::{Path, PathBuf};
20 use std::sync::OnceLock;21 use std::sync::OnceLock;
21 22
@@ -62,6 +63,87 @@ impl Default for VhFrame {
62 }63 }
63 }64 }
64 65
66+/// One decoded picture *left on the GPU*: a DRM-PRIME buffer the encoder
67+/// imports instead of the caller reading the pixels back and writing them out
68+/// again. All integers, so it crosses a channel to the encoding thread the way
69+/// a picture's bytes used to.
70+///
71+/// The `fd` belongs to whoever holds this: the plugin hands ownership over with
72+/// the descriptor and [`DmaFrame`] closes it. What it does *not* own is the
73+/// buffer's contents -- the decode session keeps the picture from being decoded
74+/// over for a few frames only (see `vh_next_frame_dma`), which is why nothing
75+/// but the export's two-deep decode channel may sit between the two calls.
76+#[repr(C)]
77+#[derive(Clone, Copy)]
78+pub struct VhDma {
79+ /// One DRM-PRIME handle per plane, luma then chroma -- which is how the
80+ /// driver hands its own surfaces out (radeonsi exports an NV12 surface as
81+ /// *two* objects into one allocation, measured 2026-08-13), and describing
82+ /// it any other way is guessing at what the second one means. `fd[0]` below
83+ /// zero says this picture is not on the GPU at all; `fd[1]` below zero says
84+ /// both planes live in the first object.
85+ pub fd: [i32; 2],
86+ /// `NV12` and nothing else, today.
87+ pub fourcc: u32,
88+ /// DRM format modifier of the buffer, passed through to the import.
89+ pub modifier: u64,
90+ /// The surface's own size, which is the picture's rounded up to whatever
91+ /// the codec codes in -- what an encoder has to agree with, sample for
92+ /// sample, before it can read this buffer at all.
93+ pub coded_width: u32,
94+ pub coded_height: u32,
95+ /// The picture inside it.
96+ pub width: u32,
97+ pub height: u32,
98+ /// Luma then chroma, each inside its own object above.
99+ pub offset: [u32; 2],
100+ pub stride: [u32; 2],
101+}
102+
103+impl Default for VhDma {
104+ fn default() -> Self {
105+ Self {
106+ fd: [-1, -1],
107+ fourcc: 0,
108+ modifier: 0,
109+ coded_width: 0,
110+ coded_height: 0,
111+ width: 0,
112+ height: 0,
113+ offset: [0; 2],
114+ stride: [0; 2],
115+ }
116+ }
117+}
118+
119+/// A [`VhDma`] with its file descriptor owned: dropping it closes the handle,
120+/// which is the only thing this side of the ABI has to get right.
121+pub struct DmaFrame(VhDma);
122+
123+impl DmaFrame {
124+ pub fn width(&self) -> u32 {
125+ self.0.width
126+ }
127+
128+ pub fn height(&self) -> u32 {
129+ self.0.height
130+ }
131+}
132+
133+impl Drop for DmaFrame {
134+ fn drop(&mut self) {
135+ for fd in self.0.fd {
136+ if fd >= 0 {
137+ // SAFETY: the plugin transferred these descriptors to us with
138+ // the frame and nothing else owns them; `DmaFrame` is not
139+ // `Clone`, and the two are distinct handles even where they
140+ // name one allocation.
141+ drop(unsafe { std::os::fd::OwnedFd::from_raw_fd(fd) });
142+ }
143+ }
144+ }
145+}
146+
65 /// What *this machine* takes, as far as the plugin implements it: one bit per147 /// What *this machine* takes, as far as the plugin implements it: one bit per
66 /// codec ([`CAP_H264`] and its three neighbours) in each mask, so a caller reads148 /// codec ([`CAP_H264`] and its three neighbours) in each mask, so a caller reads
67 /// "H.264 decodes and encodes here, HEVC only decodes" off three `u32`s.149 /// "H.264 decodes and encodes here, HEVC only decodes" off three `u32`s.
@@ -90,6 +172,12 @@ struct Plugin {
90 open_at: unsafe extern "C" fn(*const c_char, u32) -> *mut c_void,172 open_at: unsafe extern "C" fn(*const c_char, u32) -> *mut c_void,
91 meta: unsafe extern "C" fn(*mut c_void, *mut VhMeta) -> i32,173 meta: unsafe extern "C" fn(*mut c_void, *mut VhMeta) -> i32,
92 next_frame: unsafe extern "C" fn(*mut c_void, *mut VhFrame) -> i32,174 next_frame: unsafe extern "C" fn(*mut c_void, *mut VhFrame) -> i32,
175+ /// The zero-copy door, and optional for the same reason [`Plugin::caps`] is:
176+ /// a plugin built before it decodes exactly as it did, through the read-back
177+ /// above.
178+ next_frame_dma: Option<
179+ unsafe extern "C" fn(*mut c_void, *mut VhFrame, *mut VhDma, u32, u32, u32, u32) -> i32,
180+ >,
93 close: unsafe extern "C" fn(*mut c_void),181 close: unsafe extern "C" fn(*mut c_void),
94 /// The capability query, and the one symbol of this table that may be182 /// The capability query, and the one symbol of this table that may be
95 /// missing: a plugin built before it exports the four above and not this,183 /// missing: a plugin built before it exports the four above and not this,
@@ -134,6 +222,7 @@ fn load() -> Option<Plugin> {
134 open_at: *lib.get(b"vh_open_at\0").ok()?,222 open_at: *lib.get(b"vh_open_at\0").ok()?,
135 meta: *lib.get(b"vh_meta\0").ok()?,223 meta: *lib.get(b"vh_meta\0").ok()?,
136 next_frame: *lib.get(b"vh_next_frame\0").ok()?,224 next_frame: *lib.get(b"vh_next_frame\0").ok()?,
225+ next_frame_dma: lib.get(b"vh_next_frame_dma\0").ok().map(|s| *s),
137 close: *lib.get(b"vh_close\0").ok()?,226 close: *lib.get(b"vh_close\0").ok()?,
138 caps: lib.get(b"vh_caps\0").ok().map(|s| *s),227 caps: lib.get(b"vh_caps\0").ok().map(|s| *s),
139 seek: lib.get(b"vh_seek\0").ok().map(|s| *s),228 seek: lib.get(b"vh_seek\0").ok().map(|s| *s),
@@ -241,6 +330,55 @@ impl HwSession {
241 1 => {}330 1 => {}
242 code => return Err(format!("hardware decode failed (code {code})").into()),331 code => return Err(format!("hardware decode failed (code {code})").into()),
243 }332 }
333+ self.pixels(&frame).map(Some)
334+ }
335+
336+ /// The next picture *without reading it back* where the caller's encoder can
337+ /// take the buffer the decoder wrote into -- which is what `want` describes,
338+ /// down to the coded size, because an encoder reads a surface of its own
339+ /// shape or none at all.
340+ ///
341+ /// Anything the plugin cannot hand over that way comes back as pixels
342+ /// instead ([`HwPicture::Pixels`]), so a mismatch costs the read-back it
343+ /// always cost and never a frame. A plugin too old to know the door exists
344+ /// is the same answer.
345+ ///
346+ /// The buffer behind a [`DmaFrame`] is the decoder's, held out of its pool
347+ /// for a few pictures only: encode it before asking this for a few more.
348+ pub fn next_frame_dma(&mut self, want: DmaWant) -> crate::Result<Option<HwPicture<'_>>> {
349+ let Some(next_dma) = self.plugin.next_frame_dma else {
350+ return Ok(self.next_frame()?.map(|(y, u, v, w, h)| HwPicture::Pixels(y, u, v, w, h)));
351+ };
352+ let mut frame = VhFrame::default();
353+ let mut dma = VhDma::default();
354+ // SAFETY: as `next_frame`, plus a writable descriptor whose `fd` the
355+ // plugin either hands us ownership of or leaves at -1.
356+ let code = unsafe {
357+ next_dma(
358+ self.handle,
359+ &mut frame,
360+ &mut dma,
361+ want.coded_width,
362+ want.coded_height,
363+ want.width,
364+ want.height,
365+ )
366+ };
367+ match code {
368+ 0 => return Ok(None),
369+ 1 => {}
370+ code => return Err(format!("hardware decode failed (code {code})").into()),
371+ }
372+ if dma.fd[0] >= 0 {
373+ return Ok(Some(HwPicture::Dma(DmaFrame(dma))));
374+ }
375+ let (y, u, v, w, h) = self.pixels(&frame)?;
376+ Ok(Some(HwPicture::Pixels(y, u, v, w, h)))
377+ }
378+
379+ /// The plugin's plane pointers as slices, checked against the strides it
380+ /// declares -- the one shape this side takes.
381+ fn pixels(&self, frame: &VhFrame) -> crate::Result<(&[u8], &[u8], &[u8], u32, u32)> {
244 let (w, h) = (frame.width as usize, frame.height as usize);382 let (w, h) = (frame.width as usize, frame.height as usize);
245 let (cw, ch) = (w.div_ceil(2), h.div_ceil(2));383 let (cw, ch) = (w.div_ceil(2), h.div_ceil(2));
246 if frame.y.is_null()384 if frame.y.is_null()
@@ -255,17 +393,34 @@ impl HwSession {
255 // SAFETY: plane pointers are non-null and the strides just checked above393 // SAFETY: plane pointers are non-null and the strides just checked above
256 // pin each plane's length; the borrow ends before the next call.394 // pin each plane's length; the borrow ends before the next call.
257 unsafe {395 unsafe {
258- Ok(Some((396+ Ok((
259 std::slice::from_raw_parts(frame.y, w * h),397 std::slice::from_raw_parts(frame.y, w * h),
260 std::slice::from_raw_parts(frame.u, cw * ch),398 std::slice::from_raw_parts(frame.u, cw * ch),
261 std::slice::from_raw_parts(frame.v, cw * ch),399 std::slice::from_raw_parts(frame.v, cw * ch),
262 frame.width,400 frame.width,
263 frame.height,401 frame.height,
264- )))402+ ))
265 }403 }
266 }404 }
267 }405 }
268 406
407+/// What an encoder needs a decoded buffer to look like before it can read it
408+/// without a copy: the surface's coded size and the picture inside it.
409+#[derive(Clone, Copy)]
410+pub struct DmaWant {
411+ pub coded_width: u32,
412+ pub coded_height: u32,
413+ pub width: u32,
414+ pub height: u32,
415+}
416+
417+/// One picture out of [`HwSession::next_frame_dma`]: still on the GPU, or read
418+/// back like every other frame.
419+pub enum HwPicture<'a> {
420+ Pixels(&'a [u8], &'a [u8], &'a [u8], u32, u32),
421+ Dma(DmaFrame),
422+}
423+
269 impl Drop for HwSession {424 impl Drop for HwSession {
270 fn drop(&mut self) {425 fn drop(&mut self) {
271 // SAFETY: `handle` came from `vh_open_at` and is closed exactly once.426 // SAFETY: `handle` came from `vh_open_at` and is closed exactly once.
@@ -291,6 +446,12 @@ struct EncPlugin {
291 open_hevc: Option<extern "C" fn(u32, u32, u32, u32, u64) -> *mut c_void>,446 open_hevc: Option<extern "C" fn(u32, u32, u32, u32, u64) -> *mut c_void>,
292 frame:447 frame:
293 unsafe extern "C" fn(*mut c_void, *const VhFrame, i32, *mut *const u8, *mut usize) -> i32,448 unsafe extern "C" fn(*mut c_void, *const VhFrame, i32, *mut *const u8, *mut usize) -> i32,
449+ /// The zero-copy pair, both optional together: an older plugin exports
450+ /// neither and every picture reaches it as bytes, which is what it always
451+ /// did.
452+ dma_geometry: Option<unsafe extern "C" fn(*mut c_void, *mut u32, *mut u32) -> i32>,
453+ frame_dma:
454+ Option<unsafe extern "C" fn(*mut c_void, *const VhDma, i32, *mut *const u8, *mut usize) -> i32>,
294 drain: unsafe extern "C" fn(*mut c_void, *mut *const u8, *mut usize) -> i32,455 drain: unsafe extern "C" fn(*mut c_void, *mut *const u8, *mut usize) -> i32,
295 close: unsafe extern "C" fn(*mut c_void),456 close: unsafe extern "C" fn(*mut c_void),
296 // Never dropped (lives in a static), so the fn pointers above stay valid.457 // Never dropped (lives in a static), so the fn pointers above stay valid.
@@ -317,6 +478,8 @@ fn load_enc() -> Option<EncPlugin> {
317 open_av1: lib.get(b"vh_enc_av1_open\0").ok().map(|s| *s),478 open_av1: lib.get(b"vh_enc_av1_open\0").ok().map(|s| *s),
318 open_hevc: lib.get(b"vh_enc_hevc_open\0").ok().map(|s| *s),479 open_hevc: lib.get(b"vh_enc_hevc_open\0").ok().map(|s| *s),
319 frame: *lib.get(b"vh_enc_frame\0").ok()?,480 frame: *lib.get(b"vh_enc_frame\0").ok()?,
481+ dma_geometry: lib.get(b"vh_enc_dma_geometry\0").ok().map(|s| *s),
482+ frame_dma: lib.get(b"vh_enc_frame_dma\0").ok().map(|s| *s),
320 drain: *lib.get(b"vh_enc_drain\0").ok()?,483 drain: *lib.get(b"vh_enc_drain\0").ok()?,
321 close: *lib.get(b"vh_enc_close\0").ok()?,484 close: *lib.get(b"vh_enc_close\0").ok()?,
322 _lib: lib,485 _lib: lib,
@@ -450,6 +613,41 @@ impl HwEncoder {
450 })613 })
451 }614 }
452 615
616+ /// What a decoded buffer must look like to reach this encoder without a
617+ /// copy -- the surface size it codes in, plus the picture it was opened for
618+ /// -- or `None` where the plugin has no zero-copy door at all.
619+ pub fn dma_want(&self, width: u32, height: u32) -> Option<DmaWant> {
620+ let geometry = self.plugin.dma_geometry?;
621+ self.plugin.frame_dma?;
622+ let (mut coded_width, mut coded_height) = (0u32, 0u32);
623+ // SAFETY: `handle` is live and both destinations are writable.
624+ if unsafe { geometry(self.handle, &mut coded_width, &mut coded_height) } != 1 {
625+ return None;
626+ }
627+ Some(DmaWant {
628+ coded_width,
629+ coded_height,
630+ width,
631+ height,
632+ })
633+ }
634+
635+ /// Feeds one picture the decoder left on the GPU. Same answer and same
636+ /// lifetime rule as [`HwEncoder::encode`]; an error here is a real one, the
637+ /// caller having asked [`HwEncoder::dma_want`] what this seat takes before
638+ /// the decoder handed the buffer over.
639+ pub fn encode_dma(&mut self, dma: &DmaFrame, force_key: bool) -> crate::Result<Option<&[u8]>> {
640+ let Some(frame_dma) = self.plugin.frame_dma else {
641+ return Err("hardware encoder has no zero-copy path".into());
642+ };
643+ let desc = dma.0;
644+ // SAFETY: `handle` is live and `desc` outlives the call; the buffer it
645+ // names is the decode session's, held for the caller by contract.
646+ self.take(|_, handle, out, out_len| unsafe {
647+ frame_dma(handle, &desc, force_key as i32, out, out_len)
648+ })
649+ }
650+
453 /// Flushes the encoder; call until it returns `Ok(None)`. Same lifetime rule651 /// Flushes the encoder; call until it returns `Ok(None)`. Same lifetime rule
454 /// as [`HwEncoder::encode`].652 /// as [`HwEncoder::encode`].
455 pub fn drain(&mut self) -> crate::Result<Option<&[u8]>> {653 pub fn drain(&mut self) -> crate::Result<Option<&[u8]>> {
crates/engine/tests/hw_encode.rsmodified+77 -1
@@ -14,7 +14,7 @@
14 14
15 use std::time::{Duration, Instant};15 use std::time::{Duration, Instant};
16 16
17-use engine::hw::{HwEncoder, HwSession};17+use engine::hw::{HwEncoder, HwPicture, HwSession};
18 18
19 const FPS: u32 = 30;19 const FPS: u32 = 30;
20 const BITRATE: u64 = 4_000_000;20 const BITRATE: u64 = 4_000_000;
@@ -140,6 +140,82 @@ fn round_trips_unaligned_dimensions() {
140 );140 );
141 }141 }
142 142
143+/// The zero-copy path: a picture the hardware decoder wrote goes into the
144+/// hardware encoder as the buffer it was decoded into, never read back and never
145+/// written out again -- which is what makes an export of an untouched clip cost
146+/// no `vaGetImage`, no colour conversion and no upload per frame.
147+///
148+/// Two things are checked and the second is the one that matters. That the
149+/// buffers are handed over *at all* (a driver whose export the plugin refuses
150+/// falls back to pixels, silently and correctly, which would make a speed claim
151+/// a lie). And that what came out is what went in: the encoded stream is decoded
152+/// in software and compared against the same file decoded through the read-back
153+/// path, so a wrong plane offset, a swapped object or an unsynchronised surface
154+/// -- the ways an imported buffer goes wrong -- fails here instead of shipping
155+/// as a garbled export.
156+#[test]
157+#[ignore = "needs libengine_hw.so and a VA-API driver with H.264 decode and encode"]
158+fn a_decoded_buffer_is_encoded_without_ever_being_read_back() {
159+ const FRAMES: usize = 24;
160+ let asset =
161+ std::path::PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("../../assets/test_baseline.mp4");
162+ let (width, height) = (1280u32, 720u32);
163+ let Some(mut encoder) = HwEncoder::open(width, height, FPS, 1, BITRATE) else {
164+ println!("no hardware encoder here -- skipping");
165+ return;
166+ };
167+ let Some(want) = encoder.dma_want(width, height) else {
168+ panic!("a hardware encoder that takes no imported buffer at all");
169+ };
170+ let mut session = HwSession::open(&asset).expect("hardware decode of the fixture");
171+
172+ let mut stream = Vec::new();
173+ let mut buffers = 0;
174+ for index in 0..FRAMES {
175+ match session.next_frame_dma(want).expect("hardware decode") {
176+ Some(HwPicture::Dma(dma)) => {
177+ assert_eq!((dma.width(), dma.height()), (width, height), "frame {index}");
178+ buffers += 1;
179+ if let Some(au) = encoder.encode_dma(&dma, false).expect("encode") {
180+ stream.extend_from_slice(au);
181+ }
182+ }
183+ Some(HwPicture::Pixels(..)) => panic!("frame {index} was read back after all"),
184+ None => panic!("the fixture ran out at frame {index}"),
185+ }
186+ }
187+ while let Some(au) = encoder.drain().expect("drain") {
188+ stream.extend_from_slice(au);
189+ }
190+ assert_eq!(buffers, FRAMES, "every picture came over as a buffer");
191+
192+ // The same file down the path this one exists to avoid, which is the only
193+ // honest reference for "the encoder read the right pixels".
194+ let mut reference = HwSession::open(&asset).expect("hardware decode of the fixture");
195+ let coded = decode(&stream);
196+ assert_eq!(coded.len(), FRAMES, "decoded picture count");
197+ for (index, frame) in coded.iter().enumerate() {
198+ let (y, u, v, w, h) = reference
199+ .next_frame()
200+ .expect("read-back decode")
201+ .expect("the fixture is longer than this");
202+ assert_eq!((w, h), (width, height), "frame {index}");
203+ for (plane, (got, want)) in [(&frame.y, y), (&frame.u, u), (&frame.v, v)]
204+ .iter()
205+ .enumerate()
206+ {
207+ // Lossy CBR against the source picture: the same tolerance the
208+ // synthetic round trip above uses, and nowhere near what a swapped
209+ // plane or a stale surface would cost.
210+ let diff = mean_abs_diff(got, want);
211+ assert!(
212+ diff < 6.0,
213+ "frame {index} plane {plane} drifted by {diff:.2}"
214+ );
215+ }
216+ }
217+}
218+
143 /// Decode and encode resolve through two independent symbol tables, so an219 /// Decode and encode resolve through two independent symbol tables, so an
144 /// encoder that cannot load must not cost us the decoder (and vice versa).220 /// encoder that cannot load must not cost us the decoder (and vice versa).
145 ///221 ///