previews: the glow goes, the eq steps, and every clip lands before you scroll to it

The track preview modal could hold a machine at 25% GPU. Three separate
causes, each measured in isolation with a kill-style ladder and, once the
GPU-engine counter proved to be clock-relative (a lighter workload read
HIGHER), with clock-immune process CPU-seconds.

Idle drain. The scrim's backdrop-filter is re-executed on every presented
frame -- a backdrop filter is never cached -- so its cost is presents/sec
times window area. Two infinite animations kept the modal presenting at the
display's refresh rate forever: the eq capsule's bars animated `height` (a
layout property, so style/layout/paint on the main thread every vsync) and
the cover glow's halo-breathe kept a blur(48px) copy recompositing. Either
one alone kept the pipeline hot, which is why killing one changed nothing.
The glow is deleted outright at Kyle's request; the eq bars now scale with
a stepped transform whose three delays are multiples of the step interval,
so all three jump on the same instants and one present serves them all.
Playing steady state: 7.2-10.5% of a core down to 1.4-2.2%. Paused: 0.2%.

Scrolling. The animations turned out to be innocent here -- reverting them
moved the number not at all. The cost was per-step work: re-decoding the
full artwork for the background wash, a main-thread accent scan, a new
cover mount, three times a second. The wash is now a 96x58 canvas with the
blur/saturate/brightness baked in at draw time and cached per artwork, and
an overlay preloader walks the manifest once at open -- nearest to the
active card first, capped at 60 -- filling the decoded-image, wash and
accent caches ahead of the user. A rapid-nav jump-cut was tried and
rejected on sight; the animations stay full at every rate.

Backend. preview_resolve swept the clip directory on every call, and any
landing outside the +/-1 prefetch window paid a full Deezer mint, download,
validate, write and loudness measure. The fetch-store-measure core is
factored out and a new preview_prewarm walks the session's track ids at
open, paced 250ms on top of the existing Deezer throttle and starting 1.5s
in so the first clip owns the network, halted by a generation guard on
dispose. A burst landing on a never-visited track is now audible in 154ms
off local disk. The sweep is throttled to ten minutes, and dispose deletes
prewarmed files instead of orphaning them until the hourly reap.

The debug overlay's GPU row was summing the counters machine-wide, so it
read roughly double the app's share with Discord and DWM folded in. It now
reports `app X% - sys Y%`, the app figure restricted to our process tree,
matching Task Manager's per-process rows.
This commit is contained in:
KeelrLeek committed 2026-08-01 07:11:17 -05:00
1 parent eba29824c9
commit 69f64c11eb
8 files changed
+440 -116

No files matched your search

