Merge branch 'worktree-agent-a1dbd9ef7cdaec697'
Browse files at this commit7 changed files +474 -113
- Cargo.toml +13 -1
- crates/engine-hw/src/lib.rs +128 -31
- crates/engine/examples/bench.rs +34 -6
- crates/engine/src/export.rs +192 -34
- crates/engine/src/mux.rs +51 -30
- scripts/bench.sh +8 -2
- vendor/cros-codecs/src/video_frame/generic_dma_video_frame.rs +48 -9
Cargo.tomlmodified+13 -1
| @@ -34,7 +34,19 @@ edition = "2024" | |||
| 34 | # writer's emulation-prevention fix that shares that code) are | 34 | # writer's emulation-prevention fix that shares that code) are |
| 35 | # applied here verbatim -- upstream work carried early, not a | 35 | # applied here verbatim -- upstream work carried early, not a |
| 36 | # local invention, and the H.265 half of what makes edith's | 36 | # local invention, and the H.265 half of what makes edith's |
| 37 | -# HEVC export run on the GPU | 37 | +# HEVC export run on the GPU. |
| 38 | +# And `video_frame/generic_dma_video_frame.rs` unmapped a DMA | ||
| 39 | +# buffer by issuing one `CLFLUSH` per *byte* -- 64 per cache | ||
| 40 | +# line, 3.1 million per 1080p picture, 6.2 ms of the 8.4 ms a | ||
| 41 | +# hardware export spent per frame (measured on radeonsi | ||
| 42 | +# 2026-08-13; upstream's own TODO asks for exactly this and | ||
| 43 | +# reports a race that the mfence pair, not the redundancy, was | ||
| 44 | +# always ordering). The same `drop` wrote its `munmap` as an | ||
| 45 | +# unconsumed `.map()`, so no mapping was ever released and an | ||
| 46 | +# encode session leaked 3 MB of address space per frame | ||
| 47 | +# (2.2 GB over a 719-frame export). Both are fixed in place | ||
| 48 | +# and marked LOCAL PATCH | ||
| 49 | + | ||
| 38 | # rusty_aac - its *decoder* runs the direct O(N²) IMDCT with a `cos` call per | 50 | # rusty_aac - its *decoder* runs the direct O(N²) IMDCT with a `cos` call per |
| 39 | # term (the fast path in the same file serves the encoder only), | 51 | # term (the fast path in the same file serves the encoder only), |
| 40 | # which is 4x slower than real time for 5.1 and therefore not | 52 | # which is 4x slower than real time for 5.1 and therefore not |
crates/engine-hw/src/lib.rsmodified+128 -31
| @@ -840,11 +840,19 @@ fn fix_slice_nal_headers(au: &mut [u8]) { | |||
| 840 | 840 | ||
| 841 | /// One hardware H.264 encode session. | 841 | /// One hardware H.264 encode session. |
| 842 | /// | 842 | /// |
| 843 | -/// Input goes through a single reusable NV12 buffer object: the caller's I420 | 843 | +/// Input goes through [`enc_depth`] reusable NV12 buffer objects: the caller's |
| 844 | -/// planes are interleaved into it and the encoder imports it as a VA surface. | 844 | +/// I420 planes are interleaved into the next one and the encoder imports it as a |
| 845 | -/// Reuse is safe because the encoder runs in blocking mode and every entry | 845 | +/// VA surface. Reuse is safe because a buffer is only written again once the |
| 846 | -/// point polls it before returning, so the GPU is finished with the buffer | 846 | +/// access unit coded *from* it has been polled back -- the encoder runs in |
| 847 | -/// before the next picture is written into it. | 847 | +/// blocking mode and a coded unit in hand means the GPU has finished reading its |
| 848 | +/// input -- and [`EncSession::encode`] holds exactly that many pictures in | ||
| 849 | +/// flight, no more. | ||
| 850 | +/// | ||
| 851 | +/// **Why more than one.** With a single buffer the picture had to be coded | ||
| 852 | +/// before the next one could be written into it, so a frame cost the CPU's | ||
| 853 | +/// interleave *plus* the GPU's encode end to end (6.7 ms + 2.5 ms at 1080p on | ||
| 854 | +/// radeonsi, measured 2026-08-13). With two, the interleave of the next picture | ||
| 855 | +/// runs while the GPU codes this one and the frame costs the longer of them. | ||
| 848 | struct EncSession { | 856 | struct EncSession { |
| 849 | /// Boxed because the three codecs are three types and everything past | 857 | /// Boxed because the three codecs are three types and everything past |
| 850 | /// `encode` is the same trait: one session type serves them all, which is | 858 | /// `encode` is the same trait: one session type serves them all, which is |
| @@ -855,9 +863,18 @@ struct EncSession { | |||
| 855 | /// differs: the H.264 driver leaves a *NAL* header byte at zero, and | 863 | /// differs: the H.264 driver leaves a *NAL* header byte at zero, and |
| 856 | /// neither an HEVC access unit nor an AV1 temporal unit has that one. | 864 | /// neither an HEVC access unit nor an AV1 temporal unit has that one. |
| 857 | codec: EncCodec, | 865 | codec: EncCodec, |
| 858 | - /// Owns the DRM node the buffer object below was allocated from. | 866 | + /// Owns the DRM node the buffer objects below were allocated from. |
| 859 | _gbm: gbm::Device<std::fs::File>, | 867 | _gbm: gbm::Device<std::fs::File>, |
| 860 | - frame: GenericDmaVideoFrame, | 868 | + /// [`enc_depth`] input buffers, used round-robin. |
| 869 | + frames: Vec<GenericDmaVideoFrame>, | ||
| 870 | + /// How many of them there are, which is how many pictures may be in the | ||
| 871 | + /// encoder at once. | ||
| 872 | + depth: usize, | ||
| 873 | + /// Which of them the next picture is written into. | ||
| 874 | + slot: usize, | ||
| 875 | + /// Pictures submitted whose access unit has not been polled back yet, which | ||
| 876 | + /// is what says whether the buffer about to be written is free. | ||
| 877 | + in_flight: usize, | ||
| 861 | layout: FrameLayout, | 878 | layout: FrameLayout, |
| 862 | /// Macroblock-aligned surface size; `width`/`height` are what is encoded. | 879 | /// Macroblock-aligned surface size; `width`/`height` are what is encoded. |
| 863 | coded: Resolution, | 880 | coded: Resolution, |
| @@ -870,6 +887,34 @@ struct EncSession { | |||
| 870 | ready: VecDeque<Vec<u8>>, | 887 | ready: VecDeque<Vec<u8>>, |
| 871 | /// The access unit currently handed out, kept alive until the next call. | 888 | /// The access unit currently handed out, kept alive until the next call. |
| 872 | out: Vec<u8>, | 889 | out: Vec<u8>, |
| 890 | + /// One padded output row, staged in ordinary memory and copied across whole | ||
| 891 | + /// -- [`EncSession::upload`] says why. | ||
| 892 | + row: Vec<u8>, | ||
| 893 | +} | ||
| 894 | + | ||
| 895 | +/// How many pictures may be in the encoder at once. Two is what it takes to | ||
| 896 | +/// overlap the CPU's interleave with the GPU's encode; more would buy nothing, | ||
| 897 | +/// since the interleave is the longer of the two and a third buffer would only | ||
| 898 | +/// hold a picture waiting for a lane that is never idle. | ||
| 899 | +const ENC_DEPTH: usize = 2; | ||
| 900 | + | ||
| 901 | +/// How many pictures *this* seat may hold, which is [`ENC_DEPTH`] for H.264 and | ||
| 902 | +/// one for the other two. | ||
| 903 | +/// | ||
| 904 | +/// Depth 2 means a submitted picture must hand its access unit back on the next | ||
| 905 | +/// poll, and [`EncSession::encode`] treats a seat that does not as an error -- | ||
| 906 | +/// it cannot write into a buffer the GPU may still be reading. That contract | ||
| 907 | +/// was measured on the H.264 seat and only there. HEVC and AV1 on this plugin | ||
| 908 | +/// are intra-only and go through the same driver, so they very probably behave | ||
| 909 | +/// the same way; "very probably" is not what a hard error should rest on, and | ||
| 910 | +/// the GPU has been unavailable since the measurement was possible. They keep | ||
| 911 | +/// the old one-buffer behaviour -- the picture coded before the next is | ||
| 912 | +/// written, exactly as every seat did before -- until someone measures them. | ||
| 913 | +fn enc_depth(codec: EncCodec) -> usize { | ||
| 914 | + match codec { | ||
| 915 | + EncCodec::H264 => ENC_DEPTH, | ||
| 916 | + EncCodec::Hevc | EncCodec::Av1 => 1, | ||
| 917 | + } | ||
| 873 | } | 918 | } |
| 874 | 919 | ||
| 875 | /// Which codec an [`EncSession`] was opened for. Decided once, at the open, the | 920 | /// Which codec an [`EncSession`] was opened for. Decided once, at the open, the |
| @@ -1049,13 +1094,20 @@ impl EncSession { | |||
| 1049 | }; | 1094 | }; |
| 1050 | // Allocated at the aligned size, so the buffer's pitch is never smaller | 1095 | // Allocated at the aligned size, so the buffer's pitch is never smaller |
| 1051 | // than a padded row. | 1096 | // than a padded row. |
| 1052 | - let frame = alloc_nv12(&gbm, coded, false).ok()?; | 1097 | + let depth = enc_depth(codec); |
| 1053 | - let layout = nv12_layout(coded, frame.get_plane_pitch()[0], false); | 1098 | + let frames: Vec<_> = (0..depth) |
| 1099 | + .map(|_| alloc_nv12(&gbm, coded, false)) | ||
| 1100 | + .collect::<Result<_, _>>() | ||
| 1101 | + .ok()?; | ||
| 1102 | + let layout = nv12_layout(coded, frames[0].get_plane_pitch()[0], false); | ||
| 1054 | Some(Self { | 1103 | Some(Self { |
| 1055 | encoder, | 1104 | encoder, |
| 1056 | codec, | 1105 | codec, |
| 1057 | _gbm: gbm, | 1106 | _gbm: gbm, |
| 1058 | - frame, | 1107 | + frames, |
| 1108 | + depth, | ||
| 1109 | + slot: 0, | ||
| 1110 | + in_flight: 0, | ||
| 1059 | layout, | 1111 | layout, |
| 1060 | coded, | 1112 | coded, |
| 1061 | width: width as usize, | 1113 | width: width as usize, |
| @@ -1064,21 +1116,38 @@ impl EncSession { | |||
| 1064 | drained: false, | 1116 | drained: false, |
| 1065 | ready: VecDeque::new(), | 1117 | ready: VecDeque::new(), |
| 1066 | out: Vec::new(), | 1118 | out: Vec::new(), |
| 1119 | + row: Vec::new(), | ||
| 1067 | }) | 1120 | }) |
| 1068 | } | 1121 | } |
| 1069 | 1122 | ||
| 1070 | - /// Interleaves one packed I420 picture into the NV12 input buffer. | 1123 | + /// Interleaves one packed I420 picture into the NV12 input buffer `slot`. |
| 1124 | + /// | ||
| 1125 | + /// **Row at a time, through ordinary memory.** The mapping below is the | ||
| 1126 | + /// GPU's own buffer, which is write-combining: a store of a byte or two | ||
| 1127 | + /// costs a partial-buffer flush, while one `memcpy` of a whole row costs a | ||
| 1128 | + /// burst. Interleaving the chroma directly into it was 8.2 ms a picture at | ||
| 1129 | + /// 1080p against 6.7 ms staged (measured 2026-08-13 on radeonsi, alternating | ||
| 1130 | + /// the two paths frame by frame inside one export so the machine's load | ||
| 1131 | + /// weighed on both), and the picture is four fifths of what a hardware | ||
| 1132 | + /// export spends per frame. The padding is written the same way and for the | ||
| 1133 | + /// same reason: it used to be a four-byte second store per row. | ||
| 1071 | /// | 1134 | /// |
| 1072 | /// # Safety | 1135 | /// # Safety |
| 1073 | /// `src`'s planes must cover `height` (resp. `height / 2`) rows of their | 1136 | /// `src`'s planes must cover `height` (resp. `height / 2`) rows of their |
| 1074 | /// declared stride. | 1137 | /// declared stride. |
| 1075 | - unsafe fn upload(&mut self, src: &VhFrame) -> Result<(), String> { | 1138 | + unsafe fn upload(&mut self, src: &VhFrame, slot: usize) -> Result<(), String> { |
| 1076 | let (w, h) = (self.width, self.height); | 1139 | let (w, h) = (self.width, self.height); |
| 1077 | let (cw, ch) = (w / 2, h / 2); | 1140 | let (cw, ch) = (w / 2, h / 2); |
| 1078 | let (aw, ah) = (self.coded.width as usize, self.coded.height as usize); | 1141 | let (aw, ah) = (self.coded.width as usize, self.coded.height as usize); |
| 1079 | - let pitch = self.frame.get_plane_pitch(); | 1142 | + // Two fields at once: the buffer is mapped for writing while the staging |
| 1080 | - let mapping = self.frame.map_mut()?; | 1143 | + // row is written into, and they are not the same field. |
| 1144 | + let Self { frames, row, .. } = self; | ||
| 1145 | + let frame = &mut frames[slot]; | ||
| 1146 | + let pitch = frame.get_plane_pitch(); | ||
| 1147 | + let mapping = frame.map_mut()?; | ||
| 1081 | let planes = mapping.get(); | 1148 | let planes = mapping.get(); |
| 1149 | + row.resize(aw, 0); | ||
| 1150 | + let row_buf = &mut row[..]; | ||
| 1082 | { | 1151 | { |
| 1083 | let mut dst = planes[0].borrow_mut(); | 1152 | let mut dst = planes[0].borrow_mut(); |
| 1084 | for row in 0..ah { | 1153 | for row in 0..ah { |
| @@ -1086,11 +1155,11 @@ impl EncSession { | |||
| 1086 | let s = unsafe { | 1155 | let s = unsafe { |
| 1087 | std::slice::from_raw_parts(src.y.add(row.min(h - 1) * src.y_stride), w) | 1156 | std::slice::from_raw_parts(src.y.add(row.min(h - 1) * src.y_stride), w) |
| 1088 | }; | 1157 | }; |
| 1089 | - let dst = &mut dst[row * pitch[0]..row * pitch[0] + aw]; | 1158 | + row_buf[..w].copy_from_slice(s); |
| 1090 | - dst[..w].copy_from_slice(s); | ||
| 1091 | // Macroblock padding: replicate the edge rather than leave the | 1159 | // Macroblock padding: replicate the edge rather than leave the |
| 1092 | // buffer's garbage there, which would cost bitrate for nothing. | 1160 | // buffer's garbage there, which would cost bitrate for nothing. |
| 1093 | - dst[w..].fill(s[w - 1]); | 1161 | + row_buf[w..].fill(s[w - 1]); |
| 1162 | + dst[row * pitch[0]..row * pitch[0] + aw].copy_from_slice(row_buf); | ||
| 1094 | } | 1163 | } |
| 1095 | } | 1164 | } |
| 1096 | let mut dst = planes[1].borrow_mut(); | 1165 | let mut dst = planes[1].borrow_mut(); |
| @@ -1103,14 +1172,14 @@ impl EncSession { | |||
| 1103 | std::slice::from_raw_parts(src.v.add(src_row * src.v_stride), cw), | 1172 | std::slice::from_raw_parts(src.v.add(src_row * src.v_stride), cw), |
| 1104 | ) | 1173 | ) |
| 1105 | }; | 1174 | }; |
| 1106 | - let dst = &mut dst[row * pitch[1]..row * pitch[1] + aw]; | ||
| 1107 | for x in 0..cw { | 1175 | for x in 0..cw { |
| 1108 | - dst[2 * x] = u[x]; | 1176 | + row_buf[2 * x] = u[x]; |
| 1109 | - dst[2 * x + 1] = v[x]; | 1177 | + row_buf[2 * x + 1] = v[x]; |
| 1110 | } | 1178 | } |
| 1111 | for x in w..aw { | 1179 | for x in w..aw { |
| 1112 | - dst[x] = dst[x - 2]; | 1180 | + row_buf[x] = row_buf[x - 2]; |
| 1113 | } | 1181 | } |
| 1182 | + dst[row * pitch[1]..row * pitch[1] + aw].copy_from_slice(row_buf); | ||
| 1114 | } | 1183 | } |
| 1115 | Ok(()) | 1184 | Ok(()) |
| 1116 | } | 1185 | } |
| @@ -1118,8 +1187,15 @@ impl EncSession { | |||
| 1118 | /// # Safety | 1187 | /// # Safety |
| 1119 | /// As [`EncSession::upload`]. | 1188 | /// As [`EncSession::upload`]. |
| 1120 | unsafe fn encode(&mut self, src: &VhFrame, force_keyframe: bool) -> Result<(), String> { | 1189 | unsafe fn encode(&mut self, src: &VhFrame, force_keyframe: bool) -> Result<(), String> { |
| 1190 | + // The buffer this picture is written into is the one whose own access | ||
| 1191 | + // unit is already in hand -- `in_flight` is held below `depth` at the | ||
| 1192 | + // end of every call, so the round-robin never catches the GPU up. At | ||
| 1193 | + // depth 1 that is the picture just coded, which is the one-buffer | ||
| 1194 | + // behaviour every seat had before ([`enc_depth`]). | ||
| 1195 | + let slot = self.slot; | ||
| 1121 | // SAFETY: caller contract, forwarded. | 1196 | // SAFETY: caller contract, forwarded. |
| 1122 | - unsafe { self.upload(src)? }; | 1197 | + unsafe { self.upload(src, slot)? }; |
| 1198 | + self.slot = (self.slot + 1) % self.depth; | ||
| 1123 | let meta = FrameMetadata { | 1199 | let meta = FrameMetadata { |
| 1124 | timestamp: self.timestamp, | 1200 | timestamp: self.timestamp, |
| 1125 | layout: self.layout.clone(), | 1201 | layout: self.layout.clone(), |
| @@ -1127,23 +1203,44 @@ impl EncSession { | |||
| 1127 | }; | 1203 | }; |
| 1128 | self.timestamp += 1; | 1204 | self.timestamp += 1; |
| 1129 | self.encoder | 1205 | self.encoder |
| 1130 | - .encode(meta, self.frame.clone()) | 1206 | + .encode(meta, self.frames[slot].clone()) |
| 1131 | .map_err(|e| e.to_string())?; | 1207 | .map_err(|e| e.to_string())?; |
| 1132 | - self.collect() | 1208 | + self.in_flight += 1; |
| 1209 | + // ...and the picture before it is collected here rather than this one: | ||
| 1210 | + // that is the whole overlap, the GPU coding what was just submitted | ||
| 1211 | + // while the caller decodes and interleaves the next picture. | ||
| 1212 | + while self.in_flight >= self.depth { | ||
| 1213 | + if !self.pull()? { | ||
| 1214 | + // Blocking mode: a picture accepted and no coded unit for the | ||
| 1215 | + // one before it means the encoder is not answering, and the | ||
| 1216 | + // next upload would overwrite a buffer the GPU still reads. | ||
| 1217 | + return Err("the encoder took a picture and returned nothing coded".into()); | ||
| 1218 | + } | ||
| 1219 | + } | ||
| 1220 | + Ok(()) | ||
| 1133 | } | 1221 | } |
| 1134 | 1222 | ||
| 1135 | /// Moves every access unit the encoder has finished into `ready`. | 1223 | /// Moves every access unit the encoder has finished into `ready`. |
| 1136 | fn collect(&mut self) -> Result<(), String> { | 1224 | fn collect(&mut self) -> Result<(), String> { |
| 1137 | - while let Some(coded) = self.encoder.poll().map_err(|e| e.to_string())? { | 1225 | + while self.pull()? {} |
| 1138 | - let mut au = coded.bitstream; | ||
| 1139 | - if self.codec == EncCodec::H264 { | ||
| 1140 | - fix_slice_nal_headers(&mut au); | ||
| 1141 | - } | ||
| 1142 | - self.ready.push_back(au); | ||
| 1143 | - } | ||
| 1144 | Ok(()) | 1226 | Ok(()) |
| 1145 | } | 1227 | } |
| 1146 | 1228 | ||
| 1229 | + /// One finished access unit into `ready`; `false` where the encoder has | ||
| 1230 | + /// none to give. | ||
| 1231 | + fn pull(&mut self) -> Result<bool, String> { | ||
| 1232 | + let Some(coded) = self.encoder.poll().map_err(|e| e.to_string())? else { | ||
| 1233 | + return Ok(false); | ||
| 1234 | + }; | ||
| 1235 | + let mut au = coded.bitstream; | ||
| 1236 | + if self.codec == EncCodec::H264 { | ||
| 1237 | + fix_slice_nal_headers(&mut au); | ||
| 1238 | + } | ||
| 1239 | + self.ready.push_back(au); | ||
| 1240 | + self.in_flight = self.in_flight.saturating_sub(1); | ||
| 1241 | + Ok(true) | ||
| 1242 | + } | ||
| 1243 | + | ||
| 1147 | /// Hands the oldest finished access unit to the caller, or reports that | 1244 | /// Hands the oldest finished access unit to the caller, or reports that |
| 1148 | /// there is none. | 1245 | /// there is none. |
| 1149 | fn take(&mut self, out: *mut *const u8, out_len: *mut usize) -> i32 { | 1246 | fn take(&mut self, out: *mut *const u8, out_len: *mut usize) -> i32 { |
crates/engine/examples/bench.rsmodified+34 -6
| @@ -27,7 +27,15 @@ | |||
| 27 | //! writing except the export destination it is handed. | 27 | //! writing except the export destination it is handed. |
| 28 | //! | 28 | //! |
| 29 | //! Env: `BENCH_TTFF_TIMEOUT` (s, default 180) how long a seek may wait for its | 29 | //! Env: `BENCH_TTFF_TIMEOUT` (s, default 180) how long a seek may wait for its |
| 30 | -//! first frame, `BENCH_EXPORT_CAP` (s, default 300) the wall clock any single | 30 | +//! first frame, `BENCH_EXPORT_SPAN` (s, default 60) how much timeline one |
| 31 | +//! export measurement covers, `BENCH_EXPORT_AUDIO` (unset) whether that | ||
| 32 | +//! timeline carries its source's sound as well -- the row is named `_av` when | ||
| 33 | +//! it does, because an export's wall clock is the audio pass plus the picture | ||
| 34 | +//! and a picture-only number is not the thing a person waits for -- | ||
| 35 | +//! `BENCH_EXPORT_ASTREAM` (default 0) which of the file's audio streams that | ||
| 36 | +//! is, a film's second track often being the one no sample table can copy and | ||
| 37 | +//! therefore the one that measures a re-encode, | ||
| 38 | +//! `BENCH_EXPORT_CAP` (s, default 300) the wall clock any single | ||
| 31 | //! export measurement may take, `BENCH_EXPORT_REPS` (default 5) how many times | 39 | //! export measurement may take, `BENCH_EXPORT_REPS` (default 5) how many times |
| 32 | //! an export is repeated *if the cap leaves room* -- a 4K encode gets one | 40 | //! an export is repeated *if the cap leaves room* -- a 4K encode gets one |
| 33 | //! capped rep, the small control gets five -- and `BENCH_KEEP` (unset) whether | 41 | //! capped rep, the small control gets five -- and `BENCH_KEEP` (unset) whether |
| @@ -620,7 +628,12 @@ fn export_bench(path: &Path, seat: &str, out_dir: &Path) { | |||
| 620 | "hevchw" => (Format::Hevc, false), | 628 | "hevchw" => (Format::Hevc, false), |
| 621 | _ => usage(), | 629 | _ => usage(), |
| 622 | }; | 630 | }; |
| 623 | - let metric = format!("export_fps_{seat}"); | 631 | + // The sound is opt-in and named in the row, so an `_av` number is never |
| 632 | + // compared against a picture-only one: what it measures is the *export* -- | ||
| 633 | + // audio pass, mux and all -- which is the only shape of the number a | ||
| 634 | + // "twice real time" claim may be made from. | ||
| 635 | + let with_audio = std::env::var_os("BENCH_EXPORT_AUDIO").is_some(); | ||
| 636 | + let metric = format!("export_fps_{seat}{}", if with_audio { "_av" } else { "" }); | ||
| 624 | let (meta, _) = match engine::demux::Demuxer::open(path) { | 637 | let (meta, _) = match engine::demux::Demuxer::open(path) { |
| 625 | Ok(opened) => opened, | 638 | Ok(opened) => opened, |
| 626 | Err(e) => { | 639 | Err(e) => { |
| @@ -628,7 +641,8 @@ fn export_bench(path: &Path, seat: &str, out_dir: &Path) { | |||
| 628 | return; | 641 | return; |
| 629 | } | 642 | } |
| 630 | }; | 643 | }; |
| 631 | - let span = ((meta.frame_rate * 60.0) as u32).min(meta.frame_count.max(1)); | 644 | + let span = ((meta.frame_rate * env_f64("BENCH_EXPORT_SPAN", 60.0)) as u32) |
| 645 | + .min(meta.frame_count.max(1)); | ||
| 632 | let in_frame = (meta.frame_count / 10).min(meta.frame_count.saturating_sub(span)); | 646 | let in_frame = (meta.frame_count / 10).min(meta.frame_count.saturating_sub(span)); |
| 633 | let clip = Clip { | 647 | let clip = Clip { |
| 634 | start: 0, | 648 | start: 0, |
| @@ -641,9 +655,16 @@ fn export_bench(path: &Path, seat: &str, out_dir: &Path) { | |||
| 641 | fit: engine::scale::FitPolicy::default(), | 655 | fit: engine::scale::FitPolicy::default(), |
| 642 | speed: Speed::NORMAL, | 656 | speed: Speed::NORMAL, |
| 643 | }; | 657 | }; |
| 658 | + // The sound, where it was asked for, is the same clip on an audio lane: | ||
| 659 | + // the very window the picture covers, so the two passes measure one export. | ||
| 660 | + let mut lanes = vec![(LaneKind::Video, vec![clip.clone()])]; | ||
| 661 | + if with_audio { | ||
| 662 | + lanes.push((LaneKind::Audio, vec![clip])); | ||
| 663 | + } | ||
| 664 | + let stream = env_f64("BENCH_EXPORT_ASTREAM", 0.0) as usize; | ||
| 644 | let project = match Project::from_parts( | 665 | let project = match Project::from_parts( |
| 645 | - vec![Source::new(path, 0)], | 666 | + vec![Source::new(path, stream)], |
| 646 | - vec![(LaneKind::Video, vec![clip])], | 667 | + lanes, |
| 647 | Vec::new(), | 668 | Vec::new(), |
| 648 | Vec::new(), | 669 | Vec::new(), |
| 649 | ) { | 670 | ) { |
| @@ -669,7 +690,14 @@ fn export_bench(path: &Path, seat: &str, out_dir: &Path) { | |||
| 669 | let handle = engine::export::start(project.clone(), meta, &out, &settings); | 690 | let handle = engine::export::start(project.clone(), meta, &out, &settings); |
| 670 | let t = Instant::now(); | 691 | let t = Instant::now(); |
| 671 | let mut capped = false; | 692 | let mut capped = false; |
| 693 | + // The highest the bar was ever seen at, not wherever it happens to | ||
| 694 | + // stand when the clock stops: an export publishes one bar from two | ||
| 695 | + // stages, and a capped run's rate is derived from this number. Taking | ||
| 696 | + // the maximum over the poll loop means a single unlucky read cannot | ||
| 697 | + // under-report the work that was really done. | ||
| 698 | + let mut peak = 0.0f64; | ||
| 672 | while !handle.is_finished() { | 699 | while !handle.is_finished() { |
| 700 | + peak = peak.max(f64::from(handle.progress())); | ||
| 673 | if t.elapsed() >= cap { | 701 | if t.elapsed() >= cap { |
| 674 | capped = true; | 702 | capped = true; |
| 675 | handle.cancel(); | 703 | handle.cancel(); |
| @@ -679,7 +707,7 @@ fn export_bench(path: &Path, seat: &str, out_dir: &Path) { | |||
| 679 | } | 707 | } |
| 680 | // A cancel is answered at the worker's next checkpoint; the rate is | 708 | // A cancel is answered at the worker's next checkpoint; the rate is |
| 681 | // read from the progress at the moment the clock stopped either way. | 709 | // read from the progress at the moment the clock stopped either way. |
| 682 | - let progress = f64::from(handle.progress()); | 710 | + let progress = peak.max(f64::from(handle.progress())); |
| 683 | let elapsed = t.elapsed().as_secs_f64(); | 711 | let elapsed = t.elapsed().as_secs_f64(); |
| 684 | let done = Instant::now() + Duration::from_secs(60); | 712 | let done = Instant::now() + Duration::from_secs(60); |
| 685 | while !handle.is_finished() && Instant::now() < done { | 713 | while !handle.is_finished() && Instant::now() < done { |
crates/engine/src/export.rsmodified+192 -34
| @@ -303,6 +303,17 @@ pub struct ExportSettings { | |||
| 303 | } | 303 | } |
| 304 | 304 | ||
| 305 | struct Shared { | 305 | struct Shared { |
| 306 | + /// Fraction of the job done, in [`PROGRESS_SCALE`]ths. | ||
| 307 | + /// | ||
| 308 | + /// **Every stage that can run beside another writes this with `fetch_max`, | ||
| 309 | + /// never `store`.** The sound and the picture are two threads publishing | ||
| 310 | + /// two bands of one bar ([`AUDIO_BAND`]): a `store` from the lower band | ||
| 311 | + /// pulls the bar backwards every time the other thread has already moved | ||
| 312 | + /// it on, which is what a person sees as a progress bar that stutters | ||
| 313 | + /// backwards -- 5,458 backward steps over one film export before this rule | ||
| 314 | + /// was written down. A `store` is only correct where nothing else can be | ||
| 315 | + /// publishing at all, which now means the terminal [`PROGRESS_SCALE`] and | ||
| 316 | + /// the audio-only export ([`run_audio`]) that has no second thread. | ||
| 306 | progress: AtomicU32, | 317 | progress: AtomicU32, |
| 307 | cancel: AtomicBool, | 318 | cancel: AtomicBool, |
| 308 | finished: AtomicBool, | 319 | finished: AtomicBool, |
| @@ -1325,10 +1336,21 @@ fn encode_audio( | |||
| 1325 | * channels; | 1336 | * channels; |
| 1326 | let mut samples: Vec<f32> = Vec::with_capacity(total); | 1337 | let mut samples: Vec<f32> = Vec::with_capacity(total); |
| 1327 | for chunk in chunks { | 1338 | for chunk in chunks { |
| 1339 | + // The only place a cancelled export can be answered before the whole | ||
| 1340 | + // timeline has been mixed. This pass runs on a thread of its own now | ||
| 1341 | + // ([`run`]), so without this a cancel left it mixing a feature film | ||
| 1342 | + // for minutes behind a job nobody is waiting for any more, writing | ||
| 1343 | + // into a `Shared` whose outcome was already settled. | ||
| 1344 | + cancelled(shared)?; | ||
| 1328 | samples.extend(chunk.samples); | 1345 | samples.extend(chunk.samples); |
| 1329 | // The bar's first third of [`AUDIO_BAND`]: the mix is the longest of | 1346 | // The bar's first third of [`AUDIO_BAND`]: the mix is the longest of |
| 1330 | // the three stages and the only one that can be counted as it goes. | 1347 | // the three stages and the only one that can be counted as it goes. |
| 1331 | - shared.progress.store( | 1348 | + // |
| 1349 | + // `fetch_max` and not `store`, for the reason [`Shared::progress`] | ||
| 1350 | + // states: this runs on the audio thread while the picture publishes | ||
| 1351 | + // numbers above [`AUDIO_BAND`] from the other, and a `store` of this | ||
| 1352 | + // small one pulled the bar backwards 5,458 times over one film export. | ||
| 1353 | + shared.progress.fetch_max( | ||
| 1332 | (samples.len().min(total) * (AUDIO_BAND / 3) as usize / total.max(1)) as u32, | 1354 | (samples.len().min(total) * (AUDIO_BAND / 3) as usize / total.max(1)) as u32, |
| 1333 | Ordering::Relaxed, | 1355 | Ordering::Relaxed, |
| 1334 | ); | 1356 | ); |
| @@ -1351,6 +1373,10 @@ fn encode_audio( | |||
| 1351 | // there is no resampler on this path, and inventing one to reach 48 kHz | 1373 | // there is no resampler on this path, and inventing one to reach 48 kHz |
| 1352 | // would resample a whole timeline to satisfy a codec, which is a bigger | 1374 | // would resample a whole timeline to satisfy a codec, which is a bigger |
| 1353 | // change to the sound than the codec is. | 1375 | // change to the sound than the codec is. |
| 1376 | + // ...and again before either encoder is entered: both of them run to the | ||
| 1377 | + // end of the mix without a checkpoint of their own, so this is the last | ||
| 1378 | + // moment a cancel costs seconds rather than the whole encode. | ||
| 1379 | + cancelled(shared)?; | ||
| 1354 | if mkv | 1380 | if mkv |
| 1355 | && audio.sample_rate == OPUS_RATE | 1381 | && audio.sample_rate == OPUS_RATE |
| 1356 | && channels == 2 | 1382 | && channels == 2 |
| @@ -1380,6 +1406,7 @@ fn encode_audio( | |||
| 1380 | // `next_packet` after `finish` yields packets until `Eof` and nothing else, | 1406 | // `next_packet` after `finish` yields packets until `Eof` and nothing else, |
| 1381 | // so the loop ends on the only error it can see. | 1407 | // so the loop ends on the only error it can see. |
| 1382 | while let Ok(packet) = encoder.next_packet() { | 1408 | while let Ok(packet) = encoder.next_packet() { |
| 1409 | + cancelled(shared)?; | ||
| 1383 | packets.push(crate::AacPacket { | 1410 | packets.push(crate::AacPacket { |
| 1384 | bytes: packet.data, | 1411 | bytes: packet.data, |
| 1385 | samples: packet.duration, | 1412 | samples: packet.duration, |
| @@ -1657,11 +1684,54 @@ fn window_fidelity( | |||
| 1657 | (da / counted.max(1) as f64 > FIDELITY_FLOOR).then(|| num / (da.sqrt() * db.sqrt()).max(1e-12)) | 1684 | (da / counted.max(1) as f64 > FIDELITY_FLOOR).then(|| num / (da.sqrt() * db.sqrt()).max(1e-12)) |
| 1658 | } | 1685 | } |
| 1659 | 1686 | ||
| 1687 | +/// The audio pass, running beside the picture: what [`run`] holds while it | ||
| 1688 | +/// encodes and joins where the file it is writing needs the track. | ||
| 1689 | +type AudioJob = thread::JoinHandle<crate::Result<Option<ExportAudio>>>; | ||
| 1690 | + | ||
| 1691 | +/// The pass's answer, or the failure that is the export's failure. A panicked | ||
| 1692 | +/// audio thread reads as an error rather than as silence: an export that wrote | ||
| 1693 | +/// its picture and quietly no sound is the one outcome this must not have. | ||
| 1694 | +fn join_audio(job: AudioJob) -> crate::Result<Option<ExportAudio>> { | ||
| 1695 | + job.join() | ||
| 1696 | + .map_err(|_| crate::Error::from("the audio pass stopped without a picture or a reason"))? | ||
| 1697 | +} | ||
| 1698 | + | ||
| 1699 | +/// The encoder line a running export shows: the seat the picture is really | ||
| 1700 | +/// being written by, and what the sound is -- or that the sound is still being | ||
| 1701 | +/// worked out, which an overlapped audio pass is until it is collected. | ||
| 1702 | +fn publish_seats( | ||
| 1703 | + shared: &Shared, | ||
| 1704 | + seat: &str, | ||
| 1705 | + project: &Project, | ||
| 1706 | + settings: &ExportSettings, | ||
| 1707 | + sound: Option<bool>, | ||
| 1708 | + opus: bool, | ||
| 1709 | + waiting: bool, | ||
| 1710 | +) { | ||
| 1711 | + let audio = match waiting { | ||
| 1712 | + // Still mixing on the other thread. The same half-line the copied- | ||
| 1713 | + // picture path has always shown, and for the same reason: what is | ||
| 1714 | + // published is never a codec that did not run. | ||
| 1715 | + true => "working out the sound…", | ||
| 1716 | + false => measured_audio_label(project, settings.format, sound, opus), | ||
| 1717 | + }; | ||
| 1718 | + *shared.encoders.lock().unwrap() = Some(format!("{seat} · {audio}")); | ||
| 1719 | +} | ||
| 1720 | + | ||
| 1721 | +fn params_of(track: &ExportAudio) -> AudioParams { | ||
| 1722 | + AudioParams { | ||
| 1723 | + freq_index: track.params.freq_index, | ||
| 1724 | + chan_conf: track.params.chan_conf, | ||
| 1725 | + sample_rate: track.params.sample_rate, | ||
| 1726 | + opus_pre_skip: track.opus_pre_skip, | ||
| 1727 | + } | ||
| 1728 | +} | ||
| 1729 | + | ||
| 1660 | fn run( | 1730 | fn run( |
| 1661 | project: &Project, | 1731 | project: &Project, |
| 1662 | meta: &VideoMeta, | 1732 | meta: &VideoMeta, |
| 1663 | out: &Path, | 1733 | out: &Path, |
| 1664 | - shared: &Shared, | 1734 | + shared: &Arc<Shared>, |
| 1665 | settings: &ExportSettings, | 1735 | settings: &ExportSettings, |
| 1666 | ) -> crate::Result<()> { | 1736 | ) -> crate::Result<()> { |
| 1667 | let total = project.timeline_frames(); | 1737 | let total = project.timeline_frames(); |
| @@ -1678,43 +1748,80 @@ fn run( | |||
| 1678 | eprintln!("export video: copy (source packets)"); | 1748 | eprintln!("export video: copy (source packets)"); |
| 1679 | *shared.encoders.lock().unwrap() = Some("copy · working out the sound…".into()); | 1749 | *shared.encoders.lock().unwrap() = Some("copy · working out the sound…".into()); |
| 1680 | } | 1750 | } |
| 1681 | - // ...then the audio: a track has to be declared when the muxer is created, | 1751 | + // ...then the audio, on a thread of its own, started before anything is |
| 1682 | - // which happens as soon as the first coded picture arrives -- and the | 1752 | + // opened for the picture. |
| 1683 | - // Matroska muxer wants the packets themselves that early too, because it | 1753 | + // |
| 1684 | - // interleaves them into the clusters as it writes. Every video format gets | 1754 | + // Where it is *waited* for is the whole of this: a Matroska file interleaves |
| 1685 | - // the same track: none of them is picture-only any more. | 1755 | + // its audio into the clusters from the header on, so that path needs every |
| 1686 | - let audio = copy_audio( | 1756 | + // packet before the first coded picture and there is nothing to overlap. An |
| 1687 | - project, | 1757 | + // mp4 writes its audio track after the whole picture -- and now declares it |
| 1688 | - meta, | 1758 | + // there too ([`MkvMuxer`]'s opposite, `Mp4Muxer::add_audio_track`) -- so the |
| 1689 | - audio_kbps_of(settings), | 1759 | + // picture's loop needs nothing at all from this until it has finished, and |
| 1690 | - settings.format.is_mkv(), | 1760 | + // the mix, its encode and the encode of every frame run at once. An export |
| 1691 | - shared, | 1761 | + // used to cost the sound *plus* the picture; an mp4 one now costs the longer |
| 1692 | - )?; | 1762 | + // of the two. On this project's own film that is 168 s of AC-3 that no |
| 1693 | - let audio_params = audio.as_ref().map(|track| AudioParams { | 1763 | + // longer stands in front of 733 s of hardware H.264. |
| 1694 | - freq_index: track.params.freq_index, | 1764 | + let audio_job = { |
| 1695 | - chan_conf: track.params.chan_conf, | 1765 | + let (project, meta, settings, shared) = ( |
| 1696 | - sample_rate: track.params.sample_rate, | 1766 | + project.clone(), |
| 1697 | - opus_pre_skip: track.opus_pre_skip, | 1767 | + *meta, |
| 1698 | - }); | 1768 | + settings.clone(), |
| 1769 | + Arc::clone(shared), | ||
| 1770 | + ); | ||
| 1771 | + thread::Builder::new() | ||
| 1772 | + .name("export-audio".into()) | ||
| 1773 | + .spawn(move || { | ||
| 1774 | + copy_audio( | ||
| 1775 | + &project, | ||
| 1776 | + &meta, | ||
| 1777 | + audio_kbps_of(&settings), | ||
| 1778 | + settings.format.is_mkv(), | ||
| 1779 | + &shared, | ||
| 1780 | + ) | ||
| 1781 | + })? | ||
| 1782 | + }; | ||
| 1783 | + // A Matroska file (and a copied one, whose muxer is the same) collects it | ||
| 1784 | + // here; an mp4 leaves it running and collects it under the picture below. | ||
| 1785 | + let mut audio_job = Some(audio_job); | ||
| 1786 | + // The condition is the *format*, and the copied-picture path below relies | ||
| 1787 | + // on that covering it too: `plan` hands its packets straight to a Matroska | ||
| 1788 | + // muxer, so it may only exist where this has already collected them -- | ||
| 1789 | + // which holds because [`CopyPlan::of`] returns `None` for every format | ||
| 1790 | + // that is not `Hevc` or `Av1`, both of which are `is_mkv`. Said out loud | ||
| 1791 | + // because a copy plan for an mp4 would otherwise reach `plan.run` with the | ||
| 1792 | + // sound still being mixed on the other thread. | ||
| 1793 | + debug_assert!( | ||
| 1794 | + settings.format.is_mkv() || plan.is_none(), | ||
| 1795 | + "a copy plan outside Matroska would run before its sound is collected" | ||
| 1796 | + ); | ||
| 1797 | + let audio = match settings.format.is_mkv() { | ||
| 1798 | + true => join_audio(audio_job.take().expect("the job was just made"))?, | ||
| 1799 | + false => None, | ||
| 1800 | + }; | ||
| 1801 | + let audio_params = audio.as_ref().map(params_of); | ||
| 1699 | // What the track *is*, kept before the packets are handed to a muxer: the | 1802 | // What the track *is*, kept before the packets are handed to a muxer: the |
| 1700 | // encoder line names a copy or an encode and only `copy_audio` knows which. | 1803 | // encoder line names a copy or an encode and only `copy_audio` knows which. |
| 1701 | - let sound = audio.as_ref().map(|track| track.copied); | 1804 | + // `None` on the mp4 path until the pass is collected -- the line says it is |
| 1805 | + // still working the sound out, which is what it is doing. | ||
| 1806 | + let mut sound = audio.as_ref().map(|track| track.copied); | ||
| 1702 | // ...and *which* encoder, for the same line: the card predicts Opus from the | 1807 | // ...and *which* encoder, for the same line: the card predicts Opus from the |
| 1703 | // format alone and cannot know the mix's rate or width ([`audio_label`]), | 1808 | // format alone and cannot know the mix's rate or width ([`audio_label`]), |
| 1704 | // while this is after the mix was opened, so it is the measured answer. | 1809 | // while this is after the mix was opened, so it is the measured answer. |
| 1705 | - let opus = audio | 1810 | + let mut opus = audio |
| 1706 | .as_ref() | 1811 | .as_ref() |
| 1707 | .is_some_and(|track| track.opus_pre_skip.is_some()); | 1812 | .is_some_and(|track| track.opus_pre_skip.is_some()); |
| 1708 | // Taken by the Matroska muxer at creation; the mp4 one writes its track | 1813 | // Taken by the Matroska muxer at creation; the mp4 one writes its track |
| 1709 | - // after the picture, so for that path this is still `Some` at the end. | 1814 | + // after the picture, so for that path this is filled in at the end. |
| 1710 | let mut packets = audio.map(|track| track.packets); | 1815 | let mut packets = audio.map(|track| track.packets); |
| 1711 | // ...and the cues with them, for the same reason: the subtitle track is | 1816 | // ...and the cues with them, for the same reason: the subtitle track is |
| 1712 | // declared in the header and its blocks are interleaved into the clusters, | 1817 | // declared in the header and its blocks are interleaved into the clusters, |
| 1713 | // so the muxer needs the lot before the first picture is written. | 1818 | // so the muxer needs the lot before the first picture is written. |
| 1714 | let mut subs = export_subtitles(project, meta, settings); | 1819 | let mut subs = export_subtitles(project, meta, settings); |
| 1715 | - // The sound is done, whichever way it went: the bar stands at the head of | 1820 | + // Whatever the sound has reached, the picture's share starts here |
| 1716 | - // the picture's own share ([`AUDIO_BAND`]). | 1821 | + // ([`AUDIO_BAND`]) -- and the bar only ever moves forwards, which is what |
| 1717 | - shared.progress.store(AUDIO_BAND, Ordering::Relaxed); | 1822 | + // `fetch_max` below keeps true while an audio pass is still publishing its |
| 1823 | + // own third of that band from the other thread. | ||
| 1824 | + shared.progress.fetch_max(AUDIO_BAND, Ordering::Relaxed); | ||
| 1718 | 1825 | ||
| 1719 | // Before an encoder is opened at all: a timeline nobody has touched, whose | 1826 | // Before an encoder is opened at all: a timeline nobody has touched, whose |
| 1720 | // sources this file can hold as they are, is written by copying their coded | 1827 | // sources this file can hold as they are, is written by copying their coded |
| @@ -1781,12 +1888,17 @@ fn run( | |||
| 1781 | // Published *after* the seat is open, so a hardware encoder the driver | 1888 | // Published *after* the seat is open, so a hardware encoder the driver |
| 1782 | // refused reads as the software one that took over rather than as the hope | 1889 | // refused reads as the software one that took over rather than as the hope |
| 1783 | // it replaced -- and the sound says whether it was copied or encoded, which | 1890 | // it replaced -- and the sound says whether it was copied or encoded, which |
| 1784 | - // `copy_audio` decided a few lines up. | 1891 | + // only `copy_audio` knows and, on the overlapped path, does not know yet. |
| 1785 | - *shared.encoders.lock().unwrap() = Some(format!( | 1892 | + let seat = encoder.label(); |
| 1786 | - "{} · {}", | 1893 | + publish_seats(shared, seat, project, settings, sound, opus, audio_job.is_some()); |
| 1787 | - encoder.label(), | 1894 | + // When the picture started, so the stage line below can say where under it |
| 1788 | - measured_audio_label(project, settings.format, sound, opus) | 1895 | + // the sound landed -- the one number that says whether the two passes |
| 1789 | - )); | 1896 | + // really overlapped, in the same voice as `encode_audio`'s own timers. |
| 1897 | + let picture_started = std::time::Instant::now(); | ||
| 1898 | + // The sound, once the pass beside this one has finished with it: an mp4 | ||
| 1899 | + // declares its audio track and writes its packets after the picture, so | ||
| 1900 | + // this is where they arrive. | ||
| 1901 | + let mut late: Option<ExportAudio> = None; | ||
| 1790 | let mut muxer = None; | 1902 | let mut muxer = None; |
| 1791 | let mut done = 0u32; | 1903 | let mut done = 0u32; |
| 1792 | let black = Black::new(meta); | 1904 | let black = Black::new(meta); |
| @@ -1873,6 +1985,27 @@ fn run( | |||
| 1873 | |offset: u32| rate.source_at(in_frame + span.speed.source_at(offset)) - opened_at; | 1985 | |offset: u32| rate.source_at(in_frame + span.speed.source_at(offset)) - opened_at; |
| 1874 | while done_here < span.len { | 1986 | while done_here < span.len { |
| 1875 | cancelled(shared)?; | 1987 | cancelled(shared)?; |
| 1988 | + // The sound's failure is the export's, and it is heard the moment | ||
| 1989 | + // it happens rather than after the last frame: a mix this engine | ||
| 1990 | + // cannot decode used to refuse in seconds, before any picture was | ||
| 1991 | + // encoded, and an overlapped pass that reported only at the end | ||
| 1992 | + // would spend the whole encode first. Also where its measured | ||
| 1993 | + // codec reaches the line on screen. | ||
| 1994 | + if audio_job | ||
| 1995 | + .as_ref() | ||
| 1996 | + .is_some_and(thread::JoinHandle::is_finished) | ||
| 1997 | + { | ||
| 1998 | + late = join_audio(audio_job.take().expect("just seen to be there"))?; | ||
| 1999 | + sound = late.as_ref().map(|track| track.copied); | ||
| 2000 | + opus = late | ||
| 2001 | + .as_ref() | ||
| 2002 | + .is_some_and(|track| track.opus_pre_skip.is_some()); | ||
| 2003 | + publish_seats(shared, seat, project, settings, sound, opus, false); | ||
| 2004 | + eprintln!( | ||
| 2005 | + "export audio: done {:.1} s into the picture", | ||
| 2006 | + picture_started.elapsed().as_secs_f64() | ||
| 2007 | + ); | ||
| 2008 | + } | ||
| 1876 | let want = source_at(done_here); | 2009 | let want = source_at(done_here); |
| 1877 | // How many timeline frames from here show that same picture: one at | 2010 | // How many timeline frames from here show that same picture: one at |
| 1878 | // real time, more when the clip is slowed or its file is slower | 2011 | // real time, more when the clip is slowed or its file is slower |
| @@ -1952,9 +2085,13 @@ fn run( | |||
| 1952 | )?; | 2085 | )?; |
| 1953 | } | 2086 | } |
| 1954 | done += 1; | 2087 | done += 1; |
| 2088 | + // Forwards only: an audio pass still running beside this one | ||
| 2089 | + // publishes its own share of [`AUDIO_BAND`], and a bar that | ||
| 2090 | + // went backwards every time it did would be worse than one | ||
| 2091 | + // that stood still. | ||
| 1955 | shared | 2092 | shared |
| 1956 | .progress | 2093 | .progress |
| 1957 | - .store(picture_progress(done, total), Ordering::Relaxed); | 2094 | + .fetch_max(picture_progress(done, total), Ordering::Relaxed); |
| 1958 | } | 2095 | } |
| 1959 | done_here += repeats; | 2096 | done_here += repeats; |
| 1960 | } | 2097 | } |
| @@ -1985,7 +2122,28 @@ fn run( | |||
| 1985 | // turned out to be. | 2122 | // turned out to be. |
| 1986 | let muxer = match muxer { | 2123 | let muxer = match muxer { |
| 1987 | Muxer::Mp4(mut mp4) => { | 2124 | Muxer::Mp4(mut mp4) => { |
| 1988 | - for packet in packets.into_iter().flatten() { | 2125 | + // The sound, collected where this file first needs it: it has been |
| 2126 | + // mixing and encoding under the whole picture, and an mp4 declares | ||
| 2127 | + // its audio track here rather than at the open precisely so that | ||
| 2128 | + // could happen ([`Mp4Muxer::add_audio_track`]). | ||
| 2129 | + let track = match audio_job.take() { | ||
| 2130 | + Some(job) => { | ||
| 2131 | + let track = join_audio(job)?; | ||
| 2132 | + // The picture finished first and this waited for the | ||
| 2133 | + // sound: the pair of stage lines is what says which of the | ||
| 2134 | + // two an export is really bounded by. | ||
| 2135 | + eprintln!( | ||
| 2136 | + "export audio: waited for after {:.1} s of picture", | ||
| 2137 | + picture_started.elapsed().as_secs_f64() | ||
| 2138 | + ); | ||
| 2139 | + track | ||
| 2140 | + } | ||
| 2141 | + None => late, | ||
| 2142 | + }; | ||
| 2143 | + if let Some(track) = &track { | ||
| 2144 | + mp4.add_audio_track(¶ms_of(track))?; | ||
| 2145 | + } | ||
| 2146 | + for packet in track.into_iter().flat_map(|track| track.packets) { | ||
| 1989 | mp4.write_audio_packet(&packet.bytes)?; | 2147 | mp4.write_audio_packet(&packet.bytes)?; |
| 1990 | } | 2148 | } |
| 1991 | mp4.write_subtitles(&subs)?; | 2149 | mp4.write_subtitles(&subs)?; |
crates/engine/src/mux.rsmodified+51 -30
| @@ -268,44 +268,65 @@ impl Mp4Muxer { | |||
| 268 | pic_param_set: video.pps.to_vec(), | 268 | pic_param_set: video.pps.to_vec(), |
| 269 | }), | 269 | }), |
| 270 | })?; | 270 | })?; |
| 271 | - if let Some(audio) = audio { | 271 | + let mut muxer = Self { |
| 272 | - // The one thing this writer must never do quietly: an `mp4a` sample | ||
| 273 | - // entry declares AAC, so Opus packets in it would be a file that | ||
| 274 | - // says one codec and holds another. `export` never asks -- Opus is | ||
| 275 | - // written for Matroska alone -- and this is the backstop that keeps | ||
| 276 | - // that true if a format is ever added on the other side. | ||
| 277 | - if audio.opus_pre_skip.is_some() { | ||
| 278 | - return Err("an Opus track in an mp4: this writer declares `mp4a` only".into()); | ||
| 279 | - } | ||
| 280 | - let freq_index = SampleFreqIndex::try_from(audio.freq_index)?; | ||
| 281 | - // The index's own rate, not `audio.sample_rate`: this is the clock | ||
| 282 | - // an `stts` counts in and the `esds` states the index, so the two | ||
| 283 | - // must not be able to disagree. | ||
| 284 | - let sample_rate = freq_index.freq(); | ||
| 285 | - writer.add_track(&TrackConfig { | ||
| 286 | - track_type: TrackType::Audio, | ||
| 287 | - timescale: sample_rate, | ||
| 288 | - language: "und".to_string(), | ||
| 289 | - media_conf: MediaConfig::AacConfig(AacConfig { | ||
| 290 | - bitrate: 0, | ||
| 291 | - profile: AudioObjectType::AacLowComplexity, | ||
| 292 | - freq_index, | ||
| 293 | - chan_conf: ChannelConfig::try_from(audio.chan_conf)?, | ||
| 294 | - }), | ||
| 295 | - })?; | ||
| 296 | - } | ||
| 297 | - | ||
| 298 | - Ok(Self { | ||
| 299 | writer, | 272 | writer, |
| 300 | frame_duration, | 273 | frame_duration, |
| 301 | - has_audio: audio.is_some(), | 274 | + has_audio: false, |
| 302 | entry, | 275 | entry, |
| 303 | colr: colr_nclx(ColorDescription::output(video.height)), | 276 | colr: colr_nclx(ColorDescription::output(video.height)), |
| 304 | path: path.to_path_buf(), | 277 | path: path.to_path_buf(), |
| 305 | timescale, | 278 | timescale, |
| 306 | frames: 0, | 279 | frames: 0, |
| 307 | sub_names: Vec::new(), | 280 | sub_names: Vec::new(), |
| 308 | - }) | 281 | + }; |
| 282 | + if let Some(audio) = audio { | ||
| 283 | + muxer.add_audio_track(audio)?; | ||
| 284 | + } | ||
| 285 | + Ok(muxer) | ||
| 286 | + } | ||
| 287 | + | ||
| 288 | + /// Declares the AAC track, which an mp4 may do at any point before its | ||
| 289 | + /// first packet is written: the sample table is built from the samples as | ||
| 290 | + /// they are handed over, and this file's audio is handed over after the | ||
| 291 | + /// whole picture ([`write_audio_packet`](Mp4Muxer::write_audio_packet)). | ||
| 292 | + /// | ||
| 293 | + /// That is what lets an export mix and encode its sound *while* it encodes | ||
| 294 | + /// the picture rather than before it: the picture's loop no longer needs to | ||
| 295 | + /// know the track's shape to start. Declaring it at the open, which is what | ||
| 296 | + /// a caller that already has the sound does, writes the same file -- | ||
| 297 | + /// `mp4 0.14` builds the movie box at `finish` from tracks in the order | ||
| 298 | + /// they were added, and the samples themselves are written in the order the | ||
| 299 | + /// caller writes them either way. | ||
| 300 | + pub fn add_audio_track(&mut self, audio: &AudioParams) -> crate::Result<()> { | ||
| 301 | + // The one thing this writer must never do quietly: an `mp4a` sample | ||
| 302 | + // entry declares AAC, so Opus packets in it would be a file that says | ||
| 303 | + // one codec and holds another. `export` never asks -- Opus is written | ||
| 304 | + // for Matroska alone -- and this is the backstop that keeps that true | ||
| 305 | + // if a format is ever added on the other side. | ||
| 306 | + if audio.opus_pre_skip.is_some() { | ||
| 307 | + return Err("an Opus track in an mp4: this writer declares `mp4a` only".into()); | ||
| 308 | + } | ||
| 309 | + if self.has_audio { | ||
| 310 | + return Err("an mp4 declares its audio track once".into()); | ||
| 311 | + } | ||
| 312 | + let freq_index = SampleFreqIndex::try_from(audio.freq_index)?; | ||
| 313 | + // The index's own rate, not `audio.sample_rate`: this is the clock an | ||
| 314 | + // `stts` counts in and the `esds` states the index, so the two must not | ||
| 315 | + // be able to disagree. | ||
| 316 | + let sample_rate = freq_index.freq(); | ||
| 317 | + self.writer.add_track(&TrackConfig { | ||
| 318 | + track_type: TrackType::Audio, | ||
| 319 | + timescale: sample_rate, | ||
| 320 | + language: "und".to_string(), | ||
| 321 | + media_conf: MediaConfig::AacConfig(AacConfig { | ||
| 322 | + bitrate: 0, | ||
| 323 | + profile: AudioObjectType::AacLowComplexity, | ||
| 324 | + freq_index, | ||
| 325 | + chan_conf: ChannelConfig::try_from(audio.chan_conf)?, | ||
| 326 | + }), | ||
| 327 | + })?; | ||
| 328 | + self.has_audio = true; | ||
| 329 | + Ok(()) | ||
| 309 | } | 330 | } |
| 310 | 331 | ||
| 311 | /// One coded picture, Annex-B framed. Parameter sets inside it are dropped | 332 | /// One coded picture, Annex-B framed. Parameter sets inside it are dropped |
scripts/bench.shmodified+8 -2
| @@ -47,11 +47,17 @@ TARGET=$(realpath -m "${CARGO_TARGET_DIR:-target}") | |||
| 47 | # The plugins are their own build: `--example` selects example targets in every | 47 | # The plugins are their own build: `--example` selects example targets in every |
| 48 | # package it is given, and a cdylib is not one, so `-p engine-hw --example | 48 | # package it is given, and a cdylib is not one, so `-p engine-hw --example |
| 49 | # bench` built no plugin at all and every run measured software while the line | 49 | # bench` built no plugin at all and every run measured software while the line |
| 50 | -# below said otherwise. engine-audio is here for the same reason -- the play | 50 | +# below said otherwise (measured 2026-08-13: the film's hardware export read |
| 51 | -# loop's underruns come from the device, and with no plugin there is no device. | 51 | +# 11.55 fps as silent software, 94.58 fps once the plugin was there). |
| 52 | +# engine-audio is here for the same reason -- the play loop's underruns come | ||
| 53 | +# from the device, and with no plugin there is no device. | ||
| 52 | cargo build --release -p engine-hw -p engine-audio || exit 1 | 54 | cargo build --release -p engine-hw -p engine-audio || exit 1 |
| 53 | cargo build --release -p engine --example bench || exit 1 | 55 | cargo build --release -p engine --example bench || exit 1 |
| 54 | BENCH="$TARGET/release/examples/bench" | 56 | BENCH="$TARGET/release/examples/bench" |
| 57 | +[ -f "$TARGET/release/libengine_hw.so" ] || { | ||
| 58 | + echo "no libengine_hw.so in $TARGET/release: every hardware row would be software" >&2 | ||
| 59 | + exit 1 | ||
| 60 | +} | ||
| 55 | # The plugin is looked for beside the running executable, and an example binary | 61 | # The plugin is looked for beside the running executable, and an example binary |
| 56 | # lives one directory below the plugin: without this, hardware decode and | 62 | # lives one directory below the plugin: without this, hardware decode and |
| 57 | # hardware encode silently fall back to software and the baseline is a lie. | 63 | # hardware encode silently fall back to software and the baseline is a lie. |
vendor/cros-codecs/src/video_frame/generic_dma_video_frame.rsmodified+48 -9
| @@ -98,6 +98,12 @@ const Y_TILE_WIDTH: usize = Y_TILE_WIDTH_IN_SUBTILES * Y_SUBTILE_WIDTH; | |||
| 98 | const Y_TILE_HEIGHT: usize = Y_TILE_HEIGHT_IN_SUBTILES * Y_SUBTILE_HEIGHT; | 98 | const Y_TILE_HEIGHT: usize = Y_TILE_HEIGHT_IN_SUBTILES * Y_SUBTILE_HEIGHT; |
| 99 | const Y_TILE_SIZE: usize = Y_TILE_WIDTH * Y_TILE_HEIGHT; | 99 | const Y_TILE_SIZE: usize = Y_TILE_WIDTH * Y_TILE_HEIGHT; |
| 100 | 100 | ||
| 101 | +/// LOCAL PATCH (see /Cargo.toml [patch.crates-io]): what one `CLFLUSH` covers, | ||
| 102 | +/// and therefore the stride the unmap below walks a buffer with. 64 bytes on | ||
| 103 | +/// every x86-64 part this runs on. | ||
| 104 | +#[cfg(target_arch = "x86_64")] | ||
| 105 | +const CACHE_LINE: usize = 64; | ||
| 106 | + | ||
| 101 | fn detile_y_tile(dst: &mut [u8], src: &[u8], width: usize, height: usize) { | 107 | fn detile_y_tile(dst: &mut [u8], src: &[u8], width: usize, height: usize) { |
| 102 | let tiles_per_row = width / Y_TILE_WIDTH; | 108 | let tiles_per_row = width / Y_TILE_WIDTH; |
| 103 | for y in 0..height { | 109 | for y in 0..height { |
| @@ -123,6 +129,11 @@ fn detile_y_tile(dst: &mut [u8], src: &[u8], width: usize, height: usize) { | |||
| 123 | pub struct DmaMapping<'a> { | 129 | pub struct DmaMapping<'a> { |
| 124 | dma_handles: Vec<BorrowedFd<'a>>, | 130 | dma_handles: Vec<BorrowedFd<'a>>, |
| 125 | addrs: Vec<NonNull<libc::c_void>>, | 131 | addrs: Vec<NonNull<libc::c_void>>, |
| 132 | + /// LOCAL PATCH (see /Cargo.toml [patch.crates-io]): what `mmap` actually | ||
| 133 | + /// returned and how much of it, which is what `munmap` has to be handed -- | ||
| 134 | + /// `addrs` above are those bases plus a plane offset that is not required | ||
| 135 | + /// to be page aligned, so unmapping *them* is EINVAL. | ||
| 136 | + maps: Vec<(NonNull<libc::c_void>, usize)>, | ||
| 126 | detiled_bufs: Vec<Vec<u8>>, | 137 | detiled_bufs: Vec<Vec<u8>>, |
| 127 | lens: Vec<usize>, | 138 | lens: Vec<usize>, |
| 128 | is_writable: bool, | 139 | is_writable: bool, |
| @@ -171,12 +182,14 @@ impl<'a> DmaMapping<'a> { | |||
| 171 | // Offsets aren't guaranteed to page aligned, so we have to map the entire FD and then | 182 | // Offsets aren't guaranteed to page aligned, so we have to map the entire FD and then |
| 172 | // do pointer arithmetic to get the right buffer. | 183 | // do pointer arithmetic to get the right buffer. |
| 173 | let mut addrs: Vec<NonNull<libc::c_void>> = vec![]; | 184 | let mut addrs: Vec<NonNull<libc::c_void>> = vec![]; |
| 185 | + let mut maps: Vec<(NonNull<libc::c_void>, usize)> = vec![]; | ||
| 174 | if borrowed_dma_handles.len() > 1 { | 186 | if borrowed_dma_handles.len() > 1 { |
| 175 | for i in 0..offsets.len() { | 187 | for i in 0..offsets.len() { |
| 176 | // SAFETY: This assumes that fd is a valid DMA buffer and that our lens and offsets | 188 | // SAFETY: This assumes that fd is a valid DMA buffer and that our lens and offsets |
| 177 | // are correct. | 189 | // are correct. |
| 190 | + let plane_size = lens[i] + offsets[i]; | ||
| 178 | addrs.push(unsafe { | 191 | addrs.push(unsafe { |
| 179 | - mmap( | 192 | + let base = mmap( |
| 180 | None, | 193 | None, |
| 181 | NonZeroUsize::new(lens[i] + offsets[i]) | 194 | NonZeroUsize::new(lens[i] + offsets[i]) |
| 182 | .ok_or("Attempted to map plane of length 0!")?, | 195 | .ok_or("Attempted to map plane of length 0!")?, |
| @@ -189,8 +202,9 @@ impl<'a> DmaMapping<'a> { | |||
| 189 | borrowed_dma_handles[i].as_fd(), | 202 | borrowed_dma_handles[i].as_fd(), |
| 190 | 0, | 203 | 0, |
| 191 | ) | 204 | ) |
| 192 | - .map_err(|err| format!("Error mapping plane {err}"))? | 205 | + .map_err(|err| format!("Error mapping plane {err}"))?; |
| 193 | - .add(offsets[i]) | 206 | + maps.push((base, plane_size)); |
| 207 | + base.add(offsets[i]) | ||
| 194 | }); | 208 | }); |
| 195 | } | 209 | } |
| 196 | } else { | 210 | } else { |
| @@ -212,6 +226,7 @@ impl<'a> DmaMapping<'a> { | |||
| 212 | 0, | 226 | 0, |
| 213 | ) | 227 | ) |
| 214 | .map_err(|err| format!("Error mapping plane {err}"))?; | 228 | .map_err(|err| format!("Error mapping plane {err}"))?; |
| 229 | + maps.push((base_addr, total_size.get())); | ||
| 215 | for i in 0..offsets.len() { | 230 | for i in 0..offsets.len() { |
| 216 | addrs.push(base_addr.add(offsets[i])); | 231 | addrs.push(base_addr.add(offsets[i])); |
| 217 | } | 232 | } |
| @@ -245,6 +260,7 @@ impl<'a> DmaMapping<'a> { | |||
| 245 | Ok(DmaMapping { | 260 | Ok(DmaMapping { |
| 246 | dma_handles: borrowed_dma_handles.clone(), | 261 | dma_handles: borrowed_dma_handles.clone(), |
| 247 | addrs: addrs, | 262 | addrs: addrs, |
| 263 | + maps: maps, | ||
| 248 | detiled_bufs: detiled_bufs, | 264 | detiled_bufs: detiled_bufs, |
| 249 | lens: lens.clone(), | 265 | lens: lens.clone(), |
| 250 | is_writable: is_writable, | 266 | is_writable: is_writable, |
| @@ -313,12 +329,29 @@ impl<'a> Drop for DmaMapping<'a> { | |||
| 313 | _mm_mfence(); | 329 | _mm_mfence(); |
| 314 | 330 | ||
| 315 | for (addr, len) in zip(self.addrs.iter(), self.lens.iter()) { | 331 | for (addr, len) in zip(self.addrs.iter(), self.lens.iter()) { |
| 316 | - // TODO: We shouldn't actually have to flush every address, we should just | 332 | + // LOCAL PATCH (see /Cargo.toml [patch.crates-io]): a cache |
| 317 | - // flush the address at the beginning of each cache line. But, during testing | 333 | + // line at a time, which is the granularity CLFLUSH has -- |
| 318 | - // this caused a race condition. | 334 | + // flushing every byte issued 64 instructions per line and |
| 319 | - for offset in 0..*len { | 335 | + // cost 6.2 ms per 1080p picture on radeonsi (measured |
| 320 | - _mm_clflush((addr.as_ptr() as *const u8).offset(offset as isize)); | 336 | + // 2026-08-13), four fifths of a hardware export's whole |
| 337 | + // per-frame budget. The upstream TODO says exactly this and | ||
| 338 | + // reports a race when it was tried; the mfence pair either | ||
| 339 | + // side is what orders the flushes, and the sixty-four | ||
| 340 | + // redundant flushes per line were never what did. | ||
| 341 | + // A plane of no bytes has no line to flush, and the last-line | ||
| 342 | + // flush below would touch the byte after the mapping. | ||
| 343 | + // Upstream's byte loop flushed nothing at all for `0..0`, | ||
| 344 | + // and this keeps that. | ||
| 345 | + if *len == 0 { | ||
| 346 | + continue; | ||
| 321 | } | 347 | } |
| 348 | + let base = addr.as_ptr() as *const u8; | ||
| 349 | + for offset in (0..*len).step_by(CACHE_LINE) { | ||
| 350 | + _mm_clflush(base.offset(offset as isize)); | ||
| 351 | + } | ||
| 352 | + // ...and the last line, where the length is not a multiple | ||
| 353 | + // of one. | ||
| 354 | + _mm_clflush(base.offset(len.saturating_sub(1) as isize)); | ||
| 322 | } | 355 | } |
| 323 | 356 | ||
| 324 | _mm_mfence(); | 357 | _mm_mfence(); |
| @@ -326,7 +359,13 @@ impl<'a> Drop for DmaMapping<'a> { | |||
| 326 | 359 | ||
| 327 | fence(Ordering::SeqCst); | 360 | fence(Ordering::SeqCst); |
| 328 | 361 | ||
| 329 | - let _ = zip(self.addrs.iter(), self.lens.iter()).map(|x| munmap(*x.0, *x.1).unwrap()); | 362 | + // LOCAL PATCH: `map` on an iterator is lazy, so the unmap upstream |
| 363 | + // writes here never ran -- every mapping leaked its address space | ||
| 364 | + // (3 MB a picture through an encode session, 2.2 GB of VSZ over a | ||
| 365 | + // 719-frame export, measured 2026-08-13). | ||
| 366 | + for (addr, len) in self.maps.iter() { | ||
| 367 | + let _ = munmap(*addr, *len); | ||
| 368 | + } | ||
| 330 | } | 369 | } |
| 331 | } | 370 | } |
| 332 | } | 371 | } |