Skip to content

armgit / hypit

Public Imported from GitHub
0

Clone any viral video with AI agents. Not just a script, the whole workflow: swap the face, the words, the B-roll, ship 100 variants in one command, and get your 100M views.

fix: the caption outline is drawn, measured, and no longer clipped (#62)

rponeawa9d5e865d956f
diff --git a/packages/caption-fine/src/render.ts b/packages/caption-fine/src/render.ts
index 61267645..b72a4ef8 100644
--- a/packages/caption-fine/src/render.ts
+++ b/packages/caption-fine/src/render.ts
@@ -282,6 +282,22 @@ function easeOutElastic(value: number): number {
const neutralMotion: MotionSnapshot = { opacity: 1, transform: "none", filter: "none", clipPath: "inset(0% 0% 0% 0%)" };
+/**
+ * Whether a motion needs `clip-path` at all.
+ *
+ * `inset(0% 0% 0% 0%)` reads as a no-op and is not one: it clips the element and everything inside it
+ * to its border box. These boxes carry no padding, so their border box is exactly the glyph advance —
+ * and an outline is painted outside that, by a filter that contributes nothing to layout. Emitted as
+ * the resting value of every motion, it cut the outline off on all four sides, along with the glow,
+ * the drop shadow and the long shadow, which reach further still.
+ *
+ * A wipe is the only motion that has anything to clip. Every keyframe of one animation has to declare
+ * the same properties, so this is decided once per animation rather than per frame.
+ */
+function wipes(kind: FineCaptionOneShotMotion): boolean {
+ return kind === "wipe-left" || kind === "wipe-right" || kind === "wipe-up" || kind === "wipe-down";
+}
+
function motionSnapshot(kind: FineCaptionOneShotMotion, progress: number, distancePx: number): MotionSnapshot {
const value = clamp(progress, 0, 1);
const eased = easeOut(value);
@@ -319,12 +335,12 @@ function motionSnapshot(kind: FineCaptionOneShotMotion, progress: number, distan
return state(eased, transform);
}
-function snapshotStyle(snapshot: MotionSnapshot): VisualStyleDeclaration[] {
+function snapshotStyle(snapshot: MotionSnapshot, clipped = true): VisualStyleDeclaration[] {
return [
{ name: "opacity", value: snapshot.opacity },
{ name: "transform", value: snapshot.transform },
{ name: "filter", value: snapshot.filter },
- { name: "clip-path", value: snapshot.clipPath },
+ ...(clipped ? [{ name: "clip-path", value: snapshot.clipPath }] : []),
];
}
@@ -343,12 +359,13 @@ function cueAnimation(parameters: FineCaptionParameters, durationFrames: number)
...transitionOffsets(0, enterFrames, parameters.motion.cueEnter),
...transitionOffsets(durationFrames - exitFrames, exitFrames, parameters.motion.cueExit),
];
+ const clipped = wipes(parameters.motion.cueEnter) || wipes(parameters.motion.cueExit);
return animationFrom(durationFrames, offsets, (frame) => {
const enterProgress = enterFrames === 0 ? 1 : clamp(frame / enterFrames, 0, 1);
const exitProgress = exitFrames === 0 ? 1 : clamp((durationFrames - frame) / exitFrames, 0, 1);
const enter = motionSnapshot(parameters.motion.cueEnter, enterProgress, parameters.motion.slideDistancePx);
const exit = motionSnapshot(parameters.motion.cueExit, exitProgress, parameters.motion.slideDistancePx);
- return snapshotStyle(enterProgress < 1 ? enter : exit);
+ return snapshotStyle(enterProgress < 1 ? enter : exit, clipped);
});
}
@@ -369,15 +386,16 @@ function atomLifecycleAnimation(
...transitionOffsets(endFrame - exitFrames, exitFrames, parameters.motion.atomExit),
...stepOffsets(endFrame),
];
+ const clipped = wipes(parameters.motion.atomEnter) || wipes(parameters.motion.atomExit);
return animationFrom(durationFrames, offsets, (frame) => {
- if (frame < startFrame) return shouldWait ? [{ name: "opacity", value: 0 }] : snapshotStyle(neutralMotion);
+ if (frame < startFrame) return shouldWait ? [{ name: "opacity", value: 0 }] : snapshotStyle(neutralMotion, clipped);
if (frame >= endFrame && parameters.motion.atomExit !== "none") {
- return snapshotStyle(motionSnapshot(parameters.motion.atomExit, 0, parameters.motion.slideDistancePx));
+ return snapshotStyle(motionSnapshot(parameters.motion.atomExit, 0, parameters.motion.slideDistancePx), clipped);
}
const enterProgress = enterFrames === 0 ? 1 : clamp((frame - startFrame) / enterFrames, 0, 1);
const exitProgress = exitFrames === 0 ? 1 : clamp((endFrame - frame) / exitFrames, 0, 1);
- if (enterProgress < 1) return snapshotStyle(motionSnapshot(parameters.motion.atomEnter, enterProgress, parameters.motion.slideDistancePx));
- return snapshotStyle(motionSnapshot(parameters.motion.atomExit, exitProgress, parameters.motion.slideDistancePx));
+ if (enterProgress < 1) return snapshotStyle(motionSnapshot(parameters.motion.atomEnter, enterProgress, parameters.motion.slideDistancePx), clipped);
+ return snapshotStyle(motionSnapshot(parameters.motion.atomExit, exitProgress, parameters.motion.slideDistancePx), clipped);
});
}
@@ -460,8 +478,9 @@ function activeResponseAnimation(
});
}
const frames = Math.min(parameters.motion.activeResponseFrames, Math.max(1, endFrame - startFrame));
+ const clipped = wipes(response);
return animationFrom(durationFrames, transitionOffsets(startFrame, frames, response), (frame) => {
- if (frame < startFrame || frame > startFrame + frames) return snapshotStyle(neutralMotion);
+ if (frame < startFrame || frame > startFrame + frames) return snapshotStyle(neutralMotion, clipped);
const progress = clamp((frame - startFrame) / frames, 0, 1);
if (response === "pop" || response === "spring") {
const amplitude = parameters.motion.activeScale - 1;
@@ -470,7 +489,7 @@ function activeResponseAnimation(
: 1 + amplitude * Math.exp(-4 * progress) * Math.sin(12 * progress);
return [{ name: "transform", value: `scale(${compactNumber(responseScale)})` }];
}
- return snapshotStyle(motionSnapshot(response, progress, parameters.motion.slideDistancePx));
+ return snapshotStyle(motionSnapshot(response, progress, parameters.motion.slideDistancePx), clipped);
});
}
@@ -542,7 +561,8 @@ function activeBoxAnimation(
const enterProgress = enterFrames === 0 ? 1 : clamp((frame - startFrame) / enterFrames, 0, 1);
const exitProgress = exitFrames === 0 ? 1 : clamp((logicalEnd - frame) / exitFrames, 0, 1);
const kind = enterProgress < 1 ? box.enter : box.exit;
- return snapshotStyle(motionSnapshot(kind, Math.min(enterProgress, exitProgress), parameters.motion.slideDistancePx));
+ return snapshotStyle(motionSnapshot(kind, Math.min(enterProgress, exitProgress), parameters.motion.slideDistancePx),
+ wipes(box.enter) || wipes(box.exit));
}) ?? { keyframes: [
{ atFrame: 0, style: [{ name: "opacity", value: 1 }] },
{ atFrame: durationFrames, style: [{ name: "opacity", value: 1 }] },
@@ -831,8 +851,9 @@ function cueElements(
{ name: "column-gap", value: `${compactNumber(parameters.layout.wordGapPx)}px` },
{ name: "display", value: "inline-flex" },
{ name: "inset", value: "0" },
- ...(kind === "glyph" && parameters.karaoke.transition === "wipe"
- ? [{ name: "overflow", value: "hidden" }] as const : []),
+ // The wipe's own `clip-path` is what reveals this layer a word at a time, and it clips to the
+ // same border box, so an `overflow` here adds nothing — except at full reveal, where the
+ // clip has opened and this was still cutting the outline off at the glyph advance.
{ name: "position", value: "absolute" },
],
animation: kind === "glyph" && parameters.karaoke.transition === "wipe"
diff --git a/packages/hyperframes/src/text.ts b/packages/hyperframes/src/text.ts
index a7876a44..b61c628c 100644
--- a/packages/hyperframes/src/text.ts
+++ b/packages/hyperframes/src/text.ts
@@ -169,6 +169,31 @@ function glyphPaintLayers(paints: readonly VisualTextPaintLayer[]): GlyphPaintLa
return paints.filter((paint): paint is GlyphPaintLayer => paint.kind !== "box");
}
+/**
+ * How far outside the glyph advance an outline reaches, in pixels.
+ *
+ * The ring is a filter — `feMorphology` dilating the glyph's own alpha — so it draws outside the
+ * element and contributes nothing to layout. Everything that measures the text therefore measures the
+ * letterform alone: the width a `max-content` box takes, where a line wraps, where a background sits,
+ * the gap between two words, and where an anchored line is placed. The outline lands past all of them.
+ *
+ * The placement decides the reach, and it is decided here — `outside` puts the whole width beyond the
+ * edge, `center` half of it, `inside` none — so the reserve is computed here rather than by whoever
+ * declared the Paint.
+ *
+ * A shadow and a glow are not part of the letterform and have never affected layout; reserving for
+ * them would re-flow a line for a soft edge. Only the outline counts.
+ */
+function strokeReserve(layers: readonly GlyphPaintLayer[]): number {
+ let reserve = 0;
+ for (const paint of layers) {
+ if (paint.kind !== "stroke") continue;
+ const reach = paint.placement === "outside" ? paint.widthPx : paint.placement === "center" ? paint.widthPx / 2 : 0;
+ reserve = Math.max(reserve, reach);
+ }
+ return reserve;
+}
+
function inheritedGlyphColor(paints: readonly VisualTextPaintLayer[]): string[] {
const fills = glyphPaintLayers(paints).filter((paint): paint is Extract<GlyphPaintLayer, { kind: "fill" }> => paint.kind === "fill");
return fills.length === 1 && fills[0]!.paint.kind === "solid" ? [`color:${fills[0]!.paint.color}`] : [];
@@ -311,8 +336,13 @@ export function renderGlyphPaintedString(
const defs = definitions.length === 0
? ""
: `<svg aria-hidden="true" width="0" height="0" style="position:absolute;overflow:hidden"><defs>${definitions}</defs></svg>`;
- // The layers occupy one grid cell each so they stack in the order they were declared.
- return `${defs}<span style="position:relative;display:inline-grid">${renderGlyphPaint(value, paints, context)}</span>`;
+ // The layers occupy one grid cell each so they stack in the order they were declared, and the
+ // wrapper carries the room the outline needs. Padding one layer would move its copy of the text
+ // away from the others and separate the body from its own ring; padding the wrapper moves all of
+ // them together and is what the box around them measures.
+ const reserve = strokeReserve(layers);
+ const box = reserve === 0 ? "" : `;padding:${number(reserve)}px`;
+ return `${defs}<span style="position:relative;display:inline-grid${box}">${renderGlyphPaint(value, paints, context)}</span>`;
}
function boxLayers(
diff --git a/packages/reference-video-tools/src/authoring.ts b/packages/reference-video-tools/src/authoring.ts
index 0dc5e391..543286d3 100644
--- a/packages/reference-video-tools/src/authoring.ts
+++ b/packages/reference-video-tools/src/authoring.ts
@@ -166,6 +166,34 @@ export function scriptBody(svml: string): { readonly text: string; readonly offs
return { text: svml.slice(start, end), offset: start };
}
+/**
+ * What a Source calls each package it imports.
+ *
+ * These tools find elements by tag — `SemanticTake`, `Normalize`, `Canvas` — and a tag is written
+ * behind whatever alias the Source chose in `<import as="…" from="…"/>`. The alias is the author's,
+ * not the package's: two Sources importing one package under two names are the same Source as far as
+ * anything downstream is concerned.
+ *
+ * Assuming the conventional alias is therefore a reading that is right until somebody writes
+ * `as="speech-track"`, at which point the element is invisible and whatever depended on finding it
+ * reports the Source as missing something it plainly has. So the alias is read from the Source, and
+ * the conventional one is the fallback for a Source that imports without naming one.
+ */
+export function aliasPattern(svml: string, specifier: string, conventional: string): string {
+ const found = new Set<string>();
+ for (const match of svml.matchAll(/<import\s+([^>]*?)\/?>/gu)) {
+ const attributes = match[1] ?? "";
+ // The scope's own `@` is part of the name, so only the last one separates it from the version.
+ const from = /\bfrom="(.+)@\d+"/u.exec(attributes)?.[1];
+ if (from !== specifier) continue;
+ found.add(/\bas="([^"]+)"/u.exec(attributes)?.[1] ?? conventional);
+ }
+ if (found.size === 0) found.add(conventional);
+ // Longest first, so `speech-track` is not matched as `speech` followed by a stray `-track`.
+ return [...found].sort((left, right) => right.length - left.length)
+ .map((alias) => alias.replace(/[.*+?^${}()|[\]\\-]/gu, "\\$&")).join("|");
+}
+
/** Every Recipe body in every sheet the Source imports, keyed `alias.path`. */
async function recipeSheets(svml: string, svmlPath: string): Promise<ReadonlyMap<string, SvsRecipe>> {
const sheets = new Map<string, SvsRecipe>();
@@ -201,7 +229,8 @@ function policiesBySegment(svml: string, sheets: ReadonlyMap<string, SvsRecipe>)
} {
const policies = new Map<string, SpeechEstimatePolicy>();
const named = new Set<string>();
- for (const match of svml.matchAll(/<estimate:Speech\b([^>]*?)\/?>/gsu)) {
+ const estimate = aliasPattern(svml, "@hypit/estimate", "estimate");
+ for (const match of svml.matchAll(new RegExp(`<(?:${estimate}):Speech\\b([^>]*?)/?>`, "gsu"))) {
const attributes = match[1] ?? "";
const segment = /\bsource=\{story\.segment\.([A-Za-z0-9_-]+)\.speech\}/u.exec(attributes)?.[1];
const recipe = /\bpolicy=\{([A-Za-z0-9_.-]+)\}/u.exec(attributes)?.[1];
@@ -821,19 +850,21 @@ export async function renderElement(input: RenderElementInput): Promise<Record<s
const clock = /<[a-z-]*:?Clock\b[^>]*?\bframe-rate="(\d+)"/su.exec(svml)?.[1]
?? /<time:Clock\b[^>]*?\bfps="(\d+)"/su.exec(svml)?.[1];
const frameRate = Number(clock ?? 30);
- const canvasMatch = /<space:Canvas\b[^>]*?\bwidth="(\d+)"[^>]*?\bheight="(\d+)"/su.exec(svml);
- assert(canvasMatch !== null, "the Source declares no <space:Canvas width= height=/>");
+ const space = aliasPattern(svml, "@hypit/spatial", "space");
+ const canvasMatch = new RegExp(`<(?:${space}):Canvas\\b[^>]*?\\bwidth="(\\d+)"[^>]*?\\bheight="(\\d+)"`, "su").exec(svml);
+ assert(canvasMatch !== null, `the Source declares no <${space.split("|")[0]}:Canvas width= height=/>`);
const canvas = { width: Number(canvasMatch[1]), height: Number(canvasMatch[2]) };
// Which SemanticTake output belongs to which Segment, so each stand-in lands on the right one.
+ const whisperx = aliasPattern(svml, "@hypit/whisperx", "whisperx");
const takeOutputs = new Map<string, string>();
- for (const match of svml.matchAll(/<whisperx:SemanticTake\b([^>]*?)\/?>/gsu)) {
+ for (const match of svml.matchAll(new RegExp(`<(?:${whisperx}):SemanticTake\\b([^>]*?)/?>`, "gsu"))) {
const attributes = match[1] ?? "";
const id = /\bid="([^"]+)"/u.exec(attributes)?.[1];
const segment = /\bsegment=\{story\.segment\.([A-Za-z0-9_-]+)\}/u.exec(attributes)?.[1];
if (id !== undefined && segment !== undefined) takeOutputs.set(segment, id);
}
- assert(takeOutputs.size > 0, "the Source declares no whisperx:SemanticTake to stand in for");
+ assert(takeOutputs.size > 0, `the Source declares no ${whisperx.split("|")[0]}:SemanticTake to stand in for`);
// What the Run already brings. A project Run declares nothing and everything is mocked; a package's
// preview Run ships its own sample pictures, and those are carried across untouched so the catalogue
@@ -899,7 +930,7 @@ export async function renderElement(input: RenderElementInput): Promise<Record<s
*/
const mockedMedia = (): ReadonlyMap<string, { readonly frames: number; readonly picture: boolean }> => {
const windows = new Map<string, number>();
- for (const match of svml.matchAll(/<whisperx:SemanticTake\b([^>]*?)\/?>/gsu)) {
+ for (const match of svml.matchAll(new RegExp(`<(?:${whisperx}):SemanticTake\\b([^>]*?)/?>`, "gsu"))) {
const attributes = match[1] ?? "";
const media = /\bmedia=\{([A-Za-z0-9_-]+)\.media\}/u.exec(attributes)?.[1];
const segment = /\bsegment=\{story\.segment\.([A-Za-z0-9_-]+)\}/u.exec(attributes)?.[1];
@@ -922,7 +953,8 @@ export async function renderElement(input: RenderElementInput): Promise<Record<s
: window.endFrameExclusive - window.startFrame);
}
const carries = new Map<string, { readonly frames: number; readonly picture: boolean }>();
- for (const match of svml.matchAll(/<pipeline:Normalize\b([^>]*?)\/?>/gsu)) {
+ const pipeline = aliasPattern(svml, "@hypit/media-pipeline", "pipeline");
+ for (const match of svml.matchAll(new RegExp(`<(?:${pipeline}):Normalize\\b([^>]*?)/?>`, "gsu"))) {
const attributes = match[1] ?? "";
const id = /\bid="([^"]+)"/u.exec(attributes)?.[1];
const video = /\bvideo="([^"]+)"/u.exec(attributes)?.[1];
diff --git a/packages/reference-video-tools/src/checks.ts b/packages/reference-video-tools/src/checks.ts
index 75f044fa..4131792e 100644
--- a/packages/reference-video-tools/src/checks.ts
+++ b/packages/reference-video-tools/src/checks.ts
@@ -14,7 +14,7 @@ import { readStudioSession } from "@hypit/studio/src/session.js";
import type { StudioSession } from "@hypit/studio/src/session.js";
import { inspectStudioRun } from "@hypit/studio/src/studio-preflight.js";
-import { invokedFrom, referenceRoot, scriptBody } from "./authoring.js";
+import { aliasPattern, invokedFrom, referenceRoot, scriptBody } from "./authoring.js";
import { assert, round } from "./media.js";
export type PreviewCheckInput = {
@@ -269,8 +269,9 @@ type FrameGeometry = {
* over a word add up to the whole picture.
*/
function frameGeometry(svml: string): FrameGeometry {
+ const space = aliasPattern(svml, "@hypit/spatial", "space");
const canvases = new Map<string, Box>();
- for (const match of svml.matchAll(/<space:Canvas\b([^>]*?)\/?>/gsu)) {
+ for (const match of svml.matchAll(new RegExp(`<(?:${space}):Canvas\\b([^>]*?)/?>`, "gsu"))) {
const attributes = match[1] ?? "";
const id = /\bid="([^"]+)"/u.exec(attributes)?.[1];
const width = Number(/\bwidth="(\d+)"/u.exec(attributes)?.[1]);
@@ -281,7 +282,7 @@ function frameGeometry(svml: string): FrameGeometry {
}
const declared = new Map<string, FrameDeclaration>();
- for (const match of svml.matchAll(/<space:Frame\b([^>]*?)\/?>/gsu)) {
+ for (const match of svml.matchAll(new RegExp(`<(?:${space}):Frame\\b([^>]*?)/?>`, "gsu"))) {
const attributes = match[1] ?? "";
const id = /\bid="([^"]+)"/u.exec(attributes)?.[1];
const within = /\bwithin=\{([A-Za-z0-9_-]+)\}/u.exec(attributes)?.[1];
@@ -548,7 +549,8 @@ export async function reconstructionCheck(
// Which Normalize ids carry a picture. A take normalized with `video="none"` is a voice: it has no
// window to fill, and nothing it feeds puts anything on the Canvas.
const moving = new Set<string>();
- for (const match of svml.matchAll(/<pipeline:Normalize\b([^>]*?)\/?>/gsu)) {
+ const pipeline = aliasPattern(svml, "@hypit/media-pipeline", "pipeline");
+ for (const match of svml.matchAll(new RegExp(`<(?:${pipeline}):Normalize\\b([^>]*?)/?>`, "gsu"))) {
const attributes = match[1] ?? "";
const id = /\bid="([^"]+)"/u.exec(attributes)?.[1];
const video = /\bvideo="([^"]+)"/u.exec(attributes)?.[1];
@@ -693,7 +695,9 @@ export async function reconstructionCheck(
// the Take's Segment has over it. A Take fed by a Normalize with `video="none"` is a voice and
// puts nothing there, so its Segment is spoken over whatever is already on screen.
const takes = new Map<string, { readonly segment: string; readonly picture: boolean }>();
- for (const match of svml.matchAll(/<whisperx:SemanticTake\b([^>]*?)\/?>/gsu)) {
+ const whisperx = aliasPattern(svml, "@hypit/whisperx", "whisperx");
+ const speech = aliasPattern(svml, "@hypit/speech-track", "speech");
+ for (const match of svml.matchAll(new RegExp(`<(?:${whisperx}):SemanticTake\\b([^>]*?)/?>`, "gsu"))) {
const attributes = match[1] ?? "";
const id = /\bid="([^"]+)"/u.exec(attributes)?.[1];
const segment = /\bsegment=\{story\.segment\.([A-Za-z0-9_-]+)\}/u.exec(attributes)?.[1];
@@ -701,10 +705,10 @@ export async function reconstructionCheck(
if (id === undefined || segment === undefined) continue;
takes.set(id, { segment, picture: media !== undefined && moving.has(media) });
}
- for (const track of svml.matchAll(/<speech:Track\b([^>]*?)>(.*?)<\/speech:Track>/gsu)) {
+ for (const track of svml.matchAll(new RegExp(`<(?:${speech}):Track\\b([^>]*?)>(.*?)</(?:${speech}):Track>`, "gsu"))) {
const where = placement(/\bvisual-frame=\{([A-Za-z0-9_-]+)\}/u.exec(track[1] ?? "")?.[1], undefined);
if (where === undefined) continue;
- for (const take of (track[2] ?? "").matchAll(/<speech:Take\b[^>]*?\bsource=\{([A-Za-z0-9_-]+)\.take\}/gu)) {
+ for (const take of (track[2] ?? "").matchAll(new RegExp(`<(?:${speech}):Take\\b[^>]*?\\bsource=\\{([A-Za-z0-9_-]+)\\.take\\}`, "gu"))) {
const named = takes.get(take[1] ?? "");
if (named?.picture === true) claimSegment(named.segment, where.canvas, where.box);
}