forge
Explore
Log in

Don't you dare go Hollow

A seek costs the UI thread a thread spawn, not a demux

Browse files at this commit

74a068ea813054dc6351f611dec969986feb1633Ahmet Kaan GümüşParent: 734ca14
  • perf
    • a seek costs the UI thread a thread spawn, not a demux
Show full message
⚡ perf(playback): a seek costs the UI thread a thread spawn, not a demux

Playback opened every span's file on the caller's thread: 300 ms warm on a
25 GB film (measured), seconds off a cold cache, and a scrub paid it per
seek. `DecodeSession::open_worker_deferred` moves the demux onto the worker
-- there is no metadata to hand back on that path anyway, `start_span`
discarded it -- so the caller pays a `thread::spawn` and the picture arrives
when it arrives, which is what `try_frame`'s `None` has always meant.

The four callers that need the refusal at the door (the public `open`, a
session open, a project load, an import) keep the sync opener, so a file
this machine cannot decode is still named to the user where it is chosen.
A file that fails to open *at a span* drops its sender, and the
disconnected receiver walks the session on to the next span exactly as the
dead receiver installed here did.

Both openers now share one worker body (`decode_span`), so hardware
fallback, the codec refusal, the tone map's declared peak and the range
clamp cannot drift apart between them.

Measured on the film: seek returns in 52-68 us (was ~300 ms), first frame
380-620 ms later. The remaining wait is the container walk on the worker;
a per-source parsed-index cache is the follow-up, not this diff.
crates/engine/src/decode.rsmodified+226 -46
@@ -414,15 +414,6 @@ impl DecodeSession {
414 return Err(meta.codec.needs_plugin().into());414 return Err(meta.codec.needs_plugin().into());
415 }415 }
416 let end_frame = end_frame.min(meta.frame_count);416 let end_frame = end_frame.min(meta.frame_count);
417- // Read off the file once, here, and carried into the worker: it is a
418- // property of the stream, so it cannot change while one range decodes.
419- let source_color = meta.color;
420- // ...and with it what the film says its own brightest picture is
421- // ([`Demuxer::light`]): the tone map's assumed peak on the reference
422- // rendition, so a 1759 cd/m^2 grade is converted at 1759 rather than at
423- // the 1000 a file that declared nothing is assumed at. Read here
424- // because the demuxer is moved into the worker below.
425- let declared_peak = demuxer.light().peak();
426 // Small bound: a 720p BGRA frame is ~3.5 MB, so we must not let the417 // Small bound: a 720p BGRA frame is ~3.5 MB, so we must not let the
427 // decoder run ahead of the display without limit.418 // decoder run ahead of the display without limit.
428 let (tx, rx) = sync_channel(2);419 let (tx, rx) = sync_channel(2);
@@ -450,46 +441,18 @@ impl DecodeSession {
450 let handle = thread::Builder::new()441 let handle = thread::Builder::new()
451 .name("decode".into())442 .name("decode".into())
452 .spawn(move || {443 .spawn(move || {
453- // Cancelled before this thread was even scheduled -- do not444+ decode_span(
454- // enter VA-API initialisation at all, because that is the one445+ &path,
455- // stretch a cancel cannot interrupt (~65-90 ms of driver setup
456- // that would then have to be torn down again).
457- if worker_cancel.load(Ordering::Relaxed) {
458- return;
459- }
460- let mut render = Render::new(color, source_color, canvas, tone, declared_peak);
461- // The plugin has to be opened on the thread that uses it: its
462- // VA-API state is not `Send`-safe across a later hand-off.
463- if let Some(hw) = open_hw(&path, start_frame) {
464- // Cancelled *during* init: close the session (dropping `hw`
465- // does it) and leave without decoding anything.
466- if worker_cancel.load(Ordering::Relaxed) {
467- return;
468- }
469- eprintln!("decode backend: hardware (VA-API plugin)");
470- worker_backend.set(Backend::Hardware);
471- if run_hw(hw, &tx, start_frame, end_frame, &mut render, &worker_cancel) {
472- return;
473- }
474- // A driver that opens but cannot decode a single frame is
475- // still a fallback case, not a dead session.
476- eprintln!("hardware decode failed before any frame, falling back to software");
477- }
478- // ...except where there is nothing to fall back to. Feeding HEVC
479- // or VP9 bytes to `rusty_h264` would be garbage, not a fallback.
480- if meta.codec != Codec::H264 {
481- eprintln!("{}", meta.codec.needs_plugin());
482- return;
483- }
484- eprintln!("decode backend: software (rusty_h264)");
485- worker_backend.set(Backend::Software);
486- run(
487 demuxer,446 demuxer,
488- tx,447+ meta,
489 start_frame,448 start_frame,
490 end_frame,449 end_frame,
491- &mut render,450+ color,
451+ canvas,
452+ tone,
453+ tx,
492 &worker_cancel,454 &worker_cancel,
455+ &worker_backend,
493 )456 )
494 })?;457 })?;
495 Ok((458 Ok((
@@ -504,6 +467,141 @@ impl DecodeSession {
504 },467 },
505 ))468 ))
506 }469 }
470+
471+ /// As [`open_worker`](Self::open_worker), but the *file* is opened on the
472+ /// worker too: nothing here touches the disk, so the caller pays a thread
473+ /// spawn and not a demux -- 550-750 ms warm on a 25 GB film, seconds cold,
474+ /// which is what a seek or a clip boundary used to cost the UI thread.
475+ ///
476+ /// The price is that there is no [`VideoMeta`] to return and no synchronous
477+ /// refusal either: a file that will not open, and a codec no decoder here
478+ /// takes (the plugin probe is skipped -- the worker's own refusal below
479+ /// covers it), simply drop the sender. The disconnected receiver is what
480+ /// carries a session on to the next span, which is exactly what a failed
481+ /// open did on this path before. Callers that must *tell* the user why --
482+ /// an import at the door -- keep the sync opener.
483+ pub(crate) fn open_worker_deferred(
484+ path: impl AsRef<Path>,
485+ start_frame: u32,
486+ end_frame: u32,
487+ color: ColorParams,
488+ canvas: Composer,
489+ tone: tonemap::Preset,
490+ ) -> FrameStream {
491+ let path = path.as_ref().to_path_buf();
492+ let (tx, rx) = sync_channel(2);
493+ let cancel = Arc::new(AtomicBool::new(false));
494+ let backend = BackendCell::default();
495+ let worker_cancel = Arc::clone(&cancel);
496+ let worker_backend = backend.clone();
497+ let handle = thread::Builder::new()
498+ .name("decode".into())
499+ .spawn(move || {
500+ // Cancelled before this thread was even scheduled: do not open
501+ // the file at all. A scrub abandons workers by the dozen and
502+ // this is where all but the last of them stop.
503+ if worker_cancel.load(Ordering::Relaxed) {
504+ return;
505+ }
506+ let (meta, demuxer) = match Demuxer::open(&path) {
507+ Ok(opened) => opened,
508+ Err(e) => {
509+ eprintln!("video open failed: {e}");
510+ // Dropping `tx` disconnects the receiver, which is the
511+ // session's "walk on to the next span".
512+ worker_backend.set(Backend::Gap);
513+ return;
514+ }
515+ };
516+ decode_span(
517+ &path,
518+ demuxer,
519+ meta,
520+ start_frame,
521+ // The clamp the sync opener does with the metadata it read
522+ // on the caller's thread; here the metadata arrives first.
523+ end_frame.min(meta.frame_count),
524+ color,
525+ canvas,
526+ tone,
527+ tx,
528+ &worker_cancel,
529+ &worker_backend,
530+ )
531+ })
532+ .ok();
533+ FrameStream {
534+ frames: rx,
535+ worker: Worker { cancel, handle },
536+ backend,
537+ }
538+ }
539+}
540+
541+/// One worker thread's whole job, on that thread: pick the decoder, decode
542+/// `[start_frame, end_frame)`, send the pictures. Both openers end here -- the
543+/// sync one, which demuxed on the caller's thread, and the deferred one, which
544+/// demuxed on this one -- so there is exactly one description of what a decode
545+/// worker does, whoever opened the file.
546+#[allow(clippy::too_many_arguments)]
547+fn decode_span(
548+ path: &PathBuf,
549+ demuxer: Demuxer,
550+ meta: VideoMeta,
551+ start_frame: u32,
552+ end_frame: u32,
553+ color: ColorParams,
554+ canvas: Composer,
555+ tone: tonemap::Preset,
556+ tx: SyncSender<Frame>,
557+ cancel: &AtomicBool,
558+ backend: &BackendCell,
559+) {
560+ // An empty range decodes nothing and must send nothing: `run_hw` counts a
561+ // frame *out* before it compares, so without this a zero-length span would
562+ // emit one picture. The sync opener never even spawns for this case.
563+ if end_frame <= start_frame {
564+ return;
565+ }
566+ // Cancelled before this thread was even scheduled -- do not enter VA-API
567+ // initialisation at all, because that is the one stretch a cancel cannot
568+ // interrupt (~65-90 ms of driver setup that would then have to be torn
569+ // down again).
570+ if cancel.load(Ordering::Relaxed) {
571+ return;
572+ }
573+ // The stream's own colour, and with it what the film says its brightest
574+ // picture is ([`Demuxer::light`]): the tone map's assumed peak on the
575+ // reference rendition, so a 1759 cd/m^2 grade is converted at 1759 rather
576+ // than at the 1000 a file that declared nothing is assumed at. Both are
577+ // properties of the stream, so neither can change while one range decodes.
578+ let mut render = Render::new(color, meta.color, canvas, tone, demuxer.light().peak());
579+ // The plugin has to be opened on the thread that uses it: its VA-API state
580+ // is not `Send`-safe across a later hand-off.
581+ if let Some(hw) = open_hw(path, start_frame) {
582+ // Cancelled *during* init: close the session (dropping `hw` does it)
583+ // and leave without decoding anything.
584+ if cancel.load(Ordering::Relaxed) {
585+ return;
586+ }
587+ eprintln!("decode backend: hardware (VA-API plugin)");
588+ backend.set(Backend::Hardware);
589+ if run_hw(hw, &tx, start_frame, end_frame, &mut render, cancel) {
590+ return;
591+ }
592+ // A driver that opens but cannot decode a single frame is still a
593+ // fallback case, not a dead session.
594+ eprintln!("hardware decode failed before any frame, falling back to software");
595+ }
596+ // ...except where there is nothing to fall back to. Feeding HEVC or VP9
597+ // bytes to `rusty_h264` would be garbage, not a fallback.
598+ if meta.codec != Codec::H264 {
599+ eprintln!("{}", meta.codec.needs_plugin());
600+ return;
601+ }
602+ eprintln!("decode backend: software (rusty_h264)");
603+ backend.set(Backend::Software);
604+ run(demuxer, tx, start_frame, end_frame, &mut render, cancel)
507 }605 }
508 606
509 /// One clip's pictures on their way to the renderer: graded, placed on the607 /// One clip's pictures on their way to the renderer: graded, placed on the
@@ -811,7 +909,7 @@ fn run_hw(
811 mod tests {909 mod tests {
812 use super::*;910 use super::*;
813 use std::sync::mpsc::RecvTimeoutError;911 use std::sync::mpsc::RecvTimeoutError;
814- use std::time::Duration;912+ use std::time::{Duration, Instant};
815 913
816 fn asset(name: &str) -> PathBuf {914 fn asset(name: &str) -> PathBuf {
817 PathBuf::from(env!("CARGO_MANIFEST_DIR"))915 PathBuf::from(env!("CARGO_MANIFEST_DIR"))
@@ -819,6 +917,88 @@ mod tests {
819 .join(name)917 .join(name)
820 }918 }
821 919
920+ /// Drops `path` from the page cache, so the open below really goes to disk
921+ /// -- the case the deferred opener exists for, and the one that costs
922+ /// seconds on a 25 GB film. Unprivileged (`posix_fadvise(DONTNEED)`), and a
923+ /// no-op wherever `python3` is not around: the assertions hold either way,
924+ /// the numbers printed are simply the warm ones.
925+ fn evict(path: &Path) {
926+ let _ = std::process::Command::new("python3")
927+ .arg("-c")
928+ .arg(
929+ "import os,sys\n\
930+ fd=os.open(sys.argv[1],os.O_RDONLY)\n\
931+ os.posix_fadvise(fd,0,0,os.POSIX_FADV_DONTNEED)\n\
932+ os.close(fd)",
933+ )
934+ .arg(path)
935+ .status();
936+ }
937+
938+ /// The whole point of [`DecodeSession::open_worker_deferred`]: the caller
939+ /// gets its stream back in the time a thread takes to spawn, and the file
940+ /// is opened behind it -- so the first frame necessarily arrives *after*
941+ /// the call returned, and the sync opener on the same cold file pays on the
942+ /// calling thread what this one does not.
943+ #[test]
944+ fn a_deferred_open_costs_the_caller_a_thread_and_not_a_demux() {
945+ let path = asset("test_baseline.mp4");
946+ evict(&path);
947+ let start = Instant::now();
948+ let stream = DecodeSession::open_worker_deferred(
949+ &path,
950+ 0,
951+ u32::MAX,
952+ ColorParams::default(),
953+ Composer::passthrough(),
954+ tonemap::Preset::default(),
955+ );
956+ let returned = start.elapsed();
957+ let frame = stream
958+ .frames
959+ .recv_timeout(Duration::from_secs(10))
960+ .expect("first frame");
961+ let first_frame = start.elapsed();
962+
963+ // The same file, equally cold, through the door the import path keeps:
964+ // that one hands back metadata, and the demux it reads to do so is on
965+ // this thread.
966+ evict(&path);
967+ let sync_start = Instant::now();
968+ let sync = DecodeSession::open_worker(
969+ &path,
970+ 0,
971+ u32::MAX,
972+ ColorParams::default(),
973+ Composer::passthrough(),
974+ tonemap::Preset::default(),
975+ )
976+ .expect("sync open");
977+ let sync_returned = sync_start.elapsed();
978+ drop(sync);
979+
980+ eprintln!(
981+ "deferred open returned in {returned:?}, first frame at {first_frame:?}; \
982+ sync open returned in {sync_returned:?}"
983+ );
984+ assert_eq!(frame.index, 0, "the deferred worker starts where it is told");
985+ assert!(
986+ returned < Duration::from_millis(10),
987+ "the caller waited {returned:?} -- something is still being read \
988+ from the file before this returns"
989+ );
990+ assert!(
991+ first_frame > returned,
992+ "the first frame arrived within the call ({first_frame:?} vs \
993+ {returned:?}), which cannot happen if the open is deferred"
994+ );
995+ assert!(
996+ returned < sync_returned,
997+ "the deferred open ({returned:?}) cost as much as the sync one \
998+ ({sync_returned:?}): the demux is still on the caller's thread"
999+ );
1000+ }
1001+
822 /// Dropping a [`FrameStream`] whose frames nobody ever took must not wait.1002 /// Dropping a [`FrameStream`] whose frames nobody ever took must not wait.
823 /// The channel is bounded, so such a worker is parked in `send` within a1003 /// The channel is bounded, so such a worker is parked in `send` within a
824 /// few frames, and the only thing that can wake it is its receiver going1004 /// few frames, and the only thing that can wake it is its receiver going
crates/engine/src/playback.rsmodified+11 -7
@@ -1000,8 +1000,12 @@ impl PlaybackSession {
1000 /// one [`PlaybackSession::now`] is in.1000 /// one [`PlaybackSession::now`] is in.
1001 ///1001 ///
1002 /// `None` means "nothing right now": the decoder is behind, or a clip1002 /// `None` means "nothing right now": the decoder is behind, or a clip
1003- /// boundary is being reopened (~80 ms, during which the caller simply keeps1003+ /// boundary is being reopened -- and *that* now happens entirely on the new
1004- /// showing its last frame). End of stream is [`PlaybackSession::is_eos`].1004+ /// worker ([`DecodeSession::open_worker_deferred`]), so it costs this
1005+ /// thread a thread spawn and the caller simply keeps showing its last frame
1006+ /// for however long the source takes to open (hundreds of milliseconds on a
1007+ /// big film, seconds off a cold cache). End of stream is
1008+ /// [`PlaybackSession::is_eos`].
1005 pub fn try_frame(&mut self) -> Option<Frame> {1009 pub fn try_frame(&mut self) -> Option<Frame> {
1006 loop {1010 loop {
1007 match self.frames.try_recv() {1011 match self.frames.try_recv() {
@@ -1103,7 +1107,9 @@ impl PlaybackSession {
1103 ///1107 ///
1104 /// A source that will not open leaves the *span* installed anyway: the1108 /// A source that will not open leaves the *span* installed anyway: the
1105 /// timeline still moves, there are simply no more pictures, and the1109 /// timeline still moves, there are simply no more pictures, and the
1106- /// disconnected receiver carries the session on to the next span.1110+ /// disconnected receiver carries the session on to the next span. For a
1111+ /// video that is now the worker's own doing -- it opens the file, so it is
1112+ /// the one that finds out -- and nothing on this thread waits to hear it.
1107 fn start_span(&mut self, span: Option<Span>) {1113 fn start_span(&mut self, span: Option<Span>) {
1108 // Which file's frames the worker about to be opened will number its1114 // Which file's frames the worker about to be opened will number its
1109 // pictures in: the span's own source, and real time for a gap, whose1115 // pictures in: the span's own source, and real time for a gap, whose
@@ -1147,7 +1153,7 @@ impl PlaybackSession {
1147 start,1153 start,
1148 from: Some((source, in_frame)),1154 from: Some((source, in_frame)),
1149 ..1155 ..
1150- }) => DecodeSession::open_worker(1156+ }) => Ok(DecodeSession::open_worker_deferred(
1151 &self.project.sources()[source].path,1157 &self.project.sources()[source].path,
1152 // The file's own frames, which is the only place they exist:1158 // The file's own frames, which is the only place they exist:
1153 // a clip counts the timeline's ([`Rate`]).1159 // a clip counts the timeline's ([`Rate`]).
@@ -1176,9 +1182,7 @@ impl PlaybackSession {
1176 // the project's own and constant across the span for that reason1182 // the project's own and constant across the span for that reason
1177 // too.1183 // too.
1178 self.project.tone(),1184 self.project.tone(),
1179- )1185+ )),
1180- .map(|(_, stream)| stream)
1181- .inspect_err(|e| eprintln!("timeline frame {start}: video open failed: {e}")),
1182 // A gap: black for as long as it runs. An emptied timeline has no1186 // A gap: black for as long as it runs. An emptied timeline has no
1183 // span at all and gets one frame of it -- enough to put black on1187 // span at all and gets one frame of it -- enough to put black on
1184 // screen, and it ends where the timeline does, at once.1188 // screen, and it ends where the timeline does, at once.
crates/engine/tests/playback.rsmodified+42 -0
@@ -267,6 +267,48 @@ fn rapid_seeks_settle_on_the_last_one() {
267 );267 );
268 }268 }
269 269
270+/// The storm the deferred open exists for: 40 seeks with nothing in between.
271+/// Each one abandons a worker and starts another, and since the open moved onto
272+/// the worker (`DecodeSession::open_worker_deferred`) not one of them reads the
273+/// file on this thread -- so the whole storm is 40 thread spawns, the parked
274+/// workers are still reaped as they go (the thread count says so), and the last
275+/// seek still decides what is on screen.
276+#[test]
277+fn a_storm_of_seeks_stays_bounded_and_the_last_one_wins() {
278+ let mut session = open(asset("test_av.mp4"));
279+ let fps = session.meta().frame_rate;
280+ let mut last_index = None;
281+
282+ session.play();
283+ run_for(&mut session, &mut last_index, Duration::from_millis(300));
284+ let before = threads();
285+
286+ let storm = Instant::now();
287+ for i in 0..39 {
288+ session.seek(f64::from(i % 5) * 0.8);
289+ }
290+ session.seek(2.0);
291+ let issued = storm.elapsed();
292+ eprintln!("40 seeks issued in {issued:?} ({before} threads before)");
293+ assert!(
294+ issued < Duration::from_secs(1),
295+ "40 seeks cost the caller {issued:?} -- a seek is opening a file again"
296+ );
297+ assert_eq!(
298+ next_index(&mut session, "40 rapid seeks"),
299+ (2.0 * fps) as u32,
300+ "the last seek is the one that decides"
301+ );
302+
303+ sleep(Duration::from_millis(500)); // abandoned workers exit within an AU
304+ let after = threads();
305+ eprintln!("seek storm: {before} threads -> {after}");
306+ assert!(
307+ after <= before + 3,
308+ "the retired list grew with the storm: {before} threads -> {after}"
309+ );
310+}
311+
270 /// The audio path proper: needs a PipeWire daemon and the output plugin next to312 /// The audio path proper: needs a PipeWire daemon and the output plugin next to
271 /// the test binary (`LD_LIBRARY_PATH=target/release`).313 /// the test binary (`LD_LIBRARY_PATH=target/release`).
272 #[test]314 #[test]
crates/engine/tests/vp9.rsmodified+49 -0
@@ -106,6 +106,55 @@ fn a_timeline_takes_the_other_codec_or_names_the_missing_decoder() {
106 }106 }
107 }107 }
108 108
109+/// The refusal *at a span*, which is where it happens now: playback opens its
110+/// files on the worker (`DecodeSession::open_worker_deferred`), so a clip no
111+/// decoder here can take is refused there rather than on the caller's thread.
112+/// What must survive that move is the behaviour a refused span always had --
113+/// no pictures from that clip, and the session walks on to the end instead of
114+/// stalling on it.
115+///
116+/// The clip is imported as H.264, because the *door* still refuses what it
117+/// cannot open; the bytes under it become VP9 afterwards, which is the only way
118+/// to put a span the worker must refuse on a timeline.
119+#[test]
120+fn a_refused_codec_at_a_span_advances_instead_of_stalling() {
121+ let scratch = Scratch::file("video_editor_vp9_span", "mp4");
122+ std::fs::copy(asset("test_av2.mp4"), &scratch).expect("copy the fixture");
123+ let mut session = PlaybackSession::open(asset("test_av.mp4")).expect("open test_av.mp4");
124+ session.set_gain(0.0);
125+ let first = session.meta().frame_count;
126+ session.import(&scratch).expect("an H.264 file joins this timeline");
127+ let end = session.timeline_duration();
128+ assert!(
129+ session
130+ .place_stream_at(end, &scratch, 0, None)
131+ .expect("a file just imported is on this timeline")
132+ );
133+ std::fs::copy(asset("test_vp9.mp4"), &scratch).expect("swap in the VP9 bytes");
134+
135+ // The no-plugin machine, forced, so hardware cannot quietly take the span.
136+ // SAFETY: the suite is documented to run with --test-threads=1.
137+ unsafe { std::env::set_var("VE_SW", "1") };
138+ session.seek(0.0);
139+ session.play();
140+ let deadline = Instant::now() + Duration::from_secs(20);
141+ let (mut count, mut last) = (0u32, None);
142+ while !session.is_eos() {
143+ session.tick();
144+ while let Some(frame) = session.try_frame() {
145+ count += 1;
146+ last = Some(frame.index);
147+ }
148+ assert!(Instant::now() < deadline, "the refused span stalled playback");
149+ std::thread::sleep(Duration::from_millis(4));
150+ }
151+ unsafe { std::env::remove_var("VE_SW") };
152+
153+ assert_eq!(last, Some(first - 1), "the refused clip made pictures");
154+ assert_eq!(count, first, "the first source still played whole");
155+ let _ = std::fs::remove_file(&scratch);
156+}
157+
109 /// The end-to-end user path: opening the file yields pictures, all of them,158 /// The end-to-end user path: opening the file yields pictures, all of them,
110 /// through the plugin.159 /// through the plugin.
111 #[test]160 #[test]