+34 -4
View File
@@ -61,7 +61,12 @@ pub struct DebugStats {
pub cpu_process: f32,
pub cpu_system: f32,
/// GPU 3D-engine utilization (Task-Manager-style), if counters opened.
/// MACHINE-WIDE — includes DWM, browsers, Discord, everything.
pub gpu_percent: Option<f32>,
/// Same counters, restricted to OUR process tree — the app's true GPU
/// share, matching Task Manager's per-process rows. The machine-wide
/// number above routinely reads 2× this on a busy desktop.
pub gpu_app_percent: Option<f32>,
/// Process tree working set / private commit, bytes.
pub mem_working_set: u64,
pub mem_private: u64,
@@ -159,10 +164,14 @@ pub fn debug_stats(app: tauri::AppHandle, state: State<'_, DiagState>) -> DebugS
None => (None, None, None),
};
let tree_u32: Vec<u32> = tree.iter().map(|p| p.as_u32()).collect();
let gpu_sample = inner.gpu.as_mut().and_then(|g| g.sample(&tree_u32));
DebugStats {
cpu_process,
cpu_system: inner.sys.global_cpu_usage(),
gpu_percent: inner.gpu.as_mut().and_then(|g| g.sample()),
gpu_percent: gpu_sample.map(|(sys, _)| sys),
gpu_app_percent: gpu_sample.map(|(_, app)| app),
mem_working_set,
mem_private,
mem_system_used: inner.sys.used_memory(),
@@ -257,7 +266,10 @@ impl GpuCounter {
}
}
fn sample(&mut self) -> Option<f32> {
/// Returns (machine_total, app_tree_total). Instance names carry the
/// owning pid — "pid_1234_luid_..._engtype_3D" — so the app's share is
/// the sum over instances whose pid is in our process tree.
fn sample(&mut self, app_pids: &[u32]) -> Option<(f32, f32)> {
use windows::Win32::System::Performance::{
PdhCollectQueryData, PdhGetFormattedCounterArrayW, PDH_FMT_COUNTERVALUE_ITEM_W,
PDH_FMT_DOUBLE,
@@ -292,14 +304,32 @@ impl GpuCounter {
return None;
}
let mut total = 0.0f64;
let mut app = 0.0f64;
for i in 0..count as usize {
total += (*items.add(i)).FmtValue.Anonymous.doubleValue;
let item = &*items.add(i);
let v = item.FmtValue.Anonymous.doubleValue;
total += v;
if !item.szName.is_null() {
if let Some(pid) = instance_pid(item.szName) {
if app_pids.contains(&pid) {
app += v;
}
}
}
}
Some(total.min(100.0) as f32)
Some((total.min(100.0) as f32, app.min(100.0) as f32))
}
}
}
/// Parse the pid out of a "pid_1234_luid_…" counter-instance name.
unsafe fn instance_pid(name: windows::core::PWSTR) -> Option<u32> {
let s = name.to_string().ok()?;
let rest = s.strip_prefix("pid_")?;
let digits: String = rest.chars().take_while(|c| c.is_ascii_digit()).collect();
digits.parse().ok()
}
impl Drop for GpuCounter {
fn drop(&mut self) {
use windows::Win32::System::Performance::PdhCloseQuery;
+1
View File
@@ -113,6 +113,7 @@ pub fn run() {
commands::preload_cached_stream,
commands::stream_waveform,
preview::preview_resolve,
preview::preview_prewarm,
preview::preview_load,
preview::preview_control,
preview::preview_dispose,
+158 -43
View File
@@ -47,10 +47,28 @@ const SAFETY_MARGIN_MS: i64 = 20_000;
const FALLBACK_SAFE_MS: i64 = 60_000;
const MAX_SAFE_MS: i64 = 30 * 60_000;
/// Clip files older than this are swept on init and on each resolve — a
/// preview session never legitimately needs an hour-old clip.
/// Clip files older than this are swept on init and periodically from the
/// resolve path — a preview session never legitimately needs an hour-old clip.
const CLIP_MAX_AGE: Duration = Duration::from_secs(60 * 60);
/// The resolve-path sweep runs at most this often. Sweeping on every resolve
/// was a directory walk + stat per step of a scrolling session for files
/// that age out hourly.
const SWEEP_MIN_INTERVAL: Duration = Duration::from_secs(10 * 60);
/// Pace between prewarm downloads. Rides ON TOP of the metadata crate's own
/// Deezer throttle; this keeps the walker from ever competing with a live
/// step's resolve for the gate.
const PREWARM_SPACING: Duration = Duration::from_millis(250);
/// The walker starts after the session's opening resolve (and its ±1
/// neighbour prefetches) have had the network to themselves.
const PREWARM_INITIAL_DELAY: Duration = Duration::from_millis(1500);
/// Hard cap on one prewarm call, mirroring the frontend preloader's cap — a
/// 500-item manifest warms its head, not the whole tail.
const PREWARM_CAP: usize = 60;
/// Re-resolving a track whose clip bytes are already on disk skips the
/// network entirely within this window (the bytes are immutable audio — only
/// the signed URL goes stale, and a local file needs no URL). This is what
@@ -96,6 +114,12 @@ pub struct PreviewState {
recent_clips: Mutex<HashMap<u64, (PathBuf, f32, Instant)>>,
clip_dir: PathBuf,
lease_counter: AtomicU64,
/// Generation guard for the session prewarm walker: bumping it (a new
/// prewarm call, or dispose) halts any walker still in flight.
prewarm_gen: Arc<AtomicU64>,
/// The resolve-path clip sweep runs at most once per SWEEP_MIN_INTERVAL —
/// it used to walk the clip directory on EVERY resolve.
last_sweep: Mutex<Instant>,
}
impl PreviewState {
@@ -251,6 +275,8 @@ pub fn init(app: &tauri::AppHandle) {
recent_clips: Mutex::new(HashMap::new()),
clip_dir,
lease_counter: AtomicU64::new(1),
prewarm_gen: Arc::new(AtomicU64::new(0)),
last_sweep: Mutex::new(Instant::now()),
});
// One forwarder per voice. Only the ACTIVE voice's events reach the UI:
@@ -425,25 +451,28 @@ fn measure_clip_gain(app: &tauri::AppHandle, path: &std::path::Path) -> f32 {
}
}
#[tauri::command]
pub async fn preview_resolve(
app: tauri::AppHandle,
library: State<'_, LibraryState>,
state: State<'_, PreviewState>,
/// A clip fetched, validated, stored on disk and loudness-measured — the
/// shared core of the live resolve and the session prewarm. Registers the
/// clip in `recent_clips`; minting a lease over it is the caller's business.
struct StoredClip {
path: PathBuf,
gain: f32,
byte_length: usize,
safe_for_ms: i64,
}
async fn fetch_store_clip(
app: &tauri::AppHandle,
library: &LibraryState,
state: &PreviewState,
track_id: u64,
) -> Result<PreviewResolveResult, String> {
sweep_old_clips(&state.clip_dir);
if let Some(cached) = mint_from_recent_clip(&state, track_id) {
return Ok(cached);
}
) -> Result<StoredClip, PreviewResolveResult> {
let Some(body) = library.metadata.deezer_track_uncached(track_id).await else {
return Ok(fail("network", true));
return Err(fail("network", true));
};
if let Some(err) = body.get("error") {
let class = err.get("type").and_then(|t| t.as_str()).unwrap_or("");
return Ok(match class {
return Err(match class {
// Deezer's 200-with-error-body shapes, from Phase 0.
"DataException" | "InvalidQueryException" => fail("not_found", false),
_ => fail("temporarily_failed", true),
@@ -455,16 +484,16 @@ pub async fn preview_resolve(
.unwrap_or("")
.to_string();
if preview_url.is_empty() {
return Ok(fail("not_provided", false));
return Err(fail("not_provided", false));
}
let media = match metadata::fetch_preview_media(&preview_url).await {
Ok(m) => m,
Err(metadata::PreviewFetchError::Status(403)) => return Ok(fail("stale_lease", true)),
Err(metadata::PreviewFetchError::Status(_)) => return Ok(fail("temporarily_failed", true)),
Err(metadata::PreviewFetchError::DisallowedUrl) => return Ok(fail("invalid_media", false)),
Err(metadata::PreviewFetchError::TooLarge) => return Ok(fail("invalid_media", false)),
Err(metadata::PreviewFetchError::Network) => return Ok(fail("network", true)),
Err(metadata::PreviewFetchError::Status(403)) => return Err(fail("stale_lease", true)),
Err(metadata::PreviewFetchError::Status(_)) => return Err(fail("temporarily_failed", true)),
Err(metadata::PreviewFetchError::DisallowedUrl) => return Err(fail("invalid_media", false)),
Err(metadata::PreviewFetchError::TooLarge) => return Err(fail("invalid_media", false)),
Err(metadata::PreviewFetchError::Network) => return Err(fail("network", true)),
};
// MIME gate first (the stale-lease body is an HTML error page), then the
@@ -477,21 +506,21 @@ pub async fn preview_resolve(
.as_deref()
.is_some_and(|m| m.starts_with("audio/mpeg"));
if !mime_ok {
return Ok(fail("invalid_media", false));
return Err(fail("invalid_media", false));
}
let audio = strip_id3v2(&media.bytes);
if !starts_with_mpeg_sync(audio) {
return Ok(fail("invalid_media", false));
return Err(fail("invalid_media", false));
}
let nonce = state.lease_counter.fetch_add(1, Ordering::Relaxed);
let lease_id = format!("pv-{track_id}-{nonce}");
let path = state.clip_dir.join(format!("{lease_id}.mp3"));
let path = state.clip_dir.join(format!("pv-{track_id}-{nonce}.mp3"));
if std::fs::write(&path, audio).is_err() {
return Ok(fail("temporarily_failed", true));
return Err(fail("temporarily_failed", true));
}
// Measure loudness off the async worker (a 30 s clip decodes in tens of
// ms). On a prefetched neighbour this is fully off the playback path.
// ms). On a prefetched or prewarmed clip this is fully off the playback
// path.
let gain = {
let app2 = app.clone();
let path2 = path.clone();
@@ -499,26 +528,61 @@ pub async fn preview_resolve(
.await
.unwrap_or(1.0)
};
state
.leases
.lock()
.expect("preview lease lock")
.insert(lease_id.clone(), (path.clone(), gain));
let byte_length = audio.len();
state
.recent_clips
.lock()
.expect("preview clip lock")
.insert(track_id, (path, gain, Instant::now()));
.insert(track_id, (path.clone(), gain, Instant::now()));
let safe_for_ms =
compute_safe_for_ms(parse_exp_ms(&preview_url), media.date_ms, now_epoch_ms());
Ok(StoredClip {
path,
gain,
byte_length,
safe_for_ms: compute_safe_for_ms(parse_exp_ms(&preview_url), media.date_ms, now_epoch_ms()),
})
}
#[tauri::command]
pub async fn preview_resolve(
app: tauri::AppHandle,
library: State<'_, LibraryState>,
state: State<'_, PreviewState>,
track_id: u64,
) -> Result<PreviewResolveResult, String> {
{
// Throttled sweep: a directory walk per resolve was pure waste in a
// scrolling session; hour-old files don't need minute-fresh reaping.
let mut last = state.last_sweep.lock().expect("preview sweep lock");
if last.elapsed() > SWEEP_MIN_INTERVAL {
*last = Instant::now();
sweep_old_clips(&state.clip_dir);
}
}
if let Some(cached) = mint_from_recent_clip(&state, track_id) {
return Ok(cached);
}
let stored = match fetch_store_clip(&app, &library, &state, track_id).await {
Ok(s) => s,
Err(failure) => return Ok(failure),
};
let nonce = state.lease_counter.fetch_add(1, Ordering::Relaxed);
let lease_id = format!("pv-{track_id}-{nonce}");
state
.leases
.lock()
.expect("preview lease lock")
.insert(lease_id.clone(), (stored.path, stored.gain));
Ok(PreviewResolveResult {
ok: true,
lease: Some(PreviewLeaseDto {
opaque_lease_id: lease_id,
safe_for_ms,
byte_length: audio.len(),
safe_for_ms: stored.safe_for_ms,
byte_length: stored.byte_length,
mime_type: "audio/mpeg".into(),
clip_duration_ms: 30_000,
}),
@@ -527,6 +591,50 @@ pub async fn preview_resolve(
})
}
/// Best-effort session prewarm: walk the manifest's Deezer track ids in
/// session order and pull every clip onto disk ahead of the user, so a step
/// landing ANYWHERE in the session resolves from `recent_clips` without
/// touching the network — the audio-side twin of the overlay's artwork
/// preloader (Kyle's call 2026-08-01: decode once at open, never during
/// scrolling). Paced gently (PREWARM_SPACING between clips, on top of the
/// metadata crate's own Deezer throttle), capped at PREWARM_CAP, and halted
/// by the generation guard the moment the session closes or a newer session
/// opens. Failures are skipped silently — the live resolve path still owns
/// error classification for anything the user actually lands on.
#[tauri::command]
pub async fn preview_prewarm(
app: tauri::AppHandle,
library: State<'_, LibraryState>,
state: State<'_, PreviewState>,
track_ids: Vec<u64>,
) -> Result<(), String> {
let my_gen = state.prewarm_gen.fetch_add(1, Ordering::Relaxed) + 1;
let gen_ctr = state.prewarm_gen.clone();
let fresh = move || gen_ctr.load(Ordering::Relaxed) == my_gen;
tokio::time::sleep(PREWARM_INITIAL_DELAY).await;
for track_id in track_ids.into_iter().take(PREWARM_CAP) {
if !fresh() {
return Ok(());
}
let cached = {
let clips = state.recent_clips.lock().expect("preview clip lock");
clips
.get(&track_id)
.is_some_and(|(_, _, at)| at.elapsed() < CLIP_REUSE_TTL)
};
if cached {
continue;
}
let _ = fetch_store_clip(&app, &library, &state, track_id).await;
if !fresh() {
return Ok(());
}
tokio::time::sleep(PREWARM_SPACING).await;
}
Ok(())
}
// ------------------------------------------------------------ transport ---
/// Load a resolved clip into the preview player. `start_paused` uses the
@@ -664,6 +772,8 @@ pub fn preview_control(
/// call repeatedly (close, navigation, hot reload all funnel here).
#[tauri::command]
pub fn preview_dispose(state: State<'_, PreviewState>) -> Result<(), String> {
// Halt any in-flight session prewarm walker before touching the caches.
state.prewarm_gen.fetch_add(1, Ordering::Relaxed);
state.bump_fades();
state.voices[0].stop();
state.voices[1].stop();
@@ -672,11 +782,16 @@ pub fn preview_dispose(state: State<'_, PreviewState>) -> Result<(), String> {
state.set_clip_gain(1, 1.0);
state.set_vol(0, state.target());
state.set_vol(1, state.target());
state
.recent_clips
.lock()
.expect("preview clip lock")
.clear();
// Drain BOTH maps and delete the files each references — prewarmed clips
// exist only in recent_clips (no lease was ever minted over them), so
// clearing the map without deleting orphaned them until the hourly
// sweep. Shared paths get two remove attempts; the second is a no-op.
{
let mut clips = state.recent_clips.lock().expect("preview clip lock");
for (_, (path, _gain, _at)) in clips.drain() {
let _ = std::fs::remove_file(path);
}
}
let mut leases = state.leases.lock().expect("preview lease lock");
for (_, (path, _gain)) in leases.drain() {
let _ = std::fs::remove_file(path);