Skip to content

Open source CapCut alternative.

TypeScript

feat(site): convert media to MP4 where the bytes already are [rebuild]

David Le59dab1174239
diff --git a/site/src/cut/lib/media.ts b/site/src/cut/lib/media.ts
index 81c82a47..5566fbae 100644
--- a/site/src/cut/lib/media.ts
+++ b/site/src/cut/lib/media.ts
@@ -6,6 +6,7 @@ import { quotaErrorMessage } from "./backend/cloud";
import { encodeWav } from "./cloudTranscribe";
import { downloadFromUrl } from "./download";
import { startUpload, uploadInFlight } from "./importQueue";
+import { convertProjectFile, dropProjectFile, mp4DisplayName } from "./mediaConvert";
import {
audioChunks,
audioPeaks,
@@ -456,8 +457,19 @@ export async function prepareImport(
const storedUrl = signed
? await stashCloudMedia(projectId, file, signed.fileName)
: stashed!.url;
- const meta = await metaP;
const fileName = signed ? signed.fileName : stashed!.fileName;
+ // Footage this browser has no decoder for imports the plain way instead:
+ // the file reaches the project first and converts there, which local-first
+ // can't do — the optimistic asset would be one nothing here can play.
+ const meta = await metaP.catch((e: unknown) => {
+ if (e instanceof UnreadableMediaError && e.undecodable) return null;
+ throw e;
+ });
+ if (!meta) {
+ URL.revokeObjectURL(objectUrl);
+ await dropLocalMedia(projectId, fileName);
+ return null;
+ }
const localUrl = storedUrl ?? objectUrl;
if (storedUrl) URL.revokeObjectURL(objectUrl);
const asset: MediaAsset = {
@@ -600,15 +612,35 @@ export async function importFileToProject(
const type = assetTypeOf(file);
if (!type) return null;
- const fileName = await uploadProjectMediaTo(backend, projectId, file, file.name);
- const url = mediaUrl(projectId, fileName, backend);
+ let fileName = await uploadProjectMediaTo(backend, projectId, file, file.name);
+ let name = file.name;
// Probe the bytes in hand: the same file the upload just wrote, with no
// second network read — which also lets a headless process import media.
- const meta = await probeMedia(type, file);
+ const meta = await probeMedia(type, file).catch(async (e: unknown) => {
+ // Footage this browser has no decoder for — a phone's HEVC, a camera's
+ // ProRes. The file is already in the project, so convert it there and
+ // import what comes back; the raw upload goes with the failure otherwise.
+ if (!(e instanceof UnreadableMediaError && e.undecodable)) throw e;
+ const made = await convertProjectFile(
+ projectId,
+ { fileName, url: mediaUrl(projectId, fileName, backend), name: file.name },
+ { backend }
+ ).catch((convertError: unknown) => {
+ void dropProjectFile(projectId, fileName, backend).catch(() => {});
+ throw convertError;
+ });
+ void dropProjectFile(projectId, fileName, backend).catch(() => {});
+ fileName = made.fileName;
+ // The asset answers to what it now is: a card reading .MOV over an MP4
+ // file is the card lying about the media.
+ name = mp4DisplayName(name);
+ return probeMedia(type, mediaUrl(projectId, fileName, backend));
+ });
+ const url = mediaUrl(projectId, fileName, backend);
return {
id: uid(),
fileName,
- name: file.name,
+ name,
type: meta.type,
duration: meta.duration,
...(meta.width !== undefined ? { width: meta.width } : {}),
diff --git a/site/src/cut/lib/mediaConvert.ts b/site/src/cut/lib/mediaConvert.ts
new file mode 100644
index 00000000..6d7fb7bf
--- /dev/null
+++ b/site/src/cut/lib/mediaConvert.ts
@@ -0,0 +1,418 @@
+"use client";
+
+/**
+ * Converting a project's media to MP4 — H.264 picture, AAC sound — in place.
+ *
+ * Footage arrives in whatever the camera wrote. A phone's .mov is HEVC, a
+ * screen recorder's is ProRes with raw PCM sound, and neither decodes in
+ * every browser: the clip previews black, or refuses to import at all.
+ * Converting it is the repair, and it is the same repair someone means when
+ * they say "turn these .mov files into mp4".
+ *
+ * Where a conversion runs is decided by where the bytes already are, because
+ * moving a video file costs more than converting one:
+ *
+ * Mac project the engine's ffmpeg, on the file in the project folder.
+ * cloud project a render-worker job, on the object in R2. The tab sends
+ * nothing and waits on the job row it polls.
+ * browser project this tab, where mediabunny drives WebCodecs — and where
+ * a file whose streams already fit is copied packet for
+ * packet, with no decoding at all. Footage this browser
+ * has no decoder for goes to the Mac when the app is
+ * running: the page posts the bytes to the engine and gets
+ * an MP4 back, the trade transcription already makes.
+ * headless a process with no page converts for itself. The engine
+ * installs a converter that works the project folder
+ * directly; the cloud runner carries decoders of its own
+ * and runs the same in-process path a tab runs.
+ *
+ * The asset keeps its id and its name, so every clip cut from it keeps
+ * playing; only the file underneath changes. The old file is deleted once the
+ * new one is in the document — a conversion that left both behind would
+ * double what the project costs against the user's storage.
+ */
+
+import {
+ BufferTarget,
+ Conversion,
+ Mp4OutputFormat,
+ Output,
+ type ConversionAudioOptions,
+ type ConversionVideoOptions,
+} from "mediabunny";
+import { apiFetch as engineFetch } from "./api";
+import { getBackend, hasLocalCompute, type CutBackend } from "./backend";
+import { resolveRegisteredBlob } from "./backend/browser/registry";
+import { enrichAsset, uploadProjectMediaTo } from "./media";
+import {
+ audioTrackOf,
+ hasUndecodableVideo,
+ openMedia,
+ probeMediaFile,
+ videoTrackOf,
+ withMedia,
+} from "./mediaRead";
+import { useEditor } from "./store";
+import { mediaUrl, type MediaAsset } from "./types";
+
+/** One file in a project, as the converter addresses it. */
+export interface ConvertSource {
+ fileName: string;
+ /** Where the bytes can be read when the conversion runs in this process. */
+ url: string;
+ /** Display name, for the message an error carries back to the user. */
+ name: string;
+}
+
+export interface ConvertOptions {
+ maxHeight?: number;
+ /** Pinned by work that outlives navigation; defaults to the active one. */
+ backend?: CutBackend;
+}
+
+/** A finished conversion: the new file, and what that file turned out to be,
+ * so nothing downstream has to read it again. */
+export interface FileConversion {
+ fileName: string;
+ /** False when the streams were copied into the new container untouched. */
+ reencoded: boolean;
+ /** The file was already an MP4 of the right streams, so it was left alone
+ * and `fileName` is the one the project already had. */
+ unchanged?: boolean;
+ duration: number;
+ width?: number;
+ height?: number;
+}
+
+/** What a conversion did to an asset, reported back to whoever asked. */
+export interface ConvertOutcome extends FileConversion {
+ assetId: string;
+ /** The asset's display name, rewritten to the new extension. */
+ name: string;
+}
+
+/** What a headless host does for itself, in place of the client's backend
+ * seam: it holds the project's files, so it converts and deletes them
+ * directly rather than addressing itself over HTTP. */
+export interface HostMediaStore {
+ convert(projectId: string, source: ConvertSource, opts: ConvertOptions): Promise<FileConversion>;
+ drop(projectId: string, fileName: string): Promise<void>;
+}
+
+/** In-process conversion holds the whole output in memory. A source past this
+ * belongs on a machine with a disk, and saying so beats an out-of-memory tab
+ * several minutes in. */
+const IN_PROCESS_MAX_BYTES = 2 * 1024 * 1024 * 1024;
+
+const inPage = () => typeof document !== "undefined";
+
+/** Containers that hold the target streams under the name people ask for. */
+const MP4_EXT = /\.(mp4|m4v)$/i;
+
+let host: HostMediaStore | null = null;
+
+/** Install the store a headless host does its own media work with. */
+export function setHostMediaStore(store: HostMediaStore | null) {
+ host = store;
+}
+
+/** The MP4 name a source file converts to: same stem, `.mp4` extension. */
+export const mp4NameFor = (fileName: string) =>
+ `${fileName.replace(/\.[^./\\]+$/, "") || "media"}.mp4`;
+
+/** A display name after conversion. A name carrying the camera's extension
+ * gets the new one — the card reading IMG_4450.MOV under a file that is now
+ * an MP4 is the card lying. A name with no extension is the user's words and
+ * stays as written. */
+export const mp4DisplayName = (name: string) =>
+ /\.[a-z0-9]{2,4}$/i.test(name) ? mp4NameFor(name) : name;
+
+/**
+ * Convert one of a project's media files to MP4, leaving the original in
+ * place. The result lands beside it under a deduped name; what points at
+ * which file is the caller's to decide.
+ */
+export async function convertProjectFile(
+ projectId: string,
+ source: ConvertSource,
+ opts: ConvertOptions = {}
+): Promise<FileConversion> {
+ if (host) return host.convert(projectId, source, opts);
+ const backend = opts.backend ?? getBackend();
+ // The machine that stores the bytes converts them: the Mac for its own
+ // projects, the worker beside R2 for cloud ones. A headless process working
+ // a cloud project is that machine, so it converts in-process.
+ return backend.kind === "local" || (backend.kind === "cloud" && inPage())
+ ? convertOnBackend(projectId, source, backend, opts.maxHeight)
+ : convertNearThePage(projectId, source, { ...opts, backend });
+}
+
+/**
+ * Convert one project asset to MP4 and point the asset at the result.
+ *
+ * `maxHeight` caps the picture's height, which forces a re-encode when the
+ * source is taller. Everything else is decided from the file: streams that
+ * already fit the container are copied, the rest are re-encoded.
+ */
+export async function convertAssetToMp4(
+ projectId: string,
+ asset: MediaAsset,
+ opts: ConvertOptions = {}
+): Promise<ConvertOutcome> {
+ if (asset.type === "image") throw new Error("Images have nothing to convert.");
+ const backend = opts.backend ?? getBackend();
+ const made = await convertProjectFile(
+ projectId,
+ { fileName: asset.fileName, url: asset.url, name: asset.name },
+ { ...opts, backend }
+ );
+
+ if (made.unchanged) return { assetId: asset.id, name: asset.name, ...made };
+
+ const patch: Partial<MediaAsset> = {
+ fileName: made.fileName,
+ name: mp4DisplayName(asset.name),
+ url: mediaUrl(projectId, made.fileName, backend),
+ duration: made.duration,
+ ...(made.width !== undefined ? { width: made.width } : {}),
+ ...(made.height !== undefined ? { height: made.height } : {}),
+ // The filmstrip and waveform were read off bytes that are about to be
+ // deleted; enrichAsset fills them again from the new file.
+ thumbs: undefined,
+ thumbStep: undefined,
+ peaks: undefined,
+ };
+ useEditor.getState().updateAsset(asset.id, patch);
+ void enrichAsset({ ...asset, ...patch }).catch(() => {});
+ // Best effort: a file left behind costs storage while everything else
+ // already points at the new one.
+ void dropProjectFile(projectId, asset.fileName, backend).catch(() => {});
+
+ return { assetId: asset.id, name: patch.name!, ...made };
+}
+
+/** Delete a project file through whichever side owns the storage. */
+export function dropProjectFile(
+ projectId: string,
+ fileName: string,
+ backend: CutBackend = getBackend()
+): Promise<unknown> {
+ if (host) return host.drop(projectId, fileName);
+ return backend.fetch(`/api/cut/projects/${projectId}/media/${encodeURIComponent(fileName)}`, {
+ method: "DELETE",
+ });
+}
+
+/** Server answer shape, identical from the engine's project route and the
+ * worker's job result. */
+interface ServerConvert {
+ fileName?: string;
+ duration?: number;
+ width?: number;
+ height?: number;
+ transcodedVideo?: boolean;
+ transcodedAudio?: boolean;
+ unchanged?: boolean;
+ error?: string;
+}
+
+const fromServer = (body: ServerConvert): FileConversion => ({
+ fileName: body.fileName!,
+ reencoded: !!body.transcodedVideo || !!body.transcodedAudio,
+ ...(body.unchanged ? { unchanged: true } : {}),
+ duration: body.duration ?? 0,
+ ...(body.width !== undefined ? { width: body.width, height: body.height } : {}),
+});
+
+/** The engine converts the project's file synchronously; the cloud queues a
+ * worker job and this polls it. Both answer with the same fields. */
+async function convertOnBackend(
+ projectId: string,
+ source: ConvertSource,
+ backend: CutBackend,
+ maxHeight?: number
+): Promise<FileConversion> {
+ const res = await backend.fetch(`/api/cut/projects/${projectId}/convert`, {
+ method: "POST",
+ headers: { "Content-Type": "application/json" },
+ body: JSON.stringify({ file: source.fileName, ...(maxHeight ? { maxHeight } : {}) }),
+ });
+ let body: ServerConvert;
+ if (backend.kind === "cloud") {
+ const started = (await res.json().catch(() => ({}))) as { jobId?: string; error?: string };
+ if (!res.ok || !started.jobId) throw new Error(started.error ?? "Could not convert that file.");
+ body = await pollConvertJob(started.jobId, backend);
+ } else {
+ body = (await res.json().catch(() => ({}))) as ServerConvert;
+ if (!res.ok) throw new Error(body.error ?? "Could not convert that file.");
+ }
+ if (!body.fileName) throw new Error(body.error ?? "Could not convert that file.");
+ return fromServer(body);
+}
+
+/** Poll a cloud convert job to completion — the import-url cadence: 2s, a
+ * ten-minute ceiling, and a run of failed polls before giving up on it. */
+async function pollConvertJob(jobId: string, backend: CutBackend): Promise<ServerConvert> {
+ const deadline = Date.now() + 10 * 60 * 1000;
+ const MAX_STRIKES = 6;
+ let strikes = 0;
+ for (;;) {
+ if (Date.now() > deadline) throw new Error("The conversion took too long.");
+ await new Promise((r) => setTimeout(r, 2000));
+ let res: Response | null = null;
+ try {
+ res = await backend.fetch(`/api/cut/jobs/${jobId}`);
+ } catch {
+ // Network blip — a strike, counted below.
+ }
+ if (res?.status === 404) throw new Error("Could not convert that file.");
+ if (!res?.ok) {
+ if (++strikes >= MAX_STRIKES) throw new Error("Could not convert that file.");
+ continue;
+ }
+ strikes = 0;
+ const job = (await res.json().catch(() => ({}))) as {
+ state?: string;
+ result?: ServerConvert;
+ error?: string;
+ };
+ if (job.state === "error") throw new Error(job.error ?? "Could not convert that file.");
+ if (job.state === "done") return job.result ?? {};
+ }
+}
+
+/** No machine stores this project, so the work happens beside the bytes: in
+ * this process, or on the Mac when this process has no decoder for them. */
+async function convertNearThePage(
+ projectId: string,
+ source: ConvertSource,
+ opts: ConvertOptions
+): Promise<FileConversion> {
+ const decodable = await withMedia(
+ source.url,
+ async (input) => !(await hasUndecodableVideo(input))
+ );
+ if (decodable) return convertInProcess(projectId, source, opts);
+ if (hasLocalCompute()) return convertOnTheMac(projectId, source, opts);
+ throw new Error(
+ `${source.name} is in a format this browser can't decode. Run the Donkey app to convert it on this Mac, open the project in Safari, or move it to the cloud.`
+ );
+}
+
+/**
+ * Convert in this process with mediabunny: WebCodecs in a tab, the headless
+ * runtime's decoders in a worker. Source packets that already fit the
+ * container are copied, which makes the common .mov of H.264 a fast remux
+ * with no decoding at all.
+ */
+async function convertInProcess(
+ projectId: string,
+ source: ConvertSource,
+ opts: ConvertOptions
+): Promise<FileConversion> {
+ const bytes = resolveRegisteredBlob(source.url);
+ if (bytes && bytes.size > IN_PROCESS_MAX_BYTES) {
+ throw new Error(`${source.name} is too large to convert here.`);
+ }
+ const input = openMedia(source.url);
+ try {
+ const [video, audio] = await Promise.all([videoTrackOf(input), audioTrackOf(input)]);
+ const height = video ? await video.getDisplayHeight() : 0;
+ const cap = opts.maxHeight && opts.maxHeight > 0 ? Math.round(opts.maxHeight) : 0;
+ const shrink = !!(cap && height > cap);
+ // Already the file a conversion would produce — a second pass would copy
+ // it to a new name and change nothing.
+ if (
+ MP4_EXT.test(source.fileName) &&
+ !shrink &&
+ (!video || video.codec === "avc") &&
+ (!audio || audio.codec === "aac")
+ ) {
+ return {
+ fileName: source.fileName,
+ reencoded: false,
+ unchanged: true,
+ duration: await input.computeDuration(),
+ ...(video ? { width: await video.getDisplayWidth(), height } : {}),
+ };
+ }
+ // A stream already in the target codec is copied packet for packet; what
+ // is left over is what gets decoded and re-encoded.
+ const reencoded =
+ (!!video && (video.codec !== "avc" || shrink)) || (!!audio && audio.codec !== "aac");
+ const videoOptions: ConversionVideoOptions = {
+ codec: "avc",
+ ...(shrink ? { height: cap } : {}),
+ };
+ const audioOptions: ConversionAudioOptions = { codec: "aac" };
+
+ const output = new Output({
+ format: new Mp4OutputFormat({ fastStart: "in-memory" }),
+ target: new BufferTarget(),
+ });
+ const conversion = await Conversion.init({
+ input,
+ output,
+ video: videoOptions,
+ audio: audioOptions,
+ });
+ if (!conversion.isValid) {
+ const reason = conversion.discardedTracks[0]?.reason;
+ throw new Error(
+ reason === "undecodable_source_codec" || reason === "no_encodable_target_codec"
+ ? `${source.name} is in a format this browser can't convert. Run the Donkey app to convert it on this Mac, open the project in Safari, or move it to the cloud.`
+ : `Could not convert ${source.name}.`
+ );
+ }
+ await conversion.execute();
+ const buffer = output.target.buffer;
+ if (!buffer) throw new Error(`Could not convert ${source.name}.`);
+ const made = await land(projectId, source, new Blob([buffer], { type: "video/mp4" }), opts);
+ return { ...made, reencoded };
+ } finally {
+ input.dispose();
+ }
+}
+
+/** Hand the bytes to the Mac and take the MP4 back. The engine keeps nothing:
+ * it converts what it is given and answers with the file. */
+async function convertOnTheMac(
+ projectId: string,
+ source: ConvertSource,
+ opts: ConvertOptions
+): Promise<FileConversion> {
+ const bytes = resolveRegisteredBlob(source.url) ?? (await (await fetch(source.url)).blob());
+ const form = new FormData();
+ form.append("file", bytes, source.fileName);
+ if (opts.maxHeight) form.append("maxHeight", String(Math.round(opts.maxHeight)));
+ const res = await engineFetch("/api/cut/convert", { method: "POST", body: form });
+ if (!res.ok) {
+ const body = (await res.json().catch(() => ({}))) as { error?: string };
+ throw new Error(body.error ?? `Could not convert ${source.name}.`);
+ }
+ // The handoff only happens for footage this process cannot decode, which is
+ // footage the Mac had to re-encode.
+ return land(projectId, source, await res.blob(), opts);
+}
+
+/** Store a converted blob in the project and read back what it is. */
+async function land(
+ projectId: string,
+ source: ConvertSource,
+ blob: Blob,
+ opts: ConvertOptions
+): Promise<FileConversion> {
+ const fileName = await uploadProjectMediaTo(
+ opts.backend ?? getBackend(),
+ projectId,
+ blob,
+ mp4NameFor(source.fileName)
+ );
+ const meta = await probeMediaFile(blob);
+ return {
+ fileName,
+ reencoded: true,
+ duration: meta.duration,
+ ...(meta.width !== undefined ? { width: meta.width, height: meta.height } : {}),
+ };
+}
diff --git a/site/src/cut/lib/mediaRead.ts b/site/src/cut/lib/mediaRead.ts
index c64a8615..7bac2b29 100644
--- a/site/src/cut/lib/mediaRead.ts
+++ b/site/src/cut/lib/mediaRead.ts
@@ -60,9 +60,15 @@ export interface FrameSize {
}
export class UnreadableMediaError extends Error {
- constructor(message = "Cut can't read this media file.") {
+ /** The container parsed and the file carries video — this browser just has
+ * no decoder for it. Callers that can convert branch on this rather than on
+ * the message. */
+ readonly undecodable: boolean;
+
+ constructor(message = "Cut can't read this media file.", undecodable = false) {
super(message);
this.name = "UnreadableMediaError";
+ this.undecodable = undecodable;
}
}
@@ -135,7 +141,10 @@ export async function probeMediaFile(src: string | Blob): Promise<MediaProbe> {
// audio would be a quieter failure, not a smaller one: the clip would look
// imported and simply have no picture.
if (!video && (await hasUndecodableVideo(input))) {
- throw new UnreadableMediaError("This video is in a format Cut can't decode in this browser.");
+ throw new UnreadableMediaError(
+ "This video is in a format Cut can't decode in this browser.",
+ true
+ );
}
if (!video && !audio) throw new UnreadableMediaError();
const duration = await input.computeDuration();
diff --git a/site/src/cut/server/cloud/jobs.ts b/site/src/cut/server/cloud/jobs.ts
index 35f6b4e7..9303cfda 100644
--- a/site/src/cut/server/cloud/jobs.ts
+++ b/site/src/cut/server/cloud/jobs.ts
@@ -453,7 +453,36 @@ export const jobsCloud = {
}
},
- /** Generic job poll for non-export kinds (import_url). */
+ /** Queue a media conversion: the worker rewrites one of the project's media
+ * files as MP4 and registers it beside the original. */
+ async convert(userId: string, projectId: string, req: Request) {
+ try {
+ const { file, maxHeight } = (await req.json()) as { file?: string; maxHeight?: number };
+ if (!file) return err("file is required.", 400);
+ if (!(await getProject(userId, projectId))) return err("Project not found.", 404);
+ const source = await prisma.cutMediaObject.findFirst({
+ where: { userId, projectId, fileName: file, kind: "media" },
+ select: { id: true },
+ });
+ if (!source) return err("Media file missing from project.", 404);
+ const capped = await renderJobCheck(userId);
+ if (capped) return capped;
+ const row = await prisma.cutRenderJob.create({
+ data: {
+ userId,
+ projectId,
+ kind: "convert",
+ spec: { file, ...(maxHeight ? { maxHeight } : {}) } as unknown as Prisma.InputJsonValue,
+ },
+ });
+ wakeRenderWorker();
+ return Response.json({ jobId: row.id });
+ } catch (e) {
+ return caught(e, "Could not convert that file.");
+ }
+ },
+
+ /** Generic job poll for non-export kinds (import_url, convert). */
async status(userId: string, jobId: string) {
const row = await findJob(userId, jobId);
if (!row) return err("Unknown job.", 404);
diff --git a/site/src/cut/server/cloud/limits.ts b/site/src/cut/server/cloud/limits.ts
index 8b02a024..3a42f210 100644
--- a/site/src/cut/server/cloud/limits.ts
+++ b/site/src/cut/server/cloud/limits.ts
@@ -35,14 +35,14 @@ export async function renderJobCheck(userId: string): Promise<Response | null> {
if (limits.renderJobsPerDay === null) return null;
const since = new Date(Date.now() - 24 * 60 * 60 * 1000);
const used = await prisma.cutRenderJob.count({
- where: { userId, kind: { in: ["export", "import_url"] }, createdAt: { gte: since } },
+ where: { userId, kind: { in: ["export", "import_url", "convert"] }, createdAt: { gte: since } },
});
if (used < limits.renderJobsPerDay) return null;
// `error` is what the client's shared error paths render — keep it human.
return Response.json(
{
error:
- "You've reached today's limit for exports and imports. It resets over the next 24 hours — or Pro raises it.",
+ "You've reached today's limit for exports, imports, and conversions. It resets over the next 24 hours — or Pro raises it.",
code: "daily_render_limit",
limit: limits.renderJobsPerDay,
},
diff --git a/site/src/cut/server/cloud/routes.ts b/site/src/cut/server/cloud/routes.ts
index 163fc4c9..355e8033 100644
--- a/site/src/cut/server/cloud/routes.ts
+++ b/site/src/cut/server/cloud/routes.ts
@@ -59,6 +59,7 @@ const CUT_CLOUD_ROUTES: CloudRoute[] = [
{ method: "POST", path: "/api/cut-cloud/projects/:id/media/presign", handler: (r, u, p) => mediaCloud.presign(u, p.id, r) },
{ method: "POST", path: "/api/cut-cloud/projects/:id/media/complete", handler: (r, u) => mediaCloud.complete(u, r) },
{ method: "POST", path: "/api/cut-cloud/projects/:id/import-url", handler: (r, u, p) => jobsCloud.importUrl(u, p.id, r) },
+ { method: "POST", path: "/api/cut-cloud/projects/:id/convert", handler: (r, u, p) => jobsCloud.convert(u, p.id, r) },
{ method: "POST", path: "/api/cut-cloud/media/presign-get", handler: (r, u) => mediaCloud.presignGetBatch(u, r) },
{ method: "GET", path: "/api/cut-cloud/library", handler: (_r, u) => libraryCloud.list(u) },
diff --git a/site/src/cut/server/convert.ts b/site/src/cut/server/convert.ts
new file mode 100644
index 00000000..f4968b4d
--- /dev/null
+++ b/site/src/cut/server/convert.ts
@@ -0,0 +1,177 @@
+import { spawn } from "node:child_process";
+import { h264Encoder, runFfmpeg, sdrConvert, vtQuality, type RenderHandle } from "./exportPipeline";
+import { videoColorInfo, videoDimensions } from "./util";
+
+/**
+ * Re-wrapping one media file as an MP4 every player and every browser opens.
+ *
+ * Two shapes come out of the same call. A file whose streams already fit —
+ * H.264 picture, AAC sound — is remuxed: the packets are copied into the new
+ * container untouched, which costs a read and a write and loses nothing. A
+ * file whose picture is HEVC or ProRes, or whose sound is the raw PCM a phone
+ * and a camera write into QuickTime, is re-encoded, one stream at a time, so
+ * a .mov with H.264 picture and PCM sound only pays for its audio.
+ *
+ * The engine calls this on the Mac's own ffmpeg; the render worker calls it in
+ * the container. Both hand it a `RenderHandle`, which is what carries a cancel
+ * (killing the live process) and the rolling log an error message is cut from.
+ */
+
+/** Codecs the target container and the browsers Cut runs in both take. */
+const KEEPS_VIDEO = new Set(["h264"]);
+const KEEPS_AUDIO = new Set(["aac", "mp3"]);
+
+/** The quality tier a conversion encodes at — visually transparent for
+ * footage that is about to be edited, cut, and exported again. */
+const CONVERT_CRF = 20;
+
+export interface ConvertOutcome {
+ /** True when the picture was re-encoded; false when its packets were copied. */
+ transcodedVideo: boolean;
+ transcodedAudio: boolean;
+ /** The source was already the file this would produce, so nothing was
+ * written and `out` does not exist. */
+ unchanged?: boolean;
+ width?: number;
+ height?: number;
+}
+
+/** Containers that hold the target streams under the name people ask for. */
+const MP4_EXT = /\.(mp4|m4v)$/i;
+
+/** Whether a source is already what a conversion would produce, so the job is
+ * to leave it alone. */
+export const fitsAlready = (
+ file: string,
+ codecs: { video?: string; audio?: string },
+ work: { shrink: boolean; sdr: boolean }
+) =>
+ MP4_EXT.test(file) &&
+ !work.shrink &&
+ !work.sdr &&
+ (!codecs.video || KEEPS_VIDEO.has(codecs.video)) &&
+ (!codecs.audio || KEEPS_AUDIO.has(codecs.audio));
+
+/** The first video and audio stream's codec names, or undefined for a file
+ * that carries no such stream (or a probe that fails — the conversion then
+ * takes the re-encode path, which is correct for anything). */
+export function streamCodecs(file: string): Promise<{ video?: string; audio?: string }> {
+ return new Promise((resolve) => {
+ const p = spawn("ffprobe", [
+ "-v", "error",
+ "-show_entries", "stream=codec_type,codec_name",
+ "-of", "json",
+ file,
+ ]);
+ let out = "";
+ const timer = setTimeout(() => {
+ p.kill("SIGKILL");
+ resolve({});
+ }, 30_000);
+ timer.unref();
+ p.stdout.on("data", (d) => (out += d));
+ p.on("close", (code) => {
+ clearTimeout(timer);
+ if (code !== 0) return resolve({});
+ try {
+ const streams = (JSON.parse(out).streams ?? []) as {
+ codec_type?: string;
+ codec_name?: string;
+ }[];
+ resolve({
+ video: streams.find((s) => s.codec_type === "video")?.codec_name,
+ audio: streams.find((s) => s.codec_type === "audio")?.codec_name,
+ });
+ } catch {
+ resolve({});
+ }
+ });
+ p.on("error", () => {
+ clearTimeout(timer);
+ resolve({});
+ });
+ });
+}
+
+/**
+ * Convert `src` into an MP4 at `out`. `maxHeight` caps the picture's display
+ * height — the height the rest of Cut measures, with the container's rotation
+ * already applied — and forces a re-encode when the source is taller.
+ */
+export async function convertToMp4(
+ handle: RenderHandle,
+ src: string,
+ out: string,
+ opts: { maxHeight?: number; onProgress?: (seconds: number) => void } = {}
+): Promise<ConvertOutcome> {
+ const [codecs, dims] = await Promise.all([streamCodecs(src), videoDimensions(src)]);
+ if (!codecs.video && !codecs.audio) throw new Error("That file carries no video or audio.");
+
+ const cap = opts.maxHeight && opts.maxHeight > 0 ? Math.round(opts.maxHeight) : 0;
+ const shrink = !!(cap && dims && dims.height > cap);
+ const color = codecs.video ? await videoColorInfo(src) : null;
+ const sdr = sdrConvert(color);
+ const transcodedVideo = !!codecs.video && (!KEEPS_VIDEO.has(codecs.video) || shrink || !!sdr);
+ const transcodedAudio = !!codecs.audio && !KEEPS_AUDIO.has(codecs.audio);
+ if (fitsAlready(src, codecs, { shrink, sdr: !!sdr })) {
+ return {
+ transcodedVideo: false,
+ transcodedAudio: false,
+ unchanged: true,
+ ...(dims ? { width: dims.width, height: dims.height } : {}),
+ };
+ }
+
+ const video: string[] = [];
+ if (codecs.video) {
+ video.push("-map", "0:v:0");
+ if (!transcodedVideo) {
+ video.push("-c:v", "copy");
+ } else {
+ // Even dimensions: H.264 in 4:2:0 has no odd sizes, and the scale filter
+ // is where an odd source height would otherwise land.
+ const scale = shrink ? `scale=-2:${cap - (cap % 2)},` : "";
+ const chain = `${sdr}${scale}`.replace(/,$/, "");
+ if (chain) video.push("-vf", chain);
+ const enc = await h264Encoder();
+ video.push(
+ ...(enc === "libx264"
+ ? ["-c:v", "libx264", "-preset", "medium", "-crf", String(CONVERT_CRF)]
+ : ["-c:v", "h264_videotoolbox", "-q:v", String(vtQuality(CONVERT_CRF)), "-allow_sw", "1"]),
+ "-pix_fmt", "yuv420p"
+ );
+ }
+ }
+
+ const audio: string[] = [];
+ if (codecs.audio) {
+ audio.push("-map", "0:a:0");
+ audio.push(...(transcodedAudio ? ["-c:a", "aac", "-b:a", "192k"] : ["-c:a", "copy"]));
+ }
+
+ await runFfmpeg(
+ handle,
+ [
+ "-y",
+ "-i", src,
+ ...video,
+ ...audio,
+ // The index rides at the head of the file, so streamed playback starts
+ // on the first bytes — a clip previews while it is still uploading.
+ "-movflags", "+faststart",
+ out,
+ ],
+ opts.onProgress
+ );
+
+ const outDims = transcodedVideo ? await videoDimensions(out) : dims;
+ return {
+ transcodedVideo,
+ transcodedAudio,
+ ...(outDims ? { width: outDims.width, height: outDims.height } : {}),
+ };
+}
+
+/** The MP4 name a source file converts to: same stem, `.mp4` extension. */
+export const mp4NameFor = (fileName: string) =>
+ `${fileName.replace(/\.[^./\\]+$/, "") || "media"}.mp4`;
diff --git a/site/src/cut/server/exportPipeline.ts b/site/src/cut/server/exportPipeline.ts
index f009e8b6..ec770c98 100644
--- a/site/src/cut/server/exportPipeline.ts
+++ b/site/src/cut/server/exportPipeline.ts
@@ -215,7 +215,7 @@ export interface RenderHandle {
* it has no libx264 and `-preset`/`-crf` don't exist there; fall back to the
* always-present VideoToolbox hardware H.264 encoder. */
let h264EncoderCache: Promise<"libx264" | "h264_videotoolbox"> | null = null;
-function h264Encoder(): Promise<"libx264" | "h264_videotoolbox"> {
+export function h264Encoder(): Promise<"libx264" | "h264_videotoolbox"> {
return (h264EncoderCache ??= new Promise((resolve) => {
let out = "";
const proc = spawn("ffmpeg", ["-hide_banner", "-encoders"]);
@@ -227,7 +227,7 @@ function h264Encoder(): Promise<"libx264" | "h264_videotoolbox"> {
/** VideoToolbox constant quality (1–100, higher = better) from the CRF knob the
* presets carry (lower CRF = better). Maps the 19/24/30 tiers to ~66/57/46. */
-function vtQuality(crf: number) {
+export function vtQuality(crf: number) {
return Math.round(Math.max(35, Math.min(80, 100 - crf * 1.8)));
}
@@ -261,7 +261,7 @@ async function resolveMedia(
* when the matrix itself is BT.2020, or when it's untagged and the wide
* primaries/transfer tags are the only signal there is.
*/
-function sdrConvert(c: Awaited<ReturnType<typeof videoColorInfo>>) {
+export function sdrConvert(c: Awaited<ReturnType<typeof videoColorInfo>>) {
if (c == null) return "";
const matrix = c.matrix && c.matrix !== "unknown" ? c.matrix : null;
const wide =
diff --git a/site/src/cut/server/http/convert.ts b/site/src/cut/server/http/convert.ts
new file mode 100644
index 00000000..dd75ee01
--- /dev/null
+++ b/site/src/cut/server/http/convert.ts
@@ -0,0 +1,43 @@
+import { mkdtemp, readFile, rm, writeFile } from "node:fs/promises";
+import os from "node:os";
+import path from "node:path";
+import { convertToMp4, mp4NameFor } from "../convert";
+
+/**
+ * Convert media the caller supplies, for a project this engine does not store.
+ * A browser project's files live in the page, and a browser without a decoder
+ * for them has nothing to convert with — so the bytes come here, the Mac's
+ * ffmpeg rewrites them, and the MP4 goes back to the page that owns them.
+ * Nothing is kept: the temp directory goes with the response.
+ */
+export const convertApi = {
+ async create(req: Request) {
+ const tmp = await mkdtemp(path.join(os.tmpdir(), "cut-convert-"));
+ try {
+ const form = await req.formData();
+ const file = form.get("file");
+ if (!(file instanceof File)) {
+ return Response.json({ error: "file is required." }, { status: 400 });
+ }
+ const maxHeight = Number(form.get("maxHeight"));
+ const src = path.join(tmp, path.basename(file.name) || "source");
+ const out = path.join(tmp, mp4NameFor(path.basename(file.name) || "media"));
+ await writeFile(src, new Uint8Array(await file.arrayBuffer()));
+ const handle = { tmpDir: tmp, outPath: out, progress: 0, log: [] as string[] };
+ await convertToMp4(handle, src, out, {
+ maxHeight: Number.isFinite(maxHeight) && maxHeight > 0 ? maxHeight : undefined,
+ });
+ const bytes = await readFile(out);
+ return new Response(new Uint8Array(bytes), {
+ headers: { "Content-Type": "video/mp4", "Content-Length": String(bytes.length) },
+ });
+ } catch (e) {
+ return Response.json(
+ { error: e instanceof Error ? e.message : "Could not convert that file." },
+ { status: 500 }
+ );
+ } finally {
+ void rm(tmp, { recursive: true, force: true });
+ }
+ },
+};
diff --git a/site/src/cut/server/http/projects.ts b/site/src/cut/server/http/projects.ts
index 3a5a8d3c..3ba7ab9a 100644
--- a/site/src/cut/server/http/projects.ts
+++ b/site/src/cut/server/http/projects.ts
@@ -22,10 +22,11 @@ import {
sweepOrphanMedia,
writeProject,
} from "../projects";
+import { convertToMp4, mp4NameFor } from "../convert";
import { serveFileRange, wantsDownload } from "../serveFile";
import { importUrlToProject } from "../urlImport";
import { createTranscribeJob, getTranscribeJob, type TranscribeSpec } from "../transcribe";
-import { exists } from "../util";
+import { exists, uniqueName } from "../util";
const err = (message: string, status: number) => Response.json({ error: message }, { status });
const caught = (e: unknown, fallback: string, status = 500) =>
@@ -403,6 +404,35 @@ export const projectsApi = {
}
},
+ /** Convert a media file in this project to MP4 (H.264/AAC), remuxing when
+ * the streams already fit. The new file lands beside the original; swapping
+ * the asset over to it and dropping the old bytes is the client's call. */
+ async convert(req: Request, { id }: { id: string }) {
+ try {
+ if (!(await readProject(id))) return err("Project not found.", 404);
+ const body = (await req.json()) as { file?: string; maxHeight?: number };
+ if (!body.file) return err("file is required.", 400);
+ const src = mediaPath(id, body.file);
+ if (!(await exists(src))) return err("Media file missing from project.", 404);
+ const fileName = await uniqueName(mp4NameFor(body.file), (n) => mediaPath(id, n));
+ const outPath = mediaPath(id, fileName);
+ const handle = { tmpDir: "", outPath, progress: 0, log: [] as string[] };
+ const outcome = await convertToMp4(handle, src, outPath, {
+ maxHeight: typeof body.maxHeight === "number" ? body.maxHeight : undefined,
+ });
+ // Nothing was written for a file that already fits; the project keeps
+ // the one it has.
+ const made = outcome.unchanged ? { file: body.file, path: src } : { file: fileName, path: outPath };
+ return Response.json({
+ fileName: made.file,
+ duration: await probeDuration(made.path),
+ ...outcome,
+ });
+ } catch (e) {
+ return caught(e, "Could not convert that file.");
+ }
+ },
+
/** Report silent stretches in a media file's audio. */
async silence(req: Request, { id }: { id: string }) {
try {
diff --git a/site/src/cut/server/http/routes.ts b/site/src/cut/server/http/routes.ts
index 3b6aa2ef..32b1edf5 100644
--- a/site/src/cut/server/http/routes.ts
+++ b/site/src/cut/server/http/routes.ts
@@ -1,5 +1,6 @@
import { matchRouteTable } from "./match";
import { aiApi } from "./ai";
+import { convertApi } from "./convert";
import { engineApi } from "./engine";
import { exportApi } from "./export";
import { libraryApi } from "./library";
@@ -46,6 +47,7 @@ export const CUT_ROUTES: CutRoute[] = [
{ method: "GET", path: "/api/cut/projects/:id/transcribe", handler: (req, p) => projectsApi.transcribePoll(req, { id: p.id }) },
{ method: "POST", path: "/api/cut/projects/:id/image", handler: (req, p) => projectsApi.importImage(req, { id: p.id }) },
{ method: "POST", path: "/api/cut/projects/:id/freeze", handler: (req, p) => projectsApi.freeze(req, { id: p.id }) },
+ { method: "POST", path: "/api/cut/projects/:id/convert", handler: (req, p) => projectsApi.convert(req, { id: p.id }) },
{ method: "POST", path: "/api/cut/projects/:id/silence", handler: (req, p) => projectsApi.silence(req, { id: p.id }) },
{ method: "POST", path: "/api/cut/projects/:id/audio", handler: (req, p) => projectsApi.audio(req, { id: p.id }) },
{ method: "POST", path: "/api/cut/projects/:id/duplicate", handler: (req, p) => projectsApi.duplicate(req, { id: p.id }) },
@@ -74,6 +76,8 @@ export const CUT_ROUTES: CutRoute[] = [
{ method: "DELETE", path: "/api/cut/export/:jobId", handler: (req, p) => exportApi.cancel(req, { jobId: p.jobId }) },
{ method: "GET", path: "/api/cut/export/:jobId/file", handler: (req, p) => exportApi.file(req, { jobId: p.jobId }) },
+ { method: "POST", path: "/api/cut/convert", handler: (req) => convertApi.create(req) },
+
{ method: "POST", path: "/api/cut/stt", handler: (req) => sttApi.create(req) },
{ method: "GET", path: "/api/cut/stt/:jobId", handler: (req, p) => sttApi.status(req, { jobId: p.jobId }) },
diff --git a/site/src/cut/worker/convertJob.ts b/site/src/cut/worker/convertJob.ts
new file mode 100644
index 00000000..e5e5aecd
--- /dev/null
+++ b/site/src/cut/worker/convertJob.ts
@@ -0,0 +1,88 @@
+import { mkdtemp, rm } from "node:fs/promises";
+import os from "node:os";
+import path from "node:path";
+import type { RenderHandle } from "../server/exportPipeline";
+import { convertToMp4, mp4NameFor } from "../server/convert";
+import { probeDuration } from "../server/frames";
+import { prisma, registerObject, unregisterObjects, type ClaimedJob } from "./db";
+import { dedupeName } from "./importUrlJob";
+import { deleteObjects, downloadToFile, mediaKey, uploadFile } from "./r2";
+
+/** What a convert job records in CutRenderJob.result — the same shape the
+ * engine's synchronous convert route returns. */
+export interface ConvertResult {
+ fileName: string;
+ duration: number;
+ width?: number;
+ height?: number;
+ transcodedVideo: boolean;
+ transcodedAudio: boolean;
+ /** The project's file was already what this would produce. */
+ unchanged?: boolean;
+}
+
+/**
+ * Run one convert job: pull the project's media file out of R2, rewrite it as
+ * MP4 with the same code the engine runs on a Mac, and land the result in the
+ * project's media prefix under a name deduped against its existing objects.
+ * The original is left alone — the client swaps its asset over and deletes
+ * what it no longer points at.
+ */
+export async function runConvertJob(
+ job: ClaimedJob,
+ handle: RenderHandle,
+ isCanceled: () => boolean
+): Promise<ConvertResult> {
+ const { file, maxHeight } = (job.spec ?? {}) as { file?: string; maxHeight?: number };
+ if (!file) throw new Error("Convert job has no file.");
+ const projectId = job.projectId;
+ if (!projectId) throw new Error("Convert job has no project.");
+
+ const tmp = await mkdtemp(path.join(os.tmpdir(), "cut-convert-"));
+ handle.tmpDir = tmp;
+ try {
+ const src = path.join(tmp, path.basename(file));
+ await downloadToFile(mediaKey(job.userId, projectId, file), src);
+ if (isCanceled()) throw new Error("Conversion canceled.");
+
+ const rows = await prisma.cutMediaObject.findMany({
+ where: { projectId, kind: "media" },
+ select: { fileName: true },
+ });
+ const fileName = dedupeName(mp4NameFor(file), new Set(rows.map((r) => r.fileName)));
+ const out = path.join(tmp, fileName);
+ handle.outPath = out;
+
+ const total = await probeDuration(src);
+ const outcome = await convertToMp4(handle, src, out, {
+ maxHeight,
+ onProgress: (seconds) => {
+ if (total > 0) handle.progress = Math.min(0.99, seconds / total);
+ },
+ });
+ if (isCanceled()) throw new Error("Conversion canceled.");
+ // Already the file this would produce: the object in R2 stays as it is.
+ if (outcome.unchanged) return { fileName: file, duration: total, ...outcome };
+
+ const key = mediaKey(job.userId, projectId, fileName);
+ try {
+ const bytes = await uploadFile(key, out, "video/mp4");
+ await registerObject({
+ userId: job.userId,
+ projectId,
+ r2Key: key,
+ fileName,
+ mime: "video/mp4",
+ bytes,
+ kind: "media",
+ });
+ } catch (err) {
+ await unregisterObjects(job.userId, [key]).catch(() => {});
+ await deleteObjects([key]);
+ throw err;
+ }
+ return { fileName, duration: await probeDuration(out), ...outcome };
+ } finally {
+ void rm(tmp, { recursive: true, force: true });
+ }
+}
diff --git a/site/src/cut/worker/importUrlJob.ts b/site/src/cut/worker/importUrlJob.ts
index bb5bab26..577b6d22 100644
--- a/site/src/cut/worker/importUrlJob.ts
+++ b/site/src/cut/worker/importUrlJob.ts
@@ -14,7 +14,7 @@ export interface ImportUrlResult {
/** First variant of `base` (stem, stem-1, stem-2, …) not already `taken` —
* the engine's on-disk dedupe scheme, run against the project's media rows. */
-function dedupeName(base: string, taken: Set<string>): string {
+export function dedupeName(base: string, taken: Set<string>): string {
const ext = path.extname(base);
const stem = base.slice(0, base.length - ext.length) || "media";
let name = base;
diff --git a/site/src/cut/worker/main.ts b/site/src/cut/worker/main.ts
index d46405dc..8f38186e 100644
--- a/site/src/cut/worker/main.ts
+++ b/site/src/cut/worker/main.ts
@@ -3,13 +3,14 @@ import type { RenderHandle } from "../server/exportPipeline";
import { prisma, type ClaimedJob } from "./db";
import { overlayKeysOf, runExportJob } from "./exportJob";
import { runHlsJob } from "./hlsJob";
+import { runConvertJob } from "./convertJob";
import { runImportUrlJob } from "./importUrlJob";
import { runTurnJob } from "./turnJob";
import { describeRuntime, installHeadlessRuntime } from "../lib/headless/runtime";
import { deleteObjects } from "./r2";
// The cloud render worker: a headless loop that claims CutRenderJob rows the
-// hosted API queues (export, preview, import_url), executes them with the
+// hosted API queues (export, preview, import_url, convert), executes them with the
// same pipeline code the local engine runs, and writes progress and results
// back to the row the client polls. Scale is horizontal: one job per process,
// several processes — the atomic claim keeps them apart.
@@ -57,7 +58,7 @@ const sleep = (ms: number) => new Promise<void>((r) => setTimeout(r, ms));
/** The kinds someone is watching happen: an export, a URL import, or a chat
* turn has a progress surface on screen, while a hover proxy and a share card
* are background polish nobody is waiting on. */
-const WATCHED_KINDS = ["export", "import_url", "agent_turn"];
+const WATCHED_KINDS = ["export", "import_url", "convert", "agent_turn"];
/** Atomically claim the next queued job: the updateMany's state guard makes
* exactly one worker win each row, so replicas never double-run a job.
@@ -161,6 +162,12 @@ async function runJob(job: ClaimedJob): Promise<void> {
where: { id: job.id, state: "running" },
data: { state: "done", progress: 1, result: result as unknown as Prisma.InputJsonValue },
});
+ } else if (job.kind === "convert") {
+ const result = await runConvertJob(job, handle, () => entry.canceled);
+ await prisma.cutRenderJob.updateMany({
+ where: { id: job.id, state: "running" },
+ data: { state: "done", progress: 1, result: result as unknown as Prisma.InputJsonValue },
+ });
} else if (job.kind === "agent_turn") {
const result = await runTurnJob(job, handle, () => entry.canceled);
await prisma.cutRenderJob.updateMany({