commit 697a4f9f32817ac9ce842e3920edd63a6a88217f
parent d2ccd7d076dc31a62bc0a46a78f6cc054dcbc4d2
Author: I Mean I'm Just Saying <imeanimjustsaying@kiwifarms.st>
Date: Thu, 19 Nov 2026 16:41:07 -0500
common: the clip engine shares the probe's input, and a cancel never waits
The save reuses the input the probe opened (one per picked file), so it does
not read the headers and index again; forgetClipInput lets it go. Every
await of the library in the save races the abort signal: a cancel while a
read is in flight answered never before (the library does not reject an
in-flight demux on dispose), and now rejects at once. A disk writer is
aborted before the cancel is reported; the input and the output are
released behind it.
Co-Authored-By: Claude <noreply@anthropic.com>
Diffstat:
2 files changed, 117 insertions(+), 40 deletions(-)
diff --git a/common/lib/localClipEngine.test.ts b/common/lib/localClipEngine.test.ts
@@ -169,3 +169,42 @@ test("cancel stops the copy, aborts the disk writer and never closes (commits) i
assert.ok(calls.includes("abort"), calls.join(","));
assert.ok(!calls.includes("close"), calls.join(","));
});
+
+test("cancel while a read is in flight answers at once, and hands back no clip", { skip }, async () => {
+ const path = join(dir, "heavy.webm");
+ execFileSync("ffmpeg", [
+ "-v", "error", "-y",
+ "-f", "lavfi", "-i", "testsrc2=size=320x180:rate=25:duration=20",
+ "-f", "lavfi", "-i", "sine=frequency=440:sample_rate=48000:duration=20",
+ "-vf", "noise=alls=80:allf=t", ...SOURCES.webm, "-b:v", "4M", "-minrate", "4M", "-maxrate", "4M", "-shortest", path,
+ ]);
+ const src = await openAsBlob(path);
+ // The file reads slowly (100 ms per 64 KiB), as from a slow disk.
+ const orig = Blob.prototype.stream;
+ Blob.prototype.stream = function (this: Blob) {
+ const reader = orig.call(this).getReader();
+ return new ReadableStream({
+ async pull(c) {
+ const { done, value } = await reader.read();
+ if (done) return c.close();
+ await new Promise((r) => setTimeout(r, Math.ceil(value.byteLength / 65536) * 100));
+ c.enqueue(value);
+ },
+ cancel: (r) => reader.cancel(r),
+ });
+ } as typeof Blob.prototype.stream;
+ try {
+ const probe = await probeClip(src, 2, 19, 0);
+ assert.ok(probe.ok);
+ if (!probe.ok) return;
+ const ac = new AbortController();
+ const run = saveClip(src, probe.plan, { kind: "memory" }, () => {}, ac.signal);
+ await new Promise((r) => setTimeout(r, 400));
+ const at = Date.now();
+ ac.abort();
+ await assert.rejects(run, ClipCancelled);
+ assert.ok(Date.now() - at < 300, `cancel took ${Date.now() - at} ms`);
+ } finally {
+ Blob.prototype.stream = orig;
+ }
+});
diff --git a/common/lib/localClipEngine.ts b/common/lib/localClipEngine.ts
@@ -114,8 +114,17 @@ function familyOf(format: InputFormat): ContainerFamily | null {
return null;
}
-function openInput(file: Blob): Input {
- return new Input({ source: new BlobSource(file), formats: FORMATS });
+// One input per picked file, shared by the probe and the save, so the save
+// does not read the file's headers and index again.
+const inputs = new WeakMap<Blob, Input>();
+
+function inputFor(file: Blob): Input {
+ let input = inputs.get(file);
+ if (!input || input.disposed) {
+ input = new Input({ source: new BlobSource(file), formats: FORMATS });
+ inputs.set(file, input);
+ }
+ return input;
}
// dispose() on an input whose format was never found leaves an unhandled
@@ -125,6 +134,37 @@ async function release(input: Input): Promise<void> {
if (await input.canRead().catch(() => false)) input.dispose();
}
+// Let go of a file's input (its reads, its cache). The job calls this when the
+// clip is closed, or the copy is cleared or replaced.
+export async function forgetClipInput(file: Blob): Promise<void> {
+ const input = inputs.get(file);
+ inputs.delete(file);
+ if (input) await release(input);
+}
+
+// `p`, or a ClipCancelled the moment `signal` aborts: a cancel never waits on
+// a read or a write the library has in flight. (`p` itself is still handled.)
+function abortable<T>(p: Promise<T>, signal: AbortSignal): Promise<T> {
+ if (signal.aborted) {
+ p.catch(() => {});
+ return Promise.reject(new ClipCancelled());
+ }
+ return new Promise<T>((resolve, reject) => {
+ const onAbort = () => reject(new ClipCancelled());
+ signal.addEventListener("abort", onAbort, { once: true });
+ p.then(
+ (v) => {
+ signal.removeEventListener("abort", onAbort);
+ resolve(v);
+ },
+ (e) => {
+ signal.removeEventListener("abort", onAbort);
+ reject(e);
+ },
+ );
+ });
+}
+
function isReadError(e: unknown): boolean {
const name = (e as { name?: unknown } | null)?.name;
return name === "NotReadableError" || name === "NotFoundError";
@@ -147,7 +187,8 @@ async function audioStartAt(sink: EncodedPacketSink, t: number): Promise<Encoded
// The marks (cue clock) against the file: the output format, where the clip
// really starts, its size — or the one refusal that says why not.
export async function probeClip(file: Blob, cueIn: number, cueOut: number, offset: number): Promise<ProbeResult> {
- const input = openInput(file);
+ const input = inputFor(file);
+ let keep = false;
try {
const family = familyOf(await input.getFormat());
if (!family) return { ok: false, refusal: { kind: "container" } };
@@ -180,6 +221,7 @@ export async function probeClip(file: Blob, cueIn: number, cueOut: number, offse
: await audioStartAt(new EncodedPacketSink(audio!), range.fileIn);
if (!start) return { ok: false, refusal: { kind: "copy" } };
const startTs = Math.min(start.timestamp, range.fileIn);
+ keep = true;
return {
ok: true,
plan: {
@@ -198,7 +240,8 @@ export async function probeClip(file: Blob, cueIn: number, cueOut: number, offse
} catch (e) {
return { ok: false, refusal: refusalFor(e) };
} finally {
- await release(input);
+ // Kept for the save; a refusal lets it go.
+ if (!keep) await forgetClipInput(file);
}
}
@@ -276,30 +319,18 @@ export async function saveClip(
onProgress: (p: SaveProgress) => void,
signal: AbortSignal,
): Promise<SaveResult> {
- const input = openInput(file);
+ const input = inputFor(file);
const guard = target.kind === "disk" ? guardWritable(target.writable) : null;
+ const w = <T,>(p: Promise<T>) => abortable(p, signal);
let output: Output | null = null;
- let stopping: Promise<void> | null = null;
- const stopAll = () =>
- (stopping ??= (async () => {
- await guard?.abort();
- try {
- await output?.cancel();
- } catch {
- /* already finished or failed */
- }
- await release(input);
- })());
- const onAbort = () => void stopAll();
- signal.addEventListener("abort", onAbort, { once: true });
try {
if (signal.aborted) throw new ClipCancelled();
- const video = plan.hasVideo ? await input.getPrimaryVideoTrack() : null;
- const audio = plan.hasAudio ? await input.getPrimaryAudioTrack() : null;
+ const video = plan.hasVideo ? await w(input.getPrimaryVideoTrack()) : null;
+ const audio = plan.hasAudio ? await w(input.getPrimaryAudioTrack()) : null;
const vSink = video ? new EncodedPacketSink(video) : null;
const aSink = audio ? new EncodedPacketSink(audio) : null;
- const key = vSink ? await keyPacketAt(vSink, plan.fileIn) : null;
- const aFirst = aSink ? await audioStartAt(aSink, key ? key.timestamp : plan.fileIn) : null;
+ const key = vSink ? await w(keyPacketAt(vSink, plan.fileIn)) : null;
+ const aFirst = aSink ? await w(audioStartAt(aSink, key ? key.timestamp : plan.fileIn)) : null;
const t0 = key ? key.timestamp : (aFirst?.timestamp ?? plan.startTs);
const total = Math.max(1e-6, plan.fileOut - t0);
@@ -316,59 +347,66 @@ export async function saveClip(
let vMeta: EncodedVideoChunkMetadata | undefined;
let aMeta: EncodedAudioChunkMetadata | undefined;
if (video && key) {
- vSource = new EncodedVideoPacketSource((await video.getCodec()) as VideoCodec);
- const rotation = await video.getRotation();
+ vSource = new EncodedVideoPacketSource((await w(video.getCodec())) as VideoCodec);
+ const rotation = await w(video.getRotation());
output.addVideoTrack(vSource, rotation && (plan.format === "mp4" || plan.format === "mov") ? { rotation } : {});
- vMeta = { decoderConfig: ((await video.getDecoderConfig()) as VideoDecoderConfig | null) ?? undefined };
+ vMeta = { decoderConfig: ((await w(video.getDecoderConfig())) as VideoDecoderConfig | null) ?? undefined };
}
if (audio && aFirst) {
- aSource = new EncodedAudioPacketSource((await audio.getCodec()) as AudioCodec);
+ aSource = new EncodedAudioPacketSource((await w(audio.getCodec())) as AudioCodec);
output.addAudioTrack(aSource);
- aMeta = { decoderConfig: ((await audio.getDecoderConfig()) as AudioDecoderConfig | null) ?? undefined };
+ aMeta = { decoderConfig: ((await w(audio.getDecoderConfig())) as AudioDecoderConfig | null) ?? undefined };
}
if (!vSource && !aSource) throw new Error("nothing to copy");
- await output.start();
+ await w(output.start());
const vIt = vSink && key ? videoPackets(vSink, key, t0, plan.fileOut) : null;
const aIt = aSink && aFirst ? audioPackets(aSink, aFirst, t0, plan.fileOut) : null;
const done: Head<EncodedPacket> = { done: true, value: undefined };
- let v: Head<EncodedPacket> = vIt ? await vIt.next() : done;
- let a: Head<EncodedPacket> = aIt ? await aIt.next() : done;
+ let v: Head<EncodedPacket> = vIt ? await w(vIt.next()) : done;
+ let a: Head<EncodedPacket> = aIt ? await w(aIt.next()) : done;
let reached = 0;
let reported = -Infinity;
while (!v.done || !a.done) {
if (signal.aborted) throw new ClipCancelled();
const takeVideo = !v.done && (a.done || v.value.timestamp <= a.value.timestamp);
if (takeVideo && !v.done) {
- await vSource!.add(v.value, vMeta);
+ await w(vSource!.add(v.value, vMeta));
reached = Math.max(reached, v.value.timestamp + v.value.duration);
- v = await vIt!.next();
+ v = await w(vIt!.next());
} else if (!a.done) {
- await aSource!.add(a.value, aMeta);
+ await w(aSource!.add(a.value, aMeta));
if (!vSource) reached = Math.max(reached, a.value.timestamp + a.value.duration);
- a = await aIt!.next();
+ a = await w(aIt!.next());
}
if (reached - reported >= PROGRESS_STEP_SECONDS) {
reported = reached;
onProgress({ fraction: Math.min(1, reached / total), doneSeconds: Math.min(reached, total), totalSeconds: total, bytes });
}
}
- if (signal.aborted) throw new ClipCancelled();
vSource?.close();
aSource?.close();
- const mimeType = await output.getMimeType();
- await output.finalize();
+ const mimeType = await w(output.getMimeType());
+ await w(output.finalize());
if (signal.aborted) throw new ClipCancelled();
onProgress({ fraction: 1, doneSeconds: total, totalSeconds: total, bytes });
+ // Only now, with the copy complete, does the clip exist as a Blob.
const blob = bufferTarget?.buffer ? new Blob([bufferTarget.buffer], { type: mimeType }) : null;
return { blob, bytes: blob ? blob.size : bytes, mimeType };
} catch (e) {
- await stopAll();
+ // A disk writer is aborted before anything is said; the rest is released
+ // behind (the input first: a read in flight is what the copy waits on).
+ await guard?.abort();
+ const out = output as Output | null;
+ void (async () => {
+ await release(input);
+ await out?.cancel().catch(() => {});
+ })();
if (signal.aborted || e instanceof ClipCancelled || e instanceof InputDisposedError) throw new ClipCancelled();
throw e;
} finally {
- signal.removeEventListener("abort", onAbort);
- await release(input);
+ inputs.delete(file);
+ if (!signal.aborted) await release(input);
}
}