A seek opens the sound on the feeder, not on the hand that seeked
Browse files at this commit46e837993caee2ae817bfe84cd8919e1d4f7a70eParent: 95fb78d- perf
- a seek opens the sound on the feeder, not on the hand that seeked
3 changed files +202 -19
- crates/engine/src/audio.rs +15 -3
- crates/engine/src/playback.rs +103 -16
- crates/engine/tests/playback.rs +84 -0
crates/engine/src/audio.rsmodified+15 -3
| @@ -581,11 +581,10 @@ impl AudioSession { | |||
| 581 | limiter: Limiter, | 581 | limiter: Limiter, |
| 582 | live: Option<&Arc<MixControls>>, | 582 | live: Option<&Arc<MixControls>>, |
| 583 | ) -> crate::Result<Option<(AudioMeta, Receiver<AudioChunk>)>> { | 583 | ) -> crate::Result<Option<(AudioMeta, Receiver<AudioChunk>)>> { |
| 584 | - let [first, rest @ ..] = lanes else { | 584 | + let [first, ..] = lanes else { |
| 585 | return Ok(None); | 585 | return Ok(None); |
| 586 | }; | 586 | }; |
| 587 | - let mastered = limiter.is_active() || gains.iter().any(|&g| g != 1.0); | 587 | + if !Self::is_mixed(lanes.len(), gains, limiter) { |
| 588 | - if rest.is_empty() && !mastered { | ||
| 589 | let flat = Vec::new(); | 588 | let flat = Vec::new(); |
| 590 | let plain = Vec::new(); | 589 | let plain = Vec::new(); |
| 591 | return Self::open_multi_streams_speed( | 590 | return Self::open_multi_streams_speed( |
| @@ -640,6 +639,19 @@ impl AudioSession { | |||
| 640 | Ok(Some((meta, rx))) | 639 | Ok(Some((meta, rx))) |
| 641 | } | 640 | } |
| 642 | 641 | ||
| 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 | + | ||
| 643 | /// Why [`open`](Self::open) came back silent for a file that *has* sound: | 655 | /// Why [`open`](Self::open) came back silent for a file that *has* sound: |
| 644 | /// `Some(reason)` when there is an audio track and it is not the AAC-LC | 656 | /// `Some(reason)` when there is an audio track and it is not the AAC-LC |
| 645 | /// this decodes (an AC-3 remux, say). `None` when the file is simply silent | 657 | /// 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 { | |||
| 149 | /// Starts a feeder for the current epoch, draining `rx` into the device. | 149 | /// Starts a feeder for the current epoch, draining `rx` into the device. |
| 150 | /// `false` if the thread would not start, i.e. nothing will ever be fed. | 150 | /// `false` if the thread would not start, i.e. nothing will ever be fed. |
| 151 | fn spawn_feeder(&self, rx: Receiver<AudioChunk>) -> bool { | 151 | 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 { | ||
| 152 | let me = self.clone(); | 175 | let me = self.clone(); |
| 153 | let epoch = self.epoch.load(Ordering::Acquire); | 176 | let epoch = self.epoch.load(Ordering::Acquire); |
| 154 | thread::Builder::new() | 177 | thread::Builder::new() |
| 155 | .name("audio-feed".into()) | 178 | .name("audio-feed".into()) |
| 156 | .spawn(move || { | 179 | .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 | + } | ||
| 158 | // Only the current feeder gets to declare the end of the audio: | 188 | // Only the current feeder gets to declare the end of the audio: |
| 159 | // a superseded one is finished, the stream is not. | 189 | // a superseded one is finished, the stream is not. |
| 160 | if me.epoch.load(Ordering::Acquire) == epoch { | 190 | if me.epoch.load(Ordering::Acquire) == epoch { |
| @@ -2252,6 +2282,20 @@ impl PlaybackSession { | |||
| 2252 | /// Puts the device back where it was: playing if it was playing, and with | 2282 | /// Puts the device back where it was: playing if it was playing, and with |
| 2253 | /// the clock held until the new stream is really audible (see | 2283 | /// the clock held until the new stream is really audible (see |
| 2254 | /// [`Audio::content_at`]). | 2284 | /// [`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. | ||
| 2255 | fn resume(&mut self, was_playing: bool) { | 2299 | fn resume(&mut self, was_playing: bool) { |
| 2256 | self.priming = true; | 2300 | self.priming = true; |
| 2257 | if was_playing && let Some(audio) = &self.audio { | 2301 | if was_playing && let Some(audio) = &self.audio { |
| @@ -2260,7 +2304,21 @@ impl PlaybackSession { | |||
| 2260 | } | 2304 | } |
| 2261 | 2305 | ||
| 2262 | /// Rebuilds the **sound** from `target` -- the second half of a restart -- | 2306 | /// 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). | ||
| 2264 | fn start_audio(&mut self, target: u32) -> bool { | 2322 | fn start_audio(&mut self, target: u32) -> bool { |
| 2265 | let fps = self.meta.frame_rate; | 2323 | let fps = self.meta.frame_rate; |
| 2266 | let mut audio_running = false; | 2324 | let mut audio_running = false; |
| @@ -2306,21 +2364,39 @@ impl PlaybackSession { | |||
| 2306 | let gains = self.project.audio_gains(); | 2364 | let gains = self.project.audio_gains(); |
| 2307 | let limiter = self.project.limiter(); | 2365 | let limiter = self.project.limiter(); |
| 2308 | let controls = crate::audio::MixControls::new(gains.clone(), limiter); | 2366 | 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 | - }; | ||
| 2321 | // Only a mixed timeline has a mixer to talk to; the single-lane | 2367 | // Only a mixed timeline has a mixer to talk to; the single-lane |
| 2322 | - // flat path is the bit-exact one and has none. | 2368 | + // flat path is the bit-exact one and has none. Decided here from |
| 2323 | - live = (audio_running && controls.is_live()).then_some(controls); | 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); | ||
| 2324 | if !audio_running { | 2400 | if !audio_running { |
| 2325 | // Nothing will ever be fed again; let `tick` fall to wall time | 2401 | // Nothing will ever be fed again; let `tick` fall to wall time |
| 2326 | // instead of waiting on a device that has no more work coming. | 2402 | // 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) { | |||
| 2706 | if accepted > 0 && audio.content_at.load(Ordering::Acquire) < 0 { | 2782 | if accepted > 0 && audio.content_at.load(Ordering::Acquire) < 0 { |
| 2707 | let at = ao.position().unwrap_or(0).max(0); | 2783 | let at = ao.position().unwrap_or(0).max(0); |
| 2708 | audio.content_at.store(at, Ordering::Release); | 2784 | 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); | ||
| 2709 | } | 2796 | } |
| 2710 | accepted | 2797 | accepted |
| 2711 | }; | 2798 | }; |
crates/engine/tests/playback.rsmodified+84 -0
| @@ -7,6 +7,8 @@ | |||
| 7 | //! cargo test -p engine --release --test playback -- --nocapture | 7 | //! cargo test -p engine --release --test playback -- --nocapture |
| 8 | //! ``` | 8 | //! ``` |
| 9 | 9 | ||
| 10 | +use std::fs::File; | ||
| 11 | +use std::os::fd::AsRawFd; | ||
| 10 | use std::path::{Path, PathBuf}; | 12 | use std::path::{Path, PathBuf}; |
| 11 | use std::thread::sleep; | 13 | use std::thread::sleep; |
| 12 | use std::time::{Duration, Instant}; | 14 | use std::time::{Duration, Instant}; |
| @@ -375,6 +377,88 @@ fn seek_keeps_the_audio_clock() { | |||
| 375 | ); | 377 | ); |
| 376 | } | 378 | } |
| 377 | 379 | ||
| 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 | + | ||
| 378 | /// The edit list end to end: two cuts, drop the middle clip, play the result. | 462 | /// The edit list end to end: two cuts, drop the middle clip, play the result. |
| 379 | /// What comes out is one contiguous timeline whose *pictures* skip the hole -- | 463 | /// What comes out is one contiguous timeline whose *pictures* skip the hole -- |
| 380 | /// no audio needed, so this runs anywhere. | 464 | /// no audio needed, so this runs anywhere. |