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..09b5f1747ea 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,28 @@ function runCapabilityQuery(args: MediaTreatmentCommandArgs): void {
console.log(JSON.stringify(withMeta({ ok: true, capabilities }), null, 2));
}
-function resolveMutationFile(args: MediaTreatmentCommandArgs) {
+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 +657,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 +690,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;
@@ -698,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.command.test.ts b/packages/cli/src/commands/normalize-audio.command.test.ts
index 3b5a6c1e085..11aad4b70a4 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,60 @@ 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 });
+ }
+ });
+
+ 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 ad5f725b853..1c703201074 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,
@@ -14,8 +14,10 @@ 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";
import { resolveProject } from "../utils/project.js";
import { failCommand } from "../utils/commandResult.js";
import type { Example } from "./_examples.js";
@@ -37,11 +39,22 @@ function fail(message: string, json: boolean, cause?: unknown): never {
failCommand(1, cause);
}
-function byId(tags: readonly AudioTag[], rawId: string, role: string): AudioTag {
+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,12 @@ interface WriteOutcome {
wrote: boolean;
withinTolerance: boolean;
tolerance: number;
- indexPath: string;
+ 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) {
@@ -73,8 +85,10 @@ function selectedTags(html: string, referenceId: string, targetId: string) {
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)}`);
}
@@ -83,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);
@@ -121,7 +135,7 @@ function parsedLufs(raw: string): number {
async function measuredAbsolutePlan(
projectDir: string,
- targetTag: AudioTag,
+ targetTag: ProjectAudioTag,
targetLufs: number,
): Promise {
const measurement = await measureAudio(
@@ -141,17 +155,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 +173,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 +227,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 +294,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;
+}