diff --git a/api/openapi.yaml b/api/openapi.yaml index b1330d1..3a303ea 100644 --- a/api/openapi.yaml +++ b/api/openapi.yaml @@ -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 diff --git a/server/internal/analysis/analysis.go b/server/internal/analysis/analysis.go index b24b19a..9178a3c 100644 --- a/server/internal/analysis/analysis.go +++ b/server/internal/analysis/analysis.go @@ -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 @@ -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. @@ -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 @@ -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), @@ -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 @@ -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 } diff --git a/server/internal/analysis/loudness.go b/server/internal/analysis/loudness.go new file mode 100644 index 0000000..bdb1de7 --- /dev/null +++ b/server/internal/analysis/loudness.go @@ -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 +} diff --git a/server/internal/analysis/loudness_test.go b/server/internal/analysis/loudness_test.go new file mode 100644 index 0000000..92e9c26 --- /dev/null +++ b/server/internal/analysis/loudness_test.go @@ -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) + } +} diff --git a/server/internal/httpapi/api.gen.go b/server/internal/httpapi/api.gen.go index cf2913f..4cb2bcd 100644 --- a/server/internal/httpapi/api.gen.go +++ b/server/internal/httpapi/api.gen.go @@ -2193,6 +2193,11 @@ type BeatMap struct { // Loudness Base64: each frame's overall level, a byte (0–255) each, scaled to the song. Loudness []byte `json:"loudness"` + // Lufs 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. + Lufs *float32 `json:"lufs,omitempty"` + // Sections The song's parts (intro, verse, drop), in order; the first starts at 0. Sections []BeatMapSection `json:"sections"` } diff --git a/server/internal/httpapi/browse.go b/server/internal/httpapi/browse.go index 636f4c8..f5bf76b 100644 --- a/server/internal/httpapi/browse.go +++ b/server/internal/httpapi/browse.go @@ -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)} } diff --git a/web/src/api/schema.gen.ts b/web/src/api/schema.gen.ts index f651204..05fb39a 100644 --- a/web/src/api/schema.gen.ts +++ b/web/src/api/schema.gen.ts @@ -5806,6 +5806,12 @@ export interface components { * song, on the same clock as the playback position. */ BeatMap: { + /** + * @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. + */ + lufs?: number; /** Format: int64 */ durationMs: number; /** @description The tempo; 0 if the song has no steady beat, and then `beats` is empty. */ diff --git a/web/src/lib/loudness.test.ts b/web/src/lib/loudness.test.ts new file mode 100644 index 0000000..769c0ea --- /dev/null +++ b/web/src/lib/loudness.test.ts @@ -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) + }) +}) diff --git a/web/src/lib/loudness.ts b/web/src/lib/loudness.ts new file mode 100644 index 0000000..fa9e83a --- /dev/null +++ b/web/src/lib/loudness.ts @@ -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