forge
Explore
Log in

Don't you dare go Hollow

A seek opens the sound on the feeder, not on the hand that seeked

Browse files at this commit

46e837993caee2ae817bfe84cd8919e1d4f7a70eAhmet Kaan GümüşParent: 95fb78d
  • perf
    • a seek opens the sound on the feeder, not on the hand that seeked
Show full message
⚡ perf(playback): a seek opens the sound on the feeder, not on the hand that seeked

The picture's open moved onto its worker last week; the sound's stayed on the
caller. `AudioSession::open_mixed_streams_live` opens every track a segment
names -- one `pread` per track, seconds off a cold cache on a 25 GB film -- and
`PlaybackSession::seek` ran it on whoever called it, which in the editor is the
thread that paints. Measured at the seat, cold: one ruler click froze the window
13.5 s, a 300-step scrub burst froze it 22 s. The line written for exactly that
wait (`seek_line`, "the window is not frozen") was unreachable, because the
thread that would have painted it was inside the open.

`Audio::spawn_feeder_deferred` gives the feeder the open as well as the drain,
mirroring `DecodeSession::open_worker_deferred`: the caller pays a thread spawn
(2.09 ms cold on the film, was 9.27 s) and the sound arrives when it arrives.
The epoch is captured at the seek rather than when the open returns, so a scrub
that abandons twenty opens leaves twenty *stale* feeders, every one of them
refused at the same lock the flush is taken under.

The clock is untouched by the wait, which is what makes the wait safe: it holds
where the seek put it until the first real sample is queued (`content_at`), so
8.7 s of cold open put the timeline 22 ms past its target rather than 8.7 s past
it. `fed` is now re-based at that same first sample instead of at the seek --
the open's seconds are device time nobody fed, and counting them handed the
timeline to wall time that far before the sound really ran out.

There is no synchronous answer to "will anything play" any more, so `start_audio`
returns whether a feeder took the job and the callers hand the clock to audio on
it; a timeline with nothing to play ends its feeder at once, and `fed_all` hands
the clock straight back, continuously. Whether there is a *mixer* to talk to is
decided from the lists the open is about to be handed (`AudioSession::is_mixed`,
the one definition, shared with the opener) rather than read off the handle
afterwards -- a fader on the single-lane flat path still rebuilds the stream.

