feat(enrichment): oximedia BPM/mood facts, mood search, and queue display (#863)

* feat(enrichment): oximedia BPM/mood facts, mood search, and queue UI

Run client-side oximedia analysis after CPU seed and persist BPM, mood JSON,
and searchable mood_tag facts. Add product mood groups (joy/sadness/dance/work/
romance) with Advanced Search filter on the local index, queue BPM/mood display,
migration 008 mood_tag index, and refreshed licenses for oximedia crates.

* fix(enrichment): keep mood_groups module comment in English

* feat(search): virtual mood groups, anger filter, and Advanced Search UX

Expand mood search via overlapping virtual groups (tag expansion only),
add anger/Злость group, skip album/artist shortcuts for track-only filters,
and simplify mood search UI (songs-only, hide type tabs). Fix CustomSelect
spurious scrollbar on short option lists.

* feat(analysis): unified track analysis plan and enqueue path

Add TrackAnalysisPlan (waveform, LUFS, enrichment) with a single
enqueue_track_analysis entry for all byte-backed triggers. Run enrichment
when cache is full but library facts are missing; route playback, cache,
and backfill through the planner. Fix browseTextSearch LocalSearchOpts tsc
gap and remove obsolete read_seed_bytes_if_needed helper.

* fix(analysis): wire playback dispatch, preload enrichment, and UI refresh

Route stream, gapless, preload, and local-file playback through analysis_dispatch
so BPM/mood enrichment runs when waveform/LUFS are already cached. Fix audio_preload
cache-hit and hot-cache paths, emit preload-cancelled for retry, and add
analysis:enrichment-updated plus content_cache_coverage key resolution.

* fix(audio): preload local files from disk and stop analysis retry loop

Seed hot/offline next tracks via LocalFilePlayback (512 MiB) instead of copying
into the RAM preload slot. Keep bytePreloadingId set after preload-ready so
progress ticks do not re-invoke audio_preload every second.

* fix(enrichment): clippy, album bpm filter routing, and queue mood display

Clippy-clean analysis_dispatch and engine imports; restrict track-derived album
routing to mood_group/mood_tag only so bpm is skipped on album queries. Log
enrichment plan errors with retry-all plan; filter queue mood labels to oximedia ids.

* fix(enrichment): simplify mood_tag backfill branch in plan_track_enrichment

Remove empty if-block; keep same behaviour when backfill fails and moods row exists.

* docs: CHANGELOG and credits for track enrichment PR #863

* docs(credits): track enrichment PR #863 contributor line

* chore(enrichment): clippy-clean plan branch and trim dead exports

Collapse mood_tag backfill if for clippy; remove unused moodGroupById and
OXIMEDIA_MOOD_LABELS re-exports; stop poll when server BPM is already known.

* fix(enrichment): close R2/S1–S3 limits and Song Info BPM fallback

Return TrackEnrichmentOutcome::Failed on oximedia errors so retries are not
masked as complete; extract mood Advanced Search SQL, unify top-3 mood tag
selection in mood_groups with TS invariant tests, and show measured BPM in
Song Info when tag BPM is missing or zero.

* fix(enrichment): restore offline coverage and show mood in Song Info

Add unit tests for offline download cancel/clear registry after the analysis
seed refactor dropped read_seed_bytes coverage; show localized mood labels in
Song Info when library enrichment facts exist.

* fix(enrichment): soft mood scoring and unblock offline cancel tests

Replace oximedia quadrant happy/excited mapping with valence/arousal
soft scores across all mood tags for display, storage, and backfill;
fix offline cancel unit tests that deadlocked by calling clear while
holding the global offline_cancel_flags mutex.

* fix(enrichment): dedupe joy cluster and cap mood display at two labels

Never show happy and excited together; pick one tag per V/A cluster,
tighten oximedia recalibration, and limit queue/Song Info to two moods
that pass a relative score floor.

* fix(enrichment): disable oximedia mood labels in UI and search tags

Oximedia 0.1.7 mood is a spectral energy heuristic, not independent mood
weights; valence correlates with loud/bright audio and false-labels metal
and lyrical tracks as happy. Hide queue/Song Info mood and stop writing
mood_tag facts until a reliable detector lands; keep V/A/moods JSON stored.

* fix(enrichment): disable oximedia mood analysis and add BPM advanced search

Stop planning, running, and storing oximedia mood facts; purge accumulated
mood rows via migration 009. Hide mood filters in Advanced Search, expose
BPM range filter with dual-storage resolution, and show a BPM column in song
results when that filter is active.

* feat(search): analysis BPM priority, source tooltip, and filter UX

Prefer analysis track_fact over file tags for BPM resolution; show source
in list tooltips. Validate BPM range on blur, add clear button, fix double tooltip.

* fix(enrichment): prefer analysis BPM in Song Info and queue tech row

Show measured track_fact BPM before file tags until analysis completes;
pick the highest-confidence analysis fact when several exist.
This commit is contained in:
cucadmuh
2026-05-23 18:54:04 +03:00
committed by GitHub
parent 67b1dc790b
commit 003b280a77
92 changed files with 4566 additions and 492 deletions
+4 -2
View File
@@ -1,4 +1,4 @@
use psysonic_analysis::analysis_runtime::enqueue_analysis_seed;
use psysonic_analysis::analysis_runtime::enqueue_track_analysis;
use psysonic_audio as audio;
use psysonic_core::user_agent::subsonic_wire_user_agent;
@@ -154,7 +154,9 @@ pub async fn promote_stream_cache_to_hot_cache(
.await
.map_err(|e| e.to_string())?;
let _ = enqueue_analysis_seed(&app, &server_id, &track_id, &bytes).await;
let high =
psysonic_analysis::analysis_runtime::analysis_backfill_is_current_track(&app, &track_id);
let _ = enqueue_track_analysis(&app, &server_id, &track_id, &bytes, high).await;
let size = tokio::fs::metadata(&file_path)
.await
+33 -126
View File
@@ -3,8 +3,9 @@ use std::sync::Arc;
use tauri::Manager;
use psysonic_analysis::analysis_cache;
use psysonic_analysis::analysis_runtime::enqueue_analysis_seed;
use psysonic_analysis::analysis_runtime::{
analysis_backfill_is_current_track, enqueue_track_analysis_from_file,
};
use crate::{offline_cancel_flags, DownloadSemaphore};
use crate::file_transfer::{finalize_streamed_download, subsonic_http_client};
@@ -17,36 +18,8 @@ pub async fn enqueue_analysis_seed_from_file(
track_id: &str,
file_path: &std::path::Path,
) {
let cache = app.try_state::<analysis_cache::AnalysisCache>();
let cache_ref: Option<&analysis_cache::AnalysisCache> = cache.as_ref().map(|s| s.inner());
let Some(bytes) = read_seed_bytes_if_needed(cache_ref, server_id, track_id, file_path).await else {
return;
};
let _ = enqueue_analysis_seed(app, server_id, track_id, &bytes).await;
}
/// AppHandle-free decision: returns the file bytes when seeding is required
/// (cache miss or no cache attached), or `None` when the cache says seeding is
/// redundant, the file can't be read, or the file is empty.
///
/// Pulled out of [`enqueue_analysis_seed_from_file`] so tests can drive every
/// branch with `AnalysisCache::open_in_memory()` plus a `tempfile::TempDir`.
pub(crate) async fn read_seed_bytes_if_needed(
cache: Option<&analysis_cache::AnalysisCache>,
server_id: &str,
track_id: &str,
file_path: &std::path::Path,
) -> Option<Vec<u8>> {
if let Some(cache) = cache {
if cache.cpu_seed_redundant_for_track(server_id, track_id).unwrap_or(false) {
return None;
}
}
let bytes = tokio::fs::read(file_path).await.ok()?;
if bytes.is_empty() {
return None;
}
Some(bytes)
let high = analysis_backfill_is_current_track(app, track_id);
let _ = enqueue_track_analysis_from_file(app, server_id, track_id, file_path, high).await;
}
/// AppHandle-free download primitive: ensures `cache_dir` exists, returns
@@ -376,100 +349,6 @@ mod tests {
assert!(sibling.exists());
}
// ── read_seed_bytes_if_needed (AppHandle-free) ──────────────────────────
use psysonic_analysis::analysis_cache::{
AnalysisCache, LoudnessEntry, TrackKey, WaveformEntry,
};
fn populate_redundant_seed_rows(cache: &AnalysisCache, track_id: &str) {
// cpu_seed_redundant_for_track returns true when both waveform AND
// loudness rows exist for the current algo version.
let key = TrackKey {
server_id: String::new(),
track_id: track_id.to_string(),
md5_16kb: "deadbeef".to_string(),
};
cache.touch_track_status(&key, "ready").unwrap();
cache
.upsert_waveform(
&key,
&WaveformEntry {
bins: vec![0u8; 1000], // 2 * 500
bin_count: 500,
is_partial: false,
known_until_sec: 0.0,
duration_sec: 0.0,
updated_at: 1_700_000_000,
},
)
.unwrap();
cache
.upsert_loudness(
&key,
&LoudnessEntry {
integrated_lufs: -14.0,
true_peak: 1.0,
recommended_gain_db: 0.0,
target_lufs: -14.0,
updated_at: 1_700_000_000,
},
)
.unwrap();
}
#[tokio::test(flavor = "multi_thread")]
async fn read_seed_bytes_returns_bytes_when_no_cache_attached() {
let dir = tempfile::tempdir().unwrap();
let file = dir.path().join("track.mp3");
std::fs::write(&file, b"audio data").unwrap();
let bytes = read_seed_bytes_if_needed(None, "", "anything", &file).await;
assert_eq!(bytes.as_deref(), Some(b"audio data".as_slice()));
}
#[tokio::test(flavor = "multi_thread")]
async fn read_seed_bytes_returns_bytes_when_cache_has_no_rows_for_track() {
let cache = AnalysisCache::open_in_memory();
let dir = tempfile::tempdir().unwrap();
let file = dir.path().join("track.flac");
std::fs::write(&file, b"some bytes").unwrap();
let bytes = read_seed_bytes_if_needed(Some(&cache), "", "fresh-track", &file).await;
assert_eq!(bytes.as_deref(), Some(b"some bytes".as_slice()));
}
#[tokio::test(flavor = "multi_thread")]
async fn read_seed_bytes_returns_none_when_cache_says_redundant() {
let cache = AnalysisCache::open_in_memory();
populate_redundant_seed_rows(&cache, "redundant-track");
let dir = tempfile::tempdir().unwrap();
let file = dir.path().join("track.mp3");
std::fs::write(&file, b"would-be-decoded bytes").unwrap();
let bytes = read_seed_bytes_if_needed(Some(&cache), "", "redundant-track", &file).await;
assert!(
bytes.is_none(),
"redundant-cache short-circuit must skip the file read entirely"
);
}
#[tokio::test(flavor = "multi_thread")]
async fn read_seed_bytes_returns_none_for_missing_file() {
let dir = tempfile::tempdir().unwrap();
let phantom = dir.path().join("never-written.mp3");
let bytes = read_seed_bytes_if_needed(None, "", "any", &phantom).await;
assert!(bytes.is_none());
}
#[tokio::test(flavor = "multi_thread")]
async fn read_seed_bytes_returns_none_for_empty_file() {
let dir = tempfile::tempdir().unwrap();
let file = dir.path().join("empty.flac");
std::fs::write(&file, b"").unwrap();
let bytes = read_seed_bytes_if_needed(None, "", "any", &file).await;
assert!(bytes.is_none(), "empty file must not trigger seeding");
}
// ── resolve_offline_cache_dir ────────────────────────────────────────────
#[test]
@@ -511,6 +390,34 @@ mod tests {
.unwrap_err();
assert_eq!(err, "VOLUME_NOT_FOUND");
}
// ── offline download cancellation registry ───────────────────────────────
#[test]
fn cancel_offline_downloads_marks_ids_for_cancellation() {
use crate::offline_cancel_flags;
let id = "test-cancel-offline-dl";
clear_offline_cancel(id.to_string());
cancel_offline_downloads(vec![id.to_string()]);
{
let flags = offline_cancel_flags().lock().unwrap();
let flag = flags.get(id).expect("cancel flag registered");
assert!(flag.load(Ordering::Relaxed));
}
clear_offline_cancel(id.to_string());
}
#[test]
fn clear_offline_cancel_removes_flag_entry() {
use crate::offline_cancel_flags;
let id = "test-clear-offline-dl";
cancel_offline_downloads(vec![id.to_string()]);
clear_offline_cancel(id.to_string());
let flags = offline_cancel_flags().lock().unwrap();
assert!(!flags.contains_key(id));
}
}
/// Returns the total size in bytes of all files in the offline cache directory (and optional custom dir).