Skip to content

Open source CapCut alternative.

TypeScript

feat(site): export cloud projects in the browser

David Le315642f7440e
diff --git a/site/src/cut/components/ExportsDock.tsx b/site/src/cut/components/ExportsDock.tsx
index 84771b53..cae47b25 100644
--- a/site/src/cut/components/ExportsDock.tsx
+++ b/site/src/cut/components/ExportsDock.tsx
@@ -38,6 +38,7 @@ export function ExportsDock() {
const jobs = useExports((s) => s.jobs);
const local = useExports((s) => s.local);
const dismissed = useExports((s) => s.dismissed);
+ const rendering = useExports((s) => s.rendering);
const [collapsed, setCollapsed] = useState(false);
// Poll the feed while the dock is mounted (i.e. the whole time the app is up).
@@ -48,8 +49,16 @@ export function ExportsDock() {
const items = useMemo(() => {
const rank = (status: string) =>
- status === "running" ? 0 : status === "queued" || status === "preparing" ? 1 : status === "done" ? 2 : 3;
- const visible = jobs.filter((j) => !dismissed.includes(j.id));
+ status === "running" || status === "rendering"
+ ? 0
+ : status === "queued" || status === "preparing"
+ ? 1
+ : status === "done"
+ ? 2
+ : 3;
+ // A row this tab is rendering shows as its local row, which has the
+ // progress; the reserved job row behind it stays out of the dock.
+ const visible = jobs.filter((j) => !dismissed.includes(j.id) && !rendering.includes(j.id));
return [
...visible.map((j) => ({ kind: "job" as const, data: j })),
...local.map((r) => ({ kind: "local" as const, data: r })),
@@ -57,11 +66,13 @@ export function ExportsDock() {
const dr = rank(a.data.status) - rank(b.data.status);
return dr !== 0 ? dr : (a.data.createdAt ?? 0) - (b.data.createdAt ?? 0);
});
- }, [jobs, local, dismissed]);
+ }, [jobs, local, dismissed, rendering]);
if (items.length === 0) return null;
- const running = items.filter((i) => i.data.status === "running").length;
+ const running = items.filter(
+ (i) => i.data.status === "running" || i.data.status === "rendering"
+ ).length;
const waiting = items.filter(
(i) => i.data.status === "queued" || i.data.status === "preparing"
).length;
@@ -116,7 +127,7 @@ export function ExportsDock() {
}
function StatusIcon({ status }: { status: string }) {
- if (status === "running" || status === "preparing")
+ if (status === "running" || status === "preparing" || status === "rendering")
return <Loader2 className="size-4 shrink-0 animate-spin text-primary" />;
if (status === "queued") return <Clock className="size-4 shrink-0 text-muted-foreground" />;
if (status === "done")
@@ -256,8 +267,10 @@ function ExportRow({ job }: { job: ExportJob }) {
}
function LocalRowView({ row }: { row: LocalRow }) {
+ const rendering = row.status === "rendering";
+ const pct = Math.round(Math.min(1, Math.max(0, row.progress ?? 0)) * 100);
return (
- <div className="flex items-center gap-2.5 px-3 py-2">
+ <div className="relative flex items-center gap-2.5 px-3 py-2">
<StatusIcon status={row.status} />
<div className="min-w-0 flex-1">
<ProjectName projectId={row.projectId} name={row.projectName} />
@@ -267,9 +280,23 @@ function LocalRowView({ row }: { row: LocalRow }) {
row.status === "error" ? "text-destructive" : "text-muted-foreground"
)}
>
- {row.status === "preparing" ? "Preparing…" : row.error || "Couldn't start export"}
+ {rendering
+ ? `Rendering… ${pct}%`
+ : row.status === "preparing"
+ ? "Preparing…"
+ : row.error || "Couldn't start export"}
</div>
</div>
+ {rendering && (
+ <Button
+ variant="ghost"
+ size="icon-xs"
+ aria-label="Stop export"
+ onClick={() => useExports.getState().cancel(row.id)}
+ >
+ <X />
+ </Button>
+ )}
{row.status === "error" && (
<Button
variant="ghost"
@@ -280,6 +307,14 @@ function LocalRowView({ row }: { row: LocalRow }) {
<X />
</Button>
)}
+ {rendering && (
+ <div className="absolute inset-x-0 bottom-0 h-0.5 bg-secondary">
+ <div
+ className="h-full bg-primary transition-[width] duration-300"
+ style={{ width: `${pct}%` }}
+ />
+ </div>
+ )}
</div>
);
}
diff --git a/site/src/cut/lib/exportClient.ts b/site/src/cut/lib/exportClient.ts
index d955f1a3..34484a43 100644
--- a/site/src/cut/lib/exportClient.ts
+++ b/site/src/cut/lib/exportClient.ts
@@ -3,6 +3,7 @@
import { apiFetch, apiJson, getBackend, type CutBackend } from "./backend";
import { quotaErrorMessage } from "./backend/cloud";
import { normalizeGrade } from "./colorGrade";
+import { renderProjectToMp4 } from "./exportRender";
import { putSigned } from "./media";
import { clipSpeed, getClipSpans, overlayLayers, projectDuration, spanSequence, useEditor } from "./store";
import { captionStyle, cueOverlay, cueWordWindows, laneCues, subtitleLaneCount, trackPos } from "./subtitles";
@@ -547,6 +548,89 @@ export async function createExportJob(
return body.id;
}
+/**
+ * Render the cut in this tab and store the result, returning the finished job's
+ * id.
+ *
+ * The worker path exists because a hosted page had no way to encode video; it
+ * does now. Rendering here removes the round trip a queued export costs — the
+ * media does not have to be pulled back out of storage into a container, and
+ * nothing waits behind another account's render — and the file matches the
+ * preview, because the same compositor drew both.
+ *
+ * Cloud projects only: a local project's engine has ffmpeg, a whole machine,
+ * and the media already on disk.
+ */
+export async function runBrowserExport(
+ projectId: string,
+ doc: ExportDoc,
+ settings: ExportSettings,
+ opts: {
+ onProgress?: (ratio: number) => void;
+ signal?: AbortSignal;
+ /** The reserved job's id, as soon as it exists — the dock hides that row
+ * while this tab is the thing rendering it. */
+ onClaimed?: (jobId: string) => void;
+ } = {}
+): Promise<string> {
+ const backend = getBackend(); // pinned: the render outlives navigation
+ if (backend.kind !== "cloud") throw new Error("This project renders on its own machine.");
+
+ // The name and the destination are claimed before a frame is drawn, so a
+ // render that is going to be refused for space or for the render cap is
+ // refused now rather than after minutes of work. The claim is a job row, so
+ // a second export started while this one renders sees it and takes the next
+ // name instead of overwriting this one's file.
+ const claim = await backend.fetch("/api/cut/export/client/presign", {
+ method: "POST",
+ headers: { "Content-Type": "application/json" },
+ body: JSON.stringify({ projectId, outName: exportOutName() }),
+ });
+ const claimed = await apiJson<{ jobId?: string; url?: string; outName?: string }>(claim);
+ if (!claim.ok || !claimed.jobId || !claimed.url) {
+ throw new Error(
+ quotaErrorMessage(claim.status, claimed) ?? claimed.error ?? "Export failed to start."
+ );
+ }
+ const jobId = claimed.jobId;
+ opts.onClaimed?.(jobId);
+
+ try {
+ const file = await renderProjectToMp4(doc, settings, {
+ // Read the asset's URL at the moment it is needed rather than off the
+ // snapshot: a long render can outlive the links it started with, and the
+ // store re-mints them behind it.
+ resolve: (asset) =>
+ useEditor.getState().assets.find((a) => a.id === asset.id)?.url ?? asset.url,
+ signal: opts.signal,
+ // The render is nearly all of the work; the upload is the tail of the bar.
+ onProgress: ({ ratio }) => opts.onProgress?.(ratio * 0.9),
+ });
+
+ await putSigned(claimed.url, file, "video/mp4", {
+ signal: opts.signal,
+ onProgress: (fraction) => opts.onProgress?.(0.9 + fraction * 0.1),
+ });
+
+ const done = await backend.fetch("/api/cut/export/client/complete", {
+ method: "POST",
+ headers: { "Content-Type": "application/json" },
+ body: JSON.stringify({ jobId }),
+ });
+ const body = await apiJson<{ id?: string }>(done);
+ if (!done.ok || !body.id) throw new Error(body.error ?? "Could not save the export.");
+ return body.id;
+ } catch (err) {
+ // A render that stopped — cancelled, failed, or refused — gives back the
+ // name it was holding. Leaving the row behind would keep the name taken and
+ // a render slot spent for a file that will never exist.
+ void backend
+ .fetch(`/api/cut/export/client/${jobId}/release`, { method: "POST" })
+ .catch(() => {});
+ throw err;
+ }
+}
+
/** 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()) {
diff --git a/site/src/cut/lib/exportRender.test.ts b/site/src/cut/lib/exportRender.test.ts
new file mode 100644
index 00000000..e93f5b46
--- /dev/null
+++ b/site/src/cut/lib/exportRender.test.ts
@@ -0,0 +1,151 @@
+import { describe, expect, test } from "bun:test";
+import { foldClips } from "./audioMix";
+import { bitrateFor, mixSpecFor } from "./exportRender";
+import type { ExportDoc } from "./exportClient";
+import type { MediaAsset, VideoClip } from "./types";
+
+const asset = (id: string): MediaAsset => ({
+ id,
+ fileName: `${id}.mp4`,
+ name: id,
+ type: "video",
+ duration: 60,
+ url: `https://media.test/${id}.mp4`,
+});
+
+const clip = (over: Partial<VideoClip> & { id: string; assetId: string }): VideoClip => ({
+ track: 0,
+ start: 0,
+ in: 0,
+ out: 4,
+ muted: false,
+ ...over,
+});
+
+const doc = (over: Partial<ExportDoc> = {}): ExportDoc => ({
+ aspect: "16:9",
+ assets: [asset("a"), asset("b")],
+ clips: [],
+ audioClips: [],
+ overlays: [],
+ subtitles: { cues: [], showOnVideo: false, showOnTimeline: false },
+ ...over,
+});
+
+const resolve = (a: MediaAsset) => a.url;
+
+describe("mixSpecFor", () => {
+ test("keeps the audio under the picture when track 0 has a leading gap", () => {
+ const spec = mixSpecFor(
+ doc({ clips: [clip({ id: "c1", assetId: "a", start: 3 })] }),
+ resolve
+ );
+ const geo = foldClips(spec.clips);
+ // The clip sits at 3s on the timeline, so its audio has to start at 3s.
+ const voiced = geo.find((g) => g.clip.file !== "");
+ expect(voiced?.at).toBeCloseTo(3, 5);
+ });
+
+ test("keeps the audio under the picture across a mid-timeline gap", () => {
+ const spec = mixSpecFor(
+ doc({
+ clips: [
+ clip({ id: "c1", assetId: "a", start: 0, out: 2 }),
+ clip({ id: "c2", assetId: "b", start: 5, out: 2 }),
+ ],
+ }),
+ resolve
+ );
+ const geo = foldClips(spec.clips);
+ const voiced = geo.filter((g) => g.clip.file !== "");
+ expect(voiced[0].at).toBeCloseTo(0, 5);
+ expect(voiced[1].at).toBeCloseTo(5, 5);
+ });
+
+ test("lays abutting clips out with no spacer between them", () => {
+ const spec = mixSpecFor(
+ doc({
+ clips: [
+ clip({ id: "c1", assetId: "a", start: 0, out: 2 }),
+ clip({ id: "c2", assetId: "b", start: 2, out: 2 }),
+ ],
+ }),
+ resolve
+ );
+ expect(spec.clips.every((c) => c.file !== "")).toBe(true);
+ });
+
+ test("mutes a still, which has no sound to read", () => {
+ const still: MediaAsset = { ...asset("s"), type: "image", fileName: "s.png" };
+ const spec = mixSpecFor(
+ doc({ assets: [still], clips: [clip({ id: "c1", assetId: "s" })] }),
+ resolve
+ );
+ expect(spec.clips[0].muted).toBe(true);
+ });
+
+ test("carries an overlay clip's fade so its sound ramps with its picture", () => {
+ const spec = mixSpecFor(
+ doc({
+ clips: [
+ clip({ id: "c0", assetId: "a" }),
+ clip({
+ id: "c1",
+ assetId: "b",
+ track: 1,
+ start: 1,
+ animIn: { style: "fade", seconds: 0.5 },
+ animOut: { style: "fade", seconds: 0.75 },
+ }),
+ ],
+ }),
+ resolve
+ );
+ const overlay = spec.items.find((i) => i.start === 1);
+ expect(overlay?.fadeIn).toBeCloseTo(0.5, 5);
+ expect(overlay?.fadeOut).toBeCloseTo(0.75, 5);
+ });
+
+ test("gives a zoom no audio ramp, since it does not change loudness", () => {
+ const spec = mixSpecFor(
+ doc({
+ clips: [
+ clip({ id: "c0", assetId: "a" }),
+ clip({
+ id: "c1",
+ assetId: "b",
+ track: 1,
+ start: 1,
+ animIn: { style: "zoom", seconds: 0.5 },
+ }),
+ ],
+ }),
+ resolve
+ );
+ expect(spec.items.find((i) => i.start === 1)?.fadeIn).toBe(0);
+ });
+
+ test("an empty track 0 still runs the project's length as silence", () => {
+ const spec = mixSpecFor(
+ doc({ clips: [clip({ id: "c1", assetId: "a", track: 1, start: 0, out: 6 })] }),
+ resolve
+ );
+ expect(spec.clips).toHaveLength(1);
+ expect(spec.clips[0].file).toBe("");
+ expect(spec.clips[0].muted).toBe(true);
+ });
+});
+
+describe("bitrateFor", () => {
+ test("spends more bits on a lower CRF", () => {
+ const base = { width: 1920, height: 1080, fps: 30, preset: "medium" };
+ expect(bitrateFor({ ...base, crf: 19 })).toBeGreaterThan(bitrateFor({ ...base, crf: 24 }));
+ });
+
+ test("scales with frame area", () => {
+ const base = { fps: 30, crf: 23, preset: "medium" };
+ expect(bitrateFor({ ...base, width: 1920, height: 1080 })).toBeGreaterThan(
+ bitrateFor({ ...base, width: 1280, height: 720 })
+ );
+ });
+});
diff --git a/site/src/cut/lib/exportRender.ts b/site/src/cut/lib/exportRender.ts
new file mode 100644
index 00000000..0b36b6b8
--- /dev/null
+++ b/site/src/cut/lib/exportRender.ts
@@ -0,0 +1,609 @@
+"use client";
+
+/**
+ * Rendering the cut to a file, in the browser.
+ *
+ * The tab already knows how to draw this project — it does it sixty times a
+ * second in the preview. The only things it was missing were a clock it could
+ * step rather than follow, and somewhere to put the frames. This supplies both:
+ * frames are pulled at exact timestamps instead of played towards, and the
+ * finished picture goes into an MP4 muxer instead of onto the screen.
+ *
+ * Everything about what a frame looks like comes from the same two modules the
+ * preview uses — `framePlan` for what is on screen at a given moment, and
+ * `FrameCompositor` for turning that into pixels. Nothing here decides how the
+ * cut should look. That is the point: a render is the preview, evaluated at
+ * every frame instead of at whatever moment the display asked for.
+ */
+
+import {
+ BufferTarget,
+ CanvasSource,
+ getFirstEncodableAudioCodec,
+ getFirstEncodableVideoCodec,
+ Mp4OutputFormat,
+ Output,
+ AudioBufferSource,
+ type VideoCodec,
+} from "mediabunny";
+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, openMedia, videoTrackOf } from "./mediaRead";
+import { getClipSpans, overlayLayers, projectDuration, spanSequence } from "./store";
+import { captionStyle, cueOverlay, cueWordWindows, laneCues, subtitleLaneCount, trackPos } from "./subtitles";
+import { renderOverlayPng } from "./textRender";
+import { frameOf, isFullRect, overlayAnimStyle, projectFadeSeconds, rectOf } from "./types";
+import type { ClipSpan, MediaAsset, TextOverlay } from "./types";
+import type { ExportDoc, ExportSettings } from "./exportClient";
+
+/** 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. */
+const VIDEO_CODECS: VideoCodec[] = ["avc", "hevc", "vp9", "av1"];
+
+export interface RenderProgress {
+ /** 0..1 across the whole render. */
+ ratio: number;
+ stage: "audio" | "video" | "finishing";
+}
+
+export interface RenderOptions {
+ /** Maps an asset's stored file name to a URL the reader can open. */
+ resolve: (asset: MediaAsset) => string;
+ onProgress?: (progress: RenderProgress) => void;
+ 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.
+ */
+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);
+}
+
+/** The frame reader for one open video source. */
+type ClipSink = ReturnType<typeof frameSink>;
+
+/** A clip's source time at timeline time `t`. */
+function sourceTimeAt(span: ClipSpan, t: number): number {
+ const speed = span.clip.speed && span.clip.speed > 0 ? span.clip.speed : 1;
+ return span.clip.in + Math.max(0, t - span.start) * speed;
+}
+
+/**
+ * Frames for one clip, pulled at exact timestamps.
+ *
+ * A video keeps its reader open across the whole render: the timestamps a
+ * render asks for only ever move forward, so the decoder walks the file once
+ * rather than seeking back to the start for every frame. A still decodes once
+ * and is handed back for as long as its clip is on screen.
+ */
+class ClipReader {
+ private input: ReturnType<typeof openMedia> | null = null;
+ private sink: ClipSink | null = null;
+ private still: Frame | null = null;
+ private opened: Promise<ClipSink | null> | null = null;
+ private reopened = false;
+
+ constructor(
+ private asset: MediaAsset,
+ /** Resolved on open, and again on a re-open, so a link re-minted while the
+ * render is running is picked up rather than the render dying on the
+ * snapshot's expired one. */
+ private url: () => string
+ ) {}
+
+ /** Open the source and hand back its frame reader, or null when it has no
+ * readable picture (a still, which is served from `this.still`, or a source
+ * with no decodable video). */
+ private open(): Promise<ClipSink | null> {
+ return (this.opened ??= (async () => {
+ if (this.asset.type === "image") {
+ const blob = await (await fetch(this.url())).blob();
+ const bitmap = await createImageBitmap(blob);
+ this.still = {
+ kind: "ready",
+ image: bitmap,
+ width: bitmap.width,
+ height: bitmap.height,
+ };
+ return null;
+ }
+ const input = openMedia(this.url());
+ const track = await videoTrackOf(input);
+ if (!track) {
+ input.dispose();
+ return null;
+ }
+ this.input = input;
+ // A small pool keeps the render's canvas allocation flat over thousands
+ // of frames.
+ this.sink = frameSink(track, undefined, 4);
+ return this.sink;
+ })());
+ }
+
+ /** The clip's picture at source time `at`, or a missing frame when the
+ * source has none — a still-less video, or a time past its end. A render
+ * never reports `pending`: it waits for the decode instead of moving on. */
+ async frameAt(at: number): Promise<Frame> {
+ const sink = await this.open();
+ if (this.still) return this.still;
+ if (!sink) return MISSING_FRAME;
+ let wrapped;
+ try {
+ wrapped = await sink.getCanvas(Math.max(0, at));
+ } catch (err) {
+ // A long render can outlive the signed link it opened with. Reopening
+ // resolves the URL again, which is enough when the link was simply
+ // re-minted; a second failure is a real one and stops the render.
+ if (this.reopened) throw err;
+ this.reopened = true;
+ this.input?.dispose();
+ this.input = null;
+ this.sink = null;
+ this.opened = null;
+ const reopened = await this.open();
+ if (!reopened) throw err;
+ wrapped = await reopened.getCanvas(Math.max(0, at));
+ }
+ if (!wrapped) return MISSING_FRAME;
+ return {
+ kind: "ready",
+ image: wrapped.canvas,
+ width: wrapped.canvas.width,
+ height: wrapped.canvas.height,
+ };
+ }
+
+ dispose() {
+ this.input?.dispose();
+ this.input = null;
+ this.sink = null;
+ if (this.still?.kind === "ready") (this.still.image as ImageBitmap).close?.();
+ this.still = null;
+ }
+}
+
+/** A text layer and the window it is on screen for. The picture is drawn when
+ * the render reaches it, not up front. */
+interface StampedLayer {
+ overlay: TextOverlay;
+ start: number;
+ end: number;
+}
+
+/**
+ * Text overlays and captions, each as one layer with the window it belongs to.
+ *
+ * Every distinct look is a layer: a plain cue is one, and a word-highlight cue
+ * is one per word, since the highlight moves. What is *not* done here is
+ * turning them into pictures. A full-frame RGBA bitmap is about 8 MB at 1080p,
+ * and a four-minute subtitled cut has several hundred word windows — decoding
+ * them all before the first frame is drawn, and holding them for the whole
+ * render, exhausts the tab on projects the worker handles comfortably.
+ *
+ * The layout itself is the same rendering the ffmpeg path burns in, so the
+ * words land in the same place whichever renderer produced the file.
+ */
+function stampText(doc: ExportDoc): StampedLayer[] {
+ const duration = projectDuration(doc);
+ const layers: StampedLayer[] = [];
+
+ for (const o of doc.overlays) {
+ if (o.start >= duration || !o.text.trim()) continue;
+ layers.push({ overlay: o, start: o.start, end: Math.min(o.end, duration) });
+ }
+
+ if (doc.subtitles.showOnVideo) {
+ const capStyle = captionStyle(doc.subtitles.style);
+ // Wrap in design space (1080 short side) from the project ratio — the same
+ // width the preview passes, whatever the render size.
+ const designWidth = frameOf(doc.aspect).w;
+ for (let lane = 0; lane < subtitleLaneCount(doc.subtitles); lane++) {
+ const cues = laneCues(doc.subtitles, lane);
+ const pos = trackPos(doc.subtitles, capStyle, lane);
+ for (let i = 0; i < cues.length; i++) {
+ const cue = cues[i];
+ if (cue.start >= duration || !cue.text.trim()) continue;
+ const windows = doc.subtitles.wordHighlight
+ ? cueWordWindows(cue)
+ : [{ start: cue.start, end: cue.end }];
+ for (let wi = 0; wi < windows.length; wi++) {
+ const win = windows[wi];
+ if (win.start >= duration) break;
+ layers.push({
+ overlay: cueOverlay(
+ cue,
+ capStyle,
+ i === 0,
+ pos,
+ doc.subtitles.wordHighlight ? wi : undefined,
+ designWidth
+ ),
+ start: win.start,
+ end: Math.min(win.end, duration),
+ });
+ }
+ }
+ }
+ }
+ return layers;
+}
+
+/**
+ * Text layer pictures, drawn on demand and released once their window passes.
+ *
+ * A render walks time forwards, so only the layers live at the current moment
+ * are needed — usually a caption and maybe a title. Holding those and dropping
+ * the rest keeps the memory a subtitled export uses flat in the length of the
+ * cut instead of growing with every word in it.
+ */
+class StampCache {
+ private drawn = new Map<StampedLayer, ImageBitmap>();
+
+ constructor(
+ private width: number,
+ private height: number
+ ) {}
+
+ async bitmapFor(layer: StampedLayer): Promise<ImageBitmap> {
+ let bitmap = this.drawn.get(layer);
+ if (!bitmap) {
+ const png = await renderOverlayPng(layer.overlay, this.width, this.height);
+ bitmap = await createImageBitmap(png);
+ this.drawn.set(layer, bitmap);
+ }
+ return bitmap;
+ }
+
+ /** Release the pictures of layers that have finished by `t`. */
+ retire(t: number) {
+ for (const [layer, bitmap] of this.drawn) {
+ if (layer.end <= t) {
+ bitmap.close();
+ this.drawn.delete(layer);
+ }
+ }
+ }
+
+ dispose() {
+ for (const bitmap of this.drawn.values()) bitmap.close();
+ this.drawn.clear();
+ }
+}
+
+/** Head and tail audio ramps for one upper-track clip: its own entrance/exit
+ * animation, or the transition that owns that edge. Mirrors the ramps the
+ * export spec carries and the gain the preview applies, so a picture that
+ * fades up takes its sound with it. */
+function overlayRamps(spans: ClipSpan[]): { head: number; tail: number }[] {
+ const ramps = spans.map(() => ({ head: 0, tail: 0 }));
+ spans.forEach((sp, i) => {
+ const apply = (anim: typeof sp.clip.animIn, side: "head" | "tail") => {
+ if (!anim) return;
+ // A zoom does not change how loud a clip is; every other style ramps.
+ if (overlayAnimStyle(anim.style) === "zoom") return;
+ ramps[i][side] = Math.max(ramps[i][side], Math.min(anim.seconds, sp.len));
+ };
+ // A transitioned joint owns its edge, so the animation there stands down.
+ if (!((spans[i - 1]?.transitionOut ?? 0) > 0)) apply(sp.clip.animIn, "head");
+ if (!(sp.transitionOut > 0)) apply(sp.clip.animOut, "tail");
+ if (sp.transitionOut > 0 && spans[i + 1]) {
+ ramps[i].tail = Math.max(ramps[i].tail, sp.transitionOut);
+ ramps[i + 1].head = Math.max(ramps[i + 1].head, sp.transitionOut);
+ }
+ });
+ return ramps;
+}
+
+/**
+ * The mix spec for a doc: track-0 clip audio in sequence, plus everything
+ * placed at an absolute time — the soundtrack and every upper-track clip's own
+ * sound, which the preview plays and the file therefore has to carry.
+ *
+ * The track-0 fold is sequential, so gaps between free-placed clips have to
+ * ship as explicit silent spacers. Without them the audio closes up the gaps
+ * while the picture keeps them, and everything after the first gap plays early.
+ */
+export function mixSpecFor(doc: ExportDoc, resolve: (asset: MediaAsset) => string): MixSpec {
+ const duration = projectDuration(doc);
+ const spans = getClipSpans(doc.clips, doc.assets, 0);
+ const byId = new Map(doc.assets.map((a) => [a.id, a]));
+ // A still has no sound, and handing its URL to the audio reader would fail on
+ // a file that is not a media container at all.
+ const silent = (asset: MediaAsset) => asset.type === "image";
+
+ const items: MixItem[] = [];
+ for (const track of new Set(overlayLayers(doc.clips).map((c) => c.track))) {
+ const trackSpans = getClipSpans(doc.clips, doc.assets, track);
+ const ramps = overlayRamps(trackSpans);
+ trackSpans.forEach((sp, i) => {
+ if (sp.clip.hidden || sp.start >= duration) return;
+ items.push({
+ file: resolve(sp.asset),
+ in: sp.clip.in,
+ out: sp.clip.out,
+ start: sp.start,
+ volume: sp.clip.volume ?? 1,
+ speed: sp.clip.speed,
+ muted: sp.clip.muted || silent(sp.asset),
+ fadeIn: ramps[i].head,
+ fadeOut: ramps[i].tail,
+ });
+ });
+ }
+ for (const a of doc.audioClips) {
+ const asset = byId.get(a.assetId);
+ if (!asset || a.hidden || a.start >= duration) continue;
+ items.push({
+ file: resolve(asset),
+ in: a.in,
+ out: a.out,
+ start: a.start,
+ volume: a.volume,
+ speed: a.speed,
+ fadeIn: a.fadeIn,
+ fadeOut: a.fadeOut,
+ duck: a.duck,
+ });
+ }
+
+ const spacer = (len: number): MixClip => ({ file: "", in: 0, out: len, muted: true });
+ const clips: MixClip[] =
+ spans.length === 0
+ ? [spacer(duration)]
+ : spanSequence(spans).flatMap(({ gapBefore, span: sp }) => [
+ ...(gapBefore > 0 ? [spacer(gapBefore)] : []),
+ {
+ file: resolve(sp.asset),
+ in: sp.clip.in,
+ out: sp.clip.out,
+ muted: sp.clip.muted || !!sp.clip.hidden || silent(sp.asset),
+ speed: sp.clip.speed,
+ volume: sp.clip.volume,
+ transition: sp.transitionOut,
+ },
+ ]);
+
+ return {
+ duration,
+ clips,
+ items,
+ fadeIn: projectFadeSeconds(doc.fadeIn, duration),
+ fadeOut: projectFadeSeconds(doc.fadeOut, duration),
+ };
+}
+
+/** 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);
+ const fadeOut = projectFadeSeconds(doc.fadeOut, total);
+ let g = 1;
+ if (fadeIn > 0 && t < fadeIn) g = Math.min(g, Math.max(0, t / fadeIn));
+ if (fadeOut > 0 && t > total - fadeOut) g = Math.min(g, Math.max(0, (total - t) / fadeOut));
+ return Math.min(1, g);
+}
+
+/**
+ * Render `doc` to an MP4.
+ *
+ * Frames are produced in order and handed to the muxer as they are drawn, so
+ * the memory this holds is a handful of decoded frames rather than the render.
+ * The audio is mixed up front, because a single offline pass over the whole
+ * timeline is both cheaper and more accurate than trying to mix it in slices
+ * that have to agree at the seams.
+ */
+export async function renderProjectToMp4(
+ doc: ExportDoc,
+ settings: ExportSettings,
+ opts: RenderOptions
+): Promise<Blob> {
+ const { resolve, onProgress, signal } = opts;
+ const duration = projectDuration(doc);
+ if (!(duration > 0)) throw new Error("There is nothing to export yet.");
+
+ const codec = await getFirstEncodableVideoCodec(VIDEO_CODECS, {
+ width: settings.width,
+ height: settings.height,
+ });
+ if (!codec) throw new Error("This browser can't encode video.");
+
+ const stop = () => {
+ if (signal?.aborted) throw new DOMException("Export canceled.", "AbortError");
+ };
+
+ onProgress?.({ ratio: 0, stage: "audio" });
+ const mix = await renderMix(mixSpecFor(doc, resolve), {
+ sampleRate: AUDIO_RATE,
+ channels: AUDIO_CHANNELS,
+ resolve: (file) => file, // mixSpecFor already resolved each asset to a URL
+ });
+ stop();
+
+ const canvas =
+ typeof OffscreenCanvas !== "undefined"
+ ? new OffscreenCanvas(settings.width, settings.height)
+ : Object.assign(document.createElement("canvas"), {
+ width: settings.width,
+ height: settings.height,
+ });
+ const comp = new FrameCompositor(canvas);
+
+ const output = new Output({ format: new Mp4OutputFormat(), target: new BufferTarget() });
+ const video = new CanvasSource(canvas, { codec, bitrate: bitrateFor(settings) });
+ output.addVideoTrack(video, { frameRate: settings.fps });
+ let audio: AudioBufferSource | null = null;
+ if (mix) {
+ const audioCodec = await getFirstEncodableAudioCodec(["aac", "opus"], {
+ numberOfChannels: AUDIO_CHANNELS,
+ sampleRate: AUDIO_RATE,
+ });
+ if (audioCodec) {
+ audio = new AudioBufferSource({ codec: audioCodec, bitrate: 192_000 });
+ output.addAudioTrack(audio);
+ }
+ }
+ await output.start();
+
+ const stamps = new StampCache(settings.width, settings.height);
+ const readers = new Map<string, ClipReader>();
+ const readerFor = (asset: MediaAsset) => {
+ let r = readers.get(asset.id);
+ if (!r) readers.set(asset.id, (r = new ClipReader(asset, () => resolve(asset))));
+ return r;
+ };
+
+ try {
+ // The audio is one buffer for the whole timeline, so it goes in before the
+ // frames rather than being interleaved with them.
+ if (audio && mix) await audio.add(mix);
+
+ const layers = stampText(doc);
+ stop();
+
+ const spans = getClipSpans(doc.clips, doc.assets, 0);
+ const overlayTracks = [...new Set(overlayLayers(doc.clips).map((c) => c.track))];
+ // Span geometry is a property of the document, which does not change while
+ // rendering — so it is computed once rather than per overlay per frame.
+ const byTrack = new Map(overlayTracks.map((track) => [track, getClipSpans(doc.clips, doc.assets, track)]));
+ const spansOf = (track: number) => byTrack.get(track) ?? [];
+ const spanOfClip = new Map<string, ClipSpan>();
+ for (const list of byTrack.values()) for (const sp of list) spanOfClip.set(sp.clip.id, sp);
+ const frameDur = 1 / settings.fps;
+ const frames = Math.max(1, Math.round(duration * settings.fps));
+
+ for (let i = 0; i < frames; i++) {
+ stop();
+ const t = i * frameDur;
+ comp.clear();
+
+ const master = spans.find((sp) => t >= sp.start && t < sp.start + sp.len);
+ if (master) {
+ const plan = trackZeroPlan(master, spans, t);
+ if (plan.backdrop) {
+ const frame = await readerFor(plan.backdrop.span.asset).frameAt(plan.backdrop.at);
+ comp.drawLayer(frame, plan.backdrop.span.clip, false, 1, t);
+ }
+ const masterFrame = master.clip.hidden
+ ? MISSING_FRAME
+ : await readerFor(master.asset).frameAt(sourceTimeAt(master, t));
+ const incFrame = plan.incoming
+ ? await readerFor(plan.incoming.asset).frameAt(sourceTimeAt(plan.incoming, t))
+ : MISSING_FRAME;
+ comp.drawCrossJoin(
+ plan.style,
+ plan.p,
+ {
+ masterFrame,
+ masterClip: master.clip,
+ masterAlpha: plan.masterAlpha,
+ masterZoom: plan.masterZoom,
+ masterFx: {
+ dx: plan.masterFxFrac.dx * settings.width,
+ dy: plan.masterFxFrac.dy * settings.height,
+ },
+ incFrame,
+ incClip: plan.incoming?.clip,
+ incAlpha: plan.incAlpha,
+ incZoom: plan.incZoom,
+ },
+ t
+ );
+ if (plan.veil > 0) comp.fillBlackVeil(plan.veil, rectOf(master.clip));
+ }
+
+ for (const layer of overlayPlan(overlayTracks, spansOf, t)) {
+ const span = spanOfClip.get(layer.clip.id);
+ if (!span) continue;
+ const frame = await readerFor(layer.asset).frameAt(sourceTimeAt(span, t));
+ const rect = rectOf(layer.clip);
+ const cover = layer.clip.fit === "fill" || (layer.clip.fit == null && isFullRect(rect));
+ comp.drawIntoRect(frame, rect, cover, layer.alpha, t, layer.zoom, layer.clip);
+ }
+
+ await drawStamps(canvas, layers, stamps, t);
+ stamps.retire(t);
+ comp.drawProjectFade(projectFadeGain(doc, t, duration));
+
+ await video.add(t, frameDur);
+ if (i % 15 === 0) {
+ onProgress?.({ ratio: i / frames, stage: "video" });
+ // Let the tab breathe: without a yield a long render starves every
+ // other task on this thread, including the one listening for a cancel.
+ await new Promise((r) => setTimeout(r, 0));
+ }
+ }
+
+ onProgress?.({ ratio: 1, stage: "finishing" });
+ await output.finalize();
+ const buffer = output.target.buffer;
+ if (!buffer) throw new Error("The render produced no file.");
+ return new Blob([buffer], { type: "video/mp4" });
+ } catch (err) {
+ await output.cancel().catch(() => {});
+ throw err;
+ } finally {
+ stamps.dispose();
+ for (const r of readers.values()) r.dispose();
+ readers.clear();
+ }
+}
+
+/** Draw the text layers live at `t` over the finished picture. */
+async function drawStamps(
+ canvas: HTMLCanvasElement | OffscreenCanvas,
+ layers: StampedLayer[],
+ stamps: StampCache,
+ t: number
+) {
+ const ctx = canvas.getContext("2d") as
+ | CanvasRenderingContext2D
+ | OffscreenCanvasRenderingContext2D
+ | null;
+ if (!ctx) return;
+ for (const layer of layers) {
+ if (t < layer.start || t >= layer.end) continue;
+ ctx.drawImage(await stamps.bitmapFor(layer), 0, 0, canvas.width, canvas.height);
+ }
+}
+
+/**
+ * Whether this render should happen in the tab.
+ *
+ * Two things have to hold. The cut has to be one a tab can carry — past ten
+ * minutes or 4K it belongs on the worker, which has a whole machine rather than
+ * a share of one. And the browser has to actually be able to encode it: whether
+ * WebCodecs offers a video encoder for these dimensions is a fact about the
+ * browser, not about the project, and asking after the render has already been
+ * routed here leaves nowhere to go. Answering it first means a browser that
+ * cannot encode quietly renders on the worker, the way every cloud export did
+ * before this path existed.
+ */
+export async function canRenderInBrowser(
+ doc: ExportDoc,
+ settings: ExportSettings
+): Promise<boolean> {
+ const duration = projectDuration(doc);
+ const pixels = settings.width * settings.height;
+ if (!(duration > 0) || duration > 10 * 60 || pixels > 3840 * 2160) return false;
+ try {
+ return !!(await getFirstEncodableVideoCodec(VIDEO_CODECS, {
+ width: settings.width,
+ height: settings.height,
+ }));
+ } catch {
+ return false;
+ }
+}
diff --git a/site/src/cut/lib/exportStore.ts b/site/src/cut/lib/exportStore.ts
index e729dcb0..b85a2297 100644
--- a/site/src/cut/lib/exportStore.ts
+++ b/site/src/cut/lib/exportStore.ts
@@ -9,9 +9,11 @@ import { localBackend } from "./backend/local";
import {
cancelExportJob,
createExportJob,
+ runBrowserExport,
type ExportDoc,
type ExportSettings,
} from "./exportClient";
+import { canRenderInBrowser } from "./exportRender";
import { useGenNotify } from "./genNotify";
// Exports are tracked app-wide, not per-open-project. The engine holds every
@@ -47,19 +49,24 @@ export function exportBackend(residency: CutMode): CutBackend {
return residency === "cloud" ? cloudBackend : localBackend;
}
-/** A client-only dock row for the brief window before the engine has a job id:
- * while the cut is being built and uploaded ("preparing"), or when that failed
- * before a job ever existed ("error"). Kept apart from the engine feed so a
+/** A client-only dock row for work no server job covers: the window before the
+ * engine has a job id ("preparing"), a failure that happened before a job ever
+ * existed ("error"), and the whole of a browser render ("rendering"), which has
+ * no server row until the file is stored. Kept apart from the engine feed so a
* poll tick never clears it. */
export interface LocalRow {
id: string;
projectId: string;
projectName?: string;
- status: "preparing" | "error";
+ status: "preparing" | "rendering" | "error";
error?: string;
+ /** 0..1 while rendering in this tab. */
+ progress?: number;
createdAt: number;
/** The backend the export is starting on, captured when it was kicked off. */
residency: CutMode;
+ /** Stops a browser render; absent for work a server owns. */
+ abort?: AbortController;
}
interface ExportsState {
@@ -69,6 +76,10 @@ interface ExportsState {
local: LocalRow[];
/** Finished/failed engine jobs the user cleared from this tab's dock. */
dismissed: string[];
+ /** Reserved job rows this tab is rendering itself. They are real rows in the
+ * feed, but the local row beside them is the one carrying progress, so they
+ * stay hidden until the render settles. */
+ rendering: string[];
/** Build the cut and hand it to the engine; the dock tracks it from there. */
start: (
projectId: string,
@@ -88,9 +99,17 @@ export const useExports = create<ExportsState>((set, get) => ({
jobs: [],
local: [],
dismissed: [],
+ rendering: [],
start: async (projectId, doc, settings, projectName) => {
const localId = `local-${crypto.randomUUID().slice(0, 8)}`;
+ const backend = getBackend();
+ // A cloud project renders in the tab: no upload of the cut to a container,
+ // no queue behind other accounts, and the file matches the preview because
+ // the same compositor drew both. Past what a tab can hold — a long cut, a
+ // very large frame — it goes to the worker, which has a whole machine.
+ const inBrowser = backend.kind === "cloud" && (await canRenderInBrowser(doc, settings));
+ const abort = inBrowser ? new AbortController() : undefined;
set((s) => ({
local: [
...s.local,
@@ -98,32 +117,73 @@ export const useExports = create<ExportsState>((set, get) => ({
id: localId,
projectId,
projectName,
- status: "preparing",
+ status: inBrowser ? "rendering" : "preparing",
+ ...(inBrowser ? { progress: 0 } : {}),
createdAt: Date.now(),
- residency: getBackend().kind,
+ residency: backend.kind,
+ abort,
},
],
}));
- try {
- await createExportJob(projectId, doc, settings);
- // Pull the queued job into the feed *before* retiring the placeholder.
- // Dropping the local row first left a round-trip with neither row on
- // screen, which read as the export card flashing away and back.
- // A failed poll must not mark a started export as a start error, so it
- // never reaches the catch below.
- await get().refresh().catch(() => {});
- set((s) => ({ local: s.local.filter((r) => r.id !== localId) }));
- } catch (err) {
+ let claimedId: string | null = null;
+ const release = () => {
+ if (claimedId) set((s) => ({ rendering: s.rendering.filter((id) => id !== claimedId) }));
+ };
+ const fail = (err: unknown) => {
const msg = err instanceof Error ? err.message : String(err);
set((s) => ({
local: s.local.map((r) =>
- r.id === localId ? { ...r, status: "error", error: msg } : r
+ r.id === localId ? { ...r, status: "error" as const, error: msg, abort: undefined } : r
),
}));
+ };
+ try {
+ if (inBrowser) {
+ await runBrowserExport(projectId, doc, settings, {
+ signal: abort!.signal,
+ // The reservation is a real job row, so the feed would show it beside
+ // the local row that carries the progress. Hide it until this tab is
+ // done with it.
+ onClaimed: (jobId) => {
+ claimedId = jobId;
+ set((s) => ({ rendering: [...new Set([...s.rendering, jobId])] }));
+ },
+ onProgress: (progress) =>
+ set((s) => ({
+ local: s.local.map((r) => (r.id === localId ? { ...r, progress } : r)),
+ })),
+ });
+ } else {
+ await createExportJob(projectId, doc, settings);
+ }
+ // Pull the finished (or queued) job into the feed *before* retiring the
+ // placeholder. Dropping the local row first left a round-trip with
+ // neither row on screen, which read as the export card flashing away and
+ // back. A failed poll must not mark a started export as a start error, so
+ // it never reaches the catch below.
+ release();
+ await get().refresh().catch(() => {});
+ set((s) => ({ local: s.local.filter((r) => r.id !== localId) }));
+ } catch (err) {
+ release();
+ // A render the user stopped leaves no row at all — the dock already
+ // showed it going, and an error card for their own cancel reads as a
+ // failure.
+ if (err instanceof DOMException && err.name === "AbortError") {
+ set((s) => ({ local: s.local.filter((r) => r.id !== localId) }));
+ return;
+ }
+ fail(err);
}
},
cancel: (id) => {
+ const local = get().local.find((r) => r.id === id);
+ if (local) {
+ local.abort?.abort();
+ set((s) => ({ local: s.local.filter((r) => r.id !== id) }));
+ return;
+ }
const job = get().jobs.find((j) => j.id === id);
cancelExportJob(id, job ? exportBackend(job.residency) : undefined);
set((s) => ({
diff --git a/site/src/cut/server/cloud/jobs.ts b/site/src/cut/server/cloud/jobs.ts
index 25af27c9..568f4601 100644
--- a/site/src/cut/server/cloud/jobs.ts
+++ b/site/src/cut/server/cloud/jobs.ts
@@ -7,14 +7,19 @@ import { EXPORT_QUOTA_MARGIN, renderJobCheck } from "./limits";
import { wakeRenderWorker } from "./wake";
import { getProject } from "./projects";
import { mediaObjectUrl } from "./mediaCdn";
-import { overlayKey, presignPut } from "./r2";
-import { quotaCheck } from "./usage";
+import { head, overlayKey, presignPut, projectExportKey } from "./r2";
+import { addUsage, quotaCheck } from "./usage";
import { caught, err, redirect } from "./util";
/** How long finished jobs stay in the export-jobs feed — the engine's registry
* keeps a bounded terminal backlog; the cloud keeps a day. */
const FEED_WINDOW_MS = 24 * 60 * 60 * 1000;
+/** How long a browser render may hold its reserved name before it is treated
+ * as a tab that went away. Generous next to the ten-minute cut the client will
+ * take on, because the wall-clock cost of a render depends on the machine. */
+const CLIENT_RENDER_WINDOW_MS = 2 * 60 * 60 * 1000;
+
type JobRow = {
id: string;
projectId: string | null;
@@ -43,15 +48,20 @@ async function findJob(userId: string, id: string): Promise<JobRow | null> {
/** Engine-style export name: `base.mp4` with a " 2", " 3"… suffix when taken
* by an existing export object or a job still in flight. The client derives the
* base from the project name; the dedupe happens here, where the rows are. */
-async function exportName(userId: string, projectId: string, baseName: string) {
+async function exportName(
+ userId: string,
+ projectId: string,
+ baseName: string,
+ tx: Prisma.TransactionClient | typeof prisma = prisma
+) {
const base =
baseName.replace(/\.mp4$/i, "").replace(/[/\\:*?"<>|]/g, "").trim().slice(0, 60) || "export";
const [files, jobs] = await Promise.all([
- prisma.cutMediaObject.findMany({
+ tx.cutMediaObject.findMany({
where: { userId, projectId, kind: "export" },
select: { fileName: true },
}),
- prisma.cutRenderJob.findMany({
+ tx.cutRenderJob.findMany({
where: { userId, projectId, kind: "export" },
select: { outName: true },
}),
@@ -221,6 +231,130 @@ export const jobsCloud = {
return Response.json({ ok: true });
},
+ /**
+ * Claim a name and a destination for an export the browser renders itself.
+ *
+ * The gates a queued render passes on its way in have to be passed here too —
+ * the concurrent-render cap and the storage margin — because a browser render
+ * is still a render this account asked for and still lands as a stored file.
+ * The name is deduped here, where the rows are, exactly as it is for the
+ * worker.
+ */
+ async exportClientPresign(userId: string, req: Request) {
+ try {
+ const body = (await req.json()) as { projectId?: string; outName?: string };
+ const projectId = body.projectId;
+ if (!projectId) return err("projectId is required.", 400);
+ if (!(await getProject(userId, projectId))) return err("Project not found.", 400);
+ const capped = await renderJobCheck(userId);
+ if (capped) return capped;
+ const over = await quotaCheck(userId, 0, EXPORT_QUOTA_MARGIN);
+ if (over) return over;
+ // The name is claimed by writing the row, not just by reading the rows
+ // that exist. `exportName` dedupes against stored objects and jobs, so a
+ // second export started while this one renders has to see this one — two
+ // tabs exporting the same project would otherwise both be handed
+ // "export.mp4", the second upload would overwrite the first, and the
+ // completion would then fail on the unique key with the render already
+ // spent. The row is the reservation.
+ const row = await prisma.$transaction(async (tx) => {
+ const outName = await exportName(userId, projectId, body.outName ?? "export.mp4", tx);
+ return tx.cutRenderJob.create({
+ data: {
+ userId,
+ projectId,
+ kind: "export",
+ // Rendering, in the tab rather than on the worker — which is why
+ // nothing ever claims it.
+ state: "running",
+ progress: 0,
+ spec: { client: true },
+ outName,
+ },
+ });
+ });
+ const key = projectExportKey(userId, projectId, row.outName!);
+ return Response.json({
+ jobId: row.id,
+ key,
+ outName: row.outName,
+ url: await presignPut(key, "video/mp4"),
+ });
+ } catch (e) {
+ return caught(e, "Could not start the export.");
+ }
+ },
+
+ /**
+ * Register a browser-rendered export that has finished uploading.
+ *
+ * The row is written already finished, because it is: the render happened in
+ * the tab and the bytes are in the bucket before this is called. That is the
+ * whole difference from a queued export — there is no state for the client to
+ * poll towards, so the dock's next refresh simply finds a completed job.
+ *
+ * The object's size is read from the bucket rather than taken from the
+ * client, since it is what the account's storage is charged.
+ */
+ async exportClientComplete(userId: string, req: Request) {
+ try {
+ const body = (await req.json()) as { jobId?: string };
+ if (!body.jobId) return err("jobId is required.", 400);
+ // The row the presign reserved carries the project and the name, so the
+ // client cannot claim a different one at completion time.
+ const row = await findJob(userId, body.jobId);
+ if (!row || row.kind !== "export" || !row.projectId || !row.outName) {
+ return err("Export not found.", 400);
+ }
+ if (row.state === "canceled") return err("Export canceled.", 400);
+ const { projectId, outName } = row;
+ const key = projectExportKey(userId, projectId, outName);
+ const object = await head(key);
+ if (!object) return err("The export was not uploaded.", 400);
+ const bytes = object.bytes;
+ await prisma.$transaction(async (tx) => {
+ await tx.cutMediaObject.create({
+ data: {
+ userId,
+ projectId,
+ r2Key: key,
+ fileName: outName,
+ mime: "video/mp4",
+ bytes: BigInt(bytes),
+ kind: "export",
+ uploadState: "complete",
+ },
+ });
+ await addUsage(tx, userId, bytes);
+ await tx.cutRenderJob.update({
+ where: { id: row.id },
+ data: { state: "done", progress: 1, outputKey: key },
+ });
+ });
+ return Response.json({ id: row.id, outName });
+ } catch (e) {
+ return caught(e, "Could not save the export.");
+ }
+ },
+
+ /**
+ * Give back a name a browser render claimed but will not use.
+ *
+ * The row is deleted rather than marked canceled: nothing rendered, so there
+ * is nothing to report, and a canceled row would put a failure card in the
+ * dock for a render the user themselves stopped.
+ */
+ async exportClientRelease(userId: string, jobId: string) {
+ try {
+ await prisma.cutRenderJob.deleteMany({
+ where: { id: jobId, userId, kind: "export", state: { in: ["running", "queued"] } },
+ });
+ return Response.json({ ok: true });
+ } catch (e) {
+ return caught(e, "Could not release the export.");
+ }
+ },
+
async exportFile(userId: string, jobId: string) {
try {
const row = await findJob(userId, jobId);
@@ -238,6 +372,22 @@ export const jobsCloud = {
/** The exports-dock feed: every export job for this account, start order —
* same view the engine's listAllJobs builds (previews stay internal). */
async exportFeed(userId: string) {
+ // A browser render lives in a tab, and a tab can close mid-render. Nothing
+ // claims those rows, so nothing else would ever release them, and each one
+ // left behind holds a name and a render slot for good. Any that have been
+ // running longer than a render plausibly takes are swept here, on the poll
+ // that would have displayed them.
+ await prisma.cutRenderJob
+ .deleteMany({
+ where: {
+ userId,
+ kind: "export",
+ state: "running",
+ claimedAt: null,
+ updatedAt: { lt: new Date(Date.now() - CLIENT_RENDER_WINDOW_MS) },
+ },
+ })
+ .catch(() => {});
const rows = await prisma.cutRenderJob.findMany({
where: {
userId,
diff --git a/site/src/cut/server/cloud/routes.ts b/site/src/cut/server/cloud/routes.ts
index c4a70bb0..fa9d58c3 100644
--- a/site/src/cut/server/cloud/routes.ts
+++ b/site/src/cut/server/cloud/routes.ts
@@ -79,6 +79,11 @@ const CUT_CLOUD_ROUTES: CloudRoute[] = [
{ method: "GET", path: "/api/cut-cloud/export-jobs", handler: (_r, u) => jobsCloud.exportFeed(u) },
{ method: "POST", path: "/api/cut-cloud/export", handler: (r, u) => jobsCloud.exportCreate(u, r) },
{ method: "POST", path: "/api/cut-cloud/export/presign", handler: (r, u) => jobsCloud.exportPresign(u, r) },
+ // A render the browser does itself: claim a name and a destination, then
+ // register the finished file. No queue in between — the tab is the worker.
+ { method: "POST", path: "/api/cut-cloud/export/client/presign", handler: (r, u) => jobsCloud.exportClientPresign(u, r) },
+ { method: "POST", path: "/api/cut-cloud/export/client/complete", handler: (r, u) => jobsCloud.exportClientComplete(u, r) },
+ { method: "POST", path: "/api/cut-cloud/export/client/:jobId/release", handler: (_r, u, p) => jobsCloud.exportClientRelease(u, p.jobId) },
{ method: "GET", path: "/api/cut-cloud/export/:jobId", handler: (_r, u, p) => jobsCloud.exportStatus(u, p.jobId) },
{ method: "DELETE", path: "/api/cut-cloud/export/:jobId", handler: (_r, u, p) => jobsCloud.exportCancel(u, p.jobId) },
{ method: "GET", path: "/api/cut-cloud/export/:jobId/file", handler: (_r, u, p) => jobsCloud.exportFile(u, p.jobId) },