Archilyzer · Source

archilyzer

Archilyzer
git clone https://archilyzer.pages.dev/source/archilyzer.git
Log | Files | Refs | README | LICENSE

commit d2ccd7d076dc31a62bc0a46a78f6cc054dcbc4d2
parent 8c36dacf05a58a6c9b0aa9597c51ff46ab13b1c6
Author: I Mean I'm Just Saying <imeanimjustsaying@kiwifarms.st>
Date:   Thu, 19 Nov 2026 16:28:31 -0500

common: localClipEngine, the stream copy of a visitor's own file

Mediabunny's packet API, not its Conversion (1.45.3 re-encodes any trim
that starts after a track's first timestamp). The clip starts at the
verified key packet at or before the in mark; every track is shifted by the
same T0; video runs, in decode order, to the last packet presented before
the out mark and stops at the next key packet; the two tracks are fed to
the muxer interleaved by timestamp. Read by ranges through BlobSource.
Built in memory (a Blob after finalize, never before) or streamed to a
picked file behind a guard: on cancel or failure the disk writer is
aborted and the muxer's close() can no longer commit a half-written file.

The Node test cuts ffmpeg-made H.264/AAC (with B-frames) and VP9/Opus
files and checks with ffprobe: the source's codecs, a key first frame,
out minus keyframe as the duration, audio and video starting within one
audio frame; marks off the file and a WAV are refused; cancel aborts and
never closes the disk writer.

Co-Authored-By: Claude <noreply@anthropic.com>

Diffstat:
Acommon/lib/localClipEngine.test.ts | 171+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Acommon/lib/localClipEngine.ts | 378+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
2 files changed, 549 insertions(+), 0 deletions(-)

