Skip to content

Open source CapCut alternative.

TypeScript

feat(site): place a Cut import before its bytes are stored

David Le0097fe2f9aed
diff --git a/site/src/cut/components/Editor.tsx b/site/src/cut/components/Editor.tsx
index 93a3bfe0..b0fd112d 100644
--- a/site/src/cut/components/Editor.tsx
+++ b/site/src/cut/components/Editor.tsx
@@ -9,14 +9,22 @@ import { loadedDocVersion } from "@/cut/lib/backend/shared";
import { writeCachedDoc } from "@/cut/lib/docCache";
import { refreshShareCard, renderPreviewProxy } from "@/cut/lib/exportClient";
import { fileZoneAt, hasRefDrag } from "@/cut/lib/assetRef";
-import { enrichAsset, importFileToProject } from "@/cut/lib/media";
+import { startUpload } from "@/cut/lib/importQueue";
+import { enrichAsset, importFileToProject, prepareImport } from "@/cut/lib/media";
// Side-effect import: registers the brief-to-video resume subscription, so a
// persisted run resumes on project load even when the AI panel never mounts.
import "@/cut/lib/genScene";
import { installDevHooks } from "@/cut/lib/devHooks";
import { backTarget, useCutBase } from "@/cut/lib/nav";
import { resolveProjectMode } from "@/cut/lib/residency";
-import { projectDuration, serializeDoc, storedAssets, useEditor } from "@/cut/lib/store";
+import {
+ docAudioClips,
+ docClips,
+ projectDuration,
+ serializeDoc,
+ storedAssets,
+ useEditor,
+} from "@/cut/lib/store";
import type { MediaAsset } from "@/cut/lib/types";
import { AiPanel } from "./AiPanel";
import { ExportDialog } from "./ExportDialog";
@@ -67,6 +75,9 @@ export function Editor({
(s) => !s.readOnly && s.selection != null && s.selection.kind !== "cue"
);
const [importing, setImporting] = useState(0);
+ // Files being probed and named, plus the ones already placed whose bytes are
+ // still going out — both are work the save indicator reports.
+ const sending = useEditor((s) => s.assets.reduce((n, a) => (a.upload ? n + 1 : n), 0));
const [conflictReloaded, setConflictReloaded] = useState(false);
const [shareGone, setShareGone] = useState(false);
const dragDepth = useRef(0);
@@ -324,8 +335,10 @@ export function Editor({
const assetsDirty = assetsChanged(s.assets);
const changed =
assetsDirty ||
- s.clips !== (last.clips as unknown) ||
- s.audioClips !== (last.audioClips as unknown) ||
+ // The projections, not the raw arrays: clips waiting on an upload are
+ // held out of the document, and holding one is not an edit.
+ docClips(s.clips, s.assets) !== (last.clips as unknown) ||
+ docAudioClips(s.audioClips, s.assets) !== (last.audioClips as unknown) ||
s.overlays !== (last.overlays as unknown) ||
s.templates !== (last.templates as unknown) ||
s.subtitles !== (last.subtitles as unknown) ||
@@ -364,9 +377,16 @@ export function Editor({
) => {
const list = Array.from(files);
setImporting((n) => n + list.length);
+ // Files are prepared one at a time: each claims its stored name against
+ // the names already taken, so two drops of the same name must not race
+ // for it. Only the bytes go out in parallel, from the upload queue.
for (const file of list) {
try {
- const asset = await importFileToProject(projectId, file);
+ // Cloud: the file is probed and named before anything is uploaded,
+ // so it can be placed now and sent behind the editor. Local: the
+ // engine names a file only once it holds the bytes.
+ const pending = await prepareImport(projectId, file);
+ const asset = pending?.asset ?? (await importFileToProject(projectId, file));
if (!asset) continue;
// Recordings are created media: tag them so they land on the timeline
// but never in the Media panel (reserved for user imports).
@@ -387,7 +407,10 @@ export function Editor({
s.addAudioFromAsset(asset.id, opts?.at);
}
}
- void enrichAsset(asset);
+ // A pending import already holds its bytes, so the filmstrip is
+ // drawn from those rather than downloaded back from storage.
+ void enrichAsset(asset, pending?.localUrl);
+ if (pending) startUpload(projectId, pending);
} catch (err) {
console.error(`Import failed for ${file.name}:`, err);
} finally {
@@ -576,7 +599,12 @@ export function Editor({
{viewer ? (
<ViewerTopBar />
) : (
- <TopBar onImport={importFiles} from={from} folder={folder} uploading={importing} />
+ <TopBar
+ onImport={importFiles}
+ from={from}
+ folder={folder}
+ uploading={importing + sending}
+ />
)}
<div
className={`grid min-h-0 ${
diff --git a/site/src/cut/components/SidePanel.tsx b/site/src/cut/components/SidePanel.tsx
index a8712c1e..3950546c 100644
--- a/site/src/cut/components/SidePanel.tsx
+++ b/site/src/cut/components/SidePanel.tsx
@@ -61,6 +61,7 @@ import {
type LibraryAsset,
type LibraryFolder,
} from "@/cut/lib/library";
+import { retryUpload } from "@/cut/lib/importQueue";
import { revealMedia } from "@/cut/lib/media";
import { mediaUrl, TRANSITION_MAX, type LibraryTemplate } from "@/cut/lib/types";
import { genPulseOverlay, isGenTab, useGenNotify, useGenPulse, useWatchGenTab } from "@/cut/lib/genNotify";
@@ -686,6 +687,39 @@ function MediaPanel({
);
}
+/** The tile's upload state. The clip is already usable, so this stays out of
+ * the way: a line across the bottom of the tile while the bytes go out, and a
+ * message only if they don't arrive. */
+function UploadState({ asset }: { asset: MediaAsset }) {
+ const upload = asset.upload;
+ if (!upload) return null;
+ if (upload.error) {
+ return (
+ <div className="absolute inset-x-0 bottom-0 flex items-center gap-1.5 bg-black/70 px-1.5 py-1 text-[10px] text-white">
+ <span className="min-w-0 flex-1 truncate">Upload failed</span>
+ <button
+ type="button"
+ className="shrink-0 font-medium underline underline-offset-2"
+ onClick={(e) => {
+ e.stopPropagation();
+ retryUpload(asset.id);
+ }}
+ >
+ Retry
+ </button>
+ </div>
+ );
+ }
+ return (
+ <span className="absolute inset-x-0 bottom-0 h-[3px] bg-black/25">
+ <span
+ className="block h-full bg-primary transition-[width] duration-150"
+ style={{ width: `${Math.round(upload.progress * 100)}%` }}
+ />
+ </span>
+ );
+}
+
function AssetCard({ asset, projectId }: { asset: MediaAsset; projectId: string }) {
const caps = useCutCaps();
const [saved, setSaved] = useState(false);
@@ -815,7 +849,7 @@ function AssetCard({ asset, projectId }: { asset: MediaAsset; projectId: string
{saved ? <Check className="size-3" /> : <Ellipsis className="size-3" />}
</DropdownMenuTrigger>
<DropdownMenuContent align="end" className="w-48" onClick={(e) => e.stopPropagation()}>
- <DropdownMenuItem onClick={saveToLibrary}>
+ <DropdownMenuItem onClick={saveToLibrary} disabled={!!asset.upload}>
<FolderPlus /> Save to library
</DropdownMenuItem>
{caps.revealInFinder && (
@@ -838,6 +872,7 @@ function AssetCard({ asset, projectId }: { asset: MediaAsset; projectId: string
className="absolute top-1.5 left-1.5 max-w-[70%] px-2 py-1 text-[11px] font-medium text-white transition-[max-width] group-hover:max-w-[calc(100%-4.75rem)]"
/>
)}
+ {asset.upload && <UploadState asset={asset} />}
</div>
{asset.type !== "audio" && (
<CopyNameLabel name={asset.name} className="text-[11px] text-muted-foreground" />
diff --git a/site/src/cut/components/TopBar.tsx b/site/src/cut/components/TopBar.tsx
index 51850c0f..aa8fc8c9 100644
--- a/site/src/cut/components/TopBar.tsx
+++ b/site/src/cut/components/TopBar.tsx
@@ -479,7 +479,11 @@ export function TopBar({
<Button
variant="ghost"
size="sm"
- disabled={!hasClips}
+ // A render reads the saved document, which an import still uploading
+ // is deliberately absent from — exporting now would quietly leave it
+ // out of the video.
+ disabled={!hasClips || cloudUploading}
+ title={cloudUploading ? "Finishing uploads…" : undefined}
onClick={() => {
const s = useEditor.getState();
s.setPlaying(false);
diff --git a/site/src/cut/lib/importQueue.ts b/site/src/cut/lib/importQueue.ts
new file mode 100644
index 00000000..c77585e1
--- /dev/null
+++ b/site/src/cut/lib/importQueue.ts
@@ -0,0 +1,119 @@
+"use client";
+
+// Imports that are on screen before they are stored. A dropped file is probed
+// from its own bytes and placed straight away; the upload runs here, behind the
+// editor, and the asset swaps from its local object URL to the stored one when
+// the bytes land.
+//
+// Three things keep that honest:
+// - Nothing about a pending asset reaches the saved document (see storedAssets
+// / docClips), so a tab that dies mid-upload leaves no broken reference.
+// - Deleting a pending asset aborts its upload; the claimed object is never
+// completed and is collected server-side.
+// - A failed upload leaves the asset in place with an error, so the user can
+// retry it rather than discover later that it was never saved.
+import type { PendingImport } from "./media";
+import { useEditor } from "./store";
+import { mediaUrl } from "./types";
+
+// Browsers cap connections per host anyway; a small window keeps one big file
+// from starving the rest of a multi-file drop.
+const MAX_IN_FLIGHT = 3;
+
+let active = 0;
+const waiting: (() => void)[] = [];
+
+function acquire(): Promise<void> {
+ if (active < MAX_IN_FLIGHT) {
+ active++;
+ return Promise.resolve();
+ }
+ return new Promise((resolve) => waiting.push(resolve));
+}
+
+function release() {
+ const next = waiting.shift();
+ if (next) next();
+ else active--;
+}
+
+type Job = { pending: PendingImport; projectId: string; controller: AbortController };
+
+const jobs = new Map<string, Job>();
+
+/** Start the background upload for a prepared import. The asset must already
+ * be in the store. */
+export function startUpload(projectId: string, pending: PendingImport) {
+ const job: Job = { pending, projectId, controller: new AbortController() };
+ jobs.set(pending.asset.id, job);
+ void run(job);
+}
+
+/** Retry an upload that failed. */
+export function retryUpload(assetId: string) {
+ const job = jobs.get(assetId);
+ if (!job) return;
+ job.controller = new AbortController();
+ useEditor.getState().updateAsset(assetId, { upload: { progress: 0 } });
+ void run(job);
+}
+
+/** Stop an upload whose asset is gone. The claimed object is left incomplete
+ * on purpose — it was never counted against the account. */
+export function cancelUpload(assetId: string) {
+ const job = jobs.get(assetId);
+ if (!job) return;
+ jobs.delete(assetId);
+ job.controller.abort();
+ URL.revokeObjectURL(job.pending.localUrl);
+}
+
+/** An upload is only worth finishing while its asset is still open in front of
+ * the user: deleting it, or leaving for another project, ends it. */
+function wanted(job: Job): boolean {
+ const s = useEditor.getState();
+ return s.projectId === job.projectId && s.assets.some((a) => a.id === job.pending.asset.id);
+}
+
+async function run(job: Job) {
+ const { asset, localUrl, send } = job.pending;
+ await acquire();
+ try {
+ if (!wanted(job)) return cancelUpload(asset.id);
+ let shown = -1;
+ await send({
+ signal: job.controller.signal,
+ onProgress: (fraction) => {
+ // The progress stream is the cheapest place to notice the asset is
+ // gone, and the only one that fires during a long upload.
+ if (!wanted(job)) return cancelUpload(asset.id);
+ const pct = Math.floor(fraction * 100);
+ if (pct === shown) return;
+ shown = pct;
+ useEditor.getState().updateAsset(asset.id, { upload: { progress: fraction } });
+ },
+ });
+ if (!wanted(job)) return cancelUpload(asset.id);
+ jobs.delete(asset.id);
+ // The stored file takes over from the local bytes. Filmstrips are
+ // self-contained frames and survive the swap; a still's single "frame" is
+ // the source itself, so it repoints with the asset.
+ const url = mediaUrl(job.projectId, asset.fileName);
+ useEditor.getState().updateAsset(asset.id, {
+ url,
+ upload: undefined,
+ ...(asset.type === "image" ? { thumbs: [url] } : {}),
+ });
+ // Decoders repoint on the URL change; let the frame they are painting
+ // finish before the bytes behind them go away.
+ setTimeout(() => URL.revokeObjectURL(localUrl), 10_000);
+ } catch (err) {
+ if (job.controller.signal.aborted) return;
+ if (!wanted(job)) return cancelUpload(asset.id);
+ useEditor.getState().updateAsset(asset.id, {
+ upload: { progress: 0, error: err instanceof Error ? err.message : "Upload failed." },
+ });
+ } finally {
+ release();
+ }
+}
diff --git a/site/src/cut/lib/media.ts b/site/src/cut/lib/media.ts
index 8e145a45..e149342e 100644
--- a/site/src/cut/lib/media.ts
+++ b/site/src/cut/lib/media.ts
@@ -94,37 +94,68 @@ export function isTextFile(file: File) {
return file.type.startsWith("text/") || /\.(txt|md|markdown|srt|vtt|csv|json)$/i.test(file.name);
}
-/** Presign a direct-to-R2 upload, PUT the bytes, and return the object key
- * for the follow-up complete call. Shared by project media, the library, and
- * export overlays; cloud backend only. */
-export async function presignedUpload(
+/** Claim a name and mint a direct-to-R2 PUT for one file. The name is deduped
+ * and reserved server-side before the URL comes back, so callers can build the
+ * asset's final identity before a single byte moves. */
+export async function presignUpload(
presignPath: string,
file: Blob,
name: string,
backend: CutBackend = getBackend()
-): Promise<string> {
+): Promise<{ key: string; url: string; fileName: string }> {
const mime = file.type || "application/octet-stream";
const res = await backend.fetch(presignPath, {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ fileName: name, mime, bytes: file.size }),
});
- const body = await apiJson<{ key?: string; url?: string }>(res);
+ const body = await apiJson<{ key?: string; url?: string; fileName?: string }>(res);
if (!res.ok || !body.key || !body.url) {
throw new Error(quotaErrorMessage(res.status, body) ?? body.error ?? "Upload failed.");
}
- await putSigned(body.url, file, mime);
- return body.key;
+ return { key: body.key, url: body.url, fileName: body.fileName ?? name };
}
-/** PUT a blob to a presigned R2 URL. */
-export async function putSigned(url: string, file: Blob, mime?: string) {
- const put = await fetch(url, {
- method: "PUT",
- headers: { "Content-Type": mime ?? (file.type || "application/octet-stream") },
- body: file,
+/** Presign a direct-to-R2 upload, PUT the bytes, and return the object key
+ * for the follow-up complete call. Shared by project media, the library, and
+ * export overlays; cloud backend only. */
+export async function presignedUpload(
+ presignPath: string,
+ file: Blob,
+ name: string,
+ backend: CutBackend = getBackend()
+): Promise<string> {
+ const signed = await presignUpload(presignPath, file, name, backend);
+ await putSigned(signed.url, file, file.type || "application/octet-stream");
+ return signed.key;
+}
+
+/** PUT a blob to a presigned R2 URL. XHR rather than fetch: it is the only way
+ * to watch the bytes leave, which is what an upload running behind the editor
+ * has to report. */
+export function putSigned(
+ url: string,
+ file: Blob,
+ mime?: string,
+ opts?: { onProgress?: (fraction: number) => void; signal?: AbortSignal }
+): Promise<void> {
+ return new Promise((resolve, reject) => {
+ if (opts?.signal?.aborted) return reject(new DOMException("Upload cancelled.", "AbortError"));
+ const xhr = new XMLHttpRequest();
+ xhr.open("PUT", url);
+ xhr.setRequestHeader("Content-Type", mime ?? (file.type || "application/octet-stream"));
+ if (opts?.onProgress) {
+ xhr.upload.onprogress = (e) => {
+ if (e.lengthComputable && e.total > 0) opts.onProgress!(e.loaded / e.total);
+ };
+ }
+ xhr.onload = () =>
+ xhr.status >= 200 && xhr.status < 300 ? resolve() : reject(new Error("Upload failed."));
+ xhr.onerror = () => reject(new Error("Upload failed."));
+ xhr.onabort = () => reject(new DOMException("Upload cancelled.", "AbortError"));
+ opts?.signal?.addEventListener("abort", () => xhr.abort(), { once: true });
+ xhr.send(file);
});
- if (!put.ok) throw new Error("Upload failed.");
}
/** Upload raw media bytes into a project. Local: the engine's multipart POST,
@@ -218,6 +249,50 @@ export async function uploadProjectImage(
};
}
+/** The kind of asset a dropped file becomes, or null if Cut can't use it.
+ * MIME wins over extension: recordings are .webm for both video and audio. */
+export function assetTypeOf(file: File): AssetType | null {
+ if (file.type.startsWith("video/")) return "video";
+ if (file.type.startsWith("audio/")) return "audio";
+ if (file.type.startsWith("image/")) return "image";
+ if (isVideoFile(file)) return "video";
+ if (isAudioFile(file)) return "audio";
+ if (isImageFile(file)) return "image";
+ return null;
+}
+
+type ProbedMeta = {
+ type: AssetType;
+ duration: number;
+ width?: number;
+ height?: number;
+ peaks?: number[];
+};
+
+/** Read a media URL's kind/duration/dimensions with the browser's own
+ * decoders. The probe can correct the guessed kind: a "video" container with
+ * no video stream is really audio. */
+async function probeMedia(type: AssetType, url: string): Promise<ProbedMeta> {
+ if (type === "image") {
+ // Images have no intrinsic duration; the timeline clip carries its length.
+ const dims = await loadImageMeta(url);
+ return { type, duration: 0, width: dims.width, height: dims.height };
+ }
+ if (type === "video") {
+ const v = await loadVideoMeta(url);
+ if (v.videoWidth === 0) return { type: "audio", duration: v.duration };
+ return { type, duration: v.duration, width: v.videoWidth, height: v.videoHeight };
+ }
+ // Decode for a sample-exact duration (HTMLAudioElement overestimates MP3s,
+ // leaving a placed clip running past its real audio) and reuse the same
+ // decode for the waveform, so enrichAsset has nothing left to do.
+ const audio = await decodeAudio(url);
+ if (audio && audio.duration > 0) {
+ return { type, duration: audio.duration, peaks: peaksFromChannel(audio.getChannelData(0)) };
+ }
+ return { type, duration: await loadAudioDuration(url) };
+}
+
/** Probe a media file's kind/duration/dimensions in the browser via an object
* URL — for backends that can't probe server-side (cloud library complete). */
export async function probeFileMeta(file: File): Promise<{
@@ -228,21 +303,80 @@ export async function probeFileMeta(file: File): Promise<{
}> {
const url = URL.createObjectURL(file);
try {
- if (isImageFile(file) && !isVideoFile(file) && !isAudioFile(file)) {
- const dims = await loadImageMeta(url);
- return { type: "image", duration: 0, width: dims.width, height: dims.height };
- }
- if (isAudioFile(file) && !isVideoFile(file)) {
- return { type: "audio", duration: await loadAudioDuration(url).catch(() => 0) };
- }
- const v = await loadVideoMeta(url);
- if (v.videoWidth === 0) return { type: "audio", duration: v.duration };
- return { type: "video", duration: v.duration, width: v.videoWidth, height: v.videoHeight };
+ const meta = await probeMedia(assetTypeOf(file) ?? "video", url);
+ return { type: meta.type, duration: meta.duration, width: meta.width, height: meta.height };
} finally {
URL.revokeObjectURL(url);
}
}
+/** An import that is on screen before its bytes have left the browser. */
+export type PendingImport = {
+ /** Ready to add to the project: plays from `localUrl`, carries its final
+ * `fileName`, and is marked `upload` until the bytes land. */
+ asset: MediaAsset;
+ /** The object URL the asset plays from until the stored file takes over. */
+ localUrl: string;
+ /** Send the bytes and mark the object complete. */
+ send: (opts?: { onProgress?: (fraction: number) => void; signal?: AbortSignal }) => Promise<void>;
+};
+
+/** Prepare a dropped file so it can appear instantly: reserve its stored name
+ * and probe it from local bytes, both before anything is uploaded. The caller
+ * adds the asset, then runs `send` in the background.
+ *
+ * Cloud only. The engine takes a file's bytes and hands back its name in one
+ * request, so there is no name to build an asset around ahead of time — and a
+ * copy to local disk is quick enough that there is nothing to hide. */
+export async function prepareImport(
+ projectId: string,
+ file: File,
+ backend: CutBackend = getBackend()
+): Promise<PendingImport | null> {
+ if (backend.kind !== "cloud") return null;
+ const type = assetTypeOf(file);
+ if (!type) return null;
+
+ const localUrl = URL.createObjectURL(file);
+ try {
+ // Probing and claiming the name are independent, so the asset is ready
+ // after whichever is slower rather than after both in turn.
+ const [meta, signed] = await Promise.all([
+ probeMedia(type, localUrl),
+ presignUpload(`/api/cut/projects/${projectId}/media/presign`, file, file.name, backend),
+ ]);
+ const asset: MediaAsset = {
+ id: uid(),
+ fileName: signed.fileName,
+ name: file.name,
+ type: meta.type,
+ duration: meta.duration,
+ ...(meta.width !== undefined ? { width: meta.width } : {}),
+ ...(meta.height !== undefined ? { height: meta.height } : {}),
+ ...(meta.peaks ? { peaks: meta.peaks } : {}),
+ url: localUrl,
+ upload: { progress: 0 },
+ };
+ const send = async (opts?: {
+ onProgress?: (fraction: number) => void;
+ signal?: AbortSignal;
+ }) => {
+ await putSigned(signed.url, file, file.type || "application/octet-stream", opts);
+ const res = await backend.fetch(`/api/cut/projects/${projectId}/media/complete`, {
+ method: "POST",
+ headers: { "Content-Type": "application/json" },
+ body: JSON.stringify({ key: signed.key }),
+ });
+ const body = await apiJson<{ fileName?: string }>(res);
+ if (!res.ok || !body.fileName) throw new Error(body.error ?? "Upload failed.");
+ };
+ return { asset, localUrl, send };
+ } catch (err) {
+ URL.revokeObjectURL(localUrl);
+ throw err;
+ }
+}
+
/** Upload a raw file into the project folder, probe it, and return the asset.
* Thumbnails/waveform are filled in asynchronously via `enrichAsset`. */
export async function importFileToProject(
@@ -250,63 +384,23 @@ export async function importFileToProject(
file: File,
backend: CutBackend = getBackend()
): Promise<MediaAsset | null> {
- // MIME wins over extension: recordings are .webm for both video and audio.
- const type: AssetType | null = file.type.startsWith("video/")
- ? "video"
- : file.type.startsWith("audio/")
- ? "audio"
- : file.type.startsWith("image/")
- ? "image"
- : isVideoFile(file)
- ? "video"
- : isAudioFile(file)
- ? "audio"
- : isImageFile(file)
- ? "image"
- : null;
+ const type = assetTypeOf(file);
if (!type) return null;
const fileName = await uploadProjectMediaTo(backend, projectId, file, file.name);
-
const url = mediaUrl(projectId, fileName);
- const asset: MediaAsset = {
+ const meta = await probeMedia(type, url);
+ return {
id: uid(),
fileName,
name: file.name,
- type,
- duration: 0,
+ type: meta.type,
+ duration: meta.duration,
+ ...(meta.width !== undefined ? { width: meta.width } : {}),
+ ...(meta.height !== undefined ? { height: meta.height } : {}),
+ ...(meta.peaks ? { peaks: meta.peaks } : {}),
url,
};
-
- if (type === "video") {
- const v = await loadVideoMeta(url);
- if (v.videoWidth === 0) {
- // A "video" container with no video stream is really audio.
- asset.type = "audio";
- asset.duration = v.duration;
- } else {
- asset.duration = v.duration;
- asset.width = v.videoWidth;
- asset.height = v.videoHeight;
- }
- } else if (type === "image") {
- // Images have no intrinsic duration; the timeline clip carries its length.
- const dims = await loadImageMeta(url);
- asset.width = dims.width;
- asset.height = dims.height;
- } else {
- // Decode for a sample-exact duration (HTMLAudioElement overestimates MP3s,
- // leaving a placed clip running past its real audio) and reuse the same
- // decode for the waveform, so enrichAsset has nothing left to do.
- const audio = await decodeAudio(url);
- if (audio && audio.duration > 0) {
- asset.duration = audio.duration;
- asset.peaks = peaksFromChannel(audio.getChannelData(0));
- } else {
- asset.duration = await loadAudioDuration(url);
- }
- }
- return asset;
}
/** Natural pixel size of an image URL, for framing on the timeline. */
@@ -723,13 +817,15 @@ export async function makeContactSheetsClientSide(
}
/** Generate filmstrip thumbnails / waveform peaks and merge them into the
- * store. Safe to call repeatedly; skips assets that are already enriched. */
-export async function enrichAsset(asset: MediaAsset) {
+ * store. Safe to call repeatedly; skips assets that are already enriched.
+ * `src` overrides where the frames are read from — an import still uploading
+ * has the bytes in the browser already, so it need not wait or re-download. */
+export async function enrichAsset(asset: MediaAsset, src = asset.url) {
try {
if (asset.type === "image") {
// A still is its own filmstrip: one frame, tiled across the clip.
if (!asset.thumbs?.length) {
- useEditor.getState().updateAsset(asset.id, { thumbs: [asset.url], thumbStep: IMAGE_CLIP_SECONDS });
+ useEditor.getState().updateAsset(asset.id, { thumbs: [src], thumbStep: IMAGE_CLIP_SECONDS });
}
} else if (asset.type === "video" && !asset.thumbs?.length) {
const key = stripCacheKey(useEditor.getState().projectId, asset.fileName);
@@ -737,12 +833,12 @@ export async function enrichAsset(asset: MediaAsset) {
if (cached) {
useEditor.getState().updateAsset(asset.id, { thumbs: cached.thumbs, thumbStep: cached.thumbStep });
} else {
- const { thumbs, thumbStep } = await makeThumbs(asset.url, asset.duration);
+ const { thumbs, thumbStep } = await makeThumbs(src, asset.duration);
useEditor.getState().updateAsset(asset.id, { thumbs, thumbStep });
writeCachedStrip(key, { thumbs, thumbStep, duration: asset.duration, at: Date.now() });
}
} else if (asset.type === "audio" && !asset.peaks?.length) {
- const peaks = await makePeaks(asset.url);
+ const peaks = await makePeaks(src);
useEditor.getState().updateAsset(asset.id, { peaks });
}
} catch {
diff --git a/site/src/cut/lib/store.ts b/site/src/cut/lib/store.ts
index 6c48c6c4..3a2e16ee 100644
--- a/site/src/cut/lib/store.ts
+++ b/site/src/cut/lib/store.ts
@@ -1262,6 +1262,9 @@ export const useEditor = create<EditorState>((baseSet, get) => {
try {
set((s) => ({
assets: s.assets.map((a) => {
+ // An import still uploading plays from local bytes; a signed URL
+ // for an object that hasn't landed would only 404.
+ if (a.upload) return a;
const url = urls.get(a.fileName);
return url && url !== a.url ? { ...a, url } : a;
}),
@@ -3037,22 +3040,53 @@ useEditor.subscribe((s, prev) => {
docSeq++;
});
+/** Ids of the assets still uploading, as a comparable key ("" when none). An
+ * import is on screen before its bytes are stored, and nothing about it may
+ * reach the document until they are. */
+function pendingKey(assets: MediaAsset[]): string {
+ let key = "";
+ for (const a of assets) if (a.upload) key += `${a.id},`;
+ return key;
+}
+
+/** Clips are held back from the document while their asset is still uploading:
+ * one pointing at bytes this tab never finished sending would reopen broken.
+ * Memoized, so autosave's change detector can compare the projection by
+ * reference and an upload in flight doesn't read as a stream of edits. */
+function docClipFilter<T extends { assetId: string }>() {
+ let memo: { clips: T[]; key: string; out: T[] } | null = null;
+ return (clips: T[], assets: MediaAsset[]): T[] => {
+ const key = pendingKey(assets);
+ if (memo && memo.clips === clips && memo.key === key) return memo.out;
+ const out = key
+ ? clips.filter((c) => !assets.some((a) => a.id === c.assetId && a.upload))
+ : clips;
+ memo = { clips, key, out };
+ return out;
+ };
+}
+export const docClips = docClipFilter<VideoClip>();
+export const docAudioClips = docClipFilter<AudioClip>();
+
/** The asset fields persisted in project.json — the projection autosave
* writes, and the one its change detector compares (runtime fields like
- * thumbs/peaks must not mark the doc dirty). */
+ * thumbs/peaks must not mark the doc dirty). Assets whose bytes are still
+ * uploading are left out entirely; they join the document when they land. */
export function storedAssets(assets: MediaAsset[]): StoredAsset[] {
- return assets.map(({ id, fileName, name, type, duration, width, height, origin, chatId, language }) => ({
- id,
- fileName,
- name,
- type,
- duration,
- ...(width !== undefined ? { width } : {}),
- ...(height !== undefined ? { height } : {}),
- ...(origin !== undefined ? { origin } : {}),
- ...(chatId !== undefined ? { chatId } : {}),
- ...(language !== undefined ? { language } : {}),
- }));
+ return assets
+ .filter((a) => !a.upload)
+ .map(({ id, fileName, name, type, duration, width, height, origin, chatId, language }) => ({
+ id,
+ fileName,
+ name,
+ type,
+ duration,
+ ...(width !== undefined ? { width } : {}),
+ ...(height !== undefined ? { height } : {}),
+ ...(origin !== undefined ? { origin } : {}),
+ ...(chatId !== undefined ? { chatId } : {}),
+ ...(language !== undefined ? { language } : {}),
+ }));
}
/** The persistable slice of the editor state, for autosave. */
@@ -3075,8 +3109,8 @@ export function serializeDoc(s: {
return {
name: s.projectName,
assets: storedAssets(s.assets),
- clips: s.clips,
- audioClips: s.audioClips,
+ clips: docClips(s.clips, s.assets),
+ audioClips: docAudioClips(s.audioClips, s.assets),
overlays: s.overlays,
templates: s.templates,
aspect: s.aspect,
diff --git a/site/src/cut/lib/types.ts b/site/src/cut/lib/types.ts
index f94a0ce1..292c2695 100644
--- a/site/src/cut/lib/types.ts
+++ b/site/src/cut/lib/types.ts
@@ -113,6 +113,17 @@ export interface StoredAsset {
chatId?: string;
}
+/** An import whose bytes are still on their way to storage. While this is set
+ * the asset plays from a local object URL, and it is held out of the saved
+ * document along with the clips that use it — a reload cannot resume bytes
+ * this tab was holding, so a doc pointing at them would open broken. */
+export interface AssetUpload {
+ /** Share of the bytes sent, 0..1. */
+ progress: number;
+ /** Set when the upload failed; the asset is retryable until it is removed. */
+ error?: string;
+}
+
/** Runtime asset: stored fields plus derived/browser-only data. */
export interface MediaAsset extends StoredAsset {
url: string; // /api/cut/projects/<id>/media/<fileName>
@@ -121,6 +132,8 @@ export interface MediaAsset extends StoredAsset {
thumbStep?: number;
/** Normalized waveform peaks 0..1 (audio only). */
peaks?: number[];
+ /** Present only while the file is still uploading. */
+ upload?: AssetUpload;
}
/**