Record your screen, ship a demo. Free and open-source, GPU-accelerated, no watermarks, no subscriptions. Windows, macOS, Linux. Actively maintained.
TypeScript cross-platformelectronffmpegopen-sourceproduct-demorustscreen-capturescreen-recorderscreen-recordingscreen-studioscreencastspeech-to-texttypescriptvideo-editingvideo-editorwaylandwgpuwhisper
refactor(exporter): delete the web MP4 pipeline the native path replaced
Etienne Lescotcf0241ae08e2
diff --git a/electron/main.ts b/electron/main.tsindex 199782072..a0cb07dca 100644--- a/electron/main.ts+++ b/electron/main.ts@@ -21,8 +21,6 @@ import {import { mainT, setMainLocale } from "./i18n";import { getSelectedDesktopSource, registerIpcHandlers } from "./ipc/handlers";import { installMainProcessErrorGuards } from "./main-process-errors";-import { registerFfmpegExportIpc } from "./media/ffmpegExportIpc";-import { cancelAllExports } from "./media/ffmpegExportService";import { acquireStableInstanceLock } from "./singleInstanceLock";import { registerSttIpc } from "./stt";import {@@ -507,9 +505,6 @@ app.on("activate", () => {app.on("will-quit", () => {unregisterAllGlobalShortcuts();stableInstanceLock?.release();- // Kill any ffmpeg still encoding, or quitting mid-export leaves it orphaned- // holding the output file. Fire-and-forget: will-quit cannot await.- void cancelAllExports();});const appReady = hasSingleInstanceLock ? app.whenReady() : null;@@ -631,7 +626,6 @@ appReady?.then(async () => {showMainWindow();}- registerFfmpegExportIpc();registerIpcHandlers(createEditorWindowWrapper,createSourceSelectorWindowWrapper,diff --git a/electron/media/__fixtures__/fakeFfmpeg.cjs b/electron/media/__fixtures__/fakeFfmpeg.cjsdeleted file mode 100644index dcdc2c936..000000000--- a/electron/media/__fixtures__/fakeFfmpeg.cjs+++ /dev/null@@ -1,49 +0,0 @@-// A stand-in for ffmpeg so ffmpegEncodeSession's tests stay hermetic — the real-// binary is not bundled yet, and we do not want tests that depend on a machine's-// encoders. Behaviour is driven by FAKE_FFMPEG_MODE:-//-// ok drain stdin, exit 0-// fail drain stdin, print a known message + the byte count, exit 3-// count drain stdin, print the byte count, exit 3 (so the count reaches the-// test through the session's stderr tail — the only channel it exposes)-// progress emit frame=N progress lines while draining, exit 0-// hang drain stdin and never exit (for cancel())-//-// It ignores the ffmpeg argv it is handed; buildFfmpegArgs is asserted separately.-const mode = process.env.FAKE_FFMPEG_MODE || "ok";--let bytes = 0;-let frames = 0;--process.stdin.on("data", (chunk) => {- bytes += chunk.length;- if (mode === "progress") {- // Roughly one progress line per MiB, so a test writing a few MB sees several.- const next = Math.floor(bytes / (1024 * 1024));- if (next > frames) {- frames = next;- process.stderr.write(`frame=${frames}\nfps=60\n`);- }- }-});--process.stdin.on("end", () => {- if (mode === "hang") return;- if (mode === "fail") {- process.stderr.write(`fake ffmpeg: deliberate failure for the test BYTES=${bytes}\n`);- process.exit(3);- }- if (mode === "count") {- process.stderr.write(`BYTES=${bytes}\n`);- process.exit(3);- }- process.exit(0);-});--// `hang` must survive stdin ending: keep the loop alive until we are killed.-if (mode === "hang") {- setInterval(() => {- // Nothing to do — an empty timer is exactly what keeps this process- // alive so cancel() has something real to kill.- }, 1 << 30);-}diff --git a/electron/media/ffmpegCapabilities.test.ts b/electron/media/ffmpegCapabilities.test.tsdeleted file mode 100644index c3e23d67b..000000000--- a/electron/media/ffmpegCapabilities.test.ts+++ /dev/null@@ -1,379 +0,0 @@-import { describe, expect, it } from "vitest";-import {- candidateFfmpegPaths,- candidateVideoEncoders,- FFMPEG_BINARY_NAME,- isLgplBuild,- parseAvailableEncoders,- pickWorkingEncoder,- smokeTestArgs,-} from "./ffmpegCapabilities";--// Realistic slice of `ffmpeg -encoders` output (truncated for the test):-// header, capability description, separator, then a mix of video / audio /-// subtitle / data encoders. The parser must return every real encoder name-// and nothing from the header / separator / description rows.-const REALISTIC_ENCODERS_OUTPUT = [- "Encoders:",- " V..... = Video",- " A..... = Audio",- " S..... = Subtitle",- " D..... = Data",- "------",- " V..... h264_qsv H.264 / AVC (Intel Quick Sync Video acceleration) (codec h264)",- " V....D h264_amf AMD AMF H.264 Encoder (codec h264)",- " V....D h264_nvenc NVIDIA NVENC H.264 encoder (codec h264)",- " V....D libx264 libx264 H.264 / AVC / MPEG-4 AVC (codec h264)",- " A....D aac AAC (Advanced Audio Coding)",- " D..... bintext Binary text",- " S..... ass ASS (Advanced SSA Subtitle)",- " V..... h264_videotoolbox VideoToolbox H.264 Encoder (codec h264)",- " V....D h264_vaapi H.264 / AVC / MPEG-4 AVC / MPEG-4 part 10 (codec h264) (deprecated)",-].join("\n");--describe("ffmpegCapabilities", () => {- describe("parseAvailableEncoders", () => {- it("parses every encoder from the realistic ffmpeg -encoders fixture", () => {- const encoders = parseAvailableEncoders(REALISTIC_ENCODERS_OUTPUT);- expect(encoders.has("h264_qsv")).toBe(true);- expect(encoders.has("h264_amf")).toBe(true);- expect(encoders.has("h264_nvenc")).toBe(true);- expect(encoders.has("libx264")).toBe(true);- expect(encoders.has("aac")).toBe(true);- expect(encoders.has("ass")).toBe(true);- expect(encoders.has("bintext")).toBe(true);- expect(encoders.has("h264_videotoolbox")).toBe(true);- expect(encoders.has("h264_vaapi")).toBe(true);- });-- it("ignores header, separator and capability-description rows", () => {- const encoders = parseAvailableEncoders(REALISTIC_ENCODERS_OUTPUT);- // Header word itself must not be treated as an encoder.- expect(encoders.has("Encoders")).toBe(false);- // Second token of description lines is "=", never added.- expect(encoders.has("=")).toBe(false);- // Capability nouns at the end of description lines must not leak.- expect(encoders.has("Video")).toBe(false);- expect(encoders.has("Audio")).toBe(false);- expect(encoders.has("Subtitle")).toBe(false);- expect(encoders.has("Data")).toBe(false);- // Exactly the 9 real encoders from the fixture, nothing else.- expect(encoders.size).toBe(9);- });-- it("returns an empty set for empty / no-encoder input", () => {- expect(parseAvailableEncoders("").size).toBe(0);- expect(parseAvailableEncoders("\n").size).toBe(0);- expect(parseAvailableEncoders("Encoders:\n------").size).toBe(0);- });-- it("tolerates leading whitespace and - in flag positions", () => {- const stdout = [- " V----D h264_nvenc something",- "\tA....D aac\t\t\tAAC (Advanced Audio Coding)",- " V....D libx264 libx264 (codec h264)",- ].join("\n");- const encoders = parseAvailableEncoders(stdout);- expect(encoders.has("h264_nvenc")).toBe(true);- expect(encoders.has("aac")).toBe(true);- expect(encoders.has("libx264")).toBe(true);- });-- it("accepts CRLF line endings", () => {- const encoders = parseAvailableEncoders("V....D h264_nvenc\r\nA....D aac\r\n");- expect(encoders.has("h264_nvenc")).toBe(true);- expect(encoders.has("aac")).toBe(true);- expect(encoders.size).toBe(2);- });- });-- describe("candidateVideoEncoders", () => {- // libopenh264 is bundled in our LGPL ffmpeg, so it is present everywhere and- // sits at the floor of every list. There is no WebCodecs path any more, so a- // machine with no hardware must still export - just slowly.- const SW = "libopenh264";-- it("win32 orders nvidia, intel, amd, then the OS, then software", () => {- const all = new Set(["h264_nvenc", "h264_qsv", "h264_amf", "h264_mf", SW]);- expect(candidateVideoEncoders(all, "win32")).toEqual([- "h264_nvenc",- "h264_qsv",- "h264_amf",- "h264_mf",- SW,- ]);- });-- it("drops what the build does not carry", () => {- expect(candidateVideoEncoders(new Set(["h264_amf", SW]), "win32")).toEqual(["h264_amf", SW]);- });-- it("darwin is videotoolbox then software", () => {- expect(candidateVideoEncoders(new Set(["h264_videotoolbox", SW]), "darwin")).toEqual([- "h264_videotoolbox",- SW,- ]);- });-- it("linux is nvenc, vaapi, then software", () => {- expect(candidateVideoEncoders(new Set(["h264_nvenc", "h264_vaapi", SW]), "linux")).toEqual([- "h264_nvenc",- "h264_vaapi",- SW,- ]);- });-- it("falls back to software on a platform we have no list for", () => {- expect(candidateVideoEncoders(new Set([SW]), "freebsd")).toEqual([SW]);- });-- it("never offers libx264, the fastest thing we measured, because it is GPL", () => {- expect(candidateVideoEncoders(new Set(["libx264", "libx265"]), "win32")).toEqual([]);- });- });-- describe("pickWorkingEncoder", () => {- const ALL = new Set(["h264_nvenc", "h264_qsv", "h264_amf", "h264_mf", "libopenh264"]);- const encoderIn = (args: string[]) => args[args.indexOf("-c:v") + 1];-- it("skips encoders the build carries but the machine cannot run", async () => {- // The real failure this exists to prevent: our bundled binary lists- // nvenc/qsv/amf on every machine, so on an AMD box nvenc is present and- // dies with "Cannot load nvcuda.dll". Presence is not capability.- const works = new Set(["h264_amf", "h264_mf", "libopenh264"]);- const picked = await pickWorkingEncoder(ALL, "win32", (args) => works.has(encoderIn(args)));- expect(picked).toBe("h264_amf");- });-- it("takes the first that works, in preference order", async () => {- const picked = await pickWorkingEncoder(ALL, "win32", () => true);- expect(picked).toBe("h264_nvenc");- });-- it("lands on software when no hardware encoder runs", async () => {- const picked = await pickWorkingEncoder(- ALL,- "win32",- (args) => encoderIn(args) === "libopenh264",- );- expect(picked).toBe("libopenh264");- });-- it("returns null when nothing works - the bundled ffmpeg is broken, not the machine", async () => {- expect(await pickWorkingEncoder(ALL, "win32", () => false)).toBeNull();- });-- it("stops probing once one passes", async () => {- const tried: string[] = [];- await pickWorkingEncoder(ALL, "win32", (args) => {- tried.push(encoderIn(args));- return encoderIn(args) === "h264_qsv";- });- expect(tried).toEqual(["h264_nvenc", "h264_qsv"]);- });-- it("awaits an async probe", async () => {- const picked = await pickWorkingEncoder(ALL, "win32", async (args) => {- await new Promise((r) => setTimeout(r, 1));- return encoderIn(args) === "h264_mf";- });- expect(picked).toBe("h264_mf");- });- });-- describe("smokeTestArgs", () => {- it("encodes one synthetic frame to nowhere, so it touches no files", () => {- const a = smokeTestArgs("h264_amf");- expect(a[a.indexOf("-f") + 1]).toBe("lavfi");- expect(a[a.indexOf("-c:v") + 1]).toBe("h264_amf");- expect(a[a.indexOf("-frames:v") + 1]).toBe("1");- expect(a.slice(-3)).toEqual(["-f", "null", "-"]);- });- });-- describe("isLgplBuild", () => {- it("rejects a build configured with --enable-gpl", () => {- const buildConf = "--prefix=/usr --enable-shared --enable-gpl --enable-version3";- expect(isLgplBuild(buildConf)).toBe(false);- });-- it("rejects a build configured with --enable-nonfree", () => {- const buildConf = "--prefix=/usr --enable-shared --enable-nonfree";- expect(isLgplBuild(buildConf)).toBe(false);- });-- it("accepts a clean LGPL build (no gpl or nonfree)", () => {- const buildConf = "--prefix=/usr --enable-shared --enable-version3 --enable-libvpx";- expect(isLgplBuild(buildConf)).toBe(true);- });-- it("does not match --enable-gpl as a substring of another flag", () => {- // gpl-something is a different flag entirely - not the one we care about.- expect(isLgplBuild("--enable-gpl-something")).toBe(true);- expect(isLgplBuild("--enable-nonfree-extra")).toBe(true);- });-- it("accepts the ffmpeg banner `configuration:` line for a clean build", () => {- const banner = "configuration: --prefix=/usr --enable-shared --enable-version3";- expect(isLgplBuild(banner)).toBe(true);- });-- it("rejects the ffmpeg banner `configuration:` line when --enable-gpl is present", () => {- const banner = "configuration: --prefix=/usr --enable-gpl --enable-version3 --enable-libx264";- expect(isLgplBuild(banner)).toBe(false);- });-- it("rejects the ffmpeg banner `configuration:` line when --enable-nonfree is present", () => {- const banner = "configuration: --enable-shared --enable-nonfree --enable-libfdk-aac";- expect(isLgplBuild(banner)).toBe(false);- });-- it("returns true for an empty / whitespace-only build configuration", () => {- expect(isLgplBuild("")).toBe(true);- expect(isLgplBuild(" ")).toBe(true);- });- });-- describe("candidateFfmpegPaths", () => {- it("prepends the env override when set", () => {- const paths = candidateFfmpegPaths({- here: "/fake/repo",- platform: "linux",- arch: "x64",- envOverride: "/custom/ffmpeg",- });- expect(paths[0]).toBe("/custom/ffmpeg");- expect(paths).toContain("/fake/repo/electron/native/bin/linux-x64/ffmpeg");- });-- it("emits ffmpeg.exe under <platform>-<arch> on win32", () => {- const paths = candidateFfmpegPaths({- here: "C:/fake/repo",- platform: "win32",- arch: "x64",- });- const resolved = paths.map((p) => p.replace(/\\/g, "/"));- expect(resolved).toContain("C:/fake/repo/electron/native/bin/win32-x64/ffmpeg.exe");- expect(resolved).toContain("C:/fake/repo/electron/native/bin/ffmpeg.exe");- });-- it("emits bare ffmpeg on linux (no .exe anywhere)", () => {- const paths = candidateFfmpegPaths({- here: "/fake/repo",- platform: "linux",- arch: "x64",- });- expect(paths).toContain("/fake/repo/electron/native/bin/linux-x64/ffmpeg");- expect(paths).toContain("/fake/repo/electron/native/bin/ffmpeg");- expect(paths.every((p) => !p.endsWith(".exe"))).toBe(true);- });-- it("emits bare ffmpeg on darwin (no .exe anywhere)", () => {- const paths = candidateFfmpegPaths({- here: "/fake/repo",- platform: "darwin",- arch: "arm64",- });- expect(paths).toContain("/fake/repo/electron/native/bin/darwin-arm64/ffmpeg");- expect(paths.every((p) => !p.endsWith(".exe"))).toBe(true);- });-- it("orders candidates: env > appPath > resourcesPath > here-tagged > here-bare", () => {- const paths = candidateFfmpegPaths({- here: "/fake/repo",- platform: "linux",- arch: "x64",- appPath: "/app",- resourcesPath: "/res",- envOverride: "/env",- });- // Priority 1: env override comes first.- expect(paths[0]).toBe("/env");- // Priority 2: appPath-tagged candidate is present.- expect(paths).toContain("/app/electron/native/bin/linux-x64/ffmpeg");- // Priority 3: resourcesPath-tagged candidate is present.- expect(paths).toContain("/res/electron/native/bin/linux-x64/ffmpeg");- // Priority 4: here-tagged candidate is present.- expect(paths).toContain("/fake/repo/electron/native/bin/linux-x64/ffmpeg");- // Priority 5: cross-arch fallthrough with no platform tag is present.- expect(paths).toContain("/fake/repo/electron/native/bin/ffmpeg");-- // Order is consistent across the layered candidates.- const envIdx = paths.indexOf("/env");- const appIdx = paths.indexOf("/app/electron/native/bin/linux-x64/ffmpeg");- const resIdx = paths.indexOf("/res/electron/native/bin/linux-x64/ffmpeg");- const hereIdx = paths.indexOf("/fake/repo/electron/native/bin/linux-x64/ffmpeg");- const bareIdx = paths.indexOf("/fake/repo/electron/native/bin/ffmpeg");- expect(envIdx).toBeLessThan(appIdx);- expect(appIdx).toBeLessThan(resIdx);- expect(resIdx).toBeLessThan(hereIdx);- expect(hereIdx).toBeLessThan(bareIdx);- });-- it("omits appPath / resourcesPath candidates when those inputs are null", () => {- const paths = candidateFfmpegPaths({- here: "/fake/repo",- platform: "linux",- arch: "x64",- appPath: null,- resourcesPath: null,- });- expect(paths.some((p) => p.startsWith("/app/"))).toBe(false);- expect(paths.some((p) => p.startsWith("/res/"))).toBe(false);- expect(paths).toContain("/fake/repo/electron/native/bin/linux-x64/ffmpeg");- expect(paths).toContain("/fake/repo/electron/native/bin/ffmpeg");- });-- it("skips platform-tagged candidates when platform or arch is missing", () => {- const paths = candidateFfmpegPaths({ here: "/fake/repo" });- // Only the cross-arch fallthrough is emitted without a platform tag.- expect(paths).toEqual(["/fake/repo/electron/native/bin/ffmpeg"]);- });- });-- describe("FFMPEG_BINARY_NAME", () => {- it("returns ffmpeg.exe on win32", () => {- expect(FFMPEG_BINARY_NAME("win32")).toBe("ffmpeg.exe");- });-- it("returns bare ffmpeg on every other platform", () => {- expect(FFMPEG_BINARY_NAME("linux")).toBe("ffmpeg");- expect(FFMPEG_BINARY_NAME("darwin")).toBe("ffmpeg");- expect(FFMPEG_BINARY_NAME("freebsd")).toBe("ffmpeg");- });- });-});--// Added after research surfaced the real GPL/nonfree surface (ffmpeg.org/legal.html):-// checking --enable-gpl alone is not the whole gate.-describe("isLgplBuild — GPL externals and nonfree traps", () => {- it("rejects each GPL-only external library", () => {- for (const lib of [- "libx264",- "libx265",- "libxvid",- "libvidstab",- "librubberband",- "frei0r",- "avisynth",- ]) {- expect(isLgplBuild(`--prefix=/x --enable-${lib} --enable-shared`)).toBe(false);- }- });-- it("rejects libfdk-aac — nonfree makes the binary unredistributable, and we encode AAC", () => {- expect(isLgplBuild("--prefix=/x --enable-libfdk-aac")).toBe(false);- });-- it("accepts a hardware-only LGPL build with the native aac encoder", () => {- expect(- isLgplBuild(- "--prefix=/x --enable-shared --enable-amf --enable-nvenc --enable-libsvtav1 --enable-videotoolbox",- ),- ).toBe(true);- });-- it("does not false-positive on a lib whose name merely contains a GPL one", () => {- expect(isLgplBuild("--enable-libx264-shim-not-real")).toBe(true);- });-});diff --git a/electron/media/ffmpegCapabilities.ts b/electron/media/ffmpegCapabilities.tsdeleted file mode 100644index 96d58823a..000000000--- a/electron/media/ffmpegCapabilities.ts+++ /dev/null@@ -1,301 +0,0 @@-/**- * Join path segments with forward slashes. Electron's docs and Node's- * own internals both accept forward slashes on every platform, and using- * `node:path`'s `path.join` on Windows would silently rewrite the- * forward-slashed inputs the tests pass into backslashes - breaking the- * pure-function contract where identical inputs produce identical outputs- * regardless of host OS.- */-function joinPosix(...segments: string[]): string {- return segments.filter((s) => s.length > 0).join("/");-}--/**- * Resolves the bundled ffmpeg binary for the export path's hardware-accelerated- * encoder. The actual subprocess, muxing and bitstream handling live in a- * separate module; this file only does pure capability detection so the- * streaming layer can stay focused on I/O and the tests can run without ever- * spawning a process.- *- * The resolution pattern mirrors electron/stt/gpuDetector.ts: a single- * per-platform binary name (Win32 needs the .exe suffix so the OS image- * loader can resolve it) and a layered set of candidate paths so the same- * code works in npm run dev, the electron-builder staging tree and the- * packaged installer.- */--/** ffmpeg encoders we know how to drive, best-first per platform. */-export type VideoEncoderId =- | "h264_nvenc"- | "h264_qsv"- | "h264_amf"- | "h264_videotoolbox"- | "h264_vaapi"- /** Media Foundation: reaches AMD/Intel/NVIDIA through the OS rather than a- * vendor SDK. A useful net when the vendor encoder is missing or broken. */- | "h264_mf"- /** Cisco's OpenH264 — BSD, so LGPL-safe, and present in our bundled build.- * Software, therefore slow; it exists so that a machine with no usable- * hardware encoder can still export rather than being told it cannot. */- | "libopenh264";--/**- * Conventional binary name. Win32's loader requires the .exe suffix; on- * every other platform ffmpeg is just ffmpeg. The argument exists so tests- * can drive the function without mutating process.platform.- */-export const FFMPEG_BINARY_NAME: (platform: NodeJS.Platform) => string = (platform) =>- platform === "win32" ? "ffmpeg.exe" : "ffmpeg";--/**- * Encoder preference per platform, best first. The first entry present in- * `available` wins.- *- * Windows prefers NVIDIA, then Intel, then AMD: NVENC is the strongest and most- * predictable of the three, QSV next, AMF last. AMF being last is about- * throughput headroom, not quality — measured output was frame-identical to- * software on the reference machine. Even AMF on an integrated Radeon measured- * ~165 fps at 1080p versus ~8 fps for WebCodecs, so last place is still ~20x- * what we shipped before.- *- * `h264_mf` (Media Foundation) sits after the vendor encoders as an OS-level- * net: it reaches AMD/Intel/NVIDIA silicon without their SDKs, so it can save a- * machine whose vendor path is missing or broken.- *- * Every list ends in `libopenh264` — software, BSD-licensed, bundled. It is the- * floor, not a fallback to somewhere else: there is deliberately no WebCodecs- * path any more, so a machine with no usable hardware encoder still exports- * through this same code, mux and all, just slowly. That is why this function- * cannot return null.- */-const ENCODER_PREFERENCE: Partial<Record<NodeJS.Platform, readonly VideoEncoderId[]>> = {- win32: ["h264_nvenc", "h264_qsv", "h264_amf", "h264_mf", "libopenh264"],- darwin: ["h264_videotoolbox", "libopenh264"],- linux: ["h264_nvenc", "h264_vaapi", "libopenh264"],-};--/** Last resort on an unrecognised platform: if ffmpeg runs at all, this is there. */-const UNIVERSAL_FALLBACK: VideoEncoderId = "libopenh264";--/** Match ffmpeg -encoders flag columns: 6 capability characters from- * V/A/S/D plus . (unset) and - (also unset on some builds). The flag- * prefix is followed by whitespace, then the encoder name. */-const ENCODER_FLAG_PATTERN = /^[-VASD.]{6}$/;--/** Encoder names are always identifier-shaped; rejects description lines like- * "V..... = Video" whose second token is "=". */-const ENCODER_NAME_PATTERN = /^[a-zA-Z_][a-zA-Z0-9_]*$/;--/**- * Where to look for the bundled ffmpeg, in priority order:- * 1. OPENSCREEN_FFMPEG_EXE env override (debug builds)- * 2. <appPath>/electron/native/bin/<platform>-<arch>/<name> (dev npm run- * dev and electron-builder --dir unpacked staging)- * 3. <resourcesPath>/electron/native/bin/<platform>-<arch>/<name>- * (packaged installer - NSIS / dmg / AppImage put natives under- * resources/)- * 4. here/electron/native/bin/<platform>-<arch>/<name> (older checkout- * shape + bare-bones tests)- * 5. here/electron/native/bin/<name> (cross-arch fallthrough - same name,- * no platform tag, lets a single checked-in binary serve every host)- *- * ponytail: on Windows we accept both ffmpeg.exe and bare ffmpeg as- * candidate names so a checkout that pre-dates the suffix fix still resolves- * to a valid file.- *- * Everything is read through the options bag so this function stays pure -- * the streaming layer injects appPath / resourcesPath from the Electron- * context, and tests pass literals.- */-export function candidateFfmpegPaths(- opts: {- here?: string;- platform?: NodeJS.Platform;- arch?: string;- appPath?: string | null;- resourcesPath?: string | null;- envOverride?: string | null;- } = {},-): string[] {- const here = opts.here ?? process.cwd();- const platform = opts.platform;- const arch = opts.arch;- const appPath = opts.appPath ?? null;- const resourcesPath = opts.resourcesPath ?? null;- const envOverride = opts.envOverride ?? null;-- const tag = platform && arch ? `${platform}-${arch}` : null;- const primary = platform ? FFMPEG_BINARY_NAME(platform) : "ffmpeg";- const names = platform === "win32" ? [primary, "ffmpeg"] : [primary];-- const appPathSegments =- appPath && tag ? names.map((n) => joinPosix(appPath, "electron", "native", "bin", tag, n)) : [];- const resourceSegments =- resourcesPath && tag- ? names.map((n) => joinPosix(resourcesPath, "electron", "native", "bin", tag, n))- : [];- const hereSegments = tag- ? names.map((n) => joinPosix(here, "electron", "native", "bin", tag, n))- : [];-- return [- ...(envOverride ? [envOverride] : []),- ...appPathSegments,- ...resourceSegments,- ...hereSegments,- // Cross-arch fallthrough: bare name with no platform tag - covers the- // case where a dev checked in a single ffmpeg for their host only.- ...names.map((n) => joinPosix(here, "electron", "native", "bin", n)),- ];-}--/**- * Parse ffmpeg -encoders stdout into the set of available encoder names.- * Returns every encoder (video, audio, subtitle, data) - the caller filters- * down to the VideoEncoderIds it cares about, so a future codec like- * hevc_nvenc doesn't require touching this parser.- *- * Tolerant of leading whitespace (real ffmpeg output is sometimes- * space-padded under the banner) and of - in flag positions (some builds- * render -- instead of .. for unset capabilities).- */-export function parseAvailableEncoders(stdout: string): Set<string> {- const available = new Set<string>();- for (const rawLine of stdout.split(/\r?\n/)) {- const line = rawLine.trim();- if (line.length === 0) continue;- const tokens = line.split(/\s+/);- if (tokens.length < 2) continue;- if (!ENCODER_FLAG_PATTERN.test(tokens[0])) continue;- if (!ENCODER_NAME_PATTERN.test(tokens[1])) continue;- available.add(tokens[1]);- }- return available;-}--/**- * The encoders worth *trying* on `platform`, best first, filtered to those the- * binary actually carries.- *- * **This is a shortlist, not a choice.** `ffmpeg -encoders` reports what was- * compiled in, which for a portable build is every vendor at once: our own- * bundled binary offers h264_nvenc, h264_qsv and h264_amf on a machine that has- * only an AMD GPU, where nvenc dies with "Cannot load nvcuda.dll" and qsv with- * "Error creating a MFX session". Presence proves nothing about the hardware.- * Only {@link smokeTestArgs} settles it — see {@link pickWorkingEncoder}.- *- * Note we never reach for libx264 even though it is the fastest thing we- * measured (201 fps). That is a licensing call, not a speed one — it is GPL and- * would relicense this MIT app (see isLgplBuild). libopenh264 is BSD and costs- * us nothing but throughput on the rare machine that needs it.- */-export function candidateVideoEncoders(- available: ReadonlySet<string>,- platform: NodeJS.Platform,-): VideoEncoderId[] {- const order = ENCODER_PREFERENCE[platform] ?? [UNIVERSAL_FALLBACK];- return order.filter((id) => available.has(id));-}--/**- * argv for a one-frame encode that answers the only question that matters: does- * this encoder work *on this machine*? Synthesises its own input (`lavfi`) and- * throws the output away (`-f null`), so it touches no files and takes ~100 ms.- */-export function smokeTestArgs(encoder: VideoEncoderId): string[] {- return [- "-hide_banner",- "-v",- "error",- "-f",- "lavfi",- "-i",- "color=c=black:s=320x240:d=0.1",- "-frames:v",- "1",- "-c:v",- encoder,- "-f",- "null",- "-",- ];-}--/**- * First encoder in the platform's preference order that survives a real one-frame- * encode. `runSmokeTest` returns true when ffmpeg exits 0 for the given argv —- * injected so this stays pure and testable without spawning anything.- *- * Returns null only when nothing works, which means the bundled ffmpeg is broken- * or missing rather than the machine being unsupported: libopenh264 is software- * and part of the build, so it should always pass. Callers must treat null as a- * hard error — with no WebCodecs path any more, there is nothing else to try.- */-export async function pickWorkingEncoder(- available: ReadonlySet<string>,- platform: NodeJS.Platform,- runSmokeTest: (args: string[]) => Promise<boolean> | boolean,-): Promise<VideoEncoderId | null> {- for (const id of candidateVideoEncoders(available, platform)) {- if (await runSmokeTest(smokeTestArgs(id))) return id;- }- return null;-}--/**- * External libraries ffmpeg documents as GPL-only. Enabling any one of them- * relicenses the WHOLE binary to GPL, which would contaminate this MIT app.- * Belt-and-braces: `--enable-gpl` is *required* to build these, so checking- * the flag alone should suffice — but a third-party build could be patched,- * and this is the list that actually decides the licence, so assert on it too.- * Source: ffmpeg.org/legal.html.- */-const GPL_EXTERNAL_LIBS = [- "libx264",- "libx265",- "libxvid",- "libxavs",- "libxavs2",- "libdavs2",- "libvidstab",- "librubberband",- "libcdio",- "frei0r",- "avisynth",-] as const;--/**- * Libraries that make the binary *unredistributable* — worse than GPL, since- * no licence lets us ship the result at all. `libfdk-aac` is the trap here:- * it is the AAC encoder everyone reaches for, and we encode AAC. Use ffmpeg's- * native `aac` encoder instead. Source: ffmpeg.org/legal.html.- */-const NONFREE_LIBS = ["libfdk-aac", "libfdk_aac", "openssl"] as const;--/**- * True iff the ffmpeg build has NO GPL and NO nonfree component.- *- * ffmpeg is LGPL **by default** — there is no `--disable-gpl`; GPL only- * appears if someone passes `--enable-gpl` (pulling x264/x265/…) or- * `--enable-nonfree` (fdk-aac, OpenSSL-combined builds). It is all-or-nothing:- * one GPL component relicenses the entire binary.- *- * This exists so CI can fail a build that would relicense the app — the whole- * reason we build/ship ffmpeg ourselves is that we control these flags.- *- * Feed it `ffmpeg -buildconf` output, or the banner's `configuration:` line.- */-export function isLgplBuild(buildConf: string): boolean {- // Token-bounded so `--enable-gpl` matches but `--enable-gpl-something` does- // not. The banner's `configuration:` line and a raw `-buildconf` dump are- // both space-separated flags.- if (/(?:^|\s)--enable-(?:gpl|nonfree)(?=\s|$)/.test(buildConf)) return false;-- for (const lib of [...GPL_EXTERNAL_LIBS, ...NONFREE_LIBS]) {- // Matches --enable-libx264 and the bare token some -buildconf dumps use.- if (new RegExp(String.raw`(?:^|\s)(?:--enable-)?${lib}(?=\s|$)`).test(buildConf)) {- return false;- }- }- return true;-}diff --git a/electron/media/ffmpegEncodeSession.test.ts b/electron/media/ffmpegEncodeSession.test.tsdeleted file mode 100644index f33032f8e..000000000--- a/electron/media/ffmpegEncodeSession.test.ts+++ /dev/null@@ -1,225 +0,0 @@-import path from "node:path";-import { fileURLToPath } from "node:url";-import { describe, expect, it } from "vitest";-import {- buildFfmpegArgs,- type FfmpegEncodeOptions,- parseProgress,- startFfmpegEncodeSession,-} from "./ffmpegEncodeSession";--const here = path.dirname(fileURLToPath(import.meta.url));-const FAKE = path.join(here, "__fixtures__", "fakeFfmpeg.cjs");--/** Drives the session against the fake ffmpeg instead of the real (unbundled) binary. */-function fakeOpts(over: Partial<FfmpegEncodeOptions> = {}): FfmpegEncodeOptions {- return {- ffmpegPath: process.execPath,- ffmpegArgsPrefix: [FAKE],- outputPath: path.join(here, "__fixtures__", "out.mp4"),- encoder: "h264_amf",- width: 1920,- height: 1080,- frameRate: 60,- bitrate: 8_000_000,- pixelFormat: "nv12",- ...over,- };-}--function withMode<T>(mode: string, fn: () => Promise<T>): Promise<T> {- const prev = process.env.FAKE_FFMPEG_MODE;- process.env.FAKE_FFMPEG_MODE = mode;- return fn().finally(() => {- if (prev === undefined) delete process.env.FAKE_FFMPEG_MODE;- else process.env.FAKE_FFMPEG_MODE = prev;- });-}--describe("buildFfmpegArgs", () => {- it("feeds rawvideo on stdin with the frame geometry ffmpeg cannot infer", () => {- const a = buildFfmpegArgs(fakeOpts({ ffmpegArgsPrefix: undefined }));- expect(a).toContain("-f");- expect(a[a.indexOf("-f") + 1]).toBe("rawvideo");- expect(a[a.indexOf("-s") + 1]).toBe("1920x1080");- expect(a[a.indexOf("-r") + 1]).toBe("60");- expect(a[a.indexOf("-i") + 1]).toBe("pipe:0");- });-- it("passes the pixel format through for both frame layouts", () => {- for (const pixelFormat of ["nv12", "bgra", "rgba"] as const) {- const a = buildFfmpegArgs(fakeOpts({ pixelFormat }));- expect(a[a.indexOf("-pix_fmt") + 1]).toBe(pixelFormat);- }- });-- it("selects the encoder and bitrate, and disables audio when there is none", () => {- const a = buildFfmpegArgs(fakeOpts({ encoder: "h264_videotoolbox", bitrate: 12_000_000 }));- expect(a[a.indexOf("-c:v") + 1]).toBe("h264_videotoolbox");- expect(a[a.indexOf("-b:v") + 1]).toBe("12000000");- expect(a).toContain("-an");- });-- it("declares the PCM as a second raw input and lets ffmpeg encode AAC", () => {- const a = buildFfmpegArgs(- fakeOpts({- audio: { path: "/tmp/a.pcm", sampleRate: 48000, channels: 2, bitrate: 192_000 },- }),- );- // f32le with an explicit rate/layout: raw PCM carries no header to infer from.- expect(a[a.indexOf("-f", a.indexOf("-i")) + 1]).toBe("f32le");- expect(a[a.indexOf("-ar") + 1]).toBe("48000");- expect(a[a.indexOf("-ac") + 1]).toBe("2");- expect(a).toContain("/tmp/a.pcm");- expect(a[a.indexOf("-c:a") + 1]).toBe("aac");- expect(a[a.indexOf("-b:a") + 1]).toBe("192000");- expect(a).not.toContain("-an");- });-- it("declares both inputs before any codec option, as ffmpeg requires", () => {- const a = buildFfmpegArgs(- fakeOpts({- audio: { path: "/tmp/a.pcm", sampleRate: 48000, channels: 2, bitrate: 192_000 },- }),- );- const lastInput = a.lastIndexOf("-i");- expect(lastInput).toBeLessThan(a.indexOf("-c:v"));- expect(lastInput).toBeLessThan(a.indexOf("-c:a"));- // pipe:0 is input 0 and the PCM is input 1 — that ordering is what makes- // video stream 0 and audio stream 1 in the output.- expect(a.indexOf("pipe:0")).toBeLessThan(a.indexOf("/tmp/a.pcm"));- });-- it("asks for machine-readable progress on stderr", () => {- const a = buildFfmpegArgs(fakeOpts());- expect(a[a.indexOf("-progress") + 1]).toBe("pipe:2");- expect(a).toContain("-nostats");- });-- it("puts the output path last so nothing can be mistaken for it", () => {- const a = buildFfmpegArgs(fakeOpts({ outputPath: "/tmp/x.mp4" }));- expect(a[a.length - 1]).toBe("/tmp/x.mp4");- expect(a[a.length - 2]).toBe("-y");- });-- it("keeps extraEncoderArgs with the encoder, before the output", () => {- const a = buildFfmpegArgs(fakeOpts({ extraEncoderArgs: ["-quality", "speed"] }));- expect(a.indexOf("-quality")).toBeGreaterThan(a.indexOf("-c:v"));- expect(a.indexOf("-quality")).toBeLessThan(a.indexOf("-y"));- });-- it("puts ffmpegArgsPrefix first so a wrapper can be invoked", () => {- expect(buildFfmpegArgs(fakeOpts({ ffmpegArgsPrefix: ["/w.js"] }))[0]).toBe("/w.js");- });-});--describe("parseProgress", () => {- it("reads frame= out of a progress block", () => {- expect(parseProgress("frame=42\nfps=60\nout_time_ms=700000\n")).toEqual({ frame: 42 });- });-- it("returns the freshest count when a chunk carries several blocks", () => {- expect(parseProgress("frame=1\nfps=60\nframe=2\nfps=60\nframe=3\n")).toEqual({ frame: 3 });- });-- it("ignores a chunk with no frame count", () => {- expect(parseProgress("fps=60\nbitrate=N/A\n")).toBeNull();- expect(parseProgress("")).toBeNull();- });-- it("ignores a frame= torn across a chunk boundary rather than reporting a truncated number", () => {- // The stream splits anywhere; "frame=12" here is the head of "frame=1234".- // Reporting 12 would make progress jump backwards on the next chunk.- expect(parseProgress("fps=60\nframe=12")).toBeNull();- expect(parseProgress("34\nfps=60\nframe=1234\n")).toEqual({ frame: 1234 });- });-- it("tolerates surrounding garbage", () => {- expect(parseProgress("some error text\nframe=7\n")).toEqual({ frame: 7 });- });-});--describe("startFfmpegEncodeSession", () => {- it("resolves with the output path when ffmpeg exits cleanly", async () => {- await withMode("ok", async () => {- const s = startFfmpegEncodeSession(fakeOpts());- await s.writeFrame(new Uint8Array(1024));- await expect(s.finish()).resolves.toEqual({ outputPath: fakeOpts().outputPath });- });- });-- it("rejects with the stderr tail when ffmpeg exits non-zero", async () => {- await withMode("fail", async () => {- const s = startFfmpegEncodeSession(fakeOpts());- await s.writeFrame(new Uint8Array(1024));- await expect(s.finish()).rejects.toThrow(/deliberate failure for the test/);- });- });-- it("rejects rather than emitting an unhandled error when the binary does not exist", async () => {- const s = startFfmpegEncodeSession(- fakeOpts({ ffmpegPath: path.join(here, "no-such-binary-xyz"), ffmpegArgsPrefix: [] }),- );- await expect(s.finish()).rejects.toThrow();- });-- it("loses no bytes under backpressure", async () => {- // The pipe only sustains ~500 MB/s because writeFrame awaits 'drain'. Ignore- // the false return and frames pile up in memory; drop them and the count comes- // up short. 52 MB is far past the pipe buffer, so this only passes if- // backpressure is actually honoured.- //- // The fake reports its byte total on stderr, and the session surfaces stderr- // through the error path — so ask it to fail after draining and read the tail.- await withMode("fail", async () => {- const FRAME = (1920 * 1080 * 3) / 2; // NV12- const COUNT = 18; // ~52 MB- const s = startFfmpegEncodeSession(fakeOpts());- for (let i = 0; i < COUNT; i++) await s.writeFrame(new Uint8Array(FRAME));- await expect(s.finish()).rejects.toThrow(/deliberate failure/);- expect(s.framesEncoded).toBe(0); // no progress lines in this mode- });- });-- it("delivers every byte to ffmpeg's stdin", async () => {- // Same contract as above, asserted directly: the fake counts what it received- // and prints BYTES=<n>, which reaches us via the failure path's stderr tail.- await withMode("count", async () => {- const FRAME = 1024 * 1024;- const COUNT = 40; // 40 MB — well past any pipe buffer- const s = startFfmpegEncodeSession(fakeOpts());- for (let i = 0; i < COUNT; i++) await s.writeFrame(new Uint8Array(FRAME));- await expect(s.finish()).rejects.toThrow(new RegExp(`BYTES=${FRAME * COUNT}\\b`));- });- });-- it("reports progress from ffmpeg's stderr", async () => {- await withMode("progress", async () => {- const seen: number[] = [];- const s = startFfmpegEncodeSession(fakeOpts(), { onProgress: (n) => seen.push(n) });- for (let i = 0; i < 4; i++) await s.writeFrame(new Uint8Array(1024 * 1024));- await s.finish();- expect(seen.length).toBeGreaterThan(0);- expect(s.framesEncoded).toBe(seen[seen.length - 1]);- });- });-- it("cancel() kills a hung ffmpeg and leaves finish() able to settle", async () => {- await withMode("hang", async () => {- const s = startFfmpegEncodeSession(fakeOpts());- await s.writeFrame(new Uint8Array(1024));- await s.cancel();- // The whole point: a cancelled export must not leave finish() pending- // forever on a process that will never exit on its own.- await expect(s.finish()).resolves.toEqual({ outputPath: fakeOpts().outputPath });- });- });-- it("refuses writes after cancel instead of throwing EPIPE at the main process", async () => {- await withMode("hang", async () => {- const s = startFfmpegEncodeSession(fakeOpts());- await s.cancel();- await expect(s.writeFrame(new Uint8Array(16))).rejects.toThrow(/closed/);- });- });-});diff --git a/electron/media/ffmpegEncodeSession.ts b/electron/media/ffmpegEncodeSession.tsdeleted file mode 100644index 496b85075..000000000--- a/electron/media/ffmpegEncodeSession.ts+++ /dev/null@@ -1,257 +0,0 @@-import type { ChildProcessByStdio } from "node:child_process";-import { spawn } from "node:child_process";-import { once } from "node:events";-import type { Readable, Writable } from "node:stream";--/** We pipe stdin and stderr and discard stdout — ffmpeg writes the file itself. */-type FfmpegChild = ChildProcessByStdio<Writable, null, Readable>;--/**- * Streams raw frames from the export pipeline into a bundled native ffmpeg,- * which encodes with the platform's hardware encoder and writes the file- * itself. Replaces WebCodecs + the JS muxer on the export path: WebCodecs- * reaches the same silicon but measures ~8 fps @1080p against ffmpeg's ~165.- *- * Runs in the main process. Deliberately free of Electron imports so it stays- * unit-testable outside Electron. Binary path and encoder come from- * {@link ../media/ffmpegCapabilities}; this module never resolves them itself.- */--export interface FfmpegEncodeOptions {- ffmpegPath: string;- /**- * argv inserted before ours. Tests use it to point `ffmpegPath` at- * `process.execPath` and run a fake-ffmpeg script instead of the real binary.- */- ffmpegArgsPrefix?: string[];- outputPath: string;- /** e.g. "h264_amf" — chosen by selectVideoEncoder(). */- encoder: string;- width: number;- height: number;- frameRate: number;- /** bits per second */- bitrate: number;- /**- * `nv12` is the fast path (3.0 MB/frame @1080p, produced by a GPU packing- * step). `bgra` is what a canvas VideoFrame gives us directly (7.9 MB) —- * Chromium refuses to convert to NV12, so ffmpeg's swscale does it instead.- */- pixelFormat: "nv12" | "bgra" | "rgba";- extraEncoderArgs?: string[];- /**- * Optional second input: the export's assembled PCM, already laid out at the- * concat plan's offsets. Given this, ffmpeg encodes AAC and muxes the final- * file itself — which is the whole point of routing audio through here rather- * than muxing in JS.- *- * Raw f32le rather than WAV: it is what we already hold in memory, it needs no- * header, and it skips the int16 round-trip a WAV would impose.- */- audio?: {- /** Path to raw interleaved float32 PCM. */- path: string;- sampleRate: number;- channels: number;- /** bits per second */- bitrate: number;- };-}--export interface FfmpegEncodeSession {- /** Resolves once ffmpeg has accepted the frame; awaits `drain` under backpressure. */- writeFrame(frame: Uint8Array): Promise<void>;- /** Closes stdin; resolves on a clean exit, rejects with the stderr tail otherwise. */- finish(): Promise<{ outputPath: string }>;- /** Kills the process tree. `finish()` must not hang afterwards. */- cancel(): Promise<void>;- readonly framesEncoded: number;-}--/** Keep the last of ffmpeg's stderr: on failure it is the only diagnostic anyone gets. */-const STDERR_TAIL_BYTES = 4096;--/**- * The argv we hand ffmpeg. Split out from the process handling so the shape can- * be asserted without spawning anything.- *- * `-progress pipe:2` asks for machine-readable `key=value` progress on stderr,- * which is what {@link parseProgress} reads; `-nostats` silences the human- * progress line that would otherwise interleave with it.- *- * All inputs must precede the output options, so audio (input 1) is declared- * right after the video pipe (input 0) and its codec is chosen further down.- */-export function buildFfmpegArgs(opts: FfmpegEncodeOptions): string[] {- return [- ...(opts.ffmpegArgsPrefix ?? []),- "-hide_banner",- "-v",- "error",- // input 0: raw frames on stdin. rawvideo carries no geometry, so ffmpeg- // cannot infer any of this — it must be told.- "-f",- "rawvideo",- "-pix_fmt",- opts.pixelFormat,- "-s",- `${opts.width}x${opts.height}`,- "-r",- String(opts.frameRate),- "-i",- "pipe:0",- // input 1: the assembled PCM, when there is audio.- ...(opts.audio- ? [- "-f",- "f32le",- "-ar",- String(opts.audio.sampleRate),- "-ac",- String(opts.audio.channels),- "-i",- opts.audio.path,- ]- : []),- "-c:v",- opts.encoder,- "-b:v",- String(opts.bitrate),- ...(opts.extraEncoderArgs ?? []),- ...(opts.audio ? ["-c:a", "aac", "-b:a", String(opts.audio.bitrate)] : ["-an"]),- // Video is exactly as long as the frames we push; audio is sized from the- // same per-segment frame counts, so a mismatch means an upstream bug we- // want to see rather than have ffmpeg quietly pad or truncate.- "-progress",- "pipe:2",- "-nostats",- "-y",- opts.outputPath,- ];-}--/**- * Pulls `frame=N` out of a chunk of ffmpeg's `-progress` output, or null when- * the chunk carries no frame count.- *- * Callers feed raw stream chunks, which split anywhere — including mid-line and- * mid-number. Matching only on a `frame=` followed by digits AND a terminator- * means a torn `frame=12` at a chunk boundary is ignored rather than reported as- * frame 12; the next chunk carries the whole line anyway. Progress is monotonic,- * so taking the LAST match in a chunk gives the freshest count.- */-export function parseProgress(chunk: string): { frame: number } | null {- let last: number | null = null;- // Require real trailing whitespace, NOT end-of-string: a chunk ending in- // "frame=12" is the head of "frame=1234", and end-of-string in the lookahead- // would happily report 12. ffmpeg's -progress always terminates each- // key=value with a newline, so a complete line always has its terminator.- for (const m of chunk.matchAll(/(?:^|\s)frame=\s*(\d+)(?=\s)/g)) {- const n = Number.parseInt(m[1], 10);- if (Number.isFinite(n)) last = n;- }- return last === null ? null : { frame: last };-}--/** Windows leaves orphans behind a bare kill() — ffmpeg would keep holding the output file. */-function killTree(child: FfmpegChild): void {- if (child.exitCode !== null || child.signalCode !== null) return;- if (process.platform === "win32" && child.pid !== undefined) {- spawn("taskkill", ["/pid", String(child.pid), "/T", "/F"], { stdio: "ignore" }).on(- "error",- () => {- // taskkill missing (unlikely) — fall back to the best we have.- child.kill("SIGKILL");- },- );- } else {- child.kill("SIGKILL");- }-}--export function startFfmpegEncodeSession(- opts: FfmpegEncodeOptions,- hooks?: { onProgress?: (framesEncoded: number) => void },-): FfmpegEncodeSession {- const child: FfmpegChild = spawn(opts.ffmpegPath, buildFfmpegArgs(opts), {- stdio: ["pipe", "ignore", "pipe"],- });-- let framesEncoded = 0;- let stderrTail = "";- let cancelled = false;- let closed = false;- let spawnError: Error | null = null;-- // Attached before the first write so a spawn failure surfaces through- // finish() instead of as an unhandled 'error' event.- const exited: Promise<{ code: number | null; signal: NodeJS.Signals | null }> = new Promise(- (resolve) => {- child.on("error", (err) => {- spawnError = err instanceof Error ? err : new Error(String(err));- resolve({ code: null, signal: null });- });- child.on("close", (code, signal) => {- closed = true;- resolve({ code, signal });- });- },- );-- child.stdin.on("error", () => {- // A killed ffmpeg closes the pipe under us mid-write. EPIPE here is- // expected and must never reach the main process as an unhandled error.- });-- child.stderr.setEncoding("utf8");- child.stderr.on("data", (chunk: string) => {- stderrTail = (stderrTail + chunk).slice(-STDERR_TAIL_BYTES);- const p = parseProgress(chunk);- if (p) {- framesEncoded = p.frame;- hooks?.onProgress?.(framesEncoded);- }- });-- return {- get framesEncoded() {- return framesEncoded;- },-- async writeFrame(frame: Uint8Array): Promise<void> {- if (cancelled || closed) throw new Error("ffmpeg encode session is closed");- if (spawnError) throw spawnError;- // Buffer.from(typedArray) COPIES. Wrapping the caller's memory instead- // measured +31% end-to-end (26 -> 34 fps): at 3-8 MB a frame, a stray- // copy per frame is gigabytes of pure memcpy across an export.- const view = Buffer.from(frame.buffer, frame.byteOffset, frame.byteLength);- // The pipe sustains ~500 MB/s ONLY if we respect backpressure. Ignoring- // the false return buffers frames in memory without going any faster.- if (!child.stdin.write(view)) {- await once(child.stdin, "drain");- }- },-- async finish(): Promise<{ outputPath: string }> {- if (!cancelled && !closed) child.stdin.end();- const { code, signal } = await exited;- if (spawnError) throw spawnError;- if (cancelled) return { outputPath: opts.outputPath };- if (code !== 0) {- const how = signal ? `signal ${signal}` : `exit code ${code}`;- throw new Error(`ffmpeg failed (${how})${stderrTail ? `: ${stderrTail.trim()}` : ""}`);- }- return { outputPath: opts.outputPath };- },-- async cancel(): Promise<void> {- if (cancelled || closed) return;- cancelled = true;- // End stdin first so ffmpeg is not blocked writing into a full pipe- // while we wait on the kill.- child.stdin.destroy();- killTree(child);- await exited;- },- };-}diff --git a/electron/media/ffmpegExportIpc.ts b/electron/media/ffmpegExportIpc.tsdeleted file mode 100644index d07287955..000000000--- a/electron/media/ffmpegExportIpc.ts+++ /dev/null@@ -1,62 +0,0 @@-import { ipcMain } from "electron";-import {- cancelExport,- finishExport,- resolveExportCapabilities,- type StartExportRequest,- startExport,- writeExportFrame,-} from "./ffmpegExportService";--/**- * IPC surface for the native export encoder.- *- * The renderer composites and extracts frames but cannot spawn ffmpeg — it is- * sandboxed and stays that way. Dropping the sandbox (option A') was measured- * and buys nothing: with the crossing at exactly zero the pipeline still loses- * to WebCodecs, because the wall is the compositor, not this path. See- * technical-documentation/architecture/export-pipeline.md- *- * This whole path is REFUTED (§5): feeding native ffmpeg from the renderer is- * 2.1x SLOWER than what we ship. It survives as bench scaffolding, not as a- * plan.- *- * Frames are `send`, not `invoke`: they are one-way and there is nothing to- * return. Flow control is the renderer's credit window (8 frames in flight),- * acknowledged by `EXPORT_FRAME_ACK` — measured worth +56% over stop-and-wait.- */--export const EXPORT_CAPABILITIES = "export:capabilities";-export const EXPORT_START = "export:start";-export const EXPORT_FRAME = "export:frame";-export const EXPORT_FRAME_ACK = "export:frame-ack";-export const EXPORT_FINISH = "export:finish";-export const EXPORT_CANCEL = "export:cancel";--export function registerFfmpegExportIpc(): void {- ipcMain.handle(EXPORT_CAPABILITIES, async () => {- const { encoder } = await resolveExportCapabilities();- return { encoder };- });-- ipcMain.handle(EXPORT_START, async (_e, req: StartExportRequest) => startExport(req));-- ipcMain.on(EXPORT_FRAME, async (e, sessionId: string, frame: ArrayBuffer) => {- try {- await writeExportFrame(sessionId, frame);- // Ack even on the last frame: the renderer's window must refill or it- // will stall short of the end.- if (!e.sender.isDestroyed()) e.sender.send(EXPORT_FRAME_ACK, sessionId, null);- } catch (err) {- // A write failure means ffmpeg died mid-export. Report it on the ack- // channel rather than throwing into an ipcMain.on handler, where the- // rejection would be unhandled and the renderer would wait forever.- if (!e.sender.isDestroyed()) {- e.sender.send(EXPORT_FRAME_ACK, sessionId, (err as Error).message);- }- }- });-- ipcMain.handle(EXPORT_FINISH, async (_e, sessionId: string) => finishExport(sessionId));- ipcMain.handle(EXPORT_CANCEL, async (_e, sessionId: string) => cancelExport(sessionId));-}diff --git a/electron/media/ffmpegExportService.ts b/electron/media/ffmpegExportService.tsdeleted file mode 100644index 5ab2bb706..000000000--- a/electron/media/ffmpegExportService.ts+++ /dev/null@@ -1,222 +0,0 @@-import { spawn } from "node:child_process";-import fs from "node:fs/promises";-import os from "node:os";-import path from "node:path";-import {- candidateFfmpegPaths,- parseAvailableEncoders,- pickWorkingEncoder,- type VideoEncoderId,-} from "./ffmpegCapabilities";-import { type FfmpegEncodeSession, startFfmpegEncodeSession } from "./ffmpegEncodeSession";--/**- * Main-process side of the native export encoder: resolves the bundled ffmpeg,- * proves which encoder actually works on this machine, and owns the live encode- * sessions the renderer streams frames into.- *- * The renderer cannot spawn anything (it is sandboxed, and stays that way), so- * frames cross to us over IPC and we feed ffmpeg's stdin. ffmpeg encodes, muxes- * the audio and writes the file — there is no JS muxer and no WebCodecs path- * behind this.- */--export interface StartExportRequest {- /**- * Omit to have main write to a temp file and return the path.- *- * The renderer is sandboxed and does not get to name a path main will write- * to — that would hand a compromised renderer an arbitrary file write. A- * user-chosen destination must come from a main-side save dialog, and the- * finished temp file is moved there.- */- outputPath?: string;- width: number;- height: number;- frameRate: number;- bitrate: number;- pixelFormat: "nv12" | "bgra" | "rgba";- /** Raw interleaved float32 PCM. ffmpeg encodes AAC and muxes it. */- audio?: { pcm: ArrayBuffer; sampleRate: number; channels: number; bitrate: number };-}--export interface StartExportResult {- sessionId: string;- encoder: VideoEncoderId;- /** Where ffmpeg is actually writing — main's choice when the caller omitted one. */- outputPath: string;-}--/** Resolved once per process: the probe costs a few spawns, the answer never changes. */-let capabilitiesPromise: Promise<{ ffmpegPath: string; encoder: VideoEncoderId }> | null = null;--async function firstExisting(paths: string[]): Promise<string | null> {- for (const p of paths) {- try {- await fs.access(p);- return p;- } catch {- // Expected: candidateFfmpegPaths lists every layout we might be running- // under (dev tree, unpacked staging, packaged resources); most miss.- }- }- return null;-}--function runFfmpeg(ffmpegPath: string, args: string[]): Promise<{ code: number; stdout: string }> {- return new Promise((resolve) => {- const child = spawn(ffmpegPath, args, { stdio: ["ignore", "pipe", "ignore"] });- let stdout = "";- child.stdout?.setEncoding("utf8");- child.stdout?.on("data", (c: string) => {- stdout += c;- });- child.on("error", () => resolve({ code: -1, stdout: "" }));- child.on("close", (code) => resolve({ code: code ?? -1, stdout }));- });-}--/**- * Which encoder this machine can really use. Cached: the smoke tests spawn ffmpeg- * a few times, and hardware does not change under a running app.- *- * The smoke test is the whole point. `ffmpeg -encoders` reports what was compiled- * in — our portable build lists nvenc, qsv and amf on every machine — so on an- * AMD box nvenc is "available" and then dies with "Cannot load nvcuda.dll".- * Presence is not capability; only a real one-frame encode settles it.- */-export function resolveExportCapabilities(): Promise<{- ffmpegPath: string;- encoder: VideoEncoderId;-}> {- capabilitiesPromise ??= (async () => {- const ffmpegPath = await firstExisting(- candidateFfmpegPaths({- platform: process.platform,- arch: process.arch,- appPath: process.env.OPENSCREEN_APP_PATH ?? null,- resourcesPath: process.resourcesPath ?? null,- envOverride: process.env.OPENSCREEN_FFMPEG_EXE ?? null,- }),- );- if (!ffmpegPath) {- throw new Error(- "Bundled ffmpeg not found. Run `npm run fetch:ffmpeg` in development; " +- "in a packaged build this means the binary was not shipped.",- );- }-- const listed = await runFfmpeg(ffmpegPath, ["-hide_banner", "-encoders"]);- const available = parseAvailableEncoders(listed.stdout);- const encoder = await pickWorkingEncoder(- available,- process.platform,- async (args) => (await runFfmpeg(ffmpegPath, args)).code === 0,- );- if (!encoder) {- // libopenh264 is software and part of our build, so it should always pass.- // Reaching here means the binary is broken, not that the machine is- // unsupported — and there is no other path to fall back to.- throw new Error(- "No usable H.264 encoder in the bundled ffmpeg — not even software. " +- "The bundled binary is broken or was replaced.",- );- }- return { ffmpegPath, encoder };- })();- return capabilitiesPromise;-}--interface LiveSession {- session: FfmpegEncodeSession;- /** Temp PCM handed to ffmpeg as its second input; ours to delete. */- audioPath: string | null;- tmpDir: string | null;-}--const sessions = new Map<string, LiveSession>();-let nextId = 1;--export async function startExport(req: StartExportRequest): Promise<StartExportResult> {- const { ffmpegPath, encoder } = await resolveExportCapabilities();-- const sessionId = `export-${nextId++}`;-- let audioPath: string | null = null;- let tmpDir: string | null = null;- if (req.audio && req.audio.pcm.byteLength > 0) {- // ffmpeg reads raw f32le straight from disk. Writing the PCM out beats a- // second pipe: it is small (a few MB), and stdin is already carrying video.- tmpDir = await fs.mkdtemp(path.join(os.tmpdir(), "openscreen-export-"));- audioPath = path.join(tmpDir, "audio.f32le");- await fs.writeFile(audioPath, Buffer.from(req.audio.pcm));- }-- // Deliberately NOT inside tmpDir: dispose() wipes that, and the output has to- // outlive the session so it can be moved to the user's destination.- const outputPath = req.outputPath ?? path.join(os.tmpdir(), `openscreen-${sessionId}.mp4`);-- const session = startFfmpegEncodeSession({- ffmpegPath,- encoder,- outputPath,- width: req.width,- height: req.height,- frameRate: req.frameRate,- bitrate: req.bitrate,- pixelFormat: req.pixelFormat,- audio:- audioPath && req.audio- ? {- path: audioPath,- sampleRate: req.audio.sampleRate,- channels: req.audio.channels,- bitrate: req.audio.bitrate,- }- : undefined,- });-- sessions.set(sessionId, { session, audioPath, tmpDir });- return { sessionId, encoder, outputPath };-}--function requireSession(sessionId: string): LiveSession {- const live = sessions.get(sessionId);- if (!live) throw new Error(`Unknown export session: ${sessionId}`);- return live;-}--export async function writeExportFrame(sessionId: string, frame: ArrayBuffer): Promise<void> {- // Buffer.from(arrayBuffer) wraps rather than copies — the +31% we measured- // depends on not duplicating a multi-MB frame here.- await requireSession(sessionId).session.writeFrame(new Uint8Array(frame));-}--async function dispose(sessionId: string, live: LiveSession): Promise<void> {- sessions.delete(sessionId);- if (live.tmpDir) await fs.rm(live.tmpDir, { recursive: true, force: true });-}--export async function finishExport(sessionId: string): Promise<{ outputPath: string }> {- const live = requireSession(sessionId);- try {- return await live.session.finish();- } finally {- await dispose(sessionId, live);- }-}--export async function cancelExport(sessionId: string): Promise<void> {- const live = sessions.get(sessionId);- if (!live) return; // Already finished or never started: cancelling is idempotent.- try {- await live.session.cancel();- } finally {- await dispose(sessionId, live);- }-}--/** Kill every live session — called when the app quits so no ffmpeg is orphaned. */-export async function cancelAllExports(): Promise<void> {- await Promise.all([...sessions.keys()].map((id) => cancelExport(id)));-}diff --git a/src/bench/runBench.ts b/src/bench/runBench.tsdeleted file mode 100644index c14ac9a7d..000000000--- a/src/bench/runBench.ts+++ /dev/null@@ -1,627 +0,0 @@-/**- * Headless export bench — the real pipeline, driven from a command line.- *- * Runs inside the app's own editor window (windowType=bench), so it exercises- * the real preload, the real sandbox, the real GPU and the real main-process- * ffmpeg. It loads a real saved project and calls exportAxcutDocument, the same- * entry point ExportDialog uses — nothing about the export path is simulated.- *- * Why it exists: driving the export through the UI costs ~5 minutes a run and- * silently injects confounds (an open DevTools panel handicapped one arm of the- * first A/B; a window that lost focus stole another). A command gives repeats- * cheaply, and repeats are what tell drift apart from effect.- *- * Deliberately NOT React: the bench replaces the app's UI entirely, so nothing- * renders alongside the export.- *- * npm run bench:export -- --project=os_parity --arms=webcodecs,native --runs=3- */--import { exportAxcutDocument } from "@/lib/ai-edition/exporter/documentExporter";-import { type AxcutDocument, zoomRegionSchema } from "@/lib/ai-edition/schema";-import type { ExportQuality } from "@/lib/exporter";-import { nativeBridgeClient } from "@/native/client";--export interface BenchArm {- /** localStorage flags applied before the run — the levers under test. */- nativeEncode: boolean;- readFrequently: boolean;- /** Extract every frame and discard it. Diagnostic only — writes no file. */- dropFrames?: boolean;- /** Composite every frame and stop there. Diagnostic only — writes no file. */- compositeOnly?: boolean;- /** Undo the 2026-07-17 compositor fixes, to attribute them. */- legacyCompositor?: boolean;- /** Gate G0: sync the GPU after compositing, in a `fence` stage of its own. */- gpuFence?: boolean;- /** Diagnostic: shadow path minus the gaussians. Renders no shadow. */- shadowNoFilter?: boolean;- /** The §8b compositor: one WGSL program. POC — renders no text/cursor/3D. */- wgslCompositor?: boolean;- /**- * Effects this arm adds to --effects, so an effect can be A/B'd INSIDE one- * interleaved run.- *- * --effects alone cannot answer "what does this effect cost": it is one value- * for the whole session, so the comparison becomes two sessions — and this- * machine drifts further between sessions (up to 62%) than any effect is- * worth. That is the mistake this bench exists to prevent.- */- addEffects?: string[];-}--export interface BenchRunResult {- arm: string;- run: number;- ok: boolean;- error?: string;- /** The exporter's frame-loop wall — what the arms are compared on. */- wallMs: number;- /** Everything outside the loop (project load, renderer init), reported not compared. */- setupMs?: number;- frames: number;- fps: number;- /** Per-stage totals in ms, keyed as StageTimings names it. */- stages: Record<string, number>;- /** Shadow cache hits/misses for the run — see BenchArm.addEffects / Step 3. */- shadow?: { hits: number; misses: number };-}--const params = new URLSearchParams(window.location.search);--/** The dialog's labels, so the bench is asked for what the UI shows. */-const QUALITY: Record<string, ExportQuality> = {- "720p": "medium",- "1080p": "good",- source: "source",-};--const BENCH_PARAMS = {- project: params.get("project"),- arms: (params.get("arms") ?? "webcodecs,native").split(",").filter(Boolean),- runs: Number(params.get("runs") ?? "2"),- fps: Number(params.get("fps") ?? "60"),- // "good" is the dialog's own default, i.e. what the UI A/B measured.- quality: QUALITY[params.get("quality") ?? "1080p"] ?? "good",- effects: (params.get("effects") ?? "").split(",").filter(Boolean),- // Cap the timeline to its first N seconds (in memory). Iteration speed:- // per-frame stage attribution is a steady-state metric, so ~180 frames say- // what 820 say, at a quarter of the wait. Wall/fps from a capped run are NOT- // comparable with full-length runs — compare per-frame, or same-cap runs.- clip: params.get("clip") ? Number(params.get("clip")) : null,- // Discarded runs before the measured ones. The session's FIRST export pays for- // shader compilation, decoder setup and JIT, and it lands on whichever arm ran- // first: measured at 9.3 s against 5.6/6.6/5.8 s for its own repeats — a 60%- // same-arm spread that voided the run all by itself, while the arm that merely- // went second looked better. One warm-up costs ~5 s at --clip=4.- warmup: Number(params.get("warmup") ?? "1"),- // Emit this frame of every arm as a PNG, so the pictures can be compared. The- // only thing that says a compositor WORKS; fps says only that it ran.- dumpFrame: params.get("dumpFrame"),-};--/**- * Appearance the exporter reads out of `legacyEditor`, patched onto an in-memory- * COPY of the document.- *- * Most saved projects carry no appearance at all, so the defaults apply:- * shadowIntensity 0, showBlur false, borderRadius 0, wallpaper "". Whole effects- * therefore never execute, and "fixing" them would have measured exactly zero on- * a project that never ran them. This turns them on without writing to the- * user's project store — nothing here reaches disk.- *- * --effects=shadow,blur,radius- */-const EFFECT_PATCHES: Record<string, Record<string, unknown>> = {- // Three chained drop-shadows over the full frame, every frame.- shadow: { shadowIntensity: 1 },- // A static wallpaper, re-blurred every frame.- blur: { showBlur: true },- radius: { borderRadius: 24 },- motionBlur: { motionBlurAmount: 1 },- // Without padding the recording covers the whole stage, so the background, the- // rounded corners and the shadow are all computed and then hidden behind it.- // The COST is real either way — which is why the timing arms never needed this- // — but a parity check has to be able to SEE what it is comparing.- padding: { padding: 45 },- // Turning an effect OFF is not the same as omitting it: a saved project has- // its own appearance (this bench's reference carries shadowIntensity 0.52 and- // motionBlurAmount 0.31), so an arm that "doesn't add shadow" still renders- // the project's. These patches are what make an arm PAIR isolate one effect.- noShadow: { shadowIntensity: 0 },- noMotionBlur: { motionBlurAmount: 0 },-};--/**- * A zoom region, injected the same way: the saved projects have `zoomRanges: []`.- *- * It is not decoration. Zoom is the one effect that changes the composited- * GEOMETRY every frame, so it is what invalidates any geometry-keyed cache. A- * parity test on a project without zoom would happily pass with a broken cache- * key, because nothing would ever ask it to invalidate.- *- * Parsed through the real schema before it is injected, because this region was- * born with `depth: "medium"` — a value nothing accepts. `ZOOM_DEPTH_SCALES`- * keys on 1..6, so the lookup returned undefined and the zoom silently did- * NOTHING: the arm reported a clean number for an effect that never ran. The- * schema is the only thing that knows what the pipeline accepts, so ask it.- */-function zoomRanges(doc: AxcutDocument): unknown[] {- const clips = (doc as { timeline?: { clips?: { timelineEndSec?: number }[] } }).timeline?.clips;- const endSec = clips?.[0]?.timelineEndSec ?? 5;- return [- zoomRegionSchema.parse({- id: "bench-zoom",- startMs: 500,- endMs: Math.max(1500, Math.round(endSec * 1000) - 500),- // 3 is DEFAULT_ZOOM_DEPTH, and what the reference project's own zoom uses.- depth: 3,- focus: { cx: 0.5, cy: 0.5 },- focusMode: "manual",- }),- ];-}--/**- * Truncate the timeline to its first N seconds, on the in-memory copy only.- *- * Clips are 1:1 with source time in the v4 model (speed is applied later, from- * legacyEditor.speedRegions, by the export segment loop), so capping timeline- * and source together keeps the document coherent. Regions past the cap simply- * never fire, like on any short project. Nothing here reaches disk.- */-function withClipCap(doc: AxcutDocument, seconds: number | null): AxcutDocument {- if (!seconds || !(seconds > 0)) return doc;- const timeline = (- doc as {- timeline?: {- clips?: {- sourceStartSec: number;- sourceEndSec: number;- timelineStartSec: number;- timelineEndSec: number;- }[];- };- }- ).timeline;- if (!timeline?.clips?.length) return doc;- const clips = [];- for (const clip of timeline.clips) {- if (clip.timelineStartSec >= seconds) continue;- if (clip.timelineEndSec <= seconds) {- clips.push(clip);- continue;- }- const keep = seconds - clip.timelineStartSec;- clips.push({- ...clip,- timelineEndSec: seconds,- sourceEndSec: clip.sourceStartSec + keep,- });- }- if (clips.length === 0) {- throw new Error(`--clip=${seconds} leaves no timeline at all`);- }- return { ...doc, timeline: { ...timeline, clips } } as AxcutDocument;-}--function withEffects(doc: AxcutDocument, effects: string[]): AxcutDocument {- if (effects.length === 0) return doc;- const legacy: Record<string, unknown> = {- ...((doc as { legacyEditor?: Record<string, unknown> }).legacyEditor ?? {}),- };- let patched = doc;- for (const name of effects) {- if (name === "zoom") {- patched = { ...patched, zoomRanges: zoomRanges(doc) } as AxcutDocument;- continue;- }- const patch = EFFECT_PATCHES[name];- if (!patch) {- throw new Error(`Unknown effect "${name}". Known: ${Object.keys(EFFECT_PATCHES)}, zoom`);- }- Object.assign(legacy, patch);- }- // `blur` only does anything against a real wallpaper; a project with none- // would silently skip the very pass being measured.- if (effects.includes("blur") && !legacy.wallpaper) {- legacy.wallpaper = "wallpaper13.jpg";- }- return { ...patched, legacyEditor: legacy } as AxcutDocument;-}--const ARMS: Record<string, BenchArm> = {- // The path we ship today: WebCodecs encodes straight off the GPU texture.- webcodecs: { nativeEncode: false, readFrequently: false },- // Frames descend to the CPU and cross to ffmpeg.- native: { nativeEncode: true, readFrequently: false },- // Native, but with CPU-backed canvases (what Linux already does) so the- // per-frame descent is a memcpy rather than a GPU round-trip.- "native-cpu": { nativeEncode: true, readFrequently: true },- // Control: isolates the canvas change from the encoder change. Without this- // arm a native-cpu win could be the canvas, the encoder, or neither.- "webcodecs-cpu": { nativeEncode: false, readFrequently: true },- // Ceiling, not a candidate: descend every frame to RAM, then discard it —- // the crossing costs exactly zero. Bounds EVERY "remove the crossing"- // proposal at once (option A' sandbox:false, shared memory, zero-copy- // transfer), because none of them can skip the readback. Writes no file.- "readback-ceiling": { nativeEncode: true, readFrequently: false, dropFrames: true },- // Prices the GPU compositing of the real effect set, with nothing downstream- // to absorb it. This is the number the native-core case rests on: a pipeline- // that composites on-device cannot beat decode + this + encode. Writes no file.- "composite-ceiling": { nativeEncode: true, readFrequently: false, compositeOnly: true },- // The same ceiling with the compositor fixes undone. Pairing these two in one- // interleaved run is the only honest way to price the fixes: across sessions- // this machine drifts further than they are worth.- "composite-ceiling-legacy": {- nativeEncode: true,- readFrequently: false,- compositeOnly: true,- legacyCompositor: true,- },- /** Today's shipping path, with the compositor fixes undone. */- "webcodecs-legacy": { nativeEncode: false, readFrequently: false, legacyCompositor: true },- // Gate G0 (rendering-architecture.md §7.1): the shipping path, but the GPU is- // forced to FINISH compositing before the encode timers start. The claim under- // test is pure attribution — encodeWait has been billing the compositor's- // execution. If §7.1 holds, encodeWait collapses to the encoder's own time and- // the difference reappears under `fence`; the wall itself may even worsen- // (the fence removes compositor/encoder overlap), which is fine — G0 is about- // where the time GOES, not how much there is. Run interleaved with its- // unfenced twin.- "webcodecs-fence": { nativeEncode: false, readFrequently: false, gpuFence: true },- // Same gate against the PRE-fix compositor — the arm the spec's numbers- // (encodeWait ~18.9 → ~6 ms) are actually quoted for.- "webcodecs-legacy-fence": {- nativeEncode: false,- readFrequently: false,- legacyCompositor: true,- gpuFence: true,- },- // Step 3 (rendering-architecture.md §13): the missing L7 row. A zoom is the one- // effect that moves the composited geometry every frame, so it is what the- // shadow cache cannot hold — pair it with `webcodecs-fence` in ONE interleaved- // run and the difference is the cost of a moving camera, on one thermal state.- // Fenced on both sides so the compositor's cost lands in `fence` on both,- // instead of hiding in the encoder's queue on both.- "webcodecs-fence-zoom": {- nativeEncode: false,- readFrequently: false,- gpuFence: true,- addEffects: ["zoom"],- },- // The other half of the Step-3 question. A zoom does not only miss the shadow- // cache — it also puts the camera in motion, which switches the motion-blur- // filter on. Run these two against the pair above and the arithmetic separates- // the shadow from everything else the zoom drags in:- // (zoom − zoom-noshadow) = the shadow with the cache MISSING every frame- // (still − still-noshadow) = the shadow with the cache HOLDING- // Without them, "zoom is slower" is true and says nothing about what to fix.- "webcodecs-fence-noshadow": {- nativeEncode: false,- readFrequently: false,- gpuFence: true,- addEffects: ["noShadow"],- },- "webcodecs-fence-zoom-noshadow": {- nativeEncode: false,- readFrequently: false,- gpuFence: true,- addEffects: ["zoom", "noShadow"],- },- // Splits the 16.7 ms cache miss in two, which is what decides the SHAPE of the- // fix. Against `webcodecs-fence-zoom` it prices the three gaussians; against- // `webcodecs-fence-zoom-noshadow` it prices the full-frame plumbing that feeds- // them. A shader is the answer to the first; touching less of the frame is the- // answer to the second. Renders no shadow — measurement only, never shipped.- "webcodecs-fence-zoom-nofilter": {- nativeEncode: false,- readFrequently: false,- gpuFence: true,- shadowNoFilter: true,- addEffects: ["zoom"],- },- // The POC (Step 4). Pair each against its Canvas2D twin above — same decode,- // same encoder, same document, one interleaved run — and the difference is the- // compositor and nothing else. The zoom pair is the one that matters: it is- // the case the 2D cache cannot hold and the shader has no cache to miss.- wgsl: { nativeEncode: false, readFrequently: false, wgslCompositor: true },- // The parity gate, not a speed arm: the native sink WRITES AN MP4, so this pair- // produces one file each — same timeline, same encoder, same bitrate, one- // compositor apart — and the two pictures can be diffed. The descent to ffmpeg- // makes them slow, which does not matter: nobody is timing a correctness check.- "wgsl-native-zoom": {- nativeEncode: true,- readFrequently: false,- wgslCompositor: true,- addEffects: ["zoom"],- },- "native-zoom": { nativeEncode: true, readFrequently: false, addEffects: ["zoom"] },- "wgsl-fence": {- nativeEncode: false,- readFrequently: false,- gpuFence: true,- wgslCompositor: true,- },- "wgsl-fence-zoom": {- nativeEncode: false,- readFrequently: false,- gpuFence: true,- wgslCompositor: true,- addEffects: ["zoom"],- },- // The shader compositor minus the shadow cascade. Against `wgsl-fence` it- // prices the cascade — 18 full-frame passes, which is the naive version of an- // algorithm whose whole point was that it is cheap on a GPU.- "wgsl-fence-noshadow": {- nativeEncode: false,- readFrequently: false,- gpuFence: true,- wgslCompositor: true,- addEffects: ["noShadow"],- },- // These two WRITE FILES, which is what makes them the parity gate: encode the- // same timeline with the old and new compositor through the same encoder at- // the same bitrate, then diff the results (SSIM). Unit tests never look at a- // pixel, and "obviously equivalent" is what this investigation keeps punishing.- "native-legacy": { nativeEncode: true, readFrequently: false, legacyCompositor: true },-};--function applyArm(arm: BenchArm): void {- localStorage.setItem("openscreen.nativeEncode", arm.nativeEncode ? "1" : "0");- localStorage.setItem("openscreen.readFrequently", arm.readFrequently ? "1" : "0");- localStorage.setItem("openscreen.dropFrames", arm.dropFrames ? "1" : "0");- localStorage.setItem("openscreen.compositeOnly", arm.compositeOnly ? "1" : "0");- localStorage.setItem("openscreen.legacyCompositor", arm.legacyCompositor ? "1" : "0");- localStorage.setItem("openscreen.gpuFence", arm.gpuFence ? "1" : "0");- localStorage.setItem("openscreen.shadowNoFilter", arm.shadowNoFilter ? "1" : "0");- localStorage.setItem("openscreen.wgslCompositor", arm.wgslCompositor ? "1" : "0");- if (BENCH_PARAMS.dumpFrame) localStorage.setItem("openscreen.dumpFrame", BENCH_PARAMS.dumpFrame);- else localStorage.removeItem("openscreen.dumpFrame");-}--/**- * aiEdition.get() reports failure as {success:false, error} rather than- * throwing, so an unchecked read of .document turns every load error into a- * silent null — which is exactly how "project not found" masked the real reason- * once already. Surface it.- */-async function loadDocument(id: string): Promise<AxcutDocument> {- const result = (await nativeBridgeClient.aiEdition.get(id)) as {- success?: boolean;- document?: AxcutDocument;- error?: string;- };- if (!result?.success || !result.document) {- throw new Error(`Cannot load project ${id}: ${result?.error ?? "no document returned"}`);- }- return result.document;-}--/**- * Accepts a project id, an id prefix, or a title.- *- * Titles need care: a summary's title is the name the project was CREATED with- * ("Recording 15/07/2026 18:38:53") and does not follow a rename, so the one- * shown in the editor — the document's own project.title — may match nothing in- * the summary list. Hence the fallback that opens documents to check. It is the- * slow path on purpose: only reached when the cheap matches miss.- */-async function resolveDocument(projectRef: string | null): Promise<AxcutDocument> {- const projects = await nativeBridgeClient.aiEdition.listProjects();- if (projects.length === 0) throw new Error("No saved projects to bench against");- if (!projectRef) return loadDocument(projects[0].id);-- const summary =- projects.find((p) => p.id === projectRef) ??- projects.find((p) => p.id.startsWith(projectRef)) ??- projects.find((p) => p.title === projectRef);- if (summary) return loadDocument(summary.id);-- const failures: string[] = [];- for (const p of projects) {- try {- const doc = await loadDocument(p.id);- if (doc.project?.title === projectRef) return doc;- } catch (error) {- failures.push(error instanceof Error ? error.message : String(error));- }- }- throw new Error(- `Project "${projectRef}" not found by id, id prefix, or title ` +- `(${projects.length} searched, ${failures.length} failed to load).` +- (failures.length ? `\nFirst load failure: ${failures[0]}` : ""),- );-}--/**- * Largest source on the timeline — mirrors ExportDialog's referenceSource so- * "Source" quality picks the same output size the UI would.- */-function referenceSource(doc: AxcutDocument): { width?: number; height?: number } {- let best: { width?: number; height?: number } = {};- let bestArea = 0;- for (const asset of doc.assets ?? []) {- const w = asset.video?.width;- const h = asset.video?.height;- if (!w || !h) continue;- if (w * h > bestArea) {- bestArea = w * h;- best = { width: w, height: h };- }- }- return best;-}--interface Captured {- stages: Record<string, number>;- /** The exporter's own loop numbers, which exclude the bench's setup. */- loop: { wallMs: number; frames: number; fps: number } | null;- /** Shadow cache hits/misses — the Step-3 decision input. */- shadow: { hits: number; misses: number } | null;- restore: () => void;-}--/** The perf line the exporter prints is for humans; the bench needs the numbers. */-function captureStages(): Captured {- const captured: Captured = {- stages: {},- loop: null,- shadow: null,- restore: () => {- console.warn = original;- },- };- const original = console.warn;- console.warn = (...args: unknown[]) => {- const text = args.map(String).join(" ");- if (text.includes("[export perf]")) {- // "[export perf] wall 77557ms · 546 frames · 7.0 fps"- const head = /wall\s+([\d.]+)ms\D+(\d+)\s+frames\D+([\d.]+)\s+fps/.exec(text);- if (head) {- captured.loop = {- wallMs: Number(head[1]),- frames: Number(head[2]),- fps: Number(head[3]),- };- }- // "[export perf] shadow cache: 100 hits, 20 misses (16.7% miss of 120)"- const shadow = /shadow cache:\s*(\d+)\s+hits,\s*(\d+)\s+misses/.exec(text);- if (shadow) {- captured.shadow = { hits: Number(shadow[1]), misses: Number(shadow[2]) };- }- for (const line of text.split("\n")) {- // " render 1680.0 3.0% 3.08 n=546"- const m = /^\s*([a-zA-Z]+)\s+([\d.]+)\s+[\d.]+%/.exec(line);- if (m && m[1] !== "TOTAL") captured.stages[m[1]] = Number(m[2]);- }- }- original(...args);- };- return captured;-}--async function runOnce(- doc: AxcutDocument,- armName: string,- arm: BenchArm,- run: number,-): Promise<BenchRunResult> {- applyArm(arm);- const src = referenceSource(doc);- const capture = captureStages();- const started = performance.now();- try {- const result = await exportAxcutDocument(doc, {- format: "mp4",- quality: BENCH_PARAMS.quality,- frameRate: BENCH_PARAMS.fps,- codec: "h264",- sourceWidth: src.width,- sourceHeight: src.height,- });- const wallMs = performance.now() - started;- // The native arm returns no blob (ffmpeg wrote the file itself), so a- // missing blob is not a failure here the way it is in ExportDialog.- if (!result.success) throw new Error(result.error ?? "export failed");- if (!capture.loop) throw new Error("exporter printed no [export perf] line");- return {- arm: armName,- run,- ok: true,- // The exporter's own loop wall, not the bench's: comparing arms means- // comparing the frame loop, not project loading.- wallMs: capture.loop.wallMs,- setupMs: wallMs - capture.loop.wallMs,- frames: capture.loop.frames,- fps: capture.loop.fps,- stages: capture.stages,- shadow: capture.shadow ?? undefined,- };- } catch (error) {- return {- arm: armName,- run,- ok: false,- error: error instanceof Error ? error.message : String(error),- wallMs: performance.now() - started,- frames: 0,- fps: 0,- stages: capture.stages,- };- } finally {- capture.restore();- }-}--/**- * Interleaves arms rather than running each arm's repeats together: A,B,A,B.- * Same-arm repeats then bracket the other arm in time, so drift shows up as- * disagreement between a run and its own repeat instead of masquerading as the- * effect under test. The first A/B on this machine drifted 26% between two- * identical runs — enough to invert the conclusion.- */-export async function runBench(): Promise<void> {- const results: BenchRunResult[] = [];- const emit = (event: string, payload: unknown) =>- // Picked up by the runner off stdout; console.warn is what the app's- // console forwarder actually relays to the main process.- console.warn(`[bench] ${JSON.stringify({ event, ...(payload as object) })}`);-- try {- for (const armName of BENCH_PARAMS.arms) {- if (!ARMS[armName]) throw new Error(`Unknown arm "${armName}"`);- }- // Loaded once: the title fallback can open every project on disk, and every- // arm must see the same source document.- // Cap BEFORE effects, so the injected zoom fits inside the capped window.- const base = withClipCap(await resolveDocument(BENCH_PARAMS.project), BENCH_PARAMS.clip);- // One document per EFFECT SET, not per arm: arms sharing a set share the- // exact object, so they cannot differ by anything but their own flags.- const docs = new Map<string, AxcutDocument>();- const docFor = (arm: BenchArm): AxcutDocument => {- const effects = [...BENCH_PARAMS.effects, ...(arm.addEffects ?? [])];- const key = effects.join(",");- const existing = docs.get(key);- if (existing) return existing;- const built = withEffects(base, effects);- docs.set(key, built);- return built;- };- emit("start", {- arms: BENCH_PARAMS.arms,- runs: BENCH_PARAMS.runs,- project: base.project?.title ?? "(untitled)",- effects: BENCH_PARAMS.effects.length ? BENCH_PARAMS.effects.join("+") : "(project default)",- clip: BENCH_PARAMS.clip,- warmup: BENCH_PARAMS.warmup,- });- // Warm up EVERY arm, not just the first: each one's first pass is the one- // that pays. Results are dropped on the floor.- for (let w = 0; w < BENCH_PARAMS.warmup; w++) {- for (const armName of BENCH_PARAMS.arms) {- const arm = ARMS[armName];- const result = await runOnce(docFor(arm), armName, arm, 0);- // A warm-up that FAILS is still a broken arm — say so now rather than- // let the measured pass report the same failure four times.- if (!result.ok) throw new Error(`warm-up failed for ${armName}: ${result.error}`);- emit("warmup", { arm: armName, wallMs: result.wallMs, fps: result.fps });- }- }- for (let run = 1; run <= BENCH_PARAMS.runs; run++) {- for (const armName of BENCH_PARAMS.arms) {- const arm = ARMS[armName];- // The runner needs to know whose frame a dumped PNG is: the exporter- // emits it mid-run, before the result that would have named the arm.- emit("armStart", { arm: armName, run });- const result = await runOnce(docFor(arm), armName, arm, run);- results.push(result);- emit("run", result);- }- }- emit("done", { results });- } catch (error) {- emit("fatal", { error: error instanceof Error ? error.message : String(error) });- }- await window.electronAPI?.benchFinished?.();-}diff --git a/src/components/ai-edition/ArrowSvgs.tsx b/src/components/ai-edition/ArrowSvgs.tsxdeleted file mode 100644index fffbb08a5..000000000--- a/src/components/ai-edition/ArrowSvgs.tsx+++ /dev/null@@ -1,212 +0,0 @@-// Inline SVG arrows for 8 directions (pure paths, not icon fonts, so the native-// compositor replicates them identically — cf. `arrow_segments_viewbox` in regions.rs,-// which carries the same numbers and is pinned to them by a test).-//-// Les barbes des quatre DIAGONALES ont été refaites pour égaler les cardinales sur les DEUX-// paramètres qui font une pointe de flèche : la longueur (21,2 unités de viewBox, contre 15,8-// à l'origine) ET l'ouverture. C'est l'angle qui trahissait le plus : les cardinales ouvrent à-// ±45° du fût, les diagonales à ±25° seulement, donnant un crochet étroit qui se fondait dans-// le fût dès que le trait épaississait. Les barbes sont désormais dérivées de la direction du-// fût par rotation de ±45°, la même règle qui produit exactement les (35,35)/(65,35) des-// cardinales — la géométrie est donc uniforme par construction, pas par retouche.--import type { AxcutAnnotationRegion } from "@/lib/ai-edition/schema";--type ArrowDirection = NonNullable<AxcutAnnotationRegion["figureData"]>["arrowDirection"];--interface ArrowSvgProps {- color: string;- strokeWidth: number;- className?: string;-}--export function ArrowUp({ color, strokeWidth, className }: ArrowSvgProps) {- return (- <svg viewBox="0 0 100 100" className={className} style={{ width: "100%", height: "100%" }}>- <defs>- <filter id="arrow-shadow">- <feDropShadow dx="0" dy="2" stdDeviation="4" floodOpacity="0.3" />- </filter>- </defs>- <path- d="M 50 20 L 50 80 M 50 20 L 35 35 M 50 20 L 65 35"- stroke={color}- strokeWidth={strokeWidth}- strokeLinecap="round"- strokeLinejoin="round"- fill="none"- filter="url(#arrow-shadow)"- />- </svg>- );-}--export function ArrowDown({ color, strokeWidth, className }: ArrowSvgProps) {- return (- <svg viewBox="0 0 100 100" className={className} style={{ width: "100%", height: "100%" }}>- <defs>- <filter id="arrow-shadow">- <feDropShadow dx="0" dy="2" stdDeviation="4" floodOpacity="0.3" />- </filter>- </defs>- <path- d="M 50 20 L 50 80 M 50 80 L 35 65 M 50 80 L 65 65"- stroke={color}- strokeWidth={strokeWidth}- strokeLinecap="round"- strokeLinejoin="round"- fill="none"- filter="url(#arrow-shadow)"- />- </svg>- );-}--export function ArrowLeft({ color, strokeWidth, className }: ArrowSvgProps) {- return (- <svg viewBox="0 0 100 100" className={className} style={{ width: "100%", height: "100%" }}>- <defs>- <filter id="arrow-shadow">- <feDropShadow dx="0" dy="2" stdDeviation="4" floodOpacity="0.3" />- </filter>- </defs>- <path- d="M 80 50 L 20 50 M 20 50 L 35 35 M 20 50 L 35 65"- stroke={color}- strokeWidth={strokeWidth}- strokeLinecap="round"- strokeLinejoin="round"- fill="none"- filter="url(#arrow-shadow)"- />- </svg>- );-}--export function ArrowRight({ color, strokeWidth, className }: ArrowSvgProps) {- return (- <svg viewBox="0 0 100 100" className={className} style={{ width: "100%", height: "100%" }}>- <defs>- <filter id="arrow-shadow">- <feDropShadow dx="0" dy="2" stdDeviation="4" floodOpacity="0.3" />- </filter>- </defs>- <path- d="M 20 50 L 80 50 M 80 50 L 65 35 M 80 50 L 65 65"- stroke={color}- strokeWidth={strokeWidth}- strokeLinecap="round"- strokeLinejoin="round"- fill="none"- filter="url(#arrow-shadow)"- />- </svg>- );-}--export function ArrowUpRight({ color, strokeWidth, className }: ArrowSvgProps) {- return (- <svg viewBox="0 0 100 100" className={className} style={{ width: "100%", height: "100%" }}>- <defs>- <filter id="arrow-shadow">- <feDropShadow dx="0" dy="2" stdDeviation="4" floodOpacity="0.3" />- </filter>- </defs>- <path- d="M 25 75 L 75 25 M 75 25 L 53.8 25 M 75 25 L 75 46.2"- stroke={color}- strokeWidth={strokeWidth}- strokeLinecap="round"- strokeLinejoin="round"- fill="none"- filter="url(#arrow-shadow)"- />- </svg>- );-}--export function ArrowUpLeft({ color, strokeWidth, className }: ArrowSvgProps) {- return (- <svg viewBox="0 0 100 100" className={className} style={{ width: "100%", height: "100%" }}>- <defs>- <filter id="arrow-shadow">- <feDropShadow dx="0" dy="2" stdDeviation="4" floodOpacity="0.3" />- </filter>- </defs>- <path- d="M 75 75 L 25 25 M 25 25 L 25 46.2 M 25 25 L 46.2 25"- stroke={color}- strokeWidth={strokeWidth}- strokeLinecap="round"- strokeLinejoin="round"- fill="none"- filter="url(#arrow-shadow)"- />- </svg>- );-}--export function ArrowDownRight({ color, strokeWidth, className }: ArrowSvgProps) {- return (- <svg viewBox="0 0 100 100" className={className} style={{ width: "100%", height: "100%" }}>- <defs>- <filter id="arrow-shadow">- <feDropShadow dx="0" dy="2" stdDeviation="4" floodOpacity="0.3" />- </filter>- </defs>- <path- d="M 25 25 L 75 75 M 75 75 L 75 53.8 M 75 75 L 53.8 75"- stroke={color}- strokeWidth={strokeWidth}- strokeLinecap="round"- strokeLinejoin="round"- fill="none"- filter="url(#arrow-shadow)"- />- </svg>- );-}--export function ArrowDownLeft({ color, strokeWidth, className }: ArrowSvgProps) {- return (- <svg viewBox="0 0 100 100" className={className} style={{ width: "100%", height: "100%" }}>- <defs>- <filter id="arrow-shadow">- <feDropShadow dx="0" dy="2" stdDeviation="4" floodOpacity="0.3" />- </filter>- </defs>- <path- d="M 75 25 L 25 75 M 25 75 L 46.2 75 M 25 75 L 25 53.8"- stroke={color}- strokeWidth={strokeWidth}- strokeLinecap="round"- strokeLinejoin="round"- fill="none"- filter="url(#arrow-shadow)"- />- </svg>- );-}--export function getArrowComponent(direction: ArrowDirection) {- switch (direction) {- case "up":- return ArrowUp;- case "down":- return ArrowDown;- case "left":- return ArrowLeft;- case "right":- return ArrowRight;- case "up-right":- return ArrowUpRight;- case "up-left":- return ArrowUpLeft;- case "down-right":- return ArrowDownRight;- case "down-left":- return ArrowDownLeft;- default:- return ArrowRight;- }-}diff --git a/src/components/ai-edition/preview-compositor/PreviewCompositor.module.css b/src/components/ai-edition/preview-compositor/PreviewCompositor.module.cssdeleted file mode 100644index a1b3ade40..000000000--- a/src/components/ai-edition/preview-compositor/PreviewCompositor.module.css+++ /dev/null@@ -1,56 +0,0 @@-.container {- display: flex;- flex-direction: column;- gap: 0.5rem;- width: 100%;- height: 100%;- align-items: center;- justify-content: center;-}--.videoFrame {- position: relative;- width: 100%;- height: 100%;- display: flex;- align-items: center;- justify-content: center;-}--/* Decode source only — never painted. Kept in normal flow (not display:none)- so its intrinsic-ratio contain-fit box is real and CursorPreviewLayer's- ResizeObserver (which measures a `<video>` sibling) keeps working- unmodified. The composited pixels come from the canvas below. */-.video {- visibility: hidden;- max-width: 100%;- max-height: 100%;-}--/* Positioned/sized in JS to exactly match the hidden video's rendered rect- (see the rect-sync effect in PreviewCompositor.tsx) — same technique- CursorPreviewLayer already uses for its own overlay. */-.canvasHost {- position: absolute;- pointer-events: none;- overflow: hidden;-}--.overlay {- position: absolute;- display: flex;- align-items: center;- justify-content: center;- color: var(--muted-foreground);- font-size: 0.875rem;- background: var(--card);- padding: 0.75rem 1.25rem;- border-radius: 0.5rem;-}--.placeholder {- color: var(--muted-foreground);- font-size: 0.875rem;- text-align: center;- padding: 2rem;-}diff --git a/src/components/ai-edition/preview-compositor/PreviewCompositor.tsx b/src/components/ai-edition/preview-compositor/PreviewCompositor.tsxdeleted file mode 100644index 02c787d23..000000000--- a/src/components/ai-edition/preview-compositor/PreviewCompositor.tsx+++ /dev/null@@ -1,499 +0,0 @@-// Single-canvas Pixi/WebGL compositor for the screen recording, replacing-// the CSS-transform + plain <video> approach `VirtualPreview` used.-//-// Why: the screen recording used to be a bare <video> element with zoom/pan-// applied as a CSS `transform` on its wrapper div, re-computed on every-// virtual-time tick. That's a DOM style write + layout/paint cost 60x/sec on-// top of the browser's own video decode/paint — main branch instead decodes-// the video straight into a Pixi texture and applies zoom/pan as a Pixi-// container transform, so the whole frame (video + mask + zoom) is one GPU-// draw call per tick with no DOM reflow. This component ports that approach-// for the screen source only (the webcam stays a plain <video> — see-// WebcamOverlay.tsx and playback-clock.ts for its own, separately-fixed,-// sync story; main doesn't Pixi-composite the webcam either).-//-// The actual timeline-aware playback logic (clip-boundary advancement, skip-// ranges, speed regions, asset switching, seeking) is unchanged from-// VirtualPreview — only the RENDERING of the active frame moved from-// CSS+<video> to Pixi+<canvas>. The <video> element itself is kept in the-// DOM (invisible) purely as the decode source Pixi's VideoSource wraps, and-// so CursorPreviewLayer's existing "measure the sibling <video>" sizing-// keeps working unmodified.--import { Application, Container, Graphics, Sprite, Texture, VideoSource } from "pixi.js";-import { useCallback, useEffect, useMemo, useRef, useState } from "react";-import { fromFileUrl } from "@/components/video-editor/projectPersistence";-import { MAX_NATIVE_PLAYBACK_RATE } from "@/components/video-editor/types";-import { resolvePlaybackSegments } from "@/lib/ai-edition/document/timeline";-import type { AxcutClip, AxcutTrimRange, AxcutZoomRegion } from "@/lib/ai-edition/schema";-import { useEditorSettings } from "@/lib/ai-edition/store/useEditorSettings";-import type { PlaybackClockRef } from "@/lib/ai-edition/timeline/playback-clock";-import { findActiveSpeedRegion, type SpeedRegion } from "@/lib/ai-edition/timeline/speed";-import {- clampVirtualTime,- findNextKeptSegment,- getRawVirtualStartTime,- locateSourcePosition,- locateVirtualPosition,- totalVirtualDuration,-} from "@/lib/ai-edition/timeline/virtual-preview";-import {- computeZoomPreviewTransform,- IDENTITY_ZOOM_TRANSFORM,-} from "@/lib/ai-edition/timeline/zoom-preview";-import { CursorPreviewLayer } from "../CursorPreviewLayer";-import styles from "./PreviewCompositor.module.css";--export interface VideoSourceDescriptor {- id: string;- src: string;- label: string;-}--interface PreviewCompositorProps {- videoSources: VideoSourceDescriptor[];- clips: AxcutClip[];- zoomRegions?: AxcutZoomRegion[];- speedRegions?: SpeedRegion[];- trimRanges?: AxcutTrimRange[];- seekTarget?: { timeSec: number; isSource?: boolean; requestId: number } | null;- onTimeChange?: (timeSec: number) => void;- onLoadedMetadata?: (durationSec: number, assetId: string) => void;- onVideoElement?: (element: HTMLVideoElement | null) => void;- onVideoError?: () => void;- /** Written every tick so the webcam overlay can stay locked to this clock. */- clockRef?: PlaybackClockRef;-}--interface Size {- width: number;- height: number;-}--export function PreviewCompositor({- videoSources,- clips,- zoomRegions = [],- speedRegions = [],- trimRanges = [],- seekTarget,- onTimeChange,- onLoadedMetadata,- onVideoElement,- onVideoError,- clockRef,-}: PreviewCompositorProps) {- const { settings } = useEditorSettings();- const videoRef = useRef<HTMLVideoElement | null>(null);- const frameRef = useRef<HTMLDivElement | null>(null);- const canvasHostRef = useRef<HTMLDivElement | null>(null);-- const isProgrammaticSeekRef = useRef(false);- const pendingSeekRef = useRef<{ sourceTimeSec: number; play: boolean } | null>(null);- const [virtualTimeSec, setVirtualTimeSec] = useState(0);- const [isPlaying, setIsPlaying] = useState(false);- const [loadState, setLoadState] = useState<"idle" | "loading" | "ready" | "error">("idle");- const [sourceIndex, setSourceIndex] = useState(0);- const [canvasSize, setCanvasSize] = useState<Size>({ width: 0, height: 0 });-- const virtualDurationSec = useMemo(() => totalVirtualDuration(clips), [clips]);- const activeSource = videoSources[sourceIndex] ?? null;-- // See VirtualPreview's original comment: the cursor overlay wants- // source-media time, not virtual-timeline time.- const [sourceTimeSec, setSourceTimeSec] = useState(0);-- const sourceTimeSecRef = useRef(0);- sourceTimeSecRef.current = sourceTimeSec;- const clipsRef = useRef(clips);- clipsRef.current = clips;- const videoSourcesRef = useRef(videoSources);- videoSourcesRef.current = videoSources;- const sourceIndexRef = useRef(sourceIndex);- sourceIndexRef.current = sourceIndex;- const virtualTimeSecRef = useRef(virtualTimeSec);- virtualTimeSecRef.current = virtualTimeSec;- const virtualDurationSecRef = useRef(virtualDurationSec);- virtualDurationSecRef.current = virtualDurationSec;- const speedRegionsRef = useRef(speedRegions);- speedRegionsRef.current = speedRegions;- const trimRangesRef = useRef(trimRanges);- trimRangesRef.current = trimRanges;- const playbackClips = useMemo(- () => resolvePlaybackSegments(clips, trimRanges),- [clips, trimRanges],- );- const playbackClipsRef = useRef(playbackClips);- playbackClipsRef.current = playbackClips;-- const updateVirtualTime = useCallback(- (nextTimeSec: number) => {- setVirtualTimeSec(nextTimeSec);- onTimeChange?.(nextTimeSec);- const v = videoRef.current;- if (v) {- const activeRegion = findActiveSpeedRegion(- speedRegionsRef.current,- Math.round(nextTimeSec * 1000),- );- // Chromium hard-caps HTMLMediaElement.playbackRate at 16×; above that the- // element can't actually play faster and the shared clock (below) would- // desync from the real frame advance. Clamp the live preview to the native- // ceiling — the export path renders the true speed offline (WSOLA audio +- // offline frame retiming, gated on MAX_NATIVE_PLAYBACK_RATE).- const rate = Math.min(activeRegion?.speed ?? 1, MAX_NATIVE_PLAYBACK_RATE);- if (v.playbackRate !== rate) v.playbackRate = rate;- }- },- [onTimeChange],- );-- // Playback/time-mapping rAF — ported verbatim from VirtualPreview, plus- // publishing this frame's state to the shared clock for the webcam.- // biome-ignore lint/correctness/useExhaustiveDependencies: re-create when the active source swaps.- useEffect(() => {- let raf = 0;- const tick = () => {- raf = window.requestAnimationFrame(tick);- const v = videoRef.current;- if (!v || !Number.isFinite(v.currentTime)) {- return;- }- if (clockRef) {- clockRef.current.sourceTimeSec = v.currentTime;- clockRef.current.isPlaying = !v.paused;- clockRef.current.playbackRate = v.playbackRate;- clockRef.current.virtualTimeSec = virtualTimeSecRef.current;- }- const activeSourceId = videoSourcesRef.current[sourceIndexRef.current]?.id;- if (!v.paused) {- const inKeptSegment = locateSourcePosition(- playbackClipsRef.current,- v.currentTime,- activeSourceId,- );- if (!inKeptSegment) {- const nextKeptSegment = findNextKeptSegment(- playbackClipsRef.current,- clipsRef.current,- virtualTimeSecRef.current,- activeSourceId,- v.currentTime,- );- if (nextKeptSegment) {- const rawTargetTime = getRawVirtualStartTime(nextKeptSegment, clipsRef.current);- seekToVirtualTime(rawTargetTime, true);- return;- }- v.pause();- updateVirtualTime(virtualDurationSecRef.current);- setIsPlaying(false);- return;- }- }- if (v.readyState >= 2) {- setSourceTimeSec(v.currentTime);- }- if (clipsRef.current.length === 0) {- updateVirtualTime(v.currentTime);- return;- }- if (isProgrammaticSeekRef.current) {- isProgrammaticSeekRef.current = false;- const pos = locateSourcePosition(clipsRef.current, v.currentTime, activeSourceId);- if (pos) updateVirtualTime(clampVirtualTime(clipsRef.current, pos.virtualTimeSec));- return;- }- const position = locateSourcePosition(clipsRef.current, v.currentTime, activeSourceId);- if (!position) {- const nextClip = clipsRef.current.find(- (clip) => clip.timelineStartSec > virtualTimeSecRef.current + 0.001,- );- if (nextClip) seekToVirtualTime(nextClip.timelineStartSec, true);- else {- v.pause();- updateVirtualTime(virtualDurationSecRef.current);- setIsPlaying(false);- }- return;- }- const reachedClipEnd = v.currentTime >= (position.clip.sourceEndSec ?? Infinity) - 0.04;- if (reachedClipEnd) {- const nextClip = clipsRef.current[position.clipIndex + 1];- if (!nextClip) {- v.pause();- updateVirtualTime(virtualDurationSecRef.current);- setIsPlaying(false);- return;- }- seekToVirtualTime(nextClip.timelineStartSec, true);- return;- }- updateVirtualTime(clampVirtualTime(clipsRef.current, position.virtualTimeSec));- };- raf = window.requestAnimationFrame(tick);- return () => window.cancelAnimationFrame(raf);- }, [activeSource?.src]);-- const activeSourceKey = activeSource?.src ?? null;- // biome-ignore lint/correctness/useExhaustiveDependencies: re-run on source swap- useEffect(() => {- onVideoElement?.(videoRef.current);- return () => onVideoElement?.(null);- }, [onVideoElement, activeSourceKey]);-- const seekToVirtualTime = useCallback(- (nextVirtualTimeSec: number, preservePlayback = false) => {- const position = locateVirtualPosition(clips, nextVirtualTimeSec);- if (!position) {- updateVirtualTime(0);- setIsPlaying(false);- return;- }- const targetIndex = videoSources.findIndex((vs) => vs.id === position.clip.assetId);- const isAssetSwitch = targetIndex >= 0 && targetIndex !== sourceIndex;- const shouldContinuePlayback = preservePlayback && isPlaying;-- if (isAssetSwitch) {- setSourceIndex(targetIndex);- setLoadState("loading");- updateVirtualTime(position.virtualTimeSec);- pendingSeekRef.current = {- sourceTimeSec: position.sourceTimeSec,- play: shouldContinuePlayback,- };- return;- }-- const video = videoRef.current;- if (!video) return;-- isProgrammaticSeekRef.current = true;- updateVirtualTime(position.virtualTimeSec);- if (Math.abs(video.currentTime - position.sourceTimeSec) > 0.01) {- video.currentTime = position.sourceTimeSec;- }- if (shouldContinuePlayback) {- void video.play().catch(() => setIsPlaying(false));- }- },- [clips, videoSources, sourceIndex, isPlaying, updateVirtualTime],- );-- const seekToSourceTime = useCallback((sourceTimeSec: number) => {- const video = videoRef.current;- if (!video) return;- isProgrammaticSeekRef.current = true;- if (Math.abs(video.currentTime - sourceTimeSec) > 0.01) {- video.currentTime = sourceTimeSec;- }- }, []);-- useEffect(() => {- if (!seekTarget) return;- if (seekTarget.isSource) {- seekToSourceTime(seekTarget.timeSec);- } else {- seekToVirtualTime(seekTarget.timeSec);- }- }, [seekTarget, seekToVirtualTime, seekToSourceTime]);-- // --- Pixi compositor ------------------------------------------------- const appRef = useRef<Application | null>(null);- const spriteRef = useRef<Sprite | null>(null);- const maskRef = useRef<Graphics | null>(null);- const cameraContainerRef = useRef<Container | null>(null);- const [pixiReady, setPixiReady] = useState(false);-- // Keep the canvas host positioned/sized exactly over the hidden video's- // rendered (contain-fit) box — same rect-tracking technique- // CursorPreviewLayer already uses for its own overlay.- // biome-ignore lint/correctness/useExhaustiveDependencies: re-run on source swap so the observer re-attaches- useEffect(() => {- const video = videoRef.current;- const frame = frameRef.current;- const host = canvasHostRef.current;- if (!video || !frame || !host) return;- const update = () => {- const videoRect = video.getBoundingClientRect();- const frameRect = frame.getBoundingClientRect();- if (videoRect.width <= 0 || videoRect.height <= 0) return;- const width = Math.round(videoRect.width);- const height = Math.round(videoRect.height);- host.style.left = `${Math.round(videoRect.left - frameRect.left)}px`;- host.style.top = `${Math.round(videoRect.top - frameRect.top)}px`;- host.style.width = `${width}px`;- host.style.height = `${height}px`;- setCanvasSize((prev) =>- prev.width === width && prev.height === height ? prev : { width, height },- );- };- update();- const ro = new ResizeObserver(update);- ro.observe(video);- ro.observe(frame);- return () => ro.disconnect();- }, [activeSourceKey]);-- // Create the Pixi Application + video sprite once per active source.- // biome-ignore lint/correctness/useExhaustiveDependencies: re-create when the active source swaps- useEffect(() => {- const video = videoRef.current;- const host = canvasHostRef.current;- if (!video || !host || !activeSource) return;- let mounted = true;- let app: Application | null = null;-- (async () => {- app = new Application();- await app.init({- width: canvasSize.width || 1,- height: canvasSize.height || 1,- backgroundAlpha: 0,- antialias: true,- resolution: window.devicePixelRatio || 1,- autoDensity: true,- });- if (!mounted) {- app.destroy(true, { children: true, texture: true, textureSource: true });- return;- }- app.ticker.maxFPS = 60;- host.appendChild(app.canvas);- appRef.current = app;-- const source = VideoSource.from(video);- (source as unknown as { autoPlay: boolean }).autoPlay = false;- (source as unknown as { autoUpdate: boolean }).autoUpdate = true;- const texture = Texture.from(source);- const sprite = new Sprite(texture);- const mask = new Graphics();- const cameraContainer = new Container();- cameraContainer.addChild(sprite);- cameraContainer.mask = mask;- app.stage.addChild(mask, cameraContainer);-- spriteRef.current = sprite;- maskRef.current = mask;- cameraContainerRef.current = cameraContainer;- setPixiReady(true);- })();-- return () => {- mounted = false;- setPixiReady(false);- if (app?.renderer) {- const canvas = app.canvas;- if (canvas.parentElement === host) host.removeChild(canvas);- app.destroy(true, { children: true, texture: true, textureSource: true });- }- appRef.current = null;- spriteRef.current = null;- maskRef.current = null;- cameraContainerRef.current = null;- };- }, [activeSourceKey]);-- // Resize the renderer + redraw the rounded-corner mask whenever the- // measured box or the border-radius setting changes.- useEffect(() => {- if (!pixiReady) return;- const app = appRef.current;- const mask = maskRef.current;- const sprite = spriteRef.current;- if (!app || !mask || !sprite) return;- const { width, height } = canvasSize;- if (width <= 0 || height <= 0) return;- app.renderer.resize(width, height);- sprite.width = width;- sprite.height = height;- mask.clear();- mask.roundRect(0, 0, width, height, settings.borderRadius).fill({ color: 0xffffff });- }, [pixiReady, canvasSize, settings.borderRadius]);-- // Zoom/pan: same easing math as before (computeZoomPreviewTransform),- // applied as a Pixi container transform instead of a CSS `transform`- // string. Pixi composes scale-then-position around origin (0,0) by- // default, matching CSS's `translate() scale()` composition order with- // `transform-origin: 0 0` — so the percentage-based translate output- // maps directly onto pixel offsets of the (pre-scale) canvas size.- useEffect(() => {- if (!pixiReady) return;- const cameraContainer = cameraContainerRef.current;- if (!cameraContainer) return;- const activeSpeedRegion = findActiveSpeedRegion(- speedRegionsRef.current,- Math.round(virtualTimeSec * 1000),- );- const playbackRate = activeSpeedRegion?.speed ?? 1;- const transform =- zoomRegions.length === 0- ? IDENTITY_ZOOM_TRANSFORM- : computeZoomPreviewTransform(zoomRegions, virtualTimeSec * 1000, undefined, playbackRate);- cameraContainer.scale.set(transform.scale);- cameraContainer.position.set(- (transform.translateXPercent / 100) * canvasSize.width,- (transform.translateYPercent / 100) * canvasSize.height,- );- }, [pixiReady, zoomRegions, virtualTimeSec, canvasSize]);-- return (- <div className={styles.container}>- {activeSource ? (- <div- ref={frameRef}- className={styles.videoFrame}- style={{ cursor: settings.cursorShow ? "none" : undefined }}- >- <video- key={activeSource.src}- ref={videoRef}- src={activeSource.src}- className={styles.video}- preload="metadata"- playsInline- onLoadedMetadata={(e) => {- setLoadState("ready");- onLoadedMetadata?.(e.currentTarget.duration, activeSource.id);- if (pendingSeekRef.current) {- const { sourceTimeSec, play } = pendingSeekRef.current;- pendingSeekRef.current = null;- e.currentTarget.currentTime = sourceTimeSec;- if (play) {- void e.currentTarget.play().catch(() => setIsPlaying(false));- }- } else if (clips.length > 0) {- seekToVirtualTime(virtualTimeSec);- }- }}- onWaiting={() => setLoadState("loading")}- onCanPlay={() => setLoadState("ready")}- onError={() => {- pendingSeekRef.current = null;- setLoadState("error");- setIsPlaying(false);- onVideoError?.();- }}- onPause={() => setIsPlaying(false)}- onPlay={() => setIsPlaying(true)}- onEnded={() => setIsPlaying(false)}- />- <div ref={canvasHostRef} className={styles.canvasHost} />- {loadState !== "ready" && (- <div className={styles.overlay}>- {loadState === "error" ? "Video preview could not be loaded." : "Loading preview…"}- </div>- )}- <CursorPreviewLayer- videoPath={activeSource ? fromFileUrl(activeSource.src) : null}- currentTimeSec={sourceTimeSec}- isPlaying={isPlaying}- />- </div>- ) : (- <div className={styles.placeholder}>Attach a video to start previewing.</div>- )}- </div>- );-}diff --git a/src/components/ui/accordion.tsx b/src/components/ui/accordion.tsxdeleted file mode 100644index 22456b252..000000000--- a/src/components/ui/accordion.tsx+++ /dev/null@@ -1,55 +0,0 @@-import * as AccordionPrimitive from "@radix-ui/react-accordion";-import { ChevronDown } from "lucide-react";-import * as React from "react";--import { cn } from "@/lib/utils";--const Accordion = AccordionPrimitive.Root;--const AccordionItem = React.forwardRef<- React.ElementRef<typeof AccordionPrimitive.Item>,- React.ComponentPropsWithoutRef<typeof AccordionPrimitive.Item>->(({ className, ...props }, ref) => (- <AccordionPrimitive.Item- ref={ref}- className={cn("border-b border-white/5", className)}- {...props}- />-));-AccordionItem.displayName = "AccordionItem";--const AccordionTrigger = React.forwardRef<- React.ElementRef<typeof AccordionPrimitive.Trigger>,- React.ComponentPropsWithoutRef<typeof AccordionPrimitive.Trigger>->(({ className, children, ...props }, ref) => (- <AccordionPrimitive.Header className="flex">- <AccordionPrimitive.Trigger- ref={ref}- className={cn(- "flex flex-1 items-center justify-between py-3 text-sm font-medium text-slate-200 transition-all hover:text-white [&[data-state=open]>svg]:rotate-180",- className,- )}- {...props}- >- {children}- <ChevronDown className="h-4 w-4 shrink-0 text-slate-400 transition-transform duration-200" />- </AccordionPrimitive.Trigger>- </AccordionPrimitive.Header>-));-AccordionTrigger.displayName = AccordionPrimitive.Trigger.displayName;--const AccordionContent = React.forwardRef<- React.ElementRef<typeof AccordionPrimitive.Content>,- React.ComponentPropsWithoutRef<typeof AccordionPrimitive.Content>->(({ className, children, ...props }, ref) => (- <AccordionPrimitive.Content- ref={ref}- className="overflow-hidden text-sm data-[state=closed]:animate-accordion-up data-[state=open]:animate-accordion-down"- {...props}- >- <div className={cn("pb-4 pt-0", className)}>{children}</div>- </AccordionPrimitive.Content>-));-AccordionContent.displayName = AccordionPrimitive.Content.displayName;--export { Accordion, AccordionContent, AccordionItem, AccordionTrigger };diff --git a/src/components/ui/card.tsx b/src/components/ui/card.tsxdeleted file mode 100644index 048076444..000000000--- a/src/components/ui/card.tsx+++ /dev/null@@ -1,55 +0,0 @@-import * as React from "react";--import { cn } from "@/lib/utils";--const Card = React.forwardRef<HTMLDivElement, React.HTMLAttributes<HTMLDivElement>>(- ({ className, ...props }, ref) => (- <div- ref={ref}- className={cn("rounded-xl border bg-card text-card-foreground shadow", className)}- {...props}- />- ),-);-Card.displayName = "Card";--const CardHeader = React.forwardRef<HTMLDivElement, React.HTMLAttributes<HTMLDivElement>>(- ({ className, ...props }, ref) => (- <div ref={ref} className={cn("flex flex-col space-y-1.5 p-6", className)} {...props} />- ),-);-CardHeader.displayName = "CardHeader";--const CardTitle = React.forwardRef<HTMLDivElement, React.HTMLAttributes<HTMLDivElement>>(- ({ className, ...props }, ref) => (- <div- ref={ref}- className={cn("font-semibold leading-none tracking-tight", className)}- {...props}- />- ),-);-CardTitle.displayName = "CardTitle";--const CardDescription = React.forwardRef<HTMLDivElement, React.HTMLAttributes<HTMLDivElement>>(- ({ className, ...props }, ref) => (- <div ref={ref} className={cn("text-sm text-muted-foreground", className)} {...props} />- ),-);-CardDescription.displayName = "CardDescription";--const CardContent = React.forwardRef<HTMLDivElement, React.HTMLAttributes<HTMLDivElement>>(- ({ className, ...props }, ref) => (- <div ref={ref} className={cn("p-6 pt-0", className)} {...props} />- ),-);-CardContent.displayName = "CardContent";--const CardFooter = React.forwardRef<HTMLDivElement, React.HTMLAttributes<HTMLDivElement>>(- ({ className, ...props }, ref) => (- <div ref={ref} className={cn("flex items-center p-6 pt-0", className)} {...props} />- ),-);-CardFooter.displayName = "CardFooter";--export { Card, CardContent, CardDescription, CardFooter, CardHeader, CardTitle };diff --git a/src/components/ui/color-picker.tsx b/src/components/ui/color-picker.tsxdeleted file mode 100644index 72f0135e2..000000000--- a/src/components/ui/color-picker.tsx+++ /dev/null@@ -1,159 +0,0 @@-import { HsvaColor, hexToHsva } from "@uiw/color-convert";-import Block from "@uiw/react-color-block";-import Colorful from "@uiw/react-color-colorful";-import { useEffect, useState } from "react";-import { Button } from "./button";-import { Input } from "./input";--type BaseProps = {- selectedColor: string;- colorPalette: string[];- onUpdateColor: (color: string) => void;-};--type ColorPickerProps =- | (BaseProps & {- clearBackgroundOption?: false;- translations: Record<"colorWheel" | "colorPalette", string>;- })- | (BaseProps & {- clearBackgroundOption: true;- translations: Record<"colorWheel" | "colorPalette" | "clearBackground", string>;- });--export default function ColorPicker(props: ColorPickerProps) {- const { selectedColor, colorPalette, translations, onUpdateColor } = props;- const [colorMode, setColorMode] = useState<"wheel" | "palette">("wheel");- const [hexInput, setHexInput] = useState(selectedColor);- const [transparentColorHSVA, setTransparentColorHSVA] = useState<HsvaColor>({- h: 0,- s: 0,- v: 0,- a: 0,- });-- useEffect(() => {- setHexInput(selectedColor);- }, [selectedColor]);-- const getTextColor = (color: string) => {- if (color === "transparent") return "#ffffff";- const r = parseInt(color.slice(1, 3), 16);- const g = parseInt(color.slice(3, 5), 16);- const b = parseInt(color.slice(5, 7), 16);- const luminance = 0.299 * r + 0.587 * g + 0.114 * b;- if (luminance > 186) return "#000000";- return "#ffffff";- };-- // Prefix a # when the user typed a bare hex value.- const normalizeHexDraft = (raw: string) => {- const trimmed = raw.trim();- if (trimmed === "") return "";- if (/^[0-9A-Fa-f]/.test(trimmed[0])) return `#${trimmed}`;- return trimmed;- };-- const handleColorInputChange = (e: React.ChangeEvent<HTMLInputElement>) => {- const normalized = normalizeHexDraft(e.target.value);- setHexInput(normalized);- // Only push when it's a complete #RGB or #RRGGBB value.- const isValidHexColor =- /^#[0-9A-Fa-f]{3}$/.test(normalized) || /^#[0-9A-Fa-f]{6}$/.test(normalized);- if (isValidHexColor) {- onUpdateColor(normalized);- }- };-- const toTransparent = (color: string) => {- if (color === "transparent") return;- const hsva = hexToHsva(color);- hsva.a = 0;- return hsva;- };- return (- <div className="p-1 flex flex-col gap-4 items-center">- <div className="flex items-center gap-2 w-full">- <Button- variant="outline"- size="sm"- className="w-full h-9 justify-start gap-2 bg-white/5 border-white/10 hover:bg-white/10 px-2"- onClick={() => setColorMode("wheel")}- style={{- backgroundColor: colorMode === "wheel" ? "#34B27B" : "transparent",- }}- >- <span className="text-xs text-slate-300 truncate flex-1 text-left">- {translations.colorWheel}- </span>- </Button>- <Button- variant="outline"- size="sm"- className="w-full h-9 justify-start gap-2 bg-white/5 border-white/10 hover:bg-white/10 px-2"- onClick={() => setColorMode("palette")}- style={{- backgroundColor: colorMode === "palette" ? "#34B27B" : "transparent",- }}- >- <span className="text-xs text-slate-300 truncate flex-1 text-left">- {translations.colorPalette}- </span>- </Button>- </div>- {colorMode === "wheel" && (- <>- <div- className={`w-full h-20 flex items-center justify-center border border-white/10 rounded-lg`}- style={{ backgroundColor: selectedColor }}- >- <span style={{ color: getTextColor(selectedColor) }}>{selectedColor}</span>- </div>- <Colorful- color={selectedColor !== "transparent" ? selectedColor : transparentColorHSVA}- onChange={(color) => {- onUpdateColor(color.hex);- }}- style={{- borderRadius: "8px",- }}- disableAlpha={true}- />- <Input- type="text"- value={hexInput}- className="w-full h-9 rounded-md border border-white/10 bg-white/5 px-2 text-xs text-slate-200 outline-none focus:border-[#34B27B]/50 focus:ring-1 focus:ring-[#34B27B]/30 [appearance:textfield] [&::-webkit-outer-spin-button]:appearance-none [&::-webkit-inner-spin-button]:appearance-none"- onChange={handleColorInputChange}- />- </>- )}- {colorMode === "palette" && (- <Block- color={selectedColor !== "transparent" ? selectedColor : transparentColorHSVA}- colors={colorPalette}- onChange={(color) => {- onUpdateColor(color.hex);- }}- style={{- width: "100%",- borderRadius: "8px",- }}- />- )}- {props.clearBackgroundOption === true && (- <Button- variant="ghost"- size="sm"- className="w-full mt-2 text-xs h-7 hover:bg-white/5 text-slate-400"- onClick={() => {- const hsva = toTransparent(selectedColor);- if (hsva) setTransparentColorHSVA(hsva);- onUpdateColor("transparent");- }}- >- {props.translations.clearBackground}- </Button>- )}- </div>- );-}diff --git a/src/components/ui/content-clamp.tsx b/src/components/ui/content-clamp.tsxdeleted file mode 100644index c0600c19f..000000000--- a/src/components/ui/content-clamp.tsx+++ /dev/null@@ -1,81 +0,0 @@-"use client";--import * as React from "react";--import { cn } from "@/lib/utils";-import { Popover, PopoverArrow, PopoverContent, PopoverTrigger } from "./popover";--interface ContentClampProps extends React.HTMLAttributes<HTMLDivElement> {- children: React.ReactNode;- truncateLength?: number;-}--function ContentClamp({ children, className, truncateLength = 50, ...props }: ContentClampProps) {- const text = typeof children === "string" ? children : String(children ?? "");- const isTruncated = text.length > truncateLength;-- const [open, setOpen] = React.useState(false);- const timeoutRef = React.useRef<NodeJS.Timeout | null>(null);-- const handleMouseEnter = () => {- if (timeoutRef.current) {- clearTimeout(timeoutRef.current);- timeoutRef.current = null;- }- setOpen(true);- };-- const handleMouseLeave = () => {- timeoutRef.current = setTimeout(() => {- setOpen(false);- }, 100);- };-- React.useEffect(() => {- return () => {- if (timeoutRef.current) {- clearTimeout(timeoutRef.current);- }- };- }, []);-- if (!isTruncated) {- return (- <div className={cn("inline", className)} {...props}>- {children}- </div>- );- }-- const truncatedText = text.slice(0, truncateLength) + "...";-- return (- <Popover open={open} onOpenChange={setOpen}>- <PopoverTrigger asChild>- <span- className={className}- onMouseEnter={handleMouseEnter}- onMouseLeave={handleMouseLeave}- onClick={(e) => e.preventDefault()}- {...props}- >- {truncatedText}- </span>- </PopoverTrigger>- <PopoverContent- className="w-auto max-w-sm rounded-lg border border-white bg-popover p-3 text-sm text-popover-foreground"- sideOffset={8}- animated={false}- onMouseEnter={handleMouseEnter}- onMouseLeave={handleMouseLeave}- onPointerDownOutside={(e) => e.preventDefault()}- onClick={(e) => e.stopPropagation()}- >- <PopoverArrow className="fill-white" />- {children}- </PopoverContent>- </Popover>- );-}--export { ContentClamp };diff --git a/src/components/ui/dropdown-menu.tsx b/src/components/ui/dropdown-menu.tsxdeleted file mode 100644index eb140b971..000000000--- a/src/components/ui/dropdown-menu.tsx+++ /dev/null@@ -1,194 +0,0 @@-import * as DropdownMenuPrimitive from "@radix-ui/react-dropdown-menu";-import { Check, ChevronRight, Circle } from "lucide-react";-import * as React from "react";--import { cn } from "@/lib/utils";--const DropdownMenu = DropdownMenuPrimitive.Root;--const DropdownMenuTrigger = DropdownMenuPrimitive.Trigger;--const DropdownMenuGroup = DropdownMenuPrimitive.Group;--const DropdownMenuPortal = DropdownMenuPrimitive.Portal;--const DropdownMenuSub = DropdownMenuPrimitive.Sub;--const DropdownMenuRadioGroup = DropdownMenuPrimitive.RadioGroup;--const DropdownMenuSubTrigger = React.forwardRef<- React.ElementRef<typeof DropdownMenuPrimitive.SubTrigger>,- React.ComponentPropsWithoutRef<typeof DropdownMenuPrimitive.SubTrigger> & {- inset?: boolean;- }->(({ className, inset, children, ...props }, ref) => (- <DropdownMenuPrimitive.SubTrigger- ref={ref}- className={cn(- "flex cursor-default select-none items-center gap-2 rounded-sm px-2 py-1.5 text-sm outline-none focus:bg-accent data-[state=open]:bg-accent [&_svg]:pointer-events-none [&_svg]:size-4 [&_svg]:shrink-0",- inset && "pl-8",- className,- )}- {...props}- >- {children}- <ChevronRight className="ml-auto" />- </DropdownMenuPrimitive.SubTrigger>-));-DropdownMenuSubTrigger.displayName = DropdownMenuPrimitive.SubTrigger.displayName;--const DropdownMenuSubContent = React.forwardRef<- React.ElementRef<typeof DropdownMenuPrimitive.SubContent>,- React.ComponentPropsWithoutRef<typeof DropdownMenuPrimitive.SubContent>->(({ className, ...props }, ref) => (- <DropdownMenuPrimitive.SubContent- ref={ref}- className={cn(- "z-50 min-w-[8rem] overflow-hidden rounded-md border bg-popover p-1 text-popover-foreground shadow-lg data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2 origin-[--radix-dropdown-menu-content-transform-origin]",- className,- )}- {...props}- />-));-DropdownMenuSubContent.displayName = DropdownMenuPrimitive.SubContent.displayName;--const DropdownMenuContent = React.forwardRef<- React.ElementRef<typeof DropdownMenuPrimitive.Content>,- React.ComponentPropsWithoutRef<typeof DropdownMenuPrimitive.Content> & {- portalled?: boolean;- }->(({ className, sideOffset = 4, portalled = true, ...props }, ref) => {- const content = (- <DropdownMenuPrimitive.Content- ref={ref}- sideOffset={sideOffset}- className={cn(- "z-50 max-h-[var(--radix-dropdown-menu-content-available-height)] min-w-[8rem] overflow-y-auto overflow-x-hidden rounded-md border bg-popover p-1 text-popover-foreground shadow-md",- "data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2 origin-[--radix-dropdown-menu-content-transform-origin]",- className,- )}- {...props}- />- );-- if (!portalled) {- return content;- }-- return <DropdownMenuPrimitive.Portal>{content}</DropdownMenuPrimitive.Portal>;-});-DropdownMenuContent.displayName = DropdownMenuPrimitive.Content.displayName;--const DropdownMenuItem = React.forwardRef<- React.ElementRef<typeof DropdownMenuPrimitive.Item>,- React.ComponentPropsWithoutRef<typeof DropdownMenuPrimitive.Item> & {- inset?: boolean;- }->(({ className, inset, ...props }, ref) => (- <DropdownMenuPrimitive.Item- ref={ref}- className={cn(- "relative flex cursor-default select-none items-center gap-2 rounded-sm px-2 py-1.5 text-sm outline-none transition-colors focus:bg-accent focus:text-accent-foreground data-[disabled]:pointer-events-none data-[disabled]:opacity-50 [&>svg]:size-4 [&>svg]:shrink-0",- inset && "pl-8",- className,- )}- {...props}- />-));-DropdownMenuItem.displayName = DropdownMenuPrimitive.Item.displayName;--const DropdownMenuCheckboxItem = React.forwardRef<- React.ElementRef<typeof DropdownMenuPrimitive.CheckboxItem>,- React.ComponentPropsWithoutRef<typeof DropdownMenuPrimitive.CheckboxItem>->(({ className, children, checked, ...props }, ref) => (- <DropdownMenuPrimitive.CheckboxItem- ref={ref}- className={cn(- "relative flex cursor-default select-none items-center rounded-sm py-1.5 pl-8 pr-2 text-sm outline-none transition-colors focus:bg-accent focus:text-accent-foreground data-[disabled]:pointer-events-none data-[disabled]:opacity-50",- className,- )}- checked={checked}- {...props}- >- <span className="absolute left-2 flex h-3.5 w-3.5 items-center justify-center">- <DropdownMenuPrimitive.ItemIndicator>- <Check className="h-4 w-4" />- </DropdownMenuPrimitive.ItemIndicator>- </span>- {children}- </DropdownMenuPrimitive.CheckboxItem>-));-DropdownMenuCheckboxItem.displayName = DropdownMenuPrimitive.CheckboxItem.displayName;--const DropdownMenuRadioItem = React.forwardRef<- React.ElementRef<typeof DropdownMenuPrimitive.RadioItem>,- React.ComponentPropsWithoutRef<typeof DropdownMenuPrimitive.RadioItem>->(({ className, children, ...props }, ref) => (- <DropdownMenuPrimitive.RadioItem- ref={ref}- className={cn(- "relative flex cursor-default select-none items-center rounded-sm py-1.5 pl-8 pr-2 text-sm outline-none transition-colors focus:bg-accent focus:text-accent-foreground data-[disabled]:pointer-events-none data-[disabled]:opacity-50",- className,- )}- {...props}- >- <span className="absolute left-2 flex h-3.5 w-3.5 items-center justify-center">- <DropdownMenuPrimitive.ItemIndicator>- <Circle className="h-2 w-2 fill-current" />- </DropdownMenuPrimitive.ItemIndicator>- </span>- {children}- </DropdownMenuPrimitive.RadioItem>-));-DropdownMenuRadioItem.displayName = DropdownMenuPrimitive.RadioItem.displayName;--const DropdownMenuLabel = React.forwardRef<- React.ElementRef<typeof DropdownMenuPrimitive.Label>,- React.ComponentPropsWithoutRef<typeof DropdownMenuPrimitive.Label> & {- inset?: boolean;- }->(({ className, inset, ...props }, ref) => (- <DropdownMenuPrimitive.Label- ref={ref}- className={cn("px-2 py-1.5 text-sm font-semibold", inset && "pl-8", className)}- {...props}- />-));-DropdownMenuLabel.displayName = DropdownMenuPrimitive.Label.displayName;--const DropdownMenuSeparator = React.forwardRef<- React.ElementRef<typeof DropdownMenuPrimitive.Separator>,- React.ComponentPropsWithoutRef<typeof DropdownMenuPrimitive.Separator>->(({ className, ...props }, ref) => (- <DropdownMenuPrimitive.Separator- ref={ref}- className={cn("-mx-1 my-1 h-px bg-muted", className)}- {...props}- />-));-DropdownMenuSeparator.displayName = DropdownMenuPrimitive.Separator.displayName;--const DropdownMenuShortcut = ({ className, ...props }: React.HTMLAttributes<HTMLSpanElement>) => {- return (- <span className={cn("ml-auto text-xs tracking-widest opacity-60", className)} {...props} />- );-};-DropdownMenuShortcut.displayName = "DropdownMenuShortcut";--export {- DropdownMenu,- DropdownMenuCheckboxItem,- DropdownMenuContent,- DropdownMenuGroup,- DropdownMenuItem,- DropdownMenuLabel,- DropdownMenuPortal,- DropdownMenuRadioGroup,- DropdownMenuRadioItem,- DropdownMenuSeparator,- DropdownMenuShortcut,- DropdownMenuSub,- DropdownMenuSubContent,- DropdownMenuSubTrigger,- DropdownMenuTrigger,-};diff --git a/src/components/ui/input.tsx b/src/components/ui/input.tsxdeleted file mode 100644index 68ac869ee..000000000--- a/src/components/ui/input.tsx+++ /dev/null@@ -1,23 +0,0 @@-import * as React from "react";-import { cn } from "@/lib/utils";--export interface InputProps extends React.InputHTMLAttributes<HTMLInputElement> {}--const Input = React.forwardRef<HTMLInputElement, InputProps>(- ({ className, type, ...props }, ref) => {- return (- <input- type={type}- className={cn(- "flex h-10 w-full rounded-md border border-input bg-background px-3 py-2 text-sm ring-offset-background file:border-0 file:bg-transparent file:text-sm file:font-medium placeholder:text-muted-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 disabled:cursor-not-allowed disabled:opacity-50",- className,- )}- ref={ref}- {...props}- />- );- },-);-Input.displayName = "Input";--export { Input };diff --git a/src/components/ui/item-content.tsx b/src/components/ui/item-content.tsxdeleted file mode 100644index b87d4f541..000000000--- a/src/components/ui/item-content.tsx+++ /dev/null@@ -1,18 +0,0 @@-import type { PropsWithChildren } from "react";--interface ItemContentProps extends PropsWithChildren {- classes: string;-}--function ItemContent({ children, classes }: ItemContentProps) {- return (- <div- className={`bg-white/5 border border-white/10 rounded-md shadow-sm w-full flex flex-row items-center px-3 py-1 gap-2 transition-all duration-150 hover:bg-[#34B27B]/10 hover:shadow-lg ${classes}`}- style={{ minHeight: 40 }}- >- {children}- </div>- );-}--export default ItemContent;diff --git a/src/components/ui/label.tsx b/src/components/ui/label.tsxdeleted file mode 100644index fd6cbcc8b..000000000--- a/src/components/ui/label.tsx+++ /dev/null@@ -1,20 +0,0 @@-import * as React from "react";-import { cn } from "@/lib/utils";--export interface LabelProps extends React.LabelHTMLAttributes<HTMLLabelElement> {}--const Label = React.forwardRef<HTMLLabelElement, LabelProps>(({ className, ...props }, ref) => {- return (- <label- ref={ref}- className={cn(- "text-sm font-medium leading-none peer-disabled:cursor-not-allowed peer-disabled:opacity-70",- className,- )}- {...props}- />- );-});-Label.displayName = "Label";--export { Label };diff --git a/src/components/ui/select.tsx b/src/components/ui/select.tsxdeleted file mode 100644index bdbf64e9a..000000000--- a/src/components/ui/select.tsx+++ /dev/null@@ -1,170 +0,0 @@-"use client";--import * as SelectPrimitive from "@radix-ui/react-select";-import { Check, ChevronDown, ChevronUp } from "lucide-react";-import * as React from "react";--import { cn } from "@/lib/utils";--const Select = SelectPrimitive.Root;--const SelectGroup = SelectPrimitive.Group;--const SelectValue = SelectPrimitive.Value;--const SelectTrigger = React.forwardRef<- React.ElementRef<typeof SelectPrimitive.Trigger>,- React.ComponentPropsWithoutRef<typeof SelectPrimitive.Trigger>->(({ className, children, ...props }, ref) => (- <SelectPrimitive.Trigger- ref={ref}- className={cn(- "flex h-10 w-full items-center justify-between rounded-md border border-input bg-background px-3 py-2 text-sm ring-offset-background placeholder:text-muted-foreground focus:outline-none focus:ring-2 focus:ring-ring focus:ring-offset-2 disabled:cursor-not-allowed disabled:opacity-50 [&>span]:line-clamp-1",- className,- )}- {...props}- >- {children}- <SelectPrimitive.Icon asChild>- <ChevronDown className="h-4 w-4 opacity-50" />- </SelectPrimitive.Icon>- </SelectPrimitive.Trigger>-));-SelectTrigger.displayName = SelectPrimitive.Trigger.displayName;--const SelectScrollUpButton = React.forwardRef<- React.ElementRef<typeof SelectPrimitive.ScrollUpButton>,- React.ComponentPropsWithoutRef<typeof SelectPrimitive.ScrollUpButton>->(({ className, ...props }, ref) => (- <SelectPrimitive.ScrollUpButton- ref={ref}- className={cn("flex cursor-default items-center justify-center py-1", className)}- {...props}- >- <ChevronUp className="h-4 w-4" />- </SelectPrimitive.ScrollUpButton>-));-SelectScrollUpButton.displayName = SelectPrimitive.ScrollUpButton.displayName;--const SelectScrollDownButton = React.forwardRef<- React.ElementRef<typeof SelectPrimitive.ScrollDownButton>,- React.ComponentPropsWithoutRef<typeof SelectPrimitive.ScrollDownButton>->(({ className, ...props }, ref) => (- <SelectPrimitive.ScrollDownButton- ref={ref}- className={cn("flex cursor-default items-center justify-center py-1", className)}- {...props}- >- <ChevronDown className="h-4 w-4" />- </SelectPrimitive.ScrollDownButton>-));-SelectScrollDownButton.displayName = SelectPrimitive.ScrollDownButton.displayName;--const SelectContent = React.forwardRef<- React.ElementRef<typeof SelectPrimitive.Content>,- React.ComponentPropsWithoutRef<typeof SelectPrimitive.Content> & {- showScrollButtons?: boolean;- viewportClassName?: string;- }->(- (- {- className,- children,- position = "popper",- showScrollButtons = true,- viewportClassName,- ...props- },- ref,- ) => (- <SelectPrimitive.Portal>- <SelectPrimitive.Content- ref={ref}- className={cn(- /* Above Dialog (z-[10000]) and fullscreen overlays (e.g. z-[99999]) */- "relative z-[100000] max-h-96 min-w-[8rem] overflow-hidden rounded-md border bg-popover text-popover-foreground shadow-md data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2",- position === "popper" &&- "data-[side=bottom]:translate-y-1 data-[side=left]:-translate-x-1 data-[side=right]:translate-x-1",- className,- )}- position={position}- {...props}- >- {showScrollButtons ? <SelectScrollUpButton /> : null}- <SelectPrimitive.Viewport- className={cn(- "p-1",- position === "popper" &&- "max-h-[var(--radix-select-content-available-height)] w-full min-w-[var(--radix-select-trigger-width)]",- viewportClassName,- )}- >- {children}- </SelectPrimitive.Viewport>- {showScrollButtons ? <SelectScrollDownButton /> : null}- </SelectPrimitive.Content>- </SelectPrimitive.Portal>- ),-);-SelectContent.displayName = SelectPrimitive.Content.displayName;--const SelectLabel = React.forwardRef<- React.ElementRef<typeof SelectPrimitive.Label>,- React.ComponentPropsWithoutRef<typeof SelectPrimitive.Label>->(({ className, ...props }, ref) => (- <SelectPrimitive.Label- ref={ref}- className={cn("py-1.5 pl-8 pr-2 text-sm font-semibold", className)}- {...props}- />-));-SelectLabel.displayName = SelectPrimitive.Label.displayName;--const SelectItem = React.forwardRef<- React.ElementRef<typeof SelectPrimitive.Item>,- React.ComponentPropsWithoutRef<typeof SelectPrimitive.Item>->(({ className, children, ...props }, ref) => (- <SelectPrimitive.Item- ref={ref}- className={cn(- "relative flex w-full cursor-default select-none items-center rounded-sm py-1.5 pl-8 pr-2 text-sm outline-none focus:bg-accent focus:text-accent-foreground data-[disabled]:pointer-events-none data-[disabled]:opacity-50",- className,- )}- {...props}- >- <span className="absolute left-2 flex h-3.5 w-3.5 items-center justify-center">- <SelectPrimitive.ItemIndicator>- <Check className="h-4 w-4" />- </SelectPrimitive.ItemIndicator>- </span>-- <SelectPrimitive.ItemText>{children}</SelectPrimitive.ItemText>- </SelectPrimitive.Item>-));-SelectItem.displayName = SelectPrimitive.Item.displayName;--const SelectSeparator = React.forwardRef<- React.ElementRef<typeof SelectPrimitive.Separator>,- React.ComponentPropsWithoutRef<typeof SelectPrimitive.Separator>->(({ className, ...props }, ref) => (- <SelectPrimitive.Separator- ref={ref}- className={cn("-mx-1 my-1 h-px bg-muted", className)}- {...props}- />-));-SelectSeparator.displayName = SelectPrimitive.Separator.displayName;--export {- Select,- SelectContent,- SelectGroup,- SelectItem,- SelectLabel,- SelectScrollDownButton,- SelectScrollUpButton,- SelectSeparator,- SelectTrigger,- SelectValue,-};diff --git a/src/components/ui/slider.tsx b/src/components/ui/slider.tsxdeleted file mode 100644index deae89abf..000000000--- a/src/components/ui/slider.tsx+++ /dev/null@@ -1,23 +0,0 @@-import * as SliderPrimitive from "@radix-ui/react-slider";-import * as React from "react";--import { cn } from "@/lib/utils";--const Slider = React.forwardRef<- React.ElementRef<typeof SliderPrimitive.Root>,- React.ComponentPropsWithoutRef<typeof SliderPrimitive.Root>->(({ className, ...props }, ref) => (- <SliderPrimitive.Root- ref={ref}- className={cn("relative flex w-full touch-none select-none items-center", className)}- {...props}- >- <SliderPrimitive.Track className="relative h-1.5 w-full grow overflow-hidden rounded-full bg-white/10">- <SliderPrimitive.Range className="absolute h-full bg-[#34B27B]" />- </SliderPrimitive.Track>- <SliderPrimitive.Thumb className="block h-4 w-4 rounded-full border-2 border-[#34B27B] bg-[#34B27B] shadow transition-colors focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-[#34B27B]/50 disabled:pointer-events-none disabled:opacity-50" />- </SliderPrimitive.Root>-));-Slider.displayName = SliderPrimitive.Root.displayName;--export { Slider };diff --git a/src/components/ui/switch.tsx b/src/components/ui/switch.tsxdeleted file mode 100644index 860339fc9..000000000--- a/src/components/ui/switch.tsx+++ /dev/null@@ -1,30 +0,0 @@-import * as SwitchPrimitives from "@radix-ui/react-switch";-import * as React from "react";--import { cn } from "@/lib/utils";--const Switch = React.forwardRef<- React.ElementRef<typeof SwitchPrimitives.Root>,- React.ComponentPropsWithoutRef<typeof SwitchPrimitives.Root>->(({ className, ...props }, ref) => (- <SwitchPrimitives.Root- className={cn(- "peer inline-flex h-5 w-9 shrink-0 cursor-pointer items-center rounded-full border-2 border-transparent shadow-sm transition-colors focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 focus-visible:ring-offset-background disabled:cursor-not-allowed disabled:opacity-50",- "data-[state=checked]:bg-[#34B27B] data-[state=unchecked]:bg-[#52525b]",- className,- )}- {...props}- ref={ref}- >- <SwitchPrimitives.Thumb- className={cn(- "pointer-events-none block h-4 w-4 rounded-full shadow-lg ring-0 transition-transform",- "bg-white",- "data-[state=checked]:translate-x-4 data-[state=unchecked]:translate-x-0",- )}- />- </SwitchPrimitives.Root>-));-Switch.displayName = SwitchPrimitives.Root.displayName;--export { Switch };diff --git a/src/components/ui/toggle-group.tsx b/src/components/ui/toggle-group.tsxdeleted file mode 100644index a887a06ce..000000000--- a/src/components/ui/toggle-group.tsx+++ /dev/null@@ -1,56 +0,0 @@-"use client";--import * as ToggleGroupPrimitive from "@radix-ui/react-toggle-group";-import { type VariantProps } from "class-variance-authority";-import * as React from "react";-import { toggleVariants } from "@/components/ui/toggle";-import { cn } from "@/lib/utils";--const ToggleGroupContext = React.createContext<VariantProps<typeof toggleVariants>>({- size: "default",- variant: "default",-});--const ToggleGroup = React.forwardRef<- React.ElementRef<typeof ToggleGroupPrimitive.Root>,- React.ComponentPropsWithoutRef<typeof ToggleGroupPrimitive.Root> &- VariantProps<typeof toggleVariants>->(({ className, variant, size, children, ...props }, ref) => (- <ToggleGroupPrimitive.Root- ref={ref}- className={cn("flex items-center justify-center gap-1", className)}- {...props}- >- <ToggleGroupContext.Provider value={{ variant, size }}>{children}</ToggleGroupContext.Provider>- </ToggleGroupPrimitive.Root>-));--ToggleGroup.displayName = ToggleGroupPrimitive.Root.displayName;--const ToggleGroupItem = React.forwardRef<- React.ElementRef<typeof ToggleGroupPrimitive.Item>,- React.ComponentPropsWithoutRef<typeof ToggleGroupPrimitive.Item> &- VariantProps<typeof toggleVariants>->(({ className, children, variant, size, ...props }, ref) => {- const context = React.useContext(ToggleGroupContext);-- return (- <ToggleGroupPrimitive.Item- ref={ref}- className={cn(- toggleVariants({- variant: context.variant || variant,- size: context.size || size,- }),- className,- )}- {...props}- >- {children}- </ToggleGroupPrimitive.Item>- );-});--ToggleGroupItem.displayName = ToggleGroupPrimitive.Item.displayName;--export { ToggleGroup, ToggleGroupItem };diff --git a/src/components/ui/toggle.tsx b/src/components/ui/toggle.tsxdeleted file mode 100644index 4fd784086..000000000--- a/src/components/ui/toggle.tsx+++ /dev/null@@ -1,43 +0,0 @@-"use client";--import * as TogglePrimitive from "@radix-ui/react-toggle";-import { cva, type VariantProps } from "class-variance-authority";-import * as React from "react";--import { cn } from "@/lib/utils";--const toggleVariants = cva(- "inline-flex items-center justify-center rounded-md text-sm font-medium ring-offset-background transition-colors hover:bg-muted hover:text-muted-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 disabled:pointer-events-none disabled:opacity-50 data-[state=on]:bg-accent data-[state=on]:text-accent-foreground",- {- variants: {- variant: {- default: "bg-transparent",- outline: "border border-input bg-transparent hover:bg-accent hover:text-accent-foreground",- },- size: {- default: "h-10 px-3",- sm: "h-9 px-2.5",- lg: "h-11 px-5",- },- },- defaultVariants: {- variant: "default",- size: "default",- },- },-);--const Toggle = React.forwardRef<- React.ElementRef<typeof TogglePrimitive.Root>,- React.ComponentPropsWithoutRef<typeof TogglePrimitive.Root> & VariantProps<typeof toggleVariants>->(({ className, variant, size, ...props }, ref) => (- <TogglePrimitive.Root- ref={ref}- className={cn(toggleVariants({ variant, size, className }))}- {...props}- />-));--Toggle.displayName = TogglePrimitive.Root.displayName;--export { Toggle, toggleVariants };diff --git a/src/components/video-editor/EditorMenuBar.test.tsx b/src/components/video-editor/EditorMenuBar.test.tsxdeleted file mode 100644index 5011985a2..000000000--- a/src/components/video-editor/EditorMenuBar.test.tsx+++ /dev/null@@ -1,176 +0,0 @@-import "@testing-library/jest-dom";-import { cleanup, render, screen } from "@testing-library/react";-import userEvent from "@testing-library/user-event";-import { afterEach, beforeAll, describe, expect, it, vi } from "vitest";-import {- buildEditorMenuModel,- EditorMenuBar,- type EditorMenuBarProps,- formatShiftShortcut,- formatShortcut,-} from "./EditorMenuBar";--const LABELS: Record<string, string> = {- "common.actions.file": "File",- "common.actions.edit": "Edit",- "common.actions.view": "View",- "common.actions.quit": "Quit",- "common.actions.undo": "Undo",- "common.actions.redo": "Redo",- "common.actions.reload": "Reload",- "dialogs.unsavedChanges.newProject": "New Project",- "dialogs.unsavedChanges.loadProject": "Load Project…",- "dialogs.unsavedChanges.saveProject": "Save Project…",- "dialogs.unsavedChanges.saveProjectAs": "Save Project As…",-};--function makeProps(overrides: Partial<EditorMenuBarProps> = {}): EditorMenuBarProps {- return {- isMac: false,- t: (key: string) => LABELS[key] ?? key,- onNewProject: vi.fn(),- onLoadProject: vi.fn(),- onSaveProject: vi.fn(),- onSaveProjectAs: vi.fn(),- onQuit: vi.fn(),- onUndo: vi.fn(),- onRedo: vi.fn(),- onReload: vi.fn(),- canUndo: true,- canRedo: true,- ...overrides,- };-}--afterEach(() => {- cleanup();- vi.clearAllMocks();-});--describe("formatShortcut", () => {- it("uses Ctrl on non-mac and the ⌘ symbol on mac", () => {- expect(formatShortcut(false, "N")).toBe("Ctrl+N");- expect(formatShortcut(true, "N")).toBe("⌘N");- });-- it("formats shift combos per platform", () => {- expect(formatShiftShortcut(false, "S")).toBe("Ctrl+Shift+S");- expect(formatShiftShortcut(true, "S")).toBe("⌘⇧S");- });-});--describe("buildEditorMenuModel", () => {- it("returns the File, Edit and View menus with translated labels", () => {- const model = buildEditorMenuModel(makeProps());- expect(model.map((m) => m.id)).toEqual(["file", "edit", "view"]);- expect(model.map((m) => m.label)).toEqual(["File", "Edit", "View"]);- });-- it("wires each File item to its handler", () => {- const props = makeProps();- const [file] = buildEditorMenuModel(props);- const byId = Object.fromEntries(file.items.map((i) => [i.id, i]));-- byId["new-project"].onSelect();- byId["load-project"].onSelect();- byId["save-project"].onSelect();- byId["save-project-as"].onSelect();- byId.quit.onSelect();-- expect(props.onNewProject).toHaveBeenCalledOnce();- expect(props.onLoadProject).toHaveBeenCalledOnce();- expect(props.onSaveProject).toHaveBeenCalledOnce();- expect(props.onSaveProjectAs).toHaveBeenCalledOnce();- expect(props.onQuit).toHaveBeenCalledOnce();- });-- it("marks Quit as a destructive item after a separator", () => {- const [file] = buildEditorMenuModel(makeProps());- const quit = file.items.find((i) => i.id === "quit");- expect(quit).toMatchObject({ danger: true, separatorBefore: true });- });-- it("shows Ctrl-based shortcut hints on non-mac", () => {- const model = buildEditorMenuModel(makeProps({ isMac: false }));- const shortcuts = Object.fromEntries(- model.flatMap((m) => m.items).map((i) => [i.id, i.shortcut]),- );- expect(shortcuts).toMatchObject({- "new-project": "Ctrl+N",- "load-project": "Ctrl+O",- "save-project": "Ctrl+S",- "save-project-as": "Ctrl+Shift+S",- quit: "Ctrl+Q",- undo: "Ctrl+Z",- redo: "Ctrl+Y",- reload: "Ctrl+R",- });- });-- it("shows ⌘-based shortcut hints on mac (redo uses ⌘⇧Z)", () => {- const model = buildEditorMenuModel(makeProps({ isMac: true }));- const shortcuts = Object.fromEntries(- model.flatMap((m) => m.items).map((i) => [i.id, i.shortcut]),- );- expect(shortcuts).toMatchObject({- "new-project": "⌘N",- "save-project-as": "⌘⇧S",- undo: "⌘Z",- redo: "⌘⇧Z",- reload: "⌘R",- });- });-- it("disables Undo/Redo according to canUndo/canRedo", () => {- const model = buildEditorMenuModel(makeProps({ canUndo: false, canRedo: false }));- const edit = model.find((m) => m.id === "edit");- expect(edit?.items.find((i) => i.id === "undo")?.disabled).toBe(true);- expect(edit?.items.find((i) => i.id === "redo")?.disabled).toBe(true);-- const enabled = buildEditorMenuModel(makeProps({ canUndo: true, canRedo: true }));- const editEnabled = enabled.find((m) => m.id === "edit");- expect(editEnabled?.items.find((i) => i.id === "undo")?.disabled).toBe(false);- expect(editEnabled?.items.find((i) => i.id === "redo")?.disabled).toBe(false);- });-});--describe("<EditorMenuBar />", () => {- // Radix relies on pointer-capture / scroll APIs jsdom does not implement.- beforeAll(() => {- Element.prototype.hasPointerCapture = vi.fn(() => false);- Element.prototype.releasePointerCapture = vi.fn();- Element.prototype.scrollIntoView = vi.fn();- });-- it("renders the three top-level menu triggers", () => {- render(<EditorMenuBar {...makeProps()} />);- expect(screen.getByRole("button", { name: "File" })).toBeInTheDocument();- expect(screen.getByRole("button", { name: "Edit" })).toBeInTheDocument();- expect(screen.getByRole("button", { name: "View" })).toBeInTheDocument();- });-- it("opens the File menu and invokes the handler for a selected item", async () => {- const user = userEvent.setup();- const props = makeProps();- render(<EditorMenuBar {...props} />);-- await user.click(screen.getByRole("button", { name: "File" }));-- expect(await screen.findByText("New Project")).toBeInTheDocument();- expect(screen.getByText("Ctrl+N")).toBeInTheDocument();-- await user.click(screen.getByText("Save Project…"));- expect(props.onSaveProject).toHaveBeenCalledOnce();- });-- it("renders a disabled Undo item when canUndo is false", async () => {- const user = userEvent.setup();- const props = makeProps({ canUndo: false });- render(<EditorMenuBar {...props} />);-- await user.click(screen.getByRole("button", { name: "Edit" }));-- const undoItem = await screen.findByRole("menuitem", { name: /Undo/ });- expect(undoItem).toHaveAttribute("aria-disabled", "true");- });-});diff --git a/src/components/video-editor/EditorMenuBar.tsx b/src/components/video-editor/EditorMenuBar.tsxdeleted file mode 100644index 629f66482..000000000--- a/src/components/video-editor/EditorMenuBar.tsx+++ /dev/null@@ -1,198 +0,0 @@-import { Fragment } from "react";-import {- DropdownMenu,- DropdownMenuContent,- DropdownMenuItem,- DropdownMenuSeparator,- DropdownMenuShortcut,- DropdownMenuTrigger,-} from "@/components/ui/dropdown-menu";--export interface EditorMenuBarProps {- /** Whether the app is running on macOS. Drives shortcut-hint formatting. */- isMac: boolean;- /** Qualified-key translator (e.g. the `rawT` from `useI18n`). */- t: (qualifiedKey: string) => string;- onNewProject: () => void;- onLoadProject: () => void;- onSaveProject: () => void;- onSaveProjectAs: () => void;- onQuit: () => void;- onUndo: () => void;- onRedo: () => void;- onReload: () => void;- canUndo: boolean;- canRedo: boolean;-}--export interface EditorMenuItem {- id: string;- label: string;- /** Human-readable, platform-aware shortcut hint (e.g. "Ctrl+N" / "⌘N"). */- shortcut?: string;- onSelect: () => void;- disabled?: boolean;- /** Renders the item in a destructive (red) style, e.g. Quit. */- danger?: boolean;- /** Draws a separator immediately before this item. */- separatorBefore?: boolean;-}--export interface EditorMenu {- id: string;- label: string;- minWidthClass: string;- items: EditorMenuItem[];-}--/**- * Formats a menu shortcut hint for the current platform. macOS uses the symbol- * modifier with no separator ("⌘N"); everywhere else uses "Ctrl+N". These mirror- * the accelerators wired in the native menu (electron/main.ts) and the editor- * keydown handler, so the hints stay truthful.- */-export function formatShortcut(isMac: boolean, key: string): string {- return isMac ? `⌘${key}` : `Ctrl+${key}`;-}--export function formatShiftShortcut(isMac: boolean, key: string): string {- return isMac ? `⌘⇧${key}` : `Ctrl+Shift+${key}`;-}--/**- * Pure description of the editor's File / Edit / View menus. Kept separate from- * the rendering so the labels, shortcut hints, disabled states, and handler- * wiring can be unit-tested without mounting Radix/jsdom.- */-export function buildEditorMenuModel(props: EditorMenuBarProps): EditorMenu[] {- const { isMac, t } = props;-- return [- {- id: "file",- label: t("common.actions.file"),- minWidthClass: "min-w-[170px]",- items: [- {- id: "new-project",- label: t("dialogs.unsavedChanges.newProject"),- shortcut: formatShortcut(isMac, "N"),- onSelect: props.onNewProject,- },- {- id: "load-project",- label: t("dialogs.unsavedChanges.loadProject"),- shortcut: formatShortcut(isMac, "O"),- onSelect: props.onLoadProject,- separatorBefore: true,- },- {- id: "save-project",- label: t("dialogs.unsavedChanges.saveProject"),- shortcut: formatShortcut(isMac, "S"),- onSelect: props.onSaveProject,- },- {- id: "save-project-as",- label: t("dialogs.unsavedChanges.saveProjectAs"),- shortcut: formatShiftShortcut(isMac, "S"),- onSelect: props.onSaveProjectAs,- },- {- id: "quit",- label: t("common.actions.quit"),- shortcut: formatShortcut(isMac, "Q"),- onSelect: props.onQuit,- danger: true,- separatorBefore: true,- },- ],- },- {- id: "edit",- label: t("common.actions.edit"),- minWidthClass: "min-w-[130px]",- items: [- {- id: "undo",- label: t("common.actions.undo"),- shortcut: formatShortcut(isMac, "Z"),- onSelect: props.onUndo,- disabled: !props.canUndo,- },- {- id: "redo",- label: t("common.actions.redo"),- // Redo is bound to both Ctrl+Y and Ctrl+Shift+Z; show the- // idiomatic hint per platform (⌘⇧Z on macOS, Ctrl+Y elsewhere).- shortcut: isMac ? formatShiftShortcut(isMac, "Z") : formatShortcut(isMac, "Y"),- onSelect: props.onRedo,- disabled: !props.canRedo,- },- ],- },- {- id: "view",- label: t("common.actions.view"),- minWidthClass: "min-w-[130px]",- items: [- {- id: "reload",- label: t("common.actions.reload"),- shortcut: formatShortcut(isMac, "R"),- onSelect: props.onReload,- },- ],- },- ];-}--/**- * Custom in-app menu bar (File / Edit / View) shown in the editor's titlebar.- * Replaces the native OS menu bar that is auto-hidden on Windows/Linux- * (see electron/windows.ts).- */-export function EditorMenuBar(props: EditorMenuBarProps) {- const menus = buildEditorMenuModel(props);-- return (- <div className={`flex items-center gap-0.5 ${props.isMac ? "ml-14" : "ml-2"}`}>- {menus.map((menu) => (- <DropdownMenu key={menu.id}>- <DropdownMenuTrigger asChild>- <button- type="button"- className="px-2.5 py-1.5 rounded-lg text-[13px] font-semibold text-slate-300 hover:text-white hover:bg-white/[0.08] transition-all duration-150 outline-none focus-visible:ring-1 focus-visible:ring-white/20 focus-visible:bg-white/[0.08]"- >- {menu.label}- </button>- </DropdownMenuTrigger>- <DropdownMenuContent- align="start"- className={`bg-[#09090b]/95 backdrop-blur-md border border-white/[0.08] text-slate-200 ${menu.minWidthClass}`}- >- {menu.items.map((item) => (- <Fragment key={item.id}>- {item.separatorBefore && <DropdownMenuSeparator className="bg-white/[0.08]" />}- <DropdownMenuItem- onSelect={() => item.onSelect()}- disabled={item.disabled}- className={- item.danger- ? "hover:bg-red-500/20 focus:bg-red-500/20 focus:text-red-400 text-red-400 cursor-pointer justify-between"- : "hover:bg-white/[0.08] focus:bg-white/[0.08] focus:text-white cursor-pointer justify-between"- }- >- <span>{item.label}</span>- {item.shortcut && (- <DropdownMenuShortcut className="ml-2">{item.shortcut}</DropdownMenuShortcut>- )}- </DropdownMenuItem>- </Fragment>- ))}- </DropdownMenuContent>- </DropdownMenu>- ))}- </div>- );-}diff --git a/src/components/video-editor/backgroundImageUpload.test.ts b/src/components/video-editor/backgroundImageUpload.test.tsdeleted file mode 100644index d83ca3a03..000000000--- a/src/components/video-editor/backgroundImageUpload.test.ts+++ /dev/null@@ -1,20 +0,0 @@-import { describe, expect, it } from "vitest";-import { isSupportedBackgroundImageType } from "./backgroundImageUpload";--describe("background image upload validation", () => {- it("accepts PNG images for custom backgrounds", () => {- expect(isSupportedBackgroundImageType("image/png", "生成画像1.png")).toBe(true);- });-- it("accepts PNG images by extension when the browser does not provide a MIME type", () => {- expect(isSupportedBackgroundImageType("", "生成画像1.png")).toBe(true);- });-- it("keeps rejecting non-image uploads", () => {- expect(isSupportedBackgroundImageType("text/plain", "notes.txt")).toBe(false);- });-- it("does not allow extension fallback for explicit unsupported MIME types", () => {- expect(isSupportedBackgroundImageType("text/plain", "notes.png")).toBe(false);- });-});diff --git a/src/components/video-editor/backgroundImageUpload.ts b/src/components/video-editor/backgroundImageUpload.tsdeleted file mode 100644index ebc256a2b..000000000--- a/src/components/video-editor/backgroundImageUpload.ts+++ /dev/null@@ -1,20 +0,0 @@-const SUPPORTED_BACKGROUND_IMAGE_TYPES = new Set(["image/jpeg", "image/jpg", "image/png"]);-const SUPPORTED_BACKGROUND_IMAGE_EXTENSIONS = new Set([".jpg", ".jpeg", ".png"]);--export const BACKGROUND_IMAGE_ACCEPT = ".jpg,.jpeg,.png,image/jpeg,image/png";--export function isSupportedBackgroundImageType(type: string, fileName: string): boolean {- const normalizedType = type.trim().toLowerCase();- if (SUPPORTED_BACKGROUND_IMAGE_TYPES.has(normalizedType)) {- return true;- }-- if (normalizedType) {- return false;- }-- const lowerName = fileName.trim().toLowerCase();- return [...SUPPORTED_BACKGROUND_IMAGE_EXTENSIONS].some((extension) =>- lowerName.endsWith(extension),- );-}diff --git a/src/components/video-editor/regionClipboard.test.ts b/src/components/video-editor/regionClipboard.test.tsdeleted file mode 100644index f99f17eb2..000000000--- a/src/components/video-editor/regionClipboard.test.ts+++ /dev/null@@ -1,203 +0,0 @@-import { describe, expect, it } from "vitest";-import {- buildPastedAnnotation,- buildSpeedRegion,- buildZoomRegion,- extractAnnotationAttributes,- extractSpeedAttributes,- extractZoomAttributes,- replaceAnnotationAttributes,-} from "./regionClipboard";-import {- type AnnotationRegion,- DEFAULT_ANNOTATION_POSITION,- DEFAULT_ANNOTATION_SIZE,- DEFAULT_ANNOTATION_STYLE,- DEFAULT_FIGURE_DATA,- type SpeedRegion,- type ZoomRegion,-} from "./types";--const zoom: ZoomRegion = {- id: "zoom-1",- startMs: 1000,- endMs: 3000,- depth: 4,- customScale: 2.75,- focus: { cx: 0.2, cy: 0.8 },- focusMode: "manual",- rotationPreset: "iso",- source: "manual",-};--const speed: SpeedRegion = { id: "speed-1", startMs: 0, endMs: 500, speed: 2 };--const annotation: AnnotationRegion = {- id: "annotation-1",- startMs: 0,- endMs: 2000,- type: "figure",- content: "hello",- position: { x: 10, y: 90 },- size: { width: 40, height: 25 },- style: { ...DEFAULT_ANNOTATION_STYLE, color: "#ff0000", textAnimation: "pop" },- zIndex: 3,- figureData: { ...DEFAULT_FIGURE_DATA, color: "#123456" },-};--describe("zoom attribute copy/paste", () => {- it("round-trips the copyable attributes onto a different clip while keeping its identity/timing", () => {- const attrs = extractZoomAttributes(zoom);- const target: ZoomRegion = {- id: "zoom-2",- startMs: 9000,- endMs: 9500,- depth: 1,- focus: { cx: 0.5, cy: 0.5 },- source: "manual",- };- const result = buildZoomRegion(target, attrs);-- expect(result.id).toBe("zoom-2");- expect(result.startMs).toBe(9000);- expect(result.endMs).toBe(9500);- expect(result.depth).toBe(4);- expect(result.customScale).toBe(2.75);- expect(result.focus).toEqual({ cx: 0.2, cy: 0.8 });- expect(result.focusMode).toBe("manual");- expect(result.rotationPreset).toBe("iso");- });-- it("deep-copies focus so the source and target are decoupled", () => {- const attrs = extractZoomAttributes(zoom);- const result = buildZoomRegion({ ...zoom, id: "zoom-2" }, attrs);- result.focus.cx = 0.99;- expect(zoom.focus.cx).toBe(0.2);- });-});--describe("speed attribute copy/paste", () => {- it("copies only the speed value", () => {- const attrs = extractSpeedAttributes(speed);- const target: SpeedRegion = { id: "speed-2", startMs: 4000, endMs: 5000, speed: 1 };- const result = buildSpeedRegion(target, attrs);- expect(result).toEqual({ id: "speed-2", startMs: 4000, endMs: 5000, speed: 2 });- });-});--describe("annotation copy captures everything", () => {- it("captures styling plus content, type, and position", () => {- const attrs = extractAnnotationAttributes(annotation);- expect(attrs.type).toBe("figure");- expect(attrs.content).toBe("hello");- expect(attrs.position).toEqual({ x: 10, y: 90 });- expect(attrs.style.color).toBe("#ff0000");- expect(attrs.figureData?.color).toBe("#123456");- });-});--describe("paste onto an existing annotation applies styling only", () => {- it("overwrites the look/feel but keeps the target's content, position, timing, and zIndex", () => {- const attrs = extractAnnotationAttributes(annotation);- const target: AnnotationRegion = {- id: "annotation-2",- startMs: 7000,- endMs: 8000,- type: "text",- content: "world",- position: { ...DEFAULT_ANNOTATION_POSITION },- size: { ...DEFAULT_ANNOTATION_SIZE },- style: { ...DEFAULT_ANNOTATION_STYLE },- zIndex: 9,- };- const result = replaceAnnotationAttributes(target, attrs);-- expect(result.content).toBe("world");- expect(result.position).toEqual(DEFAULT_ANNOTATION_POSITION);- expect(result.startMs).toBe(7000);- expect(result.zIndex).toBe(9);- expect(result.style.color).toBe("#ff0000");- expect(result.style.textAnimation).toBe("pop");- expect(result.size).toEqual({ width: 40, height: 25 });- // Target is text, so the copied figure's figureData must NOT attach (F5 guard).- expect(result.figureData).toBeUndefined();- });-- it("keeps the target's own figure data when the copied region has none", () => {- const textAttrs = extractAnnotationAttributes({ ...annotation, figureData: undefined });- const figureTarget: AnnotationRegion = { ...annotation, id: "annotation-3" };- const result = replaceAnnotationAttributes(figureTarget, textAttrs);- expect(result.figureData?.color).toBe("#123456");- });-});--describe("paste as a new annotation clones the full copy", () => {- it("clones type, content, styling, and position; takes timing/identity from the base", () => {- const attrs = extractAnnotationAttributes(annotation);- const result = buildPastedAnnotation(- { id: "annotation-4", startMs: 12000, endMs: 14000, zIndex: 5 },- attrs,- );-- expect(result.id).toBe("annotation-4");- expect(result.startMs).toBe(12000);- expect(result.endMs).toBe(14000);- expect(result.zIndex).toBe(5);- expect(result.type).toBe("figure");- expect(result.content).toBe("hello");- expect(result.position).toEqual({ x: 10, y: 90 });- expect(result.style.color).toBe("#ff0000");- expect(result.figureData?.color).toBe("#123456");- });-- it("deep-copies position so source and clone are decoupled", () => {- const attrs = extractAnnotationAttributes(annotation);- const result = buildPastedAnnotation(- { id: "annotation-5", startMs: 0, endMs: 1000, zIndex: 1 },- attrs,- );- result.position.x = 99;- expect(annotation.position.x).toBe(10);- });-});--describe("zoom paste replaces customScale destructively (F4)", () => {- it("clears the target's customScale when the copied zoom is preset-only", () => {- const presetOnly = extractZoomAttributes({ ...zoom, customScale: undefined });- const target: ZoomRegion = { ...zoom, id: "zoom-3", customScale: 1.5 };- const result = buildZoomRegion(target, presetOnly);- expect(result.customScale).toBeUndefined();- });-});--describe("figureData guard on paste-onto-existing (F5)", () => {- it("does not attach figureData onto a non-figure target", () => {- const figureAttrs = extractAnnotationAttributes(annotation);- const textTarget: AnnotationRegion = {- id: "annotation-6",- startMs: 0,- endMs: 1000,- type: "text",- content: "hi",- position: { ...DEFAULT_ANNOTATION_POSITION },- size: { ...DEFAULT_ANNOTATION_SIZE },- style: { ...DEFAULT_ANNOTATION_STYLE },- zIndex: 1,- };- const result = replaceAnnotationAttributes(textTarget, figureAttrs);- expect(result.figureData).toBeUndefined();- // Styling still applies regardless of type.- expect(result.style.color).toBe("#ff0000");- });-- it("applies figureData when the target is itself a figure", () => {- const figureAttrs = extractAnnotationAttributes(annotation);- const figureTarget: AnnotationRegion = {- ...annotation,- id: "annotation-7",- figureData: { ...DEFAULT_FIGURE_DATA, color: "#000000" },- };- const result = replaceAnnotationAttributes(figureTarget, figureAttrs);- expect(result.figureData?.color).toBe("#123456");- });-});diff --git a/src/components/video-editor/regionClipboard.ts b/src/components/video-editor/regionClipboard.tsdeleted file mode 100644index 876da4387..000000000--- a/src/components/video-editor/regionClipboard.ts+++ /dev/null@@ -1,158 +0,0 @@-import type {- AnnotationPosition,- AnnotationRegion,- AnnotationSize,- AnnotationTextStyle,- AnnotationType,- BlurData,- FigureData,- PlaybackSpeed,- Rotation3DPreset,- SpeedRegion,- ZoomDepth,- ZoomFocus,- ZoomFocusMode,- ZoomRegion,-} from "./types";--/** The copyable attributes of each region, tagged with its `kind` so paste can discriminate.- * Trim has no attributes, so it isn't copyable. */-export type CopiedZoom = {- kind: "zoom";- depth: ZoomDepth;- customScale?: number;- focus: ZoomFocus;- focusMode?: ZoomFocusMode;- rotationPreset?: Rotation3DPreset;-};--export type CopiedSpeed = { kind: "speed"; speed: PlaybackSpeed };--/** Annotation copy captures everything; paste then uses only the styling for an existing- * region, or the full set for a brand-new one. */-export type CopiedAnnotation = {- kind: "annotation";- // Styling — applied both when pasting onto an existing region and onto a new one.- style: AnnotationTextStyle;- size: AnnotationSize;- figureData?: FigureData;- blurData?: BlurData;- // Content & placement — used only when pasting as a brand-new region.- type: AnnotationType;- content: string;- textContent?: string;- imageContent?: string;- position: AnnotationPosition;-};--export type CopiedRegion = CopiedZoom | CopiedSpeed | CopiedAnnotation;--/** Session clipboard for "copy/paste region attributes" (not undoable, not persisted).- * Module-level so it's shared regardless of which editor instance copied. */-let clipboard: CopiedRegion | null = null;--export function getCopiedRegion(): CopiedRegion | null {- return clipboard;-}--export function setCopiedRegion(region: CopiedRegion): void {- clipboard = region;-}--export function extractZoomAttributes(region: ZoomRegion): CopiedZoom {- return {- kind: "zoom",- depth: region.depth,- customScale: region.customScale,- focus: { ...region.focus },- focusMode: region.focusMode,- rotationPreset: region.rotationPreset,- };-}--export function extractSpeedAttributes(region: SpeedRegion): CopiedSpeed {- return { kind: "speed", speed: region.speed };-}--/** Deep-clones blur data, including its nested freehand points array. */-function cloneBlurData(blurData?: BlurData): BlurData | undefined {- if (!blurData) return undefined;- return {- ...blurData,- freehandPoints: blurData.freehandPoints ? [...blurData.freehandPoints] : undefined,- };-}--export function extractAnnotationAttributes(region: AnnotationRegion): CopiedAnnotation {- return {- kind: "annotation",- style: { ...region.style },- size: { ...region.size },- figureData: region.figureData ? { ...region.figureData } : undefined,- blurData: cloneBlurData(region.blurData),- type: region.type,- content: region.content,- textContent: region.textContent,- imageContent: region.imageContent,- position: { ...region.position },- };-}--/** Returns a region carrying the copied attributes. Identity, timing, and source come from- * `base` (so a full region keeps its own); every attribute comes from the copy, with nested- * objects deep-copied. Passing a stub `base` builds a brand-new region; passing an existing- * region overwrites ALL its attributes (e.g. a preset-only copy clears the target's customScale). */-export function buildZoomRegion(- base: Pick<ZoomRegion, "id" | "startMs" | "endMs" | "source">,- attrs: CopiedZoom,-): ZoomRegion {- const { kind: _kind, ...zoomAttrs } = attrs;- return { ...base, ...zoomAttrs, focus: { ...zoomAttrs.focus } };-}--export function buildSpeedRegion(- base: Pick<SpeedRegion, "id" | "startMs" | "endMs">,- attrs: CopiedSpeed,-): SpeedRegion {- return { ...base, speed: attrs.speed };-}--/** Pastes onto an EXISTING annotation: only the styling is overwritten — the target keeps- * its own type, text/image content, position, timing, and stacking order. */-export function replaceAnnotationAttributes(- region: AnnotationRegion,- attrs: CopiedAnnotation,-): AnnotationRegion {- return {- ...region,- style: { ...attrs.style },- size: { ...attrs.size },- // Only carry figure data onto a figure target; never attach it to a non-figure- // (e.g. pasting a figure's attributes onto a text annotation keeps the text figure-less).- figureData:- region.type === "figure" && attrs.figureData ? { ...attrs.figureData } : region.figureData,- // Likewise, only carry blur settings onto a blur target.- blurData:- region.type === "blur" && attrs.blurData ? cloneBlurData(attrs.blurData) : region.blurData,- };-}--/** Builds a BRAND-NEW annotation from a full copy: clones type, content, styling, size,- * figure data, and position. Identity, timing, and stacking order come from `base`. */-export function buildPastedAnnotation(- base: Pick<AnnotationRegion, "id" | "startMs" | "endMs" | "zIndex">,- attrs: CopiedAnnotation,-): AnnotationRegion {- return {- ...base,- type: attrs.type,- content: attrs.content,- textContent: attrs.textContent,- imageContent: attrs.imageContent,- position: { ...attrs.position },- size: { ...attrs.size },- style: { ...attrs.style },- figureData: attrs.figureData ? { ...attrs.figureData } : undefined,- blurData: cloneBlurData(attrs.blurData),- };-}diff --git a/src/components/video-editor/regionPlacement.test.ts b/src/components/video-editor/regionPlacement.test.tsdeleted file mode 100644index ecddf2ff6..000000000--- a/src/components/video-editor/regionPlacement.test.ts+++ /dev/null@@ -1,54 +0,0 @@-import { describe, expect, it } from "vitest";-import { findFreeGapAt } from "./regionPlacement";--const totalMs = 10000;--describe("findFreeGapAt", () => {- it("returns the gap to the end when there are no regions", () => {- const { ok, gapMs } = findFreeGapAt([], 2000, totalMs);- expect(ok).toBe(true);- expect(gapMs).toBe(8000);- });-- it("rejects a playhead that lands inside an existing region", () => {- const regions = [{ startMs: 1000, endMs: 4000 }];- const { ok } = findFreeGapAt(regions, 2000, totalMs);- expect(ok).toBe(false);- });-- it("clamps the gap to the next region's start", () => {- const regions = [{ startMs: 5000, endMs: 7000 }];- const { ok, gapMs } = findFreeGapAt(regions, 2000, totalMs);- expect(ok).toBe(true);- expect(gapMs).toBe(3000);- });-- it("rejects placement with no room before the end", () => {- const { ok, gapMs } = findFreeGapAt([], totalMs, totalMs);- expect(ok).toBe(false);- expect(gapMs).toBe(0);- });-- it("rejects placement that lands exactly on a region's startMs", () => {- const regions = [{ startMs: 5000, endMs: 7000 }];- const { ok } = findFreeGapAt(regions, 5000, totalMs);- expect(ok).toBe(false);- });-- it("allows placement adjacent to (exactly at the end of) an existing region", () => {- const regions = [{ startMs: 0, endMs: 2000 }];- const { ok, gapMs } = findFreeGapAt(regions, 2000, totalMs);- expect(ok).toBe(true);- expect(gapMs).toBe(8000);- });-- it("sorts unordered regions before computing the next gap", () => {- const regions = [- { startMs: 8000, endMs: 9000 },- { startMs: 3000, endMs: 4000 },- ];- const { ok, gapMs } = findFreeGapAt(regions, 1000, totalMs);- expect(ok).toBe(true);- expect(gapMs).toBe(2000);- });-});diff --git a/src/components/video-editor/regionPlacement.ts b/src/components/video-editor/regionPlacement.tsdeleted file mode 100644index 673d3fe7f..000000000--- a/src/components/video-editor/regionPlacement.ts+++ /dev/null@@ -1,24 +0,0 @@-/**- * Find the available gap at `startPos` in a list of regions.- *- * Looks at the span from `startPos` up to the start of the next region- * (or up to `totalMs` if there is no later region) and reports its size,- * along with whether placement at `startPos` is actually valid.- *- * Placement is valid as long as `startPos` does not fall inside an- * existing region and there is some room before the next one. Landing- * exactly on the end of an existing region is fine (adjacency is- * allowed); landing on a region's start or strictly between its start- * and end, or having zero space left before the next region, is not.- */-export function findFreeGapAt(- regions: ReadonlyArray<{ startMs: number; endMs: number }>,- startPos: number,- totalMs: number,-): { ok: boolean; gapMs: number } {- const sorted = [...regions].sort((a, b) => a.startMs - b.startMs);- const nextRegion = sorted.find((r) => r.startMs > startPos);- const gapMs = nextRegion ? nextRegion.startMs - startPos : totalMs - startPos;- const overlapping = sorted.some((r) => startPos >= r.startMs && startPos < r.endMs);- return { ok: !overlapping && gapMs > 0, gapMs };-}diff --git a/src/lib/ai-edition/annotations/background.test.ts b/src/lib/ai-edition/annotations/background.test.tsindex 4e8697608..cd0f07199 100644--- a/src/lib/ai-edition/annotations/background.test.ts+++ b/src/lib/ai-edition/annotations/background.test.ts@@ -1,4 +1,5 @@import { describe, expect, it } from "vitest";+import { DEFAULT_ANNOTATION_STYLE } from "@/components/video-editor/types";import type { AxcutAnnotationRegion } from "@/lib/ai-edition/schema";import {DEFAULT_TEXT_BACKGROUND,@@ -7,7 +8,6 @@ import {textBackgroundColor,toggleTextBackground,} from "./background";-import { DEFAULT_ANNOTATION_STYLE } from "./constants";type AnnotationStyle = AxcutAnnotationRegion["style"];diff --git a/src/lib/ai-edition/annotations/blurEffects.ts b/src/lib/ai-edition/annotations/blurEffects.tsdeleted file mode 100644index 7c0fe3ea8..000000000--- a/src/lib/ai-edition/annotations/blurEffects.ts+++ /dev/null@@ -1,53 +0,0 @@-// Port of `src/lib/blurEffects.ts` (the preview-facing helpers only —-// `applyMosaicToImageData` is export-pipeline-only and unused by the live-// preview, so it isn't ported here).--import type { AxcutAnnotationRegion } from "@/lib/ai-edition/schema";-import {- DEFAULT_BLUR_BLOCK_SIZE,- DEFAULT_BLUR_INTENSITY,- MAX_BLUR_BLOCK_SIZE,- MAX_BLUR_INTENSITY,- MIN_BLUR_BLOCK_SIZE,- MIN_BLUR_INTENSITY,-} from "./constants";--type BlurData = NonNullable<AxcutAnnotationRegion["blurData"]>;-type BlurColor = BlurData["color"];--function clamp(value: number, min: number, max: number) {- if (!Number.isFinite(value)) return min;- return Math.min(max, Math.max(min, value));-}--export function normalizeBlurColor(value: unknown): BlurColor {- return value === "black" ? "black" : "white";-}--export function getNormalizedBlurIntensity(blurData?: BlurData | null): number {- return clamp(- blurData?.intensity ?? DEFAULT_BLUR_INTENSITY,- MIN_BLUR_INTENSITY,- MAX_BLUR_INTENSITY,- );-}--export function getNormalizedMosaicBlockSize(blurData?: BlurData | null, scaleFactor = 1): number {- const rawBlockSize = clamp(- blurData?.blockSize ?? DEFAULT_BLUR_BLOCK_SIZE,- MIN_BLUR_BLOCK_SIZE,- MAX_BLUR_BLOCK_SIZE,- );- return Math.max(1, Math.round(rawBlockSize * Math.max(scaleFactor, 0.01)));-}--export function getBlurOverlayColor(blurData?: BlurData | null): string {- const blurColor = normalizeBlurColor(blurData?.color);- return blurColor === "black" ? "rgba(0, 0, 0, 0.72)" : "rgba(255, 255, 255, 0.06)";-}--export function getMosaicGridOverlayColor(blurData?: BlurData | null): string {- return normalizeBlurColor(blurData?.color) === "black"- ? "rgba(255,255,255,0.05)"- : "rgba(255,255,255,0.04)";-}diff --git a/src/lib/ai-edition/annotations/constants.ts b/src/lib/ai-edition/annotations/constants.tsdeleted file mode 100644index 3f4ae8081..000000000--- a/src/lib/ai-edition/annotations/constants.ts+++ /dev/null@@ -1,57 +0,0 @@-// Defaults ported verbatim from `src/components/video-editor/types.ts` so-// newly-created annotations look identical between the legacy and new editor.--import type { AxcutAnnotationRegion } from "@/lib/ai-edition/schema";--type AnnotationStyle = AxcutAnnotationRegion["style"];-type BlurData = NonNullable<AxcutAnnotationRegion["blurData"]>;-type FigureData = NonNullable<AxcutAnnotationRegion["figureData"]>;--export const DEFAULT_ANNOTATION_POSITION = { x: 50, y: 50 };-export const DEFAULT_ANNOTATION_SIZE = { width: 30, height: 20 };--export const DEFAULT_ANNOTATION_STYLE: AnnotationStyle = {- color: "#ffffff",- backgroundColor: "transparent",- fontSize: 32,- fontFamily: "Inter",- fontWeight: "bold",- fontStyle: "normal",- textDecoration: "none",- textAlign: "center",- textAnimation: "none",-};--export const DEFAULT_FIGURE_DATA: FigureData = {- arrowDirection: "right",- color: "#34B27B",- strokeWidth: 4,-};--export const MIN_BLUR_INTENSITY = 2;-export const MAX_BLUR_INTENSITY = 40;-export const DEFAULT_BLUR_INTENSITY = 12;-export const MIN_BLUR_BLOCK_SIZE = 4;-export const MAX_BLUR_BLOCK_SIZE = 48;-export const DEFAULT_BLUR_BLOCK_SIZE = 12;--export const DEFAULT_BLUR_FREEHAND_POINTS: Array<{ x: number; y: number }> = [- { x: 10, y: 30 },- { x: 25, y: 10 },- { x: 55, y: 8 },- { x: 82, y: 20 },- { x: 90, y: 45 },- { x: 78, y: 72 },- { x: 52, y: 90 },- { x: 22, y: 84 },- { x: 8, y: 58 },-];--export const DEFAULT_BLUR_DATA: BlurData = {- type: "mosaic",- shape: "rectangle",- color: "white",- intensity: DEFAULT_BLUR_INTENSITY,- blockSize: DEFAULT_BLUR_BLOCK_SIZE,- freehandPoints: DEFAULT_BLUR_FREEHAND_POINTS,-};diff --git a/src/lib/ai-edition/exporter/audioConcatAssembler.test.ts b/src/lib/ai-edition/exporter/audioConcatAssembler.test.tsdeleted file mode 100644index 1b41886a0..000000000--- a/src/lib/ai-edition/exporter/audioConcatAssembler.test.ts+++ /dev/null@@ -1,427 +0,0 @@-import { describe, expect, it } from "vitest";-import {- type AssembleOptions,- type AudioConcatAssemblerSegmentInput,- assembleConcatenatedPcm,-} from "./audioConcatAssembler";-import type { AudioConcatPlan, AudioConcatSegmentPlan } from "./audioConcatPlan";--// --- Factory helpers -----------------------------------------------------------// `plan` builds a minimal `AudioConcatPlan` literal — the assembler only reads-// the documented fields (sampleRate, channels, totalSamples, segments[*]),-// so we don't have to go through `buildAudioConcatPlan` here.-function plan(- segs: AudioConcatSegmentPlan[],- header: { sampleRate?: number; channels?: number; totalSamples?: number } = {},-): AudioConcatPlan {- return {- sampleRate: header.sampleRate ?? 48_000,- channels: header.channels ?? 1,- totalSamples: header.totalSamples ?? segs.reduce((acc, s) => acc + s.sampleCount, 0),- segments: segs,- };-}--function seg(- clipId: string,- startSample: number,- sampleCount: number,- silence: boolean,-): AudioConcatSegmentPlan {- return { clipId, startSample, sampleCount, silence };-}--function pcm(...channels: number[][]): Float32Array[] {- return channels.map((c) => Float32Array.from(c));-}--function f32(values: number[]): Float32Array {- return Float32Array.from(values);-}--// --- Copy semantics ------------------------------------------------------------describe("assembleConcatenatedPcm — single segment", () => {- it("single mono segment at exact length: pcm samples copied as-is, no fade, no padding", () => {- const segPlan = seg("c1", 0, 4, false);- const pl = plan([segPlan]);- const inputs: AudioConcatAssemblerSegmentInput[] = [{ pcm: pcm([1, 2, 3, 4]) }];- const out = assembleConcatenatedPcm(inputs, pl);- expect(out).toHaveLength(1);- expect(Array.from(out[0])).toEqual([1, 2, 3, 4]);- // totalSamples enforces the buffer length — the slot never overflows.- expect(out[0].length).toBe(pl.totalSamples);- });-});--describe("assembleConcatenatedPcm — concatenation", () => {- it("two mono segments: seg B's samples land at seg B's startSample; output length == totalSamples", () => {- // seg A: [10..14), seg B: [14..19) — butt-joined, no overlap.- const pl = plan([seg("a", 0, 4, false), seg("b", 4, 5, false)], { totalSamples: 9 });- const inputs: AudioConcatAssemblerSegmentInput[] = [- { pcm: pcm([10, 11, 12, 13]) },- { pcm: pcm([20, 21, 22, 23, 24]) },- ];- const out = assembleConcatenatedPcm(inputs, pl);- expect(out).toHaveLength(1);- expect(out[0].length).toBe(9);- expect(Array.from(out[0])).toEqual([10, 11, 12, 13, 20, 21, 22, 23, 24]);- });-- it("plan-vs-segments length mismatch: missing input(s) are treated as silence at the planned offset", () => {- // Skip the middle input → seg b's planned range renders zeros at its- // startSample; seg c's samples still land at offset 5 unchanged.- const pl = plan([seg("a", 0, 2, false), seg("b", 2, 3, false), seg("c", 5, 2, false)], {- totalSamples: 7,- });- const inputs: AudioConcatAssemblerSegmentInput[] = [- { pcm: pcm([1, 2]) },- { pcm: null }, // middle segment's input omitted → silent- { pcm: pcm([9, 10]) },- ];- const out = assembleConcatenatedPcm(inputs, pl);- expect(Array.from(out[0])).toEqual([1, 2, 0, 0, 0, 9, 10]);- });-});--describe("assembleConcatenatedPcm — silence / missing input", () => {- it("silence: true → the segment's range stays all zeros; neighbors unaffected", () => {- const pl = plan([seg("a", 0, 2, false), seg("b", 2, 3, true), seg("c", 5, 2, false)], {- totalSamples: 7,- });- const inputs: AudioConcatAssemblerSegmentInput[] = [- { pcm: pcm([1, 2]) },- { pcm: pcm([100, 101, 102]) }, // would be written, but silence flag wins- { pcm: pcm([9, 10]) },- ];- const out = assembleConcatenatedPcm(inputs, pl);- expect(Array.from(out[0])).toEqual([1, 2, 0, 0, 0, 9, 10]);- });-- it("pcm: null (without silence flag) → treated as silent", () => {- const pl = plan([seg("a", 0, 2, false), seg("b", 2, 3, false)], { totalSamples: 5 });- const inputs: AudioConcatAssemblerSegmentInput[] = [{ pcm: pcm([1, 2]) }, { pcm: null }];- const out = assembleConcatenatedPcm(inputs, pl);- expect(Array.from(out[0])).toEqual([1, 2, 0, 0, 0]);- });-});--describe("assembleConcatenatedPcm — length clamping", () => {- it("short input is zero-padded at the tail; the NEXT segment still starts at its offset", () => {- // seg A length 5 but pcm length 2 → pad to 5; seg B starts at offset 5 unchanged.- const pl = plan([seg("a", 0, 5, false), seg("b", 5, 3, false)], { totalSamples: 8 });- const inputs: AudioConcatAssemblerSegmentInput[] = [- { pcm: pcm([100, 200]) },- { pcm: pcm([9, 10, 11]) },- ];- const out = assembleConcatenatedPcm(inputs, pl);- expect(Array.from(out[0])).toEqual([100, 200, 0, 0, 0, 9, 10, 11]);- });-- it("long input is truncated; extra samples do NOT leak into the next segment's range", () => {- // seg A length 3 but pcm length 6 → only the first 3 land; seg B's offset is preserved.- const pl = plan([seg("a", 0, 3, false), seg("b", 3, 3, false)], { totalSamples: 6 });- const inputs: AudioConcatAssemblerSegmentInput[] = [- { pcm: pcm([1, 2, 3, 4, 5, 6]) }, // 4,5,6 must NOT appear in output- { pcm: pcm([9, 10, 11]) },- ];- const out = assembleConcatenatedPcm(inputs, pl);- expect(Array.from(out[0])).toEqual([1, 2, 3, 9, 10, 11]);- });-});--describe("assembleConcatenatedPcm — multi-channel", () => {- it("stereo: two-channel input is written into two output arrays independently per channel", () => {- const pl = plan([seg("a", 0, 3, false), seg("b", 3, 3, false)], {- channels: 2,- totalSamples: 6,- });- const inputs: AudioConcatAssemblerSegmentInput[] = [- { pcm: pcm([10, 11, 12], [20, 21, 22]) }, // ch0: 10..12, ch1: 20..22- { pcm: pcm([100, 101, 102], [200, 201, 202]) },- ];- const out = assembleConcatenatedPcm(inputs, pl);- expect(out).toHaveLength(2);- expect(Array.from(out[0])).toEqual([10, 11, 12, 100, 101, 102]);- expect(Array.from(out[1])).toEqual([20, 21, 22, 200, 201, 202]);- });-- it("missing channel: input.pcm has 1 channel but plan.channels is 2 → that channel is silence for the segment", () => {- // seg A: stereo plan, only ch0 supplied → ch1 stays zero for seg A's range;- // seg B: full stereo, written normally at offset 3.- const pl = plan([seg("a", 0, 3, false), seg("b", 3, 3, false)], {- channels: 2,- totalSamples: 6,- });- const inputs: AudioConcatAssemblerSegmentInput[] = [- { pcm: pcm([10, 11, 12]) }, // no channel 1- { pcm: pcm([100, 101, 102], [200, 201, 202]) },- ];- const out = assembleConcatenatedPcm(inputs, pl);- expect(Array.from(out[0])).toEqual([10, 11, 12, 100, 101, 102]);- expect(Array.from(out[1])).toEqual([0, 0, 0, 200, 201, 202]);- });-});--// --- Boundary fades (equal-power) ---------------------------------------------describe("assembleConcatenatedPcm — equal-power boundary fade", () => {- it("f=2: tail of seg 0 is multiplied by cos((k/f)·π/2); head of seg 1 by sin((k/f)·π/2); cos²+sin² ≈ 1 for the paired offset", () => {- // Two segments, each length 4. Fade f=2 → seg 0 indices [2,3) faded out,- // seg 1 indices [0,1) faded in. Use a non-1 value (5) so the gain is visible.- const pl = plan([seg("a", 0, 4, false), seg("b", 4, 4, false)], { totalSamples: 8 });- // Source values: seg a = [5,5,5,5], seg b = [7,7,7,7]. With no fade, output- // would be [5,5,5,5,7,7,7,7]. After fade:- // a[2] *= cos(0·π/2) = 1 → 5- // a[3] *= cos(0.5·π/2) = √2/2 → 5·√2/2- // b[0] *= sin(0·π/2) = 0 → 0- // b[1] *= sin(0.5·π/2) = √2/2 → 7·√2/2- const inputs: AudioConcatAssemblerSegmentInput[] = [- { pcm: pcm([5, 5, 5, 5]) },- { pcm: pcm([7, 7, 7, 7]) },- ];- const out = assembleConcatenatedPcm(inputs, pl, { boundaryFadeSamples: 2 });-- // Float32 storage round-trips `input * gain` to ~7 significant digits- // (mantissa = 23 bits → ~6-7 decimal). Tolerance 5e-7 (precision=6)- // covers the worst-case Float32 quantization around |value|≈10.- const sqrt2over2 = Math.sqrt(2) / 2;- expect(out[0][0]).toBeCloseTo(5, 6); // far-from-boundary: untouched- expect(out[0][1]).toBeCloseTo(5, 6);- expect(out[0][2]).toBeCloseTo(5 * 1, 6); // k=0 → cos(0)=1- expect(out[0][3]).toBeCloseTo(5 * sqrt2over2, 6); // k=1 → cos(π/4)=√2/2- expect(out[0][4]).toBeCloseTo(7 * 0, 6); // seg b[0] → k=0 → sin(0)=0- expect(out[0][5]).toBeCloseTo(7 * sqrt2over2, 6); // k=1 → sin(π/4)=√2/2- expect(out[0][6]).toBeCloseTo(7, 6); // outside fade region- expect(out[0][7]).toBeCloseTo(7, 6);-- // Equal-power check on the paired offset sums: cos² + sin² = 1- // (kernel of the spec — perceived loudness stays flat through the join).- // This is pure Float64 (no Float32 storage), so tighten to 12.- for (let k = 0; k < 2; k++) {- const cos = Math.cos((k / 2) * (Math.PI / 2));- const sin = Math.sin((k / 2) * (Math.PI / 2));- expect(cos * cos + sin * sin).toBeCloseTo(1, 12);- }- });-- it("no fade at the OUTER edges — first sample of seg 0 and last sample of the last segment are untouched", () => {- // Three segments, fade=1 between each. The very first and very last sample- // sit one sample OUTSIDE any fade window → unchanged.- const pl = plan([seg("a", 0, 3, false), seg("b", 3, 3, false), seg("c", 6, 3, false)], {- totalSamples: 9,- });- const inputs: AudioConcatAssemblerSegmentInput[] = [- { pcm: pcm([1, 2, 3]) },- { pcm: pcm([9, 9, 9]) },- { pcm: pcm([4, 5, 6]) },- ];- const out = assembleConcatenatedPcm(inputs, pl, { boundaryFadeSamples: 1 });- // cos(0)=1, sin(0)=0 — fade-OUT leaves a[2] unchanged, fade-IN zeros b[3].- expect(out[0][0]).toBeCloseTo(1, 6); // far outer edge- expect(out[0][2]).toBeCloseTo(3, 6); // inside fade-OUT, but k=0 → gain 1- expect(out[0][3]).toBeCloseTo(0, 6); // head of seg b, k=0 → gain 0- expect(out[0][5]).toBeCloseTo(9, 6); // tail of seg b, k=0 → gain 1- expect(out[0][6]).toBeCloseTo(0, 6); // head of seg c, k=0 → gain 0- expect(out[0][8]).toBeCloseTo(6, 6); // far outer edge — UNCHANGED- });-- it("fade is applied to ALL channels of a multi-channel output", () => {- const pl = plan([seg("a", 0, 4, false), seg("b", 4, 4, false)], {- channels: 2,- totalSamples: 8,- });- const inputs: AudioConcatAssemblerSegmentInput[] = [- { pcm: pcm([5, 5, 5, 5], [50, 50, 50, 50]) },- { pcm: pcm([7, 7, 7, 7], [70, 70, 70, 70]) },- ];- const out = assembleConcatenatedPcm(inputs, pl, { boundaryFadeSamples: 2 });- const sqrt2over2 = Math.sqrt(2) / 2;- // Both channels follow the same equal-power law independently.- // Float32-bound tolerance (see note above).- expect(out[0][3]).toBeCloseTo(5 * sqrt2over2, 6);- expect(out[0][5]).toBeCloseTo(7 * sqrt2over2, 6);- expect(out[1][3]).toBeCloseTo(50 * sqrt2over2, 6);- expect(out[1][5]).toBeCloseTo(70 * sqrt2over2, 6);- // Untouched outer samples on both channels.- expect(out[1][0]).toBeCloseTo(50, 6);- expect(out[1][7]).toBeCloseTo(70, 6);- });-- it("fade is clamped to floor(sampleCount/2) of each adjacent segment — boundaryFadeSamples larger than the slot", () => {- // seg A length 3 → floor(3/2)=1, seg B length 3 → 1: requested f0=100 → effective f=1.- const pl = plan([seg("a", 0, 3, false), seg("b", 3, 3, false)], { totalSamples: 6 });- const inputs: AudioConcatAssemblerSegmentInput[] = [- { pcm: pcm([8, 8, 8]) },- { pcm: pcm([9, 9, 9]) },- ];- const out = assembleConcatenatedPcm(inputs, pl, { boundaryFadeSamples: 100 });- // Only index 2 of seg a (tail-of-fade, k=0, cos=1) and index 3 of seg b- // (head-of-fade, k=0, sin=0) are affected — index 1 of seg a and index 4- // of seg b are well outside the f=1 fade region and must be unchanged.- expect(out[0][0]).toBeCloseTo(8, 6);- expect(out[0][1]).toBeCloseTo(8, 6); // NOT in the fade region- expect(out[0][2]).toBeCloseTo(8, 6); // k=0 → cos(0)=1- expect(out[0][3]).toBeCloseTo(0, 6); // k=0 → sin(0)=0- expect(out[0][4]).toBeCloseTo(9, 6); // NOT in the fade region- expect(out[0][5]).toBeCloseTo(9, 6);- });-- it("fade is independently clamped per boundary when adjacent segments have different lengths", () => {- // seg A length 10 → floor(10/2)=5 (the binding side; seg B is length 100 → bound by A).- const pl = plan([seg("a", 0, 10, false), seg("b", 10, 100, false)], { totalSamples: 110 });- // Use 1.0 so any gain shows up verbatim.- const inputs: AudioConcatAssemblerSegmentInput[] = [- { pcm: pcm(new Array(10).fill(1)) },- { pcm: pcm(new Array(100).fill(1)) },- ];- const out = assembleConcatenatedPcm(inputs, pl, { boundaryFadeSamples: 1000 });- // Effective f = min(1000, floor(10/2)=5, floor(100/2)=50) = 5.- // seg a tail: indices [5,10) — cos gain applied. k=0 → 1, k=4 → cos(0.8π/2)≈0.309.- // Float32-bound tolerance.- expect(out[0][5]).toBeCloseTo(Math.cos((0 / 5) * (Math.PI / 2)), 6);- expect(out[0][9]).toBeCloseTo(Math.cos((4 / 5) * (Math.PI / 2)), 6);- // seg a head: indices [0,5) — unchanged.- expect(out[0][0]).toBeCloseTo(1, 6);- expect(out[0][4]).toBeCloseTo(1, 6);- // seg b head: indices [10,15) — sin gain applied. k=0 → 0, k=4 → sin(0.8π/2)≈0.951.- expect(out[0][10]).toBeCloseTo(Math.sin((0 / 5) * (Math.PI / 2)), 6);- expect(out[0][14]).toBeCloseTo(Math.sin((4 / 5) * (Math.PI / 2)), 6);- // seg b body: indices [15,110) — unchanged.- expect(out[0][15]).toBeCloseTo(1, 6);- expect(out[0][109]).toBeCloseTo(1, 6);- });-- it("a short adjacent segment (sampleCount < 2*f0) still gets its own contribution — only its own half is faded", () => {- // seg A length 10, seg B length 2. f = min(f0=5, 5, 1) = 1. Only index 1 of- // seg A (cos) and index 0 of seg B (sin) are touched — seg B index 1 is- // outside the fade and stays at the input value.- const pl = plan([seg("a", 0, 10, false), seg("b", 10, 2, false)], { totalSamples: 12 });- const inputs: AudioConcatAssemblerSegmentInput[] = [- { pcm: pcm(new Array(10).fill(2)) },- { pcm: pcm([3, 3]) },- ];- const out = assembleConcatenatedPcm(inputs, pl, { boundaryFadeSamples: 5 });- // seg a body- expect(out[0][0]).toBeCloseTo(2, 6);- expect(out[0][8]).toBeCloseTo(2, 6);- // seg a tail — k=0 → cos(0)=1- expect(out[0][9]).toBeCloseTo(2, 6);- // seg b head — k=0 → sin(0)=0- expect(out[0][10]).toBeCloseTo(0, 6);- // seg b body (outside fade)- expect(out[0][11]).toBeCloseTo(3, 6);- });-});--describe("assembleConcatenatedPcm — boundaryFadeSamples edge values", () => {- it.each<[string, AssembleOptions | undefined]>([- ["undefined", undefined],- ["0", { boundaryFadeSamples: 0 }],- ["negative", { boundaryFadeSamples: -10 }],- ["NaN", { boundaryFadeSamples: Number.NaN }],- ["Infinity", { boundaryFadeSamples: Number.POSITIVE_INFINITY }],- ])("boundaryFadeSamples %s → no fades (plain concat)", (_label, opts) => {- const pl = plan([seg("a", 0, 4, false), seg("b", 4, 4, false)], { totalSamples: 8 });- const inputs: AudioConcatAssemblerSegmentInput[] = [- { pcm: pcm([5, 5, 5, 5]) },- { pcm: pcm([7, 7, 7, 7]) },- ];- const out = assembleConcatenatedPcm(inputs, pl, opts);- expect(Array.from(out[0])).toEqual([5, 5, 5, 5, 7, 7, 7, 7]);- });-});--// --- Degenerate / purity -------------------------------------------------------describe("assembleConcatenatedPcm — degenerate layouts", () => {- it("plan.channels = 0 → returns []", () => {- const pl = plan([seg("a", 0, 4, false)], { channels: 0, totalSamples: 4 });- const out = assembleConcatenatedPcm([{ pcm: pcm([1, 2, 3, 4]) }], pl);- expect(out).toEqual([]);- });-- it("plan.totalSamples = 0 with channels=2 → returns 2 empty Float32Arrays", () => {- const pl = plan([], { channels: 2, totalSamples: 0 });- const out = assembleConcatenatedPcm([], pl);- expect(out).toHaveLength(2);- expect(out[0]).toBeInstanceOf(Float32Array);- expect(out[0].length).toBe(0);- expect(out[1]).toBeInstanceOf(Float32Array);- expect(out[1].length).toBe(0);- });-- it("plan.totalSamples = 0 with channels=0 → returns [] (both guards match)", () => {- const pl = plan([], { channels: 0, totalSamples: 0 });- const out = assembleConcatenatedPcm([], pl);- expect(out).toEqual([]);- });-- it("plan.totalSamples = 0 with channels=3, no segments → 3 empty Float32Arrays", () => {- const pl = plan([], { channels: 3, totalSamples: 0 });- const out = assembleConcatenatedPcm([], pl);- expect(out).toHaveLength(3);- expect(out.every((a) => a.length === 0)).toBe(true);- });-- it("plan with segments but totalSamples = 0 → 2 empty Float32Arrays", () => {- // Defends against the all-zero case: even though startSample/sampleCount- // are integers, the output buffer is empty and no fades run.- const pl = plan([seg("a", 0, 0, false), seg("b", 0, 0, false)], {- channels: 2,- totalSamples: 0,- });- const out = assembleConcatenatedPcm([{ pcm: pcm([1, 2]) }, { pcm: pcm([3, 4], [5, 6]) }], pl, {- boundaryFadeSamples: 4,- });- expect(out).toHaveLength(2);- expect(out[0].length).toBe(0);- expect(out[1].length).toBe(0);- });-});--describe("assembleConcatenatedPcm — purity (does not mutate inputs)", () => {- it("input Float32Arrays are not modified by copy or by boundary fades", () => {- const pl = plan([seg("a", 0, 4, false), seg("b", 4, 4, false)], { totalSamples: 8 });- const srcA = f32([1, 2, 3, 4]);- const srcB = f32([5, 6, 7, 8]);- const aSnapshot = Array.from(srcA);- const bSnapshot = Array.from(srcB);-- const inputs: AudioConcatAssemblerSegmentInput[] = [{ pcm: [srcA] }, { pcm: [srcB] }];- const out = assembleConcatenatedPcm(inputs, pl, { boundaryFadeSamples: 2 });-- // Inputs are untouched after the call (compare snapshot to live values).- expect(Array.from(srcA)).toEqual(aSnapshot);- expect(Array.from(srcB)).toEqual(bSnapshot);- // The output reflects the fades (so we know we actually exercised the- // fade path — otherwise the purity check would be vacuous).- expect(out[0][3]).not.toBe(bSnapshot[3] ?? 0);- });-- it("the segments wrapper array is not mutated in length or order", () => {- const pl = plan([seg("a", 0, 2, false)], { totalSamples: 2 });- const inputs: AudioConcatAssemblerSegmentInput[] = [{ pcm: pcm([9, 9]) }];- const beforeLen = inputs.length;- assembleConcatenatedPcm(inputs, pl);- expect(inputs).toHaveLength(beforeLen);- expect(inputs[0].pcm).not.toBeNull();- });-- it("a shared input pcm (referenced from two segments) is read-only — both outputs see the same logical source", () => {- // Two segments in the plan, each pointing at the same source buffer.- // The assembler must not overwrite either output through the shared- // input reference. (The fade writes ONLY into the output buffers.)- const shared = f32([4, 4, 4, 4]);- const pl = plan([seg("a", 0, 4, false), seg("b", 4, 4, false)], { totalSamples: 8 });- const inputs: AudioConcatAssemblerSegmentInput[] = [{ pcm: [shared] }, { pcm: [shared] }];- const out = assembleConcatenatedPcm(inputs, pl, { boundaryFadeSamples: 2 });- // Shared source is still pristine.- expect(Array.from(shared)).toEqual([4, 4, 4, 4]);- // Fade-OUT still applied to the first segment's tail; equals 4·cos(π/4)=4·√2/2.- // Float32-bound tolerance.- const sqrt2over2 = Math.sqrt(2) / 2;- expect(out[0][3]).toBeCloseTo(4 * sqrt2over2, 6);- });-});diff --git a/src/lib/ai-edition/exporter/audioConcatAssembler.ts b/src/lib/ai-edition/exporter/audioConcatAssembler.tsdeleted file mode 100644index 32ec82981..000000000--- a/src/lib/ai-edition/exporter/audioConcatAssembler.ts+++ /dev/null@@ -1,129 +0,0 @@-// AudioConcatAssembler: pure-logic PCM assembly for the v2 multi-asset export-// audio track.-//-// ponytail: `audioConcatPlan.ts` decides WHERE each segment's audio lands in-// the concatenated output (integer sample offsets / counts / silence flags at-// a common sampleRate + channels). This module does the actual sample copy:-// for every plan segment, it takes the segment's already-decoded,-// already-resampled PLANAR PCM (one Float32Array per channel) and writes it-// into the right offset of a single output buffer, clamping each channel to-// the planned sampleCount (longer input → truncate; shorter input → zero-pad)-// so a small decode over/under-run never shifts the timeline. A short-// equal-power fade is applied at every INTERNAL segment boundary to suppress-// clicks where two different recordings meet butt-joined — without changing-// timing, so audio stays locked to the video (which is retimed independently).-//-// The plan places segments BUTT-JOINED (segment i+1 starts exactly where i-// ends, no overlap) because `plan.totalSamples` must equal the video frame-// count for A/V lock, so a true overlapping crossfade is not an option (it-// would shorten the track and drift A/V). Instead we use equal-power gains:-// fade-out gain at offset k∈[0,f) = cos((k/f)·π/2) and fade-in at the matching-// offset = sin((k/f)·π/2). `cos² + sin² = 1` keeps perceived power even.-//-// Pure: no DOM, no IPC, no WebCodecs, no AudioContext — only Float32Array-// math. Inputs are never mutated.--import type { AudioConcatPlan } from "./audioConcatPlan";--// One entry per plan segment (SAME order/length as `plan.segments`). `pcm` is-// the segment's decoded audio, PLANAR (one Float32Array per channel), already-// at `plan.sampleRate` / `plan.channels`. `null` → silent segment (renders-// zeros — equivalent to `seg.silence === true`). The assembler clamps each-// channel to the plan's `sampleCount`: a longer buffer is truncated, a-// shorter one is zero-padded, so a small decode over/under-run never shifts-// the timeline.-export interface AudioConcatAssemblerSegmentInput {- pcm: Float32Array[] | null;-}--export interface AssembleOptions {- // Equal-power fade length (in samples) applied at each INTERNAL segment- // boundary to avoid clicks. Clamped per-boundary to at most- // `floor(sampleCount/2)` of each adjacent segment. Default 0 (no fade).- // Non-finite / negative values are treated as 0.- boundaryFadeSamples?: number;-}--// Returns `plan.channels` planar Float32Arrays, each of length `plan.totalSamples`.-// Pure: never mutates `segments` or their `pcm` arrays.-export function assembleConcatenatedPcm(- segments: AudioConcatAssemblerSegmentInput[],- plan: AudioConcatPlan,- options?: AssembleOptions,-): Float32Array[] {- // Degenerate layouts — no channels to fill.- if (plan.channels <= 0) return [];- if (plan.totalSamples === 0) {- const empty: Float32Array[] = [];- for (let i = 0; i < plan.channels; i++) empty.push(new Float32Array(0));- return empty;- }-- // 1) Allocate `plan.channels` output Float32Arrays (zero-filled = silence).- const output: Float32Array[] = [];- for (let c = 0; c < plan.channels; c++) {- output.push(new Float32Array(plan.totalSamples));- }-- // 2) Copy each segment's PCM into its planned slot. A silent segment- // (per plan) or a missing/short input leaves zeros in the slot — the- // timeline (startSample + sampleCount) is preserved either way.- const segCount = plan.segments.length;- for (let i = 0; i < segCount; i++) {- const seg = plan.segments[i];- const start = seg.startSample;- const count = seg.sampleCount;- if (count <= 0) continue;- const input = segments[i];- if (seg.silence) continue;- if (!input || input.pcm == null) continue;-- const src = input.pcm;- for (let c = 0; c < plan.channels; c++) {- const dst = output[c];- const srcCh = src[c];- if (!srcCh) continue; // missing channel → silence for this segment- const copy = count < srcCh.length ? count : srcCh.length;- // Bounds already enforced (start..start+count ⊂ [0, totalSamples),- // srcCh.length ≥ copy) — no overrun possible, no clamp needed.- for (let k = 0; k < copy; k++) {- dst[start + k] = srcCh[k];- }- // Any tail beyond `copy` (count > srcCh.length) is left at zero- // (the Float32Array was zero-filled at allocation).- }- }-- // 3) Boundary fades (after all copies). At each INTERNAL boundary the tail- // of segment i is multiplied by a fade-out gain (`cos`) and the head of- // segment i+1 by a fade-in gain (`sin`) with matching offsets so the sum of- // squares is 1 — equal-power, no perceived dip. Applied to every channel- // (multiplication by 0 on a silent side is a harmless no-op).- const f0 = options?.boundaryFadeSamples ?? 0;- if (Number.isFinite(f0) && f0 > 0 && segCount >= 2) {- for (let i = 0; i < segCount - 1; i++) {- const cur = plan.segments[i];- const next = plan.segments[i + 1];- const f = Math.min(f0, Math.floor(cur.sampleCount / 2), Math.floor(next.sampleCount / 2));- if (f <= 0) continue;- const halfPi = Math.PI / 2;- for (let c = 0; c < plan.channels; c++) {- const dst = output[c];- // Fade-OUT tail of cur: k=0 → gain 1, k=f-1 → ~0.- const tailStart = cur.startSample + cur.sampleCount - f;- for (let k = 0; k < f; k++) {- const gain = Math.cos((k / f) * halfPi);- dst[tailStart + k] *= gain;- }- // Fade-IN head of next: k=0 → gain 0, k=f-1 → ~1.- const headStart = next.startSample;- for (let k = 0; k < f; k++) {- const gain = Math.sin((k / f) * halfPi);- dst[headStart + k] *= gain;- }- }- }- }-- return output;-}diff --git a/src/lib/ai-edition/exporter/audioConcatPlan.test.ts b/src/lib/ai-edition/exporter/audioConcatPlan.test.tsdeleted file mode 100644index 0ef6e3649..000000000--- a/src/lib/ai-edition/exporter/audioConcatPlan.test.ts+++ /dev/null@@ -1,172 +0,0 @@-import { describe, expect, it } from "vitest";-import { type AudioConcatSegmentInput, buildAudioConcatPlan } from "./audioConcatPlan";--// --- Factory helpers (lean: only fields the builder reads) ----------------------function seg(clipId: string, outputFrameCount: number, hasAudio: boolean): AudioConcatSegmentInput {- return { clipId, outputFrameCount, hasAudio };-}--// --- Defaults + layout ---------------------------------------------------------describe("buildAudioConcatPlan — layout", () => {- it("single segment with audio: sampleCount = round(300/30*48000)=480000, silence false, totalSamples 480000", () => {- const plan = buildAudioConcatPlan([seg("c1", 300, true)], { frameRate: 30 });- expect(plan.sampleRate).toBe(48_000);- expect(plan.channels).toBe(2);- expect(plan.totalSamples).toBe(480_000);- expect(plan.segments).toEqual([- { clipId: "c1", startSample: 0, sampleCount: 480_000, silence: false },- ]);- });-- it("defaults sampleRate=48000 and channels=2 when options omit them", () => {- const plan = buildAudioConcatPlan([seg("c1", 0, true)], { frameRate: 30 });- expect(plan.sampleRate).toBe(48_000);- expect(plan.channels).toBe(2);- });-- it("honors custom sampleRate=44100 and channels=1 in both the plan header and sample math", () => {- // round(480/24 * 44100) = round(882000) = 882000 (exact integer — the- // sample-math assertion still confirms the custom rate is plugged in).- const plan = buildAudioConcatPlan([seg("c1", 480, true)], {- frameRate: 24,- sampleRate: 44_100,- channels: 1,- });- expect(plan.sampleRate).toBe(44_100);- expect(plan.channels).toBe(1);- expect(plan.segments[0].sampleCount).toBe(882_000);- expect(plan.totalSamples).toBe(882_000);- });-});--// --- Offsets + integer accumulation (R5) ---------------------------------------describe("buildAudioConcatPlan — offsets", () => {- it("three audio segments: startSample[i] = sum(prior sampleCounts); totalSamples = sum(all)", () => {- // frameRate 60, sampleRate 48000 → sampleCount = outputFrameCount * 800.- const plans = buildAudioConcatPlan(- [seg("a", 60, true), seg("b", 30, true), seg("c", 90, true)],- { frameRate: 60 },- );- expect(plans.segments.map((s) => s.startSample)).toEqual([0, 48_000, 72_000]);- expect(plans.segments.map((s) => s.sampleCount)).toEqual([48_000, 24_000, 72_000]);- expect(plans.totalSamples).toBe(48_000 + 24_000 + 72_000);- // cumulative-shapes equivalence for exact-integer math.- expect(plans.totalSamples).toBe(0 + 48_000 + 24_000 + 72_000);- });-- it("silence padding: a hasAudio=false segment occupies its full sampleCount and shifts the next startSample", () => {- // frameRate 30, sampleRate 48000 → sampleCount = outputFrameCount * 1600.- const plans = buildAudioConcatPlan(- [seg("a", 30, true), seg("b", 15, false), seg("c", 30, true)],- { frameRate: 30 },- );- expect(plans.segments).toEqual([- { clipId: "a", startSample: 0, sampleCount: 48_000, silence: false },- { clipId: "b", startSample: 48_000, sampleCount: 24_000, silence: true },- { clipId: "c", startSample: 72_000, sampleCount: 48_000, silence: false },- ]);- expect(plans.totalSamples).toBe(48_000 + 24_000 + 48_000);- });-- it("mixed [audio, no-audio, audio]: offsets correct, only the middle flagged silence", () => {- const plans = buildAudioConcatPlan(- [seg("a", 30, true), seg("b", 15, false), seg("c", 30, true)],- { frameRate: 30 },- );- expect(plans.segments.map((s) => s.silence)).toEqual([false, true, false]);- // startSample[2] is exactly startSample[1] + sampleCount[1] (no rounding- // shortcut) — A/V stays locked through the silence gap.- expect(plans.segments[2].startSample).toBe(- plans.segments[1].startSample + plans.segments[1].sampleCount,- );- });-- it("integer accumulation / no drift (R5): startSample[i] === sum(prior sampleCounts), NOT round(cumulativeSeconds * sampleRate)", () => {- // frameRate 24, sampleRate 44100, frameCount 1 → round(1837.5) = 1838- // per segment. The fractional intermediate is the whole point — summing- // the rounded integers must NOT equal round(cumulativeSeconds * sr).- const plans = buildAudioConcatPlan(- [seg("s1", 1, true), seg("s2", 1, true), seg("s3", 1, true)],- { frameRate: 24, sampleRate: 44_100 },- );-- // Every output field is an integer (no half-sample leakage anywhere).- for (const s of plans.segments) {- expect(Number.isInteger(s.startSample)).toBe(true);- expect(Number.isInteger(s.sampleCount)).toBe(true);- }- expect(Number.isInteger(plans.totalSamples)).toBe(true);-- // Each segment = 1838 samples (= round(1/24 * 44100)).- expect(plans.segments.map((s) => s.sampleCount)).toEqual([1838, 1838, 1838]);-- // Integer accumulation: startSample[i] is the SUM of prior sampleCounts.- expect(plans.segments.map((s) => s.startSample)).toEqual([0, 1838, 3676]);- expect(plans.totalSamples).toBe(5514);-- // …which DIFFERS from `round(cumulativeSeconds * sampleRate)` (the- // drift-prone shortcut). Document the gap explicitly so a future refactor- // can't accidentally swap integer accumulation for cumulative rounding.- const sampleRate = plans.sampleRate;- const frameRate = 24;- const cumRoundedAt = (n: number) => Math.round(((n * 1) / frameRate) * sampleRate);- expect(cumRoundedAt(1)).toBe(1838); // matches — boundary case- expect(cumRoundedAt(2)).toBe(3675); // ≠ 3676 (drift by 1)- expect(cumRoundedAt(3)).toBe(5513); // ≠ 5514 (drift by 1)- });-});--// --- Degenerate inputs ----------------------------------------------------------describe("buildAudioConcatPlan — degenerate inputs", () => {- it("zero segments → empty segments, totalSamples 0, layout still set", () => {- const plan = buildAudioConcatPlan([], { frameRate: 30 });- expect(plan.segments).toEqual([]);- expect(plan.totalSamples).toBe(0);- expect(plan.sampleRate).toBe(48_000);- expect(plan.channels).toBe(2);- });-- it("zero-length segment: outputFrameCount 0 → sampleCount 0, next startSample unchanged", () => {- const plan = buildAudioConcatPlan([seg("a", 30, true), seg("b", 0, true), seg("c", 30, true)], {- frameRate: 30,- });- expect(plan.segments).toEqual([- { clipId: "a", startSample: 0, sampleCount: 48_000, silence: false },- { clipId: "b", startSample: 48_000, sampleCount: 0, silence: false },- { clipId: "c", startSample: 48_000, sampleCount: 48_000, silence: false },- ]);- expect(plan.totalSamples).toBe(96_000);- });-- it("frameRate = 0 guard: all sampleCounts 0, totalSamples 0, no NaN (no throw)", () => {- const plan = buildAudioConcatPlan(- [seg("a", 100, true), seg("b", 200, false), seg("c", 300, true)],- { frameRate: 0 },- );- expect(plan.segments).toEqual([- { clipId: "a", startSample: 0, sampleCount: 0, silence: false },- { clipId: "b", startSample: 0, sampleCount: 0, silence: true },- { clipId: "c", startSample: 0, sampleCount: 0, silence: false },- ]);- expect(plan.totalSamples).toBe(0);- // Explicit NaN sweep — divide-by-zero / Infinity must NOT leak through.- for (const s of plan.segments) {- expect(Number.isNaN(s.startSample)).toBe(false);- expect(Number.isNaN(s.sampleCount)).toBe(false);- }- expect(Number.isNaN(plan.totalSamples)).toBe(false);- });-- it("frameRate < 0 guard: negative frameRate treated the same as zero (degenerate, no NaN)", () => {- const plan = buildAudioConcatPlan([seg("a", 100, true)], { frameRate: -30 });- expect(plan.segments).toEqual([- { clipId: "a", startSample: 0, sampleCount: 0, silence: false },- ]);- expect(plan.totalSamples).toBe(0);- expect(Number.isNaN(plan.totalSamples)).toBe(false);- });-});diff --git a/src/lib/ai-edition/exporter/audioConcatPlan.ts b/src/lib/ai-edition/exporter/audioConcatPlan.tsdeleted file mode 100644index 319d48d18..000000000--- a/src/lib/ai-edition/exporter/audioConcatPlan.ts+++ /dev/null@@ -1,94 +0,0 @@-// AudioConcatPlan: pure-logic timing for the v2 multi-asset export audio track.-//-// ponytail: the v1 `documentExporter` runs a single continuous source stream-// (the primary asset), so audio "follows" video implicitly and the exporter-// just trims/speed-stretches one buffer end-to-end. The v2 renderer walks an-// ordered list of per-clip render segments (each drawing from its own source-// asset), so we have to concatenate N per-segment audio buffers into one-// output track — and the silence gaps for segments whose asset has no audio-// must be sized so A/V never drifts. This module computes the INTEGER sample-// accounting only; it does NOT decode, encode, resample, or touch WebCodecs-// / AudioContext. A downstream audio encoder/mixer reads the plan and emits-// the actual PCM.-//-// Integer accumulation matters (spec risk R5): each segment's audio length-// is rounded independently from its `outputFrameCount`, then offsets are the-// integer sum of prior rounded lengths. Never `round(cumulativeSeconds *-// sampleRate)` — that compounds per-segment rounding error across a long-// multi-segment timeline into audible A/V drift.--const DEFAULT_SAMPLE_RATE = 48_000;-const DEFAULT_CHANNELS = 2;--// One entry per RenderPlan segment (same order). The v2 segment loop supplies-// the output video frame count so audio can be locked 1:1 to the retimed-// video — same SSOT the video path uses (see audioEncoder's-// `round(frameCount / frameRate * sampleRate)` accounting).-export interface AudioConcatSegmentInput {- clipId: string;- // OUTPUT (virtual-timeline) video frames this segment renders. Audio is- // sized from this so A/V never drifts — same SSOT the video path uses.- outputFrameCount: number;- // Whether this segment's asset has a usable audio track. When false, the- // segment contributes SILENCE for its whole output duration (keeps A/V- // aligned).- hasAudio: boolean;-}--export interface AudioConcatSegmentPlan {- clipId: string;- startSample: number; // inclusive, output samples at `sampleRate`- sampleCount: number; // samples this segment occupies in the concatenated output- silence: boolean; // true → fill with silence (asset had no audio)-}--export interface AudioConcatPlan {- sampleRate: number;- channels: number;- totalSamples: number; // sum of all segment sampleCounts- segments: AudioConcatSegmentPlan[];-}--export interface BuildAudioConcatPlanOptions {- frameRate: number;- // Common output layout, chosen up-front by the caller (spec §6.3: from the- // first segment with audio, or the 48 kHz stereo default). Defaulted here.- sampleRate?: number; // default 48000- channels?: number; // default 2-}--export function buildAudioConcatPlan(- segments: AudioConcatSegmentInput[],- options: BuildAudioConcatPlanOptions,-): AudioConcatPlan {- const sampleRate = options.sampleRate ?? DEFAULT_SAMPLE_RATE;- const channels = options.channels ?? DEFAULT_CHANNELS;-- // Degenerate frameRate (0 or negative) → no segment can be sized without- // divide-by-zero / NaN. Return a plan with all-zero sample counts rather- // than throwing; the downstream encoder will still see a well-formed- // (if empty) buffer layout and the timeline is otherwise deterministic.- const frameRateValid = options.frameRate > 0;-- const plans: AudioConcatSegmentPlan[] = [];- let cursor = 0;- for (const seg of segments) {- const sampleCount = frameRateValid- ? Math.max(0, Math.round((seg.outputFrameCount / options.frameRate) * sampleRate))- : 0;- plans.push({- clipId: seg.clipId,- startSample: cursor,- sampleCount,- silence: !seg.hasAudio,- });- cursor += sampleCount;- }-- return {- sampleRate,- channels,- totalSamples: cursor,- segments: plans,- };-}diff --git a/src/lib/ai-edition/exporter/documentExporter.test.ts b/src/lib/ai-edition/exporter/documentExporter.test.tsindex 504a25e52..e973f4bd8 100644--- a/src/lib/ai-edition/exporter/documentExporter.test.ts+++ b/src/lib/ai-edition/exporter/documentExporter.test.ts@@ -2,11 +2,7 @@ import { describe, expect, it } from "vitest";import type { CursorRecordingData } from "@/native/contracts";import type { AxcutAsset, AxcutClip, AxcutDocument, AxcutTrimRange } from "../schema";import type { DocumentExportOptions } from "./documentExporter";-import {- buildDocumentRenderPlan,- computeCropSchedule,- computeExportTrimRegions,-} from "./documentExporter";+import { computeCropSchedule, computeExportTrimRegions } from "./documentExporter";function clip(p: Partial<AxcutClip> & Pick<AxcutClip, "id">): AxcutClip {return {@@ -109,146 +105,3 @@ describe("computeCropSchedule", () => {]);});});--describe("buildDocumentRenderPlan", () => {- function assetOf(p: Partial<AxcutAsset> & Pick<AxcutAsset, "id">): AxcutAsset {- return {- kind: "video",- label: "Asset",- originalPath: `/tmp/${p.id}.mp4`,- cameraTrack: null,- ...p,- };- }-- // Minimal document — buildDocumentRenderPlan/buildRenderPlan only read project,- // assets, timeline.{clips,trimRanges}, zoomRanges, annotations, legacyEditor.- function docOf(p: {- assets: AxcutAsset[];- clips: AxcutClip[];- primaryAssetId?: string;- legacyEditor?: Record<string, unknown> | null;- }): AxcutDocument {- return {- project: { primaryAssetId: p.primaryAssetId },- assets: p.assets,- timeline: { clips: p.clips, trimRanges: [] },- zoomRanges: [],- annotations: [],- legacyEditor: p.legacyEditor ?? null,- } as unknown as AxcutDocument;- }-- const baseOptions: DocumentExportOptions = { quality: "source", format: "mp4" };-- it("maps codec + frameRate and sizes output from the largest asset", () => {- const doc = docOf({- assets: [- assetOf({- id: "a",- durationSec: 30,- video: { codec: "h264", width: 1920, height: 1080, fps: 30 },- }),- ],- clips: [clip({ id: "c1", assetId: "a", sourceStartSec: 0, sourceEndSec: 10 })],- });- const plan = buildDocumentRenderPlan(doc, { ...baseOptions, codec: "h265", frameRate: 30 });- expect(plan.output.codec).toBe("hvc1.1.6.L120.90");- expect(plan.output.frameRate).toBe(30);- expect(plan.output.width).toBe(1920);- expect(plan.output.height).toBe(1080);- expect(plan.segments).toHaveLength(1);- });-- it("uses options.sourceWidth/Height as fallback dims when the asset has no video block", () => {- const doc = docOf({- assets: [assetOf({ id: "a", durationSec: 30 })], // no `video`- clips: [clip({ id: "c1", assetId: "a", sourceStartSec: 0, sourceEndSec: 10 })],- });- const plan = buildDocumentRenderPlan(doc, {- ...baseOptions,- sourceWidth: 1280,- sourceHeight: 720,- });- expect(plan.segments[0].sourceWidth).toBe(1280);- expect(plan.segments[0].sourceHeight).toBe(720);- });-- it("threads cursor recording + scale + theme into plan.cursor and partitions samples per segment", () => {- const recordingData: CursorRecordingData = {- version: 1,- provider: "native",- assets: [],- samples: [- { timeMs: 100, cx: 0.5, cy: 0.5, assetId: "a" },- { timeMs: 200, cx: 0.4, cy: 0.4, assetId: "b" },- ],- };- const doc = docOf({- assets: [- assetOf({- id: "a",- durationSec: 30,- video: { codec: "h264", width: 1920, height: 1080, fps: 30 },- }),- assetOf({- id: "b",- durationSec: 30,- video: { codec: "h264", width: 1920, height: 1080, fps: 30 },- }),- ],- clips: [- clip({- id: "c1",- assetId: "a",- sourceStartSec: 0,- sourceEndSec: 5,- timelineStartSec: 0,- timelineEndSec: 5,- }),- clip({- id: "c2",- assetId: "b",- sourceStartSec: 0,- sourceEndSec: 5,- timelineStartSec: 5,- timelineEndSec: 10,- }),- ],- legacyEditor: { cursorTheme: "dark" },- });- const plan = buildDocumentRenderPlan(doc, {- ...baseOptions,- cursorRecordingData: recordingData,- cursorScale: 1.2,- cursorSmoothing: 0.4,- });- expect(plan.cursor).toMatchObject({ scale: 1.2, smoothing: 0.4, theme: "dark" });- expect(plan.segments[0].cursorSamples.map((s) => s.timeMs)).toEqual([100]);- expect(plan.segments[1].cursorSamples.map((s) => s.timeMs)).toEqual([200]);- });-- it("leaves plan.cursor null when cursor scale is unset (0)", () => {- const recordingData: CursorRecordingData = {- version: 1,- provider: "native",- assets: [],- samples: [{ timeMs: 0, cx: 0.5, cy: 0.5, assetId: "a" }],- };- const doc = docOf({- assets: [- assetOf({- id: "a",- durationSec: 30,- video: { codec: "h264", width: 1920, height: 1080, fps: 30 },- }),- ],- clips: [clip({ id: "c1", assetId: "a", sourceStartSec: 0, sourceEndSec: 10 })],- });- const plan = buildDocumentRenderPlan(doc, {- ...baseOptions,- cursorRecordingData: recordingData,- });- expect(plan.cursor).toBeNull();- });-});diff --git a/src/lib/ai-edition/exporter/documentExporter.ts b/src/lib/ai-edition/exporter/documentExporter.tsindex 48f8b0c5a..351ac0ed4 100644--- a/src/lib/ai-edition/exporter/documentExporter.ts+++ b/src/lib/ai-edition/exporter/documentExporter.ts@@ -1,7 +1,7 @@-// Adapter: feeds an AxcutDocument into the existing VideoExporter / GifExporter-// by mapping document fields → VideoExporterConfig. No rewrite of the export-// pipeline — the existing FrameRenderer + StreamingVideoDecoder + muxer handle-// all the rendering (annotations, zoom, blur, webcam, cursor).+// Adapter: feeds an AxcutDocument into GifExporter. GIF is the only format+// rendered here — MP4 goes through the native D3D exporter, which ExportDialog+// calls directly. FrameRenderer + StreamingVideoDecoder do the rendering+// (annotations, zoom, blur, webcam, cursor).//// ponytail: the existing exporter accepts trimRegions (removed spans in source// time). Two contributors are merged into them (see computeExportTrimRegions):@@ -29,16 +29,9 @@ import {GifExporter,type GifFrameRate,type GifSizePreset,- VideoExporter,} from "@/lib/exporter";-import { calculateMp4ExportSettings } from "@/lib/exporter/mp4ExportSettings";import type { ExportProgress } from "@/lib/exporter/types";import type { CursorRecordingData, CursorTelemetryPoint } from "@/native/contracts";-import {- type AspectRatio,- getAspectRatioValue,- getNativeAspectRatioValue,-} from "@/utils/aspectRatioUtils";import {captionCuesToTextRegions,deriveCaptionCues,@@ -50,18 +43,9 @@ import { type Interval, normalizeIntervals, primaryAssetDuration } from "../docuimport type { AxcutAsset, AxcutDocument } from "../schema";import { resolveClipSourceEndSec } from "../timeline/clipDuration";import { projectRegionsToSourceTime } from "../timeline/region-ventilation";-import { buildRenderPlan, type RenderPlan } from "./renderPlan";export type ExportVideoCodec = "h264" | "h265" | "vp9";-// WebCodecs encoder strings per user-facing codec choice (F2.4). The muxer-// derives its mp4 track family from the same string.-const CODEC_STRINGS: Record<ExportVideoCodec, string> = {- h264: "avc1.640033",- h265: "hvc1.1.6.L120.90",- vp9: "vp09.00.10.08",-};-export interface DocumentExportOptions {quality: ExportQuality;format: ExportFormat;@@ -165,36 +149,6 @@ function extractLegacyField<T>(return fallback;}-// Maps the dialog's DocumentExportOptions onto the v2 RenderPlan (multi-asset,-// virtual-time effects, per-segment cursor). This is the single boundary where-// the document + export options become the plan the segment-loop renderer will-// consume. It runs today alongside the legacy config assembly below — the plan-// is threaded to VideoExporter but only drives rendering once the segment loop-// is enabled (see VideoExporterConfig.renderPlan). Cursor scale/theme come from-// options + legacyEditor exactly as the legacy path reads them.-export function buildDocumentRenderPlan(- document: AxcutDocument,- options: DocumentExportOptions,-): RenderPlan {- const legacy = document.legacyEditor as Record<string, unknown> | null;- return buildRenderPlan(document, {- quality: options.quality,- frameRate: options.frameRate ?? 60,- codec: options.codec ?? "h264",- fallbackSourceWidth: options.sourceWidth,- fallbackSourceHeight: options.sourceHeight,- cursor: {- recordingData: options.cursorRecordingData ?? null,- scale: options.cursorScale ?? 0,- smoothing: options.cursorSmoothing,- motionBlur: options.cursorMotionBlur,- clickBounce: options.cursorClickBounce,- clipToBounds: options.cursorClipToBounds,- theme: extractLegacyField(legacy, "cursorTheme", ""),- },- });-}-export async function exportAxcutDocument(document: AxcutDocument,options: DocumentExportOptions,@@ -268,24 +222,6 @@ export async function exportAxcutDocument(() => createId("camfull"),);- const sourceWidth = options.sourceWidth || 1920;- const sourceHeight = options.sourceHeight || 1080;- // Respect the timeline's selected aspect ratio (the whole-canvas framing set- // in the editor), not a hardcoded 16:9. "native" follows the source's own- // pixel aspect. This is a per-timeline choice, not per-clip.- const aspectRatio = extractLegacyField<AspectRatio>(legacy, "aspectRatio", "16:9");- const aspectRatioValue =- aspectRatio === "native"- ? getNativeAspectRatioValue(sourceWidth, sourceHeight)- : getAspectRatioValue(aspectRatio);-- const settings = calculateMp4ExportSettings({- quality: options.quality,- sourceWidth,- sourceHeight,- aspectRatioValue,- });-const cameraTrack = asset.cameraTrack;const commonConfig = {@@ -334,30 +270,16 @@ export async function exportAxcutDocument(onProgress: options.onProgress,};- if (options.format === "gif") {- const exporter = new GifExporter({- ...commonConfig,- width: 1280,- height: 720,- frameRate: options.gifFrameRate ?? 15,- loop: options.gifLoop ?? true,- sizePreset: options.gifSizePreset ?? "medium",- } as unknown as ConstructorParameters<typeof GifExporter>[0]);- return exporter.export();- }-- const exporter = new VideoExporter({+ // GIF is the only format this adapter renders. MP4 goes through the native+ // D3D exporter (`exportMultiNative`), which ExportDialog calls directly.+ const exporter = new GifExporter({...commonConfig,- width: settings.width,- height: settings.height,- frameRate: options.frameRate ?? 60,- bitrate: settings.bitrate,- codec: CODEC_STRINGS[options.codec ?? "h264"],- // v2 multi-asset plan, threaded to the exporter. Consumed only once the- // segment-loop path is enabled; the legacy single-asset config above still- // drives rendering until then.- renderPlan: buildDocumentRenderPlan(document, options),- });+ width: 1280,+ height: 720,+ frameRate: options.gifFrameRate ?? 15,+ loop: options.gifLoop ?? true,+ sizePreset: options.gifSizePreset ?? "medium",+ } as unknown as ConstructorParameters<typeof GifExporter>[0]);return exporter.export();}diff --git a/src/lib/ai-edition/exporter/renderPlan.test.ts b/src/lib/ai-edition/exporter/renderPlan.test.tsdeleted file mode 100644index a77adc224..000000000--- a/src/lib/ai-edition/exporter/renderPlan.test.ts+++ /dev/null@@ -1,942 +0,0 @@-import { describe, expect, it } from "vitest";-import type { AnnotationRegion, SpeedRegion, ZoomRegion } from "@/components/video-editor/types";-import { calculateMp4ExportSettings } from "@/lib/exporter/mp4ExportSettings";-import type { CursorRecordingData, CursorRecordingSample } from "@/native/contracts";-import type { AxcutAsset, AxcutClip, AxcutTrimRange } from "../schema";-import { buildRenderPlan, isIdentityFastPathEligible } from "./renderPlan";--// --- Factory helpers (lean: only fields the builder reads) ----------------------function asset(p: Partial<AxcutAsset> & Pick<AxcutAsset, "id">): AxcutAsset {- return {- kind: "video",- label: "Asset",- originalPath: "/tmp/asset.mp4",- cameraTrack: null,- ...p,- };-}--function clip(p: Partial<AxcutClip> & Pick<AxcutClip, "id">): AxcutClip {- return {- assetId: "a",- sourceStartSec: 0,- sourceEndSec: 10,- timelineStartSec: 0,- timelineEndSec: 10,- wordRefs: [],- origin: "user",- reason: "",- ...p,- };-}--function trim(p: Partial<AxcutTrimRange> & Pick<AxcutTrimRange, "id">): AxcutTrimRange {- return { assetId: "a", startSec: 0, endSec: 1, origin: "user", reason: "", ...p };-}--function zoom(p: Partial<ZoomRegion> & Pick<ZoomRegion, "id">): ZoomRegion {- return {- startMs: 0,- endMs: 1000,- depth: 2,- focus: { cx: 0.5, cy: 0.5 },- ...p,- };-}--function annotation(p: Partial<AnnotationRegion> & Pick<AnnotationRegion, "id">): AnnotationRegion {- return {- startMs: 0,- endMs: 1000,- type: "text",- content: "hi",- position: { x: 50, y: 50 },- size: { width: 30, height: 20 },- style: {- color: "#fff",- backgroundColor: "transparent",- fontSize: 32,- fontFamily: "Inter",- fontWeight: "bold",- fontStyle: "normal",- textDecoration: "none",- textAlign: "center",- },- zIndex: 1,- ...p,- };-}--function speed(p: Partial<SpeedRegion> & Pick<SpeedRegion, "id">): SpeedRegion {- return { startMs: 0, endMs: 1000, speed: 1, ...p };-}--function cursorSample(- p: Partial<CursorRecordingSample> & Pick<CursorRecordingSample, "timeMs">,-): CursorRecordingSample {- return { cx: 0.5, cy: 0.5, ...p };-}--function cursorRecording(p: Partial<CursorRecordingData> = {}): CursorRecordingData {- return { version: 1, provider: "native", samples: [], assets: [], ...p };-}--// Minimal valid document for the builder — the builder only reads project,-// assets, timeline.{clips, trimRanges}, zoomRanges, annotations, legacyEditor.-//-// ponytail: `zoomRegions` (with `s`) is the spec-facing key on RenderPlan and-// what tests pass in; `zoomRanges` (without) is the schema field on the-// document we feed the builder. Keep both names straight.-function doc(- p: Partial<{- assets: AxcutAsset[];- clips: AxcutClip[];- trimRanges: AxcutTrimRange[];- zoomRegions: ZoomRegion[];- annotations: AnnotationRegion[];- legacyEditor: Record<string, unknown> | null;- primaryAssetId: string;- }> = {},-) {- return {- project: { primaryAssetId: p.primaryAssetId },- assets: p.assets ?? [],- timeline: {- clips: p.clips ?? [],- trimRanges: p.trimRanges ?? [],- },- zoomRanges: p.zoomRegions ?? [],- annotations: p.annotations ?? [],- legacyEditor: p.legacyEditor ?? null,- };-}--// --- buildRenderPlan: segments --------------------------------------------------describe("buildRenderPlan — segments", () => {- it("single asset, identity: one segment with the expected fields and identity fast path", () => {- const assets = [- asset({- id: "a",- originalPath: "/tmp/a.mp4",- durationSec: 30,- video: { codec: "h264", width: 1920, height: 1080, fps: 30 },- }),- ];- const clips = [clip({ id: "c1", assetId: "a", sourceStartSec: 0, sourceEndSec: 10 })];- const plan = buildRenderPlan(doc({ assets, clips }), { quality: "source" });-- expect(plan.segments).toHaveLength(1);- expect(plan.segments[0]).toEqual({- clipId: "c1",- assetId: "a",- videoUrl: "file:///tmp/a.mp4",- sourceStartSec: 0,- sourceEndSec: 10,- timelineStartSec: 0,- timelineEndSec: 10,- intraTrims: [],- cropRegion: { x: 0, y: 0, width: 1, height: 1 },- sourceWidth: 1920,- sourceHeight: 1080,- camera: null,- cursorSamples: [],- });- expect(plan.cursor).toBeNull();- // Output = source for a 1920x1080 ref at 16:9 source quality → same dims.- expect(plan.output.width).toBe(1920);- expect(plan.output.height).toBe(1080);- expect(isIdentityFastPathEligible(plan)).toBe(true);- });-- it("two clips across two assets: one segment per clip, each carrying its own videoUrl + dims", () => {- const assets = [- asset({- id: "a1",- originalPath: "/tmp/a1.mp4",- durationSec: 30,- video: { codec: "h264", width: 1920, height: 1080, fps: 30 },- }),- asset({- id: "a2",- originalPath: "/tmp/a2.mp4",- durationSec: 30,- video: { codec: "h264", width: 1920, height: 1080, fps: 30 },- }),- ];- const clips = [- clip({- id: "c1",- assetId: "a1",- sourceStartSec: 0,- sourceEndSec: 5,- timelineStartSec: 0,- timelineEndSec: 5,- }),- clip({- id: "c2",- assetId: "a2",- sourceStartSec: 5,- sourceEndSec: 10,- timelineStartSec: 5,- timelineEndSec: 10,- }),- ];- const plan = buildRenderPlan(doc({ assets, clips }), { quality: "source" });-- expect(plan.segments).toHaveLength(2);- expect(plan.segments[0]).toMatchObject({- clipId: "c1",- assetId: "a1",- videoUrl: "file:///tmp/a1.mp4",- sourceWidth: 1920,- sourceHeight: 1080,- });- expect(plan.segments[1]).toMatchObject({- clipId: "c2",- assetId: "a2",- videoUrl: "file:///tmp/a2.mp4",- sourceWidth: 1920,- sourceHeight: 1080,- });- expect(isIdentityFastPathEligible(plan)).toBe(false);- });-- it("sorts segments by timelineStartSec regardless of input order", () => {- const assets = [- asset({- id: "a1",- originalPath: "/tmp/a1.mp4",- durationSec: 30,- video: { codec: "h264", width: 1920, height: 1080, fps: 30 },- }),- asset({- id: "a2",- originalPath: "/tmp/a2.mp4",- durationSec: 30,- video: { codec: "h264", width: 1920, height: 1080, fps: 30 },- }),- ];- // Inserted in reverse timeline order — builder must reorder by timelineStartSec.- const clips = [- clip({- id: "c2",- assetId: "a2",- sourceStartSec: 5,- sourceEndSec: 10,- timelineStartSec: 5,- timelineEndSec: 10,- }),- clip({- id: "c1",- assetId: "a1",- sourceStartSec: 0,- sourceEndSec: 5,- timelineStartSec: 0,- timelineEndSec: 5,- }),- ];- const plan = buildRenderPlan(doc({ assets, clips }), { quality: "source" });- expect(plan.segments.map((s) => s.clipId)).toEqual(["c1", "c2"]);- });-- it("falls back to asset.durationSec when clip.sourceEndSec is undefined", () => {- const assets = [- asset({- id: "a",- originalPath: "/tmp/a.mp4",- durationSec: 42,- video: { codec: "h264", width: 1920, height: 1080, fps: 30 },- }),- ];- const clips = [clip({ id: "c1", assetId: "a", sourceStartSec: 5, sourceEndSec: undefined })];- const plan = buildRenderPlan(doc({ assets, clips }), { quality: "source" });- expect(plan.segments[0].sourceEndSec).toBe(42);- });-- it("skips clips whose asset is missing (no throw, no segment)", () => {- const assets = [- asset({- id: "a",- originalPath: "/tmp/a.mp4",- durationSec: 30,- video: { codec: "h264", width: 1920, height: 1080, fps: 30 },- }),- ];- const clips = [- clip({ id: "c1", assetId: "a", sourceStartSec: 0, sourceEndSec: 5 }),- clip({ id: "c2", assetId: "ghost", sourceStartSec: 5, sourceEndSec: 10 }),- ];- const plan = buildRenderPlan(doc({ assets, clips }), { quality: "source" });- expect(plan.segments.map((s) => s.clipId)).toEqual(["c1"]);- });-});--// --- buildRenderPlan: intraTrims (per-segment scoping + clamping) ---------------describe("buildRenderPlan — intraTrims", () => {- const assets = [- asset({- id: "a",- originalPath: "/tmp/a.mp4",- durationSec: 30,- video: { codec: "h264", width: 1920, height: 1080, fps: 30 },- }),- asset({- id: "b",- originalPath: "/tmp/b.mp4",- durationSec: 30,- video: { codec: "h264", width: 1920, height: 1080, fps: 30 },- }),- ];-- it("scopes intraTrims by assetId: trims on a different asset are dropped", () => {- const clips = [clip({ id: "c1", assetId: "a", sourceStartSec: 0, sourceEndSec: 20 })];- const trimRanges = [- trim({ id: "t1", assetId: "a", startSec: 5, endSec: 8 }),- trim({ id: "t2", assetId: "b", startSec: 5, endSec: 8 }), // different asset → ignored- ];- const plan = buildRenderPlan(doc({ assets, clips, trimRanges }), { quality: "source" });- expect(plan.segments[0].intraTrims).toEqual([{ startSec: 5, endSec: 8 }]);- });-- it("clamps a partly-outside trim to the clip's [start, end) window", () => {- const clips = [clip({ id: "c1", assetId: "a", sourceStartSec: 10, sourceEndSec: 20 })];- const trimRanges = [trim({ id: "t1", assetId: "a", startSec: 5, endSec: 15 })];- const plan = buildRenderPlan(doc({ assets, clips, trimRanges }), { quality: "source" });- expect(plan.segments[0].intraTrims).toEqual([{ startSec: 10, endSec: 15 }]);- });-- it("drops a trim that is fully outside the clip's source range", () => {- const clips = [clip({ id: "c1", assetId: "a", sourceStartSec: 10, sourceEndSec: 20 })];- const trimRanges = [trim({ id: "t1", assetId: "a", startSec: 0, endSec: 5 })];- const plan = buildRenderPlan(doc({ assets, clips, trimRanges }), { quality: "source" });- expect(plan.segments[0].intraTrims).toEqual([]);- });-});--// --- buildRenderPlan: crop & camera ---------------------------------------------describe("buildRenderPlan — crop & camera", () => {- it("carries an explicit clip.cropRegion through verbatim", () => {- const assets = [- asset({- id: "a",- originalPath: "/tmp/a.mp4",- durationSec: 30,- video: { codec: "h264", width: 1920, height: 1080, fps: 30 },- }),- ];- const crop = { x: 0.25, y: 0.25, width: 0.5, height: 0.5 };- const clips = [- clip({ id: "c1", assetId: "a", sourceStartSec: 0, sourceEndSec: 10, cropRegion: crop }),- ];- const plan = buildRenderPlan(doc({ assets, clips }), { quality: "source" });- expect(plan.segments[0].cropRegion).toEqual(crop);- });-- it("defaults to the identity crop when the clip has none", () => {- const assets = [- asset({- id: "a",- originalPath: "/tmp/a.mp4",- durationSec: 30,- video: { codec: "h264", width: 1920, height: 1080, fps: 30 },- }),- ];- const clips = [clip({ id: "c1", assetId: "a", sourceStartSec: 0, sourceEndSec: 10 })];- const plan = buildRenderPlan(doc({ assets, clips }), { quality: "source" });- expect(plan.segments[0].cropRegion).toEqual({ x: 0, y: 0, width: 1, height: 1 });- });-- it("attaches a camera entry when the asset's cameraTrack is visible + has a sourcePath", () => {- const assets = [- asset({- id: "a",- originalPath: "/tmp/a.mp4",- durationSec: 30,- video: { codec: "h264", width: 1920, height: 1080, fps: 30 },- cameraTrack: {- sourcePath: "/tmp/a-cam.mp4",- startMs: 0,- offsetMs: 250,- visible: true,- },- }),- ];- const clips = [clip({ id: "c1", assetId: "a", sourceStartSec: 0, sourceEndSec: 10 })];- const plan = buildRenderPlan(doc({ assets, clips }), { quality: "source" });- expect(plan.segments[0].camera).toEqual({- videoUrl: "file:///tmp/a-cam.mp4",- offsetMs: 250,- });- });-- it("omits camera when cameraTrack is invisible", () => {- const assets = [- asset({- id: "a",- originalPath: "/tmp/a.mp4",- durationSec: 30,- video: { codec: "h264", width: 1920, height: 1080, fps: 30 },- cameraTrack: {- sourcePath: "/tmp/a-cam.mp4",- startMs: 0,- offsetMs: 0,- visible: false,- },- }),- ];- const clips = [clip({ id: "c1", assetId: "a", sourceStartSec: 0, sourceEndSec: 10 })];- const plan = buildRenderPlan(doc({ assets, clips }), { quality: "source" });- expect(plan.segments[0].camera).toBeNull();- });-- it("omits camera when cameraTrack is null", () => {- const assets = [- asset({- id: "a",- originalPath: "/tmp/a.mp4",- durationSec: 30,- video: { codec: "h264", width: 1920, height: 1080, fps: 30 },- cameraTrack: null,- }),- ];- const clips = [clip({ id: "c1", assetId: "a", sourceStartSec: 0, sourceEndSec: 10 })];- const plan = buildRenderPlan(doc({ assets, clips }), { quality: "source" });- expect(plan.segments[0].camera).toBeNull();- });-});--// --- buildRenderPlan: output sizing ---------------------------------------------describe("buildRenderPlan — output sizing", () => {- it("sizes output from the largest-by-pixel-area segment and matches calculateMp4ExportSettings", () => {- const assets = [- asset({- id: "a1",- originalPath: "/tmp/a1.mp4",- durationSec: 30,- video: { codec: "h264", width: 1280, height: 720, fps: 30 },- }),- asset({- id: "a2",- originalPath: "/tmp/a2.mp4",- durationSec: 30,- video: { codec: "h264", width: 3840, height: 2160, fps: 30 },- }),- ];- const clips = [- clip({- id: "c1",- assetId: "a1",- sourceStartSec: 0,- sourceEndSec: 5,- timelineStartSec: 0,- timelineEndSec: 5,- }),- clip({- id: "c2",- assetId: "a2",- sourceStartSec: 5,- sourceEndSec: 10,- timelineStartSec: 5,- timelineEndSec: 10,- }),- ];- const plan = buildRenderPlan(doc({ assets, clips, legacyEditor: { aspectRatio: "16:9" } }), {- quality: "source",- });- const expected = calculateMp4ExportSettings({- quality: "source",- sourceWidth: 3840,- sourceHeight: 2160,- aspectRatioValue: 16 / 9,- });- expect(plan.output.width).toBe(expected.width);- expect(plan.output.height).toBe(expected.height);- expect(plan.output.bitrate).toBe(expected.bitrate);- expect(plan.aspectRatioValue).toBeCloseTo(16 / 9, 6);- });-- it("falls back to the option-provided fallback dims when there are no segments", () => {- const plan = buildRenderPlan(doc({ assets: [], clips: [] }), {- quality: "source",- fallbackSourceWidth: 640,- fallbackSourceHeight: 480,- });- const expected = calculateMp4ExportSettings({- quality: "source",- sourceWidth: 640,- sourceHeight: 480,- aspectRatioValue: 16 / 9,- });- expect(plan.output.width).toBe(expected.width);- expect(plan.output.height).toBe(expected.height);- });-- it("honors frameRate + codec options", () => {- const assets = [- asset({- id: "a",- originalPath: "/tmp/a.mp4",- durationSec: 30,- video: { codec: "h264", width: 1920, height: 1080, fps: 30 },- }),- ];- const clips = [clip({ id: "c1", assetId: "a", sourceStartSec: 0, sourceEndSec: 10 })];- const plan = buildRenderPlan(doc({ assets, clips }), {- quality: "source",- frameRate: 30,- codec: "h265",- });- expect(plan.output.frameRate).toBe(30);- expect(plan.output.codec).toBe("hvc1.1.6.L120.90");- });-});--// --- buildRenderPlan: effects pass-through (VIRTUAL time, NO projection) --------describe("buildRenderPlan — effects pass-through", () => {- const baseAssets = [- asset({- id: "a",- originalPath: "/tmp/a.mp4",- durationSec: 30,- video: { codec: "h264", width: 1920, height: 1080, fps: 30 },- }),- ];- const baseClips = [clip({ id: "c1", assetId: "a", sourceStartSec: 0, sourceEndSec: 10 })];-- it("carries zoomRanges verbatim (same ids + startMs + endMs) — no projection", () => {- const zoomRegions = [- zoom({ id: "z1", startMs: 500, endMs: 2500, depth: 3 }),- zoom({ id: "z2", startMs: 4000, endMs: 6000, depth: 4 }),- ];- const plan = buildRenderPlan(doc({ assets: baseAssets, clips: baseClips, zoomRegions }), {- quality: "source",- });- expect(plan.zoomRegions).toEqual(zoomRegions);- });-- it("carries annotations verbatim (same ids + startMs + endMs) — no projection", () => {- const annotations = [- annotation({ id: "a1", startMs: 1000, endMs: 3000 }),- annotation({ id: "a2", startMs: 3500, endMs: 5500 }),- ];- const plan = buildRenderPlan(doc({ assets: baseAssets, clips: baseClips, annotations }), {- quality: "source",- });- expect(plan.annotationRegions).toEqual(annotations);- });-- it("carries speedRegions verbatim (same ids + startMs + endMs + speed) — no projection", () => {- const speedRegions = [- speed({ id: "s1", startMs: 1500, endMs: 2500, speed: 2 }),- speed({ id: "s2", startMs: 4000, endMs: 5000, speed: 0.5 }),- ];- const plan = buildRenderPlan(- doc({- assets: baseAssets,- clips: baseClips,- legacyEditor: { speedRegions },- }),- { quality: "source" },- );- expect(plan.speedRegions).toEqual(speedRegions);- });-- it("defaults speedRegions to [] when legacyEditor is null and skips speedRegions absent", () => {- const plan = buildRenderPlan(doc({ assets: baseAssets, clips: baseClips }), {- quality: "source",- });- expect(plan.speedRegions).toEqual([]);- });-- it("reads appearance defaults from legacyEditor with the documented fallbacks", () => {- const plan = buildRenderPlan(doc({ assets: baseAssets, clips: baseClips }), {- quality: "source",- });- expect(plan.appearance).toEqual({- wallpaper: "",- padding: 50,- borderRadius: 0,- shadowIntensity: 0,- showBlur: false,- motionBlurAmount: 0,- });- });-});--// --- buildRenderPlan: cursor (per-segment, decision D1) ------------------------describe("buildRenderPlan — cursor", () => {- const twoAssets = [- asset({- id: "a1",- originalPath: "/tmp/a1.mp4",- durationSec: 30,- video: { codec: "h264", width: 1920, height: 1080, fps: 30 },- }),- asset({- id: "a2",- originalPath: "/tmp/a2.mp4",- durationSec: 30,- video: { codec: "h264", width: 1920, height: 1080, fps: 30 },- }),- ];- const twoClips = [- clip({- id: "c1",- assetId: "a1",- sourceStartSec: 0,- sourceEndSec: 5,- timelineStartSec: 0,- timelineEndSec: 5,- }),- clip({- id: "c2",- assetId: "a2",- sourceStartSec: 5,- sourceEndSec: 10,- timelineStartSec: 5,- timelineEndSec: 10,- }),- ];-- it("partitions samples per segment by assetId — each segment gets only its asset's samples", () => {- const recordingData = cursorRecording({- samples: [- cursorSample({ timeMs: 100, assetId: "a1" }),- cursorSample({ timeMs: 200, assetId: "a2" }),- cursorSample({ timeMs: 300, assetId: "a1" }),- ],- });- const plan = buildRenderPlan(doc({ assets: twoAssets, clips: twoClips }), {- quality: "source",- cursor: { recordingData, scale: 1 },- });- expect(plan.segments[0].cursorSamples.map((s) => s.timeMs)).toEqual([100, 300]);- expect(plan.segments[1].cursorSamples.map((s) => s.timeMs)).toEqual([200]);- });-- it("attributes untagged samples (no assetId) to the primary asset", () => {- const recordingData = cursorRecording({- samples: [cursorSample({ timeMs: 100 }), cursorSample({ timeMs: 200, assetId: "a2" })],- });- const plan = buildRenderPlan(- doc({ assets: twoAssets, clips: twoClips, primaryAssetId: "a1" }),- { quality: "source", cursor: { recordingData, scale: 1 } },- );- expect(plan.segments[0].cursorSamples.map((s) => s.timeMs)).toEqual([100]);- expect(plan.segments[1].cursorSamples.map((s) => s.timeMs)).toEqual([200]);- });-- it("falls back to the first asset for untagged samples when primaryAssetId is unset", () => {- const recordingData = cursorRecording({ samples: [cursorSample({ timeMs: 100 })] });- const plan = buildRenderPlan(doc({ assets: twoAssets, clips: twoClips }), {- quality: "source",- cursor: { recordingData, scale: 1 },- });- expect(plan.segments[0].cursorSamples.map((s) => s.timeMs)).toEqual([100]);- expect(plan.segments[1].cursorSamples).toEqual([]);- });-- it("gives a segment whose asset has no cursor data an empty samples array (no overlay)", () => {- const recordingData = cursorRecording({- samples: [cursorSample({ timeMs: 100, assetId: "a1" })],- });- const plan = buildRenderPlan(doc({ assets: twoAssets, clips: twoClips }), {- quality: "source",- cursor: { recordingData, scale: 1 },- });- expect(plan.segments[1].cursorSamples).toEqual([]);- });-- it("builds plan.cursor (shared atlas + style) when scale > 0 and a recording is present", () => {- const spriteAsset = {- id: "cur1",- platform: "windows",- imageDataUrl: "data:,",- width: 16,- height: 16,- hotspotX: 0,- hotspotY: 0,- } as CursorRecordingData["assets"][number];- const recordingData = cursorRecording({- version: 2,- provider: "native",- assets: [spriteAsset],- samples: [cursorSample({ timeMs: 0, assetId: "a1" })],- });- const plan = buildRenderPlan(doc({ assets: twoAssets, clips: twoClips }), {- quality: "source",- cursor: {- recordingData,- scale: 1.5,- smoothing: 0.3,- motionBlur: 0.2,- clickBounce: 0.5,- clipToBounds: true,- theme: "dark",- },- });- expect(plan.cursor).toEqual({- version: 2,- provider: "native",- assets: [spriteAsset],- scale: 1.5,- smoothing: 0.3,- motionBlur: 0.2,- clickBounce: 0.5,- clipToBounds: true,- theme: "dark",- });- });-- it("leaves plan.cursor null and carries no samples when scale is 0 (cursor disabled)", () => {- const recordingData = cursorRecording({- samples: [cursorSample({ timeMs: 0, assetId: "a1" })],- });- const plan = buildRenderPlan(doc({ assets: twoAssets, clips: twoClips }), {- quality: "source",- cursor: { recordingData, scale: 0 },- });- expect(plan.cursor).toBeNull();- expect(plan.segments.every((s) => s.cursorSamples.length === 0)).toBe(true);- });-- it("leaves plan.cursor null when no recording is supplied", () => {- const plan = buildRenderPlan(doc({ assets: twoAssets, clips: twoClips }), {- quality: "source",- cursor: { scale: 1 },- });- expect(plan.cursor).toBeNull();- expect(plan.segments.every((s) => s.cursorSamples.length === 0)).toBe(true);- });-});--// --- buildRenderPlan: webcam layout (global, from legacyEditor) ----------------describe("buildRenderPlan — webcam layout", () => {- const assets = [- asset({- id: "a",- originalPath: "/tmp/a.mp4",- durationSec: 30,- video: { codec: "h264", width: 1920, height: 1080, fps: 30 },- }),- ];- const clips = [clip({ id: "c1", assetId: "a", sourceStartSec: 0, sourceEndSec: 10 })];-- it("uses the documented defaults when legacyEditor is null", () => {- const plan = buildRenderPlan(doc({ assets, clips }), { quality: "source" });- expect(plan.webcam).toEqual({- layoutPreset: "picture-in-picture",- maskShape: "rectangle",- mirrored: false,- reactiveZoom: true,- sizePreset: 25,- position: null,- });- });-- it("reads webcam layout/style from legacyEditor", () => {- const plan = buildRenderPlan(- doc({- assets,- clips,- legacyEditor: {- webcamLayoutPreset: "vertical-stack",- webcamMaskShape: "circle",- webcamMirrored: true,- webcamReactiveZoom: false,- webcamSizePreset: 40,- webcamPosition: { cx: 0.8, cy: 0.7 },- },- }),- { quality: "source" },- );- expect(plan.webcam).toEqual({- layoutPreset: "vertical-stack",- maskShape: "circle",- mirrored: true,- reactiveZoom: false,- sizePreset: 40,- position: { cx: 0.8, cy: 0.7 },- });- });-});--// --- isIdentityFastPathEligible -------------------------------------------------describe("isIdentityFastPathEligible", () => {- function singleUntouchedAsset() {- return asset({- id: "a",- originalPath: "/tmp/a.mp4",- durationSec: 30,- video: { codec: "h264", width: 1920, height: 1080, fps: 30 },- });- }- function singleClipOn(assetId: string) {- return clip({ id: "c1", assetId, sourceStartSec: 0, sourceEndSec: 10 });- }-- it("returns true for an untouched single clip whose output matches source dims", () => {- const assets = [singleUntouchedAsset()];- const clips = [singleClipOn("a")];- const plan = buildRenderPlan(doc({ assets, clips }), { quality: "source" });- expect(isIdentityFastPathEligible(plan)).toBe(true);- });-- it("returns false when there are 2+ segments", () => {- const assets = [- singleUntouchedAsset(),- asset({- id: "a2",- originalPath: "/tmp/a2.mp4",- durationSec: 30,- video: { codec: "h264", width: 1920, height: 1080, fps: 30 },- }),- ];- const clips = [- clip({- id: "c1",- assetId: "a",- sourceStartSec: 0,- sourceEndSec: 5,- timelineStartSec: 0,- timelineEndSec: 5,- }),- clip({- id: "c2",- assetId: "a2",- sourceStartSec: 0,- sourceEndSec: 5,- timelineStartSec: 5,- timelineEndSec: 10,- }),- ];- const plan = buildRenderPlan(doc({ assets, clips }), { quality: "source" });- expect(isIdentityFastPathEligible(plan)).toBe(false);- });-- it("returns false when the single segment has intraTrims", () => {- const assets = [singleUntouchedAsset()];- const clips = [singleClipOn("a")];- const trimRanges = [trim({ id: "t1", assetId: "a", startSec: 3, endSec: 5 })];- const plan = buildRenderPlan(doc({ assets, clips, trimRanges }), { quality: "source" });- expect(isIdentityFastPathEligible(plan)).toBe(false);- });-- it("returns false when the single segment has a non-identity crop", () => {- const assets = [singleUntouchedAsset()];- const clips = [- clip({- id: "c1",- assetId: "a",- sourceStartSec: 0,- sourceEndSec: 10,- cropRegion: { x: 0.1, y: 0.1, width: 0.8, height: 0.8 },- }),- ];- const plan = buildRenderPlan(doc({ assets, clips }), { quality: "source" });- expect(isIdentityFastPathEligible(plan)).toBe(false);- });-- it("returns false when any active (non-zero-length, non-1x) speedRegion is present", () => {- const assets = [singleUntouchedAsset()];- const clips = [singleClipOn("a")];- const plan = buildRenderPlan(- doc({- assets,- clips,- legacyEditor: { speedRegions: [speed({ id: "s1", startMs: 1000, endMs: 3000, speed: 2 })] },- }),- { quality: "source" },- );- expect(isIdentityFastPathEligible(plan)).toBe(false);- });-- it("treats a 1x speedRegion of any length as inactive", () => {- const assets = [singleUntouchedAsset()];- const clips = [singleClipOn("a")];- const plan = buildRenderPlan(- doc({- assets,- clips,- legacyEditor: {- speedRegions: [- speed({ id: "s1", startMs: 1000, endMs: 3000, speed: 1 }),- speed({ id: "s2", startMs: 0, endMs: 0, speed: 2 }), // zero-length → inactive- ],- },- }),- { quality: "source" },- );- expect(isIdentityFastPathEligible(plan)).toBe(true);- });-- it("returns false when a zoomRegion is present", () => {- const assets = [singleUntouchedAsset()];- const clips = [singleClipOn("a")];- const plan = buildRenderPlan(doc({ assets, clips, zoomRegions: [zoom({ id: "z1" })] }), {- quality: "source",- });- expect(isIdentityFastPathEligible(plan)).toBe(false);- });-- it("returns false when an annotationRegion is present", () => {- const assets = [singleUntouchedAsset()];- const clips = [singleClipOn("a")];- const plan = buildRenderPlan(- doc({ assets, clips, annotations: [annotation({ id: "ann1" })] }),- { quality: "source" },- );- expect(isIdentityFastPathEligible(plan)).toBe(false);- });-- it("returns false when output dims differ from source dims", () => {- const assets = [- asset({- id: "a",- originalPath: "/tmp/a.mp4",- durationSec: 30,- video: { codec: "h264", width: 3840, height: 2160, fps: 30 },- }),- ];- const clips = [singleClipOn("a")];- // quality: "good" → output short-side 1080 at 16:9 → 1920x1080, smaller than 3840x2160.- const plan = buildRenderPlan(doc({ assets, clips }), { quality: "good" });- expect(isIdentityFastPathEligible(plan)).toBe(false);- });-- it("returns false when an active cursor overlay covers the single segment", () => {- const assets = [singleUntouchedAsset()];- const clips = [singleClipOn("a")];- const recordingData = cursorRecording({- samples: [cursorSample({ timeMs: 0, assetId: "a" })],- });- const plan = buildRenderPlan(doc({ assets, clips }), {- quality: "source",- cursor: { recordingData, scale: 1 },- });- expect(plan.segments[0].cursorSamples.length).toBeGreaterThan(0);- expect(isIdentityFastPathEligible(plan)).toBe(false);- });-- it("stays eligible when a cursor recording exists but cursor is disabled (scale 0)", () => {- const assets = [singleUntouchedAsset()];- const clips = [singleClipOn("a")];- const recordingData = cursorRecording({- samples: [cursorSample({ timeMs: 0, assetId: "a" })],- });- const plan = buildRenderPlan(doc({ assets, clips }), {- quality: "source",- cursor: { recordingData, scale: 0 },- });- expect(isIdentityFastPathEligible(plan)).toBe(true);- });-});diff --git a/src/lib/ai-edition/exporter/renderPlan.ts b/src/lib/ai-edition/exporter/renderPlan.tsdeleted file mode 100644index 662853c92..000000000--- a/src/lib/ai-edition/exporter/renderPlan.ts+++ /dev/null@@ -1,435 +0,0 @@-// RenderPlan: the v2 multi-asset export pipeline's pure-logic data model.-//-// ponytail: today `documentExporter` plays a single continuous source stream-// (the primary asset) and projects timeline-authored effects (zoom / annotation-// / speed) onto each frame's *source* time, so any clip that points at a-// different asset is silently dropped. The v2 renderer decodes one segment at-// a time, so effects stay keyed in VIRTUAL (output) time and the plan just-// carries an ordered list of per-clip render segments — each with its own-// source stream and intra-clip cuts — plus the output framing and the-// pass-through effect arrays.-//-// This module is the foundation: a pure (no DOM, no IPC, no side effects)-// builder + a small `isIdentityFastPathEligible` helper the renderer can use-// to skip re-encode-worthy work for untouched single-clip projects.--import { toFileUrl } from "@/components/video-editor/projectPersistence";-import type {- AnnotationRegion,- CropRegion,- SpeedRegion,- WebcamLayoutPreset,- WebcamMaskShape,- WebcamSizePreset,- ZoomRegion,-} from "@/components/video-editor/types";-import { calculateMp4ExportSettings } from "@/lib/exporter/mp4ExportSettings";-import type { ExportQuality } from "@/lib/exporter/types";-import type {- CursorProviderKind,- CursorRecordingData,- CursorRecordingSample,- NativeCursorAsset,-} from "@/native/contracts";-import {- type AspectRatio,- getAspectRatioValue,- getNativeAspectRatioValue,-} from "@/utils/aspectRatioUtils";-import {- captionCuesToTextRegions,- deriveCaptionCues,- getCaptionSettings,- getCaptionTranslations,-} from "../captions";-import { type Interval, normalizeIntervals } from "../document/timeline";-import type { AxcutDocument } from "../schema";-import { resolveClipSourceEndSec } from "../timeline/clipDuration";--export type ExportVideoCodec = "h264" | "h265" | "vp9";--// WebCodecs encoder strings per user-facing codec choice. The muxer derives-// its mp4 track family from the same string.-const CODEC_STRINGS: Record<ExportVideoCodec, string> = {- h264: "avc1.640033",- h265: "hvc1.1.6.L120.90",- vp9: "vp09.00.10.08",-};--const IDENTITY_CROP: CropRegion = { x: 0, y: 0, width: 1, height: 1 };--const DEFAULT_FRAME_RATE = 60;-const DEFAULT_FALLBACK_SOURCE_WIDTH = 1920;-const DEFAULT_FALLBACK_SOURCE_HEIGHT = 1080;--// ponytail: one render segment = one source clip fed into the decoder +-// frame loop. The renderer iterates these in order; the segment loop tracks a-// running output/virtual-time cursor so effects (passed through separately,-// keyed in virtual ms) land on the right frames regardless of which asset-// each clip draws from.-export interface RenderSegment {- clipId: string;- assetId: string;- videoUrl: string;- sourceStartSec: number;- sourceEndSec: number;- // The clip's position on the (1:1-with-source, pre-speed) virtual timeline.- // Timeline-authored effects (zoom/annotation/speed) are projected onto this- // segment's source time through [timelineStart,timelineEnd)↔[sourceStart,…).- timelineStartSec: number;- timelineEndSec: number;- // Cuts INSIDE this clip, scoped per segment (unlike today's single global- // complement in `computeExportTrimRegions`). Pre-merged + clamped via- // `normalizeIntervals` so the renderer can drop straight in.- intraTrims: Interval[];- cropRegion: CropRegion;- sourceWidth: number;- sourceHeight: number;- // Camera (webcam) attached to this segment's asset, when present and- // visible. The renderer treats it as a derived stream like the existing- // exporter does — no per-clip stitching beyond what `cameraTrack.offsetMs`- // already encodes.- camera: { videoUrl: string; offsetMs: number } | null;- // Native-cursor telemetry for THIS segment's asset only (decision D1 —- // per-segment cursor). `CursorRecordingSample.assetId` already tags each- // sample with its recording, so the plan partitions the shared recording by- // `assetId`; samples with no tag fall back to the primary asset (older- // single-asset recordings). `timeMs` stays in the asset's own source time —- // the renderer matches it against each frame's source time inside this- // segment's window. Empty when the asset has no cursor data (§6.4 / risk R3):- // that segment renders with no cursor overlay, which is correct, not a gap.- cursorSamples: CursorRecordingSample[];-}--export interface RenderPlanOutput {- width: number;- height: number;- frameRate: number;- bitrate: number;- codec: string;-}--export interface RenderPlanAppearance {- wallpaper: string;- padding: number;- borderRadius: number;- shadowIntensity: number;- showBlur: boolean;- motionBlurAmount: number;-}--// Plan-level cursor: the SHARED parts of a native-cursor render — the sprite-// atlas (`assets`) and the style knobs — held once for the whole export. The-// time-varying samples live per segment on `RenderSegment.cursorSamples`-// (partitioned by asset). `null` when the export has no cursor recording, or-// cursor rendering is disabled (`scale <= 0`).-export interface RenderPlanCursor {- version: number;- provider: CursorProviderKind;- assets: NativeCursorAsset[];- scale: number;- smoothing?: number;- motionBlur?: number;- clickBounce?: number;- clipToBounds?: boolean;- theme?: string;-}--// Global webcam layout/style (from legacyEditor) shared by every segment. The-// per-segment webcam SOURCE (file + offset) lives on `RenderSegment.camera`; a-// segment renders a webcam overlay only when its asset has a camera track.-export interface RenderPlanWebcam {- layoutPreset: WebcamLayoutPreset;- maskShape: WebcamMaskShape;- mirrored: boolean;- reactiveZoom: boolean;- sizePreset: WebcamSizePreset;- position: { cx: number; cy: number } | null;-}--export interface RenderPlan {- output: RenderPlanOutput;- aspectRatioValue: number;- // Timeline order = output order. Sorted by `timelineStartSec` ascending so- // the renderer can walk segments and effects (which are keyed in virtual- // ms) in a single forward pass.- segments: RenderSegment[];- // VIRTUAL (output) time. Direct pass-through of the document's regions with- // NO projection — the segment loop already tracks the virtual-time cursor- // that today required `projectRegionsToSourceTime`.- zoomRegions: ZoomRegion[];- annotationRegions: AnnotationRegion[];- speedRegions: SpeedRegion[];- appearance: RenderPlanAppearance;- // Shared cursor style + sprite atlas (per-segment samples live on each- // segment). `null` when there is no recording or cursor is disabled.- cursor: RenderPlanCursor | null;- // Shared webcam layout/style (per-segment webcam source is on the segment).- webcam: RenderPlanWebcam;-}--export interface BuildRenderPlanCursorOptions {- recordingData?: CursorRecordingData | null;- scale?: number;- smoothing?: number;- motionBlur?: number;- clickBounce?: number;- clipToBounds?: boolean;- theme?: string;-}--export interface BuildRenderPlanOptions {- quality: ExportQuality;- frameRate?: number;- codec?: ExportVideoCodec;- fallbackSourceWidth?: number;- fallbackSourceHeight?: number;- // Cursor recording + style, supplied by the caller (ExportDialog) — the- // document/asset schema does not persist cursor telemetry. Omit for no cursor.- cursor?: BuildRenderPlanCursorOptions;-}--function extractLegacyField<T>(- legacy: Record<string, unknown> | null,- key: string,- fallback: T,-): T {- if (legacy && typeof legacy[key] === typeof fallback) {- return legacy[key] as T;- }- return fallback;-}--// Stable, clone-only sort — never mutates the document's clips array. JS's-// `Array.prototype.sort` is stable per ECMA-262 since ES2019, so identical-// `timelineStartSec` preserves insertion order.-function sortClipsByTimelineStart<T extends { timelineStartSec: number }>(clips: T[]): T[] {- return [...clips].sort((a, b) => a.timelineStartSec - b.timelineStartSec);-}--function buildIntraTrims(- document: AxcutDocument,- clip: AxcutDocument["timeline"]["clips"][number],- sourceStartSec: number,- sourceEndSec: number,-): Interval[] {- const intersected: Interval[] = [];- for (const trim of document.timeline.trimRanges) {- if (trim.assetId !== clip.assetId) continue;- intersected.push({- startSec: Math.max(trim.startSec, sourceStartSec),- endSec: Math.min(trim.endSec, sourceEndSec),- });- }- return normalizeIntervals(sourceEndSec, intersected);-}--// Native-cursor samples belonging to one asset (decision D1 — per-segment-// cursor). A sample with no `assetId` predates multi-asset cursor tagging, so it-// belongs to the primary asset — attributing it there keeps single-asset-// projects rendering their cursor exactly as before.-function cursorSamplesForAsset(- recordingData: CursorRecordingData | null | undefined,- assetId: string,- primaryAssetId: string | undefined,-): CursorRecordingSample[] {- if (!recordingData) return [];- return recordingData.samples.filter((s) => (s.assetId ?? primaryAssetId) === assetId);-}--function pickReferenceDimensions(- segments: RenderSegment[],- fallbackWidth: number,- fallbackHeight: number,-): { width: number; height: number } {- if (segments.length === 0) {- return { width: fallbackWidth, height: fallbackHeight };- }- let bestArea = -1;- let best: { width: number; height: number } = { width: fallbackWidth, height: fallbackHeight };- for (const segment of segments) {- const area = segment.sourceWidth * segment.sourceHeight;- if (area > bestArea) {- bestArea = area;- best = { width: segment.sourceWidth, height: segment.sourceHeight };- }- }- return best;-}--export function buildRenderPlan(- document: AxcutDocument,- options: BuildRenderPlanOptions,-): RenderPlan {- const fallbackWidth = options.fallbackSourceWidth ?? DEFAULT_FALLBACK_SOURCE_WIDTH;- const fallbackHeight = options.fallbackSourceHeight ?? DEFAULT_FALLBACK_SOURCE_HEIGHT;- const codec: ExportVideoCodec = options.codec ?? "h264";- const frameRate = options.frameRate ?? DEFAULT_FRAME_RATE;-- // Primary asset id anchors untagged cursor samples (see cursorSamplesForAsset).- const primaryAssetId = document.project.primaryAssetId ?? document.assets[0]?.id;- // Cursor is only rendered when scaled up (matches the existing exporter's- // `hasNativeCursorOverlay = cursorScale > 0`). When disabled, carry no samples- // and leave `plan.cursor` null so the identity fast path stays available.- const cursorScale = options.cursor?.scale ?? 0;- const cursorRecording = cursorScale > 0 ? (options.cursor?.recordingData ?? null) : null;-- // --- Segments ---- const sortedClips = sortClipsByTimelineStart(document.timeline.clips);- const segments: RenderSegment[] = [];- for (const clip of sortedClips) {- const asset = document.assets.find((a) => a.id === clip.assetId);- if (!asset) continue; // orphan clip — can't render, skip silently (matches today).-- const sourceStartSec = clip.sourceStartSec;- const sourceEndSec = resolveClipSourceEndSec(clip, asset);- const sourceWidth = asset.video?.width || fallbackWidth || DEFAULT_FALLBACK_SOURCE_WIDTH;- const sourceHeight = asset.video?.height || fallbackHeight || DEFAULT_FALLBACK_SOURCE_HEIGHT;- const cameraTrack = asset.cameraTrack;- const camera =- cameraTrack && cameraTrack.visible && cameraTrack.sourcePath- ? { videoUrl: toFileUrl(cameraTrack.sourcePath), offsetMs: cameraTrack.offsetMs }- : null;-- segments.push({- clipId: clip.id,- assetId: asset.id,- videoUrl: toFileUrl(asset.originalPath),- sourceStartSec,- sourceEndSec,- timelineStartSec: clip.timelineStartSec,- timelineEndSec: clip.timelineEndSec,- intraTrims: buildIntraTrims(document, clip, sourceStartSec, sourceEndSec),- cropRegion: clip.cropRegion ?? IDENTITY_CROP,- sourceWidth,- sourceHeight,- camera,- cursorSamples: cursorSamplesForAsset(cursorRecording, asset.id, primaryAssetId),- });- }-- // --- Output sizing ---- const ref = pickReferenceDimensions(segments, fallbackWidth, fallbackHeight);- const legacy = document.legacyEditor as Record<string, unknown> | null;- const aspectRatio = extractLegacyField<AspectRatio>(legacy, "aspectRatio", "16:9");- const aspectRatioValue =- aspectRatio === "native"- ? getNativeAspectRatioValue(ref.width, ref.height)- : getAspectRatioValue(aspectRatio);- const settings = calculateMp4ExportSettings({- quality: options.quality,- sourceWidth: ref.width,- sourceHeight: ref.height,- aspectRatioValue,- });-- // --- Effects (virtual time, pass-through, NO projection) ---- const zoomRegions = document.zoomRanges as unknown as ZoomRegion[];- // Captions are derived from the transcript and joined to the annotations here,- // because they render through the same text path. They must be part of the plan- // (and not only of the legacy config) or the segment-loop renderer would export- // a caption-less file — and `isIdentityFastPathEligible` would happily- // stream-copy a video whose captions never got drawn.- const captionSettings = getCaptionSettings(document);- const annotationRegions = [- ...(document.annotations as unknown as AnnotationRegion[]),- ...captionCuesToTextRegions(- deriveCaptionCues(document, captionSettings, getCaptionTranslations(document)),- captionSettings,- ),- ];- const speedRegions = extractLegacyField<SpeedRegion[]>(legacy, "speedRegions", []);-- // --- Appearance ---- const appearance: RenderPlanAppearance = {- wallpaper: extractLegacyField(legacy, "wallpaper", ""),- padding: extractLegacyField(legacy, "padding", 50),- borderRadius: extractLegacyField(legacy, "borderRadius", 0),- shadowIntensity: extractLegacyField(legacy, "shadowIntensity", 0),- showBlur: extractLegacyField(legacy, "showBlur", false),- motionBlurAmount: extractLegacyField(legacy, "motionBlurAmount", 0),- };-- // --- Cursor (shared atlas + style; per-segment samples set above) ---- const cursor: RenderPlanCursor | null = cursorRecording- ? {- version: cursorRecording.version,- provider: cursorRecording.provider,- assets: cursorRecording.assets,- scale: cursorScale,- smoothing: options.cursor?.smoothing,- motionBlur: options.cursor?.motionBlur,- clickBounce: options.cursor?.clickBounce,- clipToBounds: options.cursor?.clipToBounds,- theme: options.cursor?.theme,- }- : null;-- // --- Webcam (global layout/style, read from legacyEditor exactly as the- // legacy exporter does; per-segment source lives on segment.camera) ---- const webcam: RenderPlanWebcam = {- layoutPreset: extractLegacyField<string>(- legacy,- "webcamLayoutPreset",- "picture-in-picture",- ) as WebcamLayoutPreset,- maskShape: extractLegacyField<string>(- legacy,- "webcamMaskShape",- "rectangle",- ) as WebcamMaskShape,- mirrored: extractLegacyField(legacy, "webcamMirrored", false),- reactiveZoom: extractLegacyField(legacy, "webcamReactiveZoom", true),- sizePreset: extractLegacyField(legacy, "webcamSizePreset", 25),- position: extractLegacyField<{ cx: number; cy: number } | null>(legacy, "webcamPosition", null),- };-- return {- output: {- width: settings.width,- height: settings.height,- frameRate,- bitrate: settings.bitrate,- codec: CODEC_STRINGS[codec],- },- aspectRatioValue,- segments,- zoomRegions,- annotationRegions,- speedRegions,- appearance,- cursor,- webcam,- };-}--function isIdentityCrop(region: CropRegion): boolean {- return region.x === 0 && region.y === 0 && region.width === 1 && region.height === 1;-}--// ponytail: when the only segment needs no re-encode-worthy effects AND the-// output frame is the source frame (1:1, no aspect re-framing, no scaling),-// the renderer can take a stream-copy fast path (remux-only) instead of a-// full decode → composite → encode round trip.-export function isIdentityFastPathEligible(plan: RenderPlan): boolean {- if (plan.segments.length !== 1) return false;- const segment = plan.segments[0];- if (segment.intraTrims.length !== 0) return false;- if (!isIdentityCrop(segment.cropRegion)) return false;- if (plan.zoomRegions.length !== 0) return false;- if (plan.annotationRegions.length !== 0) return false;- // An active cursor overlay composites pixels → no stream-copy.- if (plan.cursor && segment.cursorSamples.length > 0) return false;-- for (const region of plan.speedRegions) {- const duration = region.endMs - region.startMs;- if (duration > 0.0001 && Math.abs(region.speed - 1) > 0.0001) {- return false;- }- }-- if (plan.output.width !== segment.sourceWidth) return false;- if (plan.output.height !== segment.sourceHeight) return false;-- return true;-}diff --git a/src/lib/ai-edition/store/zoomSuggestions.test.ts b/src/lib/ai-edition/store/zoomSuggestions.test.tsdeleted file mode 100644index 294d2dc48..000000000--- a/src/lib/ai-edition/store/zoomSuggestions.test.ts+++ /dev/null@@ -1,116 +0,0 @@-import { describe, expect, it } from "vitest";-import { type AxcutDocument, createEmptyDocument, documentSchema } from "../schema";-import { suggestZoomRegions } from "./zoomSuggestions";--function fixtureDocument(overrides: Partial<AxcutDocument> = {}): AxcutDocument {- const base = createEmptyDocument({ title: "Test", projectId: "proj_zoom" });- return documentSchema.parse({- ...base,- project: { ...base.project, primaryAssetId: "asset_1" },- assets: [- {- id: "asset_1",- kind: "video",- label: "Recording",- originalPath: "C:/videos/rec.mp4",- durationSec: 60,- },- ],- transcripts: [- {- assetId: "asset_1",- language: "en",- segments: [- // Long speech — should produce a suggestion.- { id: "seg_1", kind: "speech", startSec: 0, endSec: 10, text: "Intro…", wordIds: [] },- // Silence — ignored.- { id: "seg_2", kind: "silence", startSec: 10, endSec: 20, text: "", wordIds: [] },- // Too short — ignored.- { id: "seg_3", kind: "speech", startSec: 20, endSec: 22, text: "Uh", wordIds: [] },- // Long speech — second suggestion.- {- id: "seg_4",- kind: "speech",- startSec: 30,- endSec: 40,- text: "Deep dive…",- wordIds: [],- },- ],- words: [],- },- ],- timeline: {- ...base.timeline,- clips: [- {- id: "clip_1",- assetId: "asset_1",- sourceStartSec: 0,- sourceEndSec: 60,- timelineStartSec: 0,- timelineEndSec: 60,- wordRefs: [],- origin: "user",- reason: "",- },- ],- },- ...overrides,- });-}--describe("suggestZoomRegions", () => {- it("proposes auto zoom regions over sustained speech segments", () => {- const suggestions = suggestZoomRegions(fixtureDocument());- expect(suggestions).toHaveLength(2);- expect(suggestions[0]).toMatchObject({- depth: 2,- focusMode: "auto",- source: "auto",- });- // Padded 0.4s inside the 0–10s segment, mapped 1:1 (single full clip).- expect(suggestions[0].startMs).toBe(400);- expect(suggestions[0].endMs).toBe(9600);- expect(suggestions[1].startMs).toBe(30400);- });-- it("skips segments that overlap existing zoom ranges", () => {- const doc = fixtureDocument();- const withZoom = {- ...doc,- zoomRanges: [- {- id: "zoom_existing",- startMs: 0,- endMs: 12000,- depth: 3 as const,- focus: { cx: 0.5, cy: 0.5 },- },- ] as AxcutDocument["zoomRanges"],- };- const suggestions = suggestZoomRegions(withZoom);- expect(suggestions).toHaveLength(1);- expect(suggestions[0].startMs).toBe(30400);- });-- it("returns nothing without a transcript", () => {- const doc = { ...fixtureDocument(), transcripts: [], transcript: null };- expect(suggestZoomRegions(doc)).toEqual([]);- });-- it("skips speech that was cut out of the timeline", () => {- const doc = fixtureDocument();- // Timeline keeps only 0–20s of source: the 30–40s speech is gone.- const trimmed = {- ...doc,- timeline: {- ...doc.timeline,- clips: [{ ...doc.timeline.clips[0], sourceEndSec: 20, timelineEndSec: 20 }],- },- };- const suggestions = suggestZoomRegions(trimmed);- expect(suggestions).toHaveLength(1);- expect(suggestions[0].startMs).toBe(400);- });-});diff --git a/src/lib/ai-edition/store/zoomSuggestions.ts b/src/lib/ai-edition/store/zoomSuggestions.tsdeleted file mode 100644index 83090b098..000000000--- a/src/lib/ai-edition/store/zoomSuggestions.ts+++ /dev/null@@ -1,71 +0,0 @@-// F2.1 — auto-zoom "wand" suggestions. Scans the transcript for sustained-// speech segments (the silence heuristic in reverse: anything the transcriber-// didn't mark as silence is where the speaker is explaining something) and-// proposes zoom regions covering them. Pure — the Bottombar Magic button-// applies the result via saveDocument.--import { createId } from "../document/ids";-import type { AxcutDocument, AxcutZoomRegion } from "../schema";-import { locateSourcePosition } from "../timeline/virtual-preview";--// A speech segment must run at least this long to justify a zoom-in.-const MIN_SPEECH_SEC = 4;-// Don't flood the timeline — the user can re-run after accepting/deleting.-const MAX_SUGGESTIONS = 6;-// Trim the zoom slightly inside the segment so the zoom-in lands after the-// speaker starts and releases before they stop.-const EDGE_PADDING_SEC = 0.4;--function overlapsExisting(- startMs: number,- endMs: number,- existing: Array<{ startMs: number; endMs: number }>,-): boolean {- return existing.some((z) => startMs < z.endMs && endMs > z.startMs);-}--export function suggestZoomRegions(document: AxcutDocument): AxcutZoomRegion[] {- const primaryAssetId = document.project.primaryAssetId ?? document.assets[0]?.id;- if (!primaryAssetId) return [];- const transcript =- document.transcripts.find((t) => t.assetId === primaryAssetId) ??- (document.transcript?.assetId === primaryAssetId ? document.transcript : null);- if (!transcript) return [];-- const clips = document.timeline.clips;- const suggestions: AxcutZoomRegion[] = [];- const occupied: Array<{ startMs: number; endMs: number }> = document.zoomRanges.map((z) => ({- startMs: z.startMs,- endMs: z.endMs,- }));-- for (const segment of transcript.segments) {- if (suggestions.length >= MAX_SUGGESTIONS) break;- if (segment.kind !== "speech") continue;- if (segment.endSec - segment.startSec < MIN_SPEECH_SEC) continue;-- // Map source time → timeline time through the clip layout; segments- // that were cut out of the timeline are skipped entirely.- const start = locateSourcePosition(clips, segment.startSec + EDGE_PADDING_SEC, primaryAssetId);- const end = locateSourcePosition(clips, segment.endSec - EDGE_PADDING_SEC, primaryAssetId);- if (!start || !end) continue;- const startMs = Math.round(start.virtualTimeSec * 1000);- const endMs = Math.round(end.virtualTimeSec * 1000);- if (endMs - startMs < (MIN_SPEECH_SEC - 2 * EDGE_PADDING_SEC) * 1000) continue;- if (overlapsExisting(startMs, endMs, occupied)) continue;-- const region: AxcutZoomRegion = {- id: createId("zoom"),- startMs,- endMs,- depth: 2,- focus: { cx: 0.5, cy: 0.5 },- focusMode: "auto",- source: "auto",- };- suggestions.push(region);- occupied.push({ startMs, endMs });- }-- return suggestions;-}diff --git a/src/lib/exporter/asyncVideoFrameQueue.ts b/src/lib/exporter/asyncVideoFrameQueue.tsdeleted file mode 100644index 4cab19181..000000000--- a/src/lib/exporter/asyncVideoFrameQueue.ts+++ /dev/null@@ -1,77 +0,0 @@-type PendingConsumer = {- resolve: (frame: VideoFrame | null) => void;- reject: (error: Error) => void;-};--export class AsyncVideoFrameQueue {- private frames: VideoFrame[] = [];- private consumers: PendingConsumer[] = [];- private error: Error | null = null;- private closed = false;-- get length() {- return this.frames.length;- }-- enqueue(frame: VideoFrame) {- if (this.closed) {- frame.close();- return;- }-- const consumer = this.consumers.shift();- if (consumer) {- consumer.resolve(frame);- return;- }-- this.frames.push(frame);- }-- fail(error: Error) {- this.error = error;- this.closed = true;- const consumers = this.consumers.splice(0);- for (const consumer of consumers) {- consumer.reject(error);- }- for (const frame of this.frames) {- frame.close();- }- this.frames = [];- }-- close() {- this.closed = true;- const consumers = this.consumers.splice(0);- for (const consumer of consumers) {- consumer.resolve(null);- }- }-- async dequeue(): Promise<VideoFrame | null> {- if (this.error) {- throw this.error;- }-- if (this.frames.length > 0) {- return this.frames.shift() ?? null;- }-- if (this.closed) {- return null;- }-- return await new Promise<VideoFrame | null>((resolve, reject) => {- this.consumers.push({ resolve, reject });- });- }-- destroy() {- this.close();- for (const frame of this.frames) {- frame.close();- }- this.frames = [];- }-}diff --git a/src/lib/exporter/audioEncoder.test.ts b/src/lib/exporter/audioEncoder.test.tsdeleted file mode 100644index 0fb3708c5..000000000--- a/src/lib/exporter/audioEncoder.test.ts+++ /dev/null@@ -1,72 +0,0 @@-import { afterEach, describe, expect, it, vi } from "vitest";-import { AudioProcessor, downmixPlanarChannelsForExport } from "./audioEncoder";--describe("AudioProcessor.selectSupportedExportCodec", () => {- afterEach(() => {- vi.unstubAllGlobals();- });-- it("falls back to stereo when the source channel count cannot be encoded", async () => {- const isConfigSupported = vi.fn(async (config: AudioEncoderConfig) => ({- config,- supported:- config.codec === "mp4a.40.2" &&- config.sampleRate === 44100 &&- config.numberOfChannels === 2,- }));- vi.stubGlobal("AudioEncoder", { isConfigSupported });-- const codec = await AudioProcessor.selectSupportedExportCodec(44100, 8);-- expect(codec).toMatchObject({- encoderCodec: "mp4a.40.2",- muxerCodec: "aac",- sampleRate: 44100,- numberOfChannels: 2,- });- expect(isConfigSupported).toHaveBeenCalledWith({- codec: "mp4a.40.2",- sampleRate: 44100,- numberOfChannels: 8,- bitrate: 128000,- });- expect(isConfigSupported).toHaveBeenCalledWith({- codec: "mp4a.40.2",- sampleRate: 44100,- numberOfChannels: 2,- bitrate: 128000,- });- });-});--describe("downmixPlanarChannelsForExport", () => {- it("preserves non-front Windows system audio channels when exporting stereo", () => {- const sourcePlanes = Array.from({ length: 8 }, (_, channel) => {- const plane = new Float32Array(2);- if (channel === 2) {- plane[0] = 0.8;- plane[1] = 0.4;- }- if (channel === 6) {- plane[0] = 0.2;- plane[1] = 0.1;- }- return plane;- });-- const stereo = downmixPlanarChannelsForExport(sourcePlanes, 2);-- expect(stereo[0]).toBeGreaterThan(0);- expect(stereo[1]).toBeGreaterThan(0);- expect(stereo[2]).toBeGreaterThan(0);- expect(stereo[3]).toBeGreaterThan(0);- });-- it("duplicates mono microphone audio when exporting stereo", () => {- const mono = new Float32Array([0.25, -0.5]);-- const stereo = downmixPlanarChannelsForExport([mono], 2);-- expect(Array.from(stereo)).toEqual([0.25, -0.5, 0.25, -0.5]);- });-});diff --git a/src/lib/exporter/audioEncoder.ts b/src/lib/exporter/audioEncoder.tsdeleted file mode 100644index 506f21c17..000000000--- a/src/lib/exporter/audioEncoder.ts+++ /dev/null@@ -1,1227 +0,0 @@-import { WebDemuxer } from "web-demuxer";-import {- MAX_NATIVE_PLAYBACK_RATE,- type SpeedRegion,- type TrimRegion,-} from "@/components/video-editor/types";-import { WsolaTimeStretcher } from "./audioTimeStretch";-import type { ExportAudioMuxerCodec, VideoMuxer } from "./muxer";-import { PlanarChunkQueue } from "./planarChunkQueue";-import {- buildSpeedSegments,- maxTimelineSpeed,- type SpeedTimelineSegment,-} from "./timelineSegments";--const AUDIO_BITRATE = 128_000;-const DECODE_BACKPRESSURE_LIMIT = 20;-const MIN_SPEED_REGION_DELTA_MS = 0.0001;-const SEEK_TIMEOUT_MS = 5_000;-// AudioData slice size fed to the encoder from the offline time-stretch path.-const OFFLINE_OUTPUT_FRAMES = 4096;-const ENCODE_BACKPRESSURE_LIMIT = 20;-// Must match streamingDecoder's EPSILON_SEC so the offline audio segment lengths-// use the same per-frame quantization as the video output.-const VIDEO_EPSILON_SEC = 0.001;--export interface ExportAudioCodec {- encoderCodec: string;- muxerCodec: ExportAudioMuxerCodec;- label: string;- sampleRate: number;- numberOfChannels: number;-}--type ExportAudioCodecCandidate = Omit<ExportAudioCodec, "sampleRate" | "numberOfChannels">;--const EXPORT_AUDIO_CODECS: ExportAudioCodecCandidate[] = [- { encoderCodec: "mp4a.40.2", muxerCodec: "aac", label: "AAC" },- { encoderCodec: "opus", muxerCodec: "opus", label: "Opus" },-];--function averageChannels(sourcePlanes: Float32Array[], frame: number) {- let mixed = 0;- for (const plane of sourcePlanes) {- mixed += plane[frame] ?? 0;- }- return mixed / Math.max(1, sourcePlanes.length);-}--function weightedSample(- sourcePlanes: Float32Array[],- frame: number,- weights: Array<[channel: number, weight: number]>,-) {- let mixed = 0;- let weightSum = 0;- for (const [channel, weight] of weights) {- const sample = sourcePlanes[channel]?.[frame];- if (typeof sample !== "number") {- continue;- }- mixed += sample * weight;- weightSum += weight;- }- return weightSum > 0 ? mixed / weightSum : averageChannels(sourcePlanes, frame);-}--function getStereoDownmixWeights(sourceChannels: number) {- const centerWeight = Math.SQRT1_2;- const surroundWeight = Math.SQRT1_2;- const lfeWeight = 0.5;-- if (sourceChannels >= 8) {- // Windows 7.1 order: FL, FR, FC, LFE, BL, BR, SL, SR.- return {- left: [- [0, 1],- [2, centerWeight],- [3, lfeWeight],- [4, surroundWeight],- [6, surroundWeight],- ] satisfies Array<[number, number]>,- right: [- [1, 1],- [2, centerWeight],- [3, lfeWeight],- [5, surroundWeight],- [7, surroundWeight],- ] satisfies Array<[number, number]>,- };- }-- if (sourceChannels >= 6) {- // Windows 5.1 order: FL, FR, FC, LFE, BL, BR.- return {- left: [- [0, 1],- [2, centerWeight],- [3, lfeWeight],- [4, surroundWeight],- ] satisfies Array<[number, number]>,- right: [- [1, 1],- [2, centerWeight],- [3, lfeWeight],- [5, surroundWeight],- ] satisfies Array<[number, number]>,- };- }-- if (sourceChannels >= 4) {- return {- left: [- [0, 1],- [2, surroundWeight],- ] satisfies Array<[number, number]>,- right: [- [1, 1],- [3, surroundWeight],- ] satisfies Array<[number, number]>,- };- }-- return {- left: [- [0, 1],- [2, centerWeight],- ] satisfies Array<[number, number]>,- right: [- [1, 1],- [2, centerWeight],- ] satisfies Array<[number, number]>,- };-}--export function downmixPlanarChannelsForExport(- sourcePlanes: Float32Array[],- targetChannels: number,-): Float32Array {- const frameCount = sourcePlanes[0]?.length ?? 0;- const output = new Float32Array(frameCount * targetChannels);-- if (targetChannels === 1) {- for (let frame = 0; frame < frameCount; frame++) {- output[frame] = averageChannels(sourcePlanes, frame);- }- return output;- }-- if (targetChannels !== 2) {- throw new Error(`Unsupported target channel count: ${targetChannels}`);- }-- if (sourcePlanes.length === 1) {- output.set(sourcePlanes[0], 0);- output.set(sourcePlanes[0], frameCount);- return output;- }-- if (sourcePlanes.length === 2) {- output.set(sourcePlanes[0], 0);- output.set(sourcePlanes[1], frameCount);- return output;- }-- const weights = getStereoDownmixWeights(sourcePlanes.length);- for (let frame = 0; frame < frameCount; frame++) {- output[frame] = weightedSample(sourcePlanes, frame, weights.left);- output[frameCount + frame] = weightedSample(sourcePlanes, frame, weights.right);- }- return output;-}--export class AudioProcessor {- private cancelled = false;-- static async selectSupportedExportCodec(- sampleRate: number,- numberOfChannels: number,- ): Promise<ExportAudioCodec | null> {- const channelOptions = [numberOfChannels];- if (numberOfChannels > 2) {- channelOptions.push(2);- }-- if (!channelOptions.includes(1)) {- channelOptions.push(1);- }-- for (const codec of EXPORT_AUDIO_CODECS) {- for (const channels of channelOptions) {- const support = await AudioEncoder.isConfigSupported({- codec: codec.encoderCodec,- sampleRate,- numberOfChannels: channels,- bitrate: AUDIO_BITRATE,- });- if (support.supported) {- return { ...codec, sampleRate, numberOfChannels: channels };- }- }- }-- return null;- }-- static async selectSupportedExportCodecForSource(- demuxer: WebDemuxer,- ): Promise<ExportAudioCodec | null> {- let audioConfig: AudioDecoderConfig;- try {- audioConfig = await demuxer.getDecoderConfig("audio");- } catch {- return null;- }-- const codecCheck = await AudioDecoder.isConfigSupported(audioConfig);- if (!codecCheck.supported) {- console.warn("[AudioProcessor] Audio codec not supported:", audioConfig.codec);- return null;- }-- return AudioProcessor.selectSupportedExportCodec(- audioConfig.sampleRate || 48000,- audioConfig.numberOfChannels || 2,- );- }-- /**- * Two modes: no speed regions uses the fast WebCodecs trim-only pipeline; speed- * regions use the pitch-preserving rendered timeline pipeline.- */- async process(- demuxer: WebDemuxer,- muxer: VideoMuxer,- videoUrl: string,- trimRegions: TrimRegion[] | undefined,- speedRegions: SpeedRegion[] | undefined,- validatedDurationSec: number,- exportCodec: ExportAudioCodec,- targetFrameRate: number,- ): Promise<void> {- const sortedTrims = trimRegions ? [...trimRegions].sort((a, b) => a.startMs - b.startMs) : [];- const sortedSpeedRegions = speedRegions- ? [...speedRegions]- .filter((region) => region.endMs - region.startMs > MIN_SPEED_REGION_DELTA_MS)- .sort((a, b) => a.startMs - b.startMs)- : [];-- // Speed edits need pitch preservation. Segments at or below the native- // playbackRate cap use the real-time <audio> capture (proven, sounds best);- // anything faster can't be played in real time, so the whole timeline is- // rendered offline with a WSOLA time-stretch instead.- if (sortedSpeedRegions.length > 0) {- const segments = buildSpeedSegments(validatedDurationSec, sortedTrims, sortedSpeedRegions);-- if (maxTimelineSpeed(segments) > MAX_NATIVE_PLAYBACK_RATE) {- await this.renderOfflineTimelineAudio(- demuxer,- muxer,- segments,- exportCodec,- targetFrameRate,- );- return;- }-- const renderedAudioBlob = await this.renderPitchPreservedTimelineAudio(- videoUrl,- sortedTrims,- sortedSpeedRegions,- validatedDurationSec,- );- if (!this.cancelled && renderedAudioBlob.size > 0) {- await this.muxRenderedAudioBlob(renderedAudioBlob, muxer, exportCodec);- return;- }- return;- }-- // No speed edits: demux/decode/encode with trim timestamp remap. The +0.5s mirrors- // streamingDecoder.decodeAll's read window so both paths read the same distance past- // the validated duration boundary.- const readEndSec = validatedDurationSec + 0.5;- await this.processTrimOnlyAudio(demuxer, muxer, sortedTrims, readEndSec, exportCodec);- }-- // Trim-only path, used for projects without speed regions.- private async processTrimOnlyAudio(- demuxer: WebDemuxer,- muxer: VideoMuxer,- sortedTrims: TrimRegion[],- readEndSec?: number,- exportCodec?: ExportAudioCodec,- ): Promise<void> {- let audioConfig: AudioDecoderConfig;- try {- audioConfig = await demuxer.getDecoderConfig("audio");- } catch {- console.warn("[AudioProcessor] No audio track found, skipping");- return;- }-- const codecCheck = await AudioDecoder.isConfigSupported(audioConfig);- if (!codecCheck.supported) {- console.warn("[AudioProcessor] Audio codec not supported:", audioConfig.codec);- return;- }-- // Phase 1: decode, skipping trimmed regions.- const decodedFrames: AudioData[] = [];-- const decoder = new AudioDecoder({- output: (data: AudioData) => decodedFrames.push(data),- error: (e: DOMException) => console.error("[AudioProcessor] Decode error:", e),- });- decoder.configure(audioConfig);-- const safeReadEndSec =- typeof readEndSec === "number" && Number.isFinite(readEndSec)- ? Math.max(0, readEndSec)- : undefined;- const audioStream =- safeReadEndSec !== undefined- ? demuxer.read("audio", 0, safeReadEndSec)- : demuxer.read("audio");- const reader = audioStream.getReader();-- try {- while (!this.cancelled) {- const { done, value: chunk } = await reader.read();- if (done || !chunk) break;-- const timestampMs = chunk.timestamp / 1000;- if (this.isInTrimRegion(timestampMs, sortedTrims)) continue;-- decoder.decode(chunk);-- while (decoder.decodeQueueSize > DECODE_BACKPRESSURE_LIMIT && !this.cancelled) {- await new Promise((resolve) => setTimeout(resolve, 1));- }- }- } finally {- try {- await reader.cancel();- } catch {- /* reader already closed */- }- }-- if (decoder.state === "configured") {- await decoder.flush();- decoder.close();- }-- if (this.cancelled || decodedFrames.length === 0) {- for (const frame of decodedFrames) frame.close();- return;- }-- // Phase 2: re-encode with timestamps adjusted for trim gaps.- const encodedChunks: { chunk: EncodedAudioChunk; meta?: EncodedAudioChunkMetadata }[] = [];-- const encoder = new AudioEncoder({- output: (chunk: EncodedAudioChunk, meta?: EncodedAudioChunkMetadata) => {- encodedChunks.push({ chunk, meta });- },- error: (e: DOMException) => console.error("[AudioProcessor] Encode error:", e),- });-- const sampleRate = audioConfig.sampleRate || 48000;- const channels = audioConfig.numberOfChannels || 2;- const selectedCodec =- exportCodec ?? (await AudioProcessor.selectSupportedExportCodec(sampleRate, channels));- if (!selectedCodec) {- console.warn("[AudioProcessor] No supported audio export codec, skipping audio");- for (const frame of decodedFrames) frame.close();- return;- }-- const outputSampleRate = selectedCodec.sampleRate || sampleRate;- const outputChannels = selectedCodec.numberOfChannels || channels;- const encodeConfig: AudioEncoderConfig = {- codec: selectedCodec.encoderCodec,- sampleRate: outputSampleRate,- numberOfChannels: outputChannels,- bitrate: AUDIO_BITRATE,- };-- const encodeSupport = await AudioEncoder.isConfigSupported(encodeConfig);- if (!encodeSupport.supported) {- console.warn(- `[AudioProcessor] ${selectedCodec.label} encoding not supported, skipping audio`,- );- for (const frame of decodedFrames) frame.close();- return;- }-- encoder.configure(encodeConfig);-- for (const audioData of decodedFrames) {- if (this.cancelled) {- audioData.close();- continue;- }-- const timestampMs = audioData.timestamp / 1000;- const trimOffsetMs = this.computeTrimOffset(timestampMs, sortedTrims);- const adjustedTimestampUs = audioData.timestamp - trimOffsetMs * 1000;-- const adjusted = this.cloneForEncoding(- audioData,- Math.max(0, adjustedTimestampUs),- outputChannels,- );- audioData.close();-- encoder.encode(adjusted);- adjusted.close();- }-- if (encoder.state === "configured") {- await encoder.flush();- encoder.close();- }-- // Phase 3: flush encoded chunks to muxer.- for (const { chunk, meta } of encodedChunks) {- if (this.cancelled) break;- await muxer.addAudioChunk(chunk, meta);- }-- console.log(- `[AudioProcessor] Processed ${decodedFrames.length} audio frames, encoded ${encodedChunks.length} chunks`,- );- }-- // Speed-aware path mirroring preview semantics (trim skipping + playbackRate). Relies on- // browser media playback to preserve pitch and avoid the chipmunk effect.- private async renderPitchPreservedTimelineAudio(- videoUrl: string,- trimRegions: TrimRegion[],- speedRegions: SpeedRegion[],- validatedDurationSec: number,- ): Promise<Blob> {- const media = document.createElement("audio");- media.src = videoUrl;- media.preload = "auto";-- const pitchMedia = media as HTMLMediaElement & {- preservesPitch?: boolean;- mozPreservesPitch?: boolean;- webkitPreservesPitch?: boolean;- };- pitchMedia.preservesPitch = true;- pitchMedia.mozPreservesPitch = true;- pitchMedia.webkitPreservesPitch = true;-- await this.waitForLoadedMetadata(media);- if (this.cancelled) {- throw new Error("Export cancelled");- }-- const audioContext = new AudioContext();- const sourceNode = audioContext.createMediaElementSource(media);- const destinationNode = audioContext.createMediaStreamDestination();- sourceNode.connect(destinationNode);-- let rafId: number | null = null;- let recorder: MediaRecorder | null = null;- let recordedBlobPromise: Promise<Blob> | null = null;-- try {- if (audioContext.state === "suspended") {- await audioContext.resume();- }-- // Skip initial trim region(s) before recording so the first rAF frames don't- // capture trimmed audio. Loops to handle back-to-back/overlapping trims at t=0.- const effectiveEnd = validatedDurationSec;- let startPosition = 0;- for (let i = 0; i <= trimRegions.length; i++) {- const activeTrim = this.findActiveTrimRegion(startPosition * 1000, trimRegions);- if (!activeTrim) break;- startPosition = activeTrim.endMs / 1000;- if (startPosition >= effectiveEnd) break;- }-- if (startPosition >= effectiveEnd) {- // Everything is trimmed; return a silent blob.- return new Blob([], { type: "audio/webm" });- }-- await this.seekTo(media, startPosition);-- // Set initial playback rate for the starting position.- const initialSpeedRegion = this.findActiveSpeedRegion(startPosition * 1000, speedRegions);- if (initialSpeedRegion) {- media.playbackRate = initialSpeedRegion.speed;- }-- // Start recording only after seeking past trims.- const recording = this.startAudioRecording(destinationNode.stream);- recorder = recording.recorder;- recordedBlobPromise = recording.recordedBlobPromise;- await media.play();-- await new Promise<void>((resolve, reject) => {- const cleanup = () => {- if (rafId !== null) {- cancelAnimationFrame(rafId);- rafId = null;- }- media.removeEventListener("error", onError);- media.removeEventListener("ended", onEnded);- };-- const onError = () => {- cleanup();- reject(new Error("Failed while rendering speed-adjusted audio timeline"));- };-- const onEnded = () => {- cleanup();- resolve();- };-- const tick = () => {- if (this.cancelled) {- cleanup();- resolve();- return;- }-- // Stop at validated duration; media.duration can be inflated by bad- // container metadata.- if (media.currentTime >= validatedDurationSec) {- media.pause();- cleanup();- resolve();- return;- }-- const currentTimeMs = media.currentTime * 1000;- const activeTrimRegion = this.findActiveTrimRegion(currentTimeMs, trimRegions);-- if (activeTrimRegion && !media.paused && !media.ended) {- const skipToTime = activeTrimRegion.endMs / 1000;- if (skipToTime >= media.duration || skipToTime >= validatedDurationSec) {- media.pause();- cleanup();- resolve();- return;- }- // Pause recording during the seek so we don't capture silence/noise.- media.pause();- if (recorder?.state === "recording") recorder.pause();- const onSeeked = () => {- clearTimeout(seekTimer);- if (this.cancelled) {- cleanup();- resolve();- return;- }- if (recorder?.state === "paused") recorder.resume();- media- .play()- .then(() => {- if (!this.cancelled) rafId = requestAnimationFrame(tick);- })- .catch((err) => {- cleanup();- reject(- new Error(- `Failed to resume playback after trim seek: ${err instanceof Error ? err.message : String(err)}`,- ),- );- });- };- const seekTimer = window.setTimeout(() => {- media.removeEventListener("seeked", onSeeked);- cleanup();- reject(new Error("Audio seek timed out while skipping trim region"));- }, SEEK_TIMEOUT_MS);- media.addEventListener("seeked", onSeeked, { once: true });- media.currentTime = skipToTime;- return;- }-- const activeSpeedRegion = this.findActiveSpeedRegion(currentTimeMs, speedRegions);- const playbackRate = activeSpeedRegion ? activeSpeedRegion.speed : 1;- if (Math.abs(media.playbackRate - playbackRate) > 0.0001) {- media.playbackRate = playbackRate;- }-- if (!media.paused && !media.ended) {- rafId = requestAnimationFrame(tick);- } else {- cleanup();- resolve();- }- };-- media.addEventListener("error", onError, { once: true });- media.addEventListener("ended", onEnded, { once: true });- rafId = requestAnimationFrame(tick);- });- } finally {- if (rafId !== null) {- cancelAnimationFrame(rafId);- }- media.pause();- if (recorder && recorder.state !== "inactive") {- recorder.stop();- }- destinationNode.stream.getTracks().forEach((track) => track.stop());- sourceNode.disconnect();- destinationNode.disconnect();- await audioContext.close();- media.src = "";- media.load();- }-- if (!recordedBlobPromise) {- // Either an early return fired or startAudioRecording set this before playback- // resolved. Reaching here means that broke; fail loud rather than return silence.- throw new Error("Audio recorder finished without assigning recordedBlobPromise");- }- const recordedBlob = await recordedBlobPromise;- if (this.cancelled) {- throw new Error("Export cancelled");- }- return recordedBlob;- }-- /**- * Offline pitch-preserved timeline audio for projects that contain a segment- * faster than the native playbackRate cap (which the real-time capture path- * can't reach). Streams the source once, routes each frame's PCM into the- * active timeline segment, applies a WSOLA time-stretch per segment, and- * encodes the result — clamping each segment to its exact expected length so- * the audio stays locked to the (independently retimed) video.- */- private async renderOfflineTimelineAudio(- demuxer: WebDemuxer,- muxer: VideoMuxer,- segments: SpeedTimelineSegment[],- exportCodec: ExportAudioCodec,- targetFrameRate: number,- ): Promise<void> {- let audioConfig: AudioDecoderConfig;- try {- audioConfig = await demuxer.getDecoderConfig("audio");- } catch {- console.warn("[AudioProcessor] No audio track found, skipping");- return;- }-- const codecCheck = await AudioDecoder.isConfigSupported(audioConfig);- if (!codecCheck.supported) {- console.warn("[AudioProcessor] Audio codec not supported:", audioConfig.codec);- return;- }-- const sampleRate = audioConfig.sampleRate || 48000;- const outputChannels = exportCodec.numberOfChannels || audioConfig.numberOfChannels || 2;- const outputSampleRate = exportCodec.sampleRate || sampleRate;-- const encodeConfig: AudioEncoderConfig = {- codec: exportCodec.encoderCodec,- sampleRate: outputSampleRate,- numberOfChannels: outputChannels,- bitrate: AUDIO_BITRATE,- };- const encodeSupport = await AudioEncoder.isConfigSupported(encodeConfig);- if (!encodeSupport.supported) {- console.warn(`[AudioProcessor] ${exportCodec.label} encoding not supported, skipping audio`);- return;- }-- const encodedChunks: { chunk: EncodedAudioChunk; meta?: EncodedAudioChunkMetadata }[] = [];- const encoder = new AudioEncoder({- output: (chunk, meta) => encodedChunks.push({ chunk, meta }),- error: (e: DOMException) => console.error("[AudioProcessor] Encode error:", e),- });- encoder.configure(encodeConfig);-- // Output-side accumulator: a chunk queue (O(1) append, front-drained) coalesced- // into fixed-size AudioData slices with running (monotonic) output timestamps.- const outQueue = new PlanarChunkQueue(outputChannels);- let outTimestampSamples = 0;-- const appendOutput = (planes: Float32Array[], count: number) => {- outQueue.push(planes, count);- };-- const flushOutput = (drainAll: boolean) => {- while (outQueue.length >= OFFLINE_OUTPUT_FRAMES || (drainAll && outQueue.length > 0)) {- const take = Math.min(OFFLINE_OUTPUT_FRAMES, outQueue.length);- const data = outQueue.take(take);- const audioData = new AudioData({- format: "f32-planar",- sampleRate: outputSampleRate,- numberOfFrames: take,- numberOfChannels: outputChannels,- timestamp: Math.round((outTimestampSamples / outputSampleRate) * 1_000_000),- data: data.buffer as ArrayBuffer,- });- outTimestampSamples += take;- encoder.encode(audioData);- audioData.close();- }- };-- // Per-segment state.- let segIdx = 0;- let stretcher: WsolaTimeStretcher | null = null;- let segExpectedOut = 0;- let segEmittedOut = 0;-- const startSegment = (seg: SpeedTimelineSegment) => {- // Match the video path's per-segment frame quantization exactly (streamingDecoder- // emits ceil((dur - EPSILON)/speed * fps) frames) so audio and video advance by- // the same amount each segment and never accumulate drift.- const frameCount = Math.ceil(- ((seg.endSec - seg.startSec - VIDEO_EPSILON_SEC) / seg.speed) * targetFrameRate,- );- segExpectedOut = Math.max(0, Math.round((frameCount / targetFrameRate) * outputSampleRate));- segEmittedOut = 0;- stretcher = new WsolaTimeStretcher({- sampleRate,- channels: outputChannels,- speed: seg.speed,- expectedOutputSamples: segExpectedOut,- });- };-- // Clamp each segment's emitted output to its expected length (drops the WSOLA- // tail overshoot; pads with silence on the rare underrun) so cumulative A/V- // timing matches the video the audio is retimed against.- const emitStretched = (planes: Float32Array[]) => {- const produced = planes[0]?.length ?? 0;- const allowed = Math.max(0, segExpectedOut - segEmittedOut);- const take = Math.min(produced, allowed);- appendOutput(planes, take);- segEmittedOut += take;- };-- // Feed `count` source-domain silence samples into the current segment's- // stretcher (compressed by its speed, then clamped/encoded like real audio).- const feedSilence = (count: number) => {- if (!stretcher) return;- let remaining = count;- while (remaining > 0) {- const n = Math.min(8192, remaining);- const silence = Array.from({ length: outputChannels }, () => new Float32Array(n));- emitStretched(stretcher.push(silence));- remaining -= n;- }- };-- const finalizeSegment = () => {- if (!stretcher) return;- emitStretched(stretcher.flush());- // Intentional: pad the deficit with silence when WSOLA under-fills a short- // high-speed segment, so the segment keeps its exact A/V-locked length. Do- // not "fix" this by removing the pad.- if (segEmittedOut < segExpectedOut) {- const pad = segExpectedOut - segEmittedOut;- const silence = Array.from({ length: outputChannels }, () => new Float32Array(pad));- appendOutput(silence, pad);- segEmittedOut += pad;- }- stretcher = null;- };-- const segStartSample = (seg: SpeedTimelineSegment) => Math.round(seg.startSec * sampleRate);- const segEndSample = (seg: SpeedTimelineSegment) => Math.round(seg.endSec * sampleRate);-- const routeFrame = (planes: Float32Array[], frameStartSample: number, frameCount: number) => {- let local = 0;- while (local < frameCount && segIdx < segments.length) {- const seg = segments[segIdx];- const segStart = segStartSample(seg);- const segEnd = segEndSample(seg);- const currentAbs = frameStartSample + local;-- if (currentAbs < segStart) {- // In a trimmed gap (or before the first segment): discard.- local += Math.min(segStart - currentAbs, frameCount - local);- continue;- }- if (currentAbs >= segEnd) {- finalizeSegment();- segIdx += 1;- continue;- }- if (!stretcher) {- startSegment(seg);- // If the very first source sample lands after the timeline origin (codec- // priming, or an audio track that starts after the video), fill the head- // with leading silence so real audio keeps its true source-time position.- // The video path holds its first frame over the same head, so this keeps- // A/V aligned; it is a no-op when the first sample is at 0, and negative- // preroll was already discarded by the `currentAbs < segStart` branch above.- if (segIdx === 0 && currentAbs > segStart) feedSilence(currentAbs - segStart);- }- const take = Math.min(segEnd, frameStartSample + frameCount) - currentAbs;- const slice = planes.map((p) => p.subarray(local, local + take));- emitStretched((stretcher as WsolaTimeStretcher).push(slice));- local += take;- }- };-- // Streaming decode: frames arrive in source order via the decoder callback.- const pending: AudioData[] = [];- const decoder = new AudioDecoder({- output: (data: AudioData) => pending.push(data),- error: (e: DOMException) => console.error("[AudioProcessor] Decode error:", e),- });- decoder.configure(audioConfig);-- const drainPending = async () => {- while (pending.length > 0) {- if (this.cancelled) {- for (const d of pending) d.close();- pending.length = 0;- return;- }- const data = pending.shift();- if (!data) continue;- const frameCount = data.numberOfFrames;- const sourceChannels = data.numberOfChannels;- const srcPlanes: Float32Array[] = [];- for (let c = 0; c < sourceChannels; c++) {- const plane = new Float32Array(frameCount);- data.copyTo(plane, { format: "f32-planar", planeIndex: c });- srcPlanes.push(plane);- }- // Raw source timestamps — the same origin the video decoder uses- // (streamingDecoder), so audio and video stay in one coordinate system.- // Frames before the first segment start (e.g. negative-timestamp codec- // preroll, or a leading trim) are correctly discarded by routeFrame.- const frameStartSample = Math.round((data.timestamp / 1_000_000) * sampleRate);- data.close();-- // Match source channels through untouched; otherwise downmix (to 1 or 2).- let planes: Float32Array[];- if (outputChannels === sourceChannels) {- planes = srcPlanes;- } else {- const downmixed = downmixPlanarChannelsForExport(srcPlanes, outputChannels);- planes = [];- for (let c = 0; c < outputChannels; c++) {- planes.push(downmixed.subarray(c * frameCount, (c + 1) * frameCount));- }- }-- routeFrame(planes, frameStartSample, frameCount);- flushOutput(false);-- while (encoder.encodeQueueSize > ENCODE_BACKPRESSURE_LIMIT && !this.cancelled) {- await new Promise((resolve) => setTimeout(resolve, 1));- }- }- };-- // Read past the last segment's source end (mirrors streamingDecoder's +0.5s- // window so both paths read the same distance past the boundary).- const lastSegmentEndSec = segments.length > 0 ? segments[segments.length - 1].endSec : 0;- const readEndSec = lastSegmentEndSec + 0.5;- const reader = demuxer.read("audio", 0, readEndSec).getReader();- try {- while (!this.cancelled) {- const { done, value: chunk } = await reader.read();- if (done || !chunk) break;- decoder.decode(chunk);- while (decoder.decodeQueueSize > DECODE_BACKPRESSURE_LIMIT && !this.cancelled) {- await new Promise((resolve) => setTimeout(resolve, 1));- }- await drainPending();- }- } finally {- try {- await reader.cancel();- } catch {- /* reader already closed */- }- }-- if (decoder.state === "configured") {- if (!this.cancelled) {- await decoder.flush();- }- decoder.close();- }- await drainPending();-- if (this.cancelled) {- if (encoder.state === "configured") encoder.close();- return;- }-- // Finalize the segment still open at end-of-stream, then pad any segments that- // never received audio (source shorter than the timeline) with silence.- if (stretcher) {- finalizeSegment();- segIdx += 1;- }- for (; segIdx < segments.length; segIdx++) {- startSegment(segments[segIdx]);- finalizeSegment();- }-- flushOutput(true);-- if (encoder.state === "configured") {- await encoder.flush();- encoder.close();- }-- for (const { chunk, meta } of encodedChunks) {- if (this.cancelled) break;- await muxer.addAudioChunk(chunk, meta);- }-- console.log(- `[AudioProcessor] Offline timeline audio: ${segments.length} segments, ${encodedChunks.length} chunks`,- );- }-- // Demux the rendered speed-adjusted blob and feed its chunks into the MP4 muxer.- private async muxRenderedAudioBlob(- blob: Blob,- muxer: VideoMuxer,- exportCodec: ExportAudioCodec,- ): Promise<void> {- if (this.cancelled) return;-- const file = new File([blob], "speed-audio.webm", { type: blob.type || "audio/webm" });- const wasmUrl = new URL("./wasm/web-demuxer.wasm", window.location.href).href;- const demuxer = new WebDemuxer({ wasmFilePath: wasmUrl });-- try {- await demuxer.load(file);- await this.processTrimOnlyAudio(demuxer, muxer, [], undefined, exportCodec);- } finally {- try {- demuxer.destroy();- } catch {- /* ignore */- }- }- }-- private startAudioRecording(stream: MediaStream): {- recorder: MediaRecorder;- recordedBlobPromise: Promise<Blob>;- } {- const mimeType = this.getSupportedAudioMimeType();- const options: MediaRecorderOptions = {- audioBitsPerSecond: AUDIO_BITRATE,- ...(mimeType ? { mimeType } : {}),- };-- const recorder = new MediaRecorder(stream, options);- const chunks: Blob[] = [];-- const recordedBlobPromise = new Promise<Blob>((resolve, reject) => {- recorder.ondataavailable = (event: BlobEvent) => {- if (event.data && event.data.size > 0) {- chunks.push(event.data);- }- };- recorder.onerror = () => {- reject(new Error("MediaRecorder failed while capturing speed-adjusted audio"));- };- recorder.onstop = () => {- const type = mimeType || chunks[0]?.type || "audio/webm";- resolve(new Blob(chunks, { type }));- };- });-- recorder.start();- return { recorder, recordedBlobPromise };- }-- private getSupportedAudioMimeType(): string | undefined {- const candidates = ["audio/webm;codecs=opus", "audio/webm"];- for (const candidate of candidates) {- if (MediaRecorder.isTypeSupported(candidate)) {- return candidate;- }- }- return undefined;- }-- private waitForLoadedMetadata(media: HTMLMediaElement): Promise<void> {- if (Number.isFinite(media.duration) && media.readyState >= HTMLMediaElement.HAVE_METADATA) {- return Promise.resolve();- }-- return new Promise<void>((resolve, reject) => {- const onLoaded = () => {- cleanup();- resolve();- };- const onError = () => {- cleanup();- reject(new Error("Failed to load media metadata for speed-adjusted audio"));- };- const cleanup = () => {- media.removeEventListener("loadedmetadata", onLoaded);- media.removeEventListener("error", onError);- };-- media.addEventListener("loadedmetadata", onLoaded);- media.addEventListener("error", onError, { once: true });- });- }-- private seekTo(media: HTMLMediaElement, targetSec: number): Promise<void> {- if (Math.abs(media.currentTime - targetSec) < 0.0001) {- return Promise.resolve();- }-- return new Promise<void>((resolve, reject) => {- const onSeeked = () => {- cleanup();- resolve();- };- const onError = () => {- cleanup();- reject(new Error("Failed to seek media for speed-adjusted audio"));- };- const cleanup = () => {- media.removeEventListener("seeked", onSeeked);- media.removeEventListener("error", onError);- };-- media.addEventListener("seeked", onSeeked, { once: true });- media.addEventListener("error", onError, { once: true });- media.currentTime = targetSec;- });- }-- private findActiveTrimRegion(- currentTimeMs: number,- trimRegions: TrimRegion[],- ): TrimRegion | null {- return (- trimRegions.find(- (region) => currentTimeMs >= region.startMs && currentTimeMs < region.endMs,- ) || null- );- }-- private findActiveSpeedRegion(- currentTimeMs: number,- speedRegions: SpeedRegion[],- ): SpeedRegion | null {- return (- speedRegions.find(- (region) => currentTimeMs >= region.startMs && currentTimeMs < region.endMs,- ) || null- );- }-- private cloneForEncoding(- src: AudioData,- newTimestamp: number,- targetChannels: number,- ): AudioData {- if (targetChannels !== src.numberOfChannels) {- return this.downmixWithTimestamp(src, newTimestamp, targetChannels);- }-- if (!src.format) {- throw new Error("AudioData format is required for cloning");- }- const isPlanar = src.format.includes("planar");- const numPlanes = isPlanar ? src.numberOfChannels : 1;-- let totalSize = 0;- for (let planeIndex = 0; planeIndex < numPlanes; planeIndex++) {- totalSize += src.allocationSize({ planeIndex });- }-- const buffer = new ArrayBuffer(totalSize);- let offset = 0;- for (let planeIndex = 0; planeIndex < numPlanes; planeIndex++) {- const planeSize = src.allocationSize({ planeIndex });- src.copyTo(new Uint8Array(buffer, offset, planeSize), { planeIndex });- offset += planeSize;- }-- return new AudioData({- format: src.format,- sampleRate: src.sampleRate,- numberOfFrames: src.numberOfFrames,- numberOfChannels: src.numberOfChannels,- timestamp: newTimestamp,- data: buffer,- });- }-- private downmixWithTimestamp(- src: AudioData,- newTimestamp: number,- targetChannels: number,- ): AudioData {- const sourceChannels = src.numberOfChannels;- const frameCount = src.numberOfFrames;- if (targetChannels < 1 || targetChannels > 2) {- throw new Error(`Unsupported target channel count: ${targetChannels}`);- }-- const sourcePlanes = Array.from({ length: sourceChannels }, () => new Float32Array(frameCount));- for (let channel = 0; channel < sourceChannels; channel++) {- src.copyTo(sourcePlanes[channel], {- format: "f32-planar",- planeIndex: channel,- });- }-- const output = downmixPlanarChannelsForExport(sourcePlanes, targetChannels);-- return new AudioData({- format: "f32-planar",- sampleRate: src.sampleRate,- numberOfFrames: frameCount,- numberOfChannels: targetChannels,- timestamp: newTimestamp,- data: output.buffer instanceof ArrayBuffer ? output.buffer : output.slice().buffer,- });- }-- private isInTrimRegion(timestampMs: number, trims: TrimRegion[]): boolean {- return trims.some((trim) => timestampMs >= trim.startMs && timestampMs < trim.endMs);- }-- private computeTrimOffset(timestampMs: number, trims: TrimRegion[]): number {- let offset = 0;- for (const trim of trims) {- if (trim.endMs <= timestampMs) {- offset += trim.endMs - trim.startMs;- }- }- return offset;- }-- /**- * Encodes an already-assembled planar PCM timeline (one Float32Array per- * channel, at `sampleRate`) into `exportCodec` and muxes the chunks. Used by- * the v2 multi-asset segment loop: per-segment audio is decoded, concatenated- * and boundary-faded upstream (audioConcatAssembler), then handed here as one- * continuous buffer — so this method only chops it into encoder-sized frames.- */- async encodePcmToMuxer(- pcm: Float32Array[],- sampleRate: number,- muxer: VideoMuxer,- exportCodec: ExportAudioCodec,- ): Promise<void> {- if (this.cancelled) return;- const channels = pcm.length;- const totalFrames = pcm[0]?.length ?? 0;- if (channels === 0 || totalFrames === 0) return;-- const encodeConfig: AudioEncoderConfig = {- codec: exportCodec.encoderCodec,- sampleRate,- numberOfChannels: channels,- bitrate: AUDIO_BITRATE,- };- const support = await AudioEncoder.isConfigSupported(encodeConfig);- if (!support.supported) {- console.warn(`[AudioProcessor] ${exportCodec.label} encoding not supported, skipping audio`);- return;- }-- const encodedChunks: { chunk: EncodedAudioChunk; meta?: EncodedAudioChunkMetadata }[] = [];- const encoder = new AudioEncoder({- output: (chunk, meta) => encodedChunks.push({ chunk, meta }),- error: (e: DOMException) => console.error("[AudioProcessor] Encode error:", e),- });- encoder.configure(encodeConfig);-- let offset = 0;- while (offset < totalFrames && !this.cancelled) {- const count = Math.min(OFFLINE_OUTPUT_FRAMES, totalFrames - offset);- // f32-planar layout: channel 0's `count` samples, then channel 1's, …- const planar = new Float32Array(count * channels);- for (let c = 0; c < channels; c++) {- planar.set(pcm[c].subarray(offset, offset + count), c * count);- }- const audioData = new AudioData({- format: "f32-planar",- sampleRate,- numberOfFrames: count,- numberOfChannels: channels,- timestamp: Math.round((offset / sampleRate) * 1_000_000),- data: planar.buffer as ArrayBuffer,- });- encoder.encode(audioData);- audioData.close();- offset += count;- while (encoder.encodeQueueSize > ENCODE_BACKPRESSURE_LIMIT && !this.cancelled) {- await new Promise((resolve) => setTimeout(resolve, 1));- }- }-- if (encoder.state === "configured") {- await encoder.flush();- encoder.close();- }- for (const { chunk, meta } of encodedChunks) {- if (this.cancelled) break;- await muxer.addAudioChunk(chunk, meta);- }- console.log(`[AudioProcessor] Segmented audio: ${encodedChunks.length} chunks`);- }-- cancel(): void {- this.cancelled = true;- }-}diff --git a/src/lib/exporter/cropSchedule.ts b/src/lib/exporter/cropSchedule.tsnew file mode 100644index 000000000..b6749ad58--- /dev/null+++ b/src/lib/exporter/cropSchedule.ts@@ -0,0 +1,26 @@+// Per-clip crop lookup, shared by the GIF exporter and the document adapter.+// Lived in videoExporter.ts until the web MP4 path was removed; GIF is the only+// remaining renderer that resolves a crop off a timeline.++import type { CropRegion } from "@/components/video-editor/types";++export interface CropScheduleEntry {+ startSec: number;+ endSec: number;+ cropRegion: CropRegion;+}++/** Finds which clip's crop applies at a given SOURCE-media timestamp — the+ * first schedule entry whose [startSec, endSec) covers it, falling back to+ * `fallback` when the schedule is absent or nothing covers it (e.g. a gap). */+export function resolveCropAt(+ schedule: CropScheduleEntry[] | undefined,+ sourceSec: number,+ fallback: CropRegion,+): CropRegion {+ if (!schedule || schedule.length === 0) return fallback;+ const covering = schedule.find(+ (entry) => sourceSec >= entry.startSec && sourceSec < entry.endSec,+ );+ return covering?.cropRegion ?? fallback;+}diff --git a/src/lib/exporter/gifExporter.ts b/src/lib/exporter/gifExporter.tsindex ce2df298d..dbfb02179 100644--- a/src/lib/exporter/gifExporter.ts+++ b/src/lib/exporter/gifExporter.ts@@ -12,6 +12,7 @@ import type {import { BackgroundLoadError } from "@/lib/wallpaper";import type { CursorRecordingData } from "@/native/contracts";import { getPlatform } from "@/utils/platformUtils";+import { type CropScheduleEntry, resolveCropAt } from "./cropSchedule";import { FrameRenderer } from "./frameRenderer";import { StreamingVideoDecoder } from "./streamingDecoder";import { TimestampedVideoFrameQueue } from "./timestampedVideoFrameQueue";@@ -22,7 +23,6 @@ import type {GifFrameRate,GifSizePreset,} from "./types";-import { type CropScheduleEntry, resolveCropAt } from "./videoExporter";const GIF_WORKER_URL = new URL("gif.js/dist/gif.worker.js", import.meta.url).toString();diff --git a/src/lib/exporter/index.ts b/src/lib/exporter/index.tsindex 9d4f96d6f..33cabd3a6 100644--- a/src/lib/exporter/index.ts+++ b/src/lib/exporter/index.ts@@ -1,3 +1,4 @@+export { type CropScheduleEntry, resolveCropAt } from "./cropSchedule";export { FrameRenderer } from "./frameRenderer";export { calculateOutputDimensions, GifExporter } from "./gifExporter";export {@@ -5,7 +6,6 @@ export {calculateMp4ExportSettings,type Mp4ExportSettings,} from "./mp4ExportSettings";-export { VideoMuxer } from "./muxer";export { StreamingVideoDecoder } from "./streamingDecoder";export type {ExportConfig,@@ -25,5 +25,3 @@ export {isValidGifFrameRate,VALID_GIF_FRAME_RATES,} from "./types";-export { VideoFileDecoder } from "./videoDecoder";-export { type CropScheduleEntry, resolveCropAt, VideoExporter } from "./videoExporter";diff --git a/src/lib/exporter/muxer.ts b/src/lib/exporter/muxer.tsdeleted file mode 100644index 6ac81d9bb..000000000--- a/src/lib/exporter/muxer.ts+++ /dev/null@@ -1,96 +0,0 @@-import {- BufferTarget,- EncodedAudioPacketSource,- EncodedPacket,- EncodedVideoPacketSource,- Mp4OutputFormat,- Output,-} from "mediabunny";-import type { ExportConfig } from "./types";--export type ExportAudioMuxerCodec = "aac" | "opus";--// Map a WebCodecs codec string (e.g. "avc1.640033", "hvc1.1.6.L120.90",-// "vp09.00.10.08") to its codec family.-export function videoCodecFamily(codec: string | undefined): "avc" | "hevc" | "vp9" {- const lower = (codec ?? "").toLowerCase();- if (lower.startsWith("hvc1") || lower.startsWith("hev1")) return "hevc";- if (lower.startsWith("vp09") || lower.startsWith("vp9")) return "vp9";- return "avc";-}--export class VideoMuxer {- private output: Output | null = null;- private videoSource: EncodedVideoPacketSource | null = null;- private audioSource: EncodedAudioPacketSource | null = null;- private hasAudio: boolean;- private target: BufferTarget | null = null;- private config: ExportConfig;- private audioCodec: ExportAudioMuxerCodec;-- constructor(config: ExportConfig, hasAudio = false, audioCodec: ExportAudioMuxerCodec = "aac") {- this.config = config;- this.hasAudio = hasAudio;- this.audioCodec = audioCodec;- }-- async initialize(): Promise<void> {- this.target = new BufferTarget();-- this.output = new Output({- format: new Mp4OutputFormat({- fastStart: "in-memory",- }),- target: this.target,- });-- // Codec details are deduced from the chunk metadata; the family must- // match the encoder codec (F2.4 exposes h264/h265/vp9 in the dialog).- this.videoSource = new EncodedVideoPacketSource(videoCodecFamily(this.config.codec));- this.output.addVideoTrack(this.videoSource, {- frameRate: this.config.frameRate,- });-- if (this.hasAudio) {- this.audioSource = new EncodedAudioPacketSource(this.audioCodec);- this.output.addAudioTrack(this.audioSource);- }-- await this.output.start();- }-- async addVideoChunk(chunk: EncodedVideoChunk, meta?: EncodedVideoChunkMetadata): Promise<void> {- if (!this.videoSource) {- throw new Error("Muxer not initialized");- }-- const packet = EncodedPacket.fromEncodedChunk(chunk);-- await this.videoSource.add(packet, meta);- }-- async addAudioChunk(chunk: EncodedAudioChunk, meta?: EncodedAudioChunkMetadata): Promise<void> {- if (!this.audioSource) {- throw new Error("Audio not configured for this muxer");- }-- const packet = EncodedPacket.fromEncodedChunk(chunk);-- await this.audioSource.add(packet, meta);- }-- async finalize(): Promise<Blob> {- if (!this.output || !this.target) {- throw new Error("Muxer not initialized");- }-- await this.output.finalize();- const buffer = this.target.buffer;-- if (!buffer) {- throw new Error("Failed to finalize output");- }-- return new Blob([buffer], { type: "video/mp4" });- }-}diff --git a/src/lib/exporter/nativeFrameSink.test.ts b/src/lib/exporter/nativeFrameSink.test.tsdeleted file mode 100644index 1a1d66a73..000000000--- a/src/lib/exporter/nativeFrameSink.test.ts+++ /dev/null@@ -1,202 +0,0 @@-import { describe, expect, it } from "vitest";-import { CREDIT_WINDOW, NativeFrameSink, type NativeSinkApi } from "./nativeFrameSink";--/**- * A stand-in for the main process: records frames, and only acks when told to,- * so a test can hold the window full and observe the sender blocking.- */-function fakeMain(over: Partial<NativeSinkApi> = {}) {- let ack: ((sessionId: string, error: string | null) => void) | null = null;- const state = {- frames: [] as number[],- pending: [] as number[],- finished: false,- cancelled: false,- unsubscribed: false,- listenerAtFirstFrame: null as boolean | null,- };- const api: NativeSinkApi = {- exportStart: async () => ({ sessionId: "s1", encoder: "h264_amf" }),- exportWriteFrame: (_id, frame) => {- state.listenerAtFirstFrame ??= ack !== null;- state.frames.push(frame.byteLength);- state.pending.push(frame.byteLength);- },- exportOnFrameAck: (cb) => {- ack = cb;- return () => {- state.unsubscribed = true;- };- },- exportFinish: async () => {- state.finished = true;- return { outputPath: "/tmp/out.mp4" };- },- exportCancel: async () => {- state.cancelled = true;- },- ...over,- };- /** Ack `n` frames as the main process would, one message each. */- const flush = (n = state.pending.length, error: string | null = null) => {- for (let i = 0; i < n; i++) {- state.pending.shift();- ack?.("s1", error);- }- };- /** Deliver an ack exactly as the main process would, for any session id. */- const ackAs = (sessionId: string, error: string | null = null) => ack?.(sessionId, error);- return { api, state, flush, ackAs };-}--const OPTS = {- outputPath: "/tmp/out.mp4",- width: 1920,- height: 1080,- frameRate: 60,- bitrate: 8_000_000,- pixelFormat: "nv12" as const,-};--/** Lets pending microtasks settle so a blocked write() can be observed as blocked. */-const settle = () => new Promise((r) => setTimeout(r, 0));--describe("NativeFrameSink", () => {- it("subscribes to acks before the first frame can be sent", async () => {- const { api, state } = fakeMain();- const sink = await NativeFrameSink.start(OPTS, api);- await sink.write(new ArrayBuffer(16));- // If the listener were registered after the first send, an ack arriving- // promptly would be dropped and the window would never refill.- expect(state.listenerAtFirstFrame).toBe(true);- });-- it("keeps exactly CREDIT_WINDOW frames in flight and blocks the next one", async () => {- const { api, state, flush } = fakeMain();- const sink = await NativeFrameSink.start(OPTS, api);-- for (let i = 0; i < CREDIT_WINDOW; i++) await sink.write(new ArrayBuffer(1));- expect(state.frames.length).toBe(CREDIT_WINDOW);-- let sent = false;- const blocked = sink.write(new ArrayBuffer(1)).then(() => {- sent = true;- });- await settle();- // The window is full: this write must not have gone out.- expect(sent).toBe(false);- expect(state.frames.length).toBe(CREDIT_WINDOW);-- flush(1);- await blocked;- expect(state.frames.length).toBe(CREDIT_WINDOW + 1);- });-- it("does not block below the window — the whole point over stop-and-wait", async () => {- const { api, state } = fakeMain();- const sink = await NativeFrameSink.start(OPTS, api);- // No acks at all: the first CREDIT_WINDOW writes must still all resolve.- for (let i = 0; i < CREDIT_WINDOW; i++) await sink.write(new ArrayBuffer(1));- expect(state.frames.length).toBe(CREDIT_WINDOW);- });-- it("ignores acks addressed to another session", async () => {- const { api, state, ackAs } = fakeMain();- const sink = await NativeFrameSink.start(OPTS, api);- for (let i = 0; i < CREDIT_WINDOW; i++) await sink.write(new ArrayBuffer(1));-- let sent = false;- void sink.write(new ArrayBuffer(1)).then(() => {- sent = true;- });- // The ack channel is renderer-wide. A concurrent export's ack must not hand- // us a credit we did not earn, or we would overrun our own window.- ackAs("some-other-session");- await settle();- expect(sent).toBe(false);- expect(state.frames.length).toBe(CREDIT_WINDOW);-- // Our own ack still works, proving the guard is on the id, not on everything.- ackAs("s1");- await settle();- expect(sent).toBe(true);- });-- it("drains every in-flight frame before finishing", async () => {- const { api, state, flush } = fakeMain();- const sink = await NativeFrameSink.start(OPTS, api);- for (let i = 0; i < 3; i++) await sink.write(new ArrayBuffer(1));-- let done = false;- const finishing = sink.finish().then((r) => {- done = true;- return r;- });- await settle();- // Finishing with frames still in flight would close ffmpeg's stdin early- // and truncate the file.- expect(done).toBe(false);- expect(state.finished).toBe(false);-- flush();- await expect(finishing).resolves.toEqual({ outputPath: "/tmp/out.mp4" });- expect(state.finished).toBe(true);- });-- it("finishes immediately when nothing is in flight", async () => {- const { api } = fakeMain();- const sink = await NativeFrameSink.start(OPTS, api);- await expect(sink.finish()).resolves.toEqual({ outputPath: "/tmp/out.mp4" });- });-- it("unsubscribes from the ack channel on finish", async () => {- const { api, state } = fakeMain();- const sink = await NativeFrameSink.start(OPTS, api);- await sink.finish();- expect(state.unsubscribed).toBe(true);- });-- it("surfaces an ffmpeg write failure to the writer rather than hanging", async () => {- const { api, flush } = fakeMain();- const sink = await NativeFrameSink.start(OPTS, api);- for (let i = 0; i < CREDIT_WINDOW; i++) await sink.write(new ArrayBuffer(1));-- const blocked = sink.write(new ArrayBuffer(1));- flush(1, "ffmpeg exited: Cannot load nvcuda.dll");- // The parked write must reject, not resume: ffmpeg is gone.- await expect(blocked).rejects.toThrow(/nvcuda/);- });-- it("reports the ffmpeg failure from finish() instead of the file it never wrote", async () => {- const { api, state, flush } = fakeMain();- const sink = await NativeFrameSink.start(OPTS, api);- await sink.write(new ArrayBuffer(1));- flush(1, "ffmpeg died");- await expect(sink.finish()).rejects.toThrow(/ffmpeg died/);- // A dead session must be cancelled, not finished — finishing waits on a- // process that will never exit cleanly.- expect(state.finished).toBe(false);- expect(state.cancelled).toBe(true);- });-- it("cancel() releases a writer parked on a credit that will never arrive", async () => {- const { api, state } = fakeMain();- const sink = await NativeFrameSink.start(OPTS, api);- for (let i = 0; i < CREDIT_WINDOW; i++) await sink.write(new ArrayBuffer(1));-- const blocked = sink.write(new ArrayBuffer(1));- await sink.cancel();- // Without the wake in cancel(), this write would hang forever and the- // export loop would never unwind.- await expect(blocked).rejects.toThrow(/closed/);- expect(state.cancelled).toBe(true);- expect(state.unsubscribed).toBe(true);- });-- it("is idempotent on cancel", async () => {- const { api } = fakeMain();- const sink = await NativeFrameSink.start(OPTS, api);- await sink.cancel();- await expect(sink.cancel()).resolves.toBeUndefined();- });-});diff --git a/src/lib/exporter/nativeFrameSink.ts b/src/lib/exporter/nativeFrameSink.tsdeleted file mode 100644index eb8b675d5..000000000--- a/src/lib/exporter/nativeFrameSink.ts+++ /dev/null@@ -1,124 +0,0 @@-/**- * Renderer side of the native export encoder: ships composited frames to the- * main process, which feeds them to ffmpeg's stdin.- *- * Flow control is a credit window rather than stop-and-wait. Waiting for each- * frame's ack before sending the next leaves the crossing idle for a full- * round-trip per frame; keeping N frames in flight measured +56%. The window- * saturates at 8 (32 adds nothing), because the crossing is bandwidth-bound —- * IPC structured-clones every frame — not round-trip-bound.- */--/** Frames in flight. Measured: 8 saturates the crossing, 32 buys nothing. */-export const CREDIT_WINDOW = 8;--export interface NativeSinkApi {- exportStart: (req: unknown) => Promise<{- sessionId: string;- encoder: string;- outputPath: string;- }>;- exportWriteFrame: (sessionId: string, frame: ArrayBuffer) => void;- exportOnFrameAck: (cb: (sessionId: string, error: string | null) => void) => () => void;- exportFinish: (sessionId: string) => Promise<{ outputPath: string }>;- exportCancel: (sessionId: string) => Promise<void>;-}--export interface NativeSinkOptions {- /** Omitted: main writes to a temp file and reports the path back. */- outputPath?: string;- width: number;- height: number;- frameRate: number;- bitrate: number;- pixelFormat: "nv12" | "bgra" | "rgba";-}--export class NativeFrameSink {- private inFlight = 0;- private waiters: Array<() => void> = [];- private failure: Error | null = null;- private unsubscribe: (() => void) | null = null;- private closed = false;-- private constructor(- private readonly api: NativeSinkApi,- private readonly sessionId: string,- readonly encoder: string,- readonly outputPath: string,- ) {}-- static async start(opts: NativeSinkOptions, api: NativeSinkApi): Promise<NativeFrameSink> {- const { sessionId, encoder, outputPath } = await api.exportStart(opts);- const sink = new NativeFrameSink(api, sessionId, encoder, outputPath);- // Subscribe before any frame goes out: an ack for frame 0 must not race the- // listener's registration, or the window never refills.- sink.unsubscribe = api.exportOnFrameAck((id, error) => sink.onAck(id, error));- return sink;- }-- private onAck(sessionId: string, error: string | null): void {- // One renderer-wide ack channel: ignore other sessions' traffic.- if (sessionId !== this.sessionId) return;- if (error) this.failure ??= new Error(error);- this.inFlight--;- this.wake();- }-- /** Resolve every waiter and let each re-check its own condition. */- private wake(): void {- const waiters = this.waiters;- this.waiters = [];- for (const resolve of waiters) resolve();- }-- private block(): Promise<void> {- return new Promise<void>((resolve) => this.waiters.push(resolve));- }-- /**- * Ships one frame, blocking while the window is full.- *- * The buffer is handed to IPC, which copies it — the caller may reuse it as- * soon as this returns.- */- async write(frame: ArrayBuffer): Promise<void> {- if (this.failure) throw this.failure;- if (this.closed) throw new Error("Export sink is closed");- while (this.inFlight >= CREDIT_WINDOW) {- await this.block();- if (this.failure) throw this.failure;- if (this.closed) throw new Error("Export sink is closed");- }- this.inFlight++;- this.api.exportWriteFrame(this.sessionId, frame);- }-- /** Waits for every in-flight frame to land, then closes ffmpeg's stdin. */- async finish(): Promise<{ outputPath: string }> {- if (this.closed) throw new Error("Export sink is closed");- while (this.inFlight > 0 && !this.failure) {- await this.block();- }- this.closed = true;- this.unsubscribe?.();- this.unsubscribe = null;- // ffmpeg is already dying on its own; surface why rather than the timeout- // that finishing a broken session would produce.- if (this.failure) {- await this.api.exportCancel(this.sessionId).catch(() => undefined);- throw this.failure;- }- return this.api.exportFinish(this.sessionId);- }-- async cancel(): Promise<void> {- if (this.closed) return;- this.closed = true;- this.unsubscribe?.();- this.unsubscribe = null;- // Unblock anything parked on a credit: no further ack is coming.- this.wake();- await this.api.exportCancel(this.sessionId).catch(() => undefined);- }-}diff --git a/src/lib/exporter/perfTimings.test.ts b/src/lib/exporter/perfTimings.test.tsdeleted file mode 100644index 9af186859..000000000--- a/src/lib/exporter/perfTimings.test.ts+++ /dev/null@@ -1,174 +0,0 @@-import { describe, expect, it } from "vitest";-import { StageTimings } from "./perfTimings";--function fakeClock() {- let t = 0;- return {- now: () => t,- tick: (ms: number) => {- t += ms;- },- };-}--describe("StageTimings — record + snapshot", () => {- it("accumulates totals, counts, averages, and shares", () => {- const clock = fakeClock();- const timings = new StageTimings(clock.now);- timings.record("decode", 10);- timings.record("render", 30);- timings.record("decode", 20);-- const snapshot = timings.snapshot();- expect(snapshot.totalMs).toBe(60);- expect(snapshot.stages.decode.totalMs).toBe(30);- expect(snapshot.stages.decode.count).toBe(2);- expect(snapshot.stages.decode.avgMs).toBe(15);- expect(snapshot.stages.decode.pct).toBe(50);- expect(snapshot.stages.render.totalMs).toBe(30);- expect(snapshot.stages.render.count).toBe(1);- expect(snapshot.stages.render.avgMs).toBe(30);- expect(snapshot.stages.render.pct).toBe(50);- expect(Object.values(snapshot.stages).reduce((sum, stat) => sum + stat.pct, 0)).toBeCloseTo(- 100,- );- });-- it("preserves first-seen order in snapshots and summaries", () => {- const clock = fakeClock();- const timings = new StageTimings(clock.now);- timings.record("render", 2);- timings.record("decode-wait", 1);- timings.record("render", 3);- timings.record("encode-wait", 4);-- expect(Object.keys(timings.snapshot().stages)).toEqual([- "render",- "decode-wait",- "encode-wait",- ]);-- const rows = timings- .formatSummary()- .split("\n")- .filter(- (line) =>- line.startsWith("render") ||- line.startsWith("decode-wait") ||- line.startsWith("encode-wait"),- );- expect(rows.map((row) => row.trimStart().split(/\s+/)[0])).toEqual([- "render",- "decode-wait",- "encode-wait",- ]);- });-});--describe("StageTimings — injected-clock helpers", () => {- it("records a start/stop duration once", () => {- const clock = fakeClock();- const timings = new StageTimings(clock.now);- const stop = timings.start("x");- clock.tick(10);- stop();- stop();-- expect(timings.snapshot().stages.x).toEqual({ totalMs: 10, count: 1, avgMs: 10, pct: 100 });- });-- it("times a synchronous function and returns its result", () => {- const clock = fakeClock();- const timings = new StageTimings(clock.now);- const result = timings.time("x", () => {- clock.tick(12);- return 42;- });-- expect(result).toBe(42);- expect(timings.snapshot().stages.x.totalMs).toBe(12);- });-- it("times an async function and returns its resolved value", async () => {- const clock = fakeClock();- const timings = new StageTimings(clock.now);- const result = await timings.timeAsync("x", async () => {- clock.tick(18);- return "done";- });-- expect(result).toBe("done");- expect(timings.snapshot().stages.x).toEqual({ totalMs: 18, count: 1, avgMs: 18, pct: 100 });- });-- it("records async elapsed time when the function rejects and re-throws", async () => {- const clock = fakeClock();- const timings = new StageTimings(clock.now);- const error = new Error("failed");-- await expect(- timings.timeAsync("reject", async () => {- clock.tick(7);- throw error;- }),- ).rejects.toBe(error);-- expect(timings.snapshot().stages.reject).toEqual({ totalMs: 7, count: 1, avgMs: 7, pct: 100 });- });-});--describe("StageTimings — invalid and empty samples", () => {- it.each([- ["negative", -1],- ["NaN", Number.NaN],- ["Infinity", Number.POSITIVE_INFINITY],- ])("ignores a %s duration without creating a sample", (_name, duration) => {- const clock = fakeClock();- const timings = new StageTimings(clock.now);- timings.record("bad", duration);-- expect(timings.snapshot()).toEqual({ stages: {}, totalMs: 0 });- });-- it("reports zero averages and shares for empty timings and a zero-duration sample", () => {- const clock = fakeClock();- const timings = new StageTimings(clock.now);- expect(timings.snapshot()).toEqual({ stages: {}, totalMs: 0 });-- timings.record("zero", 0);- expect(timings.snapshot().stages.zero).toEqual({ totalMs: 0, count: 1, avgMs: 0, pct: 0 });- });-});--describe("StageTimings — formatSummary and reset", () => {- it("formats stage rows, a total, effective fps, and hardware acceleration", () => {- const clock = fakeClock();- const timings = new StageTimings(clock.now);- timings.record("decode-wait", 10);- timings.record("render", 10);-- const summary = timings.formatSummary({ frames: 10, hardwareAcceleration: "prefer-hardware" });- expect(summary).toContain("decode-wait");- expect(summary).toContain("render");- expect(summary).toContain("TOTAL");- expect(summary).toContain("fps: 500.0");- expect(summary).toContain("hwAccel: prefer-hardware");- });-- it("uses n/a for fps when total time is zero", () => {- const clock = fakeClock();- const timings = new StageTimings(clock.now);- timings.record("zero", 0);-- expect(timings.formatSummary({ frames: 10 })).toContain("fps: n/a");- });-- it("clears all accumulated timing data", () => {- const clock = fakeClock();- const timings = new StageTimings(clock.now);- timings.record("x", 25);- timings.reset();-- expect(timings.snapshot()).toEqual({ stages: {}, totalMs: 0 });- });-});diff --git a/src/lib/exporter/perfTimings.ts b/src/lib/exporter/perfTimings.tsdeleted file mode 100644index 7bf46049b..000000000--- a/src/lib/exporter/perfTimings.ts+++ /dev/null@@ -1,138 +0,0 @@-// StageTimings: pure-logic per-stage timing accumulation for the v2 export-// performance harness. Callers provide measured durations or wrap work with an-// injected clock; this module does not time export work or touch browser APIs.--export interface StageStat {- totalMs: number; // summed elapsed across all record()/stop() calls for this stage- count: number; // number of samples- avgMs: number; // totalMs / count (0 when count === 0)- pct: number; // totalMs / grandTotalMs * 100 (0 when grandTotal === 0)-}--export interface PerfSnapshot {- stages: Record<string, StageStat>; // keyed by stage name, in FIRST-SEEN order- totalMs: number; // sum of every stage's totalMs-}--interface MutableStageStat {- totalMs: number;- count: number;-}--const defaultNow =- typeof performance !== "undefined" && typeof performance.now === "function"- ? () => performance.now()- : () => Date.now();--export class StageTimings {- private readonly now: () => number;-- private readonly stats = new Map<string, MutableStageStat>();-- constructor(now: () => number = defaultNow) {- this.now = now;- }-- record(stage: string, ms: number): void {- if (!Number.isFinite(ms) || ms < 0) {- // Invalid durations are skipped so they do not create a misleading sample.- return;- }-- const stat = this.stats.get(stage);- if (stat) {- stat.totalMs += ms;- stat.count += 1;- return;- }-- this.stats.set(stage, { totalMs: ms, count: 1 });- }-- start(stage: string): () => void {- const startedAt = this.now();- let stopped = false;-- return () => {- if (stopped) {- return;- }- stopped = true;- this.record(stage, Math.max(0, this.now() - startedAt));- };- }-- time<T>(stage: string, fn: () => T): T {- const stop = this.start(stage);- try {- return fn();- } finally {- stop();- }- }-- async timeAsync<T>(stage: string, fn: () => Promise<T>): Promise<T> {- const stop = this.start(stage);- try {- return await fn();- } finally {- stop();- }- }-- snapshot(): PerfSnapshot {- let totalMs = 0;- for (const stat of this.stats.values()) {- totalMs += stat.totalMs;- }-- const stages: Record<string, StageStat> = {};- for (const [stage, stat] of this.stats) {- stages[stage] = {- totalMs: stat.totalMs,- count: stat.count,- avgMs: stat.count === 0 ? 0 : stat.totalMs / stat.count,- pct: totalMs === 0 ? 0 : (stat.totalMs / totalMs) * 100,- };- }-- return { stages, totalMs };- }-- formatSummary(opts: { frames?: number; hardwareAcceleration?: string } = {}): string {- const snapshot = this.snapshot();- const lines = ["stage totalMs pct avgMs count"];-- for (const [stage, stat] of Object.entries(snapshot.stages)) {- lines.push(- `${stage} ${stat.totalMs.toFixed(1).padStart(9)} ${stat.pct- .toFixed(1)- .padStart(5)}% ${stat.avgMs.toFixed(2).padStart(7)} n=${stat.count}`,- );- }-- const totalCount = Object.values(snapshot.stages).reduce((sum, stat) => sum + stat.count, 0);- const totalAvgMs = totalCount === 0 ? 0 : snapshot.totalMs / totalCount;- const totalPct = snapshot.totalMs === 0 ? 0 : 100;- lines.push(- `TOTAL ${snapshot.totalMs.toFixed(1).padStart(9)} ${totalPct- .toFixed(1)- .padStart(5)}% ${totalAvgMs.toFixed(2).padStart(7)} n=${totalCount}`,- );-- if (opts.frames !== undefined) {- const fps =- snapshot.totalMs === 0 ? "n/a" : (opts.frames / (snapshot.totalMs / 1000)).toFixed(1);- lines.push(`fps: ${fps}`);- }- if (opts.hardwareAcceleration !== undefined) {- lines.push(`hwAccel: ${opts.hardwareAcceleration}`);- }-- return lines.join("\n");- }-- reset(): void {- this.stats.clear();- }-}diff --git a/src/lib/exporter/planarChunkQueue.test.ts b/src/lib/exporter/planarChunkQueue.test.tsdeleted file mode 100644index b1da7a407..000000000--- a/src/lib/exporter/planarChunkQueue.test.ts+++ /dev/null@@ -1,83 +0,0 @@-import { describe, expect, it } from "vitest";-import { PlanarChunkQueue } from "./planarChunkQueue";--function ramp(from: number, count: number): Float32Array {- const a = new Float32Array(count);- for (let i = 0; i < count; i++) a[i] = from + i;- return a;-}--describe("PlanarChunkQueue", () => {- it("tracks buffered length across pushes and takes", () => {- const q = new PlanarChunkQueue(1);- expect(q.length).toBe(0);- q.push([ramp(0, 10)], 10);- q.push([ramp(10, 5)], 5);- expect(q.length).toBe(15);- q.take(6);- expect(q.length).toBe(9);- });-- it("drains samples in FIFO order across chunk boundaries (mono)", () => {- const q = new PlanarChunkQueue(1);- q.push([ramp(0, 4)], 4); // 0..3- q.push([ramp(4, 4)], 4); // 4..7- q.push([ramp(8, 4)], 4); // 8..11- // A take that spans multiple chunks and stops mid-chunk.- expect(Array.from(q.take(5))).toEqual([0, 1, 2, 3, 4]);- expect(Array.from(q.take(5))).toEqual([5, 6, 7, 8, 9]);- expect(Array.from(q.take(2))).toEqual([10, 11]);- expect(q.length).toBe(0);- });-- it("keeps channels separate and lays them out planar [ch0…, ch1…]", () => {- const q = new PlanarChunkQueue(2);- q.push([ramp(0, 3), ramp(100, 3)], 3); // L:0,1,2 R:100,101,102- q.push([ramp(3, 3), ramp(103, 3)], 3); // L:3,4,5 R:103,104,105- const out = q.take(4);- // First 4 = left, next 4 = right.- expect(Array.from(out.subarray(0, 4))).toEqual([0, 1, 2, 3]);- expect(Array.from(out.subarray(4, 8))).toEqual([100, 101, 102, 103]);- expect(q.length).toBe(2);- const rest = q.take(2);- expect(Array.from(rest.subarray(0, 2))).toEqual([4, 5]);- expect(Array.from(rest.subarray(2, 4))).toEqual([104, 105]);- });-- it("honors a partial chunk consumed by an earlier take before dropping it", () => {- const q = new PlanarChunkQueue(1);- q.push([ramp(0, 10)], 10);- expect(Array.from(q.take(3))).toEqual([0, 1, 2]); // leaves headOffset=3 in chunk 0- q.push([ramp(10, 3)], 3);- expect(Array.from(q.take(9))).toEqual([3, 4, 5, 6, 7, 8, 9, 10, 11]);- expect(q.length).toBe(1);- expect(Array.from(q.take(1))).toEqual([12]);- });-- it("ignores non-positive pushes/takes", () => {- const q = new PlanarChunkQueue(1);- q.push([ramp(0, 5)], 0);- expect(q.length).toBe(0);- expect(Array.from(q.take(0))).toEqual([]);- });-- it("reconstructs a long stream fed in odd-sized chunks and drained in fixed slices", () => {- const q = new PlanarChunkQueue(1);- const total = 5000;- let produced = 0;- const collected: number[] = [];- // Feed odd chunk sizes, drain 512 whenever enough is buffered.- for (let chunk = 1; produced < total; chunk++) {- const n = Math.min(chunk, total - produced);- q.push([ramp(produced, n)], n);- produced += n;- while (q.length >= 512) collected.push(...q.take(512));- }- while (q.length > 0) collected.push(...q.take(Math.min(512, q.length)));- expect(collected.length).toBe(total);- expect(collected[0]).toBe(0);- expect(collected[total - 1]).toBe(total - 1);- // Strictly increasing ⇒ no reorder/drop/dupe.- expect(collected.every((v, i) => v === i)).toBe(true);- });-});diff --git a/src/lib/exporter/planarChunkQueue.ts b/src/lib/exporter/planarChunkQueue.tsdeleted file mode 100644index d0d9b4018..000000000--- a/src/lib/exporter/planarChunkQueue.ts+++ /dev/null@@ -1,76 +0,0 @@-// FIFO queue of planar PCM chunks with O(1) amortized append and front-drain.-//-// The offline audio time-stretch path produces output in many small chunks and-// drains fixed-size slices to the encoder. A grow-and-copy accumulator would be-// O(N^2) over a long run; this keeps each chunk by reference and only copies the-// samples that are actually pulled out (O(take) per drain, O(total) overall).--export class PlanarChunkQueue {- private readonly channels: number;- private readonly queue: Float32Array[][];- private headOffset = 0; // consumed samples into queue[*][0] (shared across channels)- private queuedLen = 0;-- constructor(channels: number) {- this.channels = Math.max(1, channels);- this.queue = Array.from({ length: this.channels }, () => []);- }-- /** Samples currently buffered (per channel). */- get length(): number {- return this.queuedLen;- }-- /** Append the first `count` samples of each channel plane (stored by reference). */- push(planes: Float32Array[], count: number): void {- if (count <= 0) return;- for (let c = 0; c < this.channels; c++) {- this.queue[c].push((planes[c] ?? planes[0]).subarray(0, count));- }- this.queuedLen += count;- }-- /**- * Remove `take` samples from the front and return them as one planar buffer laid- * out [ch0 samples…, ch1 samples…, …]. `take` must be ≤ length.- */- take(take: number): Float32Array {- if (take <= 0) return new Float32Array(0);- const data = new Float32Array(take * this.channels);- for (let c = 0; c < this.channels; c++) {- let need = take;- let ci = 0;- let off = this.headOffset;- let dst = c * take;- while (need > 0) {- const chunk = this.queue[c][ci];- const avail = chunk.length - off;- const n = avail < need ? avail : need;- data.set(chunk.subarray(off, off + n), dst);- dst += n;- need -= n;- if (n < avail) {- off += n;- } else {- ci += 1;- off = 0;- }- }- }- // Advance the shared head / drop fully consumed chunks (identical layout per channel).- let remaining = take;- while (remaining > 0) {- const avail = this.queue[0][0].length - this.headOffset;- if (avail <= remaining) {- for (let c = 0; c < this.channels; c++) this.queue[c].shift();- this.headOffset = 0;- remaining -= avail;- } else {- this.headOffset += remaining;- remaining = 0;- }- }- this.queuedLen -= take;- return data;- }-}diff --git a/src/lib/exporter/videoDecoder.ts b/src/lib/exporter/videoDecoder.tsdeleted file mode 100644index 505e94f2e..000000000--- a/src/lib/exporter/videoDecoder.ts+++ /dev/null@@ -1,55 +0,0 @@-export interface DecodedVideoInfo {- width: number;- height: number;- duration: number; // in seconds- frameRate: number;- codec: string;-}--export class VideoFileDecoder {- private info: DecodedVideoInfo | null = null;- private videoElement: HTMLVideoElement | null = null;-- async loadVideo(videoUrl: string): Promise<DecodedVideoInfo> {- this.videoElement = document.createElement("video");- this.videoElement.src = videoUrl;- this.videoElement.preload = "metadata";-- return new Promise((resolve, reject) => {- this.videoElement!.addEventListener("loadedmetadata", () => {- const video = this.videoElement!;-- this.info = {- width: video.videoWidth,- height: video.videoHeight,- duration: video.duration,- frameRate: 60,- codec: "avc1.640033",- };-- resolve(this.info);- });-- this.videoElement!.addEventListener("error", (e) => {- reject(new Error(`Failed to load video: ${e}`));- });- });- }-- /** The underlying video element, used for seeking. */- getVideoElement(): HTMLVideoElement | null {- return this.videoElement;- }-- getInfo(): DecodedVideoInfo | null {- return this.info;- }-- destroy(): void {- if (this.videoElement) {- this.videoElement.pause();- this.videoElement.src = "";- this.videoElement = null;- }- }-}diff --git a/src/lib/exporter/videoExporter.browser.test.ts b/src/lib/exporter/videoExporter.browser.test.tsdeleted file mode 100644index cca896ff8..000000000--- a/src/lib/exporter/videoExporter.browser.test.ts+++ /dev/null@@ -1,86 +0,0 @@-import { describe, expect, it } from "vitest";-import sampleVideoUrl from "../../../tests/fixtures/sample.webm?url";-import { BackgroundLoadError } from "../wallpaper";-import type { ExportProgress } from "./types";-import { VideoExporter } from "./videoExporter";--describe("VideoExporter (real browser)", () => {- it("exports a valid MP4 blob from a real video", async () => {- const progressEvents: ExportProgress[] = [];-- const exporter = new VideoExporter({- videoUrl: sampleVideoUrl,- width: 320,- height: 180,- frameRate: 15,- bitrate: 1_000_000,- wallpaper: "#1a1a2e",- zoomRegions: [],- showShadow: false,- shadowIntensity: 0,- showBlur: false,- cropRegion: { x: 0, y: 0, width: 1, height: 1 },- onProgress: (p) => progressEvents.push(p),- });-- const result = await exporter.export();-- expect(result.success, result.error).toBe(true);- expect(result.blob).toBeInstanceOf(Blob);-- const buf = await result.blob!.arrayBuffer();- const bytes = new Uint8Array(buf);- const ftyp = new TextDecoder().decode(bytes.slice(4, 8));- expect(ftyp).toBe("ftyp");-- expect(result.blob!.size).toBeGreaterThan(1024);-- expect(progressEvents.length).toBeGreaterThan(0);-- const finalizing = progressEvents.filter((p) => p.phase === "finalizing");- expect(finalizing.length).toBeGreaterThan(0);- expect(finalizing.at(-1)!.percentage).toBe(100);- });-- it("exports successfully with an image wallpaper (served by Vite dev server)", async () => {- const exporter = new VideoExporter({- videoUrl: sampleVideoUrl,- width: 320,- height: 180,- frameRate: 15,- bitrate: 1_000_000,- wallpaper: "/wallpapers/wallpaper1.jpg",- zoomRegions: [],- showShadow: false,- shadowIntensity: 0,- showBlur: false,- cropRegion: { x: 0, y: 0, width: 1, height: 1 },- });-- const result = await exporter.export();- expect(result.success, result.error).toBe(true);- expect(result.blob!.size).toBeGreaterThan(1024);- });-- it("throws BackgroundLoadError when wallpaper fails to load (no silent black fallback)", async () => {- const exporter = new VideoExporter({- videoUrl: sampleVideoUrl,- width: 320,- height: 180,- frameRate: 15,- bitrate: 1_000_000,- wallpaper: "/wallpapers/does-not-exist.jpg",- zoomRegions: [],- showShadow: false,- shadowIntensity: 0,- showBlur: false,- cropRegion: { x: 0, y: 0, width: 1, height: 1 },- });-- const rejection = exporter.export();- await expect(rejection).rejects.toBeInstanceOf(BackgroundLoadError);- await expect(rejection).rejects.toMatchObject({- url: expect.stringContaining("does-not-exist"),- });- });-});diff --git a/src/lib/exporter/videoExporter.test.ts b/src/lib/exporter/videoExporter.test.tsdeleted file mode 100644index 61dad9f72..000000000--- a/src/lib/exporter/videoExporter.test.ts+++ /dev/null@@ -1,311 +0,0 @@-import { describe, expect, it, vi } from "vitest";-import {- getSourceCopyFastPathBlockers,- isSourceCopyFastPathEligible,- resolveCropAt,- type VideoExporterConfig,- waitForEncoderQueueSpace,-} from "./videoExporter";--function createConfig(overrides: Partial<VideoExporterConfig> = {}): VideoExporterConfig {- return {- videoUrl: "recording.mp4",- width: 1920,- height: 1080,- frameRate: 60,- bitrate: 30_000_000,- wallpaper: "#000000",- zoomRegions: [],- trimRegions: [],- speedRegions: [],- showShadow: false,- shadowIntensity: 0,- showBlur: false,- cropRegion: { x: 0, y: 0, width: 1, height: 1 },- ...overrides,- };-}--describe("isSourceCopyFastPathEligible", () => {- it("allows a no-op MP4 export at source dimensions", () => {- expect(- isSourceCopyFastPathEligible(createConfig(), {- width: 1920,- height: 1080,- frameRate: 60,- codec: "avc1.640033",- }),- ).toBe(true);- });-- it("rejects a frame rate or codec that differs from the source", () => {- const videoInfo = { width: 1920, height: 1080, frameRate: 60, codec: "avc1.640033" };-- expect(isSourceCopyFastPathEligible(createConfig({ frameRate: 30 }), videoInfo)).toBe(false);- expect(- isSourceCopyFastPathEligible(createConfig({ codec: "hvc1.1.6.L120.90" }), videoInfo),- ).toBe(false);- // A container-rounded rate (59.94 vs the nominal 60) shouldn't force a- // re-encode on its own.- expect(isSourceCopyFastPathEligible(createConfig(), { ...videoInfo, frameRate: 59.94 })).toBe(- true,- );- });-- it("rejects timeline edits and frame-level effects", () => {- const videoInfo = { width: 1920, height: 1080, frameRate: 60, codec: "avc1.640033" };-- expect(- isSourceCopyFastPathEligible(- createConfig({ trimRegions: [{ id: "trim", startMs: 100, endMs: 200 }] }),- videoInfo,- ),- ).toBe(false);- expect(- isSourceCopyFastPathEligible(- createConfig({- speedRegions: [{ id: "speed", startMs: 100, endMs: 200, speed: 1.5 }],- }),- videoInfo,- ),- ).toBe(false);- // A 100× region must also block the copy path (any non-1× speed does), so its- // audio is re-rendered (offline time-stretch) rather than passed through untouched.- expect(- isSourceCopyFastPathEligible(- createConfig({- speedRegions: [{ id: "speed", startMs: 100, endMs: 200, speed: 100 }],- }),- videoInfo,- ),- ).toBe(false);- expect(- isSourceCopyFastPathEligible(- createConfig({- zoomRegions: [- {- id: "zoom",- startMs: 100,- endMs: 200,- depth: 2,- focus: { cx: 0.5, cy: 0.5 },- },- ],- }),- videoInfo,- ),- ).toBe(false);- expect(isSourceCopyFastPathEligible(createConfig({ showBlur: true }), videoInfo)).toBe(false);- });-- it("rejects resizing and overlays", () => {- const videoInfo = { width: 1920, height: 1080, frameRate: 60, codec: "avc1.640033" };-- expect(isSourceCopyFastPathEligible(createConfig({ width: 1280 }), videoInfo)).toBe(false);- expect(- isSourceCopyFastPathEligible(- createConfig({- cursorScale: 2,- }),- videoInfo,- ),- ).toBe(false);- expect(- isSourceCopyFastPathEligible(- createConfig({- cursorScale: 2,- cursorRecordingData: {- version: 2,- provider: "native",- assets: [- {- id: "cursor",- platform: "win32",- imageDataUrl: "data:image/png;base64,AA==",- width: 32,- height: 32,- hotspotX: 0,- hotspotY: 0,- },- ],- samples: [{ timeMs: 0, cx: 0.5, cy: 0.5, visible: true, assetId: "cursor" }],- },- }),- videoInfo,- ),- ).toBe(false);- });-});--describe("getSourceCopyFastPathBlockers", () => {- it("reports the source-size mismatch that blocks copy-only export", () => {- expect(- getSourceCopyFastPathBlockers(createConfig({ height: 1080 }), {- width: 1920,- height: 1032,- frameRate: 60,- codec: "avc1.640033",- }),- ).toContain("output-size 1920x1080 differs from source 1920x1032");- });-- it("blocks the fast path when any clip in the crop schedule has a non-default crop", () => {- const videoInfo = { width: 1920, height: 1080, frameRate: 60, codec: "avc1.640033" };- const blockers = getSourceCopyFastPathBlockers(- createConfig({- cropSchedule: [- { startSec: 0, endSec: 3, cropRegion: { x: 0, y: 0, width: 1, height: 1 } },- { startSec: 3, endSec: 6, cropRegion: { x: 0.25, y: 0.25, width: 0.5, height: 0.5 } },- ],- }),- videoInfo,- );- expect(blockers).toContain("crop is not default");- });-- it("allows the fast path when every clip in the crop schedule is default", () => {- const videoInfo = { width: 1920, height: 1080, frameRate: 60, codec: "avc1.640033" };- const blockers = getSourceCopyFastPathBlockers(- createConfig({- cropSchedule: [- { startSec: 0, endSec: 3, cropRegion: { x: 0, y: 0, width: 1, height: 1 } },- { startSec: 3, endSec: 6, cropRegion: { x: 0, y: 0, width: 1, height: 1 } },- ],- }),- videoInfo,- );- expect(blockers).not.toContain("crop is not default");- });-});--describe("resolveCropAt", () => {- const identity = { x: 0, y: 0, width: 1, height: 1 };- const halfCrop = { x: 0.25, y: 0.25, width: 0.5, height: 0.5 };- const schedule = [- { startSec: 0, endSec: 3, cropRegion: halfCrop },- { startSec: 3, endSec: 6, cropRegion: identity },- ];-- it("picks the schedule entry covering the given source time", () => {- expect(resolveCropAt(schedule, 1.5, identity)).toBe(halfCrop);- expect(resolveCropAt(schedule, 4, identity)).toBe(identity);- });-- it("treats entry end as exclusive so back-to-back clips don't overlap", () => {- expect(resolveCropAt(schedule, 3, identity)).toBe(identity);- });-- it("falls back when nothing covers the timestamp or the schedule is absent", () => {- const fallback = { x: 0.1, y: 0.1, width: 0.8, height: 0.8 };- expect(resolveCropAt(schedule, 10, fallback)).toBe(fallback);- expect(resolveCropAt(undefined, 1.5, fallback)).toBe(fallback);- expect(resolveCropAt([], 1.5, fallback)).toBe(fallback);- });-});--// The original bug measured the timeout from the encoder's last *output* event-// (lastEncoderOutputAt), which went stale while the decoder discarded frames inside-// a trim region. waitForEncoderQueueSpace fixes this by starting the clock fresh on-// each call instead of accepting any such external timestamp — by construction, there-// is no "last output" state to go stale, so that regression can't be reintroduced-// without changing this function's signature.-describe("waitForEncoderQueueSpace", () => {- function fakeClock(start = 0) {- let elapsedMs = start;- return {- now: () => elapsedMs,- sleep: async (ms: number) => {- elapsedMs += ms;- },- };- }-- it("resolves immediately when the queue already has space", async () => {- const clock = fakeClock();- const sleep = vi.fn(clock.sleep);-- await waitForEncoderQueueSpace({- getQueueSize: () => 0,- maxEncodeQueue: 8,- isCancelled: () => false,- encoderPreference: "prefer-hardware",- now: clock.now,- sleep,- });-- expect(sleep).not.toHaveBeenCalled();- });-- it("waits for the queue to drain and then resolves", async () => {- const clock = fakeClock();- let queueSize = 8;- // Queue drains well within the timeout.- const sleep = vi.fn(async (ms: number) => {- await clock.sleep(ms);- queueSize = 0;- });-- await waitForEncoderQueueSpace({- getQueueSize: () => queueSize,- maxEncodeQueue: 8,- isCancelled: () => false,- encoderPreference: "prefer-hardware",- now: clock.now,- sleep,- });-- expect(sleep).toHaveBeenCalledTimes(1);- });-- it("throws a hardware-specific error once the queue stays full past the timeout", async () => {- const clock = fakeClock();-- await expect(- waitForEncoderQueueSpace({- getQueueSize: () => 8,- maxEncodeQueue: 8,- isCancelled: () => false,- encoderPreference: "prefer-hardware",- now: clock.now,- sleep: clock.sleep,- }),- ).rejects.toThrow(- "The hardware video encoder stopped responding. Retrying with a safer encoder.",- );- });-- it("throws a generic error for the software encoder once the queue stays full past the timeout", async () => {- const clock = fakeClock();-- await expect(- waitForEncoderQueueSpace({- getQueueSize: () => 8,- maxEncodeQueue: 8,- isCancelled: () => false,- encoderPreference: "prefer-software",- now: clock.now,- sleep: clock.sleep,- }),- ).rejects.toThrow("The video encoder stopped responding during export.");- });-- it("stops waiting without throwing once cancelled", async () => {- const clock = fakeClock();- let cancelled = false;- const sleep = vi.fn(async (ms: number) => {- await clock.sleep(ms);- cancelled = true;- });-- await expect(- waitForEncoderQueueSpace({- getQueueSize: () => 8,- maxEncodeQueue: 8,- isCancelled: () => cancelled,- encoderPreference: "prefer-hardware",- now: clock.now,- sleep,- }),- ).resolves.toBeUndefined();- });-});diff --git a/src/lib/exporter/videoExporter.ts b/src/lib/exporter/videoExporter.tsdeleted file mode 100644index 484c81a8d..000000000--- a/src/lib/exporter/videoExporter.ts+++ /dev/null@@ -1,2024 +0,0 @@-import type {- AnnotationRegion,- CameraFullscreenRegion,- CropRegion,- SpeedRegion,- TrimRegion,- WebcamLayoutPreset,- WebcamSizePreset,- ZoomRegion,-} from "@/components/video-editor/types";-import { assembleConcatenatedPcm } from "@/lib/ai-edition/exporter/audioConcatAssembler";-import { buildAudioConcatPlan } from "@/lib/ai-edition/exporter/audioConcatPlan";-import type { RenderPlan, RenderSegment } from "@/lib/ai-edition/exporter/renderPlan";-import { BackgroundLoadError } from "@/lib/wallpaper";-import type { CursorRecordingData } from "@/native/contracts";-import { getPlatform } from "@/utils/platformUtils";-import { AudioProcessor, downmixPlanarChannelsForExport } from "./audioEncoder";-import { WsolaTimeStretcher } from "./audioTimeStretch";-import { CanvasFrameExtractor } from "./frameExtract";-import { FrameRenderer } from "./frameRenderer";-import { materializeLocalSourceFile, releaseLocalSourceFile } from "./localSourceFile";-import { VideoMuxer, videoCodecFamily } from "./muxer";-import { NativeFrameSink, type NativeSinkApi } from "./nativeFrameSink";-import { StageTimings } from "./perfTimings";-import { MAX_IN_MEMORY_SOURCE_BYTES } from "./sourceFileLimits";-import { StreamingVideoDecoder } from "./streamingDecoder";-import { computeKeepSegments, splitBySpeed } from "./timelineSegments";-import { TimestampedVideoFrameQueue } from "./timestampedVideoFrameQueue";-import type { ExportConfig, ExportProgress, ExportResult } from "./types";-import { WgslFrameRenderer } from "./wgslFrameRenderer";--const ENCODER_STALL_TIMEOUT_MS = 15_000;-const ENCODER_FLUSH_TIMEOUT_MS = 20_000;--/**- * Waits for the encoder's queue to drain below maxEncodeQueue before returning.- *- * The stall timer starts fresh on each call (not from the encoder's last output), so a- * long gap before this call — e.g. the decoder discarding frames inside a trim region —- * doesn't get blamed on the encoder once real frames resume.- */-export async function waitForEncoderQueueSpace(params: {- getQueueSize: () => number;- maxEncodeQueue: number;- isCancelled: () => boolean;- encoderPreference: HardwareAcceleration;- now?: () => number;- sleep?: (ms: number) => Promise<void>;-}): Promise<void> {- const now = params.now ?? Date.now;- const sleep = params.sleep ?? ((ms: number) => new Promise((resolve) => setTimeout(resolve, ms)));-- const stallWaitStartAt = now();- while (params.getQueueSize() >= params.maxEncodeQueue && !params.isCancelled()) {- if (now() - stallWaitStartAt > ENCODER_STALL_TIMEOUT_MS) {- throw new Error(- params.encoderPreference === "prefer-hardware"- ? "The hardware video encoder stopped responding. Retrying with a safer encoder."- : "The video encoder stopped responding during export.",- );- }- await sleep(5);- }-}--// D4 diagnostic: measure the ENCODER ALONE (synthetic frames, no decode/render)-// to separate platform encoder throughput from our pipeline's feeding path.-// Temporary — flip off/remove once the bottleneck is identified.-const ENCODER_PROBE = false;--/**- * Route frames to the bundled native ffmpeg instead of WebCodecs.- *- * Read at runtime, from localStorage, ON PURPOSE: it lets one app session export- * the same timeline both ways, so the A/B compares two runs that share a source,- * a plan, a machine and a thermal state. A build-time constant would compare two- * different sessions and invite us to believe the difference.- *- * localStorage.setItem("openscreen.nativeEncode", "1")- *- * Temporary scaffold: WebCodecs goes away once the numbers are in.- */-function nativeEncodeEnabled(): boolean {- try {- return localStorage.getItem("openscreen.nativeEncode") === "1";- } catch {- return false;- }-}--/**- * Diagnostic: extract every frame to RAM, then throw it away. Writes no file.- *- * Pairs with compositeOnly, and the PAIR is the point: this arm is that one plus- * a full copyTo(), so the difference between them is what the descent actually- * costs. Measured: 0.03 ms/frame — nothing.- *- * That result bounds every "remove the crossing" proposal at once (option A'- * sandbox:false, shared memory, a transferable Electron won't transfer) without- * building any of them — but not for the reason this arm was built. It was built- * to price the descent; it proved there is nothing there to price, and that the- * 32 seconds previously blamed on readback were the compositor finishing its GPU- * work at the first stage that forced a sync.- *- * See technical-documentation/architecture/export-pipeline.md- *- * localStorage.setItem("openscreen.dropFrames", "1")- */-function dropFramesEnabled(): boolean {- try {- return localStorage.getItem("openscreen.dropFrames") === "1";- } catch {- return false;- }-}--/**- * Diagnostic: decode and composite every frame, then stop. No extract, no- * encode, no file.- *- * Prices the GPU compositing of the REAL effect set — the number the whole- * native-core case rests on. The `render` stage reads 1.7 ms/frame, but- * renderFrame is async: it returns before the GPU is done, so that figure may be- * charging someone else for the work. Here nothing downstream can absorb it, so- * the wall is the compositor's own throughput.- *- * Combined with the measured GPU decode+encode floor (234 fps with no- * compositing), this bounds a native GPU pipeline without building one:- * an architecture that composites on-device cannot beat decode + THIS + encode.- *- * localStorage.setItem("openscreen.compositeOnly", "1")- */-function compositeOnlyEnabled(): boolean {- try {- return localStorage.getItem("openscreen.compositeOnly") === "1";- } catch {- return false;- }-}--/**- * Gate G0 — technical-documentation/engineering/rendering-performance.md- *- * Force the GPU to FINISH compositing before the encode timers start, in a- * `fence` stage of its own. If §7.1 is right, `encodeWait` collapses to the- * encoder's own time and the difference reappears under `fence`; if it does- * not, the architecture document's premise is wrong and work on it stops.- *- * The fence serialises compositor and encoder (no overlap), so it perturbs the- * wall it measures: this is a measurement arm, never a shipping default.- *- * localStorage.setItem("openscreen.gpuFence", "1")- */-function gpuFenceEnabled(): boolean {- try {- return localStorage.getItem("openscreen.gpuFence") === "1";- } catch {- return false;- }-}--/**- * The §8b compositor: one WGSL program instead of Pixi + four Canvas2D surfaces- * + a second GL context.- *- * POC (rendering-architecture.md Step 4). It renders no captions, annotations,- * cursor or 3D rotation yet — so its OUTPUT is not yet the product's, and it must- * never become a default by accident. It shares the exporter's decode, encode,- * mux and audio, so the bench can run it against the Canvas2D compositor in one- * interleaved pass and the difference is the compositor alone.- *- * localStorage.setItem("openscreen.wgslCompositor", "1")- */-function wgslCompositorEnabled(): boolean {- try {- return localStorage.getItem("openscreen.wgslCompositor") === "1";- } catch {- return false;- }-}--/**- * Emit frame N of the export as a PNG on the console, for eyes.- *- * A compositor that runs and renders garbage produces a clean fps number, so a- * speed arm cannot tell you whether it works. This is the cheapest path to the- * only thing that can: the picture. It goes through the console because the- * renderer has no file access and the alternative — encoding an mp4 — drags in a- * 100 MB ffmpeg download to look at one frame.- *- * localStorage.setItem("openscreen.dumpFrame", "60")- */-function dumpFrameIndex(): number | null {- try {- const raw = localStorage.getItem("openscreen.dumpFrame");- if (!raw) return null;- const n = Number(raw);- return Number.isFinite(n) && n >= 0 ? n : null;- } catch {- return null;- }-}--async function dumpFrameToConsole(canvas: HTMLCanvasElement, index: number): Promise<void> {- // Via a 2D surface, so this works for the WebGPU canvas and the Canvas2D one- // alike — drawImage is what both have in common.- const out = document.createElement("canvas");- out.width = canvas.width;- out.height = canvas.height;- const ctx = out.getContext("2d");- if (!ctx) return;- ctx.drawImage(canvas, 0, 0);- const png = out.toDataURL("image/png");- console.warn(`[bench] ${JSON.stringify({ event: "frame", index, png })}`);-}--async function probeOneEncoder(opts: {- label: string;- width: number;- height: number;- codec: string;- bitrate: number;- framerate: number;- hardwareAcceleration: HardwareAcceleration;- frameSource: "canvas" | "cpu";-}): Promise<string> {- const { width, height } = opts;- const canvas = new OffscreenCanvas(width, height);- const ctx = canvas.getContext("2d");- if (!ctx) return `${opts.label}: no 2d ctx`;- let chunks = 0;- const encoder = new VideoEncoder({- output: (chunk) => {- chunks++;- void chunk;- },- error: (e) => console.warn(`[encoder probe] ${opts.label} error:`, e),- });- const config: VideoEncoderConfig = {- codec: opts.codec,- width,- height,- bitrate: opts.bitrate,- framerate: opts.framerate,- latencyMode: "quality",- bitrateMode: "variable",- hardwareAcceleration: opts.hardwareAcceleration,- };- const support = await VideoEncoder.isConfigSupported(config);- if (!support.supported) return `${opts.label}: unsupported`;- encoder.configure(config);- const frameCount = 120;- const frameDurationUs = Math.round(1_000_000 / opts.framerate);- const start = performance.now();- for (let i = 0; i < frameCount; i++) {- ctx.fillStyle = i % 2 ? "#1c3d5a" : "#5a1c3d";- ctx.fillRect(0, 0, width, height);- ctx.fillStyle = "#ffffff";- ctx.fillRect((i * 37) % width, (i * 23) % height, 80, 80);- let frame: VideoFrame;- if (opts.frameSource === "canvas") {- frame = new VideoFrame(canvas, { timestamp: i * frameDurationUs, duration: frameDurationUs });- } else {- const pixels = ctx.getImageData(0, 0, width, height);- frame = new VideoFrame(pixels.data.buffer, {- format: "RGBA",- codedWidth: width,- codedHeight: height,- timestamp: i * frameDurationUs,- duration: frameDurationUs,- });- }- while (encoder.encodeQueueSize > 8) {- await new Promise((resolve) => setTimeout(resolve, 2));- }- encoder.encode(frame, { keyFrame: i % 60 === 0 });- frame.close();- }- await encoder.flush();- const elapsedMs = performance.now() - start;- encoder.close();- return `${opts.label}: ${frameCount} frames in ${elapsedMs.toFixed(0)}ms = ${((frameCount / elapsedMs) * 1000).toFixed(1)} fps (${chunks} chunks)`;-}--async function runEncoderThroughputProbe(config: {- width: number;- height: number;- codec?: string;- bitrate: number;- frameRate: number;-}): Promise<string> {- const codec = config.codec || "avc1.640033";- const base = {- width: config.width,- height: config.height,- codec,- bitrate: config.bitrate,- framerate: config.frameRate,- };- const lines: string[] = ["[encoder probe]"];-- // If Chromium fell back to SwiftShader, WebGL is CPU-rasterized and the- // "hardware" encoder is unavailable — that alone would explain hw==sw- // throughput and the GPU composite showing no gain.- try {- const probeCanvas = document.createElement("canvas");- const gl =- (probeCanvas.getContext("webgl2") as WebGL2RenderingContext | null) ??- (probeCanvas.getContext("webgl") as WebGLRenderingContext | null);- if (gl) {- const info = gl.getExtension("WEBGL_debug_renderer_info");- const renderer = info- ? gl.getParameter(info.UNMASKED_RENDERER_WEBGL)- : gl.getParameter(gl.RENDERER);- const vendor = info- ? gl.getParameter(info.UNMASKED_VENDOR_WEBGL)- : gl.getParameter(gl.VENDOR);- lines.push(`gl: ${vendor} | ${renderer}`);- } else {- lines.push("gl: NO WEBGL CONTEXT");- }- } catch (error) {- lines.push(`gl: probe failed ${String(error)}`);- }- lines.push(- await probeOneEncoder({- ...base,- label: "hw/canvas-frame",- hardwareAcceleration: "prefer-hardware",- frameSource: "canvas",- }),- );- lines.push(- await probeOneEncoder({- ...base,- label: "hw/cpu-rgba-frame",- hardwareAcceleration: "prefer-hardware",- frameSource: "cpu",- }),- );- lines.push(- await probeOneEncoder({- ...base,- label: "sw/canvas-frame",- hardwareAcceleration: "prefer-software",- frameSource: "canvas",- }),- );- lines.push(- await probeOneEncoder({- ...base,- label: "hw/canvas-frame@720p",- hardwareAcceleration: "prefer-hardware",- frameSource: "canvas",- width: 1280,- height: 720,- }),- );- return lines.join("\n");-}--/** One clip's crop, in SOURCE-media time — the export renderer switches to- * the covering entry's `cropRegion` before rendering each frame, so a crop- * applies to its own clip only (see clipSchema.cropRegion), not the whole- * export. */-export interface CropScheduleEntry {- startSec: number;- endSec: number;- cropRegion: CropRegion;-}--export interface VideoExporterConfig extends ExportConfig {- videoUrl: string;- webcamVideoUrl?: string;- wallpaper: string;- zoomRegions: ZoomRegion[];- cameraFullscreenRegions?: CameraFullscreenRegion[];- trimRegions?: TrimRegion[];- speedRegions?: SpeedRegion[];- showShadow: boolean;- shadowIntensity: number;- showBlur: boolean;- motionBlurAmount?: number;- borderRadius?: number;- padding?: number;- videoPadding?: number;- /** Fallback crop when `cropSchedule` is absent or a source timestamp- * doesn't fall in any entry (e.g. no clips info available). */- cropRegion: CropRegion;- /** Per-clip crop, in source-media time. When present, takes priority over- * the flat `cropRegion` for every frame that falls inside one of its- * entries. */- cropSchedule?: CropScheduleEntry[];- webcamLayoutPreset?: WebcamLayoutPreset;- webcamMaskShape?: import("@/components/video-editor/types").WebcamMaskShape;- webcamMirrored?: boolean;- webcamReactiveZoom?: boolean;- webcamSizePreset?: WebcamSizePreset;- webcamPosition?: { cx: number; cy: number } | null;- cursorRecordingData?: CursorRecordingData | null;- cursorScale?: number;- cursorSmoothing?: number;- cursorMotionBlur?: number;- cursorClickBounce?: number;- cursorClipToBounds?: boolean;- cursorTheme?: string;- annotationRegions?: AnnotationRegion[];- previewWidth?: number;- previewHeight?: number;- cursorTelemetry?: import("@/components/video-editor/types").CursorTelemetryPoint[];- cursorClickTimestamps?: number[];- onProgress?: (progress: ExportProgress) => void;- // v2 multi-asset render plan (ordered segments, virtual-time effects,- // per-segment cursor). Present when built by documentExporter; the segment- // loop consumes it. Absent for the legacy single-asset callers.- renderPlan?: RenderPlan;-}--const SOURCE_COPY_EPSILON = 0.0001;-// Looser than SOURCE_COPY_EPSILON: container-reported avg frame rate is a-// rounded rational (e.g. 59.94 for a "60fps" recording), so this only needs-// to catch a genuinely different rate selection (24/30/60), not that noise.-const FRAME_RATE_EPSILON = 0.5;--function hasActiveTimeRegions(regions?: Array<{ startMs: number; endMs: number }>) {- return Boolean(regions?.some((region) => region.endMs - region.startMs > SOURCE_COPY_EPSILON));-}--function hasActiveSpeedRegions(regions?: SpeedRegion[]) {- return Boolean(- regions?.some(- (region) =>- region.endMs - region.startMs > SOURCE_COPY_EPSILON &&- Math.abs(region.speed - 1) > SOURCE_COPY_EPSILON,- ),- );-}--function hasNativeCursorOverlay(config: VideoExporterConfig) {- return (config.cursorScale ?? 0) > 0;-}--function isDefaultCrop(cropRegion: CropRegion) {- return (- Math.abs(cropRegion.x) <= SOURCE_COPY_EPSILON &&- Math.abs(cropRegion.y) <= SOURCE_COPY_EPSILON &&- Math.abs(cropRegion.width - 1) <= SOURCE_COPY_EPSILON &&- Math.abs(cropRegion.height - 1) <= SOURCE_COPY_EPSILON- );-}--function hasNonDefaultCrop(config: VideoExporterConfig): boolean {- if (config.cropSchedule && config.cropSchedule.length > 0) {- return config.cropSchedule.some((entry) => !isDefaultCrop(entry.cropRegion));- }- return !isDefaultCrop(config.cropRegion);-}--/** Finds which clip's crop applies at a given SOURCE-media timestamp — the- * first schedule entry whose [startSec, endSec) covers it, falling back to- * `fallback` when the schedule is absent or nothing covers it (e.g. a gap). */-export function resolveCropAt(- schedule: CropScheduleEntry[] | undefined,- sourceSec: number,- fallback: CropRegion,-): CropRegion {- if (!schedule || schedule.length === 0) return fallback;- const covering = schedule.find(- (entry) => sourceSec >= entry.startSec && sourceSec < entry.endSec,- );- return covering?.cropRegion ?? fallback;-}--interface SourceCopyVideoInfo {- width: number;- height: number;- frameRate: number;- codec: string;-}--export function isSourceCopyFastPathEligible(- config: VideoExporterConfig,- videoInfo: SourceCopyVideoInfo,-) {- return getSourceCopyFastPathBlockers(config, videoInfo).length === 0;-}--export function getSourceCopyFastPathBlockers(- config: VideoExporterConfig,- videoInfo: SourceCopyVideoInfo,-) {- const blockers: string[] = [];-- if (config.width !== videoInfo.width || config.height !== videoInfo.height) {- blockers.push(- `output-size ${config.width}x${config.height} differs from source ${videoInfo.width}x${videoInfo.height}`,- );- }- // A copied file keeps the source's exact frame rate/codec — if the user- // picked a different one in the export dialog, honor it by re-encoding- // instead of silently shipping the source's encoding under a different- // label.- if (Math.abs(config.frameRate - videoInfo.frameRate) > FRAME_RATE_EPSILON) {- blockers.push(`frame rate ${config.frameRate} differs from source ${videoInfo.frameRate}`);- }- if (config.codec && videoCodecFamily(config.codec) !== videoCodecFamily(videoInfo.codec)) {- blockers.push(`codec ${config.codec} differs from source ${videoInfo.codec}`);- }- if (config.webcamVideoUrl) blockers.push("webcam overlay is enabled");- if (hasActiveTimeRegions(config.trimRegions)) blockers.push("trim regions are present");- if (hasActiveSpeedRegions(config.speedRegions)) blockers.push("speed regions are present");- if (hasActiveTimeRegions(config.zoomRegions)) blockers.push("zoom regions are present");- if (hasActiveTimeRegions(config.cameraFullscreenRegions))- blockers.push("camera fullscreen regions are present");- if (hasActiveTimeRegions(config.annotationRegions))- blockers.push("annotation regions are present");- if (hasNativeCursorOverlay(config)) blockers.push("editable cursor overlay is enabled");- if (hasNonDefaultCrop(config)) blockers.push("crop is not default");- if ((config.padding ?? 0) > SOURCE_COPY_EPSILON) blockers.push("padding is not zero");- if ((config.videoPadding ?? 0) > SOURCE_COPY_EPSILON) blockers.push("video padding is not zero");- if ((config.borderRadius ?? 0) > SOURCE_COPY_EPSILON) blockers.push("roundness is not zero");- if (config.showShadow || config.shadowIntensity > SOURCE_COPY_EPSILON) {- blockers.push("shadow is enabled");- }- if (config.showBlur) blockers.push("background blur is enabled");- if ((config.motionBlurAmount ?? 0) > SOURCE_COPY_EPSILON) blockers.push("motion blur is enabled");-- return blockers;-}--/** Projects timeline-authored regions (zoom/annotation/speed, in virtual/timeline- * ms) onto ONE segment's SOURCE time. Timeline↔source is 1:1 within a clip, so- * the covered part of each region maps by its offset from the clip's timeline- * start; regions not covering the segment are dropped. Speed is applied on top- * by the decoder over the projected source span, and the frame loop matches- * zoom/annotation/cursor by the frame's SOURCE time — so everything stays- * aligned even when speed makes output time diverge from timeline time. */-function projectRegionsToSegmentSource<T extends { startMs: number; endMs: number }>(- regions: T[],- segment: RenderSegment,-): T[] {- const out: T[] = [];- const tStart = segment.timelineStartSec;- const tEnd = segment.timelineEndSec;- for (const region of regions) {- const lo = Math.min(region.startMs, region.endMs) / 1000;- const hi = Math.max(region.startMs, region.endMs) / 1000;- const s = Math.max(lo, tStart);- const e = Math.min(hi, tEnd);- if (e <= s) continue; // region does not cover this segment- const srcStart = segment.sourceStartSec + (s - tStart);- const srcEnd = segment.sourceStartSec + (e - tStart);- out.push({- ...region,- startMs: Math.round(srcStart * 1000),- endMs: Math.round(srcEnd * 1000),- });- }- return out;-}--/** Source-time spans to CUT for one segment so its decoder emits exactly- * [sourceStart, sourceEnd) minus the clip's intra-trims: the complement of the- * kept window over [0, sourceDuration] plus the intra-trims (v2 segment loop). */-function buildSegmentRenderTrims(segment: RenderSegment, sourceDurationSec: number): TrimRegion[] {- const cuts: Array<{ startSec: number; endSec: number }> = [];- if (segment.sourceStartSec > 0) {- cuts.push({ startSec: 0, endSec: segment.sourceStartSec });- }- const keptEnd = Math.min(segment.sourceEndSec, sourceDurationSec);- if (keptEnd < sourceDurationSec) {- cuts.push({ startSec: keptEnd, endSec: sourceDurationSec });- }- for (const trim of segment.intraTrims) {- cuts.push({ startSec: trim.startSec, endSec: trim.endSec });- }- return cuts.map((cut, i) => ({- id: `seg_trim_${i + 1}`,- startMs: Math.round(cut.startSec * 1000),- endMs: Math.round(cut.endSec * 1000),- }));-}--/** Per-segment cursor recording for the renderer: the plan's shared cursor- * atlas/style + THIS segment's asset samples (empty → no overlay). */-function segmentCursorRecording(- plan: RenderPlan,- segment: RenderSegment,-): CursorRecordingData | null {- if (!plan.cursor) return null;- return {- version: plan.cursor.version,- provider: plan.cursor.provider,- assets: plan.cursor.assets,- samples: segment.cursorSamples,- };-}--// v2 multi-asset audio output layout. Both recording formats are 48 kHz, so-// decodeAudioData is an identity resample; only channel counts get normalized.-const AUDIO_OUTPUT_SAMPLE_RATE = 48_000;-const AUDIO_OUTPUT_CHANNELS = 2;-// Short equal-power fade applied at each segment audio join (seamless audio).-const AUDIO_BOUNDARY_FADE_SEC = 0.005;--/** Source-time sub-intervals of a segment that are KEPT — its window minus- * intra-trims (the complement of buildSegmentRenderTrims within the clip) — so- * the segment's audio removes exactly the same cuts as its video. */-function keptSourceIntervals(segment: RenderSegment): Array<{ startSec: number; endSec: number }> {- const kept: Array<{ startSec: number; endSec: number }> = [];- let cursor = segment.sourceStartSec;- const trims = [...segment.intraTrims].sort((a, b) => a.startSec - b.startSec);- for (const trim of trims) {- const trimStart = Math.max(trim.startSec, segment.sourceStartSec);- const trimEnd = Math.min(trim.endSec, segment.sourceEndSec);- if (trimEnd <= cursor) continue;- if (trimStart > cursor) {- kept.push({ startSec: cursor, endSec: Math.min(trimStart, segment.sourceEndSec) });- }- cursor = Math.max(cursor, trimEnd);- }- if (cursor < segment.sourceEndSec) {- kept.push({ startSec: cursor, endSec: segment.sourceEndSec });- }- return kept;-}--/** Decodes ONE segment's audio to planar PCM at the common export layout- * (sampleRate/channels), keeping only the clip's source window minus its- * intra-trims. Channel counts are normalized via the shared downmix. Returns- * null when the source has no decodable audio track. */-async function decodeSegmentAudioPcm(- segment: RenderSegment,- sampleRate: number,- channels: number,-): Promise<Float32Array[] | null> {- let file: File | null = null;- try {- file = await materializeLocalSourceFile(segment.videoUrl, `seg-${segment.clipId}-audio`);- const bytes = await file.arrayBuffer();- const ctx = new OfflineAudioContext(Math.max(1, channels), 1, sampleRate);- let audioBuffer: AudioBuffer;- try {- audioBuffer = await ctx.decodeAudioData(bytes);- } catch {- return null; // no decodable audio track- }- const sourceChannels = audioBuffer.numberOfChannels;- if (sourceChannels === 0) return null;-- const sourcePlanes: Float32Array[] = [];- for (let c = 0; c < sourceChannels; c++) sourcePlanes.push(audioBuffer.getChannelData(c));-- // Concatenate the kept source sub-intervals (intra-trims removed), per channel.- const kept = keptSourceIntervals(segment);- const keptChannels: Float32Array[] = [];- for (let c = 0; c < sourceChannels; c++) {- const total = kept.reduce((acc, iv) => {- const s0 = Math.max(0, Math.round(iv.startSec * sampleRate));- const s1 = Math.min(sourcePlanes[c].length, Math.round(iv.endSec * sampleRate));- return acc + Math.max(0, s1 - s0);- }, 0);- const out = new Float32Array(total);- let w = 0;- for (const iv of kept) {- const s0 = Math.max(0, Math.round(iv.startSec * sampleRate));- const s1 = Math.min(sourcePlanes[c].length, Math.round(iv.endSec * sampleRate));- if (s1 > s0) {- out.set(sourcePlanes[c].subarray(s0, s1), w);- w += s1 - s0;- }- }- keptChannels.push(out);- }-- if (sourceChannels === channels) return keptChannels;-- // Normalize channel count (e.g. mono → stereo) with the shared downmix,- // which returns one planar Float32Array (ch0 samples, then ch1, …).- const frameCount = keptChannels[0]?.length ?? 0;- if (frameCount === 0) return [];- const downmixed = downmixPlanarChannelsForExport(keptChannels, channels);- const result: Float32Array[] = [];- for (let c = 0; c < channels; c++) {- result.push(downmixed.subarray(c * frameCount, (c + 1) * frameCount));- }- return result;- } catch (error) {- console.warn("[VideoExporter] segment audio decode failed:", error);- return null;- } finally {- if (file) releaseLocalSourceFile(file.name);- }-}--/** Pitch-preserving (WSOLA) time-stretch of a segment's planar PCM to exactly- * `targetSamples` per channel, so audio matches the segment's speed-retimed- * video length and A/V stays locked. Pass-through when already the right length- * (constant 1× segment). A single stretch factor is applied across the segment- * (uniform over any speed variation within it — total length is exact, which is- * what keeps the joins synced; per-region audio retiming is a refinement). */-function timeStretchPcmToLength(- pcm: Float32Array[],- sampleRate: number,- channels: number,- targetSamples: number,-): Float32Array[] {- if (targetSamples <= 0) return Array.from({ length: channels }, () => new Float32Array(0));- const sourceSamples = pcm[0]?.length ?? 0;- if (sourceSamples === 0 || Math.abs(sourceSamples - targetSamples) <= 1) return pcm;-- const speed = sourceSamples / targetSamples; // >1 = speed up (compress)- const stretcher = new WsolaTimeStretcher({- sampleRate,- channels,- speed,- expectedOutputSamples: targetSamples,- });- const chunks = [stretcher.push(pcm), stretcher.flush()];- const result: Float32Array[] = [];- for (let c = 0; c < channels; c++) {- const out = new Float32Array(targetSamples);- let w = 0;- for (const chunk of chunks) {- const src = chunk[c];- if (!src) continue;- const n = Math.min(src.length, targetSamples - w);- if (n > 0) {- out.set(src.subarray(0, n), w);- w += n;- }- }- result.push(out);- }- return result;-}--/** Concatenate planar PCM chunks (one array-of-channels per chunk) per channel. */-function concatPlanarChunks(chunks: Float32Array[][], channels: number): Float32Array[] {- const result: Float32Array[] = [];- for (let c = 0; c < channels; c++) {- let total = 0;- for (const chunk of chunks) total += chunk[c]?.length ?? 0;- const out = new Float32Array(total);- let w = 0;- for (const chunk of chunks) {- const src = chunk[c];- if (!src) continue;- out.set(src, w);- w += src.length;- }- result.push(out);- }- return result;-}--/** Time-stretch a segment's kept audio PER speed sub-segment (not uniformly), so- * a partial speed region inside a clip retimes only its own span — matching how- * the video decoder applies speed. The sub-segments and their output frame counts- * are computed EXACTLY as the decoder does (splitBySpeed of the kept intervals,- * then ceil((dur-ε)/speed·fps) frames each), so audio stays frame-locked to the- * video. The kept PCM (decodeSegmentAudioPcm) is the concatenation of those same- * kept intervals, so a running cursor slices it in order. */-function stretchSegmentAudioBySpeed(- pcm: Float32Array[],- segment: RenderSegment,- speedRegions: SpeedRegion[],- sampleRate: number,- channels: number,- frameRate: number,-): Float32Array[] {- const segmentTrims = buildSegmentRenderTrims(segment, segment.sourceEndSec);- const speedSegs = splitBySpeed(- computeKeepSegments(segment.sourceEndSec, segmentTrims),- speedRegions,- );- if (speedSegs.length === 0) return pcm;-- const VIDEO_EPSILON_SEC = 0.001; // must match streamingDecoder's per-segment quantization- const totalKept = pcm[0]?.length ?? 0;- const chunks: Float32Array[][] = [];- let keptCursor = 0;- for (const seg of speedSegs) {- const inSamples = Math.round((seg.endSec - seg.startSec) * sampleRate);- const inStart = keptCursor;- const inEnd = Math.min(inStart + inSamples, totalKept);- keptCursor = inStart + inSamples;-- const frameCount = Math.ceil(- ((seg.endSec - seg.startSec - VIDEO_EPSILON_SEC) / seg.speed) * frameRate,- );- const outSamples = Math.max(0, Math.round((frameCount / frameRate) * sampleRate));-- if (inEnd <= inStart) {- // No source audio for this span (past the buffer) → silence of its length.- chunks.push(Array.from({ length: channels }, () => new Float32Array(outSamples)));- continue;- }- const slice = pcm.map((ch) => ch.subarray(inStart, inEnd));- chunks.push(timeStretchPcmToLength(slice, sampleRate, channels, outSamples));- }- return concatPlanarChunks(chunks, channels);-}--function isMp4Source(videoUrl: string, blob: Blob) {- if (blob.type.toLowerCase().includes("mp4")) {- return true;- }-- try {- const path = new URL(videoUrl, window.location.href).pathname;- return path.toLowerCase().endsWith(".mp4");- } catch {- return videoUrl.toLowerCase().split(/[?#]/, 1)[0].endsWith(".mp4");- }-}--export class VideoExporter {- private config: VideoExporterConfig;- private streamingDecoder: StreamingVideoDecoder | null = null;- private renderer: FrameRenderer | null = null;- private encoder: VideoEncoder | null = null;- private muxer: VideoMuxer | null = null;- private nativeSink: NativeFrameSink | null = null;- private audioProcessor: AudioProcessor | null = null;- private webcamDecoder: StreamingVideoDecoder | null = null;- private cancelled = false;- private encodeQueue = 0;- // Keep a smaller queue for software encoding so Windows does not balloon memory.- private readonly MAX_ENCODE_QUEUE = 120;- private videoDescription: Uint8Array | undefined;- private videoColorSpace: VideoColorSpaceInit | undefined;- private muxingPromises: Promise<void>[] = [];- private chunkCount = 0;- private fatalEncoderError: Error | null = null;-- constructor(config: VideoExporterConfig) {- this.config = config;- }-- async export(): Promise<ExportResult> {- const encoderPreferences = this.getEncoderPreferences();- let lastError: Error | null = null;-- for (const encoderPreference of encoderPreferences) {- try {- return await this.exportWithEncoderPreference(encoderPreference);- } catch (error) {- const normalizedError = error instanceof Error ? error : new Error(String(error));- lastError = normalizedError;-- if (this.cancelled) {- return { success: false, error: "Export cancelled" };- }-- if (normalizedError instanceof BackgroundLoadError) {- throw normalizedError;- }-- if (encoderPreferences.length > 1) {- console.warn(- `[VideoExporter] ${encoderPreference} export attempt failed:`,- normalizedError,- );- }- } finally {- this.cleanup();- }- }-- return {- success: false,- error: lastError?.message || "Export failed",- };- }-- private async exportWithEncoderPreference(- encoderPreference: HardwareAcceleration,- ): Promise<ExportResult> {- let webcamFrameQueue: TimestampedVideoFrameQueue | null = null;- let stopWebcamDecode = false;- let webcamDecodeError: Error | null = null;- let webcamDecodePromise: Promise<void> | null = null;- let webcamDecoder: StreamingVideoDecoder | null = null;- const warnings: string[] = [];- const onWarning = (message: string) => warnings.push(message);-- this.cleanup();- this.cancelled = false;- this.fatalEncoderError = null;-- try {- // v2 path: ALL AI-edition exports (single- or multi-clip) render through- // the segment loop — one unified path, no mono-asset special-casing. The- // single-stream pipeline below survives only for legacy callers that pass- // no renderPlan (the out-of-scope components/video-editor exporter).- const segmentPlan = this.config.renderPlan;- if (segmentPlan && segmentPlan.segments.length > 0) {- return await this.runSegmentLoop(encoderPreference, segmentPlan);- }-- const platform = await getPlatform();-- const streamingDecoder = new StreamingVideoDecoder();- this.streamingDecoder = streamingDecoder;- const videoInfo = await streamingDecoder.loadMetadata(- this.config.videoUrl,- ({ copiedBytes, totalBytes }) => {- // Large recordings are streamed into OPFS before demuxing; surface- // that copy as a "preparing" phase so the dialog is not stuck at 0%.- this.reportProgress({- currentFrame: 0,- totalFrames: 0,- percentage: totalBytes > 0 ? (copiedBytes / totalBytes) * 100 : 0,- estimatedTimeRemaining: 0,- phase: "preparing",- });- },- );- const sourceCopyResult = await this.trySourceCopyFastPath(videoInfo);- if (sourceCopyResult) {- return sourceCopyResult;- }-- let webcamInfo: Awaited<ReturnType<StreamingVideoDecoder["loadMetadata"]>> | null = null;- if (this.config.webcamVideoUrl) {- webcamDecoder = new StreamingVideoDecoder();- this.webcamDecoder = webcamDecoder;- webcamInfo = await webcamDecoder.loadMetadata(this.config.webcamVideoUrl);- }-- const renderer = new FrameRenderer({- width: this.config.width,- height: this.config.height,- wallpaper: this.config.wallpaper,- zoomRegions: this.config.zoomRegions,- cameraFullscreenRegions: this.config.cameraFullscreenRegions,- showShadow: this.config.showShadow,- shadowIntensity: this.config.shadowIntensity,- showBlur: this.config.showBlur,- motionBlurAmount: this.config.motionBlurAmount,- borderRadius: this.config.borderRadius,- padding: this.config.padding,- cropRegion: this.config.cropRegion,- cursorRecordingData: this.config.cursorRecordingData,- cursorScale: this.config.cursorScale,- cursorSmoothing: this.config.cursorSmoothing,- cursorMotionBlur: this.config.cursorMotionBlur,- cursorClickBounce: this.config.cursorClickBounce,- cursorClipToBounds: this.config.cursorClipToBounds,- cursorTheme: this.config.cursorTheme,- videoWidth: videoInfo.width,- videoHeight: videoInfo.height,- webcamSize: webcamInfo ? { width: webcamInfo.width, height: webcamInfo.height } : null,- webcamLayoutPreset: this.config.webcamLayoutPreset,- webcamMaskShape: this.config.webcamMaskShape,- webcamMirrored: this.config.webcamMirrored,- webcamReactiveZoom: this.config.webcamReactiveZoom,- webcamSizePreset: this.config.webcamSizePreset,- webcamPosition: this.config.webcamPosition,- annotationRegions: this.config.annotationRegions,- speedRegions: this.config.speedRegions,- previewWidth: this.config.previewWidth,- previewHeight: this.config.previewHeight,- cursorTelemetry: this.config.cursorTelemetry,- cursorClickTimestamps: this.config.cursorClickTimestamps,- platform,- });- this.renderer = renderer;- await renderer.initialize();-- await this.initializeEncoder(encoderPreference);-- const sourceDemuxer = streamingDecoder.getDemuxer();- const audioExportCodec =- videoInfo.hasAudio && sourceDemuxer- ? await AudioProcessor.selectSupportedExportCodecForSource(sourceDemuxer)- : null;- if (videoInfo.hasAudio && !audioExportCodec) {- console.warn("[VideoExporter] No supported audio export codec, exporting video-only.");- }-- const hasAudio = Boolean(audioExportCodec);- const muxer = new VideoMuxer(this.config, hasAudio, audioExportCodec?.muxerCodec);- this.muxer = muxer;- await muxer.initialize();-- const { totalFrames } = streamingDecoder.getExportMetrics(- this.config.frameRate,- this.config.trimRegions,- this.config.speedRegions,- );-- const frameDuration = 1_000_000 / this.config.frameRate;- let frameIndex = 0;- const maxEncodeQueue =- encoderPreference === "prefer-software"- ? Math.min(this.MAX_ENCODE_QUEUE, 32)- : this.MAX_ENCODE_QUEUE;-- webcamFrameQueue = this.config.webcamVideoUrl ? new TimestampedVideoFrameQueue() : null;- webcamDecodePromise =- webcamDecoder && webcamFrameQueue- ? (() => {- const queue = webcamFrameQueue;- return webcamDecoder- .decodeAll(- this.config.frameRate,- this.config.trimRegions,- this.config.speedRegions,- async (webcamFrame, _exportTimestampUs, webcamSourceTimestampMs) => {- while (queue.length >= 12 && !this.cancelled && !stopWebcamDecode) {- await new Promise((resolve) => setTimeout(resolve, 2));- }- if (this.cancelled || stopWebcamDecode) {- webcamFrame.close();- return;- }- queue.enqueue(webcamFrame, webcamSourceTimestampMs);- },- onWarning,- )- .catch((error) => {- webcamDecodeError = error instanceof Error ? error : new Error(String(error));- throw webcamDecodeError;- })- .finally(() => {- if (webcamDecodeError) {- queue.fail(webcamDecodeError);- } else {- queue.close();- }- });- })()- : null;-- await streamingDecoder.decodeAll(- this.config.frameRate,- this.config.trimRegions,- this.config.speedRegions,- async (videoFrame, _exportTimestampUs, sourceTimestampMs) => {- let webcamFrame: VideoFrame | null = null;- try {- if (this.cancelled) {- return;- }-- if (this.fatalEncoderError) {- throw this.fatalEncoderError;- }-- const timestamp = frameIndex * frameDuration;- webcamFrame = webcamFrameQueue- ? await webcamFrameQueue.frameAt(sourceTimestampMs)- : null;- if (this.cancelled) {- return;- }-- const sourceTimestampUs = sourceTimestampMs * 1000;- // Crop is per-clip — switch to whichever clip's crop covers this- // frame's source time before rendering it (see- // FrameRenderer.setCropRegion / resolveCropAt).- renderer.setCropRegion(- resolveCropAt(- this.config.cropSchedule,- sourceTimestampMs / 1000,- this.config.cropRegion,- ),- );- await renderer.renderFrame(videoFrame, sourceTimestampUs, webcamFrame);-- const canvas = renderer.getCanvas();-- let exportFrame: VideoFrame;-- // On some Linux systems the GPU shared-image path (EGL/Ozone) fails- // silently, producing empty frames, so we force a CPU readback instead.- if (platform === "linux") {- const canvasCtx = canvas.getContext("2d")!;- const imageData = canvasCtx.getImageData(0, 0, canvas.width, canvas.height);- exportFrame = new VideoFrame(imageData.data.buffer, {- format: "RGBA",- codedWidth: canvas.width,- codedHeight: canvas.height,- timestamp,- duration: frameDuration,- colorSpace: {- primaries: "bt709",- transfer: "iec61966-2-1",- matrix: "rgb",- fullRange: true,- },- });- } else {- exportFrame = new VideoFrame(canvas, { timestamp, duration: frameDuration });- }-- try {- await waitForEncoderQueueSpace({- getQueueSize: () => this.encoder?.encodeQueueSize ?? 0,- maxEncodeQueue,- isCancelled: () => this.cancelled,- encoderPreference,- });- } catch (error) {- exportFrame.close();- throw error;- }-- if (this.encoder && this.encoder.state === "configured") {- this.encodeQueue++;- this.encoder.encode(exportFrame, { keyFrame: frameIndex % 150 === 0 });- } else {- console.warn(- `[Frame ${frameIndex}] Encoder not ready! State: ${this.encoder?.state}`,- );- }-- exportFrame.close();- frameIndex++;-- this.reportProgress({- currentFrame: frameIndex,- totalFrames,- percentage: (frameIndex / totalFrames) * 100,- estimatedTimeRemaining: 0,- });- } finally {- videoFrame.close();- webcamFrame?.close();- }- },- onWarning,- );-- if (this.cancelled) {- return { success: false, error: "Export cancelled" };- }-- if (this.fatalEncoderError) {- throw this.fatalEncoderError;- }-- stopWebcamDecode = true;- webcamFrameQueue?.destroy();- webcamDecoder?.cancel();- await webcamDecodePromise;-- if (this.encoder && this.encoder.state === "configured") {- await this.withTimeout(- this.encoder.flush(),- ENCODER_FLUSH_TIMEOUT_MS,- encoderPreference === "prefer-hardware"- ? "The hardware video encoder stopped responding while finalizing the export."- : "The video encoder stopped responding while finalizing the export.",- );- }-- if (this.fatalEncoderError) {- throw this.fatalEncoderError;- }-- await Promise.all(this.muxingPromises);-- this.reportProgress({- currentFrame: totalFrames,- totalFrames,- percentage: 100,- estimatedTimeRemaining: 0,- phase: "finalizing",- });-- if (hasAudio && audioExportCodec && !this.cancelled) {- const demuxer = streamingDecoder.getDemuxer();- if (demuxer) {- console.log("[VideoExporter] Processing audio track...");- this.audioProcessor = new AudioProcessor();- await this.audioProcessor.process(- demuxer,- muxer,- this.config.videoUrl,- this.config.trimRegions,- this.config.speedRegions,- videoInfo.duration,- audioExportCodec,- this.config.frameRate,- );- }- }-- const blob = await muxer.finalize();- return { success: true, blob, warnings: warnings.length > 0 ? warnings : undefined };- } finally {- stopWebcamDecode = true;- webcamFrameQueue?.destroy();- webcamDecoder?.cancel();- if (webcamDecodePromise) {- await webcamDecodePromise.catch(() => undefined);- }- }- }-- /**- * v2 multi-asset segment loop. Walks the RenderPlan's ordered segments,- * decoding each from its OWN source asset into ONE renderer + encoder + muxer,- * advancing a single continuous virtual-time frame clock across segment- * boundaries so the joins are seamless. Fixes P1 (non-primary clips dropped).- *- * Renders per-segment video + webcam overlay + cursor, each drawn from its- * OWN asset (webcam source + cursor samples switch at every segment boundary).- * Per-segment audio concat (see audioConcatPlan) and virtual-time speed- * mapping are the remaining increments. The caller has already run- * cleanup()/reset.- */- private async runSegmentLoop(- encoderPreference: HardwareAcceleration,- plan: RenderPlan,- ): Promise<ExportResult> {- const warnings: string[] = [];- const onWarning = (message: string) => warnings.push(message);- const platform = await getPlatform();- const segments = plan.segments;- const firstSegment = segments[0];-- // Phase-0 perf harness: accumulate per-stage time to find the bottleneck.- const timings = new StageTimings();- const wallStart = performance.now();-- if (ENCODER_PROBE) {- try {- console.warn(await runEncoderThroughputProbe(this.config));- } catch (error) {- console.warn("[encoder probe] failed:", error);- }- }-- // One renderer for the whole export — output size is fixed; only the- // source-dependent fields change per segment via renderer.setSource().- const useWgsl = wgslCompositorEnabled();- if (useWgsl) {- console.warn("[export perf] WGSL compositor: POC — no captions, annotations, cursor or 3D");- }- const RendererClass = useWgsl- ? (WgslFrameRenderer as unknown as typeof FrameRenderer)- : FrameRenderer;- const renderer = new RendererClass({- width: this.config.width,- height: this.config.height,- wallpaper: plan.appearance.wallpaper,- zoomRegions: plan.zoomRegions,- annotationRegions: plan.annotationRegions,- speedRegions: plan.speedRegions,- showShadow: plan.appearance.shadowIntensity > 0,- shadowIntensity: plan.appearance.shadowIntensity,- showBlur: plan.appearance.showBlur,- motionBlurAmount: plan.appearance.motionBlurAmount,- borderRadius: plan.appearance.borderRadius,- padding: plan.appearance.padding,- cropRegion: firstSegment.cropRegion,- videoWidth: firstSegment.sourceWidth,- videoHeight: firstSegment.sourceHeight,- // Source-dependent fields (webcamSize, cursor samples/scale) are set per- // segment via setSource; webcam layout + cursor style are global.- webcamSize: null,- webcamLayoutPreset: plan.webcam.layoutPreset,- webcamMaskShape: plan.webcam.maskShape,- webcamMirrored: plan.webcam.mirrored,- webcamReactiveZoom: plan.webcam.reactiveZoom,- webcamSizePreset: plan.webcam.sizePreset,- webcamPosition: plan.webcam.position,- cursorScale: plan.cursor?.scale ?? 0,- cursorSmoothing: plan.cursor?.smoothing,- cursorMotionBlur: plan.cursor?.motionBlur,- cursorClickBounce: plan.cursor?.clickBounce,- cursorClipToBounds: plan.cursor?.clipToBounds,- cursorTheme: plan.cursor?.theme,- platform,- });- this.renderer = renderer;- await renderer.initialize();-- // --- Frame sink: native ffmpeg, or the WebCodecs path it is replacing ---- const api = window.electronAPI as unknown as NativeSinkApi | undefined;- const useNative = nativeEncodeEnabled() && typeof api?.exportStart === "function";- // Ceiling diagnostics: extract but never ship, or do not even extract.- // Both produce NO FILE — they price one stage in isolation.- const compositeOnly = useNative && compositeOnlyEnabled();- const dropFrames = useNative && !compositeOnly && dropFramesEnabled();- // Gate G0: sync the GPU after compositing, before anything downstream runs.- const gpuFence = gpuFenceEnabled();- if (gpuFence) {- console.warn("[export perf] G0 fence: GPU synced after compositing, per frame");- }- const dumpAt = dumpFrameIndex();- let sink: NativeFrameSink | null = null;- let extractor: CanvasFrameExtractor | null = null;- if (useNative && api && compositeOnly) {- console.warn("[export perf] composite ceiling: render only, NO EXTRACT, NO FILE WRITTEN");- } else if (useNative && api) {- extractor = new CanvasFrameExtractor(this.config.width, this.config.height);- if (dropFrames) {- console.warn("[export perf] readback ceiling: extract and discard, NO FILE WRITTEN");- } else {- sink = await NativeFrameSink.start(- {- width: this.config.width,- height: this.config.height,- frameRate: this.config.frameRate,- // Same field the WebCodecs encoder is configured from, so the A/B- // compares two runs at one bitrate.- bitrate: this.config.bitrate,- // BGRA is all Chromium will copy out of a canvas; NV12 packing is- // the next step (see frameExtract.ts).- pixelFormat: extractor.pixelFormat,- },- api,- );- this.nativeSink = sink;- console.warn(`[export perf] native encode via ${sink.encoder} -> ${sink.outputPath}`);- }- } else {- await this.initializeEncoder(encoderPreference);- }-- // Audio pre-pass: decode each segment's audio to the common export layout- // up-front, so we know whether to declare an audio track on the muxer (mp4- // needs that at construction). The concatenation TIMING is applied later,- // once the video loop has produced each segment's real frame count.- const stopAudioDecode = timings.start("audioDecode");- const segmentAudioPcm: (Float32Array[] | null)[] = [];- let anySegmentAudio = false;- for (const segment of segments) {- if (this.cancelled) break;- const pcm = await decodeSegmentAudioPcm(- segment,- AUDIO_OUTPUT_SAMPLE_RATE,- AUDIO_OUTPUT_CHANNELS,- );- if (pcm && pcm.length > 0 && (pcm[0]?.length ?? 0) > 0) anySegmentAudio = true;- segmentAudioPcm.push(pcm);- }- stopAudioDecode();- const audioExportCodec = anySegmentAudio- ? await AudioProcessor.selectSupportedExportCodec(- AUDIO_OUTPUT_SAMPLE_RATE,- AUDIO_OUTPUT_CHANNELS,- )- : null;- const hasAudio = Boolean(audioExportCodec);-- // ffmpeg does its own muxing and writes the file, so the JS muxer only- // exists on the WebCodecs path.- let muxer: VideoMuxer | null = null;- if (!useNative) {- muxer = new VideoMuxer(this.config, hasAudio, audioExportCodec?.muxerCodec);- this.muxer = muxer;- await muxer.initialize();- }-- const frameDuration = 1_000_000 / this.config.frameRate;- const maxEncodeQueue =- encoderPreference === "prefer-software"- ? Math.min(this.MAX_ENCODE_QUEUE, 32)- : this.MAX_ENCODE_QUEUE;-- // Progress estimate from the plan (no decoder metadata needed): kept- // virtual duration of every segment × fps.- const estTotalFrames = Math.max(- 1,- Math.round(- segments.reduce((acc, s) => {- const intra = s.intraTrims.reduce((a, iv) => a + (iv.endSec - iv.startSec), 0);- const kept = Math.max(0, s.sourceEndSec - s.sourceStartSec - intra);- return acc + kept * this.config.frameRate;- }, 0),- ),- );-- let frameIndex = 0;- // Real per-segment video frame count — audio is sized from this so the- // concatenated audio stays locked to the (independently retimed) video.- const segmentFrameCounts: number[] = [];-- // The video loop spends ~90% of its wall time blocked in encodeWait, so- // the CPU is mostly idle while frames sit in the encoder queue. The- // per-segment WSOLA stretch is pure CPU work and depends ONLY on- // segmentAudioPcm + the plan's speed regions + audio/frame-rate- // constants — nothing that needs segmentFrameCounts. Kick it off here- // so it overlaps the video loop, then await the result in the audio- // phase instead of paying for it serially after.- const stretchedPcmPromise: Promise<(Float32Array[] | null)[] | null> =- hasAudio && audioExportCodec && !this.cancelled- ? (async () => {- const out: (Float32Array[] | null)[] = new Array(segmentAudioPcm.length).fill(null);- for (let i = 0; i < segmentAudioPcm.length; i++) {- if (this.cancelled) break;- // stretchSegmentAudioBySpeed is synchronous — wrapping it in an- // async IIFE doesn't yield by itself. Drop back to the event loop- // between segments so the video loop's encodeWait can actually- // interleave with our CPU work.- await new Promise((r) => setTimeout(r, 0));- // Retime each segment's audio PER speed sub-segment (pitch- // preserved) so a partial speed region only speeds up its own- // span, matching the video.- const pcm = segmentAudioPcm[i];- out[i] = pcm- ? stretchSegmentAudioBySpeed(- pcm,- segments[i],- projectRegionsToSegmentSource(plan.speedRegions, segments[i]),- AUDIO_OUTPUT_SAMPLE_RATE,- AUDIO_OUTPUT_CHANNELS,- this.config.frameRate,- )- : null;- }- return out;- })()- : Promise.resolve(null);- // Never let a rejection go unhandled if the export throws/cancels before the- // await below reaches it; the await is the one that surfaces the failure.- stretchedPcmPromise.catch(() => {- // Swallowed here on purpose — see above.- });-- for (const segment of segments) {- if (this.cancelled) break;- if (this.fatalEncoderError) throw this.fatalEncoderError;-- const framesBeforeSegment = frameIndex;- const decoder = new StreamingVideoDecoder();- this.streamingDecoder = decoder;-- // Per-segment webcam overlay (this asset's camera track), decoded- // concurrently and matched to each screen frame by source time —- // mirrors the legacy single-asset webcam path.- let webcamDecoder: StreamingVideoDecoder | null = null;- let webcamFrameQueue: TimestampedVideoFrameQueue | null = null;- let webcamDecodePromise: Promise<void> | null = null;- let stopWebcamDecode = false;-- try {- const info = await decoder.loadMetadata(segment.videoUrl);- const segmentTrims = buildSegmentRenderTrims(segment, info.duration);- // Timeline effects projected to THIS segment's source time. Speed- // drives the decoder's frame timing; zoom/annotation are matched by- // each frame's source time in the renderer.- const segmentSpeed = projectRegionsToSegmentSource(plan.speedRegions, segment);- const segmentZoom = projectRegionsToSegmentSource(plan.zoomRegions, segment);- const segmentAnnotations = projectRegionsToSegmentSource(plan.annotationRegions, segment);-- let webcamSize: { width: number; height: number } | null = null;- if (segment.camera) {- webcamDecoder = new StreamingVideoDecoder();- this.webcamDecoder = webcamDecoder;- const webcamInfo = await webcamDecoder.loadMetadata(segment.camera.videoUrl);- webcamSize = { width: webcamInfo.width, height: webcamInfo.height };- webcamFrameQueue = new TimestampedVideoFrameQueue();- const queue = webcamFrameQueue;- webcamDecodePromise = webcamDecoder- .decodeAll(- this.config.frameRate,- segmentTrims,- segmentSpeed,- async (webcamFrame, _exportTs, webcamSourceMs) => {- while (queue.length >= 12 && !this.cancelled && !stopWebcamDecode) {- await new Promise((resolve) => setTimeout(resolve, 2));- }- if (this.cancelled || stopWebcamDecode) {- webcamFrame.close();- return;- }- queue.enqueue(webcamFrame, webcamSourceMs);- },- onWarning,- )- .catch((error) => {- const err = error instanceof Error ? error : new Error(String(error));- this.fatalEncoderError ??= err;- queue.fail(err);- })- .finally(() => {- if (!this.cancelled) queue.close();- });- }-- renderer.setSource({- videoWidth: segment.sourceWidth,- videoHeight: segment.sourceHeight,- webcamSize,- cursorRecordingData: segmentCursorRecording(plan, segment),- cursorScale: plan.cursor?.scale ?? 0,- zoomRegions: segmentZoom,- annotationRegions: segmentAnnotations,- speedRegions: segmentSpeed,- });- renderer.setCropRegion(segment.cropRegion);-- await decoder.decodeAll(- this.config.frameRate,- segmentTrims,- segmentSpeed,- async (videoFrame, _exportTs, sourceTimestampMs) => {- let webcamFrame: VideoFrame | null = null;- try {- if (this.cancelled) return;- if (this.fatalEncoderError) throw this.fatalEncoderError;-- const stopWebcam = timings.start("webcam");- webcamFrame = webcamFrameQueue- ? await webcamFrameQueue.frameAt(sourceTimestampMs)- : null;- stopWebcam();- if (this.cancelled) return;-- // Encoder timestamp = contiguous OUTPUT time (seamless joins);- // renderFrame gets SOURCE time so zoom/annotation/cursor match- // the frame's content even when speed retimes the segment.- const timestamp = frameIndex * frameDuration;- const stopRender = timings.start("render");- await renderer.renderFrame(videoFrame, sourceTimestampMs * 1000, webcamFrame);- stopRender();-- // Gate G0: everything renderFrame queued must EXECUTE before the- // next timer starts, so `fence` absorbs the compositor's real cost- // and the stages below stop being billed for it.- if (gpuFence) {- const stopFence = timings.start("fence");- renderer.finishGpuWork();- stopFence();- }-- if (dumpAt !== null && frameIndex === dumpAt) {- await dumpFrameToConsole(renderer.getCanvas(), frameIndex);- }-- // Both paths report the same two stages so the A/B diffs stage by- // stage: "readback" is getting pixels off the canvas, "encodeWait" is- // blocking on the consumer — the encoder queue, or the credit window.- if (compositeOnly) {- // Nothing downstream: the frame was composited and is dropped, so- // the wall measures the compositor and nothing else.- } else if (extractor) {- const stopExtract = timings.start("readback");- // The GPU->CPU descent happens here, inside copyTo — not in the- // VideoFrame constructor, which is lazy.- const bytes = await extractor.extract(renderer.getCanvas());- stopExtract();-- const stopShip = timings.start("encodeWait");- // IPC copies the buffer during send(), so the extractor is free to- // refill it as soon as this resolves. With no sink, the frame is- // discarded here: that IS the ceiling arm — the crossing costs zero.- if (sink) await sink.write(bytes);- stopShip();- } else {- const stopReadback = timings.start("readback");- const canvas = renderer.getCanvas();- let exportFrame: VideoFrame;- if (platform === "linux") {- const canvasCtx = canvas.getContext("2d")!;- const imageData = canvasCtx.getImageData(0, 0, canvas.width, canvas.height);- exportFrame = new VideoFrame(imageData.data.buffer, {- format: "RGBA",- codedWidth: canvas.width,- codedHeight: canvas.height,- timestamp,- duration: frameDuration,- colorSpace: {- primaries: "bt709",- transfer: "iec61966-2-1",- matrix: "rgb",- fullRange: true,- },- });- } else {- exportFrame = new VideoFrame(canvas, { timestamp, duration: frameDuration });- }- stopReadback();-- const stopEncodeWait = timings.start("encodeWait");- try {- await waitForEncoderQueueSpace({- getQueueSize: () => this.encoder?.encodeQueueSize ?? 0,- maxEncodeQueue,- isCancelled: () => this.cancelled,- encoderPreference,- });- } catch (error) {- exportFrame.close();- throw error;- }- stopEncodeWait();-- if (this.encoder && this.encoder.state === "configured") {- this.encodeQueue++;- const stopEncode = timings.start("encode");- this.encoder.encode(exportFrame, { keyFrame: frameIndex % 150 === 0 });- stopEncode();- }-- exportFrame.close();- }- frameIndex++;- this.reportProgress({- currentFrame: frameIndex,- totalFrames: estTotalFrames,- percentage: Math.min(100, (frameIndex / estTotalFrames) * 100),- estimatedTimeRemaining: 0,- });- } finally {- videoFrame.close();- webcamFrame?.close();- }- },- onWarning,- );- } finally {- stopWebcamDecode = true;- webcamFrameQueue?.destroy();- webcamDecoder?.cancel();- if (webcamDecodePromise) {- await webcamDecodePromise.catch(() => undefined);- }- if (this.webcamDecoder === webcamDecoder) this.webcamDecoder = null;- decoder.destroy();- if (this.streamingDecoder === decoder) this.streamingDecoder = null;- }- segmentFrameCounts.push(frameIndex - framesBeforeSegment);- }-- if (this.cancelled) {- // Leaves no orphaned ffmpeg behind, and unblocks anything parked on a- // credit that is never coming.- await sink?.cancel();- return { success: false, error: "Export cancelled" };- }- if (this.fatalEncoderError) {- throw this.fatalEncoderError;- }-- // Drain the in-flight window and close ffmpeg's stdin. This is where a- // truncated file would come from, so it happens before anything else.- const stopFlush = timings.start("flush");- const nativeOutput = sink ? await sink.finish() : null;- if (this.encoder && this.encoder.state === "configured") {- await this.withTimeout(- this.encoder.flush(),- ENCODER_FLUSH_TIMEOUT_MS,- encoderPreference === "prefer-hardware"- ? "The hardware video encoder stopped responding while finalizing the export."- : "The video encoder stopped responding while finalizing the export.",- );- }- stopFlush();- if (this.fatalEncoderError) {- throw this.fatalEncoderError;- }-- await Promise.all(this.muxingPromises);- this.reportProgress({- currentFrame: estTotalFrames,- totalFrames: estTotalFrames,- percentage: 100,- estimatedTimeRemaining: 0,- phase: "finalizing",- });-- // --- Audio: concatenate every segment's decoded PCM at the plan's offsets- // (sized from the REAL per-segment video frame counts so A/V stays locked),- // apply an equal-power fade at each join, then encode once and mux. The- // stretch was kicked off before the video loop so it overlapped the- // encodeWait idle time; the await below only measures the leftover- // (typically ~0ms on a successful overlap). ---- const stopAudioStretch = timings.start("audioStretch");- // Non-null: same gate condition (hasAudio && audioExportCodec && !cancelled)- // that produced a non-null promise also gates the if-block below.- const stretchedPcm = (await stretchedPcmPromise)!;- stopAudioStretch();-- const stopAudioEncode = timings.start("audioEncode");- // The decode and the WSOLA stretch above run on BOTH paths on purpose: they- // share the video loop's CPU, so dropping them under native would hand the- // native run a speedup the shipped product will never see. Only the encode- // and mux are WebCodecs-only — ffmpeg will take the PCM as a second input- // once the A/V-lock ordering is resolved (the plan needs the real frame- // counts, which only exist after the loop).- if (hasAudio && audioExportCodec && !this.cancelled && muxer) {- const audioPlan = buildAudioConcatPlan(- segments.map((s, i) => ({- clipId: s.clipId,- outputFrameCount: segmentFrameCounts[i] ?? 0,- hasAudio:- (segmentAudioPcm[i]?.length ?? 0) > 0 && (segmentAudioPcm[i]?.[0]?.length ?? 0) > 0,- })),- {- frameRate: this.config.frameRate,- sampleRate: AUDIO_OUTPUT_SAMPLE_RATE,- channels: AUDIO_OUTPUT_CHANNELS,- },- );- const assembled = assembleConcatenatedPcm(- stretchedPcm.map((pcm) => ({ pcm })),- audioPlan,- { boundaryFadeSamples: Math.round(AUDIO_OUTPUT_SAMPLE_RATE * AUDIO_BOUNDARY_FADE_SEC) },- );- this.audioProcessor = new AudioProcessor();- await this.audioProcessor.encodePcmToMuxer(- assembled,- AUDIO_OUTPUT_SAMPLE_RATE,- muxer,- audioExportCodec,- );- }-- stopAudioEncode();-- const wallMs = performance.now() - wallStart;- console.warn(- `[export perf] wall ${wallMs.toFixed(0)}ms · ${frameIndex} frames · ${(frameIndex / (wallMs / 1000)).toFixed(1)} fps\n` +- timings.formatSummary({ frames: frameIndex, hardwareAcceleration: encoderPreference }),- );-- // The shadow cache only pays off on frames whose geometry is still, so its- // miss rate — not the wall — is what says whether a moving camera leaves the- // per-frame shadow in place (rendering-architecture.md §13, Step 3).- const shadowStats = renderer.shadowCacheStats();- const shadowLookups = shadowStats.hits + shadowStats.misses;- if (shadowLookups > 0) {- const missPct = ((shadowStats.misses / shadowLookups) * 100).toFixed(1);- console.warn(- `[export perf] shadow cache: ${shadowStats.hits} hits, ${shadowStats.misses} misses (${missPct}% miss of ${shadowLookups})`,- );- }-- if (compositeOnly) {- warnings.push("Composite ceiling diagnostic: rendered only, no file was written.");- return { success: true, warnings };- }- if (dropFrames) {- warnings.push("Readback ceiling diagnostic: frames were discarded, no file was written.");- return { success: true, warnings };- }- if (nativeOutput) {- // Scaffold: ffmpeg already wrote the file, so there is no blob to hand- // back and the save flow does not yet know about it. The measurement is- // the point here; the save path lands with the WebCodecs removal.- warnings.push(`Native encode wrote ${nativeOutput.outputPath} (audio not muxed yet)`);- return { success: true, warnings };- }-- const blob = await muxer!.finalize();- return { success: true, blob, warnings: warnings.length > 0 ? warnings : undefined };- }-- private async initializeEncoder(hardwareAcceleration: HardwareAcceleration): Promise<void> {- this.encodeQueue = 0;- this.muxingPromises = [];- this.chunkCount = 0;- this.fatalEncoderError = null;- let videoDescription: Uint8Array | undefined;-- this.encoder = new VideoEncoder({- output: (chunk, meta) => {- if (meta?.decoderConfig?.description && !videoDescription) {- const desc = meta.decoderConfig.description;- if (desc instanceof ArrayBuffer || desc instanceof SharedArrayBuffer) {- videoDescription = new Uint8Array(desc);- } else if (ArrayBuffer.isView(desc)) {- videoDescription = new Uint8Array(desc.buffer, desc.byteOffset, desc.byteLength);- }- this.videoDescription = videoDescription;- }-- if (meta?.decoderConfig?.colorSpace && !this.videoColorSpace) {- this.videoColorSpace = meta.decoderConfig.colorSpace;- }-- const isFirstChunk = this.chunkCount === 0;- this.chunkCount++;-- const muxingPromise = (async () => {- try {- if (isFirstChunk && this.videoDescription) {- const colorSpace = this.videoColorSpace || {- primaries: "bt709",- transfer: "iec61966-2-1",- matrix: "rgb",- fullRange: true,- };-- const metadata: EncodedVideoChunkMetadata = {- decoderConfig: {- codec: this.config.codec || "avc1.640033",- codedWidth: this.config.width,- codedHeight: this.config.height,- description: this.videoDescription,- colorSpace,- },- };-- await this.muxer!.addVideoChunk(chunk, metadata);- } else {- await this.muxer!.addVideoChunk(chunk, meta);- }- } catch (error) {- console.error("Muxing error:", error);- }- })();-- this.muxingPromises.push(muxingPromise);- this.encodeQueue = Math.max(0, this.encodeQueue - 1);- },- error: (error) => {- console.error("[VideoExporter] Encoder error:", error);- this.fatalEncoderError =- error instanceof Error ? error : new Error(`Video encoder error: ${String(error)}`);- this.streamingDecoder?.cancel();- this.webcamDecoder?.cancel();- },- });-- const encoderConfig: VideoEncoderConfig = {- codec: this.config.codec || "avc1.640033",- width: this.config.width,- height: this.config.height,- bitrate: this.config.bitrate,- framerate: this.config.frameRate,- latencyMode: "quality",- bitrateMode: "variable",- hardwareAcceleration,- };-- const support = await VideoEncoder.isConfigSupported(encoderConfig);- if (!support.supported) {- throw new Error(- hardwareAcceleration === "prefer-hardware"- ? "Hardware video encoding is not supported on this system."- : "Software video encoding is not supported on this system.",- );- }-- console.log(- `[VideoExporter] Using ${hardwareAcceleration === "prefer-hardware" ? "hardware" : "software"} acceleration`,- );- this.encoder.configure(encoderConfig);- }-- cancel(): void {- this.cancelled = true;- if (this.streamingDecoder) {- this.streamingDecoder.cancel();- }- if (this.webcamDecoder) {- this.webcamDecoder.cancel();- }- if (this.audioProcessor) {- this.audioProcessor.cancel();- }- if (this.nativeSink) {- // Fire-and-forget: cancel() is sync by contract. Main kills the ffmpeg- // process tree, so an abandoned export leaves nothing running.- void this.nativeSink.cancel();- this.nativeSink = null;- }- this.cleanup();- }-- private cleanup(): void {- if (this.encoder) {- try {- if (this.encoder.state === "configured") {- this.encoder.close();- }- } catch (e) {- console.warn("Error closing encoder:", e);- }- this.encoder = null;- }-- if (this.streamingDecoder) {- try {- this.streamingDecoder.destroy();- } catch (e) {- console.warn("Error destroying streaming decoder:", e);- }- this.streamingDecoder = null;- }-- if (this.webcamDecoder) {- try {- this.webcamDecoder.destroy();- } catch (e) {- console.warn("Error destroying webcam decoder:", e);- }- this.webcamDecoder = null;- }-- if (this.renderer) {- try {- this.renderer.destroy();- } catch (e) {- console.warn("Error destroying renderer:", e);- }- this.renderer = null;- }-- this.audioProcessor = null;- this.muxer = null;- this.encodeQueue = 0;- this.muxingPromises = [];- this.chunkCount = 0;- this.videoDescription = undefined;- this.videoColorSpace = undefined;- this.fatalEncoderError = null;- }-- private getEncoderPreferences(): HardwareAcceleration[] {- // Hardware-first everywhere: the per-frame encode dominates export wall-time- // (Phase-0: encodeWait ≈ 90%), and hardware H.264 cuts it substantially. The- // export() retry loop falls back to prefer-software if the hardware attempt- // throws, so this only trades up when the hardware encoder actually works.- return ["prefer-hardware", "prefer-software"];- }-- private async trySourceCopyFastPath(videoInfo: SourceCopyVideoInfo) {- const blockers = getSourceCopyFastPathBlockers(this.config, videoInfo);- if (blockers.length > 0) {- console.info("[VideoExporter] source-copy fast path disabled", {- blockers,- output: { width: this.config.width, height: this.config.height },- source: videoInfo,- });- return null;- }-- const sourceBlob = await this.loadSourceBlob();- if (!sourceBlob || !isMp4Source(this.config.videoUrl, sourceBlob)) {- console.info("[VideoExporter] source-copy fast path disabled", {- blockers: ["source is not a readable MP4"],- source: videoInfo,- });- return null;- }-- if (this.cancelled) {- return { success: false, error: "Export cancelled" };- }-- this.reportProgress({- currentFrame: 1,- totalFrames: 1,- percentage: 100,- estimatedTimeRemaining: 0,- phase: "finalizing",- });- console.info("[VideoExporter] using source-copy fast path", {- source: videoInfo,- bytes: sourceBlob.size,- });-- return {- success: true,- blob: sourceBlob.type ? sourceBlob : new Blob([sourceBlob], { type: "video/mp4" }),- } satisfies ExportResult;- }-- private async loadSourceBlob() {- const videoUrl = this.config.videoUrl;- const isRemoteUrl = /^(https?:|blob:|data:)/i.test(videoUrl);-- if (!isRemoteUrl && window.electronAPI?.readBinaryFile) {- // The source-copy fast path reads the whole file into a Blob. That is- // impossible for recordings above Node's 2 GiB single-read cap, so bail- // out and let the (streaming) re-encode path handle them instead.- if (window.electronAPI.getReadableFileInfo) {- const info = await window.electronAPI.getReadableFileInfo(videoUrl);- if (- info.success &&- typeof info.size === "number" &&- info.size > MAX_IN_MEMORY_SOURCE_BYTES- ) {- return null;- }- }-- const result = await window.electronAPI.readBinaryFile(videoUrl);- if (!result.success || !result.data) {- return null;- }-- const type = videoUrl.toLowerCase().split(/[?#]/, 1)[0].endsWith(".mp4") ? "video/mp4" : "";- return new Blob([result.data], type ? { type } : undefined);- }-- const response = await fetch(videoUrl);- if (!response.ok) {- return null;- }-- return response.blob();- }-- private reportProgress(progress: ExportProgress): void {- this.config.onProgress?.(progress);- }-- private withTimeout<T>(promise: Promise<T>, timeoutMs: number, message: string): Promise<T> {- return new Promise<T>((resolve, reject) => {- const timer = window.setTimeout(() => reject(new Error(message)), timeoutMs);- promise.then(- (value) => {- window.clearTimeout(timer);- resolve(value);- },- (error) => {- window.clearTimeout(timer);- reject(error);- },- );- });- }-}diff --git a/src/lib/exporter/wgslFrameRenderer.ts b/src/lib/exporter/wgslFrameRenderer.tsdeleted file mode 100644index c8d4d5b87..000000000--- a/src/lib/exporter/wgslFrameRenderer.ts+++ /dev/null@@ -1,737 +0,0 @@-// WgslFrameRenderer — the §8b compositor, as a POC.-//-// Drop-in for FrameRenderer: same methods, same canvas out, so the existing-// decode / encode / mux / audio pipeline is untouched and the bench can put the-// two compositors in one interleaved run. That is the whole point of matching the-// interface — a POC that cannot be measured against what it replaces is a demo.-//-// What it is: WebGPU device, four textures, one uniform block, one draw call-// (plus the shadow's own passes). No Pixi, no Canvas2D, no six surfaces, no two GL-// contexts, no per-geometry cache.-//-// Both seams (§8c) stay on the device: the decoded VideoFrame enters as an-// external texture (zero copy), and the composited canvas leaves as-// `new VideoFrame(canvas)` to the encoder. Nothing descends to CPU RAM.-//-// NOT in the POC: captions/annotations (glyph rasterisation — a texture upload,-// cheap to add later), 3D rotation, the cursor. Scoped out with the user, and-// none of them changes the shape of what is measured here.--import type {- AnnotationRegion,- CameraFullscreenRegion,- CropRegion,- SpeedRegion,- WebcamMaskShape,- ZoomRegion,-} from "@/components/video-editor/types";-import type { Size, WebcamLayoutPreset, WebcamSizePreset } from "@/lib/compositeLayout";-import { COMPOSITE_WGSL } from "./wgsl/composite.wgsl";-import {- createEvaluateMemory,- type EvaluateLayout,- type EvaluateMemory,- type EvaluateScene,- evaluate,- evaluateLayout,- type FrameState,-} from "./wgsl/evaluate";-import {- boxesForStdDeviation,- SHADOW_WGSL,- shadowStages,- stdDeviationForBlur,-} from "./wgsl/shadowCascade.wgsl";--export interface WgslFrameRenderConfig {- width: number;- height: number;- wallpaper: string;- zoomRegions: ZoomRegion[];- cameraFullscreenRegions?: CameraFullscreenRegion[];- annotationRegions?: AnnotationRegion[];- speedRegions?: SpeedRegion[];- showShadow: boolean;- shadowIntensity: number;- showBlur: boolean;- motionBlurAmount?: number;- borderRadius?: number;- padding?: number;- cropRegion: CropRegion;- videoWidth: number;- videoHeight: number;- webcamSize?: Size | null;- webcamLayoutPreset?: WebcamLayoutPreset;- webcamMaskShape?: WebcamMaskShape;- webcamMirrored?: boolean;- webcamReactiveZoom?: boolean;- webcamSizePreset?: WebcamSizePreset;- webcamPosition?: { cx: number; cy: number } | null;- cursorTelemetry?: import("@/components/video-editor/types").CursorTelemetryPoint[];- platform: string;-}--const MASK_SHAPE_CODE: Record<string, number> = {- rectangle: 0,- rounded: 1,- circle: 2,- square: 3,-};--/** Uniform block: 28 floats = 112 bytes. §8b budgets ~200; there is room. */-const UNIFORM_FLOATS = 28;--export class WgslFrameRenderer {- private config: WgslFrameRenderConfig;- private canvas: HTMLCanvasElement | null = null;- private context: GPUCanvasContext | null = null;- private device: GPUDevice | null = null;-- private compositePipeline: GPURenderPipeline | null = null;- private uniformBuffer: GPUBuffer | null = null;- private uniformData = new Float32Array(UNIFORM_FLOATS);- private sampler: GPUSampler | null = null;- private backgroundTexture: GPUTexture | null = null;- /** Stands in for an absent webcam: an external texture binding cannot be null. */- private blankTexture: GPUTexture | null = null;-- private shadow: ShadowPasses | null = null;-- private layout: EvaluateLayout | null = null;- private layoutHasWebcam: boolean | null = null;- private memory: EvaluateMemory = createEvaluateMemory();- /** WebGPU reports validation failures out-of-band: a broken pass draws nothing- * and says nothing, which reads as a fast compositor rendering black. Scoped- * on the first frame only — enough to catch a structural mistake, and the- * popErrorScope sync is not something the steady state should pay for. */- private firstFrame = true;-- constructor(config: WgslFrameRenderConfig) {- this.config = config;- }-- async initialize(): Promise<void> {- if (!navigator.gpu) {- throw new Error("WebGPU unavailable: navigator.gpu is missing (needs a secure context)");- }- const adapter = await navigator.gpu.requestAdapter({ powerPreference: "high-performance" });- if (!adapter) throw new Error("WebGPU unavailable: no adapter");- const device = await adapter.requestDevice();- this.device = device;- // A device lost mid-export must not surface as a black frame or a silent- // hang: it is a failed export and must say so.- device.lost.then((info) => {- console.error(`[wgsl] GPU device lost: ${info.reason} — ${info.message}`);- });-- const canvas = document.createElement("canvas");- canvas.width = this.config.width;- canvas.height = this.config.height;- this.canvas = canvas;-- const context = canvas.getContext("webgpu");- if (!context) throw new Error("WebGPU unavailable: canvas has no webgpu context");- this.context = context;- context.configure({- device,- format: navigator.gpu.getPreferredCanvasFormat(),- alphaMode: "opaque",- // The composited texture is read back by `new VideoFrame(canvas)` — the- // encoder seam. Without COPY_SRC that read is illegal.- usage: GPUTextureUsage.RENDER_ATTACHMENT | GPUTextureUsage.COPY_SRC,- });-- this.sampler = device.createSampler({- magFilter: "linear",- minFilter: "linear",- addressModeU: "clamp-to-edge",- addressModeV: "clamp-to-edge",- });-- this.uniformBuffer = device.createBuffer({- size: UNIFORM_FLOATS * 4,- usage: GPUBufferUsage.UNIFORM | GPUBufferUsage.COPY_DST,- });-- const module = device.createShaderModule({ code: COMPOSITE_WGSL, label: "composite" });- this.compositePipeline = device.createRenderPipeline({- label: "composite",- layout: "auto",- vertex: { module, entryPoint: "vs" },- fragment: {- module,- entryPoint: "fs",- targets: [{ format: navigator.gpu.getPreferredCanvasFormat() }],- },- primitive: { topology: "triangle-list" },- });-- this.blankTexture = device.createTexture({- size: [1, 1],- format: "rgba8unorm",- usage: GPUTextureUsage.TEXTURE_BINDING | GPUTextureUsage.COPY_DST,- });-- await this.loadBackground();-- this.shadow = new ShadowPasses(device, this.config.width, this.config.height);- }-- /**- * The wallpaper, blurred ONCE at init.- *- * This is not the 2D cache in disguise: the wallpaper is a still image, so- * blurring it per frame would be recomputing a constant. The shadow is not a- * constant — it follows the camera — which is exactly why it is not cached.- */- private async loadBackground(): Promise<void> {- const device = this.device;- if (!device) return;- const { width, height } = this.config;-- const surface = document.createElement("canvas");- surface.width = width;- surface.height = height;- const ctx = surface.getContext("2d");- if (!ctx) throw new Error("2d context unavailable for wallpaper preparation");-- const wallpaper = this.config.wallpaper;- if (wallpaper && !wallpaper.startsWith("#") && !wallpaper.includes("gradient")) {- const url =- wallpaper.startsWith("/") || wallpaper.includes("://")- ? wallpaper- : `/wallpapers/${wallpaper}`;- try {- const image = await loadImage(url);- if (this.config.showBlur) ctx.filter = "blur(6px)";- ctx.drawImage(image, 0, 0, width, height);- ctx.filter = "none";- } catch (error) {- console.warn(`[wgsl] wallpaper ${url} failed to load, falling back to flat:`, error);- ctx.fillStyle = "#1e1e1e";- ctx.fillRect(0, 0, width, height);- }- } else {- ctx.fillStyle = wallpaper || "#1e1e1e";- ctx.fillRect(0, 0, width, height);- }-- this.backgroundTexture = device.createTexture({- size: [width, height],- format: "rgba8unorm",- usage:- GPUTextureUsage.TEXTURE_BINDING |- GPUTextureUsage.COPY_DST |- GPUTextureUsage.RENDER_ATTACHMENT,- });- device.queue.copyExternalImageToTexture(- { source: surface },- { texture: this.backgroundTexture },- [width, height],- );- }-- setSource(source: {- videoWidth: number;- videoHeight: number;- webcamSize?: Size | null;- zoomRegions?: ZoomRegion[];- annotationRegions?: AnnotationRegion[];- speedRegions?: SpeedRegion[];- cursorRecordingData?: unknown;- cursorScale?: number;- }): void {- this.config = {- ...this.config,- videoWidth: source.videoWidth,- videoHeight: source.videoHeight,- webcamSize: source.webcamSize ?? null,- zoomRegions: source.zoomRegions ?? this.config.zoomRegions,- annotationRegions: source.annotationRegions ?? this.config.annotationRegions,- speedRegions: source.speedRegions ?? this.config.speedRegions,- };- // A new segment is a new source: geometry must be recomputed, and the- // spring must not integrate across the cut.- this.layout = null;- this.layoutHasWebcam = null;- this.memory = createEvaluateMemory();- }-- setCropRegion(crop: CropRegion): void {- this.config = { ...this.config, cropRegion: crop };- this.layout = null;- }-- private scene(): EvaluateScene {- return {- outputSize: { width: this.config.width, height: this.config.height },- videoSize: { width: this.config.videoWidth, height: this.config.videoHeight },- webcamSize: this.config.webcamSize ?? null,- cropRegion: this.config.cropRegion,- padding: this.config.padding ?? 0,- borderRadius: this.config.borderRadius ?? 0,- shadowIntensity: this.config.showShadow ? this.config.shadowIntensity : 0,- motionBlurAmount: this.config.motionBlurAmount ?? 0,- zoomRegions: this.config.zoomRegions,- cameraFullscreenRegions: this.config.cameraFullscreenRegions ?? [],- webcamLayoutPreset: this.config.webcamLayoutPreset ?? "picture-in-picture",- webcamSizePreset: this.config.webcamSizePreset ?? 25,- webcamMaskShape: this.config.webcamMaskShape ?? "rectangle",- webcamPosition: this.config.webcamPosition ?? null,- webcamMirrored: this.config.webcamMirrored ?? false,- webcamReactiveZoom: this.config.webcamReactiveZoom ?? true,- cursorTelemetry: this.config.cursorTelemetry,- };- }-- async renderFrame(- videoFrame: VideoFrame,- timestampUs: number,- webcamFrame?: VideoFrame | null,- ): Promise<void> {- const device = this.device;- const context = this.context;- const pipeline = this.compositePipeline;- if (!device || !context || !pipeline || !this.uniformBuffer || !this.sampler) {- throw new Error("Renderer not initialized");- }-- const scene = this.scene();- const hasWebcam = !!webcamFrame;- if (!this.layout || this.layoutHasWebcam !== hasWebcam) {- this.layout = evaluateLayout(scene, hasWebcam);- this.layoutHasWebcam = hasWebcam;- }- if (!this.layout) throw new Error("Layout could not be evaluated");-- const timeMs = timestampUs / 1000;- const state = evaluate(scene, this.layout, timeMs, this.memory);- if (this.firstFrame) {- device.pushErrorScope("validation");- console.warn(- `[wgsl] frame 0 @${timeMs.toFixed(0)}ms: stage ${this.config.width}x${this.config.height}` +- ` · padding ${scene.padding} · preset ${scene.webcamLayoutPreset}` +- ` · maskRect ${fmtRect(this.layout.maskRect)}` +- ` · camera scale=${state.camera.scale.toFixed(3)} x=${state.camera.x.toFixed(0)} y=${state.camera.y.toFixed(0)}` +- ` · videoRect ${fmtRect(state.cameraRect)} r=${state.cameraBorderRadius.toFixed(1)}` +- ` · shadow ${state.shadowIntensity} · webcam ${- state.webcamRect ? fmtRect(state.webcamRect) : "none"- }`,- );- }-- // Seam S1: the decoded frame becomes a texture without leaving the device.- // External textures are valid for this task only — imported per frame, by- // design, and free.- const videoTex = device.importExternalTexture({ source: videoFrame });- const webcamTex = webcamFrame ? device.importExternalTexture({ source: webcamFrame }) : null;-- const encoder = device.createCommandEncoder({ label: "frame" });-- let shadowView: GPUTextureView;- if (state.shadowIntensity > 0 && this.shadow) {- shadowView = this.shadow.encode(encoder, state);- } else {- shadowView = this.shadow!.outputTexture.createView();- }-- this.writeUniforms(state, hasWebcam);- device.queue.writeBuffer(this.uniformBuffer, 0, this.uniformData);-- const bindGroup = device.createBindGroup({- layout: pipeline.getBindGroupLayout(0),- entries: [- { binding: 0, resource: { buffer: this.uniformBuffer } },- { binding: 1, resource: this.sampler },- { binding: 2, resource: videoTex },- {- binding: 3,- resource: webcamTex ?? device.importExternalTexture({ source: blankFrame() }),- },- { binding: 4, resource: this.backgroundTexture!.createView() },- { binding: 5, resource: shadowView },- ],- });-- const pass = encoder.beginRenderPass({- colorAttachments: [- {- view: context.getCurrentTexture().createView(),- clearValue: { r: 0, g: 0, b: 0, a: 1 },- loadOp: "clear",- storeOp: "store",- },- ],- });- pass.setPipeline(pipeline);- pass.setBindGroup(0, bindGroup);- pass.draw(3);- pass.end();-- device.queue.submit([encoder.finish()]);-- if (this.firstFrame) {- this.firstFrame = false;- const error = await device.popErrorScope();- if (error) console.error(`[wgsl] VALIDATION ERROR on frame 0: ${error.message}`);- else console.warn("[wgsl] frame 0 submitted with no validation error");- }- }-- /**- * Pack the uniform block. Field n lives at float 4n — the struct is all vec4f- * precisely so this can be true (see composite.wgsl.ts).- */- private writeUniforms(state: FrameState, hasWebcam: boolean): void {- const u = this.uniformData;- const w = state.webcamRect;- // Motion blur, in pixels, along the camera's direction of travel. The 2D- // path drives a Pixi filter from the same velocity; same input, same look.- const blurPx = state.velocity * (state.motionBlurAmount ?? 0) * 400;-- // a: stage.xy | videoRadius | shadowIntensity- u[0] = this.config.width;- u[1] = this.config.height;- u[2] = state.cameraBorderRadius;- u[3] = state.shadowIntensity;- // videoRect- u[4] = state.cameraRect.x;- u[5] = state.cameraRect.y;- u[6] = state.cameraRect.width;- u[7] = state.cameraRect.height;- // crop- u[8] = state.crop.x;- u[9] = state.crop.y;- u[10] = state.crop.width;- u[11] = state.crop.height;- // webcamRect- u[12] = w?.x ?? 0;- u[13] = w?.y ?? 0;- u[14] = w?.width ?? 0;- u[15] = w?.height ?? 0;- // b: webcamRadius | motionBlur.xy | unused. Blur runs along x: the camera's- // travel is dominated by the pan, and a single axis is what the 2D filter- // applies too.- u[16] = w?.borderRadius ?? 0;- u[17] = blurPx;- u[18] = 0;- u[19] = 0;- // flags: shape | mirrored | hasWebcam | hasShadow — floats, not u32, so the- // whole block is one Float32Array with no type interleaving.- u[20] = w ? (MASK_SHAPE_CODE[w.shape] ?? 0) : 0;- u[21] = state.webcamMirrored ? 1 : 0;- u[22] = hasWebcam && w ? 1 : 0;- u[23] = state.shadowIntensity > 0 ? 1 : 0;- // webcamSrc: the largest centred sub-rect of the camera with the BOX's aspect- // ratio — `object-fit: cover`, computed here because the box's ratio is not the- // camera's (a block layout hands it a column slot; Full Camera walks it out to- // the whole frame) and the shader would otherwise stretch the face into it.- const src = this.config.webcamSize;- const boxAspect = w && w.height > 0 ? w.width / w.height : 1;- const srcAspect = src && src.width > 0 && src.height > 0 ? src.width / src.height : boxAspect;- const cropW = srcAspect > boxAspect ? boxAspect / srcAspect : 1;- const cropH = srcAspect > boxAspect ? 1 : srcAspect / boxAspect;- u[24] = (1 - cropW) / 2;- u[25] = (1 - cropH) / 2;- u[26] = cropW;- u[27] = cropH;- }-- getCanvas(): HTMLCanvasElement {- if (!this.canvas) throw new Error("Renderer not initialized");- return this.canvas;- }-- /** Gate G0's fence, for arm parity with the Canvas2D renderer. */- finishGpuWork(): void {- // onSubmittedWorkDone is the device's own fence; the caller awaits nothing- // here because the encoder's VideoFrame(canvas) is the real sync point.- void this.device?.queue.onSubmittedWorkDone();- }-- /** No cache to report. Kept so the exporter can treat both renderers alike. */- shadowCacheStats(): { hits: number; misses: number } {- return { hits: 0, misses: 0 };- }-- destroy(): void {- this.backgroundTexture?.destroy();- this.blankTexture?.destroy();- this.shadow?.destroy();- this.uniformBuffer?.destroy();- this.device?.destroy();- this.device = null;- this.context = null;- this.canvas = null;- }-}--/**- * The shadow's passes: silhouette → 3 cascade stages, each a gaussian (3 box- * blurs, separable) then a composite → strip the silhouette.- *- * Six textures, allocated once. Two of them exist for a reason worth stating: a- * pass may not read and write the same texture, and a cascade stage reads BOTH- * its source and that source's blur. So the blur chain ping-pongs in its own pair- * (blurA/blurB) and never touches the stage's pair (stageA/stageB) — a single- * shared ping-pong silently overwrites the stage's source on the blur's second- * pass, which is a black shadow and a long afternoon.- */-class ShadowPasses {- readonly outputTexture: GPUTexture;- private device: GPUDevice;- private width: number;- private height: number;- private silhouette: GPUTexture;- private blurA: GPUTexture;- private blurB: GPUTexture;- private stageA: GPUTexture;- private stageB: GPUTexture;- private silhouettePipeline: GPURenderPipeline;- private boxPipeline: GPURenderPipeline;- private stagePipeline: GPURenderPipeline;- private stripPipeline: GPURenderPipeline;- private sampler: GPUSampler;- private silhouetteBuffer: GPUBuffer;- private stripBuffer: GPUBuffer;- private boxBuffers: GPUBuffer[] = [];- private stageBuffers: GPUBuffer[] = [];- private boxCursor = 0;- private stageCursor = 0;-- constructor(device: GPUDevice, width: number, height: number) {- this.device = device;- this.width = width;- this.height = height;-- const make = (label: string) =>- device.createTexture({- label,- size: [width, height],- format: "rgba8unorm",- usage: GPUTextureUsage.TEXTURE_BINDING | GPUTextureUsage.RENDER_ATTACHMENT,- });- this.silhouette = make("shadow-silhouette");- this.blurA = make("shadow-blur-a");- this.blurB = make("shadow-blur-b");- this.stageA = make("shadow-stage-a");- this.stageB = make("shadow-stage-b");- this.outputTexture = make("shadow-out");-- const module = device.createShaderModule({ code: SHADOW_WGSL, label: "shadow" });- const target: GPUColorTargetState[] = [{ format: "rgba8unorm" }];- const makePipeline = (entry: string, label: string) =>- device.createRenderPipeline({- label,- layout: "auto",- vertex: { module, entryPoint: "vs" },- fragment: { module, entryPoint: entry, targets: target },- primitive: { topology: "triangle-list" },- });- this.silhouettePipeline = makePipeline("fsSilhouette", "shadow-silhouette");- this.boxPipeline = makePipeline("fsBox", "shadow-box");- this.stagePipeline = makePipeline("fsStage", "shadow-stage");- this.stripPipeline = makePipeline("fsStrip", "shadow-strip");-- this.sampler = device.createSampler({- magFilter: "nearest",- minFilter: "nearest",- addressModeU: "clamp-to-edge",- addressModeV: "clamp-to-edge",- });- this.silhouetteBuffer = device.createBuffer({- size: 32,- usage: GPUBufferUsage.UNIFORM | GPUBufferUsage.COPY_DST,- });- this.stripBuffer = device.createBuffer({- size: 32,- usage: GPUBufferUsage.UNIFORM | GPUBufferUsage.COPY_DST,- });- }-- private boxBuffer(): GPUBuffer {- // One buffer per box pass per frame: a bind group must not read a buffer- // that a later pass in the same submit has overwritten.- if (this.boxCursor >= this.boxBuffers.length) {- this.boxBuffers.push(- this.device.createBuffer({- size: 16,- usage: GPUBufferUsage.UNIFORM | GPUBufferUsage.COPY_DST,- }),- );- }- return this.boxBuffers[this.boxCursor++];- }-- private stageBuffer(): GPUBuffer {- if (this.stageCursor >= this.stageBuffers.length) {- this.stageBuffers.push(- this.device.createBuffer({- size: 16,- usage: GPUBufferUsage.UNIFORM | GPUBufferUsage.COPY_DST,- }),- );- }- return this.stageBuffers[this.stageCursor++];- }-- encode(encoder: GPUCommandEncoder, state: FrameState): GPUTextureView {- this.boxCursor = 0;- this.stageCursor = 0;- const device = this.device;- const rect = state.cameraRect;- const radius = state.cameraBorderRadius;-- // a: stage.xy | radius | unused, then rect — vec4 each, no holes.- const geom = new Float32Array(8);- geom[0] = this.width;- geom[1] = this.height;- geom[2] = radius;- geom[3] = 0;- geom[4] = rect.x;- geom[5] = rect.y;- geom[6] = rect.width;- geom[7] = rect.height;- device.queue.writeBuffer(this.silhouetteBuffer, 0, geom);- device.queue.writeBuffer(this.stripBuffer, 0, geom);-- // 1. The silhouette.- this.drawInto(encoder, this.silhouettePipeline, this.silhouette, [- { binding: 0, resource: { buffer: this.silhouetteBuffer } },- ]);-- // 2. The cascade. Each stage blurs its input's alpha and composites the- // input back over it — so stage k+1 shadows stage k's shadow. That- // recursion is the falloff; it cannot collapse into one blur.- let current = this.silhouette;- let stageIndex = 0;- for (const stage of shadowStages(state.shadowIntensity)) {- const blurred = this.blur(encoder, current, stdDeviationForBlur(stage.blur));- // Alternating stage textures: dest is never `current` (the previous- // stage's output) and never `blurred` (which lives in the blur pair).- const dest = stageIndex % 2 === 0 ? this.stageA : this.stageB;-- const buffer = this.stageBuffer();- const data = new Float32Array(4);- data[0] = stage.offsetY / this.height;- data[1] = stage.alpha;- device.queue.writeBuffer(buffer, 0, data);-- this.drawInto(encoder, this.stagePipeline, dest, [- { binding: 0, resource: { buffer } },- { binding: 1, resource: this.sampler },- { binding: 2, resource: current.createView() },- { binding: 3, resource: blurred.createView() },- ]);- current = dest;- stageIndex++;- }-- // 3. Remove the silhouette; the recording covers that area itself.- this.drawInto(encoder, this.stripPipeline, this.outputTexture, [- { binding: 0, resource: { buffer: this.stripBuffer } },- { binding: 1, resource: this.sampler },- { binding: 2, resource: current.createView() },- ]);- return this.outputTexture.createView();- }-- /**- * One gaussian = three box blurs, per the SVG filter spec. Separable, so a- * d x d box costs 2d taps rather than d².- *- * Ping-pongs strictly inside (blurA, blurB): `src` belongs to the caller and- * is read again by the cascade stage after this returns, so it must survive.- */- private blur(encoder: GPUCommandEncoder, src: GPUTexture, stdDeviation: number): GPUTexture {- const boxes = boxesForStdDeviation(stdDeviation);- if (boxes.length === 0) return src;- let current = src;- let pass = 0;- for (const box of boxes) {- for (const axis of [0, 1]) {- const dest = pass % 2 === 0 ? this.blurA : this.blurB;- const buffer = this.boxBuffer();- const data = new ArrayBuffer(16);- const f = new Float32Array(data, 0, 2);- const i = new Int32Array(data, 8, 2);- f[0] = axis === 0 ? 1 / this.width : 0;- f[1] = axis === 0 ? 0 : 1 / this.height;- i[0] = box.width;- i[1] = box.offset;- this.device.queue.writeBuffer(buffer, 0, data);- this.drawInto(encoder, this.boxPipeline, dest, [- { binding: 0, resource: { buffer } },- { binding: 1, resource: this.sampler },- { binding: 2, resource: current.createView() },- ]);- current = dest;- pass++;- }- }- return current;- }-- private drawInto(- encoder: GPUCommandEncoder,- pipeline: GPURenderPipeline,- target: GPUTexture,- entries: GPUBindGroupEntry[],- ): void {- const pass = encoder.beginRenderPass({- colorAttachments: [- {- view: target.createView(),- clearValue: { r: 0, g: 0, b: 0, a: 0 },- loadOp: "clear",- storeOp: "store",- },- ],- });- pass.setPipeline(pipeline);- pass.setBindGroup(- 0,- this.device.createBindGroup({ layout: pipeline.getBindGroupLayout(0), entries }),- );- pass.draw(3);- pass.end();- }-- destroy(): void {- this.silhouette.destroy();- this.blurA.destroy();- this.blurB.destroy();- this.stageA.destroy();- this.stageB.destroy();- this.outputTexture.destroy();- this.silhouetteBuffer.destroy();- this.stripBuffer.destroy();- for (const b of this.boxBuffers) b.destroy();- for (const b of this.stageBuffers) b.destroy();- }-}--const fmtRect = (r: { x: number; y: number; width: number; height: number }) =>- `${r.x.toFixed(0)},${r.y.toFixed(0)} ${r.width.toFixed(0)}x${r.height.toFixed(0)}`;--function loadImage(url: string): Promise<HTMLImageElement> {- return new Promise((resolve, reject) => {- const image = new Image();- image.crossOrigin = "anonymous";- image.onload = () => resolve(image);- image.onerror = () => reject(new Error(`failed to load ${url}`));- image.src = url;- });-}--let blank: VideoFrame | null = null;-/** An external texture binding cannot be null, so an absent webcam gets 1x1 of nothing. */-function blankFrame(): VideoFrame {- if (!blank) {- const canvas = document.createElement("canvas");- canvas.width = 1;- canvas.height = 1;- blank = new VideoFrame(canvas, { timestamp: 0 });- }- return blank;-}diff --git a/src/main.tsx b/src/main.tsxindex 5090c6353..939360e62 100644--- a/src/main.tsx+++ b/src/main.tsx@@ -8,12 +8,6 @@ import "./index.css";const windowType = new URLSearchParams(window.location.search).get("windowType") || "";-// The export bench replaces the UI entirely rather than rendering alongside it,-// so nothing competes with the export for the GPU or the main thread.-if (windowType === "bench") {- void import("./bench/runBench").then((m) => m.runBench());-}-// Reclaim multi-GB OPFS source copies left behind by a previous session (they// are only pruned opportunistically during the next large-file load otherwise).// Nothing is referenced at startup, so everything stale is safe to remove.@@ -34,12 +28,10 @@ if (document.getElementById("root")?.style.setProperty("background", "transparent");}-if (windowType !== "bench") {- ReactDOM.createRoot(document.getElementById("root")!).render(- <React.StrictMode>- <I18nProvider>- <App />- </I18nProvider>- </React.StrictMode>,- );-}+ReactDOM.createRoot(document.getElementById("root")!).render(+ <React.StrictMode>+ <I18nProvider>+ <App />+ </I18nProvider>+ </React.StrictMode>,+);