From a92326c1b44ebb78bfd323586a4ec2276cd389a9 Mon Sep 17 00:00:00 2001 From: tgiachi Date: Sat, 14 Nov 2026 16:02:23 +0100 Subject: [PATCH] feat(player): play every song at a similar volume with ReplayGain I want songs from different albums to play at about the same loudness without touching the volume. - The scan reads REPLAYGAIN_TRACK_GAIN, REPLAYGAIN_ALBUM_GAIN and the two peaks from each file, offline, and keeps them on the file (migration 0029, SQLite and PostgreSQL). A tag that makes no sense (not a number, more than 60 dB) is left out. Files indexed before have none until a full rescan. - A track in the API carries them as replay_gain (null when its first playable file says nothing). - The web player levels each song with them: the sound passes through a gain node, so a quiet song can be raised too, but never so much that its peak would clip (and never more than 12 dB when there is no peak). Without Web Audio the element is turned down instead. - A new Playback section in Settings chooses song by song (default), album by album or off; the choice stays on the device. - README: the ReplayGain entry, and the old line that said the year was not in the index is removed. - English and Italian. --- README.md | 5 +- internal/api/http/catalog_test.go | 26 +++++++- internal/api/http/friends_test.go | 2 +- internal/api/http/handlers_catalog.go | 13 ++++ internal/api/http/peer_test.go | 2 +- internal/api/openapi/openapi.yaml | 14 ++++ internal/catalog/catalog.go | 11 +++- internal/library/taglib.go | 43 +++++++++++++ internal/library/taglib_test.go | 85 +++++++++++++++++++++++++ internal/library/types.go | 9 +++ internal/storage/catalog.go | 25 +++++++- internal/storage/library.go | 26 +++++++- internal/storage/library_test.go | 69 ++++++++++++++++++++ internal/storage/storage_test.go | 4 +- migrations/postgres/0029_replaygain.sql | 6 ++ migrations/sqlite/0029_replaygain.sql | 8 +++ web/src/api/schema.d.ts | 11 ++++ web/src/i18n/locales/en.json | 6 ++ web/src/i18n/locales/it.json | 6 ++ web/src/pages/SettingsPage.test.tsx | 17 +++++ web/src/pages/SettingsPage.tsx | 14 ++++ web/src/player/analyser.test.ts | 35 +++++++++- web/src/player/analyser.ts | 26 +++++++- web/src/player/engine.test.ts | 71 ++++++++++++++++++++- web/src/player/engine.ts | 25 +++++++- web/src/player/replayGain.test.ts | 74 +++++++++++++++++++++ web/src/player/replayGain.ts | 59 +++++++++++++++++ web/src/player/usePlayer.ts | 3 +- 28 files changed, 672 insertions(+), 23 deletions(-) create mode 100644 migrations/postgres/0029_replaygain.sql create mode 100644 migrations/sqlite/0029_replaygain.sql create mode 100644 web/src/player/replayGain.test.ts create mode 100644 web/src/player/replayGain.ts diff --git a/README.md b/README.md index f88cac0..63d737d 100644 --- a/README.md +++ b/README.md @@ -22,7 +22,8 @@ It is a single executable, one database (SQLite by default, PostgreSQL if you pr - **Artist photos.** `GET /artists/{id}/image` serves a free picture of an artist from Wikimedia Commons, and `GET /artists/{id}/image/credit` says whose it is and under which licence, which you must show next to it. Only free licences are kept (public domain, CC0, CC BY, CC BY-SA): non-commercial, no-derivatives, fair-use and unknown ones are refused, because Sonda stores a copy (`?size=small` is 300 pixels, `large` 1000) in the data folder. With the `commons` provider and the `musicbrainz` one switched on, Sonda follows ids and never a name: the artist's MusicBrainz id, the Wikidata item MusicBrainz links to it, the picture Wikidata names for it, and Commons for its licence. Many artists will have none. Kept for 30 days (a week when there is none) and removed, files included, with the provider's data. To look for the pictures of the whole library in one go, an admin starts a background job like a scan: `POST /library/artist-images` (follow it with `GET /library/artist-images`, stop it with `DELETE /library/artist-images`; `?refresh=true` searches every artist again). It only goes through artists that have a MusicBrainz id, never replaces a picture by a failure, and ends at once, saying so, when a provider it needs is off. See [External providers](#external-providers). - **Album covers.** `GET /albums/{id}/cover` serves the cover of an album from your own files: the picture embedded in them, or else a `cover`, `folder`, `front`, `album` or `albumart` image in the album's folder. It is built the first time it is asked for (a few at a time), scaled (`?size=small` is 300 pixels, `large` 1000) and kept in the data folder (`storage.data_dir`, you can delete it: covers are built again). A picture you replace in a folder is noticed within a week, or at once after a full rescan. When your files have no picture at all and an admin switched on the `coverartarchive` provider, the cover is asked from the Cover Art Archive by the MusicBrainz release group id that the tags of the album's files carry (`MUSICBRAINZ_RELEASEGROUPID`; run a full rescan to read it for music you already indexed); your own files always come first, and only that id leaves the server. An album whose files have no id is looked up in MusicBrainz by its artist and title when the `musicbrainz` provider is on too (see the list of what leaves your server). For an album split in `CD1`/`Disc 2` folders, the picture in the folder above is used. Nothing is sent anywhere unless you switched on the `coverartarchive` provider (see [External providers](#external-providers)). It also takes `?access_token=`, so an `` element can use it. To build the covers of the whole library in one go instead of one album at a time, an admin starts a background job like a scan: `POST /library/covers` (follow it with `GET /library/covers`, stop it with `DELETE /library/covers`; `?refresh=true` searches every album again; it never replaces a cover by "no cover" because a disk was not mounted, and keeps the covers that came from the archive if you switched it off). - **Mixes.** `GET /mixes` lists playlists that Sonda makes for you, like the mixes of a streaming service, from what you listen to and from the genres of your music: one mix for each genre of your library that has at least 30 songs by 4 artists (the genres you play most first), and, once you have some listening history, *Your favourites* and *Rediscover* (artists you like and have not played for a month); *New to you* is the songs you never played. `GET /mixes/{id}` gives a mix of up to 50 songs, at most 3 by one artist and never two of the same artist in a row. They are picked by weighted chance: the artists you play weigh more and songs you skipped lately or artists you avoid are left out. A mix stays the same for a day, and `?variant=2` gives another; `POST /mixes/{id}/playlist` keeps the one you are looking at as a playlist of your own. A mix is worked out when you ask for it, from your own history and the genre tags of your files: nothing is stored and nothing is sent to a provider. The id of a genre mix has the genre in it (`genre:hard rock`), so it is percent-encoded in the path. Each mix says which albums stand for it (`album_ids`: up to 4 albums that have a cover, by different artists, with most of the songs the mix draws from), for a picture made of their covers; the covers are the ones the library already has, so a mix has a picture once the covers of its albums were looked up (browsing the albums, or the covers job), and none is fetched for it. -- **Smart playlists.** A smart playlist is a set of rules instead of a list of songs, worked out again every time you open it, so new songs and your listening change it by themselves. `POST /smart-playlists` keeps a name, the rules, an order (`random`, `most_played`, `least_played`, `recently_added` or `title`) and a limit (50 by default, 500 at most); `GET /smart-playlists/{id}/tracks` gives the songs now. Every rule that is set must hold: genres, artists and albums (is, or is not), file formats and a minimum bitrate (about the same file), added in the last N days (by the date of the file), never played, played or not played in the last N days, played at least N times (optionally counting only the plays of the last N days, which is what makes the songs in rotation lately and the top of the year), skipped or not skipped lately, only artists you like or without the ones you avoid, the length of the song, and the year it came out (`min_year` and `max_year`, both included: 1980 to 1989 is the eighties). The year comes from the tags of the file (the original date first, then the date); a song with no year never matches a year rule, and the files indexed before this existed have none until a full rescan (`POST /library/scan?full=true`) reads their tags again. `POST /smart-playlists/preview` tries rules without keeping them, and `POST /smart-playlists/{id}/playlist` keeps what you see as a normal playlist (a copy). Only the rules are stored; the songs come from the files and from your own history, nothing is sent to a provider, and a smart playlist is yours alone, and `GET /genres` lists the genres to choose from. A random order stays the same for a day, and `?variant=2` gives another. `GET /smart-playlists/{id}/covers` and `GET /smart-playlists/suggested/{key}/covers` say which albums stand for one (up to 4 that have a cover, in the order of the songs it gives now), for its picture; they are apart from the songs so that the list of smart playlists shows at once and each card fills in its cover when it arrives. Some are there without anybody making them: `GET /smart-playlists/suggested` lists a fixed set (`recently-added`, `on-rotation`, `top-year`, `most-played`, `never-played`, `forgotten`, `high-quality`, `long-tracks`), the same rules for everyone and worked out on your own library and history, nothing stored; `GET /smart-playlists/suggested/{key}/tracks` gives their songs and `POST /smart-playlists/suggested/{key}/playlist` keeps them as a playlist, and `on-rotation` is the songs you played most in the last 30 days and `top-year` the same over a year, so they change as you listen; a copy of their rules becomes a smart playlist of your own with `POST /smart-playlists`. The year of a song is not in the index yet, so there is no rule about it. A user can have 200. +- **ReplayGain.** The scan reads the ReplayGain tags of each file (`REPLAYGAIN_TRACK_GAIN`, `REPLAYGAIN_ALBUM_GAIN` and the two peaks), offline, and keeps them on the file; a tag that makes no sense (not a number, more than 60 dB) is left out. A track in the API has them as `replay_gain` (gains in decibels, peaks as a fraction of full scale), or `null` when its first playable file says nothing; the files indexed before this existed have none until a full rescan (`POST /library/scan?full=true`) reads their tags again. The server never changes a file or the sound: a client uses the numbers to play every song at a similar volume, as the web app does (see [Web app](#web-app)). +- **Smart playlists.** A smart playlist is a set of rules instead of a list of songs, worked out again every time you open it, so new songs and your listening change it by themselves. `POST /smart-playlists` keeps a name, the rules, an order (`random`, `most_played`, `least_played`, `recently_added` or `title`) and a limit (50 by default, 500 at most); `GET /smart-playlists/{id}/tracks` gives the songs now. Every rule that is set must hold: genres, artists and albums (is, or is not), file formats and a minimum bitrate (about the same file), added in the last N days (by the date of the file), never played, played or not played in the last N days, played at least N times (optionally counting only the plays of the last N days, which is what makes the songs in rotation lately and the top of the year), skipped or not skipped lately, only artists you like or without the ones you avoid, the length of the song, and the year it came out (`min_year` and `max_year`, both included: 1980 to 1989 is the eighties). The year comes from the tags of the file (the original date first, then the date); a song with no year never matches a year rule, and the files indexed before this existed have none until a full rescan (`POST /library/scan?full=true`) reads their tags again. `POST /smart-playlists/preview` tries rules without keeping them, and `POST /smart-playlists/{id}/playlist` keeps what you see as a normal playlist (a copy). Only the rules are stored; the songs come from the files and from your own history, nothing is sent to a provider, and a smart playlist is yours alone, and `GET /genres` lists the genres to choose from. A random order stays the same for a day, and `?variant=2` gives another. `GET /smart-playlists/{id}/covers` and `GET /smart-playlists/suggested/{key}/covers` say which albums stand for one (up to 4 that have a cover, in the order of the songs it gives now), for its picture; they are apart from the songs so that the list of smart playlists shows at once and each card fills in its cover when it arrives. Some are there without anybody making them: `GET /smart-playlists/suggested` lists a fixed set (`recently-added`, `on-rotation`, `top-year`, `most-played`, `never-played`, `forgotten`, `high-quality`, `long-tracks`), the same rules for everyone and worked out on your own library and history, nothing stored; `GET /smart-playlists/suggested/{key}/tracks` gives their songs and `POST /smart-playlists/suggested/{key}/playlist` keeps them as a playlist, and `on-rotation` is the songs you played most in the last 30 days and `top-year` the same over a year, so they change as you listen; a copy of their rules becomes a smart playlist of your own with `POST /smart-playlists`. A user can have 200. - **Playlists.** `POST /playlists` makes a playlist (a name and an optional description) and `GET /playlists` lists yours, the one changed last first. `POST /playlists/{id}/tracks` adds 1 to 500 tracks at the end or at a `position`, `GET /playlists/{id}/tracks` lists them in order, `PATCH /playlists/{id}/tracks/{item}` moves one and `DELETE` takes one out; `PATCH /playlists/{id}` renames and `DELETE /playlists/{id}` deletes (the tracks stay in the library). A track can be in a playlist more than once, which is why each place has its own item id. A playlist is yours alone: someone else's answers `playlist_not_found`, as one that does not exist. A track whose files were deleted or moved away stays in the playlist and shows `available: false`; it plays again when the files come back and a scan finds them. Each playlist says which albums stand for it (`album_ids`: up to 4 albums that have a cover, in the order they first appear in it, each once), for a picture made of their covers; nothing is fetched for it. A user can have 1000 playlists of up to 10000 tracks. Nothing is shared and nothing leaves your server. - **Wishlist and "not interested".** `PUT /wishlist/{artist}` puts an artist on your wishlist (`GET /wishlist` lists it, `DELETE` takes it off), and `POST /discover/{artist}/dismiss` hides an artist from your Discover for good (`DELETE` brings it back, `GET /discover/dismissed` lists them). An artist is wished or dismissed, never both, and both lists are yours alone. Discover marks the wished artists it shows (`wishlisted`) and never suggests a dismissed one. The wishlist is a list for you and sends nothing anywhere; Sonda downloads nothing, but an admin can send an artist that Discover showed to their own Lidarr (see [External providers](#external-providers)), which works for an artist that has a MusicBrainz id and that Sonda knows of from a list or from your files. An artist that only Last.fm named is kept while you have it marked (your lists still show it, but other users cannot see that it exists), and goes with the rest of Last.fm's data if an admin removes Last.fm's data. Removing MusicBrainz's data does not touch it. - **Your own settings.** `GET` and `PATCH /me/settings` hold choices that belong to you, not to the server. Everyone starts private: `discover_from_listening` is off, so this setting never sends your listening to a provider. When you turn it on, Discover may start from the artists you listen to most, and their names are sent to Last.fm (only if an admin switched it on). What Last.fm answers is kept in the shared database like any other lookup, so another local user can see, from `retrieved_at` of `GET /artists/{id}/similar`, that someone looked up an artist, but not who. @@ -354,7 +355,7 @@ npm install SONDA_URL=http://127.0.0.1:8080 npm run dev # open http://localhost:5173, /api is proxied to Sonda ``` -What it does today: sign in (and create the first account of a new server), browse artists, albums and songs, search, and play with a queue, shuffle, repeat, media keys, a volume slider with mute (remembered in the browser) and a full-screen player. Artist pages show the Wikipedia text, similar artists and tags when those providers are on, each with its credit, and the photo credit next to the photo. It reports one listen per play. Playlists have a page of their own, shown as cards with a collage of their covers (as the mixes and the smart playlists have): make one, put a song in it with the button next to any song (or make a new playlist right there), play it, rename it, delete it, move a song up or down and take one out; a song whose files are gone is shown as not available and skipped when the playlist plays. Mixes have a page too: a card for each mix, with a collage of the covers of its albums (the ones from your listening first, then one for each genre), and on a mix its songs, Play, Shuffle again (another set of songs) and Save as playlist, which keeps what you see as a playlist of your own. Where a playlist is renamed, and where a smart playlist is edited, a Suggest a name button asks for a name. Smart playlists have their own page too, which begins with the ones Sonda makes for you (ready to play, to keep as a playlist, or to make your own with a click), and then yours: make one with an editor of the rules (genres, format and bitrate, when it was added, your listening and taste, the length, the order and the limit) and a live preview of the songs it gives, play it, shuffle it again (for the random order), keep what you see as a playlist, edit it or delete it; rules by artist and album are in the API only, and an edit keeps them. Discover suggests artists from the ones you pick, or from your listening only after you allow it (a dialog says that their names go to Last.fm), explains each score, and keeps your wishlist and the artists you are not interested in. A suggested artist you do not have shows a letter, not a photo, because a photo is a lookup at the providers: a "Show photo" button on the card asks for that one artist when you press it (the card says it goes to Wikimedia Commons by MusicBrainz id, and says so when there is no free photo). An admin who set up the `lidarr` provider gets a "Request on Lidarr" button on an artist's page and on the Discover cards: it asks first, then sends that one artist to their own Lidarr, which does the downloading (the web app downloads nothing; the page of an artist reads what Lidarr has, the cards ask nothing until you send). An admin also gets an Admin area to add, rename, move and remove libraries and to start a scan (of one library or all, optionally reading every file again) and follow it, and to manage accounts: add one by email, give or take away the admin role, reset a password (which ends that person's sessions) and delete an account. The last admin cannot be changed, and your own account has no buttons there. Providers have a card each that says what the provider is sent: turning one on asks first, the API key is write-only (never shown, and gone from the page once saved), and there are a test of the key, the contact or address, removing what a provider gave, and, for Lidarr, the profiles and root folder to use when an artist is added. The bulk jobs (album covers, artist pictures, artist descriptions) each have a card that says what the job sends and to whom: starting one asks first and says it goes through the whole library, reading everything again is a separate choice, a job whose providers are off cannot be started, and the page follows its progress and can stop it. The web app is a PWA: it has a manifest and a service worker, so a browser can install it (Settings has an Install button where the browser lets a page ask) and it opens at once from its own icon, and shows its own page when the server cannot be reached. The worker keeps only the files of the app (the page, its scripts and styles, the manifest and the icons) and never anything from `/api/`: the catalog, the covers, the songs and what a person did are private and are not kept. A new version waits until you press Reload, so nothing changes under a song. It needs https, or localhost. The menu on the left folds to a narrow bar with the icons of the pages (a button in it, remembered in the browser; on a phone it stays a row of links). There are six themes (Sonda, Tokyo Night, Gruvbox dark, Gruvbox light, Dracula and Neon) and two languages (English and Italian), both chosen in Settings. +What it does today: sign in (and create the first account of a new server), browse artists, albums and songs, search, and play with a queue, shuffle, repeat, media keys, a volume slider with mute (remembered in the browser), the volume evened out by the ReplayGain tags of your files (Settings: song by song, album by album or off; a quiet song is raised, but never so much that its loudest sample would clip, and one with no tags plays as it is) and a full-screen player. Artist pages show the Wikipedia text, similar artists and tags when those providers are on, each with its credit, and the photo credit next to the photo. It reports one listen per play. Playlists have a page of their own, shown as cards with a collage of their covers (as the mixes and the smart playlists have): make one, put a song in it with the button next to any song (or make a new playlist right there), play it, rename it, delete it, move a song up or down and take one out; a song whose files are gone is shown as not available and skipped when the playlist plays. Mixes have a page too: a card for each mix, with a collage of the covers of its albums (the ones from your listening first, then one for each genre), and on a mix its songs, Play, Shuffle again (another set of songs) and Save as playlist, which keeps what you see as a playlist of your own. Where a playlist is renamed, and where a smart playlist is edited, a Suggest a name button asks for a name. Smart playlists have their own page too, which begins with the ones Sonda makes for you (ready to play, to keep as a playlist, or to make your own with a click), and then yours: make one with an editor of the rules (genres, format and bitrate, when it was added, your listening and taste, the length, the order and the limit) and a live preview of the songs it gives, play it, shuffle it again (for the random order), keep what you see as a playlist, edit it or delete it; rules by artist and album are in the API only, and an edit keeps them. Discover suggests artists from the ones you pick, or from your listening only after you allow it (a dialog says that their names go to Last.fm), explains each score, and keeps your wishlist and the artists you are not interested in. A suggested artist you do not have shows a letter, not a photo, because a photo is a lookup at the providers: a "Show photo" button on the card asks for that one artist when you press it (the card says it goes to Wikimedia Commons by MusicBrainz id, and says so when there is no free photo). An admin who set up the `lidarr` provider gets a "Request on Lidarr" button on an artist's page and on the Discover cards: it asks first, then sends that one artist to their own Lidarr, which does the downloading (the web app downloads nothing; the page of an artist reads what Lidarr has, the cards ask nothing until you send). An admin also gets an Admin area to add, rename, move and remove libraries and to start a scan (of one library or all, optionally reading every file again) and follow it, and to manage accounts: add one by email, give or take away the admin role, reset a password (which ends that person's sessions) and delete an account. The last admin cannot be changed, and your own account has no buttons there. Providers have a card each that says what the provider is sent: turning one on asks first, the API key is write-only (never shown, and gone from the page once saved), and there are a test of the key, the contact or address, removing what a provider gave, and, for Lidarr, the profiles and root folder to use when an artist is added. The bulk jobs (album covers, artist pictures, artist descriptions) each have a card that says what the job sends and to whom: starting one asks first and says it goes through the whole library, reading everything again is a separate choice, a job whose providers are off cannot be started, and the page follows its progress and can stop it. The web app is a PWA: it has a manifest and a service worker, so a browser can install it (Settings has an Install button where the browser lets a page ask) and it opens at once from its own icon, and shows its own page when the server cannot be reached. The worker keeps only the files of the app (the page, its scripts and styles, the manifest and the icons) and never anything from `/api/`: the catalog, the covers, the songs and what a person did are private and are not kept. A new version waits until you press Reload, so nothing changes under a song. It needs https, or localhost. The menu on the left folds to a narrow bar with the icons of the pages (a button in it, remembered in the browser; on a phone it stays a row of links). There are six themes (Sonda, Tokyo Night, Gruvbox dark, Gruvbox light, Dracula and Neon) and two languages (English and Italian), both chosen in Settings. More commands, all run in `web/`: `npm test`, `npm run build`, and `npm run gen:api`, which rebuilds `src/api/schema.d.ts` from the OpenAPI spec (it fetches the generator with `npx`, so it needs the network once). `npm run build` writes to `internal/webui/dist` (git-ignored), not to `web/dist`. diff --git a/internal/api/http/catalog_test.go b/internal/api/http/catalog_test.go index cbc63b3..434ee72 100644 --- a/internal/api/http/catalog_test.go +++ b/internal/api/http/catalog_test.go @@ -139,7 +139,7 @@ func TestCatalogListShapeAndPaging(t *testing.T) { r = do(t, h, "GET", "/api/v1/tracks", tok, nil) tr := r.Body["items"].([]any)[0].(map[string]any) // No file path, root or library path may ever appear. - sameKeys(t, "track", tr, "id", "title", "duration_ms", "track_no", "disc_no", "album", "artists", "format") + sameKeys(t, "track", tr, "id", "title", "duration_ms", "track_no", "disc_no", "album", "artists", "format", "replay_gain") sameKeys(t, "track album", tr["album"].(map[string]any), "id", "title") if tr["format"] != "flac" || len(tr["artists"].([]any)) != 1 { t.Errorf("track = %v", tr) @@ -170,6 +170,28 @@ func TestTrackWithoutAlbumHasNullAlbum(t *testing.T) { } } +func TestTrackCarriesItsReplayGain(t *testing.T) { + g := func(v float64) *float64 { return &v } + fc := &fakeCatalog{tracks: []catalog.Track{ + {ID: 1, Title: "Tagged", ReplayGain: &catalog.ReplayGain{TrackGain: g(-6.5), TrackPeak: g(0.98)}}, + {ID: 2, Title: "Plain"}, + }} + h, tok := catalogAPI(t, fc) + items := do(t, h, "GET", "/api/v1/tracks", tok, nil).Body["items"].([]any) + + tagged := items[0].(map[string]any)["replay_gain"].(map[string]any) + sameKeys(t, "replay_gain", tagged, "track_gain_db", "album_gain_db", "track_peak", "album_peak") + if tagged["track_gain_db"] != -6.5 || tagged["track_peak"] != 0.98 { + t.Errorf("replay_gain = %v, want the gain -6.5 and the peak 0.98", tagged) + } + if v, present := tagged["album_gain_db"]; !present || v != nil { + t.Errorf("album_gain_db = %#v, want an explicit null: the file does not say", v) + } + if v, present := items[1].(map[string]any)["replay_gain"]; !present || v != nil { + t.Errorf("replay_gain of a song with none = %#v, want an explicit null", v) + } +} + func TestCatalogQueryParametersReachTheService(t *testing.T) { fc := &fakeCatalog{} h, tok := catalogAPI(t, fc) @@ -226,7 +248,7 @@ func TestCatalogDetails(t *testing.T) { r = do(t, h, "GET", "/api/v1/albums/6", tok, nil) sameKeys(t, "album", r.Body, "id", "title", "artist", "track_count", "duration_ms") r = do(t, h, "GET", "/api/v1/tracks/7", tok, nil) - sameKeys(t, "track", r.Body, "id", "title", "duration_ms", "track_no", "disc_no", "album", "artists", "format") + sameKeys(t, "track", r.Body, "id", "title", "duration_ms", "track_no", "disc_no", "album", "artists", "format", "replay_gain") if r.Code != http.StatusOK || r.Body["id"] != float64(7) { t.Errorf("track: %d %v", r.Code, r.Body) } diff --git a/internal/api/http/friends_test.go b/internal/api/http/friends_test.go index e6b1aa3..52c46ad 100644 --- a/internal/api/http/friends_test.go +++ b/internal/api/http/friends_test.go @@ -139,7 +139,7 @@ func TestAListenerBrowsesWhatAFriendSharesAndNothingElse(t *testing.T) { t.Errorf("%s = %d %v", path, r.Code, r.Body) } } - sameKeys(t, "track", f.get(t, base+"/tracks/"+idOf(track)).Body, "id", "title", "duration_ms", "track_no", "disc_no", "album", "artists", "format") + sameKeys(t, "track", f.get(t, base+"/tracks/"+idOf(track)).Body, "id", "title", "duration_ms", "track_no", "disc_no", "album", "artists", "format", "replay_gain") if got := titlesIn(f.get(t, base+"/tracks?album_id="+idOf(album))); len(got) != 1 { t.Errorf("the tracks of an album = %v", got) } diff --git a/internal/api/http/handlers_catalog.go b/internal/api/http/handlers_catalog.go index cf63891..7dbe2ca 100644 --- a/internal/api/http/handlers_catalog.go +++ b/internal/api/http/handlers_catalog.go @@ -49,6 +49,16 @@ type trackJSON struct { Album *albumRefJSON `json:"album"` Artists []artistRefJSON `json:"artists"` Format string `json:"format"` + // What the first playable file says about its loudness: null when it says nothing. + ReplayGain *replayGainJSON `json:"replay_gain"` +} + +// replayGainJSON is the ReplayGain of a track. A part the file does not say is null. +type replayGainJSON struct { + TrackGainDB *float64 `json:"track_gain_db"` + AlbumGainDB *float64 `json:"album_gain_db"` + TrackPeak *float64 `json:"track_peak"` + AlbumPeak *float64 `json:"album_peak"` } func toArtistJSON(a catalog.Artist) artistJSON { @@ -74,6 +84,9 @@ func toTrackJSON(t catalog.Track) trackJSON { for i, a := range t.Artists { out.Artists[i] = artistRefJSON{ID: a.ID, Name: a.Name} } + if g := t.ReplayGain; g != nil { + out.ReplayGain = &replayGainJSON{TrackGainDB: g.TrackGain, AlbumGainDB: g.AlbumGain, TrackPeak: g.TrackPeak, AlbumPeak: g.AlbumPeak} + } return out } diff --git a/internal/api/http/peer_test.go b/internal/api/http/peer_test.go index 5e1bba8..3453d8e 100644 --- a/internal/api/http/peer_test.go +++ b/internal/api/http/peer_test.go @@ -301,7 +301,7 @@ func TestAFriendReadsOnlyTheSharedLibraries(t *testing.T) { t.Errorf("asking for the other library found %v", got) } one := f.get(t, "/tracks/"+strconv.FormatInt(f.track["Shared Song"], 10)) - sameKeys(t, "track", one.Body, "id", "title", "duration_ms", "track_no", "disc_no", "album", "artists", "format") + sameKeys(t, "track", one.Body, "id", "title", "duration_ms", "track_no", "disc_no", "album", "artists", "format", "replay_gain") if one.Code != 200 || one.Body["title"] != "Shared Song" { t.Errorf("track = %d %v", one.Code, one.Body) } diff --git a/internal/api/openapi/openapi.yaml b/internal/api/openapi/openapi.yaml index 28e6b22..ed320fd 100644 --- a/internal/api/openapi/openapi.yaml +++ b/internal/api/openapi/openapi.yaml @@ -4430,6 +4430,20 @@ components: type: array items: {$ref: '#/components/schemas/ArtistRef'} format: {type: string, description: 'Format of the first playable file, for example `mp3` or `flac`.'} + replay_gain: + type: object + nullable: true + description: >- + What the first playable file says about its own loudness, from its ReplayGain tags; null when it says + nothing. A player can use it to play every song at a similar volume. Files indexed before this existed have + none until a full rescan (`POST /library/scan?full=true`) reads their tags again. + additionalProperties: false + required: [track_gain_db, album_gain_db, track_peak, album_peak] + properties: + track_gain_db: {type: number, nullable: true, description: 'Decibels to add to play this song at the reference loudness.'} + album_gain_db: {type: number, nullable: true, description: 'The same for the whole album, which keeps the differences between its songs.'} + track_peak: {type: number, nullable: true, description: 'The loudest sample of the song, 1 being full scale.'} + album_peak: {type: number, nullable: true, description: 'The loudest sample of the album, 1 being full scale.'} ArtistPage: type: object diff --git a/internal/catalog/catalog.go b/internal/catalog/catalog.go index 68a5d8b..013c7d5 100644 --- a/internal/catalog/catalog.go +++ b/internal/catalog/catalog.go @@ -81,7 +81,15 @@ type Album struct { DurationMs int64 } -// Track is a playable track. Format is that of its first playable file. +// ReplayGain is what the first playable file of a track says about its loudness; a field it does not say is nil. +// Gains are in decibels, peaks a fraction of full scale (1 is the loudest a sample can be). +type ReplayGain struct { + TrackGain, AlbumGain *float64 + TrackPeak, AlbumPeak *float64 +} + +// Track is a playable track. Format and ReplayGain are those of its first playable file; ReplayGain is nil when the +// file says nothing about its loudness. type Track struct { ID int64 Title string @@ -91,6 +99,7 @@ type Track struct { Album *AlbumRef Artists []ArtistRef Format string + ReplayGain *ReplayGain } // Store reads the catalog. Lists are ordered deterministically and must load diff --git a/internal/library/taglib.go b/internal/library/taglib.go index d936423..7bc6479 100644 --- a/internal/library/taglib.go +++ b/internal/library/taglib.go @@ -2,6 +2,7 @@ package library import ( "fmt" + "math" "path/filepath" "regexp" "strconv" @@ -59,6 +60,12 @@ func (TaglibReader) Read(path string) (Metadata, error) { TrackNo: leadingInt(first(tags, "TRACKNUMBER")), DiscNo: leadingInt(first(tags, "DISCNUMBER")), Year: yearOf(tags), + ReplayGain: ReplayGain{ + TrackGain: parseGain(first(tags, "REPLAYGAIN_TRACK_GAIN")), + AlbumGain: parseGain(first(tags, "REPLAYGAIN_ALBUM_GAIN")), + TrackPeak: parsePeak(first(tags, "REPLAYGAIN_TRACK_PEAK")), + AlbumPeak: parsePeak(first(tags, "REPLAYGAIN_ALBUM_PEAK")), + }, }, Properties: Properties{ Format: strings.ToLower(props.Format), @@ -98,6 +105,42 @@ func yearOf(tags map[string][]string) int { return 0 } +// maxGainDB bounds a gain that is believed: a tag that asks for more than this is a mistake, and playing it would +// be either silence or a blast. +const maxGainDB = 60 + +// maxPeak bounds a peak that is believed. A real peak is a little above 1 at most (a file that was clipped when it +// was decoded); anything near this is not a peak. +const maxPeak = 1000 + +// parseGain reads a ReplayGain gain: a number of decibels, written as "-6.54 dB", "+3.2 dB" or only "-6.54" (some +// taggers write a comma). Anything else is no gain. +func parseGain(s string) *float64 { + v, ok := parseDecimal(strings.TrimSpace(strings.TrimSuffix(strings.ToLower(strings.TrimSpace(s)), "db"))) + if !ok || math.Abs(v) > maxGainDB { + return nil + } + return &v +} + +// parsePeak reads a ReplayGain peak: a positive number, 1 meaning full scale. Anything else is no peak. +func parsePeak(s string) *float64 { + v, ok := parseDecimal(strings.TrimSpace(s)) + if !ok || v <= 0 || v > maxPeak { + return nil + } + return &v +} + +// parseDecimal reads a number written with a point or a comma, and refuses NaN and infinity. +func parseDecimal(s string) (float64, bool) { + v, err := strconv.ParseFloat(strings.ReplaceAll(s, ",", "."), 64) + if err != nil || math.IsNaN(v) || math.IsInf(v, 0) { + return 0, false + } + return v, true +} + // maxGenreLen bounds one genre; a longer one is a sentence, not a genre. const maxGenreLen = 100 diff --git a/internal/library/taglib_test.go b/internal/library/taglib_test.go index 41c3f0d..3cf005b 100644 --- a/internal/library/taglib_test.go +++ b/internal/library/taglib_test.go @@ -328,3 +328,88 @@ func TestTaglibReaderYear(t *testing.T) { }) } } + +func TestParseGain(t *testing.T) { + for in, want := range map[string]*float64{ + "-6.54 dB": ptr(-6.54), + "+3.2 dB": ptr(3.2), + "-6.54": ptr(-6.54), + " 0.00 DB ": ptr(0), + "-6,54 dB": ptr(-6.54), + "": nil, + "loud": nil, + "NaN dB": nil, + "Inf": nil, + "99 dB": nil, // nobody tags a song that needs ninety-nine decibels + "-99 dB": nil, + } { + got := parseGain(in) + if (got == nil) != (want == nil) || (got != nil && *got != *want) { + t.Errorf("parseGain(%q) = %v, want %v", in, deref(got), deref(want)) + } + } +} + +func TestParsePeak(t *testing.T) { + for in, want := range map[string]*float64{ + "0.988553": ptr(0.988553), + " 1.0 ": ptr(1), + "1,25": ptr(1.25), + "0": nil, // a peak of nothing says nothing + "-0.5": nil, + "": nil, + "high": nil, + "Inf": nil, + "100000000": nil, + } { + got := parsePeak(in) + if (got == nil) != (want == nil) || (got != nil && *got != *want) { + t.Errorf("parsePeak(%q) = %v, want %v", in, deref(got), deref(want)) + } + } +} + +func ptr(v float64) *float64 { return &v } + +func deref(p *float64) any { + if p == nil { + return nil + } + return *p +} + +func TestTaglibReaderReplayGain(t *testing.T) { + dir := t.TempDir() + meta := map[string]string{ + "title": "a", + "REPLAYGAIN_TRACK_GAIN": "-6.54 dB", + "REPLAYGAIN_TRACK_PEAK": "0.988553", + "REPLAYGAIN_ALBUM_GAIN": "-7.10 dB", + "REPLAYGAIN_ALBUM_PEAK": "1.000000", + } + for _, name := range []string{"a.flac", "a.mp3"} { + t.Run(name, func(t *testing.T) { + m, err := TaglibReader{}.Read(makeAudio(t, dir, name, meta)) + if err != nil { + t.Fatal(err) + } + g := m.ReplayGain + if g.TrackGain == nil || *g.TrackGain != -6.54 || g.AlbumGain == nil || *g.AlbumGain != -7.10 { + t.Errorf("gains = %v, %v, want -6.54 and -7.1", deref(g.TrackGain), deref(g.AlbumGain)) + } + if g.TrackPeak == nil || *g.TrackPeak != 0.988553 || g.AlbumPeak == nil || *g.AlbumPeak != 1 { + t.Errorf("peaks = %v, %v, want 0.988553 and 1", deref(g.TrackPeak), deref(g.AlbumPeak)) + } + }) + } +} + +func TestTaglibReaderWithoutReplayGain(t *testing.T) { + m, err := TaglibReader{}.Read(makeAudio(t, t.TempDir(), "plain.flac", map[string]string{"title": "a"})) + if err != nil { + t.Fatal(err) + } + if m.ReplayGain != (ReplayGain{}) { + t.Errorf("a file with no ReplayGain tags has %+v", m.ReplayGain) + } +} diff --git a/internal/library/types.go b/internal/library/types.go index 500ccad..877c080 100644 --- a/internal/library/types.go +++ b/internal/library/types.go @@ -32,6 +32,15 @@ type Tags struct { TrackNo int DiscNo int Year int // the year the song came out (the original date first), 0 when the file has none or it is not a year + ReplayGain ReplayGain +} + +// ReplayGain is what the file says about its own loudness, read offline from its ReplayGain tags. A field the file +// lacks (or writes in a way that makes no sense) is nil. Gains are in decibels (what to add to play the song at the +// reference loudness); peaks are linear, 1 being the loudest a sample can be. +type ReplayGain struct { + TrackGain, AlbumGain *float64 + TrackPeak, AlbumPeak *float64 } // MinYear and MaxYear bound what is taken for the year of a song. diff --git a/internal/storage/catalog.go b/internal/storage/catalog.go index 4ccdbde..8ab122e 100644 --- a/internal/storage/catalog.go +++ b/internal/storage/catalog.go @@ -496,7 +496,9 @@ func (r *CatalogRepo) attachTrackDetails(ctx context.Context, page *catalog.Page } formats := map[int64]string{} - fq := "SELECT f.track_id, f.format FROM audio_files f WHERE f.track_id IN (?) AND f.missing_at IS NULL" + replayGains := map[int64]*catalog.ReplayGain{} + fq := `SELECT f.track_id, f.format, f.rg_track_gain, f.rg_album_gain, f.rg_track_peak, f.rg_album_peak + FROM audio_files f WHERE f.track_id IN (?) AND f.missing_at IS NULL` fargs := []any{bun.In(ids)} if r.sharedOnly { fq += " AND f.library_id IN (SELECT id FROM libraries WHERE shared = ?)" @@ -514,11 +516,13 @@ func (r *CatalogRepo) attachTrackDetails(ctx context.Context, page *catalog.Page for frows.Next() { var trackID int64 var format string - if err := frows.Scan(&trackID, &format); err != nil { + var tg, ag, tp, ap sql.NullFloat64 + if err := frows.Scan(&trackID, &format, &tg, &ag, &tp, &ap); err != nil { return err } if _, ok := formats[trackID]; !ok { // the first playable file wins formats[trackID] = normalizeFormat(format) + replayGains[trackID] = replayGainOf(tg, ag, tp, ap) } } if err := frows.Err(); err != nil { @@ -537,10 +541,27 @@ func (r *CatalogRepo) attachTrackDetails(ctx context.Context, page *catalog.Page t.Artists = c } t.Format = formats[t.ID] + t.ReplayGain = replayGains[t.ID] } return nil } +// replayGainOf is what a file says about its loudness, or nil when it says nothing. +func replayGainOf(trackGain, albumGain, trackPeak, albumPeak sql.NullFloat64) *catalog.ReplayGain { + g := catalog.ReplayGain{TrackGain: floatOf(trackGain), AlbumGain: floatOf(albumGain), TrackPeak: floatOf(trackPeak), AlbumPeak: floatOf(albumPeak)} + if g == (catalog.ReplayGain{}) { + return nil + } + return &g +} + +func floatOf(v sql.NullFloat64) *float64 { + if !v.Valid { + return nil + } + return &v.Float64 +} + // normalizeFormat shows TagLib's "mpeg" as the familiar "mp3". func normalizeFormat(f string) string { if f == "mpeg" { diff --git a/internal/storage/library.go b/internal/storage/library.go index c424bd0..26193f6 100644 --- a/internal/storage/library.go +++ b/internal/storage/library.go @@ -70,6 +70,11 @@ type audioFileModel struct { MTimeUnix int64 `bun:"mtime_unix,notnull"` SampleRate int `bun:"sample_rate,nullzero"` BitRate int `bun:"bitrate,nullzero"` + // What the file says about its loudness (its ReplayGain tags); NULL for what it does not say. + RGTrackGain sql.NullFloat64 `bun:"rg_track_gain"` + RGAlbumGain sql.NullFloat64 `bun:"rg_album_gain"` + RGTrackPeak sql.NullFloat64 `bun:"rg_track_peak"` + RGAlbumPeak sql.NullFloat64 `bun:"rg_album_peak"` // ContentHash is the SHA-256 of the file as it was when it was read for duplicates; empty until then. ContentHash sql.NullString `bun:"content_hash"` MissingAt sql.NullInt64 `bun:"missing_at"` @@ -208,9 +213,11 @@ func (r *LibraryRepo) SaveFile(ctx context.Context, libraryID int64, f library.P } file.Format, file.SizeBytes, file.MTimeUnix = f.Format, f.Size, f.MTimeUnix file.SampleRate, file.BitRate = f.SampleRate, f.BitRate + file.setReplayGain(f.ReplayGain) file.MissingAt = sql.NullInt64{} if _, err := tx.NewUpdate().Model(&file). - Column("format", "size_bytes", "mtime_unix", "sample_rate", "bitrate", "content_hash", "missing_at"). + Column("format", "size_bytes", "mtime_unix", "sample_rate", "bitrate", "content_hash", "missing_at", + "rg_track_gain", "rg_album_gain", "rg_track_peak", "rg_album_peak"). WherePK().Exec(ctx); err != nil { return fmt.Errorf("update audio file: %w", err) } @@ -226,10 +233,25 @@ func (r *LibraryRepo) SaveFile(ctx context.Context, libraryID int64, f library.P } func newAudioFile(libraryID int64, f library.ParsedFile, trackID int64) *audioFileModel { - return &audioFileModel{ + file := &audioFileModel{ TrackID: trackID, LibraryID: libraryID, RelPath: f.RelPath, Format: f.Format, SizeBytes: f.Size, MTimeUnix: f.MTimeUnix, SampleRate: f.SampleRate, BitRate: f.BitRate, } + file.setReplayGain(f.ReplayGain) + return file +} + +// setReplayGain keeps what the file says about its loudness; what it does not say is NULL. +func (f *audioFileModel) setReplayGain(g library.ReplayGain) { + f.RGTrackGain, f.RGAlbumGain = nullFloat(g.TrackGain), nullFloat(g.AlbumGain) + f.RGTrackPeak, f.RGAlbumPeak = nullFloat(g.TrackPeak), nullFloat(g.AlbumPeak) +} + +func nullFloat(v *float64) sql.NullFloat64 { + if v == nil { + return sql.NullFloat64{} + } + return sql.NullFloat64{Float64: *v, Valid: true} } // RenameFile points an indexed file at a new relative path and clears its missing flag. diff --git a/internal/storage/library_test.go b/internal/storage/library_test.go index c4fd9d3..ab48465 100644 --- a/internal/storage/library_test.go +++ b/internal/storage/library_test.go @@ -11,6 +11,7 @@ import ( "github.com/uptrace/bun" + "codeberg.org/squidd/sonda/internal/catalog" "codeberg.org/squidd/sonda/internal/library" "codeberg.org/squidd/sonda/internal/streaming" ) @@ -662,3 +663,71 @@ func TestLibraryRepoKeepsTheYearOfATrackAndUpdatesItOnARescan(t *testing.T) { } }) } + +func gainOf(v float64) *float64 { return &v } + +func TestLibraryRepoKeepsTheReplayGainOfAFileAndUpdatesItOnARescan(t *testing.T) { + forEachBackend(t, func(t *testing.T, db *bun.DB, _ string) { + ctx := context.Background() + repo := NewLibraryRepo(db) + lib := mkLib(t, repo, "music") + f := parsed("a/1.flac", "Song", "Album", "Radiohead") + f.ReplayGain = library.ReplayGain{TrackGain: gainOf(-6.5), AlbumGain: gainOf(-7), TrackPeak: gainOf(0.98), AlbumPeak: gainOf(1)} + if _, err := repo.SaveFile(ctx, lib, f, 0); err != nil { + t.Fatal(err) + } + read := func() (tg, ag, tp, ap sql.NullFloat64) { + if err := db.QueryRow("SELECT rg_track_gain, rg_album_gain, rg_track_peak, rg_album_peak FROM audio_files").Scan(&tg, &ag, &tp, &ap); err != nil { + t.Fatal(err) + } + return + } + tg, ag, tp, ap := read() + if tg.Float64 != -6.5 || ag.Float64 != -7 || tp.Float64 != 0.98 || ap.Float64 != 1 { + t.Fatalf("stored %v %v %v %v", tg, ag, tp, ap) + } + var fileID int64 + if err := db.QueryRow("SELECT id FROM audio_files").Scan(&fileID); err != nil { + t.Fatal(err) + } + f.ReplayGain = library.ReplayGain{TrackGain: gainOf(-3)} + if _, err := repo.SaveFile(ctx, lib, f, fileID); err != nil { + t.Fatal(err) + } + tg, ag, tp, ap = read() + if tg.Float64 != -3 || ag.Valid || tp.Valid || ap.Valid { + t.Errorf("after a rescan %v %v %v %v, want only the track gain, -3", tg, ag, tp, ap) + } + }) +} + +func TestTracksCarryTheReplayGainOfTheirFirstPlayableFile(t *testing.T) { + forEachBackend(t, func(t *testing.T, db *bun.DB, _ string) { + ctx := context.Background() + repo := NewLibraryRepo(db) + lib := mkLib(t, repo, "music") + tagged := parsed("a/1.flac", "Tagged", "Album", "Radiohead") + tagged.ReplayGain = library.ReplayGain{TrackGain: gainOf(-6.5), TrackPeak: gainOf(0.98)} + if _, err := repo.SaveFile(ctx, lib, tagged, 0); err != nil { + t.Fatal(err) + } + if _, err := repo.SaveFile(ctx, lib, parsed("a/2.flac", "Plain", "Album", "Radiohead"), 0); err != nil { + t.Fatal(err) + } + page, err := NewCatalogRepo(db).ListTracks(ctx, catalog.Filter{Limit: 10}) + if err != nil { + t.Fatal(err) + } + got := map[string]*catalog.ReplayGain{} + for _, tr := range page.Items { + got[tr.Title] = tr.ReplayGain + } + g := got["Tagged"] + if g == nil || g.TrackGain == nil || *g.TrackGain != -6.5 || g.TrackPeak == nil || *g.TrackPeak != 0.98 || g.AlbumGain != nil || g.AlbumPeak != nil { + t.Errorf("the tagged song has %+v", g) + } + if got["Plain"] != nil { + t.Errorf("a song with no ReplayGain tags has %+v, want none", got["Plain"]) + } + }) +} diff --git a/internal/storage/storage_test.go b/internal/storage/storage_test.go index 5dd8c7c..5aa4c9f 100644 --- a/internal/storage/storage_test.go +++ b/internal/storage/storage_test.go @@ -156,8 +156,8 @@ func TestMigrateCreatesSchemaAndIsIdempotent(t *testing.T) { if err := db.QueryRow("SELECT COUNT(*) FROM schema_migrations").Scan(&applied); err != nil { t.Fatal(err) } - if applied != 28 { - t.Errorf("applied migrations = %d, want 28", applied) + if applied != 29 { + t.Errorf("applied migrations = %d, want 29", applied) } }) } diff --git a/migrations/postgres/0029_replaygain.sql b/migrations/postgres/0029_replaygain.sql new file mode 100644 index 0000000..5f3652a --- /dev/null +++ b/migrations/postgres/0029_replaygain.sql @@ -0,0 +1,6 @@ +-- PostgreSQL flavour of sqlite/0029_replaygain.sql. + +ALTER TABLE audio_files ADD COLUMN rg_track_gain DOUBLE PRECISION; +ALTER TABLE audio_files ADD COLUMN rg_album_gain DOUBLE PRECISION; +ALTER TABLE audio_files ADD COLUMN rg_track_peak DOUBLE PRECISION; +ALTER TABLE audio_files ADD COLUMN rg_album_peak DOUBLE PRECISION; diff --git a/migrations/sqlite/0029_replaygain.sql b/migrations/sqlite/0029_replaygain.sql new file mode 100644 index 0000000..80795af --- /dev/null +++ b/migrations/sqlite/0029_replaygain.sql @@ -0,0 +1,8 @@ +-- What a file says about its own loudness, from its ReplayGain tags: gains in decibels, peaks as a fraction of full +-- scale. NULL when the file has none, and for the files already indexed until a full rescan reads their tags again. +-- The web player uses them to play every song at a similar volume. + +ALTER TABLE audio_files ADD COLUMN rg_track_gain REAL; +ALTER TABLE audio_files ADD COLUMN rg_album_gain REAL; +ALTER TABLE audio_files ADD COLUMN rg_track_peak REAL; +ALTER TABLE audio_files ADD COLUMN rg_album_peak REAL; diff --git a/web/src/api/schema.d.ts b/web/src/api/schema.d.ts index 62d3005..380b861 100644 --- a/web/src/api/schema.d.ts +++ b/web/src/api/schema.d.ts @@ -2908,6 +2908,17 @@ export interface components { artists: components["schemas"]["ArtistRef"][]; /** @description Format of the first playable file, for example `mp3` or `flac`. */ format: string; + /** @description What the first playable file says about its own loudness, from its ReplayGain tags; null when it says nothing. A player can use it to play every song at a similar volume. Files indexed before this existed have none until a full rescan (`POST /library/scan?full=true`) reads their tags again. */ + replay_gain?: { + /** @description Decibels to add to play this song at the reference loudness. */ + track_gain_db: number | null; + /** @description The same for the whole album, which keeps the differences between its songs. */ + album_gain_db: number | null; + /** @description The loudest sample of the song, 1 being full scale. */ + track_peak: number | null; + /** @description The loudest sample of the album, 1 being full scale. */ + album_peak: number | null; + } | null; }; ArtistPage: { items: components["schemas"]["Artist"][]; diff --git a/web/src/i18n/locales/en.json b/web/src/i18n/locales/en.json index 67602fd..15ea7fe 100644 --- a/web/src/i18n/locales/en.json +++ b/web/src/i18n/locales/en.json @@ -93,6 +93,12 @@ "visualizerScope": "Oscilloscope", "visualizerMilkdrop": "Milkdrop", "visualizerOff": "None", + "playback": "Playback", + "replayGain": "Even out the volume", + "replayGainHelp": "Quiet and loud songs play at about the same volume, using the ReplayGain tags in your files (a song without them plays as it is). Album by album keeps the differences between the songs of an album. Files added before need a full rescan to be read for these tags. The choice stays on this device.", + "replayGainTrack": "Song by song", + "replayGainAlbum": "Album by album", + "replayGainOff": "Off", "password": "Password", "currentPassword": "Current password", "newPassword": "New password", diff --git a/web/src/i18n/locales/it.json b/web/src/i18n/locales/it.json index e868132..b7162c7 100644 --- a/web/src/i18n/locales/it.json +++ b/web/src/i18n/locales/it.json @@ -93,6 +93,12 @@ "visualizerScope": "Oscilloscopio", "visualizerMilkdrop": "Milkdrop", "visualizerOff": "Nessuna", + "playback": "Riproduzione", + "replayGain": "Uniforma il volume", + "replayGainHelp": "I brani piano e quelli forti suonano più o meno allo stesso volume, secondo i tag ReplayGain dei tuoi file (un brano senza tag suona così com'è). «Album per album» mantiene le differenze tra i brani di un album. I file aggiunti prima vanno riscansionati per intero per leggerne i tag. La scelta resta su questo dispositivo.", + "replayGainTrack": "Brano per brano", + "replayGainAlbum": "Album per album", + "replayGainOff": "Disattivato", "password": "Password", "currentPassword": "Password attuale", "newPassword": "Nuova password", diff --git a/web/src/pages/SettingsPage.test.tsx b/web/src/pages/SettingsPage.test.tsx index 481b557..db72a26 100644 --- a/web/src/pages/SettingsPage.test.tsx +++ b/web/src/pages/SettingsPage.test.tsx @@ -5,6 +5,7 @@ import { MemoryRouter } from 'react-router-dom' import { beforeEach, expect, test, vi } from 'vitest' import { sessionStore } from '@/auth/session' import { initI18n } from '@/i18n' +import { useReplayGainPref } from '@/player/replayGain' import { useVisualizerPref } from '@/player/prefs' import { usePlayer } from '@/player/store' import { apiError, mockFetch } from '@/test/mockFetch' @@ -31,6 +32,8 @@ beforeEach(async () => { initTheme() localStorage.removeItem('sonda.visualizer') useVisualizerPref.setState({ mode: 'spectrogram' }) + localStorage.removeItem('sonda.replaygain') + useReplayGainPref.setState({ mode: 'track' }) sessionStore.setState({ status: 'authenticated', user: { id: 1, email: 'tom@example.org', is_admin: true }, @@ -212,6 +215,20 @@ test('the picture of the sound in the player is chosen from five, and the choice expect(localStorage.getItem('sonda.visualizer')).toBe('off') }) +test('the volume can be evened out song by song or album by album, and the choice stays on this device', async () => { + renderSettings() + const group = screen.getByRole('radiogroup', { name: 'Even out the volume' }) + const names = within(group).getAllByRole('radio').map((r) => r.closest('label')?.textContent) + expect(names).toEqual(['Song by song', 'Album by album', 'Off']) + expect(within(group).getByRole('radio', { name: 'Song by song' })).toBeChecked() + await userEvent.click(within(group).getByRole('radio', { name: 'Album by album' })) + expect(within(group).getByRole('radio', { name: 'Album by album' })).toBeChecked() + expect(localStorage.getItem('sonda.replaygain')).toBe('album') + await userEvent.click(within(group).getByRole('radio', { name: 'Off' })) + expect(localStorage.getItem('sonda.replaygain')).toBe('off') + expect(useReplayGainPref.getState().mode).toBe('off') +}) + test('there is a place to connect a Mastodon account, off until it is connected', async () => { renderSettings() const section = await screen.findByRole('region', { name: 'Mastodon' }) diff --git a/web/src/pages/SettingsPage.tsx b/web/src/pages/SettingsPage.tsx index e62b165..a6211bb 100644 --- a/web/src/pages/SettingsPage.tsx +++ b/web/src/pages/SettingsPage.tsx @@ -13,6 +13,7 @@ import { Label } from '@/components/ui/label' import { errorMessageKey, useLanguage, type Lang } from '@/i18n' import { usePlayer } from '@/player/store' import { VISUALIZERS, type Visualizer, useVisualizerPref } from '@/player/prefs' +import { REPLAY_GAIN_MODES, type ReplayGainMode, useReplayGainPref } from '@/player/replayGain' import { THEMES, useTheme, type ThemeId } from '@/theme/theme' import PageTitle from '@/components/PageTitle' @@ -108,6 +109,7 @@ export default function SettingsPage() { const { lang, setLanguage } = useLanguage() const app = useInstall() const visualizer = useVisualizerPref() + const replayGain = useReplayGainPref() return (
@@ -152,6 +154,18 @@ export default function SettingsPage() {
+
+
+ + label={t('settings.replayGain')} + value={replayGain.mode} + onChange={replayGain.setMode} + choices={REPLAY_GAIN_MODES.map((mode) => ({ value: mode, label: t(`settings.replayGain${mode[0].toUpperCase()}${mode.slice(1)}`) }))} + /> +

{t('settings.replayGainHelp')}

+
+
+ {app.available && (

{t('pwa.installIntro')}

diff --git a/web/src/player/analyser.test.ts b/web/src/player/analyser.test.ts index 35bfde0..23ff90b 100644 --- a/web/src/player/analyser.test.ts +++ b/web/src/player/analyser.test.ts @@ -1,5 +1,5 @@ import { afterEach, beforeEach, expect, test, vi } from 'vitest' -import { attachAnalyser, hasAnalyser, listenTo, readBins, readWave, resetAnalyser } from './analyser' +import { attachAnalyser, hasAnalyser, listenTo, readBins, readWave, resetAnalyser, setOutputGain } from './analyser' function fakeContext() { const analyser = { @@ -12,13 +12,16 @@ function fakeContext() { getByteFrequencyData: vi.fn((bins: Uint8Array) => bins.fill(7)), getByteTimeDomainData: vi.fn((wave: Uint8Array) => wave.fill(200)), } + const gain = { gain: { value: 1 }, connect: vi.fn() } + const source = { connect: vi.fn() } class FakeContext { destination = {} createAnalyser = () => analyser - createMediaElementSource = () => ({ connect: vi.fn() }) + createGain = () => gain + createMediaElementSource = () => source resume = vi.fn() } - return { Context: FakeContext, analyser } + return { Context: FakeContext, analyser, gain, source } } beforeEach(() => resetAnalyser()) @@ -57,3 +60,29 @@ test('where the browser has no Web Audio nothing listens and nothing breaks', () expect(() => attachAnalyser(document.createElement('audio'))).not.toThrow() expect(hasAnalyser()).toBe(false) }) + +test('the sound goes through a gain on its way to the analyser, so a song can be leveled', () => { + const { Context, analyser, gain, source } = fakeContext() + vi.stubGlobal('AudioContext', Context) + attachAnalyser(document.createElement('audio')) + expect(source.connect).toHaveBeenCalledWith(gain) + expect(gain.connect).toHaveBeenCalledWith(analyser) + expect(analyser.connect).toHaveBeenCalled() +}) + +test('the output gain is taken by the node once the audio is attached', () => { + const { Context, gain } = fakeContext() + vi.stubGlobal('AudioContext', Context) + expect(setOutputGain(0.5)).toBe(false) // nothing to take it yet: the caller must level the sound itself + attachAnalyser(document.createElement('audio')) + expect(gain.gain.value).toBe(0.5) // asked before, applied at the attach + expect(setOutputGain(1.5)).toBe(true) + expect(gain.gain.value).toBe(1.5) +}) + +test('where there is no Web Audio the output gain is not taken', () => { + vi.stubGlobal('AudioContext', undefined) + vi.stubGlobal('webkitAudioContext', undefined) + attachAnalyser(document.createElement('audio')) + expect(setOutputGain(0.5)).toBe(false) +}) diff --git a/web/src/player/analyser.ts b/web/src/player/analyser.ts index 9b9f981..b984d35 100644 --- a/web/src/player/analyser.ts +++ b/web/src/player/analyser.ts @@ -4,12 +4,16 @@ * did something), and it only listens: the sound goes on to the speakers unchanged. Where the browser has no Web * Audio there is no analyser and the pictures stay quiet. * + * The sound also passes through a gain, which levels songs by their ReplayGain (`setOutputGain`): an audio element can + * only be turned down, and this can also raise a quiet song. + * * The audio comes from this server for every track, a friend's included, so it is never cross-origin and the analyser * is never given silence for that reason. */ interface Ear { context: AudioContext + gain: GainNode analyser: AnalyserNode bins: Uint8Array wave: Uint8Array @@ -17,6 +21,8 @@ interface Ear { let ear: Ear | null = null let tried = false +/** What the sound is multiplied by; asked for before the audio is attached, it is applied when it is. */ +let wantedGain = 1 type AudioContextConstructor = typeof AudioContext @@ -36,16 +42,31 @@ export function attachAnalyser(audio: HTMLMediaElement): void { const analyser = context.createAnalyser() analyser.fftSize = 512 analyser.smoothingTimeConstant = 0.6 + const gain = context.createGain() + gain.gain.value = wantedGain const source = context.createMediaElementSource(audio) - source.connect(analyser) + source.connect(gain) + gain.connect(analyser) analyser.connect(context.destination) - ear = { context, analyser, bins: new Uint8Array(analyser.frequencyBinCount), wave: new Uint8Array(analyser.fftSize) } + ear = { context, gain, analyser, bins: new Uint8Array(analyser.frequencyBinCount), wave: new Uint8Array(analyser.fftSize) } void context.resume?.() } catch { ear = null // the sound plays as it did, without the picture } } +/** + * Multiplies the sound by this much from now on. Returns true when the gain of the audio graph took it; false when + * there is none (the audio is not attached yet, or the browser has no Web Audio), and then the caller has to level the + * sound some other way. Asked before the audio is attached, it is applied when it is. + */ +export function setOutputGain(factor: number): boolean { + wantedGain = factor + if (!ear) return false + ear.gain.gain.value = factor + return true +} + /** How loud each pitch is now (0 to 255 for each of the bins, lowest first), or null when nothing listens. */ export function readBins(): Uint8Array | null { if (!ear) return null @@ -74,4 +95,5 @@ export function hasAnalyser(): boolean { export function resetAnalyser(): void { ear = null tried = false + wantedGain = 1 } diff --git a/web/src/player/engine.test.ts b/web/src/player/engine.test.ts index 232a1a6..3f2ce45 100644 --- a/web/src/player/engine.test.ts +++ b/web/src/player/engine.test.ts @@ -1,13 +1,18 @@ import { afterEach, beforeEach, expect, test, vi } from 'vitest' +import { setOutputGain } from './analyser' import type { Track } from '@/api/catalog' import { login, sessionStore } from '@/auth/session' import { mockFetch } from '@/test/mockFetch' import { createEngine, type AudioLike } from './engine' +import { useReplayGainPref } from './replayGain' import { usePlayer } from './store' -type AudioEvent = 'timeupdate' | 'ended' | 'error' | 'loadedmetadata' +type AudioEvent = 'timeupdate' | 'ended' | 'error' | 'loadedmetadata' | 'play' /** A stand-in for the audio element: it keeps what was set and lets a test fire the events. */ +// The engine only needs the gain of the audio graph, and a test has no Web Audio: it is told whether the node took it. +vi.mock('./analyser', () => ({ setOutputGain: vi.fn(() => false) })) + class FakeAudio implements AudioLike { currentTime = 0 duration = Number.NaN @@ -95,6 +100,9 @@ beforeEach(async () => { muted: false, }) sessionStore.setState({ status: 'anonymous', user: null, accessToken: null, accessExpiresAt: 0, refreshToken: null }) + vi.mocked(setOutputGain).mockClear() + vi.mocked(setOutputGain).mockReturnValue(false) + useReplayGainPref.setState({ mode: 'track' }) hooks.onStart.mockClear() hooks.onPlayed.mockClear() hooks.onFinish.mockClear() @@ -341,3 +349,64 @@ test('a renewed token keeps a friend’s track playing from the same second', as expect(audio.currentTime).toBe(42) expect(hooks.onStart).not.toHaveBeenCalled() }) + +const leveled = (n: number, gain: Partial>): Track => ({ + ...track(n), + replay_gain: { track_gain_db: null, album_gain_db: null, track_peak: null, album_peak: null, ...gain }, +}) + +test('a song with ReplayGain is turned down by its gain, on top of the volume', () => { + usePlayer.getState().playTracks([leveled(1, { track_gain_db: -6 })]) + expect(audio.volume).toBeCloseTo(0.501, 3) + usePlayer.getState().setVolume(0.5) + expect(audio.volume).toBeCloseTo(0.251, 3) +}) + +test('the audio element can only be turned down, so a raise is left to the audio graph', () => { + usePlayer.getState().playTracks([leveled(1, { track_gain_db: 6, track_peak: 0.5 })]) + expect(audio.volume).toBe(1) + expect(setOutputGain).toHaveBeenLastCalledWith(expect.closeTo(1.995, 3)) +}) + +test('when the audio graph takes the gain the element plays at the volume of the player', () => { + vi.mocked(setOutputGain).mockReturnValue(true) + usePlayer.getState().playTracks([leveled(1, { track_gain_db: -6 })]) + expect(audio.volume).toBe(1) + expect(setOutputGain).toHaveBeenLastCalledWith(expect.closeTo(0.501, 3)) +}) + +test('the graph is attached when the audio first plays: the level is set again then', () => { + usePlayer.getState().playTracks([leveled(1, { track_gain_db: -6 })]) + expect(audio.volume).toBeCloseTo(0.501, 3) // nothing took the gain yet: the element did + vi.mocked(setOutputGain).mockReturnValue(true) + audio.emit('play') + expect(audio.volume).toBe(1) // now the node does, and the element is not turned down twice +}) + +test('each song is leveled by its own gain, and one with none plays as it is', () => { + usePlayer.getState().playTracks([leveled(1, { track_gain_db: -6 }), t2, leveled(3, { track_gain_db: -3 })]) + expect(audio.volume).toBeCloseTo(0.501, 3) + usePlayer.getState().next() + expect(audio.volume).toBe(1) + usePlayer.getState().next() + expect(audio.volume).toBeCloseTo(0.708, 3) +}) + +test('the album gain is used when that is what the listener chose, and nothing when it is off', () => { + usePlayer.getState().playTracks([leveled(1, { track_gain_db: -6, album_gain_db: -3 })]) + expect(audio.volume).toBeCloseTo(0.501, 3) + useReplayGainPref.getState().setMode('album') + expect(audio.volume).toBeCloseTo(0.708, 3) + useReplayGainPref.getState().setMode('off') + expect(audio.volume).toBe(1) +}) + +test('nothing in the audio is left behind once the engine is gone', () => { + const before = audio.listenerCount() + expect(before).toBeGreaterThan(0) + engine.destroy() + expect(audio.listenerCount()).toBe(0) + vi.mocked(setOutputGain).mockClear() + useReplayGainPref.getState().setMode('album') + expect(setOutputGain).not.toHaveBeenCalled() +}) diff --git a/web/src/player/engine.ts b/web/src/player/engine.ts index 81995de..c03f456 100644 --- a/web/src/player/engine.ts +++ b/web/src/player/engine.ts @@ -1,8 +1,10 @@ import { mediaUrl, onTokenChange } from '@/auth/session' import { streamPath, trackKey, type QueuedTrack } from './media' +import { setOutputGain } from './analyser' +import { replayGainFactor, useReplayGainPref } from './replayGain' import { currentTrack, usePlayer, type PlayerState } from './store' -export type AudioEvent = 'timeupdate' | 'ended' | 'error' | 'loadedmetadata' +export type AudioEvent = 'timeupdate' | 'ended' | 'error' | 'loadedmetadata' | 'play' /** The part of an audio element the engine uses, so that tests can stand in for it. */ export interface AudioLike { @@ -51,6 +53,16 @@ export function createEngine(audio: AudioLike, hooks: EngineHooks = {}): { destr let lastTime = 0 let pendingRestore: { time: number; resume: boolean } | null = null + /** + * How loud the audio is: the volume of the player, leveled by the ReplayGain of the song that plays. The audio + * graph does the leveling when there is one (it can raise a quiet song too); until then, and where the browser + * has no Web Audio, the element is turned down by it, which is all an element can do. + */ + function level(state: PlayerState) { + const factor = replayGainFactor(currentTrack(state)?.replay_gain, useReplayGainPref.getState().mode) + audio.volume = setOutputGain(factor) ? state.volume : state.volume * Math.min(1, factor) + } + function play() { audio.play().catch(() => usePlayer.setState({ playing: false })) // the browser refused: wait for a click } @@ -63,6 +75,7 @@ export function createEngine(audio: AudioLike, hooks: EngineHooks = {}): { destr pendingRestore = null playedMs = 0 lastTime = 0 + level(state) if (!track) { audio.pause() audio.src = '' @@ -94,7 +107,7 @@ export function createEngine(audio: AudioLike, hooks: EngineHooks = {}): { destr } function sync(state: PlayerState, previous: PlayerState) { - if (state.volume !== previous.volume) audio.volume = state.volume + if (state.volume !== previous.volume) level(state) if (state.muted !== previous.muted) audio.muted = state.muted const track = currentTrack(state) if ((track ? trackKey(track) : null) !== (loaded ? trackKey(loaded) : null) || state.playId !== loadedPlayId) { @@ -109,9 +122,13 @@ export function createEngine(audio: AudioLike, hooks: EngineHooks = {}): { destr } // The audio starts at the volume the player remembers; after that it follows every change. - audio.volume = initial.volume + level(initial) audio.muted = initial.muted const unsubscribeStore = usePlayer.subscribe(sync) + const unsubscribeLeveling = useReplayGainPref.subscribe(() => level(usePlayer.getState())) + // The audio graph is attached when the audio first plays: from then on it does the leveling. + const onPlay = () => level(usePlayer.getState()) + audio.addEventListener('play', onPlay) sync(initial, { ...initial, queue: [], playId: initial.playId - 1 }) const unsubscribeToken = onTokenChange(() => { @@ -158,6 +175,8 @@ export function createEngine(audio: AudioLike, hooks: EngineHooks = {}): { destr return { destroy() { unsubscribeStore() + unsubscribeLeveling() + audio.removeEventListener('play', onPlay) unsubscribeToken() audio.removeEventListener('loadedmetadata', onLoadedMetadata) audio.removeEventListener('timeupdate', onTimeUpdate) diff --git a/web/src/player/replayGain.test.ts b/web/src/player/replayGain.test.ts new file mode 100644 index 0000000..c0d431f --- /dev/null +++ b/web/src/player/replayGain.test.ts @@ -0,0 +1,74 @@ +import { beforeEach, expect, test } from 'vitest' +import { readReplayGainMode, replayGainFactor, useReplayGainPref } from './replayGain' + +const db = (factor: number) => 20 * Math.log10(factor) +const tagged = { track_gain_db: -6, album_gain_db: -3, track_peak: 0.9, album_peak: 1 } + +test('a song with no ReplayGain, or with the leveling off, plays as it is', () => { + expect(replayGainFactor(null, 'track')).toBe(1) + expect(replayGainFactor(undefined, 'album')).toBe(1) + expect(replayGainFactor(tagged, 'off')).toBe(1) + expect(replayGainFactor({ track_gain_db: null, album_gain_db: null, track_peak: 0.5, album_peak: 0.5 }, 'track')).toBe(1) +}) + +test('the gain is a number of decibels turned into a factor', () => { + expect(db(replayGainFactor({ ...tagged, track_gain_db: -6 }, 'track'))).toBeCloseTo(-6) + expect(db(replayGainFactor({ ...tagged, track_gain_db: 0 }, 'track'))).toBeCloseTo(0) +}) + +test('the track mode uses the gain of the song and the album mode the gain of the album', () => { + expect(db(replayGainFactor({ ...tagged, track_gain_db: -6, album_gain_db: -3 }, 'track'))).toBeCloseTo(-6) + expect(db(replayGainFactor({ ...tagged, track_gain_db: -6, album_gain_db: -3 }, 'album'))).toBeCloseTo(-3) +}) + +test('when the one asked for is missing, the other is better than nothing', () => { + expect(db(replayGainFactor({ ...tagged, track_gain_db: null, album_gain_db: -3 }, 'track'))).toBeCloseTo(-3) + expect(db(replayGainFactor({ ...tagged, track_gain_db: -6, album_gain_db: null }, 'album'))).toBeCloseTo(-6) +}) + +test('a quiet song is raised, but never so much that its loudest sample would clip', () => { + // +6 dB is a factor of 2; with a peak of 0.8 the most the song can be raised is 1 / 0.8. + const f = replayGainFactor({ track_gain_db: 6, album_gain_db: null, track_peak: 0.8, album_peak: null }, 'track') + expect(f).toBeCloseTo(1.25) + // A peak that leaves room is no limit. + expect(db(replayGainFactor({ track_gain_db: 2, album_gain_db: null, track_peak: 0.5, album_peak: null }, 'track'))).toBeCloseTo(2) +}) + +test('a peak limits only the gain it belongs to', () => { + // The album gain is used, so the album peak limits it, not the song's. + const f = replayGainFactor({ track_gain_db: 6, album_gain_db: 6, track_peak: 0.5, album_peak: 0.9 }, 'album') + expect(f).toBeCloseTo(1 / 0.9) +}) + +test('a gain with no peak to check it is held to twelve decibels', () => { + expect(db(replayGainFactor({ track_gain_db: 20, album_gain_db: null, track_peak: null, album_peak: null }, 'track'))).toBeCloseTo(12, 0) +}) + +test('a song that is already over full scale is left as it is, not cut for a raise it asked for', () => { + expect(replayGainFactor({ track_gain_db: 3, album_gain_db: null, track_peak: 1.4, album_peak: null }, 'track')).toBe(1) +}) + +test('a cut is never held back by the peak', () => { + expect(db(replayGainFactor({ track_gain_db: -9, album_gain_db: null, track_peak: 1.4, album_peak: null }, 'track'))).toBeCloseTo(-9) +}) + +beforeEach(() => { + localStorage.clear() + useReplayGainPref.setState({ mode: 'track' }) +}) + +test('songs are leveled one by one until another choice is made', () => { + expect(readReplayGainMode()).toBe('track') + expect(useReplayGainPref.getState().mode).toBe('track') +}) + +test('the choice is remembered on this device, and only a known one is believed', () => { + useReplayGainPref.getState().setMode('album') + expect(useReplayGainPref.getState().mode).toBe('album') + expect(localStorage.getItem('sonda.replaygain')).toBe('album') + expect(readReplayGainMode()).toBe('album') + useReplayGainPref.getState().setMode('off') + expect(readReplayGainMode()).toBe('off') + localStorage.setItem('sonda.replaygain', 'loud') + expect(readReplayGainMode()).toBe('track') +}) diff --git a/web/src/player/replayGain.ts b/web/src/player/replayGain.ts new file mode 100644 index 0000000..db95dcb --- /dev/null +++ b/web/src/player/replayGain.ts @@ -0,0 +1,59 @@ +import { create } from 'zustand' +import type { Track } from '@/api/catalog' + +const KEY = 'sonda.replaygain' + +/** How the player levels the songs: by the gain of each song, by the gain of its album, or not at all. */ +export const REPLAY_GAIN_MODES = ['track', 'album', 'off'] as const +export type ReplayGainMode = (typeof REPLAY_GAIN_MODES)[number] + +function isMode(value: string | null): value is ReplayGainMode { + return REPLAY_GAIN_MODES.some((m) => m === value) +} + +/** What this device chose: one song at a time until something else is picked. */ +export function readReplayGainMode(): ReplayGainMode { + try { + const saved = localStorage.getItem(KEY) + if (isMode(saved)) return saved + } catch { + // Nothing is kept here: the default applies. + } + return 'track' +} + +/** How the player levels the songs. A choice of this device, like the theme. */ +export const useReplayGainPref = create<{ mode: ReplayGainMode; setMode(mode: ReplayGainMode): void }>()((set) => ({ + mode: readReplayGainMode(), + setMode: (mode) => { + set({ mode }) + try { + localStorage.setItem(KEY, mode) + } catch { + // The choice still applies for this page view. + } + }, +})) + +/** The most a song is raised when its file gives no peak to check it against: twelve decibels. */ +const MAX_UNCHECKED_FACTOR = 4 + +/** + * What to multiply the sound of a song by to level it: 1 when the leveling is off or the file says nothing about its + * loudness. A gain is in decibels. The gain asked for is used (the song's in `track`, the album's in `album`) and, when + * the file lacks it, the other one: better than nothing. A raise is held where the loudest sample of the song would + * reach full scale (the peak that goes with the gain used), and to twelve decibels when there is no peak; a cut + * is never held back. + */ +export function replayGainFactor(gain: Track['replay_gain'] | undefined, mode: ReplayGainMode): number { + if (!gain || mode === 'off') return 1 + const track = { db: gain.track_gain_db, peak: gain.track_peak } + const album = { db: gain.album_gain_db, peak: gain.album_peak } + const [first, second] = mode === 'album' ? [album, track] : [track, album] + const used = first.db != null ? first : second + if (used.db == null) return 1 + const factor = 10 ** (used.db / 20) + if (factor <= 1) return factor + // A song already over full scale is not raised, and not cut for it either. + return Math.max(1, Math.min(factor, used.peak != null && used.peak > 0 ? 1 / used.peak : MAX_UNCHECKED_FACTOR)) +} diff --git a/web/src/player/usePlayer.ts b/web/src/player/usePlayer.ts index 1ffe95a..94dca2a 100644 --- a/web/src/player/usePlayer.ts +++ b/web/src/player/usePlayer.ts @@ -15,7 +15,8 @@ import { currentTrack, usePlayer } from './store' export function usePlayerEngine(): void { useEffect(() => { const audio = new Audio() - // The spectrogram listens to the sound: the analyser is connected when something first plays. + // The spectrogram listens to the sound: the analyser is connected when something first plays. This has to come + // before the engine's own listener of `play`, which levels the sound with the gain of that same graph. const onPlay = () => attachAnalyser(audio) audio.addEventListener('play', onPlay) const reporter = createListenReporter({