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]) {
153 if tag != T_NEXT_WIDE {153 if tag != T_NEXT_WIDE {
154 wide_run = 0;154 wide_run = 0;
155 }155 }
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+ }
156 if ahead.is_some() && tag != T_NEXT_WIDE {165 if ahead.is_some() && tag != T_NEXT_WIDE {
157 ahead = None;166 ahead = None;
158 if tag != T_SEEK {167 if tag != T_SEEK {
crates/engine-hw/src/enc_ec.rsmodified+36 -2
@@ -39,8 +39,16 @@ pub(crate) struct EcEncSession {
39 /// The access unit currently handed out, kept alive until the next call.39 /// The access unit currently handed out, kept alive until the next call.
40 out: Vec<u8>,40 out: Vec<u8>,
41 ten_bit: bool,41 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>>)>,
42 }46 }
43 47
48+type ImportKey = (Vec<u64>, VhDma);
49+
50+const IMPORTS_MAX: usize = 32;
51+
44 /// The `open` arguments, for any of the three codecs.52 /// The `open` arguments, for any of the three codecs.
45 pub(crate) struct EcOpen {53 pub(crate) struct EcOpen {
46 pub codec: EncCodec,54 pub codec: EncCodec,
@@ -125,6 +133,7 @@ impl EcEncSession {
125 coded,133 coded,
126 timestamp: 0,134 timestamp: 0,
127 ready: VecDeque::new(),135 ready: VecDeque::new(),
136+ imports: VecDeque::new(),
128 out: Vec::new(),137 out: Vec::new(),
129 ten_bit,138 ten_bit,
130 })139 })
@@ -206,8 +215,33 @@ impl EcEncSession {
206 /// imported surface, which owns its copies until it is dropped at the end215 /// imported surface, which owns its copies until it is dropped at the end
207 /// of this call.216 /// of this call.
208 pub(crate) fn encode_dma(&mut self, frame: &DmaFrame, force_keyframe: bool) -> Result<(), String> {217 pub(crate) fn encode_dma(&mut self, frame: &DmaFrame, force_keyframe: bool) -> Result<(), String> {
209- let prime = prime_from_vhdma(&frame.desc, &frame.fds)?;218+ let inodes = frame
210- let surface = Rc::new(ec_va::import_prime(&self.display, &prime).map_err(|e| e.to_string())?);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+ };
211 let display = (self.width as u32, self.height as u32);245 let display = (self.width as u32, self.height as u32);
212 let meta = self.meta(force_keyframe);246 let meta = self.meta(force_keyframe);
213 if self.ten_bit {247 if self.ten_bit {
crates/engine/src/export.rsmodified+253 -85
@@ -2222,6 +2222,7 @@ struct LayerFeed {
2222 transformed: Planes,2222 transformed: Planes,
2223 /// The decoder, and the file frame its next picture is.2223 /// The decoder, and the file frame its next picture is.
2224 decoder: Option<(ClipDecoder, u32)>,2224 decoder: Option<(ClipDecoder, u32)>,
2225+ parked: Option<Arc<Parked>>,
2225 /// The placed picture, and the file frame it is of.2226 /// The placed picture, and the file frame it is of.
2226 current: Option<(u32, Planes)>,2227 current: Option<(u32, Planes)>,
2227 /// The same picture composed at 10 bits ([`LayerStack::picture16`]), and the2228 /// The same picture composed at 10 bits ([`LayerStack::picture16`]), and the
@@ -2364,6 +2365,7 @@ impl LayerFeed {
2364 Ok(Self {2365 Ok(Self {
2365 steady,2366 steady,
2366 steadied: Default::default(),2367 steadied: Default::default(),
2368+ parked: None,
2367 deint,2369 deint,
2368 adjust: crate::generate::is_adjust(&info.path),2370 adjust: crate::generate::is_adjust(&info.path),
2369 adjusted: Default::default(),2371 adjusted: Default::default(),
@@ -2558,7 +2560,7 @@ impl LayerFeed {
2558 } else if backwards && !crate::is_image(&path) {2560 } else if backwards && !crate::is_image(&path) {
2559 ClipDecoder::reversed(&path, want, self.info.rate.source_at(self.clip.in_frame), self.deint)2561 ClipDecoder::reversed(&path, want, self.info.rate.source_at(self.clip.in_frame), self.deint)
2560 } else {2562 } 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)?
2562 };2564 };
2563 self.decoder = Some((decoder, want));2565 self.decoder = Some((decoder, want));
2564 }2566 }
@@ -2923,6 +2925,13 @@ impl LayerStack {
2923 })2925 })
2924 }2926 }
2925 2927
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+
2926 /// The composed I420 picture at timeline `frame`, or `None` once a clip's2935 /// The composed I420 picture at timeline `frame`, or `None` once a clip's
2927 /// file ends before it. The bottom clip is drawn exactly as a single clip2936 /// file ends before it. The bottom clip is drawn exactly as a single clip
2928 /// is (its bars black); each clip above lands on it where its own picture2937 /// is (its bars black); each clip above lands on it where its own picture
@@ -5575,7 +5584,58 @@ fn run(
5575 (Some(b), true) => split_spans(spans, |f| b.quiet(f, f + 1)),5584 (Some(b), true) => split_spans(spans, |f| b.quiet(f, f + 1)),
5576 _ => spans,5585 _ => spans,
5577 };5586 };
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() {
5579 // Every clip reopens its own source file at its own in point; the5639 // Every clip reopens its own source file at its own in point; the
5580 // encoder is *not* reopened, so the export is one continuous stream5640 // encoder is *not* reopened, so the export is one continuous stream
5581 // whose GOP boundaries need not line up with the cuts -- nor with the5641 // whose GOP boundaries need not line up with the cuts -- nor with the
@@ -5611,28 +5671,8 @@ fn run(
5611 // the fourth thing that would touch it, and the decoder answers5671 // the fourth thing that would touch it, and the decoder answers
5612 // that one: a picture of another size than this file's is one5672 // that one: a picture of another size than this file's is one
5613 // the plugin hands back as pixels ([`HwSession::next_frame_dma`]).5673 // the plugin hands back as pixels ([`HwSession::next_frame_dma`]).
5614- let untouched = mapper.is_none()5674+ let plan = plans[index].take();
5615- && keyed_color.is_none()5675+ let want = plan.as_ref().is_some_and(|p| p.untouched).then(|| encoder.dma_want(meta)).flatten();
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();
5636 // Opened at the file's own frame, which is the only place the5676 // Opened at the file's own frame, which is the only place the
5637 // file's numbering is used -- the span's are the timeline's.5677 // file's numbering is used -- the span's are the timeline's.
5638 let flags = project.composite_visualizer_at(span.start);5678 let flags = project.composite_visualizer_at(span.start);
@@ -5653,7 +5693,11 @@ fn run(
5653 let lo = span.source_window().map_or(0, |(_, lo, _)| rate.source_at(lo));5693 let lo = span.source_window().map_or(0, |(_, lo, _)| rate.source_at(lo));
5654 ClipDecoder::reversed(&entry.path, rate.source_at(in_frame), lo, deint)5694 ClipDecoder::reversed(&entry.path, rate.source_at(in_frame), lo, deint)
5655 } else {5695 } 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+ }
5657 };5701 };
5658 (5702 (
5659 Some(pictures),5703 Some(pictures),
@@ -5679,6 +5723,15 @@ fn run(
5679 crate::demux::PixelAspect::SQUARE,5723 crate::demux::PixelAspect::SQUARE,
5680 ),5724 ),
5681 };5725 };
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+ }
5682 // Mixed spaces on one timeline: a clip coded against another matrix than5735 // Mixed spaces on one timeline: a clip coded against another matrix than
5683 // the one this file declares is rewritten into it, *after* the grade --5736 // the one this file declares is rewritten into it, *after* the grade --
5684 // playback grades in the source's own space and converts for the screen5737 // playback grades in the source's own space and converts for the screen
@@ -5717,7 +5770,8 @@ fn run(
5717 out_color.matrix,5770 out_color.matrix,
5718 None,5771 None,
5719 Some((&shared.cancel, &shared.measuring)),5772 Some((&shared.cancel, &shared.measuring)),
5720- )?),5773+ )?
5774+ .park_in(&parked)),
5721 false => None,5775 false => None,
5722 };5776 };
5723 // A 10-bit export composes a layered picture at 10 bits too ([`LayerStack::picture16`]).5777 // A 10-bit export composes a layered picture at 10 bits too ([`LayerStack::picture16`]).
@@ -5849,7 +5903,8 @@ fn run(
5849 // encoded, and an overlapped pass that reported only at the end5903 // encoded, and an overlapped pass that reported only at the end
5850 // would spend the whole encode first. Also where its measured5904 // would spend the whole encode first. Also where its measured
5851 // codec reaches the line on screen.5905 // 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 {
5853 late = join_audio(audio_job.take().expect("just seen to be there"))?;5908 late = join_audio(audio_job.take().expect("just seen to be there"))?;
5854 sound = late.as_ref().map(|track| track.copied);5909 sound = late.as_ref().map(|track| track.copied);
5855 opus = late5910 opus = late
@@ -5862,6 +5917,9 @@ fn run(
5862 ); }5917 ); }
5863 feed_late_audio(&mut muxer, &late, &mut audio_fed)?;5918 feed_late_audio(&mut muxer, &late, &mut audio_fed)?;
5864 }5919 }
5920+ if let Some(Muxer::Mp4(mp4)) = muxer.as_mut() {
5921+ mp4.audio_pending = audio_job.running();
5922+ }
5865 let want = source_at(done_here);5923 let want = source_at(done_here);
5866 // A colour-keyed clip on the 10-bit path: this picture's grade is the5924 // A colour-keyed clip on the 10-bit path: this picture's grade is the
5867 // keys' value at its first timeline frame (a slowed picture repeated5925 // keys' value at its first timeline frame (a slowed picture repeated
@@ -6137,8 +6195,7 @@ fn run(
6137 };6195 };
6138 let faded = picture_fade_at(project, frame_at).map(|k| fade_planes((y, u, v), k));6196 let faded = picture_fade_at(project, frame_at).map(|k| fade_planes((y, u, v), k));
6139 let (y, u, v) = faded.as_ref().map_or((y, u, v), borrow_planes);6197 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));6198+ let (y, u, v) = burned16(&mut burn, frame_at, aw, ah, (y, u, v)).unwrap_or((y, u, v));
6141- let (y, u, v) = painted.as_ref().map_or((y, u, v), borrow_planes);
6142 encoder.encode_wide(y, u, v, aw, ah)?6199 encoder.encode_wide(y, u, v, aw, ah)?
6143 }6200 }
6144 (Some(d), true) => {6201 (Some(d), true) => {
@@ -6211,8 +6268,7 @@ fn run(
6211 .filter(|_| !layered_here)6268 .filter(|_| !layered_here)
6212 .map(|k| fade_planes((y, u, v), k));6269 .map(|k| fade_planes((y, u, v), k));
6213 let (y, u, v) = faded.as_ref().map_or((y, u, v), borrow_planes);6270 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));6271+ let (y, u, v) = burned16(&mut burn, frame_at, width, height, (y, u, v)).unwrap_or((y, u, v));
6215- let (y, u, v) = painted.as_ref().map_or((y, u, v), borrow_planes);
6216 encoder.encode_wide(y, u, v, width, height)?6272 encoder.encode_wide(y, u, v, width, height)?
6217 }6273 }
6218 (Frame::Dma(dma), None) => encoder.encode_dma(dma, settings.intra_only)?,6274 (Frame::Dma(dma), None) => encoder.encode_dma(dma, settings.intra_only)?,
@@ -6467,6 +6523,9 @@ struct Burn {
6467 /// One per title, the overlay it was last drawn as, with what made it ([`TitleKey`]).6523 /// One per title, the overlay it was last drawn as, with what made it ([`TitleKey`]).
6468 title_last: Vec<Option<(TitleKey, Overlay)>>,6524 title_last: Vec<Option<(TitleKey, Overlay)>>,
6469 native: Option<Native>,6525 native: Option<Native>,
6526+ spare: Option<Planes>,
6527+ narrow: Planes,
6528+ merged: Planes16,
6470 }6529 }
6471 6530
6472 struct Native {6531 struct Native {
@@ -6479,7 +6538,7 @@ fn native_script(project: &Project, pick: usize, style: &TextStyle) -> Option<cr
6479 return None;6538 return None;
6480 }6539 }
6481 let track = project.subtitles().get(pick)?;6540 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()) {
6483 return None;6542 return None;
6484 }6543 }
6485 crate::assrender::Captions::from_file(&track.path)6544 crate::assrender::Captions::from_file(&track.path)
@@ -6569,6 +6628,9 @@ impl Burn {
6569 title_last: vec![None; titles.len()],6628 title_last: vec![None; titles.len()],
6570 titles,6629 titles,
6571 native,6630 native,
6631+ spare: None,
6632+ narrow: Default::default(),
6633+ merged: Default::default(),
6572 }))6634 }))
6573 }6635 }
6574 6636
@@ -6607,7 +6669,7 @@ impl Burn {
6607 };6669 };
6608 let mut planes = out6670 let mut planes = out
6609 .take()6671 .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));
6611 if alpha == 255 {6673 if alpha == 255 {
6612 ov.blend_i420(&mut planes.0, &mut planes.1, &mut planes.2, self.full_range);6674 ov.blend_i420(&mut planes.0, &mut planes.1, &mut planes.2, self.full_range);
6613 } else {6675 } else {
@@ -6627,7 +6689,7 @@ impl Burn {
6627 let t_us = (f64::from(frame) / self.fps * 1e6).round() as i64;6689 let t_us = (f64::from(frame) / self.fps * 1e6).round() as i64;
6628 let mut planes = out6690 let mut planes = out
6629 .take()6691 .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));
6631 native.captions.draw_i420(6693 native.captions.draw_i420(
6632 (&mut planes.0, &mut planes.1, &mut planes.2),6694 (&mut planes.0, &mut planes.1, &mut planes.2),
6633 (width, height),6695 (width, height),
@@ -6658,7 +6720,7 @@ impl Burn {
6658 if let Some((_, _, _, _, ov)) = self.last.as_ref() {6720 if let Some((_, _, _, _, ov)) = self.last.as_ref() {
6659 let mut planes = out6721 let mut planes = out
6660 .take()6722 .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));
6662 ov.blend_i420(&mut planes.0, &mut planes.1, &mut planes.2, self.full_range);6724 ov.blend_i420(&mut planes.0, &mut planes.1, &mut planes.2, self.full_range);
6663 out = Some(planes);6725 out = Some(planes);
6664 }6726 }
@@ -6713,28 +6775,58 @@ fn widen_into(src: &[u8], out: &mut Vec<u16>) {
6713 /// [`burned`] at 10 bits. A caption or a title is an 8-bit overlay, so the picture is6775 /// [`burned`] at 10 bits. A caption or a title is an 8-bit overlay, so the picture is
6714 /// narrowed for it; where the overlay changed a code, that code is written back6776 /// narrowed for it; where the overlay changed a code, that code is written back
6715 /// widened, and every other code keeps its 10-bit value.6777 /// widened, and every other code keeps its 10-bit value.
6716-fn burned16(6778+fn copied(spare: Option<Planes>, planes: (&[u8], &[u8], &[u8])) -> Planes {
6717- burn: &mut Option<Burn>,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>,
6718 frame: u32,6809 frame: u32,
6719 width: u32,6810 width: u32,
6720 height: u32,6811 height: u32,
6721 planes: (&[u16], &[u16], &[u16]),6812 planes: (&[u16], &[u16], &[u16]),
6722-) -> Option<Planes16> {6813+) -> Option<(&'a [u16], &'a [u16], &'a [u16])> {
6723 let burn = burn.as_mut()?;6814 let burn = burn.as_mut()?;
6724- let narrow = |s: &[u16]| -> Vec<u8> { s.iter().map(|&c| (c >> 2) as u8).collect() };6815+ let mut narrow = std::mem::take(&mut burn.narrow);
6725- let (ny, nu, nv) = (narrow(planes.0), narrow(planes.1), narrow(planes.2));6816+ narrow_into(planes.0, &mut narrow.0);
6726- let painted = burn.paint(frame, width, height, (&ny[..], &nu[..], &nv[..]))?;6817+ narrow_into(planes.1, &mut narrow.1);
6727- let merge = |orig: &[u16], before: &[u8], after: &[u8]| -> Vec<u16> {6818+ narrow_into(planes.2, &mut narrow.2);
6728- orig.iter()6819+ let painted = burn.paint(frame, width, height, (&narrow.0[..], &narrow.1[..], &narrow.2[..]));
6729- .zip(before.iter().zip(after))6820+ let Some(painted) = painted else {
6730- .map(|(&o, (&b, &a))| if a == b { o } else { widen_code(a) })6821+ burn.narrow = narrow;
6731- .collect()6822+ return None;
6732 };6823 };
6733- Some((6824+ merge_into(planes.0, &narrow.0, &painted.0, &mut burn.merged.0);
6734- merge(planes.0, &ny, &painted.0[..]),6825+ merge_into(planes.1, &narrow.1, &painted.1, &mut burn.merged.1);
6735- merge(planes.1, &nu, &painted.1[..]),6826+ merge_into(planes.2, &narrow.2, &painted.2, &mut burn.merged.2);
6736- merge(planes.2, &nv, &painted.2[..]),6827+ burn.narrow = narrow;
6737- ))6828+ burn.spare = Some(painted);
6829+ Some((&burn.merged.0[..], &burn.merged.1[..], &burn.merged.2[..]))
6738 }6830 }
6739 6831
6740 /// The 10-bit placement's scratch: the turn, the pixel-aspect stretch, the grade and the6832 /// The 10-bit placement's scratch: the turn, the pixel-aspect stretch, the grade and the
@@ -9761,10 +9853,24 @@ struct Streamed {
9761 park: Option<Park>,9853 park: Option<Park>,
9762 }9854 }
9763 9855
9764-/// What a software decode thread leaves behind when it is stopped: the9856+/// What a decode thread leaves behind when it is stopped or runs out: the
9765-/// decoder, and the pictures it had decoded past the last one its span took,9857+/// decoder, and the pictures from the last one its span took on, in order.
9766-/// in order -- the ones the channel still held, then the ones it had not sent.9858+/// A hardware session carries the file frame it decodes next.
9767-type Kept = (Box<SwDecoder>, VecDeque<Yuv>);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+}
9768 9874
9769 /// The way back from a span's [`Streamed`] to the [`Parked`] lot: the lot, the9875 /// The way back from a span's [`Streamed`] to the [`Parked`] lot: the lot, the
9770 /// file, and the flag that asks the decode thread to stop at its next picture.9876 /// file, and the flag that asks the decode thread to stop at its next picture.
@@ -9779,9 +9885,8 @@ struct Park {
9779 /// seeking back to a sync sample and decoding the whole GOP in front of its in9885 /// seeking back to a sync sample and decoding the whole GOP in front of its in
9780 /// point again (a long-GOP source pays up to a GOP per clip that way).9886 /// point again (a long-GOP source pays up to a GOP per clip that way).
9781 ///9887 ///
9782-/// Only a decoder that is *resumable* is ever taken: see [`resumable`]. Hardware9888+/// Only a software decoder that is *resumable* is ever taken: see [`resumable`].
9783-/// sessions are never kept, since whether a span gets one is the hardware's9889+/// A hardware session is taken by file and repositioned with its own seek.
9784-/// answer and not this lot's.
9785 #[derive(Default)]9890 #[derive(Default)]
9786 struct Parked(Mutex<VecDeque<ParkedDecoder>>);9891 struct Parked(Mutex<VecDeque<ParkedDecoder>>);
9787 9892
@@ -9793,6 +9898,11 @@ const PARKED_MAX: usize = 4;
9793 /// pictures it decoded that no span took (see [`Kept`]).9898 /// pictures it decoded that no span took (see [`Kept`]).
9794 struct ParkedDecoder {9899 struct ParkedDecoder {
9795 path: PathBuf,9900 path: PathBuf,
9901+ decoder: Held,
9902+ backlog: VecDeque<Yuv>,
9903+}
9904+
9905+struct ParkedSw {
9796 decoder: Box<SwDecoder>,9906 decoder: Box<SwDecoder>,
9797 backlog: VecDeque<Yuv>,9907 backlog: VecDeque<Yuv>,
9798 }9908 }
@@ -9809,20 +9919,45 @@ impl Parked {
9809 /// The decoder that can serve a span of `path` starting at `start`, taken9919 /// The decoder that can serve a span of `path` starting at `start`, taken
9810 /// out of the lot and wound forward to that picture: whatever it holds9920 /// out of the lot and wound forward to that picture: whatever it holds
9811 /// before `start` is dropped, and the rest is what the span decodes from.9921 /// 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> {
9813 let mut lot = self.0.lock().ok()?;9923 let mut lot = self.0.lock().ok()?;
9814 let at = lot9924 let at = lot
9815 .iter()9925 .iter()
9816 .position(|entry| entry.path == path && entry.serves(start))?;9926 .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+ };
9818 let start = i64::from(start);9930 let start = i64::from(start);
9819- while entry.backlog.front().is_some()9931+ while backlog.front().is_some() && decoder.index() - (backlog.len() as i64) < start {
9820- && entry.decoder.index() - (entry.backlog.len() as i64) < start9932+ backlog.pop_front();
9821- {
9822- entry.backlog.pop_front();
9823 }9933 }
9824- entry.decoder.start = start as u32;9934+ decoder.start = start as u32;
9825- Some(entry)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))
9826 }9961 }
9827 }9962 }
9828 9963
@@ -9830,14 +9965,17 @@ impl ParkedDecoder {
9830 /// Whether this decoder can serve a span starting at `start`: asked of the9965 /// Whether this decoder can serve a span starting at `start`: asked of the
9831 /// file itself, where a fresh decoder would seek to.9966 /// file itself, where a fresh decoder would seek to.
9832 fn serves(&self, start: u32) -> bool {9967 fn serves(&self, start: u32) -> bool {
9968+ let Held::Sw(decoder) = &self.decoder else {
9969+ return false;
9970+ };
9833 let Ok((_, mut demuxer)) = Demuxer::open(&self.path) else {9971 let Ok((_, mut demuxer)) = Demuxer::open(&self.path) else {
9834 return false;9972 return false;
9835 };9973 };
9836 let restart = demuxer.seek_to_sync_at_or_before(start);9974 let restart = demuxer.seek_to_sync_at_or_before(start);
9837 resumable(9975 resumable(
9838- self.decoder.index(),9976+ decoder.index(),
9839 self.backlog.len(),9977 self.backlog.len(),
9840- self.decoder.origin(),9978+ decoder.origin(),
9841 restart,9979 restart,
9842 i64::from(start),9980 i64::from(start),
9843 )9981 )
@@ -9894,11 +10032,9 @@ impl Drop for Streamed {
9894 // next send is answered by this drain and its next look at the flag10032 // next send is answered by this drain and its next look at the flag
9895 // ends it, dropping the sender, which is what the drain waits for.10033 // ends it, dropping the sender, which is what the drain waits for.
9896 park.stop.store(true, Ordering::Relaxed);10034 park.stop.store(true, Ordering::Relaxed);
9897- let mut backlog = VecDeque::new();10035+ let mut backlog: VecDeque<Yuv> = self.current.take().into_iter().collect();
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.
9900 while let Ok(item) = self.frames.recv() {10036 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 {
9902 backlog.push_back(frame);10038 backlog.push_back(frame);
9903 }10039 }
9904 }10040 }
@@ -10008,15 +10144,28 @@ impl ClipDecoder {
10008 Self::open_with(path, start_frame, want, parked, wide, Deinterlace::Frame)10144 Self::open_with(path, start_frame, want, parked, wide, Deinterlace::Frame)
10009 }10145 }
10010 10146
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+
10011 /// [`open`](Self::open) for a clip with a deinterlace setting. `Field` over an10158 /// [`open`](Self::open) for a clip with a deinterlace setting. `Field` over an
10012 /// interlaced file makes `start_frame` a field number and every picture a field.10159 /// 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(
10014 path: &Path,10162 path: &Path,
10015 start_frame: u32,10163 start_frame: u32,
10016 want: Option<DmaWant>,10164 want: Option<DmaWant>,
10017 parked: Option<&Arc<Parked>>,10165 parked: Option<&Arc<Parked>>,
10018 wide: bool,10166 wide: bool,
10019 deint: Deinterlace,10167 deint: Deinterlace,
10168+ tail: u32,
10020 ) -> crate::Result<Self> {10169 ) -> crate::Result<Self> {
10021 // Before either decoder: an image is not a stream, so `start_frame`10170 // Before either decoder: an image is not a stream, so `start_frame`
10022 // means nothing to it -- every frame of a still span is the same10171 // means nothing to it -- every frame of a still span is the same
@@ -10035,7 +10184,7 @@ impl ClipDecoder {
10035 let thread_park = parked.map(|lot| (Arc::clone(lot), Arc::clone(&stop)));10184 let thread_park = parked.map(|lot| (Arc::clone(lot), Arc::clone(&stop)));
10036 let handle = thread::Builder::new()10185 let handle = thread::Builder::new()
10037 .name("export-decode".into())10186 .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))?;
10039 Ok(Self::Streamed(Streamed {10188 Ok(Self::Streamed(Streamed {
10040 frames,10189 frames,
10041 _thread: DecodeThread(Some(handle)),10190 _thread: DecodeThread(Some(handle)),
@@ -10193,20 +10342,29 @@ fn decode_stream(
10193 parked: Option<(Arc<Parked>, Arc<AtomicBool>)>,10342 parked: Option<(Arc<Parked>, Arc<AtomicBool>)>,
10194 wide: bool,10343 wide: bool,
10195 deint: Deinterlace,10344 deint: Deinterlace,
10345+ tail: u32,
10196 ) -> Option<Kept> {10346 ) -> Option<Kept> {
10197 // A 10-bit export asks the hardware seat for whole 10-bit pictures ([`Pictures::Hw`]).10347 // 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+ }
10199 // The decode door's own gate ([`crate::decode::open_hw`]): a VP9 4:2:2 or 4:4:410357 // The decode door's own gate ([`crate::decode::open_hw`]): a VP9 4:2:2 or 4:4:4
10200 // stream is never offered to the GPU, which would refuse it on stderr.10358 // 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)),10359+ (false, None) => crate::decode::open_hw(path, start_frame).map(|hw| (Pictures::Hw(Box::new(hw), wide), VecDeque::new())),
10202- true => None,10360+ (true, _) => None,
10203 };10361 };
10204 if std::env::var_os("EDITH_DEBUG").is_some() {10362 if std::env::var_os("EDITH_DEBUG").is_some() {
10205 eprintln!("export decode: {}{}", if opened.is_some() { "hardware" } else { "software" }, if wide { ", 10-bit" } else { "" });10363 eprintln!("export decode: {}{}", if opened.is_some() { "hardware" } else { "software" }, if wide { ", 10-bit" } else { "" });
10206 }10364 }
10207 // Pictures decoded ahead of the span that a parked decoder still holds.10365 // Pictures decoded ahead of the span that a parked decoder still holds.
10208 let (mut decoder, mut backlog) = match opened {10366 let (mut decoder, mut backlog) = match opened {
10209- Some(hw) => (hw, VecDeque::new()),10367+ Some(hw) => hw,
10210 None => match parked10368 None => match parked
10211 .as_ref()10369 .as_ref()
10212 .and_then(|(lot, _)| lot.take(path, start_frame))10370 .and_then(|(lot, _)| lot.take(path, start_frame))
@@ -10233,28 +10391,35 @@ fn decode_stream(
10233 .is_some_and(|(_, stop)| stop.load(Ordering::Relaxed))10391 .is_some_and(|(_, stop)| stop.load(Ordering::Relaxed))
10234 {10392 {
10235 return match decoder {10393 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)),
10237 _ => None,10396 _ => None,
10238 };10397 };
10239 }10398 }
10240 // Hardware that ends before its first picture has failed the same way10399 // Hardware that ends before its first picture has failed the same way
10241 // one that errors there has: the mid-GOP AV1 seek ends the stream with10400 // one that errors there has: the mid-GOP AV1 seek ends the stream with
10242 // nothing (see `decode::run_hw`), and it falls back here too.10401 // 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() {
10244 Some(frame) => Ok(Some(frame)),10403 Some(frame) => Ok(Some(frame)),
10245- None => decoder.next(want),10404+ None => {
10405+ next += 1;
10406+ decoder.next(want.filter(|_| next <= tail))
10407+ }
10246 };10408 };
10247- let next = match next {10409+ let pulled = match pulled {
10248 Ok(None) if decoded == 0 && matches!(decoder, Pictures::Hw(..)) => {10410 Ok(None) if decoded == 0 && matches!(decoder, Pictures::Hw(..)) => {
10249 Err("hardware gave no picture from the start frame".into())10411 Err("hardware gave no picture from the start frame".into())
10250 }10412 }
10251 other => other,10413 other => other,
10252 };10414 };
10253- let frame = match next {10415+ let frame = match pulled {
10254 Ok(Some(frame)) => frame,10416 Ok(Some(frame)) => frame,
10255 Ok(None) => {10417 Ok(None) => {
10256 let _ = tx.send(Ok(None));10418 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+ };
10258 }10423 }
10259 Err(e) => {10424 Err(e) => {
10260 if matches!(decoder, Pictures::Hw(..)) {10425 if matches!(decoder, Pictures::Hw(..)) {
@@ -12073,6 +12238,9 @@ mod burn_stack_tests {
12073 titles: Vec::new(),12238 titles: Vec::new(),
12074 title_last: Vec::new(),12239 title_last: Vec::new(),
12075 native: None,12240 native: None,
12241+ spare: None,
12242+ narrow: Default::default(),
12243+ merged: Default::default(),
12076 };12244 };
12077 let y = vec![40u8; (w * h) as usize];12245 let y = vec![40u8; (w * h) as usize];
12078 let u = vec![128u8; (w / 2 * (h / 2)) as usize];12246 let u = vec![128u8; (w / 2 * (h / 2)) as usize];
@@ -12382,7 +12550,7 @@ mod vp9_444_tests {
12382 assert_eq!(chroma, Some(Chroma::C444), "the fixture is a 4:4:4 stream");12550 assert_eq!(chroma, Some(Chroma::C444), "the fixture is a 4:4:4 stream");
12383 let (tx, rx) = sync_channel(64);12551 let (tx, rx) = sync_channel(64);
12384 let before = crate::hw::OPEN_ATTEMPTS.with(|n| n.get());12552 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);
12386 let after = crate::hw::OPEN_ATTEMPTS.with(|n| n.get());12554 let after = crate::hw::OPEN_ATTEMPTS.with(|n| n.get());
12387 drop(rx);12555 drop(rx);
12388 let _ = std::fs::remove_file(&path);12556 let _ = std::fs::remove_file(&path);
crates/engine/src/hw.rsmodified+1 -1
@@ -493,7 +493,7 @@ impl Drop for HwSession {
493 493
494 /// What an encoder needs a decoded buffer to look like before it can read it494 /// What an encoder needs a decoded buffer to look like before it can read it
495 /// without a copy: the surface's coded size and the picture inside it.495 /// without a copy: the surface's coded size and the picture inside it.
496-#[derive(Clone, Copy)]496+#[derive(Clone, Copy, PartialEq, Eq)]
497 pub struct DmaWant {497 pub struct DmaWant {
498 pub coded_width: u32,498 pub coded_width: u32,
499 pub coded_height: u32,499 pub coded_height: u32,
crates/engine/src/hwproc.rsmodified+17 -0
@@ -515,6 +515,23 @@ pub fn available() -> bool {
515 /// reads our stdout as JSON-RPC only. `None` when there is no child binary or515 /// reads our stdout as JSON-RPC only. `None` when there is no child binary or
516 /// it will not start.516 /// it will not start.
517 pub fn spawn_child(args: &[OsString]) -> Option<(Child, UnixStream)> {517 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)> {
518 let bin = child_path()?;535 let bin = child_path()?;
519 let (mine, theirs) = UnixStream::pair().ok()?;536 let (mine, theirs) = UnixStream::pair().ok()?;
520 mine.set_read_timeout(Some(timeout())).ok()?;537 mine.set_read_timeout(Some(timeout())).ok()?;
crates/engine/src/mux.rsmodified+13 -7
@@ -187,17 +187,16 @@ pub struct Mp4Muxer {
187 /// two tracks' bytes end up beside each other in `mdat` rather than one187 /// two tracks' bytes end up beside each other in `mdat` rather than one
188 /// whole track then the other. `(bytes, is_sync)`.188 /// whole track then the other. `(bytes, is_sync)`.
189 ///189 ///
190- /// NONDETERMINISM: how tightly the two interleave depends on when the190+ /// While [`audio_pending`](Mp4Muxer::audio_pending) is set the hold never
191- /// mix thread's join lands relative to the picture loop -- a mix that191+ /// flushes video-only, so the interleave depends on timestamps alone and
192- /// finishes before this hold fills stays byte-interleaved from the192+ /// not on when the mix lands; `export` joins the mix once the hold passes
193- /// start; a mix that lands late only interleaves the tail. A test on193+ /// [`HOLD_SECONDS`] to bound its memory.
194- /// this has to pin that landing (force the join before frame N in a
195- /// fixture) rather than race the real mixer thread.
196 hold: VecDeque<(Vec<u8>, bool)>,194 hold: VecDeque<(Vec<u8>, bool)>,
197 /// `hold`'s span, in the video track's own ticks -- flushed video-only195 /// `hold`'s span, in the video track's own ticks -- flushed video-only
198 /// once it passes [`HOLD_SECONDS`], so a mix that never lands (or lands196 /// once it passes [`HOLD_SECONDS`], so a mix that never lands (or lands
199 /// very late) cannot stall the encode behind an unbounded queue.197 /// very late) cannot stall the encode behind an unbounded queue.
200 hold_ticks: u64,198 hold_ticks: u64,
199+ pub audio_pending: bool,
201 /// AAC packets handed over by [`write_audio_packet`](Mp4Muxer::write_audio_packet)200 /// AAC packets handed over by [`write_audio_packet`](Mp4Muxer::write_audio_packet)
202 /// before `drain` has caught up to them -- normally empty the instant201 /// before `drain` has caught up to them -- normally empty the instant
203 /// after that call returns; only grows past one packet where the whole202 /// after that call returns; only grows past one packet where the whole
@@ -334,6 +333,7 @@ impl Mp4Muxer {
334 frames: 0,333 frames: 0,
335 hold: VecDeque::new(),334 hold: VecDeque::new(),
336 hold_ticks: 0,335 hold_ticks: 0,
336+ audio_pending: false,
337 audio_queue: VecDeque::new(),337 audio_queue: VecDeque::new(),
338 audio_ticks: 0,338 audio_ticks: 0,
339 flushed_video_ticks: 0,339 flushed_video_ticks: 0,
@@ -460,6 +460,7 @@ impl Mp4Muxer {
460 frames: 0,460 frames: 0,
461 hold: VecDeque::new(),461 hold: VecDeque::new(),
462 hold_ticks: 0,462 hold_ticks: 0,
463+ audio_pending: false,
463 audio_queue: VecDeque::new(),464 audio_queue: VecDeque::new(),
464 audio_ticks: 0,465 audio_ticks: 0,
465 flushed_video_ticks: 0,466 flushed_video_ticks: 0,
@@ -509,6 +510,7 @@ impl Mp4Muxer {
509 let mut info = StreamInfo::new(self.streams, TimeBase::from_rate(sample_rate), params);510 let mut info = StreamInfo::new(self.streams, TimeBase::from_rate(sample_rate), params);
510 info.language = Some(mp4_language(audio.language.as_deref().unwrap_or("und")));511 info.language = Some(mp4_language(audio.language.as_deref().unwrap_or("und")));
511 self.audio_stream = self.add_stream(info)?;512 self.audio_stream = self.add_stream(info)?;
513+ self.audio_pending = false;
512 self.has_audio = true;514 self.has_audio = true;
513 self.audio_rate = sample_rate;515 self.audio_rate = sample_rate;
514 Ok(())516 Ok(())
@@ -619,7 +621,7 @@ impl Mp4Muxer {
619 self.flush_video_front()?;621 self.flush_video_front()?;
620 }622 }
621 }623 }
622- (Some(_), None) if self.hold_ticks > HOLD_SECONDS * u64::from(self.timescale) => {624+ (Some(_), None) if !self.audio_pending && self.holding_long() => {
623 self.flush_video_front()?;625 self.flush_video_front()?;
624 }626 }
625 // Sound with no picture to wait for is written as it arrives.627 // Sound with no picture to wait for is written as it arrives.
@@ -630,6 +632,10 @@ impl Mp4Muxer {
630 Ok(())632 Ok(())
631 }633 }
632 634
635+ pub fn holding_long(&self) -> bool {
636+ self.hold_ticks > HOLD_SECONDS * u64::from(self.timescale)
637+ }
638+
633 fn flush_video_front(&mut self) -> crate::Result<()> {639 fn flush_video_front(&mut self) -> crate::Result<()> {
634 let Some((bytes, is_sync)) = self.hold.pop_front() else {640 let Some((bytes, is_sync)) = self.hold.pop_front() else {
635 return Ok(());641 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() {
1930 let started = Instant::now();1930 let started = Instant::now();
1931 let wedged = encoder1931 let wedged = encoder
1932 .encode(&y, &u, &v, width, height, false)1932 .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");
1934 let waited = started.elapsed();1936 let waited = started.elapsed();
1935 println!("wedge at the shipping default: contained in {waited:.2?}");1937 println!("wedge at the shipping default: contained in {waited:.2?}");
1936 assert!(engine::hwproc::is_lost(&wedged), "{wedged}");1938 assert!(engine::hwproc::is_lost(&wedged), "{wedged}");
@@ -2066,7 +2068,9 @@ fn a_dead_encoder_answers_every_later_call_the_same_way() {
2066 );2068 );
2067 let died = encoder2069 let died = encoder
2068 .encode(&y, &u, &v, width, height, false)2070 .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");
2070 assert!(2074 assert!(
2071 engine::hwproc::is_lost(&died),2075 engine::hwproc::is_lost(&died),
2072 "an encoder death must say so: {died}"2076 "an encoder death must say so: {died}"