fix(viz): stop the visualizer pipeline while paused

The NPB Large dock idled at ~2.5% CPU paused: the visualizer gates on
visibility only, so the FFT producer kept re-transforming the stale
ring buffer at 30fps and the drain timer kept churning the 28 bar
models. Producer now parks when enabled-but-paused (same bounded
200ms park_timeout shape as the existing disabled-park; the atomic is
a lone Relaxed store, submit path untouched); the drain early-returns
when not playing and unparks the producer on the resume edge, so
fresh bars land in <100ms. The paused flag is stored at every
playing-state flip: toggle, track meta seed, the poll loop dirty-push
(catch-all for MPRIS/tray/hotkeys/QConnect within one 450ms tick),
the cast poll while casting, stop-after, queue end and the
unavailable-skip halts. Bars freeze at their last values while
paused; immersive freezes too — intended. Legacy Tauri tree's tap
literal gained the field to keep compiling.

cc
This commit is contained in:
vicrodh committed 2026-07-08 16:57:28 -06:00
1 parent fef978fc76
commit f5ed2ec1fe
6 files changed
+119 -13

No files matched your search

+22
View File
@@ -38,6 +38,13 @@ pub struct VisualizerTap {
pub ring_buffer: Arc<RingBuffer>,
/// Whether visualization is enabled
pub enabled: Arc<AtomicBool>,
/// Whether playback is paused. While `enabled && paused` the FFT producer
/// parks instead of re-FFTing the stale ring buffer at TARGET_FPS (the
/// buffer receives no new samples while the player is paused/stopped).
/// Consumer-side gate only — `push()` does NOT check it, so the
/// sample-submit path is untouched. Defaults to `false` (not paused) so
/// frontends that never wire it keep the historical behavior.
pub paused: Arc<AtomicBool>,
/// Current sample rate
pub sample_rate: Arc<AtomicU32>,
}
@@ -48,6 +55,7 @@ impl VisualizerTap {
Self {
ring_buffer: Arc::new(RingBuffer::new(FFT_SIZE * 2)),
enabled: Arc::new(AtomicBool::new(false)),
paused: Arc::new(AtomicBool::new(false)),
sample_rate: Arc::new(AtomicU32::new(44100)),
}
}
@@ -71,6 +79,20 @@ impl VisualizerTap {
self.enabled.store(enabled, Ordering::Relaxed);
}
/// Check if playback is paused (fast atomic check)
#[inline]
pub fn is_paused(&self) -> bool {
self.paused.load(Ordering::Relaxed)
}
/// Mark playback as paused/resumed. While paused (and enabled) the FFT
/// producer parks on a bounded timeout instead of burning CPU on the
/// stale buffer; it self-wakes within that bound after a resume, so no
/// caller is required to unpark it. Atomic store — never blocks.
pub fn set_paused(&self, paused: bool) {
self.paused.store(paused, Ordering::Relaxed);
}
/// Update the sample rate
pub fn set_sample_rate(&self, rate: u32) {
self.sample_rate.store(rate, Ordering::Relaxed);
+17 -12
View File
@@ -65,11 +65,13 @@ pub trait VizSink: Send + Sync {
fn submit(&self, frame: VizFrame);
}
/// Disabled-state idle poll. Instead of spinning at `TARGET_FPS` while the tap
/// is off, the producer parks for this long between `enabled` re-checks. An
/// enable path MAY `unpark()` the thread (via the returned `JoinHandle`'s
/// `.thread()`) for an instant wake — the Slint frontend does; callers that
/// don't still get picked up within this bound.
/// Idle poll for the disabled AND paused states. Instead of spinning at
/// `TARGET_FPS` while the tap is off (or the player is paused and the ring
/// buffer is stale), the producer parks for this long between re-checks of the
/// `enabled`/`paused` atomics. An enable/resume path MAY `unpark()` the thread
/// (via the returned `JoinHandle`'s `.thread()`) for an instant wake — the
/// Slint frontend does; callers that don't still get picked up within this
/// bound (≤200ms, well under the ~250ms resume-latency budget).
const IDLE_POLL: Duration = Duration::from_millis(200);
/// Spawn the FFT processing thread. Idempotency is the caller's concern (the
@@ -88,8 +90,8 @@ pub fn spawn_visualizer_thread(tap: VisualizerTap, sink: Arc<dyn VizSink>) -> Jo
/// Main FFT processing loop. Reads samples from the tap's ring buffer, computes
/// all five streams at `TARGET_FPS`, and submits them to the sink. The enabled
/// path (pacing, `sample_rate` reads, `SpectralAnalyzer` cadence, DSP) matches
/// the historical Tauri loop; while DISABLED the thread parks (see [`IDLE_POLL`])
/// instead of spinning at `TARGET_FPS`.
/// the historical Tauri loop; while DISABLED or PAUSED the thread parks (see
/// [`IDLE_POLL`]) instead of spinning at `TARGET_FPS`.
fn run_fft_loop(tap: VisualizerTap, sink: Arc<dyn VizSink>) {
// Pre-allocate all buffers to avoid allocations in the hot path
let mut samples = vec![0.0f32; FFT_SIZE];
@@ -124,11 +126,14 @@ fn run_fft_loop(tap: VisualizerTap, sink: Arc<dyn VizSink>) {
let frame_duration = Duration::from_micros(1_000_000 / TARGET_FPS);
loop {
if !tap.enabled.load(Ordering::Relaxed) {
// Disabled: park instead of pacing at TARGET_FPS doing nothing.
// Spurious wakeups are fine (the loop just re-checks the atomic);
// the bounded timeout means no enable path is REQUIRED to unpark.
// Never blocks shutdown: the thread is detached and always wakes.
if !tap.enabled.load(Ordering::Relaxed) || tap.paused.load(Ordering::Relaxed) {
// Disabled OR paused: park instead of pacing at TARGET_FPS doing
// nothing (paused = the ring buffer receives no new samples, so
// re-FFTing it would burn CPU on identical stale data).
// Spurious wakeups are fine (the loop just re-checks the atomics);
// the bounded timeout means no enable/resume path is REQUIRED to
// unpark. Never blocks shutdown: the thread is detached and always
// wakes.
std::thread::park_timeout(IDLE_POLL);
continue;
}
+13
View File
@@ -870,6 +870,12 @@ impl SlintCastService {
// Push position to CastState + the now-playing bar (the local poll is
// stopped while casting, so the cast poll drives the bar).
// Mirror the flag onto the visualizer tap too: the local poll (which
// normally owns it) is skipped while casting, and a paused renderer
// must park the FFT producer like a local pause does.
if let Some(tap) = self.runtime.visualizer_tap() {
tap.set_paused(!playing);
}
let weak = self.window.clone();
let _ = weak.upgrade_in_event_loop(move |w| {
use slint::ComponentHandle;
@@ -1007,6 +1013,13 @@ impl SlintCastService {
inner.is_playing,
)
};
// Same tap mirror as poll_once: while connected this owns the bar's
// playing flag, so it owns the producer gate too.
if connected {
if let Some(tap) = self.runtime.visualizer_tap() {
tap.set_paused(!playing);
}
}
let weak = self.window.clone();
let _ = weak.upgrade_in_event_loop(move |w| {
use slint::ComponentHandle;
+43 -1
View File
@@ -642,6 +642,7 @@ fn auto_skip_unavailable<'a>(
if failed_track_id != 0
&& runtime.core().consume_stop_after_if(failed_track_id).await
{
set_viz_paused(runtime, true);
let _ = weak.upgrade_in_event_loop(|w| {
w.global::<NowPlayingState>().set_playing(false);
});
@@ -657,6 +658,7 @@ fn auto_skip_unavailable<'a>(
qbz_i18n::t("No available tracks to play"),
crate::ToastKind::Warning,
);
set_viz_paused(runtime, true);
let _ = weak.upgrade_in_event_loop(|w| {
w.global::<NowPlayingState>().set_playing(false);
});
@@ -1494,6 +1496,19 @@ fn load_now_playing_artwork_large(weak: slint::Weak<AppWindow>, art: qbz_models:
});
}
/// Mirror the playing/paused state onto the visualizer tap so the FFT producer
/// parks while nothing plays (paused/stopped it would otherwise re-FFT the
/// stale ring buffer at 30fps — the NPB Large dock idled at ~2.5% CPU). Called
/// next to every `NowPlayingState.set_playing` flip so the producer stays
/// consistent with the UI-thread drain gate (visualizer.rs), which keys off the
/// same flag. Atomic store — safe from any thread, never blocks; a paused park
/// self-wakes within 200ms after resume (no unpark required).
fn set_viz_paused(runtime: &Runtime, paused: bool) {
if let Some(tap) = runtime.visualizer_tap() {
tap.set_paused(paused);
}
}
/// Wall-clock now in milliseconds. Used by the poll loop to extrapolate the
/// peer renderer's position (`position_ms + (now - updated_at_ms)`) while
/// QBZ is CONTROLLING a peer (the local player is stopped, so the seek bar
@@ -1812,6 +1827,10 @@ pub(crate) async fn refresh_now_playing_meta(runtime: &Runtime, weak: &slint::We
// renders add vs remove honestly for the new track. Kept live between
// track changes by set_album_row_favorite (main.rs).
let album_favorite = crate::fav_cache::is_album_favorite(&album_id);
// The bar is seeded playing=true below — wake the visualizer producer with
// it (stored BEFORE the UI post so the drain gate never opens while the
// producer is still marked paused).
set_viz_paused(runtime, false);
let _ = weak.upgrade_in_event_loop(move |w| {
let np = w.global::<NowPlayingState>();
np.set_has_track(true);
@@ -3658,6 +3677,10 @@ pub fn toggle_play_pause(
if runtime.core().get_playback_state().is_playing {
if let Err(e) = runtime.core().pause() {
log::error!("[qbz-slint] playback: pause failed: {e}");
} else {
// Park the visualizer producer on the edge, ahead of the
// 450ms poll tick that mirrors the flag onto the bar.
set_viz_paused(&runtime, true);
}
// Persist the paused position so a restart resumes near where the
// user stopped (no-op unless `persist_session` is on).
@@ -3669,6 +3692,9 @@ pub fn toggle_play_pause(
if runtime.core().player().has_loaded_audio() {
if let Err(e) = runtime.core().resume() {
log::error!("[qbz-slint] playback: resume failed: {e}");
} else {
// Wake the producer on the edge — resume must feel instant.
set_viz_paused(&runtime, false);
}
return;
}
@@ -4041,6 +4067,11 @@ pub fn start_poll_loop(
);
if last_remote_ui_push != Some(remote_snapshot) {
last_remote_ui_push = Some(remote_snapshot);
// Keep the visualizer producer in step with the same flag
// the drain gate reads (a paused PEER parks it too; while
// the peer plays, the local buffer is stale — historical
// behavior, the bars simply freeze).
set_viz_paused(&runtime, !playing);
let elapsed = fmt_elapsed(position_secs);
let remaining = fmt_remaining(position_secs, duration_secs);
let _ = weak.upgrade_in_event_loop(move |w| {
@@ -4337,6 +4368,13 @@ pub fn start_poll_loop(
);
if last_ui_push != Some(ui_snapshot) {
last_ui_push = Some(ui_snapshot);
// Mirror engine truth onto the visualizer tap alongside the
// set_playing push below. This is the catch-all: EVERY local
// transition (pause/resume from any surface — MPRIS, tray,
// hotkey, QConnect renderer command — plus stop, track end,
// seek-while-paused snapshots) lands here within one 450ms
// tick; the direct edge sites above only shave latency.
set_viz_paused(&runtime, !is_playing);
let progress = if duration > 0 {
(position as f32 / duration as f32).clamp(0.0, 1.0)
} else {
@@ -4492,6 +4530,8 @@ pub fn start_poll_loop(
if let Err(e) = runtime.core().pause() {
log::warn!("[qbz-slint] stop-after: pause failed: {e}");
}
// Stop counts as paused for the visualizer tap.
set_viz_paused(&runtime, true);
last_track_id = 0;
was_playing = false;
seen_position = 0;
@@ -4516,8 +4556,10 @@ pub fn start_poll_loop(
// replaced the queue and refreshes the sidebar itself).
} else {
log::info!("[qbz-slint] playback: queue finished");
// Nothing more will play — force-clear any lingering spinner.
// Nothing more will play — force-clear any lingering spinner
// and park the visualizer producer (stop counts as paused).
clear_loading(&weak, 0);
set_viz_paused(&runtime, true);
let _ = weak.upgrade_in_event_loop(|w| {
let np = w.global::<NowPlayingState>();
np.set_playing(false);
+23
View File
@@ -116,10 +116,33 @@ pub fn install(window: &AppWindow, runtime: &Arc<AppRuntime<SlintAdapter>>) {
let mut last_progress = 0.0f32;
// Smoothed highest-active-band fraction → the spectral-ribbon ceiling line.
let mut last_peak = 0.0f32;
// Paused gate edge tracker (see the top of the closure).
let mut drain_saw_playing = false;
// Second handle to the producer thread for the resume unpark below (the
// original moves into the set-enabled handler).
let fft_thread_drain = fft_thread.clone();
timer.start(
slint::TimerMode::Repeated,
std::time::Duration::from_millis(33),
move || {
// Paused gate: while NowPlayingState says not-playing, skip the
// whole drain (cell takes, 28 set_row_data models, shader frame) —
// the producer is parked via the tap's `paused` flag (playback.rs
// mirrors every set_playing flip), so there is no fresh data; the
// bars simply freeze at their last values. On the paused→playing
// edge, unpark the producer so resume feels instant (≤33ms to
// observe the flag here vs its 200ms park self-wake).
let Some(win) = weak.upgrade() else {
return;
};
let playing = win.global::<NowPlayingState>().get_playing();
if playing && !drain_saw_playing {
fft_thread_drain.unpark();
}
drain_saw_playing = playing;
if !playing {
return;
}
if let Some(b) = cells.bars.lock().unwrap().take() {
for (i, v) in b.iter().enumerate() {
bars.set_row_data(i, *v);
+1
View File
@@ -1176,6 +1176,7 @@ pub fn run(qconnect_cli_override: Option<bool>) {
let v2_viz_tap = qbz_audio::VisualizerTap {
ring_buffer: v1_viz_tap.ring_buffer.clone(),
enabled: v1_viz_tap.enabled.clone(),
paused: v1_viz_tap.paused.clone(),
sample_rate: v1_viz_tap.sample_rate.clone(),
};
tauri::async_runtime::spawn(async move {