forge
Explore
Log in

Don't you dare go Hollow

The picture is written where the last one is already coded

Browse files at this commit

01fb8ce71599995362958e7f8e1a5e1ede7936e8Ahmet Kaan GümüşParent: 267d45b
  • perf
    • the picture is written where the last one is already coded
Show full message
⚡ perf(engine-hw): the picture is written where the last one is already coded

A hardware export spent four fifths of its per-frame time putting the picture
*into* the encoder, not encoding it. Two things were paying for that, and both
are gone:

The NV12 rows were interleaved a byte at a time straight into the mapped buffer
object, which is write-combining memory -- every pair of stores flushed a
partial buffer. The row is built in ordinary memory now and copied across in
one piece: 8.2 ms a picture became 6.7 ms at 1080p (measured on radeonsi by
alternating the two paths frame by frame inside one export, so the machine's
load weighed on both).

And there was one input buffer, so the GPU had to finish coding a picture
before the next could be written into it -- the CPU's interleave and the GPU's
encode ran end to end. There are two now, and the access unit collected after a
submit is the *previous* picture's: the GPU codes while the caller interleaves.

Per-frame encode cost, minimum over 719 frames of the same film span, three
interleaved runs each: 9.4/9.4/10.2 ms before, 6.9/7.3/7.4 ms after -- 27% off
the only stage that was costing anything.

The file is the same file: a ten-second span of the same source exported
through both plugins is byte-identical (6,379,699 bytes, cmp clean), ffmpeg
-v error empty, and tests/hw_encode.rs round trips all three ways.
crates/engine-hw/src/lib.rsmodified+102 -31
@@ -771,11 +771,19 @@ fn fix_slice_nal_headers(au: &mut [u8]) {
771771
772772 /// One hardware H.264 encode session.
773773 ///
774-/// Input goes through a single reusable NV12 buffer object: the caller's I420
775-/// planes are interleaved into it and the encoder imports it as a VA surface.
776-/// Reuse is safe because the encoder runs in blocking mode and every entry
777-/// point polls it before returning, so the GPU is finished with the buffer
778-/// before the next picture is written into it.
774+/// Input goes through [`ENC_DEPTH`] reusable NV12 buffer objects: the caller's
775+/// I420 planes are interleaved into the next one and the encoder imports it as a
776+/// VA surface. Reuse is safe because a buffer is only written again once the
777+/// access unit coded *from* it has been polled back -- the encoder runs in
778+/// blocking mode and a coded unit in hand means the GPU has finished reading its
779+/// input -- and [`EncSession::encode`] holds exactly that many pictures in
780+/// flight, no more.
781+///
782+/// **Why more than one.** With a single buffer the picture had to be coded
783+/// before the next one could be written into it, so a frame cost the CPU's
784+/// interleave *plus* the GPU's encode end to end (6.7 ms + 2.5 ms at 1080p on
785+/// radeonsi, measured 2026-08-13). With two, the interleave of the next picture
786+/// runs while the GPU codes this one and the frame costs the longer of them.
779787 struct EncSession {
780788 /// Boxed because the three codecs are three types and everything past
781789 /// `encode` is the same trait: one session type serves them all, which is
@@ -786,9 +794,15 @@ struct EncSession {
786794 /// differs: the H.264 driver leaves a *NAL* header byte at zero, and
787795 /// neither an HEVC access unit nor an AV1 temporal unit has that one.
788796 codec: EncCodec,
789- /// Owns the DRM node the buffer object below was allocated from.
797+ /// Owns the DRM node the buffer objects below were allocated from.
790798 _gbm: gbm::Device<std::fs::File>,
791- frame: GenericDmaVideoFrame,
799+ /// [`ENC_DEPTH`] input buffers, used round-robin.
800+ frames: Vec<GenericDmaVideoFrame>,
801+ /// Which of them the next picture is written into.
802+ slot: usize,
803+ /// Pictures submitted whose access unit has not been polled back yet, which
804+ /// is what says whether the buffer about to be written is free.
805+ in_flight: usize,
792806 layout: FrameLayout,
793807 /// Macroblock-aligned surface size; `width`/`height` are what is encoded.
794808 coded: Resolution,
@@ -801,8 +815,17 @@ struct EncSession {
801815 ready: VecDeque<Vec<u8>>,
802816 /// The access unit currently handed out, kept alive until the next call.
803817 out: Vec<u8>,
818+ /// One padded output row, staged in ordinary memory and copied across whole
819+ /// -- [`EncSession::upload`] says why.
820+ row: Vec<u8>,
804821 }
805822
823+/// How many pictures may be in the encoder at once. Two is what it takes to
824+/// overlap the CPU's interleave with the GPU's encode; more would buy nothing,
825+/// since the interleave is the longer of the two and a third buffer would only
826+/// hold a picture waiting for a lane that is never idle.
827+const ENC_DEPTH: usize = 2;
828+
806829 /// Which codec an [`EncSession`] was opened for. Decided once, at the open, the
807830 /// way the H.264 seat's dimensions are -- everything after it is one trait.
808831 #[derive(Clone, Copy, PartialEq, Eq)]
@@ -980,13 +1003,18 @@ impl EncSession {
9801003 };
9811004 // Allocated at the aligned size, so the buffer's pitch is never smaller
9821005 // than a padded row.
983- let frame = alloc_nv12(&gbm, coded, false).ok()?;
984- let layout = nv12_layout(coded, frame.get_plane_pitch()[0], false);
1006+ let frames: Vec<_> = (0..ENC_DEPTH)
1007+ .map(|_| alloc_nv12(&gbm, coded, false))
1008+ .collect::<Result<_, _>>()
1009+ .ok()?;
1010+ let layout = nv12_layout(coded, frames[0].get_plane_pitch()[0], false);
9851011 Some(Self {
9861012 encoder,
9871013 codec,
9881014 _gbm: gbm,
989- frame,
1015+ frames,
1016+ slot: 0,
1017+ in_flight: 0,
9901018 layout,
9911019 coded,
9921020 width: width as usize,
@@ -995,21 +1023,38 @@ impl EncSession {
9951023 drained: false,
9961024 ready: VecDeque::new(),
9971025 out: Vec::new(),
1026+ row: Vec::new(),
9981027 })
9991028 }
10001029
1001- /// Interleaves one packed I420 picture into the NV12 input buffer.
1030+ /// Interleaves one packed I420 picture into the NV12 input buffer `slot`.
1031+ ///
1032+ /// **Row at a time, through ordinary memory.** The mapping below is the
1033+ /// GPU's own buffer, which is write-combining: a store of a byte or two
1034+ /// costs a partial-buffer flush, while one `memcpy` of a whole row costs a
1035+ /// burst. Interleaving the chroma directly into it was 8.2 ms a picture at
1036+ /// 1080p against 6.7 ms staged (measured 2026-08-13 on radeonsi, alternating
1037+ /// the two paths frame by frame inside one export so the machine's load
1038+ /// weighed on both), and the picture is four fifths of what a hardware
1039+ /// export spends per frame. The padding is written the same way and for the
1040+ /// same reason: it used to be a four-byte second store per row.
10021041 ///
10031042 /// # Safety
10041043 /// `src`'s planes must cover `height` (resp. `height / 2`) rows of their
10051044 /// declared stride.
1006- unsafe fn upload(&mut self, src: &VhFrame) -> Result<(), String> {
1045+ unsafe fn upload(&mut self, src: &VhFrame, slot: usize) -> Result<(), String> {
10071046 let (w, h) = (self.width, self.height);
10081047 let (cw, ch) = (w / 2, h / 2);
10091048 let (aw, ah) = (self.coded.width as usize, self.coded.height as usize);
1010- let pitch = self.frame.get_plane_pitch();
1011- let mapping = self.frame.map_mut()?;
1049+ // Two fields at once: the buffer is mapped for writing while the staging
1050+ // row is written into, and they are not the same field.
1051+ let Self { frames, row, .. } = self;
1052+ let frame = &mut frames[slot];
1053+ let pitch = frame.get_plane_pitch();
1054+ let mapping = frame.map_mut()?;
10121055 let planes = mapping.get();
1056+ row.resize(aw, 0);
1057+ let row_buf = &mut row[..];
10131058 {
10141059 let mut dst = planes[0].borrow_mut();
10151060 for row in 0..ah {
@@ -1017,11 +1062,11 @@ impl EncSession {
10171062 let s = unsafe {
10181063 std::slice::from_raw_parts(src.y.add(row.min(h - 1) * src.y_stride), w)
10191064 };
1020- let dst = &mut dst[row * pitch[0]..row * pitch[0] + aw];
1021- dst[..w].copy_from_slice(s);
1065+ row_buf[..w].copy_from_slice(s);
10221066 // Macroblock padding: replicate the edge rather than leave the
10231067 // buffer's garbage there, which would cost bitrate for nothing.
1024- dst[w..].fill(s[w - 1]);
1068+ row_buf[w..].fill(s[w - 1]);
1069+ dst[row * pitch[0]..row * pitch[0] + aw].copy_from_slice(row_buf);
10251070 }
10261071 }
10271072 let mut dst = planes[1].borrow_mut();
@@ -1034,14 +1079,14 @@ impl EncSession {
10341079 std::slice::from_raw_parts(src.v.add(src_row * src.v_stride), cw),
10351080 )
10361081 };
1037- let dst = &mut dst[row * pitch[1]..row * pitch[1] + aw];
10381082 for x in 0..cw {
1039- dst[2 * x] = u[x];
1040- dst[2 * x + 1] = v[x];
1083+ row_buf[2 * x] = u[x];
1084+ row_buf[2 * x + 1] = v[x];
10411085 }
10421086 for x in w..aw {
1043- dst[x] = dst[x - 2];
1087+ row_buf[x] = row_buf[x - 2];
10441088 }
1089+ dst[row * pitch[1]..row * pitch[1] + aw].copy_from_slice(row_buf);
10451090 }
10461091 Ok(())
10471092 }
@@ -1049,8 +1094,13 @@ impl EncSession {
10491094 /// # Safety
10501095 /// As [`EncSession::upload`].
10511096 unsafe fn encode(&mut self, src: &VhFrame, force_keyframe: bool) -> Result<(), String> {
1097+ // The buffer this picture is written into is the one whose own access
1098+ // unit is already in hand -- `in_flight` is held below [`ENC_DEPTH`] at
1099+ // the end of every call, so the round-robin never catches the GPU up.
1100+ let slot = self.slot;
10521101 // SAFETY: caller contract, forwarded.
1053- unsafe { self.upload(src)? };
1102+ unsafe { self.upload(src, slot)? };
1103+ self.slot = (self.slot + 1) % ENC_DEPTH;
10541104 let meta = FrameMetadata {
10551105 timestamp: self.timestamp,
10561106 layout: self.layout.clone(),
@@ -1058,23 +1108,44 @@ impl EncSession {
10581108 };
10591109 self.timestamp += 1;
10601110 self.encoder
1061- .encode(meta, self.frame.clone())
1111+ .encode(meta, self.frames[slot].clone())
10621112 .map_err(|e| e.to_string())?;
1063- self.collect()
1113+ self.in_flight += 1;
1114+ // ...and the picture before it is collected here rather than this one:
1115+ // that is the whole overlap, the GPU coding what was just submitted
1116+ // while the caller decodes and interleaves the next picture.
1117+ while self.in_flight >= ENC_DEPTH {
1118+ if !self.pull()? {
1119+ // Blocking mode: a picture accepted and no coded unit for the
1120+ // one before it means the encoder is not answering, and the
1121+ // next upload would overwrite a buffer the GPU still reads.
1122+ return Err("the encoder took a picture and returned nothing coded".into());
1123+ }
1124+ }
1125+ Ok(())
10641126 }
10651127
10661128 /// Moves every access unit the encoder has finished into `ready`.
10671129 fn collect(&mut self) -> Result<(), String> {
1068- while let Some(coded) = self.encoder.poll().map_err(|e| e.to_string())? {
1069- let mut au = coded.bitstream;
1070- if self.codec == EncCodec::H264 {
1071- fix_slice_nal_headers(&mut au);
1072- }
1073- self.ready.push_back(au);
1074- }
1130+ while self.pull()? {}
10751131 Ok(())
10761132 }
10771133
1134+ /// One finished access unit into `ready`; `false` where the encoder has
1135+ /// none to give.
1136+ fn pull(&mut self) -> Result<bool, String> {
1137+ let Some(coded) = self.encoder.poll().map_err(|e| e.to_string())? else {
1138+ return Ok(false);
1139+ };
1140+ let mut au = coded.bitstream;
1141+ if self.codec == EncCodec::H264 {
1142+ fix_slice_nal_headers(&mut au);
1143+ }
1144+ self.ready.push_back(au);
1145+ self.in_flight = self.in_flight.saturating_sub(1);
1146+ Ok(true)
1147+ }
1148+
10781149 /// Hands the oldest finished access unit to the caller, or reports that
10791150 /// there is none.
10801151 fn take(&mut self, out: *mut *const u8, out_len: *mut usize) -> i32 {