Skip to content

Open source CapCut alternative.

TypeScript

fix(site): correct caption emphasis and mattes [rebuild]

David Le11f2587dc5f7
diff --git a/site/src/cut/components/CameraCardSection.tools.ts b/site/src/cut/components/CameraCardSection.tools.ts
index dfff524a..746b4ecb 100644
--- a/site/src/cut/components/CameraCardSection.tools.ts
+++ b/site/src/cut/components/CameraCardSection.tools.ts
@@ -52,8 +52,8 @@ export const CAMERA_CARD_TOOLS = [
),
shadow: num(`Card shadow opacity 0..1, 0 for none (default ${CARD_DEFAULTS.shadow})`),
scale: num(`Footage size over the default placement, ${CARD_SCALE_MIN}..${CARD_SCALE_MAX} (default 1)`),
- offset_x: num(`Footage shift right, fraction of the frame width, -${CARD_OFFSET_MAX}..${CARD_OFFSET_MAX} (default 0)`),
- offset_y: num(`Footage shift down, fraction of the frame height, -${CARD_OFFSET_MAX}..${CARD_OFFSET_MAX} (default 0)`),
+ offset_x: num(`Footage shift right, fraction of the clip's box width, -${CARD_OFFSET_MAX}..${CARD_OFFSET_MAX} (default 0)`),
+ offset_y: num(`Footage shift down, fraction of the clip's box height, -${CARD_OFFSET_MAX}..${CARD_OFFSET_MAX} (default 0)`),
}),
},
] as const satisfies readonly AiToolDef[];
diff --git a/site/src/cut/components/CameraCardSection.tsx b/site/src/cut/components/CameraCardSection.tsx
index ffd4400c..34975f97 100644
--- a/site/src/cut/components/CameraCardSection.tsx
+++ b/site/src/cut/components/CameraCardSection.tsx
@@ -1,6 +1,5 @@
"use client";
-import { useEffect } from "react";
import { Switch } from "@/components/ui/switch";
import { Button } from "@/components/ui/button";
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select";
@@ -23,7 +22,7 @@ import {
type CameraCard,
type CardSide,
} from "@/cut/lib/cameraCard";
-import { ensureCardMatte, retryCardMatte, useMatteBakes } from "@/cut/lib/removal/bakeJobs";
+import { retryCardMatte, useMatteBakes } from "@/cut/lib/removal/bakeJobs";
import { useEditor } from "@/cut/lib/store";
import { frameOf, rectOf, type VideoClip } from "@/cut/lib/types";
import { ResetButton, Row, Section, useSliderCheckpoint } from "@/cut/components/panelBits";
@@ -50,13 +49,6 @@ export function CameraCardSection({ clip }: { clip: VideoClip }) {
const job = useMatteBakes((s) => s.jobs[cardMatteKey(clip.id)]);
const aspect = useEditor((s) => s.aspect);
const asset = useEditor((s) => s.assets.find((a) => a.id === clip.assetId));
- // The head's matte is owed while the card shows it; the doc sweep starts
- // it too, so this only makes the start immediate.
- const owes = !!card?.popOut && !card.matte;
- useEffect(() => {
- if (owes) ensureCardMatte(clip.id);
- }, [owes, clip.id]);
-
const current = () => st().clips.find((c) => c.id === clip.id)?.card;
const draft = (patch: Partial<CameraCard>) => {
const c = current();
diff --git a/site/src/cut/components/Inspector.tsx b/site/src/cut/components/Inspector.tsx
index 64d2ccbc..b9ac270d 100644
--- a/site/src/cut/components/Inspector.tsx
+++ b/site/src/cut/components/Inspector.tsx
@@ -88,6 +88,7 @@ import {
penClosed,
restingMaskFrame,
AMOUNTLESS_EFFECTS,
+ displayWords,
} from "@donkeycut/effects-kit";
import { BLOCK_COLOR } from "@/cut/lib/blockSource";
import { bindRecording, unbindRecording } from "@/cut/lib/soundBind";
@@ -127,7 +128,7 @@ import {
import { patchLibrary, refetchLibrary, useLibrary } from "@/cut/lib/queries";
import { TEXT_SIZES, writeTextStyle } from "@/cut/lib/textStyle";
import { formatTime } from "@/cut/lib/time";
-import { captionStyle, cueAnchor, trackPos } from "@/cut/lib/subtitles";
+import { cueSpot } from "@/cut/lib/subtitles";
import { cueEmphasis } from "@/cut/lib/captionEmphasis";
import {
fontStack,
@@ -3365,15 +3366,13 @@ function PositionRow({
function CuePanel({ cue }: { cue: SubtitleCue }) {
const subtitles = useEditor((s) => s.subtitles);
const posCk = useSliderCheckpoint();
- const style = captionStyle(subtitles.style);
- const track = trackPos(subtitles, style, cue.lane ?? 0);
const own = cue.x !== undefined && cue.y !== undefined;
- const pose = cueAnchor(cue, track, style);
+ const pose = cueSpot(subtitles, cue);
const setPos = (axis: "x" | "y", pct: number) => {
const v = Math.min(0.98, Math.max(0.02, pct / 100));
useEditor.getState().setCuePosition(cue.id, { ...pose, [axis]: v });
};
- const words = cue.text.split(/\s+/).filter(Boolean);
+ const words = displayWords(cue.text);
const marked = new Set(cueEmphasis(cue));
return (
<div className="flex flex-col gap-1 px-3.5 pt-2 pb-4">
@@ -3383,7 +3382,7 @@ function CuePanel({ cue }: { cue: SubtitleCue }) {
enabled={own}
onEnabledChange={(on) => {
useEditor.getState().pushHistory();
- useEditor.getState().setCuePosition(cue.id, on ? cueAnchor({}, track, style) : null);
+ useEditor.getState().setCuePosition(cue.id, on ? cueSpot(subtitles, { lane: cue.lane }) : null);
}}
>
<PositionRow pose={pose} min={2} max={98} ck={posCk} onSet={setPos} />
diff --git a/site/src/cut/components/SubtitlesPanel.tsx b/site/src/cut/components/SubtitlesPanel.tsx
index c85f03e7..f00bb436 100644
--- a/site/src/cut/components/SubtitlesPanel.tsx
+++ b/site/src/cut/components/SubtitlesPanel.tsx
@@ -21,7 +21,7 @@ import {
subtitleLaneCount,
trackLocale,
} from "@/cut/lib/subtitles";
-import { cueEmphasis, emphasisRuns, wordIndicesIn } from "@/cut/lib/captionEmphasis";
+import { cueEmphasis, emphasisRuns, typedToggle } from "@/cut/lib/captionEmphasis";
import { DropdownMenu, DropdownMenuContent, DropdownMenuItem } from "@/components/ui/dropdown-menu";
import {
cueWordCount,
@@ -785,8 +785,7 @@ const CueSpan = memo(function CueSpan({ cue, gap }: { cue: SubtitleCue; gap: num
label: string;
on: boolean;
} | null>(null);
- const marked = cueEmphasis(cue);
- const markKey = marked.join(",");
+ const markKey = cueEmphasis(cue).join(",");
// The span is uncontrolled while focused (so the caret survives typing);
// outside edits (undo, regenerate, emphasis) sync the DOM here.
@@ -795,23 +794,15 @@ const CueSpan = memo(function CueSpan({ cue, gap }: { cue: SubtitleCue; gap: num
if (el && document.activeElement !== el) paintCue(el, cue.text, markKey ? markKey.split(",").map(Number) : []);
}, [cue.text, markKey]);
- /** The words a character range of the caption touches, and whether they
- * would all be emphasized by the toggle. Typing not yet committed is
- * committed first, so the words are the ones on screen. */
+ /** The words a character range of the caption touches, and whether the
+ * toggle turns them on. Typing not yet committed is committed first, so the
+ * words are the ones on screen. */
const wordsAt = (from: number, to: number) => {
const el = ref.current;
if (!el) return null;
const typed = el.textContent ?? "";
- const indices = wordIndicesIn(typed, from, to);
- if (indices.length === 0) return null;
- const words = typed.split(/\s+/).filter(Boolean);
- const set = new Set(marked);
- return {
- typed,
- indices,
- on: !indices.every((i) => set.has(i)),
- label: indices.map((i) => words[i]).join(" "),
- };
+ const hit = typedToggle(cue, typed, from, to);
+ return hit ? { typed, ...hit } : null;
};
const toggle = (from: number, to: number) => {
diff --git a/site/src/cut/hooks/usePlayback.ts b/site/src/cut/hooks/usePlayback.ts
index bda2d5cc..7cbb0ff6 100644
--- a/site/src/cut/hooks/usePlayback.ts
+++ b/site/src/cut/hooks/usePlayback.ts
@@ -9,7 +9,7 @@ import {
projectDuration,
useEditor,
} from "@/cut/lib/store";
-import { headSrc, matteLumaToAlpha, retimeOf, smoothsAt } from "@donkeycut/effects-kit";
+import { headSrc, retimeOf, smoothsAt } from "@donkeycut/effects-kit";
import { blendInto, SYNTH_EDGE, synthWeight } from "@/cut/lib/frameSynth";
import { playheadAt, previewAt, setPlayhead, subscribePlayhead } from "@/cut/lib/playhead";
import { assetIsSilent, clipCovers, rectOf } from "@/cut/lib/types";
@@ -39,7 +39,7 @@ import {
import { registerSourceColor, registerSourceSampler } from "@/cut/lib/previewCanvas";
import { colorRead, previewFile, type ColorRead } from "@/cut/lib/sourceColor";
import { backdropStill } from "@/cut/lib/backdropStills";
-import { cardMatteKey } from "@/cut/lib/cameraCard";
+import { MatteAlpha } from "@/cut/lib/matteAlpha";
import { createRasterCanvas, type RasterSurface } from "@/cut/lib/raster";
import { disposeDetailGpu } from "@/cut/lib/detailGpu";
@@ -249,12 +249,13 @@ class Engine {
/** Whether the tick being drawn is a playing one — read by the matte
* provider, which the compositor calls mid-frame. */
private renderPlaying = false;
- /** Per removal clip: the last decoded matte luma frame converted to alpha,
+ /** Per matte read: the last decoded matte luma frame converted to alpha,
* so the conversion runs once per new frame rather than once per draw. Keyed
- * by clip — two clips reading the same matte at different times each keep
- * their own frame — and bounded LRU, so a long session's re-bakes and
- * deleted clips never pile up canvases. */
- private matteAlpha = new Map<string, { ts: number; canvas: RasterSurface }>();
+ * by the matte's mapping — a card that takes over its cutout's matte shares
+ * the cutout's conversion, while two clips reading one matte at different
+ * times each keep their own — and bounded LRU, so a long session's re-bakes
+ * and deleted clips never pile up canvases. */
+ private matteAlpha = new Map<string, MatteAlpha>();
private static readonly MATTE_ALPHA_MAX = 8;
/** Per clip, the canvas its smoothed slow motion is blended on. Bounded
* like the mattes: the clips drawn longest ago give theirs up. */
@@ -283,8 +284,8 @@ class Engine {
private presentCanvas: HTMLCanvasElement | null
) {
this.comp = new FrameCompositor(canvas);
- this.comp.removalMatteProvider = (clip, at) => this.matteFor(clip.id, clip.removal?.matte, clip, at);
- this.comp.cardMatteProvider = (clip, at) => this.matteFor(cardMatteKey(clip.id), clip.card?.matte, clip, at);
+ this.comp.removalMatteProvider = (clip, at) => this.matteFor(clip.removal?.matte, clip, at);
+ this.comp.cardMatteProvider = (clip, at) => this.matteFor(clip.card?.matte, clip, at);
// A clip's color recipe describes the frames its source hands over — the
// file that source reads, read the way it reads it; a LUT built off the
// thread repaints when it lands.
@@ -511,11 +512,10 @@ class Engine {
/**
* The alpha matte `m` — a removal clip's, or a camera card's — at timeline
* time `t`: the baked matte video read like any other source, its luma
- * turned into alpha and held under `key`. Null while nothing has decoded
- * yet — the picture draws plain until the matte lands.
+ * turned into alpha and held under the read's mapping. Null while nothing
+ * has decoded yet — the picture draws plain until the matte lands.
*/
private matteFor(
- key: string,
m: { assetId: string; in: number } | undefined,
clip: VideoClip,
at: number
@@ -529,8 +529,9 @@ class Engine {
// Coverage tolerates far less resolution than the picture, and the luma →
// alpha read below is a per-frame pixel pass; capping the matte's decode
// keeps that pass off the frame budget.
+ const key = mappingKey(asset.id, retimeOf(clip), clip.start, m.in);
const src = this.pool.get(
- mappingKey(asset.id, retimeOf(clip), clip.start, m.in),
+ key,
asset,
Math.min(this.decodeHeight(), 480)
);
@@ -543,30 +544,16 @@ class Engine {
);
const frame = src.frameAt(mt, 0, dur);
if (!frame) return null;
- const held = this.matteAlpha.get(key);
- // Re-insert on every touch so the cap below drops the clip drawn longest
+ const alpha = this.matteAlpha.get(key) ?? new MatteAlpha();
+ // Re-insert on every touch so the cap below drops the matte drawn longest
// ago.
this.matteAlpha.delete(key);
- if (held && held.ts === frame.timestamp) {
- this.matteAlpha.set(key, held);
- return held.canvas as CanvasImageSource;
- }
- const canvas = held?.canvas ?? createRasterCanvas(frame.width, frame.height);
- if (canvas.width !== frame.width) canvas.width = frame.width;
- if (canvas.height !== frame.height) canvas.height = frame.height;
- const ctx = canvas.getContext("2d") as CanvasRenderingContext2D | null;
- if (!ctx) return null;
- ctx.clearRect(0, 0, canvas.width, canvas.height);
- ctx.drawImage(frame.image, 0, 0, canvas.width, canvas.height);
- const img = ctx.getImageData(0, 0, canvas.width, canvas.height);
- matteLumaToAlpha(img.data);
- ctx.putImageData(img, 0, 0);
- this.matteAlpha.set(key, { ts: frame.timestamp, canvas });
+ this.matteAlpha.set(key, alpha);
if (this.matteAlpha.size > Engine.MATTE_ALPHA_MAX) {
const oldest = this.matteAlpha.keys().next().value;
if (oldest !== undefined) this.matteAlpha.delete(oldest);
}
- return canvas as CanvasImageSource;
+ return alpha.of(frame, String(frame.timestamp));
}
/**
diff --git a/site/src/cut/lib/aiContext.ts b/site/src/cut/lib/aiContext.ts
index 2573499f..03e0b052 100644
--- a/site/src/cut/lib/aiContext.ts
+++ b/site/src/cut/lib/aiContext.ts
@@ -13,7 +13,7 @@ import type { VideoProject } from "./genvideo/types";
import { playheadAt, skimAt } from "./playhead";
import { cueWordCount } from "./cueChunk";
import { laneCues, subtitleLaneCount } from "./subtitles";
-import { cueEmphasis } from "./captionEmphasis";
+import { emphasizedWords } from "./captionEmphasis";
import { watchSweepActive } from "./watch/sweep";
import { libraryFontId, listLibraryFonts, listLutChoices } from "./linkedLibrary";
import { savedGradesKnown } from "./gradePresets";
@@ -97,7 +97,7 @@ function clipEffects(clip: VideoClip, live: boolean, frame?: CardFrame) {
/** What a camera card's defaults read: the frame shape and the clip's
* source. */
-export interface CardFrame {
+interface CardFrame {
aspect: Aspect;
assetById: Map<string, MediaAsset>;
}
@@ -754,10 +754,9 @@ function describeState(
* [index, word] pairs (set_caption_emphasis), and its own x/y when it sits
* apart from its track (update_cue). Absent when it has neither. */
function cueExtras(c: SubtitleCue) {
- const marked = cueEmphasis(c);
- const words = marked.length > 0 ? c.text.split(/\s+/).filter(Boolean) : [];
+ const emphasis = emphasizedWords(c);
return {
- ...(marked.length > 0 ? { emphasis: marked.map((i) => [i, words[i]] as const) } : {}),
+ ...(emphasis.length > 0 ? { emphasis } : {}),
...(c.x !== undefined && c.y !== undefined ? { x: r(c.x), y: r(c.y) } : {}),
};
}
diff --git a/site/src/cut/lib/aiTools.ts b/site/src/cut/lib/aiTools.ts
index 25c7aa1e..fcb07215 100644
--- a/site/src/cut/lib/aiTools.ts
+++ b/site/src/cut/lib/aiTools.ts
@@ -76,6 +76,7 @@ import {
type OverlayAnimStyle,
type OverlayLoopStyle,
CARET_BLINKS_MAX,
+ displayWords,
edgeMotion,
edgePreset,
OVERLAY_HIT_DEFAULT_SECONDS,
@@ -212,8 +213,8 @@ import { renderStageFrame, storeStageStill } from "./stageFrame";
import { createRasterCanvas, decodeRasterImageUrl, rasterCanvasToDataUrl } from "./raster";
import { buildAiContext, describeCameraCard, describeDoc, hiddenFromChat, placedAssetIds } from "./aiContext";
import { CARD_SIDES, newCard, normalizeCard, type CardSide } from "./cameraCard";
-import { CAPTION_STYLES, captionEmphasis, captionStyle, cueAnchor, EMPHASIS_SCALE_MAX, EMPHASIS_SCALE_MIN, laneCues, subtitleLaneCount, trackPos } from "./subtitles";
-import { cueEmphasis, emphasisIndicesOf } from "./captionEmphasis";
+import { CAPTION_STYLES, captionEmphasis, cueSpot, EMPHASIS_SCALE_MAX, EMPHASIS_SCALE_MIN, laneCues, subtitleLaneCount } from "./subtitles";
+import { cueEmphasis, emphasisIndicesOf, emphasizedWords } from "./captionEmphasis";
import { findHighlights } from "./highlights";
import { fuseTimeline, renderFusedTimeline, speechOnsets, speechOver } from "./watch/fuse";
import {
@@ -2662,7 +2663,7 @@ const toolRuns: Record<BrowserToolName, ToolRun> = {
const edits: { id: string; indices: number[]; on?: boolean }[] = [];
for (const m of marks) {
const cue = requireItem(s.subtitles.cues, m.cue_id, "subtitle cue");
- const count = cue.text.split(/\s+/).filter(Boolean).length;
+ const count = displayWords(cue.text).length;
const indices: number[] = [];
if (Array.isArray(m.indices)) {
for (const i of m.indices) {
@@ -2694,10 +2695,7 @@ const toolRuns: Record<BrowserToolName, ToolRun> = {
return {
cues: cur.cues
.filter((c) => touched.has(c.id))
- .map((c) => {
- const words = c.text.split(/\s+/).filter(Boolean);
- return { id: c.id, text: c.text, emphasis: cueEmphasis(c).map((i) => words[i]) };
- }),
+ .map((c) => ({ id: c.id, text: c.text, emphasis: emphasizedWords(c).map(([, w]) => w) })),
emphasizedCues: cur.cues.filter((c) => cueEmphasis(c).length > 0).length,
...(cur.showOnVideo ? {} : { note: "Captions are hidden on the video; subtitles_set_view shows them." }),
};
@@ -4806,11 +4804,7 @@ const toolRuns: Record<BrowserToolName, ToolRun> = {
const live = st.subtitles.cues.find((c) => c.id === cue.id);
if (live) {
// One side given keeps the other where the caption already sits.
- const at = cueAnchor(
- live,
- trackPos(st.subtitles, captionStyle(st.subtitles.style), live.lane ?? 0),
- captionStyle(st.subtitles.style)
- );
+ const at = cueSpot(st.subtitles, live);
st.pushHistory();
st.setCuePosition(
cue.id,
diff --git a/site/src/cut/lib/cameraCard.ts b/site/src/cut/lib/cameraCard.ts
index c5a1ca3d..4b5f08e3 100644
--- a/site/src/cut/lib/cameraCard.ts
+++ b/site/src/cut/lib/cameraCard.ts
@@ -77,7 +77,7 @@ export const CARD_SCALE_MIN = 0.5;
export const CARD_SCALE_MAX = 3;
export const CARD_OFFSET_MAX = 1;
/** The shadow's blur, design px. */
-export const CARD_SHADOW_BLUR = 60;
+const CARD_SHADOW_BLUR = 60;
/** Boxes at least this wide for their height take a side card. */
const SIDE_ASPECT = 0.999;
@@ -176,7 +176,7 @@ export function aboveShare(aspect: number): number {
/** The side a card takes in a box of `boxAspect` (width / height) when it
* names none. */
-export const defaultCardSide = (boxAspect: number): CardSide => (boxAspect >= SIDE_ASPECT ? "right" : "bottom");
+const defaultCardSide = (boxAspect: number): CardSide => (boxAspect >= SIDE_ASPECT ? "right" : "bottom");
/** A side card's default width share in a box of `boxAspect`. */
export function defaultCardWidth(boxAspect: number): number {
@@ -324,9 +324,6 @@ export function newCard(): CameraCard {
return { ...CARD_DEFAULTS };
}
-/** Whether a clip lays out as a camera card. */
-export const cardActive = (c: { card?: CameraCard }): boolean => !!c.card;
-
/** The key a card's matte job and staged matte frame go under, beside the
* clip's own cutout under its bare id. */
export const cardMatteKey = (clipId: string): string => `card:${clipId}`;
diff --git a/site/src/cut/lib/cameraCardVideo.ts b/site/src/cut/lib/cameraCardVideo.ts
index ed8183ab..433498df 100644
--- a/site/src/cut/lib/cameraCardVideo.ts
+++ b/site/src/cut/lib/cameraCardVideo.ts
@@ -11,46 +11,15 @@
* head, the preview's own degrade.
*/
-import { matteLumaToAlpha, removalActive, retimeOf, type ClipRemoval } from "@donkeycut/effects-kit";
+import { removalActive, retimeOf } from "@donkeycut/effects-kit";
import { openCanvasVideo } from "./canvasVideo";
-import { FrameCompositor, type Frame } from "./composite";
+import { FrameCompositor } from "./composite";
import { ensureClipLuts } from "./lutBuild";
-import { createRasterCanvas, decodeRasterImageUrl, type RasterSurface } from "./raster";
+import { matteStage } from "./matteAlpha";
+import { createRasterCanvas, decodeRasterImageUrl } from "./raster";
import { splitFrame, type RemovalPieces } from "./removalVideo";
import type { MediaAsset, VideoClip } from "./types";
import { liveReader } from "./liveReader";
-import type { ClipReader } from "./exportRender";
-
-type Matte = NonNullable<ClipRemoval["matte"]>;
-
-/** One baked matte read alongside the clip: the frame staged per output
- * frame, luma turned to alpha in a canvas kept for the whole render. */
-export function matteStage(m: Matte | undefined, assets: MediaAsset[]) {
- const asset = m ? assets.find((a) => a.id === m.assetId) : undefined;
- if (!m || !asset) return null;
- const reader: ClipReader = liveReader(asset);
- const canvas: RasterSurface = createRasterCanvas(2, 2);
- const dur = Math.max(0.1, asset.duration || 0.1);
- let ready = false;
- return {
- async stage(srcT: number) {
- ready = false;
- const f: Frame = await reader.frameAt(Math.min(Math.max(0, srcT - m.in), dur - 0.001));
- if (f.kind !== "ready") return;
- if (canvas.width !== f.width) canvas.width = f.width;
- if (canvas.height !== f.height) canvas.height = f.height;
- const ctx = canvas.getContext("2d", { willReadFrequently: true }) as CanvasRenderingContext2D;
- ctx.clearRect(0, 0, f.width, f.height);
- ctx.drawImage(f.image, 0, 0);
- const px = ctx.getImageData(0, 0, f.width, f.height);
- matteLumaToAlpha(px.data);
- ctx.putImageData(px, 0, 0);
- ready = true;
- },
- get: () => (ready ? (canvas as CanvasImageSource) : null),
- dispose: () => reader.dispose(),
- };
-}
/**
* Render one card clip's layer over its segment at `fps`, `box` pixels wide
diff --git a/site/src/cut/lib/captionEmphasis.test.ts b/site/src/cut/lib/captionEmphasis.test.ts
index f71869e8..52448ac1 100644
--- a/site/src/cut/lib/captionEmphasis.test.ts
+++ b/site/src/cut/lib/captionEmphasis.test.ts
@@ -5,6 +5,7 @@ import {
emphasisIndicesOf,
emphasisRuns,
remapEmphasis,
+ typedToggle,
toggleEmphasis,
wordIndicesIn,
} from "./captionEmphasis";
@@ -124,6 +125,15 @@ describe("picking words", () => {
expect(runs.filter((r) => r.em).map((r) => r.text)).toEqual(["big", "win"]);
});
+ test("a toggle on unsaved typing reads the emphasis on the words typed", () => {
+ const cue: SubtitleCue = { id: "c", start: 0, end: 1, text: "buy Notion now", emphasis: [1] };
+ const typed = "please buy Notion now";
+ const at = typed.indexOf("Notion");
+ expect(typedToggle(cue, typed, at, at + 6)).toEqual({ indices: [2], on: false, label: "Notion" });
+ const buy = typed.indexOf("buy");
+ expect(typedToggle(cue, typed, buy, buy + 3)?.on).toBe(true);
+ });
+
test("toggling flips each word and drops the field when empty", () => {
const cue: SubtitleCue = { id: "c", start: 0, end: 1, text: "a b c" };
const on = toggleEmphasis(cue, [0, 2]);
diff --git a/site/src/cut/lib/captionEmphasis.ts b/site/src/cut/lib/captionEmphasis.ts
index f004f083..209f58b7 100644
--- a/site/src/cut/lib/captionEmphasis.ts
+++ b/site/src/cut/lib/captionEmphasis.ts
@@ -31,11 +31,6 @@ export function cueEmphasis(cue: Pick<SubtitleCue, "text" | "emphasis">): number
return out;
}
-/** The field as a cue stores it: absent when nothing is marked. */
-export function emphasisField(marked: readonly number[]): { emphasis?: number[] } {
- return marked.length > 0 ? { emphasis: [...marked] } : {};
-}
-
/** The cue with `indices` set on or off; `on` absent flips each one. */
export function toggleEmphasis(
cue: SubtitleCue,
@@ -51,27 +46,69 @@ export function toggleEmphasis(
return withEmphasis(cue, cueEmphasis({ text: cue.text, emphasis: [...marked] }));
}
-/** The cue carrying exactly `marked`. */
+/** The cue carrying exactly `marked`, the field absent when nothing is. */
export function withEmphasis(cue: SubtitleCue, marked: readonly number[]): SubtitleCue {
const out: SubtitleCue = { ...cue };
delete out.emphasis;
- return { ...out, ...emphasisField(marked) };
+ if (marked.length > 0) out.emphasis = [...marked];
+ return out;
}
-/** The emphasis of words [from, to) of a cue, re-indexed from 0 — one half of
- * a split. */
-export function sliceEmphasis(marked: readonly number[], from: number, to: number): number[] {
+/** The emphasis of words [from, to) of a cue, re-indexed from 0. */
+function sliceEmphasis(marked: readonly number[], from: number, to: number): number[] {
return marked.filter((i) => i >= from && i < to).map((i) => i - from);
}
-/** Two cues' emphasis joined, the second's words following the first's
- * `count` — a merge. */
-export function joinEmphasis(
- first: readonly number[],
- count: number,
- second: readonly number[]
+/** A split's two halves of `cue`'s emphasis: the left takes the marks of its
+ * first words, the right those of its last. A word cut in two is in both
+ * halves, so both pieces keep its mark. */
+export function splitEmphasis(
+ cue: Pick<SubtitleCue, "text" | "emphasis">,
+ leftText: string,
+ rightText: string
+): [number[], number[]] {
+ const marked = cueEmphasis(cue);
+ const from = Math.max(0, displayWords(cue.text).length - displayWords(rightText).length);
+ return [sliceEmphasis(marked, 0, displayWords(leftText).length), sliceEmphasis(marked, from, Infinity)];
+}
+
+/** A merge's emphasis: `first`'s marks, then `second`'s after its words. */
+export function mergeEmphasis(
+ first: Pick<SubtitleCue, "text" | "emphasis">,
+ second: Pick<SubtitleCue, "text" | "emphasis">
): number[] {
- return [...first, ...second.map((i) => i + count)];
+ const count = displayWords(first.text).length;
+ return [...cueEmphasis(first), ...cueEmphasis(second).map((i) => i + count)];
+}
+
+/** A cue's emphasized words as [index, word] pairs. */
+export function emphasizedWords(cue: Pick<SubtitleCue, "text" | "emphasis">): [number, string][] {
+ const marked = cueEmphasis(cue);
+ if (marked.length === 0) return [];
+ const words = displayWords(cue.text);
+ return marked.map((i) => [i, words[i]]);
+}
+
+/** What a toggle over characters [from, to) of `typed` — the caption's text
+ * as it is on screen, maybe not yet saved — would do: the words it names,
+ * whether it turns them on, and their label. The cue's saved emphasis is
+ * carried onto the typed words first, so the answer is about the words the
+ * person sees. Null when the range touches no word. */
+export function typedToggle(
+ cue: Pick<SubtitleCue, "text" | "emphasis">,
+ typed: string,
+ from: number,
+ to: number
+): { indices: number[]; on: boolean; label: string } | null {
+ const indices = wordIndicesIn(typed, from, to);
+ if (indices.length === 0) return null;
+ const marked = new Set(remapEmphasis(cue.text, typed, cueEmphasis(cue)));
+ const words = displayWords(typed);
+ return {
+ indices,
+ on: !indices.every((i) => marked.has(i)),
+ label: indices.map((i) => words[i]).join(" "),
+ };
}
/** A word reduced to what identifies it across a rewrite: case and the
diff --git a/site/src/cut/lib/composite.ts b/site/src/cut/lib/composite.ts
index 77451fb2..d771e8a1 100644
--- a/site/src/cut/lib/composite.ts
+++ b/site/src/cut/lib/composite.ts
@@ -20,7 +20,7 @@
*/
import { applyDetail, applyEffectToCanvas, applyLutToImageData, applyMaskToCanvas, detailActive, grainTile, hexToHlgHex, lookCssFilter, lookPost, maskComposite, paintStrokeInk, removalActive, retimeOf, type ClipColorRecipe, type OutputSpace } from "@donkeycut/effects-kit";
-import { cameraCardLayout, cardActive, traceCardPath, type CardLayout } from "./cameraCard";
+import { cameraCardLayout, traceCardPath, type CardLayout } from "./cameraCard";
import { applyDetailGpu } from "./detailGpu";
import { applyLutGpu } from "./gradeGpu";
import { clipRecipe, peekClipLut, requestClipLut, type ClipLut, type RecipeSource } from "./lutBuild";
@@ -708,7 +708,7 @@ export class FrameCompositor {
!!clip &&
(clipPosed(clip) ||
// A camera card casts its own shadow; the box style stands aside.
- (!!clip.boxStyle?.shadow && !cardActive(clip)) ||
+ (!!clip.boxStyle?.shadow && !clip.card) ||
!!(clip.mask && (clip.mask.kind !== "subject" || this.subjectMatteProvider)))
);
}
@@ -816,7 +816,7 @@ export class FrameCompositor {
ctx.save();
ctx.translate(Math.round(fx.dx ?? 0), Math.round(fx.dy ?? 0));
}
- const shade = cardActive(clip) ? null : this.shadowOf(out, clip.boxStyle?.shadow);
+ const shade = clip.card ? null : this.shadowOf(out, clip.boxStyle?.shadow);
if (shade) ctx.drawImage(shade, 0, 0);
ctx.drawImage(out, 0, 0);
if (hasFx) ctx.restore();
@@ -873,7 +873,7 @@ export class FrameCompositor {
);
return;
}
- if (clip && cardActive(clip)) {
+ if (clip?.card) {
this.drawCard(frame, rect, alpha, at, zoom, clip);
return;
}
@@ -1207,7 +1207,7 @@ export class FrameCompositor {
// styled box (rounded corners, border) or a mirrored picture also routes
// through the rect path, which knows how to draw those at full frame too.
const rect = rectOf(clip ?? {});
- if (!isFullRect(rect) || clip?.boxStyle || clip?.flipH || clip?.flipV || (clip && cardActive(clip))) {
+ if (!isFullRect(rect) || clip?.boxStyle || clip?.flipH || clip?.flipV || !!clip?.card) {
this.drawIntoRect(frame, rect, !!clip && clipCovers(clip), alpha, at, zoom, clip);
if (hasFx) ctx.restore();
return;
diff --git a/site/src/cut/lib/exportClient.ts b/site/src/cut/lib/exportClient.ts
index 40286be4..9ae36e70 100644
--- a/site/src/cut/lib/exportClient.ts
+++ b/site/src/cut/lib/exportClient.ts
@@ -25,7 +25,6 @@ import { planStems, type StemDef } from "./stems";
import { putSigned } from "./media";
import { withAssetColors } from "./mediaRead";
import { renderRemovalPieces } from "./removalVideo";
-import { cardActive } from "./cameraCard";
import { renderCardPieces } from "./cameraCardVideo";
import { drawBlock } from "./blockSource";
import { createRasterCanvas, rasterCanvasToPng } from "./raster";
@@ -819,7 +818,7 @@ export function specColor(
/** A camera card draws its own corners and shadow, so its clip's box style
* stands aside in every painted picture (mask corners, border, shadow). */
-const cardBoxless = (c: VideoClip): VideoClip => (cardActive(c) && c.boxStyle ? { ...c, boxStyle: undefined } : c);
+const cardBoxless = (c: VideoClip): VideoClip => (c.card && c.boxStyle ? { ...c, boxStyle: undefined } : c);
/** The spec fields of a camera-card clip whose layer ships as `<tag>`
* pieces: the pair stands in for the source, already framed to the box,
@@ -1031,7 +1030,7 @@ export async function buildExportPayload(
// matte yet — the export shows the plain picture, like the preview); a
// broken render throws and fails the export instead of silently dropping
// the cutout.
- if (cardActive(c) && !c.hidden) {
+ if (c.card && !c.hidden) {
const rp = regionPx(c.frame, settings.width, settings.height);
const pieces = await renderCardPieces(spans[i].asset, spans[i].clip, doc.assets, {
fps: settings.fps,
@@ -1242,7 +1241,7 @@ export async function buildExportPayload(
// applies no grade or look to it — both bake into the pieces here, the
// way image overlays already carry their pixels ready-made.
const oAsset = assetById.get(c.assetId);
- if (cardActive(c) && oAsset) {
+ if (c.card && oAsset) {
const pieces = await renderCardPieces(oAsset, c, doc.assets, {
fps: settings.fps,
frameW: settings.width,
diff --git a/site/src/cut/lib/exportRender.ts b/site/src/cut/lib/exportRender.ts
index 67ea0cca..b5cc32a7 100644
--- a/site/src/cut/lib/exportRender.ts
+++ b/site/src/cut/lib/exportRender.ts
@@ -47,9 +47,10 @@ import { getClipSpans, overlayLayers, projectDuration, spanSequence } from "./st
import { captionStyle, cueOverlay, cueWordFrames, laneCues, laneHidden, subtitleLaneCount, trackPos } from "./subtitles";
import { ElementFx, elementLook } from "@donkeycut/effects-kit";
import { darkenCanvas } from "@donkeycut/effects-kit";
-import { applyEffectToCanvas, diveView, divesAt, evalOverlayFrame, measureDiveFocus, retimeOf, grainTile, smoothsAt, isAudioEffect, isMaskAnimated, isOverlayAnimated, maskFrameAt, MATTE_FPS, matteLumaToAlpha, planAnimatedLayers, type DiveFocus, type LottieHandle, type OverlayAnim, type PaintPhase } from "@donkeycut/effects-kit";
+import { applyEffectToCanvas, diveView, divesAt, evalOverlayFrame, measureDiveFocus, retimeOf, grainTile, smoothsAt, isAudioEffect, isMaskAnimated, isOverlayAnimated, maskFrameAt, planAnimatedLayers, type DiveFocus, type LottieHandle, type OverlayAnim, type PaintPhase } from "@donkeycut/effects-kit";
import { backdropStill, loadBackdropStill } from "./backdropStills";
import { hasSubjectOverlays, SubjectMaskCompositor } from "./behindPass";
+import { MatteAlpha, matteStamp } from "./matteAlpha";
import { createRasterCanvas, type RasterSurface } from "./raster";
import { exportFrameSynth, SYNTH_EDGE, synthWeight, type FrameSynth } from "./frameSynth";
import { cutRenderEnv, renderElementCanvas, renderElementPng } from "./textRender";
@@ -1448,11 +1449,9 @@ export class FramePainter {
* with the layer frames (readers are async) and read synchronously by the
* compositor's provider mid-draw. */
private matteFrames = new Map<string, CanvasImageSource>();
- /** Per-clip conversion scratch for those mattes (luma frame → alpha). */
- private matteScratch = new Map<string, RasterSurface>();
- /** Which matte frame each scratch currently holds, so the luma → alpha
- * pixel pass runs once per matte frame. */
- private matteStamp = new Map<string, string>();
+ /** Per-clip conversion of those mattes (luma frame → alpha), run once per
+ * matte frame. */
+ private matteAlpha = new Map<string, MatteAlpha>();
/** Text layers, deepest lane first — so a walk of them is a walk up the stack. */
private stacked: StampedLayer[] = [];
private spans: ClipSpan[] = [];
@@ -1640,29 +1639,15 @@ export class FramePainter {
if (!asset) return;
const dur = Math.max(0.001, asset.duration);
const mt = Math.max(0, Math.min(sourceTimeAt(span, t) - m.in, dur - 0.001));
- const frame = await this.readerFor(asset).frameAt(mt);
- if (frame.kind !== "ready") return;
- let scratch = this.matteScratch.get(key);
+ let alpha = this.matteAlpha.get(key);
+ if (!alpha) this.matteAlpha.set(key, (alpha = new MatteAlpha()));
// The matte advances at its own baked rate below the export's, so a
- // converted frame is reused until the read crosses into the next one —
- // the pixel pass is per matte frame, never per output frame.
- const stamp = `${m.assetId}:${Math.floor(mt * MATTE_FPS)}`;
- if (scratch && this.matteStamp.get(key) === stamp) {
- this.matteFrames.set(key, scratch as CanvasImageSource);
- return;
- }
- if (!scratch) this.matteScratch.set(key, (scratch = createRasterCanvas(frame.width, frame.height)));
- if (scratch.width !== frame.width) scratch.width = frame.width;
- if (scratch.height !== frame.height) scratch.height = frame.height;
- const ctx = scratch.getContext("2d") as CanvasRenderingContext2D | null;
- if (!ctx) return;
- ctx.clearRect(0, 0, scratch.width, scratch.height);
- ctx.drawImage(frame.image, 0, 0, scratch.width, scratch.height);
- const img = ctx.getImageData(0, 0, scratch.width, scratch.height);
- matteLumaToAlpha(img.data);
- ctx.putImageData(img, 0, 0);
- this.matteStamp.set(key, stamp);
- this.matteFrames.set(key, scratch as CanvasImageSource);
+ // converted frame is reused until the read crosses into the next one.
+ const stamp = matteStamp(m.assetId, mt);
+ const held = alpha.held(stamp);
+ const frame = held ? null : await this.readerFor(asset).frameAt(mt);
+ const img = held ?? (frame?.kind === "ready" ? alpha.of(frame, stamp) : null);
+ if (img) this.matteFrames.set(key, img);
}
/** Draw the whole cut at timeline time `t` onto the canvas. */
diff --git a/site/src/cut/lib/itemKinds.ts b/site/src/cut/lib/itemKinds.ts
index af49c79a..76c623aa 100644
--- a/site/src/cut/lib/itemKinds.ts
+++ b/site/src/cut/lib/itemKinds.ts
@@ -14,7 +14,7 @@
// every entry proves it copies and pastes.
import { KEY_EPSILON, maskKeyAt, poseAt, retimeOf, shiftCamera, type Mask, type OverlayKey, type OverlayPose } from "@donkeycut/effects-kit";
-import { cueEmphasis, sliceEmphasis, withEmphasis } from "./captionEmphasis";
+import { splitEmphasis, withEmphasis } from "./captionEmphasis";
import {
clipPoseAt,
fontAssetId,
@@ -228,13 +228,11 @@ export const ITEM_KINDS: { [K in ItemKind]: ItemKindDef<K> } = {
const offset = Math.round(c.text.length * ((at - c.start) / (c.end - c.start)));
const leftText = left?.length ? left.map((w) => w.w).join(" ") : c.text.slice(0, offset).trim() || c.text;
const rightText = right?.length ? right.map((w) => w.w).join(" ") : c.text.slice(offset).trim() || c.text;
- // Each half keeps the emphasis of the words it took, a word cut in two
- // on both sides.
- const marked = cueEmphasis(c);
- const count = (t: string) => t.split(/\s+/).filter(Boolean).length;
+ // Each half keeps the emphasis of the words it took.
+ const [leftMarks, rightMarks] = splitEmphasis(c, leftText, rightText);
return [
- withEmphasis({ ...c, end: at, text: leftText, words: left?.length ? left : undefined }, sliceEmphasis(marked, 0, count(leftText))),
- withEmphasis({ ...c, start: at, text: rightText, words: right?.length ? right : undefined }, sliceEmphasis(marked, Math.max(0, count(c.text) - count(rightText)), Infinity)),
+ withEmphasis({ ...c, end: at, text: leftText, words: left?.length ? left : undefined }, leftMarks),
+ withEmphasis({ ...c, start: at, text: rightText, words: right?.length ? right : undefined }, rightMarks),
];
},
clone: deep,
diff --git a/site/src/cut/lib/maskVideo.ts b/site/src/cut/lib/maskVideo.ts
index 12a65c28..59c7804f 100644
--- a/site/src/cut/lib/maskVideo.ts
+++ b/site/src/cut/lib/maskVideo.ts
@@ -33,7 +33,7 @@ import { getClipSpans } from "./store";
import { clipCovers, frameOf, isEffectOverlay, isTextOverlay, rectOf, subjectMasked, type ClipSpan, type MediaAsset, type VideoClip } from "./types";
import { liveReader } from "./liveReader";
import { cardMatteKey } from "./cameraCard";
-import { matteStage } from "./cameraCardVideo";
+import { matteStage } from "./matteAlpha";
/** Encoded mask rate — the server's fps filter duplicates frames up to the
* output rate, and a person moves little in 1/15s. */
diff --git a/site/src/cut/lib/matteAlpha.ts b/site/src/cut/lib/matteAlpha.ts
new file mode 100644
index 00000000..3b8d4cd5
--- /dev/null
+++ b/site/src/cut/lib/matteAlpha.ts
@@ -0,0 +1,82 @@
+/**
+ * Baked mattes turned into alpha. A matte bakes as a luma video — white where
+ * the subject is — and the compositor wants it as an alpha picture, so every
+ * reader of a matte runs the same pixel pass: draw the frame, read it back,
+ * move luma into alpha. The pass is a full read of the matte's pixels, and a
+ * matte advances at its own baked rate (MATTE_FPS) below any output rate, so
+ * the pass runs once per matte frame and every draw in between reuses it.
+ */
+
+import { matteLumaToAlpha, MATTE_FPS, type ClipRemoval } from "@donkeycut/effects-kit";
+import { liveReader } from "./liveReader";
+import { createRasterCanvas, type RasterSurface } from "./raster";
+import type { MediaAsset } from "./types";
+
+type Matte = NonNullable<ClipRemoval["matte"]>;
+
+/** A decoded matte frame, as any reader hands it over. */
+interface MatteFrame {
+ image: CanvasImageSource;
+ width: number;
+ height: number;
+}
+
+/** Which baked matte frame source time `mt` falls in — equal stamps are the
+ * same pixels. */
+export const matteStamp = (assetId: string, mt: number): string =>
+ `${assetId}:${Math.floor(mt * MATTE_FPS)}`;
+
+/** One matte's alpha picture, held on a single surface and converted only
+ * when the frame's stamp moves. */
+export class MatteAlpha {
+ private surface: RasterSurface | null = null;
+ private stamp: string | null = null;
+
+ /** The picture of `stamp` when it is the one already converted. */
+ held(stamp: string): CanvasImageSource | null {
+ return this.surface && this.stamp === stamp ? (this.surface as CanvasImageSource) : null;
+ }
+
+ /** `frame`'s alpha picture, converted unless `stamp` is already held. */
+ of(frame: MatteFrame, stamp: string): CanvasImageSource | null {
+ const held = this.held(stamp);
+ if (held) return held;
+ const s = this.surface ?? (this.surface = createRasterCanvas(frame.width, frame.height));
+ if (s.width !== frame.width) s.width = frame.width;
+ if (s.height !== frame.height) s.height = frame.height;
+ const ctx = s.getContext("2d", { willReadFrequently: true }) as CanvasRenderingContext2D | null;
+ if (!ctx) return null;
+ ctx.clearRect(0, 0, s.width, s.height);
+ ctx.drawImage(frame.image, 0, 0, s.width, s.height);
+ const px = ctx.getImageData(0, 0, s.width, s.height);
+ matteLumaToAlpha(px.data);
+ ctx.putImageData(px, 0, 0);
+ this.stamp = stamp;
+ return s as CanvasImageSource;
+ }
+}
+
+/** One baked matte read alongside a clip in an export pass: `stage` before
+ * each output frame, then `get` reads the alpha picture for that frame. A
+ * stamp already converted skips both the read and the pixel pass. Null when
+ * there is no matte or its asset is gone. */
+export function matteStage(m: Matte | undefined, assets: MediaAsset[]) {
+ const asset = m ? assets.find((a) => a.id === m.assetId) : undefined;
+ if (!m || !asset) return null;
+ const reader = liveReader(asset);
+ const alpha = new MatteAlpha();
+ const dur = Math.max(0.1, asset.duration || 0.1);
+ let ready: CanvasImageSource | null = null;
+ return {
+ async stage(srcT: number) {
+ const mt = Math.min(Math.max(0, srcT - m.in), dur - 0.001);
+ const stamp = matteStamp(m.assetId, mt);
+ ready = alpha.held(stamp);
+ if (ready) return;
+ const f = await reader.frameAt(mt);
+ ready = f.kind === "ready" ? alpha.of(f, stamp) : null;
+ },
+ get: () => ready,
+ dispose: () => reader.dispose(),
+ };
+}
diff --git a/site/src/cut/lib/removalVideo.ts b/site/src/cut/lib/removalVideo.ts
index f4992408..10e362e5 100644
--- a/site/src/cut/lib/removalVideo.ts
+++ b/site/src/cut/lib/removalVideo.ts
@@ -10,10 +10,11 @@
* channel, which is why the layer travels as a pair.
*/
-import { matteLumaToAlpha, removalActive, retimeOf } from "@donkeycut/effects-kit";
+import { removalActive, retimeOf } from "@donkeycut/effects-kit";
import { openCanvasVideo, scaledEvenSize } from "./canvasVideo";
-import { FrameCompositor, type Frame } from "./composite";
+import { FrameCompositor } from "./composite";
import { ensureClipLuts } from "./lutBuild";
+import { matteStage } from "./matteAlpha";
import { createRasterCanvas, decodeRasterImageUrl, type RasterSurface } from "./raster";
import type { MediaAsset, VideoClip } from "./types";
import { liveReader } from "./liveReader";
@@ -69,17 +70,15 @@ export async function renderRemovalPieces(
): Promise<RemovalPieces | null> {
const r = clip.removal;
if (!removalActive(r) || !r) return null;
- const matteAsset = r.matte ? assets.find((a) => a.id === r.matte!.assetId) : undefined;
- if (!matteAsset) return null;
+ const matte = matteStage(r.matte, assets);
+ if (!matte) return null;
const rt = retimeOf(clip);
const still = asset.type === "image";
const dur = Math.max(0.1, rt.len);
const frames = Math.max(1, Math.ceil(dur * opts.fps));
- const baked = clip.removal!.matte;
const reader = liveReader(asset);
- const matteReader = matteAsset ? liveReader(matteAsset) : null;
try {
const first = await reader.frameAt(still ? 0 : clip.in);
if (first.kind !== "ready") throw new Error("The removal clip's picture could not be read.");
@@ -116,7 +115,6 @@ export async function renderRemovalPieces(
comp.sourceProvider = () => reader.colorRead.recipe();
const bakeClip = opts.bakeLook ? clip : { ...clip, look: undefined };
await ensureClipLuts([comp.recipeFor(bakeClip)]);
- const matteFrame = createRasterCanvas(2, 2);
// The alpha plane's staging buffer, rewritten whole every frame.
const alphaPlane = new ImageData(w, h);
const backdrops = new Map<string, CanvasImageSource | null>();
@@ -126,25 +124,7 @@ export async function renderRemovalPieces(
backdrops.set(r.backdrop.assetId, img ? img.source : null);
}
comp.backdropImageProvider = (assetId) => backdrops.get(assetId) ?? null;
- let matteReady: Frame | null = null;
- comp.removalMatteProvider = () => {
- if (matteReady?.kind !== "ready") return null;
- // Luma to alpha, once per staged frame.
- const mw = matteReady.width;
- const mh = matteReady.height;
- if (matteFrame.width !== mw || matteFrame.height !== mh) {
- matteFrame.width = mw;
- matteFrame.height = mh;
- }
- const mctx = matteFrame.getContext("2d", {
- willReadFrequently: true,
- }) as CanvasRenderingContext2D;
- mctx.drawImage(matteReady.image, 0, 0);
- const mpx = mctx.getImageData(0, 0, mw, mh);
- matteLumaToAlpha(mpx.data);
- mctx.putImageData(mpx, 0, 0);
- return matteFrame as CanvasImageSource;
- };
+ comp.removalMatteProvider = () => matte.get();
for (let i = 0; i < frames; i++) {
const s = Math.min(dur - 1 / (opts.fps * 2), i / opts.fps);
@@ -156,12 +136,7 @@ export async function renderRemovalPieces(
alphaCtx.fillStyle = "#000000";
alphaCtx.fillRect(0, 0, w, h);
} else {
- matteReady = null;
- if (matteReader && baked) {
- const mdur = Math.max(0.1, matteAsset!.duration || 0.1);
- const mt = Math.min(Math.max(0, srcT - baked.in), mdur - 0.001);
- matteReady = await matteReader.frameAt(mt);
- }
+ await matte.stage(srcT);
const layer = comp.removedLayer(frame, bakeClip, clip.start + s, {
bakeLookPost: opts.bakeLook,
});
@@ -173,6 +148,6 @@ export async function renderRemovalPieces(
return { rgb: await rgbOut.finish(), alpha: await alphaOut.finish() };
} finally {
reader.dispose();
- matteReader?.dispose();
+ matte.dispose();
}
}
diff --git a/site/src/cut/lib/store.ts b/site/src/cut/lib/store.ts
index 563579ec..40c6ac45 100644
--- a/site/src/cut/lib/store.ts
+++ b/site/src/cut/lib/store.ts
@@ -91,7 +91,7 @@ import { useGenNotify } from "./genNotify";
import { clampPlayhead, playheadAt, previewAt, setPlayhead, setSkim } from "./playhead";
import { engineTranscribeSamples, withEngineStt } from "./localStt";
import { laneCues, subtitleLaneCount, trackLocale } from "./subtitles";
-import { cueEmphasis, emphasisField, joinEmphasis, remapEmphasis, sliceEmphasis, toggleEmphasis, withEmphasis } from "./captionEmphasis";
+import { cueEmphasis, mergeEmphasis, remapEmphasis, splitEmphasis, toggleEmphasis, withEmphasis } from "./captionEmphasis";
import { clipboardItemAssetIds, clipboardItemFor, listedAssetIds, type TimelineClipboardItem } from "./itemKinds";
import { ANIM_STYLE_IDS, animStyleOfTransition, assetIsSilent, clipPoseAt, DEFAULT_BACKGROUND, emptySubtitles, frameOf, IMAGE_CLIP_SECONDS, isAudioTransition, fontAssetId, isEffectOverlay, isStickerOverlay, MAX_SUBTITLE_LANES, mediaUrl, migrateBehindSubject, migrateLegacyTransitions, normalizeAspect, overlayAnimStyle, projectBackground, SPEED_FLOOR, SPEED_MIN, stampOverlayKinds, stripDefaultOverlayKinds, isTimelineId, sanitizeTimelines, timelineAspect, TRANSITION_MAX, TRANSITION_STYLE_IDS, transitionBarAt, transitionBarStart, transitionStyleOfAnim, type TransitionBoundaryKind } from "./types";
import { liftMoveTracks } from "./textMotion";
@@ -4935,7 +4935,6 @@ export const useEditor = create<EditorState>((baseSet, get, api) => {
let rightStart: number;
let leftWords: SubtitleCue["words"];
let rightWords: SubtitleCue["words"];
- const marked = cueEmphasis(cue);
if (cue.words && cue.words.length > 1) {
// Word timings are intact: split on the word under the caret so both
// halves keep real timestamps.
@@ -4960,27 +4959,26 @@ export const useEditor = create<EditorState>((baseSet, get, api) => {
push();
const leftText = leftWords ? leftWords.map((w) => w.w).join(" ") : before;
const rightText = rightWords ? rightWords.map((w) => w.w).join(" ") : after;
- // Each half keeps the emphasis of the words it took. A caret inside a
- // word leaves a piece of it on both sides, and both pieces keep it.
- const count = (t: string) => t.split(/\s+/).filter(Boolean).length;
+ // Each half keeps the emphasis of the words it took.
+ const [leftMarks, rightMarks] = splitEmphasis(cue, leftText, rightText);
const left: SubtitleCue = withEmphasis(
{ ...cue, end: leftEnd, text: leftText, words: leftWords },
- sliceEmphasis(marked, 0, count(leftText))
+ leftMarks
);
// The second half keeps the track and the spot the caption sat on.
- const right: SubtitleCue = {
- id: uid(),
- start: rightStart,
- end: cue.end,
- text: rightText,
- words: rightWords,
- ...emphasisField(
- sliceEmphasis(marked, count(cue.text) - count(rightText), Infinity)
- ),
- ...(cue.lane ? { lane: cue.lane } : {}),
- ...(cue.x !== undefined ? { x: cue.x } : {}),
- ...(cue.y !== undefined ? { y: cue.y } : {}),
- };
+ const right: SubtitleCue = withEmphasis(
+ {
+ id: uid(),
+ start: rightStart,
+ end: cue.end,
+ text: rightText,
+ words: rightWords,
+ ...(cue.lane ? { lane: cue.lane } : {}),
+ ...(cue.x !== undefined ? { x: cue.x } : {}),
+ ...(cue.y !== undefined ? { y: cue.y } : {}),
+ },
+ rightMarks
+ );
set((cur) => ({
subtitles: {
...cur.subtitles,
@@ -5008,11 +5006,7 @@ export const useEditor = create<EditorState>((baseSet, get, api) => {
text: `${prev.text} ${cue.text}`.replace(/\s+/g, " ").trim(),
words: prev.words && cue.words ? [...prev.words, ...cue.words] : undefined,
},
- joinEmphasis(
- cueEmphasis(prev),
- prev.text.split(/\s+/).filter(Boolean).length,
- cueEmphasis(cue)
- )
+ mergeEmphasis(prev, cue)
);
set((s) => ({
subtitles: {
diff --git a/site/src/cut/lib/subtitles.ts b/site/src/cut/lib/subtitles.ts
index dc9b807c..17664846 100644
--- a/site/src/cut/lib/subtitles.ts
+++ b/site/src/cut/lib/subtitles.ts
@@ -118,6 +118,15 @@ export function cueAnchor(
return { x: cue.x ?? track?.x ?? style.x, y: cue.y ?? track?.y ?? style.y };
}
+/** Where one caption sits in `subs`, its track and style filled in. */
+export function cueSpot(
+ subs: SubtitlesBlock,
+ cue: Pick<SubtitleCue, "x" | "y" | "lane">
+): { x: number; y: number } {
+ const style = captionStyle(subs.style);
+ return cueAnchor(cue, trackPos(subs, style, cue.lane ?? 0), style);
+}
+
/** How emphasized caption words look when the track names nothing: a bold
* italic serif in yellow, at the caption's own size. */
export const CAPTION_EMPHASIS_DEFAULT: Readonly<Required<WordFace>> = {