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.
This commit is contained in:
parent
e9f85c2f39
commit
a92326c1b4
13 changed files with 672 additions and 23 deletions
|
|
@ -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)
|
||||
}
|
||||
|
|
|
|||
|
|
@ -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)
|
||||
}
|
||||
|
|
|
|||
|
|
@ -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
|
||||
}
|
||||
|
||||
|
|
|
|||
|
|
@ -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)
|
||||
}
|
||||
|
|
|
|||
|
|
@ -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
|
||||
|
|
|
|||
|
|
@ -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
|
||||
|
|
|
|||
|
|
@ -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
|
||||
|
||||
|
|
|
|||
|
|
@ -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)
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -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.
|
||||
|
|
|
|||
|
|
@ -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" {
|
||||
|
|
|
|||
|
|
@ -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.
|
||||
|
|
|
|||
|
|
@ -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"])
|
||||
}
|
||||
})
|
||||
}
|
||||
|
|
|
|||
|
|
@ -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)
|
||||
}
|
||||
})
|
||||
}
|
||||
|
|
|
|||
Loading…
Reference in a new issue