feat: per-user volume leveling preference, synced across devices (M464 #4998)
release / govulncheck (push) Successful in 22s
release / go (push) Successful in 1m17s
release / web (push) Failing after 1m5s
release / android (push) Failing after 1m51s
release / Attach APK to the Release (tag releases only) (push) Canceled after 0s
release / Build + push container image (push) Canceled after 0s
release / Verify release artifacts (tag releases only) (push) Canceled after 0s
release / integration (push) Canceled after 4m12s
release / Build signed APK (releases and dev) (push) Canceled after 3m21s

Mode (off, auto, track, album), target (-18, -16, -14 LUFS) and boost
(within headroom, or fully with a limiter), stored per user on the server
so the web player, the Android app and casts apply the same one.

- Server: user_normalization_prefs (migration 0067), GET/PUT
  /api/me/normalization; a whole-body PUT, validated, last write wins.
- Web: Settings > Playback > Volume leveling. Saves at once, restores the
  old choice if the save fails, and caches the value for the player.
- Android: Settings card. The device keeps a copy for offline playback
  (Room v9 with an explicit migration, so the upgrade wipes nothing).
  Writes are offline-first: shown at once, PUT best effort, queued on
  failure (NORMALIZATION_SET, collapsed to the newest). A refresh never
  overwrites a change still queued.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
2026-10-06 14:29:40 -04:00
co-authored by Claude Opus 5.5
parent e3aa8629d3
commit af36b2f24a
34 changed files with 1225 additions and 5 deletions
+42
View File
@@ -0,0 +1,42 @@
import { api } from './client';
// Loudness normalization preference (M464 #4998). One per user, stored on
// the server so the web player, the Android app and casts agree.
export type NormalizationMode = 'off' | 'auto' | 'track' | 'album';
export type NormalizationTarget = -18 | -16 | -14;
export type NormalizationBoost = 'headroom' | 'limiter';
export type NormalizationPrefs = {
mode: NormalizationMode;
target_lufs: NormalizationTarget;
boost: NormalizationBoost;
};
// Must match library.DefaultNormalizationPrefs on the server.
export const DEFAULT_NORMALIZATION: NormalizationPrefs = {
mode: 'auto',
target_lufs: -18,
boost: 'headroom'
};
export const NORMALIZATION_MODES: NormalizationMode[] = ['off', 'auto', 'track', 'album'];
export const NORMALIZATION_TARGETS: NormalizationTarget[] = [-18, -16, -14];
export function isNormalizationPrefs(v: unknown): v is NormalizationPrefs {
if (typeof v !== 'object' || v === null) return false;
const p = v as Record<string, unknown>;
return (
NORMALIZATION_MODES.includes(p.mode as NormalizationMode) &&
NORMALIZATION_TARGETS.includes(p.target_lufs as NormalizationTarget) &&
(p.boost === 'headroom' || p.boost === 'limiter')
);
}
export function getNormalization(): Promise<NormalizationPrefs> {
return api.get<NormalizationPrefs>('/api/me/normalization');
}
// The whole preference is sent every time; the server keeps the last write.
export function putNormalization(p: NormalizationPrefs): Promise<NormalizationPrefs> {
return api.put<NormalizationPrefs>('/api/me/normalization', p);
}
@@ -0,0 +1,104 @@
<script lang="ts">
import { onMount } from 'svelte';
import {
NORMALIZATION_MODES,
NORMALIZATION_TARGETS,
type NormalizationPrefs
} from '$lib/api/normalization';
import {
normalization,
loadNormalization,
setNormalization
} from '$lib/stores/normalization.svelte';
import { pushToast } from '$lib/stores/toast.svelte';
// Volume leveling (M464 #4998). The choice is the user's, stored on the
// server, so it follows them to the Android app and to casts.
onMount(() => {
void loadNormalization();
});
const modeLabels: Record<string, string> = {
off: 'Off',
auto: 'Auto',
track: 'Track',
album: 'Album'
};
const modeHints: Record<string, string> = {
off: 'Tracks play at their mastered volume.',
auto: 'Album gain for whole albums in order, track gain otherwise.',
track: 'Every track at the same loudness.',
album: 'Albums keep their own quiet and loud tracks.'
};
async function change(patch: Partial<NormalizationPrefs>): Promise<void> {
try {
await setNormalization({ ...normalization.value, ...patch });
} catch {
pushToast('Could not save volume leveling.', 'error');
}
}
const pill = (on: boolean) =>
`flex cursor-pointer items-center rounded border border-border px-3 py-1.5 text-sm ${
on ? 'bg-action-secondary text-action-fg' : 'text-text-primary hover:bg-surface-hover'
}`;
</script>
<div class="space-y-3">
<fieldset class="space-y-2">
<legend class="block text-sm text-text-secondary">Volume leveling</legend>
<div class="flex flex-wrap gap-2">
{#each NORMALIZATION_MODES as m (m)}
<label class={pill(normalization.value.mode === m)}>
<input
type="radio"
name="normalization-mode"
value={m}
checked={normalization.value.mode === m}
onchange={() => change({ mode: m })}
class="sr-only"
/>
{modeLabels[m]}
</label>
{/each}
</div>
<p class="text-xs text-text-secondary">{modeHints[normalization.value.mode]}</p>
</fieldset>
{#if normalization.value.mode !== 'off'}
<fieldset class="space-y-2">
<legend class="block text-sm text-text-secondary">Target loudness</legend>
<div class="flex flex-wrap gap-2">
{#each NORMALIZATION_TARGETS as t (t)}
<label class={pill(normalization.value.target_lufs === t)}>
<input
type="radio"
name="normalization-target"
value={t}
checked={normalization.value.target_lufs === t}
onchange={() => change({ target_lufs: t })}
class="sr-only"
/>
<span class="tabular-nums">{t} LUFS</span>
</label>
{/each}
</div>
<p class="text-xs text-text-secondary">Higher is louder; −18 leaves the most headroom.</p>
</fieldset>
<label class="flex cursor-pointer items-center justify-between gap-3">
<span>
<span class="block text-sm text-text-primary">Boost quiet tracks fully</span>
<span class="block text-xs text-text-secondary">A limiter catches the peaks.</span>
</span>
<input
type="checkbox"
checked={normalization.value.boost === 'limiter'}
onchange={(e) =>
change({ boost: (e.currentTarget as HTMLInputElement).checked ? 'limiter' : 'headroom' })}
class="h-4 w-4 accent-accent"
/>
</label>
{/if}
</div>
@@ -0,0 +1,65 @@
import { afterEach, describe, expect, test, vi } from 'vitest';
import { render, screen, fireEvent, waitFor } from '@testing-library/svelte';
vi.mock('$lib/api/normalization', async (importOriginal) => ({
...(await importOriginal<typeof import('$lib/api/normalization')>()),
getNormalization: vi.fn(),
putNormalization: vi.fn()
}));
vi.mock('$lib/stores/toast.svelte', () => ({ pushToast: vi.fn() }));
import NormalizationSetting from './NormalizationSetting.svelte';
import { getNormalization, putNormalization } from '$lib/api/normalization';
import { normalization } from '$lib/stores/normalization.svelte';
import { pushToast } from '$lib/stores/toast.svelte';
afterEach(() => {
vi.clearAllMocks();
localStorage.clear();
});
describe('NormalizationSetting', () => {
test('shows the server value and saves the whole preference on a change', async () => {
vi.mocked(getNormalization).mockResolvedValue({ mode: 'track', target_lufs: -16, boost: 'headroom' });
vi.mocked(putNormalization).mockImplementation(async (p) => p);
render(NormalizationSetting);
await waitFor(() => expect(screen.getByRole('radio', { name: 'Track' })).toBeChecked());
expect(screen.getByRole('radio', { name: '-16 LUFS' })).toBeChecked();
await fireEvent.click(screen.getByRole('radio', { name: 'Album' }));
await waitFor(() =>
expect(putNormalization).toHaveBeenCalledWith({ mode: 'album', target_lufs: -16, boost: 'headroom' })
);
await fireEvent.click(screen.getByRole('checkbox', { name: /boost quiet tracks/i }));
await waitFor(() =>
expect(putNormalization).toHaveBeenLastCalledWith({ mode: 'album', target_lufs: -16, boost: 'limiter' })
);
// The last value seen is cached for the player's first track of a session.
expect(JSON.parse(localStorage.getItem('minstrel:normalization') ?? 'null')).toEqual({
mode: 'album',
target_lufs: -16,
boost: 'limiter'
});
});
test('a failed save puts the previous choice back and says so', async () => {
vi.mocked(getNormalization).mockResolvedValue({ mode: 'auto', target_lufs: -18, boost: 'headroom' });
vi.mocked(putNormalization).mockRejectedValue(new Error('offline'));
render(NormalizationSetting);
await waitFor(() => expect(screen.getByRole('radio', { name: 'Auto' })).toBeChecked());
await fireEvent.click(screen.getByRole('radio', { name: 'Off' }));
await waitFor(() => expect(pushToast).toHaveBeenCalledWith('Could not save volume leveling.', 'error'));
expect(normalization.value.mode).toBe('auto');
expect(screen.getByRole('radio', { name: 'Auto' })).toBeChecked();
});
test('off hides the target and boost controls', async () => {
vi.mocked(getNormalization).mockResolvedValue({ mode: 'off', target_lufs: -18, boost: 'headroom' });
render(NormalizationSetting);
await waitFor(() => expect(screen.getByRole('radio', { name: 'Off' })).toBeChecked());
expect(screen.queryByRole('radio', { name: '-18 LUFS' })).toBeNull();
expect(screen.queryByRole('checkbox')).toBeNull();
});
});
@@ -0,0 +1,66 @@
import * as storage from '$lib/util/safeLocalStorage';
import {
DEFAULT_NORMALIZATION,
getNormalization,
isNormalizationPrefs,
putNormalization,
type NormalizationPrefs
} from '$lib/api/normalization';
// The signed-in user's normalization preference. The server holds it; this
// keeps the last value seen in localStorage too, so the player levels the
// first track of a session before the fetch returns.
const STORAGE_KEY = 'minstrel:normalization';
function readCached(): NormalizationPrefs {
try {
const v: unknown = JSON.parse(storage.read(STORAGE_KEY) ?? 'null');
return isNormalizationPrefs(v) ? v : DEFAULT_NORMALIZATION;
} catch {
return DEFAULT_NORMALIZATION;
}
}
let _prefs = $state<NormalizationPrefs>(readCached());
// Bumped by every change made here. A load or a save that resolves after a
// newer change must not overwrite it.
let _generation = 0;
export const normalization = {
get value(): NormalizationPrefs {
return _prefs;
}
};
function commit(p: NormalizationPrefs): void {
_prefs = p;
storage.write(STORAGE_KEY, JSON.stringify(p));
}
/** Refreshes from the server; on failure the cached value stands. */
export async function loadNormalization(): Promise<void> {
const gen = _generation;
try {
const p = await getNormalization();
if (gen === _generation) commit(p);
} catch {
// Offline or signed out: keep what we had.
}
}
/**
* Applies [next] at once, then saves it. If the save fails the previous
* value is restored and the error rethrown for the caller to report.
*/
export async function setNormalization(next: NormalizationPrefs): Promise<void> {
const prev = _prefs;
const gen = ++_generation;
commit(next);
try {
const saved = await putNormalization(next);
if (gen === _generation) commit(saved);
} catch (err) {
if (gen === _generation) commit(prev);
throw err;
}
}
+3
View File
@@ -30,6 +30,7 @@
import MobileAppDownload from '$lib/components/MobileAppDownload.svelte';
import ServerVersion from '$lib/components/ServerVersion.svelte';
import ActiveSessions from '$lib/components/ActiveSessions.svelte';
import NormalizationSetting from '$lib/components/NormalizationSetting.svelte';
const queryClient = useQueryClient();
@@ -341,6 +342,8 @@
0 = off · most albums sound best at 0.
</p>
</div>
<NormalizationSetting />
</section>
<section class="space-y-4 rounded border border-border bg-surface p-4">
@@ -25,6 +25,16 @@ vi.mock('$lib/api/listenbrainz', () => {
};
});
// The Volume leveling setting loads on mount; keep it off the network.
vi.mock('$lib/api/normalization', async (importOriginal) => {
const mod = await importOriginal<typeof import('$lib/api/normalization')>();
return {
...mod,
getNormalization: vi.fn().mockResolvedValue(mod.DEFAULT_NORMALIZATION),
putNormalization: vi.fn()
};
});
vi.mock('$lib/api/metrics', () => ({
createRecommendationMetricsQuery: () => ({
subscribe: (run: (v: unknown) => void) => {
+10
View File
@@ -11,6 +11,16 @@ vi.mock('$lib/api/listenbrainz', () => ({
setListenBrainzEnabled: vi.fn()
}));
// The Volume leveling setting loads on mount; keep it off the network.
vi.mock('$lib/api/normalization', async (importOriginal) => {
const mod = await importOriginal<typeof import('$lib/api/normalization')>();
return {
...mod,
getNormalization: vi.fn().mockResolvedValue(mod.DEFAULT_NORMALIZATION),
putNormalization: vi.fn()
};
});
vi.mock('$lib/api/me', () => ({
updateProfile: vi.fn(),
changePassword: vi.fn(),