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
This commit is contained in:
Miguel Ángel
2026-11-24 19:30:50 +00:00
committed by GitHub
parent 5db64b4adf
commit 630409ca19
34 changed files with 900 additions and 107 deletions
+6
View File
@@ -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",
+10
View File
@@ -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"
+19 -1
View File
@@ -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). */
+28
View File
@@ -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);
});
});
+15 -21
View File
@@ -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);
+85
View File
@@ -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<typeof context>, ...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);
});
});
+76
View File
@@ -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<number | null> {
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<Response>; knownSeconds?: number } = {},
): Promise<AudioBuffer> {
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);
}
+3 -16
View File
@@ -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[] = [];
+25 -1
View File
@@ -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();
});
});
+2 -3
View File
@@ -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();
@@ -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)", () => {
+44 -13
View File
@@ -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<AudioBuffer | null> {
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<ArrayBuffer | null> {
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<AudioBuffer | null> {
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<AudioBuffer | null> {
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.
+1 -1
View File
@@ -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"],
+17
View File
@@ -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<string, unknown>).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")),
);
};
}
@@ -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`, {
@@ -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"));
@@ -14,6 +14,9 @@ export class AudioDecodeTimeoutError extends Error {
const runDecode = createJobSlots(AUDIO_DECODE_LIMIT);
export const inAudioDecodeSlot = (run: () => Promise<unknown>, signal: AbortSignal) =>
runDecode(run, signal);
interface SharedDecode {
result: Promise<number[]>;
waiting: number;
@@ -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,
);
});
});
+73
View File
@@ -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<string | null> {
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<ChildProcess>((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),
},
},
);
});
}
@@ -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);
@@ -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<string, string>) {
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<typeof vi.fn> {
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<void> {
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<HTMLInputElement>(".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<HTMLInputElement>(".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<string, Float32Array>): 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",
@@ -272,11 +272,11 @@ export function useFxCarve(
const persistMeasuredCarve = async (
measured: NonNullable<Awaited<ReturnType<typeof measureCarve>>>,
): Promise<void> => {
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] });
@@ -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<Float32Array> => {
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<typeof analyseCarveBands>,
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) : [];
});
@@ -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;
};
@@ -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<typeof import("@hyperframes/core/beats")>()),
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<typeof import("../player/components/timelineMotion")>()),
whenTimelineIdle: async () => {},
}));
const { useMusicBeatAnalysis } = await import("./useMusicBeatAnalysis");
@@ -51,16 +61,17 @@ async function opened(elements: TimelineElement[]) {
</FileManagerProvider>,
);
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(() =>
@@ -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<string, ReturnType<typeof analyzeMusicFromUrl>>();
const analysisCache = new Map<string, Promise<MusicBeatAnalysis>>();
const MAX_ANALYSIS_CACHE = 4;
const PERSIST_DEBOUNCE_MS = 350;
function cacheAnalysis(url: string, promise: ReturnType<typeof analyzeMusicFromUrl>): void {
function cacheAnalysis(url: string, promise: Promise<MusicBeatAnalysis>): 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<Beats |
}
}
type MusicAnalysis = Awaited<ReturnType<typeof analyzeMusicFromUrl>>;
type MusicAnalysis = MusicBeatAnalysis;
type Loaded = { analysis: MusicAnalysis } & Beats;
async function analyzeTrack(url: string): Promise<MusicBeatAnalysis> {
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<MusicAnalysis | null> {
let promise = analysisCache.get(musicSrc);
if (!promise) {
promise = analyzeMusicFromUrl(musicSrc, { pause: whenTimelineIdle });
promise = analyzeTrack(musicSrc);
cacheAnalysis(musicSrc, promise);
}
return promise.catch(() => null);
@@ -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(
<AudioWaveform
audioUrl="/media/hour.mp3"
label=""
labelColor="#fff"
projectId="project-a"
sessionEpoch={1}
priority="visible"
/>,
);
});
const request = leaseSpy.mock.calls.at(-1)?.[0] as {
load: (s: AbortSignal) => Promise<unknown>;
};
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";
@@ -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<num
}
async function decodeWaveformPeaks(url: string, signal: AbortSignal): Promise<number[]> {
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 {
@@ -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);
@@ -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$/);
});
+60
View File
@@ -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/<path>")); 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<number> {
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<Float32Array> {
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;
});
}
+1 -1
View File
@@ -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 } },
},
+1 -1
View File
@@ -18,7 +18,7 @@
"files": 13
},
"media-use": {
"hash": "63feb63ed82a6e9a",
"hash": "c308eba538e05979",
"files": 134
},
"remotion-to-hyperframes": {
File diff suppressed because one or more lines are too long