diff --git a/docs/packages/cli.mdx b/docs/packages/cli.mdx index 52888fcc61..c6b9f04e5a 100644 --- a/docs/packages/cli.mdx +++ b/docs/packages/cli.mdx @@ -1084,8 +1084,10 @@ on the API at `HEYGEN_API_URL` when set. API keys are sent as `x-api-key`; OAuth credentials are sent as bearer tokens. If the service refuses a request, analysis falls back with a warning. Without a credential, stems are skipped and `api` is -passed over. At `local`, the default, no credential is looked up and nothing -leaves the machine. +passed over. At `local`, the default, and at `fast`, no credential is looked up +and nothing leaves the machine. Stems saved by an earlier `--quality best` read are +reused at any quality, but only when this install wrote them; stems that arrive +with a project are ignored. Stems are described through HeyGen only at `best`. To use another service, set `HYPERFRAMES_AUDIO_STEMS_URL` or `HYPERFRAMES_AUDIO_API_URL` to its full URL together with diff --git a/packages/cli/src/audio/analysis/decode.ts b/packages/cli/src/audio/analysis/decode.ts index 9e2be5e2e0..d678ddafea 100644 --- a/packages/cli/src/audio/analysis/decode.ts +++ b/packages/cli/src/audio/analysis/decode.ts @@ -80,6 +80,7 @@ export interface DecodeWindow { export interface DecodeFormat { sampleRate?: number; mono?: boolean; + inputArgs?: readonly string[]; } export interface Decoded { @@ -94,7 +95,8 @@ export async function decodeAudio( probed?: AudioStreamInfo, format: DecodeFormat = {}, ): Promise { - const probedInfo = probed ?? (await probeAudio(file)); + const inputArgs = format.inputArgs ?? []; + const probedInfo = probed ?? (await probeAudio(file, inputArgs)); if (!probedInfo) return null; const info = { ...probedInfo, @@ -111,7 +113,7 @@ export async function decodeAudio( "-v", "error", ...inputSeek, - ...mediaInputFormatArgs(ffmpeg, file), + ...literalInputArgs(ffmpeg, file, inputArgs), "-i", file, ...decodedSeek, diff --git a/packages/cli/src/audio/read/describe.ts b/packages/cli/src/audio/read/describe.ts index a7a09cb867..72dbcbf467 100644 --- a/packages/cli/src/audio/read/describe.ts +++ b/packages/cli/src/audio/read/describe.ts @@ -4,7 +4,7 @@ import { mkdtemp, rm } from "node:fs/promises"; import { tmpdir } from "node:os"; import { join } from "node:path"; import type { Span } from "@hyperframes/core/audio-analysis"; -import { findFfBinary, mediaInputFormatArgs } from "@hyperframes/parsers/ff-binaries"; +import { assertLiteralMediaInput, findFfBinary } from "@hyperframes/parsers/ff-binaries"; import { replaceFileAtomically } from "@hyperframes/core/atomic-file"; import { readPlainFile } from "../../utils/projectRecords.js"; import { isPlainFile, makeRealFolder } from "../cacheFolder.js"; @@ -14,6 +14,7 @@ import { serviceFailure, type ServiceAccess, } from "../analysis/providers/shared.js"; +import { SELF_CONTAINED_STEM_INPUT } from "./stems.js"; import type { AudibleStem, Description } from "./types.js"; const MODEL = "gemini-4-argon"; @@ -91,6 +92,11 @@ const isMp3 = (bytes: Buffer) => (bytes[0] === 0x49 && bytes[1] === 0x44 && bytes[2] === 0x33) || (bytes[0] === 0xff && (bytes[1]! & 0xe0) === 0xe0); +function stemInput(path: string): readonly string[] { + assertLiteralMediaInput(path); + return SELF_CONTAINED_STEM_INPUT; +} + async function mp3Of(path: string, scratch: string): Promise { const bytes = readFileSync(path); if (isMp3(bytes)) return bytes; @@ -100,7 +106,7 @@ async function mp3Of(path: string, scratch: string): Promise { await runFile( ffmpeg, [ - ...["-v", "error", "-y", ...mediaInputFormatArgs(ffmpeg, path), "-i", path], + ...["-v", "error", "-y", ...stemInput(path), "-i", path], ...["-vn", "-ac", "2", "-ar", "44100", "-b:a", "160k", out], ], { windowsHide: true, maxBuffer: 8 * 1024 * 1024 }, diff --git a/packages/cli/src/audio/read/read.test.ts b/packages/cli/src/audio/read/read.test.ts index 3f1f7e3f02..792ba039ca 100644 --- a/packages/cli/src/audio/read/read.test.ts +++ b/packages/cli/src/audio/read/read.test.ts @@ -20,9 +20,17 @@ import { findFfBinary } from "@hyperframes/parsers/ff-binaries"; import { readAudio } from "./read.js"; import { formatRead } from "./format.js"; import { READ_VERSION } from "./types.js"; -import { cachedStems, fetchStems } from "./stems.js"; +import { cachedStems, fetchStems, recordStems } from "./stems.js"; const RATE = 22_050; + +/** Marks stems a test wrote by hand as this install's, as a separation would. */ +function ownStems(stemDir: string): void { + recordStems( + stemDir, + readdirSync(stemDir).filter((name) => lstatSync(join(stemDir, name)).isFile()), + ); +} const dir = mkdtempSync(join(tmpdir(), "hf-audio-read-")); afterAll(() => rmSync(dir, { recursive: true, force: true })); @@ -252,6 +260,7 @@ describe.skipIf(!ffmpeg)("readAudio", () => { ...Object.fromEntries(names.map((n) => [n, "silence.wav"])), }), ); + ownStems(stemDir); const { analysis, textPath, jsonPath } = await readAudio(path, "room.wav", { cacheDir, quality: "best", @@ -306,6 +315,7 @@ describe.skipIf(!ffmpeg)("readAudio", () => { ...Object.fromEntries(["vocals", "bass", "guitar", "piano"].map((n) => [n, "silence.wav"])), }), ); + ownStems(stemDir); const { analysis, textPath } = await readAudio(path, "effect-in-room.wav", { cacheDir }); expect(analysis.ambience).toHaveLength(1); expect(analysis.effects!.events).toHaveLength(1); @@ -344,6 +354,7 @@ describe.skipIf(!ffmpeg)("readAudio", () => { ), }), ); + ownStems(stemDir); const { analysis } = await readAudio(path, file, { cacheDir }); expect(analysis.music!.segments.length).toBeGreaterThan(0); expect(analysis.effects!.events).toEqual([]); @@ -460,6 +471,7 @@ describe.skipIf(!ffmpeg)("readAudio", () => { names[stem] = `${stem}.audio`; } writeFileSync(join(stemDir, "stems.json"), JSON.stringify(names)); + ownStems(stemDir); writeFileSync( `${path}.transcript.json`, JSON.stringify({ @@ -679,6 +691,7 @@ describe.skipIf(!ffmpeg || process.platform === "win32")("readAudio cache links" join(stemDir, "stems.json"), JSON.stringify({ ...names, guitar: "bed.wav", piano: "bed.wav", other: "bed.wav" }), ); + ownStems(stemDir); symlinkSync(victim, join(stemDir, `no-vocals.wav.${process.pid}.tmp.wav`)); const { analysis } = await readAudio(path, "mix-links.wav", { cacheDir, quality: "fast" }); expect(analysis.voiceFreeMix).toMatch(/no-vocals\.wav$/); diff --git a/packages/cli/src/audio/read/read.ts b/packages/cli/src/audio/read/read.ts index 59b9c4e494..8ffc22e392 100644 --- a/packages/cli/src/audio/read/read.ts +++ b/packages/cli/src/audio/read/read.ts @@ -1,7 +1,7 @@ import { createHash } from "node:crypto"; import { createReadStream, existsSync, readFileSync, renameSync, rmSync } from "node:fs"; import { basename, dirname, extname, join, relative } from "node:path"; -import { findFfBinary } from "@hyperframes/parsers/ff-binaries"; +import { assertLiteralMediaInput, findFfBinary } from "@hyperframes/parsers/ff-binaries"; import { createStagingDir, replaceFileAtomically } from "@hyperframes/core/atomic-file"; import { loudness, type AnalysisQuality, type Span } from "@hyperframes/core/audio-analysis"; import { loadTranscript } from "../../whisper/normalize.js"; @@ -23,7 +23,14 @@ import { round, spanDb, } from "./signal.js"; -import { DRUM_STEM, VOICE_STEM, cachedStems, fetchStems, stemsAccess } from "./stems.js"; +import { + DRUM_STEM, + SELF_CONTAINED_STEM_INPUT, + VOICE_STEM, + cachedStems, + fetchStems, + stemsAccess, +} from "./stems.js"; import { READ_VERSION, type AudibleStem, @@ -144,7 +151,10 @@ async function mixedFile(paths: string[], out: string, warnings: string[]) { ffmpeg, [ ...["-v", "error", "-y"], - ...paths.flatMap((path) => ["-i", path]), + ...paths.flatMap((path) => { + assertLiteralMediaInput(path); + return [...SELF_CONTAINED_STEM_INPUT, "-i", path]; + }), ...["-filter_complex", `amix=inputs=${paths.length}:normalize=0`], ...["-c:a", "pcm_f32le", temporary], ], @@ -179,8 +189,11 @@ function tempoOf(music: Music | null): number | null { async function decodedStems(stemPaths: Record) { const pitched: Record = {}; for (const [name, stemPath] of Object.entries(stemPaths)) - if (name !== VOICE_STEM && name !== DRUM_STEM) pitched[name] = await decodeMono(stemPath); - const drums = stemPaths[DRUM_STEM] ? await decodeMono(stemPaths[DRUM_STEM]) : null; + if (name !== VOICE_STEM && name !== DRUM_STEM) + pitched[name] = await decodeMono(stemPath, READ_RATE, SELF_CONTAINED_STEM_INPUT); + const drums = stemPaths[DRUM_STEM] + ? await decodeMono(stemPaths[DRUM_STEM], READ_RATE, SELF_CONTAINED_STEM_INPUT) + : null; return { pitched, drums }; } @@ -330,7 +343,13 @@ async function described( voiceFreeMix: mix && relative(project, mix), warnings, }; - if (quality === "fast") return located; + if (quality !== "best") { + if (quality === "local") + warnings.push( + "stems not described: quality local keeps audio on this machine; --quality best describes them through HeyGen", + ); + return located; + } const { stems, description } = await describeStems( stemPaths, { @@ -345,6 +364,11 @@ async function described( return { ...located, stems, description }; } +const voiceSource = (path: string, stemPaths: Record | null) => + stemPaths + ? { path: stemPaths[VOICE_STEM] ?? path, input: SELF_CONTAINED_STEM_INPUT } + : { path, input: [] as readonly string[] }; + async function analyze( path: string, file: string, @@ -357,8 +381,8 @@ async function analyze( const warnings: string[] = []; const stemPaths = await stemsFor(path, stemDir, quality, warnings); const words = transcript ? wordsOf(transcript) : []; - const voicePath = stemPaths?.[VOICE_STEM] ?? path; - const voiceSamples = await decodeMono(voicePath); + const voiceFile = voiceSource(path, stemPaths); + const voiceSamples = await decodeMono(voiceFile.path, READ_RATE, voiceFile.input); const about = base(file, sha, round(voiceSamples.length / READ_RATE, 3), stemPaths, transcript); if (!stemPaths && !words.length) { warnings.push( @@ -368,7 +392,7 @@ async function analyze( } if (!words.length) warnings.push(`no transcript: voice lines carry no words; ${transcribeHint(file)}`); - const pitch = pitchTrack(await decodeMono(voicePath, PITCH_RATE)); + const pitch = pitchTrack(await decodeMono(voiceFile.path, PITCH_RATE, voiceFile.input)); const mix = await recording(path, stemPaths !== null, voiceSamples); const levelOf = (span: Span) => spanDb(mix, READ_RATE, span.start, span.end); const voice = words.length diff --git a/packages/cli/src/audio/read/signal.ts b/packages/cli/src/audio/read/signal.ts index 19d79be78f..0131dbf330 100644 --- a/packages/cli/src/audio/read/signal.ts +++ b/packages/cli/src/audio/read/signal.ts @@ -7,8 +7,12 @@ export { PITCH_RATE }; const SILENT_DB = -120; export const ABSENT_DB = -55; -export async function decodeMono(path: string, sampleRate = READ_RATE): Promise { - const decoded = await decodeAudio(path, {}, undefined, { sampleRate, mono: true }); +export async function decodeMono( + path: string, + sampleRate = READ_RATE, + inputArgs: readonly string[] = [], +): Promise { + const decoded = await decodeAudio(path, {}, undefined, { sampleRate, mono: true, inputArgs }); if (!decoded) throw new Error(`${path} has no audio stream`); const samples = decoded.signal.channels[0]!; if (samples.some((sample) => !Number.isFinite(sample))) diff --git a/packages/cli/src/audio/read/stems.ts b/packages/cli/src/audio/read/stems.ts index 2ea6001f39..d24b8deaf1 100644 --- a/packages/cli/src/audio/read/stems.ts +++ b/packages/cli/src/audio/read/stems.ts @@ -1,8 +1,8 @@ -import { randomUUID } from "node:crypto"; -import { statSync } from "node:fs"; +import { createHash, randomUUID } from "node:crypto"; +import { lstatSync, mkdirSync, readFileSync, realpathSync, statSync, writeFileSync } from "node:fs"; import { mkdtemp, rm } from "node:fs/promises"; import { tmpdir } from "node:os"; -import { join } from "node:path"; +import { dirname, join } from "node:path"; import { findFfBinary, mediaInputFormatArgs } from "@hyperframes/parsers/ff-binaries"; import { replaceFileAtomically } from "@hyperframes/core/atomic-file"; import { setTimeout as sleep } from "node:timers/promises"; @@ -16,6 +16,7 @@ import { type ServiceAccess, } from "../analysis/providers/shared.js"; import { probeAudio } from "../analysis/decode.js"; +import { hyperframesConfigDir } from "../../utils/configDir.js"; import { readPlainFile } from "../../utils/projectRecords.js"; import { isPlainFile, isPlainName, isRealFolder, makeRealFolder } from "../cacheFolder.js"; @@ -45,6 +46,51 @@ const STEM_NAMES = ["vocals", "drums", "bass", "guitar", "piano", "other"] as co export const VOICE_STEM = "vocals"; export const DRUM_STEM = "drums"; +export const SELF_CONTAINED_STEM_INPUT = [ + "-protocol_whitelist", + "file", + "-format_whitelist", + "wav,w64,mp3,flac,ogg,aiff,caf,aac,mov,matroska", +] as const; + +const recordOutsideProject = (dir: string) => + hyperframesConfigDir( + "read-audio-stems", + `${createHash("sha256").update(realpathSync(dir)).digest("hex").slice(0, 32)}.json`, + ); + +function identity(path: string): string | null { + const found = lstatSync(path, { bigint: true, throwIfNoEntry: false }); + return found?.isFile() ? `${found.dev}:${found.ino}:${found.size}:${found.mtimeNs}` : null; +} + +export function recordStems(dir: string, files: readonly string[]): void { + try { + const record = recordOutsideProject(dir); + mkdirSync(dirname(record), { recursive: true, mode: 0o700 }); + const ids = Object.fromEntries(files.map((file) => [file, identity(join(dir, file))])); + writeFileSync(record, JSON.stringify(ids), { mode: 0o600 }); + } catch { + // expected: a read-only config folder only means the stems are separated again next time + } +} + +function writtenHere(dir: string, files: readonly string[]): boolean { + let recorded: Record; + try { + recorded = JSON.parse(readFileSync(recordOutsideProject(dir), "utf8")) as Record< + string, + unknown + >; + } catch { + return false; + } + return files.every((file) => { + const id = identity(join(dir, file)); + return id !== null && recorded[file] === id; + }); +} + /** How to reach the stems service, or why it cannot be reached. */ export const stemsAccess = () => serviceAccess( @@ -67,14 +113,13 @@ function namedStems(text: string): Record | null { : null; } -/** Stems already fetched into `dir`, by name; null when there are none yet or a link stands in for any of it. */ +/** Stems this install fetched into `dir`, by name; null when none, or when no record outside the project shows this install wrote them (a project can ship its own). */ export function cachedStems(dir: string): Record | null { const done = join(dir, DONE); - if (!isRealFolder(dir, 2) || !isPlainFile(done)) return null; + if (!isRealFolder(dir, 2) || !isPlainFile(done) || !writtenHere(dir, [DONE])) return null; const names = namedStems(readPlainFile(done, MAX_DONE_BYTES)); - if (!names) return null; - const paths = Object.fromEntries(STEM_NAMES.map((name) => [name, join(dir, names[name]!)])); - return Object.values(paths).every(isPlainFile) ? paths : null; + if (!names || !writtenHere(dir, Object.values(names))) return null; + return Object.fromEntries(STEM_NAMES.map((name) => [name, join(dir, names[name]!)])); } class StillRunning extends Error {} @@ -194,7 +239,8 @@ export async function fetchStems( names[name] = file; } replaceFileAtomically(join(dir, DONE), JSON.stringify(names)); - return cachedStems(dir)!; + recordStems(dir, [DONE, ...Object.values(names)]); + return Object.fromEntries(STEM_NAMES.map((name) => [name, join(dir, names[name]!)])); } finally { await rm(scratch, { recursive: true, force: true }); } diff --git a/packages/cli/src/audio/read/stemsProof.test.ts b/packages/cli/src/audio/read/stemsProof.test.ts new file mode 100644 index 0000000000..67b01b5ffd --- /dev/null +++ b/packages/cli/src/audio/read/stemsProof.test.ts @@ -0,0 +1,120 @@ +import { createHash } from "node:crypto"; +import { existsSync, mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs"; +import { tmpdir } from "node:os"; +import { join } from "node:path"; +import { afterAll, afterEach, describe, expect, it, vi } from "vitest"; +import { findFfBinary } from "@hyperframes/parsers/ff-binaries"; + +const { describeAccess } = vi.hoisted(() => ({ describeAccess: vi.fn() })); +vi.mock("./describe.js", async (original) => ({ + ...(await original()), + describeAccess, +})); + +import { readAudio } from "./read.js"; +import { cachedStems, recordStems } from "./stems.js"; + +const RATE = 22_050; +const dir = mkdtempSync(join(tmpdir(), "hf-audio-stems-proof-")); +afterAll(() => rmSync(dir, { recursive: true, force: true })); +afterEach(() => { + vi.unstubAllEnvs(); + vi.restoreAllMocks(); + describeAccess.mockReset(); +}); + +function wav(path: string, seconds: number, fill: (t: number) => number): string { + const frames = Math.round(seconds * RATE); + const data = Buffer.alloc(frames * 2); + for (let i = 0; i < frames; i++) data.writeInt16LE(Math.round(fill(i / RATE) * 32767), i * 2); + const header = Buffer.alloc(44); + header.write("RIFF", 0); + header.writeUInt32LE(36 + data.length, 4); + header.write("WAVEfmt ", 8); + header.writeUInt32LE(16, 16); + header.writeUInt16LE(1, 20); + header.writeUInt16LE(1, 22); + header.writeUInt32LE(RATE, 24); + header.writeUInt32LE(RATE * 2, 28); + header.writeUInt16LE(2, 32); + header.writeUInt16LE(16, 34); + header.write("data", 36); + header.writeUInt32LE(data.length, 40); + writeFileSync(path, Buffer.concat([header, data])); + return path; +} + +const voiced = (t: number) => (t >= 0.5 && t < 2.5 ? 0.3 * Math.sin(2 * Math.PI * 180 * t) : 0); +const hum = (t: number) => 0.08 * Math.sin(2 * Math.PI * 261.63 * t); +const STEMS = ["vocals", "drums", "bass", "guitar", "piano", "other"]; + +/** A project holding a recording and a well-formed stems folder for it, as one could arrive with the project. */ +function projectWithStems(name: string, stemFile: (stemDir: string) => string = () => "bed.wav") { + const project = join(dir, name); + const cacheDir = join(project, ".hyperframes", "read-audio"); + const path = wav(join(dir, `${name}.wav`), 3, (t) => voiced(t) + hum(t)); + const sha = createHash("sha256").update(readFileSync(path)).digest("hex"); + const stemDir = join(cacheDir, "stems", sha.slice(0, 12)); + mkdirSync(stemDir, { recursive: true }); + wav(join(stemDir, "vocals.wav"), 3, voiced); + wav(join(stemDir, "bed.wav"), 3, hum); + const other = stemFile(stemDir); + const names = Object.fromEntries( + STEMS.map((stem) => [ + stem, + stem === "vocals" ? "vocals.wav" : stem === "other" ? other : "bed.wav", + ]), + ); + writeFileSync(join(stemDir, "stems.json"), JSON.stringify(names)); + const own = () => recordStems(stemDir, ["stems.json", ...new Set(Object.values(names))]); + return { path, cacheDir, stemDir, own }; +} + +describe.skipIf(!findFfBinary("ffmpeg") || !findFfBinary("ffprobe"))("audio --read stems", () => { + it("ignores a stems folder that arrived with the project, and reads it once this install wrote it", async () => { + const { path, cacheDir, stemDir, own } = projectWithStems("planted"); + expect(cachedStems(stemDir)).toBeNull(); + const { analysis } = await readAudio(path, "planted.wav", { cacheDir }); + expect(analysis.separation).toBe("mix"); + expect(analysis.warnings[0]).toContain("not separated into stems"); + own(); + expect(Object.keys(cachedStems(stemDir) ?? {})).toEqual(STEMS); + writeFileSync(join(stemDir, "bed.wav"), readFileSync(join(stemDir, "vocals.wav"))); + expect(cachedStems(stemDir)).toBeNull(); + }); + + it.each(["local", "fast"] as const)( + "at %s quality, reads its own stems with no request and no credential", + async (quality) => { + vi.stubEnv("HEYGEN_API_KEY", "test-key"); + const fetch = vi.spyOn(globalThis, "fetch"); + const { path, cacheDir, own } = projectWithStems(`own-${quality}`); + own(); + const { analysis } = await readAudio(path, `own-${quality}.wav`, { cacheDir, quality }); + expect(analysis.separation).not.toBe("mix"); + expect(analysis.description ?? null).toBeNull(); + expect(fetch).not.toHaveBeenCalled(); + expect(describeAccess).not.toHaveBeenCalled(); + }, + ); + + it("refuses a stem that is a playlist before it is decoded, mixed or sent", async () => { + vi.stubEnv("HEYGEN_API_KEY", "test-key"); + const fetch = vi.spyOn(globalThis, "fetch"); + const outside = wav(join(dir, "outside.wav"), 3, hum); + const { path, cacheDir, stemDir, own } = projectWithStems("playlist", (stemDir) => { + writeFileSync( + join(stemDir, "other.m3u8"), + `#EXTM3U\n#EXT-X-TARGETDURATION:3\n#EXTINF:3,\n${outside}\n#EXT-X-ENDLIST\n`, + ); + return "other.m3u8"; + }); + own(); + await expect(readAudio(path, "playlist.wav", { cacheDir, quality: "best" })).rejects.toThrow( + /whitelist/, + ); + expect(existsSync(join(stemDir, "no-vocals.wav"))).toBe(false); + expect(fetch).not.toHaveBeenCalled(); + expect(describeAccess).not.toHaveBeenCalled(); + }); +});