From 630409ca19e13bf3400d1d2180bc8c14932970b7 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Miguel=20=C3=81ngel?= Date: Tue, 24 Nov 2026 19:30:50 +0000 Subject: [PATCH] feat(studio): long audio keeps its fx and beats, read from the server, no page OOM (#8622) * fix(core): decode whole audio files only up to ten minutes * test: give the header stub only to tests with a DOM * refactor(core): one header stub for both test setups, length check as its own step * refactor(core): one decode gate for failed and too-long sources * feat(studio): long audio keeps its fx and beats, read from the server as PCM * fix(core): carve and levels read the same span of audio at any sample rate * test(studio): beat analysis test waits for its read to start * test(studio): beat analysis tests run on an idle timeline * fix(studio): the clip menu's duck passes its carve rate too * fix(core): publish the audio-decode subpath * refactor(studio-server): the PCM route registers with the waveform routes * fix(studio-server): the PCM route checks the file without blocking the server * chore(skills): media-use's carve copy picks up the time-sized analysis window * chore(skills): the skills manifest records media-use's new carve copy * fix(studio): the PCM route refuses other sites, shares the decode slots and keeps stereo for beats * fix(core): a short file whose length can't be read decodes again, judged by its size * refactor(core): one window level and Hann helper, PCM route and decode split into steps * chore(skills): the skills manifest records media-use with main's change and this branch's carve copy * fix(studio-server): the PCM route answers not found for a request path it can't read * chore(skills): the carve copy and skills manifest regenerate over main's carve change * chore(skills): the skills manifest regenerates over main's media-use change --- packages/core/package-subpaths.json | 6 + packages/core/package.json | 10 + packages/core/src/audioAnalysis.ts | 20 +- packages/core/src/audioCarve.test.ts | 28 +++ packages/core/src/audioCarve.ts | 36 ++-- packages/core/src/audioDecode.test.ts | 85 ++++++++ packages/core/src/audioDecode.ts | 76 ++++++++ packages/core/src/audioLeveller.ts | 19 +- packages/core/src/beats/beatDetection.test.ts | 26 ++- packages/core/src/beats/beatDetection.ts | 5 +- .../src/runtime/webAudioTransport.test.ts | 11 ++ .../core/src/runtime/webAudioTransport.ts | 57 ++++-- packages/core/vitest.config.ts | 2 +- packages/core/vitest.mediaHeader.ts | 17 ++ .../src/createStudioApi.originGuard.test.ts | 2 + packages/studio-server/src/createStudioApi.ts | 1 + .../studio-server/src/helpers/audioDecodes.ts | 3 + packages/studio-server/src/routes/pcm.test.ts | 107 ++++++++++ packages/studio-server/src/routes/pcm.ts | 73 +++++++ packages/studio-server/src/routes/waveform.ts | 2 + .../editor/propertyPanelAudioFxGroup.test.tsx | 183 +++++++++++++++++- .../src/components/editor/useFxCarve.ts | 4 +- .../src/components/editor/useFxCarveNodes.ts | 29 ++- .../src/components/editor/useFxLevelling.ts | 17 +- .../src/hooks/useMusicBeatAnalysis.test.tsx | 17 +- .../studio/src/hooks/useMusicBeatAnalysis.ts | 18 +- .../player/components/AudioWaveform.test.tsx | 36 ++++ .../src/player/components/AudioWaveform.tsx | 9 +- .../src/player/components/clipMenuDuck.ts | 9 +- packages/studio/src/utils/projectPcm.test.ts | 33 ++++ packages/studio/src/utils/projectPcm.ts | 60 ++++++ packages/studio/vite.config.ts | 2 +- skills-manifest.json | 2 +- .../audio/scripts/lib/audio-carve.mjs | 2 +- 34 files changed, 900 insertions(+), 107 deletions(-) create mode 100644 packages/core/src/audioDecode.test.ts create mode 100644 packages/core/src/audioDecode.ts create mode 100644 packages/core/vitest.mediaHeader.ts create mode 100644 packages/studio-server/src/routes/pcm.test.ts create mode 100644 packages/studio-server/src/routes/pcm.ts create mode 100644 packages/studio/src/utils/projectPcm.test.ts create mode 100644 packages/studio/src/utils/projectPcm.ts diff --git a/packages/core/package-subpaths.json b/packages/core/package-subpaths.json index 79f215f328..2dd81cf6fe 100644 --- a/packages/core/package-subpaths.json +++ b/packages/core/package-subpaths.json @@ -386,6 +386,12 @@ "types": "./dist/audioFade.d.ts", "environments": ["browser", "bun", "node"] }, + "./audio-decode": { + "source": "./src/audioDecode.ts", + "runtime": "./dist/audioDecode.js", + "types": "./dist/audioDecode.d.ts", + "environments": ["browser", "bun", "node"] + }, "./speed-ramp": { "source": "./src/speedRamp.ts", "runtime": "./dist/speedRamp.js", diff --git a/packages/core/package.json b/packages/core/package.json index 4517c1fadd..c110afba8e 100644 --- a/packages/core/package.json +++ b/packages/core/package.json @@ -398,6 +398,12 @@ "import": "./src/audioFade.ts", "types": "./src/audioFade.ts" }, + "./audio-decode": { + "bun": "./src/audioDecode.ts", + "node": "./dist/audioDecode.js", + "import": "./src/audioDecode.ts", + "types": "./src/audioDecode.ts" + }, "./speed-ramp": { "bun": "./src/speedRamp.ts", "node": "./dist/speedRamp.js", @@ -988,6 +994,10 @@ "import": "./dist/audioFade.js", "types": "./dist/audioFade.d.ts" }, + "./audio-decode": { + "import": "./dist/audioDecode.js", + "types": "./dist/audioDecode.d.ts" + }, "./speed-ramp": { "import": "./dist/speedRamp.js", "types": "./dist/speedRamp.d.ts" diff --git a/packages/core/src/audioAnalysis.ts b/packages/core/src/audioAnalysis.ts index 6506d6769a..c9d828f5fd 100644 --- a/packages/core/src/audioAnalysis.ts +++ b/packages/core/src/audioAnalysis.ts @@ -173,7 +173,25 @@ function rmsFrames( return frames; } -const fftSizeFor = (sampleRate: number) => 2 ** Math.round(Math.log2(sampleRate * 0.023)); +export const windowSizeFor = (sampleRate: number, seconds: number): number => + 2 ** Math.round(Math.log2(sampleRate * seconds)); + +/** Level in dB of one window, or -Infinity for silence. */ +export function windowDb(samples: Float32Array, from: number, count: number): number { + let sum = 0; + let n = 0; + for (let i = from; i < from + count; i++) { + const s = samples[i]; + if (s === undefined) break; + sum += s * s; + n += 1; + } + if (n === 0) return Number.NEGATIVE_INFINITY; + const rms = Math.sqrt(sum / n); + return rms > 0 ? 20 * Math.log10(rms) : Number.NEGATIVE_INFINITY; +} + +const fftSizeFor = (sampleRate: number) => windowSizeFor(sampleRate, 0.023); /** Magnitude spectra of Hann-windowed frames centred on each hop, limited to `band`. */ /** The FFT bins inside `band`, as [first, end). */ diff --git a/packages/core/src/audioCarve.test.ts b/packages/core/src/audioCarve.test.ts index bedcc35a09..5fa64eac16 100644 --- a/packages/core/src/audioCarve.test.ts +++ b/packages/core/src/audioCarve.test.ts @@ -15,6 +15,7 @@ import { DEFAULT_CARVE, normalizeCarveSettings, } from "./audioCarve.js"; +import { analyseLevelling } from "./audioLeveller.js"; /** The profile the panel's default strength produces — what the separate controls defaulted to. */ const PROFILE = carveProfile(DEFAULT_CARVE.strength); @@ -684,3 +685,30 @@ describe("carve settings written before this took a list of voices", () => { expect(normalizeCarveSettings({ source: "" } as never).sources).toEqual([]); }); }); + +describe("carve and levels read the same span of audio at any rate", () => { + /** Speech-like bursts of 1 kHz with pauses, 20 s at `rate`. */ + const talk = (rate: number) => + Float32Array.from({ length: rate * 20 }, (_, i) => { + const t = i / rate; + return (Math.floor(t) % 3 === 2 ? 0.02 : 0.6) * Math.sin(2 * Math.PI * 1000 * t); + }); + const near = (a: { t: number; v: number }[], b: { t: number; v: number }[]) => + a.every((p, i) => Math.abs(p.t - b[i]!.t) < 0.01 && Math.abs(p.v - b[i]!.v) <= 0.11); + + it("draws the same carve envelope from 24 kHz as from 48 kHz", () => { + const band = [{ freq: 1000, gainDb: -8, q: 1.4 }]; + const [at48] = analyseCarveDynamics(talk(48_000), 48_000, band); + const [at24] = analyseCarveDynamics(talk(24_000), 24_000, band); + expect(at24!.points).toHaveLength(at48!.points.length); + expect(near(at48!.points, at24!.points)).toBe(true); + }); + + it("draws the same levelling lane from 24 kHz as from 48 kHz", () => { + const at48 = analyseLevelling(talk(48_000), 48_000); + const at24 = analyseLevelling(talk(24_000), 24_000); + expect(at48.length).toBeGreaterThan(0); + expect(at24).toHaveLength(at48.length); + expect(near(at48, at24)).toBe(true); + }); +}); diff --git a/packages/core/src/audioCarve.ts b/packages/core/src/audioCarve.ts index bd09a14400..dff1aed988 100644 --- a/packages/core/src/audioCarve.ts +++ b/packages/core/src/audioCarve.ts @@ -17,15 +17,22 @@ import { type HfAudioFxChain, type HfAudioFxNode, } from "./audioFx.js"; +import { windowDb, windowSizeFor } from "./audioAnalysis"; import { fft } from "./fft"; +/** A symmetric Hann window of `size` samples. */ +function hannWindow(size: number): Float32Array { + const window = new Float32Array(size); + for (let i = 0; i < size; i++) window[i] = 0.5 - 0.5 * Math.cos((2 * Math.PI * i) / (size - 1)); + return window; +} + export const HF_AUDIO_CARVE_ATTR = "data-fx-carve"; /** Third-octave centres spanning the range speech actually occupies. */ const CANDIDATE_CENTERS_HZ = [160, 250, 400, 630, 1000, 1600, 2500, 4000, 6000] as const; -const FRAME = 4096; -const HOP = 2048; +const FRAME_SECONDS = 4096 / 48_000; export interface HfCarveBand { freq: number; @@ -352,6 +359,8 @@ function powerSpectrum( mono: Float32Array, sampleRate: number, ): { freqs: number[]; power: number[] } { + const FRAME = windowSizeFor(sampleRate, FRAME_SECONDS); + const HOP = FRAME / 2; const n = Math.max(mono.length, FRAME); const padded = mono.length >= FRAME @@ -362,8 +371,7 @@ function powerSpectrum( return p; })(); - const window = new Float32Array(FRAME); - for (let i = 0; i < FRAME; i++) window[i] = 0.5 - 0.5 * Math.cos((2 * Math.PI * i) / (FRAME - 1)); + const window = hannWindow(FRAME); const bins = FRAME / 2 + 1; const acc = new Float64Array(bins); @@ -601,8 +609,8 @@ export function analyseCarveDynamics( ): HfCarveDynamics[] { if (voice.length === 0 || bands.length === 0) return []; - const window = new Float32Array(FRAME); - for (let i = 0; i < FRAME; i++) window[i] = 0.5 - 0.5 * Math.cos((2 * Math.PI * i) / (FRAME - 1)); + const FRAME = windowSizeFor(sampleRate, FRAME_SECONDS); + const window = hannWindow(FRAME); // One window per emitted point, so the hop is what keeps the lane in budget. const hop = Math.max(FRAME, Math.ceil(voice.length / POINT_BUDGET)); @@ -654,21 +662,6 @@ export function analyseCarveDynamics( }); } -/** Level in dB of one window, or -Infinity for silence. */ -function windowDb(samples: Float32Array, from: number, count: number): number { - let sum = 0; - let n = 0; - for (let i = from; i < from + count; i++) { - const s = samples[i]; - if (s === undefined) break; - sum += s * s; - n += 1; - } - if (n === 0) return Number.NEGATIVE_INFINITY; - const rms = Math.sqrt(sum / n); - return rms > 0 ? 20 * Math.log10(rms) : Number.NEGATIVE_INFINITY; -} - /** * The level envelope that keeps a bed under a voice. * @@ -692,6 +685,7 @@ export function analyseCarveDuck( ): { t: number; v: number }[] { if (voice.length === 0 || profile.duckDb <= 0) return []; + const FRAME = windowSizeFor(sampleRate, FRAME_SECONDS); const hop = Math.max(FRAME, Math.ceil(voice.length / POINT_BUDGET)); const bedOffset = Math.round(offsetSeconds * sampleRate); diff --git a/packages/core/src/audioDecode.test.ts b/packages/core/src/audioDecode.test.ts new file mode 100644 index 0000000000..adf2ed6825 --- /dev/null +++ b/packages/core/src/audioDecode.test.ts @@ -0,0 +1,85 @@ +import { afterEach, describe, expect, it, vi } from "vitest"; +import { + AudioTooLong, + UNREAD_LENGTH_MAX_BYTES, + decodeAudioWithin, + pcmRateFor, +} from "./audioDecode"; + +const decoded = {} as AudioBuffer; +const context = () => ({ decodeAudioData: vi.fn(async () => decoded) }); +const served = () => + vi.fn(async () => ({ ok: true, arrayBuffer: async () => new ArrayBuffer(8) }) as Response); +const decodeWith = (ctx: ReturnType, ...rest: [string, object?]) => + decodeAudioWithin(ctx as unknown as BaseAudioContext, ...rest); + +afterEach(() => vi.unstubAllGlobals()); + +describe("decodeAudioWithin", () => { + it("decodes a half-hour file, whose decode fits the page", async () => { + vi.stubGlobal("mediaHeaderSeconds", () => 30 * 60); + const ctx = context(); + const fetch = served(); + await expect(decodeWith(ctx, "/a.mp3", { fetch })).resolves.toBe(decoded); + expect(fetch).toHaveBeenCalledWith("/a.mp3"); + }); + + it("refuses an hour-long file before a byte of it is fetched or decoded", async () => { + vi.stubGlobal("mediaHeaderSeconds", () => 3600); + const ctx = context(); + const fetch = served(); + const refused = decodeWith(ctx, "/hour.mp3", { fetch }); + await expect(refused).rejects.toBeInstanceOf(AudioTooLong); + await expect(refused).rejects.toMatchObject({ seconds: 3600 }); + expect(fetch).not.toHaveBeenCalled(); + expect(ctx.decodeAudioData).not.toHaveBeenCalled(); + }); + + // A recorded webm or ogg blob reads its duration as Infinity; main decoded those. + it("decodes a short file whose length cannot be read, its bytes alone keeping it in budget", async () => { + vi.stubGlobal("mediaHeaderSeconds", () => null); + const ctx = context(); + await expect(decodeWith(ctx, "blob:recording", { fetch: served() })).resolves.toBe(decoded); + expect(ctx.decodeAudioData).toHaveBeenCalledOnce(); + }); + + it("refuses an unread-length file whose bytes could pass the budget, without decoding it", async () => { + vi.stubGlobal("mediaHeaderSeconds", () => null); + const ctx = context(); + const big = new ArrayBuffer(UNREAD_LENGTH_MAX_BYTES + 1); + const fetch = vi.fn(async () => ({ ok: true, arrayBuffer: async () => big }) as Response); + await expect(decodeWith(ctx, "/odd.bin", { fetch })).rejects.toMatchObject({ + name: "AudioTooLong", + seconds: null, + }); + expect(ctx.decodeAudioData).not.toHaveBeenCalled(); + }); + + it("takes the length the caller's own element read over the header", async () => { + const header = vi.fn(() => 3600); + vi.stubGlobal("mediaHeaderSeconds", header); + await expect( + decodeWith(context(), "/a.mp3", { fetch: served(), knownSeconds: 30 }), + ).resolves.toBe(decoded); + vi.stubGlobal("mediaHeaderSeconds", () => 30); + await expect( + decodeWith(context(), "/a.mp3", { fetch: served(), knownSeconds: 3600 }), + ).rejects.toBeInstanceOf(AudioTooLong); + expect(header).not.toHaveBeenCalled(); + }); + + it("does not decode a refused request's error page", async () => { + const ctx = context(); + const fetch = vi.fn(async () => ({ ok: false, status: 404 }) as Response); + await expect(decodeWith(ctx, "/gone.mp3", { fetch })).rejects.toThrow("404"); + expect(ctx.decodeAudioData).not.toHaveBeenCalled(); + }); +}); + +describe("pcmRateFor", () => { + it("keeps 48 kHz up to twenty minutes and halves it past that", () => { + expect(pcmRateFor(20 * 60)).toBe(48_000); + expect(pcmRateFor(20 * 60 + 1)).toBe(24_000); + expect(pcmRateFor(90 * 60)).toBe(24_000); + }); +}); diff --git a/packages/core/src/audioDecode.ts b/packages/core/src/audioDecode.ts new file mode 100644 index 0000000000..1d693d35cf --- /dev/null +++ b/packages/core/src/audioDecode.ts @@ -0,0 +1,76 @@ +/** A whole decode in a page peaks at ~2x the file as stereo 48 kHz, whatever the context's rate (90 min: 4 GB). */ + +import { wallClearTimeout, wallSetTimeout } from "./runtime/wallClock"; + +const PEAK_BYTES_PER_SECOND = 48_000 * 2 * 4 * 2; +export const DECODE_PEAK_BUDGET_BYTES = 1.5 * 1024 ** 3; +export const decodePeakBytes = (seconds: number): number => seconds * PEAK_BYTES_PER_SECOND; + +/** Analysis PCM rate: 48 kHz up to 20 minutes, 24 kHz past it, so a long file holds half the samples. */ +export const pcmRateFor = (seconds: number): 48_000 | 24_000 => + seconds <= 20 * 60 ? 48_000 : 24_000; + +export class AudioTooLong extends Error { + constructor(readonly seconds: number | null) { + super("This clip is too long to decode here."); + this.name = "AudioTooLong"; + } +} + +const HEADER_READ_MS = 10_000; + +/** The length a media element reads from the file's header (metadata only, no audio decoded); null when unread. */ +export function headerSeconds(url: string): Promise { + if (typeof document === "undefined") return Promise.resolve(null); + return new Promise((resolve) => { + const audio = document.createElement("audio"); + audio.preload = "metadata"; + // timer-ok: a stalled header read counts as unread. Wall clock: a render runs page timers on film time. + const late = wallSetTimeout(() => done(null), HEADER_READ_MS); + const done = (seconds: number | null) => { + wallClearTimeout(late); + audio.onloadedmetadata = audio.onerror = null; + audio.removeAttribute("src"); + audio.load(); + resolve(seconds); + }; + audio.onloadedmetadata = () => done(Number.isFinite(audio.duration) ? audio.duration : null); + audio.onerror = () => done(null); + audio.src = url; + audio.load(); + }); +} + +/** An unread length (a recorded blob reads Infinity): its bytes alone keep the peak in budget even at 8 kbps. */ +export const UNREAD_LENGTH_MAX_BYTES = (DECODE_PEAK_BUDGET_BYTES / PEAK_BYTES_PER_SECOND) * 1_000; + +/** Throws AudioTooLong when `url`'s length, from `knownSeconds` (the caller's own element) or the file's header, is + * past DECODE_PEAK_BUDGET_BYTES. Resolves "unread" when neither gives a length: unreadFits judges its bytes. */ +export async function assertDecodeFits( + url: string, + knownSeconds?: number, +): Promise<"read" | "unread"> { + const seconds = + knownSeconds !== undefined && Number.isFinite(knownSeconds) && knownSeconds > 0 + ? knownSeconds + : await headerSeconds(url); + if (seconds === null) return "unread"; + if (decodePeakBytes(seconds) > DECODE_PEAK_BUDGET_BYTES) throw new AudioTooLong(seconds); + return "read"; +} + +export const unreadFits = (byteLength: number): boolean => byteLength <= UNREAD_LENGTH_MAX_BYTES; + +/** `url` decoded whole into `context` within the budget: a read length past it is never fetched. */ +export async function decodeAudioWithin( + context: BaseAudioContext, + url: string, + options: { fetch?: (url: string) => Promise; knownSeconds?: number } = {}, +): Promise { + const length = await assertDecodeFits(url, options.knownSeconds); + const response = await (options.fetch ?? globalThis.fetch)(url); + if (!response.ok) throw new Error(`Audio request failed (${response.status})`); + const bytes = await response.arrayBuffer(); + if (length === "unread" && !unreadFits(bytes.byteLength)) throw new AudioTooLong(null); + return context.decodeAudioData(bytes); +} diff --git a/packages/core/src/audioLeveller.ts b/packages/core/src/audioLeveller.ts index 1c1f77ee80..9cb0cdeeb1 100644 --- a/packages/core/src/audioLeveller.ts +++ b/packages/core/src/audioLeveller.ts @@ -30,6 +30,7 @@ import { type HfAutomation, type HfAutomationPoint, } from "./audioAutomation.js"; +import { windowDb, windowSizeFor } from "./audioAnalysis"; import { HF_AUDIO_FX_CHAIN_VERSION, mintAudioFxNodeId, @@ -39,7 +40,7 @@ import { } from "./audioFx.js"; /** One window per emitted point; the hop keeps the lane inside its budget. */ -const FRAME = 4096; +const FRAME_SECONDS = 4096 / 48_000; const POINT_BUDGET = 400; /** Below this, a window is silence rather than a quiet passage worth lifting. */ const FLOOR_BELOW_PEAK_DB = 42; @@ -75,21 +76,6 @@ export function levellerProfile(strength: number): HfLevellerProfile { return { correction: Number((0.25 + s * 0.6).toFixed(3)) }; } -/** Level in dB of one window, or -Infinity for silence. */ -function windowDb(samples: Float32Array, from: number, count: number): number { - let sum = 0; - let n = 0; - for (let i = from; i < from + count; i += 1) { - const s = samples[i]; - if (s === undefined) break; - sum += s * s; - n += 1; - } - if (n === 0) return Number.NEGATIVE_INFINITY; - const rms = Math.sqrt(sum / n); - return rms > 0 ? 20 * Math.log10(rms) : Number.NEGATIVE_INFINITY; -} - /** * Measure a track and return the gain moves that even it out, in dB against * clip-local seconds. Empty when there is nothing worth correcting. @@ -101,6 +87,7 @@ export function analyseLevelling( ): HfAutomationPoint[] { if (samples.length === 0 || sampleRate <= 0) return []; const profile = levellerProfile(strength); + const FRAME = windowSizeFor(sampleRate, FRAME_SECONDS); const hop = Math.max(FRAME, Math.ceil(samples.length / POINT_BUDGET)); const levels: number[] = []; diff --git a/packages/core/src/beats/beatDetection.test.ts b/packages/core/src/beats/beatDetection.test.ts index 22f9e94bd9..e501fb227f 100644 --- a/packages/core/src/beats/beatDetection.test.ts +++ b/packages/core/src/beats/beatDetection.test.ts @@ -13,7 +13,11 @@ vi.mock("../fft", async (importOriginal) => { import { signalProvider, type AudioSignal } from "../audioAnalysis"; import { STEADY_BEAT_CONFIDENCE, rhythm } from "../audioRhythm"; -import { analyzeMusicFromBuffer, analyzeMusicFromSignal } from "./beatDetection"; +import { + analyzeMusicFromBuffer, + analyzeMusicFromSignal, + analyzeMusicFromUrl, +} from "./beatDetection"; const RATE = 22_050; @@ -222,3 +226,23 @@ describe("analyzeMusicFromBuffer", () => { expect(Math.min(...analysis.beatStrengths)).toBeGreaterThan(0.5); }); }); + +describe("analyzeMusicFromUrl", () => { + it("never fetches an hour-long song, too long to decode in the page, and closes its context", async () => { + const close = vi.fn(async () => {}); + vi.stubGlobal( + "AudioContext", + class { + close = close; + decodeAudioData = vi.fn(); + }, + ); + vi.stubGlobal("mediaHeaderSeconds", () => 3600); + const fetch = vi.fn(); + vi.stubGlobal("fetch", fetch); + await expect(analyzeMusicFromUrl("/song.mp3")).rejects.toMatchObject({ name: "AudioTooLong" }); + expect(fetch).not.toHaveBeenCalled(); + expect(close).toHaveBeenCalled(); + vi.unstubAllGlobals(); + }); +}); diff --git a/packages/core/src/beats/beatDetection.ts b/packages/core/src/beats/beatDetection.ts index ae3a1460f5..0850812ec4 100644 --- a/packages/core/src/beats/beatDetection.ts +++ b/packages/core/src/beats/beatDetection.ts @@ -1,6 +1,7 @@ import { energyMixSteps, type AudioSignal } from "../audioAnalysis"; import { rhythmSteps, tempoOf } from "../audioRhythm"; import { finish, type Steps } from "../audioSteps"; +import { decodeAudioWithin } from "../audioDecode"; export interface MusicBeatAnalysis { beatTimes: number[]; @@ -111,9 +112,7 @@ export async function analyzeMusicFromUrl( await options.pause?.(); const audioContext = new AudioContext(); try { - const response = await fetch(url); - const arrayBuffer = await response.arrayBuffer(); - const audioBuffer = await audioContext.decodeAudioData(arrayBuffer); + const audioBuffer = await decodeAudioWithin(audioContext, url); return analyzeMusicFromBuffer(audioBuffer, options); } finally { await audioContext.close(); diff --git a/packages/core/src/runtime/webAudioTransport.test.ts b/packages/core/src/runtime/webAudioTransport.test.ts index e36ab16098..ab00b018b7 100644 --- a/packages/core/src/runtime/webAudioTransport.test.ts +++ b/packages/core/src/runtime/webAudioTransport.test.ts @@ -1855,6 +1855,17 @@ describe("WebAudioTransport", () => { it("leaves a clip that has not loaded to its source", () => { expect(transport().fitsDecodeBudget(audio("a.mp4", Number.NaN))).toBe(false); }); + + it("never fetches an hour-long source, too long to decode in the page, on a path that skips the budget", async () => { + vi.stubGlobal("mediaHeaderSeconds", () => 3600); + const fetch = vi.fn(); + vi.stubGlobal("fetch", fetch); + const t = transport(); + await expect(t.decodeAudioElement(audio("long.mp4", Number.NaN))).resolves.toBeNull(); + await expect(t.decodeAudioElement(audio("hour.mp4", 3600))).resolves.toBeNull(); + expect(fetch).not.toHaveBeenCalled(); + vi.unstubAllGlobals(); + }); }); describe("decodeAudioElement retry policy (late-asset self-heal)", () => { diff --git a/packages/core/src/runtime/webAudioTransport.ts b/packages/core/src/runtime/webAudioTransport.ts index a6c5812f80..8079b93702 100644 --- a/packages/core/src/runtime/webAudioTransport.ts +++ b/packages/core/src/runtime/webAudioTransport.ts @@ -26,6 +26,7 @@ import { assetUrl } from "./assetUrl.js"; import { mediaElementTime } from "./mediaClock.js"; import { sourceLengthOf } from "./sourceLength.js"; import { clampFadesToDuration, fadeGain, readElementFades } from "../audioFade.js"; +import { AudioTooLong, assertDecodeFits, unreadFits } from "../audioDecode.js"; const MASTER_FX_ATTRS: FxAttributes = { automation: null }; @@ -406,17 +407,23 @@ export class WebAudioTransport { return bytes; } - private async fetchAndDecode(src: string, el: HTMLMediaElement): Promise { - if (this._bufferCache.has(src)) return this._bufferCache.get(src)!; + /** Whether its length was read, for a source that has not failed for good and is not too long to decode. */ + private async mayDecode(src: string, el: HTMLMediaElement): Promise<"read" | "unread" | null> { if (this._failedSrcs.has(src)) return null; - if (!this._ctx) return null; + try { + return await assertDecodeFits(src, el.duration); + } catch (err) { + if (!(err instanceof AudioTooLong)) throw err; + this._failedSrcs.add(src); + return null; + } + } - // Fetch the bytes. A network error or non-OK status (e.g. a 404 for an - // asset that simply has not been uploaded yet) is TRANSIENT — return null - // WITHOUT blacklisting, so the next play/seek generation retries once the - // asset becomes available. (Previously these were added to `_failedSrcs`, - // which is never cleared, permanently silencing a merely-late track.) - let arrayBuffer: ArrayBuffer; + // Fetch the bytes. A network error or non-OK status (e.g. a 404 for an + // asset that simply has not been uploaded yet) is TRANSIENT — return null + // WITHOUT blacklisting, so the next play/seek generation retries once the + // asset becomes available. + private async fetchBytes(src: string, el: HTMLMediaElement): Promise { try { // `no-store`: a retry must actually re-request the asset — not replay a // cached 404/stale response from the failed attempt that we chose not to @@ -427,16 +434,40 @@ export class WebAudioTransport { reportMediaLoadFailure(el, "fetch", response.status); return null; } - arrayBuffer = await response.arrayBuffer(); + return await response.arrayBuffer(); } catch (err) { swallow("webAudioTransport.fetch", err); reportMediaLoadFailure(el, "fetch", null); return null; } + } - // A decode failure means the bytes themselves are unusable (corrupt or an - // unsupported codec) — that IS permanent, so blacklist to avoid re-decoding - // the same bad payload on every generation. + private async fetchAndDecode(src: string, el: HTMLMediaElement): Promise { + if (this._bufferCache.has(src)) return this._bufferCache.get(src)!; + if (!this._ctx) return null; + const length = await this.mayDecode(src, el); + if (!length) return null; + + const arrayBuffer = await this.fetchBytes(src, el); + if (!arrayBuffer) return null; + + // A source whose length can't be read and whose bytes could pass the budget plays through its element. + if (length === "unread" && !unreadFits(arrayBuffer.byteLength)) { + this._failedSrcs.add(src); + return null; + } + return this.decode(src, el, arrayBuffer); + } + + // A decode failure means the bytes themselves are unusable (corrupt or an + // unsupported codec) — that IS permanent, so blacklist to avoid re-decoding + // the same bad payload on every generation. + private async decode( + src: string, + el: HTMLMediaElement, + arrayBuffer: ArrayBuffer, + ): Promise { + if (!this._ctx) return null; try { const audioBuffer = await this._ctx.decodeAudioData(arrayBuffer); // A file whose container timescale disagrees with its stream decodes short; its element plays it whole. diff --git a/packages/core/vitest.config.ts b/packages/core/vitest.config.ts index 1bf9d00259..69db1bdd77 100644 --- a/packages/core/vitest.config.ts +++ b/packages/core/vitest.config.ts @@ -4,7 +4,7 @@ export default defineConfig({ test: { include: ["src/**/*.test.ts"], environment: "jsdom", - setupFiles: ["./vitest.setup.ts"], + setupFiles: ["./vitest.setup.ts", "./vitest.mediaHeader.ts"], coverage: { provider: "v8", include: ["src/runtime/**/*.ts"], diff --git a/packages/core/vitest.mediaHeader.ts b/packages/core/vitest.mediaHeader.ts new file mode 100644 index 0000000000..c9adac7652 --- /dev/null +++ b/packages/core/vitest.mediaHeader.ts @@ -0,0 +1,17 @@ +// The test DOM loads no media. A detached element's header read (src/audioDecode.ts) answers +// mediaHeaderSeconds(url): one minute unless a test stubs it; null answers as unreadable. +(globalThis as Record).mediaHeaderSeconds = (): number | null => 60; +if (typeof HTMLMediaElement !== "undefined") { + const loadMedia = HTMLMediaElement.prototype.load; + HTMLMediaElement.prototype.load = function (this: HTMLMediaElement) { + const src = this.getAttribute("src"); + if (this.isConnected || !src) return loadMedia.call(this); + const read = globalThis as unknown as { mediaHeaderSeconds: (url: string) => number | null }; + const seconds = read.mediaHeaderSeconds(src); + if (seconds !== null) + Object.defineProperty(this, "duration", { configurable: true, value: seconds }); + queueMicrotask(() => + this.dispatchEvent(new Event(seconds === null ? "error" : "loadedmetadata")), + ); + }; +} diff --git a/packages/studio-server/src/createStudioApi.originGuard.test.ts b/packages/studio-server/src/createStudioApi.originGuard.test.ts index 2445cda227..56e5b4fc5d 100644 --- a/packages/studio-server/src/createStudioApi.originGuard.test.ts +++ b/packages/studio-server/src/createStudioApi.originGuard.test.ts @@ -286,6 +286,8 @@ describe("createStudioApi media analysis from another site", () => { ["waveform", "same-site"], ["peaks", "cross-site"], ["peaks", "same-site"], + ["pcm", "cross-site"], + ["pcm", "same-site"], ])("refuses a %s request marked %s", async (route, site) => { const { app } = createApp(); const res = await app.request(`http://localhost/projects/demo/${route}/talk.mp4`, { diff --git a/packages/studio-server/src/createStudioApi.ts b/packages/studio-server/src/createStudioApi.ts index 2ae9ea7e1a..549b35deb5 100644 --- a/packages/studio-server/src/createStudioApi.ts +++ b/packages/studio-server/src/createStudioApi.ts @@ -219,6 +219,7 @@ export function createStudioApi(adapter: StudioApiAdapter, options: StudioApiOpt api.use("/projects/:id/thumbnail/*", refuseForAnotherSite("thumbnail")); api.use("/projects/:id/waveform/*", refuseForAnotherSite("waveform")); api.use("/projects/:id/peaks/*", refuseForAnotherSite("peaks")); + api.use("/projects/:id/pcm/*", refuseForAnotherSite("pcm")); api.use("/projects/:id/image-thumbnail/*", refuseForAnotherSite("image thumbnail")); api.use("/projects/:id/media/metadata", refuseForAnotherSite("media metadata")); api.use("/projects/:id/lint", refuseForAnotherSite("lint")); diff --git a/packages/studio-server/src/helpers/audioDecodes.ts b/packages/studio-server/src/helpers/audioDecodes.ts index e542aca39d..bfedfecc7b 100644 --- a/packages/studio-server/src/helpers/audioDecodes.ts +++ b/packages/studio-server/src/helpers/audioDecodes.ts @@ -14,6 +14,9 @@ export class AudioDecodeTimeoutError extends Error { const runDecode = createJobSlots(AUDIO_DECODE_LIMIT); +export const inAudioDecodeSlot = (run: () => Promise, signal: AbortSignal) => + runDecode(run, signal); + interface SharedDecode { result: Promise; waiting: number; diff --git a/packages/studio-server/src/routes/pcm.test.ts b/packages/studio-server/src/routes/pcm.test.ts new file mode 100644 index 0000000000..c95bcbaa2c --- /dev/null +++ b/packages/studio-server/src/routes/pcm.test.ts @@ -0,0 +1,107 @@ +import { afterEach, describe, expect, it, vi } from "vitest"; +import { Hono } from "hono"; +import { execFileSync } from "node:child_process"; +import { mkdtempSync, rmSync, writeFileSync } from "node:fs"; +import { tmpdir } from "node:os"; +import { join } from "node:path"; +import { clearFfBinaryLookupCache, findFfBinary } from "@hyperframes/parsers/ff-binaries"; +import { registerPcmRoutes } from "./pcm"; +import { stubAdapter } from "./stubAdapter.test-helpers"; + +const ffmpeg = findFfBinary("ffmpeg"); +const dirs: string[] = []; +afterEach(() => { + for (const dir of dirs.splice(0)) rmSync(dir, { recursive: true, force: true }); +}); + +function project(): { app: Hono; dir: string } { + const dir = mkdtempSync(join(tmpdir(), "hf-pcm-route-")); + dirs.push(dir); + const app = new Hono(); + registerPcmRoutes(app, stubAdapter(dir)); + return { app, dir }; +} + +describe("GET /projects/:id/pcm/*", () => { + it.skipIf(!ffmpeg)("streams the file's first channel at the asked rate", async () => { + const { app, dir } = project(); + // Left a 440 Hz tone, right silence: the first channel, not a downmix, is what the fx read today. + execFileSync(ffmpeg ?? "ffmpeg", [ + ...["-v", "error", "-f", "lavfi", "-i", "sine=frequency=440:duration=2:sample_rate=44100"], + ...["-f", "lavfi", "-i", "anullsrc=r=44100:cl=mono", "-t", "2"], + ...["-filter_complex", "[0][1]amerge=inputs=2", join(dir, "bed.wav")], + ]); + for (const rate of [48_000, 24_000]) { + const res = await app.request(`http://localhost/projects/p/pcm/bed.wav?rate=${rate}`); + expect(res.headers.get("x-sample-rate")).toBe(String(rate)); + const samples = new Float32Array(await res.arrayBuffer()); + expect(Math.abs(samples.length - 2 * rate)).toBeLessThan(rate / 100); + expect(Math.max(...samples.subarray(rate / 2, rate))).toBeGreaterThan(0.1); + } + }); + + // fails without the fix: beats read one sample-domain mix, so a channel inverted against the other summed to silence + // and no beats were found where main found them. + it.skipIf(!ffmpeg)( + "streams every channel apart for beats, so out-of-phase stereo keeps its sound", + async () => { + const { app, dir } = project(); + execFileSync(ffmpeg ?? "ffmpeg", [ + ...["-v", "error", "-f", "lavfi", "-i", "sine=frequency=440:duration=1:sample_rate=48000"], + ...[ + "-filter_complex", + "[0]asplit[l][r];[r]volume=-1[ri];[l][ri]amerge=inputs=2", + join(dir, "flip.wav"), + ], + ]); + const res = await app.request( + "http://localhost/projects/p/pcm/flip.wav?rate=48000&channels=all", + ); + expect(res.headers.get("x-channels")).toBe("2"); + const frames = new Float32Array(await res.arrayBuffer()); + const left = frames.filter((_, i) => i % 2 === 0); + const sum = frames.filter((_, i) => i % 2 === 0).map((l, i) => l + frames[i * 2 + 1]!); + expect(Math.max(...left.subarray(12_000, 24_000))).toBeGreaterThan(0.1); + expect(Math.max(...sum.subarray(12_000, 24_000).map(Math.abs))).toBeLessThan(0.01); + }, + ); + + // fails without the fix: ffmpeg failing partway still ended the body cleanly, and the cut-short samples were read. + it.skipIf(!ffmpeg || process.platform === "win32")( + "errors the body when ffmpeg fails partway, never a 200 that ends cleanly", + async () => { + const { app, dir } = project(); + execFileSync(ffmpeg ?? "ffmpeg", [ + ...["-v", "error", "-f", "lavfi", "-i", "sine=frequency=440:duration=1"], + join(dir, "tone.wav"), + ]); + // An ffmpeg that sends some samples, then fails. + const failing = join(dir, "ffmpeg-fails"); + writeFileSync(failing, "#!/bin/sh\nhead -c 4000 /dev/zero\nexit 1\n", { mode: 0o755 }); + vi.stubEnv("HYPERFRAMES_FFMPEG_PATH", failing); + clearFfBinaryLookupCache(); + try { + const res = await app.request("http://localhost/projects/p/pcm/tone.wav?rate=48000"); + expect(res.status).toBe(200); + await expect(res.arrayBuffer()).rejects.toThrow(); + } finally { + vi.unstubAllEnvs(); + clearFfBinaryLookupCache(); + } + }, + ); + + it("refuses any rate but the two analysis rates, and any file outside the project", async () => { + const { app, dir } = project(); + writeFileSync(join(dir, "bed.wav"), "audio"); + expect((await app.request("http://localhost/projects/p/pcm/bed.wav?rate=8000")).status).toBe( + 400, + ); + expect( + (await app.request("http://localhost/projects/p/pcm/../../etc/passwd?rate=48000")).status, + ).toBe(404); + expect((await app.request("http://localhost/projects/p/pcm/gone.wav?rate=48000")).status).toBe( + 404, + ); + }); +}); diff --git a/packages/studio-server/src/routes/pcm.ts b/packages/studio-server/src/routes/pcm.ts new file mode 100644 index 0000000000..4d1ad883d2 --- /dev/null +++ b/packages/studio-server/src/routes/pcm.ts @@ -0,0 +1,73 @@ +import { spawn, type ChildProcess } from "node:child_process"; +import { stat } from "node:fs/promises"; +import { resolve } from "node:path"; +import { PassThrough, Readable } from "node:stream"; +import { isWithinProjectRoot } from "@hyperframes/parsers/asset-resolution"; +import { requireFfBinary } from "@hyperframes/parsers/ff-binaries"; +import type { Hono } from "hono"; +import type { StudioApiAdapter } from "../types.js"; +import { probeAudioTrack } from "../helpers/mediaMetadata.js"; +import { mediaInputArgs } from "../helpers/mediaExtensions.js"; +import { inAudioDecodeSlot } from "../helpers/audioDecodes.js"; +import { requestSubPath } from "../helpers/requestSubPath.js"; + +const RATES = new Set([48_000, 24_000]); + +/** The file at `sub` inside the project, or null for no path, one outside it or one missing. */ +async function projectFile(dir: string, sub: string | null): Promise { + if (sub === null) return null; + const path = resolve(dir, sub); + if (!isWithinProjectRoot(dir, path)) return null; + return (await stat(path).catch(() => null)) ? path : null; +} + +/** ffmpeg's output, ending only once ffmpeg has: a decode that fails partway errors the body, never a 200 cut short. */ +function endsWithFfmpeg(proc: ChildProcess, stdout: Readable): PassThrough { + const body = new PassThrough(); + stdout.pipe(body, { end: false }); + proc.once("close", (code) => + code === 0 ? body.end() : body.destroy(new Error(`ffmpeg exited ${code}`)), + ); + proc.once("error", (error) => body.destroy(error)); + return body; +} + +/** A project file's audio for analysis as float32 PCM, streamed, so no page decodes it whole: its first channel (what + * the fx read), or with `channels=all` every channel interleaved (beat detection, which sums each one's power). */ +export function registerPcmRoutes(api: Hono, adapter: StudioApiAdapter): void { + api.get("/projects/:id/pcm/*", async (c) => { + const rate = Number(c.req.query("rate")); + const all = c.req.query("channels") === "all"; + if (!RATES.has(rate)) return c.json({ error: "rate must be 48000 or 24000" }, 400); + const project = await adapter.resolveProject(c.req.param("id")); + if (!project) return c.json({ error: "not found" }, 404); + const audioPath = await projectFile(project.dir, requestSubPath(c.req.url, "projects/:id/pcm")); + if (!audioPath) return c.json({ error: "file not found" }, 404); + const track = await probeAudioTrack(audioPath); + if (!track) return c.json({ error: "no audio stream" }, 422); + const args = [...mediaInputArgs(audioPath), "-i", audioPath, "-map", `0:a:${track.stream}`]; + const out = [...(all ? [] : ["-af", "pan=mono|c0=c0"]), "-ar", String(rate), "-f", "f32le"]; + const proc = await new Promise((started, gone) => { + inAudioDecodeSlot(() => { + const ffmpeg = spawn(requireFfBinary("ffmpeg"), [...args, ...out, "-vn", "pipe:1"], { + stdio: ["ignore", "pipe", "ignore"], + windowsHide: true, + signal: c.req.raw.signal, + }); + started(ffmpeg); + return new Promise((ended) => ffmpeg.once("close", ended)); + }, c.req.raw.signal).catch(gone); + }).catch(() => null); + if (!proc?.stdout) return new Response(null, { status: 499 }); + return new Response( + Readable.toWeb(endsWithFfmpeg(proc, proc.stdout)) as unknown as ReadableStream, + { + headers: { + "content-type": "application/octet-stream", + "x-sample-rate": String(rate), + "x-channels": String(all ? track.channels : 1), + }, + }, + ); + }); +} diff --git a/packages/studio-server/src/routes/waveform.ts b/packages/studio-server/src/routes/waveform.ts index b7c3d61eac..b3bdfdc62c 100644 --- a/packages/studio-server/src/routes/waveform.ts +++ b/packages/studio-server/src/routes/waveform.ts @@ -11,8 +11,10 @@ import { } from "../helpers/waveform.js"; import { requestSubPath } from "../helpers/requestSubPath.js"; import { decodeShared } from "../helpers/audioDecodes.js"; +import { registerPcmRoutes } from "./pcm.js"; export function registerWaveformRoutes(api: Hono, adapter: StudioApiAdapter): void { + registerPcmRoutes(api, adapter); api.get("/projects/:id/waveform/*", async (c) => { const project = await adapter.resolveProject(c.req.param("id")); if (!project) return c.json({ error: "not found" }, 404); diff --git a/packages/studio/src/components/editor/propertyPanelAudioFxGroup.test.tsx b/packages/studio/src/components/editor/propertyPanelAudioFxGroup.test.tsx index 5c44f617c5..3038413078 100644 --- a/packages/studio/src/components/editor/propertyPanelAudioFxGroup.test.tsx +++ b/packages/studio/src/components/editor/propertyPanelAudioFxGroup.test.tsx @@ -406,7 +406,11 @@ describe("AudioFxGroup dynamic carve", () => { } vi.stubGlobal( "fetch", - vi.fn(async () => ({ arrayBuffer: async () => new ArrayBuffer(8) })), + vi.fn(async () => ({ + ok: true, + headers: new Headers(), + arrayBuffer: async () => new ArrayBuffer(8), + })), ); vi.stubGlobal( "OfflineAudioContext", @@ -436,7 +440,11 @@ describe("AudioFxGroup dynamic carve", () => { }); vi.stubGlobal( "fetch", - vi.fn(async () => ({ arrayBuffer: async () => new ArrayBuffer(8) })), + vi.fn(async () => ({ + ok: true, + headers: new Headers(), + arrayBuffer: async () => new ArrayBuffer(8), + })), ); vi.stubGlobal( "OfflineAudioContext", @@ -465,7 +473,11 @@ describe("AudioFxGroup dynamic carve", () => { async function levelledLane(data: Float32Array, dataAttributes: Record) { vi.stubGlobal( "fetch", - vi.fn(async () => ({ arrayBuffer: async () => new ArrayBuffer(8) })), + vi.fn(async () => ({ + ok: true, + headers: new Headers(), + arrayBuffer: async () => new ArrayBuffer(8), + })), ); vi.stubGlobal( "OfflineAudioContext", @@ -493,6 +505,22 @@ describe("AudioFxGroup dynamic carve", () => { lane.points.reduce((best, p) => (Math.abs(p.t - t) < Math.abs(best.t - t) ? p : best)); } + it("Even Out Levels never fetches an hour-long clip with no project path, too long to decode in the page", async () => { + stubDecode(); + vi.stubGlobal("mediaHeaderSeconds", () => 3600); + const { host, onSetAttributeQuiet } = mount({ "fx-chain": CHAIN }); + document.getElementById("bed")?.setAttribute("src", "bed.wav"); + act(() => byTextButton(host, "Audio FX")?.click()); + act(() => byTextButton(host, "+ effect")?.click()); + await act(async () => { + byTextButton(host, "Even Out Levels")?.click(); + await new Promise((r) => setTimeout(r, 0)); + await new Promise((r) => setTimeout(r, 0)); + }); + expect(globalThis.fetch).not.toHaveBeenCalled(); + expect(writeTo(onSetAttributeQuiet.mock.calls, "data-automation")).toBeFalsy(); + }); + /** A 300 Hz tone, 16 s long: quiet between `quietFrom` and `quietTo`, loud elsewhere. */ function toneWithQuietPassage(quietFrom: number, quietTo: number): Float32Array { const data = new Float32Array(SAMPLE_RATE * 16); @@ -503,6 +531,68 @@ describe("AudioFxGroup dynamic carve", () => { return data; } + /** A project file: the preview frame's base is the project's preview path, so its clips read the server's PCM. */ + function inProject(): () => void { + const base = document.createElement("base"); + base.href = "http://localhost/api/projects/p/preview/"; + document.head.append(base); + return () => base.remove(); + } + + /** The server's PCM for every file: `data` as float32 bytes, at whatever rate was asked. */ + function stubServerPcm(data: Float32Array): ReturnType { + vi.stubGlobal( + "fetch", + vi.fn(async () => ({ + ok: true, + headers: new Headers(), + arrayBuffer: async () => data.slice().buffer, + })), + ); + const decode = vi.fn(); + vi.stubGlobal( + "OfflineAudioContext", + class { + decodeAudioData = decode; + }, + ); + return decode; + } + + const askedUrls = () => + (globalThis.fetch as unknown as { mock: { calls: unknown[][] } }).mock.calls.map((c) => + String(c[0]), + ); + + async function runLeveller(host: HTMLElement): Promise { + act(() => byTextButton(host, "Audio FX")?.click()); + act(() => byTextButton(host, "+ effect")?.click()); + await act(async () => { + byTextButton(host, "Even Out Levels")?.click(); + await new Promise((r) => setTimeout(r, 0)); + await new Promise((r) => setTimeout(r, 0)); + }); + } + + it.each([ + { minutes: 90, rate: 24_000 }, + { minutes: 12, rate: 48_000 }, + ])( + "levels a $minutes-minute project clip from the server's $rate Hz samples, never decoding it in the page", + async ({ minutes, rate }) => { + const leave = inProject(); + vi.stubGlobal("mediaHeaderSeconds", () => minutes * 60); + const decode = stubServerPcm(toneWithQuietPassage(2, 5)); + const { host, onSetAttributeQuiet } = mount({ "fx-chain": CHAIN }); + document.getElementById("bed")?.setAttribute("src", "bed.wav"); + await runLeveller(host); + expect(askedUrls()).toEqual([`http://localhost/api/projects/p/pcm/bed.wav?rate=${rate}`]); + expect(decode).not.toHaveBeenCalled(); + expect(writeTo(onSetAttributeQuiet.mock.calls, "data-automation")).toBeTruthy(); + leave(); + }, + ); + it("levels the part of the file the clip plays, not the file from its start", async () => { // A lane's `t` is seconds from the start of the CLIP, but the decode is the // whole file. The file is quiet 2-5 s and the clip trims the first 2 s, so @@ -856,6 +946,87 @@ describe("AudioFxGroup dynamic carve", () => { expect(nodes.some((n) => n.type === "peaking")).toBe(true); }); + it("carves a 90-minute project bed under a short voice, both read from the server at 24 kHz, no page decode", async () => { + const leave = inProject(); + stubDecode(); + const decode = vi.fn(); + vi.stubGlobal( + "OfflineAudioContext", + class { + decodeAudioData = decode; + }, + ); + const voice = new Float32Array(24_000 * 4).map((_, i) => { + const t = i / 24_000; + return t > 1 && t < 3 ? 0.7 * Math.sin(2 * Math.PI * 1000 * t) : 0; + }); + vi.stubGlobal( + "fetch", + vi.fn(async () => ({ + ok: true, + headers: new Headers(), + arrayBuffer: async () => voice.slice().buffer, + })), + ); + vi.stubGlobal("mediaHeaderSeconds", (url: string) => (url.includes("bed") ? 90 * 60 : 60)); + const { host, onSetAttributeQuiet } = mount( + { + "fx-chain": JSON.stringify({ version: 1, nodes: [] }), + "fx-carve": JSON.stringify({ enabled: true, sources: ["vo"], strength: 0.3 }), + start: "0", + }, + false, + ); + document.getElementById("vo")!.setAttribute("src", "voice.wav"); + document.getElementById("bed")!.setAttribute("src", "bed.m4a"); + const dial = host.querySelector(".hf-fx-carve input[type=range]")!; + await act(async () => { + Object.getOwnPropertyDescriptor(HTMLInputElement.prototype, "value")?.set?.call(dial, "0.6"); + dial.dispatchEvent(new Event("input", { bubbles: true })); + dial.dispatchEvent(new PointerEvent("pointerup", { bubbles: true })); + }); + expect(askedUrls().sort()).toEqual([ + "http://localhost/api/projects/p/pcm/bed.m4a?rate=24000", + "http://localhost/api/projects/p/pcm/voice.wav?rate=24000", + ]); + expect(decode).not.toHaveBeenCalled(); + const chainWrite = writeTo(onSetAttributeQuiet.mock.calls, "data-fx-chain"); + expect(parseWrite(chainWrite!).nodes.some((n: { fromCarve?: boolean }) => n.fromCarve)).toBe( + true, + ); + leave(); + }); + + it("leaves out an hour-long bed with no project path, never fetched, and still carves for the voice", async () => { + stubDecode(); + vi.stubGlobal("mediaHeaderSeconds", (url: string) => (url.includes("bed") ? 3600 : 60)); + const { host, onSetAttributeQuiet } = mount( + { + "fx-chain": JSON.stringify({ version: 1, nodes: [] }), + "fx-carve": JSON.stringify({ enabled: true, sources: ["vo"], strength: 0.3 }), + start: "0", + }, + false, + ); + document.getElementById("vo")!.setAttribute("src", "voice.wav"); + document.getElementById("bed")!.setAttribute("src", "bed.m4a"); + const dial = host.querySelector(".hf-fx-carve input[type=range]")!; + await act(async () => { + Object.getOwnPropertyDescriptor(HTMLInputElement.prototype, "value")?.set?.call(dial, "0.6"); + dial.dispatchEvent(new Event("input", { bubbles: true })); + dial.dispatchEvent(new PointerEvent("pointerup", { bubbles: true })); + }); + const fetched = ( + globalThis.fetch as unknown as { mock: { calls: unknown[][] } } + ).mock.calls.map((c) => String(c[0])); + expect(fetched.some((u) => u.includes("voice.wav"))).toBe(true); + expect(fetched.some((u) => u.includes("bed.m4a"))).toBe(false); + const chainWrite = writeTo(onSetAttributeQuiet.mock.calls, "data-fx-chain"); + expect(parseWrite(chainWrite!).nodes.some((n: { fromCarve?: boolean }) => n.fromCarve)).toBe( + true, + ); + }); + it("analyses every named voice, not just the first", async () => { // The point of a list: a bed running under a narrator and an interview answer // should make room for both, so both are decoded and summed onto the bed's clock @@ -1013,7 +1184,11 @@ describe("AudioFxGroup dynamic carve", () => { function stubFiles(files: Record): void { vi.stubGlobal( "fetch", - vi.fn(async (url: string) => ({ arrayBuffer: async () => url })), + vi.fn(async (url: string) => ({ + ok: true, + headers: new Headers(), + arrayBuffer: async () => url, + })), ); vi.stubGlobal( "OfflineAudioContext", diff --git a/packages/studio/src/components/editor/useFxCarve.ts b/packages/studio/src/components/editor/useFxCarve.ts index 8f5752850c..7a8b2d1152 100644 --- a/packages/studio/src/components/editor/useFxCarve.ts +++ b/packages/studio/src/components/editor/useFxCarve.ts @@ -272,11 +272,11 @@ export function useFxCarve( const persistMeasuredCarve = async ( measured: NonNullable>>, ): Promise => { - const { bands, carved, duck, voiceMix } = measured; + const { bands, carved, duck, voiceMix, sampleRate } = measured; const { next, carvedNodes, duckNode } = mintCarveNodes(chain, carved, duck); await onSetAttributeQuiet(HF_AUDIO_FX_ATTR, serializeAudioFxChain(next)); - const lanes = carveLanes(carvedNodes, duckNode, duck, voiceMix, bands); + const lanes = carveLanes(carvedNodes, duckNode, duck, voiceMix, bands, sampleRate); const carriedOver = withoutCarveLanes(automation, chain); if (lanes.length > 0 || carriedOver.lanes.length !== automation.lanes.length) { writeAutomation({ version: 1, lanes: [...carriedOver.lanes, ...lanes] }); diff --git a/packages/studio/src/components/editor/useFxCarveNodes.ts b/packages/studio/src/components/editor/useFxCarveNodes.ts index 0f1c4321d6..959b9c55e3 100644 --- a/packages/studio/src/components/editor/useFxCarveNodes.ts +++ b/packages/studio/src/components/editor/useFxCarveNodes.ts @@ -24,10 +24,7 @@ import { import { fxAutomationTarget, type HfAutomationLane } from "@hyperframes/core/audio-automation"; import { clipStart } from "./propertyPanelAudioFxGroupUtils.js"; import { clipAudioOnItsClock, type ClipClock } from "./clipAudioClock.js"; -import { studioApiFetch } from "../../utils/studioApiFetch"; - -/** Decode rate every carve measurement shares — see `measureCarve`. */ -const DECODE_SAMPLE_RATE = 48000; +import { analysisRateOf, readPcm } from "../../utils/projectPcm"; /** * Turns the analysed bands (and, if the carve is asked to match levels, a @@ -85,6 +82,7 @@ export async function measureCarve( carved: HfAudioFxChain; duck: { t: number; v: number }[]; voiceMix: Float32Array; + sampleRate: number; } | null> { // Decoded in an OfflineAudioContext, not a live one. Opening a second output // device mid-playback makes the running track glitch while the hardware is @@ -94,13 +92,13 @@ export async function measureCarve( (window as unknown as { webkitOfflineAudioContext?: typeof OfflineAudioContext }) .webkitOfflineAudioContext; if (!Ctor) return null; + const urlOf = (relative: string) => new URL(relative, doc.baseURI).href; + const sources = [...voices.map((voice) => voice.src), ...(bed.src ? [bed.src] : [])]; + const rate = await analysisRateOf(sources.map(urlOf)); // Each clip as it plays: trimmed to its in-point and duration, and at its own speed. const decode = async (relative: string, clock: ClipClock): Promise => { - const res = await studioApiFetch(new URL(relative, doc.baseURI).href); - const buffer = await new Ctor(1, 1, DECODE_SAMPLE_RATE).decodeAudioData( - await res.arrayBuffer(), - ); - return clipAudioOnItsClock(buffer.getChannelData(0), DECODE_SAMPLE_RATE, clock); + const samples = await readPcm(urlOf(relative), rate, (r) => new Ctor(1, 1, r)); + return clipAudioOnItsClock(samples, rate, clock); }; const bedStart = clipStart(bed.start); // Every voice, summed onto the bed's own clock. One question — where and @@ -114,7 +112,7 @@ export async function measureCarve( offsetSeconds: clipStart(voice.start) - bedStart, })), ); - const mixed = mixCarveSources(decoded, DECODE_SAMPLE_RATE); + const mixed = mixCarveSources(decoded, rate); if (mixed.length === 0) return null; // Strength is what the author set; these are the numbers it means. const profile = carveProfile(strength); @@ -123,13 +121,11 @@ export async function measureCarve( const bedSamples = bed.src ? await decode(bed.src, bed.clock).catch(() => null) : null; // Speech after the bed stops has no bed to carve. const voiceMix = bedSamples ? mixed.subarray(0, bedSamples.length) : mixed; - const bands = analyseCarveBands(voiceMix, DECODE_SAMPLE_RATE, profile); + const bands = analyseCarveBands(voiceMix, rate, profile); // The level half of the carve, measured against the speech it has to sit // under. No offset to apply: the mix is already on the bed's clock. - const duck = bedSamples - ? analyseCarveDuck(voiceMix, bedSamples, DECODE_SAMPLE_RATE, profile, 0) - : []; - return { bands, carved: carveBandsToChain(bands), duck, voiceMix }; + const duck = bedSamples ? analyseCarveDuck(voiceMix, bedSamples, rate, profile, 0) : []; + return { bands, carved: carveBandsToChain(bands), duck, voiceMix, sampleRate: rate }; } /** Each filter's depth as an envelope, plus the level envelope if there is one. */ @@ -139,10 +135,11 @@ export function carveLanes( duck: { t: number; v: number }[], voiceMix: Float32Array, bands: ReturnType, + sampleRate: number, ): HfAutomationLane[] { // Each filter's depth becomes an envelope of the speech's level in that // band, so pauses leave the bed alone and whoever is talking sets the depth. - const lanes = analyseCarveDynamics(voiceMix, DECODE_SAMPLE_RATE, bands).flatMap((dyn, i) => { + const lanes = analyseCarveDynamics(voiceMix, sampleRate, bands).flatMap((dyn, i) => { const id = carvedNodes[i]?.id; return id ? carveLaneFor(id, dyn.points) : []; }); diff --git a/packages/studio/src/components/editor/useFxLevelling.ts b/packages/studio/src/components/editor/useFxLevelling.ts index 351bb4a515..51cce1b50d 100644 --- a/packages/studio/src/components/editor/useFxLevelling.ts +++ b/packages/studio/src/components/editor/useFxLevelling.ts @@ -26,13 +26,7 @@ import { trackLeveller } from "./audioFxTelemetry.js"; import type { DomEditSelection } from "./domEditingTypes"; import { clipSourceWindow, readClipClock } from "./clipAudioClock.js"; import { useAuditionTransport } from "./useAuditionTransport.js"; -import { studioApiFetch } from "../../utils/studioApiFetch"; - -/** - * Rate the track is decoded at. Analysis is self-consistent because it reads - * the decoded buffer's own rate, so this only has to be a sane audio rate. - */ -const DECODE_SAMPLE_RATE = 48000; +import { analysisRateOf, readPcm } from "../../utils/projectPcm"; export function useFxLevelling( element: DomEditSelection, @@ -64,11 +58,10 @@ export function useFxLevelling( (window as unknown as { webkitOfflineAudioContext?: typeof OfflineAudioContext }) .webkitOfflineAudioContext; if (!Ctor) return null; - const res = await studioApiFetch(new URL(src, doc.baseURI).href); - const buffer = await new Ctor(1, 1, DECODE_SAMPLE_RATE).decodeAudioData( - await res.arrayBuffer(), - ); - const next = { src, samples: buffer.getChannelData(0), sampleRate: buffer.sampleRate }; + const url = new URL(src, doc.baseURI).href; + const sampleRate = await analysisRateOf([url]); + const samples = await readPcm(url, sampleRate, (rate) => new Ctor(1, 1, rate)); + const next = { src, samples, sampleRate }; decoded.current = next; return next; }; diff --git a/packages/studio/src/hooks/useMusicBeatAnalysis.test.tsx b/packages/studio/src/hooks/useMusicBeatAnalysis.test.tsx index 296a371a21..d28816b0d9 100644 --- a/packages/studio/src/hooks/useMusicBeatAnalysis.test.tsx +++ b/packages/studio/src/hooks/useMusicBeatAnalysis.test.tsx @@ -7,9 +7,19 @@ import { FileManagerProvider } from "../contexts/FileManagerContext"; import { mountReactHarness } from "./domSelectionTestHarness"; const analyze = vi.hoisted(() => vi.fn()); +const read = vi.hoisted(() => vi.fn(async (_url: string) => [new Float32Array(1)])); vi.mock("@hyperframes/core/beats", async (actual) => ({ ...(await actual()), - analyzeMusicFromUrl: analyze, + analyzeMusicFromSignal: analyze, +})); +vi.mock("../utils/projectPcm", () => ({ + analysisRateOf: async () => 48_000, + readPcmChannels: read, +})); +// The timeline is at rest, so a read starts within the settle below and "nothing was read" means it. +vi.mock("../player/components/timelineMotion", async (actual) => ({ + ...(await actual()), + whenTimelineIdle: async () => {}, })); const { useMusicBeatAnalysis } = await import("./useMusicBeatAnalysis"); @@ -51,16 +61,17 @@ async function opened(elements: TimelineElement[]) { , ); await act(async () => { - for (let i = 0; i < 5; i += 1) await Promise.resolve(); + await new Promise((settled) => setTimeout(settled, 0)); }); const beats = usePlayerStore.getState().beatAnalysis?.beatTimes ?? null; act(() => root.unmount()); - return { decoded: analyze.mock.calls.map(([src]) => src), beats }; + return { decoded: read.mock.calls.map(([src]) => src), beats }; } beforeEach(() => { savedBeats = ""; analyze.mockReset(); + read.mockClear(); analyze.mockResolvedValue({ beatTimes: [1, 2], beatStrengths: [1, 1], bpm: 120 }); }); afterEach(() => diff --git a/packages/studio/src/hooks/useMusicBeatAnalysis.ts b/packages/studio/src/hooks/useMusicBeatAnalysis.ts index d88a3c008c..b125886191 100644 --- a/packages/studio/src/hooks/useMusicBeatAnalysis.ts +++ b/packages/studio/src/hooks/useMusicBeatAnalysis.ts @@ -1,7 +1,8 @@ import { useEffect, useMemo, useRef } from "react"; import { usePlayerStore } from "../player/store/playerStore"; import { fitsBeatAnalysis, resolveBeatSourceTrack } from "../utils/timelineInspector"; -import { analyzeMusicFromUrl } from "@hyperframes/core/beats"; +import { analyzeMusicFromSignal, type MusicBeatAnalysis } from "@hyperframes/core/beats"; +import { analysisRateOf, readPcmChannels } from "../utils/projectPcm"; import { whenTimelineIdle } from "../player/components/timelineMotion"; import { useFileManagerContextOptional } from "../contexts/FileManagerContext"; import { mergeUserBeats } from "../utils/beatEditing"; @@ -16,12 +17,12 @@ import { // Module-level cache so the same URL isn't re-decoded/analyzed on re-mount. // Capped so decoded PCM buffers don't accumulate unbounded across a session. -const analysisCache = new Map>(); +const analysisCache = new Map>(); const MAX_ANALYSIS_CACHE = 4; const PERSIST_DEBOUNCE_MS = 350; -function cacheAnalysis(url: string, promise: ReturnType): void { +function cacheAnalysis(url: string, promise: Promise): void { analysisCache.set(url, promise); while (analysisCache.size > MAX_ANALYSIS_CACHE) { const oldest = analysisCache.keys().next().value; @@ -47,15 +48,22 @@ async function readSavedBeats(io: ProjectIo, beatPath: string): Promise>; +type MusicAnalysis = MusicBeatAnalysis; type Loaded = { analysis: MusicAnalysis } & Beats; +async function analyzeTrack(url: string): Promise { + await whenTimelineIdle(); + const rate = await analysisRateOf([url]); + const channels = await readPcmChannels(url, rate, (r) => new OfflineAudioContext(1, 1, r)); + return analyzeMusicFromSignal({ sampleRate: rate, channels }, { pause: whenTimelineIdle }); +} + /** A track's analysis (memoized per URL), or null when decode or analysis fails. */ async function decodeTrack(musicSrc: string): Promise { let promise = analysisCache.get(musicSrc); if (!promise) { - promise = analyzeMusicFromUrl(musicSrc, { pause: whenTimelineIdle }); + promise = analyzeTrack(musicSrc); cacheAnalysis(musicSrc, promise); } return promise.catch(() => null); diff --git a/packages/studio/src/player/components/AudioWaveform.test.tsx b/packages/studio/src/player/components/AudioWaveform.test.tsx index 20819a8c97..bfe89115b0 100644 --- a/packages/studio/src/player/components/AudioWaveform.test.tsx +++ b/packages/studio/src/player/components/AudioWaveform.test.tsx @@ -248,6 +248,42 @@ describe("AudioWaveform", () => { act(() => root.unmount()); }); + it("draws no bars for an hour-long file with no server peaks, too long to decode in the page, and never fetches it", async () => { + vi.stubGlobal("mediaHeaderSeconds", () => 3600); + const fetch = vi.fn(); + vi.stubGlobal("fetch", fetch); + vi.stubGlobal( + "AudioContext", + class { + close = async () => {}; + }, + ); + const host = document.createElement("div"); + document.body.append(host); + const root = createRoot(host); + mounted.push(root); + act(() => { + root.render( + , + ); + }); + const request = leaseSpy.mock.calls.at(-1)?.[0] as { + load: (s: AbortSignal) => Promise; + }; + await expect(request.load(new AbortController().signal)).rejects.toMatchObject({ + name: "AudioTooLong", + }); + expect(fetch).not.toHaveBeenCalled(); + vi.unstubAllGlobals(); + }); + it("greys the clip in place when muted", () => { const host = document.createElement("div"); host.className = "timeline-clip is-audio"; diff --git a/packages/studio/src/player/components/AudioWaveform.tsx b/packages/studio/src/player/components/AudioWaveform.tsx index ef5b2f5514..88c4e842cf 100644 --- a/packages/studio/src/player/components/AudioWaveform.tsx +++ b/packages/studio/src/player/components/AudioWaveform.tsx @@ -1,5 +1,6 @@ import { memo, useCallback, useContext, useEffect, useMemo, useRef, useState } from "react"; import { fadeGain } from "@hyperframes/core/audio-fade"; +import { decodeAudioWithin } from "@hyperframes/core/audio-decode"; import { useThumbnailLease } from "../../hooks/useThumbnailLease"; import { useThumbnailStripSize } from "../../hooks/useThumbnailStripSize"; import { createThumbnailKey, type ThumbnailPriority } from "../lib/thumbnailScheduler"; @@ -143,13 +144,11 @@ async function fetchWaveformPeaks(url: string, signal: AbortSignal): Promise { - const response = await studioApiFetch(url, { signal }); - if (!response.ok) throw new Error(`Audio request failed (${response.status})`); - const buffer = await response.arrayBuffer(); - if (signal.aborted) throw new DOMException("Aborted", "AbortError"); const context = new AudioContext(); try { - const decoded = await context.decodeAudioData(buffer); + const decoded = await decodeAudioWithin(context, url, { + fetch: (asked) => studioApiFetch(asked, { signal }), + }); if (signal.aborted) throw new DOMException("Aborted", "AbortError"); return extractPeaks(decoded.getChannelData(0), 4000); } finally { diff --git a/packages/studio/src/player/components/clipMenuDuck.ts b/packages/studio/src/player/components/clipMenuDuck.ts index 4af9a1ccac..c4c96e1f02 100644 --- a/packages/studio/src/player/components/clipMenuDuck.ts +++ b/packages/studio/src/player/components/clipMenuDuck.ts @@ -107,7 +107,14 @@ async function writeMeasuredCarve( const automation = readAutomation(bed); const { next, carvedNodes, duckNode } = mintCarveNodes(chain, measured.carved, measured.duck); await write(HF_AUDIO_FX_ATTR, serializeAudioFxChain(next)); - const lanes = carveLanes(carvedNodes, duckNode, measured.duck, measured.voiceMix, measured.bands); + const lanes = carveLanes( + carvedNodes, + duckNode, + measured.duck, + measured.voiceMix, + measured.bands, + measured.sampleRate, + ); const carriedOver = withoutCarveLanes(automation, chain); const nextAutomation = { version: 1, lanes: [...carriedOver.lanes, ...lanes] }; await write(HF_AUDIO_AUTOMATION_ATTR, automationAttrValue(nextAutomation) || null); diff --git a/packages/studio/src/utils/projectPcm.test.ts b/packages/studio/src/utils/projectPcm.test.ts new file mode 100644 index 0000000000..ffd4732bb3 --- /dev/null +++ b/packages/studio/src/utils/projectPcm.test.ts @@ -0,0 +1,33 @@ +// @vitest-environment happy-dom +import { afterEach, expect, it, vi } from "vitest"; +import { readPcm, readPcmChannels } from "./projectPcm"; + +afterEach(() => vi.unstubAllGlobals()); + +const serving = (samples: number[], channels?: number) => + vi.fn( + async () => + new Response(new Float32Array(samples).buffer, { + headers: channels ? { "x-channels": String(channels) } : {}, + }), + ); +const noContext = () => ({}) as BaseAudioContext; +const file = "/api/projects/p/preview/assets/mix.wav"; + +it("hands beat detection each channel apart, from the server's interleaved frames", async () => { + const fetch = serving([1, -1, 0.5, -0.5], 2); + vi.stubGlobal("fetch", fetch); + const [left, right] = await readPcmChannels(file, 48_000, noContext); + expect([...left!]).toEqual([1, 0.5]); + expect([...right!]).toEqual([-1, -0.5]); + expect(String(fetch.mock.calls[0]![0])).toMatch( + /\/api\/projects\/p\/pcm\/assets\/mix\.wav\?rate=48000&channels=all$/, + ); +}); + +it("hands the fx the first channel, asked for alone", async () => { + const fetch = serving([0.25, 0.75]); + vi.stubGlobal("fetch", fetch); + expect([...(await readPcm(file, 24_000, noContext))]).toEqual([0.25, 0.75]); + expect(String(fetch.mock.calls[0]![0])).toMatch(/\/pcm\/assets\/mix\.wav\?rate=24000$/); +}); diff --git a/packages/studio/src/utils/projectPcm.ts b/packages/studio/src/utils/projectPcm.ts new file mode 100644 index 0000000000..7a3f0d16a0 --- /dev/null +++ b/packages/studio/src/utils/projectPcm.ts @@ -0,0 +1,60 @@ +import { decodeAudioWithin, headerSeconds, pcmRateFor } from "@hyperframes/core/audio-decode"; +import { studioApiFetch } from "./studioApiFetch"; + +/** A project file's preview URL (buildProjectApiPath(id, "/preview/")); a clip with no project path misses. */ +const PREVIEW_PATH = /^(\/api\/projects\/[^/]+)\/preview\/(.+)$/; + +/** The server's PCM URL for a project file, or null for a clip with no project path. */ +function pcmUrlOf(url: string, rate: number, all: boolean): string | null { + const parsed = new URL(url, window.location.origin); + const match = PREVIEW_PATH.exec(parsed.pathname); + const query = `?rate=${rate}${all ? "&channels=all" : ""}`; + return match ? `${parsed.origin}${match[1]}/pcm/${match[2]}${query}` : null; +} + +/** One analysis rate for files read together: pcmRateFor their longest; a length that cannot be read counts long. */ +export async function analysisRateOf(urls: string[]): Promise { + const lengths = await Promise.all(urls.map((url) => headerSeconds(url))); + return pcmRateFor( + lengths.some((s) => s === null) ? Infinity : Math.max(0, ...(lengths as number[])), + ); +} + +type OfflineContextAt = (rate: number) => BaseAudioContext; + +/** `url`'s first channel at `rate` (what the fx read): the server's for a project file, else decoded here in budget. */ +export async function readPcm( + url: string, + rate: number, + context: OfflineContextAt, +): Promise { + return (await readChannels(url, rate, context, false))[0]!; +} + +/** Every channel of `url` at `rate`, apart: beats sum each one's power, so out-of-phase stereo can't cancel. */ +export const readPcmChannels = (url: string, rate: number, context: OfflineContextAt) => + readChannels(url, rate, context, true); + +async function readChannels(url: string, rate: number, context: OfflineContextAt, all: boolean) { + const served = pcmUrlOf(url, rate, all); + if (!served) { + const decoded = await decodeAudioWithin(context(rate), url, { + fetch: (u) => studioApiFetch(u), + }); + const count = all ? decoded.numberOfChannels : 1; + return Array.from({ length: count }, (_, c) => decoded.getChannelData(c)); + } + const response = await studioApiFetch(served); + if (!response.ok) throw new Error(`Audio request failed (${response.status})`); + const count = Number(response.headers.get("x-channels")) || 1; + const bytes = await response.arrayBuffer(); + const frames = Math.floor(bytes.byteLength / 4 / count); + if (frames < 1) throw new Error("The server sent no audio samples"); + const interleaved = new Float32Array(bytes, 0, frames * count); + if (count === 1) return [interleaved]; + return Array.from({ length: count }, (_, c) => { + const channel = new Float32Array(frames); + for (let i = 0; i < frames; i++) channel[i] = interleaved[i * count + c]!; + return channel; + }); +} diff --git a/packages/studio/vite.config.ts b/packages/studio/vite.config.ts index d965dd7e29..5b616f1844 100644 --- a/packages/studio/vite.config.ts +++ b/packages/studio/vite.config.ts @@ -423,7 +423,7 @@ export default defineConfig({ }, test: { exclude: ["data/**", "node_modules/**"], - setupFiles: ["src/test-setup.ts"], + setupFiles: ["src/test-setup.ts", "../core/vitest.mediaHeader.ts"], environmentOptions: { happyDOM: { settings: { enableIframePageLoading: true } }, }, diff --git a/skills-manifest.json b/skills-manifest.json index b22c0ce0c3..7a626b7426 100644 --- a/skills-manifest.json +++ b/skills-manifest.json @@ -18,7 +18,7 @@ "files": 13 }, "media-use": { - "hash": "63feb63ed82a6e9a", + "hash": "c308eba538e05979", "files": 134 }, "remotion-to-hyperframes": { diff --git a/skills/media-use/audio/scripts/lib/audio-carve.mjs b/skills/media-use/audio/scripts/lib/audio-carve.mjs index d7447bf45d..a0054ef2f2 100644 --- a/skills/media-use/audio/scripts/lib/audio-carve.mjs +++ b/skills/media-use/audio/scripts/lib/audio-carve.mjs @@ -2,4 +2,4 @@ // packages/parsers/src/privatePath.ts, bundled by scripts/generate-media-use-audio-carve.mjs so carve.mjs // runs the same analysis and private-path rule as Studio without loading @hyperframes/core from the project. // Regenerate: node scripts/generate-media-use-audio-carve.mjs -var te="data-fx-chain",je=te.slice(5),E=1,D=(e="frequency",t="Frequency",n=1e3,r=20,a=2e4)=>({kind:"number",key:e,label:t,unit:"Hz",min:r,max:a,step:1,default:n,scale:"log",automatable:!0}),T=(e=.707,t="Bandwidth: higher is narrower.")=>({kind:"number",key:"q",label:"Q",unit:"",min:.1,max:20,step:.01,default:e,scale:"log",automatable:!0,hint:t}),_=(e=-40,t=40,n=0)=>({kind:"number",key:"gain",label:"Gain",unit:"dB",min:e,max:t,step:.1,default:n,automatable:!0}),U={kind:"enum",key:"poles",label:"Slope",options:[{value:"1",label:"6 dB/oct"},{value:"2",label:"12 dB/oct"}],default:"2",hint:"Two poles is the usual biquad; one pole is gentler."},V=[{id:"gain",label:"Gain",group:"dynamics",description:"Raise or lower the whole signal. Automate it to duck under something else.",params:[_(-60,12,0)],web:"gain-node"},{id:"peaking",label:"Peaking EQ",group:"filter",description:"Boost or cut a band, leaving everything either side alone.",params:[D("frequency","Frequency",1e3),_(-40,40,0),T(1)],web:"biquad-peaking"},{id:"lowshelf",label:"Low Shelf",group:"filter",description:"Lift or drop everything below the corner frequency.",params:[D("frequency","Frequency",200,20,2e3),_(-40,40,0)],web:"biquad-lowshelf"},{id:"highshelf",label:"High Shelf",group:"filter",description:"Lift or drop everything above the corner frequency.",params:[D("frequency","Frequency",4e3,500,2e4),_(-40,40,0)],web:"biquad-highshelf"},{id:"highpass",label:"High-pass",group:"filter",description:"Remove low frequencies: the usual fix for rumble on a voice.",params:[D("frequency","Cutoff",300,20,2e4),T(.707),U],web:"biquad-highpass"},{id:"lowpass",label:"Low-pass",group:"filter",description:"Remove high frequencies, which darkens or muffles a track.",params:[D("frequency","Cutoff",8e3,100,2e4),T(.707),U],web:"biquad-lowpass"},{id:"compressor",label:"Compressor",group:"dynamics",description:"Pull loud parts down so the quiet ones can come up.",params:[{kind:"number",key:"threshold",label:"Threshold",unit:"dB",min:-60,max:0,step:.5,default:-24,hint:"Level above which the compressor starts working."},{kind:"number",key:"ratio",label:"Ratio",unit:":1",min:1,max:20,step:.1,default:4},{kind:"number",key:"attack",label:"Attack",unit:"ms",min:.01,max:2e3,step:.1,default:20,scale:"log"},{kind:"number",key:"release",label:"Release",unit:"ms",min:.01,max:9e3,step:1,default:250,scale:"log"},{kind:"number",key:"knee",label:"Knee",unit:"",min:1,max:8,step:.01,default:2.83,hint:"1 is a hard corner; higher eases into it."},{kind:"number",key:"makeup",label:"Makeup",unit:"dB",min:0,max:36,step:.1,default:0},{kind:"number",key:"mix",label:"Mix",unit:"",min:0,max:1,step:.01,default:1,hint:"Below 1 blends the dry signal back in."}],web:"worklet-compressor"},{id:"limiter",label:"Limiter",group:"dynamics",description:"Peak limiter that follows the signal's level. It has no lookahead, so a fast peak or an inter-sample peak can pass the ceiling; use the true-peak limiter for a delivery limit.",params:[{kind:"number",key:"limit",label:"Ceiling",unit:"dB",min:-24,max:0,step:.1,default:-1},{kind:"number",key:"attack",label:"Attack",unit:"ms",min:.1,max:80,step:.1,default:5},{kind:"number",key:"release",label:"Release",unit:"ms",min:1,max:8e3,step:1,default:50,scale:"log"},{kind:"number",key:"level_out",label:"Output",unit:"dB",min:-24,max:24,step:.1,default:0}],web:"worklet-limiter"},{id:"truepeak",label:"True-peak limiter",group:"dynamics",description:"Lookahead limiter that holds a 4x estimate of the inter-sample peak at a dBTP ceiling; full-band noise can land up to about 1.7 dB above it. Adds lookahead plus about 0.3 ms of latency.",params:[{kind:"number",key:"ceiling",label:"Ceiling",unit:"dBTP",min:-24,max:0,step:.1,default:-1,hint:"Target true peak, measured on a 4x oversampled signal. Dense full-band sound can end up to about 1.7 dB above it."},{kind:"number",key:"lookahead",label:"Lookahead",unit:"ms",min:.5,max:10,step:.1,default:3,hint:"How far ahead the gain starts falling. Longer is smoother and adds the same latency."},{kind:"number",key:"release",label:"Release",unit:"ms",min:10,max:2e3,step:1,default:80,scale:"log"}],web:"worklet-truepeak"},{id:"gate",label:"Noise Gate",group:"dynamics",description:"Silence the track when it drops below the threshold.",params:[{kind:"number",key:"threshold",label:"Threshold",unit:"dB",min:-80,max:0,step:.5,default:-35},{kind:"number",key:"range",label:"Range",unit:"dB",min:-80,max:0,step:.5,default:-24,hint:"How far down the gate pulls when closed."},{kind:"number",key:"ratio",label:"Ratio",unit:":1",min:1,max:20,step:.1,default:10},{kind:"number",key:"attack",label:"Attack",unit:"ms",min:.01,max:9e3,step:.1,default:1,scale:"log"},{kind:"number",key:"release",label:"Release",unit:"ms",min:.01,max:9e3,step:1,default:100,scale:"log"},{kind:"number",key:"knee",label:"Knee",unit:"",min:1,max:8,step:.01,default:2.83}],web:"worklet-gate"},{id:"saturate",label:"Saturation",group:"nonlinear",description:"Soft-clip the waveform for warmth or outright distortion.",params:[{kind:"enum",key:"type",label:"Curve",options:[{value:"tanh",label:"Tanh"},{value:"atan",label:"Arctan"},{value:"cubic",label:"Cubic"},{value:"exp",label:"Exponential"},{value:"alg",label:"Algebraic"},{value:"quintic",label:"Quintic"},{value:"sin",label:"Sine"},{value:"erf",label:"Error function"},{value:"hard",label:"Hard clip"}],default:"tanh"},{kind:"number",key:"threshold",label:"Threshold",unit:"dB",min:-40,max:0,step:.1,default:-6},{kind:"number",key:"output",automatable:!0,label:"Output",unit:"dB",min:-24,max:24,step:.1,default:0},{kind:"number",key:"oversample",label:"Oversample",unit:"x",min:1,max:8,step:1,default:4,hint:"Higher costs more but keeps aliasing down."}],web:"waveshaper"},{id:"bitcrush",label:"Bitcrush",group:"nonlinear",description:"Drop bit depth and sample rate for a lo-fi, digital sound.",params:[{kind:"number",key:"bits",label:"Bit depth",unit:"bit",min:1,max:32,step:.1,default:8},{kind:"number",key:"samples",label:"Sample hold",unit:"x",min:1,max:250,step:1,default:1,hint:"Repeats each sample N times, a crude downsample."},{kind:"number",key:"mix",label:"Mix",unit:"",min:0,max:1,step:.01,default:1}],web:"worklet-bitcrush"},{id:"pitchshift",label:"Pitch shift",group:"time",description:"Shifts pitch up or down without changing playback speed. Adds ~50 ms of latency.",params:[{kind:"number",key:"semitones",label:"Semitones",unit:"st",min:-12,max:12,step:1,default:0},{kind:"number",key:"mix",label:"Mix",unit:"",min:0,max:1,step:.01,default:1}],web:"worklet-pitchshift"},{id:"delay",label:"Delay",group:"time",description:"Repeating echoes behind the dry signal.",params:[{kind:"number",key:"time",automatable:!0,label:"Time",unit:"ms",min:1,max:5e3,step:1,default:250,scale:"log"},{kind:"number",key:"feedback",automatable:!0,label:"Feedback",unit:"",min:.01,max:.95,step:.01,default:.35},{kind:"number",key:"mix",automatable:!0,label:"Mix",unit:"",min:0,max:1,step:.01,default:.4}],web:"delay-feedback"},{id:"chorus",label:"Chorus",group:"time",description:"Detuned copies of the signal for width and thickness.",params:[{kind:"number",key:"delay",automatable:!0,label:"Delay",unit:"ms",min:1,max:100,step:.1,default:7},{kind:"number",key:"depth",automatable:!0,label:"Depth",unit:"ms",min:0,max:10,step:.01,default:2},{kind:"number",key:"speed",automatable:!0,label:"Rate",unit:"Hz",min:.01,max:10,step:.01,default:1},{kind:"number",key:"mix",automatable:!0,label:"Mix",unit:"",min:0,max:1,step:.01,default:.5}],web:"chorus-lfo"},{id:"phaser",label:"Phaser",group:"time",description:"Sweeping notches moving through the spectrum.",params:[{kind:"number",key:"in_gain",automatable:!0,label:"Input",unit:"",min:0,max:1,step:.01,default:.4},{kind:"number",key:"out_gain",automatable:!0,label:"Output",unit:"",min:0,max:2,step:.01,default:.74},{kind:"number",key:"delay",label:"Delay",unit:"ms",min:.1,max:5,step:.1,default:3},{kind:"number",key:"decay",label:"Decay",unit:"",min:0,max:.99,step:.01,default:.4},{kind:"number",key:"speed",automatable:!0,label:"Rate",unit:"Hz",min:.1,max:2,step:.01,default:.5},{kind:"enum",key:"type",label:"Waveform",options:[{value:"0",label:"Triangular"},{value:"1",label:"Sinusoidal"}],default:"0"}],web:"allpass-phaser"},{id:"reverb",label:"Reverb",group:"time",description:"Room tail. Both ends convolve the same generated impulse, so preview matches render.",params:[{kind:"number",key:"size",label:"Room size",unit:"",min:.05,max:1,step:.01,default:.7},{kind:"number",key:"damping",label:"Damping",unit:"",min:0,max:1,step:.01,default:.5,hint:"Higher rolls the top off the tail faster."},{kind:"number",key:"wet",automatable:!0,label:"Wet",unit:"",min:0,max:1,step:.01,default:.35},{kind:"number",key:"dry",automatable:!0,label:"Dry",unit:"",min:0,max:1,step:.01,default:.7}],web:"convolver"}],q=new Map(V.map(e=>[e.id,e]));var $e=V.map(e=>e.id);function O(e){let t=q.get(e);if(!t)return{};let n={};for(let r of t.params)n[r.key]=r.default;return n}function j(e,t){let n=q.get(e);if(!n)return{};let r={};for(let a of n.params){let o=t?.[a.key];if(a.kind==="enum"){let i=a.options.some(u=>u.value===o);r[a.key]=i?o:a.default;continue}let s=typeof o=="number"?o:typeof o=="string"&&o.trim()!==""?Number(o):Number.NaN;r[a.key]=Number.isFinite(s)?Math.min(a.max,Math.max(a.min,s)):a.default}return r}var y=class extends Error{constructor(t){super(t),this.name="AudioFxChainError"}};function ne(e){let t;try{t=JSON.parse(e)}catch(a){throw new y(`Chain file is not valid JSON: ${a.message}`)}if(typeof t!="object"||t===null)throw new y("Chain file must be a JSON object.");let n=t;if(n.version!==E)throw new y(`Unsupported chain version: ${String(n.version)}`);if(!Array.isArray(n.nodes))throw new y("Chain file is missing a `nodes` array.");let r=n.nodes.map(oe);return{version:E,nodes:r}}function re(e){return JSON.stringify({version:E,nodes:e.nodes.map(ie)})}function ae(e){let t=new Set(e.nodes.map(n=>n.id).filter(Boolean));for(let n=1;;n+=1){let r=`n${n}`;if(!t.has(r))return r}}function oe(e,t){if(typeof e!="object"||e===null)throw new y(`Node ${t} is not an object.`);let n=e;if(typeof n.type!="string"||!q.has(n.type))throw new y(`Node ${t} has unknown effect type: ${String(n.type)}`);return z({type:n.type,id:w(n.id),fromCarve:M(n.fromCarve),fromPreset:w(n.fromPreset),label:w(n.label),fromEq:w(n.fromEq),fromLeveller:M(n.fromLeveller),presetAmount:$(n.presetAmount),enabled:n.enabled!==!1,params:j(n.type,n.params??void 0)})}function ie(e){return z({type:e.type,id:w(e.id),fromCarve:M(e.fromCarve),fromPreset:w(e.fromPreset),label:w(e.label),fromEq:w(e.fromEq),fromLeveller:M(e.fromLeveller),presetAmount:e.presetAmount===1?void 0:$(e.presetAmount),enabled:e.enabled===!1?!1:void 0,params:j(e.type,e.params)})}function w(e){return typeof e=="string"&&e?e:void 0}function M(e){return e===!0?!0:void 0}function $(e){if(!(typeof e!="number"||!Number.isFinite(e)))return Math.min(1,Math.max(0,e))}function z(e){for(let t of Object.keys(e))e[t]===void 0&&delete e[t];return e}function B(e,t){let n=e.length;for(let r=1,a=0;r>1;for(;a&o;o>>=1)a^=o;a^=o,r`${me}${e}${de}`,ce=new RegExp(`music|bgm|${H("bed")}|soundtrack|score|${H("song")}|theme|instrumental|track\\d`,"i"),fe=new RegExp(`voice|${H("vo")}|${H("vox")}|narrat|speech|dialog|monolog|announce|${H("tts")}|talk|interview|podcast|recap|script`,"i");function pe(...e){let t=e.filter(Boolean).join(" ");return fe.test(t)?"voice":le.test(t)?"sfx":ce.test(t)?"music":"unknown"}function be(e,t){let n=r=>typeof r.duration=="number"&&Number.isFinite(r.duration)?r.start+Math.max(0,r.duration):Number.POSITIVE_INFINITY;return e.start({samples:o.samples,at:Math.round(o.offsetSeconds*t)})),r=n.reduce((o,s)=>Math.max(o,s.at+s.samples.length),0);if(r<=0)return new Float32Array(0);let a=new Float32Array(r);for(let{samples:o,at:s}of n){let i=s<0?-s:0;for(let u=i;u=r||(a[l]=(a[l]??0)+(o[u]??0))}}return a}function xe(e,t){let n=Math.max(e.length,d),r=e.length>=d?e:(()=>{let f=new Float32Array(d);return f.set(e),f})(),a=new Float32Array(d);for(let f=0;f=r&&e[i]0?o/s:0}var ke=30;function ye(e,t){let n=Math.log2(e/2e3),r=Math.exp(-(n*n)/2);return t*ke*(1-r)}function we(e,t,n){if(e.length===0)return[];let{freqs:r,power:a}=xe(e,t),s=se.map(u=>{let l=W(r,a,u);return{center:u,hasEnergy:l>0,scoreDb:l>0?10*Math.log10(l)-ye(u,n.intelligibilityBias):Number.NEGATIVE_INFINITY}}).sort((u,l)=>l.scoreDb-u.scoreDb).slice(0,Math.max(1,n.bands)).filter(u=>u.hasEnergy);if(s.length===0)return[];let i=s[0].scoreDb;return s.map(({center:u,scoreDb:l})=>{let c=Math.pow(10,(l-i)/10),h=Math.min(n.maxCutDb,Math.max(n.maxCutDb/2,n.maxCutDb*c));return{freq:u,gainDb:-Number(h.toFixed(2)),q:n.q}}).sort((u,l)=>u.freq-l.freq)}var Y=30,K=.05,ve=.25,Ae=2.4,X=400,P=.2,J=.5;function Q(e,t){let n=[{t:0,v:0}],r=0,a=-1;return e.forEach((o,s)=>{s!==e.length-1&&Math.abs(o.v-r)0&&a!==s-1&&n.push(e[s-1]),n.push(o),r=o.v,a=s)}),n}function Fe(e,t,n){if(e.length===0||n.length===0)return[];let r=new Float32Array(d);for(let m=0;m[]),l=new Float64Array(d),c=new Float64Array(d);for(let m=0;mu[v].push(W(s,g,b.freq)))}let h=e.length/t,f=1-Math.exp(-(a/t)/K),p=1-Math.exp(-(a/t)/ve);return n.map((m,g)=>{let b=u[g],v=Math.max(...b),k=0,S=[];b.forEach((F,x)=>{let N=F>0&&v>0?Math.max(0,1+10*Math.log10(F/v)/Y):0;k+=(N>k?f:p)*(N-k);let C=m.gainDb*k,I=Math.abs(C)0?20*Math.log10(o):Number.NEGATIVE_INFINITY}function Ne(e,t,n,r,a){if(e.length===0||r.duckDb<=0)return[];let o=Math.max(d,Math.ceil(e.length/X)),s=Math.round(a*n),i=[],u=[],l=[];for(let x=0;x{let C=u[N]??Number.NEGATIVE_INFINITY,I=x>h&&Number.isFinite(C)?C-(x-r.headroomDb):0,L=Math.min(r.duckDb,Math.max(0,I));m+=(L>m?f:p)*(L-m);let ee=m=P;)m+=p*-m,v+=b,g.push({t:Number(v.toFixed(3)),v:m=F||k.push({t:F,v:0}),k}function Ce(e){let t=e.map(n=>({type:"peaking",enabled:!0,params:{...O("peaking"),frequency:n.freq,gain:n.gainDb,q:n.q}}));return{version:E,nodes:t}}import{isAbsolute as De,relative as Je,resolve as Qe,sep as Ze}from"node:path";function R(e){return e.normalize("NFKC").toUpperCase().toLowerCase().replace(/\p{Default_Ignorable_Code_Point}/gu,"").split(/[\\/]/).map(t=>Ee(t.split(":",1)[0]??""))}function Ee(e){let t=e.length;for(;t>0&&(e[t-1]==="."||e[t-1]===" ");)t--;return e.slice(0,t)}function He(e){return R(e).some(t=>t===".git"||t.startsWith(".env"))}var Se=new Set([".hyperframes/studio-motion.json",".hyperframes/studio-manual-edits.json"]),_e=[".hyperframes/prepared-assets",".hyperframes/requests"],Z=".hyperframes/prepared-assets/downloads",Me=new Set([".npmrc",".yarnrc",".yarnrc.yml",".pypirc","pip.conf","pip.ini",".netrc","_netrc",".git-credentials",".gitconfig",".mcp.json","credentials.json","serviceaccountkey.json","service-account.json","service_account.json"]),Pe=new Set([".ssh",".aws",".gnupg",".docker",".kube",".azure",".claude",".codex",".cursor",".agents",".gemini",".vscode",".idea"]),Ie=new Set(["gcloud","gh"]),Te=/^(?:id_(?:rsa|dsa|ecdsa|ed25519).*|.*\.(?:pem|key|p12|pfx|p8|ppk|jks|keystore|kdbx))$/,qe=/\.(?:tfstate(?:\.backup)?|tfvars(?:\.json)?)$/;function Oe(e){let t=R(e),n=t.at(-1)??"";return Me.has(n)||Te.test(n)||qe.test(n)||t.some((r,a)=>Pe.has(r)||r===".config"&&Ie.has(t[a+1]??""))}function Be(e){if(He(e)||Oe(e))return!0;let t=R(e),n=!De(e)&&!/^\.\.[. ]*$/.test(e.split(/[\\/]/,1)[0]??""),r=t.at(-1)??"",a=!r.startsWith(".")&&Ue.test(r);return t.some((o,s)=>{let i=t.slice(0,s).every(l=>l==="");if(o===".hyperframes")return!i||!Ve(t.slice(s).join("/"));if(Le.has(o))return n;let u=i&&o===Re;return n&&o.startsWith(".")&&!u&&!a})}var Re=".media",Le=new Set([".next",".nuxt",".output",".svelte-kit",".vercel",".netlify",".wrangler",".astro",".turbo"]),Ue=/.\.(?:png|jpe?g|gif|webp|avif|svg|ico|bmp|tiff?|heic|heif|mp4|m4v|mov|webm|mkv|mxf|avi|mp3|wav|m4a|aac|ogg|oga|opus|flac|woff2?|ttf|otf|css|m?js|cjs)$/;function Ve(e){return e===Z||e.startsWith(`${Z}/`)?!1:Se.has(e)||_e.some(t=>e===t||e.startsWith(`${t}/`))}export{we as analyseCarveBands,Ne as analyseCarveDuck,Fe as analyseCarveDynamics,Ce as carveBandsToChain,he as carveProfile,pe as classifyAudioName,be as clipsOverlap,O as defaultAudioFxParams,Be as isStudioPrivatePath,ae as mintAudioFxNodeId,ge as mixCarveSources,ne as parseAudioFxChain,re as serializeAudioFxChain}; +var de="data-fx-chain",et=de.slice(5),P=1,E=(e="frequency",n="Frequency",t=1e3,r=20,a=2e4)=>({kind:"number",key:e,label:n,unit:"Hz",min:r,max:a,step:1,default:t,scale:"log",automatable:!0}),H=(e=.707,n="Bandwidth: higher is narrower.")=>({kind:"number",key:"q",label:"Q",unit:"",min:.1,max:20,step:.01,default:e,scale:"log",automatable:!0,hint:n}),I=(e=-40,n=40,t=0)=>({kind:"number",key:"gain",label:"Gain",unit:"dB",min:e,max:n,step:.1,default:t,automatable:!0}),W={kind:"enum",key:"poles",label:"Slope",options:[{value:"1",label:"6 dB/oct"},{value:"2",label:"12 dB/oct"}],default:"2",hint:"Two poles is the usual biquad; one pole is gentler."},Y=[{id:"gain",label:"Gain",group:"dynamics",description:"Raise or lower the whole signal. Automate it to duck under something else.",params:[I(-60,12,0)],web:"gain-node"},{id:"peaking",label:"Peaking EQ",group:"filter",description:"Boost or cut a band, leaving everything either side alone.",params:[E("frequency","Frequency",1e3),I(-40,40,0),H(1)],web:"biquad-peaking"},{id:"lowshelf",label:"Low Shelf",group:"filter",description:"Lift or drop everything below the corner frequency.",params:[E("frequency","Frequency",200,20,2e3),I(-40,40,0)],web:"biquad-lowshelf"},{id:"highshelf",label:"High Shelf",group:"filter",description:"Lift or drop everything above the corner frequency.",params:[E("frequency","Frequency",4e3,500,2e4),I(-40,40,0)],web:"biquad-highshelf"},{id:"highpass",label:"High-pass",group:"filter",description:"Remove low frequencies: the usual fix for rumble on a voice.",params:[E("frequency","Cutoff",300,20,2e4),H(.707),W],web:"biquad-highpass"},{id:"lowpass",label:"Low-pass",group:"filter",description:"Remove high frequencies, which darkens or muffles a track.",params:[E("frequency","Cutoff",8e3,100,2e4),H(.707),W],web:"biquad-lowpass"},{id:"compressor",label:"Compressor",group:"dynamics",description:"Pull loud parts down so the quiet ones can come up.",params:[{kind:"number",key:"threshold",label:"Threshold",unit:"dB",min:-60,max:0,step:.5,default:-24,hint:"Level above which the compressor starts working."},{kind:"number",key:"ratio",label:"Ratio",unit:":1",min:1,max:20,step:.1,default:4},{kind:"number",key:"attack",label:"Attack",unit:"ms",min:.01,max:2e3,step:.1,default:20,scale:"log"},{kind:"number",key:"release",label:"Release",unit:"ms",min:.01,max:9e3,step:1,default:250,scale:"log"},{kind:"number",key:"knee",label:"Knee",unit:"",min:1,max:8,step:.01,default:2.83,hint:"1 is a hard corner; higher eases into it."},{kind:"number",key:"makeup",label:"Makeup",unit:"dB",min:0,max:36,step:.1,default:0},{kind:"number",key:"mix",label:"Mix",unit:"",min:0,max:1,step:.01,default:1,hint:"Below 1 blends the dry signal back in."}],web:"worklet-compressor"},{id:"limiter",label:"Limiter",group:"dynamics",description:"Peak limiter that follows the signal's level. It has no lookahead, so a fast peak or an inter-sample peak can pass the ceiling; use the true-peak limiter for a delivery limit.",params:[{kind:"number",key:"limit",label:"Ceiling",unit:"dB",min:-24,max:0,step:.1,default:-1},{kind:"number",key:"attack",label:"Attack",unit:"ms",min:.1,max:80,step:.1,default:5},{kind:"number",key:"release",label:"Release",unit:"ms",min:1,max:8e3,step:1,default:50,scale:"log"},{kind:"number",key:"level_out",label:"Output",unit:"dB",min:-24,max:24,step:.1,default:0}],web:"worklet-limiter"},{id:"truepeak",label:"True-peak limiter",group:"dynamics",description:"Lookahead limiter that holds a 4x estimate of the inter-sample peak at a dBTP ceiling; full-band noise can land up to about 1.7 dB above it. Adds lookahead plus about 0.3 ms of latency.",params:[{kind:"number",key:"ceiling",label:"Ceiling",unit:"dBTP",min:-24,max:0,step:.1,default:-1,hint:"Target true peak, measured on a 4x oversampled signal. Dense full-band sound can end up to about 1.7 dB above it."},{kind:"number",key:"lookahead",label:"Lookahead",unit:"ms",min:.5,max:10,step:.1,default:3,hint:"How far ahead the gain starts falling. Longer is smoother and adds the same latency."},{kind:"number",key:"release",label:"Release",unit:"ms",min:10,max:2e3,step:1,default:80,scale:"log"}],web:"worklet-truepeak"},{id:"gate",label:"Noise Gate",group:"dynamics",description:"Silence the track when it drops below the threshold.",params:[{kind:"number",key:"threshold",label:"Threshold",unit:"dB",min:-80,max:0,step:.5,default:-35},{kind:"number",key:"range",label:"Range",unit:"dB",min:-80,max:0,step:.5,default:-24,hint:"How far down the gate pulls when closed."},{kind:"number",key:"ratio",label:"Ratio",unit:":1",min:1,max:20,step:.1,default:10},{kind:"number",key:"attack",label:"Attack",unit:"ms",min:.01,max:9e3,step:.1,default:1,scale:"log"},{kind:"number",key:"release",label:"Release",unit:"ms",min:.01,max:9e3,step:1,default:100,scale:"log"},{kind:"number",key:"knee",label:"Knee",unit:"",min:1,max:8,step:.01,default:2.83}],web:"worklet-gate"},{id:"saturate",label:"Saturation",group:"nonlinear",description:"Soft-clip the waveform for warmth or outright distortion.",params:[{kind:"enum",key:"type",label:"Curve",options:[{value:"tanh",label:"Tanh"},{value:"atan",label:"Arctan"},{value:"cubic",label:"Cubic"},{value:"exp",label:"Exponential"},{value:"alg",label:"Algebraic"},{value:"quintic",label:"Quintic"},{value:"sin",label:"Sine"},{value:"erf",label:"Error function"},{value:"hard",label:"Hard clip"}],default:"tanh"},{kind:"number",key:"threshold",label:"Threshold",unit:"dB",min:-40,max:0,step:.1,default:-6},{kind:"number",key:"output",automatable:!0,label:"Output",unit:"dB",min:-24,max:24,step:.1,default:0},{kind:"number",key:"oversample",label:"Oversample",unit:"x",min:1,max:8,step:1,default:4,hint:"Higher costs more but keeps aliasing down."}],web:"waveshaper"},{id:"bitcrush",label:"Bitcrush",group:"nonlinear",description:"Drop bit depth and sample rate for a lo-fi, digital sound.",params:[{kind:"number",key:"bits",label:"Bit depth",unit:"bit",min:1,max:32,step:.1,default:8},{kind:"number",key:"samples",label:"Sample hold",unit:"x",min:1,max:250,step:1,default:1,hint:"Repeats each sample N times, a crude downsample."},{kind:"number",key:"mix",label:"Mix",unit:"",min:0,max:1,step:.01,default:1}],web:"worklet-bitcrush"},{id:"pitchshift",label:"Pitch shift",group:"time",description:"Shifts pitch up or down without changing playback speed. Adds ~50 ms of latency.",params:[{kind:"number",key:"semitones",label:"Semitones",unit:"st",min:-12,max:12,step:1,default:0},{kind:"number",key:"mix",label:"Mix",unit:"",min:0,max:1,step:.01,default:1}],web:"worklet-pitchshift"},{id:"delay",label:"Delay",group:"time",description:"Repeating echoes behind the dry signal.",params:[{kind:"number",key:"time",automatable:!0,label:"Time",unit:"ms",min:1,max:5e3,step:1,default:250,scale:"log"},{kind:"number",key:"feedback",automatable:!0,label:"Feedback",unit:"",min:.01,max:.95,step:.01,default:.35},{kind:"number",key:"mix",automatable:!0,label:"Mix",unit:"",min:0,max:1,step:.01,default:.4}],web:"delay-feedback"},{id:"chorus",label:"Chorus",group:"time",description:"Detuned copies of the signal for width and thickness.",params:[{kind:"number",key:"delay",automatable:!0,label:"Delay",unit:"ms",min:1,max:100,step:.1,default:7},{kind:"number",key:"depth",automatable:!0,label:"Depth",unit:"ms",min:0,max:10,step:.01,default:2},{kind:"number",key:"speed",automatable:!0,label:"Rate",unit:"Hz",min:.01,max:10,step:.01,default:1},{kind:"number",key:"mix",automatable:!0,label:"Mix",unit:"",min:0,max:1,step:.01,default:.5}],web:"chorus-lfo"},{id:"phaser",label:"Phaser",group:"time",description:"Sweeping notches moving through the spectrum.",params:[{kind:"number",key:"in_gain",automatable:!0,label:"Input",unit:"",min:0,max:1,step:.01,default:.4},{kind:"number",key:"out_gain",automatable:!0,label:"Output",unit:"",min:0,max:2,step:.01,default:.74},{kind:"number",key:"delay",label:"Delay",unit:"ms",min:.1,max:5,step:.1,default:3},{kind:"number",key:"decay",label:"Decay",unit:"",min:0,max:.99,step:.01,default:.4},{kind:"number",key:"speed",automatable:!0,label:"Rate",unit:"Hz",min:.1,max:2,step:.01,default:.5},{kind:"enum",key:"type",label:"Waveform",options:[{value:"0",label:"Triangular"},{value:"1",label:"Sinusoidal"}],default:"0"}],web:"allpass-phaser"},{id:"reverb",label:"Reverb",group:"time",description:"Room tail. Both ends convolve the same generated impulse, so preview matches render.",params:[{kind:"number",key:"size",label:"Room size",unit:"",min:.05,max:1,step:.01,default:.7},{kind:"number",key:"damping",label:"Damping",unit:"",min:0,max:1,step:.01,default:.5,hint:"Higher rolls the top off the tail faster."},{kind:"number",key:"wet",automatable:!0,label:"Wet",unit:"",min:0,max:1,step:.01,default:.35},{kind:"number",key:"dry",automatable:!0,label:"Dry",unit:"",min:0,max:1,step:.01,default:.7}],web:"convolver"}],B=new Map(Y.map(e=>[e.id,e]));var tt=Y.map(e=>e.id);function L(e){let n=B.get(e);if(!n)return{};let t={};for(let r of n.params)t[r.key]=r.default;return t}function X(e,n){let t=B.get(e);if(!t)return{};let r={};for(let a of t.params){let o=n?.[a.key];if(a.kind==="enum"){let i=a.options.some(l=>l.value===o);r[a.key]=i?o:a.default;continue}let s=typeof o=="number"?o:typeof o=="string"&&o.trim()!==""?Number(o):Number.NaN;r[a.key]=Number.isFinite(s)?Math.min(a.max,Math.max(a.min,s)):a.default}return r}var A=class extends Error{constructor(n){super(n),this.name="AudioFxChainError"}};function fe(e){let n;try{n=JSON.parse(e)}catch(a){throw new A(`Chain file is not valid JSON: ${a.message}`)}if(typeof n!="object"||n===null)throw new A("Chain file must be a JSON object.");let t=n;if(t.version!==P)throw new A(`Unsupported chain version: ${String(t.version)}`);if(!Array.isArray(t.nodes))throw new A("Chain file is missing a `nodes` array.");let r=t.nodes.map(be);return{version:P,nodes:r}}function pe(e){return JSON.stringify({version:P,nodes:e.nodes.map(ge)})}function he(e){let n=new Set(e.nodes.map(t=>t.id).filter(Boolean));for(let t=1;;t+=1){let r=`n${t}`;if(!n.has(r))return r}}function be(e,n){if(typeof e!="object"||e===null)throw new A(`Node ${n} is not an object.`);let t=e;if(typeof t.type!="string"||!B.has(t.type))throw new A(`Node ${n} has unknown effect type: ${String(t.type)}`);return Q({type:t.type,id:M(t.id),fromCarve:D(t.fromCarve),fromPreset:M(t.fromPreset),label:M(t.label),fromEq:M(t.fromEq),fromLeveller:D(t.fromLeveller),presetAmount:Z(t.presetAmount),enabled:t.enabled!==!1,params:X(t.type,t.params??void 0)})}function ge(e){return Q({type:e.type,id:M(e.id),fromCarve:D(e.fromCarve),fromPreset:M(e.fromPreset),label:M(e.label),fromEq:M(e.fromEq),fromLeveller:D(e.fromLeveller),presetAmount:e.presetAmount===1?void 0:Z(e.presetAmount),enabled:e.enabled===!1?!1:void 0,params:X(e.type,e.params)})}function M(e){return typeof e=="string"&&e?e:void 0}function D(e){return e===!0?!0:void 0}function Z(e){if(!(typeof e!="number"||!Number.isFinite(e)))return Math.min(1,Math.max(0,e))}function Q(e){for(let n of Object.keys(e))e[n]===void 0&&delete e[n];return e}function _(e,n){let t=e.length;for(let r=1,a=0;r>1;for(;a&o;o>>=1)a^=o;a^=o,r{let t=n/J;return t>=q?0:(t===0?1:Math.sin(Math.PI*t)/(Math.PI*t))*(.5+.5*Math.cos(Math.PI*t/q))});var te=22050;var $=4096;var ht=Array.from({length:$/2},(e,n)=>{let t=n*te/$;return t<55||t>2e3?-1:((Math.round(12*Math.log2(t/440))+9)%12+12)%12});var bt=$/2/te;var z=16;var wt=(()=>{let e=Array.from({length:2*z},(t,r)=>r-z),n=t=>Math.exp(-.5*(((t<0?-t-1:t)+.5)/(z/2))**2);return e.map(t=>e.map(r=>(t<0==r<0?1:-1)*n(t)*n(r)))})();var R=(e,n)=>2**Math.round(Math.log2(e*n));function U(e,n,t){let r=0,a=0;for(let s=n;s0?20*Math.log10(o):Number.NEGATIVE_INFINITY}var ne=4,V=12,Rt=Array.from({length:ne-1},(e,n)=>{let t=(n+1)/ne;return Float64Array.from({length:2*V},(r,a)=>{let o=a-V+1-t;return(o===0?1:Math.sin(Math.PI*o)/(Math.PI*o))*(.5+.5*Math.cos(Math.PI*o/V))})});function re(e){let n=new Float32Array(e);for(let t=0;t`${Me}${e}${Fe}`,ke=new RegExp(`music|bgm|${C("bed")}|soundtrack|score|${C("song")}|theme|instrumental|track\\d`,"i"),we=new RegExp(`voice|${C("vo")}|${C("vox")}|narrat|speech|dialog|monolog|announce|${C("tts")}|talk|interview|podcast|recap|script`,"i");function Se(...e){let n=e.filter(Boolean).join(" ");return we.test(n)?"voice":Ae.test(n)?"sfx":ke.test(n)?"music":"unknown"}function ve(e,n){let t=r=>typeof r.duration=="number"&&Number.isFinite(r.duration)?r.start+Math.max(0,r.duration):Number.POSITIVE_INFINITY;return e.start({samples:o.samples,at:Math.round(o.offsetSeconds*n)})),r=t.reduce((o,s)=>Math.max(o,s.at+s.samples.length),0);if(r<=0)return new Float32Array(0);let a=new Float32Array(r);for(let{samples:o,at:s}of t){let i=s<0?-s:0;for(let l=i;l=r||(a[c]=(a[c]??0)+(o[l]??0))}}return a}function _e(e,n){let t=R(n,G),r=t/2,a=Math.max(e.length,t),o=e.length>=t?e:(()=>{let d=new Float32Array(t);return d.set(e),d})(),s=re(t),i=t/2+1,l=new Float64Array(i),c=new Float64Array(t),m=new Float64Array(t),p=0;for(let d=0;d+t<=a;d+=r){m.fill(0);for(let u=0;u=r&&e[i]0?o/s:0}var Ce=30;function Oe(e,n){let t=Math.log2(e/2e3),r=Math.exp(-(t*t)/2);return n*Ce*(1-r)}function Ie(e,n,t){if(e.length===0)return[];let{freqs:r,power:a}=_e(e,n),s=xe.map(l=>{let c=oe(r,a,l);return{center:l,hasEnergy:c>0,scoreDb:c>0?10*Math.log10(c)-Oe(l,t.intelligibilityBias):Number.NEGATIVE_INFINITY}}).sort((l,c)=>c.scoreDb-l.scoreDb).slice(0,Math.max(1,t.bands)).filter(l=>l.hasEnergy);if(s.length===0)return[];let i=s[0].scoreDb;return s.map(({center:l,scoreDb:c})=>{let m=Math.pow(10,(c-i)/10),p=Math.min(t.maxCutDb,Math.max(t.maxCutDb/2,t.maxCutDb*m));return{freq:l,gainDb:-Number(p.toFixed(2)),q:t.q}}).sort((l,c)=>l.freq-c.freq)}var ae=30,se=.05,De=.25,Re=2.4,ie=400,N=.2,ue=.5;function le(e,n){let t=[{t:0,v:0}],r=0,a=-1;return e.forEach((o,s)=>{s!==e.length-1&&Math.abs(o.v-r)0&&a!==s-1&&t.push(e[s-1]),t.push(o),r=o.v,a=s)}),t}function Ne(e,n,t){if(e.length===0||t.length===0)return[];let r=R(n,G),a=re(r),o=Math.max(r,Math.ceil(e.length/ie)),s=r/2+1,i=[];for(let u=0;u[]),m=new Float64Array(r),p=new Float64Array(r);for(let u=0;uc[F].push(oe(i,y,f.freq)))}let b=e.length/n,g=1-Math.exp(-(o/n)/se),d=1-Math.exp(-(o/n)/De);return t.map((u,y)=>{let f=c[y],F=Math.max(...f),x=0,O=[];f.forEach((w,h)=>{let S=w>0&&F>0?Math.max(0,1+10*Math.log10(w/F)/ae):0;x+=(S>x?g:d)*(S-x);let v=u.gainDb*x,T=Math.abs(v){let v=c[S]??Number.NEGATIVE_INFINITY,T=h>b&&Number.isFinite(v)?v-(h-r.headroomDb):0,j=Math.min(r.duckDb,Math.max(0,T));u+=(j>u?g:d)*(j-u);let me=u=N;)u+=d*-u,F+=f,y.push({t:Number(F.toFixed(3)),v:u=w||x.push({t:w,v:0}),x}function He(e){let n=e.map(t=>({type:"peaking",enabled:!0,params:{...L("peaking"),frequency:t.freq,gain:t.gainDb,q:t.q}}));return{version:P,nodes:n}}import{isAbsolute as Be,relative as Kt,resolve as jt,sep as Wt}from"node:path";function K(e){return e.normalize("NFKC").toUpperCase().toLowerCase().replace(/\p{Default_Ignorable_Code_Point}/gu,"").split(/[\\/]/).map(n=>Le(n.split(":",1)[0]??""))}function Le(e){let n=e.length;for(;n>0&&(e[n-1]==="."||e[n-1]===" ");)n--;return e.slice(0,n)}function qe(e){return K(e).some(n=>n===".git"||n.startsWith(".env"))}var $e=new Set([".hyperframes/studio-motion.json",".hyperframes/studio-manual-edits.json"]),ze=[".hyperframes/prepared-assets",".hyperframes/requests"],ce=".hyperframes/prepared-assets/downloads",Ve=new Set([".npmrc",".yarnrc",".yarnrc.yml",".pypirc","pip.conf","pip.ini",".netrc","_netrc",".git-credentials",".gitconfig",".mcp.json","credentials.json","serviceaccountkey.json","service-account.json","service_account.json"]),Ue=new Set([".ssh",".aws",".gnupg",".docker",".kube",".azure",".claude",".codex",".cursor",".agents",".gemini",".vscode",".idea"]),Ge=new Set(["gcloud","gh"]),Ke=/^(?:id_(?:rsa|dsa|ecdsa|ed25519).*|.*\.(?:pem|key|p12|pfx|p8|ppk|jks|keystore|kdbx))$/,je=/\.(?:tfstate(?:\.backup)?|tfvars(?:\.json)?)$/;function We(e){let n=K(e),t=n.at(-1)??"";return Ve.has(t)||Ke.test(t)||je.test(t)||n.some((r,a)=>Ue.has(r)||r===".config"&&Ge.has(n[a+1]??""))}function Ye(e){if(qe(e)||We(e))return!0;let n=K(e),t=!Be(e)&&!/^\.\.[. ]*$/.test(e.split(/[\\/]/,1)[0]??""),r=n.at(-1)??"",a=!r.startsWith(".")&&Qe.test(r);return n.some((o,s)=>{let i=n.slice(0,s).every(c=>c==="");if(o===".hyperframes")return!i||!Je(n.slice(s).join("/"));if(Ze.has(o))return t;let l=i&&o===Xe;return t&&o.startsWith(".")&&!l&&!a})}var Xe=".media",Ze=new Set([".next",".nuxt",".output",".svelte-kit",".vercel",".netlify",".wrangler",".astro",".turbo"]),Qe=/.\.(?:png|jpe?g|gif|webp|avif|svg|ico|bmp|tiff?|heic|heif|mp4|m4v|mov|webm|mkv|mxf|avi|mp3|wav|m4a|aac|ogg|oga|opus|flac|woff2?|ttf|otf|css|m?js|cjs)$/;function Je(e){return e===ce||e.startsWith(`${ce}/`)?!1:$e.has(e)||ze.some(n=>e===n||e.startsWith(`${n}/`))}export{Ie as analyseCarveBands,Te as analyseCarveDuck,Ne as analyseCarveDynamics,He as carveBandsToChain,Ee as carveProfile,Se as classifyAudioName,ve as clipsOverlap,L as defaultAudioFxParams,Ye as isStudioPrivatePath,he as mintAudioFxNodeId,Pe as mixCarveSources,fe as parseAudioFxChain,pe as serializeAudioFxChain};