mirror of
https://github.com/heygen-com/hyperframes.git
synced 2026-08-31 02:41:44 +00:00
fix(core): retire worklet processors, retry failed registration, reuse FFT scratch (#3175)
* fix(core): remove the build-audio-fx-runtime.ts stray resurrected by a main merge An earlier merge with main brought this deleted file back (git's merge/delete handling on an unchanged-on-one-side file); package.json already points at build-inline-artifact.ts, so it sat unreachable and duplicating that file's config, both of which fallow flagged. * fix(studio): pull TimelineLanes under the 600-line cap TimelineLanes.tsx hit 620 lines. Extracted the three per-clip pointer gestures (resize-start, pointer-down move-arm, click/razor-split) into createClipGestureHandlers — one factory call per rendered clip instead of ~120 lines of inline handler bodies in the render loop. 529 lines now. * fix(studio): split the extracted pointerdown handler under the CRAP threshold Moving the ~120-line gesture logic into timelineClipGestureHandlers.ts concentrated it into two functions fallow flagged (onPointerDown at CRAP 63.6, onResizeStart at 31.6). Split the decision logic (which gesture a pointerdown implies) into a pure resolvePointerDownAction, then split its own intent-blocking check into isIntentBlocked. onResizeStart's guard moved into canStartResize. Every function now scores under 30. * fix(studio): drop the unused DomEditSelection import in PropertyPanelFlat CI caught it on PR #3026 (wa-12-panel-params); a later refactor in the stack removed the last use of the type here without removing the import. * fix(studio): close the typecheck and fallow gaps wa-18b-reschedule opened useAutomationLanes.ts's write() assumed gesture-scoped coalescing and a preview-only commit that useDomEditAttributeCommits.ts never grew — backported that option support from its own later commit so the two sides of the API agree. The paste path and its tests were missing the box selection's v0/v1 bounds a sibling commit added to AutomationSelection. The FX panel's carve controls still edited the six mechanism numbers (maxCutDb, bands, intelligibilityBias) after carveProfile() collapsed authoring to one Strength knob, so those fields no longer existed on HfCarveSettings; UI now edits strength, and analyseCarveBands is called with carveProfile(strength). Also closes fallow's complexity, dead-code and duplication findings on this PR's diff: extracted automationLaneDragMath.ts (pure group/point-move math) and useAutomationRangeDrag.ts (the marquee-select gesture) out of useAutomationLaneGestures.ts, pulled a couple of render-loop ternaries and a resolver into named functions, dropped an export nothing outside its file used, and shared a step-simplifier between audioCarve's two envelope builders. The edge-stretch vs. box-select priority test in TimelineAutomationLane.test was still pinning the pre-box-select rule (edge wins over a point sitting on it) that a sibling commit deliberately reversed — a point inside the box is now selected content, so grabbing it drags the group instead. Updated the test to the shipped rule instead of the old one. Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com> * fix(core): cap the via conic's weight so an edge-clamped via point can't NaN A via point pulled out past the segment (viaX: 5, viaY: -3) clamps to (0.999, 0.001) — exactly on the steady region's edge, where edge - viaX is 0. viaConic divided by that zero to get an infinite weight, and shapeVia turned Infinity into NaN a few steps later (Infinity - Infinity in the quadratic coefficient). NaN reaching setValueCurveAtTime silences the automated parameter for the rest of the render. Capped the weight at 1e6 instead of leaving it unbounded — past that point the arc already reads as touching the via point, so nothing visible is lost. Also hardened shapeVia's existing denominator guard (`<= 0`) to `!(> 0)`, since NaN fails the original comparison and fell through it. Review by Miga (PR #3208). * fix(studio-server): fingerprint the proactive waveform cache key too The route already keys the waveform cache on the asset's size and mtime as well as its path, so a rebuilt-in-place file gets fresh peaks instead of stale ones. generateWaveformCache — the proactive path that runs on upload — still called buildWaveformCacheKey with the path alone, so it wrote to a different key than the route reads from (making the pre-generated cache never found) and kept the exact collision bug this fingerprint exists to fix on its own path. Review by Miga (PR #3211). * style(docs): run oxfmt on the /hyperframes-audio skill docs Table column widths had drifted out of alignment with oxfmt's own rules, failing format:check and blocking the Preflight gate every downstream branch inherits. Whitespace only, no content change. * fix(core): stop \b from missing underscore-separated names, guard clipsOverlap's negative duration \b treats `_` as a word character, so \bbed\b never matched bed_01, music_bed_loop, or theme_song, and \bvo\b/\bvox\b/\btts\b had the same gap — an underscore-separated bed classified as "unknown" and could end up offered as its own carve source. Replaced the short hints with a boundary that actually excludes letters and digits on both sides. clipsOverlap computed end = start + duration without guarding sign, so a negative duration put end before start — an interval that does not describe anything, and one specific case showed it silently dropping a real overlap (a shorter, earlier broken end rejected a clip that genuinely contained the point). Duration clamps to zero instead: a clip cannot un-play time, and a zero-length clip at its start is the sane reading of "duration nobody wrote down as positive." Review by Miga (PR #3212). * fix(studio): widen PropertyPanel's resetModules render timeout again The 20s margin (already once widened for the same reason) is timing out in CI's full-monorepo Test run — the resetModules()+fresh-import render this test needs is uncached and competes with every other package's test suite for the same worker pool, and the same test passes in well under 2s standalone. Went to 45s rather than re-tuning to whatever number happens to clear the current CI load, since that number moves every time CI gains a package. * fix(studio): stop the single-candidate auto-apply carve firing twice Two auto-apply effects both fire when sourceOptions.length === 1: the multi-candidate effect only guards length === 0, so a single candidate passes it too, and the single-candidate effect passes its own guard right after — both compute the same sources list and both call setCarve, so the common case (one narrator, one bed) triggered two decodes, two FFT runs, and two concurrent attribute writes for one decision. The multi-candidate effect now defers to its sibling for exactly one candidate, which already has its own detailed handling for that case. Review by Miga (PR #3213). * feat(core): carve against every voice over a bed, always (#3212) * feat(core): carve against every voice over a bed, always dynamically A bed usually runs under a whole sequence — a narrator, an interview answer, a second presenter — and carving against one of them left the others fighting it. `source` becomes `sources`, and `mixCarveSources` sums every voice onto the BED's clock before anything is measured. That is what keeps one analysis sufficient: the chain is fixed, so there is no per-voice filter to switch between, and bands drawn from all the speech there is with envelopes that rise wherever any of it happens answer the actual question — where and when is speech masking this bed. Summed rather than averaged: two people talking at once mask more than either alone. Audio before the bed starts is dropped rather than folded in at zero, since it plays over nothing and shifting it would put a cut where there is no voice. `dynamic` is gone. A fixed depth thins the bed through every pause, and once both have been heard there is no reason to want it, so every carve follows the speech. Two helpers the panel and the headless script now share instead of each carrying a copy — two definitions of "what does this name suggest" drift, and then the two disagree about which track is the voice: - `classifyAudioName` reads a track's kind from its id and filename together. `unknown` is deliberately common: treating an unrecognised name as "not a voice" would hide the one track somebody needs to pick. - `clipsOverlap` keeps out a voice that never plays while the bed does. An unwritten duration counts as unbounded, not zero — refusing a clip whose length the composition leaves to the media would drop the commonest case there is. Files written before this still load: a single `source` reads as a one-voice list, a stored `dynamic` is ignored, and an absent attribute means the defaults whole. Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com> * fix(core): stop \b from missing underscore-separated names, guard clipsOverlap's negative duration \b treats `_` as a word character, so \bbed\b never matched bed_01, music_bed_loop, or theme_song, and \bvo\b/\bvox\b/\btts\b had the same gap — an underscore-separated bed classified as "unknown" and could end up offered as its own carve source. Replaced the short hints with a boundary that actually excludes letters and digits on both sides. clipsOverlap computed end = start + duration without guarding sign, so a negative duration put end before start — an interval that does not describe anything, and one specific case showed it silently dropping a real overlap (a shorter, earlier broken end rejected a clip that genuinely contained the point). Duration clamps to zero instead: a clip cannot un-play time, and a zero-length clip at its start is the sane reading of "duration nobody wrote down as positive." Review by Miga (PR #3212). --------- Co-authored-by: Claude Opus 5 (1M context) <noreply@anthropic.com> * fix(studio): port the carve UI off the removed source/dynamic fields #3212 (accidentally squash-merged into this branch instead of main) changed HfCarveSettings from a single `source` + `dynamic` toggle to a `sources` list with dynamic mode removed outright — the multi-voice UI consumer that goes with that shape lands in the very next PR, so this branch was left with a type that no longer matched its own code. Minimal port, not the multi-voice redesign that PR does properly: the "Listen to" picker and analyse() treat sources[0] as the one voice this UI still understands, and every dynamic-mode branch (the automated envelope lanes, the toggle, the checkbox) is gone along with the field — a carve is now always the static value the analysis computes, matching what the type change made permanent. Test suite trimmed the same way: the automation-lane and toggle tests covered behavior that no longer exists. --------- Co-authored-by: Claude Opus 5 (1M context) <noreply@anthropic.com>
This commit is contained in:
co-authored by
Claude Opus 5
parent
ea0344122c
commit
f6cf3b242b
@@ -149,13 +149,6 @@
|
||||
"file": "packages/studio/src/utils/studioHelpers.ts",
|
||||
"exports": ["resolveDroppedAssetDimensions"],
|
||||
},
|
||||
// Audio FX worklets sit near the bottom of the audio stack: the worklet
|
||||
// source and its test reset are consumed by the runtime and engine PRs
|
||||
// upstack, so a per-PR audit against the merge base sees them as unused.
|
||||
{
|
||||
"file": "packages/core/src/audio/audioFxWorklets.ts",
|
||||
"exports": ["AUDIO_FX_WORKLET_SOURCE", "__resetAudioFxWorkletsForTests"],
|
||||
},
|
||||
{
|
||||
"file": "packages/core/src/audio/audioFxGraph.ts",
|
||||
"exports": ["ensureAudioFxWorklets"],
|
||||
|
||||
@@ -155,6 +155,16 @@ describe("buildFxNode", () => {
|
||||
expect(workletNodes[0]!.messages[0]).toMatchObject({ threshold: -30 });
|
||||
});
|
||||
|
||||
it("tells a worklet processor to retire on dispose, not just disconnect it", () => {
|
||||
// Disconnecting leaves the processor alive — it lives until `process()`
|
||||
// returns false — so every rebuild that dropped a worklet effect left one
|
||||
// running on the audio thread for the rest of the session.
|
||||
workletNodes.length = 0;
|
||||
const h = buildFxNode(asCtx(ctx()), "compressor", defaultAudioFxParams("compressor"));
|
||||
h.dispose();
|
||||
expect(workletNodes[0]!.messages).toEqual([{ __hfDispose: true }]);
|
||||
});
|
||||
|
||||
it("rebuilds the saturation curve for the selected shape", () => {
|
||||
const c = ctx();
|
||||
buildFxNode(asCtx(c), "saturate", { ...defaultAudioFxParams("saturate"), type: "hard" });
|
||||
|
||||
@@ -182,7 +182,17 @@ function workletBuilder(processor: string): Builder {
|
||||
input: node,
|
||||
output: node,
|
||||
update: (v) => node.port.postMessage({ ...v }),
|
||||
dispose: () => node.disconnect(),
|
||||
dispose: () => {
|
||||
// Disconnecting is not enough to retire an AudioWorkletProcessor: it
|
||||
// lives until its `process()` returns false, and these all returned
|
||||
// true unconditionally. So every chain rebuild that dropped a limiter,
|
||||
// compressor, gate or bitcrush left it running on the audio thread for
|
||||
// the rest of the session, and a few edits to a carved bed accumulated
|
||||
// a stack of them. The processors treat this message as their cue to
|
||||
// stop.
|
||||
node.port.postMessage({ __hfDispose: true });
|
||||
node.disconnect();
|
||||
},
|
||||
};
|
||||
};
|
||||
}
|
||||
|
||||
@@ -0,0 +1,103 @@
|
||||
import { describe, expect, it, vi } from "vitest";
|
||||
import { audioFxWorkletsReady, ensureAudioFxWorklets } from "./audioFxWorklets.js";
|
||||
|
||||
/** Just enough of a BaseAudioContext for the registration cache to key on. */
|
||||
const contextWith = (addModule: (url: string) => Promise<void>): BaseAudioContext =>
|
||||
({ audioWorklet: { addModule } }) as unknown as BaseAudioContext;
|
||||
|
||||
describe("ensureAudioFxWorklets", () => {
|
||||
it("registers once per context and reuses the result", async () => {
|
||||
const addModule = vi.fn(async () => undefined);
|
||||
const ctx = contextWith(addModule);
|
||||
|
||||
await ensureAudioFxWorklets(ctx);
|
||||
await ensureAudioFxWorklets(ctx);
|
||||
|
||||
expect(addModule).toHaveBeenCalledTimes(1);
|
||||
expect(audioFxWorkletsReady(ctx)).toBe(true);
|
||||
});
|
||||
|
||||
it("retries after a failure instead of replaying it forever", async () => {
|
||||
// The rejected promise used to stay in the cache, so every later attempt
|
||||
// got the same rejection back — the limiter, compressor, gate and bitcrush
|
||||
// were silent for the life of the context after one transient failure.
|
||||
const addModule = vi
|
||||
.fn<(url: string) => Promise<void>>()
|
||||
.mockRejectedValueOnce(new Error("module load failed"))
|
||||
.mockResolvedValue(undefined);
|
||||
const ctx = contextWith(addModule);
|
||||
|
||||
await expect(ensureAudioFxWorklets(ctx)).rejects.toThrow("module load failed");
|
||||
expect(audioFxWorkletsReady(ctx)).toBe(false);
|
||||
|
||||
await expect(ensureAudioFxWorklets(ctx)).resolves.toBeUndefined();
|
||||
expect(addModule).toHaveBeenCalledTimes(2);
|
||||
expect(audioFxWorkletsReady(ctx)).toBe(true);
|
||||
});
|
||||
|
||||
it("refuses a context with no AudioWorklet rather than hanging", async () => {
|
||||
const ctx = {} as BaseAudioContext;
|
||||
await expect(ensureAudioFxWorklets(ctx)).rejects.toThrow(/secure context/);
|
||||
});
|
||||
});
|
||||
|
||||
/**
|
||||
* A processor lives until its `process()` returns false — disconnecting the
|
||||
* node does not retire it. These all returned true unconditionally, so every
|
||||
* chain rebuild that dropped a worklet effect left it running on the audio
|
||||
* thread for the rest of the session.
|
||||
*
|
||||
* The source is taken from the data: URL registration actually hands to
|
||||
* `addModule`, so this also proves the URL carries what it claims to.
|
||||
*/
|
||||
describe("the worklet processors themselves", () => {
|
||||
/** Evaluate the registered module and hand back the processor classes by name. */
|
||||
async function loadProcessors(): Promise<Map<string, new (o: unknown) => Processor>> {
|
||||
let moduleSource = "";
|
||||
await ensureAudioFxWorklets(
|
||||
contextWith(async (url: string) => {
|
||||
moduleSource = atob(url.replace("data:text/javascript;base64,", ""));
|
||||
}),
|
||||
);
|
||||
const made = new Map<string, new (o: unknown) => Processor>();
|
||||
class Base {
|
||||
port = {
|
||||
onmessage: null as ((e: { data: unknown }) => void) | null,
|
||||
postMessage: (data: unknown) => this.port.onmessage?.({ data }),
|
||||
};
|
||||
}
|
||||
new Function("AudioWorkletProcessor", "registerProcessor", "sampleRate", moduleSource)(
|
||||
Base,
|
||||
(name: string, cls: new (o: unknown) => Processor) => made.set(name, cls),
|
||||
48000,
|
||||
);
|
||||
return made;
|
||||
}
|
||||
|
||||
interface Processor {
|
||||
port: { postMessage(data: unknown): void };
|
||||
process(inputs: Float32Array[][], outputs: Float32Array[][]): boolean;
|
||||
}
|
||||
|
||||
const block = (): Float32Array[][] => [[new Float32Array(128)]];
|
||||
|
||||
it("every processor keeps running until it is told to stop, then retires", async () => {
|
||||
const processors = await loadProcessors();
|
||||
expect([...processors.keys()]).toEqual([
|
||||
"hf-compressor",
|
||||
"hf-limiter",
|
||||
"hf-gate",
|
||||
"hf-bitcrush",
|
||||
]);
|
||||
|
||||
for (const [name, Cls] of processors) {
|
||||
const p = new Cls({ processorOptions: {} });
|
||||
expect(p.process(block(), block()), `${name} retired before it was disposed`).toBe(true);
|
||||
p.port.postMessage({ __hfDispose: true });
|
||||
expect(p.process(block(), block()), `${name} kept running after dispose`).toBe(false);
|
||||
// And it stays retired — a later parameter update must not revive it.
|
||||
p.port.postMessage({ mix: 0.5 });
|
||||
expect(p.process(block(), block()), `${name} came back to life`).toBe(false);
|
||||
}
|
||||
});
|
||||
});
|
||||
@@ -60,11 +60,13 @@ class HfCompressor extends AudioWorkletProcessor {
|
||||
this.p = o.processorOptions || {};
|
||||
this.env = new EnvBank(this.p.attack ?? 20, this.p.release ?? 250);
|
||||
this.port.onmessage = (e) => {
|
||||
if (e.data && e.data.__hfDispose) { this.dead = true; return; }
|
||||
this.p = { ...this.p, ...e.data };
|
||||
this.env.set(this.p.attack ?? 20, this.p.release ?? 250);
|
||||
};
|
||||
}
|
||||
process(inputs, outputs) {
|
||||
if (this.dead) return false;
|
||||
const i = inputs[0], o = outputs[0];
|
||||
if (!i || !i.length) return true;
|
||||
const p = this.p;
|
||||
@@ -105,11 +107,13 @@ class HfLimiter extends AudioWorkletProcessor {
|
||||
this.p = o.processorOptions || {};
|
||||
this.env = new EnvBank(this.p.attack ?? 5, this.p.release ?? 50);
|
||||
this.port.onmessage = (e) => {
|
||||
if (e.data && e.data.__hfDispose) { this.dead = true; return; }
|
||||
this.p = { ...this.p, ...e.data };
|
||||
this.env.set(this.p.attack ?? 5, this.p.release ?? 50);
|
||||
};
|
||||
}
|
||||
process(inputs, outputs) {
|
||||
if (this.dead) return false;
|
||||
const i = inputs[0], o = outputs[0];
|
||||
if (!i || !i.length) return true;
|
||||
const ceiling = dbToLin(this.p.limit ?? -1);
|
||||
@@ -136,11 +140,13 @@ class HfGate extends AudioWorkletProcessor {
|
||||
this.env = new EnvBank(this.p.attack ?? 1, this.p.release ?? 100);
|
||||
this.gains = [];
|
||||
this.port.onmessage = (e) => {
|
||||
if (e.data && e.data.__hfDispose) { this.dead = true; return; }
|
||||
this.p = { ...this.p, ...e.data };
|
||||
this.env.set(this.p.attack ?? 1, this.p.release ?? 100);
|
||||
};
|
||||
}
|
||||
process(inputs, outputs) {
|
||||
if (this.dead) return false;
|
||||
const i = inputs[0], o = outputs[0];
|
||||
if (!i || !i.length) return true;
|
||||
const p = this.p;
|
||||
@@ -183,9 +189,13 @@ class HfBitcrush extends AudioWorkletProcessor {
|
||||
this.p = o.processorOptions || {};
|
||||
this.holds = [];
|
||||
this.held = [];
|
||||
this.port.onmessage = (e) => { this.p = { ...this.p, ...e.data }; };
|
||||
this.port.onmessage = (e) => {
|
||||
if (e.data && e.data.__hfDispose) { this.dead = true; return; }
|
||||
this.p = { ...this.p, ...e.data };
|
||||
};
|
||||
}
|
||||
process(inputs, outputs) {
|
||||
if (this.dead) return false;
|
||||
const i = inputs[0], o = outputs[0];
|
||||
if (!i || !i.length) return true;
|
||||
const p = this.p;
|
||||
@@ -243,7 +253,16 @@ export function ensureAudioFxWorklets(ctx: BaseAudioContext): Promise<void> {
|
||||
)}`;
|
||||
await ctx.audioWorklet.addModule(url);
|
||||
readyContexts.add(ctx);
|
||||
})();
|
||||
})().catch((err: unknown) => {
|
||||
// A failed registration must not be remembered. `readyContexts` is only
|
||||
// written on success, so callers correctly keep asking — and every ask
|
||||
// replayed this same rejected promise, leaving the limiter, compressor,
|
||||
// gate and bitcrush silent for the life of the context with no way back.
|
||||
// One transient failure (a slow module load, a context still warming up)
|
||||
// permanently disabled half the rack.
|
||||
registered.delete(ctx);
|
||||
throw err;
|
||||
});
|
||||
registered.set(ctx, modulePromise);
|
||||
}
|
||||
return modulePromise;
|
||||
|
||||
@@ -250,6 +250,48 @@ describe("analyseCarveBands", () => {
|
||||
});
|
||||
});
|
||||
|
||||
/**
|
||||
* Both analysis loops reuse one pair of FFT scratch arrays across every window
|
||||
* rather than allocating a pair per hop — a 5-minute 48 kHz voiceover is ~7000
|
||||
* hops, so ~460 MB of transient Float64Array used to churn through the main
|
||||
* thread for one carve. `re` is fully overwritten each window, but `im` is only
|
||||
* ever added to, so it has to be cleared; missing that, the imaginary part
|
||||
* accumulates across windows and every spectrum after the first is wrong by a
|
||||
* growing amount.
|
||||
*/
|
||||
describe("reused FFT scratch across windows", () => {
|
||||
/** A steady tone on an exact bin centre (48000/4096 x 128), so every window is identical. */
|
||||
const steady = (seconds: number): Float32Array => {
|
||||
const n = Math.floor(SR * seconds);
|
||||
const out = new Float32Array(n);
|
||||
for (let i = 0; i < n; i++) out[i] = 0.5 * Math.sin((2 * Math.PI * 1500 * i) / SR);
|
||||
return out;
|
||||
};
|
||||
|
||||
it("measures the same bands however many windows the clip has", () => {
|
||||
// Every window carries the same spectrum, so the Welch average cannot
|
||||
// depend on how many were averaged — unless one window is contaminating
|
||||
// the next.
|
||||
const short = analyseCarveBands(steady(0.5), SR, PROFILE);
|
||||
const long = analyseCarveBands(steady(12), SR, PROFILE);
|
||||
expect(short.length).toBeGreaterThan(0);
|
||||
expect(long).toEqual(short);
|
||||
});
|
||||
|
||||
it("keeps a steady tone's dynamics envelope flat instead of drifting", () => {
|
||||
const [lane] = analyseCarveDynamics(steady(12), SR, [{ freq: 1600, gainDb: -8, q: 1.4 }]);
|
||||
const value = (t: number): number =>
|
||||
sampleAutomationLane({ target: "fx.n1.gain", points: lane!.points }, t);
|
||||
// Past the attack the cut has to sit still, because the signal does. A
|
||||
// window contaminated by the one before it grows the measured power over
|
||||
// the clip, and the envelope — which is relative to the band's own peak —
|
||||
// slides with it.
|
||||
expect(value(4)).toBeLessThan(-1);
|
||||
expect(value(8)).toBeCloseTo(value(4), 0);
|
||||
expect(value(11)).toBeCloseTo(value(4), 0);
|
||||
});
|
||||
});
|
||||
|
||||
describe("carveBandsToChain", () => {
|
||||
it("turns bands into peaking nodes carrying the analysed values", () => {
|
||||
const chain = carveBandsToChain([{ freq: 1000, gainDb: -6, q: 1.4 }]);
|
||||
|
||||
@@ -332,12 +332,23 @@ function powerSpectrum(
|
||||
|
||||
const bins = FRAME / 2 + 1;
|
||||
const acc = new Float64Array(bins);
|
||||
// Reused across hops. These used to be allocated inside the loop: a 5-minute
|
||||
// 48 kHz voiceover is ~7000 hops, so ~460 MB of transient Float64Array
|
||||
// churned through the main thread for a single carve. `re` is fully
|
||||
// overwritten below; only `im` has to be cleared.
|
||||
const re = new Float64Array(FRAME);
|
||||
const im = new Float64Array(FRAME);
|
||||
//
|
||||
// Every hop is still read. Striding them — Welch's average is supposed to
|
||||
// settle long before 7000 windows — was measured on a 5-minute voiceover and
|
||||
// moves the result: at strength 0.9 the chosen band set changed (630 Hz for
|
||||
// 160 Hz), and it did not converge back to the full read even at 2048
|
||||
// windows. 27x faster is not worth silently redrawing the author's carve.
|
||||
let frames = 0;
|
||||
for (let start = 0; start + FRAME <= n; start += HOP) {
|
||||
// Goertzel-free naive DFT would be O(n^2); use a real FFT via recursion on
|
||||
// a copied frame. FRAME is a power of two so the radix-2 split is exact.
|
||||
const re = new Float64Array(FRAME);
|
||||
const im = new Float64Array(FRAME);
|
||||
im.fill(0);
|
||||
for (let i = 0; i < FRAME; i++) re[i] = (padded[start + i] ?? 0) * window[i]!;
|
||||
fft(re, im);
|
||||
for (let k = 0; k < bins; k++) acc[k]! += re[k]! * re[k]! + im[k]! * im[k]!;
|
||||
@@ -601,9 +612,13 @@ export function analyseCarveDynamics(
|
||||
|
||||
const times: number[] = [];
|
||||
const perBand = bands.map(() => [] as number[]);
|
||||
// Reused across windows, as in powerSpectrum. `re` is fully overwritten
|
||||
// below; only `im` has to be cleared. The hop here is already bounded by
|
||||
// POINT_BUDGET, so there is nothing to stride.
|
||||
const re = new Float64Array(FRAME);
|
||||
const im = new Float64Array(FRAME);
|
||||
for (let start = 0; start < voice.length; start += hop) {
|
||||
const re = new Float64Array(FRAME);
|
||||
const im = new Float64Array(FRAME);
|
||||
im.fill(0);
|
||||
for (let i = 0; i < FRAME; i++) re[i] = (voice[start + i] ?? 0) * window[i]!;
|
||||
fft(re, im);
|
||||
const power: number[] = [];
|
||||
|
||||
@@ -69,6 +69,27 @@ describe("normalizeAudioFxParams", () => {
|
||||
expect(v.gain).toBe(0);
|
||||
});
|
||||
|
||||
it("treats a blank or missing value as absent rather than as zero", () => {
|
||||
// `Number(null)`, `Number("")`, `Number(false)` and `Number([])` are all 0
|
||||
// and all finite, so these used to clamp to 0 instead of falling back. Zero
|
||||
// is a legal setting for most of these knobs, so nothing downstream could
|
||||
// tell: a compressor whose threshold arrived as null sat at 0 dB and never
|
||||
// engaged, silently, rather than at its declared -24 dB.
|
||||
const def = defaultAudioFxParams("compressor").threshold;
|
||||
expect(def).not.toBe(0);
|
||||
for (const blank of [null, undefined, "", " ", false, [], {}]) {
|
||||
expect(
|
||||
normalizeAudioFxParams("compressor", { threshold: blank as unknown as number }).threshold,
|
||||
`${JSON.stringify(blank)} was read as a number`,
|
||||
).toBe(def);
|
||||
}
|
||||
// A string that really does spell a number still counts — that is how the
|
||||
// panel's inputs arrive.
|
||||
expect(
|
||||
normalizeAudioFxParams("compressor", { threshold: "-30" as unknown as number }).threshold,
|
||||
).toBe(-30);
|
||||
});
|
||||
|
||||
it("falls back to the default for an unrecognised enum value", () => {
|
||||
expect(normalizeAudioFxParams("saturate", { type: "sawtooth" }).type).toBe("tanh");
|
||||
expect(normalizeAudioFxParams("saturate", { type: "atan" }).type).toBe("atan");
|
||||
|
||||
@@ -761,7 +761,20 @@ export function normalizeAudioFxParams(
|
||||
out[p.key] = ok ? (raw as string) : p.default;
|
||||
continue;
|
||||
}
|
||||
const n = typeof raw === "number" ? raw : Number(raw);
|
||||
// Only a number, or a string that actually spells one. `Number(null)`,
|
||||
// `Number("")`, `Number(false)` and `Number([])` are all 0 and all pass
|
||||
// Number.isFinite, so a missing or blanked value used to clamp to 0 rather
|
||||
// than fall back to the declared default — and 0 is a legal value for most
|
||||
// of these knobs, so nothing downstream could tell. A compressor whose
|
||||
// threshold arrived as null sat at 0 dB and never engaged, silently,
|
||||
// instead of at its -24 dB default. `numberOrNull` in audioAutomation.ts
|
||||
// already guards exactly this.
|
||||
const n =
|
||||
typeof raw === "number"
|
||||
? raw
|
||||
: typeof raw === "string" && raw.trim() !== ""
|
||||
? Number(raw)
|
||||
: Number.NaN;
|
||||
out[p.key] = Number.isFinite(n) ? Math.min(p.max, Math.max(p.min, n)) : p.default;
|
||||
}
|
||||
return out;
|
||||
|
||||
@@ -122,7 +122,27 @@ describe("runAudioStage", () => {
|
||||
const result = await runAudioStage(makeInput());
|
||||
expect(result.hasAudio).toBe(false);
|
||||
expect(result.audioError).toMatch(/Audio FX failed for track bgm/);
|
||||
expect(result.audioFailures).toBeUndefined();
|
||||
// And it is classified. This used to come back undefined, so the warning
|
||||
// policy — which reads owner, retryability, reason and stage off this list
|
||||
// — described the FATAL failure with strictly less detail than a single
|
||||
// dropped track gets.
|
||||
expect(result.audioFailures).toEqual([
|
||||
{
|
||||
stage: "internal",
|
||||
reason: "internal",
|
||||
owner: "system",
|
||||
retryable: false,
|
||||
detail: "Audio FX failed for track bgm: browser launch failed",
|
||||
},
|
||||
]);
|
||||
});
|
||||
|
||||
it("bounds the synthesised failure's detail", async () => {
|
||||
// `detail` is contractually bounded diagnostic text; an ffmpeg-flavoured
|
||||
// message can run to tens of kilobytes.
|
||||
processCompositionAudioMock.mockRejectedValue(new Error("x".repeat(5_000)));
|
||||
const result = await runAudioStage(makeInput());
|
||||
expect(result.audioFailures?.[0]?.detail.length).toBe(2_000);
|
||||
});
|
||||
|
||||
it("lets an abort keep its own shape rather than becoming an audio error", async () => {
|
||||
|
||||
@@ -90,12 +90,28 @@ export async function runAudioStage(input: AudioStageInput): Promise<AudioStageR
|
||||
} catch (err) {
|
||||
// An abort is the caller's own signal and must keep its own shape.
|
||||
assertNotAborted();
|
||||
const detail = err instanceof Error ? err.message : String(err);
|
||||
return {
|
||||
audioOutputPath,
|
||||
hasAudio: false,
|
||||
audioProcessMs: Date.now() - stage3Start,
|
||||
audioError: err instanceof Error ? err.message : String(err),
|
||||
audioFailures: undefined,
|
||||
audioError: detail,
|
||||
// Synthesised rather than left undefined. The warning policy reads
|
||||
// owner, retryability, reason and stage off this list, so reporting the
|
||||
// FATAL failure — the one that took the whole mix down — with an empty
|
||||
// one gave it strictly less classification than a single dropped track
|
||||
// gets, which is the opposite of what this stage exists to do.
|
||||
// "internal" is the honest bucket: the stages enumerate ffmpeg steps
|
||||
// and this is the FX render, which is none of them.
|
||||
audioFailures: [
|
||||
{
|
||||
stage: "internal",
|
||||
reason: "internal",
|
||||
owner: "system",
|
||||
retryable: false,
|
||||
detail: detail.slice(0, 2_000),
|
||||
},
|
||||
],
|
||||
};
|
||||
}
|
||||
assertNotAborted();
|
||||
|
||||
Reference in New Issue
Block a user