Skip to content

Open source CapCut alternative.

TypeScript

feat(cut): generalize aspect to arbitrary W:H ratios [rebuild]

David Lee7d51bacd2d8
diff --git a/site/src/cut/components/GeneratePanel.tsx b/site/src/cut/components/GeneratePanel.tsx
index 82eded33..74253f19 100644
--- a/site/src/cut/components/GeneratePanel.tsx
+++ b/site/src/cut/components/GeneratePanel.tsx
@@ -20,6 +20,7 @@ import { useLightbox } from "@/cut/lib/lightbox";
import { refsFromDroppedFiles } from "@/cut/lib/refMedia";
import { characterPrompt, stockTitle } from "@/cut/lib/stock";
import { useEditor } from "@/cut/lib/store";
+import { nearestAspect } from "@/cut/lib/types";
import { useLocalPref } from "@/cut/lib/uiState";
import { useVideoGen } from "@/cut/lib/videoGen";
import {
@@ -76,12 +77,16 @@ export function GenerateVideoPanel({ projectId }: { projectId: string }) {
// Every knob renders from — and is clamped to — what the selected model
// supports, so a stored pick from another model can never reach the API.
const model = VIDEO_MODELS.find((m) => m.tier === tier) ?? VIDEO_MODELS[0];
- const effAspect = model.aspects.includes(aspect) ? aspect : model.aspects[0];
+ const effAspect = nearestAspect(aspect, model.aspects);
// Default the shape to the project's own orientation when the panel opens,
- // same as the image panel (the user can still pick the other one).
+ // same as the image panel (the user can still pick the other one). A custom
+ // project ratio seeds the closest shape the model renders.
useEffect(() => {
- useVideoGen.getState().setAspect(useEditor.getState().aspect);
+ useVideoGen
+ .getState()
+ .setAspect(nearestAspect(useEditor.getState().aspect, model.aspects));
+ // eslint-disable-next-line react-hooks/exhaustive-deps -- mount-time seed only
}, []);
const go = () => {
diff --git a/site/src/cut/components/ImageGenPanel.tsx b/site/src/cut/components/ImageGenPanel.tsx
index 5beba71d..5c9b140f 100644
--- a/site/src/cut/components/ImageGenPanel.tsx
+++ b/site/src/cut/components/ImageGenPanel.tsx
@@ -19,7 +19,7 @@ import {
import { useLightbox } from "@/cut/lib/lightbox";
import { refsFromDroppedFiles } from "@/cut/lib/refMedia";
import { useEditor } from "@/cut/lib/store";
-import type { MediaAsset } from "@/cut/lib/types";
+import { nearestAspect, type MediaAsset } from "@/cut/lib/types";
import { cn } from "@/lib/utils";
import { MentionTextarea, RefChips, RefHandlePill } from "./AssetRefs";
import { DictationControl } from "./MicDictation";
@@ -87,7 +87,11 @@ export function ImageGenPanel({ projectId }: { projectId: string }) {
// a widescreen project generates landscape images by default (the user can
// still pick another size). 1:1 has no project counterpart.
useEffect(() => {
- useImageGen.getState().setAspect(useEditor.getState().aspect);
+ useImageGen
+ .getState()
+ .setAspect(
+ nearestAspect(useEditor.getState().aspect, Object.keys(ASPECT_WORD) as ImageAspect[])
+ );
}, []);
const go = () => {
diff --git a/site/src/cut/components/OverlayLayer.tsx b/site/src/cut/components/OverlayLayer.tsx
index 20e385aa..8c3f5ebc 100644
--- a/site/src/cut/components/OverlayLayer.tsx
+++ b/site/src/cut/components/OverlayLayer.tsx
@@ -21,7 +21,7 @@ import {
plateFill,
SHADOW,
} from "@/cut/lib/textRender";
-import { FRAME, fontStack, type TextOverlay } from "@/cut/lib/types";
+import { frameOf, fontStack, type TextOverlay } from "@/cut/lib/types";
import { cn } from "@/lib/utils";
// Plate geometry as CSS, kept in lockstep with the export burn-in metrics.
@@ -63,7 +63,7 @@ export function OverlayLayer({ stageWidth }: { stageWidth: number }) {
else boxes.current.delete(id);
}, []);
- const stageHeight = (stageWidth * FRAME[aspect].h) / FRAME[aspect].w;
+ const stageHeight = (stageWidth * frameOf(aspect).h) / frameOf(aspect).w;
// Figma-style smart snapping: while dragging an item, pull its left/center/
// right edges to the frame edges, safe margins, center line, and the edges
@@ -236,7 +236,14 @@ function SubtitleCaption({
// Captions ride the same style/opener/anchor logic as the export burn-in,
// so the preview and the rendered file match exactly.
const style = captionStyle(subtitles.style);
- const ov = cueOverlay(cue, style, cue.id === cues[0]?.id, trackPos(subtitles, style, lane));
+ const ov = cueOverlay(
+ cue,
+ style,
+ cue.id === cues[0]?.id,
+ trackPos(subtitles, style, lane),
+ undefined,
+ frameOf(aspect).w
+ );
// Karaoke: the word under the playhead lights up as it is spoken.
const wordIndex = subtitles.wordHighlight
? cueWordWindows(cue).findIndex((w) => t >= w.start && t < w.end)
@@ -262,7 +269,7 @@ function SubtitleCaption({
textDecorationThickness: "0.07em",
textUnderlineOffset: "0.14em",
};
- const scale = stageWidth / FRAME[aspect].w;
+ const scale = stageWidth / frameOf(aspect).w;
return (
<div
ref={(el) => registerBox(subtitleBoxId(lane), el)}
@@ -344,7 +351,7 @@ function OverlayItem({
const [editing, setEditing] = useState(false);
const editRef = useRef<HTMLDivElement>(null);
const boxRef = useRef<HTMLDivElement>(null);
- const frame = useEditor((s) => FRAME[s.aspect]);
+ const frame = frameOf(useEditor((s) => s.aspect));
const scale = stageWidth / frame.w;
const stageHeight = (stageWidth * frame.h) / frame.w;
diff --git a/site/src/cut/components/Preview.tsx b/site/src/cut/components/Preview.tsx
index fa2c919e..9bf9c1b6 100644
--- a/site/src/cut/components/Preview.tsx
+++ b/site/src/cut/components/Preview.tsx
@@ -6,7 +6,7 @@ import { clearAssetDrag, setAssetDragData } from "@/cut/lib/assetDrag";
import { startDrag } from "@/cut/lib/drag";
import { getClipSpans, useEditor } from "@/cut/lib/store";
import { setPreviewCanvas } from "@/cut/lib/previewCanvas";
-import { FRAME, isFullRect, rectOf, type Aspect, type ClipSpan, type FrameRect, type MediaAsset, type VideoClip } from "@/cut/lib/types";
+import { frameOf, isFullRect, rectOf, type Aspect, type ClipSpan, type FrameRect, type MediaAsset, type VideoClip } from "@/cut/lib/types";
import { cn } from "@/lib/utils";
import { OverlayLayer } from "./OverlayLayer";
@@ -26,7 +26,7 @@ function pannableSpan(s: {
if (!span || span.clip.fit !== "fill" || !isFullRect(rectOf(span.clip))) return null;
const { width, height } = span.asset;
if (!width || !height) return null;
- const frame = FRAME[s.aspect];
+ const frame = frameOf(s.aspect);
const scale = Math.max(frame.w / width, frame.h / height);
const ox = width * scale - frame.w;
const oy = height * scale - frame.h;
@@ -39,7 +39,7 @@ export function Preview() {
const [stage, setStage] = useState({ w: 270, h: 480 });
const pannable = useEditor((s) => pannableSpan(s) !== null);
const aspect = useEditor((s) => s.aspect);
- const frame = FRAME[aspect];
+ const frame = frameOf(aspect);
usePlayback(canvasRef);
@@ -51,7 +51,7 @@ export function Preview() {
useEffect(() => {
const wrap = wrapRef.current;
if (!wrap) return;
- const [rw, rh] = aspect === "9:16" ? [9, 16] : [16, 9];
+ const { w: rw, h: rh } = frameOf(aspect);
const fit = () => {
const r = wrap.getBoundingClientRect();
const pad = 28;
@@ -71,7 +71,7 @@ export function Preview() {
const s = useEditor.getState();
const span = pannableSpan(s);
if (!span) return false;
- const fr = FRAME[s.aspect];
+ const fr = frameOf(s.aspect);
const { width = 1, height = 1 } = span.asset;
const scale = Math.max(fr.w / width, fr.h / height);
const ox = width * scale - fr.w;
diff --git a/site/src/cut/components/SceneCard.tsx b/site/src/cut/components/SceneCard.tsx
index 881be5e9..03d90a79 100644
--- a/site/src/cut/components/SceneCard.tsx
+++ b/site/src/cut/components/SceneCard.tsx
@@ -20,7 +20,7 @@ import { NO_CREDITS_MESSAGE } from "../lib/generate";
import { GEN_FPS } from "../lib/genvideo/editorBridge";
import { useEditor } from "../lib/store";
import { formatTime } from "../lib/time";
-import type { MediaAsset } from "../lib/types";
+import { frameOf, type MediaAsset } from "../lib/types";
import type { Shot, ShotStatus } from "../lib/genvideo/types";
import { cn } from "@/lib/utils";
import { HostedErrorText } from "./hostedError";
@@ -263,7 +263,8 @@ function ShotStrip({
}) {
const assets = useEditor((s) => s.assets);
const aspect = useEditor((s) => s.aspect);
- const baseRatio = aspect === "9:16" ? 9 / 16 : 16 / 9;
+ const baseFrame = frameOf(aspect);
+ const baseRatio = baseFrame.w / baseFrame.h;
return (
<div className="ai-scene-strip mt-1.5 grid grid-cols-2 gap-1.5">
{run.shots.map((sh, i) => (
diff --git a/site/src/cut/components/TopBar.tsx b/site/src/cut/components/TopBar.tsx
index 72e5a38f..6d406b2c 100644
--- a/site/src/cut/components/TopBar.tsx
+++ b/site/src/cut/components/TopBar.tsx
@@ -2,7 +2,7 @@
import { useState } from "react";
import Link from "next/link";
-import { Check, ChevronDown, ChevronLeft, Cloud, Loader2, Mic, Monitor, Share2, Smartphone, Sparkles, Upload, Video } from "lucide-react";
+import { Check, ChevronDown, ChevronLeft, Cloud, Loader2, Mic, Monitor, Share2, Smartphone, Sparkles, Square, Upload, Video } from "lucide-react";
import { Button } from "@/components/ui/button";
import {
Dialog,
@@ -24,11 +24,17 @@ import { useWebMode } from "@/cut/lib/flags";
import { backTarget, projectHref, useCutBase } from "@/cut/lib/nav";
import { copyProjectAcross } from "@/cut/lib/projectCopy";
import { useEditor } from "@/cut/lib/store";
-import { ASPECT_LABEL, type Aspect } from "@/cut/lib/types";
+import { ASPECT_PRESETS, aspectLabel, aspectOrientation, type Aspect } from "@/cut/lib/types";
import { cn } from "@/lib/utils";
import { RecordDialog, type RecordMode } from "./RecordDialog";
import { ShareDialog } from "./ShareDialog";
+function AspectIcon({ aspect, className }: { aspect: Aspect; className?: string }) {
+ const o = aspectOrientation(aspect);
+ const Icon = o === "square" ? Square : o === "landscape" ? Monitor : Smartphone;
+ return <Icon className={className} />;
+}
+
export function TopBar({
onImport,
from,
@@ -106,21 +112,19 @@ export function TopBar({
<div className="absolute left-1/2 flex -translate-x-1/2 items-center gap-2">
<DropdownMenu>
<DropdownMenuTrigger className="aspect-switch flex items-center gap-1.5 rounded-full border border-border bg-card px-3 py-1.5 text-xs font-medium text-muted-foreground shadow-xs transition-colors hover:text-foreground">
- {aspect === "9:16" ? <Smartphone className="size-3.5" /> : <Monitor className="size-3.5" />}
- {ASPECT_LABEL[aspect]}
+ <AspectIcon aspect={aspect} className="size-3.5" />
+ {aspectLabel(aspect)}
<ChevronDown className="size-3" />
</DropdownMenuTrigger>
<DropdownMenuContent align="start" className="w-56">
- {(Object.keys(ASPECT_LABEL) as Aspect[]).map((a) => (
- <DropdownMenuItem key={a} onClick={() => useEditor.getState().setAspect(a)}>
- {a === "9:16" ? <Smartphone /> : <Monitor />}
+ {ASPECT_PRESETS.map((p) => (
+ <DropdownMenuItem key={p.value} onClick={() => useEditor.getState().setAspect(p.value)}>
+ <AspectIcon aspect={p.value} />
<span className="flex-1">
- {ASPECT_LABEL[a]}
- <span className="block text-[10.5px] text-muted-foreground">
- {a === "9:16" ? "TikTok, Reels, Shorts" : "YouTube"}
- </span>
+ {p.name} · {p.value}
+ <span className="block text-[10.5px] text-muted-foreground">{p.sublabel}</span>
</span>
- {aspect === a && <Check className="size-3.5 text-muted-foreground" />}
+ {aspect === p.value && <Check className="size-3.5 text-muted-foreground" />}
</DropdownMenuItem>
))}
</DropdownMenuContent>
diff --git a/site/src/cut/lib/aiContext.ts b/site/src/cut/lib/aiContext.ts
index f5899097..86a86d65 100644
--- a/site/src/cut/lib/aiContext.ts
+++ b/site/src/cut/lib/aiContext.ts
@@ -4,7 +4,7 @@ import { chatOwner } from "./chatAssets";
import { useGenerate } from "./generate";
import { getClipSpans, overlayLayers, totalDuration, useEditor } from "./store";
import { laneCues, subtitleLaneCount } from "./subtitles";
-import { rectOf, regionLabel, type ClipSpan, type VideoClip } from "./types";
+import { frameOf, rectOf, regionLabel, type ClipSpan, type VideoClip } from "./types";
const r = (n: number) => Math.round(n * 100) / 100;
@@ -111,7 +111,7 @@ export function buildAiContext(opts?: { fullCues?: boolean; chatId?: string | nu
name: s.projectName,
duration: r(duration),
aspect: s.aspect,
- frame: s.aspect === "9:16" ? "1080x1920" : "1920x1080",
+ frame: `${frameOf(s.aspect).w}x${frameOf(s.aspect).h}`,
...(s.fadeIn > 0 ? { fadeIn: r(s.fadeIn) } : {}),
...(s.fadeOut > 0 ? { fadeOut: r(s.fadeOut) } : {}),
},
diff --git a/site/src/cut/lib/aiTools.ts b/site/src/cut/lib/aiTools.ts
index 77023131..ae08e817 100644
--- a/site/src/cut/lib/aiTools.ts
+++ b/site/src/cut/lib/aiTools.ts
@@ -48,18 +48,21 @@ import { DUCK_DEFAULT, generateSubtitlesReadout } from "./voiceover";
import {
ANIM_DEFAULT_SECONDS,
ANIM_STYLE_IDS,
- FRAME,
+ frameOf,
IMAGE_CLIP_SECONDS,
LAYOUTS,
LOOK_IDS,
MAX_SUBTITLE_LANES,
mediaUrl,
+ nearestAspect,
overlayAnimStyle,
+ parseRatio,
rectOf,
regionLabel,
SPEED_FLOOR,
TRANSITION_STYLE_IDS,
type AnimStyle,
+ type Aspect,
type AudioClip,
type ColorGrade,
type FontId,
@@ -671,7 +674,7 @@ export async function runAiTool(
// Bake the still at the current project frame, framed exactly as
// the preview shows it. Switching aspect later letterboxes this
// still — capture a fresh one to re-fit.
- frame: { w: FRAME[s.aspect].w, h: FRAME[s.aspect].h },
+ frame: frameOf(s.aspect),
framing: {
fit: span.clip.fit ?? "fit",
panX: span.clip.panX ?? 0,
@@ -814,7 +817,7 @@ export async function runAiTool(
aspect:
input.aspect === "16:9" || input.aspect === "9:16"
? input.aspect
- : useEditor.getState().aspect,
+ : nearestAspect(useEditor.getState().aspect, ["16:9", "9:16"] as const),
chatId: chatOwner() ?? undefined,
});
const stillAsset =
@@ -1704,10 +1707,17 @@ export async function runAiTool(
}
case "set_aspect": {
- const a = input.aspect === "16:9" ? "16:9" : input.aspect === "9:16" ? "9:16" : null;
- if (!a) throw new ToolError('aspect must be "9:16" or "16:9".');
+ const a =
+ typeof input.aspect === "string" && parseRatio(input.aspect)
+ ? (input.aspect as Aspect)
+ : null;
+ if (!a)
+ throw new ToolError(
+ 'aspect must be "W:H" with whole numbers up to a 4:1 shape, e.g. "9:16", "16:9", "1:1", or "9:5".'
+ );
s.setAspect(a);
- return { aspect: a };
+ const f = frameOf(a);
+ return { aspect: a, frame: `${f.w}x${f.h}` };
}
case "set_project_fade": {
diff --git a/site/src/cut/lib/exportClient.ts b/site/src/cut/lib/exportClient.ts
index 2228f049..e2f5f289 100644
--- a/site/src/cut/lib/exportClient.ts
+++ b/site/src/cut/lib/exportClient.ts
@@ -7,7 +7,7 @@ import { putSigned } from "./media";
import { clipSpeed, getClipSpans, overlayLayers, projectDuration, spanSequence, useEditor } from "./store";
import { captionStyle, cueOverlay, cueWordWindows, laneCues, subtitleLaneCount, trackPos } from "./subtitles";
import { renderOverlayPng } from "./textRender";
-import { FRAME, overlayAnimStyle } from "./types";
+import { frameOf, overlayAnimStyle } from "./types";
import type {
Aspect,
AudioClip,
@@ -26,36 +26,45 @@ export interface ExportSettings {
preset: string;
}
-/** Presets are stored portrait (9:16); `presetSettings` flips them for 16:9. */
+/** Presets pick a short-side target; `presetSettings` derives both dims from
+ * the project ratio. */
export const EXPORT_PRESETS = [
{
id: "tiktok",
label: "Best · 1080p",
detail: "H.264 · best quality",
- settings: { width: 1080, height: 1920, fps: 30, crf: 19, preset: "medium" },
+ shortSide: 1080,
+ settings: { fps: 30, crf: 19, preset: "medium" },
},
{
id: "fast",
label: "Quick share · 1080p",
detail: "smaller file, faster",
- settings: { width: 1080, height: 1920, fps: 30, crf: 24, preset: "veryfast" },
+ shortSide: 1080,
+ settings: { fps: 30, crf: 24, preset: "veryfast" },
},
{
id: "light",
label: "Draft · 720p",
detail: "fastest render",
- settings: { width: 720, height: 1280, fps: 30, crf: 24, preset: "veryfast" },
+ shortSide: 720,
+ settings: { fps: 30, crf: 24, preset: "veryfast" },
},
] as const;
+/** Frame dims for an aspect scaled to a short-side target, even-rounded. */
+function scaledFrame(aspect: Aspect, shortSide: number): { width: number; height: number } {
+ const f = frameOf(aspect);
+ const k = shortSide / Math.min(f.w, f.h);
+ const even = (n: number) => 2 * Math.round((n * k) / 2);
+ return { width: even(f.w), height: even(f.h) };
+}
+
export function presetSettings(
preset: (typeof EXPORT_PRESETS)[number],
aspect: Aspect
): ExportSettings {
- const { width, height, ...rest } = preset.settings;
- return aspect === "16:9"
- ? { width: height, height: width, ...rest }
- : { width, height, ...rest };
+ return { ...scaledFrame(aspect, preset.shortSide), ...preset.settings };
}
/**
@@ -70,7 +79,7 @@ export function originalSettings(
clips: VideoClip[],
assets: MediaAsset[]
): ExportSettings {
- const base = FRAME[aspect];
+ const base = frameOf(aspect);
const srcLong = Math.max(
0,
...getClipSpans(clips, assets).map((sp) =>
@@ -357,7 +366,15 @@ async function buildExportPayload(
const win = windows[wi];
if (win.start >= duration) break;
const png = await renderOverlayPng(
- cueOverlay(cue, capStyle, i === 0, pos, doc.subtitles.wordHighlight ? wi : undefined),
+ cueOverlay(
+ cue,
+ capStyle,
+ i === 0,
+ pos,
+ doc.subtitles.wordHighlight ? wi : undefined,
+ // Wrap in design space (1080 short side), whatever the render size.
+ Math.round((1080 * settings.width) / Math.min(settings.width, settings.height))
+ ),
settings.width,
settings.height
);
@@ -525,8 +542,7 @@ export function cancelExportJob(jobId: string, backend: CutBackend = getBackend(
* footage yet. */
export async function renderPreviewProxy(projectId: string, doc: ExportDoc, aspect: Aspect) {
const backend = getBackend(); // pinned: the proxy render outlives navigation
- const [width, height] = aspect === "16:9" ? [640, 360] : [360, 640];
- const settings: ExportSettings = { width, height, fps: 24, crf: 30, preset: "veryfast" };
+ const settings: ExportSettings = { ...scaledFrame(aspect, 360), fps: 24, crf: 30, preset: "veryfast" };
let res: Response;
try {
const payload = await buildExportPayload(projectId, doc, settings, "preview");
@@ -578,8 +594,7 @@ export function docFirstSeconds(doc: ExportDoc, seconds: number): ExportDoc {
/** Card frame size for an aspect: 16:9 sits close to the 1.91:1 social cards
* want, and portrait cuts get a tall card rather than a letterboxed wide one. */
function cardSettings(aspect: Aspect): ExportSettings {
- const [width, height] = aspect === "16:9" ? [1280, 720] : [720, 1280];
- return { width, height, fps: 15, crf: 26, preset: "veryfast" };
+ return { ...scaledFrame(aspect, 720), fps: 15, crf: 26, preset: "veryfast" };
}
/** Render the project's link-preview card: the opening five seconds, which
diff --git a/site/src/cut/lib/genScene.ts b/site/src/cut/lib/genScene.ts
index abcfc038..d669de18 100644
--- a/site/src/cut/lib/genScene.ts
+++ b/site/src/cut/lib/genScene.ts
@@ -10,7 +10,7 @@ import { onActivity } from "./genvideo/activity";
import { projectWriteMode, withProjectDoc } from "./genvideo/docWriter";
import type { RefAsset, Shot, VideoEvent, VideoPhase, VideoProject } from "./genvideo/types";
import { useEditor } from "./store";
-import type { Aspect } from "./types";
+import { nearestAspect, type Aspect } from "./types";
// Brief-to-video ("generate a video") controller. It owns one VideoOrchestrator
// per open project and runs it browser-side, exactly where generation and the
@@ -263,7 +263,7 @@ function newProject(projectId: string, params: StartSceneParams): VideoProject {
// The plan owns its shape from the start (start() applies params.aspect to
// an empty timeline before this runs), so a background render can never
// pick up another open project's aspect.
- aspect: useEditor.getState().aspect,
+ aspect: nearestAspect(useEditor.getState().aspect, ["9:16", "16:9"] as const),
style: params.style?.trim() ?? "",
suiteLabel: "donkey-hosted",
...(params.chatId ? { chatId: params.chatId } : {}),
diff --git a/site/src/cut/lib/generate.ts b/site/src/cut/lib/generate.ts
index 6eef932e..976ef197 100644
--- a/site/src/cut/lib/generate.ts
+++ b/site/src/cut/lib/generate.ts
@@ -22,7 +22,7 @@ import { refsToInlineImages, videoSafeInline, visualRefs, type InlineImage } fro
import { useGenNotify } from "./genNotify";
import { useImageGen } from "./imageGen";
import { useEditor } from "./store";
-import { mediaSlug, type MediaAsset, type RenderRecord } from "./types";
+import { mediaSlug, nearestAspect, type MediaAsset, type RenderRecord } from "./types";
import { videoModel } from "./videoModels";
import { walkLadder, type VideoAttempt } from "./videoLadder";
@@ -603,7 +603,9 @@ export const useGenerate = create<GenerateState>((set, get) => {
set((s) => ({ jobs: [job, ...s.jobs] }));
return (async () => {
try {
- const aspect = opts?.aspect ?? useEditor.getState().aspect;
+ const aspect =
+ opts?.aspect ??
+ nearestAspect(useEditor.getState().aspect, ["16:9", "9:16", "1:1"] as const);
const resolution = opts?.resolution ?? useImageGen.getState().resolution;
// The job (and the landed asset's name) keeps the user's own words;
// only the render sees the composed prompt. The image model takes
@@ -738,7 +740,8 @@ export const useGenerate = create<GenerateState>((set, get) => {
? { inputs: { images } }
: {}),
parameters: {
- aspectRatio: opts?.aspect ?? useEditor.getState().aspect,
+ aspectRatio:
+ opts?.aspect ?? nearestAspect(useEditor.getState().aspect, ["16:9", "9:16"] as const),
...(opts?.negativePrompt ? { negativePrompt: opts.negativePrompt } : {}),
},
});
diff --git a/site/src/cut/lib/genvideo/editorBridge.ts b/site/src/cut/lib/genvideo/editorBridge.ts
index a5991c3d..bc628856 100644
--- a/site/src/cut/lib/genvideo/editorBridge.ts
+++ b/site/src/cut/lib/genvideo/editorBridge.ts
@@ -23,7 +23,7 @@
*/
import { useEditor } from "../store";
-import { TRANSITION_STYLE_IDS, type TransitionStyle } from "../types";
+import { nearestAspect, TRANSITION_STYLE_IDS, type TransitionStyle } from "../types";
import { docPlaceGenAudio, docPlaceGenClip, projectWriteMode, withProjectDoc } from "./docWriter";
import type { AudioClipInfo, EditorBridge, TimelineInfo } from "./editor";
@@ -73,7 +73,9 @@ export class StoreEditorBridge implements EditorBridge {
this.lastTimeline = {
fps: GEN_FPS,
durationFrames: Math.round(clipEnd * GEN_FPS),
- aspect: s.aspect,
+ // The pipeline renders in the shapes the models support; a custom
+ // project ratio maps to the closest one and letterboxes on the timeline.
+ aspect: nearestAspect(s.aspect, ["9:16", "16:9"] as const),
};
return this.lastTimeline;
}
diff --git a/site/src/cut/lib/store.ts b/site/src/cut/lib/store.ts
index 7499b86f..c0911cb7 100644
--- a/site/src/cut/lib/store.ts
+++ b/site/src/cut/lib/store.ts
@@ -32,7 +32,7 @@ import { fetchSignedMediaUrls } from "./backend/cloud";
import { markSignedBatch } from "./mediaLinks";
import { cloudTranscribeSpec, type CloudTranscribeSpec } from "./cloudTranscribe";
import { trackLocale } from "./subtitles";
-import { ANIM_STYLE_IDS, emptySubtitles, IMAGE_CLIP_SECONDS, LOOK_IDS, MAX_SUBTITLE_LANES, mediaUrl, migrateLegacyTransitions, SPEED_FLOOR, SPEED_MIN, TRANSITION_MAX } from "./types";
+import { ANIM_STYLE_IDS, emptySubtitles, IMAGE_CLIP_SECONDS, LOOK_IDS, MAX_SUBTITLE_LANES, mediaUrl, migrateLegacyTransitions, parseRatio, SPEED_FLOOR, SPEED_MIN, TRANSITION_MAX } from "./types";
import { readTextStyle } from "./textStyle";
import { loadUiState, saveUiState } from "./uiState";
import { captureTimelineFrames } from "./visualFrames";
@@ -1087,7 +1087,9 @@ export const useEditor = create<EditorState>((baseSet, get) => {
if (batchDepth === 0) flush(); // commit the whole run as one undo step
},
- setAspect: (a) => set({ aspect: a }),
+ setAspect: (a) => {
+ if (parseRatio(a)) set({ aspect: a });
+ },
setProjectFade: (patch) => {
const clamp = (v: number | undefined) =>
v === undefined ? undefined : Math.max(0, Math.min(TRANSITION_MAX, v));
diff --git a/site/src/cut/lib/subtitles.ts b/site/src/cut/lib/subtitles.ts
index 96c8be67..512a2755 100644
--- a/site/src/cut/lib/subtitles.ts
+++ b/site/src/cut/lib/subtitles.ts
@@ -285,12 +285,12 @@ export function wrapCaption(text: string): string {
* line centered without wrapping, so this is what guarantees captions stay in
* bounds — bigger styles (and the punchy opener) wrap to fewer words per line.
*/
-export function wrapCaptionForSize(text: string, size: number): string {
+export function wrapCaptionForSize(text: string, size: number, frameW = 1080): string {
const words = text.trim().replace(/\s+/g, " ").split(" ").filter(Boolean);
if (words.length === 0) return "";
- // ~88% of the 1080 design short-side, with a conservative bold-glyph advance
+ // ~88% of the frame width, with a conservative bold-glyph advance
// (~0.58·size) so real fonts stay comfortably inside the safe area.
- const maxChars = Math.max(8, Math.floor((0.88 * 1080) / (0.58 * size)));
+ const maxChars = Math.max(8, Math.floor((0.88 * frameW) / (0.58 * size)));
const lines: string[] = [];
let line = "";
for (const w of words) {
@@ -344,7 +344,8 @@ export function cueOverlay(
style: CaptionStyle = CAPTION_STYLES.clean,
isOpener = false,
pos?: { x?: number; y?: number; size?: number; font?: FontId; accentMode?: WordAccentMode; accentColor?: string },
- wordIndex?: number
+ wordIndex?: number,
+ frameW = 1080
): TextOverlay {
const kl = wordIndex !== undefined ? karaokeLook(style, pos) : null;
const size = Math.round(
@@ -352,7 +353,7 @@ export function cueOverlay(
);
return {
id: `sub-${cue.id}`,
- text: wrapCaptionForSize(cue.text, size),
+ text: wrapCaptionForSize(cue.text, size, frameW),
start: cue.start,
end: cue.end,
x: pos?.x ?? style.x,
diff --git a/site/src/cut/lib/types.ts b/site/src/cut/lib/types.ts
index c48285a5..ddb94a46 100644
--- a/site/src/cut/lib/types.ts
+++ b/site/src/cut/lib/types.ts
@@ -7,18 +7,68 @@ export type AssetType = "video" | "audio" | "image";
* an image has no intrinsic duration, so the clip carries this as its `out`. */
export const IMAGE_CLIP_SECONDS = 8;
-/** Project output frame. Vertical (TikTok/Reels) or widescreen (YouTube). */
-export type Aspect = "9:16" | "16:9";
+/** Project output frame ratio as "W:H". Presets cover common platforms;
+ * any ratio that passes `parseRatio` (e.g. "9:5") is valid. */
+export type Aspect = `${number}:${number}`;
+
+/** Parse a "W:H" ratio. Null unless both sides are positive integers up to
+ * three digits and the long/short ratio is at most 4 (keeps ffmpeg output
+ * dims and text layout sane). */
+export function parseRatio(a: string | undefined | null): { w: number; h: number } | null {
+ const m = /^(\d{1,3}):(\d{1,3})$/.exec(a ?? "");
+ if (!m) return null;
+ const w = Number(m[1]);
+ const h = Number(m[2]);
+ if (!w || !h || Math.max(w, h) / Math.min(w, h) > 4) return null;
+ return { w, h };
+}
-export const FRAME: Record<Aspect, { w: number; h: number }> = {
- "9:16": { w: 1080, h: 1920 },
- "16:9": { w: 1920, h: 1080 },
-};
+/** Output frame in pixels. The short side is pinned to 1080 — the design
+ * short side that text scaling and overlay math assume — and the long side
+ * follows the ratio, rounded to even for the encoder. */
+export function frameOf(aspect: Aspect): { w: number; h: number } {
+ const r = parseRatio(aspect) ?? { w: 9, h: 16 };
+ const long = 2 * Math.round((1080 * Math.max(r.w, r.h)) / Math.min(r.w, r.h) / 2);
+ return r.w >= r.h ? { w: long, h: 1080 } : { w: 1080, h: long };
+}
-export const ASPECT_LABEL: Record<Aspect, string> = {
- "9:16": "Vertical · 9:16",
- "16:9": "Widescreen · 16:9",
-};
+export const ASPECT_PRESETS: { value: Aspect; name: string; sublabel: string }[] = [
+ { value: "16:9", name: "Widescreen", sublabel: "YouTube" },
+ { value: "4:3", name: "Classic", sublabel: "LinkedIn, Facebook ads" },
+ { value: "2:1", name: "Cinematic", sublabel: "Wide social banners" },
+ { value: "9:16", name: "Vertical", sublabel: "TikTok, Reels, Shorts" },
+ { value: "1:1", name: "Square", sublabel: "Instagram posts" },
+ { value: "3:4", name: "Portrait", sublabel: "Feed photos" },
+];
+
+export function aspectLabel(aspect: Aspect): string {
+ const preset = ASPECT_PRESETS.find((p) => p.value === aspect);
+ return preset ? `${preset.name} · ${preset.value}` : `Custom · ${aspect}`;
+}
+
+export function aspectOrientation(aspect: Aspect): "landscape" | "portrait" | "square" {
+ const r = parseRatio(aspect) ?? { w: 9, h: 16 };
+ return r.w === r.h ? "square" : r.w > r.h ? "landscape" : "portrait";
+}
+
+/** Project the project aspect onto a model/provider's supported ratio list:
+ * the entry whose shape is closest (log-ratio distance), first entry on ties. */
+export function nearestAspect<T extends string>(aspect: Aspect, supported: readonly T[]): T {
+ const r = parseRatio(aspect) ?? { w: 9, h: 16 };
+ const target = Math.log(r.w / r.h);
+ let best = supported[0];
+ let bestDist = Infinity;
+ for (const s of supported) {
+ const sr = parseRatio(s);
+ if (!sr) continue;
+ const dist = Math.abs(Math.log(sr.w / sr.h) - target);
+ if (dist < bestDist) {
+ bestDist = dist;
+ best = s;
+ }
+ }
+ return best;
+}
/** Asset fields persisted in project.json. */
export interface StoredAsset {
diff --git a/site/src/cut/server/cloud/projects.ts b/site/src/cut/server/cloud/projects.ts
index 0d7af57a..55251b4b 100644
--- a/site/src/cut/server/cloud/projects.ts
+++ b/site/src/cut/server/cloud/projects.ts
@@ -1,6 +1,6 @@
// Cloud twin of the engine's project CRUD (server/projects.ts + http/projects.ts):
// docs and metadata in Postgres, media bytes in R2. Every query scopes by userId.
-import type { ProjectDoc, ProjectFolder, ProjectSummary } from "@/cut/lib/types";
+import { parseRatio, type ProjectDoc, type ProjectFolder, type ProjectSummary } from "@/cut/lib/types";
import type { Prisma } from "@/generated/prisma/client";
import { prisma } from "@/lib/prisma";
import {
@@ -156,7 +156,7 @@ export const projectsCloud = {
: existing.overlayClips,
overlays: Array.isArray(body.overlays) ? body.overlays : existing.overlays,
templates: Array.isArray(body.templates) ? body.templates : existing.templates,
- aspect: body.aspect === "9:16" || body.aspect === "16:9" ? body.aspect : existing.aspect,
+ aspect: parseRatio(body.aspect) ? body.aspect : existing.aspect,
fadeIn: typeof body.fadeIn === "number" ? body.fadeIn : existing.fadeIn,
fadeOut: typeof body.fadeOut === "number" ? body.fadeOut : existing.fadeOut,
subtitles:
diff --git a/site/src/cut/server/http/projects.ts b/site/src/cut/server/http/projects.ts
index 9f18b553..1d73fe8a 100644
--- a/site/src/cut/server/http/projects.ts
+++ b/site/src/cut/server/http/projects.ts
@@ -1,5 +1,5 @@
import { execFile } from "node:child_process";
-import type { ProjectDoc } from "@/cut/lib/types";
+import { parseRatio, type ProjectDoc } from "@/cut/lib/types";
import { detectSilence, extractAudio, makeContactSheets, makeFreezeFrame, probeDims, probeDuration } from "../frames";
import {
createProject,
@@ -122,7 +122,7 @@ export const projectsApi = {
: existing.overlayClips,
overlays: Array.isArray(body.overlays) ? body.overlays : existing.overlays,
templates: Array.isArray(body.templates) ? body.templates : existing.templates,
- aspect: body.aspect === "9:16" || body.aspect === "16:9" ? body.aspect : existing.aspect,
+ aspect: parseRatio(body.aspect) ? body.aspect : existing.aspect,
fadeIn: typeof body.fadeIn === "number" ? body.fadeIn : existing.fadeIn,
fadeOut: typeof body.fadeOut === "number" ? body.fadeOut : existing.fadeOut,
subtitles: