From bed9d9929dab92a6e085ba329c1645e4c1b8be16 Mon Sep 17 00:00:00 2001 From: Miguel Angel Simon Sierra Date: Sun, 25 Oct 2026 19:19:29 -0400 Subject: [PATCH 1/3] fix(cli): media-treatment and normalize-audio find clips inside mounted scenes --- .../cli/src/commands/media-treatment.test.ts | 34 ++++++++++++ packages/cli/src/commands/media-treatment.ts | 29 +++++++++-- .../commands/normalize-audio.command.test.ts | 35 ++++++++++++- packages/cli/src/commands/normalize-audio.ts | 52 ++++++++++++------- packages/cli/src/utils/mountedCompositions.ts | 22 ++++++++ 5 files changed, 148 insertions(+), 24 deletions(-) create mode 100644 packages/cli/src/utils/mountedCompositions.ts diff --git a/packages/cli/src/commands/media-treatment.test.ts b/packages/cli/src/commands/media-treatment.test.ts index ec3aef7ccbe..d5e62b20f7d 100644 --- a/packages/cli/src/commands/media-treatment.test.ts +++ b/packages/cli/src/commands/media-treatment.test.ts @@ -662,6 +662,40 @@ describe("applyMediaTreatmentToHtml", () => { } }); + it("finds a clip inside a mounted scene and edits it in its own file", async () => { + const project = mkdtempSync(join(tmpdir(), "hf-media-scene-")); + const log = vi.spyOn(console, "log").mockImplementation(() => undefined); + const root = `
`; + mkdirSync(join(project, "compositions")); + writeFileSync(join(project, "index.html"), root); + writeFileSync(join(project, "compositions", "intro.html"), VIDEO); + try { + await runCommand(mediaTreatmentCommand, { + rawArgs: [ + "--project", + project, + "--selector", + "#hero", + "--grading", + '{"preset":"warm-daylight"}', + "--apply", + "--json", + ], + }); + expect(JSON.parse(String(log.mock.calls.at(-1)?.[0]))).toMatchObject({ + ok: true, + file: "compositions/intro.html", + }); + expect( + gradingsOf(readFileSync(join(project, "compositions", "intro.html"), "utf8")), + ).not.toEqual([null]); + expect(readFileSync(join(project, "index.html"), "utf8")).toBe(root); + } finally { + log.mockRestore(); + rmSync(project, { recursive: true, force: true }); + } + }); + it("reports how many elements an --apply treated", async () => { const project = mkdtempSync(join(tmpdir(), "hf-media-all-")); const log = vi.spyOn(console, "log").mockImplementation(() => undefined); diff --git a/packages/cli/src/commands/media-treatment.ts b/packages/cli/src/commands/media-treatment.ts index 2af21733e22..2d1e249b616 100644 --- a/packages/cli/src/commands/media-treatment.ts +++ b/packages/cli/src/commands/media-treatment.ts @@ -32,6 +32,7 @@ import { c } from "../ui/colors.js"; import { failCommand } from "../utils/commandResult.js"; import { normalizeErrorMessage } from "../utils/errorMessage.js"; import { readOptionalString } from "../utils/pathArgs.js"; +import { projectCompositionFiles } from "../utils/mountedCompositions.js"; import { resolveProject } from "../utils/project.js"; import { withMeta } from "../utils/updateCheck.js"; import { analyzeMediaTreatment } from "./media-treatment-analysis.js"; @@ -625,9 +626,29 @@ function runCapabilityQuery(args: MediaTreatmentCommandArgs): void { console.log(JSON.stringify(withMeta({ ok: true, capabilities }), null, 2)); } -function resolveMutationFile(args: MediaTreatmentCommandArgs) { +/** Without --file, the one project file that declares an element matching `selector`: index.html or a mounted scene. */ +function fileDeclaringSelector(projectDir: string, selector: string): string { + const declaring = projectCompositionFiles(projectDir).filter((file) => { + try { + const document = parseSourceDocument(readFileSync(resolve(projectDir, file), "utf8")); + return queryIncludingTemplates(document, selector).length > 0; + } catch { + return false; + } + }); + if (declaring.length > 1) { + throw new Error( + `Selector matches clips in ${declaring.join(", ")}; pass --file to pick one: ${selector}`, + ); + } + return declaring[0] ?? "index.html"; +} + +function resolveMutationFile(args: MediaTreatmentCommandArgs, selector: string | undefined) { const project = resolveProject(readOptionalString(args.project)); - const fileArg = readOptionalString(args.file) ?? "index.html"; + const fileArg = + readOptionalString(args.file) ?? + (selector ? fileDeclaringSelector(project.dir, selector) : "index.html"); const filePath = resolve(project.dir, fileArg); if (!isPathInside(filePath, project.dir) || !filePath.toLowerCase().endsWith(".html")) { throw new Error("--file must be an HTML file inside the project"); @@ -637,8 +658,8 @@ function resolveMutationFile(args: MediaTreatmentCommandArgs) { } function analyzeTarget(args: MediaTreatmentCommandArgs) { - const { project, filePath } = resolveMutationFile(args); const selector = readOptionalString(args.selector); + const { project, filePath } = resolveMutationFile(args, selector); if (!selector) throw new Error("--selector is required"); if ( readOptionalString(args.grading) || @@ -670,8 +691,8 @@ function analyzeTarget(args: MediaTreatmentCommandArgs) { } async function prepareMutation(args: MediaTreatmentCommandArgs) { - const { project, filePath } = resolveMutationFile(args); const selector = readOptionalString(args.selector); + const { project, filePath } = resolveMutationFile(args, selector); if (!selector) throw new Error("--selector is required"); const clear = args.clear === true; const apply = args.apply === true; diff --git a/packages/cli/src/commands/normalize-audio.command.test.ts b/packages/cli/src/commands/normalize-audio.command.test.ts index 3b5a6c1e085..7931131ac19 100644 --- a/packages/cli/src/commands/normalize-audio.command.test.ts +++ b/packages/cli/src/commands/normalize-audio.command.test.ts @@ -1,4 +1,4 @@ -import { mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs"; +import { mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs"; import { tmpdir } from "node:os"; import { join } from "node:path"; import { runCommand } from "citty"; @@ -69,3 +69,36 @@ describe("absolute normalize-audio command", () => { } }); }); + +describe("normalize-audio on a clip inside a mounted scene", () => { + it("measures it and writes the gain into the scene file", async () => { + const dir = mkdtempSync(join(tmpdir(), "hf-normalize-scene-test-")); + const log = vi.spyOn(console, "log").mockImplementation(() => {}); + try { + const root = `
`; + const scene = ``; + mkdirSync(join(dir, "compositions")); + writeFileSync(join(dir, "index.html"), root); + writeFileSync(join(dir, "compositions", "intro.html"), scene); + writeFileSync(join(dir, "voice.wav"), "audio bytes"); + measureAudio.mockResolvedValue({ integratedLufs: -16, truePeakDbfs: -12.3 }); + + await runCommand(normalizeAudioCommand, { + rawArgs: [dir, "--target", "voice", "--json", "--write"], + }); + + expect(JSON.parse(String(log.mock.calls.at(-1)?.[0]))).toMatchObject({ + ok: true, + targetId: "voice", + wrote: true, + }); + expect(readFileSync(join(dir, "index.html"), "utf8")).toBe(root); + expect(readFileSync(join(dir, "compositions", "intro.html"), "utf8")).toBe( + scene.replace('data-volume="0"', 'data-volume="1"'), + ); + } finally { + log.mockRestore(); + rmSync(dir, { recursive: true, force: true }); + } + }); +}); diff --git a/packages/cli/src/commands/normalize-audio.ts b/packages/cli/src/commands/normalize-audio.ts index ad5f725b853..54451c0b1cc 100644 --- a/packages/cli/src/commands/normalize-audio.ts +++ b/packages/cli/src/commands/normalize-audio.ts @@ -1,5 +1,5 @@ import { existsSync, readFileSync, renameSync, writeFileSync } from "node:fs"; -import { relative } from "node:path"; +import { relative, resolve } from "node:path"; import { absoluteLoudnessPlan, audioNormalizationPlan, @@ -16,6 +16,7 @@ import { } from "@hyperframes/studio-server/loudness"; import { defineCommand } from "citty"; import { c } from "../ui/colors.js"; +import { projectCompositionFiles } from "../utils/mountedCompositions.js"; import { resolveProject } from "../utils/project.js"; import { failCommand } from "../utils/commandResult.js"; import type { Example } from "./_examples.js"; @@ -37,11 +38,23 @@ function fail(message: string, json: boolean, cause?: unknown): never { failCommand(1, cause); } -function byId(tags: readonly AudioTag[], rawId: string, role: string): AudioTag { +/** An audio tag with the project file that declares it. */ +type ProjectAudioTag = AudioTag & { file: string }; + +function projectAudioTags(projectDir: string): ProjectAudioTag[] { + return projectCompositionFiles(projectDir).flatMap((file) => + audioTags(readFileSync(resolve(projectDir, file), "utf8")).map((tag) => ({ ...tag, file })), + ); +} + +function byId(tags: readonly ProjectAudioTag[], rawId: string, role: string): ProjectAudioTag { const id = rawId.trim().replace(/^#/, ""); - const tag = tags.find((candidate) => candidate.id === id); - if (!tag) throw new Error(`${role} audio #${id} was not found`); - return tag; + const matches = tags.filter((candidate) => candidate.id === id); + if (matches.length > 1) { + throw new Error(`${role} audio #${id} is declared in ${matches.map((m) => m.file).join(", ")}`); + } + if (!matches[0]) throw new Error(`${role} audio #${id} was not found`); + return matches[0]; } interface NormalizeAudioOptions { @@ -58,13 +71,13 @@ interface WriteOutcome { wrote: boolean; withinTolerance: boolean; tolerance: number; - indexPath: string; + /** The project file that declares the target audio, and the one `--write` changed. */ + filePath: string; } type NormalizeAudioResult = WriteOutcome & ModePlan; -function selectedTags(html: string, referenceId: string, targetId: string) { - const tags = audioTags(html); +function selectedTags(tags: readonly ProjectAudioTag[], referenceId: string, targetId: string) { const referenceTag = byId(tags, referenceId, "Reference"); const targetTag = byId(tags, targetId, "Target"); if (referenceTag.id === targetTag.id) { @@ -141,17 +154,17 @@ type ModePlan = async function plannedNormalization( projectDir: string, - html: string, + tags: readonly ProjectAudioTag[], options: NormalizeAudioOptions, tolerance: number, -): Promise<{ targetTag: AudioTag; withinTolerance: boolean; plan: ModePlan }> { +): Promise<{ targetTag: ProjectAudioTag; withinTolerance: boolean; plan: ModePlan }> { if (options.reference === undefined) { - const targetTag = byId(audioTags(html), options.target, "Target"); + const targetTag = byId(tags, options.target, "Target"); const plan = await measuredAbsolutePlan(projectDir, targetTag, parsedLufs(options.lufs)); const withinTolerance = targetTag.volume > 0 && Math.abs(plan.changeDb) <= tolerance; return { targetTag, withinTolerance, plan: { mode: "absolute", ...plan } }; } - const { referenceTag, targetTag } = selectedTags(html, options.reference, options.target); + const { referenceTag, targetTag } = selectedTags(tags, options.reference, options.target); const plan = await measuredPlan(projectDir, referenceTag, targetTag); const withinTolerance = Math.abs(plan.referenceLufs - plan.targetLufs) <= tolerance; return { targetTag, withinTolerance, plan: { mode: "reference", ...plan } }; @@ -159,22 +172,23 @@ async function plannedNormalization( async function normalizeAudio(options: NormalizeAudioOptions): Promise { const project = resolveProject(options.dir); - const html = readFileSync(project.indexPath, "utf8"); + const tags = projectAudioTags(project.dir); const tolerance = parsedTolerance(options.tolerance); const { targetTag, withinTolerance, plan } = await plannedNormalization( project.dir, - html, + tags, options, tolerance, ); + const filePath = resolve(project.dir, targetTag.file); const wrote = options.write && !withinTolerance; if (wrote) { writeAtomically( - project.indexPath, - updateAudioVolume(readFileSync(project.indexPath, "utf8"), targetTag.id, plan.volume), + filePath, + updateAudioVolume(readFileSync(filePath, "utf8"), targetTag.id, plan.volume), ); } - return { ok: true, wrote, withinTolerance, tolerance, indexPath: project.indexPath, ...plan }; + return { ok: true, wrote, withinTolerance, tolerance, filePath, ...plan }; } const LIMIT_TEXT: Record = { @@ -212,7 +226,7 @@ function printHumanResult(result: NormalizeAudioResult): void { ); console.log( result.wrote - ? c.success(`Updated ${relative(process.cwd(), result.indexPath) || "index.html"}.`) + ? c.success(`Updated ${relative(process.cwd(), result.filePath) || "index.html"}.`) : c.dim("Dry run only. Pass --write to persist this gain."), ); } @@ -279,7 +293,7 @@ export default defineCommand({ write: args.write, }); if (args.json) { - const { indexPath: _, ...jsonResult } = result; + const { filePath: _, ...jsonResult } = result; console.log(JSON.stringify(jsonResult, null, 2)); return; } diff --git a/packages/cli/src/utils/mountedCompositions.ts b/packages/cli/src/utils/mountedCompositions.ts new file mode 100644 index 00000000000..1dcc081ccef --- /dev/null +++ b/packages/cli/src/utils/mountedCompositions.ts @@ -0,0 +1,22 @@ +import { existsSync, readFileSync } from "node:fs"; +import { relative, resolve } from "node:path"; +import { parseHTML } from "linkedom"; +import { isPathInside } from "@hyperframes/core"; + +/** The entry file plus every sub-composition file it mounts, nested ones included, as project-relative paths. */ +export function projectCompositionFiles(projectDir: string, entry = "index.html"): string[] { + const files: string[] = []; + const visit = (file: string): void => { + if (files.includes(file)) return; + const path = resolve(projectDir, file); + if (!isPathInside(path, projectDir) || !existsSync(path)) return; + files.push(file); + const { document } = parseHTML(readFileSync(path, "utf8")); + for (const host of document.querySelectorAll("[data-composition-src]")) { + const src = host.getAttribute("data-composition-src"); + if (src) visit(relative(projectDir, resolve(projectDir, src)).split("\\").join("/")); + } + }; + visit(entry); + return files; +} From 0284ebd77678aecf9170e349eed96fe93024e0eb Mon Sep 17 00:00:00 2001 From: Miguel Angel Simon Sierra Date: Sun, 25 Oct 2026 20:13:10 -0400 Subject: [PATCH 2/3] fix(cli): report the scene file with forward slashes and drop added comments --- packages/cli/src/commands/media-treatment.ts | 3 +-- packages/cli/src/commands/normalize-audio.ts | 2 -- 2 files changed, 1 insertion(+), 4 deletions(-) diff --git a/packages/cli/src/commands/media-treatment.ts b/packages/cli/src/commands/media-treatment.ts index 2d1e249b616..09b5f1747ea 100644 --- a/packages/cli/src/commands/media-treatment.ts +++ b/packages/cli/src/commands/media-treatment.ts @@ -626,7 +626,6 @@ function runCapabilityQuery(args: MediaTreatmentCommandArgs): void { console.log(JSON.stringify(withMeta({ ok: true, capabilities }), null, 2)); } -/** Without --file, the one project file that declares an element matching `selector`: index.html or a mounted scene. */ function fileDeclaringSelector(projectDir: string, selector: string): string { const declaring = projectCompositionFiles(projectDir).filter((file) => { try { @@ -719,7 +718,7 @@ async function prepareMutation(args: MediaTreatmentCommandArgs) { payload: { ok: true, action, - file: relative(project.dir, filePath) || "index.html", + file: relative(project.dir, filePath).split("\\").join("/") || "index.html", selector, count: result.targets.length, ...(result.targets.length === 1 diff --git a/packages/cli/src/commands/normalize-audio.ts b/packages/cli/src/commands/normalize-audio.ts index 54451c0b1cc..250e9717209 100644 --- a/packages/cli/src/commands/normalize-audio.ts +++ b/packages/cli/src/commands/normalize-audio.ts @@ -38,7 +38,6 @@ function fail(message: string, json: boolean, cause?: unknown): never { failCommand(1, cause); } -/** An audio tag with the project file that declares it. */ type ProjectAudioTag = AudioTag & { file: string }; function projectAudioTags(projectDir: string): ProjectAudioTag[] { @@ -71,7 +70,6 @@ interface WriteOutcome { wrote: boolean; withinTolerance: boolean; tolerance: number; - /** The project file that declares the target audio, and the one `--write` changed. */ filePath: string; } From 07e1b8a19650beae9e4fe7b85bee03bccdbd69fb Mon Sep 17 00:00:00 2001 From: Miguel Angel Simon Sierra Date: Sun, 25 Oct 2026 21:33:24 -0400 Subject: [PATCH 3/3] fix(cli): normalize-audio reads a scene's audio relative to the scene file --- .../commands/normalize-audio.command.test.ts | 24 +++++++++++++++++++ packages/cli/src/commands/normalize-audio.ts | 13 ++++++---- 2 files changed, 32 insertions(+), 5 deletions(-) diff --git a/packages/cli/src/commands/normalize-audio.command.test.ts b/packages/cli/src/commands/normalize-audio.command.test.ts index 7931131ac19..11aad4b70a4 100644 --- a/packages/cli/src/commands/normalize-audio.command.test.ts +++ b/packages/cli/src/commands/normalize-audio.command.test.ts @@ -101,4 +101,28 @@ describe("normalize-audio on a clip inside a mounted scene", () => { rmSync(dir, { recursive: true, force: true }); } }); + + it("resolves the scene's audio source against the scene file, not the project root", async () => { + const dir = mkdtempSync(join(tmpdir(), "hf-normalize-scene-src-test-")); + const log = vi.spyOn(console, "log").mockImplementation(() => {}); + try { + const root = `
`; + const scene = ``; + mkdirSync(join(dir, "compositions")); + mkdirSync(join(dir, "assets")); + writeFileSync(join(dir, "index.html"), root); + writeFileSync(join(dir, "compositions", "intro.html"), scene); + writeFileSync(join(dir, "assets", "voice.wav"), "audio bytes"); + measureAudio.mockClear(); + measureAudio.mockResolvedValue({ integratedLufs: -16, truePeakDbfs: -12.3 }); + + await runCommand(normalizeAudioCommand, { rawArgs: [dir, "--target", "voice", "--json"] }); + + expect(JSON.parse(String(log.mock.calls.at(-1)?.[0]))).toMatchObject({ ok: true }); + expect(measureAudio.mock.calls[0]?.[1]).toBe(join(dir, "assets", "voice.wav")); + } finally { + log.mockRestore(); + rmSync(dir, { recursive: true, force: true }); + } + }); }); diff --git a/packages/cli/src/commands/normalize-audio.ts b/packages/cli/src/commands/normalize-audio.ts index 250e9717209..1c703201074 100644 --- a/packages/cli/src/commands/normalize-audio.ts +++ b/packages/cli/src/commands/normalize-audio.ts @@ -14,6 +14,7 @@ import { type AudioTag, type LoudnessLimit, } from "@hyperframes/studio-server/loudness"; +import { resolveAuthoredAssetFile } from "@hyperframes/parsers/asset-resolution"; import { defineCommand } from "citty"; import { c } from "../ui/colors.js"; import { projectCompositionFiles } from "../utils/mountedCompositions.js"; @@ -84,8 +85,10 @@ function selectedTags(tags: readonly ProjectAudioTag[], referenceId: string, tar return { referenceTag, targetTag }; } -function existingAudioFile(projectDir: string, tag: AudioTag): string { - const file = resolveLocalAudioPath(projectDir, tag.src); +function existingAudioFile(projectDir: string, tag: ProjectAudioTag): string { + const file = + resolveAuthoredAssetFile(projectDir, tag.file, tag.src) ?? + resolveLocalAudioPath(projectDir, tag.src); if (!existsSync(file)) { throw new Error(`Audio #${tag.id} file was not found: ${relative(projectDir, file)}`); } @@ -94,8 +97,8 @@ function existingAudioFile(projectDir: string, tag: AudioTag): string { async function measuredPlan( projectDir: string, - referenceTag: AudioTag, - targetTag: AudioTag, + referenceTag: ProjectAudioTag, + targetTag: ProjectAudioTag, ): Promise { const ffmpegPath = requiredFfmpeg(); const referenceFile = existingAudioFile(projectDir, referenceTag); @@ -132,7 +135,7 @@ function parsedLufs(raw: string): number { async function measuredAbsolutePlan( projectDir: string, - targetTag: AudioTag, + targetTag: ProjectAudioTag, targetLufs: number, ): Promise { const measurement = await measureAudio(