Cold, playing, the device now runs through the open with an empty ring: audibly
the same silence, counted as 1721 underruns where it was 5. Named at `resume`
with its upgrade path. A warm session is unchanged (46 -> 53 across the suite).
crates/engine/src/audio.rsmodified+15 -3
@@ -581,11 +581,10 @@ impl AudioSession {
581581 limiter: Limiter,
582582 live: Option<&Arc<MixControls>>,
583583 ) -> crate::Result<Option<(AudioMeta, Receiver<AudioChunk>)>> {
584- let [first, rest @ ..] = lanes else {
584+ let [first, ..] = lanes else {
585585 return Ok(None);
586586 };
587- let mastered = limiter.is_active() || gains.iter().any(|&g| g != 1.0);
588- if rest.is_empty() && !mastered {
587+ if !Self::is_mixed(lanes.len(), gains, limiter) {
589588 let flat = Vec::new();
590589 let plain = Vec::new();
591590 return Self::open_multi_streams_speed(
@@ -640,6 +639,19 @@ impl AudioSession {
640639 Ok(Some((meta, rx)))
641640 }
642641
642+ /// Whether these settings put the timeline through the **mixer**: more than
643+ /// one lane to sum, a lane off unity, or a limiter over the sum. Anything
644+ /// else is the single-lane flat path, which is `open_multi_streams`
645+ /// verbatim and has no mixer thread to talk to.
646+ ///
647+ /// Public to the crate because [`crate::PlaybackSession`] has to know the
648+ /// answer *before* the open now that it happens on another thread, and the
649+ /// answer must not be spelled out twice: what it decides is whether a fader
650+ /// is handed to a running mixer or rebuilds the stream.
651+ pub(crate) fn is_mixed(lanes: usize, gains: &[f32], limiter: Limiter) -> bool {
652+ lanes > 1 || limiter.is_active() || gains.iter().any(|&g| g != 1.0)
653+ }
654+
643655 /// Why [`open`](Self::open) came back silent for a file that *has* sound:
644656 /// `Some(reason)` when there is an audio track and it is not the AAC-LC
645657 /// this decodes (an AC-3 remux, say). `None` when the file is simply silent
crates/engine/src/playback.rsmodified+103 -16
@@ -149,12 +149,42 @@ impl Audio {
149149 /// Starts a feeder for the current epoch, draining `rx` into the device.
150150 /// `false` if the thread would not start, i.e. nothing will ever be fed.
151151 fn spawn_feeder(&self, rx: Receiver<AudioChunk>) -> bool {
152+ self.spawn_feeder_deferred(move || Some(rx))
153+ }
154+
155+ /// As [`spawn_feeder`](Self::spawn_feeder), but the *stream* is opened on
156+ /// the feeder too: `open` runs on that thread, so nothing here touches the
157+ /// disk and the caller pays a thread spawn instead of a demux -- seconds off
158+ /// a cold cache on a big film, which is what a seek used to cost the UI
159+ /// thread ([`crate::DecodeSession::open_worker_deferred`] is the picture's
160+ /// half of the same move).
161+ ///
162+ /// The price is the same one: there is no [`crate::audio::AudioMeta`] to
163+ /// hand back and no synchronous answer to "will anything play". `None` from
164+ /// `open` -- a silent timeline, a source that will not open -- is a feeder
165+ /// with nothing to feed, which ends exactly as a played-out stream does and
166+ /// hands the clock to wall time ([`tick`](PlaybackSession::tick)).
167+ ///
168+ /// The epoch is captured *here*, at the seek, not when the open returns: a
169+ /// scrub abandons opens by the dozen and every one of them must still be
170+ /// the stale stream it was started as, however late it lands.
171+ fn spawn_feeder_deferred(
172+ &self,
173+ open: impl FnOnce() -> Option<Receiver<AudioChunk>> + Send + 'static,
174+ ) -> bool {
152175 let me = self.clone();
153176 let epoch = self.epoch.load(Ordering::Acquire);
154177 thread::Builder::new()
155178 .name("audio-feed".into())
156179 .spawn(move || {
157- feed(rx, &me, epoch);
180+ // Superseded before this thread was even scheduled: do not open
181+ // anything at all. A scrub leaves all but the last one here.
182+ if me.epoch.load(Ordering::Acquire) != epoch {
183+ return;
184+ }
185+ if let Some(rx) = open() {
186+ feed(rx, &me, epoch);
187+ }
158188 // Only the current feeder gets to declare the end of the audio:
159189 // a superseded one is finished, the stream is not.
160190 if me.epoch.load(Ordering::Acquire) == epoch {
@@ -2252,6 +2282,20 @@ impl PlaybackSession {
22522282 /// Puts the device back where it was: playing if it was playing, and with
22532283 /// the clock held until the new stream is really audible (see
22542284 /// [`Audio::content_at`]).
2285+ ///
2286+ /// ponytail: the device is made active here, before the new stream has been
2287+ /// opened ([`start_audio`](Self::start_audio) opens on the feeder now), so a
2288+ /// cold open leaves it playing its own silence with an empty ring -- audibly
2289+ /// the same silence as before, and counted: a scripted cold play-seek-scrub
2290+ /// session goes from 5 to 1721 `engine_audio: N underruns`, one per starved
2291+ /// quantum, while a warm one is unchanged (46 -> 53 over the suite's 11
2292+ /// sessions). Ceiling: the count stops meaning "the decoder was late" during
2293+ /// a cold seek. Upgrade path is a `wants_active` flag written here and read
2294+ /// by the feeder under the device lock beside the [`Audio::content_at`]
2295+ /// stamp, so the device is started by the first real sample rather than by
2296+ /// the intent to play -- it has to be the lock and the epoch check, or a
2297+ /// pause during the open would be overtaken by a late activation and the
2298+ /// timeline would play while it says it is paused.
22552299 fn resume(&mut self, was_playing: bool) {
22562300 self.priming = true;
22572301 if was_playing && let Some(audio) = &self.audio {
@@ -2260,7 +2304,21 @@ impl PlaybackSession {
22602304 }
22612305
22622306 /// Rebuilds the **sound** from `target` -- the second half of a restart --
2263- /// and says whether anything will be fed.
2307+ /// and says whether a feeder took the job. Not whether it will find
2308+ /// anything to play: the stream is opened on that feeder
2309+ /// ([`Audio::spawn_feeder_deferred`]), so a silent timeline is heard of
2310+ /// there, not here. Nothing on this thread reads the file.
2311+ ///
2312+ /// The clock is unaffected by the wait, which is the reason it may be a
2313+ /// long one: it holds where the seek put it until the *first real sample*
2314+ /// is queued ([`Audio::content_at`], [`tick`](Self::tick)), whether that is
2315+ /// ten milliseconds later or ten seconds.
2316+ ///
2317+ /// `true` is therefore *optimistic*, and the callers' `switch_to_audio` with
2318+ /// it: a timeline that turns out to have nothing to play ends its feeder at
2319+ /// once, which sets `fed_all` and hands the clock back to wall time at the
2320+ /// next tick, from where it stood ([`PlaybackClock::switch_to_wall`] is
2321+ /// continuous, so nothing jumps).
22642322 fn start_audio(&mut self, target: u32) -> bool {
22652323 let fps = self.meta.frame_rate;
22662324 let mut audio_running = false;
@@ -2306,21 +2364,39 @@ impl PlaybackSession {
23062364 let gains = self.project.audio_gains();
23072365 let limiter = self.project.limiter();
23082366 let controls = crate::audio::MixControls::new(gains.clone(), limiter);
2309- audio_running = match AudioSession::open_mixed_streams_live(
2310- &sources,
2311- &segs,
2312- &eqs,
2313- &speeds,
2314- &gains,
2315- limiter,
2316- Some(&controls),
2317- ) {
2318- Ok(Some((_, rx))) => audio.spawn_feeder(rx),
2319- _ => false,
2320- };
23212367 // Only a mixed timeline has a mixer to talk to; the single-lane
2322- // flat path is the bit-exact one and has none.
2323- live = (audio_running && controls.is_live()).then_some(controls);
2368+ // flat path is the bit-exact one and has none. Decided here from
2369+ // the very lists the open is about to be handed
2370+ // ([`AudioSession::is_mixed`]) rather than read off the handle
2371+ // afterwards, because there *is* no afterwards on this thread any
2372+ // more -- the open runs on the feeder.
2373+ let mixed = crate::audio::AudioSession::is_mixed(segs.len(), &gains, limiter);
2374+ let worker_controls = Arc::clone(&controls);
2375+ // ...and the open itself -- every track a segment names, its packet
2376+ // table, its priming -- happens there too. That is the whole point:
2377+ // one `pread` on a cold 25 GB film is seconds, and this is called
2378+ // from a ruler drag ([`Audio::spawn_feeder_deferred`]).
2379+ audio_running = audio.spawn_feeder_deferred(move || {
2380+ match AudioSession::open_mixed_streams_live(
2381+ &sources,
2382+ &segs,
2383+ &eqs,
2384+ &speeds,
2385+ &gains,
2386+ limiter,
2387+ Some(&worker_controls),
2388+ ) {
2389+ Ok(Some((_, rx))) => Some(rx),
2390+ // A silent timeline, and a source that will not open: both
2391+ // feed nothing, which the feeder itself reports by ending.
2392+ Ok(None) => None,
2393+ Err(e) => {
2394+ eprintln!("timeline audio open failed: {e}");
2395+ None
2396+ }
2397+ }
2398+ });
2399+ live = (audio_running && mixed).then_some(controls);
23242400 if !audio_running {
23252401 // Nothing will ever be fed again; let `tick` fall to wall time
23262402 // instead of waiting on a device that has no more work coming.
@@ -2706,6 +2782,17 @@ fn feed(rx: Receiver<AudioChunk>, audio: &Audio, epoch: u64) {
27062782 if accepted > 0 && audio.content_at.load(Ordering::Acquire) < 0 {
27072783 let at = ao.position().unwrap_or(0).max(0);
27082784 audio.content_at.store(at, Ordering::Release);
2785+ // ...and the device position this stream's samples are counted
2786+ // from ([`Audio::played_out`]). Rebased *here* rather than at
2787+ // the seek, because the open runs on this thread now: every
2788+ // millisecond it took is device time nobody fed, and counting
2789+ // it would make the stream read as played out that long before
2790+ // it really is -- an early hand-off to wall time at the end of
2791+ // the timeline. The seek's own rebase still stands for the
2792+ // stream that never queues a sample at all.
2793+ audio
2794+ .fed
2795+ .store(at as u64 * audio.channels, Ordering::Relaxed);
27092796 }
27102797 accepted
27112798 };
crates/engine/tests/playback.rsmodified+84 -0
@@ -7,6 +7,8 @@
77 //! cargo test -p engine --release --test playback -- --nocapture
88 //! ```
99
10+use std::fs::File;
11+use std::os::fd::AsRawFd;
1012 use std::path::{Path, PathBuf};
1113 use std::thread::sleep;
1214 use std::time::{Duration, Instant};
@@ -375,6 +377,88 @@ fn seek_keeps_the_audio_clock() {
375377 );
376378 }
377379
380+/// Drops `path` out of the page cache, so the next read of it is a real disk
381+/// read. `posix_fadvise(POSIX_FADV_DONTNEED)`, glibc's own and declared here
382+/// rather than pulled in as a dependency for one call.
383+fn evict(path: &Path) {
384+ unsafe extern "C" {
385+ fn posix_fadvise(fd: i32, offset: i64, len: i64, advice: i32) -> i32;
386+ }
387+ let file = File::open(path).expect("open to evict");
388+ // 0 length is "to the end of the file"; 4 is POSIX_FADV_DONTNEED on Linux.
389+ let rc = unsafe { posix_fadvise(file.as_raw_fd(), 0, 0, 4) };
390+ assert_eq!(rc, 0, "could not evict {}", path.display());
391+}
392+
393+/// What a seek costs the *caller* when the sound has to be opened again off a
394+/// cold page cache -- the audio half of the move
395+/// [`a_storm_of_seeks_stays_bounded_and_the_last_one_wins`] measures for the
396+/// picture. That open is a `pread` per track (21 s on a cold 25 GB film,
397+/// measured at the seat) and it used to run on whoever called `seek`, which in
398+/// the editor is the thread that paints: one ruler click froze the window for
399+/// the whole of it. On the feeder it is a thread spawn, whatever the file.
400+///
401+/// And the clock still anchors on the first real sample, which is the invariant
402+/// the wait threatens: the timeline holds where the seek put it for however
403+/// long the open takes, and starts counting from *there* rather than from the
404+/// silence the device played meanwhile.
405+///
406+/// `assets/test_av.mp4` by default, which makes this a regression guard;
407+/// `EDITH_COLD_FILM=<a big film>` makes it the measurement.
408+#[test]
409+#[ignore = "needs a running PipeWire daemon"]
410+fn a_cold_audio_open_does_not_block_the_seek() {
411+ let path = std::env::var_os("EDITH_COLD_FILM")
412+ .map(PathBuf::from)
413+ .unwrap_or_else(|| asset("test_av.mp4"));
414+ let mut session = open(&path);
415+ let target = session.timeline_duration() * 0.5;
416+ let mut last_index = None;
417+ session.play();
418+ run_for(&mut session, &mut last_index, Duration::from_millis(300));
419+
420+ // The seek's own reads and nothing else: the open above warmed every byte
421+ // of this file that anything here touches.
422+ evict(&path);
423+ let issued = Instant::now();
424+ session.seek(target);
425+ let blocked = issued.elapsed();
426+ eprintln!(
427+ "cold seek on {}: caller blocked {blocked:?}",
428+ path.display()
429+ );
430+ assert!(
431+ blocked < Duration::from_millis(10),
432+ "the caller opened the file itself: seek blocked {blocked:?}"
433+ );
434+ assert!(
435+ (session.now() - target).abs() < 0.05,
436+ "the seek did not land: clock at {}",
437+ session.now()
438+ );
439+
440+ // The sound arrives when it arrives, and the clock does not move until it
441+ // does. Long deadline: that is the point of the test.
442+ let waited = Instant::now();
443+ let deadline = waited + Duration::from_secs(120);
444+ while session.now() <= target + 0.001 {
445+ session.tick();
446+ while session.try_frame().is_some() {}
447+ assert!(
448+ Instant::now() < deadline,
449+ "the clock never moved after a cold seek"
450+ );
451+ sleep(Duration::from_millis(8));
452+ }
453+ let (moved, waited) = (session.now(), waited.elapsed().as_secs_f64());
454+ eprintln!("clock moved to {moved:.3}s (target {target:.3}s) after {waited:.3}s of open");
455+ assert!(
456+ moved - target < 0.5,
457+ "the open leaked into the timeline: {waited:.3}s of it put the clock at \
458+ {moved:.3}s instead of {target:.3}s"
459+ );
460+}
461+
378462 /// The edit list end to end: two cuts, drop the middle clip, play the result.
379463 /// What comes out is one contiguous timeline whose *pictures* skip the hole --
380464 /// no audio needed, so this runs anywhere.