fix(preview): Symphonia format sniff and cluster member stream URLs

Resolve preview container hints from HTTP headers, Subsonic suffix, and
magic-byte sniff after Symphonia 0.6. Route preview streams through
clusterBrowseServerId like main playback; guard CoverArtImage when the
preview cover ref is still loading.
This commit is contained in:
Maxim Isaev
2026-06-05 18:48:13 +03:00
parent 1d65a8d339
commit 0a09d29b06
11 changed files with 218 additions and 36 deletions
+2 -2
View File
@@ -8,7 +8,7 @@ import type { Track } from '../../store/playerStoreTypes';
import { songToTrack } from '../../utils/playback/songToTrack';
import { useSelectionStore } from '../../store/selectionStore';
import { useThemeStore } from '../../store/themeStore';
import { usePreviewStore } from '../../store/previewStore';
import { previewInputFromSong, usePreviewStore } from '../../store/previewStore';
import StarRating from '../StarRating';
import { codecLabel, type ColKey } from '../../utils/componentHelpers/albumTrackListHelpers';
import { formatLongDuration } from '../../utils/format/formatDuration';
@@ -116,7 +116,7 @@ export const TrackRow = React.memo(function TrackRow({
className={`playlist-suggestion-preview-btn${isPreviewing ? ' is-previewing' : ''}${isPreviewAudioStarted ? ' audio-started' : ''}`}
onClick={e => {
e.stopPropagation();
usePreviewStore.getState().startPreview({ id: song.id, title: song.title, artist: song.artist, coverArt: song.coverArt, duration: song.duration }, 'albums');
usePreviewStore.getState().startPreview(previewInputFromSong(song), 'albums');
}}
data-tooltip={isPreviewing ? t('playlists.previewStop') : t('playlists.preview')}
aria-label={isPreviewing ? t('playlists.previewStop') : t('playlists.preview')}
@@ -3,7 +3,7 @@ import { useTranslation } from 'react-i18next';
import { AudioLines, ChevronRight, Play, Square } from 'lucide-react';
import type { SubsonicAlbum, SubsonicSong } from '../../api/subsonicTypes';
import { usePlayerStore } from '../../store/playerStore';
import { usePreviewStore } from '../../store/previewStore';
import { previewInputFromSong, usePreviewStore } from '../../store/previewStore';
import { useOrbitSongRowBehavior } from '../../hooks/useOrbitSongRowBehavior';
import { songToTrack } from '../../utils/playback/songToTrack';
import { formatTrackTime } from '../../utils/format/formatDuration';
@@ -84,7 +84,7 @@ export default function ArtistDetailTopTracks({
<button
type="button"
className={`playlist-suggestion-preview-btn${previewingId === song.id ? ' is-previewing' : ''}${previewingId === song.id && previewAudioStarted ? ' audio-started' : ''}`}
onClick={e => { e.stopPropagation(); usePreviewStore.getState().startPreview({ id: song.id, title: song.title, artist: song.artist, coverArt: song.coverArt, duration: song.duration }, 'artist'); }}
onClick={e => { e.stopPropagation(); usePreviewStore.getState().startPreview(previewInputFromSong(song), 'artist'); }}
data-tooltip={previewingId === song.id ? t('playlists.previewStop') : t('playlists.preview')}
aria-label={previewingId === song.id ? t('playlists.previewStop') : t('playlists.preview')}
>
@@ -7,7 +7,7 @@ import { useNavigate } from 'react-router-dom';
import type { ColDef } from '../../utils/useTracklistColumns';
import type { SubsonicSong } from '../../api/subsonicTypes';
import { usePlayerStore } from '../../store/playerStore';
import { usePreviewStore } from '../../store/previewStore';
import { previewInputFromSong, usePreviewStore } from '../../store/previewStore';
import { useSelectionStore } from '../../store/selectionStore';
import { useThemeStore } from '../../store/themeStore';
import { useDragDrop } from '../../contexts/DragDropContext';
@@ -122,7 +122,7 @@ export default function FavoritesSongsTracklist({
L.playTrack(L.visibleTracks[index], L.visibleTracks);
},
startPreview: (song) => usePreviewStore.getState().startPreview(
{ id: song.id, title: song.title, artist: song.artist, coverArt: song.coverArt, duration: song.duration },
previewInputFromSong(song),
'favorites',
),
rate: (songId, r) => latest.current.handleRate(songId, r),
+7 -2
View File
@@ -62,7 +62,12 @@ export function PlayerTrackInfo({
const previewCoverRef = useAlbumCoverRef(
showPreviewMeta ? coverArtId : null,
showPreviewMeta ? coverArtId : null,
undefined,
showPreviewMeta
? { clusterSeedServerId: previewingTrack?.clusterBrowseServerId, libraryResolve: false }
: undefined,
);
const activeCoverRef = showPreviewMeta ? previewCoverRef : playbackCoverRef;
const layoutItems = usePlayerBarLayoutStore(s => s.items);
const isLayoutVisible = (id: PlayerBarLayoutItemId) =>
layoutItems.find(i => i.id === id)?.visible !== false;
@@ -88,10 +93,10 @@ export function PlayerTrackInfo({
<Cast size={20} />
</div>
)
) : !isRadio && (showPreviewMeta ? coverArtId : playbackCoverRef) ? (
) : !isRadio && activeCoverRef ? (
<CoverArtImage
className="player-album-art"
coverRef={showPreviewMeta ? previewCoverRef! : playbackCoverRef!}
coverRef={activeCoverRef}
displayCssPx={128}
surface="sparse"
ensurePriority="high"
@@ -13,7 +13,7 @@ import type { ColDef } from '../../utils/useTracklistColumns';
import type { SubsonicSong } from '../../api/subsonicTypes';
import type { Track } from '../../store/playerStoreTypes';
import { usePlayerStore } from '../../store/playerStore';
import { usePreviewStore } from '../../store/previewStore';
import { previewInputFromSong, usePreviewStore } from '../../store/previewStore';
import { useThemeStore } from '../../store/themeStore';
import { useDragDrop } from '../../contexts/DragDropContext';
import { useOrbitSongRowBehavior } from '../../hooks/useOrbitSongRowBehavior';
@@ -149,7 +149,7 @@ export default function PlaylistTracklist({
L.playTrack(L.displayedTracks[index], L.displayedTracks);
},
startPreview: (song) => usePreviewStore.getState().startPreview(
{ id: song.id, title: song.title, artist: song.artist, coverArt: song.coverArt, duration: song.duration },
previewInputFromSong(song),
'playlists',
),
toggleStar: (song, e) => latest.current.handleToggleStar(song, e),
@@ -3,7 +3,7 @@ import { useTranslation } from 'react-i18next';
import { AudioLines, ChevronRight, Heart, Play, Square } from 'lucide-react';
import type { SubsonicSong } from '../../api/subsonicTypes';
import type { Track } from '../../store/playerStoreTypes';
import { usePreviewStore } from '../../store/previewStore';
import { previewInputFromSong, usePreviewStore } from '../../store/previewStore';
import { useDragDrop } from '../../contexts/DragDropContext';
import { formatRandomMixDuration } from '../../utils/componentHelpers/randomMixHelpers';
@@ -110,7 +110,7 @@ export default function RandomMixTrackRow({
onClick={e => {
e.stopPropagation();
usePreviewStore.getState().startPreview(
{ id: song.id, title: song.title, artist: song.artist, coverArt: song.coverArt, duration: song.duration },
previewInputFromSong(song),
'randomMix',
);
}}
+13 -1
View File
@@ -13,7 +13,7 @@ import { useCoverArt } from './useCoverArt';
import type { CoverArtRef, CoverPrefetchPriority, CoverSurfaceKind } from './types';
export type CoverArtImageProps = {
coverRef: CoverArtRef;
coverRef: CoverArtRef | null | undefined;
displayCssPx: number;
surface?: CoverSurfaceKind;
fullRes?: boolean;
@@ -39,6 +39,18 @@ export function CoverArtImage({
onError: restOnError,
...rest
}: CoverArtImageProps) {
if (!coverRef) {
return (
<div
className={className}
data-cover-provisional="true"
role="img"
aria-label={alt ?? ''}
{...(rest as React.HTMLAttributes<HTMLDivElement>)}
/>
);
}
const pinnedHigh = ensurePriorityProp === 'high';
const [ensurePriority, setEnsurePriority] = useState<CoverPrefetchPriority>(
ensurePriorityProp ?? 'middle',
+2 -8
View File
@@ -1,5 +1,5 @@
import { useCallback, useEffect } from 'react';
import { usePreviewStore } from '../store/previewStore';
import { previewInputFromSong, usePreviewStore } from '../store/previewStore';
import type { SubsonicSong } from '../api/subsonicTypes';
export function usePlaylistPreview(): {
@@ -9,13 +9,7 @@ export function usePlaylistPreview(): {
// handled in `audio_preview_play` / `audio_preview_stop`. The store mirrors
// engine events so we just dispatch here and read `previewingId` for UI.
const startPreview = useCallback((song: SubsonicSong) => {
usePreviewStore.getState().startPreview({
id: song.id,
title: song.title,
artist: song.artist,
coverArt: song.coverArt,
duration: song.duration,
}, 'suggestions').catch(() => { /* engine errored — store already rolled back */ });
usePreviewStore.getState().startPreview(previewInputFromSong(song), 'suggestions').catch(() => { /* engine errored — store already rolled back */ });
}, []);
// Cancel any in-flight preview when the user navigates away.
+34 -2
View File
@@ -6,10 +6,19 @@
*
* Drives the store through its public action surface with the real
* Zustand instance, stubs the Tauri commands via `onInvoke`, and uses
* `vi.mock('@/api/subsonic')` because `startPreview` calls `buildStreamUrl`.
* `vi.mock` for stream URL resolution — `startPreview` uses `buildPreviewStreamUrl`.
*/
import { describe, it, expect, beforeEach, vi } from 'vitest';
const { resolvePlaybackUrlMock } = vi.hoisted(() => ({
resolvePlaybackUrlMock: vi.fn((trackId: string, serverId?: string) =>
`https://mock/stream/${serverId || 'default'}/${trackId}`),
}));
vi.mock('../utils/playback/resolvePlaybackUrl', () => ({
resolvePlaybackUrl: resolvePlaybackUrlMock,
}));
vi.mock('@/api/subsonic', () => ({
savePlayQueue: vi.fn(async () => undefined),
getPlayQueue: vi.fn(async () => ({ songs: [], current: undefined, position: 0 })),
@@ -164,6 +173,7 @@ describe('previewStore — startPreview', () => {
resetAuthStore();
resetOrbitStore();
resetPlayerStore();
resolvePlaybackUrlMock.mockClear();
onInvoke('audio_preview_play', () => undefined);
onInvoke('audio_preview_stop', () => undefined);
onInvoke('audio_preview_set_volume', () => undefined);
@@ -200,6 +210,28 @@ describe('previewStore — startPreview', () => {
expect(state.duration).toBe(30);
});
it('resolves stream URL on clusterBrowseServerId member, not active server', async () => {
useAuthStore.setState({
servers: [
{ id: 'a', name: 'A', url: 'http://a.test', username: 'u', password: 'p' },
{ id: 'b', name: 'B', url: 'http://b.test', username: 'u', password: 'p' },
],
activeServerId: 'a',
});
await usePreviewStore.getState().startPreview({
...song('track-x'),
clusterBrowseServerId: 'b',
}, 'albums');
expect(resolvePlaybackUrlMock).toHaveBeenCalledWith('track-x', 'b');
const call = invokeMock.mock.calls.find(c => c[0] === 'audio_preview_play');
expect(call?.[1]).toMatchObject({
url: 'https://mock/stream/b/track-x',
});
expect(usePreviewStore.getState().previewingTrack?.clusterBrowseServerId).toBe('b');
});
it('starts at 0 when the track is too short to need a mid-track seek', async () => {
// duration <= previewDuration * 1.5 → start at 0.
await usePreviewStore.getState().startPreview({ ...song(), duration: 30 }, 'suggestions');
@@ -277,7 +309,7 @@ describe('previewStore — startPreview', () => {
throw new Error('engine offline');
});
await expect(usePreviewStore.getState().startPreview(song('song-2'), 'suggestions')).rejects.toThrow(/engine offline/);
await usePreviewStore.getState().startPreview(song('song-2'), 'suggestions');
// Only rolls back when the rolled-back id is still the optimistic one.
const state = usePreviewStore.getState();
+48 -5
View File
@@ -1,10 +1,12 @@
import { buildStreamUrl } from '../api/subsonicStreamUrl';
import type { SubsonicSong } from '../api/subsonicTypes';
import type { TrackPreviewLocation } from './authStoreTypes';
import { create } from 'zustand';
import { invoke } from '@tauri-apps/api/core';
import { usePlayerStore } from './playerStore';
import { useAuthStore } from './authStore';
import { isOrbitPlaybackSyncActive } from '../utils/orbit';
import { resolveStreamServerIdForTrack } from '../utils/playback/playbackServer';
import { resolvePlaybackUrl } from '../utils/playback/resolvePlaybackUrl';
/** Minimal track info needed to surface the preview in the player bar UI. */
export interface PreviewingTrack {
@@ -12,6 +14,32 @@ export interface PreviewingTrack {
title: string;
artist: string;
coverArt?: string;
clusterBrowseServerId?: string;
}
export interface PreviewSongInput {
id: string;
title: string;
artist: string;
coverArt?: string;
duration?: number;
suffix?: string;
clusterBrowseServerId?: string;
}
/** Map a browse/playlist song row into preview input (keeps cluster member id). */
export function previewInputFromSong(
song: Pick<SubsonicSong, 'id' | 'title' | 'artist' | 'coverArt' | 'duration' | 'suffix' | 'clusterBrowseServerId'>,
): PreviewSongInput {
return {
id: song.id,
title: song.title,
artist: song.artist,
coverArt: song.coverArt,
duration: song.duration,
suffix: song.suffix,
clusterBrowseServerId: song.clusterBrowseServerId,
};
}
interface PreviewState {
@@ -33,7 +61,7 @@ interface PreviewState {
*/
audioStarted: boolean;
startPreview: (song: { id: string; title: string; artist: string; coverArt?: string; duration?: number }, location: TrackPreviewLocation) => Promise<void>;
startPreview: (song: PreviewSongInput, location: TrackPreviewLocation) => Promise<void>;
stopPreview: () => Promise<void>;
/** Internal — called from the TauriEventBridge on `audio:preview-start`. */
@@ -65,6 +93,14 @@ export function computePreviewVolume(): number {
return Math.max(0, Math.min(1, volume));
}
/** Cluster-aware stream URL — same member resolution as main playback. */
export function buildPreviewStreamUrl(song: Pick<PreviewSongInput, 'id' | 'clusterBrowseServerId'>): string {
const streamServerId = resolveStreamServerIdForTrack(
song.clusterBrowseServerId ? { clusterBrowseServerId: song.clusterBrowseServerId } : null,
);
return resolvePlaybackUrl(song.id, streamServerId);
}
export const usePreviewStore = create<PreviewState>((set, get) => ({
previewingId: null,
previewingTrack: null,
@@ -92,7 +128,7 @@ export const usePreviewStore = create<PreviewState>((set, get) => ({
const previewDuration = auth.trackPreviewDurationSec;
const startRatio = auth.trackPreviewStartRatio;
const url = buildStreamUrl(song.id);
const url = buildPreviewStreamUrl(song);
const trackDuration = Math.max(song.duration ?? 0, 0);
const startSec = trackDuration > previewDuration * 1.5
? trackDuration * startRatio
@@ -100,7 +136,13 @@ export const usePreviewStore = create<PreviewState>((set, get) => ({
set({
previewingId: song.id,
previewingTrack: { id: song.id, title: song.title, artist: song.artist, coverArt: song.coverArt },
previewingTrack: {
id: song.id,
title: song.title,
artist: song.artist,
coverArt: song.coverArt,
clusterBrowseServerId: song.clusterBrowseServerId,
},
elapsed: 0,
duration: previewDuration,
audioStarted: false,
@@ -113,13 +155,14 @@ export const usePreviewStore = create<PreviewState>((set, get) => ({
startSec,
durationSec: previewDuration,
volume: computePreviewVolume(),
formatSuffix: song.suffix ?? null,
});
} catch (e) {
// Roll back optimistic state on failure.
if (get().previewingId === song.id) {
set({ previewingId: null, previewingTrack: null, elapsed: 0, audioStarted: false });
}
throw e;
console.error('Preview playback failed', e);
}
},