diff --git a/common/lib/localClipEngine.test.ts b/common/lib/localClipEngine.test.ts @@ -0,0 +1,171 @@ +import { test } from "node:test"; +import assert from "node:assert/strict"; +import { execFileSync } from "node:child_process"; +import { mkdtempSync, openAsBlob, rmSync, writeFileSync } from "node:fs"; +import { tmpdir } from "node:os"; +import { join } from "node:path"; +import { ClipCancelled, outputSupport, probeClip, saveClip } from "./localClipEngine"; +import { MkvOutputFormat, MovOutputFormat, Mp4OutputFormat, WebMOutputFormat } from "mediabunny"; + +// Run with: +// pnpm --filter yt-dlp-transcript-common exec tsx --test lib/localClipEngine.test.ts +// +// The stream copy itself, in Node over a Blob of a file ffmpeg makes here +// (keyframes every 2.0 s, B-frames in the H.264 one), checked with ffprobe: +// the codecs are the source's (nothing re-encoded), the clip starts on a key +// frame at the keyframe the probe named, lasts out − keyframe, and its audio +// and video start within one audio frame of each other. Skipped, with the +// reason, on a machine with no ffmpeg. + +function has(cmd: string): boolean { + try { + execFileSync(cmd, ["-version"], { stdio: "ignore" }); + return true; + } catch { + return false; + } +} +const FFMPEG = has("ffmpeg") && has("ffprobe"); +const skip = FFMPEG ? false : "ffmpeg/ffprobe not on PATH"; + +const dir = mkdtempSync(join(tmpdir(), "local-clip-engine-")); +process.on("exit", () => rmSync(dir, { recursive: true, force: true })); + +const SOURCES = { + mp4: [ + "-c:v", "libx264", "-profile:v", "main", "-bf", "2", "-g", "50", "-keyint_min", "50", "-sc_threshold", "0", + "-pix_fmt", "yuv420p", "-c:a", "aac", "-b:a", "64k", + ], + webm: [ + "-c:v", "libvpx-vp9", "-g", "50", "-keyint_min", "50", "-deadline", "realtime", "-cpu-used", "8", "-b:v", "200k", + "-c:a", "libopus", "-b:a", "48k", + ], +} as const; + +function make(kind: keyof typeof SOURCES): string { + const out = join(dir, `source.${kind}`); + execFileSync("ffmpeg", [ + "-v", "error", "-y", + "-f", "lavfi", "-i", "testsrc2=size=160x90:rate=25:duration=12", + "-f", "lavfi", "-i", "sine=frequency=440:sample_rate=48000:duration=12", + ...SOURCES[kind], "-shortest", out, + ]); + return out; +} + +type Probe = { streams: { codec_type: string; codec_name: string; start_time: string; duration?: string }[]; format: { duration: string } }; +function ffprobe(path: string): Probe { + return JSON.parse( + execFileSync("ffprobe", ["-v", "error", "-show_entries", "stream=codec_type,codec_name,start_time,duration:format=duration", "-of", "json", path], { + encoding: "utf8", + }), + ); +} +function firstFrameIsKey(path: string): boolean { + const out = execFileSync( + "ffprobe", + ["-v", "error", "-select_streams", "v:0", "-show_entries", "frame=key_frame", "-read_intervals", "%+#1", "-of", "csv=p=0", path], + { encoding: "utf8" }, + ); + return out.trim().split("\n")[0]?.trim() === "1"; +} + +test("the output support handed to the pure module is the library's own", () => { + const s = outputSupport(); + assert.deepEqual(s.mp4, new Mp4OutputFormat().getSupportedCodecs()); + assert.deepEqual(s.mov, new MovOutputFormat().getSupportedCodecs()); + assert.deepEqual(s.mkv, new MkvOutputFormat().getSupportedCodecs()); + assert.deepEqual(s.webm, new WebMOutputFormat().getSupportedCodecs()); +}); + +for (const kind of ["mp4", "webm"] as const) { + test(`${kind}: a stream copy from the keyframe before the in mark`, { skip }, async () => { + const src = await openAsBlob(make(kind)); + // Marks 5.0 → 9.0 on the cue clock, no offset: the keyframe is 4.0. + const probe = await probeClip(src, 5, 9, 0); + assert.ok(probe.ok, JSON.stringify(probe)); + if (!probe.ok) return; + const { plan } = probe; + assert.equal(plan.format, kind); + assert.equal(plan.ext, `.${kind}`); + assert.ok(Math.abs(plan.startTs - 4) < 0.05, `keyframe at ${plan.startTs}`); + assert.equal(plan.fileIn, 5); + assert.equal(plan.fileOut, 9); + assert.ok(plan.duration !== null && Math.abs(plan.duration - 12) < 0.1); + assert.equal(plan.hasVideo, true); + assert.equal(plan.hasAudio, true); + assert.equal(plan.extraTracks, false); + + const progress: number[] = []; + const saved = await saveClip(src, plan, { kind: "memory" }, (p) => progress.push(p.fraction), new AbortController().signal); + assert.ok(saved.blob); + assert.ok(saved.bytes > 0); + assert.equal(saved.blob!.size, saved.bytes); + assert.ok(progress.length > 0 && progress.at(-1)! >= 0.95, `progress ${progress.at(-1)}`); + const out = join(dir, `clip.${kind}`); + writeFileSync(out, Buffer.from(await saved.blob!.arrayBuffer())); + + const info = ffprobe(out); + const v = info.streams.find((s) => s.codec_type === "video")!; + const a = info.streams.find((s) => s.codec_type === "audio")!; + // Copied, not re-encoded. + assert.equal(v.codec_name, kind === "mp4" ? "h264" : "vp9"); + assert.equal(a.codec_name, kind === "mp4" ? "aac" : "opus"); + assert.ok(firstFrameIsKey(out), "the first frame is a key frame"); + // out − keyframe = 5.0 s, give or take a frame. + const duration = Number(info.format.duration); + assert.ok(Math.abs(duration - 5) < 0.12, `duration ${duration}`); + // A/V in step at the cut: the two start within one audio frame (AAC 1024 + // samples at 48 kHz ≈ 21.3 ms; Opus 20 ms). + const gap = Math.abs(Number(v.start_time) - Number(a.start_time)); + assert.ok(gap <= 0.0215, `video starts at ${v.start_time}, audio at ${a.start_time}`); + }); +} + +test("an offset moves the in mark onto a keyframe: the clip starts at the mark", { skip }, async () => { + const src = await openAsBlob(make("webm")); + // Cue 5.0 + offset 1 = file 6.0, a keyframe. + const probe = await probeClip(src, 5, 9, 1); + assert.ok(probe.ok); + if (!probe.ok) return; + assert.equal(probe.plan.fileIn, 6); + assert.equal(probe.plan.fileOut, 10); + assert.ok(Math.abs(probe.plan.startTs - 6) < 0.05, `keyframe at ${probe.plan.startTs}`); +}); + +test("marks outside the file, and a file that is not a container it reads, are refused", { skip }, async () => { + const src = await openAsBlob(make("mp4")); + const outside = await probeClip(src, 20, 25, 0); + assert.deepEqual(outside.ok ? null : outside.refusal.kind, "outside"); + const wav = join(dir, "tone.wav"); + execFileSync("ffmpeg", ["-v", "error", "-y", "-f", "lavfi", "-i", "sine=duration=2", wav]); + const notOurs = await probeClip(await openAsBlob(wav), 0.5, 1.5, 0); + assert.deepEqual(notOurs.ok ? null : notOurs.refusal, { kind: "container" }); +}); + +test("cancel stops the copy, aborts the disk writer and never closes (commits) it", { skip }, async () => { + const src = await openAsBlob(make("mp4")); + const probe = await probeClip(src, 1, 11, 0); + assert.ok(probe.ok); + if (!probe.ok) return; + const calls: string[] = []; + const writable = new WritableStream({ + async write() { + calls.push("write"); + await new Promise((r) => setTimeout(r, 20)); + }, + close() { + calls.push("close"); + }, + abort() { + calls.push("abort"); + }, + }); + const ac = new AbortController(); + const run = saveClip(src, probe.plan, { kind: "disk", writable }, (p) => { + if (p.fraction > 0.2) ac.abort(); + }, ac.signal); + await assert.rejects(run, ClipCancelled); + assert.ok(calls.includes("abort"), calls.join(",")); + assert.ok(!calls.includes("close"), calls.join(",")); +}); diff --git a/common/lib/localClipEngine.ts b/common/lib/localClipEngine.ts @@ -0,0 +1,378 @@ +// THE STREAM COPY (lane browser-clip): a part of the visitor's own file, cut +// in the browser with Mediabunny (MPL-2.0; export/THIRD-PARTY-NOTICES.md). +// +// Loaded ONLY through lib/localClipLoader.ts's dynamic import, when a clip is +// asked for, so the site's first load does not carry the library. +// +// Why not Mediabunny's Conversion API: in 1.45.3 any trim start after a +// track's first timestamp forces a re-encode (conversion.ts, needsTranscode / +// needsResample). So the copy is done here with the packet API: +// - the start is the verified key packet at or before the in mark (T0), and +// every track is shifted by the same T0, so A/V keep their timing; +// - video: every packet, in decode order, up to the last one presented +// before the out mark (the frames it depends on come before it in decode +// order), stopping at the first key packet past the mark; packets +// presented before T0 (open-GOP leading pictures) are dropped; +// - audio: from the packet at T0 to the out mark, nothing before T0; +// - the two are fed to the muxer interleaved by timestamp, so it never holds +// a whole track in memory. +// The file is read by ranges (BlobSource: File.slice, an 8 MiB cache), never +// whole. Nothing here reaches the network or any storage +// (components/LocalFilePicker.test.ts reads this source). + +import { + BlobSource, + BufferTarget, + EncodedAudioPacketSource, + EncodedPacketSink, + EncodedVideoPacketSource, + Input, + InputDisposedError, + MATROSKA, + MP4, + MkvOutputFormat, + MovOutputFormat, + Mp4OutputFormat, + Output, + QTFF, + StreamTarget, + UnsupportedInputFormatError, + WEBM, + WebMOutputFormat, + type AudioCodec, + type EncodedPacket, + type InputFormat, + type OutputFormat, + type StreamTargetChunk, + type VideoCodec, +} from "mediabunny"; +import { + chooseOutput, + estimateBytes, + fileRange, + type ContainerFamily, + type OutputFormatName, + type OutputSupport, + type Refusal, +} from "./localClip"; + +const FORMATS = [MP4, QTFF, MATROSKA, WEBM]; +const VERIFY = { verifyKeyPackets: true } as const; +// How much media time passes between two progress reports. +const PROGRESS_STEP_SECONDS = 0.25; + +export type ClipPlan = { + format: OutputFormatName; + ext: string; + hasVideo: boolean; + hasAudio: boolean; + // The file has tracks beyond the main video and audio; they are left out. + extraTracks: boolean; + // The file's length in seconds, when the library could tell. + duration: number | null; + // The marks in file time, and where the clip really starts (file time). + fileIn: number; + fileOut: number; + startTs: number; + estimate: number; +}; + +export type ProbeResult = { ok: true; plan: ClipPlan } | { ok: false; refusal: Refusal }; + +export type SaveTarget = + | { kind: "memory" } + // A file the visitor picked (showSaveFilePicker's createWritable()). + | { kind: "disk"; writable: WritableStream<StreamTargetChunk> }; + +export type SaveProgress = { fraction: number; doneSeconds: number; totalSeconds: number; bytes: number }; + +export type SaveResult = { blob: Blob | null; bytes: number; mimeType: string }; + +export class ClipCancelled extends Error { + constructor() { + super("The clip was cancelled."); + this.name = "ClipCancelled"; + } +} + +// What each output format can hold, from the library itself. +export function outputSupport(): OutputSupport { + return { + mp4: new Mp4OutputFormat().getSupportedCodecs(), + mov: new MovOutputFormat().getSupportedCodecs(), + mkv: new MkvOutputFormat().getSupportedCodecs(), + webm: new WebMOutputFormat().getSupportedCodecs(), + }; +} + +function familyOf(format: InputFormat): ContainerFamily | null { + // WEBM is a MATROSKA, so it is asked first. + if (format === WEBM) return "webm"; + if (format === MATROSKA) return "mkv"; + if (format === QTFF) return "mov"; + if (format === MP4) return "mp4"; + return null; +} + +function openInput(file: Blob): Input { + return new Input({ source: new BlobSource(file), formats: FORMATS }); +} + +// dispose() on an input whose format was never found leaves an unhandled +// rejection behind (1.45.3: it chains .then on the failed demuxer promise), so +// such an input is left to the library's own finalizer, which frees its reads. +async function release(input: Input): Promise<void> { + if (await input.canRead().catch(() => false)) input.dispose(); +} + +function isReadError(e: unknown): boolean { + const name = (e as { name?: unknown } | null)?.name; + return name === "NotReadableError" || name === "NotFoundError"; +} + +function refusalFor(e: unknown): Refusal { + if (e instanceof UnsupportedInputFormatError) return { kind: "container" }; + if (isReadError(e)) return { kind: "read" }; + return { kind: "copy" }; +} + +async function keyPacketAt(sink: EncodedPacketSink, t: number): Promise<EncodedPacket | null> { + return (await sink.getKeyPacket(t, VERIFY)) ?? (await sink.getFirstKeyPacket(VERIFY)); +} + +async function audioStartAt(sink: EncodedPacketSink, t: number): Promise<EncodedPacket | null> { + return (await sink.getPacket(t)) ?? (await sink.getFirstPacket()); +} + +// 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); + try { + const family = familyOf(await input.getFormat()); + if (!family) return { ok: false, refusal: { kind: "container" } }; + const tracks = await input.getTracks(); + const video = await input.getPrimaryVideoTrack(); + const audio = await input.getPrimaryAudioTrack(); + const videoCodec = video ? ((await video.getCodec()) ?? "") : null; + const audioCodec = audio ? ((await audio.getCodec()) ?? "") : null; + const choice = chooseOutput(family, videoCodec, audioCodec, outputSupport()); + if (!choice.ok) return { ok: false, refusal: { kind: "codec", track: choice.track, codec: choice.codec } }; + + let duration: number | null = null; + try { + const d = await input.computeDuration(); + duration = Number.isFinite(d) && d > 0 ? d : null; + } catch (e) { + if (isReadError(e)) throw e; + } + const range = fileRange(cueIn, cueOut, offset, duration); + if (!range.ok) { + return { + ok: false, + refusal: + range.reason === "outside" ? { kind: "outside", duration: duration ?? 0, offset } : { kind: "short" }, + }; + } + + const start = video + ? await keyPacketAt(new EncodedPacketSink(video), range.fileIn) + : await audioStartAt(new EncodedPacketSink(audio!), range.fileIn); + if (!start) return { ok: false, refusal: { kind: "copy" } }; + const startTs = Math.min(start.timestamp, range.fileIn); + return { + ok: true, + plan: { + format: choice.format, + ext: choice.ext, + hasVideo: video !== null, + hasAudio: audio !== null, + extraTracks: tracks.length > (video ? 1 : 0) + (audio ? 1 : 0), + duration, + fileIn: range.fileIn, + fileOut: range.fileOut, + startTs, + estimate: estimateBytes(file.size, duration, range.fileOut - startTs), + }, + }; + } catch (e) { + return { ok: false, refusal: refusalFor(e) }; + } finally { + await release(input); + } +} + +const shift = (p: EncodedPacket, t0: number) => p.clone({ timestamp: Math.max(0, p.timestamp - t0) }); + +async function* videoPackets(sink: EncodedPacketSink, key: EncodedPacket, t0: number, out: number) { + // Packets presented at or after the out mark, held until a later packet (in + // decode order) shows they are needed: a B-frame before the mark refers to + // the P-frame after it. + const held: EncodedPacket[] = []; + for await (const p of sink.packets(key, undefined, VERIFY)) { + if (p.timestamp < out) { + for (const h of held) yield h; + held.length = 0; + if (p.timestamp >= t0) yield shift(p, t0); + } else { + if (p.type === "key" && p.sequenceNumber !== key.sequenceNumber) return; + held.push(shift(p, t0)); + } + } +} + +async function* audioPackets(sink: EncodedPacketSink, first: EncodedPacket, t0: number, out: number) { + for await (const p of sink.packets(first)) { + if (p.timestamp >= out) return; + if (p.timestamp < t0) continue; + yield shift(p, t0); + } +} + +function outputFormat(name: OutputFormatName, inMemory: boolean): OutputFormat { + // In memory, MP4/MOV put their index first (better for posting the file); + // streamed to disk, last (bounded memory). + const fastStart = inMemory ? ("in-memory" as const) : false; + if (name === "mp4") return new Mp4OutputFormat({ fastStart }); + if (name === "mov") return new MovOutputFormat({ fastStart }); + if (name === "webm") return new WebMOutputFormat(); + return new MkvOutputFormat(); +} + +// The disk writer behind a door we hold: on cancel or failure the writer is +// ABORTED (a picked file's changes are discarded), and the muxer's later +// close() is then a no-op — it would otherwise commit a half-written file. +function guardWritable(dest: WritableStream<StreamTargetChunk>) { + const writer = dest.getWriter(); + let stopped = false; + const stream = new WritableStream<StreamTargetChunk>({ + write: (chunk) => (stopped ? undefined : writer.write(chunk)), + close: () => (stopped ? undefined : writer.close()), + abort: (reason) => { + if (stopped) return; + stopped = true; + return writer.abort(reason); + }, + }); + return { + stream, + abort: async () => { + if (stopped) return; + stopped = true; + await writer.abort().catch(() => {}); + }, + }; +} + +type Head<T> = IteratorResult<T, void>; + +// Copy the planned clip into the target. Resolves with the clip (a Blob when +// built in memory); rejects with ClipCancelled when `signal` aborts, having +// aborted a disk writer and released everything. +export async function saveClip( + file: Blob, + plan: ClipPlan, + target: SaveTarget, + onProgress: (p: SaveProgress) => void, + signal: AbortSignal, +): Promise<SaveResult> { + const input = openInput(file); + const guard = target.kind === "disk" ? guardWritable(target.writable) : null; + 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 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 t0 = key ? key.timestamp : (aFirst?.timestamp ?? plan.startTs); + const total = Math.max(1e-6, plan.fileOut - t0); + + const bufferTarget = target.kind === "memory" ? new BufferTarget() : null; + const outTarget = bufferTarget ?? new StreamTarget(guard!.stream, { chunked: true }); + let bytes = 0; + outTarget.on("write", ({ end }) => { + if (end > bytes) bytes = end; + }); + output = new Output({ format: outputFormat(plan.format, bufferTarget !== null), target: outTarget }); + + let vSource: EncodedVideoPacketSource | null = null; + let aSource: EncodedAudioPacketSource | null = null; + let vMeta: EncodedVideoChunkMetadata | undefined; + let aMeta: EncodedAudioChunkMetadata | undefined; + if (video && key) { + vSource = new EncodedVideoPacketSource((await video.getCodec()) as VideoCodec); + const rotation = await video.getRotation(); + output.addVideoTrack(vSource, rotation && (plan.format === "mp4" || plan.format === "mov") ? { rotation } : {}); + vMeta = { decoderConfig: ((await video.getDecoderConfig()) as VideoDecoderConfig | null) ?? undefined }; + } + if (audio && aFirst) { + aSource = new EncodedAudioPacketSource((await audio.getCodec()) as AudioCodec); + output.addAudioTrack(aSource); + aMeta = { decoderConfig: ((await audio.getDecoderConfig()) as AudioDecoderConfig | null) ?? undefined }; + } + if (!vSource && !aSource) throw new Error("nothing to copy"); + await 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 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); + reached = Math.max(reached, v.value.timestamp + v.value.duration); + v = await vIt!.next(); + } else if (!a.done) { + await aSource!.add(a.value, aMeta); + if (!vSource) reached = Math.max(reached, a.value.timestamp + a.value.duration); + a = await 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(); + if (signal.aborted) throw new ClipCancelled(); + onProgress({ fraction: 1, doneSeconds: total, totalSeconds: total, bytes }); + const blob = bufferTarget?.buffer ? new Blob([bufferTarget.buffer], { type: mimeType }) : null; + return { blob, bytes: blob ? blob.size : bytes, mimeType }; + } catch (e) { + await stopAll(); + if (signal.aborted || e instanceof ClipCancelled || e instanceof InputDisposedError) throw new ClipCancelled(); + throw e; + } finally { + signal.removeEventListener("abort", onAbort); + await release(input); + } +} + +// What the panel says when a save fails for a reason other than a cancel. +export function saveFailure(e: unknown): Refusal { + return isReadError(e) ? { kind: "read" } : { kind: "copy" }; +}