OpenReel Video - Professional browser-based video editor. Open source CapCut alternative. 100% browser-based, no installation, no cloud uploads, no watermarks.
TypeScript
Sync 1.0 release prep: Premiere-gap tools, performance and CI fixes (#127)
Augustus Otu8f8b6c08fc12
diff --git a/apps/desktop/build/entitlements.mac.plist b/apps/desktop/build/entitlements.mac.plistindex 0c516c27..41b979f7 100644--- a/apps/desktop/build/entitlements.mac.plist+++ b/apps/desktop/build/entitlements.mac.plist@@ -5,5 +5,7 @@<key>com.apple.security.cs.allow-jit</key><true/><key>com.apple.security.cs.allow-unsigned-executable-memory</key><true/><key>com.apple.security.cs.disable-library-validation</key><true/>+ <key>com.apple.security.device.audio-input</key><true/>+ <key>com.apple.security.device.camera</key><true/></dict></plist>diff --git a/apps/desktop/electron-builder.yml b/apps/desktop/electron-builder.ymlindex 082675b0..d558213f 100644--- a/apps/desktop/electron-builder.yml+++ b/apps/desktop/electron-builder.yml@@ -55,6 +55,10 @@ mac:- target: ziparch: [arm64, x64]hardenedRuntime: true+ # Without these the hardened runtime blocks the microphone silently (voice-over, webcam recording).+ extendInfo:+ NSMicrophoneUsageDescription: OpenReel uses the microphone to record voice-overs and narration into your project.+ NSCameraUsageDescription: OpenReel uses the camera to record webcam clips into your project.gatekeeperAssess: falseentitlements: build/entitlements.mac.plistentitlementsInherit: build/entitlements.mac.plistdiff --git a/apps/desktop/src/main/index.ts b/apps/desktop/src/main/index.tsindex c4df0acf..d1cfa0e5 100644--- a/apps/desktop/src/main/index.ts+++ b/apps/desktop/src/main/index.ts@@ -36,6 +36,7 @@ import { applyWindowControl, windowIsMaximized } from "./window-controls";import { registerLinkedCompIpc } from "./linked-comp-windows";import { registerOnboardingIpc } from "./ipc/onboarding";import { registerOllamaIpc } from "./ipc/ollama";+import { installMediaPermissionHandlers, registerMicrophoneIpc } from "./ipc/microphone";import { registerSamplesIpc } from "./ipc/samples";import { registerFontsIpc } from "./ipc/fonts";import { registerMcpFilesIpc } from "./ipc/mcp-files";@@ -440,6 +441,8 @@ app.whenReady().then(() => {});registerOnboardingIpc();registerOllamaIpc();+ registerMicrophoneIpc();+ installMediaPermissionHandlers();registerSamplesIpc();registerFontsIpc();registerMcpFilesIpc();diff --git a/apps/desktop/src/main/ingest/proxy-args.ts b/apps/desktop/src/main/ingest/proxy-args.tsindex ca596da1..38806ca8 100644--- a/apps/desktop/src/main/ingest/proxy-args.ts+++ b/apps/desktop/src/main/ingest/proxy-args.ts@@ -18,6 +18,8 @@ export interface ProxyArgsSpec {const H264_ARGS = ["-c:v", "libx264", "-preset", "veryfast", "-crf", "24", "-g", "12", "-bf", "0", "-c:a", "aac", "-b:a", "128k"];// ProRes 422 Proxy: prores_ks profile 0, 10-bit 4:2:2, PCM audio (what QuickTime / Premiere / Resolve expect).+// DNxHR LB: dnxhd encoder, 8-bit 4:2:2, resolution independent; PCM audio like ProRes.+const DNXHR_ARGS = ["-c:v", "dnxhd", "-profile:v", "dnxhr_lb", "-c:a", "pcm_s16le"];const PRORES_ARGS = ["-c:v", "prores_ks", "-profile:v", "0", "-vendor", "apl0", "-c:a", "pcm_s16le"];/** ffmpeg arguments for one proxy job: a single decode feeding one or two outputs. */@@ -28,8 +30,18 @@ export function buildProxyArgs(spec: ProxyArgsSpec): string[] {const args = ["-y", "-hide_banner", "-nostdin", "-loglevel", "error"];if (spec.hwaccel !== false) args.push("-hwaccel", "auto");args.push("-i", spec.srcPath, "-threads", String(Math.max(1, spec.threads)));+ const dnxhr = spec.profile.codec === "dnxhr-lb";const prores = spec.profile.codec === "prores-proxy";- if (prores && spec.previewOutPath) {+ if (dnxhr && spec.previewOutPath) {+ args.push(+ "-filter_complex",+ `[0:v:0]${scale},split=2[a][b];[a]format=yuv422p[p];[b]format=yuv420p[h]`,+ "-map", "[p]", "-map", "0:a:0?", ...DNXHR_ARGS, "-f", "mov", spec.outPath,+ "-map", "[h]", "-map", "0:a:0?", ...H264_ARGS, "-movflags", "+faststart", "-f", "mp4", spec.previewOutPath,+ );+ } else if (dnxhr) {+ args.push("-vf", `${scale},format=yuv422p`, "-map", "0:v:0", "-map", "0:a:0?", ...DNXHR_ARGS, "-f", "mov", spec.outPath);+ } else if (prores && spec.previewOutPath) {args.push("-filter_complex",`[0:v:0]${scale},split=2[a][b];[a]format=yuv422p10le[p];[b]format=yuv420p[h]`,diff --git a/apps/desktop/src/main/ingest/proxy-runner.ts b/apps/desktop/src/main/ingest/proxy-runner.tsindex cd119c0b..240748b9 100644--- a/apps/desktop/src/main/ingest/proxy-runner.ts+++ b/apps/desktop/src/main/ingest/proxy-runner.ts@@ -3,6 +3,7 @@ import { promises as fs } from "node:fs";import os from "node:os";import path from "node:path";import { desktopPreviewTwinName } from "../../../../../packages/core/src/media/desktop-ingest";+import { isIntermediateProxyCodec } from "../../../../../packages/core/src/media/proxy-presets";import { resolveFfmpegPath } from "../sidecar/ffmpeg-path";import { buildProxyArgs, parseProgressSeconds } from "./proxy-args";import { probeMediaFile } from "./probe-media";@@ -82,8 +83,8 @@ export async function runProxyJob(if (!probe?.hasVideo || !probe.width || !probe.height) throw new Error("ffmpeg could not read a video stream from this file.");await fs.mkdir(job.outDir, { recursive: true });const outPath = path.join(job.outDir, job.fileName);- const prores = job.profile.codec === "prores-proxy";- const previewPath = prores && job.previewTwin ? path.join(job.outDir, desktopPreviewTwinName(job.fileName)) : undefined;+ const intermediate = isIntermediateProxyCodec(job.profile.codec);+ const previewPath = intermediate && job.previewTwin ? path.join(job.outDir, desktopPreviewTwinName(job.fileName)) : undefined;const part = `${outPath}.part`;const previewPart = previewPath ? `${previewPath}.part` : undefined;const cleanup = async (): Promise<void> => {@@ -133,7 +134,7 @@ export async function runProxyJob(height: out.height,duration: out.duration ?? duration,frameRate: out.frameRate ?? probe.frameRate ?? 0,- codec: out.videoCodec ?? (prores ? "prores" : "h264"),+ codec: out.videoCodec ?? (job.profile.codec === "prores-proxy" ? "prores" : job.profile.codec === "dnxhr-lb" ? "dnxhd" : "h264"),fileSize: stat.size,};}diff --git a/apps/desktop/src/main/ipc/export.ts b/apps/desktop/src/main/ipc/export.tsindex 575f15fc..266e7c87 100644--- a/apps/desktop/src/main/ipc/export.ts+++ b/apps/desktop/src/main/ipc/export.ts@@ -9,6 +9,7 @@ import { SmartExportSession, type SmartStreamMatch } from "../sidecar/smart-expoimport { CfrWriter } from "../sidecar/cfr";import { selectEncoder, getVerifiedEncoders, isHardwareEncoder } from "../sidecar/encoder-probe";import { join } from "node:path";+import { resolveEncoderChoice, type EncoderChoice } from "../../../../../packages/core/src/export/encoder-choice";import { appTempDir, newTempPathReady, releaseTemp, releaseTempSync } from "../temp-dir";import { acquirePowerHold, releasePowerHold, releaseAllPowerHolds } from "../power";import { isBroadcastExportCodec, isProres4444, type BroadcastScan, type DnxhrProfile, type ExportCodec, type EncodeMode } from "../sidecar/encode-args";@@ -30,6 +31,8 @@ interface ExportStartArgs {audioSampleRate: number;audioChannels: number;encodeMode?: "fast" | "balanced" | "smallest";+ /** Encoder picker. Absent or "auto" keeps the encode-mode ordering. */+ encoderChoice?: EncoderChoice;quality?: number;proresProfile?: "proxy" | "lt" | "standard" | "hq" | "4444" | "4444xq";dnxhrProfile?: DnxhrProfile;@@ -118,6 +121,8 @@ interface JobEntry {/** True once the renderer's "finish" has been delivered to the current job. */finishDelivered: boolean;retried: boolean;+ /** Hardware was chosen explicitly: a failure is reported, never retried on the software encoder. */+ strictHardware: boolean;cancelled: boolean;cfr: CfrWriter | null;port: MessagePortMain;@@ -208,6 +213,18 @@ export function broadcastExportFields(args: ExportStartArgs): Pick<ExportArgs, "return out;}+/**+ * Honour an explicit Hardware / Software choice for H.264, H.265 and AV1. Auto (or no choice) returns+ * null so the encode-mode ordering decides. Hardware never falls back: it throws with the reason.+ */+function pickChosenEncoder(args: ExportStartArgs, platform: NodeJS.Platform, usable: string[]): string | null {+ if (args.encoderChoice !== "hardware" && args.encoderChoice !== "software") return null;+ if (!["h264", "h265", "hevc", "av1"].includes(args.codec)) return null;+ const resolved = resolveEncoderChoice({ codec: args.codec, choice: args.encoderChoice, platform, available: usable });+ if (!resolved.encoder) throw new Error(resolved.reason ?? "The chosen encoder is not available.");+ return resolved.encoder;+}+export function resolveExportArgs(args: ExportStartArgs,platform: NodeJS.Platform,@@ -235,6 +252,14 @@ export function resolveExportArgs();}const twoPass = args.rateControl === "vbr2";+ const chosen = args.encoderChoice === "hardware" || args.encoderChoice === "software" ? args.encoderChoice : null;+ const choiceApplies = chosen !== null && (codec === "h264" || codec === "hevc" || codec === "av1");+ if (twoPass && choiceApplies && chosen === "hardware") {+ throw new Error("Hardware encoders have no two-pass mode. Choose Software or Auto for Two-pass VBR, or pick another rate control for Hardware.");+ }+ if (color && choiceApplies && chosen === "hardware") {+ throw new Error("Hardware encoding is not available with Rec.2020 / HDR output (it needs libx265 for the HDR metadata). Choose Software or Auto, or set the sequence colour space to Rec.709.");+ }if (twoPass) {if (codec !== "h264" && codec !== "hevc") throw new Error("Two-pass VBR is available for H.264 and H.265 only.");if (color) throw new Error("Two-pass VBR is not available with Rec.2020 / HDR output; use one-pass VBR or constant quality.");@@ -247,8 +272,11 @@ export function resolveExportArgs(throw new Error(`Two-pass VBR needs the ${twoPassEncoder} encoder, which this ffmpeg build does not include.`);}const encoder = twoPass ? twoPassEncoder : (broadcastEncoder ?? (color- ? selectColorEncoder(codec, color, usable, platform, mode)- : (selectEncoder(args.codec, platform, usable, mode) ?? "libx264")));+ ? (color.transfer === "bt709" && choiceApplies && chosen === "software" ? pickChosenEncoder(args, platform, usable) : null) ?? selectColorEncoder(codec, color, usable, platform, mode)+ : (pickChosenEncoder(args, platform, usable) ?? selectEncoder(args.codec, platform, usable, mode) ?? "libx264")));+ if (choiceApplies && chosen === "software" && isHardwareEncoder(encoder)) {+ throw new Error(`Software was chosen, but this export would use the hardware encoder ${encoder}. Choose Auto or Hardware, or install an ffmpeg build with the software encoder.`);+ }const hdrProres = !!color && codec === "prores" && color.transfer !== "bt709";return {...(color ? { color } : {}),@@ -348,6 +376,7 @@ export async function startExport(wc: WebContents, args: ExportStartArgs): PromireplayBytes: 0,finishDelivered: false,retried: false,+ strictHardware: args.encoderChoice === "hardware",cancelled: false,cfr: null,port: port1,@@ -523,7 +552,7 @@ function handleJobError(jobId: string, entry: JobEntry, failed: ExportJob, msg:const { encoder, codec, outputPath } = entry.exportArgs;const hardwareFailure = isHardwareEncoder(encoder) && !isOutputIoFailure(msg, outputPath);const software =- entry.retried || !hardwareFailure ? null : softwareFallbackEncoder(codec, encoder, entry.encoders);+ entry.retried || entry.strictHardware || !hardwareFailure ? null : softwareFallbackEncoder(codec, encoder, entry.encoders);if (software && entry.replay) {entry.retried = true;console.warn(`[export] ${encoder} failed, retrying with ${software}: ${msg}`);@@ -534,7 +563,11 @@ function handleJobError(jobId: string, entry: JobEntry, failed: ExportJob, msg:}entry.port.postMessage({type: "error",- message: hardwareFailure ? hardwareFailureMessage(encoder, msg) : msg,+ message: hardwareFailure+ ? entry.strictHardware+ ? `${msg}\nThe hardware encoder ${encoder} failed on this system. Hardware was chosen explicitly, so OpenReel did not switch to software. Choose Auto or Software and export again.`+ : hardwareFailureMessage(encoder, msg)+ : msg,});cleanupJob(jobId);}diff --git a/apps/desktop/src/main/ipc/microphone.ts b/apps/desktop/src/main/ipc/microphone.tsnew file mode 100644index 00000000..9693da19--- /dev/null+++ b/apps/desktop/src/main/ipc/microphone.ts@@ -0,0 +1,105 @@+import { shell, systemPreferences, session, type Session } from "electron";+import { z } from "zod";+import { handle } from "./index";+import { CHANNELS } from "../../shared/channels";+import type { MicrophoneAccess } from "../../shared/microphone";++/** Origins the app itself is served from: the packaged `app://` scheme and the Vite dev/preview hosts. */+export function isTrustedAppOrigin(url: string | undefined | null): boolean {+ if (!url) return false;+ try {+ const parsed = new URL(url);+ if (parsed.protocol === "app:") return parsed.hostname === "openreel";+ if (parsed.protocol === "http:" || parsed.protocol === "https:") {+ return ["localhost", "127.0.0.1", "[::1]"].includes(parsed.hostname);+ }+ } catch {+ // fall through+ }+ return false;+}++export interface MediaPermissionRequest {+ permission: string;+ requestingUrl: string;+ /** "audio" / "video" entries of a `media` request. */+ mediaTypes?: readonly string[];+ /** macOS TCC state for the microphone; other platforms report "granted". */+ micAccess: MicrophoneAccess;+}++/**+ * Whether a permission request may be granted. The app only ever loads its own pages, so those keep+ * Electron's default (grant); any other origin is refused. A microphone request additionally needs+ * the operating system to have granted access, so the renderer gets a clean NotAllowedError instead+ * of silence when macOS or Windows privacy settings block the device.+ */+export function decidePermission(request: MediaPermissionRequest): boolean {+ if (!isTrustedAppOrigin(request.requestingUrl)) return false;+ if (request.permission !== "media") return true;+ const wantsAudio = (request.mediaTypes ?? ["audio"]).includes("audio");+ if (wantsAudio && (request.micAccess === "denied" || request.micAccess === "restricted")) return false;+ return true;+}++export function readMicrophoneAccess(platform: NodeJS.Platform = process.platform): MicrophoneAccess {+ if (platform !== "darwin" && platform !== "win32") return "granted";+ try {+ const status = systemPreferences.getMediaAccessStatus("microphone");+ return status === "unknown" ? "not-determined" : status;+ } catch {+ return "not-determined";+ }+}++/** Resolves once the OS prompt (macOS only) has been answered; elsewhere reports the current state. */+export async function requestMicrophoneAccess(): Promise<MicrophoneAccess> {+ const current = readMicrophoneAccess();+ if (process.platform === "darwin" && current === "not-determined") {+ try {+ await systemPreferences.askForMediaAccess("microphone");+ } catch {+ // The status read below reports the outcome either way.+ }+ return readMicrophoneAccess();+ }+ return current;+}++export function microphoneSettingsUrl(platform: NodeJS.Platform = process.platform): string | null {+ if (platform === "darwin") return "x-apple.systempreferences:com.apple.preference.security?Privacy_Microphone";+ if (platform === "win32") return "ms-settings:privacy-microphone";+ return null;+}++export function installMediaPermissionHandlers(target: Session = session.defaultSession): void {+ target.setPermissionRequestHandler((webContents, permission, callback, details) => {+ const mediaTypes = (details as { mediaTypes?: string[] }).mediaTypes;+ const wantsAudio = permission === "media" && (mediaTypes ?? ["audio"]).includes("audio");+ void (wantsAudio ? requestMicrophoneAccess() : Promise.resolve(readMicrophoneAccess())).then((micAccess) => {+ callback(+ decidePermission({ permission, requestingUrl: details.requestingUrl || webContents.getURL(), mediaTypes, micAccess }),+ );+ });+ });+ target.setPermissionCheckHandler((webContents, permission, requestingOrigin, details) => {+ const mediaType = (details as { mediaType?: string }).mediaType;+ return decidePermission({+ permission,+ requestingUrl: requestingOrigin || webContents?.getURL() || "",+ mediaTypes: mediaType && mediaType !== "unknown" ? [mediaType] : undefined,+ micAccess: mediaType === "audio" ? readMicrophoneAccess() : "granted",+ });+ });+}++export function registerMicrophoneIpc(): void {+ handle(CHANNELS.microphoneStatus, z.undefined(), (): MicrophoneAccess => readMicrophoneAccess());+ handle(CHANNELS.microphoneRequest, z.undefined(), (): Promise<MicrophoneAccess> => requestMicrophoneAccess());+ handle(CHANNELS.microphoneOpenSettings, z.undefined(), async (): Promise<boolean> => {+ const url = microphoneSettingsUrl();+ if (!url) return false;+ await shell.openExternal(url);+ return true;+ });+}diff --git a/apps/desktop/src/preload/index.ts b/apps/desktop/src/preload/index.tsindex fc506562..68944e12 100644--- a/apps/desktop/src/preload/index.ts+++ b/apps/desktop/src/preload/index.ts@@ -20,6 +20,11 @@ contextBridge.exposeInMainWorld("openreel", {ollama: {probe: () => ipcRenderer.invoke(CHANNELS.ollamaProbe, undefined),},+ microphone: {+ status: () => ipcRenderer.invoke(CHANNELS.microphoneStatus, undefined),+ request: () => ipcRenderer.invoke(CHANNELS.microphoneRequest, undefined),+ openSettings: () => ipcRenderer.invoke(CHANNELS.microphoneOpenSettings, undefined),+ },samples: {list: () => ipcRenderer.invoke(CHANNELS.samplesList, undefined),get: (id: string) => ipcRenderer.invoke(CHANNELS.samplesGet, { id }),@@ -98,8 +103,8 @@ contextBridge.exposeInMainWorld("openreel", {},export: {start: (args: unknown) =>- new Promise((resolve) => {- ipcRenderer.once("openreel:export-port", (event, meta) => {+ new Promise((resolve, reject) => {+ const onPort = (event: Electron.IpcRendererEvent, meta: unknown) => {const { jobId } = meta as { jobId: string };const [port] = event.ports;// A live MessagePort cannot survive contextBridge serialization into@@ -107,8 +112,13 @@ contextBridge.exposeInMainWorld("openreel", {// documented Electron path) and resolve with just the jobId.window.postMessage({ __openreelExportPort: true, jobId }, "*", [port]);resolve({ jobId });+ };+ ipcRenderer.once("openreel:export-port", onPort);+ // A refused start (for example Hardware with Two-pass VBR) rejects here instead of waiting for a port that never arrives.+ ipcRenderer.invoke(CHANNELS.exportStart, args).catch((error: unknown) => {+ ipcRenderer.removeListener("openreel:export-port", onPort);+ reject(error);});- ipcRenderer.invoke(CHANNELS.exportStart, args);}),writeAudioWav: (jobId: string, wav: ArrayBuffer) =>ipcRenderer.invoke(CHANNELS.exportWriteAudioWav, { jobId, wav }),diff --git a/apps/desktop/src/shared/channels.ts b/apps/desktop/src/shared/channels.tsindex be7f4608..42a768ee 100644--- a/apps/desktop/src/shared/channels.ts+++ b/apps/desktop/src/shared/channels.ts@@ -90,6 +90,9 @@ export const CHANNELS = {onboardingGet: "openreel:onboarding:get",onboardingSet: "openreel:onboarding:set",ollamaProbe: "openreel:ollama:probe",+ microphoneStatus: "openreel:microphone:status",+ microphoneRequest: "openreel:microphone:request",+ microphoneOpenSettings: "openreel:microphone:openSettings",samplesList: "openreel:samples:list",samplesGet: "openreel:samples:get",fontsBrotliDecompress: "openreel:fonts:brotliDecompress",diff --git a/apps/desktop/src/shared/ipc-contract.ts b/apps/desktop/src/shared/ipc-contract.tsindex c3e928f9..d78819ed 100644--- a/apps/desktop/src/shared/ipc-contract.ts+++ b/apps/desktop/src/shared/ipc-contract.ts@@ -311,7 +311,7 @@ export const windowControlArgsSchema = z.object({const ingestConfigSchema = z.object({- proxyProfile: z.object({ codec: z.enum(["prores-proxy", "h264"]), size: z.enum(["half", "quarter", "720p", "1080p"]) }).optional(),+ proxyProfile: z.object({ codec: z.enum(["prores-proxy", "h264", "dnxhr-lb"]), size: z.enum(["half", "quarter", "720p", "1080p"]) }).optional(),proxyFolder: z.string().min(1).optional(),mediaFolder: z.string().min(1).optional(),concurrency: z.union([z.literal(1), z.literal(2)]).optional(),@@ -333,7 +333,7 @@ export const ingestProxyEnqueueArgsSchema = ingestProjectSchema.extend({mediaId: z.string().min(1),name: z.string().min(1),srcPath: z.string().min(1),- profile: z.object({ codec: z.enum(["prores-proxy", "h264"]), size: z.enum(["half", "quarter", "720p", "1080p"]) }),+ profile: z.object({ codec: z.enum(["prores-proxy", "h264", "dnxhr-lb"]), size: z.enum(["half", "quarter", "720p", "1080p"]) }),previewTwin: z.boolean(),}),)diff --git a/apps/desktop/src/shared/microphone.ts b/apps/desktop/src/shared/microphone.tsnew file mode 100644index 00000000..424c905e--- /dev/null+++ b/apps/desktop/src/shared/microphone.ts@@ -0,0 +1,2 @@+/** Operating-system microphone permission, as reported by Electron's systemPreferences. */+export type MicrophoneAccess = "not-determined" | "granted" | "denied" | "restricted";diff --git a/apps/desktop/test/export-integration.test.ts b/apps/desktop/test/export-integration.test.tsindex d22cfb06..07d2fdca 100644--- a/apps/desktop/test/export-integration.test.ts+++ b/apps/desktop/test/export-integration.test.ts@@ -138,19 +138,27 @@ describe.skipIf(!HAS_FFMPEG)("native export integration", () => {proresOut,]);let stderr = "";+ let closed = false;proc.stderr.on("data", (chunk: Buffer) => { stderr += chunk.toString(); });+ // An unavailable encoder makes ffmpeg exit before reading every frame;+ // the late writes then fail with EPIPE, which the close handler reports.+ proc.stdin.on("error", () => undefined);proc.on("error", reject);proc.on("close", (code) => {+ closed = true;if (code === 0) resolve();else reject(new Error(`ffmpeg (${encoder}) exited with code ${code}\n${stderr.slice(-2000)}`));});(async () => {- for (let i = 0; i < FPS; i++) {+ for (let i = 0; i < FPS && !closed; i++) {if (!proc.stdin.write(frame)) {- await new Promise<void>((r) => proc.stdin.once("drain", r));+ await new Promise<void>((r) => {+ proc.stdin.once("drain", r);+ proc.stdin.once("close", r);+ });}}- proc.stdin.end();+ if (!closed) proc.stdin.end();})().catch(reject);});diff --git a/apps/desktop/test/ingest-electron.test.ts b/apps/desktop/test/ingest-electron.test.tsindex 582a0853..19a24608 100644--- a/apps/desktop/test/ingest-electron.test.ts+++ b/apps/desktop/test/ingest-electron.test.ts@@ -261,11 +261,26 @@ d("desktop ingest in real Electron", () => {expect(historyBefore + 3).toBe(await E(page, "h.project.getState().actionExecutor.getHistory().getUndoStackSize()"));// Preview: place the clip, look through the proxy, toggle, look at the original.+ const rendererWarnings: string[] = [];+ page.on("console", (m: any) => {+ if (m.type() === "warning" || m.type() === "error") rendererWarnings.push(`${m.type()}: ${String(m.text()).slice(0, 240)}`);+ });const clip = await placeClip(page, "clip4k.mp4");- await page.waitForFunction((mid: string) => (window as any).__openreelE2E.proxy.cache.store.getState().entries[mid]?.status === "ready", id, { timeout: 120_000 });+ // The preview cache entry must be "ready" and stay that way while the clip is looked at. Fail at once, with the+ // reason, if playback disables the proxy (status "error") instead of idling out the full timeout.+ const proxyEntry = () => E(page, `(() => { const e = h.proxy.cache.store.getState().entries["${id}"]; return e ? { status: e.status, error: e.error ?? null } : null; })()`);+ const watchStart = Date.now();+ for (;;) {+ const entry = await proxyEntry();+ if (entry?.status === "ready") break;+ if (entry?.status === "error") throw new Error(`the preview proxy was disabled: ${entry.error}; renderer: ${rendererWarnings.slice(-6).join(" | ")}`);+ if (Date.now() - watchStart > 120_000) throw new Error(`preview cache entry never became ready (${JSON.stringify(entry)}); renderer: ${rendererWarnings.slice(-6).join(" | ")}`);+ await sleep(250);+ }await seekTo(page, clip.start + 1.2);await sleep(2000);const viaProxy = await decodeLog(page, id);+ expect((await proxyEntry())?.status, `proxy still enabled after the first preview frame; renderer: ${rendererWarnings.slice(-6).join(" | ")}`).toBe("ready");console.log(`[desktop-ingest] preview decode log, proxies on: ${JSON.stringify(viaProxy)}`);expect(viaProxy?.source).toBe("proxy");expect(viaProxy!.proxy).toBeGreaterThan(0);diff --git a/apps/desktop/test/microphone-permission.test.ts b/apps/desktop/test/microphone-permission.test.tsnew file mode 100644index 00000000..32566db7--- /dev/null+++ b/apps/desktop/test/microphone-permission.test.ts@@ -0,0 +1,64 @@+import { describe, expect, it, vi } from "vitest";++vi.mock("electron", () => ({+ shell: { openExternal: vi.fn() },+ systemPreferences: { getMediaAccessStatus: vi.fn(), askForMediaAccess: vi.fn() },+ session: { defaultSession: {} },+}));++import { CHANNELS } from "../src/shared/channels";+import { decidePermission, isTrustedAppOrigin, microphoneSettingsUrl } from "../src/main/ipc/microphone";++describe("isTrustedAppOrigin", () => {+ it("trusts the packaged scheme and loopback dev hosts only", () => {+ expect(isTrustedAppOrigin("app://openreel/index.html")).toBe(true);+ expect(isTrustedAppOrigin("http://localhost:5173/")).toBe(true);+ expect(isTrustedAppOrigin("http://127.0.0.1:5391")).toBe(true);+ expect(isTrustedAppOrigin("app://evil/index.html")).toBe(false);+ expect(isTrustedAppOrigin("https://example.com/")).toBe(false);+ expect(isTrustedAppOrigin("")).toBe(false);+ expect(isTrustedAppOrigin("not a url")).toBe(false);+ });+});++describe("decidePermission", () => {+ const base = { requestingUrl: "app://openreel/index.html", micAccess: "granted" as const };++ it("grants a microphone request from the app once the OS allows it", () => {+ expect(decidePermission({ ...base, permission: "media", mediaTypes: ["audio"] })).toBe(true);+ });++ it("refuses the microphone when macOS or Windows privacy settings block it", () => {+ expect(decidePermission({ ...base, permission: "media", mediaTypes: ["audio"], micAccess: "denied" })).toBe(false);+ expect(decidePermission({ ...base, permission: "media", mediaTypes: ["audio"], micAccess: "restricted" })).toBe(false);+ });++ it("does not let a blocked microphone stop a camera-only request", () => {+ expect(decidePermission({ ...base, permission: "media", mediaTypes: ["video"], micAccess: "denied" })).toBe(true);+ });++ it("refuses every request from a foreign origin", () => {+ expect(decidePermission({ ...base, requestingUrl: "https://example.com/", permission: "media", mediaTypes: ["audio"] })).toBe(false);+ expect(decidePermission({ ...base, requestingUrl: "https://example.com/", permission: "clipboard-read" })).toBe(false);+ });++ it("keeps the default grant for the app's own non-media permissions", () => {+ expect(decidePermission({ ...base, permission: "fullscreen" })).toBe(true);+ });+});++describe("microphone settings", () => {+ it("deep-links to the privacy pane where one exists", () => {+ expect(microphoneSettingsUrl("darwin")).toContain("Privacy_Microphone");+ expect(microphoneSettingsUrl("win32")).toBe("ms-settings:privacy-microphone");+ expect(microphoneSettingsUrl("linux")).toBeNull();+ });++ it("freezes the channel names the preload bridge uses", () => {+ expect(CHANNELS).toMatchObject({+ microphoneStatus: "openreel:microphone:status",+ microphoneRequest: "openreel:microphone:request",+ microphoneOpenSettings: "openreel:microphone:openSettings",+ });+ });+});diff --git a/apps/desktop/test/proxy-preset-args.test.ts b/apps/desktop/test/proxy-preset-args.test.tsnew file mode 100644index 00000000..407352da--- /dev/null+++ b/apps/desktop/test/proxy-preset-args.test.ts@@ -0,0 +1,79 @@+import { describe, expect, it, vi } from "vitest";++vi.mock("electron", () => ({ app: { isPackaged: false } }));++import { buildProxyArgs } from "../src/main/ingest/proxy-args";+import { resolveExportArgs } from "../src/main/ipc/export";+import { PROXY_PRESETS } from "../../../packages/core/src/media/proxy-presets";++const spec = { srcPath: "/in.mov", outPath: "/o.mov.part", srcWidth: 3840, srcHeight: 2160, threads: 2 };+const after = (args: string[], flag: string): string => args[args.indexOf(flag) + 1];+const preset = (id: string) => PROXY_PRESETS.find((p) => p.id === id)!.profile;++describe("proxy preset ffmpeg arguments", () => {+ it("ProRes Proxy: prores_ks profile 0, 4:2:2 10-bit, half size", () => {+ const a = buildProxyArgs({ ...spec, profile: preset("prores-proxy") });+ expect(after(a, "-c:v")).toBe("prores_ks");+ expect(after(a, "-profile:v")).toBe("0");+ expect(after(a, "-vf")).toContain("scale=1920:1080");+ expect(after(a, "-vf")).toContain("yuv422p10le");+ });+ it("H.264 half and quarter differ only in size", () => {+ const half = buildProxyArgs({ ...spec, outPath: "/o.mp4.part", profile: preset("h264-half") });+ const quarter = buildProxyArgs({ ...spec, outPath: "/o.mp4.part", profile: preset("h264-quarter") });+ expect(after(half, "-c:v")).toBe("libx264");+ expect(after(half, "-vf")).toContain("scale=1920:1080");+ expect(after(quarter, "-vf")).toContain("scale=960:540");+ expect(half).toContain("+faststart");+ });+ it("DNxHR LB: dnxhd encoder with the dnxhr_lb profile, 8-bit 4:2:2 in a mov", () => {+ const a = buildProxyArgs({ ...spec, profile: preset("dnxhr-lb") });+ expect(after(a, "-c:v")).toBe("dnxhd");+ expect(after(a, "-profile:v")).toBe("dnxhr_lb");+ expect(after(a, "-vf")).toContain("format=yuv422p");+ expect(after(a, "-f")).toBe("mov");+ });+ it("DNxHR LB with a preview twin writes the intermediate and an H.264 mp4 from one decode", () => {+ const a = buildProxyArgs({ ...spec, profile: preset("dnxhr-lb"), previewOutPath: "/o.preview.mp4.part" });+ expect(a.filter((x) => x === "-c:v")).toHaveLength(2);+ expect(a).toContain("dnxhd");+ expect(a).toContain("libx264");+ expect(a.filter((x) => x === "-i")).toHaveLength(1);+ });+});++describe("export encoder choice reaches the encoder", () => {+ const start = { width: 1920, height: 1080, frameRate: 30, codec: "h264", format: "mp4", bitrateKbps: 8000, outputPath: "/tmp/x.mp4", totalFrames: 10, audioSampleRate: 48000, audioChannels: 2 };+ const encoders = ["libx264", "h264_videotoolbox"];+ const run = (choice: "auto" | "hardware" | "software" | undefined, available = encoders) =>+ resolveExportArgs({ ...start, ...(choice ? { encoderChoice: choice } : {}) }, "darwin", available, "/tmp/a.wav").encoder;+ it("Software forces libx264 even in a hardware-first mode", () => {+ expect(run("software")).toBe("libx264");+ });+ it("Hardware and Auto use VideoToolbox when present", () => {+ expect(run("hardware")).toBe("h264_videotoolbox");+ expect(run("auto")).toBe("h264_videotoolbox");+ expect(run(undefined)).toBe("h264_videotoolbox");+ });+ it("Hardware refuses, with a reason, when no hardware encoder works; Auto falls back", () => {+ expect(() => run("hardware", ["libx264"])).toThrow(/VideoToolbox/);+ expect(run("auto", ["libx264"])).toBe("libx264");+ });+ const hevc = { ...start, codec: "h265", outputPath: "/tmp/x.mov", format: "mov" };+ const pq = { primaries: "bt2020", transfer: "pq", bitDepth: 10, chroma: "420" } as const;+ const go = (over: Record<string, unknown>, available = ["libx264", "libx265", "h264_videotoolbox", "hevc_videotoolbox"]) =>+ resolveExportArgs({ ...hevc, ...over } as never, "darwin", available, "/tmp/a.wav").encoder;+ it("Hardware with Two-pass VBR is refused, not silently switched to libx264", () => {+ expect(() => go({ codec: "h264", encoderChoice: "hardware", rateControl: "vbr2" })).toThrow(/two-pass/i);+ expect(go({ codec: "h264", encoderChoice: "software", rateControl: "vbr2" })).toBe("libx264");+ });+ it("Hardware with Rec.2020 output is refused; Software gets libx265", () => {+ expect(() => go({ encoderChoice: "hardware", color: pq })).toThrow(/Rec\.2020/);+ expect(go({ encoderChoice: "software", color: pq })).toBe("libx265");+ });+ it("Software never ends up on a hardware encoder under colour output", () => {+ const sdr2020 = { ...pq, transfer: "bt709" };+ expect(go({ encoderChoice: "software", color: sdr2020 })).toBe("libx265");+ expect(() => go({ encoderChoice: "software", color: pq }, ["hevc_videotoolbox"])).toThrow();+ });+});diff --git a/apps/desktop/test/proxy-preset-ffmpeg.integration.test.ts b/apps/desktop/test/proxy-preset-ffmpeg.integration.test.tsnew file mode 100644index 00000000..cd901c9b--- /dev/null+++ b/apps/desktop/test/proxy-preset-ffmpeg.integration.test.ts@@ -0,0 +1,37 @@+import { beforeAll, describe, expect, it, vi } from "vitest";+import { execFileSync, spawnSync } from "node:child_process";+import { mkdtempSync, existsSync } from "node:fs";+import { tmpdir } from "node:os";+import { join } from "node:path";++vi.mock("electron", () => ({ app: { isPackaged: false } }));++import { buildProxyArgs } from "../src/main/ingest/proxy-args";+import { PROXY_PRESETS } from "../../../packages/core/src/media/proxy-presets";++const have = spawnSync("ffmpeg", ["-version"]).status === 0;++// Runs every proxy preset through a real ffmpeg and checks the file it writes with ffprobe.+describe.skipIf(!have)("proxy presets produce real files with ffmpeg", () => {+ // describe.skipIf still runs this callback to collect tests, so the ffmpeg work must wait for beforeAll.+ const dir = mkdtempSync(join(tmpdir(), "openreel-proxy-preset-"));+ const src = join(dir, "src.mp4");+ beforeAll(() => execFileSync("ffmpeg", ["-v", "error", "-f", "lavfi", "-i", "testsrc2=size=1280x720:rate=24:duration=1", "-f", "lavfi", "-i", "sine=duration=1", "-c:v", "libx264", "-pix_fmt", "yuv420p", "-c:a", "aac", "-shortest", "-y", src]));+ const probe = (file: string) =>+ JSON.parse(execFileSync("ffprobe", ["-v", "error", "-select_streams", "v:0", "-show_entries", "stream=codec_name,width,height", "-of", "json", file]).toString()).streams[0] as { codec_name: string; width: number; height: number };++ for (const preset of PROXY_PRESETS) {+ it(`${preset.id}`, () => {+ const ext = preset.profile.codec === "h264" ? "mp4" : "mov";+ const out = join(dir, `${preset.id}.${ext}`);+ const args = buildProxyArgs({ srcPath: src, outPath: out, srcWidth: 1280, srcHeight: 720, threads: 2, profile: preset.profile });+ const run = spawnSync("ffmpeg", ["-y", ...args], { encoding: "utf8" });+ expect(run.status, run.stderr).toBe(0);+ expect(existsSync(out)).toBe(true);+ const v = probe(out);+ const expected = { "prores-proxy": "prores", "h264-half": "h264", "h264-quarter": "h264", "dnxhr-lb": "dnxhd" }[preset.id];+ if (expected) expect(v.codec_name).toBe(expected);+ expect(v.width).toBeLessThanOrEqual(1280);+ });+ }+});diff --git a/apps/desktop/test/proxy-presets-electron.test.ts b/apps/desktop/test/proxy-presets-electron.test.tsnew file mode 100644index 00000000..19021c78--- /dev/null+++ b/apps/desktop/test/proxy-presets-electron.test.ts@@ -0,0 +1,299 @@+/**+ * Real-Electron test for the proxy presets (Create Proxies dialog, Proxies panel preset selector, DNxHR LB,+ * preview twin, toggle-proxies) and for the hardware / software encoder choice on the ffmpeg sidecar.+ * Same build and opt-in as ingest-electron.test.ts (OPENREEL_DESKTOP_E2E=1, VITE_OPENREEL_E2E=1 desktop build).+ */+import { createRequire } from "node:module";+import { execFileSync, spawnSync } from "node:child_process";+import { createHash } from "node:crypto";+import fs from "node:fs";+import os from "node:os";+import path from "node:path";+import { afterAll, beforeAll, describe, expect, it } from "vitest";++const root = path.resolve(__dirname, "../../..");+const FFMPEG = process.env.FFMPEG ?? "/opt/homebrew/bin/ffmpeg";+const FFPROBE = process.env.FFPROBE ?? "/opt/homebrew/bin/ffprobe";+const enabled =+ process.env.OPENREEL_DESKTOP_E2E === "1" &&+ fs.existsSync(FFMPEG) &&+ fs.existsSync(path.join(root, "apps/desktop/dist/main/index.js")) &&+ fs.existsSync(path.join(root, "apps/web/dist/index.html"));+const d = enabled ? describe : describe.skip;++const require = createRequire(path.join(root, "package.json"));+function loadPlaywright(): { _electron: any } {+ const pnpmDir = path.join(root, "node_modules/.pnpm");+ const dir = fs.readdirSync(pnpmDir).find((name) => name.startsWith("playwright@"));+ return require(path.join(pnpmDir, dir!, "node_modules/playwright"));+}++/** Same file on disk, whatever spelling of the path (macOS temp dirs are symlinked under /private). */+const samePath = (a: string, b: string) => expect(fs.realpathSync(a)).toBe(fs.realpathSync(b));+/** Poll until `read` returns something truthy (the test runner's own `expect` has no locator matchers). */+async function until<T>(label: string, read: () => Promise<T> | T, timeout = 30_000): Promise<NonNullable<T>> {+ const start = Date.now();+ for (;;) {+ const value = await read();+ if (value) return value as NonNullable<T>;+ if (Date.now() - start > timeout) throw new Error(`timed out waiting for ${label}`);+ await new Promise((r) => setTimeout(r, 150));+ }+}+const textOf = (loc: any) => loc.innerText().catch(() => "");+const sleep = (ms: number) => new Promise((r) => setTimeout(r, ms));+const sha = (file: string) => createHash("sha256").update(fs.readFileSync(file)).digest("hex");+const probe = (file: string): any => JSON.parse(execFileSync(FFPROBE, ["-v", "error", "-show_streams", "-show_format", "-of", "json", file], { encoding: "utf8" }));+const videoOf = (file: string) => probe(file).streams.find((s: any) => s.codec_type === "video");++let work = "";+let CLIP = "";+let projectDir = "";+let userData = "";++function makeClip(out: string, seconds: number): void {+ execFileSync(FFMPEG, [+ "-y", "-v", "error",+ "-f", "lavfi", "-i", `testsrc2=size=1280x720:rate=30:duration=${seconds}`,+ "-f", "lavfi", "-i", `sine=frequency=440:sample_rate=48000:duration=${seconds}`,+ "-c:v", "libx264", "-preset", "veryfast", "-crf", "20", "-g", "30", "-pix_fmt", "yuv420p", "-c:a", "aac", "-shortest", out,+ ]);+}++interface Session {+ app: any;+ page: any;+}+const sessions: Session[] = [];++let launches = 0;+/** A fresh profile per launch unless `dir` is given (the restart test reuses one). */+async function launch(dir?: string): Promise<Session> {+ const { _electron } = loadPlaywright();+ const profile = dir ?? path.join(work, `profile-${++launches}`);+ const app = await _electron.launch({+ args: [path.join(root, "apps/desktop"), `--user-data-dir=${profile}`],+ env: { ...process.env, OPENREEL_FFMPEG_PATH: FFMPEG, OPENREEL_SKIP_ONBOARDING: "1" },+ timeout: 120_000,+ });+ const page = await app.firstWindow();+ await page.addInitScript(() => {+ try {+ localStorage.setItem("openreel-onboarding-complete", "true");+ localStorage.setItem("openreel-mograph-tour-complete", "true");+ } catch {+ /* storage unavailable */+ }+ });+ await page.reload();+ const session = { app, page };+ sessions.push(session);+ return session;+}++async function openEditor(page: any): Promise<void> {+ await page.getByRole("button", { name: /Horizontal/ }).click({ timeout: 60_000 });+ await page.locator('canvas[aria-label^="Program frame"]').waitFor({ timeout: 60_000 });+ await page.waitForFunction(() => Boolean((window as any).__openreelE2E?.proxy?.desktop), undefined, { timeout: 30_000 });+}++/** Evaluate an expression against the e2e hook `h` in the page (awaited). */+const E = (page: any, expression: string): Promise<any> => page.evaluate(`(async (h) => (${expression}))(window.__openreelE2E)`);++async function closeApp(session: Session | undefined, graceful: boolean): Promise<void> {+ if (!session) return;+ let proc: { kill(signal: string): void };+ try {+ proc = session.app.process();+ } catch {+ return; // already closed+ }+ if (graceful) await Promise.race([session.app.evaluate(({ app }: any) => app.quit()).catch(() => undefined), sleep(8000)]);+ else await Promise.race([session.app.evaluate(({ app }: any) => app.exit(0)).catch(() => undefined), sleep(4000)]);+ await sleep(300);+ try {+ proc.kill("SIGKILL");+ } catch {+ /* already gone */+ }+}++const mediaNamed = (page: any, name: string) =>+ page.evaluate((n: string) => {+ const item = (window as any).__openreelE2E.project.getState().project.mediaLibrary.items.find((m: any) => m.name === n);+ return item ? { id: item.id as string, proxy: item.proxy ?? null, sourceFile: item.sourceFile ?? null, copiedFrom: item.copiedFrom ?? null, placeholder: !!item.isPlaceholder } : null;+ }, name);++async function importClip(page: any, file: string, name: string): Promise<string> {+ await page.locator('[data-tour="assets"] input[type="file"]').setInputFiles(file);+ await page.getByLabel(`Select media ${name}`).waitFor({ timeout: 60_000 });+ const item = await mediaNamed(page, name);+ if (!item) throw new Error(`${name} was not imported`);+ return item.id;+}++async function stubDialogs(app: any, args: { savePath?: string; folder?: string }): Promise<void> {+ await app.evaluate(({ dialog }: any, a: any) => {+ if (a.savePath) dialog.showSaveDialog = async () => ({ canceled: false, filePath: a.savePath });+ if (a.folder) dialog.showOpenDialog = async () => ({ canceled: false, filePaths: [a.folder] });+ }, args);+}++async function saveProjectAs(session: Session, file: string): Promise<void> {+ await stubDialogs(session.app, { savePath: file });+ await session.page.evaluate(() => (document.activeElement as HTMLElement | null)?.blur?.());+ await session.page.keyboard.press("Meta+s");+ const start = Date.now();+ while (!fs.existsSync(file)) {+ if (Date.now() - start > 20_000) throw new Error("project was not saved");+ await sleep(200);+ }+}++async function placeClip(page: any, name: string): Promise<{ start: number }> {+ await page.getByRole("button", { name: `Media actions for ${name}` }).click();+ await page.getByRole("menuitem", { name: "Add to timeline" }).click();+ await page.getByRole("button", { name: "Match Video" }).click({ timeout: 8_000 }).catch(() => undefined);+ await page.waitForFunction(() => (window as any).__openreelE2E.project.getState().project.timeline.tracks.some((t: any) => t.clips.length > 0), undefined, { timeout: 30_000 });+ await sleep(600);+ const settings = await E(page, "h.project.getState().project.settings");+ if (settings.width !== 3840 || settings.height !== 2160) {+ await E(page, "h.project.getState().updateSettings({ width: 3840, height: 2160, frameRate: 30 })");+ await sleep(500);+ }+ return { start: await E(page, "h.project.getState().project.timeline.tracks.flatMap((t) => t.clips)[0].startTime") };+}++const seekTo = async (page: any, t: number) => {+ await page.evaluate((s: number) => (window as any).__openreelE2E.timeline.getState().seekTo(s), t);+ await sleep(400);+};+const decodeLog = (page: any, id: string) =>+ page.evaluate((mediaId: string) => {+ const x = (window as any).__openreelE2E.proxy.cache.decodes[mediaId];+ return x ? { source: x.source as string, proxy: x.proxyCount as number, original: x.originalCount as number } : null;+ }, id);++async function waitProxyLinked(page: any, name: string, timeout = 180_000) {+ let ref: any = null;+ const start = Date.now();+ while (Date.now() - start < timeout) {+ ref = (await mediaNamed(page, name))?.proxy ?? null;+ if (ref?.status === "ready") return ref;+ await sleep(300);+ }+ throw new Error(`proxy for ${name} was not linked in ${timeout} ms`);+}++beforeAll(() => {+ if (!enabled) return;+ work = fs.mkdtempSync(path.join(os.tmpdir(), "oringest-e2e-"));+ userData = path.join(work, "userdata");+ projectDir = path.join(work, "Project");+ fs.mkdirSync(projectDir, { recursive: true });+ CLIP = path.join(work, "src", "clip4k.mp4");+ fs.mkdirSync(path.dirname(CLIP), { recursive: true });+ makeClip(CLIP, 3);+}, 180_000);++afterAll(async () => {+ for (const s of sessions) await closeApp(s, false);+ if (work) fs.rmSync(work, { recursive: true, force: true });+});++d("proxy presets and encoder choice in real Electron", () => {+ let session: Session;++ it("Create Proxies dialog builds a DNxHR LB proxy with an H.264 preview twin; the panel preset selector and toggle work", async () => {+ session = await launch();+ const { page } = session;+ await openEditor(page);+ await saveProjectAs(session, path.join(projectDir, "film.oreel"));+ const id = await importClip(page, CLIP, "clip4k.mp4");+ expect((await mediaNamed(page, "clip4k.mp4"))?.proxy ?? null).toBeNull();++ const panel = page.getByTestId("proxy-panel");+ const body = page.getByTestId("proxy-panel-body");+ if (!(await body.isVisible())) await panel.getByRole("button", { name: /^Proxies/ }).first().click();+ console.log(`[proxy-presets] panel: ${(await textOf(body)).replace(/\s+/g, " ").slice(0, 400)}`);+ await body.getByRole("button", { name: "Create proxies with a preset" }).click({ timeout: 15_000 });+ const dialog = page.getByTestId("create-proxies-dialog");+ await dialog.waitFor({ timeout: 10_000 });+ await dialog.getByTestId("proxy-preset-dnxhr-lb").click();+ await expect(dialog.getByTestId("proxy-preset-dnxhr-lb").getAttribute("data-selected")).resolves.toBe("true");+ await dialog.getByTestId("create-proxies-confirm").click();++ const ref = await (async () => {+ const start = Date.now();+ for (;;) {+ const linked = (await mediaNamed(page, "clip4k.mp4"))?.proxy;+ if (linked?.status === "ready") return linked;+ if (Date.now() - start > 240_000) throw new Error("DNxHR proxy never linked");+ await sleep(300);+ }+ })();+ console.log(`[proxy-presets] ref: ${JSON.stringify({ path: path.basename(ref.path), codec: ref.codec, profile: ref.profile, preview: ref.previewPath ? path.basename(ref.previewPath) : null })}`);+ expect(ref.profile).toEqual({ codec: "dnxhr-lb", size: "half" });+ expect(videoOf(ref.path)).toMatchObject({ codec_name: "dnxhd", width: 640, height: 360 });+ expect(ref.previewPath).toBeTruthy();+ expect(videoOf(ref.previewPath)).toMatchObject({ codec_name: "h264", width: 640, height: 360 });+ expect(await E(page, "h.project.getState().project.mediaLibrary.desktopIngest")).toEqual({ proxyProfile: { codec: "dnxhr-lb", size: "half" } });++ // Undo restores the previous profile (one undo step for the preset change).+ // Panel preset selector reflects and changes the saved preset.+ if (!(await body.isVisible())) await panel.getByRole("button", { name: /^Proxies/ }).first().click();+ await body.getByTestId("desktop-ingest-settings").getByRole("combobox", { name: "Proxy preset" }).click();+ await page.getByRole("option", { name: "H.264 1/4 resolution" }).click();+ await until("quarter profile saved", async () => (await E(page, "h.project.getState().project.mediaLibrary.desktopIngest")).proxyProfile?.size === "quarter");+ expect(await E(page, "h.project.getState().project.mediaLibrary.desktopIngest")).toEqual({ proxyProfile: { codec: "h264", size: "quarter" } });+ await E(page, "h.project.getState().undo()");+ await until("undo restores DNxHR", async () => (await E(page, "h.project.getState().project.mediaLibrary.desktopIngest")).proxyProfile?.codec === "dnxhr-lb");++ // Toggle proxies: the preview decodes the proxy twin, then the original.+ const clip = await placeClip(page, "clip4k.mp4");+ await page.waitForFunction((mid: string) => (window as any).__openreelE2E.proxy.cache.store.getState().entries[mid]?.status === "ready", id, { timeout: 120_000 });+ await seekTo(page, clip.start + 1.2);+ await sleep(2000);+ expect((await decodeLog(page, id))?.source).toBe("proxy");+ await page.getByTestId("toggle-proxies").click();+ await seekTo(page, clip.start + 1.3);+ await seekTo(page, clip.start + 1.2);+ await sleep(2500);+ expect((await decodeLog(page, id))?.source).toBe("original");+ }, 600_000);++ const exportWith = async (page: any, extra: string): Promise<{ status: string; path?: string; error?: string }> => {+ await E(page, `h.exportQueue.getState().enqueue({ settings: { width: 1280, height: 720, frameRate: 24, format: "mp4", codec: "h264", bitrate: 6000, ${extra} }, presetLabel: "enc" })`);+ await E(page, "h.exportQueue.getState().start()");+ const done = await page.waitForFunction(() => {+ const jobs = (window as any).__openreelE2E.exportQueue.getState().queue.jobs as any[];+ const job = jobs[jobs.length - 1];+ return job && (job.status === "completed" || job.status === "failed") ? { status: job.status as string, path: job.output?.path as string | undefined, error: job.error as string | undefined } : null;+ }, undefined, { timeout: 300_000, polling: 500 });+ return (await done.jsonValue()) as { status: string; path?: string; error?: string };+ };++ it("Software and Hardware choices reach the ffmpeg sidecar: libx264 vs VideoToolbox, and Hardware + Two-pass is refused", async () => {+ const { page } = session;+ const encoders: string[] = await page.evaluate(async () => ((await (window as any).openreel.probeHardware?.())?.encoders ?? []) as string[]);+ console.log(`[encoder] sidecar reports: ${encoders.join(", ")}`);+ const encoderTag = (file: string) => (execFileSync(FFPROBE, ["-v", "error", "-show_entries", "stream_tags=encoder:format_tags=encoder", "-of", "default=nw=1", file], { encoding: "utf8" }) + execFileSync("strings", [file], { encoding: "utf8", maxBuffer: 1 << 28 }).split("\n").filter((l) => /libx264|videotoolbox/i.test(l)).join("\n"));+ const soft = await exportWith(page, 'encoderChoice: "software"');+ expect(soft.status, soft.error).toBe("completed");+ expect(videoOf(soft.path!).codec_name).toBe("h264");+ expect(encoderTag(soft.path!)).toMatch(/libx264/);+ if (encoders.includes("h264_videotoolbox")) {+ const hard = await exportWith(page, 'encoderChoice: "hardware"');+ expect(hard.status, hard.error).toBe("completed");+ expect(videoOf(hard.path!).codec_name).toBe("h264");+ expect(encoderTag(hard.path!)).not.toMatch(/libx264/);+ }+ const twoPass = await exportWith(page, 'encoderChoice: "software", rateControl: "vbr2", maxBitrate: 9000');+ console.log(`[encoder] software + two-pass: ${twoPass.status} ${twoPass.error ?? ""}`);+ expect(twoPass.status, twoPass.error).toBe("completed");+ const refused = await exportWith(page, 'encoderChoice: "hardware", rateControl: "vbr2"');+ console.log(`[encoder] hardware + two-pass: ${refused.status} ${refused.error}`);+ expect(refused.status).toBe("failed");+ expect(refused.error ?? "").toMatch(/two-pass/i);+ }, 900_000);+});diff --git a/apps/web/bundle-budgets.json b/apps/web/bundle-budgets.jsonindex 75eb9e49..69c71684 100644--- a/apps/web/bundle-budgets.json+++ b/apps/web/bundle-budgets.json@@ -3,8 +3,8 @@"budgets": {"entry": {"rawKb": 640,- "gzipKb": 190,- "note": "startup entry chunk: everything the first paint compiles and evaluates. w9: video/motion/audio engines, action handlers, export engine and schema normalizers are behind services/lazy-engines (1988 KB / 568.8 KB gzip before; 608.5 / 179.0 after)"+ "gzipKb": 180,+ "note": "startup entry chunk: everything the first paint compiles and evaluates. w9: video/motion/audio engines, action handlers, export engine and schema normalizers are behind services/lazy-engines (1988 KB / 568.8 KB gzip before; 608.5 / 179.0 after). Entry diet: the desktop-only native ffmpeg backend, native decode, path hydration and smart-render load lazily inside main.tsx's isDesktop branch, and the in-thread RAW developer (dng, develop, tiff, color) loads on first use (621.0 / 190.0 before; 577.3 / 174.7 after)"},"initialJs": {"rawKb": 1230,diff --git a/apps/web/e2e/audio-channels.spec.ts b/apps/web/e2e/audio-channels.spec.tsnew file mode 100644index 00000000..65f62084--- /dev/null+++ b/apps/web/e2e/audio-channels.spec.ts@@ -0,0 +1,411 @@+import { expect, test, type Page } from "@playwright/test";+import { execFileSync } from "node:child_process";+import { mkdtempSync, writeFileSync } from "node:fs";+import { tmpdir } from "node:os";+import { join } from "node:path";+import { clickClip, importInput, openEditor, settle, undo } from "./helpers";++/**+ * Modify > Audio Channels, checked in real Chrome with a stereo file whose left channel is 440 Hz and right 1000 Hz:+ * - Swap L/R, Left only and mono Mix through the dialog change the export mixdown exactly as mapped;+ * - one undo restores the previous mapping, a multi-selection maps every selected clip in one step;+ * - Split to mono clips turns the stereo interview into two mono clips on two tracks (and undoes as one);+ * - the default-on-import preference stamps new files and the mixdown follows it.+ */++interface Hook {+ project: { getState(): Record<string, any> };+ audio: Record<string, any>;+}+declare function E(): Hook;++test.beforeEach(async ({ page }) => {+ await page.addInitScript(() => {+ (window as unknown as { E: () => unknown }).E = () => (window as unknown as { __openreelE2E: unknown }).__openreelE2E;+ });+});++const SR = 48000;+const workDir = mkdtempSync(join(tmpdir(), "openreel-channels-"));++/** Stereo 16-bit WAV: 440 Hz on the left, 1000 Hz on the right. */+function writeStereo(name: string, seconds: number): string {+ const n = SR * seconds;+ const pcm = Buffer.alloc(44 + n * 4);+ pcm.write("RIFF", 0);+ pcm.writeUInt32LE(36 + n * 4, 4);+ pcm.write("WAVEfmt ", 8);+ pcm.writeUInt32LE(16, 16);+ pcm.writeUInt16LE(1, 20);+ pcm.writeUInt16LE(2, 22);+ pcm.writeUInt32LE(SR, 24);+ pcm.writeUInt32LE(SR * 4, 28);+ pcm.writeUInt16LE(4, 32);+ pcm.writeUInt16LE(16, 34);+ pcm.write("data", 36);+ pcm.writeUInt32LE(n * 4, 40);+ for (let i = 0; i < n; i++) {+ pcm.writeInt16LE(Math.round(0.4 * Math.sin((2 * Math.PI * 440 * i) / SR) * 32767), 44 + i * 4);+ pcm.writeInt16LE(Math.round(0.4 * Math.sin((2 * Math.PI * 1000 * i) / SR) * 32767), 46 + i * 4);+ }+ const path = join(workDir, name);+ writeFileSync(path, pcm);+ return path;+}++/** 6-channel 16-bit WAV (L R C LFE Ls Rs): a distinct tone on each channel, 300/500/700/900/1100/1300 Hz. */+const SIX_TONES = [300, 500, 700, 900, 1100, 1300] as const;+function writeFiveOne(name: string, seconds: number): string {+ const n = SR * seconds;+ const frame = 12;+ const pcm = Buffer.alloc(44 + n * frame);+ pcm.write("RIFF", 0);+ pcm.writeUInt32LE(36 + n * frame, 4);+ pcm.write("WAVEfmt ", 8);+ pcm.writeUInt32LE(16, 16);+ pcm.writeUInt16LE(1, 20);+ pcm.writeUInt16LE(6, 22);+ pcm.writeUInt32LE(SR, 24);+ pcm.writeUInt32LE(SR * frame, 28);+ pcm.writeUInt16LE(frame, 32);+ pcm.writeUInt16LE(16, 34);+ pcm.write("data", 36);+ pcm.writeUInt32LE(n * frame, 40);+ for (let i = 0; i < n; i++) {+ for (let c = 0; c < 6; c++) pcm.writeInt16LE(Math.round(0.3 * Math.sin((2 * Math.PI * SIX_TONES[c] * i) / SR) * 32767), 44 + i * frame + c * 2);+ }+ const path = join(workDir, name);+ writeFileSync(path, pcm);+ return path;+}++async function importAudio(page: Page, path: string) {+ const name = path.split("/").pop()!;+ await importInput(page).setInputFiles(path);+ await page.getByLabel(`Select media ${name}`).waitFor({ timeout: 30_000 });+}++async function addToLane(page: Page, mediaName: string, lane: string, start: number): Promise<string> {+ const result = await page.evaluate(+ async ([media, laneName, at]) => {+ const st = E().project.getState();+ const item = st.project.mediaLibrary.items.find((m: any) => m.name === media);+ const target = st.project.timeline.tracks.find((t: any) => t.name === laneName);+ const added = await st.addClip(target.id, item.id, at);+ const clips = E().project.getState().project.timeline.tracks.find((t: any) => t.name === laneName).clips;+ return { success: added.success, id: clips.find((c: any) => c.mediaId === item.id && Math.abs(c.startTime - at) < 0.01)?.id as string | undefined };+ },+ [mediaName, lane, start] as const,+ );+ expect(result.success && result.id, JSON.stringify(result)).toBeTruthy();+ await settle(page, 300);+ return result.id!;+}++async function muteMain(page: Page) {+ await page.evaluate(async () => {+ const st = E().project.getState();+ await st.muteTrack(st.project.timeline.tracks.find((t: any) => t.name === "Main").id, true);+ });+}++const clipState = (page: Page, id: string) =>+ page.evaluate((clipId) => {+ const clip = E().project.getState().project.timeline.tracks.flatMap((t: any) => t.clips).find((c: any) => c.id === clipId);+ return JSON.parse(JSON.stringify(clip));+ }, id);++/** Both mixdown channels of [from, from+length] exactly as the export engine renders them. */+async function mixdown(page: Page, from: number, length: number) {+ return page.evaluate(+ async ([start, len]) => {+ const engine = E().audio.getAudioEngine();+ if (!engine.isInitialized()) await engine.initialize();+ const rendered = await engine.renderAudio(E().project.getState().getFullProject(), start, len);+ const buffer = rendered.buffer as AudioBuffer;+ return { rate: buffer.sampleRate, left: Array.from(buffer.getChannelData(0)) as number[], right: Array.from(buffer.getChannelData(1)) as number[] };+ },+ [from, length] as const,+ );+}++/** Amplitude of one frequency (single-bin DFT) over [from, to) seconds. */+const toneAmp = (x: number[], rate: number, freq: number, from: number, to: number): number => {+ const a = Math.floor(from * rate);+ const b = Math.floor(to * rate);+ let re = 0;+ let im = 0;+ for (let i = a; i < b; i++) {+ const w = (2 * Math.PI * freq * (i - a)) / rate;+ re += x[i] * Math.cos(w);+ im -= x[i] * Math.sin(w);+ }+ return (2 * Math.hypot(re, im)) / (b - a);+};++async function tones(page: Page, from = 0.5, to = 2.5) {+ const m = await mixdown(page, 0, 3);+ return {+ leftLow: toneAmp(m.left, m.rate, 440, from, to),+ leftHigh: toneAmp(m.left, m.rate, 1000, from, to),+ rightLow: toneAmp(m.right, m.rate, 440, from, to),+ rightHigh: toneAmp(m.right, m.rate, 1000, from, to),+ };+}++async function openDialog(page: Page, clipId: string) {+ await clickClip(page, clipId);+ await page.getByRole("tab", { name: /^Audio$/ }).click();+ const section = page.getByTestId("audio-channels-section");+ if (!(await section.isVisible().catch(() => false))) {+ await page.getByRole("button", { name: /Audio channels/i }).first().click();+ await page.waitForTimeout(1200);+ }+ await page.getByTestId("audio-channels-open").click();+ await page.getByTestId("audio-channels-dialog").waitFor({ timeout: 15_000 });+}++test("Swap, Left only and Mix change the mixdown as mapped; undo restores each", async ({ page }, testInfo) => {+ testInfo.setTimeout(240_000);+ await openEditor(page);+ await muteMain(page);+ await importAudio(page, writeStereo("interview.wav", 3));+ const clip = await addToLane(page, "interview.wav", "Dialogue", 0);++ const base = await tones(page);+ expect(base.leftLow, "file plays left on the left").toBeGreaterThan(0.3);+ expect(base.rightHigh, "file plays right on the right").toBeGreaterThan(0.3);+ expect(base.leftHigh).toBeLessThan(0.02);+ expect(base.rightLow).toBeLessThan(0.02);++ await openDialog(page, clip);+ await expect(page.getByTestId("audio-channels-apply")).toBeDisabled();+ await page.getByTestId("audio-channels-swap").click();+ await expect(page.getByTestId("audio-channels-custom")).toBeVisible();+ await page.screenshot({ path: testInfo.outputPath("audio-channels-dialog.png") });+ await page.getByTestId("audio-channels-apply").click();+ await expect(page.getByTestId("audio-channels-dialog")).toBeHidden();+ expect((await clipState(page, clip)).channelMap).toEqual({ format: "stereo", sources: [1, 0] });+ const swapped = await tones(page);+ expect(swapped.leftHigh, "swapped: right source on the left").toBeGreaterThan(0.3);+ expect(swapped.rightLow, "swapped: left source on the right").toBeGreaterThan(0.3);+ expect(swapped.leftLow).toBeLessThan(0.02);+ expect(swapped.rightHigh).toBeLessThan(0.02);++ await undo(page);+ await settle(page, 300);+ expect((await clipState(page, clip)).channelMap).toBeUndefined();+ const restored = await tones(page);+ expect(restored.leftLow).toBeGreaterThan(0.3);++ await openDialog(page, clip);+ await page.getByTestId("audio-channels-left-only").click();+ await page.getByTestId("audio-channels-apply").click();+ await expect(page.getByTestId("audio-channels-dialog")).toBeHidden();+ expect((await clipState(page, clip)).channelMap).toEqual({ format: "mono", sources: [0] });+ const leftOnly = await tones(page);+ expect(leftOnly.leftLow, "left only plays on both sides").toBeGreaterThan(0.2);+ expect(leftOnly.rightLow).toBeGreaterThan(0.2);+ expect(leftOnly.leftHigh, "right channel is gone").toBeLessThan(0.02);+ expect(leftOnly.rightHigh).toBeLessThan(0.02);++ await openDialog(page, clip);+ await page.getByTestId("audio-channels-format-mono").click();+ await page.getByTestId("audio-channels-cell-0-mix").click();+ await page.getByTestId("audio-channels-apply").click();+ await expect(page.getByTestId("audio-channels-dialog")).toBeHidden();+ const mix = await tones(page);+ expect(mix.leftLow, "mono fold-down keeps both channels").toBeGreaterThan(0.1);+ expect(mix.leftHigh).toBeGreaterThan(0.1);+ expect(mix.rightHigh).toBeGreaterThan(0.1);+ await expect(page.getByTestId("audio-channels-current")).toContainText("Mono");+});++test("Split to mono clips makes two mono clips on two tracks, one undo", async ({ page }, testInfo) => {+ testInfo.setTimeout(240_000);+ await openEditor(page);+ await muteMain(page);+ await importAudio(page, writeStereo("two-people.wav", 3));+ const clip = await addToLane(page, "two-people.wav", "Dialogue", 0);+ const tracksBefore = await page.evaluate(() => E().project.getState().project.timeline.tracks.length as number);+ await openDialog(page, clip);+ await page.getByTestId("audio-channels-split").click();+ await expect(page.getByTestId("audio-channels-dialog")).toBeHidden();+ const maps = await page.evaluate((id) => {+ const tracks = E().project.getState().project.timeline.tracks as any[];+ return {+ count: tracks.length,+ clips: tracks.flatMap((t) => t.clips).filter((c: any) => c.mediaId === tracks.flatMap((x) => x.clips).find((k: any) => k.id === id).mediaId).map((c: any) => ({ id: c.id, map: c.channelMap })),+ };+ }, clip);+ expect(maps.count).toBe(tracksBefore + 1);+ expect(maps.clips.map((c: any) => c.map.sources[0]).sort()).toEqual([0, 1]);+ const split = await tones(page);+ expect(split.leftLow, "first clip: the left channel").toBeGreaterThan(0.2);+ expect(split.rightHigh, "second clip: the right channel").toBeGreaterThan(0.2);+ await undo(page);+ await settle(page, 300);+ expect(await page.evaluate(() => E().project.getState().project.timeline.tracks.length as number)).toBe(tracksBefore);+ expect((await clipState(page, clip)).channelMap).toBeUndefined();+});++test("Split to mono clips works on a video clip with embedded stereo audio", async ({ page }, testInfo) => {+ testInfo.setTimeout(240_000);+ const out = join(workDir, "interview.mp4");+ try {+ execFileSync("ffmpeg", ["-y", "-f", "lavfi", "-i", "color=c=gray:s=320x180:r=24:d=3", "-i", writeStereo("interview-src.wav", 3), "-c:v", "libx264", "-pix_fmt", "yuv420p", "-c:a", "aac", "-shortest", out], { stdio: "ignore" });+ } catch {+ test.skip(true, "ffmpeg is not available to build the stereo video fixture");+ }+ await openEditor(page);+ await importAudio(page, out);+ const clip = await addToLane(page, "interview.mp4", "Main", 0);+ const tracksBefore = await page.evaluate(() => E().project.getState().project.timeline.tracks.length as number);+ await openDialog(page, clip);+ await page.getByTestId("audio-channels-split").click();+ await expect(page.getByTestId("audio-channels-dialog")).toBeHidden();+ const after = await page.evaluate((id) => {+ const tracks = E().project.getState().project.timeline.tracks as any[];+ const mediaId = tracks.flatMap((t) => t.clips).find((k: any) => k.id === id).mediaId;+ return { count: tracks.length, sources: tracks.flatMap((t) => t.clips).filter((c: any) => c.mediaId === mediaId).map((c: any) => c.channelMap?.sources?.[0]).sort() };+ }, clip);+ expect(after.count).toBe(tracksBefore + 1);+ expect(after.sources).toEqual([0, 1]);+ await undo(page);+ await settle(page, 300);+ expect(await page.evaluate(() => E().project.getState().project.timeline.tracks.length as number)).toBe(tracksBefore);+});++test("Default audio channels preference stamps new imports and the mixdown follows it", async ({ page }, testInfo) => {+ testInfo.setTimeout(240_000);+ await openEditor(page);+ await muteMain(page);+ await page.evaluate(() => {+ const store = (window as any).__openreelE2E.settings;+ store.getState().setDefaultAudioChannels("mono");+ });+ await importAudio(page, writeStereo("default-mono.wav", 3));+ const clip = await addToLane(page, "default-mono.wav", "Dialogue", 0);+ const preset = await page.evaluate(() => E().project.getState().project.mediaLibrary.items.find((m: any) => m.name === "default-mono.wav").channelPreset);+ expect(preset).toBe("mono");+ const mix = await tones(page);+ expect(mix.leftLow, "mono preset plays the first channel on both sides").toBeGreaterThan(0.1);+ expect(mix.rightLow).toBeGreaterThan(0.1);+ expect(mix.leftHigh).toBeLessThan(0.02);+ await openDialog(page, clip);+ await expect(page.getByTestId("audio-channels-preset-mono")).toHaveAttribute("aria-checked", "true");+});++test("a 5.1 source reaches every channel through the mapping in the export mixdown", async ({ page }, testInfo) => {+ testInfo.setTimeout(300_000);+ await openEditor(page);+ await muteMain(page);+ await importAudio(page, writeFiveOne("surround.wav", 3));+ const clip = await addToLane(page, "surround.wav", "Dialogue", 0);+ const channels = await page.evaluate(() => E().project.getState().project.mediaLibrary.items.find((m: any) => m.name === "surround.wav").metadata.channels);+ expect(channels).toBe(6);+ const at = async (freqs: readonly number[]) => {+ const m = await mixdown(page, 0, 3);+ return freqs.map((f) => ({ f, left: toneAmp(m.left, m.rate, f, 0.5, 2.5), right: toneAmp(m.right, m.rate, f, 0.5, 2.5) }));+ };++ // Mono <- source 3 (Centre, 700 Hz) through the dialog.+ await openDialog(page, clip);+ await page.getByTestId("audio-channels-format-mono").click();+ await page.getByTestId("audio-channels-cell-0-2").click();+ await page.getByTestId("audio-channels-apply").click();+ await expect(page.getByTestId("audio-channels-dialog")).toBeHidden();+ expect((await clipState(page, clip)).channelMap).toEqual({ format: "mono", sources: [2] });+ const centre = await at(SIX_TONES);+ expect(centre[2].left, "Centre plays on the left").toBeGreaterThan(0.1);+ expect(centre[2].right, "Centre plays on the right").toBeGreaterThan(0.1);+ for (const i of [0, 1, 3, 4, 5]) expect(Math.max(centre[i].left, centre[i].right), `tone ${SIX_TONES[i]} is gone`).toBeLessThan(0.02);++ // Stereo <- Ls (1100 Hz) and Rs (1300 Hz).+ await openDialog(page, clip);+ await page.getByTestId("audio-channels-format-stereo").click();+ await page.getByTestId("audio-channels-cell-0-4").click();+ await page.getByTestId("audio-channels-cell-1-5").click();+ await page.getByTestId("audio-channels-apply").click();+ await expect(page.getByTestId("audio-channels-dialog")).toBeHidden();+ expect((await clipState(page, clip)).channelMap).toEqual({ format: "stereo", sources: [4, 5] });+ const rear = await at(SIX_TONES);+ expect(rear[4].left, "Ls on the left").toBeGreaterThan(0.1);+ expect(rear[5].right, "Rs on the right").toBeGreaterThan(0.1);+ for (const i of [0, 1, 2, 3]) expect(Math.max(rear[i].left, rear[i].right), `tone ${SIX_TONES[i]} is gone`).toBeLessThan(0.02);+ expect(rear[4].right).toBeLessThan(0.02);+ expect(rear[5].left).toBeLessThan(0.02);+});++test("realtime preview plays the mapped channels (swap and a 5.1 source) frequency-exact", async ({ page }) => {+ test.setTimeout(240_000);+ await openEditor(page);+ const out = await page.evaluate(async ({ sr, six }) => {+ const { RealtimeAudioGraph } = E().audio;+ const render = async (tones: number[], channelMap: unknown) => {+ const ctx = new OfflineAudioContext(2, sr * 2, sr);+ const clock = { getAudioContext: () => ctx, currentTime: 0, isPlaying: true };+ const graph = new RealtimeAudioGraph(clock as any);+ const buffer = ctx.createBuffer(tones.length, sr * 2, sr);+ tones.forEach((hz, c) => {+ const data = buffer.getChannelData(c);+ for (let i = 0; i < data.length; i++) data[i] = 0.3 * Math.sin((2 * Math.PI * hz * i) / sr);+ });+ graph.scheduleClip({ clipId: "c", trackId: "t", audioBuffer: buffer, channelMap, startTime: 0, endTime: 2, mediaOffset: 0, volume: 1, volumeAutomation: [], pan: 0, effects: [], speed: 1 });+ const rendered = await ctx.startRendering();+ const amp = (data: Float32Array, hz: number) => {+ let re = 0;+ let im = 0;+ const a = Math.floor(0.5 * sr);+ const b = Math.floor(1.5 * sr);+ for (let i = a; i < b; i++) {+ const w = (2 * Math.PI * hz * (i - a)) / sr;+ re += data[i] * Math.cos(w);+ im -= data[i] * Math.sin(w);+ }+ return (2 * Math.hypot(re, im)) / (b - a);+ };+ const l = rendered.getChannelData(0);+ const r = rendered.getChannelData(1);+ return tones.map((hz) => ({ hz, left: amp(l, hz), right: amp(r, hz) }));+ };+ return {+ plain: await render([440, 1000], undefined),+ swapped: await render([440, 1000], { format: "stereo", sources: [1, 0] }),+ rear: await render(six, { format: "stereo", sources: [4, 5] }),+ centre: await render(six, { format: "mono", sources: [2] }),+ };+ }, { sr: SR, six: [...SIX_TONES] });+ expect(out.plain[0].left).toBeGreaterThan(0.2);+ expect(out.plain[1].right).toBeGreaterThan(0.2);+ expect(out.swapped[1].left, "swap: right source plays on the left").toBeGreaterThan(0.2);+ expect(out.swapped[0].right, "swap: left source plays on the right").toBeGreaterThan(0.2);+ expect(out.swapped[0].left).toBeLessThan(0.02);+ expect(out.swapped[1].right).toBeLessThan(0.02);+ expect(out.rear[4].left, "Ls on the left").toBeGreaterThan(0.2);+ expect(out.rear[5].right, "Rs on the right").toBeGreaterThan(0.2);+ expect(Math.max(out.rear[0].left, out.rear[0].right, out.rear[2].left)).toBeLessThan(0.02);+ expect(out.centre[2].left).toBeGreaterThan(0.1);+ expect(out.centre[2].right).toBeGreaterThan(0.1);+ expect(Math.max(out.centre[4].left, out.centre[4].right)).toBeLessThan(0.02);+});++test("Preferences shows accurate Default audio channels copy and the picker stamps a UI import", async ({ page }, testInfo) => {+ testInfo.setTimeout(240_000);+ await openEditor(page);+ await muteMain(page);+ await page.evaluate(() => (window as any).__openreelE2E.settings.getState().openSettings());+ const trigger = page.getByRole("combobox", { name: "Default audio channels" });+ await trigger.scrollIntoViewIfNeeded();+ const copy = page.getByText(/Applies to files you import from now on/);+ await expect(copy).toContainText("Mono plays the first channel only");+ await expect(copy).not.toContainText("folds");+ await trigger.click();+ await page.getByRole("option", { name: "Mono" }).click();+ await expect(trigger).toContainText("Mono");+ await page.screenshot({ path: testInfo.outputPath("prefs-audio-channels.png") });+ await page.keyboard.press("Escape");+ await importAudio(page, writeStereo("via-ui.wav", 3));+ const preset = await page.evaluate(() => E().project.getState().project.mediaLibrary.items.find((m: any) => m.name === "via-ui.wav").channelPreset);+ expect(preset).toBe("mono");+});diff --git a/apps/web/e2e/audio-output-solo-safe.spec.ts b/apps/web/e2e/audio-output-solo-safe.spec.tsnew file mode 100644index 00000000..7825d04b--- /dev/null+++ b/apps/web/e2e/audio-output-solo-safe.spec.ts@@ -0,0 +1,202 @@+import { expect, test, type Page } from "@playwright/test";+import { openEditor, settle } from "./helpers";+import { AUDIO_FIXTURE_PATH } from "./global-setup";++/**+ * Audio output device picker + solo-safe tracks, real Chrome:+ * - solo on one track silences the others in the offline (export) mixdown, except a solo-safe track,+ * and mute still beats solo-safe; toggling solo-safe is one undo step and is saved with the project;+ * - the output device chosen in Preferences is applied with AudioContext.setSinkId, remembered across+ * a reload, falls back to the system default with a toast when the device is unplugged, and+ * switches back when it returns.+ */++interface Hook {+ project: { getState(): any };+ ui: { getState(): any };+ audio: Record<string, any>;+}+declare function E(): Hook;++const TONE = "Select media tone-4s.wav";++const history = (page: Page) =>+ page.evaluate(() => E().project.getState().actionExecutor.getHistory().getUndoStackSize() as number);++async function rms(page: Page, start: number, duration: number): Promise<number> {+ return page.evaluate(+ async ([s, d]) => {+ const engine = E().audio.getAudioEngine();+ if (!engine.isInitialized()) await engine.initialize();+ const project = E().project.getState().getFullProject();+ const out = await engine.renderAudio(project, s, d);+ const left = out.buffer.getChannelData(0);+ let sum = 0;+ for (let i = 0; i < left.length; i++) sum += left[i] * left[i];+ return Math.sqrt(sum / left.length);+ },+ [start, duration] as const,+ );+}++async function addToLane(page: Page, lane: string) {+ const result = await page.evaluate(+ async ([laneName]) => {+ const st = E().project.getState();+ const item = st.project.mediaLibrary.items.find((m: any) => m.name === "tone-4s.wav");+ const target = st.project.timeline.tracks.find((t: any) => t.name === laneName);+ return st.addClip(target.id, item.id, 0);+ },+ [lane] as const,+ );+ expect(result.success, JSON.stringify(result)).toBe(true);+ await settle(page, 400);+}++/** Open the mixer panel; it stays open across a reload, so only toggle when it is not already showing. */+const openMixer = async (page: Page) => {+ const mixer = page.getByTestId("audio-mixer");+ const alreadyOpen = await mixer.waitFor({ timeout: 2_000 }).then(() => true, () => false);+ if (!alreadyOpen) await page.evaluate(() => E().ui.getState().togglePanel("audioMixer"));+ await mixer.waitFor({ timeout: 15_000 });+};++const trackState = (page: Page, name: string) =>+ page.evaluate((n) => {+ const t = E().project.getState().project.timeline.tracks.find((x: any) => x.name === n);+ return { muted: t.muted as boolean, solo: t.solo as boolean, soloSafe: t.soloSafe as boolean | undefined };+ }, name);++test.describe("Solo-safe tracks", () => {+ test.describe.configure({ timeout: 240_000 });+ test.beforeEach(async ({ page }) => {+ await page.addInitScript(() => {+ (window as unknown as { E: () => unknown }).E = () => (window as unknown as { __openreelE2E: unknown }).__openreelE2E;+ });+ });++ test("a solo-safe track keeps playing in the export mixdown while another track is soloed", async ({ page }) => {+ await openEditor(page);+ await page.locator('input[type="file"]').first().setInputFiles(AUDIO_FIXTURE_PATH);+ await page.getByLabel(TONE).waitFor({ timeout: 30_000 });+ await addToLane(page, "Dialogue");+ await addToLane(page, "Music");+ await page.evaluate(async () => {+ const st = E().project.getState();+ await st.muteTrack(st.project.timeline.tracks.find((t: any) => t.name === "Main").id, true);+ });+ const both = await rms(page, 0, 3);+ expect(both, "both tones are audible").toBeGreaterThan(0.01);++ await openMixer(page);+ const depth = await history(page);++ // Solo Dialogue: Music is silenced, so the mix is one tone instead of two (half the level).+ await page.getByRole("button", { name: "Solo Dialogue", exact: true }).click();+ await expect.poll(() => history(page)).toBe(depth + 1);+ expect(await rms(page, 0, 3)).toBeCloseTo(both / 2, 2);++ // Solo Safe on Music: it plays again although Dialogue is still soloed. One undo step.+ await page.getByRole("button", { name: "Solo Safe Music", exact: true }).click();+ await expect.poll(() => history(page)).toBe(depth + 2);+ await expect(page.getByRole("button", { name: "Solo Safe Music", exact: true })).toHaveAttribute("aria-pressed", "true");+ expect(await rms(page, 0, 3)).toBeCloseTo(both, 2);+ expect((await trackState(page, "Music")).soloSafe).toBe(true);++ // Saved with the project.+ const saved = await page.evaluate(() => JSON.parse(JSON.stringify(E().project.getState().getFullProject())).timeline.tracks.find((t: any) => t.name === "Music").soloSafe);+ expect(saved).toBe(true);++ // Mute still wins over solo-safe.+ await page.getByRole("button", { name: "Mute Music", exact: true }).click();+ expect(await rms(page, 0, 3)).toBeCloseTo(both / 2, 2);+ await page.getByRole("button", { name: "Mute Music", exact: true }).click();+ expect(await rms(page, 0, 3)).toBeCloseTo(both, 2);++ // Undo (unmute, mute, solo-safe) returns Music to "silenced by the solo".+ for (let i = 0; i < 3; i++) await page.evaluate(() => E().project.getState().undo());+ await expect(page.getByRole("button", { name: "Solo Safe Music", exact: true })).toHaveAttribute("aria-pressed", "false");+ expect(await rms(page, 0, 3)).toBeCloseTo(both / 2, 2);++ // Clearing the solo plays everything again.+ await page.getByRole("button", { name: "Solo Dialogue", exact: true }).click();+ expect(await rms(page, 0, 3)).toBeCloseTo(both, 2);+ });+});++test.describe("Audio output device", () => {+ test.describe.configure({ timeout: 240_000 });++ test.beforeEach(async ({ page }) => {+ await page.addInitScript(() => {+ const w = window as unknown as Record<string, any>;+ w.E = () => w.__openreelE2E;+ const device = (deviceId: string, label: string) => ({ deviceId, label, kind: "audiooutput", groupId: "g", toJSON: () => ({}) });+ w.__devices = [device("default", "Default - Speakers"), device("speakers-id", "Built-in Speakers"), device("headset-id", "USB Headset")];+ w.__sinkCalls = [] as string[];+ const media = navigator.mediaDevices;+ media.enumerateDevices = async () => w.__devices;+ // Headless Chrome has no real outputs: record the sink instead of asking the OS for a fake id.+ (AudioContext.prototype as any).setSinkId = async function (id: unknown) {+ w.__sinkCalls.push(typeof id === "string" ? id : JSON.stringify(id));+ };+ w.__plug = (list: string[]) => {+ const all = [device("default", "Default - Speakers"), device("speakers-id", "Built-in Speakers"), device("headset-id", "USB Headset")];+ w.__devices = all.filter((d) => d.deviceId === "default" || list.includes(d.deviceId));+ media.dispatchEvent(new Event("devicechange"));+ };+ });+ });++ const sinkCalls = (page: Page) => page.evaluate(() => (window as any).__sinkCalls as string[]);++ async function openPreferences(page: Page) {+ await page.evaluate(() => (window as any).__openreelE2E.settings.getState().openSettings("general"));+ await page.getByTestId("prefs-audio-output").waitFor({ timeout: 10_000 });+ }++ test("picker applies setSinkId, is remembered, falls back with a toast on unplug and returns on replug", async ({ page }) => {+ await openEditor(page);+ await openMixer(page); // creates the preview graph the sink is applied to+ await openPreferences(page);++ await page.getByTestId("prefs-audio-output-trigger").click();+ await expect(page.getByRole("option", { name: "System default" })).toBeVisible();+ await expect(page.getByRole("option", { name: "Built-in Speakers" })).toBeVisible();+ await page.getByRole("option", { name: "USB Headset" }).click();+ await expect.poll(async () => (await sinkCalls(page)).at(-1)).toBe("headset-id");+ await expect(page.getByTestId("prefs-audio-output-trigger")).toContainText("USB Headset");+ expect(await page.evaluate(() => JSON.parse(localStorage.getItem("openreel-settings") ?? "{}").state.audioOutputDeviceId)).toBe("headset-id");++ // The mixer carries the same picker, showing the same device.+ await page.keyboard.press("Escape");+ await expect(page.getByTestId("mixer-audio-output-trigger")).toContainText("USB Headset");++ // Unplug: audio moves to the system default and the user is told.+ await page.evaluate(() => (window as any).__plug(["speakers-id"]));+ await expect.poll(async () => (await sinkCalls(page)).at(-1)).toBe("");+ await expect(page.getByText("USB Headset disconnected")).toBeVisible();+ await expect(page.getByTestId("mixer-audio-output-status")).toContainText("disconnected");+ // The choice is still remembered.+ expect(await page.evaluate(() => JSON.parse(localStorage.getItem("openreel-settings") ?? "{}").state.audioOutputDeviceId)).toBe("headset-id");++ // Replug: back on the chosen device.+ await page.evaluate(() => (window as any).__plug(["speakers-id", "headset-id"]));+ await expect.poll(async () => (await sinkCalls(page)).at(-1)).toBe("headset-id");+ await expect(page.getByText("Back on USB Headset")).toBeVisible();++ // A fresh session applies the remembered device without opening Preferences.+ await page.reload();+ await page.getByRole("button", { name: /Horizontal/ }).click();+ await page.locator('canvas[aria-label^="Program frame"]').waitFor({ timeout: 60_000 });+ await openMixer(page);+ await expect.poll(async () => (await sinkCalls(page)).at(-1)).toBe("headset-id");+ await expect(page.getByTestId("mixer-audio-output-trigger")).toContainText("USB Headset");++ // Choosing the system default switches back and forgets the device.+ await page.getByTestId("mixer-audio-output-trigger").click();+ await page.getByRole("option", { name: "System default" }).click();+ await expect.poll(async () => (await sinkCalls(page)).at(-1)).toBe("");+ expect(await page.evaluate(() => JSON.parse(localStorage.getItem("openreel-settings") ?? "{}").state.audioOutputDeviceId)).toBe("");+ });+});diff --git a/apps/web/e2e/audio-routing.spec.ts b/apps/web/e2e/audio-routing.spec.tsindex f6c841c3..36f6a438 100644--- a/apps/web/e2e/audio-routing.spec.ts+++ b/apps/web/e2e/audio-routing.spec.ts@@ -247,55 +247,107 @@ test.describe("Audio buses, sends and submix routing", () => {return analyser;};const w = window as unknown as { __taps: Record<string, AnalyserNode> };- w.__taps = { master: tap(graph.getMasterGain()), bus: tap(graph.getBusOutputGain(musBus)) };+ w.__ctx = ctx; w.__taps = { master: tap(graph.getMasterGain()), bus: tap(graph.getBusOutputGain(musBus)) };},[mus[0]] as const,);- const measure = (which: "master" | "bus", ms: number) =>+ // Samples the named taps over the same window and returns each one's 75th-percentile RMS. Measuring the+ // master and the Music bus in one window halves the time spent inside the 4 s tones, which matters on+ // a starved machine where the page can stall for seconds between phases.+ const measureAll = <K extends "master" | "bus">(names: readonly K[], ms: number) =>page.evaluate(- async ([name, duration]) => {- const analyser = (window as unknown as { __taps: Record<string, AnalyserNode> }).__taps[name];- const buf = new Float32Array(analyser.fftSize);- const frames: number[] = [];+ async ([taps, duration]) => {+ const all = (window as unknown as { __taps: Record<string, AnalyserNode> }).__taps;+ const buf = new Float32Array(2048);+ const frames: Record<string, number[]> = Object.fromEntries((taps as string[]).map((n) => [n, []]));const t0 = performance.now();while (performance.now() - t0 < (duration as number)) {- analyser.getFloatTimeDomainData(buf);- let s = 0;- for (const v of buf) s += v * v;- frames.push(Math.sqrt(s / buf.length));+ for (const name of taps as string[]) {+ all[name].getFloatTimeDomainData(buf);+ let s = 0;+ for (const v of buf) s += v * v;+ frames[name].push(Math.sqrt(s / buf.length));+ }await new Promise((r) => setTimeout(r, 30));}- frames.sort((a, b) => a - b);// The tones are steady, so a high-ish percentile equals the median on a quiet machine. On a// starved one the page can stall past the 4 s tone's end and the tail frames are silence;- // the 75th percentile still reads the live tone (a flaky run under a load average of ~50- // measured the master 2.7 dB low through exactly that).- return frames[Math.floor(frames.length * 0.75)];+ // the 75th percentile still reads the live tone.+ return Object.fromEntries(+ Object.entries(frames).map(([name, list]) => {+ list.sort((a, b) => a - b);+ return [name, list[Math.floor(list.length * 0.75)]];+ }),+ );},- [which, ms] as const,- );- const play = async () => {+ [names, ms] as const,+ ) as Promise<Record<K, number>>;+ const measure = async (which: "master" | "bus", ms: number) => (await measureAll([which], ms))[which];+ const play = async (opts: { musicBus?: boolean } = { musicBus: true }) => {await page.evaluate(() => {const t = E().timeline.getState();t.pause();t.seekTo(0.2);});await settle(page, 300);- await page.evaluate(() => E().timeline.getState().play());- await settle(page, 700);+ await page.evaluate(() => {+ // The tones end 3.8 s after play starts (they are 4 s long and playback starts at 0.2 s); remember a+ // conservative end on the audio clock so a measurement can tell it ran off the end of the tone.+ const w = window as unknown as { __ctx: AudioContext; __toneEnd: number };+ w.__toneEnd = w.__ctx.currentTime + 3.7;+ E().timeline.getState().play();+ });+ // Wait for the taps to carry signal rather than assuming a fixed start latency: the first play+ // builds the live graph and schedules the clips on the main thread, which a starved CPU (software+ // GPU, shared CI runner) can delay past a second. The master always carries the Dialogue track, so+ // it is audible in every phase; while the Music bus tap is still wired in (before the send edit rebuilds+ // the bus nodes) it must carry the Music clip too, otherwise a measurement could span the moment Music joins in.+ await page.evaluate(+ async (needBus) => {+ const taps = (window as unknown as { __taps: Record<string, AnalyserNode> }).__taps;+ const buf = new Float32Array(2048);+ const peakOf = (analyser: AnalyserNode) => {+ analyser.getFloatTimeDomainData(buf);+ let peak = 0;+ for (const v of buf) peak = Math.max(peak, Math.abs(v));+ return peak;+ };+ const t0 = performance.now();+ while (performance.now() - t0 < 20_000) {+ if (peakOf(taps.master) > 0.01 && (!needBus || peakOf(taps.bus) > 0.004)) return;+ await new Promise((r) => setTimeout(r, 20));+ }+ },+ opts.musicBus === true,+ );+ await settle(page, 250); // the gate already proved signal; keep the measured window inside the 4 s tones+ };++ // Plays and measures one phase. A starved machine can stall the page for seconds, which pushes the+ // measurement window past the end of the 4 s tones and reads silence; such a window says nothing about+ // routing, so it is discarded and the phase is replayed (the assertions on the values never relax).+ const phase = async <K extends "master" | "bus">(names: readonly K[], opts?: { musicBus?: boolean }) => {+ let result: Record<K, number> | undefined;+ for (let attempt = 0; attempt < 4; attempt++) {+ await play(opts);+ result = await measureAll(names, 800);+ const inTone = await page.evaluate(() => {+ const w = window as unknown as { __ctx: AudioContext; __toneEnd: number };+ return w.__ctx.currentTime < w.__toneEnd;+ });+ if (inTone) break;+ }+ return result as Record<K, number>;};- await play();- const unity = await measure("master", 900);- const busUnity = await measure("bus", 600);+ const { master: unity, bus: busUnity } = await phase(["master", "bus"]);expect(unity, "both tones are audible live").toBeGreaterThan(0.01);expect(busUnity, "the Music bus carries the music track").toBeGreaterThan(0.004);// Edits apply to the playing graph: -12 dB on the Music bus.await page.evaluate((id) => E().project.getState().setAudioRack(id, { effects: [], volume: 0.25 }), mus[0]);- await play(); // the tones are 4 s long: restart so every phase measures live audio- const lowered = await measure("master", 900);- const busLowered = await measure("bus", 600);+ // The tones are 4 s long: every phase restarts them so it measures live audio.+ const { master: lowered, bus: busLowered } = await phase(["master", "bus"]);expect(db(busLowered / busUnity)).toBeGreaterThan(-12.8);expect(db(busLowered / busUnity)).toBeLessThan(-11.2);expect(db(lowered / unity)).toBeCloseTo(db((1 + 0.25) / 2), 0);@@ -309,14 +361,14 @@ test.describe("Audio buses, sends and submix routing", () => {},[ids.dialogue, fx[0]] as const,);- await play();- const withSend = await measure("master", 900);+ // The routing edit rebuilds the live bus nodes, so the Music bus tap made above no longer carries signal.+ const { master: withSend } = await phase(["master"], { musicBus: false });expect(db(withSend / lowered)).toBeGreaterThan(3.2); // dialogue doubles: (2 + 0.25) / (1 + 0.25) = 5.1 dBexpect(db(withSend / lowered)).toBeLessThan(6.5);// Muting the Music bus mid-playback silences its bus meter and drops the master to dialogue x2.await page.getByTestId(`bus-mute-${mus[0]}`).click();- await play();+ await play({ musicBus: false });expect(await measure("bus", 500)).toBeLessThan(1e-4);await page.evaluate(() => E().timeline.getState().pause());});diff --git a/apps/web/e2e/background-tasks.spec.ts b/apps/web/e2e/background-tasks.spec.tsnew file mode 100644index 00000000..f7c747b9--- /dev/null+++ b/apps/web/e2e/background-tasks.spec.ts@@ -0,0 +1,89 @@+import { expect, test, type Page } from "@playwright/test";+import { openEditor } from "./helpers";++/**+ * Unified background-task panel: export-queue jobs and tracked work show up in one popover with+ * progress, and cancel / retry reach the owning system.+ */++interface Hook {+ exportQueue: { getState(): Record<string, any> };+ backgroundTasks: {+ track<T>(o: Record<string, unknown>, w: (c: { signal: AbortSignal; progress(v: number | null, d?: string): void }) => Promise<T>): Promise<T>;+ get(id: string): { status: string; progress: number | null } | undefined;+ };+}++const openPanel = async (page: Page) => {+ await page.getByTestId("background-tasks-button").click();+ const panel = page.getByTestId("background-tasks-panel");+ await expect(panel).toBeVisible();+ return panel;+};++test("background tasks panel lists export jobs and forwards cancel and retry", async ({ page }) => {+ await openEditor(page);+ await expect(page.getByTestId("editor-status-bar").getByTestId("background-tasks-button")).toBeVisible();++ // Pause the queue so the job stays queued, then add one.+ const jobId = await page.evaluate(() => {+ const h = (window as unknown as { __openreelE2E: Hook }).__openreelE2E;+ h.exportQueue.getState().pause();+ const job = h.exportQueue.getState().enqueue({ settings: { width: 640, height: 360, frameRate: 30, format: "mp4", codec: "h264", bitrate: 2000 } });+ if (!job) throw new Error("enqueue returned null");+ return job.id as string;+ });++ await expect(page.getByTestId("background-tasks-badge")).toHaveAttribute("data-count", "1");+ const panel = await openPanel(page);+ const row = panel.locator(`[data-task-id="export-queue:${jobId}"]`);+ // The queue is paused, so the job reads "paused" and the row offers Resume (forwarded to the queue's Start).+ await expect(row).toHaveAttribute("data-status", "paused");+ await expect(row.getByRole("button", { name: /^Resume/ })).toBeVisible();+ await expect(panel.getByTestId("background-tasks-summary")).toContainText("1 background task");++ await row.getByRole("button", { name: /^Cancel/ }).click();+ await expect(row).toHaveAttribute("data-status", "cancelled");+ await row.getByRole("button", { name: /^Retry/ }).click();+ await expect(row).toHaveAttribute("data-status", "paused");+ // Per-row Pause is not offered: pausing is queue-wide.+ await expect(row.getByRole("button", { name: /^Pause/ })).toHaveCount(0);+ await row.getByRole("button", { name: /^Cancel/ }).click();+ await expect(row).toHaveAttribute("data-status", "cancelled");++ // Clear finished sticks even when the queue changes afterwards.+ await panel.getByRole("button", { name: "Clear finished tasks" }).click();+ await expect(panel.getByTestId("background-task-row")).toHaveCount(0);+ await page.evaluate(() => (window as unknown as { __openreelE2E: Hook }).__openreelE2E.exportQueue.getState().pause());+ await expect(panel.getByTestId("background-task-row")).toHaveCount(0);+});++test("tracked work shows progress, can be cancelled and a failure can be retried", async ({ page }) => {+ await openEditor(page);+ await page.evaluate(() => {+ const h = (window as unknown as { __openreelE2E: Hook }).__openreelE2E;+ void h.backgroundTasks+ .track({ id: "e2e:analysis", kind: "analysis", title: "Beat detection" }, (ctx) => {+ ctx.progress(0.4, "Analysing");+ return new Promise((_, reject) => ctx.signal.addEventListener("abort", () => reject(new DOMException("a", "AbortError"))));+ })+ .catch(() => undefined);+ void h.backgroundTasks.track({ id: "e2e:import", kind: "import", title: "Import · clip.mp4", retry: () => undefined }, async () => {+ throw new Error("Unsupported container");+ }).catch(() => undefined);+ });++ const panel = await openPanel(page);+ const analysis = panel.locator('[data-task-id="e2e:analysis"]');+ await expect(analysis).toHaveAttribute("data-status", "running");+ await expect(analysis.getByRole("progressbar")).toHaveAttribute("aria-valuenow", "40");+ const failed = panel.locator('[data-task-id="e2e:import"]');+ await expect(failed).toContainText("Unsupported container");+ await expect(failed.getByRole("button", { name: /^Retry/ })).toBeVisible();++ await analysis.getByRole("button", { name: /^Cancel/ }).click();+ await expect(analysis).toHaveAttribute("data-status", "cancelled");++ await panel.getByRole("button", { name: "Clear finished tasks" }).click();+ await expect(panel.getByTestId("background-task-row")).toHaveCount(0);+});diff --git a/apps/web/e2e/burn-in-lib.ts b/apps/web/e2e/burn-in-lib.tsnew file mode 100644index 00000000..31e45eee--- /dev/null+++ b/apps/web/e2e/burn-in-lib.ts@@ -0,0 +1,427 @@+import { expect, test, type Page } from "@playwright/test";+import { execFileSync } from "node:child_process";+import { clickClip, clipsOf, openEditor, readState, seek, settle } from "./helpers";++/**+ * Timecode and Clip Name burn-ins, on real pixels, in the three places a frame is drawn:+ * - the Program monitor (the preview pipeline),+ * - VideoEngine.renderFrame (what export calls for every frame),+ * - a real exported MP4 (the "Burn in timecode" switch in the Export dialog), decoded with ffmpeg.+ * The fixture's second scene (2 s to 4 s) is solid red, so any near-white pixel there is burn-in text.+ * Shared by the gpu project (burn-in.spec.ts) and the fallback projects (fallback-burn-in.spec.ts).+ */++const PROGRAM = 'canvas[aria-label^="Program frame"]';+/** 29.97 fps drop-frame, starting at the broadcast hour. */+const START_TIMECODE = "01:00:00;00";+/** Red scene instants: frame 74 and frame 90 of 29.97 fps. */+const T1 = 2.5;+const T2 = 3.003;+const TEXT_T1 = "01:00:02;14";+const TEXT_T2 = "01:00:03;00";++interface Region {+ x0: number;+ y0: number;+ x1: number;+ y1: number;+}++interface Stats {+ width: number;+ height: number;+ /** Near-white pixels inside each named region. */+ white: Record<string, number>;+ /** Near-white pixels outside every named region. */+ whiteElsewhere: number;+}++/** Regions as fractions of the frame: the timecode band (bottom centre) and the name band (top left). */+const REGIONS = {+ timecode: { x0: 0.3, y0: 0.82, x1: 0.7, y1: 1 },+ name: { x0: 0, y0: 0, x1: 0.45, y1: 0.16 },+} as const;++async function useBroadcastSequence(page: Page): Promise<string> {+ await page.evaluate(async (startTimecode) => {+ const e = (window as any).__openreelE2E;+ await e.project.getState().updateSettings({ frameRate: 29.97, startTimecode });+ }, START_TIMECODE);+ const settings = await page.evaluate(() => (window as any).__openreelE2E.project.getState().project.settings);+ expect(settings.frameRate).toBeCloseTo(29.97, 2);+ expect(settings.startTimecode).toBe(START_TIMECODE);+ const [clip] = clipsOf(await readState(page), "Main");+ return clip.id;+}++async function addEffectFromInspector(page: Page, clipId: string, label: string): Promise<void> {+ await page.evaluate(+ (id) => (window as any).__openreelE2E.inspectorNav.getState().requestSection("video-effects", id),+ clipId,+ );+ await settle(page, 1000);+ await page.getByRole("button", { name: "Add Effect", exact: true }).first().click();+ await page.getByRole("searchbox", { name: "Search visual effects" }).fill(label);+ await page.getByRole("button", { name: `Preview and add ${label}`, exact: true }).click();+ await settle(page, 900);+}++/** Renders `time` through the real VideoEngine and measures near-white pixels per region. */+async function engineStats(page: Page, time: number, options?: Record<string, unknown>, withoutEffects = false): Promise<Stats> {+ return page.evaluate(+ async ([t, opts, strip, regions]) => {+ const e = (window as any).__openreelE2E;+ let project = e.project.getState().project;+ if (strip) {+ project = {+ ...project,+ timeline: {+ ...project.timeline,+ tracks: project.timeline.tracks.map((track: any) => ({+ ...track,+ clips: track.clips.map((clip: any) => ({ ...clip, effects: [] })),+ })),+ },+ };+ }+ const W = 960;+ const H = 540;+ const frame = await e.video.getVideoEngine().renderFrame(project, t, W, H, opts ?? undefined);+ const canvas = new OffscreenCanvas(W, H);+ const g = canvas.getContext("2d", { willReadFrequently: true })!;+ g.drawImage(frame.image, 0, 0, W, H);+ frame.image.close?.();+ const data = g.getImageData(0, 0, W, H).data;+ const white: Record<string, number> = {};+ for (const name of Object.keys(regions)) white[name] = 0;+ let elsewhere = 0;+ for (let y = 0; y < H; y++) {+ for (let x = 0; x < W; x++) {+ const i = (y * W + x) * 4;+ if (data[i] < 215 || data[i + 1] < 215 || data[i + 2] < 215) continue;+ let inside = false;+ for (const [name, r] of Object.entries(regions as Record<string, any>)) {+ if (x >= r.x0 * W && x < r.x1 * W && y >= r.y0 * H && y < r.y1 * H) {+ white[name]++;+ inside = true;+ }+ }+ if (!inside) elsewhere++;+ }+ }+ return { width: W, height: H, white, whiteElsewhere: elsewhere };+ },+ [time, options ?? null, withoutEffects, REGIONS] as const,+ );+}++/** A 960x540 render of `time` as raw RGBA, to compare two renders pixel by pixel. */+async function engineBytes(page: Page, time: number, options?: Record<string, unknown>, withoutEffects = false): Promise<number[]> {+ return page.evaluate(+ async ([t, opts, strip]) => {+ const e = (window as any).__openreelE2E;+ let project = e.project.getState().project;+ if (strip) {+ project = {+ ...project,+ timeline: {+ ...project.timeline,+ tracks: project.timeline.tracks.map((track: any) => ({+ ...track,+ clips: track.clips.map((clip: any) => ({ ...clip, effects: [] })),+ })),+ },+ };+ }+ const W = 960;+ const H = 540;+ const frame = await e.video.getVideoEngine().renderFrame(project, t, W, H, opts ?? undefined);+ const canvas = new OffscreenCanvas(W, H);+ const g = canvas.getContext("2d", { willReadFrequently: true })!;+ g.drawImage(frame.image, 0, 0, W, H);+ frame.image.close?.();+ return Array.from(g.getImageData(0, 0, W, H).data);+ },+ [time, options ?? null, withoutEffects] as const,+ );+}++/** What the burn-in draws for `text` at 960x540 over the effect-free render of `time`: the reference for the overlay. */+async function expectedOverlayBytes(page: Page, time: number, text: string, params: Record<string, unknown>): Promise<number[]> {+ return page.evaluate(+ async ([t, label, p]) => {+ const e = (window as any).__openreelE2E;+ const project = e.project.getState().project;+ const stripped = {+ ...project,+ timeline: {+ ...project.timeline,+ tracks: project.timeline.tracks.map((track: any) => ({+ ...track,+ clips: track.clips.map((clip: any) => ({ ...clip, effects: [] })),+ })),+ },+ };+ const W = 960;+ const H = 540;+ const frame = await e.video.getVideoEngine().renderFrame(stripped, t, W, H);+ const canvas = new OffscreenCanvas(W, H);+ const g = canvas.getContext("2d", { willReadFrequently: true })!;+ g.drawImage(frame.image, 0, 0, W, H);+ frame.image.close?.();+ e.core.burnIn.drawBurnIn(g, "burn-in-timecode", { ...(p as object), __text: label }, W, H);+ return Array.from(g.getImageData(0, 0, W, H).data);+ },+ [time, text, params] as const,+ );+}++const maxDiff = (a: number[], b: number[]): number => {+ let max = 0;+ for (let i = 0; i < a.length; i++) {+ const d = Math.abs(a[i] - b[i]);+ if (d > max) max = d;+ }+ return max;+};++const changedPixels = (a: number[], b: number[], threshold = 60): number => {+ let n = 0;+ for (let i = 0; i < a.length; i += 4) {+ if (Math.abs(a[i] - b[i]) + Math.abs(a[i + 1] - b[i + 1]) + Math.abs(a[i + 2] - b[i + 2]) > threshold) n++;+ }+ return n;+};++async function programWhite(page: Page, regions: typeof REGIONS): Promise<Stats> {+ return page.evaluate(+ ([selector, rs]) => {+ const c = document.querySelector(selector as string) as HTMLCanvasElement;+ const probe = document.createElement("canvas");+ probe.width = c.width;+ probe.height = c.height;+ const g = probe.getContext("2d", { willReadFrequently: true })!;+ g.drawImage(c, 0, 0);+ const data = g.getImageData(0, 0, c.width, c.height).data;+ const white: Record<string, number> = {};+ for (const name of Object.keys(rs as object)) white[name] = 0;+ let elsewhere = 0;+ for (let y = 0; y < c.height; y++) {+ for (let x = 0; x < c.width; x++) {+ const i = (y * c.width + x) * 4;+ if (data[i] < 215 || data[i + 1] < 215 || data[i + 2] < 215) continue;+ let inside = false;+ for (const [name, r] of Object.entries(rs as Record<string, any>)) {+ if (x >= r.x0 * c.width && x < r.x1 * c.width && y >= r.y0 * c.height && y < r.y1 * c.height) {+ white[name]++;+ inside = true;+ }+ }+ if (!inside) elsewhere++;+ }+ }+ return { width: c.width, height: c.height, white, whiteElsewhere: elsewhere };+ },+ [PROGRAM, regions] as const,+ );+}++export function registerBurnInTests(): void {+ test.describe.configure({ mode: "serial" });++ test("Timecode and Clip Name effects: added in the inspector, drawn in the monitor and in export frames, drop-frame text, deterministic", async ({ page }) => {+ test.setTimeout(480_000);+ await openEditor(page);+ const clipId = await useBroadcastSequence(page);+ await clickClip(page, clipId);++ // Premiere-like authoring: both effects come from the Add Effect picker and have their own controls.+ await addEffectFromInspector(page, clipId, "Timecode");+ await expect(page.locator('[data-testid="burn-in-controls-burn-in-timecode"]')).toBeVisible();+ await addEffectFromInspector(page, clipId, "Clip Name");+ await expect(page.locator('[data-testid="burn-in-controls-burn-in-name"]')).toBeVisible();+ const effects = await page.evaluate((id) => {+ const project = (window as any).__openreelE2E.project.getState().project;+ for (const track of project.timeline.tracks) for (const clip of track.clips) if (clip.id === id) return clip.effects.map((x: any) => ({ type: x.type, params: x.params }));+ return [];+ }, clipId);+ expect(effects.map((x: any) => x.type)).toEqual(["burn-in-timecode", "burn-in-name"]);+ expect(effects[0].params).toMatchObject({ source: "sequence", position: "bottom-center", opacity: 100 });+ expect(effects[1].params).toMatchObject({ nameSource: "clip", position: "top-left" });++ // The controls write the effect: change the position in the inspector, then put it back.+ const timecodeControls = page.locator('[data-testid="burn-in-controls-burn-in-timecode"]');+ await timecodeControls.getByRole("combobox", { name: "Position" }).click();+ await page.getByRole("option", { name: "Top right" }).click();+ await expect+ .poll(() => page.evaluate((id) => {+ const project = (window as any).__openreelE2E.project.getState().project;+ for (const track of project.timeline.tracks) for (const clip of track.clips) if (clip.id === id) return clip.effects[0].params.position;+ return null;+ }, clipId))+ .toBe("top-right");+ await timecodeControls.getByRole("combobox", { name: "Position" }).click();+ await page.getByRole("option", { name: "Bottom center" }).click();+ await expect+ .poll(() => page.evaluate((id) => {+ const project = (window as any).__openreelE2E.project.getState().project;+ for (const track of project.timeline.tracks) for (const clip of track.clips) if (clip.id === id) return clip.effects[0].params.position;+ return null;+ }, clipId))+ .toBe("bottom-center");++ // Export-frame path: text lands in its two bands and nowhere else on the solid red scene.+ const baseline = await engineStats(page, T1, undefined, true);+ expect(baseline.white.timecode + baseline.white.name + baseline.whiteElsewhere).toBe(0);+ const first = await engineStats(page, T1);+ expect(first.white.timecode).toBeGreaterThan(150);+ expect(first.white.name).toBeGreaterThan(100);+ expect(first.whiteElsewhere).toBe(0);++ // Dynamic and deterministic: the digits change with the frame, and the same frame renders to the same bytes.+ const bytes1 = await engineBytes(page, T1);+ const bytes1Again = await engineBytes(page, T1);+ const bytes2 = await engineBytes(page, T2);+ expect(maxDiff(bytes1, bytes1Again)).toBe(0);+ expect(changedPixels(bytes1, bytes2)).toBeGreaterThan(20);+ // Only the timecode changes between the two frames; the clip name is the same, so the top-left band is identical.+ const topRows = 960 * 4 * Math.floor(540 * 0.16);+ expect(maxDiff(bytes1.slice(0, topRows), bytes2.slice(0, topRows))).toBe(0);++ // Program monitor: the same text appears on the preview canvas.+ await seek(page, T1);+ await settle(page, 1200);+ const monitor = await programWhite(page, REGIONS);+ expect(monitor.white.timecode).toBeGreaterThan(40);+ expect(monitor.white.name).toBeGreaterThan(25);+ expect(monitor.whiteElsewhere).toBe(0);+ await seek(page, T2);+ await settle(page, 1200);+ const monitor2 = await programWhite(page, REGIONS);+ expect(monitor2.white.timecode).toBeGreaterThan(40);+ expect(monitor2.white.timecode).not.toBe(monitor.white.timecode);+ });++ test("export Timecode burn-in overlay: the exact drop-frame text, position and scale, above everything, in every frame render", async ({ page }) => {+ test.setTimeout(480_000);+ await openEditor(page);+ await useBroadcastSequence(page);++ // The overlay is drawn by export for the frame time alone: compare with the reference drawing of the expected text.+ for (const [time, text] of [[T1, TEXT_T1], [T2, TEXT_T2]] as const) {+ const overlay = await engineBytes(page, time, { timecodeBurnIn: { enabled: true } });+ const expected = await expectedOverlayBytes(page, time, text, { position: "bottom-center", size: 5, opacity: 100, box: true });+ // Same drawing routine on a GPU-backed and a CPU-backed canvas: glyph edges may differ by anti-aliasing, glyphs+ // may not. A wrong digit changes hundreds of pixels.+ const wrong = await expectedOverlayBytes(page, time, text === TEXT_T1 ? TEXT_T2 : TEXT_T1, { position: "bottom-center", size: 5, opacity: 100, box: true });+ const right = changedPixels(overlay, expected, 90);+ const other = changedPixels(overlay, wrong, 90);+ expect(other, "a different timecode must look different").toBeGreaterThan(100);+ expect(right, `overlay at ${time}s must draw ${text}`).toBeLessThan(other / 10);+ }++ // It is a setting of the export, not of the project: no option, no text.+ const plain = await engineStats(page, T1);+ expect(plain.white.timecode + plain.whiteElsewhere).toBe(0);++ // Position, size, opacity and the box are honoured; a gap-free source timecode counts from the file's start.+ const moved = await engineStats(page, T1, { timecodeBurnIn: { enabled: true, position: "top-left", size: 8, box: false } });+ expect(moved.white.name).toBeGreaterThan(100);+ expect(moved.white.timecode).toBe(0);+ const faded = await engineBytes(page, T1, { timecodeBurnIn: { enabled: true, opacity: 0 } });+ expect(maxDiff(faded, await engineBytes(page, T1))).toBe(0);+ const source = await engineBytes(page, T1, { timecodeBurnIn: { enabled: true, source: "source" } });+ const expectedSequence = await expectedOverlayBytes(page, T1, TEXT_T1, { position: "bottom-center", size: 5, opacity: 100, box: true });+ const sourceExpected = await expectedOverlayBytes(page, T1, "00:00:02:15", { position: "bottom-center", size: 5, opacity: 100, box: true });+ expect(changedPixels(source, sourceExpected, 90), "source timecode 00:00:02:15").toBe(0);+ expect(changedPixels(source, expectedSequence, 90), "source mode differs from the sequence timecode").toBeGreaterThan(100);+ });++ test("Export dialog: one switch burns the sequence timecode into the exported MP4", async ({ page }, testInfo) => {+ test.setTimeout(600_000);+ await openEditor(page);+ await useBroadcastSequence(page);+ // 640x360 keeps the encode small; the burn-in scales with the frame.+ await page.evaluate(async () => {+ await (window as any).__openreelE2E.project.getState().updateSettings({ width: 640, height: 360 });+ });+ await seek(page, 0);+ await page.getByRole("button", { name: "Export", exact: true }).first().click();+ await settle(page, 1500);++ const burnIn = page.getByRole("switch", { name: "Burn in timecode" });+ await expect(burnIn).toBeVisible();+ await expect(burnIn).not.toBeChecked();+ await burnIn.click();+ await expect(burnIn).toBeChecked();+ // Position and source are one click away once it is on.+ await expect(page.getByRole("combobox", { name: "Burn-in position" })).toBeVisible();+ await expect(page.getByRole("combobox", { name: "Burn-in timecode source" })).toBeVisible();++ const download = page.waitForEvent("download", { timeout: 540_000 });+ await page.getByRole("button", { name: "Export Video" }).last().click();+ const file = testInfo.outputPath("burn-in.mp4");+ await (await download).saveAs(file);++ const W = 640;+ const H = 360;+ const frameAt = (t: number): Buffer =>+ execFileSync("ffmpeg", ["-v", "error", "-ss", String(t), "-i", file, "-frames:v", "1", "-vf", `scale=${W}:${H}`, "-f", "rawvideo", "-pix_fmt", "rgb24", "-"], {+ maxBuffer: 64 * 1024 * 1024,+ });+ const white = (buf: Buffer): { band: number; elsewhere: number; mask: Uint8Array } => {+ const mask = new Uint8Array(W * H);+ let band = 0;+ let elsewhere = 0;+ for (let y = 0; y < H; y++) {+ for (let x = 0; x < W; x++) {+ const i = (y * W + x) * 3;+ if (buf[i] < 200 || buf[i + 1] < 200 || buf[i + 2] < 200) continue;+ mask[y * W + x] = 1;+ if (x >= W * 0.3 && x < W * 0.7 && y >= H * 0.82) band++;+ else elsewhere++;+ }+ }+ return { band, elsewhere, mask };+ };+ const f1 = frameAt(T1);+ const f2 = frameAt(3.0);+ expect(f1.length).toBe(W * H * 3);+ const m1 = white(f1);+ const m2 = white(f2);+ expect(m1.band).toBeGreaterThan(60);+ expect(m1.elsewhere).toBe(0);+ expect(m2.band).toBeGreaterThan(60);+ expect(m2.elsewhere).toBe(0);+ let differing = 0;+ for (let i = 0; i < m1.mask.length; i++) if (m1.mask[i] !== m2.mask[i]) differing++;+ expect(differing, "the digits change from frame to frame").toBeGreaterThan(10);++ // The exported text is the reference drawing of the right digits: high overlap of the white glyph pixels.+ const reference = await page.evaluate(+ async ([w, h, text]) => {+ const e = (window as any).__openreelE2E;+ const canvas = new OffscreenCanvas(w as number, h as number);+ const g = canvas.getContext("2d", { willReadFrequently: true })!;+ g.fillStyle = "#ff0000";+ g.fillRect(0, 0, w as number, h as number);+ e.core.burnIn.drawBurnIn(g, "burn-in-timecode", { position: "bottom-center", size: 5, opacity: 100, box: true, __text: text }, w, h);+ const data = g.getImageData(0, 0, w as number, h as number).data;+ const out: number[] = [];+ for (let i = 0; i < data.length; i += 4) out.push(data[i] > 200 && data[i + 1] > 200 && data[i + 2] > 200 ? 1 : 0);+ return out;+ },+ [W, H, "01:00:02;14"] as const,+ );+ let inter = 0;+ let union = 0;+ for (let i = 0; i < reference.length; i++) {+ const a = reference[i] === 1;+ const b = m1.mask[i] === 1;+ if (a && b) inter++;+ if (a || b) union++;+ }+ expect(union).toBeGreaterThan(0);+ expect(inter / union, "exported glyphs overlap the reference rendering of 01:00:02;14").toBeGreaterThan(0.5);+ });+}diff --git a/apps/web/e2e/burn-in.spec.ts b/apps/web/e2e/burn-in.spec.tsnew file mode 100644index 00000000..dcf78d6f--- /dev/null+++ b/apps/web/e2e/burn-in.spec.ts@@ -0,0 +1,5 @@+import { registerBurnInTests } from "./burn-in-lib";++// Runs under the gpu project. The fallback-nowebgpu / fallback-software projects run the same flow from+// fallback-burn-in.spec.ts (they only match fallback-*.spec.ts).+registerBurnInTests();diff --git a/apps/web/e2e/camera-log.spec.ts b/apps/web/e2e/camera-log.spec.tsnew file mode 100644index 00000000..ea02f7fd--- /dev/null+++ b/apps/web/e2e/camera-log.spec.ts@@ -0,0 +1,183 @@+import { expect, test } from "@playwright/test";+import { ensureLumetriFixtures, openColorGrading, openWithClips, bandMeans } from "./lumetri-basic-lib";+import { openHookPage, settle, snapStable, undo } from "./helpers";++/**+ * Camera log input presets. Two flows:+ * 1. the WebGL2 shader decode of every camera curve against the Float32 CPU reference (same GLSL source the unit+ * tests hold to the TypeScript curve), on the "gpu" project;+ * 2. the Color tab "Camera input" picker: choosing S-Log3 changes the Program frame to exactly what the shared CPU+ * input transform predicts for the ramp, one undo reverts it.+ */++interface CoreHook {+ hdrWorking: Record<string, any>;+ hdrGpu: Record<string, any>;+ cameraLog: Record<string, any>;+ inputTransform: Record<string, any>;+}++test.beforeAll(() => ensureLumetriFixtures());++test("the shader decodes every camera log curve like the CPU reference (ramp through all nine transfers)", async ({ page }, testInfo) => {+ test.setTimeout(120_000);+ await openHookPage(page);+ const result = await page.evaluate(() => {+ const core = (window as unknown as { __openreelE2E: { core: CoreHook } }).__openreelE2E.core;+ if (!core.hdrGpu.isGpuHdrAvailable()) return { skipped: "no WebGL2 with EXT_color_buffer_float" };+ const hw = core.hdrWorking;+ const W = 256;+ const H = 8;+ // 8-bit grey ramp: every code 0..255 once, left to right.+ const data = new Uint8ClampedArray(W * H * 4);+ for (let y = 0; y < H; y++)+ for (let x = 0; x < W; x++) {+ const o = (y * W + x) * 4;+ data[o] = x;+ data[o + 1] = x;+ data[o + 2] = x;+ data[o + 3] = 255;+ }+ const identity = { position: { x: 0, y: 0 }, scale: { x: 1, y: 1 }, rotation: 0, anchor: { x: 0.5, y: 0.5 }, opacity: 1, fitMode: "stretch" };+ const geometry = hw.computeLayerGeometry(identity, W, H, W, H);+ const cpu = new hw.CpuHdrCompositor();+ const gpu = new core.hdrGpu.GpuHdrCompositor();+ const out: Array<{ id: string; maxRel: number; over: number; peak: number }> = [];+ for (const def of core.cameraLog.CAMERA_LOGS as Array<{ id: string; gamut: string }>) {+ const decode = hw.hdrSourceDecode({ primaries: def.gamut === "bt2020" ? "bt2020" : def.gamut, transfer: def.id, matrix: "rgb", fullRange: true });+ const run = (comp: any) => {+ comp.begin(W, H);+ comp.drawCodes({ depth: 8, width: W, height: H, data }, decode, { geometry, opacity: 1 });+ return comp.readFrame().data as Float32Array;+ };+ const a = run(cpu);+ const b = run(gpu);+ let maxRel = 0;+ let over = 0;+ let peak = 0;+ for (let i = 0; i < a.length; i++) {+ const rel = Math.abs(a[i] - b[i]) / Math.max(0.02, Math.abs(a[i]));+ if (rel > maxRel) maxRel = rel;+ if (rel > 0.02) over++;+ if (i % 4 === 0 && b[i] > peak) peak = b[i];+ }+ out.push({ id: def.id, maxRel, over: over / a.length, peak });+ }+ gpu.dispose();+ cpu.dispose();+ return { curves: out };+ });+ console.log(`[${testInfo.project.name}] camera log shader parity: ${JSON.stringify(result)}`);+ if ("skipped" in result) test.skip(true, String(result.skipped));+ const { curves } = result as { curves: Array<{ id: string; maxRel: number; over: number; peak: number }> };+ expect(curves).toHaveLength(9);+ for (const c of curves) {+ expect(c.over, `${c.id} fraction of samples off by more than 2%`).toBeLessThan(0.005);+ // A real log decode: signal 1.0 is far above SDR white.+ expect(c.peak, `${c.id} peak`).toBeGreaterThan(1.5);+ }+});++test("Color tab Camera input: picking S-Log3 converts the Program frame like the CPU input transform and undoes", async ({ page }) => {+ test.setTimeout(240_000);+ const [clipId] = await openWithClips(page, ["lumetri-gradient.mp4"]);+ await openColorGrading(page, clipId);++ const select = page.getByTestId("camera-input-select");+ await select.scrollIntoViewIfNeeded();+ await expect(select).toHaveValue("tagged");+ await settle(page, 400);+ await snapStable(page, "before");+ const before = await bandMeans(page, "before", 8);++ await select.selectOption("log-slog3");+ await expect(page.getByTestId("camera-input-status")).toContainText("Sony S-Log3 / S-Gamut3.Cine");+ await settle(page, 1200);+ await snapStable(page, "slog3");+ const after = await bandMeans(page, "slog3", 8);++ const media = await page.evaluate(() => {+ const e = (window as unknown as { __openreelE2E: { project: { getState(): any } } }).__openreelE2E;+ return e.project.getState().project.mediaLibrary.items.map((i: any) => i.colorInterpretation);+ });+ expect(media).toEqual(["log-slog3"]);++ // Predicted by the shared input transform from the decoded ramp (grey code = x / width).+ const expected = await page.evaluate(+ ([count]) => {+ const core = (window as unknown as { __openreelE2E: { core: CoreHook } }).__openreelE2E.core;+ const space = { primaries: "sgamut3cine", transfer: "slog3", matrix: "rgb", fullRange: true };+ const t = core.inputTransform.createInputTransform(space);+ const out: number[] = [];+ for (let b = 0; b < (count as number); b++) {+ let sum = 0;+ const N = 64;+ for (let k = 0; k < N; k++) {+ const code = Math.round(((b + (k + 0.5) / N) / (count as number)) * 255) / 255;+ sum += core.inputTransform.transformPixel(code, code, code, t)[1] * 255;+ }+ out.push(sum / N);+ }+ return out;+ },+ [8] as const,+ );+ const greens = after.bands.map((b) => b[1]);+ console.log(`[camera-log] bands before=${before.bands.map((b) => b[1].toFixed(0))} after=${greens.map((g) => g.toFixed(0))} expected=${expected.map((g) => g.toFixed(0))}`);+ // The frame really changed (a log ramp is a different image) ...+ expect(Math.max(...greens.map((g, i) => Math.abs(g - before.bands[i][1])))).toBeGreaterThan(20);+ // ... and matches the transform within the 8-bit decode / encode rounding.+ greens.forEach((g, i) => expect(Math.abs(g - expected[i]), `band ${i}`).toBeLessThan(8));++ await undo(page);+ await settle(page, 1200);+ const reverted = await page.evaluate(() => {+ const e = (window as unknown as { __openreelE2E: { project: { getState(): any } } }).__openreelE2E;+ return e.project.getState().project.mediaLibrary.items.map((i: any) => i.colorInterpretation ?? null);+ });+ expect(reverted).toEqual([null]);+ await expect(page.getByTestId("camera-input-select")).toHaveValue("tagged");+});++test("Interpret Footage dialog: camera select is labelled, fits a 1366x700 laptop viewport and applies one undoable step", async ({ page }) => {+ test.setTimeout(240_000);+ await openWithClips(page, ["lumetri-gradient.mp4"]);+ await page.setViewportSize({ width: 1366, height: 700 });+ await settle(page, 400);+ await page.getByRole("button", { name: "Media actions for lumetri-gradient.mp4" }).click();+ await page.getByTestId("menu-interpret-footage").click();+ const dialog = page.getByTestId("interpret-footage-dialog");+ await expect(dialog).toBeVisible();++ await settle(page, 600);+ const box = await dialog.boundingBox();+ console.log(`[camera-log] dialog box ${JSON.stringify(box)}`);+ expect(box!.y).toBeGreaterThanOrEqual(0);+ expect(box!.y + box!.height).toBeLessThanOrEqual(700);+ const apply = dialog.getByTestId("interpret-apply");+ await expect(apply).toBeInViewport();+ // Nothing may be clipped sideways: the longest camera option once pushed the grid wider than the dialog.+ const fit = await dialog.evaluate((el) => ({ scroll: el.scrollWidth, client: el.clientWidth, right: el.getBoundingClientRect().right }));+ expect(fit.scroll, "dialog content overflows horizontally").toBeLessThanOrEqual(fit.client);+ const applyBox = await apply.boundingBox();+ expect(applyBox!.x + applyBox!.width).toBeLessThanOrEqual(fit.right);++ const select = dialog.getByLabel("Camera input (log)");+ await expect(select).toHaveValue("");+ await select.selectOption("log-logc3");+ await expect(page.getByTestId("media-color-effective")).toContainText("LogC3");+ await apply.click();+ await expect(dialog).toBeHidden();+ const media = await page.evaluate(() => {+ const e = (window as unknown as { __openreelE2E: { project: { getState(): any } } }).__openreelE2E;+ return e.project.getState().project.mediaLibrary.items.map((i: any) => i.colorInterpretation);+ });+ expect(media).toEqual(["log-logc3"]);+ await undo(page);+ await settle(page, 600);+ const reverted = await page.evaluate(() => {+ const e = (window as unknown as { __openreelE2E: { project: { getState(): any } } }).__openreelE2E;+ return e.project.getState().project.mediaLibrary.items.map((i: any) => i.colorInterpretation ?? null);+ });+ expect(reverted).toEqual([null]);+});diff --git a/apps/web/e2e/caption-formats.spec.ts b/apps/web/e2e/caption-formats.spec.tsnew file mode 100644index 00000000..32dd0857--- /dev/null+++ b/apps/web/e2e/caption-formats.spec.ts@@ -0,0 +1,150 @@+import { expect, test, type Page } from "@playwright/test";+import { mkdtempSync, readFileSync } from "node:fs";+import { tmpdir } from "node:os";+import { join } from "node:path";+import { dirname } from "node:path";+import { fileURLToPath } from "node:url";+import { clipsOf, importInput, openEditor, readState, seek, settle } from "./helpers";++const REAL_FOOTAGE = join(dirname(fileURLToPath(import.meta.url)), "fixtures", "real-interview.mp4");++/** SBV and TTML / DFXP caption import and export in real Chrome, including skipped-cue notes. */++const workDir = mkdtempSync(join(tmpdir(), "openreel-capfmt-"));++const TTML = `<?xml version="1.0" encoding="UTF-8"?>+<tt xmlns="http://www.w3.org/ns/ttml" xmlns:tts="http://www.w3.org/ns/ttml#styling" xml:lang="en">+ <head>+ <styling><style xml:id="y" tts:color="#FFFF00"/><style xml:id="rs" tts:color="#FF0000" tts:textAlign="right" tts:displayAlign="before"/></styling>+ <layout><region xml:id="top" tts:origin="10% 5%" tts:extent="80% 15%" tts:displayAlign="before"/>+ <region xml:id="viaStyle" style="rs" tts:origin="10% 5%" tts:extent="80% 15%"/></layout>+ </head>+ <body><div>+ <p begin="00:00:01.000" end="00:00:02.500" region="top" style="y">Top yellow</p>+ <p begin="00:00:02.600" end="00:00:02.900" region="viaStyle">Region via style</p>+ <p begin="00:00:03.000" end="00:00:04.000">Plain<br/>two lines</p>+ <p>Missing timing</p>+ </div></body>+</tt>`;++interface Cue { text: string; start: number; end: number; track: string; color?: string; position?: string }++const cues = (page: Page, track?: string): Promise<Cue[]> =>+ page.evaluate((t) => {+ const subs = (window as any).__openreelE2E.project.getState().project.timeline.subtitles as any[];+ return subs+ .filter((s) => t === undefined || (s.captionTrackId ?? "") === t)+ .map((s) => ({ text: s.text, start: s.startTime, end: s.endTime, track: s.captionTrackId ?? "", color: s.style?.color, position: s.style?.position }))+ .sort((a, b) => a.start - b.start);+ }, track);++async function openTranscript(page: Page) {+ await page.getByRole("button", { name: "Text & captions", exact: true }).click();+ await page.getByRole("tab", { name: "Transcript" }).click();+ await page.getByTestId("transcript-panel").waitFor();+}++const importAs = async (page: Page, name: string, buffer: Buffer, lang: string) => {+ await page.getByLabel("Language of the imported captions").fill(lang);+ await page.getByTestId("transcript-import-input").setInputFiles({ name, mimeType: "application/octet-stream", buffer });+};++async function exportAs(page: Page, format: string, file: string): Promise<string> {+ await page.getByRole("combobox", { name: "Caption export format" }).click();+ await page.getByRole("option", { name: format }).click();+ const [download] = await Promise.all([page.waitForEvent("download"), page.getByRole("button", { name: "Export captions" }).click()]);+ const path = join(workDir, file);+ await download.saveAs(path);+ return path;+}++test("TTML import maps style and region, skips a bad paragraph with a visible note; SBV and TTML export re-import", async ({ page }) => {+ await openEditor(page);+ await openTranscript(page);++ await importAs(page, "sample.ttml", Buffer.from(TTML), "en");+ await expect.poll(async () => (await cues(page, "en")).length).toBe(3);+ const first = (await cues(page, "en"))[0];+ expect(first).toMatchObject({ text: "Top yellow", start: 1, end: 2.5, color: "#FFFF00", position: "top" });+ expect((await cues(page, "en"))[1]).toMatchObject({ text: "Region via style", color: "#FF0000", position: "top" });+ await expect(page.getByTestId("caption-export-report")).toContainText("Skipped");+ await expect(page.getByTestId("caption-export-report")).toContainText("no timing");++ // Not a caption file at all: a clear failure, nothing added.+ await importAs(page, "notes.xml", Buffer.from("<html><body>hi</body></html>"), "bad");+ await expect(page.getByTestId("caption-export-report")).toContainText("Not a TTML");+ expect((await cues(page, "bad")).length).toBe(0);++ const sbv = await exportAs(page, "SBV (YouTube)", "out.sbv");+ expect(readFileSync(sbv, "utf8")).toContain("0:00:01.000,0:00:02.500\nTop yellow");+ const ttml = await exportAs(page, "TTML (IMSC1)", "out.ttml");+ expect(readFileSync(ttml, "utf8")).toContain("<tt ");++ await importAs(page, "out.sbv", readFileSync(sbv), "sbv");+ await expect.poll(async () => (await cues(page, "sbv")).length).toBeGreaterThan(0);+ await importAs(page, "out.ttml", readFileSync(ttml), "ttml");+ await expect.poll(async () => (await cues(page, "ttml")).length).toBeGreaterThan(0);+ const all = await cues(page);+ for (const track of ["sbv", "ttml"]) {+ const back = all.filter((c) => c.track === track);+ expect(back.map((c) => c.text)).toContain("Top yellow");+ }+});++test("imported TTML colour renders over real footage in the program monitor", async ({ page }) => {+ test.setTimeout(240_000);+ await page.addInitScript(() => {+ try {+ localStorage.setItem("openreel-onboarding-complete", "true");+ localStorage.setItem("openreel-mograph-tour-complete", "true");+ } catch { /* storage unavailable */ }+ });+ await page.goto("/");+ await page.getByRole("button", { name: /Horizontal/ }).click();+ const canvas = page.locator('canvas[aria-label^="Program frame"]');+ await canvas.waitFor({ timeout: 60_000 });+ await importInput(page).setInputFiles(REAL_FOOTAGE);+ await page.getByLabel("Select media real-interview.mp4").waitFor({ timeout: 90_000 });+ await page.getByRole("button", { name: "Media actions for real-interview.mp4" }).click();+ await page.getByRole("menuitem", { name: "Add to timeline" }).click();+ await page.getByRole("button", { name: "Match Video" }).click({ timeout: 8_000 }).catch(() => undefined);+ await expect.poll(async () => clipsOf(await readState(page), "Main").length, { timeout: 30_000 }).toBe(1);++ await openTranscript(page);+ await importAs(page, "sample.ttml", Buffer.from(TTML), "en");+ await expect.poll(async () => (await cues(page, "en")).length).toBe(3);++ const countYellow = () =>+ canvas.evaluate((c: HTMLCanvasElement) => {+ const copy = document.createElement("canvas");+ copy.width = c.width;+ copy.height = c.height;+ const ctx = copy.getContext("2d")!;+ ctx.drawImage(c, 0, 0);+ const d = ctx.getImageData(0, 0, c.width, c.height).data;+ let n = 0;+ let top = c.height;+ let bottom = -1;+ for (let i = 0; i < d.length; i += 4) {+ if (d[i] > 230 && d[i + 1] > 230 && d[i + 2] < 60) {+ n++;+ const y = Math.floor(i / 4 / c.width);+ if (y < top) top = y;+ if (y > bottom) bottom = y;+ }+ }+ return { n, heightFraction: bottom >= top ? (bottom - top + 1) / c.height : 0 };+ });+ await seek(page, 1.7);+ await settle(page, 800);+ const duringStats = await countYellow();+ const during = duringStats.n;+ await page.screenshot({ path: join(workDir, "real-footage-caption.png") });+ await seek(page, 2.9);+ await settle(page, 800);+ const outside = (await countYellow()).n;+ expect(during, "yellow caption pixels while the cue is active").toBeGreaterThan(200);+ expect(during).toBeGreaterThan(outside + 150);+ // The imported cue uses the normal caption size: it must not balloon over the frame.+ expect(duringStats.heightFraction, "yellow caption occupies a modest band of the frame").toBeLessThan(0.25);+});diff --git a/apps/web/e2e/caption-translate.spec.ts b/apps/web/e2e/caption-translate.spec.tsnew file mode 100644index 00000000..ffa12cb2--- /dev/null+++ b/apps/web/e2e/caption-translate.spec.ts@@ -0,0 +1,172 @@+import { expect, test, type Page } from "@playwright/test";+import { openEditor, press, seek } from "./helpers";++/**+ * Caption translation in real Chrome. A test double stands in for the browser's on-device+ * Translator API (headless Chrome ships without language packs); everything else is the real+ * editor: the Transcript panel, the translation command, the action system and undo.+ */++const TRANSCRIPT = {+ language: "en",+ segments: [+ { speaker: "Ann", words: [{ word: "Welcome", start: 0.5, end: 0.9 }, { word: "home.", start: 0.9, end: 1.5 }] },+ { speaker: "Bob", words: [{ word: "Thanks", start: 2.0, end: 2.5 }, { word: "all.", start: 2.5, end: 3.0 }] },+ ],+};++const mockTranslator = (ms: number) => {+ (window as any).Translator = {+ availability: async () => "available",+ create: async () => ({+ translate: (text: string, o?: { signal?: AbortSignal }) =>+ new Promise<string>((resolve, reject) => {+ const t = setTimeout(() => resolve(`[es] ${text}`), ms);+ o?.signal?.addEventListener("abort", () => {+ clearTimeout(t);+ reject(new DOMException("aborted", "AbortError"));+ });+ }),+ destroy: () => {},+ }),+ };+};++const cues = (page: Page, track: string) =>+ page.evaluate((t) => {+ const subs = (window as any).__openreelE2E.project.getState().project.timeline.subtitles as any[];+ return subs+ .filter((s) => (s.captionTrackId ?? "") === t)+ .map((s) => ({ text: s.text, start: s.startTime, end: s.endTime, speaker: s.speaker, language: s.language }))+ .sort((a, b) => a.start - b.start);+ }, track);++async function importAndOpenTranslate(page: Page) {+ await openEditor(page);+ await page.getByRole("button", { name: "Text & captions", exact: true }).click();+ await page.getByRole("tab", { name: "Transcript" }).click();+ await page.getByTestId("transcript-panel").waitFor();+ await page.getByTestId("transcript-import-input").setInputFiles({+ name: "interview.json",+ mimeType: "application/json",+ buffer: Buffer.from(JSON.stringify(TRANSCRIPT)),+ });+ await expect.poll(async () => (await cues(page, "")).length).toBe(2);+ await page.getByRole("button", { name: "Translate", exact: true }).click();+ await page.getByLabel("Source language").fill("en");+}++test("translates a caption track into a new track with the same timing, and undo removes it", async ({ page }) => {+ await page.addInitScript(mockTranslator, 5);+ await importAndOpenTranslate(page);+ await expect(page.getByTestId("translate-engine")).toContainText("Browser");+ await page.getByRole("button", { name: /^Translate to/ }).click();+ await expect.poll(async () => (await cues(page, "es")).length).toBe(2);++ const original = await cues(page, "");+ const translated = await cues(page, "es");+ expect(translated.map((c) => c.text)).toEqual(original.map((c) => `[es] ${c.text}`));+ expect(translated.map((c) => [c.start, c.end])).toEqual(original.map((c) => [c.start, c.end]));+ expect(translated.map((c) => c.speaker)).toEqual(original.map((c) => c.speaker));+ expect(translated.every((c) => c.language === "es")).toBe(true);+ expect(original.map((c) => c.text)).toEqual(["Welcome home.", "Thanks all."]);++ await page.locator("body").click({ position: { x: 5, y: 5 } });+ await press(page, "Meta+z");+ await expect.poll(async () => (await cues(page, "es")).length).toBe(0);+ expect((await cues(page, "")).length).toBe(2);+});++test("cancelling a translation adds nothing", async ({ page }) => {+ await page.addInitScript(mockTranslator, 2000);+ await importAndOpenTranslate(page);+ await page.getByRole("button", { name: /^Translate to/ }).click();+ await expect(page.getByTestId("translate-progress")).toBeVisible();+ await page.getByRole("button", { name: "Cancel", exact: true }).click();+ await expect(page.getByRole("button", { name: /^Translate to/ })).toBeVisible();+ expect((await cues(page, "es")).length).toBe(0);+ expect((await cues(page, "")).length).toBe(2);+});++test("shows a clear unavailable state when no translator exists", async ({ page }) => {+ await page.addInitScript(() => {+ delete (window as any).Translator;+ });+ await importAndOpenTranslate(page);+ await expect(page.getByTestId("translate-unavailable")).toContainText("No translator is available");+ await expect(page.getByRole("button", { name: /^Translate to/ })).toBeDisabled();+});++const spyDrawnText = () => {+ const drawn: string[] = [];+ (window as any).__drawnText = drawn;+ const patch = (proto: { fillText: (...a: any[]) => void } | undefined) => {+ if (!proto) return;+ const original = proto.fillText;+ proto.fillText = function (this: unknown, text: string, ...rest: number[]) {+ drawn.push(String(text));+ return (original as any).call(this, text, ...rest);+ };+ };+ patch(CanvasRenderingContext2D.prototype);+ patch(typeof OffscreenCanvasRenderingContext2D === "undefined" ? undefined : OffscreenCanvasRenderingContext2D.prototype);+};++const drawnAt = async (page: Page, time: number) => {+ await page.evaluate(() => ((window as any).__drawnText.length = 0));+ // Move off and back so the preview redraws this frame.+ await seek(page, time + 0.4);+ await page.evaluate(() => ((window as any).__drawnText.length = 0));+ await seek(page, time);+ return page.evaluate(() => ((window as any).__drawnText as string[]).join(" | "));+};++test("the preview draws one language at a time; Show in picture switches it, and export follows", async ({ page }) => {+ await page.addInitScript(mockTranslator, 5);+ await page.addInitScript(spyDrawnText);+ await importAndOpenTranslate(page);+ await page.getByRole("button", { name: /^Translate to/ }).click();+ await expect.poll(async () => (await cues(page, "es")).length).toBe(2);++ // The translation is kept out of the picture: only the original is drawn, never both stacked.+ const hidden = await page.evaluate(() => {+ const subs = (window as any).__openreelE2E.project.getState().project.timeline.subtitles as any[];+ return subs.filter((s) => s.captionTrackId === "es").every((s) => s.hidden === true) && subs.filter((s) => !s.captionTrackId).every((s) => !s.hidden);+ });+ expect(hidden).toBe(true);+ const original = await drawnAt(page, 1.0);+ expect(original.split(" | ")).toContain("Welcome home.");+ expect(original).not.toContain("[es]");++ // Show the translation: the original leaves the picture.+ await page.getByRole("switch", { name: "Show this caption track in the picture" }).click();+ await expect.poll(() => drawnAt(page, 1.0)).toContain("[es] Welcome home.");+ expect((await drawnAt(page, 1.0)).split(" | ")).not.toContain("Welcome home.");++ // Burned-in export uses the same selection.+ const burned = await page.evaluate(async () => {+ const subs = (window as any).__openreelE2E.project.getState().project.timeline.subtitles as any[];+ return subs.filter((s) => !s.hidden).map((s) => s.captionTrackId ?? "");+ });+ expect(new Set(burned)).toEqual(new Set(["es"]));+});++test("export frames and cached segments draw only the visible track, never the hidden translation", async ({ page }) => {+ await page.addInitScript(mockTranslator, 5);+ await page.addInitScript(spyDrawnText);+ await importAndOpenTranslate(page);+ await page.getByRole("button", { name: /^Translate to/ }).click();+ await expect.poll(async () => (await cues(page, "es")).length).toBe(2);++ // The engine path that exportFrame / image / GIF / render-bridge / render-cache all go through.+ const drawn = await page.evaluate(async () => {+ const e2e = (window as any).__openreelE2E;+ const project = e2e.project.getState().project;+ (window as any).__drawnText.length = 0;+ const frame = await e2e.video.getVideoEngine().renderFrame(project, 1.0, 640, 360);+ frame.image?.close?.();+ return ((window as any).__drawnText as string[]).join(" | ");+ });+ expect(drawn.split(" | ")).toContain("Welcome home.");+ expect(drawn).not.toContain("[es]");+});diff --git a/apps/web/e2e/clip-markers.spec.ts b/apps/web/e2e/clip-markers.spec.tsnew file mode 100644index 00000000..97dc94bc--- /dev/null+++ b/apps/web/e2e/clip-markers.spec.ts@@ -0,0 +1,65 @@+import { expect, test, type Page } from "@playwright/test";+import { clipLocator, clipsOf, openEditor, readState, seek, setZoom, settle, splitIntoThree, undo } from "./helpers";++/**+ * Master-clip markers: a marker set in the Source monitor lives on the media and shows on every+ * timeline instance at the right offset (here: only on the split clip whose source range holds it).+ */++const MEDIA = "Select media three-scenes.mp4";++interface Hook {+ __openreelE2E: {+ project: { getState(): { project: { mediaLibrary: { items: { id: string; markers?: { time: number; label: string }[] }[] } } } };+ };+}++const masterMarkers = (page: Page) =>+ page.evaluate(() =>+ (window as unknown as Hook).__openreelE2E.project+ .getState()+ .project.mediaLibrary.items.flatMap((i) => i.markers ?? [])+ .map((m) => ({ time: m.time, label: m.label })),+ );++test("a Source monitor marker shows on the timeline instance that contains it, lists in the panel and undoes", async ({ page }) => {+ test.setTimeout(180_000);+ await openEditor(page);+ await splitIntoThree(page);+ await setZoom(page, 100);++ await page.getByLabel(MEDIA).dblclick();+ await expect(page.getByTestId("source-monitor")).toBeVisible();+ await settle(page, 500);+ await page.evaluate(() => {+ const e = (window as unknown as { __openreelE2E: { source: { getState(): { setPosition(n: number): void; stop(): void } } } }).__openreelE2E;+ e.source.getState().stop();+ e.source.getState().setPosition(3);+ });+ await settle(page, 300);+ await page.getByTestId("source-add-marker").click();+ await expect.poll(async () => (await masterMarkers(page)).length).toBe(1);+ expect((await masterMarkers(page))[0].time).toBeCloseTo(3, 2);+ await expect(page.getByTestId("source-marker-tick")).toHaveCount(1);++ // Back to the program: only the middle scene (source 2s..4s) shows the flag, 1s into the clip.+ await seek(page, 3);+ await expect(page.getByTestId("clip-marker-flag")).toHaveCount(1);+ const middle = clipsOf(await readState(page), "Main")[1];+ const flag = page.getByTestId("clip-marker-flag");+ const clipBox = await clipLocator(page, middle.id).boundingBox();+ const flagBox = await flag.boundingBox();+ if (clipBox && flagBox) expect(Math.abs(flagBox.x - clipBox.x - 100)).toBeLessThan(8);++ // Markers panel, Clips view.+ await page.getByRole("button", { name: "Markers", exact: true }).click();+ await page.getByTestId("markers-scope-clips").click();+ await expect(page.getByTestId("clip-marker-row")).toHaveCount(1);+ await expect(page.getByTestId("clip-marker-row")).toHaveAttribute("data-scope", "master");+ await expect(page.getByTestId("clip-marker-time")).not.toHaveText("");++ // One undo removes it everywhere.+ await undo(page);+ await expect.poll(async () => (await masterMarkers(page)).length).toBe(0);+ await expect(page.getByTestId("clip-marker-flag")).toHaveCount(0);+});diff --git a/apps/web/e2e/color-wb-eyedropper-lib.ts b/apps/web/e2e/color-wb-eyedropper-lib.tsnew file mode 100644index 00000000..05d4cddb--- /dev/null+++ b/apps/web/e2e/color-wb-eyedropper-lib.ts@@ -0,0 +1,310 @@+import { expect, type Page } from "@playwright/test";+import { clickClip, clipsOf, openEditor, press, readState, seek, settle, snap, undo } from "./helpers";+import { openColorGrading } from "./lumetri-basic-lib";++/** SMPTE bars (4s..6s): the first of seven bars is neutral grey. */+const BARS_TIME = 5;+const GREY_BAR = { x: 0.5 / 7, y: 0.3 };+const PROGRAM = 'canvas[aria-label^="Program frame"]';+const LAYER = "wb-eyedropper-layer";++interface E2EStores {+ project: { getState(): Record<string, any> };+}++async function grade(page: Page, clipId: string): Promise<{ temperature: number; tint: number }> {+ return page.evaluate((id) => {+ const g = (window as unknown as { __openreelE2E: E2EStores }).__openreelE2E.project.getState().getClip(id)?.colorGrading ?? {};+ return { temperature: g.temperature ?? 0, tint: g.tint ?? 0 };+ }, clipId);+}++/** Mean RGB of a small window around a frame fraction of the stored snapshot. */+async function meanAt(page: Page, key: string, fx: number, fy: number): Promise<[number, number, number]> {+ return page.evaluate(+ ([k, x, y]) => {+ const d = (window as unknown as { __snaps: Record<string, Uint8ClampedArray> }).__snaps[k as string];+ const c = document.querySelector('canvas[aria-label^="Program frame"]') as HTMLCanvasElement;+ const cx = Math.floor(c.width * (x as number));+ const cy = Math.floor(c.height * (y as number));+ let r = 0;+ let g = 0;+ let b = 0;+ let n = 0;+ for (let yy = cy - 4; yy <= cy + 4; yy++)+ for (let xx = cx - 4; xx <= cx + 4; xx++) {+ const i = (yy * c.width + xx) * 4;+ r += d[i];+ g += d[i + 1];+ b += d[i + 2];+ n++;+ }+ return [r / n, g / n, b / n] as [number, number, number];+ },+ [key, fx, fy] as const,+ );+}++const spread = (rgb: number[]): number => Math.max(...rgb) - Math.min(...rgb);++export interface WbFlowResult {+ castSpread: number;+ pickedSpread: number;+ picked: { temperature: number; tint: number };+ historyDeltaForPick: number;+ undone: { temperature: number; tint: number };+ escHistoryDelta: number;+ layerGoneAfterEsc: boolean;+ layerGoneAfterPick: boolean;+ readoutSeen: boolean;+}++async function clickGreyBar(page: Page): Promise<void> {+ const box = await page.locator(PROGRAM).boundingBox();+ if (!box) throw new Error("no Program canvas box");+ await page.mouse.click(box.x + box.width * GREY_BAR.x, box.y + box.height * GREY_BAR.y);+}++/**+ * Cast the grey bar with Temperature / Tint, pick it with the eyedropper, check+ * the sliders neutralise it as ONE undo step, and that Esc cancels cleanly.+ */+export async function runWbEyedropperFlow(page: Page): Promise<WbFlowResult> {+ await openEditor(page);+ await seek(page, BARS_TIME);+ const [clip] = clipsOf(await readState(page), "Main");+ await openColorGrading(page, clip.id);++ await page.evaluate(async (id) => {+ await (window as unknown as { __openreelE2E: E2EStores }).__openreelE2E.project+ .getState()+ .updateColorGrading(id, { temperature: 45, tint: 18 });+ }, clip.id);+ await settle(page, 900);+ await snap(page, "cast");+ const castSpread = spread(await meanAt(page, "cast", GREY_BAR.x, GREY_BAR.y));++ // Esc cancels: layer disappears and nothing is written.+ const eyedropper = page.getByRole("button", { name: "White balance eyedropper", exact: true });+ await eyedropper.click();+ await page.getByTestId(LAYER).waitFor();+ const historyBeforeEsc = (await readState(page)).historyLength;+ await page.keyboard.press("Escape");+ await expect(page.getByTestId(LAYER)).toHaveCount(0);+ const escHistoryDelta = (await readState(page)).historyLength - historyBeforeEsc;+ expect(await grade(page, clip.id)).toEqual({ temperature: 45, tint: 18 });++ // Arm again, hover for the live read-out, then click the grey bar.+ await eyedropper.click();+ await page.getByTestId(LAYER).waitFor();+ const box = await page.locator(PROGRAM).boundingBox();+ if (!box) throw new Error("no Program canvas box");+ await page.mouse.move(box.x + box.width * GREY_BAR.x, box.y + box.height * GREY_BAR.y, { steps: 4 });+ const readoutSeen = await page+ .getByTestId("wb-eyedropper-readout")+ .waitFor({ timeout: 4000 })+ .then(() => true)+ .catch(() => false);+ const historyBefore = (await readState(page)).historyLength;+ await clickGreyBar(page);+ await expect(page.getByTestId(LAYER)).toHaveCount(0);+ await settle(page, 1000);+ const historyDeltaForPick = (await readState(page)).historyLength - historyBefore;+ const picked = await grade(page, clip.id);+ await snap(page, "picked");+ const pickedSpread = spread(await meanAt(page, "picked", GREY_BAR.x, GREY_BAR.y));++ await press(page, "Escape");+ await undo(page);+ await settle(page, 700);+ const undone = await grade(page, clip.id);++ return {+ castSpread,+ pickedSpread,+ picked,+ historyDeltaForPick,+ undone,+ escHistoryDelta,+ layerGoneAfterEsc: true,+ layerGoneAfterPick: true,+ readoutSeen,+ };+}++export function expectWbFlow(r: WbFlowResult): void {+ // The cast was visible, the pick removed the slider cast (the grey source needs 0/0) in one undo step.+ expect(r.castSpread).toBeGreaterThan(25);+ expect(Math.abs(r.picked.temperature)).toBeLessThanOrEqual(1);+ expect(Math.abs(r.picked.tint)).toBeLessThanOrEqual(1);+ expect(r.pickedSpread).toBeLessThan(3);+ expect(r.historyDeltaForPick).toBe(1);+ expect(r.escHistoryDelta).toBe(0);+ expect(r.undone).toEqual({ temperature: 45, tint: 18 });+ expect(r.readoutSeen).toBe(true);+}++// ---------------------------------------------------------------------------------------------------------------+// Real footage with a real colour cast and later grade stages (the case the SMPTE grey bar cannot cover).+// ---------------------------------------------------------------------------------------------------------------++interface Patch {+ fx: number;+ fy: number;+ spread: number;+}++/** A flat, near-neutral mid-tone 9x9 patch with a slight tint of its own (the interview's wall), from the stored snapshot. */+async function findNeutralPatch(page: Page, key: string): Promise<Patch> {+ return page.evaluate((k) => {+ const d = (window as unknown as { __snaps: Record<string, Uint8ClampedArray> }).__snaps[k];+ const c = document.querySelector('canvas[aria-label^="Program frame"]') as HTMLCanvasElement;+ let best: Patch | null = null;+ let bestScore = Infinity;+ for (let cy = Math.floor(c.height * 0.12); cy < c.height * 0.88; cy += 6) {+ for (let cx = Math.floor(c.width * 0.08); cx < c.width * 0.92; cx += 6) {+ let r = 0;+ let g = 0;+ let b = 0;+ let lumaSq = 0;+ let luma = 0;+ let n = 0;+ for (let yy = cy - 4; yy <= cy + 4; yy++)+ for (let xx = cx - 4; xx <= cx + 4; xx++) {+ const i = (yy * c.width + xx) * 4;+ r += d[i];+ g += d[i + 1];+ b += d[i + 2];+ const l = 0.2126 * d[i] + 0.7152 * d[i + 1] + 0.0722 * d[i + 2];+ luma += l;+ lumaSq += l * l;+ n++;+ }+ const mean = luma / n;+ const std = Math.sqrt(Math.max(0, lumaSq / n - mean * mean));+ const rgb = [r / n, g / n, b / n];+ const spread = Math.max(...rgb) - Math.min(...rgb);+ // Mid-tones only (no clipped or near-black pixels) and flat enough to sample reliably.+ if (mean < 80 || mean > 190 || std > 5 || spread < 8 || spread > 40) continue;+ // Near-neutral but with a real tint of its own, so the pick has to find nonzero values.+ const score = Math.abs(spread - 16);+ if (score < bestScore) {+ bestScore = score;+ best = { fx: cx / c.width, fy: cy / c.height, spread };+ }+ }+ }+ if (!best) throw new Error("no flat mid-tone patch found in the footage");+ return best;+ }, key);+}++export interface RealFootageResult {+ pipeline: number;+ patchSpreadUngraded: number;+ castSpread: number;+ pickedSpread: number;+ picked: { temperature: number; tint: number };+ historyDelta: number;+ undone: { temperature: number; tint: number };+ inputFrameModeSeen: string | null;+}++/**+ * Real footage with a slider cast PLUS a later grade stage. On a version 2 clip white balance runs first and the+ * contrast stage after it, so the picked patch must come out neutral on the Program monitor only if the pick+ * sampled the white balance stage input, not the displayed (contrast-graded) pixel.+ */+export async function runWbRealFootageFlow(+ page: Page,+ pipelineVersion: 1 | 2,+ openFootage: (page: Page) => Promise<{ id: string }>,+): Promise<RealFootageResult> {+ const clip = await openFootage(page);+ await seek(page, 1);+ await settle(page, 1200);+ await openColorGrading(page, clip.id);+ const setGrade = (patch: Record<string, unknown>) =>+ page.evaluate(+ async ([id, p]) => {+ await (window as unknown as { __openreelE2E: E2EStores }).__openreelE2E.project+ .getState()+ .updateColorGrading(id as string, p as Record<string, unknown>);+ },+ [clip.id, patch] as const,+ );++ await setGrade({ pipelineVersion, temperature: 0, tint: 0, tone: { exposure: 0, contrast: 0, highlights: 0, shadows: 0, whites: 0, blacks: 0 } });+ await settle(page, 900);+ await snap(page, "raw");+ const patch = await findNeutralPatch(page, "raw");++ // A real cast (sliders) and a later stage that would fool a pick of the displayed pixel.+ await setGrade({ temperature: 40, tint: 10, tone: { exposure: 0, contrast: 60, highlights: 0, shadows: 0, whites: 0, blacks: 0 } });+ await settle(page, 1000);+ await snap(page, "cast");+ const castSpread = spread(await meanAt(page, "cast", patch.fx, patch.fy));++ await page.getByRole("button", { name: "White balance eyedropper", exact: true }).click();+ const layer = page.getByTestId(LAYER);+ await layer.waitFor();+ // Armed hint must not squeeze the sample-size control (the 5x5 label was clipped to "5x").+ const sizeGroup = page.getByRole("group", { name: "White balance sample size" });+ for (const label of ["Point", "5×5"]) {+ const clipped = await sizeGroup.getByRole("button", { name: new RegExp(label === "Point" ? "Point" : "5") }).evaluate((el) => el.scrollWidth > el.clientWidth + 0.5);+ expect(clipped, `${label} label is clipped`).toBe(false);+ }+ await expect(sizeGroup).toBeVisible();+ await page.screenshot({ path: "/private/tmp/claude-501/wb-armed.png" });+ const box = await page.locator(PROGRAM).boundingBox();+ if (!box) throw new Error("no Program canvas box");+ const x = box.x + box.width * patch.fx;+ const y = box.y + box.height * patch.fy;+ await page.mouse.move(x, y, { steps: 4 });+ // v2 with later stages renders the stage input once (transient) before the read-out can be exact.+ await expect(layer).toHaveAttribute("data-input-frame", /ready|live/, { timeout: 15_000 });+ await page.mouse.move(x + 1, y + 1, { steps: 2 });+ await page.getByTestId("wb-eyedropper-readout").waitFor({ timeout: 5000 });+ const inputFrameModeSeen = await layer.getAttribute("data-input-frame");++ const historyBefore = (await readState(page)).historyLength;+ await page.mouse.click(x, y);+ await expect(page.getByTestId(LAYER)).toHaveCount(0);+ await settle(page, 1200);+ const historyDelta = (await readState(page)).historyLength - historyBefore;+ const picked = await grade(page, clip.id);+ await snap(page, "picked");+ const pickedSpread = spread(await meanAt(page, "picked", patch.fx, patch.fy));++ // The transient render must never leak: the stored grade is intact and the monitor shows the full grade.+ const stored = await page.evaluate(+ (id) => (window as unknown as { __openreelE2E: E2EStores }).__openreelE2E.project.getState().getClip(id)?.colorGrading?.tone?.contrast,+ clip.id,+ );+ expect(stored).toBe(60);++ await undo(page);+ await settle(page, 800);+ const undone = await grade(page, clip.id);+ return {+ pipeline: pipelineVersion,+ patchSpreadUngraded: patch.spread,+ castSpread,+ pickedSpread,+ picked,+ historyDelta,+ undone,+ inputFrameModeSeen,+ };+}++export function expectRealFootage(r: RealFootageResult): void {+ expect(r.castSpread).toBeGreaterThan(r.patchSpreadUngraded + 20);+ // Nonzero values: the footage's own cast has to be corrected, not just the slider cast removed.+ expect(Math.abs(r.picked.temperature) + Math.abs(r.picked.tint)).toBeGreaterThan(3);+ // Contrast 60 amplifies the 8-bit / 0.1-slider residue; sampling the displayed pixel leaves ~27 here.+ expect(r.pickedSpread).toBeLessThan(Math.min(9, r.patchSpreadUngraded * 0.6));+ expect(r.historyDelta).toBe(1);+ expect(r.undone).toEqual({ temperature: 40, tint: 10 });+ expect(r.inputFrameModeSeen).toBe("ready");+}diff --git a/apps/web/e2e/color-wb-eyedropper.spec.ts b/apps/web/e2e/color-wb-eyedropper.spec.tsnew file mode 100644index 00000000..0a237b38--- /dev/null+++ b/apps/web/e2e/color-wb-eyedropper.spec.ts@@ -0,0 +1,23 @@+import { test } from "@playwright/test";+import { expectRealFootage, expectWbFlow, runWbEyedropperFlow, runWbRealFootageFlow } from "./color-wb-eyedropper-lib";+import { openRealFootage } from "./looks-luts-lib";++// Premiere-style White Balance eyedropper (GPU project; fallback-color-wb-eyedropper.spec.ts runs the same+// flow on the Canvas2D / software path).+test("white balance eyedropper neutralises the sampled grey as one undo step; Esc cancels", async ({ page }) => {+ test.setTimeout(240_000);+ const r = await runWbEyedropperFlow(page);+ console.log(`[wb-eyedropper] ${JSON.stringify(r)}`);+ expectWbFlow(r);+});++// The case the grey bar cannot show: real footage with a real cast and a later stage. Version 2 runs white balance+// first, so the pick has to sample the white balance stage input, not the contrast-graded pixel on screen.+for (const version of [2, 1] as const) {+ test(`white balance eyedropper on real footage neutralises a patch under a cast + contrast (pipeline v${version})`, async ({ page }) => {+ test.setTimeout(300_000);+ const r = await runWbRealFootageFlow(page, version, (p) => openRealFootage(p));+ console.log(`[wb-eyedropper real v${version}] ${JSON.stringify(r)}`);+ expectRealFootage(r);+ });+}diff --git a/apps/web/e2e/diarization.spec.ts b/apps/web/e2e/diarization.spec.tsnew file mode 100644index 00000000..90622db7--- /dev/null+++ b/apps/web/e2e/diarization.spec.ts@@ -0,0 +1,276 @@+import { expect, test, type Page } from "@playwright/test";+import { basename, dirname, join } from "node:path";+import { fileURLToPath } from "node:url";+import { clipsOf, importInput, openEditor, readState, seek, settle, shape, undo, redo } from "./helpers";++/**+ * Speaker diarization, reassign and per-speaker caption looks against the generated three-scenes.mp4 (6 s, picture+ * and a 440 Hz tone). The fixture transcript has word timings; the picture's+ * audio is separated onto Dialogue (linked to the picture). Deleting a sentence+ * in the Transcript panel must ripple-cut that exact range from picture and+ * sound together as ONE undo step, and WebVTT export must be valid.+ */+const TRANSCRIPT = {+ language: "en",+ segments: [+ {+ speaker: "Ann",+ words: [+ { word: "Welcome", start: 0.5, end: 0.9 },+ { word: "to", start: 0.9, end: 1.0 },+ { word: "the", start: 1.0, end: 1.1 },+ { word: "show.", start: 1.1, end: 1.5 },+ ],+ },+ {+ speaker: "Ann",+ words: [+ { word: "Um,", start: 2.0, end: 2.3 },+ { word: "this", start: 2.5, end: 2.8 },+ { word: "is", start: 2.8, end: 3.0 },+ { word: "like", start: 3.0, end: 3.2 },+ { word: "great.", start: 3.2, end: 3.8 },+ ],+ },+ {+ speaker: "Bob",+ words: [+ { word: "Thanks", start: 4.5, end: 5.0 },+ { word: "all.", start: 5.0, end: 5.5 },+ ],+ },+ ],+};++/**+ * fixtures/two-voices.mp4: six passages read alternately by two different synthetic voices (macOS Daniel / Samantha,+ * AAC 32 kbps), 0.5 s apart. Passage times in seconds.+ */+const TWO_VOICES = join(dirname(fileURLToPath(import.meta.url)), "fixtures", "two-voices.mp4");+const PASSAGES: Array<[number, number]> = [+ [0.5, 5.2],+ [5.7, 9.9],+ [10.4, 14.7],+ [15.2, 19.3],+ [19.9, 23.7],+ [24.2, 28.8],+];+const INTERVIEW = {+ language: "en",+ segments: PASSAGES.map(([start, end], i) => ({+ words: [+ { word: `Passage${i + 1}`, start, end: start + 1 },+ { word: "speaks", start: (start + end) / 2 - 0.5, end: (start + end) / 2 + 0.5 },+ { word: "here.", start: end - 1, end },+ ],+ })),+};++async function openTwoVoices(page: Page) {+ await page.addInitScript(() => {+ try {+ localStorage.setItem("openreel-onboarding-complete", "true");+ localStorage.setItem("openreel-mograph-tour-complete", "true");+ } catch {+ /* storage unavailable */+ }+ });+ await page.goto("/");+ await page.getByRole("button", { name: /Horizontal/ }).click();+ await page.locator('canvas[aria-label^="Program frame"]').waitFor({ timeout: 60_000 });+ await importInput(page).setInputFiles(TWO_VOICES);+ await page.getByLabel(`Select media ${basename(TWO_VOICES)}`).waitFor({ timeout: 90_000 });+ await page.getByRole("button", { name: `Media actions for ${basename(TWO_VOICES)}` }).click();+ await page.getByRole("menuitem", { name: "Add to timeline" }).click();+ await page.getByRole("button", { name: "Match Video" }).click({ timeout: 8_000 }).catch(() => undefined);+ await expect.poll(async () => clipsOf(await readState(page), "Main").length, { timeout: 30_000 }).toBe(1);+ await page.getByRole("button", { name: "Text & captions", exact: true }).click();+ await page.getByRole("tab", { name: "Transcript" }).click();+ await page.getByTestId("transcript-panel").waitFor();+ await page.getByTestId("transcript-import-input").setInputFiles({+ name: "interview.json",+ mimeType: "application/json",+ buffer: Buffer.from(JSON.stringify(INTERVIEW)),+ });+ await expect(page.locator("[data-word-index]")).toHaveCount(18);+}++async function openTranscript(page: Page) {+ await page.getByRole("button", { name: "Text & captions", exact: true }).click();+ await page.getByRole("tab", { name: "Transcript" }).click();+ await page.getByTestId("transcript-panel").waitFor();+ await page.getByTestId("transcript-import-input").setInputFiles({+ name: "interview.json",+ mimeType: "application/json",+ buffer: Buffer.from(JSON.stringify(TRANSCRIPT)),+ });+ await expect(page.locator("[data-word-index]")).toHaveCount(11);+}++async function layout(page: Page) {+ await openEditor(page);+ const state = await readState(page);+ const main = clipsOf(state, "Main")[0];+ const sep = await page.evaluate(+ (id) => (window as any).__openreelE2E.project.getState().separateAudio(id),+ main.id,+ );+ expect(sep.success, JSON.stringify(sep)).toBe(true);+ await settle(page, 500);+ const after = await readState(page);+ expect(shape(clipsOf(after, "Main"))).toEqual([[0, 6, 0, 6]]);+ expect(shape(clipsOf(after, "Dialogue"))).toEqual([[0, 6, 0, 6]]);+}++const sub = (page: Page) =>+ page.evaluate(() =>+ (window as any).__openreelE2E.project+ .getState()+ .project.timeline.subtitles.map((s: any) => ({+ id: s.id,+ text: s.text,+ start: s.startTime,+ end: s.endTime,+ speaker: s.speaker,+ })),+ );++const word = (page: Page, text: string) => page.locator("[data-word-index]", { hasText: text }).first();+++test.describe("Speaker diarization", () => {+ test("recolour, reposition and reassign speakers; each is one undo step and styles the captions", async ({ page }) => {+ await layout(page);+ await openTranscript(page);+ const subs = () =>+ page.evaluate(() => {+ const s = (window as any).__openreelE2E.project.getState().project;+ return { cues: s.timeline.subtitles.map((c: any) => ({ speaker: c.speaker, color: c.style?.color, position: c.style?.position })), speakers: s.speakers };+ });+ const history = async () => (await readState(page)).historyLength;+ const base = await history();++ await page.getByRole("button", { name: /^Speakers/ }).click();+ const colour = page.getByLabel("Colour for Bob");+ // React tracks the instance value, so set it through the prototype setter like a real picker does.+ await colour.evaluate((el: HTMLInputElement) => {+ Object.getOwnPropertyDescriptor(HTMLInputElement.prototype, "value")!.set!.call(el, "#ff0000");+ el.dispatchEvent(new Event("input", { bubbles: true }));+ });+ await expect.poll(async () => (await subs()).cues[2].color).toBe("#ff0000");+ await page.getByLabel("Caption position for Bob").selectOption("top");+ await expect.poll(async () => (await subs()).cues[2].position).toBe("top");+ expect((await subs()).cues[0].color).toBe("#4F9DFF");++ // Reassign the last passage to Ann: the cue takes Ann's look.+ await page.getByLabel("Reassign speaker for this passage").last().selectOption("Ann");+ await expect.poll(async () => (await subs()).cues.map((c: any) => c.speaker)).toEqual(["Ann", "Ann", "Ann"]);+ expect(await history()).toBe(base + 3);++ await undo(page);+ await expect.poll(async () => (await subs()).cues[2].speaker).toBe("Bob");+ await undo(page);+ await undo(page);+ await expect.poll(async () => (await subs()).cues[2].color).toBeUndefined();+ await redo(page);+ await expect.poll(async () => (await subs()).cues[2].color).toBe("#ff0000");+ });++ test("Detect speakers (Auto) separates two real voices, and re-detecting keeps renames without stale profiles", async ({ page }) => {+ test.setTimeout(240_000);+ await openTwoVoices(page);+ const project = () =>+ page.evaluate(() => {+ const p = (window as any).__openreelE2E.project.getState().project;+ return {+ cues: p.timeline.subtitles.map((c: any) => ({ speaker: c.speaker, color: c.style?.color, position: c.style?.position, base: c.speakerBase })),+ speakers: (p.speakers ?? []).map((x: any) => ({ name: x.name, color: x.color, position: x.position })),+ };+ });+ const speakers = async () => (await project()).cues.map((c: any) => c.speaker);+ const history = async () => (await readState(page)).historyLength;+ const base = await history();++ // Default Auto detection, no hint about the number of voices.+ await expect(page.getByLabel("Number of speakers")).toHaveValue("auto");+ await page.getByRole("button", { name: "Detect speakers" }).click();+ const alternating = ["Speaker 1", "Speaker 2", "Speaker 1", "Speaker 2", "Speaker 1", "Speaker 2"];+ await expect.poll(speakers, { timeout: 120_000 }).toEqual(alternating);+ expect(await history()).toBe(base + 1);+ const detected = await project();+ expect(detected.speakers.map((s: any) => s.name)).toEqual(["Speaker 1", "Speaker 2"]);+ expect(detected.cues[0].color).toBe(detected.speakers[0].color);+ expect(detected.cues[1].color).toBe(detected.speakers[1].color);++ // The panel states the approximate nature of voice matching.+ await expect(page.getByTestId("speaker-limits-note")).toContainText(/approximate/i);++ // The speaker list stays one compact line and leaves the passages their room.+ const list = page.getByRole("region", { name: "Speakers" });+ expect((await list.boundingBox())!.height).toBeLessThan(40);+ await list.getByRole("button", { name: /^Speakers/ }).click();+ await expect(page.getByLabel("Colour for Speaker 1")).toBeVisible();++ // Rename + reposition one speaker, clear another passage's speaker.+ await page.getByRole("button", { name: "Speaker Speaker 1. Click to rename" }).first().click();+ await page.getByLabel("Rename speaker Speaker 1").fill("Host");+ await page.keyboard.press("Enter");+ await expect.poll(speakers).toEqual(["Host", "Speaker 2", "Host", "Speaker 2", "Host", "Speaker 2"]);+ await page.getByLabel("Caption position for Host").selectOption("top");+ await expect.poll(async () => (await project()).cues[0].position).toBe("top");+ await page.getByLabel("Reassign speaker for this passage").nth(3).selectOption("No speaker");+ await expect.poll(async () => (await project()).cues[3].speaker).toBeUndefined();+ // The speaker's look is taken off the cue again: nothing is left baked on a cue without a speaker.+ const cleared = (await project()).cues[3];+ expect(cleared.color).toBeUndefined();+ expect(cleared.base).toBeUndefined();++ // Detect again: Host stays Host with its look, nothing is orphaned, no duplicate Speaker 1.+ await page.getByRole("button", { name: "Detect speakers" }).click();+ await expect.poll(speakers, { timeout: 120_000 }).toEqual(["Host", "Speaker 2", "Host", "Speaker 2", "Host", "Speaker 2"]);+ const again = await project();+ expect(again.speakers.map((s: any) => s.name)).toEqual(["Host", "Speaker 2"]);+ expect(again.speakers[0]).toMatchObject({ color: detected.speakers[0].color, position: "top" });+ expect(again.cues[3].color).toBe(again.speakers[1].color);+ });+ test("with a hidden translated track present, detection finds the same speakers and the translation follows", async ({ page }) => {+ test.setTimeout(240_000);+ await openTwoVoices(page);+ // Add a hidden Spanish track with the same timings as the English cues.+ await page.evaluate(async () => {+ const e2e = (window as any).__openreelE2E.project.getState();+ const source = e2e.project.timeline.subtitles as any[];+ const translated = source.map((c) => ({+ ...c,+ id: `es-${c.id}`,+ text: `[es] ${c.text}`,+ language: "es",+ captionTrackId: "track-es",+ hidden: true,+ words: [],+ }));+ await e2e.executeAction({+ type: "subtitle/setAll",+ id: crypto.randomUUID(),+ timestamp: Date.now(),+ params: { subtitles: [...source, ...translated] },+ });+ });+ const read = () =>+ page.evaluate(() => {+ const p = (window as any).__openreelE2E.project.getState().project;+ const subs = p.timeline.subtitles as any[];+ const pick = (hidden: boolean) =>+ subs.filter((c) => Boolean(c.hidden) === hidden).sort((a, b) => a.startTime - b.startTime).map((c) => ({ speaker: c.speaker, color: c.style?.color }));+ return { source: pick(false), translated: pick(true), profiles: (p.speakers ?? []).map((x: any) => x.name) };+ });+ await expect.poll(async () => (await read()).translated.length).toBe(6);+ await page.getByRole("button", { name: "Detect speakers" }).click();+ const alternating = ["Speaker 1", "Speaker 2", "Speaker 1", "Speaker 2", "Speaker 1", "Speaker 2"];+ await expect.poll(async () => (await read()).source.map((c: any) => c.speaker), { timeout: 120_000 }).toEqual(alternating);+ const detected = await read();+ // Same count as without translation, and the translated cues carry the same speakers and colours.+ expect(detected.profiles).toEqual(["Speaker 1", "Speaker 2"]);+ expect(detected.translated).toEqual(detected.source);+ });+});diff --git a/apps/web/e2e/effect-previews-lib.ts b/apps/web/e2e/effect-previews-lib.tsindex fbaff114..dcec71db 100644--- a/apps/web/e2e/effect-previews-lib.ts+++ b/apps/web/e2e/effect-previews-lib.ts@@ -1,5 +1,7 @@import { expect, test, type Page } from "@playwright/test";import { existsSync, mkdirSync } from "node:fs";+import { join } from "node:path";+import { tmpdir } from "node:os";import { clickClip, clipsOf, importInput, openEditor, programMean, readState, seek, settle, splitIntoThree, track } from "./helpers";/**@@ -8,7 +10,7 @@ import { clickClip, clipsOf, importInput, openEditor, programMean, readState, se* Shared by the gpu project (effect-previews.spec.ts) and the fallback projects (fallback-effect-previews.spec.ts).*/-const SHOTS = process.env.OPENREEL_PREVIEW_SHOTS ?? "/private/tmp/effect-previews-shots";+const SHOTS = process.env.OPENREEL_PREVIEW_SHOTS ?? join(tmpdir(), "effect-previews-shots");const GRAYSCALE = "Black & white";const SOURCE_CARD = "Stabilize"; // footage with the stabilization crop: still the unaffected colours@@ -387,17 +389,34 @@ export function registerEffectPreviewTests(): void {const labels = ["Black & white", "Glow", "Vignette", "Sharpen", "Film grain", "Chroma key", "Stabilize", "LUT · Warm"];for (const label of labels) await waitForPoster(page, label);const quiet = await readStats(page);+ // How long the pointer actually stays on each card: a nominal 90 ms visit takes several hundred ms (up to seconds)+ // on a slow software-GL runner, and playback legitimately renders more frames the longer the card is hovered.+ // The bound below therefore scales with the measured dwell instead of assuming a fast machine.+ const hoverStarts: number[] = [];for (const label of labels) {+ hoverStarts.push(Date.now());await page.locator(`button[aria-label^="${label}. Drag"]`).first().hover();await page.waitForTimeout(90);}+ hoverStarts.push(Date.now());await page.mouse.move(5, 5);await page.waitForTimeout(500);const swept = await readStats(page);expect(swept.cachedPosters, "hover sweep did not evict any poster").toBeGreaterThanOrEqual(quiet.cachedPosters);expect(swept.cachedBytes).toBeLessThanOrEqual(48 * 1024 * 1024);- // A 90 ms visit renders a handful of frames ahead of playback, not the 24-frame window of every card.- expect(swept.rendersStarted - quiet.rendersStarted, "bounded hover work during a sweep").toBeLessThanOrEqual(labels.length * 10);+ // A visit renders a handful of frames ahead of playback (HOVER_LEAD) plus what playback itself consumes at 12 fps+ // while the pointer is there, and never more than the card's 24-frame window. A regression that decodes the whole+ // window of every card on a brief hover (24 each) still exceeds the budget of a short visit.+ const HOVER_LEAD = 8;+ const PREVIEW_FPS = 12;+ const WINDOW_FRAMES = 24;+ const hoverBudget = hoverStarts.slice(1).reduce((sum, end, i) => {+ const dwellSeconds = (end - hoverStarts[i]) / 1000;+ return sum + Math.min(WINDOW_FRAMES, HOVER_LEAD + Math.ceil(dwellSeconds * PREVIEW_FPS));+ }, 0);+ const hoverRenders = swept.rendersStarted - quiet.rendersStarted;+ console.log(`[hover-sweep ${project}] renders ${hoverRenders}, budget ${hoverBudget}, dwell ms ${hoverStarts.slice(1).map((end, i) => end - hoverStarts[i]).join(",")}`);+ expect(hoverRenders, "bounded hover work during a sweep").toBeLessThanOrEqual(hoverBudget);expect((await readCard(page, "Black & white")).state).toBe("poster");// ── scrubbing with the panel open: preview work is held, long tasks are recorded ───────────────────────diff --git a/apps/web/e2e/encoder-picker.spec.ts b/apps/web/e2e/encoder-picker.spec.tsnew file mode 100644index 00000000..13c3df8f--- /dev/null+++ b/apps/web/e2e/encoder-picker.spec.ts@@ -0,0 +1,59 @@+import { execFileSync } from "node:child_process";+import { expect, test } from "@playwright/test";+import { settle } from "./helpers";+import { ensureLumetriFixtures, openWithClips } from "./lumetri-basic-lib";++// Export dialog > Encoder: Auto / Hardware / Software, enabled only where WebCodecs reports the encoder.+// An unavailable choice is shown disabled with the reason; a Software export is a real H.264 file.++test.beforeAll(() => ensureLumetriFixtures());++test("Encoder picker reflects this browser's WebCodecs support and a Software export is real H.264", async ({ page }, testInfo) => {+ test.setTimeout(300_000);+ await openWithClips(page, ["lumetri-flat.mp4"]);+ const support = await page.evaluate(async () => {+ const probe = async (hardwareAcceleration: "prefer-hardware" | "prefer-software"): Promise<boolean> => {+ try {+ return (await VideoEncoder.isConfigSupported({ codec: "avc1.640028", width: 1920, height: 1080, bitrate: 5_000_000, framerate: 30, hardwareAcceleration })).supported === true;+ } catch {+ return false;+ }+ };+ return typeof VideoEncoder === "undefined" ? { hardware: false, software: false } : { hardware: await probe("prefer-hardware"), software: await probe("prefer-software") };+ });+ console.log(`[encoder] webcodecs support: ${JSON.stringify(support)}`);++ await page.getByRole("button", { name: "Export", exact: true }).first().click();+ await settle(page, 1500);+ await page.getByRole("tab", { name: "Custom Settings" }).click();+ const picker = page.getByTestId("encoder-picker");+ await picker.scrollIntoViewIfNeeded();+ await expect(picker).toBeVisible();+ await expect(page.getByTestId("encoder-auto")).toHaveAttribute("data-selected", "true");+ await expect(page.getByTestId("encoder-hardware")).toHaveAttribute("data-available", String(support.hardware));+ await expect(page.getByTestId("encoder-software")).toHaveAttribute("data-available", String(support.software));+ if (!support.hardware) await expect(page.getByTestId("encoder-hardware")).toContainText(/no hardware encoder/i);+ if (support.hardware) {+ // Changing a setting that re-runs the probe must never change the user's encoder choice.+ await page.getByTestId("encoder-hardware").click();+ await expect(page.getByTestId("encoder-hardware")).toHaveAttribute("data-selected", "true");+ await page.locator("#export-frame-rate").click();+ await page.getByRole("option", { name: /^24/ }).first().click();+ await settle(page, 1500);+ await expect(page.getByTestId("encoder-hardware")).toHaveAttribute("data-selected", "true");+ await expect(page.getByTestId("encoder-auto")).not.toHaveAttribute("data-selected", "true");+ }+ if (!support.software) {+ testInfo.annotations.push({ type: "encoder", description: "no software WebCodecs encoder here: disabled state verified, export not exercised" });+ return;+ }++ await page.getByTestId("encoder-software").click();+ await expect(page.getByTestId("encoder-software")).toHaveAttribute("data-selected", "true");+ const download = page.waitForEvent("download", { timeout: 240_000 });+ await page.getByRole("button", { name: "Export Video" }).last().click();+ const out = testInfo.outputPath("software.mp4");+ await (await download).saveAs(out);+ const codec = execFileSync("ffprobe", ["-v", "error", "-select_streams", "v:0", "-show_entries", "stream=codec_name", "-of", "csv=p=0", out]).toString().trim();+ expect(codec).toBe("h264");+});diff --git a/apps/web/e2e/fallback-burn-in.spec.ts b/apps/web/e2e/fallback-burn-in.spec.tsnew file mode 100644index 00000000..02842cc8--- /dev/null+++ b/apps/web/e2e/fallback-burn-in.spec.ts@@ -0,0 +1,17 @@+import { test } from "@playwright/test";+import { registerBurnInTests } from "./burn-in-lib";++// fallback-nowebgpu and fallback-software projects: the burn-ins must draw the same way through the Canvas2D+// fallback renderer (no WebGPU), in the monitor, in export frames and in an exported file.+test.beforeEach(async ({ page }, testInfo) => {+ if (testInfo.project.name !== "fallback-nowebgpu") return;+ await page.addInitScript(() => {+ try {+ delete (Navigator.prototype as unknown as { gpu?: unknown }).gpu;+ } catch {+ /* non-configurable on this build; requestAdapter() is still null */+ }+ });+});++registerBurnInTests();diff --git a/apps/web/e2e/fallback-color-wb-eyedropper.spec.ts b/apps/web/e2e/fallback-color-wb-eyedropper.spec.tsnew file mode 100644index 00000000..5ba4d2d6--- /dev/null+++ b/apps/web/e2e/fallback-color-wb-eyedropper.spec.ts@@ -0,0 +1,36 @@+import { expect, test } from "@playwright/test";+import { expectRealFootage, expectWbFlow, runWbEyedropperFlow, runWbRealFootageFlow } from "./color-wb-eyedropper-lib";+import { openRealFootage } from "./looks-luts-lib";++// Runs under fallback-nowebgpu and fallback-software (playwright.config.ts): no WebGPU (and, for the second+// project, no GPU), so the Program monitor is the Canvas2D / software frame. Same flow, same result.+test.beforeEach(async ({ page }, testInfo) => {+ if (testInfo.project.name !== "fallback-nowebgpu") return;+ await page.addInitScript(() => {+ try {+ delete (Navigator.prototype as unknown as { gpu?: unknown }).gpu;+ } catch {+ /* non-configurable on this build; requestAdapter() is still null */+ }+ });+});++test("fallback: white balance eyedropper neutralises the sampled grey as one undo step; Esc cancels", async ({ page }, testInfo) => {+ test.setTimeout(420_000);+ await page.goto("/");+ const adapter = await page.evaluate(async () => {+ const gpu = (navigator as unknown as { gpu?: { requestAdapter(): Promise<unknown> } }).gpu;+ return gpu ? await gpu.requestAdapter() : null;+ });+ expect(adapter).toBeNull();+ const r = await runWbEyedropperFlow(page);+ console.log(`[${testInfo.project.name}] wb-eyedropper ${JSON.stringify(r)}`);+ expectWbFlow(r);+});++test("fallback: white balance eyedropper on real footage neutralises a patch under a cast + contrast (pipeline v2)", async ({ page }, testInfo) => {+ test.setTimeout(420_000);+ const r = await runWbRealFootageFlow(page, 2, (p) => openRealFootage(p));+ console.log(`[${testInfo.project.name}] wb-eyedropper real ${JSON.stringify(r)}`);+ expectRealFootage(r);+});diff --git a/apps/web/e2e/fallback-time-effects.spec.ts b/apps/web/e2e/fallback-time-effects.spec.tsnew file mode 100644index 00000000..75301e27--- /dev/null+++ b/apps/web/e2e/fallback-time-effects.spec.ts@@ -0,0 +1,16 @@+import { test } from "@playwright/test";+import { registerTimeEffectTests } from "./time-effects-lib";++// fallback-nowebgpu and fallback-software projects: Echo / Posterize Time through the Canvas2D fallback renderer path.+test.beforeEach(async ({ page }, testInfo) => {+ if (testInfo.project.name !== "fallback-nowebgpu") return;+ await page.addInitScript(() => {+ try {+ delete (Navigator.prototype as unknown as { gpu?: unknown }).gpu;+ } catch {+ /* non-configurable on this build; requestAdapter() is still null */+ }+ });+});++registerTimeEffectTests();diff --git a/apps/web/e2e/fallback-ultra-key.spec.ts b/apps/web/e2e/fallback-ultra-key.spec.tsnew file mode 100644index 00000000..cbb2989e--- /dev/null+++ b/apps/web/e2e/fallback-ultra-key.spec.ts@@ -0,0 +1,17 @@+import { test } from "@playwright/test";+import { registerUltraKeyTests } from "./ultra-key-lib";++// fallback-nowebgpu and fallback-software projects: Ultra Key must key real green-screen footage through+// the Canvas2D fallback renderer path too (same VideoEffectsEngine canvas passes, no WebGPU involved).+test.beforeEach(async ({ page }, testInfo) => {+ if (testInfo.project.name !== "fallback-nowebgpu") return;+ await page.addInitScript(() => {+ try {+ delete (Navigator.prototype as unknown as { gpu?: unknown }).gpu;+ } catch {+ /* non-configurable on this build; requestAdapter() is still null */+ }+ });+});++registerUltraKeyTests();diff --git a/apps/web/e2e/fixtures/real-interview.CREDITS.txt b/apps/web/e2e/fixtures/real-interview.CREDITS.txtindex 3f33402a..cb22abb7 100644--- a/apps/web/e2e/fixtures/real-interview.CREDITS.txt+++ b/apps/web/e2e/fixtures/real-interview.CREDITS.txt@@ -1 +1,3 @@real-interview.mp4: 3 s, 640x360 cut of Pexels "woman talking in front of the camera" https://www.pexels.com/video/woman-talking-in-front-of-the-camera-5940726/ (Pexels license, free to use).++two-voices.mp4: 29 s, 640x360 flat colour with six passages read alternately by two macOS synthetic voices (Daniel, Samantha), AAC 32 kbps. Generated for the speaker diarization e2e; no third-party material.diff --git a/apps/web/e2e/fixtures/two-voices.mp4 b/apps/web/e2e/fixtures/two-voices.mp4new file mode 100644index 00000000..a12b2734Binary files /dev/null and b/apps/web/e2e/fixtures/two-voices.mp4 differdiff --git a/apps/web/e2e/hdr-float.spec.ts b/apps/web/e2e/hdr-float.spec.tsindex 04024518..b4605537 100644--- a/apps/web/e2e/hdr-float.spec.ts+++ b/apps/web/e2e/hdr-float.spec.ts@@ -1,4 +1,5 @@import { expect, test, type Page } from "@playwright/test";+import { SOFTWARE_GPU } from "./env";import { openEditor, seek, settle } from "./helpers";/**@@ -266,8 +267,11 @@ test("playback cost of the float path versus the 8-bit grading pass (1080p)", asif ("skipped" in result) test.skip(true, String(result.skipped));const r = result as Record<string, number>;// Sanity bounds only (the numbers are reported in docs/colour-management.md): the float preview must be able to- // run a 1080p frame well under a second even on a software GL stack.- expect(r.previewMs).toBeLessThan(1000);+ // run a 1080p frame in about a second on hardware GL. A GPU-less runner executes the same shaders on SwiftShader+ // (1000.1 ms measured on a GitHub ubuntu runner, so the old flat 1 s bound was a coin flip there), which gets a 4x+ // budget: still far below the 10+ s a path that fell back to per-pixel work would take.+ const previewBudgetMs = SOFTWARE_GPU ? 4000 : 1000;+ expect(r.previewMs, `float preview frame at 1080p (budget ${previewBudgetMs} ms)`).toBeLessThan(previewBudgetMs);});test("VideoEngine: Rec.709 projects never touch the float path; Rec.2020 / HDR export render SDR footage consistently", async ({ page }, testInfo) => {diff --git a/apps/web/e2e/inspector-previews-lib.ts b/apps/web/e2e/inspector-previews-lib.tsindex 67e3b02c..bcae530a 100644--- a/apps/web/e2e/inspector-previews-lib.ts+++ b/apps/web/e2e/inspector-previews-lib.ts@@ -1,6 +1,7 @@import { expect, test, type Locator, type Page } from "@playwright/test";import { existsSync, mkdirSync } from "node:fs";-import { basename } from "node:path";+import { basename, join } from "node:path";+import { tmpdir } from "node:os";import { clickClip, clipsOf, importInput, openEditor, readState, seek, settle } from "./helpers";/**@@ -9,7 +10,7 @@ import { clickClip, clipsOf, importInput, openEditor, readState, seek, settle }* at rest as a poster and while hovered as a looping animation. Shared by the gpu project and the fallback projects.*/-const SHOTS = process.env.OPENREEL_PREVIEW_SHOTS ?? "/private/tmp/inspector-previews-shots";+const SHOTS = process.env.OPENREEL_PREVIEW_SHOTS ?? join(tmpdir(), "inspector-previews-shots");interface Read {state: string | undefined;diff --git a/apps/web/e2e/keyframe-graph-editor.spec.ts b/apps/web/e2e/keyframe-graph-editor.spec.tsindex e5c678f4..31e1d811 100644--- a/apps/web/e2e/keyframe-graph-editor.spec.ts+++ b/apps/web/e2e/keyframe-graph-editor.spec.ts@@ -141,4 +141,85 @@ test.describe("Premiere-parity: keyframe graph editor", () => {// Source clip is untouched by the paste.expect(await keyframesOf(page, first.id)).toHaveLength(4);});++ test("temporal interpolation: context menu and toolbar apply per-side types to the selection", async ({ page }) => {+ const { first, panel } = await setup(page);+ await panel.getByRole("combobox", { name: "Property" }).click();+ await page.getByRole("option", { name: "opacity" }).click();+ await panel.getByRole("button", { name: /^Keyframe at 0.000s/ }).click();+ await panel.getByRole("button", { name: /^Keyframe at 1.000s/ }).click({ modifiers: ["Shift"] });+ const depth = await historyDepth(page);+ const key = async (id: string) => (await keyframesOf(page, first.id)).find((k) => k.id === id)!;++ // Context menu on a selected keyframe row acts on the whole selection, one undo step.+ await panel.getByRole("button", { name: /^Keyframe at 1.000s/ }).click({ button: "right" });+ await page.getByRole("menuitemcheckbox", { name: "Auto Bezier" }).click();+ await expect.poll(async () => (await key("o1")).interpolationOut).toBe("auto-bezier");+ expect((await key("o2")).interpolationIn).toBe("auto-bezier");+ expect((await key("o1")).easing).toBe("bezier");+ expect(await historyDepth(page)).toBe(depth + 1);+ // The menu marks the current type of the clicked key.+ await panel.getByRole("button", { name: /^Keyframe at 1.000s/ }).click({ button: "right" });+ await expect(page.getByRole("menuitemcheckbox", { name: "Auto Bezier" })).toHaveAttribute("aria-checked", "true");+ await page.keyboard.press("Escape");++ // Out-only Linear leaves the in side's Auto Bezier alone.+ await panel.getByRole("combobox", { name: "Interpolation side" }).click();+ await page.getByRole("option", { name: "Out only" }).click();+ await panel.getByRole("combobox", { name: "Interpolation", exact: true }).click();+ await page.getByRole("option", { name: "Linear" }).click();+ await expect.poll(async () => (await key("o1")).interpolationOut).toBeUndefined();+ expect((await key("o2")).interpolationIn).toBe("auto-bezier");+ expect((await key("o1")).interpolationIn ?? "auto-bezier").toBe("auto-bezier");++ await panel.getByRole("combobox", { name: "Interpolation side" }).click();+ await page.getByRole("option", { name: "Both sides" }).click();+ await panel.getByRole("combobox", { name: "Interpolation", exact: true }).click();+ await page.getByRole("option", { name: "Continuous Bezier" }).click();+ await expect.poll(async () => (await key("o1")).interpolationOut).toBe("continuous-bezier");++ await panel.getByRole("combobox", { name: "Interpolation", exact: true }).click();+ await page.getByRole("option", { name: "Hold" }).click();+ await expect.poll(async () => (await key("o1")).easing).toBe("hold");+ expect((await key("o1")).interpolationOut).toBeUndefined();+ await undo(page);+ expect((await key("o1")).interpolationOut).toBe("continuous-bezier");+ });++ test("dragging a handle on an Auto Bezier key keeps the drag and converts that side to Bezier", async ({ page }) => {+ await page.setViewportSize({ width: 1600, height: 1300 });+ const { first, panel } = await setup(page);+ await panel.getByRole("combobox", { name: "Property" }).click();+ await page.getByRole("option", { name: "opacity" }).click();+ await panel.getByRole("button", { name: /^Keyframe at 0.000s/ }).click();+ await panel.getByRole("button", { name: /^Keyframe at 1.000s/ }).click({ modifiers: ["Shift"] });+ await panel.getByRole("combobox", { name: "Interpolation", exact: true }).click();+ await page.getByRole("option", { name: "Auto Bezier" }).click();+ await panel.getByRole("button", { name: /^Keyframe at 0.000s/ }).click();+ await settle(page, 300);+ const canvas = panel.getByLabel("Keyframe value graph");+ await canvas.scrollIntoViewIfNeeded();+ await settle(page, 300);+ const box = (await canvas.boundingBox())!;+ const pad = 40, plotW = box.width - pad * 2, plotH = box.height - pad * 2;+ const duration = clipsOf(await readState(page), "Main")[0].duration;+ const tx = (t: number) => box.x + pad + (t / Math.max(1, duration)) * plotW;+ const vy = (v: number) => box.y + pad + (1 - (v + 0.1) / 1.2) * plotH;+ const depth = await historyDepth(page);++ // The first key is flat (Auto): its outgoing handle sits at (1/3, 0).+ await page.mouse.move(tx(1 / 3), vy(0));+ await page.mouse.down();+ await page.mouse.move(tx(0.6), vy(0.8), { steps: 8 });+ await page.mouse.up();++ await expect.poll(async () => (await keyframesOf(page, first.id)).find((k) => k.id === "o1")?.bezierHandles?.in.y ?? 0).toBeGreaterThan(0.5);+ const o1 = (await keyframesOf(page, first.id)).find((k) => k.id === "o1")!;+ const o2 = (await keyframesOf(page, first.id)).find((k) => k.id === "o2")!;+ expect(o1.interpolationOut).toBeUndefined();+ expect(o2.interpolationIn).toBe("auto-bezier");+ // The other end of the shared segment keeps its own Auto handle (flat).+ expect(o1.bezierHandles.out.y).toBeCloseTo(1, 6);+ expect(await historyDepth(page)).toBe(depth + 1);+ });});diff --git a/apps/web/e2e/looks-luts-lib.ts b/apps/web/e2e/looks-luts-lib.tsindex 5653b304..397f42cd 100644--- a/apps/web/e2e/looks-luts-lib.ts+++ b/apps/web/e2e/looks-luts-lib.ts@@ -15,7 +15,7 @@ import { clickClip, clipsOf, importInput, openEditor, programMean, readState, se*/const REAL_FOOTAGE = process.env.OPENREEL_LOOKS_FOOTAGE ?? join(dirname(fileURLToPath(import.meta.url)), "fixtures", "real-interview.mp4");-const SHOTS = process.env.OPENREEL_LOOKS_SHOTS ?? "/private/tmp/polish-b/looks-luts";+const SHOTS = process.env.OPENREEL_LOOKS_SHOTS ?? join(tmpdir(), "polish-b", "looks-luts");interface CardRead {state: string | undefined;@@ -91,11 +91,16 @@ const signatureDiff = (a: number[], b: number[]): number => {async function waitForPoster(page: Page, ariaLabel: string, atTime?: number): Promise<CardRead> {const canvas = page.locator(cardSelector(ariaLabel)).first();await canvas.scrollIntoViewIfNeeded();+ // A card under the pointer loops its footage window on hover: a read taken then is some frame of the loop, not the+ // poster at the playhead the monitor shows. A card slides under the pointer whenever the list re-lays out (an+ // imported LUT, a click that leaves the pointer on a card), which is common on a slow runner where playback+ // starts before the read. Park the pointer and only accept a resting poster.+ await page.mouse.move(5, 5);await expect.poll(async () => {const read = await readCard(page, ariaLabel);- if (!["poster", "playing"].includes(read.state ?? "")) return false;+ if (read.state !== "poster") return false;return atTime === undefined || (read.time !== undefined && Math.abs(read.time - atTime) < 0.15);},{ timeout: 45_000, message: `poster for ${ariaLabel}${atTime === undefined ? "" : ` at ${atTime}s`}` },@@ -171,7 +176,7 @@ async function programSignature(page: Page): Promise<number[]> {}/** Opens the editor with real footage (a person, skin tones, shallow depth of field) as the only clip. */-async function openRealFootage(page: Page, file = REAL_FOOTAGE): Promise<{ id: string }> {+export async function openRealFootage(page: Page, file = REAL_FOOTAGE): Promise<{ id: string }> {await page.addInitScript(() => {try {localStorage.setItem("openreel-onboarding-complete", "true");diff --git a/apps/web/e2e/lumetri-basic-lib.ts b/apps/web/e2e/lumetri-basic-lib.tsindex 5414ef3d..0d309243 100644--- a/apps/web/e2e/lumetri-basic-lib.ts+++ b/apps/web/e2e/lumetri-basic-lib.ts@@ -234,6 +234,30 @@ export interface MatchResult {grade: Record<string, any> | undefined;}+/**+ * Opens the Match Color popover, picks the reference clip and presses "Apply match".+ *+ * The popover is portalled and anchored to the "Match Color…" button, which sits below the fold of a long, scrolling+ * Inspector. Anything that re-lays-out the Inspector after the popover opens (late thumbnails and scopes on a slow+ * runner) moves that button, and the popover with it, out of the viewport, where Playwright can neither scroll to it+ * (it is fixed-position) nor click it (a CI run waited out the whole 300 s on exactly this). So keep the anchor in+ * view until the Apply button is inside the viewport, then click with a bounded timeout.+ */+async function clickApplyMatch(page: Page, referenceId: string): Promise<void> {+ const trigger = page.getByRole("button", { name: "Match Color…", exact: true });+ await trigger.click();+ await page.getByRole("combobox", { name: "Reference clip" }).selectOption(referenceId);+ const apply = page.getByRole("button", { name: "Apply match" });+ const inViewport = async (): Promise<boolean> => {+ await trigger.scrollIntoViewIfNeeded().catch(() => undefined);+ const box = await apply.boundingBox();+ const view = page.viewportSize();+ return !!box && !!view && box.y >= 0 && box.y + box.height <= view.height && box.x >= 0 && box.x + box.width <= view.width;+ };+ await expect.poll(inViewport, { message: "the Apply match button is inside the viewport", timeout: 20_000 }).toBe(true);+ await apply.click({ timeout: 30_000 });+}+/** Cool clip A matched to warm clip B through the Match Color popover. */export async function runMatchFlow(page: Page): Promise<MatchResult> {const [a, b] = await openWithClips(page, ["lumetri-cool.mp4", "lumetri-warm.mp4"]);@@ -246,9 +270,7 @@ export async function runMatchFlow(page: Page): Promise<MatchResult> {const bBefore = await mean(3, "match-b-before");await seek(page, 1);await openColorGrading(page, a);- await page.getByRole("button", { name: "Match Color…", exact: true }).click();- await page.getByRole("combobox", { name: "Reference clip" }).selectOption(b);- await page.getByRole("button", { name: "Apply match" }).click();+ await clickApplyMatch(page, b);await expect.poll(async () => (await clipGrade(page, a))?.colorWheels, { timeout: 30_000 }).toBeTruthy();await expect(page.getByText(/^Applied\./)).toBeVisible();await page.keyboard.press("Escape");diff --git a/apps/web/e2e/match-frame.spec.ts b/apps/web/e2e/match-frame.spec.tsnew file mode 100644index 00000000..b2d00351--- /dev/null+++ b/apps/web/e2e/match-frame.spec.ts@@ -0,0 +1,40 @@+import { expect, test } from "@playwright/test";+import { clipsOf, openEditor, readSource, readState, seek, settle } from "./helpers";++async function sourceSeek(page: import("@playwright/test").Page, seconds: number) {+ await page.evaluate((t) => {+ const e = (window as unknown as { __openreelE2E: { source: { getState(): { setPosition(n: number): void; stop(): void } } } }).__openreelE2E;+ e.source.getState().stop();+ e.source.getState().setPosition(t);+ }, seconds);+ await settle(page, 300);+}++test("Reverse Match Frame finds the Source frame in the sequence; history lists the clip", async ({ page }) => {+ await openEditor(page);+ const clip = clipsOf(await readState(page), "Main")[0];+ await seek(page, 0);++ await page.getByLabel("Select media three-scenes.mp4").dblclick();+ await expect(page.getByTestId("source-monitor")).toBeVisible();+ await expect.poll(async () => (await readSource(page)).tab).toBe("source");++ // History dropdown shows the loaded clip.+ await page.getByTestId("source-history").click();+ await expect(page.getByTestId("source-history-item")).toHaveCount(1);+ await expect(page.getByTestId("source-history-item").first()).toContainText("three-scenes.mp4");+ await page.keyboard.press("Escape");++ // Shift+F with the Source monitor focused moves the playhead to the matching frame.+ await page.getByTestId("source-monitor").click({ position: { x: 20, y: 60 } });+ await sourceSeek(page, clip.inPoint + 1.5);+ await page.keyboard.press("Shift+F");+ await expect.poll(async () => (await readState(page)).playhead).toBeCloseTo(clip.start + 1.5, 1);++ // A frame outside the sequence leaves the playhead and warns.+ const before = (await readState(page)).playhead;+ await sourceSeek(page, clip.outPoint + 5);+ await page.getByTestId("reverse-match-frame").click();+ await expect(page.getByText(/not in the sequence/i).first()).toBeVisible();+ expect((await readState(page)).playhead).toBeCloseTo(before, 3);+});diff --git a/apps/web/e2e/media-audio-browsers.spec.ts b/apps/web/e2e/media-audio-browsers.spec.tsindex 192e99da..b76ab8b0 100644--- a/apps/web/e2e/media-audio-browsers.spec.ts+++ b/apps/web/e2e/media-audio-browsers.spec.ts@@ -99,7 +99,7 @@ test("music rows stream in with real progress and distinct waveforms", async ({rows.slice(0, 8).map((row) => [...row.querySelectorAll(".workspace-sound-waveform span")].map((b) => (b as HTMLElement).style.height).join(",")),);expect(new Set(shapes).size).toBe(shapes.length);- await page.screenshot({ path: "/private/tmp/verify-wa/media-audio-fix/music-loaded.png" });+ await page.screenshot({ path: test.info().outputPath("music-loaded.png") });});test("an offline item that still has a thumbnail shows the hatched offline tile", async ({ page }) => {@@ -121,7 +121,7 @@ test("an offline item that still has a thumbnail shows the hatched offline tile"await expect(tile).toBeVisible();await expect(tile).toContainText("Media offline");await expect(tile).toHaveClass(/has-thumbnail/);- await page.screenshot({ path: "/private/tmp/verify-wa/media-audio-fix/offline-with-thumbnail.png" });+ await page.screenshot({ path: test.info().outputPath("offline-with-thumbnail.png") });});test("the media grid keeps most of the panel when an item is offline", async ({ page }) => {@@ -135,5 +135,5 @@ test("the media grid keeps most of the panel when an item is offline", async ({expect(scroll!.height / panel!.height).toBeGreaterThan(0.5);// Header controls are one row: nothing may be truncated.await expect(page.getByTestId("missing-assets-bar")).toContainText("Relink");- await page.screenshot({ path: "/private/tmp/verify-wa/media-audio-fix/media-offline-layout.png" });+ await page.screenshot({ path: test.info().outputPath("media-offline-layout.png") });});diff --git a/apps/web/e2e/motion-track-flow.ts b/apps/web/e2e/motion-track-flow.tsindex f962764b..7c0a6d55 100644--- a/apps/web/e2e/motion-track-flow.ts+++ b/apps/web/e2e/motion-track-flow.ts@@ -1,4 +1,5 @@import { expect, type Page, type TestInfo } from "@playwright/test";+import { SOFTWARE_GPU } from "./env";import { clickClip, clipsOf, readState, redo, seek, settle, undo } from "./helpers";import {FPS, FRAMES, FULL_OCCLUSION, PARTIAL_OCCLUSION, SPRITE, exportedCentroids, generateTrackClip, generateTrackClip1080, openEditorWith, readTrack, targetAt, type TrackData,@@ -393,7 +394,11 @@ export async function run1080pFlow(page: Page, testInfo: TestInfo, label: stringexpect(data.keyframes.length).toBe(FRAMES);expect(err, "1080p path accuracy in source pixels on confident frames").toBeLessThanOrEqual(14);expect(data.lostFrames.length, "only a few frames are flagged").toBeLessThanOrEqual(6);- expect(data.stats!.framesPerSecond, "tracking speed on a 1080p clip").toBeGreaterThan(10);+ // Tracking is CPU work (1080p decode plus the tracker in a worker), so its speed follows the machine: > 10 frames/s on+ // a laptop, 9.7 on a shared 4-vCPU GitHub runner (the GPU-less project). Half the rate there still fails a tracker that+ // lost its worker or fell back to full-frame work, which is what this bound is for.+ const minFps = SOFTWARE_GPU ? 5 : 10;+ expect(data.stats!.framesPerSecond, `tracking speed on a 1080p clip (at least ${minFps} frames/s)`).toBeGreaterThan(minFps);expect(Math.max(...gaps), "the main thread keeps painting while the worker tracks").toBeLessThan(500);}diff --git a/apps/web/e2e/overlays-templates-lib.ts b/apps/web/e2e/overlays-templates-lib.tsindex e0987cc6..aa948e05 100644--- a/apps/web/e2e/overlays-templates-lib.ts+++ b/apps/web/e2e/overlays-templates-lib.ts@@ -5,6 +5,7 @@ import { tmpdir } from "node:os";import { join } from "node:path";import { clickClip, clipsOf, importInput, openEditor, readState, seek, settle, waitForPresentedPlayhead } from "./helpers";import { FIXTURE_PATH } from "./global-setup";+import { SOFTWARE_GPU } from "./env";/*** Graphics > Overlays cards and the template gallery render the real thing on real pixels:@@ -14,7 +15,7 @@ import { FIXTURE_PATH } from "./global-setup";* cards, no empty platform tabs.* Shared by the gpu project (overlays-templates.spec.ts) and the fallback projects (fallback-overlays-templates.spec.ts).*/-const SHOTS = process.env.OPENREEL_OVERLAY_SHOTS ?? "/private/tmp/polish-b/overlays-templates/e2e";+const SHOTS = process.env.OPENREEL_OVERLAY_SHOTS ?? join(tmpdir(), "polish-b", "overlays-templates", "e2e");interface Region {x0: number;@@ -626,7 +627,11 @@ export function registerOverlayTemplateTests(): void {const max = Math.max(0, ...tasks);console.log(`templates long tasks 4K ${JSON.stringify(tasks)} ${JSON.stringify(await page.evaluate(() => (window as any).__loaf))}`);await page.screenshot({ path: `${SHOTS}/${testInfo.project.name}-templates-4k-longtask.png` });- expect(max, `longest Templates-tab task ${max} ms on 4K (all: ${tasks.join(", ")})`).toBeLessThan(50);+ // Hardware: no task over 50 ms. On SwiftShader (no GPU) the card canvases rasterize on the CPU and a single hover+ // frame can spike past 90 ms on a loaded runner (one 98 ms task on CI; steady frames cost ~10 ms), so allow 3x:+ // still far below the multi-hundred-ms stall of decoding or resampling the 4K frame on the main thread.+ const budget = SOFTWARE_GPU ? 150 : 50;+ expect(max, `longest Templates-tab task ${max} ms on 4K (all: ${tasks.join(", ")}), budget ${budget} ms`).toBeLessThan(budget);});const traces: Record<string, { settled: number; count: number; max: number; total: number }> = {};diff --git a/apps/web/e2e/planar-track.spec.ts b/apps/web/e2e/planar-track.spec.tsnew file mode 100644index 00000000..7e16ed6a--- /dev/null+++ b/apps/web/e2e/planar-track.spec.ts@@ -0,0 +1,232 @@+import { execFileSync } from "node:child_process";+import { mkdtempSync } from "node:fs";+import { tmpdir } from "node:os";+import { join } from "node:path";+import { expect, test, type Page } from "@playwright/test";+import { E2E_FFMPEG } from "./env";+import { clickClip, clipsOf, importInput, readState, redo, seek, settle, undo } from "./helpers";+import { openEditorWith, type Hook } from "./motion-track-lib";+import { applyHomography, homographyBetweenQuads, invertHomography, seededRandom, type Quad } from "../../../packages/core/src/video/planar-homography";+import { exportTo } from "./motion-track-flow";++/**+ * Planar (corner-pin) tracking in a real browser. A textured surface is warped through a changing perspective+ * quad over a different textured background (rendered here by an exact homography warp), so the+ * TRUE corners of every frame are known. The tracker is driven through the Inspector, a red full-frame clip+ * above is pinned to the result, the project is exported and the red pixels are compared with the true quad.+ */+const FPS = 30, FRAMES = 45;+const quadAt = (n: number): Array<{ x: number; y: number }> => [+ { x: 150 + 2 * n, y: 70 + 0.6 * n }, { x: 470 + 2.2 * n, y: 90 + 0.2 * n },+ { x: 490 + 1.8 * n, y: 290 - 0.4 * n }, { x: 130 + 2 * n, y: 270 + 0.2 * n },+];+/** Frame n of the surface: a seeded value-noise texture warped onto the quad of frame n over a different background. */+function renderFrames(): Buffer {+ const W = 640, H = 360;+ const noise = (seed: number, cell: number) => {+ const rand = seededRandom(seed), cols = Math.ceil(W / cell) + 2, rows = Math.ceil(H / cell) + 2, grid = new Float32Array(cols * rows);+ for (let i = 0; i < grid.length; i++) grid[i] = rand();+ return (x: number, y: number) => {+ const gx = x / cell, gy = y / cell, x0 = Math.floor(gx), y0 = Math.floor(gy), fx = gx - x0, fy = gy - y0;+ const at = (i: number, j: number) => grid[Math.min(rows - 1, Math.max(0, j)) * cols + Math.min(cols - 1, Math.max(0, i))];+ return (at(x0, y0) * (1 - fx) + at(x0 + 1, y0) * fx) * (1 - fy) + (at(x0, y0 + 1) * (1 - fx) + at(x0 + 1, y0 + 1) * fx) * fy;+ };+ };+ const surface = noise(42, 3), back = noise(7, 5);+ const out = Buffer.alloc(W * H * FRAMES);+ for (let n = 0; n < FRAMES; n++) {+ const q = quadAt(n) as unknown as Quad;+ const h = homographyBetweenQuads([{ x: 0, y: 0 }, { x: W, y: 0 }, { x: W, y: H }, { x: 0, y: H }], q)!;+ const inv = invertHomography(h)!;+ for (let y = 0; y < H; y++) for (let x = 0; x < W; x++) {+ const t = applyHomography(inv, { x: x + 0.5, y: y + 0.5 });+ const on = t.x >= 0 && t.x < W - 1 && t.y >= 0 && t.y < H - 1;+ out[n * W * H + y * W + x] = Math.round(on ? 40 + 190 * surface(t.x, t.y) : 30 + 70 * back(x, y));+ }+ }+ return out;+}++function fixtures(): { surface: string; red: string } {+ const dir = mkdtempSync(join(tmpdir(), "openreel-planar-"));+ const surface = join(dir, "planar.mp4"), red = join(dir, "red.mp4");+ execFileSync(E2E_FFMPEG, ["-y", "-f", "rawvideo", "-pix_fmt", "gray", "-s", "640x360", "-r", "30", "-i", "-", "-c:v", "libx264", "-crf", "12", "-g", "15", "-pix_fmt", "yuv420p", "-frames:v", String(FRAMES), surface], { input: renderFrames(), stdio: ["pipe", "ignore", "ignore"], maxBuffer: 64 * 1024 * 1024 });+ execFileSync(E2E_FFMPEG, ["-y", "-f", "lavfi", "-i", "color=c=red:s=640x360:r=30:d=1.5", "-c:v", "libx264", "-crf", "12", "-pix_fmt", "yuv420p", "-frames:v", String(FRAMES), red], { stdio: "ignore" });+ return { surface, red };+}++/** Fraction of the quad interior that is red, and red pixels outside it as a fraction of the quad area, in one exported frame. */+function redCoverage(file: string, frame: number): { inside: number; outside: number } {+ const w = 640, h = 360, q = quadAt(frame);+ const buf = execFileSync(E2E_FFMPEG, ["-v", "error", "-ss", String((frame + 0.5) / FPS), "-i", file, "-frames:v", "1", "-vf", `scale=${w}:${h}`, "-f", "rawvideo", "-pix_fmt", "rgb24", "-"], { maxBuffer: 64 * 1024 * 1024 });+ const inQuad = (x: number, y: number, margin: number): boolean => {+ let sign = 0;+ for (let i = 0; i < 4; i++) {+ const a = q[i], b = q[(i + 1) % 4];+ const cross = ((b.x - a.x) * (y - a.y) - (b.y - a.y) * (x - a.x)) / Math.hypot(b.x - a.x, b.y - a.y);+ if (Math.abs(cross) < margin) return false;+ const s = Math.sign(cross);+ if (sign === 0) sign = s; else if (s !== sign) return false;+ }+ return true;+ };+ let insideRed = 0, insideTotal = 0, outsideRed = 0;+ for (let y = 0; y < h; y++) for (let x = 0; x < w; x++) {+ const o = (y * w + x) * 3, red = buf[o] > 190 && buf[o + 1] < 90 && buf[o + 2] < 90;+ if (inQuad(x, y, 4)) { insideTotal++; if (red) insideRed++; }+ else if (red && !inQuad(x, y, -4)) outsideRed++;+ }+ return { inside: insideRed / Math.max(1, insideTotal), outside: outsideRed / Math.max(1, insideTotal) };+}++async function setCorners(page: Page, corners: Array<{ x: number; y: number }>): Promise<void> {+ const names = ["Top left", "Top right", "Bottom right", "Bottom left"];+ for (const [i, name] of names.entries()) for (const [axis, value] of [["X", corners[i].x], ["Y", corners[i].y]] as const) {+ const input = page.getByRole("spinbutton", { name: `${name} ${axis}`, exact: true });+ await input.scrollIntoViewIfNeeded();+ await input.fill(String(Math.round(value)));+ await input.press("Enter");+ await input.blur();+ }+}++async function openPlanarSection(page: Page, clipId: string): Promise<void> {+ for (let attempt = 0; attempt < 4; attempt++) {+ await clickClip(page, clipId);+ await settle(page, 500);+ if ((await readState(page)).selected.some((item) => item.id === clipId)) break;+ }+ const marker = page.getByText(/Drag the corners on the Program monitor/);+ if (!(await marker.isVisible().catch(() => false))) {+ const effects = page.getByRole("button", { name: /Expand Effects · \d+ section/ });+ if (await effects.count()) await effects.click();+ const header = page.getByRole("button", { name: /Planar Tracking/ }).first();+ await header.scrollIntoViewIfNeeded({ timeout: 10_000 });+ if (!(await marker.isVisible().catch(() => false))) await header.click();+ }+ await marker.waitFor({ timeout: 10_000 });+}++const analysis = (page: Page, clipId: string) => page.evaluate((id) => {+ const project = (window as unknown as { __openreelE2E: Hook }).__openreelE2E.project.getState().project;+ const clip = project.timeline.tracks.flatMap((t: any) => t.clips).find((c: any) => c.id === id);+ const saved = clip?.metadata?.workspacePlanarTrackAnalysis;+ return saved ? JSON.parse(JSON.stringify(saved.data)) as { keyframes: Array<{ frame: number; corners: number[] }>; confidence: number[]; lostFrames: number[]; manualFrames: number[] } : null;+}, clipId);++const cornerError = (corners: number[], frame: number): number => Math.max(...quadAt(frame).map((p, i) => Math.hypot(p.x - corners[i * 2], p.y - corners[i * 2 + 1])));+const seekFrame = (page: Page, frame: number) => seek(page, (frame + 0.01) / FPS);++test.describe("planar tracking", () => {+ test.setTimeout(600_000);++ test("track a perspective surface, edit a frame, pin a clip, export and undo", async ({ page }, testInfo) => {+ const { surface, red } = fixtures();+ await openEditorWith(page, surface, "planar.mp4");+ const [clip] = clipsOf(await readState(page), "Main");++ // A graphic above the footage, the same length.+ await importInput(page).setInputFiles(red);+ await page.getByLabel("Select media red.mp4").waitFor({ timeout: 30_000 });+ const redClipId = await page.evaluate(async () => {+ const store = (window as unknown as { __openreelE2E: Hook }).__openreelE2E.project.getState();+ const media = store.project.mediaLibrary.items.find((m: any) => m.name === "red.mp4");+ await store.addClipToNewTrack(media.id, 0);+ const added = (window as unknown as { __openreelE2E: Hook }).__openreelE2E.project.getState().project.timeline.tracks.at(-1);+ await store.reorderTrack(added.id, 0);+ return added.clips[0].id as string;+ });+ await settle(page);++ await openPlanarSection(page, clip.id);+ await setCorners(page, quadAt(0));+ await expect(page.getByTestId("planar-track-overlay")).toBeVisible();++ const historyBefore = (await readState(page)).historyLength;+ const began = Date.now();+ await page.getByRole("button", { name: /Start Tracking/ }).last().click();+ await expect(page.getByTestId("planar-track-complete")).toBeVisible({ timeout: 180_000 });+ const trackMs = Date.now() - began;+ expect((await readState(page)).historyLength, "tracking is one undo step").toBe(historyBefore + 1);+ const data = (await analysis(page, clip.id))!;+ expect(data.keyframes.length).toBe(FRAMES);+ const errors = data.keyframes.map((k) => cornerError(k.corners, k.frame));+ const worst = Math.max(...errors), mean = errors.reduce((a, b) => a + b, 0) / errors.length;+ console.log(`[planar-track] ${FRAMES} frames in ${trackMs} ms, corner error max ${worst.toFixed(2)} px mean ${mean.toFixed(2)} px, lost ${data.lostFrames.length}`);+ expect(worst, "tracked corners follow the true surface").toBeLessThanOrEqual(4);+ expect(data.lostFrames).toEqual([]);++ // Undo is exact and redo restores the identical path.+ await undo(page);+ expect(await analysis(page, clip.id)).toBeNull();+ await redo(page);+ expect((await analysis(page, clip.id))!.keyframes).toEqual(data.keyframes);++ // Hand-edit the corners of one frame: a manual, full-confidence sample.+ await seekFrame(page, 20);+ await settle(page, 500);+ await setCorners(page, quadAt(20).map((p) => ({ x: p.x + 3, y: p.y - 2 })));+ await page.getByRole("button", { name: "Set corners at this frame" }).click();+ await expect.poll(async () => (await analysis(page, clip.id))?.manualFrames, { timeout: 10_000 }).toEqual([20]);+ const edited = (await analysis(page, clip.id))!;+ expect(edited.keyframes.find((k) => k.frame === 20)!.corners[0]).toBeCloseTo(quadAt(20)[0].x + 3, 0);+ await undo(page);+ expect((await analysis(page, clip.id))!.manualFrames).toEqual([]);+ await seekFrame(page, 0);++ // Pin the red graphic: a Corner Pin effect keyframed to the surface, one undo step.+ const historyPin = (await readState(page)).historyLength;+ const target = page.getByRole("combobox", { name: "Corner pin target" });+ await target.scrollIntoViewIfNeeded();+ await target.click();+ await page.getByRole("option", { name: /red\.mp4/ }).first().click();+ await page.getByRole("button", { name: "Pin Clip to Surface" }).click();+ await expect(page.getByRole("button", { name: "Update Pin" })).toBeVisible({ timeout: 15_000 });+ expect((await readState(page)).historyLength, "pin is one undo step").toBe(historyPin + 1);+ const pinned = await page.evaluate((id) => {+ const project = (window as unknown as { __openreelE2E: Hook }).__openreelE2E.project.getState().project;+ const c = project.timeline.tracks.flatMap((t: any) => t.clips).find((x: any) => x.id === id);+ return { effects: c.effects.map((e: any) => e.type), keys: c.keyframes.filter((k: any) => k.property.startsWith("fx:")).length };+ }, redClipId);+ expect(pinned.effects).toContain("corner-pin");+ expect(pinned.keys).toBeGreaterThanOrEqual(8);++ // Export and compare the red pixels with the true quad.+ const file = testInfo.outputPath("planar-pinned.mp4");+ await exportTo(page, file);+ const lines: string[] = [];+ for (const frame of [2, 12, 22, 32, 42]) {+ const { inside, outside } = redCoverage(file, frame);+ lines.push(`${frame}: in ${(inside * 100).toFixed(1)}% out ${(outside * 100).toFixed(1)}%`);+ expect(inside, `red covers the true surface in exported frame ${frame}`).toBeGreaterThanOrEqual(0.93);+ expect(outside, `no red outside the true surface in exported frame ${frame}`).toBeLessThanOrEqual(0.04);+ }+ console.log(`[planar-track] export red coverage ${lines.join(" | ")}`);++ // Remove the pin: the effect this feature added goes away with its keyframes.+ await page.getByRole("button", { name: "Remove Pin" }).click();+ await expect(page.getByRole("button", { name: "Pin Clip to Surface" })).toBeVisible({ timeout: 15_000 });+ const gone = await page.evaluate((id) => {+ const project = (window as unknown as { __openreelE2E: Hook }).__openreelE2E.project.getState().project;+ const c = project.timeline.tracks.flatMap((t: any) => t.clips).find((x: any) => x.id === id);+ return { effects: c.effects.length, keys: c.keyframes.length };+ }, redClipId);+ expect(gone).toEqual({ effects: 0, keys: 0 });+ });++ test("cancel stops tracking and saves nothing", async ({ page }) => {+ const { surface } = fixtures();+ await openEditorWith(page, surface, "planar.mp4");+ const [clip] = clipsOf(await readState(page), "Main");+ await openPlanarSection(page, clip.id);+ await setCorners(page, quadAt(0));+ const historyBefore = (await readState(page)).historyLength;+ await page.getByRole("button", { name: /Start Tracking/ }).last().click();+ await page.getByRole("button", { name: "Cancel Planar Tracking" }).click();+ await expect(page.getByTestId("planar-track-progress")).toBeHidden({ timeout: 15_000 });+ await settle(page, 800);+ expect(await analysis(page, clip.id)).toBeNull();+ expect((await readState(page)).historyLength).toBe(historyBefore);+ await expect(page.getByRole("button", { name: /Start Tracking/ }).last()).toBeEnabled();+ });+});diff --git a/apps/web/e2e/replace-fit.spec.ts b/apps/web/e2e/replace-fit.spec.tsnew file mode 100644index 00000000..bc7c02d4--- /dev/null+++ b/apps/web/e2e/replace-fit.spec.ts@@ -0,0 +1,148 @@+import { expect, test, type Page } from "@playwright/test";+import {+ clickClip,+ clipsOf,+ openEditor,+ readSource,+ readState,+ seek,+ settle,+ shape,+ splitIntoThree,+ undo,+ redo,+} from "./helpers";++const MEDIA = "Select media three-scenes.mp4";++type E2E = { __openreelE2E: Record<string, { getState(): any }> };++async function openSource(page: Page) {+ await page.getByLabel(MEDIA).dblclick();+ await expect(page.getByTestId("source-monitor")).toBeVisible();+ await expect.poll(async () => (await readSource(page)).tab).toBe("source");+ await settle(page, 500);+}++async function sourceSeek(page: Page, seconds: number) {+ await page.evaluate((t) => {+ const s = (window as unknown as E2E).__openreelE2E.source.getState();+ s.stop();+ s.setPosition(t);+ }, seconds);+ await settle(page, 300);+}++async function markSource(page: Page, inAt: number, outAt: number) {+ await page.evaluate(+ ([a, b]) => {+ const s = (window as unknown as E2E).__openreelE2E.source.getState();+ s.setMark(s.mediaId, "in", a);+ s.setMark(s.mediaId, "out", b);+ },+ [inAt, outAt],+ );+ await settle(page, 200);+}++async function setSequenceRange(page: Page, start: number, end: number) {+ await page.evaluate(+ ([a, b]) => (window as unknown as E2E).__openreelE2E.timeline.getState().setLoopRange(a, b),+ [start, end],+ );+ await settle(page, 200);+}++async function targetTrack(page: Page, name: string) {+ await page.getByRole("button", { name: `Target ${name}`, exact: true }).click();+ await expect(page.getByRole("button", { name: `Untarget ${name}`, exact: true })).toHaveAttribute("aria-pressed", "true");+}++test.describe("Replace edit and Fit to Fill", () => {+ test("Fit to Fill retimes the source range to the timeline range in one undoable step", async ({ page }) => {+ await openEditor(page);+ await openSource(page);+ await markSource(page, 1, 5);+ await targetTrack(page, "B-roll");++ // Without timeline In/Out the command is unavailable and says why.+ await expect(page.getByTestId("fit-to-fill")).toBeDisabled();+ await setSequenceRange(page, 1, 3);+ await expect(page.getByTestId("fit-to-fill")).toBeEnabled();+ const before = await readState(page);++ await page.getByTestId("fit-to-fill").click();+ await settle(page, 500);+ const after = await readState(page);+ // 4s of source into 2s of timeline: twice as fast.+ expect(shape(clipsOf(after, "B-roll"))).toEqual([[1, 2, 1, 5]]);+ expect(clipsOf(after, "B-roll")[0].speed).toBe(2);+ expect(shape(clipsOf(after, "Main"))).toEqual(shape(clipsOf(before, "Main")));+ expect(after.historyLength).toBe(before.historyLength + 1);++ await undo(page);+ const undone = await readState(page);+ expect(clipsOf(undone, "B-roll")).toHaveLength(0);+ expect(undone.historyLength).toBe(before.historyLength);+ await redo(page);+ expect(clipsOf(await readState(page), "B-roll")[0].speed).toBe(2);+ });++ test("Alt+Shift+F fits to fill from the keyboard", async ({ page }) => {+ await openEditor(page);+ await openSource(page);+ await markSource(page, 0, 1);+ await targetTrack(page, "B-roll");+ await setSequenceRange(page, 2, 4);+ await page.getByTestId("source-monitor").click({ position: { x: 20, y: 60 } });+ await page.keyboard.press("Alt+Shift+F");+ await settle(page, 500);+ const clips = clipsOf(await readState(page), "B-roll");+ expect(shape(clips)).toEqual([[2, 2, 0, 1]]);+ expect(clips[0].speed).toBeCloseTo(0.5, 5);+ });++ test("Replace swaps the selected clip's footage, keeps its place and length, aligns playheads; one undo", async ({ page }) => {+ await openEditor(page);+ await splitIntoThree(page);+ const before = await readState(page);+ const middle = clipsOf(before, "Main")[1];+ expect(shape([middle])).toEqual([[2, 2, 2, 4]]);++ await openSource(page);+ await clickClip(page, middle.id);+ // Timeline playhead 0.5s into the clip; the Source frame at 1.5s sits there.+ await seek(page, 2.5);+ await sourceSeek(page, 1.5);+ await page.getByTestId("replace-edit").click();+ await settle(page, 500);++ const after = await readState(page);+ const clips = clipsOf(after, "Main");+ expect(clips.map((c) => c.id)).toEqual(clipsOf(before, "Main").map((c) => c.id));+ expect(shape(clips)).toEqual([[0, 2, 0, 2], [2, 2, 1, 3], [4, 2, 4, 6]]);+ expect(after.historyLength).toBe(before.historyLength + 1);++ await undo(page);+ expect(shape(clipsOf(await readState(page), "Main"))).toEqual(shape(clipsOf(before, "Main")));+ await redo(page);+ expect(shape(clipsOf(await readState(page), "Main"))[1]).toEqual([2, 2, 1, 3]);+ });++ test("Replace refuses a source that is too short and leaves the timeline alone", async ({ page }) => {+ await openEditor(page);+ await splitIntoThree(page);+ const middle = clipsOf(await readState(page), "Main")[1];+ await openSource(page);+ await clickClip(page, middle.id);+ await seek(page, 2);+ await sourceSeek(page, 5.5);+ const before = await readState(page);+ await page.getByTestId("replace-edit").click();+ await settle(page, 400);+ const after = await readState(page);+ expect(shape(clipsOf(after, "Main"))).toEqual(shape(clipsOf(before, "Main")));+ expect(after.historyLength).toBe(before.historyLength);+ await expect(page.getByText(/from that point/)).toBeVisible();+ });+});diff --git a/apps/web/e2e/ripple-speed.spec.ts b/apps/web/e2e/ripple-speed.spec.tsnew file mode 100644index 00000000..f67b592c--- /dev/null+++ b/apps/web/e2e/ripple-speed.spec.ts@@ -0,0 +1,144 @@+import { expect, test, type Page } from "@playwright/test";+import {+ boxOf,+ clickClip,+ clipsOf,+ drag,+ openEditor,+ press,+ readState,+ redo,+ setZoom,+ splitIntoThree,+ undo,+ type ClipState,+} from "./helpers";++const PPS = 100;++/** Separate the audio of every Main clip onto Dialogue (linked to its picture). */+async function separateAll(page: Page): Promise<void> {+ for (const clip of clipsOf(await readState(page), "Main")) {+ const result = await page.evaluate(+ (id) => (window as unknown as { __openreelE2E: { project: { getState(): { separateAudio(id: string): Promise<{ success: boolean }> } } } })+ .__openreelE2E.project.getState().separateAudio(id),+ clip.id,+ );+ expect(result.success, JSON.stringify(result)).toBe(true);+ }+ await page.waitForTimeout(500);+}++async function threeClips(page: Page): Promise<ClipState[]> {+ await openEditor(page);+ await splitIntoThree(page);+ await setZoom(page, PPS);+ return clipsOf(await readState(page), "Main");+}++/** Click a clip, then Shift-click another so both are selected. */+async function selectTwo(page: Page, a: string, b: string) {+ await clickClip(page, a);+ const box = await boxOf(page, b);+ await page.keyboard.down("Shift");+ await page.mouse.click(box.left + 20, box.centerY);+ await page.keyboard.up("Shift");+ await page.waitForTimeout(250);+}++test.describe("Premiere-parity: multi-clip speed with ripple", () => {+ test("Speed/Duration dialog speeds up two clips, ripples the rest, one undo step", async ({ page }) => {+ const [a, b, c] = await threeClips(page);+ await selectTwo(page, a.id, b.id);+ const before = await readState(page);+ await press(page, "Meta+Alt+r");+ const dialog = page.getByRole("dialog", { name: /speed \/ duration/i });+ await expect(dialog).toBeVisible();+ await dialog.getByLabel("Speed percent").fill("200");+ await dialog.getByRole("button", { name: "OK" }).click();+ await page.waitForTimeout(600);++ const after = await readState(page);+ const [x, y, z] = clipsOf(after, "Main");+ expect(after.historyLength - before.historyLength, "one history entry").toBe(1);+ expect(x.speed).toBeCloseTo(2, 2);+ expect(y.speed).toBeCloseTo(2, 2);+ expect(x.duration).toBeCloseTo(a.duration / 2, 2);+ expect(y.start).toBeCloseTo(x.start + x.duration, 2);+ expect(z.start).toBeCloseTo(y.start + y.duration, 2);+ expect(z.duration).toBeCloseTo(c.duration, 3);+ expect(z.speed).toBeCloseTo(1, 3);++ await undo(page);+ const undone = clipsOf(await readState(page), "Main");+ expect(undone.map((k) => [k.start, k.duration])).toEqual([a, b, c].map((k) => [k.start, k.duration]));+ await redo(page);+ expect(clipsOf(await readState(page), "Main")[2].start).toBeCloseTo(z.start, 3);+ });++ test("Rate Stretch on a multi-selection scales every selected clip and ripples", async ({ page }) => {+ const [a, b, c] = await threeClips(page);+ await selectTwo(page, a.id, b.id);+ await press(page, "Shift+R");+ const start = await readState(page);+ const box = await boxOf(page, b.id);+ await drag(page, { x: box.right - 3, y: box.centerY }, -1 * PPS);+ const after = await readState(page);+ const [x, y, z] = clipsOf(after, "Main");+ expect(after.historyLength - start.historyLength).toBe(1);+ // b went 2s -> 1s, so both selected clips run at 2x.+ expect(y.duration).toBeCloseTo(b.duration / 2, 1);+ expect(x.duration).toBeCloseTo(a.duration / 2, 1);+ expect(x.speed).toBeCloseTo(2, 1);+ expect(y.speed).toBeCloseTo(2, 1);+ expect(z.start).toBeCloseTo(y.start + y.duration, 2);+ expect(z.duration).toBeCloseTo(c.duration, 3);+ });++ test("linked audio is retimed with its picture, with Linked Selection on or off, and the rest ripples", async ({ page }) => {+ const [a, b, c] = await threeClips(page);+ await separateAll(page);+ for (const linkedSelection of [true, false]) {+ await page.evaluate(+ (value) => (window as unknown as { __openreelE2E: { workspace: { setState(s: object): void } } }).__openreelE2E.workspace.setState({ linkedSelection: value }),+ linkedSelection,+ );+ await selectTwo(page, a.id, b.id);+ const before = await readState(page);+ await press(page, "Meta+Alt+r");+ const dialog = page.getByRole("dialog", { name: /speed \/ duration/i });+ await expect(dialog).toBeVisible();+ await dialog.getByLabel("Speed percent").fill("200");+ await dialog.getByRole("button", { name: "OK" }).click();+ await page.waitForTimeout(600);+ const after = await readState(page);+ expect(after.historyLength - before.historyLength, "one history entry").toBe(1);+ const dialogue = clipsOf(after, "Dialogue");+ const main = clipsOf(after, "Main");+ expect(dialogue.length).toBe(3);+ for (let i = 0; i < 3; i++) {+ expect(dialogue[i].start, `audio ${i} start (linked=${linkedSelection})`).toBeCloseTo(main[i].start, 2);+ expect(dialogue[i].duration, `audio ${i} duration`).toBeCloseTo(main[i].duration, 2);+ }+ expect(dialogue[0].speed).toBeCloseTo(2, 2);+ expect(main[2].duration).toBeCloseTo(c.duration, 3);+ await undo(page);+ const undone = await readState(page);+ expect(clipsOf(undone, "Dialogue").map((k) => k.duration)).toEqual(clipsOf(before, "Dialogue").map((k) => k.duration));+ }+ });++ test("Alt-dragging the Rate Stretch edge stretches the selection without rippling", async ({ page }) => {+ const [a, b, c] = await threeClips(page);+ await selectTwo(page, a.id, b.id);+ await press(page, "Shift+R");+ const box = await boxOf(page, b.id);+ await page.keyboard.down("Alt");+ await drag(page, { x: box.right - 3, y: box.centerY }, -1 * PPS);+ await page.keyboard.up("Alt");+ const [x, y, z] = clipsOf(await readState(page), "Main");+ expect(y.duration).toBeCloseTo(b.duration / 2, 1);+ expect(x.duration).toBeCloseTo(a.duration / 2, 1);+ expect(z.start, "trailing clip stays put").toBeCloseTo(c.start, 3);+ });+});diff --git a/apps/web/e2e/shard-weights.json b/apps/web/e2e/shard-weights.jsonindex 0d56ff36..9a63a4e0 100644--- a/apps/web/e2e/shard-weights.json+++ b/apps/web/e2e/shard-weights.json@@ -174,5 +174,12 @@"gpu|w7-composition.spec.ts secondary + new effect + pen mask render identically before and after nesting, and undo restores them": 58,"gpu|w8-composition.spec.ts a DeHum in a bus rack cleans that bus's stem only, and editing the rack invalidates the cached mixdown": 28,"gpu|w8-composition.spec.ts an Essential Graphics template and burned-in captions are in the same export, and each can be removed alone": 56,- "gpu|w8-composition.spec.ts multicam angles decode the proxy while proxies are on and the original when off; export reads full resolution": 34+ "gpu|w8-composition.spec.ts multicam angles decode the proxy while proxies are on and the original when off; export reads full resolution": 34,+ "gpu|color-wb-eyedropper.spec.ts white balance eyedropper neutralises the sampled grey as one undo step; Esc cancels": 14,+ "gpu|color-wb-eyedropper.spec.ts white balance eyedropper on real footage neutralises a patch under a cast + contrast (pipeline v1)": 12,+ "gpu|color-wb-eyedropper.spec.ts white balance eyedropper on real footage neutralises a patch under a cast + contrast (pipeline v2)": 11,+ "fallback-nowebgpu|fallback-color-wb-eyedropper.spec.ts fallback: white balance eyedropper neutralises the sampled grey as one undo step; Esc cancels": 16,+ "fallback-nowebgpu|fallback-color-wb-eyedropper.spec.ts fallback: white balance eyedropper on real footage neutralises a patch under a cast + contrast (pipeline v2)": 13,+ "fallback-software|fallback-color-wb-eyedropper.spec.ts fallback: white balance eyedropper neutralises the sampled grey as one undo step; Esc cancels": 26,+ "fallback-software|fallback-color-wb-eyedropper.spec.ts fallback: white balance eyedropper on real footage neutralises a patch under a cast + contrast (pipeline v2)": 15}diff --git a/apps/web/e2e/smart-render.spec.ts b/apps/web/e2e/smart-render.spec.tsindex e4d89aae..e83f01bf 100644--- a/apps/web/e2e/smart-render.spec.ts+++ b/apps/web/e2e/smart-render.spec.ts@@ -498,10 +498,16 @@ test("smart render copies a source whose start_time is nonzero and off the frameexpect(vsFull.length).toBe(nSmart);const worst = Math.min(...vsFull);const shifted = psnrSeries(smartFile, fullFile, aligned, "setpts=(N+1)/(30*TB)");- const shiftedMean = shifted.filter(Number.isFinite).reduce((x, y) => x + y, 0) / shifted.filter(Number.isFinite).length;- console.log(`[smart-render-offset] PSNR vs full re-encode: worst frame ${worst.toFixed(1)} dB (frame ${vsFull.indexOf(worst)}); same pairing shifted by one frame: mean ${shiftedMean.toFixed(1)} dB`);+ const meanOf = (series: number[]) => series.filter(Number.isFinite).reduce((x, y) => x + y, 0) / series.filter(Number.isFinite).length;+ const shiftedMean = meanOf(shifted);+ const alignedMean = meanOf(vsFull);+ console.log(`[smart-render-offset] PSNR vs full re-encode: worst frame ${worst.toFixed(1)} dB (frame ${vsFull.indexOf(worst)}), aligned mean ${alignedMean.toFixed(1)} dB; same pairing shifted by one frame: mean ${shiftedMean.toFixed(1)} dB`);expect(worst).toBeGreaterThan(30);- expect(shiftedMean).toBeLessThan(25); // the check can see a one-frame slip+ // The check can see a one-frame slip. An absolute ceiling is encoder dependent (the full re-encode goes through the+ // platform's H.264 encoder, which differs between a hardware Mac and a software CI runner: the shifted mean was 24.0 dB+ // on one and 25.4 dB on the other), so the shifted pairing must sit well below the aligned pairing measured in the same run.+ expect(shiftedMean).toBeLessThan(alignedMean - 12);+ expect(shiftedMean).toBeLessThan(30);// Copied frames are the source's own bytes, on the output frame that shows that source frame (output i = source i - LEAD).const vsSource = psnrSeries(smartFile, startFile, `trim=start_frame=${LEAD},setpts=N/(30*TB)`, aligned);diff --git a/apps/web/e2e/split-edits.spec.ts b/apps/web/e2e/split-edits.spec.tsindex 461ebd0c..e6102e42 100644--- a/apps/web/e2e/split-edits.spec.ts+++ b/apps/web/e2e/split-edits.spec.ts@@ -17,6 +17,7 @@ import {type ClipState,type EditorState,} from "./helpers";+import { SOFTWARE_GPU } from "./env";const PPS = 100; // 12 frames = 0.4s = exactly 40pxconst TWELVE = 12 * FRAME;@@ -44,12 +45,25 @@ const snapshot = (p: Pair) =>async function linkedPairs(page: Page): Promise<Pair> {await openEditor(page);const clip = videoOf(await readState(page))[0];- await page.evaluate(- (id) =>- (window as unknown as { __openreelE2E: { project: { getState(): { separateAudio(id: string): Promise<unknown> } } } })- .__openreelE2E.project.getState().separateAudio(id),- clip.id,- );+ // Separating audio runs ffmpeg.wasm, whose core is fetched from a CDN. On a slow or flaky network that fetch can+ // fail (CI saw a truncated wasm body: "FFmpeg load error", separateAudio resolved {success:false}). The result used+ // to be ignored, so the test just waited out 30 s for audio that was never coming. Retry until the call succeeds+ // (each attempt re-loads ffmpeg from scratch) and report the last failure if it never does.+ let last: unknown;+ await expect+ .poll(+ async () => {+ last = await page.evaluate(+ (id) =>+ (window as unknown as { __openreelE2E: { project: { getState(): { separateAudio(id: string): Promise<{ success: boolean }> } } } })+ .__openreelE2E.project.getState().separateAudio(id).catch((e: unknown) => ({ success: false, error: String(e) })),+ clip.id,+ );+ return (last as { success: boolean }).success || (await pair(page)).a.length === 1;+ },+ { timeout: SOFTWARE_GPU ? 120_000 : 60_000, intervals: [0, 2_000, 5_000], message: () => `separateAudio never succeeded: ${JSON.stringify(last)}` },+ )+ .toBe(true);await expect.poll(async () => (await pair(page)).a.length, { timeout: 30_000 }).toBe(1);await splitIntoThree(page);await expect.poll(async () => (await pair(page)).a.length, { timeout: 10_000 }).toBe(3);diff --git a/apps/web/e2e/surround-51.spec.ts b/apps/web/e2e/surround-51.spec.tsindex 97895549..71c9c21e 100644--- a/apps/web/e2e/surround-51.spec.ts+++ b/apps/web/e2e/surround-51.spec.ts@@ -305,12 +305,36 @@ async function exportCurrent(page: Page, testInfo: { outputPath(name: string): sawait page.locator("#export-format").click();await page.getByRole("option", { name: container, exact: true }).click();const download = page.waitForEvent("download", { timeout: 360_000 });+ // An export that fails shows a dismissable error banner and never downloads: surface that at once instead of waiting+ // out the download timeout (a CI run burned 6 minutes on exactly this).+ const banner = page.getByRole("button", { name: "Dismiss export error" });+ const failed = banner.waitFor({ timeout: 360_000 }).then(async () => {+ throw new Error(`${container} export failed: ${(await banner.getAttribute("title").catch(() => null)) ?? "(no message)"}`);+ });+ failed.catch(() => undefined);+ download.catch(() => undefined);await page.getByRole("button", { name: "Export Video" }).last().click();const out = testInfo.outputPath(name);- await (await download).saveAs(out);+ await (await Promise.race([download, failed])).saveAs(out);return out;}+/** Whether this browser can encode six-channel AAC (WebCodecs AudioEncoder): Chrome on Linux ships no AAC encoder. */+async function canEncodeSurroundAac(page: Page): Promise<boolean> {+ return page.evaluate(async (sampleRate) => {+ if (typeof AudioEncoder === "undefined") return false;+ for (const bitrate of [384_000, 192_000, 128_000]) {+ try {+ const support = await AudioEncoder.isConfigSupported({ codec: "mp4a.40.2", sampleRate, numberOfChannels: 6, bitrate });+ if (support.supported) return true;+ } catch {+ /* try the next bitrate */+ }+ }+ return false;+ }, SR);+}+test("exporting a 5.1 sequence writes six AAC channels in MP4 and MOV: ffprobe layout 5.1 and per-channel energy", async ({ page }, testInfo) => {testInfo.setTimeout(600_000);await openEditor(page);@@ -361,6 +385,12 @@ test("exporting a 5.1 sequence writes six AAC channels in MP4 and MOV: ffprobe l});};+ // The exports below are real AAC encodes through the browser's WebCodecs encoder. Chrome on Linux (the GPU-less CI+ // runner) has none, and the export then correctly refuses ("No supported audio encoder"), so there is nothing to+ // inspect there. The six-channel order logic is covered by aac-surround-order.test.ts; this half runs wherever the+ // browser can encode AAC (macOS, Windows).+ test.skip(!(await canEncodeSurroundAac(page)), "this browser has no six-channel AAC encoder (WebCodecs AudioEncoder, mp4a.40.2); Chrome on Linux CI cannot encode AAC");+const mp4 = await exportCurrent(page, testInfo, "surround.mp4", "MP4");check(mp4, "MP4");diff --git a/apps/web/e2e/time-effects-lib.ts b/apps/web/e2e/time-effects-lib.tsnew file mode 100644index 00000000..af2a33a5--- /dev/null+++ b/apps/web/e2e/time-effects-lib.ts@@ -0,0 +1,367 @@+import { execFileSync } from "node:child_process";+import { tmpdir } from "node:os";+import { join } from "node:path";+import { expect, test, type Page } from "@playwright/test";+import { clickClip, clipsOf, diffSnaps, openEditor, openHookPage, readState, seek, settle, snapStable } from "./helpers";++/**+ * Echo and Posterize Time (Premiere "Time" effects), in a real browser:+ * - the Effects panel lists both under the Time filter and previews them on real footage;+ * - Posterize Time holds the program frame: the monitor shows exactly the frame the unprocessed clip shows at the+ * start of the held interval;+ * - Echo through the real VideoEngine equals the reference composite of the plain frames at t - k * echoTime for+ * all six operators, in preview mode and in export mode, whatever order the frames are rendered in;+ * - the Canvas2D echo compositor matches the pure per-pixel definition.+ * Shared by the gpu project (time-effects.spec.ts) and the fallback projects (fallback-time-effects.spec.ts).+ */++interface Hook {+ project: { getState(): { project: any } };+ video: { getVideoEngine(): { exportMode: boolean; renderFrame(project: unknown, t: number, w: number, h: number): Promise<{ image: ImageBitmap }> } };+ effectPreviews: () => { render(def: unknown, index: number, priority: string): Promise<ImageBitmap | null> } | null;+ core: { temporalEffects: any; echoCompositor: any };+}++const cardCanvas = (label: string) => `button[aria-label^="${label}. Drag"] canvas`;++async function waitForPoster(page: Page, label: string): Promise<void> {+ await page.locator(cardCanvas(label)).first().scrollIntoViewIfNeeded();+ await expect+ .poll(() => page.locator(cardCanvas(label)).first().getAttribute("data-preview-state"), { timeout: 40_000, message: `poster for ${label}` })+ .toBe("poster");+}++export function registerTimeEffectTests(): void {+ test("the echo compositor draws the six operators exactly like the per-pixel definition", async ({ page }) => {+ test.setTimeout(120_000);+ await openHookPage(page);+ const result = await page.evaluate(async () => {+ const h = (window as unknown as { __openreelE2E: Hook }).__openreelE2E;+ const { temporalEffects: te, echoCompositor: ec } = h.core;+ const W = 48;+ const H = 32;+ // Frames with full-range, spatially varying colour and (optionally) partly translucent content.+ const frame = (seed: number, alphaAt: (x: number, y: number) => number) => {+ const canvas = new OffscreenCanvas(W, H);+ const g = canvas.getContext("2d", { willReadFrequently: true })!;+ const img = g.createImageData(W, H);+ for (let y = 0; y < H; y++)+ for (let x = 0; x < W; x++) {+ const i = (y * W + x) * 4;+ img.data[i] = (x * 5 + seed * 70) % 256;+ img.data[i + 1] = (y * 8 + seed * 40) % 256;+ img.data[i + 2] = ((x + y) * 3 + seed * 110) % 256;+ img.data[i + 3] = alphaAt(x, y);+ }+ g.putImageData(img, 0, 0);+ return { canvas, pixels: img.data };+ };+ const bases = {+ opaque: frame(0, () => 255),+ translucent: frame(0, (x) => (x < 12 ? 0 : x < 24 ? 128 : 255)),+ };+ const echoFrames = [frame(1, () => 255), frame(2, (_x, y) => (y < 10 ? 160 : 255))];+ const compositor = new ec.EchoCompositor();+ const out: Array<{ operator: string; frame: string; maxDiff: number; changed: boolean }> = [];+ for (const operator of te.ECHO_OPERATORS as string[]) {+ for (const [name, source] of Object.entries(bases)) {+ const echo = { operator, startIntensity: 0.8 };+ const ordered = te.echoCompositeOrder(+ [+ { k: 1, weight: 0.5 },+ { k: 2, weight: 0.25 },+ ],+ operator,+ ) as Array<{ k: number; weight: number }>;+ const bitmap = await createImageBitmap(source.canvas);+ const drawn = compositor.draw(+ bitmap,+ ordered.map((s) => ({ image: echoFrames[s.k - 1].canvas, weight: s.weight })),+ echo,+ ) as OffscreenCanvas;+ const got = drawn.getContext("2d", { willReadFrequently: true })!.getImageData(0, 0, W, H).data;+ const expected = te.compositeEchoReference(+ source.pixels,+ ordered.map((s) => ({ data: echoFrames[s.k - 1].pixels, weight: s.weight })),+ echo,+ ) as Uint8ClampedArray;+ let maxDiff = 0;+ let changed = false;+ for (let i = 0; i < expected.length; i += 4) {+ // Where the result is transparent its colour is undefined: weigh colour error by alpha.+ const weight = Math.max(got[i + 3], expected[i + 3]) / 255;+ maxDiff = Math.max(maxDiff, Math.abs(got[i + 3] - expected[i + 3]));+ for (let c = 0; c < 3; c++) maxDiff = Math.max(maxDiff, Math.abs(got[i + c] - expected[i + c]) * weight);+ if (expected[i] !== source.pixels[i] || expected[i + 1] !== source.pixels[i + 1]) changed = true;+ }+ out.push({ operator, frame: name, maxDiff, changed });+ }+ }+ return out;+ });+ for (const r of result) {+ console.log(`[time-effects] ${r.operator}/${r.frame}: max diff ${r.maxDiff}`);+ expect(r.maxDiff, `${r.operator} on ${r.frame} frame vs reference`).toBeLessThanOrEqual(3);+ }+ // the references are not trivially the identity+ expect(result.filter((r) => r.frame === "opaque" && r.operator !== "composite-back").every((r) => r.changed)).toBe(true);+ });++ test("Posterize Time holds the frame the unprocessed clip shows at the start of the held interval", async ({ page }) => {+ test.setTimeout(240_000);+ await openEditor(page);+ const [clip] = clipsOf(await readState(page), "Main");+ await clickClip(page, clip.id);++ // Plain frames of the moving testsrc2 scene (0-2 s) before the effect exists.+ const plain: Record<string, number> = { 0: 0, 1: 1 };+ for (const t of Object.values(plain)) {+ await seek(page, t);+ await snapStable(page, `plain-${t}`);+ }+ expect((await diffSnaps(page, "plain-0", "plain-1")).changed, "the footage moves between 0 s and 1 s").toBeGreaterThan(2000);++ // Add it from the Effects panel Time filter like a user does.+ await page.getByRole("button", { name: "Effects", exact: true }).first().click();+ await settle(page, 500);+ await page.getByRole("group", { name: "Effect categories" }).getByRole("button", { name: "Time", exact: true }).click();+ await expect(page.locator('button[aria-label^="Echo. Drag"]')).toBeVisible();+ const card = page.locator('button[aria-label^="Posterize Time. Drag"]');+ await expect(card).toBeVisible();+ await card.dblclick();+ await expect.poll(async () => clipsOf(await readState(page), "Main")[0].effects, { timeout: 15_000 }).toBe(1);+ const params = await page.evaluate(() => {+ const h = (window as unknown as { __openreelE2E: Hook }).__openreelE2E;+ return h.project.getState().project.timeline.tracks.flatMap((t: any) => t.clips).flatMap((c: any) => c.effects);+ });+ expect(params).toEqual([expect.objectContaining({ type: "posterize-time", enabled: true, params: { frameRate: 1 } })]);++ // 1 fps: 0.2 s and 0.9 s are both the frame at 0 s; 1.2 s is the frame at 1 s.+ const shown = async (t: number, key: string) => {+ await seek(page, t);+ await snapStable(page, key);+ };+ await shown(0.2, "held-0.2");+ await shown(0.9, "held-0.9");+ await shown(1.2, "held-1.2");+ for (const [a, b] of [["held-0.2", "held-0.9"], ["held-0.2", "plain-0"], ["held-0.2", "plain-1"], ["held-1.2", "plain-1"], ["held-1.2", "plain-0"]])+ console.log(`[time-effects] ${a} vs ${b}: ${(await diffSnaps(page, a, b)).changed} px`);+ const tolerance = 150; // pixels of 230400 (colour pipeline rounding of an identical source frame)+ expect((await diffSnaps(page, "held-0.2", "plain-0")).changed, "0.2 s shows the 0 s frame").toBeLessThanOrEqual(tolerance);+ expect((await diffSnaps(page, "held-0.9", "plain-0")).changed, "0.9 s shows the 0 s frame").toBeLessThanOrEqual(tolerance);+ expect((await diffSnaps(page, "held-1.2", "plain-1")).changed, "1.2 s shows the 1 s frame").toBeLessThanOrEqual(tolerance);+ expect((await diffSnaps(page, "held-0.9", "held-1.2")).changed, "the held frame changes at the next boundary").toBeGreaterThan(2000);+ });++ test("Echo applied from the Effects panel shows in the program monitor exactly as the engine renders it", async ({ page }) => {+ test.setTimeout(240_000);+ await openEditor(page);+ const [clip] = clipsOf(await readState(page), "Main");+ await clickClip(page, clip.id);+ await seek(page, 1);+ await snapStable(page, "plain");+ await page.getByRole("button", { name: "Effects", exact: true }).first().click();+ await settle(page, 500);+ await page.getByRole("group", { name: "Effect categories" }).getByRole("button", { name: "Time", exact: true }).click();+ await page.locator('button[aria-label^="Echo. Drag"]').dblclick();+ await expect.poll(async () => clipsOf(await readState(page), "Main")[0].effects, { timeout: 15_000 }).toBe(1);+ const stored = await page.evaluate(() => {+ const h = (window as unknown as { __openreelE2E: Hook }).__openreelE2E;+ return h.project.getState().project.timeline.tracks.flatMap((t: any) => t.clips).flatMap((c: any) => c.effects);+ });+ expect(stored).toEqual([+ expect.objectContaining({ type: "echo", enabled: true, params: { echoTime: 0.033, echoes: 2, startIntensity: 1, decay: 0.5, operator: "add" } }),+ ]);+ await seek(page, 1);+ await snapStable(page, "echo");+ expect((await diffSnaps(page, "plain", "echo")).changed, "the monitor shows the echo").toBeGreaterThan(2000);++ // The monitor frame is the engine frame: compare pixel by pixel.+ const maxDiff = await page.evaluate(async () => {+ const h = (window as unknown as { __openreelE2E: Hook }).__openreelE2E;+ const canvas = document.querySelector('canvas[aria-label^="Program frame"]') as HTMLCanvasElement;+ const frame = await h.video.getVideoEngine().renderFrame(h.project.getState().project, 1, canvas.width, canvas.height);+ const read = (source: CanvasImageSource) => {+ const c = new OffscreenCanvas(canvas.width, canvas.height);+ const g = c.getContext("2d", { willReadFrequently: true })!;+ g.drawImage(source, 0, 0, canvas.width, canvas.height);+ return g.getImageData(0, 0, c.width, c.height).data;+ };+ const a = read(canvas);+ const b = read(frame.image);+ let worst = 0;+ for (let i = 0; i < a.length; i += 4) for (let c = 0; c < 3; c++) worst = Math.max(worst, Math.abs(a[i + c] - b[i + c]));+ return worst;+ });+ console.log(`[time-effects] monitor vs engine frame: max channel diff ${maxDiff}`);+ expect(maxDiff).toBeLessThanOrEqual(3);+ });++ test("an exported file holds the posterized frames", async ({ page }) => {+ test.setTimeout(600_000);+ await openEditor(page);+ const [clip] = clipsOf(await readState(page), "Main");+ await clickClip(page, clip.id);+ await page.getByRole("button", { name: "Effects", exact: true }).first().click();+ await settle(page, 500);+ await page.getByRole("group", { name: "Effect categories" }).getByRole("button", { name: "Time", exact: true }).click();+ await page.locator('button[aria-label^="Posterize Time. Drag"]').dblclick();+ await expect.poll(async () => clipsOf(await readState(page), "Main")[0].effects, { timeout: 15_000 }).toBe(1);+ await seek(page, 0);+ await page.getByRole("button", { name: "Export", exact: true }).first().click();+ await settle(page, 1500);+ const download = page.waitForEvent("download", { timeout: 540_000 });+ await page.getByRole("button", { name: "Export Video" }).last().click();+ const out = join(tmpdir(), `openreel-posterize-time-${Date.now()}.mp4`);+ await (await download).saveAs(out);++ const W = 160;+ const H = 90;+ const frameAt = (t: number): Buffer =>+ execFileSync("ffmpeg", ["-v", "error", "-ss", String(t), "-i", out, "-frames:v", "1", "-vf", `scale=${W}:${H}`, "-f", "rawvideo", "-pix_fmt", "rgb24", "-"], {+ maxBuffer: 64 * 1024 * 1024,+ });+ const meanDiff = (a: Buffer, b: Buffer): number => {+ let total = 0;+ for (let i = 0; i < a.length; i++) total += Math.abs(a[i] - b[i]);+ return total / a.length;+ };+ // 1 fps: 0.1 s, 0.5 s and 0.9 s are the frame at 0 s; 1.1 s and 1.6 s are the frame at 1 s.+ const f01 = frameAt(0.1);+ const f05 = frameAt(0.5);+ const f09 = frameAt(0.9);+ const f11 = frameAt(1.1);+ const f16 = frameAt(1.6);+ console.log(`[time-effects] export held diffs: ${[meanDiff(f01, f05), meanDiff(f05, f09), meanDiff(f11, f16)].map((v) => v.toFixed(2))}, across ${meanDiff(f09, f11).toFixed(2)}`);+ for (const held of [meanDiff(f01, f05), meanDiff(f05, f09), meanDiff(f11, f16)]) expect(held, "frames inside a posterized frame are the same picture").toBeLessThan(1.5);+ expect(meanDiff(f09, f11), "the picture changes at the next posterized frame").toBeGreaterThan(6);+ });++ test("Echo and Posterize Time cards preview real footage frames", async ({ page }) => {+ test.setTimeout(240_000);+ await openEditor(page);+ const [clip] = clipsOf(await readState(page), "Main");+ await clickClip(page, clip.id);+ await seek(page, 0.5);+ await page.getByRole("button", { name: "Effects", exact: true }).first().click();+ await settle(page, 600);+ await page.getByRole("group", { name: "Effect categories" }).getByRole("button", { name: "Time", exact: true }).click();+ await waitForPoster(page, "Echo");+ await waitForPoster(page, "Posterize Time");+ for (const label of ["Echo", "Posterize Time"]) {+ expect(await page.locator(cardCanvas(label)).first().getAttribute("data-preview-source"), `${label} card shows decoded footage`).toBe("footage");+ }+ await expect(page.locator('button[aria-label^="Posterize Time. Drag"]')).toContainText("Hover to play");+ await expect(page.locator('button[aria-label^="Echo. Drag"]')).not.toContainText("Hover to play");++ // The frames the engine renders for the cards, compared pixel by pixel.+ const read = await page.evaluate(async () => {+ const h = (window as unknown as { __openreelE2E: Hook }).__openreelE2E;+ const engine = h.effectPreviews();+ if (!engine) throw new Error("no preview engine");+ const grab = async (def: unknown, index: number) => {+ const bmp = await engine.render(def, index, "hover");+ if (!bmp) throw new Error("no bitmap");+ const c = new OffscreenCanvas(bmp.width, bmp.height);+ const g = c.getContext("2d", { willReadFrequently: true })!;+ g.drawImage(bmp, 0, 0);+ return Array.from(g.getImageData(0, 0, c.width, c.height).data.filter((_, i) => i % 4 !== 3));+ };+ const frames: Record<string, number[]> = {};+ for (let i = 0; i < 7; i++) frames[`held${i}`] = await grab({ id: "e2e-posterize-time", type: "posterize-time" }, i);+ frames.plain9 = await grab({ id: "e2e-neutral-echo", type: "echo", params: { echoes: 0 } }, 9);+ frames.echo9 = await grab({ id: "e2e-echo", type: "echo" }, 9);+ frames.echo0 = await grab({ id: "e2e-echo", type: "echo" }, 0);+ frames.plain0 = await grab({ id: "e2e-neutral-echo", type: "echo", params: { echoes: 0 } }, 0);+ const diff = (a: number[], b: number[]) => a.reduce((n, v, i) => n + (v !== b[i] ? 1 : 0), 0) / a.length;+ return {+ heldPairs: [diff(frames.held0, frames.held1), diff(frames.held1, frames.held2), diff(frames.held2, frames.held3), diff(frames.held3, frames.held4), diff(frames.held5, frames.held6)],+ echoVsPlain: diff(frames.echo9, frames.plain9),+ firstFrameEcho: diff(frames.echo0, frames.plain0),+ };+ });+ // 3 window frames per held frame: 0-2 identical, 3-5 identical, 6 new.+ expect(read.heldPairs[0]).toBe(0);+ expect(read.heldPairs[1]).toBe(0);+ expect(read.heldPairs[2], "held frame changes after three window frames").toBeGreaterThan(0.01);+ expect(read.heldPairs[3]).toBe(0);+ expect(read.heldPairs[4], "second held frame ends at window frame 6").toBeGreaterThan(0.01);+ expect(read.echoVsPlain, "Echo trails earlier window frames behind the current one").toBeGreaterThan(0.05);+ expect(read.firstFrameEcho, "nothing is behind the first frame of the window").toBe(0);+ });++ test("Echo through the VideoEngine equals the reference composite of t - k * echoTime for every operator, in preview and export", async ({ page }) => {+ test.setTimeout(300_000);+ await openEditor(page);+ const result = await page.evaluate(async () => {+ const h = (window as unknown as { __openreelE2E: Hook }).__openreelE2E;+ const te = h.core.temporalEffects;+ const engine = h.video.getVideoEngine();+ const project = h.project.getState().project;+ const W = 640;+ const H = 360;+ const withEffects = (effects: unknown[]) => ({+ ...project,+ timeline: {+ ...project.timeline,+ tracks: project.timeline.tracks.map((track: any) => ({+ ...track,+ clips: track.clips.map((clip: any) => ({ ...clip, effects, keyframes: [] })),+ })),+ },+ });+ const pixels = async (p: unknown, t: number): Promise<Uint8ClampedArray> => {+ const frame = await engine.renderFrame(p, t, W, H);+ const c = new OffscreenCanvas(frame.image.width, frame.image.height);+ const g = c.getContext("2d", { willReadFrequently: true })!;+ g.drawImage(frame.image, 0, 0);+ return g.getImageData(0, 0, c.width, c.height).data;+ };+ const plainProject = withEffects([]);+ const plain = async (t: number) => pixels(plainProject, t);+ const out: Array<Record<string, unknown>> = [];+ for (const operator of te.ECHO_OPERATORS as string[]) {+ const params = { echoTime: 0.1, echoes: 2, startIntensity: 0.8, decay: 0.5, operator };+ const echoProject = withEffects([{ id: "e2e-echo", type: "echo", enabled: true, params }]);+ const t = 1.2;+ const echo = te.resolveEcho(params);+ const plan = te.planEcho(t, 2, echo) as Array<{ k: number; localTime: number; weight: number }>;+ const expected = te.compositeEchoReference(+ await plain(t),+ await Promise.all(plan.map(async (s) => ({ data: await plain(s.localTime), weight: s.weight }))),+ echo,+ ) as Uint8ClampedArray;+ const runs: Uint8ClampedArray[] = [];+ for (const exportMode of [false, true]) {+ engine.exportMode = exportMode;+ // other positions first: the result must not depend on what was rendered before+ await pixels(echoProject, 0.4);+ await pixels(echoProject, 1.9);+ runs.push(await pixels(echoProject, t));+ }+ engine.exportMode = false;+ let maxDiff = 0;+ let previewVsExport = 0;+ let differsFromPlain = 0;+ const base = await plain(t);+ for (let i = 0; i < expected.length; i += 4) {+ for (let c = 0; c < 3; c++) {+ maxDiff = Math.max(maxDiff, Math.abs(runs[0][i + c] - expected[i + c]));+ previewVsExport = Math.max(previewVsExport, Math.abs(runs[0][i + c] - runs[1][i + c]));+ }+ if (Math.abs(runs[0][i] - base[i]) > 6 || Math.abs(runs[0][i + 1] - base[i + 1]) > 6) differsFromPlain++;+ }+ out.push({ operator, planned: plan.map((s) => s.localTime), maxDiff, previewVsExport, differsFromPlain: differsFromPlain / (expected.length / 4) });+ }+ return out;+ });+ for (const r of result as Array<{ operator: string; planned: number[]; maxDiff: number; previewVsExport: number; differsFromPlain: number }>) {+ console.log(`[time-effects] engine echo ${r.operator}: reference diff ${r.maxDiff}, preview vs export ${r.previewVsExport}, changed ${(r.differsFromPlain * 100).toFixed(1)}%`);+ expect(r.planned.map((v) => Number(v.toFixed(3)))).toEqual(r.operator === "composite-front" ? [1, 1.1] : [1.1, 1]);+ expect(r.maxDiff, `${r.operator} engine frame vs reference composite`).toBeLessThanOrEqual(4);+ expect(r.previewVsExport, `${r.operator} preview == export`).toBe(0);+ // Composite in Back of an opaque frame is invisible by definition; every other operator changes the picture+ if (r.operator !== "composite-back") expect(r.differsFromPlain, `${r.operator} changes the picture`).toBeGreaterThan(0.01);+ }+ });+}diff --git a/apps/web/e2e/time-effects.spec.ts b/apps/web/e2e/time-effects.spec.tsnew file mode 100644index 00000000..1331b34e--- /dev/null+++ b/apps/web/e2e/time-effects.spec.ts@@ -0,0 +1,5 @@+import { registerTimeEffectTests } from "./time-effects-lib";++// Runs under the gpu project. The fallback-nowebgpu / fallback-software projects run the same flows from+// fallback-time-effects.spec.ts (they only match fallback-*.spec.ts).+registerTimeEffectTests();diff --git a/apps/web/e2e/ultra-key-lib.ts b/apps/web/e2e/ultra-key-lib.tsnew file mode 100644index 00000000..11bc9cc6--- /dev/null+++ b/apps/web/e2e/ultra-key-lib.ts@@ -0,0 +1,375 @@+import { expect, test, type Page } from "@playwright/test";+import { execFileSync } from "node:child_process";+import { existsSync, mkdirSync } from "node:fs";+import { join } from "node:path";+import { FIXTURE_DIR } from "./global-setup";+import { clickClip, importInput, openEditor, readState, seek, settle, snap } from "./helpers";++/**+ * Ultra Key on real footage: a green-screen clip generated with ffmpeg (a lit, noisy green screen with a skin-toned subject),+ * keyed through the real inspector: effect applied from the Effects panel, key colour picked with the Program monitor+ * eyedropper, output views, keyframes, and the GLSL shader checked against the CPU reference (the Canvas2D fallback / export path).+ * Shared by the gpu project (ultra-key.spec.ts) and the fallback projects (fallback-ultra-key.spec.ts).+ */++export const GREEN_SCREEN_PATH = join(FIXTURE_DIR, "green-screen-v1.mp4");+/** Frame fractions: bare screen and the middle of the subject. */+const SCREEN = { x: 0.1, y: 0.5 };+const SUBJECT = { x: 0.5, y: 0.5 };++export function ensureGreenScreenFixture(): void {+ mkdirSync(FIXTURE_DIR, { recursive: true });+ if (existsSync(GREEN_SCREEN_PATH)) return;+ execFileSync(+ "ffmpeg",+ [+ "-y",+ "-f", "lavfi",+ "-i", "color=c=0x14b44c:s=640x360:r=30:d=3,vignette=angle=PI/5,noise=alls=7:allf=t,drawbox=x=220:y=60:w=200:h=260:color=0xd9a07a:t=fill,drawbox=x=250:y=90:w=60:h=40:color=0x2a3f8f:t=fill,format=yuv420p",+ "-c:v", "libx264", "-g", "15", "-pix_fmt", "yuv420p",+ "-x264-params", "colorprim=bt709:transfer=bt709:colormatrix=bt709:range=tv",+ "-movflags", "+write_colr",+ GREEN_SCREEN_PATH,+ ],+ { stdio: "ignore" },+ );+}++interface E2EStores {+ project: { getState(): Record<string, any> };+}++const PROGRAM = 'canvas[aria-label^="Program frame"]';++async function pixel(page: Page, key: string, at: { x: number; y: number }): Promise<[number, number, number]> {+ return page.evaluate(+ ([k, fx, fy]) => {+ const d = (window as unknown as { __snaps: Record<string, Uint8ClampedArray> }).__snaps[k as string];+ const c = document.querySelector('canvas[aria-label^="Program frame"]') as HTMLCanvasElement;+ const x = Math.floor((fx as number) * c.width);+ const y = Math.floor((fy as number) * c.height);+ const i = (y * c.width + x) * 4;+ return [d[i], d[i + 1], d[i + 2]] as [number, number, number];+ },+ [key, at.x, at.y] as const,+ );+}++/** Re-captures the Program frame until `ok` holds for the pixel (the picker refresh and the effect update land async under load). */+async function snapUntil(+ page: Page,+ key: string,+ at: { x: number; y: number },+ ok: (px: [number, number, number]) => boolean,+): Promise<void> {+ await expect+ .poll(+ async () => {+ await snap(page, key);+ return ok(await pixel(page, key, at));+ },+ { timeout: 25_000, intervals: [300, 500, 1000] },+ )+ .toBe(true);+}++async function ultraKeyEffects(page: Page): Promise<Array<{ id: string; params: Record<string, any> }>> {+ return page.evaluate(() => {+ const project = (window as unknown as { __openreelE2E: E2EStores }).__openreelE2E.project.getState().project;+ const out: Array<{ id: string; params: Record<string, any> }> = [];+ for (const track of project.timeline.tracks)+ for (const clip of track.clips)+ for (const effect of clip.effects ?? []) if (effect.type === "ultra-key") out.push({ id: effect.id, params: { ...effect.params } });+ return out;+ });+}++async function importGreenClip(page: Page): Promise<string> {+ const allClips = async () => (await readState(page)).tracks.flatMap((t) => t.clips);+ const known = new Set((await allClips()).map((c) => c.id));+ await importInput(page).setInputFiles(GREEN_SCREEN_PATH);+ await page.getByLabel("Select media green-screen-v1.mp4").waitFor({ timeout: 90_000 });+ await page.getByRole("button", { name: "Media actions for green-screen-v1.mp4" }).click();+ await page.getByRole("menuitem", { name: "Add to timeline" }).click();+ await expect.poll(async () => (await allClips()).length, { timeout: 30_000 }).toBe(known.size + 1);+ const green = (await allClips()).find((c) => !known.has(c.id));+ if (!green) throw new Error("the green screen clip was not added");+ await seek(page, green.start + 0.5);+ await clickClip(page, green.id);+ return green.id;+}++export function registerUltraKeyTests(): void {+ test.beforeAll(() => ensureGreenScreenFixture());++ test("Ultra Key: apply from the Effects panel, eyedropper the screen, key it on the Program monitor, output views, keyframes", async ({ page }) => {+ test.setTimeout(420_000);+ await openEditor(page);+ const clipId = await importGreenClip(page);+ await settle(page, 900);+ await snap(page, "source");+ const screenBefore = await pixel(page, "source", SCREEN);+ const subjectBefore = await pixel(page, "source", SUBJECT);+ console.log(`[ultra-key] source screen=${screenBefore} subject=${subjectBefore}`);+ expect(screenBefore[1], "the clip is a green screen").toBeGreaterThan(screenBefore[0] + 40);+ expect(subjectBefore[0], "the subject is skin toned").toBeGreaterThan(subjectBefore[1]);++ // Apply from the Keying chip of the Effects panel (double-click a card applies it to the selected clip).+ await page.getByRole("button", { name: "Effects", exact: true }).first().click();+ await settle(page, 500);+ await page.getByRole("button", { name: "Keying", exact: true }).first().click();+ const card = page.locator('button[aria-label^="Ultra Key. Drag"]').first();+ await card.scrollIntoViewIfNeeded();+ await card.dblclick();+ await expect.poll(async () => (await ultraKeyEffects(page)).length, { timeout: 15_000 }).toBe(1);+ const [fx] = await ultraKeyEffects(page);+ expect(fx.params.keyG, "authored defaults are written").toBe(255);+ expect(fx.params.tolerance).toBe(50);++ // Point the key somewhere wrong, then fix it with the eyedropper on the Program monitor.+ await page.evaluate(+ async ([c, e]) => {+ await (window as unknown as { __openreelE2E: E2EStores }).__openreelE2E.project+ .getState()+ .updateVideoEffect(c as string, e as string, { keyR: 255, keyG: 0, keyB: 0 });+ },+ [clipId, fx.id] as const,+ );+ await settle(page, 600);+ await page.getByRole("button", { name: "Edit Ultra Key" }).click();+ await expect(page.getByTestId("ultra-key-controls")).toBeVisible({ timeout: 15_000 });+ await snap(page, "wrong-key");+ // A red key leaves the green screen on the monitor.+ expect((await pixel(page, "wrong-key", SCREEN))[1]).toBeGreaterThan(60);++ await page.getByRole("button", { name: "Pick key color from the Program monitor" }).click();+ await page.getByTestId("ultra-key-picker-layer").waitFor();+ await settle(page, 900);+ const box = await page.locator(PROGRAM).boundingBox();+ if (!box) throw new Error("no Program canvas box");+ await page.mouse.click(box.x + box.width * SCREEN.x, box.y + box.height * SCREEN.y);+ await expect(page.getByTestId("ultra-key-picker-layer")).toHaveCount(0);+ await expect+ .poll(async () => (await ultraKeyEffects(page))[0].params.keyG, { timeout: 10_000 })+ .toBeGreaterThan(70);+ const picked = (await ultraKeyEffects(page))[0].params;+ console.log(`[ultra-key] picked key ${picked.keyR},${picked.keyG},${picked.keyB}`);+ expect(picked.keyR).toBeLessThan(90);+ expect(picked.keyG).toBeGreaterThan(picked.keyR + 60);+ await settle(page, 900);++ // Composite: the screen is gone, the subject is untouched.+ await snapUntil(page, "keyed", SCREEN, (px) => px[1] < px[0] + 20);+ const screenKeyed = await pixel(page, "keyed", SCREEN);+ const subjectKeyed = await pixel(page, "keyed", SUBJECT);+ console.log(`[ultra-key] keyed screen=${screenKeyed} subject=${subjectKeyed}`);+ // Transparent: whatever sits under the clip shows through (another clip's picture here), never the green.+ expect(screenKeyed[1], "keyed screen no longer shows green").toBeLessThan(screenKeyed[0] + 20);+ expect(Math.abs(screenKeyed[1] - screenBefore[1]) + Math.abs(screenKeyed[0] - screenBefore[0]), "the screen pixel changed").toBeGreaterThan(60);+ for (let i = 0; i < 3; i++) expect(Math.abs(subjectKeyed[i] - subjectBefore[i]), `subject channel ${i}`).toBeLessThan(14);++ // Alpha channel output: the matte as grey (screen black, subject white); the colour channel shows the footage.+ await page.getByRole("group", { name: "Ultra Key output" }).getByRole("button", { name: "Alpha" }).click();+ await settle(page, 900);+ await snapUntil(page, "alpha", SCREEN, (px) => Math.max(...px) < 20);+ const alphaScreen = await pixel(page, "alpha", SCREEN);+ const alphaSubject = await pixel(page, "alpha", SUBJECT);+ expect(Math.max(...alphaScreen)).toBeLessThan(20);+ expect(Math.min(...alphaSubject)).toBeGreaterThan(235);+ await page.getByRole("group", { name: "Ultra Key output" }).getByRole("button", { name: "Color" }).click();+ await settle(page, 900);+ await snap(page, "color");+ expect((await pixel(page, "color", SCREEN))[1], "colour channel keeps the screen").toBeGreaterThan(60);+ await page.getByRole("group", { name: "Ultra Key output" }).getByRole("button", { name: "Composite" }).click();+ await settle(page, 700);++ // Eyedroppers are mutually exclusive: arming Ultra Key then White Balance disarms the key picker,+ // so the key output returns to the composite and the WB pick (not the key pick) takes the click.+ const monitor = (): string =>+ "(window.__openreelE2E.colorMonitor.getState())";+ await page.getByRole("button", { name: "Pick key color from the Program monitor" }).click();+ await page.getByTestId("ultra-key-picker-layer").waitFor();+ await settle(page, 600);+ await page.evaluate(+ (id) => (window as unknown as { __openreelE2E: { colorMonitor: { getState(): Record<string, any> } } }).__openreelE2E.colorMonitor.getState().setWhiteBalancePick({ clipId: id }),+ clipId,+ );+ await expect(page.getByTestId("ultra-key-picker-layer")).toHaveCount(0);+ await page.getByTestId("wb-eyedropper-layer").waitFor();+ expect(await page.evaluate(`${monitor()}.keyPicker`)).toBeNull();+ await settle(page, 900);+ await snapUntil(page, "after-wb-arm", SCREEN, (px) => px[1] < px[0] + 20);+ const screenAfterArm = await pixel(page, "after-wb-arm", SCREEN);+ expect(screenAfterArm[1], "key output is back to composite, not stuck on the source").toBeLessThan(screenAfterArm[0] + 20);+ const keyBeforeWb = (await ultraKeyEffects(page))[0].params;+ await page.mouse.click(box.x + box.width * SUBJECT.x, box.y + box.height * SUBJECT.y);+ await expect(page.getByTestId("wb-eyedropper-layer")).toHaveCount(0);+ await expect+ .poll(+ async () =>+ page.evaluate((id) => {+ const g = (window as unknown as { __openreelE2E: { project: { getState(): Record<string, any> } } }).__openreelE2E.project.getState().getClip(id)?.colorGrading ?? {};+ return Math.abs(g.temperature ?? 0) + Math.abs(g.tint ?? 0);+ }, clipId),+ { timeout: 10_000 },+ )+ .toBeGreaterThan(0);+ const keyAfterWb = (await ultraKeyEffects(page))[0].params;+ expect(keyAfterWb.keyR, "the WB pick did not retarget the key colour").toBe(keyBeforeWb.keyR);+ expect(keyAfterWb.keyG).toBe(keyBeforeWb.keyG);++ // Keyframable: a diamond on a slider stores an effect-instance keyframe on the clip.+ await page.getByRole("button", { name: "Keyframe transparency" }).first().click();+ await settle(page, 400);+ const keyframes = await page.evaluate((id) => {+ const state = (window as unknown as { __openreelE2E: { project: { getState(): Record<string, any> } } }).__openreelE2E.project.getState();+ return (state.getClip(id)?.keyframes ?? []).map((k: { property: string }) => k.property);+ }, clipId);+ expect(keyframes).toContain(`fx:${fx.id}:transparency`);++ // The keyboard shortcut undoes Ultra Key edits too (not only the toolbar button): switch the output, blur, Ctrl/Cmd+Z.+ await page.getByRole("group", { name: "Ultra Key output" }).getByRole("button", { name: "Alpha" }).click();+ await settle(page, 500);+ const outputAfter = (await ultraKeyEffects(page))[0].params.output;+ await page.evaluate(() => (document.activeElement as HTMLElement | null)?.blur());+ await page.keyboard.press(process.platform === "darwin" ? "Meta+z" : "Control+z");+ await expect+ .poll(async () => (await ultraKeyEffects(page))[0].params.output, { timeout: 10_000 })+ .not.toBe(outputAfter);+ });++ test("Ultra Key card previews the real key on your footage and is badged as a sample", async ({ page }) => {+ test.setTimeout(240_000);+ await openEditor(page);+ await seek(page, 0.2);+ await page.getByRole("button", { name: "Effects", exact: true }).first().click();+ await settle(page, 500);+ await page.getByRole("button", { name: "Keying", exact: true }).first().click();+ const canvas = page.locator('button[aria-label^="Ultra Key. Drag"] canvas').first();+ await canvas.scrollIntoViewIfNeeded();+ await expect.poll(async () => canvas.getAttribute("data-preview-state"), { timeout: 60_000 }).toBe("poster");+ expect(await canvas.getAttribute("data-preview-source")).toBe("footage");+ await expect(page.locator('button[aria-label^="Ultra Key. Drag"] [aria-hidden="true"] span').first()).toHaveText("Sample key");+ // The card must show the footage keyed, not an empty checkerboard: plenty of distinct colours, not just the two checker tones.+ const colours = await canvas.evaluate((el) => {+ const c = el as HTMLCanvasElement;+ const g = document.createElement("canvas");+ g.width = c.width;+ g.height = c.height;+ const ctx = g.getContext("2d", { willReadFrequently: true })!;+ ctx.drawImage(c, 0, 0);+ const d = ctx.getImageData(0, 0, g.width, g.height).data;+ const seen = new Set<number>();+ for (let i = 0; i < d.length; i += 4) seen.add(((d[i] >> 4) << 8) | ((d[i + 1] >> 4) << 4) | (d[i + 2] >> 4));+ return seen.size;+ });+ expect(colours, "the card shows the subject, not just the checkerboard").toBeGreaterThan(12);+ });++ test("Ultra Key shader matches the CPU reference (WebGL2 path vs software / export path)", async ({ page }) => {+ test.setTimeout(180_000);+ await page.goto("/");+ await page.waitForFunction(() => Boolean((window as unknown as { __openreelE2E?: unknown }).__openreelE2E));+ const report = await page.evaluate(() => {+ const hook = (window as unknown as { __openreelE2E: { secondary: Record<string, any>; core: { proEffects: Record<string, any> } } }).__openreelE2E;+ const e = hook.secondary;+ const defaults = hook.core.proEffects.PRO_EFFECT_DEFAULTS["ultra-key"] as Record<string, unknown>;+ const W = 192;+ const H = 108;+ // A lit green screen (brighter in the middle, noisy), a skin subject with a blue patch and a soft pale-green rim.+ const src = new Uint8ClampedArray(W * H * 4);+ let seed = 12345;+ const rnd = () => ((seed = (seed * 1664525 + 1013904223) >>> 0) / 4294967296 - 0.5) * 10;+ for (let y = 0; y < H; y++)+ for (let x = 0; x < W; x++) {+ const lit = 0.65 + 0.35 * Math.sin((x / W) * Math.PI) * Math.sin((y / H) * Math.PI);+ let px = [20 * lit, 180 * lit, 76 * lit];+ const dx = x - W / 2;+ const dy = y - H / 2;+ const r = Math.hypot(dx / 38, dy / 40);+ if (r < 1) px = [217, 160, 122];+ if (r < 1 && x < W / 2 - 8 && y < H / 2 - 10) px = [42, 63, 143];+ if (r >= 1 && r < 1.12) px = [150 + 60 * (r - 1) * 8, 200, 120]; // spill rim+ src.set([px[0] + rnd(), px[1] + rnd(), px[2] + rnd(), 255], (y * W + x) * 4);+ }+ const base = { keyR: 20, keyG: 180, keyB: 76 };+ const cases: Record<string, Record<string, unknown>> = {+ default: { ...defaults, ...base },+ "wide key": { ...base, transparency: 80, highlight: 30, shadow: 20, tolerance: 70, pedestal: 5, spill: 0, desaturate: 0, luma: 0 },+ "choke + soften": { ...base, transparency: 45, tolerance: 50, choke: 60, soften: 50, spill: 0, desaturate: 0, luma: 0 },+ "contrast + midpoint": { ...base, transparency: 60, tolerance: 40, contrast: 70, midPoint: 35, spill: 0, desaturate: 0, luma: 0 },+ "spill + colour correction": { ...base, spill: 100, range: 90, desaturate: 60, luma: 80, saturation: 130, hue: 20, luminance: 90 },+ "alpha channel": { ...base, output: "alpha", choke: 30, soften: 30 },+ "colour channel": { ...base, output: "color", spill: 80, range: 70, saturation: 80 },+ };+ const supported = Boolean(e.MotionShaderRenderer.isSupported());+ const renderer = supported ? new e.MotionShaderRenderer() : null;+ const rows: Array<Record<string, number | string>> = [];+ for (const [name, params] of Object.entries(cases)) {+ const full = { ...(params as Record<string, unknown>) };+ const cpu = new Uint8ClampedArray(src);+ e.applyProEffect("ultra-key", full, cpu, W, H);+ if (!renderer) {+ rows.push({ name, gpu: "unsupported" });+ continue;+ }+ const input = document.createElement("canvas");+ input.width = W;+ input.height = H;+ input.getContext("2d", { willReadFrequently: true })!.putImageData(new ImageData(new Uint8ClampedArray(src), W, H), 0, 0);+ const out = renderer.render(e.PRO_EFFECT_SHADER_DEFS["ultra-key"], {+ width: W,+ height: H,+ time: 0,+ params: e.proEffectGpuUniforms("ultra-key", full, H),+ inputCanvas: input,+ strict: true,+ });+ if (!out) {+ rows.push({ name, gpu: "render-failed" });+ continue;+ }+ const c2 = document.createElement("canvas");+ c2.width = W;+ c2.height = H;+ const g2 = c2.getContext("2d", { willReadFrequently: true })!;+ g2.drawImage(out, 0, 0, W, H);+ const gpu = g2.getImageData(0, 0, W, H).data;+ let alphaSum = 0;+ let alphaOver = 0;+ let rgbSum = 0;+ let rgbN = 0;+ let rgbOver = 0;+ let transparent = 0;+ for (let i = 0; i < gpu.length; i += 4) {+ const da = Math.abs(gpu[i + 3] - cpu[i + 3]);+ alphaSum += da;+ if (da > 3) alphaOver++;+ if (cpu[i + 3] < 8) transparent++;+ // Colour is only meaningful where the pixel is visible (premultiplied storage loses it below that).+ if (cpu[i + 3] >= 200 && gpu[i + 3] >= 200)+ for (let k = 0; k < 3; k++) {+ const d = Math.abs(gpu[i + k] - cpu[i + k]);+ rgbSum += d;+ rgbN++;+ if (d > 3) rgbOver++;+ }+ }+ const px = W * H;+ rows.push({ name, gpu: "ok", alphaMean: alphaSum / px, alphaOver: alphaOver / px, rgbMean: rgbN ? rgbSum / rgbN : 0, rgbOver: rgbN ? rgbOver / rgbN : 0, transparent: transparent / px });+ }+ return { supported, rows };+ });+ console.log(`[ultra-key] shader parity (WebGL2 supported=${report.supported})\n` + report.rows.map((r) => JSON.stringify(r)).join("\n"));+ test.skip(!report.supported, "WebGL2 unavailable in this browser: the CPU reference is the only path here");+ for (const row of report.rows) {+ expect(row.gpu, String(row.name)).toBe("ok");+ expect(row.alphaMean as number, `${row.name} mean alpha diff`).toBeLessThan(0.8);+ expect(row.alphaOver as number, `${row.name} share of alpha off by more than 3`).toBeLessThan(0.004);+ expect(row.rgbMean as number, `${row.name} mean colour diff`).toBeLessThan(0.8);+ expect(row.rgbOver as number, `${row.name} share of channels off by more than 3`).toBeLessThan(0.004);+ }+ // The cases must actually key something (guards against comparing two no-ops).+ expect(report.rows.find((r) => r.name === "default")?.transparent as number).toBeGreaterThan(0.3);+ });+}diff --git a/apps/web/e2e/ultra-key.spec.ts b/apps/web/e2e/ultra-key.spec.tsnew file mode 100644index 00000000..91501bf8--- /dev/null+++ b/apps/web/e2e/ultra-key.spec.ts@@ -0,0 +1,4 @@+import { registerUltraKeyTests } from "./ultra-key-lib";++// Runs under the gpu project. The fallback-nowebgpu / fallback-software projects run the same flow from fallback-ultra-key.spec.ts.+registerUltraKeyTests();diff --git a/apps/web/e2e/voiceover-lib.ts b/apps/web/e2e/voiceover-lib.tsnew file mode 100644index 00000000..939bb0cd--- /dev/null+++ b/apps/web/e2e/voiceover-lib.ts@@ -0,0 +1,78 @@+import type { Page } from "@playwright/test";++/**+ * Chrome's fake audio capture device (--use-fake-device-for-media-stream) answers getUserMedia in under a+ * second on Linux CI, but on a macOS host whose microphone privacy (TCC) state is unresolved for Chrome the+ * audio request never settles (video is unaffected; enumerateDevices still lists the fake inputs). This+ * init script keeps the fake device first and falls back to a synthetic tone stream (a sine written through a+ * MediaStreamTrackGenerator) only when the real request has not settled after `FALLBACK_MS`, so the+ * recorder is exercised end to end on either host. `window.__voiceOverFakeMic` records which one answered.+ */+export function installFakeMicFallback(page: Page, fallbackMs = 4000): Promise<void> {+ // fallbackMs <= 0 is strict mode: only Chrome's real fake device may answer (CI sets VO_STRICT_FAKE_MIC).+ return page.addInitScript((ms: number) => {+ const devices = navigator.mediaDevices;+ if (!devices?.getUserMedia) return;+ const original = devices.getUserMedia.bind(devices);+ // Every audio request is logged so specs can assert which device a take actually opened.+ const calls: Array<{ deviceId: string | null; echoCancellation: boolean | null }> = [];+ (window as unknown as { __voiceOverGum: typeof calls }).__voiceOverGum = calls;+ let synthetic = false;+ // A MediaStreamTrackGenerator needs no AudioContext, which can take many seconds to open on a host whose+ // audio device is wedged (the same condition that stalls the real fake-device request).+ const tone = (): MediaStream => {+ const Generator = (window as unknown as { MediaStreamTrackGenerator?: new (init: { kind: "audio" }) => MediaStreamTrack & { writable: WritableStream } }).MediaStreamTrackGenerator;+ const AudioDataCtor = (window as unknown as { AudioData?: new (init: Record<string, unknown>) => unknown }).AudioData;+ if (Generator && AudioDataCtor) {+ const track = new Generator({ kind: "audio" });+ const writer = track.writable.getWriter();+ const rate = 48000;+ const frames = 960;+ let sampleIndex = 0;+ setInterval(() => {+ const samples = new Float32Array(frames);+ for (let i = 0; i < frames; i++) samples[i] = 0.3 * Math.sin((2 * Math.PI * 220 * (sampleIndex + i)) / rate);+ const data = new AudioDataCtor({ format: "f32-planar", sampleRate: rate, numberOfFrames: frames, numberOfChannels: 1, timestamp: Math.round((sampleIndex / rate) * 1e6), data: samples });+ sampleIndex += frames;+ void writer.write(data).catch(() => undefined);+ }, 20);+ return new MediaStream([track]);+ }+ const context = new AudioContext();+ void context.resume();+ const oscillator = context.createOscillator();+ oscillator.frequency.value = 220;+ const gain = context.createGain();+ gain.gain.value = 0.3;+ const destination = context.createMediaStreamDestination();+ oscillator.connect(gain).connect(destination);+ oscillator.start();+ return destination.stream;+ };+ (window as unknown as { __voiceOverFakeMic: string }).__voiceOverFakeMic = "chrome-fake-device";+ devices.getUserMedia = async (constraints?: MediaStreamConstraints) => {+ if (!constraints?.audio || constraints.video) return original(constraints);+ const audio = constraints.audio === true ? {} : (constraints.audio as MediaTrackConstraints);+ const wanted = audio.deviceId;+ calls.push({+ deviceId: wanted ? (typeof wanted === "string" ? wanted : Array.isArray(wanted) ? (wanted[0] ?? null) : ((wanted as ConstrainDOMStringParameters).exact as string | undefined) ?? null) : null,+ echoCancellation: typeof audio.echoCancellation === "boolean" ? audio.echoCancellation : null,+ });+ if (ms <= 0) return original(constraints);+ if (synthetic) return tone();+ const real = original(constraints);+ const settled = await Promise.race([+ real.then(+ (stream) => ({ stream }),+ (error: unknown) => ({ error }),+ ),+ new Promise<null>((resolve) => setTimeout(() => resolve(null), ms)),+ ]);+ if (settled && "stream" in settled) return settled.stream;+ if (settled && "error" in settled) throw settled.error;+ synthetic = true;+ (window as unknown as { __voiceOverFakeMic: string }).__voiceOverFakeMic = "synthetic-tone";+ return tone();+ };+ }, fallbackMs);+}diff --git a/apps/web/e2e/voiceover.spec.ts b/apps/web/e2e/voiceover.spec.tsnew file mode 100644index 00000000..b2ca5e71--- /dev/null+++ b/apps/web/e2e/voiceover.spec.ts@@ -0,0 +1,227 @@+import { expect, test, type Page } from "@playwright/test";+import { GPU_ARGS } from "./env";+import { openEditor, readState, settle } from "./helpers";+import { installFakeMicFallback } from "./voiceover-lib";++/**+ * Voice-over recording against Chrome's fake microphone (--use-fake-device-for-media-stream feeds a beep+ * stream and --use-fake-ui-for-media-stream answers the permission prompt):+ * - the input device is chosen from enumerateDevices and remembered (parsing on reload is unit tested);+ * - the pre-roll counts down while the timeline plays, then recording starts at the playhead;+ * - the take is a normal clip named "Voice Over Take N" on a new Voice Over track, removed by ONE undo;+ * - a re-take of the same range stacks on a new track instead of overlapping;+ * - "mute playback while recording" silences the preview only for the take;+ * - punch in/out records exactly between the In and Out marks and stops by itself.+ */+test.use({+ launchOptions: { args: [...GPU_ARGS, "--use-fake-device-for-media-stream", "--use-fake-ui-for-media-stream", "--autoplay-policy=no-user-gesture-required"] },+ permissions: ["microphone"],+});++test.beforeEach(async ({ page }) => {+ // CI (or VO_STRICT_FAKE_MIC=1) lets only Chrome's real fake device answer; elsewhere a tone stands in for a+ // host whose microphone privacy state stalls the request, and the spec says which one it used.+ await installFakeMicFallback(page, process.env.CI || process.env.VO_STRICT_FAKE_MIC ? 0 : 2500);+ if (process.env.VO_DEBUG) { page.on("console", (m) => { if (m.type() !== "debug") console.log("CONSOLE", m.type(), m.text().slice(0, 300)); }); page.on("pageerror", (e) => console.log("PAGEERR", e.message)); }+});++interface E2EWindow {+ __openreelE2E: {+ voiceover: { getState(): Record<string, any> };+ timeline: { getState(): Record<string, any> };+ workspace: { getState(): Record<string, any> };+ project: { getState(): Record<string, any> };+ };+}++async function openVoiceOverPanel(page: Page): Promise<void> {+ await page.evaluate(() => {+ const workspace = (window as unknown as E2EWindow).__openreelE2E.workspace.getState();+ workspace.setSection("audio");+ workspace.setAudioSource("voiceover");+ });+ await expect(page.getByTestId("voiceover-panel")).toBeVisible();+}++/** Records every recorder state change (phase, countdown, transport) so a stalled page cannot miss the 1 s steps. */+async function traceRecorder(page: Page): Promise<void> {+ await page.evaluate(() => {+ const w = window as unknown as E2EWindow & { __voTrace: Array<{ phase: string; countdown: number; playing: boolean; playhead: number }> };+ w.__voTrace = [];+ w.__openreelE2E.voiceover.subscribe((state: Record<string, any>) => {+ const t = w.__openreelE2E.timeline.getState();+ w.__voTrace.push({ phase: state.phase, countdown: state.countdown, playing: t.playbackState === "playing", playhead: t.playheadPosition });+ });+ });+}+const readTrace = (page: Page) =>+ page.evaluate(() => (window as unknown as { __voTrace: Array<{ phase: string; countdown: number; playing: boolean; playhead: number }> }).__voTrace);++const phase = (page: Page) => page.getByTestId("voiceover-panel").getAttribute("data-phase");++async function timeline(page: Page): Promise<{ playhead: number; playing: boolean }> {+ return page.evaluate(() => {+ const t = (window as unknown as E2EWindow).__openreelE2E.timeline.getState();+ return { playhead: t.playheadPosition as number, playing: t.playbackState === "playing" };+ });+}++const voiceTracks = async (page: Page) =>+ (await readState(page)).tracks.filter((track) => track.name.startsWith("Voice Over") && track.clips.length > 0);++test("records a take with pre-roll, stacks a re-take, mutes playback and undoes in one step", async ({ page }) => {+ test.setTimeout(420_000);+ await openEditor(page);+ await openVoiceOverPanel(page);++ // Input devices come from enumerateDevices; the fake device is listed once the microphone is open.+ await page.getByTestId("voiceover-monitor").click();+ await expect(page.getByTestId("voiceover-panel")).toHaveAttribute("data-phase", "monitoring", { timeout: 20_000 });+ const device = page.getByTestId("voiceover-device");+ await expect.poll(async () => device.locator("option").count()).toBeGreaterThan(1);+ const micSource = await page.evaluate(() => (window as unknown as { __voiceOverFakeMic: string }).__voiceOverFakeMic);+ test.info().annotations.push({ type: "mic-source", description: micSource });+ // The meter reads the live input, so the beep stream must light it.+ await expect+ .poll(async () => page.evaluate(() => (window as unknown as E2EWindow).__openreelE2E.voiceover.getState().level as number), { timeout: 20_000 })+ .toBeGreaterThan(0.02);+ await page.getByTestId("voiceover-monitor").click();+ await expect(page.getByTestId("voiceover-panel")).toHaveAttribute("data-phase", "idle");++ const chosen = await device.locator("option").nth(1).getAttribute("value");+ await device.selectOption(chosen!);+ await page.getByTestId("voiceover-preroll").selectOption("2");+ const remembered = await page.evaluate(() => JSON.parse(localStorage.getItem("openreel:voiceover:prefs:v1") ?? "{}"));+ expect(remembered).toMatchObject({ deviceId: chosen, preRoll: 2, muteDuringRecord: true });++ const before = await readState(page);+ await page.evaluate(() => (window as unknown as E2EWindow).__openreelE2E.timeline.getState().seekTo(3));+ await settle(page, 300);++ await traceRecorder(page);+ await page.getByRole("button", { name: "Record Voice Over" }).click();+ await expect(page.getByTestId("voiceover-panel")).toHaveAttribute("data-phase", "recording", { timeout: 60_000 });+ // The countdown ran 2, 1 with the transport playing, and the timeline was parked 2 s before the take (3 - 2 = 1 s).+ const trace = await readTrace(page);+ const countdown = trace.filter((entry) => entry.phase === "countdown");+ expect(countdown.map((entry) => entry.countdown)).toContain(2);+ expect(countdown.map((entry) => entry.countdown)).toContain(1);+ expect(countdown.some((entry) => entry.playing)).toBe(true);+ expect(countdown[0].playhead).toBeGreaterThanOrEqual(0.99);+ expect(countdown[0].playhead).toBeLessThan(3);+ // Playback runs through the pre-roll: the playhead advances toward the take start while counting down.+ const advanced = Math.max(...trace.map((entry) => entry.playhead)) - countdown[0].playhead;+ expect(advanced).toBeGreaterThan(0.3);+ // Playback is silenced for the take only.+ await expect(page.getByRole("button", { name: "Unmute", exact: true })).toBeVisible();+ await page.waitForTimeout(1600);+ await page.getByRole("button", { name: "Stop & Add to Timeline" }).click();++ await expect.poll(async () => (await voiceTracks(page)).length, { timeout: 30_000 }).toBe(1);+ await expect(page.getByTestId("voiceover-panel")).toHaveAttribute("data-phase", "idle", { timeout: 15_000 });+ await expect(page.getByRole("button", { name: "Mute", exact: true })).toBeVisible();+ expect((await timeline(page)).playing).toBe(false);++ const first = (await voiceTracks(page))[0];+ expect(first.name).toBe("Voice Over");+ expect(first.type).toBe("audio");+ expect(first.clips[0].start).toBeGreaterThan(2.7);+ expect(first.clips[0].start).toBeLessThanOrEqual(3.001);+ expect(first.clips[0].duration).toBeGreaterThan(1);+ await expect(page.getByTestId("voiceover-take").first()).toContainText("Voice Over Take 1");++ // Re-take over the same range on the same track: stacked on a new track, never overlapping.+ await page.getByTestId("voiceover-track").selectOption(first.id);+ await page.getByTestId("voiceover-preroll").selectOption("0");+ await page.evaluate((t) => (window as unknown as E2EWindow).__openreelE2E.timeline.getState().seekTo(t), first.clips[0].start + 0.2);+ await settle(page, 300);+ await page.getByRole("button", { name: "Record Voice Over" }).click();+ await expect(page.getByTestId("voiceover-panel")).toHaveAttribute("data-phase", "recording", { timeout: 60_000 });+ await page.waitForTimeout(1200);+ await page.getByRole("button", { name: "Stop & Add to Timeline" }).click();+ await expect.poll(async () => (await voiceTracks(page)).length, { timeout: 30_000 }).toBe(2);+ const tracks = await voiceTracks(page);+ expect(tracks.map((t) => t.name).sort()).toEqual(["Voice Over", "Voice Over 2"]);+ await expect(page.getByTestId("voiceover-take")).toHaveCount(2);+ await expect(page.getByTestId("voiceover-take").nth(1)).toContainText("Voice Over Take 2");+ await expect(page.getByTestId("voiceover-note")).toContainText("stacked on a new track");++ // One undo removes the whole second take (new track, rename and clip together), leaving the first take.+ await page.getByTestId("voiceover-panel").click({ position: { x: 4, y: 4 } });+ await page.evaluate(() => (document.activeElement as HTMLElement | null)?.blur?.());+ await page.keyboard.press("ControlOrMeta+z");+ await expect.poll(async () => (await voiceTracks(page)).length, { timeout: 10_000 }).toBe(1);+ expect((await readState(page)).tracks.length).toBe(before.tracks.length + 1);+ await page.keyboard.press("ControlOrMeta+z");+ await expect.poll(async () => (await readState(page)).tracks.length, { timeout: 10_000 }).toBe(before.tracks.length);+});++test("punch in/out records only between the In and Out marks and stops by itself", async ({ page }) => {+ test.setTimeout(180_000);+ await openEditor(page);+ await openVoiceOverPanel(page);++ // Punch needs a valid In/Out range.+ await expect(page.getByTestId("voiceover-punch")).toBeDisabled();+ await page.evaluate(() => (window as unknown as E2EWindow).__openreelE2E.timeline.getState().setLoopRange(1, 2.6));+ await expect(page.getByTestId("voiceover-punch")).toBeEnabled();+ await page.getByTestId("voiceover-punch").check();+ await page.getByTestId("voiceover-preroll").selectOption("1");+ await page.evaluate(() => (window as unknown as E2EWindow).__openreelE2E.timeline.getState().seekTo(5));+ await expect(page.getByTestId("voiceover-subline")).toContainText("Punches 0:01.0 to 0:02.6");++ await page.getByRole("button", { name: "Record Voice Over" }).click();+ await expect(page.getByTestId("voiceover-panel")).toHaveAttribute("data-phase", "recording", { timeout: 60_000 });+ // No Stop click: the take ends at Out by itself, about 1.6 s after it began.+ await expect.poll(async () => (await voiceTracks(page)).length, { timeout: 30_000 }).toBe(1);+ const clip = (await voiceTracks(page))[0].clips[0];+ expect(clip.start).toBeGreaterThan(0.74);+ expect(clip.start).toBeLessThanOrEqual(1.001);+ expect(clip.duration).toBeGreaterThan(0.9);+ expect(clip.duration).toBeLessThan(2.4);+ await expect(page.getByTestId("voiceover-panel")).toHaveAttribute("data-phase", "idle", { timeout: 15_000 });+});++test("a device picked during a level check is the one the take is recorded from", async ({ page }) => {+ test.setTimeout(180_000);+ await openEditor(page);+ await openVoiceOverPanel(page);++ await page.getByTestId("voiceover-monitor").click();+ await expect(page.getByTestId("voiceover-panel")).toHaveAttribute("data-phase", "monitoring", { timeout: 20_000 });+ const device = page.getByTestId("voiceover-device");+ await expect.poll(async () => device.locator("option").count()).toBeGreaterThan(2);+ // The "default" alias is the same microphone as "System default": it is listed once.+ const values = await device.locator("option").evaluateAll((options) => options.map((o) => (o as HTMLOptionElement).value));+ expect(values).not.toContain("default");+ expect(values.filter((v) => v === "").length).toBe(1);++ const gum = () => page.evaluate(() => (window as unknown as { __voiceOverGum: Array<{ deviceId: string | null; echoCancellation: boolean | null }> }).__voiceOverGum);+ const callsBefore = (await gum()).length;+ const chosen = values.find((v) => v !== "")!;+ await device.selectOption(chosen);+ // The monitor reopens on the new microphone right away.+ await expect.poll(async () => (await gum()).length, { timeout: 15_000 }).toBeGreaterThan(callsBefore);+ expect((await gum()).at(-1)?.deviceId).toBe(chosen);+ await expect(page.getByTestId("voiceover-panel")).toHaveAttribute("data-phase", "monitoring", { timeout: 20_000 });++ // Toggling mute-input changes the echo-cancellation constraint, which also reopens the stream.+ const callsMid = (await gum()).length;+ await page.getByTestId("voiceover-mute").click();+ await expect.poll(async () => (await gum()).length, { timeout: 15_000 }).toBeGreaterThan(callsMid);+ await expect(page.getByTestId("voiceover-panel")).toHaveAttribute("data-phase", "monitoring", { timeout: 20_000 });++ await page.getByTestId("voiceover-preroll").selectOption("0");+ await page.getByRole("button", { name: "Record Voice Over" }).click();+ await expect(page.getByTestId("voiceover-panel")).toHaveAttribute("data-phase", "recording", { timeout: 60_000 });+ expect((await gum()).at(-1)?.deviceId).toBe(chosen);+ await page.waitForTimeout(1000);+ await page.getByRole("button", { name: "Stop & Add to Timeline" }).click();+ await expect.poll(async () => (await voiceTracks(page)).length, { timeout: 30_000 }).toBe(1);+ // The inspector/take list shows the clean take name, without the file extension.+ await expect(page.getByTestId("voiceover-take").first()).not.toContainText(".webm");+ const mediaNames = await page.evaluate(() =>+ ((window as unknown as E2EWindow).__openreelE2E.project.getState().project.mediaLibrary.items as Array<{ name: string }>).map((i) => i.name),+ );+ expect(mediaNames).toContain("Voice Over Take 1");+});diff --git a/apps/web/src/bridges/effects-bridge.ts b/apps/web/src/bridges/effects-bridge.tsindex dbcc4cb2..09acc971 100644--- a/apps/web/src/bridges/effects-bridge.ts+++ b/apps/web/src/bridges/effects-bridge.ts@@ -13,11 +13,13 @@ import {type VignetteValues,type HueCurvesValues,planColorGrading,+ whiteBalanceInputGrading,DEFAULT_COLOR_WHEELS,DEFAULT_CURVES,DEFAULT_HSL,isNeutralColorGrading,type ProEffectType,+ type BurnInEffectType,} from "@openreel/core";import type { Effect } from "@openreel/core";import { v4 as uuidv4 } from "uuid";@@ -47,6 +49,7 @@ export type VideoEffectType =| "radial-blur"| "chromatic-aberration"| ProEffectType+ | BurnInEffectType| "shader"/** Third-party effect plugin: `plugin:<pluginId>` (see packages/core/src/plugins). */| `plugin:${string}`;@@ -158,6 +161,7 @@ export class EffectsBridge {* view). Never serialized and never read by the export pipeline.*/private transientEffectParams: Map<string, Record<string, unknown>> = new Map();+ private whiteBalanceInputClip: string | null = null;// WebGPU renderer support// Note: Actual rendering is delegated to VideoEffectsEngine which handles@@ -858,7 +862,18 @@ export class EffectsBridge {* @returns Color grading settings*/getColorGrading(clipId: string): ColorGradingSettings {- return this.clipColorGrading.get(clipId) || {};+ const stored = this.clipColorGrading.get(clipId) || {};+ // Preview-only: the white balance eyedropper renders the clip as the white balance stage sees it.+ return clipId === this.whiteBalanceInputClip ? whiteBalanceInputGrading(stored) : stored;+ }++ /** Preview-only view of `clipId` at the white balance stage input (null restores the full grade). Never stored or exported. */+ setWhiteBalanceInputView(clipId: string | null): void {+ this.whiteBalanceInputClip = clipId;+ }++ whiteBalanceInputView(): string | null {+ return this.whiteBalanceInputClip;}/**diff --git a/apps/web/src/bridges/media-bridge.ts b/apps/web/src/bridges/media-bridge.tsindex ec4b96a1..6283288d 100644--- a/apps/web/src/bridges/media-bridge.ts+++ b/apps/web/src/bridges/media-bridge.ts@@ -5,6 +5,7 @@ import type {WaveformData,MediaTrackInfo,} from "@openreel/core";+import { backgroundTasks, type TrackContext } from "@openreel/core/tasks/task-registry";import { useProjectStore } from "../stores/project-store";import { loadEngineModules } from "../services/lazy-engines";import { toast } from "../stores/notification-store";@@ -14,6 +15,12 @@ const CODEC_UNSUPPORTED_PREFIX = "This browser cannot decode this video's codec"// Matches core's PRO_MEDIA_PROXY_PREFIX (pro media converted to a browser proxy).const PRO_MEDIA_PROXY_PREFIX = "Pro media proxy:";+class ImportTaskFailure extends Error {+ constructor(readonly result: MediaBridgeImportResult) {+ super(result.error ?? "Import failed");+ }+}+/*** Import progress callback type*/@@ -187,7 +194,45 @@ export class MediaBridge {* @param generateWaveform - Whether to generate waveform data (default: true)* @returns Import result with processed media or error*/- async importFile(+ importFile(+ file: File,+ generateWaveform = true,+ quickMode = false,+ onProgress?: (stage: string) => void,+ options: { untracked?: boolean; signal?: AbortSignal } = {},+ ): Promise<MediaBridgeImportResult> {+ // Callers that own a wider task (the project store's import action) pass `untracked`.+ // Otherwise imports are reported to the task registry; a failed result is a failed task, never an exception.+ const cancelled: MediaBridgeImportResult = { success: false, error: "Import cancelled", hasWaveform: false };+ const withSignal = (signal: AbortSignal | undefined, stage?: (s: string) => void): Promise<MediaBridgeImportResult> => {+ if (signal?.aborted) return Promise.resolve(cancelled);+ const work = this.importFileUntracked(file, generateWaveform, quickMode, stage);+ if (!signal) return work;+ // The decode cannot be interrupted, so Cancel detaches from it: its result is discarded, never published.+ return new Promise((resolve, reject) => {+ const onAbort = () => resolve(cancelled);+ signal.addEventListener("abort", onAbort, { once: true });+ work.then(resolve, reject).finally(() => signal.removeEventListener("abort", onAbort));+ });+ };+ if (options.untracked) return withSignal(options.signal, onProgress);+ const run = (ctx: TrackContext): Promise<MediaBridgeImportResult> =>+ withSignal(ctx.signal, (stage) => {+ ctx.progress(null, stage);+ onProgress?.(stage);+ }).then((result) => {+ if (!result.success && !ctx.signal.aborted) throw new ImportTaskFailure(result);+ return result;+ });+ return backgroundTasks+ .track({ kind: "import", source: "import", title: `Import \u00b7 ${file.name}` }, run)+ .catch((error) => {+ if (error instanceof ImportTaskFailure) return error.result;+ throw error;+ });+ }++ private async importFileUntracked(file: File,generateWaveform = true,quickMode = false,diff --git a/apps/web/src/bridges/motion-tracking-bridge.ts b/apps/web/src/bridges/motion-tracking-bridge.tsindex 1d745d30..3bfdc951 100644--- a/apps/web/src/bridges/motion-tracking-bridge.ts+++ b/apps/web/src/bridges/motion-tracking-bridge.ts@@ -13,6 +13,7 @@ import {import { createMotionTrackingSource } from "../services/motion-tracking-source";import { createWorkerTrackStepper } from "../services/motion-track-stepper";import { persistMotionTrackingAnalysis, readMotionTrackingAnalysis, applyMotionTracking, removeMotionTracking, type MotionTrackingApplyOptions } from "../services/motion-tracking-edit";+import { backgroundTasks } from "@openreel/core/tasks/task-registry";import { useProjectStore } from "../stores/project-store";export interface MotionTrackingRunOptions extends TrackingOptions {@@ -71,8 +72,40 @@ class MotionTrackingBridge {if (this.active && !this.active.controller.signal.aborted) this.pendingLostFrames.push(frameIndex);};+ private taskId: string | null = null;+ private taskClipId: string | null = null;+ private taskTitle = "Motion tracking";++ /** Mirror the run into the unified background-task registry (cancel forwards to cancelTracking). */+ private reportTask(): void {+ const state = this.currentState;+ if (state.isTracking) {+ if (!this.taskId) {+ this.taskId = `tracking:${Date.now()}`;+ const clipId = this.taskClipId;+ const project = useProjectStore.getState();+ const clip = clipId ? project.getClip(clipId) : undefined;+ const media = clip ? project.getMediaItem(clip.mediaId) : undefined;+ this.taskTitle = media ? `Tracking \u00b7 ${media.name}` : "Motion tracking";+ }+ backgroundTasks.upsert(+ { id: this.taskId, kind: "tracking", source: "tracking", title: this.taskTitle, detail: state.lostFrames.length ? `${state.lostFrames.length} frames lost` : "Following the selected region", status: "running", progress: state.progress / 100 },+ { cancel: () => this.cancelTracking() },+ );+ } else if (this.taskId) {+ const id = this.taskId;+ this.taskId = null;+ backgroundTasks.upsert(+ state.error+ ? { id, kind: "tracking", source: "tracking", title: this.taskTitle, status: "failed", error: state.error }+ : { id, kind: "tracking", source: "tracking", title: this.taskTitle, status: state.trackingData ? "completed" : "cancelled", progress: state.trackingData ? 1 : null },+ );+ }+ }+private updateState(partial: Partial<MotionTrackingState>): void {this.currentState = { ...this.currentState, ...partial };+ this.reportTask();this.notifyListeners();}@@ -117,6 +150,7 @@ class MotionTrackingBridge {const active: { controller: AbortController; source: ReturnType<typeof createMotionTrackingSource>; job?: TrackingJob } = { controller, source };this.active = active;this.lastProgressAt = 0; this.pendingLostFrames = [];+ this.taskClipId = clipId;this.updateState({ isTracking: true, progress: 0, lostFrames: [], error: null, trackingData: null, currentJob: null });try {const job = await this.engine.startTracking(clipId, source.region, {diff --git a/apps/web/src/bridges/planar-track-bridge.ts b/apps/web/src/bridges/planar-track-bridge.tsnew file mode 100644index 00000000..a1d70815--- /dev/null+++ b/apps/web/src/bridges/planar-track-bridge.ts@@ -0,0 +1,78 @@+import { correctPlanarFrame, mergePlanarTrack, trackPlanarSurface, type PlanarTrackData } from "@openreel/core";+import { createMotionTrackingSource } from "../services/motion-tracking-source";+import { createWorkerPlanarStepper } from "../services/planar-track-stepper";+import { persistPlanarTrackAnalysis, readPlanarTrackAnalysis } from "../services/planar-track-edit";+import { useProjectStore } from "../stores/project-store";++export type PlanarTrackRange = "clip" | "forward" | "backward";+export interface PlanarTrackState { isTracking: boolean; progress: number; lostFrames: number; error: string | null; clipId: string | null }+export interface PlanarTrackRun { clipId: string; /** Source pixels, TL TR BR BL, defined at `anchorFrame`. */ corners: number[]; anchorFrame: number; range: PlanarTrackRange; confidenceThreshold?: number; merge?: boolean }++type Listener = (state: PlanarTrackState) => void;+const IDLE: PlanarTrackState = { isTracking: false, progress: 0, lostFrames: 0, error: null, clipId: null };++class PlanarTrackBridge {+ private state: PlanarTrackState = IDLE;+ private listeners = new Set<Listener>();+ private active: AbortController | null = null;++ subscribe(listener: Listener): () => void { this.listeners.add(listener); listener(this.state); return () => this.listeners.delete(listener); }+ getState(): PlanarTrackState { return this.state; }+ private update(partial: Partial<PlanarTrackState>): void { this.state = { ...this.state, ...partial }; for (const l of this.listeners) l(this.state); }++ /** Track and save the path on the clip (one undo step). Resolves with the saved data; rejects on failure or cancel. */+ async track(run: PlanarTrackRun): Promise<PlanarTrackData> {+ if (this.active) throw new Error("The previous tracking job is still finishing");+ const controller = new AbortController();+ this.active = controller;+ this.update({ isTracking: true, progress: 0, lostFrames: 0, error: null, clipId: run.clipId });+ const xs = run.corners.filter((_, i) => i % 2 === 0), ys = run.corners.filter((_, i) => i % 2 === 1);+ const bounds = { x: Math.min(...xs), y: Math.min(...ys), width: Math.max(...xs) - Math.min(...xs), height: Math.max(...ys) - Math.min(...ys) };+ let source: ReturnType<typeof createMotionTrackingSource> | null = null;+ try {+ source = createMotionTrackingSource(run.clipId, bounds, controller.signal);+ const anchor = Math.max(0, Math.min(source.lastFrame, Math.round(run.anchorFrame)));+ const legs: Array<"forward" | "backward"> = run.range === "clip" ? ["backward", "forward"] : [run.range];+ let result: PlanarTrackData | null = null, lost = 0;+ for (const [index, direction] of legs.entries()) {+ const base = index / legs.length * 100;+ const leg = await trackPlanarSurface({+ clipId: run.clipId, frameRate: source.frameRate, anchorFrame: anchor, direction, corners: run.corners, confidenceThreshold: run.confidenceThreshold,+ startFrame: direction === "backward" ? 0 : anchor, endFrame: direction === "backward" ? anchor : source.lastFrame,+ readFrame: source.readFrame, createStepper: createWorkerPlanarStepper, signal: controller.signal,+ onProgress: (percent, lostFrames) => this.update({ progress: base + percent / legs.length, lostFrames: lost + lostFrames }),+ });+ lost += leg.lostFrames.length;+ result = result ? mergePlanarTrack(result, leg) : leg;+ }+ if (!result) throw new Error("Tracking did not produce a path");+ source.assertCurrent();+ const previous = run.merge ? readPlanarTrackAnalysis(run.clipId)?.data ?? null : null;+ const data = run.merge ? mergePlanarTrack(previous, result) : result;+ await persistPlanarTrackAnalysis(source.projectId, { version: 1, signature: source.signature, data }, controller.signal, run.merge ? "Re-track planar surface" : "Track planar surface");+ this.update({ isTracking: false, progress: 100, lostFrames: data.lostFrames.length });+ return data;+ } catch (error) {+ const cancelled = controller.signal.aborted || (error instanceof DOMException && error.name === "AbortError");+ this.update({ isTracking: false, progress: 0, error: cancelled ? null : error instanceof Error ? error.message : "Tracking failed" });+ throw cancelled ? new Error("Tracking was cancelled") : error;+ } finally {+ source?.dispose();+ this.active = null;+ }+ }++ cancel(): void { this.active?.abort(); }++ /** Set the four corners at one frame by hand. One undo step; every pinned clip follows. */+ async correctFrame(clipId: string, frame: number, corners: number[]): Promise<PlanarTrackData> {+ const saved = readPlanarTrackAnalysis(clipId);+ if (!saved) throw new Error("Track the clip before editing corners");+ const data = correctPlanarFrame(saved.data, frame, corners);+ await persistPlanarTrackAnalysis(useProjectStore.getState().project.id, { ...saved, data }, undefined, "Edit planar corners");+ return data;+ }+}++let instance: PlanarTrackBridge | null = null;+export function getPlanarTrackBridge(): PlanarTrackBridge { return instance ??= new PlanarTrackBridge(); }diff --git a/apps/web/src/bridges/playback-bridge.ts b/apps/web/src/bridges/playback-bridge.tsindex d23bac86..7779e44c 100644--- a/apps/web/src/bridges/playback-bridge.ts+++ b/apps/web/src/bridges/playback-bridge.ts@@ -1,3 +1,4 @@+import { isTrackAudible } from "@openreel/core";import type { PlaybackController, PlaybackEvent } from "@openreel/core";import { useTimelineStore, type PlaybackState } from "../stores/timeline-store";import { useEngineStore } from "../stores/engine-store";@@ -393,20 +394,11 @@ export class PlaybackBridge {* @returns true if the track should be audible*/isTrackAudible(- track: { muted: boolean; solo: boolean },+ track: { muted: boolean; solo: boolean; soloSafe?: boolean },hasSoloTracks: boolean,): boolean {- // If track is explicitly muted, it's not audible (Requirement 2.5)- if (track.muted) {- return false;- }-- // If any track has solo enabled, only soloed tracks are audible (Requirement 2.6)- if (hasSoloTracks && !track.solo) {- return false;- }-- return true;+ // Muted never plays (Requirement 2.5); while anything is soloed only soloed or solo-safe tracks do (Requirement 2.6).+ return isTrackAudible(track, hasSoloTracks);}/**@@ -421,7 +413,7 @@ export class PlaybackBridge {* @returns Array of TrackAudibility objects*/getTrackAudibility(- tracks: Array<{ id: string; muted: boolean; solo: boolean }>,+ tracks: Array<{ id: string; muted: boolean; solo: boolean; soloSafe?: boolean }>,): TrackAudibility[] {const hasSoloTracks = tracks.some((t) => t.solo);diff --git a/apps/web/src/bridges/render-bridge.ts b/apps/web/src/bridges/render-bridge.tsindex 9c1e77d8..e43c9371 100644--- a/apps/web/src/bridges/render-bridge.ts+++ b/apps/web/src/bridges/render-bridge.ts@@ -11,6 +11,7 @@ import {getVideoEffectsEngine,TransitionEngine,createTransitionEngine,+ createBurnInSource,getAnimatedVideoEffects,} from "@openreel/core";import { useEngineStore } from "../stores/engine-store";@@ -344,7 +345,7 @@ export class RenderBridge {const localTime =clipLocalTime ??Math.max(0, useTimelineStore.getState().playheadPosition - clip.startTime);- const effects = getAnimatedVideoEffects(clip, localTime);+ const effects = getAnimatedVideoEffects(clip, localTime, createBurnInSource(project));if (effects.length === 0) return frame;return this.applyEffects(frame, effects);}diff --git a/apps/web/src/components/audio-mixer/AudioMixer.test.tsx b/apps/web/src/components/audio-mixer/AudioMixer.test.tsxindex 8e7d6acd..bb9b90ba 100644--- a/apps/web/src/components/audio-mixer/AudioMixer.test.tsx+++ b/apps/web/src/components/audio-mixer/AudioMixer.test.tsx@@ -290,6 +290,36 @@ describe("direct shadcn mixer controls", () => {});});+describe("solo safe", () => {+ it("keeps a solo-safe strip live while another track is soloed, as one undo step", async () => {+ render(<AudioMixer />);+ await act(async () => {+ fireEvent.click(screen.getByRole("button", { name: "Solo Safe Camera" }));+ });+ expect(state().project.timeline.tracks[1].soloSafe).toBe(true);+ expect(screen.getByRole("button", { name: "Solo Safe Camera" })).toHaveAttribute("aria-pressed", "true");+ await act(async () => {+ fireEvent.click(screen.getByRole("button", { name: "Solo Voice" }));+ });+ // The silent third track is silenced by the solo; the solo-safe Camera keeps playing.+ expect(screen.getByRole("slider", { name: "Camera pan control" })).not.toHaveAttribute("aria-disabled", "true");+ expect(screen.getByRole("button", { name: "Solo Safe Camera" })).toHaveAttribute("aria-pressed", "true");+ await act(async () => {+ await state().undo();+ });+ await act(async () => {+ await state().undo();+ });+ expect(state().project.timeline.tracks[1].soloSafe).toBeUndefined();+ expect(screen.getByRole("button", { name: "Solo Safe Camera" })).toHaveAttribute("aria-pressed", "false");+ });++ it("offers the output device picker in the mixer header", () => {+ render(<AudioMixer />);+ expect(screen.getByTestId("mixer-audio-output-trigger")).toBeInTheDocument();+ });+});+describe("meter lifecycle", () => {it("updates actual sample values and stops every tap and interval on pause", () => {useTimelineStore.setState({ playbackState: "playing" });diff --git a/apps/web/src/components/audio-mixer/AudioMixer.tsx b/apps/web/src/components/audio-mixer/AudioMixer.tsxindex bb2ece75..2a35a519 100644--- a/apps/web/src/components/audio-mixer/AudioMixer.tsx+++ b/apps/web/src/components/audio-mixer/AudioMixer.tsx@@ -46,6 +46,7 @@ import { AudioRackSection } from "./AudioRackSection";import { LoudnessPanel } from "./LoudnessPanel";import { BusStrip } from "./BusStrip";import { commitRoutingPlan } from "./routing-ui";+import { AudioOutputSelect } from "../editor/settings/AudioOutputSelect";import { exportStemsAsDownloads } from "../../services/audio-stems";import { toast } from "../../stores/notification-store";import { createMixerChannelSelector } from "../../services/audio-mixer-channels";@@ -269,6 +270,7 @@ export const AudioMixer: React.FC<AudioMixerProps> = ({pan: trackPans[track.id] ?? 0,muted: track.muted,solo: track.solo,+ soloSafe: track.soloSafe === true,rack: track.audioRack,output: track.output,sends: track.sends,@@ -450,9 +452,9 @@ export const AudioMixer: React.FC<AudioMixerProps> = ({aria-label="Audio Mixing Console">{/* Header */}- <div className="flex items-center justify-between mb-4">- <span className="font-semibold text-lg text-fg">Audio Mixer</span>- <div className="ml-3 flex items-center gap-1.5" data-testid="mixer-channel-layout-group">+ <div className="mb-4 flex flex-wrap items-center gap-y-2">+ <span className="whitespace-nowrap text-lg font-semibold text-fg">Audio Mixer</span>+ <div className="ml-3 flex shrink-0 items-center gap-1.5" data-testid="mixer-channel-layout-group"><span className="text-xs text-fg-muted" id="mixer-channel-layout-label">Sequence audio</span><Select value={channelLayout} onValueChange={(next) => void setSequenceChannelLayout(next as ChannelLayout)}><SelectTrigger className="h-7 w-[140px] text-xs" aria-labelledby="mixer-channel-layout-label" data-testid="mixer-channel-layout">@@ -467,6 +469,10 @@ export const AudioMixer: React.FC<AudioMixerProps> = ({</SelectContent></Select></div>+ <div className="ml-3 flex shrink-0 items-center gap-1.5" data-testid="mixer-output-device-group">+ <span className="text-xs text-fg-muted">Output</span>+ <AudioOutputSelect compact testId="mixer-audio-output" />+ </div><div className="ml-auto mr-2 flex flex-wrap items-center justify-end gap-1.5" data-testid="mixer-routing-actions"><Button type="button" variant="outline" size="sm" className="h-7 gap-1 px-2 text-xs" onClick={addBus} data-testid="add-bus"><Plus size={12} aria-hidden />diff --git a/apps/web/src/components/audio-mixer/ChannelStrip.tsx b/apps/web/src/components/audio-mixer/ChannelStrip.tsxindex f8ae7d9c..d7227651 100644--- a/apps/web/src/components/audio-mixer/ChannelStrip.tsx+++ b/apps/web/src/components/audio-mixer/ChannelStrip.tsx@@ -4,7 +4,8 @@ import { volumeToDb, formatDb, formatPan } from "./types";import { Button, Slider, cn } from "@openreel/ui";import { Film, Music } from "@/icons/lucide-compat";-import { resolveSurroundPan, type AudioBus } from "@openreel/core";+import { isTrackSoloSuppressed, resolveSurroundPan, type AudioBus } from "@openreel/core";+import { useProjectStore } from "../../stores/project-store";import { SurroundPanner } from "./SurroundPanner";import { setSurroundPan } from "../../services/surround-audio";import { MixerLevelMeters } from "./MixerLevelMeters";@@ -147,13 +148,15 @@ export const ChannelStrip = memo(onSoloToggle(channel.trackId);}, [channel.trackId, onSoloToggle]);- // Determine if this channel is effectively muted- // (either explicitly muted, or not soloed when other tracks are soloed)- const isEffectivelyMuted = useMemo(() => {- if (channel.muted) return true;- if (hasSoloedTracks && !channel.solo) return true;- return false;- }, [channel.muted, channel.solo, hasSoloedTracks]);+ const handleSoloSafeClick = useCallback(() => {+ void useProjectStore.getState().setTrackSoloSafe(channel.trackId, channel.soloSafe !== true);+ }, [channel.trackId, channel.soloSafe]);++ // Effectively muted: explicitly muted, or silenced by another track's solo (solo-safe tracks are exempt).+ const isEffectivelyMuted = useMemo(+ () => channel.muted || isTrackSoloSuppressed(channel, hasSoloedTracks),+ [channel.muted, channel.solo, channel.soloSafe, hasSoloedTracks], // eslint-disable-line react-hooks/exhaustive-deps+ );// Track type iconconst TrackTypeIcon = channel.trackType === "audio" ? Music : Film;@@ -262,6 +265,26 @@ export const ChannelStrip = memo(><span className="truncate">{"S"}</span></Button>++ {/* Solo Safe: keeps this track playing while other tracks are soloed */}+ <Button+ aria-label={`Solo Safe ${channel.trackName}`}+ aria-pressed={channel.soloSafe === true}+ title={channel.soloSafe === true ? "Solo Safe on: this track keeps playing while other tracks are soloed" : "Solo Safe: keep this track playing while other tracks are soloed"}+ data-testid={`solo-safe-${channel.trackId}`}+ onClick={handleSoloSafeClick}+ type="button"+ variant="outline"+ size="sm"+ className={cn(+ "h-7 rounded px-1.5 text-[10px] font-bold",+ channel.soloSafe === true+ ? "bg-accent text-bg hover:bg-accent/90"+ : "bg-border-strong text-fg-muted hover:bg-hover",+ )}+ >+ <span className="truncate">{"SF"}</span>+ </Button></div></div>);@@ -277,6 +300,7 @@ export const ChannelStrip = memo(a.pan === b.pan &&a.muted === b.muted &&a.solo === b.solo &&+ a.soloSafe === b.soloSafe &&a.levels === b.levels &&a.rack === b.rack &&a.output === b.output &&diff --git a/apps/web/src/components/audio-mixer/types.ts b/apps/web/src/components/audio-mixer/types.tsindex 7089677c..422fa4bf 100644--- a/apps/web/src/components/audio-mixer/types.ts+++ b/apps/web/src/components/audio-mixer/types.ts@@ -12,6 +12,8 @@ export interface ChannelStripState {readonly pan: number; // -1 (left) to 1 (right)readonly muted: boolean;readonly solo: boolean;+ /** Solo Safe: stays audible while other tracks are soloed. */+ readonly soloSafe?: boolean;readonly levels: StereoSignalLevels;readonly rack?: AudioRack;/** Output assignment: a bus id, absent = master. */diff --git a/apps/web/src/components/editor/AssetsPanel.tsx b/apps/web/src/components/editor/AssetsPanel.tsxindex 634f81df..d99309f8 100644--- a/apps/web/src/components/editor/AssetsPanel.tsx+++ b/apps/web/src/components/editor/AssetsPanel.tsx@@ -34,10 +34,6 @@ import { RAW_FILE_ACCEPT, groupCinemaDng, interpretedDisplaySize, type MediaItemimport { enqueueImportBatch, takeNextImportBatch, type PendingImportBatch } from "../../services/import-batch-queue";import { importCinemaDngSequence, looksLikeCinemaDngFrame } from "../../services/cinemadng-sequence";import { AspectRatioMatchDialog } from "./dialogs/AspectRatioMatchDialog";-import { WorkspaceGeneratePanel } from "./WorkspaceGeneratePanel";-import { WorkspaceRecipesPanel } from "./panels/WorkspaceRecipesPanel";-import { MarkersPanel } from "./MarkersPanel";-import { CommentsPanel } from "./CommentsPanel";import { VersionsPanel } from "./VersionsPanel";import { TemplatesTab } from "./panels/TemplatesTab";import {@@ -67,6 +63,12 @@ import { ProjectPanelBar, ProjectPanelDialogs, useMediaSelectionCount } from "./import { writeMediaDrag } from "./project-panel/dnd";import { Scissors } from "@/icons/lucide-compat";+const panelFallback = <div className="h-full" role="status" aria-label="Loading panel" />;+const WorkspaceGeneratePanel = React.lazy(() => import("./WorkspaceGeneratePanel").then((m) => ({ default: m.WorkspaceGeneratePanel })));+const WorkspaceRecipesPanel = React.lazy(() => import("./panels/WorkspaceRecipesPanel").then((m) => ({ default: m.WorkspaceRecipesPanel })));+const MarkersPanel = React.lazy(() => import("./MarkersPanel").then((m) => ({ default: m.MarkersPanel })));+const CommentsPanel = React.lazy(() => import("./CommentsPanel").then((m) => ({ default: m.CommentsPanel })));+const formatDuration = (seconds: number): string => {const mins = Math.floor(seconds / 60);const secs = Math.floor(seconds % 60);@@ -1491,25 +1493,25 @@ export const AssetsPanel: React.FC = () => {case "ai":return (<div className="flex min-h-0 flex-1 flex-col bg-background-secondary content-area-fix">- <WorkspaceGeneratePanel />+ <React.Suspense fallback={panelFallback}><WorkspaceGeneratePanel /></React.Suspense></div>);case "recipes":return (<div className="flex min-h-0 flex-1 flex-col bg-background-secondary content-area-fix">- <WorkspaceRecipesPanel key={projectId} />+ <React.Suspense fallback={panelFallback}><WorkspaceRecipesPanel key={projectId} /></React.Suspense></div>);case "markers":return (<div className="flex min-h-0 flex-1 flex-col bg-background-secondary content-area-fix">- <MarkersPanel />+ <React.Suspense fallback={panelFallback}><MarkersPanel /></React.Suspense></div>);case "comments":return (<div className="flex min-h-0 flex-1 flex-col bg-background-secondary content-area-fix">- <CommentsPanel />+ <React.Suspense fallback={panelFallback}><CommentsPanel /></React.Suspense></div>);case "versions":diff --git a/apps/web/src/components/editor/AudioChannelsDialog.tsx b/apps/web/src/components/editor/AudioChannelsDialog.tsxnew file mode 100644index 00000000..ce60ae29--- /dev/null+++ b/apps/web/src/components/editor/AudioChannelsDialog.tsx@@ -0,0 +1,213 @@+import { useEffect, useMemo, useState } from "react";+import { Button, Dialog, DialogContent, DialogDescription, DialogFooter, DialogHeader, DialogTitle, ToggleGroup, ToggleGroupItem, cn } from "@openreel/ui";+import {+ CHANNEL_PRESETS,+ CHANNEL_PRESET_LABELS,+ CLIP_CHANNEL_FORMATS,+ FORMAT_CHANNEL_COUNT,+ FORMAT_CHANNEL_NAMES,+ MIX_CHANNELS,+ SILENT_CHANNEL,+ channelMatrix,+ fileChannelFormat,+ identityChannelMap,+ isIdentityChannelMap,+ matchChannelPreset,+ presetChannelMap,+ resolveClipChannelMap,+ sameChannelMap,+ type ChannelPreset,+ type ClipChannelFormat,+ type ClipChannelMap,+} from "@openreel/core";+import { useProjectStore } from "../../stores/project-store";+import { useAudioChannelsStore } from "../../stores/audio-channels-store";+import { canSplitToMono, setClipChannelMap, splitClipToMono } from "../../services/audio-channels";+import { toast } from "../../stores/notification-store";++const SOURCE_NAMES: Record<ClipChannelFormat, readonly string[]> = FORMAT_CHANNEL_NAMES;++/** Names a source channel: L/R for stereo files, the 5.1 names for 6-channel files, otherwise "Ch n". */+function sourceChannelName(index: number, sourceChannels: number): string {+ if (sourceChannels === 1) return "Mono";+ const names = SOURCE_NAMES[fileChannelFormat(sourceChannels)];+ return names[index] ?? `Ch ${index + 1}`;+}++/** Re-targets a map to another format, keeping what the old outputs played where the new format has the same slots. */+function withFormat(map: ClipChannelMap, format: ClipChannelFormat, sourceChannels: number): ClipChannelMap {+ if (map.format === format) return map;+ const count = FORMAT_CHANNEL_COUNT[format];+ const fallback = identityChannelMap(sourceChannels).sources;+ const sources = Array.from({ length: count }, (_, index) => {+ if (map.sources[index] !== undefined) return map.sources[index];+ if (format === "mono") return 0;+ return fallback[index] !== undefined ? fallback[index] : SILENT_CHANNEL;+ });+ return { format, sources };+}++/**+ * Modify > Audio Channels. Maps the source file's channels onto the clip's channels (mono, stereo, 5.1) for one+ * clip or a whole selection; the quick buttons cover the common jobs (left only, right only, swap) and Split to+ * mono clips turns a stereo interview into two mono clips. Nothing is applied until Apply (one undo step).+ */+export function AudioChannelsDialog() {+ const open = useAudioChannelsStore((state) => state.open);+ const clipIds = useAudioChannelsStore((state) => state.clipIds);+ const close = useAudioChannelsStore((state) => state.close);+ const project = useProjectStore((state) => state.project);++ const targets = useMemo(() => {+ const clips = project.timeline.tracks.flatMap((track) => track.clips);+ return clipIds.flatMap((id) => {+ const clip = clips.find((candidate) => candidate.id === id);+ const media = clip && project.mediaLibrary.items.find((item) => item.id === clip.mediaId);+ return clip && media ? [{ clip, media }] : [];+ });+ }, [clipIds, project]);++ const sourceChannels = Math.max(1, ...targets.map(({ media }) => media.metadata.channels || 2));+ const first = targets[0];+ const initial = useMemo<ClipChannelMap>(+ () => (first ? resolveClipChannelMap(first.clip, first.media) ?? identityChannelMap(first.media.metadata.channels || 2) : identityChannelMap(2)),+ // Re-seed only when the dialog opens for a different selection, not on every unrelated project change.+ // eslint-disable-next-line react-hooks/exhaustive-deps+ [open, clipIds],+ );+ const [draft, setDraft] = useState<ClipChannelMap>(initial);+ const [busy, setBusy] = useState(false);+ useEffect(() => { if (open) setDraft(initial); }, [open, initial]);++ const mixedStarts = targets.some(({ clip, media }) => !sameChannelMap(resolveClipChannelMap(clip, media) ?? identityChannelMap(media.metadata.channels || 2), initial));+ // For a stereo file "Use file" and "Stereo" are the same map, so the preset the user picked stays shown while it still matches.+ const [picked, setPicked] = useState<ChannelPreset | null>(null);+ useEffect(() => { if (open) setPicked(null); }, [open, clipIds]);+ const pickedMap = picked ? (picked === "file" ? identityChannelMap(sourceChannels) : presetChannelMap(picked, sourceChannels)) : undefined;+ const preset = picked && sameChannelMap(pickedMap, draft) ? picked : matchChannelPreset(draft, sourceChannels);+ const matrix = channelMatrix(draft, sourceChannels);+ const outputNames = FORMAT_CHANNEL_NAMES[draft.format];+ const canSplit = targets.length === 1 && canSplitToMono(project, targets[0].clip.id);+ const changed = mixedStarts || !sameChannelMap(draft, initial);++ const setOutput = (output: number, source: number) =>+ setDraft((map) => ({ ...map, sources: map.sources.map((entry, index) => (index === output ? source : entry)) }));+ const applyPreset = (name: ChannelPreset) => {+ setPicked(name);+ setDraft(name === "file" ? identityChannelMap(sourceChannels) : presetChannelMap(name, sourceChannels) ?? identityChannelMap(sourceChannels));+ };++ const apply = async () => {+ setBusy(true);+ try {+ // The file's own layout is stored as "no map" unless one of the clips' files has an import default that must be overridden.+ const overridesPreset = targets.some(({ media }) => media.channelPreset && media.channelPreset !== "file");+ const map = isIdentityChannelMap(draft, sourceChannels) && !overridesPreset ? null : draft;+ const result = await setClipChannelMap(targets.map(({ clip }) => clip.id), map);+ if (result.success) close();+ else toast.error("Audio channels not changed", result.error?.message ?? "The clips could not be updated.");+ } finally {+ setBusy(false);+ }+ };+ const split = async () => {+ if (!first) return;+ setBusy(true);+ try {+ const result = await splitClipToMono(first.clip.id);+ if (result.success) close();+ else toast.error("Could not split to mono", result.error?.message ?? "The clip could not be split.");+ } finally {+ setBusy(false);+ }+ };++ const title = targets.length === 1 ? first.media.name : `${targets.length} clips`;+ const columns: { key: number; label: string }[] = [+ ...Array.from({ length: sourceChannels }, (_, index) => ({ key: index, label: sourceChannelName(index, sourceChannels) })),+ { key: MIX_CHANNELS, label: "Mix" },+ { key: SILENT_CHANNEL, label: "Off" },+ ];++ return (+ <Dialog open={open} onOpenChange={(next) => { if (!next) close(); }}>+ <DialogContent className="w-[calc(100vw-32px)] max-w-lg gap-4" data-testid="audio-channels-dialog">+ <DialogHeader>+ <DialogTitle>Modify clip: Audio channels</DialogTitle>+ <DialogDescription className="truncate">{title}{targets.length === 1 ? ` · ${sourceChannels}-channel source` : ` · up to ${sourceChannels} source channels`}</DialogDescription>+ </DialogHeader>++ <div className="space-y-1.5">+ <div className="text-xs font-medium text-fg-2" id="audio-channels-preset-label">Preset</div>+ <ToggleGroup type="single" value={preset ?? ""} onValueChange={(value) => { if (value) applyPreset(value as ChannelPreset); }} aria-labelledby="audio-channels-preset-label" className="justify-start">+ {CHANNEL_PRESETS.map((name) => (+ <ToggleGroupItem key={name} value={name} data-testid={`audio-channels-preset-${name}`} className="h-8 px-3 text-xs">{CHANNEL_PRESET_LABELS[name]}</ToggleGroupItem>+ ))}+ </ToggleGroup>+ {preset === null && <p className="text-[11px] text-fg-muted" data-testid="audio-channels-custom">Custom mapping</p>}+ </div>++ <div className="space-y-1.5">+ <div className="text-xs font-medium text-fg-2" id="audio-channels-format-label">Clip channel format</div>+ <ToggleGroup type="single" value={draft.format} onValueChange={(value) => { if (value) setDraft((map) => withFormat(map, value as ClipChannelFormat, sourceChannels)); }} aria-labelledby="audio-channels-format-label" className="justify-start">+ {CLIP_CHANNEL_FORMATS.map((format) => (+ <ToggleGroupItem key={format} value={format} data-testid={`audio-channels-format-${format}`} className="h-8 px-3 text-xs">{format === "mono" ? "Mono" : format === "stereo" ? "Stereo" : "5.1"}</ToggleGroupItem>+ ))}+ </ToggleGroup>+ </div>++ <div className="space-y-1.5">+ <div className="flex items-center justify-between">+ <div className="text-xs font-medium text-fg-2">Source channel for each clip channel</div>+ {sourceChannels >= 2 && draft.format !== "5.1" && (+ <div className="flex gap-1">+ <Button type="button" variant="outline" size="sm" className="h-7 px-2 text-[11px]" data-testid="audio-channels-left-only" onClick={() => setDraft({ format: "mono", sources: [0] })}>Left only</Button>+ <Button type="button" variant="outline" size="sm" className="h-7 px-2 text-[11px]" data-testid="audio-channels-right-only" onClick={() => setDraft({ format: "mono", sources: [1] })}>Right only</Button>+ <Button type="button" variant="outline" size="sm" className="h-7 px-2 text-[11px]" data-testid="audio-channels-swap" onClick={() => setDraft({ format: "stereo", sources: [1, 0] })}>Swap L/R</Button>+ </div>+ )}+ </div>+ <div role="grid" aria-label="Channel mapping" className="overflow-x-auto rounded-md border border-border bg-bg-2" data-testid="audio-channels-grid">+ <div role="row" className="grid items-center border-b border-border text-[10px] uppercase tracking-wide text-fg-muted" style={{ gridTemplateColumns: `minmax(64px,auto) repeat(${columns.length}, minmax(34px,1fr))` }}>+ <div role="columnheader" className="px-2 py-1.5">Clip</div>+ {columns.map((column) => <div key={column.key} role="columnheader" className="px-1 py-1.5 text-center">{column.label}</div>)}+ </div>+ {draft.sources.map((entry, output) => (+ <div key={output} role="row" className="grid items-center border-b border-border last:border-b-0" style={{ gridTemplateColumns: `minmax(64px,auto) repeat(${columns.length}, minmax(34px,1fr))` }} data-testid={`audio-channels-row-${output}`}>+ <div role="rowheader" className="px-2 py-1.5 text-xs font-medium">{outputNames[output]}</div>+ {columns.map((column) => {+ const selected = entry === column.key;+ return (+ <div key={column.key} role="gridcell" className="flex justify-center py-1">+ <button+ type="button"+ role="radio"+ aria-checked={selected}+ aria-label={`${outputNames[output]} plays ${column.key === MIX_CHANNELS ? "a mix of all source channels" : column.key === SILENT_CHANNEL ? "nothing" : `source ${column.label}`}`}+ data-testid={`audio-channels-cell-${output}-${column.key === MIX_CHANNELS ? "mix" : column.key === SILENT_CHANNEL ? "off" : column.key}`}+ onClick={() => setOutput(output, column.key)}+ className={cn("h-5 w-5 rounded-full border transition-colors focus-visible:outline focus-visible:outline-2 focus-visible:outline-primary", selected ? "border-primary bg-primary" : "border-border bg-transparent hover:border-fg-2")}+ />+ </div>+ );+ })}+ </div>+ ))}+ </div>+ <p className="text-[11px] text-fg-muted" data-testid="audio-channels-summary">+ {matrix.map((row, index) => `${outputNames[index]}: ${row.every((gain) => gain === 0) ? "silent" : row.every((gain) => gain === row[0]) && row.length > 1 ? "mix of all channels" : row.map((gain, source) => (gain > 0 ? sourceChannelName(source, sourceChannels) : null)).filter(Boolean).join(" + ")}`).join(" · ")}+ </p>+ {draft.format === "5.1" && sourceChannels < 6 && <p className="text-[11px] text-fg-muted">This source has {sourceChannels} channel{sourceChannels === 1 ? "" : "s"}; the other 5.1 channels stay silent.</p>}+ </div>++ <DialogFooter className="flex-col gap-2 sm:flex-row sm:items-center sm:justify-between">+ {canSplit ? <Button type="button" variant="outline" size="sm" disabled={busy} data-testid="audio-channels-split" onClick={() => { void split(); }}>Split to mono clips</Button> : <span />}+ <div className="flex gap-2">+ <Button type="button" variant="ghost" size="sm" onClick={close}>Cancel</Button>+ <Button type="button" size="sm" disabled={busy || !changed || targets.length === 0} data-testid="audio-channels-apply" onClick={() => { void apply(); }}>Apply</Button>+ </div>+ </DialogFooter>+ </DialogContent>+ </Dialog>+ );+}diff --git a/apps/web/src/components/editor/BackgroundTasksPanel.tsx b/apps/web/src/components/editor/BackgroundTasksPanel.tsxnew file mode 100644index 00000000..e419c0a6--- /dev/null+++ b/apps/web/src/components/editor/BackgroundTasksPanel.tsx@@ -0,0 +1,135 @@+import React, { useEffect, useSyncExternalStore } from "react";+import { Button, Popover, PopoverContent, PopoverTrigger, cn } from "@openreel/ui";+import { Activity, AlertTriangle, Check, RotateCcw, Trash2, X } from "@/icons/lucide-compat";+import {+ backgroundTasks,+ formatTaskEta,+ isActiveStatus,+ summarizeTasks,+ type BackgroundTaskKind,+ type BackgroundTaskView,+} from "@openreel/core/tasks/task-registry";+import { startBackgroundTaskSources } from "../../services/background-task-sources";++const KIND_LABEL: Record<BackgroundTaskKind, string> = {+ export: "Export",+ proxy: "Proxy",+ transcription: "Transcription",+ import: "Import",+ analysis: "Analysis",+ tracking: "Tracking",+ other: "Task",+};++const useTasks = (): readonly BackgroundTaskView[] =>+ useSyncExternalStore(backgroundTasks.subscribe, backgroundTasks.getSnapshot, backgroundTasks.getSnapshot);++function TaskRow({ task }: { task: BackgroundTaskView }) {+ const active = isActiveStatus(task.status);+ const percent = task.progress === null ? null : Math.round(task.progress * 100);+ const eta = task.status === "running" ? formatTaskEta(task.etaMs) : "";+ return (+ <li className="border-b border-border px-3 py-2 last:border-b-0" data-testid="background-task-row" data-task-id={task.id} data-status={task.status}>+ <div className="flex items-center gap-2">+ <span className="shrink-0 rounded bg-bg-3 px-1 text-xs font-semibold uppercase tracking-wide text-fg-muted">{KIND_LABEL[task.kind]}</span>+ <span className="min-w-0 flex-1 truncate text-xs text-fg-1" title={task.title}>{task.title}</span>+ {task.status === "completed" && <Check size={13} className="shrink-0 text-status-success" aria-label="Completed" />}+ {task.status === "failed" && <AlertTriangle size={13} className="shrink-0 text-status-error" aria-label="Failed" />}+ {task.can.cancel && (+ <Button type="button" variant="ghost" size="icon" className="h-6 w-6" aria-label={`Cancel ${task.title}`} onClick={() => backgroundTasks.cancel(task.id)}>+ <X size={13} />+ </Button>+ )}+ {task.can.pause && <Button type="button" variant="ghost" size="sm" className="h-6 px-1.5 text-xs" onClick={() => backgroundTasks.pause(task.id)}>Pause</Button>}+ {task.can.resume && <Button type="button" variant="ghost" size="sm" className="h-6 px-1.5 text-xs" onClick={() => backgroundTasks.resume(task.id)}>Resume</Button>}+ {task.can.retry && (+ <Button type="button" variant="ghost" size="sm" className="h-6 gap-1 px-1.5 text-xs" aria-label={`Retry ${task.title}`} onClick={() => backgroundTasks.retry(task.id)}>+ <RotateCcw size={11} aria-hidden /> Retry+ </Button>+ )}+ </div>+ {active && (+ <div+ className="mt-2 h-2 overflow-hidden rounded-full bg-bg-3 ring-1 ring-inset ring-border"+ role="progressbar"+ aria-label={`${task.title} progress`}+ aria-valuemin={0}+ aria-valuemax={100}+ aria-valuenow={percent ?? undefined}+ >+ <div+ className={cn("h-full rounded-full bg-accent-strong transition-[width]", percent === null && task.status === "running" && "w-1/3 animate-pulse")}+ style={percent === null ? undefined : { width: `${percent}%` }}+ />+ </div>+ )}+ <p className="mt-1 truncate text-xs text-fg-muted">+ {task.status === "failed"+ ? task.error ?? "Failed"+ : task.status === "queued"+ ? "Waiting"+ : task.status === "paused"+ ? task.detail ?? "Paused"+ : task.status === "cancelled"+ ? "Cancelled"+ : task.status === "completed"+ ? "Done"+ : [percent === null ? "Working…" : `${percent}%`, eta && `${eta} left`, task.detail].filter(Boolean).join(" · ")}+ </p>+ </li>+ );+}++/** Status-bar indicator and popover listing every background job (exports, proxies, transcription, imports, analysis, tracking). */+export const BackgroundTasksIndicator: React.FC<{ className?: string }> = ({ className }) => {+ useEffect(() => startBackgroundTaskSources(), []);+ const tasks = useTasks();+ const summary = summarizeTasks(tasks);+ const hasFinished = tasks.some((t) => !isActiveStatus(t.status));+ const busy = summary.active > 0;+ return (+ <Popover>+ <PopoverTrigger asChild>+ <button+ type="button"+ className={cn("relative flex h-full items-center gap-1.5 rounded px-2 text-xs font-medium text-fg-1 transition-colors hover:bg-bg-2 hover:text-fg-1 focus-visible:outline focus-visible:outline-1 focus-visible:outline-accent", className)}+ aria-label={`Background tasks: ${summary.label}`}+ data-testid="background-tasks-button"+ data-active={summary.active}+ >+ <Activity size={14} aria-hidden className={cn(busy && "text-accent")} />+ <span className="truncate" data-testid="background-tasks-badge" data-count={summary.active}>+ {busy || summary.failed > 0 ? summary.label : "Idle"}+ </span>+ {summary.failed > 0 && busy && <span className="h-1.5 w-1.5 rounded-full bg-status-error" aria-hidden />}+ {summary.progress !== null && (+ <span className="h-2 w-20 overflow-hidden rounded-full bg-bg-3 ring-1 ring-inset ring-border" aria-hidden>+ <span className="block h-full rounded-full bg-accent-strong" style={{ width: `${Math.round(summary.progress * 100)}%` }} />+ </span>+ )}+ </button>+ </PopoverTrigger>+ <PopoverContent side="top" align="start" className="w-[400px] max-w-[calc(100vw-24px)] p-0 data-[state=open]:animate-none data-[state=closed]:animate-none" data-testid="background-tasks-panel">+ <header className="flex items-center gap-2 border-b border-border px-3 py-2">+ <div className="min-w-0 flex-1">+ <h2 className="text-xs font-semibold leading-tight text-fg-1">Background tasks</h2>+ <p className="truncate text-xs leading-tight text-fg-muted" data-testid="background-tasks-summary">{summary.label}</p>+ </div>+ <Button type="button" variant="ghost" size="icon" className="h-6 w-6" aria-label="Clear finished tasks" disabled={!hasFinished} onClick={() => backgroundTasks.clearFinished()}>+ <Trash2 size={13} />+ </Button>+ </header>+ {tasks.length === 0 ? (+ <p className="px-3 py-6 text-center text-xs text-fg-muted">Exports, proxies, transcription, imports and analysis show up here while they run.</p>+ ) : (+ <ul className="max-h-[50vh] overflow-y-auto" aria-label="Background tasks">+ {tasks.map((task) => <TaskRow key={task.id} task={task} />)}+ </ul>+ )}+ <p className="border-t border-border px-3 py-2 text-xs text-fg-muted" data-testid="background-tasks-note">+ Cancel works on every running task. Pause is only available for export-queue jobs, and pauses the whole queue; running exports, proxies and analysis cannot be paused.+ </p>+ </PopoverContent>+ </Popover>+ );+};diff --git a/apps/web/src/components/editor/CaptionTranslateSection.tsx b/apps/web/src/components/editor/CaptionTranslateSection.tsxnew file mode 100644index 00000000..3c6777fa--- /dev/null+++ b/apps/web/src/components/editor/CaptionTranslateSection.tsx@@ -0,0 +1,147 @@+import { useEffect, useRef, useState } from "react";+import type { CaptionTranslationProgress } from "@openreel/core";+import { Button, Input, Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@openreel/ui";+import { toast } from "../../stores/notification-store";+import { detectTranslator, languageName, makeTranslator, type TranslatorAvailability } from "../../services/caption-translator";+import { translateCaptionTrackCommand } from "../../services/transcript-commands";++export const TRANSLATION_LANGUAGES = [+ "en", "es", "fr", "de", "it", "pt", "nl", "sv", "pl", "tr", "ru", "uk", "ar", "hi", "bn", "id", "vi", "th", "ja", "ko", "zh", "zh-Hant",+] as const;++interface Props {+ /** Source track id ("" is the default track). */+ trackId: string;+ trackLanguage?: string;+ cueCount: number;+ onTranslated: (trackId: string) => void;+}++/** Translate the active caption track into a new track in another language. */+export function CaptionTranslateSection({ trackId, trackLanguage, cueCount, onTranslated }: Props) {+ const [target, setTarget] = useState("es");+ const [source, setSource] = useState(trackLanguage ?? "");+ const [availability, setAvailability] = useState<TranslatorAvailability | null>(null);+ const [progress, setProgress] = useState<CaptionTranslationProgress | null>(null);+ const [download, setDownload] = useState<number | null>(null);+ const controller = useRef<AbortController | null>(null);+ const running = progress !== null;++ useEffect(() => setSource(trackLanguage ?? ""), [trackLanguage, trackId]);++ useEffect(() => {+ let live = true;+ setAvailability(null);+ void detectTranslator({ sourceLanguage: source.trim() || undefined, targetLanguage: target }).then((a) => {+ if (live) setAvailability(a);+ });+ return () => {+ live = false;+ };+ }, [source, target]);++ useEffect(() => () => controller.current?.abort(), []);++ const start = async () => {+ if (!availability || availability.engine === null) return;+ const abort = new AbortController();+ controller.current = abort;+ setProgress({ done: 0, total: cueCount });+ setDownload(null);+ try {+ const translator = makeTranslator(availability.engine, {+ signal: abort.signal,+ sourceLanguage: source.trim() || undefined,+ onDownloadProgress: setDownload,+ });+ const outcome = await translateCaptionTrackCommand({+ sourceTrackId: trackId,+ targetLanguage: target,+ translator: { translate: (texts, o) => translator.translate(texts, { ...o, sourceLanguage: o.sourceLanguage ?? (source.trim() || undefined) }) },+ signal: abort.signal,+ onProgress: setProgress,+ });+ if (outcome.success && outcome.trackId) {+ toast.success(`Translated ${outcome.added} captions to ${languageName(target)}`, "The translation is kept out of the picture so languages do not overlap. Use Show this track in the picture to display it. Undo removes the new track.");+ onTranslated(outcome.trackId);+ } else if (outcome.cancelled) {+ toast.info("Translation cancelled", "Nothing was added.");+ } else {+ toast.error("Translation failed", outcome.message);+ }+ } catch (error) {+ toast.error("Translation failed", error instanceof Error ? error.message : undefined);+ } finally {+ controller.current = null;+ setProgress(null);+ setDownload(null);+ }+ };++ const unavailable = availability?.state === "unavailable" ? availability.reason : null;+ const pct = progress && progress.total ? Math.round((progress.done / progress.total) * 100) : 0;++ return (+ <section aria-label="Caption translation" className="space-y-1.5 rounded-md border border-border bg-bg-1 p-2">+ <div className="flex items-center gap-1.5 text-[11px] text-fg-2">+ <Input+ aria-label="Source language"+ placeholder="From (en…)"+ value={source}+ disabled={running}+ onChange={(e) => setSource(e.currentTarget.value)}+ onKeyDown={(e) => e.stopPropagation()}+ className="h-7 w-20 shrink-0 text-[11px]"+ />+ <span aria-hidden>→</span>+ <Select value={target} onValueChange={setTarget} disabled={running}>+ <SelectTrigger aria-label="Target language" className="h-7 min-w-0 flex-1 text-[11px]">+ <SelectValue />+ </SelectTrigger>+ <SelectContent>+ {TRANSLATION_LANGUAGES.map((code) => (+ <SelectItem key={code} value={code}>+ {languageName(code)} ({code})+ </SelectItem>+ ))}+ </SelectContent>+ </Select>+ </div>+ {unavailable ? (+ <p role="status" data-testid="translate-unavailable" className="text-[11px] text-fg-3">+ {unavailable}+ </p>+ ) : (+ <p className="text-[10px] text-fg-3" data-testid="translate-engine">+ {availability && availability.state !== "unavailable" ? `Translator: ${availability.engine === "ai" ? "AI model" : "Browser"} · ${availability.label}` : "Checking translators…"}+ </p>+ )}+ {running ? (+ <div className="space-y-1" role="status" aria-live="polite">+ <div className="h-1.5 overflow-hidden rounded-full bg-bg-3" aria-hidden>+ <div className="h-full bg-accent transition-[width]" style={{ width: `${pct}%` }} />+ </div>+ <div className="flex items-center justify-between text-[10px] text-fg-3">+ <span data-testid="translate-progress">+ {download !== null && download < 1+ ? `Downloading language pack ${Math.round(download * 100)}%`+ : `${progress?.done ?? 0} / ${progress?.total ?? 0} captions`}+ </span>+ <Button type="button" variant="ghost" className="h-6 px-2 text-[11px]" onClick={() => controller.current?.abort()}>+ Cancel+ </Button>+ </div>+ </div>+ ) : (+ <Button+ type="button"+ className="h-7 w-full text-[11px]"+ disabled={!availability || availability.engine === null || target === source.trim() || cueCount === 0}+ onClick={() => void start()}+ >+ Translate to {languageName(target)}+ </Button>+ )}+ </section>+ );+}diff --git a/apps/web/src/components/editor/ClipMarkersList.tsx b/apps/web/src/components/editor/ClipMarkersList.tsxnew file mode 100644index 00000000..3fe49703--- /dev/null+++ b/apps/web/src/components/editor/ClipMarkersList.tsx@@ -0,0 +1,122 @@+import { useMemo, useState } from "react";+import { flattenClipMarkers, type Clip, type Marker } from "@openreel/core";+import { Button, Input } from "@openreel/ui";+import { Trash2 } from "@/icons/lucide-compat";+import { useProjectStore } from "../../stores/project-store";+import { useUIStore } from "../../stores/ui-store";+import { formatFrameTimecode } from "../../utils/frame-timecode";+import { removeClipMarker, seekToClipMarker, updateClipMarker } from "../../services/clip-marker-commands";++/**+ * Clip and master-clip markers of the timeline's clips. A master-clip marker (set in the Source+ * monitor) is listed once per timeline instance, each at its own offset; editing it edits the+ * shared marker. Rows of selected clips are highlighted.+ */+export function ClipMarkersList() {+ const tracks = useProjectStore((s) => s.project.timeline.tracks);+ const items = useProjectStore((s) => s.project.mediaLibrary.items);+ const fps = useProjectStore((s) => s.project.settings.frameRate) || 30;+ const selectedItems = useUIStore((s) => s.selectedItems);+ const [editingKey, setEditingKey] = useState<string | null>(null);+ const [name, setName] = useState("");++ const selectedIds = useMemo(+ () => new Set(selectedItems.filter((i) => i.type === "clip").map((i) => i.id)),+ [selectedItems],+ );++ const rows = useMemo(() => {+ const clips: Clip[] = [];+ for (const track of tracks) for (const clip of track.clips) clips.push(clip);+ const byId = new Map(items.map((i) => [i.id, i]));+ const names = new Map(clips.map((c) => [c.id, byId.get(c.mediaId)?.name ?? "Clip"]));+ return flattenClipMarkers(clips, (id) => byId.get(id)).map((r) => ({+ ...r,+ clip: clips.find((c) => c.id === r.clipId)!,+ clipName: names.get(r.clipId) ?? "Clip",+ }));+ }, [tracks, items]);++ const targetOf = (row: (typeof rows)[number]) =>+ row.scope === "master" ? { mediaId: row.clip.mediaId } : { clipId: row.clip.id };++ const commit = (row: (typeof rows)[number]) => {+ const label = name.trim();+ setEditingKey(null);+ if (label && label !== row.marker.label) void updateClipMarker(targetOf(row), row.marker.id, { label } as Partial<Marker>);+ };++ if (rows.length === 0) {+ return (+ <p className="px-4 py-8 text-center text-[12px] text-fg-muted" data-testid="clip-markers-empty">+ No clip markers yet. Press M in the Source monitor to mark the source clip, or Alt+Shift+M on the timeline to mark a clip.+ </p>+ );+ }++ return (+ <ul className="divide-y divide-border/60 text-[12px]" aria-label="Clip marker list" data-testid="clip-marker-list">+ {rows.map((row) => {+ const key = `${row.clipId}:${row.scope}:${row.marker.id}`;+ const editing = editingKey === key;+ return (+ <li+ key={key}+ data-testid="clip-marker-row"+ data-scope={row.scope}+ data-clip-id={row.clipId}+ aria-selected={selectedIds.has(row.clipId)}+ className={`flex cursor-pointer items-center gap-2 px-3 py-1.5 hover:bg-bg-2 ${selectedIds.has(row.clipId) ? "bg-bg-2" : ""}`}+ onClick={() => seekToClipMarker(row.clip, row.marker)}+ onDoubleClick={() => {+ setName(row.marker.label);+ setEditingKey(key);+ }}+ >+ <span className="h-3 w-3 shrink-0 rounded-full border border-border" style={{ backgroundColor: row.marker.color }} />+ <div className="min-w-0 flex-1">+ {editing ? (+ <Input+ autoFocus+ aria-label="Marker name"+ value={name}+ onClick={(event) => event.stopPropagation()}+ onChange={(event) => setName(event.target.value)}+ onBlur={() => commit(row)}+ onKeyDown={(event) => {+ event.stopPropagation();+ if (event.key === "Enter") commit(row);+ if (event.key === "Escape") setEditingKey(null);+ }}+ className="h-6 text-[12px]"+ />+ ) : (+ <div className="truncate font-medium" data-testid="clip-marker-name">+ {row.marker.label || <span className="text-fg-muted">Untitled</span>}+ </div>+ )}+ <div className="truncate text-[11px] text-fg-muted">+ {row.clipName} <span className="uppercase tracking-wide">· {row.scope === "master" ? "Master" : "Clip"}</span>+ </div>+ </div>+ <span className="font-mono text-[11px] text-fg-2" data-testid="clip-marker-time">+ {formatFrameTimecode(row.timelineTime, fps)}+ </span>+ <Button+ variant="ghost"+ size="icon-sm"+ className="h-6 w-6"+ aria-label={`Delete ${row.scope === "master" ? "master clip" : "clip"} marker ${row.marker.label || "Untitled"}`}+ onClick={(event) => {+ event.stopPropagation();+ void removeClipMarker(targetOf(row), row.marker.id);+ }}+ >+ <Trash2 size={12} aria-hidden />+ </Button>+ </li>+ );+ })}+ </ul>+ );+}diff --git a/apps/web/src/components/editor/ClipSpeedDialog.test.tsx b/apps/web/src/components/editor/ClipSpeedDialog.test.tsxnew file mode 100644index 00000000..8bf88710--- /dev/null+++ b/apps/web/src/components/editor/ClipSpeedDialog.test.tsx@@ -0,0 +1,96 @@+// @vitest-environment jsdom+import { describe, it, expect, vi, beforeEach } from "vitest";+import { render, screen, fireEvent, cleanup, act } from "@testing-library/react";++const clip = (id: string, inPoint: number, outPoint: number, duration: number, extra: Record<string, unknown> = {}) => ({+ id,+ inPoint,+ outPoint,+ duration,+ speed: 1,+ ...extra,+});+let selected: ReturnType<typeof clip>[] = [];+const applyClipSpeedEdit = vi.fn((_edit: unknown, _ripple: boolean) => ({ success: true }) as { success: boolean; message?: string });+vi.mock("../../services/clip-speed-multi", () => ({+ selectedSpeedClips: () => selected,+ applyClipSpeedEdit: (edit: unknown, ripple: boolean) => applyClipSpeedEdit(edit, ripple),+}));+const warning = vi.fn();+vi.mock("../../stores/notification-store", () => ({ toast: { warning: (...args: unknown[]) => warning(...args) } }));++const { ClipSpeedDialog } = await import("./ClipSpeedDialog");+const { useClipSpeedDialogStore } = await import("../../stores/clip-speed-dialog-store");++const openDialog = () => {+ render(<ClipSpeedDialog />);+ act(() => useClipSpeedDialogStore.getState().setOpen(true));+};+const ok = () => screen.getByRole("button", { name: "OK" });++beforeEach(() => {+ cleanup();+ vi.clearAllMocks();+ useClipSpeedDialogStore.setState({ open: false });+ selected = [clip("a", 0, 4, 4)];+});++describe("Clip Speed/Duration dialog", () => {+ it("keeps OK disabled until a field changes", () => {+ openDialog();+ expect(ok()).toBeDisabled();+ fireEvent.change(screen.getByLabelText("Speed percent"), { target: { value: "200" } });+ expect(ok()).toBeEnabled();+ });++ it("applies a speed edit with ripple on by default and closes", () => {+ openDialog();+ fireEvent.change(screen.getByLabelText("Speed percent"), { target: { value: "200" } });+ fireEvent.click(ok());+ expect(applyClipSpeedEdit).toHaveBeenCalledWith({ speed: 2 }, true);+ expect(useClipSpeedDialogStore.getState().open).toBe(false);+ });++ it("links duration to speed for a single clip", () => {+ openDialog();+ fireEvent.change(screen.getByLabelText("Duration"), { target: { value: "2" } });+ expect((screen.getByLabelText("Speed percent") as HTMLInputElement).value).toBe("200");+ fireEvent.click(ok());+ expect(applyClipSpeedEdit).toHaveBeenCalledWith({ duration: 2 }, true);+ });++ it("scales the combined length across a multi-selection and can turn ripple off", () => {+ selected = [clip("a", 0, 4, 4), clip("b", 0, 4, 4, { speed: 2 })];+ openDialog();+ expect(screen.getByText("Total duration")).toBeInTheDocument();+ expect((screen.getByLabelText("Speed percent") as HTMLInputElement).placeholder).toBe("Mixed");+ fireEvent.change(screen.getByLabelText("Duration"), { target: { value: "4" } });+ fireEvent.click(screen.getByLabelText(/ripple edit/i));+ fireEvent.click(ok());+ expect(applyClipSpeedEdit).toHaveBeenCalledWith({ durationScale: 4 / 8 }, false);+ });++ it("rejects an out-of-range speed", () => {+ openDialog();+ fireEvent.change(screen.getByLabelText("Speed percent"), { target: { value: "5000" } });+ expect(screen.getByRole("alert")).toHaveTextContent(/between/i);+ expect(ok()).toBeDisabled();+ });++ it("sends reverse and pitch only when touched", () => {+ openDialog();+ fireEvent.click(screen.getByLabelText("Reverse speed"));+ fireEvent.click(screen.getByLabelText("Maintain audio pitch"));+ fireEvent.click(ok());+ expect(applyClipSpeedEdit).toHaveBeenCalledWith({ reversed: true, maintainPitch: false }, true);+ });++ it("stays open and explains a blocked edit", () => {+ applyClipSpeedEdit.mockReturnValueOnce({ success: false, message: "Unlock the target track before editing." });+ openDialog();+ fireEvent.change(screen.getByLabelText("Speed percent"), { target: { value: "50" } });+ fireEvent.click(ok());+ expect(warning).toHaveBeenCalledWith("Speed/Duration blocked", "Unlock the target track before editing.");+ expect(useClipSpeedDialogStore.getState().open).toBe(true);+ });+});diff --git a/apps/web/src/components/editor/ClipSpeedDialog.tsx b/apps/web/src/components/editor/ClipSpeedDialog.tsxnew file mode 100644index 00000000..71771e0e--- /dev/null+++ b/apps/web/src/components/editor/ClipSpeedDialog.tsx@@ -0,0 +1,162 @@+import { useEffect, useMemo, useState } from "react";+import { SPEED_MAX, SPEED_MIN, type ClipSpeedEdit } from "@openreel/core";+import { Button, Dialog, DialogContent, DialogDescription, DialogFooter, DialogHeader, DialogTitle, Input } from "@openreel/ui";+import { useClipSpeedDialogStore } from "../../stores/clip-speed-dialog-store";+import { useProjectStore } from "../../stores/project-store";+import { toast } from "../../stores/notification-store";+import { applyClipSpeedEdit, selectedSpeedClips } from "../../services/clip-speed-multi";+import { formatFrameTimecode, parseFrameTimecode } from "../../utils/frame-timecode";++const EPS = 1e-6;+const rateOf = (clip: { speed?: number }) => clip.speed ?? 1;++/**+ * Clip > Speed/Duration for one or many selected clips (Premiere parity).+ * Speed and Duration are linked; with several clips Duration is the combined+ * length and scales every clip by the same factor. "Ripple Edit, Shifting+ * Trailing Clips" honours sync lock; linked audio always follows.+ */+export function ClipSpeedDialog() {+ const open = useClipSpeedDialogStore((s) => s.open);+ const setOpen = useClipSpeedDialogStore((s) => s.setOpen);+ const frameRate = useProjectStore((s) => s.project.settings.frameRate) || 30;+ const clips = useMemo(() => (open ? selectedSpeedClips() : []), [open]);+ const baseDuration = clips.reduce((sum, clip) => sum + clip.duration, 0);+ const speeds = clips.map(rateOf);+ const uniform = speeds.every((value) => Math.abs(value - speeds[0]) < EPS);+ const reversedAll = clips.length > 0 && clips.every((clip) => clip.reversed);+ const pitchAll = clips.every((clip) => clip.pitchCorrection ?? true);++ const [speed, setSpeed] = useState("");+ const [duration, setDuration] = useState("");+ const [touched, setTouched] = useState<"speed" | "duration" | null>(null);+ const [reverse, setReverse] = useState(false);+ const [reverseTouched, setReverseTouched] = useState(false);+ const [pitch, setPitch] = useState(true);+ const [pitchTouched, setPitchTouched] = useState(false);+ const [ripple, setRipple] = useState(true);++ useEffect(() => {+ if (!open) return;+ setSpeed(uniform ? String(Math.round(speeds[0] * 10000) / 100) : "");+ setDuration(formatFrameTimecode(baseDuration, frameRate));+ setTouched(null);+ setReverse(reversedAll);+ setReverseTouched(false);+ setPitch(pitchAll);+ setPitchTouched(false);+ // Reset only when the dialog opens.+ // eslint-disable-next-line react-hooks/exhaustive-deps+ }, [open]);++ const parsedSpeed = Number(speed);+ const speedValid = speed.trim() !== "" && Number.isFinite(parsedSpeed) && parsedSpeed / 100 >= SPEED_MIN - EPS && parsedSpeed / 100 <= SPEED_MAX + EPS;+ const parsedDuration = parseFrameTimecode(duration, frameRate);+ const durationValid = parsedDuration !== null && parsedDuration > 0;+ const error =+ touched === "speed" && !speedValid+ ? `Speed must be between ${SPEED_MIN * 100}% and ${SPEED_MAX * 100}%.`+ : touched === "duration" && !durationValid+ ? "Enter a duration as seconds or timecode (HH:MM:SS:FF)."+ : "";+ const changed = touched !== null || reverseTouched || pitchTouched;+ const valid = changed && !error;++ const onSpeed = (value: string) => {+ setSpeed(value);+ setTouched("speed");+ const next = Number(value) / 100;+ if (value.trim() !== "" && Number.isFinite(next) && next > 0) {+ // Linked field: the new total length at this rate.+ const total = clips.reduce((sum, clip) => sum + (clip.outPoint - clip.inPoint) / next, 0);+ setDuration(formatFrameTimecode(total, frameRate));+ }+ };+ const onDuration = (value: string) => {+ setDuration(value);+ setTouched("duration");+ const seconds = parseFrameTimecode(value, frameRate);+ if (seconds && seconds > 0 && baseDuration > 0 && clips.length === 1) {+ const clip = clips[0];+ setSpeed(String(Math.round(((clip.outPoint - clip.inPoint) / seconds) * 10000) / 100));+ }+ };++ const apply = () => {+ if (!valid) return;+ const edit: ClipSpeedEdit = {};+ if (touched === "speed") edit.speed = parsedSpeed / 100;+ else if (touched === "duration" && parsedDuration !== null)+ if (clips.length === 1) edit.duration = parsedDuration;+ else edit.durationScale = parsedDuration / baseDuration;+ if (reverseTouched) edit.reversed = reverse;+ if (pitchTouched) edit.maintainPitch = pitch;+ const outcome = applyClipSpeedEdit(edit, ripple);+ if (!outcome.success) {+ toast.warning("Speed/Duration blocked", outcome.message ?? "The edit could not be applied.");+ return;+ }+ setOpen(false);+ };++ return (+ <Dialog open={open} onOpenChange={setOpen}>+ <DialogContent className="max-w-sm">+ <DialogHeader>+ <DialogTitle>Clip speed / duration</DialogTitle>+ <DialogDescription>+ {clips.length > 1+ ? `Applies to ${clips.length} selected clips, including linked audio, as one undo step.`+ : "Change how fast the clip plays. Linked audio follows."}+ </DialogDescription>+ </DialogHeader>+ <form+ onSubmit={(event) => {+ event.preventDefault();+ apply();+ }}+ className="space-y-3"+ >+ <label className="grid grid-cols-[110px_1fr] items-center gap-2 text-xs text-fg-2">+ Speed (%)+ <Input+ autoFocus+ inputMode="decimal"+ aria-label="Speed percent"+ placeholder={uniform ? "" : "Mixed"}+ value={speed}+ onChange={(event) => onSpeed(event.target.value)}+ />+ </label>+ <label className="grid grid-cols-[110px_1fr] items-center gap-2 text-xs text-fg-2">+ {clips.length > 1 ? "Total duration" : "Duration"}+ <Input+ aria-label="Duration"+ value={duration}+ onChange={(event) => onDuration(event.target.value)}+ />+ </label>+ {error ? <p role="alert" className="text-xs text-status-error">{error}</p> : null}+ <div className="space-y-1.5 text-xs text-fg-2">+ <label className="flex items-center gap-2">+ <input type="checkbox" checked={reverse} onChange={(event) => { setReverse(event.target.checked); setReverseTouched(true); }} />+ Reverse speed+ </label>+ <label className="flex items-center gap-2">+ <input type="checkbox" checked={pitch} onChange={(event) => { setPitch(event.target.checked); setPitchTouched(true); }} />+ Maintain audio pitch+ </label>+ <label className="flex items-center gap-2">+ <input type="checkbox" checked={ripple} onChange={(event) => setRipple(event.target.checked)} />+ Ripple edit, shifting trailing clips+ </label>+ </div>+ <DialogFooter>+ <Button type="button" variant="ghost" onClick={() => setOpen(false)}>Cancel</Button>+ <Button type="submit" disabled={!valid}>OK</Button>+ </DialogFooter>+ </form>+ </DialogContent>+ </Dialog>+ );+}diff --git a/apps/web/src/components/editor/CreateProxiesDialog.tsx b/apps/web/src/components/editor/CreateProxiesDialog.tsxnew file mode 100644index 00000000..b0e77764--- /dev/null+++ b/apps/web/src/components/editor/CreateProxiesDialog.tsx@@ -0,0 +1,74 @@+import React, { useEffect, useState } from "react";+import {+ PROXY_PRESETS,+ proxyPresetForProfile,+ resolveDesktopProxyProfile,+ type ProxyPresetId,+} from "@openreel/core";+import { Button, Dialog, DialogContent, DialogDescription, DialogFooter, DialogHeader, DialogTitle, Label, RadioGroup, RadioGroupItem, cn } from "@openreel/ui";+import { useProjectStore } from "../../stores/project-store";+import { setDesktopProxyProfile } from "../../services/desktop-ingest";++interface CreateProxiesDialogProps {+ open: boolean;+ onOpenChange: (open: boolean) => void;+ /** How many items the proxies will be built for. */+ count: number;+ /** Selected items, or every item that lacks a proxy. */+ scopeLabel: string;+ /** Builds the proxies once the chosen preset is saved to the project. */+ onCreate: () => void;+}++/** Create Proxies dialog (desktop): pick a preset, save it with the project, then build. */+export const CreateProxiesDialog: React.FC<CreateProxiesDialogProps> = ({ open, onOpenChange, count, scopeLabel, onCreate }) => {+ const ingestConfig = useProjectStore((s) => s.project.mediaLibrary.desktopIngest);+ const current = proxyPresetForProfile(resolveDesktopProxyProfile({ mediaLibrary: { items: [], desktopIngest: ingestConfig } }));+ const [choice, setChoice] = useState<ProxyPresetId>(current ?? "h264-half");+ useEffect(() => {+ if (open && current) setChoice(current);+ }, [open, current]);++ const submit = async (): Promise<void> => {+ const preset = PROXY_PRESETS.find((entry) => entry.id === choice) ?? PROXY_PRESETS[1];+ if (current !== preset.id) await setDesktopProxyProfile(preset.profile);+ onOpenChange(false);+ onCreate();+ };++ return (+ <Dialog open={open} onOpenChange={onOpenChange}>+ <DialogContent className="max-w-md" data-testid="create-proxies-dialog">+ <DialogHeader>+ <DialogTitle>Create Proxies</DialogTitle>+ <DialogDescription className="text-xs text-fg-muted">+ {count} {count === 1 ? "clip" : "clips"} ({scopeLabel}). The preset is saved with this project and used for new imports.+ </DialogDescription>+ </DialogHeader>+ <RadioGroup aria-label="Proxy preset" value={choice} onValueChange={(value) => setChoice(value as ProxyPresetId)} className="grid gap-2">+ {PROXY_PRESETS.map((preset) => (+ <Label+ key={preset.id}+ htmlFor={`proxy-preset-${preset.id}`}+ data-testid={`proxy-preset-${preset.id}`}+ data-selected={choice === preset.id ? "true" : undefined}+ className={cn(+ "block cursor-pointer rounded-md border border-border bg-bg-1 px-3 py-2 text-left transition-colors hover:bg-bg-2 focus-within:ring-2 focus-within:ring-ring",+ choice === preset.id && "border-accent bg-selected shadow-[0_0_0_1px_var(--accent)]",+ )}+ >+ <RadioGroupItem id={`proxy-preset-${preset.id}`} value={preset.id} aria-label={preset.label} className="sr-only" />+ <span className="block text-[12px] font-semibold text-fg">{preset.label}</span>+ <span className="mt-0.5 block text-[10px] leading-snug text-fg-muted">{preset.description}</span>+ </Label>+ ))}+ </RadioGroup>+ <p className="text-[10px] leading-snug text-fg-muted">Proxies are for editing only. Exports always read the full-resolution media.</p>+ <DialogFooter>+ <Button type="button" variant="secondary" onClick={() => onOpenChange(false)}>Cancel</Button>+ <Button type="button" onClick={() => void submit()} disabled={count === 0} data-testid="create-proxies-confirm">Create proxies</Button>+ </DialogFooter>+ </DialogContent>+ </Dialog>+ );+};diff --git a/apps/web/src/components/editor/EditorInterface.tsx b/apps/web/src/components/editor/EditorInterface.tsxindex 9070c306..212c6d36 100644--- a/apps/web/src/components/editor/EditorInterface.tsx+++ b/apps/web/src/components/editor/EditorInterface.tsx@@ -6,6 +6,7 @@ import React, { useEffect, useState, useRef, useCallback } from "react";import { Button, Button as ShadcnButton, Dialog, DialogContent, DialogTitle, ScrollArea } from "@openreel/ui";import { ChangesPanel } from "./chat/ChangesPanel";+import { BackgroundTasksIndicator } from "./BackgroundTasksPanel";import { Toolbar } from "./Toolbar";import { EditorActionRail } from "./EditorActionRail";import { AssetsPanel } from "./AssetsPanel";@@ -17,18 +18,20 @@ import { Timeline } from "./Timeline";import { useLatch } from "./use-latch";import { PanelErrorBoundary } from "../ErrorBoundary";import { SpotlightTour, MoGraphTour } from "./tour";-import { useProjectStore } from "../../stores/project-store";+import { useProjectStore, registerSmoothKeyframeRefresh } from "../../stores/project-store";import { useUIStore } from "../../stores/ui-store";+import { useAudioChannelsStore } from "../../stores/audio-channels-store";import {useDockSize,MIN_MEDIA_W, MAX_MEDIA_W, MIN_INSPECTOR_W, MAX_INSPECTOR_W, MIN_CHAT_W, MAX_CHAT_W, MIN_TIMELINE_VH, MAX_TIMELINE_VH,} from "../../stores/workspace-layout-store";import { WorkspaceSaveDialog } from "./WorkspaceSaveDialog";+import { ClipSpeedDialog } from "./ClipSpeedDialog";import { ProjectLockBanner } from "./ProjectLockBanner";import { MissingFontsBanner } from "./MissingFontsBanner";import { applyPendingWorkspace } from "../../services/workspace-apply";import { useTimelineStore } from "../../stores/timeline-store";-import { copyKeyframeSet, pasteKeyframeSet } from "@openreel/core";+import { copyKeyframeSet, pasteKeyframeSet, applyKeyframeInterpolation, refreshSmoothKeyframesAfterEdit, type KeyframeInterpolationOp, type KeyframeInterpolationSide } from "@openreel/core";import { useInspectorNavigationStore } from "../../stores/inspector-navigation-store";import { useKeyboardShortcuts } from "../../hooks/useKeyboardShortcuts";import { useEditorInitialization } from "../../hooks/useEditorInitialization";@@ -38,6 +41,7 @@ import { usePreviewProxyPreference } from "../../hooks/use-preview-proxy-prefereimport { startProxyIngest } from "../../services/proxy-ingest";import { useMediaWaveforms } from "../../hooks/use-media-waveforms";import { startAudioRackSync } from "../../services/audio-rack-sync";+import { startAudioOutputService } from "../../services/audio-output-service";import { startLinkedCompHost } from "../../services/linked-comp-host";import "./editor-responsive.css";@@ -77,6 +81,7 @@ const KeyframeEditorPanel = React.lazy(() =>const AudioMixer = React.lazy(() =>loadAudioMixer().then((module) => ({ default: module.AudioMixer })),);+const AudioChannelsDialog = React.lazy(() => import("./AudioChannelsDialog").then(module => ({ default: module.AudioChannelsDialog })));const MultiCameraDialog = React.lazy(() =>loadMultiCameraDialog().then((module) => ({ default: module.MultiCameraDialog })),);@@ -120,6 +125,11 @@ const useIdlePanelPrefetch = (enabled: boolean) => {}, [enabled]);};+/** Applies the remembered monitor output device and reports unplug / replug while the editor is open. */+const useAudioOutputDevice = () => {+ useEffect(() => startAudioOutputService(), []);+};+/*** Auto-save initialization hook*/@@ -148,6 +158,8 @@ const useAutoSave = () => {* dividers between panels. Values are persisted to CSS custom* properties on the root grid so panels can pick them up.*/+registerSmoothKeyframeRefresh(refreshSmoothKeyframesAfterEdit);+export const EditorInterface: React.FC = () => {const compact = useCompactEditor();const phone = usePhoneEditor();@@ -160,6 +172,7 @@ export const EditorInterface: React.FC = () => {useKeyboardShortcuts();const shortcutsOverlayLatched = useLatch(showShortcutsOverlay);useAutoSave();+ useAudioOutputDevice();// Onboarding Pro row: apply the workspace picked on the welcome screen, once.useEffect(() => { applyPendingWorkspace(); }, []);usePreviewProxyPreference();@@ -168,6 +181,7 @@ export const EditorInterface: React.FC = () => {useIdlePanelPrefetch(initialized);const sourceTab = useSourceMonitorStore((state) => state.tab);+ const audioChannelsOpen = useAudioChannelsStore((state) => state.open);const keyframeEditorOpen = useUIStore((state) => state.keyframeEditorOpen);const setKeyframeEditorOpen = useUIStore((state) => state.setKeyframeEditorOpen);// Selection only matters here while the keyframe editor is open (or as a boolean for the@@ -231,7 +245,18 @@ export const EditorInterface: React.FC = () => {for (const [field, value] of Object.entries(updates)) if (value === undefined) delete next[field];return next as unknown as import("@openreel/core").Keyframe;});- if (changed) updateClipKeyframes(clip.id, keyframes);+ if (changed) {+ updateClipKeyframes(clip.id, keyframes);+ }+ },+ [selectedClip, getEditableKeyframeClip, updateClipKeyframes],+ );++ const handleApplyInterpolation = React.useCallback(+ (keyframeIds: string[], op: KeyframeInterpolationOp, side: KeyframeInterpolationSide) => {+ const clip = selectedClip && getEditableKeyframeClip(selectedClip.id);+ if (!clip?.keyframes || !keyframeIds.length) return;+ updateClipKeyframes(clip.id, applyKeyframeInterpolation(clip.keyframes, keyframeIds, op, side), { derived: true });},[selectedClip, getEditableKeyframeClip, updateClipKeyframes],);@@ -642,6 +667,7 @@ export const EditorInterface: React.FC = () => {onClose={() => setKeyframeEditorOpen(false)}disabled={keyframeExporting || keyframeOperationLocked || keyframeTrackLocked}onUpdateKeyframes={handleUpdateKeyframes}+ onApplyInterpolation={handleApplyInterpolation}onDeleteKeyframes={handleDeleteKeyframes}onCopyKeyframes={handleCopyKeyframes}onPasteKeyframes={handlePasteKeyframes}@@ -658,6 +684,12 @@ export const EditorInterface: React.FC = () => {</div></div>+ {!phone && (+ <footer data-testid="editor-status-bar" className="flex h-7 shrink-0 items-center justify-between border-t border-border bg-bg-1 px-1">+ <BackgroundTasksIndicator />+ </footer>+ )}+{phone && <React.Suspense fallback={<div style={{ height: 66, flexShrink: 0 }} role="status" aria-label="Loading mobile tools"/>}><MobileEditorTools onPanel={openCompactPanel}/></React.Suspense>}{compact && !phone && (<nav aria-label="Editor workspace" className="editor-workspace-tabs">@@ -680,6 +712,13 @@ export const EditorInterface: React.FC = () => {/></React.Suspense>)}+ {audioChannelsOpen && (+ <PanelErrorBoundary name="Audio channels" silent>+ <React.Suspense fallback={null}>+ <AudioChannelsDialog />+ </React.Suspense>+ </PanelErrorBoundary>+ )}<PanelErrorBoundary name="Multicam" silent><React.Suspense fallback={null}><MultiCameraDialog />@@ -707,6 +746,7 @@ export const EditorInterface: React.FC = () => {</Dialog><WorkspaceSaveDialog />+ <ClipSpeedDialog /><SpotlightTour /><MoGraphTour /></div>diff --git a/apps/web/src/components/editor/EditorMenuBar.tsx b/apps/web/src/components/editor/EditorMenuBar.tsxindex 715a0d89..5e2659a3 100644--- a/apps/web/src/components/editor/EditorMenuBar.tsx+++ b/apps/web/src/components/editor/EditorMenuBar.tsx@@ -42,6 +42,7 @@ import { useRouter } from "../../hooks/use-router";import { startTour, startMoGraphTour } from "./tour";import { DOCS_URL, ISSUES_URL } from "./about-links";import { useOnboardingStore } from "../../stores/onboarding-store";+import { openAudioChannelsForSelection } from "../../services/audio-channels";import { canResetClipTransform, resetClipTransform } from "../../services/reset-clip-transform";// Reset Transform enablement is a boolean derived from the selection and the project. Reading it@@ -238,6 +239,8 @@ export function EditorMenuBar({null,{ label: "Insert selected media", action: command("editing.insert"), shortcut: "," },{ label: "Overwrite with selected media", action: command("editing.overwrite"), shortcut: "." },+ { label: "Replace clip from Source monitor", action: command("editing.replaceEdit"), shortcut: "⇧G" },+ { label: "Fit to Fill from Source monitor", action: command("editing.fitToFill"), shortcut: "⌥⇧F" },{ label: "Lift In/Out range", action: command("editing.lift"), shortcut: ";" },{ label: "Extract In/Out range", action: command("editing.extract"), shortcut: "'" },{ label: "Add edit to all tracks", action: command("editing.addEditAllTracks"), shortcut: "⇧⌘K" },@@ -251,6 +254,10 @@ export function EditorMenuBar({{ label: "J-cut (audio leads)", action: command("editing.jCut"), shortcut: "⌥J" },{ label: "L-cut (audio trails)", action: command("editing.lCut"), shortcut: "⌥L" },{ label: "Match frame", action: command("editing.matchFrame"), shortcut: "F" },+ { label: "Reverse match frame", action: command("editing.reverseMatchFrame"), shortcut: "⇧F" },+ null,+ { label: "Audio channels…", description: "Map source channels: left only, swap, mono, stereo, 5.1", action: () => { if (!openAudioChannelsForSelection()) toast.info("Select a clip with audio", "Audio channels applies to the selected clips."); } },+ { label: "Speed/Duration…", description: "Speed, duration, reverse and pitch for the selected clips, with ripple", action: command("editing.speedDuration"), shortcut: "⌥⌘R" },null,{ label: "Replace with linked composition", action: command("linked.replace"), shortcut: "⌥⌘L" },{ label: "Open linked composition", action: command("linked.open"), shortcut: "⌥⌘O" },diff --git a/apps/web/src/components/editor/EncoderPicker.test.tsx b/apps/web/src/components/editor/EncoderPicker.test.tsxnew file mode 100644index 00000000..5f379680--- /dev/null+++ b/apps/web/src/components/editor/EncoderPicker.test.tsx@@ -0,0 +1,57 @@+import { describe, expect, it, vi, beforeEach, afterEach } from "vitest";+import { act, render, screen } from "@testing-library/react";+import { EncoderPicker } from "./EncoderPicker";++type Config = { hardwareAcceleration: string };+let supportsHardware = true;+let resolvers: Array<() => void> = [];++beforeEach(() => {+ supportsHardware = true;+ resolvers = [];+ vi.stubGlobal("VideoEncoder", {+ isConfigSupported: (config: Config) =>+ new Promise((resolve) => {+ resolvers.push(() => resolve({ supported: config.hardwareAcceleration === "prefer-software" ? true : supportsHardware }));+ }),+ });+});+afterEach(() => {+ vi.unstubAllGlobals();+});++const flush = async () => {+ await act(async () => {+ resolvers.splice(0).forEach((resolve) => resolve());+ await Promise.resolve();+ });+};++describe("EncoderPicker", () => {+ it("never changes the chosen encoder while a probe is running or after settings change", async () => {+ const onChange = vi.fn();+ const props = { codec: "h264", width: 1920, height: 1080, value: "hardware" as const, onChange };+ const { rerender } = render(<EncoderPicker {...props} frameRate={30} />);+ await flush();+ await flush();+ expect(screen.getByTestId("encoder-hardware").getAttribute("data-available")).toBe("true");+ rerender(<EncoderPicker {...props} frameRate={24} />);+ // Probe pending for the new frame rate: the choice stays Hardware and stays available.+ expect(screen.getByTestId("encoder-hardware").getAttribute("data-selected")).toBe("true");+ await flush();+ await flush();+ expect(onChange).not.toHaveBeenCalled();+ });++ it("shows an unavailable saved choice honestly and blocks export instead of switching silently", async () => {+ supportsHardware = false;+ const onChange = vi.fn();+ const onBlockedChange = vi.fn();+ render(<EncoderPicker codec="h264" width={1920} height={1080} frameRate={30} value="hardware" onChange={onChange} onBlockedChange={onBlockedChange} />);+ await flush();+ await flush();+ expect(onChange).not.toHaveBeenCalled();+ expect(screen.getByTestId("encoder-unavailable-note").textContent).toMatch(/not available here/i);+ expect(onBlockedChange).toHaveBeenLastCalledWith(true);+ });+});diff --git a/apps/web/src/components/editor/EncoderPicker.tsx b/apps/web/src/components/editor/EncoderPicker.tsxnew file mode 100644index 00000000..b60f4b49--- /dev/null+++ b/apps/web/src/components/editor/EncoderPicker.tsx@@ -0,0 +1,111 @@+import React, { useEffect, useState } from "react";+import {+ describeBrowserEncoderOptions,+ describeEncoderOptions,+ probeWebCodecsEncoderSupport,+ type EncoderChoice,+ type EncoderOption,+ type WebCodecsEncoderSupport,+} from "@openreel/core";+import { Label, RadioGroup, RadioGroupItem, cn } from "@openreel/ui";++interface EncoderPickerProps {+ codec: string;+ width: number;+ height: number;+ frameRate: number;+ value: EncoderChoice;+ onChange: (choice: EncoderChoice) => void;+ /** True while the saved choice cannot run on this machine (Export should be blocked until the user picks another). */+ onBlockedChange?: (blocked: boolean) => void;+}++const isDesktop = (): boolean => typeof window !== "undefined" && window.openreel?.platform === "desktop";++/**+ * Encoder choice for H.264 / H.265 / AV1: Auto, Hardware or Software. The desktop asks the ffmpeg+ * sidecar which encoders actually opened on this machine (VideoToolbox, NVENC, Quick Sync, AMF);+ * the browser asks WebCodecs. A choice the machine cannot run is disabled with the reason shown.+ */+export const EncoderPicker: React.FC<EncoderPickerProps> = ({ codec, width, height, frameRate, value, onChange, onBlockedChange }) => {+ const desktop = isDesktop();+ const [encoders, setEncoders] = useState<string[] | null>(null);+ const [platform, setPlatform] = useState<string>("");+ const [web, setWeb] = useState<WebCodecsEncoderSupport | null>(null);++ useEffect(() => {+ if (!desktop) return;+ let active = true;+ void (window.openreel?.probeHardware?.() ?? Promise.resolve(null))+ .catch(() => null)+ .then((info) => {+ if (!active) return;+ setEncoders(info?.encoders ?? []);+ setPlatform(info?.platform ?? "");+ });+ return () => {+ active = false;+ };+ }, [desktop]);++ useEffect(() => {+ if (desktop) return;+ let active = true;+ // Keep the previous answer while a new probe runs, so an in-flight probe never reads as "unavailable".+ void probeWebCodecsEncoderSupport(codec, width, height, frameRate).then((support) => {+ if (active) setWeb(support);+ });+ return () => {+ active = false;+ };+ }, [desktop, codec, width, height, frameRate]);++ const options: EncoderOption[] = desktop+ ? describeEncoderOptions({ codec, platform, available: encoders })+ : describeBrowserEncoderOptions(web);++ // The choice is never changed behind the user's back. Once a probe has answered, a choice the+ // machine cannot run is shown as such and Export is blocked until the user picks another.+ const probed = desktop ? encoders !== null : web !== null;+ const selectedOption = options.find((option) => option.choice === value);+ const blocked = probed && value !== "auto" && !!selectedOption && !selectedOption.available;+ useEffect(() => {+ onBlockedChange?.(blocked);+ return () => onBlockedChange?.(false);+ }, [blocked, onBlockedChange]);++ return (+ <div className="col-span-2 border-t border-border pt-4" data-testid="encoder-picker">+ <span className="mb-2 block text-[11px] font-bold text-fg-2">Encoder</span>+ <RadioGroup aria-label="Encoder" value={value} onValueChange={(next) => onChange(next as EncoderChoice)} className="grid grid-cols-3 gap-2">+ {options.map((option) => (+ <Label+ key={option.choice}+ data-testid={`encoder-${option.choice}`}+ data-available={option.available ? "true" : "false"}+ data-selected={value === option.choice ? "true" : undefined}+ htmlFor={`export-encoder-${option.choice}`}+ className={cn(+ "relative block min-h-[58px] rounded-md border border-border bg-bg-1 px-3 py-2.5 text-left text-fg transition-colors focus-within:ring-2 focus-within:ring-ring",+ option.available ? "cursor-pointer hover:bg-bg-2" : "cursor-not-allowed opacity-60",+ value === option.choice && "border-accent bg-selected shadow-[0_0_0_1px_var(--accent)]",+ )}+ >+ <RadioGroupItem id={`export-encoder-${option.choice}`} value={option.choice} disabled={!option.available} aria-label={option.label} className="sr-only" />+ <span className="block text-[11px] font-semibold">{option.label}</span>+ <span className="mt-0.5 block text-[9px] leading-3 text-fg-muted">{option.detail}</span>+ </Label>+ ))}+ </RadioGroup>+ {blocked && selectedOption && (+ <p role="alert" data-testid="encoder-unavailable-note" className="mt-2 text-[11px] text-error">+ {selectedOption.label} is not available here: {selectedOption.detail}. Choose{" "}+ <button type="button" className="underline" onClick={() => onChange("auto")}>+ Auto+ </button>{" "}+ or another encoder to export.+ </p>+ )}+ </div>+ );+};diff --git a/apps/web/src/components/editor/ExportCaptionOptions.tsx b/apps/web/src/components/editor/ExportCaptionOptions.tsxindex fb118f11..c9465f7a 100644--- a/apps/web/src/components/editor/ExportCaptionOptions.tsx+++ b/apps/web/src/components/editor/ExportCaptionOptions.tsx@@ -67,6 +67,11 @@ export function ExportCaptionOptions({[subtitles, value, format, isDesktop, frameRate],);+ const hiddenTracks = useMemo(() => {+ const shown = new Set(subtitles.filter((c) => !c.hidden).map((c) => c.captionTrackId ?? ""));+ return new Set(tracks.filter((t) => !shown.has(t.id)).map((t) => t.id));+ }, [subtitles, tracks]);+const update = (id: string, patch: Partial<CaptionTrackExportSettings>) => {const next = { ...trackExportSettings(value, id), ...patch };const others = value.tracks.filter((t) => t.captionTrackId !== id);@@ -113,12 +118,14 @@ export function ExportCaptionOptions({<div className="grid grid-cols-1 gap-2 sm:grid-cols-[auto_minmax(0,1fr)_minmax(0,1fr)]"><div className="flex items-center justify-between gap-2 sm:flex-col sm:items-start sm:justify-start"><Label htmlFor={`caption-burn-${key}`} className="text-[10px] text-fg-muted">- Burn in+ {hiddenTracks.has(track.id) ? "Burn in (hidden)" : "Burn in"}</Label><Switchid={`caption-burn-${key}`}aria-label={`Burn in ${trackName(track.id, track.language)}`}- checked={settings.burnIn}+ title={hiddenTracks.has(track.id) ? "This track is hidden in the picture. Choose it with Show in picture in the Transcript panel." : undefined}+ disabled={hiddenTracks.has(track.id)}+ checked={settings.burnIn && !hiddenTracks.has(track.id)}onCheckedChange={(burnIn) => update(track.id, { burnIn })}/></div>diff --git a/apps/web/src/components/editor/ExportDialog.tsx b/apps/web/src/components/editor/ExportDialog.tsxindex 13ad7469..aeb5b489 100644--- a/apps/web/src/components/editor/ExportDialog.tsx+++ b/apps/web/src/components/editor/ExportDialog.tsx@@ -40,7 +40,8 @@ import {AlertTriangle,X,} from "@/icons/lucide-compat";-import { isBroadcastCodec, effectiveRateControl, twoPassAvailability } from "@openreel/core";+import { isBroadcastCodec, effectiveRateControl, twoPassAvailability, BURN_IN_POSITIONS, DEFAULT_TIMECODE_BURN_IN, type TimecodeBurnInSettings, type BurnInPosition } from "@openreel/core";+import { EncoderPicker } from "./EncoderPicker";import {Button,Alert,@@ -255,6 +256,70 @@ const PresetAspectFrame: React.FC<{);};+/**+ * "Burn in timecode": one switch draws the sequence timecode (drop-frame aware) into every exported frame, above all+ * tracks and captions. Position and source are one click away; size and opacity keep the defaults.+ */+function TimecodeBurnInControl({+ value,+ onChange,+}: {+ value: TimecodeBurnInSettings;+ onChange: (next: TimecodeBurnInSettings) => void;+}) {+ const position = value.position ?? DEFAULT_TIMECODE_BURN_IN.position;+ const source = value.source ?? DEFAULT_TIMECODE_BURN_IN.source;+ return (+ <div className="space-y-2" data-testid="export-timecode-burn-in">+ <div className="flex items-center justify-between gap-3">+ <div>+ <Label htmlFor="export-burn-in-timecode" className="text-[12px] font-semibold text-fg">+ Burn in timecode+ </Label>+ <p className="text-[10px] text-fg-muted">+ Draws the {source === "source" ? "source file" : "sequence"} timecode into every frame. Frames are re-rendered, so no stream copy.+ </p>+ </div>+ <Switch+ id="export-burn-in-timecode"+ aria-label="Burn in timecode"+ checked={value.enabled}+ onCheckedChange={(enabled) => onChange({ ...value, enabled })}+ />+ </div>+ {value.enabled && (+ <div className="grid grid-cols-2 gap-2">+ <div className="space-y-1">+ <Label htmlFor="export-burn-in-source" className="text-[10px] text-fg-muted">Timecode</Label>+ <Select value={source} onValueChange={(next) => onChange({ ...value, source: next as "sequence" | "source" })}>+ <SelectTrigger id="export-burn-in-source" aria-label="Burn-in timecode source" className="h-7 w-full text-xs">+ <SelectValue />+ </SelectTrigger>+ <SelectContent>+ <SelectItem value="sequence" className="text-xs">Sequence</SelectItem>+ <SelectItem value="source" className="text-xs">Source file (topmost clip)</SelectItem>+ </SelectContent>+ </Select>+ </div>+ <div className="space-y-1">+ <Label htmlFor="export-burn-in-position" className="text-[10px] text-fg-muted">Position</Label>+ <Select value={position} onValueChange={(next) => onChange({ ...value, position: next as BurnInPosition })}>+ <SelectTrigger id="export-burn-in-position" aria-label="Burn-in position" className="h-7 w-full text-xs">+ <SelectValue />+ </SelectTrigger>+ <SelectContent>+ {BURN_IN_POSITIONS.map((option) => (+ <SelectItem key={option.value} value={option.value} className="text-xs">{option.label}</SelectItem>+ ))}+ </SelectContent>+ </Select>+ </div>+ </div>+ )}+ </div>+ );+}+/** A small JPEG of the Program frame at the playhead, captured once when the dialog opens. */function useProgramFrameUrl(active: boolean): string | null {const [url, setUrl] = useState<string | null>(null);@@ -429,6 +494,7 @@ export const ExportDialog: React.FC<ExportDialogProps> = ({const subtitles = useProjectStore((state) => state.project.timeline.subtitles);const projectName = useProjectStore((state) => state.project.name);const [captionExport, setCaptionExport] = useState<CaptionExportSettings>({ tracks: [] });+ const [timecodeBurnIn, setTimecodeBurnIn] = useState<TimecodeBurnInSettings>({ enabled: false });const loudnessInvalid =activeTab === "custom" && loudness.enabled && !isValidLoudnessTarget(loudness);const applyExportSection = useCallback(@@ -453,8 +519,10 @@ export const ExportDialog: React.FC<ExportDialogProps> = ({activeTab === "custom" && captionExport.tracks.length > 0? captionExport: undefined,+ // One click, on every video tab: the sequence timecode is drawn into each frame.+ burnInTimecode: timecodeBurnIn.enabled && activeTab !== "stills" ? { ...timecodeBurnIn } : undefined,}),- [exportSection, validMarkedRange, loudness, activeTab, captionExport, sequenceIsSurround, audioChannelChoice],+ [exportSection, validMarkedRange, loudness, activeTab, captionExport, timecodeBurnIn, sequenceIsSurround, audioChannelChoice],);/** Sidecar caption files are independent of the render: save them when the export starts. */@@ -480,6 +548,7 @@ export const ExportDialog: React.FC<ExportDialogProps> = ({const aspectType = getAspectRatioType(projectWidth, projectHeight);const [bitrateDraft, setBitrateDraft] = useState("15000");+ const [encoderBlocked, setEncoderBlocked] = useState(false);const [customSettings, setCustomSettings] = useState<VideoExportSettings>({format: "mp4",codec: "h264",@@ -1005,6 +1074,7 @@ export const ExportDialog: React.FC<ExportDialogProps> = ({]);const exportDisabled =+ (encoderBlocked && activeTab === "custom") ||loudnessInvalid ||(activeTab === "presets" && !selectedPreset) ||(activeTab === "reduce" && !reducePlan) ||@@ -1197,6 +1267,9 @@ export const ExportDialog: React.FC<ExportDialogProps> = ({</span></RadioGroup></fieldset>+ {activeTab !== "stills" && (+ <TimecodeBurnInControl value={timecodeBurnIn} onChange={setTimecodeBurnIn} />+ )}<TabsListaria-label="Export mode"className="h-8 w-full max-w-[440px] justify-start bg-bg-2 p-0.5"@@ -2245,6 +2318,18 @@ export const ExportDialog: React.FC<ExportDialogProps> = ({</div></div>+ {["h264", "h265", "av1"].includes(customSettings.codec) && (+ <EncoderPicker+ codec={customSettings.codec}+ width={customSettings.width}+ height={customSettings.height}+ frameRate={customSettings.frameRate}+ value={customSettings.encoderChoice ?? "auto"}+ onChange={(encoderChoice) => setCustomSettings((current) => ({ ...current, encoderChoice }))}+ onBlockedChange={setEncoderBlocked}+ />+ )}+{isDesktop && (<div className="col-span-2 border-t border-border pt-4"><span className="text-fg-2 font-bold block mb-2 text-[11px]">diff --git a/apps/web/src/components/editor/KeyframeEditorPanel.test.tsx b/apps/web/src/components/editor/KeyframeEditorPanel.test.tsxindex a4301cb5..327a4b9a 100644--- a/apps/web/src/components/editor/KeyframeEditorPanel.test.tsx+++ b/apps/web/src/components/editor/KeyframeEditorPanel.test.tsx@@ -159,4 +159,19 @@ describe("graph editor: handles, presets, overlay, speed, paste", () => {fireEvent.click(screen.getByRole("button", { name: "Paste" }));expect(props.onPasteKeyframes).toHaveBeenLastCalledWith("multi", 1.5, "opacity");});+ it("names each side of a key's interpolation and applies a type to the chosen side", async () => {+ const mixed: Keyframe[] = [+ { ...keys[0], easing: "linear", interpolationOut: "auto-bezier" },+ { ...keys[1], easing: "hold", interpolationIn: "auto-bezier" },+ { id: "c", property: "opacity", time: 6, value: 0.5, easing: "linear" },+ ];+ const onApplyInterpolation = vi.fn();+ mount({ clip: { ...clip, keyframes: mixed } as Clip, selectedKeyframeIds: ["a"], onApplyInterpolation });+ // First key shows only its outgoing side; the held segment reads Hold on both of its ends.+ expect(screen.getByRole("button", { name: /Keyframe at 0.000s.*Auto Bezier$/ })).toBeTruthy();+ expect(screen.getByRole("button", { name: /Keyframe at 4.000s.*In Hold · Out Hold$|Keyframe at 4.000s.*Hold$/ })).toBeTruthy();+ await selectOption(screen.getByRole("combobox", { name: "Interpolation side" }), "Out only");+ await selectOption(screen.getByRole("combobox", { name: "Interpolation" }), "Linear");+ expect(onApplyInterpolation).toHaveBeenCalledWith(["a"], "linear", "out");+ });});diff --git a/apps/web/src/components/editor/KeyframeEditorPanel.tsx b/apps/web/src/components/editor/KeyframeEditorPanel.tsxindex f7e534fb..f9364777 100644--- a/apps/web/src/components/editor/KeyframeEditorPanel.tsx+++ b/apps/web/src/components/editor/KeyframeEditorPanel.tsx@@ -1,10 +1,10 @@import React, { useState, useMemo, useCallback, useRef, useEffect } from "react";import {- EASING_TYPES, EASE_PRESETS, clampBezierHandles, effectiveBezierHandles, keyframeEngine, keyframeSpeedAt,+ EASING_TYPES, EASE_PRESETS, KEYFRAME_INTERPOLATION_OPS, KEYFRAME_INTERPOLATION_LABELS, KEYFRAME_INTERPOLATION_SIDE_LABELS, keyframeSideTypes, type KeyframeInterpolationOp, type KeyframeInterpolationSide, type KeyframeSideType, clampBezierHandles, effectiveBezierHandles, keyframeEngine, keyframeSpeedAt,type BezierHandles, type EasePresetId, type Keyframe, type Clip,} from "@openreel/core";import { X, Copy, Clipboard, Trash2, ChevronLeft, ChevronRight } from "@/icons/lucide-compat";-import { Button, ScrollArea, Select, SelectTrigger, SelectValue, SelectContent, SelectItem, cn } from "@openreel/ui";+import { Button, ScrollArea, Select, SelectTrigger, SelectValue, SelectContent, SelectItem, ContextMenu, ContextMenuTrigger, ContextMenuContent, ContextMenuCheckboxItem, ContextMenuLabel, cn } from "@openreel/ui";const PROPERTY_COLORS: Record<string, string> = {"position.x": "#22d3ee", "position.y": "#34d399", "scale.x": "#4ade80", "scale.y": "#86efac",@@ -22,6 +22,45 @@ const PRESET_BUTTONS: { id: EasePresetId; label: string }[] = [];const easingLabel = (value: string) => value === "bezier" ? "Custom Bézier" : value.replace(/([a-z])([A-Z])/g, "$1 $2").replaceAll("-", " ").replace(/\b\w/g, letter => letter.toUpperCase());+const typeLabel = (type: KeyframeSideType) => type in KEYFRAME_INTERPOLATION_LABELS ? KEYFRAME_INTERPOLATION_LABELS[type as KeyframeInterpolationOp] : easingLabel(type);+type SideTypes = { in?: KeyframeSideType; out?: KeyframeSideType };+/** One label for a key: a single type when both sides agree, otherwise each side named. */+function sideTypesLabel(types: SideTypes): string {+ if (types.in && types.out) return types.in === types.out ? typeLabel(types.in) : `In ${typeLabel(types.in)} · Out ${typeLabel(types.out)}`;+ const only = types.in ?? types.out;+ return only ? typeLabel(only) : "";+}++/** Premiere-style "Temporal Interpolation" context menu; applies to the clicked key, or the whole selection when it was part of it. */+function InterpolationMenu({ children, disabled, side, resolveIds, typesOf, onApply }: {+ children: React.ReactNode; disabled: boolean; side: KeyframeInterpolationSide; resolveIds: (event: React.MouseEvent) => string[];+ typesOf: (id: string) => SideTypes; onApply: (ids: string[], op: KeyframeInterpolationOp) => void;+}) {+ const ids = useRef<string[]>([]);+ const [current, setCurrent] = useState<SideTypes>({});+ const isCurrent = (op: KeyframeInterpolationOp) => {+ const wanted = side === "both" ? [current.in, current.out] : [side === "in" ? current.in : current.out];+ return op !== "ease-in" && op !== "ease-out" && wanted.some(Boolean) && wanted.filter(Boolean).every(type => type === op);+ };+ return (+ <ContextMenu>+ <ContextMenuTrigger asChild disabled={disabled}+ onContextMenuCapture={(event: React.MouseEvent) => {+ ids.current = resolveIds(event);+ setCurrent(ids.current.length ? typesOf(ids.current[0]) : {});+ if (!ids.current.length) event.preventDefault();+ }}>+ {children}+ </ContextMenuTrigger>+ <ContextMenuContent aria-label="Temporal interpolation">+ <ContextMenuLabel>Temporal Interpolation ({KEYFRAME_INTERPOLATION_SIDE_LABELS[side].toLowerCase()})</ContextMenuLabel>+ {KEYFRAME_INTERPOLATION_OPS.map(op => (+ <ContextMenuCheckboxItem key={op} checked={isCurrent(op)} onSelect={() => onApply(ids.current, op)}>{KEYFRAME_INTERPOLATION_LABELS[op]}</ContextMenuCheckboxItem>+ ))}+ </ContextMenuContent>+ </ContextMenu>+ );+}const numericKey = (key: Keyframe): key is Keyframe & { value: number } =>typeof key.value === "number" && Number.isFinite(key.value) && Number.isFinite(key.time);function formatValue(value: unknown): string {@@ -40,6 +79,7 @@ interface KeyframeEditorPanelProps {playheadTime?: number;onClose: () => void;onUpdateKeyframes: (ids: string[], updates: Partial<Keyframe>) => void;+ onApplyInterpolation?: (ids: string[], op: KeyframeInterpolationOp, side: KeyframeInterpolationSide) => void;onDeleteKeyframes: (ids: string[]) => void;onCopyKeyframes: (ids: string[]) => void;onPasteKeyframes: (clipId: string, time: number, targetProperty?: string) => void;@@ -98,13 +138,14 @@ function handlePoints(key: NumericKey, next: NumericKey, handles: BezierHandles)};}-export function KeyframeEditorPanel({ clip, disabled = false, playheadTime = 0, onClose, onUpdateKeyframes, onDeleteKeyframes,+export function KeyframeEditorPanel({ clip, disabled = false, playheadTime = 0, onClose, onUpdateKeyframes, onApplyInterpolation, onDeleteKeyframes,onCopyKeyframes, onPasteKeyframes, selectedKeyframeIds, onSelectKeyframe, copiedKeyframes }: KeyframeEditorPanelProps) {const [activeProperty, setActiveProperty] = useState<string | null>(null);const [overlay, setOverlay] = useState<string[]>([]);const [mode, setMode] = useState<"value" | "speed">("value");const [pasteIntoActive, setPasteIntoActive] = useState(false);const [page, setPage] = useState(1);+ const [interpSide, setInterpSide] = useState<KeyframeInterpolationSide>("both");const [graphWidth, setGraphWidth] = useState(GRAPH_WIDTH);const [draft, setDraft] = useState<Draft | null>(null);const canvasRef = useRef<HTMLCanvasElement>(null);@@ -132,6 +173,12 @@ export function KeyframeEditorPanel({ clip, disabled = false, playheadTime = 0,.map((group, index): PropertyGroup => ({ ...group, color: colorFor(group.property, index) }));}, [clip?.keyframes]);const activeGroup = propertyGroups.find(group => group.property === activeProperty) ?? propertyGroups[0] ?? null;+ const typesOf = useCallback((id: string): SideTypes => {+ const group = propertyGroups.find(g => g.keyframes.some(key => key.id === id));+ const index = group ? group.keyframes.findIndex(key => key.id === id) : -1;+ if (!group || index < 0) return {};+ return keyframeSideTypes(group.keyframes[index - 1], group.keyframes[index], index < group.keyframes.length - 1);+ }, [propertyGroups]);const selectedKeys = useMemo(() => {const ids = new Set(selectedKeyframeIds);return (clip?.keyframes ?? []).filter(key => ids.has(key.id));@@ -394,16 +441,29 @@ export function KeyframeEditorPanel({ clip, disabled = false, playheadTime = 0,</div></div>}<div className="p-3">+ <InterpolationMenu disabled={disabled || !onApplyInterpolation} side={interpSide} typesOf={typesOf} onApply={(ids, op) => onApplyInterpolation?.(ids, op, interpSide)} resolveIds={event => {+ const rect = (event.currentTarget as HTMLElement).getBoundingClientRect();+ if (!activeLayer || rect.width <= 0) return selectedIds;+ const x = (event.clientX - rect.left) * graphWidth / rect.width, y = (event.clientY - rect.top) * GRAPH_HEIGHT / rect.height;+ const hit = layers.flatMap(layer => layer.keys.map(key => ({ key, layer }))).find(({ key, layer }) => Math.hypot(x - timeToX(key.time), y - valueToY(layer.range, key.value)) < HIT_RADIUS);+ if (!hit) return selectedIds;+ if (!selectedIdSet.has(hit.key.id)) onSelectKeyframe(hit.key.id, false);+ return selectedIdSet.has(hit.key.id) ? selectedIds : [hit.key.id];+ }}><canvas ref={canvasRef} width={GRAPH_WIDTH} height={GRAPH_HEIGHT} data-graph-mode={mode} aria-label="Keyframe value graph" className={cn("w-full touch-none rounded-md border border-border bg-bg-1", disabled || mode === "speed" ? "cursor-default" : "cursor-crosshair")} style={{ height: GRAPH_HEIGHT }} onPointerDown={startDrag} onPointerMove={moveDrag}/>+ </InterpolationMenu>{!numericActive && <p className="mt-2 text-[11px] text-fg-muted">{activeGroup ? "This property has no numeric curve." : "Add keyframes in the inspector to start animating."}</p>}{numericActive && mode === "value" && <p className="mt-2 text-[10px] text-fg-muted">Select a keyframe to drag its Bézier handles. {layers.length > 1 ? "Overlaid curves are each scaled to their own range." : ""}</p>}{mode === "speed" && <p className="mt-2 text-[10px] text-fg-muted">Speed graph: rate of change per second. Each curve is scaled to its own peak.</p>}</div>{!!rows.length && <div className="border-t border-border px-2 py-1"><div aria-hidden className="grid grid-cols-[1fr_1fr_2fr] gap-2 px-2 py-1 text-[10px] text-fg-muted"><span>Time</span><span>Value</span><span>Easing</span></div>- {rows.map(key => <Button key={key.id} variant="ghost" aria-pressed={selectedIdSet.has(key.id)} aria-label={`Keyframe at ${key.time.toFixed(3)}s, value ${formatValue(key.value)}, ${easingLabel(key.easing)}`} onClick={event => onSelectKeyframe(key.id, event.shiftKey || event.metaKey || event.ctrlKey)} className={cn("grid h-auto w-full grid-cols-[1fr_1fr_2fr] gap-2 whitespace-normal rounded px-2 py-1.5 text-left text-[11px] font-normal", selectedIdSet.has(key.id) && "bg-accent/10 text-accent")}>- <span className="font-mono">{key.time.toFixed(3)}s</span><span className="min-w-0 break-words font-mono">{formatValue(key.value)}</span><span>{easingLabel(key.easing)}</span>- </Button>)}+ {rows.map(key => <InterpolationMenu key={key.id} disabled={disabled || !onApplyInterpolation} side={interpSide} typesOf={typesOf} onApply={(ids, op) => onApplyInterpolation?.(ids, op, interpSide)} resolveIds={() => {+ if (!selectedIdSet.has(key.id)) onSelectKeyframe(key.id, false);+ return selectedIdSet.has(key.id) ? selectedIds : [key.id];+ }}><Button variant="ghost" aria-pressed={selectedIdSet.has(key.id)} aria-label={`Keyframe at ${key.time.toFixed(3)}s, value ${formatValue(key.value)}, ${sideTypesLabel(typesOf(key.id))}`} onClick={event => onSelectKeyframe(key.id, event.shiftKey || event.metaKey || event.ctrlKey)} className={cn("grid h-auto w-full grid-cols-[1fr_1fr_2fr] gap-2 whitespace-normal rounded px-2 py-1.5 text-left text-[11px] font-normal", selectedIdSet.has(key.id) && "bg-accent/10 text-accent")}>+ <span className="font-mono">{key.time.toFixed(3)}s</span><span className="min-w-0 break-words font-mono">{formatValue(key.value)}</span><span>{sideTypesLabel(typesOf(key.id))}</span>+ </Button></InterpolationMenu>)}{pageCount > 1 && <div className="flex items-center justify-between py-2"><Button variant="ghost" size="icon-sm" aria-label="Previous keyframe page" disabled={visiblePage === 1} onClick={() => setPage(visiblePage - 1)}><ChevronLeft size={14}/></Button><span className="text-[10px] text-fg-muted">Page {visiblePage} of {pageCount}</span>@@ -411,12 +471,19 @@ export function KeyframeEditorPanel({ clip, disabled = false, playheadTime = 0,</div>}</div>}</ScrollArea>- <div className="flex shrink-0 flex-wrap items-center gap-2 border-t border-border bg-bg-2 px-3 py-2 text-[11px]">- <span className="text-fg-2">Easing</span>- <Select value={selectedEasing} onValueChange={value => onUpdateKeyframes(selectedIds, { easing: value as Keyframe["easing"] })} disabled={disabled || !selectedIds.length}>- <SelectTrigger aria-label="Easing" className="h-7 w-40 bg-bg-1 px-2 text-[12px]"><SelectValue placeholder={selectedIds.length ? "Mixed" : "Select keyframes"}/></SelectTrigger>+ <div className="flex shrink-0 flex-wrap items-center gap-1.5 border-t border-border bg-bg-2 px-3 py-1.5 text-[11px]">+ <Select value={selectedEasing} onValueChange={value => onUpdateKeyframes(selectedIds, { easing: value as Keyframe["easing"] })} disabled={disabled || !selectedIds.length}>+ <SelectTrigger aria-label="Easing" className="h-7 w-32 bg-bg-1 px-2 text-[12px]"><SelectValue placeholder={selectedIds.length ? "Mixed" : "Select keyframes"}/></SelectTrigger><SelectContent>{EASING_TYPES.map(easing => <SelectItem key={easing} value={easing}>{easingLabel(easing)}</SelectItem>)}</SelectContent></Select>+ <Select value={interpSide} onValueChange={value => setInterpSide(value as KeyframeInterpolationSide)} disabled={disabled}>+ <SelectTrigger aria-label="Interpolation side" title="Which side of each selected keyframe an interpolation type applies to" className="h-7 w-24 bg-bg-1 px-2 text-[12px]"><SelectValue/></SelectTrigger>+ <SelectContent>{(Object.keys(KEYFRAME_INTERPOLATION_SIDE_LABELS) as KeyframeInterpolationSide[]).map(sideId => <SelectItem key={sideId} value={sideId}>{KEYFRAME_INTERPOLATION_SIDE_LABELS[sideId]}</SelectItem>)}</SelectContent>+ </Select>+ <Select value="" onValueChange={value => onApplyInterpolation?.(selectedIds, value as KeyframeInterpolationOp, interpSide)} disabled={disabled || !selectedIds.length || !onApplyInterpolation}>+ <SelectTrigger aria-label="Interpolation" className="h-7 w-32 bg-bg-1 px-2 text-[12px]"><SelectValue placeholder="Interpolation"/></SelectTrigger>+ <SelectContent>{KEYFRAME_INTERPOLATION_OPS.map(op => <SelectItem key={op} value={op}>{KEYFRAME_INTERPOLATION_LABELS[op]}</SelectItem>)}</SelectContent>+ </Select><div role="group" aria-label="Ease presets" className="flex flex-wrap gap-1">{PRESET_BUTTONS.map(preset => <Button key={preset.id} variant="ghost" size="sm" aria-label={`Apply ${preset.label}`}disabled={disabled || !selectedIds.length}diff --git a/apps/web/src/components/editor/MarkersPanel.tsx b/apps/web/src/components/editor/MarkersPanel.tsxindex 96a92c84..37211c78 100644--- a/apps/web/src/components/editor/MarkersPanel.tsx+++ b/apps/web/src/components/editor/MarkersPanel.tsx@@ -2,6 +2,7 @@ import { useEffect, useMemo, useRef, useState } from "react";import { MARKER_KINDS, sortMarkers, type Marker, type MarkerKind } from "@openreel/core";import { Button, Input } from "@openreel/ui";import { Bookmark, Download, Plus, Trash2 } from "@/icons/lucide-compat";+import { ClipMarkersList } from "./ClipMarkersList";import { useEditorWorkspaceStore } from "../../stores/editor-workspace-store";import { useProjectStore } from "../../stores/project-store";import { useTimelineStore } from "../../stores/timeline-store";@@ -50,6 +51,8 @@ export function MarkersPanel() {const selectedId = useEditorWorkspaceStore((s) => s.selectedMarkerId);const setSelectedId = useEditorWorkspaceStore((s) => s.setSelectedMarkerId);const playhead = useTimelineStore((s) => s.playheadPosition);+ const scope = useEditorWorkspaceStore((s) => s.markerScope);+ const setScope = useEditorWorkspaceStore((s) => s.setMarkerScope);const [query, setQuery] = useState("");const [kindFilter, setKindFilter] = useState<MarkerKind | "all">("all");@@ -168,7 +171,7 @@ export function MarkersPanel() {{markers.length}</span></h2>- <div className="flex gap-1">+ <div className={`flex gap-1 ${scope === "clips" ? "hidden" : ""}`}><Buttonvariant="ghost"size="sm"@@ -192,15 +195,30 @@ export function MarkersPanel() {</Button></div></div>- <Input+ <div role="tablist" aria-label="Marker scope" className="flex gap-1 rounded-md bg-bg-2 p-0.5">+ {(["sequence", "clips"] as const).map((value) => (+ <button+ key={value}+ type="button"+ role="tab"+ aria-selected={scope === value}+ data-testid={`markers-scope-${value}`}+ onClick={() => setScope(value)}+ className={`h-6 flex-1 rounded px-2 text-[12px] ${scope === value ? "bg-bg-1 font-medium text-fg shadow-sm" : "text-fg-muted hover:text-fg"}`}+ >+ {value === "sequence" ? "Sequence" : "Clips"}+ </button>+ ))}+ </div>+ {scope === "sequence" && <Inputaria-label="Search markers"placeholder="Search names and comments"value={query}onChange={(event) => setQuery(event.target.value)}onKeyDown={(event) => event.stopPropagation()}className="h-7 text-[12px]"- />- <div className="flex gap-2">+ />}+ {scope === "sequence" && <div className="flex gap-2"><selectaria-label="Filter by type"className={`${SELECT_CLASS} flex-1`}@@ -227,11 +245,13 @@ export function MarkersPanel() {</option>))}</select>- </div>+ </div>}</header><div className="min-h-0 flex-1 overflow-auto">- {markers.length === 0 ? (+ {scope === "clips" ? (+ <ClipMarkersList />+ ) : markers.length === 0 ? (<p className="px-4 py-8 text-center text-[12px] text-fg-muted" data-testid="markers-empty">No markers yet. Press M to drop one at the playhead, or Alt-drag the ruler for a range.</p>@@ -409,12 +429,12 @@ export function MarkersPanel() {)}</div>- <footer className="flex items-center gap-1.5 border-t border-border px-3 py-2">+ {scope === "sequence" && <footer className="flex items-center gap-1.5 border-t border-border px-3 py-2"><span className="mr-auto text-[11px] text-fg-muted">Export</span>{exportButton("chapters", "Chapters")}{exportButton("csv", "CSV")}{exportButton("edl", "EDL")}- </footer>+ </footer>}</section>);}diff --git a/apps/web/src/components/editor/Preview.tsx b/apps/web/src/components/editor/Preview.tsxindex fefb3034..f951da06 100644--- a/apps/web/src/components/editor/Preview.tsx+++ b/apps/web/src/components/editor/Preview.tsx@@ -1,3 +1,4 @@+import { selectVoiceOverPlaybackMuted, useVoiceOverStore } from "../../services/voiceover/voiceover-recorder";import { clipNeedsFrameProcessing, preparePreviewFrame, renderOverlayLayerWithEffects } from "./preview/frame-processing";import { inputTransformForClip } from "./preview/clip-input-transform";import { usePhoneEditor } from "../../hooks/usePhoneEditor";@@ -10,6 +11,7 @@ import { notifyPreviewDeviceLoss, registerProgramRenderer } from "./preview/deviimport { ProgramMonitorOverlays } from "./preview/ProgramMonitorOverlays";import { DynamicTrimTwoUp } from "./preview/DynamicTrimTwoUp";import { MotionTrackingOverlay } from "./preview/MotionTrackingOverlay";+import { PlanarTrackOverlay } from "./preview/PlanarTrackOverlay";import { registerProgramFrameControl } from "./preview/program-frame-control";import React, {useRef,@@ -35,6 +37,7 @@ import {} from "@/icons/lucide-compat";import { cn } from "@openreel/ui";import { useProjectStore } from "../../stores/project-store";+import { currentBurnInSource } from "../../utils/burn-in-source";import { useEditPointStore } from "../../stores/edit-point-store";import { getMonitorProject } from "../../services/dynamic-trim";import { startLiveDuckingSync } from "../../services/live-ducking-sync";@@ -161,10 +164,12 @@ import { editingFrameDurationMs } from "./editing-frame-rate";import {getPersonSegmentationEngine,getBackgroundRemovalEngine,+ withBurnInText,createMotionAwareOcclusionMask,getStabilizedTransform,getVidstabEngine,frameConformFor,+ clipHasTemporalEffects,interpretedDisplaySize,} from "@openreel/core";import {@@ -216,12 +221,19 @@ const applyPreviewAdjustmentLayers = async (canvas: OffscreenCanvas,ctx: CanvasRenderingContext2D | OffscreenCanvasRenderingContext2D,layers: readonly AdjustmentLayer[],+ time: number,): Promise<boolean> => {let applied = false;const effectsBridge = getEffectsBridge();if (!effectsBridge.isInitialized()) return false;for (const layer of layers) {- const effects = layer.effects.filter((effect) => effect.enabled !== false);+ // Burn-ins on an adjustment layer count from the layer's first frame, like a clip's.+ const effects = withBurnInText(+ layer.effects.filter((effect) => effect.enabled !== false),+ { id: layer.id, startTime: layer.startTime, inPoint: 0 },+ time - layer.startTime,+ currentBurnInSource(),+ ) as Effect[];if (effects.length === 0) continue;let source: ImageBitmap | null = null;let processed: ImageBitmap | null = null;@@ -1054,7 +1066,7 @@ export const Preview: React.FC = () => {const getResolvedClipPlaybackParams = useCallback((clip: PreviewClip) =>resolveClipPlaybackAudioParams(clip, {tracks: timelineTracksRef.current,- }), []);+ }, useProjectStore.getState().getMediaItem(clip.mediaId)), []);const rendererRef = useRef<Renderer | null>(null);const rendererInitializedRef = useRef<boolean>(false);@@ -1066,7 +1078,10 @@ export const Preview: React.FC = () => {motionRendererRef.current = null;}, []);- const [isMuted, setIsMuted] = useState(false);+ const [userMuted, setIsMuted] = useState(false);+ // Voice-over recording silences playback (when asked to) so speakers cannot feed back into the microphone.+ const recordMuted = useVoiceOverStore(selectVoiceOverPlaybackMuted);+ const isMuted = userMuted || recordMuted;const [isRenderBridgeReady, setIsRenderBridgeReady] = useState(false);const [canvasSize, setCanvasSize] = useState({ width: 0, height: 0 });const [videoAreaSize, setVideoAreaSize] = useState({ width: 0, height: 0 });@@ -1450,7 +1465,8 @@ export const Preview: React.FC = () => {// Get subtitles from project timelineconst allSubtitles = useMemo(() => {- return project.timeline.subtitles || [];+ // Hidden tracks (a translation not chosen for the picture) are not drawn.+ return (project.timeline.subtitles || []).filter((cue) => !cue.hidden);}, [project.timeline.subtitles]);const updateClipTransform = useProjectStore(@@ -2213,6 +2229,7 @@ export const Preview: React.FC = () => {pan: 0,muted: audioTrack.muted || false,solo: audioTrack.solo || false,+ soloSafe: audioTrack.soloSafe === true,effects: [],});@@ -2572,6 +2589,7 @@ export const Preview: React.FC = () => {trackId: track.id,muted: track.muted === true || track.hidden === true,solo: track.solo === true,+ soloSafe: track.soloSafe === true,})),);return audioGraphRef.current;@@ -2775,17 +2793,20 @@ export const Preview: React.FC = () => {} catch (error) {if (!isStaleRequest()) {console.warn("Paused video frame decoding failed", error);- failProxyPlayback(clip.mediaId, mediaBlob);const cached = videoElementCacheRef.current.get(clip.mediaId);if (cached?.blob === mediaBlob) {releaseVideoElement(cached);videoElementCacheRef.current.delete(clip.mediaId);}if (!retried) {+ // A slow or software decoder can fail once on a fresh element (metadata or seek timeout). Only a+ // second failure on a new element means the proxy cannot play; disabling it on the first+ // would drop a working proxy for good.retried = true;await decodePausedFrame();return;}+ failProxyPlayback(clip.mediaId, mediaBlob);scheduleScrubVideoRelease();if (fallbackMediaTime !== null) {const fallback = await decodeFrameWithWebCodecs(mediaBlob, fallbackMediaTime).catch((fallbackError: unknown) => {@@ -2868,7 +2889,7 @@ export const Preview: React.FC = () => {!track.hidden &&track.clips.some((clip) =>- getCompoundClipId(clip) !== null &&+ (getCompoundClipId(clip) !== null || clipHasTemporalEffects(clip)) &&time >= clip.startTime &&time < clip.startTime + clip.duration,),@@ -2934,7 +2955,7 @@ export const Preview: React.FC = () => {const { base, placements } = isolatedTrack;isolatedTrack = null;try {- if (await applyPreviewAdjustmentLayers(frameCanvas, ctx, placements.map((p) => p.layer))) {+ if (await applyPreviewAdjustmentLayers(frameCanvas, ctx, placements.map((p) => p.layer), time)) {hasRenderedFrame = true;}ctx.save();@@ -2961,7 +2982,7 @@ export const Preview: React.FC = () => {await closeIsolatedTrack();const compositeLayers = adjustmentSchedule.takeCompositeBefore(stackIndex);if (compositeLayers.length > 0) {- await applyPreviewAdjustmentLayers(frameCanvas, ctx, compositeLayers.map((p) => p.layer));+ await applyPreviewAdjustmentLayers(frameCanvas, ctx, compositeLayers.map((p) => p.layer), time);}if (scopedPlacements.length > 0 && hasContent) {// Paint this stage alone on a clear canvas so the effects reach only it; the backdrop returns beneath.@@ -3406,7 +3427,7 @@ export const Preview: React.FC = () => {await closeIsolatedTrack();const remainingLayers = adjustmentSchedule.takeRemainingComposite();if (remainingLayers.length > 0) {- if (await applyPreviewAdjustmentLayers(frameCanvas, ctx, remainingLayers.map((p) => p.layer))) {+ if (await applyPreviewAdjustmentLayers(frameCanvas, ctx, remainingLayers.map((p) => p.layer), time)) {hasRenderedFrame = true;}}@@ -3939,6 +3960,10 @@ export const Preview: React.FC = () => {if (frameConformFor(mediaItem) !== null) {return { canUse: false, clips: [] };}+ // Echo / Posterize Time need frames other than the one the element is playing.+ if (clipHasTemporalEffects(clip)) {+ return { canUse: false, clips: [] };+ }if (clipSpeed !== 1 ||isReverse ||@@ -4214,6 +4239,7 @@ export const Preview: React.FC = () => {pan: 0,muted: audioTrack.muted || false,solo: audioTrack.solo || false,+ soloSafe: audioTrack.soloSafe === true,effects: [],});}@@ -4759,7 +4785,7 @@ export const Preview: React.FC = () => {return JSON.stringify([clip.id, token, canvas.width, canvas.height, video.readyState >= HTMLMediaElement.HAVE_CURRENT_DATA,transform, clipCssFilterOnly(clip.id, clip), canvasFillModeRef.current, canvasFillColorRef.current,- previewBgRef.current, isColorBypassed(),+ previewBgRef.current, isColorBypassed(), getEffectsBridge().whiteBalanceInputView(),]);})();if (!frameGate.shouldDraw(gateKey)) {@@ -5718,6 +5744,7 @@ export const Preview: React.FC = () => {pan: 0,muted: track.muted || false,solo: track.solo || false,+ soloSafe: track.soloSafe === true,effects: [],});}@@ -5935,8 +5962,9 @@ export const Preview: React.FC = () => {}}+ // Echo / Posterize Time pick other frames of the clip: the engine renderer (export's) decodes them.const hasActiveCompound = activeClips.some(- ({ clip }) => getCompoundClipId(clip) !== null,+ ({ clip }) => getCompoundClipId(clip) !== null || clipHasTemporalEffects(clip),);// Anamorphic / interlaced footage is conformed by the engine renderer, never the raw video-element draw.const hasActiveConformClip = activeClips.some(({ clip }) => {@@ -8540,7 +8568,7 @@ export const Preview: React.FC = () => {<ShadcnButton variant="ghost" size="icon-sm" title={`Loop ${formatFrameTimecode(previewLoopRange?.start ?? 0, settings.frameRate)} to ${formatFrameTimecode(previewLoopRange?.end ?? 0, settings.frameRate)} • I: mark start • O: mark end • Shift+L: toggle`} aria-pressed={loopEnabled} onClick={handleToggleLoop} type="button" aria-label={loopEnabled ? "Disable preview loop" : "Enable preview loop"} disabled={(actualEndTime <= 0 || exportState.isExporting)} className={cn("inline-flex shrink-0 items-center justify-center rounded-[7px] outline-none transition-colors focus-visible:ring-2 focus-visible:ring-ring disabled:pointer-events-none disabled:opacity-50", "h-7 w-7", "bg-transparent text-fg-muted hover:bg-bg-2 hover:text-fg", `w-[34px] h-[34px] grid place-items-center rounded-[7px] transition-colors ${loopEnabled ? "bg-accent/15 text-accent" : "bg-bg-2 text-fg-2 hover:bg-bg-3 hover:text-fg"}`)}>{<PreviewTransportIcon name="loop" size={16} strokeWidth={1.8} />}</ShadcnButton>- <ShadcnButton variant="ghost" size="icon-sm" onClick={() => setIsMuted(!isMuted)} type="button" aria-label={isMuted ? "Unmute" : "Mute"} title={isMuted ? "Unmute" : "Mute"} className={cn("inline-flex shrink-0 items-center justify-center rounded-[7px] outline-none transition-colors focus-visible:ring-2 focus-visible:ring-ring disabled:pointer-events-none disabled:opacity-50", "h-7 w-7", "bg-transparent text-fg-muted hover:bg-bg-2 hover:text-fg", `w-[34px] h-[34px] grid place-items-center rounded-[7px] transition-colors ${+ <ShadcnButton variant="ghost" size="icon-sm" onClick={() => setIsMuted(!userMuted)} type="button" aria-label={isMuted ? "Unmute" : "Mute"} title={isMuted ? "Unmute" : "Mute"} className={cn("inline-flex shrink-0 items-center justify-center rounded-[7px] outline-none transition-colors focus-visible:ring-2 focus-visible:ring-ring disabled:pointer-events-none disabled:opacity-50", "h-7 w-7", "bg-transparent text-fg-muted hover:bg-bg-2 hover:text-fg", `w-[34px] h-[34px] grid place-items-center rounded-[7px] transition-colors ${isMuted? "bg-bg-2 text-status-error": "bg-bg-2 text-fg-2 hover:text-fg hover:bg-bg-3"@@ -8644,6 +8672,7 @@ export const Preview: React.FC = () => {<ProgramMonitorOverlays /><DynamicTrimTwoUp /><MotionTrackingOverlay clipId={(selectedClip || clipAtPlayhead)?.id ?? null} bounds={clipBounds} />+ <PlanarTrackOverlay clipId={(selectedClip || clipAtPlayhead)?.id ?? null} bounds={clipBounds} />{decoderLimitHit && (<div role="status" aria-live="polite" data-testid="decoder-limit-notice" className="absolute left-1/2 top-3 z-30 w-max max-w-[min(92%,34rem)] -translate-x-1/2 rounded-md border border-border bg-bg-2 px-2.5 py-1.5 text-[11px] text-fg-2 shadow-sm">diff --git a/apps/web/src/components/editor/ProxyIngestPanel.tsx b/apps/web/src/components/editor/ProxyIngestPanel.tsxindex 5f64668c..cf749628 100644--- a/apps/web/src/components/editor/ProxyIngestPanel.tsx+++ b/apps/web/src/components/editor/ProxyIngestPanel.tsx@@ -4,6 +4,8 @@ import { ChevronDown, ChevronRight } from "@/icons/lucide-compat";import {DESKTOP_PROXY_CODECS,DESKTOP_PROXY_SIZES,+ PROXY_PRESETS,+ proxyPresetForProfile,PROXY_STATE_LABEL,formatProxyCounts,proxyDisplayState,@@ -11,11 +13,13 @@ import {resolveDesktopProxyProfile,summarizeProxyStates,type DesktopProxyCodec,+ type ProxyPresetId,type DesktopProxySize,type IngestPreset,type MediaItem,type ProxyDisplayState,} from "@openreel/core";+import { CreateProxiesDialog } from "./CreateProxiesDialog";import { useProjectStore } from "../../stores/project-store";import { useUIStore } from "../../stores/ui-store";import { usePreviewProxyStore } from "../../stores/preview-proxy-store";@@ -126,6 +130,7 @@ export const ProxyIngestPanel: React.FC = () => {const rows = useProxyRows();const [open, setOpen] = useState(false);const [moreOpen, setMoreOpen] = useState(false);+ const [dialogOpen, setDialogOpen] = useState(false);const desktop = desktopIngestAvailable();const preset = useProjectStore((s) => s.project.mediaLibrary.ingestPreset ?? "none");const ingestConfig = useProjectStore((s) => s.project.mediaLibrary.desktopIngest);@@ -246,11 +251,27 @@ export const ProxyIngestPanel: React.FC = () => {</div>{desktop ? (<div className="space-y-2" data-testid="desktop-ingest-settings">+ <label className="block min-w-0 text-fg-muted">+ Proxy preset+ <Select+ value={proxyPresetForProfile(profile) ?? "custom"}+ onValueChange={(value) => {+ const chosen = PROXY_PRESETS.find((entry) => entry.id === (value as ProxyPresetId));+ if (chosen) void setDesktopProxyProfile(chosen.profile);+ }}+ >+ <SelectTrigger aria-label="Proxy preset" className="mt-1 h-8 min-w-0 text-[11px]"><SelectValue /></SelectTrigger>+ <SelectContent>+ {PROXY_PRESETS.map((entry) => <SelectItem key={entry.id} value={entry.id}>{entry.label}</SelectItem>)}+ {proxyPresetForProfile(profile) === null && <SelectItem value="custom" disabled>Custom</SelectItem>}+ </SelectContent>+ </Select>+ </label><div className="grid grid-cols-2 gap-2"><label className="min-w-0 text-fg-muted">Proxy format<Select value={profile.codec} onValueChange={(value) => void setDesktopProxyProfile({ ...profile, codec: value as DesktopProxyCodec })}>- <SelectTrigger aria-label="Proxy format" className="mt-1 h-8 min-w-0 text-[11px]"><SelectValue>{profile.codec === "prores-proxy" ? "ProRes Proxy" : "H.264"}</SelectValue></SelectTrigger>+ <SelectTrigger aria-label="Proxy format" className="mt-1 h-8 min-w-0 text-[11px]"><SelectValue>{profile.codec === "prores-proxy" ? "ProRes Proxy" : profile.codec === "dnxhr-lb" ? "DNxHR LB" : "H.264"}</SelectValue></SelectTrigger><SelectContent>{DESKTOP_PROXY_CODECS.map((codec) => <SelectItem key={codec.id} value={codec.id}>{codec.label}</SelectItem>)}</SelectContent>@@ -331,6 +352,11 @@ export const ProxyIngestPanel: React.FC = () => {<Button type="button" variant="secondary" className={smallButton} onClick={create} disabled={!createTargets.length} aria-label="Create proxies">{targets.length ? "Create for selected" : "Create proxies"}</Button>+ {desktop && (+ <Button type="button" variant="secondary" className={smallButton} onClick={() => setDialogOpen(true)} disabled={!createTargets.length} aria-label="Create proxies with a preset">+ Preset…+ </Button>+ )}<Button type="button" variant="secondary" className={smallButton} onClick={() => void retryFailed()} disabled={!counts.failed} aria-label="Retry failed proxies">Retry failed{counts.failed ? ` (${counts.failed})` : ""}</Button>@@ -390,6 +416,15 @@ export const ProxyIngestPanel: React.FC = () => {</div></PopoverContent></Popover>+ {desktop && (+ <CreateProxiesDialog+ open={dialogOpen}+ onOpenChange={setDialogOpen}+ count={createTargets.length}+ scopeLabel={targets.length ? "selected" : "without a proxy"}+ onCreate={create}+ />+ )}</section>);};diff --git a/apps/web/src/components/editor/SourceMonitor.tsx b/apps/web/src/components/editor/SourceMonitor.tsxindex 665a6cfd..f7fc75e5 100644--- a/apps/web/src/components/editor/SourceMonitor.tsx+++ b/apps/web/src/components/editor/SourceMonitor.tsx@@ -1,6 +1,7 @@import React, { useCallback, useEffect, useRef, useState } from "react";-import { Button } from "@openreel/ui";+import { Button, DropdownMenu, DropdownMenuContent, DropdownMenuItem, DropdownMenuTrigger } from "@openreel/ui";import { getRawDeveloper, isDevelopedRaw, mediaImageVersion, type MediaItem } from "@openreel/core";+import { addSourceMarker } from "../../services/clip-marker-commands";import { useProjectStore } from "../../stores/project-store";import { useTimelineStore } from "../../stores/timeline-store";import { useSourceMonitorStore } from "../../stores/source-monitor-store";@@ -15,10 +16,14 @@ import {stepSourceFrame,} from "../../services/source-monitor-controller";import {+ fitToFillFromSource,+ openInSourceMonitor,insertFromSource,overwriteFromSource,+ replaceFromSource,} from "../../services/source-monitor-commands";-import { runWithToast } from "../../services/premiere-edit-commands";+import { StallWatchdog, sampleMedia } from "../../services/media-stall";+import { reverseMatchFrame, runWithToast } from "../../services/premiere-edit-commands";import { makeSubclipFromSource } from "../../services/project-panel-commands";import { toast } from "../../stores/notification-store";import { PreviewScrubber } from "./PreviewScrubber";@@ -29,6 +34,48 @@ import { SourcePatch } from "./SourcePatch";/** Drag payload marker read by the timeline lanes. */export const SOURCE_DRAG_KEY = "sourceMonitor";+/** Recent-clips dropdown in the Source monitor header (Premiere's source history). */+function SourceHistory({ current }: { current: MediaItem | undefined }) {+ const history = useSourceMonitorStore((s) => s.history);+ const library = useProjectStore((s) => s.project.mediaLibrary.items);+ const entries = history+ .map((id) => library.find((item) => item.id === id))+ .filter((item): item is MediaItem => !!item);+ if (entries.length === 0)+ return <span>{current ? current.name : "No clip loaded"}</span>;+ return (+ <DropdownMenu>+ <DropdownMenuTrigger asChild>+ <button+ type="button"+ data-testid="source-history"+ aria-label="Recent source clips"+ title="Recent clips"+ className="flex max-w-[260px] items-center gap-1 rounded px-1.5 py-0.5 hover:bg-[#26282d]"+ >+ <span className="truncate">{current ? current.name : "No clip loaded"}</span>+ <svg width="10" height="10" viewBox="0 0 10 10" fill="none" stroke="currentColor" strokeWidth="1.5" aria-hidden="true"><path d="M2 3.5 5 6.5 8 3.5" /></svg>+ </button>+ </DropdownMenuTrigger>+ <DropdownMenuContent align="start" className="max-h-72 min-w-[220px] overflow-y-auto">+ {entries.map((item) => (+ <DropdownMenuItem+ key={item.id}+ data-testid="source-history-item"+ onSelect={() => {+ const outcome = openInSourceMonitor(item.id);+ if (!outcome.success) toast.warning("Source monitor", outcome.message ?? "");+ }}+ className={item.id === current?.id ? "font-medium text-accent" : undefined}+ >+ <span className="truncate">{item.name}</span>+ </DropdownMenuItem>+ ))}+ </DropdownMenuContent>+ </DropdownMenu>+ );+}+function useBlobUrl(blob: Blob | null | undefined): string | null {const [url, setUrl] = useState<string | null>(null);useEffect(() => {@@ -144,6 +191,8 @@ export function SourceMonitor() {const [restrictSubclip, setRestrictSubclip] = useState(false);const marks = useSourceMonitorStore((s) => (s.mediaId ? s.marks[s.mediaId] : undefined));const projectFrameRate = useProjectStore((s) => s.project.settings.frameRate);+ const replaceKeeps = useSourceMonitorStore((s) => s.replaceKeepsAttributes);+ const rangeMarked = useTimelineStore((s) => s.loopEnd - s.loopStart > 1e-6);const media = useProjectStore((s) =>mediaId ? s.project.mediaLibrary.items.find((m) => m.id === mediaId) : undefined,);@@ -236,6 +285,18 @@ export function SourceMonitor() {if (Math.abs(el.currentTime - position) > 0.0005) el.currentTime = position;}, [position, rate, url]);+ // Recover from a wedged media pipeline: after seeks Chrome can leave a fully buffered element+ // without future data ("waiting") forever. Re-issuing the seek restarts it.+ useEffect(() => {+ const el = elRef.current;+ if (!el) return;+ const watchdog = new StallWatchdog();+ const id = window.setInterval(() => {+ if (watchdog.check(sampleMedia(el), performance.now())) el.currentTime = sampleMedia(el).currentTime;+ }, 250);+ return () => window.clearInterval(id);+ }, [mediaId, url]);+const onDragStart = useCallback((component: "both" | "video" | "audio") => (event: React.DragEvent) => {if (!mediaId) return;@@ -274,8 +335,9 @@ export function SourceMonitor() {><div className="workspace-preview-header"><MonitorTabs active="source" />- <span>{media ? media.name : "No clip loaded"}</span>+ <SourceHistory current={media} /><div className="workspace-preview-options">+ <Button type="button" variant="ghost" size="sm" data-testid="reverse-match-frame" title="Reverse Match Frame (Shift+F)" onMouseDown={noFocusSteal} disabled={!media} onClick={() => runWithToast("Reverse match frame", reverseMatchFrame)}>Find in sequence</Button><span className="font-mono text-[11px] tabular-nums text-fg-3" data-testid="source-duration">{media ? `Dur ${tc(rangeLength)}` : ""}</span>@@ -348,6 +410,21 @@ export function SourceMonitor() {/></div>)}+ {media?.markers?.map((m) => (+ <button+ key={m.id}+ type="button"+ data-testid="source-marker-tick"+ aria-label={`Go to marker ${m.label}`}+ title={m.label}+ onMouseDown={noFocusSteal}+ onClick={() => seekSource(m.time)}+ className="absolute top-[1px] z-10 h-[9px] w-[9px] -translate-x-1/2 p-0"+ style={{ left: `calc(0.75rem + (100% - 1.5rem) * ${Math.min(1, m.time / duration)})` }}+ >+ <svg width="9" height="9" viewBox="0 0 9 9" aria-hidden="true"><path d="M0.5 0.5h8v4l-4 4-4-4z" fill={m.color} stroke="rgba(0,0,0,0.55)" /></svg>+ </button>+ ))}<PreviewScrubberposition={position}duration={duration}@@ -375,7 +452,8 @@ export function SourceMonitor() {{rate !== 0 && <span className="text-accent" data-testid="source-rate">{rate}x</span>}</div>{media && <SourcePatch hasVideo={hasVideo} hasAudio={hasAudio} />}- <div className="ml-auto flex items-center gap-2">+ <div className="ml-auto flex flex-wrap items-center justify-end gap-2 [&>*]:whitespace-nowrap">+ <Button type="button" variant="ghost" size="sm" data-testid="source-add-marker" title="Add a master-clip marker at the playhead (M)" onMouseDown={noFocusSteal} disabled={!media} onClick={() => void addSourceMarker()}>Add marker</Button><Button type="button" variant="ghost" size="sm" onMouseDown={noFocusSteal} disabled={!media || (marks?.in === undefined && marks?.out === undefined)} onClick={clearSourceMarks}>Clear marks</Button>{hasVideo && media?.type === "video" && (<span@@ -437,8 +515,54 @@ export function SourceMonitor() {</Button></>)}- <Button type="button" variant="secondary" size="sm" onMouseDown={noFocusSteal} disabled={!media} onClick={() => runWithToast("Insert", () => insertFromSource())}>Insert (,)</Button>- <Button type="button" variant="secondary" size="sm" onMouseDown={noFocusSteal} disabled={!media} onClick={() => runWithToast("Overwrite", () => overwriteFromSource())}>Overwrite (.)</Button>+ <Button type="button" variant="secondary" size="sm" onMouseDown={noFocusSteal} disabled={!media} aria-label="Insert (,)" title="Insert at the timeline playhead (,)" onClick={() => runWithToast("Insert", () => insertFromSource())}>Insert</Button>+ <Button type="button" variant="secondary" size="sm" onMouseDown={noFocusSteal} disabled={!media} aria-label="Overwrite (.)" title="Overwrite at the timeline playhead (.)" onClick={() => runWithToast("Overwrite", () => overwriteFromSource())}>Overwrite</Button>+ <Button+ type="button"+ variant="secondary"+ size="sm"+ data-testid="replace-edit"+ aria-label="Replace (⇧G)"+ title="Replace the selected timeline clip, or the clip under the playhead, with this source. The clip keeps its place and length; the Source playhead lines up with the timeline playhead (Shift+G)"+ onMouseDown={noFocusSteal}+ disabled={!media}+ onClick={() => runWithToast("Replace", () => replaceFromSource())}+ >+ Replace+ </Button>+ <Button+ type="button"+ variant="ghost"+ size="sm"+ data-testid="replace-keep"+ aria-pressed={replaceKeeps}+ title="Replace keeps the clip's effects, keyframes and audio settings. Off resets them."+ onMouseDown={noFocusSteal}+ disabled={!media}+ onClick={() => useSourceMonitorStore.getState().setReplaceKeepsAttributes(!replaceKeeps)}+ className={replaceKeeps ? "bg-[#26282d] text-fg" : "text-fg-3"}+ >+ Keep FX+ </Button>+ <Button+ type="button"+ variant="secondary"+ size="sm"+ data-testid="fit-to-fill"+ aria-label="Fit to Fill (⌥⇧F)"+ title={+ media?.type === "image"+ ? "Fit to Fill needs video or audio"+ : rangeMarked+ ? "Retime the source In/Out to exactly fill the timeline In/Out range (Alt+Shift+F)"+ : "Set In and Out marks on the timeline to fill (Alt+Shift+F)"+ }+ onMouseDown={noFocusSteal}+ disabled={!media || media.type === "image" || !rangeMarked}+ onClick={() => runWithToast("Fit to Fill", () => fitToFillFromSource())}+ >+ Fit to Fill+ </Button></div></div></div>diff --git a/apps/web/src/components/editor/Timeline.tsx b/apps/web/src/components/editor/Timeline.tsxindex ee51f1fd..bee84ef6 100644--- a/apps/web/src/components/editor/Timeline.tsx+++ b/apps/web/src/components/editor/Timeline.tsx@@ -173,6 +173,7 @@ export const Timeline: React.FC<{ onOpenMedia?: () => void }> = ({ onOpenMedia }lockTrack,muteTrack,soloTrack,+ setTrackSoloSafe,renameTrack,removeTrack,} = useProjectStore(useShallow((state) => ({@@ -191,6 +192,7 @@ export const Timeline: React.FC<{ onOpenMedia?: () => void }> = ({ onOpenMedia }lockTrack: state.lockTrack,muteTrack: state.muteTrack,soloTrack: state.soloTrack,+ setTrackSoloSafe: state.setTrackSoloSafe,renameTrack: state.renameTrack,removeTrack: state.removeTrack,})));@@ -1331,6 +1333,20 @@ export const Timeline: React.FC<{ onOpenMedia?: () => void }> = ({ onOpenMedia }>S</ShadcnButton>+ <ShadcnButton variant="ghost" size="sm"+ type="button"+ aria-label={`Solo safe ${name}`}+ title="Solo safe: stays audible when other tracks are soloed"+ aria-pressed={!!track.soloSafe}+ onClick={() => void setTrackSoloSafe(track.id, !track.soloSafe)}+ className={`flex h-7 min-w-7 items-center justify-center rounded-md px-1 text-[10px] font-black transition-colors ${+ track.soloSafe+ ? "bg-accent text-bg hover:bg-accent/90"+ : "text-fg-muted hover:bg-hover hover:text-fg"+ }`}+ >+ SF+ </ShadcnButton></>) : null}<ShadcnButton variant="ghost" size="icon-sm" aria-pressed={track.locked} onClick={() => void lockTrack(track.id, !track.locked)} type="button" aria-label={`Lock ${name}`} title={`Lock ${name}`} className={cn("inline-flex shrink-0 items-center justify-center rounded-[7px] outline-none transition-colors focus-visible:ring-2 focus-visible:ring-ring disabled:pointer-events-none disabled:opacity-50", "h-7 w-7", (track.locked ? "border border-border bg-bg-2 text-fg-2 hover:bg-bg-3 hover:text-fg" : "bg-transparent text-fg-muted hover:bg-bg-2 hover:text-fg"))}>diff --git a/apps/web/src/components/editor/TranscriptPanel.tsx b/apps/web/src/components/editor/TranscriptPanel.tsxindex 6c3636f8..f8ac78dd 100644--- a/apps/web/src/components/editor/TranscriptPanel.tsx+++ b/apps/web/src/components/editor/TranscriptPanel.tsx@@ -5,7 +5,12 @@ import {DEFAULT_FILLER_PHRASES,buildTranscript,cutDuration,+ SPEAKER_PALETTE,+ defaultSpeakerName,findFillerWords,+ findSpeakerProfile,+ type SpeakerPosition,+ type SpeakerProfile,findPauses,listCaptionTracks,listSpeakers,@@ -27,6 +32,7 @@ import {SelectItem,SelectTrigger,SelectValue,+ Switch,} from "@openreel/ui";import { useProjectStore } from "../../stores/project-store";import { useTimelineStore } from "../../stores/timeline-store";@@ -36,7 +42,12 @@ import {exportCaptionBytes,importCaptionBytes,renameTranscriptSpeaker,+ setCaptionSpeaker,+ setCaptionTrackInPicture,+ updateSpeakerProfile,} from "../../services/transcript-commands";+import { diarizeCaptions } from "../../services/diarization";+import { CaptionTranslateSection } from "./CaptionTranslateSection";import { formatFrameTimecode } from "../../utils/frame-timecode";/** Programme start timecode written into / read out of broadcast caption files. */@@ -54,9 +65,17 @@ function broadcastFrameRate(format: CaptionExportFormat | "import", fps: number)return [24, 25, 29.97, 30].find(near);}+/** Parse errors of an import as panel notes (one per skipped cue / block). */+function skippedNotes(errors: readonly string[] | undefined): CaptionFormatIssue[] {+ return (errors ?? []).slice(0, 50).map((message) => ({ severity: "warning" as const, code: "import-skipped", message: `Skipped: ${message}` }));+}+/** Radix Select items cannot have an empty value; the default caption track ("") uses this. */const DEFAULT_TRACK_VALUE = "__default__";+/** Used only until a speaker has a stored profile (same order as the core palette). */+const SPEAKER_FALLBACK = SPEAKER_PALETTE;+const seconds = (value: number) => `${(Math.round(value * 100) / 100).toFixed(2)}s`;interface WordProps {@@ -89,7 +108,7 @@ const Word = memo(function Word({ word, active, selected, matched, removing }: W);});-function SpeakerLabel({ name, onRename }: { name?: string; onRename: (from: string, to: string) => void }) {+function SpeakerLabel({ name, color, onRename }: { name?: string; color?: string; onRename: (from: string, to: string) => void }) {const [editing, setEditing] = useState(false);const [draft, setDraft] = useState(name ?? "");useEffect(() => setDraft(name ?? ""), [name]);@@ -122,14 +141,101 @@ function SpeakerLabel({ name, onRename }: { name?: string; onRename: (from: strititle="Rename speaker"aria-label={`Speaker ${name}. Click to rename`}onClick={() => setEditing(true)}- className="select-none rounded px-1 text-[11px] font-semibold text-accent hover:bg-bg-3"+ className="flex select-none items-center gap-1 rounded px-1 text-[11px] font-semibold text-accent hover:bg-bg-3"+ style={color ? { color } : undefined}>+ {color && <span aria-hidden className="size-2 rounded-full" style={{ backgroundColor: color }} />}{name}</button>);}-type Tool = "fillers" | "pauses" | null;+const NEW_SPEAKER = "__new__";+const NO_SPEAKER = "__none__";++function SpeakerReassign({+ current,+ names,+ onAssign,+}: {+ current?: string;+ names: string[];+ onAssign: (speaker: string) => void;+}) {+ return (+ <select+ aria-label="Reassign speaker for this passage"+ title="Reassign this passage to another speaker"+ value={current ?? NO_SPEAKER}+ onChange={(e) => {+ const v = e.currentTarget.value;+ if (v === NEW_SPEAKER) {+ let n = names.length + 1;+ while (names.includes(defaultSpeakerName(n))) n++;+ onAssign(defaultSpeakerName(n));+ } else onAssign(v === NO_SPEAKER ? "" : v);+ }}+ onKeyDown={(e) => e.stopPropagation()}+ className="h-5 max-w-[88px] rounded border border-border bg-bg-2 px-0.5 text-[10px] text-fg-3 hover:text-fg"+ >+ <option value={NO_SPEAKER}>No speaker</option>+ {names.map((n) => (+ <option key={n} value={n}>+ {n}+ </option>+ ))}+ <option value={NEW_SPEAKER}>New speaker</option>+ </select>+ );+}++const POSITION_AUTO = "auto";++function SpeakerRow({+ profile,+ onRename,+}: {+ profile: SpeakerProfile;+ onRename: (from: string, to: string) => void;+}) {+ const report = (outcome: { success: boolean; message?: string }) => {+ if (!outcome.success) toast.error("Speaker update failed", outcome.message);+ };+ return (+ <li className="flex items-center gap-1.5">+ <input+ type="color"+ aria-label={`Colour for ${profile.name}`}+ title="Speaker and caption colour"+ value={/^#[0-9a-f]{6}$/i.test(profile.color) ? profile.color : "#ffffff"}+ onChange={(e) => void updateSpeakerProfile(profile.name, { color: e.currentTarget.value }).then(report)}+ className="size-5 shrink-0 cursor-pointer rounded border border-border bg-transparent p-0"+ />+ <span className="min-w-0 flex-1">+ <SpeakerLabel name={profile.name} onRename={onRename} />+ </span>+ <select+ aria-label={`Caption position for ${profile.name}`}+ title="Where this speaker's captions sit"+ value={profile.position ?? POSITION_AUTO}+ onChange={(e) => {+ const v = e.currentTarget.value;+ void updateSpeakerProfile(profile.name, {+ position: v === POSITION_AUTO ? undefined : (v as SpeakerPosition),+ }).then(report);+ }}+ className="h-6 rounded border border-border bg-bg-2 px-1 text-[10px] text-fg-2"+ >+ <option value={POSITION_AUTO}>Position: as is</option>+ <option value="top">Top</option>+ <option value="center">Centre</option>+ <option value="bottom">Bottom</option>+ </select>+ </li>+ );+}++type Tool = "fillers" | "pauses" | "translate" | null;export function TranscriptPanel() {const subtitles = useProjectStore((s) => s.project.timeline.subtitles);@@ -140,11 +246,49 @@ export function TranscriptPanel() {const tracks = useMemo(() => listCaptionTracks(subtitles), [subtitles]);const [trackId, setTrackId] = useState<string>("");const activeTrack = tracks.some((t) => t.id === trackId) ? trackId : (tracks[0]?.id ?? "");+ const trackHidden = useMemo(+ () => !subtitles.some((c) => (c.captionTrackId ?? "") === activeTrack && !c.hidden),+ [subtitles, activeTrack],+ );const transcript = useMemo(() => buildTranscript(subtitles, tracks.length > 1 ? { captionTrackId: activeTrack } : {}),[subtitles, tracks.length, activeTrack],);const speakers = useMemo(() => listSpeakers(subtitles), [subtitles]);+ const storedProfiles = useProjectStore((s) => s.project.speakers);+ const profiles = useMemo<SpeakerProfile[]>(+ () => speakers.map((name, i) => findSpeakerProfile(storedProfiles, name) ?? { name, color: SPEAKER_FALLBACK[i % SPEAKER_FALLBACK.length] }),+ [speakers, storedProfiles],+ );+ const [detect, setDetect] = useState<{ progress: number; message: string } | null>(null);+ const [speakerCount, setSpeakerCount] = useState("auto");+ const [speakersOpen, setSpeakersOpen] = useState(false);+ const detectAbort = useRef<AbortController | null>(null);+ useEffect(() => () => detectAbort.current?.abort(), []);+ const detectSpeakers = async () => {+ const controller = new AbortController();+ detectAbort.current = controller;+ setDetect({ progress: 0, message: "Reading audio…" });+ try {+ const outcome = await diarizeCaptions({+ speakerCount: speakerCount === "auto" ? undefined : Number(speakerCount),+ signal: controller.signal,+ onProgress: (progress, message) => setDetect({ progress, message }),+ });+ if (outcome.success)+ toast.success(+ `${outcome.speakers} speaker${outcome.speakers === 1 ? "" : "s"} found`,+ "Voice matching is approximate, so check the labels. Rename, recolour or reassign a passage below. Undo restores the previous labels.",+ );+ else toast.error("Speaker detection failed", outcome.message);+ } catch (error) {+ if (!(error instanceof DOMException && error.name === "AbortError"))+ toast.error("Speaker detection failed", error instanceof Error ? error.message : undefined);+ } finally {+ detectAbort.current = null;+ setDetect(null);+ }+ };const { words, sentences } = transcript;const [query, setQuery] = useState("");@@ -333,12 +477,15 @@ export function TranscriptPanel() {});if (outcome.success) {if (lang) setTrackId(lang);- setExportNotes(outcome.issues ?? []);+ setExportNotes([...skippedNotes(outcome.errors), ...(outcome.issues ?? [])]);toast.success(`Imported ${outcome.added} caption${outcome.added === 1 ? "" : "s"}`,- outcome.errors?.length ? `${outcome.errors.length} skipped` : undefined,+ outcome.errors?.length ? `${outcome.errors.length} skipped, see the notes in the Transcript panel` : undefined,);- } else toast.error("Import failed", outcome.message);+ } else {+ setExportNotes([...skippedNotes(outcome.errors), ...(outcome.issues ?? [])]);+ toast.error(`Could not import ${file.name}`, outcome.message);+ }};const broadcast = exportFormat === "scc" || exportFormat === "stl";@@ -371,6 +518,12 @@ export function TranscriptPanel() {if (!outcome.success) toast.error("Rename failed", outcome.message);};+ const onReassign = async (wordStart: number, wordEnd: number, speaker: string) => {+ const ids = [...new Set(words.slice(wordStart, wordEnd).map((w) => w.subtitleId))];+ const outcome = await setCaptionSpeaker(ids, speaker);+ if (!outcome.success) toast.error("Reassign failed", outcome.message);+ };+const fillerTotal = cutDuration(chosenFillers);const pauseTotal = cutDuration(mergeTimeRanges(pauses.map((p) => p.cut)));const estimated = words.some((w) => w.estimated);@@ -442,6 +595,54 @@ export function TranscriptPanel() {>Remove pauses</Button>+ {detect ? (+ <Button+ type="button"+ variant="ghost"+ className={toolbarButton}+ onClick={() => detectAbort.current?.abort()}+ aria-label="Cancel speaker detection"+ >+ {detect.message} {Math.round(detect.progress * 100)}% · Cancel+ </Button>+ ) : (+ <>+ <Button+ type="button"+ variant="ghost"+ className={toolbarButton}+ disabled={!words.length}+ onClick={() => void detectSpeakers()}+ title="Label who is speaking, on this device. Approximate: best with clearly different voices and one person talking at a time."+ >+ Detect speakers+ </Button>+ <select+ aria-label="Number of speakers"+ value={speakerCount}+ onChange={(e) => setSpeakerCount(e.currentTarget.value)}+ onKeyDown={(e) => e.stopPropagation()}+ className="h-7 rounded border border-border bg-bg-2 px-1 text-[11px] text-fg-2"+ >+ <option value="auto">Auto</option>+ {[1, 2, 3, 4, 5, 6].map((n) => (+ <option key={n} value={n}>+ {n} speaker{n === 1 ? "" : "s"}+ </option>+ ))}+ </select>+ </>+ )}+ <Button+ type="button"+ variant="ghost"+ className={toolbarButton}+ aria-pressed={tool === "translate"}+ disabled={!subtitles.length}+ onClick={() => setTool(tool === "translate" ? null : "translate")}+ >+ Translate+ </Button><Buttontype="button"variant="ghost"@@ -454,6 +655,18 @@ export function TranscriptPanel() {</Button></div>+ {tool === "translate" && (+ <CaptionTranslateSection+ trackId={activeTrack}+ trackLanguage={tracks.find((t) => t.id === activeTrack)?.language}+ cueCount={tracks.find((t) => t.id === activeTrack)?.cueCount ?? 0}+ onTranslated={(id) => {+ setTrackId(id);+ setTool(null);+ }}+ />+ )}+{tool === "fillers" && (<sectionaria-label="Filler word preview"@@ -553,9 +766,18 @@ export function TranscriptPanel() {const speakerChanged = sentence.speaker !== previous?.speaker;return (<p key={sentence.index} data-sentence-index={sentence.index} className="m-0">- {(speakerChanged || i === 0) && sentence.speaker && (+ {(speakerChanged || i === 0) && (sentence.speaker || speakers.length > 0) && (<span className="mb-0.5 flex items-center gap-1.5">- <SpeakerLabel name={sentence.speaker} onRename={onRename} />+ <SpeakerLabel+ name={sentence.speaker}+ color={profiles.find((p) => p.name === sentence.speaker)?.color}+ onRename={onRename}+ />+ <SpeakerReassign+ current={sentence.speaker}+ names={speakers}+ onAssign={(name) => void onReassign(sentence.wordStart, sentence.wordEnd, name)}+ /><span className="font-mono text-[10px] text-fg-3">{formatFrameTimecode(sentence.start, frameRate)}</span>@@ -579,9 +801,42 @@ export function TranscriptPanel() {</ScrollArea><div className="shrink-0 space-y-1.5 border-t border-border px-2.5 py-2">- {speakers.length > 0 && (- <p className="text-[10px] text-fg-3">- {speakers.length} speaker{speakers.length === 1 ? "" : "s"}: click a name to rename it everywhere.+ {profiles.length > 0 && (+ <section aria-label="Speakers">+ <button+ type="button"+ aria-expanded={speakersOpen}+ aria-controls="transcript-speaker-list"+ title="Colour and position carry into the captions"+ onClick={() => setSpeakersOpen((open) => !open)}+ className="flex w-full items-center gap-2 rounded px-0.5 py-0.5 text-left hover:bg-bg-3"+ >+ <span className="shrink-0 text-[11px] font-semibold text-fg-2">Speakers</span>+ <span className="flex min-w-0 flex-1 items-center gap-2 overflow-hidden">+ {profiles.map((profile) => (+ <span key={profile.name} className="flex min-w-0 items-center gap-1 text-[10px] text-fg-3">+ <span aria-hidden className="size-2 shrink-0 rounded-full" style={{ backgroundColor: profile.color }} />+ <span className="truncate">{profile.name}</span>+ </span>+ ))}+ </span>+ <span aria-hidden className="shrink-0 text-[10px] text-fg-3">+ {speakersOpen ? "Hide" : "Edit"}+ </span>+ </button>+ {speakersOpen && (+ <ul id="transcript-speaker-list" className="m-0 mt-1 max-h-24 list-none space-y-1 overflow-y-auto p-0 pr-1">+ {profiles.map((profile) => (+ <SpeakerRow key={profile.name} profile={profile} onRename={onRename} />+ ))}+ </ul>+ )}+ </section>+ )}+ {profiles.length > 0 && (+ <p className="text-[10px] text-fg-3" data-testid="speaker-limits-note">+ Speakers are matched by voice on this device. It is approximate: similar voices can merge, one voice can+ split, and overlapping speech is not separated. Check the labels and fix any passage with its menu.</p>)}{estimated && (@@ -589,6 +844,20 @@ export function TranscriptPanel() {Some captions have no word timings; their word times are estimated from the caption.</p>)}+ {tracks.length > 1 && (+ <label className="flex items-center justify-between gap-2 text-[11px] text-fg-2">+ <span>Show this track in the picture</span>+ <Switch+ aria-label="Show this caption track in the picture"+ checked={!trackHidden}+ onCheckedChange={(visible) => {+ void setCaptionTrackInPicture(activeTrack, visible).then((o) => {+ if (!o.success) toast.error("Could not change the picture", o.message);+ });+ }}+ />+ </label>+ )}{tracks.length > 1 && (<Select value={activeTrack || DEFAULT_TRACK_VALUE} onValueChange={(v) => setTrackId(v === DEFAULT_TRACK_VALUE ? "" : v)}><SelectTrigger aria-label="Caption track" className="h-7 text-[11px]">@@ -615,7 +884,7 @@ export function TranscriptPanel() {<inputref={fileRef}type="file"- accept=".srt,.vtt,.json,.txt,.scc,.stl"+ accept=".srt,.vtt,.sbv,.ttml,.dfxp,.xml,.json,.txt,.scc,.stl"data-testid="transcript-import-input"className="hidden"onChange={(e) => {diff --git a/apps/web/src/components/editor/inspector/AudioChannelsSection.tsx b/apps/web/src/components/editor/inspector/AudioChannelsSection.tsxnew file mode 100644index 00000000..59c74078--- /dev/null+++ b/apps/web/src/components/editor/inspector/AudioChannelsSection.tsx@@ -0,0 +1,38 @@+import React from "react";+import { describeChannelMap, resolveClipChannelMap } from "@openreel/core";+import { Button } from "@openreel/ui";+import { useProjectStore } from "../../../stores/project-store";+import { openAudioChannelsForSelection, setClipChannelMap } from "../../../services/audio-channels";++/**+ * Modify > Audio Channels for the inspector: shows what the clips play from their file and opens the mapping+ * dialog. A multi-selection lists "Mixed" when the clips differ.+ */+export const AudioChannelsSection: React.FC<{ clipIds: readonly string[] }> = ({ clipIds }) => {+ const rows = useProjectStore((state) => {+ const clips = state.project.timeline.tracks.flatMap((track) => track.clips);+ return clipIds.flatMap((id) => {+ const clip = clips.find((candidate) => candidate.id === id);+ const media = clip && state.project.mediaLibrary.items.find((item) => item.id === clip.mediaId);+ return clip && media ? [{ clip, media }] : [];+ });+ });+ if (rows.length === 0) return null;+ const labels = new Set(rows.map(({ clip, media }) => describeChannelMap(resolveClipChannelMap(clip, media), media.metadata.channels || 2)));+ const label = labels.size === 1 ? [...labels][0] : "Mixed";+ const custom = rows.some(({ clip }) => clip.channelMap !== undefined);+ return (+ <div className="flex flex-col gap-2 p-1" data-testid="audio-channels-section">+ <div className="flex items-center justify-between gap-2">+ <span className="min-w-0 truncate text-xs" data-testid="audio-channels-current">{label}</span>+ <div className="flex shrink-0 gap-1">+ {custom && (+ <Button type="button" variant="ghost" size="sm" className="h-7 px-2 text-[11px]" data-testid="audio-channels-reset" onClick={() => { void setClipChannelMap(clipIds, null); }}>Reset</Button>+ )}+ <Button type="button" variant="outline" size="sm" className="h-7 px-2 text-[11px]" data-testid="audio-channels-open" onClick={() => openAudioChannelsForSelection(clipIds)}>Modify…</Button>+ </div>+ </div>+ <p className="text-[11px] text-fg-muted">Choose which source channels the clip plays: left only, swap, mono or 5.1.</p>+ </div>+ );+};diff --git a/apps/web/src/components/editor/inspector/ColorGradingSection.tsx b/apps/web/src/components/editor/inspector/ColorGradingSection.tsxindex b4e77d3e..2f676228 100644--- a/apps/web/src/components/editor/inspector/ColorGradingSection.tsx+++ b/apps/web/src/components/editor/inspector/ColorGradingSection.tsx@@ -1,13 +1,14 @@-import React, { Suspense, lazy, useCallback, useMemo } from "react";+import React, { Suspense, lazy, useCallback, useEffect, useMemo } from "react";import { Button } from "@openreel/ui";import { Card } from "@openreel/ui";import { PropertySlider } from "./shell/PropertySlider";-import { ChevronDown, RotateCcw, Sparkles, Sun, Thermometer } from "@/icons/lucide-compat";+import { ChevronDown, Pipette, RotateCcw, Sparkles, Sun, Thermometer } from "@/icons/lucide-compat";import { Switch } from "@openreel/ui";import { useUIStore } from "../../../stores/ui-store";import { useProjectStore } from "../../../stores/project-store";+import { useColorMonitorStore } from "../../../stores/color-monitor-store";import type {ColorWheelValues,HSLValues,@@ -162,6 +163,20 @@ export const ColorGradingSection: React.FC<ColorGradingSectionProps> = ({[clipId, updateColorGrading],);+ const wbPick = useColorMonitorStore((state) => state.whiteBalancePick);+ const wbSize = useColorMonitorStore((state) => state.whiteBalanceSize);+ const setWbPick = useColorMonitorStore((state) => state.setWhiteBalancePick);+ const setWbSize = useColorMonitorStore((state) => state.setWhiteBalanceSize);+ const wbArmed = wbPick?.clipId === clipId;+ // Leaving the clip (or the section) must not leave a stale eyedropper over the monitor.+ useEffect(+ () => () => {+ const state = useColorMonitorStore.getState();+ if (state.whiteBalancePick?.clipId === clipId) state.setWhiteBalancePick(null);+ },+ [clipId],+ );+const handleWhiteBalanceReset = useCallback(() => {updateColorGrading(clipId, { temperature: 0, tint: 0 });}, [clipId, updateColorGrading]);@@ -335,6 +350,44 @@ export const ColorGradingSection: React.FC<ColorGradingSectionProps> = ({</Button></div>+ <div className="flex items-center gap-1.5">+ <Button+ type="button"+ variant={wbArmed ? "default" : "outline"}+ size="icon-sm"+ className={`h-7 w-7 shrink-0 ${wbArmed ? "bg-accent text-white ring-2 ring-accent/40 hover:bg-accent" : ""}`}+ aria-pressed={wbArmed}+ aria-label="White balance eyedropper"+ title="Pick a neutral area on the Program monitor (Esc cancels)"+ onClick={() => setWbPick(wbArmed ? null : { clipId })}+ >+ <Pipette size={12} aria-hidden />+ </Button>+ <div+ role="group"+ aria-label="White balance sample size"+ className="flex shrink-0 overflow-hidden rounded-[6px] border border-border"+ >+ {([1, 5] as const).map((option) => (+ <button+ key={option}+ type="button"+ aria-pressed={wbSize === option}+ title={option === 1 ? "Sample a single pixel" : "Average a 5 by 5 pixel area"}+ onClick={() => setWbSize(option)}+ className={`whitespace-nowrap px-1.5 py-0.5 text-[9px] font-semibold ${+ wbSize === option ? "bg-accent text-white" : "bg-bg-2 text-fg-3 hover:text-fg"+ }`}+ >+ {option === 1 ? "Point" : "5×5"}+ </button>+ ))}+ </div>+ <span className={`min-w-0 flex-1 truncate text-[10px] ${wbArmed ? "font-medium text-accent" : "text-fg-3"}`} title={wbArmed ? "Click a neutral area on the Program monitor. Esc cancels." : undefined}>+ {wbArmed ? "Click a neutral area" : "Pick neutral"}+ </span>+ </div>+<div className="space-y-2"><div className="flex items-center gap-1.5"><Thermometer size={12} className="text-fg-3" />diff --git a/apps/web/src/components/editor/inspector/FilterPresetsPanel.test.tsx b/apps/web/src/components/editor/inspector/FilterPresetsPanel.test.tsxindex d51659af..39fed67c 100644--- a/apps/web/src/components/editor/inspector/FilterPresetsPanel.test.tsx+++ b/apps/web/src/components/editor/inspector/FilterPresetsPanel.test.tsx@@ -50,7 +50,8 @@ async function enterIntensity(value: number) {}async function renderPanel() {render(<FilterPresetsPanel clipId="clip" />);- await screen.findByRole("button", { name: "Apply Film Noir filter preset" });+ // The looks grid is lazy-loaded; under a loaded machine the chunk can take longer than findBy's 1 s default.+ await screen.findByRole("button", { name: "Apply Film Noir filter preset" }, { timeout: 10_000 });}beforeEach(() => seedProject());afterEach(() => { cleanup(); vi.restoreAllMocks(); });diff --git a/apps/web/src/components/editor/inspector/HslSecondarySection.tsx b/apps/web/src/components/editor/inspector/HslSecondarySection.tsxindex 638c025c..e0446113 100644--- a/apps/web/src/components/editor/inspector/HslSecondarySection.tsx+++ b/apps/web/src/components/editor/inspector/HslSecondarySection.tsx@@ -166,7 +166,7 @@ const MiniWheel: React.FC<{);};-const KeyButton: React.FC<{+export const KeyButton: React.FC<{clipId: string;effectId: string;paramKey: string;diff --git a/apps/web/src/components/editor/inspector/MotionTrackingSection.tsx b/apps/web/src/components/editor/inspector/MotionTrackingSection.tsxindex 24273c6a..a0051955 100644--- a/apps/web/src/components/editor/inspector/MotionTrackingSection.tsx+++ b/apps/web/src/components/editor/inspector/MotionTrackingSection.tsx@@ -24,7 +24,7 @@ const ALGORITHMS = [{ id: "feature", name: "Feature Match", description: "Follow distinct visual corners" },] as const;-function RegionInput({ label, value, onChange, min, max, disabled }: {+export function RegionInput({ label, value, onChange, min, max, disabled }: {label: string; value: number; onChange: (value: number) => void; min?: number; max?: number; disabled?: boolean;}) {const id = useId();diff --git a/apps/web/src/components/editor/inspector/MultiClipInspector.tsx b/apps/web/src/components/editor/inspector/MultiClipInspector.tsxindex c44d2a9f..5d9b3573 100644--- a/apps/web/src/components/editor/inspector/MultiClipInspector.tsx+++ b/apps/web/src/components/editor/inspector/MultiClipInspector.tsx@@ -30,6 +30,7 @@ import { getTimelineSelectionItem } from "../../../utils/timeline-item-actions";import { InspectorSection } from "./shell/InspectorSection";import { NestedSequenceSection } from "./NestedSequenceSection";import { EssentialSoundSection } from "./EssentialSoundSection";+import { AudioChannelsSection } from "./AudioChannelsSection";import { TextSection } from "./TextSection";import {cloneVideoEffectStackWithFreshIds,@@ -423,6 +424,11 @@ export function MultiClipInspector({ clipIds }: MultiClipInspectorProps): JSX.El<EssentialSoundSection clipIds={audioClipIds} /></InspectorSection>)}+ {audioClipIds.length > 0 && (+ <InspectorSection title="Audio channels" sectionId="audio-channels" defaultOpen>+ <AudioChannelsSection clipIds={audioClipIds} />+ </InspectorSection>+ )}{visualEntries.length > 0 ? (<InspectorSectiondiff --git a/apps/web/src/components/editor/inspector/PlanarTrackingSection.tsx b/apps/web/src/components/editor/inspector/PlanarTrackingSection.tsxnew file mode 100644index 00000000..4a1bb70b--- /dev/null+++ b/apps/web/src/components/editor/inspector/PlanarTrackingSection.tsx@@ -0,0 +1,150 @@+import { useEffect, useMemo, useRef, useState } from "react";+import { Alert, AlertDescription, AlertTitle, Button, Card, Label, Progress, Select, SelectContent, SelectItem, SelectTrigger, SelectValue, ToggleGroup, ToggleGroupItem } from "@openreel/ui";+import { AlertTriangle, Check, Target, X } from "@/icons/lucide-compat";+import { planarCornersAt, type PlanarTrackData, type TrackingData } from "@openreel/core";+import { useProjectStore } from "../../../stores/project-store";+import { useTimelineStore } from "../../../stores/timeline-store";+import { useUIStore } from "../../../stores/ui-store";+import { getPlanarTrackBridge, type PlanarTrackRange, type PlanarTrackState } from "../../../bridges/planar-track-bridge";+import { applyPlanarTrack, readPlanarTrackAnalysis, readPlanarTrackApplication, removePlanarTrack } from "../../../services/planar-track-edit";+import { defaultPlanarCorners, usePlanarTrackOverlayStore } from "../../../stores/planar-track-overlay-store";+import { PropertySlider } from "./shell/PropertySlider";+import { RegionInput } from "./MotionTrackingSection";+import { MotionTrackQualityStrip } from "./MotionTrackQualityStrip";++const IDLE: PlanarTrackState = { isTracking: false, progress: 0, lostFrames: 0, error: null, clipId: null };+const CORNERS = ["Top left", "Top right", "Bottom right", "Bottom left"];+const THRESHOLD = 0.5;++/** The planar path shaped as a point track so the shared quality strip can draw it. */+function asQualityData(data: PlanarTrackData): TrackingData {+ return { trackId: data.trackId, clipId: data.clipId, frameRate: data.frameRate, region: { x: 0, y: 0, width: 1, height: 1 }, confidence: data.confidence,+ lostFrames: data.lostFrames, manualFrames: data.manualFrames, keyframes: data.keyframes.map(k => ({ frame: k.frame, position: { x: k.corners[0], y: k.corners[1] } })) };+}++export function PlanarTrackingSection({ clipId }: { clipId: string }) {+ const projectId = useProjectStore(state => state.project.id);+ return <PlanarTrackingControls key={`${projectId}:${clipId}`} clipId={clipId} />;+}++function PlanarTrackingControls({ clipId }: { clipId: string }) {+ const project = useProjectStore(state => state.project);+ const exporting = useUIStore(state => state.exportState.isExporting);+ const playbackLocked = useTimelineStore(state => Boolean(state.playbackLockedReason));+ const source = project.timeline.tracks.flatMap(track => track.clips).find(clip => clip.id === clipId);+ const sourceTrack = project.timeline.tracks.find(track => track.id === source?.trackId);+ const media = project.mediaLibrary.items.find(item => item.id === source?.mediaId);+ const width = media?.metadata.width ?? project.settings.width, height = media?.metadata.height ?? project.settings.height;+ const fps = project.settings.frameRate;+ const frameCount = Math.max(1, Math.ceil((source?.duration ?? 0) * fps));+ const frame = useTimelineStore(state => Math.max(0, Math.min(frameCount - 1, Math.round((state.playheadPosition - (source?.startTime ?? 0)) * fps))));+ const bridge = getPlanarTrackBridge();+ const analysis = readPlanarTrackAnalysis(clipId), data = analysis?.data ?? null;+ const [state, setState] = useState(IDLE);+ const [corners, setCorners] = useState<number[]>(() => (data ? planarCornersAt(data, frame)?.corners : null) ?? data?.anchorCorners ?? defaultPlanarCorners(width, height));+ const [range, setRange] = useState<PlanarTrackRange>("clip");+ const [smoothing, setSmoothing] = useState(0);+ const [targetId, setTargetId] = useState<string>("");+ const [error, setError] = useState<string | null>(null), [busy, setBusy] = useState(false);+ const alive = useRef(true), owned = useRef(false);+ const choices = useMemo(() => project.timeline.tracks.filter(track => track.type !== "audio").flatMap(track => track.clips+ .filter(clip => clip.id !== clipId && project.mediaLibrary.items.find(item => item.id === clip.mediaId)?.type !== "audio")+ .map(clip => ({ id: clip.id, label: `${project.mediaLibrary.items.find(item => item.id === clip.mediaId)?.name ?? track.name} · ${track.name}`, locked: track.locked }))), [project, clipId]);+ const pinned = choices.find(choice => readPlanarTrackApplication(choice.id)?.sourceClipId === clipId)?.id;+ const target = targetId || pinned || choices[0]?.id || "";+ const application = target ? readPlanarTrackApplication(target) : null;+ const applied = application?.sourceClipId === clipId;+ const targetLocked = !choices.find(choice => choice.id === target) || Boolean(choices.find(choice => choice.id === target)?.locked);+ const disabled = !source || Boolean(sourceTrack?.locked) || exporting || busy || playbackLocked;++ useEffect(() => {+ alive.current = true;+ const unsubscribe = bridge.subscribe(snapshot => { if (snapshot.clipId === clipId || !snapshot.isTracking) setState(snapshot); });+ return () => { alive.current = false; unsubscribe(); if (owned.current) bridge.cancel(); };+ }, [bridge, clipId]);++ // Show the tracked corners of the playhead frame; with no track the corners are a draft the user places.+ const trackedAt = data ? planarCornersAt(data, frame) : null;+ const trackedKey = trackedAt ? trackedAt.corners.join(",") : "";+ useEffect(() => { if (trackedAt) setCorners(trackedAt.corners.map(v => Math.round(v * 10) / 10)); }, [trackedKey]); // eslint-disable-line react-hooks/exhaustive-deps++ const overlay = usePlanarTrackOverlayStore;+ useEffect(() => {+ overlay.getState().open({ clipId, corners, mediaWidth: width, mediaHeight: height });+ return () => overlay.getState().close(clipId);+ // eslint-disable-next-line react-hooks/exhaustive-deps -- opened once per clip; later changes are mirrored below+ }, [clipId, width, height]);+ useEffect(() => { overlay.getState().mirror(clipId, corners); }, [clipId, corners, overlay]);+ const dragRevision = overlay(s => (s.clipId === clipId ? s.editRevision : 0));+ useEffect(() => {+ const dragged = overlay.getState();+ if (dragRevision > 0 && dragged.clipId === clipId && dragged.corners) setCorners(previous => (previous.every((v, i) => v === dragged.corners![i]) ? previous : [...dragged.corners!]));+ }, [dragRevision, clipId, overlay]);++ const run = async (direction: PlanarTrackRange, merge: boolean) => {+ if (disabled || state.isTracking) return;+ setError(null); owned.current = true;+ try { await bridge.track({ clipId, corners, anchorFrame: frame, range: direction, confidenceThreshold: THRESHOLD, merge }); }+ catch (failure) { if (alive.current && !(failure instanceof Error && /cancelled/.test(failure.message))) setError(failure instanceof Error ? failure.message : "Tracking failed"); }+ finally { owned.current = false; }+ };+ const guarded = async (action: () => Promise<unknown>, fallback: string) => {+ if (disabled) return;+ setError(null); setBusy(true);+ try { await action(); } catch (failure) { if (alive.current) setError(failure instanceof Error ? failure.message : fallback); } finally { if (alive.current) setBusy(false); }+ };++ return <div className="min-w-0 space-y-3" data-testid="planar-tracking">+ <Card className="flex items-center gap-2 rounded-md border-primary/30 bg-primary/10 p-2 shadow-none">+ <Target size={16} className="shrink-0 text-primary" aria-hidden /><div className="min-w-0"><p className="text-xs font-medium">Planar Tracking</p><p className="text-[10px] text-fg-2">Track a flat surface by its four corners and pin a clip to it.</p></div>+ </Card>+ <fieldset disabled={disabled || state.isTracking} className="min-w-0 space-y-3">+ <p className="text-[11px] text-fg-2">Drag the corners on the Program monitor onto the surface at frame {frame}, or type them (source pixels, {width} × {height}).</p>+ <div className="grid grid-cols-2 gap-2">+ {CORNERS.map((name, i) => <div key={name} className="contents">+ <RegionInput label={`${name} X`} value={Math.round(corners[i * 2] * 10) / 10} min={0} max={width} onChange={v => setCorners(c => c.map((n, j) => j === i * 2 ? v : n))} />+ <RegionInput label={`${name} Y`} value={Math.round(corners[i * 2 + 1] * 10) / 10} min={0} max={height} onChange={v => setCorners(c => c.map((n, j) => j === i * 2 + 1 ? v : n))} />+ </div>)}+ </div>+ <Button type="button" variant="outline" className="h-[30px] w-full text-xs" onClick={() => setCorners(defaultPlanarCorners(width, height))}>Reset corners</Button>+ <div className="space-y-1.5"><Label className="text-xs">Track</Label>+ <ToggleGroup type="single" value={range} onValueChange={value => { if (value) setRange(value as PlanarTrackRange); }} aria-label="Planar tracking range" className="grid grid-cols-3 gap-1">+ <ToggleGroupItem value="clip" className="h-[30px] px-1 text-[11px]">Whole clip</ToggleGroupItem>+ <ToggleGroupItem value="forward" className="h-[30px] px-1 text-[11px]">Forward ▸</ToggleGroupItem>+ <ToggleGroupItem value="backward" className="h-[30px] px-1 text-[11px]">◂ Backward</ToggleGroupItem>+ </ToggleGroup>+ </div>+ <Button type="button" className="h-8 w-full text-xs" onClick={() => void run(range, Boolean(data) && range !== "clip")}><Target size={14} aria-hidden />{data ? "Re-track Surface" : "Start Tracking"}</Button>+ </fieldset>+ {state.isTracking && <div role="status" className="space-y-2 rounded-md bg-bg-2 p-3" data-testid="planar-track-progress">+ <div className="flex items-center justify-between gap-2"><p className="text-xs">Tracking in Progress · {Math.round(state.progress)}%</p><Button variant="ghost" size="icon-sm" aria-label="Cancel Planar Tracking" onClick={() => bridge.cancel()}><X size={14} aria-hidden /></Button></div>+ <Progress value={state.progress} aria-label="Planar tracking progress" />+ {state.lostFrames > 0 && <p className="text-[11px] text-amber-400">Lost the surface on {state.lostFrames} frame(s)</p>}+ </div>}+ {(error || state.error) && <Alert variant="destructive"><AlertTriangle size={14} aria-hidden /><AlertTitle>Tracking Failed</AlertTitle><AlertDescription>{error ?? state.error}</AlertDescription></Alert>}+ {data && !state.isTracking && <div className="space-y-3">+ <div role="status" className="flex items-center gap-2 rounded-md border border-primary/30 bg-primary/10 p-2" data-testid="planar-track-complete"><Check size={14} className="text-primary" aria-hidden /><p className="text-xs">Tracking Complete · {data.keyframes.length} frames{data.lostFrames.length ? ` · ${data.lostFrames.length} low confidence` : ""}</p></div>+ <MotionTrackQualityStrip data={asQualityData(data)} frameCount={frameCount} selectedFrame={frame} threshold={THRESHOLD} onSelect={next => useTimelineStore.getState().seekTo((source?.startTime ?? 0) + next / fps)} />+ <div className="space-y-2 rounded-md bg-bg-2 p-2">+ <p className="text-[11px]" data-testid="planar-track-frame-info">Frame {frame}{trackedAt ? ` · ${Math.round(trackedAt.confidence * 100)}% · ${trackedAt.manual ? "set by hand" : trackedAt.exact ? "tracked" : "between samples"}` : ""}</p>+ <Button type="button" className="h-[30px] w-full text-[11px]" disabled={disabled} onClick={() => void guarded(() => bridge.correctFrame(clipId, frame, corners), "Could not set corners")}>Set corners at this frame</Button>+ <div className="grid grid-cols-2 gap-1">+ <Button type="button" variant="outline" className="h-[30px] px-1 text-[11px]" disabled={disabled} onClick={() => void run("forward", true)}>Re-track from here</Button>+ <Button type="button" variant="outline" className="h-[30px] px-1 text-[11px]" disabled={disabled} onClick={() => void run("backward", true)}>Re-track backward</Button>+ </div>+ </div>+ <div className="min-w-0 space-y-3">+ <div className="space-y-1.5"><Label className="text-xs">Pin clip</Label>+ <Select value={target} onValueChange={setTargetId} disabled={disabled || !choices.length}>+ <SelectTrigger aria-label="Corner pin target" className="h-[30px] min-w-0 text-xs"><SelectValue placeholder="No other clip to pin" /></SelectTrigger>+ <SelectContent>{choices.map(choice => <SelectItem key={choice.id} value={choice.id} disabled={choice.locked}>{choice.label}</SelectItem>)}</SelectContent>+ </Select>+ <p className="text-[10px] text-fg-2">Adds a Corner Pin effect to the clip, keyframed to the surface. It maps the clip's frame, so a full-frame graphic fits best.</p>+ </div>+ <PropertySlider label="Path Smoothing" min={0} max={10} step={1} value={smoothing} onChange={setSmoothing} isDisabled={disabled || targetLocked} />+ <Button type="button" className="h-8 w-full text-xs" disabled={disabled || targetLocked} onClick={() => void guarded(() => applyPlanarTrack(clipId, target, { smoothing }), "Could not pin the clip")}>{busy ? "Applying…" : applied ? "Update Pin" : "Pin Clip to Surface"}</Button>+ {applied && <Button type="button" variant="outline" className="h-[30px] w-full text-xs" disabled={disabled || targetLocked} onClick={() => void guarded(() => removePlanarTrack(target), "Could not remove the pin")}>Remove Pin</Button>}+ </div>+ </div>}+ </div>;+}diff --git a/apps/web/src/components/editor/inspector/SubtitleInspector.tsx b/apps/web/src/components/editor/inspector/SubtitleInspector.tsxindex 8a671c3f..a80dc4a5 100644--- a/apps/web/src/components/editor/inspector/SubtitleInspector.tsx+++ b/apps/web/src/components/editor/inspector/SubtitleInspector.tsx@@ -5,13 +5,11 @@ import { Captions, Upload } from "@/icons/lucide-compat";import { useProjectStore } from "../../../stores/project-store";import { toast } from "../../../stores/notification-store";import { FONT_CATEGORIES, FONT_FILE_ACCEPT, registerCustomFont, useCustomFonts } from "./font-options";+import { DEFAULT_CAPTION_STYLE } from "@openreel/core/captions/caption-layout";import { InspectorSection as Section } from "./shell/InspectorSection";import { SavedStylesSection } from "./SavedStylesSection";-const DEFAULT_STYLE: SubtitleStyle = {- fontFamily: "Inter", fontSize: 24, color: "#ffffff",- backgroundColor: "rgba(0, 0, 0, 0.7)", position: "bottom",-};+const DEFAULT_STYLE: SubtitleStyle = DEFAULT_CAPTION_STYLE;const HIGHLIGHT_COLORS = ["#ffff00", "#00ff00", "#ff6b6b", "#4ecdc4", "#ff9f43", "#a55eea"];const OPACITY_OPTIONS = [{ value: "0", label: "None" }, { value: "0.5", label: "50%" }, { value: "0.7", label: "70%" }, { value: "1", label: "100%" }];const ANIMATION_HELP: Record<CaptionAnimationStyle, string> = {diff --git a/apps/web/src/components/editor/inspector/UltraKeyControls.tsx b/apps/web/src/components/editor/inspector/UltraKeyControls.tsxnew file mode 100644index 00000000..28f9ed62--- /dev/null+++ b/apps/web/src/components/editor/inspector/UltraKeyControls.tsx@@ -0,0 +1,200 @@+import React, { useCallback, useEffect } from "react";+import { Button, cn } from "@openreel/ui";+import { Pipette, RotateCcw } from "@/icons/lucide-compat";+import { PRO_EFFECT_DEFAULTS, PRO_EFFECT_SPECS, resolveProEffectParams } from "@openreel/core";+import { PropertySlider } from "./shell/PropertySlider";+import { KeyButton } from "./HslSecondarySection";+import { useColorMonitorStore } from "../../../stores/color-monitor-store";++const TYPE = "ultra-key";+const SPEC = PRO_EFFECT_SPECS[TYPE];++/** Premiere's Setting menu: starting points for the matte generation sliders. */+const SETTINGS: ReadonlyArray<{ id: string; label: string; patch: Record<string, number> }> = [+ { id: "default", label: "Default", patch: { transparency: 45, highlight: 10, shadow: 50, tolerance: 50, pedestal: 0 } },+ { id: "relaxed", label: "Relaxed", patch: { transparency: 30, highlight: 20, shadow: 60, tolerance: 35, pedestal: 0 } },+ { id: "aggressive", label: "Aggressive", patch: { transparency: 65, highlight: 5, shadow: 35, tolerance: 70, pedestal: 10 } },+];++const OUTPUTS: ReadonlyArray<{ value: string; label: string }> = [+ { value: "composite", label: "Composite" },+ { value: "alpha", label: "Alpha" },+ { value: "color", label: "Color" },+];++const GROUPS: ReadonlyArray<{ title: string; keys: readonly string[] }> = [+ { title: "Matte generation", keys: ["transparency", "highlight", "shadow", "tolerance", "pedestal"] },+ { title: "Matte cleanup", keys: ["choke", "soften", "contrast", "midPoint"] },+ { title: "Spill suppression", keys: ["desaturate", "range", "spill", "luma"] },+ { title: "Color correction", keys: ["saturation", "hue", "luminance"] },+];++const hex2 = (v: number): string => Math.round(Math.min(255, Math.max(0, v))).toString(16).padStart(2, "0");++/**+ * Ultra Key inspector: key colour with a Program monitor eyedropper, the four Premiere parameter groups (every+ * slider keyframable) and the output view. All values are stored in the effect's params like any pro effect.+ */+export const UltraKeyControls: React.FC<{+ clipId: string;+ effectId: string;+ params: Record<string, unknown>;+ disabled: boolean;+ onChange: (params: Record<string, unknown>) => void;+}> = ({ clipId, effectId, params, disabled, onChange }) => {+ const values = resolveProEffectParams(TYPE, params);+ const picker = useColorMonitorStore((state) => state.keyPicker);+ const setPicker = useColorMonitorStore((state) => state.setKeyPicker);+ const armed = picker?.effectId === effectId;++ // Leaving the effect (or the clip) must not leave the picker armed.+ useEffect(+ () => () => {+ const current = useColorMonitorStore.getState().keyPicker;+ if (current?.effectId === effectId) useColorMonitorStore.getState().setKeyPicker(null);+ },+ [effectId],+ );++ const keyR = Number(values.keyR);+ const keyG = Number(values.keyG);+ const keyB = Number(values.keyB);+ const hex = `#${hex2(keyR)}${hex2(keyG)}${hex2(keyB)}`;+ const output = String(values.output);++ const setHex = useCallback(+ (next: string) => {+ const m = /^#([0-9a-f]{2})([0-9a-f]{2})([0-9a-f]{2})$/i.exec(next);+ if (!m) return;+ onChange({ keyR: parseInt(m[1], 16), keyG: parseInt(m[2], 16), keyB: parseInt(m[3], 16) });+ },+ [onChange],+ );++ const slider = (key: string) => {+ const spec = SPEC.params.find((param) => param.key === key);+ if (!spec) return null;+ const value = Number(values[key]);+ return (+ <div key={key} className="flex items-end gap-1">+ <div className="min-w-0 flex-1">+ <PropertySlider+ label={spec.label}+ ariaLabel={`Ultra Key ${spec.label}`}+ isDisabled={disabled}+ value={value}+ onChange={(v) => onChange({ [key]: v })}+ min={spec.min ?? 0}+ max={spec.max ?? 100}+ step={spec.step ?? 1}+ defaultValue={Number(PRO_EFFECT_DEFAULTS[TYPE][key] ?? 0)}+ formatValue={(v) => `${Math.round(v)}${spec.unit ?? ""}`}+ />+ </div>+ {spec.keyframable ? (+ <KeyButton clipId={clipId} effectId={effectId} paramKey={key} value={value} disabled={disabled} />+ ) : null}+ </div>+ );+ };++ const segmented = (+ label: string,+ options: ReadonlyArray<{ value: string; label: string }>,+ current: string,+ onPick: (value: string) => void,+ ) => (+ <div role="group" aria-label={label} className="flex overflow-hidden rounded-[6px] border border-border">+ {options.map((option) => (+ <button+ key={option.value}+ type="button"+ disabled={disabled}+ aria-pressed={current === option.value}+ className={cn(+ "flex-1 px-2 py-1 text-[10px] font-medium transition-colors disabled:opacity-50",+ current === option.value ? "bg-accent text-white" : "bg-bg-1 text-fg-2 hover:bg-bg-3",+ )}+ onClick={() => onPick(option.value)}+ >+ {option.label}+ </button>+ ))}+ </div>+ );++ return (+ <div className="flex flex-col gap-2" data-testid="ultra-key-controls" data-effect-id={effectId}>+ <div className="flex items-center justify-between gap-2">+ <span className="text-[10px] font-normal text-fg-2">Key color</span>+ <div className="flex items-center gap-1">+ <input+ type="color"+ aria-label="Key color"+ data-testid="ultra-key-swatch"+ value={hex}+ disabled={disabled}+ onChange={(event) => setHex(event.target.value)}+ className="h-6 w-8 cursor-pointer rounded border border-border bg-transparent p-0 disabled:opacity-50"+ />+ <Button+ type="button"+ variant={armed ? "secondary" : "outline"}+ size="icon-sm"+ className="h-6 w-6"+ disabled={disabled}+ aria-pressed={armed}+ aria-label="Pick key color from the Program monitor"+ title="Pick the key color from the Program monitor (Esc cancels)"+ onClick={() => setPicker(armed ? null : { clipId, effectId })}+ >+ <Pipette className="h-3 w-3" />+ </Button>+ <Button+ type="button"+ variant="ghost"+ size="icon-sm"+ className="h-6 w-6"+ disabled={disabled}+ aria-label="Reset Ultra Key"+ title="Reset to defaults"+ onClick={() => onChange({ ...PRO_EFFECT_DEFAULTS[TYPE] })}+ >+ <RotateCcw className="h-3 w-3" />+ </Button>+ </div>+ </div>+ {armed ? (+ <p role="status" className="text-[10px] leading-snug text-accent">+ Click the screen colour on the Program monitor. Esc cancels.+ </p>+ ) : null}+ <div className="flex items-center justify-between gap-2">+ <span className="text-[10px] font-normal text-fg-2">Setting</span>+ <div className="w-[170px]">+ {segmented(+ "Ultra Key setting",+ SETTINGS.map((s) => ({ value: s.id, label: s.label })),+ "",+ (id) => {+ const setting = SETTINGS.find((s) => s.id === id);+ if (setting) onChange(setting.patch);+ },+ )}+ </div>+ </div>+ <div className="flex items-center justify-between gap-2">+ <span className="text-[10px] font-normal text-fg-2">Output</span>+ <div className="w-[170px]">+ {segmented("Ultra Key output", OUTPUTS, output, (value) => onChange({ output: value }))}+ </div>+ </div>+ {GROUPS.map((group) => (+ <div key={group.title} className="flex flex-col gap-1.5 border-t border-border pt-2">+ <span className="text-[10px] font-semibold uppercase tracking-wide text-fg-3">{group.title}</span>+ {group.keys.map(slider)}+ </div>+ ))}+ </div>+ );+};diff --git a/apps/web/src/components/editor/inspector/VideoEffectsSection.tsx b/apps/web/src/components/editor/inspector/VideoEffectsSection.tsxindex d077282c..0e5b8c7d 100644--- a/apps/web/src/components/editor/inspector/VideoEffectsSection.tsx+++ b/apps/web/src/components/editor/inspector/VideoEffectsSection.tsx@@ -34,6 +34,11 @@ import {getMotionShaderEffectDefs,defaultMotionShaderParams,isProEffectType,+ isBurnInEffectType,+ BURN_IN_SPECS,+ resolveBurnInParams,+ type BurnInEffectType,+ type BurnInParamSpec,describePluginEffect,getPluginRegistry,isPluginEffectType,@@ -130,10 +135,152 @@ const EffectSlider: React.FC<{/>);+const UltraKeyControls = React.lazy(() =>+ import("./UltraKeyControls").then((m) => ({ default: m.UltraKeyControls })),+);+const PRO_EFFECT_LABELS = Object.fromEntries(PRO_EFFECT_TYPES.map((type) => [type, PRO_EFFECT_SPECS[type].label]),) as Record<ProEffectType, string>;+const BURN_IN_LABELS: Record<BurnInEffectType, string> = {+ "burn-in-timecode": BURN_IN_SPECS["burn-in-timecode"].label,+ "burn-in-name": BURN_IN_SPECS["burn-in-name"].label,+};++/** A text field that commits on Enter or blur, so typing a label is one undo step, not one per keystroke. */+const BurnInTextField: React.FC<{+ spec: Extract<BurnInParamSpec, { kind: "text" }>;+ value: string;+ disabled: boolean;+ onCommit: (value: string) => void;+}> = ({ spec, value, disabled, onCommit }) => {+ const [draft, setDraft] = React.useState(value);+ React.useEffect(() => setDraft(value), [value]);+ const commit = () => {+ if (draft !== value) onCommit(draft);+ };+ return (+ <div className="flex items-center justify-between gap-2">+ <span className="text-fg-2 font-normal text-[10px]">{spec.label}</span>+ <Input+ aria-label={spec.label}+ value={draft}+ disabled={disabled}+ maxLength={spec.maxLength}+ placeholder={spec.placeholder}+ onChange={(event) => setDraft(event.target.value)}+ onBlur={commit}+ onKeyDown={(event) => {+ if (event.key === "Enter") commit();+ }}+ className="h-6 max-w-[150px] text-[10px] md:text-[10px]"+ />+ </div>+ );+};++/**+ * Inspector controls for the Timecode and Clip Name burn-ins, generated from BURN_IN_SPECS and grouped like+ * Premiere's panel (source, layout, text, background). The box options only show while the box is on.+ */+const BurnInControls: React.FC<{+ type: BurnInEffectType;+ params: Record<string, unknown>;+ onChange: (params: Record<string, unknown>) => void;+ disabled: boolean;+}> = ({ type, params, onChange, disabled }) => {+ const values = resolveBurnInParams(type, params);+ const visible = (spec: BurnInParamSpec): boolean => {+ if (spec.key === "hideExtension") return values.nameSource === "file";+ if (spec.key === "boxColor" || spec.key === "boxOpacity" || spec.key === "boxPadding") return values.box === true;+ return true;+ };+ const groups: BurnInParamSpec["group"][] = ["Source", "Layout", "Text", "Background"];+ return (+ <div className="space-y-3" data-testid={`burn-in-controls-${type}`}>+ {groups.map((group) => {+ const specs = BURN_IN_SPECS[type].params.filter((spec) => spec.group === group && visible(spec));+ if (specs.length === 0) return null;+ return (+ <section key={group} aria-label={`${group} options`} className="space-y-2">+ <div className="text-[9px] font-bold uppercase tracking-[0.12em] text-fg-muted">{group}</div>+ {specs.map((spec) => {+ const value = values[spec.key];+ switch (spec.kind) {+ case "toggle":+ return (+ <div key={spec.key} className="flex items-center justify-between gap-2">+ <span className="text-fg-2 font-normal text-[10px]">{spec.label}</span>+ <Switch+ aria-label={spec.label}+ checked={value === true}+ disabled={disabled}+ onCheckedChange={(checked) => onChange({ [spec.key]: checked })}+ />+ </div>+ );+ case "select":+ return (+ <div key={spec.key} className="flex items-center justify-between gap-2">+ <span className="text-fg-2 font-normal text-[10px]">{spec.label}</span>+ <Select value={String(value)} disabled={disabled} onValueChange={(next) => onChange({ [spec.key]: next })}>+ <SelectTrigger aria-label={spec.label} className="h-6 max-w-[150px] text-[10px]">+ <SelectValue />+ </SelectTrigger>+ <SelectContent>+ {spec.options.map((option) => (+ <SelectItem key={option.value} value={option.value}>+ {option.label}+ </SelectItem>+ ))}+ </SelectContent>+ </Select>+ </div>+ );+ case "text":+ return (+ <BurnInTextField+ key={spec.key}+ spec={spec}+ value={String(value)}+ disabled={disabled}+ onCommit={(next) => onChange({ [spec.key]: next })}+ />+ );+ case "color":+ return (+ <EffectColorField+ key={spec.key}+ disabled={disabled}+ label={spec.label}+ value={String(value)}+ onChange={(next) => onChange({ [spec.key]: next })}+ />+ );+ default:+ return (+ <EffectSlider+ key={spec.key}+ disabled={disabled}+ label={spec.label}+ value={Number(value)}+ onChange={(next) => onChange({ [spec.key]: next })}+ min={spec.min}+ max={spec.max}+ step={spec.step}+ unit={spec.unit}+ />+ );+ }+ })}+ </section>+ );+ })}+ </div>+ );+};+/** Inspector controls for the pro effects library, generated from PRO_EFFECT_SPECS. */const ProEffectControls: React.FC<{type: ProEffectType;@@ -396,6 +543,7 @@ const EffectItem: React.FC<{"radial-blur": "Radial Blur","chromatic-aberration": "Chromatic Aberration",...PRO_EFFECT_LABELS,+ ...BURN_IN_LABELS,shader: "Shader",};@@ -470,6 +618,29 @@ const EffectItem: React.FC<{</span>);}+ if (isBurnInEffectType(effect.type)) {+ return (+ <BurnInControls+ type={effect.type}+ params={effect.params}+ disabled={editingDisabled}+ onChange={(params) => onUpdate(effect.id, params)}+ />+ );+ }+ if (effect.type === "ultra-key") {+ return (+ <React.Suspense fallback={null}>+ <UltraKeyControls+ clipId={clipId}+ effectId={effect.id}+ params={effect.params}+ disabled={editingDisabled}+ onChange={(params) => onUpdate(effect.id, params)}+ />+ </React.Suspense>+ );+ }if (isProEffectType(effect.type)) {return (<ProEffectControlsdiff --git a/apps/web/src/components/editor/inspector/VoiceOverMeter.test.tsx b/apps/web/src/components/editor/inspector/VoiceOverMeter.test.tsxnew file mode 100644index 00000000..1acb0e16--- /dev/null+++ b/apps/web/src/components/editor/inspector/VoiceOverMeter.test.tsx@@ -0,0 +1,24 @@+import { describe, expect, it } from "vitest";+import { render } from "@testing-library/react";+import { VoiceOverMeter } from "./VoiceOverPanel";++const segments = (container: HTMLElement) => Array.from(container.querySelectorAll('[data-testid="voiceover-meter"] > span'));++describe("VoiceOverMeter", () => {+ it("lights segments in proportion to the level and goes dark when inactive", () => {+ const half = render(<VoiceOverMeter level={0.5} active />);+ const lit = (el: Element) => el.className.includes("bg-accent") || el.className.includes("bg-status");+ expect(segments(half.container).filter(lit)).toHaveLength(12);+ half.unmount();+ const idle = render(<VoiceOverMeter level={0.9} active={false} />);+ expect(segments(idle.container).filter(lit)).toHaveLength(0);+ });++ it("turns the top segments red as the level clips, and exposes the level to assistive tech", () => {+ const { container, getByRole } = render(<VoiceOverMeter level={1} active />);+ const bars = segments(container);+ expect(bars.at(-1)?.className).toContain("bg-status-error");+ expect(bars.at(-5)?.className).toContain("bg-status-warning");+ expect(getByRole("meter").getAttribute("aria-valuenow")).toBe("1");+ });+});diff --git a/apps/web/src/components/editor/inspector/VoiceOverPanel.takes.test.ts b/apps/web/src/components/editor/inspector/VoiceOverPanel.takes.test.tsdeleted file mode 100644index 105afe21..00000000--- a/apps/web/src/components/editor/inspector/VoiceOverPanel.takes.test.ts+++ /dev/null@@ -1,21 +0,0 @@-import { describe, expect, it } from "vitest";-import { listVoiceOverTakes, peakLevel } from "./VoiceOverPanel";--describe("peakLevel", () => {- it("is 0 for silence and 1 at full scale", () => {- expect(peakLevel([128, 128, 128])).toBe(0);- expect(peakLevel([128, 0, 128])).toBe(1);- expect(peakLevel([128, 192])).toBeCloseTo(0.5);- });-});--describe("listVoiceOverTakes", () => {- it("lists clips on Voice Over tracks in time order", () => {- const takes = listVoiceOverTakes([- { id: "t1", name: "Main", clips: [{ id: "x", startTime: 0, duration: 5 }] },- { id: "t2", name: "Voice Over", clips: [{ id: "b", startTime: 9, duration: 3 }, { id: "a", startTime: 2, duration: 4 }] },- ]);- expect(takes.map((take) => take.clipId)).toEqual(["a", "b"]);- expect(takes[0]).toMatchObject({ trackId: "t2", duration: 4 });- });-});diff --git a/apps/web/src/components/editor/inspector/VoiceOverPanel.tsx b/apps/web/src/components/editor/inspector/VoiceOverPanel.tsxindex 2087ca87..00a269b6 100644--- a/apps/web/src/components/editor/inspector/VoiceOverPanel.tsx+++ b/apps/web/src/components/editor/inspector/VoiceOverPanel.tsx@@ -1,61 +1,28 @@-import React, { useCallback, useEffect, useMemo, useRef, useState } from "react";+import React, { useEffect, useMemo } from "react";import { Button, Card } from "@openreel/ui";import { AlertCircle, Mic, Square } from "@/icons/lucide-compat";import { useUIStore } from "../../../stores/ui-store";import { useProjectStore } from "../../../stores/project-store";import { useTimelineStore } from "../../../stores/timeline-store";+import { useVoiceOverStore } from "../../../services/voiceover/voiceover-recorder";+import {+ MAX_PRE_ROLL_SECONDS,+ audioTrackChoices,+ formatClock,+ listVoiceOverTakes,+ peakLevel,+ punchRange,+ resolveRecordPlan,+ selectVoiceOverMimeType as selectMimeType,+ type PlacementTrack,+} from "../../../services/voiceover/voiceover-logic";++export { listVoiceOverTakes, peakLevel };export function selectVoiceOverMimeType(supports: (mimeType: string) => boolean = MediaRecorder.isTypeSupported,): { mimeType: string; extension: string } | null {- const candidates = [- { mimeType: "audio/webm;codecs=opus", extension: "webm" },- { mimeType: "audio/mp4", extension: "m4a" },- { mimeType: "audio/webm", extension: "webm" },- { mimeType: "audio/ogg;codecs=opus", extension: "ogg" },- ];- return candidates.find((candidate) => supports(candidate.mimeType)) ?? null;-}--function formatElapsed(milliseconds: number): string {- const seconds = Math.floor(milliseconds / 1_000);- return `${Math.floor(seconds / 60).toString().padStart(2, "0")}:${(seconds % 60)- .toString()- .padStart(2, "0")}`;-}--/** Peak level 0..1 of 8-bit time-domain samples (128 is silence). */-export function peakLevel(samples: ArrayLike<number>): number {- let peak = 0;- for (let i = 0; i < samples.length; i++) {- const v = Math.abs(samples[i] - 128) / 128;- if (v > peak) peak = v;- }- return Math.min(1, peak);-}--export interface VoiceOverTake {- clipId: string;- trackId: string;- startTime: number;- duration: number;-}--/** Clips on the "Voice Over" tracks, newest position last. */-export function listVoiceOverTakes(- tracks: ReadonlyArray<{ id: string; name: string; clips: ReadonlyArray<{ id: string; startTime: number; duration: number }> }>,-): VoiceOverTake[] {- return tracks- .filter((track) => track.name === "Voice Over")- .flatMap((track) =>- track.clips.map((clip) => ({- clipId: clip.id,- trackId: track.id,- startTime: clip.startTime,- duration: clip.duration,- })),- )- .sort((a, b) => a.startTime - b.startTime);+ return selectMimeType(supports);}const INPUT_METER_BARS = 24;@@ -90,284 +57,309 @@ export const VoiceOverMeter: React.FC<{ level: number; active: boolean }> = ({ l);};+const FIELD = "h-7 min-w-0 flex-1 truncate rounded-md border border-border bg-bg-1 px-2 text-[11px] text-fg disabled:opacity-60";+const ROW = "flex items-center justify-between gap-2";+const LABEL = "text-[11px] font-semibold text-fg shrink-0";++const Toggle: React.FC<{+ id: string;+ checked: boolean;+ disabled?: boolean;+ onChange: (checked: boolean) => void;+ title: string;+ hint: string;+}> = ({ id, checked, disabled, onChange, title, hint }) => (+ <label htmlFor={id} className={`flex cursor-pointer items-start gap-2 ${disabled ? "opacity-60" : ""}`}>+ <input+ id={id}+ data-testid={id}+ type="checkbox"+ checked={checked}+ disabled={disabled}+ onChange={(event) => onChange(event.target.checked)}+ className="mt-0.5 h-3.5 w-3.5 shrink-0 accent-[var(--accent,#3b82f6)]"+ />+ <span className="min-w-0">+ <span className="block text-[11px] font-semibold text-fg">{title}</span>+ <span className="block text-[9px] text-fg-muted">{hint}</span>+ </span>+ </label>+);++function timecode(seconds: number): string {+ const whole = Math.max(0, seconds);+ const minutes = Math.floor(whole / 60);+ return `${minutes}:${(whole - minutes * 60).toFixed(1).padStart(4, "0")}`;+}+export const VoiceOverPanel: React.FC = () => {- const importMedia = useProjectStore((state) => state.importMedia);- const addClipToNewTrack = useProjectStore((state) => state.addClipToNewTrack);- const renameTrack = useProjectStore((state) => state.renameTrack);- const playheadPosition = useTimelineStore((state) => state.playheadPosition);- const recorderRef = useRef<MediaRecorder | null>(null);- const streamRef = useRef<MediaStream | null>(null);- const chunksRef = useRef<Blob[]>([]);- const startedAtRef = useRef(0);- const saveRecordingRef = useRef(true);- const [isRecording, setIsRecording] = useState(false);- const [isSaving, setIsSaving] = useState(false);- const [elapsed, setElapsed] = useState(0);- const [error, setError] = useState<string | null>(null);- const [level, setLevel] = useState(0);- const [devices, setDevices] = useState<MediaDeviceInfo[]>([]);- const [deviceId, setDeviceId] = useState("");+ const phase = useVoiceOverStore((state) => state.phase);+ const countdown = useVoiceOverStore((state) => state.countdown);+ const elapsedMs = useVoiceOverStore((state) => state.elapsedMs);+ const level = useVoiceOverStore((state) => state.level);+ const error = useVoiceOverStore((state) => state.error);+ const errorKind = useVoiceOverStore((state) => state.errorKind);+ const devices = useVoiceOverStore((state) => state.devices);+ const prefs = useVoiceOverStore((state) => state.prefs);+ const lastTake = useVoiceOverStore((state) => state.lastTake);+ const setPrefs = useVoiceOverStore((state) => state.setPrefs);const tracks = useProjectStore((state) => state.project.timeline.tracks);- const takes = useMemo(() => listVoiceOverTakes(tracks), [tracks]);- const meterRef = useRef<{ context: AudioContext; frame: number } | null>(null);-- const stopMeter = useCallback(() => {- if (meterRef.current) {- cancelAnimationFrame(meterRef.current.frame);- void meterRef.current.context.close().catch(() => undefined);- meterRef.current = null;- }- setLevel(0);- }, []);+ const mediaItems = useProjectStore((state) => state.project.mediaLibrary.items);+ const playhead = useTimelineStore((state) => state.playheadPosition);+ const markIn = useTimelineStore((state) => state.loopStart);+ const markOut = useTimelineStore((state) => state.loopEnd);- const startMeter = useCallback((stream: MediaStream) => {- try {- const context = new AudioContext();- const analyser = context.createAnalyser();- analyser.fftSize = 512;- context.createMediaStreamSource(stream).connect(analyser);- const data = new Uint8Array(analyser.fftSize);- const state = { context, frame: 0 };- const tick = () => {- analyser.getByteTimeDomainData(data);- setLevel((previous) => Math.max(peakLevel(data), previous * 0.85));- state.frame = requestAnimationFrame(tick);- };- state.frame = requestAnimationFrame(tick);- meterRef.current = state;- } catch {- // The meter is informational; recording works without it.- }- }, []);+ const busy = phase === "countdown" || phase === "recording" || phase === "saving";+ const range = punchRange(markIn, markOut);+ const audioTracks = useMemo(() => audioTrackChoices(tracks as unknown as PlacementTrack[]), [tracks]);+ const takes = useMemo(+ () => listVoiceOverTakes(tracks, new Map(mediaItems.map((item) => [item.id, item.name]))),+ [tracks, mediaItems],+ );+ const plan = resolveRecordPlan({ playhead, preRoll: prefs.preRoll, punch: prefs.punch, markIn, markOut });+ const targetName = audioTracks.find((track) => track.id === prefs.targetTrackId)?.name ?? "a new Voice Over track";+ const savedDeviceMissing = Boolean(prefs.deviceId) && devices.length > 0 && !devices.some((device) => device.deviceId === prefs.deviceId);useEffect(() => {const media = navigator.mediaDevices;- if (!media?.enumerateDevices) return;- let active = true;- const refresh = () => {- media- .enumerateDevices()- .then((list) => {- if (!active) return;- const inputs = list.filter((device) => device.kind === "audioinput" && device.deviceId);- setDevices(inputs);- setDeviceId((current) => (inputs.some((device) => device.deviceId === current) ? current : ""));- })- .catch(() => undefined);- };- refresh();- media.addEventListener?.("devicechange", refresh);+ void useVoiceOverStore.getState().refreshDevices();+ const refresh = () => void useVoiceOverStore.getState().refreshDevices();+ media?.addEventListener?.("devicechange", refresh);return () => {- active = false;- media.removeEventListener?.("devicechange", refresh);+ media?.removeEventListener?.("devicechange", refresh);+ // A level check holds the microphone open; a take in progress must keep running when the panel closes.+ useVoiceOverStore.getState().stopMonitor();};- }, [isRecording]);-- const releaseStream = useCallback(() => {- streamRef.current?.getTracks().forEach((track) => track.stop());- streamRef.current = null;- recorderRef.current = null;- stopMeter();- }, [stopMeter]);+ }, []);useEffect(() => {- if (!isRecording) return;- const timer = window.setInterval(- () => setElapsed(Date.now() - startedAtRef.current),- 200,- );- return () => window.clearInterval(timer);- }, [isRecording]);-- useEffect(- () => () => {- saveRecordingRef.current = false;- if (recorderRef.current?.state !== "inactive") recorderRef.current?.stop();- releaseStream();- },- [releaseStream],- );-- const saveVoiceOver = useCallback(- async (blob: Blob, extension: string, startTime: number) => {- if (blob.size === 0) throw new Error("The microphone recording was empty.");- setIsSaving(true);- const beforeMediaIds = new Set(- useProjectStore.getState().project.mediaLibrary.items.map((item) => item.id),- );- const file = new File(- [blob],- `Voice-over ${new Date().toISOString().replace(/[:.]/g, "-")}.${extension}`,- { type: blob.type, lastModified: Date.now() },- );- const importResult = await importMedia(file);- if (!importResult.success) {- throw new Error(importResult.error?.message ?? "Could not import the recording.");- }- const mediaItem = useProjectStore- .getState()- .project.mediaLibrary.items.find((item) => !beforeMediaIds.has(item.id));- if (!mediaItem) throw new Error("The recorded audio could not be found after import.");- const addResult = await addClipToNewTrack(mediaItem.id, startTime);- if (!addResult.success) {- throw new Error(addResult.error?.message ?? "Could not add the voice over to the timeline.");+ if (phase !== "countdown" && phase !== "recording") return;+ const onKey = (event: KeyboardEvent) => {+ if (event.key === "Escape") {+ event.preventDefault();+ useVoiceOverStore.getState().cancel();}- const voiceTrack = useProjectStore- .getState()- .project.timeline.tracks.find((track) =>- track.clips.some((clip) => clip.mediaId === mediaItem.id),- );- if (voiceTrack) await renameTrack(voiceTrack.id, "Voice Over");- },- [addClipToNewTrack, importMedia, renameTrack],- );-- const startRecording = useCallback(async () => {- setError(null);- if (!navigator.mediaDevices?.getUserMedia || typeof MediaRecorder === "undefined") {- setError("Voice-over recording is not supported by this browser.");- return;- }- const format = selectVoiceOverMimeType();- if (!format) {- setError("This browser does not provide a supported microphone recording format.");- return;- }- try {- const stream = await navigator.mediaDevices.getUserMedia({- audio: {- ...(deviceId ? { deviceId: { exact: deviceId } } : {}),- echoCancellation: true,- noiseSuppression: true,- autoGainControl: true,- },- });- const recorder = new MediaRecorder(stream, {- mimeType: format.mimeType,- audioBitsPerSecond: 128_000,- });- const timelineStart = playheadPosition;- chunksRef.current = [];- saveRecordingRef.current = true;- streamRef.current = stream;- recorderRef.current = recorder;- recorder.ondataavailable = (event) => {- if (event.data.size > 0) chunksRef.current.push(event.data);- };- recorder.onerror = () => {- setError("The microphone recording stopped unexpectedly.");- };- recorder.onstop = () => {- const shouldSave = saveRecordingRef.current;- const blob = new Blob(chunksRef.current, { type: format.mimeType });- chunksRef.current = [];- releaseStream();- setIsRecording(false);- if (!shouldSave) return;- void saveVoiceOver(blob, format.extension, timelineStart)- .catch((reason) => {- setError(reason instanceof Error ? reason.message : "Could not save the voice over.");- })- .finally(() => setIsSaving(false));- };- startedAtRef.current = Date.now();- setElapsed(0);- recorder.start(250);- startMeter(stream);- setIsRecording(true);- } catch (reason) {- releaseStream();- setError(- reason instanceof DOMException && reason.name === "NotAllowedError"- ? "Allow microphone access to record a voice over."- : reason instanceof Error- ? reason.message- : "Could not start microphone recording.",- );- }- }, [deviceId, playheadPosition, releaseStream, saveVoiceOver, startMeter]);+ };+ window.addEventListener("keydown", onKey);+ return () => window.removeEventListener("keydown", onKey);+ }, [phase]);- const stopRecording = () => {- saveRecordingRef.current = true;- recorderRef.current?.stop();- };+ const headline =+ phase === "countdown"+ ? "Get ready"+ : phase === "recording"+ ? plan.punched ? "Recording punch" : "Recording"+ : phase === "saving"+ ? "Adding to timeline"+ : "Record at playhead";+ const subline =+ phase === "countdown"+ ? `Recording starts at ${timecode(plan.recordStart)}. Playback is running.`+ : phase === "recording"+ ? plan.recordEnd !== null+ ? `Stops automatically at ${timecode(plan.recordEnd)}.`+ : "Press Stop when you are done."+ : plan.punched+ ? `Punches ${timecode(plan.recordStart)} to ${timecode(plan.recordEnd ?? plan.recordStart)} on ${targetName}.`+ : `Starts at ${timecode(plan.recordStart)} on ${targetName}.`;return (- <div className="space-y-3">- <Card className="min-w-0 rounded-[7px] shadow-none bg-bg-2 text-fg p-3 flex items-center justify-between border border-border">- <div>- <span className="font-bold block text-[11px] text-fg">- Record at playhead+ <div className="space-y-3" data-testid="voiceover-panel" data-phase={phase}>+ <Card className="min-w-0 rounded-[7px] shadow-none bg-bg-2 text-fg p-3 flex items-center justify-between gap-3 border border-border">+ <div className="min-w-0">+ <span className="font-bold block text-[11px] text-fg">{headline}</span>+ <span className="text-fg-2 font-normal block text-[9px]" data-testid="voiceover-subline">{subline}</span>+ </div>+ {phase === "countdown" ? (+ <span+ className="font-mono text-2xl font-bold leading-none text-status-warning tabular-nums"+ role="timer"+ aria-live="assertive"+ data-testid="voiceover-countdown"+ >+ {countdown}</span>- <span className="text-fg-2 font-normal block text-[9px]">- Starts at {playheadPosition.toFixed(1)}s on a new Voice Over track.+ ) : (+ <span+ className={`flex items-center gap-1.5 font-mono text-sm tabular-nums ${phase === "recording" ? "text-red-400" : "text-fg-2"}`}+ data-testid="voiceover-elapsed"+ >+ {phase === "recording" && <span className="h-2 w-2 animate-pulse rounded-full bg-red-500" aria-hidden />}+ {formatClock(elapsedMs)}</span>- </div>- <span className={`font-mono text-sm ${isRecording ? "text-red-400" : "text-fg-2"}`}>- {formatElapsed(elapsed)}- </span>+ )}</Card>- <div className="space-y-1.5 rounded-[7px] border border-border bg-bg-2 p-3">- <div className="flex items-center justify-between gap-2">- <label htmlFor="voiceover-input" className="text-[11px] font-semibold text-fg">- Input- </label>++ <div className="space-y-2 rounded-[7px] border border-border bg-bg-2 p-3">+ <div className={ROW}>+ <label htmlFor="voiceover-input" className={LABEL}>Input</label><selectid="voiceover-input"data-testid="voiceover-device"- value={deviceId}- disabled={isRecording}- onChange={(event) => setDeviceId(event.target.value)}- className="h-7 min-w-0 max-w-[190px] flex-1 truncate rounded-md border border-border bg-bg-1 px-2 text-[11px] text-fg disabled:opacity-60"+ value={devices.some((device) => device.deviceId === prefs.deviceId) ? prefs.deviceId : ""}+ disabled={busy}+ onChange={(event) => setPrefs({ deviceId: event.target.value })}+ className={FIELD}><option value="">System default microphone</option>- {devices.map((device, index) => (- <option key={device.deviceId} value={device.deviceId}>- {device.label || `Microphone ${index + 1}`}- </option>+ {devices.map((device) => (+ <option key={device.deviceId} value={device.deviceId}>{device.label}</option>+ ))}+ </select>+ </div>+ {savedDeviceMissing && (+ <p className="text-[9px] text-status-warning" data-testid="voiceover-device-missing">+ Your saved microphone is not connected. The system default will be used.+ </p>+ )}+ <VoiceOverMeter level={level} active={phase !== "idle" && phase !== "saving"} />+ <div className={ROW}>+ <p className="text-[9px] text-fg-muted">+ {phase === "idle" ? "Check your level before recording." : "Live input level. Keep peaks out of the red."}+ </p>+ {(+ <button+ type="button"+ disabled={busy}+ data-testid="voiceover-monitor"+ onClick={() => (phase === "monitoring" ? useVoiceOverStore.getState().stopMonitor() : void useVoiceOverStore.getState().startMonitor())}+ className="shrink-0 rounded-md border border-border bg-bg-1 px-2 py-1 text-[10px] font-semibold text-fg hover:bg-bg-3 focus-visible:ring-2 focus-visible:ring-ring disabled:pointer-events-none disabled:opacity-40"+ >+ {phase === "monitoring" ? "Stop check" : "Check level"}+ </button>+ )}+ </div>+ </div>++ <div className="space-y-2 rounded-[7px] border border-border bg-bg-2 p-3">+ <div className={ROW}>+ <label htmlFor="voiceover-track" className={LABEL}>Record to</label>+ <select+ id="voiceover-track"+ data-testid="voiceover-track"+ value={audioTracks.some((track) => track.id === prefs.targetTrackId) ? prefs.targetTrackId : ""}+ disabled={busy}+ onChange={(event) => setPrefs({ targetTrackId: event.target.value })}+ className={FIELD}+ >+ <option value="">New Voice Over track</option>+ {audioTracks.map((track) => (+ <option key={track.id} value={track.id}>{track.name}</option>+ ))}+ </select>+ </div>+ <div className={ROW}>+ <label htmlFor="voiceover-preroll" className={LABEL}>Pre-roll</label>+ <select+ id="voiceover-preroll"+ data-testid="voiceover-preroll"+ value={prefs.preRoll}+ disabled={busy}+ onChange={(event) => setPrefs({ preRoll: Number(event.target.value) })}+ className={FIELD}+ >+ {Array.from({ length: MAX_PRE_ROLL_SECONDS + 1 }, (_, seconds) => (+ <option key={seconds} value={seconds}>{seconds === 0 ? "None" : `${seconds} s countdown`}</option>))}</select></div>- <VoiceOverMeter level={level} active={isRecording} />- <p className="text-[9px] text-fg-muted">- {isRecording ? "Live input level. Keep peaks out of the red." : "The level meter moves while you record."}- </p>+ <Toggle+ id="voiceover-punch"+ checked={prefs.punch && range !== null}+ disabled={busy || range === null}+ onChange={(punch) => setPrefs({ punch })}+ title="Punch in / out"+ hint={+ range+ ? `Record only between In ${timecode(range.start)} and Out ${timecode(range.end)}.`+ : "Set In and Out marks (I and O) on the timeline to enable."+ }+ />+ <Toggle+ id="voiceover-mute"+ checked={prefs.muteDuringRecord}+ disabled={busy}+ onChange={(muteDuringRecord) => setPrefs({ muteDuringRecord })}+ title="Mute playback while recording"+ hint="Silences the timeline once recording starts so speakers do not feed back into the microphone."+ /></div>+{error && (- <Card className="min-w-0 rounded-[7px] shadow-none text-fg p-2 flex items-start gap-2 border border-red-500/30 bg-red-500/10">+ <Card+ className="min-w-0 rounded-[7px] shadow-none text-fg p-2 flex items-start gap-2 border border-red-500/30 bg-red-500/10"+ role="alert"+ data-testid="voiceover-error"+ ><AlertCircle size={14} className="mt-0.5 shrink-0 text-red-400" aria-hidden />- <span className="font-normal text-[10px] text-red-400">{error}</span>+ <div className="min-w-0 space-y-1">+ <span className="block font-normal text-[10px] text-red-400">{error}</span>+ {(errorKind === "blocked" || errorKind === "denied") && typeof window !== "undefined" && window.openreel?.microphone && (+ <button+ type="button"+ data-testid="voiceover-open-settings"+ onClick={() => void window.openreel?.microphone?.openSettings()}+ className="rounded-md border border-red-500/40 px-2 py-0.5 text-[10px] font-semibold text-red-300 hover:bg-red-500/10 focus-visible:ring-2 focus-visible:ring-ring"+ >+ Open microphone settings+ </button>+ )}+ </div></Card>)}- {isRecording ? (- <Button onClick={stopRecording} type="button" aria-label="Stop & Add to Timeline" className="inline-flex min-w-0 items-center gap-1.5 rounded-[7px] font-semibold outline-none transition-colors focus-visible:ring-2 focus-visible:ring-ring disabled:pointer-events-none disabled:opacity-50 h-8 px-3 text-[12px] text-accent-fg w-full justify-center bg-red-500 hover:bg-red-600">- <span className="flex h-4 w-4 shrink-0 items-center justify-center">{<Square size={13} aria-hidden />}</span>- <span className="truncate">{"Stop & Add to Timeline"}</span>+ {lastTake?.note && (+ <p className="text-[10px] text-fg-2" data-testid="voiceover-note">{lastTake.note}</p>+ )}++ {phase === "countdown" ? (+ <Button+ onClick={() => useVoiceOverStore.getState().cancel()}+ type="button"+ aria-label="Cancel recording"+ className="inline-flex min-w-0 items-center gap-1.5 rounded-[7px] font-semibold outline-none transition-colors focus-visible:ring-2 focus-visible:ring-ring h-8 px-3 text-[12px] w-full justify-center bg-bg-3 text-fg hover:bg-bg-3/80"+ >+ <span className="truncate">Cancel (Esc)</span>+ </Button>+ ) : phase === "recording" ? (+ <Button+ onClick={() => useVoiceOverStore.getState().stop()}+ type="button"+ aria-label="Stop & Add to Timeline"+ className="inline-flex min-w-0 items-center gap-1.5 rounded-[7px] font-semibold outline-none transition-colors focus-visible:ring-2 focus-visible:ring-ring disabled:pointer-events-none disabled:opacity-50 h-8 px-3 text-[12px] text-accent-fg w-full justify-center bg-red-500 hover:bg-red-600"+ >+ <span className="flex h-4 w-4 shrink-0 items-center justify-center"><Square size={13} aria-hidden /></span>+ <span className="truncate">Stop & Add to Timeline</span></Button>) : (- <Button onClick={startRecording} type="button" aria-label={(isSaving ? "Adding Voice Over…" : "Record Voice Over").trim() || undefined} disabled={(isSaving)} className="inline-flex min-w-0 items-center gap-1.5 rounded-[7px] font-semibold outline-none transition-colors focus-visible:ring-2 focus-visible:ring-ring disabled:pointer-events-none disabled:opacity-50 h-8 px-3 text-[12px] bg-accent text-accent-fg hover:bg-accent/90 w-full justify-center">- <span className="flex h-4 w-4 shrink-0 items-center justify-center">{<Mic size={14} aria-hidden />}</span>- <span className="truncate">{isSaving ? "Adding Voice Over…" : "Record Voice Over"}</span>+ <Button+ onClick={() => void useVoiceOverStore.getState().start()}+ type="button"+ aria-label={phase === "saving" ? "Adding Voice Over…" : "Record Voice Over"}+ disabled={phase === "saving"}+ className="inline-flex min-w-0 items-center gap-1.5 rounded-[7px] font-semibold outline-none transition-colors focus-visible:ring-2 focus-visible:ring-ring disabled:pointer-events-none disabled:opacity-50 h-8 px-3 text-[12px] bg-accent text-accent-fg hover:bg-accent/90 w-full justify-center"+ >+ <span className="flex h-4 w-4 shrink-0 items-center justify-center"><Mic size={14} aria-hidden /></span>+ <span className="truncate">{phase === "saving" ? "Adding Voice Over…" : "Record Voice Over"}</span></Button>)}+{takes.length > 0 && (<section aria-label="Takes" data-testid="voiceover-takes" className="space-y-1">- <h4 className="text-[10px] font-semibold uppercase tracking-[0.12em] text-fg-muted">- Takes · {takes.length}- </h4>- {takes.map((take, index) => (+ <h4 className="text-[10px] font-semibold uppercase tracking-[0.12em] text-fg-muted">Takes · {takes.length}</h4>+ {takes.map((take) => (<buttonkey={take.clipId}type="button"+ data-testid="voiceover-take"onClick={() => {useTimelineStore.getState().seekTo(take.startTime);useUIStore.getState().select({ type: "clip", id: take.clipId, trackId: take.trackId });}}- className="flex w-full items-center justify-between rounded-md border border-border bg-bg-2 px-2.5 py-1.5 text-left text-[11px] text-fg hover:bg-bg-3 focus-visible:ring-2 focus-visible:ring-ring"+ className="flex w-full items-center justify-between gap-2 rounded-md border border-border bg-bg-2 px-2.5 py-1.5 text-left text-[11px] text-fg hover:bg-bg-3 focus-visible:ring-2 focus-visible:ring-ring">- <span>Take {index + 1}</span>- <span className="font-mono text-fg-muted">- {formatElapsed(take.startTime * 1000)} · {formatElapsed(take.duration * 1000)} long+ <span className="min-w-0 truncate">{take.name}</span>+ <span className="shrink-0 font-mono text-fg-muted">+ {timecode(take.startTime)} · {formatClock(take.duration * 1000)}</span></button>))}diff --git a/apps/web/src/components/editor/inspector/index.ts b/apps/web/src/components/editor/inspector/index.tsindex ed03bdae..780249b9 100644--- a/apps/web/src/components/editor/inspector/index.ts+++ b/apps/web/src/components/editor/inspector/index.ts@@ -52,6 +52,7 @@ export { EmphasisAnimationSection } from "./EmphasisAnimationSection";// Advanced Featuresexport { MotionTrackingSection } from "./MotionTrackingSection";+export { PlanarTrackingSection } from "./PlanarTrackingSection";export { NestedSequenceSection } from "./NestedSequenceSection";export { AdjustmentLayerSection } from "./AdjustmentLayerSection";export { AutoReframeSection } from "./AutoReframeSection";diff --git a/apps/web/src/components/editor/inspector/looks/CameraInputPicker.tsx b/apps/web/src/components/editor/inspector/looks/CameraInputPicker.tsxnew file mode 100644index 00000000..91f18185--- /dev/null+++ b/apps/web/src/components/editor/inspector/looks/CameraInputPicker.tsx@@ -0,0 +1,70 @@+import React, { useMemo } from "react";+import {+ CAMERA_FOOTAGE_COLOR_PRESETS,+ FOOTAGE_COLOR_PRESETS,+ cameraPresetOf,+ describeSourceColor,+ inputSpaceForItem,+ type FootageColorPreset,+} from "@openreel/core";+import { useProjectStore } from "../../../../stores/project-store";+import { applyFootageInterpretation, runOrganize } from "../../../../services/project-panel-commands";++const sectionTitle = "text-[10px] font-semibold uppercase tracking-wide text-fg-3";++/**+ * "Camera input": the camera log transform for the footage under the selected clip. It is the same setting as+ * Interpret Footage > Camera input (one undoable media edit), so the preview, scopes and export all read one value.+ * The transform runs first, before the Input LUT and the grade, and is formula based (no LUT file).+ */+const CameraInputPicker: React.FC<{ clipId: string }> = ({ clipId }) => {+ const mediaId = useProjectStore((s) => s.getClip(clipId)?.mediaId);+ const media = useProjectStore((s) => (mediaId ? s.project.mediaLibrary.items.find((i) => i.id === mediaId) : undefined));+ const makers = useMemo(() => [...new Set(CAMERA_FOOTAGE_COLOR_PRESETS.map((p) => p.camera!.maker))], []);++ if (!media || media.type === "audio") return null;+ const current = media.colorInterpretation;+ const camera = cameraPresetOf(current);+ const otherOverride = current && !camera ? FOOTAGE_COLOR_PRESETS.find((p) => p.id === current) : undefined;+ const value = camera ? camera.id : otherOverride ? otherOverride.id : "tagged";+ const transforming = inputSpaceForItem(media) !== null;++ const change = (next: string) => {+ const color: FootageColorPreset | null = next === "tagged" ? null : (next as FootageColorPreset);+ void runOrganize("Camera input", applyFootageInterpretation([media.id], { color }));+ };++ return (+ <div className="space-y-2" data-testid="camera-input">+ <div className={sectionTitle}>Camera input</div>+ <select+ aria-label="Camera input"+ value={value}+ onChange={(e) => change(e.target.value)}+ className="h-7 w-full min-w-0 rounded-[6px] border border-border bg-bg-1 px-2 text-[11px] text-fg"+ data-testid="camera-input-select"+ >+ <option value="tagged">None (as tagged)</option>+ {makers.map((maker) => (+ <optgroup key={maker} label={maker}>+ {CAMERA_FOOTAGE_COLOR_PRESETS.filter((p) => p.camera!.maker === maker).map((p) => (+ <option key={p.id} value={p.id}>+ {p.label}+ </option>+ ))}+ </optgroup>+ ))}+ {otherOverride && <option value={otherOverride.id}>{otherOverride.label} (Interpret Footage)</option>}+ </select>+ <div className="text-[9px] leading-snug text-fg-3" data-testid="camera-input-status">+ {camera+ ? `${describeSourceColor(camera.space)} to Rec.709. A built-in formula, applied to every clip of "${media.name}" before the Input LUT and the grade, in the preview, scopes and export.`+ : transforming+ ? "Footage is converted with its Interpret Footage setting."+ : "Pick the camera that shot this clip to convert its log footage to Rec.709. Leave on None for footage that is already Rec.709."}+ </div>+ </div>+ );+};++export default CameraInputPicker;diff --git a/apps/web/src/components/editor/inspector/looks/LooksAndLutsSection.tsx b/apps/web/src/components/editor/inspector/looks/LooksAndLutsSection.tsxindex f3597147..5e2b6b2d 100644--- a/apps/web/src/components/editor/inspector/looks/LooksAndLutsSection.tsx+++ b/apps/web/src/components/editor/inspector/looks/LooksAndLutsSection.tsx@@ -31,6 +31,7 @@ import FilterLooksPanel from "./FilterLooksPanel";import type { ColorGradingSettings } from "../../../../bridges/effects-bridge";import { LookCard, lookIconButton } from "./LookCard";import { CompareToggle, useLookCompare } from "./compare-context";+import CameraInputPicker from "./CameraInputPicker";/** Clips an apply action targets: the timeline selection, or the inspected clip. */function targetClipIds(clipId: string): string[] {@@ -316,6 +317,8 @@ const LooksAndLuts: React.FC<Props> = ({ clipId }) => {)}</div>+ <CameraInputPicker clipId={clipId} />+<div className="space-y-2"><div className={sectionTitle}>Input LUT</div><div className="text-[9px] leading-snug text-fg-3">diff --git a/apps/web/src/components/editor/inspector/tabs/AudioTab.tsx b/apps/web/src/components/editor/inspector/tabs/AudioTab.tsxindex c95bcf98..826b3670 100644--- a/apps/web/src/components/editor/inspector/tabs/AudioTab.tsx+++ b/apps/web/src/components/editor/inspector/tabs/AudioTab.tsx@@ -1,6 +1,7 @@import { PrimaryAudioProperties } from "../PrimaryAudioProperties";import { EssentialSoundSection } from "../EssentialSoundSection";import { SurroundPanSection } from "../SurroundPanSection";+import { AudioChannelsSection } from "../AudioChannelsSection";import React from "react";import { getChannelLayout } from "@openreel/core";import { useProjectStore } from "../../../../stores/project-store";@@ -46,6 +47,11 @@ export const AudioTab: React.FC<AudioTabProps> = ({</InspectorSection>)}{showAudioEffects && clip && <PrimaryAudioProperties clipId={clipId} />}+ {showAudioEffects && clip && (+ <InspectorSection title="Audio channels" sectionId="audio-channels" defaultOpen>+ <AudioChannelsSection clipIds={[clipId]} />+ </InspectorSection>+ )}{showAudioEffects && clip && surround && (<InspectorSection title="Surround pan" sectionId="surround-pan" defaultOpen><SurroundPanSection clipId={clipId} />diff --git a/apps/web/src/components/editor/inspector/tabs/EffectsTab.tsx b/apps/web/src/components/editor/inspector/tabs/EffectsTab.tsxindex 6cd4638d..b9ebb662 100644--- a/apps/web/src/components/editor/inspector/tabs/EffectsTab.tsx+++ b/apps/web/src/components/editor/inspector/tabs/EffectsTab.tsx@@ -16,6 +16,7 @@ import {PiPSection,MaskSection,MotionTrackingSection,+ PlanarTrackingSection,NestedSequenceSection,AdjustmentLayerSection,BackgroundRemovalSection,@@ -327,6 +328,12 @@ export const EffectsTab: React.FC<EffectsTabProps> = ({</InspectorSection>)}+ {showVideoControls && (+ <InspectorSection title="Planar Tracking" sectionId="planar-tracking">+ <PlanarTrackingSection clipId={clipId} />+ </InspectorSection>+ )}+{showVideoEffects && (<InspectorSection title="Video Effects" sectionId="video-effects"><VideoEffectsSection clipId={clipId} />diff --git a/apps/web/src/components/editor/inspector/useAutoCaptions.ts b/apps/web/src/components/editor/inspector/useAutoCaptions.tsindex 2ac5fa6f..f0713522 100644--- a/apps/web/src/components/editor/inspector/useAutoCaptions.ts+++ b/apps/web/src/components/editor/inspector/useAutoCaptions.ts@@ -1,3 +1,4 @@+import { backgroundTasks } from "@openreel/core/tasks/task-registry";import { useCallback, useEffect, useMemo, useRef, useState } from "react";import { SUBTITLE_STYLE_PRESETS, splitCaptionIntoSingleLineCues, type TranscriptionSegment, type Clip, type MediaItem } from "@openreel/core";import { getReferenceCaptionStyle } from "./reference-caption-style";@@ -144,6 +145,31 @@ export function useAutoCaptions({ clipId, clipIds, sourceTrackId, sourceLabel, mreturn () => { generation.current += 1; releaseWorker(); void audioContextRef.current?.close().catch(() => undefined); };}, [projectId, cancel, releaseWorker]);+ // Mirror the local transcription run into the unified background-task panel. One row per run:+ // it keeps its creation time while progress ticks and stays as history (completed / failed / cancelled).+ const taskIdRef = useRef<string | null>(null);+ const userCancelled = useRef(false);+ const cancelFromPanel = useCallback(() => { userCancelled.current = true; cancel(); }, [cancel]);+ useEffect(() => {+ if (isTranscribing) {+ if (!taskIdRef.current) { taskIdRef.current = `transcription:captions:${Date.now()}`; userCancelled.current = false; }+ backgroundTasks.upsert(+ { id: taskIdRef.current, kind: "transcription", source: "transcription", title: "Transcribing captions", detail: progressMessage || undefined, status: "running", progress },+ { cancel: cancelFromPanel },+ );+ return;+ }+ const id = taskIdRef.current;+ if (!id) return;+ taskIdRef.current = null;+ const base = { id, kind: "transcription" as const, source: "transcription", title: "Transcribing captions" };+ backgroundTasks.upsert(+ error ? { ...base, status: "failed", error }+ : userCancelled.current ? { ...base, status: "cancelled" }+ : { ...base, status: "completed", progress: 1 },+ );+ }, [isTranscribing, progress, progressMessage, cancelFromPanel, error]);+const sourceIsCurrent = useCallback((owner: NonNullable<typeof ownerRef.current>) => {const current = useProjectStore.getState();if (current.project.id !== owner.projectId || !owner.sources.every(({ clip, media }) => {diff --git a/apps/web/src/components/editor/panels/EffectsTransitionsPanel.tsx b/apps/web/src/components/editor/panels/EffectsTransitionsPanel.tsxindex 29f442d2..af47a045 100644--- a/apps/web/src/components/editor/panels/EffectsTransitionsPanel.tsx+++ b/apps/web/src/components/editor/panels/EffectsTransitionsPanel.tsx@@ -24,6 +24,7 @@ import {setClipLutEnabled,} from "../../../services/editor-effect-application";import { PRO_EFFECT_PREVIEWS } from "./proEffectPreviews";+import { BURN_IN_PREVIEWS } from "./burnInPreviews";// ─── Effect & Transition catalogs ──────────────────────────────────// Each item ships with a small CSS recipe used to animate the live@@ -38,7 +39,8 @@ export type EffectCategory =| "Stylize"| "Keying"| "Distort"- | "Generate";+ | "Generate"+ | "Time";type EffectCategoryFilter =| "All"| "Adjust"@@ -47,6 +49,7 @@ type EffectCategoryFilter =| "Distort"| "Generate"| "Keying"+ | "Time"| "Plugins"| "Audio";const workspaceEffectCategories: EffectCategoryFilter[] = [@@ -57,6 +60,7 @@ const workspaceEffectCategories: EffectCategoryFilter[] = ["Distort","Generate","Keying",+ "Time","Plugins","Audio",];@@ -73,7 +77,8 @@ function matchesEffectCategory(["Creative", "Stylize"].includes(effect.category)) ||(category === "Distort" && effect.category === "Distort") ||(category === "Generate" && effect.category === "Generate") ||- (category === "Keying" && effect.category === "Keying")+ (category === "Keying" && effect.category === "Keying") ||+ (category === "Time" && effect.category === "Time"));}@@ -301,6 +306,7 @@ const ALL_EFFECT_PREVIEWS: EditorEffectPreviewDef[] = [}),},...PRO_EFFECT_PREVIEWS,+ ...BURN_IN_PREVIEWS,{id: "cinematic-punch",type: "contrast",@@ -509,6 +515,7 @@ export const EDITOR_EFFECT_CATEGORIES: EffectCategory[] = ["Keying","Distort","Generate",+ "Time",];interface TransitionDef {diff --git a/apps/web/src/components/editor/panels/WorkspaceRecipesPanel.test.tsx b/apps/web/src/components/editor/panels/WorkspaceRecipesPanel.test.tsxindex e52ce398..fb0f830c 100644--- a/apps/web/src/components/editor/panels/WorkspaceRecipesPanel.test.tsx+++ b/apps/web/src/components/editor/panels/WorkspaceRecipesPanel.test.tsx@@ -127,8 +127,7 @@ describe("recipe progress cards", () => {);useEditorWorkspaceStore.getState().setSection("recipes");render(<AssetsPanel />);- const card = screen- .getByRole("heading", { name: "Remove silences" })+ const card = (await screen.findByRole("heading", { name: "Remove silences" })).closest("article")!;fireEvent.click(within(card).getByRole("button", { name: "Run" }));fireEvent.click(screen.getByRole("button", { name: "Analyze" }));diff --git a/apps/web/src/components/editor/panels/burnInPreviews.test.ts b/apps/web/src/components/editor/panels/burnInPreviews.test.tsnew file mode 100644index 00000000..d8f2ea7b--- /dev/null+++ b/apps/web/src/components/editor/panels/burnInPreviews.test.ts@@ -0,0 +1,32 @@+import { describe, expect, it } from "vitest";+import { BURN_IN_SPECS, withEffectDefaults } from "@openreel/core";+import { BURN_IN_PREVIEWS } from "./burnInPreviews";+import { EDITOR_EFFECT_PREVIEWS } from "./EffectsTransitionsPanel";+import { BURN_IN_CARD_SIZE_BOOST, previewNote, previewParams } from "./effect-previews/preview-params";++describe("burn-in effect cards", () => {+ it("lists Timecode and Clip Name once each under Generate, with the effect type as the card id", () => {+ expect(BURN_IN_PREVIEWS.map((d) => [d.id, d.type, d.label, d.category])).toEqual([+ ["burn-in-timecode", "burn-in-timecode", "Timecode", "Generate"],+ ["burn-in-name", "burn-in-name", "Clip Name", "Generate"],+ ]);+ for (const def of BURN_IN_PREVIEWS) {+ expect(EDITOR_EFFECT_PREVIEWS.filter((d) => d.type === def.type)).toHaveLength(1);+ expect(def.description).toBe(BURN_IN_SPECS[def.type as "burn-in-timecode"].description);+ }+ });++ it("applies with visible defaults and the card says its text is a sample", () => {+ for (const def of BURN_IN_PREVIEWS) {+ expect(withEffectDefaults(def.type, def.params)).toMatchObject({ opacity: 100, box: true });+ expect(previewNote({ kind: "effect", type: def.type } as Parameters<typeof previewNote>[0])).toBe("Sample text");+ }+ });++ it("enlarges the sample text at card scale and keeps the name clear of the badge, without touching other params", () => {+ const tc = previewParams({ kind: "effect", type: "burn-in-timecode" } as Parameters<typeof previewParams>[0], { size: 5, position: "bottom-center", opacity: 100 });+ expect(tc).toEqual({ size: 5 * BURN_IN_CARD_SIZE_BOOST, position: "bottom-center", opacity: 100 });+ const name = previewParams({ kind: "effect", type: "burn-in-name" } as Parameters<typeof previewParams>[0], { size: 4, position: "top-left" });+ expect(name).toEqual({ size: 4 * BURN_IN_CARD_SIZE_BOOST, position: "bottom-left" });+ });+});diff --git a/apps/web/src/components/editor/panels/burnInPreviews.ts b/apps/web/src/components/editor/panels/burnInPreviews.tsnew file mode 100644index 00000000..36c58243--- /dev/null+++ b/apps/web/src/components/editor/panels/burnInPreviews.ts@@ -0,0 +1,23 @@+import { BURN_IN_EFFECT_TYPES, BURN_IN_SPECS, type BurnInEffectType } from "@openreel/core";+import type { CSSProperties } from "react";+import type { EditorEffectPreviewDef } from "./EffectsTransitionsPanel";++/** CSS stand-in for the hover animation of the instant-preview fallback; the card itself shows the engine's real text. */+const PREVIEW_STYLES: Record<BurnInEffectType, (p: number) => CSSProperties> = {+ "burn-in-timecode": (p) => ({+ boxShadow: `inset 0 -${Math.round(8 + p * 4)}px 0 rgba(0,0,0,0.45)`,+ }),+ "burn-in-name": (p) => ({+ boxShadow: `inset 0 ${Math.round(8 + p * 4)}px 0 rgba(0,0,0,0.45)`,+ }),+};++/** Effects panel entries for the text burn-ins (Premiere Timecode and Clip Name), listed under Generate. */+export const BURN_IN_PREVIEWS: EditorEffectPreviewDef[] = BURN_IN_EFFECT_TYPES.map((type) => ({+ id: type,+ type,+ label: BURN_IN_SPECS[type].label,+ description: BURN_IN_SPECS[type].description,+ category: "Generate",+ previewStyle: PREVIEW_STYLES[type],+}));diff --git a/apps/web/src/components/editor/panels/effect-previews/effect-renderer.ts b/apps/web/src/components/editor/panels/effect-previews/effect-renderer.tsindex b7ca5ace..cb5f5419 100644--- a/apps/web/src/components/editor/panels/effect-previews/effect-renderer.ts+++ b/apps/web/src/components/editor/panels/effect-previews/effect-renderer.ts@@ -2,7 +2,9 @@ import { getDefaultTransitionParams, getGLContextCounters } from "@openreel/coreimport type {ChromaKeyEngine,ColorGradingEngine,+ EchoCompositor,Effect,+ UltraKeyParams,Transition,TransitionEngine,TransitionType,@@ -17,6 +19,13 @@ import { LaneSet, MAX_PREVIEW_LANES, SharedResourcePool, type PoolResource, typeimport { refreshAllPreviewEngines, type EffectRenderer, type PreviewEffectDef, type RenderInput } from "./preview-engine";import { lookEffectsFor, pickSampleKeyColor, previewParams } from "./preview-params";+/** Largest share of the footage a sampled (non-green) Ultra Key card may remove, so the subject stays visible. */+const SAMPLE_KEY_MAX_COVERAGE = 0.4;++function isPureGreenKey(key: { r: number; g: number; b: number }): boolean {+ return key.r === 0 && key.g === 1 && key.b === 0;+}+interface Lane {effects: VideoEffectsEngine;grading: ColorGradingEngine | null;@@ -24,6 +33,8 @@ interface Lane {transitions: TransitionEngine | null;transitionSize: string;video: VideoEngine | null;+ /** Echo cards: the compositor of the engine's own echo routine. */+ echo: EchoCompositor | null;}/** Stabilization crops the frame edges to leave room to steady it: the card shows that crop. */@@ -76,6 +87,7 @@ class PreviewGpuResources implements PoolResource {transitions: null,transitionSize: "",video: null,+ echo: null,};},(lane) => {@@ -83,6 +95,7 @@ class PreviewGpuResources implements PoolResource {lane.grading?.dispose();lane.video?.dispose();lane.transitions?.dispose();+ lane.echo?.dispose();},MAX_PREVIEW_LANES,() => this.disposeKinds(),@@ -156,6 +169,8 @@ export class EngineEffectRenderer implements EffectRenderer {if (def.type === "chromaKey") return await this.renderChromaKey(lane, modules, frame);+ if (def.type === "ultra-key") return await this.renderUltraKey(lane, modules, def, frame);+if (def.type === "lut") {if (!lane.grading) {lane.grading = new modules.ColorGradingEngine(frame.width, frame.height);@@ -170,10 +185,22 @@ export class EngineEffectRenderer implements EffectRenderer {return graded.image;}+ // Echo: the card's current frame and the earlier window frames, combined by the engine's EchoCompositor.+ if (def.type === "echo" && input.temporal?.echo && input.trail && input.trail.length > 0) {+ lane.echo ??= new modules.EchoCompositor();+ return await lane.echo.compose(+ frame,+ input.trail.map((entry) => ({ image: entry.frame, weight: entry.weight })),+ input.temporal.echo,+ );+ }+const params = previewParams(def, { ...(modules.withEffectDefaults(def.type, def.params) ?? {}) });// Time-driven shaders (scanlines, glitch, ...) animate off their own time uniform.if (def.type === "shader") params.time = input.sourceTime;- const effect: Effect = { id: "effect-preview", type: def.type, enabled: true, params };+ const sampled: Effect = { id: "effect-preview", type: def.type, enabled: true, params };+ // Burn-in cards draw the effect's own text for a sample clip (the badge says so), moving with the hover loop.+ const [effect] = modules.withBurnInText([sampled], { id: "effect-preview", mediaId: "sample", startTime: input.sourceTime }, 0, modules.BURN_IN_SAMPLE_SOURCE) as Effect[];const canvas = await lane.effects.applyEffectsToCanvas(frame, [effect]);return await createImageBitmap(canvas ?? frame);} catch (error) {@@ -284,6 +311,57 @@ export class EngineEffectRenderer implements EffectRenderer {}}+ /**+ * Ultra Key: the real effect (GLSL passes of the effects engine, the routine the Canvas2D fallback and export run) with its+ * default parameters on the footage, keyed on a sample colour because footage rarely has a green screen, over a transparency+ * checkerboard. The card carries the "Sample key" badge.+ */+ private async renderUltraKey(+ lane: Lane,+ modules: Awaited<ReturnType<typeof loadEngineModules>>,+ def: PreviewEffectDef,+ frame: ImageBitmap,+ ): Promise<ImageBitmap> {+ const probe = new OffscreenCanvas(48, 27);+ const probeCtx = probe.getContext("2d", { willReadFrequently: true });+ if (!probeCtx) throw new Error("2D canvas unavailable");+ probeCtx.drawImage(frame, 0, 0, probe.width, probe.height);+ const probeData = probeCtx.getImageData(0, 0, probe.width, probe.height).data;+ const key = pickSampleKeyColor(probeData);+ const params: Record<string, unknown> = {+ ...(modules.withEffectDefaults(def.type, def.params) ?? {}),+ keyR: Math.round(key.r * 255),+ keyG: Math.round(key.g * 255),+ keyB: Math.round(key.b * 255),+ };+ if (!isPureGreenKey(key)) {+ // A sampled (skin / dominant hue / grey) key is low in chroma, so the default tolerance would key out the whole+ // frame. Narrow the matte until the card still shows most of the footage, as an artist would by pulling Tolerance.+ const baseTolerance = Number(params.tolerance);+ const baseTransparency = Number(params.transparency);+ for (const tolerance of [baseTolerance, 40, 30, 22, 15, 10, 6, 3]) {+ if (tolerance > baseTolerance) continue;+ const transparency = Math.min(baseTransparency, tolerance * 0.9);+ const prep = modules.prepareUltraKey({ ...(params as unknown as UltraKeyParams), tolerance, transparency }, probe.height);+ let keyed = 0;+ for (let i = 0; i < probeData.length; i += 4) {+ if (modules.ultraKeyBaseMatte(probeData[i], probeData[i + 1], probeData[i + 2], prep) < 0.5) keyed++;+ }+ params.tolerance = tolerance;+ params.transparency = transparency;+ if (keyed / (probeData.length / 4) <= SAMPLE_KEY_MAX_COVERAGE) break;+ }+ }+ const effect: Effect = { id: "effect-preview", type: def.type, enabled: true, params };+ const keyed = await lane.effects.applyEffectsToCanvas(frame, [effect]);+ const out = new OffscreenCanvas(frame.width, frame.height);+ const ctx = out.getContext("2d");+ if (!ctx) throw new Error("2D canvas unavailable");+ checkerboard(ctx, frame.width, frame.height);+ ctx.drawImage(keyed ?? frame, 0, 0, frame.width, frame.height);+ return await createImageBitmap(out);+ }+/** Gives the lease back; the shared GPU set is disposed once no preview engine holds it (after a short idle grace). */dispose(): void {if (this.disposed) return;diff --git a/apps/web/src/components/editor/panels/effect-previews/preview-engine.test.ts b/apps/web/src/components/editor/panels/effect-previews/preview-engine.test.tsindex 22ffd857..b3190cf0 100644--- a/apps/web/src/components/editor/panels/effect-previews/preview-engine.test.ts+++ b/apps/web/src/components/editor/panels/effect-previews/preview-engine.test.ts@@ -106,6 +106,34 @@ describe("EffectPreviewEngine", () => {expect(engine.peek(defs[0], 0)).toBe(a);});+ it("hands Echo cards the earlier window frames, and Posterize Time cards the held frame", async () => {+ const { engine, renderer, windows } = setup();+ await engine.getWindow();+ const frames = windows[0].frameBitmaps;+ const echo: PreviewEffectDef = { id: "pro-echo", type: "echo" };+ await engine.render(echo, 9, "hover");+ const echoInput = vi.mocked(renderer.render).mock.calls.at(-1)?.[2];+ expect(echoInput?.frame).toBe(frames[9]);+ expect(echoInput?.trail?.map((entry) => entry.frame)).toEqual([frames[7], frames[5]]);+ expect(echoInput?.trail?.map((entry) => entry.weight)).toEqual([0.5, 0.25]);+ expect(echoInput?.temporal?.echo?.operator).toBe("add");++ const poster = await engine.renderPoster(echo);+ expect(poster).not.toBeNull();+ const posterInput = vi.mocked(renderer.render).mock.calls.at(-1)?.[2];+ expect(posterInput?.frame).toBe(frames[4]);+ expect(posterInput?.trail).toHaveLength(2);++ await engine.render({ id: "pro-posterize-time", type: "posterize-time" }, 4, "hover");+ const heldInput = vi.mocked(renderer.render).mock.calls.at(-1)?.[2];+ expect(heldInput?.frame).toBe(frames[3]);+ expect(heldInput?.trail).toBeUndefined();++ // Every other card keeps rendering the frame it is asked for+ await engine.render(defs[0], 4, "hover");+ expect(vi.mocked(renderer.render).mock.calls.at(-1)?.[2].frame).toBe(frames[4]);+ });+it("coalesces concurrent requests for the same frame", async () => {const { engine, renderer } = setup();const [a, b] = await Promise.all([engine.renderPoster(defs[1]), engine.renderPoster(defs[1])]);diff --git a/apps/web/src/components/editor/panels/effect-previews/preview-engine.ts b/apps/web/src/components/editor/panels/effect-previews/preview-engine.tsindex 306f947e..a5a0a24f 100644--- a/apps/web/src/components/editor/panels/effect-previews/preview-engine.ts+++ b/apps/web/src/components/editor/panels/effect-previews/preview-engine.ts@@ -2,6 +2,7 @@ import { transitionPosterProgress } from "./preview-params";import type { ClipColorGrading } from "@openreel/core";import { CostLruCache } from "./preview-cache";import { PriorityTaskQueue, TaskCancelledError, whenIdle, type TaskPriority } from "./task-queue";+import { isTemporalCard, planTemporalCard, type TemporalCardPlan } from "./temporal-preview";import { isSameSource, previewSourceKey, type PreviewSource } from "./source-selection";/** The part of an effect card the preview needs. Mirrors EditorEffectPreviewDef without importing the panel. */@@ -74,6 +75,10 @@ export interface RenderInput {/** Transitions only: 0..1 progress of the blend. */readonly progress: number;readonly sourceTime: number;+ /** Echo cards: the footage frames drawn behind `frame` (earlier moments of the window) and their opacity. */+ readonly trail?: readonly { readonly frame: ImageBitmap; readonly weight: number }[];+ /** Echo cards: the parameters the trail was planned with. */+ readonly temporal?: TemporalCardPlan;/*** True when this render is the card's poster (the at-rest tile), false for a hover frame. Time-driven cards use it* to pick the instant, or the set of instants, that shows what the preset does at rest.@@ -126,7 +131,12 @@ export const previewDefKey = (def: PreviewEffectDef): string => {};/** Cards with their own timeline (a blend, a preset's keyframes): the poster is a moment of it, not the playhead frame. */-const hasOwnTimeline = (def: PreviewEffectDef): boolean => def.kind === "transition" || def.kind === "overlay" || !!def.loop;+const hasOwnTimeline = (def: PreviewEffectDef): boolean =>+ def.kind === "transition" ||+ def.kind === "overlay" ||+ !!def.loop ||+ // Echo rests a few frames into the window so it has footage behind it (see temporal-preview.ts).+ ((def.kind === undefined || def.kind === "effect") && isTemporalCard(def.type));/*** Owns the shared footage window and the rendered-frame cache for the Effects@@ -410,9 +420,23 @@ export class EffectPreviewEngine {const transition = def.kind === "transition";const loop = def.loop;// Looping cards animate their own clock over the poster frame; everything else walks the footage window.- const frameIndex = index === POSTER_INDEX || loop ? window.posterIndex : index;+ // Time effects (Echo, Posterize Time) pick other frames of the window: see temporal-preview.ts.+ const temporal =+ !loop && (def.kind === undefined || def.kind === "effect") && isTemporalCard(def.type)+ ? planTemporalCard(def.type, def.params, window, index === POSTER_INDEX ? -1 : index)+ : null;+ const frameIndex = temporal ? temporal.frameIndex : index === POSTER_INDEX || loop ? window.posterIndex : index;const frame = await window.frame(frameIndex);if (!frame || generation !== this.generation || this.disposed) return null;+ let trail: { frame: ImageBitmap; weight: number }[] | undefined;+ if (temporal && temporal.trail.length > 0) {+ const frames = await Promise.all(temporal.trail.map((entry) => window.frame(entry.index)));+ if (generation !== this.generation || this.disposed) return null;+ trail = [];+ frames.forEach((trailFrame, at) => {+ if (trailFrame) trail?.push({ frame: trailFrame, weight: temporal.trail[at].weight });+ });+ }let partner: ImageBitmap | null = null;// Transitions blend by it; overlay cards read it as the position in the window (-1 at the poster).let progress = index === POSTER_INDEX ? -1 : frameIndex / Math.max(window.count - 1, 1);@@ -431,6 +455,8 @@ export class EffectPreviewEngine {partner,progress,sourceTime: loop ? progress * loop.seconds : (window.times[frameIndex] ?? 0),+ trail,+ temporal: temporal ?? undefined,poster: index === POSTER_INDEX,});} catch (error) {diff --git a/apps/web/src/components/editor/panels/effect-previews/preview-params.ts b/apps/web/src/components/editor/panels/effect-previews/preview-params.tsindex 49d0a6c6..e277c086 100644--- a/apps/web/src/components/editor/panels/effect-previews/preview-params.ts+++ b/apps/web/src/components/editor/panels/effect-previews/preview-params.ts@@ -7,7 +7,21 @@ import type { PreviewEffectDef } from "./preview-engine";*/export const GRAIN_CARD_BOOST = 2.5;+/**+ * Card-scale compensation for the text burn-ins: at ~150 px wide a 5 % high timecode is a smudge, so the text is drawn+ * 1.8x larger, and the clip name moves to the bottom where the card's "Sample text" badge does not cover it. The+ * badge says the text is a sample; every other parameter is the real default.+ */+export const BURN_IN_CARD_SIZE_BOOST = 1.8;+export function previewParams(def: PreviewEffectDef, resolved: Record<string, unknown>): Record<string, unknown> {+ if ((def.type === "burn-in-timecode" || def.type === "burn-in-name") && typeof resolved.size === "number") {+ return {+ ...resolved,+ size: Math.min(30, resolved.size * BURN_IN_CARD_SIZE_BOOST),+ ...(def.type === "burn-in-name" ? { position: "bottom-left" } : {}),+ };+ }if (def.type === "grain" && typeof resolved.amount === "number") {return { ...resolved, amount: Math.min(100, resolved.amount * GRAIN_CARD_BOOST) };}@@ -61,9 +75,16 @@ export function previewNote(def: PreviewEffectDef): string | null {if (def.kind === "transition") return null;switch (def.type) {case "chromaKey":+ case "ultra-key":return "Sample key";case "stabilize":return "Needs analysis";+ // A held frame is indistinguishable from the source in a still: the card shows it as it plays.+ case "posterize-time":+ return "Hover to play";+ case "burn-in-timecode":+ case "burn-in-name":+ return "Sample text";default:return null;}diff --git a/apps/web/src/components/editor/panels/effect-previews/temporal-preview.test.ts b/apps/web/src/components/editor/panels/effect-previews/temporal-preview.test.tsnew file mode 100644index 00000000..2e60be4e--- /dev/null+++ b/apps/web/src/components/editor/panels/effect-previews/temporal-preview.test.ts@@ -0,0 +1,55 @@+import { describe, expect, it } from "vitest";+import { ECHO_CARD_STRIDE, POSTERIZE_CARD_HOLD, isTemporalCard, planTemporalCard } from "./temporal-preview";+import { previewNote } from "./preview-params";++const win = { count: 24, fps: 12, posterIndex: 0 };++describe("temporal effect cards", () => {+ it("recognises the two time effects only", () => {+ expect(isTemporalCard("echo")).toBe(true);+ expect(isTemporalCard("posterize-time")).toBe(true);+ expect(isTemporalCard("posterize")).toBe(false);+ });++ it("rests an Echo poster far enough into the window to have footage behind it", () => {+ const plan = planTemporalCard("echo", undefined, win, -1);+ expect(plan.frameIndex).toBe(2 * ECHO_CARD_STRIDE);+ expect(plan.trail.map((t) => t.index)).toEqual([2, 0]);+ expect(plan.trail.map((t) => t.weight)).toEqual([0.5, 0.25]);+ expect(plan.echo?.operator).toBe("add");+ });++ it("builds the trail up from the first hover frame, like the start of a clip", () => {+ expect(planTemporalCard("echo", undefined, win, 0).trail).toEqual([]);+ expect(planTemporalCard("echo", undefined, win, 2).trail.map((t) => t.index)).toEqual([0]);+ expect(planTemporalCard("echo", undefined, win, 9).trail.map((t) => t.index)).toEqual([7, 5]);+ });++ it("follows the card's own echo count, intensity and operator", () => {+ const plan = planTemporalCard("echo", { echoes: 3, decay: 0.8, operator: "screen" }, win, 12);+ expect(plan.trail.map((t) => t.index)).toEqual([10, 8, 6]);+ expect(plan.trail[1].weight).toBeCloseTo(0.64, 9);+ expect(plan.echo?.operator).toBe("screen");+ expect(planTemporalCard("echo", { operator: "composite-front", echoes: 3 }, win, 12).trail.map((t) => t.index)).toEqual([6, 8, 10]);+ });++ it("is deterministic for a frame and clamps inside a short window", () => {+ expect(planTemporalCard("echo", undefined, win, 9)).toEqual(planTemporalCard("echo", undefined, win, 9));+ const short = planTemporalCard("echo", undefined, { count: 3, fps: 12, posterIndex: 0 }, -1);+ expect(short.frameIndex).toBe(2);+ expect(short.trail.map((t) => t.index)).toEqual([0]);+ expect(planTemporalCard("echo", undefined, { count: 1, fps: 12, posterIndex: 0 }, -1).trail).toEqual([]);+ });++ it("holds Posterize Time frames for POSTERIZE_CARD_HOLD window frames", () => {+ const shown = Array.from({ length: 12 }, (_, i) => planTemporalCard("posterize-time", undefined, win, i).frameIndex);+ expect(shown).toEqual([0, 0, 0, 3, 3, 3, 6, 6, 6, 9, 9, 9]);+ expect(new Set(shown).size).toBe(12 / POSTERIZE_CARD_HOLD);+ expect(planTemporalCard("posterize-time", undefined, win, -1).frameIndex).toBe(0);+ });++ it("badges the Posterize Time card, whose poster looks like the source", () => {+ expect(previewNote({ type: "posterize-time" })).toBe("Hover to play");+ expect(previewNote({ type: "echo" })).toBeNull();+ });+});diff --git a/apps/web/src/components/editor/panels/effect-previews/temporal-preview.ts b/apps/web/src/components/editor/panels/effect-previews/temporal-preview.tsnew file mode 100644index 00000000..23a849d3--- /dev/null+++ b/apps/web/src/components/editor/panels/effect-previews/temporal-preview.ts@@ -0,0 +1,64 @@+import { PRO_EFFECT_DEFAULTS, planEcho, posterizeTime, resolveEcho, type ResolvedEcho } from "@openreel/core";++/**+ * Echo and Posterize Time choose which frames of the clip are shown, so their cards walk the footage window+ * (real frames of the selected clip) instead of filtering one frame. The frame choice is the very math the+ * renderer uses (planEcho / posterizeTime); only the time scale is compensated for the card, like grain's boost:+ * at the real defaults (a 33 ms echo, 8 fps) the frames of a 2 s hover window are too close to tell apart.+ */++/** Window frames between the echoes of an Echo card (at 12 fps: a sixth of a second). */+export const ECHO_CARD_STRIDE = 2;+/** Window frames each held frame of a Posterize Time card lasts (12 fps held at 4 fps). */+export const POSTERIZE_CARD_HOLD = 3;++export const isTemporalCard = (type: string): boolean => type === "echo" || type === "posterize-time";++export interface TemporalWindow {+ readonly count: number;+ readonly fps: number;+ readonly posterIndex: number;+}++export interface TemporalCardPlan {+ /** Window frame shown as the current frame. */+ readonly frameIndex: number;+ /** Echo cards: the window frames drawn behind it, in compositing order, with their opacity. */+ readonly trail: readonly { readonly index: number; readonly weight: number }[];+ /** Echo cards: the resolved parameters (the user-facing defaults with the card-scale echo time). */+ readonly echo: ResolvedEcho | null;+}++const clampIndex = (index: number, count: number): number => Math.min(Math.max(index, 0), Math.max(count - 1, 0));++/**+ * `index` is the hover frame of the window, or a negative value for the poster. A poster rests a few frames into+ * the window so an Echo card has footage behind it to show; hover then plays from the window's first frame, where+ * the trail builds up exactly as it does at the start of a clip.+ */+export function planTemporalCard(+ type: string,+ params: Record<string, unknown> | undefined,+ window: TemporalWindow,+ index: number,+): TemporalCardPlan {+ const poster = index < 0;+ if (type === "posterize-time") {+ const at = poster ? window.posterIndex : index;+ const held = posterizeTime(at / window.fps, window.fps / POSTERIZE_CARD_HOLD);+ return { frameIndex: clampIndex(Math.round(held * window.fps), window.count), trail: [], echo: null };+ }+ const echo = resolveEcho({+ ...PRO_EFFECT_DEFAULTS.echo,+ ...(params ?? {}),+ echoTime: ECHO_CARD_STRIDE / window.fps,+ });+ const lead = echo.echoes * ECHO_CARD_STRIDE;+ const current = clampIndex(poster ? Math.max(window.posterIndex, lead) : index, window.count);+ const samples = planEcho(current / window.fps, window.count / window.fps, echo);+ return {+ frameIndex: current,+ trail: samples.map((sample) => ({ index: clampIndex(Math.round(sample.localTime * window.fps), window.count), weight: sample.weight })),+ echo,+ };+}diff --git a/apps/web/src/components/editor/panels/proEffectPreviews.test.ts b/apps/web/src/components/editor/panels/proEffectPreviews.test.tsindex 3e438de7..6f864312 100644--- a/apps/web/src/components/editor/panels/proEffectPreviews.test.ts+++ b/apps/web/src/components/editor/panels/proEffectPreviews.test.ts@@ -33,7 +33,7 @@ describe("pro effects in the effects browser", () => {for (const label of ["Gaussian Blur", "Mosaic", "Lens Distortion", "Mirror", "Posterize", "VHS / Glitch",]) expect(labels.filter((entry) => entry === label), label).toHaveLength(1);- const duplicateConcepts = [/pixelate|mosaic/i, /mirror/i, /lens distort|fisheye/i, /gaussian/i, /posterize/i, /vhs/i];+ const duplicateConcepts = [/pixelate|mosaic/i, /mirror/i, /lens distort|fisheye/i, /gaussian/i, /posterize(?! time)/i, /vhs/i];for (const concept of duplicateConcepts) {expect(labels.filter((label) => concept.test(label)), String(concept)).toHaveLength(1);}diff --git a/apps/web/src/components/editor/panels/proEffectPreviews.ts b/apps/web/src/components/editor/panels/proEffectPreviews.tsindex b6b2ffaf..9244791c 100644--- a/apps/web/src/components/editor/panels/proEffectPreviews.ts+++ b/apps/web/src/components/editor/panels/proEffectPreviews.ts@@ -69,6 +69,10 @@ const PREVIEW_STYLES: Record<ProEffectType, (p: number) => CSSProperties> = {filter: `hue-rotate(${lerp(0, 90, p)}deg) saturate(${lerp(1, 1.5, p)})`,opacity: lerp(1, 0.75, p),}),+ "ultra-key": (p) => ({+ filter: `hue-rotate(${lerp(0, 18, p)}deg) saturate(${lerp(1, 1.3, p)})`,+ boxShadow: `inset 0 0 0 ${lerp(0, 5, p)}px rgba(34,197,94,.75)`,+ }),"alpha-adjust": (p) => ({ opacity: lerp(1, 0.45, p) }),"leave-color": (p) => ({ filter: `grayscale(${lerp(0, 0.85, p)}) contrast(${lerp(1, 1.1, p)})` }),"change-to-color": (p) => ({ filter: `hue-rotate(${lerp(0, 140, p)}deg) saturate(${lerp(1, 1.3, p)})` }),@@ -116,6 +120,11 @@ const PREVIEW_STYLES: Record<ProEffectType, (p: number) => CSSProperties> = {backgroundImage: `radial-gradient(circle at 72% 28%, rgba(255,240,200,${lerp(0, 0.95, p)}) 0, rgba(255,200,120,${lerp(0, 0.4, p)}) 14%, transparent 34%)`,}),"strobe-light": (p) => ({ filter: `brightness(${p > 0.5 ? 1.9 : 1})` }),+ // Stand-ins for the CSS card fallback only; the real cards render real footage frames (effect-previews).+ echo: (p) => ({+ filter: `drop-shadow(${lerp(0, -7, p)}px 0 0 rgba(255,255,255,0.35)) drop-shadow(${lerp(0, -14, p)}px 0 0 rgba(255,255,255,0.18))`,+ }),+ "posterize-time": (p) => ({ transform: `translateX(${Math.floor(p * 4) * 2 - 3}px)` }),grid: (p) => ({backgroundImage: `linear-gradient(rgba(255,255,255,${lerp(0, 0.6, p)}) 1px, transparent 1px), linear-gradient(90deg, rgba(255,255,255,${lerp(0, 0.6, p)}) 1px, transparent 1px)`,backgroundSize: "12px 12px",diff --git a/apps/web/src/components/editor/preview/PlanarTrackOverlay.tsx b/apps/web/src/components/editor/preview/PlanarTrackOverlay.tsxnew file mode 100644index 00000000..7d306539--- /dev/null+++ b/apps/web/src/components/editor/preview/PlanarTrackOverlay.tsx@@ -0,0 +1,80 @@+import React, { useRef } from "react";+import { dragPlanarCorner, dragPlanarQuad, usePlanarTrackOverlayStore } from "../../../stores/planar-track-overlay-store";++interface Bounds { x: number; y: number; width: number; height: number }+const NAMES = ["top left", "top right", "bottom right", "bottom left"];++/**+ * The tracked surface as a draggable quad on the Program monitor. Drag a corner handle (or focus it and use the+ * arrow keys, Shift = 10 px) to fit the surface; drag inside the quad to move all four. `bounds` is the clip's+ * picture on the monitor, in the monitor frame's own pixels.+ */+export const PlanarTrackOverlay: React.FC<{ clipId: string | null; bounds: Bounds | null }> = ({ clipId, bounds }) => {+ const state = usePlanarTrackOverlayStore();+ const drag = useRef<{ corner: number | "quad"; x: number; y: number; start: number[] } | null>(null);+ if (!clipId || !bounds || state.clipId !== clipId || !state.corners || state.mediaWidth <= 0 || state.mediaHeight <= 0) return null;+ const { corners, mediaWidth, mediaHeight } = state;+ const sx = bounds.width / mediaWidth, sy = bounds.height / mediaHeight;+ const pts = [0, 1, 2, 3].map(i => ({ x: bounds.x + corners[i * 2] * sx, y: bounds.y + corners[i * 2 + 1] * sy }));+ const begin = (corner: number | "quad") => (event: React.PointerEvent) => {+ event.preventDefault(); event.stopPropagation();+ event.currentTarget.setPointerCapture(event.pointerId);+ drag.current = { corner, x: event.clientX, y: event.clientY, start: corners };+ };+ const move = (event: React.PointerEvent) => {+ const d = drag.current;+ if (!d) return;+ const dx = (event.clientX - d.x) / sx, dy = (event.clientY - d.y) / sy;+ state.edit(d.corner === "quad" ? dragPlanarQuad(d.start, dx, dy, mediaWidth, mediaHeight) : dragPlanarCorner(d.start, d.corner, dx, dy, mediaWidth, mediaHeight));+ };+ const end = (event: React.PointerEvent) => {+ if (event.currentTarget.hasPointerCapture(event.pointerId)) event.currentTarget.releasePointerCapture(event.pointerId);+ drag.current = null;+ };+ const nudge = (index: number) => (event: React.KeyboardEvent) => {+ const step = event.shiftKey ? 10 : 1;+ const delta = event.key === "ArrowLeft" ? [-step, 0] : event.key === "ArrowRight" ? [step, 0] : event.key === "ArrowUp" ? [0, -step] : event.key === "ArrowDown" ? [0, step] : null;+ if (!delta) return;+ event.preventDefault(); event.stopPropagation();+ state.edit(dragPlanarCorner(corners, index, delta[0], delta[1], mediaWidth, mediaHeight));+ };+ const path = pts.map(p => `${p.x},${p.y}`).join(" ");++ return (+ <div data-testid="planar-track-overlay" className="pointer-events-none absolute inset-0 z-30">+ <svg className="absolute inset-0 h-full w-full overflow-visible" aria-hidden="true">+ <polygon+ points={path}+ data-testid="planar-track-quad"+ className="pointer-events-auto cursor-move fill-accent/10 stroke-accent"+ strokeWidth={2}+ style={{ touchAction: "none" }}+ onPointerDown={begin("quad")}+ onPointerMove={move}+ onPointerUp={end}+ onPointerCancel={end}+ />+ </svg>+ {pts.map((p, i) => (+ <span+ key={i}+ role="slider"+ tabIndex={0}+ aria-label={`Planar track ${NAMES[i]} corner at ${Math.round(corners[i * 2])}, ${Math.round(corners[i * 2 + 1])}. Drag or use arrow keys.`}+ aria-valuenow={Math.round(corners[i * 2])}+ data-testid={`planar-track-corner-${i}`}+ className="pointer-events-auto absolute h-3 w-3 -translate-x-1/2 -translate-y-1/2 cursor-crosshair rounded-full border-2 border-black/70 bg-white outline-none focus-visible:ring-2 focus-visible:ring-accent"+ style={{ left: p.x, top: p.y, touchAction: "none" }}+ onPointerDown={begin(i)}+ onPointerMove={move}+ onPointerUp={end}+ onPointerCancel={end}+ onKeyDown={nudge(i)}+ />+ ))}+ <span className="pointer-events-none absolute rounded bg-black/65 px-1 py-0.5 text-[9px] font-semibold uppercase tracking-wide text-white/85" style={{ left: pts[0].x, top: Math.max(0, pts[0].y - 18) }}>+ Planar surface+ </span>+ </div>+ );+};diff --git a/apps/web/src/components/editor/preview/ProgramMonitorOverlays.tsx b/apps/web/src/components/editor/preview/ProgramMonitorOverlays.tsxindex f4119124..0817b32c 100644--- a/apps/web/src/components/editor/preview/ProgramMonitorOverlays.tsx+++ b/apps/web/src/components/editor/preview/ProgramMonitorOverlays.tsx@@ -1,5 +1,6 @@import React, { useCallback, useEffect, useRef } from "react";import {+ ultraKeyColorFromSample,qualifierFromSample,readQualifier,sampleAverageRgb,@@ -17,6 +18,7 @@ import { getPreviewCanvas } from "../scopes/preview-canvas-registry";import { applyFalseColor, FALSE_COLOR_BANDS } from "@openreel/core/video/scopes-extra";import { refreshProgramFrame } from "./program-frame-control";import { DroppedFrameIndicator } from "./DroppedFrameIndicator";+import { WhiteBalanceEyedropperLayer } from "./WhiteBalanceEyedropperLayer";/*** Program monitor overlays: the comparison view (side by side / wipe) and the@@ -54,6 +56,78 @@ function useSecondaryViewSync(): void {);}+/**+ * While the Ultra Key picker is armed the keyed effect shows its source, so the pick samples the+ * unkeyed frame; disarming (or leaving the clip) restores the live key.+ */+function useKeyPickerSync(): void {+ const picker = useColorMonitorStore((state) => state.keyPicker);+ useEffect(() => {+ if (!picker) return undefined;+ const bridge = getEffectsBridge();+ bridge.setTransientEffectParams(picker.effectId, { output: "source" });+ void refreshProgramFrame(useTimelineStore.getState().playheadPosition);+ return () => {+ bridge.setTransientEffectParams(picker.effectId, null);+ void refreshProgramFrame(useTimelineStore.getState().playheadPosition);+ };+ }, [picker]);+}++const KeyPickerLayer: React.FC = () => {+ const picker = useColorMonitorStore((state) => state.keyPicker);+ const setKeyPicker = useColorMonitorStore((state) => state.setKeyPicker);++ useEffect(() => {+ if (!picker) return undefined;+ const onKey = (event: KeyboardEvent) => {+ if (event.key === "Escape") setKeyPicker(null);+ };+ window.addEventListener("keydown", onKey);+ return () => window.removeEventListener("keydown", onKey);+ }, [picker, setKeyPicker]);++ if (!picker) return null;++ const pick = (event: React.PointerEvent<HTMLDivElement>) => {+ const source = getPreviewCanvas();+ if (!source || source.width === 0) return;+ const rect = event.currentTarget.getBoundingClientRect();+ const x = ((event.clientX - rect.left) / rect.width) * source.width;+ const y = ((event.clientY - rect.top) / rect.height) * source.height;+ const scratch = document.createElement("canvas");+ scratch.width = source.width;+ scratch.height = source.height;+ const ctx = scratch.getContext("2d", { willReadFrequently: true });+ if (!ctx) return;+ ctx.drawImage(source, 0, 0);+ const image = ctx.getImageData(0, 0, scratch.width, scratch.height);+ const [r, g, b] = sampleAverageRgb(image.data, image.width, image.height, x, y, 3);+ const store = useProjectStore.getState();+ const effect = store.getVideoEffect(picker.clipId, picker.effectId);+ setKeyPicker(null);+ if (!effect) return;+ void store.updateVideoEffect(+ picker.clipId,+ picker.effectId,+ ultraKeyColorFromSample({ r: r * 255, g: g * 255, b: b * 255 }),+ );+ };++ return (+ <div+ data-testid="ultra-key-picker-layer"+ aria-label="Key colour picker. Click the Program monitor to sample the key colour, Escape cancels."+ className="absolute inset-0 z-40 cursor-crosshair rounded-[10px] ring-2 ring-accent"+ onPointerDown={(event) => {+ event.preventDefault();+ event.stopPropagation();+ pick(event);+ }}+ />+ );+};+/*** Mounted only while a comparison mode is on, so the playhead / project* subscriptions below never re-render the Program monitor on every tick when@@ -390,11 +464,14 @@ const EyedropperLayer: React.FC = () => {export const ProgramMonitorOverlays: React.FC = () => {useSecondaryViewSync();+ useKeyPickerSync();return (<>+ <KeyPickerLayer /><ComparisonOverlayGate /><FalseColorToggle /><EyedropperLayer />+ <WhiteBalanceEyedropperLayer /><DroppedFrameIndicator /></>);diff --git a/apps/web/src/components/editor/preview/WhiteBalanceEyedropperLayer.test.tsx b/apps/web/src/components/editor/preview/WhiteBalanceEyedropperLayer.test.tsxnew file mode 100644index 00000000..88e3c6ab--- /dev/null+++ b/apps/web/src/components/editor/preview/WhiteBalanceEyedropperLayer.test.tsx@@ -0,0 +1,92 @@+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";+import { act, cleanup, fireEvent, render, screen } from "@testing-library/react";+import { useColorMonitorStore } from "../../../stores/color-monitor-store";++const apply = vi.fn();+const preview = vi.fn();+const read = vi.fn();++vi.mock("../../../services/white-balance-eyedropper", async (importOriginal) => ({+ ...(await importOriginal<typeof import("../../../services/white-balance-eyedropper")>()),+ applyWhiteBalancePick: (...args: unknown[]) => apply(...args),+ previewWhiteBalancePick: (...args: unknown[]) => preview(...args),+ readCanvasSample: (...args: unknown[]) => read(...args),+}));+vi.mock("../scopes/preview-canvas-registry", () => ({+ getPreviewCanvas: () => ({ width: 200, height: 100 }),+}));++import { WhiteBalanceEyedropperLayer } from "./WhiteBalanceEyedropperLayer";++const rect = { left: 0, top: 0, width: 200, height: 100, right: 200, bottom: 100, x: 0, y: 0, toJSON: () => ({}) } as DOMRect;++beforeEach(() => {+ // jsdom has no PointerEvent: without it clientX / button are dropped from pointer events.+ if (typeof window.PointerEvent === "undefined") {+ (window as unknown as { PointerEvent: typeof MouseEvent }).PointerEvent = class extends MouseEvent {} as typeof MouseEvent;+ }+ apply.mockReset().mockResolvedValue({ ok: true, solution: { temperature: -12, tint: 3, clamped: false, neutral: [0.5, 0.5, 0.5] } });+ preview.mockReset().mockReturnValue({ ok: true, solution: { temperature: -12, tint: 3, clamped: false, neutral: [0.5, 0.5, 0.5] } });+ read.mockReset().mockReturnValue([0.6, 0.5, 0.4]);+ vi.spyOn(HTMLElement.prototype, "getBoundingClientRect").mockReturnValue(rect);+ useColorMonitorStore.setState({ whiteBalancePick: null, whiteBalanceSize: 5 });+});+afterEach(() => {+ cleanup();+ vi.restoreAllMocks();+});++describe("White balance eyedropper layer", () => {+ it("renders only while armed and Esc cancels without picking", () => {+ render(<WhiteBalanceEyedropperLayer />);+ expect(screen.queryByTestId("wb-eyedropper-layer")).toBeNull();+ act(() => useColorMonitorStore.getState().setWhiteBalancePick({ clipId: "c" }));+ expect(screen.getByTestId("wb-eyedropper-layer").className).toContain("cursor-crosshair");+ fireEvent.keyDown(window, { key: "Escape" });+ expect(useColorMonitorStore.getState().whiteBalancePick).toBeNull();+ expect(screen.queryByTestId("wb-eyedropper-layer")).toBeNull();+ expect(apply).not.toHaveBeenCalled();+ });++ it("a click samples the clicked canvas pixel with the chosen footprint and disarms after applying", async () => {+ useColorMonitorStore.setState({ whiteBalanceSize: 1 });+ act(() => useColorMonitorStore.getState().setWhiteBalancePick({ clipId: "c" }));+ render(<WhiteBalanceEyedropperLayer />);+ fireEvent.pointerDown(screen.getByTestId("wb-eyedropper-layer"), { clientX: 100, clientY: 50, button: 0 });+ await act(async () => {});+ expect(read).toHaveBeenCalledWith(expect.anything(), 100, 50, 1);+ expect(apply).toHaveBeenCalledWith("c", [0.6, 0.5, 0.4], false);+ expect(useColorMonitorStore.getState().whiteBalancePick).toBeNull();+ });++ it("stays armed when the sample is clipped so another spot can be tried", async () => {+ apply.mockResolvedValue({ ok: false, reason: "unusable-sample" });+ act(() => useColorMonitorStore.getState().setWhiteBalancePick({ clipId: "c" }));+ render(<WhiteBalanceEyedropperLayer />);+ fireEvent.pointerDown(screen.getByTestId("wb-eyedropper-layer"), { clientX: 10, clientY: 10, button: 0 });+ await act(async () => {});+ expect(useColorMonitorStore.getState().whiteBalancePick).toEqual({ clipId: "c" });+ });++ it("right click cancels", () => {+ act(() => useColorMonitorStore.getState().setWhiteBalancePick({ clipId: "c" }));+ render(<WhiteBalanceEyedropperLayer />);+ fireEvent.pointerDown(screen.getByTestId("wb-eyedropper-layer"), { clientX: 10, clientY: 10, button: 2 });+ expect(useColorMonitorStore.getState().whiteBalancePick).toBeNull();+ expect(apply).not.toHaveBeenCalled();+ });++ it("hover shows the live Temperature / Tint read-out", async () => {+ vi.stubGlobal("requestAnimationFrame", (cb: (time: number) => void) => {+ cb(0);+ return 1;+ });+ act(() => useColorMonitorStore.getState().setWhiteBalancePick({ clipId: "c" }));+ render(<WhiteBalanceEyedropperLayer />);+ fireEvent.pointerMove(screen.getByTestId("wb-eyedropper-layer"), { clientX: 60, clientY: 30 });+ await act(async () => {});+ expect(screen.getByTestId("wb-eyedropper-readout").textContent).toContain("Temp -12");+ expect(screen.getByTestId("wb-eyedropper-readout").textContent).toContain("Tint +3");+ vi.unstubAllGlobals();+ });+});diff --git a/apps/web/src/components/editor/preview/WhiteBalanceEyedropperLayer.tsx b/apps/web/src/components/editor/preview/WhiteBalanceEyedropperLayer.tsxnew file mode 100644index 00000000..500b9a59--- /dev/null+++ b/apps/web/src/components/editor/preview/WhiteBalanceEyedropperLayer.tsx@@ -0,0 +1,291 @@+import React, { useCallback, useEffect, useRef, useState } from "react";+import { useColorMonitorStore } from "../../../stores/color-monitor-store";+import { getPreviewCanvas } from "../scopes/preview-canvas-registry";+import { toast } from "../../../stores/notification-store";+import { useTimelineStore } from "../../../stores/timeline-store";+import { useProjectStore } from "../../../stores/project-store";+import { captureWhiteBalanceInputFrame } from "../../../services/comparison-service";+import {+ applyWhiteBalancePick,+ clipNeedsWhiteBalanceInputFrame,+ previewWhiteBalancePick,+ readCanvasSample,+ WHITE_BALANCE_PICK_MESSAGES,+ type WhiteBalancePickResult,+} from "../../../services/white-balance-eyedropper";++/**+ * White Balance eyedropper over the Program monitor. Crosshair cursor, a+ * footprint box and a live read-out of what Temperature / Tint a click would+ * set. Click applies (one undo step) and disarms; Esc or right-click cancels.+ * DOM-only: the Program canvas, scopes and exports are untouched.+ */++interface HoverState {+ /** Overlay-relative pixel position of the cursor. */+ left: number;+ top: number;+ /** Footprint box size in overlay pixels. */+ box: number;+ rgb: [number, number, number] | null;+ result: WhiteBalancePickResult;+ /** The stage input frame is still rendering. */+ preparing: boolean;+}++/** Maps a pointer position to canvas pixels, honouring `object-fit: contain` letterboxing. */+function toCanvasPoint(+ rect: DOMRect,+ canvas: HTMLCanvasElement,+ clientX: number,+ clientY: number,+): { x: number; y: number; scale: number } | null {+ const scale = Math.min(rect.width / canvas.width, rect.height / canvas.height);+ if (!(scale > 0)) return null;+ const offsetX = (rect.width - canvas.width * scale) / 2;+ const offsetY = (rect.height - canvas.height * scale) / 2;+ const x = (clientX - rect.left - offsetX) / scale;+ const y = (clientY - rect.top - offsetY) / scale;+ if (x < 0 || y < 0 || x >= canvas.width || y >= canvas.height) return null;+ return { x, y, scale };+}++const fmt = (value: number): string => `${value > 0 ? "+" : ""}${Math.round(value)}`;++export const WhiteBalanceEyedropperLayer: React.FC = () => {+ const pick = useColorMonitorStore((state) => state.whiteBalancePick);+ const size = useColorMonitorStore((state) => state.whiteBalanceSize);+ const setPick = useColorMonitorStore((state) => state.setWhiteBalancePick);+ const [hover, setHover] = useState<HoverState | null>(null);+ const frame = useRef(0);+ const project = useProjectStore((state) => state.project);+ const playhead = useTimelineStore((state) => state.playheadPosition);+ const playing = useTimelineStore((state) => state.playbackState === "playing");+ const holdRef = useRef<HTMLCanvasElement>(null);+ const snapshot = useRef<ImageBitmap | null>(null);+ const [snapshotReady, setSnapshotReady] = useState(false);+ const generation = useRef(0);+ // The Program pixel only equals the white balance stage input on a plain clip; otherwise the+ // stage input is rendered once per frame (transient, preview-only) and the picker samples that.+ const needsInput = pick ? clipNeedsWhiteBalanceInputFrame(pick.clipId) : false;+ const inputMode = needsInput && !playing;++ /** Renders the clip's white balance stage input; the picture on screen is held still meanwhile. */+ const captureInput = useCallback(async (clipId: string): Promise<ImageBitmap | null> => {+ const program = getPreviewCanvas();+ const hold = holdRef.current;+ if (hold && program && program.width > 0 && program.height > 0) {+ hold.width = program.width;+ hold.height = program.height;+ hold.getContext("2d")?.drawImage(program, 0, 0);+ hold.style.visibility = "visible";+ }+ try {+ return await captureWhiteBalanceInputFrame(clipId);+ } finally {+ if (hold) hold.style.visibility = "hidden";+ }+ }, []);++ useEffect(() => {+ snapshot.current?.close();+ snapshot.current = null;+ setSnapshotReady(false);+ if (!pick || !inputMode) return;+ const id = ++generation.current;+ const timer = window.setTimeout(() => {+ void captureInput(pick.clipId).then((bitmap) => {+ if (id !== generation.current) {+ bitmap?.close();+ return;+ }+ snapshot.current = bitmap;+ setSnapshotReady(bitmap !== null);+ });+ }, 120);+ return () => {+ generation.current++;+ window.clearTimeout(timer);+ };+ }, [pick, inputMode, playhead, project, captureInput]);++ useEffect(+ () => () => {+ snapshot.current?.close();+ snapshot.current = null;+ },+ [],+ );++ useEffect(() => {+ if (!pick) return;+ const onKey = (event: KeyboardEvent) => {+ if (event.key !== "Escape") return;+ event.preventDefault();+ event.stopPropagation();+ setPick(null);+ };+ window.addEventListener("keydown", onKey, true);+ return () => {+ window.removeEventListener("keydown", onKey, true);+ cancelAnimationFrame(frame.current);+ };+ }, [pick, setPick]);++ useEffect(() => {+ if (!pick) setHover(null);+ }, [pick]);++ const sampleAt = useCallback(+ (target: HTMLDivElement, clientX: number, clientY: number, source?: ImageBitmap | null) => {+ const canvas = getPreviewCanvas();+ if (!canvas || !pick) return null;+ const rect = target.getBoundingClientRect();+ const point = toCanvasPoint(rect, canvas, clientX, clientY);+ if (!point) return null;+ const input = source ?? (inputMode ? snapshot.current : null);+ const rgb = inputMode && !input ? null : readCanvasSample(input ?? canvas, point.x, point.y, size);+ return { point, rgb, rect, inputFrame: input !== null };+ },+ [pick, size, inputMode],+ );++ if (!pick) return null;++ const onMove = (event: React.PointerEvent<HTMLDivElement>) => {+ const target = event.currentTarget;+ const { clientX, clientY } = event;+ cancelAnimationFrame(frame.current);+ frame.current = requestAnimationFrame(() => {+ const hit = sampleAt(target, clientX, clientY);+ if (!hit) {+ setHover(null);+ return;+ }+ setHover({+ left: clientX - hit.rect.left,+ top: clientY - hit.rect.top,+ box: Math.max(6, size * hit.point.scale),+ rgb: hit.rgb,+ result: previewWhiteBalancePick(pick.clipId, hit.rgb, hit.inputFrame),+ preparing: inputMode && !hit.inputFrame,+ });+ });+ };++ const onDown = (event: React.PointerEvent<HTMLDivElement>) => {+ event.preventDefault();+ event.stopPropagation();+ if (event.button === 2) {+ setPick(null);+ return;+ }+ if (event.button !== 0) return;+ const { clientX, clientY } = event;+ const target = event.currentTarget;+ void (async () => {+ // A click before the stage input finished rendering renders it now.+ let source: ImageBitmap | null = snapshot.current;+ if (inputMode && !source) source = await captureInput(pick.clipId);+ const hit = sampleAt(target, clientX, clientY, source);+ if (!hit) {+ if (source && source !== snapshot.current) source.close();+ return;+ }+ const result = await applyWhiteBalancePick(pick.clipId, hit.rgb, hit.inputFrame);+ if (source && source !== snapshot.current) source.close();+ if (result.ok) {+ setPick(null);+ const message = `Temperature ${fmt(result.solution.temperature)}, Tint ${fmt(result.solution.tint)}${+ result.solution.clamped ? " (limited to the slider range)" : ""+ }`;+ if (result.farFromNeutral) {+ toast.warning("White balance set from a coloured area", `${message}. That area was far from neutral; undo and pick a grey or white surface for a truer result.`);+ } else {+ toast.success("White balance set", message);+ }+ } else if (result.reason === "unusable-sample" || result.reason === "outside-clip") {+ // Stay armed so the user can pick a better spot.+ toast.warning("White balance", WHITE_BALANCE_PICK_MESSAGES[result.reason]);+ } else {+ setPick(null);+ toast.warning("White balance", WHITE_BALANCE_PICK_MESSAGES[result.reason]);+ }+ })();+ };++ const usable = hover?.result.ok === true;+ const swatch = hover?.rgb+ ? `rgb(${hover.rgb.map((v) => Math.round(v * 255)).join(",")})`+ : "transparent";++ return (+ <div+ data-testid="wb-eyedropper-layer"+ data-input-frame={inputMode ? (snapshotReady ? "ready" : "pending") : "live"}+ role="application"+ aria-label={`White balance eyedropper. Click a neutral area of the Program monitor to set Temperature and Tint. Escape cancels.`}+ className="absolute inset-0 z-40 cursor-crosshair rounded-[10px] ring-2 ring-accent"+ onPointerMove={onMove}+ onPointerLeave={() => {+ cancelAnimationFrame(frame.current);+ setHover(null);+ }}+ onPointerDown={onDown}+ onContextMenu={(event) => event.preventDefault()}+ >+ <canvas+ ref={holdRef}+ aria-hidden+ data-testid="wb-eyedropper-hold"+ className="pointer-events-none absolute inset-0 h-full w-full rounded-[10px] bg-black object-contain"+ style={{ visibility: "hidden" }}+ />+ <div className="pointer-events-none absolute left-2 top-2 rounded bg-black/70 px-2 py-1 text-[10px] font-medium text-white/90">+ White balance: click a neutral grey or white area. Esc cancels.+ </div>+ {hover ? (+ <>+ <div+ aria-hidden+ data-testid="wb-eyedropper-box"+ className="pointer-events-none absolute border border-white mix-blend-difference"+ style={{+ left: hover.left - hover.box / 2,+ top: hover.top - hover.box / 2,+ width: hover.box,+ height: hover.box,+ }}+ />+ <div+ data-testid="wb-eyedropper-readout"+ className="pointer-events-none absolute flex items-center gap-1.5 whitespace-nowrap rounded bg-black/80 px-1.5 py-1 text-[10px] text-white"+ style={{ left: hover.left + 14, top: hover.top + 14 }}+ >+ <span+ aria-hidden+ className="inline-block h-3 w-3 rounded-sm border border-white/60"+ style={{ background: swatch }}+ />+ {hover.preparing ? (+ <span className="text-white/70">Preparing frame...</span>+ ) : hover.result.ok ? (+ <span className={hover.result.farFromNeutral ? "text-amber-300" : undefined}>+ Temp {fmt(hover.result.solution.temperature)} · Tint {fmt(hover.result.solution.tint)}+ {hover.result.solution.clamped ? " (limit)" : ""}+ {hover.result.farFromNeutral ? " · not neutral" : ""}+ </span>+ ) : (+ <span className="text-white/70">+ {hover.result.reason === "unusable-sample" ? "Clipped: pick another area" : "Cannot pick here"}+ </span>+ )}+ </div>+ </>+ ) : null}+ <span className="sr-only" aria-live="polite">+ {usable ? "Neutral sample ready" : ""}+ </span>+ </div>+ );+};diff --git a/apps/web/src/components/editor/preview/canvas-renderers.ts b/apps/web/src/components/editor/preview/canvas-renderers.tsindex 31656757..d6a41ff0 100644--- a/apps/web/src/components/editor/preview/canvas-renderers.ts+++ b/apps/web/src/components/editor/preview/canvas-renderers.ts@@ -1,3 +1,4 @@+import { currentBurnInSource } from "../../../utils/burn-in-source";import {titleEngine,getAnimatedVideoEffects,@@ -35,6 +36,7 @@ import { overlayBlendAlpha } from "@openreel/core";import { displayLayoutWidth, normalizeSequencePar, withDisplaySpace } from "@openreel/core/video/sequence-par";import {DEFAULT_CAPTION_FONT_SIZE,+ captionFont,drawCaption,drawCaptionText,fillCaptionBox,@@ -1528,7 +1530,7 @@ const renderAnimatedSubtitle = (const fontFamily = style.fontFamily || "Inter";const baseColor = style.color || "#ffffff";- ctx.font = `bold ${fontSize}px "${fontFamily}"`;+ ctx.font = captionFont(fontSize, fontFamily);ctx.textBaseline = "middle";ctx.textAlign = "left";@@ -1814,7 +1816,7 @@ const applyEffectsToFrameGraded = async (const effectsBridge = getEffectsBridge();const animated = effectFrame && hasAnimatedVideoEffects(effectFrame.clip)- ? getAnimatedVideoEffects(effectFrame.clip, effectFrame.time - effectFrame.clip.startTime)+ ? getAnimatedVideoEffects(effectFrame.clip, effectFrame.time - effectFrame.clip.startTime, currentBurnInSource()): null;const isInit = effectsBridge.isInitialized();if (!isInit) {diff --git a/apps/web/src/components/editor/project-panel/InterpretFootageDialog.tsx b/apps/web/src/components/editor/project-panel/InterpretFootageDialog.tsxindex 41ff9b0b..200725ea 100644--- a/apps/web/src/components/editor/project-panel/InterpretFootageDialog.tsx+++ b/apps/web/src/components/editor/project-panel/InterpretFootageDialog.tsx@@ -2,6 +2,8 @@ import React from "react";import { Button, Dialog, DialogContent, DialogDescription, DialogFooter, DialogHeader, DialogTitle } from "@openreel/ui";import {FOOTAGE_COLOR_PRESETS,+ CAMERA_FOOTAGE_COLOR_PRESETS,+ cameraPresetOf,PIXEL_ASPECT_PRESETS,FIELD_ORDERS,DEINTERLACE_MODES,@@ -33,6 +35,7 @@ export const InterpretFootageDialog: React.FC<{ media: MediaItem; onClose: () =>const effective = effectiveSourceColor({ ...media, colorInterpretation: choice === "tagged" ? undefined : choice });const willTransform = inputSpaceForItem({ ...media, colorInterpretation: choice === "tagged" ? undefined : choice }) !== null;const hdr = isHdrTransfer(effective);+ const cameraLog = cameraPresetOf(choice === "tagged" ? undefined : choice);const isVideo = media.type === "video";const [fps, setFps] = React.useState(String(media.interpretation?.frameRate ?? media.metadata.frameRate ?? ""));@@ -77,12 +80,12 @@ export const InterpretFootageDialog: React.FC<{ media: MediaItem; onClose: () =>return (<Dialog open onOpenChange={(open) => !open && onClose()}>- <DialogContent className="max-w-[440px] border-border bg-bg-1 text-fg" data-testid="interpret-footage-dialog">+ <DialogContent className="max-h-[calc(100vh-2rem)] max-w-[440px] overflow-y-auto overflow-x-hidden border-border bg-bg-1 text-fg" data-testid="interpret-footage-dialog"><DialogHeader><DialogTitle>Interpret footage</DialogTitle><DialogDescription className="truncate">{media.name}</DialogDescription></DialogHeader>- <dl className="grid grid-cols-[110px_1fr] gap-x-3 gap-y-1 text-xs" data-testid="media-color-info">+ <dl className="grid grid-cols-[110px_minmax(0,1fr)] gap-x-3 gap-y-1 text-xs" data-testid="media-color-info"><dt className="text-fg-3">Tagged as</dt><dd data-testid="media-color-detected">{detected ? describeSourceColor(detected) : `${describeSourceColor(DEFAULT_SOURCE_COLOR)} - no colour tags`}</dd><dt className="text-fg-3">Treated as</dt>@@ -92,7 +95,9 @@ export const InterpretFootageDialog: React.FC<{ media: MediaItem; onClose: () =>{willTransform? hdr? "HDR to SDR working image (tone-mapped), identical in preview and export"- : "Gamut converted to Rec.709, identical in preview and export"+ : cameraLog+ ? "Camera log to Rec.709 (built-in formula, highlights rolled off), identical in preview and export"+ : "Gamut converted to Rec.709, identical in preview and export": "None: pixels are used as decoded"}</dd></dl>@@ -101,15 +106,34 @@ export const InterpretFootageDialog: React.FC<{ media: MediaItem; onClose: () =><input type="radio" name="interpret" checked={choice === "tagged"} onChange={() => setChoice("tagged")} data-testid="interpret-tagged" />As tagged{detected ? ` (${describeSourceColor(detected)})` : " (Rec.709)"}</label>- {FOOTAGE_COLOR_PRESETS.map((preset) => (+ {FOOTAGE_COLOR_PRESETS.filter((preset) => !preset.camera).map((preset) => (<label key={preset.id} className="flex items-center gap-2 text-xs"><input type="radio" name="interpret" checked={choice === preset.id} onChange={() => setChoice(preset.id)} data-testid={`interpret-${preset.id}`} />{preset.label}</label>))}</fieldset>+ <div className="grid grid-cols-[110px_minmax(0,1fr)] items-center gap-x-3 text-xs">+ <label htmlFor="interpret-camera" className="text-fg-3">Camera input (log)</label>+ <select+ id="interpret-camera"+ value={cameraLog ? choice : ""}+ onChange={(e) => e.target.value && setChoice(e.target.value as typeof choice)}+ className="h-7 w-full min-w-0 rounded border border-border bg-bg-2 px-1"+ data-testid="interpret-camera-select"+ >+ <option value="" disabled>None (use the option above)</option>+ {Array.from(new Set(CAMERA_FOOTAGE_COLOR_PRESETS.map((preset) => preset.camera?.maker ?? ""))).map((maker) => (+ <optgroup key={maker} label={maker}>+ {CAMERA_FOOTAGE_COLOR_PRESETS.filter((preset) => (preset.camera?.maker ?? "") === maker).map((preset) => (+ <option key={preset.id} value={preset.id}>{preset.label}</option>+ ))}+ </optgroup>+ ))}+ </select>+ </div>{isVideo && (- <div className="grid grid-cols-[110px_1fr] items-center gap-x-3 gap-y-2 text-xs" data-testid="interpret-timing">+ <div className="grid grid-cols-[110px_minmax(0,1fr)] items-center gap-x-3 gap-y-2 text-xs" data-testid="interpret-timing"><label htmlFor="interpret-fps" className="text-fg-3">Frame rate</label><inputid="interpret-fps"@@ -119,12 +143,12 @@ export const InterpretFootageDialog: React.FC<{ media: MediaItem; onClose: () =>step="any"value={fps}onChange={(e) => setFps(e.target.value)}- className="h-7 rounded border border-border bg-bg-2 px-2"+ className="h-7 w-full min-w-0 rounded border border-border bg-bg-2 px-2"data-testid="interpret-fps"/>{draftError && <p className="col-span-2 text-[10px] text-red-400" data-testid="interpret-error">{draftError}</p>}<label htmlFor="interpret-par" className="text-fg-3">Pixel aspect</label>- <div className="flex items-center gap-2">+ <div className="flex min-w-0 items-center gap-2"><selectaria-label="Pixel aspect preset"value={PIXEL_ASPECT_PRESETS.find((p) => Math.abs(p.value - Number(par)) < 1e-3)?.id ?? ""}@@ -135,7 +159,7 @@ export const InterpretFootageDialog: React.FC<{ media: MediaItem; onClose: () =>setParExact(preset.value);}}}- className="h-7 rounded border border-border bg-bg-2 px-1"+ className="h-7 w-full min-w-0 rounded border border-border bg-bg-2 px-1"data-testid="interpret-par-preset"><option value="">Custom</option>@@ -151,7 +175,7 @@ export const InterpretFootageDialog: React.FC<{ media: MediaItem; onClose: () =>step="any"value={par}onChange={(e) => { setPar(e.target.value); setParExact(null); }}- className="h-7 w-20 rounded border border-border bg-bg-2 px-2"+ className="h-7 w-20 shrink-0 rounded border border-border bg-bg-2 px-2"data-testid="interpret-par"/></div>@@ -166,7 +190,7 @@ export const InterpretFootageDialog: React.FC<{ media: MediaItem; onClose: () =>id="interpret-field"value={field}onChange={(e) => setField(e.target.value as FieldOrder)}- className="h-7 rounded border border-border bg-bg-2 px-1"+ className="h-7 w-full min-w-0 rounded border border-border bg-bg-2 px-1"data-testid="interpret-field">{FIELD_ORDERS.map((o) => (@@ -179,7 +203,7 @@ export const InterpretFootageDialog: React.FC<{ media: MediaItem; onClose: () =>value={deinterlace}disabled={field === "progressive"}onChange={(e) => setDeinterlace(e.target.value as DeinterlaceMode)}- className="h-7 rounded border border-border bg-bg-2 px-1"+ className="h-7 w-full min-w-0 rounded border border-border bg-bg-2 px-1"data-testid="interpret-deinterlace">{DEINTERLACE_MODES.map((m) => (@@ -202,7 +226,7 @@ export const InterpretFootageDialog: React.FC<{ media: MediaItem; onClose: () =>HDR and wide-gamut files itself, so only an override changes them there; the desktop app decodes them through ffmpeg and applies thefile's own tags.</p>- <DialogFooter>+ <DialogFooter className="sticky bottom-0 -mb-6 bg-bg-1 pb-6 pt-2"><Button variant="secondary" onClick={onClose}>Cancel</Button><Button onClick={apply} disabled={!!draftError || !!parError} data-testid="interpret-apply">Apply</Button></DialogFooter>diff --git a/apps/web/src/components/editor/settings/AudioOutputSelect.tsx b/apps/web/src/components/editor/settings/AudioOutputSelect.tsxnew file mode 100644index 00000000..e0c9d534--- /dev/null+++ b/apps/web/src/components/editor/settings/AudioOutputSelect.tsx@@ -0,0 +1,87 @@+import { useCallback, useEffect, useId, useState } from "react";+import { getAudioOutputRouter, type AudioOutputDevice } from "@openreel/core";+import { Button, Select, SelectContent, SelectItem, SelectTrigger, SelectValue, cn } from "@openreel/ui";+import { useSettingsStore } from "../../../stores/settings-store";++const DEFAULT_VALUE = "default";++/** Output devices from the shared router, kept fresh as devices are plugged and unplugged. */+export function useAudioOutputDevices(): { devices: AudioOutputDevice[]; support: ReturnType<ReturnType<typeof getAudioOutputRouter>["getSupport"]>; labelsHidden: boolean; fallbackActive: boolean; requestAccess: () => Promise<void> } {+ const router = getAudioOutputRouter();+ const [devices, setDevices] = useState<AudioOutputDevice[]>([]);+ const [fallbackActive, setFallbackActive] = useState(router.isFallbackActive());+ const refresh = useCallback(async () => {+ setDevices(await router.listDevices());+ setFallbackActive(router.isFallbackActive());+ }, [router]);+ useEffect(() => {+ void refresh();+ const stop = router.subscribe((event) => {+ if (event.type === "devices") setDevices([...event.devices]);+ setFallbackActive(router.isFallbackActive());+ });+ router.startWatching();+ return stop;+ }, [router, refresh]);+ const labelsHidden = devices.some((device) => !device.isDefault && /^Audio output \d+$/.test(device.label));+ const requestAccess = useCallback(async () => {+ await router.requestDeviceAccess();+ await refresh();+ }, [router, refresh]);+ return { devices, support: router.getSupport(), labelsHidden, fallbackActive, requestAccess };+}++/**+ * Monitor output picker shared by Preferences and the Audio Mixer. The choice is remembered; when+ * the device is unplugged playback continues on the system default and this shows the device as+ * disconnected until it returns.+ */+export function AudioOutputSelect({ className, compact = false, testId = "audio-output-select" }: { className?: string; compact?: boolean; testId?: string }) {+ const deviceId = useSettingsStore((state) => state.audioOutputDeviceId);+ const deviceLabel = useSettingsStore((state) => state.audioOutputDeviceLabel);+ const { devices, support, labelsHidden, fallbackActive, requestAccess } = useAudioOutputDevices();+ const statusId = useId();+ const selected = deviceId || DEFAULT_VALUE;+ const missing = deviceId !== "" && !devices.some((device) => device.deviceId === deviceId) && devices.length > 0;+ const unsupported = support === "none";+ const choose = (value: string) => {+ const id = value === DEFAULT_VALUE ? "" : value;+ const label = devices.find((device) => device.deviceId === id)?.label ?? "";+ useSettingsStore.getState().setAudioOutputDevice(id, label);+ };+ return (+ <div className={cn("flex min-w-0 flex-col gap-1", className)} data-testid={testId}>+ <Select value={selected} onValueChange={choose} disabled={unsupported}>+ <SelectTrigger+ aria-label="Audio output device"+ aria-describedby={statusId}+ data-testid={`${testId}-trigger`}+ className={cn("min-w-0 rounded-md bg-bg-2 px-2 text-xs", compact ? "h-7 w-[170px]" : "h-8 w-full")}+ >+ <SelectValue />+ </SelectTrigger>+ <SelectContent>+ <SelectItem value={DEFAULT_VALUE}>System default</SelectItem>+ {missing && <SelectItem value={deviceId}>{`${deviceLabel || "Saved device"} (disconnected)`}</SelectItem>}+ {devices.filter((device) => !device.isDefault).map((device) => (+ <SelectItem key={device.deviceId} value={device.deviceId}>{device.label}</SelectItem>+ ))}+ </SelectContent>+ </Select>+ <p id={statusId} role="status" className="text-[11px] leading-4 text-fg-2" data-testid={`${testId}-status`}>+ {unsupported+ ? "This browser can't choose an output device; audio plays on the system default."+ : missing || fallbackActive+ ? `${deviceLabel || "The saved device"} is disconnected. Playing on the system default until it returns.`+ : support === "element"+ ? "Routed through a media element in this browser; expect slightly higher latency."+ : compact ? "" : "Applies to preview playback and scrubbing. Exports are not affected."}+ </p>+ {labelsHidden && !unsupported && (+ <Button type="button" variant="outline" size="sm" className="h-7 w-fit px-2 text-xs" onClick={() => void requestAccess()} data-testid={`${testId}-reveal`}>+ Show device names+ </Button>+ )}+ </div>+ );+}diff --git a/apps/web/src/components/editor/settings/GeneralPanel.tsx b/apps/web/src/components/editor/settings/GeneralPanel.tsxindex 9ff7dde1..2f88381a 100644--- a/apps/web/src/components/editor/settings/GeneralPanel.tsx+++ b/apps/web/src/components/editor/settings/GeneralPanel.tsx@@ -3,7 +3,9 @@ import { useShallow } from "zustand/react/shallow";import { Button, Card, Checkbox, Input, Label, Select, SelectContent, SelectItem, SelectTrigger, SelectValue, Switch, ToggleGroup, ToggleGroupItem, cn } from "@openreel/ui";import { useSettingsStore, SERVICE_REGISTRY, type TtsProvider, type LlmProvider, type AggregatorProvider } from "../../../stores/settings-store";import { useProjectStore } from "../../../stores/project-store";+import { CHANNEL_PRESETS, CHANNEL_PRESET_LABELS, type ChannelPreset } from "@openreel/core";import { EDITING_FRAME_RATE_OPTIONS } from "../editing-frame-rate";+import { AudioOutputSelect } from "./AudioOutputSelect";const ASPECT_PRESETS = [{ label: "16:9 Landscape (1080p)", width: 1920, height: 1080 },@@ -29,7 +31,7 @@ function PreferenceText({ label, value, onChange, placeholder }: { label: stringexport function GeneralPanel() {const preferences = useSettingsStore(useShallow(state => ({ autoSave: state.autoSave, autoSaveInterval: state.autoSaveInterval,defaultTtsProvider: state.defaultTtsProvider, defaultLlmProvider: state.defaultLlmProvider, llmBaseUrl: state.llmBaseUrl,- llmModel: state.llmModel, defaultAggregator: state.defaultAggregator, configuredServices: state.configuredServices })));+ llmModel: state.llmModel, defaultAggregator: state.defaultAggregator, defaultAudioChannels: state.defaultAudioChannels, configuredServices: state.configuredServices })));const project = useProjectStore(state => state.project.settings);const projectId = useProjectStore(state => state.project.id);const backgroundFillMode = useProjectStore(state => state.project.timeline.backgroundFillMode);@@ -70,11 +72,22 @@ export function GeneralPanel() {</div></section><hr className="border-border" />+ <section className="space-y-3" aria-labelledby="audio-channels-settings-heading"><h3 id="audio-channels-settings-heading" className="text-sm font-medium">Audio</h3>+ <Card className="flex flex-col justify-between gap-3 rounded-md bg-bg-2 p-3 shadow-none sm:flex-row sm:items-center"><div className="min-w-0"><h4 className="text-xs font-medium">Default audio channels</h4><p className="mt-1 text-[11px] leading-4 text-fg-2">Applies to files you import from now on. "Use file" keeps each file's own channels; Mono plays the first channel only, Stereo plays the first two channels. Change any clip later with Clip > Audio Channels.</p></div>+ <PreferenceSelect label="Default audio channels" value={preferences.defaultAudioChannels} options={CHANNEL_PRESETS.map(preset => ({ value: preset, label: CHANNEL_PRESET_LABELS[preset] }))} onChange={value => useSettingsStore.getState().setDefaultAudioChannels(value as ChannelPreset)} />+ </Card>+ </section>+ <hr className="border-border" /><section className="space-y-3" aria-labelledby="autosave-settings-heading"><h3 id="autosave-settings-heading" className="text-sm font-medium">Auto-Save</h3><div className="flex items-center justify-between gap-3"><div><Label htmlFor={autoSaveId} className="text-xs">Enable auto-save</Label><p id={`${autoSaveId}-description`} className="mt-1 text-[11px] leading-4 text-fg-2">Automatically save your project at regular intervals</p></div><Switch id={autoSaveId} aria-describedby={`${autoSaveId}-description`} checked={preferences.autoSave} onCheckedChange={value => useSettingsStore.getState().setAutoSave(value)} /></div>{preferences.autoSave && <div className="flex flex-col gap-2 sm:flex-row sm:items-center"><span className="text-xs text-fg-2">Save every</span><PreferenceSelect label="Auto-save interval" value={String(preferences.autoSaveInterval)} onChange={value => useSettingsStore.getState().setAutoSaveInterval(Number(value))} options={[1, 2, 5, 10, 15, 30].map(value => ({ value: String(value), label: `${value} minute${value === 1 ? "" : "s"}` }))} /></div>}</section><hr className="border-border" />+ <section className="space-y-3" aria-labelledby="audio-output-settings-heading"><h3 id="audio-output-settings-heading" className="text-sm font-medium">Audio Output</h3>+ <div className="flex flex-col gap-2"><div className="min-w-0"><Label className="text-xs">Playback device</Label><p className="mt-1 text-[11px] leading-4 text-fg-2">Choose the speakers or headphones used for preview. Remembered between sessions; falls back to the system default if the device is unplugged.</p></div>+ <AudioOutputSelect testId="prefs-audio-output" className="w-full max-w-[320px]" /></div>+ </section>+ <hr className="border-border" /><section className="space-y-3" aria-labelledby="connection-settings-heading"><h3 id="connection-settings-heading" className="text-sm font-medium">AI Connections</h3><p className="text-xs leading-5 text-fg-2">Connect a compatible endpoint you control. OpenReel does not choose a vendor or model for you.</p><div className="flex flex-col gap-2 sm:flex-row sm:items-center sm:justify-between"><span className="text-xs text-fg-2">Text to Speech/Voice To Speech/Sound Effects</span><PreferenceSelect label="Text to Speech provider" value={preferences.defaultTtsProvider} onChange={value => useSettingsStore.getState().setDefaultTtsProvider(value as TtsProvider)} options={SERVICE_REGISTRY.filter(service => service.id === "elevenlabs").map(service => ({ value: service.id, label: service.label }))} /></div><div className="flex flex-col gap-2 sm:flex-row sm:items-center sm:justify-between"><span className="text-xs text-fg-2">Creative tools API format</span><PreferenceSelect label="Creative tools API format" value={preferences.defaultLlmProvider ?? "none"} onChange={value => useSettingsStore.getState().setDefaultLlmProvider(value === "none" ? null : value as LlmProvider)} options={[{ value: "none", label: "Choose API format…" }, ...llmProviders.map(service => ({ value: service.id, label: service.label }))]} /></div>diff --git a/apps/web/src/components/editor/timeline/ClipComponent.tsx b/apps/web/src/components/editor/timeline/ClipComponent.tsxindex 9ffdbaa9..0bd161a5 100644--- a/apps/web/src/components/editor/timeline/ClipComponent.tsx+++ b/apps/web/src/components/editor/timeline/ClipComponent.tsx@@ -1,4 +1,5 @@import { trackIdAtOffset } from "./track-hit-test";+import { useChannelWaveform } from "./use-channel-waveform";import { setDragResolvesOverlap } from "../../../stores/project/drag-placement";import { useEditorWorkspaceStore } from "../../../stores/editor-workspace-store";import { useTimelineTouchGesture, listenTimelineGesture } from "./touch-gestures";@@ -11,6 +12,7 @@ import { Box, Image, Layers } from "@/icons/lucide-compat";import { getCompoundClipId, type Clip, type Track, type TransitionType } from "@openreel/core";import { computeLaneInfos, type ClipLaneInfo } from "./clip-lane-info";import { useProjectStore } from "../../../stores/project-store";+import { ClipMarkerFlags } from "./ClipMarkerFlags";import { useUIStore } from "../../../stores/ui-store";import { useEditPointStore } from "../../../stores/edit-point-store";import { selectEditPoint } from "../../../services/edit-point-commands";@@ -895,6 +897,7 @@ const ClipComponentImpl: React.FC<ClipComponentProps> = ({{ length: thumbnailRange.end - thumbnailRange.start },(_, index) => thumbnailRange.start + index,);+ const channelWaveform = useChannelWaveform(clip, mediaItem, drawWaveform);const waveformBarCount = Math.max(1, Math.floor((width - 8) / 3));const waveformRange = getVisibleRepeatRange(left,@@ -906,7 +909,7 @@ const ClipComponentImpl: React.FC<ClipComponentProps> = ({const waveformAmplitudes = React.useMemo(() =>drawWaveform- ? getClipWaveformBarAmplitudes(mediaItem?.waveformData, {+ ? getClipWaveformBarAmplitudes(channelWaveform, {barCount: waveformBarCount,startBar: waveformRange.start,endBar: waveformRange.end,@@ -918,7 +921,7 @@ const ClipComponentImpl: React.FC<ClipComponentProps> = ({: [],[drawWaveform,- mediaItem?.waveformData,+ channelWaveform,mediaItem?.metadata.duration,waveformBarCount,waveformRange.start,@@ -1214,6 +1217,9 @@ const ClipComponentImpl: React.FC<ClipComponentProps> = ({</div>)}+ {(clip.markers?.length || mediaItem?.markers?.length) ? (+ <ClipMarkerFlags clip={clip} media={mediaItem} pixelsPerSecond={pixelsPerSecond} />+ ) : null}{splitOffset && <SplitEditBadge offsets={splitOffset} frameRate={frameRate} />}{(isVideo || isImage || isAudio) && onTrimClip && (<>diff --git a/apps/web/src/components/editor/timeline/ClipMarkerFlags.tsx b/apps/web/src/components/editor/timeline/ClipMarkerFlags.tsxnew file mode 100644index 00000000..2843713c--- /dev/null+++ b/apps/web/src/components/editor/timeline/ClipMarkerFlags.tsx@@ -0,0 +1,54 @@+import { memo, useMemo } from "react";+import { resolveClipMarkers, type Clip, type MediaItem } from "@openreel/core";++interface ClipMarkerFlagsProps {+ clip: Clip;+ media: Pick<MediaItem, "markers"> | undefined;+ pixelsPerSecond: number;+}++/**+ * Clip and master-clip markers drawn along the bottom edge of a timeline clip, at the timeline+ * offset that honours the clip's in point, speed and reverse. Range markers show as a bar. Master+ * markers (from the Source monitor) are drawn solid, clip markers with a lighter outline.+ */+function ClipMarkerFlagsImpl({ clip, media, pixelsPerSecond }: ClipMarkerFlagsProps) {+ const resolved = useMemo(() => resolveClipMarkers(clip, media), [clip, media]);+ if (resolved.length === 0) return null;+ return (+ <div className="pointer-events-none absolute inset-x-0 bottom-0 z-10 h-[10px]" data-testid="clip-marker-flags" aria-hidden="true">+ {resolved.map((r) => {+ const x = (r.timelineTime - clip.startTime) * pixelsPerSecond;+ const w = r.timelineDuration * pixelsPerSecond;+ return (+ <div+ key={`${r.scope}-${r.marker.id}`}+ data-testid="clip-marker-flag"+ data-scope={r.scope}+ data-marker-id={r.marker.id}+ title={`${r.scope === "master" ? "Master clip marker" : "Clip marker"}: ${r.marker.label}`}+ className="absolute bottom-0"+ style={{ left: x, width: w > 4 ? w : undefined }}+ >+ {w > 4 && <div className="absolute bottom-0 h-[3px] w-full opacity-80" style={{ backgroundColor: r.marker.color }} />}+ <svg+ width="9"+ height="10"+ viewBox="0 0 9 10"+ className="absolute bottom-0 left-0 -translate-x-[4px] drop-shadow-[0_0_1px_rgba(0,0,0,0.9)]"+ >+ <path+ d="M0.5 0.5h8v6l-4 3-4-3z"+ fill={r.marker.color}+ stroke={r.scope === "clip" ? "rgba(255,255,255,0.85)" : "rgba(0,0,0,0.55)"}+ strokeWidth="1"+ />+ </svg>+ </div>+ );+ })}+ </div>+ );+}++export const ClipMarkerFlags = memo(ClipMarkerFlagsImpl);diff --git a/apps/web/src/components/editor/timeline/TrackHeader.tsx b/apps/web/src/components/editor/timeline/TrackHeader.tsxindex 7e95d76a..4e7cb539 100644--- a/apps/web/src/components/editor/timeline/TrackHeader.tsx+++ b/apps/web/src/components/editor/timeline/TrackHeader.tsx@@ -50,6 +50,7 @@ export const TrackHeader: React.FC<TrackHeaderProps> = React.memo(function TrackhideTrack,muteTrack,soloTrack,+ setTrackSoloSafe,removeTrack,consolidateTrack,groupTracks,@@ -60,6 +61,7 @@ export const TrackHeader: React.FC<TrackHeaderProps> = React.memo(function TrackhideTrack: state.hideTrack,muteTrack: state.muteTrack,soloTrack: state.soloTrack,+ setTrackSoloSafe: state.setTrackSoloSafe,removeTrack: state.removeTrack,consolidateTrack: state.consolidateTrack,groupTracks: state.groupTracks,@@ -171,6 +173,7 @@ export const TrackHeader: React.FC<TrackHeaderProps> = React.memo(function Track{kind === "context" && isAudio && <><ContextMenuCheckboxItem checked={track.muted} onCheckedChange={checked => void muteTrack(track.id, checked === true)}>{`Mute ${track.name}`}</ContextMenuCheckboxItem><ContextMenuCheckboxItem checked={track.solo} onCheckedChange={checked => void soloTrack(track.id, checked === true)}>{`Solo ${track.name}`}</ContextMenuCheckboxItem>+ <ContextMenuCheckboxItem checked={track.soloSafe === true} onCheckedChange={checked => void setTrackSoloSafe(track.id, checked === true)}>{`Solo Safe ${track.name}`}</ContextMenuCheckboxItem><Separator /></>}<Item onSelect={startRename}><Pencil size={14} aria-hidden />Rename Track</Item>@@ -280,6 +283,7 @@ export const TrackHeader: React.FC<TrackHeaderProps> = React.memo(function Track{isAudio && <><DropdownMenuItem onSelect={() => void muteTrack(track.id, !track.muted)}>{track.muted ? "Unmute track" : "Mute track"}</DropdownMenuItem><DropdownMenuItem onSelect={() => void soloTrack(track.id, !track.solo)}>{track.solo ? "Clear solo" : "Solo track"}</DropdownMenuItem>+ <DropdownMenuItem onSelect={() => void setTrackSoloSafe(track.id, track.soloSafe !== true)}>{track.soloSafe === true ? "Turn off Solo Safe" : "Turn on Solo Safe"}</DropdownMenuItem></>}<DropdownMenuItem onSelect={() => void lockTrack(track.id, !track.locked)}>{track.locked ? "Unlock track" : "Lock track"}</DropdownMenuItem><DropdownMenuSeparator />{trackActions("dropdown")}diff --git a/apps/web/src/components/editor/timeline/use-channel-waveform.ts b/apps/web/src/components/editor/timeline/use-channel-waveform.tsnew file mode 100644index 00000000..5787b797--- /dev/null+++ b/apps/web/src/components/editor/timeline/use-channel-waveform.ts@@ -0,0 +1,65 @@+import { useEffect, useState } from "react";+import { applyChannelMapToChannels, isIdentityChannelMap, resolveClipChannelMap, type Clip, type ClipChannelMap, type MediaItem } from "@openreel/core";++const PEAKS_PER_SECOND = 100;+const MAX_DECODE_BYTES = 200 * 1024 * 1024;+/** Peaks of a media file as the given channel map plays it; null while computing or when it cannot be decoded. */+const peaksCache = new Map<string, Float32Array | null>();+const pending = new Map<string, Promise<Float32Array | null>>();+const mapKey = (map: ClipChannelMap): string => `${map.format}:${map.sources.join(",")}`;++async function computeMappedPeaks(blob: Blob, map: ClipChannelMap): Promise<Float32Array | null> {+ if (blob.size > MAX_DECODE_BYTES) return null;+ try {+ const context = new OfflineAudioContext(1, 1, 44100);+ const buffer = await context.decodeAudioData(await blob.arrayBuffer());+ const channels: Float32Array[] = [];+ for (let c = 0; c < buffer.numberOfChannels; c++) channels.push(buffer.getChannelData(c));+ const mapped = applyChannelMapToChannels(channels, map);+ const window = Math.max(1, Math.floor(buffer.sampleRate / PEAKS_PER_SECOND));+ const peaks = new Float32Array(Math.ceil(buffer.length / window));+ for (const data of mapped) {+ for (let i = 0; i < peaks.length; i++) {+ let peak = peaks[i];+ const end = Math.min(data.length, (i + 1) * window);+ for (let s = i * window; s < end; s++) {+ const value = Math.abs(data[s]);+ if (value > peak) peak = value;+ }+ peaks[i] = peak;+ }+ }+ return peaks;+ } catch {+ return null;+ }+}++/**+ * The waveform a timeline clip draws. Without an Audio Channels mapping this is the media's stored waveform; with+ * one it is recomputed from the mapped channels (left only draws only the left channel, a muted channel is flat),+ * so what you see matches what you hear.+ */+export function useChannelWaveform(clip: Pick<Clip, "id" | "channelMap" | "mediaId">, media: MediaItem | undefined, enabled: boolean): Float32Array | null | undefined {+ const map = media ? resolveClipChannelMap(clip, media) : undefined;+ const mapped = enabled && media?.blob && map && !isIdentityChannelMap(map, media.metadata.channels || 2) ? map : undefined;+ const key = mapped && media ? `${media.id}:${media.blob?.size ?? 0}:${mapKey(mapped)}` : null;+ const [, bump] = useState(0);+ useEffect(() => {+ if (!key || !mapped || !media?.blob || peaksCache.has(key) || pending.has(key)) return;+ const job = computeMappedPeaks(media.blob, mapped).then((peaks) => { peaksCache.set(key, peaks); pending.delete(key); return peaks; });+ pending.set(key, job);+ let live = true;+ void job.then(() => { if (live) bump((n) => n + 1); });+ return () => { live = false; };+ // eslint-disable-next-line react-hooks/exhaustive-deps+ }, [key]);+ useEffect(() => {+ if (!key || !pending.has(key)) return;+ let live = true;+ void pending.get(key)!.then(() => { if (live) bump((n) => n + 1); });+ return () => { live = false; };+ }, [key]);+ if (!key) return media?.waveformData;+ return peaksCache.get(key) ?? media?.waveformData;+}diff --git a/apps/web/src/components/editor/timeline/useTimelineToolGesture.ts b/apps/web/src/components/editor/timeline/useTimelineToolGesture.tsindex 94520538..34c2f1b6 100644--- a/apps/web/src/components/editor/timeline/useTimelineToolGesture.ts+++ b/apps/web/src/components/editor/timeline/useTimelineToolGesture.ts@@ -10,10 +10,12 @@ import {NUDGE_FRAMES,NUDGE_FRAMES_LARGE,prepareEdgeMove,+ prepareMultiRateStretch,prepareTimelineToolEdit,sideOfTrack,type TimelineToolMode,} from "@openreel/core";+import { v4 as uuidv4 } from "uuid";import { useProjectStore } from "../../../stores/project-store";import { useTimelineStore } from "../../../stores/timeline-store";import { useUIStore } from "../../../stores/ui-store";@@ -46,6 +48,7 @@ export function useTimelineToolGesture(tool: TimelineToolMode,edge: "left" | "right",unlinked = false,+ ripple = true,) => {const state = useProjectStore.getState();const project = state.getFullProject();@@ -71,6 +74,34 @@ export function useTimelineToolGesture([id],useEditorWorkspaceStore.getState().linkedSelection,);+ // Rate Stretch on a multi-selection: every selected clip (and linked+ // audio) is scaled by the primary's drag, trailing clips ripple.+ const selection = new Set(useUIStore.getState().getSelectedClipIds());+ const mediaSelected = project.timeline.tracks+ .flatMap((track) => track.clips)+ .filter((clip) => selection.has(clip.id));+ if (tool === "stretch" && mediaSelected.length > 1 && selection.has(id)) {+ const multi = prepareMultiRateStretch(project, {+ itemId: id,+ // Linked audio always stretches with its picture.+ clipIds: getLinkedTimelineSelection(project, mediaSelected.map((clip) => clip.id), true),+ edge,+ ripple,+ });+ const primary = project.timeline.tracks.flatMap((track) => track.clips).find((clip) => clip.id === id)!;+ return {+ prepared: {+ primary: primary as ReturnType<typeof prepareTimelineToolEdit>["primary"],+ mode: tool,+ preview: multi.preview,+ plan: (delta: number) => multi.plan(delta, uuidv4()),+ },+ owner: state.project,+ executor: state.actionExecutor,+ tracks: state.project.timeline.tracks,+ modifiedAt: state.project.modifiedAt,+ };+ }return {prepared: prepareTimelineToolEdit(project, {mode: tool,@@ -112,7 +143,14 @@ export function useTimelineToolGesture(if (locked() || active.current) return;let context: ReturnType<typeof prepare>;try {- context = prepare(id, altSplit ? "roll" : (mode as TimelineToolMode), edge ?? "right", altSplit);+ // Alt on the Rate Stretch tool switches ripple off for a multi-selection.+ context = prepare(+ id,+ altSplit ? "roll" : (mode as TimelineToolMode),+ edge ?? "right",+ altSplit,+ !(mode === "stretch" && event.altKey),+ );} catch (error) {toast.warning("Cannot edit this item",@@ -120,6 +158,7 @@ export function useTimelineToolGesture();return;}+ const noRipple = mode === "stretch" && event.altKey;const startX = event.clientX;const additive = event.shiftKey || event.metaKey || event.ctrlKey;const initialX = startX - lane.current.getBoundingClientRect().left;@@ -169,6 +208,8 @@ export function useTimelineToolGesture(const neighbors = (value.neighbors ?? (value.neighbor ? [value.neighbor] : [])).map((neighbor, index) => ({ ...neighbor, label: readout.neighbors[index] }),);+ if (mode === "stretch" && noRipple && (value.neighbors?.length ?? 0) > 0)+ readout.label += " · no ripple";useTimelineToolPreview.getState().setGhost({trackId: context.prepared.primary.trackId!,startTime: value.startTime,diff --git a/apps/web/src/desktop/editor/DesktopExportButton.tsx b/apps/web/src/desktop/editor/DesktopExportButton.tsxindex 8a0cd9ac..a6a81fde 100644--- a/apps/web/src/desktop/editor/DesktopExportButton.tsx+++ b/apps/web/src/desktop/editor/DesktopExportButton.tsx@@ -1,7 +1,7 @@import type { JSX } from "react";import React, { lazy, Suspense, useCallback, useEffect, useState } from "react";import type { VideoExportSettings } from "@openreel/core";-import { desktopExportRequiresNativeEncoder, setEncoderBackendFactory, WebCodecsBackend } from "@openreel/core";+import { desktopExportRequiresNativeEncoder, encoderChoiceForcesNative, setEncoderBackendFactory, WebCodecsBackend, webCodecsEncoderOptions } from "@openreel/core";import { useUIStore } from "../../stores/ui-store";import { useProjectStore } from "../../stores/project-store";import { addDialogExportToQueue, isExportQueueBusy } from "../../stores/export-queue-store";@@ -46,6 +46,7 @@ function shouldUseWebCodecs(settings: QuickVideoExportSettings): boolean {return (hasWebCodecs &&!desktopExportRequiresNativeEncoder(settings) &&+ !encoderChoiceForcesNative(settings.encoderChoice, settings.codec) &&(settings.codec === "h264" || settings.codec === "h265") &&(mode === "fast" || mode === "balanced"));@@ -123,7 +124,7 @@ export function DesktopExportButton({ compact = false }: { compact?: boolean } =setEncoderBackendFactory((mediabunny) =>mediabunny? new WebCodecsBackend(mediabunny, {- hardwareAcceleration: "prefer-hardware",+ ...webCodecsEncoderOptions(settings.encoderChoice),videoCodecs: [videoCodec],// Desktop streams frames to disk and uses the hardware encoder,// so export at the full (matched) resolution — no browser clamp.diff --git a/apps/web/src/e2e-hook.ts b/apps/web/src/e2e-hook.tsindex c3e8f131..09b1d6ed 100644--- a/apps/web/src/e2e-hook.ts+++ b/apps/web/src/e2e-hook.ts@@ -1,3 +1,4 @@+import { useVoiceOverStore } from "./services/voiceover/voiceover-recorder";import { useProjectStore } from "./stores/project-store";import { getActiveEffectPreviewEngine } from "./components/editor/panels/effect-previews/active-engine";import { previewGpuStats } from "./components/editor/panels/effect-previews/effect-renderer";@@ -7,6 +8,7 @@ import { useInspectorNavigationStore } from "./stores/inspector-navigation-storeimport { useTimelineStore } from "./stores/timeline-store";import { useEditorWorkspaceStore } from "./stores/editor-workspace-store";import { useUIStore } from "./stores/ui-store";+import { useSettingsStore } from "./stores/settings-store";import { useChatStore } from "./stores/chat-store";import { useAIConnectionStore } from "./stores/ai-connection-store";import { useSourceMonitorStore } from "./stores/source-monitor-store";@@ -27,6 +29,7 @@ import { useEngineStore } from "./stores/engine-store";import { analyzeTimelineLoudness } from "./services/loudness";import { deleteMediaBlob } from "./services/media-storage";import { proxyRecordId } from "@openreel/core";+import { backgroundTasks } from "@openreel/core/tasks/task-registry";import { previewProxyCache } from "./stores/preview-proxy-store";import { useProxyIngestStore, startProxyIngest } from "./services/proxy-ingest";import { getNativeDecodeSamples, clearNativeDecodeSamples } from "./services/native-decode";@@ -55,6 +58,8 @@ import { MotionShaderRenderer } from "@openreel/core/motion/motion-shader-renderimport * as proEffectsModule from "@openreel/core/video/pro-effects";import * as proEffectShadersModule from "@openreel/core/video/pro-effect-shaders";import * as proEffectsExtraModule from "@openreel/core/video/pro-effects-extra";+import * as temporalEffectsModule from "@openreel/core/video/temporal-effects";+import * as echoCompositorModule from "@openreel/core/video/echo-compositor";import * as motionShaderRendererModule from "@openreel/core/motion/motion-shader-renderer";import * as maskPathModule from "@openreel/core/video/mask-path";import * as canvas2dFallbackRendererModule from "@openreel/core/video/canvas2d-fallback-renderer";@@ -62,8 +67,11 @@ import * as colorGradingEngineModule from "@openreel/core/video/color-grading-enimport * as hueCurvesModule from "@openreel/core/video/hue-curves";import * as lumetriPipelineModule from "@openreel/core/video/lumetri-pipeline";import * as hdrWorkingModule from "@openreel/core/color/hdr-working";+import * as cameraLogModule from "@openreel/core/color/camera-log";+import * as inputTransformModule from "@openreel/core/color/input-transform";import * as hdrGpuModule from "@openreel/core/video/hdr-gpu";import * as colorOutputModule from "@openreel/core/export/color-output";+import * as burnInModule from "@openreel/core/video/burn-in";import { PRO_EFFECT_SHADER_DEFS } from "@openreel/core/video/pro-effect-shaders";import { computeScopeStats } from "@openreel/core/video/scope-stats";import { useColorMonitorStore } from "./stores/color-monitor-store";@@ -113,6 +121,8 @@ export function installE2EHook(): void {aiConnection: useAIConnectionStore,onboardingAi: { mount: mountAiOnboardingSheet },timeline: useTimelineStore,+ /** Voice-over recorder (pre-roll, punch, takes): phase, prefs and the last placed take. */+ voiceover: useVoiceOverStore,/** Effects panel live previews: the mounted preview engine (stats, cache, source) or null. */effectPreviews: getActiveEffectPreviewEngine,/** Preview GPU budget: shared lanes / shader renderers / live engine-owned WebGL contexts (created, released, live). */@@ -133,6 +143,7 @@ export function installE2EHook(): void {inspectorNav: useInspectorNavigationStore,workspace: useEditorWorkspaceStore,ui: useUIStore,+ settings: useSettingsStore,source: useSourceMonitorStore,multicam: useMulticamStore,multicamController,@@ -160,6 +171,7 @@ export function installE2EHook(): void {projectFile: { openEditorProject, projectManager, lock: useProjectLockStore, retryProjectLock },renderCache: renderCacheService,exportQueue: useExportQueueStore,+ backgroundTasks,/** Changed-source guard: the full-content fingerprint the renderer sends to the desktop copy path. */sourceFingerprint: { fingerprintBlob, computeFingerprint, fingerprintMismatch },autoSave: autoSaveManager,@@ -211,6 +223,8 @@ export function installE2EHook(): void {proEffects: proEffectsModule,proEffectShaders: proEffectShadersModule,proEffectsExtra: proEffectsExtraModule,+ temporalEffects: temporalEffectsModule,+ echoCompositor: echoCompositorModule,motionShaderRenderer: motionShaderRendererModule,maskPath: maskPathModule,canvas2dFallbackRenderer: canvas2dFallbackRendererModule,@@ -218,8 +232,11 @@ export function installE2EHook(): void {hueCurves: hueCurvesModule,lumetriPipeline: lumetriPipelineModule,hdrWorking: hdrWorkingModule,+ cameraLog: cameraLogModule,+ inputTransform: inputTransformModule,hdrGpu: hdrGpuModule,colorOutput: colorOutputModule,+ burnIn: burnInModule,},sequences: sequenceCommands,graphics: {diff --git a/apps/web/src/hooks/useKeyboardShortcuts.ts b/apps/web/src/hooks/useKeyboardShortcuts.tsindex 13f78558..aa710229 100644--- a/apps/web/src/hooks/useKeyboardShortcuts.ts+++ b/apps/web/src/hooks/useKeyboardShortcuts.ts@@ -1,3 +1,4 @@+import { addClipMarkerAtPlayhead } from "../services/clip-marker-commands";import { v4 as uuidv4 } from "uuid";import { planRippleTrimToPlayhead } from "@openreel/core";import { useColorMonitorStore } from "../stores/color-monitor-store";@@ -37,6 +38,7 @@ import {goToNextMarker,goToPreviousMarker,} from "../services/marker-commands";+import { openClipSpeedDialog } from "../services/clip-speed-multi";import { flushEditorFieldDrafts } from "../services/editor-field-drafts";import {addEditToAllTracks,@@ -45,6 +47,7 @@ import {insertSelectedMedia,liftRange,matchFrame,+ reverseMatchFrame,overwriteSelectedMedia,pasteInsertClips,commit,@@ -52,6 +55,7 @@ import {pickPasteTrack,runWithToast,} from "../services/premiere-edit-commands";+import { fitToFillFromSource, replaceFromSource } from "../services/source-monitor-commands";import {toggleSyncLockOnSelectedTrack,toggleTargetOnSelectedTrack,@@ -438,6 +442,8 @@ export function useKeyboardShortcuts() {if (editPointSelected()) trimEditPoint(1, false);else runWithToast("Overwrite", overwriteSelectedMedia);}],+ ["editing.replaceEdit", () => runWithToast("Replace", () => replaceFromSource())],+ ["editing.fitToFill", () => runWithToast("Fit to Fill", () => fitToFillFromSource())],["editing.trimEditLeftLarge", () => trimEditPoint(-1, true)],["editing.trimEditRightLarge", () => trimEditPoint(1, true)],["editing.lift", () => runWithToast("Lift", liftRange)],@@ -462,6 +468,8 @@ export function useKeyboardShortcuts() {if (!outcome.success) toast.warning("Sync Lock", outcome.message);})],["editing.matchFrame", () => runWithToast("Match frame", matchFrame)],+ ["editing.reverseMatchFrame", () => runWithToast("Reverse match frame", reverseMatchFrame)],+ ["editing.speedDuration", () => runWithToast("Speed/Duration", openClipSpeedDialog)],["linked.replace", () => void replaceSelectionWithLinkedComposition()],["linked.open", () => void openSelectedLinkedComposition()],["linked.render", () => void renderSelectedLinkedComposition()],@@ -513,6 +521,7 @@ export function useKeyboardShortcuts() {});}],["tools.addMarker", () => { void addMarkerAtPlayhead(); }],+ ["tools.addClipMarker", () => { void addClipMarkerAtPlayhead(); }],["tools.editMarker", editMarkerAtPlayhead],["tools.nextMarker", () => { goToNextMarker(); }],["tools.prevMarker", () => { goToPreviousMarker(); }],diff --git a/apps/web/src/main.tsx b/apps/web/src/main.tsxindex 423606c1..f90ce63e 100644--- a/apps/web/src/main.tsx+++ b/apps/web/src/main.tsx@@ -5,10 +5,7 @@ import "./index.css";import { AppProviders } from "./components/AppProviders";import { registerServiceWorker } from "./services/service-worker";import { initCustomFonts } from "./components/editor/inspector/font-options";-import { setEncoderBackendFactory } from "@openreel/core";-import { NativeFFmpegBackend } from "./services/native-ffmpeg-backend";-import { installDesktopNativeDecode } from "./services/native-decode";-import { startNativePathHydration } from "./services/native-path-hydration";+import { setEncoderBackendFactory } from "@openreel/core/export/encoder-backend";import { installRawWorker } from "./services/raw-worker-client";import { startRawThumbnailSync } from "./services/raw-thumbnails";import { compositionIdFromHash } from "./services/linked-comp-protocol";@@ -26,18 +23,30 @@ if (import.meta.env.VITE_OPENREEL_E2E === "1") {const isDesktop =typeof window !== "undefined" && window.openreel?.platform === "desktop";-if (isDesktop) {- installDesktopNativeDecode();- startNativePathHydration();- setEncoderBackendFactory(- () =>- new NativeFFmpegBackend(- () =>- (window as { __openreelExportPath?: string }).__openreelExportPath ??- "",- ),- );-}+// Desktop native decode, path hydration and the ffmpeg export backend are desktop-only, so they load as a+// separate chunk instead of sitting in the web entry. The first render waits for them (in parallel with the+// DesktopApp chunk, see renderApplication), so no import, decode or export can start before they are installed.+const desktopNativeReady: Promise<void> = !isDesktop+ ? Promise.resolve()+ : Promise.all([+ import("./services/native-decode"),+ import("./services/native-path-hydration"),+ import("./services/native-ffmpeg-backend"),+ ]).then(([decode, hydration, backend]) => {+ decode.installDesktopNativeDecode();+ hydration.startNativePathHydration();+ setEncoderBackendFactory(+ () =>+ new backend.NativeFFmpegBackend(+ () =>+ (window as { __openreelExportPath?: string }).__openreelExportPath ??+ "",+ ),+ );+ })+ .catch((error: unknown) => {+ console.error("[openreel] desktop native decode / export backend failed to load", error);+ });// The editor chunk (1.6 MB) and engine init are warmed by DesktopApp's idle callback// once the welcome screen is mounted. Queueing them here instead made the editor@@ -68,6 +77,7 @@ async function renderApplication(): Promise<void> {// A linked composition window shows only that composition's editor (see linked-comp-bridge).const compositionId = compositionIdFromHash(window.location.hash);if (compositionId) {+ await desktopNativeReady;await renderCompositionWindow(compositionId);return;}@@ -81,9 +91,12 @@ async function renderApplication(): Promise<void> {const loadDesktopApp = () => import("./desktop/DesktopApp");// A failed chunk fetch must not leave a blank window: retry once, then fall back to the// lazy/Suspense path so the failure surfaces through React like it did before.- const module = await loadDesktopApp()- .catch(() => new Promise<void>((resolve) => setTimeout(resolve, 400)).then(loadDesktopApp))- .catch(() => null);+ const [module] = await Promise.all([+ loadDesktopApp()+ .catch(() => new Promise<void>((resolve) => setTimeout(resolve, 400)).then(loadDesktopApp))+ .catch(() => null),+ desktopNativeReady,+ ]);if (module) {application = <module.DesktopApp />;} else {diff --git a/apps/web/src/services/agent/export-job-runner.ts b/apps/web/src/services/agent/export-job-runner.tsindex 7ee21c66..4cba0d8d 100644--- a/apps/web/src/services/agent/export-job-runner.ts+++ b/apps/web/src/services/agent/export-job-runner.ts@@ -12,6 +12,7 @@ import {isValidLoudnessTarget,setEncoderBackendFactory,WebCodecsBackend,+ webCodecsEncoderOptions,type LoudnessTargetSettings,} from "@openreel/core";import { useProjectStore } from "../../stores/project-store";@@ -316,7 +317,7 @@ export function createExportJobRunner(): JobRunner {setEncoderBackendFactory((mediabunny) =>mediabunny? new WebCodecsBackend(mediabunny, {- hardwareAcceleration: "prefer-hardware",+ ...webCodecsEncoderOptions(settings.encoderChoice),videoCodecs: [videoCodec],clampResolution: false,})diff --git a/apps/web/src/services/audio-channels.ts b/apps/web/src/services/audio-channels.tsnew file mode 100644index 00000000..5387281b--- /dev/null+++ b/apps/web/src/services/audio-channels.ts@@ -0,0 +1,111 @@+import { v4 as uuidv4 } from "uuid";+import {+ getMediaItemCapabilities,+ type ActionResult,+ type Clip,+ type ClipChannelMap,+ type MediaItem,+ type Project,+ type Track,+} from "@openreel/core";+import { useProjectStore } from "../stores/project-store";+import { useUIStore } from "../stores/ui-store";+import { useAudioChannelsStore } from "../stores/audio-channels-store";+import { cloneProjectForEdit } from "../stores/project/clone-project-for-edit";++/** A clip that has audio the dialog can map: audio-track clips and video clips whose file carries audio. */+export function clipHasMappableAudio(project: Project, clip: Clip): boolean {+ const media = project.mediaLibrary.items.find((item) => item.id === clip.mediaId);+ if (!media) return false;+ const track = project.timeline.tracks.find((candidate) => candidate.clips.some((c) => c.id === clip.id));+ return track?.type === "audio" || getMediaItemCapabilities(media).audio;+}++export function selectedAudioClipIds(): string[] {+ const { project } = useProjectStore.getState();+ const selected = useUIStore.getState().selectedItems.filter((item) => item.type === "clip").map((item) => item.id);+ const clips = project.timeline.tracks.flatMap((track) => track.clips);+ return selected.filter((id) => {+ const clip = clips.find((candidate) => candidate.id === id);+ return clip ? clipHasMappableAudio(project, clip) : false;+ });+}++/** Clip > Audio Channels…: opens the dialog for the selected clips (no-op without a selected clip that has audio). */+export function openAudioChannelsForSelection(ids: readonly string[] = selectedAudioClipIds()): boolean {+ if (ids.length === 0) return false;+ useAudioChannelsStore.getState().openFor(ids);+ return true;+}++/** Sets (map) or clears (null) the channel map of one or many clips: one undoable step. */+export function setClipChannelMap(clipIds: readonly string[], map: ClipChannelMap | null): Promise<ActionResult> {+ return useProjectStore.getState().executeAction({+ id: uuidv4(),+ timestamp: Date.now(),+ type: "audio/setChannelMap",+ params: { clipIds: [...clipIds], map },+ });+}++const sourceChannelsOf = (media: MediaItem | undefined): number => Math.max(1, media?.metadata.channels || 2);++/** Whether Split to mono is offered: one multichannel clip (audio file or video with embedded audio) on an unlocked track. */+export function canSplitToMono(project: Project, clipId: string): boolean {+ const track = project.timeline.tracks.find((candidate) => candidate.clips.some((c) => c.id === clipId));+ const clip = track?.clips.find((c) => c.id === clipId);+ const media = clip && project.mediaLibrary.items.find((item) => item.id === clip.mediaId);+ return !!track && !!media && !track.locked && getMediaItemCapabilities(media).audio && sourceChannelsOf(media) >= 2;+}++/**+ * Split to mono clips (Premiere: Break Out to Mono): the clip keeps its first channel as a mono clip and+ * every further source channel (up to 8) becomes its own mono clip on a new audio track, in sync, one undo step.+ */+export async function splitClipToMono(clipId: string): Promise<ActionResult> {+ const current = useProjectStore.getState();+ const { project, actionExecutor } = current;+ const failure = (message: string): ActionResult => ({ success: false, error: { code: "INVALID_PARAMS", message } });+ if (!canSplitToMono(project, clipId)) return failure("Only an unlocked clip with stereo or multichannel audio can be split to mono.");+ const sourceTrack = project.timeline.tracks.find((track) => track.clips.some((c) => c.id === clipId)) as Track;+ const clip = sourceTrack.clips.find((c) => c.id === clipId) as Clip;+ const media = project.mediaLibrary.items.find((item) => item.id === clip.mediaId);+ const channels = Math.min(sourceChannelsOf(media), 8);+ const projectCopy = cloneProjectForEdit(project);+ const history = actionExecutor.getHistory();+ const undoSizeBefore = history.getUndoStackSize();+ let committed = false;+ history.beginGroup("Split to mono clips");+ try {+ let result: ActionResult = await actionExecutor.execute(+ { type: "audio/setChannelMap", id: uuidv4(), timestamp: Date.now(), params: { clipIds: [clipId], map: { format: "mono", sources: [0] } } },+ projectCopy,+ );+ if (!result.success) return result;+ for (let channel = 1; channel < channels; channel++) {+ const trackId = uuidv4();+ result = await actionExecutor.execute(+ { type: "track/add", id: uuidv4(), timestamp: Date.now(), params: { trackType: "audio", trackId, name: `${sourceTrack.name} ${channel + 1}` } },+ projectCopy,+ );+ if (!result.success) return result;+ result = await actionExecutor.execute(+ {+ type: "clip/add", id: uuidv4(), timestamp: Date.now(),+ params: {+ trackId, mediaId: clip.mediaId, startTime: clip.startTime,+ sourceClip: { ...clip, id: uuidv4(), trackId, channelMap: { format: "mono", sources: [channel] } },+ },+ },+ projectCopy,+ );+ if (!result.success) return result;+ }+ useProjectStore.setState({ project: { ...projectCopy, modifiedAt: Date.now() } });+ committed = true;+ return result;+ } finally {+ history.endGroup();+ if (!committed && history.getUndoStackSize() > undoSizeBefore) await actionExecutor.undo(projectCopy);+ }+}diff --git a/apps/web/src/services/audio-mixer-channels.ts b/apps/web/src/services/audio-mixer-channels.tsindex 28b96da1..d1f5a1ea 100644--- a/apps/web/src/services/audio-mixer-channels.ts+++ b/apps/web/src/services/audio-mixer-channels.ts@@ -4,7 +4,7 @@ import {type Track,} from "@openreel/core";-type MixerTrack = Pick<Track, "id" | "name" | "type" | "muted" | "solo" | "audioRack" | "output" | "sends" | "surroundPan">;+type MixerTrack = Pick<Track, "id" | "name" | "type" | "muted" | "solo" | "soloSafe" | "audioRack" | "output" | "sends" | "surroundPan">;/** Index audio capability once per library change and retain stable control/meter identities. */export function createMixerChannelSelector() {@@ -33,12 +33,13 @@ export function createMixerChannelSelector() {track.type === "audio" ||track.clips.some((clip) => resolveAudio(clip).audio),)- .map(({ id, name, type, muted, solo, audioRack, output, sends, surroundPan }) => ({+ .map(({ id, name, type, muted, solo, soloSafe, audioRack, output, sends, surroundPan }) => ({id,name,type,muted,solo,+ soloSafe,audioRack,output,sends,@@ -54,6 +55,7 @@ export function createMixerChannelSelector() {track.type === previous.type &&track.muted === previous.muted &&track.solo === previous.solo &&+ track.soloSafe === previous.soloSafe &&track.audioRack === previous.audioRack &&track.output === previous.output &&track.sends === previous.sends &&diff --git a/apps/web/src/services/audio-output-service.test.ts b/apps/web/src/services/audio-output-service.test.tsnew file mode 100644index 00000000..a116be87--- /dev/null+++ b/apps/web/src/services/audio-output-service.test.ts@@ -0,0 +1,70 @@+import { afterEach, describe, expect, it, vi } from "vitest";+import { AudioOutputRouter, setAudioOutputRouterForTests, type AudioOutputEvent } from "@openreel/core";+import { useNotificationStore } from "../stores/notification-store";+import { useSettingsStore } from "../stores/settings-store";+import { describeAudioOutputEvent, startAudioOutputService } from "./audio-output-service";++describe("describeAudioOutputEvent", () => {+ it("warns on fallback, confirms on restore, stays quiet otherwise", () => {+ const unplugged: AudioOutputEvent = { type: "fallback", reason: "unplugged", requestedId: "h", requestedLabel: "USB Headset" };+ expect(describeAudioOutputEvent(unplugged)).toMatchObject({ level: "warning", title: "USB Headset disconnected" });+ expect(describeAudioOutputEvent({ ...unplugged, reason: "error" })).toMatchObject({ level: "warning", title: "Could not use USB Headset" });+ expect(describeAudioOutputEvent({ type: "restored", deviceId: "h", label: "USB Headset" })).toMatchObject({ level: "success", title: "Back on USB Headset" });+ expect(describeAudioOutputEvent({ type: "applied", deviceId: "h", label: "USB Headset" })).toBeNull();+ expect(describeAudioOutputEvent({ type: "devices", devices: [] })).toBeNull();+ });+});++describe("startAudioOutputService", () => {+ afterEach(() => {+ setAudioOutputRouterForTests(null);+ useSettingsStore.getState().setAudioOutputDevice("");+ useNotificationStore.getState().clearAll();+ });++ function boot() {+ let list = [+ { deviceId: "default", label: "Default - Speakers", kind: "audiooutput" },+ { deviceId: "headset-id", label: "USB Headset", kind: "audiooutput" },+ ] as MediaDeviceInfo[];+ const handlers = new Set<() => void>();+ const router = new AudioOutputRouter({+ mediaDevices: {+ enumerateDevices: async () => list,+ addEventListener: (_t: string, h: () => void) => handlers.add(h),+ removeEventListener: (_t: string, h: () => void) => handlers.delete(h),+ } as never,+ });+ setAudioOutputRouterForTests(router);+ const setSinkId = vi.fn(async () => undefined);+ router.attach({ destination: {}, setSinkId } as unknown as AudioContext, { connect: vi.fn(), disconnect: vi.fn() } as unknown as AudioNode);+ return { router, setSinkId, unplug: async () => { list = list.slice(0, 1); handlers.forEach((h) => h()); await router.reconcile(); } };+ }++ it("applies the remembered device, follows preference changes and toasts on unplug", async () => {+ useSettingsStore.getState().setAudioOutputDevice("headset-id", "USB Headset");+ const { router, setSinkId, unplug } = boot();+ const stop = startAudioOutputService();+ await vi.waitFor(() => expect(setSinkId).toHaveBeenCalledWith("headset-id"));+ expect(router.getActiveDeviceId()).toBe("headset-id");++ await unplug();+ const toasts = useNotificationStore.getState().notifications;+ expect(toasts).toHaveLength(1);+ expect(toasts[0]).toMatchObject({ type: "warning", title: "USB Headset disconnected" });+ expect(router.getActiveDeviceId()).toBe("");+ expect(useSettingsStore.getState().audioOutputDeviceId).toBe("headset-id"); // still remembered++ useSettingsStore.getState().setAudioOutputDevice("default");+ await vi.waitFor(() => expect(router.getPreferredDeviceId()).toBe(""));+ stop();+ });++ it("persists the choice under the settings store key", () => {+ useSettingsStore.getState().setAudioOutputDevice("headset-id", "USB Headset");+ expect(JSON.parse(localStorage.getItem("openreel-settings") ?? "{}").state).toMatchObject({+ audioOutputDeviceId: "headset-id",+ audioOutputDeviceLabel: "USB Headset",+ });+ });+});diff --git a/apps/web/src/services/audio-output-service.ts b/apps/web/src/services/audio-output-service.tsnew file mode 100644index 00000000..53a423e8--- /dev/null+++ b/apps/web/src/services/audio-output-service.ts@@ -0,0 +1,49 @@+import { getAudioOutputRouter, type AudioOutputEvent } from "@openreel/core";+import { toast } from "../stores/notification-store";+import { useSettingsStore } from "../stores/settings-store";++/** Toast copy for each routing event; null = stay silent. Exported for tests. */+export function describeAudioOutputEvent(event: AudioOutputEvent): { level: "warning" | "success"; title: string; message: string } | null {+ if (event.type === "fallback") {+ return {+ level: "warning",+ title: event.reason === "unplugged" ? `${event.requestedLabel} disconnected` : `Could not use ${event.requestedLabel}`,+ message: "Audio is playing on the system default output. It switches back when the device returns.",+ };+ }+ if (event.type === "restored") {+ return { level: "success", title: `Back on ${event.label}`, message: "Audio output returned to your chosen device." };+ }+ return null;+}++/**+ * Keeps the preview's monitor device in sync with the remembered preference and reports unplug /+ * replug. Start once while the editor is mounted; the returned function stops it.+ */+export function startAudioOutputService(): () => void {+ const router = getAudioOutputRouter();+ const apply = (id: string, label: string) => {+ router.rememberLabel(id, label);+ void router.setPreferredDevice(id);+ };+ const initial = useSettingsStore.getState();+ apply(initial.audioOutputDeviceId, initial.audioOutputDeviceLabel);+ const stopStore = useSettingsStore.subscribe(+ (state) => `${state.audioOutputDeviceId}\u0000${state.audioOutputDeviceLabel}`,+ () => {+ const state = useSettingsStore.getState();+ if (state.audioOutputDeviceId !== router.getPreferredDeviceId()) apply(state.audioOutputDeviceId, state.audioOutputDeviceLabel);+ },+ );+ const stopEvents = router.subscribe((event) => {+ const description = describeAudioOutputEvent(event);+ if (description) toast[description.level](description.title, description.message);+ });+ router.startWatching();+ return () => {+ stopStore();+ stopEvents();+ router.stopWatching();+ };+}diff --git a/apps/web/src/services/background-task-sources.ts b/apps/web/src/services/background-task-sources.tsnew file mode 100644index 00000000..73288de6--- /dev/null+++ b/apps/web/src/services/background-task-sources.ts@@ -0,0 +1,183 @@+import { backgroundTasks, type BackgroundTaskInput, type BackgroundTaskStatus } from "@openreel/core/tasks/task-registry";+import type { ExportJob } from "@openreel/core";+import { useExportQueueStore } from "../stores/export-queue-store";+import { previewProxyCache } from "../stores/preview-proxy-store";+import { useUIStore } from "../stores/ui-store";+import { cancelProxyJob, queueProxies } from "./proxy-ingest";+import { useDesktopIngestStore } from "./desktop-ingest";+import { useProjectStore } from "../stores/project-store";+import { getBeatSyncBridge } from "../bridges/beat-sync-bridge";++/**+ * Mirrors the existing job systems into the unified task registry. Nothing here runs work: the+ * export queue, proxy cache and direct export keep their own state, and every control forwards+ * to the owning system. Imports, scene detection and transcription report through+ * `backgroundTasks.track` / `upsert` at their call sites.+ */++const EXPORT_STATUS: Record<ExportJob["status"], BackgroundTaskStatus> = {+ queued: "queued",+ running: "running",+ completed: "completed",+ failed: "failed",+ cancelled: "cancelled",+ interrupted: "failed",+};++function syncExportQueue(): void {+ const { queue, cancel, retry, start } = useExportQueueStore.getState();+ backgroundTasks.syncSource(+ "export-queue",+ queue.jobs.map((job) => ({+ task: {+ id: `export-queue:${job.id}`,+ kind: "export",+ source: "export-queue",+ title: job.kind === "stems" ? `Stems · ${job.sequenceName}` : `Export · ${job.outputName}`,+ detail: job.status === "queued" && queue.paused ? "Export queue is paused \u00b7 Resume starts the whole queue" : job.status === "running" ? job.phase || job.presetLabel : job.status === "interrupted" ? "Interrupted by a restart" : job.presetLabel,+ // Queued jobs wait on the queue's own Start switch. Pausing is a queue-wide action, so no per-row Pause is offered.+ status: job.status === "queued" && queue.paused ? "paused" : EXPORT_STATUS[job.status],+ progress: job.status === "queued" ? 0 : job.progress,+ etaMs: job.status === "running" ? job.etaMs : undefined,+ error: job.error,+ createdAt: job.createdAt,+ startedAt: job.startedAt,+ finishedAt: job.finishedAt,+ } satisfies BackgroundTaskInput,+ controls: { cancel: () => cancel(job.id), retry: () => retry(job.id), resume: start },+ })),+ );+}++function syncDirectExport(): void {+ const { isExporting, progress, phase } = useUIStore.getState().exportState;+ backgroundTasks.syncSource(+ "export",+ isExporting+ ? [{ task: { id: "export:direct", kind: "export", source: "export", title: "Export", detail: phase || undefined, status: "running", progress } }]+ : [],+ );+}++type ProxyItem = { task: BackgroundTaskInput; controls: { cancel: () => void; retry: () => void } };++/** Last active snapshot of each proxy job, so a job that leaves the cache can be shown as finished or cancelled. */+const proxyLive = new Map<string, ProxyItem>();+/** Finished proxy jobs (completed / cancelled this session), listed until cleared. */+const proxyHistory = new Map<string, ProxyItem>();+const proxyCancelled = new Set<string>();++function finishedProxy(item: ProxyItem, status: "completed" | "cancelled"): ProxyItem {+ return { ...item, task: { ...item.task, status, progress: status === "completed" ? 1 : item.task.progress, error: undefined, etaMs: undefined, finishedAt: Date.now() } };+}++function syncProxies(): void {+ const { entries } = previewProxyCache.store.getState();+ const mediaItems = useProjectStore.getState().project.mediaLibrary.items;+ const names = new Map(mediaItems.map((m) => [m.id, m.name]));+ const active = new Map<string, ProxyItem>();+ for (const [id, entry] of Object.entries(entries)) {+ if (entry.status === "ready") continue;+ const key = `proxy:${id}`;+ active.set(key, {+ task: {+ id: key,+ kind: "proxy",+ source: "proxy",+ title: `Proxy · ${entry.source.name}`,+ detail: `${entry.preset} quality`,+ status: entry.status === "error" ? "failed" : entry.status === "encoding" ? "running" : "queued",+ progress: entry.status === "queued" ? 0 : entry.progress,+ error: entry.error,+ createdAt: entry.createdAt,+ },+ controls: {+ cancel: () => { proxyCancelled.add(key); cancelProxyJob(id); },+ retry: () => void queueProxies([id], entry.preset, true),+ },+ });+ }+ // Desktop native proxy jobs (ffmpeg sidecar) live in the ingest store.+ for (const [mediaId, job] of Object.entries(useDesktopIngestStore.getState().jobs)) {+ if (job.status === "done") continue;+ const key = `proxy:native:${mediaId}`;+ active.set(key, {+ task: {+ id: key,+ kind: "proxy",+ source: "proxy",+ title: `Proxy · ${names.get(mediaId) ?? job.fileName}`,+ detail: `${job.profile.codec === "prores-proxy" ? "ProRes Proxy" : "H.264"} · ${job.profile.size}`,+ status: job.status === "failed" ? "failed" : job.status === "running" ? "running" : "queued",+ progress: job.status === "queued" ? 0 : job.progress,+ error: job.error,+ },+ controls: {+ cancel: () => { proxyCancelled.add(key); cancelProxyJob(mediaId); },+ retry: () => void queueProxies([mediaId], undefined, true),+ },+ });+ }+ // A job that left the cache either finished (a proxy is linked / ready), was cancelled here, or was removed with its media.+ for (const [key, last] of proxyLive) {+ if (active.has(key)) continue;+ proxyLive.delete(key);+ if (proxyCancelled.delete(key)) {+ proxyHistory.set(key, finishedProxy(last, "cancelled"));+ continue;+ }+ const mediaId = key.startsWith("proxy:native:") ? key.slice("proxy:native:".length) : key.slice("proxy:".length);+ const ready = entries[mediaId]?.status === "ready" || !!mediaItems.find((m) => m.id === mediaId)?.proxy;+ if (ready && last.task.status !== "failed") proxyHistory.set(key, finishedProxy(last, "completed"));+ }+ for (const [key, item] of active) {+ proxyLive.set(key, item);+ proxyHistory.delete(key);+ }+ backgroundTasks.syncSource("proxy", [...active.values(), ...proxyHistory.values()]);+}++function syncCopies(): void {+ const names = new Map(useProjectStore.getState().project.mediaLibrary.items.map((m) => [m.id, m.name]));+ backgroundTasks.syncSource(+ "ingest-copy",+ Object.entries(useDesktopIngestStore.getState().copying).map(([mediaId, progress]) => ({+ task: { id: `ingest:copy:${mediaId}`, kind: "import" as const, source: "ingest-copy", title: `Copy to project \u00b7 ${names.get(mediaId) ?? mediaId}`, detail: "Copying and verifying checksum", status: "running" as const, progress },+ })),+ );+}++function syncBeats(): void {+ const state = getBeatSyncBridge().getState();+ backgroundTasks.syncSource(+ "beat-detection",+ state.isAnalyzing+ ? [{ task: { id: "analysis:beats", kind: "analysis", source: "beat-detection", title: "Beat detection", status: "running", progress: state.progress / 100 } }]+ : [],+ );+}++let started: (() => void) | null = null;++/** Idempotent; returns a disposer (HMR / tests). */+export function startBackgroundTaskSources(): () => void {+ if (started) return started;+ syncExportQueue();+ syncDirectExport();+ syncProxies();+ syncBeats();+ syncCopies();+ const offs = [+ useExportQueueStore.subscribe((s, p) => { if (s.queue !== p.queue) syncExportQueue(); }),+ useUIStore.subscribe((s, p) => { if (s.exportState !== p.exportState) syncDirectExport(); }),+ previewProxyCache.store.subscribe(syncProxies),+ useDesktopIngestStore.subscribe((s, p) => { if (s.jobs !== p.jobs) syncProxies(); if (s.copying !== p.copying) syncCopies(); }),+ getBeatSyncBridge().subscribe(syncBeats),+ ];+ const dispose = () => {+ offs.forEach((off) => off());+ started = null;+ };+ started = dispose;+ return dispose;+}diff --git a/apps/web/src/services/caption-translator.test.ts b/apps/web/src/services/caption-translator.test.tsnew file mode 100644index 00000000..c0a60c0b--- /dev/null+++ b/apps/web/src/services/caption-translator.test.ts@@ -0,0 +1,61 @@+import { describe, expect, it, vi } from "vitest";+import {+ createAiTranslator,+ createBrowserTranslator,+ detectTranslator,+ NO_TRANSLATOR_REASON,+ type BrowserTranslatorApi,+} from "./caption-translator";++const noKey = { provider: "openai", baseUrl: "https://api.openai.com/v1", model: "gpt-4o", apiKey: "" };+const withKey = { ...noKey, apiKey: "sk-test" };++const api = (state: string): BrowserTranslatorApi => ({+ availability: vi.fn(async () => state),+ create: vi.fn(async () => ({ translate: async (t: string) => `es:${t}` })),+});++describe("detectTranslator", () => {+ it("prefers the connected AI model", async () => {+ expect(await detectTranslator({ targetLanguage: "es" }, { connection: withKey, api: api("available") })).toMatchObject({ engine: "ai", state: "ready" });+ });+ it("falls back to the on-device translator", async () => {+ expect(await detectTranslator({ sourceLanguage: "en", targetLanguage: "es" }, { connection: noKey, api: api("available") })).toMatchObject({ engine: "browser", state: "ready" });+ expect(await detectTranslator({ sourceLanguage: "en", targetLanguage: "es" }, { connection: noKey, api: api("downloadable") })).toMatchObject({ engine: "browser", state: "downloadable" });+ });+ it("reports unavailable honestly", async () => {+ expect(await detectTranslator({ targetLanguage: "es" }, { connection: noKey, api: undefined })).toEqual({ engine: null, state: "unavailable", reason: NO_TRANSLATOR_REASON });+ const unsupported = await detectTranslator({ sourceLanguage: "en", targetLanguage: "xx" }, { connection: noKey, api: api("unavailable") });+ expect(unsupported.state).toBe("unavailable");+ const needsSource = await detectTranslator({ targetLanguage: "es" }, { connection: noKey, api: api("available") });+ expect(needsSource.state).toBe("unavailable");+ });+});++describe("translators", () => {+ it("AI translator sends the cues and parses the JSON reply", async () => {+ const complete = vi.fn(async () => ({ text: '["Hola","Mundo"]', toolUses: [], stopReason: "end_turn" as const }));+ const out = await createAiTranslator({ complete } as never).translate(["Hello", "World"], { sourceLanguage: "en", targetLanguage: "es" });+ expect(out).toEqual(["Hola", "Mundo"]);+ const input = (complete.mock.calls[0] as unknown as [{ messages: Array<{ content: string }>; tools: unknown[] }])[0];+ expect(input.messages[0].content).toContain('["Hello","World"]');+ expect(input.tools).toEqual([]);+ });+ it("AI translator rejects a reply with the wrong count", async () => {+ const complete = vi.fn(async () => ({ text: '["Hola"]', toolUses: [], stopReason: "end_turn" as const }));+ await expect(createAiTranslator({ complete } as never).translate(["a", "b"], { targetLanguage: "es" })).rejects.toThrow(/1 lines for 2/);+ });+ it("AI translator honours an aborted signal", async () => {+ const c = new AbortController();+ c.abort();+ const complete = vi.fn();+ await expect(createAiTranslator({ complete } as never).translate(["a"], { targetLanguage: "es", signal: c.signal })).rejects.toBeTruthy();+ expect(complete).not.toHaveBeenCalled();+ });+ it("browser translator translates each cue with the mocked API", async () => {+ const mock = api("available");+ const out = await createBrowserTranslator(mock).translate(["a", "b"], { sourceLanguage: "en", targetLanguage: "es" });+ expect(out).toEqual(["es:a", "es:b"]);+ expect(mock.create).toHaveBeenCalledWith(expect.objectContaining({ sourceLanguage: "en", targetLanguage: "es" }));+ });+});diff --git a/apps/web/src/services/caption-translator.ts b/apps/web/src/services/caption-translator.tsnew file mode 100644index 00000000..810c5637--- /dev/null+++ b/apps/web/src/services/caption-translator.ts@@ -0,0 +1,143 @@+import {+ buildTranslationPrompt,+ parseTranslationReply,+ type CaptionTranslator,+} from "@openreel/core";+import { useAIConnectionStore } from "../stores/ai-connection-store";+import { isConnectionReady } from "../components/editor/chat/ai-connection-labels";+import { makeDirectBYOKClient } from "./agent/direct-llm-transport";++/**+ * Translator back ends for caption translation. The AI provider the user connected+ * for the AI editor is preferred; without one the browser's on-device Translator API+ * is used when it exists. When neither is available the caller shows a clear+ * unavailable state: there is no fallback that fakes output.+ */++export type TranslatorEngineId = "ai" | "browser";++export type TranslatorAvailability =+ | { engine: TranslatorEngineId; state: "ready"; label: string }+ | { engine: "browser"; state: "downloadable"; label: string }+ | { engine: null; state: "unavailable"; reason: string };++/** The subset of the browser Translator API this feature uses (Chrome 138+). */+export interface BrowserTranslatorApi {+ availability(options: { sourceLanguage: string; targetLanguage: string }): Promise<string>;+ create(options: {+ sourceLanguage: string;+ targetLanguage: string;+ signal?: AbortSignal;+ monitor?: (m: EventTarget) => void;+ }): Promise<{ translate(text: string, options?: { signal?: AbortSignal }): Promise<string>; destroy?(): void }>;+}++export const browserTranslatorApi = (): BrowserTranslatorApi | undefined => {+ try {+ const api = (globalThis as { Translator?: BrowserTranslatorApi }).Translator;+ return api && typeof api.create === "function" && typeof api.availability === "function" ? api : undefined;+ } catch {+ return undefined;+ }+};++export function languageName(code: string): string {+ try {+ return new Intl.DisplayNames(["en"], { type: "language" }).of(code) ?? code;+ } catch {+ return code;+ }+}++export const NO_TRANSLATOR_REASON =+ "No translator is available. Connect an AI model in Settings, or use a browser with on-device translation (Chrome 138 or later).";++export async function detectTranslator(+ languages: { sourceLanguage?: string; targetLanguage: string },+ deps: { api?: BrowserTranslatorApi; connection?: Parameters<typeof isConnectionReady>[0] } = {},+): Promise<TranslatorAvailability> {+ const connection = deps.connection ?? useAIConnectionStore.getState();+ if (isConnectionReady(connection)) {+ return { engine: "ai", state: "ready", label: `${connection.model}` };+ }+ const api = deps.api ?? browserTranslatorApi();+ if (!api) return { engine: null, state: "unavailable", reason: NO_TRANSLATOR_REASON };+ if (!languages.sourceLanguage) {+ return { engine: null, state: "unavailable", reason: "Enter the language of the source captions to use on-device translation." };+ }+ try {+ const state = await api.availability({ sourceLanguage: languages.sourceLanguage, targetLanguage: languages.targetLanguage });+ if (state === "available") return { engine: "browser", state: "ready", label: "On-device" };+ if (state === "downloadable" || state === "downloading") {+ return { engine: "browser", state: "downloadable", label: "On-device (language pack downloads on first use)" };+ }+ } catch {+ // fall through to unavailable+ }+ return {+ engine: null,+ state: "unavailable",+ reason: `On-device translation does not support ${languageName(languages.sourceLanguage)} to ${languageName(languages.targetLanguage)} in this browser. Connect an AI model in Settings to translate.`,+ };+}++export function createAiTranslator(+ client: { complete: ReturnType<typeof makeDirectBYOKClient>["complete"] },+): CaptionTranslator {+ return {+ async translate(texts, { sourceLanguage, targetLanguage, signal }) {+ signal?.throwIfAborted();+ const { system, user } = buildTranslationPrompt(texts, {+ sourceLanguage: sourceLanguage ? languageName(sourceLanguage) : undefined,+ targetLanguage,+ targetName: languageName(targetLanguage),+ });+ const reply = await client.complete({ system, messages: [{ role: "user", content: user }], tools: [] });+ signal?.throwIfAborted();+ return parseTranslationReply(reply.text, texts.length);+ },+ };+}++export function createBrowserTranslator(+ api: BrowserTranslatorApi,+ onDownloadProgress?: (fraction: number) => void,+): CaptionTranslator {+ return {+ async translate(texts, { sourceLanguage, targetLanguage, signal }) {+ if (!sourceLanguage) throw new Error("Enter the language of the source captions.");+ const translator = await api.create({+ sourceLanguage,+ targetLanguage,+ signal,+ monitor: (m) =>+ m.addEventListener("downloadprogress", (e) => onDownloadProgress?.((e as Event & { loaded?: number }).loaded ?? 0)),+ });+ try {+ const out: string[] = [];+ for (const text of texts) {+ signal?.throwIfAborted();+ out.push(await translator.translate(text, { signal }));+ }+ return out;+ } finally {+ translator.destroy?.();+ }+ },+ };+}++export function makeTranslator(+ engine: TranslatorEngineId,+ options: { signal?: AbortSignal; sourceLanguage?: string; onDownloadProgress?: (fraction: number) => void } = {},+): CaptionTranslator {+ if (engine === "ai") {+ const c = useAIConnectionStore.getState();+ return createAiTranslator(+ makeDirectBYOKClient({ provider: c.provider, baseUrl: c.baseUrl, model: c.model, apiKey: c.apiKey, signal: options.signal }),+ );+ }+ const api = browserTranslatorApi();+ if (!api) throw new Error(NO_TRANSLATOR_REASON);+ return createBrowserTranslator(api, options.onDownloadProgress);+}diff --git a/apps/web/src/services/clip-marker-commands.ts b/apps/web/src/services/clip-marker-commands.tsnew file mode 100644index 00000000..e870ac59--- /dev/null+++ b/apps/web/src/services/clip-marker-commands.ts@@ -0,0 +1,121 @@+import { sourceTimeForTimelineMarker, sourceToTimelineTime, type Clip, type Marker } from "@openreel/core";+import { useProjectStore } from "../stores/project-store";+import { useSourceMonitorStore } from "../stores/source-monitor-store";+import { useTimelineStore } from "../stores/timeline-store";+import { useUIStore } from "../stores/ui-store";+import { useEditorWorkspaceStore } from "../stores/editor-workspace-store";+import { toast } from "../stores/notification-store";+import { DEFAULT_MARKER_COLOR } from "./marker-commands";++/**+ * Clip markers (one timeline instance) and master-clip markers (the Source monitor's clip, shown+ * on every instance). Marker times are source-media seconds; see core `editing/clip-markers`.+ */++export type ClipMarkerTarget = { clipId: string } | { mediaId: string };++const newId = (): string => `marker-${crypto.randomUUID()}`;++const findClip = (clipId: string): Clip | undefined => {+ for (const track of useProjectStore.getState().project.timeline.tracks) {+ const clip = track.clips.find((c) => c.id === clipId);+ if (clip) return clip;+ }+ return undefined;+};++const currentMarkers = (target: ClipMarkerTarget): readonly Marker[] => {+ const project = useProjectStore.getState().project;+ if ("clipId" in target) return findClip(target.clipId)?.markers ?? [];+ return project.mediaLibrary.items.find((i) => i.id === target.mediaId)?.markers ?? [];+};++/** Clip under the playhead on the selected clips, else the topmost visual clip under it. */+export function clipForMarker(): Clip | null {+ const time = useTimelineStore.getState().playheadPosition;+ const selected = new Set(useUIStore.getState().getSelectedClipIds());+ const tracks = useProjectStore.getState().project.timeline.tracks;+ const covers = (c: Clip) => time >= c.startTime - 1e-6 && time <= c.startTime + c.duration + 1e-6;+ for (const track of tracks) {+ for (const clip of track.clips) if (selected.has(clip.id) && covers(clip)) return clip;+ }+ for (const track of tracks) {+ if (track.type !== "video" && track.type !== "audio" && track.type !== "image") continue;+ const clip = track.clips.find(covers);+ if (clip) return clip;+ }+ return null;+}++export async function addClipMarker(+ target: ClipMarkerTarget,+ sourceTime: number,+ extra: Partial<Marker> = {},+): Promise<string | null> {+ const list = currentMarkers(target);+ const marker: Marker = {+ id: newId(),+ time: Math.max(0, sourceTime),+ label: `Marker ${list.length + 1}`,+ color: DEFAULT_MARKER_COLOR,+ ...extra,+ };+ const result = await useProjectStore.getState().setClipMarkers(target, [...list, marker]);+ return result.success ? marker.id : null;+}++export async function updateClipMarker(+ target: ClipMarkerTarget,+ markerId: string,+ updates: Partial<Marker>,+): Promise<void> {+ const next = currentMarkers(target).map((m) => {+ if (m.id !== markerId) return m;+ const merged: Record<string, unknown> = { ...m };+ for (const [key, value] of Object.entries(updates)) {+ if (value === undefined) delete merged[key];+ else merged[key] = value;+ }+ return merged as unknown as Marker;+ });+ await useProjectStore.getState().setClipMarkers(target, next);+}++export async function removeClipMarker(target: ClipMarkerTarget, markerId: string): Promise<void> {+ await useProjectStore.getState().setClipMarkers(+ target,+ currentMarkers(target).filter((m) => m.id !== markerId),+ );+}++/** Alt+Shift+M on the timeline: a clip marker at the playhead on the selected (or topmost) clip. */+export async function addClipMarkerAtPlayhead(): Promise<void> {+ const clip = clipForMarker();+ if (!clip) {+ toast.info("No clip at the playhead", "Select a clip or park the playhead over one to add a clip marker.");+ return;+ }+ const time = useTimelineStore.getState().playheadPosition;+ const source = sourceTimeForTimelineMarker(clip, time);+ if (source === null) return;+ const id = await addClipMarker({ clipId: clip.id }, source);+ if (id) {+ useEditorWorkspaceStore.getState().setSection("markers");+ useEditorWorkspaceStore.getState().setMarkerScope("clips");+ }+}++/** M / Alt+Shift+M in the Source monitor: a master-clip marker at the source playhead. */+export async function addSourceMarker(): Promise<void> {+ const { mediaId, position } = useSourceMonitorStore.getState();+ if (!mediaId) return;+ await addClipMarker({ mediaId }, position);+}++/** Park the playhead on a marker of a timeline instance (a range marker's start, clamped to the clip). */+export function seekToClipMarker(clip: Clip, marker: Pick<Marker, "time">): void {+ const timeline = useTimelineStore.getState();+ timeline.pause();+ timeline.seekTo(Math.max(0, sourceToTimelineTime(clip, Math.min(clip.outPoint, Math.max(clip.inPoint, marker.time)))));+ useTimelineStore.getState().scrollToPlayhead();+}diff --git a/apps/web/src/services/clip-speed-multi.ts b/apps/web/src/services/clip-speed-multi.tsnew file mode 100644index 00000000..8e04cfc2--- /dev/null+++ b/apps/web/src/services/clip-speed-multi.ts@@ -0,0 +1,48 @@+import { planClipSpeedEdit, type Clip, type ClipSpeedEdit } from "@openreel/core";+import { v4 as uuidv4 } from "uuid";+import { useProjectStore } from "../stores/project-store";+import { useUIStore } from "../stores/ui-store";+import { useTimelineStore } from "../stores/timeline-store";+import { getLinkedTimelineSelection } from "../utils/linked-timeline-selection";+import { commit, type CommandOutcome } from "./premiere-edit-commands";+import { useClipSpeedDialogStore } from "../stores/clip-speed-dialog-store";++/**+ * Selected media clips plus their linked partners. Linked audio always follows+ * a speed change, whatever the Linked Selection toggle says: retiming only the+ * picture would silently put the sound out of sync.+ */+export function selectedSpeedClips(): Clip[] {+ const state = useProjectStore.getState();+ if (!state.hasOpenProject) return [];+ const project = state.getFullProject();+ const ids = getLinkedTimelineSelection(+ project,+ useUIStore.getState().getSelectedClipIds(),+ true,+ );+ const wanted = new Set(ids);+ return project.timeline.tracks.flatMap((track) => track.clips.filter((clip) => wanted.has(clip.id)));+}++/**+ * Apply Speed/Duration to every selected clip as one undo step.+ * `ripple` is "Ripple Edit, Shifting Trailing Clips".+ */+export function applyClipSpeedEdit(edit: ClipSpeedEdit, ripple: boolean): CommandOutcome {+ if (useUIStore.getState().exportState.isExporting || useTimelineStore.getState().playbackLockedReason)+ return { success: false, message: "Wait for the export or playback lock to finish." };+ const clips = selectedSpeedClips();+ if (!clips.length) return { success: false, message: "Select one or more clips first." };+ const outcome = commit(+ (project) => planClipSpeedEdit(project, clips.map((clip) => clip.id), edit, { ripple }, uuidv4()),+ "Nothing changed.",+ );+ return { success: outcome.success, message: outcome.message };+}++export function openClipSpeedDialog(): CommandOutcome {+ if (!selectedSpeedClips().length) return { success: false, message: "Select one or more clips first." };+ useClipSpeedDialogStore.getState().setOpen(true);+ return { success: true };+}diff --git a/apps/web/src/services/comparison-service.ts b/apps/web/src/services/comparison-service.tsindex 3f82ca1c..5a496b19 100644--- a/apps/web/src/services/comparison-service.ts+++ b/apps/web/src/services/comparison-service.ts@@ -16,6 +16,7 @@ import {type StillEntry,} from "../stores/color-monitor-store";import { useTimelineStore } from "../stores/timeline-store";+import { getEffectsBridge } from "../bridges/effects-bridge";const stillBitmaps = new Map<string, ImageBitmap>();let liveReference: ImageBitmap | null = null;@@ -58,25 +59,30 @@ function isPlaying(): boolean {/** Render `time`, snapshot the canvas, then put the playhead frame back. */async function captureAt(time: number,- options: { bypass: boolean },+ options: { bypass: boolean; whiteBalanceInputClip?: string },): Promise<ImageBitmap | null> {const control = getProgramFrameControl();const playhead = useTimelineStore.getState().playheadPosition;const moved = Math.abs(time - playhead) > 1e-6;const store = useColorMonitorStore.getState();- if (!control && (moved || options.bypass)) return null;- if ((moved || options.bypass) && isPlaying()) return null;+ const rerender = moved || options.bypass || options.whiteBalanceInputClip !== undefined;+ if (!control && rerender) return null;+ if (rerender && isPlaying()) return null;store.setCaptureBusy(true);try {if (options.bypass) setColorBypass(true);- if (control && (moved || options.bypass)) {+ if (options.whiteBalanceInputClip !== undefined) {+ getEffectsBridge().setWhiteBalanceInputView(options.whiteBalanceInputClip);+ }+ if (control && rerender) {await control.renderAt(time, { scrubbing: moved });}return await snapshotProgramCanvas();} finally {if (options.bypass) setColorBypass(false);- if (control && (moved || options.bypass)) {+ if (options.whiteBalanceInputClip !== undefined) getEffectsBridge().setWhiteBalanceInputView(null);+ if (control && rerender) {// The user may have scrubbed while the reference rendered: put back the// CURRENT playhead frame, not the one captured when the job started.await control.renderAt(useTimelineStore.getState().playheadPosition, { scrubbing: false });@@ -100,6 +106,18 @@ export function captureProgramFrame();}+/**+ * The Program frame at the playhead with `clipId` rendered as its white balance+ * stage sees it (only the input LUT on a version 2 clip; the full grade minus+ * white balance on version 1). Composition, transforms and the other layers are+ * rendered as usual. Preview-only; resolves null while playing.+ */+export function captureWhiteBalanceInputFrame(clipId: string): Promise<ImageBitmap | null> {+ return enqueue(() =>+ captureAt(useTimelineStore.getState().playheadPosition, { bypass: false, whiteBalanceInputClip: clipId }),+ );+}+function makeThumb(bitmap: ImageBitmap): string {try {const canvas = document.createElement("canvas");diff --git a/apps/web/src/services/desktop-ingest.ts b/apps/web/src/services/desktop-ingest.tsindex 23fe2072..ded4d335 100644--- a/apps/web/src/services/desktop-ingest.ts+++ b/apps/web/src/services/desktop-ingest.ts@@ -3,6 +3,7 @@ import { v4 as uuidv4 } from "uuid";import {createProxyRef,getMediaEngine,+ isIntermediateProxyCodec,matchRelinkCandidates,relinkTargetFor,resolveDesktopProxyProfile,@@ -232,11 +233,11 @@ export function queueDesktopProxies(mediaIds: readonly string[], force = false):async function submitBatch(batch: Array<{ mediaId: string; name: string; srcPath: string; profile: DesktopProxyProfile }>, force: boolean): Promise<void> {const api = bridge();if (!api) return;- const previewTwin = batch.some((entry) => entry.profile.codec === "prores-proxy") && !(await rendererDecodesProres());+ const previewTwin = batch.some((entry) => isIntermediateProxyCodec(entry.profile.codec)) && !(await rendererDecodesProres());try {const jobs = await api.enqueueProxies({...ingestProject(),- items: batch.map((entry) => ({ ...entry, previewTwin: entry.profile.codec === "prores-proxy" && previewTwin })),+ items: batch.map((entry) => ({ ...entry, previewTwin: isIntermediateProxyCodec(entry.profile.codec) && previewTwin })),force,});patchState((s) => ({ jobs: { ...s.jobs, ...Object.fromEntries(jobs.map((job) => [job.mediaId, job])) } }));diff --git a/apps/web/src/services/diarization.test.ts b/apps/web/src/services/diarization.test.tsnew file mode 100644index 00000000..b4a297d2--- /dev/null+++ b/apps/web/src/services/diarization.test.ts@@ -0,0 +1,27 @@+import { describe, expect, it, vi } from "vitest";++const state = {+ project: {+ speakers: [],+ mediaLibrary: { items: [{ id: "m1", type: "video", metadata: { hasAudio: false, audioTrackCount: 0 } }] },+ timeline: {+ tracks: [{ clips: [{ id: "c1", mediaId: "m1", startTime: 0, duration: 10, inPoint: 0 }] }],+ subtitles: [{ id: "s1", text: "hello there", startTime: 1, endTime: 3, words: [] }],+ },+ },+ executeAction: vi.fn(),+};++vi.mock("../stores/project-store", () => ({ useProjectStore: { getState: () => state } }));+vi.mock("../utils/load-audio-buffer", () => ({ loadAudioBuffer: vi.fn() }));++import { diarizeCaptions } from "./diarization";++describe("diarizeCaptions", () => {+ it("says the clip has no audio instead of claiming decoding failed", async () => {+ const outcome = await diarizeCaptions();+ expect(outcome.success).toBe(false);+ expect(outcome.message).toMatch(/no audio track/i);+ expect(state.executeAction).not.toHaveBeenCalled();+ });+});diff --git a/apps/web/src/services/diarization.ts b/apps/web/src/services/diarization.tsnew file mode 100644index 00000000..3406b547--- /dev/null+++ b/apps/web/src/services/diarization.ts@@ -0,0 +1,169 @@+import { v4 as uuidv4 } from "uuid";+import {+ applySpeakerStyles,+ clusterEmbeddings,+ detectionCues,+ mirrorSpeakersToTranslations,+ ensureSpeakerProfiles,+ labelCuesBySpeaker,+ type Clip,+ type MediaItem,+ type Subtitle,+} from "@openreel/core";+import { useProjectStore } from "../stores/project-store";+import { loadAudioBuffer } from "../utils/load-audio-buffer";+import { audioBufferToWhisperSamples } from "../utils/whisper-audio";+import type { DiarizationWorkerResponse } from "../workers/diarization-worker";+import type { CommandOutcome } from "./premiere-edit-commands";++/**+ * On-device speaker diarization for the caption cues. Each cue's audio is+ * decoded from the source clip under it, voice-printed in a worker, clustered,+ * and the result (Speaker 1..N labels + profiles, with their caption looks+ * baked on) is committed as ONE undo step. Nothing leaves the machine.+ */++const MAX_CUE_SECONDS = 10;++export interface DiarizeOptions {+ /** Exact number of speakers; omit to detect automatically. */+ speakerCount?: number;+ signal?: AbortSignal;+ onProgress?: (progress: number, message: string) => void;+}++export type DiarizeOutcome = CommandOutcome & { speakers?: number; skipped?: number };++function clipUnder(project: ReturnType<typeof useProjectStore.getState>["project"], time: number) {+ const media = new Map(project.mediaLibrary.items.map((item) => [item.id, item]));+ let found: { clip: Clip; media: MediaItem } | undefined;+ for (const track of project.timeline.tracks) {+ for (const clip of track.clips) {+ const item = media.get(clip.mediaId);+ if (!item || (item.type !== "audio" && item.type !== "video")) continue;+ if (time < clip.startTime || time >= clip.startTime + clip.duration) continue;+ if (!found || item.type === "audio") found = { clip, media: item };+ }+ }+ return found;+}++function runWorker(+ segments: Array<{ id: string; samples: Float32Array }>,+ options: DiarizeOptions,+): Promise<Map<string, Float32Array | null>> {+ const worker = new Worker(new URL("../workers/diarization-worker.ts", import.meta.url), { type: "module" });+ const requestId = uuidv4();+ return new Promise((resolve, reject) => {+ const done = () => {+ options.signal?.removeEventListener("abort", onAbort);+ worker.terminate();+ };+ const onAbort = () => {+ done();+ reject(new DOMException("Speaker detection cancelled.", "AbortError"));+ };+ options.signal?.addEventListener("abort", onAbort);+ worker.onmessage = (event: MessageEvent<DiarizationWorkerResponse>) => {+ const message = event.data;+ if (message.requestId !== requestId) return;+ if (message.type === "progress") options.onProgress?.(0.4 + message.progress * 0.55, "Analysing voices…");+ else {+ done();+ resolve(new Map(message.embeddings.map((e) => [e.id, e.embedding])));+ }+ };+ worker.onerror = () => {+ done();+ reject(new Error("The speaker analysis worker stopped. Try again."));+ };+ worker.postMessage({ requestId, segments }, segments.map((s) => s.samples.buffer));+ });+}++export async function diarizeCaptions(options: DiarizeOptions = {}): Promise<DiarizeOutcome> {+ const store = useProjectStore.getState();+ const all: Subtitle[] = store.project.timeline.subtitles;+ // Hidden translated tracks repeat the same time ranges; analyse the visible track only.+ const subtitles = detectionCues(all);+ if (!subtitles.length) return { success: false, message: "There are no captions to label yet." };++ const plan = subtitles.map((cue) => ({ cue, source: clipUnder(store.project, (cue.startTime + cue.endTime) / 2) }));+ const usable = plan.filter((p) => p.source);+ if (!usable.length) return { success: false, message: "No captions overlap a clip with audio." };+ // A source with no audio stream at all gets its own message (not "could not be decoded").+ const silent = (item: MediaItem) =>+ item.metadata?.hasAudio === false || (item.type === "video" && item.metadata?.hasAudio === undefined && item.metadata?.audioTrackCount === 0);+ const withAudio = usable.filter((p) => !silent((p.source as NonNullable<typeof p.source>).media));+ if (!withAudio.length)+ return { success: false, message: "The clips under these captions have no audio track, so there are no voices to tell apart." };++ const audioContext = new AudioContext();+ try {+ const segments: Array<{ id: string; samples: Float32Array }> = [];+ let previous: { blob: Blob; track?: number; buffer: AudioBuffer } | undefined;+ // Cues in clip order so adjacent cues share one decode.+ const ordered = withAudio.sort((a, b) => a.cue.startTime - b.cue.startTime);+ for (let i = 0; i < ordered.length; i++) {+ if (options.signal?.aborted) throw new DOMException("Speaker detection cancelled.", "AbortError");+ const { cue, source } = ordered[i];+ const { clip, media } = source as NonNullable<typeof source>;+ const blob = media.blob ?? (media.fileHandle ? await media.fileHandle.getFile() : null);+ if (!blob) return { success: false, message: "Reconnect the source media before detecting speakers." };+ let buffer: AudioBuffer | null =+ previous && previous.blob === blob && previous.track === clip.audioTrackIndex ? previous.buffer : null;+ if (!buffer) {+ buffer = await loadAudioBuffer(audioContext, blob, { audioTrackIndex: clip.audioTrackIndex });+ if (buffer) previous = { blob, track: clip.audioTrackIndex, buffer };+ }+ options.onProgress?.((i / ordered.length) * 0.4, "Reading audio…");+ if (!buffer) continue;+ const speed = Math.max(clip.speed ?? 1, 0.01);+ const from = Math.max(0, (clip.inPoint ?? 0) + (Math.max(cue.startTime, clip.startTime) - clip.startTime) * speed);+ const to = Math.min(+ buffer.duration,+ from + Math.min(MAX_CUE_SECONDS, (Math.min(cue.endTime, clip.startTime + clip.duration) - Math.max(cue.startTime, clip.startTime)) * speed),+ );+ if (to > from) segments.push({ id: cue.id, samples: audioBufferToWhisperSamples(buffer, from, to) });+ }+ if (!segments.length) return { success: false, message: "No audio could be read from the clips under the captions." };++ options.onProgress?.(0.4, "Analysing voices…");+ const embeddings = await runWorker(segments, options);+ const voiced = subtitles.map((cue) => embeddings.get(cue.id) ?? null);+ const indexes = voiced.map((e, i) => (e ? i : -1)).filter((i) => i >= 0);+ if (indexes.length < 1) return { success: false, message: "No speech was clear enough to tell voices apart." };++ const clustered = clusterEmbeddings(indexes.map((i) => voiced[i] as Float32Array), { speakerCount: options.speakerCount });+ const clusters: Array<number | null> = subtitles.map(() => null);+ indexes.forEach((cueIndex, k) => (clusters[cueIndex] = clustered[k]));++ const current = useProjectStore.getState();+ if (current.project.timeline.subtitles !== all) return { success: false, message: "The captions changed while detecting speakers. Run it again." };+ // A re-run maps each voice back onto the speaker it overlaps most (renamed ones keep their name and look); the rest are replaced.+ const { labels, profiles } = labelCuesBySpeaker(subtitles, clusters, current.project.speakers ?? [], {+ previous: subtitles.map((cue) => cue.speaker),+ });+ const labelById = new Map(subtitles.map((cue, i) => [cue.id, labels[i]] as const));+ const detected = all.map((cue) => {+ const label = labelById.get(cue.id);+ return label ? { ...cue, speaker: label } : cue;+ });+ // Translated cues of the same time range share the speaker (and so the colour / label).+ const labelled = mirrorSpeakersToTranslations(detected, new Set(subtitles.map((cue) => cue.id)));+ const used = new Set(labelled.map((cue) => cue.speaker));+ const finalProfiles = ensureSpeakerProfiles(labelled, profiles).filter((p) => used.has(p.name));+ const result = await current.executeAction({+ type: "speaker/apply",+ id: uuidv4(),+ timestamp: Date.now(),+ params: { subtitles: applySpeakerStyles(labelled, finalProfiles), profiles: finalProfiles },+ });+ options.onProgress?.(1, "Done");+ return result.success+ ? { success: true, speakers: new Set(labels.filter(Boolean)).size, skipped: subtitles.length - indexes.length }+ : { success: false, message: result.error?.message ?? "Speaker labels could not be applied." };+ } finally {+ void audioContext.close().catch(() => undefined);+ }+}diff --git a/apps/web/src/services/engine-modules.ts b/apps/web/src/services/engine-modules.tsindex 2461c947..fd495e51 100644--- a/apps/web/src/services/engine-modules.ts+++ b/apps/web/src/services/engine-modules.ts@@ -41,6 +41,7 @@ export {getMotionPreset,registerProjectGeneratedShaders,VideoEffectsEngine,+ EchoCompositor,ColorGradingEngine,lutFromJson,isWebGPUSupported,@@ -54,8 +55,12 @@ export {normalizeProjectIrisAnimations,reflowMotionAutoLayoutGroups,withEffectDefaults,+ prepareUltraKey,+ ultraKeyBaseMatte,getDefaultEffectParams,isProEffectType,+ withBurnInText,+ BURN_IN_SAMPLE_SOURCE,PRO_EFFECT_DEFAULTS,resolveEditingTemplate,getBuiltInEditingTemplate,diff --git a/apps/web/src/services/export-queue/export-queue-runner.test.ts b/apps/web/src/services/export-queue/export-queue-runner.test.tsindex d0bdf166..4b9e7e44 100644--- a/apps/web/src/services/export-queue/export-queue-runner.test.ts+++ b/apps/web/src/services/export-queue/export-queue-runner.test.ts@@ -9,6 +9,7 @@ const hoisted = vi.hoisted(() => ({singletonUsed: vi.fn(),disposed: vi.fn(async () => undefined),isolatedCreated: vi.fn(),+ options: [] as unknown[],}));vi.mock("@openreel/core", async (importOriginal) => {@@ -28,8 +29,9 @@ vi.mock("@openreel/core", async (importOriginal) => {if (hoisted.initFail.current) throw new Error("init failed");},cancel: () => hoisted.calls.push("engine.cancel"),- async *exportVideo() {+ async *exportVideo(_project: unknown, _settings: unknown, _writable: unknown, options: unknown) {hoisted.calls.push("engine.exportVideo");+ hoisted.options.push(options);yield { phase: "rendering", progress: 0.5 };if (hoisted.fail.current) throw new Error("encoder crashed");return {@@ -96,6 +98,7 @@ const hooks = { onProgress: vi.fn(), isCancelled: () => false };beforeEach(() => {hoisted.calls.length = 0;+ hoisted.options.length = 0;calls.length = 0;hoisted.fail.current = false;hoisted.initFail.current = false;@@ -114,6 +117,13 @@ describe("runExportJob isolation from the live preview", () => {expect(result.smartRender).toEqual({ copiedPercent: 62, summary: "Smart render: 62% copied", copiedFrames: 62, totalFrames: 100, copiedRuns: 1, reasons: [] });});+ it("passes the software preference to the browser engine for this run only", async () => {+ await runExportJob(job, snapshot, hooks, "prefer-software");+ await runExportJob(job, snapshot, hooks);+ expect(hoisted.options[0]).toMatchObject({ encoderPreference: "prefer-software" });+ expect(hoisted.options[1]).not.toHaveProperty("encoderPreference");+ });+it("restores and unlocks when the export fails midway", async () => {hoisted.fail.current = true;await expect(runExportJob(job, snapshot, hooks)).rejects.toThrow("encoder crashed");diff --git a/apps/web/src/services/export-queue/export-queue-runner.ts b/apps/web/src/services/export-queue/export-queue-runner.tsindex b1fe161a..d4ad5855 100644--- a/apps/web/src/services/export-queue/export-queue-runner.ts+++ b/apps/web/src/services/export-queue/export-queue-runner.ts@@ -4,7 +4,9 @@ import {desktopExportRequiresNativeEncoder,planInvalidation,setEncoderBackendFactory,+ encoderChoiceForcesNative,WebCodecsBackend,+ webCodecsEncoderOptions,type ExportEngine,type ExportFrameSource,type ExportJob,@@ -75,12 +77,17 @@ export function createDiskWritable(path: string): Promise<FileSystemWritableFile});}-const webCodecsFactoryFor = (settings: VideoExportSettings, clamp: boolean) => {+/** Which encoder a job asks WebCodecs for. A re-run after a hardware session could not be opened asks for software. */+export type EncoderPreference = "prefer-hardware" | "prefer-software";++const webCodecsFactoryFor = (settings: VideoExportSettings, clamp: boolean, encoder: EncoderPreference = "prefer-hardware") => {const videoCodec = settings.codec === "h265" ? "hevc" : "avc";return (mediabunny: unknown) =>mediabunny? new WebCodecsBackend(mediabunny as ConstructorParameters<typeof WebCodecsBackend>[0], {- hardwareAcceleration: "prefer-hardware",+ ...webCodecsEncoderOptions(settings.encoderChoice),+ // The automatic re-run after a hardware session failed to open asks for software, unless the user chose Hardware.+ ...(encoder === "prefer-software" && settings.encoderChoice !== "hardware" ? { hardwareAcceleration: "prefer-software" as const } : {}),videoCodecs: [videoCodec],clampResolution: clamp,})@@ -104,14 +111,14 @@ export interface RunJobHooks {* Encode one queued job from its project snapshot. The editor's live project is* never read here, which is what makes a queued job immune to later edits.*/-export async function runExportJob(job: ExportJob, project: Project, hooks: RunJobHooks): Promise<RunJobResult> {+export async function runExportJob(job: ExportJob, project: Project, hooks: RunJobHooks, encoder: EncoderPreference = "prefer-hardware"): Promise<RunJobResult> {// A queued job renders with its own video/audio engines. The live preview's// engines are never put in export mode, never have their caches cleared, and// never see the job's frames.const isolated = createIsolatedExportEngine();activeJobEngine = isolated.engine;try {- return await runExportJobWith(isolated.engine, job, project, hooks);+ return await runExportJobWith(isolated.engine, job, project, hooks, encoder);} finally {// Owned here so an early failure (engine init, fonts, output sink) cannot leak the engines.if (activeJobEngine === isolated.engine) activeJobEngine = null;@@ -119,7 +126,7 @@ export async function runExportJob(job: ExportJob, project: Project, hooks: RunJ}}-async function runExportJobWith(engine: ExportEngine, job: ExportJob, project: Project, hooks: RunJobHooks): Promise<RunJobResult> {+async function runExportJobWith(engine: ExportEngine, job: ExportJob, project: Project, hooks: RunJobHooks, encoder: EncoderPreference): Promise<RunJobResult> {const settings: VideoExportSettings = { ...job.settings, ...(job.range ? { range: job.range } : {}) };const ext = extForFormat(settings.format, settings.codec);const desktop = isDesktop();@@ -153,13 +160,13 @@ async function runExportJobWith(engine: ExportEngine, job: ExportJob, project: Pif (desktop) {const fs = window.openreel!.fs;const path = await fs.tempFilePath(ext, true);- const native = desktopExportRequiresNativeEncoder(settings) || settings.encodeMode === "smallest" || settings.codec === "av1";+ const native = desktopExportRequiresNativeEncoder(settings) || settings.encodeMode === "smallest" || settings.codec === "av1" || encoderChoiceForcesNative(settings.encoderChoice, settings.codec);(window as { __openreelExportPath?: string }).__openreelExportPath = path;if (native) {setEncoderBackendFactory(() => new NativeFFmpegBackend(() => path));writable = NOOP_WRITABLE;} else {- setEncoderBackendFactory(webCodecsFactoryFor(settings, false));+ setEncoderBackendFactory(webCodecsFactoryFor(settings, false, encoder));writable = await createDiskWritable(path);}restoreFactory = () => setEncoderBackendFactory(() => new NativeFFmpegBackend(() => path));@@ -183,7 +190,11 @@ async function runExportJobWith(engine: ExportEngine, job: ExportJob, project: PlockedPlayback = true;useProjectStore.getState().syncRenderProcessingFrom(project);}- generator = engine.exportVideo(project, settings, writable, frameSource ? { cachedFrames: frameSource } : {});+ // Desktop carries the preference in its encoder factory; the browser passes it per run so it never outlives this job.+ generator = engine.exportVideo(project, settings, writable, {+ ...(frameSource ? { cachedFrames: frameSource } : {}),+ ...(!desktop && encoder === "prefer-software" ? { encoderPreference: "prefer-software" as const } : {}),+ });let framesFromCache = 0;let smartRender: RunJobResult["smartRender"];let sourceMedia: string | undefined;diff --git a/apps/web/src/services/export-queue/transient-encoder-error.test.ts b/apps/web/src/services/export-queue/transient-encoder-error.test.tsindex 1043fa05..b0dfc2a3 100644--- a/apps/web/src/services/export-queue/transient-encoder-error.test.ts+++ b/apps/web/src/services/export-queue/transient-encoder-error.test.ts@@ -1,5 +1,5 @@import { describe, expect, it, vi } from "vitest";-import { isTransientEncoderError, runWithEncoderRetry } from "./transient-encoder-error";+import { canRetryInSoftware, hardwareEncoderFailureMessage, isTransientEncoderError, runWithEncoderRetry } from "./transient-encoder-error";const encodingError = () => new DOMException("Encoding error.", "EncodingError");@@ -24,6 +24,17 @@ describe("runWithEncoderRetry", () => {await expect(runWithEncoderRetry(run, { delayMs: 0 })).resolves.toBe("ok");expect(run).toHaveBeenCalledTimes(2);});+ it("tells each run its attempt number so the re-run can switch to a software encoder", async () => {+ vi.spyOn(console, "warn").mockImplementation(() => undefined);+ const accelerator = new DOMException("Encoding error. (Failed to initialize video encode accelerator.)", "EncodingError");+ expect(isTransientEncoderError(accelerator)).toBe(true);+ const run = vi.fn(async (attempt: number) => {+ if (attempt === 1) throw accelerator;+ return `software on attempt ${attempt}`;+ });+ await expect(runWithEncoderRetry(run, { delayMs: 0 })).resolves.toBe("software on attempt 2");+ expect(run.mock.calls.map(([attempt]) => attempt)).toEqual([1, 2]);+ });it("gives up after the attempts are used and surfaces the last error", async () => {vi.spyOn(console, "warn").mockImplementation(() => undefined);const run = vi.fn().mockRejectedValue(encodingError());@@ -40,3 +51,20 @@ describe("runWithEncoderRetry", () => {expect(cancelled).toHaveBeenCalledTimes(1);});});++describe("hardware-only retry policy", () => {+ it("only retries in software unless the user chose Hardware", () => {+ expect(canRetryInSoftware(undefined)).toBe(true);+ expect(canRetryInSoftware("auto")).toBe(true);+ expect(canRetryInSoftware("software")).toBe(true);+ expect(canRetryInSoftware("hardware")).toBe(false);+ });+ it("explains why a hardware failure was not retried", () => {+ expect(hardwareEncoderFailureMessage(encodingError())).toMatch(/Encoding error.*not retried in software.*Auto or Software/);+ });+ it("shouldRetry=false for Hardware surfaces the first error without a second run", async () => {+ const run = vi.fn().mockRejectedValue(encodingError());+ await expect(runWithEncoderRetry(run, { delayMs: 0, shouldRetry: () => canRetryInSoftware("hardware") })).rejects.toThrow("Encoding error");+ expect(run).toHaveBeenCalledTimes(1);+ });+});diff --git a/apps/web/src/services/export-queue/transient-encoder-error.ts b/apps/web/src/services/export-queue/transient-encoder-error.tsindex e51d65f6..daa9c49e 100644--- a/apps/web/src/services/export-queue/transient-encoder-error.ts+++ b/apps/web/src/services/export-queue/transient-encoder-error.ts@@ -24,11 +24,12 @@ export interface EncoderRetryOptions {readonly delayMs?: number;}-export async function runWithEncoderRetry<T>(run: () => Promise<T>, options: EncoderRetryOptions = {}): Promise<T> {+/** `run` receives the 1-based attempt number so a re-run can change strategy (e.g. fall back to a software encoder). */+export async function runWithEncoderRetry<T>(run: (attempt: number) => Promise<T>, options: EncoderRetryOptions = {}): Promise<T> {const attempts = options.attempts ?? 2;for (let attempt = 1; ; attempt++) {try {- return await run();+ return await run(attempt);} catch (error) {if (attempt >= attempts || !isTransientEncoderError(error) || options.shouldRetry?.(error, attempt + 1) === false) throw error;console.warn(`[export-queue] transient encoder failure (${(error as { message?: string }).message ?? error}); running the job again (attempt ${attempt + 1} of ${attempts}).`);@@ -36,3 +37,14 @@ export async function runWithEncoderRetry<T>(run: () => Promise<T>, options: Enc}}}++/** A re-run only helps when it can change something: an explicit Hardware choice would repeat the same failing encoder. */+export function canRetryInSoftware(encoderChoice: string | undefined): boolean {+ return encoderChoice !== "hardware";+}++export function hardwareEncoderFailureMessage(error: unknown): string {+ const detail = (error as { message?: unknown } | null)?.message;+ const reason = typeof detail === "string" && detail ? detail : "the hardware encoder failed";+ return `The hardware encoder failed (${reason}). Hardware was chosen in the export settings, so the export was not retried in software. Choose Auto or Software and export again.`;+}diff --git a/apps/web/src/services/keyboard-shortcuts.ts b/apps/web/src/services/keyboard-shortcuts.tsindex 5b1e5265..80d0d081 100644--- a/apps/web/src/services/keyboard-shortcuts.ts+++ b/apps/web/src/services/keyboard-shortcuts.ts@@ -484,6 +484,26 @@ const DEFAULT_SHORTCUTS: ShortcutDefinition[] = [action: "editing.overwrite",enabled: true,},+ {+ id: "editing.replaceEdit",+ name: "Replace Edit",+ description: "Replace the selected clip with the Source monitor clip, keeping its length",+ category: "editing",+ defaultKey: "shift+g",+ currentKey: "shift+g",+ action: "editing.replaceEdit",+ enabled: true,+ },+ {+ id: "editing.fitToFill",+ name: "Fit to Fill",+ description: "Fit the Source In/Out range into the timeline In/Out range, changing speed",+ category: "editing",+ defaultKey: "alt+shift+f",+ currentKey: "alt+shift+f",+ action: "editing.fitToFill",+ enabled: true,+ },{id: "editing.lift",name: "Lift",@@ -714,6 +734,16 @@ const DEFAULT_SHORTCUTS: ShortcutDefinition[] = [action: "tracks.toggleSyncLock",enabled: true,},+ {+ id: "editing.speedDuration",+ name: "Speed/Duration",+ description: "Change speed, duration, direction and pitch of the selected clips, optionally rippling trailing clips",+ category: "editing",+ defaultKey: "cmd+alt+r",+ currentKey: "cmd+alt+r",+ action: "editing.speedDuration",+ enabled: true,+ },{id: "editing.matchFrame",name: "Match Frame",@@ -724,6 +754,16 @@ const DEFAULT_SHORTCUTS: ShortcutDefinition[] = [action: "editing.matchFrame",enabled: true,},+ {+ id: "editing.reverseMatchFrame",+ name: "Reverse Match Frame",+ description: "Find the Source monitor frame in the sequence and move the playhead there",+ category: "editing",+ defaultKey: "shift+f",+ currentKey: "shift+f",+ action: "editing.reverseMatchFrame",+ enabled: true,+ },{id: "linked.replace",name: "Replace with Linked Composition",@@ -955,6 +995,16 @@ const DEFAULT_SHORTCUTS: ShortcutDefinition[] = [action: "tools.addMarker",enabled: true,},+ {+ id: "tools.addClipMarker",+ name: "Add Clip Marker",+ description: "Add a marker to the selected clip at the playhead (master-clip marker in the Source monitor)",+ category: "tools",+ defaultKey: "alt+shift+m",+ currentKey: "alt+shift+m",+ action: "tools.addClipMarker",+ enabled: true,+ },{id: "tools.editMarker",name: "Edit Marker",diff --git a/apps/web/src/services/media-stall.test.ts b/apps/web/src/services/media-stall.test.tsnew file mode 100644index 00000000..0f8c99f0--- /dev/null+++ b/apps/web/src/services/media-stall.test.ts@@ -0,0 +1,46 @@+import { describe, expect, it } from "vitest";+import { StallWatchdog, isWedged, type MediaSample } from "./media-stall";++const wedged: MediaSample = { currentTime: 1.257, readyState: 2, seeking: false, bufferedEnd: 6 };++describe("isWedged", () => {+ it("flags a buffered element with no future data and no pending seek", () => {+ expect(isWedged(wedged)).toBe(true);+ });+ it("ignores healthy, seeking and genuinely unbuffered elements", () => {+ expect(isWedged({ ...wedged, readyState: 4 })).toBe(false);+ expect(isWedged({ ...wedged, readyState: 4, seeking: false })).toBe(false);+ expect(isWedged({ ...wedged, bufferedEnd: -1 })).toBe(false);+ expect(isWedged({ ...wedged, bufferedEnd: 1.3 })).toBe(false);+ });+});++describe("StallWatchdog", () => {+ it("gives a pending seek longer than a plain stall before re-issuing it", () => {+ const w = new StallWatchdog(700, 2000);+ const seeking = { ...wedged, readyState: 1, seeking: true };+ expect(w.check(seeking, 0)).toBe(false);+ expect(w.check(seeking, 1500)).toBe(false);+ expect(w.check(seeking, 2000)).toBe(true);+ });+ it("asks for a re-seek after the element stays wedged at one position, then retries", () => {+ const w = new StallWatchdog(700);+ expect(w.check(wedged, 0)).toBe(false);+ expect(w.check(wedged, 400)).toBe(false);+ expect(w.check(wedged, 700)).toBe(true);+ expect(w.check(wedged, 1000)).toBe(false);+ expect(w.check(wedged, 1400)).toBe(true);+ });+ it("never fires while the position keeps moving or the element is healthy", () => {+ const w = new StallWatchdog(700);+ for (let t = 0; t < 3000; t += 250) expect(w.check({ ...wedged, currentTime: 1 + t / 1000 }, t)).toBe(false);+ for (let t = 0; t < 3000; t += 250) expect(w.check({ ...wedged, readyState: 4 }, t)).toBe(false);+ });+ it("restarts the timer when the position changes", () => {+ const w = new StallWatchdog(700);+ w.check(wedged, 0);+ w.check({ ...wedged, currentTime: 1.3 }, 600);+ expect(w.check({ ...wedged, currentTime: 1.3 }, 1000)).toBe(false);+ expect(w.check({ ...wedged, currentTime: 1.3 }, 1300)).toBe(true);+ });+});diff --git a/apps/web/src/services/media-stall.ts b/apps/web/src/services/media-stall.tsnew file mode 100644index 00000000..55efa36e--- /dev/null+++ b/apps/web/src/services/media-stall.ts@@ -0,0 +1,66 @@+/**+ * Stall recovery for the Source monitor's media element.+ *+ * Chrome's media pipeline can wedge after a seek: the element reports readyState < HAVE_FUTURE_DATA+ * (a "waiting" event), or a seek that never completes, although the whole file is buffered, and it+ * never resumes by itself. Pause/play does not help, but re-issuing the seek to the current position does.+ * The watchdog below detects exactly that state and reports when to re-seek.+ */++export interface MediaSample {+ currentTime: number;+ readyState: number;+ seeking: boolean;+ /** End of the buffered range containing currentTime, or -1 when none does. */+ bufferedEnd: number;+}++const HAVE_FUTURE_DATA = 3;+/** Buffered data this far ahead of the playhead means the element is not simply waiting for bytes. */+const MIN_BUFFERED_AHEAD = 0.25;++/**+ * True when the element looks wedged: it has no future data (or a seek that never completes) although+ * local data past the playhead is buffered, so it is not simply waiting for bytes.+ */+export function isWedged(s: MediaSample): boolean {+ return (s.seeking || s.readyState < HAVE_FUTURE_DATA) && s.bufferedEnd > s.currentTime + MIN_BUFFERED_AHEAD;+}++export function sampleMedia(el: HTMLMediaElement): MediaSample {+ let bufferedEnd = -1;+ for (let i = 0; i < el.buffered.length; i++) {+ if (el.buffered.start(i) <= el.currentTime + 0.05 && el.buffered.end(i) > el.currentTime) {+ bufferedEnd = el.buffered.end(i);+ break;+ }+ }+ return { currentTime: el.currentTime, readyState: el.readyState, seeking: el.seeking, bufferedEnd };+}++/**+ * Tracks consecutive wedged samples at an unchanged position. `check` returns true once the element+ * has been wedged for `stallMs` (`seekMs` while a seek is pending, since real seeks can be slow on a+ * loaded machine), then restarts the timer so a failed recovery is retried.+ */+export class StallWatchdog {+ private stuckSince: number | null = null;+ private lastTime = Number.NaN;++ constructor(+ private readonly stallMs = 700,+ private readonly seekMs = 2000,+ ) {}++ check(sample: MediaSample, now: number): boolean {+ if (!isWedged(sample) || sample.currentTime !== this.lastTime) {+ this.lastTime = sample.currentTime;+ this.stuckSince = isWedged(sample) ? now : null;+ return false;+ }+ if (this.stuckSince === null) this.stuckSince = now;+ if (now - this.stuckSince < (sample.seeking ? this.seekMs : this.stallMs)) return false;+ this.stuckSince = now;+ return true;+ }+}diff --git a/apps/web/src/services/motion-tracking-edit.ts b/apps/web/src/services/motion-tracking-edit.tsindex b6dadb05..c65847ae 100644--- a/apps/web/src/services/motion-tracking-edit.ts+++ b/apps/web/src/services/motion-tracking-edit.ts@@ -1,4 +1,4 @@-import { interpretedDisplaySize, keyframeEngine, resolveCanvasFitDimensions, type Clip, type ClipMetadata, type Keyframe, type MediaItem, type Project, type TrackingData, type Transform } from "@openreel/core";+import { interpretedDisplaySize, keyframeEngine, resolveCanvasFitDimensions, type Clip, type ClipMetadata, type Effect, type Keyframe, type MediaItem, type Project, type TrackingData, type Transform } from "@openreel/core";import { useProjectStore } from "../stores/project-store";import { useTimelineStore } from "../stores/timeline-store";import { useUIStore } from "../stores/ui-store";@@ -54,7 +54,7 @@ export function readMotionTrackingApplication(targetId: string): Application | nreturn value?.version === 1 && Array.isArray(value.generatedIds) && Array.isArray(value.replacedKeys) ? value : null;}-function replaceTarget(project: Project, id: string, changes: Pick<Target, "keyframes" | "metadata">): Project {+export function replaceTarget(project: Project, id: string, changes: Pick<Target, "keyframes" | "metadata"> & { effects?: Effect[] }): Project {return { ...project,timeline: { ...project.timeline, tracks: project.timeline.tracks.map(track => ({ ...track, clips: track.clips.map(clip => clip.id === id ? { ...clip, ...changes } : clip) })) },textClips: project.textClips?.map(clip => clip.id === id ? { ...clip, ...changes } : clip),@@ -64,7 +64,7 @@ function replaceTarget(project: Project, id: string, changes: Pick<Target, "keyf};}-function assertEditable(project: Project, target: Target) {+export function assertEditable(project: Project, target: Target) {if (!project.timeline.tracks.some(track => track.id === target.trackId && !track.locked)|| useUIStore.getState().exportState.isExporting || useUIStore.getState().effectApplicationClipId !== null || useTimelineStore.getState().playbackLockedReason) throw new Error("Unlock the target and finish exporting before applying tracking");}@@ -109,8 +109,22 @@ function animatedTransform(target: Target, time: number): Transform {scale: { x: sample("scale.x", base.scale.x), y: sample("scale.y", base.scale.y) }, rotation: sample("rotation", base.rotation) };}+/** A tracked source-pixel point, mapped through the source clip's animated transform onto the canvas (pixels from the top left). */+export function projectTrackedPoint(project: Project, source: Clip, media: MediaItem, position: { x: number; y: number }, localTime: number): { x: number; y: number; transform: Transform } {+ const transform = animatedTransform(source, localTime), crop = transform.crop;+ // Tracker samples are in stored pixels; the render fits the display shape (pixel aspect applied to the width).+ const display = interpretedDisplaySize(media), parX = display.width / media.metadata.width;+ const width = display.width * (crop?.width ?? 1), height = display.height * (crop?.height ?? 1);+ const fitted = resolveCanvasFitDimensions(transform.fitMode, width, height, project.settings.width, project.settings.height);+ const x = (position.x * parX - (crop?.x ?? 0) * display.width - width * transform.anchor.x) * fitted.width / width * transform.scale.x;+ const y = (position.y - (crop?.y ?? 0) * media.metadata.height - height * transform.anchor.y) * fitted.height / height * transform.scale.y;+ const radians = transform.rotation * Math.PI / 180;+ return { x: project.settings.width / 2 + transform.position.x + x * Math.cos(radians) - y * Math.sin(radians),+ y: project.settings.height / 2 + transform.position.y + x * Math.sin(radians) + y * Math.cos(radians), transform };+}+/** Remove only numerically collinear points; retain the authored sampled path. */-function compactLinearKeys(keys: Keyframe[]): Keyframe[] {+export function compactLinearKeys(keys: Keyframe[]): Keyframe[] {const output: Keyframe[] = [];for (const key of keys) {while (output.length > 1) {@@ -154,18 +168,7 @@ function computeApplication(project: Project, source: Clip, media: MediaItem, taconst time = source.startTime + sample.frame / analysis.data.frameRate;return time > overlapStart && time < overlapEnd;}), atTime(overlapEnd - source.startTime)];- const projectPoint = (sample: typeof selected[number]) => {- const transform = animatedTransform(source, sample.frame / analysis.data.frameRate), crop = transform.crop;- // Tracker samples are in stored pixels; the render fits the display shape (pixel aspect applied to the width).- const display = interpretedDisplaySize(media), parX = display.width / media.metadata.width;- const width = display.width * (crop?.width ?? 1), height = display.height * (crop?.height ?? 1);- const fitted = resolveCanvasFitDimensions(transform.fitMode, width, height, project.settings.width, project.settings.height);- const x = (sample.position.x * parX - (crop?.x ?? 0) * display.width - width * transform.anchor.x) * fitted.width / width * transform.scale.x;- const y = (sample.position.y - (crop?.y ?? 0) * media.metadata.height - height * transform.anchor.y) * fitted.height / height * transform.scale.y;- const radians = transform.rotation * Math.PI / 180;- return { x: project.settings.width / 2 + transform.position.x + x * Math.cos(radians) - y * Math.sin(radians),- y: project.settings.height / 2 + transform.position.y + x * Math.sin(radians) + y * Math.cos(radians), transform };- };+ const projectPoint = (sample: typeof selected[number]) => projectTrackedPoint(project, source, media, sample.position, sample.frame / analysis.data.frameRate);const first = selected[0], anchor = projectPoint(first), base = animatedTransform(target.clip, overlapStart - target.clip.startTime);const controlled = new Set(["position.x", "position.y", ...(options.applyScale ? ["scale.x", "scale.y"] : []), ...(options.applyRotation ? ["rotation"] : [])]);const localStart = overlapStart - target.clip.startTime, localEnd = overlapEnd - target.clip.startTime;diff --git a/apps/web/src/services/multicam-transcription.ts b/apps/web/src/services/multicam-transcription.tsindex 4fb38e3a..bde01664 100644--- a/apps/web/src/services/multicam-transcription.ts+++ b/apps/web/src/services/multicam-transcription.ts@@ -1,4 +1,5 @@import type { MulticamTranscriptSegment } from "@openreel/core";+import { backgroundTasks } from "@openreel/core/tasks/task-registry";import { audioBufferToWhisperSamples } from "../utils/whisper-audio";import type { WhisperModelKey } from "../workers/whisper-models";import { isDesktopRenderer } from "../workers/whisper-threads";@@ -20,13 +21,32 @@ export function whisperChunksToMulticamTranscript(});}-export async function transcribeMulticamChannels(+export function transcribeMulticamChannels(buffers: ReadonlyMap<string, AudioBuffer>,options: {model?: WhisperModelKey;language?: string;onStatus?: (angleId: string, message: string) => void;} = {},+): Promise<Record<string, MulticamTranscriptSegment[]>> {+ return backgroundTasks.track(+ { kind: "transcription", source: "transcription", title: `Transcribing multicam \u00b7 ${buffers.size} angle${buffers.size === 1 ? "" : "s"}` },+ (ctx) => transcribeMulticamChannelsUntracked(buffers, {+ ...options,+ signal: ctx.signal,+ onStatus: (angleId, message) => { ctx.progress(null, message); options.onStatus?.(angleId, message); },+ }),+ );+}++async function transcribeMulticamChannelsUntracked(+ buffers: ReadonlyMap<string, AudioBuffer>,+ options: {+ model?: WhisperModelKey;+ language?: string;+ onStatus?: (angleId: string, message: string) => void;+ signal?: AbortSignal;+ } = {},): Promise<Record<string, MulticamTranscriptSegment[]>> {const worker = new Worker(new URL("../workers/whisper-worker.ts", import.meta.url),@@ -38,6 +58,8 @@ export async function transcribeMulticamChannels(const requestId = crypto.randomUUID();options.onStatus?.(angleId, "Loading local Whisper model…");const result = await new Promise<{ chunks: WorkerChunk[] }>((resolve, reject) => {+ if (options.signal?.aborted) return reject(new DOMException("Aborted", "AbortError"));+ options.signal?.addEventListener("abort", () => reject(new DOMException("Aborted", "AbortError")), { once: true });const handleMessage = (event: MessageEvent<Record<string, unknown>>) => {if (event.data.requestId !== requestId) return;const type = event.data.type;diff --git a/apps/web/src/services/native-ffmpeg-backend.ts b/apps/web/src/services/native-ffmpeg-backend.tsindex 1603e2c7..e3183beb 100644--- a/apps/web/src/services/native-ffmpeg-backend.ts+++ b/apps/web/src/services/native-ffmpeg-backend.ts@@ -248,6 +248,8 @@ export class NativeFFmpegBackend implements EncoderBackend {});const portPromise = this.awaitExportPort();+ // If the start request is refused, the port never arrives; its timeout must not surface as an unhandled rejection.+ portPromise.catch(() => undefined);this.embeddedCaptions = undefined;let captions: Array<{ kind: "mov_text" | "cea608"; data: string; language?: string }> | undefined;@@ -279,6 +281,7 @@ export class NativeFFmpegBackend implements EncoderBackend {audioSampleRate: settings.audioSettings.sampleRate,audioChannels: monoTracks || settings.audioSettings.channels,encodeMode: settings.encodeMode ?? "balanced",+ ...(settings.encoderChoice && settings.encoderChoice !== "auto" ? { encoderChoice: settings.encoderChoice } : {}),quality: settings.quality,proresProfile: settings.proresProfile,...(settings.codec === "dnxhr" ? { dnxhrProfile: settings.dnxhrProfile ?? "hq" } : {}),diff --git a/apps/web/src/services/planar-track-edit.ts b/apps/web/src/services/planar-track-edit.tsnew file mode 100644index 00000000..853acb33--- /dev/null+++ b/apps/web/src/services/planar-track-edit.ts@@ -0,0 +1,129 @@+import { PRO_EFFECT_NEUTRAL_PARAMS, planarCornersAt,+ type Clip, type Effect, type Keyframe, type MediaItem, type PlanarTrackData, type Project,+} from "@openreel/core";+import { effectInstanceKeyframeProperty } from "@openreel/core/video/effect-instance-keyframes";+import { useProjectStore } from "../stores/project-store";+import { EditingSession } from "./agent/editing-session";+import { assertEditable, compactLinearKeys, projectTrackedPoint, replaceTarget } from "./motion-tracking-edit";+import { motionTrackingSourceSignature } from "./motion-tracking-source";++const PLANAR_ANALYSIS = "workspacePlanarTrackAnalysis";+export const PLANAR_APPLICATION = "workspacePlanarTrackApplication";+export interface PlanarTrackAnalysis { version: 1; signature: string; data: PlanarTrackData }+export interface PlanarApplyOptions { smoothing: number }+interface PlanarApplication { version: 1; sourceClipId: string; effectId: string; effectCreated: boolean; generatedIds: string[]; options: PlanarApplyOptions }++const PARAM_RANGE = { min: -100, max: 200 } as const;+export const planarEffectId = (sourceId: string): string => `planar-pin-${sourceId}`;++function validAnalysis(value: PlanarTrackAnalysis | undefined, clipId: string): value is PlanarTrackAnalysis {+ const d = value?.data;+ return value?.version === 1 && typeof value.signature === "string" && d?.version === 1 && d.clipId === clipId+ && Number.isFinite(d.frameRate) && d.frameRate > 0 && Array.isArray(d.keyframes) && Array.isArray(d.confidence)+ && Array.isArray(d.lostFrames) && Array.isArray(d.manualFrames) && d.anchorCorners?.length === 8+ && d.keyframes.every((k, i, all) => Number.isInteger(k.frame) && k.frame >= 0 && (i === 0 || k.frame > all[i - 1].frame)+ && k.corners.length === 8 && k.corners.every(Number.isFinite));+}++function sourceOf(project: Project, clipId: string): { clip: Clip; media: MediaItem } | null {+ const clip = project.timeline.tracks.flatMap(track => track.clips).find(c => c.id === clipId);+ const media = project.mediaLibrary.items.find(item => item.id === clip?.mediaId);+ return clip && media ? { clip, media } : null;+}++export function readPlanarTrackAnalysis(clipId: string): PlanarTrackAnalysis | null {+ const project = useProjectStore.getState().project, source = sourceOf(project, clipId);+ const value = source?.clip.metadata?.[PLANAR_ANALYSIS] as PlanarTrackAnalysis | undefined;+ return source && validAnalysis(value, clipId) && value.signature === motionTrackingSourceSignature(project, source.clip, source.media) ? value : null;+}++export function readPlanarTrackApplication(targetId: string): PlanarApplication | null {+ const clip = useProjectStore.getState().project.timeline.tracks.flatMap(track => track.clips).find(c => c.id === targetId);+ const value = clip?.metadata?.[PLANAR_APPLICATION] as PlanarApplication | undefined;+ return value?.version === 1 && Array.isArray(value.generatedIds) ? value : null;+}++/** Corner-pin keyframes (percent of the canvas) for the target, one `fx:` track per corner coordinate. Pure. */+function computeApplication(project: Project, source: Clip, media: MediaItem, target: Clip, data: PlanarTrackData, options: PlanarApplyOptions): { effects: Effect[]; keyframes: Keyframe[]; metadata: Clip["metadata"] } {+ if (!data.keyframes.length) throw new Error("The planar track is empty");+ if (!Number.isFinite(options.smoothing)) throw new Error("Choose valid tracking options");+ const start = Math.max(source.startTime, target.startTime), end = Math.min(source.startTime + source.duration, target.startTime + target.duration);+ if (end <= start) throw new Error("The source and target clips do not overlap");+ const fps = data.frameRate, radius = Math.max(0, Math.min(10, Math.round(options.smoothing)));+ const smoothed = data.keyframes.map((key, i) => {+ const near = data.keyframes.slice(Math.max(0, i - radius), Math.min(data.keyframes.length, i + radius + 1));+ return { frame: key.frame, corners: key.corners.map((_, c) => near.reduce((sum, n) => sum + n.corners[c], 0) / near.length) };+ });+ const view: PlanarTrackData = { ...data, keyframes: smoothed };+ const edgeFrame = (time: number) => (time - source.startTime) * fps;+ const frames = [edgeFrame(start), ...smoothed.map(k => k.frame).filter(f => source.startTime + f / fps > start && source.startTime + f / fps < end), edgeFrame(end)];+ const effectId = planarEffectId(source.id), previous = target.metadata?.[PLANAR_APPLICATION] as PlanarApplication | undefined;+ const generated = new Set(previous?.generatedIds ?? []);+ const lanes = new Map<string, Keyframe[]>();+ frames.forEach((frame, index) => {+ const at = planarCornersAt(view, frame);+ if (!at) return;+ const time = source.startTime + frame / fps;+ for (let c = 0; c < 4; c++) {+ const p = projectTrackedPoint(project, source, media, { x: at.corners[c * 2], y: at.corners[c * 2 + 1] }, frame / fps);+ const values = [p.x / project.settings.width * 100, p.y / project.settings.height * 100];+ (["x", "y"] as const).forEach((axis, k) => {+ const param = `${axis}${c}`, value = Math.max(PARAM_RANGE.min, Math.min(PARAM_RANGE.max, values[k]));+ if (!Number.isFinite(value)) throw new Error("Tracking produced an invalid corner");+ const lane = lanes.get(param) ?? [];+ lane.push({ id: `planar-${data.trackId}-${effectId}-${param}-${index}`, property: effectInstanceKeyframeProperty(effectId, param), time: time - target.startTime, value, easing: "linear" });+ lanes.set(param, lane);+ });+ }+ });+ const fresh = [...lanes.values()].flatMap(compactLinearKeys);+ const existing = target.effects.find(e => e.id === effectId);+ const effect: Effect = existing ?? { id: effectId, type: "corner-pin", params: { ...PRO_EFFECT_NEUTRAL_PARAMS["corner-pin"] }, enabled: true };+ const effects = existing ? target.effects.map(e => e.id === effectId ? { ...e, enabled: true } : e) : [...target.effects, effect];+ const application: PlanarApplication = { version: 1, sourceClipId: source.id, effectId, effectCreated: previous?.effectCreated ?? !existing, generatedIds: fresh.map(k => k.id), options };+ return { effects, keyframes: [...target.keyframes.filter(k => !generated.has(k.id)), ...fresh], metadata: { ...target.metadata, [PLANAR_APPLICATION]: application } };+}++function targets(project: Project, sourceId: string): Clip[] {+ return project.timeline.tracks.flatMap(track => track.clips).filter(c => (c.metadata?.[PLANAR_APPLICATION] as PlanarApplication | undefined)?.sourceClipId === sourceId);+}++/** Save an analysis on the source clip; every corner pin attached to it follows the new path in the same undo step. */+export async function persistPlanarTrackAnalysis(projectId: string, analysis: PlanarTrackAnalysis, signal?: AbortSignal, label = "Track planar surface"): Promise<void> {+ const session = new EditingSession(signal), transaction = session.beginTransaction(), project = session.getProject();+ const source = sourceOf(project, analysis.data.clipId);+ if (project.id !== projectId || !source || !validAnalysis(analysis, source.clip.id) || motionTrackingSourceSignature(project, source.clip, source.media) !== analysis.signature) throw new Error("The tracking source changed; analyze it again");+ assertEditable(project, source.clip);+ let next = replaceTarget(project, source.clip.id, { keyframes: source.clip.keyframes, metadata: { ...source.clip.metadata, [PLANAR_ANALYSIS]: structuredClone(analysis) } });+ for (const target of targets(next, source.clip.id)) {+ const application = target.metadata?.[PLANAR_APPLICATION] as PlanarApplication;+ if (!next.timeline.tracks.some(t => t.id === target.trackId && !t.locked)) continue;+ try { next = replaceTarget(next, target.id, computeApplication(next, source.clip, source.media, target, analysis.data, application.options)); } catch { /* a target that cannot follow keeps its last pin */ }+ }+ session.replaceDraft(next);+ await session.commitTransaction(transaction, label);+}++export async function applyPlanarTrack(sourceId: string, targetId: string, options: PlanarApplyOptions): Promise<void> {+ const session = new EditingSession(), transaction = session.beginTransaction(), project = session.getProject();+ const source = sourceOf(project, sourceId), target = project.timeline.tracks.flatMap(track => track.clips).find(c => c.id === targetId);+ const analysis = source?.clip.metadata?.[PLANAR_ANALYSIS] as PlanarTrackAnalysis | undefined;+ if (!source || !target || target.id === source.clip.id || !validAnalysis(analysis, sourceId) || analysis.signature !== motionTrackingSourceSignature(project, source.clip, source.media)) throw new Error("Track the current source and choose a different clip to pin");+ assertEditable(project, target);+ session.replaceDraft(replaceTarget(project, targetId, computeApplication(project, source.clip, source.media, target, analysis.data, options)));+ await session.commitTransaction(transaction, "Pin to tracked surface");+}++/** Detach the track: its keyframes go, and the Corner Pin effect goes too when this feature created it. */+export async function removePlanarTrack(targetId: string): Promise<void> {+ const session = new EditingSession(), transaction = session.beginTransaction(), project = session.getProject();+ const target = project.timeline.tracks.flatMap(track => track.clips).find(c => c.id === targetId);+ const application = target?.metadata?.[PLANAR_APPLICATION] as PlanarApplication | undefined;+ if (!target || application?.version !== 1) return;+ assertEditable(project, target);+ const generated = new Set(application.generatedIds), metadata = { ...target.metadata };+ delete metadata[PLANAR_APPLICATION];+ const effects = application.effectCreated ? target.effects.filter(e => e.id !== application.effectId) : target.effects;+ session.replaceDraft(replaceTarget(project, targetId, { effects, keyframes: target.keyframes.filter(k => !generated.has(k.id)), metadata }));+ await session.commitTransaction(transaction, "Remove planar tracking");+}diff --git a/apps/web/src/services/planar-track-stepper.ts b/apps/web/src/services/planar-track-stepper.tsnew file mode 100644index 00000000..d29fb6dd--- /dev/null+++ b/apps/web/src/services/planar-track-stepper.ts@@ -0,0 +1,34 @@+import { PlanarTrackSession, type PlanarSessionConfig, type PlanarStep, type PlanarStepper, type PlanarStepperFactory } from "@openreel/core";+import type { PlanarTrackWorkerReply } from "../workers/planar-track-worker";++/** Run the planar tracker in a dedicated worker (frame pixels are transferred), or in-thread where workers are unavailable. */+export const createWorkerPlanarStepper: PlanarStepperFactory = (config: PlanarSessionConfig): PlanarStepper => {+ if (typeof Worker === "undefined") {+ const session = new PlanarTrackSession(config);+ return { step: frame => session.step(frame), dispose: () => undefined };+ }+ const worker = new Worker(new URL("../workers/planar-track-worker.ts", import.meta.url), { type: "module" });+ const waiting = new Map<number, { resolve: (step: PlanarStep) => void; reject: (error: Error) => void }>();+ let nextId = 1, closed = false, failure: string | null = null;+ const failAll = (message: string) => { for (const entry of waiting.values()) entry.reject(new Error(message)); waiting.clear(); };+ worker.onmessage = (event: MessageEvent<PlanarTrackWorkerReply>) => {+ const reply = event.data;+ if (reply.type === "error" && reply.id === 0) { failure = reply.message; failAll(reply.message); return; }+ const entry = waiting.get(reply.id);+ if (!entry) return;+ waiting.delete(reply.id);+ if (reply.type === "step") entry.resolve(reply.step); else entry.reject(new Error(reply.message));+ };+ worker.onerror = event => { failure = event.message || "Tracking worker failed"; failAll(failure); };+ worker.postMessage({ type: "init", config });+ return {+ step: frame => new Promise<PlanarStep>((resolve, reject) => {+ if (closed) { reject(new DOMException("Tracking cancelled", "AbortError")); return; }+ if (failure) { reject(new Error(failure)); return; }+ const id = nextId++;+ waiting.set(id, { resolve, reject });+ worker.postMessage({ type: "step", id, frame }, [frame.data.buffer]);+ }),+ dispose: () => { closed = true; failAll("Tracking cancelled"); worker.terminate(); },+ };+};diff --git a/apps/web/src/services/premiere-edit-commands.test.ts b/apps/web/src/services/premiere-edit-commands.test.tsindex b723e393..ab05d2be 100644--- a/apps/web/src/services/premiere-edit-commands.test.ts+++ b/apps/web/src/services/premiere-edit-commands.test.ts@@ -4,6 +4,7 @@ import { beforeEach, describe, expect, it } from "vitest";import { useProjectStore } from "../stores/project-store";import { useTimelineStore } from "../stores/timeline-store";import { useUIStore } from "../stores/ui-store";+import { useSourceMonitorStore, pushSourceHistory } from "../stores/source-monitor-store";import { useEngineStore } from "../stores/engine-store";import { useEditorWorkspaceStore } from "../stores/editor-workspace-store";import { createEmptyProject } from "../stores/project/project-helpers";@@ -14,6 +15,7 @@ import {liftRange,matchFrame,overwriteSelectedMedia,+ reverseMatchFrame,} from "./premiere-edit-commands";const transform = {@@ -146,6 +148,31 @@ describe("premiere edit commands", () => {expect(useUIStore.getState().selectedItems.map((i) => i.id)).toEqual(["source"]);});+ it("reverse match frame moves the playhead to the topmost instance, or reports not found", () => {+ const project = useProjectStore.getState().project;+ const sm = useSourceMonitorStore.getState();+ useSourceMonitorStore.setState({ mediaId: null, history: [] });+ expect(reverseMatchFrame().success).toBe(false);+ sm.open("source", project.id, 12);+ const found = reverseMatchFrame();+ expect(found.success).toBe(true);+ expect(useTimelineStore.getState().playheadPosition).toBeCloseTo(6, 2);+ sm.open("source", project.id, 18);+ const missing = reverseMatchFrame();+ expect(missing.success).toBe(false);+ expect(useTimelineStore.getState().playheadPosition).toBeCloseTo(6, 2);+ });++ it("source history is most-recent-first, de-duplicated and capped", () => {+ expect(pushSourceHistory(["a", "b", "c"], "b")).toEqual(["b", "a", "c"]);+ expect(pushSourceHistory(Array.from({ length: 10 }, (_, i) => `m${i}`), "n")).toHaveLength(10);+ const project = useProjectStore.getState().project;+ useSourceMonitorStore.setState({ history: [], projectId: project.id });+ useSourceMonitorStore.getState().open("x", project.id);+ useSourceMonitorStore.getState().open("source", project.id);+ expect(useSourceMonitorStore.getState().history).toEqual(["source", "x"]);+ });+it("match frame on a specific clip uses that clip, not the topmost one", () => {const project = useProjectStore.getState().project;const first = project.timeline.tracks.flatMap((t) => t.clips)[0];diff --git a/apps/web/src/services/premiere-edit-commands.ts b/apps/web/src/services/premiere-edit-commands.tsindex 08017403..6e0f0c9b 100644--- a/apps/web/src/services/premiere-edit-commands.ts+++ b/apps/web/src/services/premiere-edit-commands.ts@@ -5,6 +5,7 @@ import {createEmptyTrack,createMediaClip,findTopmostVisualClipAt,+ findReverseMatch,planAddEdit,planAddEditToAllTracks,planExtract,@@ -296,6 +297,35 @@ export function matchFrame(clipId?: string): CommandOutcome {return { success: true, message: `${media.name} at ${timecode}` };}+/**+ * Reverse Match Frame (Shift+F): find the frame showing in the Source monitor+ * in the active sequence and park the playhead there. The topmost instance+ * wins; with none, nothing moves and the outcome explains why.+ */+export function reverseMatchFrame(): CommandOutcome {+ const source = useSourceMonitorStore.getState();+ const project = useProjectStore.getState().project;+ const media = source.mediaId+ ? project.mediaLibrary.items.find((item) => item.id === source.mediaId)+ : undefined;+ if (!media) return fail("Open a clip in the Source monitor first.");+ const frameRate = media.metadata.frameRate || project.settings.frameRate || 30;+ const hit = findReverseMatch(+ project,+ media.id,+ source.position,+ useTimelineStore.getState().playheadPosition,+ 1 / frameRate,+ );+ if (!hit) return fail(`This frame of ${media.name} is not in the sequence.`);+ useTimelineStore.getState().seekTo(hit.time);+ useUIStore.getState().select({ type: "clip", id: hit.clipId });+ return {+ success: true,+ message: `${media.name} at ${formatFrameTimecode(hit.time, project.settings.frameRate || frameRate)}`,+ };+}+/** The track a paste lands on: the first targeted track of the copied track* type, else the selected track, else the first unlocked track. */export function pickPasteTrack(project: Project): Track | undefined {diff --git a/apps/web/src/services/scene-detection.ts b/apps/web/src/services/scene-detection.tsindex 7fb3e260..7f9f88bc 100644--- a/apps/web/src/services/scene-detection.ts+++ b/apps/web/src/services/scene-detection.ts@@ -1,3 +1,4 @@+import { backgroundTasks } from "@openreel/core/tasks/task-registry";import {detectScenes,initializeMediaEngine,@@ -101,7 +102,27 @@ export function sourceToTimelineTime(clip: Clip, sourceTime: number): number {}/** Decodes small frames across the clip's source range and finds hard cuts. */-export async function analyseClipScenes(+export function analyseClipScenes(+ clipId: string,+ options: SceneDetectionRunOptions,+): Promise<SceneAnalysis> {+ return backgroundTasks.track({ kind: "analysis", source: "scene-detection", title: "Scene edit detection" }, (ctx) => {+ // The dialog's own signal and the task panel's cancel both stop the run.+ const external = options.signal;+ if (external?.aborted) backgroundTasks.cancel(ctx.id);+ else external?.addEventListener("abort", () => backgroundTasks.cancel(ctx.id), { once: true });+ return runSceneAnalysis(clipId, {+ ...options,+ signal: ctx.signal,+ onProgress: (p) => {+ ctx.progress(p.fraction);+ options.onProgress?.(p);+ },+ });+ });+}++async function runSceneAnalysis(clipId: string,options: SceneDetectionRunOptions,): Promise<SceneAnalysis> {diff --git a/apps/web/src/services/source-monitor-commands.test.ts b/apps/web/src/services/source-monitor-commands.test.tsindex 51ebbf6c..e3d10366 100644--- a/apps/web/src/services/source-monitor-commands.test.ts+++ b/apps/web/src/services/source-monitor-commands.test.ts@@ -92,3 +92,70 @@ describe("source monitor commands", () => {expect(useSourceMonitorStore.getState().rate).toBe(1);});});++describe("Replace and Fit to Fill commands", () => {+ const seedTimeline = () => {+ const base = createEmptyProject("t");+ const old = { id: "old", name: "old.mp4", type: "video", fileHandle: null, blob: null, thumbnailUrl: null, waveformData: null,+ metadata: { duration: 10, width: 640, height: 360, frameRate: 30, sampleRate: 48000, channels: 2, codec: "x", fileSize: 1, hasAudio: false } } as unknown as MediaItem;+ const clip = {+ id: "target", mediaId: "old", trackId: "v", startTime: 2, duration: 4, inPoint: 0, outPoint: 4,+ effects: [{ id: "fx", type: "blur", params: {}, enabled: true }], audioEffects: [],+ transform: { position: { x: 0, y: 0 }, scale: { x: 1, y: 1 }, rotation: 0, anchor: { x: 0.5, y: 0.5 }, opacity: 1 },+ volume: 1, keyframes: [],+ };+ useProjectStore.setState({+ hasOpenProject: true,+ project: {+ ...base,+ mediaLibrary: { items: [old, media("vid", "video")] },+ timeline: { ...base.timeline, tracks: [{ ...track("v", "video"), clips: [clip] } as unknown as Track] },+ },+ });+ useSourceMonitorStore.setState({ projectId: null, marks: {}, mediaId: null, position: 0, replaceKeepsAttributes: true });+ useSourceMonitorStore.getState().open("vid", useProjectStore.getState().project.id);+ };++ beforeEach(seedTimeline);++ it("Replace keeps the clip and its effects, and one undo restores the old footage", async () => {+ const { useTimelineStore } = await import("../stores/timeline-store");+ const { replaceFromSource } = await import("./source-monitor-commands");+ useTimelineStore.getState().seekTo(3);+ useSourceMonitorStore.getState().setPosition(5);+ const outcome = replaceFromSource();+ expect(outcome.success, outcome.message).toBe(true);+ const clip = () => useProjectStore.getState().project.timeline.tracks[0].clips[0];+ expect(clip()).toMatchObject({ id: "target", mediaId: "vid", startTime: 2, duration: 4, inPoint: 4, outPoint: 8 });+ expect(clip().effects).toHaveLength(1);+ await useProjectStore.getState().undo();+ expect(clip()).toMatchObject({ mediaId: "old", inPoint: 0, outPoint: 4 });+ });++ it("Replace without Keep resets effects; a too-short source changes nothing", async () => {+ const { useTimelineStore } = await import("../stores/timeline-store");+ const { replaceFromSource } = await import("./source-monitor-commands");+ useTimelineStore.getState().seekTo(2);+ expect(replaceFromSource({ keepAttributes: false }).success).toBe(true);+ expect(useProjectStore.getState().project.timeline.tracks[0].clips[0].effects).toHaveLength(0);+ seedTimeline();+ useTimelineStore.getState().seekTo(2);+ useSourceMonitorStore.getState().setPosition(8);+ const refused = replaceFromSource();+ expect(refused.success).toBe(false);+ expect(useProjectStore.getState().project.timeline.tracks[0].clips[0].mediaId).toBe("old");+ });++ it("Fit to Fill needs timeline marks, then retimes into them", async () => {+ const { useTimelineStore } = await import("../stores/timeline-store");+ const { fitToFillFromSource } = await import("./source-monitor-commands");+ useTimelineStore.getState().clearLoopRange();+ expect(fitToFillFromSource().success).toBe(false);+ setSourceMarks("vid", { in: 0, out: 8 });+ useTimelineStore.getState().setLoopRange(10, 14);+ const outcome = fitToFillFromSource();+ expect(outcome.success, outcome.message).toBe(true);+ const placed = useProjectStore.getState().project.timeline.tracks.flatMap((t) => t.clips).find((c) => c.id === outcome.clipId)!;+ expect(placed).toMatchObject({ startTime: 10, duration: 4, speed: 2, inPoint: 0, outPoint: 8 });+ });+});diff --git a/apps/web/src/services/source-monitor-commands.ts b/apps/web/src/services/source-monitor-commands.tsindex 8dabeb0f..49a2df5b 100644--- a/apps/web/src/services/source-monitor-commands.ts+++ b/apps/web/src/services/source-monitor-commands.ts@@ -1,18 +1,26 @@import { v4 as uuidv4 } from "uuid";import {+ findReplaceTarget,+ planFitToFill,+ planReplaceEdit,planSourceEdit,sourceDropError,type MediaItem,+ type ReplaceAlignment,+ type ResolvedFitToFill,+ type ResolvedReplace,type ResolvedSourceEdit,type SourceComponent,} from "@openreel/core";import { useProjectStore } from "../stores/project-store";+import { useUIStore } from "../stores/ui-store";import { useTimelineStore } from "../stores/timeline-store";import { useSourceMonitorStore } from "../stores/source-monitor-store";import {commit,findSourceTracks,getMarkedRange,+ getTargetedTrackIds,type CommandOutcome,} from "./premiere-edit-commands";@@ -184,3 +192,120 @@ export function dropSourceRange(if (outcome.success && resolved) useTimelineStore.getState().seekTo(resolved.at + resolved.duration);return { success: outcome.success, message: outcome.message };}++export interface FitToFillOutcome extends CommandOutcome {+ resolved?: ResolvedFitToFill;+ clipId?: string;+ trackId?: string;+ audioTrackId?: string;+}++const percent = (speed: number) => `${Math.round(speed * 1000) / 10}%`;++/**+ * Fit to Fill: the Source monitor's In/Out range (the whole media when+ * unmarked) is retimed to exactly fill the timeline In/Out range, and+ * overwritten onto the patched / targeted tracks. Audio follows the speed+ * with its pitch preserved. One undo step; no ripple, so Sync Lock has+ * nothing to move.+ */+export function fitToFillFromSource(component: SourceComponent = "both"): FitToFillOutcome {+ const sequence = getMarkedRange();+ if (!sequence) return fail("Fit to Fill needs In and Out marks on the timeline.");+ const media = getSourceMedia();+ if (!media) return fail("Open a clip in the Source monitor first.");+ if (media.type === "image") return fail("Fit to Fill needs video or audio; a still has no speed to change.");+ const marks = useSourceMonitorStore.getState().getMarks(media.id);+ const { primary, audio } = findSourceTracks(useProjectStore.getState().project, media, component);+ const { track, created } = primary;+ const clipId = uuidv4();+ const audioClipId = uuidv4();+ let resolved: ResolvedFitToFill | undefined;+ const outcome = commit((project) => {+ const planned = planFitToFill(project, {+ media,+ trackId: track.id,+ clipId,+ operationId: uuidv4(),+ sourceIn: marks.in,+ sourceOut: marks.out,+ sequenceIn: sequence.start,+ sequenceOut: sequence.end,+ component,+ newTrack: created,+ audioPatch: audio+ ? { trackId: audio.track.id, clipId: audioClipId, newTrack: audio.created }+ : undefined,+ });+ resolved = planned.resolved;+ return planned.plan;+ }, "Nothing to place.");+ if (!outcome.success || !resolved) return { success: false, message: outcome.message };+ useTimelineStore.getState().seekTo(resolved.at + resolved.duration);+ return {+ success: true,+ message: `Fit to Fill at ${percent(resolved.speed)} speed`,+ resolved,+ clipId,+ trackId: track.id,+ ...(audio ? { audioTrackId: audio.track.id } : {}),+ };+}++export interface ReplaceOutcome extends CommandOutcome {+ resolved?: ResolvedReplace;+}++/**+ * Replace edit: swap the footage of the selected timeline clip (else the+ * topmost clip under the playhead) for the Source monitor's clip. The clip+ * keeps its place and length. By default the Source monitor's current frame is+ * aligned with the timeline playhead; with the playhead outside the clip, or+ * `alignment: "in"`, the source In (media start when unmarked) lands on the+ * clip's first frame. Effects, keyframes and audio settings are kept unless+ * the Source monitor's Keep toggle is off. One undo step.+ */+export function replaceFromSource(+ options: { alignment?: ReplaceAlignment; keepAttributes?: boolean } = {},+): ReplaceOutcome {+ const playhead = useTimelineStore.getState().playheadPosition;+ const media = getSourceMedia();+ if (!media) return fail("Open a clip in the Source monitor first.");+ const source = useSourceMonitorStore.getState();+ const marks = source.getMarks(media.id);+ const keepAttributes = options.keepAttributes ?? source.replaceKeepsAttributes;+ const alignment = options.alignment ?? "playhead";+ const selectedClipIds = useUIStore+ .getState()+ .selectedItems.filter((item) => item.type === "clip")+ .map((item) => item.id);+ let resolved: ResolvedReplace | undefined;+ const outcome = commit((project) => {+ const target = findReplaceTarget(project, {+ media,+ selectedClipIds,+ playhead,+ targetedTrackIds: getTargetedTrackIds(project),+ });+ if (!target) throw new Error("Select a timeline clip, or park the playhead over one, to replace.");+ const planned = planReplaceEdit(project, {+ clipId: target.id,+ media,+ alignment,+ playhead,+ sourcePosition: source.position,+ sourceIn: marks.in,+ keepAttributes,+ });+ resolved = planned.resolved;+ return planned.plan;+ }, "Nothing to replace.");+ if (!outcome.success || !resolved) return { success: false, message: outcome.message };+ return {+ success: true,+ resolved,+ message: resolved.fellBackToIn+ ? `Replaced with ${media.name}, aligned at the source In (the playhead is outside the clip)`+ : `Replaced with ${media.name}`,+ };+}diff --git a/apps/web/src/services/source-monitor-controller.ts b/apps/web/src/services/source-monitor-controller.tsindex ea97639f..1a81abe2 100644--- a/apps/web/src/services/source-monitor-controller.ts+++ b/apps/web/src/services/source-monitor-controller.ts@@ -5,6 +5,7 @@ import {insertFromSource,overwriteFromSource,} from "./source-monitor-commands";+import { addSourceMarker } from "./clip-marker-commands";import { runWithToast } from "./premiere-edit-commands";/**@@ -116,6 +117,8 @@ export function handleSourceMonitorAction(action: string): boolean {case "playback.goToEnd": seekSource(Number.POSITIVE_INFINITY); return true;case "playback.markLoopStart": markSource("in"); return true;case "playback.markLoopEnd": markSource("out"); return true;+ case "tools.addMarker":+ case "tools.addClipMarker": void addSourceMarker(); return true;case "editing.insert": runWithToast("Insert", () => insertFromSource()); return true;case "editing.overwrite": runWithToast("Overwrite", () => overwriteFromSource()); return true;default: return false;diff --git a/apps/web/src/services/transcript-commands.speaker.test.ts b/apps/web/src/services/transcript-commands.speaker.test.tsnew file mode 100644index 00000000..a27e8bdc--- /dev/null+++ b/apps/web/src/services/transcript-commands.speaker.test.ts@@ -0,0 +1,36 @@+import { describe, expect, it, vi } from "vitest";++const cue = (id: string, start: number, end: number, extra: Record<string, unknown> = {}) => ({+ id, text: id, startTime: start, endTime: end, words: [], ...extra,+});+const state = {+ project: {+ speakers: [] as unknown[],+ timeline: {+ tracks: [],+ subtitles: [+ cue("a", 0, 2, { speaker: "Ann" }),+ cue("b", 2, 4, { speaker: "Ann" }),+ cue("fa", 0, 2, { captionTrackId: "fr", hidden: true, speaker: "Ann" }),+ cue("fb", 2, 4, { captionTrackId: "fr", hidden: true, speaker: "Ann" }),+ ],+ },+ },+ executeAction: vi.fn(async () => ({ success: true })),+};+vi.mock("../stores/project-store", () => ({ useProjectStore: { getState: () => state } }));+vi.mock("../stores/timeline-store", () => ({ useTimelineStore: { getState: () => ({}) } }));++import { setCaptionSpeaker } from "./transcript-commands";++describe("setCaptionSpeaker", () => {+ it("reassigns the matching cues on translated tracks too", async () => {+ const outcome = await setCaptionSpeaker(["b"], "Bob");+ expect(outcome.success).toBe(true);+ const call = state.executeAction.mock.calls[0] as unknown as [+ { params: { subtitles: Array<{ id: string; speaker?: string }> } },+ ];+ const speakers = Object.fromEntries(call[0].params.subtitles.map((c) => [c.id, c.speaker]));+ expect(speakers).toEqual({ a: "Ann", b: "Bob", fa: "Ann", fb: "Bob" });+ });+});diff --git a/apps/web/src/services/transcript-commands.ts b/apps/web/src/services/transcript-commands.tsindex d4d58af8..4807d08e 100644--- a/apps/web/src/services/transcript-commands.ts+++ b/apps/web/src/services/transcript-commands.ts@@ -1,8 +1,14 @@import { v4 as uuidv4 } from "uuid";import {+ applySpeakerStyles,assignSpeaker,+ mirrorSpeakersToTranslations,+ ensureSpeakerProfiles,+ renameSpeakerProfile,+ type SpeakerProfile,buildTranscript,cutDuration,+ decodeCaptionText,exportCaptionFile,exportCaptions,findFillerWords,@@ -13,6 +19,9 @@ import {parseTranscriptJson,planTranscriptCut,renameSpeaker,+ translateCaptionTrack,+ type CaptionTranslationProgress,+ type CaptionTranslator,type CaptionExportFormat,type CaptionExportOptions,type CaptionFile,@@ -104,7 +113,7 @@ export async function importCaptionBytes(bytes: Uint8Array,options: CaptionImportOptions = {},): Promise<CaptionImportOutcome> {- if (!isStlContent(bytes)) return importCaptionText(new TextDecoder("utf-8").decode(bytes), options);+ if (!isStlContent(bytes)) return importCaptionText(decodeCaptionText(bytes), options);const r = parseCaptionBytes(bytes, options);const errors = r.errors.map((e) => e.message);if (!r.subtitles.length)@@ -113,19 +122,58 @@ export async function importCaptionBytes(return { ...outcome, added: r.subtitles.length, errors, issues: r.issues };}-/** Rename a speaker on every cue (one undo step). */+const getProfiles = (): readonly SpeakerProfile[] => useProjectStore.getState().project.speakers ?? [];++/** Profiles of speakers that still have cues (unused ones are dropped). */+const used = (subtitles: readonly Subtitle[], profiles: SpeakerProfile[]) =>+ profiles.filter((p) => subtitles.some((cue) => cue.speaker === p.name));++/** Commit cues and speaker profiles together as one undo step. */+async function applySpeakers(subtitles: Subtitle[], profiles: SpeakerProfile[]): Promise<CommandOutcome> {+ const result = await useProjectStore.getState().executeAction({+ type: "speaker/apply",+ id: uuidv4(),+ timestamp: Date.now(),+ params: { subtitles: applySpeakerStyles(subtitles, used(subtitles, profiles)), profiles: used(subtitles, profiles) },+ });+ return result.success+ ? { success: true }+ : { success: false, message: result.error?.message ?? "The speaker change failed." };+}++/** Rename a speaker on every cue and its profile (one undo step). Renaming onto another speaker merges them. */export async function renameTranscriptSpeaker(from: string, to: string): Promise<CommandOutcome> {const current = getSubtitles();const next = renameSpeaker(current, from, to);if (next === current) return { success: false, message: `No captions are labelled "${from}".` };- return setSubtitles(next);+ const profiles = ensureSpeakerProfiles(next, renameSpeakerProfile(ensureSpeakerProfiles(current, getProfiles()), from, to));+ return applySpeakers(next, profiles);}+/** Reassign cues to a speaker (an empty name clears it); a new name gets the next palette colour. */export async function setCaptionSpeaker(subtitleIds: readonly string[],speaker: string,): Promise<CommandOutcome> {- return setSubtitles(assignSpeaker(getSubtitles(), subtitleIds, speaker));+ const next = mirrorSpeakersToTranslations(+ assignSpeaker(getSubtitles(), subtitleIds, speaker),+ new Set(subtitleIds),+ );+ return applySpeakers(next, ensureSpeakerProfiles(next, getProfiles()));+}++/** Change a speaker's colour / caption position; their cues are restyled in the same undo step. */+export async function updateSpeakerProfile(+ name: string,+ patch: Partial<Pick<SpeakerProfile, "color" | "position">>,+): Promise<CommandOutcome> {+ const current = getSubtitles();+ const profiles = ensureSpeakerProfiles(current, getProfiles()).map((p) => {+ if (p.name !== name) return p;+ const { position, ...rest } = { ...p, ...patch };+ return position ? { ...rest, position } : rest;+ });+ return applySpeakers(current, profiles);}/** Cut time ranges out of the sequence (linked tracks together), one undo step. */@@ -170,3 +218,50 @@ export const exportCaptionBytes = (format: CaptionExportFormat,options: CaptionExportOptions = {},): CaptionFile => exportCaptionFile(getSubtitles(), format, options);++export type CaptionTranslateOutcome = CommandOutcome & { trackId?: string; added?: number; cancelled?: boolean };++/**+ * Choose which caption track is drawn in the picture (Preview and burned-in export).+ * Showing a track hides every other track so two languages never overlap; hiding+ * a track just hides it. One undo step. Transcript, sidecar and embedded captions are unaffected.+ */+export async function setCaptionTrackInPicture(trackId: string, visible: boolean): Promise<CommandOutcome> {+ const next = getSubtitles().map((cue): Subtitle => {+ const mine = (cue.captionTrackId ?? "") === trackId;+ if (mine) return visible ? omitHidden(cue) : { ...cue, hidden: true };+ return visible ? { ...cue, hidden: true } : cue;+ });+ return setSubtitles(next);+}++function omitHidden(cue: Subtitle): Subtitle {+ const { hidden: _hidden, ...rest } = cue;+ void _hidden;+ return rest;+}++/**+ * Translate a caption track into a new track (one undo step: removing the track's cues).+ * Nothing is committed unless every batch succeeded.+ */+export async function translateCaptionTrackCommand(options: {+ sourceTrackId: string;+ targetLanguage: string;+ translator: CaptionTranslator;+ signal?: AbortSignal;+ onProgress?: (progress: CaptionTranslationProgress) => void;+}): Promise<CaptionTranslateOutcome> {+ const result = await translateCaptionTrack({+ subtitles: getSubtitles(),+ sourceTrackId: options.sourceTrackId,+ targetLanguage: options.targetLanguage,+ translator: options.translator,+ signal: options.signal,+ onProgress: options.onProgress,+ idFactory: () => `tr-${uuidv4()}`,+ });+ if (!result.ok) return { success: false, message: result.message, cancelled: result.reason === "cancelled" };+ const outcome = await setSubtitles([...getSubtitles(), ...result.cues]);+ return outcome.success ? { success: true, trackId: result.trackId, added: result.cues.length } : outcome;+}diff --git a/apps/web/src/services/voiceover/voiceover-logic.test.ts b/apps/web/src/services/voiceover/voiceover-logic.test.tsnew file mode 100644index 00000000..4f095b15--- /dev/null+++ b/apps/web/src/services/voiceover/voiceover-logic.test.ts@@ -0,0 +1,192 @@+import { describe, expect, it } from "vitest";+import {+ DEFAULT_VOICE_OVER_PREFS,+ audioTrackChoices,+ chooseTakeTrack,+ clampPreRoll,+ countdownSeconds,+ isVoiceOverMediaName,+ listVoiceOverTakes,+ nextTakeNumber,+ nextVoiceTrackName,+ parseTakeNumber,+ parseVoiceOverPrefs,+ peakLevel,+ planTimings,+ punchRange,+ resolveRecordPlan,+ selectVoiceOverMimeType,+ takeName,+ takeTimelineStart,+ type PlacementTrack,+} from "./voiceover-logic";++describe("resolveRecordPlan", () => {+ it("records from the playhead with a pre-roll lead-in", () => {+ const plan = resolveRecordPlan({ playhead: 10, preRoll: 3, punch: false, markIn: 0, markOut: 0 });+ expect(plan).toEqual({ punched: false, recordStart: 10, recordEnd: null, preRoll: 3, playFrom: 7, playDelay: 0 });+ });++ it("delays playback when the pre-roll reaches before the start of the timeline", () => {+ const plan = resolveRecordPlan({ playhead: 1, preRoll: 3, punch: false, markIn: 0, markOut: 0 });+ expect(plan.playFrom).toBe(0);+ expect(plan.playDelay).toBe(2);+ const atZero = resolveRecordPlan({ playhead: 0, preRoll: 2, punch: false, markIn: 0, markOut: 0 });+ expect(atZero.playFrom).toBe(0);+ expect(atZero.playDelay).toBe(2);+ });++ it("starts immediately with zero pre-roll", () => {+ const plan = resolveRecordPlan({ playhead: 4.5, preRoll: 0, punch: false, markIn: 0, markOut: 0 });+ expect(plan).toMatchObject({ recordStart: 4.5, playFrom: 4.5, playDelay: 0, preRoll: 0 });+ expect(planTimings(plan)).toEqual({ startAfterMs: 0, autoStopAfterMs: null });+ });++ it("punches between In and Out regardless of the playhead", () => {+ const plan = resolveRecordPlan({ playhead: 99, preRoll: 2, punch: true, markIn: 8, markOut: 14.5 });+ expect(plan).toEqual({ punched: true, recordStart: 8, recordEnd: 14.5, preRoll: 2, playFrom: 6, playDelay: 0 });+ expect(planTimings(plan)).toEqual({ startAfterMs: 2000, autoStopAfterMs: 6500 });+ });++ it("falls back to a normal take when punch is on but there is no valid In/Out range", () => {+ const plan = resolveRecordPlan({ playhead: 5, preRoll: 1, punch: true, markIn: 0, markOut: 0 });+ expect(plan.punched).toBe(false);+ expect(plan.recordStart).toBe(5);+ expect(plan.recordEnd).toBeNull();+ expect(punchRange(5, 4)).toBeNull();+ expect(punchRange(2, 2.01)).toBeNull();+ });++ it("clamps the pre-roll to 0..5 whole seconds", () => {+ expect(clampPreRoll(9)).toBe(5);+ expect(clampPreRoll(-2)).toBe(0);+ expect(clampPreRoll(2.6)).toBe(3);+ expect(clampPreRoll("x")).toBe(DEFAULT_VOICE_OVER_PREFS.preRoll);+ expect(resolveRecordPlan({ playhead: 20, preRoll: 12, punch: false, markIn: 0, markOut: 0 }).preRoll).toBe(5);+ });+});++describe("countdownSeconds", () => {+ it("counts whole seconds down to zero", () => {+ expect([3000, 2999, 1001, 1000, 1, 0, -5].map(countdownSeconds)).toEqual([3, 3, 2, 1, 1, 0, 0]);+ });+});++describe("takeTimelineStart", () => {+ it("moves the take earlier by the input latency, within bounds", () => {+ expect(takeTimelineStart(10, 0.04)).toBeCloseTo(9.96);+ expect(takeTimelineStart(10, 5)).toBe(9.75);+ expect(takeTimelineStart(0.01, 0.1)).toBe(0);+ expect(takeTimelineStart(10, undefined)).toBe(10);+ expect(takeTimelineStart(10, Number.NaN)).toBe(10);+ expect(takeTimelineStart(10, -1)).toBe(10);+ });+});++describe("take naming", () => {+ it("numbers takes after the highest existing one", () => {+ expect(nextTakeNumber([])).toBe(1);+ expect(nextTakeNumber(["Music.mp3", "Voice Over Take 1.webm", "Voice Over Take 4.webm", "Voice Over Take 2.webm"])).toBe(5);+ expect(takeName(3)).toBe("Voice Over Take 3");+ expect(parseTakeNumber("Voice Over Take 12.webm")).toBe(12);+ expect(parseTakeNumber("Voice Over Take 7")).toBe(7);+ expect(parseTakeNumber("My Voice Over Take 7")).toBeNull();+ });++ it("recognises older date-stamped voice-overs", () => {+ expect(isVoiceOverMediaName("Voice-over 2026-05-22T10-11-12-000Z.webm")).toBe(true);+ expect(isVoiceOverMediaName("Interview.webm")).toBe(false);+ });++ it("names new tracks Voice Over, Voice Over 2, ...", () => {+ expect(nextVoiceTrackName([{ name: "Audio 1" }])).toBe("Voice Over");+ expect(nextVoiceTrackName([{ name: "Voice Over" }])).toBe("Voice Over 2");+ expect(nextVoiceTrackName([{ name: "Voice Over" }, { name: "Voice Over 2" }])).toBe("Voice Over 3");+ });+});++const track = (id: string, patch: Partial<PlacementTrack> = {}): PlacementTrack => ({+ id,+ name: id,+ type: "audio",+ locked: false,+ clips: [],+ ...patch,+});++describe("chooseTakeTrack", () => {+ it("creates a new track when none is chosen", () => {+ expect(chooseTakeTrack([track("a1")], "", 0, 5)).toEqual({ kind: "new", trackName: "Voice Over", reason: "requested" });+ });++ it("uses the chosen track when the range is free", () => {+ const tracks = [track("a1", { clips: [{ startTime: 0, duration: 4 }] })];+ expect(chooseTakeTrack(tracks, "a1", 4, 9)).toEqual({ kind: "existing", trackId: "a1" });+ });++ it("stacks onto a new track when the range is occupied (a re-take never overlaps)", () => {+ const tracks = [track("a1", { name: "Voice Over", clips: [{ startTime: 2, duration: 6 }] })];+ expect(chooseTakeTrack(tracks, "a1", 5, 9)).toEqual({ kind: "new", trackName: "Voice Over 2", reason: "occupied" });+ expect(chooseTakeTrack(tracks, "a1", 0, 3)).toMatchObject({ kind: "new", reason: "occupied" });+ });++ it("treats touching clips as free", () => {+ const tracks = [track("a1", { clips: [{ startTime: 0, duration: 5 }] })];+ expect(chooseTakeTrack(tracks, "a1", 5, 8).kind).toBe("existing");+ });++ it("does not record onto a missing, locked or non-audio track", () => {+ expect(chooseTakeTrack([track("a1", { locked: true })], "a1", 0, 2)).toMatchObject({ kind: "new", reason: "unavailable" });+ expect(chooseTakeTrack([track("v1", { type: "video" })], "v1", 0, 2)).toMatchObject({ kind: "new", reason: "unavailable" });+ expect(chooseTakeTrack([], "gone", 0, 2)).toMatchObject({ kind: "new", reason: "unavailable" });+ });++ it("offers only unlocked audio tracks", () => {+ const tracks = [track("a1"), track("a2", { locked: true }), track("v1", { type: "video" })];+ expect(audioTrackChoices(tracks).map((t) => t.id)).toEqual(["a1"]);+ });+});++describe("listVoiceOverTakes", () => {+ it("lists older recordings first, then takes in recording order", () => {+ const names = new Map([+ ["m1", "Voice Over Take 2.webm"],+ ["m2", "Voice Over Take 1.webm"],+ ["m3", "Voice-over 2026-01-02T03-04-05-000Z.webm"],+ ["m4", "Music.mp3"],+ ]);+ const takes = listVoiceOverTakes(+ [+ { id: "t1", clips: [{ id: "c1", mediaId: "m1", startTime: 9, duration: 3 }, { id: "c4", mediaId: "m4", startTime: 0, duration: 30 }] },+ { id: "t2", clips: [{ id: "c2", mediaId: "m2", startTime: 2, duration: 4 }, { id: "c3", mediaId: "m3", startTime: 1, duration: 2 }] },+ ],+ names,+ );+ expect(takes.map((t) => t.clipId)).toEqual(["c3", "c2", "c1"]);+ expect(takes[1]).toMatchObject({ name: "Voice Over Take 1", number: 1, trackId: "t2", duration: 4 });+ });+});++describe("parseVoiceOverPrefs", () => {+ it("round-trips and falls back on bad input", () => {+ const saved = { deviceId: "mic-7", preRoll: 4, punch: true, muteDuringRecord: false, targetTrackId: "t9" };+ expect(parseVoiceOverPrefs(JSON.stringify(saved))).toEqual(saved);+ expect(parseVoiceOverPrefs(null)).toEqual(DEFAULT_VOICE_OVER_PREFS);+ expect(parseVoiceOverPrefs("{not json")).toEqual(DEFAULT_VOICE_OVER_PREFS);+ expect(parseVoiceOverPrefs('{"preRoll":99,"punch":"yes"}')).toMatchObject({ preRoll: 5, punch: false });+ });+});++describe("meter and format helpers", () => {+ it("peakLevel is 0 for silence and 1 at full scale", () => {+ expect(peakLevel([128, 128, 128])).toBe(0);+ expect(peakLevel([128, 0, 128])).toBe(1);+ expect(peakLevel([128, 192])).toBeCloseTo(0.5);+ });++ it("selects the first supported recording format", () => {+ expect(selectVoiceOverMimeType((t) => t === "audio/webm;codecs=opus")).toEqual({ mimeType: "audio/webm;codecs=opus", extension: "webm" });+ expect(selectVoiceOverMimeType((t) => t === "audio/mp4")).toEqual({ mimeType: "audio/mp4", extension: "m4a" });+ expect(selectVoiceOverMimeType(() => false)).toBeNull();+ });+});diff --git a/apps/web/src/services/voiceover/voiceover-logic.ts b/apps/web/src/services/voiceover/voiceover-logic.tsnew file mode 100644index 00000000..62cc5cb6--- /dev/null+++ b/apps/web/src/services/voiceover/voiceover-logic.ts@@ -0,0 +1,289 @@+/**+ * Pure timing, placement and naming rules for voice-over recording. Nothing here touches the DOM,+ * the stores or the clock, so the rules are unit-tested on their own (voiceover-logic.test.ts) and the+ * recorder service only wires them to MediaRecorder, the transport and the action system.+ */++export const MAX_PRE_ROLL_SECONDS = 5;+/** Shortest In/Out range that counts as a punch range. */+export const MIN_PUNCH_SECONDS = 0.05;+/** Largest input latency we compensate for when placing a take. */+export const MAX_LATENCY_COMPENSATION_SECONDS = 0.25;+const OVERLAP_EPSILON = 1e-4;++export const VOICE_OVER_TRACK_NAME = "Voice Over";++export interface VoiceOverPrefs {+ /** Chosen input device; "" is the system default. */+ deviceId: string;+ /** Seconds of countdown with playback running before recording starts, 0..5. */+ preRoll: number;+ /** Record only between the In and Out marks. */+ punch: boolean;+ /** Mute timeline playback while recording so speakers do not bleed into the microphone. */+ muteDuringRecord: boolean;+ /** Destination audio track id; "" creates a new Voice Over track. */+ targetTrackId: string;+}++export const DEFAULT_VOICE_OVER_PREFS: VoiceOverPrefs = {+ deviceId: "",+ preRoll: 3,+ punch: false,+ muteDuringRecord: true,+ targetTrackId: "",+};++export const VOICE_OVER_PREFS_KEY = "openreel:voiceover:prefs:v1";++export function clampPreRoll(value: unknown): number {+ const n = typeof value === "number" ? value : Number(value);+ if (!Number.isFinite(n)) return DEFAULT_VOICE_OVER_PREFS.preRoll;+ return Math.min(MAX_PRE_ROLL_SECONDS, Math.max(0, Math.round(n)));+}++/** Reads remembered preferences defensively: anything missing or malformed falls back to the default. */+export function parseVoiceOverPrefs(raw: string | null | undefined): VoiceOverPrefs {+ if (!raw) return { ...DEFAULT_VOICE_OVER_PREFS };+ try {+ const value = JSON.parse(raw) as Partial<Record<keyof VoiceOverPrefs, unknown>> | null;+ if (!value || typeof value !== "object") return { ...DEFAULT_VOICE_OVER_PREFS };+ return {+ deviceId: typeof value.deviceId === "string" ? value.deviceId : DEFAULT_VOICE_OVER_PREFS.deviceId,+ preRoll: value.preRoll === undefined ? DEFAULT_VOICE_OVER_PREFS.preRoll : clampPreRoll(value.preRoll),+ punch: typeof value.punch === "boolean" ? value.punch : DEFAULT_VOICE_OVER_PREFS.punch,+ muteDuringRecord:+ typeof value.muteDuringRecord === "boolean" ? value.muteDuringRecord : DEFAULT_VOICE_OVER_PREFS.muteDuringRecord,+ targetTrackId: typeof value.targetTrackId === "string" ? value.targetTrackId : DEFAULT_VOICE_OVER_PREFS.targetTrackId,+ };+ } catch {+ return { ...DEFAULT_VOICE_OVER_PREFS };+ }+}++/** The In/Out marks (the timeline's loop range) are a punch range only when Out is after In. */+export function punchRange(markIn: number, markOut: number): { start: number; end: number } | null {+ if (!Number.isFinite(markIn) || !Number.isFinite(markOut)) return null;+ if (markOut - markIn < MIN_PUNCH_SECONDS) return null;+ return { start: Math.max(0, markIn), end: markOut };+}++export interface RecordPlanInput {+ playhead: number;+ preRoll: number;+ punch: boolean;+ markIn: number;+ markOut: number;+}++export interface RecordPlan {+ /** Whether recording is bounded by the In/Out marks. */+ punched: boolean;+ /** Timeline time at which recording starts; where the take is placed. */+ recordStart: number;+ /** Timeline time at which recording stops by itself; null records until stopped. */+ recordEnd: number | null;+ /** Countdown length in seconds (always the configured pre-roll). */+ preRoll: number;+ /** Timeline time playback starts from during the pre-roll. */+ playFrom: number;+ /** Seconds the transport waits before playing; > 0 only when the start is closer to 0 than the pre-roll. */+ playDelay: number;+}++/**+ * With a punch range, recording runs from In to Out and the pre-roll lead-in precedes In. Otherwise it+ * starts at the playhead and runs until stopped. Playback starts `preRoll` seconds before the start; when+ * that would be before 0 the playhead waits at 0 for the difference, so the countdown always lasts the+ * configured time and playback reaches the start exactly when recording begins.+ */+export function resolveRecordPlan(input: RecordPlanInput): RecordPlan {+ const preRoll = clampPreRoll(input.preRoll);+ const range = input.punch ? punchRange(input.markIn, input.markOut) : null;+ const recordStart = range ? range.start : Math.max(0, input.playhead);+ const playFrom = Math.max(0, recordStart - preRoll);+ return {+ punched: range !== null,+ recordStart,+ recordEnd: range ? range.end : null,+ preRoll,+ playFrom,+ playDelay: Math.max(0, preRoll - (recordStart - playFrom)),+ };+}++/** Seconds from "record" until the recorder starts, then how long a punched take runs. */+export function planTimings(plan: RecordPlan): { startAfterMs: number; autoStopAfterMs: number | null } {+ return {+ startAfterMs: Math.round(plan.preRoll * 1000),+ autoStopAfterMs: plan.recordEnd === null ? null : Math.round((plan.recordEnd - plan.recordStart) * 1000),+ };+}++/** Whole seconds shown on the countdown ("3 2 1"); 0 once recording may begin. */+export function countdownSeconds(remainingMs: number): number {+ return remainingMs <= 0 ? 0 : Math.ceil(remainingMs / 1000);+}++/**+ * Where a take lands on the timeline: the planned start moved earlier by the input's reported latency+ * (sound captured at time T reaches the recorder at T + latency), never before 0 or by more than the cap.+ */+export function takeTimelineStart(recordStart: number, inputLatencySeconds: number | undefined): number {+ const latency =+ typeof inputLatencySeconds === "number" && Number.isFinite(inputLatencySeconds)+ ? Math.min(MAX_LATENCY_COMPENSATION_SECONDS, Math.max(0, inputLatencySeconds))+ : 0;+ return Math.max(0, recordStart - latency);+}++const TAKE_NAME = /^Voice Over Take (\d+)(?:\.\w+)?$/;+const LEGACY_NAME = /^Voice-over \d{4}-/;++export function takeName(number: number): string {+ return `Voice Over Take ${number}`;+}++/** Take number parsed from a media name; null for anything that is not a voice-over take. */+export function parseTakeNumber(name: string): number | null {+ const match = TAKE_NAME.exec(name.trim());+ return match ? Number(match[1]) : null;+}++/** True for takes recorded by this panel and for older date-stamped voice-overs. */+export function isVoiceOverMediaName(name: string): boolean {+ return TAKE_NAME.test(name.trim()) || LEGACY_NAME.test(name.trim());+}++/** The next free take number across every media name in the project. */+export function nextTakeNumber(mediaNames: Iterable<string>): number {+ let highest = 0;+ for (const name of mediaNames) {+ const n = parseTakeNumber(name);+ if (n !== null && n > highest) highest = n;+ }+ return highest + 1;+}++interface PlacementClip {+ startTime: number;+ duration: number;+}++export interface PlacementTrack {+ id: string;+ name: string;+ type: string;+ locked: boolean;+ clips: ReadonlyArray<PlacementClip>;+}++/** Unlocked audio tracks a take can be recorded to. */+export function audioTrackChoices<T extends PlacementTrack>(tracks: ReadonlyArray<T>): T[] {+ return tracks.filter((track) => track.type === "audio" && !track.locked);+}++export function rangeOccupied(clips: ReadonlyArray<PlacementClip>, start: number, end: number): boolean {+ return clips.some((clip) => start < clip.startTime + clip.duration - OVERLAP_EPSILON && clip.startTime < end - OVERLAP_EPSILON);+}++export type TakePlacement =+ | { kind: "existing"; trackId: string }+ | { kind: "new"; trackName: string; reason: "requested" | "occupied" | "unavailable" };++/** "Voice Over", then "Voice Over 2", "Voice Over 3"... (the first free name among the project's tracks). */+export function nextVoiceTrackName(tracks: ReadonlyArray<{ name: string }>): string {+ const used = new Set(tracks.map((track) => track.name));+ if (!used.has(VOICE_OVER_TRACK_NAME)) return VOICE_OVER_TRACK_NAME;+ for (let n = 2; ; n++) {+ const candidate = `${VOICE_OVER_TRACK_NAME} ${n}`;+ if (!used.has(candidate)) return candidate;+ }+}++/**+ * Takes stack: a take goes on the chosen track when its time range is free there, otherwise on a new+ * track below, so a re-take never overwrites or overlaps an earlier take.+ */+export function chooseTakeTrack(+ tracks: ReadonlyArray<PlacementTrack>,+ targetTrackId: string,+ start: number,+ end: number,+): TakePlacement {+ const newName = nextVoiceTrackName(tracks);+ if (!targetTrackId) return { kind: "new", trackName: newName, reason: "requested" };+ const target = tracks.find((track) => track.id === targetTrackId);+ if (!target || target.type !== "audio" || target.locked) {+ return { kind: "new", trackName: newName, reason: "unavailable" };+ }+ if (rangeOccupied(target.clips, start, end)) return { kind: "new", trackName: newName, reason: "occupied" };+ return { kind: "existing", trackId: target.id };+}++export interface VoiceOverTake {+ clipId: string;+ trackId: string;+ mediaId: string;+ name: string;+ /** Recording order; null for older date-stamped voice-overs. */+ number: number | null;+ startTime: number;+ duration: number;+}++/** Every voice-over clip in the project, takes in recording order and older recordings by position. */+export function listVoiceOverTakes(+ tracks: ReadonlyArray<{ id: string; clips: ReadonlyArray<{ id: string; mediaId: string; startTime: number; duration: number }> }>,+ mediaNames: ReadonlyMap<string, string>,+): VoiceOverTake[] {+ const takes: VoiceOverTake[] = [];+ for (const track of tracks) {+ for (const clip of track.clips) {+ const name = mediaNames.get(clip.mediaId);+ if (!name || !isVoiceOverMediaName(name)) continue;+ takes.push({+ clipId: clip.id,+ trackId: track.id,+ mediaId: clip.mediaId,+ name: name.replace(/\.\w+$/, ""),+ number: parseTakeNumber(name),+ startTime: clip.startTime,+ duration: clip.duration,+ });+ }+ }+ return takes.sort((a, b) => {+ if (a.number !== null && b.number !== null) return a.number - b.number;+ if (a.number !== null) return 1;+ if (b.number !== null) return -1;+ return a.startTime - b.startTime;+ });+}++/** Peak level 0..1 of 8-bit time-domain samples (128 is silence). */+export function peakLevel(samples: ArrayLike<number>): number {+ let peak = 0;+ for (let i = 0; i < samples.length; i++) {+ const v = Math.abs(samples[i] - 128) / 128;+ if (v > peak) peak = v;+ }+ return Math.min(1, peak);+}++export function selectVoiceOverMimeType(+ supports: (mimeType: string) => boolean,+): { mimeType: string; extension: string } | null {+ const candidates = [+ { mimeType: "audio/webm;codecs=opus", extension: "webm" },+ { mimeType: "audio/mp4", extension: "m4a" },+ { mimeType: "audio/webm", extension: "webm" },+ { mimeType: "audio/ogg;codecs=opus", extension: "ogg" },+ ];+ return candidates.find((candidate) => supports(candidate.mimeType)) ?? null;+}++export function formatClock(milliseconds: number): string {+ const seconds = Math.max(0, Math.floor(milliseconds / 1_000));+ return `${Math.floor(seconds / 60).toString().padStart(2, "0")}:${(seconds % 60).toString().padStart(2, "0")}`;+}diff --git a/apps/web/src/services/voiceover/voiceover-recorder.ts b/apps/web/src/services/voiceover/voiceover-recorder.tsnew file mode 100644index 00000000..98f9054a--- /dev/null+++ b/apps/web/src/services/voiceover/voiceover-recorder.ts@@ -0,0 +1,552 @@+import { create } from "zustand";+import { getRealtimeAudioGraph } from "@openreel/core";+import { useProjectStore } from "../../stores/project-store";+import { useTimelineStore } from "../../stores/timeline-store";+import { useUIStore } from "../../stores/ui-store";+import {+ DEFAULT_VOICE_OVER_PREFS,+ VOICE_OVER_PREFS_KEY,+ chooseTakeTrack,+ clampPreRoll,+ countdownSeconds,+ nextTakeNumber,+ parseVoiceOverPrefs,+ peakLevel,+ planTimings,+ resolveRecordPlan,+ selectVoiceOverMimeType,+ takeName,+ takeTimelineStart,+ type PlacementTrack,+ type RecordPlan,+ type VoiceOverPrefs,+} from "./voiceover-logic";++export type VoiceOverPhase = "idle" | "monitoring" | "countdown" | "recording" | "saving";+export type VoiceOverErrorKind = "unsupported" | "blocked" | "denied" | "no-device" | "failed";++export interface VoiceOverDevice {+ deviceId: string;+ label: string;+}++export interface VoiceOverLastTake {+ clipId: string;+ trackId: string;+ name: string;+ /** Set when the take could not go on the chosen track and was stacked onto a new one. */+ note: string | null;+}++interface VoiceOverState {+ phase: VoiceOverPhase;+ /** Whole seconds left of the pre-roll countdown. */+ countdown: number;+ elapsedMs: number;+ /** Smoothed input peak, 0..1. */+ level: number;+ error: string | null;+ errorKind: VoiceOverErrorKind | null;+ devices: VoiceOverDevice[];+ prefs: VoiceOverPrefs;+ lastTake: VoiceOverLastTake | null;+ setPrefs: (patch: Partial<VoiceOverPrefs>) => void;+ refreshDevices: () => Promise<void>;+ startMonitor: () => Promise<void>;+ stopMonitor: () => void;+ start: () => Promise<void>;+ stop: () => void;+ cancel: () => void;+}++class VoiceOverError extends Error {+ constructor(+ readonly kind: VoiceOverErrorKind,+ message: string,+ ) {+ super(message);+ }+}++interface Runtime {+ stream: MediaStream | null;+ /** The device and echo setting the open stream was created with. */+ streamKey: string;+ recorder: MediaRecorder | null;+ format: { mimeType: string; extension: string } | null;+ chunks: Blob[];+ meter: { context: AudioContext; source: MediaStreamAudioSourceNode; owned: boolean; frame: number } | null;+ plan: RecordPlan | null;+ originalPlayhead: number;+ startedAt: number;+ latency: number | undefined;+ save: boolean;+ tick: number | null;+ playTimer: number | null;+ stopTimer: number | null;+ elapsedTimer: number | null;+ /** Guards against a second start while the first is still opening the device. */+ starting: boolean;+}++const rt: Runtime = {+ stream: null,+ streamKey: "",+ recorder: null,+ format: null,+ chunks: [],+ meter: null,+ plan: null,+ originalPlayhead: 0,+ startedAt: 0,+ latency: undefined,+ save: true,+ tick: null,+ playTimer: null,+ stopTimer: null,+ elapsedTimer: null,+ starting: false,+};++function readStoredPrefs(): VoiceOverPrefs {+ try {+ return parseVoiceOverPrefs(window.localStorage.getItem(VOICE_OVER_PREFS_KEY));+ } catch {+ return { ...DEFAULT_VOICE_OVER_PREFS };+ }+}++function storePrefs(prefs: VoiceOverPrefs): void {+ try {+ window.localStorage.setItem(VOICE_OVER_PREFS_KEY, JSON.stringify(prefs));+ } catch {+ // Remembering the settings is a convenience; recording works without it.+ }+}++function streamKeyFor(prefs: VoiceOverPrefs): string {+ return `${prefs.deviceId}|${prefs.muteDuringRecord ? 1 : 0}`;+}++function clearTimers(): void {+ for (const key of ["tick", "playTimer", "stopTimer", "elapsedTimer"] as const) {+ const handle = rt[key];+ if (handle !== null) {+ window.clearTimeout(handle);+ window.clearInterval(handle);+ rt[key] = null;+ }+ }+}++function stopMeter(): void {+ if (rt.meter) {+ cancelAnimationFrame(rt.meter.frame);+ try {+ rt.meter.source.disconnect();+ } catch {+ // Already disconnected.+ }+ if (rt.meter.owned) void rt.meter.context.close().catch(() => undefined);+ rt.meter = null;+ }+}++function releaseStream(): void {+ rt.stream?.getTracks().forEach((track) => track.stop());+ rt.stream = null;+ rt.streamKey = "";+ rt.recorder = null;+ stopMeter();+ useVoiceOverStore.setState({ level: 0 });+}++/**+ * Meters the live input on the editor's own AudioContext (opening another context per take is slow and can+ * stall on some audio hardware); a private context is only the fallback when the shared one is unavailable.+ */+function startMeter(stream: MediaStream): void {+ stopMeter();+ try {+ let context: AudioContext;+ let owned = false;+ try {+ context = getRealtimeAudioGraph().getAudioContext();+ } catch {+ context = new AudioContext();+ owned = true;+ }+ if (context.state === "suspended") void context.resume().catch(() => undefined);+ const analyser = context.createAnalyser();+ analyser.fftSize = 512;+ const source = context.createMediaStreamSource(stream);+ source.connect(analyser);+ const data = new Uint8Array(analyser.fftSize);+ const state = { context, source, owned, frame: 0 };+ const tick = () => {+ analyser.getByteTimeDomainData(data);+ const previous = useVoiceOverStore.getState().level;+ const next = Math.max(peakLevel(data), previous * 0.85);+ if (Math.abs(next - previous) > 0.01) useVoiceOverStore.setState({ level: next });+ state.frame = requestAnimationFrame(tick);+ };+ state.frame = requestAnimationFrame(tick);+ rt.meter = state;+ } catch {+ // The meter is informational; recording works without it.+ }+}++/** Desktop only: have the OS grant (or explain the refusal of) microphone access before the page asks. */+async function ensureDesktopMicrophone(): Promise<void> {+ const microphone = typeof window !== "undefined" ? window.openreel?.microphone : undefined;+ if (!microphone) return;+ try {+ let status = await microphone.status();+ if (status === "not-determined") status = await microphone.request();+ if (status === "denied" || status === "restricted") {+ throw new VoiceOverError(+ "blocked",+ status === "restricted"+ ? "Microphone access is restricted on this computer by a system policy."+ : "Microphone access is turned off for OpenReel. Allow it in your system privacy settings, then try again.",+ );+ }+ } catch (reason) {+ if (reason instanceof VoiceOverError) throw reason;+ // A bridge failure must not block recording; the browser prompt below still decides.+ }+}++async function openStream(prefs: VoiceOverPrefs): Promise<MediaStream> {+ if (!navigator.mediaDevices?.getUserMedia || typeof MediaRecorder === "undefined") {+ throw new VoiceOverError("unsupported", "Voice-over recording is not supported by this browser.");+ }+ const constraints = (deviceId: string): Parameters<MediaDevices["getUserMedia"]>[0] => ({+ audio: {+ ...(deviceId ? { deviceId: { exact: deviceId } } : {}),+ // Echo cancellation only helps when the timeline is audible on speakers; it colours a clean take.+ echoCancellation: !prefs.muteDuringRecord,+ noiseSuppression: true,+ autoGainControl: true,+ },+ });+ try {+ return await navigator.mediaDevices.getUserMedia(constraints(prefs.deviceId));+ } catch (reason) {+ const name = reason instanceof DOMException ? reason.name : "";+ if (prefs.deviceId && (name === "OverconstrainedError" || name === "NotFoundError")) {+ // The remembered microphone is unplugged: fall back to the system default instead of failing.+ useVoiceOverStore.getState().setPrefs({ deviceId: "" });+ return navigator.mediaDevices.getUserMedia(constraints(""));+ }+ if (name === "NotAllowedError" || name === "SecurityError") {+ throw new VoiceOverError("denied", "Microphone access was denied. Allow it for this site (or in your system privacy settings) and try again.");+ }+ if (name === "NotFoundError" || name === "NotReadableError") {+ throw new VoiceOverError("no-device", name === "NotReadableError" ? "The microphone is in use by another application." : "No microphone was found.");+ }+ throw new VoiceOverError("failed", reason instanceof Error ? reason.message : "Could not start microphone recording.");+ }+}++function fail(reason: unknown): void {+ const kind = reason instanceof VoiceOverError ? reason.kind : "failed";+ useVoiceOverStore.setState({+ error: reason instanceof Error ? reason.message : "Could not start microphone recording.",+ errorKind: kind,+ });+}++function pausePlayback(): void {+ useTimelineStore.getState().pause();+}++function resetToIdle(): void {+ clearTimers();+ rt.plan = null;+ rt.starting = false;+ useVoiceOverStore.setState({ phase: "idle", countdown: 0, elapsedMs: 0 });+}++function beginRecording(): void {+ if (rt.tick !== null) {+ window.clearInterval(rt.tick);+ rt.tick = null;+ }+ const stream = rt.stream;+ const plan = rt.plan;+ if (!stream || !plan) return;+ try {+ const format = rt.format ?? selectVoiceOverMimeType((type) => MediaRecorder.isTypeSupported(type));+ if (!format) throw new VoiceOverError("unsupported", "This browser does not provide a supported microphone recording format.");+ rt.format = format;+ const recorder = new MediaRecorder(stream, { mimeType: format.mimeType, audioBitsPerSecond: 128_000 });+ rt.chunks = [];+ rt.save = true;+ rt.recorder = recorder;+ rt.latency = (stream.getAudioTracks()[0]?.getSettings() as { latency?: number } | undefined)?.latency;+ recorder.ondataavailable = (event) => {+ if (event.data.size > 0) rt.chunks.push(event.data);+ };+ recorder.onerror = () => {+ useVoiceOverStore.setState({ error: "The microphone recording stopped unexpectedly.", errorKind: "failed" });+ };+ recorder.onstop = () => void finishRecording(format);+ rt.startedAt = Date.now();+ recorder.start(250);+ useVoiceOverStore.setState({ phase: "recording", countdown: 0, elapsedMs: 0 });+ rt.elapsedTimer = window.setInterval(() => {+ useVoiceOverStore.setState({ elapsedMs: Date.now() - rt.startedAt });+ }, 100);+ const { autoStopAfterMs } = planTimings(plan);+ if (autoStopAfterMs !== null) rt.stopTimer = window.setTimeout(() => useVoiceOverStore.getState().stop(), autoStopAfterMs);+ } catch (reason) {+ pausePlayback();+ useTimelineStore.getState().seekTo(rt.originalPlayhead);+ releaseStream();+ resetToIdle();+ fail(reason);+ }+}++async function finishRecording(format: { mimeType: string; extension: string }): Promise<void> {+ const shouldSave = rt.save;+ const plan = rt.plan;+ const elapsedSeconds = (Date.now() - rt.startedAt) / 1000;+ const blob = new Blob(rt.chunks, { type: format.mimeType });+ const latency = rt.latency;+ rt.chunks = [];+ clearTimers();+ pausePlayback();+ releaseStream();+ if (!shouldSave || !plan) {+ resetToIdle();+ return;+ }+ useVoiceOverStore.setState({ phase: "saving", elapsedMs: 0 });+ try {+ await saveTake(blob, format.extension, takeTimelineStart(plan.recordStart, latency), elapsedSeconds);+ } catch (reason) {+ fail(reason);+ } finally {+ resetToIdle();+ }+}++/**+ * Imports the recording as media named "Voice Over Take N" and places it as an ordinary audio clip on the+ * chosen track (or a new "Voice Over" track when that range is taken). The track creation, rename and clip+ * add are one history group, so a single undo removes the whole take.+ */+export async function saveTake(blob: Blob, extension: string, startTime: number, durationHint: number): Promise<void> {+ if (blob.size === 0) throw new Error("The microphone recording was empty.");+ const store = useProjectStore.getState();+ const name = takeName(nextTakeNumber(store.project.mediaLibrary.items.map((item) => item.name)));+ const before = new Set(store.project.mediaLibrary.items.map((item) => item.id));+ const file = new File([blob], `${name}.${extension}`, { type: blob.type, lastModified: Date.now() });+ const imported = await store.importMedia(file);+ if (!imported.success) throw new Error(imported.error?.message ?? "Could not import the recording.");+ const media = useProjectStore.getState().project.mediaLibrary.items.find((item) => !before.has(item.id));+ if (!media) throw new Error("The recorded audio could not be found after import.");++ const prefs = useVoiceOverStore.getState().prefs;+ const duration = media.metadata.duration > 0 ? media.metadata.duration : durationHint;+ const tracks = useProjectStore.getState().project.timeline.tracks as unknown as PlacementTrack[];+ const placement = chooseTakeTrack(tracks, prefs.targetTrackId, startTime, startTime + duration);++ const history = useProjectStore.getState().actionExecutor.getHistory();+ history.beginGroup("Record voice-over");+ let clipTrackId: string | null = null;+ try {+ const api = useProjectStore.getState();+ if (placement.kind === "existing") {+ const result = await api.addClip(placement.trackId, media.id, startTime);+ if (!result.success) throw new Error(result.error?.message ?? "Could not add the voice-over to the timeline.");+ clipTrackId = placement.trackId;+ } else {+ const result = await api.addClipToNewTrack(media.id, startTime);+ if (!result.success) throw new Error(result.error?.message ?? "Could not add the voice-over to the timeline.");+ const created = useProjectStore.getState().project.timeline.tracks.find((track) => track.clips.some((clip) => clip.mediaId === media.id));+ if (created) {+ clipTrackId = created.id;+ await useProjectStore.getState().renameTrack(created.id, placement.trackName);+ }+ }+ // The imported media carries the file's extension; show the clean take name instead.+ await useProjectStore.getState().renameMedia(media.id, name);+ } finally {+ history.endGroup();+ }+ const track = clipTrackId ? useProjectStore.getState().project.timeline.tracks.find((t) => t.id === clipTrackId) : undefined;+ const clip = track?.clips.find((c) => c.mediaId === media.id);+ if (track && clip) {+ useUIStore.getState().select({ type: "clip", id: clip.id, trackId: track.id });+ useVoiceOverStore.setState({+ lastTake: {+ clipId: clip.id,+ trackId: track.id,+ name,+ note:+ placement.kind === "new" && placement.reason === "occupied"+ ? `That range was already recorded, so ${name} was stacked on a new track.`+ : placement.kind === "new" && placement.reason === "unavailable"+ ? `The chosen track was not available, so ${name} went on a new track.`+ : null,+ },+ });+ }+}++export const useVoiceOverStore = create<VoiceOverState>((set, get) => ({+ phase: "idle",+ countdown: 0,+ elapsedMs: 0,+ level: 0,+ error: null,+ errorKind: null,+ devices: [],+ prefs: readStoredPrefs(),+ lastTake: null,++ setPrefs: (patch) => {+ const next: VoiceOverPrefs = { ...get().prefs, ...patch };+ next.preRoll = clampPreRoll(next.preRoll);+ storePrefs(next);+ set({ prefs: next });+ // A level check holds the old device open: reopen it so the meter and the take use the new choice.+ if (get().phase === "monitoring" && !rt.starting && rt.streamKey !== streamKeyFor(next)) {+ get().stopMonitor();+ void get().startMonitor();+ }+ },++ refreshDevices: async () => {+ const media = typeof navigator !== "undefined" ? navigator.mediaDevices : undefined;+ if (!media?.enumerateDevices) return;+ try {+ const list = await media.enumerateDevices();+ set({+ devices: list+ .filter((device) => device.kind === "audioinput" && device.deviceId && device.deviceId !== "communications" && device.deviceId !== "default")+ .map((device, index) => ({ deviceId: device.deviceId, label: device.label || `Microphone ${index + 1}` })),+ });+ } catch {+ // Listing devices is best-effort.+ }+ },++ startMonitor: async () => {+ if (get().phase !== "idle" || rt.starting) return;+ rt.starting = true;+ set({ error: null, errorKind: null });+ try {+ await ensureDesktopMicrophone();+ rt.stream = await openStream(get().prefs);+ rt.streamKey = streamKeyFor(get().prefs);+ startMeter(rt.stream);+ set({ phase: "monitoring" });+ void get().refreshDevices();+ } catch (reason) {+ releaseStream();+ fail(reason);+ } finally {+ rt.starting = false;+ }+ },++ stopMonitor: () => {+ if (get().phase !== "monitoring") return;+ releaseStream();+ set({ phase: "idle" });+ },++ start: async () => {+ const phase = get().phase;+ if ((phase !== "idle" && phase !== "monitoring") || rt.starting) return;+ rt.starting = true;+ set({ error: null, errorKind: null, lastTake: null });+ try {+ if (rt.stream && rt.streamKey !== streamKeyFor(get().prefs)) releaseStream();+ if (!rt.stream || phase === "idle") {+ await ensureDesktopMicrophone();+ rt.stream = await openStream(get().prefs);+ rt.streamKey = streamKeyFor(get().prefs);+ startMeter(rt.stream);+ void get().refreshDevices();+ }+ if (!selectVoiceOverMimeType((type) => MediaRecorder.isTypeSupported(type))) {+ throw new VoiceOverError("unsupported", "This browser does not provide a supported microphone recording format.");+ }+ const timeline = useTimelineStore.getState();+ const { prefs } = get();+ const plan = resolveRecordPlan({+ playhead: timeline.playheadPosition,+ preRoll: prefs.preRoll,+ punch: prefs.punch,+ markIn: timeline.loopStart,+ markOut: timeline.loopEnd,+ });+ rt.plan = plan;+ rt.originalPlayhead = timeline.playheadPosition;+ timeline.pause();+ timeline.seekTo(plan.playFrom);+ const { startAfterMs } = planTimings(plan);+ const startedAt = performance.now();+ set({ phase: "countdown", countdown: countdownSeconds(startAfterMs), elapsedMs: 0 });+ // Playback runs through the pre-roll so the narrator hears the lead-in, arriving at the start as recording begins.+ rt.playTimer = window.setTimeout(() => useTimelineStore.getState().play(), Math.round(plan.playDelay * 1000));+ if (startAfterMs <= 0) {+ beginRecording();+ } else {+ rt.tick = window.setInterval(() => {+ const remaining = startAfterMs - (performance.now() - startedAt);+ if (remaining <= 0) beginRecording();+ else set({ countdown: countdownSeconds(remaining) });+ }, 50);+ }+ } catch (reason) {+ releaseStream();+ resetToIdle();+ fail(reason);+ } finally {+ rt.starting = false;+ }+ },++ stop: () => {+ const { phase } = get();+ if (phase === "countdown") {+ get().cancel();+ return;+ }+ if (phase !== "recording") return;+ if (rt.stopTimer !== null) {+ window.clearTimeout(rt.stopTimer);+ rt.stopTimer = null;+ }+ rt.save = true;+ if (rt.recorder && rt.recorder.state !== "inactive") rt.recorder.stop();+ },++ cancel: () => {+ const { phase } = get();+ if (phase === "recording") {+ rt.save = false;+ if (rt.recorder && rt.recorder.state !== "inactive") rt.recorder.stop();+ useTimelineStore.getState().seekTo(rt.originalPlayhead);+ return;+ }+ if (phase !== "countdown") return;+ clearTimers();+ pausePlayback();+ useTimelineStore.getState().seekTo(rt.originalPlayhead);+ releaseStream();+ resetToIdle();+ },+}));++/** True while timeline playback must be silent: recording with "mute playback while recording" on. */+export function selectVoiceOverPlaybackMuted(state: Pick<VoiceOverState, "phase" | "prefs">): boolean {+ return state.phase === "recording" && state.prefs.muteDuringRecord;+}diff --git a/apps/web/src/services/white-balance-eyedropper.test.ts b/apps/web/src/services/white-balance-eyedropper.test.tsnew file mode 100644index 00000000..3aa3d700--- /dev/null+++ b/apps/web/src/services/white-balance-eyedropper.test.ts@@ -0,0 +1,119 @@+import "../test/install-local-storage-mock";+import { beforeEach, describe, expect, it, vi } from "vitest";+import type { Clip } from "@openreel/core";+import { applyWhiteBalance } from "@openreel/core";+import { useProjectStore } from "../stores/project-store";+import { useTimelineStore } from "../stores/timeline-store";+import { applyWhiteBalancePick, clipNeedsWhiteBalanceInputFrame, previewWhiteBalancePick } from "./white-balance-eyedropper";++vi.mock("../bridges/effects-bridge", async (importOriginal) => ({+ ...(await importOriginal<typeof import("../bridges/effects-bridge")>()),+ getEffectsBridge: () => ({ isInitialized: () => false }),+}));++const clip: Clip = {+ id: "wb",+ mediaId: "media",+ trackId: "main",+ startTime: 2,+ duration: 4,+ inPoint: 0,+ outPoint: 4,+ volume: 1,+ effects: [],+ audioEffects: [],+ keyframes: [],+ colorGrading: { temperature: 20, tint: -5 },+ transform: { position: { x: 0, y: 0 }, scale: { x: 1, y: 1 }, anchor: { x: 0.5, y: 0.5 }, opacity: 1, rotation: 0 },+};+const current = () => useProjectStore.getState().getClip(clip.id)!;+const historySize = () => useProjectStore.getState().actionExecutor.getHistory().getUndoStackSize();++function load(next: Clip): void {+ useProjectStore.getState().createNewProject("WB eyedropper");+ const project = useProjectStore.getState().project;+ useProjectStore.setState({+ project: {+ ...project,+ timeline: {+ ...project.timeline,+ duration: 8,+ tracks: [+ { id: "main", name: "Main", type: "video", clips: [structuredClone(next)], transitions: [], locked: false, hidden: false, muted: false, solo: false },+ ],+ },+ },+ });+ useTimelineStore.setState({ playheadPosition: 3 });+}++beforeEach(() => load(clip));++describe("White balance eyedropper service", () => {+ it("replaces Temperature and Tint in one undoable step and the picked sample ends up neutral", async () => {+ // What the monitor shows: a neutral-ish source cast by the clip's current 20 / -5.+ const source: [number, number, number] = [0.5, 0.46, 0.41];+ const shown = applyWhiteBalance(source, 20, -5);+ const before = historySize();+ const result = await applyWhiteBalancePick(clip.id, shown);+ expect(result.ok).toBe(true);+ expect(historySize()).toBe(before + 1);+ const grade = current().colorGrading!;+ const after = applyWhiteBalance(source, grade.temperature!, grade.tint!);+ expect(Math.max(...after) - Math.min(...after)).toBeLessThan(1 / 255);++ await useProjectStore.getState().undo();+ expect(current().colorGrading).toMatchObject({ temperature: 20, tint: -5 });+ });++ it("keeps the rest of the grade", async () => {+ load({ ...clip, colorGrading: { temperature: 0, tint: 0, pipelineVersion: 2, tone: { exposure: 0.2, contrast: 0, highlights: 0, shadows: 0, whites: 0, blacks: 0 } } });+ await applyWhiteBalancePick(clip.id, [0.6, 0.5, 0.4]);+ expect(current().colorGrading?.tone?.exposure).toBe(0.2);+ expect(current().colorGrading?.temperature).toBeLessThan(0);+ });++ it("refuses unusable samples, a playhead off the clip, and keyframed white balance without writing", async () => {+ const before = historySize();+ expect(await applyWhiteBalancePick(clip.id, [1, 1, 1])).toEqual({ ok: false, reason: "unusable-sample" });+ expect(await applyWhiteBalancePick(clip.id, null)).toEqual({ ok: false, reason: "no-frame" });+ useTimelineStore.setState({ playheadPosition: 7 });+ expect(previewWhiteBalancePick(clip.id, [0.5, 0.5, 0.4])).toEqual({ ok: false, reason: "outside-clip" });+ useTimelineStore.setState({ playheadPosition: 3 });+ expect(historySize()).toBe(before);+ load({ ...clip, keyframes: [{ id: "k", property: "colorGrade.temperature", time: 0, value: 10, easing: "linear" }] });+ const keyedBefore = historySize();+ expect(await applyWhiteBalancePick(clip.id, [0.5, 0.5, 0.4])).toEqual({ ok: false, reason: "keyframed" });+ expect(historySize()).toBe(keyedBefore);+ });++ it("refuses a clip that no longer exists", () => {+ expect(previewWhiteBalancePick("missing", [0.5, 0.5, 0.5])).toEqual({ ok: false, reason: "no-clip" });+ });++ it("treats an input-frame sample as already free of the clip's white balance", () => {+ const sample: [number, number, number] = [0.55, 0.5, 0.45];+ const displayed = previewWhiteBalancePick(clip.id, sample, false);+ const input = previewWhiteBalancePick(clip.id, sample, true);+ expect(input.ok && displayed.ok && input.solution.temperature !== displayed.solution.temperature).toBe(true);+ // Solved from zero: applying the result to the sample neutralises it.+ if (input.ok) {+ const after = applyWhiteBalance(sample, input.solution.temperature, input.solution.tint);+ expect(Math.max(...after) - Math.min(...after)).toBeLessThan(1 / 255);+ }+ });++ it("flags strongly coloured samples without blocking the pick", () => {+ const brown = previewWhiteBalancePick(clip.id, [31 / 255, 22 / 255, 14 / 255], true);+ expect(brown.ok && brown.farFromNeutral).toBe(true);+ const wall = previewWhiteBalancePick(clip.id, [0.55, 0.5, 0.45], true);+ expect(wall.ok && wall.farFromNeutral).toBe(false);+ });++ it("needs the stage input frame when later grade stages follow white balance", () => {+ load({ ...clip, colorGrading: { pipelineVersion: 2, tone: { exposure: 0, contrast: 60, highlights: 0, shadows: 0, whites: 0, blacks: 0 } } });+ expect(clipNeedsWhiteBalanceInputFrame(clip.id)).toBe(true);+ load({ ...clip, colorGrading: { pipelineVersion: 2 } });+ expect(clipNeedsWhiteBalanceInputFrame(clip.id)).toBe(false);+ });+});diff --git a/apps/web/src/services/white-balance-eyedropper.ts b/apps/web/src/services/white-balance-eyedropper.tsnew file mode 100644index 00000000..c3591a69--- /dev/null+++ b/apps/web/src/services/white-balance-eyedropper.ts@@ -0,0 +1,144 @@+/**+ * White Balance eyedropper: reads the Program monitor under the cursor and+ * turns the sample into Temperature / Tint for one clip.+ *+ * The Program canvas is read directly (the same source the scopes use), so+ * the WebGL and Canvas2D paths behave identically. The clip's current white+ * balance is removed from the sample before solving, so the result replaces+ * the sliders instead of stacking on them. The pick is one+ * `clip/setColorGrading` action: a single undo step.+ */+import {+ evaluateKeyframesAt,+ isFarFromNeutral,+ isNeutralColorGrading,+ isUsableWhiteBalanceSample,+ needsWhiteBalanceInputFrame,+ sampleAverageRgb,+ solveNeutralWhiteBalance,+ whiteBalanceSampleRadius,+ type WhiteBalanceSampleSize,+ type WhiteBalanceSolution,+} from "@openreel/core";+import { useProjectStore } from "../stores/project-store";+import { useTimelineStore } from "../stores/timeline-store";++export type WhiteBalancePickResult =+ | { ok: true; solution: WhiteBalanceSolution; farFromNeutral: boolean }+ | { ok: false; reason: "no-frame" | "unusable-sample" | "no-clip" | "outside-clip" | "keyframed" };++/** Average colour (0..1) of the `size` footprint centred on canvas pixel (x, y). Reads only that window. */+export function readCanvasSample(+ source: HTMLCanvasElement | ImageBitmap | OffscreenCanvas,+ x: number,+ y: number,+ size: WhiteBalanceSampleSize,+): [number, number, number] | null {+ if (source.width === 0 || source.height === 0) return null;+ const radius = whiteBalanceSampleRadius(size);+ const cx = Math.min(source.width - 1, Math.max(0, Math.floor(x)));+ const cy = Math.min(source.height - 1, Math.max(0, Math.floor(y)));+ const sx = Math.max(0, cx - radius);+ const sy = Math.max(0, cy - radius);+ const w = Math.min(source.width, cx + radius + 1) - sx;+ const h = Math.min(source.height, cy + radius + 1) - sy;+ const scratch = document.createElement("canvas");+ scratch.width = w;+ scratch.height = h;+ const ctx = scratch.getContext("2d", { willReadFrequently: true });+ if (!ctx) return null;+ ctx.drawImage(source, sx, sy, w, h, 0, 0, w, h);+ const image = ctx.getImageData(0, 0, w, h);+ return sampleAverageRgb(image.data, w, h, cx - sx, cy - sy, radius);+}++interface ClipWhiteBalanceState {+ temperature: number;+ tint: number;+ keyframed: boolean;+}++function clipWhiteBalance(clipId: string): ClipWhiteBalanceState | null {+ const clip = useProjectStore.getState().getClip(clipId);+ if (!clip) return null;+ const keys = clip.keyframes ?? [];+ const keyframed = keys.some(+ (key) => key.property === "colorGrade.temperature" || key.property === "colorGrade.tint",+ );+ const sampled = keyframed+ ? evaluateKeyframesAt(keys, Math.max(0, useTimelineStore.getState().playheadPosition - clip.startTime))+ : null;+ return {+ temperature: sampled?.get("colorGrade.temperature") ?? clip.colorGrading?.temperature ?? 0,+ tint: sampled?.get("colorGrade.tint") ?? clip.colorGrading?.tint ?? 0,+ keyframed,+ };+}++/** True when the playhead is over the clip, so the Program frame shows it. */+export function playheadOverClip(clipId: string): boolean {+ const clip = useProjectStore.getState().getClip(clipId);+ if (!clip) return false;+ const head = useTimelineStore.getState().playheadPosition;+ return head >= clip.startTime && head <= clip.startTime + clip.duration;+}++/**+ * True when the displayed Program pixel differs from the white balance stage+ * input (a version 2 clip with later grade stages, or any active white+ * balance), so the pick must sample a transient render of that input.+ */+export function clipNeedsWhiteBalanceInputFrame(clipId: string): boolean {+ const grading = useProjectStore.getState().getClip(clipId)?.colorGrading;+ if (!grading) return false;+ // The clip stores LUTs as JSON; only the neutral/non-neutral decision is needed here.+ return needsWhiteBalanceInputFrame(grading, (g) =>+ isNeutralColorGrading(g as unknown as Parameters<typeof isNeutralColorGrading>[0]),+ );+}++/**+ * What the sliders would become for this sample, without changing the project.+ * `inputFrame` says the sample already is the white balance stage input, so no+ * current white balance is removed from it.+ */+export function previewWhiteBalancePick(+ clipId: string,+ sample: [number, number, number] | null,+ inputFrame = false,+): WhiteBalancePickResult {+ const state = clipWhiteBalance(clipId);+ if (!state) return { ok: false, reason: "no-clip" };+ if (state.keyframed) return { ok: false, reason: "keyframed" };+ if (!playheadOverClip(clipId)) return { ok: false, reason: "outside-clip" };+ if (!sample) return { ok: false, reason: "no-frame" };+ if (!isUsableWhiteBalanceSample(sample)) return { ok: false, reason: "unusable-sample" };+ const solution = solveNeutralWhiteBalance(sample, inputFrame ? {} : state);+ return solution ? { ok: true, solution, farFromNeutral: isFarFromNeutral(sample) } : { ok: false, reason: "unusable-sample" };+}++/** Commit a pick as one undoable action. */+export async function applyWhiteBalancePick(+ clipId: string,+ sample: [number, number, number] | null,+ inputFrame = false,+): Promise<WhiteBalancePickResult> {+ const result = previewWhiteBalancePick(clipId, sample, inputFrame);+ if (!result.ok) return result;+ const saved = await useProjectStore.getState().updateColorGrading(clipId, {+ temperature: result.solution.temperature,+ tint: result.solution.tint,+ });+ return saved ? result : { ok: false, reason: "no-clip" };+}++export const WHITE_BALANCE_PICK_MESSAGES: Record<+ Exclude<WhiteBalancePickResult, { ok: true }>["reason"],+ string+> = {+ "no-frame": "The Program monitor has no frame to sample yet.",+ "unusable-sample": "That pixel is pure black or white. Pick a neutral grey or white area that is not clipped.",+ "no-clip": "The clip is no longer available.",+ "outside-clip": "Move the playhead over the clip, then pick a neutral area.",+ keyframed: "Temperature or Tint is keyframed on this clip. Remove the keyframes or edit them at the playhead.",+};diff --git a/apps/web/src/stores/audio-channels-store.ts b/apps/web/src/stores/audio-channels-store.tsnew file mode 100644index 00000000..18c2e0ec--- /dev/null+++ b/apps/web/src/stores/audio-channels-store.ts@@ -0,0 +1,16 @@+import { create } from "zustand";++/** Which clips the Modify > Audio Channels dialog is editing (empty + closed = not shown). */+interface AudioChannelsDialogState {+ open: boolean;+ clipIds: readonly string[];+ openFor: (clipIds: readonly string[]) => void;+ close: () => void;+}++export const useAudioChannelsStore = create<AudioChannelsDialogState>((set) => ({+ open: false,+ clipIds: [],+ openFor: (clipIds) => set({ open: clipIds.length > 0, clipIds: [...clipIds] }),+ close: () => set({ open: false }),+}));diff --git a/apps/web/src/stores/clip-speed-dialog-store.ts b/apps/web/src/stores/clip-speed-dialog-store.tsnew file mode 100644index 00000000..473eea7f--- /dev/null+++ b/apps/web/src/stores/clip-speed-dialog-store.ts@@ -0,0 +1,12 @@+import { create } from "zustand";++/** Open state of the Clip > Speed/Duration dialog. */+interface ClipSpeedDialogState {+ open: boolean;+ setOpen: (open: boolean) => void;+}++export const useClipSpeedDialogStore = create<ClipSpeedDialogState>((set) => ({+ open: false,+ setOpen: (open) => set({ open }),+}));diff --git a/apps/web/src/stores/color-monitor-store.test.ts b/apps/web/src/stores/color-monitor-store.test.tsindex 8d8abc70..8efacb51 100644--- a/apps/web/src/stores/color-monitor-store.test.ts+++ b/apps/web/src/stores/color-monitor-store.test.ts@@ -8,6 +8,9 @@ const reset = () =>secondary: { clipId: null, effectId: null, matteView: 0, eyedropper: null },captureBusy: false,referenceRevision: 0,+ whiteBalancePick: null,+ whiteBalanceSize: 5,+ keyPicker: null,});describe("color monitor store", () => {@@ -41,4 +44,42 @@ describe("color monitor store", () => {expect(stills).toHaveLength(12);expect(stills[0].id).toBe("s3");});++ it("arming the white balance eyedropper disarms the secondary one and vice versa", () => {+ const store = useColorMonitorStore.getState();+ store.setSecondaryView({ clipId: "c", effectId: "e", eyedropper: "set" });+ store.setWhiteBalancePick({ clipId: "c" });+ expect(useColorMonitorStore.getState().secondary.eyedropper).toBeNull();+ expect(useColorMonitorStore.getState().whiteBalancePick).toEqual({ clipId: "c" });+ store.setSecondaryView({ eyedropper: "add" });+ expect(useColorMonitorStore.getState().whiteBalancePick).toBeNull();+ store.setWhiteBalancePick({ clipId: "c" });+ store.setSecondaryView({ matteView: 2 });+ expect(useColorMonitorStore.getState().whiteBalancePick).toEqual({ clipId: "c" });+ store.setWhiteBalanceSize(1);+ expect(useColorMonitorStore.getState().whiteBalanceSize).toBe(1);+ });++ it("arming any one of the Ultra Key picker, White Balance and Secondary eyedroppers disarms the others", () => {+ const get = () => useColorMonitorStore.getState();+ const key = { clipId: "c", effectId: "e" };+ get().setKeyPicker(key);+ get().setWhiteBalancePick({ clipId: "c" });+ expect(get().keyPicker).toBeNull();+ expect(get().whiteBalancePick).toEqual({ clipId: "c" });++ get().setSecondaryView({ clipId: "c", effectId: "s", eyedropper: "add" });+ expect(get().whiteBalancePick).toBeNull();+ expect(get().keyPicker).toBeNull();++ get().setKeyPicker(key);+ expect(get().keyPicker).toEqual(key);+ expect(get().secondary.eyedropper).toBeNull();+ expect(get().whiteBalancePick).toBeNull();++ get().setKeyPicker(null);+ get().setWhiteBalancePick({ clipId: "c" });+ get().setWhiteBalancePick(null);+ expect(get().keyPicker).toBeNull();+ });});diff --git a/apps/web/src/stores/color-monitor-store.ts b/apps/web/src/stores/color-monitor-store.tsindex 7c1d3792..04c5feb7 100644--- a/apps/web/src/stores/color-monitor-store.ts+++ b/apps/web/src/stores/color-monitor-store.ts@@ -1,5 +1,5 @@import { create } from "zustand";-import type { EyedropperMode } from "@openreel/core";+import type { EyedropperMode, WhiteBalanceSampleSize } from "@openreel/core";export type ComparisonMode = "off" | "side" | "split-v" | "split-h";export type ComparisonReference = "still" | "bypass" | "playhead";@@ -34,7 +34,27 @@ export interface SecondaryViewState {eyedropper: EyedropperMode | null;}+/** White Balance eyedropper armed on the Program monitor for one clip. */+export interface WhiteBalancePick {+ clipId: string;+}++/** An armed Ultra Key colour picker: the next click on the Program monitor sets this effect's key colour. */+export interface KeyPickerState {+ clipId: string;+ effectId: string;+}+interface ColorMonitorStore {+ /** Ultra Key eyedropper; while armed the effect shows its source so the pick reads the unkeyed frame. */+ keyPicker: KeyPickerState | null;+ setKeyPicker: (picker: KeyPickerState | null) => void;+ /** Armed White Balance eyedropper, or null. Mutually exclusive with the Secondary eyedropper and the Ultra Key picker. */+ whiteBalancePick: WhiteBalancePick | null;+ /** Sample footprint: a single pixel or a 5x5 average. */+ whiteBalanceSize: WhiteBalanceSampleSize;+ setWhiteBalancePick: (pick: WhiteBalancePick | null) => void;+ setWhiteBalanceSize: (size: WhiteBalanceSampleSize) => void;comparison: ComparisonState;stills: StillEntry[];secondary: SecondaryViewState;@@ -70,6 +90,28 @@ const SECONDARY_DEFAULT: SecondaryViewState = {};export const useColorMonitorStore = create<ColorMonitorStore>((set) => ({+ whiteBalancePick: null,+ whiteBalanceSize: 5,+ setWhiteBalancePick: (pick) =>+ set((state) => ({+ whiteBalancePick: pick,+ keyPicker: pick ? null : state.keyPicker,+ secondary:+ pick && state.secondary.eyedropper+ ? { ...state.secondary, eyedropper: null }+ : state.secondary,+ })),+ setWhiteBalanceSize: (size) => set({ whiteBalanceSize: size }),+ keyPicker: null,+ setKeyPicker: (picker) =>+ set((state) => ({+ keyPicker: picker,+ whiteBalancePick: picker ? null : state.whiteBalancePick,+ secondary:+ picker && state.secondary.eyedropper+ ? { ...state.secondary, eyedropper: null }+ : state.secondary,+ })),comparison: COMPARISON_DEFAULT,stills: [],secondary: SECONDARY_DEFAULT,@@ -106,7 +148,11 @@ export const useColorMonitorStore = create<ColorMonitorStore>((set) => ({: state.comparison,})),setSecondaryView: (patch) =>- set((state) => ({ secondary: { ...state.secondary, ...patch } })),+ set((state) => ({+ secondary: { ...state.secondary, ...patch },+ whiteBalancePick: patch.eyedropper ? null : state.whiteBalancePick,+ keyPicker: patch.eyedropper ? null : state.keyPicker,+ })),setCaptureBusy: (busy) => set({ captureBusy: busy }),bumpReference: () => set((state) => ({ referenceRevision: state.referenceRevision + 1 })),}));diff --git a/apps/web/src/stores/editor-workspace-store.ts b/apps/web/src/stores/editor-workspace-store.tsindex 7a8e9d3b..7f3440c6 100644--- a/apps/web/src/stores/editor-workspace-store.ts+++ b/apps/web/src/stores/editor-workspace-store.ts@@ -56,6 +56,9 @@ export const useEditorWorkspaceStore = create<{setLinkedSelection: (enabled: boolean) => void;section: AssetSection;setSection: (section: AssetSection) => void;+ /** Markers panel view: sequence markers, or the clip / master-clip markers of timeline clips. */+ markerScope: "sequence" | "clips";+ setMarkerScope: (scope: "sequence" | "clips") => void;/** Marker the Markers panel should open for inline editing (set by Edit Marker / M twice). */editingMarkerId: string | null;setEditingMarkerId: (id: string | null) => void;@@ -108,6 +111,8 @@ export const useEditorWorkspaceStore = create<{setLinkedSelection: (linkedSelection) => set({ linkedSelection }),section: "media",setSection: (section) => set({ section }),+ markerScope: "sequence",+ setMarkerScope: (markerScope) => set({ markerScope }),editingMarkerId: null,setEditingMarkerId: (editingMarkerId) => set({ editingMarkerId }),selectedMarkerId: null,diff --git a/apps/web/src/stores/export-queue-store.test.ts b/apps/web/src/stores/export-queue-store.test.tsindex e69246af..e0c2e7c4 100644--- a/apps/web/src/stores/export-queue-store.test.ts+++ b/apps/web/src/stores/export-queue-store.test.ts@@ -9,6 +9,7 @@ const hoisted = vi.hoisted(() => ({reject: (error: unknown) => void;isCancelled: () => boolean;onProgress: (p: number, phase: string) => void;+ encoder?: string;}>,persisted: { current: null as unknown },cancelEngine: vi.fn(),@@ -43,6 +44,7 @@ vi.mock("../services/export-queue/export-queue-runner", () => {job: { id: string },project: unknown,hooks: { isCancelled: () => boolean; onProgress: (p: number, phase: string) => void },+ encoder?: string,) =>new Promise((resolve, reject) => {hoisted.runs.push({@@ -52,6 +54,7 @@ vi.mock("../services/export-queue/export-queue-runner", () => {reject,isCancelled: hooks.isCancelled,onProgress: hooks.onProgress,+ encoder,});}),};@@ -256,6 +259,39 @@ describe("export queue store", () => {expect(status()).toEqual(["A:completed"]);});+ it("re-runs on the software encoder with progress and ETA reset, in the same single job row", async () => {+ vi.spyOn(console, "warn").mockImplementation(() => undefined);+ useExportQueueStore.getState().enqueue({ settings, presetLabel: "A" });+ useExportQueueStore.getState().start();+ await flush();+ expect(hoisted.runs[0].encoder).toBe("prefer-hardware");+ hoisted.runs[0].onProgress(0.9, "Encoding");+ expect(useExportQueueStore.getState().queue.jobs[0].progress).toBe(0.9);+ hoisted.runs[0].reject(new DOMException("Encoding error.", "EncodingError"));+ await new Promise((resolve) => setTimeout(resolve, 700));+ expect(hoisted.runs).toHaveLength(2);+ expect(hoisted.runs[1].encoder).toBe("prefer-software");+ expect(useExportQueueStore.getState().queue.jobs).toHaveLength(1);+ expect(useExportQueueStore.getState().queue.jobs[0]).toMatchObject({ progress: 0, status: "running", phase: "Preparing" });+ hoisted.runs[1].onProgress(0.2, "Rendering");+ expect(useExportQueueStore.getState().queue.jobs[0].progress).toBe(0.2);+ hoisted.runs[1].resolve(done);+ await flush();+ expect(status()).toEqual(["A:completed"]);+ });++ it("does not retry an explicit Hardware choice and fails right away with a clear message", async () => {+ vi.spyOn(console, "warn").mockImplementation(() => undefined);+ useExportQueueStore.getState().enqueue({ settings: { ...settings, encoderChoice: "hardware" }, presetLabel: "A" });+ useExportQueueStore.getState().start();+ await flush();+ hoisted.runs[0].reject(new DOMException("Encoding error.", "EncodingError"));+ await new Promise((resolve) => setTimeout(resolve, 700));+ expect(hoisted.runs).toHaveLength(1);+ expect(status()).toEqual(["A:failed"]);+ expect(useExportQueueStore.getState().queue.jobs[0].error).toMatch(/hardware encoder failed.*not retried in software/i);+ });+it("cancels a running job (the runner sees it and the engine is told) and moves on", async () => {const store = useExportQueueStore.getState();store.enqueue({ settings, presetLabel: "A" });diff --git a/apps/web/src/stores/export-queue-store.ts b/apps/web/src/stores/export-queue-store.tsindex 8c716c51..7dcace26 100644--- a/apps/web/src/stores/export-queue-store.ts+++ b/apps/web/src/stores/export-queue-store.ts@@ -16,6 +16,7 @@ import {isStemsJob,removeExportJob,reportExportProgress,+ resetExportProgress,retryExportJob,setExportQueuePaused,startExportJob,@@ -32,7 +33,7 @@ import { extForFormat } from "../services/export-runner";import { renderCacheService } from "../services/render-cache-service";import { ExportJobCancelled, cancelRunningExportJob, runExportJob } from "../services/export-queue/export-queue-runner";import { cancelRunningStemsJob, runStemsJob } from "../services/export-queue/stems-job-runner";-import { runWithEncoderRetry } from "../services/export-queue/transient-encoder-error";+import { canRetryInSoftware, hardwareEncoderFailureMessage, isTransientEncoderError, runWithEncoderRetry } from "../services/export-queue/transient-encoder-error";import { isExportQueueRunning, setExportQueueRunning } from "../services/export-queue/export-queue-activity";import {deleteBrowserOutput,@@ -176,7 +177,7 @@ export const useExportQueueStore = create<ExportQueueStore>((set, get) => {let project = snapshots.get(job.id) ?? null;let lastReport = 0;// Wall-clock ETA that counts down, converges and stays hidden until it means something.- const estimator = new ProgressEstimator(Date.now);+ let estimator = new ProgressEstimator(Date.now);estimator.start();try {project ??= await loadSnapshot(job.id);@@ -199,8 +200,28 @@ export const useExportQueueStore = create<ExportQueueStore>((set, get) => {const result = isStemsJob(fresh)? { ...(await runStemsJob(fresh, project, hooks)), framesFromCache: undefined, smartRender: undefined, sourceMedia: undefined }: {- // A transient encoder failure (reclaimed/failed session under load) is retried once before it is shown.- ...(await runWithEncoderRetry(() => runExportJob(fresh, project!, hooks), { shouldRetry: () => !hooks.isCancelled() })),+ // A transient encoder failure (reclaimed session, or a hardware encoder that could not be opened, as on+ // machines and VMs without a video encode accelerator) is retried once, on the software encoder.+ ...(await runWithEncoderRetry(+ (attempt) => {+ if (attempt > 1) {+ // The re-run starts over: drop the failed attempt's progress, phase and ETA so the bar and the+ // background-task row count up again instead of freezing at the old value.+ estimator = new ProgressEstimator(Date.now);+ estimator.start();+ lastReport = 0;+ apply((s) => resetExportProgress(s, job.id, Date.now()), true);+ }+ return runExportJob(fresh, project!, hooks, attempt === 1 ? "prefer-hardware" : "prefer-software");+ },+ { shouldRetry: () => !hooks.isCancelled() && canRetryInSoftware(fresh.settings.encoderChoice) },+ ).catch((error: unknown) => {+ // An explicit Hardware choice cannot fall back, so a re-run would repeat the failure: say so right away.+ if (!canRetryInSoftware(fresh.settings.encoderChoice) && isTransientEncoderError(error) && !hooks.isCancelled()) {+ throw new Error(hardwareEncoderFailureMessage(error));+ }+ throw error;+ })),stemOutputs: undefined,};if (!ownsJob()) {diff --git a/apps/web/src/stores/planar-track-overlay-store.test.ts b/apps/web/src/stores/planar-track-overlay-store.test.tsnew file mode 100644index 00000000..0c28e978--- /dev/null+++ b/apps/web/src/stores/planar-track-overlay-store.test.ts@@ -0,0 +1,33 @@+import { describe, expect, it } from "vitest";+import { defaultPlanarCorners, dragPlanarCorner, dragPlanarQuad, usePlanarTrackOverlayStore } from "./planar-track-overlay-store";++describe("planar track overlay store", () => {+ const quad = [100, 100, 300, 100, 300, 200, 100, 200];++ it("drags one corner and keeps it inside the media", () => {+ expect(dragPlanarCorner(quad, 2, 20, -10, 640, 360).slice(4, 6)).toEqual([320, 190]);+ expect(dragPlanarCorner(quad, 0, -500, -500, 640, 360).slice(0, 2)).toEqual([0, 0]);+ });++ it("moves the whole quad but never past an edge", () => {+ expect(dragPlanarQuad(quad, 10, 5, 640, 360)).toEqual([110, 105, 310, 105, 310, 205, 110, 205]);+ expect(dragPlanarQuad(quad, 9999, 0, 640, 360).filter((_, i) => i % 2 === 0)).toEqual([440, 640, 640, 440]);+ });++ it("proposes a centred default quad", () => {+ expect(defaultPlanarCorners(640, 360)).toEqual([192, 108, 448, 108, 448, 252, 192, 252]);+ });++ it("mirrors Inspector writes without bumping the edit revision, and counts overlay edits", () => {+ const s = usePlanarTrackOverlayStore;+ s.getState().open({ clipId: "a", corners: quad, mediaWidth: 640, mediaHeight: 360 });+ s.getState().mirror("a", [1, 2, 3, 4, 5, 6, 7, 8]);+ expect(s.getState().editRevision).toBe(0);+ s.getState().edit(quad);+ expect(s.getState().editRevision).toBe(1);+ s.getState().mirror("other", [0, 0, 0, 0, 0, 0, 0, 0]);+ expect(s.getState().corners).toEqual(quad);+ s.getState().close("a");+ expect(s.getState().corners).toBeNull();+ });+});diff --git a/apps/web/src/stores/planar-track-overlay-store.ts b/apps/web/src/stores/planar-track-overlay-store.tsnew file mode 100644index 00000000..0608bc68--- /dev/null+++ b/apps/web/src/stores/planar-track-overlay-store.ts@@ -0,0 +1,49 @@+import { create } from "zustand";++/**+ * The planar-track corners as shown on the Program monitor. The Inspector section owns the numbers and mirrors+ * them here; the overlay's draggable handles write back through `edit`. Source pixels of the tracked clip's media,+ * ordered top-left, top-right, bottom-right, bottom-left (eight numbers).+ */+export interface PlanarTrackOverlayState {+ clipId: string | null;+ corners: number[] | null;+ mediaWidth: number;+ mediaHeight: number;+ /** Bumped by overlay drags only, so the Inspector can tell a drag from its own writes. */+ editRevision: number;+ open: (input: { clipId: string; corners: number[]; mediaWidth: number; mediaHeight: number }) => void;+ close: (clipId: string) => void;+ mirror: (clipId: string, corners: number[]) => void;+ edit: (corners: number[]) => void;+}++const same = (a: readonly number[] | null, b: readonly number[]): boolean => a !== null && a.length === b.length && a.every((v, i) => v === b[i]);++export const usePlanarTrackOverlayStore = create<PlanarTrackOverlayState>((set, get) => ({+ clipId: null, corners: null, mediaWidth: 0, mediaHeight: 0, editRevision: 0,+ open: input => set({ ...input }),+ close: clipId => { if (get().clipId === clipId) set({ clipId: null, corners: null }); },+ mirror: (clipId, corners) => { const s = get(); if (s.clipId === clipId && !same(s.corners, corners)) set({ corners }); },+ edit: corners => { const s = get(); if (s.clipId && !same(s.corners, corners)) set({ corners, editRevision: s.editRevision + 1 }); },+}));++/** Move one corner by (dx, dy) source pixels from `start`, kept inside the media (a little outside is allowed for pins at the frame edge). */+export function dragPlanarCorner(start: readonly number[], index: number, dx: number, dy: number, mediaWidth: number, mediaHeight: number): number[] {+ const next = [...start];+ next[index * 2] = Math.round(Math.max(0, Math.min(mediaWidth, start[index * 2] + dx)) * 10) / 10;+ next[index * 2 + 1] = Math.round(Math.max(0, Math.min(mediaHeight, start[index * 2 + 1] + dy)) * 10) / 10;+ return next;+}++/** Move the whole quad, clamped so no corner leaves the media. */+export function dragPlanarQuad(start: readonly number[], dx: number, dy: number, mediaWidth: number, mediaHeight: number): number[] {+ const xs = start.filter((_, i) => i % 2 === 0), ys = start.filter((_, i) => i % 2 === 1);+ const mx = Math.max(-Math.min(...xs), Math.min(mediaWidth - Math.max(...xs), dx)), my = Math.max(-Math.min(...ys), Math.min(mediaHeight - Math.max(...ys), dy));+ return start.map((v, i) => Math.round((v + (i % 2 === 0 ? mx : my)) * 10) / 10);+}++export function defaultPlanarCorners(mediaWidth: number, mediaHeight: number): number[] {+ const x0 = mediaWidth * 0.3, x1 = mediaWidth * 0.7, y0 = mediaHeight * 0.3, y1 = mediaHeight * 0.7;+ return [x0, y0, x1, y0, x1, y1, x0, y1].map(v => Math.round(v));+}diff --git a/apps/web/src/stores/project-store.test.ts b/apps/web/src/stores/project-store.test.tsindex 4c62c5b9..e48adf6f 100644--- a/apps/web/src/stores/project-store.test.ts+++ b/apps/web/src/stores/project-store.test.ts@@ -1,5 +1,5 @@import { describe, it, expect, beforeEach, vi } from "vitest";-import { useProjectStore } from "./project-store";+import { useProjectStore, registerSmoothKeyframeRefresh } from "./project-store";import { useEngineStore } from "./engine-store";import { useTimelineStore } from "./timeline-store";import { useUIStore } from "./ui-store";@@ -9,6 +9,8 @@ import {getAnimatedVideoEffects,getPluginRegistry,parsePluginPackage,+ applyKeyframeInterpolation,+ refreshSmoothKeyframesAfterEdit,} from "@openreel/core";import type {Project,@@ -2346,3 +2348,93 @@ describe("ProjectStore - generated shader registry lifecycle", () => {).toEqual([shaderA.id]);});});++describe("ProjectStore - smooth keyframe interpolation", () => {+ const createProjectWithVideoClip = (): Project => ({+ id: "effects-project",+ name: "Effects Project",+ createdAt: Date.now(),+ modifiedAt: Date.now(),+ settings: {+ width: 1920,+ height: 1080,+ frameRate: 30,+ sampleRate: 48000,+ channels: 2,+ },+ mediaLibrary: { items: [] },+ timeline: {+ tracks: [+ {+ id: "video-track-1",+ type: "video",+ name: "Video",+ clips: [+ {+ id: "video-clip-1",+ mediaId: "video-media-1",+ trackId: "video-track-1",+ startTime: 0,+ duration: 8,+ inPoint: 0,+ outPoint: 8,+ effects: [],+ audioEffects: [],+ transform: {+ position: { x: 0.5, y: 0.5 },+ scale: { x: 1, y: 1 },+ rotation: 0,+ anchor: { x: 0.5, y: 0.5 },+ opacity: 1,+ },+ volume: 1,+ keyframes: [],+ },+ ],+ transitions: [],+ locked: false,+ hidden: false,+ muted: false,+ solo: false,+ },+ ],+ subtitles: [],+ duration: 8,+ markers: [],+ },+ });++ const key = (id: string, time: number, value: number) => ({ id, time, property: "opacity", value, easing: "linear" as const });+ const keysOf = () => useProjectStore.getState().getClip("video-clip-1")!.keyframes!;++ beforeEach(() => {+ useProjectStore.getState().loadProject(createProjectWithVideoClip());+ registerSmoothKeyframeRefresh(refreshSmoothKeyframesAfterEdit);+ });++ it("re-derives Auto Bezier sides when a neighbour changes, whichever path edits the keys", () => {+ const store = useProjectStore.getState();+ const auto = applyKeyframeInterpolation([key("a", 0, 0), key("b", 1, 1), key("c", 2, 3)], ["b"], "auto-bezier");+ store.updateClipKeyframes("video-clip-1", auto, { derived: true });+ const before = keysOf().find((k) => k.id === "b")!.bezierHandles;+ store.updateClipKeyframes("video-clip-1", keysOf().map((k) => (k.id === "c" ? { ...k, value: 9 } : k)));+ expect(keysOf().find((k) => k.id === "b")!.bezierHandles).not.toEqual(before);+ expect(keysOf().find((k) => k.id === "b")).toMatchObject({ interpolationIn: "auto-bezier", interpolationOut: "auto-bezier" });+ });++ it("an easing change through any path drops the stale Auto tag so the label matches the curve", () => {+ const store = useProjectStore.getState();+ store.updateClipKeyframes("video-clip-1", applyKeyframeInterpolation([key("a", 0, 0), key("b", 1, 1), key("c", 2, 3)], ["b"], "auto-bezier"), { derived: true });+ store.updateClipKeyframes("video-clip-1", keysOf().map((k) => (k.id === "b" ? { ...k, easing: "ease-out" as const } : k)));+ const b = keysOf().find((k) => k.id === "b")!;+ expect(b.easing).toBe("ease-out");+ expect(b.interpolationOut).toBeUndefined();+ expect(b.interpolationIn).toBe("auto-bezier");+ });++ it("leaves legacy keyframes untouched", () => {+ const legacy = [key("a", 0, 0), key("b", 1, 1)];+ useProjectStore.getState().updateClipKeyframes("video-clip-1", legacy);+ expect(keysOf()).toEqual(legacy);+ });+});diff --git a/apps/web/src/stores/project-store.ts b/apps/web/src/stores/project-store.tsindex 2cdcdc48..76cf8931 100644--- a/apps/web/src/stores/project-store.ts+++ b/apps/web/src/stores/project-store.ts@@ -238,6 +238,8 @@ export interface ProjectState {hideTrack: (trackId: string, hidden: boolean) => Promise<ActionResult>;muteTrack: (trackId: string, muted: boolean) => Promise<ActionResult>;soloTrack: (trackId: string, solo: boolean) => Promise<ActionResult>;+ /** Solo Safe: keep the track audible while other tracks are soloed (live and in the export mixdown). */+ setTrackSoloSafe: (trackId: string, soloSafe: boolean) => Promise<ActionResult>;setTrackSyncLock: (trackId: string, syncLock: boolean) => Promise<ActionResult>;/** Replace a track's (or the master bus's, target "master") effect rack: one undo step. */setAudioRack: (target: string, rack: AudioRack | null) => Promise<ActionResult>;@@ -499,6 +501,11 @@ export interface ProjectState {markerId: string,updates: Partial<import("@openreel/core").Marker>,) => Promise<ActionResult>;+ /** Replace the markers of one clip (`clipId`) or of a media item's master clip (`mediaId`); source-time markers. */+ setClipMarkers: (+ target: { clipId: string } | { mediaId: string },+ markers: import("@openreel/core").Marker[],+ ) => Promise<ActionResult>;getMarker: (markerId: string) => import("@openreel/core").Marker | undefined;getMarkers: () => import("@openreel/core").Marker[];@@ -692,7 +699,8 @@ export interface ProjectState {clearClipAudioDucking: (clipId: string) => boolean;// Keyframe actions- updateClipKeyframes: (clipId: string, keyframes: Keyframe[]) => boolean;+ /** `derived` marks keys already produced by applyKeyframeInterpolation, so smooth sides are not re-derived as if hand-edited. */+ updateClipKeyframes: (clipId: string, keyframes: Keyframe[], options?: { derived?: boolean }) => boolean;// Undo/Redoundo: () => Promise<ActionResult>;@@ -741,6 +749,18 @@ const TITLE_ENGINE_SYNC_ACTIONS = new Set<string>(["style/applyCaption",]);+/**+ * Re-derives Auto / Continuous Bezier sides after a keyframe edit. The derivation lives in core and is+ * registered by the editor chunk (the only place smooth keys can be created), which keeps it out of the+ * startup entry chunk. Keys without smooth sides never reach it.+ */+type SmoothKeyframeRefresh = (prior: readonly Keyframe[] | undefined, next: readonly Keyframe[]) => Keyframe[];+let smoothKeyframeRefresh: SmoothKeyframeRefresh | null = null;+export function registerSmoothKeyframeRefresh(refresh: SmoothKeyframeRefresh): void {+ smoothKeyframeRefresh = refresh;+}+const hasSmoothSide = (key: Keyframe): boolean => key.interpolationIn !== undefined || key.interpolationOut !== undefined;+export const useProjectStore = create<ProjectState>()(subscribeWithSelector((set, get) => {const actionHistory = new ActionHistory();@@ -4590,7 +4610,8 @@ export const useProjectStore = create<ProjectState>()(* Update keyframes for a clip* Keyframe animation support*/- updateClipKeyframes: (clipId: string, keyframes: Keyframe[]) => {+ updateClipKeyframes: (clipId: string, inputKeyframes: Keyframe[], options?: { derived?: boolean }) => {+ let keyframes = inputKeyframes;const { project } = get();for (const track of project.timeline.tracks) {@@ -4598,6 +4619,9 @@ export const useProjectStore = create<ProjectState>()(if (clipIndex !== -1) {const clip = track.clips[clipIndex];const priorKeyframes = clip.keyframes;+ if (!options?.derived && smoothKeyframeRefresh && (keyframes.some(hasSmoothSide) || priorKeyframes?.some(hasSmoothSide))) {+ keyframes = smoothKeyframeRefresh(priorKeyframes, keyframes);+ }const updatedClip = { ...clip, keyframes };const updatedClips = [...track.clips];updatedClips[clipIndex] = updatedClip;diff --git a/apps/web/src/stores/project/marker-slice.ts b/apps/web/src/stores/project/marker-slice.tsindex e9a1418f..9eeaf2ac 100644--- a/apps/web/src/stores/project/marker-slice.ts+++ b/apps/web/src/stores/project/marker-slice.ts@@ -8,7 +8,7 @@ type Set = StoreApi<ProjectState>["setState"];type MarkerSlice = Pick<ProjectState,- "addMarker" | "removeMarker" | "updateMarker" | "getMarker" | "getMarkers"+ "addMarker" | "removeMarker" | "updateMarker" | "getMarker" | "getMarkers" | "setClipMarkers">;export function createMarkerSlice(set: Set, get: Get): MarkerSlice {@@ -58,6 +58,21 @@ export function createMarkerSlice(set: Set, get: Get): MarkerSlice {return result;},+ setClipMarkers: async (target, markers) => {+ const { project, actionExecutor } = get();+ const action: Action = {+ type: "clipmarker/set",+ id: uuidv4(),+ timestamp: Date.now(),+ params: { ...target, markers },+ };+ const result = await actionExecutor.execute(action, project);+ if (result.success) {+ set({ project: { ...project, modifiedAt: Date.now() } });+ }+ return result;+ },+getMarker: (markerId) =>get().project.timeline.markers.find((m) => m.id === markerId),diff --git a/apps/web/src/stores/project/media-slice.ts b/apps/web/src/stores/project/media-slice.tsindex 43474fa1..eb6d462a 100644--- a/apps/web/src/stores/project/media-slice.ts+++ b/apps/web/src/stores/project/media-slice.ts@@ -1,4 +1,5 @@import { v4 as uuidv4 } from "uuid";+import { backgroundTasks } from "@openreel/core/tasks/task-registry";import type { StoreApi } from "zustand";import { claimNativeSource, probeFootageShape, isRawFileName, type Action, type MediaItem, type SourceColorSpace } from "@openreel/core";import { buildRawMediaItem } from "../../services/raw-import";@@ -6,6 +7,7 @@ import type { ProjectState } from "../project-store";import { getMediaBridge, initializeMediaBridge } from "../../bridges/media-bridge";import { saveMediaBlob, deleteMediaBlob } from "../../services/media-storage";import { toast } from "../notification-store";+import { useSettingsStore } from "../settings-store";import { nativePathForFile } from "../../services/native-path";import { sourceTimecodeMetadata } from "../../services/source-timecode";@@ -58,7 +60,7 @@ type MediaSlice = Pick<export function createMediaSlice(set: Set, get: Get): MediaSlice {const replacementRequests = new Map<string, symbol>();- return {+ const slice: MediaSlice = {importMedia: async (file, onProgress, source, options) => {const { project, actionExecutor } = get();const cancelled = () => options?.signal?.aborted || options?.isCurrent?.() === false;@@ -121,7 +123,7 @@ export function createMediaSlice(set: Set, get: Get): MediaSlice {if (!ownsRequest()) return unavailableResult();const isLargeFile = file.size > 50 * 1024 * 1024;- const importResult = await mediaBridge.importFile(file, true, isLargeFile, onProgress);+ const importResult = await mediaBridge.importFile(file, true, isLargeFile, onProgress, { untracked: true, signal: options?.signal });if (!ownsRequest()) return unavailableResult();if (!importResult.success || !importResult.media) {@@ -245,6 +247,10 @@ export function createMediaSlice(set: Set, get: Get): MediaSlice {...(nativePathForFile(file) ? { path: nativePathForFile(file) } : {}),},importedAt: Date.now(),+ // Preferences > Default audio channels: a mono/stereo default is stamped on files that carry audio.+ ...(processedMedia.metadata.hasAudio && useSettingsStore.getState().defaultAudioChannels !== "file"+ ? { channelPreset: useSettingsStore.getState().defaultAudioChannels }+ : {}),// Import into the bin being viewed (Premiere imports into the active bin)....(importBinId(get().project) ? { binId: importBinId(get().project) } : {}),};@@ -632,4 +638,43 @@ export function createMediaSlice(set: Set, get: Get): MediaSlice {getMediaItem: (mediaId: string) =>get().project.mediaLibrary.items.find((item) => item.id === mediaId),};++ // Every import is one background task covering the whole action (decode and adding to the project),+ // so Cancel stops before the media is added and Retry re-runs the same row with the same follow-up.+ const importInner = slice.importMedia;+ const taskId = (): string => `import:${uuidv4()}`;+ const runTracked = (id: string, args: Parameters<MediaSlice["importMedia"]>): ReturnType<MediaSlice["importMedia"]> => {+ const [file, onProgress, source, options] = args;+ return backgroundTasks+ .track(+ { id, kind: "import", source: "import", title: `Import \u00b7 ${file.name}`, retry: () => void runTracked(id, args).catch(() => undefined) },+ async (ctx) => {+ const merged = new AbortController();+ const forward = () => merged.abort();+ for (const signal of [ctx.signal, options?.signal]) {+ if (signal?.aborted) forward();+ else signal?.addEventListener("abort", forward, { once: true });+ }+ try {+ const result = await importInner(file, (stage) => { ctx.progress(null, stage); onProgress?.(stage); }, source, { ...options, signal: merged.signal });+ if (!result.success && !ctx.signal.aborted) throw new ImportActionFailure(result);+ return result;+ } finally {+ ctx.signal.removeEventListener("abort", forward);+ options?.signal?.removeEventListener("abort", forward);+ }+ },+ )+ .catch((error) => {+ if (error instanceof ImportActionFailure) return error.result;+ throw error;+ });+ };+ return { ...slice, importMedia: (...args) => runTracked(taskId(), args) };+}++class ImportActionFailure extends Error {+ constructor(readonly result: Awaited<ReturnType<MediaSlice["importMedia"]>>) {+ super(result.error?.message ?? "Import failed");+ }}diff --git a/apps/web/src/stores/project/track-slice.ts b/apps/web/src/stores/project/track-slice.tsindex 1dcd3865..19e99ad7 100644--- a/apps/web/src/stores/project/track-slice.ts+++ b/apps/web/src/stores/project/track-slice.ts@@ -21,6 +21,7 @@ type TrackSlice = Pick<| "muteTrack"| "soloTrack"| "setTrackSyncLock"+ | "setTrackSoloSafe"| "setAudioRack"| "applyAudioRouting"| "setTrackAutomation"@@ -187,6 +188,21 @@ export function createTrackSlice(set: Set, get: Get): TrackSlice {return result;},+ setTrackSoloSafe: async (trackId, soloSafe) => {+ const { project, actionExecutor } = get();+ const action: Action = {+ type: "track/setSoloSafe",+ id: uuidv4(),+ timestamp: Date.now(),+ params: { trackId, soloSafe },+ };+ const result = await actionExecutor.execute(action, project);+ if (result.success) {+ set({ project: { ...project } });+ }+ return result;+ },+hideTrack: async (trackId, hidden) => {const { project, actionExecutor } = get();const action: Action = {diff --git a/apps/web/src/stores/settings-store.ts b/apps/web/src/stores/settings-store.tsindex 6005a69f..5ae85ae5 100644--- a/apps/web/src/stores/settings-store.ts+++ b/apps/web/src/stores/settings-store.ts@@ -50,6 +50,7 @@ export const SERVICE_REGISTRY: readonly ServiceConfig[] = [export type TtsProvider = "elevenlabs";export type LlmProvider = "openai-compatible" | "anthropic-compatible";export type AggregatorProvider = "kie-ai" | "freepik";+import type { ChannelPreset } from "@openreel/core";export type SettingsTab = "general" | "ai-editor" | "api-keys" | "mcp";function isLlmProvider(value: unknown): value is LlmProvider {@@ -61,6 +62,12 @@ interface SettingsState {autoSave: boolean;autoSaveInterval: number;language: string;+ /** Preview monitor device (setSinkId); "" = system default. Remembered across sessions. */+ audioOutputDeviceId: string;+ /** Last known name of that device, so an unplugged device can still be named. */+ audioOutputDeviceLabel: string;+ /** Modify > Audio Channels default for newly imported files with audio. */+ defaultAudioChannels: ChannelPreset;// AI/Service preferencesdefaultTtsProvider: TtsProvider;@@ -94,6 +101,8 @@ interface SettingsState {setAutoSave: (enabled: boolean) => void;setAutoSaveInterval: (minutes: number) => void;setLanguage: (lang: string) => void;+ setAudioOutputDevice: (deviceId: string, label?: string) => void;+ setDefaultAudioChannels: (preset: ChannelPreset) => void;setDefaultTtsProvider: (provider: TtsProvider) => void;setDefaultLlmProvider: (provider: LlmProvider | null) => void;setLlmBaseUrl: (url: string) => void;@@ -123,6 +132,9 @@ export const useSettingsStore = create<SettingsState>()(autoSave: true,autoSaveInterval: 5,language: "en",+ audioOutputDeviceId: "",+ audioOutputDeviceLabel: "",+ defaultAudioChannels: "file" as ChannelPreset,defaultTtsProvider: "elevenlabs" as TtsProvider,defaultLlmProvider: null,@@ -151,6 +163,12 @@ export const useSettingsStore = create<SettingsState>()(setLanguage: (lang: string) => set({ language: lang }),+ setAudioOutputDevice: (deviceId: string, label = "") => {+ const id = deviceId === "default" ? "" : deviceId;+ set({ audioOutputDeviceId: id, audioOutputDeviceLabel: id ? label : "" });+ },+ setDefaultAudioChannels: (preset: ChannelPreset) => set({ defaultAudioChannels: preset }),+setDefaultTtsProvider: (provider: TtsProvider) =>set({ defaultTtsProvider: provider }),@@ -268,6 +286,9 @@ export const useSettingsStore = create<SettingsState>()(autoSave: state.autoSave,autoSaveInterval: state.autoSaveInterval,language: state.language,+ audioOutputDeviceId: state.audioOutputDeviceId,+ audioOutputDeviceLabel: state.audioOutputDeviceLabel,+ defaultAudioChannels: state.defaultAudioChannels,defaultTtsProvider: state.defaultTtsProvider,defaultLlmProvider: state.defaultLlmProvider,llmBaseUrl: state.llmBaseUrl,diff --git a/apps/web/src/stores/source-monitor-store.ts b/apps/web/src/stores/source-monitor-store.tsindex 0151a9db..ee34ca89 100644--- a/apps/web/src/stores/source-monitor-store.ts+++ b/apps/web/src/stores/source-monitor-store.ts@@ -17,6 +17,13 @@ export type MonitorTab = "program" | "source" | "multicam";export type MonitorFocus = "program" | "source";const MARKS_KEY = "openreel-source-marks:";+/** Premiere's Source monitor keeps a short most-recent-first list of loaded clips. */+export const SOURCE_HISTORY_LIMIT = 10;++/** Push `mediaId` to the front of a history list, de-duplicated and capped. */+export function pushSourceHistory(history: readonly string[], mediaId: string): string[] {+ return [mediaId, ...history.filter((id) => id !== mediaId)].slice(0, SOURCE_HISTORY_LIMIT);+}function readMarks(projectId: string): Record<string, SourceMarks> {try {@@ -65,11 +72,17 @@ interface SourceMonitorState {rate: number;projectId: string | null;marks: Record<string, SourceMarks>;+ /** Recently loaded media ids, most recent first (this project, this session). */+ history: string[];/** Bumped on every open request so the view can re-focus/seek. */openNonce: number;+ /** Replace edit keeps the replaced clip's effects, keyframes and audio+ * settings (on) or resets them to a fresh clip (off). */+ replaceKeepsAttributes: boolean;setTab: (tab: MonitorTab) => void;setFocus: (focus: MonitorFocus) => void;+ setReplaceKeepsAttributes: (keep: boolean) => void;/** Load a media item into the source monitor and show the Source tab. */open: (mediaId: string, projectId: string, time?: number) => void;setPosition: (seconds: number) => void;@@ -78,6 +91,8 @@ interface SourceMonitorState {stop: () => void;togglePlay: () => void;bindProject: (projectId: string) => void;+ /** Drop a media id (deleted from the project) from the history. */+ forgetHistory: (mediaId: string) => void;setMark: (mediaId: string, which: "in" | "out", seconds: number | null) => void;clearMarks: (mediaId: string) => void;getMarks: (mediaId: string) => SourceMarks;@@ -91,13 +106,16 @@ export const useSourceMonitorStore = create<SourceMonitorState>((set, get) => ({rate: 0,projectId: null,marks: {},+ history: [],openNonce: 0,+ replaceKeepsAttributes: true,setTab: (tab) => set({ tab, ...(tab === "program" ? { rate: 0, focus: "program" as const } : {}) }),setFocus: (focus) => set({ focus }),+ setReplaceKeepsAttributes: (replaceKeepsAttributes) => set({ replaceKeepsAttributes }),bindProject: (projectId) => {if (get().projectId === projectId) return;- set({ projectId, marks: readMarks(projectId), mediaId: null, position: 0, rate: 0 });+ set({ projectId, marks: readMarks(projectId), mediaId: null, position: 0, rate: 0, history: [] });},open: (mediaId, projectId, time) => {const state = get();@@ -110,6 +128,7 @@ export const useSourceMonitorStore = create<SourceMonitorState>((set, get) => ({rate: 0,projectId,marks: sameProject ? state.marks : readMarks(projectId),+ history: pushSourceHistory(sameProject ? state.history : [], mediaId),openNonce: state.openNonce + 1,});},@@ -118,6 +137,7 @@ export const useSourceMonitorStore = create<SourceMonitorState>((set, get) => ({shuttle: (direction) => set((s) => ({ rate: nextShuttleRate(s.rate, direction) })),stop: () => set({ rate: 0 }),togglePlay: () => set((s) => ({ rate: s.rate === 0 ? 1 : 0 })),+ forgetHistory: (mediaId) => set((s) => ({ history: s.history.filter((id) => id !== mediaId) })),setMark: (mediaId, which, seconds) => {const { marks, projectId } = get();const current = { ...(marks[mediaId] ?? {}) };diff --git a/apps/web/src/types/global.d.ts b/apps/web/src/types/global.d.tsindex d2c48907..2d47a727 100644--- a/apps/web/src/types/global.d.ts+++ b/apps/web/src/types/global.d.ts@@ -23,6 +23,7 @@ interface OpenReelExportStartArgs {audioSampleRate: number;audioChannels: number;encodeMode?: "fast" | "balanced" | "smallest";+ encoderChoice?: "auto" | "hardware" | "software";quality?: number;proresProfile?: "proxy" | "lt" | "standard" | "hq" | "4444" | "4444xq";dnxhrProfile?: "lb" | "sq" | "hq" | "hqx" | "444";@@ -353,7 +354,7 @@ export interface OpenReelProxyJob {srcPath: string;outDir: string;fileName: string;- profile: { codec: "prores-proxy" | "h264"; size: "half" | "quarter" | "720p" | "1080p" };+ profile: { codec: "prores-proxy" | "h264" | "dnxhr-lb"; size: "half" | "quarter" | "720p" | "1080p" };previewTwin: boolean;status: "queued" | "running" | "done" | "failed";progress: number;@@ -379,7 +380,7 @@ export interface OpenReelIngestProject {projectId: string;projectPath?: string | null;config?: {- proxyProfile?: { codec: "prores-proxy" | "h264"; size: "half" | "quarter" | "720p" | "1080p" };+ proxyProfile?: { codec: "prores-proxy" | "h264" | "dnxhr-lb"; size: "half" | "quarter" | "720p" | "1080p" };proxyFolder?: string;mediaFolder?: string;concurrency?: 1 | 2;@@ -394,7 +395,7 @@ export interface OpenReelIngestBridge {mediaId: string;name: string;srcPath: string;- profile: { codec: "prores-proxy" | "h264"; size: "half" | "quarter" | "720p" | "1080p" };+ profile: { codec: "prores-proxy" | "h264" | "dnxhr-lb"; size: "half" | "quarter" | "720p" | "1080p" };previewTwin: boolean;}>;force?: boolean;@@ -447,6 +448,12 @@ declare global {ollama?: {probe(): Promise<OpenReelOllamaProbeResult>;};+ /** OS microphone permission (macOS/Windows privacy settings); the desktop app only. */+ microphone?: {+ status(): Promise<"not-determined" | "granted" | "denied" | "restricted">;+ request(): Promise<"not-determined" | "granted" | "denied" | "restricted">;+ openSettings(): Promise<boolean>;+ };/** Main-process helpers for fonts; Brotli for WOFF2 licence checks (Electron's Chromium has no Brotli DecompressionStream). */fonts?: {brotliDecompress(data: Uint8Array): Promise<Uint8Array | null>;diff --git a/apps/web/src/utils/burn-in-source.ts b/apps/web/src/utils/burn-in-source.tsnew file mode 100644index 00000000..60620396--- /dev/null+++ b/apps/web/src/utils/burn-in-source.ts@@ -0,0 +1,9 @@+import { createBurnInSource, type BurnInSource } from "@openreel/core";+import { useProjectStore } from "../stores/project-store";++/**+ * Burn-in source of the project being edited (cached per project object by the core, so this is a pointer lookup+ * once a frame). Preview, playback and effect cards read names and timecodes through it; export builds its own+ * from the project it was handed.+ */+export const currentBurnInSource = (): BurnInSource => createBurnInSource(useProjectStore.getState().project);diff --git a/apps/web/src/workers/diarization-worker.ts b/apps/web/src/workers/diarization-worker.tsnew file mode 100644index 00000000..8b6fe265--- /dev/null+++ b/apps/web/src/workers/diarization-worker.ts@@ -0,0 +1,22 @@+/// <reference lib="webworker" />+import { computeSpeakerEmbedding } from "@openreel/core";++export interface DiarizationWorkerRequest {+ requestId: string;+ segments: Array<{ id: string; samples: Float32Array }>;+}++export type DiarizationWorkerResponse =+ | { requestId: string; type: "progress"; progress: number }+ | { requestId: string; type: "result"; embeddings: Array<{ id: string; embedding: Float32Array | null }> };++/** Voice-prints for caption-cue audio, fully on device. */+self.onmessage = (event: MessageEvent<DiarizationWorkerRequest>) => {+ const { requestId, segments } = event.data;+ const post = (message: DiarizationWorkerResponse) => (self as unknown as Worker).postMessage(message);+ const embeddings = segments.map((segment, i) => {+ if (i % 8 === 0) post({ requestId, type: "progress", progress: i / Math.max(1, segments.length) });+ return { id: segment.id, embedding: computeSpeakerEmbedding(segment.samples) };+ });+ post({ requestId, type: "result", embeddings });+};diff --git a/apps/web/src/workers/planar-track-worker.ts b/apps/web/src/workers/planar-track-worker.tsnew file mode 100644index 00000000..591c1285--- /dev/null+++ b/apps/web/src/workers/planar-track-worker.ts@@ -0,0 +1,32 @@+/// <reference lib="webworker" />++import { PlanarTrackSession, type PlanarSessionConfig, type PlanarSessionFrame, type PlanarStep } from "@openreel/core";++type Request =+ | { type: "init"; config: PlanarSessionConfig }+ | { type: "step"; id: number; frame: PlanarSessionFrame };+export type PlanarTrackWorkerReply =+ | { type: "step"; id: number; step: PlanarStep }+ | { type: "error"; id: number; message: string };++let session: PlanarTrackSession | null = null;+// Steps are strictly sequential; chaining keeps them ordered even if the host posts ahead.+let chain: Promise<void> = Promise.resolve();++self.onmessage = (event: MessageEvent<Request>) => {+ const request = event.data;+ if (request.type === "init") {+ try { session = new PlanarTrackSession(request.config); } catch (error) { session = null; self.postMessage({ type: "error", id: 0, message: error instanceof Error ? error.message : "Tracking failed" } satisfies PlanarTrackWorkerReply); }+ return;+ }+ chain = chain.then(async () => {+ try {+ if (!session) throw new Error("Tracking worker was not initialised");+ self.postMessage({ type: "step", id: request.id, step: await session.step(request.frame) } satisfies PlanarTrackWorkerReply);+ } catch (error) {+ self.postMessage({ type: "error", id: request.id, message: error instanceof Error ? error.message : "Tracking failed" } satisfies PlanarTrackWorkerReply);+ }+ });+};++export {};diff --git a/docs/AGENT-CAPABILITIES.md b/docs/AGENT-CAPABILITIES.mdindex 795fcf06..e4671ed4 100644--- a/docs/AGENT-CAPABILITIES.md+++ b/docs/AGENT-CAPABILITIES.md@@ -2,7 +2,7 @@# OpenReel Agent — Capability Reference-The agent exposes **452 tools** spanning read/observe, project, track, clip, transform, effect, color, speed, audio, subtitle, keyframe, transition, marker, text and graphics domains — plus `execute_action` and `batch_actions` escape hatches for any capability without a dedicated tool.+The agent exposes **453 tools** spanning read/observe, project, track, clip, transform, effect, color, speed, audio, subtitle, keyframe, transition, marker, text and graphics domains — plus `execute_action` and `batch_actions` escape hatches for any capability without a dedicated tool.## Tools@@ -267,6 +267,7 @@ The agent exposes **452 tools** spanning read/observe, project, track, clip, tra- **set_track_sync_lock** — Turn a track's Sync Lock on or off (default on). Ripple-type edits (ripple delete, ripple trim, insert, extract, paste-insert, close gap) keep sync-locked tracks in sync by shifting them with the edit, or are blocked (naming the track) when the removed range is not empty there; tracks with Sync Lock off are never touched by edits to other tracks. One undo step.- **hide_track** — Show/hide a track.- **mute_track** — Mute/unmute a track.+- **set_track_solo_safe** — Turn Solo Safe on or off for a track. A solo-safe track keeps playing (preview and export mixdown) while other tracks are soloed; mute still silences it. Saved with the project. One undo step.- **solo_track** — Solo/unsolo a track.- **consolidate_track** — Remove Gaps: close every empty stretch on a track. Sync Lock: every other unlocked sync-locked track must be empty over each closed gap and shifts with it; otherwise the edit is blocked and the error names the track. Locked tracks are never changed. One undo step.- **delete_gap** — Ripple-delete the empty gap on a track that contains `time` (seconds, or timeFrame in frames): later clips move earlier to close it. Space after the last clip is not a gap. Sync Lock: every other unlocked sync-locked track must be empty over the gap and shifts with it; otherwise the edit is blocked and the error names the track. Locked tracks block it. One undo step.@@ -350,7 +351,7 @@ The agent exposes **452 tools** spanning read/observe, project, track, clip, tra- **set_clip_blend_opacity** — Set a clip's blend opacity (0..1).## effect-- **add_video_effect** — Add a video effect to a clip. Standard effectType values include brightness, contrast, saturation, blur, sharpen, vignette, grain, temperature, tint, shadow, glow, motion-blur, radial-blur, chromatic-aberration. Pro effect types (params validated against their ranges; omitted params take the same defaults as adding the effect in the editor UI): mosaic (size 1..200); posterize (levels 2..256); mirror (mode none|horizontal|vertical|quad, center 0..100); lens-distortion (amount -100..100, zoom 10..400, compensate boolean); directional-blur (angle 0..360, length 0..200); find-edges (amount 0..100, invert boolean); emboss (amount 0..100, angle 0..360, relief 0..10); exposure (exposure -5..5, offset -0.5..0.5, gamma 0.2..3); threshold (level 0..255, mix 0..100); halftone (dotSize 2..100, angle 0..360, amount 0..100, invert boolean); vhs-glitch (scanlines 0..100, rgbSplit 0..100, jitter 0..200, noise 0..100, time 0..3600, seed 0..9999); unsharp-mask (amount 0..500, radius 0.1..50, threshold 0..255); gaussian-blur (blurX 0..100, blurY 0..100); crop (left 0..100, top 0..100, right 0..100, bottom 0..100, feather 0..100); vibrance (vibrance -100..100, saturation -100..100); skew (skewX -60..60, skewY -60..60); hsl-secondary (hueMin 0..360, hueMax 0..360, hueSoft 0..180, satMin 0..100, satMax 0..100, satSoft 0..100, lumMin 0..100, lumMax 0..100, lumSoft 0..100, denoise 0..100, blur 0..20, invert boolean, temperature -100..100, tint -100..100, contrast -100..100, sharpen 0..100, saturation -100..100, wheelX -1..1, wheelY -1..1, maskShape none|ellipse|rectangle, maskX 0..100, maskY 0..100, maskW 0..100, maskH 0..100, maskFeather 0..200, maskInvert boolean); camera-blur (radius 0..60); channel-blur (red 0..60, green 0..60, blue 0..60, alpha 0..60); tilt-shift (blur 0..40, angle 0..360, center 0..100, focus 0..100, falloff 1..100); luma-key (mode none|darker|brighter, threshold 0..100, softness 0..100); color-key (keyR 0..255, keyG 0..255, keyB 0..255, tolerance 0..100, softness 0..100, invert boolean); alpha-adjust (opacity 0..100, ignore boolean, invert boolean, matte boolean); leave-color (keyR 0..255, keyG 0..255, keyB 0..255, amount 0..100, tolerance 0..100, softness 0..100); change-to-color (fromR 0..255, fromG 0..255, fromB 0..255, toR 0..255, toG 0..255, toB 0..255, tolerance 0..100, softness 0..100); solarize (threshold 0..100); levels (inBlack 0..254, inWhite 1..255, gamma 0.1..10, outBlack 0..255, outWhite 0..255); channel-mixer (rr -200..200, rg -200..200, rb -200..200, gr -200..200, gg -200..200, gb -200..200, br -200..200, bg -200..200, bb -200..200, mono boolean); tint-map (blackR 0..255, blackG 0..255, blackB 0..255, whiteR 0..255, whiteG 0..255, whiteB 0..255, amount 0..100); spherize (amount -100..100, radius 1..200, centerX 0..100, centerY 0..100); twirl (angle -720..720, radius 1..200, centerX 0..100, centerY 0..100); ripple (amplitude 0..200, wavelength 4..1000, angle 0..360, phase 0..360, speed -10..10, time 0..3600); turbulent-displace (amount 0..300, size 4..1000, complexity 1..4, evolution 0..1000, seed 0..9999); offset (shiftX -100..100, shiftY -100..100, edge wrap|clamp|transparent); corner-pin (x0 -100..200, y0 -100..200, x1 -100..200, y1 -100..200, x2 -100..200, y2 -100..200, x3 -100..200, y3 -100..200); polar-coordinates (mode rect-to-polar|polar-to-rect, amount 0..100); replicate (count 1..16); color-emboss (amount 0..100, angle 0..360, relief 0..10); noise (amount 0..100, size 1..32, mono boolean, time 0..3600, seed 0..9999); bevel-alpha (thickness 1..50, angle 0..360, intensity 0..100); four-color-gradient (c1R 0..255, c1G 0..255, c1B 0..255, c2R 0..255, c2G 0..255, c2B 0..255, c3R 0..255, c3G 0..255, c3B 0..255, c4R 0..255, c4G 0..255, c4B 0..255, opacity 0..100, blend normal|multiply|screen|add); lens-flare (centerX 0..100, centerY 0..100, brightness 0..200, size 1..200); strobe-light (flashR 0..255, flashG 0..255, flashB 0..255, opacity 0..100, period 0.05..10, duration 0..10, phase -10..10, blend normal|add, time 0..3600); grid (size 4..500, border 1..50, lineR 0..255, lineG 0..255, lineB 0..255, opacity 0..100). Prefer the pro type where one supersedes a legacy effect (gaussian-blur over blur, mosaic over shader pixelate, mirror over shader mirror, lens-distortion over shader fisheye, posterize over shader posterize, vhs-glitch over shader vhs); the legacy types still render in existing projects. Omitted legacy params also take the editor's visible defaults. Pro effect params can be keyframed with add_keyframe property fx:<effectId>:<param> (effectId from get_clip or list_effect_params). Set effectType to 'shader' to run a GPU shader effect from the Motion shader library (only category 'effect' shaders, e.g. the Paper Design catalog like paper-halftone-dots or paper-liquid-metal — use list_motion_shaders with category 'effect' to discover ids); for shader effects, params MUST include a valid shaderId plus optional numeric params (name/value pairs from the shader's params) and an optional numeric time. Shader effects no-op gracefully when WebGL2 is unavailable.+- **add_video_effect** — Add a video effect to a clip. Standard effectType values include brightness, contrast, saturation, blur, sharpen, vignette, grain, temperature, tint, shadow, glow, motion-blur, radial-blur, chromatic-aberration. Pro effect types (params validated against their ranges; omitted params take the same defaults as adding the effect in the editor UI): mosaic (size 1..200); posterize (levels 2..256); mirror (mode none|horizontal|vertical|quad, center 0..100); lens-distortion (amount -100..100, zoom 10..400, compensate boolean); directional-blur (angle 0..360, length 0..200); find-edges (amount 0..100, invert boolean); emboss (amount 0..100, angle 0..360, relief 0..10); exposure (exposure -5..5, offset -0.5..0.5, gamma 0.2..3); threshold (level 0..255, mix 0..100); halftone (dotSize 2..100, angle 0..360, amount 0..100, invert boolean); vhs-glitch (scanlines 0..100, rgbSplit 0..100, jitter 0..200, noise 0..100, time 0..3600, seed 0..9999); unsharp-mask (amount 0..500, radius 0.1..50, threshold 0..255); gaussian-blur (blurX 0..100, blurY 0..100); crop (left 0..100, top 0..100, right 0..100, bottom 0..100, feather 0..100); vibrance (vibrance -100..100, saturation -100..100); skew (skewX -60..60, skewY -60..60); hsl-secondary (hueMin 0..360, hueMax 0..360, hueSoft 0..180, satMin 0..100, satMax 0..100, satSoft 0..100, lumMin 0..100, lumMax 0..100, lumSoft 0..100, denoise 0..100, blur 0..20, invert boolean, temperature -100..100, tint -100..100, contrast -100..100, sharpen 0..100, saturation -100..100, wheelX -1..1, wheelY -1..1, maskShape none|ellipse|rectangle, maskX 0..100, maskY 0..100, maskW 0..100, maskH 0..100, maskFeather 0..200, maskInvert boolean); camera-blur (radius 0..60); channel-blur (red 0..60, green 0..60, blue 0..60, alpha 0..60); tilt-shift (blur 0..40, angle 0..360, center 0..100, focus 0..100, falloff 1..100); luma-key (mode none|darker|brighter, threshold 0..100, softness 0..100); color-key (keyR 0..255, keyG 0..255, keyB 0..255, tolerance 0..100, softness 0..100, invert boolean); ultra-key (keyR 0..255, keyG 0..255, keyB 0..255, transparency 0..100, highlight 0..100, shadow 0..100, tolerance 0..100, pedestal 0..100, choke 0..100, soften 0..100, contrast 0..100, midPoint 0..100, desaturate 0..100, range 0..100, spill 0..100, luma 0..100, saturation 0..200, hue -180..180, luminance 0..200, output composite|alpha|color|source); alpha-adjust (opacity 0..100, ignore boolean, invert boolean, matte boolean); leave-color (keyR 0..255, keyG 0..255, keyB 0..255, amount 0..100, tolerance 0..100, softness 0..100); change-to-color (fromR 0..255, fromG 0..255, fromB 0..255, toR 0..255, toG 0..255, toB 0..255, tolerance 0..100, softness 0..100); solarize (threshold 0..100); levels (inBlack 0..254, inWhite 1..255, gamma 0.1..10, outBlack 0..255, outWhite 0..255); channel-mixer (rr -200..200, rg -200..200, rb -200..200, gr -200..200, gg -200..200, gb -200..200, br -200..200, bg -200..200, bb -200..200, mono boolean); tint-map (blackR 0..255, blackG 0..255, blackB 0..255, whiteR 0..255, whiteG 0..255, whiteB 0..255, amount 0..100); spherize (amount -100..100, radius 1..200, centerX 0..100, centerY 0..100); twirl (angle -720..720, radius 1..200, centerX 0..100, centerY 0..100); ripple (amplitude 0..200, wavelength 4..1000, angle 0..360, phase 0..360, speed -10..10, time 0..3600); turbulent-displace (amount 0..300, size 4..1000, complexity 1..4, evolution 0..1000, seed 0..9999); offset (shiftX -100..100, shiftY -100..100, edge wrap|clamp|transparent); corner-pin (x0 -100..200, y0 -100..200, x1 -100..200, y1 -100..200, x2 -100..200, y2 -100..200, x3 -100..200, y3 -100..200); polar-coordinates (mode rect-to-polar|polar-to-rect, amount 0..100); replicate (count 1..16); color-emboss (amount 0..100, angle 0..360, relief 0..10); noise (amount 0..100, size 1..32, mono boolean, time 0..3600, seed 0..9999); bevel-alpha (thickness 1..50, angle 0..360, intensity 0..100); four-color-gradient (c1R 0..255, c1G 0..255, c1B 0..255, c2R 0..255, c2G 0..255, c2B 0..255, c3R 0..255, c3G 0..255, c3B 0..255, c4R 0..255, c4G 0..255, c4B 0..255, opacity 0..100, blend normal|multiply|screen|add); lens-flare (centerX 0..100, centerY 0..100, brightness 0..200, size 1..200); strobe-light (flashR 0..255, flashG 0..255, flashB 0..255, opacity 0..100, period 0.05..10, duration 0..10, phase -10..10, blend normal|add, time 0..3600); grid (size 4..500, border 1..50, lineR 0..255, lineG 0..255, lineB 0..255, opacity 0..100); echo (echoTime -2..2, echoes 0..32, startIntensity 0..1, decay 0..1, operator add|maximum|minimum|screen|composite-back|composite-front); posterize-time (frameRate 0..120). Prefer the pro type where one supersedes a legacy effect (gaussian-blur over blur, mosaic over shader pixelate, mirror over shader mirror, lens-distortion over shader fisheye, posterize over shader posterize, vhs-glitch over shader vhs); the legacy types still render in existing projects. Omitted legacy params also take the editor's visible defaults. Pro effect params can be keyframed with add_keyframe property fx:<effectId>:<param> (effectId from get_clip or list_effect_params). Set effectType to 'shader' to run a GPU shader effect from the Motion shader library (only category 'effect' shaders, e.g. the Paper Design catalog like paper-halftone-dots or paper-liquid-metal — use list_motion_shaders with category 'effect' to discover ids); for shader effects, params MUST include a valid shaderId plus optional numeric params (name/value pairs from the shader's params) and an optional numeric time. Shader effects no-op gracefully when WebGL2 is unavailable.- **remove_video_effect** — Remove a clip's video effect.- **update_video_effect** — Update a video effect's params. Pro effect params (see list_pro_effects) are range-checked.- **toggle_video_effect** — Enable/disable a video effect.@@ -3168,6 +3169,196 @@ The agent exposes **452 tools** spanning read/observe, project, track, clip, tra}]},+ {+ "type": "ultra-key",+ "label": "Ultra Key",+ "category": "Keying",+ "params": [+ {+ "key": "keyR",+ "kind": "number",+ "min": 0,+ "max": 255,+ "step": 1,+ "default": 0,+ "neutral": 0+ },+ {+ "key": "keyG",+ "kind": "number",+ "min": 0,+ "max": 255,+ "step": 1,+ "default": 255,+ "neutral": 255+ },+ {+ "key": "keyB",+ "kind": "number",+ "min": 0,+ "max": 255,+ "step": 1,+ "default": 0,+ "neutral": 0+ },+ {+ "key": "transparency",+ "kind": "number",+ "min": 0,+ "max": 100,+ "step": 1,+ "default": 45,+ "neutral": 0+ },+ {+ "key": "highlight",+ "kind": "number",+ "min": 0,+ "max": 100,+ "step": 1,+ "default": 10,+ "neutral": 0+ },+ {+ "key": "shadow",+ "kind": "number",+ "min": 0,+ "max": 100,+ "step": 1,+ "default": 50,+ "neutral": 0+ },+ {+ "key": "tolerance",+ "kind": "number",+ "min": 0,+ "max": 100,+ "step": 1,+ "default": 50,+ "neutral": 0+ },+ {+ "key": "pedestal",+ "kind": "number",+ "min": 0,+ "max": 100,+ "step": 1,+ "default": 0,+ "neutral": 0+ },+ {+ "key": "choke",+ "kind": "number",+ "min": 0,+ "max": 100,+ "step": 1,+ "default": 0,+ "neutral": 0+ },+ {+ "key": "soften",+ "kind": "number",+ "min": 0,+ "max": 100,+ "step": 1,+ "default": 0,+ "neutral": 0+ },+ {+ "key": "contrast",+ "kind": "number",+ "min": 0,+ "max": 100,+ "step": 1,+ "default": 0,+ "neutral": 0+ },+ {+ "key": "midPoint",+ "kind": "number",+ "min": 0,+ "max": 100,+ "step": 1,+ "default": 50,+ "neutral": 50+ },+ {+ "key": "desaturate",+ "kind": "number",+ "min": 0,+ "max": 100,+ "step": 1,+ "default": 15,+ "neutral": 0+ },+ {+ "key": "range",+ "kind": "number",+ "min": 0,+ "max": 100,+ "step": 1,+ "default": 50,+ "neutral": 0+ },+ {+ "key": "spill",+ "kind": "number",+ "min": 0,+ "max": 100,+ "step": 1,+ "default": 50,+ "neutral": 0+ },+ {+ "key": "luma",+ "kind": "number",+ "min": 0,+ "max": 100,+ "step": 1,+ "default": 50,+ "neutral": 0+ },+ {+ "key": "saturation",+ "kind": "number",+ "min": 0,+ "max": 200,+ "step": 1,+ "default": 100,+ "neutral": 100+ },+ {+ "key": "hue",+ "kind": "number",+ "min": -180,+ "max": 180,+ "step": 1,+ "default": 0,+ "neutral": 0+ },+ {+ "key": "luminance",+ "kind": "number",+ "min": 0,+ "max": 200,+ "step": 1,+ "default": 100,+ "neutral": 100+ },+ {+ "key": "output",+ "kind": "select",+ "default": "composite",+ "neutral": "composite",+ "options": [+ "composite",+ "alpha",+ "color",+ "source"+ ]+ }+ ]+ },{"type": "alpha-adjust","label": "Alpha Adjust",@@ -4375,6 +4566,79 @@ The agent exposes **452 tools** spanning read/observe, project, track, clip, tra"neutral": 0}]+ },+ {+ "type": "echo",+ "label": "Echo",+ "category": "Time",+ "params": [+ {+ "key": "echoTime",+ "kind": "number",+ "min": -2,+ "max": 2,+ "step": 0.001,+ "default": 0.033,+ "neutral": 0+ },+ {+ "key": "echoes",+ "kind": "number",+ "min": 0,+ "max": 32,+ "step": 1,+ "default": 2,+ "neutral": 0+ },+ {+ "key": "startIntensity",+ "kind": "number",+ "min": 0,+ "max": 1,+ "step": 0.01,+ "default": 1,+ "neutral": 1+ },+ {+ "key": "decay",+ "kind": "number",+ "min": 0,+ "max": 1,+ "step": 0.01,+ "default": 0.5,+ "neutral": 0.5+ },+ {+ "key": "operator",+ "kind": "select",+ "default": "add",+ "neutral": "add",+ "options": [+ "add",+ "maximum",+ "minimum",+ "screen",+ "composite-back",+ "composite-front"+ ]+ }+ ]+ },+ {+ "type": "posterize-time",+ "label": "Posterize Time",+ "category": "Time",+ "params": [+ {+ "key": "frameRate",+ "kind": "number",+ "min": 0,+ "max": 120,+ "step": 1,+ "default": 1,+ "neutral": 0+ }+ ]}],"premiere": {diff --git a/docs/PREMIERE-GAPS.md b/docs/PREMIERE-GAPS.mdindex 549cc662..9a4084e6 100644--- a/docs/PREMIERE-GAPS.md+++ b/docs/PREMIERE-GAPS.md@@ -27,8 +27,8 @@- **WP1 Trim and edit points:** closed. Dynamic JKL trim previews the trimmed result live on the Program monitor, with a two-up (outgoing | incoming) view at a cut. Edit-point selection, `,`/`.` trim, numeric trim, ripple/roll toggle, gap select/delete, Go to In/Out and Mark Clip are in (`edit-point-commands.test.ts`, `dynamic-trim.test.ts`, `e2e/trim-tools.spec.ts`).- **WP2 Effects and keyframes:** closed. Instance-keyed keyframes with migration on load, a stopwatch per parameter, mask combine modes and effect presets (`effect-instance-keyframes.test.ts`, `mask-engine.combine.test.ts`, `effect-presets.test.ts`).-- **WP3 Audio depth:** audible scrubbing and automation lanes are closed. **Open:** voice-over record upgrade (pre-roll, input select), solo-safe and output-device picker, source-channel mapping.-- **WP4 Colour fidelity:** closed for the LUT parser, 1D LUTs, LUT library, `.cube` export, Input LUT, scope modes, false colour, nit scale and saved looks. **Open:** white-balance eyedropper parity and a camera-log preset set.+- **WP3 Audio depth:** audible scrubbing, automation lanes, solo-safe and the output-device picker are closed (`track-audibility.test.ts`, `audio-output-device.test.ts`, `e2e/audio-output-solo-safe.spec.ts`). Voice-over record upgrade is closed (pre-roll countdown with playback, remembered input select, live meter, target track, punch in/out, mute-during-record, stacked named takes, desktop microphone permissions; `voiceover-logic.test.ts`, `e2e/voiceover.spec.ts`). Source-channel mapping (Clip > Audio Channels) is closed.+- **WP4 Colour fidelity:** closed for the LUT parser, 1D LUTs, LUT library, `.cube` export, Input LUT, scope modes, false colour, nit scale and saved looks. White-balance eyedropper is closed (Program-monitor sampling, point / 5x5, one undo step; `white-balance-eyedropper.test.ts`). Camera-log presets (Sony, Panasonic, ARRI, Canon, Nikon, Fujifilm, Blackmagic; formula based, Interpret Footage and Color tab picker) are in. **Open:** ACES / OCIO.- **WP5 Media and delivery:** closed for preset management, image-sequence and GIF export, EDL import with reel relink, Interpret Footage, and two-pass and target/max rate control. Interchange verification stays open (item 11).- **WP6 Text, captions, graphics:** closed for on-canvas text editing, caption style model with VTT cue settings, saved styles, roll and crawl, the `path` shape and the missing-font report. **Open:** speaker diarization and translation.@@ -88,7 +88,7 @@ Perf work (must-fix 6 to 8) has its own owner in `apps/desktop/scripts/*` and `p- **Large effort, low audience:** VST3/AU host, Atmos and AC-3 delivery, multichannel monitoring, native R3D/BRAW/ARRIRAW, `.prproj` read and Dynamic Link, `.mogrt` interchange, ACES/OCIO and display P3, HDR monitoring and Dolby Vision, spectral editing, ML speech enhancement, multicam editable sources and angle add/replace.- **Architecture, ship after verification:** WebGPU effects and transition coverage, float HDR for all effects, off-thread compositing, persistent render cache with a scratch-disk setting and full-resolution previews, Windows and Linux perf qualification, a separate encoder process with watch folders.-- **Polish:** clip and master-clip markers, Source monitor history and Reverse Match Frame, multichannel source patching, Replace and Fit to Fill, multi-clip ripple speed, 1000+ clip measurements, bezier handle types, planar and corner-pin tracking, missing Premiere effects (Echo, Posterize Time, VR, Ultra Key), custom transitions, Media Browser, XMP metadata, Project Manager transcode, hardware encoder picker, timecode and name overlays, publish targets, smart-render breadth, proxy presets, unified background-task panel, template catalog, extra caption import formats.+- **Polish:** clip and master-clip markers, Source monitor history and Reverse Match Frame, multichannel source patching, multi-clip ripple speed, 1000+ clip measurements, bezier handle types, planar and corner-pin tracking, missing Premiere effects (VR; Echo, Posterize Time and Ultra Key are done), custom transitions, Media Browser, XMP metadata, Project Manager transcode, hardware encoder picker, publish targets, smart-render breadth, proxy presets, unified background-task panel, template catalog, extra caption import formats.## 5. Strengths to marketdiff --git a/docs/known-limitations.md b/docs/known-limitations.mdindex be7f1a49..d7c032b0 100644--- a/docs/known-limitations.md+++ b/docs/known-limitations.md@@ -253,3 +253,59 @@ See docs/collaboration.md for the design and security model. Limits:- **Security.** The server does not validate actions or the conflict keys an author declares; editors are trusted. Room access is a bearer link (anyone holding it joins); there are no per-user accounts, revocation, or audit trail, and a link cannot be revoked short of abandoning the room. Cloud identities are still the dev shim.- **Text, shape, graphics and other overlay clips** sync through their actions but the title/graphics engines are re-synced from the project only after each remote batch; rapid concurrent overlay edits were covered by unit tests only, not an end-to-end run.- The Durable Object itself was exercised through a fake `DurableObjectState`/socket harness (the real `RoomCore` and storage layout), not a live `wrangler dev`/miniflare instance, and nothing was deployed.++## Audio Channels++- Waveforms for a mapped clip are recomputed by decoding the whole file; media over 200 MB keeps the unmapped waveform (playback and export still follow the map).+- Edits to a channel map made during playback take effect when playback restarts, like other audio edits.+- Channel maps are verified end to end for WAV and for AAC video sources; exotic codecs that the browser cannot decode natively go through the ffmpeg fallback, which keeps up to six source channels only when a clip is mapped to a channel beyond L/R or to 5.1.++## Speaker detection (captions)++Detect speakers runs entirely on this device and uses a small voice-print (MFCC statistics plus pitch) with clustering, not a trained speaker-recognition model. No such model is bundled, and nothing is downloaded or sent off the machine.++- **Accuracy on real voices is limited.** It separates clearly different voices (for example a low and a high voice) well, but similar voices can be merged into one speaker and one voice can be split into two. In a test with three synthetic voices reading different sentences, Auto and a fixed count both got only some of the passages right. Treat the result as a first pass and check the labels.+- **Overlapping speech is not separated.** A caption passage is assigned to a single speaker.+- **Fixing the speaker count helps only when you know it.** Auto picks the count from the clearest gap between voices and can be wrong; the speaker-count menu overrides it.+- **Re-running detection replaces the labels,** including passages you reassigned by hand. Renames, colours and positions of speakers that are still found are kept.+- **Clearing a passage's speaker restores the caption look it had before it was labelled,** which discards style edits made to that caption in between.+- **Clips with no audio track** cannot be labelled; Detect speakers says so.+- The only real-voice evidence is a short fixture of two synthetic text-to-speech voices; no recorded human interviews are in the test suite.++## Caption translation++- **Machine translation quality is the engine's.** Translation uses the connected AI model or the browser's on-device Translator API (Chrome 138+, language packs may download). Neither was verified against a live provider in automated tests (mocked clients and a Translator test double); with neither available the Translate tool says so and adds nothing.+- **Translated cues drop word timings**, so karaoke-style word animations fall back to whole-cue display. Cue timing, style and speakers are preserved.+- **A translation is kept out of the picture by default** (its cues are hidden) so two languages never overlap. Choose which track is shown with "Show this track in the picture"; showing one track hides the others. Sidecar and embedded caption files still include every track.+- The browser engine translates one cue per call, so long tracks take a while.++## Ultra Key++- **The Effects-tab card key is a heuristic, labelled "Sample key".** The card previews the effect on your own footage by guessing a key colour from that frame, then narrowing tolerance and transparency until at most about 40% of the frame is keyed. On non-green footage (for example an interview shot) it shows a representative checkerboard-keyed sample, not a prediction of the result. Pick the real key colour with the eyedropper in the Inspector, which samples the Program monitor.+- **Preview/export parity was verified on WebGL2 in headless Chromium** (shader versus the CPU reference used by the Canvas2D fallback and export: 0 pixels off in RGB and alpha on the test frames). It has not been exercised on real WebGPU hardware or in the Electron desktop app.++## Background-task panel++The panel (status bar pill and popover) is a presentation layer over `BackgroundTaskRegistry`; it owns no work. Limits, stated in the panel itself where they affect the user:++- **Pause is per export-queue only.** Pause and Resume exist only for export-queue jobs, and they act on the whole queue (a queued row reads "Export queue is paused" and Resume starts the whole queue). A running export, proxy job, transcription, import, scene detection, beat detection or tracking run cannot be paused; those can be cancelled. The panel footer says so.+- **Import Cancel discards, it does not stop the decode.** The decode keeps running in the background and its result is thrown away. Retry re-runs the full import action; caller-specific follow-ups (for example placing the clip on the timeline) are not replayed.+- **Cleared rows stay cleared for the session**, including mirrored export-queue rows. A retried job shows again. Finished history (40 rows) is not persisted across reloads.+- **Proxy history is session-only.** A proxy that finished or was cancelled shows as such until cleared; proxies that were already ready when the editor loaded are not listed.+- **Not exercised on real footage or hardware:** scene detection, beat detection, transcription, motion tracking, desktop copy-to-project and the desktop native proxy rows, and import cancel on large media. They are covered by typecheck, registry unit tests and synthetic e2e only.+- The popover opens upward over the timeline; it has no pin or dock mode.++## Keyframe temporal interpolation++- **Numeric properties only.** Auto Bezier and Continuous Bezier need a numeric value to compute a tangent; keys on non-numeric properties (colour strings, text) ignore those two types and keep their normal easing.+- **Hold belongs to a whole segment.** Hold is an outgoing type by definition (the value is held until the next key), so choosing Hold with "Both sides" applies it to the outgoing side only. Choosing Linear, Bezier or an Auto type on the In side of the key that follows a held segment converts that segment, because both ends share it. Ease In is always the In side and Ease Out always the Out side; the side menu is ignored for them.+- **Continuous Bezier always links both sides.** Applying it to one side links both. Editing a single handle keeps the link and mirrors the other side's tangent; replacing a whole segment (an ease preset, an easing change) unlinks it.+- **Handle time influence is preserved, not chosen.** Auto and Continuous re-derive the tangent (slope) and keep each handle's existing time length (one third for fresh Auto handles). There is no separate control for influence beyond dragging a handle, which converts an Auto side to plain Bezier.+- **The agent tool registry (`packages/agent`) does not expose the new types yet.** Agents can set easing and Bezier handles as before.++## Encoder choice and proxy presets++- **The browser capability probe asks WebCodecs about one representative profile per codec** (H.264 High L4.0, HEVC Main, AV1 Main, 5 Mbps) at the export size and frame rate. A machine can accept that and still refuse the project's exact bitrate or profile; the export then fails with the encoder's own message (Hardware and Software are strict, they never switch kind silently). Auto is the only choice that falls back.+- **Hardware encoding on the desktop is not offered with Two-pass VBR or Rec.2020 / HDR output** (hardware encoders have no two-pass mode; HDR needs libx265 for the HDR metadata). Choosing Hardware there is refused with the reason; Software and Auto work. A failed hardware encode with Hardware chosen is reported, not retried on the software encoder.+- **Hardware encoders (VideoToolbox, NVENC, Quick Sync, AMF) were exercised end to end only on VideoToolbox (macOS).** NVENC, Quick Sync and AMF are covered by argument and capability-mapping tests, not by a run on that hardware.+- **Create Proxies with a preset only targets clips that have no proxy (or a failed or missing one).** To rebuild an existing proxy in another preset, use Rebuild on the row after changing the preset in the Proxies panel.diff --git a/docs/releases/next.md b/docs/releases/next.mdindex b7593b3d..9ebd3b4f 100644--- a/docs/releases/next.md+++ b/docs/releases/next.md@@ -18,3 +18,32 @@- Look, LUT, saved-look and white balance cards: one Before / after switch for the whole Color tab, a Sample badge when a card shows the bundled sample scene, and posters are stamped so tests wait for the real render.- Particle preset cards: Soft Dissolve now emits across the frame (a visible dissolve, in the preview and on apply), Ambient Dust reads at card size, and every hover loop starts with particles already in flight.- Overlay and template polish, third pass: Overlays and Graphics > Templates cards in vertical or square projects now place your footage exactly as the Program monitor does (contained and letterboxed on black, never cover-cropped), from the real decoded playhead frame at its own aspect instead of the small import thumbnail, so they are crisp. Overlay cards are full panel width so a 12 px progress bar is a visible few pixels. The template modal hero plays the template's own animation on hover or keyboard focus (reduced motion keeps the still). Preview SVG and sticker clips now honour blend opacity like export, stickers can take a blend mode and opacity from the inspector, and motion instances mirror their 0..1 opacity on the clip's 0-100 Blend Opacity scale. The save-template dialog plays its exit animation. Verified in real Chrome: saved and cloud template thumbnails, a 4K long-task trace (no long tasks), and an export-versus-preview pixel test for blend opacity (`blend-opacity.spec.ts`).+- Clip markers and master-clip markers: M in the Source monitor (or the new Add marker button) drops a master-clip marker on the media; Alt+Shift+M on the timeline drops a clip marker on the selected clip (or the clip under the playhead). Marker times are stored in source seconds, so they follow the footage through trims, speed changes and reverse: master markers appear on every timeline instance at the right offset (flags along the clip's lower edge, range markers as bars; ticks on the Source monitor scrubber). The Markers panel has a Sequence / Clips switch; Clips lists each instance's markers at timeline time (click to seek, double-click to rename, delete), with the rows of selected clips highlighted. All edits are one undoable `clipmarker/set` action. XMEML export writes clip and master markers into each clipitem (source frames) and import reads them back as clip markers. Unit tests cover offset mapping with in point, speed, reverse and range markers (`editing/clip-markers.test.ts`); e2e in `apps/web/e2e/clip-markers.spec.ts`. Not carried: FCPXML / OTIO / AAF clip markers, markers on nested-sequence clips, and variable-speed (speed ramp) mapping, which uses the constant-speed map.++- Source monitor history and Reverse Match Frame: the Source monitor title is now a recent-clips dropdown (last 10 clips loaded this session, most recent first) and Shift+F (Edit menu, or "Find in sequence" in the Source monitor) finds the frame showing in the Source monitor in the active sequence and moves the playhead there, selecting the clip. The topmost video track wins (hidden tracks skipped, audio-only sources fall back to audio tracks), the instance nearest the playhead wins within a track, and speed changes, reverse and speed ramps are inverted with the same mapping the renderer uses. A frame that is not in the sequence leaves the playhead alone and shows a toast. Match Frame (F) is unchanged.++- Planar tracking (Effects tab > Planar Tracking): track a flat surface by its four corners and pin a clip above it. Drag the corner quad on the Program monitor (or type the corners), then track the whole clip, forward or backward from the playhead, with progress and cancel. Shi-Tomasi features inside the quad are followed with pyramidal Lucas-Kanade in a worker; every feature remembers its anchor-frame position, so a seeded RANSAC homography fitted anchor to current rejects occluders without accumulating drift. Frames where the surface is lost are flagged in the quality strip, and the corners of any frame can be edited by hand and re-tracked from there. "Pin Clip to Surface" adds a Corner Pin effect to the chosen clip with per-frame corner keyframes (`fx:` instance keyframes), so preview and export render the same pixels deterministically, and everything is one undo step. Homography estimation, RANSAC and the tracker have unit tests (`planar-homography.test.ts`, `planar-track.test.ts`); the browser flow is `apps/web/e2e/planar-track.spec.ts`.++- White Balance eyedropper (Color tab > White Balance): pick a neutral grey or white area on the Program monitor and Temperature / Tint are set so that sample becomes neutral, like Lumetri's WB Selector. Choose a single pixel or a 5x5 average; the cursor becomes a crosshair with a footprint box and a live "Temp / Tint" read-out, Esc or right-click cancels, and a click applies and disarms. The sample is the clip as the white balance stage sees it: on a plain clip that is the Program canvas, and when later grade stages (tone, curves, wheels, LUT, look on the default Premiere-order pipeline) or an active white balance would change the picture, the monitor re-renders that stage input once, preview-only, while the visible frame is held still, so contrast or a look never skews the result. It works the same on the GPU and Canvas2D paths, picking again never compounds, and the pick is exactly one undo step. A strongly coloured sample is applied but flagged "not neutral" in the read-out and the toast. Clipped black / white samples and keyframed white balance are refused with a message. The neutralising maths is a closed form over the same offsets the preview, export and HDR grade use (`white-balance-eyedropper.test.ts` checks it against `prepareHdrGrade`). Verified on real footage with a cast and a contrast stage (v1 and v2 pipelines) in `apps/web/e2e/color-wb-eyedropper.spec.ts` and `fallback-color-wb-eyedropper.spec.ts`.+- Camera log input presets. Interpret Footage has a new "Camera input (log)" group and the Color tab has a "Camera input" picker (above the Input LUT) with built-in, formula-based transforms from the published manufacturer specifications, no LUT files: Sony S-Log3 / S-Gamut3.Cine, Panasonic V-Log / V-Gamut, ARRI LogC3 (EI 800) / AWG3 and LogC4 / AWG4, Canon C-Log3 / Cinema Gamut, Nikon N-Log (Rec.2020), Fujifilm F-Log and F-Log2 (Rec.2020) and Blackmagic Film Gen5 / Wide Gamut. Each converts log to scene-linear (18% grey = 0.18), maps the camera gamut to Rec.709 (matrices derived from the published primaries) and rolls highlights off with the shared shoulder, so footage looks neutral and exposure-correct rather than graded. The same curve runs in the preview, scopes and export CPU input transform, the CPU HDR reference and the WebGL2 HDR compositor shader (generated from the same constants), so they cannot disagree. The setting is the media item's Interpret Footage colour setting: one undoable step shared by every clip of that footage. Verified by unit tests against published reference values (`packages/core/src/color/camera-log.test.ts`: 0%, 18% grey and 90% white code values, segment joins, gamut matrices, shader source evaluated against the TypeScript curve) and on real pixels in `apps/web/e2e/camera-log.spec.ts` (WebGL2 shader against the CPU reference for all nine curves; the picker against the CPU transform).+- Voice-over recording is now a proper Premiere-style tool (Audio > Voiceover). Pick the input from the device list (remembered between sessions, with a fallback to the system default when a saved microphone is unplugged), watch the live input meter (and "Check level" before you commit), choose the destination audio track, set a 0 to 5 s pre-roll and press Record: the timeline plays from the pre-roll start while the countdown runs, recording begins exactly at the playhead and playback is muted for the take (optional, on by default) so speakers cannot bleed into the microphone. With In and Out marks set, "Punch in / out" records only between them and stops by itself. Each take is named "Voice Over Take N", listed in the Takes list, and lands as an ordinary audio clip; recording over a range that is already taken stacks the new take on a new "Voice Over N" track instead of overlapping, and one undo removes the whole take (track, name and clip together). Desktop: the app now declares the microphone and camera to macOS (usage descriptions plus the audio-input and camera hardened-runtime entitlements), asks the operating system for access before the first take, explains a denied or restricted state with an "Open microphone settings" shortcut, and only grants media permissions to its own pages. Unit tests cover the timing and placement rules (`voiceover-logic.test.ts`) and the desktop permission policy; `apps/web/e2e/voiceover.spec.ts` records against Chrome's fake microphone.+- Audio output device picker and solo-safe tracks. Choose the speakers or headphones used for preview in Settings > General > Audio Output or in the Audio Mixer header (also `AudioOutputSelect` in the mixer). The choice is applied with `AudioContext.setSinkId` (Chromium, Electron), or through a hidden media element's `setSinkId` where only that exists, is remembered between sessions, and when the device is unplugged playback continues on the system default with a toast; it switches back (with a second toast) when the device returns. Exports render offline and are unaffected. Solo Safe (the SF button on each mixer strip, "Solo Safe" in the track header menus, `set_track_solo_safe` for the agent) keeps a track playing while other tracks are soloed, in live playback, scrubbing and the export mixdown; mute still wins. It is one undo step and saved with the project (`track.soloSafe`, absent on older projects = off). The mute/solo/solo-safe rule lives in `packages/core/src/audio/track-audibility.ts` and is covered by an exhaustive matrix test; verified end to end in `apps/web/e2e/audio-output-solo-safe.spec.ts`.++- Echo and Posterize Time, Premiere's two missing Time effects, are in the Effects panel under a new Time filter (and the inspector effect picker). Posterize Time holds the clip at a fixed frame rate (0 is off; the default is Premiere's 1 fps): the frame shown is the one at the start of the held interval on the clip-local timeline (`floor(t * fps) / fps`, float-safe, through the clip's speed), so it is the very frame the unprocessed clip shows there. Echo (echo time, number of echoes up to 32, starting intensity, decay, operator Add / Maximum / Minimum / Screen / Composite in Back / Composite in Front) combines the current frame with the frames at `t - k * echoTime` (a positive echo time reaches back; the default is 0.033 s, one frame at 30 fps), weighted `startIntensity * decay^k`; echoes that would fall outside the clip show nothing. Effects above the Echo in the stack are applied to every echo frame (sampled at that frame's own time), the ones below see the combined frame. Both are keyframable, and the frame choice is a pure function of the clip-local time, so preview, scrubbing, the render cache and export pick identical frames. Clips with these effects play through the same engine renderer export uses. The Effects cards play real footage: Echo rests a few frames into the window with its trail (and the trail builds up from the first frame on hover), Posterize Time holds frames while it plays. Verified on real pixels in `apps/web/e2e/time-effects.spec.ts` (gpu) and `fallback-time-effects.spec.ts`: Posterize Time equals the plain frame at the start of the interval, an exported file holds the posterized frames, and Echo matches the reference composite of the plain frames for all six operators, in preview mode and export mode, in any render order.++- Timecode and Clip Name burn-in. Two new effects under Generate in the Effects panel and the inspector's Add Effect picker: Timecode draws sequence, source-file or clip timecode (drop-frame aware for 29.97 and 59.94, a Time display override, frames and feet + frames formats, an offset in frames, an optional second-field mark and a label) and Clip Name draws the clip name, file name (extension optional) or sequence name with an optional prefix. Both have position (nine anchors plus margin and offset), size, opacity, text colour and a background box. Text is resolved per frame from the clip's place on the timeline and in its source (speed and freeze frames respected) and drawn with Canvas2D at a fixed digit advance, so the monitor, playback, the Canvas2D fallback and export show identical digits for the same frame; adjustment layers and text, shape, SVG and sticker clips carry them too. Export > Burn in timecode is a one-click switch in the Export dialog (every video tab) that draws the sequence timecode, or the topmost clip's source timecode, over the whole picture including captions, with a position choice; it re-renders every frame (no stream copy). Verified on real pixels in the monitor, in `VideoEngine.renderFrame` and in an exported MP4 decoded with ffmpeg (`apps/web/e2e/burn-in.spec.ts` gpu, `fallback-burn-in.spec.ts` no-WebGPU and software), with unit tests for 29.97 and 59.94 drop-frame formatting and boundaries.++- Replace edit and Fit to Fill in the Source monitor (Premiere's remaining Source-monitor edit commands). Replace (Shift+G, button, Edit menu) swaps the footage of the selected timeline clip, else the topmost clip under the playhead (targeted tracks first), for the Source monitor's clip. The clip keeps its id, place, length, transitions and links; the Source playhead frame is lined up with the timeline playhead, or the source In (media start when unmarked) lands on the clip's first frame when the playhead is outside the clip. A Keep FX toggle keeps (default) or resets the clip's effects, keyframes, transform, audio settings and fades; the old footage's speed, ramps, freeze frames and stabilization never carry over, and linked audio of the same footage is replaced with the picture. It refuses, changing nothing, when the source is too short, the aligned frame is before the media start, a track is locked, the kinds do not match or a restricted subclip would be exceeded. Fit to Fill (Alt+Shift+F, button, Edit menu) retimes the source In/Out range (the whole media when unmarked) to exactly fill the timeline In/Out range and overwrites it onto the patched / targeted tracks, with video and audio patched to separate linked tracks at the same speed; audio keeps its pitch through the existing pitch-correction default. The needed speed is shown in the confirmation and refused outside the 10%-2000% clip speed limits (now one shared constant). Both are single undo steps through the timeline action path; neither ripples, so Sync Lock has nothing to shift (locked tracks are refused). Fixed a Replace-blocking validation bug: a footage swap was bounded by the old media's duration. Covered by `replace-fit.test.ts` and `apps/web/e2e/replace-fit.spec.ts`.+- Clip > Audio Channels… (Premiere "Modify > Audio Channels"): map a clip's source channels onto mono, stereo or 5.1 clip channels for one clip or a whole selection. The dialog has a Preset (Use file, Mono = first channel, Stereo), and 5.1 sources keep all six channels for the mapping in preview, waveforms and export (stereo sequences included), a clip channel format, a source-channel grid with Mix and Off columns, quick Left only / Right only / Swap L/R buttons, and Split to mono clips, which breaks any clip with multichannel audio (audio files and video with embedded audio) out to in-sync mono clips on separate tracks. Everything is one undo step (`audio/setChannelMap`, multi-clip safe). The mapping is applied to the decoded source, so preview playback (realtime graph, scrub grains, stretched renders), the offline mixdown used by export, compound audio, metering and the timeline waveform (recomputed from the mapped channels) all agree. Preferences > Audio > Default audio channels stamps new imports with Mono or Stereo (Use file by default). Matrix, action and undo covered by `channel-map.test.ts` and `channel-actions.test.ts`; real mixdown checked in `apps/web/e2e/audio-channels.spec.ts`.++- Speaker diarization: Transcript > "Detect speakers" labels the caption cues "Speaker 1..N" fully on device (no upload). Each cue's audio is voice-printed in a worker (MFCC statistics plus pitch, no model download), clustered by average-linkage cosine distance (Auto finds the speaker count from the clearest gap in the merge distances, validated on real two-voice AAC audio; or fix the count), and short A-B-A flickers are smoothed; cues with no usable audio take the nearest speaker in time. Speakers are saved with the project (`Project.speakers`), shown with a colour in the transcript, renameable (renaming onto another speaker merges them), reassignable per passage, and each speaker's colour and caption position (Top / Centre / Bottom) are baked onto their cues so preview and every export render the same. Detect, rename, reassign and recolour are each one undo step (`speaker/apply`). Re-running Detect keeps renamed speakers (a voice maps back onto the speaker it overlaps most), drops stale profiles, and clearing a passage's speaker restores its original caption look. The speaker list is one collapsed line (Edit expands it). The panel and docs/known-limitations.md state that matching is approximate (similar voices can merge or split, overlapping speech is not separated); a clip with no audio track gets its own message. Unit tests use synthetic embeddings and synthetic voices; e2e (real two-voice fixture, Auto detection, rename, clear, re-detect) in `apps/web/e2e/diarization.spec.ts`.++- Caption translation: Transcript panel > Translate turns the active caption track into a new track in another language (timing, speaker and style of every cue are kept; word timings are dropped because translated words no longer line up). It uses the AI model connected for the AI editor when there is one, otherwise the browser's on-device Translator API (Chrome 138+, language packs download on first use), and says plainly when neither is available instead of producing stand-in text. Translation runs in batches with a progress bar and Cancel, commits nothing unless every batch succeeds, and the new track is one undo step.++- Ultra Key (Keying category): a Premiere-style chroma keyer as a keyframable effect. Matte generation (transparency, highlight, shadow, tolerance, pedestal), matte cleanup (choke, soften, contrast, mid point), spill suppression (desaturate, range, spill, luma), colour correction (saturation, hue, luminance) and Composite / Alpha channel / Colour channel / Source outputs. The inspector has a key-colour eyedropper that samples the Program monitor, and the Effects card previews the real key on your footage. One shared implementation drives the WebGL2 shader, the Canvas2D fallback and export; unit tests cover the key math and Playwright (gpu and no-WebGPU projects) keys a generated green-screen clip and compares the shader to the CPU reference (`ultra-key.test.ts`, `ultra-key.spec.ts`, `fallback-ultra-key.spec.ts`).+- Unified background-task panel: a status bar at the bottom of the editor shows a live count and progress; clicking it opens one Background tasks popover listing every long-running job with progress, ETA and cancel / pause / resume / retry where the owning system supports it: export-queue jobs (queued jobs pause and resume with the queue) and direct exports, proxy generation (in-app and desktop native), desktop copy-to-project, local caption and multicam transcription, media imports (Cancel stops before the media is added; Retry re-runs the same row and adds the media), scene edit detection, beat detection and motion tracking. Finished runs stay as history, failures show their error. It is a presentation layer over one `BackgroundTaskRegistry` in core (`tasks/task-registry`): existing job systems mirror their state in and keep owning the work, so there is no second job system.++- Keyframe temporal interpolation (Premiere): right-click a keyframe (graph or list; the menu ticks the current type) or use the Interpolation menu to apply Linear, Bezier, Auto Bezier, Continuous Bezier, Hold, Ease In or Ease Out to the selection as one undo step, to both sides of each key or to its In or Out side only (the Interpolation side menu). Every key has an independent incoming and outgoing type, shown in the list as "In X · Out Y". Auto Bezier derives smooth, overshoot-free tangents and re-derives them when a neighbour moves; Continuous Bezier keeps both handles of a key tangent-linked while you drag either one. A smooth side only ever rewrites the handle it owns, so a hand-tuned handle at the other end of a shared segment is never overwritten, and dragging a handle on an Auto side converts that side to plain Bezier. Types bake into the existing bezier handles, so preview, export and the graph evaluate identically; older projects open unchanged (new optional `interpolationIn` / `interpolationOut` fields, gated by portable-edit version). Unit tests in `keyframe-interpolation.test.ts`, e2e in `keyframe-graph-editor.spec.ts`.+- Caption import now also reads TTML / DFXP / IMSC1 (clock, offset, frame and tick times, parent-relative timing, referential styles and regions mapped to the caption style and cue position, `ttm:agent` speakers) and YouTube SBV; SBV joins SRT, WebVTT, TTML, SCC and EBU-STL as an export format. Text files are decoded as UTF-8, UTF-16 (BOM) or Windows-1252, and every skipped cue or block is listed in the Transcript panel's notes with its line number.+- Multi-clip Speed/Duration with ripple. Clip > Speed/Duration... (Cmd/Ctrl+Alt+R) sets speed, duration, direction and Maintain Audio Pitch for every selected clip (linked audio follows) as one undo step, with Premiere's "Ripple edit, shifting trailing clips": trailing clips on each edited track shift by what the clip gained or lost, unlocked sync-locked tracks and markers open or close the same span, and shrinking is blocked when a sync-locked track holds media in the span it would close. With several clips, Duration is the combined length and scales each clip by the same factor. The Rate Stretch tool now works on a multi-selection: dragging one selected clip's edge scales every selected clip and ripples the rest (one undo step, bounded to 0.1x-20x), with a ghost on every stretched clip; hold Alt while dragging to stretch without rippling (a clip then cannot grow into its neighbour). Linked audio always follows a speed change, even with Linked Selection off. Core planner `planClipSpeedEdit` in `packages/core/src/editing/clip-speed-edit.ts` (unit tests alongside, `apps/web/e2e/ripple-speed.spec.ts` for the UI).+- Encoder picker and proxy presets: the export dialog has an Encoder choice (Auto, Hardware, Software) for H.264, H.265 and AV1. On desktop it lists what the ffmpeg sidecar verified on this machine (VideoToolbox, NVENC, Quick Sync, AMF) and in the browser what WebCodecs reports; a choice the machine cannot run is disabled with the reason, and Hardware never silently falls back. Proxy presets (ProRes Proxy, H.264 1/2, H.264 1/4, DNxHR LB) are selectable in the Proxies panel, apply to new imports, are saved with the project, and are also offered in a Create Proxies dialog; ProRes and DNxHR proxies get an H.264 preview twin so the toggle-proxies button keeps working.diff --git a/packages/agent/src/registry.pro-edit-tools.test.ts b/packages/agent/src/registry.pro-edit-tools.test.tsindex 8b89e97e..626ca24b 100644--- a/packages/agent/src/registry.pro-edit-tools.test.ts+++ b/packages/agent/src/registry.pro-edit-tools.test.ts@@ -119,7 +119,7 @@ describe("premiere-parity agent tools: registration", () => {...premiere.scopes.tools,];for (const name of listed) expect(getTool(name), name).toBeDefined();- expect(proEffects).toHaveLength(44);+ expect(proEffects).toHaveLength(47);expect(proEffects.map((e) => e.type)).toContain("halftone");});@@ -491,13 +491,13 @@ describe("scopes tools", () => {});describe("pro effects through add_video_effect", () => {- it("lists all 44 pro effects with ranges, defaults and neutral values", async () => {+ it("lists all 47 pro effects with ranges, defaults and neutral values", async () => {const { host } = setup();const all = await executeTool("list_pro_effects", {}, host);expect(all.ok).toBe(true);const list = all.data as Array<{ type: string; params: Array<{ key: string; default: unknown; neutral: unknown }> }>;expect(list.map((e) => e.type).sort()).toEqual([...PRO_EFFECT_TYPES].sort());- expect(list).toHaveLength(44);+ expect(list).toHaveLength(47);for (const effect of list) {expect(effect.params.length).toBeGreaterThan(0);for (const p of effect.params) expect(p).toHaveProperty("neutral");diff --git a/packages/agent/src/registry.pro-effects.test.ts b/packages/agent/src/registry.pro-effects.test.tsindex 1c0ce463..58967668 100644--- a/packages/agent/src/registry.pro-effects.test.ts+++ b/packages/agent/src/registry.pro-effects.test.ts@@ -21,7 +21,7 @@ describe("agent pro effects", () => {it("lists every pro effect and its params in the add_video_effect description", () => {const description = getTool("add_video_effect")?.description ?? "";for (const type of PRO_EFFECT_TYPES) expect(description).toContain(type);- expect(PRO_EFFECT_TYPES).toHaveLength(44);+ expect(PRO_EFFECT_TYPES).toHaveLength(47);expect(description).toContain("blurX 0..100");});diff --git a/packages/agent/src/registry.ts b/packages/agent/src/registry.tsindex 7c45cb5f..e30141f9 100644--- a/packages/agent/src/registry.ts+++ b/packages/agent/src/registry.ts@@ -15649,6 +15649,7 @@ const TOOLS: RegisteredTool[] = [actionTool({ name: "set_track_sync_lock", domain: "track", actionType: "track/setSyncLock", title: "Set track sync lock", description: "Turn a track's Sync Lock on or off (default on). Ripple-type edits (ripple delete, ripple trim, insert, extract, paste-insert, close gap) keep sync-locked tracks in sync by shifting them with the edit, or are blocked (naming the track) when the removed range is not empty there; tracks with Sync Lock off are never touched by edits to other tracks. One undo step.", inputSchema: obj({ trackId: str, syncLock: bool }, ["trackId", "syncLock"]) }),actionTool({ name: "hide_track", domain: "track", actionType: "track/hide", title: "Hide track", description: "Show/hide a track.", inputSchema: obj({ trackId: str, hidden: bool }, ["trackId", "hidden"]) }),actionTool({ name: "mute_track", domain: "track", actionType: "track/mute", title: "Mute track", description: "Mute/unmute a track.", inputSchema: obj({ trackId: str, muted: bool }, ["trackId", "muted"]) }),+ actionTool({ name: "set_track_solo_safe", domain: "track", actionType: "track/setSoloSafe", title: "Set track solo safe", description: "Turn Solo Safe on or off for a track. A solo-safe track keeps playing (preview and export mixdown) while other tracks are soloed; mute still silences it. Saved with the project. One undo step.", inputSchema: obj({ trackId: str, soloSafe: bool }, ["trackId", "soloSafe"]) }),actionTool({ name: "solo_track", domain: "track", actionType: "track/solo", title: "Solo track", description: "Solo/unsolo a track.", inputSchema: obj({ trackId: str, solo: bool }, ["trackId", "solo"]) }),actionTool({ name: "consolidate_track", domain: "track", actionType: "track/consolidate", title: "Consolidate", description: "Close gaps on a track.", inputSchema: obj({ trackId: str }, ["trackId"]) }),diff --git a/packages/agent/src/serialize.ts b/packages/agent/src/serialize.tsindex 55b5b3ae..b0ffdf2e 100644--- a/packages/agent/src/serialize.ts+++ b/packages/agent/src/serialize.ts@@ -68,6 +68,8 @@ interface TrackView {readonly hidden: boolean;readonly muted: boolean;readonly solo: boolean;+ /** Solo Safe: stays audible while other tracks are soloed. */+ readonly soloSafe: boolean;readonly clipCount: number;}@@ -112,6 +114,7 @@ interface RawTrack {hidden?: boolean;muted?: boolean;solo?: boolean;+ soloSafe?: boolean;clips: RawClip[];}@@ -202,6 +205,7 @@ export function listTracks(project: Project): TrackView[] {hidden: t.hidden ?? false,muted: t.muted ?? false,solo: t.solo ?? false,+ soloSafe: t.soloSafe === true,clipCount: t.clips.length,}));}diff --git a/packages/core/src/actions/action-executor.ts b/packages/core/src/actions/action-executor.tsindex 10883f3f..67da6f55 100644--- a/packages/core/src/actions/action-executor.ts+++ b/packages/core/src/actions/action-executor.ts@@ -914,6 +914,17 @@ export class ActionExecutor {);break;}++ case "track/setSoloSafe": {+ const params = action.params as { trackId: string; soloSafe: boolean };+ timeline.tracks = timeline.tracks.map((t: MutableTrack) => {+ if (t.id !== params.trackId) return t;+ const { soloSafe: _previous, ...rest } = t as MutableTrack & { soloSafe?: boolean };+ void _previous;+ return params.soloSafe ? { ...rest, soloSafe: true } : rest;+ });+ break;+ }}}diff --git a/packages/core/src/actions/action-history.ts b/packages/core/src/actions/action-history.tsindex 5ffd5218..b4fd22f4 100644--- a/packages/core/src/actions/action-history.ts+++ b/packages/core/src/actions/action-history.ts@@ -64,6 +64,8 @@ const ACTION_DESCRIPTIONS: Record<"audio/toggleEffect": () => "Toggle audio effect","audio/setEssentialSound": (params) => (params.audioType ? `Set audio type: ${params.audioType}` : "Clear audio type"),"audio/setSurroundPan": (params) => (params.pan ? "Set surround position" : "Reset surround position"),+ "audio/setChannelMap": (params) => (params.map ? "Modify audio channels" : "Reset audio channels"),+ "audio/restoreChannelMaps": () => "Modify audio channels","audio/setLiveDucking": (params) => (params.config ? "Duck under dialogue" : "Remove ducking"),"subtitle/add": () => "Add subtitle","subtitle/remove": () => "Remove subtitle",diff --git a/packages/core/src/actions/action-validator.ts b/packages/core/src/actions/action-validator.tsindex 54d314ac..b0c586ec 100644--- a/packages/core/src/actions/action-validator.ts+++ b/packages/core/src/actions/action-validator.ts@@ -315,6 +315,7 @@ export class ActionValidator {case "track/hide":case "track/mute":case "track/solo":+ case "track/setSoloSafe":if (!action.params.trackId ||typeof action.params.trackId !== "string"@@ -384,6 +385,16 @@ export class ActionValidator {path: "params.solo",});}+ if (+ action.type === "track/setSoloSafe" &&+ typeof action.params.soloSafe !== "boolean"+ ) {+ errors.push({+ code: "INVALID_PARAMS",+ message: "soloSafe parameter must be a boolean",+ path: "params.soloSafe",+ });+ }break;case "track/reorder":diff --git a/packages/core/src/actions/channel-actions.test.ts b/packages/core/src/actions/channel-actions.test.tsnew file mode 100644index 00000000..01641d17--- /dev/null+++ b/packages/core/src/actions/channel-actions.test.ts@@ -0,0 +1,63 @@+import { describe, expect, it } from "vitest";+import { ActionExecutor } from "./action-executor";+import { ActionHistory } from "./action-history";+import type { Project } from "../types/project";+import type { Clip, Track } from "../types/timeline";+import type { ClipChannelMap } from "../audio/channel-map";++const clip = (id: string, channelMap?: ClipChannelMap): Clip =>+ ({+ id, mediaId: "m", trackId: "t1", startTime: 0, duration: 2, inPoint: 0, outPoint: 2,+ effects: [], audioEffects: [], transform: {} as Clip["transform"], volume: 1, keyframes: [],+ ...(channelMap ? { channelMap } : {}),+ }) as Clip;++const makeProject = (): Project => ({+ id: "p", name: "Channels", createdAt: 1, modifiedAt: 1,+ settings: { width: 1920, height: 1080, frameRate: 30, sampleRate: 48000, channels: 2 },+ mediaLibrary: { items: [] },+ timeline: {+ tracks: [+ { id: "t1", type: "audio", name: "A1", clips: [clip("c1"), clip("c2", { format: "stereo", sources: [1, 0] })], transitions: [], locked: false, hidden: false, muted: false, solo: false } as Track,+ ],+ subtitles: [], markers: [], duration: 2,+ },+});+const left: ClipChannelMap = { format: "mono", sources: [0] };+const clips = (project: Project) => project.timeline.tracks[0].clips;++describe("audio/setChannelMap", () => {+ it("maps several clips in one undo step and restores each clip's own previous map", async () => {+ const project = makeProject();+ const history = new ActionHistory();+ const executor = new ActionExecutor(history);+ const result = await executor.execute({ type: "audio/setChannelMap", id: "a1", timestamp: 2, params: { clipIds: ["c1", "c2"], map: left } }, project);+ expect(result.success, JSON.stringify(result.error)).toBe(true);+ expect(clips(project).map((c) => c.channelMap)).toEqual([left, left]);+ expect(history.getUndoStackSize()).toBe(1);+ await executor.undo(project);+ expect(clips(project)[0].channelMap).toBeUndefined();+ expect(clips(project)[1].channelMap).toEqual({ format: "stereo", sources: [1, 0] });+ await executor.redo(project);+ expect(clips(project).map((c) => c.channelMap)).toEqual([left, left]);+ });++ it("clears the map with null and undoes that too", async () => {+ const project = makeProject();+ const executor = new ActionExecutor(new ActionHistory());+ await executor.execute({ type: "audio/setChannelMap", id: "a2", timestamp: 2, params: { clipIds: ["c2"], map: null } }, project);+ expect("channelMap" in clips(project)[1]).toBe(false);+ await executor.undo(project);+ expect(clips(project)[1].channelMap).toEqual({ format: "stereo", sources: [1, 0] });+ });++ it("rejects unknown clips and malformed maps", async () => {+ const project = makeProject();+ const executor = new ActionExecutor(new ActionHistory());+ const missing = await executor.execute({ type: "audio/setChannelMap", id: "a3", timestamp: 2, params: { clipIds: ["nope"], map: left } }, project);+ expect(missing.success).toBe(false);+ const bad = await executor.execute({ type: "audio/setChannelMap", id: "a4", timestamp: 2, params: { clipIds: ["c1"], map: { format: "quad", sources: [] } } }, project);+ expect(bad.success).toBe(false);+ expect(clips(project)[0].channelMap).toBeUndefined();+ });+});diff --git a/packages/core/src/actions/handlers/audio-channels.ts b/packages/core/src/actions/handlers/audio-channels.tsnew file mode 100644index 00000000..5331bd72--- /dev/null+++ b/packages/core/src/actions/handlers/audio-channels.ts@@ -0,0 +1,109 @@+import type { Project } from "../../types/project";+import type { Action, ValidationResult } from "../../types/actions";+import type { Clip, Track } from "../../types/timeline";+import { sanitizeChannelMap, type ClipChannelMap } from "../../audio/channel-map";+import { registerActionHandler } from "../registry";+import type { ActionHandler } from "../registry";++interface SetChannelMapParams {+ readonly clipIds: readonly string[];+ /** The new mapping, or null to go back to the file's import default. */+ readonly map: ClipChannelMap | null;+}++const findClip = (project: Project, id: string): Clip | undefined => {+ for (const track of project.timeline.tracks) {+ const clip = track.clips.find((c) => c.id === id);+ if (clip) return clip;+ }+ return undefined;+};++/**+ * Modify > Audio Channels: sets (or clears) the channel map of one or many clips in one undo step.+ * The inverse restores every clip's previous map individually, so a multi-selection with+ * different starting maps undoes exactly.+ */+const audioSetChannelMap: ActionHandler = {+ type: "audio/setChannelMap",+ validate(action: Action, project: Project): ValidationResult {+ const params = action.params as unknown as SetChannelMapParams;+ const errors: { code: string; message: string }[] = [];+ if (!Array.isArray(params.clipIds) || params.clipIds.length === 0) {+ errors.push({ code: "INVALID_PARAMS", message: "Give at least one clip id" });+ } else {+ for (const id of params.clipIds) {+ if (!findClip(project, id)) errors.push({ code: "CLIP_NOT_FOUND", message: `Clip not found: ${id}` });+ }+ }+ if (params.map !== null && !sanitizeChannelMap(params.map)) {+ errors.push({ code: "INVALID_PARAMS", message: "map must be { format: mono | stereo | 5.1, sources: number[] } or null" });+ }+ return { valid: errors.length === 0, errors };+ },+ apply(action: Action, project: Project): void {+ const params = action.params as unknown as SetChannelMapParams;+ const map = params.map === null ? undefined : sanitizeChannelMap(params.map);+ const ids = new Set(params.clipIds);+ const set = (clip: Clip): Clip => {+ const { channelMap: _old, ...rest } = clip;+ void _old;+ return (map ? { ...rest, channelMap: map } : rest) as Clip;+ };+ const timeline = project.timeline as { tracks: Track[] };+ timeline.tracks = timeline.tracks.map((track) =>+ track.clips.some((c) => ids.has(c.id)) ? { ...track, clips: track.clips.map((c) => (ids.has(c.id) ? set(c) : c)) } : track,+ );+ },+ invert(action: Action, projectBefore: Project): Action | null {+ const params = action.params as unknown as SetChannelMapParams;+ const restore = params.clipIds.map((id) => ({ clipId: id, map: findClip(projectBefore, id)?.channelMap ?? null }));+ return {+ type: "audio/restoreChannelMaps",+ id: `inverse-${action.id}`,+ timestamp: Date.now(),+ params: { restore },+ };+ },+};++interface RestoreParams {+ readonly restore: readonly { readonly clipId: string; readonly map: ClipChannelMap | null }[];+}++/** Inverse of audio/setChannelMap: puts each clip's own previous map back. */+const audioRestoreChannelMaps: ActionHandler = {+ type: "audio/restoreChannelMaps",+ validate(action: Action, project: Project): ValidationResult {+ const params = action.params as unknown as RestoreParams;+ const errors = (params.restore ?? [])+ .filter((entry) => !findClip(project, entry.clipId))+ .map((entry) => ({ code: "CLIP_NOT_FOUND", message: `Clip not found: ${entry.clipId}` }));+ return { valid: errors.length === 0, errors };+ },+ apply(action: Action, project: Project): void {+ const params = action.params as unknown as RestoreParams;+ const byClip = new Map(params.restore.map((entry) => [entry.clipId, entry.map] as const));+ const timeline = project.timeline as { tracks: Track[] };+ timeline.tracks = timeline.tracks.map((track) =>+ track.clips.some((c) => byClip.has(c.id))+ ? {+ ...track,+ clips: track.clips.map((c) => {+ if (!byClip.has(c.id)) return c;+ const { channelMap: _old, ...rest } = c;+ void _old;+ const map = byClip.get(c.id);+ return (map ? { ...rest, channelMap: map } : rest) as Clip;+ }),+ }+ : track,+ );+ },+ invert(): Action | null {+ return null;+ },+};++registerActionHandler(audioSetChannelMap);+registerActionHandler(audioRestoreChannelMaps);diff --git a/packages/core/src/actions/handlers/clip-fx.ts b/packages/core/src/actions/handlers/clip-fx.tsindex 0ece8c53..b2d3eb69 100644--- a/packages/core/src/actions/handlers/clip-fx.ts+++ b/packages/core/src/actions/handlers/clip-fx.ts@@ -4,8 +4,7 @@ import { registerActionHandler } from "../registry";import type { ActionHandler } from "../registry";import { makeClipFieldHandler, findClip, patchClip } from "./clip-helpers";-const SPEED_MIN = 0.1;-const SPEED_MAX = 20;+import { CLIP_SPEED_MIN as SPEED_MIN, CLIP_SPEED_MAX as SPEED_MAX } from "../../editing/speed-limits";const isNumber = (v: unknown): v is number =>typeof v === "number" && Number.isFinite(v);diff --git a/packages/core/src/actions/handlers/clip-markers.ts b/packages/core/src/actions/handlers/clip-markers.tsnew file mode 100644index 00000000..9293a3b1--- /dev/null+++ b/packages/core/src/actions/handlers/clip-markers.ts@@ -0,0 +1,79 @@+import type { Action, ValidationResult } from "../../types/actions";+import type { Project } from "../../types/project";+import type { Marker } from "../../types/timeline";+import { MARKER_KINDS } from "../../types/timeline";+import { registerActionHandler, createInverseAction } from "../registry";+import { findClip, patchClip } from "./clip-helpers";++/**+ * `clipmarker/set`: replaces the markers of one clip (clip markers) or one media item+ * (master-clip markers) as a single undoable action. Marker times are source-media seconds.+ * `markers: []` clears them. The inverse is the same action carrying the previous list.+ */+export interface ClipMarkerSetParams {+ readonly clipId?: string;+ readonly mediaId?: string;+ readonly markers: readonly Marker[];+}++const validMarker = (m: unknown): boolean => {+ const x = m as Partial<Marker> | null;+ return (+ !!x &&+ typeof x.id === "string" &&+ typeof x.time === "number" &&+ Number.isFinite(x.time) &&+ x.time >= 0 &&+ typeof x.label === "string" &&+ typeof x.color === "string" &&+ (x.duration === undefined || (Number.isFinite(x.duration) && x.duration >= 0)) &&+ (x.kind === undefined || (MARKER_KINDS as readonly string[]).includes(x.kind))+ );+};++function validate(action: Action, project: Project): ValidationResult {+ const p = action.params as unknown as ClipMarkerSetParams;+ const errors: { code: string; message: string }[] = [];+ if ((p.clipId === undefined) === (p.mediaId === undefined))+ errors.push({ code: "INVALID_PARAMS", message: "Exactly one of clipId or mediaId is required" });+ else if (p.clipId !== undefined && !findClip(project, p.clipId))+ errors.push({ code: "CLIP_NOT_FOUND", message: "Clip not found" });+ else if (p.mediaId !== undefined && !project.mediaLibrary.items.some((i) => i.id === p.mediaId))+ errors.push({ code: "INVALID_PARAMS", message: "Media item not found" });+ if (!Array.isArray(p.markers) || !p.markers.every(validMarker))+ errors.push({ code: "INVALID_PARAMS", message: "markers must be a list of valid markers" });+ else if (new Set(p.markers.map((m) => m.id)).size !== p.markers.length)+ errors.push({ code: "INVALID_PARAMS", message: "marker ids must be unique" });+ return { valid: errors.length === 0, errors } as ValidationResult;+}++function apply(action: Action, project: Project): void {+ const p = action.params as unknown as ClipMarkerSetParams;+ const markers = p.markers.map((m) => ({ ...m }));+ if (p.clipId !== undefined) {+ patchClip(project, p.clipId, { markers: markers.length ? markers : undefined });+ return;+ }+ const library = project.mediaLibrary as { items: Project["mediaLibrary"]["items"] };+ library.items = library.items.map((item) => {+ if (item.id !== p.mediaId) return item;+ const next = { ...item, markers };+ if (!markers.length) delete (next as { markers?: unknown }).markers;+ return next;+ });+}++function invert(action: Action, before: Project): Action | null {+ const p = action.params as unknown as ClipMarkerSetParams;+ const prior =+ p.clipId !== undefined+ ? findClip(before, p.clipId)?.markers+ : before.mediaLibrary.items.find((i) => i.id === p.mediaId)?.markers;+ if (p.clipId !== undefined && !findClip(before, p.clipId)) return null;+ const params: Record<string, unknown> = { markers: (prior ?? []).map((m) => ({ ...m })) };+ if (p.clipId !== undefined) params.clipId = p.clipId;+ else params.mediaId = p.mediaId;+ return createInverseAction(action, "clipmarker/set", params);+}++registerActionHandler({ type: "clipmarker/set", validate, apply, invert });diff --git a/packages/core/src/actions/handlers/index.ts b/packages/core/src/actions/handlers/index.tsindex 4ed64b3d..33a4be06 100644--- a/packages/core/src/actions/handlers/index.ts+++ b/packages/core/src/actions/handlers/index.ts@@ -4,6 +4,7 @@ import "./bulk-set";import "./effect-presets";import "./overlay";import "./saved-styles";+import "./speakers";import "./motion";import "./creation";import "./multicam";@@ -15,3 +16,5 @@ import "./audio-rack";import "./audio-routing";import "./track-automation";import "./audio-surround";+import "./clip-markers";+import "./audio-channels";diff --git a/packages/core/src/actions/handlers/speakers.ts b/packages/core/src/actions/handlers/speakers.tsnew file mode 100644index 00000000..494f1c0b--- /dev/null+++ b/packages/core/src/actions/handlers/speakers.ts@@ -0,0 +1,53 @@+import type { Project } from "../../types/project";+import type { Action, ValidationResult } from "../../types/actions";+import type { Subtitle } from "../../types/timeline";+import type { MutableTimeline } from "../../utils/immutable-updates";+import type { SpeakerProfile } from "../../captions/diarization";+import { registerActionHandler, type ActionHandler } from "../registry";++/**+ * speaker/apply {subtitles?, profiles?}: set the caption cues and/or the+ * project's speaker profiles in one undo step (diarize, rename, reassign,+ * recolour). Omitted parts are left alone; the inverse restores both.+ */++const bad = (message: string): ValidationResult => ({ valid: false, errors: [{ code: "INVALID_PARAMS", message }] });++const speakerApply: ActionHandler = {+ type: "speaker/apply",+ validate(action) {+ const p = action.params as { subtitles?: unknown; profiles?: unknown };+ if (p.subtitles === undefined && p.profiles === undefined) return bad("subtitles or profiles is required");+ if (p.subtitles !== undefined && !Array.isArray(p.subtitles)) return bad("subtitles must be a list");+ if (p.profiles !== undefined) {+ if (!Array.isArray(p.profiles)) return bad("profiles must be a list");+ const names = new Set<string>();+ for (const profile of p.profiles as Array<Partial<SpeakerProfile>>) {+ if (typeof profile?.name !== "string" || !profile.name.trim() || typeof profile.color !== "string")+ return bad("each profile needs a name and a colour");+ if (names.has(profile.name)) return bad(`Duplicate speaker: ${profile.name}`);+ names.add(profile.name);+ }+ }+ return { valid: true, errors: [] };+ },+ apply(action: Action, project: Project) {+ const p = action.params as { subtitles?: Subtitle[]; profiles?: SpeakerProfile[] };+ if (p.subtitles) (project.timeline as MutableTimeline).subtitles = p.subtitles;+ if (p.profiles) (project as { speakers?: readonly SpeakerProfile[] }).speakers = p.profiles;+ },+ invert(action: Action, projectBefore: Project): Action | null {+ const p = action.params as { subtitles?: Subtitle[]; profiles?: SpeakerProfile[] };+ return {+ type: "speaker/apply",+ id: `inverse-${action.id}`,+ timestamp: Date.now(),+ params: {+ ...(p.subtitles ? { subtitles: projectBefore.timeline.subtitles.map((s) => ({ ...s })) } : {}),+ ...(p.profiles ? { profiles: (projectBefore.speakers ?? []).map((s) => ({ ...s })) } : {}),+ },+ };+ },+};++registerActionHandler(speakerApply);diff --git a/packages/core/src/actions/inverse-action-generator.ts b/packages/core/src/actions/inverse-action-generator.tsindex fda31e32..fa79e627 100644--- a/packages/core/src/actions/inverse-action-generator.ts+++ b/packages/core/src/actions/inverse-action-generator.ts@@ -379,6 +379,18 @@ export class InverseActionGenerator {});}+ case "track/setSoloSafe": {+ const track = timeline.tracks.find(+ (t) => t.id === action.params.trackId,+ );+ if (!track) return null;++ return this.createInverseAction(action, "track/setSoloSafe", {+ trackId: action.params.trackId,+ soloSafe: track.soloSafe === true,+ });+ }+case "track/solo": {const track = timeline.tracks.find((t) => t.id === action.params.trackId,diff --git a/packages/core/src/actions/speakers.test.ts b/packages/core/src/actions/speakers.test.tsnew file mode 100644index 00000000..230072ec--- /dev/null+++ b/packages/core/src/actions/speakers.test.ts@@ -0,0 +1,49 @@+import { describe, expect, it } from "vitest";+import { ActionExecutor } from "./action-executor";+import type { Action } from "../types/actions";+import type { Project } from "../types/project";++const makeProject = (): Project =>+ ({+ id: "p1",+ name: "Speakers",+ createdAt: 0,+ modifiedAt: 0,+ settings: { width: 1920, height: 1080, frameRate: 30, sampleRate: 48000, channels: 2 },+ timeline: { duration: 10, tracks: [], markers: [], subtitles: [{ id: "c1", text: "hi", startTime: 0, endTime: 1, speaker: "Ann" }] },+ mediaLibrary: { items: [] },+ }) as unknown as Project;++let n = 0;+const act = (params: Record<string, unknown>): Action =>+ ({ id: `s${++n}`, type: "speaker/apply", timestamp: Date.now() + n * 1000, params }) as unknown as Action;++describe("speaker/apply", () => {+ it("sets cues and profiles together; undo and redo restore both", async () => {+ const executor = new ActionExecutor();+ const project = makeProject();+ const result = await executor.execute(+ act({+ subtitles: [{ id: "c1", text: "hi", startTime: 0, endTime: 1, speaker: "Speaker 1" }],+ profiles: [{ name: "Speaker 1", color: "#4F9DFF", position: "top" }],+ }),+ project,+ );+ expect(result.success).toBe(true);+ expect(project.timeline.subtitles[0].speaker).toBe("Speaker 1");+ expect(project.speakers).toEqual([{ name: "Speaker 1", color: "#4F9DFF", position: "top" }]);++ expect((await executor.undo(project)).success).toBe(true);+ expect(project.timeline.subtitles[0].speaker).toBe("Ann");+ expect(project.speakers).toEqual([]);+ expect((await executor.redo(project)).success).toBe(true);+ expect(project.speakers?.[0].name).toBe("Speaker 1");+ });++ it("rejects duplicate or malformed profiles", async () => {+ const executor = new ActionExecutor();+ const dup = await executor.execute(act({ profiles: [{ name: "A", color: "#1" }, { name: "A", color: "#2" }] }), makeProject());+ expect(dup.success).toBe(false);+ expect((await executor.execute(act({}), makeProject())).success).toBe(false);+ });+});diff --git a/packages/core/src/animation/index.ts b/packages/core/src/animation/index.tsindex 10630f66..1533e1ce 100644--- a/packages/core/src/animation/index.ts+++ b/packages/core/src/animation/index.ts@@ -14,3 +14,4 @@ export * from "./evaluate-keyframes";export * from "./keyframe-properties";export * from "./keyframe-bezier";export * from "./keyframe-clipboard";+export * from "./keyframe-interpolation";diff --git a/packages/core/src/animation/keyframe-interpolation.test.ts b/packages/core/src/animation/keyframe-interpolation.test.tsnew file mode 100644index 00000000..bf7415bb--- /dev/null+++ b/packages/core/src/animation/keyframe-interpolation.test.ts@@ -0,0 +1,212 @@+import { describe, expect, it } from "vitest";+import type { Keyframe } from "../types/timeline";+import { AnimationEngine } from "../video/animation-engine";+import { evaluateKeyframesAt } from "./evaluate-keyframes";+import { effectiveBezierHandles, solveBezierEase } from "./keyframe-bezier";+import { applyKeyframeInterpolation, keyframeSideTypes, refreshSmoothKeyframes, refreshSmoothKeyframesAfterEdit, segmentTangents } from "./keyframe-interpolation";++const kf = (id: string, time: number, value: number, easing: Keyframe["easing"] = "linear"): Keyframe => ({ id, time, property: "opacity", value, easing });+const three = () => [kf("a", 0, 0), kf("b", 1, 1), kf("c", 2, 0.5)];+const byId = (keys: Keyframe[], id: string) => keys.find(k => k.id === id)!;++describe("applyKeyframeInterpolation", () => {+ it("hold clears the segment's handles and both owners' tags; linear resets only the chosen key's handles", () => {+ const start = three().map(k => ({ ...k, easing: "bezier" as const, bezierHandles: { in: { x: 0.2, y: 0.9 }, out: { x: 0.8, y: 0.1 } }, interpolationIn: "auto-bezier" as const, interpolationOut: "auto-bezier" as const }));+ const hold = applyKeyframeInterpolation(start, ["a"], "hold");+ expect(byId(hold, "a")).toMatchObject({ easing: "hold" });+ expect(byId(hold, "a").bezierHandles).toBeUndefined();+ expect(byId(hold, "a").interpolationOut).toBeUndefined();+ expect(byId(hold, "b").interpolationIn).toBeUndefined();+ expect(byId(hold, "b").interpolationOut).toBe("auto-bezier");+ const lin = applyKeyframeInterpolation(start, ["b"], "linear");+ // b's outgoing handle is linear, but the far end (c's incoming) is not b's to change.+ expect(byId(lin, "b").bezierHandles!.in).toEqual({ x: 1 / 3, y: 1 / 3 });+ expect(byId(lin, "a").bezierHandles!.out.y).toBeCloseTo(2 / 3, 9);+ expect(byId(lin, "b").interpolationIn).toBeUndefined();+ expect(byId(lin, "b").interpolationOut).toBeUndefined();+ expect(byId(lin, "c").interpolationIn).toBe("auto-bezier");+ // Linear on both ends of a segment collapses to plain linear easing.+ const both = applyKeyframeInterpolation(start, ["b", "c"], "linear");+ expect(byId(both, "b").easing).toBe("linear");+ expect(byId(both, "b").bezierHandles).toBeUndefined();+ });++ it("in and out types are independent per key", () => {+ const out = applyKeyframeInterpolation(three(), ["b"], "auto-bezier", "out");+ expect(byId(out, "b").interpolationOut).toBe("auto-bezier");+ expect(byId(out, "b").interpolationIn).toBeUndefined();+ const inOnly = applyKeyframeInterpolation(out, ["b"], "linear", "in");+ expect(keyframeSideTypes(byId(inOnly, "a"), byId(inOnly, "b"))).toMatchObject({ out: "auto-bezier" });+ const mixed = applyKeyframeInterpolation(three(), ["b"], "ease-in");+ expect(keyframeSideTypes(byId(mixed, "a"), byId(mixed, "b"))).toEqual({ in: "bezier", out: "linear" });+ const held = applyKeyframeInterpolation(three(), ["b"], "hold");+ expect(keyframeSideTypes(byId(held, "a"), byId(held, "b"))).toEqual({ in: "linear", out: "hold" });+ expect(keyframeSideTypes(byId(held, "b"), byId(held, "c"), false)).toEqual({ in: "hold", out: undefined });+ });++ it("an Auto side never overwrites a hand-tuned handle at the other end of a shared segment", () => {+ // a->b is hand-tuned (plain Bezier keys); b is Auto on its OUT side only.+ const tuned = three().map(k => (k.id === "a" ? { ...k, easing: "bezier" as const, bezierHandles: { in: { x: 0.3, y: 0.2 }, out: { x: 0.7, y: 0.65 } } } : k));+ const out = applyKeyframeInterpolation(tuned, ["b"], "auto-bezier", "out");+ expect(byId(out, "a").bezierHandles).toEqual(byId(tuned, "a").bezierHandles);+ // Even a full-both Auto on b only rewrites b's own incoming handle (P2 of a->b), leaving a's outgoing P1.+ const both = applyKeyframeInterpolation(tuned, ["b"], "auto-bezier");+ expect(byId(both, "a").bezierHandles!.in).toEqual({ x: 0.3, y: 0.2 });+ });++ it("bezier freezes the current shape into editable handles without changing the curve", () => {+ const out = applyKeyframeInterpolation(three(), ["a"], "bezier");+ expect(byId(out, "a").easing).toBe("bezier");+ const h = byId(out, "a").bezierHandles!;+ expect(solveBezierEase(0.37, h.in.x, h.in.y, h.out.x, h.out.y)).toBeCloseTo(0.37, 6);+ });++ it("auto bezier: smooth tangent equal on both sides, flat at ends and at extrema", () => {+ const out = applyKeyframeInterpolation([kf("a", 0, 0), kf("b", 1, 1), kf("c", 2, 3), kf("d", 3, 2)], ["b"], "auto-bezier");+ const ks = out.filter(k => k.property === "opacity").sort((x, y) => x.time - y.time);+ const a = ks[0] as Keyframe & { value: number }, b = ks[1] as Keyframe & { value: number }, c = ks[2] as Keyframe & { value: number };+ const tin = segmentTangents(a, b, effectiveBezierHandles(a)!).in;+ const tout = segmentTangents(b, c, effectiveBezierHandles(b)!).out;+ expect(tin).toBeCloseTo(1.5, 6);+ expect(tout).toBeCloseTo(1.5, 6);+ expect(byId(out, "b")).toMatchObject({ interpolationIn: "auto-bezier", interpolationOut: "auto-bezier" });+ // end key auto => flat+ const ends = applyKeyframeInterpolation(three(), ["a"], "auto-bezier");+ expect(effectiveBezierHandles(byId(ends, "a"))!.in.y).toBeCloseTo(0, 9);+ // extremum: b is a peak in three() => flat both sides+ const peak = applyKeyframeInterpolation(three(), ["b"], "auto-bezier");+ expect(effectiveBezierHandles(byId(peak, "b"))!.in.y).toBeCloseTo(0, 9);+ expect(effectiveBezierHandles(byId(peak, "a"))!.out.y).toBeCloseTo(1, 9);+ });++ it("auto bezier re-derives when a neighbour moves", () => {+ const tagged = applyKeyframeInterpolation([kf("a", 0, 0), kf("b", 1, 1), kf("c", 2, 3)], ["b"], "auto-bezier");+ const moved = tagged.map(k => (k.id === "c" ? { ...k, value: 5 } : k));+ const refreshed = refreshSmoothKeyframes(moved, new Set(["c"]));+ const b = byId(refreshed, "b") as Keyframe & { value: number };+ const c = byId(refreshed, "c") as Keyframe & { value: number };+ expect(segmentTangents(b, c, effectiveBezierHandles(b)!).out).toBeCloseTo(2.5, 6);+ });++ it("continuous bezier mirrors the edited side's tangent onto the other", () => {+ const start = applyKeyframeInterpolation([kf("a", 0, 0), kf("b", 1, 1), kf("c", 2, 3)], ["b"], "continuous-bezier");+ const edited = start.map(k => (k.id === "b" ? { ...k, easing: "bezier" as const, bezierHandles: { in: { x: 1 / 3, y: 0.9 }, out: { x: 2 / 3, y: 0.4 } } } : k));+ const out = refreshSmoothKeyframes(edited, new Set(["b:out"]));+ const a = byId(out, "a") as Keyframe & { value: number }, b = byId(out, "b") as Keyframe & { value: number }, c = byId(out, "c") as Keyframe & { value: number };+ const tout = segmentTangents(b, c, effectiveBezierHandles(b)!).out;+ expect(tout).toBeCloseTo(0.9 * 2 * 3, 6);+ expect(segmentTangents(a, b, effectiveBezierHandles(a)!).in).toBeCloseTo(tout, 6);+ });++ it("ease in / ease out flatten the correct side only", () => {+ const eo = applyKeyframeInterpolation(three(), ["a"], "ease-out");+ expect(effectiveBezierHandles(byId(eo, "a"))!.in).toEqual({ x: 1 / 3, y: 0 });+ expect(effectiveBezierHandles(byId(eo, "a"))!.out).toEqual({ x: 2 / 3, y: 2 / 3 });+ const ei = applyKeyframeInterpolation(three(), ["b"], "ease-in");+ expect(effectiveBezierHandles(byId(ei, "a"))!.out.x).toBeCloseTo(2 / 3, 9);+ expect(effectiveBezierHandles(byId(ei, "a"))!.out.y).toBe(1);+ expect(effectiveBezierHandles(byId(ei, "a"))!.in).toEqual({ x: 1 / 3, y: 1 / 3 });+ expect(byId(ei, "b").easing).toBe("linear");+ });++ it("multi-select applies to every selected key across properties and is deterministic", () => {+ const keys = [...three(), { ...kf("r1", 0, 0), property: "rotation" }, { ...kf("r2", 1, 90), property: "rotation" }];+ const a = applyKeyframeInterpolation(keys, ["a", "r1"], "ease-out");+ expect(byId(a, "r1").easing).toBe("bezier");+ expect(byId(a, "a").easing).toBe("bezier");+ expect(applyKeyframeInterpolation(keys, ["a", "r1"], "ease-out")).toEqual(a);+ });++ it("preview, export and graph evaluate the baked curve identically", () => {+ const keys = applyKeyframeInterpolation([kf("a", 0, 0), kf("b", 1, 1), kf("c", 2, 3)], ["b"], "auto-bezier");+ const engine = new AnimationEngine();+ for (const t of [0.1, 0.5, 0.9, 1.3, 1.8]) {+ const viaEval = evaluateKeyframesAt(keys, t).get("opacity")!;+ const sorted = [...keys].sort((x, y) => x.time - y.time);+ const i = t < 1 ? 0 : 1;+ const p = (t - sorted[i].time) / (sorted[i + 1].time - sorted[i].time);+ const e = engine.applyKeyframeEasing(p, sorted[i]);+ const expected = (sorted[i].value as number) + ((sorted[i + 1].value as number) - (sorted[i].value as number)) * e;+ expect(viaEval).toBeCloseTo(expected, 6);+ }+ });++ it("legacy keyframes without interpolation are untouched by refresh", () => {+ const legacy = [kf("a", 0, 0, "ease-in"), kf("b", 1, 1, "bezier")];+ expect(refreshSmoothKeyframes(legacy)).toEqual(legacy);+ });+});++describe("user edits on smooth keys", () => {+ const edit = (prior: Keyframe[], id: string, updates: Partial<Keyframe>) =>+ refreshSmoothKeyframesAfterEdit(prior, prior.map(k => {+ if (k.id !== id) return k;+ const next = { ...k, ...updates } as Record<string, unknown>;+ for (const [f, v] of Object.entries(updates)) if (v === undefined) delete next[f];+ return next as unknown as Keyframe;+ }));++ it("dragging one handle of an auto side keeps it and converts only that side to plain Bezier", () => {+ const auto = applyKeyframeInterpolation(three(), ["a", "b", "c"], "auto-bezier");+ const base = byId(auto, "b").bezierHandles!;+ const handles = { in: { x: 0.5, y: 0.1 }, out: base.out };+ const out = edit(auto, "b", { easing: "bezier", bezierHandles: handles });+ expect(byId(out, "b").bezierHandles).toEqual(handles);+ expect(byId(out, "b").interpolationOut).toBeUndefined();+ expect(byId(out, "b").interpolationIn).toBe("auto-bezier");+ expect(byId(out, "c").interpolationIn).toBe("auto-bezier");+ });++ it("dragging the entering handle clears the far key's incoming tag", () => {+ const auto = applyKeyframeInterpolation(three(), ["a", "b", "c"], "auto-bezier");+ const handles = { in: byId(auto, "a").bezierHandles!.in, out: { x: 0.9, y: 0.7 } };+ const out = edit(auto, "a", { easing: "bezier", bezierHandles: handles });+ expect(byId(out, "a").bezierHandles).toEqual(handles);+ expect(byId(out, "b").interpolationIn).toBeUndefined();+ expect(byId(out, "b").interpolationOut).toBe("auto-bezier");+ });++ it("an ease preset on an auto-bezier key replaces the segment and clears both owners' tags", () => {+ const auto = applyKeyframeInterpolation(three(), ["a", "b", "c"], "auto-bezier");+ const preset = { in: { x: 0.42, y: 0 }, out: { x: 1, y: 1 } };+ const out = edit(auto, "b", { easing: "bezier", bezierHandles: preset });+ expect(byId(out, "b").bezierHandles).toEqual(preset);+ expect(byId(out, "b").interpolationOut).toBeUndefined();+ expect(byId(out, "c").interpolationIn).toBeUndefined();+ const lin = edit(auto, "b", { easing: "linear", bezierHandles: undefined });+ expect(byId(lin, "b").easing).toBe("linear");+ expect(byId(lin, "b").interpolationOut).toBeUndefined();+ });++ it("any path that changes easing drops a stale tag (no label/curve disagreement)", () => {+ const auto = applyKeyframeInterpolation([kf("a", 0, 0), kf("b", 1, 1), kf("c", 2, 3)], ["b"], "auto-bezier");+ const out = edit(auto, "b", { easing: "ease-in" });+ expect(byId(out, "b").interpolationOut).toBeUndefined();+ expect(keyframeSideTypes(byId(out, "a"), byId(out, "b")).out).toBe("ease-in");+ });++ it("continuous keys keep their link on a handle drag and mirror the other side", () => {+ const cont = applyKeyframeInterpolation(three(), ["b"], "continuous-bezier");+ const b = byId(cont, "b");+ const handles = { in: { x: 1 / 3, y: 0.9 }, out: b.bezierHandles?.out ?? { x: 2 / 3, y: 2 / 3 } };+ const out = edit(cont, "b", { easing: "bezier", bezierHandles: handles });+ const na = byId(out, "a") as Keyframe & { value: number }, nb = byId(out, "b") as Keyframe & { value: number }, nc = byId(out, "c") as Keyframe & { value: number };+ expect(nb.interpolationIn).toBe("continuous-bezier");+ expect(nb.interpolationOut).toBe("continuous-bezier");+ const tout = segmentTangents(nb, nc, effectiveBezierHandles(nb)!).out;+ expect(segmentTangents(na, nb, effectiveBezierHandles(na)!).in).toBeCloseTo(tout, 6);+ // Dragging the entering handle instead drives the outgoing one.+ const fromIn = edit(cont, "a", { easing: "bezier", bezierHandles: { in: byId(cont, "a").bezierHandles?.in ?? { x: 1 / 3, y: 1 / 3 }, out: { x: 0.6, y: 0.4 } } });+ const fa = byId(fromIn, "a") as Keyframe & { value: number }, fb = byId(fromIn, "b") as Keyframe & { value: number }, fc = byId(fromIn, "c") as Keyframe & { value: number };+ expect(fa.bezierHandles!.out).toEqual({ x: 0.6, y: 0.4 });+ expect(segmentTangents(fb, fc, effectiveBezierHandles(fb)!).out).toBeCloseTo(segmentTangents(fa, fb, effectiveBezierHandles(fa)!).in, 6);+ });++ it("time and value changes re-derive auto keys; legacy keys untouched", () => {+ const auto = applyKeyframeInterpolation(three(), ["a", "b", "c"], "auto-bezier");+ const moved = refreshSmoothKeyframesAfterEdit(auto, auto.map(k => (k.id === "c" ? { ...k, value: 2 } : k)));+ expect(byId(moved, "b").bezierHandles).not.toEqual(byId(auto, "b").bezierHandles);+ const legacy = three();+ expect(refreshSmoothKeyframesAfterEdit(legacy, legacy)).toEqual(legacy);+ });+});diff --git a/packages/core/src/animation/keyframe-interpolation.ts b/packages/core/src/animation/keyframe-interpolation.tsnew file mode 100644index 00000000..b2d66da1--- /dev/null+++ b/packages/core/src/animation/keyframe-interpolation.ts@@ -0,0 +1,328 @@+import type { Keyframe } from "../types/timeline";+import {+ LINEAR_BEZIER_HANDLES,+ clampBezierHandles,+ effectiveBezierHandles,+ type BezierHandlePoint,+ type BezierHandles,+} from "./keyframe-bezier";++/**+ * Premiere-style temporal interpolation for keyframes, with independent incoming and outgoing+ * types per key.+ *+ * Storage model (unchanged for the engines): each segment A->B lives on key A as `easing` plus+ * `bezierHandles` (P1 = in, the handle leaving A; P2 = out, the handle entering B). The two ends of+ * a segment therefore have distinct owners: P1 belongs to A's OUT side, P2 to B's IN side. Every+ * mode is baked into those handles so preview, export and the graph evaluate identically.+ *+ * "auto-bezier" and "continuous-bezier" are additionally persisted per side (`interpolationIn` /+ * `interpolationOut`) so a side's handle can be re-derived when neighbours move. A smooth side only+ * ever rewrites the handle it owns, so a hand-tuned handle on the other end of a shared segment is+ * never overwritten. Older projects lack the fields and are never touched.+ */+export const KEYFRAME_INTERPOLATION_OPS = [+ "linear",+ "bezier",+ "auto-bezier",+ "continuous-bezier",+ "hold",+ "ease-in",+ "ease-out",+] as const;+export type KeyframeInterpolationOp = (typeof KEYFRAME_INTERPOLATION_OPS)[number];+export type KeyframeInterpolationSide = "both" | "in" | "out";++export const KEYFRAME_INTERPOLATION_LABELS: Readonly<Record<KeyframeInterpolationOp, string>> = {+ linear: "Linear",+ bezier: "Bezier",+ "auto-bezier": "Auto Bezier",+ "continuous-bezier": "Continuous Bezier",+ hold: "Hold",+ "ease-in": "Ease In",+ "ease-out": "Ease Out",+};+export const KEYFRAME_INTERPOLATION_SIDE_LABELS: Readonly<Record<KeyframeInterpolationSide, string>> = {+ both: "Both sides",+ in: "In only",+ out: "Out only",+};++type Side = "in" | "out";+type SmoothTag = NonNullable<Keyframe["interpolationIn"]>;+const THIRD = 1 / 3;+const EPS = 1e-9;+const NONE: ReadonlySet<string> = new Set();+type NumKey = Keyframe & { value: number };+const isNum = (key: Keyframe): key is NumKey => typeof key.value === "number" && Number.isFinite(key.value);+const sideId = (id: string, side: Side) => `${id}:${side}`;+const tagField = (side: Side) => (side === "in" ? "interpolationIn" : "interpolationOut") as "interpolationIn" | "interpolationOut";+const samePoint = (a: BezierHandlePoint, b: BezierHandlePoint) => Math.abs(a.x - b.x) < 1e-6 && Math.abs(a.y - b.y) < 1e-6;++/** Value-per-second slope leaving a segment's start (P1) and arriving at its end (P2). */+export function segmentTangents(a: NumKey, b: NumKey, h: BezierHandles): { out: number; in: number } {+ const dt = b.time - a.time;+ const dv = b.value - a.value;+ const xo = Math.max(h.in.x, EPS);+ const xi = Math.max(1 - h.out.x, EPS);+ return { out: (h.in.y * dv) / (xo * dt), in: ((1 - h.out.y) * dv) / (xi * dt) };+}++type KeyMap = Map<string, Keyframe>;+type Order = readonly string[];++function groups(keys: readonly Keyframe[]): Order[] {+ const byProp = new Map<string, Keyframe[]>();+ for (const key of keys) byProp.set(key.property, [...(byProp.get(key.property) ?? []), key]);+ return [...byProp.values()].map(list => [...list].sort((a, b) => a.time - b.time).map(k => k.id));+}+const rebuild = (keys: readonly Keyframe[], m: KeyMap) => keys.map(k => m.get(k.id) ?? k);++function setTagField(key: Keyframe, field: "interpolationIn" | "interpolationOut", tag: SmoothTag | undefined): Keyframe {+ if (tag) return { ...key, [field]: tag };+ if (key[field] === undefined) return key;+ const next = { ...key } as Record<string, unknown>;+ delete next[field];+ return next as unknown as Keyframe;+}+/** Clearing one side of a Continuous pair unlinks both (a single continuous side has no meaning). */+function clearTag(m: KeyMap, id: string, side: Side): void {+ const key = m.get(id) as Keyframe;+ const other = tagField(side === "in" ? "out" : "in");+ let next = setTagField(key, tagField(side), undefined);+ if (key[tagField(side)] === "continuous-bezier" && next[other] === "continuous-bezier") next = setTagField(next, other, undefined);+ m.set(id, next);+}++/** Handles owned by a side: out side = P1 of the segment starting here; in side = P2 of the segment ending here. */+function segmentFor(order: Order, pos: number, side: Side): { segId: string; endId: string } | null {+ if (side === "out") return pos < order.length - 1 ? { segId: order[pos], endId: order[pos + 1] } : null;+ return pos > 0 ? { segId: order[pos - 1], endId: order[pos] } : null;+}+function handlesOf(m: KeyMap, segId: string): BezierHandles {+ return effectiveBezierHandles(m.get(segId) as Keyframe) ?? LINEAR_BEZIER_HANDLES;+}+function writePoint(m: KeyMap, segId: string, side: Side, point: BezierHandlePoint): void {+ const key = m.get(segId) as Keyframe;+ const h = handlesOf(m, segId);+ const handles = clampBezierHandles(side === "out" ? { in: point, out: h.out } : { in: h.in, out: point });+ m.set(segId, { ...key, easing: "bezier", bezierHandles: handles });+}+/** A segment whose two handles are exactly the identity curve is stored as plain linear. */+function normalizeLinear(m: KeyMap, segId: string): void {+ const key = m.get(segId) as Keyframe;+ if (key.easing !== "bezier" || !key.bezierHandles) return;+ const h = clampBezierHandles(key.bezierHandles);+ if (samePoint(h.in, LINEAR_BEZIER_HANDLES.in) && samePoint(h.out, LINEAR_BEZIER_HANDLES.out)) {+ const next = { ...key, easing: "linear" } as Record<string, unknown>;+ delete next.bezierHandles;+ m.set(segId, next as unknown as Keyframe);+ }+}+function makeHold(m: KeyMap, segId: string): void {+ const next = { ...(m.get(segId) as Keyframe), easing: "hold" } as Record<string, unknown>;+ delete next.bezierHandles;+ m.set(segId, next as unknown as Keyframe);+}+/** Smooth tangent at index k: Catmull-Rom slope, flat at ends and at local extrema (no overshoot). */+function autoTangent(keys: NumKey[], k: number): number {+ const prev = keys[k - 1];+ const next = keys[k + 1];+ if (!prev || !next) return 0;+ const d0 = keys[k].value - prev.value;+ const d1 = next.value - keys[k].value;+ if (d0 * d1 <= 0) return 0;+ const span = next.time - prev.time;+ return span > EPS ? (next.value - prev.value) / span : 0;+}++/** Slope of the side's own handle, in value units per second; undefined when the segment can't carry one. */+function readSlope(m: KeyMap, num: NumKey[], pos: number, side: Side): number | undefined {+ const seg = segmentFor(num.map(k => k.id), pos, side);+ if (!seg) return undefined;+ const a = m.get(seg.segId) as NumKey, b = m.get(seg.endId) as NumKey;+ if (a.easing === "hold" || !(b.time > a.time)) return undefined;+ const t = segmentTangents(a, b, handlesOf(m, seg.segId));+ return side === "out" ? t.out : t.in;+}+/** Points the side's own handle at `slope`, preserving its time influence unless `influence` is given. */+function writeSlope(m: KeyMap, num: NumKey[], pos: number, side: Side, slope: number, protect: ReadonlySet<string>): void {+ const seg = segmentFor(num.map(k => k.id), pos, side);+ if (!seg || protect.has(sideId(num[pos].id, side))) return;+ const a = m.get(seg.segId) as NumKey, b = m.get(seg.endId) as NumKey;+ if (a.easing === "hold" || !(b.time > a.time) || !Number.isFinite(slope)) return;+ const h = handlesOf(m, seg.segId);+ const dv = b.value - a.value;+ const dt = b.time - a.time;+ if (side === "out") {+ const x = h.in.x > EPS ? h.in.x : THIRD;+ writePoint(m, seg.segId, "out", { x, y: Math.abs(dv) > EPS ? (slope * x * dt) / dv : 0 });+ } else {+ const xi = 1 - h.out.x > EPS ? 1 - h.out.x : THIRD;+ writePoint(m, seg.segId, "in", { x: 1 - xi, y: Math.abs(dv) > EPS ? 1 - (slope * xi * dt) / dv : 1 });+ }+}++/**+ * Re-derives smooth sides: Auto sides always follow their neighbours; a Continuous key (both sides+ * tagged) mirrors the side in `edited` onto the other, or averages both when neither was edited.+ * Sides in `protect` are never rewritten. Keys without tags are never touched.+ */+export function refreshSmoothKeyframes(+ keyframes: readonly Keyframe[],+ edited: ReadonlySet<string> = NONE,+ protect: ReadonlySet<string> = NONE,+): Keyframe[] {+ if (!keyframes.some(k => k.interpolationIn || k.interpolationOut)) return [...keyframes];+ const m: KeyMap = new Map(keyframes.map(k => [k.id, k]));+ for (const order of groups(keyframes)) {+ const ordered = order.map(id => m.get(id) as Keyframe);+ if (!ordered.some(k => k.interpolationIn || k.interpolationOut)) continue;+ if (!ordered.every(isNum)) continue;+ const num = ordered as NumKey[];+ for (let pos = 0; pos < num.length; pos++) {+ const key = m.get(num[pos].id) as Keyframe;+ const tin = key.interpolationIn, tout = key.interpolationOut;+ if (tout === "auto-bezier") writeSlope(m, num, pos, "out", autoTangent(num, pos), protect);+ if (tin === "auto-bezier") writeSlope(m, num, pos, "in", autoTangent(num, pos), protect);+ if (tin === "continuous-bezier" && tout === "continuous-bezier") {+ const outSlope = readSlope(m, num, pos, "out");+ const inSlope = readSlope(m, num, pos, "in");+ const outEdited = edited.has(sideId(key.id, "out")) && outSlope !== undefined;+ const inEdited = edited.has(sideId(key.id, "in")) && inSlope !== undefined;+ if (outEdited && !inEdited) writeSlope(m, num, pos, "in", outSlope as number, protect);+ else if (inEdited && !outEdited) writeSlope(m, num, pos, "out", inSlope as number, protect);+ else if (!outEdited && !inEdited && (outSlope !== undefined || inSlope !== undefined)) {+ const o = (outSlope ?? inSlope) as number;+ const i = (inSlope ?? outSlope) as number;+ const slope = (o + i) / 2;+ writeSlope(m, num, pos, "out", slope, protect);+ writeSlope(m, num, pos, "in", slope, protect);+ }+ }+ }+ }+ return rebuild(keyframes, m);+}++/** Apply a temporal interpolation mode to one or both sides of the selected keyframes. Pure. */+export function applyKeyframeInterpolation(+ keyframes: readonly Keyframe[],+ ids: readonly string[],+ op: KeyframeInterpolationOp,+ side: KeyframeInterpolationSide = "both",+): Keyframe[] {+ const selected = new Set(ids);+ const m: KeyMap = new Map(keyframes.map(k => [k.id, k]));+ const touched = new Set<string>();+ const smooth = op === "auto-bezier" || op === "continuous-bezier";+ for (const order of groups(keyframes)) {+ order.forEach((id, pos) => {+ if (!selected.has(id)) return;+ const key = m.get(id) as Keyframe;+ // Hold is outgoing by definition; Ease In / Ease Out name their own side; Continuous links both.+ let sides: Side[] = side === "both" ? ["in", "out"] : [side];+ if (op === "hold" && side === "both") sides = ["out"];+ if (op === "ease-out") sides = side === "in" ? [] : ["out"];+ if (op === "ease-in") sides = side === "out" ? [] : ["in"];+ if (op === "continuous-bezier") sides = ["in", "out"];+ for (const s of sides) {+ const seg = segmentFor(order, pos, s);+ if (smooth) {+ if (isNum(key)) m.set(id, setTagField(m.get(id) as Keyframe, tagField(s), op));+ if (seg && (m.get(seg.segId) as Keyframe).easing === "hold") writePoint(m, seg.segId, s, s === "out" ? LINEAR_BEZIER_HANDLES.in : LINEAR_BEZIER_HANDLES.out);+ continue;+ }+ if (!seg) {+ if (op === "hold" && s === "out") m.set(id, { ...(m.get(id) as Keyframe), easing: "hold" });+ clearTag(m, id, s);+ continue;+ }+ touched.add(sideId(id, s));+ clearTag(m, id, s);+ const h = handlesOf(m, seg.segId);+ const numeric = isNum(m.get(seg.segId) as Keyframe);+ switch (op) {+ case "hold":+ makeHold(m, seg.segId);+ clearTag(m, seg.endId, "in");+ touched.add(sideId(seg.endId, "in"));+ break;+ case "linear":+ writePoint(m, seg.segId, s, s === "out" ? LINEAR_BEZIER_HANDLES.in : LINEAR_BEZIER_HANDLES.out);+ normalizeLinear(m, seg.segId);+ break;+ case "bezier":+ if (numeric) writePoint(m, seg.segId, s, s === "out" ? h.in : h.out);+ else m.set(seg.segId, { ...(m.get(seg.segId) as Keyframe), easing: "bezier" });+ break;+ case "ease-out":+ if (numeric) writePoint(m, seg.segId, "out", { x: THIRD, y: 0 });+ break;+ case "ease-in":+ if (numeric) writePoint(m, seg.segId, "in", { x: 1 - THIRD, y: 1 });+ break;+ }+ }+ });+ }+ // Explicit modes own the sides they touched; neighbouring smooth sides must not undo them.+ return refreshSmoothKeyframes(rebuild(keyframes, m), NONE, smooth ? NONE : touched);+}++/**+ * Re-derives smooth sides after any keyframe list change (time/value edits, add, delete, paste,+ * handle drags, presets). Sides whose handle differs from `prior` were set explicitly: they are+ * protected from re-derivation. Dragging one handle of an Auto side converts it to plain Bezier+ * (as Premiere does); Continuous keeps its link and mirrors the opposite handle; replacing a+ * whole segment (a preset, an easing change) unlinks Continuous too.+ */+export function refreshSmoothKeyframesAfterEdit(+ prior: readonly Keyframe[] | undefined,+ next: readonly Keyframe[],+): Keyframe[] {+ if (!next.some(k => k.interpolationIn || k.interpolationOut)) return [...next];+ const before = new Map((prior ?? []).map(k => [k.id, k]));+ const m: KeyMap = new Map(next.map(k => [k.id, k]));+ const edited = new Set<string>();+ for (const order of groups(next)) {+ order.forEach((id, pos) => {+ const old = before.get(id);+ const now = m.get(id) as Keyframe;+ const nextId = order[pos + 1];+ if (!old || !nextId) return;+ const oh = effectiveBezierHandles(old), nh = effectiveBezierHandles(now);+ let p1 = false, p2 = false;+ if (oh && nh) { p1 = !samePoint(oh.in, nh.in); p2 = !samePoint(oh.out, nh.out); }+ else if (oh !== nh || old.easing !== now.easing) { p1 = true; p2 = true; }+ if (p1) edited.add(sideId(id, "out"));+ if (p2) edited.add(sideId(nextId, "in"));+ if (p1 && p2) { clearTag(m, id, "out"); clearTag(m, nextId, "in"); }+ else {+ if (p1 && m.get(id)?.interpolationOut === "auto-bezier") clearTag(m, id, "out");+ if (p2 && m.get(nextId)?.interpolationIn === "auto-bezier") clearTag(m, nextId, "in");+ }+ });+ }+ return refreshSmoothKeyframes(rebuild(next, m), edited, edited);+}++export type KeyframeSideType = KeyframeInterpolationOp | Keyframe["easing"];++/**+ * The interpolation type each side of `key` currently has. `previous` is the earlier key of the+ * same property (its easing/handles describe the incoming side). Smooth tags win while their+ * segment is still a curve; a Hold segment always reads Hold on both of its ends.+ */+export function keyframeSideTypes(previous: Keyframe | undefined, key: Keyframe, hasNext = true): { in?: KeyframeSideType; out?: KeyframeSideType } {+ const describe = (seg: Keyframe, tag: SmoothTag | undefined): KeyframeSideType => {+ if (seg.easing === "hold") return "hold";+ if (tag) return tag;+ if (seg.easing === "bezier") return "bezier";+ return seg.easing;+ };+ return {+ in: previous ? describe(previous, key.interpolationIn) : undefined,+ out: hasNext ? describe(key, key.interpolationOut) : undefined,+ };+}diff --git a/packages/core/src/audio/audio-engine.ts b/packages/core/src/audio/audio-engine.tsindex 19749ae9..f3636481 100644--- a/packages/core/src/audio/audio-engine.ts+++ b/packages/core/src/audio/audio-engine.ts@@ -1,4 +1,5 @@import type { Timeline, Track, Clip, Effect } from "../types/timeline";+import { hasAnySoloedTrack, isTrackAudible } from "./track-audibility";import type { AudioEffectParams } from "../types/effects";import type { MediaItem, Project } from "../types/project";import type {@@ -34,6 +35,7 @@ import { AudioRoutingGraph, buildOfflineTrackChain } from "./audio-routing-graphimport { planTimelineDelayCompensation, rackLatencySamples } from "./effect-latency";import { scheduleClipFadeEnvelope } from "./clip-fade-envelope";import { getTrackTransitionAudioFades } from "./transition-audio-fades";+import { channelMapNeedsWideSource, mapAudioBuffer, resolveClipChannelMap, type ClipChannelMap } from "./channel-map";import { createSurroundPanner, fallbackDecodeChannels, isSurroundLayout, mixChannelCount, resolveSurroundPan } from "./surround";import {createRackBus,@@ -324,7 +326,9 @@ export class AudioEngine {const sampleRate = settings.sampleRate || this.config.sampleRate;const surround = isSurroundLayout(settings);const channels = mixChannelCount(settings, this.config.channels);- this.setDecodeSurround(surround);+ // Audio Channels: a clip mapped to 5.1 or to a source channel beyond L/R needs the file's own channels,+ // not the stereo fold-down the ffmpeg decode would otherwise give a stereo sequence.+ this.setDecodeSurround(surround || this.projectNeedsWideSources(project));const safeDuration = Math.max(duration, 0.001);const frameCount = audioFrameCount(safeDuration, sampleRate);// Plugin delay compensation: every path is aligned to the slowest, so the@@ -418,10 +422,7 @@ export class AudioEngine {trackInfo: AudioTrackRenderInfo,hasSoloTracks: boolean,): boolean {- if (trackInfo.muted) return true;- if (hasSoloTracks && !trackInfo.solo) return true;-- return false;+ return !isTrackAudible(trackInfo, hasSoloTracks);}/**@@ -432,15 +433,10 @@ export class AudioEngine {*/getEffectiveTrackAudibility(tracks: Track[]): Map<string, boolean> {const audibility = new Map<string, boolean>();- const hasSoloTracks = tracks.some((t) => t.solo);-- for (const track of tracks) {- // Track is audible if:- // 1. Not muted AND- // 2. Either no tracks are soloed OR this track is soloed- const isAudible = !track.muted && (!hasSoloTracks || track.solo);- audibility.set(track.id, isAudible);- }+ const hasSoloTracks = hasAnySoloedTrack(tracks);++ // Not muted AND (nothing soloed OR this track is soloed OR it is solo-safe).+ for (const track of tracks) audibility.set(track.id, isTrackAudible(track, hasSoloTracks));return audibility;}@@ -456,6 +452,7 @@ export class AudioEngine {const endTime = startTime + duration;const { timeline } = project;+ const mediaById = new Map(project.mediaLibrary.items.map((item) => [item.id, item] as const));timeline.tracks.forEach((track, index) => {if (track.hidden) return;const clips = this.getClipsInRange(track, startTime, endTime).filter(@@ -468,8 +465,9 @@ export class AudioEngine {index,muted: track.muted,solo: track.solo,+ ...(track.soloSafe === true ? { soloSafe: true } : {}),clips: clips.map((clip) =>- this.createClipRenderInfo(clip, startTime, endTime, timeline, track, preview, surround),+ this.createClipRenderInfo(clip, startTime, endTime, timeline, track, preview, surround, resolveClipChannelMap(clip, mediaById.get(clip.mediaId))),),});});@@ -496,6 +494,7 @@ export class AudioEngine {track: Track,preview: boolean,surround = false,+ channelMap?: ClipChannelMap,): AudioClipRenderInfo {const clipStart = Math.max(clip.startTime, rangeStart);const clipEnd = Math.min(clip.startTime + clip.duration, rangeEnd);@@ -525,6 +524,7 @@ export class AudioEngine {panAutomation: resolveClipPanAutomation(clip, timeline),pitchCorrection: resolveClipPitchCorrection(clip, timeline),...(surround ? { surroundPan: resolveSurroundPan(clip, track) } : {}),+ ...(channelMap ? { channelMap } : {}),effects: clipAudioEffects,fadeIn: clip.fade?.fadeIn,fadeOut: clip.fade?.fadeOut,@@ -573,6 +573,13 @@ export class AudioEngine {/** True while decoding for a 5.1 sequence: sources keep their own channels (up to 6) instead of being folded to stereo. */private decodeSurround = false;+ private projectNeedsWideSources(project: Project): boolean {+ const mediaById = new Map(project.mediaLibrary.items.map((item) => [item.id, item] as const));+ return project.timeline.tracks.some((track) =>+ track.clips.some((clip) => channelMapNeedsWideSource(resolveClipChannelMap(clip, mediaById.get(clip.mediaId)))),+ );+ }+private setDecodeSurround(surround: boolean): void {if (this.decodeSurround === surround) return;// Cached buffers were decoded for the other layout.@@ -698,6 +705,8 @@ export class AudioEngine {renderStartTime: number,sourceOffset = clipInfo.sourceTime,): Promise<void> {+ // Audio Channels: every later stage (reverse, stretch, effects, panner) sees the clip's channels, not the file's.+ audioBuffer = mapAudioBuffer(context, audioBuffer, clipInfo.channelMap);const source = context.createBufferSource();const speed = clipInfo.speed || 1;diff --git a/packages/core/src/audio/audio-output-device.test.ts b/packages/core/src/audio/audio-output-device.test.tsnew file mode 100644index 00000000..7ccdbb5c--- /dev/null+++ b/packages/core/src/audio/audio-output-device.test.ts@@ -0,0 +1,242 @@+import { describe, expect, it, vi, type Mock } from "vitest";+import {+ AudioOutputRouter,+ normalizeOutputId,+ reconcileOutputDevice,+ type AudioOutputEvent,+} from "./audio-output-device";++const device = (deviceId: string, label: string, kind: MediaDeviceKind = "audiooutput") =>+ ({ deviceId, label, kind, groupId: "g" }) as MediaDeviceInfo;++const SPEAKERS = device("speakers-id", "MacBook Speakers");+const HEADSET = device("headset-id", "USB Headset");+const DEFAULT = device("default", "Default - MacBook Speakers");+const MIC = device("mic-id", "Mic", "audioinput");++function fakeMediaDevices(initial: MediaDeviceInfo[]) {+ let list = initial;+ const handlers = new Set<() => void>();+ return {+ enumerateDevices: vi.fn(async () => list),+ addEventListener: vi.fn((_type: string, handler: () => void) => { handlers.add(handler); }),+ removeEventListener: vi.fn((_type: string, handler: () => void) => { handlers.delete(handler); }),+ set(next: MediaDeviceInfo[]) { list = next; },+ fire() { for (const handler of [...handlers]) handler(); },+ handlers,+ };+}++function fakeContext(options: { sink?: boolean; rejectIds?: string[] } = {}) {+ const sinkCalls: string[] = [];+ const destination = { id: "destination" };+ const context: Record<string, unknown> = {+ destination,+ createMediaStreamDestination: vi.fn(() => ({ stream: { id: "stream" } })),+ };+ if (options.sink !== false) {+ context.setSinkId = vi.fn(async (id: string) => {+ if (options.rejectIds?.includes(id)) throw new DOMException("not found", "NotFoundError");+ sinkCalls.push(id);+ });+ }+ return { context: context as unknown as AudioContext, sinkCalls, destination };+}++const fakeMaster = () => ({ connect: vi.fn(), disconnect: vi.fn() }) as unknown as AudioNode & { connect: ReturnType<typeof vi.fn>; disconnect: ReturnType<typeof vi.fn> };++function setup(devices: MediaDeviceInfo[], contextOptions: Parameters<typeof fakeContext>[0] = {}) {+ const mediaDevices = fakeMediaDevices(devices);+ const ctx = fakeContext(contextOptions);+ const master = fakeMaster();+ const elements: Array<{ srcObject: unknown; setSinkId: Mock; play: Mock; pause: Mock }> = [];+ const router = new AudioOutputRouter({+ mediaDevices: mediaDevices as never,+ createAudioElement: () => {+ const element = { srcObject: null as unknown, setSinkId: vi.fn(async () => undefined), play: vi.fn(async () => undefined), pause: vi.fn() };+ elements.push(element);+ return element as never;+ },+ });+ const events: AudioOutputEvent[] = [];+ router.subscribe((event) => { if (event.type !== "devices") events.push(event); });+ router.attach(ctx.context, master);+ return { router, mediaDevices, ctx, master, events, elements };+}++describe("reconcileOutputDevice", () => {+ const base = { availableIds: ["a", "b"] };+ it("keeps, falls back and restores according to presence", () => {+ expect(reconcileOutputDevice({ ...base, preferredId: "a", activeId: "a" })).toBe("keep");+ expect(reconcileOutputDevice({ ...base, preferredId: "a", activeId: "" })).toBe("restore");+ expect(reconcileOutputDevice({ ...base, preferredId: "gone", activeId: "gone" })).toBe("fallback");+ expect(reconcileOutputDevice({ ...base, preferredId: "gone", activeId: "" })).toBe("keep");+ expect(reconcileOutputDevice({ ...base, preferredId: "", activeId: "a" })).toBe("fallback");+ expect(reconcileOutputDevice({ ...base, preferredId: "default", activeId: "" })).toBe("keep");+ });+ it("never treats an empty device list as an unplug", () => {+ expect(reconcileOutputDevice({ availableIds: [], preferredId: "a", activeId: "a" })).toBe("keep");+ expect(reconcileOutputDevice({ availableIds: [], preferredId: "a", activeId: "" })).toBe("restore");+ // ...but a real list that only holds the default means the device really is gone.+ expect(reconcileOutputDevice({ availableIds: [], listKnown: true, preferredId: "a", activeId: "a" })).toBe("fallback");+ });+ it("normalizes the default aliases", () => {+ expect(normalizeOutputId("default")).toBe("");+ expect(normalizeOutputId(undefined)).toBe("");+ expect(normalizeOutputId("x")).toBe("x");+ });+});++describe("AudioOutputRouter listing", () => {+ it("lists outputs only, folds the default alias, labels unnamed devices", async () => {+ const { router } = setup([DEFAULT, device("communications", "Communications"), SPEAKERS, device("x", ""), MIC]);+ const devices = await router.listDevices();+ expect(devices.map((d) => [d.deviceId, d.label, d.isDefault])).toEqual([+ ["", "System default", true],+ ["speakers-id", "MacBook Speakers", false],+ ["x", "Audio output 1", false],+ ]);+ expect(await router.needsAccessForLabels()).toBe(true);+ });+});++describe("AudioOutputRouter on AudioContext.setSinkId", () => {+ it("treats a withheld device list (empty ids) as unknown, not unplugged", async () => {+ const { router, ctx, events, mediaDevices } = setup([DEFAULT, HEADSET]);+ await router.setPreferredDevice("headset-id");+ events.length = 0;+ mediaDevices.set([device("", "", "audiooutput")]);+ await router.reconcile();+ expect(router.getActiveDeviceId()).toBe("headset-id");+ expect(events).toEqual([]);+ expect(ctx.sinkCalls).toEqual(["headset-id"]);+ });++ it("falls back when the unplug leaves only the system default", async () => {+ const { router, events, mediaDevices } = setup([DEFAULT, HEADSET]);+ await router.setPreferredDevice("headset-id");+ events.length = 0;+ mediaDevices.set([DEFAULT]);+ await router.reconcile();+ expect(router.getActiveDeviceId()).toBe("");+ expect(events).toEqual([{ type: "fallback", reason: "unplugged", requestedId: "headset-id", requestedLabel: "USB Headset" }]);+ });++ it("applies the chosen device and reports it", async () => {+ const { router, ctx, events } = setup([DEFAULT, SPEAKERS, HEADSET]);+ expect(router.getSupport()).toBe("context");+ await router.setPreferredDevice("headset-id");+ expect(ctx.sinkCalls).toEqual(["headset-id"]);+ expect(router.getActiveDeviceId()).toBe("headset-id");+ expect(events).toEqual([{ type: "applied", deviceId: "headset-id", label: "USB Headset" }]);+ });++ it("switches back to the system default when the user picks it", async () => {+ const { router, ctx } = setup([DEFAULT, SPEAKERS, HEADSET]);+ await router.setPreferredDevice("headset-id");+ await router.setPreferredDevice("default");+ expect(ctx.sinkCalls).toEqual(["headset-id", ""]);+ expect(router.getActiveDeviceId()).toBe("");+ });++ it("applies the remembered device as soon as the graph attaches", async () => {+ const mediaDevices = fakeMediaDevices([DEFAULT, HEADSET]);+ const router = new AudioOutputRouter({ mediaDevices: mediaDevices as never });+ await router.setPreferredDevice("headset-id"); // before any AudioContext exists: nothing to retarget yet+ const ctx = fakeContext();+ router.attach(ctx.context, fakeMaster());+ await router.reconcile();+ expect(ctx.sinkCalls).toEqual(["headset-id"]);+ });++ it("falls back to the default with a notice when the device is unplugged, and returns when it is back", async () => {+ const { router, ctx, events, mediaDevices } = setup([DEFAULT, SPEAKERS, HEADSET]);+ router.startWatching();+ await router.setPreferredDevice("headset-id");+ events.length = 0;++ mediaDevices.set([DEFAULT, SPEAKERS]);+ mediaDevices.fire();+ await router.reconcile();+ expect(router.getActiveDeviceId()).toBe("");+ expect(router.isFallbackActive()).toBe(true);+ expect(router.getPreferredDeviceId()).toBe("headset-id"); // the choice is remembered+ expect(events.filter((e) => e.type === "fallback")).toEqual([+ { type: "fallback", reason: "unplugged", requestedId: "headset-id", requestedLabel: "USB Headset" },+ ]);+ expect(ctx.sinkCalls.at(-1)).toBe("");++ // Further device churn while it is gone does not repeat the notice.+ events.length = 0;+ mediaDevices.fire();+ await router.reconcile();+ expect(events).toEqual([]);++ mediaDevices.set([DEFAULT, SPEAKERS, HEADSET]);+ mediaDevices.fire();+ await router.reconcile();+ expect(router.getActiveDeviceId()).toBe("headset-id");+ expect(router.isFallbackActive()).toBe(false);+ expect(events).toEqual([{ type: "restored", deviceId: "headset-id", label: "USB Headset" }]);+ });++ it("falls back with an error notice when the browser refuses the sink", async () => {+ const { router, ctx, events } = setup([DEFAULT, HEADSET], { rejectIds: ["headset-id"] });+ await router.setPreferredDevice("headset-id");+ expect(router.getActiveDeviceId()).toBe("");+ expect(ctx.sinkCalls).toEqual([""]);+ expect(events).toEqual([{ type: "fallback", reason: "error", requestedId: "headset-id", requestedLabel: "USB Headset" }]);+ });++ it("uses the remembered label for a saved device that is not connected", async () => {+ const mediaDevices = fakeMediaDevices([DEFAULT, SPEAKERS]);+ const router = new AudioOutputRouter({ mediaDevices: mediaDevices as never });+ const events: AudioOutputEvent[] = [];+ router.subscribe((event) => { if (event.type !== "devices") events.push(event); });+ router.rememberLabel("headset-id", "USB Headset");+ router.attach(fakeContext().context, fakeMaster());+ await router.setPreferredDevice("headset-id");+ expect(events).toEqual([{ type: "fallback", reason: "unplugged", requestedId: "headset-id", requestedLabel: "USB Headset" }]);+ });++ it("stops listening for device changes", () => {+ const { router, mediaDevices } = setup([DEFAULT]);+ router.startWatching();+ router.startWatching();+ expect(mediaDevices.handlers.size).toBe(1);+ router.stopWatching();+ expect(mediaDevices.handlers.size).toBe(0);+ });+});++describe("AudioOutputRouter media element fallback", () => {+ it("routes the master mix through an element's setSinkId when the context cannot", async () => {+ const { router, ctx, master, elements, events } = setup([DEFAULT, HEADSET], { sink: false });+ expect(router.getSupport()).toBe("element");+ await router.setPreferredDevice("headset-id");+ expect(elements).toHaveLength(1);+ expect(elements[0].setSinkId).toHaveBeenCalledWith("headset-id");+ expect(elements[0].play).toHaveBeenCalled();+ expect(master.disconnect).toHaveBeenCalledWith(ctx.destination);+ expect(master.connect).toHaveBeenCalled();+ expect(events).toEqual([{ type: "applied", deviceId: "headset-id", label: "USB Headset" }]);+ });++ it("restores the direct destination connection when going back to the default", async () => {+ const { router, ctx, master, elements } = setup([DEFAULT, HEADSET], { sink: false });+ await router.setPreferredDevice("headset-id");+ master.connect.mockClear();+ await router.setPreferredDevice("");+ expect(elements[0].pause).toHaveBeenCalled();+ expect(master.connect).toHaveBeenCalledWith(ctx.destination);+ expect(router.getActiveDeviceId()).toBe("");+ });++ it("reports no support when neither path exists", () => {+ const mediaDevices = fakeMediaDevices([DEFAULT]);+ const router = new AudioOutputRouter({ mediaDevices: mediaDevices as never });+ const ctx = { destination: {} } as unknown as AudioContext;+ router.attach(ctx, fakeMaster());+ expect(router.getSupport()).toBe("none");+ });+});diff --git a/packages/core/src/audio/audio-output-device.ts b/packages/core/src/audio/audio-output-device.tsnew file mode 100644index 00000000..9f5e16d4--- /dev/null+++ b/packages/core/src/audio/audio-output-device.ts@@ -0,0 +1,402 @@+/**+ * Audio output device routing (monitor speakers / headphones).+ *+ * The preview mix plays through one master AudioContext. Chromium (and Electron) can retarget it+ * with `AudioContext.setSinkId`. Where only `HTMLMediaElement.setSinkId` exists, the master signal+ * is looped through a MediaStream into a hidden <audio> element that carries the sink instead+ * (slightly higher latency, so it is only used when the context cannot do it directly). The+ * export mixdown renders offline and never touches the output device.+ *+ * The preferred device is remembered by the caller (settings store). This router keeps it applied+ * and, when the device disappears (unplugged, Bluetooth off), falls back to the system default+ * and tells the UI so it can show a toast; when the device returns it is switched back.+ */++/** `""` is the system default in setSinkId terms; the UI uses `"default"` as the same thing. */+export const SYSTEM_DEFAULT_OUTPUT_ID = "";++export interface AudioOutputDevice {+ readonly deviceId: string;+ readonly label: string;+ /** True for the system default entry. */+ readonly isDefault: boolean;+}++export type AudioOutputSupport = "context" | "element" | "none";++export type AudioOutputEvent =+ | { readonly type: "applied"; readonly deviceId: string; readonly label: string }+ /** The preferred device is gone or refused: playing on the system default instead. */+ | { readonly type: "fallback"; readonly reason: "unplugged" | "error"; readonly requestedId: string; readonly requestedLabel: string }+ /** The preferred device is back and playback moved to it again. */+ | { readonly type: "restored"; readonly deviceId: string; readonly label: string }+ | { readonly type: "devices"; readonly devices: readonly AudioOutputDevice[] };++export type AudioOutputListener = (event: AudioOutputEvent) => void;++interface SinkContext {+ readonly destination: AudioNode;+ setSinkId?: (sinkId: string | { type: "none" }) => Promise<void>;+ createMediaStreamDestination?: () => MediaStreamAudioDestinationNode;+}++interface SinkElement {+ srcObject: MediaProvider | null;+ setSinkId?: (sinkId: string) => Promise<void>;+ play: () => Promise<void>;+ pause: () => void;+}++export interface AudioOutputEnvironment {+ readonly mediaDevices?: Pick<MediaDevices, "enumerateDevices" | "addEventListener" | "removeEventListener"> & {+ selectAudioOutput?: () => Promise<MediaDeviceInfo>;+ };+ readonly createAudioElement?: () => SinkElement;+}++export function normalizeOutputId(deviceId: string | null | undefined): string {+ return !deviceId || deviceId === "default" ? SYSTEM_DEFAULT_OUTPUT_ID : deviceId;+}++/** What to do after the device list changed. Pure so the unplug / replug matrix is unit-testable. */+export type OutputReconcileAction = "keep" | "fallback" | "restore";++export function reconcileOutputDevice(input: {+ readonly preferredId: string;+ readonly activeId: string;+ readonly availableIds: readonly string[];+ /** The browser returned real device entries (false = ids withheld, so absence proves nothing). Default: any ids at all. */+ readonly listKnown?: boolean;+}): OutputReconcileAction {+ const preferred = normalizeOutputId(input.preferredId);+ if (preferred === SYSTEM_DEFAULT_OUTPUT_ID) return input.activeId === SYSTEM_DEFAULT_OUTPUT_ID ? "keep" : "fallback";+ // No device list at all (permissions withheld): never treat that as "unplugged"; just try to apply.+ if (!(input.listKnown ?? input.availableIds.length > 0)) return input.activeId === preferred ? "keep" : "restore";+ const present = input.availableIds.includes(preferred);+ if (present) return input.activeId === preferred ? "keep" : "restore";+ return input.activeId === SYSTEM_DEFAULT_OUTPUT_ID ? "keep" : "fallback";+}++export class AudioOutputRouter {+ private context: SinkContext | null = null;+ private masterNode: AudioNode | null = null;+ private preferredId = SYSTEM_DEFAULT_OUTPUT_ID;+ private activeId = SYSTEM_DEFAULT_OUTPUT_ID;+ private mode: "context" | "element" | "none" = "none";+ private elementSink: { element: SinkElement; stream: MediaStreamAudioDestinationNode } | null = null;+ private listeners = new Set<AudioOutputListener>();+ private labels = new Map<string, string>();+ private watching = false;+ private queue: Promise<void> = Promise.resolve();+ private fellBack = false;+ private readonly onDeviceChange = () => {+ void this.reconcile();+ };++ constructor(private readonly environment: AudioOutputEnvironment = {}) {}++ private get mediaDevices(): NonNullable<AudioOutputEnvironment["mediaDevices"]> | undefined {+ return this.environment.mediaDevices ?? (typeof navigator !== "undefined" ? (navigator.mediaDevices as AudioOutputEnvironment["mediaDevices"]) : undefined);+ }++ /** Which retargeting path this browser offers for the attached context. */+ getSupport(): AudioOutputSupport {+ if (this.context && typeof this.context.setSinkId === "function") return "context";+ if (this.elementSupported()) return "element";+ // Before a context is attached, report what the platform could do.+ if (!this.context && typeof AudioContext !== "undefined" && "setSinkId" in AudioContext.prototype) return "context";+ return "none";+ }++ private elementSupported(): boolean {+ if (this.environment.createAudioElement) return true;+ return typeof HTMLMediaElement !== "undefined" && "setSinkId" in HTMLMediaElement.prototype && typeof this.context?.createMediaStreamDestination === "function";+ }++ getPreferredDeviceId(): string {+ return this.preferredId;+ }++ /** The device audio is actually playing on right now ("" = system default). */+ getActiveDeviceId(): string {+ return this.activeId;+ }++ isFallbackActive(): boolean {+ return this.fellBack;+ }++ subscribe(listener: AudioOutputListener): () => void {+ this.listeners.add(listener);+ return () => this.listeners.delete(listener);+ }++ private emit(event: AudioOutputEvent): void {+ for (const listener of [...this.listeners]) {+ try {+ listener(event);+ } catch {+ // A faulty listener must not break routing.+ }+ }+ }++ /** Seed a name for a device that is not plugged in yet (remembered across sessions). */+ rememberLabel(deviceId: string, label: string): void {+ const id = normalizeOutputId(deviceId);+ if (id !== SYSTEM_DEFAULT_OUTPUT_ID && label) this.labels.set(id, label);+ }++ labelFor(deviceId: string): string {+ const id = normalizeOutputId(deviceId);+ if (id === SYSTEM_DEFAULT_OUTPUT_ID) return "System default";+ return this.labels.get(id) || "Audio output device";+ }++ /** The master AudioContext and its final node; applies the remembered device straight away. */+ attach(context: AudioContext, masterNode: AudioNode): void {+ if (this.context === context && this.masterNode === masterNode) return;+ this.teardownElementSink();+ this.context = context as unknown as SinkContext;+ this.masterNode = masterNode;+ this.activeId = SYSTEM_DEFAULT_OUTPUT_ID;+ this.mode = "none";+ if (this.preferredId !== SYSTEM_DEFAULT_OUTPUT_ID) void this.enqueue(() => this.reconcileNow(true));+ }++ detach(context?: AudioContext): void {+ if (context && this.context !== (context as unknown as SinkContext)) return;+ this.teardownElementSink();+ this.context = null;+ this.masterNode = null;+ this.activeId = SYSTEM_DEFAULT_OUTPUT_ID;+ this.mode = "none";+ }++ /** Remember the user's choice and apply it. Resolves once the sink changed (or fell back). */+ setPreferredDevice(deviceId: string): Promise<void> {+ this.preferredId = normalizeOutputId(deviceId);+ this.fellBack = false;+ return this.enqueue(() => this.reconcileNow(true));+ }++ async listDevices(): Promise<AudioOutputDevice[]> {+ return (await this.enumerateOutputs()).devices;+ }++ private async enumerateOutputs(): Promise<{ devices: AudioOutputDevice[]; known: boolean }> {+ const mediaDevices = this.mediaDevices;+ if (!mediaDevices?.enumerateDevices) return { devices: [], known: false };+ let infos: MediaDeviceInfo[];+ try {+ infos = await mediaDevices.enumerateDevices();+ } catch {+ return { devices: [], known: false };+ }+ const outputs = infos.filter((info) => info.kind === "audiooutput");+ // Entries without an id mean the browser is withholding the list until the user grants access.+ const known = outputs.some((info) => info.deviceId !== "");+ let unnamed = 0;+ const devices: AudioOutputDevice[] = [];+ for (const info of outputs) {+ // Chromium also lists a "communications" alias of the default; it is not a separate device.+ if (info.deviceId === "communications") continue;+ if (info.deviceId === "") continue;+ const isDefault = info.deviceId === "default";+ const id = normalizeOutputId(info.deviceId);+ const label = info.label ? info.label.replace(/^Default - /, "") : isDefault ? "System default" : `Audio output ${++unnamed}`;+ if (!isDefault || info.label) this.labels.set(id, label);+ devices.push({ deviceId: id, label: isDefault ? "System default" : label, isDefault });+ }+ if (!devices.some((device) => device.isDefault)) devices.unshift({ deviceId: SYSTEM_DEFAULT_OUTPUT_ID, label: "System default", isDefault: true });+ return { devices, known };+ }++ /** True when labels are hidden until the user grants access (Chromium without a media permission). */+ async needsAccessForLabels(): Promise<boolean> {+ const devices = await this.listDevices();+ return devices.some((device) => !device.isDefault && /^Audio output \d+$/.test(device.label));+ }++ /** Prompt the user to pick (and thereby reveal) an output device where the browser supports it. */+ async requestDeviceAccess(): Promise<AudioOutputDevice | null> {+ const select = this.mediaDevices?.selectAudioOutput;+ if (!select) return null;+ try {+ const info = await select.call(this.mediaDevices);+ if (info.label) this.labels.set(normalizeOutputId(info.deviceId), info.label);+ await this.emitDevices();+ return { deviceId: normalizeOutputId(info.deviceId), label: info.label || "Audio output device", isDefault: info.deviceId === "default" };+ } catch {+ return null;+ }+ }++ /** Watch for devices appearing or disappearing; idempotent. */+ startWatching(): void {+ if (this.watching) return;+ const mediaDevices = this.mediaDevices;+ if (!mediaDevices?.addEventListener) return;+ this.watching = true;+ mediaDevices.addEventListener("devicechange", this.onDeviceChange);+ void this.emitDevices();+ }++ stopWatching(): void {+ if (!this.watching) return;+ this.watching = false;+ this.mediaDevices?.removeEventListener?.("devicechange", this.onDeviceChange);+ }++ private async emitDevices(): Promise<void> {+ this.emit({ type: "devices", devices: await this.listDevices() });+ }++ reconcile(): Promise<void> {+ return this.enqueue(async () => {+ await this.emitDevices();+ await this.reconcileNow(false);+ });+ }++ private enqueue(task: () => Promise<void>): Promise<void> {+ const next = this.queue.then(task, task);+ this.queue = next.catch(() => undefined);+ return next;+ }++ private async reconcileNow(announceApplied: boolean): Promise<void> {+ // Nothing to retarget until the preview graph exists; attach() reconciles then.+ if (!this.context) return;+ const { devices, known } = await this.enumerateOutputs();+ const availableIds = devices.filter((device) => !device.isDefault).map((device) => device.deviceId);+ const action = reconcileOutputDevice({ preferredId: this.preferredId, activeId: this.activeId, availableIds, listKnown: known });+ if (action === "fallback") {+ const requestedId = this.preferredId;+ const requestedLabel = this.labelFor(requestedId);+ await this.applySink(SYSTEM_DEFAULT_OUTPUT_ID);+ if (requestedId !== SYSTEM_DEFAULT_OUTPUT_ID) {+ this.fellBack = true;+ this.emit({ type: "fallback", reason: "unplugged", requestedId, requestedLabel });+ }+ return;+ }+ if (action === "restore") {+ const ok = await this.applySink(this.preferredId);+ if (!ok) {+ this.fellBack = true;+ this.emit({ type: "fallback", reason: "error", requestedId: this.preferredId, requestedLabel: this.labelFor(this.preferredId) });+ return;+ }+ const wasFallback = this.fellBack;+ this.fellBack = false;+ this.emit(wasFallback ? { type: "restored", deviceId: this.activeId, label: this.labelFor(this.activeId) } : { type: "applied", deviceId: this.activeId, label: this.labelFor(this.activeId) });+ return;+ }+ // A saved device that is not connected (e.g. after a restart): say so once, we are on the default.+ if (this.preferredId !== SYSTEM_DEFAULT_OUTPUT_ID && known && !availableIds.includes(this.preferredId) && !this.fellBack) {+ this.fellBack = true;+ this.emit({ type: "fallback", reason: "unplugged", requestedId: this.preferredId, requestedLabel: this.labelFor(this.preferredId) });+ return;+ }+ if (announceApplied && this.activeId === this.preferredId && this.context) {+ this.emit({ type: "applied", deviceId: this.activeId, label: this.labelFor(this.activeId) });+ } else if (announceApplied && this.preferredId === SYSTEM_DEFAULT_OUTPUT_ID) {+ await this.applySink(SYSTEM_DEFAULT_OUTPUT_ID);+ }+ }++ /** Point the output at `deviceId`. Returns false (and plays on the default) when the browser refuses. */+ private async applySink(deviceId: string): Promise<boolean> {+ const context = this.context;+ if (!context) return false;+ if (deviceId === this.activeId && (deviceId === SYSTEM_DEFAULT_OUTPUT_ID || this.mode !== "none")) return true;+ try {+ if (typeof context.setSinkId === "function") {+ this.teardownElementSink();+ await context.setSinkId(deviceId);+ this.mode = deviceId === SYSTEM_DEFAULT_OUTPUT_ID ? "none" : "context";+ } else if (deviceId === SYSTEM_DEFAULT_OUTPUT_ID) {+ this.teardownElementSink();+ this.mode = "none";+ } else if (this.elementSupported()) {+ await this.routeThroughElement(deviceId);+ this.mode = "element";+ } else {+ return false;+ }+ this.activeId = deviceId;+ return true;+ } catch {+ this.teardownElementSink();+ try {+ if (typeof context.setSinkId === "function") await context.setSinkId(SYSTEM_DEFAULT_OUTPUT_ID);+ } catch {+ // Already on whatever the browser considers default.+ }+ this.activeId = SYSTEM_DEFAULT_OUTPUT_ID;+ this.mode = "none";+ return false;+ }+ }++ private async routeThroughElement(deviceId: string): Promise<void> {+ const context = this.context;+ const master = this.masterNode;+ if (!context || !master) throw new Error("Audio output is not attached");+ if (!this.elementSink) {+ if (!context.createMediaStreamDestination) throw new Error("MediaStream destination is unavailable");+ const stream = context.createMediaStreamDestination();+ const element = this.environment.createAudioElement ? this.environment.createAudioElement() : (new Audio() as unknown as SinkElement);+ element.srcObject = stream.stream;+ this.elementSink = { element, stream };+ try {+ master.disconnect(context.destination);+ } catch {+ // Not connected to the destination (already rerouted).+ }+ master.connect(stream);+ }+ if (!this.elementSink.element.setSinkId) throw new Error("setSinkId is unavailable");+ await this.elementSink.element.setSinkId(deviceId);+ await this.elementSink.element.play();+ }++ private teardownElementSink(): void {+ const sink = this.elementSink;+ if (!sink) return;+ this.elementSink = null;+ try {+ sink.element.pause();+ sink.element.srcObject = null;+ } catch {+ // Element already released.+ }+ const context = this.context;+ const master = this.masterNode;+ if (!context || !master) return;+ try {+ master.disconnect(sink.stream);+ } catch {+ // Already disconnected.+ }+ try {+ master.connect(context.destination);+ } catch {+ // Context closed.+ }+ }+}++let routerInstance: AudioOutputRouter | null = null;++/** The app-wide router the realtime graph attaches its master output to. */+export function getAudioOutputRouter(): AudioOutputRouter {+ if (!routerInstance) routerInstance = new AudioOutputRouter();+ return routerInstance;+}++/** Test seam: replace or clear the shared router. */+export function setAudioOutputRouterForTests(router: AudioOutputRouter | null): void {+ routerInstance = router;+}diff --git a/packages/core/src/audio/channel-map.test.ts b/packages/core/src/audio/channel-map.test.tsnew file mode 100644index 00000000..167942a9--- /dev/null+++ b/packages/core/src/audio/channel-map.test.ts@@ -0,0 +1,108 @@+import { describe, expect, it } from "vitest";+import {+ MIX_CHANNELS, SILENT_CHANNEL, applyChannelMapToChannels, channelMapNeedsWideSource, channelMatrix, describeChannelMap, fileChannelFormat,+ identityChannelMap, isIdentityChannelMap, mapAudioBuffer, matchChannelPreset, presetChannelMap, resolveClipChannelMap, sanitizeChannelMap,+ type ClipChannelMap,+} from "./channel-map";++const mono = (...sources: number[]): ClipChannelMap => ({ format: "mono", sources });+const stereo = (...sources: number[]): ClipChannelMap => ({ format: "stereo", sources });++describe("channel map matrix", () => {+ it("identity maps are recognised per file layout", () => {+ expect(identityChannelMap(1)).toEqual(mono(0));+ expect(identityChannelMap(2)).toEqual(stereo(0, 1));+ expect(identityChannelMap(6).sources).toEqual([0, 1, 2, 3, 4, 5]);+ expect(fileChannelFormat(4)).toBe("stereo");+ expect(isIdentityChannelMap(undefined, 2)).toBe(true);+ expect(isIdentityChannelMap(stereo(0, 1), 2)).toBe(true);+ expect(isIdentityChannelMap(stereo(1, 0), 2)).toBe(false);+ });++ it("builds the matrix for left only, right only, swap and mix", () => {+ expect(channelMatrix(mono(0), 2)).toEqual([[1, 0]]);+ expect(channelMatrix(mono(1), 2)).toEqual([[0, 1]]);+ expect(channelMatrix(stereo(1, 0), 2)).toEqual([[0, 1], [1, 0]]);+ expect(channelMatrix(mono(MIX_CHANNELS), 2)).toEqual([[0.5, 0.5]]);+ expect(channelMatrix(stereo(0, SILENT_CHANNEL), 2)).toEqual([[1, 0], [0, 0]]);+ });++ it("treats a source channel the file does not have as silent", () => {+ expect(channelMatrix(stereo(0, 3), 2)).toEqual([[1, 0], [0, 0]]);+ expect(channelMatrix({ format: "5.1", sources: [0, 1, 2, 3, 4, 5] }, 2)[5]).toEqual([0, 0]);+ });++ it("presets: use file is no mapping, mono is the first channel, stereo follows the file", () => {+ expect(presetChannelMap("file", 2)).toBeUndefined();+ expect(presetChannelMap("mono", 2)).toEqual(mono(0));+ expect(presetChannelMap("mono", 1)).toEqual(mono(0));+ expect(presetChannelMap("stereo", 2)).toEqual(stereo(0, 1));+ expect(presetChannelMap("stereo", 1)).toEqual(stereo(0, 0));+ expect(matchChannelPreset(stereo(0, 0), 1)).toBe("stereo");+ expect(matchChannelPreset(mono(0), 2)).toBe("mono");+ expect(matchChannelPreset(stereo(1, 0), 2)).toBeNull();+ expect(matchChannelPreset(undefined, 2)).toBe("file");+ });++ it("sanitises untrusted maps", () => {+ expect(sanitizeChannelMap(null)).toBeUndefined();+ expect(sanitizeChannelMap({ format: "quad", sources: [] })).toBeUndefined();+ expect(sanitizeChannelMap({ format: "stereo", sources: [1] })).toEqual(stereo(1, SILENT_CHANNEL));+ expect(sanitizeChannelMap({ format: "mono", sources: [-2.5] })).toEqual(mono(SILENT_CHANNEL));+ expect(sanitizeChannelMap({ format: "mono", sources: [MIX_CHANNELS] })).toEqual(mono(MIX_CHANNELS));+ });++ it("clip map wins over the media import preset", () => {+ const media = { channelPreset: "mono" as const, metadata: { channels: 2 } };+ expect(resolveClipChannelMap({}, media)).toEqual(mono(0));+ expect(resolveClipChannelMap({ channelMap: stereo(1, 0) }, media)).toEqual(stereo(1, 0));+ expect(resolveClipChannelMap({}, { metadata: { channels: 2 } })).toBeUndefined();+ });++ it("describes maps", () => {+ expect(describeChannelMap(undefined, 2)).toBe("Stereo (file)");+ expect(describeChannelMap(mono(0), 2)).toBe("Mono (Left)");+ expect(describeChannelMap(stereo(1, 0), 2)).toBe("Stereo (Right / Left)");+ });+});++describe("channel map on sample data", () => {+ const left = Float32Array.from([1, 1, 1, 1]);+ const right = Float32Array.from([0.5, 0.5, 0.5, 0.5]);++ it("routes, swaps, mixes and mutes", () => {+ expect(applyChannelMapToChannels([left, right], mono(0))).toEqual([left]);+ expect(applyChannelMapToChannels([left, right], mono(1))).toEqual([right]);+ expect(applyChannelMapToChannels([left, right], stereo(1, 0))).toEqual([right, left]);+ expect(Array.from(applyChannelMapToChannels([left, right], mono(MIX_CHANNELS))[0])).toEqual([0.75, 0.75, 0.75, 0.75]);+ expect(Array.from(applyChannelMapToChannels([left, right], stereo(0, SILENT_CHANNEL))[1])).toEqual([0, 0, 0, 0]);+ });++ it("maps AudioBuffers once and returns the source when nothing changes", () => {+ const makeBuffer = (channels: number, length: number, sampleRate: number) => {+ const data = Array.from({ length: channels }, (_, c) => (c === 0 ? left : right).slice());+ return { numberOfChannels: channels, length, sampleRate, duration: length / sampleRate, getChannelData: (c: number) => data[c] } as unknown as AudioBuffer;+ };+ const ctx = { createBuffer: makeBuffer };+ const source = makeBuffer(2, 4, 48000);+ expect(mapAudioBuffer(ctx, source, undefined)).toBe(source);+ expect(mapAudioBuffer(ctx, source, stereo(0, 1))).toBe(source);+ const swapped = mapAudioBuffer(ctx, source, stereo(1, 0));+ expect(swapped).not.toBe(source);+ expect(swapped.numberOfChannels).toBe(2);+ expect(Array.from(swapped.getChannelData(0))).toEqual(Array.from(right));+ expect(mapAudioBuffer(ctx, source, stereo(1, 0))).toBe(swapped);+ expect(mapAudioBuffer(ctx, source, mono(0)).numberOfChannels).toBe(1);+ });+});++describe("wide source decoding", () => {+ it("is needed only when a map reads beyond L/R or outputs 5.1", () => {+ expect(channelMapNeedsWideSource(undefined)).toBe(false);+ expect(channelMapNeedsWideSource(stereo(0, 1))).toBe(false);+ expect(channelMapNeedsWideSource(mono(MIX_CHANNELS))).toBe(false);+ expect(channelMapNeedsWideSource(mono(2))).toBe(true);+ expect(channelMapNeedsWideSource(stereo(4, 5))).toBe(true);+ expect(channelMapNeedsWideSource({ format: "5.1", sources: [0, 1, 2, 3, 4, 5] })).toBe(true);+ });+});diff --git a/packages/core/src/audio/channel-map.ts b/packages/core/src/audio/channel-map.tsnew file mode 100644index 00000000..feecf175--- /dev/null+++ b/packages/core/src/audio/channel-map.ts@@ -0,0 +1,169 @@+/**+ * Audio channel mapping (Premiere "Modify > Audio Channels").+ *+ * A clip's channel map says what each of its OUTPUT channels (mono = 1, stereo = 2, 5.1 = 6)+ * plays from the SOURCE file. One entry per output channel:+ * - n >= 0 source channel n (0-based: L, R, C, LFE, Ls, Rs for a 5.1 file)+ * - SILENT (-1) the channel is muted+ * - MIX (-2) the average of every source channel (a mono fold-down)+ * The map is applied to the decoded source buffer, so preview, waveforms, metering and the+ * export mixdown all hear the same thing.+ */++export type ClipChannelFormat = "mono" | "stereo" | "5.1";+/** What a newly imported file defaults to. "file" follows the file's own channel layout. */+export type ChannelPreset = "file" | "mono" | "stereo";++export const SILENT_CHANNEL = -1;+export const MIX_CHANNELS = -2;++export const CLIP_CHANNEL_FORMATS: readonly ClipChannelFormat[] = ["mono", "stereo", "5.1"];+export const CHANNEL_PRESETS: readonly ChannelPreset[] = ["file", "mono", "stereo"];+export const FORMAT_CHANNEL_COUNT: Readonly<Record<ClipChannelFormat, number>> = { mono: 1, stereo: 2, "5.1": 6 };+export const FORMAT_CHANNEL_NAMES: Readonly<Record<ClipChannelFormat, readonly string[]>> = {+ mono: ["Mono"],+ stereo: ["Left", "Right"],+ "5.1": ["L", "R", "C", "LFE", "Ls", "Rs"],+};+export const CHANNEL_PRESET_LABELS: Readonly<Record<ChannelPreset, string>> = {+ file: "Use file",+ mono: "Mono",+ stereo: "Stereo",+};++export interface ClipChannelMap {+ readonly format: ClipChannelFormat;+ /** Source channel for each output channel; `sources.length === FORMAT_CHANNEL_COUNT[format]`. */+ readonly sources: readonly number[];+}++export const isClipChannelFormat = (value: unknown): value is ClipChannelFormat =>+ value === "mono" || value === "stereo" || value === "5.1";+export const isChannelPreset = (value: unknown): value is ChannelPreset =>+ value === "file" || value === "mono" || value === "stereo";++/** Channel format a file has on its own. */+export function fileChannelFormat(sourceChannels: number | undefined): ClipChannelFormat {+ const count = Math.round(sourceChannels ?? 2);+ if (count <= 1) return "mono";+ return count >= 6 ? "5.1" : "stereo";+}++/** The map that plays a file untouched. */+export function identityChannelMap(sourceChannels: number | undefined): ClipChannelMap {+ const format = fileChannelFormat(sourceChannels);+ const count = FORMAT_CHANNEL_COUNT[format];+ return { format, sources: Array.from({ length: count }, (_, index) => index) };+}++const sourceCount = (sourceChannels: number | undefined): number => Math.max(1, Math.round(sourceChannels ?? 2));++/** Normalises untrusted input (saved project, agent call); undefined when it is not a valid map. */+export function sanitizeChannelMap(value: unknown): ClipChannelMap | undefined {+ if (!value || typeof value !== "object") return undefined;+ const { format, sources } = value as { format?: unknown; sources?: unknown };+ if (!isClipChannelFormat(format) || !Array.isArray(sources)) return undefined;+ const count = FORMAT_CHANNEL_COUNT[format];+ const cleaned = Array.from({ length: count }, (_, index) => {+ const entry = sources[index];+ if (entry === MIX_CHANNELS) return MIX_CHANNELS;+ return typeof entry === "number" && Number.isInteger(entry) && entry >= 0 && entry < 64 ? entry : SILENT_CHANNEL;+ });+ return { format, sources: cleaned };+}++/** The map a preset gives a file of `sourceChannels` channels; undefined for "file" (no mapping). */+export function presetChannelMap(preset: ChannelPreset | undefined, sourceChannels: number | undefined): ClipChannelMap | undefined {+ if (!preset || preset === "file") return undefined;+ if (preset === "mono") return { format: "mono", sources: [0] };+ return { format: "stereo", sources: sourceCount(sourceChannels) > 1 ? [0, 1] : [0, 0] };+}++/** Preset a map corresponds to for a file of `sourceChannels` channels, or null for a custom map. */+export function matchChannelPreset(map: ClipChannelMap | undefined, sourceChannels: number | undefined): ChannelPreset | null {+ if (!map || isIdentityChannelMap(map, sourceChannels)) return "file";+ for (const preset of ["mono", "stereo"] as const) {+ const candidate = presetChannelMap(preset, sourceChannels);+ if (candidate && sameChannelMap(candidate, map)) return preset;+ }+ return null;+}++/** True when a map reads source channels a stereo decode would have folded away (a 5.1 output, or a source beyond L/R). */+export const channelMapNeedsWideSource = (map: ClipChannelMap | undefined): boolean =>+ !!map && (map.format === "5.1" || map.sources.some((entry) => entry >= 2));++export const sameChannelMap = (a: ClipChannelMap | undefined, b: ClipChannelMap | undefined): boolean =>+ a === b || (!!a && !!b && a.format === b.format && a.sources.length === b.sources.length && a.sources.every((source, index) => source === b.sources[index]));++export function isIdentityChannelMap(map: ClipChannelMap | undefined, sourceChannels: number | undefined): boolean {+ return !map || sameChannelMap(map, identityChannelMap(sourceChannels));+}++/**+ * The mapping as a matrix: `matrix[output][source]` is the gain of that source channel in that+ * output channel (0 or 1, or 1/N for a MIX row). The unit-tested definition of a channel map.+ */+export function channelMatrix(map: ClipChannelMap, sourceChannels: number): number[][] {+ const available = sourceCount(sourceChannels);+ return map.sources.map((entry) => {+ const row = new Array<number>(available).fill(0);+ if (entry === MIX_CHANNELS) row.fill(1 / available);+ else if (entry >= 0 && entry < available) row[entry] = 1;+ return row;+ });+}++/** Applies a map to decoded channel data. Single-source outputs reuse the source array; mixes and silence allocate. */+export function applyChannelMapToChannels(channels: readonly Float32Array[], map: ClipChannelMap): Float32Array[] {+ const length = channels[0]?.length ?? 0;+ const matrix = channelMatrix(map, channels.length);+ return matrix.map((row) => {+ const taps = row.flatMap((gain, source) => (gain === 0 ? [] : [[source, gain] as const]));+ if (taps.length === 0) return new Float32Array(length);+ if (taps.length === 1 && taps[0][1] === 1) return channels[taps[0][0]];+ const out = new Float32Array(length);+ for (const [source, gain] of taps) {+ const data = channels[source];+ for (let i = 0; i < length; i++) out[i] += data[i] * gain;+ }+ return out;+ });+}++const mappedBuffers = new WeakMap<AudioBuffer, Map<string, AudioBuffer>>();+const mapKey = (map: ClipChannelMap): string => `${map.format}:${map.sources.join(",")}`;++/** The clip-channel buffer for a decoded source buffer; the source itself when the map changes nothing. Cached per source buffer. */+export function mapAudioBuffer(context: Pick<BaseAudioContext, "createBuffer">, buffer: AudioBuffer, map: ClipChannelMap | undefined): AudioBuffer {+ if (!map || isIdentityChannelMap(map, buffer.numberOfChannels)) return buffer;+ const key = mapKey(map);+ const cached = mappedBuffers.get(buffer)?.get(key);+ if (cached) return cached;+ const source: Float32Array[] = [];+ for (let c = 0; c < buffer.numberOfChannels; c++) source.push(buffer.getChannelData(c));+ const mapped = applyChannelMapToChannels(source, map);+ const out = context.createBuffer(mapped.length, Math.max(1, buffer.length), buffer.sampleRate);+ mapped.forEach((data, c) => out.getChannelData(c).set(data));+ let perBuffer = mappedBuffers.get(buffer);+ if (!perBuffer) mappedBuffers.set(buffer, (perBuffer = new Map()));+ perBuffer.set(key, out);+ return out;+}++/** The map a clip plays with: its own, else the file's import preset. undefined = the file as it is. */+export function resolveClipChannelMap(+ clip: { readonly channelMap?: ClipChannelMap },+ media: { readonly channelPreset?: ChannelPreset; readonly metadata?: { readonly channels?: number } } | undefined,+): ClipChannelMap | undefined {+ return clip.channelMap ?? presetChannelMap(media?.channelPreset, media?.metadata?.channels);+}++/** Short human label for a map, e.g. "Mono (Left)", "Stereo (swapped)". */+export function describeChannelMap(map: ClipChannelMap | undefined, sourceChannels: number | undefined): string {+ if (isIdentityChannelMap(map, sourceChannels) || !map) return `${FORMAT_LABELS[fileChannelFormat(sourceChannels)]} (file)`;+ const names = FORMAT_CHANNEL_NAMES[fileChannelFormat(sourceChannels)];+ const parts = map.sources.map((entry) => (entry === SILENT_CHANNEL ? "off" : entry === MIX_CHANNELS ? "mix" : names[entry] ?? `${entry + 1}`));+ return `${FORMAT_LABELS[map.format]} (${parts.join(" / ")})`;+}+const FORMAT_LABELS: Readonly<Record<ClipChannelFormat, string>> = { mono: "Mono", stereo: "Stereo", "5.1": "5.1" };diff --git a/packages/core/src/audio/clip-audio-resolution.ts b/packages/core/src/audio/clip-audio-resolution.tsindex 25a1693d..0790e832 100644--- a/packages/core/src/audio/clip-audio-resolution.ts+++ b/packages/core/src/audio/clip-audio-resolution.ts@@ -1,3 +1,4 @@+import { resolveClipChannelMap, type ChannelPreset, type ClipChannelMap } from "./channel-map";import type {AutomationPoint,Clip,@@ -119,10 +120,15 @@ export const resolveClipPitchCorrection = (export const resolveClipPlaybackAudioParams = (clip: Clip,timeline: TimelineWithTracks,-): { panAutomation: AutomationPoint[]; pitchCorrection: boolean } => ({- panAutomation: resolveClipPanAutomation(clip, timeline),- pitchCorrection: resolveClipPitchCorrection(clip, timeline),-});+ media?: { readonly channelPreset?: ChannelPreset; readonly metadata?: { readonly channels?: number } },+): { panAutomation: AutomationPoint[]; pitchCorrection: boolean; channelMap?: ClipChannelMap } => {+ const channelMap = resolveClipChannelMap(clip, media);+ return {+ panAutomation: resolveClipPanAutomation(clip, timeline),+ pitchCorrection: resolveClipPitchCorrection(clip, timeline),+ ...(channelMap ? { channelMap } : {}),+ };+};/** The volume lane that is actually heard: the stored lane with live ducking under dialogue applied. */export const resolveClipVolumeAutomation = (diff --git a/packages/core/src/audio/index.ts b/packages/core/src/audio/index.tsindex bb67769a..863ae605 100644--- a/packages/core/src/audio/index.ts+++ b/packages/core/src/audio/index.ts@@ -33,6 +33,8 @@ export * from "./highlight-analyzer";export * from "./track-audio-rack";export * from "./loudness";export * from "./mixdown-cache";+export * from "./track-audibility";+export * from "./audio-output-device";export * from "./audio-routing";export * from "./track-automation";export * from "./scrub-grain";@@ -41,4 +43,5 @@ export * from "./audio-routing-graph";export * from "./repair";export * from "./essential-sound";export * from "./surround";+export * from "./channel-map";export * from "./multichannel-fx";diff --git a/packages/core/src/audio/mixdown-cache.ts b/packages/core/src/audio/mixdown-cache.tsindex fe78774d..ee1076f5 100644--- a/packages/core/src/audio/mixdown-cache.ts+++ b/packages/core/src/audio/mixdown-cache.ts@@ -76,13 +76,13 @@ function audioClipHash(clip: Clip): string {clip.mediaId, clip.startTime, clip.duration, clip.inPoint, clip.outPoint,clip.volume, clip.fade, clip.automation, clip.speed, clip.reversed,clip.pitchCorrection, clip.audioTrackIndex, clip.speedKeyframes, clip.freezeFrames,- clip.audioEffects, clip.effects, clip.keyframes, clip.metadata, clip.surroundPan,+ clip.audioEffects, clip.effects, clip.keyframes, clip.metadata, clip.surroundPan, clip.channelMap,]);}function trackLevelHash(track: Track): string {return hashOf(track, () => [- track.id, track.hidden, track.muted, track.solo, track.audioRack, track.transitions,+ track.id, track.hidden, track.muted, track.solo, track.soloSafe, track.audioRack, track.transitions,// Output assignment and sends decide where this track's signal goes.track.output, track.sends, track.surroundPan,]);@@ -108,7 +108,7 @@ function mediaHash(project: Project, ids: ReadonlySet<string>): string {for (const item of project.mediaLibrary.items) {if (!ids.has(item.id)) continue;parts.push(- `${hashOf(item, () => [item.id, item.name, item.type, item.metadata, item.isPlaceholder, item.sourceFile])}:${blobId(item.blob)}`,+ `${hashOf(item, () => [item.id, item.name, item.type, item.metadata, item.isPlaceholder, item.sourceFile, item.channelPreset])}:${blobId(item.blob)}`,);}return parts.join(",");diff --git a/packages/core/src/audio/realtime-audio-graph.clips.test.ts b/packages/core/src/audio/realtime-audio-graph.clips.test.tsindex ed83fa17..e0d4f44f 100644--- a/packages/core/src/audio/realtime-audio-graph.clips.test.ts+++ b/packages/core/src/audio/realtime-audio-graph.clips.test.ts@@ -1,6 +1,7 @@import { afterEach, describe, expect, it, vi } from "vitest";import {RealtimeAudioGraph,+ SCHEDULE_START_LOOKAHEAD_SECONDS as LEAD,type AudioClipSchedule,} from "./realtime-audio-graph";import type { MasterTimelineClock } from "../playback/master-timeline-clock";@@ -99,16 +100,21 @@ describe("each scheduled clip owns its effects and nodes", () => {it("schedules overlapping fades without losing their audible peak", () => {const { graph, gains } = fixture();graph.scheduleClip(schedule("overlap", { fadeIn: 5, fadeOut: 5 }));- expect(gains.map(({ gain }) => gain.linearRampToValueAtTime.mock.calls)).toContainEqual([[0.5, 2.5], [0, 5]]);+ const ramps = gains.map(({ gain }) => gain.linearRampToValueAtTime.mock.calls as number[][]).find((calls) => calls.length === 2);+ expect(ramps).toBeDefined();+ expect(ramps![0][0]).toBeCloseTo(0.5, 9);+ expect(ramps![0][1]).toBeCloseTo(2.5, 9);+ expect(ramps![1][0]).toBeCloseTo(0, 9);+ expect(ramps![1][1]).toBeCloseTo(5, 9);});it("keeps original-clock fades and local transition timing after a seek", () => {const { graph, gains, state } = fixture();- state.time = 0.5;+ state.time = 0.5 - LEAD; // the clip starts LEAD ahead of the clock, i.e. at 0.5 on the timelinegraph.scheduleClip(schedule("piece", { endTime: 2, fadeIn: 5, fadeOut: 4, fadeOrigin: { offset: 4, duration: 10 }, transitionFadeIn: 1 }));- const fade = gains.find(({ gain }) => gain.setValueAtTime.mock.calls.some(([value, time]) => Math.abs(value - 0.5) < 1e-8 && time === 0));+ const fade = gains.find(({ gain }) => gain.setValueAtTime.mock.calls.some(([value, time]) => Math.abs(value - 0.5) < 1e-8 && Math.abs(time - LEAD) < 1e-8));expect(fade).toBeDefined();- expect(fade!.gain.linearRampToValueAtTime.mock.calls.some(([value, time]) => Math.abs(value - 1) < 1e-8 && Math.abs(time - 0.5) < 1e-8)).toBe(true);+ expect(fade!.gain.linearRampToValueAtTime.mock.calls.some(([value, time]) => Math.abs(value - 1) < 1e-8 && Math.abs(time - (0.5 + LEAD)) < 1e-8)).toBe(true);});it("keeps overlapping sources and the root mixer tap while applying independent clip pan", () => {@@ -160,14 +166,28 @@ describe("each scheduled clip owns its effects and nodes", () => {});it("seeks source audio using clip speed and keeps the requested timeline duration", () => {const { graph, state, sources } = fixture();- state.time = 3;+ state.time = 3 - LEAD; // the clip starts LEAD ahead of the clock, i.e. at 3 on the timelinegraph.scheduleClip(schedule("fast", { startTime: 1, endTime: 6, mediaOffset: 2, speed: 2, pitchCorrection: false }),);- expect(sources[0].start).toHaveBeenCalledWith(0, 6, 6);+ expect(sources[0].start).toHaveBeenCalledWith(LEAD, expect.closeTo(6, 9), expect.closeTo(6, 9));expect(sources[0].stop).not.toHaveBeenCalled();graph.dispose();});+ it("starts every clip of one batch from the same instant even while the clock advances between clips", () => {+ const { graph, state, sources } = fixture();+ // A starved main thread: the audio clock moves 5 ms each time it is read.+ let now = 0.2;+ Object.defineProperty(state, "time", { get: () => (now += 0.005) });+ graph.scheduleClips([+ schedule("dialogue", { startTime: 0, endTime: 4 }),+ schedule("music", { startTime: 0, endTime: 4, trackId: "t2" }),+ ]);+ const offsets = sources.map((source) => source.start.mock.calls[0][1]);+ expect(offsets).toHaveLength(2);+ expect(offsets[1]).toBe(offsets[0]);+ graph.dispose();+ });const bigBuffer = (seconds: number, rate = 8000) => ({numberOfChannels: 1, sampleRate: rate, length: rate * seconds, duration: seconds,getChannelData: () => new Float32Array(rate * seconds),@@ -227,7 +247,10 @@ describe("each scheduled clip owns its effects and nodes", () => {expect(seen).toEqual([16000]);graph.scheduleClip(schedule("fast-again", { audioBuffer, endTime: 1, speed: 2, mediaOffset: 100 }));expect(sources.at(-1)!.buffer?.duration).toBeCloseTo(1, 3);- expect(sources.at(-1)!.start).toHaveBeenCalledWith(0, 0, 1);+ const [when, offset, duration] = sources.at(-1)!.start.mock.calls[0];+ expect(when).toBe(LEAD);+ expect(offset).toBeCloseTo(LEAD, 9); // the stretched render begins at the clip's first used sample, plus the start lead+ expect(duration).toBeCloseTo(1 - LEAD, 9);graph.dispose();});it("lets a clip effect tail ring out when the resampled source is retired for the stretch", async () => {diff --git a/packages/core/src/audio/realtime-audio-graph.latency.test.ts b/packages/core/src/audio/realtime-audio-graph.latency.test.tsindex 63d9e25c..223f6e19 100644--- a/packages/core/src/audio/realtime-audio-graph.latency.test.ts+++ b/packages/core/src/audio/realtime-audio-graph.latency.test.ts@@ -1,7 +1,7 @@import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";import type { MasterTimelineClock } from "../playback/master-timeline-clock";import type { Effect } from "../types";-import { RealtimeAudioGraph, type AudioClipSchedule } from "./realtime-audio-graph";+import { RealtimeAudioGraph, SCHEDULE_START_LOOKAHEAD_SECONDS as LEAD, type AudioClipSchedule } from "./realtime-audio-graph";const SR = 48000;@@ -91,8 +91,8 @@ describe("realtime scheduling compensates lookahead effects", () => {graph.scheduleClip(clip({ effects: [compressor] }));const lookahead = Math.floor(0.006 * SR) / SR;const [when, offset] = sources[0].start.mock.calls[0];- expect(when).toBe(0);- expect(offset).toBeCloseTo(3 + lookahead, 9);+ expect(when).toBeCloseTo(10 + LEAD, 9); // context time (10) plus the start lead+ expect(offset).toBeCloseTo(3 + lookahead + LEAD, 9);});it("a track rack with a limiter shifts every clip on every track by the graph latency", () => {diff --git a/packages/core/src/audio/realtime-audio-graph.test.ts b/packages/core/src/audio/realtime-audio-graph.test.tsindex fcd71a24..89f29156 100644--- a/packages/core/src/audio/realtime-audio-graph.test.ts+++ b/packages/core/src/audio/realtime-audio-graph.test.ts@@ -1,6 +1,6 @@import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";import type { MasterTimelineClock } from "../playback/master-timeline-clock";-import { RealtimeAudioGraph, type AudioClipSchedule } from "./realtime-audio-graph";+import { RealtimeAudioGraph, SCHEDULE_START_LOOKAHEAD_SECONDS as LEAD, type AudioClipSchedule } from "./realtime-audio-graph";function createAudioFixture() {const sources: Array<{@@ -73,7 +73,7 @@ describe("RealtimeAudioGraph seek scheduling", () => {expect(sources[0].stop).toHaveBeenCalledOnce();expect(provider).toHaveBeenLastCalledWith(2);expect(sources).toHaveLength(2);- expect(sources[1].start).toHaveBeenCalledWith(0, 2, 8);+ expect(sources[1].start).toHaveBeenCalledWith(LEAD, expect.closeTo(2 + LEAD, 9), expect.closeTo(8 - LEAD, 9));graph.dispose();});@@ -90,7 +90,7 @@ describe("RealtimeAudioGraph seek scheduling", () => {state.position = 2.5;graph.seekTo(2.5);expect(sources).toHaveLength(2);- expect(sources[1].start).toHaveBeenCalledWith(0, 0.5, 7.5);+ expect(sources[1].start).toHaveBeenCalledWith(LEAD, expect.closeTo(0.5 + LEAD, 9), expect.closeTo(7.5 - LEAD, 9));state.position = 2.6;vi.advanceTimersByTime(100);expect(sources).toHaveLength(2);@@ -114,7 +114,7 @@ describe("RealtimeAudioGraph seek scheduling", () => {state.playing = true;graph.startScheduler(provider);expect(sources).toHaveLength(2);- expect(sources[1].start).toHaveBeenCalledWith(0, 4, 6);+ expect(sources[1].start).toHaveBeenCalledWith(LEAD, expect.closeTo(4 + LEAD, 9), expect.closeTo(6 - LEAD, 9));graph.dispose();});diff --git a/packages/core/src/audio/realtime-audio-graph.ts b/packages/core/src/audio/realtime-audio-graph.tsindex c4782c72..e251d6b4 100644--- a/packages/core/src/audio/realtime-audio-graph.ts+++ b/packages/core/src/audio/realtime-audio-graph.ts@@ -18,13 +18,18 @@ import { SCRUB_GRAIN_SECONDS, SCRUB_MAX_GRAINS, planScrubGrains } from "./scrub-import { StretchCache, getSharedStretchCache, type StretchRequest, type StretchRunner } from "./stretch-cache";import { createRackBus, rackPan, rackVolume, type RackBusLike } from "./track-audio-rack";import { createLinkedCompressorStage, createMultichannelConvolver, needsMultichannelNodes, pinChannels } from "./multichannel-fx";+import { mapAudioBuffer, type ClipChannelMap } from "./channel-map";import { createSurroundPanner, resolveSurroundPan, type ChannelLayout, type SurroundPannerNodes } from "./surround";import { effectChainLatencySamples, rackLatencySamples } from "./effect-latency";+import { isTrackAudible } from "./track-audibility";+import { getAudioOutputRouter } from "./audio-output-device";export interface AudioClipSchedule {clipId: string;trackId: string;audioBuffer: AudioBuffer;+ /** Audio Channels mapping applied to `audioBuffer` when the clip is scheduled. */+ channelMap?: ClipChannelMap;startTime: number;endTime: number;mediaOffset: number;@@ -50,6 +55,8 @@ interface TrackConfig {pan: number;muted: boolean;solo: boolean;+ /** Solo Safe: stays audible while other tracks are soloed. */+ soloSafe?: boolean;effects: Effect[];}@@ -111,6 +118,9 @@ interface TrackNodes {preFaderGate: GainNode;}+/** How far ahead of "now" a clip that is already playing is started (see scheduleClip). */+export const SCHEDULE_START_LOOKAHEAD_SECONDS = 0.02;+export class RealtimeAudioGraph {private audioContext: AudioContext;private masterClock: MasterTimelineClock;@@ -158,6 +168,8 @@ export class RealtimeAudioGraph {this.masterGain.connect(this.masterBus.input);this.masterBus.output.connect(this.masterOutput);this.masterOutput.connect(this.audioContext.destination);+ // Monitor device chosen in Preferences / the mixer (no-op until one is picked).+ getAudioOutputRouter().attach(this.audioContext, this.masterOutput);this.routing = new AudioRoutingGraph(this.audioContext, this.masterGain, {live: true,getTimelineTime: () => this.masterClock.currentTime,@@ -319,7 +331,7 @@ export class RealtimeAudioGraph {const now = this.audioContext.currentTime;const hasVolume = (lanes?.volume?.length ?? 0) > 0;const hasPan = (lanes?.pan?.length ?? 0) > 0;- const audible = !config.muted && (!this.hasSoloTracks || config.solo);+ const audible = isTrackAudible(config, this.hasSoloTracks);const time = timelineTime ?? this.masterClock.currentTime;const ctxStart = now + (this.trackLatencySeconds.get(trackId) ?? 0) - this.routing.getTotalLatencySeconds();if (hasVolume && audible && lanes?.volume) {@@ -816,19 +828,28 @@ export class RealtimeAudioGraph {}}+ setTrackSoloSafe(trackId: string, soloSafe: boolean): void {+ const config = this.trackConfigs.get(trackId);+ if (config) {+ config.soloSafe = soloSafe;+ this.updateTrackAudibility(trackId);+ }+ }+/*** Mirrors the timeline's mute/solo state into the graph without recreating existing tracks. Tracks are otherwise* only created when playback starts, so scrubbing (or a solo toggled after the last play) needs this to be audible correctly.*/- syncTrackStates(states: ReadonlyArray<{ trackId: string; muted: boolean; solo: boolean }>): void {+ syncTrackStates(states: ReadonlyArray<{ trackId: string; muted: boolean; solo: boolean; soloSafe?: boolean }>): void {for (const state of states) {const config = this.trackConfigs.get(state.trackId);if (!config) {- this.createTrack({ trackId: state.trackId, volume: 1, pan: 0, muted: state.muted, solo: state.solo, effects: [] });+ this.createTrack({ trackId: state.trackId, volume: 1, pan: 0, muted: state.muted, solo: state.solo, soloSafe: state.soloSafe === true, effects: [] });continue;}config.muted = state.muted;config.solo = state.solo;+ config.soloSafe = state.soloSafe === true;}this.updateSoloState();}@@ -847,12 +868,7 @@ export class RealtimeAudioGraph {const config = this.trackConfigs.get(trackId);if (!nodes || !config) return;- let audible = true;- if (config.muted) {- audible = false;- } else if (this.hasSoloTracks && !config.solo) {- audible = false;- }+ const audible = isTrackAudible(config, this.hasSoloTracks);const targetGain = audible ? config.volume : 0;nodes.outputGain.gain.setValueAtTime(@@ -942,10 +958,44 @@ export class RealtimeAudioGraph {rebuild.push(scheduled.schedule);}}- for (const schedule of rebuild) this.scheduleClip(schedule, { fadeInSeconds: STRETCH_SWAP_FADE_SECONDS });+ this.scheduleBatch(() => { for (const schedule of rebuild) this.scheduleClip(schedule, { fadeInSeconds: STRETCH_SWAP_FADE_SECONDS }); });}- scheduleClip(schedule: AudioClipSchedule, options: { fadeInSeconds?: number } = {}): void {+ /**+ * One (audio-context time, timeline time) pair for a whole scheduling batch. Clips that start+ * "now" begin at the audio thread's next render quantum, so their media offsets must all be+ * computed from the same instant: reading the clock per clip lets the audio clock advance+ * between two clips of one batch (several ms on a starved main thread), which starts them with+ * offsets that disagree by that gap and leaves sibling tracks out of sync (and out of phase).+ */+ private scheduleAnchor: { contextTime: number; timelineTime: number } | null = null;++ private captureScheduleAnchor(): { contextTime: number; timelineTime: number } {+ // The clock derives from the context time, so re-read until both reads saw the same context time.+ let contextTime = this.audioContext.currentTime;+ let timelineTime = this.masterClock.currentTime;+ for (let attempt = 0; attempt < 8 && this.audioContext.currentTime !== contextTime; attempt++) {+ contextTime = this.audioContext.currentTime;+ timelineTime = this.masterClock.currentTime;+ }+ return { contextTime, timelineTime };+ }++ private scheduleBatch(run: () => void): void {+ if (this.scheduleAnchor) { run(); return; }+ this.scheduleAnchor = this.captureScheduleAnchor();+ try { run(); } finally { this.scheduleAnchor = null; }+ }++ /** The schedule with its source buffer swapped for the clip's channels (cached per buffer + map), so stretch, rebuilds and scrub grains all see them. */+ private withChannelMap(schedule: AudioClipSchedule): AudioClipSchedule {+ if (!schedule.channelMap) return schedule;+ const { channelMap, ...rest } = schedule;+ return { ...rest, audioBuffer: mapAudioBuffer(this.audioContext, schedule.audioBuffer, channelMap) };+ }++ scheduleClip(rawSchedule: AudioClipSchedule, options: { fadeInSeconds?: number } = {}): void {+ const schedule = this.withChannelMap(rawSchedule);if (!this.trackNodes.has(schedule.trackId)) {this.createTrack({ trackId: schedule.trackId, volume: 1, pan: 0, muted: false, solo: false, effects: [] });}@@ -1000,16 +1050,22 @@ export class RealtimeAudioGraph {// lookahead effects `lead` is 0 and this is the plain schedule.const chainLatency = chain ? effectChainLatencySamples(processingEffects, this.audioContext.sampleRate || 48000) / (this.audioContext.sampleRate || 48000) : 0;const lead = this.routing.getTotalLatencySeconds() + chainLatency;- const effectiveNow = this.masterClock.currentTime + lead;+ const anchor = this.scheduleAnchor ?? this.captureScheduleAnchor();+ // Clips already under the playhead start SCHEDULE_START_LOOKAHEAD_SECONDS ahead of the anchor, at an+ // explicit context time, with their offset advanced by the same amount. A start("now") takes effect at+ // whichever render quantum the audio thread reaches when it handles that message, so two clips+ // scheduled in one batch can land quanta apart (2.7 ms each) and play out of phase; an explicit time+ // keeps them sample-aligned to each other and to the timeline as long as the batch finishes inside it.+ const effectiveNow = anchor.timelineTime + lead + SCHEDULE_START_LOOKAHEAD_SECONDS;const clipOffset = Math.max(0, effectiveNow - schedule.startTime);// The stretched render starts at the clip's first used source sample.const mediaOffset = stretched ? 0 : schedule.mediaOffset;const sourceOffset = clipOffset * speed + mediaOffset;const playbackDuration = Math.min(duration - clipOffset, (clipBuffer.duration - sourceOffset) / speed);const startsLater = schedule.startTime > effectiveNow;- const sourceStartTime = this.audioContext.currentTime + Math.max(0, schedule.startTime - effectiveNow);+ const sourceStartTime = anchor.contextTime + SCHEDULE_START_LOOKAHEAD_SECONDS + Math.max(0, schedule.startTime - effectiveNow);// Gains and fades sit after the clip chain: they see the signal chainLatency later.- const playbackStartTime = (startsLater ? sourceStartTime : this.audioContext.currentTime) + chainLatency;+ const playbackStartTime = sourceStartTime + chainLatency;if (!(playbackDuration > 0) || !Number.isFinite(playbackDuration)) { release(); return; }scheduleVolumeAutomationOnGain(clipGain, schedule.volumeAutomation, schedule.volume, clipOffset, playbackDuration, playbackStartTime);if (!panner) schedulePanAutomationOnParam((clipPan as StereoPannerNode).pan, schedule.panAutomation, basePan, clipOffset, playbackDuration, playbackStartTime);@@ -1020,7 +1076,7 @@ export class RealtimeAudioGraph {swapGain.gain.setValueAtTime(0, playbackStartTime);swapGain.gain.linearRampToValueAtTime(1, playbackStartTime + options.fadeInSeconds);}- source.start(startsLater ? sourceStartTime : 0, sourceOffset, playbackDuration * speed);+ source.start(sourceStartTime, sourceOffset, playbackDuration * speed);// Shared by natural end and the stretch swap: effect tails (reverb, delay) ring out instead of being cut.const onSourceEnded = () => {if (released) return;@@ -1073,7 +1129,7 @@ export class RealtimeAudioGraph {if (!trackNodes) continue;while (this.scrubGrains.length >= SCRUB_MAX_GRAINS) this.scrubGrains[0].release();const source = this.audioContext.createBufferSource();- source.buffer = schedule.audioBuffer;+ source.buffer = this.withChannelMap(schedule).audioBuffer;const speed = Number.isFinite(schedule.speed) && schedule.speed > 0 ? schedule.speed : 1;source.playbackRate.value = speed;const gain = this.audioContext.createGain();@@ -1113,9 +1169,7 @@ export class RealtimeAudioGraph {}scheduleClips(schedules: AudioClipSchedule[]): void {- for (const schedule of schedules) {- this.scheduleClip(schedule);- }+ this.scheduleBatch(() => { for (const schedule of schedules) this.scheduleClip(schedule); });}stopAllClips(): void {@@ -1173,7 +1227,7 @@ export class RealtimeAudioGraph {if (scheduleUntil > this.lastScheduledTime) {const clips = getClipsAtTime(this.lastScheduledTime);- for (const clip of clips) {+ this.scheduleBatch(() => { for (const clip of clips) {if (clip.startTime <= scheduleUntil &&clip.endTime > this.lastScheduledTime@@ -1187,7 +1241,7 @@ export class RealtimeAudioGraph {this.scheduleClip(clip);}}- }+ } });this.lastScheduledTime = scheduleUntil;}};@@ -1235,6 +1289,7 @@ export class RealtimeAudioGraph {this.masterBus.dispose();this.masterGain.disconnect();this.masterOutput.disconnect();+ getAudioOutputRouter().detach(this.audioContext);}}diff --git a/packages/core/src/audio/track-audibility.test.ts b/packages/core/src/audio/track-audibility.test.tsnew file mode 100644index 00000000..dfd68556--- /dev/null+++ b/packages/core/src/audio/track-audibility.test.ts@@ -0,0 +1,225 @@+import { describe, expect, it, vi } from "vitest";+import type { Project } from "../types/project";+import type { Clip, Track } from "../types/timeline";+import { AudioEngine } from "./audio-engine";+import { audioRangeFingerprint } from "./mixdown-cache";+import { RealtimeAudioGraph } from "./realtime-audio-graph";+import type { MasterTimelineClock } from "../playback/master-timeline-clock";+import {+ computeTrackAudibility,+ hasAnySoloedTrack,+ isTrackAudible,+ isTrackSoloSuppressed,+ type TrackAudibilityInput,+} from "./track-audibility";++const BOOLS = [false, true] as const;++/** Independent restatement of the rule: the table the UI and the export both have to honour. */+function expected(muted: boolean, solo: boolean, soloSafe: boolean, anySolo: boolean): boolean {+ if (muted) return false; // mute always wins+ if (!anySolo) return true; // nothing soloed: everything unmuted plays+ if (solo) return true; // soloed tracks play+ return soloSafe; // others are silenced unless solo-safe+}++describe("solo / solo-safe mute matrix", () => {+ for (const muted of BOOLS) for (const solo of BOOLS) for (const soloSafe of BOOLS) for (const anySolo of BOOLS) {+ // anySolo=false with solo=true is impossible (the track itself would be a solo).+ if (solo && !anySolo) continue;+ it(`muted=${muted} solo=${solo} soloSafe=${soloSafe} anySolo=${anySolo}`, () => {+ expect(isTrackAudible({ muted, solo, soloSafe }, anySolo)).toBe(expected(muted, solo, soloSafe, anySolo));+ });+ }++ it("treats a missing soloSafe (older projects) as off", () => {+ expect(isTrackAudible({ muted: false, solo: false }, true)).toBe(false);+ expect(isTrackAudible({ muted: false, solo: false }, false)).toBe(true);+ });++ it("solo-safe alone never counts as a solo", () => {+ expect(hasAnySoloedTrack([{ solo: false }, { solo: false }])).toBe(false);+ expect(hasAnySoloedTrack([{ solo: false }, { solo: true }])).toBe(true);+ });++ it("reports which tracks are being silenced by someone else's solo", () => {+ expect(isTrackSoloSuppressed({ muted: false, solo: false }, true)).toBe(true);+ expect(isTrackSoloSuppressed({ muted: false, solo: false, soloSafe: true }, true)).toBe(false);+ expect(isTrackSoloSuppressed({ muted: false, solo: true }, true)).toBe(false);+ expect(isTrackSoloSuppressed({ muted: true, solo: false }, true)).toBe(false);+ expect(isTrackSoloSuppressed({ muted: false, solo: false }, false)).toBe(false);+ });++ it("computes a whole timeline: dialogue soloed, music solo-safe, fx muted-and-safe, rest silenced", () => {+ const tracks = [+ { id: "dialogue", muted: false, solo: true },+ { id: "music", muted: false, solo: false, soloSafe: true },+ { id: "fx", muted: true, solo: false, soloSafe: true },+ { id: "ambience", muted: false, solo: false },+ ];+ const audibility = computeTrackAudibility(tracks);+ expect([...audibility.entries()]).toEqual([+ ["dialogue", true],+ ["music", true],+ ["fx", false],+ ["ambience", false],+ ]);+ // Clear the solo: everything unmuted plays again, solo-safe or not.+ const cleared = computeTrackAudibility(tracks.map((t) => ({ ...t, solo: false })));+ expect(cleared.get("ambience")).toBe(true);+ expect(cleared.get("fx")).toBe(false);+ });++ it("matches the exhaustive matrix for every pair of tracks", () => {+ const states: TrackAudibilityInput[] = [];+ for (const muted of BOOLS) for (const solo of BOOLS) for (const soloSafe of BOOLS) states.push({ muted, solo, soloSafe });+ for (const a of states) for (const b of states) {+ const anySolo = a.solo || b.solo;+ const result = computeTrackAudibility([{ id: "a", ...a }, { id: "b", ...b }]);+ expect(result.get("a")).toBe(expected(a.muted, a.solo, a.soloSafe === true, anySolo));+ expect(result.get("b")).toBe(expected(b.muted, b.solo, b.soloSafe === true, anySolo));+ }+ });+});++const clip = (id: string, trackId: string): Clip => ({+ id, mediaId: "m1", trackId, startTime: 0, duration: 10, inPoint: 0, outPoint: 10,+ effects: [], audioEffects: [],+ transform: { position: { x: 0, y: 0 }, scale: { x: 1, y: 1 }, rotation: 0, anchor: { x: 0.5, y: 0.5 }, opacity: 1 },+ volume: 1, keyframes: [],+});+const track = (id: string, over: Partial<Track> = {}): Track => ({+ id, type: "audio", name: id, clips: [clip(`${id}-c`, id)], transitions: [], locked: false, hidden: false, muted: false, solo: false, ...over,+});+const project = (tracks: Track[]): Project => ({+ id: "p", name: "P", createdAt: 0, modifiedAt: 0,+ settings: { width: 1920, height: 1080, frameRate: 30, sampleRate: 48000, channels: 2 },+ timeline: { duration: 60, markers: [], subtitles: [], tracks },+ mediaLibrary: { items: [{ id: "m1", name: "a.wav", type: "audio", blob: null, fileHandle: null, thumbnailUrl: null, waveformData: null, metadata: { duration: 60 } }] },+} as unknown as Project);++describe("export mixdown honours solo-safe", () => {+ const engine = new AudioEngine();+ const internals = engine as unknown as {+ getAudioTracksAtTime(project: Project, start: number, duration: number, preview: boolean): Array<{ trackId: string; muted: boolean; solo: boolean; soloSafe?: boolean }>;+ };+ const decide = (p: Project): Record<string, boolean> => {+ const infos = internals.getAudioTracksAtTime(p, 0, 5, false);+ const anySolo = p.timeline.tracks.some((t) => !t.hidden && t.solo);+ return Object.fromEntries(infos.map((info) => [info.trackId, !engine.isTrackMuted(info as unknown as Parameters<typeof engine.isTrackMuted>[0], anySolo)]));+ };++ it("keeps a solo-safe track in the mix while another track is soloed", () => {+ const p = project([track("dialogue", { solo: true }), track("music", { soloSafe: true }), track("ambience")]);+ expect(decide(p)).toEqual({ dialogue: true, music: true, ambience: false });+ });++ it("without solo-safe the unsoloed tracks are silenced, exactly as before", () => {+ const p = project([track("dialogue", { solo: true }), track("music"), track("ambience")]);+ expect(decide(p)).toEqual({ dialogue: true, music: false, ambience: false });+ });++ it("mute beats solo-safe", () => {+ const p = project([track("dialogue", { solo: true }), track("music", { soloSafe: true, muted: true })]);+ expect(decide(p)).toEqual({ dialogue: true, music: false });+ });++ it("agrees with getEffectiveTrackAudibility (the mixer's view of the same state)", () => {+ const tracks = [track("a", { solo: true }), track("b", { soloSafe: true }), track("c")];+ const view = engine.getEffectiveTrackAudibility(tracks);+ expect(Object.fromEntries(view)).toEqual({ a: true, b: true, c: false });+ });++ it("plays everything when nothing is soloed regardless of solo-safe", () => {+ const p = project([track("a", { soloSafe: true }), track("b")]);+ expect(decide(p)).toEqual({ a: true, b: true });+ });++ it("changes the mixdown cache fingerprint when solo-safe is toggled", () => {+ const base = project([track("a", { solo: true }), track("b")]);+ const safe = project([track("a", { solo: true }), track("b", { soloSafe: true })]);+ expect(audioRangeFingerprint(safe, 0, 10)).not.toBe(audioRangeFingerprint(base, 0, 10));+ });+});++describe("live graph honours solo-safe", () => {+ function graphFixture() {+ const param = () => ({ value: 1, setValueAtTime: vi.fn(), linearRampToValueAtTime: vi.fn(), cancelScheduledValues: vi.fn() });+ const node = () => ({ connect: vi.fn(), disconnect: vi.fn() });+ const context = {+ currentTime: 5,+ destination: node(),+ createGain: () => ({ ...node(), gain: param() }),+ createStereoPanner: () => ({ ...node(), pan: param() }),+ createDynamicsCompressor: () => node(),+ createBiquadFilter: () => ({ ...node(), frequency: param(), Q: param(), gain: param() }),+ createAnalyser: () => node(),+ createBufferSource: () => ({ ...node(), start: vi.fn(), stop: vi.fn(), playbackRate: param() }),+ createChannelMerger: () => node(),+ createChannelSplitter: () => node(),+ audioWorklet: { addModule: () => Promise.resolve() },+ state: "running",+ };+ const clock = { getAudioContext: () => context, currentTime: 0, isPlaying: false } as unknown as MasterTimelineClock;+ return new RealtimeAudioGraph(clock);+ }+ const lastGain = (graph: RealtimeAudioGraph, id: string): number | undefined => {+ const out = graph.getTrackOutputGain(id) as unknown as { gain: { setValueAtTime: ReturnType<typeof vi.fn> } } | null;+ return out?.gain.setValueAtTime.mock.calls.at(-1)?.[0] as number | undefined;+ };++ it("keeps a solo-safe track audible while another is soloed, and silences the rest", () => {+ const graph = graphFixture();+ graph.syncTrackStates([+ { trackId: "dialogue", muted: false, solo: true },+ { trackId: "music", muted: false, solo: false, soloSafe: true },+ { trackId: "ambience", muted: false, solo: false },+ { trackId: "fx", muted: true, solo: false, soloSafe: true },+ ]);+ expect(lastGain(graph, "dialogue")).toBe(1);+ expect(lastGain(graph, "music")).toBe(1);+ expect(lastGain(graph, "ambience")).toBe(0);+ expect(lastGain(graph, "fx")).toBe(0);+ graph.dispose();+ });++ it("follows solo-safe toggled live, and clearing the solo restores everyone", () => {+ const graph = graphFixture();+ graph.syncTrackStates([+ { trackId: "dialogue", muted: false, solo: true },+ { trackId: "music", muted: false, solo: false },+ ]);+ expect(lastGain(graph, "music")).toBe(0);+ graph.setTrackSoloSafe("music", true);+ expect(lastGain(graph, "music")).toBe(1);+ graph.setTrackSoloSafe("music", false);+ expect(lastGain(graph, "music")).toBe(0);+ graph.syncTrackStates([+ { trackId: "dialogue", muted: false, solo: false },+ { trackId: "music", muted: false, solo: false },+ ]);+ expect(lastGain(graph, "music")).toBe(1);+ graph.dispose();+ });+});++describe("track/setSoloSafe action (saved with the project)", () => {+ it("toggles the flag as one undoable action, survives a JSON round-trip and rejects bad params", async () => {+ const { ActionExecutor } = await import("../actions/action-executor");+ const p = project([track("a"), track("b")]);+ const executor = new ActionExecutor();+ const set = (soloSafe: unknown, trackId = "b") =>+ executor.execute({ type: "track/setSoloSafe", id: "s", timestamp: 1, params: { trackId, soloSafe } } as never, p);+ expect((await set(true)).success).toBe(true);+ expect(p.timeline.tracks[1].soloSafe).toBe(true);+ expect(p.timeline.tracks[0].soloSafe).toBeUndefined();+ const saved = JSON.parse(JSON.stringify(p)) as Project;+ expect(saved.timeline.tracks[1].soloSafe).toBe(true);+ expect((await executor.undo(p)).success).toBe(true);+ expect(p.timeline.tracks[1].soloSafe).toBeUndefined();+ expect((await executor.redo(p)).success).toBe(true);+ expect(p.timeline.tracks[1].soloSafe).toBe(true);+ expect((await set("yes")).success).toBe(false);+ expect((await set(true, "missing")).success).toBe(false);+ });+});diff --git a/packages/core/src/audio/track-audibility.ts b/packages/core/src/audio/track-audibility.tsnew file mode 100644index 00000000..f2089619--- /dev/null+++ b/packages/core/src/audio/track-audibility.ts@@ -0,0 +1,43 @@+/**+ * Track mute / solo / solo-safe audibility.+ *+ * One rule shared by the live graph, the offline mixdown (preview render and export) and the+ * mixer UI so they can never disagree:+ *+ * audible = !muted && (!anySolo || solo || soloSafe)+ *+ * - Mute always wins: a muted track is silent even if it is solo-safe or soloed.+ * - Solo on any track silences every other track...+ * - ...except solo-safe tracks (Premiere's "Solo Safe"): they keep playing while others are soloed.+ * - A solo-safe track that is itself soloed is just soloed; solo-safe never makes a track "a solo".+ */+export interface TrackAudibilityInput {+ readonly muted: boolean;+ readonly solo: boolean;+ /** Absent = false (projects saved before solo-safe existed). */+ readonly soloSafe?: boolean;+}++/** True when at least one of the tracks is soloed (solo-safe alone does not count). */+export function hasAnySoloedTrack(tracks: Iterable<Pick<TrackAudibilityInput, "solo">>): boolean {+ for (const track of tracks) if (track.solo) return true;+ return false;+}++export function isTrackAudible(track: TrackAudibilityInput, anySolo: boolean): boolean {+ if (track.muted) return false;+ if (!anySolo) return true;+ return track.solo || track.soloSafe === true;+}++/** True when solo on another track is silencing this track (it is not muted, soloed or solo-safe). */+export function isTrackSoloSuppressed(track: TrackAudibilityInput, anySolo: boolean): boolean {+ return anySolo && !track.muted && !track.solo && track.soloSafe !== true;+}++export function computeTrackAudibility<T extends TrackAudibilityInput & { readonly id: string }>(+ tracks: readonly T[],+): Map<string, boolean> {+ const anySolo = hasAnySoloedTrack(tracks);+ return new Map(tracks.map((track) => [track.id, isTrackAudible(track, anySolo)]));+}diff --git a/packages/core/src/audio/types.ts b/packages/core/src/audio/types.tsindex 25bfc126..8307c05a 100644--- a/packages/core/src/audio/types.ts+++ b/packages/core/src/audio/types.ts@@ -18,6 +18,8 @@ export interface AudioTrackRenderInfo {readonly index: number;readonly muted: boolean;readonly solo: boolean;+ /** Solo Safe: stays audible while other tracks are soloed. */+ readonly soloSafe?: boolean;readonly clips: AudioClipRenderInfo[];}@@ -39,6 +41,8 @@ export interface AudioClipRenderInfo {readonly pitchCorrection?: boolean;/** 5.1 sequences only: the clip's resolved surround position (clip, else track). */readonly surroundPan?: import("./surround").SurroundPan;+ /** Audio Channels mapping (clip, else the media's import preset); applied to the decoded source before anything else. */+ readonly channelMap?: import("./channel-map").ClipChannelMap;readonly effects: Effect[];readonly fadeIn?: number;readonly fadeOut?: number;@@ -57,6 +61,7 @@ export interface AudioChannelState {readonly pan: number;readonly muted: boolean;readonly solo: boolean;+ readonly soloSafe?: boolean;readonly peakLevel: number;readonly rmsLevel: number;}diff --git a/packages/core/src/capabilities/manifest.test.ts b/packages/core/src/capabilities/manifest.test.tsindex 730dd432..f2046fe2 100644--- a/packages/core/src/capabilities/manifest.test.ts+++ b/packages/core/src/capabilities/manifest.test.ts@@ -101,8 +101,8 @@ describe("CAPABILITY_MANIFEST superseded legacy effects", () => {});describe("CAPABILITY_MANIFEST premiere parity", () => {- it("lists all forty-four pro effects with valid numeric ranges and neutral values", () => {- expect(CAPABILITY_MANIFEST.proEffects).toHaveLength(44);+ it("lists all forty-seven pro effects with valid numeric ranges and neutral values", () => {+ expect(CAPABILITY_MANIFEST.proEffects).toHaveLength(47);for (const effect of CAPABILITY_MANIFEST.proEffects) {expect(effect.params.length).toBeGreaterThan(0);for (const param of effect.params) {diff --git a/packages/core/src/captions/caption-export.test.ts b/packages/core/src/captions/caption-export.test.tsindex 3842e809..4bf93b5c 100644--- a/packages/core/src/captions/caption-export.test.ts+++ b/packages/core/src/captions/caption-export.test.ts@@ -34,6 +34,12 @@ describe("burn-in", () => {expect(burnedInSubtitles(cues, undefined)).toHaveLength(2);expect(burnedInSubtitles(cues, settings([]))).toHaveLength(2);});+ it("never burns in hidden cues, with or without settings", () => {+ const withHidden: Subtitle[] = [cues[0], { ...cues[1], hidden: true }];+ expect(burnedInSubtitles(withHidden, undefined).map((c) => c.id)).toEqual(["a"]);+ expect(burnedInSubtitles(withHidden, settings([{ captionTrackId: "es", burnIn: true, sidecar: "none", embedded: "none" }])).map((c) => c.id)).toEqual(["a"]);+ expect(captionsChangeBurnIn(withHidden, undefined)).toBe(true);+ });it("leaves out tracks that are not burned in", () => {const s = settings([{ captionTrackId: "es", burnIn: false, sidecar: "none", embedded: "none" }]);expect(burnedInSubtitles(cues, s).map((c) => c.id)).toEqual(["a"]);diff --git a/packages/core/src/captions/caption-export.ts b/packages/core/src/captions/caption-export.tsindex 13e53666..4aa4f804 100644--- a/packages/core/src/captions/caption-export.ts+++ b/packages/core/src/captions/caption-export.ts@@ -58,13 +58,14 @@ export function trackExportSettings(};}-/** Cues that must be drawn into the picture (a track with no entry is burned in). */+/** Cues that must be drawn into the picture (a track with no entry is burned in unless its cues are hidden). */export function burnedInSubtitles(subtitles: readonly Subtitle[],captions: CaptionExportSettings | undefined,): Subtitle[] {- if (!captions || !captions.tracks.length) return subtitles.slice();- return subtitles.filter((cue) => trackExportSettings(captions, trackOf(cue)).burnIn);+ const shown = subtitles.filter((cue) => !cue.hidden);+ if (!captions || !captions.tracks.length) return shown;+ return shown.filter((cue) => trackExportSettings(captions, trackOf(cue)).burnIn);}/** True when the settings remove cues from the picture, so cached preview frames cannot be reused. */diff --git a/packages/core/src/captions/caption-formats.ts b/packages/core/src/captions/caption-formats.tsindex a450653c..46c82dfe 100644--- a/packages/core/src/captions/caption-formats.ts+++ b/packages/core/src/captions/caption-formats.ts@@ -1,10 +1,12 @@import type { CueSettings, Subtitle, SubtitleStyle } from "../types/timeline";import { encodeScc, isSccContent, parseScc, type CaptionFormatIssue } from "./scc";import { encodeStl, isStlContent, parseStl } from "./ebu-stl";+import { encodeSbv, isSbvContent, parseSbv } from "./sbv";+import { isTtmlContent, parseTtml } from "./ttml";/**- * Caption interchange: SRT and WebVTT import, SRT / WebVTT / TTML (IMSC1 text- * profile) export. Pure functions over `Subtitle[]`; the editor commits the+ * Caption interchange: SRT, WebVTT, SBV and TTML / DFXP import, SRT / WebVTT / SBV / TTML+ * (IMSC1 text profile) export. Pure functions over `Subtitle[]`; the editor commits the* result through the action system.** Speakers travel as WebVTT voice tags (`<v Name>`); SRT has no standard for@@ -19,7 +21,7 @@ import { encodeStl, isStlContent, parseStl } from "./ebu-stl";export interface CaptionParseResult {subtitles: Subtitle[];errors: Array<{ line: number; message: string }>;- format: "srt" | "vtt" | "scc" | "stl";+ format: "srt" | "vtt" | "scc" | "stl" | "ttml" | "sbv";/** Format-specific notes (SCC / STL decoding). */issues?: CaptionFormatIssue[];}@@ -184,11 +186,24 @@ export interface CaptionImportOptions {/** Parse SRT, WebVTT or SCC (auto-detected). Malformed blocks are reported, not fatal. */export function parseCaptions(content: string, options: CaptionImportOptions = {}): CaptionParseResult {+ if (isTtmlContent(content)) {+ const r = parseTtml(content, options);+ return { subtitles: r.subtitles, errors: r.errors, format: "ttml", issues: r.issues };+ }+ // XML / HTML that is not TTML. A plain SRT/VTT/SBV whose first cue merely starts with an inline tag+ // (`<i>`, `<b>`...) has timing arrows and is parsed normally below.+ if (/^\s*(?:\uFEFF)?<(?:\?xml|!|[A-Za-z])/.test(content) && !/-->|^\s*\d+:\d{2}:\d{2}[.,]\d+\s*,/m.test(content.slice(0, 4096))) {+ return { subtitles: [], errors: [{ line: 1, message: "Not a TTML caption file: no <tt> root element was found." }], format: "ttml" };+ }+ if (isSbvContent(content)) {+ const r = parseSbv(content, options);+ return { subtitles: r.subtitles, errors: r.errors, format: "sbv", issues: r.issues };+ }if (isSccContent(content)) {const r = parseScc(content, options);return { subtitles: r.subtitles, errors: r.errors, format: "scc", issues: r.issues };}- const text = content.replace(/^/, "").replace(/\r\n?/g, "\n");+ const text = content.replace(/^\uFEFF/, "").replace(/\r\n?/g, "\n");const format: "srt" | "vtt" = text.trimStart().startsWith("WEBVTT") ? "vtt" : "srt";const lines = text.split("\n");const subtitles: Subtitle[] = [];@@ -294,10 +309,44 @@ export function exportTtml((name) =>` <ttm:agent xml:id="${agentId.get(name)}" type="person"><ttm:name type="alias">${escapeXml(name)}</ttm:name></ttm:agent>`,);+ // Cues positioned away from the default bottom edge get their own region (box bottom edge = line %).+ const regionKeys = new Map<number, string>();+ const lineOf = (cue: Subtitle): number => {+ const settings = cue.cueSettings;+ if (settings && settings.snapToLines === false && typeof settings.line === "number") return Math.min(100, Math.max(18, Math.round(settings.line * 100) / 100));+ const pos = cue.style?.position;+ return pos === "top" ? 23 : pos === "center" ? 59 : 96;+ };+ for (const cue of cues) {+ const line = lineOf(cue);+ if (line !== 96 && !regionKeys.has(line)) regionKeys.set(line, `r${regionKeys.size + 2}`);+ }+ // One <style> per distinct cue look (colour, box, font, outline); cues without a custom style share the default s1.+ const toTtmlFont = (family: string): string => {+ const f = family.toLowerCase();+ return f === "monospace" ? "monospace" : f === "serif" ? "serif" : f === "sans-serif" ? "proportionalSansSerif" : family;+ };+ const styleAttrs = (cue: Subtitle): string => {+ const st = cue.style;+ if (!st) return "";+ const parts: string[] = [];+ if (st.fontFamily && st.fontFamily !== "Inter") parts.push(`tts:fontFamily="${escapeXml(toTtmlFont(st.fontFamily))}"`);+ if (st.color) parts.push(`tts:color="${escapeXml(st.color)}"`);+ if (st.backgroundColor) parts.push(`tts:backgroundColor="${escapeXml(st.backgroundColor)}"`);+ if (st.strokeColor && (st.strokeWidth ?? 0) > 0) parts.push(`tts:textOutline="${escapeXml(st.strokeColor)} ${st.strokeWidth}px"`);+ return parts.join(" ");+ };+ const styleIds = new Map<string, string>();+ for (const cue of cues) {+ const attrs = styleAttrs(cue);+ if (attrs && !styleIds.has(attrs)) styleIds.set(attrs, `s${styleIds.size + 2}`);+ }const paragraphs = cues.map((cue, index) => {+ const regionId = regionKeys.get(lineOf(cue)) ?? "r1";+ const styleId = styleIds.get(styleAttrs(cue)) ?? "s1";const lines = cue.text.split("\n").map(escapeXml).join("<br/>");const agent = cue.speaker ? ` ttm:agent="${agentId.get(cue.speaker)}"` : "";- return ` <p xml:id="c${index + 1}" begin="${formatVttTime(cue.startTime)}" end="${formatVttTime(cue.endTime)}" region="r1" style="s1"${agent}>${lines}</p>`;+ return ` <p xml:id="c${index + 1}" begin="${formatVttTime(cue.startTime)}" end="${formatVttTime(cue.endTime)}" region="${regionId}" style="${styleId}"${agent}>${lines}</p>`;});return [`<?xml version="1.0" encoding="UTF-8"?>`,@@ -306,9 +355,14 @@ export function exportTtml(...(agents.length ? [` <metadata>`, ...agents, ` </metadata>`] : []),` <styling>`,` <style xml:id="s1" tts:fontFamily="proportionalSansSerif" tts:fontSize="100%" tts:color="#FFFFFF" tts:backgroundColor="#000000B3" tts:textAlign="center"/>`,+ ...[...styleIds].map(([attrs, id]) => ` <style xml:id="${id}" style="s1" ${attrs}/>`),` </styling>`,` <layout>`,` <region xml:id="r1" tts:origin="10% 78%" tts:extent="80% 18%" tts:displayAlign="after" tts:textAlign="center"/>`,+ ...[...regionKeys].map(+ ([line, id]) =>+ ` <region xml:id="${id}" tts:origin="10% ${line - 18}%" tts:extent="80% 18%" tts:displayAlign="after" tts:textAlign="center"/>`,+ ),` </layout>`,` </head>`,` <body>`,@@ -321,8 +375,8 @@ export function exportTtml(].join("\n");}-export type CaptionExportFormat = "srt" | "vtt" | "ttml" | "scc" | "stl";-export const CAPTION_EXPORT_FORMATS: readonly CaptionExportFormat[] = ["srt", "vtt", "ttml", "scc", "stl"];+export type CaptionExportFormat = "srt" | "vtt" | "sbv" | "ttml" | "scc" | "stl";+export const CAPTION_EXPORT_FORMATS: readonly CaptionExportFormat[] = ["srt", "vtt", "sbv", "ttml", "scc", "stl"];export interface CaptionExportOptions extends CaptionTrackSelect {includeSpeakers?: boolean;@@ -342,6 +396,7 @@ export const CAPTION_FORMAT_INFO: Readonly<> = {srt: { label: "SRT", extension: "srt", mimeType: "application/x-subrip", binary: false },vtt: { label: "WebVTT", extension: "vtt", mimeType: "text/vtt", binary: false },+ sbv: { label: "SBV (YouTube)", extension: "sbv", mimeType: "text/plain", binary: false },ttml: { label: "TTML (IMSC1)", extension: "ttml", mimeType: "application/ttml+xml", binary: false },scc: { label: "SCC (CEA-608)", extension: "scc", mimeType: "text/x-scc", binary: false },stl: { label: "EBU-STL", extension: "stl", mimeType: "application/octet-stream", binary: true },@@ -356,6 +411,7 @@ export function exportCaptions(if (format === "srt") return exportSrt(subtitles, options);if (format === "vtt") return exportVtt(subtitles, options);if (format === "ttml") return exportTtml(subtitles, options);+ if (format === "sbv") return encodeSbv(select(subtitles, options)).content;if (format === "scc") return encodeScc(subtitles, options).content;if (format === "stl") throw new Error("EBU-STL is a binary format: use exportCaptionFile.");throw new Error(`Unsupported caption format "${String(format)}". Use ${CAPTION_EXPORT_FORMATS.join(", ")}.`);@@ -389,17 +445,28 @@ export function exportCaptionFile(bytes: new TextEncoder().encode(exportCaptions(subtitles, format, options)),mimeType: info.mimeType,extension: info.extension,- issues: [],+ issues: format === "sbv" ? encodeSbv(select(subtitles, options)).issues : [],};}+/** Text caption bytes -> string: UTF-16 by BOM, UTF-8, else Windows-1252 (legacy SRT files). */+export function decodeCaptionText(bytes: Uint8Array): string {+ if (bytes.length >= 2 && bytes[0] === 0xff && bytes[1] === 0xfe) return new TextDecoder("utf-16le").decode(bytes.subarray(2));+ if (bytes.length >= 2 && bytes[0] === 0xfe && bytes[1] === 0xff) return new TextDecoder("utf-16be").decode(bytes.subarray(2));+ try {+ return new TextDecoder("utf-8", { fatal: true }).decode(bytes);+ } catch {+ return new TextDecoder("windows-1252").decode(bytes);+ }+}+/** Parse caption file bytes: EBU-STL is detected by its GSI block, everything else is decoded as text. */export function parseCaptionBytes(bytes: Uint8Array, options: CaptionImportOptions = {}): CaptionParseResult {if (isStlContent(bytes)) {const r = parseStl(bytes, options);return { subtitles: r.subtitles, errors: r.errors, format: "stl", issues: r.issues };}- return parseCaptions(new TextDecoder("utf-8").decode(bytes), options);+ return parseCaptions(decodeCaptionText(bytes), options);}/** A caption track is a distinct `captionTrackId`; "" is the default track. */diff --git a/packages/core/src/captions/caption-layout.ts b/packages/core/src/captions/caption-layout.tsindex 2d5b9e65..5d5fe21c 100644--- a/packages/core/src/captions/caption-layout.ts+++ b/packages/core/src/captions/caption-layout.ts@@ -32,6 +32,24 @@ export interface CaptionLayout {}export const DEFAULT_CAPTION_FONT_SIZE = 24;++/** The caption look an imported cue starts from before a format overrides individual properties. */+export const DEFAULT_CAPTION_STYLE: SubtitleStyle = {+ fontFamily: "Inter",+ fontSize: DEFAULT_CAPTION_FONT_SIZE,+ color: "#ffffff",+ backgroundColor: "rgba(0, 0, 0, 0.7)",+ position: "bottom",+};++const GENERIC_CSS_FAMILIES = new Set(["serif", "sans-serif", "monospace", "cursive", "fantasy", "system-ui"]);++/** CSS font shorthand for a caption. Generic families must not be quoted or the browser treats them as a missing font name (serif fallback). */+export function captionFont(fontSize: number, fontFamily: string | undefined): string {+ const family = (fontFamily || "Inter").trim();+ const css = GENERIC_CSS_FAMILIES.has(family.toLowerCase()) ? family.toLowerCase() : `"${family}"`;+ return `bold ${fontSize}px ${css}, sans-serif`;+}const LINE_HEIGHT_RATIO = 1.3;const clamp = (v: number, lo: number, hi: number) => Math.min(hi, Math.max(lo, v));@@ -199,7 +217,7 @@ export function drawCaption(ctx: Ctx2D, subtitle: Subtitle, canvasWidth: number,const style: Partial<SubtitleStyle> = subtitle.style ?? {};const fontSize = style.fontSize || DEFAULT_CAPTION_FONT_SIZE;ctx.save();- ctx.font = `bold ${fontSize}px "${style.fontFamily || "Inter"}"`;+ ctx.font = captionFont(fontSize, style.fontFamily);ctx.textAlign = "left";ctx.textBaseline = "middle";const layout = layoutCaption(subtitle, canvasWidth, canvasHeight, (t) => ctx.measureText(t).width);diff --git a/packages/core/src/captions/caption-translate.test.ts b/packages/core/src/captions/caption-translate.test.tsnew file mode 100644index 00000000..982efb95--- /dev/null+++ b/packages/core/src/captions/caption-translate.test.ts@@ -0,0 +1,125 @@+import { describe, expect, it, vi } from "vitest";+import type { Subtitle } from "../types/timeline";+import {+ buildTranslationPrompt,+ parseTranslationReply,+ translateCaptionTrack,+ uniqueCaptionTrackId,+ type CaptionTranslator,+} from "./caption-translate";++const cue = (id: string, text: string, startTime: number, endTime: number, extra: Partial<Subtitle> = {}): Subtitle => ({+ id, text, startTime, endTime, ...extra,+});++const SUBS: Subtitle[] = [+ cue("a", "Hello", 0, 1, { speaker: "Ann", language: "en", words: [{ text: "Hello", startTime: 0, endTime: 1 }] }),+ cue("b", "World", 2, 3, { language: "en" }),+ cue("c", "Other track", 5, 6, { captionTrackId: "fr" }),+];++const upper: CaptionTranslator = {+ translate: async (texts) => texts.map((t) => `[es] ${t}`),+};++describe("translateCaptionTrack", () => {+ it("creates a new track preserving timing, speaker and style", async () => {+ const result = await translateCaptionTrack({ subtitles: SUBS, sourceTrackId: "", targetLanguage: "es", translator: upper });+ expect(result.ok).toBe(true);+ if (!result.ok) return;+ expect(result.trackId).toBe("es");+ expect(result.cues.map((c) => [c.text, c.startTime, c.endTime])).toEqual([+ ["[es] Hello", 0, 1],+ ["[es] World", 2, 3],+ ]);+ expect(result.cues[0].speaker).toBe("Ann");+ expect(result.cues.every((c) => c.captionTrackId === "es" && c.language === "es")).toBe(true);+ expect(result.cues[0].words).toBeUndefined();+ // Kept out of the picture so it never draws over the original at the same time and place.+ expect(result.cues.every((c) => c.hidden === true)).toBe(true);+ expect(new Set(result.cues.map((c) => c.id)).size).toBe(2);+ expect(SUBS[0].text).toBe("Hello");+ });++ it("batches and reports progress; passes the source language", async () => {+ const translate = vi.fn(upper.translate);+ const progress: number[] = [];+ const result = await translateCaptionTrack({+ subtitles: SUBS, sourceTrackId: "", targetLanguage: "es", batchSize: 1,+ translator: { translate }, onProgress: (p) => progress.push(p.done),+ });+ expect(result.ok).toBe(true);+ expect(translate).toHaveBeenCalledTimes(2);+ expect(translate.mock.calls[0][1]).toMatchObject({ sourceLanguage: "en", targetLanguage: "es" });+ expect(progress).toEqual([0, 1, 2]);+ });++ it("reports several progress steps even for a short track", async () => {+ const many = Array.from({ length: 10 }, (_, i) => cue(`m${i}`, `t${i}`, i, i + 1));+ const progress: number[] = [];+ const result = await translateCaptionTrack({ subtitles: many, sourceTrackId: "", targetLanguage: "es", translator: upper, onProgress: (p) => progress.push(p.done) });+ expect(result.ok).toBe(true);+ expect(progress.length).toBeGreaterThanOrEqual(5);+ });++ it("avoids clashing with an existing track id", async () => {+ const result = await translateCaptionTrack({ subtitles: SUBS, sourceTrackId: "", targetLanguage: "fr", translator: upper });+ expect(result.ok && result.trackId).toBe("fr-2");+ expect(uniqueCaptionTrackId(SUBS, "")).toBe("captions-2");+ });++ it("cancels between batches and returns no cues", async () => {+ const controller = new AbortController();+ const translate = vi.fn(async (texts: readonly string[]) => {+ controller.abort();+ return texts.map((t) => t);+ });+ const result = await translateCaptionTrack({+ subtitles: SUBS, sourceTrackId: "", targetLanguage: "es", batchSize: 1,+ translator: { translate }, signal: controller.signal,+ });+ expect(result).toMatchObject({ ok: false, reason: "cancelled" });+ expect(translate).toHaveBeenCalledTimes(1);+ });++ it("treats an AbortError from the translator as cancellation", async () => {+ const result = await translateCaptionTrack({+ subtitles: SUBS, sourceTrackId: "", targetLanguage: "es",+ translator: { translate: async () => { throw new DOMException("x", "AbortError"); } },+ });+ expect(result).toMatchObject({ ok: false, reason: "cancelled" });+ });++ it("fails without output when the translator returns the wrong count or throws", async () => {+ const short = await translateCaptionTrack({+ subtitles: SUBS, sourceTrackId: "", targetLanguage: "es", translator: { translate: async (texts) => texts.slice(1) },+ });+ expect(short).toMatchObject({ ok: false, reason: "failed" });+ const boom = await translateCaptionTrack({+ subtitles: SUBS, sourceTrackId: "", targetLanguage: "es", translator: { translate: async () => { throw new Error("offline"); } },+ });+ expect(boom).toMatchObject({ ok: false, reason: "failed", message: "offline" });+ });++ it("reports an empty track", async () => {+ const result = await translateCaptionTrack({ subtitles: SUBS, sourceTrackId: "zz", targetLanguage: "es", translator: upper });+ expect(result).toMatchObject({ ok: false, reason: "empty" });+ });+});++describe("translation prompt and reply parsing", () => {+ it("round-trips a JSON array and tolerates code fences", () => {+ expect(parseTranslationReply('```json\n["a","b"]\n```', 2)).toEqual(["a", "b"]);+ expect(parseTranslationReply('Sure: ["a\\nb"]', 1)).toEqual(["a\nb"]);+ });+ it("rejects wrong length and non-arrays", () => {+ expect(() => parseTranslationReply('["a"]', 2)).toThrow(/1 lines for 2/);+ expect(() => parseTranslationReply("nope", 1)).toThrow();+ expect(() => parseTranslationReply("[1]", 1)).toThrow();+ });+ it("puts the cues in the user message", () => {+ const p = buildTranslationPrompt(["Hi"], { targetLanguage: "es", targetName: "Spanish" });+ expect(p.user).toContain("Spanish (es)");+ expect(p.user).toContain('["Hi"]');+ });+});diff --git a/packages/core/src/captions/caption-translate.ts b/packages/core/src/captions/caption-translate.tsnew file mode 100644index 00000000..cca1ee56--- /dev/null+++ b/packages/core/src/captions/caption-translate.ts@@ -0,0 +1,178 @@+import type { Subtitle } from "../types/timeline";++/**+ * Caption translation: turns one caption track into a new track in another language.+ * The translator is injected (an AI provider or the browser's on-device Translator),+ * so this stays pure and testable. Timing, style, speaker and cue settings of every+ * cue are preserved; only the text changes. Word timings are dropped because the+ * translated words no longer line up with the spoken ones.+ */++export interface CaptionTranslator {+ /**+ * Translate `texts` (one cue each) and return exactly one string per input, in order.+ * Must reject with an AbortError when `signal` aborts.+ */+ translate(+ texts: readonly string[],+ options: { sourceLanguage?: string; targetLanguage: string; signal?: AbortSignal },+ ): Promise<string[]>;+}++export interface CaptionTranslationProgress {+ readonly done: number;+ readonly total: number;+}++export interface TranslateCaptionTrackOptions {+ readonly subtitles: readonly Subtitle[];+ /** Source track id; "" is the default track. */+ readonly sourceTrackId: string;+ readonly targetLanguage: string;+ readonly translator: CaptionTranslator;+ /** Id for the new track; defaults to the target language, made unique among existing tracks. */+ readonly targetTrackId?: string;+ /** Cues per translator call. Default 20. */+ readonly batchSize?: number;+ readonly signal?: AbortSignal;+ readonly onProgress?: (progress: CaptionTranslationProgress) => void;+ readonly idFactory?: (index: number) => string;+}++export type CaptionTranslationResult =+ | {+ readonly ok: true;+ readonly trackId: string;+ /** The new cues only. Append them to the project's subtitles to create the track. */+ readonly cues: Subtitle[];+ }+ | { readonly ok: false; readonly reason: "empty" | "cancelled" | "failed"; readonly message: string };++const DEFAULT_BATCH = 20;++export function isAbortError(error: unknown): boolean {+ return (+ typeof error === "object" &&+ error !== null &&+ (error as { name?: unknown }).name === "AbortError"+ );+}++/** A track id that no existing cue uses. */+export function uniqueCaptionTrackId(subtitles: readonly Subtitle[], wanted: string): string {+ const used = new Set(subtitles.map((s) => s.captionTrackId ?? ""));+ if (wanted && !used.has(wanted)) return wanted;+ const base = wanted || "captions";+ for (let n = 2; ; n++) {+ const candidate = `${base}-${n}`;+ if (!used.has(candidate)) return candidate;+ }+}++export async function translateCaptionTrack(+ options: TranslateCaptionTrackOptions,+): Promise<CaptionTranslationResult> {+ const { subtitles, sourceTrackId, targetLanguage, translator, signal } = options;+ const source = subtitles+ .filter((s) => (s.captionTrackId ?? "") === sourceTrackId && s.text.trim() !== "")+ .sort((a, b) => a.startTime - b.startTime || a.endTime - b.endTime);+ if (!source.length) {+ return { ok: false, reason: "empty", message: "That caption track has no text to translate." };+ }+ const sourceLanguage = source.find((s) => s.language)?.language;+ // Short tracks still report several progress steps instead of jumping from 0 to done.+ const batchSize = Math.max(1, Math.floor(options.batchSize ?? Math.min(DEFAULT_BATCH, Math.ceil(source.length / 5))));+ const trackId = uniqueCaptionTrackId(subtitles, options.targetTrackId?.trim() || targetLanguage);+ const makeId = options.idFactory ?? ((i: number) => `tx-${trackId}-${i}`);++ const translated: string[] = [];+ options.onProgress?.({ done: 0, total: source.length });+ try {+ for (let from = 0; from < source.length; from += batchSize) {+ if (signal?.aborted) return cancelled();+ const batch = source.slice(from, from + batchSize);+ const out = await translator.translate(+ batch.map((s) => s.text),+ { sourceLanguage, targetLanguage, signal },+ );+ if (signal?.aborted) return cancelled();+ if (!Array.isArray(out) || out.length !== batch.length) {+ return {+ ok: false,+ reason: "failed",+ message: `The translator returned ${Array.isArray(out) ? out.length : 0} lines for ${batch.length} captions. Nothing was added.`,+ };+ }+ translated.push(...out.map((t) => String(t)));+ options.onProgress?.({ done: translated.length, total: source.length });+ }+ } catch (error) {+ if (isAbortError(error) || signal?.aborted) return cancelled();+ return {+ ok: false,+ reason: "failed",+ message: error instanceof Error ? error.message : "Translation failed.",+ };+ }++ const cues = source.map((cue, i): Subtitle => {+ const { words: _words, ...rest } = cue;+ void _words;+ return {+ ...rest,+ id: makeId(i),+ text: translated[i].trim() || cue.text,+ language: targetLanguage,+ captionTrackId: trackId,+ // Drawn over the same time range and position as the original, so it stays out of the+ // picture until the editor chooses which language to show.+ hidden: true,+ };+ });+ return { ok: true, trackId, cues };+}++function cancelled(): CaptionTranslationResult {+ return { ok: false, reason: "cancelled", message: "Translation cancelled. Nothing was added." };+}++/**+ * Prompt + parser for LLM-backed translators. Cues travel as a JSON array of strings and+ * must come back as a JSON array of the same length, so line breaks inside a cue survive.+ */+export function buildTranslationPrompt(+ texts: readonly string[],+ languages: { sourceLanguage?: string; targetLanguage: string; targetName?: string },+): { system: string; user: string } {+ const target = languages.targetName ? `${languages.targetName} (${languages.targetLanguage})` : languages.targetLanguage;+ return {+ system:+ "You translate video captions. Translate each caption faithfully and concisely into the target language, keeping line breaks, speaker names, music notes and sound cues in brackets. " ++ "Reply with ONLY a JSON array of strings, one per input caption, in the same order and with exactly the same length. No commentary, no code fences.",+ user:+ `Source language: ${languages.sourceLanguage ?? "auto-detect"}\nTarget language: ${target}\n\n` ++ JSON.stringify(texts),+ };+}++export function parseTranslationReply(reply: string, expected: number): string[] {+ let body = reply.trim();+ const fenced = /^```(?:json)?\s*([\s\S]*?)\s*```$/i.exec(body);+ if (fenced) body = fenced[1];+ const start = body.indexOf("[");+ const end = body.lastIndexOf("]");+ if (start < 0 || end < start) throw new Error("The model did not return a translation.");+ let parsed: unknown;+ try {+ parsed = JSON.parse(body.slice(start, end + 1));+ } catch {+ throw new Error("The model's translation could not be read.");+ }+ if (!Array.isArray(parsed) || !parsed.every((v) => typeof v === "string")) {+ throw new Error("The model's translation could not be read.");+ }+ if (parsed.length !== expected) {+ throw new Error(`The model returned ${parsed.length} lines for ${expected} captions.`);+ }+ return parsed as string[];+}diff --git a/packages/core/src/captions/cea608-sei.ts b/packages/core/src/captions/cea608-sei.tsindex 851660c8..f967a642 100644--- a/packages/core/src/captions/cea608-sei.ts+++ b/packages/core/src/captions/cea608-sei.ts@@ -41,7 +41,7 @@ export function sccToFrameSchedule(options: { frameRate: number; offsetSeconds?: number },): Cc608FrameSchedule {const warnings: string[] = [];- const text = scc.replace(/^/, "").replace(/\r\n?/g, "\n");+ const text = scc.replace(/^\uFEFF/, "").replace(/\r\n?/g, "\n");const lines = text.split("\n");if (!/^\s*Scenarist_SCC/i.test(lines[0] ?? "")) throw new Error('Not an SCC file: the "Scenarist_SCC V1.0" header is missing.');const hasDrop = lines.some((line) => /^\d{1,2}:\d{2}:\d{2};\d{2}\s/.test(line.trim()));diff --git a/packages/core/src/captions/diarization-translations.test.ts b/packages/core/src/captions/diarization-translations.test.tsnew file mode 100644index 00000000..f9985ad1--- /dev/null+++ b/packages/core/src/captions/diarization-translations.test.ts@@ -0,0 +1,49 @@+import { describe, expect, it } from "vitest";+import { detectionCues, mirrorSpeakersToTranslations } from "./diarization";+import type { Subtitle } from "../types/timeline";++const cue = (id: string, start: number, end: number, extra: Partial<Subtitle> = {}): Subtitle => ({+ id,+ text: id,+ startTime: start,+ endTime: end,+ words: [],+ ...extra,+});+const source = [cue("a", 0, 2), cue("b", 2, 4)];+const translated = [+ cue("fa", 0, 2, { captionTrackId: "fr", language: "fr", hidden: true }),+ cue("fb", 2, 4, { captionTrackId: "fr", language: "fr", hidden: true }),+];++describe("detectionCues", () => {+ it("analyses only the visible track", () => {+ expect(detectionCues([...source, ...translated]).map((c) => c.id)).toEqual(["a", "b"]);+ expect(detectionCues([...translated, ...source]).map((c) => c.id)).toEqual(["a", "b"]);+ });++ it("falls back to the first track when everything is hidden", () => {+ const hidden = [...source, ...translated].map((c) => ({ ...c, hidden: true }));+ expect(detectionCues(hidden).map((c) => c.id)).toEqual(["a", "b"]);+ expect(detectionCues([])).toEqual([]);+ });+});++describe("mirrorSpeakersToTranslations", () => {+ it("copies speakers onto translated cues of the same range, and clears them", () => {+ const labelled = [{ ...source[0], speaker: "Ann" }, { ...source[1], speaker: "Bob" }, ...translated];+ const out = mirrorSpeakersToTranslations(labelled, new Set(["a", "b"]));+ expect(out.map((c) => c.speaker)).toEqual(["Ann", "Bob", "Ann", "Bob"]);+ const out2 = mirrorSpeakersToTranslations(+ [source[0], labelled[1], { ...translated[0], speaker: "Ann" }, translated[1]],+ new Set(["a"]),+ );+ expect(out2[2].speaker).toBeUndefined();+ });++ it("does not touch cues whose range differs", () => {+ const other = cue("x", 5, 6, { captionTrackId: "fr", hidden: true });+ const out = mirrorSpeakersToTranslations([{ ...source[0], speaker: "Ann" }, other], new Set(["a"]));+ expect(out[1].speaker).toBeUndefined();+ });+});diff --git a/packages/core/src/captions/diarization.test.ts b/packages/core/src/captions/diarization.test.tsnew file mode 100644index 00000000..4db29c2a--- /dev/null+++ b/packages/core/src/captions/diarization.test.ts@@ -0,0 +1,163 @@+import { describe, expect, it } from "vitest";+import {+ applySpeakerStyles,+ clusterEmbeddings,+ ensureSpeakerProfiles,+ labelCuesBySpeaker,+ renameSpeakerProfile,+ SPEAKER_PALETTE,+} from "./diarization";+import { computeSpeakerEmbedding, EMBEDDING_SAMPLE_RATE, SPEAKER_EMBEDDING_DIMENSIONS } from "./speaker-embedding";+import type { Subtitle } from "../types/timeline";++let seed = 7;+const rand = () => ((seed = (seed * 1664525 + 1013904223) >>> 0) / 2 ** 32 - 0.5);+const voice = (center: number[], noise = 0.05) => Float32Array.from(center, (c) => c + rand() * noise);+const A = [1, 0, 0, 0, 0, 0, 0, 0];+const B = [0, 1, 0, 0, 0, 0, 0, 0];+const C = [0, 0, 1, 0, 0, 0, 0, 0];++describe("clusterEmbeddings", () => {+ it("separates synthetic voices and numbers clusters by first appearance", () => {+ const e = [voice(B), voice(A), voice(B), voice(A), voice(C), voice(B)];+ expect(clusterEmbeddings(e)).toEqual([0, 1, 0, 1, 2, 0]);+ });+ it("honours an explicit speaker count and a max", () => {+ const e = [voice(A), voice(B), voice(C), voice(A)];+ expect(new Set(clusterEmbeddings(e, { speakerCount: 2 })).size).toBe(2);+ expect(new Set(clusterEmbeddings(e, { speakerCount: 1 })).size).toBe(1);+ expect(new Set(clusterEmbeddings(e, { maxSpeakers: 2 })).size).toBe(2);+ });+ it("handles empty and single input", () => {+ expect(clusterEmbeddings([])).toEqual([]);+ expect(clusterEmbeddings([voice(A)])).toEqual([0]);+ });+});++describe("automatic speaker count", () => {+ // 26-dim voice-prints: each speaker has a fixed signature; every cue adds "what was said" variation.+ const dims = SPEAKER_EMBEDDING_DIMENSIONS;+ const signature = (id: number) => Float32Array.from({ length: dims }, (_, d) => Math.sin((id + 1) * (d + 1) * 1.7) * 4);+ const cue = (id: number) => Float32Array.from(signature(id), (c) => c + rand() * 3);+ it("finds two voices in a six-passage interview", () => {+ expect(clusterEmbeddings([0, 1, 0, 1, 0, 1].map(cue))).toEqual([0, 1, 0, 1, 0, 1]);+ });+ it("finds three voices and one voice", () => {+ expect(new Set(clusterEmbeddings([0, 1, 2, 0, 1, 2, 0, 1].map(cue))).size).toBe(3);+ expect(new Set(clusterEmbeddings([0, 0, 0, 0, 0, 0].map(cue))).size).toBe(1);+ });+ it("is not fooled by duplicate cues", () => {+ const a = cue(0);+ expect(new Set(clusterEmbeddings([a, a, a, cue(1), cue(1)])).size).toBe(2);+ expect(new Set(clusterEmbeddings([a, a, a, a])).size).toBe(1);+ });+ it("treats fewer than three cues as one voice unless told otherwise", () => {+ expect(clusterEmbeddings([cue(0), cue(1)])).toEqual([0, 0]);+ expect(clusterEmbeddings([cue(0), cue(1)], { speakerCount: 2 })).toEqual([0, 1]);+ });+});++describe("labelCuesBySpeaker", () => {+ const cues = [0, 1, 2, 3, 4].map((i) => ({ startTime: i * 2, endTime: i * 2 + 2 }));+ it("names speakers in order of first appearance and assigns palette colours", () => {+ const { labels, profiles } = labelCuesBySpeaker(cues, [1, 0, 1, 0, 0]);+ expect(labels).toEqual(["Speaker 1", "Speaker 2", "Speaker 1", "Speaker 2", "Speaker 2"]);+ expect(profiles.map((p) => p.color)).toEqual([SPEAKER_PALETTE[0], SPEAKER_PALETTE[1]]);+ });+ it("gives cues without audio the nearest speaker in time", () => {+ const { labels } = labelCuesBySpeaker(cues, [0, null, 1, 1, null]);+ expect(labels[1]).toMatch(/Speaker/);+ expect(labels[4]).toBe(labels[3]);+ });+ it("smooths a short A-B-A flicker", () => {+ const short = [{ startTime: 0, endTime: 2 }, { startTime: 2, endTime: 2.5 }, { startTime: 2.5, endTime: 5 }];+ expect(labelCuesBySpeaker(short, [0, 1, 0]).labels).toEqual(["Speaker 1", "Speaker 1", "Speaker 1"]);+ expect(labelCuesBySpeaker(short, [0, 1, 0], [], { smooth: false }).labels[1]).toBe("Speaker 2");+ });+ it("re-running keeps renamed speakers and their look, and drops stale profiles", () => {+ const existing = [+ { name: "Host", color: "#123456", position: "top" as const },+ { name: "Speaker 2", color: "#654321" },+ { name: "Gone", color: "#abcdef" },+ ];+ const previous = ["Host", "Speaker 2", "Host", "Speaker 2", "Host"];+ const { labels, profiles } = labelCuesBySpeaker(cues, [1, 0, 1, 0, 1], existing, { previous });+ expect(labels).toEqual(["Host", "Speaker 2", "Host", "Speaker 2", "Host"]);+ expect(profiles.map((p) => p.name)).toEqual(["Host", "Speaker 2"]);+ expect(profiles[0]).toEqual(existing[0]);+ });+ it("gives a new voice the lowest free name and an unused colour", () => {+ const existing = [{ name: "Host", color: SPEAKER_PALETTE[0], position: "top" as const }];+ const { labels, profiles } = labelCuesBySpeaker(cues, [0, 1, 0, 1, 1], existing, { previous: ["Host", "Host", "Host", "Host", "Host"] });+ expect(labels).toEqual(["Speaker 1", "Host", "Speaker 1", "Host", "Host"]);+ expect(profiles[1]).toEqual({ name: "Speaker 1", color: SPEAKER_PALETTE[1] });+ });+ it("keeps existing profiles", () => {+ const { profiles } = labelCuesBySpeaker(cues, [0, 0, 0, 0, 0], [{ name: "Speaker 1", color: "#123456" }]);+ expect(profiles).toEqual([{ name: "Speaker 1", color: "#123456" }]);+ });+});++describe("speaker profiles", () => {+ const cue = (id: string, speaker?: string, style?: Subtitle["style"]): Subtitle => ({ id, text: id, startTime: 0, endTime: 1, speaker, style });+ it("ensures a profile per used speaker", () => {+ const p = ensureSpeakerProfiles([cue("a", "Ann"), cue("b", "Bo"), cue("c")], [{ name: "Ann", color: "#111111" }]);+ expect(p.map((x) => x.name)).toEqual(["Ann", "Bo"]);+ expect(p[1].color).toBe(SPEAKER_PALETTE[1]);+ });+ it("renames and merges profiles", () => {+ const base = [{ name: "A", color: "#1" }, { name: "B", color: "#2" }];+ expect(renameSpeakerProfile(base, "A", "Zed")[0].name).toBe("Zed");+ expect(renameSpeakerProfile(base, "A", "B")).toEqual([{ name: "B", color: "#2" }]);+ expect(renameSpeakerProfile(base, "A", "")).toEqual([{ name: "B", color: "#2" }]);+ });+ it("puts the original look back when the speaker is cleared or no longer styles captions", () => {+ const plain = cue("a", "Ann");+ const styled = cue("b", "Bo", { fontFamily: "Inter", fontSize: 40, color: "#eeeeee", backgroundColor: "#000", position: "center" });+ const profiles = [{ name: "Ann", color: "#ff0000", position: "top" as const }, { name: "Bo", color: "#00ff00" }];+ const baked = applySpeakerStyles([plain, styled], profiles);+ expect(baked[0].style?.color).toBe("#ff0000");+ const cleared = applySpeakerStyles(baked.map((c) => ({ ...c, speaker: undefined })), profiles);+ expect(cleared[0].style).toBeUndefined();+ expect(cleared[0].speakerBase).toBeUndefined();+ expect(cleared[1].style).toMatchObject({ color: "#eeeeee", position: "center", fontSize: 40 });+ const off = applySpeakerStyles(baked, [{ ...profiles[1], styleCaptions: false }, { ...profiles[0], styleCaptions: false }]);+ expect(off[1].style?.color).toBe("#eeeeee");+ // Reassigning between speakers keeps the very first original.+ const moved = applySpeakerStyles([{ ...baked[1], speaker: "Ann" }], profiles);+ expect(moved[0].style).toMatchObject({ color: "#ff0000", position: "top" });+ expect(moved[0].speakerBase).toEqual(baked[1].speakerBase);+ });+ it("bakes colour and position onto the speaker's cues only, idempotently", () => {+ const subs = [cue("a", "Ann"), cue("b", "Bo"), cue("c")];+ const profiles = [{ name: "Ann", color: "#ff0000", position: "top" as const }, { name: "Bo", color: "#00ff00", styleCaptions: false }];+ const out = applySpeakerStyles(subs, profiles);+ expect(out[0].style).toMatchObject({ color: "#ff0000", position: "top" });+ expect(out[1]).toBe(subs[1]);+ expect(out[2]).toBe(subs[2]);+ expect(applySpeakerStyles(out, profiles)[0]).toBe(out[0]);+ });+});++describe("computeSpeakerEmbedding", () => {+ const tone = (f0: number, formant: number, seconds = 1) => {+ const n = EMBEDDING_SAMPLE_RATE * seconds;+ return Float32Array.from({ length: n }, (_, i) => {+ const t = i / EMBEDDING_SAMPLE_RATE;+ let v = 0;+ for (let h = 1; h * f0 < 4000; h++) v += Math.exp(-((h * f0 - formant) ** 2) / 600000) * Math.sin(2 * Math.PI * h * f0 * t) / h ** 0.3;+ return v * 0.1 + rand() * 0.002;+ });+ };+ it("returns null for silence and short audio", () => {+ expect(computeSpeakerEmbedding(new Float32Array(16000))).toBeNull();+ expect(computeSpeakerEmbedding(new Float32Array(100))).toBeNull();+ });+ it("clusters synthetic voices with different pitch and formants apart", () => {+ const low = [tone(110, 500), tone(112, 520), tone(108, 490)];+ const high = [tone(220, 1500), tone(224, 1480), tone(218, 1520)];+ const e = [...low, ...high].map((s) => computeSpeakerEmbedding(s) as Float32Array);+ expect(e.every(Boolean)).toBe(true);+ expect(clusterEmbeddings(e, { speakerCount: 2 })).toEqual([0, 0, 0, 1, 1, 1]);+ });+});diff --git a/packages/core/src/captions/diarization.ts b/packages/core/src/captions/diarization.tsnew file mode 100644index 00000000..f09917a9--- /dev/null+++ b/packages/core/src/captions/diarization.ts@@ -0,0 +1,371 @@+import type { Subtitle, SubtitleStyle } from "../types/timeline";+import { SPEAKER_EMBEDDING_DIMENSIONS, SPEAKER_EMBEDDING_WEIGHTS } from "./speaker-embedding";++/**+ * Speaker diarization (pure logic). Voice embeddings come from+ * speaker-embedding.ts (computed in a worker); this module clusters them,+ * labels caption cues "Speaker 1..N" in order of first appearance, and keeps+ * the per-speaker look (colour, caption position) that is baked onto cues so+ * preview and every export render identically.+ */++export type SpeakerPosition = "top" | "center" | "bottom";++export interface SpeakerProfile {+ /** The label cues carry in `Subtitle.speaker`. Unique within a project. */+ readonly name: string;+ /** Hex colour used in the transcript and (when `styleCaptions`) for caption text. */+ readonly color: string;+ /** Caption position for this speaker; unset keeps the cue's own. */+ readonly position?: SpeakerPosition;+ /** Bake colour/position onto this speaker's cues. Default true. */+ readonly styleCaptions?: boolean;+}++export const SPEAKER_PALETTE: readonly string[] = [+ "#4F9DFF",+ "#FF8A4C",+ "#3DD68C",+ "#E56BFF",+ "#FFD24A",+ "#FF5C7A",+ "#4FD8E6",+ "#A98BFF",+];++export const defaultSpeakerName = (n: number): string => `Speaker ${n}`;+export const paletteColor = (index: number): string => SPEAKER_PALETTE[index % SPEAKER_PALETTE.length];++export interface ClusterOptions {+ /** Force exactly this many speakers (clamped to the number of voices). */+ speakerCount?: number;+ /** Upper bound when auto-detecting. Default 8. */+ maxSpeakers?: number;+ /** Fixed merge-distance cut instead of gap detection (advanced). */+ threshold?: number;+}++function standardize(vectors: readonly Float32Array[], weights?: ArrayLike<number>): Float64Array[] {+ const dims = vectors[0].length;+ const mean = new Float64Array(dims);+ for (const v of vectors) for (let d = 0; d < dims; d++) mean[d] += v[d] / vectors.length;+ const sd = new Float64Array(dims);+ for (const v of vectors) for (let d = 0; d < dims; d++) sd[d] += (v[d] - mean[d]) ** 2 / vectors.length;+ // Shrink toward the average spread so near-constant (noise-only) dimensions are not blown up.+ const floor = 0.25 * (sd.reduce((a, b) => a + b, 0) / dims);+ return vectors.map((v) => Float64Array.from(v, (x, d) => ((x - mean[d]) / (Math.sqrt(sd[d] + floor) || 1)) * (weights ? weights[d] : 1)));+}++export function cosineDistance(a: ArrayLike<number>, b: ArrayLike<number>): number {+ let dot = 0;+ let na = 0;+ let nb = 0;+ for (let i = 0; i < a.length; i++) {+ dot += a[i] * b[i];+ na += a[i] * a[i];+ nb += b[i] * b[i];+ }+ return na && nb ? 1 - dot / Math.sqrt(na * nb) : 1;+}++export interface Merge {+ /** Average-linkage cosine distance at which the two clusters joined. */+ readonly height: number;+ /** Cluster count left after this merge. */+ readonly remaining: number;+}++/**+ * Full average-linkage dendrogram over z-scored embeddings (Lance-Williams+ * updates on a distance matrix). `owners(k)` cuts it to k clusters.+ */+function dendrogram(embeddings: readonly Float32Array[], weights?: ArrayLike<number>): { merges: Merge[]; owners: (k: number) => number[] } {+ const n = embeddings.length;+ const points = standardize(embeddings, weights);+ const dist = Array.from({ length: n }, (_, i) =>+ Float64Array.from({ length: n }, (_, j) => (i === j ? 0 : cosineDistance(points[i], points[j]))),+ );+ const members: number[][] = Array.from({ length: n }, (_, i) => [i]);+ const alive: number[] = Array.from({ length: n }, (_, i) => i);+ const merges: Merge[] = [];+ const snapshots = new Map<number, number[][]>();+ snapshots.set(n, members.map((m) => [...m]));+ while (alive.length > 1) {+ let bi = 0;+ let bj = 1;+ let best = Infinity;+ for (let x = 0; x < alive.length; x++)+ for (let y = x + 1; y < alive.length; y++) {+ const d = dist[alive[x]][alive[y]];+ if (d < best) {+ best = d;+ bi = x;+ bj = y;+ }+ }+ const a = alive[bi];+ const b = alive[bj];+ const na = members[a].length;+ const nb = members[b].length;+ for (const c of alive) {+ if (c === a || c === b) continue;+ const d = (dist[a][c] * na + dist[b][c] * nb) / (na + nb);+ dist[a][c] = d;+ dist[c][a] = d;+ }+ members[a] = [...members[a], ...members[b]];+ alive.splice(bj, 1);+ merges.push({ height: best, remaining: alive.length });+ snapshots.set(alive.length, alive.map((id) => [...members[id]]));+ }+ const owners = (k: number) => {+ const owner = new Array<number>(n);+ (snapshots.get(Math.max(1, Math.min(n, k))) as number[][]).forEach((group, c) => group.forEach((m) => (owner[m] = c)));+ const renumber = new Map<number, number>();+ return owner.map((c) => {+ if (!renumber.has(c)) renumber.set(c, renumber.size);+ return renumber.get(c) as number;+ });+ };+ return { merges, owners };+}++/**+ * How many voices are there? Looks for the clearest gap in the merge heights:+ * a split into k voices is justified when the merge that would join two of+ * them costs much more than the merges inside them. The denominator is floored+ * so near-duplicate cues (height ~0) cannot fake a gap, and a dendrogram with+ * no clear gap is one voice. Needs at least three cues.+ */+export function estimateSpeakerCount(merges: readonly Merge[], maxSpeakers: number, minGap = 1.7): number {+ const n = merges.length + 1;+ if (n < 3) return 1;+ const heights = merges.map((m) => m.height);+ const floor = 0.3 * heights[heights.length - 1];+ let bestK = 1;+ let bestRatio = minGap;+ for (let k = 2; k <= Math.min(maxSpeakers, n - 1); k++) {+ // heights[n - k] is the merge that would take k clusters down to k - 1.+ const ratio = heights[n - k] / Math.max(heights[n - k - 1], floor, 1e-6);+ if (ratio > bestRatio) {+ bestRatio = ratio;+ bestK = k;+ }+ }+ return bestK;+}++/**+ * Agglomerative (average-linkage, cosine) clustering. Returns one cluster id+ * per input, numbered 0..k-1 by first appearance. With no `speakerCount` the+ * count is detected from the dendrogram's clearest gap.+ */+export function clusterEmbeddings(+ embeddings: readonly Float32Array[],+ options: ClusterOptions = {},+): number[] {+ const n = embeddings.length;+ if (n === 0) return [];+ if (n === 1) return [0];+ const maxSpeakers = Math.max(1, options.maxSpeakers ?? 8);+ const tree = dendrogram(embeddings, embeddings[0].length === SPEAKER_EMBEDDING_DIMENSIONS ? SPEAKER_EMBEDDING_WEIGHTS : undefined);+ const k = options.speakerCount+ ? Math.max(1, Math.min(n, Math.round(options.speakerCount)))+ : options.threshold !== undefined+ ? Math.min(maxSpeakers, 1 + tree.merges.filter((m) => m.height > (options.threshold as number)).length)+ : Math.min(maxSpeakers, estimateSpeakerCount(tree.merges, tree.merges.length));+ return tree.owners(k);+}++/**+ * Cue speaker labels from per-cue clusters. `clusters[i]` is the cluster of+ * `cues[i]` or null when the cue had no usable audio; such cues take the label+ * of the nearest labelled cue in time. A single flicker between two identical+ * neighbours (A B A) is smoothed to A.+ */+export function labelCuesBySpeaker(+ cues: readonly Pick<Subtitle, "startTime" | "endTime">[],+ clusters: ReadonlyArray<number | null>,+ existing: readonly SpeakerProfile[] = [],+ options: { smooth?: boolean; previous?: ReadonlyArray<string | undefined> } = {},+): { labels: string[]; profiles: SpeakerProfile[] } {+ const filled = [...clusters];+ const order = cues.map((_, i) => i).sort((a, b) => cues[a].startTime - cues[b].startTime);+ const labelled = order.filter((i) => clusters[i] !== null);+ for (const i of order) {+ if (filled[i] !== null || !labelled.length) continue;+ let nearest = labelled[0];+ for (const j of labelled)+ if (Math.abs(cues[j].startTime - cues[i].startTime) < Math.abs(cues[nearest].startTime - cues[i].startTime)) nearest = j;+ filled[i] = clusters[nearest];+ }+ if (options.smooth !== false) {+ for (let k = 1; k < order.length - 1; k++) {+ const prev = filled[order[k - 1]];+ const next = filled[order[k + 1]];+ const cur = filled[order[k]];+ const dur = cues[order[k]].endTime - cues[order[k]].startTime;+ if (prev !== null && prev === next && cur !== prev && dur < 1.2) filled[order[k]] = prev;+ }+ }+ const names = nameClusters(filled, order, options.previous);+ // A re-run replaces the old labels: profiles nothing maps to anymore are dropped.+ const mapped = new Set(names.values());+ const profiles: SpeakerProfile[] = options.previous ? existing.filter((p) => mapped.has(p.name)) : [...existing];+ for (const name of names.values())+ if (!profiles.some((p) => p.name === name)) profiles.push({ name, color: freeColor(profiles) });+ return { labels: filled.map((c) => (c === null ? "" : (names.get(c) as string))), profiles };+}++function freeColor(profiles: readonly SpeakerProfile[]): string {+ const used = new Set(profiles.map((p) => p.color.toLowerCase()));+ return SPEAKER_PALETTE.find((c) => !used.has(c.toLowerCase())) ?? paletteColor(profiles.length);+}++/**+ * Names for clusters. A cluster that mostly overlaps cues already labelled+ * "Host" stays "Host" (one-to-one, strongest overlap first), so re-running+ * detection keeps renamed speakers and their look. The rest take the lowest+ * free "Speaker N", in order of first appearance.+ */+function nameClusters(+ filled: ReadonlyArray<number | null>,+ order: readonly number[],+ previous: ReadonlyArray<string | undefined> | undefined,+): Map<number, string> {+ const names = new Map<number, string>();+ const taken = new Set<string>();+ if (previous) {+ const overlap = new Map<string, number>();+ filled.forEach((c, i) => {+ const prev = previous[i];+ if (c !== null && prev) overlap.set(`${c}\u0000${prev}`, (overlap.get(`${c}\u0000${prev}`) ?? 0) + 1);+ });+ const ranked = [...overlap.entries()]+ .map(([key, count]) => ({ cluster: Number(key.split("\u0000")[0]), name: key.split("\u0000")[1], count }))+ .sort((a, b) => b.count - a.count || a.cluster - b.cluster);+ for (const { cluster, name } of ranked) {+ if (names.has(cluster) || taken.has(name)) continue;+ names.set(cluster, name);+ taken.add(name);+ }+ }+ let n = 1;+ for (const i of order) {+ const c = filled[i];+ if (c === null || names.has(c)) continue;+ while (taken.has(defaultSpeakerName(n))) n++;+ names.set(c, defaultSpeakerName(n));+ taken.add(defaultSpeakerName(n));+ }+ return names;+}++export const findSpeakerProfile = (+ profiles: readonly SpeakerProfile[] | undefined,+ name: string | undefined,+): SpeakerProfile | undefined => (name ? profiles?.find((p) => p.name === name) : undefined);++/** Profiles for every speaker used by `subtitles` (keeps existing, appends new from the palette). */+export function ensureSpeakerProfiles(+ subtitles: readonly Subtitle[],+ profiles: readonly SpeakerProfile[] = [],+): SpeakerProfile[] {+ const next = [...profiles];+ for (const cue of subtitles)+ if (cue.speaker && !next.some((p) => p.name === cue.speaker)) next.push({ name: cue.speaker, color: paletteColor(next.length) });+ return next;+}++/** Rename a profile; renaming onto an existing name merges (the target's look wins). */+export function renameSpeakerProfile(profiles: readonly SpeakerProfile[], from: string, to: string): SpeakerProfile[] {+ const name = to.trim();+ const source = profiles.find((p) => p.name === from);+ if (!source) return [...profiles];+ if (!name) return profiles.filter((p) => p.name !== from);+ if (name === from) return [...profiles];+ if (profiles.some((p) => p.name === name)) return profiles.filter((p) => p.name !== from);+ return profiles.map((p) => (p.name === from ? { ...p, name } : p));+}++const BASE_STYLE: SubtitleStyle = {+ fontFamily: "Inter",+ fontSize: 48,+ color: "#ffffff",+ backgroundColor: "rgba(0, 0, 0, 0.7)",+ position: "bottom",+};++/**+ * Bake each speaker's colour and position onto their cues, remembering what+ * the cue looked like first (`speakerBase`). A cue whose speaker was cleared,+ * or whose profile no longer styles captions, gets that look back. Cues that+ * were never speaker-styled are untouched. Idempotent.+ */+export function applySpeakerStyles(subtitles: readonly Subtitle[], profiles: readonly SpeakerProfile[]): Subtitle[] {+ return subtitles.map((cue) => {+ const profile = findSpeakerProfile(profiles, cue.speaker);+ if (!profile || profile.styleCaptions === false) return restoreSpeakerBase(cue);+ const base = cue.style ?? BASE_STYLE;+ const style: SubtitleStyle = { ...base, color: profile.color, ...(profile.position ? { position: profile.position } : {}) };+ if (cue.speakerBase && style.color === base.color && style.position === base.position) return cue;+ const speakerBase = cue.speakerBase ?? {+ hadStyle: Boolean(cue.style),+ color: cue.style?.color,+ position: cue.style?.position,+ ...(cue.cueSettings ? { cueSettings: cue.cueSettings } : {}),+ };+ // A cue-level WebVTT position would override the speaker's.+ const { cueSettings: _cue, ...rest } = cue;+ return { ...rest, style, speakerBase, ...(profile.position ? {} : cue.cueSettings ? { cueSettings: cue.cueSettings } : {}) };+ });+}++function restoreSpeakerBase(cue: Subtitle): Subtitle {+ const base = cue.speakerBase;+ if (!base) return cue;+ const { speakerBase: _b, style, cueSettings, ...rest } = cue;+ const restored: Subtitle = { ...rest, ...(base.cueSettings ?? cueSettings ? { cueSettings: base.cueSettings ?? cueSettings } : {}) };+ if (!base.hadStyle || !style) return restored;+ const next: SubtitleStyle = { ...style, color: base.color ?? BASE_STYLE.color, position: base.position ?? BASE_STYLE.position };+ return { ...restored, style: next };+}++const trackOf = (cue: Subtitle): string => cue.captionTrackId ?? "";+const TWIN_EPSILON = 1e-3;++/**+ * The cues speaker detection should analyse: the visible caption track(s).+ * Hidden translated versions cover the same time ranges, so including them+ * would double the work and skew the speaker count. When every cue is hidden,+ * the first track (in order of appearance) is used.+ */+export function detectionCues(subtitles: readonly Subtitle[]): Subtitle[] {+ const visible = subtitles.filter((cue) => !cue.hidden);+ if (visible.length) return visible;+ if (!subtitles.length) return [];+ const first = trackOf(subtitles[0]);+ return subtitles.filter((cue) => trackOf(cue) === first);+}++/**+ * Copy the speaker of the cues in `sourceIds` onto the cues of other caption+ * tracks with the same start/end (translated versions), so every language of a+ * passage shares one speaker. A cleared speaker is cleared on the twins too.+ */+export function mirrorSpeakersToTranslations(subtitles: readonly Subtitle[], sourceIds: ReadonlySet<string>): Subtitle[] {+ const sources = subtitles.filter((cue) => sourceIds.has(cue.id));+ if (!sources.length) return [...subtitles];+ return subtitles.map((cue) => {+ if (sourceIds.has(cue.id)) return cue;+ const source = sources.find(+ (s) =>+ trackOf(s) !== trackOf(cue) &&+ Math.abs(s.startTime - cue.startTime) < TWIN_EPSILON &&+ Math.abs(s.endTime - cue.endTime) < TWIN_EPSILON,+ );+ if (!source || source.speaker === cue.speaker) return cue;+ const { speaker: _old, ...rest } = cue;+ return source.speaker ? { ...rest, speaker: source.speaker } : rest;+ });+}diff --git a/packages/core/src/captions/sbv-ttml.test.ts b/packages/core/src/captions/sbv-ttml.test.tsnew file mode 100644index 00000000..e2f19dda--- /dev/null+++ b/packages/core/src/captions/sbv-ttml.test.ts@@ -0,0 +1,254 @@+import { describe, expect, it } from "vitest";+import {+ decodeCaptionText,+ exportCaptionFile,+ exportCaptions,+ parseCaptionBytes,+ parseCaptions,+} from "./caption-formats";+import { parseTtml } from "./ttml";+import { captionFont, DEFAULT_CAPTION_FONT_SIZE, DEFAULT_CAPTION_STYLE } from "./caption-layout";+import { parseSbv } from "./sbv";+import type { Subtitle } from "../types/timeline";++const SBV = `0:00:01.500,0:00:04.000+Hello there.+Second line.++0:00:05.000,0:00:07.250+General Kenobi!++bad block without timing++0:00:08.000,0:00:08.000+Zero length+`;++const TTML_IMSC = `<?xml version="1.0" encoding="UTF-8"?>+<tt xmlns="http://www.w3.org/ns/ttml" xmlns:tts="http://www.w3.org/ns/ttml#styling" xmlns:ttp="http://www.w3.org/ns/ttml#parameter" xmlns:ttm="http://www.w3.org/ns/ttml#metadata" xml:lang="fr" ttp:timeBase="media">+ <head>+ <metadata><ttm:agent xml:id="a1" type="person"><ttm:name type="alias">Alice</ttm:name></ttm:agent></metadata>+ <styling>+ <style xml:id="base" tts:color="#FFFF00" tts:fontFamily="monospaceSansSerif" tts:backgroundColor="#000000CC"/>+ <style xml:id="it" style="base" tts:fontStyle="italic"/>+ </styling>+ <layout>+ <region xml:id="top" tts:origin="10% 5%" tts:extent="80% 15%" tts:displayAlign="before" tts:textAlign="center"/>+ <region xml:id="bot" tts:origin="10% 80%" tts:extent="80% 15%" tts:displayAlign="after"/>+ </layout>+ </head>+ <body>+ <!-- a comment -->+ <div style="base">+ <p xml:id="p1" begin="00:00:01.000" end="00:00:03.500" region="top" ttm:agent="a1">Bonjour & salut<br/>le monde</p>+ <p begin="4s" dur="1.5s" region="bot"><span style="it">Italic</span> <span>plain</span></p>+ <p begin="6000ms" end="7000ms"> Spaced+ out text </p>+ <p end="9s">No begin is fine</p>+ <p>No timing at all</p>+ <p begin="1:2:3:4:5" end="9s">Bad time</p>+ </div>+ </body>+</tt>`;++describe("SBV", () => {+ it("parses cues, multi-line text and reports bad blocks with line numbers", () => {+ const r = parseSbv(SBV);+ expect(r.subtitles.map((c) => [c.startTime, c.endTime, c.text])).toEqual([+ [1.5, 4, "Hello there.\nSecond line."],+ [5, 7.25, "General Kenobi!"],+ ]);+ expect(r.errors.map((e) => e.line)).toEqual([8, 10]);+ });++ it("is auto-detected by parseCaptions, with CRLF and BOM", () => {+ const r = parseCaptions(`\uFEFF${SBV.replace(/\n/g, "\r\n")}`, { language: "en", captionTrackId: "en" });+ expect(r.format).toBe("sbv");+ expect(r.subtitles).toHaveLength(2);+ expect(r.subtitles[0].captionTrackId).toBe("en");+ });++ it("round-trips through export", () => {+ const cues = parseSbv(SBV).subtitles;+ const out = exportCaptions(cues, "sbv");+ expect(out).toBe("0:00:01.500,0:00:04.000\nHello there.\nSecond line.\n\n0:00:05.000,0:00:07.250\nGeneral Kenobi!\n");+ expect(parseSbv(out).subtitles.map((c) => c.text)).toEqual(cues.map((c) => c.text));+ });++ it("notes that styling is dropped on export", () => {+ const cue: Subtitle = { id: "a", text: "x", startTime: 0, endTime: 1, cueSettings: { line: 10 } };+ expect(exportCaptionFile([cue], "sbv").issues[0]?.code).toBe("sbv-style");+ });+});++describe("TTML / DFXP import", () => {+ const r = parseTtml(TTML_IMSC);++ it("reads clock, offset and ms times, parent-relative end, and skips bad paragraphs with line numbers", () => {+ expect(r.subtitles.map((c) => [c.startTime, c.endTime])).toEqual([+ [1, 3.5],+ [4, 5.5],+ [6, 7],+ [0, 9],+ ]);+ expect(r.errors).toHaveLength(2);+ expect(r.errors[0].message).toMatch(/no timing/i);+ expect(r.errors[1].message).toMatch(/begin time/i);+ expect(r.errors[0].line).toBeGreaterThan(10);+ });++ it("decodes entities, br and whitespace", () => {+ expect(r.subtitles[0].text).toBe("Bonjour & salut\nle monde");+ expect(r.subtitles[1].text).toBe("Italic plain");+ expect(r.subtitles[2].text).toBe("Spaced out text");+ });++ it("maps agents, language, colours, fonts, region layout", () => {+ const c = r.subtitles[0];+ expect(c.speaker).toBe("Alice");+ expect(c.language).toBe("fr");+ expect(c.style).toMatchObject({ color: "#FFFF00", fontFamily: "monospace", backgroundColor: "rgba(0,0,0,0.8)", position: "top" });+ expect(c.cueSettings).toMatchObject({ align: "center", snapToLines: false, size: 80, position: 50, lineAlign: "start" });+ expect(r.subtitles[1].style?.position).toBe("bottom");+ expect(r.subtitles[1].cueSettings?.line).toBe(95);+ });++ it("keeps italic runs as tags on request", () => {+ expect(parseTtml(TTML_IMSC, { styleTags: "keep" }).subtitles[1].text).toBe("<i>Italic</i> plain");+ });++ it("is auto-detected by parseCaptions and bytes (UTF-16 with BOM)", () => {+ expect(parseCaptions(TTML_IMSC).format).toBe("ttml");+ const u16 = new Uint8Array(2 + TTML_IMSC.length * 2);+ u16[0] = 0xff;+ u16[1] = 0xfe;+ for (let i = 0; i < TTML_IMSC.length; i++) {+ u16[2 + i * 2] = TTML_IMSC.charCodeAt(i) & 0xff;+ u16[3 + i * 2] = TTML_IMSC.charCodeAt(i) >> 8;+ }+ expect(parseCaptionBytes(u16).subtitles).toHaveLength(4);+ });++ it("handles DFXP with namespace prefixes, frame / tick times and offsets", () => {+ const dfxp = `<?xml version="1.0"?>+<tt:tt xmlns:tt="http://www.w3.org/ns/ttml" xmlns:ttp="http://www.w3.org/ns/ttml#parameter" ttp:frameRate="25" ttp:tickRate="10000000" ttp:timeBase="smpte">+<tt:body><tt:div>+<tt:p begin="01:00:01:12" end="01:00:03:00">One</tt:p>+<tt:p begin="20000000t" end="30000000t">Two</tt:p>+<tt:p begin="50f" end="75f">Three</tt:p>+</tt:div></tt:body></tt:tt>`;+ expect(parseTtml(dfxp).subtitles.map((c) => [c.startTime, c.endTime]).slice(1)).toEqual([+ [2, 3],+ [2, 3],+ ]);+ const d = parseTtml(dfxp, { offsetSeconds: 3600 });+ expect(d.subtitles.map((c) => [c.startTime, c.endTime])).toEqual([[1.48, 3]]);+ });++ it("derives paragraph time from timed spans and honours div offsets", () => {+ const d = parseTtml(`<tt xmlns="http://www.w3.org/ns/ttml"><body><div begin="10s"><p><span begin="1s" end="2s">a</span><span begin="2s" end="4s">b</span></p></div></body></tt>`);+ expect(d.subtitles[0]).toMatchObject({ startTime: 11, endTime: 14, text: "ab" });+ });++ it("tolerates unterminated and stray markup", () => {+ const d = parseTtml(`<tt xmlns="http://www.w3.org/ns/ttml"><body><div><p begin="0s" end="1s">ok</p></b><p begin="1s" end="2s">cut off`);+ expect(d.subtitles.map((c) => c.text)).toEqual(["ok", "cut off"]);+ });++ it("surfaces a clear error for non-TTML XML and for a missing body", () => {+ expect(parseTtml("<html><body/></html>").errors[0].message).toMatch(/Not a TTML/);+ expect(parseTtml(`<tt xmlns="http://www.w3.org/ns/ttml"><head/></tt>`).errors[0].message).toMatch(/no <body>/);+ });++ it("rejects other XML / HTML with a clear message", () => {+ const r = parseCaptions("<html><body>hi</body></html>");+ expect(r.subtitles).toEqual([]);+ expect(r.errors[0].message).toMatch(/Not a TTML/);+ });++ it("resolves a region that references a <style> and maps origin to position", () => {+ const xml = `<tt xmlns="http://www.w3.org/ns/ttml" xmlns:tts="http://www.w3.org/ns/ttml#styling"><head><styling>+<style xml:id="s1" tts:color="#FF0000" tts:textAlign="right" tts:displayAlign="after"/></styling>+<layout><region xml:id="r1" style="s1" tts:origin="10% 70%" tts:extent="80% 20%"/></layout></head>+<body><div><p begin="0s" end="2s" region="r1">Hi</p></div></body></tt>`;+ const r = parseTtml(xml);+ expect(r.errors).toEqual([]);+ expect(r.subtitles[0].style?.color).toBe("#FF0000");+ expect(r.subtitles[0].cueSettings?.align).toBe("right");+ expect(r.subtitles[0].style?.position).toBe("bottom");+ const low = parseTtml(xml.replace("10% 70%", "10% 5%").replace("80% 20%", "80% 10%"));+ expect(low.subtitles[0].style?.position).toBe("top");+ });++ it("round-trips cue vertical position through TTML regions", () => {+ const back = parseTtml(exportCaptions([+ { id: "1", text: "a", startTime: 0, endTime: 1, cueSettings: { line: 60, snapToLines: false } },+ { id: "2", text: "b", startTime: 1, endTime: 2 },+ ] as Subtitle[], "ttml"));+ expect(back.subtitles[0].cueSettings?.line).toBe(60);+ expect(back.subtitles[0].style?.position).toBe("center");+ expect(back.subtitles[1].cueSettings?.line).toBe(96);+ });++ it("round-trips our own TTML export", () => {+ const cues: Subtitle[] = [+ { id: "1", text: "A & B\nline", startTime: 1, endTime: 2.5, speaker: "Bob" },+ { id: "2", text: "C", startTime: 3, endTime: 4 },+ ];+ const back = parseTtml(exportCaptions(cues, "ttml"));+ expect(back.errors).toEqual([]);+ expect(back.subtitles.map((c) => [c.text, c.startTime, c.endTime, c.speaker])).toEqual([+ ["A & B\nline", 1, 2.5, "Bob"],+ ["C", 3, 4, undefined],+ ]);+ });+});++describe("decodeCaptionText", () => {+ it("falls back to Windows-1252 for legacy files", () => {+ expect(decodeCaptionText(new Uint8Array([0x63, 0x61, 0x66, 0xe9]))).toBe("café");+ });+});++describe("TTML fidelity", () => {+ const doc = (body: string, head = "") =>+ `<?xml version="1.0"?><tt xmlns="http://www.w3.org/ns/ttml" xmlns:tts="http://www.w3.org/ns/ttml#styling" xml:lang="en"><head>${head}</head><body><div>${body}</div></body></tt>`;++ it("uses the shared caption defaults, not a hardcoded size or quoted generic family", () => {+ const r = parseTtml(doc(`<p begin="0s" end="2s" tts:color="#FFFF00">Hi</p>`));+ expect(r.subtitles[0].style?.fontSize).toBe(DEFAULT_CAPTION_FONT_SIZE);+ expect(r.subtitles[0].style?.fontFamily).toBe(DEFAULT_CAPTION_STYLE.fontFamily);+ expect(r.subtitles[0].style?.color).toBe("#FFFF00");+ });++ it("promotes a uniform span colour to the cue and reports mixed colours", () => {+ const one = parseTtml(doc(`<p begin="0s" end="2s"><span tts:color="red">Hi</span> <span tts:color="red">there</span></p>`));+ expect(one.subtitles[0].style?.color).toBe("red");+ const mixed = parseTtml(doc(`<p begin="0s" end="2s"><span tts:color="red">Hi</span> <span tts:color="blue">there</span></p>`));+ expect(mixed.subtitles[0].style?.color).toBe("red");+ expect(mixed.issues.some((i) => /multi-colour/.test(i.message))).toBe(true);+ });++ it("keeps per-cue colour through TTML export and re-import", () => {+ const cues: Subtitle[] = [+ { id: "1", text: "A", startTime: 0, endTime: 1, style: { ...DEFAULT_CAPTION_STYLE, color: "#ffff00" } },+ { id: "2", text: "B", startTime: 2, endTime: 3, style: { ...DEFAULT_CAPTION_STYLE, color: "#00ff00" } },+ ];+ const back = parseTtml(exportCaptions(cues, "ttml"));+ expect(back.subtitles.map((c) => c.style?.color?.toLowerCase())).toEqual(["#ffff00", "#00ff00"]);+ });++ it("does not treat SRT with inline tags as TTML", () => {+ const srt = "<i>1</i>\n00:00:01,000 --> 00:00:02,000\n<i>Hello</i> <tt>mono</tt>\n";+ const r = parseCaptions(srt);+ expect(r.format).toBe("srt");+ const plain = parseCaptions("1\n00:00:01,000 --> 00:00:02,000\n<tt>mono</tt>\n");+ expect(plain.format).toBe("srt");+ expect(plain.subtitles).toHaveLength(1);+ });++ it("writes generic families unquoted for canvas", () => {+ expect(captionFont(24, "sans-serif")).toBe("bold 24px sans-serif, sans-serif");+ expect(captionFont(24, "Inter")).toBe('bold 24px "Inter", sans-serif');+ });+});diff --git a/packages/core/src/captions/sbv.ts b/packages/core/src/captions/sbv.tsnew file mode 100644index 00000000..dce5475b--- /dev/null+++ b/packages/core/src/captions/sbv.ts@@ -0,0 +1,100 @@+import type { Subtitle } from "../types/timeline";+import type { CaptionFormatIssue } from "./scc";++/**+ * YouTube SBV: `h:mm:ss.mmm,h:mm:ss.mmm` timing line followed by the cue text,+ * blocks separated by blank lines. No styling, no cue ids.+ */++const SBV_TIME = String.raw`(\d{1,3}):(\d{1,2}):(\d{1,2})(?:[.,](\d{1,3}))?`;+const SBV_TIMING = new RegExp(`^\\s*${SBV_TIME}\\s*,\\s*${SBV_TIME}\\s*$`);++export function isSbvContent(content: string): boolean {+ const first = content+ .replace(/^\uFEFF/, "")+ .split(/\r\n?|\n/)+ .find((line) => line.trim() !== "");+ return first !== undefined && SBV_TIMING.test(first);+}++const toSeconds = (h: string, m: string, s: string, ms = "0") =>+ Number(h) * 3600 + Number(m) * 60 + Number(s) + Number(ms.padEnd(3, "0")) / 1000;++export interface SbvParseResult {+ subtitles: Subtitle[];+ errors: Array<{ line: number; message: string }>;+ issues: CaptionFormatIssue[];+}++let counter = 0;++export function parseSbv(+ content: string,+ options: { language?: string; captionTrackId?: string; offsetSeconds?: number } = {},+): SbvParseResult {+ const lines = content.replace(/^\uFEFF/, "").split(/\r\n?|\n/);+ const subtitles: Subtitle[] = [];+ const errors: SbvParseResult["errors"] = [];+ const offset = options.offsetSeconds ?? 0;+ let i = 0;+ while (i < lines.length) {+ while (i < lines.length && lines[i].trim() === "") i++;+ if (i >= lines.length) break;+ const start = i;+ const block: string[] = [];+ while (i < lines.length && lines[i].trim() !== "") block.push(lines[i++]);+ const m = SBV_TIMING.exec(block[0]);+ if (!m) {+ errors.push({ line: start + 1, message: "Cue has no valid timing line (expected h:mm:ss.mmm,h:mm:ss.mmm)." });+ continue;+ }+ const startTime = Math.max(0, toSeconds(m[1], m[2], m[3], m[4]) - offset);+ const endTime = Math.max(0, toSeconds(m[5], m[6], m[7], m[8]) - offset);+ if (!(endTime > startTime)) {+ errors.push({ line: start + 1, message: "Cue ends before it starts." });+ continue;+ }+ const text = block+ .slice(1)+ .map((l) => l.trim())+ .filter(Boolean)+ .join("\n");+ if (!text) {+ errors.push({ line: start + 1, message: "Cue has no text." });+ continue;+ }+ subtitles.push({+ id: `cue-sbv-${Date.now().toString(36)}-${(counter++).toString(36)}`,+ text,+ startTime,+ endTime,+ ...(options.language ? { language: options.language } : {}),+ ...(options.captionTrackId ? { captionTrackId: options.captionTrackId } : {}),+ });+ }+ const issues: CaptionFormatIssue[] = [];+ if (subtitles.some((c) => c.cueSettings || c.style)) issues.push({ severity: "info", code: "sbv-style", message: "SBV carries no styling." });+ return { subtitles, errors, issues };+}++export function formatSbvTime(seconds: number): string {+ const total = Math.max(0, Math.round(seconds * 1000));+ const h = Math.floor(total / 3_600_000);+ const m = Math.floor(total / 60_000) % 60;+ const s = Math.floor(total / 1000) % 60;+ return `${h}:${String(m).padStart(2, "0")}:${String(s).padStart(2, "0")}.${String(total % 1000).padStart(3, "0")}`;+}++export function encodeSbv(cues: readonly Subtitle[]): { content: string; issues: CaptionFormatIssue[] } {+ const issues: CaptionFormatIssue[] = [];+ const blocks = cues.map((cue) => {+ if (cue.cueSettings || cue.style)+ issues.push({ severity: "info", code: "sbv-style", message: "SBV has no styling or positioning; it was dropped.", cueId: cue.id });+ return `${formatSbvTime(cue.startTime)},${formatSbvTime(cue.endTime)}\n${cue.text}`;+ });+ const styled = issues.length;+ return {+ content: blocks.length ? `${blocks.join("\n\n")}\n` : "",+ issues: styled ? [issues[0]] : [],+ };+}diff --git a/packages/core/src/captions/scc.ts b/packages/core/src/captions/scc.tsindex c076651e..b75177f9 100644--- a/packages/core/src/captions/scc.ts+++ b/packages/core/src/captions/scc.ts@@ -657,11 +657,11 @@ export interface SccParseOptions {}export function isSccContent(content: string): boolean {- return /^?\s*Scenarist_SCC/i.test(content);+ return /^\uFEFF?\s*Scenarist_SCC/i.test(content);}export function parseScc(content: string, options: SccParseOptions = {}): SccParseResult {- const text = content.replace(/^/, "").replace(/\r\n?/g, "\n");+ const text = content.replace(/^\uFEFF/, "").replace(/\r\n?/g, "\n");const errors: SccParseResult["errors"] = [];const issues: CaptionFormatIssue[] = [];const keepTags = options.styleTags === "keep";diff --git a/packages/core/src/captions/speaker-embedding.ts b/packages/core/src/captions/speaker-embedding.tsnew file mode 100644index 00000000..e5c64ebc--- /dev/null+++ b/packages/core/src/captions/speaker-embedding.ts@@ -0,0 +1,178 @@+/**+ * On-device speaker embedding: a compact voice-print from MFCC statistics and+ * pitch, computed with plain DSP (no model download, no network). It is a+ * classical i-vector-lite, good for telling a handful of voices apart inside+ * one programme, not for identifying people across recordings.+ */++export const EMBEDDING_SAMPLE_RATE = 16_000;+const FRAME = 512;+const HOP = 160;+const MEL_BANDS = 26;+const MFCCS = 13;+const MIN_VOICED_SECONDS = 0.3;+const PITCH_MIN_HZ = 70;+const PITCH_MAX_HZ = 420;++export const SPEAKER_EMBEDDING_DIMENSIONS = (MFCCS - 1) * 2 + 2;++/**+ * Per-dimension weights applied when clustering (after z-scoring). Mean pitch+ * is the most text-independent cue but natural intonation moves it, so it is+ * only doubled; MFCC deviations are the most text-dependent and are halved;+ * pitch deviation is ignored. Checked on 7 distinct voices speaking different+ * sentences.+ */+export const SPEAKER_EMBEDDING_WEIGHTS: readonly number[] = [+ ...Array<number>(MFCCS - 1).fill(1),+ ...Array<number>(MFCCS - 1).fill(0.5),+ 2,+ 0,+];++const hz2mel = (hz: number) => 2595 * Math.log10(1 + hz / 700);+const mel2hz = (mel: number) => 700 * (10 ** (mel / 2595) - 1);++let cachedBank: { filters: Float32Array[]; window: Float32Array } | null = null;++function bank() {+ if (cachedBank) return cachedBank;+ const bins = FRAME / 2 + 1;+ const lo = hz2mel(60);+ const hi = hz2mel(EMBEDDING_SAMPLE_RATE / 2 - 200);+ const points = Array.from({ length: MEL_BANDS + 2 }, (_, i) =>+ Math.floor(((FRAME + 1) * mel2hz(lo + ((hi - lo) * i) / (MEL_BANDS + 1))) / EMBEDDING_SAMPLE_RATE),+ );+ const filters = Array.from({ length: MEL_BANDS }, (_, m) => {+ const f = new Float32Array(bins);+ for (let k = points[m]; k < points[m + 1]; k++) f[k] = (k - points[m]) / Math.max(1, points[m + 1] - points[m]);+ for (let k = points[m + 1]; k < points[m + 2]; k++) f[k] = (points[m + 2] - k) / Math.max(1, points[m + 2] - points[m + 1]);+ return f;+ });+ const window = Float32Array.from({ length: FRAME }, (_, i) => 0.5 - 0.5 * Math.cos((2 * Math.PI * i) / (FRAME - 1)));+ cachedBank = { filters, window };+ return cachedBank;+}++/** In-place radix-2 FFT. */+function fft(re: Float32Array, im: Float32Array): void {+ const n = re.length;+ for (let i = 1, j = 0; i < n; i++) {+ let bit = n >> 1;+ for (; j & bit; bit >>= 1) j ^= bit;+ j ^= bit;+ if (i < j) {+ [re[i], re[j]] = [re[j], re[i]];+ [im[i], im[j]] = [im[j], im[i]];+ }+ }+ for (let len = 2; len <= n; len <<= 1) {+ const ang = (-2 * Math.PI) / len;+ const wr = Math.cos(ang);+ const wi = Math.sin(ang);+ for (let i = 0; i < n; i += len) {+ let cr = 1;+ let ci = 0;+ for (let k = 0; k < len / 2; k++) {+ const a = i + k;+ const b = a + len / 2;+ const tr = re[b] * cr - im[b] * ci;+ const ti = re[b] * ci + im[b] * cr;+ re[b] = re[a] - tr;+ im[b] = im[a] - ti;+ re[a] += tr;+ im[a] += ti;+ const nr = cr * wr - ci * wi;+ ci = cr * wi + ci * wr;+ cr = nr;+ }+ }+ }+}++function pitchOf(frame: Float32Array): number | null {+ const minLag = Math.floor(EMBEDDING_SAMPLE_RATE / PITCH_MAX_HZ);+ const maxLag = Math.min(frame.length - 1, Math.ceil(EMBEDDING_SAMPLE_RATE / PITCH_MIN_HZ));+ let zero = 0;+ for (let i = 0; i < frame.length; i++) zero += frame[i] * frame[i];+ if (zero <= 0) return null;+ let best = 0;+ let bestLag = 0;+ for (let lag = minLag; lag <= maxLag; lag++) {+ let sum = 0;+ for (let i = 0; i + lag < frame.length; i++) sum += frame[i] * frame[i + lag];+ if (sum > best) {+ best = sum;+ bestLag = lag;+ }+ }+ return bestLag && best / zero > 0.35 ? EMBEDDING_SAMPLE_RATE / bestLag : null;+}++/**+ * Voice-print of `samples` (mono, 16 kHz), or null when there is less than+ * 0.3 s of voiced audio. Layout: 12 MFCC means, 12 MFCC deviations, log-pitch+ * mean, voiced-frame pitch deviation.+ */+export function computeSpeakerEmbedding(samples: Float32Array): Float32Array | null {+ if (samples.length < FRAME) return null;+ const { filters, window } = bank();+ const frames = Math.floor((samples.length - FRAME) / HOP) + 1;+ const energies = new Float64Array(frames);+ for (let f = 0; f < frames; f++) {+ let e = 0;+ for (let i = 0; i < FRAME; i += 4) e += samples[f * HOP + i] ** 2;+ energies[f] = e;+ }+ const sorted = Array.from(energies).sort((a, b) => a - b);+ const peak = sorted[Math.floor(sorted.length * 0.95)] || 0;+ if (peak <= 1e-9) return null;+ const gate = peak * 10 ** (-30 / 10);++ const re = new Float32Array(FRAME);+ const im = new Float32Array(FRAME);+ const sums = new Float64Array(MFCCS - 1);+ const squares = new Float64Array(MFCCS - 1);+ const pitches: number[] = [];+ let voiced = 0;+ const frameBuf = new Float32Array(FRAME);+ for (let f = 0; f < frames; f++) {+ if (energies[f] < gate) continue;+ voiced++;+ for (let i = 0; i < FRAME; i++) {+ frameBuf[i] = samples[f * HOP + i];+ re[i] = frameBuf[i] * window[i];+ im[i] = 0;+ }+ fft(re, im);+ const logMel = new Float64Array(MEL_BANDS);+ for (let m = 0; m < MEL_BANDS; m++) {+ let e = 0;+ const filter = filters[m];+ for (let k = 0; k <= FRAME / 2; k++) if (filter[k]) e += filter[k] * (re[k] * re[k] + im[k] * im[k]);+ logMel[m] = Math.log(e + 1e-10);+ }+ for (let c = 1; c < MFCCS; c++) {+ let v = 0;+ for (let m = 0; m < MEL_BANDS; m++) v += logMel[m] * Math.cos((Math.PI * c * (m + 0.5)) / MEL_BANDS);+ sums[c - 1] += v;+ squares[c - 1] += v * v;+ }+ const pitch = pitchOf(frameBuf);+ if (pitch) pitches.push(Math.log(pitch));+ }+ if (voiced * (HOP / EMBEDDING_SAMPLE_RATE) < MIN_VOICED_SECONDS) return null;++ const out = new Float32Array(SPEAKER_EMBEDDING_DIMENSIONS);+ for (let c = 0; c < MFCCS - 1; c++) {+ const mean = sums[c] / voiced;+ out[c] = mean;+ out[MFCCS - 1 + c] = Math.sqrt(Math.max(0, squares[c] / voiced - mean * mean));+ }+ if (pitches.length >= 5) {+ const mean = pitches.reduce((a, b) => a + b, 0) / pitches.length;+ out[2 * (MFCCS - 1)] = mean;+ out[2 * (MFCCS - 1) + 1] = Math.sqrt(pitches.reduce((a, b) => a + (b - mean) ** 2, 0) / pitches.length);+ }+ return out;+}diff --git a/packages/core/src/captions/ttml.ts b/packages/core/src/captions/ttml.tsnew file mode 100644index 00000000..b1297b5a--- /dev/null+++ b/packages/core/src/captions/ttml.ts@@ -0,0 +1,417 @@+import type { CueSettings, Subtitle, SubtitleStyle } from "../types/timeline";+import type { CaptionFormatIssue } from "./scc";+import { DEFAULT_CAPTION_STYLE } from "./caption-layout";++/**+ * TTML / DFXP / IMSC1 import. A small tolerant XML tokenizer (no DOMParser, so+ * it runs in workers, Node and the desktop shell alike) feeds a TTML reader:+ * media / clock / smpte time bases, clock-time, offset-time (h m s ms f t) and+ * frame expressions, begin / end / dur with parent-relative timing, `<style>`+ * and `<region>` resolution (referential and inline), and `ttm:agent` speakers.+ * Colours, alignment, display alignment, region origin / extent, outline,+ * italic / bold / underline are mapped onto the caption style model.+ */++interface XmlNode {+ name: string;+ attrs: Record<string, string>;+ children: Array<XmlNode | string>;+ line: number;+}++const ENTITIES: Record<string, string> = { lt: "<", gt: ">", amp: "&", quot: '"', apos: "'", nbsp: " ", lrm: "", rlm: "" };++function decode(value: string): string {+ return value.replace(/&(#x[0-9a-f]+|#\d+|[a-z]+);/gi, (all, body: string) => {+ if (body[0] === "#") {+ const code = body[1] === "x" || body[1] === "X" ? parseInt(body.slice(2), 16) : parseInt(body.slice(1), 10);+ return Number.isFinite(code) && code > 0 && code <= 0x10ffff ? String.fromCodePoint(code) : "";+ }+ return ENTITIES[body.toLowerCase()] ?? all;+ });+}++const localName = (name: string) => name.slice(name.indexOf(":") + 1);++/** Parse into a tree of elements keyed by their local (prefix-free) names; attributes too. */+function parseXml(source: string): XmlNode | undefined {+ const root: XmlNode = { name: "#root", attrs: {}, children: [], line: 1 };+ const stack: XmlNode[] = [root];+ const re = /<!--[\s\S]*?-->|<!\[CDATA\[([\s\S]*?)\]\]>|<\?[\s\S]*?\?>|<!DOCTYPE[^>]*(?:\[[\s\S]*?\])?>|<\/\s*([^\s>]+)\s*>|<([^\s/>!?]+)((?:\s+[^\s=/>]+(?:\s*=\s*(?:"[^"]*"|'[^']*'|[^\s>]+))?)*)\s*(\/?)>/g;+ let last = 0;+ let line = 1;+ let counted = 0;+ const lineAt = (index: number) => {+ for (; counted < index; counted++) if (source.charCodeAt(counted) === 10) line++;+ return line;+ };+ const text = (value: string) => {+ if (value) stack[stack.length - 1].children.push(decode(value));+ };+ for (let m = re.exec(source); m; m = re.exec(source)) {+ text(source.slice(last, m.index));+ last = re.lastIndex;+ if (m[1] !== undefined) {+ stack[stack.length - 1].children.push(m[1]);+ } else if (m[2] !== undefined) {+ const name = localName(m[2]);+ // Close to the nearest matching open element; stray closers are ignored.+ for (let i = stack.length - 1; i > 0; i--) {+ if (stack[i].name === name) {+ stack.length = i;+ break;+ }+ }+ } else if (m[3] !== undefined) {+ const attrs: Record<string, string> = {};+ const attrRe = /([^\s=/>]+)(?:\s*=\s*(?:"([^"]*)"|'([^']*)'|([^\s>]+)))?/g;+ for (let a = attrRe.exec(m[4] ?? ""); a; a = attrRe.exec(m[4] ?? "")) {+ const key = a[1].startsWith("xmlns") ? a[1] : localName(a[1]);+ attrs[key] = decode(a[2] ?? a[3] ?? a[4] ?? "");+ }+ const node: XmlNode = { name: localName(m[3]), attrs, children: [], line: lineAt(m.index) };+ stack[stack.length - 1].children.push(node);+ if (!m[5]) stack.push(node);+ }+ }+ text(source.slice(last));+ return root.children.find((c): c is XmlNode => typeof c !== "string" && c.name === "tt");+}++/**+ * A TTML document starts with an XML prolog / comments / doctype and then a `<tt>` root.+ * Anchoring to the start keeps an SRT whose cue text contains `<tt>` (teletype) or other+ * inline markup from being mistaken for TTML.+ */+export function isTtmlContent(content: string): boolean {+ const head = content.replace(/^\uFEFF/, "").slice(0, 8192);+ return /^\s*(?:<\?xml[^>]*\?>\s*|<!--[\s\S]*?-->\s*|<!DOCTYPE[^>]*>\s*)*<(?:[A-Za-z_][\w.-]*:)?tt[\s>]/.test(head);+}++interface TimeContext {+ timeBase: "media" | "smpte" | "clock";+ frameRate: number;+ tickRate: number;+}++function parseTime(raw: string | undefined, ctx: TimeContext): number | undefined {+ if (raw === undefined) return undefined;+ const v = raw.trim();+ if (!v) return undefined;+ let m = /^(\d+):(\d{1,2}):(\d{1,2}(?:\.\d+)?)(?::(\d+)(?:\.(\d+))?)?$/.exec(v);+ if (m) {+ const frames = m[4] ? Number(m[4]) / ctx.frameRate : 0;+ return Number(m[1]) * 3600 + Number(m[2]) * 60 + Number(m[3]) + frames;+ }+ m = /^(\d+(?:\.\d+)?|\.\d+)(h|ms|m|s|f|t)$/.exec(v);+ if (m) {+ const n = Number(m[1]);+ switch (m[2]) {+ case "h": return n * 3600;+ case "m": return n * 60;+ case "s": return n;+ case "ms": return n / 1000;+ case "f": return n / ctx.frameRate;+ case "t": return n / ctx.tickRate;+ }+ }+ // Bare numbers are seconds in the wild, even though the spec wants a metric.+ if (/^\d+(?:\.\d+)?$/.test(v)) return Number(v);+ return NaN;+}++type Attrs = Record<string, string>;++/** `#RGB`, `#RRGGBB`, `#RRGGBBAA`, `rgb()/rgba()` and CSS names -> a CSS colour string. */+function colour(raw: string | undefined): string | undefined {+ if (!raw) return undefined;+ const v = raw.trim();+ if (/^transparent$/i.test(v)) return "rgba(0,0,0,0)";+ if (/^#[0-9a-f]{8}$/i.test(v)) {+ const a = parseInt(v.slice(7, 9), 16) / 255;+ return `rgba(${parseInt(v.slice(1, 3), 16)},${parseInt(v.slice(3, 5), 16)},${parseInt(v.slice(5, 7), 16)},${Math.round(a * 100) / 100})`;+ }+ if (/^#[0-9a-f]{6}$/i.test(v) || /^#[0-9a-f]{3}$/i.test(v)) return v;+ if (/^rgba?\(/i.test(v) || /^[a-z]+$/i.test(v)) return v.toLowerCase();+ return undefined;+}++const GENERIC_FONTS: Record<string, string> = {+ default: "sans-serif",+ monospace: "monospace",+ sansserif: "sans-serif",+ serif: "serif",+ monospacesansserif: "monospace",+ monospaceserif: "monospace",+ proportionalsansserif: "sans-serif",+ proportionalserif: "serif",+};++const percent = (raw: string | undefined): number | undefined => {+ const m = /^(-?\d+(?:\.\d+)?)%$/.exec((raw ?? "").trim());+ return m ? Number(m[1]) : undefined;+};++export interface TtmlParseOptions {+ language?: string;+ captionTrackId?: string;+ /** Seconds subtracted from every time (e.g. a 01:00:00:00 programme start). */+ offsetSeconds?: number;+ /** Frame rate for frame-based times when the file declares none. */+ frameRate?: number;+ /** Keep <i> / <b> / <u> for styled runs (default: strip). */+ styleTags?: "keep" | "strip";+}++export interface TtmlParseResult {+ subtitles: Subtitle[];+ errors: Array<{ line: number; message: string }>;+ issues: CaptionFormatIssue[];+}++let counter = 0;++export function parseTtml(content: string, options: TtmlParseOptions = {}): TtmlParseResult {+ const errors: TtmlParseResult["errors"] = [];+ const issues: CaptionFormatIssue[] = [];+ const empty = { subtitles: [], errors, issues };+ const source = content.replace(/^\uFEFF/, "");+ const tt = parseXml(source);+ if (!tt) {+ errors.push({ line: 1, message: "Not a TTML document: no <tt> root element was found." });+ return empty;+ }+ const child = (n: XmlNode, name: string) => n.children.find((c): c is XmlNode => typeof c !== "string" && c.name === name);+ const kids = (n: XmlNode, name: string) => n.children.filter((c): c is XmlNode => typeof c !== "string" && c.name === name);+ const descendants = (n: XmlNode, name: string, out: XmlNode[] = []): XmlNode[] => {+ for (const c of n.children) if (typeof c !== "string") {+ if (c.name === name) out.push(c);+ descendants(c, name, out);+ }+ return out;+ };++ const rate = Number(tt.attrs.frameRate) || options.frameRate || 30;+ const mult = /^(\d+)\s+(\d+)$/.exec((tt.attrs.frameRateMultiplier ?? "").trim());+ const ctx: TimeContext = {+ timeBase: tt.attrs.timeBase === "smpte" ? "smpte" : tt.attrs.timeBase === "clock" ? "clock" : "media",+ frameRate: mult ? (rate * Number(mult[1])) / Number(mult[2]) : rate,+ tickRate: Number(tt.attrs.tickRate) || (tt.attrs.frameRate ? rate * (Number(tt.attrs.subFrameRate) || 1) : 1),+ };+ if (ctx.timeBase === "clock") issues.push({ severity: "warning", code: "ttml-clock", message: "Wall-clock time base: times are read as media times." });+ const language = options.language ?? (tt.attrs.lang || undefined);++ const head = child(tt, "head");+ const styles = new Map<string, Attrs>();+ const regions = new Map<string, Attrs>();+ const agents = new Map<string, string>();+ if (head) {+ for (const s of descendants(head, "style")) if (s.attrs.id) styles.set(s.attrs.id, s.attrs);+ for (const r of descendants(head, "region")) {+ if (!r.attrs.id) continue;+ // Styles nested in a region apply to it.+ // Referential styles (`style="s1"`) first, then nested <style> children, then the region's own attributes.+ const merged: Attrs = resolveStyle(r.attrs);+ for (const s of kids(r, "style")) Object.assign(merged, resolveStyle(s.attrs));+ Object.assign(merged, r.attrs, { style: merged.style });+ regions.set(r.attrs.id, merged);+ }+ for (const a of descendants(head, "agent")) {+ const id = a.attrs.id;+ const name = kids(a, "name")[0]?.children.filter((c): c is string => typeof c === "string").join("").trim();+ if (id && name) agents.set(id, name);+ }+ }+ function resolveStyle(attrs: Attrs, seen = new Set<string>()): Attrs {+ const out: Attrs = {};+ for (const ref of (attrs.style ?? "").split(/\s+/).filter(Boolean)) {+ const target = styles.get(ref);+ if (target && !seen.has(ref)) Object.assign(out, resolveStyle(target, new Set(seen).add(ref)));+ }+ return Object.assign(out, attrs);+ }++ interface Inherited { style: Attrs; begin: number; end: number; region?: string; agent?: string }+ const subtitles: Subtitle[] = [];+ const unsupported = new Set<string>();++ const readText = (node: XmlNode, inherited: Attrs, keep: boolean, runs?: Array<string | undefined>): string => {+ let out = "";+ for (const c of node.children) {+ if (typeof c === "string") {+ out += c.replace(/\s+/g, " ");+ if (runs && c.trim()) runs.push(colour(inherited.color));+ }+ else if (c.name === "br") out += "\n";+ else if (c.name === "span" || c.name === "p") {+ const st = { ...inherited, ...resolveStyle(c.attrs) };+ let inner = readText(c, st, keep, runs);+ if (keep && inner.trim()) {+ if (st.fontStyle === "italic" || st.fontStyle === "oblique") inner = `<i>${inner}</i>`;+ if (st.fontWeight === "bold") inner = `<b>${inner}</b>`;+ if (/underline/.test(st.textDecoration ?? "")) inner = `<u>${inner}</u>`;+ }+ out += inner;+ } else if (c.name === "set" || c.name === "animate" || c.name === "metadata") {+ if (c.name !== "metadata") unsupported.add("animation");+ }+ }+ return out;+ };++ const walk = (node: XmlNode, inh: Inherited) => {+ const style = { ...inh.style, ...resolveStyle(node.attrs) };+ const b = parseTime(node.attrs.begin, ctx);+ const e = parseTime(node.attrs.end, ctx);+ const d = parseTime(node.attrs.dur, ctx);+ let unreadable = false;+ for (const [label, v] of [["begin", b], ["end", e], ["dur", d]] as const) {+ if (v !== undefined && Number.isNaN(v)) {+ unreadable = true;+ errors.push({ line: node.line, message: `Unreadable ${label} time "${node.attrs[label]}".` });+ }+ }+ if (unreadable) return;+ const begin = inh.begin + (b !== undefined && !Number.isNaN(b) ? b : 0);+ let end = inh.end;+ if (e !== undefined && !Number.isNaN(e)) end = inh.begin + e;+ else if (d !== undefined && !Number.isNaN(d)) end = begin + d;+ const next: Inherited = {+ style,+ begin,+ end,+ region: node.attrs.region ?? inh.region,+ agent: node.attrs.agent ?? inh.agent,+ };+ if (node.name !== "p") {+ for (const c of node.children) if (typeof c !== "string" && ["body", "div", "p"].includes(c.name)) walk(c, next);+ return;+ }+ const spans = descendants(node, "span");+ let start = begin;+ let stop = end;+ if (stop === Infinity) {+ // `<p>` without its own end: take the extent of its timed spans.+ const times = spans.map((s) => [parseTime(s.attrs.begin, ctx), parseTime(s.attrs.end, ctx)] as const);+ const begins = times.map((t) => t[0]).filter((t): t is number => t !== undefined && !Number.isNaN(t));+ const ends = times.map((t) => t[1]).filter((t): t is number => t !== undefined && !Number.isNaN(t));+ if (begins.length && ends.length) {+ start = begin + Math.min(...begins);+ stop = begin + Math.max(...ends);+ }+ }+ if (!Number.isFinite(stop) || !Number.isFinite(start)) {+ errors.push({ line: node.line, message: "Paragraph has no timing (begin / end / dur)." });+ return;+ }+ const region = (next.region ? regions.get(next.region) : undefined) ?? undefined;+ if (next.region && !region && !node.attrs.origin) unsupported.add(`missing region "${next.region}"`);+ const runColours: Array<string | undefined> = [];+ const text = readText(node, { ...(region ? regionOf(region) : {}), ...style }, options.styleTags === "keep", runColours)+ .split("\n")+ .map((l) => l.trim())+ .filter(Boolean)+ .join("\n");+ if (!text) {+ errors.push({ line: node.line, message: "Paragraph has no text." });+ return;+ }+ const offset = options.offsetSeconds ?? 0;+ const startTime = Math.max(0, Math.round((start - offset) * 1000) / 1000);+ const endTime = Math.max(0, Math.round((stop - offset) * 1000) / 1000);+ if (!(endTime > startTime)) {+ errors.push({ line: node.line, message: "Paragraph ends before it starts." });+ return;+ }+ // A colour set on spans (`<span tts:color=...>`) becomes the cue colour when every text run shares it;+ // a cue that mixes colours cannot be represented by one style, so say so instead of silently flattening.+ const distinct = new Set(runColours.map((c) => c ?? ""));+ const merged: Attrs = { ...style, ...(region ? regionOf(region) : {}) };+ if (distinct.size === 1) {+ const only = [...runColours][0];+ if (only) merged.color = only;+ } else if (distinct.size > 1) {+ unsupported.add("multi-colour text within one cue (the first colour is used)");+ const first = runColours.find(Boolean);+ if (first) merged.color = first;+ }+ const { cueStyle, cueSettings } = mapLayout(merged, node.attrs);+ const speaker = next.agent ? agents.get(next.agent) : undefined;+ subtitles.push({+ id: `cue-ttml-${Date.now().toString(36)}-${(counter++).toString(36)}`,+ text,+ startTime,+ endTime,+ ...(speaker ? { speaker } : {}),+ ...(cueStyle ? { style: cueStyle } : {}),+ ...(cueSettings ? { cueSettings } : {}),+ ...(language ? { language } : {}),+ ...(options.captionTrackId ? { captionTrackId: options.captionTrackId } : {}),+ });+ };+ const regionOf = (r: Attrs): Attrs => r;++ const body = child(tt, "body");+ if (!body) {+ errors.push({ line: tt.line, message: "TTML document has no <body>." });+ return empty;+ }+ walk(body, { style: {}, begin: 0, end: Infinity });+ for (const u of unsupported) issues.push({ severity: "info", code: "ttml-unsupported", message: `TTML ${u} is not supported and was ignored.` });+ if (!subtitles.length && !errors.length) errors.push({ line: 1, message: "No timed paragraphs were found in the TTML file." });+ return { subtitles, errors, issues };+}++function mapLayout(s: Attrs, pAttrs: Attrs): { cueStyle?: SubtitleStyle; cueSettings?: CueSettings } {+ const style: Record<string, unknown> = {};+ const color = colour(s.color);+ const bg = colour(s.backgroundColor);+ if (color) style.color = color;+ if (bg) style.backgroundColor = bg;+ if (s.fontFamily) {+ const first = s.fontFamily.split(",")[0].trim().replace(/^["']|["']$/g, "");+ style.fontFamily = GENERIC_FONTS[first.toLowerCase()] ?? first;+ }+ const px = /^(\d+(?:\.\d+)?)px$/.exec((s.fontSize ?? "").trim());+ if (px) style.fontSize = Number(px[1]);+ const outline = /^(?:(\S+)\s+)?(\d+(?:\.\d+)?)(?:px)?(?:\s+\S+)?$/.exec((s.textOutline ?? "").trim());+ if (outline && s.textOutline !== "none") {+ const oc = colour(outline[1]);+ if (oc) style.strokeColor = oc;+ style.strokeWidth = Number(outline[2]);+ }+ const align = s.displayAlign === "before" ? "top" : s.displayAlign === "center" ? "center" : s.displayAlign === "after" ? "bottom" : undefined;+ const origin = (pAttrs.origin ?? s.origin ?? "").trim().split(/\s+/);+ const extent = (pAttrs.extent ?? s.extent ?? "").trim().split(/\s+/);+ const ox = percent(origin[0]);+ const oy = percent(origin[1]);+ const ew = percent(extent[0]);+ const eh = percent(extent[1]);+ const settings: Record<string, unknown> = {};+ const ta = s.textAlign;+ if (ta === "left" || ta === "right" || ta === "center" || ta === "start" || ta === "end") settings.align = ta;+ if (oy !== undefined) {+ // Regions anchor text to the top / bottom of their box; WebVTT `line` is the box edge of that anchor.+ const height = eh ?? 0;+ const line = align === "bottom" || !align ? oy + height : align === "center" ? oy + height / 2 : oy;+ settings.line = Math.round(Math.min(100, Math.max(0, line)) * 100) / 100;+ settings.snapToLines = false;+ settings.lineAlign = align === "bottom" || !align ? "end" : align === "center" ? "center" : "start";+ }+ if (ew !== undefined) {+ settings.size = ew;+ if (ox !== undefined) settings.position = Math.round(Math.min(100, Math.max(0, ox + ew / 2)) * 100) / 100;+ settings.positionAlign = "center";+ }+ const position = oy !== undefined+ ? (oy + (eh ?? 0) / 2 < 33 ? "top" : oy + (eh ?? 0) / 2 < 66 ? "center" : "bottom")+ : align;+ const cueStyle: SubtitleStyle | undefined = Object.keys(style).length > 0+ ? ({+ ...DEFAULT_CAPTION_STYLE,+ position: position ?? DEFAULT_CAPTION_STYLE.position,+ ...style,+ } as SubtitleStyle)+ : undefined;+ return { cueStyle, cueSettings: Object.keys(settings).length ? (settings as CueSettings) : undefined };+}diff --git a/packages/core/src/color/camera-log.test.ts b/packages/core/src/color/camera-log.test.tsnew file mode 100644index 00000000..209df2fe--- /dev/null+++ b/packages/core/src/color/camera-log.test.ts@@ -0,0 +1,193 @@+import { describe, expect, it } from "vitest";+import {+ CAMERA_LOGS,+ cameraGamutToBt2020,+ cameraGamutToBt709,+ cameraLogDef,+ cameraLogGlsl,+ cameraLogGlslExpression,+ decodeCameraLog,+ encodeCameraLog,+ type CameraLogId,+} from "./camera-log";+import { createInputTransform, transformPixel } from "./input-transform";+import { CAMERA_FOOTAGE_COLOR_PRESETS, effectiveSourceColor, inputSpaceForItem, isFootageColorPreset, needsInputTransform } from "./source-color";+import { decodeToWorkingLinear, hdrSourceDecode } from "./hdr-working";++/**+ * Published reference values. Each manufacturer states the signal for 0% and 18% grey (and most for 90% white);+ * the 10-bit code values quoted in their documents are signal * 1023.+ */+const REFERENCE: Record<CameraLogId, { black: number; grey18: number; white90: number; tolerance: number }> = {+ // Sony: 95 / 420 / 598 (10-bit CV)+ slog3: { black: 95 / 1023, grey18: 420 / 1023, white90: 598 / 1023, tolerance: 6e-4 },+ // Panasonic: 0.125 / 0.423311 / 0.5886+ vlog: { black: 0.125, grey18: 0.423311, white90: 0.5886, tolerance: 6e-4 },+ // ARRI LogC3 EI 800: 0.092809 / 0.391007 / 0.5594+ logc3: { black: 0.092809, grey18: 0.391007, white90: 0.5594, tolerance: 4e-4 },+ // ARRI LogC4: 0.092864 / 0.278395 published; 90% white is hand-evaluated from the specification formula+ logc4: { black: 95 / 1023, grey18: 0.278395, white90: 0.41798, tolerance: 4e-4 },+ // Canon C-Log3: 0.073059 / 0.313437 / 0.5678+ clog3: { black: 0.073059361, grey18: 0.313437, white90: 0.5678, tolerance: 4e-4 },+ // Nikon N-Log: 0.1243 / 0.363667 / 0.5896+ nlog: { black: 0.1243, grey18: 0.363667, white90: 0.5896, tolerance: 6e-4 },+ // Fujifilm F-Log: 95 / 470 / 705 (10-bit CV)+ flog: { black: 0.092864, grey18: 0.459319, white90: 0.68951, tolerance: 4e-4 },+ // Fujifilm F-Log2: 95 / 400 / 570+ flog2: { black: 0.092864, grey18: 0.391007, white90: 0.55713, tolerance: 4e-4 },+ // Blackmagic Film Gen5: black 0.0924657 (E), 18% grey 0.38357; 90% white hand-evaluated from the formula+ bmdfilm5: { black: 0.0924657534, grey18: 0.383566, white90: 0.52137, tolerance: 6e-4 },+};++describe("camera log curves against published reference values", () => {+ for (const def of CAMERA_LOGS) {+ const ref = REFERENCE[def.id];+ it(`${def.label}: encodes 0%, 18% grey and 90% white to the published signal`, () => {+ expect(def.encode(0)).toBeCloseTo(ref.black, 3);+ expect(Math.abs(def.encode(0.18) - ref.grey18)).toBeLessThan(ref.tolerance);+ expect(Math.abs(def.encode(0.9) - ref.white90)).toBeLessThan(ref.tolerance * 3);+ expect(Math.abs(def.grey18 - ref.grey18)).toBeLessThan(ref.tolerance);+ });+ it(`${def.label}: the 18% grey signal decodes to 0.18 scene linear`, () => {+ expect(def.decode(ref.grey18)).toBeCloseTo(0.18, 2);+ expect(def.decode(def.encode(0.18))).toBeCloseTo(0.18, 5);+ });+ it(`${def.label}: decode inverts encode across the range and is monotonic`, () => {+ let previous = -Infinity;+ for (const linear of [-0.005, 0, 0.0005, 0.002, 0.01, 0.05, 0.18, 0.5, 0.9, 1, 2, 5, 10]) {+ const signal = def.encode(linear);+ const back = def.decode(signal);+ // N-Log's two segments meet with a 0.2 code gap in the published constants.+ const tolerance = def.id === "nlog" ? 2e-3 : def.id === "flog" ? 1e-4 : 1e-5;+ expect(Math.abs(back - linear)).toBeLessThan(Math.max(tolerance, Math.abs(linear) * 1e-4));+ expect(signal).toBeGreaterThan(previous);+ previous = signal;+ }+ });+ }++ it("matches exact published values at the segment joins and landmarks", () => {+ // S-Log3: 1.0 reflectance and the cut between the log and linear segments.+ expect(decodeCameraLog(171.2102946929 / 1023, "slog3")).toBeCloseTo(0.01125, 6);+ // LogC4 mid grey is the specification's 0.2784 and 0 maps to 95/1023.+ expect(encodeCameraLog(0.18, "logc4")).toBeCloseTo(0.2784, 3);+ // ARRI LogC3 EI 800 is continuous at the cut.+ expect(encodeCameraLog(0.010591, "logc3")).toBeCloseTo(5.367655 * 0.010591 + 0.092809, 4);+ // V-Log is continuous at its cut (0.181 signal <-> 0.01 linear).+ expect(decodeCameraLog(0.181, "vlog")).toBeCloseTo(0.01, 4);+ // C-Log3 is continuous at both cuts.+ expect(decodeCameraLog(0.04076162, "clog3")).toBeCloseTo(-0.014, 4);+ expect(decodeCameraLog(0.105357102, "clog3")).toBeCloseTo(0.014, 4);+ // Blackmagic: published A, B, C and the derived toe slope D = 8.283611, E = 0.0924657.+ expect(encodeCameraLog(0.005, "bmdfilm5")).toBeCloseTo(0.13389, 4);+ expect(encodeCameraLog(0, "bmdfilm5")).toBeCloseTo(0.0924657, 6);+ expect((encodeCameraLog(0.005001, "bmdfilm5") - encodeCameraLog(0.005, "bmdfilm5")) / 0.000001).toBeCloseTo(8.283611, 2);+ });++ it("clamps nothing: highlights above white decode above 1.0", () => {+ for (const def of CAMERA_LOGS) expect(def.decode(1)).toBeGreaterThan(1);+ });+});++describe("shader parity", () => {+ // The shader expression is plain arithmetic plus pow / exp and ?:, so it evaluates as JavaScript.+ const evaluate = (id: CameraLogId): ((y: number) => number) =>+ new Function("pow", "exp", "y", `return ${cameraLogGlslExpression(id)};`).bind(null, Math.pow, Math.exp) as (y: number) => number;++ for (const def of CAMERA_LOGS) {+ it(`${def.label}: the GLSL source equals the TypeScript curve over the full signal range`, () => {+ const shader = evaluate(def.id);+ for (let i = 0; i <= 1023; i++) {+ const y = i / 1023;+ const expected = def.decode(y);+ expect(Math.abs(shader(y) - expected)).toBeLessThanOrEqual(Math.max(1e-9, Math.abs(expected) * 1e-9));+ }+ });+ }++ it("emits one GLSL function per curve and a dispatcher for transfer ids 4..12", () => {+ const glsl = cameraLogGlsl();+ for (const def of CAMERA_LOGS) {+ expect(glsl).toContain(`float camLog_${def.id}(float y)`);+ expect(glsl).toContain(`if (id == ${def.shaderId}) return`);+ }+ expect(CAMERA_LOGS.map((d) => d.shaderId)).toEqual([4, 5, 6, 7, 8, 9, 10, 11, 12]);+ // Every numeric literal carries a decimal point or exponent (GLSL ES has no implicit int-to-float).+ expect(glsl.replace(/camLog_\w+|\bid == \d+|vec3|float|int/g, "")).not.toMatch(/(?<![\w.])\d+(?![\w.\d])/);+ });+});++describe("gamut matrices", () => {+ const rowSums = (m: readonly (readonly number[])[]) => m.map((r) => r[0] + r[1] + r[2]);++ it("every gamut conversion preserves white (rows sum to 1)", () => {+ for (const def of CAMERA_LOGS) {+ for (const s of rowSums(cameraGamutToBt709(def.gamut))) expect(s).toBeCloseTo(1, 5);+ for (const s of rowSums(cameraGamutToBt2020(def.gamut))) expect(s).toBeCloseTo(1, 5);+ }+ });++ it("matches the published S-Gamut3.Cine and ARRI Wide Gamut 3 to Rec.709 matrices", () => {+ const sony = cameraGamutToBt709("sgamut3cine");+ const sonyRef = [[1.6269474, -0.5401385, -0.0868089], [-0.1785403, 1.4179409, -0.2394006], [-0.0444361, -0.1959199, 1.240356]];+ const arri = cameraGamutToBt709("awg3");+ const arriRef = [[1.617523, -0.537287, -0.080237], [-0.070573, 1.334613, -0.26404], [-0.021102, -0.226954, 1.248056]];+ for (let r = 0; r < 3; r++) {+ for (let c = 0; c < 3; c++) {+ expect(sony[r][c]).toBeCloseTo(sonyRef[r][c], 2);+ expect(arri[r][c]).toBeCloseTo(arriRef[r][c], 2);+ }+ }+ });++ it("Rec.2020 (Nikon, Fujifilm) converts with the standard Rec.2020 to Rec.709 matrix", () => {+ const m = cameraGamutToBt709("bt2020");+ const ref = [[1.660491, -0.587641, -0.072850], [-0.124550, 1.132900, -0.008349], [-0.018151, -0.100579, 1.118730]];+ for (let r = 0; r < 3; r++) for (let c = 0; c < 3; c++) expect(m[r][c]).toBeCloseTo(ref[r][c], 3);+ });+});++describe("camera presets in the colour pipeline", () => {+ it("offers one Camera input preset per curve and they are valid footage presets", () => {+ expect(CAMERA_FOOTAGE_COLOR_PRESETS).toHaveLength(9);+ for (const p of CAMERA_FOOTAGE_COLOR_PRESETS) {+ expect(isFootageColorPreset(p.id)).toBe(true);+ expect(needsInputTransform(p.space)).toBe(true);+ }+ });++ it("an interpretation override selects the input transform, and tags alone do not", () => {+ expect(inputSpaceForItem({ metadata: {}, colorInterpretation: "log-slog3" })?.transfer).toBe("slog3");+ expect(effectiveSourceColor({ metadata: {}, colorInterpretation: "log-logc4" }).primaries).toBe("awg4");+ });++ it("18% grey log footage lands on sRGB grey 18% (code 118) and stays neutral", () => {+ for (const def of CAMERA_LOGS) {+ const t = createInputTransform(CAMERA_FOOTAGE_COLOR_PRESETS.find((p) => p.camera?.logId === def.id)!.space)!;+ expect(t).not.toBeNull();+ // The 8-bit code nearest the published grey signal.+ const code = Math.round(def.grey18 * 255) / 255;+ const [r, g, b] = transformPixel(code, code, code, t);+ expect(Math.abs(r * 255 - 118)).toBeLessThan(3);+ expect(Math.abs(r - g)).toBeLessThan(0.01);+ expect(Math.abs(g - b)).toBeLessThan(0.01);+ }+ });++ it("black stays black and over-exposed log stays inside the display range", () => {+ const t = createInputTransform(CAMERA_FOOTAGE_COLOR_PRESETS[0].space)!;+ expect(transformPixel(0, 0, 0, t).every((v) => v < 0.02)).toBe(true);+ expect(transformPixel(1, 1, 1, t).every((v) => v <= 1)).toBe(true);+ });++ it("the HDR working-space decode (CPU reference of the shader path) uses the same curve and a BT.2020 matrix", () => {+ for (const def of CAMERA_LOGS) {+ const space = CAMERA_FOOTAGE_COLOR_PRESETS.find((p) => p.camera?.logId === def.id)!.space;+ const decode = hdrSourceDecode(space);+ expect(decode.transfer).toBe(def.shaderId);+ expect(decodeToWorkingLinear(0.5, decode.transfer)).toBeCloseTo(def.decode(0.5), 12);+ expect(cameraLogDef(def.id).gamut).toBe(space.primaries);+ for (const s of decode.toBt2020.map((r) => r[0] + r[1] + r[2])) expect(s).toBeCloseTo(1, 5);+ }+ });+});diff --git a/packages/core/src/color/camera-log.ts b/packages/core/src/color/camera-log.tsnew file mode 100644index 00000000..ed11838c--- /dev/null+++ b/packages/core/src/color/camera-log.ts@@ -0,0 +1,367 @@+/**+ * Camera log input transforms: the published manufacturer log encodings and+ * wide gamuts, as formulas (no LUT files), for Sony S-Log3 / S-Gamut3.Cine,+ * Panasonic V-Log / V-Gamut, ARRI LogC3 / LogC4 (AWG3 / AWG4), Canon C-Log3 /+ * Cinema Gamut, Nikon N-Log (Rec.2020), Fujifilm F-Log and F-Log2 (Rec.2020)+ * and Blackmagic Film Gen5 / Wide Gamut.+ *+ * Each curve maps the normalised log signal (0..1, i.e. 10-bit code / 1023,+ * after the decoder's range handling) to SCENE-LINEAR reflectance where+ * 18% grey = 0.18 and a 90% white card = 0.9. That is the same unit the HDR+ * working space uses (1.0 = SDR reference white), so the CPU input transform,+ * the CPU HDR reference and the WebGL2 shader all share one definition: the+ * shader source below is generated from the same constants as the TypeScript+ * decoders, and `camera-log.test.ts` evaluates that shader source against the+ * TypeScript curves.+ *+ * Display rendering (log -> Rec.709) is done by the shared input transform:+ * gamut matrix to Rec.709 primaries, the shared highlight shoulder+ * (`toneMapLuminance`), then the sRGB OETF. It is a technical, exposure+ * neutral conversion, not a creative look: grey stays grey, 18% grey lands on+ * sRGB code 118, and nothing is added to contrast.+ *+ * Sources of the constants: Sony "Technical Summary for S-Gamut3.Cine/S-Log3",+ * Panasonic "V-Log/V-Gamut Reference Manual", ARRI "LogC3 curve" white paper+ * (EI 800) and "ARRI LogC4 Logarithmic Color Space Specification", Canon+ * "Canon Log 3 / Cinema Gamut" white paper, Nikon "N-Log Specification+ * Document", Fujifilm "F-Log / F-Log2 Data Sheet", Blackmagic Design+ * "Blackmagic Generation 5 Color Science".+ *+ * This module imports nothing so every colour module can depend on it.+ */++export type CameraLogId =+ | "slog3"+ | "vlog"+ | "logc3"+ | "logc4"+ | "clog3"+ | "nlog"+ | "flog"+ | "flog2"+ | "bmdfilm5";++export type CameraGamutId = "sgamut3cine" | "vgamut" | "awg3" | "awg4" | "cinemagamut" | "bt2020" | "bmdwg";++type Matrix3 = readonly [readonly number[], readonly number[], readonly number[]];++// -- constants -----------------------------------------------------------------------------------------------++const SLOG3_CUT = 171.2102946929 / 1023;++const VLOG = { cut1: 0.01, cut2: 0.181, b: 0.00873, c: 0.241514, d: 0.598206 } as const;++const LOGC3 = { cut: 0.010591, a: 5.555556, b: 0.052272, c: 0.24719, d: 0.385537, e: 5.367655, f: 0.092809 } as const;++const LOGC4_A = (2 ** 18 - 16) / 117.45;+const LOGC4_B = (1023 - 95) / 1023;+const LOGC4_C = 95 / 1023;+const LOGC4 = {+ a: LOGC4_A,+ b: LOGC4_B,+ c: LOGC4_C,+ s: (7 * Math.LN2 * 2 ** (7 - (14 * LOGC4_C) / LOGC4_B)) / (LOGC4_A * LOGC4_B),+ t: (2 ** (14 * (-LOGC4_C / LOGC4_B) + 6) - 64) / LOGC4_A,+} as const;++const CLOG3 = {+ lowCut: 0.04076162,+ highCut: 0.105357102,+ lowOffset: 0.07623209,+ lowSlope: 0.42889912,+ lowScale: 14.98325,+ midOffset: 0.073059361,+ midSlope: 2.3069815,+ highOffset: 0.069886632,+} as const;++const NLOG = { cut: 452 / 1023, scale: 650, offset: 0.0075, logBase: 619, logScale: 150 } as const;++const FLOG = { a: 0.555556, b: 0.009468, c: 0.344676, d: 0.790453, e: 8.735631, f: 0.092864, cut1: 0.00089, cut2: 0.100537775223865 } as const;+const FLOG2 = { a: 5.555556, b: 0.064829, c: 0.245281, d: 0.384316, e: 8.799461, f: 0.092864, cut1: 0.000889, cut2: 0.100686685370811 } as const;++const BMD_A = 0.08692876065491224;+const BMD_B = 0.005494072432257808;+const BMD_C = 0.5300133039991736;+const BMD_LIN_CUT = 0.005;+/** The linear toe is the tangent of the log segment at the cut, which fixes both of its constants. */+const BMD_D = BMD_A / (BMD_LIN_CUT + BMD_B);+const BMD_E = BMD_A * Math.log(BMD_LIN_CUT + BMD_B) + BMD_C - BMD_D * BMD_LIN_CUT;+const BMDFILM5 = { a: BMD_A, b: BMD_B, c: BMD_C, d: BMD_D, e: BMD_E, linCut: BMD_LIN_CUT, logCut: BMD_D * BMD_LIN_CUT + BMD_E } as const;++// -- curves: log signal -> scene linear ----------------------------------------------------------------------++const log10 = Math.log10;++function slog3Decode(y: number): number {+ return y >= SLOG3_CUT+ ? 10 ** ((y * 1023 - 420) / 261.5) * (0.18 + 0.01) - 0.01+ : ((y * 1023 - 95) * 0.01125) / (171.2102946929 - 95);+}+function slog3Encode(x: number): number {+ return x >= 0.01125 ? (420 + log10((x + 0.01) / (0.18 + 0.01)) * 261.5) / 1023 : ((x * (171.2102946929 - 95)) / 0.01125 + 95) / 1023;+}++function vlogDecode(y: number): number {+ return y < VLOG.cut2 ? (y - 0.125) / 5.6 : 10 ** ((y - VLOG.d) / VLOG.c) - VLOG.b;+}+function vlogEncode(x: number): number {+ return x < VLOG.cut1 ? 5.6 * x + 0.125 : VLOG.c * log10(x + VLOG.b) + VLOG.d;+}++function logc3Decode(y: number): number {+ return y > LOGC3.e * LOGC3.cut + LOGC3.f ? (10 ** ((y - LOGC3.d) / LOGC3.c) - LOGC3.b) / LOGC3.a : (y - LOGC3.f) / LOGC3.e;+}+function logc3Encode(x: number): number {+ return x > LOGC3.cut ? LOGC3.c * log10(LOGC3.a * x + LOGC3.b) + LOGC3.d : LOGC3.e * x + LOGC3.f;+}++function logc4Decode(y: number): number {+ return y >= 0 ? (2 ** ((14 * (y - LOGC4.c)) / LOGC4.b + 6) - 64) / LOGC4.a : y * LOGC4.s + LOGC4.t;+}+function logc4Encode(x: number): number {+ return x >= LOGC4.t ? ((Math.log2(LOGC4.a * x + 64) - 6) / 14) * LOGC4.b + LOGC4.c : (x - LOGC4.t) / LOGC4.s;+}++function clog3Decode(y: number): number {+ const k = CLOG3;+ if (y < k.lowCut) return -(10 ** ((k.lowOffset - y) / k.lowSlope) - 1) / k.lowScale;+ if (y <= k.highCut) return (y - k.midOffset) / k.midSlope;+ return (10 ** ((y - k.highOffset) / k.lowSlope) - 1) / k.lowScale;+}+function clog3Encode(x: number): number {+ const k = CLOG3;+ if (x < -0.014) return -k.lowSlope * log10(-x * k.lowScale + 1) + k.lowOffset;+ if (x <= 0.014) return k.midSlope * x + k.midOffset;+ return k.lowSlope * log10(x * k.lowScale + 1) + k.highOffset;+}++function nlogDecode(y: number): number {+ const code = y * 1023;+ return y < NLOG.cut ? (code / NLOG.scale) ** 3 - NLOG.offset : Math.exp((code - NLOG.logBase) / NLOG.logScale);+}+function nlogEncode(x: number): number {+ return (x < 0.328 ? NLOG.scale * Math.cbrt(x + NLOG.offset) : NLOG.logScale * Math.log(x) + NLOG.logBase) / 1023;+}++function makeFujiDecode(k: typeof FLOG | typeof FLOG2): (y: number) => number {+ return (y) => (y >= k.cut2 ? (10 ** ((y - k.d) / k.c) - k.b) / k.a : (y - k.f) / k.e);+}+function makeFujiEncode(k: typeof FLOG | typeof FLOG2): (x: number) => number {+ return (x) => (x >= k.cut1 ? k.c * log10(k.a * x + k.b) + k.d : k.e * x + k.f);+}++function bmdDecode(y: number): number {+ return y >= BMDFILM5.logCut ? Math.exp((y - BMDFILM5.c) / BMDFILM5.a) - BMDFILM5.b : (y - BMDFILM5.e) / BMDFILM5.d;+}+function bmdEncode(x: number): number {+ return x >= BMDFILM5.linCut ? BMDFILM5.a * Math.log(x + BMDFILM5.b) + BMDFILM5.c : BMDFILM5.d * x + BMDFILM5.e;+}++// -- shader source ---------------------------------------------------------------------------------------------++/** A GLSL float literal that always carries a decimal point or exponent. */+function glf(value: number): string {+ const text = String(value);+ return /[.e]/i.test(text) ? text : `${text}.0`;+}++const cube = (expr: string) => `((${expr})*(${expr})*(${expr}))`;++/**+ * Each curve as a single GLSL ES 3.00 float expression of `y` (the log+ * signal). Only `pow`, `exp`, `?:` and arithmetic are used, so the same text+ * is valid JavaScript once `pow` and `exp` are mapped: the unit test does that+ * to hold the shader to the TypeScript curve.+ */+const GLSL_EXPR: Record<CameraLogId, string> = {+ slog3: `y >= ${glf(SLOG3_CUT)} ? pow(10.0, (y * 1023.0 - 420.0) / 261.5) * 0.19 - 0.01 : (y * 1023.0 - 95.0) * 0.01125 / (171.2102946929 - 95.0)`,+ vlog: `y < ${glf(VLOG.cut2)} ? (y - 0.125) / 5.6 : pow(10.0, (y - ${glf(VLOG.d)}) / ${glf(VLOG.c)}) - ${glf(VLOG.b)}`,+ logc3: `y > ${glf(LOGC3.e * LOGC3.cut + LOGC3.f)} ? (pow(10.0, (y - ${glf(LOGC3.d)}) / ${glf(LOGC3.c)}) - ${glf(LOGC3.b)}) / ${glf(LOGC3.a)} : (y - ${glf(LOGC3.f)}) / ${glf(LOGC3.e)}`,+ logc4: `y >= 0.0 ? (pow(2.0, 14.0 * (y - ${glf(LOGC4.c)}) / ${glf(LOGC4.b)} + 6.0) - 64.0) / ${glf(LOGC4.a)} : y * ${glf(LOGC4.s)} + ${glf(LOGC4.t)}`,+ clog3: `y < ${glf(CLOG3.lowCut)} ? -(pow(10.0, (${glf(CLOG3.lowOffset)} - y) / ${glf(CLOG3.lowSlope)}) - 1.0) / ${glf(CLOG3.lowScale)} : y <= ${glf(CLOG3.highCut)} ? (y - ${glf(CLOG3.midOffset)}) / ${glf(CLOG3.midSlope)} : (pow(10.0, (y - ${glf(CLOG3.highOffset)}) / ${glf(CLOG3.lowSlope)}) - 1.0) / ${glf(CLOG3.lowScale)}`,+ nlog: `y < ${glf(NLOG.cut)} ? ${cube(`y * 1023.0 / ${glf(NLOG.scale)}`)} - ${glf(NLOG.offset)} : exp((y * 1023.0 - ${glf(NLOG.logBase)}) / ${glf(NLOG.logScale)})`,+ flog: `y >= ${glf(FLOG.cut2)} ? (pow(10.0, (y - ${glf(FLOG.d)}) / ${glf(FLOG.c)}) - ${glf(FLOG.b)}) / ${glf(FLOG.a)} : (y - ${glf(FLOG.f)}) / ${glf(FLOG.e)}`,+ flog2: `y >= ${glf(FLOG2.cut2)} ? (pow(10.0, (y - ${glf(FLOG2.d)}) / ${glf(FLOG2.c)}) - ${glf(FLOG2.b)}) / ${glf(FLOG2.a)} : (y - ${glf(FLOG2.f)}) / ${glf(FLOG2.e)}`,+ bmdfilm5: `y >= ${glf(BMDFILM5.logCut)} ? exp((y - ${glf(BMDFILM5.c)}) / ${glf(BMDFILM5.a)}) - ${glf(BMDFILM5.b)} : (y - ${glf(BMDFILM5.e)}) / ${glf(BMDFILM5.d)}`,+};++/** The single-expression GLSL body of a curve (a function of `y`), exposed for parity tests. */+export function cameraLogGlslExpression(id: CameraLogId): string {+ return GLSL_EXPR[id];+}++// -- gamuts ----------------------------------------------------------------------------------------------------++type XY = readonly [number, number];+interface GamutDef {+ readonly r: XY;+ readonly g: XY;+ readonly b: XY;+ readonly white: XY;+}++const D65: XY = [0.3127, 0.329];++const GAMUTS: Record<CameraGamutId | "rec709", GamutDef> = {+ rec709: { r: [0.64, 0.33], g: [0.3, 0.6], b: [0.15, 0.06], white: D65 },+ bt2020: { r: [0.708, 0.292], g: [0.17, 0.797], b: [0.131, 0.046], white: D65 },+ sgamut3cine: { r: [0.766, 0.275], g: [0.225, 0.8], b: [0.089, -0.087], white: D65 },+ vgamut: { r: [0.73, 0.28], g: [0.165, 0.84], b: [0.1, -0.03], white: D65 },+ awg3: { r: [0.684, 0.313], g: [0.221, 0.848], b: [0.0861, -0.102], white: D65 },+ awg4: { r: [0.7347, 0.2653], g: [0.1424, 0.8576], b: [0.0991, -0.0308], white: D65 },+ cinemagamut: { r: [0.74, 0.27], g: [0.17, 1.14], b: [0.08, -0.1], white: D65 },+ bmdwg: { r: [0.7177215, 0.3171181], g: [0.228041, 0.861569], b: [0.1005841, -0.0825512], white: [0.312717, 0.3290312] },+};++function mul3(a: Matrix3, b: Matrix3): Matrix3 {+ const out = [0, 1, 2].map((i) => [0, 1, 2].map((j) => a[i][0] * b[0][j] + a[i][1] * b[1][j] + a[i][2] * b[2][j]));+ return out as unknown as Matrix3;+}++function inv3(m: Matrix3): Matrix3 {+ const [[a, b, c], [d, e, f], [g, h, i]] = m;+ const A = e * i - f * h;+ const B = -(d * i - f * g);+ const C = d * h - e * g;+ const det = a * A + b * B + c * C;+ return [+ [A / det, -(b * i - c * h) / det, (b * f - c * e) / det],+ [B / det, (a * i - c * g) / det, -(a * f - c * d) / det],+ [C / det, -(a * h - b * g) / det, (a * e - b * d) / det],+ ];+}++const xyzOf = ([x, y]: XY): [number, number, number] => [x / y, 1, (1 - x - y) / y];++/** Linear RGB (the gamut's own primaries and white) to CIE XYZ. */+function rgbToXyz(g: GamutDef): Matrix3 {+ const cols = [xyzOf(g.r), xyzOf(g.g), xyzOf(g.b)];+ const prim: Matrix3 = [+ [cols[0][0], cols[1][0], cols[2][0]],+ [cols[0][1], cols[1][1], cols[2][1]],+ [cols[0][2], cols[1][2], cols[2][2]],+ ];+ const w = xyzOf(g.white);+ const inverse = inv3(prim);+ const s = [0, 1, 2].map((i) => inverse[i][0] * w[0] + inverse[i][1] * w[1] + inverse[i][2] * w[2]);+ return [+ [prim[0][0] * s[0], prim[0][1] * s[1], prim[0][2] * s[2]],+ [prim[1][0] * s[0], prim[1][1] * s[1], prim[1][2] * s[2]],+ [prim[2][0] * s[0], prim[2][1] * s[1], prim[2][2] * s[2]],+ ];+}++const BRADFORD: Matrix3 = [+ [0.8951, 0.2664, -0.1614],+ [-0.7502, 1.7135, 0.0367],+ [0.0389, -0.0685, 1.0296],+];++/** Bradford chromatic adaptation from one white to another (identity when they match). */+function adaptation(from: XY, to: XY): Matrix3 {+ if (from[0] === to[0] && from[1] === to[1]) return [[1, 0, 0], [0, 1, 0], [0, 0, 1]];+ const src = xyzOf(from);+ const dst = xyzOf(to);+ const cs = [0, 1, 2].map((i) => BRADFORD[i][0] * src[0] + BRADFORD[i][1] * src[1] + BRADFORD[i][2] * src[2]);+ const cd = [0, 1, 2].map((i) => BRADFORD[i][0] * dst[0] + BRADFORD[i][1] * dst[1] + BRADFORD[i][2] * dst[2]);+ const scale: Matrix3 = [[cd[0] / cs[0], 0, 0], [0, cd[1] / cs[1], 0], [0, 0, cd[2] / cs[2]]];+ return mul3(inv3(BRADFORD), mul3(scale, BRADFORD));+}++/** Linear light in `from` primaries to linear light in `to` primaries, both viewed under D65. */+export function gamutConversion(from: CameraGamutId | "rec709", to: CameraGamutId | "rec709"): Matrix3 {+ const f = GAMUTS[from];+ const t = GAMUTS[to];+ return mul3(inv3(rgbToXyz({ ...t, white: D65 })), mul3(adaptation(f.white, D65), rgbToXyz(f)));+}++const conversionCache = new Map<string, Matrix3>();+function cachedConversion(from: CameraGamutId, to: "rec709" | "bt2020"): Matrix3 {+ const key = `${from}>${to}`;+ let m = conversionCache.get(key);+ if (!m) {+ m = gamutConversion(from, to);+ conversionCache.set(key, m);+ }+ return m;+}++/** Linear camera gamut to linear Rec.709 primaries. */+export function cameraGamutToBt709(gamut: CameraGamutId): Matrix3 {+ return cachedConversion(gamut, "rec709");+}++/** Linear camera gamut to linear Rec.2020 primaries (HDR working space). */+export function cameraGamutToBt2020(gamut: CameraGamutId): Matrix3 {+ return cachedConversion(gamut, "bt2020");+}++// -- registry --------------------------------------------------------------------------------------------------++export interface CameraLogDef {+ readonly id: CameraLogId;+ readonly maker: string;+ /** Picker label, e.g. "Sony S-Log3 / S-Gamut3.Cine". */+ readonly label: string;+ readonly gamut: CameraGamutId;+ /** Shader transfer id (hdr-working's HdrTransferId space; 0..3 are sRGB, PQ, HLG, linear). */+ readonly shaderId: number;+ /** Published 18% grey signal (0..1), the anchor the tests check. */+ readonly grey18: number;+ decode(signal: number): number;+ encode(linear: number): number;+}++export const CAMERA_LOGS: readonly CameraLogDef[] = [+ { id: "slog3", maker: "Sony", label: "Sony S-Log3 / S-Gamut3.Cine", gamut: "sgamut3cine", shaderId: 4, grey18: 420 / 1023, decode: slog3Decode, encode: slog3Encode },+ { id: "vlog", maker: "Panasonic", label: "Panasonic V-Log / V-Gamut", gamut: "vgamut", shaderId: 5, grey18: 0.423311, decode: vlogDecode, encode: vlogEncode },+ { id: "logc3", maker: "ARRI", label: "ARRI LogC3 (EI 800) / AWG3", gamut: "awg3", shaderId: 6, grey18: 0.391007, decode: logc3Decode, encode: logc3Encode },+ { id: "logc4", maker: "ARRI", label: "ARRI LogC4 / AWG4", gamut: "awg4", shaderId: 7, grey18: 0.278396, decode: logc4Decode, encode: logc4Encode },+ { id: "clog3", maker: "Canon", label: "Canon C-Log3 / Cinema Gamut", gamut: "cinemagamut", shaderId: 8, grey18: 0.313437, decode: clog3Decode, encode: clog3Encode },+ { id: "nlog", maker: "Nikon", label: "Nikon N-Log / Rec.2020", gamut: "bt2020", shaderId: 9, grey18: 0.363667, decode: nlogDecode, encode: nlogEncode },+ { id: "flog", maker: "Fujifilm", label: "Fujifilm F-Log / Rec.2020", gamut: "bt2020", shaderId: 10, grey18: 0.459319, decode: makeFujiDecode(FLOG), encode: makeFujiEncode(FLOG) },+ { id: "flog2", maker: "Fujifilm", label: "Fujifilm F-Log2 / Rec.2020", gamut: "bt2020", shaderId: 11, grey18: 0.391007, decode: makeFujiDecode(FLOG2), encode: makeFujiEncode(FLOG2) },+ { id: "bmdfilm5", maker: "Blackmagic", label: "Blackmagic Film Gen5 / Wide Gamut", gamut: "bmdwg", shaderId: 12, grey18: 0.383566, decode: bmdDecode, encode: bmdEncode },+];++const BY_ID = new Map<string, CameraLogDef>(CAMERA_LOGS.map((d) => [d.id, d]));++export function isCameraLogId(value: unknown): value is CameraLogId {+ return typeof value === "string" && BY_ID.has(value);+}++export function cameraLogDef(id: CameraLogId): CameraLogDef {+ return BY_ID.get(id)!;+}++/** Log signal 0..1 to scene-linear (0.18 = 18% grey). */+export function decodeCameraLog(signal: number, id: CameraLogId): number {+ return BY_ID.get(id)!.decode(signal);+}++/** Scene-linear to log signal; the inverse of `decodeCameraLog`. */+export function encodeCameraLog(linear: number, id: CameraLogId): number {+ return BY_ID.get(id)!.encode(linear);+}++/** Camera log whose shader transfer id this is, or undefined for the sRGB / PQ / HLG / linear ids. */+export function cameraLogForShaderId(shaderId: number): CameraLogDef | undefined {+ return CAMERA_LOGS.find((d) => d.shaderId === shaderId);+}++/**+ * GLSL ES 3.00 for the shader decode: `decodeCameraLog(vec3 c, int id)` returns+ * scene-linear in the camera gamut for transfer ids 4..12.+ */+export function cameraLogGlsl(): string {+ const fns = CAMERA_LOGS.map((d) => `float camLog_${d.id}(float y) { return ${GLSL_EXPR[d.id]}; }`).join("\n");+ const cases = CAMERA_LOGS.map((d) => ` if (id == ${d.shaderId}) return vec3(camLog_${d.id}(c.r), camLog_${d.id}(c.g), camLog_${d.id}(c.b));`).join("\n");+ return `${fns}+vec3 decodeCameraLog(vec3 c, int id) {+ c = clamp(c, 0.0, 1.0);+${cases}+ return c;+}+`;+}diff --git a/packages/core/src/color/hdr-working.ts b/packages/core/src/color/hdr-working.tsindex 5872f1cb..c8b8a050 100644--- a/packages/core/src/color/hdr-working.ts+++ b/packages/core/src/color/hdr-working.ts@@ -31,6 +31,7 @@ import { applyHdrEffects, type HdrLayerEffect } from "./hdr-effects";import { applyColorWheelsToRgb } from "../video/lumetri-pipeline";import { BT2020_TO_BT709, hlgInverseOetf, P3_TO_BT709, TONE_MAP_KNEE } from "./input-transform";import type { SourceColorSpace, SourceTransfer } from "./source-color";+import { CAMERA_LOGS, cameraGamutToBt2020, cameraLogForShaderId, decodeCameraLog, type CameraGamutId } from "./camera-log";/*** Scene-referred HDR working mode.@@ -84,7 +85,8 @@ export function isHdrWorkingMode(// -- source decode ---------------------------------------------------------------------------------------------export type HdrTransferId = 0 | 1 | 2 | 3;+/** 0 sRGB, 1 PQ, 2 HLG, 3 linear, 4..12 the camera log curves (`CAMERA_LOGS[n].shaderId`). */+export type HdrTransferId = number;export const HDR_TRANSFER_SRGB: HdrTransferId = 0;export const HDR_TRANSFER_PQ: HdrTransferId = 1;export const HDR_TRANSFER_HLG: HdrTransferId = 2;@@ -107,14 +109,29 @@ function transferId(transfer: SourceTransfer): HdrTransferId {case "linear":return HDR_TRANSFER_LINEAR;default:- return HDR_TRANSFER_SRGB;+ return CAMERA_LOGS.find((d) => d.id === transfer)?.shaderId ?? HDR_TRANSFER_SRGB;+ }+}++/** Source primaries to BT.2020 in linear light. */+function primariesToBt2020(primaries: SourceColorSpace["primaries"]): Matrix3 {+ switch (primaries) {+ case "bt2020":+ return IDENTITY;+ case "p3":+ return P3_TO_BT2020;+ case "bt709":+ case "bt601":+ return BT709_TO_BT2020;+ default:+ return cameraGamutToBt2020(primaries as CameraGamutId);}}/** Decode description of footage. `null` (untagged / plain SDR) reads the canvas as sRGB Rec.709. */export function hdrSourceDecode(space: SourceColorSpace | null | undefined): HdrSourceDecode {if (!space) return SDR_DECODE;- const toBt2020 = space.primaries === "bt2020" ? IDENTITY : space.primaries === "p3" ? P3_TO_BT2020 : BT709_TO_BT2020;+ const toBt2020 = primariesToBt2020(space.primaries);return { key: `${space.primaries}/${space.transfer}`, transfer: transferId(space.transfer), toBt2020 };}@@ -125,6 +142,8 @@ export const HDR_OVERLAY_DECODE: HdrSourceDecode = SDR_DECODE;/** Signal 0..1 to scene-linear where 1.0 = SDR reference white (no clipping above 1). */export function decodeToWorkingLinear(signal: number, transfer: HdrTransferId): number {+ const log = cameraLogForShaderId(transfer);+ if (log) return decodeCameraLog(Math.max(0, Math.min(1, signal)), log.id);switch (transfer) {case HDR_TRANSFER_PQ:return pqDecodeToNits(signal) / PQ_SDR_WHITE_NITS;diff --git a/packages/core/src/color/input-transform.ts b/packages/core/src/color/input-transform.tsindex b5076334..a5aec995 100644--- a/packages/core/src/color/input-transform.ts+++ b/packages/core/src/color/input-transform.ts@@ -1,5 +1,6 @@import { BT709_TO_BT2020, HLG_SDR_WHITE_SCENE, PQ_SDR_WHITE_NITS, linearToSrgb, pqDecodeToNits, srgbToLinear } from "../export/color-output";-import { needsInputTransform, type SourceColorSpace } from "./source-color";+import { cameraGamutToBt709, decodeCameraLog, type CameraGamutId } from "./camera-log";+import { isCameraLogTransfer, needsInputTransform, type SourceColorSpace } from "./source-color";/*** Input transform: footage in its own colour space -> the editor's working@@ -71,6 +72,7 @@ export function hlgInverseOetf(signal: number): number {/** Signal 0..1 to linear light where 1.0 = SDR reference white. */export function decodeSourceTransfer(signal: number, transfer: SourceColorSpace["transfer"]): number {+ if (isCameraLogTransfer(transfer)) return decodeCameraLog(signal, transfer);switch (transfer) {case "pq":return pqDecodeToNits(signal) / PQ_SDR_WHITE_NITS;@@ -100,6 +102,20 @@ export interface InputTransform {readonly decodeLut: Float32Array;}+function primariesToBt709(primaries: SourceColorSpace["primaries"]): Matrix3 | null {+ switch (primaries) {+ case "bt2020":+ return BT2020_TO_BT709;+ case "p3":+ return P3_TO_BT709;+ case "bt709":+ case "bt601":+ return null;+ default:+ return cameraGamutToBt709(primaries as CameraGamutId);+ }+}+export function inputTransformKey(source: SourceColorSpace): string {return `${source.primaries}/${source.transfer}`;}@@ -112,8 +128,9 @@ export function createInputTransform(source: SourceColorSpace): InputTransform |return {source,key: inputTransformKey(source),- toneMap: source.transfer === "pq" || source.transfer === "hlg",- matrix: source.primaries === "bt2020" ? BT2020_TO_BT709 : source.primaries === "p3" ? P3_TO_BT709 : null,+ // Camera log scene light goes through the same shoulder: log footage holds highlights far above white.+ toneMap: source.transfer === "pq" || source.transfer === "hlg" || isCameraLogTransfer(source.transfer),+ matrix: primariesToBt709(source.primaries),decodeLut,};}diff --git a/packages/core/src/color/source-color.ts b/packages/core/src/color/source-color.tsindex 9affdccf..9f7d7dcc 100644--- a/packages/core/src/color/source-color.ts+++ b/packages/core/src/color/source-color.ts@@ -8,9 +8,10 @@*/import type { RawOutputColorSpace } from "../raw/color";+import { CAMERA_LOGS, type CameraGamutId, type CameraLogId } from "./camera-log";-export type SourcePrimaries = "bt709" | "bt2020" | "p3" | "bt601";-export type SourceTransfer = "srgb" | "bt709" | "pq" | "hlg" | "linear";+export type SourcePrimaries = "bt709" | "bt2020" | "p3" | "bt601" | Exclude<CameraGamutId, "bt2020">;+export type SourceTransfer = "srgb" | "bt709" | "pq" | "hlg" | "linear" | CameraLogId;export type SourceMatrix = "bt709" | "bt2020-ncl" | "bt601" | "rgb";export interface SourceColorSpace {@@ -29,13 +30,20 @@ export const DEFAULT_SOURCE_COLOR: SourceColorSpace = {};/** "Interpret footage" choices. `undefined` on the media item means "as tagged". */-export type FootageColorPreset = "rec709" | "srgb" | "rec2020" | "p3" | "hdr10-pq" | "hlg";+export type StandardFootageColorPreset = "rec709" | "srgb" | "rec2020" | "p3" | "hdr10-pq" | "hlg";+/** Camera log input presets: "log-" + the curve id ("log-slog3", "log-logc4", ...). */+export type CameraFootageColorPreset = `log-${CameraLogId}`;+export type FootageColorPreset = StandardFootageColorPreset | CameraFootageColorPreset;-export const FOOTAGE_COLOR_PRESETS: ReadonlyArray<{+export interface FootageColorPresetDef {readonly id: FootageColorPreset;readonly label: string;readonly space: SourceColorSpace;-}> = [+ /** Set on camera log presets: the picker groups them under "Camera input". */+ readonly camera?: { readonly logId: CameraLogId; readonly maker: string };+}++const STANDARD_FOOTAGE_COLOR_PRESETS: ReadonlyArray<FootageColorPresetDef> = [{ id: "rec709", label: "Rec.709 (SDR)", space: { primaries: "bt709", transfer: "bt709", matrix: "bt709", fullRange: false } },{ id: "srgb", label: "sRGB (full range)", space: { primaries: "bt709", transfer: "srgb", matrix: "rgb", fullRange: true } },{ id: "rec2020", label: "Rec.2020 (SDR)", space: { primaries: "bt2020", transfer: "bt709", matrix: "bt2020-ncl", fullRange: false } },@@ -44,6 +52,37 @@ export const FOOTAGE_COLOR_PRESETS: ReadonlyArray<{{ id: "hlg", label: "Rec.2020 HLG", space: { primaries: "bt2020", transfer: "hlg", matrix: "bt2020-ncl", fullRange: false } },];+/**+ * Camera log presets: the signal is the camera's log curve in its wide gamut (RGB after the decoder's YCbCr+ * conversion, so the matrix is "rgb" and the range is whatever the decoder delivered).+ */+export const CAMERA_FOOTAGE_COLOR_PRESETS: ReadonlyArray<FootageColorPresetDef> = CAMERA_LOGS.map((def) => ({+ id: `log-${def.id}` as CameraFootageColorPreset,+ label: def.label,+ space: {+ primaries: def.gamut,+ transfer: def.id,+ matrix: "rgb",+ fullRange: true,+ } satisfies SourceColorSpace,+ camera: { logId: def.id, maker: def.maker },+}));++export const FOOTAGE_COLOR_PRESETS: ReadonlyArray<FootageColorPresetDef> = [+ ...STANDARD_FOOTAGE_COLOR_PRESETS,+ ...CAMERA_FOOTAGE_COLOR_PRESETS,+];++/** True for the camera log transfers (S-Log3, V-Log, LogC3, ...). */+export function isCameraLogTransfer(transfer: SourceTransfer): transfer is CameraLogId {+ return CAMERA_LOGS.some((d) => d.id === transfer);+}++/** The camera log preset a media item is interpreted as, if any. */+export function cameraPresetOf(preset: FootageColorPreset | null | undefined): FootageColorPresetDef | undefined {+ return preset ? CAMERA_FOOTAGE_COLOR_PRESETS.find((p) => p.id === preset) : undefined;+}+export function isFootageColorPreset(value: unknown): value is FootageColorPreset {return typeof value === "string" && FOOTAGE_COLOR_PRESETS.some((p) => p.id === value);}@@ -123,7 +162,8 @@ export function needsInputTransform(space: SourceColorSpace): boolean {isHdrTransfer(space) ||space.primaries === "bt2020" ||space.primaries === "p3" ||- space.transfer === "linear"+ space.transfer === "linear" ||+ isCameraLogTransfer(space.transfer));}@@ -134,8 +174,10 @@ export function sourceColorEquals(a: SourceColorSpace, b: SourceColorSpace): boo/** Short label for the media info: "Rec.2020 / PQ / BT.2020nc / limited". */export function describeSourceColor(space: SourceColorSpace | null | undefined): string {if (!space) return "Rec.709 (untagged)";- const primaries = { bt709: "Rec.709", bt2020: "Rec.2020", p3: "P3", bt601: "BT.601" }[space.primaries];- const transfer = { srgb: "sRGB", bt709: "BT.709", pq: "PQ", hlg: "HLG", linear: "Linear" }[space.transfer];+ const camera = CAMERA_LOGS.find((d) => d.id === space.transfer);+ if (camera) return camera.label;+ const primaries = ({ bt709: "Rec.709", bt2020: "Rec.2020", p3: "P3", bt601: "BT.601" } as Record<string, string>)[space.primaries] ?? space.primaries;+ const transfer = ({ srgb: "sRGB", bt709: "BT.709", pq: "PQ", hlg: "HLG", linear: "Linear" } as Record<string, string>)[space.transfer] ?? space.transfer;const matrix = { bt709: "BT.709", "bt2020-ncl": "BT.2020nc", bt601: "BT.601", rgb: "RGB" }[space.matrix];return `${primaries} / ${transfer} / ${matrix} / ${space.fullRange ? "full" : "limited"}`;}diff --git a/packages/core/src/editing/clip-markers.test.ts b/packages/core/src/editing/clip-markers.test.tsnew file mode 100644index 00000000..bf11d8a7--- /dev/null+++ b/packages/core/src/editing/clip-markers.test.ts@@ -0,0 +1,190 @@+import { describe, expect, it } from "vitest";+import type { Clip, Marker } from "../types/timeline";+import { ActionExecutor } from "../actions/action-executor";+import type { Action } from "../types/actions";+import type { Project } from "../types/project";+import { buildProject } from "../interchange/__fixtures__/project";+import { exportTimeline, importTimeline } from "../interchange";+import {+ flattenClipMarkers,+ resolveClipMarkers,+ sourceTimeForTimelineMarker,+ sourceToTimelineTime,+ timelineToSourceTime,+} from "./clip-markers";+import { clipSourceTimeAt } from "./premiere-edits";++const mk = (id: string, time: number, extra: Partial<Marker> = {}): Marker => ({ id, time, label: id, color: "#f00", ...extra });++const clip = (over: Partial<Clip>): Clip =>+ ({+ id: "c",+ mediaId: "m",+ trackId: "t",+ startTime: 10,+ duration: 5,+ inPoint: 20,+ outPoint: 25,+ effects: [],+ audioEffects: [],+ keyframes: [],+ volume: 1,+ ...over,+ }) as unknown as Clip;++describe("source <-> timeline marker offset mapping", () => {+ it("maps with the in-point at normal speed", () => {+ const c = clip({});+ expect(sourceToTimelineTime(c, 22)).toBeCloseTo(12);+ expect(timelineToSourceTime(c, 12)).toBeCloseTo(22);+ });++ it("scales by speed (2x: 4 source seconds take 2 timeline seconds)", () => {+ const c = clip({ speed: 2, duration: 2.5, inPoint: 20, outPoint: 25 });+ expect(sourceToTimelineTime(c, 24)).toBeCloseTo(10 + 4 / 2);+ expect(timelineToSourceTime(c, 12)).toBeCloseTo(24);+ });++ it("slow motion stretches (0.5x)", () => {+ const c = clip({ speed: 0.5, duration: 10 });+ expect(sourceToTimelineTime(c, 21)).toBeCloseTo(10 + 1 / 0.5);+ });++ it("reverse plays the out point first", () => {+ const c = clip({ reversed: true });+ expect(sourceToTimelineTime(c, 25)).toBeCloseTo(10);+ expect(sourceToTimelineTime(c, 20)).toBeCloseTo(15);+ expect(sourceToTimelineTime(c, 23)).toBeCloseTo(12);+ });++ it("reverse and speed together", () => {+ const c = clip({ reversed: true, speed: 2, duration: 2.5 });+ expect(sourceToTimelineTime(c, 23)).toBeCloseTo(10 + 2 / 2);+ expect(timelineToSourceTime(c, 11)).toBeCloseTo(23);+ });++ it("agrees with the playback engine's source time (speed, reverse, both)", () => {+ for (const over of [{}, { speed: 2, duration: 2.5 }, { reversed: true }, { reversed: true, speed: 0.5, duration: 10 }]) {+ const c = clip(over);+ for (const f of [0, 0.3, 0.5, 0.9]) {+ const t = c.startTime + c.duration * f;+ expect(timelineToSourceTime(c, t)).toBeCloseTo(clipSourceTimeAt(c, t), 6);+ }+ }+ });+});++describe("resolveClipMarkers", () => {+ it("hides markers outside the trimmed range and merges master with clip markers", () => {+ const c = clip({ markers: [mk("own", 24)] });+ const out = resolveClipMarkers(c, { markers: [mk("m-in", 21), mk("m-before", 5), mk("m-after", 40)] });+ expect(out.map((r) => [r.marker.id, r.scope])).toEqual([+ ["m-in", "master"],+ ["own", "clip"],+ ]);+ expect(out.map((r) => r.timelineTime)).toEqual([11, 14]);+ });++ it("clips a range marker to the in/out range and scales its length by speed", () => {+ const c = clip({ speed: 2, duration: 2.5 });+ const [r] = resolveClipMarkers(c, { markers: [mk("r", 18, { duration: 6 })] });+ // visible source 20..24 -> 2 timeline seconds starting at the clip start+ expect(r.timelineTime).toBeCloseTo(10);+ expect(r.timelineDuration).toBeCloseTo(2);+ });++ it("puts a reversed range marker at its earliest timeline time", () => {+ const c = clip({ reversed: true });+ const [r] = resolveClipMarkers(c, { markers: [mk("r", 21, { duration: 2 })] });+ expect(r.timelineTime).toBeCloseTo(12); // source 23 plays at 12, source 21 at 14+ expect(r.timelineDuration).toBeCloseTo(2);+ });++ it("shows a master marker on every instance at its own offset", () => {+ const media = { markers: [mk("shared", 22)] };+ const a = clip({ id: "a", startTime: 0 });+ const b = clip({ id: "b", startTime: 100, speed: 2, duration: 2.5 });+ const flat = flattenClipMarkers([a, b], () => media);+ expect(flat.map((r) => [r.clipId, r.timelineTime])).toEqual([+ ["a", 2],+ ["b", 101],+ ]);+ });++ it("places a timeline marker at the right source time, null off the clip", () => {+ const c = clip({ speed: 2, duration: 2.5 });+ expect(sourceTimeForTimelineMarker(c, 11)).toBeCloseTo(22);+ expect(sourceTimeForTimelineMarker(c, 50)).toBeNull();+ });+});++const act = (type: string, params: Record<string, unknown>): Action =>+ ({ id: `a${Math.random()}`, type, timestamp: Date.now(), params }) as unknown as Action;++describe("clipmarker/set action", () => {+ it("sets, undoes and redoes clip markers and master markers", async () => {+ const project = buildProject(30) as Project;+ const ex = new ActionExecutor();+ const clipId = project.timeline.tracks[0].clips[0].id;+ const mediaId = project.timeline.tracks[0].clips[0].mediaId;++ expect((await ex.execute(act("clipmarker/set", { clipId, markers: [mk("x", 2)] }), project)).success).toBe(true);+ expect(project.timeline.tracks[0].clips[0].markers).toHaveLength(1);+ expect((await ex.execute(act("clipmarker/set", { mediaId, markers: [mk("y", 3)] }), project)).success).toBe(true);+ expect(project.mediaLibrary.items.find((i) => i.id === mediaId)?.markers).toHaveLength(1);++ await ex.undo(project);+ expect(project.mediaLibrary.items.find((i) => i.id === mediaId)?.markers).toBeUndefined();+ await ex.undo(project);+ expect(project.timeline.tracks[0].clips[0].markers ?? []).toHaveLength(0);+ await ex.redo(project);+ expect(project.timeline.tracks[0].clips[0].markers?.[0].id).toBe("x");+ });++ it("rejects missing targets and bad markers", async () => {+ const project = buildProject(30) as Project;+ const ex = new ActionExecutor();+ expect((await ex.execute(act("clipmarker/set", { clipId: "nope", markers: [] }), project)).success).toBe(false);+ expect((await ex.execute(act("clipmarker/set", { markers: [] }), project)).success).toBe(false);+ const clipId = project.timeline.tracks[0].clips[0].id;+ expect((await ex.execute(act("clipmarker/set", { clipId, markers: [{ id: "q", time: -1, label: "", color: "" }] }), project)).success).toBe(false);+ });+});++const mainTrack = (p: Project) => p.timeline.tracks.find((t) => t.id === "t-main")!;++describe("XMEML clip markers", () => {+ it("writes clip and master markers in the clipitem and reads them back in source time", () => {+ const project = buildProject(30) as Project;+ const first = mainTrack(project).clips[0]; // A: source 1s..3s+ const mediaId = first.mediaId;+ (project.mediaLibrary as { items: unknown }).items = project.mediaLibrary.items.map((i) =>+ i.id === mediaId ? { ...i, markers: [mk("master", 2, { comment: "from source" })] } : i,+ );+ (mainTrack(project) as { clips: unknown }).clips = mainTrack(project).clips.map((c) =>+ c.id === first.id ? { ...c, markers: [mk("own", 1.5, { duration: 1 })] } : c,+ );+ const text = exportTimeline(project, "xmeml").files[0].content;+ expect(text).toContain("<name>master</name>");+ expect(text).toContain("<name>own</name>");++ let n = 0;+ const imported = importTimeline(text, { mediaItems: project.mediaLibrary.items, makeId: () => `i${++n}` });+ const clips = imported.tracks.flatMap((t) => t.clips).filter((c) => c.markers?.length);+ const labels = clips.flatMap((c) => (c.markers ?? []).map((m) => [m.label, Math.round(m.time * 100) / 100, m.duration ? Math.round(m.duration * 100) / 100 : 0]));+ expect(labels).toContainEqual(["master", 2, 0]);+ expect(labels).toContainEqual(["own", 1.5, 1]);+ });++ it("omits markers outside the clip's range and honours includeMarkers:false", () => {+ const project = buildProject(30) as Project;+ const first = mainTrack(project).clips[0];+ (mainTrack(project) as { clips: unknown }).clips = mainTrack(project).clips.map((c) =>+ c.id === first.id ? { ...c, markers: [mk("outside", 500)] } : c,+ );+ expect(exportTimeline(project, "xmeml").files[0].content).not.toContain("<name>outside</name>");+ const withIn = mainTrack(project).clips.map((c) => (c.id === first.id ? { ...c, markers: [mk("inside", 1.2)] } : c));+ (mainTrack(project) as { clips: unknown }).clips = withIn;+ expect(exportTimeline(project, "xmeml", { includeMarkers: false }).files[0].content).not.toContain("<name>inside</name>");+ });+});diff --git a/packages/core/src/editing/clip-markers.ts b/packages/core/src/editing/clip-markers.tsnew file mode 100644index 00000000..56bbc25f--- /dev/null+++ b/packages/core/src/editing/clip-markers.ts@@ -0,0 +1,92 @@+import type { Clip, Marker } from "../types/timeline";+import type { MediaItem } from "../types/project";++/**+ * Clip markers and master-clip markers (Premiere). Both store `time` in SOURCE media seconds,+ * so they stay on the same frame of the footage through trims, speed changes and reverse.+ * Master-clip markers live on the media item and show on every timeline instance; clip markers+ * live on one timeline instance. These helpers map between source time and timeline time.+ */++const EPS = 1e-6;++export type ClipMarkerScope = "master" | "clip";++export interface ResolvedClipMarker {+ readonly marker: Marker;+ readonly scope: ClipMarkerScope;+ /** Timeline seconds of the marker's start (for a reversed clip: where its source start plays). */+ readonly timelineTime: number;+ /** Timeline length of a range marker (0 for a point marker), speed applied. */+ readonly timelineDuration: number;+}++const speedOf = (clip: Pick<Clip, "speed">): number => {+ const s = Math.abs(clip.speed ?? 1);+ return s > 0 ? s : 1;+};++const isReversed = (clip: Pick<Clip, "speed" | "reversed">): boolean => clip.reversed === true || (clip.speed ?? 1) < 0;++/** Timeline time at which `clip` plays source time `sourceTime` (not clamped to the clip). */+export function sourceToTimelineTime(clip: Clip, sourceTime: number): number {+ const s = speedOf(clip);+ const offset = isReversed(clip) ? clip.outPoint - sourceTime : sourceTime - clip.inPoint;+ return clip.startTime + offset / s;+}++/** Source time that `clip` plays at timeline `time` (constant speed; not clamped to the clip). */+export function timelineToSourceTime(clip: Clip, time: number): number {+ const s = speedOf(clip);+ const local = (time - clip.startTime) * s;+ return isReversed(clip) ? clip.outPoint - local : clip.inPoint + local;+}++/** True when source time lies inside the clip's in..out range. */+export function sourceTimeInClip(clip: Clip, sourceTime: number): boolean {+ return sourceTime >= clip.inPoint - EPS && sourceTime <= clip.outPoint + EPS;+}++/**+ * Markers of one timeline instance: the media's master markers plus the clip's own, mapped to+ * timeline time and filtered to the visible source range. A range marker is clipped to it.+ * Sorted by timeline time.+ */+export function resolveClipMarkers(+ clip: Clip,+ media?: Pick<MediaItem, "markers"> | null,+): ResolvedClipMarker[] {+ const out: ResolvedClipMarker[] = [];+ const add = (markers: readonly Marker[] | undefined, scope: ClipMarkerScope): void => {+ for (const marker of markers ?? []) {+ const srcStart = marker.time;+ const srcEnd = srcStart + (marker.duration ?? 0);+ if (srcEnd < clip.inPoint - EPS || srcStart > clip.outPoint + EPS) continue;+ const a = sourceToTimelineTime(clip, Math.max(srcStart, clip.inPoint));+ const b = sourceToTimelineTime(clip, Math.min(srcEnd, clip.outPoint));+ const start = Math.min(a, b);+ out.push({ marker, scope, timelineTime: start, timelineDuration: Math.abs(b - a) });+ }+ };+ add(media?.markers, "master");+ add(clip.markers, "clip");+ return out.sort((x, y) => x.timelineTime - y.timelineTime);+}++/** A marker placed at timeline `time` on `clip`, as a source-time marker draft; null when off the clip. */+export function sourceTimeForTimelineMarker(clip: Clip, time: number): number | null {+ if (time < clip.startTime - EPS || time > clip.startTime + clip.duration + EPS) return null;+ const src = timelineToSourceTime(clip, time);+ return Math.min(clip.outPoint, Math.max(clip.inPoint, src));+}++/** Every marker visible on timeline instances of `clips`, as timeline-time `Marker`s (for lists and navigation). */+export function flattenClipMarkers(+ clips: readonly Clip[],+ mediaFor: (mediaId: string) => Pick<MediaItem, "markers"> | undefined,+): Array<ResolvedClipMarker & { readonly clipId: string }> {+ const out: Array<ResolvedClipMarker & { readonly clipId: string }> = [];+ for (const clip of clips)+ for (const r of resolveClipMarkers(clip, mediaFor(clip.mediaId))) out.push({ ...r, clipId: clip.id });+ return out.sort((a, b) => a.timelineTime - b.timelineTime);+}diff --git a/packages/core/src/editing/clip-speed-edit.test.ts b/packages/core/src/editing/clip-speed-edit.test.tsnew file mode 100644index 00000000..05217ad4--- /dev/null+++ b/packages/core/src/editing/clip-speed-edit.test.ts@@ -0,0 +1,193 @@+import { describe, expect, it } from "vitest";+import type { Clip, Project, Track } from "../types";+import { planClipSpeedEdit, prepareMultiRateStretch } from "./clip-speed-edit";+import { SyncLockBlockedError } from "./sync-lock";+import {+ applyTimelineToolEdits,+ invertTimelineToolEdits,+ validateTimelineToolEdits,+ type TimelineToolPlan,+} from "./timeline-tool-edit";++const transform = {+ position: { x: 0, y: 0 },+ scale: { x: 1, y: 1 },+ anchor: { x: 0.5, y: 0.5 },+ rotation: 0,+ opacity: 1,+};+const clip = (+ id: string,+ trackId: string,+ startTime: number,+ duration: number,+ extra: Partial<Clip> = {},+): Clip => ({+ id,+ mediaId: "media",+ trackId,+ startTime,+ duration,+ inPoint: 0,+ outPoint: duration,+ effects: [],+ audioEffects: [],+ transform,+ volume: 1,+ keyframes: [],+ ...extra,+});+const track = (+ id: string,+ type: Track["type"],+ clips: Clip[],+ extra: Partial<Track> = {},+): Track => ({+ id,+ name: id.toUpperCase(),+ type,+ clips,+ transitions: [],+ locked: false,+ hidden: false,+ muted: false,+ solo: false,+ ...extra,+});+const project = (tracks: Track[]): Project =>+ ({+ id: "p",+ name: "p",+ createdAt: 0,+ modifiedAt: 0,+ settings: { width: 640, height: 360, frameRate: 30, sampleRate: 48000, channels: 2 },+ mediaLibrary: {+ items: [+ {+ id: "media",+ name: "Media.mp4",+ type: "video",+ fileHandle: null,+ blob: null,+ thumbnailUrl: null,+ waveformData: null,+ metadata: {+ duration: 60,+ width: 640,+ height: 360,+ frameRate: 30,+ sampleRate: 48000,+ channels: 2,+ codec: "h264",+ fileSize: 1,+ hasAudio: true,+ },+ },+ ],+ },+ timeline: { duration: 40, markers: [], subtitles: [], tracks },+ }) as unknown as Project;++const run = (p: Project, plan: TimelineToolPlan) => {+ validateTimelineToolEdits(p, plan.edits);+ return applyTimelineToolEdits(p, plan.edits);+};+const clipsOf = (p: Project, trackId: string) =>+ [...p.timeline.tracks.find((t) => t.id === trackId)!.clips].sort(+ (a, b) => a.startTime - b.startTime,+ );+const spans = (p: Project, trackId: string) =>+ clipsOf(p, trackId).map((c) => [+c.startTime.toFixed(6), +(c.startTime + c.duration).toFixed(6)]);++describe("planClipSpeedEdit", () => {+ const two = () => project([track("v1", "video", [clip("a", "v1", 0, 4), clip("b", "v1", 4, 4), clip("c", "v1", 8, 2)])]);++ it("ripples trailing clips when several clips are sped up, as one plan", () => {+ const p = two();+ const plan = planClipSpeedEdit(p, ["a", "b"], { speed: 2 }, { ripple: true }, "op");+ const next = run(p, plan);+ expect(spans(next, "v1")).toEqual([[0, 2], [2, 4], [4, 6]]);+ expect(clipsOf(next, "v1")[0].speed).toBe(2);+ expect(clipsOf(next, "v1")[2].speed).toBeUndefined();+ // Undo restores everything.+ expect(spans(applyTimelineToolEdits(next, invertTimelineToolEdits(plan.edits)), "v1")).toEqual([[0, 4], [4, 8], [8, 10]]);+ });++ it("without ripple leaves a gap and blocks overlapping growth", () => {+ const p = two();+ expect(spans(run(p, planClipSpeedEdit(p, ["a"], { speed: 2 }, { ripple: false }, "op")), "v1")).toEqual([[0, 2], [4, 8], [8, 10]]);+ expect(() => planClipSpeedEdit(p, ["a"], { speed: 0.5 }, { ripple: false }, "op")).toThrow(/overlap/);+ // Two adjacent selected clips slowed together still collide without ripple.+ expect(() => planClipSpeedEdit(p, ["a", "b"], { speed: 0.5 }, { ripple: false }, "op")).toThrow(/overlap/);+ expect(spans(run(p, planClipSpeedEdit(p, ["a"], { speed: 0.5 }, { ripple: true }, "op")), "v1")).toEqual([[0, 8], [8, 12], [12, 14]]);+ });++ it("scales a multi-selection duration and clamps the rate", () => {+ const p = two();+ const next = run(p, planClipSpeedEdit(p, ["a", "b"], { durationScale: 0.5 }, { ripple: true }, "op"));+ expect(spans(next, "v1")).toEqual([[0, 2], [2, 4], [4, 6]]);+ const slow = run(p, planClipSpeedEdit(p, ["c"], { speed: 0.01 }, { ripple: true }, "op"));+ expect(clipsOf(slow, "v1")[2].speed).toBeCloseTo(0.1);+ });++ it("moves linked audio with the video and shifts sync-locked tracks", () => {+ const p = project([+ track("v1", "video", [clip("v", "v1", 0, 4), clip("v2", "v1", 4, 4)]),+ track("a1", "audio", [clip("au", "a1", 0, 4), clip("au2", "a1", 4, 4)]),+ track("v2t", "video", [clip("x", "v2t", 6, 2)], { syncLock: true }),+ ]);+ const next = run(p, planClipSpeedEdit(p, ["v", "au"], { speed: 2, maintainPitch: false }, { ripple: false }, "op"));+ expect(spans(next, "a1")).toEqual([[0, 2], [4, 8]]);+ const rippled = run(p, planClipSpeedEdit(p, ["v", "au"], { speed: 2 }, { ripple: true }, "op"));+ expect(spans(rippled, "v1")).toEqual([[0, 2], [2, 6]]);+ expect(spans(rippled, "a1")).toEqual([[0, 2], [2, 6]]);+ // The sync-locked track holds media inside the span that would close.+ const locked = project([+ track("v1", "video", [clip("v", "v1", 0, 4), clip("v2", "v1", 4, 4)]),+ track("s", "video", [clip("x", "s", 3, 1)], { syncLock: true }),+ ]);+ expect(() => planClipSpeedEdit(locked, ["v"], { speed: 2 }, { ripple: true }, "op")).toThrow(SyncLockBlockedError);+ });++ it("applies reverse and pitch without moving clips, and refuses locked tracks and ramps", () => {+ const p = two();+ const next = run(p, planClipSpeedEdit(p, ["a", "b"], { reversed: true, maintainPitch: false }, { ripple: true }, "op"));+ expect(spans(next, "v1")).toEqual([[0, 4], [4, 8], [8, 10]]);+ expect(clipsOf(next, "v1")[1].reversed).toBe(true);+ expect(clipsOf(next, "v1")[1].pitchCorrection).toBe(false);+ expect(planClipSpeedEdit(p, ["a"], { speed: 1 }, { ripple: true }, "op").edits).toHaveLength(0);+ const locked = project([track("v1", "video", [clip("a", "v1", 0, 4)], { locked: true })]);+ expect(() => planClipSpeedEdit(locked, ["a"], { speed: 2 }, { ripple: true }, "op")).toThrow(/Unlock/);+ const ramp = project([track("v1", "video", [clip("a", "v1", 0, 4, { freezeFrames: [{ id: "f", time: 1, duration: 1 }] as never })])]);+ expect(() => planClipSpeedEdit(ramp, ["a"], { speed: 2 }, { ripple: true }, "op")).toThrow(/ramps/);+ });+});++describe("prepareMultiRateStretch", () => {+ it("scales every selected clip by the primary's drag and ripples the rest", () => {+ const p = project([track("v1", "video", [clip("a", "v1", 0, 4), clip("b", "v1", 4, 4), clip("c", "v1", 8, 2)])]);+ const stretch = prepareMultiRateStretch(p, { itemId: "a", clipIds: ["a", "b"], edge: "right" });+ expect(stretch.preview(-2).duration).toBeCloseTo(2);+ const next = run(p, stretch.plan(-2, "op"));+ expect(spans(next, "v1")).toEqual([[0, 2], [2, 4], [4, 6]]);+ expect(clipsOf(next, "v1")[1].speed).toBeCloseTo(2);+ // Bounded by the 0.1x floor.+ expect(stretch.preview(1000).speed).toBeCloseTo(0.1);+ });++ it("previews a ghost for every other stretched clip", () => {+ const p = project([track("v1", "video", [clip("a", "v1", 0, 4), clip("b", "v1", 4, 4), clip("c", "v1", 8, 2)])]);+ const stretch = prepareMultiRateStretch(p, { itemId: "a", clipIds: ["a", "b"], edge: "right" });+ const ghost = stretch.preview(-2);+ expect(ghost.neighbors).toEqual([{ trackId: "v1", startTime: 4, duration: 2 }]);+ });++ it("without ripple leaves trailing clips alone and cannot grow into a neighbour", () => {+ const p = project([track("v1", "video", [clip("a", "v1", 0, 4), clip("b", "v1", 4, 4), clip("c", "v1", 12, 2)])]);+ const stretch = prepareMultiRateStretch(p, { itemId: "a", clipIds: ["a", "b"], edge: "right", ripple: false });+ // a touches b, so the scale is capped at 1 and growing does nothing.+ expect(stretch.preview(3).duration).toBeCloseTo(4);+ const next = run(p, stretch.plan(-2, "op"));+ expect(spans(next, "v1")).toEqual([[0, 2], [4, 6], [12, 14]]);+ });+});diff --git a/packages/core/src/editing/clip-speed-edit.ts b/packages/core/src/editing/clip-speed-edit.tsnew file mode 100644index 00000000..702c8aa0--- /dev/null+++ b/packages/core/src/editing/clip-speed-edit.ts@@ -0,0 +1,279 @@+import type { Project } from "../types/project";+import type { Clip } from "../types/timeline";+import { SPEED_MAX, SPEED_MIN } from "../video/speed-engine";+import {+ allTracksRipple,+ diffPlan,+ openTimelineGap,+ pruneTransitions,+ removeTimelineSpan,+ shiftAfter,+ splitAt,+} from "./premiere-edits";+import { assertRangeEmptyOnTracks, syncFollowerTrackIds } from "./sync-lock";+import { resizeKeys, type Item, type TimelineToolPlan, type TimelineToolPreview } from "./timeline-tool-edit";++/**+ * Speed/Duration for several clips at once (Premiere Clip > Speed/Duration).+ *+ * One planner covers the Speed/Duration dialog, the Rate Stretch tool on a+ * multi-selection and "Ripple Edit, Shifting Trailing Clips". With ripple on,+ * every clip that gets longer or shorter moves its trailing material on its+ * own track; unlocked sync-locked tracks open (or close) the same span, and+ * shrinking is blocked when a sync-locked track holds media inside the span it+ * would close, exactly like a ripple delete. Linked audio is expected in+ * `clipIds` (the caller expands link groups). The result is one plan, so one+ * undo step.+ */+const EPS = 1e-6;+const MIN_DURATION = 1e-3;++export interface ClipSpeedEdit {+ /** Absolute playback rate for every clip. */+ speed?: number;+ /** Absolute timeline duration for every clip (seconds). */+ duration?: number;+ /** Multiplies every clip's current duration (rate stretch of a selection). */+ durationScale?: number;+ reversed?: boolean;+ /** Maintain audio pitch while the rate changes. */+ maintainPitch?: boolean;+}+export interface ClipSpeedOptions {+ /** Ripple Edit, Shifting Trailing Clips. */+ ripple: boolean;+}++export const clampSpeed = (value: number): number =>+ Math.min(SPEED_MAX, Math.max(SPEED_MIN, value));++/** The rate a clip would get from `edit`, or null when the edit leaves it alone. */+export function resolveClipRate(clip: Clip, edit: ClipSpeedEdit): number | null {+ const span = clip.outPoint - clip.inPoint;+ if (!(span > EPS)) return null;+ if (edit.speed != null) return clampSpeed(edit.speed);+ if (edit.duration != null) return clampSpeed(span / Math.max(MIN_DURATION, edit.duration));+ if (edit.durationScale != null)+ return clampSpeed(span / Math.max(MIN_DURATION, clip.duration * edit.durationScale));+ return null;+}++interface Change {+ trackId: string;+ before: Clip;+ after: Clip;+ delta: number;+}++export function planClipSpeedEdit(+ project: Project,+ clipIds: readonly string[],+ edit: ClipSpeedEdit,+ options: ClipSpeedOptions,+ operationId: string,+): TimelineToolPlan {+ const label = options.ripple ? "Speed/duration (ripple)" : "Speed/duration";+ for (const value of [edit.speed, edit.duration, edit.durationScale])+ if (value != null && (!Number.isFinite(value) || value <= 0))+ throw new Error("Speed and duration must be positive numbers.");+ const wanted = new Set(clipIds);+ const changes: Change[] = [];+ let found = 0;+ for (const track of project.timeline.tracks) {+ for (const clip of track.clips) {+ if (!wanted.has(clip.id)) continue;+ found++;+ if (track.locked) throw new Error("Unlock the target track before editing.");+ const rate = resolveClipRate(clip, edit);+ const retimes = rate != null;+ if (retimes && (clip.speedKeyframes?.length || clip.freezeFrames?.length))+ throw new Error("Remove speed ramps and freeze frames before changing speed or duration.");+ const duration = retimes ? (clip.outPoint - clip.inPoint) / rate : clip.duration;+ const next: Clip = {+ ...(resizeKeys(clip as Item, duration) as Clip),+ ...(retimes ? { speed: rate } : {}),+ ...(edit.reversed != null ? { reversed: edit.reversed } : {}),+ ...(edit.maintainPitch != null ? { pitchCorrection: edit.maintainPitch } : {}),+ };+ const same =+ Math.abs(next.duration - clip.duration) < EPS &&+ (next.speed ?? 1) === (clip.speed ?? 1) &&+ (next.reversed ?? false) === (clip.reversed ?? false) &&+ (next.pitchCorrection ?? true) === (clip.pitchCorrection ?? true);+ if (!same) changes.push({ trackId: track.id, before: clip, after: next, delta: next.duration - clip.duration });+ }+ }+ if (!found) throw new Error("Select at least one clip.");+ if (!changes.length) return { label, delta: 0, edits: [] };++ // Process right to left so shifting trailing clips never moves an earlier edit.+ changes.sort((a, b) => b.before.startTime - a.before.startTime);+ const retimed = changes.filter((c) => Math.abs(c.delta) > EPS);++ if (!options.ripple) {+ for (const c of retimed) {+ if (c.delta <= 0) continue;+ const track = project.timeline.tracks.find((t) => t.id === c.trackId)!;+ const end = c.before.startTime + c.before.duration;+ const newEnd = c.after.startTime + c.after.duration;+ const wall = track.clips.find(+ (o) => o.id !== c.before.id && o.startTime >= end - EPS && o.startTime < newEnd - EPS,+ );+ if (wall)+ throw new Error("The slower clip would overlap the next clip. Turn on ripple to shift trailing clips.");+ }+ }++ const editTracks = [...new Set(changes.map((c) => c.trackId))];+ const followers = options.ripple ? syncFollowerTrackIds(project, editTracks) : [];+ // Per group of overlapping (linked) clips, shared ripple data shifts once by+ // the amount every edit track really changed.+ const groups: { start: number; end: number; delta: number }[] = [];+ if (options.ripple) {+ for (const c of [...retimed].sort((a, b) => a.before.startTime - b.before.startTime)) {+ const start = c.before.startTime;+ const end = start + c.before.duration;+ const last = groups[groups.length - 1];+ if (last && start < last.end - EPS) {+ last.end = Math.max(last.end, end);+ last.delta = Math.sign(last.delta) === Math.sign(c.delta)+ ? Math.sign(c.delta) * Math.min(Math.abs(last.delta), Math.abs(c.delta))+ : 0;+ } else groups.push({ start, end, delta: c.delta });+ }+ for (const g of groups)+ if (g.delta < -EPS && followers.length)+ assertRangeEmptyOnTracks(project, followers, g.end + g.delta, g.end);+ }++ let work = project;+ const replaceClips = (trackId: string, replacements: Map<string, Clip>) => {+ work = {+ ...work,+ timeline: {+ ...work.timeline,+ tracks: work.timeline.tracks.map((t) =>+ t.id !== trackId+ ? t+ : { ...t, clips: t.clips.map((clip) => replacements.get(clip.id) ?? clip) },+ ),+ },+ };+ };+ for (const c of changes) {+ replaceClips(c.trackId, new Map([[c.before.id, c.after]]));+ if (options.ripple && Math.abs(c.delta) > EPS)+ work = shiftAfter(work, [c.trackId], c.before.startTime + c.before.duration, c.delta);+ }+ if (options.ripple) {+ const counter = { n: 0 };+ const moveCaptions = allTracksRipple(project, [...editTracks, ...followers]);+ for (const g of [...groups].reverse()) {+ if (Math.abs(g.delta) <= EPS) continue;+ if (g.delta > 0) {+ work = splitAt(work, followers, g.end, operationId, counter);+ work = shiftAfter(work, followers, g.end, g.delta);+ work = openTimelineGap(work, g.end, g.delta, operationId, moveCaptions);+ } else {+ work = shiftAfter(work, followers, g.end, g.delta);+ work = removeTimelineSpan(work, g.end + g.delta, g.end, moveCaptions);+ }+ }+ }+ return diffPlan(project, pruneTransitions(work, project), label);+}++export interface MultiRateStretch {+ primaryId: string;+ /** Clips that stretch together (the selection plus linked partners). */+ clipIds: readonly string[];+ preview(delta: number): TimelineToolPreview;+ plan(delta: number, operationId: string): TimelineToolPlan;+}++/**+ * Rate Stretch on a multi-selection: dragging the primary clip's edge by+ * `delta` scales every selected clip's duration by the same factor and+ * ripples the trailing clips (sync lock and linked audio honoured). The scale+ * is bounded so no clip leaves the 0.1x to 20x range or drops under a frame.+ */+export function prepareMultiRateStretch(+ project: Project,+ options: {+ itemId: string;+ clipIds: readonly string[];+ edge: "left" | "right";+ /** Ripple trailing clips (default). Off, a clip may not grow into its neighbour. */+ ripple?: boolean;+ },+): MultiRateStretch {+ const ripple = options.ripple ?? true;+ const wanted = new Set([options.itemId, ...options.clipIds]);+ const clips: Clip[] = [];+ for (const track of project.timeline.tracks)+ for (const clip of track.clips) {+ if (!wanted.has(clip.id)) continue;+ if (track.locked) throw new Error("Unlock the affected tracks before editing.");+ if (clip.speedKeyframes?.length || clip.freezeFrames?.length)+ throw new Error("Remove speed ramps and freeze frames before rate stretching.");+ if (!(clip.outPoint - clip.inPoint > EPS))+ throw new Error("Rate stretch requires a video or audio source.");+ clips.push(clip);+ }+ const primary = clips.find((c) => c.id === options.itemId);+ if (!primary) throw new Error("This timeline item is no longer available.");+ const frame = 1 / Math.max(1, project.settings.frameRate || 30);+ let low = frame / primary.duration;+ let high = Infinity;+ for (const clip of clips) {+ const span = clip.outPoint - clip.inPoint;+ low = Math.max(low, span / SPEED_MAX / clip.duration);+ high = Math.min(high, span / SPEED_MIN / clip.duration);+ }+ if (!ripple) {+ // Without ripple nothing moves out of the way: a clip may grow only up to+ // the next clip on its track, selected or not.+ for (const track of project.timeline.tracks)+ for (const clip of clips) {+ if (clip.trackId !== track.id) continue;+ const wall = track.clips+ .filter((o) => o.id !== clip.id && o.startTime >= clip.startTime + clip.duration - EPS)+ .reduce<number>((min, o) => Math.min(min, o.startTime), Infinity);+ if (Number.isFinite(wall)) high = Math.min(high, (wall - clip.startTime) / clip.duration);+ }+ }+ const scaleFor = (delta: number) => {+ const raw = (primary.duration + (options.edge === "right" ? delta : -delta)) / primary.duration;+ const snapped = Math.round((raw * primary.duration) / frame) * frame / primary.duration;+ return Math.min(high, Math.max(low, snapped));+ };+ return {+ primaryId: primary.id,+ clipIds: clips.map((c) => c.id),+ preview(delta) {+ const scale = scaleFor(delta);+ const duration = primary.duration * scale;+ return {+ startTime: primary.startTime,+ duration,+ inPoint: primary.inPoint,+ outPoint: primary.outPoint,+ delta: options.edge === "right" ? duration - primary.duration : primary.duration - duration,+ speed: clampSpeed((primary.outPoint - primary.inPoint) / duration),+ // Every other clip stretching with the primary gets its own ghost.+ neighbors: clips+ .filter((c) => c.id !== primary.id)+ .map((c) => ({ trackId: c.trackId, startTime: c.startTime, duration: c.duration * scale })),+ };+ },+ plan(delta, operationId) {+ return planClipSpeedEdit(+ project,+ clips.map((c) => c.id),+ { durationScale: scaleFor(delta) },+ { ripple },+ operationId,+ );+ },+ };+}diff --git a/packages/core/src/editing/portable-project.ts b/packages/core/src/editing/portable-project.tsindex 38a2ba0e..cc7a29b5 100644--- a/packages/core/src/editing/portable-project.ts+++ b/packages/core/src/editing/portable-project.ts@@ -64,7 +64,7 @@ const essentialStateSchema = obj({}, ["options"]);const liveDuckingSchema = obj({ enabled: bool, amountDb: num(1, 40), attackMs: num(10, 3000), releaseMs: num(10, 3000), holdMs: num(0, 3000) }, ["enabled", "amountDb", "attackMs", "releaseMs", "holdMs"]);const clipLinkMetadataSchema = obj({ splitSourceClipId: id, separatedFromClipId: id, sourceAudioTrackIndex: num(0, 63), essentialSound: essentialStateSchema, liveDucking: liveDuckingSchema });-const clipKeyframeSchema = { ...keyframeSchema, properties: { ...keyframeSchema.properties, time: num(-86400, 86400), bezierHandles: obj({ in: pair, out: pair }, ["in", "out"]), roving: bool } };+const clipKeyframeSchema = { ...keyframeSchema, properties: { ...keyframeSchema.properties, time: num(-86400, 86400), bezierHandles: obj({ in: pair, out: pair }, ["in", "out"]), roving: bool, interpolationIn: en(["auto-bezier", "continuous-bezier"]), interpolationOut: en(["auto-bezier", "continuous-bezier"]) } };const automation = obj({ volume: arr(obj({ time, value: num(0, 4) }, ["time", "value"])), pan: arr(obj({ time, value: num(-1, 1) }, ["time", "value"])) });const clipSchema = obj({ id, mediaId: id, trackId: id, startTime: time, duration: num(0.001, 86400), inPoint: time, outPoint: time, effects: arr(effectSchema, 100), audioEffects: arr(audioEffectSchema, 100), transform: fullTransformSchema, volume: num(0, 4), fade: obj({ fadeIn: time, fadeOut: time, origin: obj({ offset: num(-86400, 86400), duration: num(0.000001, 86400), fadeIn: bool, fadeOut: bool, out: obj({ offset: num(-86400, 86400), duration: num(0.000001, 86400) }, ["offset", "duration"]) }, ["offset", "duration"]) }, ["fadeIn", "fadeOut"]), keyframes: arr(clipKeyframeSchema), automation, speed: num(-20, 20), reversed: bool, pitchCorrection: bool, audioType: en(["dialogue", "music", "sfx", "ambience"]), audioTrackIndex: num(0, 63), metadata: clipLinkMetadataSchema }, ["id", "mediaId", "trackId", "startTime", "duration", "inPoint", "outPoint", "effects", "audioEffects", "transform", "volume", "keyframes"]);const transitionSchema = obj({ id, type: en(TRANSITION_TYPES), clipAId: id, clipBId: id, duration: num(0.001, 30), params: transitionParamsSchema, edge: en(["in", "out"]) }, ["id", "type", "clipAId", "duration", "params"]);@@ -73,7 +73,7 @@ const sourceSchema = obj({ name: str, size: num(0, 1e12), lastModified: num(0, 1const mediaSchema = obj({ id, name: str, type: en(["video", "audio", "image"]), metadata: metadataSchema, sourceFile: sourceSchema }, ["id", "name", "type", "metadata"]);export const settingsSchema = obj({ width: num(16, 8192), height: num(16, 8192), frameRate: num(1, 120), sampleRate: num(8000, 192000), channels: num(1, 8) }, ["width", "height", "frameRate", "sampleRate", "channels"]);const subtitleStyle = obj({ fontFamily: str, fontSize: num(1, 1000), color: str, backgroundColor: str, position: en(["top", "center", "bottom"]), highlightColor: str, upcomingColor: str });-const projectSchema = obj({ id, name: str, settings: settingsSchema, media: arr(mediaSchema), timeline: obj({ tracks: arr(obj({ id, name: str, type: en(["video", "audio", "image", "text", "graphics"]), mode: en(["standard"]), role: en(["general", "captions", "dialogue", "music", "effects", "ambience"]), groupId: id, locked: bool, syncLock: bool, hidden: bool, muted: bool, solo: bool, clips: arr(clipSchema), transitions: arr(transitionSchema) }, ["id", "name", "type", "locked", "hidden", "muted", "solo", "clips", "transitions"]), 100), subtitles: arr(obj({ id, text: str, startTime: time, endTime: time, style: subtitleStyle }, ["id", "text", "startTime", "endTime"])), markers: arr(obj({ id, time, label: str, color: str, duration: time, comment: str, kind: en(["comment", "chapter", "segmentation", "web"]), author: str, status: en(["open", "resolved"]), createdAt: num(0, 1e15), replies: arr(obj({ id, author: str, text: str, createdAt: num(0, 1e15) }, ["id", "author", "text", "createdAt"]), 1000) }, ["id", "time", "label", "color"])), duration: time, backgroundFillMode: en(["color", "blur"]), layoutBackgroundColor: str }, ["tracks", "subtitles", "markers", "duration"]), textClips: arr(obj({ id, trackId: id, text: str, startTime: time, duration: num(0.001, 86400), style: { ...textStyleSchema, required: ["fontFamily", "fontSize", "fontWeight", "fontStyle", "color", "textAlign", "verticalAlign", "lineHeight", "letterSpacing"] }, transform: fullTransformSchema, keyframes: arr(keyframeSchema) }, ["id", "trackId", "text", "startTime", "duration", "style", "transform", "keyframes"])) }, ["id", "name", "settings", "media", "timeline", "textClips"]);+const projectSchema = obj({ id, name: str, settings: settingsSchema, media: arr(mediaSchema), timeline: obj({ tracks: arr(obj({ id, name: str, type: en(["video", "audio", "image", "text", "graphics"]), mode: en(["standard"]), role: en(["general", "captions", "dialogue", "music", "effects", "ambience"]), groupId: id, locked: bool, syncLock: bool, hidden: bool, muted: bool, solo: bool, soloSafe: bool, clips: arr(clipSchema), transitions: arr(transitionSchema) }, ["id", "name", "type", "locked", "hidden", "muted", "solo", "clips", "transitions"]), 100), subtitles: arr(obj({ id, text: str, startTime: time, endTime: time, style: subtitleStyle }, ["id", "text", "startTime", "endTime"])), markers: arr(obj({ id, time, label: str, color: str, duration: time, comment: str, kind: en(["comment", "chapter", "segmentation", "web"]), author: str, status: en(["open", "resolved"]), createdAt: num(0, 1e15), replies: arr(obj({ id, author: str, text: str, createdAt: num(0, 1e15) }, ["id", "author", "text", "createdAt"]), 1000) }, ["id", "time", "label", "color"])), duration: time, backgroundFillMode: en(["color", "blur"]), layoutBackgroundColor: str }, ["tracks", "subtitles", "markers", "duration"]), textClips: arr(obj({ id, trackId: id, text: str, startTime: time, duration: num(0.001, 86400), style: { ...textStyleSchema, required: ["fontFamily", "fontSize", "fontWeight", "fontStyle", "color", "textAlign", "verticalAlign", "lineHeight", "letterSpacing"] }, transform: fullTransformSchema, keyframes: arr(keyframeSchema) }, ["id", "trackId", "text", "startTime", "duration", "style", "transform", "keyframes"])) }, ["id", "name", "settings", "media", "timeline", "textClips"]);const portableEditSchema = obj({ format: { enum: [EDIT_FORMAT] }, version: { enum: [EDIT_VERSION, EDIT_FADE_ORIGIN_VERSION] }, project: projectSchema }, ["format", "version", "project"]);interface PortableEdit {@@ -100,7 +100,7 @@ function validatePortableEdit(doc: unknown): asserts doc is PortableEdit {if (clip.outPoint <= clip.inPoint || asset.type !== "image" && clip.outPoint > asset.metadata.duration + 0.05) throw new Error(`Clip ${clip.id}: source range exceeds media duration`);if (clip.speed !== undefined && Math.abs(clip.speed) < 0.1) throw new Error(`Clip ${clip.id}: playback speed is outside the supported range`);if (Math.abs(clip.duration - (clip.outPoint - clip.inPoint) / Math.abs(clip.speed ?? 1)) > 0.05) throw new Error(`Clip ${clip.id}: duration does not match source range and speed`);- if ((clip.fade?.origin || clip.automation || (clip.speed !== undefined && (clip.speed < 0 || clip.speed > 16)) || clip.keyframes.some(key => key.time < 0 || key.bezierHandles || key.roving !== undefined)) && (doc as PortableEdit).version !== EDIT_FADE_ORIGIN_VERSION) throw new Error(`Clip ${clip.id}: retained clip clocks require portable edit version 4`);+ if ((clip.fade?.origin || clip.automation || (clip.speed !== undefined && (clip.speed < 0 || clip.speed > 16)) || clip.keyframes.some(key => key.time < 0 || key.bezierHandles || key.roving !== undefined || key.interpolationIn !== undefined || key.interpolationOut !== undefined)) && (doc as PortableEdit).version !== EDIT_FADE_ORIGIN_VERSION) throw new Error(`Clip ${clip.id}: retained clip clocks require portable edit version 4`);const origin = clip.fade?.origin;if (clip.fade && (clip.fade.fadeIn > (origin && origin.fadeIn !== false ? origin.duration : clip.duration) || clip.fade.fadeOut > (origin && origin.fadeOut !== false ? origin.out?.duration ?? origin.duration : clip.duration))) throw new Error(`Clip ${clip.id}: audio fade exceeds its authored duration`);[...clip.effects, ...clip.audioEffects, ...clip.keyframes].forEach((x) => unique(x.id));@@ -168,7 +168,7 @@ export function createPortableEdit(project: Project): PortableEdit {if (project[key]?.length) throw new Error(`Portable edits do not yet support ${key}; use the ordinary project format to retain them`);}if (project.creation) throw new Error("Portable edits do not yet support creation scenes");- const version = project.timeline.tracks.some(track => track.clips.some(clip => clip.fade?.origin || clip.automation || (clip.speed !== undefined && (clip.speed < 0 || clip.speed > 16)) || clip.keyframes.some(key => key.time < 0 || key.bezierHandles || key.roving !== undefined))) ? EDIT_FADE_ORIGIN_VERSION : EDIT_VERSION;+ const version = project.timeline.tracks.some(track => track.clips.some(clip => clip.fade?.origin || clip.automation || (clip.speed !== undefined && (clip.speed < 0 || clip.speed > 16)) || clip.keyframes.some(key => key.time < 0 || key.bezierHandles || key.roving !== undefined || key.interpolationIn !== undefined || key.interpolationOut !== undefined))) ? EDIT_FADE_ORIGIN_VERSION : EDIT_VERSION;const doc = JSON.parse(JSON.stringify({ format: EDIT_FORMAT, version, project: { id: project.id, name: project.name, settings: project.settings, timeline: project.timeline, textClips: project.textClips ?? [], media: project.mediaLibrary.items.map((m) => ({ id: m.id, name: m.name, type: m.type, metadata: portableMediaMetadata(m.metadata), ...(m.sourceFile ? { sourceFile: { name: m.sourceFile.name, size: m.sourceFile.size, lastModified: m.sourceFile.lastModified } } : {}) })) } })) as PortableEdit;const normalized = { ...doc, project: { ...doc.project, timeline: mapTimelineEffectParams(doc.project.timeline, toNormalizedVideoEffectParams) } };validatePortableEdit(normalized);diff --git a/packages/core/src/editing/replace-fit.test.ts b/packages/core/src/editing/replace-fit.test.tsnew file mode 100644index 00000000..431c6bbf--- /dev/null+++ b/packages/core/src/editing/replace-fit.test.ts@@ -0,0 +1,289 @@+import { describe, expect, it } from "vitest";+import type { Clip, Project, Track } from "../types";+import type { MediaItem } from "../types/project";+import {+ findReplaceTarget,+ planFitToFill,+ planReplaceEdit,+ resolveFitToFill,+} from "./replace-fit";+import { CLIP_SPEED_MAX } from "./speed-limits";+import {+ applyTimelineToolEdits,+ invertTimelineToolEdits,+ validateTimelineToolEdits,+} from "./timeline-tool-edit";++const transform = {+ position: { x: 0, y: 0 },+ scale: { x: 1, y: 1 },+ anchor: { x: 0.5, y: 0.5 },+ rotation: 0,+ opacity: 1,+};+const clip = (id: string, trackId: string, startTime: number, duration: number, extra: Partial<Clip> = {}): Clip => ({+ id,+ mediaId: "old",+ trackId,+ startTime,+ duration,+ inPoint: 0,+ outPoint: duration,+ effects: [],+ audioEffects: [],+ transform,+ volume: 1,+ keyframes: [],+ ...extra,+});+const track = (id: string, type: Track["type"], clips: Clip[], extra: Partial<Track> = {}): Track => ({+ id,+ name: id,+ type,+ mode: "standard",+ role: "general",+ clips,+ transitions: [],+ locked: false,+ hidden: false,+ muted: false,+ solo: false,+ ...extra,+});+const mediaItem = (id: string, type: MediaItem["type"], duration: number, hasAudio = true) =>+ ({+ id,+ name: `${id}.mp4`,+ type,+ fileHandle: null,+ blob: null,+ thumbnailUrl: null,+ waveformData: null,+ metadata: { duration, width: 640, height: 360, frameRate: 30, sampleRate: 48000, channels: 2, codec: "h264", fileSize: 1, hasAudio },+ }) as unknown as MediaItem;++const src = mediaItem("src", "video", 20);+const still = mediaItem("still", "image", 5, false);+const music = mediaItem("music", "audio", 30);++const effect = { id: "fx1", type: "blur", params: { radius: 4 }, enabled: true };+const key = { id: "k1", time: 1, property: "opacity", value: 0.5, easing: "linear" };+const graded = clip("b", "main", 4, 6, {+ effects: [effect],+ keyframes: [key as never],+ volume: 0.6,+ speed: 2,+ speedKeyframes: [{ id: "s1", time: 0, speed: 2, easing: "linear" }],+ metadata: { custom: "keep-me" },+});++const base = {+ id: "p",+ name: "p",+ createdAt: 0,+ modifiedAt: 0,+ settings: { width: 640, height: 360, frameRate: 30, sampleRate: 48000, channels: 2 },+ mediaLibrary: { items: [src, still, music] },+ timeline: {+ duration: 12,+ markers: [],+ subtitles: [],+ tracks: [+ track("main", "video", [clip("a", "main", 0, 4), graded]),+ track("broll", "video", [clip("c", "broll", 2, 6)]),+ track("a1", "audio", [clip("snd", "a1", 4, 6, { speed: 2, metadata: { separatedFromClipId: "b" } })]),+ ],+ },+} as unknown as Project;++const apply = (p: Project, edits: Parameters<typeof applyTimelineToolEdits>[1]) => {+ validateTimelineToolEdits(p, edits);+ return applyTimelineToolEdits(p, edits);+};+const find = (p: Project, id: string) => p.timeline.tracks.flatMap((t) => t.clips).find((c) => c.id === id)!;+const snapshot = (p: Project) =>+ JSON.stringify(p.timeline.tracks.map((t) => [t.id, [...t.clips].sort((x, y) => x.startTime - y.startTime)]));++describe("resolveFitToFill", () => {+ it("speeds a long source into a short range", () => {+ expect(resolveFitToFill({ mediaDuration: 20, sourceIn: 2, sourceOut: 12, sequenceIn: 3, sequenceOut: 8 })).toMatchObject({+ at: 3, sourceIn: 2, sourceOut: 12, duration: 5, speed: 2,+ });+ });+ it("slows a short source down across a long range", () => {+ expect(resolveFitToFill({ mediaDuration: 20, sourceIn: 0, sourceOut: 2, sequenceIn: 0, sequenceOut: 8 }).speed).toBeCloseTo(0.25);+ });+ it("uses the whole media when the source is unmarked", () => {+ expect(resolveFitToFill({ mediaDuration: 20, sequenceIn: 1, sequenceOut: 11 })).toMatchObject({ sourceIn: 0, sourceOut: 20, speed: 2 });+ });+ it("is a plain overwrite at 100% when the lengths match", () => {+ expect(resolveFitToFill({ mediaDuration: 20, sourceIn: 1, sourceOut: 4, sequenceIn: 0, sequenceOut: 3 }).speed).toBe(1);+ });+ it("refuses speeds outside the clip speed limits, naming the speed", () => {+ expect(() => resolveFitToFill({ mediaDuration: 400, sourceIn: 0, sourceOut: 400, sequenceIn: 0, sequenceOut: 10 })).toThrow(/4000%/);+ expect(() => resolveFitToFill({ mediaDuration: 20, sourceIn: 0, sourceOut: 0.5, sequenceIn: 0, sequenceOut: 10 })).toThrow(/5%/);+ expect(CLIP_SPEED_MAX).toBe(20);+ });+ it("needs both timeline marks", () => {+ expect(() => resolveFitToFill({ mediaDuration: 20, sequenceIn: 1, sequenceOut: Number.NaN })).toThrow(/In and Out/);+ expect(() => resolveFitToFill({ mediaDuration: 20, sequenceIn: 4, sequenceOut: 4 })).toThrow(/after the sequence In/);+ });+});++describe("planFitToFill", () => {+ const request = { media: src, trackId: "broll", clipId: "n", operationId: "op" };+ it("fills the range with a retimed clip whose duration equals the range", () => {+ const { plan, resolved, clip: placed } = planFitToFill(base, {+ ...request, sourceIn: 0, sourceOut: 10, sequenceIn: 1, sequenceOut: 6,+ });+ expect(plan.label).toBe("Fit to Fill");+ expect(resolved.speed).toBe(2);+ expect(placed).toMatchObject({ startTime: 1, duration: 5, inPoint: 0, outPoint: 10, speed: 2 });+ const after = apply(base, plan.edits);+ const broll = [...after.timeline.tracks.find((t) => t.id === "broll")!.clips].sort((x, y) => x.startTime - y.startTime);+ // "c" (2..8) is overwritten inside 1..6 and keeps its tail 6..8.+ expect(broll.map((c) => [c.id === "n" ? "n" : "tail", c.startTime, c.duration])).toEqual([["n", 1, 5], ["tail", 6, 2]]);+ const n = broll[0];+ expect((n.outPoint - n.inPoint) / (n.speed ?? 1)).toBeCloseTo(n.duration);+ expect(n.pitchCorrection).toBeUndefined(); // engine default: pitch preserved+ });+ it("leaves the speed unset at 100%", () => {+ const { clip: placed } = planFitToFill(base, { ...request, sourceIn: 3, sourceOut: 8, sequenceIn: 0, sequenceOut: 5 });+ expect(placed.speed).toBeUndefined();+ });+ it("is one undo step that restores the project exactly", () => {+ const { plan } = planFitToFill(base, { ...request, sourceIn: 0, sourceOut: 10, sequenceIn: 1, sequenceOut: 6 });+ const after = apply(base, plan.edits);+ expect(snapshot(apply(after, invertTimelineToolEdits(plan.edits)))).toBe(snapshot(base));+ });+ it("does not ripple: the other tracks and later clips stay put", () => {+ const { plan } = planFitToFill(base, { ...request, sourceIn: 0, sourceOut: 10, sequenceIn: 1, sequenceOut: 6 });+ const after = apply(base, plan.edits);+ expect(find(after, "b")).toMatchObject({ startTime: 4 });+ expect(find(after, "snd")).toMatchObject({ startTime: 4 });+ });+ it("patches video and audio to separate tracks at the same speed, linked", () => {+ const { plan } = planFitToFill(base, {+ ...request, trackId: "broll", sourceIn: 0, sourceOut: 10, sequenceIn: 1, sequenceOut: 6,+ audioPatch: { trackId: "a1", clipId: "n-audio" },+ });+ const after = apply(base, plan.edits);+ expect(find(after, "n")).toMatchObject({ speed: 2, duration: 5, volume: 0 });+ expect(find(after, "n-audio")).toMatchObject({ speed: 2, duration: 5, startTime: 1 });+ expect(find(after, "n-audio").metadata?.separatedFromClipId).toBe("n");+ });+ it("audio-only sources retime on an audio track", () => {+ const { clip: placed } = planFitToFill(base, { ...request, media: music, trackId: "a1", sourceIn: 0, sourceOut: 12, sequenceIn: 0, sequenceOut: 6 });+ expect(placed).toMatchObject({ speed: 2, duration: 6 });+ });+ it("refuses stills, locked tracks and out-of-range speeds", () => {+ expect(() => planFitToFill(base, { ...request, media: still, sequenceIn: 0, sequenceOut: 4 })).toThrow(/video or audio/);+ const locked = { ...base, timeline: { ...base.timeline, tracks: base.timeline.tracks.map((t) => (t.id === "broll" ? { ...t, locked: true } : t)) } } as Project;+ expect(() => planFitToFill(locked, { ...request, sourceIn: 0, sourceOut: 10, sequenceIn: 1, sequenceOut: 6 })).toThrow(/Unlock/);+ expect(() => planFitToFill(base, { ...request, sourceIn: 0, sourceOut: 20, sequenceIn: 0, sequenceOut: 0.5 })).toThrow(/speed/);+ });+ it("honours a restricted subclip window", () => {+ const sub = { ...src, subclip: { sourceMediaId: "src", inPoint: 4, outPoint: 8, restrictTrims: true } } as unknown as MediaItem;+ const { resolved } = planFitToFill(base, { ...request, media: sub, sequenceIn: 0, sequenceOut: 8 });+ expect(resolved).toMatchObject({ sourceIn: 4, sourceOut: 8, speed: 0.5 });+ });+});++describe("planReplaceEdit", () => {+ const request = { clipId: "b", media: src, alignment: "in" as const, playhead: 5, sourcePosition: 9, keepAttributes: true };+ it("keeps position and duration, swaps the footage, aligned at the source In", () => {+ const { plan, resolved } = planReplaceEdit(base, { ...request, sourceIn: 3 });+ expect(resolved).toMatchObject({ clipId: "b", at: 4, duration: 6, sourceIn: 3, sourceOut: 9, fellBackToIn: false });+ const after = apply(base, plan.edits);+ expect(find(after, "b")).toMatchObject({ id: "b", mediaId: "src", startTime: 4, duration: 6, inPoint: 3, outPoint: 9 });+ expect(find(after, "a")).toEqual(find(base, "a"));+ });+ it("aligns the Source playhead frame to the timeline playhead", () => {+ // Playhead 1s into the clip; source frame 9 sits there, so the clip starts at 8.+ const { resolved } = planReplaceEdit(base, { ...request, alignment: "playhead" });+ expect(resolved).toMatchObject({ sourceIn: 8, sourceOut: 14 });+ });+ it("falls back to the In point when the playhead is outside the clip", () => {+ const { resolved } = planReplaceEdit(base, { ...request, alignment: "playhead", playhead: 1, sourceIn: 2 });+ expect(resolved).toMatchObject({ sourceIn: 2, fellBackToIn: true });+ });+ it("keeps effects, keyframes, volume and metadata but drops the old footage's speed", () => {+ const { plan } = planReplaceEdit(base, request);+ const out = find(apply(base, plan.edits), "b");+ expect(out.effects).toEqual([effect]);+ expect(out.keyframes).toEqual([key]);+ expect(out.volume).toBe(0.6);+ expect(out.metadata?.custom).toBe("keep-me");+ expect(out.speed).toBeUndefined();+ expect(out.speedKeyframes).toBeUndefined();+ expect(out.outPoint - out.inPoint).toBeCloseTo(out.duration);+ });+ it("resets the clip to a fresh one when attributes are not kept", () => {+ const { plan } = planReplaceEdit(base, { ...request, keepAttributes: false });+ const out = find(apply(base, plan.edits), "b");+ expect(out).toMatchObject({ effects: [], keyframes: [], volume: 1, startTime: 4, duration: 6, mediaId: "src" });+ expect(out.speed).toBeUndefined();+ });+ it("replaces the linked audio together with the picture", () => {+ const linkedBase = {+ ...base,+ timeline: {+ ...base.timeline,+ tracks: base.timeline.tracks.map((t) =>+ t.id === "a1" ? { ...t, clips: t.clips.map((c) => ({ ...c, mediaId: "old" })) } : t),+ },+ } as Project;+ const { plan, resolved } = planReplaceEdit(linkedBase, request);+ expect(resolved.linkedClipIds).toEqual(["snd"]);+ const after = apply(linkedBase, plan.edits);+ expect(find(after, "snd")).toMatchObject({ mediaId: "src", startTime: 4, duration: 6, inPoint: 0, outPoint: 6 });+ });+ it("is one undo step that restores the project exactly", () => {+ const { plan } = planReplaceEdit(base, request);+ expect(plan.label).toBe("Replace");+ const after = apply(base, plan.edits);+ expect(snapshot(after)).not.toBe(snapshot(base));+ expect(snapshot(apply(after, invertTimelineToolEdits(plan.edits)))).toBe(snapshot(base));+ });+ it("keeps transitions attached (the clip id survives)", () => {+ const withTransition = {+ ...base,+ timeline: {+ ...base.timeline,+ tracks: base.timeline.tracks.map((t) =>+ t.id === "main" ? { ...t, transitions: [{ id: "t", clipAId: "a", clipBId: "b", type: "crossfade", duration: 1, params: {} }] } : t),+ },+ } as unknown as Project;+ const { plan } = planReplaceEdit(withTransition, request);+ expect(plan.edits.every((e) => e.kind !== "transition")).toBe(true);+ });+ it("refuses when the source is too short, ahead of its start, locked, or the wrong kind", () => {+ expect(() => planReplaceEdit(base, { ...request, sourceIn: 18 })).toThrow(/from that point/);+ expect(() => planReplaceEdit(base, { ...request, alignment: "playhead", sourcePosition: 0.5 })).toThrow(/Not enough source before/);+ const locked = { ...base, timeline: { ...base.timeline, tracks: base.timeline.tracks.map((t) => (t.id === "main" ? { ...t, locked: true } : t)) } } as Project;+ expect(() => planReplaceEdit(locked, request)).toThrow(/Unlock/);+ expect(() => planReplaceEdit(base, { ...request, media: music })).toThrow(/audio track/i);+ expect(() => planReplaceEdit(base, { ...request, clipId: "missing" })).toThrow(/Select the timeline clip/);+ });+ it("lets a still fill a clip of any length", () => {+ const { plan } = planReplaceEdit(base, { ...request, media: still });+ const out = find(apply(base, plan.edits), "b");+ expect(out).toMatchObject({ mediaId: "still", duration: 6, inPoint: 0, outPoint: 6 });+ });+ it("refuses to leave a restricted subclip window", () => {+ const sub = { ...src, subclip: { sourceMediaId: "src", inPoint: 4, outPoint: 8, restrictTrims: true } } as unknown as MediaItem;+ expect(() => planReplaceEdit(base, { ...request, media: sub, sourceIn: 4 })).toThrow(/restricted/);+ });+});++describe("findReplaceTarget", () => {+ it("prefers the selection, else the topmost clip under the playhead", () => {+ expect(findReplaceTarget(base, { media: src, selectedClipIds: ["c"], playhead: 5 })?.id).toBe("c");+ expect(findReplaceTarget(base, { media: src, selectedClipIds: [], playhead: 5 })?.id).toBe("b");+ expect(findReplaceTarget(base, { media: src, selectedClipIds: [], playhead: 5, targetedTrackIds: ["broll"] })?.id).toBe("c");+ expect(findReplaceTarget(base, { media: src, selectedClipIds: [], playhead: 11 })).toBeNull();+ });+ it("audio sources look at audio tracks", () => {+ expect(findReplaceTarget(base, { media: music, selectedClipIds: [], playhead: 5 })?.id).toBe("snd");+ });+});diff --git a/packages/core/src/editing/replace-fit.ts b/packages/core/src/editing/replace-fit.tsnew file mode 100644index 00000000..efbe4a0e--- /dev/null+++ b/packages/core/src/editing/replace-fit.ts@@ -0,0 +1,378 @@+import type { Clip, Project, Track } from "../types";+import type { MediaItem } from "../types/project";+import { getCompoundClipId } from "../timeline/timeline-items";+import { subclipRange } from "../media/bins";+import { diffPlan, planOverwrite, findTopmostVisualClipAt } from "./premiere-edits";+import {+ boundSourceMarks,+ createSourceClip,+ sourceDropError,+ type SourceComponent,+ type SourceEditRequest,+} from "./source-edit";+import { findLinkedPartners } from "./split-edit";+import { CLIP_SPEED_MAX, CLIP_SPEED_MIN } from "./speed-limits";+import type { TimelineToolPlan } from "./timeline-tool-edit";++/**+ * Premiere's two remaining Source-monitor edit commands.+ *+ * - Replace edit swaps the media of ONE timeline clip for the Source monitor's+ * clip. The timeline clip keeps its position, duration and (optionally) its+ * effects and keyframes; only the footage under it changes. Nothing moves,+ * so Sync Lock has nothing to ripple; locked tracks are refused.+ * - Fit to Fill places the source In/Out range into the sequence In/Out range+ * and retimes it (speed = source length / sequence length). It is an+ * overwrite-type edit, so it touches only its destination tracks. Audio+ * follows the clip speed through the existing pitch-preserving path+ * (Clip.pitchCorrection defaults to on).+ *+ * Both return one TimelineToolPlan, i.e. one undo step.+ */+const EPS = 1e-6;++/* ------------------------------ Fit to Fill ------------------------------ */++export interface FitToFillRequest+ extends Omit<SourceEditRequest, "mode" | "playhead" | "sequenceIn" | "sequenceOut"> {+ sequenceIn: number;+ sequenceOut: number;+}++export interface ResolvedFitToFill {+ at: number;+ sourceIn: number;+ sourceOut: number;+ /** Timeline length: the whole sequence range. */+ duration: number;+ /** Playback rate applied to the clip (1 = unchanged, 2 = twice as fast). */+ speed: number;+ rule: "fit-to-fill";+}++export interface FitToFillPlan {+ plan: TimelineToolPlan;+ resolved: ResolvedFitToFill;+ clip: Clip;+}++const pct = (speed: number) => `${Math.round(speed * 1000) / 10}%`;++/** The speed Fit to Fill needs, or the reason it cannot be done. */+export function resolveFitToFill(input: {+ mediaDuration: number;+ sourceIn?: number | null;+ sourceOut?: number | null;+ sequenceIn: number;+ sequenceOut: number;+}): ResolvedFitToFill {+ const media = input.mediaDuration > 0 ? input.mediaDuration : 5;+ const has = (v: number | null | undefined): v is number =>+ typeof v === "number" && Number.isFinite(v);+ if (!has(input.sequenceIn) || !has(input.sequenceOut))+ throw new Error("Fit to Fill needs In and Out marks on the timeline.");+ const span = input.sequenceOut - input.sequenceIn;+ if (input.sequenceIn < 0 || span <= EPS)+ throw new Error("The sequence Out must be after the sequence In.");+ const a = has(input.sourceIn) ? Math.max(0, Math.min(media, input.sourceIn)) : 0;+ const b = has(input.sourceOut) ? Math.max(0, Math.min(media, input.sourceOut)) : media;+ if (b - a <= EPS) throw new Error("The source Out must be after the source In.");+ const speed = (b - a) / span;+ if (speed < CLIP_SPEED_MIN - 1e-9 || speed > CLIP_SPEED_MAX + 1e-9)+ throw new Error(+ `Fit to Fill needs ${pct(speed)} speed; clips play between ${pct(CLIP_SPEED_MIN)} and ${pct(CLIP_SPEED_MAX)}. Adjust the source range or the timeline range.`,+ );+ return {+ at: input.sequenceIn,+ sourceIn: a,+ sourceOut: b,+ duration: span,+ speed: Math.abs(speed - 1) < 1e-6 ? 1 : speed,+ rule: "fit-to-fill",+ };+}++export function planFitToFill(project: Project, request: FitToFillRequest): FitToFillPlan {+ if (request.media.type === "image")+ throw new Error("Fit to Fill needs video or audio; a still has no speed to change.");+ const marks = boundSourceMarks(request.media, request.sourceIn, request.sourceOut);+ const resolved = resolveFitToFill({+ mediaDuration: request.media.metadata.duration,+ sourceIn: marks.sourceIn,+ sourceOut: marks.sourceOut,+ sequenceIn: request.sequenceIn,+ sequenceOut: request.sequenceOut,+ });+ const range = { inPoint: resolved.sourceIn, outPoint: resolved.sourceOut };+ const retime = (clip: Clip): Clip => ({+ ...clip,+ duration: resolved.duration,+ ...(resolved.speed !== 1 ? { speed: resolved.speed } : {}),+ });+ const split =+ request.audioPatch !== undefined &&+ (request.component ?? "both") === "both" &&+ request.media.type === "video" &&+ request.media.metadata.hasAudio !== false;+ const clip = retime(+ createSourceClip(+ request.media,+ request.trackId,+ request.clipId,+ range,+ split ? "video" : request.component,+ ),+ );+ const placements = [{ trackId: request.trackId, clip }];+ if (split && request.audioPatch) {+ const sound = createSourceClip(+ request.media,+ request.audioPatch.trackId,+ request.audioPatch.clipId,+ range,+ "audio",+ );+ placements.push({+ trackId: request.audioPatch.trackId,+ clip: retime({+ ...sound,+ metadata: { ...sound.metadata, separatedFromClipId: request.clipId },+ }),+ });+ }+ const newTracks = [request.newTrack, split ? request.audioPatch?.newTrack : undefined].filter(+ (track): track is NonNullable<typeof track> => track !== undefined,+ );+ const plan = planOverwrite(+ project,+ resolved.at,+ placements,+ request.operationId,+ newTracks.length ? newTracks : undefined,+ );+ return { plan: { ...plan, label: "Fit to Fill" }, resolved, clip: { ...clip, startTime: resolved.at } };+}++/* ------------------------------ Replace edit ----------------------------- */++/** Which source frame lines up with which timeline frame:+ * - "playhead": the Source monitor's current frame sits under the timeline+ * playhead (Premiere's Replace from Source Monitor);+ * - "in": the source In (media start when unmarked) sits at the clip's first+ * frame (Premiere's Replace using the In point). */+export type ReplaceAlignment = "playhead" | "in";++export interface ReplaceEditRequest {+ clipId: string;+ media: MediaItem;+ alignment: ReplaceAlignment;+ /** Timeline playhead, for the "playhead" alignment. */+ playhead: number;+ /** Source monitor position, for the "playhead" alignment. */+ sourcePosition: number;+ sourceIn?: number | null;+ /** Keep the clip's effects, keyframes, transform, audio settings, fades,+ * blend and colour. Off resets them to a fresh clip's defaults. */+ keepAttributes: boolean;+ component?: SourceComponent;+}++export interface ResolvedReplace {+ clipId: string;+ /** Linked clips (e.g. the audio of a video clip) replaced together. */+ linkedClipIds: string[];+ at: number;+ duration: number;+ sourceIn: number;+ sourceOut: number;+ alignment: ReplaceAlignment;+ /** True when "playhead" fell back to the In point because the playhead is+ * outside the clip. */+ fellBackToIn: boolean;+}++export interface ReplaceEditPlan {+ plan: TimelineToolPlan;+ resolved: ResolvedReplace;+}++/** Fields that describe how the OLD footage plays and cannot carry over. */+const FOOTAGE_BOUND_KEYS = [+ "speed",+ "reversed",+ "smoothSlowMo",+ "interpolationQuality",+ "speedKeyframes",+ "freezeFrames",+ "stabilization",+ "audioTrackIndex",+ "pitchCorrection",+] as const satisfies readonly (keyof Clip)[];++function findClipIn(project: Project, clipId: string): { clip: Clip; track: Track } | null {+ for (const track of project.timeline.tracks) {+ const clip = track.clips.find((c) => c.id === clipId);+ if (clip) return { clip, track };+ }+ return null;+}++const lengthOf = (media: Pick<MediaItem, "metadata">) =>+ media.metadata.duration > 0 ? media.metadata.duration : 5;++/** The component a replacement clip carries: a video-only/audio-only clip stays+ * that way; a video source on an audio track is sound only. */+function componentFor(old: Clip, track: Track, media: MediaItem, requested?: SourceComponent): SourceComponent {+ const kept = old.metadata?.sourceMonitorComponent;+ if (media.type === "video" && (kept === "video" || kept === "audio")) return kept;+ if (media.type === "video" && track.type === "audio") return "audio";+ return requested ?? "both";+}++/**+ * Which clip a Replace edit acts on: the selected media clip, else the topmost+ * clip under the playhead (on the targeted tracks when any are targeted; audio+ * sources look at audio tracks). Returns null when nothing qualifies.+ */+export function findReplaceTarget(+ project: Project,+ options: {+ media: Pick<MediaItem, "type">;+ selectedClipIds: readonly string[];+ playhead: number;+ targetedTrackIds?: readonly string[];+ },+): Clip | null {+ for (let i = options.selectedClipIds.length - 1; i >= 0; i--) {+ const found = findClipIn(project, options.selectedClipIds[i]);+ if (found) return found.clip;+ }+ if (options.media.type === "audio") {+ const only = options.targetedTrackIds?.length ? new Set(options.targetedTrackIds) : null;+ for (const track of project.timeline.tracks) {+ if (track.type !== "audio" || track.hidden || (only && !only.has(track.id))) continue;+ const clip = track.clips.find(+ (c) => c.startTime <= options.playhead + EPS && options.playhead < c.startTime + c.duration - EPS,+ );+ if (clip) return clip;+ }+ return null;+ }+ const visualTargets = (options.targetedTrackIds ?? []).filter((id) => {+ const type = project.timeline.tracks.find((t) => t.id === id)?.type;+ return type === "video" || type === "image";+ });+ return findTopmostVisualClipAt(project, options.playhead, visualTargets);+}++export function planReplaceEdit(project: Project, request: ReplaceEditRequest): ReplaceEditPlan {+ const found = findClipIn(project, request.clipId);+ if (!found) throw new Error("Select the timeline clip to replace first.");+ const { clip: target, track } = found;+ if (getCompoundClipId(target)) throw new Error("Nested sequences cannot be replaced with a source clip.");+ const media = request.media;+ const duration = target.duration;+ const imageSource = media.type === "image";+ const window = boundSourceMarks(media, request.sourceIn, null);+ const total = lengthOf(media);++ let sourceIn: number;+ let fellBackToIn = false;+ const inside =+ request.playhead >= target.startTime - EPS && request.playhead < target.startTime + duration - EPS;+ if (imageSource) {+ sourceIn = 0;+ } else if (request.alignment === "playhead" && inside) {+ sourceIn = request.sourcePosition - Math.max(0, request.playhead - target.startTime);+ } else {+ fellBackToIn = request.alignment === "playhead";+ sourceIn = window.sourceIn ?? 0;+ }+ if (sourceIn < -EPS)+ throw new Error("Not enough source before the aligned frame. Move the Source playhead later or use the In point.");+ sourceIn = Math.max(0, sourceIn);+ const sourceOut = imageSource ? duration : sourceIn + duration;+ if (!imageSource && sourceOut > total + 1e-4)+ throw new Error(+ `The source has ${Math.max(0, total - sourceIn).toFixed(2)}s from that point; the clip is ${duration.toFixed(2)}s. Choose an earlier In or Source playhead.`,+ );+ const locked = media.subclip?.restrictTrims ? subclipRange(media) : null;+ if (locked && !imageSource && (sourceIn < locked.start - EPS || sourceOut > locked.end + EPS))+ throw new Error("This subclip is restricted; the replacement would play outside its In/Out.");++ const replaceOne = (old: Clip, oldTrack: Track): Clip => {+ if (oldTrack.locked) throw new Error("Unlock the target track before editing.");+ const component = componentFor(old, oldTrack, media, request.component);+ const refusal = sourceDropError(oldTrack, media, component);+ if (refusal) throw new Error(refusal);+ const range = { inPoint: sourceIn, outPoint: Math.min(sourceOut, total) };+ const fresh = imageSource+ ? createSourceClip(media, oldTrack.id, old.id, { inPoint: 0, outPoint: Math.min(total, duration) }, component)+ : createSourceClip(media, oldTrack.id, old.id, range, component);+ const link = old.metadata?.separatedFromClipId;+ const sizing = { startTime: old.startTime, duration: old.duration, inPoint: sourceIn, outPoint: sourceOut };+ if (!request.keepAttributes) {+ return {+ ...fresh,+ ...sizing,+ ...(old.label !== undefined ? { label: old.label } : {}),+ metadata: {+ ...fresh.metadata,+ ...(typeof link === "string" ? { separatedFromClipId: link } : {}),+ },+ };+ }+ const kept: Record<string, unknown> = { ...old };+ for (const key of FOOTAGE_BOUND_KEYS) delete kept[key];+ const keptMetadata = { ...old.metadata };+ delete keptMetadata.sourceMonitorComponent;+ return {+ ...(kept as unknown as Clip),+ ...sizing,+ mediaId: media.id,+ metadata: { ...keptMetadata, ...(fresh.metadata?.sourceMonitorComponent ? { sourceMonitorComponent: fresh.metadata.sourceMonitorComponent } : {}) },+ // A component change (video-only to audio-only) still mutes or hides.+ ...(component === "video" ? { volume: 0 } : {}),+ ...(component === "audio" ? { transform: { ...old.transform, opacity: 0 } } : {}),+ };+ };++ const replaced = new Map<string, Clip>();+ replaced.set(target.id, replaceOne(target, track));+ const linkedClipIds: string[] = [];+ if (media.type !== "image" && media.metadata.hasAudio !== false) {+ for (const partner of findLinkedPartners(target, project.timeline.tracks)) {+ const sameSpan =+ Math.abs(partner.clip.startTime - target.startTime) < EPS &&+ Math.abs(partner.clip.duration - target.duration) < EPS;+ if (!sameSpan || partner.clip.mediaId !== target.mediaId) continue;+ replaced.set(partner.clip.id, replaceOne(partner.clip, partner.track));+ linkedClipIds.push(partner.clip.id);+ }+ }++ const work: Project = {+ ...project,+ timeline: {+ ...project.timeline,+ tracks: project.timeline.tracks.map((t) =>+ t.clips.some((c) => replaced.has(c.id))+ ? { ...t, clips: t.clips.map((c) => replaced.get(c.id) ?? c) }+ : t,+ ),+ },+ };+ return {+ plan: diffPlan(project, work, "Replace"),+ resolved: {+ clipId: target.id,+ linkedClipIds,+ at: target.startTime,+ duration,+ sourceIn,+ sourceOut,+ alignment: request.alignment,+ fellBackToIn,+ },+ };+}diff --git a/packages/core/src/editing/reverse-match-frame.test.ts b/packages/core/src/editing/reverse-match-frame.test.tsnew file mode 100644index 00000000..2d3ec046--- /dev/null+++ b/packages/core/src/editing/reverse-match-frame.test.ts@@ -0,0 +1,69 @@+import { describe, expect, it } from "vitest";+import type { Clip, Project } from "../types";+import { findReverseMatch, timelineTimeForSource } from "./reverse-match-frame";++const transform = { position: { x: 0, y: 0 }, scale: { x: 1, y: 1 }, rotation: 0, opacity: 1, anchor: { x: 0.5, y: 0.5 } };+const clip = (id: string, startTime: number, duration: number, inPoint: number, extra: Partial<Clip> = {}): Clip =>+ ({+ id, trackId: "t", mediaId: "m", startTime, duration, inPoint, outPoint: inPoint + duration,+ volume: 1, effects: [], audioEffects: [], keyframes: [], transform, ...extra,+ }) as Clip;+const track = (id: string, type: string, clips: Clip[], hidden = false) => ({+ id, name: id, type, locked: false, hidden, solo: false, muted: false, transitions: [], clips,+});+const project = (tracks: ReturnType<typeof track>[]) =>+ ({ timeline: { tracks } }) as unknown as Project;++describe("timelineTimeForSource", () => {+ it("maps source time through an in-point offset", () => {+ expect(timelineTimeForSource(clip("a", 10, 4, 6), 8)).toBeCloseTo(12, 5);+ });+ it("returns null outside the used range and honours tolerance", () => {+ const c = clip("a", 0, 4, 6);+ expect(timelineTimeForSource(c, 5)).toBeNull();+ expect(timelineTimeForSource(c, 10.2)).toBeNull();+ expect(timelineTimeForSource(c, 10.02, 0.05)).not.toBeNull();+ });+ it("accounts for a speed change (source range stays inPoint..outPoint)", () => {+ // 2x: 4 timeline seconds consume 8 source seconds.+ const c = clip("a", 0, 4, 0, { speed: 2, outPoint: 8 });+ expect(timelineTimeForSource(c, 6)).toBeCloseTo(3, 3);+ const slow = clip("b", 0, 8, 0, { speed: 0.5, outPoint: 4 });+ expect(timelineTimeForSource(slow, 1)).toBeCloseTo(2, 3);+ });+ it("inverts reversed clips", () => {+ const c = clip("a", 0, 4, 0, { reversed: true });+ expect(timelineTimeForSource(c, 1)).toBeCloseTo(3, 3);+ expect(timelineTimeForSource(c, 4)).toBeCloseTo(0, 3);+ });+});++describe("findReverseMatch", () => {+ it("returns null when the frame is not in the sequence", () => {+ expect(findReverseMatch(project([track("v1", "video", [clip("a", 0, 4, 0)])]), "m", 9, 0)).toBeNull();+ expect(findReverseMatch(project([track("v1", "video", [clip("a", 0, 4, 0)])]), "other", 1, 0)).toBeNull();+ });+ it("prefers the topmost track", () => {+ const p = project([+ track("v2", "video", [clip("top", 20, 4, 0)]),+ track("v1", "video", [clip("bottom", 0, 4, 0)]),+ ]);+ expect(findReverseMatch(p, "m", 2, 0)?.clipId).toBe("top");+ });+ it("skips hidden video tracks and falls back to audio", () => {+ const p = project([+ track("v1", "video", [clip("hid", 0, 4, 0)], true),+ track("a1", "audio", [clip("aud", 30, 4, 0)]),+ ]);+ expect(findReverseMatch(p, "m", 1, 0)?.clipId).toBe("aud");+ });+ it("chooses the instance nearest the playhead within a track", () => {+ const p = project([track("v1", "video", [clip("a", 0, 4, 0), clip("b", 10, 4, 0)])]);+ expect(findReverseMatch(p, "m", 2, 11)?.clipId).toBe("b");+ expect(findReverseMatch(p, "m", 2, 1)?.clipId).toBe("a");+ });+ it("finds a frame inside a sped-up instance", () => {+ const p = project([track("v1", "video", [clip("a", 5, 4, 0, { speed: 2, outPoint: 8 })])]);+ expect(findReverseMatch(p, "m", 4, 0)?.time).toBeCloseTo(7, 3);+ });+});diff --git a/packages/core/src/editing/reverse-match-frame.ts b/packages/core/src/editing/reverse-match-frame.tsnew file mode 100644index 00000000..af3a8ff5--- /dev/null+++ b/packages/core/src/editing/reverse-match-frame.ts@@ -0,0 +1,75 @@+import type { Clip, Project } from "../types";+import { clipSourceTimeAt } from "./premiere-edits";++export interface ReverseMatch {+ clipId: string;+ trackId: string;+ /** Timeline time at which the clip shows the requested source time. */+ time: number;+}++/**+ * Timeline time at which `clip` shows `sourceTime`, honouring speed, reverse+ * and speed keyframes (the mapping is monotonic, so it is inverted by+ * bisection over the same function the renderer uses). Null when the clip+ * never shows that source time. `tolerance` (seconds) forgives a source time+ * just outside the clip's used range, e.g. a frame of rounding.+ */+export function timelineTimeForSource(+ clip: Clip,+ sourceTime: number,+ tolerance = 0,+): number | null {+ if (clip.duration <= 0) return null;+ const start = clip.startTime;+ const end = clip.startTime + clip.duration;+ const a = clipSourceTimeAt(clip, start);+ const b = clipSourceTimeAt(clip, end);+ const lo = Math.min(a, b);+ const hi = Math.max(a, b);+ if (sourceTime < lo - tolerance || sourceTime > hi + tolerance) return null;+ const target = Math.min(hi, Math.max(lo, sourceTime));+ const ascending = b >= a;+ let left = start;+ let right = end;+ for (let i = 0; i < 48; i++) {+ const mid = (left + right) / 2;+ const value = clipSourceTimeAt(clip, mid);+ if (value < target === ascending) left = mid;+ else right = mid;+ }+ return (left + right) / 2;+}++/**+ * Reverse Match Frame: find where `mediaId` at `sourceTime` appears in the+ * sequence. The topmost track wins (lower index is on top; video/image before+ * audio, hidden video skipped); when that track holds several instances the+ * one nearest `playhead` wins. `frameDuration` is the match tolerance.+ */+export function findReverseMatch(+ project: Project,+ mediaId: string,+ sourceTime: number,+ playhead: number,+ frameDuration = 0,+): ReverseMatch | null {+ const tolerance = Math.max(0, frameDuration) / 2;+ const tracks = project.timeline.tracks;+ const visual = tracks.filter(+ (t) => (t.type === "video" || t.type === "image") && !t.hidden,+ );+ const rest = tracks.filter((t) => t.type === "audio");+ for (const track of [...visual, ...rest]) {+ let best: ReverseMatch | null = null;+ for (const clip of track.clips) {+ if (clip.mediaId !== mediaId) continue;+ const time = timelineTimeForSource(clip, sourceTime, tolerance);+ if (time === null) continue;+ if (!best || Math.abs(time - playhead) < Math.abs(best.time - playhead))+ best = { clipId: clip.id, trackId: track.id, time };+ }+ if (best) return best;+ }+ return null;+}diff --git a/packages/core/src/editing/source-edit.ts b/packages/core/src/editing/source-edit.tsindex d3890b3f..796828ee 100644--- a/packages/core/src/editing/source-edit.ts+++ b/packages/core/src/editing/source-edit.ts@@ -190,22 +190,32 @@ export function createSourceClip(: { ...base, transform: { ...base.transform, opacity: 0 }, metadata };}-export function planSourceEdit(- project: Project,- request: SourceEditRequest,-): SourceEditPlan {- // A subclip places its own window when the Source monitor has no marks, and- // restricted subclips never place outside it.- const window = subclipRange(request.media);- const restricted = request.media.subclip?.restrictTrims ? window : null;+/** The source marks an edit works from: a subclip places its own window when+ * the Source monitor has no marks, and a restricted subclip never places+ * outside it. */+export function boundSourceMarks(+ media: MediaItem,+ sourceIn?: number | null,+ sourceOut?: number | null,+): { sourceIn: number | undefined; sourceOut: number | undefined } {+ const window = subclipRange(media);+ const restricted = media.subclip?.restrictTrims ? window : null;const bound = (value: number | null | undefined, fallback: number | undefined) => {const v = typeof value === "number" && Number.isFinite(value) ? value : fallback;return v !== undefined && restricted ? Math.min(restricted.end, Math.max(restricted.start, v)) : v;};+ return { sourceIn: bound(sourceIn, window?.start), sourceOut: bound(sourceOut, window?.end) };+}++export function planSourceEdit(+ project: Project,+ request: SourceEditRequest,+): SourceEditPlan {+ const marks = boundSourceMarks(request.media, request.sourceIn, request.sourceOut);const resolved = resolveThreePointEdit({mediaDuration: request.media.metadata.duration,- sourceIn: bound(request.sourceIn, window?.start),- sourceOut: bound(request.sourceOut, window?.end),+ sourceIn: marks.sourceIn,+ sourceOut: marks.sourceOut,playhead: request.playhead,sequenceIn: request.sequenceIn,sequenceOut: request.sequenceOut,diff --git a/packages/core/src/editing/speed-limits.ts b/packages/core/src/editing/speed-limits.tsnew file mode 100644index 00000000..308df202--- /dev/null+++ b/packages/core/src/editing/speed-limits.ts@@ -0,0 +1,4 @@+/** Playback-rate bounds of a clip (10% to 2000%), shared by clip/setSpeed and+ * Fit to Fill so both refuse or clamp at the same limits. */+export const CLIP_SPEED_MIN = 0.1;+export const CLIP_SPEED_MAX = 20;diff --git a/packages/core/src/editing/timeline-tool-edit.ts b/packages/core/src/editing/timeline-tool-edit.tsindex 1ffc8138..f78b84f8 100644--- a/packages/core/src/editing/timeline-tool-edit.ts+++ b/packages/core/src/editing/timeline-tool-edit.ts@@ -695,7 +695,13 @@ export function validateTimelineToolEdits(?.type !== "image" &&!clip.metadata?.motionClip &&clip.outPoint >- sourceLimit(project, (edit.before ?? clip) as Clip) + EPS)+ // A Replace edit swaps the footage: bound it by the NEW media.+ sourceLimit(+ project,+ edit.before && (edit.before as Clip).mediaId === clip.mediaId+ ? (edit.before as Clip)+ : clip,+ ) + EPS))throw new Error("The edit exceeds the source bounds.");}diff --git a/packages/core/src/export/encoder-choice.test.ts b/packages/core/src/export/encoder-choice.test.tsnew file mode 100644index 00000000..41f3ba89--- /dev/null+++ b/packages/core/src/export/encoder-choice.test.ts@@ -0,0 +1,92 @@+import { describe, expect, it } from "vitest";+import {+ describeBrowserEncoderOptions,+ describeEncoderOptions,+ hardwareFamilyOf,+ resolveEncoderChoice,+ webCodecsHardwareHint,+ webCodecsEncoderOptions,+ encoderChoiceForcesNative,+} from "./encoder-choice";++const mac = ["libx264", "libx265", "h264_videotoolbox", "hevc_videotoolbox"];+const win = ["libx264", "libx265", "h264_nvenc", "h264_qsv", "hevc_nvenc", "av1_nvenc"];++describe("resolveEncoderChoice", () => {+ it("maps Auto to the platform hardware encoder and Software to the CPU encoder", () => {+ expect(resolveEncoderChoice({ codec: "h264", choice: "auto", platform: "darwin", available: mac })).toMatchObject({ encoder: "h264_videotoolbox", hardware: true, family: "videotoolbox" });+ expect(resolveEncoderChoice({ codec: "h264", choice: "software", platform: "darwin", available: mac })).toMatchObject({ encoder: "libx264", hardware: false });+ expect(resolveEncoderChoice({ codec: "h265", choice: "hardware", platform: "darwin", available: mac }).encoder).toBe("hevc_videotoolbox");+ });+ it("prefers NVENC over Quick Sync on Windows and maps AV1", () => {+ expect(resolveEncoderChoice({ codec: "h264", choice: "auto", platform: "win32", available: win }).family).toBe("nvenc");+ expect(resolveEncoderChoice({ codec: "h264", choice: "hardware", platform: "win32", available: ["libx264", "h264_qsv"] }).family).toBe("qsv");+ expect(resolveEncoderChoice({ codec: "av1", choice: "auto", platform: "win32", available: win }).encoder).toBe("av1_nvenc");+ });+ it("Auto falls back to software; Hardware never does and says why", () => {+ const softwareOnly = ["libx264"];+ expect(resolveEncoderChoice({ codec: "h264", choice: "auto", platform: "win32", available: softwareOnly })).toMatchObject({ encoder: "libx264", hardware: false });+ const hw = resolveEncoderChoice({ codec: "h264", choice: "hardware", platform: "win32", available: softwareOnly });+ expect(hw.encoder).toBeNull();+ expect(hw.reason).toMatch(/NVIDIA NVENC/);+ });+ it("never picks VAAPI, and reports an encoder missing from the build", () => {+ expect(resolveEncoderChoice({ codec: "h264", choice: "hardware", platform: "linux", available: ["libx264", "h264_vaapi"] }).encoder).toBeNull();+ expect(resolveEncoderChoice({ codec: "h264", choice: "software", platform: "linux", available: ["h264_nvenc"] }).reason).toMatch(/libx264/);+ });+ it("AV1 has no VideoToolbox encoder", () => {+ expect(resolveEncoderChoice({ codec: "av1", choice: "hardware", platform: "darwin", available: ["libsvtav1"] }).reason).toMatch(/no AV1 encoder on this platform/i);+ });+ it("leaves fixed-encoder codecs alone", () => {+ expect(resolveEncoderChoice({ codec: "prores", choice: "hardware", platform: "darwin", available: mac }).encoder).toBeNull();+ });+ it("identifies hardware families", () => {+ expect(hardwareFamilyOf("h264_amf")).toBe("amf");+ expect(hardwareFamilyOf("libx264")).toBeNull();+ });+});++describe("describeEncoderOptions", () => {+ it("shows what each choice uses on this machine", () => {+ const options = describeEncoderOptions({ codec: "h264", platform: "darwin", available: mac });+ expect(options.map((o) => o.available)).toEqual([true, true, true]);+ expect(options[1].detail).toBe("Apple VideoToolbox (h264_videotoolbox)");+ expect(options[2].detail).toBe("libx264, CPU");+ });+ it("marks Hardware unavailable honestly and keeps Auto usable", () => {+ const options = describeEncoderOptions({ codec: "h264", platform: "linux", available: ["libx264"] });+ expect(options.find((o) => o.choice === "hardware")).toMatchObject({ available: false });+ expect(options.find((o) => o.choice === "auto")).toMatchObject({ available: true });+ });+ it("only Auto is selectable while the probe is pending", () => {+ expect(describeEncoderOptions({ codec: "h264", platform: "", available: null }).map((o) => o.available)).toEqual([true, false, false]);+ });+});++describe("browser (WebCodecs) mapping", () => {+ it("reflects the probe result", () => {+ expect(describeBrowserEncoderOptions({ hardware: false, software: true }).map((o) => o.available)).toEqual([true, false, true]);+ expect(describeBrowserEncoderOptions({ hardware: false, software: false }).every((o) => !o.available)).toBe(true);+ });+ it("maps choices onto the hardwareAcceleration hint", () => {+ expect(webCodecsHardwareHint("software")).toBe("prefer-software");+ expect(webCodecsHardwareHint("hardware")).toBe("prefer-hardware");+ expect(webCodecsHardwareHint(undefined)).toBe("prefer-hardware");+ });+});++describe("strict WebCodecs options and native routing", () => {+ it("makes Hardware and Software strict, Auto lenient", () => {+ expect(webCodecsEncoderOptions("software")).toEqual({ hardwareAcceleration: "prefer-software", strictHardwareAcceleration: true });+ expect(webCodecsEncoderOptions("hardware")).toEqual({ hardwareAcceleration: "prefer-hardware", strictHardwareAcceleration: true });+ expect(webCodecsEncoderOptions("auto").strictHardwareAcceleration).toBe(false);+ expect(webCodecsEncoderOptions(undefined).strictHardwareAcceleration).toBe(false);+ });++ it("sends explicit choices for H.264/H.265/AV1 to the ffmpeg sidecar on desktop", () => {+ expect(encoderChoiceForcesNative("hardware", "h264")).toBe(true);+ expect(encoderChoiceForcesNative("software", "h265")).toBe(true);+ expect(encoderChoiceForcesNative("auto", "h264")).toBe(false);+ expect(encoderChoiceForcesNative("hardware", "prores")).toBe(false);+ });+});diff --git a/packages/core/src/export/encoder-choice.ts b/packages/core/src/export/encoder-choice.tsnew file mode 100644index 00000000..fe58b204--- /dev/null+++ b/packages/core/src/export/encoder-choice.ts@@ -0,0 +1,163 @@+/**+ * Encoder picker: Auto, Hardware or Software, with honest capability detection.+ * Pure mapping from (codec, platform, encoders the ffmpeg sidecar reports) to what the export+ * dialog may offer and which ffmpeg encoder a choice resolves to. The browser path maps the same+ * three choices onto WebCodecs `hardwareAcceleration` hints.+ */+export type EncoderChoice = "auto" | "hardware" | "software";+export type HardwareFamily = "videotoolbox" | "nvenc" | "qsv" | "amf";+export type EncoderCodec = "h264" | "h265" | "hevc" | "av1";++export const ENCODER_CHOICES: readonly EncoderChoice[] = ["auto", "hardware", "software"];+export const isEncoderChoice = (value: unknown): value is EncoderChoice => value === "auto" || value === "hardware" || value === "software";++export const HARDWARE_FAMILY_LABEL: Record<HardwareFamily, string> = {+ videotoolbox: "Apple VideoToolbox",+ nvenc: "NVIDIA NVENC",+ qsv: "Intel Quick Sync",+ amf: "AMD AMF",+};++const normalizeCodec = (codec: string): "h264" | "hevc" | "av1" | null =>+ codec === "h264" ? "h264" : codec === "h265" || codec === "hevc" ? "hevc" : codec === "av1" ? "av1" : null;++const SOFTWARE: Record<"h264" | "hevc" | "av1", string> = { h264: "libx264", hevc: "libx265", av1: "libsvtav1" };++/** Hardware encoders in preference order per platform. VAAPI is excluded: encode-args emits no hwupload. */+const HARDWARE: Record<"h264" | "hevc" | "av1", Partial<Record<string, string[]>>> = {+ h264: { darwin: ["h264_videotoolbox"], win32: ["h264_nvenc", "h264_qsv", "h264_amf"], linux: ["h264_nvenc", "h264_qsv"] },+ hevc: { darwin: ["hevc_videotoolbox"], win32: ["hevc_nvenc", "hevc_qsv", "hevc_amf"], linux: ["hevc_nvenc", "hevc_qsv"] },+ av1: { win32: ["av1_nvenc", "av1_qsv", "av1_amf"], linux: ["av1_nvenc", "av1_qsv"] },+};++export function hardwareFamilyOf(encoder: string): HardwareFamily | null {+ if (encoder.endsWith("_videotoolbox")) return "videotoolbox";+ if (encoder.endsWith("_nvenc")) return "nvenc";+ if (encoder.endsWith("_qsv")) return "qsv";+ if (encoder.endsWith("_amf")) return "amf";+ return null;+}++export interface ResolvedEncoder {+ /** ffmpeg encoder name, or null when the choice cannot be honoured. */+ readonly encoder: string | null;+ readonly hardware: boolean;+ readonly family: HardwareFamily | null;+ /** Why the choice is unavailable (set exactly when `encoder` is null). */+ readonly reason?: string;+}++const unavailable = (reason: string): ResolvedEncoder => ({ encoder: null, hardware: false, family: null, reason });++/**+ * Resolve a choice to an ffmpeg encoder. `available` is the verified encoder list from the sidecar+ * (hardware entries are smoke-tested, so a listed one actually opens). Auto prefers hardware and+ * falls back to software; Hardware never falls back, it reports why it cannot run.+ */+export function resolveEncoderChoice(input: {+ codec: string;+ choice: EncoderChoice;+ platform: string;+ available: readonly string[];+}): ResolvedEncoder {+ const codec = normalizeCodec(input.codec);+ if (!codec) return unavailable("This codec is encoded by a fixed encoder; the encoder choice does not apply.");+ const software = SOFTWARE[codec];+ const hasSoftware = input.available.includes(software);+ const hardwareEncoder = (HARDWARE[codec][input.platform] ?? []).find((name) => input.available.includes(name));+ const hw = (name: string): ResolvedEncoder => ({ encoder: name, hardware: true, family: hardwareFamilyOf(name) });+ const sw: ResolvedEncoder = { encoder: software, hardware: false, family: null };+ if (input.choice === "software") {+ return hasSoftware ? sw : unavailable(`This ffmpeg build has no ${software} software encoder.`);+ }+ if (input.choice === "hardware") {+ if (hardwareEncoder) return hw(hardwareEncoder);+ return unavailable(noHardwareReason(codec, input.platform));+ }+ if (hardwareEncoder) return hw(hardwareEncoder);+ return hasSoftware ? sw : unavailable("No usable encoder for this codec was found in this ffmpeg build.");+}++function noHardwareReason(codec: "h264" | "hevc" | "av1", platform: string): string {+ const names = (HARDWARE[codec][platform] ?? []).map((name) => hardwareFamilyOf(name)).filter((f): f is HardwareFamily => f !== null);+ const label = codec === "hevc" ? "H.265" : codec === "av1" ? "AV1" : "H.264";+ if (!names.length) return `${platform === "darwin" ? "VideoToolbox" : "No hardware encoder"} has no ${label} encoder on this platform.`;+ return `No working ${names.map((family) => HARDWARE_FAMILY_LABEL[family]).join(" / ")} ${label} encoder was detected on this machine.`;+}++export interface EncoderOption {+ readonly choice: EncoderChoice;+ readonly label: string;+ /** One line under the label: the encoder it would use, or why it is unavailable. */+ readonly detail: string;+ readonly available: boolean;+}++const CHOICE_LABEL: Record<EncoderChoice, string> = { auto: "Auto", hardware: "Hardware", software: "Software" };++/** What the picker shows for each choice on the desktop (ffmpeg sidecar). */+export function describeEncoderOptions(input: { codec: string; platform: string; available: readonly string[] | null }): EncoderOption[] {+ if (input.available === null) {+ return ENCODER_CHOICES.map((choice) => ({ choice, label: CHOICE_LABEL[choice], detail: "Checking this machine…", available: choice === "auto" }));+ }+ const available = input.available;+ return ENCODER_CHOICES.map((choice) => {+ const resolved = resolveEncoderChoice({ codec: input.codec, choice, platform: input.platform, available });+ if (!resolved.encoder) return { choice, label: CHOICE_LABEL[choice], detail: resolved.reason ?? "Unavailable", available: false };+ const family = resolved.family ? HARDWARE_FAMILY_LABEL[resolved.family] : null;+ const detail = resolved.hardware ? `${family ?? "Hardware"} (${resolved.encoder})` : `${resolved.encoder}, CPU`;+ return { choice, label: CHOICE_LABEL[choice], detail: choice === "auto" ? `Hardware when it can, else software (prefers ${detail})` : detail, available: true };+ });+}++export interface WebCodecsEncoderSupport {+ readonly hardware: boolean;+ readonly software: boolean;+}++/** Browser path: describe the choices from a WebCodecs probe (`null` while probing, or no WebCodecs). */+export function describeBrowserEncoderOptions(support: WebCodecsEncoderSupport | null): EncoderOption[] {+ if (support === null) return ENCODER_CHOICES.map((choice) => ({ choice, label: CHOICE_LABEL[choice], detail: "Checking this browser…", available: choice === "auto" }));+ const anyEncoder = support.hardware || support.software;+ return [+ { choice: "auto", label: "Auto", detail: support.hardware ? "Hardware (WebCodecs) when it can, else software" : support.software ? "Software (WebCodecs)" : "No encoder found in this browser", available: anyEncoder },+ { choice: "hardware", label: "Hardware", detail: support.hardware ? "GPU encoder through WebCodecs" : "This browser reports no hardware encoder for this codec", available: support.hardware },+ { choice: "software", label: "Software", detail: support.software ? "CPU encoder through WebCodecs" : "This browser reports no software encoder for this codec", available: support.software },+ ];+}++/** WebCodecs `hardwareAcceleration` hint for a choice. */+export function webCodecsHardwareHint(choice: EncoderChoice | undefined): "prefer-hardware" | "prefer-software" {+ return choice === "software" ? "prefer-software" : "prefer-hardware";+}++/** WebCodecs backend options for a choice. Hardware and Software are strict: no silent switch to the other kind. */+export function webCodecsEncoderOptions(choice: EncoderChoice | undefined): {+ hardwareAcceleration: "prefer-hardware" | "prefer-software";+ strictHardwareAcceleration: boolean;+} {+ return { hardwareAcceleration: webCodecsHardwareHint(choice), strictHardwareAcceleration: choice === "hardware" || choice === "software" };+}++/** Desktop: an explicit Hardware or Software choice is honoured by the ffmpeg sidecar, whose encoder names the picker shows. */+export function encoderChoiceForcesNative(choice: EncoderChoice | undefined, codec: string): boolean {+ return (choice === "hardware" || choice === "software") && (codec === "h264" || codec === "h265" || codec === "hevc" || codec === "av1");+}++/** Probe WebCodecs for hardware and software encoders of a codec at a size. Never throws. */+export async function probeWebCodecsEncoderSupport(codec: string, width: number, height: number, frameRate = 30): Promise<WebCodecsEncoderSupport> {+ const VideoEncoderCtor = (globalThis as { VideoEncoder?: { isConfigSupported(config: unknown): Promise<{ supported?: boolean; config?: { hardwareAcceleration?: string } }> } }).VideoEncoder;+ if (!VideoEncoderCtor?.isConfigSupported) return { hardware: false, software: false };+ const string = codec === "h265" || codec === "hevc" ? "hvc1.1.6.L93.B0" : codec === "av1" ? "av01.0.05M.08" : codec === "vp9" ? "vp09.00.10.08" : "avc1.640028";+ const test = async (hardwareAcceleration: "prefer-hardware" | "prefer-software"): Promise<boolean> => {+ try {+ const result = await VideoEncoderCtor.isConfigSupported({ codec: string, width, height, framerate: frameRate, bitrate: 5_000_000, hardwareAcceleration });+ return result.supported === true;+ } catch {+ return false;+ }+ };+ // Chromium answers `supported: false` for prefer-hardware when no hardware encoder exists; other engines may treat the hint loosely.+ const [hardware, software] = await Promise.all([test("prefer-hardware"), test("prefer-software")]);+ return { hardware, software };+}diff --git a/packages/core/src/export/export-engine.test.ts b/packages/core/src/export/export-engine.test.tsindex e9fad980..94387e36 100644--- a/packages/core/src/export/export-engine.test.ts+++ b/packages/core/src/export/export-engine.test.ts@@ -341,6 +341,24 @@ describe("ExportEngine", () => {}}+ describe("timecode burn-in", () => {+ beforeEach(() => mockRenderFrame.mockClear());++ it("hands the burn-in setting to every rendered frame", async () => {+ const burnInTimecode = { enabled: true, position: "top-left" as const };+ await drainVideoExport({ ...DEFAULT_VIDEO_SETTINGS, frameRate: 1, width: 640, height: 360, burnInTimecode }, 2);+ expect(mockRenderFrame.mock.calls.length).toBeGreaterThan(0);+ for (const call of mockRenderFrame.mock.calls) expect(call[4]).toEqual({ timecodeBurnIn: burnInTimecode });+ });++ it("renders frames exactly as before when it is off or absent", async () => {+ await drainVideoExport({ ...DEFAULT_VIDEO_SETTINGS, frameRate: 1, width: 640, height: 360, burnInTimecode: { enabled: false } }, 1);+ await drainVideoExport({ ...DEFAULT_VIDEO_SETTINGS, frameRate: 1, width: 640, height: 360 }, 1);+ expect(mockRenderFrame.mock.calls.length).toBeGreaterThan(0);+ for (const call of mockRenderFrame.mock.calls) expect(call).toHaveLength(4);+ });+ });+describe("frame pipelining", () => {afterEach(() => setEncoderBackendFactory(null));diff --git a/packages/core/src/export/export-engine.ts b/packages/core/src/export/export-engine.tsindex 48cdeb5b..2af64540 100644--- a/packages/core/src/export/export-engine.ts+++ b/packages/core/src/export/export-engine.ts@@ -35,6 +35,7 @@ import { getWavEncoder } from "../wasm/wav";import type { EncoderBackend } from "./encoder-backend";import { getEncoderBackendFactory, setEncoderBackendFactory } from "./encoder-backend";import { WebCodecsBackend } from "./webcodecs-backend";+import { webCodecsEncoderOptions } from "./encoder-choice";import { encodeGif, gifPlaybackFps, validateGifFrameBudget, validateGifOptions, type GifFrame } from "./gif-encoder";import { MAX_SEQUENCE_BYTES, packImageSequence, sequenceFrameRange, validateSequenceRange, type SequenceImageFormat } from "./image-sequence";import { declineSmartRender, formatSmartRenderSummary, planSmartRender, type SmartRenderPlan, type SmartRenderSourceInfo } from "./smart-render";@@ -211,7 +212,8 @@ export class ExportEngine {const project = applyCaptionBurnIn(sourceProject, settings.captions);const burnInChanged = project !== sourceProject;// Cached preview frames contain every caption, so they cannot be reused when some are excluded.- const cachedFrames = burnInChanged ? undefined : exportOptions.cachedFrames;+ // The timecode overlay is not in the preview cache either.+ const cachedFrames = burnInChanged || settings.burnInTimecode?.enabled ? undefined : exportOptions.cachedFrames;let cachedFrameCount = 0;if (!this.mediabunny) {@@ -241,7 +243,12 @@ export class ExportEngine {const encoderBackendFactory = getEncoderBackendFactory();const backend: EncoderBackend = encoderBackendFactory? encoderBackendFactory(this.mediabunny)- : new WebCodecsBackend(this.mediabunny!);+ : new WebCodecsBackend(this.mediabunny!, {+ ...webCodecsEncoderOptions(fullSettings.encoderChoice),+ ...(exportOptions.encoderPreference === "prefer-software" && fullSettings.encoderChoice !== "hardware"+ ? { hardwareAcceleration: "prefer-software" as const }+ : {}),+ });if (backend.normalizesProResToH264 && (fullSettings.codec === "prores" || fullSettings.codec === "dnxhr" || isBroadcastCodec(fullSettings.codec) || fullSettings.format === "mxf" || hasBroadcastOptions(fullSettings.broadcast))) {return { success: false, error: this.createError("UNSUPPORTED_CODEC", "ProRes, DNxHR, XDCAM HD422, AVC-Intra, MXF, mono audio tracks and timecode tracks require the desktop encoder. Choose H.264 / MP4 for browser export.", "preparing") };@@ -457,6 +464,7 @@ export class ExportEngine {exportStart + time,fullSettings.width,fullSettings.height,+ ...(fullSettings.burnInTimecode?.enabled ? [{ timecodeBurnIn: fullSettings.burnInTimecode }] : []),), abortController.signal, "rendering", (lateFrame) => lateFrame.image.close(), RENDER_FRAME_WATCHDOG_MS);renderMsTotal += performance.now() - renderStart;if (frame === segment.startFrame && segment.startFrame === 0) phase("first-frame-rendered");@@ -645,6 +653,8 @@ export class ExportEngine {totalFrames: number,): Promise<SmartRenderPlan | null> {if (!backend.smartRender || settings.smartRender === false || !this.mediabunny) return null;+ // Stream-copied spans carry no overlay: a timecode burn-in re-renders every frame.+ if (settings.burnInTimecode?.enabled) return null;// Smart render joins stream-copied spans with a stereo audio pass; a mono-track or broadcast delivery is rendered in full.if (isBroadcastCodec(settings.codec) || wantsMonoTracks(settings.broadcast) || settings.broadcast?.mxfPattern === "opatom") return null;// Stream-copied source packets carry the source's colour, so a Rec.2020 / HDR export re-renders everything.diff --git a/packages/core/src/export/export-queue.test.ts b/packages/core/src/export/export-queue.test.tsindex 2ed001e2..a5e9e2b7 100644--- a/packages/core/src/export/export-queue.test.ts+++ b/packages/core/src/export/export-queue.test.ts@@ -14,6 +14,7 @@ import {nextRunnableJob,removeExportJob,reportExportProgress,+ resetExportProgress,retryExportJob,setExportQueuePaused,startExportJob,@@ -62,6 +63,19 @@ describe("export queue model", () => {expect(estimateEtaMs(1000, 1)).toBeUndefined();});+ it("resets progress, phase and ETA for a re-run so the failed attempt's value does not freeze the bar", () => {+ let s = startExportJob(build("a"), "a", 0);+ s = reportExportProgress(s, "a", 0.8, "Encoding", 4000);+ expect(s.jobs[0].progress).toBe(0.8);+ s = resetExportProgress(s, "a", 5000);+ expect(s.jobs[0]).toMatchObject({ status: "running", progress: 0, phase: "Preparing", elapsedMs: 0, etaMs: undefined, startedAt: 5000, attempts: 1 });+ s = reportExportProgress(s, "a", 0.1, "Rendering", 5500);+ expect(s.jobs[0]).toMatchObject({ progress: 0.1, phase: "Rendering", elapsedMs: 500 });+ expect(s.jobs).toHaveLength(1);+ const queued = build("b");+ expect(resetExportProgress(queued, "b")).toBe(queued);+ });+it("ignores progress for jobs that are not running", () => {const s = build("a");expect(reportExportProgress(s, "a", 0.5, "x", 10)).toBe(s);diff --git a/packages/core/src/export/export-queue.ts b/packages/core/src/export/export-queue.tsindex 9bbd25ca..9b1283e8 100644--- a/packages/core/src/export/export-queue.ts+++ b/packages/core/src/export/export-queue.ts@@ -203,6 +203,15 @@ export function reportExportProgress(});}+/** A re-run of the same job (same attempt owner) starts from zero: progress, ETA and phase of the failed attempt are dropped. */+export function resetExportProgress(state: ExportQueueState, id: string, now?: number): ExportQueueState {+ return patch(state, id, (job) =>+ job.status !== "running"+ ? job+ : { ...job, progress: 0, phase: "Preparing", elapsedMs: 0, etaMs: undefined, ...(now === undefined ? {} : { startedAt: now }) },+ );+}+export function completeExportJob(state: ExportQueueState,id: string,diff --git a/packages/core/src/export/index.ts b/packages/core/src/export/index.tsindex c15e6994..6bb6def2 100644--- a/packages/core/src/export/index.ts+++ b/packages/core/src/export/index.ts@@ -1,6 +1,7 @@export * from "./types";export * from "./color-output";export * from "./broadcast";+export * from "./encoder-choice";export * from "./export-engine";export * from "./loudness-export";export * from "./export-queue";diff --git a/packages/core/src/export/types.ts b/packages/core/src/export/types.tsindex 6f410982..a3e9337e 100644--- a/packages/core/src/export/types.ts+++ b/packages/core/src/export/types.ts@@ -2,6 +2,7 @@ import type { LoudnessTargetSettings } from "../audio/loudness/loudness-normalizimport type { LoudnessExportReport } from "./loudness-export";import type { ProxyExportReport } from "../media/proxy-workflow";import type { CaptionExportSettings } from "../captions/caption-export";+import type { TimecodeBurnInSettings } from "../video/burn-in";import type { BroadcastCodec, BroadcastDeliverySettings } from "./broadcast";export type UpscaleQuality = "fast" | "balanced" | "quality";@@ -66,6 +67,8 @@ export interface VideoExportSettings {rateControl?: RateControl;maxBitrate?: number;encodeMode?: "fast" | "balanced" | "smallest";+ /** Encoder picker: Auto (hardware when it works), Hardware (never falls back) or Software. Absent = Auto. */+ encoderChoice?: "auto" | "hardware" | "software";quality: number;keyframeInterval: number;audioSettings: AudioExportSettings;@@ -91,6 +94,11 @@ export interface VideoExportSettings {* track. Omitted = every caption is burned in and nothing else is written.*/captions?: CaptionExportSettings;+ /**+ * One-click "Burn in timecode": the sequence timecode (or the topmost clip's source timecode) is drawn into+ * every exported frame, over all tracks and captions. Frames are always re-rendered (no stream copy).+ */+ burnInTimecode?: TimecodeBurnInSettings;}export interface AudioExportSettings {@@ -227,6 +235,12 @@ export interface ExportFrameSource {export interface ExportVideoOptions {cachedFrames?: ExportFrameSource;+ /**+ * Per-run encoder preference for the browser (WebCodecs) backend, used by the queue's automatic re-run after a+ * hardware session failed. Only takes effect when the export's encoderChoice is auto/undefined; scoped to this+ * run, never stored globally.+ */+ encoderPreference?: "prefer-hardware" | "prefer-software";}export const DEFAULT_VIDEO_SETTINGS: VideoExportSettings = {diff --git a/packages/core/src/export/webcodecs-backend.ts b/packages/core/src/export/webcodecs-backend.tsindex ab273693..0e35594f 100644--- a/packages/core/src/export/webcodecs-backend.ts+++ b/packages/core/src/export/webcodecs-backend.ts@@ -30,6 +30,8 @@ type VideoCodecName = Parameters<interface WebCodecsBackendOptions {hardwareAcceleration?: HardwarePreference;+ /** An explicit Hardware or Software choice: never retry with no-preference, fail instead of silently switching encoder kind. */+ strictHardwareAcceleration?: boolean;videoCodecs?: VideoCodecName[];// The resolution clamp (export-engine) exists to bound browser-tab memory.// On desktop, frames stream to disk one at a time and the hardware encoder@@ -45,6 +47,7 @@ export class WebCodecsBackend implements EncoderBackend {private readonly mediabunny: MediaBunnyModule;private readonly hardwareAcceleration: HardwarePreference;+ private readonly strictHardwareAcceleration: boolean;private readonly videoCodecPreference?: VideoCodecName[];private output: OutputInstance | null = null;private videoSource: VideoSampleSourceInstance | null = null;@@ -107,6 +110,7 @@ export class WebCodecsBackend implements EncoderBackend {constructor(mediabunny: MediaBunnyModule, options?: WebCodecsBackendOptions) {this.mediabunny = mediabunny;this.hardwareAcceleration = options?.hardwareAcceleration ?? "prefer-hardware";+ this.strictHardwareAcceleration = options?.strictHardwareAcceleration === true;this.videoCodecPreference = options?.videoCodecs;this.requiresWebCodecsClamping = options?.clampResolution ?? true;}@@ -188,7 +192,9 @@ export class WebCodecsBackend implements EncoderBackend {const hardwarePreferences: HardwarePreference[] =this.hardwareAcceleration === "no-preference"? ["no-preference"]- : [this.hardwareAcceleration, "no-preference"];+ : this.strictHardwareAcceleration+ ? [this.hardwareAcceleration]+ : [this.hardwareAcceleration, "no-preference"];let selectedHardwareAcceleration: HardwarePreference = "no-preference";let videoCodec: VideoCodecName | null = null;@@ -531,7 +537,11 @@ export class WebCodecsBackend implements EncoderBackend {const level = area <= 414_720 ? "1e" : area <= 921_600 ? "1f" : area <= 2_097_152 ? "28" : area <= 8_912_896 ? "33" : "34";const codecs = [`avc1.6400${level}`, `avc1.4d00${level}`, `avc1.4200${level}`];const preferences: HardwarePreference[] =- this.hardwareAcceleration === "no-preference" ? ["no-preference"] : [this.hardwareAcceleration, "no-preference"];+ this.hardwareAcceleration === "no-preference"+ ? ["no-preference"]+ : this.strictHardwareAcceleration+ ? [this.hardwareAcceleration]+ : [this.hardwareAcceleration, "no-preference"];let chosen: VideoEncoderConfig | null = null;for (const hardwareAcceleration of preferences) {for (const codec of codecs) {diff --git a/packages/core/src/index.ts b/packages/core/src/index.tsindex 2d052afe..fff668dd 100644--- a/packages/core/src/index.ts+++ b/packages/core/src/index.ts@@ -46,11 +46,13 @@ export {validateGifOptions,} from "./export/gif-encoder";export * from "./export/broadcast";+export * from "./export/encoder-choice";export * from "./color/source-color";export * from "./color/cube-lut";export * from "./color/lut-json";export * from "./color/looks";export * from "./color/input-transform";+export * from "./color/camera-log";export * from "./color/hdr-working";export * from "./color/hdr-effects";export * from "./color/hdr-light-level";@@ -152,6 +154,7 @@ export { planTrackSelect, type TrackSelectItem, type TrackSelectKind, type Trackexport { zoomAtPoint, zoomToRange, type ViewState, type ZoomLimits } from "./editing/timeline-view";export { planRippleDelete, planCloseGap, planCloseGapBeforeClip, planRemoveGaps, planSilenceCut } from "./editing/ripple-delete";export { planClipDropResolution, clipDropOptionsFromModifiers, snapshotClipOrigins, type ClipDropMode, type ClipDropOptions, type ClipOrigin } from "./editing/clip-drop";+export { planClipSpeedEdit, prepareMultiRateStretch, type MultiRateStretch, resolveClipRate, type ClipSpeedEdit, type ClipSpeedOptions } from "./editing/clip-speed-edit";export { planRippleTrimToPlayhead, type RippleTrimToPlayheadOptions } from "./editing/ripple-trim-playhead";export {isSyncLocked,@@ -178,6 +181,22 @@ export {sourceDropError,sourceTargetKind,} from "./editing/source-edit";+export {+ findReplaceTarget,+ planFitToFill,+ planReplaceEdit,+ resolveFitToFill,+} from "./editing/replace-fit";+export type {+ FitToFillPlan,+ FitToFillRequest,+ ReplaceAlignment,+ ReplaceEditPlan,+ ReplaceEditRequest,+ ResolvedFitToFill,+ ResolvedReplace,+} from "./editing/replace-fit";+export { CLIP_SPEED_MAX, CLIP_SPEED_MIN } from "./editing/speed-limits";export type {ResolvedSourceEdit,SourceComponent,@@ -191,10 +210,13 @@ export * from "./media/interpretation";export * from "./media/smart-bins";export * from "./media/proxy-workflow";export * from "./media/desktop-ingest";+export * from "./media/proxy-presets";export type { MediaItemPatch, ClipLabelPatch, MediaOrganizeParams } from "./actions/handlers/media-organize";export { buildBenchProject } from "./perf/bench-project";export type { BenchProjectOptions } from "./perf/bench-project";export type { ClipPlacement, NewTrackPlacement } from "./editing/premiere-edits";+export { findReverseMatch, timelineTimeForSource } from "./editing/reverse-match-frame";+export type { ReverseMatch } from "./editing/reverse-match-frame";export {canTargetTrack,chooseTrackForMedia,@@ -221,6 +243,7 @@ export {formatSrtTime,CAPTION_EXPORT_FORMATS,CAPTION_FORMAT_INFO,+ decodeCaptionText,exportCaptionFile,parseCaptionBytes,} from "./captions/caption-formats";@@ -232,6 +255,8 @@ export type {CaptionParseResult,CaptionTrackSummary,} from "./captions/caption-formats";+export { parseTtml, isTtmlContent } from "./captions/ttml";+export { parseSbv, encodeSbv, isSbvContent } from "./captions/sbv";export { encodeScc, exportScc, parseScc, isSccContent } from "./captions/scc";export type { CaptionFormatIssue, SccExportResult, SccOptions, SccParseOptions, SccParseResult } from "./captions/scc";export { encodeStl, exportStl, parseStl, isStlContent } from "./captions/ebu-stl";@@ -263,6 +288,26 @@ export type {EmbeddedCaptionPlan,SidecarFile,} from "./captions/caption-export";+export {+ SPEAKER_PALETTE,+ defaultSpeakerName,+ paletteColor,+ cosineDistance,+ clusterEmbeddings,+ labelCuesBySpeaker,+ findSpeakerProfile,+ ensureSpeakerProfiles,+ renameSpeakerProfile,+ applySpeakerStyles,+ detectionCues,+ mirrorSpeakersToTranslations,+} from "./captions/diarization";+export type { SpeakerProfile, SpeakerPosition, ClusterOptions } from "./captions/diarization";+export {+ computeSpeakerEmbedding,+ EMBEDDING_SAMPLE_RATE,+ SPEAKER_EMBEDDING_DIMENSIONS,+} from "./captions/speaker-embedding";export {buildTranscript,wordRange,@@ -296,6 +341,15 @@ export type { TranscriptionProvider, TranscriptionRequest } from "./captions/traexport * from "./review/review-comments";export { nextMarker, prevMarker, markersInRange, markerAt, sortMarkers } from "./editing/marker-nav";export type { MarkerNavOptions } from "./editing/marker-nav";+export {+ sourceToTimelineTime,+ timelineToSourceTime,+ sourceTimeInClip,+ resolveClipMarkers,+ sourceTimeForTimelineMarker,+ flattenClipMarkers,+} from "./editing/clip-markers";+export type { ClipMarkerScope, ResolvedClipMarker } from "./editing/clip-markers";export {chaptersText,markersCsv,@@ -318,3 +372,18 @@ export type {ParsedLoc,} from "./interchange/marker-export";export * from "./export/surround-export";++export {+ translateCaptionTrack,+ uniqueCaptionTrackId,+ buildTranslationPrompt,+ parseTranslationReply,+ isAbortError,+} from "./captions/caption-translate";+export type {+ CaptionTranslator,+ CaptionTranslationProgress,+ CaptionTranslationResult,+ TranslateCaptionTrackOptions,+} from "./captions/caption-translate";+export * from "./tasks";diff --git a/packages/core/src/interchange/model.ts b/packages/core/src/interchange/model.tsindex ad41ae40..e9ff88d3 100644--- a/packages/core/src/interchange/model.ts+++ b/packages/core/src/interchange/model.ts@@ -43,6 +43,16 @@ export interface SeqMedia {readonly mediaItemId?: string;}+/** A marker on a clip (clip + master-clip markers merged); `sec` is in the media's own (source) time. */+export interface SeqClipMarker {+ readonly sec: number;+ readonly name: string;+ readonly durationSec?: number;+ readonly comment?: string;+ readonly color?: string;+ readonly kind?: MarkerKind;+}+export interface SeqClip {readonly id: string;readonly name: string;@@ -73,6 +83,8 @@ export interface SeqClip {* clips of the active angle's media). FCPXML turns it into an `mc-clip`; the other formats ignore it.*/readonly multicam?: { readonly sourceId: string; readonly angleId: string };+ /** Clip markers merged with the media's master-clip markers, in source time (XMEML writes them in the clipitem). */+ readonly markers?: readonly SeqClipMarker[];/** EDL import: the event's reel name and source timecodes, kept on the clip as `metadata.edl`. */readonly edl?: { readonly reel: string; readonly sourceIn: string; readonly sourceOut: string; readonly event: number };}@@ -389,6 +401,17 @@ export function projectToSequence(const speedRaw = clip.speed ?? 1;const speed = Math.abs(speedRaw) > 0 ? Math.abs(speedRaw) : 1;const multicam = noteMulticam(clip);+ const clipMarkers = [...(mediaById.get(clip.mediaId)?.markers ?? []), ...(clip.markers ?? [])]+ .filter((m) => options.includeMarkers !== false && m.time >= clip.inPoint - 1e-6 && m.time <= clip.outPoint + 1e-6)+ .sort((a, b) => a.time - b.time)+ .map((m) => ({+ sec: m.time,+ name: m.label,+ ...(m.duration ? { durationSec: m.duration } : {}),+ ...(m.comment ? { comment: m.comment } : {}),+ ...(m.color ? { color: m.color } : {}),+ ...(m.kind && m.kind !== "comment" ? { kind: m.kind } : {}),+ }));return {id: clip.id,name: media.name,@@ -403,6 +426,7 @@ export function projectToSequence(volume: clip.volume ?? 1,withAudio: isVisualTrack(track) && media.kind === "video" && media.hasAudio,...(multicam ? { multicam } : {}),+ ...(clipMarkers.length ? { markers: clipMarkers } : {}),};};@@ -815,6 +839,19 @@ export function sequenceToTimeline(: {}),...(sc.speed !== 1 ? { speed: sc.speed } : {}),...(sc.reversed ? { reversed: true } : {}),+ ...(sc.markers?.length+ ? {+ markers: sc.markers.map((m) => ({+ id: `marker-${makeId()}`,+ time: m.sec,+ label: m.name,+ color: m.color ?? DEFAULT_IMPORTED_MARKER_COLOR,+ ...(m.durationSec && m.durationSec > 0 ? { duration: m.durationSec } : {}),+ ...(m.comment ? { comment: m.comment } : {}),+ ...(m.kind ? { kind: m.kind } : {}),+ })),+ }+ : {}),};idForSeq.set(sc, clip.id);clips.push(clip);diff --git a/packages/core/src/interchange/xmeml.ts b/packages/core/src/interchange/xmeml.tsindex 9eaa260f..9cd75da2 100644--- a/packages/core/src/interchange/xmeml.ts+++ b/packages/core/src/interchange/xmeml.ts@@ -20,6 +20,7 @@ import type {InterchangeReport,Sequence,SeqClip,+ SeqClipMarker,SeqMarker,SeqMedia,SeqMulticam,@@ -156,6 +157,15 @@ export function serializeXmeml(input: Sequence): string {}};+ /** Clip + master-clip markers as <marker> children of the clipitem; in/out are source frames of the media. */+ const writeClipMarkers = (clip: SeqClip, media: SeqMedia): void => {+ for (const m of clip.markers ?? []) {+ const inF = sourceFrames(media, m.sec);+ const outF = m.durationSec && m.durationSec > 0 ? sourceFrames(media, m.sec + m.durationSec) : -1;+ w.open("marker").leaf("name", m.name).leaf("comment", m.comment ?? "").leaf("in", inF).leaf("out", outF).close("marker");+ }+ };+const writeAudioFilters = (clip: SeqClip): void => {if (clip.volume === 1) return;w.open("filter").open("effect");@@ -334,6 +344,7 @@ export function serializeXmeml(input: Sequence): string {w.leaf("in", sourceFrames(media, clip.inSec)).leaf("out", sourceFrames(media, clip.outSec));writeFile(media);writeMulticam(clip, seq);+ writeClipMarkers(clip, media);writeVideoFilters(clip);const partner = audioIndexOfLinked.get(clip.id);writeLink(id, "video", vi + 1, ci + 1);@@ -406,6 +417,7 @@ export function serializeXmeml(input: Sequence): string {w.leaf("start", clip.startFrame).leaf("end", clip.endFrame);w.leaf("in", sourceFrames(media, clip.inSec)).leaf("out", sourceFrames(media, clip.outSec));writeFile(media);+ if (entry.pairedVideo === undefined) writeClipMarkers(clip, media);w.open("sourcetrack").leaf("mediatype", "audio").leaf("trackindex", 1).close("sourcetrack");writeAudioRetime(clip);writeAudioFilters(clip);@@ -689,6 +701,20 @@ export function parseXmeml(source: string): { sequence: Sequence; report: Intercconst volume = levelParam !== undefined && Number.isFinite(Number(levelParam)) ? Number(levelParam) : 1;if (!asBool(childText(el, "enabled"), true)) warnings.push(`Clip "${name}" is disabled in the source; it was imported enabled.`);const multicam = media && kind === "video" ? parseMulticam(el, media.key) : undefined;+ const clipMarkers: SeqClipMarker[] = childrenNamed(el, "marker").flatMap((m) => {+ const inM = childNumber(m, "in");+ if (inM === undefined || inM < 0) return [];+ const outM = childNumber(m, "out");+ const comment = childText(m, "comment");+ return [+ {+ sec: framesToSeconds(inM, clipRate),+ name: childText(m, "name") ?? "",+ ...(outM !== undefined && outM > inM ? { durationSec: framesToSeconds(outM - inM, clipRate) } : {}),+ ...(comment ? { comment } : {}),+ },+ ];+ });clips.push({clip: {id: el.attrs.id ?? `${kind}-${index}-${clips.length}`,@@ -705,6 +731,7 @@ export function parseXmeml(source: string): { sequence: Sequence; report: IntercwithAudio: false,...(nested ? { nested } : {}),...(multicam ? { multicam } : {}),+ ...(clipMarkers.length && !nested ? { markers: clipMarkers } : {}),},elementId: el.attrs.id,linkRefs: childrenNamed(el, "link").map((l) => childText(l, "linkclipref") ?? ""),diff --git a/packages/core/src/media/desktop-ingest.ts b/packages/core/src/media/desktop-ingest.tsindex acd8d6f3..dc7a72d4 100644--- a/packages/core/src/media/desktop-ingest.ts+++ b/packages/core/src/media/desktop-ingest.ts@@ -16,6 +16,7 @@ import { proxyMatchKey, type ProxyDisplayState } from "./proxy-workflow";export const DESKTOP_PROXY_CODECS: readonly { id: DesktopProxyCodec; label: string; extension: "mov" | "mp4" }[] = [{ id: "prores-proxy", label: "ProRes 422 Proxy (.mov)", extension: "mov" },+ { id: "dnxhr-lb", label: "DNxHR LB (.mov)", extension: "mov" },{ id: "h264", label: "H.264 (.mp4)", extension: "mp4" },];@@ -28,7 +29,7 @@ export const DESKTOP_PROXY_SIZES: readonly { id: DesktopProxySize; label: stringexport const DEFAULT_DESKTOP_PROXY_PROFILE: DesktopProxyProfile = { codec: "h264", size: "half" };-export const isDesktopProxyCodec = (value: unknown): value is DesktopProxyCodec => value === "prores-proxy" || value === "h264";+export const isDesktopProxyCodec = (value: unknown): value is DesktopProxyCodec => value === "prores-proxy" || value === "h264" || value === "dnxhr-lb";export const isDesktopProxySize = (value: unknown): value is DesktopProxySize =>value === "half" || value === "quarter" || value === "720p" || value === "1080p";@@ -56,7 +57,7 @@ export const resolveDesktopProxyProfile = (project: Pick<Project, "mediaLibrary"export const resolveDesktopConcurrency = (project: Pick<Project, "mediaLibrary">): 1 | 2 =>project.mediaLibrary.desktopIngest?.concurrency ?? 1;-export const desktopProxyExtension = (codec: DesktopProxyCodec): "mov" | "mp4" => (codec === "prores-proxy" ? "mov" : "mp4");+export const desktopProxyExtension = (codec: DesktopProxyCodec): "mov" | "mp4" => (codec === "h264" ? "mp4" : "mov");export function describeDesktopProxyProfile(profile: DesktopProxyProfile): string {const codec = DESKTOP_PROXY_CODECS.find((entry) => entry.id === profile.codec)?.label ?? profile.codec;diff --git a/packages/core/src/media/ffmpeg-fallback.ts b/packages/core/src/media/ffmpeg-fallback.tsindex 27e9639f..ed3caadc 100644--- a/packages/core/src/media/ffmpeg-fallback.ts+++ b/packages/core/src/media/ffmpeg-fallback.ts@@ -1,6 +1,35 @@import type { ExportProgress } from "../export/types";const FFMPEG_CORE_BASE_URL = "https://unpkg.com/@ffmpeg/[email protected]/dist/esm";+const FFMPEG_DOWNLOAD_ATTEMPTS = 3;++/**+ * Downloads one ffmpeg core file. A CDN can answer 200 and then cut the body short (seen on CI: a 26.9 MB wasm+ * arrived as ~0.3 MB and failed to compile, which broke every ffmpeg-backed feature for that page load), so the+ * byte count is checked against Content-Length and a short or failed download is retried.+ */+async function fetchCoreFile(filename: string, signal: AbortSignal): Promise<ArrayBuffer> {+ let lastError: unknown;+ for (let attempt = 1; attempt <= FFMPEG_DOWNLOAD_ATTEMPTS; attempt++) {+ try {+ const response = await fetch(`${FFMPEG_CORE_BASE_URL}/${filename}`, { signal, ...(attempt > 1 ? { cache: "reload" as const } : {}) });+ if (!response.ok) throw new Error(`FFmpeg download failed (${response.status}): ${filename}`);+ const bytes = await response.arrayBuffer();+ const expected = Number(response.headers?.get("content-length"));+ // Content-Length is the encoded size; only compare when the body was not transparently decompressed.+ if (!response.headers?.get("content-encoding") && Number.isFinite(expected) && expected > 0 && bytes.byteLength !== expected) {+ throw new Error(`FFmpeg download truncated (${bytes.byteLength} of ${expected} bytes): ${filename}`);+ }+ return bytes;+ } catch (error) {+ if (signal.aborted) throw error;+ lastError = error;+ if (attempt < FFMPEG_DOWNLOAD_ATTEMPTS) await new Promise((r) => setTimeout(r, 500 * attempt));+ }+ }+ throw lastError;+}+type FFmpegInstance = {load(options?: {coreURL?: string;@@ -151,9 +180,7 @@ export class FFmpegFallback {this.ffmpeg = instance;const download = async (filename: string, mime: string): Promise<string> => {try {- const response = await fetch(`${FFMPEG_CORE_BASE_URL}/${filename}`, { signal: controller.signal });- if (!response.ok) throw new Error(`FFmpeg download failed (${response.status}): ${filename}`);- const bytes = await response.arrayBuffer();+ const bytes = await fetchCoreFile(filename, controller.signal);checkAborted();const url = URL.createObjectURL(new Blob([bytes], { type: mime }));urls.push(url);diff --git a/packages/core/src/media/proxy-presets.test.ts b/packages/core/src/media/proxy-presets.test.tsnew file mode 100644index 00000000..2fcc2f0f--- /dev/null+++ b/packages/core/src/media/proxy-presets.test.ts@@ -0,0 +1,29 @@+import { describe, expect, it } from "vitest";+import { DEFAULT_PROXY_PRESET_ID, PROXY_PRESETS, isIntermediateProxyCodec, isProxyPresetId, proxyPresetById, proxyPresetForProfile } from "./proxy-presets";+import { desktopProxyDimensions, desktopProxyExtension, isDesktopProxyProfile } from "./desktop-ingest";++describe("proxy presets", () => {+ it("offers ProRes Proxy, H.264 half and quarter, and DNxHR LB, all valid saved profiles", () => {+ expect(PROXY_PRESETS.map((p) => p.id)).toEqual(["prores-proxy", "h264-half", "h264-quarter", "dnxhr-lb"]);+ for (const preset of PROXY_PRESETS) expect(isDesktopProxyProfile(preset.profile)).toBe(true);+ });+ it("round-trips a profile to its preset and reports custom combinations as null", () => {+ for (const preset of PROXY_PRESETS) expect(proxyPresetForProfile(preset.profile)).toBe(preset.id);+ expect(proxyPresetForProfile({ codec: "h264", size: "1080p" })).toBeNull();+ expect(isProxyPresetId("dnxhr-lb")).toBe(true);+ expect(isProxyPresetId("nope")).toBe(false);+ expect(proxyPresetById(DEFAULT_PROXY_PRESET_ID).profile.codec).toBe("h264");+ });+ it("sizes and containers follow the preset", () => {+ expect(desktopProxyDimensions(3840, 2160, proxyPresetById("h264-quarter").profile.size)).toEqual({ width: 960, height: 540 });+ expect(desktopProxyDimensions(3840, 2160, proxyPresetById("dnxhr-lb").profile.size)).toEqual({ width: 1920, height: 1080 });+ expect(desktopProxyExtension("dnxhr-lb")).toBe("mov");+ expect(desktopProxyExtension("prores-proxy")).toBe("mov");+ expect(desktopProxyExtension("h264")).toBe("mp4");+ });+ it("gives intermediate codecs an H.264 preview twin", () => {+ expect(isIntermediateProxyCodec("dnxhr-lb")).toBe(true);+ expect(isIntermediateProxyCodec("prores-proxy")).toBe(true);+ expect(isIntermediateProxyCodec("h264")).toBe(false);+ });+});diff --git a/packages/core/src/media/proxy-presets.ts b/packages/core/src/media/proxy-presets.tsnew file mode 100644index 00000000..bf858b53--- /dev/null+++ b/packages/core/src/media/proxy-presets.ts@@ -0,0 +1,41 @@+import type { DesktopProxyCodec, DesktopProxyProfile } from "../types/project";++/**+ * Named proxy presets (Premiere's Create Proxies presets). A preset is a codec + frame-size pair that+ * maps onto the per-project `DesktopProxyProfile`, so the choice is saved with the project and the+ * ingest / Create Proxies paths build from one profile. Pure: the Electron main process turns a+ * profile into ffmpeg arguments (apps/desktop/src/main/ingest/proxy-args.ts).+ */+export type ProxyPresetId = "prores-proxy" | "h264-half" | "h264-quarter" | "dnxhr-lb";++export interface ProxyPreset {+ readonly id: ProxyPresetId;+ readonly label: string;+ readonly description: string;+ readonly profile: DesktopProxyProfile;+}++export const PROXY_PRESETS: readonly ProxyPreset[] = [+ { id: "prores-proxy", label: "ProRes Proxy", description: "ProRes 422 Proxy .mov at half size. Light to decode, opens in other editors.", profile: { codec: "prores-proxy", size: "half" } },+ { id: "h264-half", label: "H.264 1/2 resolution", description: "H.264 .mp4 at half size. Small and plays everywhere.", profile: { codec: "h264", size: "half" } },+ { id: "h264-quarter", label: "H.264 1/4 resolution", description: "H.264 .mp4 at quarter size. Smallest files, fastest scrubbing on weak machines.", profile: { codec: "h264", size: "quarter" } },+ { id: "dnxhr-lb", label: "DNxHR LB", description: "DNxHR LB .mov at half size. Intra-frame, for Avid-style workflows.", profile: { codec: "dnxhr-lb", size: "half" } },+];++export const DEFAULT_PROXY_PRESET_ID: ProxyPresetId = "h264-half";++export function isProxyPresetId(value: unknown): value is ProxyPresetId {+ return PROXY_PRESETS.some((preset) => preset.id === value);+}++export function proxyPresetById(id: ProxyPresetId): ProxyPreset {+ return PROXY_PRESETS.find((preset) => preset.id === id) ?? PROXY_PRESETS[1];+}++/** The preset a stored profile equals, or null when it is a custom codec/size combination. */+export function proxyPresetForProfile(profile: DesktopProxyProfile): ProxyPresetId | null {+ return PROXY_PRESETS.find((preset) => preset.profile.codec === profile.codec && preset.profile.size === profile.size)?.id ?? null;+}++/** Intermediate codecs (ProRes, DNxHR) are not decodable by the preview player, so they get an H.264 preview twin. */+export const isIntermediateProxyCodec = (codec: DesktopProxyCodec): boolean => codec !== "h264";diff --git a/packages/core/src/playback/playback-controller.ts b/packages/core/src/playback/playback-controller.tsindex 9ff7ce99..753c37c1 100644--- a/packages/core/src/playback/playback-controller.ts+++ b/packages/core/src/playback/playback-controller.ts@@ -626,6 +626,7 @@ export class PlaybackController {pan: 0,muted: track.muted,solo: track.solo,+ soloSafe: track.soloSafe === true,effects: [],});@@ -667,7 +668,7 @@ export class PlaybackController {pan: getPanFromAudioEffects(clip.audioEffects || []),effects: getPreviewAudioEffects(clip.audioEffects || []),speed: clip.speed ?? 1,- ...resolveClipPlaybackAudioParams(clip, timeline),+ ...resolveClipPlaybackAudioParams(clip, timeline, mediaItem),fadeIn: clip.fade?.fadeIn,fadeOut: clip.fade?.fadeOut,fadeOrigin: clip.fade?.origin,diff --git a/packages/core/src/raw/index.ts b/packages/core/src/raw/index.tsindex e2c83647..5814d516 100644--- a/packages/core/src/raw/index.ts+++ b/packages/core/src/raw/index.ts@@ -7,3 +7,4 @@ export * from "./settings";export * from "./develop";export * from "./formats";export * from "./raw-media";+export * from "./inspect";diff --git a/packages/core/src/raw/inspect.ts b/packages/core/src/raw/inspect.tsnew file mode 100644index 00000000..a384eb2c--- /dev/null+++ b/packages/core/src/raw/inspect.ts@@ -0,0 +1,29 @@+import { developedSize } from "./develop";+import type { DngRaw } from "./dng";+import { defaultRawSettings } from "./settings";+import { asShotKelvinTint } from "./color";+import type { RawInspection } from "./raw-media";++export function describeCfa(raw: DngRaw): string {+ return raw.samplesPerPixel === 3 ? "RGB" : raw.cfa.map((c) => "RGB"[c]).join("");+}++export function inspectDngRaw(raw: DngRaw): RawInspection {+ const settings = defaultRawSettings(raw);+ const size = developedSize(raw, settings);+ const asShot = asShotKelvinTint(raw);+ return {+ info: {+ format: "dng",+ developedBy: "openreel",+ make: raw.make,+ model: raw.model,+ bitDepth: raw.bitsPerSample,+ cfa: describeCfa(raw),+ settings,+ asShot: { temperature: asShot.kelvin, tint: asShot.tint },+ },+ width: size.width,+ height: size.height,+ };+}diff --git a/packages/core/src/raw/raw-media.ts b/packages/core/src/raw/raw-media.tsindex a6e917b7..5ed59ba2 100644--- a/packages/core/src/raw/raw-media.ts+++ b/packages/core/src/raw/raw-media.ts@@ -1,8 +1,10 @@-import { developRaw, developedSize, type DevelopedFrame } from "./develop";-import { decodeDng, looksLikeDng, type DngRaw } from "./dng";-import { RawDecodeError } from "./tiff";-import { defaultRawSettings, rawSettingsKey, type RawSourceSettings, type RawStillInfo } from "./settings";-import { asShotKelvinTint } from "./color";+import type { DevelopedFrame } from "./develop";+import type { DngRaw } from "./dng";+import { rawSettingsKey, type RawSourceSettings, type RawStillInfo } from "./settings";++// develop/dng/tiff/color are the heavy RAW developer. The in-thread developer is only a+// fallback (the app installs a worker), so it loads them on first use to keep them out of+// the app's entry chunk./*** Glue between camera files and the media library: inspecting a RAW file on@@ -36,7 +38,8 @@ function decodeBlob(sourceKey: string, blob: Blob): Promise<DngRaw> {decodeCache.set(sourceKey, hit);return hit;}- const pending = blob.arrayBuffer().then((buffer) => {+ const pending = blob.arrayBuffer().then(async (buffer) => {+ const [{ decodeDng, looksLikeDng }, { RawDecodeError }] = await Promise.all([import("./dng"), import("./tiff")]);if (!looksLikeDng(buffer)) throw new RawDecodeError("This file is not a DNG.");return decodeDng(buffer);});@@ -46,36 +49,14 @@ function decodeBlob(sourceKey: string, blob: Blob): Promise<DngRaw> {return pending;}-export function describeCfa(raw: DngRaw): string {- return raw.samplesPerPixel === 3 ? "RGB" : raw.cfa.map((c) => "RGB"[c]).join("");-}--export function inspectDngRaw(raw: DngRaw): RawInspection {- const settings = defaultRawSettings(raw);- const size = developedSize(raw, settings);- const asShot = asShotKelvinTint(raw);- return {- info: {- format: "dng",- developedBy: "openreel",- make: raw.make,- model: raw.model,- bitDepth: raw.bitsPerSample,- cfa: describeCfa(raw),- settings,- asShot: { temperature: asShot.kelvin, tint: asShot.tint },- },- width: size.width,- height: size.height,- };-}-/** The default developer: decodes and develops on the calling thread. */export const inThreadRawDeveloper: RawDeveloper = {async develop({ sourceKey, blob, settings, maxLongEdge }) {+ const { developRaw } = await import("./develop");return developRaw(await decodeBlob(sourceKey, blob), settings, maxLongEdge ? { maxLongEdge } : {});},async inspect({ sourceKey, blob }) {+ const { inspectDngRaw } = await import("./inspect");return inspectDngRaw(await decodeBlob(sourceKey, blob));},};diff --git a/packages/core/src/tasks/index.ts b/packages/core/src/tasks/index.tsnew file mode 100644index 00000000..63becf2f--- /dev/null+++ b/packages/core/src/tasks/index.ts@@ -0,0 +1 @@+export * from "./task-registry";diff --git a/packages/core/src/tasks/task-registry.test.ts b/packages/core/src/tasks/task-registry.test.tsnew file mode 100644index 00000000..021b79bc--- /dev/null+++ b/packages/core/src/tasks/task-registry.test.ts@@ -0,0 +1,132 @@+import { describe, expect, it, vi } from "vitest";+import { BackgroundTaskRegistry, formatTaskEta, summarizeTasks } from "./task-registry";++const base = { kind: "export" as const, source: "s", title: "T" };++describe("BackgroundTaskRegistry", () => {+ it("orders running before queued before finished and exposes capabilities", () => {+ const r = new BackgroundTaskRegistry(() => 100);+ r.upsert({ ...base, id: "done", status: "completed", finishedAt: 5 });+ r.upsert({ ...base, id: "q", status: "queued" }, { cancel: vi.fn() });+ r.upsert({ ...base, id: "run", status: "running", progress: 0.5 }, { cancel: vi.fn(), pause: vi.fn() });+ r.upsert({ ...base, id: "bad", status: "failed", error: "x" }, { retry: vi.fn() });+ const list = r.getSnapshot();+ expect(list.map((t) => t.id)).toEqual(["run", "q", "bad", "done"]);+ expect(list[0].can).toMatchObject({ cancel: true, pause: true, retry: false });+ expect(list[2].can).toMatchObject({ retry: true, cancel: false });+ expect(r.getSnapshot()).toBe(list);+ });++ it("clamps progress, keeps indeterminate as null and notifies subscribers", () => {+ const r = new BackgroundTaskRegistry();+ const listener = vi.fn();+ r.subscribe(listener);+ r.upsert({ ...base, id: "a", status: "running", progress: 4 });+ r.upsert({ ...base, id: "b", status: "running" });+ expect(r.get("a")?.progress).toBe(1);+ expect(r.get("b")?.progress).toBeNull();+ expect(listener).toHaveBeenCalledTimes(2);+ });++ it("syncSource replaces only its own tasks and stays quiet when nothing changed", () => {+ const r = new BackgroundTaskRegistry();+ r.upsert({ ...base, id: "other", source: "o", status: "running" });+ const task = { ...base, id: "j1", status: "running" as const, progress: 0.2 };+ r.syncSource("s", [{ task }]);+ const listener = vi.fn();+ r.subscribe(listener);+ r.syncSource("s", [{ task }]);+ expect(listener).not.toHaveBeenCalled();+ r.syncSource("s", []);+ expect(r.get("j1")).toBeUndefined();+ expect(r.get("other")).toBeDefined();+ expect(listener).toHaveBeenCalledTimes(1);+ });++ it("forwards cancel / pause / resume / retry to the owning system", () => {+ const r = new BackgroundTaskRegistry();+ const c = { cancel: vi.fn(), pause: vi.fn(), resume: vi.fn(), retry: vi.fn() };+ r.upsert({ ...base, id: "a", status: "running" }, c);+ r.cancel("a"); r.pause("a"); r.resume("a"); r.retry("a");+ expect(c.cancel).toHaveBeenCalled();+ expect(c.pause).toHaveBeenCalled();+ expect(c.resume).toHaveBeenCalled();+ expect(c.retry).toHaveBeenCalled();+ expect(() => r.cancel("missing")).not.toThrow();+ });++ it("offers pause on queued tasks and resume on paused ones", () => {+ const r = new BackgroundTaskRegistry();+ const c = { pause: vi.fn(), resume: vi.fn() };+ r.upsert({ ...base, id: "q", status: "queued" }, c);+ expect(r.getSnapshot()[0].can).toMatchObject({ pause: true, resume: false });+ r.upsert({ ...base, id: "q", status: "paused" }, c);+ expect(r.getSnapshot()[0].can).toMatchObject({ pause: false, resume: true });+ r.resume("q");+ expect(c.resume).toHaveBeenCalled();+ });++ it("track completes, fails and cancels", async () => {+ const r = new BackgroundTaskRegistry();+ await expect(r.track({ id: "ok", kind: "analysis", title: "A" }, async (ctx) => { ctx.progress(0.5, "half"); expect(r.get("ok")?.progress).toBe(0.5); return 7; })).resolves.toBe(7);+ expect(r.get("ok")).toMatchObject({ status: "completed", progress: 1, detail: "half" });++ await expect(r.track({ id: "bad", kind: "import", title: "I", retry: () => undefined }, async () => { throw new Error("boom"); })).rejects.toThrow("boom");+ expect(r.get("bad")).toMatchObject({ status: "failed", error: "boom" });+ expect(r.getSnapshot().find((t) => t.id === "bad")?.can.retry).toBe(true);++ const run = r.track({ id: "c", kind: "tracking", title: "K" }, (ctx) => new Promise((_, reject) => ctx.signal.addEventListener("abort", () => reject(new DOMException("x", "AbortError")))));+ r.cancel("c");+ await expect(run).rejects.toThrow();+ expect(r.get("c")?.status).toBe("cancelled");+ });++ it("ignores late progress after cancel and trims finished history", () => {+ const r = new BackgroundTaskRegistry();+ for (let i = 0; i < 60; i++) r.upsert({ ...base, id: `f${i}`, status: "completed", finishedAt: i });+ expect(r.getSnapshot().length).toBe(40);+ expect(r.get("f59")).toBeDefined();+ expect(r.get("f0")).toBeUndefined();+ r.clearFinished();+ expect(r.getSnapshot()).toHaveLength(0);+ });++ it("summarizes and formats", () => {+ const r = new BackgroundTaskRegistry();+ r.upsert({ ...base, id: "a", status: "running", progress: 0.5 });+ r.upsert({ ...base, id: "b", status: "running", progress: 0.25 });+ r.upsert({ ...base, id: "c", status: "queued" });+ const s = summarizeTasks(r.getSnapshot());+ expect(s).toMatchObject({ active: 3, running: 2, queued: 1, progress: 0.375 });+ expect(s.label).toBe("3 background tasks · 38%");+ expect(summarizeTasks([]).label).toBe("No background tasks");+ expect(formatTaskEta(80000)).toBe("1m 20s");+ expect(formatTaskEta(undefined)).toBe("");+ });++ it("keeps cleared mirrored tasks cleared across later source syncs, until the id runs again", () => {+ const r = new BackgroundTaskRegistry(() => 1);+ const item = (id: string, status: "running" | "completed") => ({ task: { id, kind: "export" as const, source: "q", title: id, status } });+ r.syncSource("q", [item("a", "completed"), item("b", "completed")]);+ expect(r.getSnapshot()).toHaveLength(2);+ r.clearFinished();+ expect(r.getSnapshot()).toHaveLength(0);+ r.syncSource("q", [item("a", "completed"), item("b", "completed"), item("c", "running")]);+ expect(r.getSnapshot().map((t) => t.id)).toEqual(["c"]);+ // A retry runs the same id again: it shows, and finishes visibly.+ r.syncSource("q", [item("a", "running"), item("c", "running")]);+ expect(r.getSnapshot().map((t) => t.id).sort()).toEqual(["a", "c"]);+ r.syncSource("q", [item("a", "completed"), item("c", "running")]);+ expect(r.getSnapshot().find((t) => t.id === "a")?.status).toBe("completed");+ });++ it("does not resurrect mirrored tasks dropped by the finished-history prune", () => {+ const r = new BackgroundTaskRegistry(() => 1);+ let t = 0;+ const done = Array.from({ length: 45 }, (_, i) => ({ task: { id: `j${i}`, kind: "export" as const, source: "q", title: `j${i}`, status: "completed" as const, finishedAt: ++t } }));+ r.syncSource("q", done);+ expect(r.getSnapshot()).toHaveLength(40);+ r.syncSource("q", done);+ expect(r.getSnapshot()).toHaveLength(40);+ });+});diff --git a/packages/core/src/tasks/task-registry.ts b/packages/core/src/tasks/task-registry.tsnew file mode 100644index 00000000..549e076f--- /dev/null+++ b/packages/core/src/tasks/task-registry.ts@@ -0,0 +1,313 @@+/**+ * Unified background-task registry.+ *+ * One list for every long-running job (exports, export queue, proxies, transcription, imports,+ * analysis, tracking). It owns no work: existing job systems either mirror their state in with+ * `syncSource` (export queue, proxy cache) or wrap a run with `track` (imports, analysis). The+ * registry only presents progress and forwards pause / cancel / retry to the owning system.+ */++export type BackgroundTaskKind = "export" | "proxy" | "transcription" | "import" | "analysis" | "tracking" | "other";+export type BackgroundTaskStatus = "queued" | "running" | "paused" | "completed" | "failed" | "cancelled";++export interface BackgroundTaskControls {+ readonly cancel?: () => void;+ readonly pause?: () => void;+ readonly resume?: () => void;+ readonly retry?: () => void;+}++export interface BackgroundTask {+ readonly id: string;+ readonly kind: BackgroundTaskKind;+ /** Registered system that owns the task (e.g. "export-queue"). */+ readonly source: string;+ readonly title: string;+ readonly detail?: string;+ readonly status: BackgroundTaskStatus;+ /** 0..1, or null when the owner cannot report progress (indeterminate). */+ readonly progress: number | null;+ readonly etaMs?: number;+ readonly startedAt?: number;+ readonly finishedAt?: number;+ readonly createdAt: number;+ readonly error?: string;+}++export type BackgroundTaskInput = Omit<BackgroundTask, "createdAt" | "progress"> & {+ readonly progress?: number | null;+ readonly createdAt?: number;+};++export interface BackgroundTaskView extends BackgroundTask {+ readonly can: { readonly cancel: boolean; readonly pause: boolean; readonly resume: boolean; readonly retry: boolean };+}++export interface BackgroundTaskSummary {+ readonly active: number;+ readonly running: number;+ readonly queued: number;+ readonly failed: number;+ /** Mean progress of running determinate tasks (0..1), null when none can report. */+ readonly progress: number | null;+ readonly label: string;+}++export const isActiveStatus = (status: BackgroundTaskStatus): boolean =>+ status === "queued" || status === "running" || status === "paused";++const ORDER: Record<BackgroundTaskStatus, number> = { running: 0, paused: 1, queued: 2, failed: 3, completed: 4, cancelled: 5 };+const MAX_FINISHED = 40;+const clamp01 = (value: number): number => (Number.isFinite(value) ? Math.min(1, Math.max(0, value)) : 0);++export interface TrackContext {+ readonly signal: AbortSignal;+ readonly id: string;+ progress(value: number | null, detail?: string): void;+}++export interface TrackOptions {+ readonly id?: string;+ readonly kind: BackgroundTaskKind;+ readonly source?: string;+ readonly title: string;+ readonly detail?: string;+ /** Provide to make the task retryable: re-runs the same work. */+ readonly retry?: () => void;+}++export class BackgroundTaskRegistry {+ private tasks = new Map<string, BackgroundTask>();+ private controls = new Map<string, BackgroundTaskControls>();+ private listeners = new Set<() => void>();+ /**+ * Finished tasks a mirrored source still lists but the user cleared (or the prune dropped). A+ * `syncSource` pass must not resurrect them; a new run under the same id (retry) lifts the mark.+ */+ private dismissed = new Set<string>();+ private snapshot: readonly BackgroundTaskView[] = [];+ private dirty = false;+ private seq = 0;++ constructor(private readonly now: () => number = Date.now) {}++ subscribe = (listener: () => void): (() => void) => {+ this.listeners.add(listener);+ return () => {+ this.listeners.delete(listener);+ };+ };++ /** Stable between changes (safe for useSyncExternalStore). */+ getSnapshot = (): readonly BackgroundTaskView[] => {+ if (this.dirty) {+ this.snapshot = [...this.tasks.values()]+ .map((task): BackgroundTaskView => {+ const c = this.controls.get(task.id) ?? {};+ const active = isActiveStatus(task.status);+ return {+ ...task,+ can: {+ cancel: active && !!c.cancel,+ pause: (task.status === "running" || task.status === "queued") && !!c.pause,+ resume: task.status === "paused" && !!c.resume,+ retry: (task.status === "failed" || task.status === "cancelled") && !!c.retry,+ },+ };+ })+ .sort((a, b) => ORDER[a.status] - ORDER[b.status] || (isActiveStatus(a.status) ? a.createdAt - b.createdAt : (b.finishedAt ?? 0) - (a.finishedAt ?? 0)));+ this.dirty = false;+ }+ return this.snapshot;+ };++ get(id: string): BackgroundTask | undefined {+ return this.tasks.get(id);+ }++ private changed(): void {+ this.dirty = true;+ for (const listener of [...this.listeners]) listener();+ }++ /** Add or replace one task. Terminal tasks get a finish time; the oldest finished ones are dropped. */+ upsert(input: BackgroundTaskInput, controls?: BackgroundTaskControls): void {+ const previous = this.tasks.get(input.id);+ const progress = input.progress === undefined || input.progress === null ? null : clamp01(input.progress);+ const active = isActiveStatus(input.status);+ const next: BackgroundTask = {+ ...input,+ progress,+ createdAt: input.createdAt ?? previous?.createdAt ?? this.now(),+ startedAt: input.startedAt ?? previous?.startedAt ?? (input.status === "running" ? this.now() : undefined),+ finishedAt: active ? undefined : (input.finishedAt ?? previous?.finishedAt ?? this.now()),+ };+ this.tasks.set(input.id, next);+ if (active) this.forget(input.id);+ if (controls) this.controls.set(input.id, controls);+ this.prune();+ this.changed();+ }++ remove(id: string): void {+ if (!this.tasks.delete(id)) return;+ this.controls.delete(id);+ this.changed();+ }++ /**+ * Replace every task owned by `source` (adapter for systems that keep their own state). Tasks the+ * source no longer lists disappear; unchanged ones keep their identity so listeners stay quiet.+ */+ syncSource(source: string, items: readonly { task: BackgroundTaskInput; controls?: BackgroundTaskControls }[]): void {+ const keep = new Set(items.map((item) => item.task.id));+ let touched = false;+ for (const [id, task] of this.tasks) {+ if (task.source === source && !keep.has(id)) {+ this.tasks.delete(id);+ this.controls.delete(id);+ touched = true;+ }+ }+ for (const id of this.dismissed) if (id.length && !keep.has(id) && this.dismissedSource.get(id) === source) this.forget(id);+ for (const { task, controls } of items) {+ if (this.dismissed.has(task.id)) {+ if (!isActiveStatus(task.status)) continue;+ this.forget(task.id);+ }+ const previous = this.tasks.get(task.id);+ const progress = task.progress === undefined ? null : task.progress === null ? null : clamp01(task.progress);+ if (+ previous && previous.status === task.status && previous.progress === progress && previous.title === task.title &&+ previous.detail === task.detail && previous.etaMs === task.etaMs && previous.error === task.error && previous.source === task.source+ ) {+ if (controls) this.controls.set(task.id, controls);+ continue;+ }+ const active = isActiveStatus(task.status);+ this.tasks.set(task.id, {+ ...task,+ progress,+ createdAt: task.createdAt ?? previous?.createdAt ?? this.now(),+ startedAt: task.startedAt ?? previous?.startedAt ?? (task.status === "running" ? this.now() : undefined),+ finishedAt: active ? undefined : (task.finishedAt ?? previous?.finishedAt ?? this.now()),+ });+ if (controls) this.controls.set(task.id, controls);+ touched = true;+ }+ if (touched) {+ this.prune();+ this.changed();+ }+ }++ /**+ * Run `work` as a tracked task. Cancel aborts `ctx.signal`; the work decides how to unwind.+ * An aborted run ends "cancelled", a thrown error "failed" (retryable when `retry` is given).+ */+ async track<T>(options: TrackOptions, work: (ctx: TrackContext) => Promise<T>): Promise<T> {+ const id = options.id ?? `task-${this.now()}-${++this.seq}`;+ const source = options.source ?? options.kind;+ const abort = new AbortController();+ const base = { id, kind: options.kind, source, title: options.title };+ const controls: BackgroundTaskControls = { cancel: () => abort.abort(), retry: options.retry };+ let detail = options.detail;+ this.upsert({ ...base, detail, status: "running", progress: null }, controls);+ const ctx: TrackContext = {+ id,+ signal: abort.signal,+ progress: (value, next) => {+ if (abort.signal.aborted) return;+ if (next !== undefined) detail = next;+ const current = this.tasks.get(id);+ if (!current || current.status !== "running") return;+ this.upsert({ ...current, detail, progress: value });+ },+ };+ try {+ const result = await work(ctx);+ this.upsert(abort.signal.aborted ? { ...base, detail, status: "cancelled" } : { ...base, detail, status: "completed", progress: 1 });+ return result;+ } catch (error) {+ if (abort.signal.aborted || (error instanceof Error && error.name === "AbortError")) {+ this.upsert({ ...base, detail, status: "cancelled" });+ } else {+ this.upsert({ ...base, detail, status: "failed", error: error instanceof Error ? error.message : String(error) });+ }+ throw error;+ }+ }++ private dismissedSource = new Map<string, string>();+ private forget(id: string): void {+ this.dismissed.delete(id);+ this.dismissedSource.delete(id);+ }+ private dismiss(task: BackgroundTask): void {+ this.dismissed.add(task.id);+ this.dismissedSource.set(task.id, task.source);+ }++ clearFinished(): void {+ let touched = false;+ for (const [id, task] of this.tasks) {+ if (!isActiveStatus(task.status)) {+ this.dismiss(task);+ this.tasks.delete(id);+ this.controls.delete(id);+ touched = true;+ }+ }+ if (touched) this.changed();+ }++ cancel(id: string): void {+ this.controls.get(id)?.cancel?.();+ }+ pause(id: string): void {+ this.controls.get(id)?.pause?.();+ }+ resume(id: string): void {+ this.controls.get(id)?.resume?.();+ }+ retry(id: string): void {+ this.controls.get(id)?.retry?.();+ }++ private prune(): void {+ const finished = [...this.tasks.values()].filter((t) => !isActiveStatus(t.status)).sort((a, b) => (b.finishedAt ?? 0) - (a.finishedAt ?? 0));+ for (const old of finished.slice(MAX_FINISHED)) {+ this.dismiss(old);+ this.tasks.delete(old.id);+ this.controls.delete(old.id);+ }+ }+}++export function summarizeTasks(tasks: readonly BackgroundTask[]): BackgroundTaskSummary {+ const running = tasks.filter((t) => t.status === "running");+ const queued = tasks.filter((t) => t.status === "queued" || t.status === "paused").length;+ const failed = tasks.filter((t) => t.status === "failed").length;+ const determinate = running.filter((t) => t.progress !== null);+ const progress = determinate.length ? determinate.reduce((sum, t) => sum + (t.progress ?? 0), 0) / determinate.length : null;+ const active = running.length + queued;+ const label = active+ ? `${active} background task${active === 1 ? "" : "s"}${progress !== null ? ` · ${Math.round(progress * 100)}%` : ""}`+ : failed+ ? `${failed} task${failed === 1 ? "" : "s"} failed`+ : "No background tasks";+ return { active, running: running.length, queued, failed, progress, label };+}++/** Compact remaining-time text ("1m 20s"), empty when unknown. */+export function formatTaskEta(etaMs: number | undefined): string {+ if (etaMs === undefined || !Number.isFinite(etaMs) || etaMs <= 0) return "";+ const s = Math.max(1, Math.round(etaMs / 1000));+ if (s < 60) return `${s}s`;+ const m = Math.floor(s / 60);+ if (m < 60) return `${m}m ${String(s % 60).padStart(2, "0")}s`;+ return `${Math.floor(m / 60)}h ${String(m % 60).padStart(2, "0")}m`;+}++/** The app-wide singleton every job source reports into. */+export const backgroundTasks = new BackgroundTaskRegistry();diff --git a/packages/core/src/types/actions.ts b/packages/core/src/types/actions.tsindex a5ebee02..319d2cae 100644--- a/packages/core/src/types/actions.ts+++ b/packages/core/src/types/actions.ts@@ -160,7 +160,8 @@ export type TrackAction =| { type: "track/setSyncLock"; params: { trackId: string; syncLock: boolean } }| { type: "track/hide"; params: { trackId: string; hidden: boolean } }| { type: "track/mute"; params: { trackId: string; muted: boolean } }- | { type: "track/solo"; params: { trackId: string; solo: boolean } };+ | { type: "track/solo"; params: { trackId: string; solo: boolean } }+ | { type: "track/setSoloSafe"; params: { trackId: string; soloSafe: boolean } };// Clip actionsexport type ClipAction =diff --git a/packages/core/src/types/project.ts b/packages/core/src/types/project.tsindex 2aed5700..f8dad46d 100644--- a/packages/core/src/types/project.ts+++ b/packages/core/src/types/project.ts@@ -1,4 +1,5 @@import type { FootageInterpretation } from "../media/interpretation";+import type { SpeakerProfile } from "../captions/diarization";import type { FootageColorPreset, SourceColorSpace } from "../color/source-color";import type { RawStillInfo } from "../raw/settings";import type { ParticleEffect } from "../effects/particle-types";@@ -96,6 +97,8 @@ export interface Project {readonly textClips?: TextClip[];/** Named text and caption styles (save once, apply to many). */readonly savedStyles?: SavedStyleLibrary;+ /** Caption speakers: colour and caption position per `Subtitle.speaker` name. */+ readonly speakers?: readonly SpeakerProfile[];readonly shapeClips?: ShapeClip[];readonly svgClips?: SVGClip[];readonly stickerClips?: StickerClip[];@@ -162,8 +165,8 @@ export interface MediaLibrary {readonly desktopIngest?: DesktopIngestConfig;}-/** Codec of a desktop (native ffmpeg) proxy: ProRes 422 Proxy in .mov, or H.264 in .mp4. */-export type DesktopProxyCodec = "prores-proxy" | "h264";+/** Codec of a desktop (native ffmpeg) proxy: ProRes 422 Proxy or DNxHR LB in .mov, or H.264 in .mp4. */+export type DesktopProxyCodec = "prores-proxy" | "h264" | "dnxhr-lb";/** Proxy frame size: half or quarter of the source, or a fixed height (never upscaled). */export type DesktopProxySize = "half" | "quarter" | "720p" | "1080p";@@ -232,6 +235,8 @@ export interface MediaItem {readonly metadata: MediaMetadata;readonly thumbnailUrl: string | null;readonly waveformData: Float32Array | null;+ /** Preferences > Default audio channels, stamped at import: clips of this file start with that channel format. Absent = use file. */+ readonly channelPreset?: import("../audio/channel-map").ChannelPreset;readonly filmstripThumbnails?: FilmstripThumbnail[];readonly isPlaceholder?: boolean;readonly originalUrl?: string;@@ -259,6 +264,8 @@ export interface MediaItem {readonly kieaiError?: boolean;/** KieAI task ID used to poll for completion */readonly kieaiTaskId?: string;+ /** Master-clip markers (Source monitor): `time` is source-media seconds; shown on every timeline instance. */+ readonly markers?: import("./timeline").Marker[];/** "Interpret footage": the user's override of the file's colour tags. Absent means as tagged. */readonly colorInterpretation?: FootageColorPreset;/** "Interpret footage": frame rate / pixel aspect ratio / field order overrides. Absent means as the file says. */diff --git a/packages/core/src/types/timeline.ts b/packages/core/src/types/timeline.tsindex cee72bb9..1a239d97 100644--- a/packages/core/src/types/timeline.ts+++ b/packages/core/src/types/timeline.ts@@ -146,6 +146,11 @@ export interface Track {readonly hidden: boolean;readonly muted: boolean;readonly solo: boolean;+ /**+ * Solo Safe: while other tracks are soloed this track keeps playing (live and in the export+ * mixdown) instead of being silenced. Mute still wins. Absent = false.+ */+ readonly soloSafe?: boolean;/** Tracks with the same id move and trim their related items together. */readonly groupId?: string;/** Premiere-style per-track effect rack (Audio Track Mixer). Absent on old projects. */@@ -332,6 +337,8 @@ export interface Clip {readonly volume: number;/** 5.1 sequences: this clip's surround position; absent = the track's. */readonly surroundPan?: import("../audio/surround").SurroundPan;+ /** Modify > Audio Channels: which source channels the clip plays. Absent = the file's import preset (default: the file as it is). */+ readonly channelMap?: import("../audio/channel-map").ClipChannelMap;readonly fade?: ClipFade;readonly automation?: {volume?: AutomationPoint[];@@ -365,6 +372,11 @@ export interface Clip {readonly audioTrackIndex?: number;/** Timeline label colour; when unset the clip shows its media's label. */readonly label?: import("./project").MediaLabelId | null;+ /**+ * Clip markers (Premiere): `time` is in the clip's SOURCE media seconds, so they follow the+ * footage through trims, speed changes and reverse. See `editing/clip-markers.ts`.+ */+ readonly markers?: Marker[];readonly metadata?: ClipMetadata;}@@ -414,6 +426,16 @@ export interface Keyframe {readonly out: { readonly x: number; readonly y: number };};readonly roving?: boolean;+ /**+ * Temporal interpolation type of this key's INCOMING side (the handle ending the previous+ * segment). "auto-bezier" keeps that handle derived from neighbours; "continuous-bezier" tangent-links+ * it with the outgoing side. Other types are fully described by the segments' easing + handles.+ * Absent on legacy keyframes. Handles are always baked into bezierHandles, so every engine+ * evaluates identically.+ */+ readonly interpolationIn?: "auto-bezier" | "continuous-bezier";+ /** Temporal interpolation type of this key's OUTGOING side (the handle leaving it); see interpolationIn. */+ readonly interpolationOut?: "auto-bezier" | "continuous-bezier";}export const EASING_TYPES = [@@ -544,6 +566,16 @@ export interface Subtitle {readonly animationStyle?: CaptionAnimationStyle;/** Who is speaking (shown in the transcript, exported as a WebVTT voice tag). */readonly speaker?: string;+ /**+ * What the cue looked like before a speaker profile's colour/position was+ * baked onto it, so clearing or changing the speaker can put it back.+ */+ readonly speakerBase?: {+ readonly hadStyle: boolean;+ readonly color?: string;+ readonly position?: SubtitleStyle["position"];+ readonly cueSettings?: CueSettings;+ };/** BCP-47 language of the text. Captions without one belong to the default track. */readonly language?: string;/**@@ -551,6 +583,12 @@ export interface Subtitle {* Cues without an id are on the default track.*/readonly captionTrackId?: string;+ /**+ * Keep this cue out of the picture (Preview and burned-in export). The cue stays in the+ * transcript and in sidecar / embedded caption files. Set per track so two language+ * versions never draw on top of each other.+ */+ readonly hidden?: boolean;/** WebVTT cue settings (line / position / size / align). Overrides `style.position` when set. */readonly cueSettings?: CueSettings;}diff --git a/packages/core/src/video/animated-video-effects.ts b/packages/core/src/video/animated-video-effects.tsindex 0f510260..dafc8fbd 100644--- a/packages/core/src/video/animated-video-effects.ts+++ b/packages/core/src/video/animated-video-effects.ts@@ -12,11 +12,18 @@ import {withProEffectTime,type ProEffectType,} from "./pro-effects";+import {+ hasBurnInEffects,+ isBurnInEffectType,+ isBurnInNeutral,+ withBurnInText,+ type BurnInSource,+} from "./burn-in";import { isPluginEffectType, pluginIdFromEffectType } from "../plugins/manifest";import { getPluginRegistry } from "../plugins/registry";import { hasPluginKeyframes, hasTimeDrivenPluginEffects, samplePluginEffects } from "../plugins/plugin-keyframes";-export type VideoEffectSource = Pick<Clip, "id"> & Partial<Pick<Clip, "effects" | "keyframes" | "transform" | "mediaId">>;+export type VideoEffectSource = Pick<Clip, "id"> & Partial<Pick<Clip, "effects" | "keyframes" | "transform" | "mediaId" | "startTime" | "inPoint">>;const effectPropertyMap: ReadonlyArray<{ keyframeProp: string; effectType: string; paramKey: string }> = [// Older entry/exit presets stored bare blur; the explicit effect property wins when both are present.{ keyframeProp: "blur", effectType: "blur", paramKey: "radius" },@@ -81,6 +88,7 @@ export function isRenderableVideoEffect(effect: Effect): boolean {return effect.enabled && !!id && !!getPluginRegistry().get(id) && !getPluginRegistry().isBypassed(id);}if (isProEffectType(effect.type) && isProEffectNeutral(effect.type, effect.params)) return false;+ if (isBurnInEffectType(effect.type) && isBurnInNeutral(effect.type, effect.params)) return false;return effect.enabled && !(effect.type === "blur" && typeof effect.params.radius === "number" && effect.params.radius <= 0);}@@ -91,6 +99,8 @@ export function hasAnimatedVideoEffects(clip: Pick<VideoEffectSource, "keyframeshasAnimatedColorGrading(clip) ||// Time-driven effects (VHS / glitch) change every frame even without keyframes.(clip.effects?.some(isTimeVaryingProEffect) ?? false) ||+ // Burn-ins (timecode, names) draw text resolved from the clip's position, so they are sampled per frame too.+ hasBurnInEffects(clip) ||// Keyframed plugin parameters and time driven plugins (grain, flicker) are sampled per frame.hasPluginKeyframes(clip) ||hasTimeDrivenPluginEffects(clip)@@ -98,11 +108,13 @@ export function hasAnimatedVideoEffects(clip: Pick<VideoEffectSource, "keyframes}/** Sample the same effect stack for preview, playback, transitions and export. */-export function getAnimatedVideoEffects(clip: VideoEffectSource, localTime: number): Effect[] {+export function getAnimatedVideoEffects(clip: VideoEffectSource, localTime: number, burnIn?: BurnInSource): Effect[] {// Time-driven pro effects get the clip-local time added last so preview,// playback and export agree; the array is returned unchanged otherwise.const sampled = samplePluginEffects(sampleKeyframedEffects(clip, localTime), clip.keyframes, localTime);- return withProEffectTime(sampled, localTime) as Effect[];+ const timed = withProEffectTime(sampled, localTime) as Effect[];+ // Burn-ins read the clip's place on the timeline and in its source, so they need the project's burn-in source.+ return withBurnInText(timed, clip, localTime, burnIn) as Effect[];}function sampleKeyframedEffects(clip: VideoEffectSource, localTime: number): Effect[] {diff --git a/packages/core/src/video/burn-in.test.ts b/packages/core/src/video/burn-in.test.tsnew file mode 100644index 00000000..b7939723--- /dev/null+++ b/packages/core/src/video/burn-in.test.ts@@ -0,0 +1,456 @@+import { describe, expect, it } from "vitest";+import { makeFrameRate, resolveFrameRate, secondsToFrames } from "../interchange/timecode";+import type { Effect } from "../types/timeline";+import {+ BURN_IN_DEFAULTS,+ BURN_IN_SPECS,+ BURN_IN_TEXT_PARAM,+ burnInFrameRate,+ createBurnInSource,+ drawBurnIn,+ elapsedFrames,+ formatBurnInTimecode,+ hasBurnInEffects,+ isBurnInNeutral,+ resolveBurnInNameText,+ resolveBurnInParams,+ resolveBurnInTimecodeText,+ timecodeBurnInOverlay,+ withBurnInText,+ type BurnInSource,+} from "./burn-in";+import { getAnimatedVideoEffects, hasAnimatedVideoEffects, isRenderableVideoEffect } from "./animated-video-effects";+import { getDefaultEffectParams, withEffectDefaults } from "./effect-defaults";++const DF30 = makeFrameRate(30, true, true);+const NDF30 = makeFrameRate(30, true, false);+const DF60 = makeFrameRate(60, true, true);+const R25 = makeFrameRate(25, false);+const R24 = makeFrameRate(24, false);++const tc = (frames: number, rate = DF30, extra: object = {}) => formatBurnInTimecode({ frames, rate, ...extra });++describe("formatBurnInTimecode", () => {+ it("counts 29.97 drop-frame: minute boundaries drop frame numbers 00 and 01", () => {+ expect(tc(0)).toBe("00:00:00;00");+ expect(tc(1799)).toBe("00:00:59;29");+ expect(tc(1800)).toBe("00:01:00;02");+ expect(tc(3597)).toBe("00:01:59;29");+ expect(tc(3598)).toBe("00:02:00;02");+ });++ it("does not drop on every tenth minute", () => {+ expect(tc(17981)).toBe("00:09:59;29");+ expect(tc(17982)).toBe("00:10:00;00");+ expect(tc(17983)).toBe("00:10:00;01");+ });++ it("matches the wall clock over an hour (107892 frames = 01:00:00;00)", () => {+ expect(tc(107891)).toBe("00:59:59;29");+ expect(tc(107892)).toBe("01:00:00;00");+ // Drop-frame stays within 3.6 ms of the wall clock per hour (the whole point of dropping).+ expect(Math.abs((107892 * 1001) / 30000 - 3600)).toBeLessThan(0.004);+ // Non-drop 29.97 drifts 3.6 s per hour.+ expect(Math.abs((108000 * 1001) / 30000 - 3600)).toBeGreaterThan(3.5);+ });++ it("counts 29.97 non-drop without dropping anything", () => {+ expect(tc(1800, NDF30)).toBe("00:01:00:00");+ expect(tc(107892, NDF30)).toBe("00:59:56:12");+ });++ it("counts 59.94 drop-frame (four frame numbers per minute)", () => {+ expect(tc(3599, DF60)).toBe("00:00:59;59");+ expect(tc(3600, DF60)).toBe("00:01:00;04");+ expect(tc(35964, DF60)).toBe("00:10:00;00");+ });++ it("handles integer rates", () => {+ expect(tc(90000, R25)).toBe("01:00:00:00");+ expect(tc(24 * 3600 + 23, R24)).toBe("01:00:00:23");+ });++ it("shows a minus sign for negative frames (offsets before the start)", () => {+ expect(tc(-30, NDF30)).toBe("-00:00:01:00");+ expect(tc(-1, DF30, { format: "frames" })).toBe("-1");+ });++ it("formats plain frames and feet + frames", () => {+ expect(tc(1234, R24, { format: "frames" })).toBe("1234");+ expect(tc(100, R24, { format: "feet-16" })).toBe("0002+20");+ expect(tc(100, R24, { format: "feet-35" })).toBe("0006+04");+ expect(tc(0, R24, { format: "feet-35" })).toBe("0000+00");+ });++ it("marks the second field with '.' (non-drop) or ',' (drop-frame)", () => {+ expect(tc(1800, NDF30, { secondField: true })).toBe("00:01:00.00");+ expect(tc(1800, DF30, { secondField: true })).toBe("00:01:00,02");+ expect(tc(1800, DF30, { secondField: false })).toBe("00:01:00;02");+ });+});++describe("frame rates", () => {+ it("maps Time display choices to exact rates", () => {+ expect(burnInFrameRate("29.97-df", { fps: 25, dropFrame: false })).toMatchObject({ timebase: 30, ntsc: true, dropFrame: true });+ expect(burnInFrameRate("29.97-ndf", { fps: 25, dropFrame: true })).toMatchObject({ timebase: 30, ntsc: true, dropFrame: false });+ expect(burnInFrameRate("59.94-df", { fps: 25, dropFrame: false })).toMatchObject({ timebase: 60, dropFrame: true });+ expect(burnInFrameRate("23.976", { fps: 25, dropFrame: false })).toMatchObject({ timebase: 24, ntsc: true });+ expect(burnInFrameRate("25", { fps: 30, dropFrame: false })).toMatchObject({ timebase: 25, ntsc: false });+ });++ it("auto follows the native rate and its drop-frame flag", () => {+ expect(burnInFrameRate("auto", { fps: 29.97, dropFrame: true })).toEqual(resolveFrameRate(29.97, { dropFrame: true }));+ expect(burnInFrameRate("auto", { fps: 24, dropFrame: true }).dropFrame).toBe(false);+ });++ it("elapsed frames land exactly on n for t = n / fps and floor in between", () => {+ const rate = resolveFrameRate(29.97);+ for (const n of [0, 1, 29, 30, 1799, 1800, 17982, 107892]) {+ expect(elapsedFrames((n * 1001) / 30000, rate)).toBe(n);+ }+ expect(elapsedFrames((10.5 * 1001) / 30000, rate)).toBe(10);+ expect(elapsedFrames(-1, rate)).toBe(0);+ expect(secondsToFrames(1, rate)).toBe(30);+ });+});++const source = (over: Partial<BurnInSource> = {}): BurnInSource => ({+ frameRate: 29.97,+ sequenceName: "Main Sequence",+ sequenceStartTimecode: "01:00:00;00",+ media: (id) =>+ id === "m1"+ ? { name: "Interview A", fileName: "A001_C003.mov", frameRate: 25, startTimecodeText: "10:00:00:00" }+ : id === "m2"+ ? { name: "Drop clip", fileName: "drop.mov", frameRate: 29.97, startTimecodeText: "00:59:59;00" }+ : undefined,+ ...over,+});++describe("resolveBurnInTimecodeText", () => {+ const clip = { id: "c1", mediaId: "m1", startTime: 0, inPoint: 0 };++ it("shows sequence timecode: start timecode plus the clip's timeline position, drop-frame from the start", () => {+ const params = { source: "sequence" };+ expect(resolveBurnInTimecodeText({ params, source: source(), clip, localTime: 0 })).toBe("01:00:00;00");+ expect(resolveBurnInTimecodeText({ params, source: source(), clip: { ...clip, startTime: 10 }, localTime: 0 })).toBe("01:00:09;29");+ // 60 s of wall clock passes the first minute boundary: frame 1800 = 00:01:00;02.+ expect(resolveBurnInTimecodeText({ params, source: source(), clip: { ...clip, startTime: 60.06 }, localTime: 0 })).toBe("01:01:00;02");+ expect(resolveBurnInTimecodeText({ params, source: source(), clip: { ...clip, startTime: 5 }, localTime: 1 })).toBe("01:00:05;29");+ });++ it("without a sequence start timecode it counts from zero", () => {+ const text = resolveBurnInTimecodeText({+ params: {},+ source: source({ sequenceStartTimecode: undefined }),+ clip: { ...clip, startTime: 3 },+ localTime: 0,+ });+ // 3 s at 29.97 fps is frame 89 (floor of 89.91), non-drop because there is no drop-frame start timecode.+ expect(text).toBe("00:00:02:29");+ });++ it("source timecode uses the file's start, the clip's in point and the file's own frame rate", () => {+ const params = { source: "source" };+ expect(resolveBurnInTimecodeText({ params, source: source(), clip: { ...clip, inPoint: 2 }, localTime: 1 })).toBe("10:00:03:00");+ expect(resolveBurnInTimecodeText({ params, source: source(), clip: { ...clip, inPoint: 0 }, localTime: 0.44 })).toBe("10:00:00:11");+ });++ it("source timecode follows a drop-frame file", () => {+ const text = resolveBurnInTimecodeText({+ params: { source: "source" },+ source: source(),+ clip: { id: "c2", mediaId: "m2", startTime: 0, inPoint: 0 },+ localTime: 1,+ });+ // 00:59:59;00 plus 29 frames (floor of 29.97) is still inside that second.+ expect(text).toBe("00:59:59;29");+ const later = resolveBurnInTimecodeText({+ params: { source: "source" },+ source: source(),+ clip: { id: "c2", mediaId: "m2", startTime: 0, inPoint: 0 },+ localTime: 2,+ });+ // Plus 59 frames: 30 finish second 59, the hour boundary has no drop, 29 more land on 01:00:00;29.+ expect(later).toBe("01:00:00;29");+ });++ it("clip timecode counts from the first frame of the clip", () => {+ const params = { source: "clip", timeBase: "25" };+ expect(resolveBurnInTimecodeText({ params, source: source(), clip: { ...clip, startTime: 40 }, localTime: 1.5 })).toBe("00:00:01:12");+ });++ it("a source timecode on a clip without a file counts from the clip start", () => {+ const text = resolveBurnInTimecodeText({+ params: { source: "source", timeBase: "25" },+ source: source(),+ clip: { id: "t1", startTime: 9, inPoint: 0 },+ localTime: 2,+ });+ expect(text).toBe("00:00:02:00");+ });++ it("applies the time display override, format, offset, field mark and label", () => {+ const base = { source: "clip", timeBase: "29.97-df" };+ const run = (extra: object, localTime = 60.07) =>+ resolveBurnInTimecodeText({ params: { ...base, ...extra }, source: source(), clip, localTime });+ expect(run({})).toBe("00:01:00;02");+ expect(run({ timeBase: "29.97-ndf" })).toBe("00:01:00:00");+ expect(run({ format: "frames" })).toBe("1800");+ expect(run({ offsetFrames: 10 })).toBe("00:01:00;12");+ expect(run({ offsetFrames: -1800 })).toBe("00:00:00;00");+ expect(run({ field: "field-2" })).toBe("00:01:00,02");+ expect(run({ label: "CAM A" })).toBe("CAM A 00:01:00;02");+ });+});++describe("resolveBurnInNameText", () => {+ const clip = { id: "c1", mediaId: "m1" };+ it("clip name, file name (with or without extension) and sequence name", () => {+ expect(resolveBurnInNameText({}, source(), clip)).toBe("Interview A");+ expect(resolveBurnInNameText({ nameSource: "file" }, source(), clip)).toBe("A001_C003.mov");+ expect(resolveBurnInNameText({ nameSource: "file", hideExtension: true }, source(), clip)).toBe("A001_C003");+ expect(resolveBurnInNameText({ nameSource: "sequence" }, source(), clip)).toBe("Main Sequence");+ expect(resolveBurnInNameText({ prefix: "SC4 - " }, source(), clip)).toBe("SC4 - Interview A");+ });++ it("a clip without media has no clip or file name", () => {+ expect(resolveBurnInNameText({}, source(), { id: "t" })).toBe("");+ expect(resolveBurnInNameText({ nameSource: "sequence" }, source(), { id: "t" })).toBe("Main Sequence");+ });+});++describe("params", () => {+ it("fills defaults and clamps ranges", () => {+ const p = resolveBurnInParams("burn-in-timecode", { size: 999, opacity: -5, position: "nowhere", textColor: "red", label: 3 });+ expect(p.size).toBe(30);+ expect(p.opacity).toBe(0);+ expect(p.position).toBe("bottom-center");+ expect(p.textColor).toBe("#ffffff");+ expect(p.label).toBe("");+ });++ it("every spec has a default that is inside its own range and option set", () => {+ for (const spec of Object.values(BURN_IN_SPECS)) {+ for (const param of spec.params) {+ if (param.kind === "number") expect(param.default).toBeGreaterThanOrEqual(param.min);+ if (param.kind === "number") expect(param.default).toBeLessThanOrEqual(param.max);+ if (param.kind === "select") expect(param.options.map((o) => o.value)).toContain(param.default);+ }+ expect(resolveBurnInParams(spec.type, BURN_IN_DEFAULTS[spec.type])).toEqual(BURN_IN_DEFAULTS[spec.type]);+ }+ });++ it("zero opacity is the neutral value", () => {+ expect(isBurnInNeutral("burn-in-name", { opacity: 0 })).toBe(true);+ expect(isBurnInNeutral("burn-in-name", {})).toBe(false);+ });++ it("new effects are seeded with visible defaults", () => {+ expect(getDefaultEffectParams("burn-in-timecode")).toEqual(BURN_IN_DEFAULTS["burn-in-timecode"]);+ expect(withEffectDefaults("burn-in-name", { prefix: "X" })).toMatchObject({ prefix: "X", nameSource: "clip", opacity: 100 });+ });+});++const effect = (type: string, params: Record<string, unknown> = {}): Effect => ({ id: `e-${type}`, type, params, enabled: true });++describe("sampling", () => {+ const clip = { id: "c1", mediaId: "m1", startTime: 4, inPoint: 0, effects: [effect("burn-in-timecode", { source: "sequence" })], keyframes: [] };++ it("getAnimatedVideoEffects resolves the text per frame and leaves other effects alone", () => {+ const withBlur = { ...clip, effects: [effect("blur", { radius: 2 }), ...clip.effects] };+ const [blur, burn] = getAnimatedVideoEffects(withBlur, 1, source());+ expect(blur.params).toEqual({ radius: 2 });+ expect(burn.params[BURN_IN_TEXT_PARAM]).toBe("01:00:04;29");+ expect(getAnimatedVideoEffects(withBlur, 2, source())[1].params[BURN_IN_TEXT_PARAM]).toBe("01:00:05;29");+ });++ it("is deterministic: the same instant gives the same text", () => {+ const a = getAnimatedVideoEffects(clip, 0.5, source())[0].params[BURN_IN_TEXT_PARAM];+ const b = getAnimatedVideoEffects(clip, 0.5, source())[0].params[BURN_IN_TEXT_PARAM];+ expect(a).toBe(b);+ });++ it("an effect with no source draws nothing (empty text) instead of inventing a value", () => {+ expect(getAnimatedVideoEffects(clip, 1)[0].params[BURN_IN_TEXT_PARAM]).toBe("");+ });++ it("burn-ins make a clip animated and are skipped at zero opacity", () => {+ expect(hasAnimatedVideoEffects(clip)).toBe(true);+ expect(hasBurnInEffects(clip)).toBe(true);+ const hidden = { ...clip, effects: [effect("burn-in-timecode", { opacity: 0 })] };+ expect(hasAnimatedVideoEffects(hidden)).toBe(false);+ expect(isRenderableVideoEffect(hidden.effects[0])).toBe(false);+ expect(isRenderableVideoEffect(clip.effects[0])).toBe(true);+ });++ it("withBurnInText returns the same array when there is no burn-in", () => {+ const effects = [effect("blur")];+ expect(withBurnInText(effects, clip, 0, source())).toBe(effects);+ });+});++describe("createBurnInSource", () => {+ const project = {+ name: "Project",+ settings: { frameRate: 25, startTimecode: "10:00:00:00" },+ mediaLibrary: {+ items: [+ { id: "m1", name: "Display Name", metadata: { frameRate: 24, startTimecodeText: "01:02:03:04" }, sourceFile: { name: "RAW_0001.MXF" } },+ { id: "m2", name: "Retimed", metadata: { frameRate: 24 }, interpretation: { frameRate: 23.976 } },+ ],+ },+ sequences: [{ id: "s1", name: "Rough Cut" }],+ activeSequenceId: "s1",+ };++ it("reads names, file names, frame rates and start timecodes from the project", () => {+ const s = createBurnInSource(project);+ expect(s.sequenceName).toBe("Rough Cut");+ expect(s.sequenceStartTimecode).toBe("10:00:00:00");+ expect(s.media("m1")).toMatchObject({ name: "Display Name", fileName: "RAW_0001.MXF", frameRate: 24, startTimecodeText: "01:02:03:04" });+ expect(s.media("m2")).toMatchObject({ fileName: "Retimed", frameRate: 23.976 });+ expect(s.media("nope")).toBeUndefined();+ expect(s.media(undefined)).toBeUndefined();+ });++ it("is cached per project object", () => {+ expect(createBurnInSource(project)).toBe(createBurnInSource(project));+ });++ it("falls back to the project name without sequences", () => {+ expect(createBurnInSource({ ...project, sequences: undefined }).sequenceName).toBe("Project");+ });+});++describe("export timecode overlay", () => {+ const project = {+ name: "P",+ settings: { frameRate: 29.97, startTimecode: "01:00:00;00" },+ mediaLibrary: { items: [{ id: "m1", name: "Cam", metadata: { frameRate: 25, startTimecodeText: "10:00:00:00" } }] },+ timeline: {+ tracks: [+ { type: "video", clips: [{ id: "top", mediaId: "m1", startTime: 2, duration: 5, inPoint: 1 }] },+ { type: "video", clips: [{ id: "bottom", mediaId: "m1", startTime: 0, duration: 10, inPoint: 0 }] },+ ],+ },+ };++ it("is null when off", () => {+ expect(timecodeBurnInOverlay(project, undefined, 1)).toBeNull();+ expect(timecodeBurnInOverlay(project, { enabled: false }, 1)).toBeNull();+ });++ it("draws the drop-frame sequence timecode at the frame time", () => {+ const at = (t: number) => timecodeBurnInOverlay(project, { enabled: true }, t)?.params[BURN_IN_TEXT_PARAM];+ expect(at(0)).toBe("01:00:00;00");+ // 30 frames of 29.97 fps last 1.001 s.+ expect(at(1.001)).toBe("01:00:01;00");+ expect(at(60.06)).toBe("01:01:00;02");+ });++ it("source mode shows the file timecode of the topmost clip, then falls back to the sequence in a gap", () => {+ const at = (t: number) => timecodeBurnInOverlay(project, { enabled: true, source: "source" }, t)?.params[BURN_IN_TEXT_PARAM];+ // top clip: starts at 2 s, in point 1 s -> 1 s into the clip = source second 2 of a 25 fps file.+ expect(at(3)).toBe("10:00:02:00");+ // bottom clip only: 8 s in.+ expect(at(8)).toBe("10:00:08:00");+ // Past both clips: the sequence timecode keeps counting (12 s = frame 359).+ expect(at(12)).toBe("01:00:11;29");+ });++ it("carries position, size, opacity and box into the drawn effect", () => {+ const overlay = timecodeBurnInOverlay(project, { enabled: true, position: "top-right", size: 8, opacity: 50, box: false }, 0);+ expect(overlay?.params).toMatchObject({ position: "top-right", size: 8, opacity: 50, box: false });+ });+});++interface Call { op: string; args: unknown[] }++/** Minimal Canvas2D recorder: text width is 0.6 em per character. */+function recorder() {+ const calls: Call[] = [];+ let font = "";+ const size = () => Number(/(\d+(?:\.\d+)?)px/.exec(font)?.[1] ?? 10);+ const ctx = {+ save: () => calls.push({ op: "save", args: [] }),+ restore: () => calls.push({ op: "restore", args: [] }),+ beginPath() {}, moveTo() {}, lineTo() {}, arcTo() {}, closePath() {},+ fill: () => calls.push({ op: "fill", args: [ctx.fillStyle] }),+ fillText: (text: string, x: number, y: number) => calls.push({ op: "fillText", args: [text, x, y, ctx.fillStyle] }),+ measureText: (text: string) => ({ width: text.length * size() * 0.6, actualBoundingBoxAscent: size() * 0.7, actualBoundingBoxDescent: size() * 0.2 }),+ set font(value: string) { font = value; },+ get font() { return font; },+ fillStyle: "", filter: "", globalAlpha: 1, globalCompositeOperation: "", textBaseline: "", textAlign: "",+ };+ return { ctx: ctx as unknown as CanvasRenderingContext2D, calls };+}++describe("drawBurnIn", () => {+ const draw = (type: "burn-in-timecode" | "burn-in-name", params: Record<string, unknown>, w = 1920, h = 1080) => {+ const r = recorder();+ const layout = drawBurnIn(r.ctx, type, params, w, h);+ return { ...r, layout };+ };++ it("draws nothing without text or at zero opacity", () => {+ expect(draw("burn-in-timecode", {}).layout).toBeNull();+ expect(draw("burn-in-timecode", { [BURN_IN_TEXT_PARAM]: "" }).calls).toHaveLength(0);+ expect(draw("burn-in-timecode", { [BURN_IN_TEXT_PARAM]: "00:00:00:00", opacity: 0 }).layout).toBeNull();+ });++ it("places timecode digits on a fixed advance, one glyph per cell", () => {+ const { calls } = draw("burn-in-timecode", { [BURN_IN_TEXT_PARAM]: "01:00:00;00" });+ const glyphs = calls.filter((c) => c.op === "fillText");+ expect(glyphs).toHaveLength(11);+ const fontSize = Math.round(0.05 * 1080);+ const cell = fontSize * 0.6;+ const xs = glyphs.map((g) => g.args[1] as number);+ for (let i = 1; i < xs.length; i++) expect(xs[i] - xs[i - 1]).toBeCloseTo(cell, 6);+ });++ it("anchors by position with margin and padding", () => {+ const margin = Math.round(1080 * 0.03);+ const tl = draw("burn-in-timecode", { [BURN_IN_TEXT_PARAM]: "00:00:00:00", position: "top-left" }).layout!;+ expect(tl.x).toBe(margin);+ expect(tl.y).toBe(margin);+ const br = draw("burn-in-timecode", { [BURN_IN_TEXT_PARAM]: "00:00:00:00", position: "bottom-right" }).layout!;+ expect(br.x + br.width).toBe(1920 - margin);+ expect(br.y + br.height).toBe(1080 - margin);+ const c = draw("burn-in-timecode", { [BURN_IN_TEXT_PARAM]: "00:00:00:00", position: "center" }).layout!;+ expect(Math.abs(c.x + c.width / 2 - 960)).toBeLessThanOrEqual(1);+ expect(Math.abs(c.y + c.height / 2 - 540)).toBeLessThanOrEqual(1);+ const bc = draw("burn-in-timecode", { [BURN_IN_TEXT_PARAM]: "00:00:00:00" }).layout!;+ expect(Math.abs(bc.x + bc.width / 2 - 960)).toBeLessThanOrEqual(1);+ });++ it("scales with the frame so preview and export agree", () => {+ const params = { [BURN_IN_TEXT_PARAM]: "00:00:00:00" };+ const hd = draw("burn-in-timecode", params, 1920, 1080).layout!;+ const uhd = draw("burn-in-timecode", params, 3840, 2160).layout!;+ expect(uhd.fontSize).toBe(hd.fontSize * 2);+ expect(Math.abs(uhd.width - hd.width * 2)).toBeLessThanOrEqual(2);+ });++ it("opacity multiplies into text and box alpha; the box can be switched off", () => {+ const withBox = draw("burn-in-timecode", { [BURN_IN_TEXT_PARAM]: "00:00:00:00", opacity: 50, boxOpacity: 100 });+ expect(withBox.calls.find((c) => c.op === "fill")?.args[0]).toBe("rgba(0,0,0,0.5)");+ expect(withBox.calls.find((c) => c.op === "fillText")?.args[3]).toBe("rgba(255,255,255,0.5)");+ const noBox = draw("burn-in-timecode", { [BURN_IN_TEXT_PARAM]: "00:00:00:00", box: false });+ expect(noBox.calls.some((c) => c.op === "fill")).toBe(false);+ expect(noBox.layout!.width).toBe(Math.round(noBox.calls.filter((c) => c.op === "fillText").length * Math.round(0.05 * 1080) * 0.6));+ });++ it("truncates a long name with an ellipsis inside the frame", () => {+ const long = "A very long clip name that cannot possibly fit on one line of a narrow frame ".repeat(3);+ const { layout, calls } = draw("burn-in-name", { [BURN_IN_TEXT_PARAM]: long }, 640, 360);+ const text = calls.find((c) => c.op === "fillText")!.args[0] as string;+ expect(text.endsWith("…")).toBe(true);+ expect(layout!.x + layout!.width).toBeLessThanOrEqual(640);+ });++ it("is deterministic", () => {+ const params = { [BURN_IN_TEXT_PARAM]: "01:00:00;00", position: "top-center" };+ expect(draw("burn-in-timecode", params).calls).toEqual(draw("burn-in-timecode", params).calls);+ });+});diff --git a/packages/core/src/video/burn-in.ts b/packages/core/src/video/burn-in.tsnew file mode 100644index 00000000..e441c275--- /dev/null+++ b/packages/core/src/video/burn-in.ts@@ -0,0 +1,648 @@+/**+ * Timecode and name burn-in (Premiere "Timecode" / "Clip Name" effects and the export "Timecode burn-in").+ *+ * Two effect types draw text into the picture:+ * - `burn-in-timecode`: sequence, source-file or clip timecode (drop-frame aware, offset, field mark,+ * frames / feet+frames formats).+ * - `burn-in-name`: the clip name, file name or sequence name.+ *+ * Everything here is deterministic. The text is a pure function of (clip timing, project, parameters): it is+ * resolved once per frame by `withBurnInText` (the same sampling step that gives time driven effects their clock),+ * stored as the internal `__text` param, and drawn by `drawBurnIn`. Preview, playback, effect cards and export all+ * share those two functions, so a frame shows the same digits wherever it is rendered. Digits are placed on a+ * fixed advance (one cell per character) so the picture does not depend on the font's tabular figures.+ */+import {+ framesToTimecode,+ makeFrameRate,+ resolveFrameRate,+ secondsToFrames,+ timecodeToFrames,+ type FrameRate,+} from "../interchange/timecode";+import { getSpeedEngine } from "./speed-engine";++export const BURN_IN_EFFECT_TYPES = ["burn-in-timecode", "burn-in-name"] as const;+export type BurnInEffectType = (typeof BURN_IN_EFFECT_TYPES)[number];++export function isBurnInEffectType(type: string): type is BurnInEffectType {+ return type === "burn-in-timecode" || type === "burn-in-name";+}++/** Param the sampler writes the resolved text into. Never stored in a project. */+export const BURN_IN_TEXT_PARAM = "__text";++export type BurnInPosition =+ | "top-left" | "top-center" | "top-right"+ | "middle-left" | "center" | "middle-right"+ | "bottom-left" | "bottom-center" | "bottom-right";++export type BurnInGroup = "Source" | "Layout" | "Text" | "Background";++export type BurnInParamSpec =+ | { readonly kind: "number"; readonly key: string; readonly label: string; readonly group: BurnInGroup; readonly min: number; readonly max: number; readonly step: number; readonly unit?: string; readonly default: number }+ | { readonly kind: "select"; readonly key: string; readonly label: string; readonly group: BurnInGroup; readonly default: string; readonly options: readonly { readonly value: string; readonly label: string }[] }+ | { readonly kind: "toggle"; readonly key: string; readonly label: string; readonly group: BurnInGroup; readonly default: boolean }+ | { readonly kind: "text"; readonly key: string; readonly label: string; readonly group: BurnInGroup; readonly default: string; readonly placeholder?: string; readonly maxLength: number }+ | { readonly kind: "color"; readonly key: string; readonly label: string; readonly group: BurnInGroup; readonly default: string };++export interface BurnInSpec {+ readonly type: BurnInEffectType;+ readonly label: string;+ readonly description: string;+ readonly params: readonly BurnInParamSpec[];+}++export const BURN_IN_POSITIONS: readonly { value: BurnInPosition; label: string }[] = [+ { value: "top-left", label: "Top left" },+ { value: "top-center", label: "Top center" },+ { value: "top-right", label: "Top right" },+ { value: "middle-left", label: "Middle left" },+ { value: "center", label: "Center" },+ { value: "middle-right", label: "Middle right" },+ { value: "bottom-left", label: "Bottom left" },+ { value: "bottom-center", label: "Bottom center" },+ { value: "bottom-right", label: "Bottom right" },+];++const layoutAndStyle = (position: BurnInPosition, size: number): BurnInParamSpec[] => [+ { kind: "select", key: "position", label: "Position", group: "Layout", default: position, options: BURN_IN_POSITIONS },+ { kind: "number", key: "margin", label: "Margin", group: "Layout", min: 0, max: 30, step: 0.5, unit: "%", default: 3 },+ { kind: "number", key: "offsetX", label: "Offset X", group: "Layout", min: -50, max: 50, step: 0.5, unit: "%", default: 0 },+ { kind: "number", key: "offsetY", label: "Offset Y", group: "Layout", min: -50, max: 50, step: 0.5, unit: "%", default: 0 },+ { kind: "number", key: "size", label: "Size", group: "Text", min: 1, max: 30, step: 0.5, unit: "%", default: size },+ { kind: "number", key: "opacity", label: "Opacity", group: "Text", min: 0, max: 100, step: 1, unit: "%", default: 100 },+ { kind: "color", key: "textColor", label: "Text color", group: "Text", default: "#ffffff" },+ { kind: "toggle", key: "box", label: "Background box", group: "Background", default: true },+ { kind: "color", key: "boxColor", label: "Box color", group: "Background", default: "#000000" },+ { kind: "number", key: "boxOpacity", label: "Box opacity", group: "Background", min: 0, max: 100, step: 1, unit: "%", default: 65 },+ { kind: "number", key: "boxPadding", label: "Box padding", group: "Background", min: 0, max: 100, step: 1, unit: "%", default: 35 },+];++export const BURN_IN_TIME_BASES: readonly { value: string; label: string }[] = [+ { value: "auto", label: "Auto (source rate)" },+ { value: "23.976", label: "23.976 fps" },+ { value: "24", label: "24 fps" },+ { value: "25", label: "25 fps" },+ { value: "29.97-df", label: "29.97 fps drop-frame" },+ { value: "29.97-ndf", label: "29.97 fps non-drop" },+ { value: "30", label: "30 fps" },+ { value: "50", label: "50 fps" },+ { value: "59.94-df", label: "59.94 fps drop-frame" },+ { value: "59.94-ndf", label: "59.94 fps non-drop" },+ { value: "60", label: "60 fps" },+];++export const BURN_IN_SPECS: Readonly<Record<BurnInEffectType, BurnInSpec>> = {+ "burn-in-timecode": {+ type: "burn-in-timecode",+ label: "Timecode",+ description: "Burn in sequence, source or clip timecode (drop-frame aware)",+ params: [+ {+ kind: "select", key: "source", label: "Timecode source", group: "Source", default: "sequence",+ options: [+ { value: "sequence", label: "Sequence" },+ { value: "source", label: "Source file" },+ { value: "clip", label: "Clip (from 0)" },+ ],+ },+ { kind: "select", key: "timeBase", label: "Time display", group: "Source", default: "auto", options: BURN_IN_TIME_BASES },+ {+ kind: "select", key: "format", label: "Format", group: "Source", default: "timecode",+ options: [+ { value: "timecode", label: "Timecode" },+ { value: "frames", label: "Frames" },+ { value: "feet-16", label: "Feet + frames (16 mm)" },+ { value: "feet-35", label: "Feet + frames (35 mm)" },+ ],+ },+ { kind: "number", key: "offsetFrames", label: "Offset", group: "Source", min: -1000000, max: 1000000, step: 1, unit: " fr", default: 0 },+ {+ kind: "select", key: "field", label: "Field mark", group: "Source", default: "off",+ options: [+ { value: "off", label: "Off" },+ { value: "field-2", label: "Second field (. or ,)" },+ ],+ },+ { kind: "text", key: "label", label: "Label", group: "Source", default: "", placeholder: "e.g. CAM A", maxLength: 40 },+ ...layoutAndStyle("bottom-center", 5),+ ],+ },+ "burn-in-name": {+ type: "burn-in-name",+ label: "Clip Name",+ description: "Burn in the clip name, file name or sequence name",+ params: [+ {+ kind: "select", key: "nameSource", label: "Name source", group: "Source", default: "clip",+ options: [+ { value: "clip", label: "Clip name" },+ { value: "file", label: "File name" },+ { value: "sequence", label: "Sequence name" },+ ],+ },+ { kind: "toggle", key: "hideExtension", label: "Hide file extension", group: "Source", default: false },+ { kind: "text", key: "prefix", label: "Prefix", group: "Source", default: "", placeholder: "e.g. SCENE 4 - ", maxLength: 60 },+ ...layoutAndStyle("top-left", 4),+ ],+ },+};++export const BURN_IN_DEFAULTS: Readonly<Record<BurnInEffectType, Readonly<Record<string, unknown>>>> = {+ "burn-in-timecode": Object.freeze(Object.fromEntries(BURN_IN_SPECS["burn-in-timecode"].params.map((p) => [p.key, p.default]))),+ "burn-in-name": Object.freeze(Object.fromEntries(BURN_IN_SPECS["burn-in-name"].params.map((p) => [p.key, p.default]))),+};++/** Stored params with defaults filled in and every value clamped into its legal range. */+export function resolveBurnInParams(type: BurnInEffectType, params: Readonly<Record<string, unknown>> | undefined): Record<string, unknown> {+ const out: Record<string, unknown> = {};+ for (const spec of BURN_IN_SPECS[type].params) {+ const raw = params?.[spec.key];+ switch (spec.kind) {+ case "number": {+ const n = typeof raw === "number" && Number.isFinite(raw) ? raw : spec.default;+ out[spec.key] = Math.min(spec.max, Math.max(spec.min, n));+ break;+ }+ case "select":+ out[spec.key] = typeof raw === "string" && spec.options.some((o) => o.value === raw) ? raw : spec.default;+ break;+ case "toggle":+ out[spec.key] = typeof raw === "boolean" ? raw : spec.default;+ break;+ case "text":+ out[spec.key] = typeof raw === "string" ? raw.slice(0, spec.maxLength) : spec.default;+ break;+ case "color":+ out[spec.key] = typeof raw === "string" && /^#[0-9a-f]{6}$/i.test(raw) ? raw : spec.default;+ break;+ }+ }+ return out;+}++/** An effect with no opacity draws nothing, so it is skipped everywhere (the neutral value of this effect). */+export function isBurnInNeutral(type: BurnInEffectType, params: Readonly<Record<string, unknown>> | undefined): boolean {+ return (resolveBurnInParams(type, params).opacity as number) <= 0;+}++/* -------------------------------------------------------------------------- */+/* Timecode formatting */+/* -------------------------------------------------------------------------- */++export type BurnInTimeFormat = "timecode" | "frames" | "feet-16" | "feet-35";++/** FrameRate for a "Time display" choice; "auto" uses the supplied native rate and drop-frame flag. */+export function burnInFrameRate(timeBase: string, native: { fps: number; dropFrame: boolean }): FrameRate {+ switch (timeBase) {+ case "23.976": return makeFrameRate(24, true);+ case "24": return makeFrameRate(24, false);+ case "25": return makeFrameRate(25, false);+ case "29.97-df": return makeFrameRate(30, true, true);+ case "29.97-ndf": return makeFrameRate(30, true, false);+ case "30": return makeFrameRate(30, false);+ case "50": return makeFrameRate(50, false);+ case "59.94-df": return makeFrameRate(60, true, true);+ case "59.94-ndf": return makeFrameRate(60, true, false);+ case "60": return makeFrameRate(60, false);+ default: return resolveFrameRate(native.fps > 0 ? native.fps : 30, { dropFrame: native.dropFrame });+ }+}++export interface FormatBurnInTimecodeOptions {+ /** Whole frames at `rate` (the start timecode plus elapsed frames plus the user offset). Negative shows a minus sign. */+ readonly frames: number;+ readonly rate: FrameRate;+ readonly format?: BurnInTimeFormat;+ /** Draw the second-field separator ("." for non-drop, "," for drop-frame, the SMPTE ST 12M-2 field mark). */+ readonly secondField?: boolean;+}++const FRAMES_PER_FOOT: Readonly<Record<"feet-16" | "feet-35", number>> = { "feet-16": 40, "feet-35": 16 };++/**+ * Text for a frame count. Timecode is `HH:MM:SS:FF` with `;` before the frames for drop-frame counting; Frames is the+ * plain count; feet + frames is `FFFF+FF` (40 frames per foot of 16 mm film, 16 per foot of 35 mm).+ */+export function formatBurnInTimecode({ frames, rate, format = "timecode", secondField = false }: FormatBurnInTimecodeOptions): string {+ const whole = Math.trunc(frames);+ const negative = whole < 0;+ const abs = Math.abs(whole);+ let text: string;+ if (format === "frames") {+ text = String(abs);+ } else if (format === "feet-16" || format === "feet-35") {+ const perFoot = FRAMES_PER_FOOT[format];+ text = `${String(Math.floor(abs / perFoot)).padStart(4, "0")}+${String(abs % perFoot).padStart(2, "0")}`;+ } else {+ text = framesToTimecode(abs, rate);+ if (secondField) {+ // ST 12M-2 field mark: the separator before the frames changes ':' to '.' and ';' to ','.+ text = text.replace(/([:;])(\d+)$/, (_m, sep: string, f: string) => `${sep === ";" ? "," : "."}${f}`);+ }+ }+ return negative ? `-${text}` : text;+}++/** Frames elapsed after `seconds` at `rate` (the frame being shown starts at or before the instant). */+export function elapsedFrames(seconds: number, rate: FrameRate): number {+ const exact = (Math.max(0, seconds) * rate.num) / rate.den;+ // The tolerance absorbs float error in n / fps so exports land on exactly frame n.+ return Math.floor(exact + 1e-6);+}++function startFramesOf(startTimecode: string | undefined, rate: FrameRate): number {+ if (!startTimecode) return 0;+ const match = /^(\d+):(\d{1,2}):(\d{1,2})[:;.,](\d+)$/.exec(startTimecode.trim());+ if (!match) return 0;+ try {+ return timecodeToFrames(`${match[1]}:${match[2]}:${match[3]}${rate.dropFrame ? ";" : ":"}${match[4]}`, rate);+ } catch {+ // A start that is a dropped number at this rate (or an out-of-range frame field) counts from zero.+ return 0;+ }+}++const isDropText = (timecode: string | undefined): boolean => !!timecode && timecode.includes(";");++/* -------------------------------------------------------------------------- */+/* Context */+/* -------------------------------------------------------------------------- */++export interface BurnInMedia {+ readonly name: string;+ readonly fileName: string;+ readonly frameRate?: number;+ /** HH:MM:SS:FF of the file's embedded start, `;` for drop-frame. */+ readonly startTimecodeText?: string;+ /** Embedded start as a time of day in seconds, when only that was read. */+ readonly startTimecodeSeconds?: number;+}++/** What a project contributes to burn-in text; build it with `createBurnInSource`. */+export interface BurnInSource {+ readonly frameRate: number;+ readonly sequenceName: string;+ readonly sequenceStartTimecode?: string;+ readonly media: (mediaId: string | undefined) => BurnInMedia | undefined;+}++export interface BurnInClipTiming {+ readonly id: string;+ readonly mediaId?: string;+ readonly startTime?: number;+ readonly inPoint?: number;+}++export interface BurnInProjectLike {+ readonly name: string;+ readonly settings: { readonly frameRate: number; readonly startTimecode?: string };+ readonly mediaLibrary: {+ readonly items: readonly {+ readonly id: string;+ readonly name: string;+ readonly metadata: { readonly frameRate: number; readonly startTimecode?: number; readonly startTimecodeText?: string };+ readonly interpretation?: { readonly frameRate?: number };+ readonly sourceFile?: { readonly name: string };+ }[];+ };+ readonly sequences?: readonly { readonly id: string; readonly name: string }[];+ readonly activeSequenceId?: string;+}++const sourceCache = new WeakMap<object, BurnInSource>();++/** Burn-in source of a project (cached per project object, so a frame loop builds it once). */+export function createBurnInSource(project: BurnInProjectLike): BurnInSource {+ const cached = sourceCache.get(project);+ if (cached) return cached;+ const byId = new Map<string, BurnInMedia>();+ for (const item of project.mediaLibrary?.items ?? []) {+ byId.set(item.id, {+ name: item.name,+ fileName: item.sourceFile?.name || item.name,+ frameRate: item.interpretation?.frameRate || item.metadata.frameRate || undefined,+ startTimecodeText: item.metadata.startTimecodeText,+ startTimecodeSeconds: item.metadata.startTimecode,+ });+ }+ const sequence = project.sequences?.find((s) => s.id === project.activeSequenceId);+ const source: BurnInSource = {+ frameRate: project.settings.frameRate,+ sequenceName: sequence?.name || project.name,+ sequenceStartTimecode: project.settings.startTimecode,+ media: (mediaId) => (mediaId ? byId.get(mediaId) : undefined),+ };+ sourceCache.set(project, source);+ return source;+}++/**+ * What an effect card or a not-yet-placed preview shows: a believable broadcast sequence (29.97 drop-frame starting at+ * 01:00:00;00) and a camera file. Never used for real frames.+ */+export const BURN_IN_SAMPLE_SOURCE: BurnInSource = {+ frameRate: 29.97,+ sequenceName: "Sequence 01",+ sequenceStartTimecode: "01:00:00;00",+ media: () => ({ name: "Interview A", fileName: "A001_C003_0912.mov", frameRate: 29.97, startTimecodeText: "14:22:10;00" }),+};++export interface ResolveBurnInTimecodeInput {+ readonly params: Readonly<Record<string, unknown>>;+ readonly source: BurnInSource;+ readonly clip: BurnInClipTiming;+ /** Seconds since the clip's first frame on the timeline. */+ readonly localTime: number;+}++/** The timecode text a `burn-in-timecode` effect shows for this clip at this instant. */+export function resolveBurnInTimecodeText({ params, source, clip, localTime }: ResolveBurnInTimecodeInput): string {+ const p = resolveBurnInParams("burn-in-timecode", params);+ const sourceKind = p.source as string;+ const media = source.media(clip.mediaId);+ const local = Math.max(0, localTime);++ let native: { fps: number; dropFrame: boolean };+ let startTimecode: string | undefined;+ let startSeconds = 0;+ let elapsedSeconds: number;+ if (sourceKind === "source" && media) {+ native = { fps: media.frameRate ?? source.frameRate, dropFrame: isDropText(media.startTimecodeText) };+ startTimecode = media.startTimecodeText;+ startSeconds = media.startTimecodeText ? 0 : (media.startTimecodeSeconds ?? 0);+ elapsedSeconds = (clip.inPoint ?? 0) + getSpeedEngine().getSourceTimeAtPlaybackTime(clip.id, local);+ } else if (sourceKind === "clip" || sourceKind === "source") {+ // A source timecode needs a file; generated clips (and clips on a missing file) count from their first frame.+ native = { fps: source.frameRate, dropFrame: false };+ elapsedSeconds = local;+ } else {+ native = { fps: source.frameRate, dropFrame: isDropText(source.sequenceStartTimecode) };+ startTimecode = source.sequenceStartTimecode;+ elapsedSeconds = (clip.startTime ?? 0) + local;+ }++ const rate = burnInFrameRate(p.timeBase as string, native);+ const base = startFramesOf(startTimecode, rate) + (startSeconds > 0 ? secondsToFrames(startSeconds, rate) : 0);+ const frames = base + elapsedFrames(elapsedSeconds, rate) + Math.round(p.offsetFrames as number);+ const text = formatBurnInTimecode({+ frames,+ rate,+ format: p.format as BurnInTimeFormat,+ secondField: p.field === "field-2",+ });+ const label = (p.label as string).trim();+ return label ? `${label} ${text}` : text;+}++/** The text a `burn-in-name` effect shows for this clip. */+export function resolveBurnInNameText(params: Readonly<Record<string, unknown>>, source: BurnInSource, clip: BurnInClipTiming): string {+ const p = resolveBurnInParams("burn-in-name", params);+ const media = source.media(clip.mediaId);+ let name = "";+ switch (p.nameSource) {+ case "file":+ name = media?.fileName ?? "";+ if (p.hideExtension) name = name.replace(/\.[A-Za-z0-9]{1,5}$/, "");+ break;+ case "sequence":+ name = source.sequenceName;+ break;+ default:+ name = media?.name ?? "";+ }+ return `${p.prefix as string}${name}`;+}++interface EffectLike {+ readonly type: string;+ readonly enabled?: boolean;+ readonly params: Record<string, unknown>;+}++/** True when the clip carries a burn-in that draws, so its frames depend on the clip's position in time. */+export function hasBurnInEffects(clip: { readonly effects?: readonly EffectLike[] }): boolean {+ return clip.effects?.some((e) => e.enabled !== false && isBurnInEffectType(e.type) && !isBurnInNeutral(e.type, e.params)) ?? false;+}++/**+ * Adds the resolved text to every burn-in effect (the array is returned untouched when there is none). Without a+ * source the effect has nothing to read and draws nothing, rather than a made-up value.+ */+export function withBurnInText<T extends EffectLike>(+ effects: readonly T[],+ clip: BurnInClipTiming,+ localTime: number,+ source: BurnInSource | undefined,+): readonly T[] {+ if (!effects.some((e) => isBurnInEffectType(e.type))) return effects;+ return effects.map((effect) => {+ if (!isBurnInEffectType(effect.type)) return effect;+ const text = !source+ ? ""+ : effect.type === "burn-in-timecode"+ ? resolveBurnInTimecodeText({ params: effect.params, source, clip, localTime })+ : resolveBurnInNameText(effect.params, source, clip);+ return { ...effect, params: { ...effect.params, [BURN_IN_TEXT_PARAM]: text } };+ });+}++/* -------------------------------------------------------------------------- */+/* Export "Timecode burn-in" overlay */+/* -------------------------------------------------------------------------- */++/** Export setting: one click burns the sequence timecode into every frame, above all tracks and captions. */+export interface TimecodeBurnInSettings {+ readonly enabled: boolean;+ /** Absent = sequence timecode; "source" shows the file timecode of the topmost video clip under the playhead. */+ readonly source?: "sequence" | "source";+ readonly position?: BurnInPosition;+ /** Percent of the frame height. */+ readonly size?: number;+ /** Percent. */+ readonly opacity?: number;+ readonly box?: boolean;+}++export const DEFAULT_TIMECODE_BURN_IN: Required<Omit<TimecodeBurnInSettings, "enabled">> = {+ source: "sequence",+ position: "bottom-center",+ size: 5,+ opacity: 100,+ box: true,+};++interface OverlayProject extends BurnInProjectLike {+ readonly timeline: {+ readonly tracks: readonly {+ readonly type: string;+ readonly hidden?: boolean;+ readonly clips: readonly { readonly id: string; readonly mediaId: string; readonly startTime: number; readonly duration: number; readonly inPoint: number }[];+ }[];+ };+}++/** The effect (with resolved text) the export draws over a frame at `time`, or null when the setting is off. */+export function timecodeBurnInOverlay(+ project: OverlayProject,+ settings: TimecodeBurnInSettings | undefined,+ time: number,+): EffectLike | null {+ if (!settings?.enabled) return null;+ const defined = Object.fromEntries(Object.entries(settings).filter(([, v]) => v !== undefined));+ const merged = { ...DEFAULT_TIMECODE_BURN_IN, ...defined };+ const params: Record<string, unknown> = {+ source: merged.source === "source" ? "source" : "sequence",+ position: merged.position,+ size: merged.size,+ opacity: merged.opacity,+ box: merged.box,+ };+ let clip: BurnInClipTiming | null = null;+ if (params.source === "source") {+ // Lower track index is on top, so the first video track with a clip under the playhead wins.+ for (const track of project.timeline.tracks) {+ if ((track.type !== "video" && track.type !== "image") || track.hidden) continue;+ const found = track.clips.find((c) => c.startTime <= time + 1e-6 && time < c.startTime + c.duration - 1e-6);+ if (found) {+ clip = found;+ break;+ }+ }+ // Nothing under the playhead (a gap): the overlay keeps counting the sequence timecode.+ if (!clip) params.source = "sequence";+ }+ const timing = clip ?? { id: "", startTime: 0 };+ const localTime = clip ? time - (clip.startTime ?? 0) : time;+ const effect: EffectLike = { type: "burn-in-timecode", enabled: true, params };+ return withBurnInText([effect], timing, localTime, createBurnInSource(project))[0];+}++/* -------------------------------------------------------------------------- */+/* Drawing */+/* -------------------------------------------------------------------------- */++type Ctx2D = CanvasRenderingContext2D | OffscreenCanvasRenderingContext2D;++const MONO_FONT = '"SF Mono", Menlo, Consolas, "DejaVu Sans Mono", "Liberation Mono", monospace';+const SANS_FONT = '-apple-system, "Segoe UI", "Helvetica Neue", Arial, "Liberation Sans", sans-serif';++function parseHex(color: string): [number, number, number] {+ const m = /^#([0-9a-f]{2})([0-9a-f]{2})([0-9a-f]{2})$/i.exec(color);+ return m ? [parseInt(m[1], 16), parseInt(m[2], 16), parseInt(m[3], 16)] : [255, 255, 255];+}++const rgba = (color: string, alpha: number): string => {+ const [r, g, b] = parseHex(color);+ return `rgba(${r},${g},${b},${Math.min(1, Math.max(0, alpha))})`;+};++function roundRect(ctx: Ctx2D, x: number, y: number, w: number, h: number, r: number): void {+ const radius = Math.min(r, w / 2, h / 2);+ ctx.beginPath();+ ctx.moveTo(x + radius, y);+ ctx.lineTo(x + w - radius, y);+ ctx.arcTo(x + w, y, x + w, y + radius, radius);+ ctx.lineTo(x + w, y + h - radius);+ ctx.arcTo(x + w, y + h, x + w - radius, y + h, radius);+ ctx.lineTo(x + radius, y + h);+ ctx.arcTo(x, y + h, x, y + h - radius, radius);+ ctx.lineTo(x, y + radius);+ ctx.arcTo(x, y, x + radius, y, radius);+ ctx.closePath();+}++/** Geometry of the drawn text block; exported so tests (and the export overlay) can assert where pixels land. */+export interface BurnInLayout {+ readonly x: number;+ readonly y: number;+ readonly width: number;+ readonly height: number;+ readonly fontSize: number;+}++/**+ * Draws a burn-in effect (its resolved `__text`) over the whole canvas. Does nothing for empty text or zero opacity.+ * Returns the box it occupied, or null when nothing was drawn.+ */+export function drawBurnIn(+ ctx: Ctx2D,+ type: BurnInEffectType,+ storedParams: Readonly<Record<string, unknown>>,+ width: number,+ height: number,+): BurnInLayout | null {+ const text = typeof storedParams[BURN_IN_TEXT_PARAM] === "string" ? (storedParams[BURN_IN_TEXT_PARAM] as string) : "";+ const p = resolveBurnInParams(type, storedParams);+ const opacity = (p.opacity as number) / 100;+ if (!text || opacity <= 0 || width <= 0 || height <= 0) return null;++ const fontSize = Math.max(6, Math.round(((p.size as number) / 100) * height));+ const mono = type === "burn-in-timecode";+ const padding = p.box ? Math.round(fontSize * ((p.boxPadding as number) / 100)) : 0;+ const margin = Math.round(Math.min(width, height) * ((p.margin as number) / 100));+ const maxTextWidth = Math.max(fontSize, width - 2 * (margin + padding));++ // The caller owns the transform (the export overlay draws inside a pixel-aspect scale).+ ctx.save();+ ctx.filter = "none";+ ctx.globalCompositeOperation = "source-over";+ ctx.globalAlpha = 1;+ ctx.font = `${mono ? 600 : 500} ${fontSize}px ${mono ? MONO_FONT : SANS_FONT}`;+ ctx.textBaseline = "alphabetic";+ ctx.textAlign = "left";++ // Fixed advance per character keeps timecode digits from jittering whatever the font's figures are.+ const cell = mono ? ctx.measureText("0").width : 0;+ let shown = text;+ let textWidth: number;+ if (mono) {+ const maxChars = Math.max(1, Math.floor(maxTextWidth / cell));+ if (shown.length > maxChars) shown = shown.slice(shown.length - maxChars);+ textWidth = cell * shown.length;+ } else {+ textWidth = ctx.measureText(shown).width;+ if (textWidth > maxTextWidth) {+ while (shown.length > 1 && ctx.measureText(`${shown}…`).width > maxTextWidth) shown = shown.slice(0, -1);+ shown = `${shown.trimEnd()}…`;+ textWidth = ctx.measureText(shown).width;+ }+ }++ const metrics = ctx.measureText("Hg");+ const ascent = metrics.actualBoundingBoxAscent || fontSize * 0.75;+ const descent = metrics.actualBoundingBoxDescent || fontSize * 0.22;+ const textHeight = Math.round(ascent + descent);+ const boxWidth = Math.round(textWidth + 2 * padding);+ const boxHeight = textHeight + 2 * padding;++ const position = p.position as BurnInPosition;+ const column = position.endsWith("left") ? 0 : position.endsWith("right") ? 2 : 1;+ const row = position.startsWith("top") ? 0 : position.startsWith("bottom") ? 2 : 1;+ let x = column === 0 ? margin : column === 2 ? width - margin - boxWidth : Math.round((width - boxWidth) / 2);+ let y = row === 0 ? margin : row === 2 ? height - margin - boxHeight : Math.round((height - boxHeight) / 2);+ x += Math.round(((p.offsetX as number) / 100) * width);+ y += Math.round(((p.offsetY as number) / 100) * height);++ if (p.box) {+ ctx.fillStyle = rgba(p.boxColor as string, opacity * ((p.boxOpacity as number) / 100));+ roundRect(ctx, x, y, boxWidth, boxHeight, Math.round(fontSize * 0.25));+ ctx.fill();+ }++ ctx.fillStyle = rgba(p.textColor as string, opacity);+ const baseline = y + padding + Math.round(ascent);+ if (mono) {+ for (let i = 0; i < shown.length; i++) {+ const ch = shown[i];+ // Narrow glyphs (":" ";" "." ",") are centred in their cell like a tabular figure.+ const glyph = ctx.measureText(ch).width;+ ctx.fillText(ch, x + padding + i * cell + (cell - glyph) / 2, baseline);+ }+ } else {+ ctx.fillText(shown, x + padding, baseline);+ }+ ctx.restore();+ return { x, y, width: boxWidth, height: boxHeight, fontSize };+}diff --git a/packages/core/src/video/echo-compositor.ts b/packages/core/src/video/echo-compositor.tsnew file mode 100644index 00000000..9967390a--- /dev/null+++ b/packages/core/src/video/echo-compositor.ts@@ -0,0 +1,93 @@+/**+ * Draws the Echo effect: the current frame plus its time-offset echo frames,+ * combined with the chosen operator. Canvas2D composite operations do the+ * per-pixel work (hardware accelerated in browsers) and are the same on the+ * GPU and software paths; compositeEchoReference in temporal-effects.ts is the+ * pure definition they are verified against.+ *+ * One compositor owns one scratch canvas, so a VideoEngine (or preview lane)+ * must not run two composes at once; callers await each compose.+ */+import {+ echoDimsBase,+ type EchoOperator,+ type ResolvedEcho,+} from "./temporal-effects";++export interface EchoFrame {+ readonly image: CanvasImageSource;+ readonly weight: number;+}++const COMPOSITE_OPERATION: Readonly<Record<EchoOperator, GlobalCompositeOperation>> = {+ add: "lighter",+ maximum: "lighten",+ minimum: "darken",+ screen: "screen",+ "composite-back": "destination-over",+ "composite-front": "source-over",+};++export class EchoCompositor {+ private canvas: OffscreenCanvas | null = null;+ private ctx: OffscreenCanvasRenderingContext2D | null = null;++ private context(width: number, height: number): OffscreenCanvasRenderingContext2D {+ if (!this.canvas || !this.ctx) {+ this.canvas = new OffscreenCanvas(width, height);+ const ctx = this.canvas.getContext("2d", { willReadFrequently: false });+ if (!ctx) throw new Error("2D canvas unavailable");+ this.ctx = ctx;+ } else if (this.canvas.width !== width || this.canvas.height !== height) {+ this.canvas.width = width;+ this.canvas.height = height;+ }+ return this.ctx as OffscreenCanvasRenderingContext2D;+ }++ /**+ * Draws `base` and the echoes (already in compositing order, see planEcho)+ * onto the scratch canvas, which is returned and valid until the next call.+ * Echo images are scaled to the base's size.+ */+ draw(+ base: ImageBitmap,+ echoes: readonly EchoFrame[],+ echo: Pick<ResolvedEcho, "operator" | "startIntensity">,+ ): OffscreenCanvas {+ const { width, height } = base;+ const ctx = this.context(width, height);+ ctx.save();+ ctx.setTransform(1, 0, 0, 1, 0, 0);+ ctx.globalCompositeOperation = "copy";+ ctx.globalAlpha = 1;+ // Straight RGB scale; alpha of the current frame is untouched.+ ctx.filter =+ echoDimsBase(echo.operator) && echo.startIntensity < 1+ ? `brightness(${echo.startIntensity})`+ : "none";+ ctx.drawImage(base, 0, 0, width, height);+ ctx.filter = "none";+ ctx.globalCompositeOperation = COMPOSITE_OPERATION[echo.operator];+ for (const frame of echoes) {+ ctx.globalAlpha = Math.min(1, Math.max(0, frame.weight));+ ctx.drawImage(frame.image, 0, 0, width, height);+ }+ ctx.restore();+ return this.canvas as OffscreenCanvas;+ }++ /** Same as draw, returned as a new bitmap the caller owns. */+ async compose(+ base: ImageBitmap,+ echoes: readonly EchoFrame[],+ echo: Pick<ResolvedEcho, "operator" | "startIntensity">,+ ): Promise<ImageBitmap> {+ return createImageBitmap(this.draw(base, echoes, echo));+ }++ dispose(): void {+ this.canvas = null;+ this.ctx = null;+ }+}diff --git a/packages/core/src/video/effect-defaults.ts b/packages/core/src/video/effect-defaults.tsindex 24616a9f..dedcb099 100644--- a/packages/core/src/video/effect-defaults.ts+++ b/packages/core/src/video/effect-defaults.ts@@ -1,4 +1,5 @@import { isProEffectType, PRO_EFFECT_DEFAULTS } from "./pro-effects";+import { BURN_IN_DEFAULTS, isBurnInEffectType } from "./burn-in";import { isPluginEffectType, newPluginEffectParams } from "../plugins/manifest";import { getPluginRegistry } from "../plugins/registry";@@ -44,6 +45,7 @@ export function getDefaultEffectParams(type: string,): Record<string, unknown> | undefined {if (isProEffectType(type)) return { ...PRO_EFFECT_DEFAULTS[type] };+ if (isBurnInEffectType(type)) return { ...BURN_IN_DEFAULTS[type] };if (isPluginEffectType(type)) {// Plugin effects seed every manifest default plus the plugin version they were authored with.const plugin = getPluginRegistry().forEffectType(type);@@ -67,7 +69,7 @@ export function withEffectDefaults(): Record<string, unknown> | undefined {const defaults = getDefaultEffectParams(type);if (!defaults) return params;- if (isProEffectType(type) || isPluginEffectType(type)) return { ...defaults, ...(params ?? {}) };+ if (isProEffectType(type) || isBurnInEffectType(type) || isPluginEffectType(type)) return { ...defaults, ...(params ?? {}) };if (params && Object.keys(params).length > 0) return params;return defaults;}diff --git a/packages/core/src/video/hdr-gpu.ts b/packages/core/src/video/hdr-gpu.tsindex 06459c64..c94e72cd 100644--- a/packages/core/src/video/hdr-gpu.ts+++ b/packages/core/src/video/hdr-gpu.ts@@ -14,6 +14,7 @@ import type { OutputColorSpec } from "../export/color-output";import { packRgbToRgba } from "../color/lut-tables";import { HUE_CURVES_GLSL, HUE_CURVE_LUT_SIZE, packHueCurveLuts } from "./hue-curves";import { BT2020_TO_BT709, TONE_MAP_KNEE } from "../color/input-transform";+import { cameraLogGlsl } from "../color/camera-log";import { BLUR_MAX_HALF, GLOW_BRIGHTNESS, GLOW_CONTRAST, gaussianKernel, glowWeight, type HdrLayerEffect } from "../color/hdr-effects";/**@@ -93,7 +94,9 @@ uniform int u_depth;uniform int u_transfer;uniform mat3 u_toBt2020;+${cameraLogGlsl()}vec3 decodeTransfer(vec3 c) {+ if (u_transfer >= 4) return decodeCameraLog(c, u_transfer);if (u_transfer == 1) return pqDecodeNitsV(c) / SDR_WHITE_NITS;if (u_transfer == 2) return hlgInverseV(c) / HLG_SDR_WHITE_SCENE;if (u_transfer == 3) return c;diff --git a/packages/core/src/video/index.ts b/packages/core/src/video/index.tsindex f80cbd11..3f07368a 100644--- a/packages/core/src/video/index.ts+++ b/packages/core/src/video/index.ts@@ -1,11 +1,15 @@export * from "./video-engine";export * from "./sequence-par";export * from "./animated-video-effects";+export * from "./burn-in";export * from "./clip-iris";export * from "./canvas-fit";export * from "./video-effects-engine";export * from "./pro-effects";+export * from "./temporal-effects";+export * from "./echo-compositor";export * from "./hsl-secondary";+export * from "./ultra-key";export * from "./effect-defaults";export * from "./pro-effect-shaders";export * from "./color-grading-engine";@@ -14,6 +18,7 @@ export * from "./tone-curve";export * from "./hue-curves";export * from "./lumetri-pipeline";export * from "./auto-tone";+export * from "./white-balance-eyedropper";export * from "./color-match";export * from "./animated-color-grading";export * from "./transition-engine";@@ -66,4 +71,6 @@ export * from "./scope-stats";export * from "./motion-track-session";export * from "./motion-template-search";export * from "./motion-track-data";+export * from "./planar-homography";+export * from "./planar-track";export * from "./gl-context";diff --git a/packages/core/src/video/planar-homography.test.ts b/packages/core/src/video/planar-homography.test.tsnew file mode 100644index 00000000..e9040818--- /dev/null+++ b/packages/core/src/video/planar-homography.test.ts@@ -0,0 +1,78 @@+import { describe, expect, it } from "vitest";+import {+ applyHomography, estimateHomography, homographyBetweenQuads, invertHomography, isConvexQuad, multiplyHomography,+ quadArea, ransacHomography, seededRandom, squareToQuad, transformQuad, type Homography, type PointPair, type Pt, type Quad,+} from "./planar-homography";++const TRUTH: Homography = [1.1, 0.12, 14, -0.08, 0.95, -6, 0.0004, -0.0002, 1];+const grid = (n: number): Pt[] => Array.from({ length: n * n }, (_, i) => ({ x: 20 + (i % n) * 31, y: 15 + Math.floor(i / n) * 27 }));+const close = (a: Pt, b: Pt, eps = 1e-6) => { expect(a.x).toBeCloseTo(b.x, 4); expect(Math.hypot(a.x - b.x, a.y - b.y)).toBeLessThan(eps * 1e3); };++describe("homography estimation", () => {+ it("recovers an exact homography from four points", () => {+ const pts = [{ x: 0, y: 0 }, { x: 100, y: 0 }, { x: 100, y: 80 }, { x: 0, y: 80 }];+ const h = estimateHomography(pts.map(p => ({ from: p, to: applyHomography(TRUTH, p) })))!;+ expect(h).not.toBeNull();+ for (const p of grid(6)) close(applyHomography(h, p), applyHomography(TRUTH, p));+ });++ it("least squares over noisy points stays within the noise", () => {+ const rand = seededRandom(7);+ const pairs: PointPair[] = grid(8).map(p => { const q = applyHomography(TRUTH, p); return { from: p, to: { x: q.x + (rand() - 0.5), y: q.y + (rand() - 0.5) } }; });+ const h = estimateHomography(pairs)!;+ for (const p of grid(5)) { const a = applyHomography(h, p), b = applyHomography(TRUTH, p); expect(Math.hypot(a.x - b.x, a.y - b.y)).toBeLessThan(0.6); }+ });++ it("rejects degenerate input", () => {+ expect(estimateHomography([])).toBeNull();+ const line = [0, 1, 2, 3, 4].map(i => ({ from: { x: i, y: i }, to: { x: i * 2, y: i * 2 } }));+ expect(estimateHomography(line)).toBeNull();+ });++ it("inverts and composes", () => {+ const inv = invertHomography(TRUTH)!;+ const id = multiplyHomography(TRUTH, inv);+ for (const p of grid(4)) close(applyHomography(id, p), p);+ expect(invertHomography([1, 2, 3, 2, 4, 6, 0, 0, 1])).toBeNull();+ });++ it("maps quads and the unit square", () => {+ const a: Quad = [{ x: 0, y: 0 }, { x: 10, y: 0 }, { x: 10, y: 10 }, { x: 0, y: 10 }];+ const b: Quad = [{ x: 3, y: 2 }, { x: 18, y: 4 }, { x: 15, y: 20 }, { x: 1, y: 14 }];+ const h = homographyBetweenQuads(a, b)!;+ transformQuad(h, a).forEach((p, i) => close(p, b[i]));+ const s = squareToQuad(b)!;+ close(applyHomography(s, { x: 1, y: 1 }), b[2]);+ expect(quadArea(a)).toBe(100);+ expect(isConvexQuad(b)).toBe(true);+ expect(isConvexQuad([a[0], a[2], a[1], a[3]])).toBe(false);+ });+});++describe("RANSAC", () => {+ const outliered = (): PointPair[] => {+ const rand = seededRandom(3);+ return grid(9).map((p, i) => i % 4 === 0 ? { from: p, to: { x: rand() * 400, y: rand() * 300 } } : { from: p, to: applyHomography(TRUTH, p) });+ };++ it("finds the model despite 25% gross outliers", () => {+ const pairs = outliered();+ const r = ransacHomography(pairs, { threshold: 1, seed: 5 })!;+ expect(r).not.toBeNull();+ expect(r.inlierCount).toBeGreaterThanOrEqual(pairs.length - Math.ceil(pairs.length / 4) - 1);+ for (const p of grid(5)) close(applyHomography(r.homography, p), applyHomography(TRUTH, p), 1e-4);+ expect(r.rmsError).toBeLessThan(1e-3);+ });++ it("is deterministic for a seed", () => {+ const pairs = outliered();+ expect(ransacHomography(pairs, { seed: 11 })).toEqual(ransacHomography(pairs, { seed: 11 }));+ });++ it("returns null with too few points or no consensus", () => {+ expect(ransacHomography(grid(1).map(p => ({ from: p, to: p })))).toBeNull();+ const rand = seededRandom(9);+ const noise = grid(6).map(p => ({ from: p, to: { x: rand() * 500, y: rand() * 500 } }));+ expect(ransacHomography(noise, { threshold: 0.5, minInliers: 20 })).toBeNull();+ });+});diff --git a/packages/core/src/video/planar-homography.ts b/packages/core/src/video/planar-homography.tsnew file mode 100644index 00000000..95487037--- /dev/null+++ b/packages/core/src/video/planar-homography.ts@@ -0,0 +1,226 @@+/**+ * Planar homography estimation: normalised DLT, deterministic RANSAC and quad helpers.+ * Pure maths with no DOM; shared by the tracking worker, the editor and tests.+ * A homography is a row-major 3x3 stored as 9 numbers with h[8] normalised to 1 where possible.+ */++export type Homography = readonly [number, number, number, number, number, number, number, number, number];+export interface Pt { x: number; y: number }+export interface PointPair { from: Pt; to: Pt }+/** Four corners, clockwise from the top left: TL, TR, BR, BL. */+export type Quad = readonly [Pt, Pt, Pt, Pt];++export const IDENTITY_HOMOGRAPHY: Homography = [1, 0, 0, 0, 1, 0, 0, 0, 1];++export function applyHomography(h: Homography, p: Pt): Pt {+ const w = h[6] * p.x + h[7] * p.y + h[8];+ const d = Math.abs(w) < 1e-12 ? 1e-12 : w;+ return { x: (h[0] * p.x + h[1] * p.y + h[2]) / d, y: (h[3] * p.x + h[4] * p.y + h[5]) / d };+}++export function multiplyHomography(a: Homography, b: Homography): Homography {+ const r = new Array<number>(9).fill(0);+ for (let i = 0; i < 3; i++) for (let j = 0; j < 3; j++) for (let k = 0; k < 3; k++) r[i * 3 + j] += a[i * 3 + k] * b[k * 3 + j];+ return normalise(r);+}++function normalise(r: number[]): Homography {+ const s = Math.abs(r[8]) > 1e-12 ? r[8] : 1;+ return r.map(v => v / s) as unknown as Homography;+}++export function invertHomography(h: Homography): Homography | null {+ const [a, b, c, d, e, f, g, i, j] = h;+ const A = e * j - f * i, B = -(d * j - f * g), C = d * i - e * g;+ const det = a * A + b * B + c * C;+ if (!Number.isFinite(det) || Math.abs(det) < 1e-14) return null;+ const inv = 1 / det;+ return normalise([A * inv, (c * i - b * j) * inv, (b * f - c * e) * inv, B * inv, (a * j - c * g) * inv, (c * d - a * f) * inv, C * inv, (b * g - a * i) * inv, (a * e - b * d) * inv]);+}++/** Hartley normalisation: translate to the centroid and scale so the mean distance is sqrt(2). */+function similarity(points: readonly Pt[]): { t: Homography; points: Pt[] } {+ let cx = 0, cy = 0;+ for (const p of points) { cx += p.x; cy += p.y; }+ cx /= points.length; cy /= points.length;+ let mean = 0;+ for (const p of points) mean += Math.hypot(p.x - cx, p.y - cy);+ mean /= points.length;+ const s = mean > 1e-12 ? Math.SQRT2 / mean : 1;+ return { t: [s, 0, -s * cx, 0, s, -s * cy, 0, 0, 1], points: points.map(p => ({ x: (p.x - cx) * s, y: (p.y - cy) * s })) };+}++/** Solve the n x n system in place by Gaussian elimination with partial pivoting; null when singular. */+function solve(matrix: number[][], rhs: number[]): number[] | null {+ const n = rhs.length;+ for (let col = 0; col < n; col++) {+ let pivot = col;+ for (let row = col + 1; row < n; row++) if (Math.abs(matrix[row][col]) > Math.abs(matrix[pivot][col])) pivot = row;+ if (Math.abs(matrix[pivot][col]) < 1e-12) return null;+ [matrix[col], matrix[pivot]] = [matrix[pivot], matrix[col]];+ [rhs[col], rhs[pivot]] = [rhs[pivot], rhs[col]];+ for (let row = col + 1; row < n; row++) {+ const f = matrix[row][col] / matrix[col][col];+ if (f === 0) continue;+ for (let k = col; k < n; k++) matrix[row][k] -= f * matrix[col][k];+ rhs[row] -= f * rhs[col];+ }+ }+ const x = new Array<number>(n).fill(0);+ for (let row = n - 1; row >= 0; row--) {+ let sum = rhs[row];+ for (let k = row + 1; k < n; k++) sum -= matrix[row][k] * x[k];+ x[row] = sum / matrix[row][row];+ }+ return x;+}++/**+ * Least-squares homography mapping `from` to `to` (exact for four points). Fixes h22 = 1 in normalised+ * space and solves the 8x8 normal equations. Null when the points are degenerate (collinear, repeated).+ */+export function estimateHomography(pairs: readonly PointPair[]): Homography | null {+ if (pairs.length < 4) return null;+ const src = similarity(pairs.map(p => p.from)), dst = similarity(pairs.map(p => p.to));+ const ata = Array.from({ length: 8 }, () => new Array<number>(8).fill(0)), atb = new Array<number>(8).fill(0);+ const accumulate = (row: number[], b: number) => {+ for (let i = 0; i < 8; i++) { atb[i] += row[i] * b; for (let j = 0; j < 8; j++) ata[i][j] += row[i] * row[j]; }+ };+ for (let k = 0; k < pairs.length; k++) {+ const { x, y } = src.points[k], { x: u, y: v } = dst.points[k];+ accumulate([x, y, 1, 0, 0, 0, -u * x, -u * y], u);+ accumulate([0, 0, 0, x, y, 1, -v * x, -v * y], v);+ }+ const sol = solve(ata, atb);+ if (!sol || !sol.every(Number.isFinite)) return null;+ const hn: Homography = [sol[0], sol[1], sol[2], sol[3], sol[4], sol[5], sol[6], sol[7], 1];+ const inverse = invertHomography(dst.t);+ if (!inverse) return null;+ const h = multiplyHomography(multiplyHomography(inverse, hn), src.t);+ return h.every(Number.isFinite) ? h : null;+}++/** Homography taking the unit square (0,0)(1,0)(1,1)(0,1) to `quad`. */+export function squareToQuad(quad: Quad): Homography | null {+ return estimateHomography([+ { from: { x: 0, y: 0 }, to: quad[0] }, { from: { x: 1, y: 0 }, to: quad[1] },+ { from: { x: 1, y: 1 }, to: quad[2] }, { from: { x: 0, y: 1 }, to: quad[3] },+ ]);+}++export function homographyBetweenQuads(from: Quad, to: Quad): Homography | null {+ return estimateHomography(from.map((p, i) => ({ from: p, to: to[i] })));+}++export function transformQuad(h: Homography, quad: Quad): Quad {+ return quad.map(p => applyHomography(h, p)) as unknown as Quad;+}++/** Signed area (shoelace); positive for the clockwise-on-screen order used here. */+export function quadArea(quad: Quad): number {+ let a = 0;+ for (let i = 0; i < 4; i++) { const p = quad[i], q = quad[(i + 1) % 4]; a += p.x * q.y - q.x * p.y; }+ return a / 2;+}++/** True for a non-degenerate, convex quad with consistent winding. */+export function isConvexQuad(quad: Quad): boolean {+ let sign = 0;+ for (let i = 0; i < 4; i++) {+ const a = quad[i], b = quad[(i + 1) % 4], c = quad[(i + 2) % 4];+ const cross = (b.x - a.x) * (c.y - b.y) - (b.y - a.y) * (c.x - b.x);+ if (!Number.isFinite(cross) || Math.abs(cross) < 1e-9) return false;+ const s = Math.sign(cross);+ if (sign === 0) sign = s; else if (s !== sign) return false;+ }+ return true;+}++export function pointInQuad(quad: Quad, p: Pt): boolean {+ let sign = 0;+ for (let i = 0; i < 4; i++) {+ const a = quad[i], b = quad[(i + 1) % 4];+ const cross = (b.x - a.x) * (p.y - a.y) - (b.y - a.y) * (p.x - a.x);+ const s = Math.sign(cross);+ if (s !== 0) { if (sign === 0) sign = s; else if (s !== sign) return false; }+ }+ return true;+}++/** Deterministic PRNG (mulberry32) so a track is identical on every run and machine. */+export function seededRandom(seed: number): () => number {+ let a = seed >>> 0;+ return () => {+ a = (a + 0x6d2b79f5) >>> 0;+ let t = a;+ t = Math.imul(t ^ (t >>> 15), t | 1);+ t ^= t + Math.imul(t ^ (t >>> 7), t | 61);+ return ((t ^ (t >>> 14)) >>> 0) / 4294967296;+ };+}++export interface RansacOptions {+ /** Reprojection error (in the `to` space) under which a pair is an inlier. */+ threshold?: number;+ iterations?: number;+ seed?: number;+ minInliers?: number;+}+export interface RansacResult { homography: Homography; inliers: boolean[]; inlierCount: number; rmsError: number }++/** Maps used to reject minimal samples that would give a near-degenerate model. */+function spread(sample: readonly Pt[]): boolean {+ for (let i = 0; i < 4; i++) for (let j = i + 1; j < 4; j++) if (Math.hypot(sample[i].x - sample[j].x, sample[i].y - sample[j].y) < 1e-3) return false;+ for (let i = 0; i < 4; i++) {+ const a = sample[i], b = sample[(i + 1) % 4], c = sample[(i + 2) % 4];+ if (Math.abs((b.x - a.x) * (c.y - a.y) - (b.y - a.y) * (c.x - a.x)) < 1e-3) return false;+ }+ return true;+}++/** RANSAC over point pairs with a final least-squares refit on the inliers. Deterministic for a given seed. */+export function ransacHomography(pairs: readonly PointPair[], options: RansacOptions = {}): RansacResult | null {+ const { threshold = 2, iterations = 200, seed = 1, minInliers = 6 } = options;+ const n = pairs.length;+ if (n < 4) return null;+ const rand = seededRandom(seed);+ const t2 = threshold * threshold;+ const errors = (h: Homography): { count: number; flags: boolean[] } => {+ const flags = new Array<boolean>(n);+ let count = 0;+ for (let i = 0; i < n; i++) {+ const q = applyHomography(h, pairs[i].from);+ const ok = (q.x - pairs[i].to.x) ** 2 + (q.y - pairs[i].to.y) ** 2 <= t2;+ flags[i] = ok; if (ok) count++;+ }+ return { count, flags };+ };+ let best: { h: Homography; count: number; flags: boolean[] } | null = null;+ if (n === 4) {+ const h = estimateHomography(pairs);+ if (!h) return null;+ const e = errors(h);+ best = { h, ...e };+ } else {+ for (let it = 0; it < iterations; it++) {+ const picks = new Set<number>();+ while (picks.size < 4) picks.add(Math.min(n - 1, Math.floor(rand() * n)));+ const sample = [...picks].map(i => pairs[i]);+ if (!spread(sample.map(p => p.from)) || !spread(sample.map(p => p.to))) continue;+ const h = estimateHomography(sample);+ if (!h) continue;+ const e = errors(h);+ if (!best || e.count > best.count) best = { h, ...e };+ if (best.count === n) break;+ }+ }+ if (!best || best.count < Math.min(minInliers, n)) return null;+ // Refit on the consensus set, re-evaluate, and keep the refit only if it does not lose inliers.+ const inlierPairs = pairs.filter((_, i) => best!.flags[i]);+ const refit = estimateHomography(inlierPairs);+ let { h, count, flags } = best;+ if (refit) { const e = errors(refit); if (e.count >= count) { h = refit; count = e.count; flags = e.flags; } }+ let sum = 0;+ for (let i = 0; i < n; i++) if (flags[i]) { const q = applyHomography(h, pairs[i].from); sum += (q.x - pairs[i].to.x) ** 2 + (q.y - pairs[i].to.y) ** 2; }+ return { homography: h, inliers: flags, inlierCount: count, rmsError: Math.sqrt(sum / Math.max(1, count)) };+}diff --git a/packages/core/src/video/planar-track.test.ts b/packages/core/src/video/planar-track.test.tsnew file mode 100644index 00000000..81c1f007--- /dev/null+++ b/packages/core/src/video/planar-track.test.ts@@ -0,0 +1,132 @@+import { describe, expect, it } from "vitest";+import { applyHomography, invertHomography, seededRandom, type Homography, type Quad } from "./planar-homography";+import {+ correctPlanarFrame, cornersToQuad, mergePlanarTrack, planarCornersAt, PlanarTrackSession, trackPlanarSurface, type PlanarSessionFrame,+} from "./planar-track";++const W = 200, H = 150;+/** A smooth-ish seeded texture sampled bilinearly, so warped frames carry real sub-pixel structure. */+function texture(seed: number): (x: number, y: number) => number {+ const rand = seededRandom(seed), size = 128, cells = new Float32Array(size * size);+ for (let i = 0; i < cells.length; i++) cells[i] = rand() * 255;+ const at = (x: number, y: number) => cells[((y % size + size) % size) * size + ((x % size + size) % size)];+ return (x, y) => {+ const x0 = Math.floor(x), y0 = Math.floor(y), fx = x - x0, fy = y - y0;+ return (at(x0, y0) * (1 - fx) + at(x0 + 1, y0) * fx) * (1 - fy) + (at(x0, y0 + 1) * (1 - fx) + at(x0 + 1, y0 + 1) * fx) * fy;+ };+}+const tex = texture(42);+const SURFACE: Quad = [{ x: 50, y: 40 }, { x: 150, y: 40 }, { x: 150, y: 110 }, { x: 50, y: 110 }];++/** Frame t: the surface moves by `world(t)` (a homography on the plane); the background is a different texture. */+function render(world: Homography): PlanarSessionFrame {+ const inv = invertHomography(world)!, bg = texture(99), data = new Uint8ClampedArray(W * H * 4);+ for (let y = 0; y < H; y++) for (let x = 0; x < W; x++) {+ const s = applyHomography(inv, { x, y });+ const inside = s.x >= 50 && s.x <= 150 && s.y >= 40 && s.y <= 110;+ const v = inside ? tex(s.x, s.y) : bg(x * 0.5, y * 0.5) * 0.3 + 40;+ const o = (y * W + x) * 4; data[o] = data[o + 1] = data[o + 2] = v; data[o + 3] = 255;+ }+ return { width: W, height: H, data };+}+const motion = (t: number): Homography => {+ const a = t * 0.01, c = Math.cos(a), s = Math.sin(a), tx = t * 1.3, ty = t * 0.6, k = 1 + t * 0.004;+ return [k * c, -k * s, tx + 100 * (1 - k * c) + 75 * k * s - 100 * 0 , k * s, k * c, ty + 75 * (1 - k * c) - 100 * k * s, 0.00003 * t, 0, 1];+};+const truthCorners = (t: number) => SURFACE.map(p => applyHomography(motion(t), p));+const err = (corners: number[], t: number) => Math.max(...truthCorners(t).map((p, i) => Math.hypot(p.x - corners[i * 2], p.y - corners[i * 2 + 1])));++describe("PlanarTrackSession", () => {+ it("tracks a moving, rotating, perspective-skewed surface through clutter", async () => {+ const session = new PlanarTrackSession({ corners: SURFACE.flatMap(p => [p.x, p.y]) });+ let worst = 0;+ for (let t = 0; t <= 14; t++) {+ const step = await session.step(render(motion(t)));+ expect(step.status).toBe("tracked");+ worst = Math.max(worst, err(step.corners, t));+ }+ expect(worst).toBeLessThan(2);+ }, 30000);++ it("is deterministic", async () => {+ const run = async () => { const s = new PlanarTrackSession({ corners: SURFACE.flatMap(p => [p.x, p.y]) }); const out: number[][] = []; for (let t = 0; t < 5; t++) out.push((await s.step(render(motion(t)))).corners); return out; };+ expect(await run()).toEqual(await run());+ }, 30000);++ it("rejects a textureless surface and a flipped quad", async () => {+ const flat: PlanarSessionFrame = { width: W, height: H, data: new Uint8ClampedArray(W * H * 4).fill(128) };+ await expect(new PlanarTrackSession({ corners: SURFACE.flatMap(p => [p.x, p.y]) }).step(flat)).rejects.toThrow(/detail/);+ await expect(new PlanarTrackSession({ corners: [50, 40, 150, 110, 150, 40, 50, 110] }).step(render(motion(0)))).rejects.toThrow(/corners/);+ });++ it("holds the last corners and reports lost when the surface vanishes", async () => {+ const session = new PlanarTrackSession({ corners: SURFACE.flatMap(p => [p.x, p.y]) });+ await session.step(render(motion(0)));+ const before = (await session.step(render(motion(1)))).corners;+ const blank: PlanarSessionFrame = { width: W, height: H, data: new Uint8ClampedArray(W * H * 4).fill(60) };+ const gone = await session.step(blank);+ expect(gone.lost).toBe(true);+ expect(gone.status).toBe("predicted");+ expect(gone.corners).toEqual(before);+ }, 30000);+});++describe("trackPlanarSurface", () => {+ const frames = new Map<number, PlanarSessionFrame>();+ const read = async (f: number) => { if (!frames.has(f)) frames.set(f, render(motion(f))); const src = frames.get(f)!; return { ...src, data: new Uint8ClampedArray(src.data) }; };+ const base = { clipId: "c", frameRate: 30, startFrame: 0, endFrame: 8, readFrame: read };++ it("tracks forward and reports progress", async () => {+ const progress: number[] = [];+ const data = await trackPlanarSurface({ ...base, anchorFrame: 0, corners: SURFACE.flatMap(p => [p.x, p.y]), onProgress: p => progress.push(p) });+ expect(data.keyframes.map(k => k.frame)).toEqual([0, 1, 2, 3, 4, 5, 6, 7, 8]);+ expect(progress.at(-1)).toBe(100);+ expect(err(data.keyframes[8].corners, 8)).toBeLessThan(2);+ }, 60000);++ it("tracks backward from a later anchor frame", async () => {+ const corners = truthCorners(8).flatMap(p => [p.x, p.y]);+ const data = await trackPlanarSurface({ ...base, anchorFrame: 8, direction: "backward", corners });+ expect(data.keyframes.map(k => k.frame)).toEqual([0, 1, 2, 3, 4, 5, 6, 7, 8]);+ expect(err(data.keyframes[0].corners, 0)).toBeLessThan(2.5);+ }, 60000);++ it("cancels through an AbortSignal", async () => {+ const controller = new AbortController();+ const run = trackPlanarSurface({ ...base, anchorFrame: 0, corners: SURFACE.flatMap(p => [p.x, p.y]), signal: controller.signal, onProgress: p => { if (p > 20) controller.abort(); } });+ await expect(run).rejects.toThrow(/cancelled/);+ }, 60000);+});++describe("planar track data", () => {+ const data = { version: 1 as const, trackId: "t", clipId: "c", frameRate: 30, anchorFrame: 0, anchorCorners: [0, 0, 1, 0, 1, 1, 0, 1],+ keyframes: [0, 10, 20].map(f => ({ frame: f, corners: Array.from({ length: 8 }, (_, i) => i + f) })), confidence: [1, 0.9, 0.2], lostFrames: [20], manualFrames: [] };++ it("interpolates corners between samples", () => {+ const at = planarCornersAt(data, 5)!;+ expect(at.corners[0]).toBeCloseTo(5);+ expect(at.exact).toBe(false);+ expect(planarCornersAt(data, 10)!.exact).toBe(true);+ expect(planarCornersAt({ ...data, keyframes: [], confidence: [] }, 3)).toBeNull();+ });++ it("applies a manual correction and clears the lost flag", () => {+ const fixed = correctPlanarFrame(data, 20, [9, 9, 9, 9, 9, 9, 9, 9]);+ expect(fixed.lostFrames).toEqual([]);+ expect(fixed.manualFrames).toEqual([20]);+ expect(fixed.confidence[2]).toBe(1);+ const added = correctPlanarFrame(data, 15, [1, 1, 1, 1, 1, 1, 1, 1]);+ expect(added.keyframes.map(k => k.frame)).toEqual([0, 10, 15, 20]);+ expect(() => correctPlanarFrame(data, -1, [1, 1, 1, 1, 1, 1, 1, 1])).toThrow();+ });++ it("merges a partial re-track over the covered frames only", () => {+ const incoming = { ...data, keyframes: [{ frame: 10, corners: Array(8).fill(99) }, { frame: 20, corners: Array(8).fill(98) }], confidence: [1, 1], lostFrames: [] };+ const merged = mergePlanarTrack(data, incoming);+ expect(merged.keyframes.map(k => k.frame)).toEqual([0, 10, 20]);+ expect(merged.keyframes[0].corners[0]).toBe(0);+ expect(merged.keyframes[1].corners[0]).toBe(99);+ expect(merged.lostFrames).toEqual([]);+ expect(cornersToQuad([1, 2, 3, 4, 5, 6, 7, 8])[2]).toEqual({ x: 5, y: 6 });+ });+});diff --git a/packages/core/src/video/planar-track.ts b/packages/core/src/video/planar-track.tsnew file mode 100644index 00000000..9b8881ba--- /dev/null+++ b/packages/core/src/video/planar-track.ts@@ -0,0 +1,349 @@+import { grayscale, type TrackingPixels } from "./motion-frame-tracker";+import {+ applyHomography, invertHomography, isConvexQuad, pointInQuad, quadArea, ransacHomography, transformQuad,+ type Pt, type Quad,+} from "./planar-homography";++/**+ * Planar (corner-pin) tracking. Shi-Tomasi features inside the surface quad are followed frame to frame with+ * pyramidal Lucas-Kanade (forward-backward checked). Every feature remembers its position on the anchor frame,+ * so a RANSAC homography is fitted anchor -> current rather than chained frame to frame: error does not+ * accumulate, outliers (occluders, moving objects) are rejected, and the four corners are the anchor quad+ * pushed through that homography. Pure and DOM-free; fully deterministic (seeded RANSAC, no clocks).+ */++export type PlanarStatus = "tracked" | "predicted";+/** Eight numbers: x0 y0 (TL) x1 y1 (TR) x2 y2 (BR) x3 y3 (BL), in source pixels. */+export type CornerList = readonly number[];++export interface PlanarSessionFrame extends TrackingPixels { sourceWidth?: number; sourceHeight?: number }+export interface PlanarSessionConfig {+ /** Surface corners at the anchor frame, source pixels, clockwise from the top left. */+ corners: CornerList;+ confidenceThreshold?: number;+ seed?: number;+}+export interface PlanarStep { corners: number[]; confidence: number; inliers: number; status: PlanarStatus; lost: boolean }++export interface PlanarStepper { step(frame: PlanarSessionFrame): Promise<PlanarStep>; dispose(): void }+export type PlanarStepperFactory = (config: PlanarSessionConfig) => PlanarStepper;++export function cornersToQuad(c: CornerList): Quad {+ return [{ x: c[0], y: c[1] }, { x: c[2], y: c[3] }, { x: c[4], y: c[5] }, { x: c[6], y: c[7] }];+}+export function quadToCorners(q: Quad): number[] { return q.flatMap(p => [p.x, p.y]); }++/* ----------------------------- image pyramid ----------------------------- */++interface Level { w: number; h: number; d: Float32Array }+const LEVELS = 4;++function buildPyramid(gray: Float32Array, w: number, h: number): Level[] {+ const levels: Level[] = [{ w, h, d: gray }];+ for (let l = 1; l < LEVELS; l++) {+ const p = levels[l - 1], nw = p.w >> 1, nh = p.h >> 1;+ if (nw < 16 || nh < 16) break;+ const d = new Float32Array(nw * nh);+ for (let y = 0; y < nh; y++) for (let x = 0; x < nw; x++) {+ const i = (2 * y) * p.w + 2 * x;+ d[y * nw + x] = (p.d[i] + p.d[i + 1] + p.d[i + p.w] + p.d[i + p.w + 1]) * 0.25;+ }+ levels.push({ w: nw, h: nh, d });+ }+ return levels;+}++function bilinear(l: Level, x: number, y: number): number {+ const x0 = Math.floor(x), y0 = Math.floor(y), fx = x - x0, fy = y - y0;+ const i = y0 * l.w + x0, d = l.d;+ return (d[i] * (1 - fx) + d[i + 1] * fx) * (1 - fy) + (d[i + l.w] * (1 - fx) + d[i + l.w + 1] * fx) * fy;+}++/* ------------------------------- features -------------------------------- */++export interface DetectOptions { maxPoints?: number; cell?: number; quality?: number; avoid?: readonly Pt[]; avoidRadius?: number }++/** Shi-Tomasi corners inside `quad`, at most one per grid cell so they spread over the surface. Deterministic. */+export function detectFeatures(gray: Float32Array, w: number, h: number, quad: Quad, options: DetectOptions = {}): Pt[] {+ const { maxPoints = 160, quality = 0.02, avoid = [], avoidRadius = 6 } = options;+ const xs = quad.map(p => p.x), ys = quad.map(p => p.y);+ const margin = 9;+ const x0 = Math.max(margin, Math.floor(Math.min(...xs))), x1 = Math.min(w - margin - 1, Math.ceil(Math.max(...xs)));+ const y0 = Math.max(margin, Math.floor(Math.min(...ys))), y1 = Math.min(h - margin - 1, Math.ceil(Math.max(...ys)));+ if (x1 - x0 < 8 || y1 - y0 < 8) return [];+ const bw = x1 - x0 + 1, bh = y1 - y0 + 1;+ const ix = new Float32Array(bw * bh), iy = new Float32Array(bw * bh);+ for (let y = 0; y < bh; y++) for (let x = 0; x < bw; x++) {+ const gx = x0 + x, gy = y0 + y, i = gy * w + gx;+ ix[y * bw + x] = (gray[i + 1] - gray[i - 1]) * 0.5; iy[y * bw + x] = (gray[i + w] - gray[i - w]) * 0.5;+ }+ const score = new Float32Array(bw * bh);+ let top = 0;+ const r = 2;+ for (let y = r; y < bh - r; y++) for (let x = r; x < bw - r; x++) {+ let a = 0, b = 0, c = 0;+ for (let dy = -r; dy <= r; dy++) for (let dx = -r; dx <= r; dx++) {+ const j = (y + dy) * bw + x + dx, gx = ix[j], gy = iy[j];+ a += gx * gx; b += gx * gy; c += gy * gy;+ }+ const tr = a + c, det = a * c - b * b;+ const min = tr / 2 - Math.sqrt(Math.max(0, tr * tr / 4 - det));+ score[y * bw + x] = min; if (min > top) top = min;+ }+ if (top <= 0) return [];+ const cell = options.cell ?? Math.max(8, Math.round(Math.sqrt(bw * bh / maxPoints)));+ const best = new Map<number, { s: number; p: Pt }>();+ for (let y = r; y < bh - r; y++) for (let x = r; x < bw - r; x++) {+ const s = score[y * bw + x];+ if (s < top * quality) continue;+ // Local maximum in a 3x3 so a corner is one point, not a blob.+ let peak = true;+ for (let dy = -1; dy <= 1 && peak; dy++) for (let dx = -1; dx <= 1; dx++) if ((dx || dy) && score[(y + dy) * bw + x + dx] > s) { peak = false; break; }+ if (!peak) continue;+ const p = { x: x0 + x, y: y0 + y };+ if (!pointInQuad(quad, p)) continue;+ if (avoid.some(a => Math.hypot(a.x - p.x, a.y - p.y) < avoidRadius)) continue;+ const key = Math.floor(y / cell) * 4096 + Math.floor(x / cell), held = best.get(key);+ if (!held || s > held.s) best.set(key, { s, p });+ }+ return [...best.values()].sort((a, b) => b.s - a.s || a.p.y - b.p.y || a.p.x - b.p.x).slice(0, maxPoints).map(v => v.p);+}++/* ------------------------- pyramidal Lucas-Kanade ------------------------- */++const WIN = 7;++/** Follow one point from `prev` to `cur`. Returns null when it leaves the image or the system is ill-conditioned. */+export function lucasKanade(prev: Level[], cur: Level[], point: Pt, guess: Pt = { x: 0, y: 0 }): { p: Pt; err: number } | null {+ const levels = Math.min(prev.length, cur.length);+ let gx = guess.x / 2 ** (levels - 1), gy = guess.y / 2 ** (levels - 1);+ let err = 0;+ const side = WIN * 2 + 1;+ const tpl = new Float32Array(side * side), dx = new Float32Array(side * side), dy = new Float32Array(side * side);+ for (let l = levels - 1; l >= 0; l--) {+ const P = prev[l], C = cur[l], s = 2 ** l, px = point.x / s, py = point.y / s;+ if (px < WIN + 2 || py < WIN + 2 || px > P.w - WIN - 3 || py > P.h - WIN - 3) { if (l === 0) return null; gx *= 2; gy *= 2; continue; }+ let sxx = 0, sxy = 0, syy = 0, k = 0;+ for (let y = -WIN; y <= WIN; y++) for (let x = -WIN; x <= WIN; x++, k++) {+ const fx = px + x, fy = py + y;+ tpl[k] = bilinear(P, fx, fy);+ dx[k] = (bilinear(P, fx + 1, fy) - bilinear(P, fx - 1, fy)) * 0.5; dy[k] = (bilinear(P, fx, fy + 1) - bilinear(P, fx, fy - 1)) * 0.5;+ sxx += dx[k] * dx[k]; sxy += dx[k] * dy[k]; syy += dy[k] * dy[k];+ }+ const det = sxx * syy - sxy * sxy;+ if (det < 1e-3 * side * side) return null;+ for (let it = 0; it < 20; it++) {+ const cx = px + gx, cy = py + gy;+ if (cx < WIN + 2 || cy < WIN + 2 || cx > C.w - WIN - 3 || cy > C.h - WIN - 3) return null;+ let bx = 0, by = 0, e = 0;+ k = 0;+ for (let y = -WIN; y <= WIN; y++) for (let x = -WIN; x <= WIN; x++, k++) {+ const diff = tpl[k] - bilinear(C, cx + x, cy + y);+ bx += diff * dx[k]; by += diff * dy[k]; e += Math.abs(diff);+ }+ const ux = (syy * bx - sxy * by) / det, uy = (sxx * by - sxy * bx) / det;+ gx += ux; gy += uy; err = e / (side * side);+ if (ux * ux + uy * uy < 1e-4) break;+ }+ if (l > 0) { gx *= 2; gy *= 2; }+ }+ const out = { x: point.x + gx, y: point.y + gy };+ return Number.isFinite(out.x) && Number.isFinite(out.y) ? { p: out, err } : null;+}++/* --------------------------------- session -------------------------------- */++interface Track { a: Pt; p: Pt }+const TARGET_POINTS = 100;+const MIN_POINTS = 8;+const FB_TOLERANCE = 1.2;+const MAX_ERR = 24;+const RANSAC_THRESHOLD = 1.6;++export class PlanarTrackSession {+ private readonly threshold: number;+ private readonly seed: number;+ private anchor: Quad | null = null;+ private prev: Level[] | null = null;+ private tracks: Track[] = [];+ private last: Quad | null = null;+ private frames = 0;+ private sx = 1;+ private sy = 1;++ constructor(private readonly config: PlanarSessionConfig) {+ if (config.corners.length !== 8 || !config.corners.every(Number.isFinite)) throw new Error("Choose four valid corners");+ this.threshold = config.confidenceThreshold ?? 0.5;+ this.seed = config.seed ?? 1;+ }++ async step(frame: PlanarSessionFrame): Promise<PlanarStep> {+ this.sx = frame.width / (frame.sourceWidth ?? frame.width); this.sy = frame.height / (frame.sourceHeight ?? frame.height);+ if (!Number.isFinite(this.sx) || !Number.isFinite(this.sy) || this.sx <= 0 || this.sy <= 0) throw new Error("Tracking frame dimensions are invalid");+ const gray = grayscale(frame), pyramid = buildPyramid(gray, frame.width, frame.height);+ const emit = (quad: Quad, confidence: number, inliers: number, status: PlanarStatus): PlanarStep => {+ this.frames++;+ return { corners: quad.flatMap(p => [p.x / this.sx, p.y / this.sy]), confidence, inliers, status, lost: confidence < this.threshold };+ };++ if (!this.anchor) {+ const quad = cornersToQuad(this.config.corners).map(p => ({ x: p.x * this.sx, y: p.y * this.sy })) as unknown as Quad;+ if (!isConvexQuad(quad) || Math.abs(quadArea(quad)) < 400) throw new Error("Place the four corners around a visible surface");+ const points = detectFeatures(gray, frame.width, frame.height, quad);+ if (points.length < MIN_POINTS) throw new Error("The surface has too little detail to track; choose a textured area");+ this.anchor = quad; this.last = quad; this.prev = pyramid;+ this.tracks = points.map(p => ({ a: p, p }));+ return emit(quad, 1, points.length, "tracked");+ }++ const anchor = this.anchor, previous = this.prev!;+ const next: Track[] = [];+ for (const t of this.tracks) {+ const fwd = lucasKanade(previous, pyramid, t.p);+ if (!fwd || fwd.err > MAX_ERR) continue;+ const back = lucasKanade(pyramid, previous, fwd.p);+ if (!back || Math.hypot(back.p.x - t.p.x, back.p.y - t.p.y) > FB_TOLERANCE) continue;+ next.push({ a: t.a, p: fwd.p });+ }+ const fit = next.length >= MIN_POINTS+ ? ransacHomography(next.map(t => ({ from: t.a, to: t.p })), { threshold: RANSAC_THRESHOLD, iterations: 150, seed: this.seed + this.frames, minInliers: MIN_POINTS })+ : null;+ const quad = fit ? transformQuad(fit.homography, anchor) : null;+ const prevArea = Math.abs(quadArea(this.last!)), area = quad ? Math.abs(quadArea(quad)) : 0;+ if (!fit || !quad || !isConvexQuad(quad) || area < prevArea * 0.5 || area > prevArea * 2) {+ // Surface not found: hold the last good corners, keep the last good frame and points to recover from.+ return emit(this.last!, 0, fit?.inlierCount ?? 0, "predicted");+ }+ const kept = next.filter((_, i) => fit.inliers[i]);+ const ratio = fit.inlierCount / next.length;+ let confidence = Math.min(1, ratio) * Math.min(1, fit.inlierCount / 15) * (1 - Math.min(0.5, fit.rmsError / RANSAC_THRESHOLD * 0.25));+ confidence = Math.max(0, Math.min(1, confidence));+ this.last = quad;+ if (kept.length < TARGET_POINTS * 0.6) {+ const inverse = invertHomography(fit.homography);+ if (inverse) {+ const fresh = detectFeatures(gray, frame.width, frame.height, quad, { maxPoints: TARGET_POINTS - kept.length, avoid: kept.map(t => t.p) });+ for (const p of fresh) kept.push({ a: applyHomography(inverse, p), p });+ }+ }+ this.tracks = kept; this.prev = pyramid;+ return emit(quad, confidence, fit.inlierCount, "tracked");+ }+}++/* ------------------------------ persisted data ----------------------------- */++export interface PlanarTrackKeyframe { frame: number; corners: number[] }+export interface PlanarTrackData {+ version: 1;+ trackId: string;+ clipId: string;+ frameRate: number;+ anchorFrame: number;+ /** Corners the user placed on the anchor frame, source pixels. */+ anchorCorners: number[];+ keyframes: PlanarTrackKeyframe[];+ confidence: number[];+ lostFrames: number[];+ /** Frames whose corners were edited by hand (always full confidence). */+ manualFrames: number[];+ stats?: { frames: number; elapsedMs: number; framesPerSecond: number };+}++export interface PlanarTrackOptions {+ clipId: string;+ frameRate: number;+ /** Frame where `corners` is defined; tracked up to `endFrame` (forward) or down to `startFrame` (backward). */+ anchorFrame: number;+ startFrame: number;+ endFrame: number;+ direction?: "forward" | "backward";+ corners: CornerList;+ confidenceThreshold?: number;+ readFrame: (frame: number) => Promise<PlanarSessionFrame | null>;+ createStepper?: PlanarStepperFactory;+ signal?: AbortSignal;+ onProgress?: (percent: number, lostFrames: number) => void;+ now?: () => number;+}++function abortError(): Error { return new DOMException("Tracking cancelled", "AbortError"); }++/** Run a planar track over a frame range. Rejects with an AbortError on cancel. Progress is reported per frame. */+export async function trackPlanarSurface(options: PlanarTrackOptions): Promise<PlanarTrackData> {+ const { startFrame, endFrame, anchorFrame, signal } = options;+ if (!Number.isInteger(startFrame) || !Number.isInteger(endFrame) || startFrame < 0 || endFrame < startFrame || anchorFrame < startFrame || anchorFrame > endFrame) throw new Error("Tracking requires a valid frame range");+ const backward = options.direction === "backward";+ const order: number[] = [];+ if (backward) for (let f = anchorFrame; f >= startFrame; f--) order.push(f); else for (let f = anchorFrame; f <= endFrame; f++) order.push(f);+ const config: PlanarSessionConfig = { corners: options.corners, confidenceThreshold: options.confidenceThreshold };+ const stepper: PlanarStepper = options.createStepper ? options.createStepper(config) : (() => { const s = new PlanarTrackSession(config); return { step: (f: PlanarSessionFrame) => s.step(f), dispose: () => undefined }; })();+ const now = options.now ?? (() => Date.now());+ const began = now();+ const rows: Array<{ frame: number; step: PlanarStep }> = [];+ try {+ let upcoming: Promise<PlanarSessionFrame | null> | null = options.readFrame(order[0]);+ for (let i = 0; i < order.length; i++) {+ if (signal?.aborted) throw abortError();+ const pixels = await upcoming;+ if (signal?.aborted) throw abortError();+ if (!pixels) throw new Error(`Could not decode tracking frame ${order[i]}`);+ upcoming = i + 1 < order.length ? options.readFrame(order[i + 1]) : null;+ upcoming?.catch(() => undefined);+ const step = await stepper.step(pixels);+ rows.push({ frame: order[i], step });+ options.onProgress?.(order.length === 1 ? 100 : i / (order.length - 1) * 100, rows.filter(r => r.step.lost).length);+ await new Promise<void>(resolve => setTimeout(resolve, 0));+ }+ } finally { stepper.dispose(); }+ rows.sort((a, b) => a.frame - b.frame);+ const elapsed = Math.max(1, now() - began);+ return {+ version: 1, trackId: `planar-${options.clipId}-${anchorFrame}-${backward ? "b" : "f"}`, clipId: options.clipId, frameRate: options.frameRate,+ anchorFrame, anchorCorners: [...options.corners],+ keyframes: rows.map(r => ({ frame: r.frame, corners: r.step.corners })),+ confidence: rows.map(r => r.step.confidence),+ lostFrames: rows.filter(r => r.step.lost).map(r => r.frame),+ manualFrames: [],+ stats: { frames: rows.length, elapsedMs: elapsed, framesPerSecond: rows.length / (elapsed / 1000) },+ };+}++/** Replace the frames a re-track covered, keeping the rest (partial forward/backward re-tracks refine the path). */+export function mergePlanarTrack(existing: PlanarTrackData | null, incoming: PlanarTrackData): PlanarTrackData {+ if (!existing || existing.clipId !== incoming.clipId || existing.frameRate !== incoming.frameRate || !incoming.keyframes.length) return incoming;+ const first = incoming.keyframes[0].frame, last = incoming.keyframes[incoming.keyframes.length - 1].frame;+ const lostBefore = new Set(existing.lostFrames), lostNow = new Set(incoming.lostFrames);+ const rows: Array<{ key: PlanarTrackKeyframe; c: number; lost: boolean }> = [];+ existing.keyframes.forEach((key, i) => { if (key.frame < first || key.frame > last) rows.push({ key, c: existing.confidence[i] ?? 1, lost: lostBefore.has(key.frame) }); });+ incoming.keyframes.forEach((key, i) => rows.push({ key, c: incoming.confidence[i] ?? 1, lost: lostNow.has(key.frame) }));+ rows.sort((a, b) => a.key.frame - b.key.frame);+ return { ...incoming, anchorFrame: existing.anchorFrame, anchorCorners: existing.anchorCorners, keyframes: rows.map(r => r.key), confidence: rows.map(r => r.c),+ lostFrames: rows.filter(r => r.lost).map(r => r.key.frame), manualFrames: existing.manualFrames.filter(f => f < first || f > last) };+}++/** Corners at a frame, linearly interpolated between samples (this is exactly what the exported keyframes do). */+export function planarCornersAt(data: PlanarTrackData, frame: number): { corners: number[]; confidence: number; exact: boolean; manual: boolean } | null {+ const keys = data.keyframes;+ if (!keys.length) return null;+ let next = keys.findIndex(k => k.frame >= frame);+ if (next < 0) next = keys.length - 1;+ const after = keys[next];+ const manual = data.manualFrames.includes(after.frame);+ if (after.frame === frame || next === 0 || after.frame < frame) return { corners: [...after.corners], confidence: data.confidence[next] ?? 1, exact: after.frame === frame, manual: manual && after.frame === frame };+ const before = keys[next - 1], t = (frame - before.frame) / Math.max(1, after.frame - before.frame);+ return { corners: before.corners.map((v, i) => v + (after.corners[i] - v) * t), confidence: Math.min(data.confidence[next - 1] ?? 1, data.confidence[next] ?? 1), exact: false, manual: false };+}++/** Set one corner (or all four) at a frame by hand. Adds the frame when the track has no sample there. */+export function correctPlanarFrame(data: PlanarTrackData, frame: number, corners: CornerList): PlanarTrackData {+ if (!Number.isInteger(frame) || frame < 0 || corners.length !== 8 || !corners.every(Number.isFinite)) throw new Error("Choose a valid frame and corners");+ const keys = data.keyframes.map(k => ({ frame: k.frame, corners: [...k.corners] })), confidence = [...data.confidence];+ const at = keys.findIndex(k => k.frame === frame);+ if (at >= 0) { keys[at].corners = [...corners]; confidence[at] = 1; }+ else {+ const insert = keys.findIndex(k => k.frame > frame), index = insert < 0 ? keys.length : insert;+ keys.splice(index, 0, { frame, corners: [...corners] }); confidence.splice(index, 0, 1);+ }+ return { ...data, keyframes: keys, confidence, lostFrames: data.lostFrames.filter(f => f !== frame), manualFrames: [...new Set([...data.manualFrames, frame])].sort((a, b) => a - b) };+}diff --git a/packages/core/src/video/pro-effect-shaders-extra.ts b/packages/core/src/video/pro-effect-shaders-extra.tsindex c63a3639..8fbc3b6d 100644--- a/packages/core/src/video/pro-effect-shaders-extra.ts+++ b/packages/core/src/video/pro-effect-shaders-extra.ts@@ -7,6 +7,8 @@*/import { PRELUDE } from "./pro-effect-prelude";import type { ExtraProEffectType } from "./pro-effects-extra";+import { ULTRA_KEY_GLSL } from "./ultra-key-shader";+import { ULTRA_KEY_UNIFORM_NAMES } from "./ultra-key";const HELPERS = `${PRELUDE}float hashU(int a, int b, int c) {@@ -573,6 +575,7 @@ export const EXTRA_GLSL: Readonly<Record<ExtraProEffectType, string>> = {"tilt-shift": TILT_SHIFT,"luma-key": LUMA_KEY,"color-key": COLOR_KEY,+ "ultra-key": ULTRA_KEY_GLSL,"alpha-adjust": ALPHA_ADJUST,"leave-color": LEAVE_COLOR,"change-to-color": CHANGE_TO_COLOR,@@ -607,6 +610,7 @@ export const EXTRA_UNIFORMS: Readonly<Record<ExtraProEffectType, readonly string"tilt-shift": ["blur", "count", "nx", "ny", "shiftPct", "bandPct", "fadePct"],"luma-key": ["dark", "threshold", "softness"],"color-key": ["keyR", "keyG", "keyB", "tolerance", "softness", "invert"],+ "ultra-key": ULTRA_KEY_UNIFORM_NAMES,"alpha-adjust": ["opacity", "ignore", "invert", "matte"],"leave-color": ["keyR", "keyG", "keyB", "amount", "tolerance", "softness"],"change-to-color": ["fromR", "fromG", "fromB", "dR", "dG", "dB", "tolerance", "softness"],diff --git a/packages/core/src/video/pro-effect-shaders.ts b/packages/core/src/video/pro-effect-shaders.tsindex 3828aaba..726d8197 100644--- a/packages/core/src/video/pro-effect-shaders.ts+++ b/packages/core/src/video/pro-effect-shaders.ts@@ -503,6 +503,14 @@ void main() {}`;+/** Temporal effects never reach the pixel pass; this identity shader only keeps every type's def complete. */+const TEMPORAL_PASSTHROUGH = `${PRELUDE}+void main() {+ vec4 c = texture(u_input, vUv);+ fragColor = emit(c.rgb, c.a);+}+`;+const GLSL: Readonly<Record<ProEffectType, string>> = {mosaic: MOSAIC,posterize: POSTERIZE,@@ -521,6 +529,8 @@ const GLSL: Readonly<Record<ProEffectType, string>> = {vibrance: VIBRANCE,skew: SKEW,"hsl-secondary": HSL_SECONDARY,+ echo: TEMPORAL_PASSTHROUGH,+ "posterize-time": TEMPORAL_PASSTHROUGH,...EXTRA_GLSL,};@@ -543,6 +553,8 @@ const UNIFORMS: Readonly<Record<ProEffectType, readonly string[]>> = {vibrance: ["vibrance", "sat"],skew: ["a", "b", "c", "d", "valid"],"hsl-secondary": ["hMin", "hMax", "hSoft", "sMin", "sMax", "sSoft", "lMin", "lMax", "lSoft", "radius", "denoise", "invert", "mShape", "mCx", "mCy", "mHx", "mHy", "mFeather", "mInvert", "tempR", "tempG", "tempB", "wheelR", "wheelG", "wheelB", "contrast", "saturation", "sharpen", "view"],+ echo: [],+ "posterize-time": [],...EXTRA_UNIFORMS,};diff --git a/packages/core/src/video/pro-effects-extra.ts b/packages/core/src/video/pro-effects-extra.tsindex 994775d0..17e75e5c 100644--- a/packages/core/src/video/pro-effects-extra.ts+++ b/packages/core/src/video/pro-effects-extra.ts@@ -18,6 +18,12 @@* can be keyframed, validated and exposed to agents like any other number.* All randomness is a pure hash of (seed, clip-local time, position).*/+import {+ applyUltraKey,+ isUltraKeyNeutral,+ ultraKeyGpuUniforms,+ type UltraKeyParams,+} from "./ultra-key";import type {ProEffectCategory,ProEffectParamSpec,@@ -31,6 +37,7 @@ export const EXTRA_PRO_EFFECT_TYPES = ["tilt-shift","luma-key","color-key",+ "ultra-key","alpha-adjust","leave-color","change-to-color",@@ -67,6 +74,7 @@ export function isExtraProEffectType(type: string): type is ExtraProEffectType {export const EXTRA_EFFECTS_WRITING_ALPHA: readonly ExtraProEffectType[] = ["luma-key","color-key",+ "ultra-key","alpha-adjust","corner-pin",];@@ -238,6 +246,37 @@ export const EXTRA_PRO_EFFECT_SPECS: Readonly<toggle("invert", "Keep key colour", false, false),],),+ "ultra-key": spec(+ "ultra-key",+ "Ultra Key",+ "Premiere-style chroma keyer: matte, cleanup, spill suppression and colour correction",+ "Keying",+ [+ ...rgb("key", "Key", [0, 255, 0]),+ num("transparency", "Transparency", 0, 100, 1, 45, 0, "%"),+ num("highlight", "Highlight", 0, 100, 1, 10, 0, "%"),+ num("shadow", "Shadow", 0, 100, 1, 50, 0, "%"),+ num("tolerance", "Tolerance", 0, 100, 1, 50, 0, "%"),+ num("pedestal", "Pedestal", 0, 100, 1, 0, 0, "%"),+ num("choke", "Choke", 0, 100, 1, 0, 0),+ num("soften", "Soften", 0, 100, 1, 0, 0),+ num("contrast", "Contrast", 0, 100, 1, 0, 0),+ num("midPoint", "Mid point", 0, 100, 1, 50, 50, "%"),+ num("desaturate", "Desaturate", 0, 100, 1, 15, 0, "%"),+ num("range", "Range", 0, 100, 1, 50, 0, "%"),+ num("spill", "Spill", 0, 100, 1, 50, 0, "%"),+ num("luma", "Luma", 0, 100, 1, 50, 0, "%"),+ num("saturation", "Saturation", 0, 200, 1, 100, 100, "%"),+ num("hue", "Hue", -180, 180, 1, 0, 0, "°"),+ num("luminance", "Luminance", 0, 200, 1, 100, 100, "%"),+ select("output", "Output", "composite", "composite", [+ ["composite", "Composite"],+ ["alpha", "Alpha channel"],+ ["color", "Color channel"],+ ["source", "Source (key picker)"],+ ]),+ ],+ ),"alpha-adjust": spec("alpha-adjust","Alpha Adjust",@@ -620,6 +659,8 @@ export function isExtraNeutral(type: ExtraProEffectType, resolved: Params): boolreturn p.mode === "none";case "color-key":return n(p, "tolerance") === 0 && n(p, "softness") === 0 && !b(p, "invert");+ case "ultra-key":+ return isUltraKeyNeutral(p as unknown as UltraKeyParams);case "alpha-adjust":return (n(p, "opacity") === 100 && !b(p, "ignore") && !b(p, "invert") && !b(p, "matte")@@ -1051,6 +1092,9 @@ export function applyExtraProEffect(}break;}+ case "ultra-key":+ applyUltraKey(data, width, height, p as unknown as UltraKeyParams);+ break;case "alpha-adjust": {const opacity = n(p, "opacity") / 100;for (let o = 0; o < data.length; o += 4) {@@ -1511,6 +1555,8 @@ export function extraProEffectGpuUniforms(softness: n(p, "softness"),invert: b(p, "invert") ? 1 : 0,};+ case "ultra-key":+ return ultraKeyGpuUniforms(p as unknown as UltraKeyParams);case "alpha-adjust":return {opacity: n(p, "opacity") / 100,diff --git a/packages/core/src/video/pro-effects.test.ts b/packages/core/src/video/pro-effects.test.tsindex 6c5ae8b8..d2edb83d 100644--- a/packages/core/src/video/pro-effects.test.ts+++ b/packages/core/src/video/pro-effects.test.ts@@ -26,6 +26,7 @@ import {} from "./pro-effects";import { PRO_EFFECT_SHADER_DEFS } from "./pro-effect-shaders";import { EXTRA_PRO_EFFECT_TYPES } from "./pro-effects-extra";+import { TEMPORAL_PRO_EFFECT_TYPES, isTemporalEffectType } from "./temporal-effects";function makeImage(width: number, height: number): Uint8ClampedArray {const data = new Uint8ClampedArray(width * height * 4);@@ -84,6 +85,7 @@ describe("pro effects registration", () => {"skew","hsl-secondary",...EXTRA_PRO_EFFECT_TYPES,+ ...TEMPORAL_PRO_EFFECT_TYPES,].sort(),);});@@ -111,7 +113,8 @@ describe("pro effects neutral-parameter identity", () => {expect(isProEffectNeutral(type, {})).toBe(true);});- it(`${type} changes the image with its default params and is not neutral`, () => {+ // Temporal effects choose frames, not pixels: their pixel pass is the identity (temporal-effects.test.ts).+ it.skipIf(isTemporalEffectType(type))(`${type} changes the image with its default params and is not neutral`, () => {const original = makeImage(W, H);const data = new Uint8ClampedArray(original);applyProEffect(type, { ...PRO_EFFECT_DEFAULTS[type] }, data, W, H);diff --git a/packages/core/src/video/pro-effects.ts b/packages/core/src/video/pro-effects.tsindex 66ddb7c4..dafb5222 100644--- a/packages/core/src/video/pro-effects.ts+++ b/packages/core/src/video/pro-effects.ts@@ -30,6 +30,13 @@ import {isExtraNeutral,isExtraProEffectType,} from "./pro-effects-extra";+import {+ TEMPORAL_EFFECTS_WRITING_ALPHA,+ TEMPORAL_PRO_EFFECT_SPECS,+ TEMPORAL_PRO_EFFECT_TYPES,+ isTemporalEffectType,+ isTemporalNeutral,+} from "./temporal-effects";const BASE_PRO_EFFECT_TYPES = ["mosaic",@@ -55,6 +62,7 @@ const BASE_PRO_EFFECT_TYPES = [export const PRO_EFFECT_TYPES = [...BASE_PRO_EFFECT_TYPES,...EXTRA_PRO_EFFECT_TYPES,+ ...TEMPORAL_PRO_EFFECT_TYPES,] as const;export type ProEffectType = (typeof PRO_EFFECT_TYPES)[number];@@ -71,6 +79,7 @@ export const PRO_EFFECTS_WRITING_ALPHA: readonly ProEffectType[] = ["crop","skew",...EXTRA_EFFECTS_WRITING_ALPHA,+ ...TEMPORAL_EFFECTS_WRITING_ALPHA,];export type MirrorMode = "none" | "horizontal" | "vertical" | "quad";@@ -82,7 +91,8 @@ export type ProEffectCategory =| "Color"| "Keying"| "Distort"- | "Generate";+ | "Generate"+ | "Time";export interface ProEffectParamSpec {readonly key: string;@@ -140,6 +150,7 @@ const toggle = (export const PRO_EFFECT_SPECS: Readonly<Record<ProEffectType, ProEffectSpec>> = {...EXTRA_PRO_EFFECT_SPECS,+ ...TEMPORAL_PRO_EFFECT_SPECS,mosaic: {type: "mosaic",label: "Mosaic",@@ -584,6 +595,7 @@ export function isProEffectNeutral(): boolean {const p = resolveProEffectParams(type, rawParams);if (isExtraProEffectType(type)) return isExtraNeutral(type, p);+ if (isTemporalEffectType(type)) return isTemporalNeutral(type, p);switch (type) {case "mosaic":return Math.floor(n(p, "size")) <= 1;@@ -1391,6 +1403,8 @@ export function applyProEffect(applyExtraProEffect(type, p, data, width, height);return true;}+ // Temporal effects choose frames rather than recolour one: the pixel pass is the identity.+ if (isTemporalEffectType(type)) return true;switch (type) {case "mosaic":applyMosaic(data, width, height, n(p, "size"));@@ -1526,6 +1540,7 @@ export function proEffectGpuUniforms(): Record<string, number> {const p = resolveProEffectParams(type, rawParams);if (isExtraProEffectType(type)) return extraProEffectGpuUniforms(type, p);+ if (isTemporalEffectType(type)) return {};switch (type) {case "mosaic":return { size: Math.floor(clamp(n(p, "size"), 1, 400)) };diff --git a/packages/core/src/video/temporal-effects.test.ts b/packages/core/src/video/temporal-effects.test.tsnew file mode 100644index 00000000..ddc622dc--- /dev/null+++ b/packages/core/src/video/temporal-effects.test.ts@@ -0,0 +1,313 @@+import { describe, expect, it } from "vitest";+import {+ PRO_EFFECT_DEFAULTS,+ PRO_EFFECT_NEUTRAL_PARAMS,+ PRO_EFFECT_SPECS,+ applyProEffect,+ isProEffectNeutral,+ isProEffectType,+ parseProEffectKeyframeProperty,+} from "./pro-effects";+import { getDefaultEffectParams } from "./effect-defaults";+import { getAnimatedVideoEffects, isRenderableVideoEffect } from "./animated-video-effects";+import {+ ECHO_OPERATORS,+ MAX_ECHOES,+ clipHasTemporalEffects,+ compositeEchoReference,+ echoCompositeOrder,+ echoIntensity,+ echoSampleTime,+ findActiveEcho,+ isTemporalNeutral,+ planEcho,+ posterizeFrameIndex,+ posterizeTime,+ posterizedClipTime,+ resolveEcho,+ resolvePosterizeRate,+ type EchoOperator,+} from "./temporal-effects";++describe("Posterize Time frame math", () => {+ it("holds the start of each 1/fps interval", () => {+ expect(posterizeTime(0, 10)).toBe(0);+ expect(posterizeTime(0.099, 10)).toBe(0);+ expect(posterizeTime(0.1, 10)).toBeCloseTo(0.1, 12);+ expect(posterizeTime(0.37, 10)).toBeCloseTo(0.3, 12);+ expect(posterizeTime(1.999, 1)).toBe(1);+ });++ it("does not lose a frame to float error (0.3 * 10 = 3.0000000000000004, 0.7 * 10 = 7.000000000000001)", () => {+ expect(posterizeFrameIndex(0.3, 10)).toBe(3);+ expect(posterizeFrameIndex(0.7, 10)).toBe(7);+ expect(posterizeFrameIndex(0.1 + 0.2, 10)).toBe(3);+ // 29.97 fps timeline positions land on their own frame+ for (let n = 0; n < 600; n++) expect(posterizeFrameIndex(n / 24, 24)).toBe(n);+ });++ it("is idempotent and never moves time forward", () => {+ for (const fps of [1, 4, 8, 12, 23.976, 30, 120]) {+ for (let i = 0; i < 400; i++) {+ const t = i * 0.0371;+ const held = posterizeTime(t, fps);+ expect(held).toBeLessThanOrEqual(t + 1e-6);+ expect(t - held).toBeLessThan(1 / fps + 1e-9);+ expect(posterizeTime(held, fps)).toBeCloseTo(held, 9);+ }+ }+ });++ it("shows the same frame for every output frame inside one posterized frame", () => {+ const fps = 5;+ const shown = new Set<number>();+ for (let i = 0; i < 24; i++) shown.add(posterizeTime(0.4 + i / 120, fps));+ // 0.4 .. 0.6 spans exactly one posterized frame boundary (at 0.6 not reached)+ expect([...shown]).toEqual([0.4]);+ });++ it("is off for a zero rate and for non-finite input", () => {+ expect(posterizeTime(1.234, 0)).toBe(1.234);+ expect(posterizeTime(1.234, -3)).toBe(1.234);+ expect(posterizeTime(Number.NaN, 8)).toBeNaN();+ expect(posterizeTime(1.234, Number.NaN)).toBe(1.234);+ });++ it("applies the first enabled non-zero Posterize Time of a stack", () => {+ const effects = [+ { type: "posterize-time", enabled: false, params: { frameRate: 2 } },+ { type: "posterize-time", enabled: true, params: { frameRate: 0 } },+ { type: "posterize-time", enabled: true, params: { frameRate: 4 } },+ { type: "posterize-time", enabled: true, params: { frameRate: 1 } },+ ];+ expect(posterizedClipTime(effects, 0.6)).toBeCloseTo(0.5, 12);+ expect(posterizedClipTime([], 0.6)).toBe(0.6);+ });+});++describe("Echo frame times", () => {+ const echo = resolveEcho({ echoTime: 0.1, echoes: 3, startIntensity: 1, decay: 0.5, operator: "add" });++ it("samples t - k * echoTime", () => {+ expect(echoSampleTime(2, 1, 0.1)).toBeCloseTo(1.9, 12);+ expect(echoSampleTime(2, 3, 0.1)).toBeCloseTo(1.7, 12);+ expect(echoSampleTime(2, 2, -0.25)).toBeCloseTo(2.5, 12);+ });++ it("weights echo k by startIntensity * decay^k", () => {+ expect(echoIntensity(0, 0.8, 0.5)).toBeCloseTo(0.8, 12);+ expect(echoIntensity(1, 0.8, 0.5)).toBeCloseTo(0.4, 12);+ expect(echoIntensity(3, 0.8, 0.5)).toBeCloseTo(0.1, 12);+ expect(echoIntensity(5, 1, 0)).toBe(0);+ });++ it("plans the echo frames of a frame deterministically", () => {+ const plan = planEcho(2, 10, echo);+ expect(plan.map((s) => s.k)).toEqual([1, 2, 3]);+ expect(plan.map((s) => s.localTime)).toEqual([+ expect.closeTo(1.9, 9),+ expect.closeTo(1.8, 9),+ expect.closeTo(1.7, 9),+ ]);+ expect(plan.map((s) => s.weight)).toEqual([0.5, 0.25, 0.125]);+ expect(planEcho(2, 10, echo)).toEqual(plan);+ });++ it("depends only on the clip-local time, never on call order or history", () => {+ const a = planEcho(5.04, 10, echo);+ planEcho(1, 10, echo);+ planEcho(9.9, 10, echo);+ expect(planEcho(5.04, 10, echo)).toEqual(a);+ });++ it("drops echoes before the clip start and past its end", () => {+ const early = planEcho(0.15, 10, echo);+ expect(early.map((s) => s.k)).toEqual([1]);+ expect(planEcho(0, 10, echo)).toEqual([]);+ const future = resolveEcho({ echoTime: -0.5, echoes: 4, startIntensity: 1, decay: 0.5 });+ expect(planEcho(8.2, 10, future).map((s) => s.k)).toEqual([1, 2, 3]);+ expect(planEcho(9.9, 10, future)).toEqual([]);+ });++ it("keeps an echo that lands exactly on the first frame", () => {+ const plan = planEcho(0.3, 10, echo);+ expect(plan.map((s) => s.k)).toEqual([1, 2, 3]);+ expect(plan[2].localTime).toBeCloseTo(0, 9);+ expect(plan[2].localTime).toBeGreaterThanOrEqual(0);+ });++ it("drops zero-intensity echoes", () => {+ const flat = resolveEcho({ echoTime: 0.1, echoes: 4, startIntensity: 1, decay: 0 });+ expect(planEcho(2, 10, flat)).toEqual([]);+ });++ it("composites Composite in Front farthest-first so the nearest echo ends on top", () => {+ const front = resolveEcho({ echoTime: 0.1, echoes: 3, operator: "composite-front" });+ expect(planEcho(2, 10, front).map((s) => s.k)).toEqual([3, 2, 1]);+ expect(echoCompositeOrder([{ k: 2 }, { k: 1 }], "composite-back").map((s) => s.k)).toEqual([1, 2]);+ });+});++describe("parameter resolution", () => {+ it("clamps and rounds stored values", () => {+ const echo = resolveEcho({ echoTime: 99, echoes: 2.6, startIntensity: 7, decay: -1, operator: "nope" });+ expect(echo).toEqual({ echoTime: 2, echoes: 3, startIntensity: 1, decay: 0, operator: "add" });+ expect(resolveEcho({ echoes: 1e6 }).echoes).toBe(MAX_ECHOES);+ expect(resolveEcho({}).echoes).toBe(0);+ });++ it("reads the posterize rate", () => {+ expect(resolvePosterizeRate({ frameRate: 12 })).toBe(12);+ expect(resolvePosterizeRate({ frameRate: 1e6 })).toBe(120);+ expect(resolvePosterizeRate({})).toBe(0);+ });++ it("treats zero echoes / zero rate as the neutral no-op", () => {+ expect(isTemporalNeutral("echo", { echoes: 0 })).toBe(true);+ expect(isTemporalNeutral("echo", { echoes: 1 })).toBe(false);+ expect(isTemporalNeutral("posterize-time", { frameRate: 0 })).toBe(true);+ expect(isTemporalNeutral("posterize-time", { frameRate: 12 })).toBe(false);+ });++ it("finds the first active echo", () => {+ const effects = [+ { type: "blur", enabled: true, params: {} },+ { type: "echo", enabled: true, params: { echoes: 0 } },+ { type: "echo", enabled: false, params: { echoes: 3 } },+ { type: "echo", enabled: true, params: { echoes: 2, operator: "screen" } },+ ];+ const found = findActiveEcho(effects);+ expect(found?.index).toBe(3);+ expect(found?.echo.operator).toBe("screen");+ expect(findActiveEcho([])).toBeNull();+ });+});++describe("pro effect registration", () => {+ it("registers both effects as keyframable Time pro effects", () => {+ for (const type of ["echo", "posterize-time"] as const) {+ expect(isProEffectType(type)).toBe(true);+ expect(PRO_EFFECT_SPECS[type].category).toBe("Time");+ expect(isProEffectNeutral(type, PRO_EFFECT_NEUTRAL_PARAMS[type])).toBe(true);+ expect(isProEffectNeutral(type, PRO_EFFECT_DEFAULTS[type])).toBe(false);+ expect(getDefaultEffectParams(type)).toEqual(PRO_EFFECT_DEFAULTS[type]);+ }+ for (const key of ["echoTime", "echoes", "startIntensity", "decay"]) {+ expect(parseProEffectKeyframeProperty(`effect.echo.${key}`)).not.toBeNull();+ }+ expect(parseProEffectKeyframeProperty("effect.posterize-time.frameRate")).not.toBeNull();+ expect(parseProEffectKeyframeProperty("effect.echo.operator")).toBeNull();+ });++ it("exposes the six Premiere echo operators", () => {+ const options = PRO_EFFECT_SPECS.echo.params.find((p) => p.key === "operator")?.options ?? [];+ expect(options.map((o) => o.value)).toEqual([...ECHO_OPERATORS]);+ });++ it("is an identity in the per-pixel pass", () => {+ const data = new Uint8ClampedArray([10, 20, 30, 255, 200, 100, 50, 128]);+ const before = [...data];+ expect(applyProEffect("echo", PRO_EFFECT_DEFAULTS.echo, data, 2, 1)).toBe(true);+ expect(applyProEffect("posterize-time", PRO_EFFECT_DEFAULTS["posterize-time"], data, 2, 1)).toBe(true);+ expect([...data]).toEqual(before);+ });++ it("renders only when not neutral", () => {+ expect(isRenderableVideoEffect({ id: "a", type: "echo", enabled: true, params: { echoes: 0 } })).toBe(false);+ expect(isRenderableVideoEffect({ id: "a", type: "echo", enabled: true, params: { echoes: 2 } })).toBe(true);+ });++ it("samples keyframed parameters at the clip-local time", () => {+ const clip = {+ id: "c",+ effects: [{ id: "e", type: "posterize-time", enabled: true, params: { frameRate: 12 } }],+ keyframes: [+ { id: "k1", time: 0, property: "effect.posterize-time.frameRate", value: 2, easing: "linear" },+ { id: "k2", time: 4, property: "effect.posterize-time.frameRate", value: 10, easing: "linear" },+ ],+ } as unknown as Parameters<typeof getAnimatedVideoEffects>[0];+ const at = (t: number) => getAnimatedVideoEffects(clip, t)[0].params.frameRate as number;+ expect(at(0)).toBeCloseTo(2, 6);+ expect(at(2)).toBeCloseTo(6, 6);+ expect(at(4)).toBeCloseTo(10, 6);+ // the held frame follows the rate at that frame+ expect(posterizedClipTime(getAnimatedVideoEffects(clip, 2), 2.4)).toBeCloseTo(2.333333, 5);+ expect(clipHasTemporalEffects(clip as never)).toBe(true);+ expect(clipHasTemporalEffects({ effects: [{ type: "blur", enabled: true }], keyframes: [] })).toBe(false);+ });+});++/** RGBA pixels from a list of [r, g, b, a] bytes. */+const px = (...p: number[][]) => new Uint8ClampedArray(p.flat());++describe("compositeEchoReference", () => {+ const base = px([200, 100, 40, 255], [10, 20, 30, 255]);+ const echoPx = px([100, 200, 255, 255], [250, 5, 30, 255]);+ const run = (operator: EchoOperator, weight: number, startIntensity = 1) =>+ [...compositeEchoReference(base, [{ data: echoPx, weight }], { operator, startIntensity })];++ it("is the identity with no echoes", () => {+ expect([...compositeEchoReference(base, [], { operator: "add", startIntensity: 1 })]).toEqual([...base]);+ });++ const near = (actual: number[], expected: number[]) => {+ expect(actual).toHaveLength(expected.length);+ actual.forEach((v, i) => expect(Math.abs(v - expected[i])).toBeLessThanOrEqual(1));+ };++ it("Add sums weighted frames and clamps", () => {+ near(run("add", 0.5), [250, 200, 168, 255, 135, 22, 45, 255]);+ near(run("add", 1), [255, 255, 255, 255, 255, 25, 60, 255]);+ });++ it("Add scales the current frame by the starting intensity", () => {+ near(run("add", 0.5, 0.5), [150, 150, 148, 255, 130, 13, 30, 255]);+ });++ it("Maximum / Minimum / Screen mix the blend result by the echo weight", () => {+ near(run("maximum", 1), [200, 200, 255, 255, 250, 20, 30, 255]);+ near(run("minimum", 1), [100, 100, 40, 255, 10, 5, 30, 255]);+ near(run("screen", 1), [222, 222, 255, 255, 250, 25, 56, 255]);+ // half weight lerps between the base and the full blend+ near(run("maximum", 0.5), [200, 150, 148, 255, 130, 20, 30, 255]);+ near(run("screen", 0.5), [211, 161, 148, 255, 130, 22, 43, 255]);+ // the starting intensity dims the current frame for Maximum too, like Add+ near(run("maximum", 0.5, 0.5), [100, 125, 138, 255, 128, 10, 22, 255]);+ });++ it("Composite in Front puts the echo over the frame at its opacity", () => {+ near(run("composite-front", 0.25), [175, 125, 94, 255, 70, 16, 30, 255]);+ near(run("composite-front", 1), [100, 200, 255, 255, 250, 5, 30, 255]);+ // composites never dim the current frame by the starting intensity+ near(run("composite-front", 0.25, 0.1), [175, 125, 94, 255, 70, 16, 30, 255]);+ });++ it("Composite in Back only shows through transparent pixels of the frame", () => {+ expect(run("composite-back", 1)).toEqual([...base]);+ const hole = px([0, 0, 0, 0], [10, 20, 30, 128]);+ const out = compositeEchoReference(hole, [{ data: echoPx, weight: 0.5 }], {+ operator: "composite-back",+ startIntensity: 1,+ });+ // fully transparent pixel takes the echo at half opacity+ expect([...out.slice(0, 4)]).toEqual([100, 200, 255, 128]);+ // half-transparent pixel gains opacity: 0.502 + 0.5 * 0.498+ expect(Math.abs(out[7] - 191)).toBeLessThanOrEqual(1);+ });++ it("applies echoes in the given order for non-commutative operators", () => {+ const red = px([255, 0, 0, 255]);+ const blue = px([0, 0, 255, 255]);+ const none = px([0, 0, 0, 255]);+ const a = compositeEchoReference(none, [{ data: red, weight: 0.5 }, { data: blue, weight: 0.5 }], {+ operator: "composite-front",+ startIntensity: 1,+ });+ const b = compositeEchoReference(none, [{ data: blue, weight: 0.5 }, { data: red, weight: 0.5 }], {+ operator: "composite-front",+ startIntensity: 1,+ });+ expect([...a]).toEqual([64, 0, 128, 255]);+ expect([...b]).toEqual([128, 0, 64, 255]);+ });+});diff --git a/packages/core/src/video/temporal-effects.ts b/packages/core/src/video/temporal-effects.tsnew file mode 100644index 00000000..206793f1--- /dev/null+++ b/packages/core/src/video/temporal-effects.ts@@ -0,0 +1,415 @@+/**+ * Temporal (Premiere "Time") video effects: Echo and Posterize Time.+ *+ * Both are pro effects in every way that matters to the rest of the app (spec,+ * defaults, inspector, keyframes, agent schemas, presets), but neither can be+ * a per-frame pixel pass: they decide WHICH source frames are shown, not how a+ * frame looks. This module is the single source of truth for that decision:+ *+ * - TEMPORAL_PRO_EFFECT_SPECS: labels, ranges, defaults and neutral values.+ * - posterizeTime / posterizedClipTime: Posterize Time quantises the clip-local+ * time onto a fixed frame grid, so the source frame shown is the same for+ * every output frame inside one posterized frame.+ * - planEcho: the clip-local times of the echo frames (t - k * echoTime), with+ * the intensity of each, dropping echoes that fall outside the clip.+ * - compositeEchoReference: the pure per-pixel definition of the six echo+ * operators. The renderer (echo-compositor.ts) draws the same operators with+ * Canvas2D composite modes and is checked against this reference.+ *+ * Everything is a pure function of (clip-local time, parameters): there is no+ * wall clock and no frame history, so preview, playback scrubbing and export+ * produce the identical frame for the same timeline position.+ */+import type {+ ProEffectCategory,+ ProEffectParamSpec,+ ProEffectSpec,+} from "./pro-effects";++export const TEMPORAL_PRO_EFFECT_TYPES = ["echo", "posterize-time"] as const;++export type TemporalEffectType = (typeof TEMPORAL_PRO_EFFECT_TYPES)[number];++const TEMPORAL_SET: ReadonlySet<string> = new Set(TEMPORAL_PRO_EFFECT_TYPES);++export function isTemporalEffectType(type: string): type is TemporalEffectType {+ return TEMPORAL_SET.has(type);+}++/** Temporal effects only ever change a layer's alpha through the Composite operators of Echo. */+export const TEMPORAL_EFFECTS_WRITING_ALPHA: readonly TemporalEffectType[] = [+ "echo",+];++export const ECHO_OPERATORS = [+ "add",+ "maximum",+ "minimum",+ "screen",+ "composite-back",+ "composite-front",+] as const;++export type EchoOperator = (typeof ECHO_OPERATORS)[number];++/** Upper bound of "Number of echoes": each echo costs one extra decoded frame per output frame. */+export const MAX_ECHOES = 32;+/** Echo time slider range, seconds (positive = frames from the past, negative = from the future). */+export const MAX_ECHO_TIME = 2;+/** Highest Posterize Time frame rate, frames per second. */+export const MAX_POSTERIZE_FPS = 120;++/** Tolerance that keeps `0.3 * 10` style float products from falling one frame short. */+const FRAME_EPSILON = 1e-6;+/** Tolerance of the clip boundary test of echo frames, seconds. */+const BOUNDARY_EPSILON = 1e-9;++const num = (+ key: string,+ label: string,+ min: number,+ max: number,+ step: number,+ def: number,+ neutral: number,+ unit?: string,+): ProEffectParamSpec => ({+ key,+ label,+ kind: "number",+ min,+ max,+ step,+ unit,+ default: def,+ neutral,+ keyframable: true,+});++const TIME_CATEGORY: ProEffectCategory = "Time";++export const TEMPORAL_PRO_EFFECT_SPECS: Readonly<+ Record<TemporalEffectType, ProEffectSpec>+> = {+ echo: {+ type: "echo",+ label: "Echo",+ description: "Combine frames from other moments of the clip into trails",+ category: TIME_CATEGORY,+ params: [+ num("echoTime", "Echo time", -MAX_ECHO_TIME, MAX_ECHO_TIME, 0.001, 0.033, 0, "s"),+ num("echoes", "Number of echoes", 0, MAX_ECHOES, 1, 2, 0),+ num("startIntensity", "Starting intensity", 0, 1, 0.01, 1, 1),+ num("decay", "Decay", 0, 1, 0.01, 0.5, 0.5),+ {+ key: "operator",+ label: "Echo operator",+ kind: "select",+ default: "add",+ neutral: "add",+ options: [+ { value: "add", label: "Add" },+ { value: "maximum", label: "Maximum" },+ { value: "minimum", label: "Minimum" },+ { value: "screen", label: "Screen" },+ { value: "composite-back", label: "Composite in Back" },+ { value: "composite-front", label: "Composite in Front" },+ ],+ },+ ],+ },+ "posterize-time": {+ type: "posterize-time",+ label: "Posterize Time",+ description: "Hold frames to play the clip at a lower, steady frame rate",+ category: TIME_CATEGORY,+ params: [+ // 0 is "off": the clip keeps its own frame rate, which makes the neutral value an exact no-op.+ num("frameRate", "Frame rate", 0, MAX_POSTERIZE_FPS, 1, 1, 0, "fps"),+ ],+ },+};++/* -------------------------------------------------------------------------- */+/* Parameter reading */+/* -------------------------------------------------------------------------- */++const finite = (raw: unknown, fallback: number): number =>+ typeof raw === "number" && Number.isFinite(raw) ? raw : fallback;++const clamp = (value: number, lo: number, hi: number): number =>+ value < lo ? lo : value > hi ? hi : value;++export interface ResolvedEcho {+ /** Seconds between echoes; positive reaches back in time (sample = t - k * echoTime). */+ readonly echoTime: number;+ /** Whole number of echoes behind the current frame, 0..MAX_ECHOES. */+ readonly echoes: number;+ readonly startIntensity: number;+ readonly decay: number;+ readonly operator: EchoOperator;+}++/** Reads stored (possibly keyframe-interpolated, possibly partial) params into valid Echo values. */+export function resolveEcho(params: Readonly<Record<string, unknown>>): ResolvedEcho {+ const operator = params.operator;+ return {+ echoTime: clamp(finite(params.echoTime, 0), -MAX_ECHO_TIME, MAX_ECHO_TIME),+ // Keyframes interpolate between integers, so the count rounds rather than truncates.+ echoes: Math.round(clamp(finite(params.echoes, 0), 0, MAX_ECHOES)),+ startIntensity: clamp(finite(params.startIntensity, 1), 0, 1),+ decay: clamp(finite(params.decay, 0.5), 0, 1),+ operator: (ECHO_OPERATORS as readonly unknown[]).includes(operator)+ ? (operator as EchoOperator)+ : "add",+ };+}++/** Posterize Time frame rate in fps; 0 when off. */+export function resolvePosterizeRate(params: Readonly<Record<string, unknown>>): number {+ return clamp(finite(params.frameRate, 0), 0, MAX_POSTERIZE_FPS);+}++/** True when the effect leaves the picture and the frame selection unchanged. */+export function isTemporalNeutral(+ type: TemporalEffectType,+ params: Readonly<Record<string, unknown>>,+): boolean {+ if (type === "echo") return resolveEcho(params).echoes === 0;+ return resolvePosterizeRate(params) <= 0;+}++/* -------------------------------------------------------------------------- */+/* Posterize Time */+/* -------------------------------------------------------------------------- */++/** Index of the posterized frame that clip-local time `t` falls into. */+export function posterizeFrameIndex(t: number, fps: number): number {+ return Math.floor(t * fps + FRAME_EPSILON);+}++/**+ * Clip-local time of the posterized frame containing `t`: the start of the+ * 1/fps interval. A rate of 0 (or less) or a non-finite time returns `t`.+ */+export function posterizeTime(t: number, fps: number): number {+ if (!Number.isFinite(t) || !Number.isFinite(fps) || fps <= 0) return t;+ return posterizeFrameIndex(t, fps) / fps;+}++/** Minimal shape of an effect the clip-level helpers read. */+export interface TemporalEffectLike {+ readonly type: string;+ readonly enabled?: boolean;+ readonly params?: Readonly<Record<string, unknown>>;+}++/**+ * Clip-local time the clip's frame is taken from once an enabled Posterize+ * Time effect is applied (the first one wins). `effects` must already be+ * sampled at `localTime`, so a keyframed frame rate is the rate at this frame.+ */+export function posterizedClipTime(+ effects: readonly TemporalEffectLike[],+ localTime: number,+): number {+ for (const effect of effects) {+ if (effect.type !== "posterize-time" || effect.enabled === false) continue;+ const fps = resolvePosterizeRate(effect.params ?? {});+ if (fps > 0) return posterizeTime(localTime, fps);+ }+ return localTime;+}++/** The first enabled, non-neutral Echo among `effects`, with its position in the list. */+export function findActiveEcho(+ effects: readonly TemporalEffectLike[],+): { readonly index: number; readonly echo: ResolvedEcho } | null {+ for (let index = 0; index < effects.length; index++) {+ const effect = effects[index];+ if (effect.type !== "echo" || effect.enabled === false) continue;+ const echo = resolveEcho(effect.params ?? {});+ if (echo.echoes > 0) return { index, echo };+ }+ return null;+}++/**+ * Does this clip pick frames other than its own at its playhead position? True for an enabled, non-neutral Echo or+ * Posterize Time, or for keyframes of their parameters (which can switch one on). The preview routes such clips+ * through the canonical engine renderer (the one export uses) and the engine skips the frame-time resolution+ * for every other clip, so the check is cheap and conservative.+ */+export function clipHasTemporalEffects(clip: {+ readonly effects?: readonly TemporalEffectLike[];+ readonly keyframes?: readonly { readonly property: string }[];+}): boolean {+ const active = clip.effects?.some(+ (e) =>+ isTemporalEffectType(e.type) &&+ e.enabled !== false &&+ !isTemporalNeutral(e.type, e.params ?? {}),+ );+ if (active) return true;+ return (+ clip.keyframes?.some(+ (k) =>+ k.property.startsWith("effect.echo.") ||+ k.property.startsWith("effect.posterize-time."),+ ) ?? false+ );+}++/* -------------------------------------------------------------------------- */+/* Echo */+/* -------------------------------------------------------------------------- */++/** Clip-local time of echo `k` (1-based) for a frame at `t`. */+export function echoSampleTime(t: number, k: number, echoTime: number): number {+ return t - k * echoTime;+}++/** Intensity of echo `k`: starting intensity times decay^k (k = 0 is the current frame). */+export function echoIntensity(k: number, startIntensity: number, decay: number): number {+ return startIntensity * Math.pow(decay, k);+}++export interface EchoSample {+ /** 1-based echo number. */+ readonly k: number;+ /** Clip-local time of the frame the echo shows, seconds. */+ readonly localTime: number;+ /** Opacity / mix weight of the echo, 0..1. */+ readonly weight: number;+}++/**+ * The echoes to draw for a frame at clip-local time `localTime` of a clip that+ * lasts `clipDuration` seconds, in the order the operator composites them.+ * Echoes that would reach before the clip's first frame or past its end show+ * nothing (there is no footage there) and are dropped, as are echoes whose+ * intensity is zero.+ */+export function planEcho(+ localTime: number,+ clipDuration: number,+ echo: ResolvedEcho,+): EchoSample[] {+ const samples: EchoSample[] = [];+ for (let k = 1; k <= echo.echoes; k++) {+ const t = echoSampleTime(localTime, k, echo.echoTime);+ if (t < -BOUNDARY_EPSILON || t > clipDuration - BOUNDARY_EPSILON) continue;+ const weight = echoIntensity(k, echo.startIntensity, echo.decay);+ if (weight <= 0) continue;+ samples.push({ k, localTime: Math.max(0, t), weight });+ }+ return echoCompositeOrder(samples, echo.operator);+}++/**+ * Composite in Front stacks the farthest echo first so the nearest ends on+ * top; every other operator walks outwards from the current frame.+ */+export function echoCompositeOrder<T extends { readonly k: number }>(+ samples: readonly T[],+ operator: EchoOperator,+): T[] {+ const ordered = [...samples].sort((a, b) => a.k - b.k);+ return operator === "composite-front" ? ordered.reverse() : ordered;+}++/** Operators that scale the current frame by the starting intensity (the composites keep it opaque). */+export function echoDimsBase(operator: EchoOperator): boolean {+ return operator !== "composite-back" && operator !== "composite-front";+}++export interface EchoPixels {+ /** Straight-alpha RGBA, 0..255. */+ readonly data: Uint8ClampedArray | Uint8Array;+ readonly weight: number;+}++/**+ * Reference implementation of the six echo operators on straight-alpha RGBA+ * buffers of equal size. `samples` must be in compositing order (planEcho).+ *+ * add Porter-Duff plus, clamped: base*start + sum(w_k * echo_k)+ * maximum lighten blend of each echo over the result at opacity w_k+ * minimum darken blend, same compositing+ * screen screen blend, same compositing+ * composite-back echo_k placed behind the result at opacity w_k+ * composite-front echo_k placed over the result at opacity w_k+ *+ * Blend modes follow the W3C compositing model with separable blend functions+ * and source alpha = weight * echo alpha; this is also exactly what the+ * Canvas2D composite operations draw.+ */+export function compositeEchoReference(+ base: Uint8ClampedArray | Uint8Array,+ samples: readonly EchoPixels[],+ echo: Pick<ResolvedEcho, "operator" | "startIntensity">,+): Uint8ClampedArray {+ const out = new Uint8ClampedArray(base.length);+ const dim = echoDimsBase(echo.operator) ? echo.startIntensity : 1;+ const op = echo.operator;+ for (let i = 0; i < base.length; i += 4) {+ let cr = (base[i] / 255) * dim;+ let cg = (base[i + 1] / 255) * dim;+ let cb = (base[i + 2] / 255) * dim;+ let ca = base[i + 3] / 255;+ for (const sample of samples) {+ const sr = sample.data[i] / 255;+ const sg = sample.data[i + 1] / 255;+ const sb = sample.data[i + 2] / 255;+ const as = (sample.data[i + 3] / 255) * sample.weight;+ let nr: number;+ let ng: number;+ let nb: number;+ let na: number;+ if (op === "add") {+ // Premultiplied sum, clamped.+ na = Math.min(1, ca + as);+ const pr = Math.min(1, cr * ca + sr * as);+ const pg = Math.min(1, cg * ca + sg * as);+ const pb = Math.min(1, cb * ca + sb * as);+ nr = na > 0 ? pr / na : 0;+ ng = na > 0 ? pg / na : 0;+ nb = na > 0 ? pb / na : 0;+ } else if (op === "composite-back") {+ na = ca + as * (1 - ca);+ nr = na > 0 ? (ca * cr + (1 - ca) * as * sr) / na : 0;+ ng = na > 0 ? (ca * cg + (1 - ca) * as * sg) / na : 0;+ nb = na > 0 ? (ca * cb + (1 - ca) * as * sb) / na : 0;+ } else if (op === "composite-front") {+ na = as + ca * (1 - as);+ nr = na > 0 ? (as * sr + (1 - as) * ca * cr) / na : 0;+ ng = na > 0 ? (as * sg + (1 - as) * ca * cg) / na : 0;+ nb = na > 0 ? (as * sb + (1 - as) * ca * cb) / na : 0;+ } else {+ na = as + ca * (1 - as);+ const blend = (b: number, s: number): number =>+ op === "maximum"+ ? Math.max(b, s)+ : op === "minimum"+ ? Math.min(b, s)+ : b + s - b * s;+ const mix = (b: number, s: number): number =>+ na > 0+ ? (as * (1 - ca) * s + as * ca * blend(b, s) + (1 - as) * ca * b) / na+ : 0;+ nr = mix(cr, sr);+ ng = mix(cg, sg);+ nb = mix(cb, sb);+ }+ cr = nr;+ cg = ng;+ cb = nb;+ ca = na;+ }+ out[i] = Math.round(cr * 255);+ out[i + 1] = Math.round(cg * 255);+ out[i + 2] = Math.round(cb * 255);+ out[i + 3] = Math.round(ca * 255);+ }+ return out;+}diff --git a/packages/core/src/video/ultra-key-shader.ts b/packages/core/src/video/ultra-key-shader.tsnew file mode 100644index 00000000..51e81850--- /dev/null+++ b/packages/core/src/video/ultra-key-shader.ts@@ -0,0 +1,121 @@+/**+ * GLSL ES 3.00 port of the Ultra Key math in ultra-key.ts. Matte cleanup+ * (choke then soften) recomputes the raw matte at each neighbour tap, so the+ * result is the same nested minimum / mean the CPU reference computes over+ * its matte planes. Input is straight alpha, output is premultiplied by emit().+ */+import { PRELUDE } from "./pro-effect-prelude";++export const ULTRA_KEY_GLSL = `${PRELUDE}+uniform float u_kCb;+uniform float u_kCr;+uniform float u_kLuma;+uniform float u_core;+uniform float u_band;+uniform float u_hasKey;+uniform float u_highlight;+uniform float u_shadow;+uniform float u_pedestal;+uniform float u_chokeRadius;+uniform float u_softenRadius;+uniform float u_contrastGain;+uniform float u_midPoint;+uniform float u_uCb;+uniform float u_uCr;+uniform float u_spill;+uniform float u_desaturate;+uniform float u_cosIn;+uniform float u_cosOut;+uniform float u_rangeOn;+uniform float u_lumaRestore;+uniform float u_satGain;+uniform float u_hueCos;+uniform float u_hueSin;+uniform float u_lumGain;+uniform float u_colorActive;+uniform float u_output;++const float KB = 0.564;+const float KR = 0.713;+const float GOLDEN = 2.399963229728653;++float baseMatte(vec3 c) {+ if (u_hasKey < 0.5) return 1.0;+ float y = dot(c, vec3(0.299, 0.587, 0.114));+ float ys = max(y, 0.15);+ float d = length(vec2(((c.b - y) * KB) / ys - u_kCb, ((c.r - y) * KR) / ys - u_kCr));+ float keyed = u_band > 0.0 ? clamp(1.0 - (d - u_core) / u_band, 0.0, 1.0) : (d <= u_core ? 1.0 : 0.0);+ float ratio = y / u_kLuma;+ keyed *= (1.0 - u_highlight * smoothstep(1.15, 1.75, ratio)) * (1.0 - u_shadow * (1.0 - smoothstep(0.1, 0.6, ratio)));+ return clamp((1.0 - keyed - u_pedestal) / (1.0 - u_pedestal), 0.0, 1.0);+}+float matteAt(vec2 p) { return baseMatte(fetchPx(p).rgb); }+float kernelCount(float radius, float mx) { return min(mx, max(6.0, ceil(radius * 2.0) + 4.0)); }+vec2 offs(float i, float n, float radius) {+ float rho = radius * sqrt((i + 0.5) / n);+ float th = i * GOLDEN;+ return floor(vec2(rho * cos(th), rho * sin(th)) + 0.5);+}+// Choke: minimum of the matte over the disc.+float choked(vec2 p) {+ float acc = matteAt(p);+ float r = u_chokeRadius * u_resolution.y / 1080.0;+ if (r <= 0.0) return acc;+ float n = kernelCount(r, 12.0);+ for (int i = 0; i < 12; i++) {+ if (float(i) >= n) break;+ acc = min(acc, matteAt(p + offs(float(i), n, r)));+ }+ return acc;+}+void main() {+ vec2 p = pxPos();+ vec4 s = fetchPx(p);+ if (u_output > 2.5) { fragColor = emit(s.rgb, s.a); return; }+ float a = choked(p);+ float sr = u_softenRadius * u_resolution.y / 1080.0;+ if (sr > 0.0) {+ float n = kernelCount(sr, 16.0);+ float acc = a;+ for (int i = 0; i < 16; i++) {+ if (float(i) >= n) break;+ acc += choked(clamp(p + offs(float(i), n, sr), vec2(0.0), u_resolution - 1.0));+ }+ a = acc / (n + 1.0);+ }+ if (u_contrastGain != 1.0) a = clamp((a - u_midPoint) * u_contrastGain + u_midPoint, 0.0, 1.0);+ if (u_output > 0.5 && u_output < 1.5) { fragColor = vec4(vec3(clamp(a * s.a, 0.0, 1.0)), 1.0); return; }+ vec3 rgb = s.rgb;+ if (u_colorActive > 0.5) {+ float y = dot(rgb, vec3(0.299, 0.587, 0.114));+ float cb = (rgb.b - y) * KB;+ float cr = (rgb.r - y) * KR;+ if (u_rangeOn > 0.5) {+ float mag = length(vec2(cb, cr));+ float proj = cb * u_uCb + cr * u_uCr;+ if (mag > 1e-5 && proj > 0.0) {+ float w = clamp((proj / mag - u_cosOut) / (u_cosIn - u_cosOut + 1e-6), 0.0, 1.0);+ float hw = w * w * (3.0 - 2.0 * w);+ float rem = proj * u_spill * hw;+ cb -= u_uCb * rem;+ cr -= u_uCr * rem;+ float f = 1.0 - u_desaturate * hw * (1.0 - a);+ cb *= f;+ cr *= f;+ y += u_lumaRestore * rem;+ }+ }+ float rotCb = cb * u_hueCos - cr * u_hueSin;+ float rotCr = cb * u_hueSin + cr * u_hueCos;+ cb = rotCb * u_satGain;+ cr = rotCr * u_satGain;+ y *= u_lumGain;+ float nr = y + cr / KR;+ float nb = y + cb / KB;+ float ng = (y - 0.299 * nr - 0.114 * nb) / 0.587;+ rgb = clamp(vec3(nr, ng, nb), 0.0, 1.0);+ }+ float alpha = u_output < 0.5 ? s.a * a : s.a;+ fragColor = emit(rgb, alpha);+}+`;diff --git a/packages/core/src/video/ultra-key.test.ts b/packages/core/src/video/ultra-key.test.tsnew file mode 100644index 00000000..cfc4ddd4--- /dev/null+++ b/packages/core/src/video/ultra-key.test.ts@@ -0,0 +1,257 @@+import { describe, expect, it } from "vitest";+import {+ applyUltraKey,+ isUltraKeyNeutral,+ prepareUltraKey,+ ultraKeyBaseMatte,+ ultraKeyColorFromSample,+ ultraKeyContrast,+ ultraKeyForeground,+ ultraKeyGpuUniforms,+ ULTRA_KEY_UNIFORM_NAMES,+ type UltraKeyParams,+} from "./ultra-key";+import { applyProEffect, isProEffectNeutral, PRO_EFFECT_DEFAULTS } from "./pro-effects";+import { ULTRA_KEY_GLSL } from "./ultra-key-shader";++const NEUTRAL: UltraKeyParams = {+ keyR: 0, keyG: 255, keyB: 0, transparency: 0, highlight: 0, shadow: 0, tolerance: 0,+ pedestal: 0, choke: 0, soften: 0, contrast: 0, midPoint: 50, desaturate: 0, range: 0,+ spill: 0, luma: 0, saturation: 100, hue: 0, luminance: 100, output: "composite",+};+const P = (over: Partial<UltraKeyParams> = {}): UltraKeyParams => ({ ...PRO_EFFECT_DEFAULTS["ultra-key"] as unknown as UltraKeyParams, ...over });+const prep = (over: Partial<UltraKeyParams> = {}) => prepareUltraKey(P(over), 1080);+const GREEN = [0, 255, 0] as const;+const SKIN = [224, 172, 140] as const;++function image(w: number, h: number, fill: (x: number, y: number) => readonly number[]): Uint8ClampedArray {+ const d = new Uint8ClampedArray(w * h * 4);+ for (let y = 0; y < h; y++) for (let x = 0; x < w; x++) d.set([...fill(x, y).slice(0, 3), fill(x, y)[3] ?? 255], (y * w + x) * 4);+ return d;+}++describe("ultra key matte generation", () => {+ it("makes the key colour fully transparent and leaves skin and blue opaque", () => {+ const u = prep();+ expect(ultraKeyBaseMatte(...GREEN, u)).toBe(0);+ expect(ultraKeyBaseMatte(...SKIN, u)).toBe(1);+ expect(ultraKeyBaseMatte(40, 60, 220, u)).toBe(1);+ });++ it("keys a darker or lighter shade of the same screen (chroma, not RGB distance)", () => {+ const u = prep({ shadow: 0, highlight: 0 });+ expect(ultraKeyBaseMatte(0, 140, 0, u)).toBe(0);+ expect(ultraKeyBaseMatte(70, 200, 70, u)).toBeLessThan(0.5);+ });++ it("tolerance and transparency are monotonic: more of either keys more", () => {+ const px: [number, number, number] = [90, 170, 90];+ const base = ultraKeyBaseMatte(...px, prep({ tolerance: 40, transparency: 40 }));+ const hiTol = ultraKeyBaseMatte(...px, prep({ tolerance: 60, transparency: 40 }));+ const hiTrans = ultraKeyBaseMatte(...px, prep({ tolerance: 40, transparency: 80 }));+ expect(base).toBe(1);+ expect(hiTol).toBeLessThan(base);+ expect(hiTrans).toBeLessThan(base);+ });++ it("a hard matte (transparency 0) is binary", () => {+ const u = prep({ transparency: 0, tolerance: 30, highlight: 0, shadow: 0 });+ for (let g = 0; g <= 255; g += 15) {+ const a = ultraKeyBaseMatte(0, g, 0, u);+ expect([0, 1]).toContain(a);+ }+ });++ it("highlight and shadow protect pixels much brighter and darker than the screen", () => {+ const bright: [number, number, number] = [150, 255, 150];+ const dark: [number, number, number] = [0, 60, 0];+ const wide = { tolerance: 100, transparency: 100 };+ expect(ultraKeyBaseMatte(...bright, prep({ ...wide, highlight: 0 }))).toBe(0);+ expect(ultraKeyBaseMatte(...bright, prep({ ...wide, highlight: 100 }))).toBeGreaterThan(0.4);+ expect(ultraKeyBaseMatte(...dark, prep({ shadow: 0 }))).toBe(0);+ expect(ultraKeyBaseMatte(...dark, prep({ shadow: 100 }))).toBeGreaterThan(0.5);+ });++ it("pedestal clips low opacity to transparent and keeps full opacity", () => {+ const px: [number, number, number] = [90, 170, 90];+ const u0 = prep({ pedestal: 0, tolerance: 70, transparency: 50 });+ const u1 = prep({ pedestal: 60, tolerance: 70, transparency: 50 });+ const a0 = ultraKeyBaseMatte(...px, u0);+ expect(a0).toBeGreaterThan(0.2);+ expect(a0).toBeLessThan(0.8);+ expect(ultraKeyBaseMatte(...px, u1)).toBe(0);+ expect(ultraKeyBaseMatte(...SKIN, u1)).toBe(1);+ });++ it("with no tolerance and no transparency nothing is keyed", () => {+ expect(ultraKeyBaseMatte(...GREEN, prep({ tolerance: 0, transparency: 0 }))).toBe(1);+ });++ it("a different key colour (blue screen) keys blue, not green", () => {+ const u = prep({ keyR: 0, keyG: 0, keyB: 255 });+ expect(ultraKeyBaseMatte(0, 0, 255, u)).toBe(0);+ expect(ultraKeyBaseMatte(0, 255, 0, u)).toBe(1);+ });+});++describe("ultra key matte contrast", () => {+ it("is identity at zero contrast and steepens around the mid point", () => {+ expect(ultraKeyContrast(0.3, prep({ contrast: 0 }))).toBe(0.3);+ const u = prep({ contrast: 100, midPoint: 50 });+ expect(ultraKeyContrast(0.5, u)).toBeCloseTo(0.5, 6);+ expect(ultraKeyContrast(0.45, u)).toBeLessThan(0.3);+ expect(ultraKeyContrast(0.55, u)).toBeGreaterThan(0.7);+ const low = prep({ contrast: 100, midPoint: 20 });+ expect(ultraKeyContrast(0.3, low)).toBeGreaterThan(0.9);+ });+});++describe("ultra key spill suppression and colour correction", () => {+ const spillPx: [number, number, number] = [200, 235, 190];+ const fg = (u: ReturnType<typeof prep>, c: readonly number[], a = 1) => {+ const out: [number, number, number] = [0, 0, 0];+ ultraKeyForeground(c[0] / 255, c[1] / 255, c[2] / 255, a, u, out);+ return out.map((v) => v * 255);+ };++ it("removes green from a spill-tinted pixel and leaves skin alone", () => {+ const u = prep({ spill: 100, range: 80 });+ const [r, g, b] = fg(u, spillPx);+ expect(g - Math.max(r, b)).toBeLessThan(spillPx[1] - Math.max(spillPx[0], spillPx[2]));+ const skin = fg(u, SKIN);+ for (let i = 0; i < 3; i++) expect(Math.abs(skin[i] - SKIN[i])).toBeLessThan(6);+ });++ it("spill 0 and desaturate 0 leave the colour exactly alone", () => {+ const u = prep({ spill: 0, desaturate: 0 });+ expect(fg(u, spillPx).map(Math.round)).toEqual([...spillPx]);+ });++ it("range limits which hues are corrected", () => {+ const wide = fg(prep({ spill: 100, range: 100 }), [150, 200, 120]);+ const none = fg(prep({ spill: 100, range: 0 }), [150, 200, 120]);+ expect(wide[1]).toBeLessThan(none[1]);+ });++ it("desaturate only acts on soft matte edges", () => {+ const u = prep({ spill: 0, desaturate: 100, range: 100 });+ const edge = fg(u, [150, 200, 120], 0.2);+ const solid = fg(u, [150, 200, 120], 1);+ const spread = (c: number[]) => Math.max(...c) - Math.min(...c);+ expect(spread(edge)).toBeLessThan(spread(solid));+ });++ it("luma restores brightness removed with the spill", () => {+ const dim = fg(prep({ spill: 100, range: 80, luma: 0 }), spillPx);+ const lit = fg(prep({ spill: 100, range: 80, luma: 100 }), spillPx);+ expect(lit[0] + lit[1] + lit[2]).toBeGreaterThan(dim[0] + dim[1] + dim[2]);+ });++ it("colour correction: saturation 0 is grey, hue rotates, luminance scales", () => {+ const grey = fg(prep({ spill: 0, desaturate: 0, saturation: 0 }), [200, 100, 50]);+ expect(Math.max(...grey) - Math.min(...grey)).toBeLessThan(1);+ const rotated = fg(prep({ spill: 0, desaturate: 0, hue: 120 }), [255, 0, 0]);+ expect(rotated[1]).toBeGreaterThan(rotated[0]);+ const dark = fg(prep({ spill: 0, desaturate: 0, luminance: 50 }), [200, 200, 200]);+ expect(dark[0]).toBeCloseTo(100, 0);+ });+});++describe("ultra key CPU render", () => {+ const W = 24;+ const H = 16;+ const split = image(W, H, (x) => (x < 12 ? [...GREEN] : [...SKIN]));++ it("composites: screen transparent, subject opaque and untouched colour-wise", () => {+ const d = new Uint8ClampedArray(split);+ applyUltraKey(d, W, H, P({ spill: 0, desaturate: 0 }));+ expect(d[3]).toBe(0);+ expect(Array.from(d.slice((8 * W + 20) * 4, (8 * W + 20) * 4 + 4))).toEqual([224, 172, 140, 255]);+ });++ it("alpha output is the matte as opaque grey and ignores source alpha shape", () => {+ const d = new Uint8ClampedArray(split);+ applyUltraKey(d, W, H, P({ output: "alpha" }));+ expect(Array.from(d.slice(0, 4))).toEqual([0, 0, 0, 255]);+ expect(Array.from(d.slice(20 * 4, 20 * 4 + 4))).toEqual([255, 255, 255, 255]);+ });++ it("colour channel output keeps full alpha and the corrected foreground", () => {+ const d = new Uint8ClampedArray(split);+ applyUltraKey(d, W, H, P({ output: "color", spill: 0, desaturate: 0 }));+ expect(Array.from(d.slice(0, 4))).toEqual([0, 255, 0, 255]);+ });++ it("source output is a pass through for the key colour picker", () => {+ const d = new Uint8ClampedArray(split);+ applyUltraKey(d, W, H, P({ output: "source" }));+ expect(Array.from(d)).toEqual(Array.from(split));+ });++ it("choke pulls the matte edge into the subject; soften feathers it", () => {+ const edgeCol = (data: Uint8ClampedArray, y = 8) => {+ const row: number[] = [];+ for (let x = 0; x < W; x++) row.push(data[(y * W + x) * 4 + 3]);+ return row;+ };+ const base = new Uint8ClampedArray(split);+ applyUltraKey(base, 24, 16, P({ spill: 0, desaturate: 0 }));+ const baseOpaque = edgeCol(base).filter((a) => a === 255).length;+ const bigSplit = image(120, 90, (x) => (x < 60 ? [...GREEN] : [...SKIN]));+ const bigBase = new Uint8ClampedArray(bigSplit);+ applyUltraKey(bigBase, 120, 90, P({ spill: 0, desaturate: 0 }));+ const choked = new Uint8ClampedArray(bigSplit);+ applyUltraKey(choked, 120, 90, P({ spill: 0, desaturate: 0, choke: 100 }));+ const row = (d: Uint8ClampedArray, w: number) => Array.from({ length: w }, (_, x) => d[(45 * w + x) * 4 + 3]);+ expect(row(choked, 120).filter((a) => a === 255).length).toBeLessThan(row(bigBase, 120).filter((a) => a === 255).length);+ const soft = new Uint8ClampedArray(bigSplit);+ applyUltraKey(soft, 120, 90, P({ spill: 0, desaturate: 0, soften: 100 }));+ const partial = row(soft, 120).filter((a) => a > 0 && a < 255).length;+ expect(partial).toBeGreaterThan(0);+ expect(row(bigBase, 120).filter((a) => a > 0 && a < 255).length).toBe(0);+ expect(baseOpaque).toBeGreaterThan(0);+ });++ it("multiplies existing alpha", () => {+ const d = image(W, H, () => [...SKIN, 128]);+ applyUltraKey(d, W, H, P());+ expect(d[3]).toBe(128);+ });++ it("neutral params are an exact no-op, defaults are not", () => {+ const d = new Uint8ClampedArray(split);+ applyProEffect("ultra-key", NEUTRAL as unknown as Record<string, unknown>, d, W, H);+ expect(Array.from(d)).toEqual(Array.from(split));+ expect(isUltraKeyNeutral(NEUTRAL)).toBe(true);+ expect(isProEffectNeutral("ultra-key", P() as unknown as Record<string, unknown>)).toBe(false);+ expect(isProEffectNeutral("ultra-key", {})).toBe(true);+ expect(isProEffectNeutral("ultra-key", NEUTRAL as unknown as Record<string, unknown>)).toBe(true);+ });++ it("is reachable through the shared pro effect dispatcher", () => {+ const d = new Uint8ClampedArray(split);+ expect(applyProEffect("ultra-key", P() as unknown as Record<string, unknown>, d, W, H)).toBe(true);+ expect(d[3]).toBe(0);+ });+});++describe("ultra key GPU contract", () => {+ it("the shader declares every uniform the mapping provides", () => {+ for (const name of ULTRA_KEY_UNIFORM_NAMES) expect(ULTRA_KEY_GLSL, name).toContain(`uniform float u_${name};`);+ expect(Object.keys(ultraKeyGpuUniforms(NEUTRAL))).toEqual(ULTRA_KEY_UNIFORM_NAMES);+ });++ it("uniforms carry the derived matte constants", () => {+ const u = ultraKeyGpuUniforms(P({ tolerance: 100, transparency: 100, choke: 50, output: "alpha" }));+ expect(u.core).toBeCloseTo(0.7, 6);+ expect(u.band).toBeCloseTo(0.45, 6);+ expect(u.chokeRadius).toBeCloseTo(5, 6);+ expect(u.output).toBe(1);+ });+});++describe("ultra key eyedropper", () => {+ it("turns a sampled colour into the key parameters", () => {+ expect(ultraKeyColorFromSample({ r: 12.4, g: 200.6, b: 300 })).toEqual({ keyR: 12, keyG: 201, keyB: 255 });+ });+});diff --git a/packages/core/src/video/ultra-key.ts b/packages/core/src/video/ultra-key.tsnew file mode 100644index 00000000..e204f355--- /dev/null+++ b/packages/core/src/video/ultra-key.ts@@ -0,0 +1,382 @@+/**+ * Ultra Key: a Premiere-style chroma keyer. This file is the single source of+ * truth for the key math. The CPU reference (applyUltraKey, used by the Canvas2D+ * fallback renderer and export) and the GLSL port in ultra-key-shader.ts are+ * written line for line against it.+ *+ * Pipeline, per pixel (straight-alpha RGBA, origin top-left):+ *+ * 1. Matte generation. Pixel and key colour are converted to BT.601 YCbCr.+ * Chroma is divided by luma (floored at 0.15) so a shaded part of the+ * screen keys like a lit one. The chroma distance d to the key decides+ * how keyed the pixel is:+ * core = tolerance / 100 * 0.7 (fully keyed inside this radius)+ * width = transparency / 100 * 0.45 (soft falloff outside the core)+ * keyed = 1 - clamp((d - core) / width)+ * Highlight and Shadow then protect pixels much brighter / darker than the+ * key (whose chroma is unreliable) by pulling the key back towards opaque, and Pedestal clips+ * the lowest opacities to fully transparent (grey noise in the screen).+ * 2. Matte cleanup. Choke erodes the matte (minimum over a disc), Soften+ * blurs it (average over a disc), Contrast steepens it around Mid Point.+ * Both radii are in 1080p pixels and scale with the frame height.+ * 3. Spill suppression on the foreground. Chroma that points towards the key+ * hue (within Range) has its key-direction component removed by Spill,+ * soft edge pixels are Desaturated and Luma gives back brightness.+ * 4. Colour correction (Saturation, Hue, Luminance) of the foreground.+ * 5. Output: composite (colour + matte), alpha channel (matte as grey) or+ * colour channel (the corrected foreground, matte ignored).+ */++export const ULTRA_KEY_OUTPUTS = ["composite", "alpha", "color", "source"] as const;+export type UltraKeyOutput = (typeof ULTRA_KEY_OUTPUTS)[number];++export interface UltraKeyParams {+ keyR: number;+ keyG: number;+ keyB: number;+ transparency: number;+ highlight: number;+ shadow: number;+ tolerance: number;+ pedestal: number;+ choke: number;+ soften: number;+ contrast: number;+ midPoint: number;+ desaturate: number;+ range: number;+ spill: number;+ luma: number;+ saturation: number;+ hue: number;+ luminance: number;+ output: UltraKeyOutput | string;+}++/** BT.601 chroma scale factors (Cb, Cr in -0.5..0.5 for RGB in 0..1). */+const KB = 0.564;+const KR = 0.713;+const CORE_MAX = 0.7;+const BAND_MAX = 0.45;+/** Luma floor of the chroma normalisation, so near-black pixels do not blow up. */+const Y_FLOOR = 0.15;+/** Luma given back per unit of removed spill chroma at Luma = 100. */+const LUMA_RESTORE = 0.35;+const GOLDEN_ANGLE = 2.399963229728653;++/** Everything derived from the parameters once per frame (shared with the GPU uniforms). */+export interface UltraKeyPrep {+ kCb: number;+ kCr: number;+ /** Key luma (floored); highlight and shadow are relative to it. */+ kLuma: number;+ core: number;+ band: number;+ hasKey: boolean;+ highlight: number;+ shadow: number;+ pedestal: number;+ chokeRadius: number;+ chokeCount: number;+ softenRadius: number;+ softenCount: number;+ contrastGain: number;+ midPoint: number;+ /** Unit key chroma direction, or 0,0 for a grey key. */+ uCb: number;+ uCr: number;+ spill: number;+ desaturate: number;+ cosIn: number;+ cosOut: number;+ rangeOn: boolean;+ luma: number;+ satGain: number;+ hueCos: number;+ hueSin: number;+ lumGain: number;+ colorActive: boolean;+ output: 0 | 1 | 2 | 3;+}++const clamp = (v: number, lo: number, hi: number): number => (v < lo ? lo : v > hi ? hi : v);++function smoothstep(e0: number, e1: number, x: number): number {+ const t = clamp((x - e0) / (e1 - e0), 0, 1);+ return t * t * (3 - 2 * t);+}++/** Neighbourhood sample count for a cleanup disc of `radius` pixels. */+export function ultraKeyKernelCount(radius: number, max: number): number {+ return Math.min(max, Math.max(6, Math.ceil(radius * 2) + 4));+}++const OUTPUT_INDEX: Record<string, 0 | 1 | 2 | 3> = { composite: 0, alpha: 1, color: 2, source: 3 };++export function prepareUltraKey(p: UltraKeyParams, height: number): UltraKeyPrep {+ const kr = clamp(p.keyR, 0, 255) / 255;+ const kg = clamp(p.keyG, 0, 255) / 255;+ const kb = clamp(p.keyB, 0, 255) / 255;+ const ky = 0.299 * kr + 0.587 * kg + 0.114 * kb;+ const rawCb = (kb - ky) * KB;+ const rawCr = (kr - ky) * KR;+ const kMag = Math.hypot(rawCb, rawCr);+ const ks = Math.max(ky, Y_FLOOR);+ const kCb = rawCb / ks;+ const kCr = rawCr / ks;+ const core = (clamp(p.tolerance, 0, 100) / 100) * CORE_MAX;+ const band = (clamp(p.transparency, 0, 100) / 100) * BAND_MAX;+ const scale = Math.max(1, height) / 1080;+ const chokeRadius = (clamp(p.choke, 0, 100) / 100) * 10 * scale;+ const softenRadius = (clamp(p.soften, 0, 100) / 100) * 10 * scale;+ const range = clamp(p.range, 0, 100);+ const halfAngle = (range / 100) * (Math.PI / 2);+ const spill = clamp(p.spill, 0, 100) / 100;+ const desaturate = clamp(p.desaturate, 0, 100) / 100;+ const hueRad = (clamp(p.hue, -180, 180) * Math.PI) / 180;+ const satGain = clamp(p.saturation, 0, 200) / 100;+ const lumGain = clamp(p.luminance, 0, 200) / 100;+ const luma = clamp(p.luma, 0, 100) / 100;+ const spillActive = kMag > 1e-4 && range > 0 && (spill > 0 || desaturate > 0);+ const colorActive =+ spillActive || satGain !== 1 || hueRad !== 0 || lumGain !== 1;+ return {+ kCb,+ kCr,+ kLuma: ks,+ core,+ band,+ hasKey: core > 0 || band > 0,+ highlight: clamp(p.highlight, 0, 100) / 100,+ shadow: clamp(p.shadow, 0, 100) / 100,+ pedestal: Math.min(clamp(p.pedestal, 0, 100) / 100, 0.999),+ chokeRadius,+ chokeCount: ultraKeyKernelCount(chokeRadius, 12),+ softenRadius,+ softenCount: ultraKeyKernelCount(softenRadius, 16),+ contrastGain: 1 + (clamp(p.contrast, 0, 100) / 100) * 7,+ midPoint: clamp(p.midPoint, 0, 100) / 100,+ uCb: kMag > 1e-4 ? rawCb / kMag : 0,+ uCr: kMag > 1e-4 ? rawCr / kMag : 0,+ spill,+ desaturate,+ cosIn: Math.cos(halfAngle * 0.5),+ cosOut: Math.cos(halfAngle),+ rangeOn: spillActive,+ luma,+ satGain,+ hueCos: Math.cos(hueRad),+ hueSin: Math.sin(hueRad),+ lumGain,+ colorActive,+ output: OUTPUT_INDEX[String(p.output)] ?? 0,+ };+}++/** Opacity (1 keeps the pixel) of the raw matte at one pixel, before cleanup. Inputs are 0-255. */+export function ultraKeyBaseMatte(r255: number, g255: number, b255: number, u: UltraKeyPrep): number {+ if (!u.hasKey) return 1;+ const r = r255 / 255;+ const g = g255 / 255;+ const b = b255 / 255;+ const y = 0.299 * r + 0.587 * g + 0.114 * b;+ const s = Math.max(y, Y_FLOOR);+ const d = Math.hypot(((b - y) * KB) / s - u.kCb, ((r - y) * KR) / s - u.kCr);+ let keyed: number;+ if (u.band > 0) keyed = clamp(1 - (d - u.core) / u.band, 0, 1);+ else keyed = d <= u.core ? 1 : 0;+ const ratio = y / u.kLuma;+ keyed *= (1 - u.highlight * smoothstep(1.15, 1.75, ratio)) * (1 - u.shadow * (1 - smoothstep(0.1, 0.6, ratio)));+ const a = 1 - keyed;+ return clamp((a - u.pedestal) / (1 - u.pedestal), 0, 1);+}++/** Matte value after Contrast / Mid Point. */+export function ultraKeyContrast(a: number, u: UltraKeyPrep): number {+ if (u.contrastGain === 1) return a;+ return clamp((a - u.midPoint) * u.contrastGain + u.midPoint, 0, 1);+}++/** Integer pixel offsets of the golden-angle disc (index i of n samples). */+export function ultraKeyOffset(i: number, n: number, radius: number): [number, number] {+ const rho = radius * Math.sqrt((i + 0.5) / n);+ const th = i * GOLDEN_ANGLE;+ return [Math.floor(rho * Math.cos(th) + 0.5), Math.floor(rho * Math.sin(th) + 0.5)];+}++/**+ * Foreground colour after spill suppression and colour correction for a pixel+ * whose final matte value is `alpha`. Inputs and outputs are 0-1.+ */+export function ultraKeyForeground(+ r: number,+ g: number,+ b: number,+ alpha: number,+ u: UltraKeyPrep,+ out: [number, number, number],+): void {+ if (!u.colorActive) {+ out[0] = r;+ out[1] = g;+ out[2] = b;+ return;+ }+ let y = 0.299 * r + 0.587 * g + 0.114 * b;+ let cb = (b - y) * KB;+ let cr = (r - y) * KR;+ if (u.rangeOn) {+ const mag = Math.hypot(cb, cr);+ const proj = cb * u.uCb + cr * u.uCr;+ if (mag > 1e-5 && proj > 0) {+ const w = clamp((proj / mag - u.cosOut) / (u.cosIn - u.cosOut + 1e-6), 0, 1);+ const hw = w * w * (3 - 2 * w);+ const rem = proj * u.spill * hw;+ cb -= u.uCb * rem;+ cr -= u.uCr * rem;+ const f = 1 - u.desaturate * hw * (1 - alpha);+ cb *= f;+ cr *= f;+ y += u.luma * LUMA_RESTORE * rem;+ }+ }+ const rotCb = cb * u.hueCos - cr * u.hueSin;+ const rotCr = cb * u.hueSin + cr * u.hueCos;+ cb = rotCb * u.satGain;+ cr = rotCr * u.satGain;+ y *= u.lumGain;+ const nr = y + cr / KR;+ const nb = y + cb / KB;+ const ng = (y - 0.299 * nr - 0.114 * nb) / 0.587;+ out[0] = clamp(nr, 0, 1);+ out[1] = clamp(ng, 0, 1);+ out[2] = clamp(nb, 0, 1);+}++/** True when the parameters leave the picture unchanged. */+export function isUltraKeyNeutral(p: UltraKeyParams): boolean {+ const u = prepareUltraKey(p, 1080);+ return u.output === 0 && !u.hasKey && !u.colorActive;+}++/** CPU reference. Mutates straight-alpha RGBA bytes. */+export function applyUltraKey(+ data: Uint8ClampedArray,+ width: number,+ height: number,+ p: UltraKeyParams,+): void {+ const u = prepareUltraKey(p, height);+ if (u.output === 3) return;+ if (!u.hasKey && !u.colorActive && u.output === 0) return;+ const total = width * height;+ let matte: Float32Array = new Float32Array(total);+ for (let i = 0, o = 0; i < total; i++, o += 4) {+ matte[i] = ultraKeyBaseMatte(data[o], data[o + 1], data[o + 2], u);+ }+ if (u.hasKey && u.chokeRadius > 0) matte = disc(matte, width, height, u.chokeRadius, u.chokeCount, "min");+ if (u.hasKey && u.softenRadius > 0) matte = disc(matte, width, height, u.softenRadius, u.softenCount, "mean");+ const fg: [number, number, number] = [0, 0, 0];+ for (let i = 0, o = 0; i < total; i++, o += 4) {+ const a = ultraKeyContrast(matte[i], u);+ if (u.output === 1) {+ const v = Math.round(a * data[o + 3]);+ data[o] = data[o + 1] = data[o + 2] = v;+ data[o + 3] = 255;+ continue;+ }+ ultraKeyForeground(data[o] / 255, data[o + 1] / 255, data[o + 2] / 255, a, u, fg);+ if (u.colorActive) {+ data[o] = Math.round(fg[0] * 255);+ data[o + 1] = Math.round(fg[1] * 255);+ data[o + 2] = Math.round(fg[2] * 255);+ }+ if (u.output === 0 && a < 1) data[o + 3] = Math.round(data[o + 3] * a);+ }+}++function disc(+ src: Float32Array,+ width: number,+ height: number,+ radius: number,+ count: number,+ mode: "min" | "mean",+): Float32Array {+ const dst = new Float32Array(src.length);+ const offsets: [number, number][] = [];+ for (let i = 0; i < count; i++) offsets.push(ultraKeyOffset(i, count, radius));+ for (let y = 0; y < height; y++) {+ for (let x = 0; x < width; x++) {+ let acc = src[y * width + x];+ for (const [dx, dy] of offsets) {+ const sx = clamp(x + dx, 0, width - 1);+ const sy = clamp(y + dy, 0, height - 1);+ const v = src[sy * width + sx];+ if (mode === "min") {+ if (v < acc) acc = v;+ } else acc += v;+ }+ dst[y * width + x] = mode === "min" ? acc : acc / (count + 1);+ }+ }+ return dst;+}++/** Uniform values for the GLSL port (names without `u_`). Radii are 1080p pixels. */+export function ultraKeyGpuUniforms(p: UltraKeyParams): Record<string, number> {+ const u = prepareUltraKey(p, 1080);+ return {+ kCb: u.kCb,+ kCr: u.kCr,+ kLuma: u.kLuma,+ core: u.core,+ band: u.band,+ hasKey: u.hasKey ? 1 : 0,+ highlight: u.highlight,+ shadow: u.shadow,+ pedestal: u.pedestal,+ // Radii at 1080p; the shader scales them by its own frame height.+ chokeRadius: u.hasKey ? u.chokeRadius : 0,+ softenRadius: u.hasKey ? u.softenRadius : 0,+ contrastGain: u.contrastGain,+ midPoint: u.midPoint,+ uCb: u.uCb,+ uCr: u.uCr,+ spill: u.spill,+ desaturate: u.desaturate,+ cosIn: u.cosIn,+ cosOut: u.cosOut,+ rangeOn: u.rangeOn ? 1 : 0,+ lumaRestore: u.luma * LUMA_RESTORE,+ satGain: u.satGain,+ hueCos: u.hueCos,+ hueSin: u.hueSin,+ lumGain: u.lumGain,+ colorActive: u.colorActive ? 1 : 0,+ output: u.output,+ };+}++export const ULTRA_KEY_UNIFORM_NAMES = Object.keys(+ ultraKeyGpuUniforms(+ {+ keyR: 0, keyG: 255, keyB: 0, transparency: 0, highlight: 0, shadow: 0, tolerance: 0,+ pedestal: 0, choke: 0, soften: 0, contrast: 0, midPoint: 50, desaturate: 0, range: 0,+ spill: 0, luma: 0, saturation: 100, hue: 0, luminance: 100, output: "composite",+ },+ ),+);++/**+ * Key colour that best represents a sampled region of a frame: the average+ * RGB, 0-255. Used by the Program monitor eyedropper.+ */+export function ultraKeyColorFromSample(rgb: { r: number; g: number; b: number }): {+ keyR: number;+ keyG: number;+ keyB: number;+} {+ const c = (v: number): number => Math.round(clamp(v, 0, 255));+ return { keyR: c(rgb.r), keyG: c(rgb.g), keyB: c(rgb.b) };+}diff --git a/packages/core/src/video/video-effects-engine.ts b/packages/core/src/video/video-effects-engine.tsindex eebef52a..3a446a39 100644--- a/packages/core/src/video/video-effects-engine.ts+++ b/packages/core/src/video/video-effects-engine.ts@@ -18,8 +18,10 @@ import {proEffectGpuUniforms,type ProEffectType,} from "./pro-effects";+import { isTemporalEffectType } from "./temporal-effects";import { PRO_EFFECT_SHADER_DEFS } from "./pro-effect-shaders";import { isPluginEffectType } from "../plugins/manifest";+import { drawBurnIn, isBurnInEffectType } from "./burn-in";import { getPluginHost } from "../plugins/plugin-host";interface ResolvedShaderEffect {@@ -1307,6 +1309,14 @@ export class VideoEffectsEngine {): Promise<void> {const params = effect.params as Record<string, unknown>;if (effect.type === "mask" && applyIrisMaskToContext(ctx, params, width, height)) return;+ if (isBurnInEffectType(effect.type)) {+ // Text burn-ins (timecode, names) are drawn with Canvas2D on every path; the text was resolved per frame.+ ctx.save();+ ctx.setTransform(1, 0, 0, 1, 0, 0);+ drawBurnIn(ctx, effect.type, params, width, height);+ ctx.restore();+ return;+ }if (isProEffectType(effect.type)) {this.applyProEffectToContext(ctx, effect.type, params, width, height);return;@@ -1537,6 +1547,8 @@ export class VideoEffectsEngine {width: number,height: number,): void {+ // Echo / Posterize Time pick source frames upstream (VideoEngine); there is nothing to draw per pixel.+ if (isTemporalEffectType(type)) return;if (isProEffectNeutral(type, params)) return;if (this.applyProEffectGpu(ctx, type, params, width, height)) return;const imageData = ctx.getImageData(0, 0, width, height);diff --git a/packages/core/src/video/video-engine-temporal.test.ts b/packages/core/src/video/video-engine-temporal.test.tsnew file mode 100644index 00000000..ae17ce1c--- /dev/null+++ b/packages/core/src/video/video-engine-temporal.test.ts@@ -0,0 +1,290 @@+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";+import type { Project } from "../types/project";+import type { Clip, Effect, Transform } from "../types/timeline";++const mocks = vi.hoisted(() => ({+ effectsApply: vi.fn(),+ compose: vi.fn(),+}));++vi.mock("./video-effects-engine", async () => {+ const actual = await vi.importActual<typeof import("./video-effects-engine")>("./video-effects-engine");+ return {+ ...actual,+ VideoEffectsEngine: vi.fn().mockImplementation(() => ({+ initialize: vi.fn().mockResolvedValue(true),+ applyEffects: mocks.effectsApply,+ dispose: vi.fn(),+ })),+ };+});++vi.mock("./echo-compositor", () => ({+ EchoCompositor: vi.fn().mockImplementation(() => ({ compose: mocks.compose, dispose: vi.fn() })),+}));++let bitmapId = 0;+const makeBitmap = (label: string): ImageBitmap =>+ ({ label, id: bitmapId++, width: 640, height: 360, close: vi.fn() }) as unknown as ImageBitmap;++const transform: Transform = {+ position: { x: 0, y: 0 },+ scale: { x: 1, y: 1 },+ rotation: 0,+ anchor: { x: 0.5, y: 0.5 },+ opacity: 1,+ fitMode: "contain",+};++const makeProject = (clip: Clip): Project =>+ ({+ id: "p",+ name: "Temporal",+ createdAt: 0,+ modifiedAt: 0,+ settings: { width: 640, height: 360, frameRate: 30, sampleRate: 48000, channels: 2 },+ mediaLibrary: {+ items: [+ {+ id: "media-1",+ name: "clip.mp4",+ type: "video",+ fileHandle: null,+ blob: new Blob(["video"]),+ metadata: { duration: 20, width: 640, height: 360, frameRate: 30, codec: "h264", sampleRate: 48000, channels: 2, fileSize: 1 },+ thumbnailUrl: null,+ waveformData: null,+ },+ ],+ },+ timeline: {+ tracks: [+ { id: "track-1", type: "video", name: "V", clips: [clip], transitions: [], locked: false, hidden: false, muted: false, solo: false },+ ],+ subtitles: [],+ duration: 10,+ markers: [],+ },+ }) as unknown as Project;++const makeClip = (effects: Effect[], extra: Partial<Clip> = {}): Clip => ({+ id: "clip-1",+ mediaId: "media-1",+ trackId: "track-1",+ startTime: 1,+ duration: 8,+ inPoint: 2,+ outPoint: 10,+ effects,+ audioEffects: [],+ transform,+ volume: 1,+ keyframes: [],+ ...extra,+});++describe("VideoEngine temporal effects", { timeout: 60_000 }, () => {+ const ctx = new Proxy({}, { get: () => vi.fn(), set: () => true });++ beforeEach(() => {+ vi.clearAllMocks();+ bitmapId = 0;+ class MockOffscreenCanvas {+ constructor(+ public width: number,+ public height: number,+ ) {}+ getContext() {+ return ctx;+ }+ }+ vi.stubGlobal("OffscreenCanvas", MockOffscreenCanvas);+ vi.stubGlobal("createImageBitmap", vi.fn(async () => makeBitmap("copy")));+ vi.stubGlobal("self", { onmessage: null, postMessage: vi.fn(), addEventListener: vi.fn(), removeEventListener: vi.fn() });+ mocks.effectsApply.mockImplementation(async (image: ImageBitmap) => ({ image, processingTime: 0, gpuAccelerated: false }));+ mocks.compose.mockImplementation(async () => makeBitmap("composed"));+ });++ afterEach(() => {+ vi.unstubAllGlobals();+ });++ async function engineFor(exportMode = false) {+ const { VideoEngine } = await import("./video-engine");+ const engine = new VideoEngine();+ Object.assign(engine as unknown as Record<string, unknown>, { initialized: true, mediabunny: {} });+ engine.exportMode = exportMode;+ const decode = vi+ .spyOn(engine as unknown as { decodeFrameWithMediaBunny: (...a: unknown[]) => Promise<ImageBitmap | null> }, "decodeFrameWithMediaBunny")+ .mockImplementation(async (_blob, time) => makeBitmap(`frame@${(time as number).toFixed(4)}`));+ return { engine, decode };+ }++ const decodedTimes = (decode: { mock: { calls: unknown[][] } }) => decode.mock.calls.map((call) => call[1] as number);++ describe("Posterize Time", () => {+ const posterize = (frameRate: number): Effect => ({ id: "pt", type: "posterize-time", enabled: true, params: { frameRate } });++ it("reads the source at the start of the held frame", async () => {+ const { engine, decode } = await engineFor();+ const project = makeProject(makeClip([posterize(4)]));+ // timeline 2.10 / 2.20 / 2.24 are clip-local 1.10 / 1.20 / 1.24 -> held at 1.00 -> source 2 + 1.00+ for (const t of [2.1, 2.2, 2.24]) await engine.renderFrame(project, t, 640, 360);+ expect(decodedTimes(decode)).toEqual([3, 3, 3]);+ decode.mockClear();+ await engine.renderFrame(project, 2.25, 640, 360);+ expect(decodedTimes(decode)).toEqual([3.25]);+ engine.dispose();+ });++ it("is off at a rate of 0 and when the effect is disabled", async () => {+ const { engine, decode } = await engineFor();+ await engine.renderFrame(makeProject(makeClip([posterize(0)])), 2.1, 640, 360);+ await engine.renderFrame(makeProject(makeClip([{ ...posterize(4), enabled: false }])), 2.1, 640, 360);+ expect(decodedTimes(decode)).toEqual([expect.closeTo(3.1, 9), expect.closeTo(3.1, 9)]);+ engine.dispose();+ });++ it("follows a keyframed frame rate", async () => {+ const { engine, decode } = await engineFor();+ const clip = makeClip([posterize(30)], {+ keyframes: [+ { id: "a", time: 0, property: "effect.posterize-time.frameRate", value: 1, easing: "linear" },+ { id: "b", time: 4, property: "effect.posterize-time.frameRate", value: 5, easing: "linear" },+ ],+ });+ // clip-local 2.0: rate 3 -> frame 6 -> 2.0 exactly; clip-local 2.2 -> 2.0 (3 fps interval 0.333)+ await engine.renderFrame(makeProject(clip), 3.2, 640, 360);+ const held = decodedTimes(decode)[0];+ const rate = 1 + (2.2 / 4) * 4;+ expect(held).toBeCloseTo(2 + Math.floor(2.2 * rate + 1e-6) / rate, 9);+ engine.dispose();+ });++ it("picks the same frame regardless of render order or export mode", async () => {+ const project = makeProject(makeClip([posterize(6)]));+ const times = [4.01, 2.5, 6.99, 2.5, 4.01];+ const runs: number[][] = [];+ for (const exportMode of [false, true]) {+ const { engine, decode } = await engineFor(exportMode);+ for (const t of times) await engine.renderFrame(project, t, 640, 360);+ runs.push(decodedTimes(decode));+ engine.dispose();+ }+ expect(runs[0]).toEqual(runs[1]);+ expect(runs[0][1]).toBe(runs[0][3]);+ expect(runs[0][0]).toBe(runs[0][4]);+ });+ });++ describe("Echo", () => {+ const echo = (params: Record<string, unknown>): Effect => ({+ id: "echo-1",+ type: "echo",+ enabled: true,+ params: { echoTime: 0.1, echoes: 2, startIntensity: 1, decay: 0.5, operator: "add", ...params },+ });++ it("decodes the frames at t - k * echoTime and composites them with their intensities", async () => {+ const { engine, decode } = await engineFor();+ await engine.renderFrame(makeProject(makeClip([echo({})])), 4, 640, 360);+ // clip-local 3 -> source 5; echoes at clip-local 2.9, 2.8 -> source 4.9, 4.8+ expect(decodedTimes(decode)).toEqual([5, expect.closeTo(4.9, 9), expect.closeTo(4.8, 9)]);+ expect(mocks.compose).toHaveBeenCalledTimes(1);+ const [base, frames, params] = mocks.compose.mock.calls[0];+ expect((base as { label: string }).label).toBe("[email protected]");+ expect(frames.map((f: { weight: number }) => f.weight)).toEqual([0.5, 0.25]);+ expect(frames.map((f: { image: { label: string } }) => f.image.label)).toEqual(["[email protected]", "[email protected]"]);+ expect(params).toMatchObject({ operator: "add", startIntensity: 1 });+ engine.dispose();+ });++ it("does not decode echoes that fall before the clip's first frame", async () => {+ const { engine, decode } = await engineFor();+ // clip-local 0.15: echo 1 at 0.05 is inside the clip, echo 2 at -0.05 is not+ await engine.renderFrame(makeProject(makeClip([echo({})])), 1.15, 640, 360);+ expect(decodedTimes(decode)).toHaveLength(2);+ expect(decodedTimes(decode)[1]).toBeCloseTo(2.05, 9);+ // first frame of the clip: nothing to echo, no composite+ mocks.compose.mockClear();+ await engine.renderFrame(makeProject(makeClip([echo({})])), 1, 640, 360);+ expect(mocks.compose).not.toHaveBeenCalled();+ engine.dispose();+ });++ it("reaches into the future with a negative echo time", async () => {+ const { engine, decode } = await engineFor();+ await engine.renderFrame(makeProject(makeClip([echo({ echoTime: -0.25, echoes: 2 })])), 4, 640, 360);+ expect(decodedTimes(decode)).toEqual([5, 5.25, 5.5]);+ engine.dispose();+ });++ it("builds the echo on posterized time", async () => {+ const { engine, decode } = await engineFor();+ const clip = makeClip([+ { id: "pt", type: "posterize-time", enabled: true, params: { frameRate: 2 } },+ echo({ echoTime: 1, echoes: 1 }),+ ]);+ // clip-local 3.3 holds at 3.0 -> source 5; the echo is one second earlier+ await engine.renderFrame(makeProject(clip), 4.3, 640, 360);+ expect(decodedTimes(decode)).toEqual([5, 4]);+ engine.dispose();+ });++ it("follows keyframed echo parameters", async () => {+ const { engine, decode } = await engineFor();+ const clip = makeClip([echo({ echoes: 1 })], {+ keyframes: [+ { id: "a", time: 0, property: "effect.echo.echoes", value: 1, easing: "linear" },+ { id: "b", time: 4, property: "effect.echo.echoes", value: 5, easing: "linear" },+ ],+ });+ await engine.renderFrame(makeProject(clip), 5, 640, 360); // clip-local 4: 5 echoes+ expect(decodedTimes(decode)).toHaveLength(6);+ decode.mockClear();+ await engine.renderFrame(makeProject(clip), 3, 640, 360); // clip-local 2: 3 echoes+ expect(decodedTimes(decode)).toHaveLength(4);+ engine.dispose();+ });++ it("samples the same frames in preview, scrubbing and export", async () => {+ const project = makeProject(makeClip([echo({ echoes: 3 })]));+ const times = [6, 3.5, 6, 8.9];+ const runs: number[][] = [];+ for (const exportMode of [false, true]) {+ const { engine, decode } = await engineFor(exportMode);+ for (const t of times) {+ decode.mockClear();+ await engine.renderFrame(project, t, 640, 360);+ runs.push(decodedTimes(decode));+ }+ engine.dispose();+ }+ expect(runs.slice(0, 4)).toEqual(runs.slice(4));+ expect(runs[0]).toEqual(runs[2]);+ });++ it("applies the effects above the echo to every echo frame and the ones below to the result", async () => {+ const { engine } = await engineFor();+ const clip = makeClip([+ { id: "bright", type: "brightness", enabled: true, params: { value: 10 } },+ echo({ echoes: 2 }),+ { id: "contrast", type: "contrast", enabled: true, params: { value: 1.2 } },+ ]);+ await engine.renderFrame(makeProject(clip), 4, 640, 360);+ const stacks = mocks.effectsApply.mock.calls.map((call) => (call[1] as Effect[]).map((e) => e.type));+ // current frame, echo 1, echo 2 each get the brightness above the echo; the composite gets contrast+ expect(stacks).toEqual([["brightness"], ["brightness"], ["brightness"], ["contrast"]]);+ engine.dispose();+ });++ it("fails an export frame instead of silently dropping an echo that cannot be decoded", async () => {+ const { engine, decode } = await engineFor(true);+ decode.mockImplementation(async (_blob, time) => ((time as number) < 5 ? null : makeBitmap("ok")));+ // the fallback decoder is not available in the test: stub it out too+ vi.spyOn(engine as unknown as { decodeFrameWithVideoElement: () => Promise<null> }, "decodeFrameWithVideoElement").mockResolvedValue(null);+ await expect(engine.renderFrame(makeProject(makeClip([echo({})])), 4, 640, 360)).rejects.toThrow(/Echo frame/);+ engine.dispose();+ });+ });+});diff --git a/packages/core/src/video/video-engine.hidden-subtitles.test.ts b/packages/core/src/video/video-engine.hidden-subtitles.test.tsnew file mode 100644index 00000000..0295bc73--- /dev/null+++ b/packages/core/src/video/video-engine.hidden-subtitles.test.ts@@ -0,0 +1,64 @@+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";+import type { Project, Subtitle } from "../types";++const drawn: string[] = [];+vi.mock("../captions/caption-layout", async (orig) => ({+ ...(await orig<typeof import("../captions/caption-layout")>()),+ drawCaption: (_ctx: unknown, sub: Subtitle) => {+ drawn.push(sub.id);+ },+}));++beforeEach(() => {+ drawn.length = 0;+ vi.stubGlobal("self", {+ onmessage: null,+ postMessage: vi.fn(),+ addEventListener: vi.fn(),+ removeEventListener: vi.fn(),+ });+});+afterEach(() => {+ vi.restoreAllMocks();+ vi.unstubAllGlobals();+});++const cue = (id: string, hidden?: boolean): Subtitle =>+ ({ id, text: id, startTime: 0, endTime: 5, ...(hidden ? { hidden: true } : {}) }) as Subtitle;++describe("hidden caption cues", () => {+ it("renderFrame draws visible cues and skips hidden (translated) cues", async () => {+ const { VideoEngine } = await import("./video-engine");+ const engine = new VideoEngine();+ const ctx = {+ canvas: {},+ fillRect: vi.fn(),+ clearRect: vi.fn(),+ save: vi.fn(),+ restore: vi.fn(),+ drawImage: vi.fn(),+ };+ Object.assign(engine, {+ ensureInitialized: vi.fn(),+ compositeCanvas: { width: 640, height: 360 },+ compositeCtx: ctx,+ });+ vi.stubGlobal("createImageBitmap", vi.fn(async () => ({ width: 640, height: 360, close: vi.fn() })));+ const project = {+ id: "p",+ name: "p",+ createdAt: 0,+ modifiedAt: 0,+ settings: { width: 640, height: 360, frameRate: 30, sampleRate: 48000, channels: 2 },+ mediaLibrary: { items: [] },+ timeline: {+ tracks: [],+ duration: 5,+ subtitles: [cue("shown"), cue("translated", true)],+ markers: [],+ },+ } as unknown as Project;+ await engine.renderFrame(project, 1, 640, 360);+ expect(drawn).toEqual(["shown"]);+ });+});diff --git a/packages/core/src/video/video-engine.ts b/packages/core/src/video/video-engine.tsindex 95063bec..e9c23508 100644--- a/packages/core/src/video/video-engine.ts+++ b/packages/core/src/video/video-engine.ts@@ -53,6 +53,14 @@ import { titleEngine } from "../text/title-engine";import type { ThreeJSLayerRenderer } from "./overlay-three-renderer";import { graphicsEngine } from "../graphics/graphics-engine";import { VideoEffectsEngine } from "./video-effects-engine";+import { EchoCompositor } from "./echo-compositor";+import {+ clipHasTemporalEffects,+ findActiveEcho,+ isTemporalEffectType,+ planEcho,+ posterizedClipTime,+} from "./temporal-effects";import {ColorGradingEngine,type ClipColorGrading,@@ -96,6 +104,7 @@ import { GPUCompositor, initializeGPUCompositor } from "./gpu-compositor";import { getRendererFactory, type Renderer } from "./renderer-factory";import { keyframeEngine } from "./keyframe-engine";import { getAnimatedVideoEffects, isRenderableVideoEffect } from "./animated-video-effects";+import { createBurnInSource, drawBurnIn, timecodeBurnInOverlay, withBurnInText, type BurnInSource, type TimecodeBurnInSettings } from "./burn-in";import { getAnimatedColorGrading } from "./animated-color-grading";import { getBackgroundRemovalEngine } from "../ai/background-removal-engine";import {@@ -148,6 +157,8 @@ interface FrameRenderOptions {textClips?: TextClip[];shapeClips?: ShapeClip[];realtime?: boolean;+ /** Export "Timecode burn-in": drawn last, over every track, adjustment layer and caption. */+ timecodeBurnIn?: TimecodeBurnInSettings;}type RenderableClipColorGrading = Omit<ClipColorGrading, "lut" | "inputLut"> & {@@ -155,6 +166,17 @@ type RenderableClipColorGrading = Omit<ClipColorGrading, "lut" | "inputLut"> & {inputLut?: LUTData;};+/** What a clip's effect stack needs to read other moments of the same clip (Echo). */+interface TemporalClipContext {+ readonly clip: Clip;+ readonly media: MediaItem;+ /** Clip-local time of the frame being rendered, with Posterize Time already applied. */+ readonly localTime: number;+ /** Size echo frames are decoded at (the project size the main frame was decoded at). */+ readonly decodeWidth: number;+ readonly decodeHeight: number;+}+/*** VideoEngine handles video frame rendering and composition.* Supports GPU acceleration, parallel decoding, frame caching, and effects.@@ -175,6 +197,8 @@ export class VideoEngine {private frameCache: Map<string, CachedFrame> = new Map();/** Pixel aspect of the sequence being rendered (1 = square); clips are squeezed by it so they keep their display shape. */private sequencePixelAspect = 1;+ /** Burn-in source of the project being composed (frames are serialized, so one slot is enough). */+ private burnInSource: BurnInSource | undefined;private gifFrameCache: Map<string, GifFrameCache> = new Map();private staticImageCache: Map<string, ImageBitmap> = new Map();private cacheConfig: FrameCacheConfig;@@ -209,6 +233,7 @@ export class VideoEngine {private gpuCompositor: GPUCompositor | null = null;private gpuRenderer: Renderer | null = null;private effectsEngine: VideoEffectsEngine | null = null;+ private readonly echoCompositor = new EchoCompositor();private colorGradingEngine: ColorGradingEngine | null = null;private transitionEngine: TransitionEngine | null = null;private maskEngine: MaskEngine | null = null;@@ -877,6 +902,7 @@ export class VideoEngine {const scaleX = width / settings.width;const scaleY = height / settings.height;this.sequencePixelAspect = normalizeSequencePar(settings.pixelAspectRatio);+ this.burnInSource = createBurnInSource(project);const activeTextClips = this.getActiveTextClips(timeline, time);const activeShapeClips = this.getActiveShapeClips(timeline, time);@@ -999,7 +1025,7 @@ export class VideoEngine {isolatedTrack = null;try {for (const placement of placements) {- await this.applyAdjustmentLayerToCtx(ctx, placement.layer, width, height);+ await this.applyAdjustmentLayerToCtx(ctx, placement.layer, width, height, time);}ctx.save();ctx.globalCompositeOperation = "destination-over";@@ -1014,7 +1040,7 @@ export class VideoEngine {for (const { track, originalIndex } of allRenderableTracks) {await closeIsolatedTrack();for (const placement of adjustmentSchedule.takeCompositeBefore(originalIndex)) {- await this.applyAdjustmentLayerToCtx(ctx, placement.layer, width, height);+ await this.applyAdjustmentLayerToCtx(ctx, placement.layer, width, height, time);}const scopedPlacements = adjustmentSchedule.scopedFor(track.id);if (@@ -1368,6 +1394,13 @@ export class VideoEngine {getAnimatedColorGrading(clip, time - clip.startTime),width,height,+ {+ clip,+ media: mediaItem,+ localTime: posterizedClipTime(clipInfo.effects ?? [], time - clip.startTime),+ decodeWidth: settings.width,+ decodeHeight: settings.height,+ },);const vidstabEng = getVidstabEngine();@@ -1487,7 +1520,7 @@ export class VideoEngine {subjectFrame?.close();await closeIsolatedTrack();for (const placement of adjustmentSchedule.takeRemainingComposite()) {- await this.applyAdjustmentLayerToCtx(ctx, placement.layer, width, height);+ await this.applyAdjustmentLayerToCtx(ctx, placement.layer, width, height, time);}// Particles and subtitles sit above every track, so no adjustment layer reaches them.@@ -1499,6 +1532,13 @@ export class VideoEngine {this.renderSubtitleToCanvasCtx(ctx, subtitle, width, height);}+ const burnInOverlay = timecodeBurnInOverlay(project, options.timecodeBurnIn, time);+ if (burnInOverlay) {+ withDisplaySpace(ctx, width, this.sequencePixelAspect, (layoutWidth) => {+ drawBurnIn(ctx, "burn-in-timecode", burnInOverlay.params, layoutWidth, height);+ });+ }+if (hdr) {// Particles and subtitles were drawn on the canvas after the last track: merge them, then show the// tone-mapped SDR view (the preview) and, for an HDR export, encode the float image itself.@@ -1729,9 +1769,16 @@ export class VideoEngine {layer: NonNullable<Project["adjustmentLayers"]>[number],width: number,height: number,+ time: number,): Promise<void> {{- const effects = layer.effects.filter((effect) => effect.enabled !== false);+ // Burn-ins on an adjustment layer count from the layer's first frame, like a clip's.+ const effects = withBurnInText(+ layer.effects.filter((effect) => effect.enabled !== false),+ { id: layer.id, startTime: layer.startTime, inPoint: 0 },+ time - layer.startTime,+ this.burnInSource,+ ) as Effect[];if (effects.length === 0) return;let source: ImageBitmap | null = null;@@ -2442,7 +2489,7 @@ export class VideoEngine {await this.drawOverlayCanvasWithEffects(ctx,renderer.render(),- getAnimatedVideoEffects(textClip, clipLocalTime),+ getAnimatedVideoEffects(textClip, clipLocalTime, this.burnInSource),width,height,);@@ -2463,7 +2510,7 @@ export class VideoEngine {await this.drawOverlayCanvasWithEffects(ctx,result.canvas,- getAnimatedVideoEffects(textClip, clipLocalTime),+ getAnimatedVideoEffects(textClip, clipLocalTime, this.burnInSource),width,height,);@@ -2488,7 +2535,7 @@ export class VideoEngine {await this.drawOverlayCanvasWithEffects(ctx,result.canvas,- getAnimatedVideoEffects(shapeClip, clipLocalTime),+ getAnimatedVideoEffects(shapeClip, clipLocalTime, this.burnInSource),width,height,);@@ -2513,7 +2560,7 @@ export class VideoEngine {await this.drawOverlayCanvasWithEffects(ctx,result.canvas,- getAnimatedVideoEffects(svgClip, clipLocalTime),+ getAnimatedVideoEffects(svgClip, clipLocalTime, this.burnInSource),width,height,);@@ -2538,7 +2585,7 @@ export class VideoEngine {await this.drawOverlayCanvasWithEffects(ctx,result.canvas,- getAnimatedVideoEffects(stickerClip, clipLocalTime),+ getAnimatedVideoEffects(stickerClip, clipLocalTime, this.burnInSource),width,height,);@@ -2589,7 +2636,8 @@ export class VideoEngine {private getActiveSubtitles(timeline: Timeline, time: number): Subtitle[] {const subtitles = timeline.subtitles || [];return subtitles.filter((sub) => {- return time >= sub.startTime && time < sub.endTime;+ // Hidden cues (e.g. the other language of a translation) stay out of the picture on every path.+ return !sub.hidden && time >= sub.startTime && time < sub.endTime;});}@@ -2681,8 +2729,11 @@ export class VideoEngine {time: number,width: number,height: number,+ sourceLocalTime?: number,): Promise<ImageBitmap | null> {if (!mediaItem.blob) return null;+ // Clip-local time the frame is read at: Posterize Time holds it, Echo frames pass their own.+ const frameLocalTime = sourceLocalTime ?? this.posterizedLocalTime(clip, time - clip.startTime);if (mediaItem.type === "image") {try {@@ -2696,8 +2747,7 @@ export class VideoEngine {}}if (gifCache && gifCache.frames.length > 0) {- const clipLocalTime = time - clip.startTime;- const idx = getGifFrameAtTime(gifCache, getAnimatedImageSourceTime(clip, clipLocalTime) * 1000);+ const idx = getGifFrameAtTime(gifCache, getAnimatedImageSourceTime(clip, frameLocalTime) * 1000);return gifCache.frames[idx];}}@@ -2716,12 +2766,11 @@ export class VideoEngine {}const speedEngine = getSpeedEngine();- const localTime = time - clip.startTime;const sourceTime = Math.max(clip.inPoint,Math.min(clip.outPoint,- clip.inPoint + speedEngine.getSourceTimeAtPlaybackTime(clip.id, localTime),+ clip.inPoint + speedEngine.getSourceTimeAtPlaybackTime(clip.id, frameLocalTime),),);@@ -2795,25 +2844,42 @@ export class VideoEngine {if (!bitmapA || !bitmapB) {return rendered;}+ const effectsA = this.getAnimatedEffects(clipA, time - clipA.startTime);processedA = await this.applyClipVideoProcessing(clipA.id,bitmapA,bitmapA,- this.getAnimatedEffects(clipA, time - clipA.startTime),+ effectsA,getAnimatedColorGrading(clipA, time - clipA.startTime),width,height,+ {+ clip: clipA,+ media: mediaA,+ localTime: posterizedClipTime(effectsA, time - clipA.startTime),+ decodeWidth: width,+ decodeHeight: height,+ },);+ const effectsB =+ clipB && mediaB ? this.getAnimatedEffects(clipB, time - clipB.startTime) : [];processedB =clipB && mediaB? await this.applyClipVideoProcessing(clipB.id,bitmapB,bitmapB,- this.getAnimatedEffects(clipB, time - clipB.startTime),+ effectsB,getAnimatedColorGrading(clipB, time - clipB.startTime),width,height,+ {+ clip: clipB,+ media: mediaB,+ localTime: posterizedClipTime(effectsB, time - clipB.startTime),+ decodeWidth: width,+ decodeHeight: height,+ },): bitmapB;@@ -2862,13 +2928,17 @@ export class VideoEngine {private createClipRenderInfo(clip: Clip, time: number): VideoClipRenderInfo {const clipLocalTime = time - clip.startTime;+ const animatedTransform = this.getAnimatedTransform(clip, clipLocalTime);+ const animatedEffects = this.getAnimatedEffects(clip, clipLocalTime);++ // Posterize Time holds the frame: the source is read at the start of the posterized frame, not at `time`.const speedEngine = getSpeedEngine();const sourceTime =clip.inPoint +- speedEngine.getSourceTimeAtPlaybackTime(clip.id, clipLocalTime);-- const animatedTransform = this.getAnimatedTransform(clip, clipLocalTime);- const animatedEffects = this.getAnimatedEffects(clip, clipLocalTime);+ speedEngine.getSourceTimeAtPlaybackTime(+ clip.id,+ posterizedClipTime(animatedEffects, clipLocalTime),+ );return {clipId: clip.id,@@ -2926,6 +2996,7 @@ export class VideoEngine {colorGrading: ClipColorGrading | undefined,width: number,height: number,+ temporal?: TemporalClipContext,): Promise<ImageBitmap> {image = await this.applyClipInputTransform(clipId, image, sourceImage);let processed = await this.applyClipEffects(@@ -2935,6 +3006,7 @@ export class VideoEngine {effects,width,height,+ temporal,);processed = await this.applyClipColorGrading(clipId,@@ -2954,12 +3026,27 @@ export class VideoEngine {effects: Effect[],width: number,height: number,+ temporal?: TemporalClipContext,): Promise<ImageBitmap> {const enabledEffects = effects.filter((effect) => effect.enabled);if (enabledEffects.length === 0) {return image;}+ const echo = temporal ? findActiveEcho(enabledEffects) : null;+ if (echo && temporal) {+ return this.applyEchoStack(+ clipId,+ image,+ sourceImage,+ enabledEffects,+ echo,+ temporal,+ width,+ height,+ );+ }+try {const effectsEngine = await this.ensureEffectsEngine(width, height);const result = await effectsEngine.applyEffects(image, enabledEffects);@@ -3163,6 +3250,111 @@ export class VideoEngine {}}+ /** Clip-local time a frame is read at once Posterize Time is applied (the time itself without the effect). */+ private posterizedLocalTime(clip: Clip, localTime: number): number {+ if (!clipHasTemporalEffects(clip)) return localTime;+ return posterizedClipTime(this.getAnimatedEffects(clip, localTime), localTime);+ }++ /**+ * Runs an effect stack that contains an active Echo. Effects above the echo+ * see every frame it combines (each echo frame is decoded at its own+ * clip-local time and graded with the stack sampled at that time), the echo+ * combines them, and the effects below it see the combined frame. The set of+ * source frames is a pure function of the clip-local time and the echo+ * parameters, so preview, scrubbing and export agree.+ */+ private async applyEchoStack(+ clipId: string,+ image: ImageBitmap,+ sourceImage: ImageBitmap,+ enabledEffects: Effect[],+ active: NonNullable<ReturnType<typeof findActiveEcho>>,+ temporal: TemporalClipContext,+ width: number,+ height: number,+ ): Promise<ImageBitmap> {+ const { clip, localTime } = temporal;+ const echoEffect = enabledEffects[active.index];+ const above = enabledEffects.slice(0, active.index).filter((e) => !isTemporalEffectType(e.type));+ const below = enabledEffects.slice(active.index + 1);+ const samples = planEcho(localTime, clip.duration, active.echo);++ let current = above.length > 0+ ? await this.applyClipEffects(clipId, image, sourceImage, above, width, height)+ : image;+ if (samples.length > 0) {+ const echoes: { frame: ImageBitmap; owned: boolean; weight: number }[] = [];+ try {+ for (const sample of samples) {+ const frame = await this.decodeEchoFrame(temporal, echoEffect.id, sample.localTime, width, height);+ if (!frame) {+ if (this.exportMode) {+ throw new Error(`Echo frame at ${sample.localTime.toFixed(3)}s of clip ${clipId} could not be decoded`);+ }+ continue;+ }+ echoes.push({ ...frame, weight: sample.weight });+ }+ const composed = await this.echoCompositor.compose(+ current,+ echoes.map((e) => ({ image: e.frame, weight: e.weight })),+ active.echo,+ );+ current = this.adoptProcessedBitmap(current, sourceImage, composed);+ } finally {+ for (const echoFrame of echoes) {+ if (echoFrame.owned) this.closeBitmap(echoFrame.frame);+ }+ }+ }+ return below.length > 0+ ? this.applyClipEffects(clipId, current, sourceImage, below, width, height)+ : current;+ }++ /**+ * One echo frame: the clip's source frame at clip-local `localTime`, through+ * the input transform and the effects stacked above the echo, sampled at+ * that time. `owned` says whether the caller must close the bitmap (stills+ * come from the shared image cache and must not be closed).+ */+ private async decodeEchoFrame(+ temporal: TemporalClipContext,+ echoEffectId: string,+ localTime: number,+ width: number,+ height: number,+ ): Promise<{ frame: ImageBitmap; owned: boolean } | null> {+ const { clip, media } = temporal;+ const decoded = await this.decodeClipBitmap(+ clip,+ media,+ clip.startTime + localTime,+ temporal.decodeWidth,+ temporal.decodeHeight,+ localTime,+ );+ if (!decoded) return null;+ const isVideo = media.type !== "image";+ let current = decoded;+ try {+ current = await this.applyClipInputTransform(clip.id, current, decoded);+ const stack = this.getAnimatedEffects(clip, localTime).filter((e) => e.enabled);+ const cut = stack.findIndex((e) => e.id === echoEffectId);+ const above = (cut < 0 ? stack : stack.slice(0, cut)).filter((e) => !isTemporalEffectType(e.type));+ if (above.length > 0) {+ current = await this.applyClipEffects(clip.id, current, decoded, above, width, height);+ }+ } catch (error) {+ if (current !== decoded) this.closeBitmap(current);+ if (isVideo) this.closeBitmap(decoded);+ throw error;+ }+ if (current !== decoded && isVideo) this.closeBitmap(decoded);+ return { frame: current, owned: current !== decoded || isVideo };+ }+private async ensureEffectsEngine(width: number,height: number,@@ -3293,7 +3485,7 @@ export class VideoEngine {}private getAnimatedEffects(clip: Clip, localTime: number): Effect[] {- return getAnimatedVideoEffects(clip, localTime);+ return getAnimatedVideoEffects(clip, localTime, this.burnInSource);}private getAnimatedTransform(clip: Clip, localTime: number): Transform {@@ -4515,6 +4707,7 @@ export class VideoEngine {this.motionRenderer = null;this.effectsEngine?.dispose();this.effectsEngine = null;+ this.echoCompositor.dispose();this.colorGradingEngine?.dispose();this.colorGradingEngine = null;this.maskEngine = null;diff --git a/packages/core/src/video/white-balance-eyedropper.test.ts b/packages/core/src/video/white-balance-eyedropper.test.tsnew file mode 100644index 00000000..33d1a0b8--- /dev/null+++ b/packages/core/src/video/white-balance-eyedropper.test.ts@@ -0,0 +1,144 @@+import { describe, expect, it } from "vitest";+import {+ applyWhiteBalance,+ isFarFromNeutral,+ isUsableWhiteBalanceSample,+ needsWhiteBalanceInputFrame,+ whiteBalanceInputGrading,+ solveNeutralWhiteBalance,+ whiteBalanceOffset,+ whiteBalanceSampleRadius,+} from "./white-balance-eyedropper";+import { prepareHdrGrade } from "../color/hdr-working";+import { sampleAverageRgb } from "./hsl-secondary";+import { isNeutralColorGrading } from "./color-grading-defaults";++const spread = (rgb: readonly number[]) => Math.max(...rgb) - Math.min(...rgb);++describe("white balance eyedropper maths", () => {+ it("uses the same offsets as the HDR grade", () => {+ for (const [temperature, tint] of [[40, 10], [-30, 25], [0, -50], [100, 100], [-100, -100]]) {+ const hdr = prepareHdrGrade({ temperature, tint })?.whiteBalance;+ const mine = whiteBalanceOffset(temperature, tint);+ expect(hdr).toBeTruthy();+ mine.forEach((v, i) => expect(v).toBeCloseTo((hdr as unknown as number[])[i], 10));+ }+ });++ it("is a no-op at zero", () => {+ expect(whiteBalanceOffset(0, 0)).toEqual([0, 0, 0]);+ });++ it("neutralises a warm cast", () => {+ const sample: [number, number, number] = [0.62, 0.5, 0.38];+ const out = solveNeutralWhiteBalance(sample)!;+ expect(out.temperature).toBeLessThan(0);+ expect(spread(applyWhiteBalance(sample, out.temperature, out.tint))).toBeLessThan(1 / 255);+ expect(out.clamped).toBe(false);+ });++ it("neutralises a cool / green cast", () => {+ const sample: [number, number, number] = [0.4, 0.55, 0.6];+ const out = solveNeutralWhiteBalance(sample)!;+ expect(out.temperature).toBeGreaterThan(0);+ expect(spread(applyWhiteBalance(sample, out.temperature, out.tint))).toBeLessThan(1 / 255);+ });++ it("recovers the inverse of any slider pair that fits the range", () => {+ for (const temperature of [-80, -35, -1, 0, 1, 22, 60, 90]) {+ for (const tint of [-70, -10, 0, 15, 55]) {+ const grey = 0.5;+ const cast = applyWhiteBalance([grey, grey, grey], temperature, tint);+ const out = solveNeutralWhiteBalance(cast)!;+ // Recovering the cast means the sliders cancel it: the neutral colour comes back.+ expect(spread(out.neutral)).toBeLessThan(1 / 255);+ const back = applyWhiteBalance(cast, out.temperature, out.tint);+ expect(spread(back)).toBeLessThan(1 / 255);+ }+ }+ });++ it("does not compound when the clip already has a white balance", () => {+ const source: [number, number, number] = [0.55, 0.48, 0.4];+ const first = solveNeutralWhiteBalance(source)!;+ const shown = applyWhiteBalance(source, first.temperature, first.tint);+ const second = solveNeutralWhiteBalance(shown, first)!;+ expect(second.temperature).toBeCloseTo(first.temperature, 0);+ expect(second.tint).toBeCloseTo(first.tint, 0);+ });++ it("picking an already neutral grey keeps the sliders at zero", () => {+ const out = solveNeutralWhiteBalance([0.5, 0.5, 0.5])!;+ expect(out.temperature).toBe(0);+ expect(out.tint).toBe(0);+ });++ it("clamps impossible casts to the slider range and says so", () => {+ const out = solveNeutralWhiteBalance([0.95, 0.5, 0.05 + 0.01])!;+ expect(out.clamped).toBe(true);+ expect(Math.abs(out.temperature)).toBeLessThanOrEqual(100);+ expect(Math.abs(out.tint)).toBeLessThanOrEqual(100);+ });++ it("rejects black, white and rail-pinned samples", () => {+ expect(solveNeutralWhiteBalance([0, 0, 0])).toBeNull();+ expect(solveNeutralWhiteBalance([1, 1, 1])).toBeNull();+ expect(solveNeutralWhiteBalance([1, 0.5, 0.4])).toBeNull();+ expect(solveNeutralWhiteBalance([Number.NaN, 0.5, 0.4])).toBeNull();+ expect(isUsableWhiteBalanceSample([0.2, 0.3, 0.4])).toBe(true);+ });++ it("survives 8-bit quantisation of the sample", () => {+ const bytes: [number, number, number] = [158, 128, 97];+ const sample = bytes.map((v) => v / 255) as [number, number, number];+ const out = solveNeutralWhiteBalance(sample)!;+ const result = applyWhiteBalance(sample, out.temperature, out.tint).map((v) => v * 255);+ expect(spread(result)).toBeLessThan(0.6);+ });++ it("averages a 5x5 footprint and a single pixel differently", () => {+ const width = 8;+ const data = new Uint8ClampedArray(width * width * 4).fill(255);+ for (let i = 0; i < width * width; i++) {+ data[i * 4] = 100;+ data[i * 4 + 1] = 100;+ data[i * 4 + 2] = 100;+ }+ const centre = (4 * width + 4) * 4;+ data[centre] = 200;+ expect(whiteBalanceSampleRadius(1)).toBe(0);+ expect(whiteBalanceSampleRadius(5)).toBe(2);+ expect(sampleAverageRgb(data, width, width, 4, 4, whiteBalanceSampleRadius(1))[0] * 255).toBeCloseTo(200);+ expect(sampleAverageRgb(data, width, width, 4, 4, whiteBalanceSampleRadius(5))[0] * 255).toBeCloseTo(104);+ });+});++describe("white balance stage input", () => {+ const tone = { contrast: 60 } as never;++ it("keeps only the input LUT on a version 2 clip (white balance runs first)", () => {+ const lut = { name: "log", size: 2, data: new Float32Array(24) } as never;+ const input = whiteBalanceInputGrading({ pipelineVersion: 2, temperature: 30, tint: 5, tone, inputLut: lut });+ expect(input).toEqual({ pipelineVersion: 2, inputLut: lut });+ });++ it("only removes white balance on a version 1 clip (white balance runs last)", () => {+ const input = whiteBalanceInputGrading({ temperature: 30, tint: 5, tone });+ expect(input).toEqual({ temperature: 0, tint: 0, tone });+ });++ it("asks for the input frame only when the displayed pixel differs from it", () => {+ const need = (g: Parameters<typeof isNeutralColorGrading>[0] & { pipelineVersion?: number }) =>+ needsWhiteBalanceInputFrame(g, isNeutralColorGrading);+ expect(need({ pipelineVersion: 2 })).toBe(false);+ expect(need({ pipelineVersion: 2, tone: { contrast: 60 } as never })).toBe(true);+ expect(need({ pipelineVersion: 2, temperature: 10 })).toBe(true);+ expect(need({ tone: { contrast: 60 } as never })).toBe(false);+ expect(need({ temperature: 10 })).toBe(true);+ });++ it("rejects strongly coloured samples", () => {+ expect(isFarFromNeutral([31 / 255, 22 / 255, 14 / 255])).toBe(true);+ expect(isFarFromNeutral([0.55, 0.5, 0.45])).toBe(false);+ });+});diff --git a/packages/core/src/video/white-balance-eyedropper.ts b/packages/core/src/video/white-balance-eyedropper.tsnew file mode 100644index 00000000..8ac5522c--- /dev/null+++ b/packages/core/src/video/white-balance-eyedropper.ts@@ -0,0 +1,156 @@+/**+ * White-balance eyedropper maths (Lumetri "WB Selector").+ *+ * The clip's Temperature / Tint sliders (-100..100) add a fixed per-channel+ * offset to the picture. The same coefficients drive the Canvas2D / export+ * path (`VideoEffectsEngine`), the effects shaders and the HDR grade+ * (`prepareHdrGrade`), so the eyedropper only has to invert one linear model:+ * pick the offset that makes a sampled colour grey.+ *+ * r' = r + 0.2 T + 0.1 t+ * g' = g + k T - 0.2 t k = 0.1 (T > 0, warm) or 0.05 (T <= 0, cool)+ * b' = b - 0.2 T + 0.1 t+ *+ * with T = temperature / 100 and t = tint / 100. Setting r' = g' = b' gives a+ * closed form, so the result is exact (no iteration) whenever it fits the+ * slider range.+ */++export type Rgb01 = readonly [number, number, number];++export interface WhiteBalanceValues {+ /** -100..100, negative = cooler. */+ temperature: number;+ /** -100..100, negative = greener. */+ tint: number;+}++export interface WhiteBalanceSolution extends WhiteBalanceValues {+ /** True when the neutralising values did not fit the slider range and were clamped. */+ clamped: boolean;+ /** The sampled colour after the returned white balance (grey unless clamped), 0..1. */+ neutral: Rgb01;+}++/** Slider range of Temperature and Tint. */+export const WB_RANGE = 100;++/** Samples closer to black / white than this carry no usable colour information. */+export const WB_CLIP_MARGIN = 2 / 255;++const COOL_GREEN = 0.05;+const WARM_GREEN = 0.1;++const clamp = (value: number, lo: number, hi: number): number => Math.min(hi, Math.max(lo, value));++/** Per-channel offset (in 0..1 units) that Temperature / Tint add to a pixel. */+export function whiteBalanceOffset(temperature: number, tint: number): [number, number, number] {+ const T = (Number.isFinite(temperature) ? temperature : 0) / WB_RANGE;+ const t = (Number.isFinite(tint) ? tint : 0) / WB_RANGE;+ const k = T > 0 ? WARM_GREEN : COOL_GREEN;+ return [0.2 * T + 0.1 * t, k * T - 0.2 * t, -0.2 * T + 0.1 * t];+}++/** The colour after Temperature / Tint (unclamped, 0..1 units). */+export function applyWhiteBalance(rgb: Rgb01, temperature: number, tint: number): [number, number, number] {+ const [dr, dg, db] = whiteBalanceOffset(temperature, tint);+ return [rgb[0] + dr, rgb[1] + dg, rgb[2] + db];+}++/**+ * Whether a sample can drive the eyedropper. Pure black / pure white (or a+ * channel pinned at either rail) says nothing about the light colour.+ */+export function isUsableWhiteBalanceSample(rgb: Rgb01): boolean {+ return rgb.every((v) => Number.isFinite(v) && v > WB_CLIP_MARGIN && v < 1 - WB_CLIP_MARGIN);+}++/**+ * Temperature / Tint that turn the sampled colour neutral.+ *+ * `sample` is what the Program monitor shows, so it already contains the+ * clip's current white balance; that offset is removed first. The result is+ * absolute (it replaces the sliders), so picking twice never compounds.+ *+ * Returns null when the sample is unusable (see `isUsableWhiteBalanceSample`).+ */+export function solveNeutralWhiteBalance(+ sample: Rgb01,+ current: Partial<WhiteBalanceValues> = {},+): WhiteBalanceSolution | null {+ if (!isUsableWhiteBalanceSample(sample)) return null;+ const [cr, cg, cb] = whiteBalanceOffset(current.temperature ?? 0, current.tint ?? 0);+ const r = sample[0] - cr;+ const g = sample[1] - cg;+ const b = sample[2] - cb;++ // r' = b' => r - b + 0.4 T = 0+ const T = (b - r) / 0.4;+ // g' = b' => 0.3 t = g - b + (k + 0.2) T, with k chosen by the sign of T+ const k = T > 0 ? WARM_GREEN : COOL_GREEN;+ const t = (g - b + (k + 0.2) * T) / 0.3;++ const temperature = clamp(Math.round(T * WB_RANGE * 10) / 10, -WB_RANGE, WB_RANGE);+ const tint = clamp(Math.round(t * WB_RANGE * 10) / 10, -WB_RANGE, WB_RANGE);+ const clamped = Math.abs(T * WB_RANGE) > WB_RANGE + 0.05 || Math.abs(t * WB_RANGE) > WB_RANGE + 0.05;+ return { temperature, tint, clamped, neutral: applyWhiteBalance([r, g, b], temperature, tint) };+}++/** Sample footprint of the eyedropper: a single pixel or a 5x5 average. */+export type WhiteBalanceSampleSize = 1 | 5;++export function whiteBalanceSampleRadius(size: WhiteBalanceSampleSize): number {+ return size === 5 ? 2 : 0;+}++/** Saturation (max-min)/max above which a sample is a coloured object, not a neutral reference. */+export const WB_MAX_SAMPLE_SATURATION = 0.5;++/** HSV saturation of a 0..1 colour. */+export function whiteBalanceSampleSaturation(rgb: Rgb01): number {+ const max = Math.max(rgb[0], rgb[1], rgb[2]);+ const min = Math.min(rgb[0], rgb[1], rgb[2]);+ return max > 0 ? (max - min) / max : 0;+}++/** True when the sample is so coloured that neutralising it would be a mistake (e.g. a brown wall, skin). */+export function isFarFromNeutral(rgb: Rgb01): boolean {+ return whiteBalanceSampleSaturation(rgb) > WB_MAX_SAMPLE_SATURATION;+}++interface WhiteBalanceInputGradingShape {+ pipelineVersion?: number;+ temperature?: number;+ tint?: number;+ inputLut?: unknown;+}++/**+ * The grade as it exists at the white-balance stage INPUT.+ *+ * Version 2 (Premiere order) runs white balance right after the input LUT and+ * before tone, curves, wheels, LUT, HSL and look, so only the input LUT is+ * kept. Version 1 runs white balance last, so everything stays and only the+ * white balance itself is removed.+ */+export function whiteBalanceInputGrading<T extends WhiteBalanceInputGradingShape>(grading: T): T {+ if (grading.pipelineVersion === 2) {+ const kept: WhiteBalanceInputGradingShape = { pipelineVersion: 2 };+ if (grading.inputLut !== undefined) kept.inputLut = grading.inputLut;+ return kept as T;+ }+ return { ...grading, temperature: 0, tint: 0 };+}++/**+ * Whether the displayed pixel differs from the white-balance stage input, so a+ * pick must render that input frame instead of reading the Program monitor.+ */+export function needsWhiteBalanceInputFrame<T extends WhiteBalanceInputGradingShape>(+ grading: T,+ isNeutral: (grading: T) => boolean,+): boolean {+ const wbActive = Math.abs(grading.temperature ?? 0) > 1e-6 || Math.abs(grading.tint ?? 0) > 1e-6;+ if (grading.pipelineVersion !== 2) return wbActive;+ return wbActive || !isNeutral({ ...grading, inputLut: undefined } as T);+}