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
+2
View File
@@ -109,6 +109,8 @@ func Mount(r chi.Router, pool *pgxpool.Pool, logger *slog.Logger, events *playev
authed.Put("/me/password", h.handleChangePassword)
authed.Put("/me/profile", h.handleUpdateMyProfile)
authed.Put("/me/timezone", h.handlePutTimezone)
authed.Get("/me/normalization", h.handleGetMyNormalization)
authed.Put("/me/normalization", h.handlePutMyNormalization)
authed.Post("/me/api-token", h.handleRegenerateMyAPIToken)
authed.Get("/me/subsonic-password", h.handleGetMySubsonicPassword)
authed.Post("/me/subsonic-password", h.handleGenerateMySubsonicPassword)
+51
View File
@@ -0,0 +1,51 @@
package api
import (
"encoding/json"
"errors"
"net/http"
"git.fabledsword.com/bvandeusen/minstrel/internal/apierror"
"git.fabledsword.com/bvandeusen/minstrel/internal/db/dbq"
"git.fabledsword.com/bvandeusen/minstrel/internal/library"
)
// GET /api/me/normalization returns the caller's loudness-normalization
// preference, or the defaults when they have never set one (M464 #4998).
func (h *handlers) handleGetMyNormalization(w http.ResponseWriter, r *http.Request) {
caller, ok := requireUser(w, r)
if !ok {
return
}
p, err := library.LoadNormalizationPrefs(r.Context(), dbq.New(h.pool), caller.ID)
if err != nil {
writeErrWithLog(w, h.logger, "normalization: load", apierror.InternalMsg("lookup failed", err))
return
}
writeJSON(w, http.StatusOK, p)
}
// PUT /api/me/normalization replaces the caller's preference with the whole
// body. Every field is required, so a client replaying a queued change
// offline sends the full state it showed the user, and the last write wins.
func (h *handlers) handlePutMyNormalization(w http.ResponseWriter, r *http.Request) {
caller, ok := requireUser(w, r)
if !ok {
return
}
var body library.NormalizationPrefs
if err := json.NewDecoder(r.Body).Decode(&body); err != nil {
writeErr(w, apierror.BadRequest("bad_body", "invalid JSON body"))
return
}
p, err := library.SaveNormalizationPrefs(r.Context(), dbq.New(h.pool), caller.ID, body)
if errors.Is(err, library.ErrNormalizationPrefsInvalid) {
writeErr(w, apierror.BadRequest("invalid_normalization", err.Error()))
return
}
if err != nil {
writeErrWithLog(w, h.logger, "normalization: save", apierror.InternalMsg("save failed", err))
return
}
writeJSON(w, http.StatusOK, p)
}
+61
View File
@@ -0,0 +1,61 @@
package api
import (
"bytes"
"encoding/json"
"net/http"
"net/http/httptest"
"testing"
"github.com/go-chi/chi/v5"
"git.fabledsword.com/bvandeusen/minstrel/internal/library"
)
func TestMyNormalization_GetPut(t *testing.T) {
h, pool := testHandlers(t)
user := seedUser(t, pool, "norm1", "pw", false)
r := chi.NewRouter()
r.Get("/api/me/normalization", h.handleGetMyNormalization)
r.Put("/api/me/normalization", h.handlePutMyNormalization)
do := func(method, body string) (int, library.NormalizationPrefs) {
t.Helper()
req := withUser(httptest.NewRequest(method, "/api/me/normalization", bytes.NewBufferString(body)), user)
rec := httptest.NewRecorder()
r.ServeHTTP(rec, req)
var p library.NormalizationPrefs
if rec.Code == http.StatusOK {
if err := json.Unmarshal(rec.Body.Bytes(), &p); err != nil {
t.Fatalf("decode %s: %v", rec.Body.String(), err)
}
}
return rec.Code, p
}
if code, p := do(http.MethodGet, ""); code != http.StatusOK || p != library.DefaultNormalizationPrefs {
t.Fatalf("GET before any save = %d %+v, want 200 with the defaults", code, p)
}
want := library.NormalizationPrefs{Mode: "album", TargetLUFS: -16, Boost: "limiter"}
if code, p := do(http.MethodPut, `{"mode":"album","target_lufs":-16,"boost":"limiter"}`); code != http.StatusOK || p != want {
t.Fatalf("PUT = %d %+v, want 200 %+v", code, p, want)
}
if code, p := do(http.MethodGet, ""); code != http.StatusOK || p != want {
t.Errorf("GET after PUT = %d %+v, want %+v", code, p, want)
}
// Bad values and partial bodies are refused, and the stored prefs stand.
for _, body := range []string{
`{"mode":"loud","target_lufs":-16,"boost":"limiter"}`,
`{"mode":"album","target_lufs":-23,"boost":"limiter"}`,
`{"mode":"album","target_lufs":-16}`,
`not json`,
} {
if code, _ := do(http.MethodPut, body); code != http.StatusBadRequest {
t.Errorf("PUT %s = %d, want 400", body, code)
}
}
if _, p := do(http.MethodGet, ""); p != want {
t.Errorf("a refused PUT changed the prefs to %+v", p)
}
}
+8
View File
@@ -784,6 +784,14 @@ type UserInvite struct {
RedeemedBy pgtype.UUID
}
type UserNormalizationPref struct {
UserID pgtype.UUID
Mode string
TargetLufs int16
Boost string
UpdatedAt pgtype.Timestamptz
}
type YouMightLikeAlbum struct {
UserID pgtype.UUID
AlbumID pgtype.UUID
@@ -0,0 +1,81 @@
// Code generated by sqlc. DO NOT EDIT.
// versions:
// sqlc v1.31.1
// source: normalization_prefs.sql
package dbq
import (
"context"
"github.com/jackc/pgx/v5/pgtype"
)
const getNormalizationPrefs = `-- name: GetNormalizationPrefs :one
SELECT mode, target_lufs, boost, updated_at
FROM user_normalization_prefs
WHERE user_id = $1
`
type GetNormalizationPrefsRow struct {
Mode string
TargetLufs int16
Boost string
UpdatedAt pgtype.Timestamptz
}
func (q *Queries) GetNormalizationPrefs(ctx context.Context, userID pgtype.UUID) (GetNormalizationPrefsRow, error) {
row := q.db.QueryRow(ctx, getNormalizationPrefs, userID)
var i GetNormalizationPrefsRow
err := row.Scan(
&i.Mode,
&i.TargetLufs,
&i.Boost,
&i.UpdatedAt,
)
return i, err
}
const upsertNormalizationPrefs = `-- name: UpsertNormalizationPrefs :one
INSERT INTO user_normalization_prefs (user_id, mode, target_lufs, boost)
VALUES ($1, $2, $3, $4)
ON CONFLICT (user_id) DO UPDATE SET
mode = EXCLUDED.mode,
target_lufs = EXCLUDED.target_lufs,
boost = EXCLUDED.boost,
updated_at = now()
RETURNING mode, target_lufs, boost, updated_at
`
type UpsertNormalizationPrefsParams struct {
UserID pgtype.UUID
Mode string
TargetLufs int16
Boost string
}
type UpsertNormalizationPrefsRow struct {
Mode string
TargetLufs int16
Boost string
UpdatedAt pgtype.Timestamptz
}
// Whole-row write from either client; the CHECKs in migration 0067 back the
// handler's own validation.
func (q *Queries) UpsertNormalizationPrefs(ctx context.Context, arg UpsertNormalizationPrefsParams) (UpsertNormalizationPrefsRow, error) {
row := q.db.QueryRow(ctx, upsertNormalizationPrefs,
arg.UserID,
arg.Mode,
arg.TargetLufs,
arg.Boost,
)
var i UpsertNormalizationPrefsRow
err := row.Scan(
&i.Mode,
&i.TargetLufs,
&i.Boost,
&i.UpdatedAt,
)
return i, err
}
@@ -0,0 +1 @@
DROP TABLE IF EXISTS user_normalization_prefs;
@@ -0,0 +1,22 @@
-- Each user's loudness-normalization preference (M464 #4998). It is kept on
-- the server, not per device, so the web player, the Android app and the
-- leveled stream for UPnP/Sonos all apply the same one.
--
-- mode: off, auto (album gain while an album plays in order, otherwise
-- track gain), track or album.
-- target: the loudness tracks are leveled to, in LUFS.
-- boost: headroom raises quiet tracks only as far as their true peak
-- allows; limiter raises them all the way and limits the peaks.
--
-- No row means the defaults, which are the column defaults here and
-- library.DefaultNormalizationPrefs in Go (a test holds them equal).
CREATE TABLE user_normalization_prefs (
user_id uuid PRIMARY KEY REFERENCES users(id) ON DELETE CASCADE,
mode text NOT NULL DEFAULT 'auto'
CHECK (mode IN ('off', 'auto', 'track', 'album')),
target_lufs smallint NOT NULL DEFAULT -18
CHECK (target_lufs IN (-18, -16, -14)),
boost text NOT NULL DEFAULT 'headroom'
CHECK (boost IN ('headroom', 'limiter')),
updated_at timestamptz NOT NULL DEFAULT now()
);
@@ -0,0 +1,16 @@
-- name: GetNormalizationPrefs :one
SELECT mode, target_lufs, boost, updated_at
FROM user_normalization_prefs
WHERE user_id = $1;
-- name: UpsertNormalizationPrefs :one
-- Whole-row write from either client; the CHECKs in migration 0067 back the
-- handler's own validation.
INSERT INTO user_normalization_prefs (user_id, mode, target_lufs, boost)
VALUES (sqlc.arg(user_id), sqlc.arg(mode), sqlc.arg(target_lufs), sqlc.arg(boost))
ON CONFLICT (user_id) DO UPDATE SET
mode = EXCLUDED.mode,
target_lufs = EXCLUDED.target_lufs,
boost = EXCLUDED.boost,
updated_at = now()
RETURNING mode, target_lufs, boost, updated_at;
+4 -3
View File
@@ -90,9 +90,10 @@ var dataTables = []string{
"duplicate_group_members", // M400
"duplicate_groups",
"duplicate_sweeps",
"track_fingerprints", // M400
"track_loudness", // M464
"album_loudness", // M464
"track_fingerprints", // M400
"track_loudness", // M464
"album_loudness", // M464
"user_normalization_prefs", // M464
"tracks",
"albums",
"artists",
+84
View File
@@ -0,0 +1,84 @@
package library
import (
"context"
"errors"
"fmt"
"slices"
"github.com/jackc/pgx/v5"
"github.com/jackc/pgx/v5/pgtype"
"git.fabledsword.com/bvandeusen/minstrel/internal/db/dbq"
)
// NormalizationPrefs is one user's loudness-normalization preference (M464
// #4998). It lives on the server so every player applies the same one: the
// web player and the Android app read it, and the leveled stream for
// UPnP/Sonos (#5001) renders with it.
type NormalizationPrefs struct {
// Mode is off, auto, track or album. Auto uses album gain while an album
// plays in order and track gain otherwise.
Mode string `json:"mode"`
// TargetLUFS is the loudness tracks are leveled to.
TargetLUFS int16 `json:"target_lufs"`
// Boost is how a track quieter than the target is raised: headroom stops
// at its true peak, limiter goes all the way and limits the peaks.
Boost string `json:"boost"`
}
// The accepted values. Migration 0067's CHECKs hold the same lists.
var (
NormalizationModes = []string{"off", "auto", "track", "album"}
NormalizationTargets = []int16{-18, -16, -14}
NormalizationBoosts = []string{"headroom", "limiter"}
)
// DefaultNormalizationPrefs applies to a user who has never chosen. It must
// equal migration 0067's column defaults; a test holds them together.
var DefaultNormalizationPrefs = NormalizationPrefs{Mode: "auto", TargetLUFS: -18, Boost: "headroom"}
// ErrNormalizationPrefsInvalid is returned for a value outside the lists.
var ErrNormalizationPrefsInvalid = errors.New("normalization preference out of range")
// Validate reports the first field holding a value the server does not
// accept.
func (p NormalizationPrefs) Validate() error {
switch {
case !slices.Contains(NormalizationModes, p.Mode):
return fmt.Errorf("%w: mode %q", ErrNormalizationPrefsInvalid, p.Mode)
case !slices.Contains(NormalizationTargets, p.TargetLUFS):
return fmt.Errorf("%w: target_lufs %d", ErrNormalizationPrefsInvalid, p.TargetLUFS)
case !slices.Contains(NormalizationBoosts, p.Boost):
return fmt.Errorf("%w: boost %q", ErrNormalizationPrefsInvalid, p.Boost)
}
return nil
}
// LoadNormalizationPrefs returns the user's preference, or the defaults if
// they have never set one.
func LoadNormalizationPrefs(ctx context.Context, q *dbq.Queries, userID pgtype.UUID) (NormalizationPrefs, error) {
row, err := q.GetNormalizationPrefs(ctx, userID)
if errors.Is(err, pgx.ErrNoRows) {
return DefaultNormalizationPrefs, nil
}
if err != nil {
return DefaultNormalizationPrefs, err
}
return NormalizationPrefs{Mode: row.Mode, TargetLUFS: row.TargetLufs, Boost: row.Boost}, nil
}
// SaveNormalizationPrefs validates and stores the user's preference,
// returning what was stored.
func SaveNormalizationPrefs(ctx context.Context, q *dbq.Queries, userID pgtype.UUID, p NormalizationPrefs) (NormalizationPrefs, error) {
if err := p.Validate(); err != nil {
return p, err
}
row, err := q.UpsertNormalizationPrefs(ctx, dbq.UpsertNormalizationPrefsParams{
UserID: userID, Mode: p.Mode, TargetLufs: p.TargetLUFS, Boost: p.Boost,
})
if err != nil {
return p, err
}
return NormalizationPrefs{Mode: row.Mode, TargetLUFS: row.TargetLufs, Boost: row.Boost}, nil
}
@@ -0,0 +1,69 @@
package library
import (
"context"
"errors"
"testing"
"git.fabledsword.com/bvandeusen/minstrel/internal/db/dbq"
"git.fabledsword.com/bvandeusen/minstrel/internal/dbtest"
)
func TestNormalizationPrefs_Validate(t *testing.T) {
if err := DefaultNormalizationPrefs.Validate(); err != nil {
t.Fatalf("the defaults are invalid: %v", err)
}
for _, p := range []NormalizationPrefs{
{Mode: "loud", TargetLUFS: -18, Boost: "headroom"},
{Mode: "auto", TargetLUFS: -23, Boost: "headroom"},
{Mode: "auto", TargetLUFS: -18, Boost: "max"},
// A field left out of a PUT body decodes as its zero value.
{Mode: "auto", Boost: "headroom"},
} {
if err := p.Validate(); !errors.Is(err, ErrNormalizationPrefsInvalid) {
t.Errorf("%+v: err = %v, want ErrNormalizationPrefsInvalid", p, err)
}
}
}
// A user with no row gets the Go defaults, and a stored row reads back the
// migration's defaults for any column the insert left out; the two must
// agree, or a user would hear a different level after their first save.
func TestNormalizationPrefs_DefaultsAndRoundTrip_Integration(t *testing.T) {
pool := newPool(t)
ctx := context.Background()
q := dbq.New(pool)
user, err := q.CreateUser(ctx, dbq.CreateUserParams{
Username: dbtest.TestUserPrefix + "norm-prefs", PasswordHash: "x", ApiTokenHash: "norm-prefs-token",
})
if err != nil {
t.Fatalf("user: %v", err)
}
got, err := LoadNormalizationPrefs(ctx, q, user.ID)
if err != nil || got != DefaultNormalizationPrefs {
t.Fatalf("unset prefs = %+v, %v; want the defaults", got, err)
}
if _, err := pool.Exec(ctx, "INSERT INTO user_normalization_prefs (user_id) VALUES ($1)", user.ID); err != nil {
t.Fatalf("insert defaults row: %v", err)
}
got, err = LoadNormalizationPrefs(ctx, q, user.ID)
if err != nil || got != DefaultNormalizationPrefs {
t.Errorf("migration defaults = %+v, Go defaults = %+v (err %v)", got, DefaultNormalizationPrefs, err)
}
want := NormalizationPrefs{Mode: "track", TargetLUFS: -14, Boost: "limiter"}
if saved, err := SaveNormalizationPrefs(ctx, q, user.ID, want); err != nil || saved != want {
t.Fatalf("save = %+v, %v; want %+v", saved, err, want)
}
if got, _ := LoadNormalizationPrefs(ctx, q, user.ID); got != want {
t.Errorf("after save = %+v, want %+v", got, want)
}
if _, err := SaveNormalizationPrefs(ctx, q, user.ID, NormalizationPrefs{Mode: "x"}); !errors.Is(err, ErrNormalizationPrefsInvalid) {
t.Errorf("invalid save: err = %v", err)
}
if got, _ := LoadNormalizationPrefs(ctx, q, user.ID); got != want {
t.Errorf("an invalid save changed the stored prefs to %+v", got)
}
}