feat(qt): listen log tracker on the playback poll loop

listen_log_qt binds the per-user ListenLogger at login/restore/offline
entry and drops it at logout. Hooks: the de-duped track edge opens a row
(closing the previous as skip), every 1 Hz tick feeds the accumulator,
the natural end-of-track predicate closes as natural, the stream-failure
toast closes as error, three consecutive empty ticks are the stop, and
main.rs closes the row in flight as shutdown after the event loop (and
on the Windows session-commit path). Cast and peer QConnect stay out.
Ephemeral ids never reach the log (same guard as recently_qt).

cc
This commit is contained in:
vicrodh committed 2026-08-28 20:30:43 -06:00
1 parent ef665dcc5c
commit b38cb34f08
4 files changed
+198

No files matched your search

+11
View File
@@ -141,6 +141,9 @@ where
// playback prefs inside init_for_user, so it works before Settings has
// published anything.
qbz_app::session_persist::init_for_user(&dir);
// Listen log (per-user listen_log.db) — opens async; rows start
// once the store is bound.
crate::listen_log_qt::init_for_user(&dir);
// Phase 5: local-favorites store (Library show-local + hearts).
crate::library_qt::init_local_favorites(&dir);
// Qobuz favourite-id cache (favorites_cache.db, shared with the Slint
@@ -318,6 +321,9 @@ where
crate::local_plex::init_for_user(&dir);
// Session persistence — see the fresh-login path.
qbz_app::session_persist::init_for_user(&dir);
// Listen log (per-user listen_log.db) — opens async; rows start
// once the store is bound.
crate::listen_log_qt::init_for_user(&dir);
crate::library_qt::init_local_favorites(&dir);
// Qobuz favourite-id cache — see the fresh-login path.
crate::fav_cache_qt::init_for_user(&dir);
@@ -393,6 +399,9 @@ where
// playback prefs inside init_for_user, so it works before Settings has
// published anything.
qbz_app::session_persist::init_for_user(&dir);
// Listen log (per-user listen_log.db) — opens async; rows start
// once the store is bound.
crate::listen_log_qt::init_for_user(&dir);
// Phase 5: local-favorites store (Library show-local + hearts).
crate::library_qt::init_local_favorites(&dir);
// Qobuz favourite-id cache. The disk seed is the ONLY source offline
@@ -439,6 +448,8 @@ where
crate::local_plex::reset();
crate::playlist_qt::teardown();
crate::integrations_qt::unbind_qobuz_user();
// Listen log: close the row in flight and drop the per-user binding.
crate::listen_log_qt::teardown().await;
// Intelligent Search: the LEARNED ranking is per-user. Without this the
// next account inherits a stranger's most-clicked results as its promoted
// top result, and keeps writing into their buckets.
+155
View File
@@ -0,0 +1,155 @@
//! Listen log glue for the Qt shell — the per-user [`ListenLogger`] binding
//! and the four hooks the playback poll loop calls.
//!
//! WIRED (all in `playback_qt::start_poll_loop`, next to the other
//! track-edge consumers):
//! - the DE-DUPED track edge → [`on_track_edge`] (opens a row; closes the
//! previous one as `skip` if it was still open);
//! - every tick with a live track → [`on_tick`] (the accumulator; a tick
//! with `track_id == 0` is the stop detector);
//! - the natural end-of-track edge → [`on_natural_end`];
//! - `main.rs` after the event loop → [`shutdown_blocking`].
//!
//! Nothing here reads the log back. The Settings toggle / clear are the only
//! other callers ([`set_enabled`], [`clear`]).
use std::path::Path;
use std::sync::{Arc, OnceLock, RwLock};
use qbz_app::listen_log::{meta_from_queue_track, ListenLogger, Origin};
use qbz_models::QueueTrack;
use qbz_player::PlaybackEvent;
static LOGGER: OnceLock<RwLock<Option<Arc<ListenLogger>>>> = OnceLock::new();
/// A `track_id == 0` tick is normally the sub-second gap while the engine
/// swaps streams; only this many CONSECUTIVE empty ticks (1 Hz) mean the
/// user actually stopped. Below that a following edge closes the row as a
/// skip instead, which is what it was.
const STOP_AFTER_EMPTY_TICKS: u32 = 3;
static EMPTY_TICKS: std::sync::atomic::AtomicU32 = std::sync::atomic::AtomicU32::new(0);
fn slot() -> &'static RwLock<Option<Arc<ListenLogger>>> {
LOGGER.get_or_init(|| RwLock::new(None))
}
fn logger() -> Option<Arc<ListenLogger>> {
slot().read().ok()?.clone()
}
/// Bind the store for the user that just logged in (`auth_qt`, beside the
/// other per-user stores). Opening is async; until it completes the hooks
/// are no-ops, which at worst misses the first seconds of the first track.
pub fn init_for_user(user_dir: &Path) {
let dir = user_dir.to_path_buf();
crate::spawn(async move {
match ListenLogger::open(dir, Origin::Install).await {
Ok(logger) => {
if let Ok(mut g) = slot().write() {
*g = Some(logger);
}
}
Err(e) => log::warn!("[qbz-qt] listen log open failed: {e}"),
}
});
}
/// Logout: close the row in flight (as `stop`) and drop the binding so the
/// next account never writes into this one's file.
pub async fn teardown() {
let taken = slot().write().ok().and_then(|mut g| g.take());
if let Some(logger) = taken {
logger.stopped(false).await;
}
}
/// Orderly exit: close the row in flight as `shutdown`. Synchronous —
/// called from `main.rs` after the event loop, behind the hard-exit
/// watchdog like the session flush next to it.
pub fn shutdown_blocking() {
if let Some(logger) = logger() {
logger.shutdown_blocking();
}
}
/// The de-duped track edge. `event` is the poll's own `PlaybackEvent`, which
/// carries the ACTUAL stream facts (bit depth / sample rate) — the queue row
/// only knows what the catalogue claimed.
pub async fn on_track_edge(track: &QueueTrack, event: &PlaybackEvent) {
// Ephemeral rows (CD / ad-hoc folder) never reach any history — owner
// rule, same guard as `recently_qt::record_queue_track`.
if crate::local_ephemeral::is_ephemeral_id(track.id as i64) {
return;
}
let Some(logger) = logger() else {
return;
};
EMPTY_TICKS.store(0, std::sync::atomic::Ordering::Relaxed);
let backend = event
.bit_perfect_mode
.map(|m| format!("{m:?}").to_ascii_lowercase());
let meta = meta_from_queue_track(track, event.bit_depth, event.sample_rate, backend);
logger.track_started(meta, false).await;
}
/// One poll tick. `position_secs` is the engine's whole-second position;
/// the accumulator only credits monotonic deltas of at most 5 s while
/// `is_playing`, so pauses and seeks add nothing.
pub async fn on_tick(track_id: u64, position_secs: u64, is_playing: bool) {
let Some(logger) = logger() else {
return;
};
if track_id == 0 {
if !logger.has_open_row() {
return;
}
let n = EMPTY_TICKS.fetch_add(1, std::sync::atomic::Ordering::Relaxed) + 1;
if n >= STOP_AFTER_EMPTY_TICKS {
EMPTY_TICKS.store(0, std::sync::atomic::Ordering::Relaxed);
logger.stopped(false).await;
}
return;
}
EMPTY_TICKS.store(0, std::sync::atomic::Ordering::Relaxed);
logger.tick(position_secs * 1_000, is_playing).await;
}
/// The poll loop's natural end-of-track edge (the `track_ended` predicate),
/// BEFORE anything advances the cursor.
pub async fn on_natural_end() {
if let Some(logger) = logger() {
logger.ended_naturally().await;
}
}
/// A stream failure on the current track.
pub async fn on_error() {
if let Some(logger) = logger() {
logger.errored().await;
}
}
// ----- Settings -------------------------------------------------------------
/// The "Listening history" toggle state for the Settings snapshot. `true`
/// while no store is bound (the default is ON, and a fresh user has no
/// `paused` flag yet).
pub fn is_enabled() -> bool {
logger().map(|l| !l.is_paused()).unwrap_or(true)
}
pub async fn set_enabled(value: bool) -> Result<(), String> {
match logger() {
Some(logger) => logger.set_paused(!value).await,
None => Err("listening history store is not open".to_string()),
}
}
/// "Clear listening history" — DELETE + VACUUM; the row in flight goes too.
pub async fn clear() -> Result<(), String> {
match logger() {
Some(logger) => logger.clear().await,
None => Err("listening history store is not open".to_string()),
}
}
+7
View File
@@ -13,6 +13,7 @@
//! async work; results hop back to Qt through the bridge's `CxxQtThread`.
mod auth_qt;
mod listen_log_qt;
mod deep_link_qt;
#[cfg(target_os = "linux")]
mod single_instance_qt;
@@ -441,6 +442,8 @@ extern "C" fn on_session_commit_data() {
// bound at shell entry. Safe from a plain thread; it would
// panic only from inside an async context, which this is not.
qbz_app::session_persist::save_on_exit();
// Listen log: the row in flight closes as `shutdown` here too.
listen_log_qt::shutdown_blocking();
let _ = tx.send(());
});
if let Err(e) = spawned {
@@ -3650,6 +3653,10 @@ fn main() {
// app with no window that only `kill -9` ends — the 2026-08-04 quit
// incident exactly. No-op unless `persist_session` is on.
qbz_app::session_persist::save_on_exit();
// Listen log: close the row in flight as `shutdown`. Same placement
// and the same reasoning as the session flush above (one SQLite
// write on the main thread, behind the watchdog).
listen_log_qt::shutdown_blocking();
// Same reason as logout: leaving the app must stop the renderer.
//
+25
View File
@@ -1160,6 +1160,8 @@ pub(crate) async fn fetch_album_queue(
source_item_id_hint: Some(album.id.clone()),
context_kind: Some("album".to_string()),
context_id: Some(album.id.clone()),
isrc: track.isrc.clone(),
recording_mbid: None,
})
.collect();
Ok(tracks)
@@ -1248,6 +1250,8 @@ async fn offline_album_queue(album_id: &str) -> Result<Vec<QueueTrack>, String>
source_item_id_hint: local.map(|row| row.id.to_string()),
context_kind: Some("album".to_string()),
context_id: Some(album_id.to_string()),
isrc: None,
recording_mbid: None,
}
})
.collect())
@@ -1314,6 +1318,8 @@ fn artist_top_queue_tracks(
source_item_id_hint: album_id,
context_kind: Some("artist".to_string()),
context_id: Some(artist_id.to_string()),
isrc: None,
recording_mbid: None,
}
})
.collect()
@@ -2054,6 +2060,8 @@ fn feed_queue_track(track_id: u64) -> Result<QueueTrack, String> {
source_item_id_hint: None,
context_kind: None,
context_id: None,
isrc: None,
recording_mbid: None,
})
}
@@ -2126,6 +2134,8 @@ async fn catalog_queue_track(
source_item_id_hint: album_key,
context_kind: None,
context_id: None,
isrc: track.isrc.clone(),
recording_mbid: None,
})
}
@@ -3145,6 +3155,9 @@ pub fn start_poll_loop(runtime: Arc<AppRuntime<LoggingAdapter>>) {
qbz_audio::health::Sandbox::None
);
crate::toast_qt::error(stream_error_text(&msg, sandboxed));
// Listen log: a stream that died mid-track closes as `error`
// (a track that never started has no row to close).
crate::listen_log_qt::on_error().await;
}
// --- QConnect CONTROLLER mode: peer-state reflection ----------
@@ -3388,6 +3401,10 @@ pub fn start_poll_loop(runtime: Arc<AppRuntime<LoggingAdapter>>) {
if let Some(track) = runtime.core().get_queue_state().await.current_track {
crate::recently_qt::record_queue_track(&track);
crate::home_qt::note_recent_store_changed();
// Listen log: open the row for this track (and close
// the previous one as a skip if it is still open).
// Runs BESIDE the old stores, never instead of them.
crate::listen_log_qt::on_track_edge(&track, &event).await;
}
}
// Persist the session (queue + current track + position) so a
@@ -3417,6 +3434,9 @@ pub fn start_poll_loop(runtime: Arc<AppRuntime<LoggingAdapter>>) {
if track_id != 0 {
log::debug!("[qbz-qt] poll: id={track_id} pos={position}/{duration} playing={is_playing} cache={cache:.2}");
}
// Listen log accumulator: credits audible seconds only (playing,
// monotonic, <= 5 s per tick); a run of empty ticks is the stop.
crate::listen_log_qt::on_tick(track_id, position, is_playing).await;
// --- Position / state push ------------------------------------
// Seek lock first, so the bar never renders a position push whose
@@ -3664,6 +3684,9 @@ pub fn start_poll_loop(runtime: Arc<AppRuntime<LoggingAdapter>>) {
&& duration > 0
&& seen_position + 2 >= duration;
if track_ended {
// Listen log: the natural end, before anything moves the
// cursor (the next edge must find no open row).
crate::listen_log_qt::on_natural_end().await;
// Seed for InfiniteRadio, read BEFORE anything moves the
// cursor: the track that just ended is still the current one.
let ended_track_id = runtime
@@ -3816,6 +3839,8 @@ mod tests {
source_item_id_hint: None,
context_kind: None,
context_id: None,
isrc: None,
recording_mbid: None,
}
}