Skip to content

Open source CapCut alternative.

TypeScript

feat(site): browser projects export in-tab to the local store

David Le69d36f434b3b
diff --git a/site/src/cut/components/ExportDialog.tsx b/site/src/cut/components/ExportDialog.tsx
index be1ead6a..182417b9 100644
--- a/site/src/cut/components/ExportDialog.tsx
+++ b/site/src/cut/components/ExportDialog.tsx
@@ -1,6 +1,6 @@
"use client";
-import { useMemo, useState } from "react";
+import { useEffect, useMemo, useState } from "react";
import { Button } from "@/components/ui/button";
import {
Dialog,
@@ -16,6 +16,8 @@ import {
originalSettings,
presetSettings,
} from "@/cut/lib/exportClient";
+import { useCutMode } from "@/cut/lib/backend/hooks";
+import { canRenderInBrowser } from "@/cut/lib/exportRender";
import { useExports } from "@/cut/lib/exportStore";
import { projectDuration, useEditor } from "@/cut/lib/store";
import { cn } from "@/lib/utils";
@@ -54,6 +56,39 @@ export function ExportDialog() {
[aspect, clips, assets]
);
const [presetId, setPresetId] = useState("original");
+ const selected = presets.find((p) => p.id === presetId) ?? presets[0];
+
+ // A browser-resident project has exactly one renderer: this tab. Ask up
+ // front whether the tab can hold this cut at the chosen size, so a refusal
+ // is a message here instead of an error card after the dialog closed.
+ const cutMode = useCutMode();
+ const [fits, setFits] = useState(true);
+ useEffect(() => {
+ if (cutMode !== "browser") {
+ setFits(true);
+ return;
+ }
+ let alive = true;
+ const s = useEditor.getState();
+ void canRenderInBrowser(
+ {
+ aspect: s.aspect,
+ assets: s.assets,
+ clips: s.clips,
+ audioClips: s.audioClips,
+ overlays: s.overlays,
+ subtitles: s.subtitles,
+ fadeIn: s.fadeIn,
+ fadeOut: s.fadeOut,
+ },
+ selected.settings
+ ).then((ok) => {
+ if (alive) setFits(ok);
+ });
+ return () => {
+ alive = false;
+ };
+ }, [cutMode, selected.settings]);
const run = () => {
const s = useEditor.getState();
@@ -110,12 +145,13 @@ export function ExportDialog() {
</div>
<DialogFooter className="flex-col gap-2 sm:flex-col">
- <Button className="w-full" onClick={run}>
+ <Button className="w-full" disabled={!fits} onClick={run}>
Export video
</Button>
<p className="text-center text-[11px] text-muted-foreground">
- Renders in the background. You can keep editing, open another project,
- or export more — each shows in the corner.
+ {fits
+ ? "Renders in the background. You can keep editing, open another project, or export more — each shows in the corner."
+ : "This project is too big to export from this tab. Move it to Cloud (top bar) to export."}
</p>
</DialogFooter>
</DialogContent>
diff --git a/site/src/cut/lib/exportClient.ts b/site/src/cut/lib/exportClient.ts
index 2f3734c7..688d6b4e 100644
--- a/site/src/cut/lib/exportClient.ts
+++ b/site/src/cut/lib/exportClient.ts
@@ -1,6 +1,13 @@
"use client";
import { apiFetch, apiJson, getBackend, type CutBackend } from "./backend";
+import {
+ removeBrowserExportJob,
+ reserveBrowserExportJob,
+ 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 { downloadFromUrl } from "./download";
import { renderProjectToMp4 } from "./exportRender";
@@ -870,12 +877,15 @@ export async function runBrowserExport(
opts: {
onProgress?: (ratio: number) => void;
signal?: AbortSignal;
+ /** Dock-row label for a browser-resident render's tab-local job. */
+ projectName?: string;
/** 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 === "browser") return runStoreExport(projectId, doc, settings, opts);
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
@@ -897,6 +907,9 @@ export async function runBrowserExport(
const jobId = claimed.jobId;
opts.onClaimed?.(jobId);
+ // The render keeps reading the project's store-served blob URLs after the
+ // user opens another project; the hold keeps them alive until it finishes.
+ holdRegistered(`/api/cut/projects/${projectId}/`);
try {
const rendered = await renderProjectToMp4(doc, settings, {
// Read the asset's URL at the moment it is needed rather than off the
@@ -936,6 +949,58 @@ export async function runBrowserExport(
.fetch(`/api/cut/export/client/${jobId}/release`, { method: "POST" })
.catch(() => {});
throw err;
+ } finally {
+ releaseRegistered(`/api/cut/projects/${projectId}/`);
+ }
+}
+
+/** A browser-resident project's export: the same in-tab render, with the
+ * finished file written into the project's exports shelf in the browser store.
+ * The job is a row in the tab-local feed, so the dock tracks, cancels, and
+ * downloads it the way it does every other residency's. */
+async function runStoreExport(
+ projectId: string,
+ doc: ExportDoc,
+ settings: ExportSettings,
+ opts: Parameters<typeof runBrowserExport>[3] = {}
+): Promise<string> {
+ const job = reserveBrowserExportJob(projectId, opts.projectName);
+ opts.onClaimed?.(job.id);
+ holdRegistered(`/api/cut/projects/${projectId}/`);
+ try {
+ const rendered = await renderProjectToMp4(doc, settings, {
+ resolve: (asset) =>
+ useEditor.getState().assets.find((a) => a.id === asset.id)?.url ?? asset.url,
+ signal: opts.signal,
+ onProgress: ({ ratio }) => {
+ opts.onProgress?.(ratio);
+ updateBrowserExportJob(job.id, { progress: ratio });
+ },
+ });
+ let outName: string;
+ try {
+ outName = await saveExport(projectId, rendered.file, exportOutName());
+ } finally {
+ void rendered.discard();
+ }
+ // Serve the finished file from the store copy: the scratch file behind the
+ // render is already gone, and these two paths are what the dock's download
+ // button and the exports shelf resolve through backend.url().
+ const saved = await readFileAt(await exportsDir(projectId), outName);
+ if (saved) {
+ registerBlobFile(`/api/cut/export/${job.id}/file`, saved);
+ registerBlobFile(
+ `/api/cut/projects/${projectId}/exports/${encodeURIComponent(outName)}`,
+ saved
+ );
+ }
+ updateBrowserExportJob(job.id, { status: "done", progress: 1, outName });
+ return job.id;
+ } catch (err) {
+ removeBrowserExportJob(job.id);
+ throw err;
+ } finally {
+ releaseRegistered(`/api/cut/projects/${projectId}/`);
}
}
diff --git a/site/src/cut/lib/exportStore.ts b/site/src/cut/lib/exportStore.ts
index 47e14f91..8b22e26b 100644
--- a/site/src/cut/lib/exportStore.ts
+++ b/site/src/cut/lib/exportStore.ts
@@ -4,6 +4,7 @@ import { useEffect, useRef } from "react";
import { create } from "zustand";
import { engineOrigin, servedFromEngine } from "./api";
import { getBackend, type CutBackend, type CutMode } from "./backend";
+import { browserBackend } from "./backend/browser";
import { cloudBackend } from "./backend/cloud";
import { localBackend } from "./backend/local";
import {
@@ -46,7 +47,9 @@ export interface ExportJob {
/** The backend a dock row lives on; per-row actions hit this, never the
* globally bound mode. */
export function exportBackend(residency: CutMode): CutBackend {
- return residency === "cloud" ? cloudBackend : localBackend;
+ if (residency === "cloud") return cloudBackend;
+ if (residency === "browser") return browserBackend;
+ return localBackend;
}
/** A client-only dock row for work no server job covers: the window before the
@@ -107,8 +110,11 @@ export const useExports = create<ExportsState>((set, get) => ({
// 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));
+ // very large frame — it goes to the worker, which has a whole machine. A
+ // browser-resident project renders in the tab too; the tab is its machine.
+ const inBrowser =
+ (backend.kind === "cloud" || backend.kind === "browser") &&
+ (await canRenderInBrowser(doc, settings));
const abort = inBrowser ? new AbortController() : undefined;
set((s) => ({
local: [
@@ -141,9 +147,15 @@ export const useExports = create<ExportsState>((set, get) => ({
}));
};
try {
+ if (backend.kind === "browser" && !inBrowser) {
+ throw new Error(
+ "This project is too big to export from this tab. Move it to Cloud to export."
+ );
+ }
if (inBrowser) {
await runBrowserExport(projectId, doc, settings, {
signal: abort!.signal,
+ projectName,
// 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.
@@ -254,9 +266,11 @@ export const useExports = create<ExportsState>((set, get) => ({
const pollCloud =
(typeof navigator === "undefined" || navigator.onLine) &&
Date.now() >= cloudRetryAt;
- const [localRows, cloudRows] = await Promise.all([
+ // The browser feed is this tab's own memory, so it always answers.
+ const [localRows, cloudRows, browserRows] = await Promise.all([
pollLocal ? fetchFeed(localBackend) : Promise.resolve(null),
pollCloud ? fetchFeed(cloudBackend) : Promise.resolve(null),
+ fetchFeed(browserBackend),
]);
if (pollCloud) {
if (cloudRows === null) {
@@ -272,7 +286,11 @@ export const useExports = create<ExportsState>((set, get) => ({
// replaces that backend's slice.
const slice = (kind: CutMode, fresh: ExportJob[] | null) =>
fresh ?? s.jobs.filter((j) => j.residency === kind);
- const jobs = [...slice("local", localRows), ...slice("cloud", cloudRows)];
+ const jobs = [
+ ...slice("local", localRows),
+ ...slice("cloud", cloudRows),
+ ...slice("browser", browserRows),
+ ];
return {
jobs,
dismissed: s.dismissed.filter((id) => jobs.some((j) => j.id === id)),