diff --git a/src/core/audio/loudness.ts b/src/core/audio/loudness.ts new file mode 100644 index 00000000..7ad5a41b --- /dev/null +++ b/src/core/audio/loudness.ts @@ -0,0 +1,128 @@ +import { LOUDNESS_BLOCK_SECONDS, LOUDNESS_HOP_SECONDS } from "@shotstack/shotstack-canvas/duck"; + +const SAMPLE_RATE = 48000; + +// BS.1770 K-weighting at 48 kHz: a high-shelf then a high-pass, as two biquads in series. +const SHELF_B = [1.53512485958697, -2.69169618940638, 1.19839281085285] as const; +const SHELF_A = [-1.69065929318241, 0.73248077421585] as const; +const HIGHPASS_B = [1, -2, 1] as const; +const HIGHPASS_A = [-1.99004745483398, 0.99007225036621] as const; + +// Once the sound stops, the filters' feedback decays into subnormals, which are slow on x86. +// Below this floor a sample's energy is under 1e-60, far beneath the -70 LUFS gate. +const STATE_FLOOR = 1e-30; +const flushed = (state: number): number => (Math.abs(state) < STATE_FLOOR ? 0 : state); + +// Filtering a long file in one task freezes the canvas, playhead and input. A slice of half a 60 Hz frame leaves them the rest. +const SLICE_MS = 8; +// Four hops filter in about 0.13 ms on an M2 Pro, so even at 4× CPU throttling a slice overruns by at most about 0.5 ms. +const HOPS_PER_CLOCK_CHECK = 4; + +export interface LoudnessScheduling { + yieldToEventLoop?: () => Promise; + now?: () => number; + hopsPerCheck?: number; +} + +// Timers are clamped to 4 ms once nested and to 1 s or more in a hidden tab; a message round trip is not. +function messageRoundTrip(): Promise { + return new Promise(resolve => { + const { port1, port2 } = new MessageChannel(); + port1.onmessage = () => { + port1.close(); + resolve(); + }; + port2.postMessage(null); + }); +} + +/** + * Each hop's sum of squared K-weighted samples, for hops `[from, to)` of one channel. Direct form I. + * `state` is the filters' memory, `[sx1, sx2, sy1, sy2, hx1, hx2, hy1, hy2]`, carried from one range to the next. + */ +function hopEnergies(samples: Float32Array, hop: number, from: number, to: number, state: Float64Array): Float64Array { + const energies = new Float64Array(to - from); + let [sx1, sx2, sy1, sy2, hx1, hx2, hy1, hy2] = state; + + for (let h = from; h < to; h += 1) { + sy1 = flushed(sy1); + sy2 = flushed(sy2); + hy1 = flushed(hy1); + hy2 = flushed(hy2); + let sum = 0; + for (let i = h * hop, end = i + hop; i < end; i += 1) { + const x = samples[i]; + const s = SHELF_B[0] * x + SHELF_B[1] * sx1 + SHELF_B[2] * sx2 - SHELF_A[0] * sy1 - SHELF_A[1] * sy2; + sx2 = sx1; + sx1 = x; + sy2 = sy1; + sy1 = s; + + const y = HIGHPASS_B[0] * s + HIGHPASS_B[1] * hx1 + HIGHPASS_B[2] * hx2 - HIGHPASS_A[0] * hy1 - HIGHPASS_A[1] * hy2; + hx2 = hx1; + hx1 = s; + hy2 = hy1; + hy1 = y; + + sum += y * y; + } + energies[h - from] = sum; + } + state.set([sx1, sx2, sy1, sy2, hx1, hx2, hy1, hy2]); + return energies; +} + +function blocksFrom(hopEnergy: Float64Array, hop: number): Float64Array { + const hopsPerBlock = Math.round(LOUDNESS_BLOCK_SECONDS / LOUDNESS_HOP_SECONDS); + // Summed afresh from its hops so rounding can't accumulate across the file. + const blocks = new Float64Array(hopEnergy.length); + for (let k = 0; k < hopEnergy.length; k += 1) { + let energy = 0; + for (let h = Math.max(0, k - hopsPerBlock + 1); h <= k; h += 1) energy += hopEnergy[h]; + blocks[k] = energy / (hop * hopsPerBlock); + } + return blocks; +} + +/** + * Block `k` is the channel sum of mean squares of the K-weighted signal over `[(k + 1) * hop - block, (k + 1) * hop)`, + * zero-padded before 0. Every channel carries weight 1. Slices end on hop boundaries and carry the filters' state, + * so `hopsPerCheck` never changes the result. + */ +export async function kWeightedBlocks( + channels: Float32Array[], + { yieldToEventLoop = messageRoundTrip, now = () => performance.now(), hopsPerCheck = HOPS_PER_CLOCK_CHECK }: LoudnessScheduling = {} +): Promise { + const hop = Math.round(LOUDNESS_HOP_SECONDS * SAMPLE_RATE); + const hops = Math.floor((channels[0]?.length ?? 0) / hop); + + const hopEnergy = new Float64Array(hops); + let sliceStart = now(); + for (const samples of channels) { + const state = new Float64Array(8); + for (let from = 0; from < hops; from += hopsPerCheck) { + const energies = hopEnergies(samples, hop, from, Math.min(from + hopsPerCheck, hops), state); + for (let i = 0; i < energies.length; i += 1) hopEnergy[from + i] += energies[i]; + if (now() - sliceStart >= SLICE_MS) { + await yieldToEventLoop(); + sliceStart = now(); + } + } + } + return blocksFrom(hopEnergy, hop); +} + +export async function decodeLoudnessBlocks(src: string, fetchImpl?: typeof fetch, scheduling: LoudnessScheduling = {}): Promise { + try { + const response = await (fetchImpl ?? fetch)(src); + if (!response.ok) return null; + + // decodeAudioData resamples to the context's rate and keeps the file's channel count. + const decoded = await new OfflineAudioContext(1, 1, SAMPLE_RATE).decodeAudioData(await response.arrayBuffer()); + const channels = Array.from({ length: decoded.numberOfChannels }, (_, i) => decoded.getChannelData(i)); + return await kWeightedBlocks(channels, scheduling); + } catch (error) { + console.warn("Loudness: could not measure", src, error); + return null; + } +} diff --git a/tests/duck-load.test.ts b/tests/duck-load.test.ts index 23631be9..7f1f35cb 100644 --- a/tests/duck-load.test.ts +++ b/tests/duck-load.test.ts @@ -1,6 +1,12 @@ +import { existsSync } from "fs"; +import { resolve } from "path"; + import { buildDuckedVolume } from "@shotstack/shotstack-canvas/duck"; import { EditSchema } from "../src/core/schemas"; +import { aliases } from "../vite.shared"; + +const DUCK = "@shotstack/shotstack-canvas/duck"; describe("duck dependencies", () => { it("accepts an audio clip with a duck property", () => { @@ -28,4 +34,20 @@ describe("duck dependencies", () => { it("resolves the canvas duck subpath", () => { expect(typeof buildDuckedVolume).toBe("function"); }); + + describe("vite alias", () => { + it("maps the duck subpath to the canvas build", () => { + expect(aliases("/repo")[DUCK]).toBe(resolve("/repo", "node_modules/@shotstack/shotstack-canvas/dist/duck.js")); + }); + + it("lists the subpath before the bare package, which also matches it", () => { + const keys = Object.keys(aliases("/repo")); + expect(keys.indexOf(DUCK)).toBeGreaterThanOrEqual(0); + expect(keys.indexOf(DUCK)).toBeLessThan(keys.indexOf("@shotstack/shotstack-canvas")); + }); + + it("points at a file the installed canvas build ships", () => { + expect(existsSync(aliases(resolve(__dirname, ".."))[DUCK])).toBe(true); + }); + }); }); diff --git a/tests/loudness.test.ts b/tests/loudness.test.ts new file mode 100644 index 00000000..5e3d95ae --- /dev/null +++ b/tests/loudness.test.ts @@ -0,0 +1,175 @@ +import { integratedLoudness } from "@shotstack/shotstack-canvas/duck"; + +import { decodeLoudnessBlocks, kWeightedBlocks } from "../src/core/audio/loudness"; + +const RATE = 48000; +const TOLERANCE = 0.15; + +const tone = (hz: number, amplitude: number, seconds: number): Float32Array => + Float32Array.from({ length: seconds * RATE }, (_, i) => amplitude * Math.sin((2 * Math.PI * hz * i) / RATE)); + +const silence = (seconds: number): Float32Array => new Float32Array(seconds * RATE); + +const join = (...parts: Float32Array[]): Float32Array => { + const out = new Float32Array(parts.reduce((sum, part) => sum + part.length, 0)); + parts.reduce((offset, part) => { + out.set(part, offset); + return offset + part.length; + }, 0); + return out; +}; + +const onePass = (channels: Float32Array[]): Promise => kWeightedBlocks(channels, { hopsPerCheck: Infinity }); + +const measure = async (...channels: Float32Array[]): Promise => + integratedLoudness(await onePass(channels), 0, channels[0].length / RATE); + +describe("kWeightedBlocks", () => { + // Reference values are ffmpeg 8.1.1's ebur128 momentary loudness, gated by integratedLoudness. + const cases: Array<[string, () => Float32Array[], number]> = [ + ["1 kHz, both channels", () => [tone(1000, 0.25, 3), tone(1000, 0.25, 3)], -12.0], + ["100 Hz, both channels", () => [tone(100, 0.25, 3), tone(100, 0.25, 3)], -13.9], + ["4 kHz, both channels", () => [tone(4000, 0.25, 3), tone(4000, 0.25, 3)], -8.8], + ["1 kHz, left channel only", () => [tone(1000, 0.25, 3), silence(3)], -15.0], + ["1 s of silence then 2 s of 1 kHz", () => [join(silence(1), tone(1000, 0.25, 2)), join(silence(1), tone(1000, 0.25, 2))], -12.4], + ["2 s loud then 2 s at a tenth", () => [join(tone(1000, 0.25, 2), tone(1000, 0.025, 2)), join(tone(1000, 0.25, 2), tone(1000, 0.025, 2))], -12.4], + ["a single channel holding the left signal", () => [tone(1000, 0.25, 3)], -15.0] + ]; + + it.each(cases)("measures %s", async (_name, channels, expected) => { + const lufs = await measure(...channels()); + expect(lufs).not.toBeNull(); + expect(Math.abs((lufs as number) - expected)).toBeLessThanOrEqual(TOLERANCE); + }); + + it("emits one block per complete hop and zero-pads before 0", async () => { + const blocks = await onePass([tone(1000, 0.25, 3), tone(1000, 0.25, 3)]); + expect(blocks).toHaveLength(30); + + const partial = await onePass([join(tone(1000, 0.25, 1), new Float32Array(100))]); + expect(partial).toHaveLength(10); + + // Block 0 holds one hop of signal in a window of four, so a quarter of the steady-state energy. + expect(blocks[0] / blocks[10]).toBeCloseTo(0.25, 1); + expect(blocks[1] / blocks[10]).toBeCloseTo(0.5, 1); + }); + + it("gives blocks for a file shorter than one window that gate to null", async () => { + const blocks = await onePass([tone(1000, 0.25, 0.3)]); + expect(blocks).toHaveLength(3); + expect(integratedLoudness(blocks, 0, 0.3)).toBeNull(); + }); + + it("measures digital silence after a tone as exactly 0 within half a second", async () => { + const blocks = await onePass([join(tone(1000, 0.25, 1), silence(3))]); + + // Block k opens at (k - 3) * 0.1 s, so block 18 is the first to open 0.5 s after the tone ends. + expect([...blocks.slice(18)]).toEqual(new Array(blocks.length - 18).fill(0)); + }); + + it("returns no blocks for no audio", async () => { + expect(await onePass([])).toHaveLength(0); + expect(await onePass([new Float32Array(0)])).toHaveLength(0); + }); +}); + +describe("decodeLoudnessBlocks", () => { + const original = Object.getOwnPropertyDescriptor(globalThis, "OfflineAudioContext"); + + beforeEach(() => { + jest.spyOn(console, "warn").mockImplementation(() => undefined); + }); + + afterEach(() => { + jest.restoreAllMocks(); + if (original) Object.defineProperty(globalThis, "OfflineAudioContext", original); + else Reflect.deleteProperty(globalThis, "OfflineAudioContext"); + }); + + const ok = (): typeof fetch => (async () => ({ ok: true, arrayBuffer: async () => new ArrayBuffer(8) })) as unknown as typeof fetch; + + function mockContext(decodeAudioData: jest.Mock): jest.Mock { + const ctor = jest.fn(() => ({ decodeAudioData })); + Object.assign(globalThis, { OfflineAudioContext: ctor }); + return ctor; + } + + const decoding = (channels: Float32Array[]): jest.Mock => + mockContext(jest.fn(async () => ({ numberOfChannels: channels.length, getChannelData: (i: number) => channels[i] }))); + + // A clock that never moves never yields, so no test here waits on real time or a MessageChannel. + const still = (): number => 0; + const ticking = (ms: number): (() => number) => { + let time = 0; + return () => { + time += ms; + return time; + }; + }; + + it("decodes at 48 kHz and measures every channel", async () => { + const channels = [tone(1000, 0.25, 3), tone(1000, 0.25, 3)]; + const ctor = decoding(channels); + + const blocks = await decodeLoudnessBlocks("https://example.com/voice.mp3", ok(), { now: still }); + + expect(ctor).toHaveBeenCalledWith(1, 1, RATE); + expect(blocks).toEqual(await onePass(channels)); + }); + + describe("in slices", () => { + // Each channel's filters decay into subnormals within a few hops of the tone ending, across several slice boundaries. + const bed = (): Float32Array[] => [join(tone(1000, 0.25, 2), silence(3)), join(tone(100, 0.5, 2), silence(3))]; + + it("lets the event loop in once a slice has run for 8 ms, without changing the result", async () => { + const channels = bed(); + decoding(channels); + const yieldToEventLoop = jest.fn(async () => undefined); + + const blocks = await decodeLoudnessBlocks("https://example.com/bed.mp3", ok(), { yieldToEventLoop, now: ticking(3) }); + + expect(yieldToEventLoop.mock.calls.length).toBeGreaterThan(1); + expect(blocks).toEqual(await onePass(channels)); + }); + + it("never yields while a slice stays under 8 ms", async () => { + const channels = bed(); + decoding(channels); + const yieldToEventLoop = jest.fn(async () => undefined); + + // About thirty reads in all, so the whole measurement takes 3 ms. + const blocks = await decodeLoudnessBlocks("https://example.com/bed.mp3", ok(), { yieldToEventLoop, now: ticking(0.1) }); + + expect(yieldToEventLoop).not.toHaveBeenCalled(); + expect(blocks).toEqual(await onePass(channels)); + }); + }); + + it("returns null when fetch rejects", async () => { + mockContext(jest.fn()); + const failing = (async () => { + throw new Error("offline"); + }) as unknown as typeof fetch; + + await expect(decodeLoudnessBlocks("https://example.com/voice.mp3", failing)).resolves.toBeNull(); + }); + + it("returns null when the response is not ok", async () => { + const decode = jest.fn(); + mockContext(decode); + const missing = (async () => ({ ok: false })) as unknown as typeof fetch; + + await expect(decodeLoudnessBlocks("https://example.com/voice.mp3", missing)).resolves.toBeNull(); + expect(decode).not.toHaveBeenCalled(); + }); + + it("returns null when decoding throws", async () => { + mockContext( + jest.fn(async () => { + throw new Error("no audio track"); + }) + ); + + await expect(decodeLoudnessBlocks("https://example.com/voice.mp3", ok())).resolves.toBeNull(); + }); +}); diff --git a/vite.shared.ts b/vite.shared.ts index 47fcf33e..8d964da7 100644 --- a/vite.shared.ts +++ b/vite.shared.ts @@ -42,6 +42,8 @@ export function aliases(dirname: string): Record { "@export": resolve(dirname, "src/core/export"), "@styles": resolve(dirname, "src/styles"), "@templates": resolve(dirname, "src/templates"), + // Vite takes the first matching key and a key also matches `key/...`, so the subpath must precede the bare package. + "@shotstack/shotstack-canvas/duck": resolve(dirname, "node_modules/@shotstack/shotstack-canvas/dist/duck.js"), "@shotstack/shotstack-canvas": resolve(dirname, "node_modules/@shotstack/shotstack-canvas/dist/entry.web.js") }; }