Open source CapCut alternative.
TypeScript
fix(cut): match source export size and offer lower resolutions [rebuild]
David Le9fb39232fc49
diff --git a/docs/guides/cut/README.md b/docs/guides/cut/README.mdindex b7b55741..32f4bd9b 100644--- a/docs/guides/cut/README.md+++ b/docs/guides/cut/README.md@@ -52,7 +52,7 @@ Guides draw over the preview from the button beside the timeline zoom: thirds, c## The export-An export is the preview drawn again frame by frame into an MP4 by the same compositor and mixer, so the file matches what the person saw. The dialog names the file, runs at the footage's own frame rate unless told otherwise, can deliver just the span the selection covers, offers a marked 4K upscale because the platforms transcode a 4K upload at a higher bitrate, and can save the captions as an SRT to the browser's Downloads folder. The Master preset is ProRes 4444, composited at 4:4:4 end to end, so titles and captions land in the file with the color the preview drew. One thing the export draws better: a clip in smooth slow motion has its in-between frames estimated from the motion around them, where the preview blends the neighbors; a browser without WebGPU blends too. The finished file goes to the project's home: the app's project folder for a Mac project, storage for a cloud one, the page's store for a browser one. A browser that cannot carry the render hands it to the machine behind the project, and the ffmpeg pipeline stays for ProRes, headless renders, share cards, and streaming ladders. The local-compute guide covers where each kind of work runs.+Exports use the preview's compositor and mixer. Best matches source dimensions, frame rate and video/audio bitrates, including low-resolution footage; project aspect and edits still apply. Named resolutions reach down to 240p. Explicit resolution, bitrate and ProRes choices control delivery. Extra soundtrack audio keeps the delivery audio budget. The dialog exports the whole timeline or a selection, names the file, and saves captions as SRT. Master uses ProRes 4444 to preserve graphics' color detail. Smooth slow motion estimates intermediate frames; browsers without WebGPU blend them. Files land in the project's home: browser storage, the Mac project folder, or cloud storage. A browser without the required encoder hands rendering to the project's machine. The [local-compute guide](local-compute.md) covers that boundary.## Sharingdiff --git a/site/src/cut/components/ExportDialog.tsx b/site/src/cut/components/ExportDialog.tsxindex ae42dba4..fbbd0ada 100644--- a/site/src/cut/components/ExportDialog.tsx+++ b/site/src/cut/components/ExportDialog.tsx@@ -40,7 +40,7 @@ import {import { useCutMode } from "@/cut/lib/backend/hooks";import { downloadText } from "@/cut/lib/download";import { deliverySpan, exportBaseName } from "@/cut/lib/exportDelivery";-import { canRenderInBrowser, sourceFrameRate, sourceFrameRateKey } from "@/cut/lib/exportRender";+import { canRenderInBrowser, sourceExportProfile, sourceFrameRateKey, type SourceExportProfile } from "@/cut/lib/exportRender";import { useExports } from "@/cut/lib/exportStore";import { projectDuration, useEditor } from "@/cut/lib/store";import { subtitleFiles } from "@/cut/lib/subtitleFile";@@ -106,13 +106,13 @@ export function ExportDialog() {// through the assets list leaves it alone — and a superseded probe closes// its readers.const probeKey = sourceFrameRateKey({ clips, assets });- const [probe, setProbe] = useState<{ key: string; fps: number | null } | null>(null);+ const [probe, setProbe] = useState<({ key: string } & SourceExportProfile) | null>(null);useEffect(() => {const abort = new AbortController();const s = useEditor.getState();- void sourceFrameRate({ clips: s.clips, assets: s.assets }, (a) => a.url, { signal: abort.signal }).then(- (fps) => {- if (!abort.signal.aborted) setProbe({ key: probeKey, fps });+ void sourceExportProfile({ clips: s.clips, assets: s.assets }, (a) => a.url, { signal: abort.signal }).then(+ (profile) => {+ if (!abort.signal.aborted) setProbe({ key: probeKey, ...profile });});return () => abort.abort();@@ -133,11 +133,12 @@ export function ExportDialog() {const typedName = baseName !== exportBaseName(projectName);const settings = useMemo<ExportSettings>(() => ({- ...choiceSettings(choice, resolutions, sourceFps ?? DEFAULT_EXPORT_FPS),+ ...choiceSettings(choice, resolutions, sourceFps ?? DEFAULT_EXPORT_FPS,+ !probing && probe ? { ...probe, ...(audioClips.length > 0 ? { audioBitrate: undefined } : {}) } : undefined),...(typedName ? { name: baseName } : {}),...(range ? { range } : {}),}),- [choice, resolutions, sourceFps, typedName, baseName, range]+ [choice, resolutions, sourceFps, probe, probing, audioClips.length, typedName, baseName, range]);const set = (patch: Partial<ExportChoice>) => setChoice((c) => ({ ...c, ...patch }));const captionFiles = useMemo(@@ -145,7 +146,7 @@ export function ExportDialog() {[subtitles, baseName, range]);// A "source" rate is not known until the probe answers; the button waits.- const waiting = probing && choice.fps === "source";+ const waiting = probing && (choice.fps === "source" || choice.resolution === "source");// 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 saysdiff --git a/site/src/cut/components/TopBar.tools.ts b/site/src/cut/components/TopBar.tools.tsindex aea2a138..025a778f 100644--- a/site/src/cut/components/TopBar.tools.ts+++ b/site/src/cut/components/TopBar.tools.ts@@ -6,6 +6,7 @@*/import { obj, str, type AiToolDef } from "@/cut/lib/aiToolDef";+import { EXPORT_RESOLUTIONS } from "@/cut/lib/exportPresets";import { GUIDE_IDS, GUIDE_PRESETS } from "@/cut/lib/guides";export const TOP_BAR_TOOLS = [@@ -47,7 +48,7 @@ export const TOP_BAR_TOOLS = [{name: "open_export",description:- "Open the export dialog so the user can render the cut: quick presets (Share, Best, Social 4K, Small, Master) or the advanced panel — file name, range (whole video or the selected items' span), format MP4/MOV, codec H.264/HEVC/ProRes, resolution from a 4K upscale through Source down to 720p, frame rate Source/24/30/60, quality tier or bitrate, AAC or PCM audio, and a captions file (SRT) saved beside the video. Exporting itself stays a user action.",+ `Open the export dialog: Best defaults to source resolution and video/audio bitrates, including sources below 720p. Other presets are Share, Social 4K, Small and Master. Controls include file name, whole video or selection range, MP4/MOV, H.264/HEVC/ProRes, resolution (${EXPORT_RESOLUTIONS.map((r) => r.label).join(", ")}, Source), frame rate, quality or custom bitrate, AAC/PCM, and an SRT captions file. Exporting itself stays a user action.`,inputSchema: obj({}),},] as const satisfies readonly AiToolDef[];diff --git a/site/src/cut/lib/exportClient.ts b/site/src/cut/lib/exportClient.tsindex 12de7a86..65f48b4f 100644--- a/site/src/cut/lib/exportClient.ts+++ b/site/src/cut/lib/exportClient.ts@@ -1,7 +1,7 @@"use client";import { captureRenderSnapshot, renderDoc, type ExportDoc, type RenderSnapshot } from "./renderSnapshot";-import { DELIVERY_DEFAULTS, EXPORT_PRESETS } from "./exportPresets";+import { DELIVERY_DEFAULTS, EXPORT_PRESETS, EXPORT_RESOLUTIONS } from "./exportPresets";import { operationFailure, type OperationFailure } from "./operationFailure";import { projectOperation } from "./projectOperation";@@ -67,8 +67,10 @@ export interface ExportSettings {codec: ExportCodec;container: ExportContainer;audioCodec: ExportAudioCodec;- /** A bitrate the user typed, bits per second. Absent = the tier's model. */+ /** Video bitrate in bits per second; omitted uses the quality tier. */bitrate?: number;+ /** AAC bitrate in bits per second; omitted uses the delivery default. */+ audioBitrate?: number;/** The file's name without its extension, as typed; absent = the project's* name. Sanitized by `exportBaseName` wherever a file is named. */name?: string;@@ -79,7 +81,7 @@ export interface ExportSettings {export { DELIVERY_DEFAULTS, EXPORT_PRESETS } from "./exportPresets";export const EXPORT_AUDIO = [- { id: "aac", label: "AAC", detail: "192 kbps" },+ { id: "aac", label: "AAC", detail: "compressed audio" },{ id: "pcm", label: "PCM", detail: "uncompressed · MOV" },] as const satisfies readonly { id: ExportAudioCodec; label: string; detail: string }[];@@ -96,18 +98,6 @@ export function exportExtension(settings: Pick<ExportSettings, "container">): st}-/**- * 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 = [@@ -194,15 +184,16 @@ export const DEFAULT_EXPORT_FPS = 30;/** The settings a choice adds up to, with the container fitted to the codec* and audio it has to carry. `sourceFps` is the footage's rate (see- * `sourceFrameRate`), what a "source" frame-rate choice resolves to. */+ * `sourceExportProfile`), what a "source" frame-rate choice resolves to. */export function choiceSettings(choice: ExportChoice,options: ResolutionOption[],- sourceFps: number = DEFAULT_EXPORT_FPS+ sourceFps: number = DEFAULT_EXPORT_FPS,+ sourceRates?: { videoBitrate?: number; audioBitrate?: number }): ExportSettings {const q = EXPORT_QUALITIES.find((x) => x.id === choice.quality) ?? EXPORT_QUALITIES[0];const r = resolveResolution(options, choice.resolution);- return fitContainer({+ const settings = fitContainer({width: r.width,height: r.height,fps: choice.fps === "source" ? sourceFps : choice.fps,@@ -217,6 +208,24 @@ export function choiceSettings(? { bitrate: Math.round(choice.bitrateMbps * 1_000_000) }: {}),});+ return choice.resolution === "source" && !choice.bitrateMbps+ ? matchSourceBitrates(settings, sourceRates)+ : settings;+}++/** Source-size delivery keeps the source's compression budget. */+export function matchSourceBitrates(+ settings: ExportSettings,+ source?: { videoBitrate?: number; audioBitrate?: number }+): ExportSettings {+ if (fixedRate(settings.codec)) return settings;+ return {+ ...settings,+ ...(source?.videoBitrate && Number.isFinite(source.videoBitrate) && source.videoBitrate > 0+ ? { bitrate: Math.round(Math.min(bitrateFor(settings), source.videoBitrate)) } : {}),+ ...(settings.audioCodec === "aac" && source?.audioBitrate && Number.isFinite(source.audioBitrate) && source.audioBitrate > 0+ ? { audioBitrate: Math.round(Math.min(audioBitrate(settings), source.audioBitrate)) } : {}),+ };}/** A size the dialog offers: the source's own frame, or a named rung above@@ -314,11 +323,8 @@ export function presetSettings(}/**- * "Original": the highest resolution the timeline's own footage justifies,- * along the project aspect. It scales the 1080p base by the sharpest source- * clip — never below the base (so it is always the highest option), never- * above 4K, and never upscaled past the source. Unknown source sizes fall- * back to the base.+ * Source dimensions fitted to the project aspect, capped at 4K.+ * Projects with no measured source dimensions use the base frame.*/export function originalSettings(aspect: Aspect,@@ -336,25 +342,20 @@ export function sourceFrame(): { width: number; height: number } {const base = frameOf(aspect);const longBase = Math.max(base.w, base.h);- const srcLong = Math.max(+ const sourceScale = Math.max(0,...getClipSpans(clips, assets).map((sp) =>- Math.max(sp.asset.width ?? 0, sp.asset.height ?? 0)+ Math.max((sp.asset.width ?? 0) / base.w, (sp.asset.height ?? 0) / base.h)));- // The 4K long-side cap wins over the 1080 base floor: a very wide custom- // ratio (whose base already exceeds 3840) scales down to stay encodable.- const k = Math.min(- 3840 / longBase,- Math.min(2, Math.max(1, srcLong / longBase || 1))- );- const even = (n: number) => 2 * Math.round((n * k) / 2);+ const k = Math.min(3840 / longBase, sourceScale || 1);+ const even = (n: number) => Math.max(2, 2 * Math.round((n * k) / 2));return { width: even(base.w), height: even(base.h) };}/*** 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+ * are given (`bitrateFor`) plus the selected audio bitrate. A CRF encode* spends what the footage needs, so busy footage runs larger and flat footage* smaller; the dialog shows it as an approximation.*/@@ -363,9 +364,9 @@ export function estimateExportBytes(settings: ExportSettings, durationSec: numbereturn ((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;+/** AAC follows its source budget or uses 192 kbps; PCM is 48 kHz stereo 16-bit. */+export function audioBitrate(settings: Pick<ExportSettings, "audioCodec" | "audioBitrate">): number {+ return settings.audioCodec === "pcm" ? 48_000 * 16 * 2 : settings.audioBitrate ?? 192_000;}/** Human-readable size estimate matching the finished-export MB display. */diff --git a/site/src/cut/lib/exportPresets.ts b/site/src/cut/lib/exportPresets.tsindex 29819648..1cdd7e0d 100644--- a/site/src/cut/lib/exportPresets.ts+++ b/site/src/cut/lib/exportPresets.ts@@ -40,3 +40,14 @@ export type DocExportPreset = (typeof DOC_EXPORT_PRESETS)[number];export function isDocExportPreset(value: unknown): value is DocExportPreset {return typeof value === "string" && (DOC_EXPORT_PRESETS as readonly string[]).includes(value);}++/** Named output sizes; Source is derived from the project media. */+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 },+ { id: "480", label: "480p", shortSide: 480 },+ { id: "360", label: "360p", shortSide: 360 },+ { id: "240", label: "240p", shortSide: 240 },+] as const;diff --git a/site/src/cut/lib/exportRender.ts b/site/src/cut/lib/exportRender.tsindex 1088d8e8..2552079d 100644--- a/site/src/cut/lib/exportRender.ts+++ b/site/src/cut/lib/exportRender.ts@@ -34,7 +34,7 @@ import { audioFxSpans } from "./audioEffects";import { renderMix, type MixClip, type MixItem, type MixSpec } from "./audioMix";import { FrameCompositor, MISSING_FRAME, type Frame } from "./composite";import { overlayPlan, trackZeroPlan } from "./framePlan";-import { frameSink, keyframeTimeAt, openMedia, videoTrackOf } from "./mediaRead";+import { audioTrackOf, frameSink, keyframeTimeAt, openMedia, videoTrackOf } from "./mediaRead";import type { InputVideoTrack, WrappedCanvas } from "mediabunny";import { allowance, canvasBytes, holdMemory } from "./memoryBudget";import { getClipSpans, overlayLayers, projectDuration, spanSequence } from "./store";@@ -174,9 +174,8 @@ const RATE_PROBE_TIMEOUT_MS = 8_000;/** The sources a rate probe would read, by footprint: the key a caller* re-probes on, so a change elsewhere in the project leaves the answer. */export function sourceFrameRateKey(doc: Pick<ExportDoc, "clips" | "assets">): string {- return rateSources(doc)- .map(([id]) => id)- .join("|");+ const byId = new Map(doc.assets.map((asset) => [asset.id, asset]));+ return JSON.stringify(rateSources(doc).map(([id]) => [id, byId.get(id)?.fileName]));}function rateSources(doc: Pick<ExportDoc, "clips" | "assets">): [string, number][] {@@ -192,19 +191,20 @@ function rateSources(doc: Pick<ExportDoc, "clips" | "assets">): [string, number].slice(0, RATE_PROBE_SOURCES);}-/**- * The rate the footage plays at: the delivery rate the most timeline seconds- * of video run at, read from each source's packet cadence. Null for a cut- * with no readable video — stills, titles, sound — which takes the default.- * An aborted probe closes its readers and answers null.- */-export async function sourceFrameRate(+export type SourceExportProfile = { fps: number | null; videoBitrate?: number; audioBitrate?: number };++/** Read cadence and compression budgets from the dominant video sources.+ * The largest source bitrate preserves detail across the sampled footage;+ * the frame rate is weighted by its time on the timeline. */+export async function sourceExportProfile(doc: Pick<ExportDoc, "clips" | "assets">,resolve: (asset: MediaAsset) => string,opts: { signal?: AbortSignal } = {}-): Promise<number | null> {+): Promise<SourceExportProfile> {const byId = new Map(doc.assets.map((a) => [a.id, a]));const seconds = new Map<number, number>();+ let videoBitrate = 0;+ let audioBitrate = 0;await Promise.all(rateSources(doc).map(async ([id, len]) => {if (opts.signal?.aborted) return;@@ -219,6 +219,14 @@ export async function sourceFrameRate(const track = await videoTrackOf(input);if (!track) return;const stats = await track.computePacketStats(120);+ const audio = await audioTrackOf(input);+ const audioStats = audio ? await audio.computePacketStats(120) : null;+ const sizeBytes = asset.sizeBytes ?? await input.source.getSizeOrNull();+ const sourceAudio = audioStats?.averageBitrate ?? 0;+ const totalBitrate = sizeBytes && asset.duration > 0 ? sizeBytes * 8 / asset.duration : 0;+ const sourceVideo = totalBitrate > sourceAudio ? totalBitrate - sourceAudio : stats.averageBitrate;+ if (Number.isFinite(sourceVideo)) videoBitrate = Math.max(videoBitrate, sourceVideo);+ if (Number.isFinite(sourceAudio)) audioBitrate = Math.max(audioBitrate, sourceAudio);const rate = stats.averagePacketRate;if (!(rate > 0) || opts.signal?.aborted) return;const snapped = DELIVERY_RATES.reduce((best, r) =>@@ -234,12 +242,12 @@ export async function sourceFrameRate(}}));- if (opts.signal?.aborted) return null;+ if (opts.signal?.aborted) return { fps: null };let pick: number | null = null;for (const [rate, len] of seconds) {if (pick === null || len > seconds.get(pick)! || (len === seconds.get(pick) && rate > pick)) pick = rate;}- return pick;+ return { fps: pick, ...(videoBitrate > 0 ? { videoBitrate } : {}), ...(audioBitrate > 0 ? { audioBitrate } : {}) };}/** The frame reader for one open video source. */@@ -1005,7 +1013,7 @@ export async function renderProjectToMp4(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 }) } : {}),+ ...(audioCodec === "aac" ? { quality: new Quality({ bitrate: settings.audioBitrate ?? 192_000 }) } : {}),});output.addAudioTrack(audio, { maximumPacketCount: Math.ceil(mix.length / 960) + 32 });}diff --git a/site/src/cut/lib/exportSettings.test.ts b/site/src/cut/lib/exportSettings.test.tsnew file mode 100644index 00000000..cce93114--- /dev/null+++ b/site/src/cut/lib/exportSettings.test.ts@@ -0,0 +1,48 @@+import { expect, test } from "bun:test";+import { choiceSettings, estimateExportBytes, EXPORT_QUICK_PRESETS, resolutionOptions, sourceFrame } from "@/cut/lib/exportClient";+import { sourceFrameRateKey } from "@/cut/lib/exportRender";+import type { MediaAsset, VideoClip } from "@/cut/lib/types";++const asset: MediaAsset = {+ id: "source", fileName: "source.mp4", name: "Source", type: "video",+ duration: 904.28, width: 320, height: 240, url: "",+};+const clip: VideoClip = { id: "clip", assetId: asset.id, start: 0, track: 0, in: 0, out: 855.3, muted: false };+const best = EXPORT_QUICK_PRESETS[1].choice;++test("Source preserves low-resolution footage within the project aspect", () => {+ expect(sourceFrame("4:3", [clip], [asset])).toEqual({ width: 320, height: 240 });+ expect(sourceFrame("16:9", [clip], [asset])).toEqual({ width: 426, height: 240 });+ expect(sourceFrame("9:16", [clip], [{ ...asset, width: 240, height: 320 }]))+ .toEqual({ width: 240, height: 426 });+});++test("converting a source refreshes the export's metadata probe", () => {+ expect(sourceFrameRateKey({ clips: [clip], assets: [asset] }))+ .not.toBe(sourceFrameRateKey({ clips: [clip], assets: [{ ...asset, fileName: "converted.mp4" }] }));+});++test("source export budgets bytes from the original compression", () => {+ const source = { videoBitrate: 140_000, audioBitrate: 48_000 };+ const options = resolutionOptions("16:9", [clip], [asset]);+ const settings = choiceSettings(best, options, 30, source);+ expect(settings).toMatchObject({ width: 426, height: 240, bitrate: 140_000, audioBitrate: 48_000 });+ expect(estimateExportBytes(settings, 855.3)).toBeLessThan(21_000_000);+});++test("the modal offers lower resolutions and marks true upscales", () => {+ const options = resolutionOptions("16:9", [clip], [{ ...asset, width: 1920, height: 1080 }]);+ for (const id of ["720", "480", "360", "240"]) {+ expect(options.find((o) => o.id === id)?.height).toBe(Number(id));+ expect(options.find((o) => o.id === id)?.upscale).toBeUndefined();+ }+ expect(resolutionOptions("16:9", [clip], [asset]).find((o) => o.id === "480")?.upscale).toBe(true);+});++test("custom bitrate and explicit upscale presets keep their chosen budgets", () => {+ const options = resolutionOptions("16:9", [clip], [asset]);+ const source = { videoBitrate: 140_000, audioBitrate: 48_000 };+ expect(choiceSettings({ ...best, bitrateMbps: 2 }, options, 30, source).bitrate).toBe(2_000_000);+ expect(choiceSettings(EXPORT_QUICK_PRESETS[2].choice, options, 30, source).bitrate).toBeUndefined();+ expect(choiceSettings(EXPORT_QUICK_PRESETS[4].choice, options, 30, source).audioBitrate).toBeUndefined();+});diff --git a/site/src/cut/lib/headless/docExport.ts b/site/src/cut/lib/headless/docExport.tsindex 5bc575e0..bd68b4b2 100644--- a/site/src/cut/lib/headless/docExport.ts+++ b/site/src/cut/lib/headless/docExport.ts@@ -4,12 +4,14 @@ import {buildExportPayload,EXPORT_PRESETS,originalSettings,+ matchSourceBitrates,presetSettings,previewSettings,type ExportSettings,} from "../exportClient";import { renderDoc, type ExportDoc } from "@/cut/lib/renderSnapshot";import { useEditor } from "../store";+import { sourceExportProfile } from "@/cut/lib/exportRender";import { bindHeadlessSession, type HeadlessSession } from "./bind";import { openCloudSnapshot, type CloudDocSnapshot } from "./docSession";@@ -20,11 +22,12 @@ import { openCloudSnapshot, type CloudDocSnapshot } from "./docSession";export { DOC_EXPORT_PRESETS, isDocExportPreset, type DocExportPreset } from "../exportPresets";import type { DocExportPreset } from "../exportPresets";-function settingsFor(preset: DocExportPreset, doc: ExportDoc): ExportSettings {+async function settingsFor(preset: DocExportPreset, doc: ExportDoc): Promise<ExportSettings> {const fixed = EXPORT_PRESETS.find((p) => p.id === preset);- return fixed- ? presetSettings(fixed, doc.aspect)- : originalSettings(doc.aspect, doc.clips, doc.assets);+ if (fixed) return presetSettings(fixed, doc.aspect);+ const source = await sourceExportProfile(doc, (asset) => asset.url);+ return matchSourceBitrates({ ...originalSettings(doc.aspect, doc.clips, doc.assets), fps: source.fps ?? 30 },+ { ...source, ...(doc.audioClips.length > 0 ? { audioBitrate: undefined } : {}) });}/**@@ -43,7 +46,7 @@ export async function buildDocExportSpec(bindHeadlessSession(session);await openCloudSnapshot(session, projectId, snapshot);const doc = renderDoc(useEditor.getState());- const payload = await buildExportPayload(projectId, doc, target === "preview" ? previewSettings(doc.aspect) : settingsFor(preset, doc), target);+ const payload = await buildExportPayload(projectId, doc, target === "preview" ? previewSettings(doc.aspect) : await settingsFor(preset, doc), target);await Promise.all(payload.pngs.map(async (p) =>writeFile(diff --git a/site/src/cut/server/ai/catalog.ts b/site/src/cut/server/ai/catalog.tsindex 58709322..01c2ceef 100644--- a/site/src/cut/server/ai/catalog.ts+++ b/site/src/cut/server/ai/catalog.ts@@ -9,6 +9,7 @@* here, so the UI and the model always offer the same catalog.*/+import { EXPORT_RESOLUTIONS } from "@/cut/lib/exportPresets";import { UI_TOOLS } from "@/cut/lib/projectCommands";import { STOCK_SFX_CATEGORIES } from "@/cut/lib/stock";import { AI_PANEL_TOOLS } from "@/cut/components/AiPanel.tools";@@ -563,7 +564,7 @@ Templates (save_template / template_add) ride the same rail and now keep grades,"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): one-click presets — Share (1080p H.264 MP4, plays everywhere), Best (source size, H.264 MP4, high quality), Social 4K (the cut upscaled to 4K in H.264, because TikTok, Reels and YouTube transcode a 4K upload on a higher bitrate rung than a 1080p one, so it comes back sharper), Small (720p, fastest), Master (source size, ProRes 4444 in a MOV with PCM audio, for handing to another editor or archiving the cut) — and an Advanced panel with every axis: file name (the project's until typed over), range (the whole video, or the span from the first selected item's start to the last one's end when something is selected), format (MP4 or MOV), codec (H.264, HEVC at about half the size for newer devices, ProRes 422 HQ, ProRes 4444), resolution (Source, which matches the sharpest clip on the timeline along the project aspect with a 1080p floor and a 4K cap; the named rungs below it; and the named rungs above it as marked upscales: 4K, 1440p, 1080p, 720p), frame rate (Source, the rate the footage plays at, read from the files; or 24, 30, 60), quality (High, Balanced, Small, or a typed bitrate in Mbps), audio (AAC or uncompressed PCM), and a captions file — the subtitle track saved as an SRT to the browser's Downloads folder (the video lands in the project's exports), one per visible language, for platforms that take their own captions. ProRes and PCM take a MOV, and ProRes sets its own rate, so the quality scale and a typed bitrate grey out. A ProRes 4444 master keeps every pixel's own color: the whole composite is built at 4:4:4 for it, so titles, captions and stickers land in the file without the color smearing a 4:2:0 delivery gives them. The other formats subsample, which is what H.264 and HEVC do at the encoder anyway. Every preset runs at the source frame rate. The dialog shows the size the choice will land at. H.264 files carry the High profile and HEVC files the Main profile; both key every two seconds, what the platforms ask for. An engine from an older Donkey app cannot take a range or a typed name, and the export says to update the app. 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.`,+Export (open_export): one-click presets — Share (1080p H.264 MP4, plays everywhere), Best (source size, H.264 MP4, high quality), Social 4K (the cut upscaled to 4K in H.264, because TikTok, Reels and YouTube transcode a 4K upload on a higher bitrate rung than a 1080p one, so it comes back sharper), Small (720p, fastest), Master (source size, ProRes 4444 in a MOV with PCM audio, for handing to another editor or archiving the cut) — and an Advanced panel with every axis: file name (the project's until typed over), range (the whole video, or the span from the first selected item's start to the last one's end when something is selected), format (MP4 or MOV), codec (H.264, HEVC at about half the size for newer devices, ProRes 422 HQ, ProRes 4444), resolution (Source, which matches the sharpest clip on the timeline along the project aspect with a 4K cap, preserving smaller sources; the named rungs below it; and the named rungs above it as marked upscales: ${EXPORT_RESOLUTIONS.map((r) => r.label).join(", ")}), frame rate (Source, the rate the footage plays at, read from the files; or 24, 30, 60), quality (High, Balanced, Small, or a typed bitrate in Mbps), audio (AAC or uncompressed PCM), and a captions file — the subtitle track saved as an SRT to the browser's Downloads folder (the video lands in the project's exports), one per visible language, for platforms that take their own captions. ProRes and PCM take a MOV, and ProRes sets its own rate, so the quality scale and a typed bitrate grey out. A ProRes 4444 master keeps every pixel's own color: the whole composite is built at 4:4:4 for it, so titles, captions and stickers land in the file without the color smearing a 4:2:0 delivery gives them. The other formats subsample, which is what H.264 and HEVC do at the encoder anyway. Every preset runs at the source frame rate. Source resolution also matches source video/audio bitrates unless a custom bitrate or ProRes is chosen; extra soundtrack audio keeps the delivery audio budget. The dialog shows the size the choice will land at. H.264 files carry the High profile and HEVC files the Main profile; both key every two seconds, what the platforms ask for. An engine from an older Donkey app cannot take a range or a typed name, and the export says to update the app. 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 b51ea44b..f7b5a800 100644--- a/site/src/cut/server/exportPipeline.test.ts+++ b/site/src/cut/server/exportPipeline.test.ts@@ -848,6 +848,12 @@ const encodeRun = async (over: Partial<ExportSpec>) => {const arg = (args: string[], flag: string) => args[args.indexOf(flag) + 1];describe("delivery", () => {+ test("source bitrates reach the worker and Mac encoders", async () => {+ const args = await encodeRun({ bitrate: 140_000, audioBitrate: 48_000 });+ expect(arg(args, "-b:v")).toBe("140000");+ expect(arg(args, "-b:a")).toBe("48000");+ expect(args).not.toContain("-crf");+ });test("a spec without delivery fields is an H.264 + AAC MP4", async () => {const args = await encodeRun({});expect(arg(args, "-c:v")).toBe("libx264");diff --git a/site/src/cut/server/exportPipeline.ts b/site/src/cut/server/exportPipeline.tsindex 808ad67e..c463bed1 100644--- a/site/src/cut/server/exportPipeline.ts+++ b/site/src/cut/server/exportPipeline.ts@@ -67,6 +67,7 @@ export interface ExportSpec {codec?: ExportCodec;container?: "mp4" | "mov";audioCodec?: "aac" | "pcm";+ audioBitrate?: number;/** A bitrate the user typed, bits per second; absent = the `crf` tier. */bitrate?: number;/** The file's name without its extension, as typed; absent = the project's@@ -445,7 +446,7 @@ export function videoCodecArgs(enc: string, spec: ExportSpec): string[] {/** 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"];+ return spec.audioCodec === "pcm" ? ["-c:a", "pcm_s16le"] : ["-c:a", "aac", "-b:a", String(spec.audioBitrate ?? 192_000)];}/** The file extension a spec's container takes. */