Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 6 additions & 0 deletions api/openapi.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -8485,6 +8485,12 @@ components:
song, on the same clock as the playback position.
required: [durationMs, bpm, confidence, beats, downbeat, sections, frameRate, bandCount, bands, loudness, features]
properties:
lufs:
type: number
description: |
The song's integrated loudness (ITU-R BS.1770), in LUFS. A speaker
turns loud songs down by it, so the room's volume stays even.
Absent for a silent song.
durationMs:
type: integer
format: int64
Expand Down
14 changes: 12 additions & 2 deletions server/internal/analysis/analysis.go
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,7 @@ const (
// SampleRate is the rate songs are decoded to for analysis.
SampleRate = 22050
// Version changes whenever an older map should be worked out again.
Version = 1
Version = 2
// Bands is how many spectrum bands the map's envelope has.
Bands = 12

Expand Down Expand Up @@ -67,6 +67,8 @@ type Map struct {
// Loudness is each frame's overall level, 0–255, scaled to the song.
Loudness []byte `json:"loudness"`
Features Features `json:"features"`
// LUFS is the song's integrated loudness (BS.1770), nil for silence.
LUFS *float64 `json:"lufs,omitempty"`
}

// Section is a part of the song: an intro, a verse, a drop.
Expand Down Expand Up @@ -111,6 +113,7 @@ func Analyze(pcm io.Reader) (Map, error) {
// analyzer takes samples as they're decoded and keeps a few numbers per window.
type analyzer struct {
fft *fft
meter *meter
hann []float64
pending []float64
samples int64
Expand All @@ -130,6 +133,7 @@ type analyzer struct {
func newAnalyzer() *analyzer {
a := &analyzer{
fft: newFFT(window),
meter: newMeter(),
hann: make([]float64, window),
spec: make([]complex128, window),
prevLog: make([]float64, window/2+1),
Expand Down Expand Up @@ -160,7 +164,9 @@ func binHz(k int) float64 { return float64(k) * SampleRate / window }
func (a *analyzer) write(b []byte) {
for i := 0; i+4 <= len(b); i += 4 {
bits := uint32(b[i]) | uint32(b[i+1])<<8 | uint32(b[i+2])<<16 | uint32(b[i+3])<<24
a.pending = append(a.pending, float64(math.Float32frombits(bits)))
x := float64(math.Float32frombits(bits))
a.pending = append(a.pending, x)
a.meter.add(x)
}
a.samples += int64(len(b) / 4)
start := 0
Expand Down Expand Up @@ -260,6 +266,10 @@ func (a *analyzer) finish() Map {

m.BandsEnv, m.Loudness = envelopes(a.bandDB, a.rmsDB)
m.Features = features(a.rmsDB, a.centroid, loud)
if l, ok := a.meter.lufs(); ok {
l = math.Round(l*10) / 10
m.LUFS = &l
}
return m
}

Expand Down
123 changes: 123 additions & 0 deletions server/internal/analysis/loudness.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,123 @@
// SPDX-License-Identifier: AGPL-3.0-only

package analysis

import "math"

// Integrated loudness, after ITU-R BS.1770-4 (EBU R128): the signal is
// K-weighted (a high shelf for the head, a high pass for the ear), its
// power taken over 400 ms blocks every 100 ms, and blocks under -70 LUFS,
// then under 10 LU below the rest, left out, so silence and quiet intros
// don't count. Rooms use it to bring songs to a similar volume.
//
// It's measured on the mono mix the analysis decodes (ffmpeg mixes each
// channel in at -3 dB), which a stereo meter reads a little louder: by
// 0.8 LU on average over a sample of real songs against ffmpeg's ebur128,
// within ±0.7 LU from a near-mono 60s single to a wide modern mix. LUFS
// adds that back.

const (
stepSamples = SampleRate / 10 // 100 ms
absoluteGate = -70.0
relativeGate = -10.0
// stereoLU is what a stereo meter reads over the mono mix, typically.
stereoLU = 0.8
)

// biquad is a second-order IIR filter, direct form I.
type biquad struct {
b0, b1, b2, a1, a2 float64
x1, x2, y1, y2 float64
}

func (f *biquad) next(x float64) float64 {
y := f.b0*x + f.b1*f.x1 + f.b2*f.x2 - f.a1*f.y1 - f.a2*f.y2
f.x2, f.x1 = f.x1, x
f.y2, f.y1 = f.y1, y
return y
}

// kWeighting is BS.1770's filter pair, designed for fs.
func kWeighting(fs float64) [2]biquad {
// The high shelf: about +4 dB above 1.7 kHz.
g, q, fc := 3.999843853973347, 0.7071752369554196, 1681.974450955533
a := math.Pow(10, g/40)
w := 2 * math.Pi * fc / fs
alpha := math.Sin(w) / (2 * q)
c := math.Cos(w)
sa := 2 * math.Sqrt(a) * alpha
a0 := (a + 1) - (a-1)*c + sa
shelf := biquad{
b0: a * ((a + 1) + (a-1)*c + sa) / a0,
b1: -2 * a * ((a - 1) + (a+1)*c) / a0,
b2: a * ((a + 1) + (a-1)*c - sa) / a0,
a1: 2 * ((a - 1) - (a+1)*c) / a0,
a2: ((a + 1) - (a-1)*c - sa) / a0,
}
// The high pass: rolls off under about 38 Hz.
q, fc = 0.5003270373238773, 38.13547087602444
w = 2 * math.Pi * fc / fs
alpha = math.Sin(w) / (2 * q)
c = math.Cos(w)
a0 = 1 + alpha
hp := biquad{
b0: (1 + c) / 2 / a0,
b1: -(1 + c) / a0,
b2: (1 + c) / 2 / a0,
a1: -2 * c / a0,
a2: (1 - alpha) / a0,
}
return [2]biquad{shelf, hp}
}

// meter takes samples and keeps the K-weighted power of each 100 ms.
type meter struct {
k [2]biquad
sum float64
n int
steps []float64
}

func newMeter() *meter { return &meter{k: kWeighting(SampleRate)} }

func (m *meter) add(x float64) {
y := m.k[1].next(m.k[0].next(x))
m.sum += y * y
if m.n++; m.n == stepSamples {
m.steps = append(m.steps, m.sum/stepSamples)
m.sum, m.n = 0, 0
}
}

// lufs is the integrated loudness, as a stereo meter would read it. ok is
// false if nothing in the song is over the absolute gate.
func (m *meter) lufs() (lufs float64, ok bool) {
var blocks []float64
for i := 0; i+4 <= len(m.steps); i++ {
blocks = append(blocks, (m.steps[i]+m.steps[i+1]+m.steps[i+2]+m.steps[i+3])/4)
}
level := func(power float64) float64 { return -0.691 + 10*math.Log10(power) }
mean := func(over float64) (float64, bool) {
var s float64
var n int
for _, b := range blocks {
if b > 0 && level(b) > over {
s += b
n++
}
}
if n == 0 {
return 0, false
}
return s / float64(n), true
}
ungated, ok := mean(absoluteGate)
if !ok {
return 0, false
}
gated, ok := mean(math.Max(absoluteGate, level(ungated)+relativeGate))
if !ok {
return 0, false
}
return level(gated) + stereoLU, true
}
54 changes: 54 additions & 0 deletions server/internal/analysis/loudness_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,54 @@
// SPDX-License-Identifier: AGPL-3.0-only

package analysis

import (
"math"
"testing"
)

// sine is seconds of a sine at hz and amplitude amp, as PCM.
func sine(hz, amp, seconds float64) []float32 {
pcm := make([]float32, int(seconds*SampleRate))
for i := range pcm {
pcm[i] = float32(amp * math.Sin(2*math.Pi*hz*float64(i)/SampleRate))
}
return pcm
}

func lufsOf(t *testing.T, pcm []float32) float64 {
t.Helper()
m := analyze(t, f32le(pcm))
if m.LUFS == nil {
t.Fatal("no loudness")
}
return *m.LUFS
}

func TestLoudness(t *testing.T) {
// BS.1770's reference: a full-scale 997 Hz sine reads -3.01 LUFS in
// one channel, plus stereoLU for the mix. The K-weighting comes out a
// little different at 22.05 kHz than at BS.1770's 48 kHz, a few tenths
// of a LU, the same for every song.
want := -3.01 + stereoLU
if l := lufsOf(t, sine(997, 1, 10)); math.Abs(l-want) > 0.5 {
t.Errorf("full-scale sine: %.2f LUFS, want %.2f", l, want)
}
// 20 dB quieter reads 20 LU less.
if l := lufsOf(t, sine(997, 0.1, 10)); math.Abs(l-(want-20)) > 0.5 {
t.Errorf("-20 dB sine: %.2f LUFS, want %.2f", l, want-20)
}
// Silence around the music doesn't make it quieter: it's gated out.
gapped := append(append(make([]float32, 20*SampleRate), sine(997, 0.1, 10)...), make([]float32, 20*SampleRate)...)
if l := lufsOf(t, gapped); math.Abs(l-(want-20)) > 0.5 {
t.Errorf("with silence around it: %.2f LUFS, want %.2f", l, want-20)
}
// The ear's weighting: deep bass counts for less than the mids.
if bass, mid := lufsOf(t, sine(30, 0.5, 10)), lufsOf(t, sine(997, 0.5, 10)); bass > mid-1 {
t.Errorf("30 Hz %.2f LUFS, 1 kHz %.2f LUFS: bass should read quieter", bass, mid)
}
// Silence has none.
if m := analyze(t, f32le(make([]float32, 5*SampleRate))); m.LUFS != nil {
t.Errorf("silence: %v LUFS", *m.LUFS)
}
}
5 changes: 5 additions & 0 deletions server/internal/httpapi/api.gen.go

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

4 changes: 4 additions & 0 deletions server/internal/httpapi/browse.go
Original file line number Diff line number Diff line change
Expand Up @@ -391,6 +391,10 @@ func toBeatMap(m analysis.Map) BeatMap {
Features: BeatMapFeatures{Energy: float32(m.Features.Energy), Brightness: float32(m.Features.Brightness), Dynamics: float32(m.Features.Dynamics)},
Sections: make([]BeatMapSection, len(m.Sections)),
}
if m.LUFS != nil {
l := float32(*m.LUFS)
out.Lufs = &l
}
for i, sec := range m.Sections {
out.Sections[i] = BeatMapSection{StartMs: sec.StartMs, Energy: float32(sec.Energy)}
}
Expand Down
6 changes: 6 additions & 0 deletions web/src/api/schema.gen.ts

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

26 changes: 26 additions & 0 deletions web/src/lib/loudness.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
import { describe, expect, it } from 'vitest'
import { TARGET_LUFS, volumeFor } from './loudness'

const db = (v: number) => 20 * Math.log10(v)

describe('evening out the volume', () => {
it('turns a loud master down to the target', () => {
// A modern master at -8 LUFS comes down 8 dB.
expect(db(volumeFor(-8))).toBeCloseTo(TARGET_LUFS + 8, 5)
})

it("leaves songs at or under the target alone (it can't turn up)", () => {
expect(volumeFor(TARGET_LUFS)).toBe(1)
expect(volumeFor(-21)).toBe(1)
})

it('cuts 12 dB at most', () => {
expect(db(volumeFor(5))).toBeCloseTo(-12, 5)
})

it('plays at full volume when the loudness is unknown', () => {
expect(volumeFor(undefined)).toBe(1)
expect(volumeFor(null)).toBe(1)
expect(volumeFor(Number.NaN)).toBe(1)
})
})
38 changes: 38 additions & 0 deletions web/src/lib/loudness.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,38 @@
// Evening out the volume from song to song. The server measures each
// song's loudness (LUFS, in its beat map); the speaker turns loud songs
// down to TARGET_LUFS, so a 60s single and a modern master sit together.
//
// An <audio> element can only turn down (volume tops out at 1), so songs
// quieter than the target stay as they are. -16 LUFS (Apple Music's level)
// is under most of a typical library, older records included: the room
// plays a little quieter overall, and most songs come out the same.

export const TARGET_LUFS = -16
/** The most a song is turned down, dB: a measurement that's way off can't make it inaudible. */
const MAX_CUT_DB = 12

/** The volume (0–1) that brings a song of this loudness to the target; 1 if it isn't known. */
export function volumeFor(lufs: number | undefined | null) {
if (typeof lufs !== 'number' || !Number.isFinite(lufs) || lufs <= TARGET_LUFS) return 1
return 10 ** (-Math.min(lufs - TARGET_LUFS, MAX_CUT_DB) / 20)
}

/**
* Moves el's volume to `to`: at once before the song is under way, else
* over a couple of seconds, so a map that arrives late doesn't jolt.
* Returns the cancel.
*/
export function rampVolume(el: HTMLMediaElement, to: number, ms = 2000) {
const from = el.volume
if (el.paused || el.currentTime < 0.5 || Math.abs(to - from) < 0.01) {
el.volume = to
return () => {}
}
const start = performance.now()
const t = setInterval(() => {
const k = Math.min(1, (performance.now() - start) / ms)
el.volume = from + (to - from) * k
if (k >= 1) clearInterval(t)
}, 50)
return () => clearInterval(t)
}
24 changes: 24 additions & 0 deletions web/src/lib/speaker.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,8 @@
import { api } from '@/api/client'
import { ApiError, errorMessage, unwrap } from '@/api/errors'
import { loadBeatMap } from './beat-map'
import { serverNow } from './clock'
import { rampVolume, volumeFor } from './loudness'
import { BACK_WITHIN_MS, newer, queueArtworkUrl, sendCommand, type Playback, type QueueItem } from './playback'
import { createStore } from './store'
import { toast } from './toast'
Expand Down Expand Up @@ -137,6 +139,9 @@ export function streamUrl(roomId: string, itemId: string, accept: string[], star

class Speaker {
private els: [HTMLAudioElement, HTMLAudioElement] | undefined
/** Each element's song, for its volume, and the volume ramp under way. */
private songOf = new WeakMap<HTMLAudioElement, string>()
private ramps = new WeakMap<HTMLAudioElement, () => void>()
private cur!: HTMLAudioElement
private pre!: HTMLAudioElement
// Where each element's stream begins in its song, in ms: 0 unless it was
Expand Down Expand Up @@ -453,6 +458,25 @@ class Speaker {
private setSrc(el: HTMLAudioElement, item: QueueItem, startMs = 0) {
el.src = streamUrl(this.roomId!, item.id, acceptedTypes(), startMs)
this.offsets.set(el, startMs)
this.level(el, item)
}

/**
* Turns el down for a loud song, so songs sit at about the same volume.
* The loudness is in the song's beat map, usually worked out before it
* plays; one that comes late is eased in.
*/
private level(el: HTMLAudioElement, item: QueueItem) {
const roomId = this.roomId
if (this.songOf.get(el) === item.id || !roomId) return
this.songOf.set(el, item.id)
this.ramps.get(el)?.()
// Until it's known, full volume, as before.
el.volume = 1
void loadBeatMap(roomId, item.id).then((map) => {
if (this.songOf.get(el) !== item.id) return
this.ramps.set(el, rampVolume(el, volumeFor(map?.lufs)))
})
}

private load(item: QueueItem, positionMs: number) {
Expand Down
Loading