Open source CapCut alternative.
TypeScript
feat(site): build playable copies of library videos [rebuild]
David Leaef53527c1e1
diff --git a/site/src/cut/lib/backend/browser/library.ts b/site/src/cut/lib/backend/browser/library.tsindex dcb07171..13d5502a 100644--- a/site/src/cut/lib/backend/browser/library.ts+++ b/site/src/cut/lib/backend/browser/library.ts@@ -55,6 +55,9 @@ type StoredAsset = {/** The source's cover image, stored beside the media and served by the same* route — an import from a site that publishes one carries it. */posterFile?: string;+ /** The playable copy of a master this browser cannot decode (a ProRes+ * file), built beside it; what the shelf's cards and viewer play. */+ proxyFile?: string;/** A linked item's identity, computed by the page before the file was* shelved; a LUT's row also says what kind of table it holds. */contentKey?: string;@@ -137,6 +140,7 @@ async function list(): Promise<Response> {for (const name of new Set([...idx.assets.map((a) => a.fileName),...idx.assets.flatMap((a) => (a.posterFile ? [a.posterFile] : [])),+ ...idx.assets.flatMap((a) => (a.proxyFile ? [a.proxyFile] : [])),...idx.templates.flatMap((t) => t.media.map((m) => m.fileName)),])) {await register(name);@@ -248,6 +252,7 @@ function takeAssets(idx: LibraryIndex, ids: ReadonlySet<string>): string[] {if (!ids.has(a.id)) return true;files.push(a.fileName);if (a.posterFile) files.push(a.posterFile);+ if (a.proxyFile) files.push(a.proxyFile);return false;});return files;@@ -286,6 +291,56 @@ async function removeAsset(id: string): Promise<Response> {}}+/**+ * Build the playable copy of a video this browser cannot decode (a ProRes+ * master) beside it, and name it on the asset: in this page when it has a+ * 10-bit encoder, else on the Mac's engine when the app is there. With+ * neither, the ask fails and says so.+ */+async function makeProxy(req: Request, id: string): Promise<Response> {+ try {+ const { maxHeight, crf } = (await req.json()) as { maxHeight?: number; crf?: number };+ if (!Number.isFinite(maxHeight) || !Number.isFinite(crf)) return err("maxHeight and crf are required.", 400);+ const asset = (await readIndex()).assets.find((a) => a.id === id);+ if (!asset) return err("Library asset not found.", 404);+ if (asset.type !== "video") return err("Only a video takes a playable copy.", 400);+ const dir = await store.libraryMediaDir(true);+ if (!dir) return err("Browser storage is unavailable.", 500);+ if (asset.proxyFile && (await store.readFileAt(dir, asset.proxyFile))) return json(asset);+ const master = await store.readFileAt(dir, asset.fileName);+ if (!master) return err("Media file not found.", 404);++ // Loaded on the ask: the encoder pulls in the decoders and the muxer.+ const { encodeProxyInPage, proxyNameFor, proxyOnTheMac } = await import("../../proxyEncode");+ const { probeMediaColor } = await import("../../mediaRead");+ const { code } = await probeMediaColor(master);+ const from = { matrix: code.matrix, fullRange: code.fullRange };+ let fileName = (await encodeProxyInPage(master, from, dir, asset.fileName, maxHeight!, () => {}))?.fileName;+ if (!fileName) {+ const blob = await proxyOnTheMac(async () => master, asset.fileName, maxHeight!, crf!);+ if (!blob) return err("This browser can't make a playable copy of this video. Open the Donkey app to make one.", 422);+ fileName = await store.saveLibraryMedia(blob, proxyNameFor(asset.fileName));+ }+ const landed = fileName;+ try {+ // The asset may have been deleted while the copy was built.+ const updated = await mutateIndex((idx) => {+ const live = idx.assets.find((a) => a.id === id);+ if (!live) throw new Error("Library asset not found.");+ live.proxyFile = landed;+ return live;+ });+ await register(landed);+ return json(updated);+ } catch (e) {+ await dropFiles([landed]);+ throw e;+ }+ } catch (e) {+ return caught(e, "Could not make the playable copy.");+ }+}+async function move(req: Request): Promise<Response> {try {const { id, folderId } = (await req.json()) as {@@ -714,6 +769,9 @@ export async function dispatchLibraryRoute(return null;}+ // /library/:id/proxy+ if (rest.length === 2 && rest[1] === "proxy" && method === "POST") return makeProxy(req(), rest[0]);+// /library/:idif (rest.length === 1 && method === "DELETE") return removeAsset(rest[0]);if (rest.length === 1 && method === "PUT") return renameAsset(req(), rest[0]);diff --git a/site/src/cut/lib/engineFeatures.ts b/site/src/cut/lib/engineFeatures.tsindex a63f16a0..929e46f8 100644--- a/site/src/cut/lib/engineFeatures.ts+++ b/site/src/cut/lib/engineFeatures.ts@@ -4,6 +4,6 @@* hands an engine work an older app would silently drop. A build from before* the list existed answers with none.*/-export const ENGINE_FEATURES = ["export.range", "export.name", "export.prores4444", "color.v2", "media.proxy", "export.hdr", "doc.timelines", "doc.timelineAspect", "export.loudness", "export.stems", "export.sound"] as const;+export const ENGINE_FEATURES = ["export.range", "export.name", "export.prores4444", "color.v2", "media.proxy", "library.proxy", "export.hdr", "doc.timelines", "doc.timelineAspect", "export.loudness", "export.stems", "export.sound"] as const;export type EngineFeature = (typeof ENGINE_FEATURES)[number];diff --git a/site/src/cut/lib/library.ts b/site/src/cut/lib/library.tsindex 34160f1f..09e512f0 100644--- a/site/src/cut/lib/library.ts+++ b/site/src/cut/lib/library.ts@@ -75,6 +75,10 @@ export interface LibraryAsset {fileName: string;/** Uploaded source retained when playback needs conversion. */originalFile?: string;+ /** The playable copy of a master the browser cannot decode (a ProRes+ * file): what the shelf's cards and viewer play. `fileName` stays the+ * master, which a project copies. */+ proxyFile?: string;name: string;type: AssetType;duration: number;@@ -170,6 +174,11 @@ export const libraryMediaUrl = (fileName: string, residency: Residency) => {return libraryRouteUrl(fileName, residency);};+/** The file a card or the viewer plays: the playable copy of a master the+ * browser cannot decode, else the file itself. A project copies the master. */+export const libraryPlaybackUrl = (a: Pick<LibraryAsset, "fileName" | "proxyFile" | "residency">) =>+ libraryMediaUrl(a.proxyFile ?? a.fileName, a.residency);+/** Mint edge URLs for everything a cloud listing names — media, covers, and* the files templates draw from. Best-effort: a shelf reads through the route* when this fails. */@@ -177,7 +186,7 @@ async function mintCloudMediaUrls(shelf: LibraryData): Promise<void> {const files = [...new Set([- ...shelf.assets.flatMap((a) => [a.fileName, a.posterFile]),+ ...shelf.assets.flatMap((a) => [a.fileName, a.posterFile, a.proxyFile]),...shelf.templates.flatMap((t) => t.media.map((m) => m.fileName)),].filter((f): f is string => !!f),),diff --git a/site/src/cut/lib/librarySharing.ts b/site/src/cut/lib/librarySharing.tsindex 7646688b..7318a3b9 100644--- a/site/src/cut/lib/librarySharing.ts+++ b/site/src/cut/lib/librarySharing.ts@@ -26,6 +26,8 @@ export type SharedLibraryAsset = {width?: number;height?: number;hasPoster?: boolean;+ /** Whether the asset has a playable copy of an undecodable master. */+ hasProxy?: boolean;};export type SharedLibraryPage = {name: string;diff --git a/site/src/cut/server/cloud/library.ts b/site/src/cut/server/cloud/library.tsindex 78098cb8..3a7f5be2 100644--- a/site/src/cut/server/cloud/library.ts+++ b/site/src/cut/server/cloud/library.ts@@ -21,6 +21,8 @@ import { MEDIA_REDIRECT_HEADERS, mediaObjectUrl, mediaUrlLifetime } from "./mediimport { getProject, takenMediaNames } from "./projects";import { copy, del, head, libraryKey, presignPut, projectMediaKey } from "./r2";import { addUsage, quotaCheck } from "./usage";+import { renderJobCheck } from "./limits";+import { wakeRenderWorker } from "./wake";import { libraryTypeOf } from "@/cut/lib/libraryFileType";import { itemName } from "@/cut/lib/itemName";import type { AssetType } from "@/cut/lib/types";@@ -29,12 +31,22 @@ import { caught, decodeFileParam, dedupeName, err, HttpResponseError, inspiratio/** Cap on one signed-URL batch, matching the project media batch. */const PRESIGN_GET_BATCH_MAX = 500;+/** The one job that builds an asset's playable copy, so a second ask joins it. */+export const libraryProxyJobId = (assetId: string) => `library-proxy-${assetId}`;++/** The objects under this account's library prefix: its files, and the+ * playable copies (kind "proxy", no project) built beside them. */+const LIBRARY_PREFIX_OBJECTS = { projectId: null, kind: { in: ["library", "proxy"] } };+/** Descriptive fields the engine derives with ffprobe; the cloud stores them on* the row, supplied by the client (which probed in the browser) or copied from* the source project doc. */interface AssetMeta {name?: string;originalFile?: string;+ /** File name of the playable copy of an undecodable master, a quota-exempt+ * object (kind "proxy") under this account's library prefix. */+ proxyFile?: string;/** The short name the titling model read off the clip itself, standing in* for the file's own name wherever the asset is shown. Written once, by* cloud/clipTitle.ts. */@@ -89,7 +101,7 @@ type MediaObjectRow = {async function takenLibraryNames(userId: string): Promise<Set<string>> {const rows = await prisma.cutMediaObject.findMany({- where: { userId, kind: "library" },+ where: { userId, ...LIBRARY_PREFIX_OBJECTS },select: { fileName: true },});return new Set(rows.map((r) => r.fileName));@@ -104,6 +116,7 @@ export function assetView(id: row.id,fileName: obj.fileName,...(meta.originalFile ? { originalFile: meta.originalFile } : {}),+ ...(meta.proxyFile ? { proxyFile: meta.proxyFile } : {}),name: meta.name ?? obj.fileName,type: meta.type ?? libraryTypeOf(obj.fileName) ?? "video",duration: meta.duration ?? 0,@@ -236,9 +249,15 @@ export async function deleteLibraryAssetCascade(const original = originalName? await prisma.cutMediaObject.findFirst({ where: { userId, kind: "library", fileName: originalName } }): null;- const objects = [obj, poster, original].filter((o): o is NonNullable<typeof o> => !!o);+ // The playable copy is derived from this asset alone, so it leaves too.+ const proxyName = ((asset.meta ?? {}) as AssetMeta).proxyFile;+ const proxy = proxyName+ ? await prisma.cutMediaObject.findFirst({ where: { userId, projectId: null, kind: "proxy", fileName: proxyName } })+ : null;+ const objects = [obj, poster, original, proxy].filter((o): o is NonNullable<typeof o> => !!o);+ // An exempt object never counted toward usage, so it frees nothing.const freed = objects- .filter((o) => o.uploadState === "complete")+ .filter((o) => o.uploadState === "complete" && !o.quotaExempt).reduce((n, o) => n + Number(o.bytes), 0);await prisma.$transaction(async (tx) => {if (opts?.tombstone) {@@ -680,6 +699,43 @@ export const libraryCloud = {}},+ /** Queue the playable copy of a library video the browser cannot decode.+ * A row that already names one answers with itself, and a job already on+ * its way answers with that job. */+ async proxy(userId: string, id: string) {+ try {+ const asset = await prisma.cutLibraryAsset.findFirst({ where: { id, userId, deletedAt: null } });+ if (!asset) return err("Library asset not found.", 404);+ const obj = await prisma.cutMediaObject.findFirst({ where: { id: asset.mediaObjectId, userId } });+ if (!obj) return err("Library asset not found.", 404);+ const view = assetView(asset, obj);+ if (view.type !== "video") return err("Only a video takes a playable copy.", 400);+ if (view.proxyFile) return Response.json(view);+ const jobId = libraryProxyJobId(id);+ const existing = await prisma.cutRenderJob.findFirst({ where: { id: jobId, userId } });+ if (existing && (existing.state === "queued" || existing.state === "running")) {+ wakeRenderWorker();+ return Response.json({ jobId });+ }+ const capped = await renderJobCheck(userId);+ if (capped) return capped;+ const spec = { target: "library", assetId: id } as Prisma.InputJsonValue;+ if (existing) {+ // A finished or failed run goes again under the same id.+ await prisma.cutRenderJob.updateMany({+ where: { id: jobId, userId },+ data: { state: "queued", progress: 0, error: null, claimedAt: null, spec },+ });+ } else {+ await prisma.cutRenderJob.create({ data: { id: jobId, userId, projectId: null, kind: "proxy", spec } });+ }+ wakeRenderWorker();+ return Response.json({ jobId });+ } catch (e) {+ return caught(e, "Could not make the playable copy.");+ }+ },+async remove(userId: string, id: string) {try {// Idempotent: a delete replayed from the iOS app's journal after the@@ -714,7 +770,7 @@ export const libraryCloud = {? await prisma.cutMediaObject.findMany({where: {userId,- kind: "library",+ ...LIBRARY_PREFIX_OBJECTS,uploadState: "complete",fileName: { in: wanted },},diff --git a/site/src/cut/server/cloud/librarySharing.ts b/site/src/cut/server/cloud/librarySharing.tsindex 151b66fe..7ba78f9c 100644--- a/site/src/cut/server/cloud/librarySharing.ts+++ b/site/src/cut/server/cloud/librarySharing.ts@@ -101,6 +101,7 @@ export function createLibrarySharing(return [{ id: v.id, name: v.title || v.name, fileName: v.fileName, type: v.type, duration: v.duration,...(v.width && v.height ? { width: v.width, height: v.height } : {}),...(v.posterFile ? { hasPoster: true } : {}),+ ...(v.proxyFile ? { hasProxy: true } : {}),}];});const body: SharedLibraryPage = {@@ -125,12 +126,15 @@ export function createLibrarySharing(file: z.string().min(1).max(512).optional(),download: z.enum(["1"]).optional(),poster: z.enum(["1"]).optional(),+ proxy: z.enum(["1"]).optional(),resolve: z.enum(["1"]).optional(),}).safeParse(Object.fromEntries(new URL(req.url).searchParams));if (!query.success) return err("Invalid media request.", 400);let folderId: string | null;let fileName: string;let mediaObjectId: string | undefined;+ // The playable copy is an object of kind "proxy" beside the library's files.+ let proxyFile: string | undefined;if (query.data.template) {if (query.data.poster || target.kind !== "folder" || query.data.template !== assetId) return err("Not found.", 404);const row = await db.cutTemplate.findFirst({ where: { id: assetId, userId: share.userId } });@@ -151,6 +155,10 @@ export function createLibrarySharing(const posterFile = assetView(row, { fileName: "" }).posterFile;if (!posterFile) return err("Not found.", 404);fileName = posterFile;+ } else if (query.data.proxy) {+ proxyFile = assetView(row, { fileName: "" }).proxyFile;+ if (!proxyFile) return err("Not found.", 404);+ fileName = proxyFile;} else {mediaObjectId = row.mediaObjectId;fileName = "";@@ -162,7 +170,8 @@ export function createLibrarySharing(select: { id: true, name: true, parentId: true } })))) return err("Not found.", 404);}const object = await db.cutMediaObject.findFirst({- where: { userId: share.userId, kind: "library", uploadState: "complete",+ where: { userId: share.userId, kind: proxyFile ? "proxy" : "library", uploadState: "complete",+ ...(proxyFile ? { projectId: null } : {}),...(mediaObjectId ? { id: mediaObjectId } : { fileName }) },});if (!object) return err("Not found.", 404);diff --git a/site/src/cut/server/cloud/routes.ts b/site/src/cut/server/cloud/routes.tsindex 43f48a11..4f45a571 100644--- a/site/src/cut/server/cloud/routes.ts+++ b/site/src/cut/server/cloud/routes.ts@@ -97,6 +97,7 @@ const CUT_CLOUD_ROUTES: CloudRoute[] = [{ method: "PUT", path: "/api/cut-cloud/library/folders/:id", handler: (r, u, p) => libraryCloud.updateFolder(u, p.id, r) },{ method: "DELETE", path: "/api/cut-cloud/library/folders/:id", handler: (_r, u, p) => libraryCloud.deleteFolder(u, p.id) },{ method: "GET", path: "/api/cut-cloud/library/media/:file", handler: (r, u, p) => libraryCloud.serveMedia(u, p.file, wantsDownload(r)) },+ { method: "POST", path: "/api/cut-cloud/library/:id/proxy", handler: (_r, u, p) => libraryCloud.proxy(u, p.id) },{ method: "PUT", path: "/api/cut-cloud/library/:id", handler: (r, u, p) => libraryCloud.updateMeta(u, p.id, r) },{ method: "DELETE", path: "/api/cut-cloud/library/:id", handler: (_r, u, p) => libraryCloud.remove(u, p.id) },diff --git a/site/src/cut/server/http/library.ts b/site/src/cut/server/http/library.tsindex 28d52062..9420a06a 100644--- a/site/src/cut/server/http/library.ts+++ b/site/src/cut/server/http/library.ts@@ -10,6 +10,7 @@ import {listFolders,listLibrary,listTemplates,+ makeLibraryProxy,moveItem,removeAsset,updateFolder,@@ -104,6 +105,19 @@ export const libraryApi = {}},+ /** Build the playable copy of a video the browser cannot decode. */+ async proxy(req: Request, { id }: { id: string }) {+ try {+ const body = (await req.json()) as { maxHeight?: number; crf?: number };+ if (!Number.isFinite(body.maxHeight) || !Number.isFinite(body.crf)) {+ return err("maxHeight and crf are required.", 400);+ }+ return Response.json(await makeLibraryProxy(id, { maxHeight: body.maxHeight!, crf: body.crf! }));+ } catch (e) {+ return caught(e, "Could not make the playable copy.");+ }+ },+async rename(req: Request, { id }: { id: string }) {try {const { name } = (await req.json()) as { name?: string };diff --git a/site/src/cut/server/http/routes.ts b/site/src/cut/server/http/routes.tsindex 732a7a88..1b68f7f5 100644--- a/site/src/cut/server/http/routes.ts+++ b/site/src/cut/server/http/routes.ts@@ -91,6 +91,7 @@ export const CUT_ROUTES: CutRoute[] = [{ method: "PUT", path: "/api/cut/library/folders/:id", handler: (req, p) => libraryApi.updateFolder(req, { id: p.id }) },{ method: "DELETE", path: "/api/cut/library/folders/:id", handler: (req, p) => libraryApi.deleteFolder(req, { id: p.id }) },{ method: "GET", path: "/api/cut/library/media/:file", handler: (req, p) => libraryApi.serveMedia(req, { file: p.file }) },+ { method: "POST", path: "/api/cut/library/:id/proxy", handler: (req, p) => libraryApi.proxy(req, { id: p.id }) },{ method: "PUT", path: "/api/cut/library/:id", handler: (req, p) => libraryApi.rename(req, { id: p.id }) },{ method: "DELETE", path: "/api/cut/library/:id", handler: (req, p) => libraryApi.remove(req, { id: p.id }) },diff --git a/site/src/cut/server/library.ts b/site/src/cut/server/library.tsindex 639590f6..83d5fd8b 100644--- a/site/src/cut/server/library.ts+++ b/site/src/cut/server/library.ts@@ -10,6 +10,7 @@ import { isLinkedAssetType, type AssetType } from "@/cut/lib/types";import { cutDataRoot } from "./dataDir";import { assertLocalRuntime } from "./local-only";import { mediaPath as projectMediaPath, readProject } from "./projects";+import { makeProxy, proxyNameFor } from "./proxy";import { templateExtras } from "./templateExtras";import { exists, uniqueName, writeJsonAtomic } from "./util";@@ -39,6 +40,10 @@ export interface LibraryAsset extends LinkedMeta {fileName: string;/** Uploaded source retained when playback needs conversion. */originalFile?: string;+ /** The playable copy of a master the browser cannot decode (a ProRes+ * file): what the shelf's cards and viewer play. `fileName` stays the+ * master, which a project copies. */+ proxyFile?: string;name: string;type: AssetType;duration: number;@@ -416,6 +421,7 @@ function takeAssets(idx: LibraryIndex, ids: ReadonlySet<string>): string[] {files.push(a.fileName);if (a.posterFile) files.push(a.posterFile);if (a.originalFile) files.push(a.originalFile);+ if (a.proxyFile) files.push(a.proxyFile);return false;});return files;@@ -445,6 +451,41 @@ export async function removeAsset(id: string) {await removeFiles(files);}+/** The copies being built, by asset id, so a second ask joins the first. */+const proxyBuilds = new Map<string, Promise<LibraryAsset>>();++/** Build the playable copy of a library video the browser cannot decode (a+ * ProRes master) beside it, with the proxy code the project preview uses, and+ * name it on the asset. An asset that already has one comes back as it is. */+export function makeLibraryProxy(id: string, opts: { maxHeight: number; crf: number }): Promise<LibraryAsset> {+ const running = proxyBuilds.get(id);+ if (running) return running;+ const build = (async () => {+ const asset = (await readIndex()).assets.find((a) => a.id === id);+ if (!asset) throw new Error("Library asset not found.");+ if (asset.type !== "video") throw new Error("Only a video takes a playable copy.");+ if (asset.proxyFile && (await exists(libMediaPath(asset.proxyFile)))) return asset;+ const fileName = await freeName(proxyNameFor(asset.fileName));+ const out = libMediaPath(fileName);+ try {+ const handle = { tmpDir: "", outPath: out, progress: 0, log: [] as string[] };+ await makeProxy(handle, libMediaPath(asset.fileName), out, opts);+ // The asset may have been deleted while the copy was built.+ return await mutateIndex((idx) => {+ const live = idx.assets.find((a) => a.id === id);+ if (!live) throw new Error("Library asset not found.");+ live.proxyFile = fileName;+ return live;+ });+ } catch (error) {+ await rm(out, { force: true });+ throw error;+ }+ })().finally(() => proxyBuilds.delete(id));+ proxyBuilds.set(id, build);+ return build;+}+export function getAsset(id: string) {return readIndex().then((idx) => idx.assets.find((a) => a.id === id));}diff --git a/site/src/cut/worker/libraryProxyJob.test.ts b/site/src/cut/worker/libraryProxyJob.test.tsnew file mode 100644index 00000000..75e7c47c--- /dev/null+++ b/site/src/cut/worker/libraryProxyJob.test.ts@@ -0,0 +1,82 @@+import { describe, expect, mock, test } from "bun:test";+import { writeFile } from "node:fs/promises";+import type { Prisma } from "@/generated/prisma/client";+import type { prisma } from "@/lib/prisma";+import { runLibraryProxyJob, type LibraryProxyIO } from "./libraryProxyJob";++type Row = { id: string; userId: string; mediaObjectId: string; folderId: string | null; deletedAt: Date | null; meta: unknown; createdAt: Date };++function harness(taken: string[] = []) {+ const row: Row = {+ id: "asset", userId: "owner", mediaObjectId: "master", folderId: "folder", deletedAt: null,+ meta: { name: "IMG_5388.MOV", type: "video", duration: 21.8, width: 1080, height: 1920, title: "Beach" },+ createdAt: new Date(0),+ };+ const media = { id: "master", fileName: "IMG_5388.MOV", r2Key: "cut/owner/library/IMG_5388.MOV" };+ const assetRead = mock(async (_args: unknown) => { void _args; return row as Row | null; });+ const takenRead = mock(async (_args: unknown) => { void _args; return taken.map((fileName) => ({ fileName })); });+ const update = mock(async ({ data }: { data: { meta: unknown } }) => ({ ...row, meta: data.meta }));+ const liveRead = mock(async (_args: unknown) => { void _args; return row as Row | null; });+ const tx = { cutLibraryAsset: { findFirst: liveRead, update } };+ const io = {+ db: {+ cutLibraryAsset: { findFirst: assetRead },+ cutMediaObject: { findFirst: mock(async () => media), findMany: takenRead },+ } as unknown as typeof prisma,+ download: mock(async (_key: string, file: string) => { await writeFile(file, "master"); }),+ upload: mock(async (_key: string, _file: string, _mime: string) => { void _file; void _mime; return 7; }),+ remove: mock(async (_keys: string[]) => { void _keys; }),+ make: mock(async (_handle: unknown, _src: string, out: string, opts: { maxHeight: number; crf: number; onProgress?: (s: number) => void }) => {+ opts.onProgress?.(1);+ await writeFile(out, "proxy");+ return { sizeBytes: 5, width: 608, height: 1080 };+ }),+ duration: mock(async () => 21.8),+ settings: mock(async () => ({ proxyMaxHeight: 1080, proxyCrf: 20 })),+ transact: async <T>(run: (tx: Prisma.TransactionClient) => Promise<T>) => run(tx as unknown as Prisma.TransactionClient),+ register: mock(async (_tx: Prisma.TransactionClient, object: { fileName: string }) => object.fileName),+ } satisfies LibraryProxyIO;+ const job = { id: "library-proxy-asset", userId: "owner", projectId: null, kind: "proxy", outName: null, spec: { target: "library", assetId: "asset" } };+ const handle = { tmpDir: "", outPath: "", progress: 0, log: [] as string[] };+ const run = (canceled = () => false) => runLibraryProxyJob(job, handle, canceled, io);+ return { run, io, row, update, liveRead, takenRead, handle };+}++describe("library proxy worker", () => {+ // A ProRes master stays the asset's file; the playable copy lands beside it+ // as an exempt object and the row names it, keeping everything else it says.+ test("builds the copy from the master and records it on the row", async () => {+ const h = harness();+ const asset = await h.run();+ expect(asset).toMatchObject({ id: "asset", fileName: "IMG_5388.MOV", proxyFile: "IMG_5388.proxy.mp4", title: "Beach" });+ expect(h.io.download.mock.calls[0][0]).toBe("cut/owner/library/IMG_5388.MOV");+ expect(h.io.make.mock.calls[0][3]).toMatchObject({ maxHeight: 1080, crf: 20 });+ expect(h.io.upload.mock.calls[0][0]).toBe("cut/owner/library/IMG_5388.proxy.mp4");+ expect(h.io.register.mock.calls[0][1]).toMatchObject({+ userId: "owner", projectId: null, fileName: "IMG_5388.proxy.mp4", kind: "proxy", mime: "video/mp4", bytes: 7,+ });+ expect(h.update.mock.calls[0][0].data.meta).toMatchObject({ title: "Beach", proxyFile: "IMG_5388.proxy.mp4" });+ expect(h.handle.progress).toBeGreaterThan(0);+ });++ test("dedupes the copy's name against the account's library files", async () => {+ const h = harness(["IMG_5388.proxy.mp4"]);+ expect((await h.run()).proxyFile).toBe("IMG_5388.proxy-1.mp4");+ expect(h.takenRead.mock.calls[0][0]).toMatchObject({ where: { userId: "owner", projectId: null, kind: { in: ["library", "proxy"] } } });+ });++ test("a row that already names its copy returns without building", async () => {+ const h = harness();+ h.row.meta = { ...(h.row.meta as object), proxyFile: "IMG_5388.proxy.mp4" };+ expect((await h.run()).proxyFile).toBe("IMG_5388.proxy.mp4");+ expect(h.io.download).not.toHaveBeenCalled();+ });++ test("an asset deleted while the copy was built takes the copy with it", async () => {+ const h = harness();+ h.liveRead.mockResolvedValue(null);+ await expect(h.run()).rejects.toThrow("deleted");+ expect(h.io.remove.mock.calls[0][0]).toEqual(["cut/owner/library/IMG_5388.proxy.mp4"]);+ expect(h.update).not.toHaveBeenCalled();+ });+});diff --git a/site/src/cut/worker/libraryProxyJob.ts b/site/src/cut/worker/libraryProxyJob.tsnew file mode 100644index 00000000..038ec0dd--- /dev/null+++ b/site/src/cut/worker/libraryProxyJob.ts@@ -0,0 +1,116 @@+import { mkdtemp, rm } from "node:fs/promises";+import os from "node:os";+import path from "node:path";+import type { Prisma } from "@/generated/prisma/client";+import { getGlobalSetting } from "@/lib/config/effective";+import type { RenderHandle } from "../server/exportPipeline";+import { makeProxy, proxyNameFor } from "../server/proxy";+import { probeDuration } from "../server/frames";+import { assetView } from "../server/cloud/library";+import { dedupeName } from "../server/cloud/util";+import type { LibraryAsset } from "../server/library";+import { prisma, registerObjectIn, storageTransaction, type ClaimedJob } from "./db";+import { deleteObjects, downloadToFile, libraryKey, uploadFile } from "./r2";++/** The edges a library proxy job crosses, stubbed by its test. */+export interface LibraryProxyIO {+ db: typeof prisma;+ download: typeof downloadToFile;+ upload: typeof uploadFile;+ remove: typeof deleteObjects;+ make: typeof makeProxy;+ duration: typeof probeDuration;+ settings: () => Promise<{ proxyMaxHeight: number; proxyCrf: number }>;+ transact: <T>(run: (tx: Prisma.TransactionClient) => Promise<T>) => Promise<T>;+ register: typeof registerObjectIn;+}++const defaultIO: LibraryProxyIO = {+ db: prisma,+ download: downloadToFile,+ upload: uploadFile,+ remove: deleteObjects,+ make: makeProxy,+ duration: probeDuration,+ settings: () => getGlobalSetting("cutColor"),+ transact: storageTransaction,+ register: registerObjectIn,+};++const DELETED = "This library file was deleted.";++/**+ * Build the playable copy of a library video the browser cannot decode (a+ * ProRes master): the same proxy the project preview plays, made with the+ * code the engine runs on a Mac. It lands under the account's library prefix+ * as a quota-exempt object, and the row names it in the same transaction, so+ * every device plays it from then on. The master stays the asset's file.+ */+export async function runLibraryProxyJob(+ job: ClaimedJob,+ handle: RenderHandle,+ isCanceled: () => boolean,+ io: LibraryProxyIO = defaultIO+): Promise<LibraryAsset> {+ const { assetId } = (job.spec ?? {}) as { assetId?: string };+ if (!assetId) throw new Error("Library proxy job has no asset.");+ const row = await io.db.cutLibraryAsset.findFirst({ where: { id: assetId, userId: job.userId, deletedAt: null } });+ if (!row) throw new Error(DELETED);+ const media = await io.db.cutMediaObject.findFirst({ where: { id: row.mediaObjectId, userId: job.userId } });+ if (!media) throw new Error("Library media is missing.");++ // A replay, or a second ask after the copy landed, returns what is there.+ if ((row.meta as { proxyFile?: string } | null)?.proxyFile) return assetView(row, media);++ const tmp = await mkdtemp(path.join(os.tmpdir(), "cut-library-proxy-"));+ handle.tmpDir = tmp;+ let key: string | undefined;+ let published = false;+ try {+ const src = path.join(tmp, path.basename(media.fileName));+ await io.download(media.r2Key, src);+ if (isCanceled()) throw new Error("Proxy canceled.");++ // The copy shares the library prefix, so its name is deduped against+ // every file the shelf holds there.+ const rows = await io.db.cutMediaObject.findMany({+ where: { userId: job.userId, projectId: null, kind: { in: ["library", "proxy"] } },+ select: { fileName: true },+ });+ const fileName = dedupeName(proxyNameFor(media.fileName), new Set(rows.map((r) => r.fileName)));+ const out = path.join(tmp, fileName);+ handle.outPath = out;++ const [total, settings] = await Promise.all([io.duration(src), io.settings()]);+ await io.make(handle, src, out, {+ maxHeight: settings.proxyMaxHeight,+ crf: settings.proxyCrf,+ onProgress: (seconds) => {+ if (total > 0) handle.progress = Math.min(0.99, seconds / total);+ },+ });+ if (isCanceled()) throw new Error("Proxy canceled.");++ key = libraryKey(job.userId, fileName);+ const bytes = await io.upload(key, out, "video/mp4");+ const stored = key;+ const updated = await io.transact(async (tx) => {+ // The asset may have been deleted while the copy was built.+ const live = await tx.cutLibraryAsset.findFirst({ where: { id: assetId, userId: job.userId, deletedAt: null } });+ if (!live) throw new Error(DELETED);+ await io.register(tx, {+ userId: job.userId, projectId: null, r2Key: stored, fileName, mime: "video/mp4", bytes, kind: "proxy",+ });+ const meta = { ...((live.meta ?? {}) as Record<string, unknown>), proxyFile: fileName };+ return tx.cutLibraryAsset.update({ where: { id: assetId }, data: { meta: meta as Prisma.InputJsonValue } });+ });+ published = true;+ return assetView(updated, media);+ } finally {+ try {+ if (key && !published) await io.remove([key]);+ } finally {+ await rm(tmp, { recursive: true, force: true });+ }+ }+}diff --git a/site/src/cut/worker/proxyJob.ts b/site/src/cut/worker/proxyJob.tsindex 63c14ff4..900ed467 100644--- a/site/src/cut/worker/proxyJob.ts+++ b/site/src/cut/worker/proxyJob.ts@@ -8,6 +8,8 @@ import { probeDuration } from "../server/frames";import { dedupeName } from "../server/cloud/util";import { prisma, registerObject, unregisterObjects, type ClaimedJob } from "./db";import { deleteObjects, downloadToFile, mediaKey, uploadFile } from "./r2";+import { runLibraryProxyJob } from "./libraryProxyJob";+import type { LibraryAsset } from "../server/library";/** What a proxy job records in CutRenderJob.result — the same shape the* engine's synchronous proxy route returns. */@@ -55,7 +57,11 @@ export async function runProxyJob(handle: RenderHandle,isCanceled: () => boolean,io: ProxyJobIO = defaultIO-): Promise<ProxyResult> {+): Promise<ProxyResult | LibraryAsset> {+ // A library video's playable copy lands on the shelf, not in a project.+ if ((job.spec as { target?: string } | null)?.target === "library") {+ return runLibraryProxyJob(job, handle, isCanceled);+ }const { file } = (job.spec ?? {}) as { file?: string };if (!file) throw new Error("Proxy job has no file.");const projectId = job.projectId;