mirror of
https://github.com/kilyabin/psysonic.git
synced 2026-07-22 06:25:41 +00:00
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:
@@ -53,6 +53,8 @@ export interface LibraryTrackDto {
|
||||
isrc?: string | null;
|
||||
mbidRecording?: string | null;
|
||||
bpm?: number | null;
|
||||
/** `'analysis'` | `'tag'` — Advanced Search BPM dual-storage projection only. */
|
||||
bpmSource?: string | null;
|
||||
replayGainTrackDb?: number | null;
|
||||
replayGainAlbumDb?: number | null;
|
||||
serverUpdatedAt?: number | null;
|
||||
|
||||
@@ -80,6 +80,8 @@ export interface SubsonicSong {
|
||||
played?: string;
|
||||
/** Beats per minute, surfaced by Navidrome when the tag is set on the file. */
|
||||
bpm?: number;
|
||||
/** Local index Advanced Search: `'tag'` (server/file tag) or `'analysis'` (measured). */
|
||||
localBpmSource?: 'tag' | 'analysis';
|
||||
replayGain?: {
|
||||
trackGain?: number;
|
||||
albumGain?: number;
|
||||
|
||||
@@ -30,10 +30,13 @@ export default function CustomSelect({ value, options, onChange, className = '',
|
||||
if (!triggerRef.current) return;
|
||||
const rect = triggerRef.current.getBoundingClientRect();
|
||||
const MARGIN = 6;
|
||||
const maxH = 240;
|
||||
const maxH = 320;
|
||||
const spaceBelow = window.innerHeight - rect.bottom - MARGIN;
|
||||
const spaceAbove = rect.top - MARGIN;
|
||||
const useAbove = spaceBelow < 80 && spaceAbove > spaceBelow;
|
||||
const viewportCap = Math.min(maxH, useAbove ? spaceAbove : spaceBelow);
|
||||
const contentH = listRef.current?.scrollHeight ?? 0;
|
||||
const needsScroll = contentH > viewportCap;
|
||||
setDropStyle({
|
||||
position: 'fixed',
|
||||
left: rect.left,
|
||||
@@ -41,7 +44,8 @@ export default function CustomSelect({ value, options, onChange, className = '',
|
||||
...(useAbove
|
||||
? { bottom: window.innerHeight - rect.top + MARGIN }
|
||||
: { top: rect.bottom + MARGIN }),
|
||||
maxHeight: Math.min(maxH, useAbove ? spaceAbove : spaceBelow),
|
||||
maxHeight: needsScroll ? viewportCap : contentH || viewportCap,
|
||||
overflowY: needsScroll ? 'auto' : 'hidden',
|
||||
zIndex: 99998,
|
||||
});
|
||||
};
|
||||
@@ -49,7 +53,10 @@ export default function CustomSelect({ value, options, onChange, className = '',
|
||||
useLayoutEffect(() => {
|
||||
if (!open) return;
|
||||
updateDropStyle();
|
||||
}, [open]);
|
||||
// Re-measure after layout so short lists (e.g. mood groups) don't get a spurious scrollbar.
|
||||
const id = requestAnimationFrame(updateDropStyle);
|
||||
return () => cancelAnimationFrame(id);
|
||||
}, [open, options]);
|
||||
|
||||
useEffect(() => {
|
||||
if (!open) return;
|
||||
|
||||
@@ -10,6 +10,8 @@ interface Props {
|
||||
loadingMore: boolean;
|
||||
/** Fetch the next page. Called as the sentinel nears the viewport. */
|
||||
onLoadMore: () => void;
|
||||
/** Show a BPM column (Advanced Search when the BPM filter is active). */
|
||||
showBpm?: boolean;
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -19,7 +21,7 @@ interface Props {
|
||||
* one chrome + paging path (no transform-positioned rows, so the sticky header
|
||||
* is never painted over — issue #841).
|
||||
*/
|
||||
export default function PagedSongList({ songs, hasMore, loadingMore, onLoadMore }: Props) {
|
||||
export default function PagedSongList({ songs, hasMore, loadingMore, onLoadMore, showBpm }: Props) {
|
||||
const sentinelRef = useRef<HTMLDivElement>(null);
|
||||
|
||||
// Re-observe whenever `onLoadMore` changes identity (callers rebuild it after
|
||||
@@ -36,9 +38,9 @@ export default function PagedSongList({ songs, hasMore, loadingMore, onLoadMore
|
||||
|
||||
return (
|
||||
<>
|
||||
<SongListHeader />
|
||||
<SongListHeader showBpm={showBpm} />
|
||||
{songs.map(song => (
|
||||
<SongRow key={song.id} song={song} />
|
||||
<SongRow key={song.id} song={song} showBpm={showBpm} />
|
||||
))}
|
||||
{hasMore && (
|
||||
<div ref={sentinelRef} style={{ display: 'flex', justifyContent: 'center', padding: '1rem' }}>
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
import { getSong } from '../api/subsonicLibrary';
|
||||
import { libraryGetFacts } from '../api/library';
|
||||
import type { SubsonicSong } from '../api/subsonicTypes';
|
||||
import React, { useEffect, useState } from 'react';
|
||||
import { createPortal } from 'react-dom';
|
||||
@@ -7,11 +8,19 @@ import { usePlayerStore } from '../store/playerStore';
|
||||
import { useShallow } from 'zustand/react/shallow';
|
||||
import { ndGetSongPath } from '../api/navidromeAdmin';
|
||||
import { useAuthStore } from '../store/authStore';
|
||||
import { useLibraryIndexStore } from '../store/libraryIndexStore';
|
||||
import { useTranslation } from 'react-i18next';
|
||||
import { copyTextToClipboard } from '../utils/server/serverMagicString';
|
||||
import { showToast } from '../utils/ui/toast';
|
||||
import { formatTrackTime } from '../utils/format/formatDuration';
|
||||
import { formatLastSeen } from '../utils/componentHelpers/userMgmtHelpers';
|
||||
import { libraryIsReady } from '../utils/library/libraryReady';
|
||||
import {
|
||||
formatQueueMoodLabels,
|
||||
parseTrackEnrichmentFacts,
|
||||
resolveQueueBpm,
|
||||
type ParsedTrackEnrichment,
|
||||
} from '../utils/library/trackEnrichment';
|
||||
import i18n from '../i18n';
|
||||
|
||||
function formatSize(bytes?: number): string | null {
|
||||
@@ -61,6 +70,7 @@ export default function SongInfoModal() {
|
||||
useShallow(s => ({ songInfoModal: s.songInfoModal, closeSongInfo: s.closeSongInfo }))
|
||||
);
|
||||
const [song, setSong] = useState<SubsonicSong | null>(null);
|
||||
const [enrichment, setEnrichment] = useState<ParsedTrackEnrichment | null>(null);
|
||||
const [loading, setLoading] = useState(false);
|
||||
// Absolute filesystem path resolved via Navidrome's native API in parallel
|
||||
// with the Subsonic getSong call. Subsonic only ever returns a relative
|
||||
@@ -71,16 +81,40 @@ export default function SongInfoModal() {
|
||||
useEffect(() => {
|
||||
if (!songInfoModal.isOpen || !songInfoModal.songId) {
|
||||
setSong(null);
|
||||
setEnrichment(null);
|
||||
setAbsolutePath(null);
|
||||
return;
|
||||
}
|
||||
let cancelled = false;
|
||||
setLoading(true);
|
||||
setEnrichment(null);
|
||||
setAbsolutePath(null);
|
||||
const songId = songInfoModal.songId;
|
||||
getSong(songId).then(s => {
|
||||
if (!cancelled) { setSong(s); setLoading(false); }
|
||||
});
|
||||
void (async () => {
|
||||
const s = await getSong(songId);
|
||||
if (cancelled) return;
|
||||
setSong(s);
|
||||
setLoading(false);
|
||||
if (!s) {
|
||||
setEnrichment(null);
|
||||
return;
|
||||
}
|
||||
const auth = useAuthStore.getState();
|
||||
const sid = auth.activeServerId;
|
||||
const indexEnabled = sid ? useLibraryIndexStore.getState().isIndexEnabled(sid) : false;
|
||||
if (sid && indexEnabled && await libraryIsReady(sid)) {
|
||||
try {
|
||||
const facts = await libraryGetFacts(sid, songId);
|
||||
if (!cancelled) {
|
||||
setEnrichment(parseTrackEnrichmentFacts(facts, s.bpm ?? null));
|
||||
}
|
||||
} catch {
|
||||
if (!cancelled) setEnrichment(null);
|
||||
}
|
||||
} else if (!cancelled) {
|
||||
setEnrichment(null);
|
||||
}
|
||||
})();
|
||||
// Try the native API in parallel; only when the active server is Navidrome
|
||||
// and we have credentials. Failures are silent — modal falls back to
|
||||
// whatever the Subsonic `path` field carried (typically nothing).
|
||||
@@ -124,6 +158,17 @@ export default function SongInfoModal() {
|
||||
const hasReplayGain = song?.replayGain &&
|
||||
(song.replayGain.trackGain !== undefined || song.replayGain.albumGain !== undefined);
|
||||
|
||||
const displayBpm = song
|
||||
? resolveQueueBpm(
|
||||
enrichment ?? {
|
||||
serverBpm: song.bpm != null && song.bpm > 0 ? song.bpm : null,
|
||||
measuredBpm: null,
|
||||
moodLabels: [],
|
||||
},
|
||||
)
|
||||
: null;
|
||||
const displayMood = enrichment ? formatQueueMoodLabels(enrichment.moodLabels, t) : null;
|
||||
|
||||
return createPortal(
|
||||
<>
|
||||
<div className="song-info-backdrop" onClick={closeSongInfo} />
|
||||
@@ -151,7 +196,8 @@ export default function SongInfoModal() {
|
||||
<Row label={t('songInfo.genre')} value={song.genre} />
|
||||
<Row label={t('songInfo.duration')} value={formatTrackTime(song.duration)} />
|
||||
<Row label={t('songInfo.track')} value={trackLabel} />
|
||||
<Row label={t('songInfo.bpm')} value={song.bpm} />
|
||||
<Row label={t('songInfo.bpm')} value={displayBpm} />
|
||||
<Row label={t('songInfo.mood')} value={displayMood} />
|
||||
<Row label={t('songInfo.playCount')} value={song.playCount} />
|
||||
<Row label={t('songInfo.lastPlayed')} value={song.played ? formatLastSeen(song.played, i18n.language, '—') : null} />
|
||||
|
||||
|
||||
@@ -12,10 +12,12 @@ import { formatTrackTime } from '../utils/format/formatDuration';
|
||||
|
||||
interface Props {
|
||||
song: SubsonicSong;
|
||||
showBpm?: boolean;
|
||||
}
|
||||
|
||||
function SongRow({ song }: Props) {
|
||||
function SongRow({ song, showBpm }: Props) {
|
||||
const navigate = useNavigate();
|
||||
const { t } = useTranslation();
|
||||
const enqueue = usePlayerStore(s => s.enqueue);
|
||||
const openContextMenu = usePlayerStore(s => s.openContextMenu);
|
||||
const isCurrent = usePlayerStore(s => s.currentTrack?.id === song.id);
|
||||
@@ -34,9 +36,16 @@ function SongRow({ song }: Props) {
|
||||
enqueue([songToTrack(song)]);
|
||||
};
|
||||
|
||||
const bpmTooltip =
|
||||
song.localBpmSource === 'analysis'
|
||||
? t('search.bpmSourceAnalysis')
|
||||
: song.localBpmSource === 'tag'
|
||||
? t('search.bpmSourceTag')
|
||||
: undefined;
|
||||
|
||||
return (
|
||||
<div
|
||||
className={`song-list-row${isCurrent ? ' is-current' : ''}`}
|
||||
className={`song-list-row${isCurrent ? ' is-current' : ''}${showBpm ? ' song-list-row--with-bpm' : ''}`}
|
||||
onDoubleClick={handlePlay}
|
||||
onContextMenu={(e) => {
|
||||
e.preventDefault();
|
||||
@@ -102,21 +111,35 @@ function SongRow({ song }: Props) {
|
||||
<div className="song-list-row-cell song-list-row-genre truncate" title={song.genre ?? ''}>
|
||||
{song.genre ?? '—'}
|
||||
</div>
|
||||
{showBpm && (
|
||||
<div
|
||||
className="song-list-row-cell song-list-row-bpm"
|
||||
data-tooltip={bpmTooltip}
|
||||
>
|
||||
{song.bpm != null && song.bpm > 0 ? song.bpm : '—'}
|
||||
</div>
|
||||
)}
|
||||
<div className="song-list-row-cell song-list-row-duration">{formatTrackTime(song.duration, '–')}</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
/** Column header with the same grid as <SongRow>. Optional — pages can render it above the list. */
|
||||
export function SongListHeader() {
|
||||
export function SongListHeader({ showBpm }: { showBpm?: boolean } = {}) {
|
||||
const { t } = useTranslation();
|
||||
return (
|
||||
<div className="song-list-row song-list-row--header" role="row">
|
||||
<div
|
||||
className={`song-list-row song-list-row--header${showBpm ? ' song-list-row--with-bpm' : ''}`}
|
||||
role="row"
|
||||
>
|
||||
<div className="song-list-row-cell song-list-row-actions" />
|
||||
<div className="song-list-row-cell">{t('albumDetail.trackTitle')}</div>
|
||||
<div className="song-list-row-cell">{t('albumDetail.trackArtist')}</div>
|
||||
<div className="song-list-row-cell">{t('albumDetail.trackAlbum')}</div>
|
||||
<div className="song-list-row-cell">{t('randomMix.trackGenre')}</div>
|
||||
{showBpm && (
|
||||
<div className="song-list-row-cell song-list-row-bpm">{t('albumDetail.trackBpm')}</div>
|
||||
)}
|
||||
<div className="song-list-row-cell song-list-row-duration">{t('albumDetail.trackDuration')}</div>
|
||||
</div>
|
||||
);
|
||||
|
||||
@@ -10,6 +10,8 @@ import {
|
||||
} from '../../utils/componentHelpers/queuePanelHelpers';
|
||||
import { loudnessGainPlaceholderUntilCacheDb } from '../../utils/audio/loudnessPlaceholder';
|
||||
import { effectiveLoudnessPreAnalysisAttenuationDb } from '../../utils/audio/loudnessPreAnalysisSlider';
|
||||
import { formatQueueBpmTech, formatQueueMoodLabels } from '../../utils/library/trackEnrichment';
|
||||
import { useQueueTrackEnrichment } from '../../hooks/useQueueTrackEnrichment';
|
||||
import { QueueLufsTargetMenu } from './QueueLufsTargetMenu';
|
||||
import { PlaybackBufferingOverlay } from '../playback/PlaybackBufferingOverlay';
|
||||
import { usePlayerStore } from '../../store/playerStore';
|
||||
@@ -48,6 +50,9 @@ export function QueueCurrentTrack({
|
||||
lufsTgtBtnRef, lufsTgtMenuRef, lufsTgtPopStyle, t,
|
||||
}: Props) {
|
||||
const showBufferingOverlay = usePlayerStore(s => s.isPlaybackBuffering);
|
||||
const enrichment = useQueueTrackEnrichment(currentTrack.id);
|
||||
const bpmTech = formatQueueBpmTech(enrichment, t);
|
||||
const moodLine = formatQueueMoodLabels(enrichment.moodLabels, t);
|
||||
return (
|
||||
<div className="queue-current-track">
|
||||
{(() => {
|
||||
@@ -62,6 +67,7 @@ export function QueueCurrentTrack({
|
||||
if (sr) return sr;
|
||||
return undefined;
|
||||
})(),
|
||||
bpmTech ?? undefined,
|
||||
].filter(Boolean) as string[];
|
||||
const rgParts = formatQueueReplayGainParts(currentTrack, t);
|
||||
const baseLine = baseParts.join(' · ');
|
||||
@@ -86,7 +92,7 @@ export function QueueCurrentTrack({
|
||||
})();
|
||||
const tgtNum = normalizationTargetLufs ?? authLoudnessTargetLufs;
|
||||
const targetLabel = `${tgtNum} LUFS`;
|
||||
if (!baseLine && !rgLine && !playbackSource) return null;
|
||||
if (!baseLine && !rgLine && !playbackSource && !bpmTech) return null;
|
||||
const showRgLine = !isLoudnessActive && expandReplayGain && !!rgLine;
|
||||
const showLufsLine = isLoudnessActive && expandReplayGain;
|
||||
return (
|
||||
@@ -215,6 +221,9 @@ export function QueueCurrentTrack({
|
||||
{currentTrack.year && (
|
||||
<div className="queue-current-sub">{currentTrack.year}</div>
|
||||
)}
|
||||
{moodLine && (
|
||||
<div className="queue-current-sub queue-current-enrichment">{moodLine}</div>
|
||||
)}
|
||||
{(() => {
|
||||
const label = orbitAttributionLabel(currentTrack.id);
|
||||
return label ? <div className="queue-current-sub queue-current-attribution">{label}</div> : null;
|
||||
|
||||
@@ -0,0 +1,69 @@
|
||||
import { describe, expect, it } from 'vitest';
|
||||
import {
|
||||
MOOD_GROUP_IDS,
|
||||
MOOD_GROUPS,
|
||||
OXIMEDIA_MOOD_TAG_IDS,
|
||||
TOP_OXIMEDIA_MOOD_TAG_TEST_SCORES,
|
||||
moodScoresFromValenceArousal,
|
||||
topDistinctOximediaMoodTagIds,
|
||||
topDistinctOximediaMoodTagIdsFromValenceArousal,
|
||||
topOximediaMoodTagIds,
|
||||
} from './moodGroups';
|
||||
|
||||
/** Keep in sync with `psysonic_library::mood_groups` invariant tests. */
|
||||
describe('moodGroups catalog invariants', () => {
|
||||
it('group ids match Rust MOOD_GROUP_IDS', () => {
|
||||
expect([...MOOD_GROUP_IDS]).toEqual(['joy', 'sadness', 'dance', 'work', 'romance', 'anger']);
|
||||
});
|
||||
|
||||
it('every oximedia tag appears in at least one group', () => {
|
||||
for (const tag of OXIMEDIA_MOOD_TAG_IDS) {
|
||||
expect(MOOD_GROUPS.some(g => g.tags.includes(tag))).toBe(true);
|
||||
}
|
||||
});
|
||||
|
||||
it('joy group tags match Rust expand_mood_groups', () => {
|
||||
expect(MOOD_GROUPS.find(g => g.id === 'joy')?.tags).toEqual(['happy', 'excited']);
|
||||
});
|
||||
|
||||
it('work and romance groups overlap on calm/peaceful', () => {
|
||||
const work = MOOD_GROUPS.find(g => g.id === 'work')!.tags;
|
||||
const romance = MOOD_GROUPS.find(g => g.id === 'romance')!.tags;
|
||||
expect(work.some(t => romance.includes(t))).toBe(true);
|
||||
});
|
||||
|
||||
it('anger group tags match Rust expand_mood_groups', () => {
|
||||
expect(MOOD_GROUPS.find(g => g.id === 'anger')?.tags).toEqual(['angry', 'tense']);
|
||||
});
|
||||
});
|
||||
|
||||
describe('moodScoresFromValenceArousal', () => {
|
||||
it('never shows both happy and excited for typical oximedia pop', () => {
|
||||
const labels = topDistinctOximediaMoodTagIdsFromValenceArousal(0.4, 0.75);
|
||||
expect(labels.includes('happy') && labels.includes('excited')).toBe(false);
|
||||
expect(labels.length).toBeLessThanOrEqual(2);
|
||||
});
|
||||
|
||||
it('prefers calm or peaceful for low arousal', () => {
|
||||
const labels = topDistinctOximediaMoodTagIdsFromValenceArousal(0.55, 0.42);
|
||||
expect(labels.some(id => id === 'calm' || id === 'peaceful')).toBe(true);
|
||||
});
|
||||
});
|
||||
|
||||
describe('topOximediaMoodTagIds', () => {
|
||||
it('matches Rust top_oximedia_mood_tag_ids_from_moods_json test vector', () => {
|
||||
expect(topOximediaMoodTagIds(TOP_OXIMEDIA_MOOD_TAG_TEST_SCORES)).toEqual([
|
||||
'happy',
|
||||
'excited',
|
||||
'calm',
|
||||
]);
|
||||
});
|
||||
|
||||
it('sorts by score descending with id tie-break', () => {
|
||||
expect(topOximediaMoodTagIds({ calm: 0.2, happy: 0.9, excited: 0.5 })).toEqual([
|
||||
'happy',
|
||||
'excited',
|
||||
'calm',
|
||||
]);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,142 @@
|
||||
/** Oximedia mood label ids — keep in sync with `psysonic_library::mood_groups` (see `moodGroups.test.ts`). */
|
||||
export const OXIMEDIA_MOOD_TAG_IDS = [
|
||||
'happy',
|
||||
'excited',
|
||||
'calm',
|
||||
'peaceful',
|
||||
'angry',
|
||||
'tense',
|
||||
'sad',
|
||||
'melancholic',
|
||||
] as const;
|
||||
|
||||
export type OximediaMoodTagId = (typeof OXIMEDIA_MOOD_TAG_IDS)[number];
|
||||
|
||||
export type MoodGroupId = 'joy' | 'sadness' | 'dance' | 'work' | 'romance' | 'anger';
|
||||
|
||||
/** Virtual mood groups for Advanced Search — overlaps are intentional. */
|
||||
export const MOOD_GROUPS: ReadonlyArray<{
|
||||
readonly id: MoodGroupId;
|
||||
readonly tags: readonly string[];
|
||||
}> = [
|
||||
{ id: 'joy', tags: ['happy', 'excited'] },
|
||||
{ id: 'sadness', tags: ['sad', 'melancholic'] },
|
||||
{ id: 'dance', tags: ['excited', 'happy', 'tense', 'angry'] },
|
||||
{ id: 'work', tags: ['calm', 'peaceful'] },
|
||||
{ id: 'romance', tags: ['peaceful', 'calm', 'melancholic'] },
|
||||
{ id: 'anger', tags: ['angry', 'tense'] },
|
||||
] as const;
|
||||
|
||||
export const MOOD_GROUP_IDS: readonly MoodGroupId[] = MOOD_GROUPS.map(g => g.id);
|
||||
|
||||
/** Valence/arousal anchor — keep in sync with Rust `mood_groups::MOOD_VA_ANCHORS`. */
|
||||
const MOOD_VA_ANCHORS: ReadonlyArray<{ readonly id: OximediaMoodTagId; readonly v: number; readonly a: number }> = [
|
||||
{ id: 'happy', v: 0.75, a: 0.72 },
|
||||
{ id: 'excited', v: 0.55, a: 0.88 },
|
||||
{ id: 'calm', v: 0.65, a: 0.22 },
|
||||
{ id: 'peaceful', v: 0.78, a: 0.12 },
|
||||
{ id: 'angry', v: -0.72, a: 0.82 },
|
||||
{ id: 'tense', v: -0.35, a: 0.68 },
|
||||
{ id: 'sad', v: -0.75, a: 0.28 },
|
||||
{ id: 'melancholic', v: -0.55, a: 0.18 },
|
||||
] as const;
|
||||
|
||||
const MOOD_VA_MAX_DIST = 1.35;
|
||||
const MOOD_VA_VALENCE_BIAS = 0.12;
|
||||
const MOOD_VA_VALENCE_SCALE = 1.4;
|
||||
const MOOD_VA_AROUSAL_OFFSET = 0.48;
|
||||
const MOOD_VA_AROUSAL_SCALE = 0.40;
|
||||
const MOOD_DISPLAY_MIN_RELATIVE = 0.55;
|
||||
const MOOD_DISPLAY_MIN_ABSOLUTE = 0.28;
|
||||
|
||||
/** One label per cluster in UI — mirrors Rust `MOOD_DISPLAY_CLUSTERS`. */
|
||||
const MOOD_DISPLAY_CLUSTERS: readonly (readonly OximediaMoodTagId[])[] = [
|
||||
['happy', 'excited'],
|
||||
['calm', 'peaceful'],
|
||||
['angry', 'tense'],
|
||||
['sad', 'melancholic'],
|
||||
] as const;
|
||||
|
||||
function moodDisplayCluster(tag: string): number | null {
|
||||
const idx = MOOD_DISPLAY_CLUSTERS.findIndex(cluster => cluster.includes(tag as OximediaMoodTagId));
|
||||
return idx >= 0 ? idx : null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Soft scores for all oximedia mood tags from raw valence/arousal.
|
||||
* Oximedia's built-in mapper returns only two labels (often happy/excited);
|
||||
* we recalibrate V/A and score every catalog tag by distance to anchors.
|
||||
*/
|
||||
export function moodScoresFromValenceArousal(valence: number, arousal: number): Record<string, number> {
|
||||
const v = Math.max(-1, Math.min(1, (valence - MOOD_VA_VALENCE_BIAS) * MOOD_VA_VALENCE_SCALE));
|
||||
const a = Math.max(0, Math.min(1, (arousal - MOOD_VA_AROUSAL_OFFSET) / MOOD_VA_AROUSAL_SCALE));
|
||||
const scores: Record<string, number> = {};
|
||||
for (const anchor of MOOD_VA_ANCHORS) {
|
||||
const dv = v - anchor.v;
|
||||
const da = a - anchor.a;
|
||||
const dist = Math.sqrt(dv * dv + da * da);
|
||||
scores[anchor.id] = Math.max(0, 1 - dist / MOOD_VA_MAX_DIST);
|
||||
}
|
||||
return scores;
|
||||
}
|
||||
|
||||
/** Shared test vector with Rust `mood_groups::top_oximedia_mood_tag_ids_from_moods_json`. */
|
||||
export const TOP_OXIMEDIA_MOOD_TAG_TEST_SCORES = {
|
||||
noise: 0.99,
|
||||
calm: 0.2,
|
||||
happy: 0.9,
|
||||
excited: 0.5,
|
||||
} as const;
|
||||
|
||||
/** Top oximedia mood tag ids by score — mirrors Rust `top_oximedia_mood_tag_ids_from_scores`. */
|
||||
export function topOximediaMoodTagIds(
|
||||
scores: Record<string, number> | null | undefined,
|
||||
limit = 3,
|
||||
): string[] {
|
||||
if (!scores) return [];
|
||||
const allowed = new Set<string>(OXIMEDIA_MOOD_TAG_IDS);
|
||||
return Object.entries(scores)
|
||||
.filter(([id]) => allowed.has(id))
|
||||
.sort((a, b) => b[1] - a[1] || a[0].localeCompare(b[0]))
|
||||
.slice(0, limit)
|
||||
.map(([id]) => id);
|
||||
}
|
||||
|
||||
/** One tag per display cluster (never happy+excited together). Mirrors Rust distinct picker. */
|
||||
export function topDistinctOximediaMoodTagIds(
|
||||
scores: Record<string, number> | null | undefined,
|
||||
limit = 2,
|
||||
): string[] {
|
||||
if (!scores) return [];
|
||||
const ranked = topOximediaMoodTagIds(scores, OXIMEDIA_MOOD_TAG_IDS.length);
|
||||
if (ranked.length === 0) return [];
|
||||
const topScore = scores[ranked[0]] ?? 0;
|
||||
const usedClusters = new Set<number>();
|
||||
const out: string[] = [];
|
||||
for (const id of ranked) {
|
||||
const score = scores[id] ?? 0;
|
||||
if (score < MOOD_DISPLAY_MIN_ABSOLUTE || score < topScore * MOOD_DISPLAY_MIN_RELATIVE) continue;
|
||||
const cluster = moodDisplayCluster(id);
|
||||
if (cluster != null) {
|
||||
if (usedClusters.has(cluster)) continue;
|
||||
usedClusters.add(cluster);
|
||||
}
|
||||
out.push(id);
|
||||
if (out.length >= limit) break;
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
export function topDistinctOximediaMoodTagIdsFromValenceArousal(
|
||||
valence: number,
|
||||
arousal: number,
|
||||
limit = 2,
|
||||
): string[] {
|
||||
return topDistinctOximediaMoodTagIds(moodScoresFromValenceArousal(valence, arousal), limit);
|
||||
}
|
||||
|
||||
/** Dedupe a stored tag list to one label per cluster (preserves rank order). */
|
||||
export function distinctOximediaMoodTagIds(tags: readonly string[], limit = 2): string[] {
|
||||
const scores = Object.fromEntries(tags.map((id, index) => [id, tags.length - index]));
|
||||
return topDistinctOximediaMoodTagIds(scores, limit);
|
||||
}
|
||||
@@ -127,6 +127,7 @@ const CONTRIBUTOR_ENTRIES = [
|
||||
'Player stats: local listening history tab with heatmap, year summary, recent days, and day drill-down (PR #849)',
|
||||
'Playback speed: global 0.5–2.0× with Speed / Varispeed / Pitch shift strategies, player bar popover, Orbit passthrough (PR #852)',
|
||||
'Local library index: full resync orphan sweep (IS-7) — remove server-deleted tracks after successful re-sync (PR #861)',
|
||||
'Track enrichment: oximedia BPM/mood analysis, mood-group Advanced Search, queue display, unified playback analysis dispatch (PR #863)',
|
||||
],
|
||||
},
|
||||
{
|
||||
|
||||
File diff suppressed because one or more lines are too long
@@ -0,0 +1,100 @@
|
||||
import { useEffect, useState } from 'react';
|
||||
import { listen } from '@tauri-apps/api/event';
|
||||
import { libraryGetFacts, libraryGetTrack } from '../api/library';
|
||||
import { usePlaybackServerId } from './usePlaybackServerId';
|
||||
import { useLibraryIndexStore } from '../store/libraryIndexStore';
|
||||
import {
|
||||
enrichmentDisplayComplete,
|
||||
OXIMEDIA_MOOD_UI_ENABLED,
|
||||
parseTrackEnrichmentFacts,
|
||||
type ParsedTrackEnrichment,
|
||||
} from '../utils/library/trackEnrichment';
|
||||
import { libraryIsReady } from '../utils/library/libraryReady';
|
||||
import { normalizeAnalysisTrackId } from '../utils/playback/queueIdentity';
|
||||
|
||||
const EMPTY: ParsedTrackEnrichment = {
|
||||
serverBpm: null,
|
||||
measuredBpm: null,
|
||||
moodLabels: [],
|
||||
};
|
||||
|
||||
/** Enrichment may finish several seconds after CPU seed / playback start. */
|
||||
const REFETCH_MS = [3_000, 8_000, 15_000, 30_000, 60_000] as const;
|
||||
|
||||
const ENRICHMENT_FACT_KINDS = OXIMEDIA_MOOD_UI_ENABLED
|
||||
? (['bpm', 'moods', 'mood_tag', 'mood_labels', 'valence', 'arousal'] as const)
|
||||
: (['bpm'] as const);
|
||||
|
||||
/**
|
||||
* Loads server BPM + oximedia mood facts for the queue "now playing" block.
|
||||
* Uses the playback server id (queue scope), not the browsed server.
|
||||
*/
|
||||
export function useQueueTrackEnrichment(trackId: string | undefined): ParsedTrackEnrichment {
|
||||
const serverId = usePlaybackServerId();
|
||||
const indexEnabled = useLibraryIndexStore(s =>
|
||||
serverId ? s.isIndexEnabled(serverId) : false,
|
||||
);
|
||||
const [data, setData] = useState<ParsedTrackEnrichment>(EMPTY);
|
||||
const [refreshNonce, setRefreshNonce] = useState(0);
|
||||
|
||||
useEffect(() => {
|
||||
if (!serverId || !trackId || !indexEnabled) {
|
||||
setData(EMPTY);
|
||||
return;
|
||||
}
|
||||
|
||||
let cancelled = false;
|
||||
const timers: ReturnType<typeof setTimeout>[] = [];
|
||||
|
||||
const load = async () => {
|
||||
if (!(await libraryIsReady(serverId))) return;
|
||||
try {
|
||||
const [track, facts] = await Promise.all([
|
||||
libraryGetTrack(serverId, trackId),
|
||||
libraryGetFacts(serverId, trackId, [...ENRICHMENT_FACT_KINDS]),
|
||||
]);
|
||||
if (cancelled) return;
|
||||
const parsed = parseTrackEnrichmentFacts(facts, track?.bpm ?? null);
|
||||
setData(parsed);
|
||||
if (enrichmentDisplayComplete(parsed)) {
|
||||
for (const id of timers) clearTimeout(id);
|
||||
timers.length = 0;
|
||||
}
|
||||
} catch {
|
||||
if (!cancelled) setData(EMPTY);
|
||||
}
|
||||
};
|
||||
|
||||
void load();
|
||||
for (const ms of REFETCH_MS) {
|
||||
timers.push(setTimeout(() => { void load(); }, ms));
|
||||
}
|
||||
|
||||
return () => {
|
||||
cancelled = true;
|
||||
for (const id of timers) clearTimeout(id);
|
||||
};
|
||||
}, [serverId, trackId, indexEnabled, refreshNonce]);
|
||||
|
||||
useEffect(() => {
|
||||
if (!serverId || !trackId || !indexEnabled) return;
|
||||
|
||||
let unlisten: (() => void) | undefined;
|
||||
void listen<{ trackId: string; serverId: string }>('analysis:enrichment-updated', ({ payload }) => {
|
||||
if (!payload?.trackId) return;
|
||||
const eventTrackId = normalizeAnalysisTrackId(payload.trackId);
|
||||
const currentId = normalizeAnalysisTrackId(trackId);
|
||||
if (!eventTrackId || eventTrackId !== currentId) return;
|
||||
if (payload.serverId && payload.serverId !== serverId) return;
|
||||
setRefreshNonce(n => n + 1);
|
||||
}).then(fn => {
|
||||
unlisten = fn;
|
||||
});
|
||||
|
||||
return () => {
|
||||
unlisten?.();
|
||||
};
|
||||
}, [serverId, trackId, indexEnabled]);
|
||||
|
||||
return data;
|
||||
}
|
||||
@@ -43,4 +43,15 @@ export const queue = {
|
||||
sourceStream: 'Wiedergabe aus dem Netzwerkstream',
|
||||
clearCachedLoudnessWaveform: 'Clear cached loudness and waveform, then re-analyze this track',
|
||||
recalculatingLoudnessWaveform: 'Recalculating loudness and waveform for this track…',
|
||||
bpm: '{{bpm}} BPM',
|
||||
moods: {
|
||||
happy: 'Happy',
|
||||
excited: 'Excited',
|
||||
calm: 'Calm',
|
||||
peaceful: 'Peaceful',
|
||||
angry: 'Angry',
|
||||
tense: 'Tense',
|
||||
sad: 'Sad',
|
||||
melancholic: 'Melancholic',
|
||||
},
|
||||
};
|
||||
|
||||
@@ -23,6 +23,13 @@ export const search = {
|
||||
advancedYearFrom: 'von',
|
||||
advancedYearTo: 'bis',
|
||||
advancedBpm: 'BPM',
|
||||
advancedBpmLocalNote: 'Uses tag BPM and measured analysis when the local index is enabled',
|
||||
advancedBpmClear: 'BPM-Filter zurücksetzen',
|
||||
bpmSourceTag: 'BPM from file tag',
|
||||
bpmSourceAnalysis: 'BPM from audio analysis',
|
||||
advancedMoodGroup: 'Mood',
|
||||
advancedAllMoods: 'All moods',
|
||||
advancedMoodLocalNote: 'Requires local library index and track analysis',
|
||||
advancedAll: 'Alle',
|
||||
advancedSearch: 'Suchen',
|
||||
advancedEmpty: 'Suchbegriff eingeben oder Filter wählen, um zu beginnen.',
|
||||
@@ -48,4 +55,12 @@ export const search = {
|
||||
shareQueuePreviewLoading: 'Loading tracks…',
|
||||
shareQueuePreviewEmpty: 'No tracks from this link could be found on the server.',
|
||||
shareQueuePreviewSkipped: '{{skipped}} of {{total}} tracks were not found on this server.',
|
||||
moodGroups: {
|
||||
joy: 'Joy',
|
||||
sadness: 'Sadness',
|
||||
dance: 'Dance',
|
||||
work: 'Work',
|
||||
romance: 'Romance',
|
||||
anger: 'Anger',
|
||||
},
|
||||
};
|
||||
|
||||
@@ -9,6 +9,7 @@ export const songInfo = {
|
||||
duration: 'Länge',
|
||||
track: 'Track',
|
||||
bpm: 'BPM',
|
||||
mood: 'Stimmung',
|
||||
playCount: 'Wiedergaben',
|
||||
lastPlayed: 'Zuletzt gespielt',
|
||||
format: 'Format',
|
||||
|
||||
@@ -43,4 +43,15 @@ export const queue = {
|
||||
sourceStream: 'Playing from network stream',
|
||||
clearCachedLoudnessWaveform: 'Clear cached loudness and waveform, then re-analyze this track',
|
||||
recalculatingLoudnessWaveform: 'Recalculating loudness and waveform for this track…',
|
||||
bpm: '{{bpm}} BPM',
|
||||
moods: {
|
||||
happy: 'Happy',
|
||||
excited: 'Excited',
|
||||
calm: 'Calm',
|
||||
peaceful: 'Peaceful',
|
||||
angry: 'Angry',
|
||||
tense: 'Tense',
|
||||
sad: 'Sad',
|
||||
melancholic: 'Melancholic',
|
||||
},
|
||||
};
|
||||
|
||||
@@ -23,6 +23,13 @@ export const search = {
|
||||
advancedYearFrom: 'from',
|
||||
advancedYearTo: 'to',
|
||||
advancedBpm: 'BPM',
|
||||
advancedBpmLocalNote: 'Measured analysis BPM takes priority over file tags when the local index is enabled',
|
||||
advancedBpmClear: 'Clear BPM filter',
|
||||
bpmSourceTag: 'BPM from file tag',
|
||||
bpmSourceAnalysis: 'BPM from audio analysis',
|
||||
advancedMoodGroup: 'Mood',
|
||||
advancedAllMoods: 'All moods',
|
||||
advancedMoodLocalNote: 'Requires local library index and track analysis',
|
||||
advancedAll: 'All',
|
||||
advancedSearch: 'Search',
|
||||
advancedEmpty: 'Enter a search term or select a filter to begin.',
|
||||
@@ -48,4 +55,12 @@ export const search = {
|
||||
shareQueuePreviewLoading: 'Loading tracks…',
|
||||
shareQueuePreviewEmpty: 'No tracks from this link could be found on the server.',
|
||||
shareQueuePreviewSkipped: '{{skipped}} of {{total}} tracks were not found on this server.',
|
||||
moodGroups: {
|
||||
joy: 'Joy',
|
||||
sadness: 'Sadness',
|
||||
dance: 'Dance',
|
||||
work: 'Work',
|
||||
romance: 'Romance',
|
||||
anger: 'Anger',
|
||||
},
|
||||
};
|
||||
|
||||
@@ -9,6 +9,7 @@ export const songInfo = {
|
||||
duration: 'Duration',
|
||||
track: 'Track',
|
||||
bpm: 'BPM',
|
||||
mood: 'Mood',
|
||||
playCount: 'Play count',
|
||||
lastPlayed: 'Last played',
|
||||
format: 'Format',
|
||||
|
||||
@@ -43,4 +43,15 @@ export const queue = {
|
||||
sourceStream: 'Reproducción desde la transmisión en red',
|
||||
clearCachedLoudnessWaveform: 'Clear cached loudness and waveform, then re-analyze this track',
|
||||
recalculatingLoudnessWaveform: 'Recalculating loudness and waveform for this track…',
|
||||
bpm: '{{bpm}} BPM',
|
||||
moods: {
|
||||
happy: 'Happy',
|
||||
excited: 'Excited',
|
||||
calm: 'Calm',
|
||||
peaceful: 'Peaceful',
|
||||
angry: 'Angry',
|
||||
tense: 'Tense',
|
||||
sad: 'Sad',
|
||||
melancholic: 'Melancholic',
|
||||
},
|
||||
};
|
||||
|
||||
@@ -23,6 +23,13 @@ export const search = {
|
||||
advancedYearFrom: 'desde',
|
||||
advancedYearTo: 'hasta',
|
||||
advancedBpm: 'BPM',
|
||||
advancedBpmLocalNote: 'Uses tag BPM and measured analysis when the local index is enabled',
|
||||
advancedBpmClear: 'Limpiar filtro BPM',
|
||||
bpmSourceTag: 'BPM from file tag',
|
||||
bpmSourceAnalysis: 'BPM from audio analysis',
|
||||
advancedMoodGroup: 'Mood',
|
||||
advancedAllMoods: 'All moods',
|
||||
advancedMoodLocalNote: 'Requires local library index and track analysis',
|
||||
advancedAll: 'Todos',
|
||||
advancedSearch: 'Buscar',
|
||||
advancedEmpty: 'Ingresa un término de búsqueda o selecciona un filtro para comenzar.',
|
||||
@@ -48,4 +55,12 @@ export const search = {
|
||||
shareQueuePreviewLoading: 'Loading tracks…',
|
||||
shareQueuePreviewEmpty: 'No tracks from this link could be found on the server.',
|
||||
shareQueuePreviewSkipped: '{{skipped}} of {{total}} tracks were not found on this server.',
|
||||
moodGroups: {
|
||||
joy: 'Joy',
|
||||
sadness: 'Sadness',
|
||||
dance: 'Dance',
|
||||
work: 'Work',
|
||||
romance: 'Romance',
|
||||
anger: 'Anger',
|
||||
},
|
||||
};
|
||||
|
||||
@@ -9,6 +9,7 @@ export const songInfo = {
|
||||
duration: 'Duración',
|
||||
track: 'Pista',
|
||||
bpm: 'BPM',
|
||||
mood: 'Estado de ánimo',
|
||||
playCount: 'Reproducciones',
|
||||
lastPlayed: 'Última reproducción',
|
||||
format: 'Formato',
|
||||
|
||||
@@ -43,4 +43,15 @@ export const queue = {
|
||||
sourceStream: 'Lecture depuis le flux réseau',
|
||||
clearCachedLoudnessWaveform: 'Clear cached loudness and waveform, then re-analyze this track',
|
||||
recalculatingLoudnessWaveform: 'Recalculating loudness and waveform for this track…',
|
||||
bpm: '{{bpm}} BPM',
|
||||
moods: {
|
||||
happy: 'Happy',
|
||||
excited: 'Excited',
|
||||
calm: 'Calm',
|
||||
peaceful: 'Peaceful',
|
||||
angry: 'Angry',
|
||||
tense: 'Tense',
|
||||
sad: 'Sad',
|
||||
melancholic: 'Melancholic',
|
||||
},
|
||||
};
|
||||
|
||||
@@ -23,6 +23,13 @@ export const search = {
|
||||
advancedYearFrom: 'de',
|
||||
advancedYearTo: 'à',
|
||||
advancedBpm: 'BPM',
|
||||
advancedBpmLocalNote: 'Uses tag BPM and measured analysis when the local index is enabled',
|
||||
advancedBpmClear: 'Effacer le filtre BPM',
|
||||
bpmSourceTag: 'BPM from file tag',
|
||||
bpmSourceAnalysis: 'BPM from audio analysis',
|
||||
advancedMoodGroup: 'Mood',
|
||||
advancedAllMoods: 'All moods',
|
||||
advancedMoodLocalNote: 'Requires local library index and track analysis',
|
||||
advancedAll: 'Tous',
|
||||
advancedSearch: 'Rechercher',
|
||||
advancedEmpty: 'Entrez un terme de recherche ou sélectionnez un filtre.',
|
||||
@@ -48,4 +55,12 @@ export const search = {
|
||||
shareQueuePreviewLoading: 'Loading tracks…',
|
||||
shareQueuePreviewEmpty: 'No tracks from this link could be found on the server.',
|
||||
shareQueuePreviewSkipped: '{{skipped}} of {{total}} tracks were not found on this server.',
|
||||
moodGroups: {
|
||||
joy: 'Joy',
|
||||
sadness: 'Sadness',
|
||||
dance: 'Dance',
|
||||
work: 'Work',
|
||||
romance: 'Romance',
|
||||
anger: 'Anger',
|
||||
},
|
||||
};
|
||||
|
||||
@@ -9,6 +9,7 @@ export const songInfo = {
|
||||
duration: 'Durée',
|
||||
track: 'Piste',
|
||||
bpm: 'BPM',
|
||||
mood: 'Ambiance',
|
||||
playCount: 'Nombre de lectures',
|
||||
lastPlayed: 'Dernière lecture',
|
||||
format: 'Format',
|
||||
|
||||
@@ -43,4 +43,15 @@ export const queue = {
|
||||
sourceStream: 'Spiller fra nettverksstrøm',
|
||||
clearCachedLoudnessWaveform: 'Clear cached loudness and waveform, then re-analyze this track',
|
||||
recalculatingLoudnessWaveform: 'Recalculating loudness and waveform for this track…',
|
||||
bpm: '{{bpm}} BPM',
|
||||
moods: {
|
||||
happy: 'Happy',
|
||||
excited: 'Excited',
|
||||
calm: 'Calm',
|
||||
peaceful: 'Peaceful',
|
||||
angry: 'Angry',
|
||||
tense: 'Tense',
|
||||
sad: 'Sad',
|
||||
melancholic: 'Melancholic',
|
||||
},
|
||||
};
|
||||
|
||||
@@ -23,6 +23,13 @@ export const search = {
|
||||
advancedYearFrom: 'fra',
|
||||
advancedYearTo: 'til',
|
||||
advancedBpm: 'BPM',
|
||||
advancedBpmLocalNote: 'Uses tag BPM and measured analysis when the local index is enabled',
|
||||
advancedBpmClear: 'Tøm BPM-filter',
|
||||
bpmSourceTag: 'BPM from file tag',
|
||||
bpmSourceAnalysis: 'BPM from audio analysis',
|
||||
advancedMoodGroup: 'Mood',
|
||||
advancedAllMoods: 'All moods',
|
||||
advancedMoodLocalNote: 'Requires local library index and track analysis',
|
||||
advancedAll: 'Alle',
|
||||
advancedSearch: 'Søk',
|
||||
advancedEmpty: 'Skriv inn et søkeord eller velg ett filter for å begynne.',
|
||||
@@ -48,4 +55,12 @@ export const search = {
|
||||
shareQueuePreviewLoading: 'Loading tracks…',
|
||||
shareQueuePreviewEmpty: 'No tracks from this link could be found on the server.',
|
||||
shareQueuePreviewSkipped: '{{skipped}} of {{total}} tracks were not found on this server.',
|
||||
moodGroups: {
|
||||
joy: 'Joy',
|
||||
sadness: 'Sadness',
|
||||
dance: 'Dance',
|
||||
work: 'Work',
|
||||
romance: 'Romance',
|
||||
anger: 'Anger',
|
||||
},
|
||||
};
|
||||
|
||||
@@ -9,6 +9,7 @@ export const songInfo = {
|
||||
duration: 'Varighet',
|
||||
track: 'Spor',
|
||||
bpm: 'BPM',
|
||||
mood: 'Stemning',
|
||||
playCount: 'Avspillinger',
|
||||
lastPlayed: 'Sist spilt',
|
||||
format: 'Format',
|
||||
|
||||
@@ -43,4 +43,15 @@ export const queue = {
|
||||
sourceStream: 'Afspelen vanuit netwerkstream',
|
||||
clearCachedLoudnessWaveform: 'Clear cached loudness and waveform, then re-analyze this track',
|
||||
recalculatingLoudnessWaveform: 'Recalculating loudness and waveform for this track…',
|
||||
bpm: '{{bpm}} BPM',
|
||||
moods: {
|
||||
happy: 'Happy',
|
||||
excited: 'Excited',
|
||||
calm: 'Calm',
|
||||
peaceful: 'Peaceful',
|
||||
angry: 'Angry',
|
||||
tense: 'Tense',
|
||||
sad: 'Sad',
|
||||
melancholic: 'Melancholic',
|
||||
},
|
||||
};
|
||||
|
||||
@@ -23,6 +23,13 @@ export const search = {
|
||||
advancedYearFrom: 'van',
|
||||
advancedYearTo: 'tot',
|
||||
advancedBpm: 'BPM',
|
||||
advancedBpmLocalNote: 'Uses tag BPM and measured analysis when the local index is enabled',
|
||||
advancedBpmClear: 'BPM-filter wissen',
|
||||
bpmSourceTag: 'BPM from file tag',
|
||||
bpmSourceAnalysis: 'BPM from audio analysis',
|
||||
advancedMoodGroup: 'Mood',
|
||||
advancedAllMoods: 'All moods',
|
||||
advancedMoodLocalNote: 'Requires local library index and track analysis',
|
||||
advancedAll: 'Alle',
|
||||
advancedSearch: 'Zoeken',
|
||||
advancedEmpty: 'Voer een zoekterm in of selecteer een filter.',
|
||||
@@ -48,4 +55,12 @@ export const search = {
|
||||
shareQueuePreviewLoading: 'Loading tracks…',
|
||||
shareQueuePreviewEmpty: 'No tracks from this link could be found on the server.',
|
||||
shareQueuePreviewSkipped: '{{skipped}} of {{total}} tracks were not found on this server.',
|
||||
moodGroups: {
|
||||
joy: 'Joy',
|
||||
sadness: 'Sadness',
|
||||
dance: 'Dance',
|
||||
work: 'Work',
|
||||
romance: 'Romance',
|
||||
anger: 'Anger',
|
||||
},
|
||||
};
|
||||
|
||||
@@ -9,6 +9,7 @@ export const songInfo = {
|
||||
duration: 'Duur',
|
||||
track: 'Track',
|
||||
bpm: 'BPM',
|
||||
mood: 'Stemming',
|
||||
playCount: 'Aantal weergaven',
|
||||
lastPlayed: 'Laatst afgespeeld',
|
||||
format: 'Formaat',
|
||||
|
||||
@@ -43,4 +43,15 @@ export const queue = {
|
||||
sourceStream: 'Se redă din stream-ul de rețea',
|
||||
clearCachedLoudnessWaveform: 'Golește zgomotul si formele de undă din cache, apoi reanalizează piesa',
|
||||
recalculatingLoudnessWaveform: 'Se recalculează zgomotul și formele de undă pentru această piesă…',
|
||||
bpm: '{{bpm}} BPM',
|
||||
moods: {
|
||||
happy: 'Fericit',
|
||||
excited: 'Entuziasmat',
|
||||
calm: 'Calm',
|
||||
peaceful: 'Pașnic',
|
||||
angry: 'Furios',
|
||||
tense: 'Tensionat',
|
||||
sad: 'Trist',
|
||||
melancholic: 'Melancolic',
|
||||
},
|
||||
};
|
||||
|
||||
@@ -23,6 +23,13 @@ export const search = {
|
||||
advancedYearFrom: 'de la',
|
||||
advancedYearTo: 'până la',
|
||||
advancedBpm: 'BPM',
|
||||
advancedBpmLocalNote: 'Uses tag BPM and measured analysis when the local index is enabled',
|
||||
advancedBpmClear: 'Golește filtrul BPM',
|
||||
bpmSourceTag: 'BPM from file tag',
|
||||
bpmSourceAnalysis: 'BPM from audio analysis',
|
||||
advancedMoodGroup: 'Mood',
|
||||
advancedAllMoods: 'All moods',
|
||||
advancedMoodLocalNote: 'Requires local library index and track analysis',
|
||||
advancedAll: 'Toate',
|
||||
advancedSearch: 'Căutare',
|
||||
advancedEmpty: 'Introdu un termen de căutare sau alege un filtru pentru a începe',
|
||||
@@ -48,4 +55,12 @@ export const search = {
|
||||
shareQueuePreviewLoading: 'Loading tracks…',
|
||||
shareQueuePreviewEmpty: 'No tracks from this link could be found on the server.',
|
||||
shareQueuePreviewSkipped: '{{skipped}} of {{total}} tracks were not found on this server.',
|
||||
moodGroups: {
|
||||
joy: 'Bucurie',
|
||||
sadness: 'Tristețe',
|
||||
dance: 'Dans',
|
||||
work: 'Muncă',
|
||||
romance: 'Romantic',
|
||||
anger: 'Furie',
|
||||
},
|
||||
};
|
||||
|
||||
@@ -9,6 +9,7 @@ export const songInfo = {
|
||||
duration: 'Durată',
|
||||
track: 'Piesă',
|
||||
bpm: 'BPM',
|
||||
mood: 'Stare de spirit',
|
||||
playCount: 'Număr de redări',
|
||||
lastPlayed: 'Ultima redare',
|
||||
format: 'Format',
|
||||
|
||||
@@ -43,4 +43,15 @@ export const queue = {
|
||||
sourceStream: 'Играет из сетевого потока',
|
||||
clearCachedLoudnessWaveform: 'Сбросить кэш громкости (LUFS) и формы волны и заново проанализировать трек',
|
||||
recalculatingLoudnessWaveform: 'Пересчёт громкости и формы волны для этого трека…',
|
||||
bpm: '{{bpm}} BPM',
|
||||
moods: {
|
||||
happy: 'Радостный',
|
||||
excited: 'Возбуждённый',
|
||||
calm: 'Спокойный',
|
||||
peaceful: 'Мирный',
|
||||
angry: 'Злой',
|
||||
tense: 'Напряжённый',
|
||||
sad: 'Грустный',
|
||||
melancholic: 'Меланхоличный',
|
||||
},
|
||||
};
|
||||
|
||||
@@ -23,6 +23,13 @@ export const search = {
|
||||
advancedYearFrom: 'от',
|
||||
advancedYearTo: 'до',
|
||||
advancedBpm: 'BPM',
|
||||
advancedBpmLocalNote: 'Тег BPM и измеренный анализ — при включённом локальном индексе; анализ приоритетнее тега',
|
||||
advancedBpmClear: 'Сбросить BPM',
|
||||
bpmSourceTag: 'BPM из тега файла',
|
||||
bpmSourceAnalysis: 'BPM из анализа аудио',
|
||||
advancedMoodGroup: 'Настроение',
|
||||
advancedAllMoods: 'Все настроения',
|
||||
advancedMoodLocalNote: 'Только локальный индекс и анализ треков',
|
||||
advancedAll: 'Все',
|
||||
advancedSearch: 'Найти',
|
||||
advancedEmpty: 'Введите запрос или выберите фильтр.',
|
||||
@@ -52,4 +59,12 @@ export const search = {
|
||||
shareQueuePreviewLoading: 'Загрузка треков…',
|
||||
shareQueuePreviewEmpty: 'Треки из этой ссылки не найдены на сервере.',
|
||||
shareQueuePreviewSkipped: '{{skipped}} из {{total}} треков не найдено на этом сервере.',
|
||||
moodGroups: {
|
||||
joy: 'Радость',
|
||||
sadness: 'Грусть',
|
||||
dance: 'Танцы',
|
||||
work: 'Работа',
|
||||
romance: 'Романтика',
|
||||
anger: 'Злость',
|
||||
},
|
||||
};
|
||||
|
||||
@@ -9,6 +9,7 @@ export const songInfo = {
|
||||
duration: 'Длительность',
|
||||
track: 'Номер',
|
||||
bpm: 'BPM',
|
||||
mood: 'Настроение',
|
||||
playCount: 'Количество прослушиваний',
|
||||
lastPlayed: 'Последнее воспроизведение',
|
||||
format: 'Формат',
|
||||
|
||||
@@ -43,4 +43,15 @@ export const queue = {
|
||||
sourceStream: '正在从网络流播放',
|
||||
clearCachedLoudnessWaveform: 'Clear cached loudness and waveform, then re-analyze this track',
|
||||
recalculatingLoudnessWaveform: 'Recalculating loudness and waveform for this track…',
|
||||
bpm: '{{bpm}} BPM',
|
||||
moods: {
|
||||
happy: 'Happy',
|
||||
excited: 'Excited',
|
||||
calm: 'Calm',
|
||||
peaceful: 'Peaceful',
|
||||
angry: 'Angry',
|
||||
tense: 'Tense',
|
||||
sad: 'Sad',
|
||||
melancholic: 'Melancholic',
|
||||
},
|
||||
};
|
||||
|
||||
@@ -23,6 +23,13 @@ export const search = {
|
||||
advancedYearFrom: '从',
|
||||
advancedYearTo: '至',
|
||||
advancedBpm: 'BPM',
|
||||
advancedBpmLocalNote: 'Uses tag BPM and measured analysis when the local index is enabled',
|
||||
advancedBpmClear: '清除 BPM 筛选',
|
||||
bpmSourceTag: 'BPM from file tag',
|
||||
bpmSourceAnalysis: 'BPM from audio analysis',
|
||||
advancedMoodGroup: 'Mood',
|
||||
advancedAllMoods: 'All moods',
|
||||
advancedMoodLocalNote: 'Requires local library index and track analysis',
|
||||
advancedAll: '全部',
|
||||
advancedSearch: '搜索',
|
||||
advancedEmpty: '请输入搜索词或选择过滤器。',
|
||||
@@ -48,4 +55,12 @@ export const search = {
|
||||
shareQueuePreviewLoading: 'Loading tracks…',
|
||||
shareQueuePreviewEmpty: 'No tracks from this link could be found on the server.',
|
||||
shareQueuePreviewSkipped: '{{skipped}} of {{total}} tracks were not found on this server.',
|
||||
moodGroups: {
|
||||
joy: 'Joy',
|
||||
sadness: 'Sadness',
|
||||
dance: 'Dance',
|
||||
work: 'Work',
|
||||
romance: 'Romance',
|
||||
anger: 'Anger',
|
||||
},
|
||||
};
|
||||
|
||||
@@ -9,6 +9,7 @@ export const songInfo = {
|
||||
duration: '时长',
|
||||
track: '曲目',
|
||||
bpm: 'BPM',
|
||||
mood: '情绪',
|
||||
playCount: '播放次数',
|
||||
lastPlayed: '上次播放',
|
||||
format: '格式',
|
||||
|
||||
+176
-10
@@ -4,7 +4,7 @@ import { getAlbumList, getRandomSongs } from '../api/subsonicLibrary';
|
||||
import type { SubsonicGenre, SubsonicArtist, SubsonicAlbum, SubsonicSong } from '../api/subsonicTypes';
|
||||
import React, { useCallback, useEffect, useMemo, useRef, useState } from 'react';
|
||||
import { useSearchParams } from 'react-router-dom';
|
||||
import { SlidersVertical } from 'lucide-react';
|
||||
import { SlidersVertical, X } from 'lucide-react';
|
||||
import { useTranslation } from 'react-i18next';
|
||||
import AlbumRow from '../components/AlbumRow';
|
||||
import ArtistRow from '../components/ArtistRow';
|
||||
@@ -14,9 +14,13 @@ import StarFilterButton from '../components/StarFilterButton';
|
||||
import { useAuthStore } from '../store/authStore';
|
||||
import { usePlayerStore } from '../store/playerStore';
|
||||
import { runLocalAdvancedSearch, loadMoreLocalSongs, runNetworkAdvancedTextSearch } from '../utils/library/advancedSearchLocal';
|
||||
import { OXIMEDIA_MOOD_SEARCH_ENABLED } from '../utils/library/trackEnrichment';
|
||||
import { raceSearchSources } from '../utils/library/searchRace';
|
||||
import { logLibrarySearch } from '../utils/library/libraryDevLog';
|
||||
import { useLibraryIndexStore } from '../store/libraryIndexStore';
|
||||
import { MOOD_GROUP_IDS } from '../config/moodGroups';
|
||||
|
||||
const MOOD_UI_ENABLED = OXIMEDIA_MOOD_SEARCH_ENABLED;
|
||||
|
||||
type ResultType = 'all' | 'artists' | 'albums' | 'songs';
|
||||
|
||||
@@ -25,6 +29,9 @@ interface SearchOpts {
|
||||
genre: string;
|
||||
yearFrom: string;
|
||||
yearTo: string;
|
||||
bpmFrom: string;
|
||||
bpmTo: string;
|
||||
moodGroup: string;
|
||||
resultType: ResultType;
|
||||
}
|
||||
|
||||
@@ -34,6 +41,13 @@ interface Results {
|
||||
songs: SubsonicSong[];
|
||||
}
|
||||
|
||||
function parseBpmInput(raw: string): number | null {
|
||||
const trimmed = raw.trim();
|
||||
if (!trimmed) return null;
|
||||
const n = parseInt(trimmed, 10);
|
||||
return Number.isFinite(n) ? n : null;
|
||||
}
|
||||
|
||||
export default function AdvancedSearch() {
|
||||
const { t } = useTranslation();
|
||||
const [params] = useSearchParams();
|
||||
@@ -42,6 +56,9 @@ export default function AdvancedSearch() {
|
||||
const [genre, setGenre] = useState('');
|
||||
const [yearFrom, setYearFrom] = useState('');
|
||||
const [yearTo, setYearTo] = useState('');
|
||||
const [bpmFrom, setBpmFrom] = useState('');
|
||||
const [bpmTo, setBpmTo] = useState('');
|
||||
const [moodGroup, setMoodGroup] = useState('');
|
||||
const [resultType, setResultType] = useState<ResultType>('all');
|
||||
const [starredOnly, setStarredOnly] = useState(false);
|
||||
const [genres, setGenres] = useState<SubsonicGenre[]>([]);
|
||||
@@ -85,11 +102,15 @@ export default function AdvancedSearch() {
|
||||
g: string,
|
||||
from: number | null,
|
||||
to: number | null,
|
||||
bpmLo: number | null,
|
||||
bpmHi: number | null,
|
||||
): SubsonicSong[] => {
|
||||
let r = list;
|
||||
if (g) r = r.filter(s => s.genre?.toLowerCase() === g.toLowerCase());
|
||||
if (from !== null) r = r.filter(s => !s.year || s.year >= from);
|
||||
if (to !== null) r = r.filter(s => !s.year || s.year <= to);
|
||||
if (bpmLo !== null) r = r.filter(s => s.bpm != null && s.bpm > 0 && s.bpm >= bpmLo);
|
||||
if (bpmHi !== null) r = r.filter(s => s.bpm != null && s.bpm > 0 && s.bpm <= bpmHi);
|
||||
return r;
|
||||
};
|
||||
|
||||
@@ -106,8 +127,12 @@ export default function AdvancedSearch() {
|
||||
|
||||
const q = opts.query.trim();
|
||||
const searchT0 = performance.now();
|
||||
const moodFilterActive = MOOD_UI_ENABLED && !!opts.moodGroup;
|
||||
const bpmFilterActive = !!(opts.bpmFrom || opts.bpmTo);
|
||||
const trackOnlyFilterActive = moodFilterActive || bpmFilterActive;
|
||||
|
||||
if (q && serverId && indexEnabled) {
|
||||
// Track-only filters (BPM dual-storage, mood) need the local index for full coverage.
|
||||
if (q && serverId && indexEnabled && !trackOnlyFilterActive) {
|
||||
try {
|
||||
const winner = await raceSearchSources(
|
||||
[
|
||||
@@ -155,7 +180,7 @@ export default function AdvancedSearch() {
|
||||
if (isStale()) return;
|
||||
}
|
||||
setLocalMode(false);
|
||||
} else {
|
||||
} else if (serverId && indexEnabled) {
|
||||
const localPage = await runLocalAdvancedSearch(serverId, opts, SONGS_INITIAL);
|
||||
if (isStale()) return;
|
||||
if (localPage) {
|
||||
@@ -170,12 +195,27 @@ export default function AdvancedSearch() {
|
||||
setLoading(false);
|
||||
return;
|
||||
}
|
||||
if (trackOnlyFilterActive) {
|
||||
setResults({ artists: [], albums: [], songs: [] });
|
||||
setLoading(false);
|
||||
return;
|
||||
}
|
||||
setLocalMode(false);
|
||||
} else {
|
||||
setLocalMode(false);
|
||||
}
|
||||
|
||||
const { genre: g, yearFrom: yf, yearTo: yt, resultType: rt } = opts;
|
||||
if (trackOnlyFilterActive && !indexEnabled) {
|
||||
setResults({ artists: [], albums: [], songs: [] });
|
||||
setLoading(false);
|
||||
return;
|
||||
}
|
||||
|
||||
const { genre: g, yearFrom: yf, yearTo: yt, bpmFrom: bf, bpmTo: bt, resultType: rt } = opts;
|
||||
const from = yf ? parseInt(yf) : null;
|
||||
const to = yt ? parseInt(yt) : null;
|
||||
const bpmLo = bf ? parseInt(bf) : null;
|
||||
const bpmHi = bt ? parseInt(bt) : null;
|
||||
|
||||
let artists: SubsonicArtist[] = [];
|
||||
let albums: SubsonicAlbum[] = [];
|
||||
@@ -186,7 +226,7 @@ export default function AdvancedSearch() {
|
||||
const r = await search(q.trim(), { artistCount: 30, albumCount: 50, songCount: SONGS_INITIAL });
|
||||
artists = r.artists;
|
||||
albums = r.albums;
|
||||
songs = applySongFilters(r.songs, g, from, to);
|
||||
songs = applySongFilters(r.songs, g, from, to, bpmLo, bpmHi);
|
||||
|
||||
if (g) {
|
||||
albums = albums.filter(a => a.genre?.toLowerCase() === g.toLowerCase());
|
||||
@@ -209,6 +249,7 @@ export default function AdvancedSearch() {
|
||||
]);
|
||||
albums = albumRes as SubsonicAlbum[];
|
||||
songs = songRes as SubsonicSong[];
|
||||
songs = applySongFilters(songs, g, from, to, bpmLo, bpmHi);
|
||||
if (from !== null) albums = albums.filter(a => !a.year || a.year >= from);
|
||||
if (to !== null) albums = albums.filter(a => !a.year || a.year <= to);
|
||||
if (songs.length > 0) setGenreNote(true);
|
||||
@@ -250,7 +291,18 @@ export default function AdvancedSearch() {
|
||||
getGenres().then(data =>
|
||||
setGenres(data.sort((a, b) => a.value.localeCompare(b.value)))
|
||||
).catch(() => {});
|
||||
if (qFromUrl) runSearch({ query: qFromUrl, genre: '', yearFrom: '', yearTo: '', resultType: 'all' });
|
||||
if (qFromUrl) {
|
||||
runSearch({
|
||||
query: qFromUrl,
|
||||
genre: '',
|
||||
yearFrom: '',
|
||||
yearTo: '',
|
||||
bpmFrom: '',
|
||||
bpmTo: '',
|
||||
moodGroup: '',
|
||||
resultType: 'all',
|
||||
});
|
||||
}
|
||||
}, [musicLibraryFilterVersion, qFromUrl]);
|
||||
|
||||
const loadMoreSongs = useCallback(async () => {
|
||||
@@ -280,8 +332,10 @@ export default function AdvancedSearch() {
|
||||
const g = activeSearch.genre;
|
||||
const from = activeSearch.yearFrom ? parseInt(activeSearch.yearFrom) : null;
|
||||
const to = activeSearch.yearTo ? parseInt(activeSearch.yearTo) : null;
|
||||
const bpmLo = activeSearch.bpmFrom ? parseInt(activeSearch.bpmFrom) : null;
|
||||
const bpmHi = activeSearch.bpmTo ? parseInt(activeSearch.bpmTo) : null;
|
||||
const page = await searchSongsPaged(q, SONGS_PAGE_SIZE, songsServerOffset);
|
||||
const filtered = applySongFilters(page, g, from, to);
|
||||
const filtered = applySongFilters(page, g, from, to, bpmLo, bpmHi);
|
||||
setResults(prev => prev ? { ...prev, songs: [...prev.songs, ...filtered] } : prev);
|
||||
setSongsServerOffset(o => o + page.length);
|
||||
// No more pages when the server returned a non-full page (regardless of how many survived filtering).
|
||||
@@ -293,9 +347,29 @@ export default function AdvancedSearch() {
|
||||
}
|
||||
}, [loadingMoreSongs, songsHasMore, activeSearch, songsServerOffset, localMode, serverId]);
|
||||
|
||||
const trackFilterActive =
|
||||
(MOOD_UI_ENABLED && !!moodGroup) || !!(bpmFrom || bpmTo);
|
||||
|
||||
const bpmFilterDraftActive = !!(bpmFrom || bpmTo);
|
||||
|
||||
const clearBpmFilter = () => {
|
||||
setBpmFrom('');
|
||||
setBpmTo('');
|
||||
};
|
||||
|
||||
const handleSubmit = (e?: React.FormEvent) => {
|
||||
e?.preventDefault();
|
||||
runSearch({ query, genre, yearFrom, yearTo, resultType });
|
||||
const effectiveType = trackFilterActive ? 'songs' : resultType;
|
||||
runSearch({
|
||||
query,
|
||||
genre,
|
||||
yearFrom,
|
||||
yearTo,
|
||||
bpmFrom,
|
||||
bpmTo,
|
||||
moodGroup,
|
||||
resultType: effectiveType,
|
||||
});
|
||||
};
|
||||
|
||||
const typeOptions: { id: ResultType; label: string }[] = [
|
||||
@@ -310,6 +384,17 @@ export default function AdvancedSearch() {
|
||||
...genres.map(g => ({ value: g.value, label: g.value })),
|
||||
];
|
||||
|
||||
const moodSelectOptions = useMemo(
|
||||
() => [
|
||||
{ value: '', label: t('search.advancedAllMoods') },
|
||||
...MOOD_GROUP_IDS.map(id => ({
|
||||
value: id,
|
||||
label: t(`search.moodGroups.${id}`),
|
||||
})),
|
||||
],
|
||||
[t],
|
||||
);
|
||||
|
||||
return (
|
||||
<div className="content-body animate-fade-in">
|
||||
<div style={{ marginBottom: '1.5rem' }}>
|
||||
@@ -379,10 +464,90 @@ export default function AdvancedSearch() {
|
||||
/>
|
||||
</div>
|
||||
|
||||
{/* Row 3: Result type + Search button */}
|
||||
{/* Row 3: BPM (tag + measured enrichment via local index) */}
|
||||
{indexEnabled && (
|
||||
<div style={{ display: 'flex', gap: '0.75rem', alignItems: 'center', flexWrap: 'wrap' }}>
|
||||
<span style={{ fontSize: 13, color: 'var(--text-muted)', minWidth: 90, flexShrink: 0 }}>
|
||||
{t('search.advancedBpm')}
|
||||
</span>
|
||||
<input
|
||||
className="input"
|
||||
type="number"
|
||||
min={20}
|
||||
max={999}
|
||||
value={bpmFrom}
|
||||
onChange={e => setBpmFrom(e.target.value)}
|
||||
onBlur={e => {
|
||||
const from = parseBpmInput(e.target.value);
|
||||
const to = parseBpmInput(bpmTo);
|
||||
if (from != null && to != null && from > to) setBpmTo('');
|
||||
}}
|
||||
placeholder={t('search.advancedYearFrom')}
|
||||
style={{ width: 96 }}
|
||||
/>
|
||||
<span style={{ color: 'var(--text-muted)', fontSize: 14 }}>–</span>
|
||||
<input
|
||||
className="input"
|
||||
type="number"
|
||||
min={20}
|
||||
max={999}
|
||||
value={bpmTo}
|
||||
onChange={e => setBpmTo(e.target.value)}
|
||||
onBlur={e => {
|
||||
const to = parseBpmInput(e.target.value);
|
||||
const from = parseBpmInput(bpmFrom);
|
||||
if (from != null && to != null && to < from) setBpmFrom('');
|
||||
}}
|
||||
placeholder={t('search.advancedYearTo')}
|
||||
style={{ width: 96 }}
|
||||
/>
|
||||
{bpmFilterDraftActive && (
|
||||
<button
|
||||
type="button"
|
||||
className="btn btn-ghost"
|
||||
onClick={clearBpmFilter}
|
||||
style={{
|
||||
padding: '0.3rem 0.55rem',
|
||||
display: 'flex',
|
||||
alignItems: 'center',
|
||||
gap: '0.3rem',
|
||||
fontSize: '0.8rem',
|
||||
flexShrink: 0,
|
||||
}}
|
||||
>
|
||||
<X size={13} />
|
||||
{t('search.advancedBpmClear')}
|
||||
</button>
|
||||
)}
|
||||
<span style={{ fontSize: 12, color: 'var(--text-muted)' }}>
|
||||
{t('search.advancedBpmLocalNote')}
|
||||
</span>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* Mood — hidden while oximedia mood analysis is disabled */}
|
||||
{indexEnabled && MOOD_UI_ENABLED && (
|
||||
<div style={{ display: 'flex', gap: '0.75rem', alignItems: 'center', flexWrap: 'wrap' }}>
|
||||
<span style={{ fontSize: 13, color: 'var(--text-muted)', minWidth: 90, flexShrink: 0 }}>
|
||||
{t('search.advancedMoodGroup')}
|
||||
</span>
|
||||
<div style={{ minWidth: 240, flex: '1 1 240px', maxWidth: 360 }}>
|
||||
<CustomSelect
|
||||
value={moodGroup}
|
||||
options={moodSelectOptions}
|
||||
onChange={setMoodGroup}
|
||||
/>
|
||||
</div>
|
||||
<span style={{ fontSize: 12, color: 'var(--text-muted)' }}>
|
||||
{t('search.advancedMoodLocalNote')}
|
||||
</span>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* Row 4: Result type + Search button */}
|
||||
<div style={{ display: 'flex', gap: '0.5rem', alignItems: 'center', justifyContent: 'space-between', flexWrap: 'wrap' }}>
|
||||
<div style={{ display: 'flex', gap: '0.3rem', flexWrap: 'wrap', alignItems: 'center' }}>
|
||||
{typeOptions.map(opt => (
|
||||
{!trackFilterActive && typeOptions.map(opt => (
|
||||
<button
|
||||
key={opt.id}
|
||||
type="button"
|
||||
@@ -454,6 +619,7 @@ export default function AdvancedSearch() {
|
||||
hasMore={songsHasMore}
|
||||
loadingMore={loadingMoreSongs}
|
||||
onLoadMore={loadMoreSongs}
|
||||
showBpm={!!(activeSearch?.bpmFrom || activeSearch?.bpmTo)}
|
||||
/>
|
||||
</section>
|
||||
)}
|
||||
|
||||
@@ -232,8 +232,16 @@ export function handleAudioProgress(
|
||||
shouldBytePreloadFromMode ||
|
||||
shouldBytePreloadForCrossfade
|
||||
);
|
||||
// Hot/offline cache: seed enrichment from disk (playback also uses psysonic-local://).
|
||||
const shouldPreloadLocalFileAnalysis = preloadMode !== 'off' && (
|
||||
preloadMode === 'early'
|
||||
? current_time >= 5
|
||||
: preloadMode === 'custom'
|
||||
? remaining < preloadCustomSeconds && remaining > 0
|
||||
: remaining < 30 && remaining > 0
|
||||
);
|
||||
|
||||
if (shouldChainGapless || shouldBytePreload || gaplessEnabled) {
|
||||
if (shouldChainGapless || shouldBytePreload || shouldPreloadLocalFileAnalysis || gaplessEnabled) {
|
||||
const { queue, queueIndex, repeatMode } = store;
|
||||
const nextIdx = queueIndex + 1;
|
||||
const nextTrack = repeatMode === 'one'
|
||||
@@ -260,9 +268,13 @@ export function handleAudioProgress(
|
||||
|
||||
const serverId = getPlaybackServerId();
|
||||
const nextUrl = resolvePlaybackUrl(nextTrack.id, serverId);
|
||||
const nextIsLocalFile = nextUrl.startsWith('psysonic-local://');
|
||||
|
||||
// Byte pre-download — runs early so bytes are cached by chain time.
|
||||
if ((shouldBytePreload || shouldBytePreloadForGaplessBackup) && nextTrack.id !== getBytePreloadingId()) {
|
||||
if (
|
||||
(shouldBytePreload || shouldBytePreloadForGaplessBackup || (shouldPreloadLocalFileAnalysis && nextIsLocalFile))
|
||||
&& nextTrack.id !== getBytePreloadingId()
|
||||
) {
|
||||
setBytePreloadingId(nextTrack.id);
|
||||
// Loudness cache only — do not call refreshWaveformForTrack(next): it writes global
|
||||
// waveformBins and would replace the current track's seekbar while still playing it.
|
||||
@@ -273,6 +285,8 @@ export function handleAudioProgress(
|
||||
nextUrl,
|
||||
shouldBytePreload,
|
||||
shouldBytePreloadForGaplessBackup,
|
||||
shouldPreloadLocalFileAnalysis,
|
||||
nextIsLocalFile,
|
||||
remaining,
|
||||
gaplessEnabled,
|
||||
});
|
||||
@@ -314,6 +328,7 @@ export function handleAudioProgress(
|
||||
fallbackDb: authState.replayGainFallbackDb,
|
||||
hiResEnabled: authState.enableHiRes,
|
||||
analysisTrackId: nextTrack.id,
|
||||
serverId: serverId || null,
|
||||
}).catch(() => {});
|
||||
}
|
||||
}
|
||||
|
||||
@@ -25,6 +25,12 @@ import {
|
||||
import { usePlayerStore } from '../playerStore';
|
||||
import { refreshWaveformForTrack } from '../waveformRefresh';
|
||||
import { bumpWaveformRefreshGen } from '../waveformRefreshGen';
|
||||
import { setBytePreloadingId } from '../gaplessPreloadState';
|
||||
|
||||
type PreloadEventPayload = {
|
||||
url: string;
|
||||
trackId?: string | null;
|
||||
};
|
||||
|
||||
/**
|
||||
* Tauri event listeners for the Rust audio engine + analysis pipeline. Returns
|
||||
@@ -95,6 +101,13 @@ export function setupAudioEngineListeners(): () => void {
|
||||
void refreshLoudnessForTrack(payloadTrackId, { syncPlayingEngine: false });
|
||||
emitNormalizationDebug('backfill:applied', { trackId: payloadTrackId });
|
||||
}),
|
||||
listen<{ trackId: string; serverId: string }>('analysis:enrichment-updated', ({ payload }) => {
|
||||
if (!payload?.trackId) return;
|
||||
emitNormalizationDebug('enrichment:applied', {
|
||||
trackId: normalizeAnalysisTrackId(payload.trackId) ?? payload.trackId,
|
||||
serverId: payload.serverId,
|
||||
});
|
||||
}),
|
||||
listen<NormalizationStatePayload>('audio:normalization-state', ({ payload }) => {
|
||||
if (!payload) return;
|
||||
const engine =
|
||||
@@ -140,8 +153,8 @@ export function setupAudioEngineListeners(): () => void {
|
||||
normalizationDbgLastEventAt: Date.now(),
|
||||
});
|
||||
}),
|
||||
listen<string>('audio:preload-ready', ({ payload }) => {
|
||||
const tid = streamUrlTrackId(payload);
|
||||
listen<PreloadEventPayload>('audio:preload-ready', ({ payload }) => {
|
||||
const tid = payload.trackId ?? streamUrlTrackId(payload.url);
|
||||
if (import.meta.env.DEV) {
|
||||
console.info('[psysonic][preload-ready]', {
|
||||
payload,
|
||||
@@ -154,6 +167,12 @@ export function setupAudioEngineListeners(): () => void {
|
||||
console.warn('[psysonic][preload-ready] could not parse track id from payload URL');
|
||||
}
|
||||
}),
|
||||
listen<PreloadEventPayload>('audio:preload-cancelled', ({ payload }) => {
|
||||
if (import.meta.env.DEV) {
|
||||
console.info('[psysonic][preload-cancelled]', payload);
|
||||
}
|
||||
setBytePreloadingId(null);
|
||||
}),
|
||||
];
|
||||
|
||||
return () => {
|
||||
|
||||
@@ -209,6 +209,12 @@
|
||||
color: var(--accent);
|
||||
}
|
||||
|
||||
.queue-current-enrichment {
|
||||
font-size: 11px;
|
||||
font-variant-numeric: tabular-nums;
|
||||
color: var(--text-muted);
|
||||
}
|
||||
|
||||
.queue-current-tech {
|
||||
width: 100%;
|
||||
font-size: 9px;
|
||||
|
||||
@@ -21,6 +21,10 @@
|
||||
grid-template-columns: 64px minmax(0, 1.5fr) minmax(0, 1fr) 56px;
|
||||
}
|
||||
|
||||
.song-list-row--with-bpm {
|
||||
grid-template-columns: 64px minmax(0, 1.5fr) minmax(0, 1fr) 48px 56px;
|
||||
}
|
||||
|
||||
.song-list-row-cell:nth-child(4), /* album */
|
||||
.song-list-row-cell:nth-child(5) { /* genre */
|
||||
display: none;
|
||||
|
||||
@@ -74,6 +74,17 @@
|
||||
font-size: 12px;
|
||||
}
|
||||
|
||||
.song-list-row--with-bpm {
|
||||
grid-template-columns: 64px minmax(0, 1.5fr) minmax(0, 1fr) minmax(0, 1fr) 110px 48px 56px;
|
||||
}
|
||||
|
||||
.song-list-row-bpm {
|
||||
text-align: right;
|
||||
font-variant-numeric: tabular-nums;
|
||||
color: var(--text-muted);
|
||||
font-size: 12px;
|
||||
}
|
||||
|
||||
.song-list-row-btn {
|
||||
background: transparent;
|
||||
border: none;
|
||||
|
||||
@@ -2,13 +2,16 @@ import { describe, it, expect, beforeEach } from 'vitest';
|
||||
import { onInvoke } from '@/test/mocks/tauri';
|
||||
import { useAuthStore } from '@/store/authStore';
|
||||
import { useLibraryIndexStore } from '@/store/libraryIndexStore';
|
||||
import { runLocalAdvancedSearch, runLocalSongBrowse } from './advancedSearchLocal';
|
||||
import { runLocalAdvancedSearch, runLocalSongBrowse, trackToSong } from './advancedSearchLocal';
|
||||
|
||||
const opts = (over: Partial<Parameters<typeof runLocalAdvancedSearch>[1]> = {}) => ({
|
||||
query: '',
|
||||
genre: '',
|
||||
yearFrom: '',
|
||||
yearTo: '',
|
||||
bpmFrom: '',
|
||||
bpmTo: '',
|
||||
moodGroup: '',
|
||||
resultType: 'all' as const,
|
||||
...over,
|
||||
});
|
||||
@@ -58,6 +61,41 @@ describe('runLocalAdvancedSearch', () => {
|
||||
expect(captured).toMatchObject({ request: { libraryScope: 'lib7' } });
|
||||
});
|
||||
|
||||
it('passes bpm between filter to library_advanced_search', async () => {
|
||||
ready();
|
||||
let captured: unknown;
|
||||
onInvoke('library_advanced_search', (args) => {
|
||||
captured = args;
|
||||
return {
|
||||
artists: [],
|
||||
albums: [],
|
||||
tracks: [],
|
||||
totals: { artists: 0, albums: 0, tracks: 0 },
|
||||
source: 'local',
|
||||
};
|
||||
});
|
||||
await runLocalAdvancedSearch('s1', opts({ bpmFrom: '120', bpmTo: '130' }), 100);
|
||||
expect(captured).toMatchObject({
|
||||
request: { filters: [{ field: 'bpm', op: 'between', value: 120, valueTo: 130 }] },
|
||||
});
|
||||
});
|
||||
|
||||
it('trackToSong keeps resolved bpm and source over rawJson tag', () => {
|
||||
const song = trackToSong({
|
||||
serverId: 's1',
|
||||
id: 't1',
|
||||
title: 'T',
|
||||
album: 'Alb',
|
||||
durationSec: 100,
|
||||
syncedAt: 0,
|
||||
bpm: 128,
|
||||
bpmSource: 'analysis',
|
||||
rawJson: { id: 't1', title: 'T', artist: 'A', album: 'Alb', albumId: 'al1', duration: 100, bpm: 90 },
|
||||
});
|
||||
expect(song.bpm).toBe(128);
|
||||
expect(song.localBpmSource).toBe('analysis');
|
||||
});
|
||||
|
||||
it('prefers rawJson, falls back to hot columns, and reports the full total', async () => {
|
||||
ready();
|
||||
onInvoke('library_advanced_search', () => ({
|
||||
|
||||
@@ -25,15 +25,19 @@ import { search } from '../../api/subsonicSearch';
|
||||
import { libraryScopeForServer } from '../../api/subsonicClient';
|
||||
import { libraryIsReady } from './libraryReady';
|
||||
import { logLibrarySearch, timed } from './libraryDevLog';
|
||||
import { OXIMEDIA_MOOD_SEARCH_ENABLED } from './trackEnrichment';
|
||||
|
||||
export type AdvancedResultType = 'all' | 'artists' | 'albums' | 'songs';
|
||||
|
||||
/** UI opts for Advanced Search — BPM filter hidden until enrichment ships. */
|
||||
/** UI opts for Advanced Search — BPM/mood filters require local index. */
|
||||
export interface LocalSearchOpts {
|
||||
query: string;
|
||||
genre: string;
|
||||
yearFrom: string;
|
||||
yearTo: string;
|
||||
bpmFrom: string;
|
||||
bpmTo: string;
|
||||
moodGroup: string;
|
||||
resultType: AdvancedResultType;
|
||||
}
|
||||
|
||||
@@ -73,9 +77,39 @@ function buildFilters(opts: LocalSearchOpts): LibraryFilterClause[] {
|
||||
} else if (to !== null) {
|
||||
filters.push({ field: 'year', op: 'lte', value: to });
|
||||
}
|
||||
const bpmFrom = opts.bpmFrom ? parseInt(opts.bpmFrom, 10) : null;
|
||||
const bpmTo = opts.bpmTo ? parseInt(opts.bpmTo, 10) : null;
|
||||
if (bpmFrom !== null && bpmTo !== null) {
|
||||
filters.push({ field: 'bpm', op: 'between', value: bpmFrom, valueTo: bpmTo });
|
||||
} else if (bpmFrom !== null) {
|
||||
filters.push({ field: 'bpm', op: 'gte', value: bpmFrom });
|
||||
} else if (bpmTo !== null) {
|
||||
filters.push({ field: 'bpm', op: 'lte', value: bpmTo });
|
||||
}
|
||||
if (OXIMEDIA_MOOD_SEARCH_ENABLED && opts.moodGroup) {
|
||||
filters.push({ field: 'mood_group', op: 'eq', value: opts.moodGroup });
|
||||
}
|
||||
return filters;
|
||||
}
|
||||
|
||||
function applyClientSongFilters(
|
||||
list: SubsonicSong[],
|
||||
opts: LocalSearchOpts,
|
||||
): SubsonicSong[] {
|
||||
let r = list;
|
||||
const g = opts.genre;
|
||||
const from = opts.yearFrom ? parseInt(opts.yearFrom, 10) : null;
|
||||
const to = opts.yearTo ? parseInt(opts.yearTo, 10) : null;
|
||||
const bpmFrom = opts.bpmFrom ? parseInt(opts.bpmFrom, 10) : null;
|
||||
const bpmTo = opts.bpmTo ? parseInt(opts.bpmTo, 10) : null;
|
||||
if (g) r = r.filter(s => s.genre?.toLowerCase() === g.toLowerCase());
|
||||
if (from !== null) r = r.filter(s => !s.year || s.year >= from);
|
||||
if (to !== null) r = r.filter(s => !s.year || s.year <= to);
|
||||
if (bpmFrom !== null) r = r.filter(s => s.bpm != null && s.bpm > 0 && s.bpm >= bpmFrom);
|
||||
if (bpmTo !== null) r = r.filter(s => s.bpm != null && s.bpm > 0 && s.bpm <= bpmTo);
|
||||
return r;
|
||||
}
|
||||
|
||||
function buildRequest(
|
||||
serverId: string,
|
||||
opts: LocalSearchOpts,
|
||||
@@ -100,6 +134,7 @@ function buildRequest(
|
||||
|
||||
export function trackToSong(t: LibraryTrackDto): SubsonicSong {
|
||||
const raw = isObject(t.rawJson) ? t.rawJson : {};
|
||||
const resolvedBpm = t.bpm != null && t.bpm > 0 ? t.bpm : undefined;
|
||||
const base: SubsonicSong = {
|
||||
id: t.id,
|
||||
title: t.title,
|
||||
@@ -119,13 +154,18 @@ export function trackToSong(t: LibraryTrackDto): SubsonicSong {
|
||||
starred: t.starredAt != null ? new Date(t.starredAt).toISOString() : undefined,
|
||||
userRating: t.userRating ?? undefined,
|
||||
playCount: t.playCount ?? undefined,
|
||||
bpm: t.bpm ?? undefined,
|
||||
bpm: resolvedBpm,
|
||||
isrc: t.isrc ?? undefined,
|
||||
albumArtist: t.albumArtist ?? undefined,
|
||||
};
|
||||
// `rawJson` is the authoritative original song — let it override the
|
||||
// hot-column fallbacks (it carries OpenSubsonic extras too).
|
||||
return { ...base, ...(raw as Partial<SubsonicSong>) };
|
||||
const merged: SubsonicSong = { ...base, ...(raw as Partial<SubsonicSong>) };
|
||||
if (resolvedBpm != null) merged.bpm = resolvedBpm;
|
||||
if (t.bpmSource === 'analysis' || t.bpmSource === 'tag') {
|
||||
merged.localBpmSource = t.bpmSource;
|
||||
}
|
||||
return merged;
|
||||
}
|
||||
|
||||
export function albumToAlbum(a: LibraryAlbumDto): SubsonicAlbum {
|
||||
@@ -165,9 +205,6 @@ export async function runNetworkAdvancedTextSearch(
|
||||
): Promise<LocalAdvancedSearchPage | null> {
|
||||
const q = opts.query.trim();
|
||||
if (!q) return null;
|
||||
const g = opts.genre;
|
||||
const from = opts.yearFrom ? parseInt(opts.yearFrom, 10) : null;
|
||||
const to = opts.yearTo ? parseInt(opts.yearTo, 10) : null;
|
||||
const rt = opts.resultType;
|
||||
|
||||
const r = await search(q, {
|
||||
@@ -178,12 +215,11 @@ export async function runNetworkAdvancedTextSearch(
|
||||
|
||||
let artists = r.artists;
|
||||
let albums = r.albums;
|
||||
let songs = r.songs;
|
||||
|
||||
if (g) songs = songs.filter(s => s.genre?.toLowerCase() === g.toLowerCase());
|
||||
if (from !== null) songs = songs.filter(s => !s.year || s.year >= from);
|
||||
if (to !== null) songs = songs.filter(s => !s.year || s.year <= to);
|
||||
let songs = applyClientSongFilters(r.songs, opts);
|
||||
|
||||
const g = opts.genre;
|
||||
const from = opts.yearFrom ? parseInt(opts.yearFrom, 10) : null;
|
||||
const to = opts.yearTo ? parseInt(opts.yearTo, 10) : null;
|
||||
if (g) albums = albums.filter(a => a.genre?.toLowerCase() === g.toLowerCase());
|
||||
if (from !== null) albums = albums.filter(a => !a.year || a.year >= from);
|
||||
if (to !== null) albums = albums.filter(a => !a.year || a.year <= to);
|
||||
|
||||
@@ -176,6 +176,9 @@ const emptyBrowseOpts = (query: string): LocalSearchOpts => ({
|
||||
genre: '',
|
||||
yearFrom: '',
|
||||
yearTo: '',
|
||||
bpmFrom: '',
|
||||
bpmTo: '',
|
||||
moodGroup: '',
|
||||
resultType: 'artists',
|
||||
});
|
||||
|
||||
@@ -184,6 +187,9 @@ const songBrowseOpts = (query: string): LocalSearchOpts => ({
|
||||
genre: '',
|
||||
yearFrom: '',
|
||||
yearTo: '',
|
||||
bpmFrom: '',
|
||||
bpmTo: '',
|
||||
moodGroup: '',
|
||||
resultType: 'songs',
|
||||
});
|
||||
|
||||
@@ -192,6 +198,9 @@ const fullSearchOpts = (query: string): LocalSearchOpts => ({
|
||||
genre: '',
|
||||
yearFrom: '',
|
||||
yearTo: '',
|
||||
bpmFrom: '',
|
||||
bpmTo: '',
|
||||
moodGroup: '',
|
||||
resultType: 'all',
|
||||
});
|
||||
|
||||
|
||||
@@ -0,0 +1,150 @@
|
||||
import { describe, expect, it } from 'vitest';
|
||||
import type { TFunction } from 'i18next';
|
||||
import {
|
||||
deriveMoodScores,
|
||||
formatQueueBpmTech,
|
||||
formatQueueMoodLabels,
|
||||
parseTrackEnrichmentFacts,
|
||||
resolveQueueBpm,
|
||||
resolveDisplayBpm,
|
||||
topMoodLabelIds,
|
||||
} from './trackEnrichment';
|
||||
import { topDistinctOximediaMoodTagIds, topOximediaMoodTagIds } from '../../config/moodGroups';
|
||||
|
||||
const t = ((key: string, opts?: Record<string, unknown>) => {
|
||||
if (key === 'queue.bpm') return `${opts?.bpm} BPM`;
|
||||
if (key === 'queue.moods.calm') return 'Calm';
|
||||
if (key === 'queue.moods.peaceful') return 'Peaceful';
|
||||
return key;
|
||||
}) as TFunction;
|
||||
|
||||
describe('parseTrackEnrichmentFacts', () => {
|
||||
it('does not surface oximedia mood labels in UI while detector is disabled', () => {
|
||||
const parsed = parseTrackEnrichmentFacts(
|
||||
[
|
||||
{
|
||||
serverId: 's1',
|
||||
trackId: 't1',
|
||||
factKind: 'moods',
|
||||
sourceKind: 'analysis',
|
||||
sourceId: 'oximedia-60s-center',
|
||||
valueText: '{"calm":0.6,"peaceful":0.4}',
|
||||
confidence: 0.9,
|
||||
fetchedAt: 1,
|
||||
},
|
||||
{
|
||||
serverId: 's1',
|
||||
trackId: 't1',
|
||||
factKind: 'valence',
|
||||
sourceKind: 'analysis',
|
||||
sourceId: 'oximedia-60s-center',
|
||||
valueReal: 0.55,
|
||||
confidence: 0.9,
|
||||
fetchedAt: 1,
|
||||
},
|
||||
{
|
||||
serverId: 's1',
|
||||
trackId: 't1',
|
||||
factKind: 'arousal',
|
||||
sourceKind: 'analysis',
|
||||
sourceId: 'oximedia-60s-center',
|
||||
valueReal: 0.42,
|
||||
confidence: 0.9,
|
||||
fetchedAt: 1,
|
||||
},
|
||||
],
|
||||
null,
|
||||
);
|
||||
expect(parsed.moodLabels).toEqual([]);
|
||||
});
|
||||
|
||||
it('reads analysis bpm fact with highest confidence', () => {
|
||||
const parsed = parseTrackEnrichmentFacts(
|
||||
[
|
||||
{
|
||||
serverId: 's1',
|
||||
trackId: 't1',
|
||||
factKind: 'bpm',
|
||||
sourceKind: 'analysis',
|
||||
sourceId: 'oximedia-60s-center',
|
||||
valueInt: 128,
|
||||
confidence: 0.9,
|
||||
fetchedAt: 1,
|
||||
},
|
||||
{
|
||||
serverId: 's1',
|
||||
trackId: 't1',
|
||||
factKind: 'bpm',
|
||||
sourceKind: 'analysis',
|
||||
sourceId: 'other',
|
||||
valueInt: 110,
|
||||
confidence: 0.5,
|
||||
fetchedAt: 1,
|
||||
},
|
||||
],
|
||||
120,
|
||||
);
|
||||
expect(parsed.measuredBpm).toBe(128);
|
||||
expect(parsed.serverBpm).toBe(120);
|
||||
expect(resolveQueueBpm(parsed)).toBe(128);
|
||||
});
|
||||
});
|
||||
|
||||
describe('resolveQueueBpm', () => {
|
||||
it('prefers measured analysis bpm over tag', () => {
|
||||
expect(resolveQueueBpm({ serverBpm: 120, measuredBpm: 128, moodLabels: [] })).toBe(128);
|
||||
});
|
||||
|
||||
it('falls back to tag bpm when no analysis fact', () => {
|
||||
expect(resolveQueueBpm({ serverBpm: 120, measuredBpm: null, moodLabels: [] })).toBe(120);
|
||||
});
|
||||
|
||||
it('falls back to measured when tag bpm missing', () => {
|
||||
expect(resolveQueueBpm({ serverBpm: null, measuredBpm: 128, moodLabels: [] })).toBe(128);
|
||||
});
|
||||
});
|
||||
|
||||
describe('resolveDisplayBpm', () => {
|
||||
it('ignores zero tag bpm and uses measured', () => {
|
||||
expect(resolveDisplayBpm(0, 132)).toBe(132);
|
||||
});
|
||||
});
|
||||
|
||||
describe('formatters', () => {
|
||||
it('formats bpm for tech row', () => {
|
||||
expect(formatQueueBpmTech({ serverBpm: 120, measuredBpm: 128, moodLabels: [] }, t)).toBe('128 BPM');
|
||||
});
|
||||
|
||||
it('localizes mood labels without weights', () => {
|
||||
expect(formatQueueMoodLabels(['calm', 'peaceful'], t)).toBe('Calm · Peaceful');
|
||||
});
|
||||
});
|
||||
|
||||
describe('topMoodLabelIds', () => {
|
||||
it('returns at most two distinct cluster labels from valence/arousal', () => {
|
||||
const labels = topMoodLabelIds(0.4, 0.75);
|
||||
expect(labels.includes('happy') && labels.includes('excited')).toBe(false);
|
||||
expect(labels.length).toBeLessThanOrEqual(2);
|
||||
});
|
||||
});
|
||||
|
||||
describe('distinct mood tag picking', () => {
|
||||
it('never keeps both happy and excited from raw scores', () => {
|
||||
expect(topDistinctOximediaMoodTagIds({ calm: 0.52, happy: 0.9, excited: 0.5 })).toEqual(['happy', 'calm']);
|
||||
});
|
||||
|
||||
it('sorts by score descending with id tie-break', () => {
|
||||
expect(topOximediaMoodTagIds({ calm: 0.2, happy: 0.9, excited: 0.5 })).toEqual([
|
||||
'happy',
|
||||
'excited',
|
||||
'calm',
|
||||
]);
|
||||
});
|
||||
});
|
||||
|
||||
describe('deriveMoodScores', () => {
|
||||
it('delegates to soft valence/arousal scoring', () => {
|
||||
const scores = deriveMoodScores(0.55, 0.42);
|
||||
expect(topDistinctOximediaMoodTagIds(scores, 2).some(id => id === 'calm' || id === 'peaceful')).toBe(true);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,163 @@
|
||||
import type { TFunction } from 'i18next';
|
||||
import type { TrackFactDto } from '../../api/library';
|
||||
import {
|
||||
distinctOximediaMoodTagIds,
|
||||
topDistinctOximediaMoodTagIds,
|
||||
topDistinctOximediaMoodTagIdsFromValenceArousal,
|
||||
moodScoresFromValenceArousal,
|
||||
} from '../../config/moodGroups';
|
||||
|
||||
/** Oximedia mood labels in queue/Song Info — off until a reliable model ships. */
|
||||
export const OXIMEDIA_MOOD_UI_ENABLED = false;
|
||||
/** Mood group filter in Advanced Search — off while oximedia mood is disabled. */
|
||||
export const OXIMEDIA_MOOD_SEARCH_ENABLED = false;
|
||||
export const OXIMEDIA_ENRICHMENT_SOURCE_KIND = 'analysis';
|
||||
export const OXIMEDIA_ENRICHMENT_SOURCE_ID = 'oximedia-60s-center';
|
||||
|
||||
/** Oximedia mood label ids — see `src/config/moodGroups.ts` and Rust `mood_groups`. */
|
||||
export type { OximediaMoodTagId } from '../../config/moodGroups';
|
||||
|
||||
export interface ParsedTrackEnrichment {
|
||||
serverBpm: number | null;
|
||||
measuredBpm: number | null;
|
||||
moodLabels: string[];
|
||||
}
|
||||
|
||||
function isOximediaFact(f: TrackFactDto): boolean {
|
||||
return (
|
||||
f.sourceKind === OXIMEDIA_ENRICHMENT_SOURCE_KIND
|
||||
&& (f.sourceId === OXIMEDIA_ENRICHMENT_SOURCE_ID
|
||||
|| f.sourceId.startsWith(`${OXIMEDIA_ENRICHMENT_SOURCE_ID}:`))
|
||||
);
|
||||
}
|
||||
|
||||
function pickBestAnalysisBpmFact(facts: readonly TrackFactDto[]): TrackFactDto | undefined {
|
||||
let best: TrackFactDto | undefined;
|
||||
for (const f of facts) {
|
||||
if (f.factKind !== 'bpm') continue;
|
||||
if (f.sourceKind !== 'analysis') continue;
|
||||
if (f.valueInt == null || f.valueInt <= 0) continue;
|
||||
if (!best || (f.confidence ?? 0) > (best.confidence ?? 0)) best = f;
|
||||
}
|
||||
return best;
|
||||
}
|
||||
|
||||
export function parseTrackEnrichmentFacts(
|
||||
facts: readonly TrackFactDto[],
|
||||
serverBpm: number | null | undefined,
|
||||
): ParsedTrackEnrichment {
|
||||
const oximedia = facts.filter(isOximediaFact);
|
||||
const measured = pickBestAnalysisBpmFact(facts);
|
||||
const moodsFact = oximedia.find(f => f.factKind === 'moods' && f.valueText);
|
||||
const legacyLabelsFact = oximedia.find(f => f.factKind === 'mood_labels' && f.valueText);
|
||||
const moodTagFacts = facts.filter(
|
||||
f => isOximediaFact(f) && f.factKind === 'mood_tag' && f.valueText,
|
||||
);
|
||||
const valence = oximedia.find(f => f.factKind === 'valence')?.valueReal ?? null;
|
||||
const arousal = oximedia.find(f => f.factKind === 'arousal')?.valueReal ?? null;
|
||||
|
||||
const hotBpm = serverBpm != null && serverBpm > 0 ? serverBpm : null;
|
||||
|
||||
const fromMoodsJson = topDistinctOximediaMoodTagIds(parseMoodsScoresJson(moodsFact?.valueText));
|
||||
const fromLegacy = parseMoodLabelsArray(legacyLabelsFact?.valueText);
|
||||
const fromMoodTags = distinctOximediaMoodTagIds(
|
||||
moodTagFacts.map(f => f.valueText!).filter(Boolean),
|
||||
);
|
||||
const fromValenceArousal =
|
||||
valence != null && arousal != null
|
||||
? topDistinctOximediaMoodTagIdsFromValenceArousal(valence, arousal)
|
||||
: [];
|
||||
const rawMoodLabels =
|
||||
(fromValenceArousal.length > 0 ? fromValenceArousal : null)
|
||||
?? (fromMoodTags.length > 0 ? fromMoodTags : null)
|
||||
?? (fromMoodsJson.length > 0 ? fromMoodsJson : null)
|
||||
?? (fromLegacy && fromLegacy.length > 0 ? fromLegacy : null)
|
||||
?? [];
|
||||
const moodLabels = OXIMEDIA_MOOD_UI_ENABLED ? rawMoodLabels : [];
|
||||
|
||||
return {
|
||||
serverBpm: hotBpm,
|
||||
measuredBpm: measured?.valueInt ?? null,
|
||||
moodLabels,
|
||||
};
|
||||
}
|
||||
|
||||
function parseMoodsScoresJson(raw: string | null | undefined): Record<string, number> | null {
|
||||
if (!raw) return null;
|
||||
try {
|
||||
const parsed: unknown = JSON.parse(raw);
|
||||
if (typeof parsed !== 'object' || parsed == null || Array.isArray(parsed)) return null;
|
||||
const out: Record<string, number> = {};
|
||||
for (const [key, value] of Object.entries(parsed as Record<string, unknown>)) {
|
||||
if (typeof value === 'number' && Number.isFinite(value)) out[key] = value;
|
||||
}
|
||||
return Object.keys(out).length > 0 ? out : null;
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
function parseMoodLabelsArray(raw: string | null | undefined): string[] | null {
|
||||
if (!raw) return null;
|
||||
try {
|
||||
const parsed: unknown = JSON.parse(raw);
|
||||
if (!Array.isArray(parsed)) return null;
|
||||
const labels = parsed.filter((v): v is string => typeof v === 'string' && v.length > 0);
|
||||
return labels.length > 0 ? labels.slice(0, 3) : null;
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
/** @deprecated Use `moodScoresFromValenceArousal` — oximedia quadrant copy. */
|
||||
export function deriveMoodScores(valence: number, arousal: number): Record<string, number> {
|
||||
return moodScoresFromValenceArousal(valence, arousal);
|
||||
}
|
||||
|
||||
/** @deprecated Use `topDistinctOximediaMoodTagIdsFromValenceArousal`. */
|
||||
export { topDistinctOximediaMoodTagIdsFromValenceArousal as topMoodLabelIds } from '../../config/moodGroups';
|
||||
|
||||
/** Analysis/measured BPM when present; otherwise file tag BPM. */
|
||||
export function resolveDisplayBpm(
|
||||
tagBpm: number | null | undefined,
|
||||
measuredBpm: number | null | undefined,
|
||||
): number | null {
|
||||
if (measuredBpm != null && measuredBpm > 0) return measuredBpm;
|
||||
if (tagBpm != null && tagBpm > 0) return tagBpm;
|
||||
return null;
|
||||
}
|
||||
|
||||
/** Analysis fact wins; tag BPM is shown until a fact is stored. */
|
||||
export function resolveQueueBpm(data: ParsedTrackEnrichment): number | null {
|
||||
return resolveDisplayBpm(data.serverBpm, data.measuredBpm);
|
||||
}
|
||||
|
||||
export function formatQueueBpmTech(data: ParsedTrackEnrichment, t: TFunction): string | null {
|
||||
const bpm = resolveQueueBpm(data);
|
||||
if (bpm == null) return null;
|
||||
return t('queue.bpm', { bpm });
|
||||
}
|
||||
|
||||
export function formatQueueMoodLabels(labels: readonly string[], t: TFunction): string | null {
|
||||
const names = labels
|
||||
.slice(0, 3)
|
||||
.map(id => {
|
||||
const key = `queue.moods.${id}`;
|
||||
const translated = t(key);
|
||||
return translated === key ? id : translated;
|
||||
});
|
||||
return names.length > 0 ? names.join(' · ') : null;
|
||||
}
|
||||
|
||||
function enrichmentHasMoodLabels(data: ParsedTrackEnrichment): boolean {
|
||||
return data.moodLabels.length > 0;
|
||||
}
|
||||
|
||||
function enrichmentHasBpm(data: ParsedTrackEnrichment): boolean {
|
||||
return (data.measuredBpm != null && data.measuredBpm > 0)
|
||||
|| (data.serverBpm != null && data.serverBpm > 0);
|
||||
}
|
||||
|
||||
export function enrichmentDisplayComplete(data: ParsedTrackEnrichment): boolean {
|
||||
return enrichmentHasMoodLabels(data) || enrichmentHasBpm(data);
|
||||
}
|
||||
Reference in New Issue
Block a user