forge
Explore
Log in

Don't you dare go Hollow

⚡ 4K HEVC export 251 -> 189 s, byte-deterministic: hw decoder reuse and next-span prefetch, encoder dmabuf import cache, persistent hw spawner thread (PDEATHSIG), mp4 interleave waits for the mix; 🐛 karaoke .ass burns via the caption path

Browse files at this commit

a888db976da3fdb5aa957111c934db0d1fa19213Ahmet Kaan GümüşParent: 902be04
crates/engine-hw/src/child.rsmodified+9 -0
@@ -153,6 +153,15 @@ fn decode(sock: &mut UnixStream, args: &[OsString]) {
153153 if tag != T_NEXT_WIDE {
154154 wide_run = 0;
155155 }
156+ if tag == T_NEXT_DMA16
157+ && let Some(pumped) = ahead.take()
158+ {
159+ let mut body = [0u8; 16];
160+ if sock.read_exact(&mut body).is_err() || answer(sock, &mut session, &mut staging, pumped).is_err() {
161+ return;
162+ }
163+ continue;
164+ }
156165 if ahead.is_some() && tag != T_NEXT_WIDE {
157166 ahead = None;
158167 if tag != T_SEEK {
crates/engine-hw/src/enc_ec.rsmodified+36 -2
@@ -39,8 +39,16 @@ pub(crate) struct EcEncSession {
3939 /// The access unit currently handed out, kept alive until the next call.
4040 out: Vec<u8>,
4141 ten_bit: bool,
42+ /// Imported decoder buffers, by the dma-buf inodes and layout they came as:
43+ /// the decoder hands the same few surfaces out again and again, and a fresh
44+ /// import costs the GPU a new mapping on its first use.
45+ imports: VecDeque<(ImportKey, Rc<ec_va::va::Surface<ec_va::surface::PrimeImport>>)>,
4246 }
4347
48+type ImportKey = (Vec<u64>, VhDma);
49+
50+const IMPORTS_MAX: usize = 32;
51+
4452 /// The `open` arguments, for any of the three codecs.
4553 pub(crate) struct EcOpen {
4654 pub codec: EncCodec,
@@ -125,6 +133,7 @@ impl EcEncSession {
125133 coded,
126134 timestamp: 0,
127135 ready: VecDeque::new(),
136+ imports: VecDeque::new(),
128137 out: Vec::new(),
129138 ten_bit,
130139 })
@@ -206,8 +215,33 @@ impl EcEncSession {
206215 /// imported surface, which owns its copies until it is dropped at the end
207216 /// of this call.
208217 pub(crate) fn encode_dma(&mut self, frame: &DmaFrame, force_keyframe: bool) -> Result<(), String> {
209- let prime = prime_from_vhdma(&frame.desc, &frame.fds)?;
210- let surface = Rc::new(ec_va::import_prime(&self.display, &prime).map_err(|e| e.to_string())?);
218+ let inodes = frame
219+ .fds
220+ .iter()
221+ .map(|fd| {
222+ use std::os::unix::fs::MetadataExt;
223+ Some(std::fs::File::from(fd.try_clone().ok()?).metadata().ok()?.ino())
224+ })
225+ .collect::<Option<Vec<u64>>>();
226+ let key = inodes.map(|inodes| (inodes, frame.desc));
227+ let cached = key
228+ .as_ref()
229+ .and_then(|key| self.imports.iter().find(|(k, _)| k == key))
230+ .map(|(_, surface)| Rc::clone(surface));
231+ let surface = match cached {
232+ Some(surface) => surface,
233+ None => {
234+ let prime = prime_from_vhdma(&frame.desc, &frame.fds)?;
235+ let surface = Rc::new(ec_va::import_prime(&self.display, &prime).map_err(|e| e.to_string())?);
236+ if let Some(key) = key {
237+ self.imports.push_back((key, Rc::clone(&surface)));
238+ if self.imports.len() > IMPORTS_MAX {
239+ self.imports.pop_front();
240+ }
241+ }
242+ surface
243+ }
244+ };
211245 let display = (self.width as u32, self.height as u32);
212246 let meta = self.meta(force_keyframe);
213247 if self.ten_bit {
crates/engine/src/export.rsmodified+253 -85
@@ -2222,6 +2222,7 @@ struct LayerFeed {
22222222 transformed: Planes,
22232223 /// The decoder, and the file frame its next picture is.
22242224 decoder: Option<(ClipDecoder, u32)>,
2225+ parked: Option<Arc<Parked>>,
22252226 /// The placed picture, and the file frame it is of.
22262227 current: Option<(u32, Planes)>,
22272228 /// The same picture composed at 10 bits ([`LayerStack::picture16`]), and the
@@ -2364,6 +2365,7 @@ impl LayerFeed {
23642365 Ok(Self {
23652366 steady,
23662367 steadied: Default::default(),
2368+ parked: None,
23672369 deint,
23682370 adjust: crate::generate::is_adjust(&info.path),
23692371 adjusted: Default::default(),
@@ -2558,7 +2560,7 @@ impl LayerFeed {
25582560 } else if backwards && !crate::is_image(&path) {
25592561 ClipDecoder::reversed(&path, want, self.info.rate.source_at(self.clip.in_frame), self.deint)
25602562 } else {
2561- ClipDecoder::open_with(&path, want, None, None, wide, self.deint)?
2563+ ClipDecoder::open_with(&path, want, None, self.parked.as_ref(), wide, self.deint)?
25622564 };
25632565 self.decoder = Some((decoder, want));
25642566 }
@@ -2923,6 +2925,13 @@ impl LayerStack {
29232925 })
29242926 }
29252927
2928+ fn park_in(mut self, lot: &Arc<Parked>) -> Self {
2929+ for feed in &mut self.feeds {
2930+ feed.parked = Some(Arc::clone(lot));
2931+ }
2932+ self
2933+ }
2934+
29262935 /// The composed I420 picture at timeline `frame`, or `None` once a clip's
29272936 /// file ends before it. The bottom clip is drawn exactly as a single clip
29282937 /// is (its bars black); each clip above lands on it where its own picture
@@ -5575,7 +5584,58 @@ fn run(
55755584 (Some(b), true) => split_spans(spans, |f| b.quiet(f, f + 1)),
55765585 _ => spans,
55775586 };
5578- for span in spans {
5587+ let dma = encoder.dma_want(meta);
5588+ let mut plans: Vec<Option<OpenPlan>> = spans
5589+ .iter()
5590+ .map(|span| {
5591+ let keyed_color = color_keyed_alone_at(project, span.start).filter(|_| ten_bit);
5592+ let (source, in_frame) = span.from.filter(|_| !(layered_at(project, span.start) && keyed_color.is_none()))?;
5593+ let entry = sources.get(source)?;
5594+ let (rate, color, _peak, rotation, pixel_aspect) = rates[source];
5595+ let deint = span_deint(project, span.start, &entry.path);
5596+ let rate = crate::deinterlace::counted_rate(deint, rate);
5597+ let mapper = tone[source].as_ref();
5598+ let dissolve = dissolve_window(project, span);
5599+ if crate::is_audio(&entry.path)
5600+ || project.composite_visualizer_at(span.start) & 1 != 0
5601+ || span.reverse
5602+ || crate::is_image(&entry.path)
5603+ {
5604+ return None;
5605+ }
5606+ let span = *span;
5607+ let untouched = mapper.is_none()
5608+ && keyed_color.is_none()
5609+ && burn.as_ref().is_none_or(|b| ten_bit && b.quiet(span.start, span.end()))
5610+ && remap_into(Some(color), false, out_color.matrix).is_none()
5611+ && project
5612+ .composite_color_at(span.start)
5613+ .is_none_or(|params| params.is_identity())
5614+ && project
5615+ .composite_transform_at(span.start)
5616+ .is_none_or(|params| params.is_identity())
5617+ // A file whose display matrix asks for a turn is *not*
5618+ // untouched, whatever else the timeline says: its pictures
5619+ // have to be turned, which is a read-back no GPU buffer
5620+ // survives. The sample aspect is the same refusal one
5621+ // stage later: its pictures have to be stretched to the
5622+ // square-pixel raster before an encoder sees them, which
5623+ // is the same kind of touch.
5624+ && rotation.is_none()
5625+ && pixel_aspect.is_square()
5626+ && dissolve.is_none()
5627+ && !picture_faded_in(project, &span);
5628+ Some(OpenPlan {
5629+ path: entry.path.clone(),
5630+ start: rate.source_at(in_frame),
5631+ untouched,
5632+ deint,
5633+ tail: span.source_window().map_or(u32::MAX, |(_, _, end)| rate.source_at(end)),
5634+ })
5635+ })
5636+ .collect();
5637+ let mut ahead: Option<((OpenPlan, Option<DmaWant>), ClipDecoder)> = None;
5638+ for (index, span) in spans.iter().copied().enumerate() {
55795639 // Every clip reopens its own source file at its own in point; the
55805640 // encoder is *not* reopened, so the export is one continuous stream
55815641 // whose GOP boundaries need not line up with the cuts -- nor with the
@@ -5611,28 +5671,8 @@ fn run(
56115671 // the fourth thing that would touch it, and the decoder answers
56125672 // that one: a picture of another size than this file's is one
56135673 // the plugin hands back as pixels ([`HwSession::next_frame_dma`]).
5614- let untouched = mapper.is_none()
5615- && keyed_color.is_none()
5616- && burn.as_ref().is_none_or(|b| ten_bit && b.quiet(span.start, span.end()))
5617- && remap_into(Some(color), false, out_color.matrix).is_none()
5618- && project
5619- .composite_color_at(span.start)
5620- .is_none_or(|params| params.is_identity())
5621- && project
5622- .composite_transform_at(span.start)
5623- .is_none_or(|params| params.is_identity())
5624- // A file whose display matrix asks for a turn is *not*
5625- // untouched, whatever else the timeline says: its pictures
5626- // have to be turned, which is a read-back no GPU buffer
5627- // survives. The sample aspect is the same refusal one
5628- // stage later: its pictures have to be stretched to the
5629- // square-pixel raster before an encoder sees them, which
5630- // is the same kind of touch.
5631- && rotation.is_none()
5632- && pixel_aspect.is_square()
5633- && dissolve.is_none()
5634- && !picture_faded_in(project, &span);
5635- let want = untouched.then(|| encoder.dma_want(meta)).flatten();
5674+ let plan = plans[index].take();
5675+ let want = plan.as_ref().is_some_and(|p| p.untouched).then(|| encoder.dma_want(meta)).flatten();
56365676 // Opened at the file's own frame, which is the only place the
56375677 // file's numbering is used -- the span's are the timeline's.
56385678 let flags = project.composite_visualizer_at(span.start);
@@ -5653,7 +5693,11 @@ fn run(
56535693 let lo = span.source_window().map_or(0, |(_, lo, _)| rate.source_at(lo));
56545694 ClipDecoder::reversed(&entry.path, rate.source_at(in_frame), lo, deint)
56555695 } else {
5656- ClipDecoder::open_with(&entry.path, rate.source_at(in_frame), want, Some(&parked), ten_bit, deint)?
5696+ let tail = span.source_window().map_or(u32::MAX, |(_, _, end)| rate.source_at(end));
5697+ match (ahead.take(), plan) {
5698+ (Some((key, decoder)), Some(plan)) if key == (plan.clone(), want) => decoder,
5699+ _ => ClipDecoder::open_span(&entry.path, rate.source_at(in_frame), want, Some(&parked), ten_bit, deint, tail)?,
5700+ }
56575701 };
56585702 (
56595703 Some(pictures),
@@ -5679,6 +5723,15 @@ fn run(
56795723 crate::demux::PixelAspect::SQUARE,
56805724 ),
56815725 };
5726+ ahead = None;
5727+ if let Some(Some(next)) = plans.get(index + 1)
5728+ && span.from.and_then(|(s, _)| sources.get(s)).is_none_or(|e| e.path != next.path)
5729+ {
5730+ let want = next.untouched.then_some(dma).flatten();
5731+ if let Ok(decoder) = ClipDecoder::open_span(&next.path, next.start, want, Some(&parked), ten_bit, next.deint, next.tail) {
5732+ ahead = Some(((next.clone(), want), decoder));
5733+ }
5734+ }
56825735 // Mixed spaces on one timeline: a clip coded against another matrix than
56835736 // the one this file declares is rewritten into it, *after* the grade --
56845737 // playback grades in the source's own space and converts for the screen
@@ -5717,7 +5770,8 @@ fn run(
57175770 out_color.matrix,
57185771 None,
57195772 Some((&shared.cancel, &shared.measuring)),
5720- )?),
5773+ )?
5774+ .park_in(&parked)),
57215775 false => None,
57225776 };
57235777 // A 10-bit export composes a layered picture at 10 bits too ([`LayerStack::picture16`]).
@@ -5849,7 +5903,8 @@ fn run(
58495903 // encoded, and an overlapped pass that reported only at the end
58505904 // would spend the whole encode first. Also where its measured
58515905 // codec reaches the line on screen.
5852- if audio_job.is_finished() {
5906+ let hold_full = audio_job.running() && matches!(&muxer, Some(Muxer::Mp4(m)) if m.holding_long());
5907+ if audio_job.is_finished() || hold_full {
58535908 late = join_audio(audio_job.take().expect("just seen to be there"))?;
58545909 sound = late.as_ref().map(|track| track.copied);
58555910 opus = late
@@ -5862,6 +5917,9 @@ fn run(
58625917 ); }
58635918 feed_late_audio(&mut muxer, &late, &mut audio_fed)?;
58645919 }
5920+ if let Some(Muxer::Mp4(mp4)) = muxer.as_mut() {
5921+ mp4.audio_pending = audio_job.running();
5922+ }
58655923 let want = source_at(done_here);
58665924 // A colour-keyed clip on the 10-bit path: this picture's grade is the
58675925 // keys' value at its first timeline frame (a slowed picture repeated
@@ -6137,8 +6195,7 @@ fn run(
61376195 };
61386196 let faded = picture_fade_at(project, frame_at).map(|k| fade_planes((y, u, v), k));
61396197 let (y, u, v) = faded.as_ref().map_or((y, u, v), borrow_planes);
6140- let painted = burned16(&mut burn, frame_at, aw, ah, (y, u, v));
6141- let (y, u, v) = painted.as_ref().map_or((y, u, v), borrow_planes);
6198+ let (y, u, v) = burned16(&mut burn, frame_at, aw, ah, (y, u, v)).unwrap_or((y, u, v));
61426199 encoder.encode_wide(y, u, v, aw, ah)?
61436200 }
61446201 (Some(d), true) => {
@@ -6211,8 +6268,7 @@ fn run(
62116268 .filter(|_| !layered_here)
62126269 .map(|k| fade_planes((y, u, v), k));
62136270 let (y, u, v) = faded.as_ref().map_or((y, u, v), borrow_planes);
6214- let painted = burned16(&mut burn, frame_at, width, height, (y, u, v));
6215- let (y, u, v) = painted.as_ref().map_or((y, u, v), borrow_planes);
6271+ let (y, u, v) = burned16(&mut burn, frame_at, width, height, (y, u, v)).unwrap_or((y, u, v));
62166272 encoder.encode_wide(y, u, v, width, height)?
62176273 }
62186274 (Frame::Dma(dma), None) => encoder.encode_dma(dma, settings.intra_only)?,
@@ -6467,6 +6523,9 @@ struct Burn {
64676523 /// One per title, the overlay it was last drawn as, with what made it ([`TitleKey`]).
64686524 title_last: Vec<Option<(TitleKey, Overlay)>>,
64696525 native: Option<Native>,
6526+ spare: Option<Planes>,
6527+ narrow: Planes,
6528+ merged: Planes16,
64706529 }
64716530
64726531 struct Native {
@@ -6479,7 +6538,7 @@ fn native_script(project: &Project, pick: usize, style: &TextStyle) -> Option<cr
64796538 return None;
64806539 }
64816540 let track = project.subtitles().get(pick)?;
6482- if track.track.is_some() {
6541+ if track.track.is_some() || track.cues.iter().any(|c| c.real_karaoke().is_some()) {
64836542 return None;
64846543 }
64856544 crate::assrender::Captions::from_file(&track.path)
@@ -6569,6 +6628,9 @@ impl Burn {
65696628 title_last: vec![None; titles.len()],
65706629 titles,
65716630 native,
6631+ spare: None,
6632+ narrow: Default::default(),
6633+ merged: Default::default(),
65726634 }))
65736635 }
65746636
@@ -6607,7 +6669,7 @@ impl Burn {
66076669 };
66086670 let mut planes = out
66096671 .take()
6610- .unwrap_or_else(|| (planes.0.to_vec(), planes.1.to_vec(), planes.2.to_vec()));
6672+ .unwrap_or_else(|| copied(self.spare.take(), planes));
66116673 if alpha == 255 {
66126674 ov.blend_i420(&mut planes.0, &mut planes.1, &mut planes.2, self.full_range);
66136675 } else {
@@ -6627,7 +6689,7 @@ impl Burn {
66276689 let t_us = (f64::from(frame) / self.fps * 1e6).round() as i64;
66286690 let mut planes = out
66296691 .take()
6630- .unwrap_or_else(|| (planes.0.to_vec(), planes.1.to_vec(), planes.2.to_vec()));
6692+ .unwrap_or_else(|| copied(self.spare.take(), planes));
66316693 native.captions.draw_i420(
66326694 (&mut planes.0, &mut planes.1, &mut planes.2),
66336695 (width, height),
@@ -6658,7 +6720,7 @@ impl Burn {
66586720 if let Some((_, _, _, _, ov)) = self.last.as_ref() {
66596721 let mut planes = out
66606722 .take()
6661- .unwrap_or_else(|| (planes.0.to_vec(), planes.1.to_vec(), planes.2.to_vec()));
6723+ .unwrap_or_else(|| copied(self.spare.take(), planes));
66626724 ov.blend_i420(&mut planes.0, &mut planes.1, &mut planes.2, self.full_range);
66636725 out = Some(planes);
66646726 }
@@ -6713,28 +6775,58 @@ fn widen_into(src: &[u8], out: &mut Vec<u16>) {
67136775 /// [`burned`] at 10 bits. A caption or a title is an 8-bit overlay, so the picture is
67146776 /// narrowed for it; where the overlay changed a code, that code is written back
67156777 /// widened, and every other code keeps its 10-bit value.
6716-fn burned16(
6717- burn: &mut Option<Burn>,
6778+fn copied(spare: Option<Planes>, planes: (&[u8], &[u8], &[u8])) -> Planes {
6779+ let mut out = spare.unwrap_or_default();
6780+ for (dst, src) in [(&mut out.0, planes.0), (&mut out.1, planes.1), (&mut out.2, planes.2)] {
6781+ dst.clear();
6782+ dst.extend_from_slice(src);
6783+ }
6784+ out
6785+}
6786+
6787+fn narrow_into(src: &[u16], out: &mut Vec<u8>) {
6788+ out.clear();
6789+ out.extend(src.iter().map(|&c| (c >> 2) as u8));
6790+}
6791+
6792+fn merge_into(orig: &[u16], before: &[u8], after: &[u8], out: &mut Vec<u16>) {
6793+ out.clear();
6794+ out.extend_from_slice(orig);
6795+ const RUN: usize = 64;
6796+ for ((o, b), a) in out.chunks_mut(RUN).zip(before.chunks(RUN)).zip(after.chunks(RUN)) {
6797+ if a != b {
6798+ for ((o, &b), &a) in o.iter_mut().zip(b).zip(a) {
6799+ if a != b {
6800+ *o = widen_code(a);
6801+ }
6802+ }
6803+ }
6804+ }
6805+}
6806+
6807+fn burned16<'a>(
6808+ burn: &'a mut Option<Burn>,
67186809 frame: u32,
67196810 width: u32,
67206811 height: u32,
67216812 planes: (&[u16], &[u16], &[u16]),
6722-) -> Option<Planes16> {
6813+) -> Option<(&'a [u16], &'a [u16], &'a [u16])> {
67236814 let burn = burn.as_mut()?;
6724- let narrow = |s: &[u16]| -> Vec<u8> { s.iter().map(|&c| (c >> 2) as u8).collect() };
6725- let (ny, nu, nv) = (narrow(planes.0), narrow(planes.1), narrow(planes.2));
6726- let painted = burn.paint(frame, width, height, (&ny[..], &nu[..], &nv[..]))?;
6727- let merge = |orig: &[u16], before: &[u8], after: &[u8]| -> Vec<u16> {
6728- orig.iter()
6729- .zip(before.iter().zip(after))
6730- .map(|(&o, (&b, &a))| if a == b { o } else { widen_code(a) })
6731- .collect()
6815+ let mut narrow = std::mem::take(&mut burn.narrow);
6816+ narrow_into(planes.0, &mut narrow.0);
6817+ narrow_into(planes.1, &mut narrow.1);
6818+ narrow_into(planes.2, &mut narrow.2);
6819+ let painted = burn.paint(frame, width, height, (&narrow.0[..], &narrow.1[..], &narrow.2[..]));
6820+ let Some(painted) = painted else {
6821+ burn.narrow = narrow;
6822+ return None;
67326823 };
6733- Some((
6734- merge(planes.0, &ny, &painted.0[..]),
6735- merge(planes.1, &nu, &painted.1[..]),
6736- merge(planes.2, &nv, &painted.2[..]),
6737- ))
6824+ merge_into(planes.0, &narrow.0, &painted.0, &mut burn.merged.0);
6825+ merge_into(planes.1, &narrow.1, &painted.1, &mut burn.merged.1);
6826+ merge_into(planes.2, &narrow.2, &painted.2, &mut burn.merged.2);
6827+ burn.narrow = narrow;
6828+ burn.spare = Some(painted);
6829+ Some((&burn.merged.0[..], &burn.merged.1[..], &burn.merged.2[..]))
67386830 }
67396831
67406832 /// The 10-bit placement's scratch: the turn, the pixel-aspect stretch, the grade and the
@@ -9761,10 +9853,24 @@ struct Streamed {
97619853 park: Option<Park>,
97629854 }
97639855
9764-/// What a software decode thread leaves behind when it is stopped: the
9765-/// decoder, and the pictures it had decoded past the last one its span took,
9766-/// in order -- the ones the channel still held, then the ones it had not sent.
9767-type Kept = (Box<SwDecoder>, VecDeque<Yuv>);
9856+/// What a decode thread leaves behind when it is stopped or runs out: the
9857+/// decoder, and the pictures from the last one its span took on, in order.
9858+/// A hardware session carries the file frame it decodes next.
9859+type Kept = (Held, VecDeque<Yuv>);
9860+
9861+enum Held {
9862+ Sw(Box<SwDecoder>),
9863+ Hw(Box<HwSession>, u32),
9864+}
9865+
9866+#[derive(Clone, PartialEq)]
9867+struct OpenPlan {
9868+ path: PathBuf,
9869+ start: u32,
9870+ untouched: bool,
9871+ deint: Deinterlace,
9872+ tail: u32,
9873+}
97689874
97699875 /// The way back from a span's [`Streamed`] to the [`Parked`] lot: the lot, the
97709876 /// file, and the flag that asks the decode thread to stop at its next picture.
@@ -9779,9 +9885,8 @@ struct Park {
97799885 /// seeking back to a sync sample and decoding the whole GOP in front of its in
97809886 /// point again (a long-GOP source pays up to a GOP per clip that way).
97819887 ///
9782-/// Only a decoder that is *resumable* is ever taken: see [`resumable`]. Hardware
9783-/// sessions are never kept, since whether a span gets one is the hardware's
9784-/// answer and not this lot's.
9888+/// Only a software decoder that is *resumable* is ever taken: see [`resumable`].
9889+/// A hardware session is taken by file and repositioned with its own seek.
97859890 #[derive(Default)]
97869891 struct Parked(Mutex<VecDeque<ParkedDecoder>>);
97879892
@@ -9793,6 +9898,11 @@ const PARKED_MAX: usize = 4;
97939898 /// pictures it decoded that no span took (see [`Kept`]).
97949899 struct ParkedDecoder {
97959900 path: PathBuf,
9901+ decoder: Held,
9902+ backlog: VecDeque<Yuv>,
9903+}
9904+
9905+struct ParkedSw {
97969906 decoder: Box<SwDecoder>,
97979907 backlog: VecDeque<Yuv>,
97989908 }
@@ -9809,20 +9919,45 @@ impl Parked {
98099919 /// The decoder that can serve a span of `path` starting at `start`, taken
98109920 /// out of the lot and wound forward to that picture: whatever it holds
98119921 /// before `start` is dropped, and the rest is what the span decodes from.
9812- fn take(&self, path: &Path, start: u32) -> Option<ParkedDecoder> {
9922+ fn take(&self, path: &Path, start: u32) -> Option<ParkedSw> {
98139923 let mut lot = self.0.lock().ok()?;
98149924 let at = lot
98159925 .iter()
98169926 .position(|entry| entry.path == path && entry.serves(start))?;
9817- let mut entry = lot.remove(at)?;
9927+ let ParkedDecoder { decoder: Held::Sw(mut decoder), mut backlog, .. } = lot.remove(at)? else {
9928+ return None;
9929+ };
98189930 let start = i64::from(start);
9819- while entry.backlog.front().is_some()
9820- && entry.decoder.index() - (entry.backlog.len() as i64) < start
9821- {
9822- entry.backlog.pop_front();
9931+ while backlog.front().is_some() && decoder.index() - (backlog.len() as i64) < start {
9932+ backlog.pop_front();
98239933 }
9824- entry.decoder.start = start as u32;
9825- Some(entry)
9934+ decoder.start = start as u32;
9935+ Some(ParkedSw { decoder, backlog })
9936+ }
9937+
9938+ fn take_hw(&self, path: &Path, start: u32, dma: bool) -> Option<(Box<HwSession>, VecDeque<Yuv>, u32)> {
9939+ let mut lot = self.0.lock().ok()?;
9940+ let at = lot
9941+ .iter()
9942+ .position(|entry| entry.path == path && matches!(entry.decoder, Held::Hw(..)))?;
9943+ let ParkedDecoder { decoder: Held::Hw(mut hw, mut next), mut backlog, .. } = lot.remove(at)? else {
9944+ return None;
9945+ };
9946+ drop(lot);
9947+ let first = next.saturating_sub(backlog.len() as u32);
9948+ let usable = (first..next).contains(&start) && (dma || !backlog.iter().any(|f| matches!(f, Yuv::Dma(_))));
9949+ if usable {
9950+ backlog.drain(..(start - first) as usize);
9951+ } else {
9952+ backlog.clear();
9953+ if start != next {
9954+ if !hw.seek(start) {
9955+ return None;
9956+ }
9957+ next = start;
9958+ }
9959+ }
9960+ Some((hw, backlog, next))
98269961 }
98279962 }
98289963
@@ -9830,14 +9965,17 @@ impl ParkedDecoder {
98309965 /// Whether this decoder can serve a span starting at `start`: asked of the
98319966 /// file itself, where a fresh decoder would seek to.
98329967 fn serves(&self, start: u32) -> bool {
9968+ let Held::Sw(decoder) = &self.decoder else {
9969+ return false;
9970+ };
98339971 let Ok((_, mut demuxer)) = Demuxer::open(&self.path) else {
98349972 return false;
98359973 };
98369974 let restart = demuxer.seek_to_sync_at_or_before(start);
98379975 resumable(
9838- self.decoder.index(),
9976+ decoder.index(),
98399977 self.backlog.len(),
9840- self.decoder.origin(),
9978+ decoder.origin(),
98419979 restart,
98429980 i64::from(start),
98439981 )
@@ -9894,11 +10032,9 @@ impl Drop for Streamed {
989410032 // next send is answered by this drain and its next look at the flag
989510033 // ends it, dropping the sender, which is what the drain waits for.
989610034 park.stop.store(true, Ordering::Relaxed);
9897- let mut backlog = VecDeque::new();
9898- // A GPU buffer is not kept: a hardware decoder is waiting on the
9899- // surfaces it has lent, and nothing here would hand them back.
10035+ let mut backlog: VecDeque<Yuv> = self.current.take().into_iter().collect();
990010036 while let Ok(item) = self.frames.recv() {
9901- if let Ok(Some(frame @ (Yuv::Pixels { .. } | Yuv::Wide { .. }))) = item {
10037+ if let Ok(Some(frame)) = item {
990210038 backlog.push_back(frame);
990310039 }
990410040 }
@@ -10008,15 +10144,28 @@ impl ClipDecoder {
1000810144 Self::open_with(path, start_frame, want, parked, wide, Deinterlace::Frame)
1000910145 }
1001010146
10147+ fn open_with(
10148+ path: &Path,
10149+ start_frame: u32,
10150+ want: Option<DmaWant>,
10151+ parked: Option<&Arc<Parked>>,
10152+ wide: bool,
10153+ deint: Deinterlace,
10154+ ) -> crate::Result<Self> {
10155+ Self::open_span(path, start_frame, want, parked, wide, deint, u32::MAX)
10156+ }
10157+
1001110158 /// [`open`](Self::open) for a clip with a deinterlace setting. `Field` over an
1001210159 /// interlaced file makes `start_frame` a field number and every picture a field.
10013- fn open_with(
10160+ /// From file frame `tail` on, GPU buffers are no longer asked for.
10161+ fn open_span(
1001410162 path: &Path,
1001510163 start_frame: u32,
1001610164 want: Option<DmaWant>,
1001710165 parked: Option<&Arc<Parked>>,
1001810166 wide: bool,
1001910167 deint: Deinterlace,
10168+ tail: u32,
1002010169 ) -> crate::Result<Self> {
1002110170 // Before either decoder: an image is not a stream, so `start_frame`
1002210171 // means nothing to it -- every frame of a still span is the same
@@ -10035,7 +10184,7 @@ impl ClipDecoder {
1003510184 let thread_park = parked.map(|lot| (Arc::clone(lot), Arc::clone(&stop)));
1003610185 let handle = thread::Builder::new()
1003710186 .name("export-decode".into())
10038- .spawn(move || decode_stream(&path, start_frame, want, &tx, thread_park, wide, deint))?;
10187+ .spawn(move || decode_stream(&path, start_frame, want, &tx, thread_park, wide, deint, tail))?;
1003910188 Ok(Self::Streamed(Streamed {
1004010189 frames,
1004110190 _thread: DecodeThread(Some(handle)),
@@ -10193,20 +10342,29 @@ fn decode_stream(
1019310342 parked: Option<(Arc<Parked>, Arc<AtomicBool>)>,
1019410343 wide: bool,
1019510344 deint: Deinterlace,
10345+ tail: u32,
1019610346 ) -> Option<Kept> {
1019710347 // A 10-bit export asks the hardware seat for whole 10-bit pictures ([`Pictures::Hw`]).
10198- let opened = match forced("VE_SW") {
10348+ let kept = (!forced("VE_SW"))
10349+ .then(|| parked.as_ref().and_then(|(lot, _)| lot.take_hw(path, start_frame, want.is_some())))
10350+ .flatten();
10351+ let mut next = start_frame;
10352+ let opened = match (forced("VE_SW"), kept) {
10353+ (false, Some((hw, backlog, at))) => {
10354+ next = at;
10355+ Some((Pictures::Hw(hw, wide), backlog))
10356+ }
1019910357 // The decode door's own gate ([`crate::decode::open_hw`]): a VP9 4:2:2 or 4:4:4
1020010358 // stream is never offered to the GPU, which would refuse it on stderr.
10201- false => crate::decode::open_hw(path, start_frame).map(|hw| Pictures::Hw(Box::new(hw), wide)),
10202- true => None,
10359+ (false, None) => crate::decode::open_hw(path, start_frame).map(|hw| (Pictures::Hw(Box::new(hw), wide), VecDeque::new())),
10360+ (true, _) => None,
1020310361 };
1020410362 if std::env::var_os("EDITH_DEBUG").is_some() {
1020510363 eprintln!("export decode: {}{}", if opened.is_some() { "hardware" } else { "software" }, if wide { ", 10-bit" } else { "" });
1020610364 }
1020710365 // Pictures decoded ahead of the span that a parked decoder still holds.
1020810366 let (mut decoder, mut backlog) = match opened {
10209- Some(hw) => (hw, VecDeque::new()),
10367+ Some(hw) => hw,
1021010368 None => match parked
1021110369 .as_ref()
1021210370 .and_then(|(lot, _)| lot.take(path, start_frame))
@@ -10233,28 +10391,35 @@ fn decode_stream(
1023310391 .is_some_and(|(_, stop)| stop.load(Ordering::Relaxed))
1023410392 {
1023510393 return match decoder {
10236- Pictures::Sw(sw) if sw.parkable() && !sw.flushed() => Some((sw, backlog)),
10394+ Pictures::Sw(sw) if sw.parkable() && !sw.flushed() => Some((Held::Sw(sw), backlog)),
10395+ Pictures::Hw(hw, _) => Some((Held::Hw(hw, next), backlog)),
1023710396 _ => None,
1023810397 };
1023910398 }
1024010399 // Hardware that ends before its first picture has failed the same way
1024110400 // one that errors there has: the mid-GOP AV1 seek ends the stream with
1024210401 // nothing (see `decode::run_hw`), and it falls back here too.
10243- let next = match backlog.pop_front() {
10402+ let pulled = match backlog.pop_front() {
1024410403 Some(frame) => Ok(Some(frame)),
10245- None => decoder.next(want),
10404+ None => {
10405+ next += 1;
10406+ decoder.next(want.filter(|_| next <= tail))
10407+ }
1024610408 };
10247- let next = match next {
10409+ let pulled = match pulled {
1024810410 Ok(None) if decoded == 0 && matches!(decoder, Pictures::Hw(..)) => {
1024910411 Err("hardware gave no picture from the start frame".into())
1025010412 }
1025110413 other => other,
1025210414 };
10253- let frame = match next {
10415+ let frame = match pulled {
1025410416 Ok(Some(frame)) => frame,
1025510417 Ok(None) => {
1025610418 let _ = tx.send(Ok(None));
10257- return None;
10419+ return match decoder {
10420+ Pictures::Hw(hw, _) if parked.is_some() => Some((Held::Hw(hw, next - 1), backlog)),
10421+ _ => None,
10422+ };
1025810423 }
1025910424 Err(e) => {
1026010425 if matches!(decoder, Pictures::Hw(..)) {
@@ -12073,6 +12238,9 @@ mod burn_stack_tests {
1207312238 titles: Vec::new(),
1207412239 title_last: Vec::new(),
1207512240 native: None,
12241+ spare: None,
12242+ narrow: Default::default(),
12243+ merged: Default::default(),
1207612244 };
1207712245 let y = vec![40u8; (w * h) as usize];
1207812246 let u = vec![128u8; (w / 2 * (h / 2)) as usize];
@@ -12382,7 +12550,7 @@ mod vp9_444_tests {
1238212550 assert_eq!(chroma, Some(Chroma::C444), "the fixture is a 4:4:4 stream");
1238312551 let (tx, rx) = sync_channel(64);
1238412552 let before = crate::hw::OPEN_ATTEMPTS.with(|n| n.get());
12385- let _ = decode_stream(&path, 0, None, &tx, None, false, Deinterlace::Frame);
12553+ let _ = decode_stream(&path, 0, None, &tx, None, false, Deinterlace::Frame, u32::MAX);
1238612554 let after = crate::hw::OPEN_ATTEMPTS.with(|n| n.get());
1238712555 drop(rx);
1238812556 let _ = std::fs::remove_file(&path);
crates/engine/src/hw.rsmodified+1 -1
@@ -493,7 +493,7 @@ impl Drop for HwSession {
493493
494494 /// What an encoder needs a decoded buffer to look like before it can read it
495495 /// without a copy: the surface's coded size and the picture inside it.
496-#[derive(Clone, Copy)]
496+#[derive(Clone, Copy, PartialEq, Eq)]
497497 pub struct DmaWant {
498498 pub coded_width: u32,
499499 pub coded_height: u32,
crates/engine/src/hwproc.rsmodified+17 -0
@@ -515,6 +515,23 @@ pub fn available() -> bool {
515515 /// reads our stdout as JSON-RPC only. `None` when there is no child binary or
516516 /// it will not start.
517517 pub fn spawn_child(args: &[OsString]) -> Option<(Child, UnixStream)> {
518+ type Job = (Vec<OsString>, std::sync::mpsc::Sender<Option<(Child, UnixStream)>>);
519+ static SPAWNER: std::sync::OnceLock<std::sync::mpsc::Sender<Job>> = std::sync::OnceLock::new();
520+ let jobs = SPAWNER.get_or_init(|| {
521+ let (tx, rx) = std::sync::mpsc::channel::<Job>();
522+ let _ = std::thread::Builder::new().name("hw-spawn".into()).spawn(move || {
523+ for (args, back) in rx {
524+ let _ = back.send(spawn_here(&args));
525+ }
526+ });
527+ tx
528+ });
529+ let (back, answer) = std::sync::mpsc::channel();
530+ jobs.send((args.to_vec(), back)).ok()?;
531+ answer.recv().ok()?
532+}
533+
534+fn spawn_here(args: &[OsString]) -> Option<(Child, UnixStream)> {
518535 let bin = child_path()?;
519536 let (mine, theirs) = UnixStream::pair().ok()?;
520537 mine.set_read_timeout(Some(timeout())).ok()?;
crates/engine/src/mux.rsmodified+13 -7
@@ -187,17 +187,16 @@ pub struct Mp4Muxer {
187187 /// two tracks' bytes end up beside each other in `mdat` rather than one
188188 /// whole track then the other. `(bytes, is_sync)`.
189189 ///
190- /// NONDETERMINISM: how tightly the two interleave depends on when the
191- /// mix thread's join lands relative to the picture loop -- a mix that
192- /// finishes before this hold fills stays byte-interleaved from the
193- /// start; a mix that lands late only interleaves the tail. A test on
194- /// this has to pin that landing (force the join before frame N in a
195- /// fixture) rather than race the real mixer thread.
190+ /// While [`audio_pending`](Mp4Muxer::audio_pending) is set the hold never
191+ /// flushes video-only, so the interleave depends on timestamps alone and
192+ /// not on when the mix lands; `export` joins the mix once the hold passes
193+ /// [`HOLD_SECONDS`] to bound its memory.
196194 hold: VecDeque<(Vec<u8>, bool)>,
197195 /// `hold`'s span, in the video track's own ticks -- flushed video-only
198196 /// once it passes [`HOLD_SECONDS`], so a mix that never lands (or lands
199197 /// very late) cannot stall the encode behind an unbounded queue.
200198 hold_ticks: u64,
199+ pub audio_pending: bool,
201200 /// AAC packets handed over by [`write_audio_packet`](Mp4Muxer::write_audio_packet)
202201 /// before `drain` has caught up to them -- normally empty the instant
203202 /// after that call returns; only grows past one packet where the whole
@@ -334,6 +333,7 @@ impl Mp4Muxer {
334333 frames: 0,
335334 hold: VecDeque::new(),
336335 hold_ticks: 0,
336+ audio_pending: false,
337337 audio_queue: VecDeque::new(),
338338 audio_ticks: 0,
339339 flushed_video_ticks: 0,
@@ -460,6 +460,7 @@ impl Mp4Muxer {
460460 frames: 0,
461461 hold: VecDeque::new(),
462462 hold_ticks: 0,
463+ audio_pending: false,
463464 audio_queue: VecDeque::new(),
464465 audio_ticks: 0,
465466 flushed_video_ticks: 0,
@@ -509,6 +510,7 @@ impl Mp4Muxer {
509510 let mut info = StreamInfo::new(self.streams, TimeBase::from_rate(sample_rate), params);
510511 info.language = Some(mp4_language(audio.language.as_deref().unwrap_or("und")));
511512 self.audio_stream = self.add_stream(info)?;
513+ self.audio_pending = false;
512514 self.has_audio = true;
513515 self.audio_rate = sample_rate;
514516 Ok(())
@@ -619,7 +621,7 @@ impl Mp4Muxer {
619621 self.flush_video_front()?;
620622 }
621623 }
622- (Some(_), None) if self.hold_ticks > HOLD_SECONDS * u64::from(self.timescale) => {
624+ (Some(_), None) if !self.audio_pending && self.holding_long() => {
623625 self.flush_video_front()?;
624626 }
625627 // Sound with no picture to wait for is written as it arrives.
@@ -630,6 +632,10 @@ impl Mp4Muxer {
630632 Ok(())
631633 }
632634
635+ pub fn holding_long(&self) -> bool {
636+ self.hold_ticks > HOLD_SECONDS * u64::from(self.timescale)
637+ }
638+
633639 fn flush_video_front(&mut self) -> crate::Result<()> {
634640 let Some((bytes, is_sync)) = self.hold.pop_front() else {
635641 return Ok(());
crates/engine/tests/export.rsmodified+6 -2
@@ -1930,7 +1930,9 @@ fn a_wedged_child_is_waited_out_by_its_own_measure_not_the_ceiling() {
19301930 let started = Instant::now();
19311931 let wedged = encoder
19321932 .encode(&y, &u, &v, width, height, false)
1933- .expect_err("a child that stops answering is not an encode");
1933+ .err()
1934+ .or_else(|| encoder.drain().err())
1935+ .expect("a child that stops answering is not an encode");
19341936 let waited = started.elapsed();
19351937 println!("wedge at the shipping default: contained in {waited:.2?}");
19361938 assert!(engine::hwproc::is_lost(&wedged), "{wedged}");
@@ -2066,7 +2068,9 @@ fn a_dead_encoder_answers_every_later_call_the_same_way() {
20662068 );
20672069 let died = encoder
20682070 .encode(&y, &u, &v, width, height, false)
2069- .expect_err("the second picture kills the child");
2071+ .err()
2072+ .or_else(|| encoder.drain().err())
2073+ .expect("the second picture kills the child");
20702074 assert!(
20712075 engine::hwproc::is_lost(&died),
20722076 "an encoder death must say so: {died}"