Open source CapCut alternative.
TypeScript
feat(site): export picks container, codec, frame rate, quality and audio [rebuild]
David Le0f618644fc0a
diff --git a/site/src/cut/components/ExportDialog.tsx b/site/src/cut/components/ExportDialog.tsxindex 5323be75..37286068 100644--- a/site/src/cut/components/ExportDialog.tsx+++ b/site/src/cut/components/ExportDialog.tsx@@ -1,6 +1,7 @@"use client";import { useEffect, useMemo, useState } from "react";+import { ChevronDown } from "lucide-react";import { Button } from "@/components/ui/button";import {Dialog,@@ -9,12 +10,21 @@ import {DialogHeader,DialogTitle,} from "@/components/ui/dialog";+import { Input } from "@/components/ui/input";import {- EXPORT_PRESETS,+ EXPORT_AUDIO,+ EXPORT_CODECS,+ EXPORT_CONTAINERS,+ EXPORT_FRAME_RATES,+ EXPORT_QUALITIES,+ EXPORT_QUICK_PRESETS,+ choiceSettings,estimateExportBytes,formatSizeEstimate,- originalSettings,- presetSettings,+ quickPresetOf,+ resolutionOptions,+ resolveResolution,+ type ExportChoice,} from "@/cut/lib/exportClient";import { useCutMode } from "@/cut/lib/backend/hooks";import { canRenderInBrowser } from "@/cut/lib/exportRender";@@ -22,9 +32,10 @@ import { useExports } from "@/cut/lib/exportStore";import { projectDuration, useEditor } from "@/cut/lib/store";import { cn } from "@/lib/utils";-// Just a launcher: pick a preset, hand the cut to the engine, and close. Every-// export — progress, queue position, the finished file — is tracked in the-// app-wide exports dock, so starting one never blocks starting another.+// Just a launcher: pick a preset or set every axis yourself, hand the cut to+// the engine, and close. Every export — progress, queue position, the+// finished file — is tracked in the app-wide exports dock, so starting one+// never blocks starting another.export function ExportDialog() {const setExportOpen = useEditor((s) => s.setExportOpen);const aspect = useEditor((s) => s.aspect);@@ -36,38 +47,26 @@ export function ExportDialog() {() => projectDuration({ clips, audioClips, overlays }),[clips, audioClips, overlays]);- // "Original" leads: sized from the footage on the timeline, so it is always- // the highest option. The fixed presets follow, flipped to the aspect.- const presets = useMemo(- () => [- {- id: "original",- label: "Original · matches source",- detail: "H.264 · best quality",- settings: originalSettings(aspect, clips, assets),- },- ...EXPORT_PRESETS.map((p) => ({- id: p.id,- label: p.label,- detail: p.detail,- settings: presetSettings(p, aspect),- })),- ],+ const resolutions = useMemo(+ () => resolutionOptions(aspect, clips, assets),[aspect, clips, assets]);- const [presetId, setPresetId] = useState("original");- const selected = presets.find((p) => p.id === presetId) ?? presets[0];+ const [choice, setChoice] = useState<ExportChoice>(EXPORT_QUICK_PRESETS[1].choice);+ const [advanced, setAdvanced] = useState(false);+ // The field's own text, so a decimal in progress ("1.") survives the parse.+ const [mbpsText, setMbpsText] = useState("");+ const preset = quickPresetOf(choice, resolutions);+ const settings = useMemo(() => choiceSettings(choice, resolutions), [choice, resolutions]);+ const set = (patch: Partial<ExportChoice>) => setChoice((c) => ({ ...c, ...patch }));- // A browser-resident project has exactly one renderer: this tab. Ask up- // front whether the browser can encode at the chosen size, so a refusal- // is a message here instead of an error card after the dialog closed.+ // A browser-resident project renders in this tab when it can, and on the+ // cloud worker when it can't; ask up front which it is, so the dialog says+ // where the render is going.const cutMode = useCutMode();- const [fits, setFits] = useState(true);+ const [browserFits, setBrowserFits] = useState(true);+ const inTab = cutMode !== "browser" || browserFits;useEffect(() => {- if (cutMode !== "browser") {- setFits(true);- return;- }+ if (cutMode !== "browser") return;let alive = true;const s = useEditor.getState();void canRenderInBrowser(@@ -82,19 +81,18 @@ export function ExportDialog() {fadeOut: s.fadeOut,background: s.background,},- selected.settings+ settings).then((ok) => {- if (alive) setFits(ok);+ if (alive) setBrowserFits(ok);});return () => {alive = false;};- }, [cutMode, selected.settings]);+ }, [cutMode, settings]);const run = () => {const s = useEditor.getState();if (!s.projectId) return;- const settings = (presets.find((p) => p.id === presetId) ?? presets[0]).settings;void useExports.getState().start(s.projectId,{@@ -114,49 +112,211 @@ export function ExportDialog() {setExportOpen(false); // the dock takes it from here};+ const codecLabel = EXPORT_CODECS.find((c) => c.id === settings.codec)?.label ?? settings.codec;+ const prores = settings.codec === "prores";+return (<Dialog open onOpenChange={(o) => !o && setExportOpen(false)}>- <DialogContent className="sm:max-w-sm">+ <DialogContent className="sm:max-w-md"><DialogHeader><DialogTitle>Export</DialogTitle></DialogHeader>- <div className="flex flex-col gap-2" role="radiogroup" aria-label="Export preset">- {presets.map((p) => (+ <div className="grid grid-cols-2 gap-1.5" role="radiogroup" aria-label="Export preset">+ {EXPORT_QUICK_PRESETS.map((p) => (<buttonkey={p.id}+ type="button"role="radio"- aria-checked={presetId === p.id}+ aria-checked={preset === p.id}className={cn(- "flex items-center gap-3 rounded-lg border border-border bg-background px-3 py-2.5 text-left transition-colors hover:border-input",- presetId === p.id && "border-primary bg-primary/10"+ "flex flex-col items-start rounded-lg border border-border bg-background px-3 py-2 text-left transition-colors hover:border-input",+ preset === p.id && "border-primary bg-primary/10")}- onClick={() => setPresetId(p.id)}+ onClick={() => {+ setMbpsText("");+ setChoice({ ...p.choice });+ }}>- <span className="flex min-w-0 flex-col items-start">- <span className="text-sm font-medium">{p.label}</span>- <span className="text-xs text-muted-foreground">- {p.settings.width} × {p.settings.height} · {p.detail}- </span>- </span>- <span className="ml-auto shrink-0 text-xs tabular-nums text-muted-foreground">- {formatSizeEstimate(estimateExportBytes(p.settings, duration))}- </span>+ <span className="text-sm font-medium">{p.label}</span>+ <span className="text-[11px] text-muted-foreground">{p.detail}</span></button>))}</div>+ <button+ type="button"+ className="flex items-center gap-1 self-start text-xs font-medium text-muted-foreground hover:text-foreground"+ aria-expanded={advanced}+ onClick={() => setAdvanced((a) => !a)}+ >+ <ChevronDown className={cn("size-3.5 transition-transform", advanced && "rotate-180")} />+ Advanced+ </button>++ {advanced && (+ <div className="flex flex-col gap-3">+ <Choice label="Format">+ {EXPORT_CONTAINERS.map((c) => (+ <Pill+ key={c.id}+ checked={settings.container === c.id}+ // MP4 can't carry ProRes or PCM; MOV is what they take.+ disabled={c.id === "mp4" && (prores || settings.audioCodec === "pcm")}+ onClick={() => set({ container: c.id })}+ title={c.label}+ />+ ))}+ </Choice>+ <Choice label="Codec">+ {EXPORT_CODECS.map((c) => (+ <Pill+ key={c.id}+ checked={settings.codec === c.id}+ onClick={() =>+ set({+ codec: c.id,+ ...(c.id === "prores" ? { container: "mov", bitrateMbps: undefined } : {}),+ })+ }+ title={c.label}+ detail={c.detail}+ />+ ))}+ </Choice>+ <Choice label="Resolution">+ {resolutions.map((r) => (+ <Pill+ key={r.id}+ checked={resolveResolution(resolutions, choice.resolution).id === r.id}+ onClick={() => set({ resolution: r.id })}+ title={r.label}+ detail={`${r.width} × ${r.height}`}+ />+ ))}+ </Choice>+ <Choice label="Frame rate">+ {EXPORT_FRAME_RATES.map((f) => (+ <Pill key={f} checked={choice.fps === f} onClick={() => set({ fps: f })} title={`${f} fps`} />+ ))}+ </Choice>+ {!prores && (+ <Choice label="Quality">+ {EXPORT_QUALITIES.map((q) => (+ <Pill+ key={q.id}+ checked={!choice.bitrateMbps && choice.quality === q.id}+ onClick={() => {+ setMbpsText("");+ set({ quality: q.id, bitrateMbps: undefined });+ }}+ title={q.label}+ detail={q.detail}+ />+ ))}+ <label+ className={cn(+ "flex min-w-[4.5rem] items-center gap-1.5 rounded-lg border border-border bg-background px-3 py-1.5 text-sm transition-colors hover:border-input",+ choice.bitrateMbps && "border-primary bg-primary/10"+ )}+ >+ <Input+ type="number"+ inputMode="decimal"+ min={0.5}+ max={MAX_MBPS}+ step={0.5}+ placeholder="Mbps"+ aria-label="Bitrate in megabits per second"+ className="h-6 w-16 px-1.5 text-sm"+ value={mbpsText}+ onChange={(e) => {+ setMbpsText(e.target.value);+ const v = Math.min(Number(e.target.value), MAX_MBPS);+ set({ bitrateMbps: v > 0 ? v : undefined });+ }}+ />+ <span className="text-[11px] text-muted-foreground">Mbps</span>+ </label>+ </Choice>+ )}+ <Choice label="Audio">+ {EXPORT_AUDIO.map((a) => (+ <Pill+ key={a.id}+ checked={settings.audioCodec === a.id}+ onClick={() => set({ audioCodec: a.id, ...(a.id === "pcm" ? { container: "mov" } : {}) })}+ title={a.label}+ detail={a.detail}+ />+ ))}+ </Choice>+ </div>+ )}+<DialogFooter className="flex-col gap-2 sm:flex-col">- <Button className="w-full" disabled={!fits} onClick={run}>+ <div className="flex items-center justify-between text-xs text-muted-foreground">+ <span>+ {settings.width} × {settings.height} · {settings.fps} fps · {settings.container.toUpperCase()} ·{" "}+ {codecLabel} + {settings.audioCodec.toUpperCase()}+ </span>+ <span className="tabular-nums">+ {formatSizeEstimate(estimateExportBytes(settings, duration))}+ </span>+ </div>+ <Button className="w-full" onClick={run}>Export video</Button><p className="text-center text-[11px] text-muted-foreground">- {fits+ {inTab? "Renders in the background. You can keep editing, open another project, or export more — each shows in the corner."- : "This browser can't export at this size. Move the project to Cloud (top bar) to export."}+ : `This browser can't encode ${prores ? "ProRes" : "this"} itself, so it renders in the cloud and lands here when done.`}</p></DialogFooter></DialogContent></Dialog>);}++/** The most a typed bitrate can ask for. */+const MAX_MBPS = 200;++function Choice({ label, children }: { label: string; children: React.ReactNode }) {+ return (+ <div className="flex flex-col gap-1.5" role="radiogroup" aria-label={label}>+ <span className="text-xs font-medium text-muted-foreground">{label}</span>+ <div className="flex flex-wrap gap-1.5">{children}</div>+ </div>+ );+}++function Pill({+ checked,+ disabled,+ onClick,+ title,+ detail,+}: {+ checked: boolean;+ disabled?: boolean;+ onClick: () => void;+ title: string;+ detail?: string;+}) {+ return (+ <button+ type="button"+ role="radio"+ aria-checked={checked}+ disabled={disabled}+ className={cn(+ "flex min-w-[4.5rem] flex-col items-start rounded-lg border border-border bg-background px-3 py-1.5 text-left transition-colors hover:border-input disabled:cursor-not-allowed disabled:opacity-40",+ checked && "border-primary bg-primary/10"+ )}+ onClick={onClick}+ >+ <span className="text-sm font-medium">{title}</span>+ {detail && <span className="text-[11px] text-muted-foreground">{detail}</span>}+ </button>+ );+}diff --git a/site/src/cut/components/SidePanel.tsx b/site/src/cut/components/SidePanel.tsxindex 8d3c638f..aea2c221 100644--- a/site/src/cut/components/SidePanel.tsx+++ b/site/src/cut/components/SidePanel.tsx@@ -117,6 +117,7 @@ import { formatTime } from "@/cut/lib/time";import { useLocalPref } from "@/cut/lib/uiState";import type { MediaAsset, SidePanelTab } from "@/cut/lib/types";import { cn } from "@/lib/utils";+import { containerOfName } from "@/cut/lib/exportDelivery";import { useRevealEffect, useRevealFlash } from "@/cut/lib/refReveal";import { usePanelRequestEffect } from "@/cut/lib/panelRequest";import { CopyNameLabel } from "./AssetRefs";@@ -574,6 +575,41 @@ function ExportPulse({ file }: { file: string }) {return pulse ? <div aria-hidden className={genPulseOverlay} /> : null;}+/** An export's first frame. A master the browser cannot decode — ProRes in a+ * MOV — shows as a film badge in its place. */+function ExportThumb({+ src,+ onPlayable,+ onUnplayable,+}: {+ src: string;+ onPlayable: () => void;+ onUnplayable: () => void;+}) {+ const [playable, setPlayable] = useState(true);+ if (!playable) {+ return (+ <span className="flex h-11 w-[25px] shrink-0 items-center justify-center rounded-[4px] bg-muted text-muted-foreground">+ <Film className="size-3" />+ </span>+ );+ }+ return (+ <video crossOrigin={MEDIA_CORS}+ muted+ playsInline+ preload="metadata"+ src={src}+ onLoadedMetadata={onPlayable}+ onError={() => {+ setPlayable(false);+ onUnplayable();+ }}+ className="h-11 w-[25px] shrink-0 rounded-[4px] bg-black object-cover"+ />+ );+}+/** An export still being worked on, in the Exports list: spinner, live* progress, and a cancel that stops it. This is the project's record of the* work, so an export hidden from the dock still has its row and its cancel@@ -789,6 +825,9 @@ function ProjectFilesPanel({const [settling, setSettling] = useState<ExportRow[]>([]);const lastExporting = useRef<ExportRow[]>([]);const [preview, setPreview] = useState<ExportItem | null>(null);+ // Exports this browser cannot decode — a ProRes master — have no post+ // preview to open; their row shows a badge and says what they are.+ const [unplayable, setUnplayable] = useState<Set<string>>(() => new Set());const [deletingExport, setDeletingExport] = useState<ExportItem | null>(null);// Whatever is being worked on right now. When the last of it drops out — a@@ -1060,15 +1099,23 @@ function ProjectFilesPanel({<buttontype="button"className="flex min-w-0 flex-1 items-center gap-2.5 text-left"- title="Preview as a post"- onClick={() => setPreview(it)}+ title={unplayable.has(it.file) ? "Master file" : "Preview as a post"}+ onClick={() => !unplayable.has(it.file) && setPreview(it)}>- <video crossOrigin={MEDIA_CORS}- muted- playsInline- preload="metadata"+ <ExportThumb+ // A re-export under the same name is a new file; the key+ // lets it try to play again.+ key={`${it.file}:${it.mtime}`}src={`${exportFileUrl(projectId, it)}#t=0.1`}- className="h-11 w-[25px] shrink-0 rounded-[4px] bg-black object-cover"+ onPlayable={() =>+ setUnplayable((u) => {+ if (!u.has(it.file)) return u;+ const next = new Set(u);+ next.delete(it.file);+ return next;+ })+ }+ onUnplayable={() => setUnplayable((u) => new Set(u).add(it.file))}/><span className="min-w-0 flex-1"><span className="block truncate text-[11.5px] font-medium">@@ -1080,7 +1127,7 @@ function ProjectFilesPanel({})}</span><span className="block text-[10.5px] text-muted-foreground">- {(it.size / (1024 * 1024)).toFixed(1)} MB · MP4+ {(it.size / (1024 * 1024)).toFixed(1)} MB · {containerOfName(it.file).label}</span></span></button>diff --git a/site/src/cut/components/TopBar.tools.ts b/site/src/cut/components/TopBar.tools.tsindex b76bd992..e8d2f361 100644--- a/site/src/cut/components/TopBar.tools.ts+++ b/site/src/cut/components/TopBar.tools.ts@@ -22,7 +22,7 @@ export const TOP_BAR_TOOLS = [{name: "open_export",description:- "Open the export dialog so the user can render the cut (presets from Original quality down to Draft 720p). Exporting itself stays a user action.",+ "Open the export dialog so the user can render the cut: quick presets (Share, Best, Small, Master) or the advanced panel — format MP4/MOV, codec H.264/HEVC/ProRes, resolution Source down to 720p, frame rate 24/30/60, quality tier or bitrate, AAC or PCM audio. Exporting itself stays a user action.",inputSchema: obj({}),},] as const satisfies readonly AiToolDef[];diff --git a/site/src/cut/lib/backend/browser/opfs.ts b/site/src/cut/lib/backend/browser/opfs.tsindex e8d3ea3d..f316f5eb 100644--- a/site/src/cut/lib/backend/browser/opfs.ts+++ b/site/src/cut/lib/backend/browser/opfs.ts@@ -17,6 +17,7 @@// Project directories are named by id — no Finder here, so nothing follows// display names. Everything is functions over handles; no module-level DOM or// storage access, because this file rides along in the engine bundle.+import { isDeliveryName } from "../../exportDelivery";import type { ProjectDoc, ProjectFolder, ProjectSummary } from "../../types";import { currentEngineUser } from "../../api";@@ -309,7 +310,7 @@ export async function listExports(id: string): Promise<ExportListing[]> {const items: ExportListing[] = [];try {for await (const [name, handle] of dir) {- if (handle.kind !== "file" || !name.endsWith(".mp4")) continue;+ if (handle.kind !== "file" || !isDeliveryName(name)) continue;const file = await (handle as FileSystemFileHandle).getFile();if (file.size > 0) items.push({ file: name, size: file.size, mtime: file.lastModified });}diff --git a/site/src/cut/lib/canvasVideo.ts b/site/src/cut/lib/canvasVideo.tsindex 27ce230c..11d691a8 100644--- a/site/src/cut/lib/canvasVideo.ts+++ b/site/src/cut/lib/canvasVideo.ts@@ -16,7 +16,7 @@ import {Output,Quality,} from "mediabunny";-import { VIDEO_CODECS } from "./exportRender";+import { WORKING_VIDEO_CODECS } from "./exportRender";import { createRasterCanvas, type RasterSurface } from "./raster";export interface CanvasVideoEncoder {@@ -39,7 +39,7 @@ export async function openCanvasVideo(opts: {/** The frame loop reads pixels back off the canvas. */readback?: boolean;}): Promise<CanvasVideoEncoder> {- const codec = await getFirstEncodableVideoCodec(VIDEO_CODECS, {+ const codec = await getFirstEncodableVideoCodec(WORKING_VIDEO_CODECS, {width: opts.width,height: opts.height,});diff --git a/site/src/cut/lib/exportClient.ts b/site/src/cut/lib/exportClient.tsindex 993a91f4..cf22bf43 100644--- a/site/src/cut/lib/exportClient.ts+++ b/site/src/cut/lib/exportClient.ts@@ -7,10 +7,10 @@ import {updateBrowserExportJob,} from "./backend/browser/exportJobs";import { exportsDir, readFileAt, saveExport } from "./backend/browser/opfs";-import { holdRegistered, registerBlobFile, releaseRegistered } from "./backend/browser/registry";-import { quotaErrorMessage } from "./backend/cloud";+import { holdRegistered, registerBlobFile, releaseRegistered, resolveRegisteredBlob } from "./backend/browser/registry";+import { cloudBackend, quotaErrorMessage } from "./backend/cloud";import { downloadFromUrl } from "./download";-import { renderProjectToMp4 } from "./exportRender";+import { bitrateFor, renderProjectToMp4 } from "./exportRender";import { putSigned } from "./media";import { renderRemovalPieces } from "./removalVideo";import { createRasterCanvas, rasterCanvasToPng } from "./raster";@@ -30,12 +30,58 @@ import type {VideoClip,} from "./types";+import {+ deliveryContainer,+ EXPORT_CONTAINERS,+ specMediaFiles,+ type ExportAudioCodec,+ type ExportCodec,+ type ExportContainer,+} from "./exportDelivery";+export { EXPORT_CONTAINERS };+export type { ExportAudioCodec, ExportCodec, ExportContainer };+export interface ExportSettings {width: number;height: number;fps: number;+ /** The quality tier, on x264's scale; the encoders that take a bitrate get+ * `bitrateFor` of it. */crf: number;preset: string;+ codec: ExportCodec;+ container: ExportContainer;+ audioCodec: ExportAudioCodec;+ /** A bitrate the user typed, bits per second. Absent = the tier's model. */+ bitrate?: number;+}++/** The delivery every render that is not the user's own export uses — hover+ * proxies, share cards, ladder masters, the phone's presets. */+export const DELIVERY_DEFAULTS = { codec: "h264", container: "mp4", audioCodec: "aac" } as const;++export const EXPORT_CODECS = [+ { id: "h264", label: "H.264", detail: "plays everywhere" },+ { id: "hevc", label: "HEVC", detail: "half the size · newer devices" },+ { id: "prores", label: "ProRes 422 HQ", detail: "edit master · MOV" },+] as const satisfies readonly { id: ExportCodec; label: string; detail: string }[];++export const EXPORT_AUDIO = [+ { id: "aac", label: "AAC", detail: "192 kbps" },+ { id: "pcm", label: "PCM", detail: "uncompressed · MOV" },+] as const satisfies readonly { id: ExportAudioCodec; label: string; detail: string }[];++/** What a container can carry: ProRes and PCM need MOV. */+export function fitContainer(settings: ExportSettings): ExportSettings {+ if (settings.codec === "prores" || settings.audioCodec === "pcm") {+ return settings.container === "mov" ? settings : { ...settings, container: "mov" };+ }+ return settings;+}++/** The file extension a setting's container takes. */+export function exportExtension(settings: Pick<ExportSettings, "container">): string {+ return deliveryContainer(settings.container).ext;}/** Presets pick a short-side target; `presetSettings` derives both dims from@@ -46,24 +92,158 @@ export const EXPORT_PRESETS = [label: "Best · 1080p",detail: "H.264 · best quality",shortSide: 1080,- settings: { fps: 30, crf: 19, preset: "medium" },+ settings: { fps: 30, crf: 19, preset: "medium", ...DELIVERY_DEFAULTS },},{id: "fast",label: "Quick share · 1080p",detail: "smaller file, faster",shortSide: 1080,- settings: { fps: 30, crf: 24, preset: "veryfast" },+ settings: { fps: 30, crf: 24, preset: "veryfast", ...DELIVERY_DEFAULTS },},{id: "light",label: "Draft · 720p",detail: "fastest render",shortSide: 720,- settings: { fps: 30, crf: 24, preset: "veryfast" },+ settings: { fps: 30, crf: 24, preset: "veryfast", ...DELIVERY_DEFAULTS },},] as const;+/**+ * The axes the export dialog offers, each one independent of the others: how+ * big, how smooth, how heavy. A preset above is one point in that space; these+ * let the user pick their own.+ */+export const EXPORT_RESOLUTIONS = [+ { id: "2160", label: "4K", shortSide: 2160 },+ { id: "1440", label: "1440p", shortSide: 1440 },+ { id: "1080", label: "1080p", shortSide: 1080 },+ { id: "720", label: "720p", shortSide: 720 },+] as const;++export const EXPORT_FRAME_RATES = [24, 30, 60] as const;++export const EXPORT_QUALITIES = [+ { id: "high", label: "High", detail: "best quality", crf: 19, preset: "medium" },+ { id: "balanced", label: "Balanced", detail: "smaller file", crf: 23, preset: "fast" },+ { id: "small", label: "Small", detail: "fastest render", crf: 28, preset: "veryfast" },+] as const;++export type ExportQualityId = (typeof EXPORT_QUALITIES)[number]["id"];++/** The user's whole choice, as the dialog holds it. */+export interface ExportChoice {+ /** A `resolutionOptions` id; one the project lacks falls back to "source". */+ resolution: string;+ fps: number;+ quality: ExportQualityId;+ codec: ExportCodec;+ container: ExportContainer;+ audioCodec: ExportAudioCodec;+ /** Megabits per second the user typed; absent = the tier. */+ bitrateMbps?: number;+}++/**+ * One-click exports. Each is a whole choice, so picking one sets every+ * advanced control at once, and the advanced panel shows what it stands for.+ */+export const EXPORT_QUICK_PRESETS = [+ {+ id: "share",+ label: "Share",+ detail: "1080p · plays everywhere",+ choice: { resolution: "1080", fps: 30, quality: "balanced", ...DELIVERY_DEFAULTS },+ },+ {+ id: "best",+ label: "Best",+ detail: "source size · H.264",+ choice: { resolution: "source", fps: 30, quality: "high", ...DELIVERY_DEFAULTS },+ },+ {+ id: "small",+ label: "Small",+ detail: "720p · fastest",+ choice: { resolution: "720", fps: 30, quality: "small", ...DELIVERY_DEFAULTS },+ },+ {+ id: "master",+ label: "Master",+ detail: "ProRes 422 HQ · MOV · PCM",+ choice: { resolution: "source", fps: 30, quality: "high", codec: "prores", container: "mov", audioCodec: "pcm" },+ },+] as const satisfies readonly { id: string; label: string; detail: string; choice: ExportChoice }[];++/** The quick preset a choice is, when it is one. */+export function quickPresetOf(choice: ExportChoice, options: ResolutionOption[]): string | null {+ const key = (c: ExportChoice) =>+ [resolveResolution(options, c.resolution).id, c.fps, c.quality, c.codec, c.container, c.audioCodec, c.bitrateMbps ?? ""].join("|");+ const k = key(choice);+ return EXPORT_QUICK_PRESETS.find((p) => key(p.choice) === k)?.id ?? null;+}++/** The option a resolution id names, or the source frame when the project+ * has no such rung. */+export function resolveResolution(options: ResolutionOption[], id: string): ResolutionOption {+ return options.find((r) => r.id === id) ?? options[0];+}++/** The settings a choice adds up to, with the container fitted to the codec+ * and audio it has to carry. */+export function choiceSettings(choice: ExportChoice, options: ResolutionOption[]): ExportSettings {+ const q = EXPORT_QUALITIES.find((x) => x.id === choice.quality) ?? EXPORT_QUALITIES[0];+ const r = resolveResolution(options, choice.resolution);+ return fitContainer({+ width: r.width,+ height: r.height,+ fps: choice.fps,+ crf: q.crf,+ preset: q.preset,+ codec: choice.codec,+ container: choice.container,+ audioCodec: choice.audioCodec,+ // ProRes has one rate per profile; a typed bitrate is for the other codecs.+ ...(choice.bitrateMbps && choice.codec !== "prores"+ ? { bitrate: Math.round(choice.bitrateMbps * 1_000_000) }+ : {}),+ });+}++/** A size the dialog offers: the source's own frame, or a named rung under it. */+export interface ResolutionOption {+ id: string;+ label: string;+ width: number;+ height: number;+}++/**+ * The sizes this project can be exported at, largest first.+ *+ * "Source" leads and is the frame the footage justifies. The named rungs below+ * it are the ones genuinely smaller — a rung that matches or exceeds the source+ * would be the same render under a second name, or an upscale, and the dialog+ * offers neither.+ */+export function resolutionOptions(+ aspect: Aspect,+ clips: VideoClip[],+ assets: MediaAsset[]+): ResolutionOption[] {+ const src = sourceFrame(aspect, clips, assets);+ const srcShort = Math.min(src.width, src.height);+ return [+ { id: "source", label: "Source", ...src },+ ...EXPORT_RESOLUTIONS.filter((r) => r.shortSide < srcShort).map((r) => ({+ id: r.id,+ label: r.label,+ ...scaledFrame(aspect, r.shortSide),+ })),+ ];+}+/** 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);@@ -91,6 +271,15 @@ export function originalSettings(clips: VideoClip[],assets: MediaAsset[]): ExportSettings {+ return { ...sourceFrame(aspect, clips, assets), fps: 30, crf: 19, preset: "medium", ...DELIVERY_DEFAULTS };+}++/** The frame `originalSettings` renders at — see its note for the rules. */+export function sourceFrame(+ aspect: Aspect,+ clips: VideoClip[],+ assets: MediaAsset[]+): { width: number; height: number } {const base = frameOf(aspect);const longBase = Math.max(base.w, base.h);const srcLong = Math.max(@@ -106,23 +295,23 @@ export function originalSettings(Math.min(2, Math.max(1, srcLong / longBase || 1)));const even = (n: number) => 2 * Math.round((n * k) / 2);- return { width: even(base.w), height: even(base.h), fps: 30, crf: 19, preset: "medium" };+ return { width: even(base.w), height: even(base.h) };}/**- * Rough output size for a preset, in bytes. The encoder is CRF (variable- * bitrate), so this is a heuristic: it models H.264 bits-per-pixel as halving- * every +6 CRF from a ~0.08 bpp anchor at CRF 23, scaled by frame area and fps,- * plus the fixed 192 kbps AAC audio. Busy footage runs larger and flat footage- * smaller, so the dialog shows it as an approximation, not a promise.+ * Rough output size for a setting, in bytes: the video bitrate the encoders+ * are given (`bitrateFor`) plus the fixed 192 kbps AAC audio. A CRF encode+ * spends what the footage needs, so busy footage runs larger and flat footage+ * smaller; the dialog shows it as an approximation.*/export function estimateExportBytes(settings: ExportSettings, durationSec: number): number {if (durationSec <= 0) return 0;- const pixelsPerSec = settings.width * settings.height * settings.fps;- const bpp = 0.08 * 2 ** ((23 - settings.crf) / 6);- const videoBps = pixelsPerSec * bpp;- const audioBps = 192_000;- return ((videoBps + audioBps) * durationSec) / 8;+ return ((bitrateFor(settings) + audioBitrate(settings)) * durationSec) / 8;+}++/** AAC at the fixed 192 kbps; PCM is 48 kHz stereo 16-bit, uncompressed. */+export function audioBitrate(settings: Pick<ExportSettings, "audioCodec">): number {+ return settings.audioCodec === "pcm" ? 48_000 * 16 * 2 : 192_000;}/** Human-readable size estimate matching the finished-export MB display. */@@ -1074,6 +1263,25 @@ export async function buildExportPayload(};}+/**+ * A cloud gate said no — the account is signed out, over its storage, or at+ * its render cap. The worker would say the same, so the export ends here with+ * the gate's own words.+ */+export class ExportRefusedError extends Error {}++/** Concurrent PUTs a cloud export's inputs go up on. */+const UPLOAD_LANES = 4;++function cloudRefusal(res: Response, body: { error?: string; bytes?: number; quotaBytes?: number } | null | undefined): ExportRefusedError | null {+ if (res.ok) return null;+ if (res.status === 401) return new ExportRefusedError("Sign in to render this export in the cloud.");+ const quota = quotaErrorMessage(res.status, body);+ if (quota) return new ExportRefusedError(quota);+ if (res.status === 429 || res.status === 413) return new ExportRefusedError(body?.error ?? "Export failed to start.");+ return null;+}+/** Serialize a payload to the engine's multipart form: PNGs in render order,* then the spec — the exact request shape from before the payload split. */function exportFormFromPayload({ spec, pngs }: ExportPayload): FormData {@@ -1093,7 +1301,8 @@ async function postExport(payload: ExportPayload,outName: string,backend: CutBackend,- extra?: Record<string, unknown>+ extra?: Record<string, unknown>,+ signal?: AbortSignal): Promise<Response> {if (backend.kind !== "cloud") {return backend.fetch("/api/cut/export", { method: "POST", body: exportFormFromPayload(payload) });@@ -1111,19 +1320,21 @@ async function postExport(const preBody =await apiJson<{ files?: { name: string; key: string; type?: string; url: string }[] }>(pre);if (!pre.ok || !preBody.files) {- throw new Error(- quotaErrorMessage(pre.status, preBody) ?? preBody.error ?? "Export failed to start."- );+ throw cloudRefusal(pre, preBody) ?? new Error(preBody.error ?? "Export failed to start.");}const byName = new Map(preBody.files.map((f) => [f.name, f]));+ // The list carries a borrowed render's whole media set, so the PUTs go a+ // few at a time, and a cancel stops the ones still in flight.+ const queue = [...payload.pngs];await Promise.all(- payload.pngs.map(async (p) => {- const target = byName.get(p.name);- if (!target) throw new Error("Export failed to start.");- // The content type the URL was signed with, not the blob's: they agree- // for the PNG frames and differ for the behind-speaker mask clip, and- // sending anything but the signed one fails the signature.- await putSigned(target.url, p.blob, target.type || "image/png");+ Array.from({ length: Math.min(UPLOAD_LANES, queue.length) }, async () => {+ for (let p = queue.shift(); p; p = queue.shift()) {+ const target = byName.get(p.name);+ if (!target) throw new Error("Export failed to start.");+ // The content type the URL was signed with: it is the one the+ // signature covers, and for a video it differs from the blob's.+ await putSigned(target.url, p.blob, target.type || "image/png", { signal });+ }}));for (const p of payload.pngs) overlays.push({ name: p.name, key: byName.get(p.name)!.key });@@ -1137,10 +1348,10 @@ async function postExport(/** The cloud names the output client-side (the engine derives it from the* project name itself, deduping on disk); mirror the engine's sanitize rule. */-function exportOutName(): string {+function exportOutName(settings: ExportSettings): string {const base =useEditor.getState().projectName.replace(/[/\\:*?"<>|]/g, "").trim().slice(0, 60) || "export";- return `${base}.mp4`;+ return `${base}${exportExtension(settings)}`;}/** Poll an export job to completion, reporting progress. Returns the file name. */@@ -1186,14 +1397,12 @@ export async function createExportJob(): Promise<string> {const backend = getBackend(); // pinned: the payload build takes a whileconst payload = await buildExportPayload(projectId, doc, settings, "export");- const res = await postExport(projectId, payload, exportOutName(), backend);+ const res = await postExport(projectId, payload, exportOutName(settings), backend);const body = await apiJson<{ id?: string }>(res);if (!res.ok || !body.id) {// A quota rejection raises the upgrade wall on its way through, the same as// one from an upload — otherwise the only sign is a terse line in the dock.- throw new Error(- quotaErrorMessage(res.status, body) ?? body.error ?? "Export failed to start."- );+ throw cloudRefusal(res, body) ?? new Error(body.error ?? "Export failed to start.");}return body.id;}@@ -1237,13 +1446,11 @@ export async function runBrowserExport(const claim = await backend.fetch("/api/cut/export/client/presign", {method: "POST",headers: { "Content-Type": "application/json" },- body: JSON.stringify({ projectId, outName: exportOutName() }),+ body: JSON.stringify({ projectId, outName: exportOutName(settings) }),});- const claimed = await apiJson<{ jobId?: string; url?: string; outName?: string }>(claim);+ const claimed = await apiJson<{ jobId?: string; url?: string; outName?: string; type?: string }>(claim);if (!claim.ok || !claimed.jobId || !claimed.url) {- throw new Error(- quotaErrorMessage(claim.status, claimed) ?? claimed.error ?? "Export failed to start."- );+ throw cloudRefusal(claim, claimed) ?? new Error(claimed.error ?? "Export failed to start.");}const jobId = claimed.jobId;opts.onClaimed?.(jobId);@@ -1264,7 +1471,7 @@ export async function runBrowserExport(});try {- await putSigned(claimed.url, rendered.file, "video/mp4", {+ await putSigned(claimed.url, rendered.file, claimed.type ?? "video/mp4", {signal: opts.signal,onProgress: (fraction) => opts.onProgress?.(0.9 + fraction * 0.1),});@@ -1320,7 +1527,7 @@ async function runStoreExport(});let outName: string;try {- outName = await saveExport(projectId, rendered.file, exportOutName());+ outName = await saveExport(projectId, rendered.file, exportOutName(settings));} finally {void rendered.discard();}@@ -1345,6 +1552,108 @@ async function runStoreExport(}}+/**+ * Render a browser-resident project on the cloud worker.+ *+ * The tab is that project's whole machine, and when it cannot carry a render+ * — no encoder for the codec, ProRes, scratch storage that gives out — the+ * worker is the machine it borrows. The cut's media lives only in this+ * browser, so it rides up with the job beside the overlay stills, the worker+ * renders from those uploads, and the finished file comes back down into the+ * project's own exports folder. The cloud keeps nothing: the uploads and the+ * output are the job's scratch, gone when the job is dismissed or swept.+ */+async function runBorrowedExport(+ projectId: string,+ doc: ExportDoc,+ settings: ExportSettings,+ opts: Parameters<typeof runBrowserExport>[3] = {}+): Promise<string> {+ const job = reserveBrowserExportJob(projectId, opts.projectName);+ opts.onClaimed?.(job.id);+ let cloudJobId: string | null = null;+ const stop = () => {+ if (opts.signal?.aborted) throw new DOMException("Export canceled.", "AbortError");+ };+ // The payload build reads the project's store-served blob URLs and can take+ // a while; the hold keeps them alive if the user opens another project+ // meanwhile, and the asset's URL is read live for the same reason.+ holdRegistered(`/api/cut/projects/${projectId}/`);+ try {+ const payload = await buildExportPayload(projectId, doc, settings, "export");+ stop();+ for (const name of specMediaFiles(payload.spec as Parameters<typeof specMediaFiles>[0])) {+ const asset = doc.assets.find((a) => a.fileName === name);+ const url = asset+ ? (useEditor.getState().assets.find((a) => a.id === asset.id)?.url ?? asset.url)+ : null;+ const blob = url ? resolveRegisteredBlob(url) : null;+ if (!blob) throw new Error(`${name} is not in this browser's storage.`);+ payload.pngs.push({ name, blob });+ }+ const res = await postExport(+ projectId,+ payload,+ exportOutName(settings),+ cloudBackend,+ { mediaFrom: "overlays" },+ opts.signal+ );+ const body = await apiJson<{ id?: string }>(res);+ if (!res.ok || !body.id) {+ throw cloudRefusal(res, body) ?? new Error(body.error ?? "Export failed to start.");+ }+ cloudJobId = body.id;+ // The cloud row is this export too; the dock shows the local row alone.+ opts.onClaimed?.(cloudJobId);+ const outName = await pollExport(+ cloudJobId,+ (_stage, ratio) => {+ opts.onProgress?.(ratio * 0.95);+ updateBrowserExportJob(job.id, { progress: ratio * 0.95 });+ },+ () => !!opts.signal?.aborted,+ cloudBackend+ );+ stop();+ const fileRes = await cloudBackend.fetch(`/api/cut/export/${cloudJobId}/file`, {+ signal: opts.signal,+ });+ if (!fileRes.ok) throw new Error("Could not fetch the rendered export.");+ const file = new File([await fileRes.blob()], outName, {+ type: deliveryContainer(settings.container).mime,+ });+ stop();+ const saved = await saveExport(projectId, file, outName);+ const stored = await readFileAt(await exportsDir(projectId), saved);+ if (stored) {+ registerBlobFile(`/api/cut/export/${job.id}/file`, stored);+ registerBlobFile(`/api/cut/projects/${projectId}/exports/${encodeURIComponent(saved)}`, stored);+ }+ updateBrowserExportJob(job.id, { status: "done", progress: 1, outName: saved });+ // The cloud's copy was the job's scratch; dismissing the job drops it.+ cancelExportJob(cloudJobId, cloudBackend);+ return job.id;+ } catch (err) {+ if (cloudJobId) cancelExportJob(cloudJobId, cloudBackend);+ removeBrowserExportJob(job.id);+ throw err;+ } finally {+ releaseRegistered(`/api/cut/projects/${projectId}/`);+ }+}++/** The cloud renders a browser-resident project's export when its tab+ * cannot; see `runBorrowedExport`. */+export function runBrowserExportInCloud(+ projectId: string,+ doc: ExportDoc,+ settings: ExportSettings,+ opts: Parameters<typeof runBrowserExport>[3] = {}+): Promise<string> {+ return runBorrowedExport(projectId, doc, settings, opts);+}+/** Cancel a running or queued export job, or retire a settled one from the* export-jobs feed. */export function cancelExportJob(jobId: string, backend: CutBackend = getBackend()) {@@ -1404,7 +1713,7 @@ export async function renderShareLadder(* footage yet. */export async function renderPreviewProxy(projectId: string, doc: ExportDoc) {const backend = getBackend(); // pinned: the proxy render outlives navigation- const settings: ExportSettings = { ...scaledFrame(doc.aspect, 360), fps: 24, crf: 30, preset: "veryfast" };+ const settings: ExportSettings = { ...scaledFrame(doc.aspect, 360), fps: 24, crf: 30, preset: "veryfast", ...DELIVERY_DEFAULTS };let res: Response;try {const payload = await buildExportPayload(projectId, doc, settings, "preview");@@ -1461,7 +1770,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 {- return { ...scaledFrame(aspect, 720), fps: 15, crf: 26, preset: "veryfast" };+ return { ...scaledFrame(aspect, 720), fps: 15, crf: 26, preset: "veryfast", ...DELIVERY_DEFAULTS };}/** Render the project's link-preview card: the opening five seconds, whichdiff --git a/site/src/cut/lib/exportDelivery.ts b/site/src/cut/lib/exportDelivery.tsnew file mode 100644index 00000000..1fb2c5b9--- /dev/null+++ b/site/src/cut/lib/exportDelivery.ts@@ -0,0 +1,77 @@+/**+ * What a delivered file is: its container, the codec inside, and the model+ * that turns a quality tier into a bitrate. Pure, so the tab, the engine, the+ * cloud routes and the worker all read the one table.+ */++export type ExportCodec = "h264" | "hevc" | "prores";+export type ExportContainer = "mp4" | "mov";+export type ExportAudioCodec = "aac" | "pcm";++export interface DeliveryContainer {+ id: ExportContainer;+ label: string;+ ext: string;+ mime: string;+}++export const EXPORT_CONTAINERS: readonly DeliveryContainer[] = [+ { id: "mp4", label: "MP4", ext: ".mp4", mime: "video/mp4" },+ { id: "mov", label: "MOV", ext: ".mov", mime: "video/quicktime" },+];++export function deliveryContainer(id: ExportContainer | undefined): DeliveryContainer {+ return EXPORT_CONTAINERS.find((c) => c.id === id) ?? EXPORT_CONTAINERS[0];+}++/** The container a delivered file's name says it is; MP4 when the name says+ * nothing this table knows. */+export function containerOfName(name: string): DeliveryContainer {+ const lower = name.toLowerCase();+ return EXPORT_CONTAINERS.find((c) => lower.endsWith(c.ext)) ?? EXPORT_CONTAINERS[0];+}++/** Whether a file name is one the export writes. */+export function isDeliveryName(name: string): boolean {+ const lower = name.toLowerCase();+ return EXPORT_CONTAINERS.some((c) => lower.endsWith(c.ext));+}++/**+ * The video bitrate a setting asks for, in bits per second: H.264+ * bits-per-pixel halving every +6 CRF from a ~0.08 bpp anchor at CRF 23, HEVC+ * landing the same tier in about 60% of the bits, ProRes 422 HQ a fixed ~3.5+ * bits a pixel (220 Mbit/s at 1080p30). A bitrate the user typed wins.+ *+ * WebCodecs and VideoToolbox encode to a bitrate while the tiers are written+ * in CRF; this is the one model they share with the dialog's size estimate, so+ * the file lands at the size the user was shown.+ */+export function videoBitrateFor(s: {+ width: number;+ height: number;+ fps: number;+ crf: number;+ codec?: ExportCodec;+ bitrate?: number;+}): number {+ const pixelsPerSec = s.width * s.height * s.fps;+ if (s.codec === "prores") return Math.round(pixelsPerSec * 3.54);+ if (s.bitrate) return s.bitrate;+ const bpp = 0.08 * 2 ** ((23 - s.crf) / 6) * (s.codec === "hevc" ? 0.6 : 1);+ return Math.max(200_000, Math.round(pixelsPerSec * bpp));+}++/** Every media file a render spec plays — clips, picture-in-picture video,+ * sound — by name, once each. */+export function specMediaFiles(spec: {+ clips?: { file?: string }[];+ overlayVideos?: { file?: string }[];+ audio?: { file?: string }[];+}): string[] {+ const names = new Set<string>();+ for (const c of [...(spec.clips ?? []), ...(spec.overlayVideos ?? []), ...(spec.audio ?? [])]) {+ if (c?.file) names.add(c.file);+ }+ return [...names];+}diff --git a/site/src/cut/lib/exportRender.test.ts b/site/src/cut/lib/exportRender.test.tsindex e93f5b46..189040fe 100644--- a/site/src/cut/lib/exportRender.test.ts+++ b/site/src/cut/lib/exportRender.test.ts@@ -136,16 +136,31 @@ describe("mixSpecFor", () => {});});+const DELIVERY = { codec: "h264", container: "mp4", audioCodec: "aac" } as const;+describe("bitrateFor", () => {test("spends more bits on a lower CRF", () => {- const base = { width: 1920, height: 1080, fps: 30, preset: "medium" };+ const base = { width: 1920, height: 1080, fps: 30, preset: "medium", ...DELIVERY };expect(bitrateFor({ ...base, crf: 19 })).toBeGreaterThan(bitrateFor({ ...base, crf: 24 }));});test("scales with frame area", () => {- const base = { fps: 30, crf: 23, preset: "medium" };+ const base = { fps: 30, crf: 23, preset: "medium", ...DELIVERY };expect(bitrateFor({ ...base, width: 1920, height: 1080 })).toBeGreaterThan(bitrateFor({ ...base, width: 1280, height: 720 }));});});++describe("bitrateFor by delivery", () => {+ const base = { width: 1920, height: 1080, fps: 30, crf: 23, preset: "medium", container: "mp4", audioCodec: "aac" } as const;+ test("HEVC asks for fewer bits than H.264 at the same tier", () => {+ expect(bitrateFor({ ...base, codec: "hevc" })).toBeLessThan(bitrateFor({ ...base, codec: "h264" }));+ });+ test("ProRes is a fixed rate, above any tier", () => {+ expect(bitrateFor({ ...base, codec: "prores" })).toBeGreaterThan(bitrateFor({ ...base, codec: "h264", crf: 10 }));+ });+ test("a typed bitrate wins", () => {+ expect(bitrateFor({ ...base, codec: "h264", bitrate: 1_234_000 })).toBe(1_234_000);+ });+});diff --git a/site/src/cut/lib/exportRender.ts b/site/src/cut/lib/exportRender.tsindex f3c7dea0..6e09750a 100644--- a/site/src/cut/lib/exportRender.ts+++ b/site/src/cut/lib/exportRender.ts@@ -20,11 +20,13 @@ import {CanvasSource,getFirstEncodableAudioCodec,getFirstEncodableVideoCodec,+ MovOutputFormat,Mp4OutputFormat,Output,AudioBufferSource,Quality,StreamTarget,+ type AudioCodec,type VideoCodec,} from "mediabunny";import { audioFxSpans } from "./audioEffects";@@ -44,14 +46,37 @@ import { renderElementPng } from "./textRender";import { assetIsSilent, behindSubjectOverlay, clipCovers, frameOf, frontSubjectOverlay, isEffectOverlay, isTextOverlay, laneOf, overlayAnimStyle, projectBackground, projectFadeSeconds, rectOf, removalActive } from "./types";import type { ClipSpan, EffectOverlay, MediaAsset, Overlay, StickerOverlay } from "./types";import type { ExportDoc, ExportSettings } from "./exportClient";+import { videoBitrateFor } from "./exportDelivery";/** Audio is written at the rate and width a delivery file wants, rather than* the 16 kHz mono a speech model reads. */const AUDIO_RATE = 48000;const AUDIO_CHANNELS = 2;-/** Video codecs to try, best first. */-export const VIDEO_CODECS: VideoCodec[] = ["avc", "hevc", "vp9", "av1"];+/**+ * What a delivered file is made of: the codec the user chose, and nothing in+ * its place.+ *+ * The container is only half of whether a file opens. An .mp4 carrying VP9,+ * AV1, or Opus is a valid file that QuickTime, the Finder preview, and most+ * phones refuse — the user gets something they cannot play and cannot convert.+ * So there is no second codec to fall back to: a browser that cannot encode+ * the chosen one at the chosen size fails `canRenderInBrowser`, and the export+ * goes where that codec is available — the worker for a cloud project, the+ * Mac app or the cloud for a browser-resident one. ProRes has no WebCodecs+ * encoder anywhere, so it always takes that road.+ */+export function deliveryVideoCodec(settings: ExportSettings): VideoCodec | null {+ return settings.codec === "h264" ? "avc" : settings.codec === "hevc" ? "hevc" : null;+}+export function deliveryAudioCodec(settings: ExportSettings): AudioCodec {+ return settings.audioCodec === "pcm" ? "pcm-s16" : "aac";+}++/** Codecs a working clip may use — the removal bakes and the behind-speaker+ * mask, which only this app's decoders and ffmpeg ever read, and both take+ * any of these. A file that leaves the app uses `deliveryVideoCodec`. */+export const WORKING_VIDEO_CODECS: VideoCodec[] = ["avc", "hevc", "vp9", "av1"];export interface RenderProgress {/** 0..1 across the whole render. */@@ -111,18 +136,10 @@ export interface RenderOptions {signal?: AbortSignal;}-/**- * The bitrate a preset's CRF asks for, in bits per second.- *- * WebCodecs encodes to a bitrate; the presets are written in CRF, which is a- * quality target the encoder spends whatever it needs to hit. The conversion- * is the same bits-per-pixel model the export dialog already estimates sizes- * with, so a preset keeps meaning roughly what it meant.- */+/** The bitrate the choice asks for — the model in `exportDelivery`, which+ * the engine and the dialog's estimate read too. */export function bitrateFor(settings: ExportSettings): number {- const pixelsPerSec = settings.width * settings.height * settings.fps;- const bpp = 0.08 * 2 ** ((23 - settings.crf) / 6);- return Math.round(pixelsPerSec * bpp);+ return videoBitrateFor(settings);}/** The frame reader for one open video source. */@@ -690,6 +707,12 @@ export function mixSpecFor(doc: ExportDoc, resolve: (asset: MediaAsset) => strin};}+/** Whether a mix spec has anything audible in it — the same test the mixer+ * uses to decide which spans it decodes. */+export function mixHasSound(spec: MixSpec): boolean {+ return spec.clips.some((c) => c.file && !c.muted) || spec.items.some((i) => !i.muted);+}+/** Whole-video fade gain at `t`, the picture's side of the project fade. */function projectFadeGain(doc: ExportDoc, t: number, total: number): number {const fadeIn = projectFadeSeconds(doc.fadeIn, total);@@ -726,11 +749,17 @@ export async function renderProjectToMp4(const duration = projectDuration(doc);if (!(duration > 0)) throw new Error("There is nothing to export yet.");- const codec = await getFirstEncodableVideoCodec(VIDEO_CODECS, {+ const wanted = deliveryVideoCodec(settings);+ if (!wanted) throw new Error("This browser can't encode ProRes.");+ const codec = await getFirstEncodableVideoCodec([wanted], {width: settings.width,height: settings.height,});- if (!codec) throw new Error("This browser can't encode video.");+ if (!codec) {+ throw new Error(+ `This browser can't encode ${settings.codec === "hevc" ? "HEVC" : "H.264"} at ${settings.width} × ${settings.height}.`+ );+ }const stop = () => {if (signal?.aborted) throw new DOMException("Export canceled.", "AbortError");@@ -763,7 +792,10 @@ export async function renderProjectToMp4(};const output = new Output({- format: new Mp4OutputFormat({ fastStart: "reserve" }),+ format:+ settings.container === "mov"+ ? new MovOutputFormat({ fastStart: "reserve" })+ : new Mp4OutputFormat({ fastStart: "reserve" }),target: new StreamTarget(writable, { chunked: true }),});@@ -774,22 +806,25 @@ export async function renderProjectToMp4(});// Reserving the index space needs a packet ceiling per track. The video's// is exact — one packet per frame; the audio's is the mix's sample count- // over the smallest samples-per-packet a codec here uses (Opus's 960; AAC- // packs more), plus slack for encoder priming.+ // over a floor below the samples a packet carries (AAC packs 1024, the+ // muxer's own PCM 2048), plus slack for encoder priming. Over-reserving+ // costs a few bytes of index; under-reserving fails the finalize.output.addVideoTrack(video, { frameRate: settings.fps, maximumPacketCount: frames + 8 });let audio: AudioBufferSource | null = null;if (mix) {- const audioCodec = await getFirstEncodableAudioCodec(["aac", "opus"], {+ // PCM is packed by the muxer itself; AAC needs the browser's encoder,+ // and a cut with sound keeps it: an Opus stand-in plays nowhere the+ // user is taking the file, so a browser without AAC hands the render on.+ const audioCodec = await getFirstEncodableAudioCodec([deliveryAudioCodec(settings)], {numberOfChannels: AUDIO_CHANNELS,sampleRate: AUDIO_RATE,});- if (audioCodec) {- audio = new AudioBufferSource({- codec: audioCodec,- quality: new Quality({ bitrate: 192_000 }),- });- output.addAudioTrack(audio, { maximumPacketCount: Math.ceil(mix.length / 960) + 32 });- }+ if (!audioCodec) throw new Error("This browser can't encode AAC audio.");+ audio = new AudioBufferSource({+ codec: audioCodec,+ ...(audioCodec === "aac" ? { quality: new Quality({ bitrate: 192_000 }) } : {}),+ });+ output.addAudioTrack(audio, { maximumPacketCount: Math.ceil(mix.length / 960) + 32 });}await output.start();@@ -1280,9 +1315,20 @@ export async function canRenderInBrowser(return false;}try {- return !!(await getFirstEncodableVideoCodec(VIDEO_CODECS, {+ const wanted = deliveryVideoCodec(settings);+ if (!wanted) return false;+ const video = await getFirstEncodableVideoCodec([wanted], {width: settings.width,height: settings.height,+ });+ if (!video) return false;+ // A cut with sound needs the audio half of the file too; a browser with+ // no AAC encoder would otherwise render the whole thing and fail at the+ // muxer, or hand back a video whose sound went missing.+ if (!mixHasSound(mixSpecFor(doc, (a) => a.url))) return true;+ return !!(await getFirstEncodableAudioCodec([deliveryAudioCodec(settings)], {+ numberOfChannels: AUDIO_CHANNELS,+ sampleRate: AUDIO_RATE,}));} catch {return false;diff --git a/site/src/cut/lib/maskVideo.ts b/site/src/cut/lib/maskVideo.tsindex 3aecf9da..09c358c0 100644--- a/site/src/cut/lib/maskVideo.ts+++ b/site/src/cut/lib/maskVideo.ts@@ -25,7 +25,7 @@ import {import { personSegmenter, segmentSubjectAlpha } from "./cutout";import { FrameCompositor, MISSING_FRAME } from "./composite";import { overlayPlan, trackZeroPlan } from "./framePlan";-import { ClipReader, VIDEO_CODECS } from "./exportRender";+import { ClipReader, WORKING_VIDEO_CODECS } from "./exportRender";import type { ExportDoc } from "./exportClient";import { createRasterCanvas } from "./raster";import { getClipSpans } from "./store";@@ -84,7 +84,7 @@ export async function renderSubjectMask(const even = (n: number) => 2 * Math.round((n * scale) / 2);const W = even(frame.w);const H = even(frame.h);- const codec = await getFirstEncodableVideoCodec(VIDEO_CODECS, { width: W, height: H });+ const codec = await getFirstEncodableVideoCodec(WORKING_VIDEO_CODECS, { width: W, height: H });if (!codec) return null;// A small compositor: the video layers only, at mask resolution.diff --git a/site/src/cut/server/ai/catalog.ts b/site/src/cut/server/ai/catalog.tsindex 53bbd81e..70d4c61c 100644--- a/site/src/cut/server/ai/catalog.ts+++ b/site/src/cut/server/ai/catalog.ts@@ -392,7 +392,7 @@ Attachments: media files dropped on the chat import into project media by themse"publish-and-export": `# Publish & exportPublish tab fields (set_publish): caption (TikTok limit 4,000 chars INCLUDING tags/emoji; hook in the first line), tags (3–5 focused tags recommended; stored space-separated, rendered as #tags), soundTitle (TikTok lets you rename the sound once after posting), handle (shown as @handle in platform previews).-Export (open_export): presets Original (matches the sharpest source clip along the aspect, 1080p floor, 4K cap), Best 1080p CRF19, Quick share 1080p, Draft 720p — H.264 + AAC, 30fps, rendered at the project aspect ratio, titles and subtitles burned in. Files land in the project's exports/ folder and appear in the Media tab's Exports section, where each can be previewed plain or in TikTok/Instagram/YouTube chrome with the publish metadata rendered in place, revealed in Finder, or deleted.`,+Export (open_export): one-click presets — Share (1080p H.264 MP4, plays everywhere), Best (source size, H.264 MP4, high quality), Small (720p, fastest), Master (source size, ProRes 422 HQ in a MOV with PCM audio, for handing to another editor) — and an Advanced panel with every axis: format (MP4 or MOV), codec (H.264, HEVC at about half the size for newer devices, ProRes 422 HQ), resolution (Source, which matches the sharpest clip on the timeline along the project aspect with a 1080p floor and a 4K cap, then every named rung below it: 4K, 1440p, 1080p, 720p), frame rate (24, 30 or 60), quality (High, Balanced, Small, or a typed bitrate in Mbps), audio (AAC or uncompressed PCM). ProRes and PCM take a MOV. The dialog shows the size the choice will land at. Every export renders at the project aspect ratio, titles and subtitles burned in. Files land in the project's exports/ folder and appear in the Media tab's Exports section, where each can be previewed plain or in TikTok/Instagram/YouTube chrome with the publish metadata rendered in place, revealed in Finder, or deleted.`,};/** System prompt shared by all providers. */diff --git a/site/src/cut/server/exportPipeline.test.ts b/site/src/cut/server/exportPipeline.test.tsindex e8bfc2f9..30695e47 100644--- a/site/src/cut/server/exportPipeline.test.ts+++ b/site/src/cut/server/exportPipeline.test.ts@@ -9,7 +9,7 @@ import {// Builds the real encode filtergraph for a spec by running the pipeline with// its edges stubbed: media exists, every stream probes present, SDR color,-// libx264, and ffmpeg runs are captured instead of spawned.+// software encoders, and every ffmpeg run is captured for the assertions./** Every ffmpeg run the pipeline made for a spec, in order; the graph is the* one carrying `-filter_complex`. */const runsFor = async (over: Partial<ExportSpec>): Promise<string[][]> => {@@ -26,7 +26,7 @@ const runsFor = async (over: Partial<ExportSpec>): Promise<string[][]> => {videoColorInfo: async () => null,videoDecodeCost: async () => null,mediaDuration: async (file) => produced.get(file) ?? 0,- h264Encoder: async () => "libx264",+ videoEncoder: async (codec) => (codec === "hevc" ? "libx265" : codec === "prores" ? "prores_ks" : "libx264"),runFfmpeg: async (_job, args) => {ffmpegCalls.push(args);const piece = args[args.length - 1].match(/^(.*)\.\d+\.(?:mov|wav)$/);@@ -776,3 +776,49 @@ describe("a reversed clip in the filtergraph", () => {expect(first).toContain(`apad=whole_dur=${retimeOf(curved).len.toFixed(3)}`);});});+++// ---------------------------------------------------------------------------+// Delivery: the encode carries the codec, container and audio the spec asks+// for, and a spec from before those fields existed is the H.264 + AAC MP4 it+// always was.+const encodeRun = async (over: Partial<ExportSpec>) => {+ const runs = await runsFor({ clips: [clip("a.mp4")], ...over });+ return runs.find((a) => a.includes("-filter_complex"))!;+};+const arg = (args: string[], flag: string) => args[args.indexOf(flag) + 1];++describe("delivery", () => {+ test("a spec without delivery fields is an H.264 + AAC MP4", async () => {+ const args = await encodeRun({});+ expect(arg(args, "-c:v")).toBe("libx264");+ expect(arg(args, "-crf")).toBe("24");+ expect(arg(args, "-pix_fmt")).toBe("yuv420p");+ expect(arg(args, "-c:a")).toBe("aac");+ expect(args[args.length - 1].endsWith("encode.mp4")).toBe(true);+ });++ test("HEVC is tagged hvc1 so QuickTime opens it", async () => {+ const args = await encodeRun({ codec: "hevc" });+ expect(arg(args, "-c:v")).toBe("libx265");+ expect(arg(args, "-tag:v")).toBe("hvc1");+ expect(arg(args, "-pix_fmt")).toBe("yuv420p");+ });++ test("a ProRes master writes 10-bit 4:2:2 HQ with PCM into a MOV", async () => {+ const args = await encodeRun({ codec: "prores", container: "mov", audioCodec: "pcm" });+ expect(arg(args, "-c:v")).toBe("prores_ks");+ expect(arg(args, "-profile:v")).toBe("3");+ expect(arg(args, "-pix_fmt")).toBe("yuv422p10le");+ expect(arg(args, "-c:a")).toBe("pcm_s16le");+ expect(args).not.toContain("-crf");+ expect(args[args.length - 1].endsWith("encode.mov")).toBe(true);+ });++ test("a typed bitrate replaces the tier's CRF", async () => {+ const args = await encodeRun({ bitrate: 6_000_000 });+ expect(args).not.toContain("-crf");+ expect(arg(args, "-b:v")).toBe("6000000");+ expect(arg(args, "-maxrate")).toBe("9000000");+ });+});diff --git a/site/src/cut/server/exportPipeline.ts b/site/src/cut/server/exportPipeline.tsindex 1ca52cfe..d39a03db 100644--- a/site/src/cut/server/exportPipeline.ts+++ b/site/src/cut/server/exportPipeline.ts@@ -1,4 +1,5 @@import { spawn, type ChildProcess } from "node:child_process";+import { deliveryContainer, videoBitrateFor } from "../lib/exportDelivery";import { readFile, stat, unlink, writeFile } from "node:fs/promises";import path from "node:path";import { atempoChain, hasStream, mediaDuration, num, videoColorInfo, videoDecodeCost } from "./util";@@ -62,6 +63,12 @@ export interface ExportSpec {fps: number;crf: number;preset: string;+ /** The delivery. A spec from before these existed is an H.264 + AAC MP4. */+ codec?: "h264" | "hevc" | "prores";+ container?: "mp4" | "mov";+ audioCodec?: "aac" | "pcm";+ /** A bitrate the user typed, bits per second; absent = the `crf` tier. */+ bitrate?: number;duration: number;/** Whole-video fades, seconds: in from black / out to black, applied to the* final composite and mix after all overlays and soundtrack. */@@ -323,23 +330,102 @@ export interface RenderHandle {* Homebrew ffmpeg does. The bundled engine ffmpeg is LGPL (`--disable-gpl`), so* it has no libx264 and `-preset`/`-crf` don't exist there; fall back to the* always-present VideoToolbox hardware H.264 encoder. */-let h264EncoderCache: Promise<"libx264" | "h264_videotoolbox"> | null = null;-export function h264Encoder(): Promise<"libx264" | "h264_videotoolbox"> {- return (h264EncoderCache ??= new Promise((resolve) => {+/** The encoders this machine's ffmpeg carries, read once. An ffmpeg that+ * cannot be asked answers empty, and the picks below then fall to the names+ * the Mac's bundled build has. */+let encodersCache: Promise<Set<string>> | null = null;+function ffmpegEncoders(): Promise<Set<string>> {+ return (encodersCache ??= new Promise((resolve) => {let out = "";const proc = spawn("ffmpeg", ["-hide_banner", "-encoders"]);proc.stdout?.on("data", (c: Buffer) => (out += c.toString()));- proc.on("error", () => resolve("h264_videotoolbox"));- proc.on("close", () => resolve(/\blibx264\b/.test(out) ? "libx264" : "h264_videotoolbox"));+ proc.on("error", () => resolve(new Set()));+ proc.on("close", () =>+ resolve(new Set(out.split("\n").map((l) => l.trim().split(/\s+/)[1]).filter(Boolean)))+ );}));}-/** VideoToolbox constant quality (1–100, higher = better) from the CRF knob the- * presets carry (lower CRF = better). Maps the 19/24/30 tiers to ~66/57/46. */+export async function h264Encoder(): Promise<"libx264" | "h264_videotoolbox"> {+ return (await ffmpegEncoders()).has("libx264") ? "libx264" : "h264_videotoolbox";+}++export type ExportVideoCodec = NonNullable<ExportSpec["codec"]>;++/**+ * The ffmpeg encoder for a delivery codec: the software one where the build+ * has it (the worker's Debian ffmpeg), VideoToolbox on the Mac's LGPL build,+ * and ffmpeg's own ProRes writer, which every build carries.+ */+export async function videoEncoder(codec: ExportVideoCodec): Promise<string> {+ const have = await ffmpegEncoders();+ if (codec === "prores") return "prores_ks";+ if (codec === "hevc") return have.has("libx265") ? "libx265" : "hevc_videotoolbox";+ return have.has("libx264") ? "libx264" : "h264_videotoolbox";+}++/** VideoToolbox constant quality (1–100, higher = better) from the CRF knob a+ * fixed-quality convert carries (lower CRF = better). Maps 19/24/30 to+ * ~66/57/46. */export function vtQuality(crf: number) {return Math.round(Math.max(35, Math.min(80, 100 - crf * 1.8)));}+/**+ * The bitrate an export's quality choice asks for at these dimensions, in bits+ * per second: H.264 bits-per-pixel halving every +6 CRF from a ~0.08 bpp anchor+ * at CRF 23.+ *+ * VideoToolbox is what the bundled ffmpeg has — the LGPL build carries no+ * libx264 — and it has neither CRF nor `-preset`. Handed `-q:v`, the quality+ * knob folded the whole preset range into a few points of constant quality:+ * every choice in the export dialog rendered at the same size and took the same+ * time, so picking "Quick share" gave back the "Best" file. A bitrate target+ * keeps the choice meaningful, and `videoBitrateFor` is the same model the+ * dialog quotes its size estimate from, so the file matches what the user was+ * shown.+ */+export function targetBitrate(width: number, height: number, fps: number, crf: number, codec: ExportVideoCodec = "h264") {+ return videoBitrateFor({ width, height, fps, crf, codec });+}++/**+ * The encoder's own arguments for a spec's delivery: the codec, its rate+ * control, the pixel format and profile players expect of it, and for HEVC the+ * `hvc1` tag QuickTime requires. ffmpeg's ProRes writer has one quality per+ * profile, so the tier and bitrate do not reach it.+ */+export function videoCodecArgs(enc: string, spec: ExportSpec): string[] {+ const codec = spec.codec ?? "h264";+ const bitrate = videoBitrateFor({ ...spec, codec });+ const rate = ["-b:v", String(bitrate), "-maxrate", String(Math.round(bitrate * 1.5)), "-bufsize", String(bitrate * 3)];+ switch (enc) {+ case "libx264":+ return ["-c:v", "libx264", "-preset", spec.preset, ...(spec.bitrate ? rate : ["-crf", String(spec.crf)]), "-profile:v", "high", "-pix_fmt", "yuv420p"];+ case "h264_videotoolbox":+ return ["-c:v", "h264_videotoolbox", ...rate, "-profile:v", "high", "-pix_fmt", "yuv420p", "-allow_sw", "1"];+ case "libx265":+ // x265's CRF scale sits about four points above x264's for the same picture.+ return ["-c:v", "libx265", "-preset", spec.preset, ...(spec.bitrate ? rate : ["-crf", String(spec.crf + 4)]), "-x265-params", "log-level=error", "-tag:v", "hvc1", "-pix_fmt", "yuv420p"];+ case "hevc_videotoolbox":+ return ["-c:v", "hevc_videotoolbox", ...rate, "-profile:v", "main", "-tag:v", "hvc1", "-pix_fmt", "yuv420p", "-allow_sw", "1"];+ case "prores_ks":+ return ["-c:v", "prores_ks", "-profile:v", "3", "-vendor", "apl0", "-pix_fmt", "yuv422p10le"];+ default:+ throw new Error(`No encoder for ${codec}.`);+ }+}++/** The audio arguments for a spec's delivery. */+export function audioCodecArgs(spec: ExportSpec): string[] {+ return spec.audioCodec === "pcm" ? ["-c:a", "pcm_s16le"] : ["-c:a", "aac", "-b:a", "192k"];+}++/** The file extension a spec's container takes. */+export function containerExtension(spec: Pick<ExportSpec, "container">): string {+ return deliveryContainer(spec.container).ext;+}+async function resolveMedia(statFn: typeof stat,mediaPathFor: (file: string) => string,@@ -471,7 +557,7 @@ export interface ExportPipelineIO {videoColorInfo: typeof videoColorInfo;videoDecodeCost: typeof videoDecodeCost;mediaDuration: typeof mediaDuration;- h264Encoder: () => Promise<"libx264" | "h264_videotoolbox">;+ videoEncoder: (codec: ExportVideoCodec) => Promise<string>;runFfmpeg: typeof runFfmpeg;}@@ -484,7 +570,7 @@ const realIO: ExportPipelineIO = {videoColorInfo,videoDecodeCost,mediaDuration,- h264Encoder,+ videoEncoder,runFfmpeg,};@@ -544,7 +630,7 @@ export async function runExport({ffmpeg: (args) => io.runFfmpeg(job, args),writeFile: (p, data) => io.writeFile(p, data),- h264Encoder: io.h264Encoder,+ h264Encoder: () => io.videoEncoder("h264") as Promise<"libx264" | "h264_videotoolbox">,duration: io.mediaDuration,},src,@@ -2140,16 +2226,12 @@ export async function runExport(aLabel = "afinal";}- const enc = await io.h264Encoder();- const videoCodecArgs =- enc === "libx264"- ? ["-c:v", "libx264", "-preset", spec.preset, "-crf", String(spec.crf)]- : ["-c:v", "h264_videotoolbox", "-q:v", String(vtQuality(spec.crf)), "-allow_sw", "1"];+ const enc = await io.videoEncoder(spec.codec ?? "h264");// Encode into the tmp dir, then re-emit the container to strip a stray output// rotation flag (see the strip pass below). Keeping the encode intermediate// lets the second pass own faststart.- const encodePath = path.join(job.tmpDir, "encode.mp4");+ const encodePath = path.join(job.tmpDir, `encode${containerExtension(spec)}`);await io.runFfmpeg(job,[@@ -2158,15 +2240,12 @@ export async function runExport("-filter_complex", assertGraphSafe(filters.join(";")),"-map", `[${vLabel}]`,"-map", `[${aLabel}]`,- ...videoCodecArgs,- "-profile:v", "high",- "-pix_fmt", "yuv420p",+ ...videoCodecArgs(enc, spec),"-color_range", "tv","-colorspace", "bt709","-color_primaries", "bt709","-color_trc", "bt709",- "-c:a", "aac",- "-b:a", "192k",+ ...audioCodecArgs(spec),"-t", num(spec.duration),encodePath,],diff --git a/site/src/cut/server/http/export.ts b/site/src/cut/server/http/export.tsindex 63b695c2..80e62e78 100644--- a/site/src/cut/server/http/export.ts+++ b/site/src/cut/server/http/export.ts@@ -46,9 +46,6 @@ export const exportApi = {if (!job || job.status !== "done") {return new Response("Export not ready.", { status: 404 });}- return serveFileRange(job.outPath, req, {- contentType: "video/mp4",- downloadName: job.outName,- });+ return serveFileRange(job.outPath, req, { downloadName: job.outName });},};diff --git a/site/src/cut/server/http/projects.ts b/site/src/cut/server/http/projects.tsindex 10626ec8..ea9b2caf 100644--- a/site/src/cut/server/http/projects.ts+++ b/site/src/cut/server/http/projects.ts@@ -275,10 +275,8 @@ export const projectsApi = {} catch {return new Response("Bad request.", { status: 400 });}- return serveFileRange(p, req, {- contentType: "video/mp4",- ...(wantsDownload(req) ? { downloadName: name } : {}),- });+ // The type follows the name: an MP4 or a MOV, whichever the export wrote.+ return serveFileRange(p, req, wantsDownload(req) ? { downloadName: name } : {});},/** Reveal a rendered export in Finder (Cut runs on the user's own Mac). */diff --git a/site/src/cut/server/jobs.ts b/site/src/cut/server/jobs.tsindex 99ce10dd..6d3114d1 100644--- a/site/src/cut/server/jobs.ts+++ b/site/src/cut/server/jobs.ts@@ -4,7 +4,7 @@ import os from "node:os";import path from "node:path";import { assertLocalRuntime } from "./local-only";import { createJobRegistry } from "./jobRegistry";-import { runExport, type ExportSpec } from "./exportPipeline";+import { containerExtension, runExport, type ExportSpec } from "./exportPipeline";import { exportsDir, mediaPath, projectDir, readProject, setActiveJobGuard } from "./projects";export type { ExportSpec } from "./exportPipeline";@@ -141,7 +141,7 @@ export function cancelJob(id: string) {/** Export file named after the project, with a " 2", " 3"… suffix when the* name is already taken by a file on disk or an export still in flight. */-async function exportName(projectId: string, projectName: string) {+async function exportName(projectId: string, projectName: string, ext: string) {const base =projectName.replace(/[/\\:*?"<>|]/g, "").trim().slice(0, 60) || "export";const taken = new Set(@@ -151,7 +151,7 @@ async function exportName(projectId: string, projectName: string) {if (j.projectId === projectId && j.outName) taken.add(j.outName);}for (let n = 1; ; n++) {- const candidate = n === 1 ? `${base}.mp4` : `${base} ${n}.mp4`;+ const candidate = n === 1 ? `${base}${ext}` : `${base} ${n}${ext}`;if (!taken.has(candidate)) return candidate;}}@@ -160,9 +160,9 @@ async function exportName(projectId: string, projectName: string) {// its outName is assigned, so two jobs racing through their first awaits could// otherwise both claim "<Project>.mp4" and overwrite each other's render.let namingQueue: Promise<unknown> = Promise.resolve();-function claimExportName(job: Job, projectName: string): Promise<void> {+function claimExportName(job: Job, projectName: string, ext: string): Promise<void> {const claim = namingQueue.then(async () => {- job.outName = await exportName(job.projectId, projectName);+ job.outName = await exportName(job.projectId, projectName, ext);});namingQueue = claim.catch(() => {});return claim;@@ -218,7 +218,7 @@ export async function createJob(form: FormData): Promise<Job> {if (!doc) throw new Error("Project not found.");job.projectName = doc.name;if (preview) job.outName = "preview.mp4";- else await claimExportName(job, doc.name);+ else await claimExportName(job, doc.name, containerExtension(spec));job.outPath = path.join(preview ? projectDir(spec.projectId) : exportsDir(spec.projectId),job.outNamediff --git a/site/src/cut/server/projects.ts b/site/src/cut/server/projects.tsindex 2952f273..a11860f3 100644--- a/site/src/cut/server/projects.ts+++ b/site/src/cut/server/projects.ts@@ -1,4 +1,5 @@import fsSync from "node:fs";+import { isDeliveryName } from "../lib/exportDelivery";import { cp, mkdir, readdir, readFile, rm, stat, writeFile } from "node:fs/promises";import path from "node:path";import { resolveParent, settleParents } from "@/cut/lib/folderTree";@@ -267,7 +268,7 @@ export async function listExports(id: string) {const names = await readdir(dir).catch(() => [] as string[]);const items = await Promise.all(names- .filter((n) => n.endsWith(".mp4"))+ .filter((n) => isDeliveryName(n)).map(async (n) => {const info = await stat(path.join(dir, n)).catch(() => null);return info?.isFile() && info.size > 0