The picture is written where the last one is already coded
Browse files at this commit01fb8ce71599995362958e7f8e1a5e1ede7936e8Parent: 267d45b- perf
- the picture is written where the last one is already coded
1 changed file +102 -31
- crates/engine-hw/src/lib.rs +102 -31
crates/engine-hw/src/lib.rsmodified+102 -31
| @@ -771,11 +771,19 @@ fn fix_slice_nal_headers(au: &mut [u8]) { | |||
| 771 | 771 | ||
| 772 | /// One hardware H.264 encode session. | 772 | /// One hardware H.264 encode session. |
| 773 | /// | 773 | /// |
| 774 | -/// Input goes through a single reusable NV12 buffer object: the caller's I420 | 774 | +/// Input goes through [`ENC_DEPTH`] reusable NV12 buffer objects: the caller's |
| 775 | -/// planes are interleaved into it and the encoder imports it as a VA surface. | 775 | +/// I420 planes are interleaved into the next one and the encoder imports it as a |
| 776 | -/// Reuse is safe because the encoder runs in blocking mode and every entry | 776 | +/// VA surface. Reuse is safe because a buffer is only written again once the |
| 777 | -/// point polls it before returning, so the GPU is finished with the buffer | 777 | +/// access unit coded *from* it has been polled back -- the encoder runs in |
| 778 | -/// before the next picture is written into it. | 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. | ||
| 779 | struct EncSession { | 787 | struct EncSession { |
| 780 | /// Boxed because the three codecs are three types and everything past | 788 | /// Boxed because the three codecs are three types and everything past |
| 781 | /// `encode` is the same trait: one session type serves them all, which is | 789 | /// `encode` is the same trait: one session type serves them all, which is |
| @@ -786,9 +794,15 @@ struct EncSession { | |||
| 786 | /// differs: the H.264 driver leaves a *NAL* header byte at zero, and | 794 | /// differs: the H.264 driver leaves a *NAL* header byte at zero, and |
| 787 | /// neither an HEVC access unit nor an AV1 temporal unit has that one. | 795 | /// neither an HEVC access unit nor an AV1 temporal unit has that one. |
| 788 | codec: EncCodec, | 796 | 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. |
| 790 | _gbm: gbm::Device<std::fs::File>, | 798 | _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, | ||
| 792 | layout: FrameLayout, | 806 | layout: FrameLayout, |
| 793 | /// Macroblock-aligned surface size; `width`/`height` are what is encoded. | 807 | /// Macroblock-aligned surface size; `width`/`height` are what is encoded. |
| 794 | coded: Resolution, | 808 | coded: Resolution, |
| @@ -801,8 +815,17 @@ struct EncSession { | |||
| 801 | ready: VecDeque<Vec<u8>>, | 815 | ready: VecDeque<Vec<u8>>, |
| 802 | /// The access unit currently handed out, kept alive until the next call. | 816 | /// The access unit currently handed out, kept alive until the next call. |
| 803 | out: Vec<u8>, | 817 | 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>, | ||
| 804 | } | 821 | } |
| 805 | 822 | ||
| 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 | + | ||
| 806 | /// Which codec an [`EncSession`] was opened for. Decided once, at the open, the | 829 | /// Which codec an [`EncSession`] was opened for. Decided once, at the open, the |
| 807 | /// way the H.264 seat's dimensions are -- everything after it is one trait. | 830 | /// way the H.264 seat's dimensions are -- everything after it is one trait. |
| 808 | #[derive(Clone, Copy, PartialEq, Eq)] | 831 | #[derive(Clone, Copy, PartialEq, Eq)] |
| @@ -980,13 +1003,18 @@ impl EncSession { | |||
| 980 | }; | 1003 | }; |
| 981 | // Allocated at the aligned size, so the buffer's pitch is never smaller | 1004 | // Allocated at the aligned size, so the buffer's pitch is never smaller |
| 982 | // than a padded row. | 1005 | // than a padded row. |
| 983 | - let frame = alloc_nv12(&gbm, coded, false).ok()?; | 1006 | + let frames: Vec<_> = (0..ENC_DEPTH) |
| 984 | - let layout = nv12_layout(coded, frame.get_plane_pitch()[0], false); | 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); | ||
| 985 | Some(Self { | 1011 | Some(Self { |
| 986 | encoder, | 1012 | encoder, |
| 987 | codec, | 1013 | codec, |
| 988 | _gbm: gbm, | 1014 | _gbm: gbm, |
| 989 | - frame, | 1015 | + frames, |
| 1016 | + slot: 0, | ||
| 1017 | + in_flight: 0, | ||
| 990 | layout, | 1018 | layout, |
| 991 | coded, | 1019 | coded, |
| 992 | width: width as usize, | 1020 | width: width as usize, |
| @@ -995,21 +1023,38 @@ impl EncSession { | |||
| 995 | drained: false, | 1023 | drained: false, |
| 996 | ready: VecDeque::new(), | 1024 | ready: VecDeque::new(), |
| 997 | out: Vec::new(), | 1025 | out: Vec::new(), |
| 1026 | + row: Vec::new(), | ||
| 998 | }) | 1027 | }) |
| 999 | } | 1028 | } |
| 1000 | 1029 | ||
| 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. | ||
| 1002 | /// | 1041 | /// |
| 1003 | /// # Safety | 1042 | /// # Safety |
| 1004 | /// `src`'s planes must cover `height` (resp. `height / 2`) rows of their | 1043 | /// `src`'s planes must cover `height` (resp. `height / 2`) rows of their |
| 1005 | /// declared stride. | 1044 | /// declared stride. |
| 1006 | - unsafe fn upload(&mut self, src: &VhFrame) -> Result<(), String> { | 1045 | + unsafe fn upload(&mut self, src: &VhFrame, slot: usize) -> Result<(), String> { |
| 1007 | let (w, h) = (self.width, self.height); | 1046 | let (w, h) = (self.width, self.height); |
| 1008 | let (cw, ch) = (w / 2, h / 2); | 1047 | let (cw, ch) = (w / 2, h / 2); |
| 1009 | let (aw, ah) = (self.coded.width as usize, self.coded.height as usize); | 1048 | let (aw, ah) = (self.coded.width as usize, self.coded.height as usize); |
| 1010 | - let pitch = self.frame.get_plane_pitch(); | 1049 | + // Two fields at once: the buffer is mapped for writing while the staging |
| 1011 | - let mapping = self.frame.map_mut()?; | 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()?; | ||
| 1012 | let planes = mapping.get(); | 1055 | let planes = mapping.get(); |
| 1056 | + row.resize(aw, 0); | ||
| 1057 | + let row_buf = &mut row[..]; | ||
| 1013 | { | 1058 | { |
| 1014 | let mut dst = planes[0].borrow_mut(); | 1059 | let mut dst = planes[0].borrow_mut(); |
| 1015 | for row in 0..ah { | 1060 | for row in 0..ah { |
| @@ -1017,11 +1062,11 @@ impl EncSession { | |||
| 1017 | let s = unsafe { | 1062 | let s = unsafe { |
| 1018 | std::slice::from_raw_parts(src.y.add(row.min(h - 1) * src.y_stride), w) | 1063 | std::slice::from_raw_parts(src.y.add(row.min(h - 1) * src.y_stride), w) |
| 1019 | }; | 1064 | }; |
| 1020 | - let dst = &mut dst[row * pitch[0]..row * pitch[0] + aw]; | 1065 | + row_buf[..w].copy_from_slice(s); |
| 1021 | - dst[..w].copy_from_slice(s); | ||
| 1022 | // Macroblock padding: replicate the edge rather than leave the | 1066 | // Macroblock padding: replicate the edge rather than leave the |
| 1023 | // buffer's garbage there, which would cost bitrate for nothing. | 1067 | // 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); | ||
| 1025 | } | 1070 | } |
| 1026 | } | 1071 | } |
| 1027 | let mut dst = planes[1].borrow_mut(); | 1072 | let mut dst = planes[1].borrow_mut(); |
| @@ -1034,14 +1079,14 @@ impl EncSession { | |||
| 1034 | std::slice::from_raw_parts(src.v.add(src_row * src.v_stride), cw), | 1079 | std::slice::from_raw_parts(src.v.add(src_row * src.v_stride), cw), |
| 1035 | ) | 1080 | ) |
| 1036 | }; | 1081 | }; |
| 1037 | - let dst = &mut dst[row * pitch[1]..row * pitch[1] + aw]; | ||
| 1038 | for x in 0..cw { | 1082 | for x in 0..cw { |
| 1039 | - dst[2 * x] = u[x]; | 1083 | + row_buf[2 * x] = u[x]; |
| 1040 | - dst[2 * x + 1] = v[x]; | 1084 | + row_buf[2 * x + 1] = v[x]; |
| 1041 | } | 1085 | } |
| 1042 | for x in w..aw { | 1086 | for x in w..aw { |
| 1043 | - dst[x] = dst[x - 2]; | 1087 | + row_buf[x] = row_buf[x - 2]; |
| 1044 | } | 1088 | } |
| 1089 | + dst[row * pitch[1]..row * pitch[1] + aw].copy_from_slice(row_buf); | ||
| 1045 | } | 1090 | } |
| 1046 | Ok(()) | 1091 | Ok(()) |
| 1047 | } | 1092 | } |
| @@ -1049,8 +1094,13 @@ impl EncSession { | |||
| 1049 | /// # Safety | 1094 | /// # Safety |
| 1050 | /// As [`EncSession::upload`]. | 1095 | /// As [`EncSession::upload`]. |
| 1051 | unsafe fn encode(&mut self, src: &VhFrame, force_keyframe: bool) -> Result<(), String> { | 1096 | 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; | ||
| 1052 | // SAFETY: caller contract, forwarded. | 1101 | // SAFETY: caller contract, forwarded. |
| 1053 | - unsafe { self.upload(src)? }; | 1102 | + unsafe { self.upload(src, slot)? }; |
| 1103 | + self.slot = (self.slot + 1) % ENC_DEPTH; | ||
| 1054 | let meta = FrameMetadata { | 1104 | let meta = FrameMetadata { |
| 1055 | timestamp: self.timestamp, | 1105 | timestamp: self.timestamp, |
| 1056 | layout: self.layout.clone(), | 1106 | layout: self.layout.clone(), |
| @@ -1058,23 +1108,44 @@ impl EncSession { | |||
| 1058 | }; | 1108 | }; |
| 1059 | self.timestamp += 1; | 1109 | self.timestamp += 1; |
| 1060 | self.encoder | 1110 | self.encoder |
| 1061 | - .encode(meta, self.frame.clone()) | 1111 | + .encode(meta, self.frames[slot].clone()) |
| 1062 | .map_err(|e| e.to_string())?; | 1112 | .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(()) | ||
| 1064 | } | 1126 | } |
| 1065 | 1127 | ||
| 1066 | /// Moves every access unit the encoder has finished into `ready`. | 1128 | /// Moves every access unit the encoder has finished into `ready`. |
| 1067 | fn collect(&mut self) -> Result<(), String> { | 1129 | fn collect(&mut self) -> Result<(), String> { |
| 1068 | - while let Some(coded) = self.encoder.poll().map_err(|e| e.to_string())? { | 1130 | + while self.pull()? {} |
| 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 | - } | ||
| 1075 | Ok(()) | 1131 | Ok(()) |
| 1076 | } | 1132 | } |
| 1077 | 1133 | ||
| 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 | + | ||
| 1078 | /// Hands the oldest finished access unit to the caller, or reports that | 1149 | /// Hands the oldest finished access unit to the caller, or reports that |
| 1079 | /// there is none. | 1150 | /// there is none. |
| 1080 | fn take(&mut self, out: *mut *const u8, out_len: *mut usize) -> i32 { | 1151 | fn take(&mut self, out: *mut *const u8, out_len: *mut usize) -> i32 { |