Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
7 changes: 4 additions & 3 deletions packages/cli/src/utils/lintProject.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -1076,7 +1076,7 @@ describe("duplicate_audio_track", () => {
expect(finding).toBeUndefined();
});

it("deduplicates same audio found in root + sub-composition", async () => {
it("ignores audio in a sub-composition the root never mounts", async () => {
const project = makeProject(validHtmlWithAudio(), {
"scene.html": validHtmlWithAudio("scene"),
});
Expand All @@ -1102,7 +1102,7 @@ describe("duplicate_audio_track", () => {

it("formats Infinity end times as 'end' without crashing", async () => {
const html = `<html><body>
<div data-composition-id="main" data-width="1920" data-height="1080" data-duration="30">
<div data-composition-id="main" data-width="1920" data-height="1080">
<audio id="a" src="a.wav" data-track-index="0" data-start="0">
<audio id="b" src="b.wav" data-track-index="0" data-start="5">
</div>
Expand All @@ -1117,7 +1117,8 @@ describe("duplicate_audio_track", () => {
});

it("finds audio across multiple HTML sources (g-flag regression)", async () => {
const project = makeProject(validHtmlWithAudio(), {
const mountScene = `</audio><div data-composition-id="scene" data-composition-src="compositions/scene.html" data-start="0"></div>`;
const project = makeProject(validHtmlWithAudio().replace("</audio>", mountScene), {
"scene.html": `<html><body>
<div data-composition-id="scene" data-width="1920" data-height="1080">
<audio id="overlap" src="music.wav" data-track-index="0" data-start="5" data-duration="20">
Expand Down
85 changes: 2 additions & 83 deletions packages/core/src/mediaTiming.ts
Original file line number Diff line number Diff line change
@@ -1,83 +1,2 @@
import { readMediaOffsetSeconds } from "@hyperframes/parsers/media-duration";

export const MEDIA_START_BASIS_ATTR = "data-hf-media-start-basis";

export type MediaStartBasis = "local" | "global";

export function readMediaStartBasis(value: string | null | undefined): MediaStartBasis {
return value?.trim().toLowerCase() === "global" ? "global" : "local";
}

/** Resolve authored media time onto the root timeline. Nested media is local
* by default; only an explicit compatibility marker preserves a legacy
* root-global value. */
export function resolveAbsoluteMediaStartSeconds(input: {
authoredStart: number;
hostStart: number;
basis?: string | null;
}): number {
return readMediaStartBasis(input.basis) === "global"
? input.authoredStart
: input.hostStart + input.authoredStart;
}

/** The one rule for a media element's root-timeline start; the runtime and the CLI both call it.
* `hostStart` is the composition's origin. With no literal start, an auto-injected start, or an
* origin at 0 there is nothing for the basis to disambiguate, so ordinary resolution applies. */
export function resolveMediaStartSeconds(
input: MediaStartInput & { ordinaryStart: () => number },
): number {
if (!hasLiteralNestedStart(input)) return input.ordinaryStart();
return resolveAbsoluteMediaStartSeconds({
authoredStart: input.authoredStart,
hostStart: input.hostStart,
basis: input.basis,
});
}

/** True when the authored start is already root time, so no host offset applies. */
export function isRootGlobalMediaStart(input: MediaStartInput): boolean {
return hasLiteralNestedStart(input) && readMediaStartBasis(input.basis) === "global";
}

export interface MediaStartInput {
authoredStart: number | null;
hostStart: number;
hasAutoStart: boolean;
basis?: string | null;
}

function hasLiteralNestedStart(
input: MediaStartInput,
): input is MediaStartInput & { authoredStart: number } {
return !input.hasAutoStart && input.authoredStart != null && input.hostStart !== 0;
}

/** A composition host's in-point; only a host with one shifts or cuts what it holds. */
export function hostInPointSeconds(host: Pick<Element, "getAttribute">): number {
return readMediaOffsetSeconds((name) => host.getAttribute(name));
}

/** Main-timeline time of a sub-composition's local t=0: its host's start minus its in-point. */
export function compositionOriginSeconds(
hostStart: number,
host: Pick<Element, "getAttribute">,
): number {
return hostStart - hostInPointSeconds(host);
}

export interface HostSlot {
start: number;
end: number;
}

/** Each in-point host cuts the span to its own window. */
export function cutToHostSlots(
span: { start: number; end: number },
hosts: readonly HostSlot[],
): { start: number; end: number } {
return hosts.reduce((kept, host) => {
const start = Math.max(kept.start, host.start);
return { start, end: Math.max(start, Math.min(kept.end, host.end)) };
}, span);
}
// Kept for existing importers; the rule lives in @hyperframes/parsers.
export * from "@hyperframes/parsers/media-timing";
108 changes: 2 additions & 106 deletions packages/engine/src/services/referenceResolver.ts
Original file line number Diff line number Diff line change
@@ -1,106 +1,2 @@
/**
* Node-side resolver for relative `data-start` timing references, shared by
* every parser that reads media timing out of compiled HTML — video frames
* (`parseVideoElements`), images (`parseImageElements`), and audio
* (`parseAudioElements`). Keeping the resolution in ONE place is load-bearing:
* if audio and video disagree on what `data-start="intro"` means, a relative
* reference that renders a video at the right time silently drops the audio
* track (they used to — audio parsed `parseFloat("intro") = NaN`).
*
* Mirrors the browser runtime's startResolver so `snapshot`/`render` agree.
* DOM access is via a minimal structural shape so it works against linkedom
* (Node) without pulling in lib.dom types.
*/

import { parseNumeric, parseStartExpression } from "@hyperframes/core";

/** Minimal structural DOM shape the reference resolver needs. */
export interface RefResolverEl {
getAttribute(name: string): string | null;
}
export interface RefResolverDoc {
getElementById(id: string): RefResolverEl | null;
querySelector(selector: string): RefResolverEl | null;
}

/**
* Find the element a relative `data-start` reference points at — by `id`
* first, then by `data-composition-id` (a sub-composition can be referenced).
* The reference-id grammar (see parseStartExpression) is restricted to
* `[A-Za-z0-9_.:-]`, none of which need escaping inside a quoted attribute
* selector, so no CSS.escape (absent in linkedom) is required.
*/
function findReferenceTargetEl(doc: RefResolverDoc, refId: string): RefResolverEl | null {
return doc.getElementById(refId) ?? doc.querySelector(`[data-composition-id="${refId}"]`);
}

/**
* Resolve an element's absolute start time (seconds) the same way the browser
* runtime's startResolver does, so `<video data-start="intro">` (a relative
* reference to another clip's end) renders at the right time instead of
* producing NaN and compositing blank / dropping audio. Durations come from
* `data-duration` or `data-end` here; the natural-media-duration fallback isn't
* known at parse time, so — exactly like the runtime — an unknown-duration
* reference falls back to the target's start and an unknown target falls back
* to 0 (never NaN).
*/
export function resolveReferencedStart(
doc: RefResolverDoc,
el: RefResolverEl,
startCache: Map<RefResolverEl, number>,
visiting: Set<RefResolverEl>,
): number {
const cached = startCache.get(el);
if (cached !== undefined) return cached;
if (visiting.has(el)) return 0; // cycle guard (A -> B -> A)
visiting.add(el);
try {
const expression = parseStartExpression(el.getAttribute("data-start"));
if (!expression) {
startCache.set(el, 0);
return 0;
}
if (expression.kind === "absolute") {
const value = Math.max(0, expression.value);
startCache.set(el, value);
return value;
}
const target = findReferenceTargetEl(doc, expression.refId);
if (!target) {
startCache.set(el, 0);
return 0;
}
const targetStart = resolveReferencedStart(doc, target, startCache, visiting);
const targetDuration = resolveReferencedDuration(doc, target, startCache, visiting);
const resolved =
targetDuration != null && targetDuration > 0
? Math.max(0, targetStart + targetDuration + expression.offset)
: Math.max(0, targetStart + expression.offset);
startCache.set(el, resolved);
return resolved;
} finally {
visiting.delete(el);
}
}

/**
* Duration of a referenced clip, from `data-duration` or `data-end - start`.
* Returns null when only the natural media duration would settle it (unknown
* at parse time) — the caller then treats the reference as duration-0.
*/
export function resolveReferencedDuration(
doc: RefResolverDoc,
el: RefResolverEl,
startCache: Map<RefResolverEl, number>,
visiting: Set<RefResolverEl>,
): number | null {
const durationAttr = parseNumeric(el.getAttribute("data-duration"));
if (durationAttr != null && durationAttr > 0) return durationAttr;
const endAttr = parseNumeric(el.getAttribute("data-end"));
if (endAttr != null) {
const start = resolveReferencedStart(doc, el, startCache, visiting);
const delta = endAttr - start;
if (Number.isFinite(delta) && delta > 0) return delta;
}
return null;
}
// Kept for existing importers; the resolver lives in @hyperframes/parsers.
export * from "@hyperframes/parsers/reference-resolver";
45 changes: 45 additions & 0 deletions packages/lint/src/project.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -1044,6 +1044,51 @@ describe("audio-aware project rules", () => {
);
expect(codes).not.toContain("duplicate_audio_track");
});

const scene = (id: string, videoDuration = 5) => `<template id="${id}-template">
<div data-composition-id="${id}" data-width="1920" data-height="1080">
${video('data-has-audio="true"')
.replace('src="a.mp4"', `src="${id}.mp4"`)
.replace('data-duration="5"', `data-duration="${videoDuration}"`)}
</div>
</template>`;
const host = (id: string, start: number | string, length: number | null) =>
`<div data-composition-id="${id}" data-composition-src="compositions/${id}.html" data-start="${start}"${length === null ? "" : ` data-duration="${length}"`} data-track-index="1"></div>`;
const scenesCodes = (
starts: Array<number | string>,
{ videoDuration = 5, hostDuration = 5 as number | null } = {},
) => {
const ids = starts.map((_, i) => `s${i}`);
const project = makeProject(
composition(ids.map((id, i) => host(id, starts[i]!, hostDuration)).join("")),
Object.fromEntries(ids.map((id) => [`${id}.html`, scene(id, videoDuration)])),
);
return lintProject(project).then(({ results }) =>
results.flatMap((result) => result.result.findings.map((f) => f.code)),
);
};

it("places each scene's audio at its host's start, so scenes played one after another pass", async () => {
expect(await scenesCodes([0, 5])).not.toContain("duplicate_audio_track");
expect(await scenesCodes([0, 5], { hostDuration: null })).not.toContain(
"duplicate_audio_track",
);
});

it("still warns when two scenes' hosts overlap", async () => {
expect(await scenesCodes([0, 2])).toContain("duplicate_audio_track");
});

it("places a scene chained to the one before it with a reference start", async () => {
expect(await scenesCodes([0, "s0"])).not.toContain("duplicate_audio_track");
expect(await scenesCodes([0, "s0 - 2"])).toContain("duplicate_audio_track");
});

it("cuts a scene's audio at its host's end, as playback does", async () => {
expect(await scenesCodes([0, 5], { videoDuration: 10 })).not.toContain(
"duplicate_audio_track",
);
});
});

describe("audio_file_without_element", () => {
Expand Down
Loading
Loading