diff --git a/src/components/settings/AudioTab.tsx b/src/components/settings/AudioTab.tsx index 2e8590e8..4c5989cd 100644 --- a/src/components/settings/AudioTab.tsx +++ b/src/components/settings/AudioTab.tsx @@ -1,27 +1,27 @@ -import { useCallback, useEffect, useMemo, useState } from 'react'; +import { useMemo } from 'react'; import { useTranslation } from 'react-i18next'; -import { invoke } from '@tauri-apps/api/core'; -import { listen } from '@tauri-apps/api/event'; -import { AudioLines, Music2, Play, RotateCcw, Sliders, Waves } from 'lucide-react'; +import { Music2, Sliders, Waves } from 'lucide-react'; import { useAuthStore } from '../../store/authStore'; -import { DEFAULT_LOUDNESS_PRE_ANALYSIS_ATTENUATION_DB, TRACK_PREVIEW_LOCATIONS } from '../../store/authStoreDefaults'; -import type { TrackPreviewLocation } from '../../store/authStoreTypes'; -import CustomSelect from '../CustomSelect'; import Equalizer from '../Equalizer'; import SettingsSubSection from '../SettingsSubSection'; -import { LoudnessLufsButtonGroup } from './LoudnessLufsButtonGroup'; -import { IS_MACOS } from '../../utils/platform'; -import { buildAudioDeviceSelectOptions, sortAudioDeviceIds } from '../../utils/audioDeviceLabels'; import { effectiveLoudnessPreAnalysisAttenuationDb } from '../../utils/loudnessPreAnalysisSlider'; -import { showToast } from '../../utils/toast'; +import { useAudioDevicesProbe } from '../../hooks/useAudioDevicesProbe'; +import { AudioOutputDeviceSection } from './audio/AudioOutputDeviceSection'; +import { NormalizationBlock } from './audio/NormalizationBlock'; +import { PlaybackBehaviorBlock } from './audio/PlaybackBehaviorBlock'; +import { TrackPreviewsSection } from './audio/TrackPreviewsSection'; export function AudioTab() { const { t } = useTranslation(); const auth = useAuthStore(); - const [audioDevices, setAudioDevices] = useState([]); - const [osDefaultAudioDeviceId, setOsDefaultAudioDeviceId] = useState(null); - const [deviceSwitching, setDeviceSwitching] = useState(false); - const [devicesLoading, setDevicesLoading] = useState(false); + const { + audioDevices, + osDefaultAudioDeviceId, + deviceSwitching, + devicesLoading, + setDeviceSwitching, + refreshAudioDevices, + } = useAudioDevicesProbe(t); const preAnalysisEffectiveDb = useMemo( () => effectiveLoudnessPreAnalysisAttenuationDb( @@ -31,120 +31,17 @@ export function AudioTab() { [auth.loudnessPreAnalysisAttenuationDb, auth.loudnessTargetLufs], ); - const refreshAudioDevices = useCallback((opts?: { silent?: boolean }) => { - const silent = !!opts?.silent; - if (!silent) setDevicesLoading(true); - const listP = invoke('audio_list_devices').catch((e) => { - console.error(e); - showToast(t('settings.audioOutputDeviceListError'), 5000, 'error'); - return [] as string[]; - }); - const defP = invoke('audio_default_output_device_name').catch(() => null); - Promise.all([listP, defP]) - .then(async ([devices, osDefault]) => { - let canon: string | null = null; - try { - canon = await invoke('audio_canonicalize_selected_device'); - if (canon) useAuthStore.getState().setAudioOutputDevice(canon); - } catch { - /* ignore */ - } - const finalList = canon - ? await invoke('audio_list_devices').catch(() => devices) - : devices; - const defId = osDefault ?? null; - setAudioDevices(sortAudioDeviceIds(finalList, defId)); - setOsDefaultAudioDeviceId(defId); - }) - .finally(() => { - if (!silent) setDevicesLoading(false); - }); - }, [t]); - - // Load available audio output devices on mount. - // Skipped on macOS — the stream is pinned to the system default (see - // audioOutputDeviceMacNotice) so there is no picker to populate. - useEffect(() => { - if (IS_MACOS) return; - refreshAudioDevices(); - }, [refreshAudioDevices]); - - // Keep device list + "current system output" mark in sync when the backend reopens the stream. - useEffect(() => { - if (IS_MACOS) return; - let cancelled = false; - const unlisteners: Array<() => void> = []; - (async () => { - for (const ev of ['audio:device-changed', 'audio:device-reset'] as const) { - const u = await listen(ev, () => { - if (!cancelled) refreshAudioDevices({ silent: true }); - }); - if (cancelled) { - u(); - return; - } - unlisteners.push(u); - } - })(); - return () => { - cancelled = true; - for (const u of unlisteners) u(); - }; - }, [refreshAudioDevices]); - return ( <> - {/* Audio Output Device */} - } - > -
- {IS_MACOS ? ( -
- {t('settings.audioOutputDeviceMacNotice')} -
- ) : ( - <> -
- {t('settings.audioOutputDeviceDesc')} -
-
- { - const device = val || null; - setDeviceSwitching(true); - try { - await invoke('audio_set_device', { deviceName: device }); - auth.setAudioOutputDevice(device); - } catch { /* device open failed — don't persist */ } - setDeviceSwitching(false); - }} - options={buildAudioDeviceSelectOptions( - audioDevices, - t('settings.audioOutputDeviceDefault'), - osDefaultAudioDeviceId, - t('settings.audioOutputDeviceOsDefaultNow'), - auth.audioOutputDevice, - t('settings.audioOutputDeviceNotInCurrentList'), - )} - /> - -
- - )} -
-
+ {/* Native Hi-Res Playback */} } >
- {/* Normalization */} -
-
{t('settings.normalization', { defaultValue: 'Normalization' })}
-
- {t('settings.normalizationDesc')} -
-
-
- - - -
- {auth.normalizationEngine === 'replaygain' && ( -
-
-
- {t('settings.replayGainMode')} -
- - - -
-
- {auth.replayGainMode === 'auto' && ( -
{t('settings.replayGainAutoDesc')}
- )} -
-
-
- {t('settings.replayGainPreGain')} - auth.setReplayGainPreGainDb(Number(e.target.value))} - /> - - {auth.replayGainPreGainDb > 0 ? `+${auth.replayGainPreGainDb}` : auth.replayGainPreGainDb} dB - -
-
{t('settings.replayGainPreGainDesc')}
-
-
-
- {t('settings.replayGainFallback')} - auth.setReplayGainFallbackDb(Number(e.target.value))} - /> - - {auth.replayGainFallbackDb > 0 ? `+${auth.replayGainFallbackDb}` : auth.replayGainFallbackDb} dB - -
-
{t('settings.replayGainFallbackDesc')}
-
-
- )} - {auth.normalizationEngine === 'loudness' && ( -
-
-
- {t('settings.loudnessTargetLufs')} - -
-
{t('settings.loudnessTargetLufsDesc')}
-
-
-
- {t('settings.loudnessPreAnalysisAttenuation')} - auth.setLoudnessPreAnalysisAttenuationDb(Number(e.target.value))} - /> - - {preAnalysisEffectiveDb} dB - - -
-
- {t('settings.loudnessPreAnalysisAttenuationDesc')}{' '} - {t('settings.loudnessPreAnalysisAttenuationRef', { - ref: auth.loudnessPreAnalysisAttenuationDb, - eff: preAnalysisEffectiveDb, - tgt: auth.loudnessTargetLufs, - })} -
-
-
{t('settings.loudnessFirstPlayNote')}
-
- )} +
- {/* Crossfade */} -
-
-
- {t('settings.crossfade')} -
-
- {auth.gaplessEnabled ? t('settings.notWithGapless') : t('settings.crossfadeDesc')} -
-
- -
- {auth.crossfadeEnabled && !auth.gaplessEnabled && ( -
- auth.setCrossfadeSecs(parseFloat(e.target.value))} - style={{ flex: 1, minWidth: 80, maxWidth: 200 }} - id="crossfade-secs-slider" - /> - - {t('settings.crossfadeSecs', { n: auth.crossfadeSecs.toFixed(1) })} - -
- )} - -
- - {/* Gapless */} -
-
-
- {t('settings.gapless')} -
-
- {auth.crossfadeEnabled ? t('settings.notWithCrossfade') : t('settings.gaplessDesc')} -
-
- -
- -
-
-
- {t('settings.preservePlayNextOrder')} -
-
- {t('settings.preservePlayNextOrderDesc')} -
-
- -
+
- } - > -
-
-
-
- {t('settings.trackPreviewsToggle')} -
-
- {t('settings.trackPreviewsDesc')} -
-
- -
- - {auth.trackPreviewsEnabled && ( - <> -
-
-
- {t('settings.trackPreviewLocationsTitle')} -
-
- {t('settings.trackPreviewLocationsDesc')} -
-
- {TRACK_PREVIEW_LOCATIONS.map((loc: TrackPreviewLocation) => ( -
-
- {t(`settings.trackPreviewLocation_${loc}`)} -
- -
- ))} -
-
- -
-
-
- {t('settings.trackPreviewStart')} -
-
- {t('settings.trackPreviewStartDesc')} -
-
- auth.setTrackPreviewStartRatio(parseFloat(e.target.value))} - style={{ flex: 1, minWidth: 80, maxWidth: 240 }} - aria-label={t('settings.trackPreviewStart')} - /> - - {Math.round(auth.trackPreviewStartRatio * 100)}% - -
-
- -
-
-
- {t('settings.trackPreviewDuration')} -
-
- {t('settings.trackPreviewDurationDesc')} -
-
- auth.setTrackPreviewDurationSec(parseInt(e.target.value, 10))} - style={{ flex: 1, minWidth: 80, maxWidth: 240 }} - aria-label={t('settings.trackPreviewDuration')} - /> - - {t('settings.trackPreviewDurationSecs', { n: auth.trackPreviewDurationSec })} - -
-
- - )} -
- + ); } diff --git a/src/components/settings/audio/AudioOutputDeviceSection.tsx b/src/components/settings/audio/AudioOutputDeviceSection.tsx new file mode 100644 index 00000000..eacc7771 --- /dev/null +++ b/src/components/settings/audio/AudioOutputDeviceSection.tsx @@ -0,0 +1,92 @@ +import React from 'react'; +import { invoke } from '@tauri-apps/api/core'; +import { AudioLines, RotateCcw } from 'lucide-react'; +import type { TFunction } from 'i18next'; +import CustomSelect from '../../CustomSelect'; +import SettingsSubSection from '../../SettingsSubSection'; +import { useAuthStore } from '../../../store/authStore'; +import { IS_MACOS } from '../../../utils/platform'; +import { buildAudioDeviceSelectOptions } from '../../../utils/audioDeviceLabels'; + +interface Props { + audioDevices: string[]; + osDefaultAudioDeviceId: string | null; + deviceSwitching: boolean; + devicesLoading: boolean; + setDeviceSwitching: (v: boolean) => void; + refreshAudioDevices: (opts?: { silent?: boolean }) => void; + t: TFunction; +} + +/** + * Audio output device picker. macOS is hard-pinned to the system default, + * so the picker collapses to a notice on that platform. + * + * The device switch is best-effort: if `audio_set_device` rejects (e.g. + * device disappeared) we leave the previous selection in the store. + */ +export function AudioOutputDeviceSection({ + audioDevices, + osDefaultAudioDeviceId, + deviceSwitching, + devicesLoading, + setDeviceSwitching, + refreshAudioDevices, + t, +}: Props) { + const audioOutputDevice = useAuthStore(s => s.audioOutputDevice); + const setAudioOutputDevice = useAuthStore(s => s.setAudioOutputDevice); + + return ( + } + > +
+ {IS_MACOS ? ( +
+ {t('settings.audioOutputDeviceMacNotice')} +
+ ) : ( + <> +
+ {t('settings.audioOutputDeviceDesc')} +
+
+ { + const device = val || null; + setDeviceSwitching(true); + try { + await invoke('audio_set_device', { deviceName: device }); + setAudioOutputDevice(device); + } catch { /* device open failed — don't persist */ } + setDeviceSwitching(false); + }} + options={buildAudioDeviceSelectOptions( + audioDevices, + t('settings.audioOutputDeviceDefault'), + osDefaultAudioDeviceId, + t('settings.audioOutputDeviceOsDefaultNow'), + audioOutputDevice, + t('settings.audioOutputDeviceNotInCurrentList'), + )} + /> + +
+ + )} +
+
+ ); +} diff --git a/src/components/settings/audio/NormalizationBlock.tsx b/src/components/settings/audio/NormalizationBlock.tsx new file mode 100644 index 00000000..41a42246 --- /dev/null +++ b/src/components/settings/audio/NormalizationBlock.tsx @@ -0,0 +1,185 @@ +import React from 'react'; +import { RotateCcw } from 'lucide-react'; +import type { TFunction } from 'i18next'; +import { useAuthStore } from '../../../store/authStore'; +import { DEFAULT_LOUDNESS_PRE_ANALYSIS_ATTENUATION_DB } from '../../../store/authStoreDefaults'; +import { LoudnessLufsButtonGroup } from '../LoudnessLufsButtonGroup'; + +interface Props { + preAnalysisEffectiveDb: number; + t: TFunction; +} + +/** + * Normalization engine picker (Off / ReplayGain / LUFS) plus the + * engine-specific configuration blocks. + * + * - ReplayGain → mode (auto/track/album), pre-gain slider, fallback gain. + * `auto` mode toggles between track/album based on what the playlist + * provides; the help line explains that. + * - Loudness → target LUFS button group + pre-analysis attenuation slider + * with reset-to-default. The effective dB readout reflects how much + * headroom is being applied for the current target. + * + * Switching engines clears the other engine's enabled flag so only one + * can be live at a time. + */ +export function NormalizationBlock({ preAnalysisEffectiveDb, t }: Props) { + const auth = useAuthStore(); + + return ( + <> +
+
{t('settings.normalization', { defaultValue: 'Normalization' })}
+
+ {t('settings.normalizationDesc')} +
+
+
+ + + +
+ {auth.normalizationEngine === 'replaygain' && ( +
+
+
+ {t('settings.replayGainMode')} +
+ + + +
+
+ {auth.replayGainMode === 'auto' && ( +
{t('settings.replayGainAutoDesc')}
+ )} +
+
+
+ {t('settings.replayGainPreGain')} + auth.setReplayGainPreGainDb(Number(e.target.value))} + /> + + {auth.replayGainPreGainDb > 0 ? `+${auth.replayGainPreGainDb}` : auth.replayGainPreGainDb} dB + +
+
{t('settings.replayGainPreGainDesc')}
+
+
+
+ {t('settings.replayGainFallback')} + auth.setReplayGainFallbackDb(Number(e.target.value))} + /> + + {auth.replayGainFallbackDb > 0 ? `+${auth.replayGainFallbackDb}` : auth.replayGainFallbackDb} dB + +
+
{t('settings.replayGainFallbackDesc')}
+
+
+ )} + {auth.normalizationEngine === 'loudness' && ( +
+
+
+ {t('settings.loudnessTargetLufs')} + +
+
{t('settings.loudnessTargetLufsDesc')}
+
+
+
+ {t('settings.loudnessPreAnalysisAttenuation')} + auth.setLoudnessPreAnalysisAttenuationDb(Number(e.target.value))} + /> + + {preAnalysisEffectiveDb} dB + + +
+
+ {t('settings.loudnessPreAnalysisAttenuationDesc')}{' '} + {t('settings.loudnessPreAnalysisAttenuationRef', { + ref: auth.loudnessPreAnalysisAttenuationDb, + eff: preAnalysisEffectiveDb, + tgt: auth.loudnessTargetLufs, + })} +
+
+
{t('settings.loudnessFirstPlayNote')}
+
+ )} + + ); +} diff --git a/src/components/settings/audio/PlaybackBehaviorBlock.tsx b/src/components/settings/audio/PlaybackBehaviorBlock.tsx new file mode 100644 index 00000000..9d0edb43 --- /dev/null +++ b/src/components/settings/audio/PlaybackBehaviorBlock.tsx @@ -0,0 +1,92 @@ +import React from 'react'; +import type { TFunction } from 'i18next'; +import { useAuthStore } from '../../../store/authStore'; + +interface Props { + t: TFunction; +} + +/** + * Crossfade ↔ Gapless are mutually exclusive — enabling one forces the + * other off (`setGaplessEnabled(false)` / `setCrossfadeEnabled(false)` + * on the toggle handlers) and the inactive row dims via opacity + + * pointerEvents:none. The crossfade-seconds slider only renders while + * crossfade is the active mode. + * + * The `preservePlayNextOrder` toggle is independent of both and pinned + * to the bottom of the block. + */ +export function PlaybackBehaviorBlock({ t }: Props) { + const auth = useAuthStore(); + + return ( + <> +
+
+
+ {t('settings.crossfade')} +
+
+ {auth.gaplessEnabled ? t('settings.notWithGapless') : t('settings.crossfadeDesc')} +
+
+ +
+ {auth.crossfadeEnabled && !auth.gaplessEnabled && ( +
+ auth.setCrossfadeSecs(parseFloat(e.target.value))} + style={{ flex: 1, minWidth: 80, maxWidth: 200 }} + id="crossfade-secs-slider" + /> + + {t('settings.crossfadeSecs', { n: auth.crossfadeSecs.toFixed(1) })} + +
+ )} + +
+ +
+
+
+ {t('settings.gapless')} +
+
+ {auth.crossfadeEnabled ? t('settings.notWithCrossfade') : t('settings.gaplessDesc')} +
+
+ +
+ +
+
+
+ {t('settings.preservePlayNextOrder')} +
+
+ {t('settings.preservePlayNextOrderDesc')} +
+
+ +
+ + ); +} diff --git a/src/components/settings/audio/TrackPreviewsSection.tsx b/src/components/settings/audio/TrackPreviewsSection.tsx new file mode 100644 index 00000000..4d407df2 --- /dev/null +++ b/src/components/settings/audio/TrackPreviewsSection.tsx @@ -0,0 +1,129 @@ +import React from 'react'; +import { Play } from 'lucide-react'; +import type { TFunction } from 'i18next'; +import { useAuthStore } from '../../../store/authStore'; +import { TRACK_PREVIEW_LOCATIONS } from '../../../store/authStoreDefaults'; +import type { TrackPreviewLocation } from '../../../store/authStoreTypes'; +import SettingsSubSection from '../../SettingsSubSection'; + +interface Props { + t: TFunction; +} + +/** + * Track previews subsection: master toggle on top, then (when enabled) + * a per-location toggle grid, a "start at %" slider, and a duration + * slider. Locations come from `TRACK_PREVIEW_LOCATIONS` so adding a new + * surface (Search, Now Playing suggestions, …) only needs a single + * source-of-truth update. + */ +export function TrackPreviewsSection({ t }: Props) { + const auth = useAuthStore(); + + return ( + } + > +
+
+
+
+ {t('settings.trackPreviewsToggle')} +
+
+ {t('settings.trackPreviewsDesc')} +
+
+ +
+ + {auth.trackPreviewsEnabled && ( + <> +
+
+
+ {t('settings.trackPreviewLocationsTitle')} +
+
+ {t('settings.trackPreviewLocationsDesc')} +
+
+ {TRACK_PREVIEW_LOCATIONS.map((loc: TrackPreviewLocation) => ( +
+
+ {t(`settings.trackPreviewLocation_${loc}`)} +
+ +
+ ))} +
+
+ +
+
+
+ {t('settings.trackPreviewStart')} +
+
+ {t('settings.trackPreviewStartDesc')} +
+
+ auth.setTrackPreviewStartRatio(parseFloat(e.target.value))} + style={{ flex: 1, minWidth: 80, maxWidth: 240 }} + aria-label={t('settings.trackPreviewStart')} + /> + + {Math.round(auth.trackPreviewStartRatio * 100)}% + +
+
+ +
+
+
+ {t('settings.trackPreviewDuration')} +
+
+ {t('settings.trackPreviewDurationDesc')} +
+
+ auth.setTrackPreviewDurationSec(parseInt(e.target.value, 10))} + style={{ flex: 1, minWidth: 80, maxWidth: 240 }} + aria-label={t('settings.trackPreviewDuration')} + /> + + {t('settings.trackPreviewDurationSecs', { n: auth.trackPreviewDurationSec })} + +
+
+ + )} +
+ + ); +} diff --git a/src/hooks/useAudioDevicesProbe.ts b/src/hooks/useAudioDevicesProbe.ts new file mode 100644 index 00000000..fcaaff64 --- /dev/null +++ b/src/hooks/useAudioDevicesProbe.ts @@ -0,0 +1,100 @@ +import { useCallback, useEffect, useState } from 'react'; +import { invoke } from '@tauri-apps/api/core'; +import { listen } from '@tauri-apps/api/event'; +import type { TFunction } from 'i18next'; +import { useAuthStore } from '../store/authStore'; +import { IS_MACOS } from '../utils/platform'; +import { sortAudioDeviceIds } from '../utils/audioDeviceLabels'; +import { showToast } from '../utils/toast'; + +interface UseAudioDevicesProbeResult { + audioDevices: string[]; + osDefaultAudioDeviceId: string | null; + deviceSwitching: boolean; + devicesLoading: boolean; + setDeviceSwitching: (v: boolean) => void; + refreshAudioDevices: (opts?: { silent?: boolean }) => void; +} + +/** + * Drive the audio-output-device picker in the audio settings tab. Calls + * the Rust side to list devices + the current OS default, canonicalises + * the persisted selection (filenames may have shifted between runs), and + * re-runs whenever the backend reopens the stream + * (`audio:device-changed` / `audio:device-reset`). + * + * macOS short-circuits — the audio stream is pinned to the system default + * there (see `audioOutputDeviceMacNotice`) and the picker UI is hidden. + */ +export function useAudioDevicesProbe(t: TFunction): UseAudioDevicesProbeResult { + const [audioDevices, setAudioDevices] = useState([]); + const [osDefaultAudioDeviceId, setOsDefaultAudioDeviceId] = useState(null); + const [deviceSwitching, setDeviceSwitching] = useState(false); + const [devicesLoading, setDevicesLoading] = useState(false); + + const refreshAudioDevices = useCallback((opts?: { silent?: boolean }) => { + const silent = !!opts?.silent; + if (!silent) setDevicesLoading(true); + const listP = invoke('audio_list_devices').catch((e) => { + console.error(e); + showToast(t('settings.audioOutputDeviceListError'), 5000, 'error'); + return [] as string[]; + }); + const defP = invoke('audio_default_output_device_name').catch(() => null); + Promise.all([listP, defP]) + .then(async ([devices, osDefault]) => { + let canon: string | null = null; + try { + canon = await invoke('audio_canonicalize_selected_device'); + if (canon) useAuthStore.getState().setAudioOutputDevice(canon); + } catch { + /* ignore */ + } + const finalList = canon + ? await invoke('audio_list_devices').catch(() => devices) + : devices; + const defId = osDefault ?? null; + setAudioDevices(sortAudioDeviceIds(finalList, defId)); + setOsDefaultAudioDeviceId(defId); + }) + .finally(() => { + if (!silent) setDevicesLoading(false); + }); + }, [t]); + + useEffect(() => { + if (IS_MACOS) return; + refreshAudioDevices(); + }, [refreshAudioDevices]); + + useEffect(() => { + if (IS_MACOS) return; + let cancelled = false; + const unlisteners: Array<() => void> = []; + (async () => { + for (const ev of ['audio:device-changed', 'audio:device-reset'] as const) { + const u = await listen(ev, () => { + if (!cancelled) refreshAudioDevices({ silent: true }); + }); + if (cancelled) { + u(); + return; + } + unlisteners.push(u); + } + })(); + return () => { + cancelled = true; + for (const u of unlisteners) u(); + }; + }, [refreshAudioDevices]); + + return { + audioDevices, + osDefaultAudioDeviceId, + deviceSwitching, + devicesLoading, + setDeviceSwitching, + refreshAudioDevices, + }; +}