diff --git a/crates/engine-hw/src/child.rs b/crates/engine-hw/src/child.rs index a71fd13..fade0b4 100644 --- a/crates/engine-hw/src/child.rs +++ b/crates/engine-hw/src/child.rs @@ -153,6 +153,15 @@ fn decode(sock: &mut UnixStream, args: &[OsString]) { if tag != T_NEXT_WIDE { wide_run = 0; } + if tag == T_NEXT_DMA16 + && let Some(pumped) = ahead.take() + { + let mut body = [0u8; 16]; + if sock.read_exact(&mut body).is_err() || answer(sock, &mut session, &mut staging, pumped).is_err() { + return; + } + continue; + } if ahead.is_some() && tag != T_NEXT_WIDE { ahead = None; if tag != T_SEEK { diff --git a/crates/engine-hw/src/enc_ec.rs b/crates/engine-hw/src/enc_ec.rs index 1ace824..40fbee8 100644 --- a/crates/engine-hw/src/enc_ec.rs +++ b/crates/engine-hw/src/enc_ec.rs @@ -39,8 +39,16 @@ pub(crate) struct EcEncSession { /// The access unit currently handed out, kept alive until the next call. out: Vec, ten_bit: bool, + /// Imported decoder buffers, by the dma-buf inodes and layout they came as: + /// the decoder hands the same few surfaces out again and again, and a fresh + /// import costs the GPU a new mapping on its first use. + imports: VecDeque<(ImportKey, Rc>)>, } +type ImportKey = (Vec, VhDma); + +const IMPORTS_MAX: usize = 32; + /// The `open` arguments, for any of the three codecs. pub(crate) struct EcOpen { pub codec: EncCodec, @@ -125,6 +133,7 @@ impl EcEncSession { coded, timestamp: 0, ready: VecDeque::new(), + imports: VecDeque::new(), out: Vec::new(), ten_bit, }) @@ -206,8 +215,33 @@ impl EcEncSession { /// imported surface, which owns its copies until it is dropped at the end /// of this call. pub(crate) fn encode_dma(&mut self, frame: &DmaFrame, force_keyframe: bool) -> Result<(), String> { - let prime = prime_from_vhdma(&frame.desc, &frame.fds)?; - let surface = Rc::new(ec_va::import_prime(&self.display, &prime).map_err(|e| e.to_string())?); + let inodes = frame + .fds + .iter() + .map(|fd| { + use std::os::unix::fs::MetadataExt; + Some(std::fs::File::from(fd.try_clone().ok()?).metadata().ok()?.ino()) + }) + .collect::>>(); + let key = inodes.map(|inodes| (inodes, frame.desc)); + let cached = key + .as_ref() + .and_then(|key| self.imports.iter().find(|(k, _)| k == key)) + .map(|(_, surface)| Rc::clone(surface)); + let surface = match cached { + Some(surface) => surface, + None => { + let prime = prime_from_vhdma(&frame.desc, &frame.fds)?; + let surface = Rc::new(ec_va::import_prime(&self.display, &prime).map_err(|e| e.to_string())?); + if let Some(key) = key { + self.imports.push_back((key, Rc::clone(&surface))); + if self.imports.len() > IMPORTS_MAX { + self.imports.pop_front(); + } + } + surface + } + }; let display = (self.width as u32, self.height as u32); let meta = self.meta(force_keyframe); if self.ten_bit { diff --git a/crates/engine/src/export.rs b/crates/engine/src/export.rs index 092c53b..e4ddeef 100644 --- a/crates/engine/src/export.rs +++ b/crates/engine/src/export.rs @@ -2222,6 +2222,7 @@ struct LayerFeed { transformed: Planes, /// The decoder, and the file frame its next picture is. decoder: Option<(ClipDecoder, u32)>, + parked: Option>, /// The placed picture, and the file frame it is of. current: Option<(u32, Planes)>, /// The same picture composed at 10 bits ([`LayerStack::picture16`]), and the @@ -2364,6 +2365,7 @@ impl LayerFeed { Ok(Self { steady, steadied: Default::default(), + parked: None, deint, adjust: crate::generate::is_adjust(&info.path), adjusted: Default::default(), @@ -2558,7 +2560,7 @@ impl LayerFeed { } else if backwards && !crate::is_image(&path) { ClipDecoder::reversed(&path, want, self.info.rate.source_at(self.clip.in_frame), self.deint) } else { - ClipDecoder::open_with(&path, want, None, None, wide, self.deint)? + ClipDecoder::open_with(&path, want, None, self.parked.as_ref(), wide, self.deint)? }; self.decoder = Some((decoder, want)); } @@ -2923,6 +2925,13 @@ impl LayerStack { }) } + fn park_in(mut self, lot: &Arc) -> Self { + for feed in &mut self.feeds { + feed.parked = Some(Arc::clone(lot)); + } + self + } + /// The composed I420 picture at timeline `frame`, or `None` once a clip's /// file ends before it. The bottom clip is drawn exactly as a single clip /// is (its bars black); each clip above lands on it where its own picture @@ -5575,7 +5584,58 @@ fn run( (Some(b), true) => split_spans(spans, |f| b.quiet(f, f + 1)), _ => spans, }; - for span in spans { + let dma = encoder.dma_want(meta); + let mut plans: Vec> = spans + .iter() + .map(|span| { + let keyed_color = color_keyed_alone_at(project, span.start).filter(|_| ten_bit); + let (source, in_frame) = span.from.filter(|_| !(layered_at(project, span.start) && keyed_color.is_none()))?; + let entry = sources.get(source)?; + let (rate, color, _peak, rotation, pixel_aspect) = rates[source]; + let deint = span_deint(project, span.start, &entry.path); + let rate = crate::deinterlace::counted_rate(deint, rate); + let mapper = tone[source].as_ref(); + let dissolve = dissolve_window(project, span); + if crate::is_audio(&entry.path) + || project.composite_visualizer_at(span.start) & 1 != 0 + || span.reverse + || crate::is_image(&entry.path) + { + return None; + } + let span = *span; + let untouched = mapper.is_none() + && keyed_color.is_none() + && burn.as_ref().is_none_or(|b| ten_bit && b.quiet(span.start, span.end())) + && remap_into(Some(color), false, out_color.matrix).is_none() + && project + .composite_color_at(span.start) + .is_none_or(|params| params.is_identity()) + && project + .composite_transform_at(span.start) + .is_none_or(|params| params.is_identity()) + // A file whose display matrix asks for a turn is *not* + // untouched, whatever else the timeline says: its pictures + // have to be turned, which is a read-back no GPU buffer + // survives. The sample aspect is the same refusal one + // stage later: its pictures have to be stretched to the + // square-pixel raster before an encoder sees them, which + // is the same kind of touch. + && rotation.is_none() + && pixel_aspect.is_square() + && dissolve.is_none() + && !picture_faded_in(project, &span); + Some(OpenPlan { + path: entry.path.clone(), + start: rate.source_at(in_frame), + untouched, + deint, + tail: span.source_window().map_or(u32::MAX, |(_, _, end)| rate.source_at(end)), + }) + }) + .collect(); + let mut ahead: Option<((OpenPlan, Option), ClipDecoder)> = None; + for (index, span) in spans.iter().copied().enumerate() { // Every clip reopens its own source file at its own in point; the // encoder is *not* reopened, so the export is one continuous stream // whose GOP boundaries need not line up with the cuts -- nor with the @@ -5611,28 +5671,8 @@ fn run( // the fourth thing that would touch it, and the decoder answers // that one: a picture of another size than this file's is one // the plugin hands back as pixels ([`HwSession::next_frame_dma`]). - let untouched = mapper.is_none() - && keyed_color.is_none() - && burn.as_ref().is_none_or(|b| ten_bit && b.quiet(span.start, span.end())) - && remap_into(Some(color), false, out_color.matrix).is_none() - && project - .composite_color_at(span.start) - .is_none_or(|params| params.is_identity()) - && project - .composite_transform_at(span.start) - .is_none_or(|params| params.is_identity()) - // A file whose display matrix asks for a turn is *not* - // untouched, whatever else the timeline says: its pictures - // have to be turned, which is a read-back no GPU buffer - // survives. The sample aspect is the same refusal one - // stage later: its pictures have to be stretched to the - // square-pixel raster before an encoder sees them, which - // is the same kind of touch. - && rotation.is_none() - && pixel_aspect.is_square() - && dissolve.is_none() - && !picture_faded_in(project, &span); - let want = untouched.then(|| encoder.dma_want(meta)).flatten(); + let plan = plans[index].take(); + let want = plan.as_ref().is_some_and(|p| p.untouched).then(|| encoder.dma_want(meta)).flatten(); // Opened at the file's own frame, which is the only place the // file's numbering is used -- the span's are the timeline's. let flags = project.composite_visualizer_at(span.start); @@ -5653,7 +5693,11 @@ fn run( let lo = span.source_window().map_or(0, |(_, lo, _)| rate.source_at(lo)); ClipDecoder::reversed(&entry.path, rate.source_at(in_frame), lo, deint) } else { - ClipDecoder::open_with(&entry.path, rate.source_at(in_frame), want, Some(&parked), ten_bit, deint)? + let tail = span.source_window().map_or(u32::MAX, |(_, _, end)| rate.source_at(end)); + match (ahead.take(), plan) { + (Some((key, decoder)), Some(plan)) if key == (plan.clone(), want) => decoder, + _ => ClipDecoder::open_span(&entry.path, rate.source_at(in_frame), want, Some(&parked), ten_bit, deint, tail)?, + } }; ( Some(pictures), @@ -5679,6 +5723,15 @@ fn run( crate::demux::PixelAspect::SQUARE, ), }; + ahead = None; + if let Some(Some(next)) = plans.get(index + 1) + && span.from.and_then(|(s, _)| sources.get(s)).is_none_or(|e| e.path != next.path) + { + let want = next.untouched.then_some(dma).flatten(); + if let Ok(decoder) = ClipDecoder::open_span(&next.path, next.start, want, Some(&parked), ten_bit, next.deint, next.tail) { + ahead = Some(((next.clone(), want), decoder)); + } + } // Mixed spaces on one timeline: a clip coded against another matrix than // the one this file declares is rewritten into it, *after* the grade -- // playback grades in the source's own space and converts for the screen @@ -5717,7 +5770,8 @@ fn run( out_color.matrix, None, Some((&shared.cancel, &shared.measuring)), - )?), + )? + .park_in(&parked)), false => None, }; // A 10-bit export composes a layered picture at 10 bits too ([`LayerStack::picture16`]). @@ -5849,7 +5903,8 @@ fn run( // encoded, and an overlapped pass that reported only at the end // would spend the whole encode first. Also where its measured // codec reaches the line on screen. - if audio_job.is_finished() { + let hold_full = audio_job.running() && matches!(&muxer, Some(Muxer::Mp4(m)) if m.holding_long()); + if audio_job.is_finished() || hold_full { late = join_audio(audio_job.take().expect("just seen to be there"))?; sound = late.as_ref().map(|track| track.copied); opus = late @@ -5862,6 +5917,9 @@ fn run( ); } feed_late_audio(&mut muxer, &late, &mut audio_fed)?; } + if let Some(Muxer::Mp4(mp4)) = muxer.as_mut() { + mp4.audio_pending = audio_job.running(); + } let want = source_at(done_here); // A colour-keyed clip on the 10-bit path: this picture's grade is the // keys' value at its first timeline frame (a slowed picture repeated @@ -6137,8 +6195,7 @@ fn run( }; let faded = picture_fade_at(project, frame_at).map(|k| fade_planes((y, u, v), k)); let (y, u, v) = faded.as_ref().map_or((y, u, v), borrow_planes); - let painted = burned16(&mut burn, frame_at, aw, ah, (y, u, v)); - let (y, u, v) = painted.as_ref().map_or((y, u, v), borrow_planes); + let (y, u, v) = burned16(&mut burn, frame_at, aw, ah, (y, u, v)).unwrap_or((y, u, v)); encoder.encode_wide(y, u, v, aw, ah)? } (Some(d), true) => { @@ -6211,8 +6268,7 @@ fn run( .filter(|_| !layered_here) .map(|k| fade_planes((y, u, v), k)); let (y, u, v) = faded.as_ref().map_or((y, u, v), borrow_planes); - let painted = burned16(&mut burn, frame_at, width, height, (y, u, v)); - let (y, u, v) = painted.as_ref().map_or((y, u, v), borrow_planes); + let (y, u, v) = burned16(&mut burn, frame_at, width, height, (y, u, v)).unwrap_or((y, u, v)); encoder.encode_wide(y, u, v, width, height)? } (Frame::Dma(dma), None) => encoder.encode_dma(dma, settings.intra_only)?, @@ -6467,6 +6523,9 @@ struct Burn { /// One per title, the overlay it was last drawn as, with what made it ([`TitleKey`]). title_last: Vec>, native: Option, + spare: Option, + narrow: Planes, + merged: Planes16, } struct Native { @@ -6479,7 +6538,7 @@ fn native_script(project: &Project, pick: usize, style: &TextStyle) -> Option) { /// [`burned`] at 10 bits. A caption or a title is an 8-bit overlay, so the picture is /// narrowed for it; where the overlay changed a code, that code is written back /// widened, and every other code keeps its 10-bit value. -fn burned16( - burn: &mut Option, +fn copied(spare: Option, planes: (&[u8], &[u8], &[u8])) -> Planes { + let mut out = spare.unwrap_or_default(); + for (dst, src) in [(&mut out.0, planes.0), (&mut out.1, planes.1), (&mut out.2, planes.2)] { + dst.clear(); + dst.extend_from_slice(src); + } + out +} + +fn narrow_into(src: &[u16], out: &mut Vec) { + out.clear(); + out.extend(src.iter().map(|&c| (c >> 2) as u8)); +} + +fn merge_into(orig: &[u16], before: &[u8], after: &[u8], out: &mut Vec) { + out.clear(); + out.extend_from_slice(orig); + const RUN: usize = 64; + for ((o, b), a) in out.chunks_mut(RUN).zip(before.chunks(RUN)).zip(after.chunks(RUN)) { + if a != b { + for ((o, &b), &a) in o.iter_mut().zip(b).zip(a) { + if a != b { + *o = widen_code(a); + } + } + } + } +} + +fn burned16<'a>( + burn: &'a mut Option, frame: u32, width: u32, height: u32, planes: (&[u16], &[u16], &[u16]), -) -> Option { +) -> Option<(&'a [u16], &'a [u16], &'a [u16])> { let burn = burn.as_mut()?; - let narrow = |s: &[u16]| -> Vec { s.iter().map(|&c| (c >> 2) as u8).collect() }; - let (ny, nu, nv) = (narrow(planes.0), narrow(planes.1), narrow(planes.2)); - let painted = burn.paint(frame, width, height, (&ny[..], &nu[..], &nv[..]))?; - let merge = |orig: &[u16], before: &[u8], after: &[u8]| -> Vec { - orig.iter() - .zip(before.iter().zip(after)) - .map(|(&o, (&b, &a))| if a == b { o } else { widen_code(a) }) - .collect() + let mut narrow = std::mem::take(&mut burn.narrow); + narrow_into(planes.0, &mut narrow.0); + narrow_into(planes.1, &mut narrow.1); + narrow_into(planes.2, &mut narrow.2); + let painted = burn.paint(frame, width, height, (&narrow.0[..], &narrow.1[..], &narrow.2[..])); + let Some(painted) = painted else { + burn.narrow = narrow; + return None; }; - Some(( - merge(planes.0, &ny, &painted.0[..]), - merge(planes.1, &nu, &painted.1[..]), - merge(planes.2, &nv, &painted.2[..]), - )) + merge_into(planes.0, &narrow.0, &painted.0, &mut burn.merged.0); + merge_into(planes.1, &narrow.1, &painted.1, &mut burn.merged.1); + merge_into(planes.2, &narrow.2, &painted.2, &mut burn.merged.2); + burn.narrow = narrow; + burn.spare = Some(painted); + Some((&burn.merged.0[..], &burn.merged.1[..], &burn.merged.2[..])) } /// The 10-bit placement's scratch: the turn, the pixel-aspect stretch, the grade and the @@ -9761,10 +9853,24 @@ struct Streamed { park: Option, } -/// What a software decode thread leaves behind when it is stopped: the -/// decoder, and the pictures it had decoded past the last one its span took, -/// in order -- the ones the channel still held, then the ones it had not sent. -type Kept = (Box, VecDeque); +/// What a decode thread leaves behind when it is stopped or runs out: the +/// decoder, and the pictures from the last one its span took on, in order. +/// A hardware session carries the file frame it decodes next. +type Kept = (Held, VecDeque); + +enum Held { + Sw(Box), + Hw(Box, u32), +} + +#[derive(Clone, PartialEq)] +struct OpenPlan { + path: PathBuf, + start: u32, + untouched: bool, + deint: Deinterlace, + tail: u32, +} /// The way back from a span's [`Streamed`] to the [`Parked`] lot: the lot, the /// file, and the flag that asks the decode thread to stop at its next picture. @@ -9779,9 +9885,8 @@ struct Park { /// seeking back to a sync sample and decoding the whole GOP in front of its in /// point again (a long-GOP source pays up to a GOP per clip that way). /// -/// Only a decoder that is *resumable* is ever taken: see [`resumable`]. Hardware -/// sessions are never kept, since whether a span gets one is the hardware's -/// answer and not this lot's. +/// Only a software decoder that is *resumable* is ever taken: see [`resumable`]. +/// A hardware session is taken by file and repositioned with its own seek. #[derive(Default)] struct Parked(Mutex>); @@ -9793,6 +9898,11 @@ const PARKED_MAX: usize = 4; /// pictures it decoded that no span took (see [`Kept`]). struct ParkedDecoder { path: PathBuf, + decoder: Held, + backlog: VecDeque, +} + +struct ParkedSw { decoder: Box, backlog: VecDeque, } @@ -9809,20 +9919,45 @@ impl Parked { /// The decoder that can serve a span of `path` starting at `start`, taken /// out of the lot and wound forward to that picture: whatever it holds /// before `start` is dropped, and the rest is what the span decodes from. - fn take(&self, path: &Path, start: u32) -> Option { + fn take(&self, path: &Path, start: u32) -> Option { let mut lot = self.0.lock().ok()?; let at = lot .iter() .position(|entry| entry.path == path && entry.serves(start))?; - let mut entry = lot.remove(at)?; + let ParkedDecoder { decoder: Held::Sw(mut decoder), mut backlog, .. } = lot.remove(at)? else { + return None; + }; let start = i64::from(start); - while entry.backlog.front().is_some() - && entry.decoder.index() - (entry.backlog.len() as i64) < start - { - entry.backlog.pop_front(); + while backlog.front().is_some() && decoder.index() - (backlog.len() as i64) < start { + backlog.pop_front(); } - entry.decoder.start = start as u32; - Some(entry) + decoder.start = start as u32; + Some(ParkedSw { decoder, backlog }) + } + + fn take_hw(&self, path: &Path, start: u32, dma: bool) -> Option<(Box, VecDeque, u32)> { + let mut lot = self.0.lock().ok()?; + let at = lot + .iter() + .position(|entry| entry.path == path && matches!(entry.decoder, Held::Hw(..)))?; + let ParkedDecoder { decoder: Held::Hw(mut hw, mut next), mut backlog, .. } = lot.remove(at)? else { + return None; + }; + drop(lot); + let first = next.saturating_sub(backlog.len() as u32); + let usable = (first..next).contains(&start) && (dma || !backlog.iter().any(|f| matches!(f, Yuv::Dma(_)))); + if usable { + backlog.drain(..(start - first) as usize); + } else { + backlog.clear(); + if start != next { + if !hw.seek(start) { + return None; + } + next = start; + } + } + Some((hw, backlog, next)) } } @@ -9830,14 +9965,17 @@ impl ParkedDecoder { /// Whether this decoder can serve a span starting at `start`: asked of the /// file itself, where a fresh decoder would seek to. fn serves(&self, start: u32) -> bool { + let Held::Sw(decoder) = &self.decoder else { + return false; + }; let Ok((_, mut demuxer)) = Demuxer::open(&self.path) else { return false; }; let restart = demuxer.seek_to_sync_at_or_before(start); resumable( - self.decoder.index(), + decoder.index(), self.backlog.len(), - self.decoder.origin(), + decoder.origin(), restart, i64::from(start), ) @@ -9894,11 +10032,9 @@ impl Drop for Streamed { // next send is answered by this drain and its next look at the flag // ends it, dropping the sender, which is what the drain waits for. park.stop.store(true, Ordering::Relaxed); - let mut backlog = VecDeque::new(); - // A GPU buffer is not kept: a hardware decoder is waiting on the - // surfaces it has lent, and nothing here would hand them back. + let mut backlog: VecDeque = self.current.take().into_iter().collect(); while let Ok(item) = self.frames.recv() { - if let Ok(Some(frame @ (Yuv::Pixels { .. } | Yuv::Wide { .. }))) = item { + if let Ok(Some(frame)) = item { backlog.push_back(frame); } } @@ -10008,15 +10144,28 @@ impl ClipDecoder { Self::open_with(path, start_frame, want, parked, wide, Deinterlace::Frame) } + fn open_with( + path: &Path, + start_frame: u32, + want: Option, + parked: Option<&Arc>, + wide: bool, + deint: Deinterlace, + ) -> crate::Result { + Self::open_span(path, start_frame, want, parked, wide, deint, u32::MAX) + } + /// [`open`](Self::open) for a clip with a deinterlace setting. `Field` over an /// interlaced file makes `start_frame` a field number and every picture a field. - fn open_with( + /// From file frame `tail` on, GPU buffers are no longer asked for. + fn open_span( path: &Path, start_frame: u32, want: Option, parked: Option<&Arc>, wide: bool, deint: Deinterlace, + tail: u32, ) -> crate::Result { // Before either decoder: an image is not a stream, so `start_frame` // means nothing to it -- every frame of a still span is the same @@ -10035,7 +10184,7 @@ impl ClipDecoder { let thread_park = parked.map(|lot| (Arc::clone(lot), Arc::clone(&stop))); let handle = thread::Builder::new() .name("export-decode".into()) - .spawn(move || decode_stream(&path, start_frame, want, &tx, thread_park, wide, deint))?; + .spawn(move || decode_stream(&path, start_frame, want, &tx, thread_park, wide, deint, tail))?; Ok(Self::Streamed(Streamed { frames, _thread: DecodeThread(Some(handle)), @@ -10193,20 +10342,29 @@ fn decode_stream( parked: Option<(Arc, Arc)>, wide: bool, deint: Deinterlace, + tail: u32, ) -> Option { // A 10-bit export asks the hardware seat for whole 10-bit pictures ([`Pictures::Hw`]). - let opened = match forced("VE_SW") { + let kept = (!forced("VE_SW")) + .then(|| parked.as_ref().and_then(|(lot, _)| lot.take_hw(path, start_frame, want.is_some()))) + .flatten(); + let mut next = start_frame; + let opened = match (forced("VE_SW"), kept) { + (false, Some((hw, backlog, at))) => { + next = at; + Some((Pictures::Hw(hw, wide), backlog)) + } // The decode door's own gate ([`crate::decode::open_hw`]): a VP9 4:2:2 or 4:4:4 // stream is never offered to the GPU, which would refuse it on stderr. - false => crate::decode::open_hw(path, start_frame).map(|hw| Pictures::Hw(Box::new(hw), wide)), - true => None, + (false, None) => crate::decode::open_hw(path, start_frame).map(|hw| (Pictures::Hw(Box::new(hw), wide), VecDeque::new())), + (true, _) => None, }; if std::env::var_os("EDITH_DEBUG").is_some() { eprintln!("export decode: {}{}", if opened.is_some() { "hardware" } else { "software" }, if wide { ", 10-bit" } else { "" }); } // Pictures decoded ahead of the span that a parked decoder still holds. let (mut decoder, mut backlog) = match opened { - Some(hw) => (hw, VecDeque::new()), + Some(hw) => hw, None => match parked .as_ref() .and_then(|(lot, _)| lot.take(path, start_frame)) @@ -10233,28 +10391,35 @@ fn decode_stream( .is_some_and(|(_, stop)| stop.load(Ordering::Relaxed)) { return match decoder { - Pictures::Sw(sw) if sw.parkable() && !sw.flushed() => Some((sw, backlog)), + Pictures::Sw(sw) if sw.parkable() && !sw.flushed() => Some((Held::Sw(sw), backlog)), + Pictures::Hw(hw, _) => Some((Held::Hw(hw, next), backlog)), _ => None, }; } // Hardware that ends before its first picture has failed the same way // one that errors there has: the mid-GOP AV1 seek ends the stream with // nothing (see `decode::run_hw`), and it falls back here too. - let next = match backlog.pop_front() { + let pulled = match backlog.pop_front() { Some(frame) => Ok(Some(frame)), - None => decoder.next(want), + None => { + next += 1; + decoder.next(want.filter(|_| next <= tail)) + } }; - let next = match next { + let pulled = match pulled { Ok(None) if decoded == 0 && matches!(decoder, Pictures::Hw(..)) => { Err("hardware gave no picture from the start frame".into()) } other => other, }; - let frame = match next { + let frame = match pulled { Ok(Some(frame)) => frame, Ok(None) => { let _ = tx.send(Ok(None)); - return None; + return match decoder { + Pictures::Hw(hw, _) if parked.is_some() => Some((Held::Hw(hw, next - 1), backlog)), + _ => None, + }; } Err(e) => { if matches!(decoder, Pictures::Hw(..)) { @@ -12073,6 +12238,9 @@ mod burn_stack_tests { titles: Vec::new(), title_last: Vec::new(), native: None, + spare: None, + narrow: Default::default(), + merged: Default::default(), }; let y = vec![40u8; (w * h) as usize]; let u = vec![128u8; (w / 2 * (h / 2)) as usize]; @@ -12382,7 +12550,7 @@ mod vp9_444_tests { assert_eq!(chroma, Some(Chroma::C444), "the fixture is a 4:4:4 stream"); let (tx, rx) = sync_channel(64); let before = crate::hw::OPEN_ATTEMPTS.with(|n| n.get()); - let _ = decode_stream(&path, 0, None, &tx, None, false, Deinterlace::Frame); + let _ = decode_stream(&path, 0, None, &tx, None, false, Deinterlace::Frame, u32::MAX); let after = crate::hw::OPEN_ATTEMPTS.with(|n| n.get()); drop(rx); let _ = std::fs::remove_file(&path); diff --git a/crates/engine/src/hw.rs b/crates/engine/src/hw.rs index ff57a0f..0bad414 100644 --- a/crates/engine/src/hw.rs +++ b/crates/engine/src/hw.rs @@ -493,7 +493,7 @@ impl Drop for HwSession { /// What an encoder needs a decoded buffer to look like before it can read it /// without a copy: the surface's coded size and the picture inside it. -#[derive(Clone, Copy)] +#[derive(Clone, Copy, PartialEq, Eq)] pub struct DmaWant { pub coded_width: u32, pub coded_height: u32, diff --git a/crates/engine/src/hwproc.rs b/crates/engine/src/hwproc.rs index a393adc..7863831 100644 --- a/crates/engine/src/hwproc.rs +++ b/crates/engine/src/hwproc.rs @@ -515,6 +515,23 @@ pub fn available() -> bool { /// reads our stdout as JSON-RPC only. `None` when there is no child binary or /// it will not start. pub fn spawn_child(args: &[OsString]) -> Option<(Child, UnixStream)> { + type Job = (Vec, std::sync::mpsc::Sender>); + static SPAWNER: std::sync::OnceLock> = std::sync::OnceLock::new(); + let jobs = SPAWNER.get_or_init(|| { + let (tx, rx) = std::sync::mpsc::channel::(); + let _ = std::thread::Builder::new().name("hw-spawn".into()).spawn(move || { + for (args, back) in rx { + let _ = back.send(spawn_here(&args)); + } + }); + tx + }); + let (back, answer) = std::sync::mpsc::channel(); + jobs.send((args.to_vec(), back)).ok()?; + answer.recv().ok()? +} + +fn spawn_here(args: &[OsString]) -> Option<(Child, UnixStream)> { let bin = child_path()?; let (mine, theirs) = UnixStream::pair().ok()?; mine.set_read_timeout(Some(timeout())).ok()?; diff --git a/crates/engine/src/mux.rs b/crates/engine/src/mux.rs index b0ea168..56e4b46 100644 --- a/crates/engine/src/mux.rs +++ b/crates/engine/src/mux.rs @@ -187,17 +187,16 @@ pub struct Mp4Muxer { /// two tracks' bytes end up beside each other in `mdat` rather than one /// whole track then the other. `(bytes, is_sync)`. /// - /// NONDETERMINISM: how tightly the two interleave depends on when the - /// mix thread's join lands relative to the picture loop -- a mix that - /// finishes before this hold fills stays byte-interleaved from the - /// start; a mix that lands late only interleaves the tail. A test on - /// this has to pin that landing (force the join before frame N in a - /// fixture) rather than race the real mixer thread. + /// While [`audio_pending`](Mp4Muxer::audio_pending) is set the hold never + /// flushes video-only, so the interleave depends on timestamps alone and + /// not on when the mix lands; `export` joins the mix once the hold passes + /// [`HOLD_SECONDS`] to bound its memory. hold: VecDeque<(Vec, bool)>, /// `hold`'s span, in the video track's own ticks -- flushed video-only /// once it passes [`HOLD_SECONDS`], so a mix that never lands (or lands /// very late) cannot stall the encode behind an unbounded queue. hold_ticks: u64, + pub audio_pending: bool, /// AAC packets handed over by [`write_audio_packet`](Mp4Muxer::write_audio_packet) /// before `drain` has caught up to them -- normally empty the instant /// after that call returns; only grows past one packet where the whole @@ -334,6 +333,7 @@ impl Mp4Muxer { frames: 0, hold: VecDeque::new(), hold_ticks: 0, + audio_pending: false, audio_queue: VecDeque::new(), audio_ticks: 0, flushed_video_ticks: 0, @@ -460,6 +460,7 @@ impl Mp4Muxer { frames: 0, hold: VecDeque::new(), hold_ticks: 0, + audio_pending: false, audio_queue: VecDeque::new(), audio_ticks: 0, flushed_video_ticks: 0, @@ -509,6 +510,7 @@ impl Mp4Muxer { let mut info = StreamInfo::new(self.streams, TimeBase::from_rate(sample_rate), params); info.language = Some(mp4_language(audio.language.as_deref().unwrap_or("und"))); self.audio_stream = self.add_stream(info)?; + self.audio_pending = false; self.has_audio = true; self.audio_rate = sample_rate; Ok(()) @@ -619,7 +621,7 @@ impl Mp4Muxer { self.flush_video_front()?; } } - (Some(_), None) if self.hold_ticks > HOLD_SECONDS * u64::from(self.timescale) => { + (Some(_), None) if !self.audio_pending && self.holding_long() => { self.flush_video_front()?; } // Sound with no picture to wait for is written as it arrives. @@ -630,6 +632,10 @@ impl Mp4Muxer { Ok(()) } + pub fn holding_long(&self) -> bool { + self.hold_ticks > HOLD_SECONDS * u64::from(self.timescale) + } + fn flush_video_front(&mut self) -> crate::Result<()> { let Some((bytes, is_sync)) = self.hold.pop_front() else { return Ok(()); diff --git a/crates/engine/tests/export.rs b/crates/engine/tests/export.rs index 677d123..a8950d6 100644 --- a/crates/engine/tests/export.rs +++ b/crates/engine/tests/export.rs @@ -1930,7 +1930,9 @@ fn a_wedged_child_is_waited_out_by_its_own_measure_not_the_ceiling() { let started = Instant::now(); let wedged = encoder .encode(&y, &u, &v, width, height, false) - .expect_err("a child that stops answering is not an encode"); + .err() + .or_else(|| encoder.drain().err()) + .expect("a child that stops answering is not an encode"); let waited = started.elapsed(); println!("wedge at the shipping default: contained in {waited:.2?}"); assert!(engine::hwproc::is_lost(&wedged), "{wedged}"); @@ -2066,7 +2068,9 @@ fn a_dead_encoder_answers_every_later_call_the_same_way() { ); let died = encoder .encode(&y, &u, &v, width, height, false) - .expect_err("the second picture kills the child"); + .err() + .or_else(|| encoder.drain().err()) + .expect("the second picture kills the child"); assert!( engine::hwproc::is_lost(&died), "an encoder death must say so: {died}"