Open source CapCut alternative.
TypeScript
feat(cut): serve a share's stream and rebuild it on a lull [rebuild]
David Le2ec36c1d27e4
diff --git a/site/src/cut/components/Editor.tsx b/site/src/cut/components/Editor.tsxindex e2dcfbb6..6e66d2c4 100644--- a/site/src/cut/components/Editor.tsx+++ b/site/src/cut/components/Editor.tsx@@ -7,7 +7,12 @@ import { Button } from "@/components/ui/button";import { apiFetch, bindCutMode, releaseCutMode } from "@/cut/lib/backend";import { loadedDocVersion } from "@/cut/lib/backend/shared";import { writeCachedDoc } from "@/cut/lib/docCache";-import { refreshShareCard, renderPreviewProxy, type ExportDoc } from "@/cut/lib/exportClient";+import {+ refreshShareCard,+ refreshShareLadder,+ renderPreviewProxy,+ type ExportDoc,+} from "@/cut/lib/exportClient";import { fileZoneAt, hasRefDrag } from "@/cut/lib/assetRef";import { startUpload } from "@/cut/lib/importQueue";import { enrichAsset, importFileToProject, prepareImport } from "@/cut/lib/media";@@ -222,6 +227,10 @@ export function Editor({try {await renderPreviewProxy(projectId, doc);refreshShareCard(projectId);+ // The share's streaming ladder rides this same lull. It is the most+ // expensive of the three — the whole cut, once per rung — so it runs+ // last, and it no-ops for a project that isn't shared.+ await refreshShareLadder(projectId);} finally {rendering = false;}diff --git a/site/src/cut/components/ShareDialog.tsx b/site/src/cut/components/ShareDialog.tsxindex 1c1edc54..e3c4512e 100644--- a/site/src/cut/components/ShareDialog.tsx+++ b/site/src/cut/components/ShareDialog.tsx@@ -18,7 +18,7 @@ import {} from "@/components/ui/dropdown-menu";import { Switch } from "@/components/ui/switch";import { apiFetch } from "@/cut/lib/backend";-import { refreshShareCard } from "@/cut/lib/exportClient";+import { refreshShareCard, refreshShareLadder } from "@/cut/lib/exportClient";import { useCutBase } from "@/cut/lib/nav";import type { ShareFeatures } from "@/cut/lib/types";@@ -98,6 +98,9 @@ export function ShareDialog({// Opening the dialog is the moment before a link gets pasted// somewhere, so bring an existing share's preview card up to date with// the cut as it stands.+ // The card is a five-second render and can ride a dialog open. The+ // ladder cannot: it re-encodes the whole cut once per rung, so it waits+ // for the editor's own lull instead (Editor.tsx).if (body.share) refreshShareCard(projectId);setShare(body.share);setLoading(false);@@ -127,8 +130,15 @@ export function ShareDialog({if (!res.ok) throw new Error();const body = (await res.json()) as { share: ShareState };// Sharing for the first time: build the link's preview card now, so the- // first person to see the link sees the cut rather than a placeholder.- if (!share) refreshShareCard(projectId);+ // first person to open the link sees the cut rather than a placeholder,+ // and start the streaming ladder so the link is playable on a phone+ // without waiting for the editor to close. This is the one interaction+ // that earns a whole-cut render — it is the moment a link starts+ // existing — and later saves leave it to the editor's lull.+ if (!share) {+ refreshShareCard(projectId);+ void refreshShareLadder(projectId);+ }setShare(body.share);return body.share;} catch {diff --git a/site/src/cut/lib/exportClient.ts b/site/src/cut/lib/exportClient.tsindex a17b7668..d955f1a3 100644--- a/site/src/cut/lib/exportClient.ts+++ b/site/src/cut/lib/exportClient.ts@@ -194,7 +194,7 @@ async function buildExportPayload(projectId: string,doc: ExportDoc,settings: ExportSettings,- target: "export" | "preview" | "card"+ target: "export" | "preview" | "card" | "hls"): Promise<ExportPayload> {const spans = getClipSpans(doc.clips, doc.assets);const duration = projectDuration(doc);@@ -446,7 +446,8 @@ async function postExport(projectId: string,payload: ExportPayload,outName: string,- backend: CutBackend+ backend: CutBackend,+ extra?: Record<string, unknown>): Promise<Response> {if (backend.kind !== "cloud") {return backend.fetch("/api/cut/export", { method: "POST", body: exportFormFromPayload(payload) });@@ -479,7 +480,7 @@ async function postExport(return backend.fetch("/api/cut/export", {method: "POST",headers: { "Content-Type": "application/json" },- body: JSON.stringify({ spec: payload.spec, overlays, projectId, outName }),+ body: JSON.stringify({ spec: payload.spec, overlays, projectId, outName, ...extra }),});}@@ -552,6 +553,53 @@ export function cancelExportJob(jobId: string, backend: CutBackend = getBackend(void backend.fetch(`/api/cut/export/${jobId}`, { method: "DELETE" }).catch(() => {});}+/**+ * Build the share's streaming ladder for the cut as it stands.+ *+ * A share plays HLS rather than a single file, so this is what makes a shared+ * project watchable — see server/hlsLadder.ts for why. The render is queued and+ * not waited on: it re-encodes the whole cut once per rung, so the caller+ * returns immediately and the viewer's page polls for the ladder to appear.+ *+ * The top rung is capped at the source, so the frame size sent here is the+ * ceiling on what any viewer can ever see; it renders at the doc's own size.+ *+ * `shareSubtitles` is what the share grants, and it decides whether captions+ * are burned in at all. The doc is what the OWNER sees, so passing it through+ * unfiltered would put cue text in the pixels of a stream sent to viewers whose+ * share hides Subtitles — and pixels are past the point where the server's doc+ * filter can take it back out.+ */+export async function renderShareLadder(+ projectId: string,+ doc: ExportDoc,+ shareSubtitles: boolean+): Promise<void> {+ const backend = getBackend(); // pinned: the ladder outlives the dialog+ // The master renders at "Original" — the ladder caps its top rung at this+ // frame, so anything given up here is given up for every viewer. The encode+ // preset is loosened because this master is an intermediate: every rung is+ // re-encoded from it, so its own compression never reaches a viewer.+ const settings: ExportSettings = {+ ...originalSettings(doc.aspect, doc.clips, doc.assets),+ preset: "veryfast",+ };+ // Both the flag and the cues go: the flag is what the burn-in reads, and+ // dropping the cues as well means no path through the pipeline can put this+ // text on screen for a viewer whose share does not grant it.+ const source: ExportDoc = shareSubtitles+ ? doc+ : { ...doc, subtitles: { ...doc.subtitles, cues: [], showOnVideo: false } };+ const burnedSubtitles = shareSubtitles && doc.subtitles?.showOnVideo === true;+ try {+ const payload = await buildExportPayload(projectId, source, settings, "hls");+ await postExport(projectId, payload, "master.m3u8", backend, { burnedSubtitles });+ } catch {+ // No clips yet, or a slot was busy. The share keeps playing whatever it+ // already had until a later attempt lands.+ }+}+/** Low-res proxy of the actual edit for the project card's hover preview.* Renders through the same pipeline (overlays and all), writing the project's* preview.mp4. Best-effort: silently no-ops if a slot is busy or there's no@@ -664,3 +712,45 @@ export function refreshShareCard(projectId: string): void {fadeOut: s.fadeOut,}).catch(() => {});}++/**+ * Rebuild the open project's streaming ladder from the cut as it stands.+ *+ * Fire and forget, like the card: a failed render leaves the previous ladder+ * serving. Unlike the card, this is not cheap — it re-encodes the whole cut+ * once per rung — so it belongs on the same lull the hover proxy waits for+ * (the editor closing, or the tab going to the background), never on an+ * interaction like opening a dialog. The server drops it for a project that+ * has no share, so callers do not have to know.+ *+ * `shareSubtitles` decides whether captions are burned in; pass what the share+ * actually grants, not what the owner is looking at.+ */+export async function refreshShareLadder(projectId: string): Promise<void> {+ const s = useEditor.getState();+ if (!s.loaded || s.projectId !== projectId || s.clips.length === 0) return;+ const backend = getBackend();+ // The share decides what the render may contain, so it is read first. This+ // also settles whether to render at all: an unshared project has no viewer to+ // build a ladder for.+ const res = await backend.fetch(`/api/cut/projects/${projectId}/share`).catch(() => null);+ if (!res?.ok) return;+ const body = (await res.json().catch(() => null)) as {+ share?: { features?: { subtitles?: boolean } } | null;+ } | null;+ if (!body?.share) return;+ await renderShareLadder(+ projectId,+ {+ aspect: s.aspect,+ assets: s.assets,+ clips: s.clips,+ audioClips: s.audioClips,+ overlays: s.overlays,+ subtitles: s.subtitles,+ fadeIn: s.fadeIn,+ fadeOut: s.fadeOut,+ },+ body.share.features?.subtitles === true+ );+}diff --git a/site/src/cut/server/cloud/jobs.ts b/site/src/cut/server/cloud/jobs.tsindex bdd38045..25af27c9 100644--- a/site/src/cut/server/cloud/jobs.ts+++ b/site/src/cut/server/cloud/jobs.ts@@ -97,6 +97,7 @@ export const jobsCloud = {overlays?: { name: string; key: string }[];projectId?: string;outName?: string;+ burnedSubtitles?: boolean;};if (!body.spec || typeof body.spec !== "object") return err("spec is required.", 400);const projectId = body.projectId ?? body.spec.projectId;@@ -112,12 +113,15 @@ export const jobsCloud = {return err("Invalid overlay key.", 400);}}- // Hover proxies and share cards are small internal renders the editor+ // Hover proxies, share cards and share ladders are renders the editor// fires on its own; only renders the user asked for count against the// cap.- const target = body.spec.target === "preview" || body.spec.target === "card"- ? body.spec.target- : "export";+ const target =+ body.spec.target === "preview" ||+ body.spec.target === "card" ||+ body.spec.target === "hls"+ ? body.spec.target+ : "export";if (target === "export") {const capped = await renderJobCheck(userId);if (capped) return capped;@@ -129,21 +133,55 @@ export const jobsCloud = {const over = await quotaCheck(userId, 0, EXPORT_QUOTA_MARGIN);if (over) return over;}+ const jobSpec = {+ spec: body.spec,+ overlays: body.overlays ?? [],+ ...(target === "hls" ? { burnedSubtitles: body.burnedSubtitles === true } : {}),+ } as unknown as Prisma.InputJsonValue;++ if (target === "hls") {+ // A ladder is only worth rendering for a project someone can actually+ // open: it is fired by the editor rather than asked for, so without+ // this an unshared project would burn a render slot on a stream with no+ // viewer.+ const shared = await prisma.cutProjectShare.findUnique({+ where: { projectId },+ select: { id: true },+ });+ if (!shared) return Response.json({ id: null, skipped: "not-shared" });++ // A ladder re-encodes the whole cut once per rung and holds a render+ // slot for the duration, so at most one runs and one waits. The waiting+ // one is REPLACED rather than kept: what matters is that the newest doc+ // renders last, and returning the in-flight job's id instead — as this+ // once did — silently dropped every edit made while one was running,+ // leaving the share streaming a pre-edit cut indefinitely.+ const queued = await prisma.cutRenderJob.findFirst({+ where: { userId, projectId, kind: "hls", state: "queued" },+ orderBy: { createdAt: "desc" },+ select: { id: true },+ });+ if (queued) {+ const replaced = await prisma.cutRenderJob.updateMany({+ where: { id: queued.id, state: "queued" },+ data: { spec: jobSpec },+ });+ // It started between the read and the write, so it is now the running+ // job and this doc needs a fresh row behind it.+ if (replaced.count > 0) {+ wakeRenderWorker();+ return Response.json({ id: queued.id });+ }+ }+ }const outName =target === "export"? await exportName(userId, projectId, body.outName?.trim() || project.name)- : `${target}.mp4`;+ : target === "hls"+ ? "master.m3u8"+ : `${target}.mp4`;const row = await prisma.cutRenderJob.create({- data: {- userId,- projectId,- kind: target,- spec: {- spec: body.spec,- overlays: body.overlays ?? [],- } as unknown as Prisma.InputJsonValue,- outName,- },+ data: { userId, projectId, kind: target, spec: jobSpec, outName },});wakeRenderWorker();return Response.json({ id: row.id });diff --git a/site/src/cut/server/cloud/sharedRoutes.ts b/site/src/cut/server/cloud/sharedRoutes.tsindex 00b67b83..40670be3 100644--- a/site/src/cut/server/cloud/sharedRoutes.ts+++ b/site/src/cut/server/cloud/sharedRoutes.ts@@ -20,6 +20,7 @@ const CUT_SHARED_ROUTES: SharedRoute[] = [{ method: "POST", path: "/api/cut-shared/:token/media/presign-get", handler: (r, p) => sharedView.presignGetBatch(p.token, r) },{ method: "GET", path: "/api/cut-shared/:token/projects/:id/chats", handler: (r, p) => sharedView.chats(p.token, p.id, r) },{ method: "GET", path: "/api/cut-shared/:token/projects/:id/preview", handler: (r, p) => sharedView.preview(p.token, p.id, r) },+ { method: "GET", path: "/api/cut-shared/:token/projects/:id/stream", handler: (r, p) => sharedView.stream(p.token, p.id, r) },{ method: "POST", path: "/api/cut-shared/:token/copy", handler: (r, p) => copyJobs.request(p.token, r) },{ method: "GET", path: "/api/cut-shared/:token/copy/:jobId", handler: (r, p) => copyJobs.status(p.token, p.jobId, r) },];diff --git a/site/src/cut/server/cloud/sharedView.ts b/site/src/cut/server/cloud/sharedView.tsindex 74152f99..d4a7701a 100644--- a/site/src/cut/server/cloud/sharedView.ts+++ b/site/src/cut/server/cloud/sharedView.ts@@ -7,8 +7,9 @@import type { ProjectDoc, StoredAsset } from "@/cut/lib/types";import { auth } from "@/lib/auth";import { prisma } from "@/lib/prisma";-import { mediaObjectUrl, mediaUrlLifetime } from "./mediaCdn";-import { projectMediaKey } from "./r2";+import { readLadder } from "./ladderStore";+import { mediaObjectUrl, mediaTreeUrl, mediaUrlLifetime } from "./mediaCdn";+import { projectHlsPrefix, projectMediaKey } from "./r2";import { normalizeEmails, normalizeFeatures, type ShareFeatures } from "./share";import { shareCacheHeaders, shareRedirectHeaders } from "./shareCache";import { caught, decodeFileParam, err, redirect } from "./util";@@ -215,6 +216,55 @@ export const sharedView = {);},+ /**+ * The share's streaming manifest: a tree-token URL for the published HLS+ * master, or 404 while no ladder exists yet.+ *+ * The token is sized to the cut's own duration, so a viewer who starts a long+ * project and watches it straight through never has playback die on an+ * expired segment. It is also the revocation window for those bytes, which is+ * why it tracks the content rather than being long by default.+ */+ async stream(token: string, id: string, req: Request) {+ try {+ const view = await resolveShare(token, req);+ if (view instanceof Response) return view;+ if (id !== view.share.projectId) return err("Not found.", 404);+ const ladder = await readLadder(id);+ // The record names the owner it was rendered for; a share whose project+ // changed hands is not served someone else's tree.+ const current = ladder?.userId === view.share.userId ? ladder.current : undefined;+ if (!current) return err("No stream yet.", 404);+ // The render is only as filtered as the share it was built for. If the+ // owner has since turned Subtitles off, the existing ladder still has cue+ // text in its pixels and there is nothing left to strip — so it is+ // withheld entirely, which reads to the viewer as a stream still being+ // prepared and is exactly what the next render fixes.+ if (current.burnedSubtitles && !view.features.subtitles) {+ return err("No stream yet.", 404);+ }+ const url = mediaTreeUrl(+ projectHlsPrefix(view.share.userId, id, current.version),+ "master.m3u8",+ { holdSeconds: Math.ceil(current.duration * 1.5) }+ );+ // Deliberately uncached, unlike the rest of a share's reads. A viewer who+ // opens a link mid-render polls this until the ladder appears, so an+ // edge-cached 404 would keep answering "not yet" after it had. The+ // response is a few bytes; the segments behind it are what caching is+ // for.+ return Response.json(+ { url, duration: current.duration },+ { headers: { "Cache-Control": "private, no-store" } }+ );+ } catch (e) {+ // 5xx, not 400: a store that is misconfigured or briefly unreachable is+ // the server's problem, and the viewer's poll should keep asking rather+ // than read it as "this share has no stream".+ return caught(e, "Could not read the stream.", 500);+ }+ },+async preview(token: string, id: string, req: Request) {try {const view = await resolveShare(token, req);@@ -222,6 +272,13 @@ export const sharedView = {if (id !== view.share.projectId) return err("Not found.", 404);const row = await ownerProject(view.share);if (!row?.previewKey) return new Response("Not found.", { status: 404 });+ // The proxy is rendered from the owner's own doc, captions and all, so it+ // crosses the same boundary the ladder does: a share that hides Subtitles+ // must not be handed a render with the cue text burned into it.+ const doc = row.doc as unknown as ProjectDoc | null;+ if (doc?.subtitles?.showOnVideo && !view.features.subtitles) {+ return new Response("Not found.", { status: 404 });+ }return redirect(mediaObjectUrl(row.previewKey),shareRedirectHeaders(view.share, MEDIA_REDIRECT_TTL)