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:
tgiachi 2026-11-14 16:02:23 +01:00
commit a92326c1b4
12 changed files with 672 additions and 23 deletions

View file

@ -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"][];

View file

@ -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",

View file

@ -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",

View file

@ -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' })

View file

@ -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 (
<div className="flex flex-col gap-10">
@ -152,6 +154,18 @@ export default function SettingsPage() {
</div>
</Section>
<Section title={t('settings.playback')}>
<div className="flex max-w-xl flex-col gap-2">
<ChoiceGroup<ReplayGainMode>
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)}`) }))}
/>
<p className="text-sm text-muted-foreground">{t('settings.replayGainHelp')}</p>
</div>
</Section>
{app.available && (
<Section title={t('settings.app')}>
<p className="text-muted-foreground">{t('pwa.installIntro')}</p>

View file

@ -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)
})

View file

@ -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<ArrayBuffer>
wave: Uint8Array<ArrayBuffer>
@ -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
}

View file

@ -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<NonNullable<Track['replay_gain']>>): 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()
})

View file

@ -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)

View file

@ -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')
})

View file

@ -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))
}

View file

@ -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({