sonda/web/src/player/engine.test.ts
tgiachi a92326c1b4 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.
2026-11-14 16:02:23 +01:00

412 lines
14 KiB
TypeScript
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

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' | '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
paused = true
volume = 1
muted = false
playCalls = 0
private url = ''
private handlers = new Map<string, Set<() => void>>()
get src() {
return this.url
}
set src(value: string) {
this.url = value
this.currentTime = 0 // a new resource starts over, and loading pauses the element
this.paused = true
}
async play() {
this.playCalls++
this.paused = false
}
pause() {
this.paused = true
}
addEventListener(type: AudioEvent, fn: () => void) {
if (!this.handlers.has(type)) this.handlers.set(type, new Set())
this.handlers.get(type)!.add(fn)
}
removeEventListener(type: string, fn: () => void) {
this.handlers.get(type)?.delete(fn)
}
emit(type: AudioEvent) {
this.handlers.get(type)?.forEach((fn) => fn())
}
listenerCount() {
return [...this.handlers.values()].reduce((n, set) => n + set.size, 0)
}
}
function track(n: number): Track {
return {
id: n,
title: `t${n}`,
duration_ms: 200_000,
track_no: n,
disc_no: 1,
album: null,
artists: [],
format: 'mp3',
}
}
const [t1, t2, t3] = [1, 2, 3].map(track)
/** A track of a friend's server: the same shape, the friend's own id, and the friend's number. */
const theirs = (n: number, friend = 3) => ({ ...track(n), friend })
function session(access: string) {
return {
access_token: access,
access_expires_at: new Date(Date.now() + 900_000).toISOString(),
refresh_token: `r-${access}`,
refresh_expires_at: new Date(Date.now() + 86_400_000).toISOString(),
user: { id: 1, email: 'tom@example.org', is_admin: false },
}
}
let audio: FakeAudio
let engine: { destroy(): void }
const hooks = { onStart: vi.fn(), onPlayed: vi.fn(), onFinish: vi.fn() }
beforeEach(async () => {
usePlayer.setState({
queue: [],
original: [],
index: 0,
playing: false,
positionMs: 0,
shuffle: false,
repeat: 'off',
seekMs: null,
seekId: 0,
playId: 0,
volume: 1,
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()
mockFetch({ 'POST /api/v1/auth/login': () => session('tok1') })
await login('tom', 'secret123')
audio = new FakeAudio()
engine = createEngine(audio, hooks)
})
afterEach(() => {
engine.destroy()
})
test('the audio starts at the volume of the player, muted or not', () => {
usePlayer.setState({ volume: 0.3, muted: true })
const other = new FakeAudio()
const second = createEngine(other, hooks)
expect(other.volume).toBe(0.3)
expect(other.muted).toBe(true)
second.destroy()
})
test('moving the volume changes the audio at once, also while it plays', () => {
usePlayer.getState().playTracks([t1])
usePlayer.getState().setVolume(0.2)
expect(audio.volume).toBe(0.2)
expect(audio.muted).toBe(false)
})
test('mute silences the audio and keeps its level, and unmute brings it back', () => {
usePlayer.getState().setVolume(0.6)
usePlayer.getState().toggleMute()
expect(audio.muted).toBe(true)
expect(audio.volume).toBe(0.6)
usePlayer.getState().toggleMute()
expect(audio.muted).toBe(false)
expect(audio.volume).toBe(0.6)
})
test('once the engine is gone the audio is left alone', () => {
engine.destroy()
usePlayer.getState().setVolume(0.1)
expect(audio.volume).toBe(1)
})
test('the current track is loaded from its stream URL with the token and played', () => {
usePlayer.getState().playTracks([t1, t2])
expect(audio.src).toBe('/api/v1/tracks/1/stream?access_token=tok1')
expect(audio.paused).toBe(false)
expect(hooks.onStart).toHaveBeenCalledWith(1)
})
test('pause and play follow the player', () => {
usePlayer.getState().playTracks([t1])
usePlayer.getState().togglePlay()
expect(audio.paused).toBe(true)
usePlayer.getState().togglePlay()
expect(audio.paused).toBe(false)
})
test('a seek moves the audio', () => {
usePlayer.getState().playTracks([t1])
usePlayer.getState().seek(42_000)
expect(audio.currentTime).toBe(42)
})
test('the position of the player follows the audio', () => {
usePlayer.getState().playTracks([t1])
audio.currentTime = 12.5
audio.emit('timeupdate')
expect(usePlayer.getState().positionMs).toBe(12_500)
})
test('a renewed token while a track plays keeps it playing from the same second', async () => {
usePlayer.getState().playTracks([t1])
audio.currentTime = 42
mockFetch({ 'POST /api/v1/auth/login': () => session('tok2') })
await login('tom', 'secret123')
expect(audio.src).toBe('/api/v1/tracks/1/stream?access_token=tok2')
const playsBefore = audio.playCalls
audio.emit('loadedmetadata')
expect(audio.currentTime).toBe(42)
expect(audio.paused).toBe(false)
expect(audio.playCalls).toBe(playsBefore + 1)
expect(hooks.onStart).toHaveBeenCalledTimes(1) // the same play, not a new one
})
test('a renewed token while paused keeps the position and stays paused', async () => {
usePlayer.getState().playTracks([t1])
usePlayer.getState().togglePlay()
audio.currentTime = 42
mockFetch({ 'POST /api/v1/auth/login': () => session('tok2') })
await login('tom', 'secret123')
const playsBefore = audio.playCalls
audio.emit('loadedmetadata')
expect(audio.currentTime).toBe(42)
expect(audio.paused).toBe(true)
expect(audio.playCalls).toBe(playsBefore)
})
test('a renewed token with nothing loaded does nothing', async () => {
mockFetch({ 'POST /api/v1/auth/login': () => session('tok2') })
await login('tom', 'secret123')
expect(audio.src).toBe('')
})
test('a track that ends moves on to the next and is reported as complete once', () => {
usePlayer.getState().playTracks([t1, t2])
audio.emit('ended')
expect(usePlayer.getState().index).toBe(1)
expect(audio.src).toBe('/api/v1/tracks/2/stream?access_token=tok1')
expect(hooks.onFinish).toHaveBeenCalledTimes(1)
expect(hooks.onFinish).toHaveBeenCalledWith('complete')
expect(hooks.onStart).toHaveBeenLastCalledWith(2)
})
test('moving on before the end reports a skip, but only if something had been played', () => {
usePlayer.getState().playTracks([t1, t2, t3])
usePlayer.getState().next() // nothing played yet
expect(hooks.onFinish).not.toHaveBeenCalled()
audio.currentTime = 1.5
audio.emit('timeupdate')
usePlayer.getState().next()
expect(hooks.onFinish).toHaveBeenCalledTimes(1)
expect(hooks.onFinish).toHaveBeenCalledWith('skip')
})
test('playing the same track again starts a new play', () => {
usePlayer.getState().playTracks([t1])
audio.currentTime = 1
audio.emit('timeupdate')
usePlayer.getState().playTracks([t1])
expect(hooks.onFinish).toHaveBeenCalledWith('skip')
expect(hooks.onStart).toHaveBeenCalledTimes(2)
})
test('repeat one after the end starts a new play of the same track', () => {
usePlayer.getState().playTracks([t1])
usePlayer.getState().cycleRepeat()
usePlayer.getState().cycleRepeat() // one
audio.emit('ended')
expect(hooks.onFinish).toHaveBeenCalledWith('complete')
expect(hooks.onStart).toHaveBeenCalledTimes(2)
expect(audio.currentTime).toBe(0)
expect(audio.paused).toBe(false)
})
test('time played is counted in steps of at most two seconds, so a seek is not counted', () => {
usePlayer.getState().playTracks([t1])
audio.currentTime = 0.5
audio.emit('timeupdate')
audio.currentTime = 1
audio.emit('timeupdate')
audio.currentTime = 31
audio.emit('timeupdate')
expect(hooks.onPlayed.mock.calls.map(([ms]) => ms)).toEqual([500, 500, 2000])
})
test('time is not counted while paused', () => {
usePlayer.getState().playTracks([t1])
usePlayer.getState().togglePlay()
audio.currentTime = 5
audio.emit('timeupdate')
expect(hooks.onPlayed).not.toHaveBeenCalled()
})
test('a stream that cannot be played stops the player', () => {
usePlayer.getState().playTracks([t1])
audio.emit('error')
expect(usePlayer.getState().playing).toBe(false)
})
test('an empty queue unloads the audio', () => {
usePlayer.getState().playTracks([t1])
usePlayer.getState().removeAt(0)
expect(audio.paused).toBe(true)
expect(audio.src).toBe('')
})
test('after destroy the engine no longer listens to anyone', async () => {
engine.destroy()
expect(audio.listenerCount()).toBe(0)
usePlayer.getState().playTracks([t1])
expect(audio.src).toBe('')
mockFetch({ 'POST /api/v1/auth/login': () => session('tok9') })
await login('tom', 'secret123')
expect(audio.src).toBe('')
})
test('a track of a friend is loaded through this server, from the stream of that friend', () => {
usePlayer.getState().playTracks([theirs(9)])
expect(audio.src).toBe('/api/v1/friends/3/tracks/9/stream?access_token=tok1')
expect(audio.paused).toBe(false)
})
test('a track of a friend is never reported as a listen', () => {
usePlayer.getState().playTracks([theirs(9), theirs(10)])
expect(hooks.onStart).not.toHaveBeenCalled()
audio.currentTime = 1.5
audio.emit('timeupdate')
expect(hooks.onPlayed).not.toHaveBeenCalled()
audio.emit('ended')
expect(usePlayer.getState().index).toBe(1)
expect(hooks.onFinish).not.toHaveBeenCalled()
usePlayer.getState().next()
expect(hooks.onFinish).not.toHaveBeenCalled()
})
test('leaving a local track for a friend’s still closes the local play, and coming back opens a new one', () => {
usePlayer.getState().playTracks([t1, theirs(9), t2])
expect(hooks.onStart).toHaveBeenCalledWith(1)
audio.currentTime = 2
audio.emit('timeupdate')
usePlayer.getState().next() // to the friend's
expect(hooks.onFinish).toHaveBeenCalledTimes(1)
expect(hooks.onFinish).toHaveBeenCalledWith('skip')
expect(hooks.onStart).toHaveBeenCalledTimes(1)
usePlayer.getState().next() // back to a local one
expect(audio.src).toBe('/api/v1/tracks/2/stream?access_token=tok1')
expect(hooks.onStart).toHaveBeenLastCalledWith(2)
expect(hooks.onFinish).toHaveBeenCalledTimes(1) // nothing was played of the friend's
})
test('a friend’s track and a local one with the same id are two tracks', () => {
usePlayer.getState().playTracks([t1, theirs(1)])
expect(audio.src).toBe('/api/v1/tracks/1/stream?access_token=tok1')
usePlayer.getState().next()
expect(audio.src).toBe('/api/v1/friends/3/tracks/1/stream?access_token=tok1')
usePlayer.getState().playTracks([theirs(1, 4)])
expect(audio.src).toBe('/api/v1/friends/4/tracks/1/stream?access_token=tok1')
})
test('a renewed token keeps a friend’s track playing from the same second', async () => {
usePlayer.getState().playTracks([theirs(9)])
audio.currentTime = 42
mockFetch({ 'POST /api/v1/auth/login': () => session('tok2') })
await login('tom', 'secret123')
expect(audio.src).toBe('/api/v1/friends/3/tracks/9/stream?access_token=tok2')
audio.emit('loadedmetadata')
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()
})