From aefca2baff396213711b59fcce5ec357896529c6 Mon Sep 17 00:00:00 2001 From: Michael Wang Date: Tue, 24 Nov 2026 09:25:11 +0000 Subject: [PATCH] fix(media-use): carve decodes only media files inside the composition's folder (#8649) * fix(media-use): carve decodes only media files inside the composition's folder carve.mjs resolved each media src from the composition and handed the result to ffmpeg, so an absolute, climbing, UNC or linked name reached a file outside the project, and a playlist inside the project was followed to the files it lists. Each src must now be a relative name that lands on a regular file inside the composition's folder after links are resolved, outside the files the project keeps private, and free of ffmpeg pattern characters. Every source is checked before any is decoded. ffmpeg then reads the one file, pinned to its probed format and the file protocol, and a list or playlist format is refused. The probe and the pinned input move from recording.mjs into lib/media-input.mjs so both scripts share them. The private-path rule and the image2 pattern guard are bundled into audio-carve.mjs from packages/parsers. * fix(media-use): media-input.mjs loads the Windows program guard first Every skill script that starts programs imports windows-exe-search.mjs before anything else, so ffprobe and ffmpeg are never looked up in the working directory on Windows. --- scripts/generate-media-use-audio-carve.mjs | 11 +- skills-manifest.json | 4 +- skills/media-use/audio/scripts/carve.mjs | 59 ++++++- skills/media-use/audio/scripts/carve.test.mjs | 157 +++++++++++++++++- .../audio/scripts/lib/audio-carve.mjs | 9 +- .../audio/scripts/lib/media-input.mjs | 58 +++++++ .../media-use/audio/scripts/lib/recording.mjs | 46 +---- skills/media-use/references/mixing.md | 2 +- 8 files changed, 280 insertions(+), 66 deletions(-) create mode 100644 skills/media-use/audio/scripts/lib/media-input.mjs diff --git a/scripts/generate-media-use-audio-carve.mjs b/scripts/generate-media-use-audio-carve.mjs index 4916284364..ec954bb90a 100644 --- a/scripts/generate-media-use-audio-carve.mjs +++ b/scripts/generate-media-use-audio-carve.mjs @@ -1,5 +1,6 @@ #!/usr/bin/env node -// Bundles the carve analysis carve.mjs uses (packages/core/src/audioCarve.ts and audioFx.ts) into a single +// Bundles the carve analysis carve.mjs uses (packages/core/src/audioCarve.ts and audioFx.ts), and the private-path +// rule it checks sources with (packages/parsers/src/privatePath.ts), into a single // import-free .mjs beside the skill, so the skill never loads @hyperframes/core from the project it edits. // Regenerate after editing the source: node scripts/generate-media-use-audio-carve.mjs import { writeFileSync } from "node:fs"; @@ -29,11 +30,13 @@ export { parseAudioFxChain, serializeAudioFxChain, } from "./audioFx.ts"; +export { isStudioPrivatePath } from "../../parsers/src/privatePath.ts"; `; -const HEADER = `// GENERATED: do not hand-edit. Source: packages/core/src/audioCarve.ts and audioFx.ts, bundled by -// scripts/generate-media-use-audio-carve.mjs so carve.mjs runs the same analysis as Studio without -// loading @hyperframes/core from the project. Regenerate: node scripts/generate-media-use-audio-carve.mjs +const HEADER = `// GENERATED: do not hand-edit. Source: packages/core/src/audioCarve.ts and audioFx.ts, and +// 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 `; export async function generate() { diff --git a/skills-manifest.json b/skills-manifest.json index 9769c17cf7..c57ba979da 100644 --- a/skills-manifest.json +++ b/skills-manifest.json @@ -18,8 +18,8 @@ "files": 13 }, "media-use": { - "hash": "277f0f64db23b1dd", - "files": 132 + "hash": "c0276ffe1b181f43", + "files": 133 }, "remotion-to-hyperframes": { "hash": "3a1dd4a513701ef6", diff --git a/skills/media-use/audio/scripts/carve.mjs b/skills/media-use/audio/scripts/carve.mjs index 9fda53b53e..fb33b3369c 100644 --- a/skills/media-use/audio/scripts/carve.mjs +++ b/skills/media-use/audio/scripts/carve.mjs @@ -25,10 +25,12 @@ import "../../scripts/lib/windows-exe-search.mjs"; import { execFileSync } from "node:child_process"; -import { readFileSync, writeFileSync } from "node:fs"; -import { dirname, resolve } from "node:path"; +import { readFileSync, realpathSync, statSync, writeFileSync } from "node:fs"; +import { dirname, relative, resolve, sep } from "node:path"; import * as carveApi from "./lib/audio-carve.mjs"; import { isMainModule } from "./lib/main-module.mjs"; +import { isIndirectFormat, pinnedInput, probeFormat } from "./lib/media-input.mjs"; +import { projectPath } from "./lib/project-path.mjs"; import { assertLiteralMediaPath } from "../../scripts/lib/literal-media-input.mjs"; /** Sample rate the analysis runs at. Matches Studio's own decode rate, so the @@ -170,18 +172,48 @@ export function groupSourceRefusal(voices, bed, members) { return strays.length > 0 ? { group, reason: "mixed", ids: strays } : null; } -/** Mono float PCM for one media file, via ffmpeg. */ +// A URL scheme, or a Windows drive name such as `C:` that a relative-looking name can start with. +const SCHEME_OR_DRIVE = /^[a-z][a-z0-9+.-]*:/i; + +/** + * The file a composition's media `src` names. Only a relative name that lands on a regular file inside the + * composition's folder, with links resolved, is accepted. Absolute, UNC, drive, URL and climbing names, and + * files the project keeps private, throw before anything opens them. + */ +export function mediaSource(compDir, src) { + const shown = JSON.stringify(src); + const path = SCHEME_OR_DRIVE.test(src) ? null : projectPath(compDir, src); + if (!path) { + throw new Error( + `media ${shown} is outside the composition's folder; copy it into the project and name it from there`, + ); + } + const rel = relative(realpathSync(compDir), path).split(sep).join("/"); + if (carveApi.isStudioPrivatePath(src) || carveApi.isStudioPrivatePath(rel)) { + throw new Error(`media ${shown} is a private project file, so carve does not read it`); + } + if (!statSync(path, { throwIfNoEntry: false })?.isFile()) { + throw new Error(`media ${shown} is not a file in the project`); + } + assertLiteralMediaPath(path); + return path; +} + +/** Mono float PCM for one media file, via ffmpeg reading that file alone. */ function decode(path) { + const format = probeFormat(path); + if (!format) fail(`could not decode ${path}: ffmpeg cannot read it as media`); + if (isIndirectFormat(format)) { + fail(`${path} is a ${format} list that points at other files; give the media file itself`); + } let raw; try { - assertLiteralMediaPath(path); raw = execFileSync( "ffmpeg", [ "-v", "error", - "-i", - path, + ...pinnedInput(format, path), "-vn", "-ac", "1", @@ -340,12 +372,21 @@ async function main() { ); const profile = carveApi.carveProfile(args.strength); + // Every source is checked before any is decoded, so a refused name stops the carve with no ffmpeg run. + let voicePaths; + let bedPath = null; + try { + voicePaths = voices.map((v) => mediaSource(compDir, unescapeAttr(attrOf(v.tag, "src")))); + if (profile.duckDb > 0) bedPath = mediaSource(compDir, unescapeAttr(bedSrc)); + } catch (error) { + fail(error.message); + } // Every voice summed onto the BED's clock before anything is measured. One // question — where and when is speech masking this bed — with one answer, even // when the answer comes from several people at different times. const voice = carveApi.mixCarveSources( - voices.map((v) => ({ - samples: decode(resolve(compDir, unescapeAttr(attrOf(v.tag, "src")))), + voices.map((v, i) => ({ + samples: decode(voicePaths[i]), offsetSeconds: startOf(v.tag) - startOf(bedTag), })), SAMPLE_RATE, @@ -356,7 +397,7 @@ async function main() { // The level half of the carve needs both sides: "how far over the speech is this // bed" cannot be answered by listening to one of them. No offset — the mix is // already on the bed's clock. - const bed = profile.duckDb > 0 ? decode(resolve(compDir, unescapeAttr(bedSrc))) : null; + const bed = bedPath ? decode(bedPath) : null; const duck = bed ? carveApi.analyseCarveDuck(voice, bed, SAMPLE_RATE, profile, 0) : []; // Anything the author built by hand survives a carve; only the previous diff --git a/skills/media-use/audio/scripts/carve.test.mjs b/skills/media-use/audio/scripts/carve.test.mjs index 9f99426b02..786037d21a 100644 --- a/skills/media-use/audio/scripts/carve.test.mjs +++ b/skills/media-use/audio/scripts/carve.test.mjs @@ -1,19 +1,26 @@ import assert from "node:assert/strict"; import test from "node:test"; -import { execFileSync } from "node:child_process"; +import { execFileSync, spawnSync } from "node:child_process"; import { existsSync, mkdirSync, mkdtempSync, readFileSync, + realpathSync, rmSync, symlinkSync, writeFileSync, } from "node:fs"; import { tmpdir } from "node:os"; -import { dirname, join } from "node:path"; +import { delimiter, dirname, join } from "node:path"; import { fileURLToPath } from "node:url"; -import { DEFAULT_STRENGTH, carveSources, groupSourceRefusal, parseArgs } from "./carve.mjs"; +import { + DEFAULT_STRENGTH, + carveSources, + groupSourceRefusal, + mediaSource, + parseArgs, +} from "./carve.mjs"; const SCRIPTS_DIR = dirname(fileURLToPath(import.meta.url)); @@ -280,3 +287,147 @@ test("the default strength is 0.8, and --strength still overrides it", () => { assert.equal(parseArgs(["--comp", "x.html"]).strength, 0.8); assert.equal(parseArgs(["--comp", "x.html", "--strength", "0.25"]).strength, 0.25); }); + +test("mediaSource accepts a regular file inside the composition's folder, by its real path", () => + inTempDir((dir) => { + mkdirSync(join(dir, "assets")); + writeFileSync(join(dir, "assets", "vo.wav"), "x"); + writeFileSync(join(dir, "bed.mp3"), "x"); + const real = realpathSync(dir); + assert.equal(mediaSource(dir, "assets/vo.wav"), join(real, "assets", "vo.wav")); + assert.equal(mediaSource(dir, "./bed.mp3"), join(real, "bed.mp3")); + assert.equal(mediaSource(dir, "assets/../bed.mp3"), join(real, "bed.mp3")); + })); + +test("mediaSource refuses every name that leaves the folder, before opening it", () => + inTempDir((dir) => { + const project = join(dir, "project"); + mkdirSync(project); + const outside = join(dir, "secret.wav"); + writeFileSync(outside, "x"); + symlinkSync(outside, join(project, "linked.wav")); + for (const src of [ + outside, + "../secret.wav", + "//attacker.example/share/x.mp3", + "\\\\attacker.example\\share\\x.mp3", + "C:secret.wav", + "C:\\secret.wav", + "file:///etc/hosts", + "http://attacker.example/x.mp3", + "linked.wav", + ]) { + assert.throws(() => mediaSource(project, src), /outside the composition's folder/, src); + } + })); + +test("mediaSource refuses private files, folders, missing files and ffmpeg patterns", () => + inTempDir((dir) => { + mkdirSync(join(dir, ".git")); + mkdirSync(join(dir, "folder.wav")); + for (const name of [".env", ".git/config", "id_rsa.wav", "take%d.png"]) { + writeFileSync(join(dir, name), "x"); + } + assert.throws(() => mediaSource(dir, ".env"), /private project file/); + assert.throws(() => mediaSource(dir, ".git/config"), /private project file/); + assert.throws(() => mediaSource(dir, "folder.wav"), /not a file in the project/); + assert.throws(() => mediaSource(dir, "missing.wav"), /not a file in the project/); + assert.throws(() => mediaSource(dir, "take%d.png"), /pattern of other files/); + })); + +/** A composition with a music bed and one narration track, both named by `src`. */ +function writeComposition(dir, voiceSrc, bedSrc = "bed.wav") { + writeFileSync( + join(dir, "index.html"), + `\n` + + `\n`, + ); +} + +const runCarve = (cwd, env = process.env) => + spawnSync(process.execPath, [join(SCRIPTS_DIR, "carve.mjs"), "--comp", "index.html"], { + cwd, + env, + encoding: "utf8", + }); + +test( + "a composition naming an outside file or a UNC host stops before any ffmpeg process starts", + { skip: process.platform === "win32" && "the stand-in ffmpeg is a shell script" }, + () => + inTempDir((dir) => { + const bin = join(dir, "bin"); + const ran = join(dir, "ffmpeg-ran"); + mkdirSync(bin); + for (const tool of ["ffmpeg", "ffprobe"]) { + writeFileSync(join(bin, tool), `#!/bin/sh\necho "$0 $*" >> "${ran}"\nexit 1\n`, { + mode: 0o755, + }); + } + const project = join(dir, "project"); + mkdirSync(project); + writeFileSync(join(project, "bed.wav"), "x"); + writeFileSync(join(dir, "secret.wav"), "x"); + const env = { ...process.env, PATH: `${bin}${delimiter}${process.env.PATH}` }; + for (const src of ["../secret.wav", "//attacker.example/share/x.mp3"]) { + writeComposition(project, src); + const before = readFileSync(join(project, "index.html"), "utf8"); + const run = runCarve(project, env); + assert.equal(run.status, 1, run.stderr); + assert.match(run.stderr, /outside the composition's folder/); + assert.equal(existsSync(ran), false, `ffmpeg ran for ${src}`); + assert.equal(readFileSync(join(project, "index.html"), "utf8"), before); + } + }), +); + +const tone = (path, seconds = 2, frequency = 440) => + spawnSync( + "ffmpeg", + [ + "-y", + "-loglevel", + "error", + "-f", + "lavfi", + "-i", + `sine=frequency=${frequency}:duration=${seconds}`, + ].concat([path]), + { encoding: "utf8" }, + ); + +test("a playlist saved under a media name inside the project is refused and opens nothing it names", () => + inTempDir((dir) => { + const project = join(dir, "project"); + mkdirSync(project); + const outside = join(dir, "outside.ts"); + const made = spawnSync( + "ffmpeg", + ["-y", "-loglevel", "error", "-f", "lavfi", "-i", "sine=duration=1", "-c:a", "aac", outside], + { encoding: "utf8" }, + ); + assert.equal(made.status, 0, made.stderr); + assert.equal(tone(join(project, "bed.wav")).status, 0); + writeFileSync( + join(project, "narration.m3u8"), + `#EXTM3U\n#EXT-X-TARGETDURATION:1\n#EXTINF:1,\n${outside}\n#EXT-X-ENDLIST\n`, + ); + writeComposition(project, "narration.m3u8"); + const before = readFileSync(join(project, "index.html"), "utf8"); + const run = runCarve(project); + assert.equal(run.status, 1, run.stderr); + assert.match(run.stderr, /list that points at other files|cannot read it as media/); + assert.equal(readFileSync(join(project, "index.html"), "utf8"), before); + })); + +test("a composition whose media are files in its folder still carves", () => + inTempDir((dir) => { + mkdirSync(join(dir, "assets")); + assert.equal(tone(join(dir, "bed.wav"), 3, 220).status, 0); + assert.equal(tone(join(dir, "assets", "narration.m4a"), 3, 1000).status, 0); + writeComposition(dir, "assets/narration.m4a"); + const run = runCarve(dir); + assert.equal(run.status, 0, run.stderr); + assert.match(run.stdout, /wrote index.html/); + assert.match(readFileSync(join(dir, "index.html"), "utf8"), /data-fx-chain=/); + })); diff --git a/skills/media-use/audio/scripts/lib/audio-carve.mjs b/skills/media-use/audio/scripts/lib/audio-carve.mjs index 80e4ccd00c..d7447bf45d 100644 --- a/skills/media-use/audio/scripts/lib/audio-carve.mjs +++ b/skills/media-use/audio/scripts/lib/audio-carve.mjs @@ -1,4 +1,5 @@ -// GENERATED: do not hand-edit. Source: packages/core/src/audioCarve.ts and audioFx.ts, bundled by -// scripts/generate-media-use-audio-carve.mjs so carve.mjs runs the same analysis as Studio without -// loading @hyperframes/core from the project. Regenerate: node scripts/generate-media-use-audio-carve.mjs -var Z="data-fx-chain",Ne=Z.slice(5),D=1,C=(e="frequency",n="Frequency",t=1e3,a=20,r=2e4)=>({kind:"number",key:e,label:n,unit:"Hz",min:a,max:r,step:1,default:t,scale:"log",automatable:!0}),I=(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}),E=(e=-40,n=40,t=0)=>({kind:"number",key:"gain",label:"Gain",unit:"dB",min:e,max:n,step:.1,default:t,automatable:!0}),L={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:[E(-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:[C("frequency","Frequency",1e3),E(-40,40,0),I(1)],web:"biquad-peaking"},{id:"lowshelf",label:"Low Shelf",group:"filter",description:"Lift or drop everything below the corner frequency.",params:[C("frequency","Frequency",200,20,2e3),E(-40,40,0)],web:"biquad-lowshelf"},{id:"highshelf",label:"High Shelf",group:"filter",description:"Lift or drop everything above the corner frequency.",params:[C("frequency","Frequency",4e3,500,2e4),E(-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:[C("frequency","Cutoff",300,20,2e4),I(.707),L],web:"biquad-highpass"},{id:"lowpass",label:"Low-pass",group:"filter",description:"Remove high frequencies, which darkens or muffles a track.",params:[C("frequency","Cutoff",8e3,100,2e4),I(.707),L],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"}],T=new Map(V.map(e=>[e.id,e]));var He=V.map(e=>e.id);function B(e){let n=T.get(e);if(!n)return{};let t={};for(let a of n.params)t[a.key]=a.default;return t}function U(e,n){let t=T.get(e);if(!t)return{};let a={};for(let r of t.params){let o=n?.[r.key];if(r.kind==="enum"){let i=r.options.some(u=>u.value===o);a[r.key]=i?o:r.default;continue}let s=typeof o=="number"?o:typeof o=="string"&&o.trim()!==""?Number(o):Number.NaN;a[r.key]=Number.isFinite(s)?Math.min(r.max,Math.max(r.min,s)):r.default}return a}var y=class extends Error{constructor(n){super(n),this.name="AudioFxChainError"}};function ee(e){let n;try{n=JSON.parse(e)}catch(r){throw new y(`Chain file is not valid JSON: ${r.message}`)}if(typeof n!="object"||n===null)throw new y("Chain file must be a JSON object.");let t=n;if(t.version!==D)throw new y(`Unsupported chain version: ${String(t.version)}`);if(!Array.isArray(t.nodes))throw new y("Chain file is missing a `nodes` array.");let a=t.nodes.map(ae);return{version:D,nodes:a}}function te(e){return JSON.stringify({version:D,nodes:e.nodes.map(re)})}function ne(e){let n=new Set(e.nodes.map(t=>t.id).filter(Boolean));for(let t=1;;t+=1){let a=`n${t}`;if(!n.has(a))return a}}function ae(e,n){if(typeof e!="object"||e===null)throw new y(`Node ${n} is not an object.`);let t=e;if(typeof t.type!="string"||!T.has(t.type))throw new y(`Node ${n} has unknown effect type: ${String(t.type)}`);return z({type:t.type,id:A(t.id),fromCarve:S(t.fromCarve),fromPreset:A(t.fromPreset),label:A(t.label),fromEq:A(t.fromEq),fromLeveller:S(t.fromLeveller),presetAmount:$(t.presetAmount),enabled:t.enabled!==!1,params:U(t.type,t.params??void 0)})}function re(e){return z({type:e.type,id:A(e.id),fromCarve:S(e.fromCarve),fromPreset:A(e.fromPreset),label:A(e.label),fromEq:A(e.fromEq),fromLeveller:S(e.fromLeveller),presetAmount:e.presetAmount===1?void 0:$(e.presetAmount),enabled:e.enabled===!1?!1:void 0,params:U(e.type,e.params)})}function A(e){return typeof e=="string"&&e?e:void 0}function S(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 n of Object.keys(e))e[n]===void 0&&delete e[n];return e}function O(e,n){let t=e.length;for(let a=1,r=0;a>1;for(;r&o;o>>=1)r^=o;r^=o,a`${ue}${e}${le}`,me=new RegExp(`music|bgm|${M("bed")}|soundtrack|score|${M("song")}|theme|instrumental|track\\d`,"i"),de=new RegExp(`voice|${M("vo")}|${M("vox")}|narrat|speech|dialog|monolog|announce|${M("tts")}|talk|interview|podcast|recap|script`,"i");function fe(...e){let n=e.filter(Boolean).join(" ");return de.test(n)?"voice":se.test(n)?"sfx":me.test(n)?"music":"unknown"}function ce(e,n){let t=a=>typeof a.duration=="number"&&Number.isFinite(a.duration)?a.start+Math.max(0,a.duration):Number.POSITIVE_INFINITY;return e.start({samples:o.samples,at:Math.round(o.offsetSeconds*n)})),a=t.reduce((o,s)=>Math.max(o,s.at+s.samples.length),0);if(a<=0)return new Float32Array(0);let r=new Float32Array(a);for(let{samples:o,at:s}of t){let i=s<0?-s:0;for(let u=i;u=a||(r[l]=(r[l]??0)+(o[u]??0))}}return r}function he(e,n){let t=Math.max(e.length,d),a=e.length>=d?e:(()=>{let c=new Float32Array(d);return c.set(e),c})(),r=new Float32Array(d);for(let c=0;c=a&&e[i]0?o/s:0}var xe=30;function ke(e,n){let t=Math.log2(e/2e3),a=Math.exp(-(t*t)/2);return n*xe*(1-a)}function ge(e,n,t){if(e.length===0)return[];let{freqs:a,power:r}=he(e,n),s=oe.map(u=>{let l=Y(a,r,u);return{center:u,hasEnergy:l>0,scoreDb:l>0?10*Math.log10(l)-ke(u,t.intelligibilityBias):Number.NEGATIVE_INFINITY}}).sort((u,l)=>l.scoreDb-u.scoreDb).slice(0,Math.max(1,t.bands)).filter(u=>u.hasEnergy);if(s.length===0)return[];let i=s[0].scoreDb;return s.map(({center:u,scoreDb:l})=>{let f=Math.pow(10,(l-i)/10),h=Math.min(t.maxCutDb,Math.max(t.maxCutDb/2,t.maxCutDb*f));return{freq:u,gainDb:-Number(h.toFixed(2)),q:t.q}}).sort((u,l)=>u.freq-l.freq)}var K=30,X=.05,ye=.25,Ae=2.4,j=400,_=.2,J=.5;function W(e,n){let t=[{t:0,v:0}],a=0,r=-1;return e.forEach((o,s)=>{s!==e.length-1&&Math.abs(o.v-a)0&&r!==s-1&&t.push(e[s-1]),t.push(o),a=o.v,r=s)}),t}function we(e,n,t){if(e.length===0||t.length===0)return[];let a=new Float32Array(d);for(let m=0;m[]),l=new Float64Array(d),f=new Float64Array(d);for(let m=0;mu[w].push(Y(s,x,p.freq)))}let h=e.length/n,c=1-Math.exp(-(r/n)/X),b=1-Math.exp(-(r/n)/ye);return t.map((m,x)=>{let p=u[x],w=Math.max(...p),g=0,P=[];p.forEach((F,k)=>{let N=F>0&&w>0?Math.max(0,1+10*Math.log10(F/w)/K):0;g+=(N>g?c:b)*(N-g);let H=m.gainDb*g,q=Math.abs(H)<_?0:Number(H.toFixed(1));P.push({t:Number(i[k].toFixed(3)),v:q})});let v=W(P,J);return v.push({t:Number(Math.max(h,v.at(-1).t).toFixed(3)),v:0}),{freq:m.freq,points:v}})}function G(e,n,t){let a=0,r=0;for(let s=n;s0?20*Math.log10(o):Number.NEGATIVE_INFINITY}function ve(e,n,t,a,r){if(e.length===0||a.duckDb<=0)return[];let o=Math.max(d,Math.ceil(e.length/j)),s=Math.round(r*t),i=[],u=[],l=[];for(let k=0;k{let H=u[N]??Number.NEGATIVE_INFINITY,q=k>h&&Number.isFinite(H)?H-(k-a.headroomDb):0,R=Math.min(a.duckDb,Math.max(0,q));m+=(R>m?c:b)*(R-m);let Q=m<_?0:-Number(m.toFixed(1));x.push({t:Number(l[N].toFixed(3)),v:Q})});let p=o/t,w=l.at(-1)??0;for(;m>=_;)m+=b*-m,w+=p,x.push({t:Number(w.toFixed(3)),v:m<_?0:-Number(m.toFixed(1))});let g=W(x,J),P=e.length/t,v=g.at(-1),F=Number(Math.max(P,v.t).toFixed(3));return v.v===0&&v.t>=F||g.push({t:F,v:0}),g}function Fe(e){let n=e.map(t=>({type:"peaking",enabled:!0,params:{...B("peaking"),frequency:t.freq,gain:t.gainDb,q:t.q}}));return{version:D,nodes:n}}export{ge as analyseCarveBands,ve as analyseCarveDuck,we as analyseCarveDynamics,Fe as carveBandsToChain,be as carveProfile,fe as classifyAudioName,ce as clipsOverlap,B as defaultAudioFxParams,ne as mintAudioFxNodeId,pe as mixCarveSources,ee as parseAudioFxChain,te as serializeAudioFxChain}; +// GENERATED: do not hand-edit. Source: packages/core/src/audioCarve.ts and audioFx.ts, and +// 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}; diff --git a/skills/media-use/audio/scripts/lib/media-input.mjs b/skills/media-use/audio/scripts/lib/media-input.mjs new file mode 100644 index 0000000000..8366b8750e --- /dev/null +++ b/skills/media-use/audio/scripts/lib/media-input.mjs @@ -0,0 +1,58 @@ +// media-input.mjs — ffmpeg input that reads one local media file and opens nothing that file names. +import "../../../scripts/lib/windows-exe-search.mjs"; +import { spawnSync } from "node:child_process"; + +// Formats whose file is a list, playlist or script naming other media or programs, which ffmpeg would then +// open. A media input must be the media itself, so these are refused. +const INDIRECT_FORMATS = new Set([ + "hls", + "applehttp", + "concat", + "dash", + "webm_dash_manifest", + "imf", + "sdp", + "rtp", + "rtsp", + "ffmetadata", + "image2", + "avisynth", + "vapoursynth", +]); + +// The demuxer name for src, such as "mp3" or "mov,mp4,m4a,3gp,3g2,mj2"; null when it cannot tell. Some +// Windows installs ship ffmpeg without ffprobe, so ffmpeg's input banner is the fallback. +export function probeFormat(src) { + const r = spawnSync( + "ffprobe", + ["-v", "error", "-protocol_whitelist", "file", "-show_entries", "format=format_name"].concat([ + "-of", + "default=nw=1:nk=1", + "--", + src, + ]), + { encoding: "utf8" }, + ); + if (r.error?.code === "ENOENT") { + const banner = spawnSync("ffmpeg", ["-hide_banner", "-protocol_whitelist", "file", "-i", src], { + encoding: "utf8", + }); + return /^Input #0, (.+?), from /m.exec(banner.stderr ?? "")?.[1] ?? null; + } + const name = r.status === 0 ? String(r.stdout).trim() : ""; + return name || null; +} + +/** True when a probed format is a list, playlist or script that names other files. */ +export const isIndirectFormat = (format) => + format.split(",").some((name) => INDIRECT_FORMATS.has(name)); + +/** ffmpeg input arguments pinned to the probed format and the file protocol: only `src` is opened. */ +export const pinnedInput = (format, src) => [ + "-format_whitelist", + format, + "-protocol_whitelist", + "file", + "-i", + src, +]; diff --git a/skills/media-use/audio/scripts/lib/recording.mjs b/skills/media-use/audio/scripts/lib/recording.mjs index 7470037bde..2eaa8b56b3 100644 --- a/skills/media-use/audio/scripts/lib/recording.mjs +++ b/skills/media-use/audio/scripts/lib/recording.mjs @@ -5,6 +5,7 @@ import { assertLiteralMediaPath } from "../../../scripts/lib/literal-media-input import { spawnSync } from "node:child_process"; import { existsSync, mkdirSync, statSync } from "node:fs"; import { dirname } from "node:path"; +import { isIndirectFormat, pinnedInput, probeFormat } from "./media-input.mjs"; import { projectPath } from "./project-path.mjs"; // ffmpeg's atempo takes 0.5..2 per stage; chain stages for the rest of the 0.1..3 speed range. @@ -32,47 +33,6 @@ export function recordingSource(hyperframesDir, audio) { ); } -// Formats whose file is a list, playlist or script naming other media or programs, which ffmpeg would then -// open. A recording must be the audio itself, so these are refused. -const INDIRECT_FORMATS = new Set([ - "hls", - "applehttp", - "concat", - "dash", - "webm_dash_manifest", - "imf", - "sdp", - "rtp", - "rtsp", - "ffmetadata", - "image2", - "avisynth", - "vapoursynth", -]); - -// The demuxer name for src, such as "mp3" or "mov,mp4,m4a,3gp,3g2,mj2"; null when it cannot tell. Some -// Windows installs ship ffmpeg without ffprobe, so ffmpeg's input banner is the fallback. -function probeFormat(src) { - const r = spawnSync( - "ffprobe", - ["-v", "error", "-protocol_whitelist", "file", "-show_entries", "format=format_name"].concat([ - "-of", - "default=nw=1:nk=1", - "--", - src, - ]), - { encoding: "utf8" }, - ); - if (r.error?.code === "ENOENT") { - const banner = spawnSync("ffmpeg", ["-hide_banner", "-protocol_whitelist", "file", "-i", src], { - encoding: "utf8", - }); - return /^Input #0, (.+?), from /m.exec(banner.stderr ?? "")?.[1] ?? null; - } - const name = r.status === 0 ? String(r.stdout).trim() : ""; - return name || null; -} - /** src -> 44.1k mono wav at wavAbs, played `speed` times faster. Returns { ok, error? }. */ export function stretchToWav(src, wavAbs, speed = 1) { try { @@ -85,7 +45,7 @@ export function stretchToWav(src, wavAbs, speed = 1) { if (!stat.isFile()) return { ok: false, error: `recording is not a file: ${src}` }; const format = probeFormat(src); if (!format) return { ok: false, error: `ffmpeg cannot read ${src} as audio` }; - if (format.split(",").some((name) => INDIRECT_FORMATS.has(name))) { + if (isIndirectFormat(format)) { return { ok: false, error: `${src} is a ${format} list that points at other files; give the audio file itself`, @@ -94,7 +54,7 @@ export function stretchToWav(src, wavAbs, speed = 1) { mkdirSync(dirname(wavAbs), { recursive: true }); const filter = speed === 1 ? [] : ["-af", atempoChain(speed)]; // The probed format pins the input: ffmpeg opens only that one local file, with no nested inputs. - const input = ["-format_whitelist", format, "-protocol_whitelist", "file", "-i", src]; + const input = pinnedInput(format, src); const r = spawnSync( "ffmpeg", ["-y", "-loglevel", "error", ...input, ...filter, "-ar", "44100", "-ac", "1", wavAbs], diff --git a/skills/media-use/references/mixing.md b/skills/media-use/references/mixing.md index 8557eca386..a4d6813377 100644 --- a/skills/media-use/references/mixing.md +++ b/skills/media-use/references/mixing.md @@ -65,7 +65,7 @@ A crossfade is two clips on different tracks that overlap, each with a fade. ## Music under a voice -Duck the bed with a `volume` lane on the music: full level before the voice, down to about 0.3–0.4 while anyone speaks (word timings from `npx hyperframes transcribe` or the voiceover give the times), back up after. Then carve the bed, which dips only the bands the voice uses: `node /audio/scripts/carve.mjs --comp index.html` (needs `ffmpeg`; `--dry-run` to see the plan). It is the same analysis as Studio's carve panel. It reads only double-quoted attributes (JSON quotes as `"`), so write the bed's chain and lanes that way or it overwrites them. Never put a carve on a voice track. +Duck the bed with a `volume` lane on the music: full level before the voice, down to about 0.3–0.4 while anyone speaks (word timings from `npx hyperframes transcribe` or the voiceover give the times), back up after. Then carve the bed, which dips only the bands the voice uses: `node /audio/scripts/carve.mjs --comp index.html` (needs `ffmpeg`; `--dry-run` to see the plan). It is the same analysis as Studio's carve panel. It decodes only media files inside the composition's folder, so copy an outside track into the project first. It reads only double-quoted attributes (JSON quotes as `"`), so write the bed's chain and lanes that way or it overwrites them. Never put a carve on a voice track. ## Group buses