// THE ONE CLIP JOB OF THE VISITOR'S OWN COPY (lane browser-clip). // // A module store, not component state: Esc collapses the modal to the // mini-player and unmounts the clip panel, and that must not cancel a clip // being made. Clearing the copy, picking another or changing the video does // (the provider calls resetLocalClip). // // The engine (and with it the library) is loaded through localClipLoader's // dynamic import on the first prepare — never before a clip is asked for. // A clip built in memory becomes a Blob only once the copy is complete, and is // handed over as a download from an object URL; nothing here reaches the // network or any storage (components/LocalFilePicker.test.ts reads this source). import type { ClipPlan, SaveTarget } from "./localClipEngine"; import { loadClipEngine } from "./localClipLoader"; import { describeClip, refusalSentence, savePath, type Refusal } from "./localClip"; export type ClipRequest = { file: File; cueIn: number; cueOut: number; offset: number; title: string; slug: string; canSaveToDisk: boolean; }; type Prepared = { plan: ClipPlan; name: string; // How "Save clip" saves it: in memory (a download), or to a file the // visitor picks (a big clip, on a browser that can). A browser that can // also offers the file for a small clip ("Save to a file…"). path: "memory" | "disk"; canSaveToDisk: boolean; // From describeClip, one set of facts: the range the clip holds, where it // really starts, where it ends when that is before the out mark. range: string; start: string; end: string | null; }; export type ClipJobState = | { phase: "idle" } | { phase: "preparing"; key: string } | ({ phase: "ready"; key: string } & Prepared) // `retry`: the refusal may not hold the next time (a read that failed, a // copy that broke), so asking for the same key again prepares again. | { phase: "refused"; key: string; sentence: string; retry: boolean } | ({ phase: "saving"; key: string; fraction: number; doneSeconds: number; totalSeconds: number; to: "memory" | "disk" } & Prepared) | { phase: "done"; key: string; name: string; bytes: number; path: "memory" | "disk" } | { phase: "cancelled"; key: string; path: "memory" | "disk" } | { phase: "failed"; key: string; sentence: string }; const IDLE: ClipJobState = { phase: "idle" }; // How long a finished in-memory clip's object URL stays alive for the // download, unless a new clip or clearing the copy lets it go first. const DOWNLOAD_URL_LIFETIME_MS = 5 * 60_000; type Engine = Awaited>; let state: ClipJobState = IDLE; let engine: Engine | null = null; let current: ClipRequest | null = null; let token = 0; let saving: AbortController | null = null; let downloadUrl: string | null = null; let downloadTimer: ReturnType | null = null; // The last key whose transient refusal was prepared again: once, not forever. let retriedKey: string | null = null; const listeners = new Set<() => void>(); const fileIds = new WeakMap(); let nextFileId = 1; function set(next: ClipJobState) { state = next; for (const l of listeners) l(); } export function subscribeLocalClip(listener: () => void): () => void { listeners.add(listener); return () => listeners.delete(listener); } export function getLocalClipState(): ClipJobState { return state; } export function getIdleLocalClipState(): ClipJobState { return IDLE; } // What a prepared clip depends on: the file, the marks, the offset. export function clipKey(req: Pick): string { let id = fileIds.get(req.file); if (id === undefined) { id = nextFileId++; fileIds.set(req.file, id); } return `${id}|${req.cueIn}|${req.cueOut}|${req.offset}`; } function revokeDownload() { if (downloadTimer !== null) clearTimeout(downloadTimer); downloadTimer = null; if (downloadUrl) URL.revokeObjectURL(downloadUrl); downloadUrl = null; } const transient = (r: Refusal) => r.kind === "read" || r.kind === "copy"; function refuse(key: string, r: Refusal) { const retry = transient(r) && retriedKey !== key; set({ phase: "refused", key, sentence: refusalSentence(r), retry }); } // Probe the file for these marks: where the clip really starts and ends, its // name and how it will be saved — or the sentence that says why it cannot be. export async function prepareLocalClip(req: ClipRequest): Promise { if (state.phase === "saving") return; const key = clipKey(req); if (state.phase === "refused" && state.key === key && state.retry) retriedKey = key; const mine = ++token; current = req; set({ phase: "preparing", key }); try { engine ??= await loadClipEngine(); const probe = await engine.probeClip(req.file, req.cueIn, req.cueOut, req.offset); if (mine !== token) return; if (!probe.ok) return refuse(key, probe.refusal); const { plan } = probe; const path = savePath(plan.estimate, req.canSaveToDisk); if (path === "too-big") return refuse(key, { kind: "too-big", bytes: plan.estimate }); const words = describeClip({ cueIn: req.cueIn, cueOut: req.cueOut, offset: req.offset, fileStart: plan.fileStart, startTs: plan.startTs, endTs: plan.endTs, title: req.title, slug: req.slug, ext: plan.ext, }); set({ phase: "ready", key, plan, path, canSaveToDisk: req.canSaveToDisk, ...words }); } catch { if (mine !== token) return; refuse(key, { kind: "copy" }); } } function startDownload(blob: Blob, name: string) { revokeDownload(); downloadUrl = URL.createObjectURL(blob); const a = document.createElement("a"); a.href = downloadUrl; a.download = name; a.rel = "noopener"; document.body.appendChild(a); a.click(); a.remove(); downloadTimer = setTimeout(revokeDownload, DOWNLOAD_URL_LIFETIME_MS); } // Make the prepared clip. `target` is memory (a download when it is done) or // a file the visitor has just picked to write to. export async function saveLocalClip(target: SaveTarget): Promise { if (state.phase !== "ready" || !current) return; const prepared = state; const req = current; const mine = ++token; const ac = new AbortController(); saving = ac; const { phase: _phase, ...rest } = prepared; void _phase; set({ ...rest, phase: "saving", to: target.kind, fraction: 0, doneSeconds: 0, totalSeconds: prepared.plan.endTs - prepared.plan.startTs }); try { const eng = (engine ??= await loadClipEngine()); try { const result = await eng.saveClip( req.file, prepared.plan, target, (p) => { if (mine !== token || state.phase !== "saving") return; set({ ...state, fraction: p.fraction, doneSeconds: p.doneSeconds, totalSeconds: p.totalSeconds }); }, ac.signal, ); if (mine !== token) return; if (result.blob) startDownload(result.blob, prepared.name); set({ phase: "done", key: prepared.key, name: prepared.name, bytes: result.bytes, path: target.kind }); } catch (e) { if (mine !== token) return; if (e instanceof eng.ClipCancelled) set({ phase: "cancelled", key: prepared.key, path: target.kind }); else set({ phase: "failed", key: prepared.key, sentence: refusalSentence(eng.saveFailure(e, req.canSaveToDisk)) }); } } finally { if (saving === ac) saving = null; } } // Stop a clip being made. Nothing is handed over as finished: an in-memory // clip never becomes a Blob, a disk writer is aborted, not closed. export function cancelLocalClip(): void { saving?.abort(); } function forget(): "memory" | "disk" | null { token++; const was = state.phase === "saving" ? state.to : null; saving?.abort(); saving = null; if (engine && current) void engine.forgetClipInput(current.file); current = null; if (state.phase !== "idle") set(IDLE); return was; } // The panel was closed: any clip being made is cancelled (its path is // returned, so the panel can say so), but a finished clip's download URL is // left to its timer — the browser may still be reading it. export function closeLocalClip(): "memory" | "disk" | null { return forget(); } // Forget the job entirely (the copy was cleared or replaced, the video // changed): any clip being made is cancelled, and a finished one's download // URL is let go. export function resetLocalClip(): void { forget(); revokeDownload(); }