Skip to content

OpenReel Video - Professional browser-based video editor. Open source CapCut alternative. 100% browser-based, no installation, no cloud uploads, no watermarks.

TypeScript

feat: Dolby Digital delivery, spectral editing and desktop watch folders (#129)

Augustus Otu2b587a1a6f4a
diff --git a/apps/desktop/package.json b/apps/desktop/package.json
index df8824b0..174c1ad2 100644
--- a/apps/desktop/package.json
+++ b/apps/desktop/package.json
@@ -37,7 +37,8 @@
"fetch:ffmpeg": "node scripts/fetch-ffmpeg.mjs",
"prepare:aurora": "node scripts/prepare-aurora-native.mjs",
"pack": "pnpm run fetch:ffmpeg && pnpm run build && electron-builder --dir",
- "dist": "pnpm run fetch:ffmpeg && pnpm run build && electron-builder"
+ "dist": "pnpm run fetch:ffmpeg && pnpm run build && electron-builder",
+ "test:watch-e2e": "OPENREEL_DESKTOP_WATCH_E2E=1 vitest run test/watch-folders-electron.test.ts test/watch-folders-project-electron.test.ts"
},
"dependencies": {
"electron-updater": "^6.3.9",
diff --git a/apps/desktop/src/main/index.ts b/apps/desktop/src/main/index.ts
index d1cfa0e5..fb79a1d6 100644
--- a/apps/desktop/src/main/index.ts
+++ b/apps/desktop/src/main/index.ts
@@ -21,6 +21,7 @@ import {
cancelAllExports,
copyExportRun,
} from "./ipc/export";
+import { encodeDolbyAudio } from "./ipc/dolby-audio";
import {
cancelAuroraPreviewSession,
cancelAuroraSequenceSession,
@@ -77,6 +78,7 @@ import {
} from "./ipc/media";
import { fetchUrl } from "./ipc/fetch-url";
import { registerIngestIpc, startIngestQueue, stopIngestQueue } from "./ingest/ipc";
+import { registerWatchFoldersIpc, startWatchFolders, stopWatchFolders } from "./watch/ipc";
import { probeRiggingBackend, rigHumanoidModel } from "./sidecar/rigging-backend";
import { disposeAuroraClient } from "./aurora/client";
import {
@@ -87,6 +89,7 @@ import {
proxyArgsSchema,
transcodeArgsSchema,
extractAudioArgsSchema,
+ encodeDolbyAudioArgsSchema,
probeAudioArgsSchema,
developRawStillArgsSchema,
fetchUrlArgsSchema,
@@ -314,6 +317,7 @@ app.whenReady().then(() => {
});
mark("ipc-fs-registered");
registerIngestIpc();
+ registerWatchFoldersIpc();
handle(CHANNELS.mediaGenerateProxy, proxyArgsSchema, generateProxy);
handle(CHANNELS.mediaTranscode, transcodeArgsSchema, transcode);
handle(CHANNELS.mediaExtractAudioWav, extractAudioArgsSchema, extractAudioWav);
@@ -398,6 +402,7 @@ app.whenReady().then(() => {
writeAudioChunk,
);
handle(CHANNELS.exportFinishAudio, z.object({ jobId: z.string() }), finishAudio);
+ handle(CHANNELS.exportEncodeDolbyAudio, encodeDolbyAudioArgsSchema, encodeDolbyAudio);
handle(CHANNELS.exportCancel, z.object({ jobId: z.string() }), cancelExport);
handle(CHANNELS.exportProbeSource, z.object({ path: z.string().min(1) }), ({ path: p }) => probeSource(p));
handle(
@@ -454,6 +459,8 @@ app.whenReady().then(() => {
mark("ipc-registered");
startIngestQueue();
mark("ingest-queue");
+ // Watch folders start a moment after launch so scanning never competes with the first paint.
+ setTimeout(() => startWatchFolders(), 1500);
// Drop temp files left by crashed sessions; never blocks startup.
void sweepStaleTemp().catch(() => undefined);
startMcpServer().catch((error) =>
@@ -512,6 +519,7 @@ app.on("will-quit", () => {
nativeDecodeService().dispose();
cancelAllExports();
stopIngestQueue();
+ stopWatchFolders();
cleanupTempOnQuit();
void stopMcpServer();
});
diff --git a/apps/desktop/src/main/ipc/dolby-audio.ts b/apps/desktop/src/main/ipc/dolby-audio.ts
new file mode 100644
index 00000000..e23b7b39
--- /dev/null
+++ b/apps/desktop/src/main/ipc/dolby-audio.ts
@@ -0,0 +1,21 @@
+import { promises as fs } from "node:fs";
+import { MediaJob } from "../sidecar/media-job";
+import { buildDolbyStreamArgs, type DolbyAudioPlan } from "../sidecar/dolby-args";
+import { newTempPathReady, releaseTemp } from "../temp-dir";
+
+/**
+ * Audio-only Dolby export: the renderer's mixdown arrives as a WAV (L R C LFE Ls Rs for 5.1) and leaves as a raw
+ * AC-3 / E-AC-3 elementary stream, encoded by the ffmpeg sidecar. The temp files are removed on every outcome.
+ */
+export async function encodeDolbyAudio(args: DolbyAudioPlan & { wav: ArrayBuffer }): Promise<ArrayBuffer> {
+ const input = await newTempPathReady("openreel-dolby-in", "wav");
+ const output = await newTempPathReady("openreel-dolby-out", args.codec === "eac3" ? "ec3" : "ac3");
+ try {
+ await fs.writeFile(input, Buffer.from(args.wav));
+ await new MediaJob(buildDolbyStreamArgs(input, output, args)).run();
+ const bytes = await fs.readFile(output);
+ return bytes.buffer.slice(bytes.byteOffset, bytes.byteOffset + bytes.byteLength) as ArrayBuffer;
+ } finally {
+ await Promise.allSettled([releaseTemp(input), releaseTemp(output)]);
+ }
+}
diff --git a/apps/desktop/src/main/ipc/export.ts b/apps/desktop/src/main/ipc/export.ts
index 266e7c87..6ac9520c 100644
--- a/apps/desktop/src/main/ipc/export.ts
+++ b/apps/desktop/src/main/ipc/export.ts
@@ -13,6 +13,8 @@ import { resolveEncoderChoice, type EncoderChoice } from "../../../../../package
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";
+import { dolbyPlanFromRequest } from "../sidecar/dolby-args";
+import { dolbyContainerProblem } from "../../../../../packages/core/src/export/dolby";
import { isNativeColorOutput, type NativeColorOutput } from "../sidecar/color-output-args";
interface ExportStartArgs {
@@ -40,6 +42,10 @@ interface ExportStartArgs {
alpha?: boolean;
keyframeInterval?: number;
audioBitrateKbps?: number;
+ /** "ac3" (Dolby Digital) / "eac3" (Dolby Digital Plus): the audio track's codec instead of AAC / Opus / PCM. MP4, MOV or MKV. */
+ audioCodec?: string;
+ /** AC-3 / E-AC-3 dialogue normalisation, dB, -31 to -1. */
+ dialnorm?: number;
/** Broadcast delivery: interlaced (1080i) flags for XDCAM HD422 / AVC-Intra 100. */
scan?: BroadcastScan;
/** MXF wrapper: "op1a" (default) or "opatom" (one file per essence track). */
@@ -243,6 +249,9 @@ export function resolveExportArgs(
if (color) throw new Error("XDCAM HD422 and AVC-Intra 100 are Rec.709 deliveries; set the sequence colour space to Rec.709.");
if (args.format !== "mxf" && args.format !== "mov") throw new Error("XDCAM HD422 and AVC-Intra 100 are delivered in MXF or MOV.");
}
+ if (args.format === "mkv" && (codec === "prores" || codec === "dnxhr" || isBroadcastExportCodec(codec))) {
+ throw new Error("ProRes, DNxHR, XDCAM HD422 and AVC-Intra are delivered in MOV or MXF, not MKV. Choose H.264, H.265, AV1 or VP9 for MKV.");
+ }
const broadcastEncoder = codec === "xdcamhd422" ? "mpeg2video" : codec === "avcintra100" ? "libx264" : null;
if (broadcastEncoder && !usable.includes(broadcastEncoder)) {
throw new Error(
@@ -278,6 +287,13 @@ export function resolveExportArgs(
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";
+ const dolby = dolbyPlanFromRequest(args);
+ if (dolby) {
+ const containerProblem = dolbyContainerProblem(args.format);
+ if (containerProblem) throw new Error(containerProblem);
+ if (args.audioTrackCount !== undefined) throw new Error("Dolby Digital audio is a stereo or 5.1 track; it cannot be combined with mono audio tracks.");
+ if (!usable.includes(dolby.codec)) throw new Error(`This ffmpeg build has no ${dolby.codec} encoder, which Dolby Digital delivery needs.`);
+ }
return {
...(color ? { color } : {}),
width: args.width,
@@ -300,6 +316,7 @@ export function resolveExportArgs(
alpha: needs4444 && args.alpha === true,
keyframeInterval: args.keyframeInterval,
audioBitrateKbps: args.audioBitrateKbps,
+ ...(dolby ? { dolby } : {}),
...broadcastExportFields(args),
};
}
@@ -636,9 +653,9 @@ function handleSmartMessage(
.then(async () => {
if (entry.cancelled) return;
entry.finishDelivered = true;
- const { outputPath, audioWavPath, audioBitrateKbps, format, captionInputs, startTimecode } = entry.exportArgs;
+ const { outputPath, audioWavPath, audioBitrateKbps, dolby, format, captionInputs, startTimecode } = entry.exportArgs;
await smart.assemble(
- { audioWavPath, outputPath, audioCodec: "aac", audioBitrateKbps, format, captionInputs, startTimecode },
+ { audioWavPath, outputPath, audioCodec: "aac", audioBitrateKbps, dolby, format, captionInputs, startTimecode },
(frame) => entry.port.postMessage({ type: "progress", frame }),
);
entry.port.postMessage({ type: "done" });
diff --git a/apps/desktop/src/main/mcp/dispatcher.ts b/apps/desktop/src/main/mcp/dispatcher.ts
index 171d8eab..54b79ffb 100644
--- a/apps/desktop/src/main/mcp/dispatcher.ts
+++ b/apps/desktop/src/main/mcp/dispatcher.ts
@@ -32,7 +32,7 @@ interface DispatcherOptions {
export interface Dispatcher {
request(
kind: BridgeRequest["kind"],
- payload?: { name?: string; args?: Record<string, unknown> },
+ payload?: { name?: string; args?: Record<string, unknown>; origin?: BridgeRequest["origin"] },
timeoutMs?: number,
): Promise<unknown>;
handleResponse(response: BridgeResponse): void;
@@ -51,7 +51,7 @@ export function createDispatcher(options: DispatcherOptions): Dispatcher {
const request = (
kind: BridgeRequest["kind"],
- payload: { name?: string; args?: Record<string, unknown> } = {},
+ payload: { name?: string; args?: Record<string, unknown>; origin?: BridgeRequest["origin"] } = {},
timeoutMs = defaultTimeoutMs,
): Promise<unknown> => {
const callId = genId();
diff --git a/apps/desktop/src/main/mcp/policy.ts b/apps/desktop/src/main/mcp/policy.ts
index 6af07705..6ec32a63 100644
--- a/apps/desktop/src/main/mcp/policy.ts
+++ b/apps/desktop/src/main/mcp/policy.ts
@@ -24,6 +24,7 @@ export interface PolicyEnv {
export class McpPolicyStore {
private allowed: string[] | null = null;
private projectFolder: string | null = null;
+ private watchRoots: string[] = [];
constructor(private readonly env: PolicyEnv) {}
@@ -61,10 +62,20 @@ export class McpPolicyStore {
this.projectFolder = dir && path.isAbsolute(dir) ? path.resolve(dir) : null;
}
- /** What path checks use: the configured roots plus the open project's folder. */
+ /**
+ * Folders the user set up as watch folders (and the output folders of export watch folders). The
+ * app reads from and writes to them on the user's behalf, so path checks accept them too. Not
+ * persisted here: the watch-folder config owns the list.
+ */
+ setWatchRoots(dirs: readonly string[]): void {
+ this.watchRoots = normalizeRoots(dirs);
+ }
+
+ /** What path checks use: the configured roots, the open project's folder and the watch folders. */
effectiveRoots(): string[] {
const roots = [...this.load()];
if (this.projectFolder && !roots.includes(this.projectFolder)) roots.push(this.projectFolder);
+ for (const root of this.watchRoots) if (!roots.includes(root)) roots.push(root);
return roots;
}
}
diff --git a/apps/desktop/src/main/mcp/renderer-bridge.ts b/apps/desktop/src/main/mcp/renderer-bridge.ts
index c26c81de..c55b3113 100644
--- a/apps/desktop/src/main/mcp/renderer-bridge.ts
+++ b/apps/desktop/src/main/mcp/renderer-bridge.ts
@@ -126,6 +126,24 @@ export function installRendererBridge(): McpToolProvider {
};
}
+/**
+ * Tool calls for watch folders. They carry `origin: "watch-folders"` so the renderer runs them without
+ * the agent confirmation gate (the folders are set up by the user in Settings).
+ */
+export function createWatchFolderToolCaller(): {
+ hasEditor(): boolean;
+ call(name: string, args: Record<string, unknown>): Promise<McpToolResult>;
+} {
+ installRendererBridge();
+ return {
+ hasEditor: () => getEditorWindow() !== null,
+ async call(name, args) {
+ const result = await bridge!.request("callTool", { name, args, origin: "watch-folders" }, LONG_RUNNING_TIMEOUT_MS);
+ return result as McpToolResult;
+ },
+ };
+}
+
/** Number of requests waiting for the renderer. Exposed for tests and diagnostics. */
export function queuedRequestCount(): number {
return queued.length;
diff --git a/apps/desktop/src/main/sidecar/dolby-args.ts b/apps/desktop/src/main/sidecar/dolby-args.ts
new file mode 100644
index 00000000..075bb0ac
--- /dev/null
+++ b/apps/desktop/src/main/sidecar/dolby-args.ts
@@ -0,0 +1,65 @@
+import {
+ clampDolbyBitrate,
+ dolbyEncodeArgs,
+ dolbyRawMuxer,
+ isDolbyFormat,
+ resolveDolbyAudioSettings,
+ type DolbyCodec,
+ type DolbyEncodeParams,
+} from "../../../../../packages/core/src/export/dolby";
+
+export type { DolbyCodec, DolbyEncodeParams };
+
+/** The Dolby audio of a video export, as the start request carries it. */
+export interface DolbyAudioPlan {
+ codec: DolbyCodec;
+ channels: number;
+ bitrateKbps: number;
+ sampleRate: number;
+ dialnorm: number;
+}
+
+/** A Dolby plan from the export request's audio fields, or null when the audio is not Dolby. Throws on settings Dolby cannot carry. */
+export function dolbyPlanFromRequest(request: {
+ audioCodec?: string;
+ audioChannels: number;
+ audioSampleRate: number;
+ audioBitrateKbps?: number;
+ dialnorm?: number;
+}): DolbyAudioPlan | null {
+ if (request.audioCodec === undefined) return null;
+ if (!isDolbyFormat(request.audioCodec)) throw new Error(`Unknown audio codec "${request.audioCodec}".`);
+ if (request.audioChannels !== 2 && request.audioChannels !== 6) throw new Error("Dolby Digital delivery is stereo or 5.1.");
+ const resolved = resolveDolbyAudioSettings({
+ format: request.audioCodec,
+ sampleRate: request.audioSampleRate as 48000,
+ bitDepth: 16,
+ bitrate: request.audioBitrateKbps ?? 0,
+ channels: request.audioChannels,
+ dialnorm: request.dialnorm,
+ });
+ return {
+ codec: request.audioCodec,
+ channels: request.audioChannels,
+ bitrateKbps: resolved.bitrate,
+ sampleRate: resolved.sampleRate,
+ dialnorm: resolved.dialnorm ?? -31,
+ };
+}
+
+/** `-c:a ac3|eac3` and its options for the audio track of a video export. */
+export function dolbyTrackArgs(plan: DolbyAudioPlan): string[] {
+ return dolbyEncodeArgs(plan);
+}
+
+/** A whole audio-only job: WAV in, raw `.ac3` / `.ec3` elementary stream out. */
+export function buildDolbyStreamArgs(inputPath: string, outputPath: string, plan: DolbyAudioPlan): string[] {
+ return [
+ "-y",
+ "-i", inputPath,
+ "-vn",
+ ...dolbyTrackArgs({ ...plan, bitrateKbps: clampDolbyBitrate(plan.codec, plan.bitrateKbps) }),
+ "-f", dolbyRawMuxer(plan.codec),
+ outputPath,
+ ];
+}
diff --git a/apps/desktop/src/main/sidecar/export-job.ts b/apps/desktop/src/main/sidecar/export-job.ts
index dee55661..56d0cdfc 100644
--- a/apps/desktop/src/main/sidecar/export-job.ts
+++ b/apps/desktop/src/main/sidecar/export-job.ts
@@ -4,6 +4,7 @@ import { join } from "node:path";
import { spawn, type ChildProcessWithoutNullStreams } from "node:child_process";
import { resolveFfmpegPath } from "./ffmpeg-path";
import { isBroadcastExportCodec, supportsTwoPass, videoEncodeArgs, withTopFieldFirst, type BroadcastScan, type DnxhrProfile, type EncodeMode, type ExportCodec } from "./encode-args";
+import { dolbyTrackArgs, type DolbyAudioPlan } from "./dolby-args";
import { colorFilterArgs, colorTagArgs, rawInputPixelFormat, type NativeColorOutput } from "./color-output-args";
export interface ExportArgs {
@@ -31,6 +32,8 @@ export interface ExportArgs {
/** ProRes 4444: keep the render's alpha channel. */
alpha?: boolean;
audioBitrateKbps?: number;
+ /** Dolby Digital / Digital Plus audio track (MP4, MOV or MKV) instead of AAC / Opus / PCM. */
+ dolby?: DolbyAudioPlan;
keyframeInterval?: number;
/**
* Colour-managed export: the pipe carries raw planar YCbCr already converted
@@ -69,7 +72,8 @@ export function parseProgressBlock(block: string): { frame: number; done: boolea
}
/** Containers whose delivery specs call for uncompressed PCM audio (MXF requires it; ProRes / DNxHR masters carry it). */
-export function usesPcmAudio(a: Pick<ExportArgs, "format" | "codec">): boolean {
+export function usesPcmAudio(a: Pick<ExportArgs, "format" | "codec"> & { dolby?: unknown }): boolean {
+ if (a.dolby) return false;
return a.format === "mxf" || a.codec === "prores" || a.codec === "dnxhr" || isBroadcastExportCodec(a.codec);
}
@@ -107,12 +111,14 @@ export function monoSplitFilter(count: number): string {
// WebM only accepts VP8/VP9/AV1 video with Opus/Vorbis audio.
function audioCodecFor(a: ExportArgs): string {
+ if (a.dolby) return a.dolby.codec;
if (usesPcmAudio(a)) return "pcm_s24le";
return a.format === "webm" || a.codec === "vp9" ? "libopus" : "aac";
}
/** The `-f` muxer to force: MXF is not reliably guessed from the output name, so it is always explicit. */
export function explicitMuxerArgs(format: string): string[] {
+ if (format === "mkv") return ["-f", "matroska"];
return format === "mxf" ? ["-f", "mxf"] : [];
}
@@ -284,10 +290,15 @@ export function buildFfmpegArgs(a: ExportArgs, stage: "single" | "pass2" = "sing
...withTopFieldFirst(a.color ? colorFilterArgs(a.color) : [...COLOR_PIPELINE_ARGS], planOf(a)),
...videoEncodeArgs(pass2 ? { ...planOf(a), pass: { stage: 2, logPrefix: passLogPrefix(a) } } : planOf(a)),
...(a.color ? colorTagArgs(a.color) : []),
- "-c:a", audioCodecFor(a),
- ...(a.audioBitrateKbps !== undefined && !usesPcmAudio(a)
- ? ["-b:a", `${clampAudioBitrateKbps(a.audioBitrateKbps)}k`]
- : []),
+ ...(a.dolby
+ // ac3 / eac3 with the 5.1 relabel, bitrate, sample rate and dialnorm (shared with the audio-only export).
+ ? dolbyTrackArgs(a.dolby)
+ : [
+ "-c:a", audioCodecFor(a),
+ ...(a.audioBitrateKbps !== undefined && !usesPcmAudio(a)
+ ? ["-b:a", `${clampAudioBitrateKbps(a.audioBitrateKbps)}k`]
+ : []),
+ ]),
...(a.format === "mp4" || a.format === "mov" ? ["-movflags", "+faststart"] : []),
...timecodeArgs(a),
...explicitMuxerArgs(a.format),
diff --git a/apps/desktop/src/main/sidecar/smart-export.ts b/apps/desktop/src/main/sidecar/smart-export.ts
index 772d7eba..852bae2f 100644
--- a/apps/desktop/src/main/sidecar/smart-export.ts
+++ b/apps/desktop/src/main/sidecar/smart-export.ts
@@ -11,6 +11,7 @@
* transport streams is a valid concatenation. One last stream-copy pass muxes
* that video with the re-rendered audio into the MP4/MOV.
*/
+import { dolbyTrackArgs, type DolbyAudioPlan } from "./dolby-args";
import { spawn, type ChildProcess } from "node:child_process";
import { createWriteStream, type WriteStream } from "node:fs";
import { promises as fs } from "node:fs";
@@ -277,6 +278,8 @@ export interface AssembleArgs {
concatList?: boolean;
audioCodec: string;
audioBitrateKbps?: number;
+ /** Dolby Digital / Digital Plus audio instead of `audioCodec`. */
+ dolby?: DolbyAudioPlan;
format: string;
captionInputs?: ExportArgs["captionInputs"];
/** MOV only: start timecode written as a timecode track. */
@@ -295,8 +298,12 @@ export function buildAssembleArgs(a: AssembleArgs): string[] {
...(captions.outputs.length ? captions.outputs : ["-map", "0:v:0", "-map", "1:a:0"]),
"-c:v", "copy",
...(a.codec === "hevc" ? ["-tag:v", "hvc1"] : []),
- "-c:a", a.audioCodec,
- ...(a.audioBitrateKbps !== undefined ? ["-b:a", `${Math.max(32, Math.min(512, Math.round(a.audioBitrateKbps)))}k`] : []),
+ ...(a.dolby
+ ? dolbyTrackArgs(a.dolby)
+ : [
+ "-c:a", a.audioCodec,
+ ...(a.audioBitrateKbps !== undefined ? ["-b:a", `${Math.max(32, Math.min(512, Math.round(a.audioBitrateKbps)))}k`] : []),
+ ]),
"-video_track_timescale", String(videoTrackTimescale(a.frameRate)),
...(a.startTimecode && a.format === "mov" ? ["-timecode", a.startTimecode] : []),
"-movflags", "+faststart",
diff --git a/apps/desktop/src/main/watch/editor-handlers.ts b/apps/desktop/src/main/watch/editor-handlers.ts
new file mode 100644
index 00000000..0e22e354
--- /dev/null
+++ b/apps/desktop/src/main/watch/editor-handlers.ts
@@ -0,0 +1,186 @@
+import fs from "node:fs";
+import path from "node:path";
+import type { WatchExportPresetId } from "../../shared/watch-folders";
+import { WATCH_PRESETS, extensionOf, isWatchPresetId, uniquePath } from "./render";
+import type { FolderContext, IngestOutcome } from "./manager";
+
+/**
+ * The parts of watch folders that run through the editor window: ingest (import into the open project)
+ * and project-file export (the editor's export queue). Both call the same agent tools the MCP server
+ * exposes, so imports are undoable actions in the open project and exports use the real export queue.
+ */
+
+export interface ToolResultLike {
+ ok: boolean;
+ summary?: string;
+ data?: unknown;
+ error?: { code?: string; message?: string; hint?: string };
+}
+
+export interface ToolCaller {
+ /** True when an editor window exists (no window is created just to look). */
+ hasEditor(): boolean;
+ call(name: string, args: Record<string, unknown>): Promise<ToolResultLike>;
+}
+
+const asRecord = (value: unknown): Record<string, unknown> => (value && typeof value === "object" ? (value as Record<string, unknown>) : {});
+const failureText = (result: ToolResultLike): string => result.error?.message ?? result.summary ?? "The editor refused the request.";
+const noProject = (result: ToolResultLike): boolean => result.error?.code === "NO_PROJECT";
+
+/** Finds the bin by name (case-insensitive) or creates it. Returns the bin id, or null when no project is open. */
+export async function ensureBin(caller: ToolCaller, name: string): Promise<string | null> {
+ const listed = await caller.call("list_bins", {});
+ if (!listed.ok) {
+ if (noProject(listed)) return null;
+ throw new Error(failureText(listed));
+ }
+ const bins = (asRecord(listed.data).bins as Array<Record<string, unknown>> | undefined) ?? [];
+ const wanted = name.trim().toLowerCase();
+ const match = bins.find((bin) => typeof bin.name === "string" && bin.name.toLowerCase() === wanted && !bin.parentId);
+ if (match && typeof match.id === "string") return match.id;
+ const created = await caller.call("create_bin", { name: name.trim() });
+ if (!created.ok) {
+ if (noProject(created)) return null;
+ throw new Error(failureText(created));
+ }
+ const id = asRecord(created.data).binId;
+ if (typeof id !== "string") throw new Error("The editor did not report the new bin.");
+ return id;
+}
+
+export async function ingestIntoOpenProject(caller: ToolCaller, context: FolderContext): Promise<IngestOutcome> {
+ const { folder, file } = context;
+ if (!caller.hasEditor()) return { outcome: "waiting", detail: "Waiting for the editor window" };
+ let binId: string | null | undefined;
+ if (folder.bin.trim()) {
+ binId = await ensureBin(caller, folder.bin);
+ if (binId === null) return { outcome: "waiting", detail: "Waiting for a project to be open" };
+ }
+ const result = await caller.call("import_media_from_path", {
+ paths: [file.path],
+ ...(binId ? { bin: binId } : {}),
+ ...(folder.createProxies ? { createProxies: true } : {}),
+ });
+ if (!result.ok) {
+ if (noProject(result)) return { outcome: "waiting", detail: "Waiting for a project to be open" };
+ throw new Error(failureText(result));
+ }
+ const imported = (asRecord(result.data).imported as unknown[] | undefined) ?? [];
+ if (imported.length === 0) throw new Error("The editor did not import the file.");
+ const where = folder.bin.trim() ? ` into "${folder.bin.trim()}"` : "";
+ return { outcome: "imported", detail: `Imported${where}${folder.createProxies ? " (proxies queued)" : ""}` };
+}
+
+/** Directories of the media paths a project file records (tolerant of the file's wrapper shape). */
+export function recordedMediaDirs(content: string): string[] {
+ let root: unknown;
+ try {
+ root = JSON.parse(content);
+ } catch {
+ return [];
+ }
+ const dirs = new Set<string>();
+ const visit = (node: unknown, depth: number): void => {
+ if (!node || typeof node !== "object" || depth > 12) return;
+ if (Array.isArray(node)) {
+ for (const entry of node) visit(entry, depth + 1);
+ return;
+ }
+ const record = node as Record<string, unknown>;
+ const source = record.sourceFile;
+ if (source && typeof source === "object") {
+ const p = (source as Record<string, unknown>).path;
+ if (typeof p === "string" && path.isAbsolute(p)) dirs.add(path.dirname(p));
+ }
+ for (const value of Object.values(record)) visit(value, depth + 1);
+ };
+ visit(root, 0);
+ return [...dirs];
+}
+
+/**
+ * A reopened project has its media offline (the file stores references, not the footage). Searches the
+ * folders the project recorded and the folder the project file sits in, so footage dropped beside the
+ * project is found too. Best effort: anything still offline is reported by the export itself.
+ */
+async function relinkOfflineMedia(caller: ToolCaller, projectPath: string): Promise<void> {
+ const folders: string[] = [];
+ try {
+ folders.push(...recordedMediaDirs(await fs.promises.readFile(projectPath, "utf8")));
+ } catch {
+ /* unreadable here: the editor already opened it */
+ }
+ folders.push(path.dirname(projectPath));
+ for (const folder of [...new Set(folders)]) {
+ await caller.call("relink_media", { folder }).catch(() => undefined);
+ }
+}
+
+export interface ProjectRenderDeps {
+ sleep(ms: number): Promise<void>;
+ pollMs: number;
+ timeoutMs: number;
+}
+
+const defaultProjectDeps: ProjectRenderDeps = { sleep: (ms) => new Promise((resolve) => setTimeout(resolve, ms)), pollMs: 1000, timeoutMs: 6 * 60 * 60 * 1000 };
+
+/**
+ * Renders a `.oreel` / `.openreel` project through the editor's export queue: open it in the editor
+ * (the project that was open is saved first), queue an export with the folder's preset, and wait for the
+ * queue job. The output lands in the folder's output directory.
+ */
+export async function renderProjectViaEditor(
+ caller: ToolCaller,
+ context: FolderContext & { onProgress(fraction: number | null): void },
+ deps: ProjectRenderDeps = defaultProjectDeps,
+): Promise<{ outputPath: string }> {
+ const { folder, file, signal } = context;
+ if (!isWatchPresetId(folder.presetId) || WATCH_PRESETS[folder.presetId as WatchExportPresetId].kind !== "video") {
+ throw new Error("Project files need a video preset; the audio-only preset cannot render a project.");
+ }
+ const opened = await caller.call("open_project_file", { path: file.path });
+ if (!opened.ok) throw new Error(failureText(opened));
+ const base = path.basename(file.path, `.${extensionOf(file.path)}`);
+ // The editor's export path guard requires an existing destination folder.
+ await fs.promises.mkdir(folder.outputDir, { recursive: true });
+ const outputPath = uniquePath(folder.outputDir, base, "mp4");
+ const runExport = async (): Promise<{ outputPath: string }> => {
+ const queued = await caller.call("queue_export", { presetId: folder.presetId, outputPath, overwrite: false, start: true });
+ if (!queued.ok) throw new Error(failureText(queued));
+ const jobId = asRecord(queued.data).jobId;
+ if (typeof jobId !== "string") throw new Error("The editor did not report the export job.");
+ const deadline = Date.now() + deps.timeoutMs;
+ for (;;) {
+ if (signal.aborted) {
+ await caller.call("cancel_export_job", { jobId }).catch(() => undefined);
+ throw new Error("Cancelled");
+ }
+ if (Date.now() > deadline) throw new Error("The export did not finish in time.");
+ const listed = await caller.call("list_export_jobs", {});
+ const jobs = (asRecord(listed.data).jobs as Array<Record<string, unknown>> | undefined) ?? [];
+ const job = jobs.find((entry) => entry.id === jobId);
+ if (!job) throw new Error("The export job disappeared from the queue.");
+ if (typeof job.progress === "number") context.onProgress(job.progress);
+ if (job.status === "completed") {
+ const placed = typeof job.outputPath === "string" ? job.outputPath : outputPath;
+ return { outputPath: placed };
+ }
+ if (job.status === "failed" || job.status === "cancelled" || job.status === "interrupted") {
+ throw new Error(typeof job.error === "string" && job.error ? job.error : `The export ${String(job.status)}.`);
+ }
+ await deps.sleep(deps.pollMs);
+ }
+ };
+ // A reopened project has its media offline (the file stores references, not the footage). The editor
+ // reconnects remembered paths on its own; the folders searched on the second try cover the rest. The
+ // export itself reports offline media, so retry only on that and let anything else fail at once.
+ for (let attempt = 0; ; attempt++) {
+ try {
+ return await runExport();
+ } catch (error) {
+ if (attempt >= 4 || !/relink the original media/i.test(error instanceof Error ? error.message : "")) throw error;
+ if (attempt === 1) await relinkOfflineMedia(caller, file.path);
+ await deps.sleep(deps.pollMs * 2);
+ }
+ }
+}
diff --git a/apps/desktop/src/main/watch/folder-scanner.ts b/apps/desktop/src/main/watch/folder-scanner.ts
new file mode 100644
index 00000000..fd1abc65
--- /dev/null
+++ b/apps/desktop/src/main/watch/folder-scanner.ts
@@ -0,0 +1,256 @@
+import fs, { type FSWatcher } from "node:fs";
+import path from "node:path";
+
+/**
+ * Watches ONE folder (non-recursive) and reports each file once it has stopped growing.
+ *
+ * Detection is fs.watch (debounced) with a slow periodic rescan behind it, because fs.watch drops
+ * events on network shares and some editors' save patterns. A file is "ready" only after its size and
+ * mtime have been unchanged for `settleMs` and it can be opened for reading, so a copy or a download
+ * that is still being written is never handed on. Files that change after they were reported are
+ * reported again (a new version).
+ */
+
+export interface ScanFile {
+ path: string;
+ name: string;
+ size: number;
+ mtimeMs: number;
+}
+
+export interface ScannerFs {
+ readdir(dir: string): Promise<Array<{ name: string; isFile: boolean }>>;
+ stat(file: string): Promise<{ size: number; mtimeMs: number } | null>;
+ canRead(file: string): Promise<boolean>;
+ watch(dir: string, onChange: () => void): { close(): void } | null;
+}
+
+export interface ScannerOptions {
+ /** How long size and mtime must stay unchanged before a file counts as fully written. */
+ settleMs: number;
+ /** How often files still settling are re-checked. */
+ pollMs: number;
+ /** Backstop rescan for missed fs.watch events. */
+ rescanMs: number;
+ /** Collapses bursts of fs.watch events into one scan. */
+ debounceMs: number;
+ now?: () => number;
+}
+
+export const DEFAULT_SCANNER_OPTIONS: ScannerOptions = { settleMs: 2500, pollMs: 700, rescanMs: 5000, debounceMs: 250 };
+
+const PARTIAL_SUFFIXES = [".part", ".partial", ".crdownload", ".download", ".tmp", ".temp", ".filepart", ".aria2", ".swp", ".lock", ".opdownload", ".!qb", "~"];
+const JUNK_NAMES = new Set(["thumbs.db", "desktop.ini", "ehthumbs.db"]);
+
+/** Hidden files, OS droppings and the temporary names downloads and copy tools use for unfinished files. */
+export function isIgnoredName(name: string): boolean {
+ if (!name || name.startsWith(".") || name.startsWith("~$")) return true;
+ const lower = name.toLowerCase();
+ return JUNK_NAMES.has(lower) || PARTIAL_SUFFIXES.some((suffix) => lower.endsWith(suffix));
+}
+
+export const nodeScannerFs: ScannerFs = {
+ async readdir(dir) {
+ const entries = await fs.promises.readdir(dir, { withFileTypes: true });
+ return entries.map((entry) => ({ name: entry.name, isFile: entry.isFile() || entry.isSymbolicLink() }));
+ },
+ async stat(file) {
+ try {
+ const stat = await fs.promises.stat(file);
+ return stat.isFile() ? { size: stat.size, mtimeMs: stat.mtimeMs } : null;
+ } catch {
+ return null;
+ }
+ },
+ async canRead(file) {
+ try {
+ const handle = await fs.promises.open(file, "r");
+ await handle.close();
+ return true;
+ } catch {
+ return false;
+ }
+ },
+ watch(dir, onChange) {
+ try {
+ const watcher: FSWatcher = fs.watch(dir, { persistent: false }, () => onChange());
+ watcher.on("error", () => undefined);
+ return watcher;
+ } catch {
+ return null;
+ }
+ },
+};
+
+interface Pending {
+ size: number;
+ mtimeMs: number;
+ stableSince: number;
+}
+
+export interface ScannerEvents {
+ /** A file appeared (or changed) and is being watched until it stops growing. */
+ onSeen?(file: ScanFile): void;
+ /** A file that was settling disappeared before it finished. */
+ onGone?(file: string): void;
+ /** The file is complete. Called once per version (size + mtime). */
+ onReady(file: ScanFile): void;
+ /** The folder cannot be read (deleted, unplugged, permission). Cleared by `onReadable`. */
+ onUnreadable?(error: NodeJS.ErrnoException): void;
+ onReadable?(): void;
+}
+
+export class FolderScanner {
+ private readonly pending = new Map<string, Pending>();
+ /** Versions already reported: path -> "size:mtime". */
+ private readonly reported = new Map<string, string>();
+ private watcher: { close(): void } | null = null;
+ private debounce: ReturnType<typeof setTimeout> | null = null;
+ private rescan: ReturnType<typeof setInterval> | null = null;
+ private poll: ReturnType<typeof setTimeout> | null = null;
+ private scanning: Promise<void> | null = null;
+ private again = false;
+ private stopped = true;
+ private unreadable = false;
+
+ constructor(
+ readonly dir: string,
+ private readonly events: ScannerEvents,
+ private readonly options: ScannerOptions = DEFAULT_SCANNER_OPTIONS,
+ private readonly scannerFs: ScannerFs = nodeScannerFs,
+ ) {}
+
+ private now(): number {
+ return (this.options.now ?? Date.now)();
+ }
+
+ /** Marks versions that are already handled (a baseline or the ledger) so they are never reported. */
+ markReported(file: ScanFile): void {
+ this.reported.set(file.path, `${file.size}:${file.mtimeMs}`);
+ }
+
+ forget(filePath: string): void {
+ this.reported.delete(filePath);
+ this.pending.delete(filePath);
+ }
+
+ start(): void {
+ if (!this.stopped) return;
+ this.stopped = false;
+ this.watcher = this.scannerFs.watch(this.dir, () => this.schedule());
+ this.rescan = setInterval(() => void this.scan(), this.options.rescanMs);
+ this.rescan.unref?.();
+ void this.scan();
+ }
+
+ stop(): void {
+ this.stopped = true;
+ this.watcher?.close();
+ this.watcher = null;
+ if (this.debounce) clearTimeout(this.debounce);
+ if (this.poll) clearTimeout(this.poll);
+ if (this.rescan) clearInterval(this.rescan);
+ this.debounce = this.poll = this.rescan = null;
+ this.pending.clear();
+ }
+
+ private schedule(): void {
+ if (this.stopped || this.debounce) return;
+ this.debounce = setTimeout(() => {
+ this.debounce = null;
+ void this.scan();
+ }, this.options.debounceMs);
+ this.debounce.unref?.();
+ }
+
+ /** One pass over the folder; overlapping calls collapse into a single follow-up pass. */
+ scan(): Promise<void> {
+ if (this.stopped) return Promise.resolve();
+ if (this.scanning) {
+ this.again = true;
+ return this.scanning;
+ }
+ this.scanning = this.scanOnce().finally(() => {
+ this.scanning = null;
+ if (this.again && !this.stopped) {
+ this.again = false;
+ void this.scan();
+ }
+ });
+ return this.scanning;
+ }
+
+ private async scanOnce(): Promise<void> {
+ let entries: Array<{ name: string; isFile: boolean }>;
+ try {
+ entries = await this.scannerFs.readdir(this.dir);
+ } catch (error) {
+ if (!this.unreadable) {
+ this.unreadable = true;
+ this.events.onUnreadable?.(error as NodeJS.ErrnoException);
+ }
+ return;
+ }
+ if (this.unreadable) {
+ this.unreadable = false;
+ this.events.onReadable?.();
+ // The watch handle of a deleted-and-recreated folder is dead: re-arm it.
+ this.watcher?.close();
+ this.watcher = this.scannerFs.watch(this.dir, () => this.schedule());
+ }
+ const present = new Set<string>();
+ for (const entry of entries) {
+ if (!entry.isFile || isIgnoredName(entry.name)) continue;
+ const full = path.join(this.dir, entry.name);
+ present.add(full);
+ if (this.stopped) return;
+ const stat = await this.scannerFs.stat(full);
+ if (!stat) continue;
+ const version = `${stat.size}:${stat.mtimeMs}`;
+ if (this.reported.get(full) === version) continue;
+ const current = this.pending.get(full);
+ if (current && current.size === stat.size && current.mtimeMs === stat.mtimeMs) continue;
+ this.pending.set(full, { size: stat.size, mtimeMs: stat.mtimeMs, stableSince: this.now() });
+ this.events.onSeen?.({ path: full, name: entry.name, size: stat.size, mtimeMs: stat.mtimeMs });
+ }
+ for (const full of [...this.pending.keys()]) {
+ if (!present.has(full)) {
+ this.pending.delete(full);
+ this.events.onGone?.(full);
+ }
+ }
+ for (const full of [...this.reported.keys()]) if (!present.has(full)) this.reported.delete(full);
+ if (this.pending.size > 0) this.armPoll();
+ }
+
+ private armPoll(): void {
+ if (this.poll || this.stopped) return;
+ this.poll = setTimeout(() => {
+ this.poll = null;
+ void this.checkPending();
+ }, this.options.pollMs);
+ this.poll.unref?.();
+ }
+
+ private async checkPending(): Promise<void> {
+ for (const [full, entry] of [...this.pending]) {
+ if (this.stopped) return;
+ const stat = await this.scannerFs.stat(full);
+ if (!stat) {
+ this.pending.delete(full);
+ this.events.onGone?.(full);
+ continue;
+ }
+ if (stat.size !== entry.size || stat.mtimeMs !== entry.mtimeMs) {
+ this.pending.set(full, { size: stat.size, mtimeMs: stat.mtimeMs, stableSince: this.now() });
+ continue;
+ }
+ if (this.now() - entry.stableSince < this.options.settleMs || stat.size === 0) continue;
+ if (!(await this.scannerFs.canRead(full))) continue;
+ this.pending.delete(full);
+ this.reported.set(full, `${stat.size}:${stat.mtimeMs}`);
+ this.events.onReady({ path: full, name: path.basename(full), size: stat.size, mtimeMs: stat.mtimeMs });
+ }
+ if (this.pending.size > 0) this.armPoll();
+ }
+}
diff --git a/apps/desktop/src/main/watch/ipc.ts b/apps/desktop/src/main/watch/ipc.ts
new file mode 100644
index 00000000..087a5021
--- /dev/null
+++ b/apps/desktop/src/main/watch/ipc.ts
@@ -0,0 +1,174 @@
+import { app, BrowserWindow, dialog, type IpcMainInvokeEvent } from "electron";
+import fs from "node:fs";
+import path from "node:path";
+import { z } from "zod";
+import { CHANNELS } from "../../shared/channels";
+import {
+ WATCH_EXPORT_PRESET_IDS,
+ WATCH_FOLDER_KINDS,
+ watchFolderAddArgsSchema,
+ watchFolderIdArgsSchema,
+ watchFolderUpdateArgsSchema,
+ watchItemIdArgsSchema,
+ type WatchFolderConfig,
+ type WatchFoldersSnapshot,
+} from "../../shared/watch-folders";
+import { handle } from "../ipc";
+import { withNativeDialog } from "../native-dialog-state";
+import { getMcpPolicyStore } from "../mcp/policy";
+import { createWatchFolderToolCaller } from "../mcp/renderer-bridge";
+import { probeMediaFile } from "../ingest/probe-media";
+import { resolveFfmpegPath } from "../sidecar/ffmpeg-path";
+import { getBestH264Encoder, isHardwareEncoder } from "../sidecar/encoder-probe";
+import { ingestIntoOpenProject, renderProjectViaEditor } from "./editor-handlers";
+import { Ledger, createFileLedgerStore } from "./ledger";
+import { WatchFolderManager, type ConfigStore, type ManagerOptions } from "./manager";
+import { isWatchPresetId, renderMediaFile } from "./render";
+
+/** Electron wiring of the watch folders: persisted config and ledger in userData, IPC for the settings UI. */
+
+const configSchema = z.object({
+ id: z.string().min(1),
+ kind: z.enum(WATCH_FOLDER_KINDS),
+ path: z.string().min(1),
+ paused: z.boolean().default(false),
+ bin: z.string().default(""),
+ createProxies: z.boolean().default(false),
+ presetId: z.enum(WATCH_EXPORT_PRESET_IDS).default("1080p-high"),
+ outputDir: z.string().default(""),
+ includeProjects: z.boolean().default(false),
+ baselined: z.boolean().default(false),
+ processExisting: z.boolean().default(false),
+});
+
+export function createFileConfigStore(file: string): ConfigStore {
+ return {
+ load(): WatchFolderConfig[] {
+ try {
+ const parsed = JSON.parse(fs.readFileSync(file, "utf8")) as { version?: number; folders?: unknown };
+ if (parsed.version !== 1 || !Array.isArray(parsed.folders)) return [];
+ const out: WatchFolderConfig[] = [];
+ for (const entry of parsed.folders) {
+ const folder = configSchema.safeParse(entry);
+ if (!folder.success || !path.isAbsolute(folder.data.path)) continue;
+ if (folder.data.kind === "export" && !path.isAbsolute(folder.data.outputDir)) {
+ folder.data.outputDir = path.join(folder.data.path, "output");
+ }
+ out.push(folder.data);
+ }
+ return out;
+ } catch {
+ return [];
+ }
+ },
+ save(folders) {
+ try {
+ fs.mkdirSync(path.dirname(file), { recursive: true });
+ const tmp = `${file}.${process.pid}.tmp`;
+ fs.writeFileSync(tmp, JSON.stringify({ version: 1, folders }, null, 2));
+ fs.renameSync(tmp, file);
+ } catch {
+ // A read-only profile only loses the list across restarts.
+ }
+ },
+ };
+}
+
+let manager: WatchFolderManager | null = null;
+let ledger: Ledger | null = null;
+
+function broadcast(snapshot: WatchFoldersSnapshot): void {
+ for (const win of BrowserWindow.getAllWindows()) {
+ if (!win.isDestroyed()) win.webContents.send(CHANNELS.watchFoldersEvent, snapshot);
+ }
+}
+
+/** Test and e2e override for how long files must be stable (ms), so the suites do not wait seconds. */
+function optionsFromEnv(): Partial<ManagerOptions> {
+ const settle = Number(process.env.OPENREEL_WATCH_SETTLE_MS);
+ if (app.isPackaged || !Number.isFinite(settle) || settle <= 0) return {};
+ return { retryWaitMs: 1000, scanner: { settleMs: settle, pollMs: Math.max(50, Math.floor(settle / 3)), rescanMs: 1000, debounceMs: 100 } };
+}
+
+function getManager(): WatchFolderManager {
+ if (manager) return manager;
+ const userData = app.getPath("userData");
+ ledger = new Ledger(createFileLedgerStore(path.join(userData, "watch-folders-ledger.json")));
+ const caller = createWatchFolderToolCaller();
+ manager = new WatchFolderManager({
+ configStore: createFileConfigStore(path.join(userData, "watch-folders.json")),
+ ledger,
+ emit: broadcast,
+ onRoots: (roots) => getMcpPolicyStore().setWatchRoots(roots),
+ options: optionsFromEnv(),
+ handlers: {
+ ingest: (context) => ingestIntoOpenProject(caller, context),
+ renderMedia: ({ folder, file, onProgress, signal }) => {
+ if (!isWatchPresetId(folder.presetId)) return Promise.reject(new Error(`Unknown export preset "${folder.presetId}".`));
+ return renderMediaFile(
+ { src: file.path, presetId: folder.presetId, outputDir: folder.outputDir, onProgress, signal },
+ {
+ ffmpegPath: resolveFfmpegPath,
+ probe: async (src) => {
+ const probe = await probeMediaFile(src, signal);
+ if (!probe) throw new Error("ffmpeg could not read this file.");
+ return probe;
+ },
+ videoEncoder: () => getBestH264Encoder(),
+ isHardwareEncoder,
+ },
+ ).then((outputPath) => ({ outputPath }));
+ },
+ renderProject: (context) => renderProjectViaEditor(caller, context),
+ },
+ });
+ return manager;
+}
+
+/** Starts the watchers. Called shortly after launch (off the cold-start path). Safe to call twice. */
+export function startWatchFolders(): void {
+ getManager().start();
+}
+
+/** Quit: stop watching, abort running renders and flush the duplicate ledger. */
+export function stopWatchFolders(): void {
+ manager?.stop();
+ manager = null;
+ ledger = null;
+}
+
+/** Test hook. */
+export function watchFolderManagerForTests(): WatchFolderManager {
+ return getManager();
+}
+
+async function pickFolder(event: IpcMainInvokeEvent, title: string): Promise<string | null> {
+ const owner = BrowserWindow.fromWebContents(event.sender) ?? BrowserWindow.getFocusedWindow() ?? undefined;
+ const options = { title, properties: ["openDirectory", "createDirectory"] as Array<"openDirectory" | "createDirectory"> };
+ const res = await withNativeDialog(() => (owner ? dialog.showOpenDialog(owner, options) : dialog.showOpenDialog(options)));
+ return res.canceled || res.filePaths.length === 0 ? null : res.filePaths[0];
+}
+
+export function registerWatchFoldersIpc(): void {
+ handle(CHANNELS.watchFoldersList, z.undefined(), () => getManager().snapshot());
+ // The folder path only ever comes from the native dialog, never from the renderer: a compromised page
+ // cannot point a watch folder (which widens the file access of the import tools) at an arbitrary place.
+ handle(CHANNELS.watchFoldersAdd, watchFolderAddArgsSchema, async ({ kind }, event) => {
+ const picked = await pickFolder(event, kind === "ingest" ? "Choose a folder to import media from" : "Choose a folder to render files from");
+ if (!picked) return { added: false as const };
+ const config = await getManager().add(kind, picked);
+ return { added: true as const, id: config.id };
+ });
+ handle(CHANNELS.watchFoldersUpdate, watchFolderUpdateArgsSchema, async ({ id, patch }) => {
+ await getManager().update(id, patch);
+ });
+ handle(CHANNELS.watchFoldersPickOutput, watchFolderIdArgsSchema, async ({ id }, event) => {
+ const picked = await pickFolder(event, "Choose where rendered files go");
+ if (!picked) return { changed: false as const };
+ await getManager().setOutputDir(id, picked);
+ return { changed: true as const };
+ });
+ handle(CHANNELS.watchFoldersRemove, watchFolderIdArgsSchema, ({ id }) => getManager().remove(id));
+ handle(CHANNELS.watchFoldersRetry, watchItemIdArgsSchema, ({ itemId }) => getManager().retry(itemId));
+ handle(CHANNELS.watchFoldersClearFinished, z.undefined(), () => getManager().clearFinished());
+}
diff --git a/apps/desktop/src/main/watch/ledger.ts b/apps/desktop/src/main/watch/ledger.ts
new file mode 100644
index 00000000..f6c85d98
--- /dev/null
+++ b/apps/desktop/src/main/watch/ledger.ts
@@ -0,0 +1,115 @@
+import { createHash } from "node:crypto";
+import fs from "node:fs";
+import path from "node:path";
+
+/**
+ * Remembers which files a watch folder has already handled, so a restart, a re-drop of the same
+ * file or a copy under another name is recognised as a duplicate. The fingerprint is the size plus a
+ * hash of the first and last 256 KiB (cheap even for multi-GB camera files, and a changed file
+ * almost always changes one of them).
+ */
+
+const SAMPLE_BYTES = 256 * 1024;
+const MAX_ENTRIES_PER_FOLDER = 5000;
+
+export async function fingerprintFile(file: string): Promise<string> {
+ const handle = await fs.promises.open(file, "r");
+ try {
+ const { size } = await handle.stat();
+ const hash = createHash("sha1");
+ hash.update(String(size));
+ const head = Buffer.alloc(Math.min(SAMPLE_BYTES, size));
+ await handle.read(head, 0, head.length, 0);
+ hash.update(head);
+ if (size > SAMPLE_BYTES) {
+ const tail = Buffer.alloc(Math.min(SAMPLE_BYTES, size - SAMPLE_BYTES));
+ await handle.read(tail, 0, tail.length, size - tail.length);
+ hash.update(tail);
+ }
+ return `${size}-${hash.digest("hex").slice(0, 20)}`;
+ } finally {
+ await handle.close();
+ }
+}
+
+export interface LedgerEntry {
+ /** Original file name when it was handled. */
+ name: string;
+ at: number;
+ outcome: "imported" | "rendered" | "baseline";
+}
+
+type LedgerData = Record<string, Record<string, LedgerEntry>>;
+
+export interface LedgerStore {
+ load(): LedgerData;
+ save(data: LedgerData): void;
+}
+
+export function createFileLedgerStore(file: string): LedgerStore {
+ return {
+ load() {
+ try {
+ const parsed = JSON.parse(fs.readFileSync(file, "utf8")) as { version?: number; folders?: LedgerData };
+ return parsed.version === 1 && parsed.folders && typeof parsed.folders === "object" ? parsed.folders : {};
+ } catch {
+ return {};
+ }
+ },
+ save(data) {
+ try {
+ fs.mkdirSync(path.dirname(file), { recursive: true });
+ const tmp = `${file}.${process.pid}.tmp`;
+ fs.writeFileSync(tmp, JSON.stringify({ version: 1, folders: data }));
+ fs.renameSync(tmp, file);
+ } catch {
+ // A read-only profile only loses duplicate detection across restarts.
+ }
+ },
+ };
+}
+
+export class Ledger {
+ private data: LedgerData;
+ private timer: ReturnType<typeof setTimeout> | null = null;
+
+ constructor(private readonly store: LedgerStore) {
+ this.data = store.load();
+ }
+
+ has(folderId: string, fingerprint: string): LedgerEntry | undefined {
+ return this.data[folderId]?.[fingerprint];
+ }
+
+ record(folderId: string, fingerprint: string, entry: LedgerEntry): void {
+ const folder = (this.data[folderId] ??= {});
+ folder[fingerprint] = entry;
+ const keys = Object.keys(folder);
+ if (keys.length > MAX_ENTRIES_PER_FOLDER) {
+ keys.sort((a, b) => folder[a].at - folder[b].at);
+ for (const key of keys.slice(0, keys.length - MAX_ENTRIES_PER_FOLDER)) delete folder[key];
+ }
+ this.saveSoon();
+ }
+
+ dropFolder(folderId: string): void {
+ delete this.data[folderId];
+ this.saveSoon();
+ }
+
+ private saveSoon(): void {
+ if (this.timer) return;
+ this.timer = setTimeout(() => {
+ this.timer = null;
+ this.store.save(this.data);
+ }, 200);
+ this.timer.unref?.();
+ }
+
+ /** Writes now (quit, tests). */
+ flush(): void {
+ if (this.timer) clearTimeout(this.timer);
+ this.timer = null;
+ this.store.save(this.data);
+ }
+}
diff --git a/apps/desktop/src/main/watch/manager.ts b/apps/desktop/src/main/watch/manager.ts
new file mode 100644
index 00000000..ea08a547
--- /dev/null
+++ b/apps/desktop/src/main/watch/manager.ts
@@ -0,0 +1,564 @@
+import { randomUUID } from "node:crypto";
+import fs from "node:fs";
+import path from "node:path";
+import {
+ WATCH_EXPORT_PRESET_IDS,
+ type WatchFolderConfig,
+ type WatchFolderKind,
+ type WatchFolderPatch,
+ type WatchFolderState,
+ type WatchFolderStatus,
+ type WatchFoldersSnapshot,
+ type WatchItem,
+} from "../../shared/watch-folders";
+import { MEDIA_EXTENSIONS } from "../mcp/path-guard";
+import { FolderScanner, DEFAULT_SCANNER_OPTIONS, nodeScannerFs, type ScanFile, type ScannerFs, type ScannerOptions } from "./folder-scanner";
+import { fingerprintFile, type Ledger } from "./ledger";
+import { classifyFile, extensionOf, uniquePath } from "./render";
+
+/**
+ * Owns the configured watch folders: one scanner each, a job lane per kind (one ingest at a time, one
+ * render at a time), duplicate detection through the ledger, and the `done/` / `failed/` bookkeeping of
+ * export folders. Pure Node (the Electron pieces arrive through `handlers`), so it is unit-tested against
+ * real temporary folders.
+ *
+ * Nothing here blocks the UI: scanning and hashing are async, renders run in ffmpeg child processes, and
+ * ingest goes through the editor's own tool path one file at a time.
+ */
+
+export interface FolderContext {
+ folder: WatchFolderConfig;
+ file: ScanFile;
+ signal: AbortSignal;
+}
+
+export type IngestOutcome = { outcome: "imported"; detail?: string } | { outcome: "waiting"; detail: string };
+
+export interface WatchHandlers {
+ ingest(context: FolderContext): Promise<IngestOutcome>;
+ renderMedia(context: FolderContext & { onProgress(fraction: number | null): void }): Promise<{ outputPath: string }>;
+ renderProject(context: FolderContext & { onProgress(fraction: number | null): void }): Promise<{ outputPath: string }>;
+}
+
+export interface ConfigStore {
+ load(): WatchFolderConfig[];
+ save(folders: WatchFolderConfig[]): void;
+}
+
+export interface ManagerOptions {
+ scanner: ScannerOptions;
+ /** How long an ingest that is waiting for an open project sleeps before it tries again. */
+ retryWaitMs: number;
+ maxItems: number;
+ emitThrottleMs: number;
+}
+
+export const DEFAULT_MANAGER_OPTIONS: ManagerOptions = { scanner: DEFAULT_SCANNER_OPTIONS, retryWaitMs: 4000, maxItems: 200, emitThrottleMs: 120 };
+
+export interface ManagerDeps {
+ configStore: ConfigStore;
+ ledger: Ledger;
+ handlers: WatchHandlers;
+ emit(snapshot: WatchFoldersSnapshot): void;
+ /** Absolute paths agents/ingest may touch because of watch folders changed. */
+ onRoots?(roots: string[]): void;
+ options?: Partial<ManagerOptions>;
+ scannerFs?: ScannerFs;
+ fingerprint?: (file: string) => Promise<string>;
+ now?: () => number;
+}
+
+interface Job {
+ item: WatchItem;
+ folderId: string;
+ file: ScanFile;
+ fingerprint: string;
+ notBefore: number;
+ controller: AbortController;
+}
+
+interface Runtime {
+ scanner: FolderScanner | null;
+ state: WatchFolderState;
+ message?: string;
+}
+
+const DONE_DIR = "done";
+const FAILED_DIR = "failed";
+
+export class WatchFolderManager {
+ private folders: WatchFolderConfig[] = [];
+ private readonly runtime = new Map<string, Runtime>();
+ private items: WatchItem[] = [];
+ private readonly jobs: Job[] = [];
+ private readonly lanes: Record<WatchFolderKind, { busy: boolean; current: Job | null }> = {
+ ingest: { busy: false, current: null },
+ export: { busy: false, current: null },
+ };
+ private readonly options: ManagerOptions;
+ private emitTimer: ReturnType<typeof setTimeout> | null = null;
+ private pumpTimer: ReturnType<typeof setTimeout> | null = null;
+ private stopped = true;
+
+ constructor(private readonly deps: ManagerDeps) {
+ this.options = { ...DEFAULT_MANAGER_OPTIONS, ...deps.options, scanner: { ...DEFAULT_MANAGER_OPTIONS.scanner, ...deps.options?.scanner } };
+ }
+
+ private now(): number {
+ return (this.deps.now ?? Date.now)();
+ }
+
+ private get scannerFs(): ScannerFs {
+ return this.deps.scannerFs ?? nodeScannerFs;
+ }
+
+ // ---- lifecycle -----------------------------------------------------------------------------
+
+ start(): void {
+ if (!this.stopped) return;
+ this.stopped = false;
+ this.folders = this.deps.configStore.load();
+ this.publishRoots();
+ for (const folder of this.folders) void this.startFolder(folder);
+ this.emitSoon();
+ }
+
+ stop(): void {
+ this.stopped = true;
+ for (const runtime of this.runtime.values()) runtime.scanner?.stop();
+ this.runtime.clear();
+ for (const job of this.jobs) job.controller.abort();
+ for (const lane of Object.values(this.lanes)) lane.current?.controller.abort();
+ if (this.pumpTimer) clearTimeout(this.pumpTimer);
+ if (this.emitTimer) clearTimeout(this.emitTimer);
+ this.pumpTimer = this.emitTimer = null;
+ this.deps.ledger.flush();
+ }
+
+ // ---- configuration -------------------------------------------------------------------------
+
+ list(): WatchFolderConfig[] {
+ return this.folders.map((folder) => ({ ...folder }));
+ }
+
+ /** Adds a folder the user picked. Throws a readable message when it is not usable. */
+ async add(kind: WatchFolderKind, folderPath: string, overrides: Partial<WatchFolderConfig> = {}): Promise<WatchFolderConfig> {
+ if (!path.isAbsolute(folderPath)) throw new Error("Choose a folder.");
+ const real = await fs.promises.realpath(folderPath).catch(() => null);
+ const stat = real ? await fs.promises.stat(real).catch(() => null) : null;
+ if (!real || !stat?.isDirectory()) throw new Error("That folder does not exist.");
+ if (real === path.parse(real).root) throw new Error("Choose a folder, not the whole drive.");
+ const config: WatchFolderConfig = {
+ id: randomUUID(),
+ kind,
+ path: real,
+ paused: false,
+ bin: kind === "ingest" ? "Watch folder" : "",
+ createProxies: false,
+ presetId: "1080p-high",
+ outputDir: kind === "export" ? path.join(real, "output") : "",
+ includeProjects: false,
+ baselined: false,
+ processExisting: false,
+ ...overrides,
+ };
+ this.assertUsable(config);
+ this.folders = [...this.folders, config];
+ this.persist();
+ void this.startFolder(config);
+ return { ...config };
+ }
+
+ async update(id: string, patch: WatchFolderPatch): Promise<WatchFolderConfig> {
+ const index = this.folders.findIndex((folder) => folder.id === id);
+ if (index < 0) throw new Error("That watch folder no longer exists.");
+ if (patch.presetId !== undefined && !(WATCH_EXPORT_PRESET_IDS as readonly string[]).includes(patch.presetId)) throw new Error("Unknown export preset.");
+ const before = this.folders[index];
+ const next: WatchFolderConfig = { ...before, ...patch };
+ this.folders = this.folders.map((folder, i) => (i === index ? next : folder));
+ this.persist();
+ if (patch.paused !== undefined && patch.paused !== before.paused) {
+ if (patch.paused) this.stopScanner(id, "paused");
+ else void this.startFolder(next);
+ }
+ this.emitSoon();
+ this.pumpSoon(0);
+ return { ...next };
+ }
+
+ /** Changes where an export folder renders to (a path from the native folder dialog). */
+ async setOutputDir(id: string, dir: string): Promise<WatchFolderConfig> {
+ const folder = this.folders.find((entry) => entry.id === id);
+ if (!folder || folder.kind !== "export") throw new Error("That watch folder no longer exists.");
+ const real = await fs.promises.realpath(dir).catch(() => null);
+ if (!real) throw new Error("That folder does not exist.");
+ const next = { ...folder, outputDir: real };
+ this.assertUsable(next, id);
+ this.folders = this.folders.map((entry) => (entry.id === id ? next : entry));
+ this.persist();
+ this.emitSoon();
+ return { ...next };
+ }
+
+ remove(id: string): void {
+ this.stopScanner(id);
+ this.runtime.delete(id);
+ this.folders = this.folders.filter((folder) => folder.id !== id);
+ for (const job of this.jobs.filter((entry) => entry.folderId === id)) job.controller.abort();
+ this.removeJobs((job) => job.folderId === id);
+ for (const lane of Object.values(this.lanes)) if (lane.current?.folderId === id) lane.current.controller.abort();
+ this.items = this.items.filter((item) => item.folderId !== id);
+ this.deps.ledger.dropFolder(id);
+ this.persist();
+ this.emitSoon();
+ }
+
+ /** Re-queues a failed item (its file is moved back out of failed/ for export folders). */
+ async retry(itemId: string): Promise<void> {
+ const item = this.items.find((entry) => entry.id === itemId);
+ const folder = item && this.folders.find((entry) => entry.id === item.folderId);
+ if (!item || !folder || item.state !== "failed") return;
+ let source = item.path;
+ if (!fs.existsSync(source)) {
+ const failedCopy = path.join(folder.path, FAILED_DIR, path.basename(item.path));
+ if (!fs.existsSync(failedCopy)) return;
+ const back = uniquePath(folder.path, path.basename(item.path, path.extname(item.path)), extensionOf(item.path));
+ await fs.promises.rename(failedCopy, back);
+ await fs.promises.rm(`${failedCopy}.error.txt`, { force: true });
+ source = back;
+ }
+ this.items = this.items.filter((entry) => entry.id !== itemId);
+ this.runtime.get(folder.id)?.scanner?.forget(source);
+ this.runtime.get(folder.id)?.scanner?.forget(item.path);
+ void this.runtime.get(folder.id)?.scanner?.scan();
+ this.emitSoon();
+ }
+
+ clearFinished(): void {
+ this.items = this.items.filter((item) => !["done", "failed", "duplicate", "cancelled"].includes(item.state));
+ this.emitSoon();
+ }
+
+ snapshot(): WatchFoldersSnapshot {
+ return {
+ folders: this.folders.map((config) => ({ config: { ...config }, status: this.statusOf(config) })),
+ items: this.items.map((item) => ({ ...item })),
+ };
+ }
+
+ // ---- validation ----------------------------------------------------------------------------
+
+ private assertUsable(candidate: WatchFolderConfig, ignoreId?: string): void {
+ const others = this.folders.filter((folder) => folder.id !== ignoreId && folder.id !== candidate.id);
+ if (others.some((folder) => folder.path === candidate.path)) throw new Error("That folder is already being watched.");
+ if (candidate.kind === "export") {
+ if (!candidate.outputDir || !path.isAbsolute(candidate.outputDir)) throw new Error("Choose an output folder.");
+ // The output may live inside the watched folder (files there are not rescanned: only the top level is watched).
+ if (others.some((folder) => folder.path === candidate.outputDir)) throw new Error("The output folder is watched by another watch folder; rendered files would be picked up again.");
+ if (candidate.outputDir === candidate.path) throw new Error("Rendered files cannot go into the watched folder itself; pick a different output folder.");
+ }
+ for (const other of others) {
+ if (other.kind === "export" && other.outputDir === candidate.path) throw new Error("That folder is the output of an export watch folder; watching it would re-process the rendered files.");
+ }
+ }
+
+ private publishRoots(): void {
+ const roots = new Set<string>();
+ for (const folder of this.folders) {
+ roots.add(folder.path);
+ if (folder.kind === "export" && folder.outputDir) roots.add(folder.outputDir);
+ }
+ this.deps.onRoots?.([...roots]);
+ }
+
+ private persist(): void {
+ this.deps.configStore.save(this.folders);
+ this.publishRoots();
+ }
+
+ // ---- scanning ------------------------------------------------------------------------------
+
+ private isRelevant(folder: WatchFolderConfig, file: string): boolean {
+ if (folder.kind === "ingest") return MEDIA_EXTENSIONS.has(extensionOf(file));
+ const kind = classifyFile(file);
+ return kind === "video" || kind === "audio" || (kind === "project" && folder.includeProjects);
+ }
+
+ private stopScanner(id: string, state?: WatchFolderState): void {
+ const runtime = this.runtime.get(id);
+ runtime?.scanner?.stop();
+ if (runtime) {
+ runtime.scanner = null;
+ if (state) runtime.state = state;
+ }
+ this.emitSoon();
+ }
+
+ private async startFolder(folder: WatchFolderConfig): Promise<void> {
+ if (this.stopped) return;
+ const runtime: Runtime = { scanner: null, state: folder.paused ? "paused" : "watching" };
+ this.runtime.set(folder.id, runtime);
+ if (folder.paused) {
+ this.emitSoon();
+ return;
+ }
+ const scanner = new FolderScanner(
+ folder.path,
+ {
+ onSeen: (file) => this.onSeen(folder.id, file),
+ onGone: (file) => this.onGone(folder.id, file),
+ onReady: (file) => void this.onReady(folder.id, file),
+ onUnreadable: (error) => {
+ const entry = this.runtime.get(folder.id);
+ if (entry) {
+ entry.state = "missing";
+ entry.message = error.code === "ENOENT" ? "The folder is missing or not mounted." : `The folder cannot be read (${error.code ?? "error"}).`;
+ }
+ this.emitSoon();
+ },
+ onReadable: () => {
+ const entry = this.runtime.get(folder.id);
+ if (entry) {
+ entry.state = "watching";
+ entry.message = undefined;
+ }
+ this.emitSoon();
+ },
+ },
+ this.options.scanner,
+ this.scannerFs,
+ );
+ runtime.scanner = scanner;
+ const current = this.folders.find((entry) => entry.id === folder.id) ?? folder;
+ if (!current.baselined) {
+ await this.baseline(current, scanner).catch(() => undefined);
+ if (this.stopped || this.runtime.get(folder.id)?.scanner !== scanner) return;
+ }
+ scanner.start();
+ this.emitSoon();
+ }
+
+ /** Records what is already in a newly added folder so only files that arrive later are processed. */
+ private async baseline(folder: WatchFolderConfig, scanner: FolderScanner): Promise<void> {
+ if (!folder.processExisting) {
+ let entries: Array<{ name: string; isFile: boolean }> = [];
+ try {
+ entries = await this.scannerFs.readdir(folder.path);
+ } catch {
+ return; // unreadable now: baseline on the next start
+ }
+ for (const entry of entries) {
+ if (!entry.isFile) continue;
+ const full = path.join(folder.path, entry.name);
+ if (!this.isRelevant(folder, full)) continue;
+ const stat = await this.scannerFs.stat(full);
+ if (!stat) continue;
+ try {
+ const fingerprint = await (this.deps.fingerprint ?? fingerprintFile)(full);
+ this.deps.ledger.record(folder.id, fingerprint, { name: entry.name, at: this.now(), outcome: "baseline" });
+ } catch {
+ /* unreadable file: it is simply not recorded */
+ }
+ scanner.markReported({ path: full, name: entry.name, size: stat.size, mtimeMs: stat.mtimeMs });
+ }
+ }
+ this.folders = this.folders.map((entry) => (entry.id === folder.id ? { ...entry, baselined: true } : entry));
+ this.persist();
+ }
+
+ private newItem(folder: WatchFolderConfig, file: ScanFile): WatchItem {
+ const item: WatchItem = { id: randomUUID(), folderId: folder.id, name: file.name, path: file.path, state: "detecting", progress: null, createdAt: this.now(), detail: "Waiting for the file to finish copying" };
+ this.items = [item, ...this.items].slice(0, this.options.maxItems);
+ return item;
+ }
+
+ private onSeen(folderId: string, file: ScanFile): void {
+ const folder = this.folders.find((entry) => entry.id === folderId);
+ if (!folder || !this.isRelevant(folder, file.path)) return;
+ const existing = this.items.find((item) => item.path === file.path && item.state === "detecting");
+ if (existing) {
+ existing.detail = "Waiting for the file to finish copying";
+ } else {
+ this.newItem(folder, file);
+ }
+ this.emitSoon();
+ }
+
+ private onGone(folderId: string, filePath: string): void {
+ const item = this.items.find((entry) => entry.folderId === folderId && entry.path === filePath && entry.state === "detecting");
+ if (item) this.items = this.items.filter((entry) => entry !== item);
+ this.emitSoon();
+ }
+
+ private async onReady(folderId: string, file: ScanFile): Promise<void> {
+ const folder = this.folders.find((entry) => entry.id === folderId);
+ if (!folder || this.stopped || !this.isRelevant(folder, file.path)) return;
+ const item = this.items.find((entry) => entry.folderId === folderId && entry.path === file.path && entry.state === "detecting") ?? this.newItem(folder, file);
+ let fingerprint: string;
+ try {
+ fingerprint = await (this.deps.fingerprint ?? fingerprintFile)(file.path);
+ } catch (error) {
+ this.finish(item, "failed", { error: `Could not read the file: ${error instanceof Error ? error.message : String(error)}` });
+ return;
+ }
+ const seen = this.deps.ledger.has(folder.id, fingerprint);
+ if (seen) {
+ if (folder.kind === "ingest" && seen.name === file.name) {
+ // The same file seen again (restart, touched): nothing to report.
+ this.items = this.items.filter((entry) => entry !== item);
+ this.emitSoon();
+ return;
+ }
+ if (folder.kind === "export") await this.moveAside(folder, file.path, DONE_DIR);
+ this.finish(item, "duplicate", { detail: `Same content as "${seen.name}" handled earlier${folder.kind === "export" ? "; moved to done" : ""}` });
+ return;
+ }
+ // Same content already queued or running under another name: do not render it twice.
+ const dup = this.jobs.find((job) => job.folderId === folder.id && job.fingerprint === fingerprint) ?? Object.values(this.lanes).map((lane) => lane.current).find((job) => job && job.folderId === folder.id && job.fingerprint === fingerprint);
+ if (dup) {
+ this.finish(item, "duplicate", { detail: `Same content as "${dup.file.name}", which is already queued` });
+ return;
+ }
+ item.state = "queued";
+ item.detail = folder.paused ? "Folder paused" : undefined;
+ this.jobs.push({ item, folderId: folder.id, file, fingerprint, notBefore: 0, controller: new AbortController() });
+ this.emitSoon();
+ this.pumpSoon(0);
+ }
+
+ // ---- job lanes -----------------------------------------------------------------------------
+
+ private pumpSoon(delayMs: number): void {
+ if (this.stopped) return;
+ if (this.pumpTimer && delayMs > 0) return;
+ if (this.pumpTimer) clearTimeout(this.pumpTimer);
+ this.pumpTimer = setTimeout(() => {
+ this.pumpTimer = null;
+ for (const kind of ["ingest", "export"] as const) void this.pump(kind);
+ }, delayMs);
+ this.pumpTimer.unref?.();
+ }
+
+ private removeJobs(predicate: (job: Job) => boolean): void {
+ for (let i = this.jobs.length - 1; i >= 0; i--) if (predicate(this.jobs[i])) this.jobs.splice(i, 1);
+ }
+
+ private async pump(kind: WatchFolderKind): Promise<void> {
+ const lane = this.lanes[kind];
+ if (lane.busy || this.stopped) return;
+ const now = this.now();
+ const index = this.jobs.findIndex((job) => {
+ const folder = this.folders.find((entry) => entry.id === job.folderId);
+ return folder?.kind === kind && !folder.paused && job.notBefore <= now;
+ });
+ if (index < 0) {
+ const waiting = this.jobs.filter((job) => this.folders.find((entry) => entry.id === job.folderId)?.kind === kind && job.notBefore > now);
+ if (waiting.length) this.pumpSoon(Math.max(50, Math.min(...waiting.map((job) => job.notBefore)) - now));
+ return;
+ }
+ const [job] = this.jobs.splice(index, 1);
+ const folder = this.folders.find((entry) => entry.id === job.folderId);
+ if (!folder) return;
+ lane.busy = true;
+ lane.current = job;
+ job.item.state = "running";
+ job.item.startedAt = job.item.startedAt ?? this.now();
+ job.item.detail = kind === "ingest" ? "Importing" : "Rendering";
+ this.emitSoon();
+ try {
+ await this.runJob(folder, job);
+ } catch (error) {
+ this.finish(job.item, "failed", { error: error instanceof Error ? error.message : String(error) });
+ } finally {
+ lane.busy = false;
+ lane.current = null;
+ this.pumpSoon(0);
+ }
+ }
+
+ private async runJob(folder: WatchFolderConfig, job: Job): Promise<void> {
+ const context: FolderContext = { folder, file: job.file, signal: job.controller.signal };
+ if (folder.kind === "ingest") {
+ const result = await this.deps.handlers.ingest(context);
+ if (job.controller.signal.aborted) return this.finish(job.item, "cancelled", {});
+ if (result.outcome === "waiting") {
+ job.item.state = "waiting";
+ job.item.detail = result.detail;
+ job.notBefore = this.now() + this.options.retryWaitMs;
+ this.jobs.push(job);
+ this.emitSoon();
+ return;
+ }
+ this.deps.ledger.record(folder.id, job.fingerprint, { name: job.file.name, at: this.now(), outcome: "imported" });
+ return this.finish(job.item, "done", { detail: result.detail ?? "Imported" });
+ }
+ const onProgress = (fraction: number | null): void => {
+ job.item.progress = fraction;
+ this.emitSoon();
+ };
+ try {
+ const kind = classifyFile(job.file.path);
+ const { outputPath } = kind === "project" ? await this.deps.handlers.renderProject({ ...context, onProgress }) : await this.deps.handlers.renderMedia({ ...context, onProgress });
+ this.deps.ledger.record(folder.id, job.fingerprint, { name: job.file.name, at: this.now(), outcome: "rendered" });
+ await this.moveAside(folder, job.file.path, DONE_DIR);
+ this.finish(job.item, "done", { outputPath, detail: `Rendered to ${path.basename(outputPath)}` });
+ } catch (error) {
+ if (job.controller.signal.aborted) return this.finish(job.item, "cancelled", {});
+ const message = error instanceof Error ? error.message : String(error);
+ await this.moveAside(folder, job.file.path, FAILED_DIR, message);
+ this.finish(job.item, "failed", { error: message, detail: "Moved to failed" });
+ }
+ }
+
+ /** Moves a processed export source into `<watch>/done` or `<watch>/failed` (never overwrites). */
+ private async moveAside(folder: WatchFolderConfig, file: string, sub: typeof DONE_DIR | typeof FAILED_DIR, errorText?: string): Promise<void> {
+ try {
+ const dir = path.join(folder.path, sub);
+ await fs.promises.mkdir(dir, { recursive: true });
+ const ext = extensionOf(file);
+ const target = uniquePath(dir, path.basename(file, path.extname(file)), ext);
+ await fs.promises.rename(file, target);
+ if (errorText) await fs.promises.writeFile(`${target}.error.txt`, `${errorText}\n`, "utf8");
+ } catch {
+ // The source stays where it is; the ledger / failed item keeps it from being processed again.
+ }
+ }
+
+ private finish(item: WatchItem, state: WatchItem["state"], extra: { error?: string; detail?: string; outputPath?: string }): void {
+ item.state = state;
+ item.progress = state === "done" ? 1 : item.progress;
+ item.finishedAt = this.now();
+ if (extra.error !== undefined) item.error = extra.error;
+ if (extra.detail !== undefined) item.detail = extra.detail;
+ else if (state === "failed") item.detail = undefined;
+ if (extra.outputPath) item.outputPath = extra.outputPath;
+ this.emitSoon();
+ }
+
+ // ---- status --------------------------------------------------------------------------------
+
+ private statusOf(config: WatchFolderConfig): WatchFolderStatus {
+ const runtime = this.runtime.get(config.id);
+ const mine = this.items.filter((item) => item.folderId === config.id);
+ const count = (...states: WatchItem["state"][]): number => mine.filter((item) => states.includes(item.state)).length;
+ return {
+ state: config.paused ? "paused" : (runtime?.state ?? "watching"),
+ ...(runtime?.message ? { message: runtime.message } : {}),
+ detecting: count("detecting"),
+ queued: count("queued", "waiting"),
+ running: count("running"),
+ done: count("done"),
+ failed: count("failed"),
+ duplicates: count("duplicate"),
+ };
+ }
+
+ private emitSoon(): void {
+ if (this.emitTimer || this.stopped) return;
+ this.emitTimer = setTimeout(() => {
+ this.emitTimer = null;
+ this.deps.emit(this.snapshot());
+ }, this.options.emitThrottleMs);
+ this.emitTimer.unref?.();
+ }
+}
diff --git a/apps/desktop/src/main/watch/render.ts b/apps/desktop/src/main/watch/render.ts
new file mode 100644
index 00000000..4f5f3d97
--- /dev/null
+++ b/apps/desktop/src/main/watch/render.ts
@@ -0,0 +1,185 @@
+import { spawn } from "node:child_process";
+import fs from "node:fs";
+import path from "node:path";
+import type { MediaProbe } from "../ingest/probe-media";
+import type { WatchExportPresetId } from "../../shared/watch-folders";
+
+/**
+ * Headless render for export watch folders: a dropped media file is re-encoded to an export preset by
+ * the bundled ffmpeg in the main process. No window, no editor and no open project are involved, so it
+ * never touches what the user is working on. (Project files go through the editor's export queue instead,
+ * see project-render.ts.)
+ *
+ * The preset ids and numbers are the Export dialog's quick presets (apps/web/src/services/quick-export-presets.ts).
+ */
+
+export interface WatchVideoPreset {
+ kind: "video";
+ label: string;
+ /** Fixed output size, or null to keep the source's size. */
+ size: { width: number; height: number } | null;
+ /** Fixed frame rate, or null to keep the source's. */
+ frameRate: number | null;
+ videoKbps: number;
+}
+export interface WatchAudioPreset {
+ kind: "audio";
+ label: string;
+}
+export type WatchPreset = WatchVideoPreset | WatchAudioPreset;
+
+export const WATCH_PRESETS: Record<WatchExportPresetId, WatchPreset> = {
+ mp4: { kind: "video", label: "MP4 Standard (source size)", size: null, frameRate: null, videoKbps: 12000 },
+ "1080p-high": { kind: "video", label: "1080p High Quality", size: { width: 1920, height: 1080 }, frameRate: 30, videoKbps: 20000 },
+ "1080p-60": { kind: "video", label: "1080p 60fps", size: { width: 1920, height: 1080 }, frameRate: 60, videoKbps: 25000 },
+ "4k": { kind: "video", label: "4K Standard", size: { width: 3840, height: 2160 }, frameRate: 30, videoKbps: 50000 },
+ wav: { kind: "audio", label: "Audio Only (WAV)" },
+};
+
+export const isWatchPresetId = (id: string): id is WatchExportPresetId => Object.prototype.hasOwnProperty.call(WATCH_PRESETS, id);
+
+export const VIDEO_EXTENSIONS: ReadonlySet<string> = new Set(["mp4", "m4v", "mov", "mkv", "webm", "avi", "mxf", "mts", "m2ts", "ts", "mpg", "mpeg", "wmv", "flv", "3gp", "ogv"]);
+export const AUDIO_EXTENSIONS: ReadonlySet<string> = new Set(["mp3", "wav", "aac", "m4a", "flac", "ogg", "opus", "aif", "aiff", "wma", "caf"]);
+export const PROJECT_EXTENSIONS: ReadonlySet<string> = new Set(["oreel", "openreel"]);
+
+export const extensionOf = (file: string): string => path.extname(file).slice(1).toLowerCase();
+
+export type WatchFileKind = "video" | "audio" | "project" | "other";
+export function classifyFile(file: string): WatchFileKind {
+ const ext = extensionOf(file);
+ if (VIDEO_EXTENSIONS.has(ext)) return "video";
+ if (AUDIO_EXTENSIONS.has(ext)) return "audio";
+ if (PROJECT_EXTENSIONS.has(ext)) return "project";
+ return "other";
+}
+
+export interface RenderPlan {
+ /** Output extension without the dot. */
+ ext: string;
+ args: string[];
+}
+
+/** ffmpeg arguments that render `src` into `out` for `presetId`. Throws a readable message when the source cannot make that output. */
+export function buildWatchRenderArgs(
+ presetId: WatchExportPresetId,
+ src: string,
+ out: string,
+ source: Pick<MediaProbe, "hasVideo" | "hasAudio">,
+ videoEncoder = "libx264",
+): RenderPlan {
+ const preset = WATCH_PRESETS[presetId];
+ const base = ["-y", "-nostdin", "-i", src, "-map_metadata", "0"];
+ if (preset.kind === "audio") {
+ if (!source.hasAudio) throw new Error("The file has no audio to export.");
+ return { ext: "wav", args: [...base, "-vn", "-map", "0:a:0", "-c:a", "pcm_s24le", "-ar", "48000", "-ac", "2", "-progress", "pipe:2", out] };
+ }
+ if (!source.hasVideo) {
+ if (!source.hasAudio) throw new Error("The file has neither video nor audio.");
+ // An audio file under a video preset becomes an AAC audio file rather than an empty video.
+ return { ext: "m4a", args: [...base, "-vn", "-map", "0:a:0", "-c:a", "aac", "-b:a", "256k", "-ar", "48000", "-progress", "pipe:2", out] };
+ }
+ const filters: string[] = [];
+ if (preset.size) {
+ const { width, height } = preset.size;
+ filters.push(`scale=${width}:${height}:force_original_aspect_ratio=decrease`, `pad=${width}:${height}:(ow-iw)/2:(oh-ih)/2`, "setsar=1");
+ } else {
+ // Even dimensions: H.264 4:2:0 refuses odd ones.
+ filters.push("scale=trunc(iw/2)*2:trunc(ih/2)*2");
+ }
+ if (preset.frameRate) filters.push(`fps=${preset.frameRate}`);
+ const args = [...base, "-map", "0:v:0", ...(source.hasAudio ? ["-map", "0:a:0"] : []), "-vf", filters.join(","), "-c:v", videoEncoder, "-b:v", `${preset.videoKbps}k`, "-pix_fmt", "yuv420p"];
+ if (videoEncoder === "libx264") args.push("-preset", "medium");
+ if (source.hasAudio) args.push("-c:a", "aac", "-b:a", "192k", "-ar", "48000", "-ac", "2");
+ args.push("-movflags", "+faststart", "-progress", "pipe:2", out);
+ return { ext: "mp4", args };
+}
+
+/** Parses the newest `out_time_us` / `out_time_ms` (both are microseconds in ffmpeg's progress output) as seconds. */
+export function parseOutTimeSeconds(chunk: string): number | null {
+ const matches = [...chunk.matchAll(/out_time_(?:us|ms)=(\d+)/g)];
+ if (matches.length === 0) return null;
+ return Number(matches[matches.length - 1][1]) / 1_000_000;
+}
+
+export function uniquePath(dir: string, base: string, ext: string, exists: (p: string) => boolean = fs.existsSync): string {
+ const dot = ext ? `.${ext}` : "";
+ let candidate = path.join(dir, `${base}${dot}`);
+ for (let i = 1; exists(candidate); i++) candidate = path.join(dir, `${base}-${i}${dot}`);
+ return candidate;
+}
+
+export interface RenderDeps {
+ ffmpegPath(): string;
+ probe(file: string): Promise<Pick<MediaProbe, "duration" | "hasVideo" | "hasAudio">>;
+ videoEncoder(): Promise<string>;
+ isHardwareEncoder(encoder: string): boolean;
+}
+
+export interface RenderRequest {
+ src: string;
+ presetId: WatchExportPresetId;
+ outputDir: string;
+ onProgress(fraction: number | null): void;
+ signal: AbortSignal;
+}
+
+function runFfmpeg(ffmpeg: string, args: string[], durationSec: number | undefined, onProgress: (f: number | null) => void, signal: AbortSignal): Promise<void> {
+ return new Promise((resolve, reject) => {
+ if (signal.aborted) return reject(new Error("Cancelled"));
+ const proc = spawn(ffmpeg, args, { stdio: ["ignore", "ignore", "pipe"] });
+ let tail = "";
+ const onAbort = (): void => {
+ proc.kill("SIGKILL");
+ };
+ signal.addEventListener("abort", onAbort, { once: true });
+ proc.stderr.on("data", (chunk: Buffer) => {
+ tail = (tail + chunk.toString()).slice(-4096);
+ const seconds = parseOutTimeSeconds(tail);
+ if (seconds !== null && durationSec && durationSec > 0) onProgress(Math.min(0.99, seconds / durationSec));
+ });
+ proc.on("error", (error) => {
+ signal.removeEventListener("abort", onAbort);
+ reject(error);
+ });
+ proc.on("close", (code) => {
+ signal.removeEventListener("abort", onAbort);
+ if (signal.aborted) return reject(new Error("Cancelled"));
+ if (code === 0) return resolve();
+ const reason = tail.split("\n").map((line) => line.trim()).filter((line) => line && !/^(frame|fps|stream_|bitrate|total_size|out_time|dup_frames|drop_frames|speed|progress)=/.test(line)).slice(-2).join(" ");
+ reject(new Error(`ffmpeg exited with code ${code}${reason ? `: ${reason}` : ""}`));
+ });
+ });
+}
+
+/**
+ * Renders one file. The output is written under a hidden temporary name and renamed when ffmpeg
+ * finishes, so nothing downstream ever sees a half-written file. Hardware encoders fall back to libx264
+ * once. Returns the final output path.
+ */
+export async function renderMediaFile(request: RenderRequest, deps: RenderDeps): Promise<string> {
+ const probe = await deps.probe(request.src);
+ const base = path.basename(request.src, path.extname(request.src));
+ await fs.promises.mkdir(request.outputDir, { recursive: true });
+ const encoder = await deps.videoEncoder();
+ const plan = buildWatchRenderArgs(request.presetId, request.src, "<out>", probe, encoder);
+ const finalPath = uniquePath(request.outputDir, base, plan.ext);
+ const partial = path.join(request.outputDir, `.${path.basename(finalPath)}.${process.pid}.partial.${plan.ext}`);
+ const argsFor = (enc: string): string[] => buildWatchRenderArgs(request.presetId, request.src, partial, probe, enc).args;
+ try {
+ try {
+ await runFfmpeg(deps.ffmpegPath(), argsFor(encoder), probe.duration, request.onProgress, request.signal);
+ } catch (error) {
+ if (request.signal.aborted || !deps.isHardwareEncoder(encoder)) throw error;
+ await runFfmpeg(deps.ffmpegPath(), argsFor("libx264"), probe.duration, request.onProgress, request.signal);
+ }
+ const stat = await fs.promises.stat(partial);
+ if (stat.size === 0) throw new Error("ffmpeg produced an empty file.");
+ // Never replace a file that appeared while rendering.
+ const target = fs.existsSync(finalPath) ? uniquePath(request.outputDir, base, plan.ext) : finalPath;
+ await fs.promises.rename(partial, target);
+ request.onProgress(1);
+ return target;
+ } finally {
+ await fs.promises.rm(partial, { force: true }).catch(() => undefined);
+ }
+}
diff --git a/apps/desktop/src/preload/index.ts b/apps/desktop/src/preload/index.ts
index 68944e12..8474f435 100644
--- a/apps/desktop/src/preload/index.ts
+++ b/apps/desktop/src/preload/index.ts
@@ -125,6 +125,7 @@ contextBridge.exposeInMainWorld("openreel", {
writeAudioChunk: (jobId: string, chunk: ArrayBuffer, position: number) =>
ipcRenderer.invoke(CHANNELS.exportWriteAudioChunk, { jobId, chunk, position }),
finishAudio: (jobId: string) => ipcRenderer.invoke(CHANNELS.exportFinishAudio, { jobId }),
+ encodeDolbyAudio: (args: unknown) => ipcRenderer.invoke(CHANNELS.exportEncodeDolbyAudio, args),
cancel: (jobId: string) => ipcRenderer.invoke(CHANNELS.exportCancel, { jobId }),
probeSource: (path: string) => ipcRenderer.invoke(CHANNELS.exportProbeSource, { path }),
copyRun: (jobId: string, run: unknown) =>
@@ -211,6 +212,20 @@ contextBridge.exposeInMainWorld("openreel", {
report: (payload: { message: string; stack?: string; type?: string; context?: unknown }) =>
ipcRenderer.send(CHANNELS.crashReport, payload),
},
+ watchFolders: {
+ list: () => ipcRenderer.invoke(CHANNELS.watchFoldersList, undefined),
+ add: (kind: "ingest" | "export") => ipcRenderer.invoke(CHANNELS.watchFoldersAdd, { kind }),
+ update: (id: string, patch: unknown) => ipcRenderer.invoke(CHANNELS.watchFoldersUpdate, { id, patch }),
+ pickOutput: (id: string) => ipcRenderer.invoke(CHANNELS.watchFoldersPickOutput, { id }),
+ remove: (id: string) => ipcRenderer.invoke(CHANNELS.watchFoldersRemove, { id }),
+ retry: (itemId: string) => ipcRenderer.invoke(CHANNELS.watchFoldersRetry, { itemId }),
+ clearFinished: () => ipcRenderer.invoke(CHANNELS.watchFoldersClearFinished, undefined),
+ onChange: (cb: (snapshot: unknown) => void) => {
+ const handler = (_event: unknown, snapshot: unknown) => cb(snapshot);
+ ipcRenderer.on(CHANNELS.watchFoldersEvent, handler);
+ return () => ipcRenderer.removeListener(CHANNELS.watchFoldersEvent, handler);
+ },
+ },
mcp: {
// The main-process MCP server pushes tool-call / list-tool requests here; the
// renderer runs them against the live editor and replies on the result
diff --git a/apps/desktop/src/shared/channels.ts b/apps/desktop/src/shared/channels.ts
index 42a768ee..aaa5ad13 100644
--- a/apps/desktop/src/shared/channels.ts
+++ b/apps/desktop/src/shared/channels.ts
@@ -25,6 +25,7 @@ export const CHANNELS = {
exportWriteAudioWav: "openreel:export:writeAudioWav",
exportWriteAudioChunk: "openreel:export:writeAudioChunk",
exportFinishAudio: "openreel:export:finishAudio",
+ exportEncodeDolbyAudio: "openreel:export:encodeDolbyAudio",
exportCancel: "openreel:export:cancel",
exportCopyRun: "openreel:export:copyRun",
exportProbeSource: "openreel:export:probeSource",
@@ -101,6 +102,15 @@ export const CHANNELS = {
mcpGetClientStatus: "openreel:mcp:getClientStatus",
mcpGetPolicy: "openreel:mcp:getPolicy",
mcpSetPolicy: "openreel:mcp:setPolicy",
+ watchFoldersList: "openreel:watchFolders:list",
+ watchFoldersAdd: "openreel:watchFolders:add",
+ watchFoldersUpdate: "openreel:watchFolders:update",
+ watchFoldersPickOutput: "openreel:watchFolders:pickOutput",
+ watchFoldersRemove: "openreel:watchFolders:remove",
+ watchFoldersRetry: "openreel:watchFolders:retry",
+ watchFoldersClearFinished: "openreel:watchFolders:clearFinished",
+ /** Main -> renderer: the watch folders' status changed (full snapshot). */
+ watchFoldersEvent: "openreel:watchFolders:event",
/** Renderer/internal (WP-E path tools): resolve absolute paths and check them against the allowed roots. */
mcpFilesResolve: "openreel:mcp:files:resolve",
/** Renderer -> main: copy an app temp export to an allowed-roots destination (export outputPath). */
diff --git a/apps/desktop/src/shared/ipc-contract.ts b/apps/desktop/src/shared/ipc-contract.ts
index d78819ed..6c5e18fe 100644
--- a/apps/desktop/src/shared/ipc-contract.ts
+++ b/apps/desktop/src/shared/ipc-contract.ts
@@ -51,6 +51,15 @@ export const extractAudioArgsSchema = z.object({
/** Output channel count (a 5.1 sequence asks for the source's own channels, up to 6). Default 2. */
channels: z.number().int().min(1).max(8).optional(),
});
+/** Audio-only Dolby export: a WAV mixdown in, a raw AC-3 / E-AC-3 stream out. */
+export const encodeDolbyAudioArgsSchema = z.object({
+ wav: z.instanceof(ArrayBuffer),
+ codec: z.enum(["ac3", "eac3"]),
+ channels: z.union([z.literal(2), z.literal(6)]),
+ bitrateKbps: z.number().int().min(32).max(2048),
+ sampleRate: z.union([z.literal(44100), z.literal(48000)]),
+ dialnorm: z.number().int().min(-31).max(-1),
+});
export const probeAudioArgsSchema = z.object({ srcPath: z.string() });
export const developRawStillArgsSchema = z.object({ srcPath: z.string().min(1) });
export const nativeProbeArgsSchema = z.object({ path: z.string().min(1) });
diff --git a/apps/desktop/src/shared/mcp.ts b/apps/desktop/src/shared/mcp.ts
index c9bb3ef4..5b8ebaf2 100644
--- a/apps/desktop/src/shared/mcp.ts
+++ b/apps/desktop/src/shared/mcp.ts
@@ -32,6 +32,12 @@ export interface McpBridgeRequest {
kind: "listTools" | "callTool";
name?: string;
args?: Record<string, unknown>;
+ /**
+ * Set only by the main process for watch-folder work. The renderer lets this origin run the few tools
+ * a watch folder needs without the agent confirmation gate: the folders are configured by the user in
+ * Settings, not by an agent. The MCP HTTP server never sets it.
+ */
+ origin?: "watch-folders";
}
export interface McpBridgeResponse {
diff --git a/apps/desktop/src/shared/watch-folders.ts b/apps/desktop/src/shared/watch-folders.ts
new file mode 100644
index 00000000..557c1022
--- /dev/null
+++ b/apps/desktop/src/shared/watch-folders.ts
@@ -0,0 +1,102 @@
+import { z } from "zod";
+
+/**
+ * Watch folders (desktop). Shared by the main process, the preload bridge and (mirrored in
+ * apps/web/src/types/global.d.ts) the renderer.
+ *
+ * An ingest folder imports media that appears in it into the open project. An export folder
+ * renders media (and optionally project) files that appear in it with an export preset into an
+ * output folder, then moves the source into `done/` or `failed/`.
+ */
+
+export const WATCH_FOLDER_KINDS = ["ingest", "export"] as const;
+export type WatchFolderKind = (typeof WATCH_FOLDER_KINDS)[number];
+
+/** Presets an export folder can render. Same ids as the Export dialog's quick presets. */
+export const WATCH_EXPORT_PRESET_IDS = ["mp4", "1080p-high", "1080p-60", "4k", "wav"] as const;
+export type WatchExportPresetId = (typeof WATCH_EXPORT_PRESET_IDS)[number];
+
+export interface WatchFolderConfig {
+ id: string;
+ kind: WatchFolderKind;
+ /** Absolute path of the watched folder. Only ever set from the native folder dialog (or a seeded config file). */
+ path: string;
+ paused: boolean;
+ /** Ingest: bin (by name) the imported media goes into. Created when missing. Empty = project root. */
+ bin: string;
+ /** Ingest: also build preview proxies for what is imported. */
+ createProxies: boolean;
+ /** Export: preset id from WATCH_EXPORT_PRESET_IDS. */
+ presetId: string;
+ /** Export: where rendered files go. Absolute. */
+ outputDir: string;
+ /** Export: also render `.oreel` / `.openreel` project files through the editor's export queue. */
+ includeProjects: boolean;
+ /** False until the files already in the folder when it was added have been recorded (and skipped, unless processExisting). */
+ baselined: boolean;
+ /** Also process the files that are already in the folder when it is added. */
+ processExisting: boolean;
+}
+
+export const watchFolderPatchSchema = z
+ .object({
+ paused: z.boolean(),
+ bin: z.string().max(200),
+ createProxies: z.boolean(),
+ presetId: z.enum(WATCH_EXPORT_PRESET_IDS),
+ includeProjects: z.boolean(),
+ processExisting: z.boolean(),
+ })
+ .partial()
+ .strict();
+export type WatchFolderPatch = z.infer<typeof watchFolderPatchSchema>;
+
+export const watchFolderAddArgsSchema = z.object({ kind: z.enum(WATCH_FOLDER_KINDS) });
+export const watchFolderIdArgsSchema = z.object({ id: z.string().min(1) });
+export const watchFolderUpdateArgsSchema = z.object({ id: z.string().min(1), patch: watchFolderPatchSchema });
+export const watchItemIdArgsSchema = z.object({ itemId: z.string().min(1) });
+
+export type WatchItemState =
+ | "detecting" // seen, waiting for the size to stop changing
+ | "queued"
+ | "waiting" // ingest: no project is open in the editor yet
+ | "running"
+ | "done"
+ | "failed"
+ | "duplicate"
+ | "cancelled";
+
+export interface WatchItem {
+ id: string;
+ folderId: string;
+ name: string;
+ path: string;
+ state: WatchItemState;
+ /** 0..1 while running, null when unknown. */
+ progress: number | null;
+ detail?: string;
+ error?: string;
+ outputPath?: string;
+ startedAt?: number;
+ finishedAt?: number;
+ createdAt: number;
+}
+
+export type WatchFolderState = "watching" | "paused" | "missing" | "error";
+
+export interface WatchFolderStatus {
+ state: WatchFolderState;
+ message?: string;
+ detecting: number;
+ queued: number;
+ running: number;
+ done: number;
+ failed: number;
+ duplicates: number;
+}
+
+export interface WatchFoldersSnapshot {
+ folders: Array<{ config: WatchFolderConfig; status: WatchFolderStatus }>;
+ /** Newest first, capped. */
+ items: WatchItem[];
+}
diff --git a/apps/desktop/test/dolby-args.test.ts b/apps/desktop/test/dolby-args.test.ts
new file mode 100644
index 00000000..398eb1ff
--- /dev/null
+++ b/apps/desktop/test/dolby-args.test.ts
@@ -0,0 +1,94 @@
+import { vi } from "vitest";
+
+vi.mock("electron", () => ({ app: { isPackaged: false } }));
+
+import { describe, expect, it } from "vitest";
+import { buildFfmpegArgs, usesPcmAudio, type ExportArgs } from "../src/main/sidecar/export-job";
+import { buildAssembleArgs } from "../src/main/sidecar/smart-export";
+import { buildDolbyStreamArgs, dolbyPlanFromRequest } from "../src/main/sidecar/dolby-args";
+import { resolveExportArgs } from "../src/main/ipc/export";
+
+const ENCODERS = ["libx264", "libx265", "ac3", "eac3", "aac", "prores_ks"];
+const plan = (patch: Partial<Parameters<typeof dolbyPlanFromRequest>[0]> = {}) =>
+ dolbyPlanFromRequest({ audioCodec: "ac3", audioChannels: 6, audioSampleRate: 48000, audioBitrateKbps: 448, ...patch })!;
+
+const request = (patch: Record<string, unknown> = {}) => ({
+ width: 1920, height: 1080, frameRate: 30, codec: "h264", format: "mp4", bitrateKbps: 15000, outputPath: "/tmp/out.mp4",
+ totalFrames: 30, audioSampleRate: 48000, audioChannels: 6, audioCodec: "ac3", audioBitrateKbps: 448, ...patch,
+}) as Parameters<typeof resolveExportArgs>[0];
+const resolve = (patch: Record<string, unknown> = {}, encoders = ENCODERS) => resolveExportArgs(request(patch), "linux", encoders, "/tmp/mix.wav");
+
+const exportArgs = (format: string, dolby = plan()): ExportArgs => ({
+ width: 1280, height: 720, frameRate: 30, codec: "h264", encoder: "libx264", mode: "balanced", quality: 80, bitrateKbps: 5000,
+ outputPath: `/tmp/out.${format}`, audioWavPath: "/tmp/mix.wav", format, dolby,
+});
+
+const audioOptions = (args: string[]): string[] => args.slice(args.indexOf("-i", args.indexOf("-i") + 1) + 2);
+
+describe("Dolby Digital audio track of a video export", () => {
+ it.each([
+ ["mp4", "ac3"],
+ ["mov", "ac3"],
+ ["mkv", "eac3"],
+ ] as const)("%s: encodes the audio with %s, relabels 5.1 by index, and drops the AAC options", (format, codec) => {
+ const args = buildFfmpegArgs(exportArgs(format, plan({ audioCodec: codec, audioBitrateKbps: codec === "eac3" ? 640 : 448 })));
+ const text = args.join(" ");
+ expect(text).toContain("-af channelmap=map=0|1|2|3|4|5:channel_layout=5.1(side)");
+ expect(text).toContain(`-c:a ${codec} -b:a ${codec === "eac3" ? 640 : 448}k -ar 48000 -dialnorm -31`);
+ expect(text).not.toMatch(/-c:a (aac|libopus|pcm)/);
+ expect(args.at(-1)).toBe(`/tmp/out.${format}`);
+ expect(args.includes("+faststart")).toBe(format !== "mkv");
+ expect(args.includes("matroska")).toBe(format === "mkv");
+ });
+
+ it("stereo has no channel filter and keeps the dialnorm", () => {
+ const text = buildFfmpegArgs(exportArgs("mp4", plan({ audioChannels: 2, audioBitrateKbps: 192, dialnorm: -24 }))).join(" ");
+ expect(text).not.toContain("channelmap");
+ expect(text).toContain("-c:a ac3 -b:a 192k -ar 48000 -dialnorm -24");
+ });
+
+ it("does not turn the audio into PCM even beside ProRes in MOV", () => {
+ expect(usesPcmAudio({ format: "mov", codec: "prores" })).toBe(true);
+ expect(usesPcmAudio({ format: "mov", codec: "prores", dolby: plan() })).toBe(false);
+ });
+
+ it("the smart-render assemble pass writes the same Dolby track", () => {
+ const args = buildAssembleArgs({ videoPath: "/tmp/v.ts", audioWavPath: "/tmp/mix.wav", outputPath: "/tmp/o.mp4", frameRate: 30, codec: "avc", audioCodec: "aac", audioBitrateKbps: 192, dolby: plan(), format: "mp4" });
+ const text = args.join(" ");
+ expect(text).toContain("-c:a ac3 -b:a 448k -ar 48000 -dialnorm -31");
+ expect(text).not.toContain("-c:a aac");
+ });
+
+ it("an audio-only job takes a WAV in and writes a raw elementary stream", () => {
+ expect(buildDolbyStreamArgs("/tmp/in.wav", "/tmp/out.ec3", plan({ audioCodec: "eac3", audioBitrateKbps: 1000 }))).toEqual([
+ "-y", "-i", "/tmp/in.wav", "-vn",
+ "-af", "channelmap=map=0|1|2|3|4|5:channel_layout=5.1(side)",
+ "-c:a", "eac3", "-b:a", "1024k", "-ar", "48000", "-dialnorm", "-31",
+ "-f", "eac3", "/tmp/out.ec3",
+ ]);
+ });
+});
+
+describe("resolving a Dolby export request", () => {
+ it("accepts AC-3 and E-AC-3 in MP4, MOV and MKV, snapping the bitrate and the rate", () => {
+ for (const format of ["mp4", "mov", "mkv"]) {
+ const resolved = resolve({ format, audioCodec: "eac3", audioBitrateKbps: 600, audioSampleRate: 96000 });
+ expect(resolved.dolby).toEqual({ codec: "eac3", channels: 6, bitrateKbps: 640, sampleRate: 48000, dialnorm: -31 });
+ }
+ expect(resolve({ dialnorm: -24, audioChannels: 2 }).dolby).toMatchObject({ channels: 2, dialnorm: -24 });
+ });
+
+ it("leaves non-Dolby exports untouched", () => {
+ expect(resolve({ audioCodec: undefined }).dolby).toBeUndefined();
+ });
+
+ it("refuses WebM and MXF, mono, an unknown codec, mono audio tracks, a missing encoder, and MKV with ProRes", () => {
+ expect(() => resolve({ format: "webm", codec: "vp9" })).toThrow(/WebM cannot carry/);
+ expect(() => resolve({ format: "mxf", codec: "dnxhr", audioChannels: 2 })).toThrow(/PCM/);
+ expect(() => resolve({ audioChannels: 1 })).toThrow(/stereo or 5.1/);
+ expect(() => resolve({ audioCodec: "dts" })).toThrow(/Unknown audio codec/);
+ expect(() => resolve({ format: "mov", audioChannels: 6, audioTrackCount: 6 })).toThrow(/mono audio tracks/);
+ expect(() => resolve({}, ENCODERS.filter((e) => e !== "ac3"))).toThrow(/no ac3 encoder/);
+ expect(() => resolve({ format: "mkv", codec: "prores", audioCodec: undefined })).toThrow(/not MKV/);
+ });
+});
diff --git a/apps/desktop/test/dolby-delivery.integration.test.ts b/apps/desktop/test/dolby-delivery.integration.test.ts
new file mode 100644
index 00000000..849578df
--- /dev/null
+++ b/apps/desktop/test/dolby-delivery.integration.test.ts
@@ -0,0 +1,265 @@
+/**
+ * Real-ffmpeg coverage of Dolby Digital / Digital Plus delivery, no Electron. Files are written by the same
+ * `resolveExportArgs` + `ExportJob` (video) and `encodeDolbyAudio` (audio-only) the desktop app runs, then read back:
+ *
+ * - ffprobe: codec_name ac3 / eac3, channels, channel_layout, bit_rate, duration, the `ac-3` / `ec-3` sample entries in
+ * MP4 and MOV, the A_AC3 / A_EAC3 codec ids in MKV;
+ * - the dialnorm parsed out of the AC-3 bitstream information;
+ * - the file decoded back: every channel of a 5.1 mix (a different tone per channel, L R C LFE Ls Rs) arrives on its own
+ * channel at its own level (within 0.5 dB) with no energy from the other tones.
+ *
+ * Runs against the bundled sidecar (apps/desktop/resources/bin) when it is there, else an installed ffmpeg;
+ * ffprobe comes from PATH (Homebrew paths) or next to the ffmpeg. Skipped when either is missing or the ffmpeg has no
+ * ac3 / eac3 encoder.
+ */
+import { vi } from "vitest";
+import { existsSync } from "node:fs";
+import path from "node:path";
+
+const bundled = path.resolve(__dirname, "../resources/bin", `${process.platform}-${process.arch}`, process.platform === "win32" ? "ffmpeg.exe" : "ffmpeg");
+const ffmpegCandidates = [process.env.OPENREEL_FFMPEG_PATH, bundled, "/opt/homebrew/bin/ffmpeg", "/usr/local/bin/ffmpeg", "/usr/bin/ffmpeg"].filter((p): p is string => Boolean(p));
+const ffmpegBin = ffmpegCandidates.find((p) => existsSync(p));
+const ffprobeCandidates = [process.env.OPENREEL_FFPROBE, ffmpegBin && path.join(path.dirname(ffmpegBin), "ffprobe"), "/opt/homebrew/bin/ffprobe", "/usr/local/bin/ffprobe", "/usr/bin/ffprobe"].filter((p): p is string => Boolean(p));
+const ffprobeBin = ffprobeCandidates.find((p) => existsSync(p));
+if (ffmpegBin) process.env.OPENREEL_FFMPEG_PATH = ffmpegBin;
+
+vi.mock("electron", () => ({ app: { isPackaged: false } }));
+
+import { afterAll, beforeAll, describe, expect, it } from "vitest";
+import { execFileSync, spawnSync } from "node:child_process";
+import { mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs";
+import os from "node:os";
+import { ExportJob } from "../src/main/sidecar/export-job";
+import { resolveExportArgs } from "../src/main/ipc/export";
+import { encodeDolbyAudio } from "../src/main/ipc/dolby-audio";
+import { parseEncoders } from "../src/main/sidecar/encoder-probe";
+
+const encoders = ffmpegBin ? parseEncoders(execFileSync(ffmpegBin, ["-hide_banner", "-encoders"]).toString()) : [];
+const enabled = Boolean(ffmpegBin && ffprobeBin && encoders.includes("ac3") && encoders.includes("eac3") && encoders.includes("libx264"));
+const suite = enabled ? describe : describe.skip;
+
+const SR = 48000;
+const SECONDS = 2;
+/** One tone per channel in the L R C LFE Ls Rs order of the 5.1 mixer, and a distinct level for each. */
+const TONES = [300, 500, 700, 60, 1100, 1300];
+const LEVELS = [0.5, 0.4, 0.3, 0.5, 0.2, 0.1];
+const NAMES = ["L", "R", "C", "LFE", "Ls", "Rs"];
+const W = 320;
+const H = 180;
+const FRAMES = 30;
+
+let work = "";
+
+/** 16-bit PCM WAV, one tone per channel. `mask` set = WAVE_FORMAT_EXTENSIBLE (the audio-only path); unset = the plain header the video path writes. */
+function toneWav(file: string, channels: number, mask?: number): ArrayBuffer {
+ const extensible = mask !== undefined;
+ const fmtSize = extensible ? 40 : 16;
+ const frames = SR * SECONDS;
+ const dataSize = frames * channels * 2;
+ const buf = Buffer.alloc(12 + 8 + fmtSize + 8 + dataSize);
+ buf.write("RIFF", 0);
+ buf.writeUInt32LE(buf.length - 8, 4);
+ buf.write("WAVEfmt ", 8);
+ buf.writeUInt32LE(fmtSize, 16);
+ buf.writeUInt16LE(extensible ? 0xfffe : 1, 20);
+ buf.writeUInt16LE(channels, 22);
+ buf.writeUInt32LE(SR, 24);
+ buf.writeUInt32LE(SR * channels * 2, 28);
+ buf.writeUInt16LE(channels * 2, 32);
+ buf.writeUInt16LE(16, 34);
+ if (extensible) {
+ buf.writeUInt16LE(22, 36);
+ buf.writeUInt16LE(16, 38);
+ buf.writeUInt32LE(mask, 40);
+ Buffer.from([0x01, 0, 0, 0, 0, 0, 0x10, 0, 0x80, 0, 0, 0xaa, 0, 0x38, 0x9b, 0x71]).copy(buf, 44);
+ }
+ const at = 20 + fmtSize;
+ buf.write("data", at);
+ buf.writeUInt32LE(dataSize, at + 4);
+ for (let i = 0; i < frames; i++) {
+ for (let c = 0; c < channels; c++) buf.writeInt16LE(Math.round(LEVELS[c] * Math.sin((2 * Math.PI * TONES[c] * i) / SR) * 32767), at + 8 + (i * channels + c) * 2);
+ }
+ writeFileSync(file, buf);
+ return buf.buffer.slice(buf.byteOffset, buf.byteOffset + buf.byteLength) as ArrayBuffer;
+}
+
+interface Probed {
+ streams: Array<Record<string, string | number>>;
+ format: { format_name: string; duration: string };
+}
+function ffprobe(file: string): Probed {
+ return JSON.parse(execFileSync(ffprobeBin!, ["-v", "error", "-show_streams", "-show_format", "-of", "json", file], { maxBuffer: 1 << 24 }).toString()) as Probed;
+}
+const audioStream = (p: Probed) => p.streams.find((s) => s.codec_type === "audio")!;
+
+/** Decoded 6-channel float PCM of the first audio stream. */
+function decode(file: string, channels: number): Float32Array[] {
+ const r = spawnSync(ffmpegBin!, ["-v", "error", "-i", file, "-map", "0:a:0", "-f", "f32le", "-acodec", "pcm_f32le", "-ac", String(channels), "-"], { maxBuffer: 1 << 29 });
+ const all = new Float32Array(r.stdout.buffer.slice(r.stdout.byteOffset, r.stdout.byteOffset + r.stdout.byteLength));
+ return Array.from({ length: channels }, (_, c) => all.filter((_v, i) => i % channels === c));
+}
+
+/** Amplitude of `freq` in the steady middle of a channel (single-bin DFT). */
+function toneAmp(x: Float32Array, freq: number): number {
+ const from = Math.floor(SR * 0.5);
+ const to = Math.floor(SR * 1.5);
+ let re = 0;
+ let im = 0;
+ for (let i = from; i < to; i += 2) {
+ const w = (2 * Math.PI * freq * i) / SR;
+ re += x[i] * Math.cos(w);
+ im += x[i] * Math.sin(w);
+ }
+ return (2 * Math.hypot(re, im)) / ((to - from) / 2);
+}
+
+/** Every channel carries its own tone at its own level (dB error under 0.5) and no other channel's tone. */
+function expectDiscreteChannels(file: string): void {
+ const pcm = decode(file, 6);
+ pcm.forEach((channel, c) => {
+ const own = toneAmp(channel, TONES[c]);
+ const dbError = 20 * Math.log10(own / LEVELS[c]);
+ expect(Math.abs(dbError), `${NAMES[c]} level error ${dbError.toFixed(2)} dB`).toBeLessThan(0.5);
+ TONES.forEach((tone, other) => {
+ if (other !== c) expect(toneAmp(channel, tone), `${NAMES[other]} tone on ${NAMES[c]}`).toBeLessThan(0.01);
+ });
+ });
+}
+
+/** Dialnorm of the first AC-3 syncframe in a raw stream (bsid <= 8: ATSC A/52 bit stream information; E-AC-3 has the same field at a different offset). */
+function ac3Dialnorm(file: string): number | null {
+ const bytes = readFileSync(file);
+ if (bytes[0] !== 0x0b || bytes[1] !== 0x77) return null;
+ let bit = 16 + 16 + 2 + 6; // syncword, crc1, fscod, frmsizecod
+ const read = (n: number): number => {
+ let v = 0;
+ for (let i = 0; i < n; i++, bit++) v = (v << 1) | ((bytes[bit >> 3] >> (7 - (bit & 7))) & 1);
+ return v;
+ };
+ const bsid = read(5);
+ if (bsid > 8) return null;
+ read(3); // bsmod
+ const acmod = read(3);
+ if (acmod & 1 && acmod !== 1) read(2); // cmixlev
+ if (acmod & 4) read(2); // surmixlev
+ if (acmod === 2) read(2); // dsurmod
+ read(1); // lfeon
+ const dialnorm = read(5);
+ return dialnorm === 0 ? -31 : -dialnorm;
+}
+
+interface Delivery {
+ format: "mp4" | "mov" | "mkv";
+ codec: "ac3" | "eac3";
+ channels: 2 | 6;
+ bitrate: number;
+ dialnorm?: number;
+}
+
+/** The real video export: gradient RGBA frames plus the six-channel WAV the native backend writes. */
+async function deliver(name: string, d: Delivery): Promise<string> {
+ const wav = path.join(work, `${name}.wav`);
+ toneWav(wav, d.channels);
+ const out = path.join(work, `${name}.${d.format}`);
+ const args = resolveExportArgs(
+ {
+ width: W, height: H, frameRate: FRAMES / SECONDS, codec: "h264", format: d.format, bitrateKbps: 2000, outputPath: out, totalFrames: FRAMES,
+ audioSampleRate: SR, audioChannels: d.channels, encodeMode: "smallest", quality: 80, audioCodec: d.codec, audioBitrateKbps: d.bitrate,
+ ...(d.dialnorm !== undefined ? { dialnorm: d.dialnorm } : {}),
+ },
+ "linux",
+ encoders.filter((e) => !e.endsWith("_videotoolbox")),
+ wav,
+ );
+ const frame = new Uint8Array(W * H * 4).fill(96);
+ await new Promise<void>((resolve, reject) => {
+ const job = new ExportJob(args, () => {}, resolve, (message) => reject(new Error(message)));
+ job.start();
+ (async () => {
+ for (let i = 0; i < FRAMES; i++) await job.writeFrame(frame);
+ job.endInput();
+ })().catch(reject);
+ });
+ return out;
+}
+
+beforeAll(() => {
+ if (enabled) work = mkdtempSync(path.join(os.tmpdir(), "openreel-dolby-"));
+});
+afterAll(() => {
+ if (work) rmSync(work, { recursive: true, force: true });
+});
+
+suite("Dolby Digital audio in video files, verified with ffprobe and by decoding", () => {
+ it.each([
+ ["mp4", "ac3", 448, "ac-3"],
+ ["mov", "ac3", 640, "ac-3"],
+ ["mp4", "eac3", 640, "ec-3"],
+ ["mov", "eac3", 1024, "ec-3"],
+ ] as const)("5.1 %s with %s at %i kbps: codec, six channels, 5.1(side), bit rate, sample entry %s, duration, every channel on its own slot", async (format, codec, bitrate, entry) => {
+ const out = await deliver(`v51-${format}-${codec}-${bitrate}`, { format, codec, channels: 6, bitrate });
+ const p = ffprobe(out);
+ expect(audioStream(p)).toMatchObject({ codec_name: codec, codec_tag_string: entry, channels: 6, channel_layout: "5.1(side)", sample_rate: "48000" });
+ expect(Number(audioStream(p).bit_rate)).toBe(bitrate * 1000);
+ expect(Math.abs(Number(p.format.duration) - SECONDS)).toBeLessThan(0.1);
+ expect(p.streams.some((s) => s.codec_name === "h264")).toBe(true);
+ expectDiscreteChannels(out);
+ }, 120_000);
+
+ it("5.1 MKV with AC-3 and with E-AC-3: Matroska codec ids, six channels, levels per channel", async () => {
+ for (const codec of ["ac3", "eac3"] as const) {
+ const out = await deliver(`v51-mkv-${codec}`, { format: "mkv", codec, channels: 6, bitrate: codec === "ac3" ? 448 : 640 });
+ const p = ffprobe(out);
+ expect(String(p.format.format_name)).toContain("matroska");
+ expect(audioStream(p)).toMatchObject({ codec_name: codec, channels: 6, channel_layout: "5.1(side)" });
+ expect(Number(audioStream(p).bit_rate)).toBe(codec === "ac3" ? 448_000 : 640_000);
+ expect(readFileSync(out).includes(Buffer.from(codec === "ac3" ? "A_AC3" : "A_EAC3"))).toBe(true);
+ expectDiscreteChannels(out);
+ }
+ }, 120_000);
+
+ it("stereo AC-3 and E-AC-3: two channels, stereo layout, the requested bit rate", async () => {
+ for (const [codec, bitrate] of [["ac3", 192], ["eac3", 256]] as const) {
+ const out = await deliver(`v2-${codec}`, { format: "mp4", codec, channels: 2, bitrate });
+ const s = audioStream(ffprobe(out));
+ expect(s).toMatchObject({ codec_name: codec, channels: 2, channel_layout: "stereo" });
+ expect(Number(s.bit_rate)).toBe(bitrate * 1000);
+ const pcm = decode(out, 2);
+ expect(Math.abs(20 * Math.log10(toneAmp(pcm[0], TONES[0]) / LEVELS[0]))).toBeLessThan(0.5);
+ expect(Math.abs(20 * Math.log10(toneAmp(pcm[1], TONES[1]) / LEVELS[1]))).toBeLessThan(0.5);
+ }
+ }, 120_000);
+});
+
+suite("raw .ac3 / .ec3 audio-only export through encodeDolbyAudio", () => {
+ const plan = (codec: "ac3" | "eac3", channels: 2 | 6, bitrateKbps: number, dialnorm: number) => ({ codec, channels, bitrateKbps, sampleRate: 48000, dialnorm });
+
+ it.each([
+ ["ac3", 6, 448, -27],
+ ["ac3", 6, 640, -24],
+ ["ac3", 2, 192, -31],
+ ["eac3", 6, 1024, -24],
+ ["eac3", 2, 256, -1],
+ ] as const)("%s, %i channels, %i kbps, dialnorm %i: ffprobe, duration, channel levels", async (codec, channels, bitrate, dialnorm) => {
+ const wavFile = path.join(work, `a-${codec}-${channels}.wav`);
+ const wav = toneWav(wavFile, channels, channels === 6 ? 0x3f : 0x3);
+ const bytes = new Uint8Array(await encodeDolbyAudio({ ...plan(codec, channels, bitrate, dialnorm), wav }));
+ const out = path.join(work, `a-${codec}-${channels}-${bitrate}.${codec === "eac3" ? "ec3" : "ac3"}`);
+ writeFileSync(out, bytes);
+ const p = ffprobe(out);
+ expect(audioStream(p)).toMatchObject({ codec_name: codec, channels, channel_layout: channels === 6 ? "5.1(side)" : "stereo", sample_rate: "48000" });
+ expect(Number(audioStream(p).bit_rate)).toBe(bitrate * 1000);
+ expect(Math.abs(Number(p.format.duration) - SECONDS)).toBeLessThan(0.1);
+ if (codec === "ac3") expect(ac3Dialnorm(out)).toBe(dialnorm);
+ if (channels === 6) expectDiscreteChannels(out);
+ }, 120_000);
+
+ it("a 44.1 kHz request is written at 44.1 kHz", async () => {
+ const wavFile = path.join(work, "a-441.wav");
+ const wav = toneWav(wavFile, 2, 0x3);
+ const bytes = new Uint8Array(await encodeDolbyAudio({ ...plan("ac3", 2, 192, -31), sampleRate: 44100, wav }));
+ const out = path.join(work, "a-441.ac3");
+ writeFileSync(out, bytes);
+ expect(audioStream(ffprobe(out))).toMatchObject({ codec_name: "ac3", sample_rate: "44100" });
+ }, 60_000);
+});
diff --git a/apps/desktop/test/watch-editor-handlers.test.ts b/apps/desktop/test/watch-editor-handlers.test.ts
new file mode 100644
index 00000000..2b178f98
--- /dev/null
+++ b/apps/desktop/test/watch-editor-handlers.test.ts
@@ -0,0 +1,151 @@
+import fs from "node:fs";
+import os from "node:os";
+import path from "node:path";
+import { describe, expect, it } from "vitest";
+import type { WatchFolderConfig } from "../src/shared/watch-folders";
+import { recordedMediaDirs, ensureBin, ingestIntoOpenProject, renderProjectViaEditor, type ToolCaller, type ToolResultLike } from "../src/main/watch/editor-handlers";
+
+const folder = (extra: Partial<WatchFolderConfig> = {}): WatchFolderConfig => ({
+ id: "f1", kind: "ingest", path: "/watch", paused: false, bin: "Cards", createProxies: false, presetId: "1080p-high", outputDir: "/out", includeProjects: true, baselined: true, processExisting: false, ...extra,
+});
+const file = { path: "/watch/a.mp4", name: "a.mp4", size: 10, mtimeMs: 1 };
+const signal = new AbortController().signal;
+
+function caller(handler: (name: string, args: Record<string, unknown>) => ToolResultLike, hasEditor = true): ToolCaller & { calls: Array<{ name: string; args: Record<string, unknown> }> } {
+ const calls: Array<{ name: string; args: Record<string, unknown> }> = [];
+ return { calls, hasEditor: () => hasEditor, call: async (name, args) => (calls.push({ name, args }), handler(name, args)) };
+}
+const NO_PROJECT: ToolResultLike = { ok: false, error: { code: "NO_PROJECT", message: "No project is open" } };
+
+describe("ensureBin", () => {
+ it("reuses a top-level bin by name, case-insensitively", async () => {
+ const c = caller(() => ({ ok: true, data: { bins: [{ id: "b1", name: "cards" }, { id: "b2", name: "Cards", parentId: "b1" }] } }));
+ expect(await ensureBin(c, "Cards")).toBe("b1");
+ expect(c.calls.map((x) => x.name)).toEqual(["list_bins"]);
+ });
+ it("creates the bin when it is missing", async () => {
+ const c = caller((name) => (name === "list_bins" ? { ok: true, data: { bins: [] } } : { ok: true, data: { binId: "new" } }));
+ expect(await ensureBin(c, " Cards ")).toBe("new");
+ expect(c.calls[1]).toEqual({ name: "create_bin", args: { name: "Cards" } });
+ });
+ it("returns null when no project is open", async () => {
+ expect(await ensureBin(caller(() => NO_PROJECT), "Cards")).toBeNull();
+ });
+});
+
+describe("ingestIntoOpenProject", () => {
+ it("imports into the bin with proxies when asked", async () => {
+ const c = caller((name) => {
+ if (name === "list_bins") return { ok: true, data: { bins: [{ id: "b1", name: "Cards" }] } };
+ return { ok: true, data: { imported: [{ mediaId: "m1" }] } };
+ });
+ const result = await ingestIntoOpenProject(c, { folder: folder({ createProxies: true }), file, signal });
+ expect(result).toEqual({ outcome: "imported", detail: 'Imported into "Cards" (proxies queued)' });
+ expect(c.calls.at(-1)).toEqual({ name: "import_media_from_path", args: { paths: ["/watch/a.mp4"], bin: "b1", createProxies: true } });
+ });
+
+ it("imports to the project root when no bin is configured", async () => {
+ const c = caller(() => ({ ok: true, data: { imported: [{ mediaId: "m1" }] } }));
+ await ingestIntoOpenProject(c, { folder: folder({ bin: "" }), file, signal });
+ expect(c.calls).toEqual([{ name: "import_media_from_path", args: { paths: ["/watch/a.mp4"] } }]);
+ });
+
+ it("waits instead of failing when there is no editor window or no open project", async () => {
+ expect(await ingestIntoOpenProject(caller(() => ({ ok: true }), false), { folder: folder(), file, signal })).toMatchObject({ outcome: "waiting" });
+ expect(await ingestIntoOpenProject(caller(() => NO_PROJECT), { folder: folder(), file, signal })).toMatchObject({ outcome: "waiting" });
+ const c = caller((name) => (name === "list_bins" ? { ok: true, data: { bins: [{ id: "b", name: "Cards" }] } } : NO_PROJECT));
+ expect(await ingestIntoOpenProject(c, { folder: folder(), file, signal })).toMatchObject({ outcome: "waiting" });
+ });
+
+ it("fails with the editor's reason when the import is refused", async () => {
+ const c = caller((name) => (name === "list_bins" ? { ok: true, data: { bins: [{ id: "b", name: "Cards" }] } } : { ok: false, error: { code: "UNSUPPORTED_TYPE", message: "OpenReel could not decode this file." } }));
+ await expect(ingestIntoOpenProject(c, { folder: folder(), file, signal })).rejects.toThrow("could not decode");
+ });
+});
+
+describe("renderProjectViaEditor", () => {
+ const deps = { sleep: async () => undefined, pollMs: 0, timeoutMs: 60_000 };
+ const out = fs.mkdtempSync(path.join(os.tmpdir(), "watch-handlers-"));
+ const projectFolder = folder({ kind: "export", outputDir: out });
+ const projectFile = { path: "/watch/cut.oreel", name: "cut.oreel", size: 10, mtimeMs: 1 };
+
+ it("opens the project, queues the export with the preset and waits for the queue job", async () => {
+ let polls = 0;
+ const progress: Array<number | null> = [];
+ const c = caller((name) => {
+ if (name === "open_project_file") return { ok: true, data: { name: "cut" } };
+ if (name === "queue_export") return { ok: true, data: { jobId: "j1" } };
+ polls++;
+ return { ok: true, data: { jobs: [{ id: "j1", status: polls < 3 ? "running" : "completed", progress: polls / 3, outputPath: path.join(out, "cut.mp4") }] } };
+ });
+ const result = await renderProjectViaEditor(c, { folder: projectFolder, file: projectFile, signal, onProgress: (f) => progress.push(f) }, deps);
+ expect(result).toEqual({ outputPath: path.join(out, "cut.mp4") });
+ expect(fs.existsSync(out)).toBe(true);
+ expect(c.calls[0]).toEqual({ name: "open_project_file", args: { path: "/watch/cut.oreel" } });
+ expect(c.calls[1]).toMatchObject({ name: "queue_export", args: { presetId: "1080p-high", overwrite: false, start: true } });
+ expect((c.calls[1].args.outputPath as string).endsWith("cut.mp4")).toBe(true);
+ expect(progress.length).toBeGreaterThan(0);
+ });
+
+ it("searches for offline media and retries the export when the editor reports it offline", async () => {
+ let queues = 0;
+ const c = caller((name) => {
+ if (name === "open_project_file") return { ok: true };
+ if (name === "relink_media") return { ok: true };
+ if (name === "queue_export") return ++queues < 3 ? { ok: false, error: { message: "Relink the original media before exporting: a.mp4" } } : { ok: true, data: { jobId: "j2" } };
+ return { ok: true, data: { jobs: [{ id: "j2", status: "completed", outputPath: path.join(out, "cut.mp4") }] } };
+ });
+ await renderProjectViaEditor(c, { folder: projectFolder, file: projectFile, signal, onProgress: () => undefined }, deps);
+ expect(c.calls.filter((call) => call.name === "relink_media").map((call) => call.args)).toEqual([{ folder: "/watch" }]);
+ expect(queues).toBe(3);
+ // An offline-media failure reported by the queue job (not the queue call) retries the same way.
+ let jobRuns = 0;
+ const viaJob = caller((name) => {
+ if (name === "queue_export") return { ok: true, data: { jobId: `j${++jobRuns}` } };
+ if (name === "list_export_jobs") return { ok: true, data: { jobs: [{ id: `j${jobRuns}`, status: jobRuns < 2 ? "failed" : "completed", error: "Relink the original media before exporting: a.mp4", outputPath: path.join(out, "cut.mp4") }] } };
+ return { ok: true };
+ });
+ await renderProjectViaEditor(viaJob, { folder: projectFolder, file: projectFile, signal, onProgress: () => undefined }, deps);
+ expect(jobRuns).toBe(2);
+ const stuck = caller((name) => (name === "queue_export" ? { ok: false, error: { message: "Relink the original media before exporting: a.mp4" } } : { ok: true }));
+ await expect(renderProjectViaEditor(stuck, { folder: projectFolder, file: projectFile, signal, onProgress: () => undefined }, deps)).rejects.toThrow(/Relink the original media/);
+ });
+
+ it("fails with the job's error, and refuses the audio-only preset", async () => {
+ const failing = caller((name) => {
+ if (name === "open_project_file") return { ok: true };
+ if (name === "queue_export") return { ok: true, data: { jobId: "j1" } };
+ return { ok: true, data: { jobs: [{ id: "j1", status: "failed", error: "Encoder failed" }] } };
+ });
+ await expect(renderProjectViaEditor(failing, { folder: projectFolder, file: projectFile, signal, onProgress: () => undefined }, deps)).rejects.toThrow("Encoder failed");
+ await expect(renderProjectViaEditor(caller(() => ({ ok: true })), { folder: folder({ kind: "export", presetId: "wav", outputDir: out }), file: projectFile, signal, onProgress: () => undefined }, deps)).rejects.toThrow(/video preset/);
+ });
+
+ it("surfaces a project that will not open", async () => {
+ const c = caller(() => ({ ok: false, error: { code: "UNREADABLE", message: "Not a valid project file" } }));
+ await expect(renderProjectViaEditor(c, { folder: projectFolder, file: projectFile, signal, onProgress: () => undefined }, deps)).rejects.toThrow("Not a valid project file");
+ });
+
+ it("cancels the queue job when aborted", async () => {
+ const controller = new AbortController();
+ const c = caller((name) => {
+ if (name === "open_project_file") return { ok: true };
+ if (name === "queue_export") return { ok: true, data: { jobId: "j9" } };
+ if (name === "list_export_jobs") {
+ controller.abort();
+ return { ok: true, data: { jobs: [{ id: "j9", status: "running", progress: 0.1 }] } };
+ }
+ return { ok: true };
+ });
+ await expect(renderProjectViaEditor(c, { folder: projectFolder, file: projectFile, signal: controller.signal, onProgress: () => undefined }, deps)).rejects.toThrow("Cancelled");
+ expect(c.calls.at(-1)).toEqual({ name: "cancel_export_job", args: { jobId: "j9" } });
+ });
+});
+
+describe("recordedMediaDirs", () => {
+ it("collects the folders of the media paths a project records, wherever the wrapper puts them", () => {
+ const project = { project: { mediaLibrary: { items: [{ sourceFile: { path: "/Volumes/A/clips/a.mp4" } }, { sourceFile: { path: "/Volumes/A/clips/b.mp4" } }, { sourceFile: { path: "relative.mp4" } }, { sourceFile: {} }] } } };
+ expect(recordedMediaDirs(JSON.stringify(project))).toEqual(["/Volumes/A/clips"]);
+ expect(recordedMediaDirs("not json")).toEqual([]);
+ });
+});
diff --git a/apps/desktop/test/watch-folder-manager.test.ts b/apps/desktop/test/watch-folder-manager.test.ts
new file mode 100644
index 00000000..a1d5c361
--- /dev/null
+++ b/apps/desktop/test/watch-folder-manager.test.ts
@@ -0,0 +1,438 @@
+import fs from "node:fs";
+import os from "node:os";
+import path from "node:path";
+import { vi, afterEach, beforeEach, describe, expect, it } from "vitest";
+import type { WatchFolderConfig, WatchFoldersSnapshot } from "../src/shared/watch-folders";
+import { Ledger, fingerprintFile, type LedgerStore } from "../src/main/watch/ledger";
+import { WatchFolderManager, type ConfigStore, type FolderContext, type IngestOutcome, type WatchHandlers } from "../src/main/watch/manager";
+import { createFileConfigStore } from "../src/main/watch/ipc";
+
+// These tests wait on real timers and folders; a loaded machine (the full parallel suite) needs more than 5 s.
+vi.setConfig({ testTimeout: 30_000 });
+
+const sleep = (ms: number) => new Promise((resolve) => setTimeout(resolve, ms));
+async function until(label: string, check: () => boolean, timeout = 15000): Promise<void> {
+ const start = Date.now();
+ while (!check()) {
+ if (Date.now() - start > timeout) throw new Error(`timed out waiting for ${label}`);
+ await sleep(15);
+ }
+}
+
+const OPTIONS = {
+ scanner: { settleMs: 150, pollMs: 40, rescanMs: 250, debounceMs: 20 },
+ retryWaitMs: 150,
+ emitThrottleMs: 10,
+};
+
+let root = "";
+let managers: WatchFolderManager[] = [];
+beforeEach(() => {
+ root = fs.realpathSync(fs.mkdtempSync(path.join(os.tmpdir(), "watch-mgr-")));
+});
+afterEach(() => {
+ for (const manager of managers) manager.stop();
+ managers = [];
+ fs.rmSync(root, { recursive: true, force: true });
+});
+
+function memoryConfig(initial: WatchFolderConfig[] = []): ConfigStore & { saved: WatchFolderConfig[] } {
+ const store = { saved: initial, load: () => store.saved.map((f) => ({ ...f })), save: (folders: WatchFolderConfig[]) => void (store.saved = folders.map((f) => ({ ...f }))) };
+ return store;
+}
+function memoryLedger(shared?: { data: unknown }): Ledger {
+ const box = shared ?? { data: {} };
+ const store: LedgerStore = { load: () => box.data as never, save: (data) => void (box.data = JSON.parse(JSON.stringify(data))) };
+ return new Ledger(store);
+}
+
+interface Harness {
+ manager: WatchFolderManager;
+ config: ReturnType<typeof memoryConfig>;
+ snapshots: WatchFoldersSnapshot[];
+ ingested: string[];
+ rendered: string[];
+ roots: string[][];
+}
+
+function build(options: {
+ handlers?: Partial<WatchHandlers>;
+ config?: ReturnType<typeof memoryConfig>;
+ ledger?: Ledger;
+}): Harness {
+ const ingested: string[] = [];
+ const rendered: string[] = [];
+ const snapshots: WatchFoldersSnapshot[] = [];
+ const roots: string[][] = [];
+ const config = options.config ?? memoryConfig();
+ const handlers: WatchHandlers = {
+ ingest: async ({ file }: FolderContext): Promise<IngestOutcome> => {
+ ingested.push(file.name);
+ return { outcome: "imported" };
+ },
+ renderMedia: async ({ file, folder }) => {
+ rendered.push(file.name);
+ fs.mkdirSync(folder.outputDir, { recursive: true });
+ const out = path.join(folder.outputDir, `${path.basename(file.name, path.extname(file.name))}.mp4`);
+ fs.writeFileSync(out, `rendered ${file.name}`);
+ return { outputPath: out };
+ },
+ renderProject: async ({ file, folder }) => {
+ rendered.push(file.name);
+ const out = path.join(folder.outputDir, "project.mp4");
+ fs.mkdirSync(folder.outputDir, { recursive: true });
+ fs.writeFileSync(out, "project render");
+ return { outputPath: out };
+ },
+ ...options.handlers,
+ };
+ const manager = new WatchFolderManager({ configStore: config, ledger: options.ledger ?? memoryLedger(), handlers, emit: (s) => snapshots.push(s), onRoots: (r) => roots.push(r), options: OPTIONS });
+ managers.push(manager);
+ manager.start();
+ return { manager, config, snapshots, ingested, rendered, roots };
+}
+
+const itemsOf = (h: Harness) => h.manager.snapshot().items;
+const makeDir = (name: string): string => {
+ const dir = path.join(root, name);
+ fs.mkdirSync(dir, { recursive: true });
+ return dir;
+};
+
+describe("ingest watch folders", () => {
+ it("imports a file dropped into the folder, once it has finished copying", async () => {
+ const dir = makeDir("in");
+ const h = build({});
+ await h.manager.add("ingest", dir, { bin: "Dailies" });
+ await sleep(120);
+ fs.writeFileSync(path.join(dir, "a.mp4"), "video bytes");
+ await until("imported", () => h.ingested.length === 1);
+ await until("item done", () => itemsOf(h).some((i) => i.state === "done"));
+ expect(h.ingested).toEqual(["a.mp4"]);
+ expect(fs.existsSync(path.join(dir, "a.mp4"))).toBe(true); // ingest never moves originals
+ const snapshot = h.manager.snapshot();
+ expect(snapshot.folders[0].status).toMatchObject({ state: "watching", done: 1, failed: 0 });
+ expect(h.roots.at(-1)).toContain(dir);
+ });
+
+ it("skips files that were already in the folder when it was added (baseline) unless processExisting is set", async () => {
+ const plain = makeDir("plain");
+ const eager = makeDir("eager");
+ fs.writeFileSync(path.join(plain, "existing.mp4"), "old");
+ fs.writeFileSync(path.join(eager, "existing2.mp4"), "old too");
+ const h = build({});
+ await h.manager.add("ingest", plain);
+ await h.manager.add("ingest", eager, { processExisting: true });
+ await until("existing2 imported", () => h.ingested.includes("existing2.mp4"));
+ await sleep(500);
+ expect(h.ingested).toEqual(["existing2.mp4"]);
+ fs.writeFileSync(path.join(plain, "new.mp4"), "new");
+ await until("new imported", () => h.ingested.includes("new.mp4"));
+ });
+
+ it("ignores files that are not media", async () => {
+ const dir = makeDir("in");
+ const h = build({});
+ await h.manager.add("ingest", dir);
+ fs.writeFileSync(path.join(dir, "notes.txt"), "text");
+ fs.writeFileSync(path.join(dir, "real.mov"), "movie");
+ await until("movie imported", () => h.ingested.length === 1);
+ await sleep(400);
+ expect(h.ingested).toEqual(["real.mov"]);
+ expect(itemsOf(h).map((i) => i.name)).toEqual(["real.mov"]);
+ });
+
+ it("keeps a file waiting while no project is open and imports it when one is", async () => {
+ const dir = makeDir("in");
+ let projectOpen = false;
+ const attempts: boolean[] = [];
+ const h = build({
+ handlers: {
+ ingest: async ({ file }) => {
+ attempts.push(projectOpen);
+ if (!projectOpen) return { outcome: "waiting", detail: "Waiting for a project to be open" };
+ return { outcome: "imported" };
+ },
+ },
+ });
+ await h.manager.add("ingest", dir);
+ await sleep(100);
+ fs.writeFileSync(path.join(dir, "late.mp4"), "bytes");
+ await until("waiting", () => itemsOf(h).some((i) => i.state === "waiting"));
+ expect(itemsOf(h)[0].detail).toMatch(/project/);
+ await sleep(400);
+ expect(attempts.filter(Boolean)).toHaveLength(0);
+ expect(attempts.length).toBeGreaterThan(1); // it keeps retrying
+ projectOpen = true;
+ await until("done", () => itemsOf(h).some((i) => i.state === "done"));
+ });
+
+ it("marks an ingest failure and lets the user retry it", async () => {
+ const dir = makeDir("in");
+ let fail = true;
+ const h = build({
+ handlers: {
+ ingest: async () => {
+ if (fail) throw new Error("The editor could not decode this file.");
+ return { outcome: "imported" };
+ },
+ },
+ });
+ await h.manager.add("ingest", dir);
+ await sleep(100);
+ fs.writeFileSync(path.join(dir, "bad.mp4"), "bytes");
+ await until("failed", () => itemsOf(h).some((i) => i.state === "failed"));
+ expect(itemsOf(h)[0].error).toMatch(/decode/);
+ await sleep(500);
+ expect(itemsOf(h)).toHaveLength(1); // not retried in a loop
+ fail = false;
+ await h.manager.retry(itemsOf(h)[0].id);
+ await until("done after retry", () => itemsOf(h).some((i) => i.state === "done"));
+ });
+
+ it("does not import the same file twice: re-seen after a restart is silent, a renamed copy is a visible duplicate", async () => {
+ const dir = makeDir("in");
+ const ledgerBox = { data: {} as unknown };
+ const config = memoryConfig();
+ const first = build({ config, ledger: memoryLedger(ledgerBox) });
+ await first.manager.add("ingest", dir);
+ await sleep(100);
+ fs.writeFileSync(path.join(dir, "take1.mp4"), "identical content");
+ await until("imported", () => first.ingested.length === 1);
+ first.manager.stop();
+
+ // "Restart": a new manager over the same persisted config and ledger.
+ const second = build({ config, ledger: memoryLedger(ledgerBox) });
+ await sleep(700);
+ expect(second.ingested).toEqual([]); // take1.mp4 is not imported again
+ expect(itemsOf(second)).toHaveLength(0);
+
+ fs.copyFileSync(path.join(dir, "take1.mp4"), path.join(dir, "take1-copy.mp4"));
+ await until("duplicate item", () => itemsOf(second).some((i) => i.state === "duplicate"));
+ expect(second.ingested).toEqual([]);
+ expect(itemsOf(second)[0]).toMatchObject({ name: "take1-copy.mp4", state: "duplicate" });
+ });
+
+ it("picks up files that arrived while the app was closed", async () => {
+ const dir = makeDir("in");
+ const config = memoryConfig();
+ const first = build({ config });
+ await first.manager.add("ingest", dir);
+ await sleep(200); // baselined (empty)
+ first.manager.stop();
+ fs.writeFileSync(path.join(dir, "while-closed.mp4"), "dropped while closed");
+ const second = build({ config });
+ await until("imported at startup", () => second.ingested.includes("while-closed.mp4"));
+ });
+
+ it("pauses and resumes a folder", async () => {
+ const dir = makeDir("in");
+ const h = build({});
+ const folder = await h.manager.add("ingest", dir);
+ await sleep(100);
+ await h.manager.update(folder.id, { paused: true });
+ fs.writeFileSync(path.join(dir, "while-paused.mp4"), "bytes");
+ await sleep(600);
+ expect(h.ingested).toEqual([]);
+ expect(h.manager.snapshot().folders[0].status.state).toBe("paused");
+ expect(h.config.saved[0].paused).toBe(true);
+ await h.manager.update(folder.id, { paused: false });
+ await until("imported after resume", () => h.ingested.length === 1);
+ expect(h.manager.snapshot().folders[0].status.state).toBe("watching");
+ });
+
+ it("reports a folder that disappears as missing", async () => {
+ const dir = makeDir("in");
+ const h = build({});
+ await h.manager.add("ingest", dir);
+ await sleep(100);
+ fs.rmSync(dir, { recursive: true, force: true });
+ await until("missing", () => h.manager.snapshot().folders[0].status.state === "missing");
+ expect(h.manager.snapshot().folders[0].status.message).toMatch(/missing|mounted/);
+ });
+});
+
+describe("export watch folders", () => {
+ it("renders a dropped file, writes to the output folder and moves the source to done/", async () => {
+ const dir = makeDir("export");
+ const out = makeDir("rendered");
+ const h = build({});
+ await h.manager.add("export", dir, { outputDir: out, presetId: "1080p-high" });
+ await sleep(100);
+ fs.writeFileSync(path.join(dir, "interview.mov"), "raw camera file");
+ await until("done", () => itemsOf(h).some((i) => i.state === "done"));
+ expect(h.rendered).toEqual(["interview.mov"]);
+ expect(fs.readFileSync(path.join(out, "interview.mp4"), "utf8")).toBe("rendered interview.mov");
+ expect(fs.existsSync(path.join(dir, "interview.mov"))).toBe(false);
+ expect(fs.existsSync(path.join(dir, "done", "interview.mov"))).toBe(true);
+ expect(itemsOf(h)[0].outputPath).toBe(path.join(out, "interview.mp4"));
+ });
+
+ it("moves a source whose render failed to failed/ with the reason, and does not retry it in a loop", async () => {
+ const dir = makeDir("export");
+ const h = build({
+ handlers: {
+ renderMedia: async () => {
+ throw new Error("ffmpeg exited with code 1: Invalid data found");
+ },
+ },
+ });
+ await h.manager.add("export", dir, { outputDir: path.join(root, "out") });
+ await sleep(100);
+ fs.writeFileSync(path.join(dir, "broken.mov"), "garbage");
+ await until("failed", () => itemsOf(h).some((i) => i.state === "failed"));
+ expect(fs.existsSync(path.join(dir, "failed", "broken.mov"))).toBe(true);
+ expect(fs.readFileSync(path.join(dir, "failed", "broken.mov.error.txt"), "utf8")).toMatch(/Invalid data/);
+ expect(fs.existsSync(path.join(dir, "broken.mov"))).toBe(false);
+ await sleep(500);
+ expect(itemsOf(h)).toHaveLength(1);
+ });
+
+ it("treats a second drop of the same content as a duplicate: no second render, moved to done/", async () => {
+ const dir = makeDir("export");
+ const h = build({});
+ await h.manager.add("export", dir, { outputDir: path.join(root, "out") });
+ await sleep(100);
+ fs.writeFileSync(path.join(dir, "a.mov"), "same bytes in both");
+ await until("first done", () => itemsOf(h).some((i) => i.state === "done"));
+ fs.writeFileSync(path.join(dir, "b.mov"), "same bytes in both");
+ await until("duplicate", () => itemsOf(h).some((i) => i.state === "duplicate"));
+ expect(h.rendered).toEqual(["a.mov"]);
+ expect(fs.readdirSync(path.join(dir, "done")).sort()).toEqual(["a.mov", "b.mov"]);
+ });
+
+ it("renders one file at a time and keeps the output of each", async () => {
+ const dir = makeDir("export");
+ const out = makeDir("out");
+ let active = 0;
+ let peak = 0;
+ const h = build({
+ handlers: {
+ renderMedia: async ({ file, folder }) => {
+ active++;
+ peak = Math.max(peak, active);
+ await sleep(120);
+ active--;
+ const target = path.join(folder.outputDir, `${path.basename(file.name, ".mov")}.mp4`);
+ fs.writeFileSync(target, "x");
+ return { outputPath: target };
+ },
+ },
+ });
+ await h.manager.add("export", dir, { outputDir: out });
+ await sleep(100);
+ for (const name of ["one.mov", "two.mov", "three.mov"]) fs.writeFileSync(path.join(dir, name), `bytes of ${name}`);
+ await until("all done", () => itemsOf(h).filter((i) => i.state === "done").length === 3, 10000);
+ expect(peak).toBe(1);
+ expect(fs.readdirSync(out).sort()).toEqual(["one.mp4", "three.mp4", "two.mp4"]);
+ });
+
+ it("only renders project files when the folder opts in", async () => {
+ const dir = makeDir("export");
+ const out = makeDir("out");
+ const h = build({});
+ const folder = await h.manager.add("export", dir, { outputDir: out });
+ await sleep(100);
+ fs.writeFileSync(path.join(dir, "cut.oreel"), "{}");
+ await sleep(600);
+ expect(h.rendered).toEqual([]);
+ expect(fs.existsSync(path.join(dir, "cut.oreel"))).toBe(true);
+ await h.manager.update(folder.id, { includeProjects: true });
+ fs.writeFileSync(path.join(dir, "cut2.oreel"), "{ \"v\": 2 }");
+ await until("project rendered", () => h.rendered.includes("cut2.oreel"));
+ });
+
+ it("ignores files that are not video or audio", async () => {
+ const dir = makeDir("export");
+ const h = build({});
+ await h.manager.add("export", dir, { outputDir: path.join(root, "out") });
+ await sleep(100);
+ fs.writeFileSync(path.join(dir, "readme.txt"), "text");
+ fs.writeFileSync(path.join(dir, "still.png"), "image");
+ await sleep(700);
+ expect(h.rendered).toEqual([]);
+ expect(itemsOf(h)).toHaveLength(0);
+ expect(fs.existsSync(path.join(dir, "readme.txt"))).toBe(true);
+ });
+
+ it("keeps queued jobs of a paused folder until it is resumed, and drops a removed folder's jobs", async () => {
+ const dir = makeDir("export");
+ const gate: { release: () => void } = { release: () => undefined };
+ const h = build({
+ handlers: {
+ renderMedia: async ({ file, folder }) => {
+ await new Promise<void>((resolve) => (gate.release = resolve));
+ const out = path.join(folder.outputDir, `${file.name}.mp4`);
+ fs.mkdirSync(folder.outputDir, { recursive: true });
+ fs.writeFileSync(out, "x");
+ return { outputPath: out };
+ },
+ },
+ });
+ const folder = await h.manager.add("export", dir, { outputDir: path.join(root, "out") });
+ await sleep(100);
+ fs.writeFileSync(path.join(dir, "a.mov"), "aaa");
+ fs.writeFileSync(path.join(dir, "b.mov"), "bbb");
+ await until("a running", () => itemsOf(h).some((i) => i.state === "running"));
+ await h.manager.update(folder.id, { paused: true });
+ gate.release();
+ await until("a done", () => itemsOf(h).some((i) => i.state === "done"));
+ await sleep(500);
+ // b was detected before the pause or not at all; either way it must not be rendered while paused.
+ expect(itemsOf(h).filter((i) => i.state === "running")).toHaveLength(0);
+ h.manager.remove(folder.id);
+ expect(h.manager.snapshot().folders).toHaveLength(0);
+ expect(itemsOf(h)).toHaveLength(0);
+ expect(h.config.saved).toHaveLength(0);
+ });
+});
+
+describe("validation and persistence", () => {
+ it("refuses folders that would loop or overlap", async () => {
+ const a = makeDir("a");
+ const b = makeDir("b");
+ const h = build({});
+ await h.manager.add("export", a, { outputDir: b });
+ await expect(h.manager.add("ingest", b)).rejects.toThrow(/output of an export watch folder/);
+ await expect(h.manager.add("ingest", a)).rejects.toThrow(/already being watched/);
+ await expect(h.manager.add("export", makeDir("c"), { outputDir: a })).rejects.toThrow(/picked up again/);
+ await expect(h.manager.add("export", makeDir("d"), { outputDir: path.join(root, "d") })).rejects.toThrow(/watched folder itself/);
+ await expect(h.manager.add("ingest", path.join(root, "nope"))).rejects.toThrow(/does not exist/);
+ });
+
+ it("persists the folder list and survives a restart", async () => {
+ const dir = makeDir("in");
+ const file = path.join(root, "cfg", "watch-folders.json");
+ const store = createFileConfigStore(file);
+ const first = build({ config: store as ReturnType<typeof memoryConfig> });
+ const added = await first.manager.add("ingest", dir, { bin: "Cards" });
+ await sleep(150); // the first scan records the baseline
+ await first.manager.update(added.id, { createProxies: true, paused: true });
+ first.manager.stop();
+ const second = build({ config: createFileConfigStore(file) as ReturnType<typeof memoryConfig> });
+ const [loaded] = second.manager.snapshot().folders;
+ expect(loaded.config).toMatchObject({ id: added.id, kind: "ingest", path: dir, bin: "Cards", createProxies: true, paused: true, baselined: true });
+ expect(loaded.status.state).toBe("paused");
+ });
+
+ it("drops corrupt entries from the config file instead of failing", () => {
+ const file = path.join(root, "watch-folders.json");
+ fs.writeFileSync(file, JSON.stringify({ version: 1, folders: [{ id: "x", kind: "bogus", path: "/tmp" }, { id: "ok", kind: "ingest", path: root }, "junk", { id: "rel", kind: "ingest", path: "relative/path" }] }));
+ expect(createFileConfigStore(file).load().map((f) => f.id)).toEqual(["ok"]);
+ fs.writeFileSync(file, "not json");
+ expect(createFileConfigStore(file).load()).toEqual([]);
+ });
+
+ it("fingerprints by content, not by name or time", async () => {
+ const a = path.join(root, "a.bin");
+ const b = path.join(root, "b.bin");
+ const c = path.join(root, "c.bin");
+ fs.writeFileSync(a, Buffer.alloc(600 * 1024, 7));
+ fs.writeFileSync(b, Buffer.alloc(600 * 1024, 7));
+ const big = Buffer.alloc(600 * 1024, 7);
+ big[big.length - 1] = 9;
+ fs.writeFileSync(c, big);
+ expect(await fingerprintFile(a)).toBe(await fingerprintFile(b));
+ expect(await fingerprintFile(a)).not.toBe(await fingerprintFile(c));
+ });
+});
diff --git a/apps/desktop/test/watch-folder-scanner.test.ts b/apps/desktop/test/watch-folder-scanner.test.ts
new file mode 100644
index 00000000..9de0abb9
--- /dev/null
+++ b/apps/desktop/test/watch-folder-scanner.test.ts
@@ -0,0 +1,135 @@
+import fs from "node:fs";
+import os from "node:os";
+import path from "node:path";
+import { afterEach, beforeEach, describe, expect, it } from "vitest";
+import { FolderScanner, isIgnoredName, type ScanFile } from "../src/main/watch/folder-scanner";
+
+const FAST = { settleMs: 160, pollMs: 40, rescanMs: 250, debounceMs: 20 };
+const sleep = (ms: number) => new Promise((resolve) => setTimeout(resolve, ms));
+async function until(label: string, check: () => boolean, timeout = 5000): Promise<void> {
+ const start = Date.now();
+ while (!check()) {
+ if (Date.now() - start > timeout) throw new Error(`timed out waiting for ${label}`);
+ await sleep(15);
+ }
+}
+
+let dir = "";
+let scanner: FolderScanner | null = null;
+beforeEach(() => {
+ dir = fs.mkdtempSync(path.join(os.tmpdir(), "watch-scan-"));
+});
+afterEach(() => {
+ scanner?.stop();
+ scanner = null;
+ fs.rmSync(dir, { recursive: true, force: true });
+});
+
+function startScanner(extra: Partial<ConstructorParameters<typeof FolderScanner>[1]> = {}) {
+ const ready: ScanFile[] = [];
+ const seen: string[] = [];
+ scanner = new FolderScanner(dir, { onReady: (file) => ready.push(file), onSeen: (file) => seen.push(file.name), ...extra }, FAST);
+ scanner.start();
+ return { ready, seen };
+}
+
+describe("isIgnoredName", () => {
+ it("ignores hidden files, OS droppings and unfinished-download names", () => {
+ for (const name of [".DS_Store", ".hidden.mov", "clip.mov.part", "movie.crdownload", "x.tmp", "~$doc.mov", "Thumbs.db", "a.mp4.download", "b.mov~", "c.partial"]) {
+ expect(isIgnoredName(name), name).toBe(true);
+ }
+ for (const name of ["clip.mov", "My Movie.mp4", "take 1.wav"]) expect(isIgnoredName(name), name).toBe(false);
+ });
+});
+
+describe("FolderScanner", () => {
+ it("reports a finished file once its size stops changing", async () => {
+ const { ready } = startScanner();
+ fs.writeFileSync(path.join(dir, "clip.mp4"), "hello world");
+ await until("ready", () => ready.length === 1);
+ expect(ready[0]).toMatchObject({ name: "clip.mp4", size: 11 });
+ // And only once.
+ await sleep(500);
+ expect(ready).toHaveLength(1);
+ });
+
+ it("does not report a file that is still being written, then reports it once the writes stop", async () => {
+ const { ready } = startScanner();
+ const file = path.join(dir, "big.mov");
+ fs.writeFileSync(file, "a");
+ // Keep appending for longer than the settle window.
+ const startedAt = Date.now();
+ while (Date.now() - startedAt < 600) {
+ fs.appendFileSync(file, "more bytes");
+ await sleep(40);
+ expect(ready).toHaveLength(0);
+ }
+ const finalSize = fs.statSync(file).size;
+ await until("ready after the writes stop", () => ready.length === 1);
+ expect(ready[0].size).toBe(finalSize);
+ });
+
+ it("ignores partial-download names and reports the file after it is renamed to its final name", async () => {
+ const { ready, seen } = startScanner();
+ fs.writeFileSync(path.join(dir, "movie.mp4.part"), "partial");
+ fs.writeFileSync(path.join(dir, ".hidden.mp4"), "hidden");
+ await sleep(500);
+ expect(ready).toHaveLength(0);
+ expect(seen).toHaveLength(0);
+ fs.renameSync(path.join(dir, "movie.mp4.part"), path.join(dir, "movie.mp4"));
+ await until("renamed file ready", () => ready.length === 1);
+ expect(ready[0].name).toBe("movie.mp4");
+ });
+
+ it("never reports an empty file", async () => {
+ const { ready } = startScanner();
+ fs.writeFileSync(path.join(dir, "empty.mp4"), "");
+ await sleep(600);
+ expect(ready).toHaveLength(0);
+ fs.writeFileSync(path.join(dir, "empty.mp4"), "now it has bytes");
+ await until("ready", () => ready.length === 1);
+ });
+
+ it("reports a changed file again as a new version, and skips baselined files", async () => {
+ const baseline = path.join(dir, "old.mp4");
+ fs.writeFileSync(baseline, "already here");
+ const stat = fs.statSync(baseline);
+ const { ready } = (() => {
+ const collected: ScanFile[] = [];
+ scanner = new FolderScanner(dir, { onReady: (file) => collected.push(file) }, FAST);
+ scanner.markReported({ path: baseline, name: "old.mp4", size: stat.size, mtimeMs: stat.mtimeMs });
+ scanner.start();
+ return { ready: collected };
+ })();
+ await sleep(600);
+ expect(ready).toHaveLength(0);
+ fs.writeFileSync(baseline, "already here, but edited later");
+ await until("changed version", () => ready.length === 1);
+ expect(ready[0].size).toBe("already here, but edited later".length);
+ });
+
+ it("ignores subfolders (done/ and failed/ are never rescanned)", async () => {
+ const { ready } = startScanner();
+ fs.mkdirSync(path.join(dir, "done"));
+ fs.writeFileSync(path.join(dir, "done", "clip.mp4"), "moved earlier");
+ await sleep(600);
+ expect(ready).toHaveLength(0);
+ });
+
+ it("reports a missing folder, then recovers when it comes back", async () => {
+ const events: string[] = [];
+ scanner = new FolderScanner(
+ dir,
+ { onReady: (file) => events.push(`ready:${file.name}`), onUnreadable: () => events.push("unreadable"), onReadable: () => events.push("readable") },
+ FAST,
+ );
+ scanner.start();
+ await sleep(100);
+ fs.rmSync(dir, { recursive: true, force: true });
+ await until("unreadable", () => events.includes("unreadable"));
+ fs.mkdirSync(dir);
+ fs.writeFileSync(path.join(dir, "back.mp4"), "after remount");
+ await until("recovered file", () => events.includes("ready:back.mp4"));
+ expect(events).toContain("readable");
+ });
+});
diff --git a/apps/desktop/test/watch-folders-electron.test.ts b/apps/desktop/test/watch-folders-electron.test.ts
new file mode 100644
index 00000000..3a589c45
--- /dev/null
+++ b/apps/desktop/test/watch-folders-electron.test.ts
@@ -0,0 +1,326 @@
+/**
+ * Real-Electron e2e for watch folders (Playwright _electron, the BUILT app).
+ *
+ * Needs a build made with the e2e hook: VITE_OPENREEL_E2E=1 pnpm --filter @openreel/desktop build
+ * and ffmpeg/ffprobe on disk. Opt in with OPENREEL_DESKTOP_WATCH_E2E=1 (skipped otherwise):
+ * pnpm --filter @openreel/desktop test:watch-e2e
+ *
+ * Covers, with a seeded folder list (the folder dialog is native, so it is not driven here):
+ * - ingest: a file still being written is NOT imported; once it stops growing it is imported into the
+ * configured bin of the open project, as an undoable action; the task shows in the background task list;
+ * the original stays in place
+ * - a copy of the same content under another name is reported as a duplicate and not imported
+ * - export: a media file dropped in is rendered with the 1080p preset into the output folder (ffprobe
+ * checks the result), the source moves to done/, a duplicate is not rendered twice, a broken file moves
+ * to failed/ with its error
+ * - restart: a file dropped while the app was closed is imported after relaunch, and a file that was
+ * already imported is not imported again
+ * - the Settings > Watch folders tab lists the folders and pauses one, and a paused folder ignores drops
+ */
+import { createRequire } from "node:module";
+import { execFileSync } from "node:child_process";
+import fs from "node:fs";
+import os from "node:os";
+import path from "node:path";
+import { afterAll, beforeAll, describe, expect, it, vi } from "vitest";
+
+vi.setConfig({ testTimeout: 240_000, hookTimeout: 240_000 });
+
+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_WATCH_E2E === "1" &&
+ fs.existsSync(FFMPEG) &&
+ fs.existsSync(FFPROBE) &&
+ 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"));
+}
+
+const sleep = (ms: number) => new Promise((r) => setTimeout(r, ms));
+async function until<T>(label: string, read: () => Promise<T> | T, timeout = 45_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 sleep(150);
+ }
+}
+const probe = (file: string): any => JSON.parse(execFileSync(FFPROBE, ["-v", "error", "-show_streams", "-show_format", "-of", "json", file], { encoding: "utf8" }));
+
+let work = "";
+let ingestDir = "";
+let exportDir = "";
+let outputDir = "";
+let CLIP = "";
+let profile = "";
+let launches = 0;
+
+function makeClip(out: string, seconds: number, size = "320x240"): void {
+ execFileSync(FFMPEG, [
+ "-y", "-v", "error",
+ "-f", "lavfi", "-i", `testsrc2=size=${size}:rate=25:duration=${seconds}`,
+ "-f", "lavfi", "-i", `sine=frequency=440:sample_rate=48000:duration=${seconds}`,
+ "-c:v", "libx264", "-preset", "veryfast", "-pix_fmt", "yuv420p", "-c:a", "aac", "-shortest", out,
+ ]);
+}
+
+interface Session {
+ app: any;
+ page: any;
+}
+const sessions: Session[] = [];
+
+async function launch(): Promise<Session> {
+ const { _electron } = loadPlaywright();
+ 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", OPENREEL_WATCH_SETTLE_MS: "600" },
+ 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);
+ launches++;
+ 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?.project), undefined, { timeout: 30_000 });
+}
+
+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;
+ }
+ 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 snapshot = (page: any): Promise<any> => page.evaluate(() => (window as any).openreel.watchFolders.list());
+const library = (page: any): Promise<Array<{ id: string; name: string; binName: string | null }>> =>
+ page.evaluate(() => {
+ const project = (window as any).__openreelE2E.project.getState().project;
+ const bins = project.bins ?? [];
+ return project.mediaLibrary.items.map((m: any) => ({ id: m.id, name: m.name, binName: bins.find((b: any) => b.id === m.binId)?.name ?? null }));
+ });
+const itemsNamed = async (page: any, name: string) => (await snapshot(page)).items.filter((i: any) => i.name === name);
+
+/** Write a file the way a slow copy does: in chunks, with pauses, so its size keeps changing. */
+async function slowCopy(src: string, dest: string, chunks = 5, pauseMs = 350): Promise<void> {
+ const data = fs.readFileSync(src);
+ const size = Math.ceil(data.length / chunks);
+ fs.writeFileSync(dest, "");
+ for (let i = 0; i < chunks; i++) {
+ fs.appendFileSync(dest, data.subarray(i * size, (i + 1) * size));
+ await sleep(pauseMs);
+ }
+}
+
+beforeAll(() => {
+ if (!enabled) return;
+ work = fs.realpathSync(fs.mkdtempSync(path.join(os.tmpdir(), "openreel-watch-e2e-")));
+ profile = path.join(work, "profile");
+ ingestDir = path.join(work, "ingest");
+ exportDir = path.join(work, "export-in");
+ outputDir = path.join(work, "export-out");
+ for (const dir of [ingestDir, exportDir, profile]) fs.mkdirSync(dir, { recursive: true });
+ CLIP = path.join(work, "source.mp4");
+ makeClip(CLIP, 2);
+ // The folder list the Settings tab would have written; the paths are what the native dialog returns.
+ fs.writeFileSync(
+ path.join(profile, "watch-folders.json"),
+ JSON.stringify({
+ version: 1,
+ folders: [
+ { id: "ingest-1", kind: "ingest", path: ingestDir, paused: false, bin: "Dropped", createProxies: false },
+ { id: "export-1", kind: "export", path: exportDir, paused: false, presetId: "1080p-high", outputDir, includeProjects: false },
+ ],
+ }),
+ );
+});
+
+afterAll(async () => {
+ for (const session of sessions) await closeApp(session, false);
+ if (work) fs.rmSync(work, { recursive: true, force: true });
+});
+
+d("watch folders in the real app", () => {
+ let session: Session;
+
+ it("starts watching the saved folders", async () => {
+ session = await launch();
+ await openEditor(session.page);
+ const snap = await until("both folders watching", async () => {
+ const s = await snapshot(session.page);
+ return s.folders.length === 2 && s.folders.every((f: any) => f.status.state === "watching" && f.config.baselined) ? s : null;
+ });
+ expect(snap.folders.map((f: any) => f.config.kind).sort()).toEqual(["export", "ingest"]);
+ });
+
+ it("does not import a file that is still being written, then imports it into the bin once complete", async () => {
+ const dest = path.join(ingestDir, "card-001.mp4");
+ const copying = slowCopy(CLIP, dest, 5, 400);
+ await sleep(1200);
+ // Still growing: seen, but not imported.
+ expect((await library(session.page)).some((m) => m.name === "card-001.mp4")).toBe(false);
+ expect((await itemsNamed(session.page, "card-001.mp4"))[0]?.state).toBe("detecting");
+ await copying;
+ const imported = await until("imported", async () => (await library(session.page)).find((m) => m.name === "card-001.mp4" && m.binName === "Dropped"), 60_000);
+ expect(imported.binName).toBe("Dropped");
+ expect(fs.existsSync(dest)).toBe(true); // the original stays where it was dropped
+ // The editor actually decoded it (not a placeholder), and it is a real clip with the right duration.
+ const item = await session.page.evaluate((id: string) => {
+ const m = (window as any).__openreelE2E.project.getState().project.mediaLibrary.items.find((x: any) => x.id === id);
+ return { type: m.type, duration: m.metadata?.duration, path: m.sourceFile?.path ?? null };
+ }, imported.id);
+ expect(item.type).toBe("video");
+ expect(item.duration).toBeGreaterThan(1.5);
+ expect(fs.realpathSync(item.path)).toBe(fs.realpathSync(dest));
+ const done = await until("item done", async () => (await itemsNamed(session.page, "card-001.mp4")).find((i: any) => i.state === "done"));
+ expect(done.detail).toContain('Imported into "Dropped"');
+ });
+
+ it("shows watch-folder work in the background task list", async () => {
+ const task = await until("completed import task", () =>
+ session.page.evaluate(() => {
+ const tasks = (window as any).__openreelE2E.backgroundTasks.getSnapshot();
+ return tasks.find((t: any) => t.source === "watch-folders" && /card-001/.test(t.title) && t.status === "completed") ?? null;
+ }),
+ );
+ expect(task).toMatchObject({ kind: "import", status: "completed", title: expect.stringContaining("Import card-001.mp4") });
+ });
+
+ it("files the media through undoable actions: undo takes it out of the bin, redo puts it back", async () => {
+ // Importing a file is not an undo step in OpenReel (same as dragging a file in; Delete removes it). Creating the
+ // bin and filing the media in it are, because they run as project actions.
+ const binOf = async () => (await library(session.page)).find((m) => m.name === "card-001.mp4")?.binName ?? null;
+ expect(await binOf()).toBe("Dropped");
+ let undos = 0;
+ while ((await binOf()) === "Dropped" && undos < 6) {
+ await session.page.evaluate(() => (window as any).__openreelE2E.project.getState().undo());
+ undos++;
+ }
+ expect(await binOf()).toBeNull();
+ expect((await library(session.page)).some((m) => m.name === "card-001.mp4")).toBe(true); // the media itself stays
+ for (let i = 0; i < undos; i++) await session.page.evaluate(() => (window as any).__openreelE2E.project.getState().redo());
+ expect(await binOf()).toBe("Dropped");
+ });
+
+ it("reports the same content under another name as a duplicate and does not import it", async () => {
+ const before = (await library(session.page)).length;
+ fs.copyFileSync(path.join(ingestDir, "card-001.mp4"), path.join(ingestDir, "card-001-copy.mp4"));
+ const dup = await until("duplicate", async () => (await itemsNamed(session.page, "card-001-copy.mp4")).find((i: any) => i.state === "duplicate"));
+ expect(dup.detail).toMatch(/Same content/);
+ expect((await library(session.page)).length).toBe(before);
+ });
+
+ it("renders a media file dropped into the export folder with the preset, then moves the source to done/", async () => {
+ const dest = path.join(exportDir, "interview.mp4");
+ await slowCopy(CLIP, dest, 3, 300);
+ const out = path.join(outputDir, "interview.mp4");
+ await until("rendered file", () => (fs.existsSync(out) && fs.statSync(out).size > 0 ? out : null), 90_000);
+ const info = probe(out);
+ const video = info.streams.find((s: any) => s.codec_type === "video");
+ expect(video).toMatchObject({ codec_name: "h264", width: 1920, height: 1080 });
+ expect(Number(video.avg_frame_rate.split("/")[0]) / Number(video.avg_frame_rate.split("/")[1])).toBeCloseTo(30, 0);
+ expect(info.streams.some((s: any) => s.codec_type === "audio")).toBe(true);
+ expect(Number(info.format.duration)).toBeGreaterThan(1.5);
+ await until("source moved to done", () => fs.existsSync(path.join(exportDir, "done", "interview.mp4")));
+ expect(fs.existsSync(dest)).toBe(false);
+ expect(fs.readdirSync(outputDir).filter((n) => n.startsWith("."))).toEqual([]); // no partial files
+ const done = await until("export item done", async () => (await itemsNamed(session.page, "interview.mp4")).find((i: any) => i.state === "done"));
+ expect(done.outputPath).toBe(out);
+ const task = await until("completed export task", () =>
+ session.page.evaluate(() => (window as any).__openreelE2E.backgroundTasks.getSnapshot().find((t: any) => t.source === "watch-folders" && /interview/.test(t.title) && t.status === "completed") ?? null),
+ );
+ expect(task).toMatchObject({ kind: "export", status: "completed" });
+ });
+
+ it("does not render a duplicate drop twice, and moves a file ffmpeg cannot read to failed/ with the reason", async () => {
+ fs.copyFileSync(CLIP, path.join(exportDir, "interview-again.mp4"));
+ await until("duplicate noted", async () => (await itemsNamed(session.page, "interview-again.mp4")).find((i: any) => i.state === "duplicate"));
+ expect(fs.readdirSync(outputDir)).toEqual(["interview.mp4"]);
+ expect(fs.existsSync(path.join(exportDir, "done", "interview-again.mp4"))).toBe(true);
+
+ fs.writeFileSync(path.join(exportDir, "broken.mov"), "this is not a video file at all");
+ await until("failed item", async () => (await itemsNamed(session.page, "broken.mov")).find((i: any) => i.state === "failed"));
+ expect(fs.existsSync(path.join(exportDir, "failed", "broken.mov"))).toBe(true);
+ expect(fs.readFileSync(path.join(exportDir, "failed", "broken.mov.error.txt"), "utf8").length).toBeGreaterThan(5);
+ expect(fs.readdirSync(outputDir)).toEqual(["interview.mp4"]);
+ });
+
+ it("lists the folders in Settings, pauses one, and a paused folder ignores a drop until resumed", async () => {
+ const page = session.page;
+ await page.evaluate(() => (window as any).__openreelE2E.ui?.getState?.().setSettingsOpen?.(true));
+ // Open the dialog through the settings store the UI uses.
+ await page.evaluate(() => (window as any).__openreelE2E.settings.getState().openSettings("watch-folders"));
+ await page.getByTestId("watch-folders-panel").waitFor({ timeout: 15_000 });
+ expect(await page.getByTestId("watch-folder").count()).toBe(2);
+ await page.getByLabel(`Pause ${ingestDir}`).click();
+ await until("paused state", async () => (await snapshot(page)).folders.find((f: any) => f.config.id === "ingest-1")?.status.state === "paused");
+ await until("paused label", async () => (await page.getByTestId("watch-folder-state").first().textContent()) === "Paused");
+ const before = (await library(page)).length;
+ fs.copyFileSync(CLIP, path.join(ingestDir, "while-paused.mp4"));
+ // Different content (so it is not a duplicate): append nothing, just rename trick is unnecessary: make a fresh clip.
+ await sleep(2500);
+ expect((await library(page)).length).toBe(before);
+ expect(await itemsNamed(page, "while-paused.mp4")).toHaveLength(0);
+ await page.getByLabel(`Resume ${ingestDir}`).click();
+ await until("while-paused handled after resume", async () => (await itemsNamed(page, "while-paused.mp4")).length > 0);
+ });
+
+ it("survives a restart: imports a file dropped while the app was closed, and does not import old files again", async () => {
+ const lib = (await library(session.page)).map((m) => m.name);
+ expect(lib).toContain("card-001.mp4");
+ await closeApp(session, true);
+ const second = path.join(work, "second.mp4");
+ makeClip(second, 3);
+ fs.copyFileSync(second, path.join(ingestDir, "card-002.mp4"));
+ session = await launch();
+ // No project is open yet: the file waits (it is not failed) until one is.
+ const early = await until("picked up at startup", async () => (await itemsNamed(session.page, "card-002.mp4")).find((i: any) => ["detecting", "queued", "running", "waiting"].includes(i.state)), 60_000);
+ expect(early).toBeTruthy();
+ expect((await itemsNamed(session.page, "card-002.mp4")).some((i: any) => i.state === "failed")).toBe(false);
+ await openEditor(session.page);
+ const imported = await until("imported after the project opened", async () => (await library(session.page)).find((m) => m.name === "card-002.mp4" && m.binName === "Dropped"), 60_000);
+ expect(imported.binName).toBe("Dropped");
+ await sleep(2500);
+ // Earlier files were not imported again: the watcher did not touch card-001 this session, and no media is in the project twice
+ // (the project itself came back from the autosave, which is why card-001 is in it at all).
+ expect(await itemsNamed(session.page, "card-001.mp4")).toHaveLength(0);
+ const names = (await library(session.page)).map((m) => m.name);
+ expect(names.filter((n) => n === "card-001.mp4").length).toBeLessThanOrEqual(1);
+ expect(names.filter((n) => n === "card-002.mp4")).toHaveLength(1);
+ expect(launches).toBe(2);
+ });
+});
diff --git a/apps/desktop/test/watch-folders-project-electron.test.ts b/apps/desktop/test/watch-folders-project-electron.test.ts
new file mode 100644
index 00000000..9ffb72b3
--- /dev/null
+++ b/apps/desktop/test/watch-folders-project-electron.test.ts
@@ -0,0 +1,160 @@
+/**
+ * Real-Electron e2e for the PROJECT-file half of export watch folders (Playwright _electron, the BUILT app).
+ *
+ * A saved .oreel project dropped into an export folder that opted in (includeProjects) is opened in the editor
+ * and rendered through the editor's own export queue with the folder's preset; the file lands in the output
+ * folder and the project file moves to done/. The project is built through the MCP tools (the same way the
+ * windowless MCP e2e does), so this also exercises the watch-folder origin of the confirmation gate: the
+ * export is expensive and the agent auto-allow is turned off here.
+ *
+ * VITE_OPENREEL_E2E=1 pnpm --filter @openreel/desktop build
+ * pnpm --filter @openreel/desktop test:watch-e2e
+ */
+import { createRequire } from "node:module";
+import { execFileSync } from "node:child_process";
+import fs from "node:fs";
+import os from "node:os";
+import path from "node:path";
+import { afterAll, beforeAll, describe, expect, it, vi } from "vitest";
+
+vi.setConfig({ testTimeout: 300_000, hookTimeout: 240_000 });
+
+const desktopDir = path.resolve(__dirname, "..");
+const repoRoot = path.resolve(desktopDir, "../..");
+const FFMPEG = process.env.FFMPEG ?? "/opt/homebrew/bin/ffmpeg";
+const FFPROBE = process.env.FFPROBE ?? path.join(path.dirname(FFMPEG), "ffprobe");
+const enabled =
+ process.env.OPENREEL_DESKTOP_WATCH_E2E === "1" &&
+ fs.existsSync(FFMPEG) &&
+ fs.existsSync(path.join(desktopDir, "dist/main/index.js")) &&
+ fs.existsSync(path.join(repoRoot, "apps/web/dist/index.html"));
+const d = enabled ? describe : describe.skip;
+
+function loadPlaywright(): { _electron: { launch(options: Record<string, unknown>): Promise<any> } } {
+ const require = createRequire(path.join(repoRoot, "package.json"));
+ const pnpmDir = path.join(repoRoot, "node_modules/.pnpm");
+ const dir = fs.readdirSync(pnpmDir).find((entry) => entry.startsWith("playwright@"));
+ if (!dir) throw new Error("playwright is not installed in the workspace");
+ return require(path.join(pnpmDir, dir, "node_modules/playwright"));
+}
+
+const sleep = (ms: number) => new Promise((resolve) => setTimeout(resolve, ms));
+async function until<T>(label: string, read: () => Promise<T> | T, timeout = 120_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 sleep(200);
+ }
+}
+
+let endpoint: { url: string; token: string };
+let nextId = 1;
+async function rpc(body: unknown): Promise<any> {
+ const response = await fetch(endpoint.url, { method: "POST", headers: { "Content-Type": "application/json", Authorization: `Bearer ${endpoint.token}` }, body: JSON.stringify(body) });
+ return response.json();
+}
+async function call(name: string, args: Record<string, unknown> = {}): Promise<{ isError: boolean; text: string; data: any }> {
+ const reply = await rpc({ jsonrpc: "2.0", id: nextId++, method: "tools/call", params: { name, arguments: args } });
+ expect(reply.error, `${name}: ${JSON.stringify(reply.error)}`).toBeUndefined();
+ const text = String(reply.result.content?.[0]?.text ?? "");
+ const blank = text.indexOf("\n\n");
+ let data: any;
+ if (reply.result.isError !== true && blank >= 0) {
+ try {
+ data = JSON.parse(text.slice(blank + 2));
+ } catch {
+ data = undefined;
+ }
+ }
+ return { isError: reply.result.isError === true, text, data };
+}
+
+d("project files in an export watch folder (real Electron)", () => {
+ let app: any;
+ let work = "";
+ let exportDir = "";
+ let outputDir = "";
+
+ beforeAll(async () => {
+ if (!enabled) return;
+ work = fs.realpathSync(fs.mkdtempSync(path.join(os.tmpdir(), "openreel-watch-proj-")));
+ const userData = path.join(work, "ud");
+ exportDir = path.join(work, "hot");
+ outputDir = path.join(work, "rendered");
+ for (const dir of [userData, exportDir, path.join(work, "Footage")]) fs.mkdirSync(dir, { recursive: true });
+ fs.writeFileSync(path.join(userData, "mcp-policy.json"), JSON.stringify({ v: 1, allowedRoots: [work] }));
+ fs.writeFileSync(
+ path.join(userData, "watch-folders.json"),
+ JSON.stringify({ version: 1, folders: [{ id: "export-1", kind: "export", path: exportDir, presetId: "1080p-high", outputDir, includeProjects: true, baselined: true }] }),
+ );
+ execFileSync(FFMPEG, ["-y", "-v", "error", "-f", "lavfi", "-i", "testsrc2=size=320x240:rate=24:duration=2", "-f", "lavfi", "-i", "sine=frequency=440:duration=2", "-c:v", "libx264", "-pix_fmt", "yuv420p", "-c:a", "aac", "-shortest", path.join(work, "Footage", "tone.mp4")]);
+ const endpointFile = path.join(work, "mcp-endpoint.json");
+ const { _electron } = loadPlaywright();
+ app = await _electron.launch({
+ args: [desktopDir, `--user-data-dir=${userData}`],
+ env: { ...process.env, OPENREEL_MCP_ENDPOINT_FILE: endpointFile, OPENREEL_FFMPEG_PATH: FFMPEG, OPENREEL_WATCH_SETTLE_MS: "600" },
+ timeout: 120_000,
+ });
+ for (let i = 0; i < 400; i++) {
+ try {
+ endpoint = JSON.parse(fs.readFileSync(endpointFile, "utf8"));
+ break;
+ } catch {
+ await sleep(50);
+ }
+ }
+ expect(endpoint, "the MCP endpoint file appeared").toBeTruthy();
+ expect((await rpc({ jsonrpc: "2.0", id: nextId++, method: "tools/list" })).result.tools.length).toBeGreaterThan(100);
+ }, 240_000);
+
+ afterAll(async () => {
+ if (!enabled) return;
+ try {
+ app?.process().kill("SIGKILL");
+ } catch {
+ /* already gone */
+ }
+ if (work) fs.rmSync(work, { recursive: true, force: true });
+ });
+
+ it("renders a dropped project file through the editor's export queue, into the output folder", async () => {
+ expect((await call("dismiss_onboarding")).isError).toBe(false);
+ expect((await call("create_project", { name: "Cut", width: 1280, height: 720, frameRate: 24 })).isError).toBe(false);
+ const imported = await call("import_media_from_path", { paths: [path.join(work, "Footage", "tone.mp4")] });
+ expect(imported.isError, imported.text).toBe(false);
+ const mediaId = imported.data.imported[0].mediaId as string;
+ let tracks = (await call("list_tracks")).data as any;
+ let video = (Array.isArray(tracks) ? tracks : tracks?.tracks ?? []).find((track: any) => track.type === "video");
+ if (!video) {
+ expect((await call("add_track", { trackType: "video" })).isError).toBe(false);
+ tracks = (await call("list_tracks")).data;
+ video = (Array.isArray(tracks) ? tracks : tracks?.tracks ?? []).find((track: any) => track.type === "video");
+ }
+ expect((await call("add_clip", { trackId: video.id, mediaId, startTime: 0 })).isError).toBe(false);
+ const staged = path.join(work, "Cut.oreel");
+ expect((await call("save_project_as", { path: staged })).isError).toBe(false);
+ // Another project is open when the file arrives: rendering replaces it (it is saved first).
+ expect((await call("create_project", { name: "Something else" })).isError).toBe(false);
+
+ fs.renameSync(staged, path.join(exportDir, "Cut.oreel"));
+ const dump = async () => {
+ const page = await app.firstWindow();
+ return JSON.stringify(await page.evaluate(() => (window as any).openreel.watchFolders.list()));
+ };
+ const out = await until("rendered project", () => {
+ const files = fs.existsSync(outputDir) ? fs.readdirSync(outputDir).filter((n) => n.endsWith(".mp4") && !n.startsWith(".")) : [];
+ return files.length ? path.join(outputDir, files[0]) : null;
+ }, 60_000).catch(async (error) => {
+ throw new Error(`${error.message}; watch state: ${await dump()}`);
+ });
+ const info = JSON.parse(execFileSync(FFPROBE, ["-v", "error", "-show_streams", "-show_format", "-of", "json", out], { encoding: "utf8" }));
+ const video0 = info.streams.find((s: any) => s.codec_type === "video");
+ expect(video0).toMatchObject({ codec_name: "h264", width: 1920, height: 1080 });
+ expect(Number(info.format.duration)).toBeGreaterThan(1.5);
+ await until("project moved to done", () => fs.existsSync(path.join(exportDir, "done", "Cut.oreel")));
+ expect(fs.existsSync(path.join(exportDir, "Cut.oreel"))).toBe(false);
+ expect((await call("get_app_state")).data).toMatchObject({ projectOpen: true });
+ });
+});
diff --git a/apps/desktop/test/watch-render.test.ts b/apps/desktop/test/watch-render.test.ts
new file mode 100644
index 00000000..fab8edbf
--- /dev/null
+++ b/apps/desktop/test/watch-render.test.ts
@@ -0,0 +1,134 @@
+import { execFileSync, spawnSync } from "node:child_process";
+import fs from "node:fs";
+import os from "node:os";
+import path from "node:path";
+import { afterAll, beforeAll, describe, expect, it, vi } from "vitest";
+
+vi.mock("electron", () => ({ app: { isPackaged: false } }));
+
+import { probeMediaFile } from "../src/main/ingest/probe-media";
+import { WATCH_EXPORT_PRESET_IDS } from "../src/shared/watch-folders";
+import { WATCH_PRESETS, buildWatchRenderArgs, classifyFile, isWatchPresetId, parseOutTimeSeconds, renderMediaFile, uniquePath, type RenderDeps } from "../src/main/watch/render";
+
+const bundled = path.resolve(__dirname, `../resources/bin/${process.platform}-${process.arch}/ffmpeg`);
+const FFMPEG = fs.existsSync(bundled) ? bundled : "ffmpeg";
+process.env.OPENREEL_FFMPEG_PATH = FFMPEG; // probeMediaFile resolves ffmpeg through the app's sidecar path
+const haveFfmpeg = spawnSync(FFMPEG, ["-version"]).status === 0;
+const haveFfprobe = spawnSync("ffprobe", ["-version"]).status === 0;
+
+describe("watch render planning", () => {
+ it("has a preset for every id the settings UI offers", () => {
+ for (const id of WATCH_EXPORT_PRESET_IDS) expect(isWatchPresetId(id)).toBe(true);
+ expect(isWatchPresetId("youtube-4k")).toBe(false);
+ expect(Object.keys(WATCH_PRESETS).sort()).toEqual([...WATCH_EXPORT_PRESET_IDS].sort());
+ });
+
+ it("classifies files by extension", () => {
+ expect(classifyFile("/x/a.MOV")).toBe("video");
+ expect(classifyFile("/x/a.wav")).toBe("audio");
+ expect(classifyFile("/x/a.oreel")).toBe("project");
+ expect(classifyFile("/x/a.openreel")).toBe("project");
+ expect(classifyFile("/x/a.png")).toBe("other");
+ expect(classifyFile("/x/a")).toBe("other");
+ });
+
+ it("builds fixed-size presets as fit-and-pad at the preset frame rate", () => {
+ const plan = buildWatchRenderArgs("1080p-60", "/in/a.mov", "/out/a.mp4", { hasVideo: true, hasAudio: true }, "libx264");
+ expect(plan.ext).toBe("mp4");
+ const vf = plan.args[plan.args.indexOf("-vf") + 1];
+ expect(vf).toContain("scale=1920:1080:force_original_aspect_ratio=decrease");
+ expect(vf).toContain("pad=1920:1080");
+ expect(vf).toContain("fps=60");
+ expect(plan.args).toContain("25000k");
+ expect(plan.args.at(-1)).toBe("/out/a.mp4");
+ });
+
+ it("keeps the source size and frame rate for the standard preset, forcing even dimensions", () => {
+ const plan = buildWatchRenderArgs("mp4", "/in/a.mov", "/out/a.mp4", { hasVideo: true, hasAudio: false });
+ const vf = plan.args[plan.args.indexOf("-vf") + 1];
+ expect(vf).toBe("scale=trunc(iw/2)*2:trunc(ih/2)*2");
+ expect(plan.args).not.toContain("-c:a");
+ });
+
+ it("makes WAV for the audio preset and AAC for an audio file under a video preset", () => {
+ expect(buildWatchRenderArgs("wav", "/in/a.mov", "/out/a.wav", { hasVideo: true, hasAudio: true }).ext).toBe("wav");
+ expect(buildWatchRenderArgs("1080p-high", "/in/a.wav", "/out/a.m4a", { hasVideo: false, hasAudio: true }).ext).toBe("m4a");
+ });
+
+ it("refuses sources that cannot make the output", () => {
+ expect(() => buildWatchRenderArgs("wav", "/in/a.mov", "/o", { hasVideo: true, hasAudio: false })).toThrow(/no audio/);
+ expect(() => buildWatchRenderArgs("mp4", "/in/a.mov", "/o", { hasVideo: false, hasAudio: false })).toThrow(/neither video nor audio/);
+ });
+
+ it("reads progress from ffmpeg's out_time and picks unique output names", () => {
+ expect(parseOutTimeSeconds("frame=1\nout_time_us=1500000\nprogress=continue\nout_time_us=2500000")).toBe(2.5);
+ expect(parseOutTimeSeconds("nothing")).toBeNull();
+ const taken = new Set(["/o/a.mp4", "/o/a-1.mp4"]);
+ expect(uniquePath("/o", "a", "mp4", (p) => taken.has(p))).toBe("/o/a-2.mp4");
+ expect(uniquePath("/o", "b", "mp4", (p) => taken.has(p))).toBe("/o/b.mp4");
+ });
+});
+
+describe.skipIf(!haveFfmpeg)("watch render with a real ffmpeg", () => {
+ let dir = "";
+ let clip = "";
+ const deps: RenderDeps = {
+ ffmpegPath: () => FFMPEG,
+ probe: async (file) => {
+ const probe = await probeMediaFile(file);
+ if (!probe) throw new Error("unreadable");
+ return probe;
+ },
+ videoEncoder: async () => "libx264",
+ isHardwareEncoder: () => false,
+ };
+ beforeAll(() => {
+ dir = fs.mkdtempSync(path.join(os.tmpdir(), "watch-render-"));
+ clip = path.join(dir, "source.mov");
+ execFileSync(FFMPEG, ["-v", "error", "-f", "lavfi", "-i", "testsrc2=size=1280x720:rate=25:duration=2", "-f", "lavfi", "-i", "sine=frequency=440:duration=2", "-c:v", "libx264", "-pix_fmt", "yuv420p", "-c:a", "aac", "-shortest", "-y", clip]);
+ });
+ afterAll(() => fs.rmSync(dir, { recursive: true, force: true }));
+
+ const streams = (file: string) =>
+ JSON.parse(execFileSync("ffprobe", ["-v", "error", "-show_entries", "stream=codec_type,codec_name,width,height,r_frame_rate", "-of", "json", file]).toString()).streams as Array<{ codec_type: string; codec_name: string; width?: number; height?: number; r_frame_rate: string }>;
+
+ it.skipIf(!haveFfprobe)("renders 1080p-high: 1920x1080 H.264 at 30 fps with audio, written atomically", async () => {
+ const out = path.join(dir, "out");
+ const progress: Array<number | null> = [];
+ const result = await renderMediaFile({ src: clip, presetId: "1080p-high", outputDir: out, onProgress: (f) => progress.push(f), signal: new AbortController().signal }, deps);
+ expect(result).toBe(path.join(out, "source.mp4"));
+ const found = streams(result);
+ const video = found.find((s) => s.codec_type === "video")!;
+ expect(video).toMatchObject({ codec_name: "h264", width: 1920, height: 1080, r_frame_rate: "30/1" });
+ expect(found.some((s) => s.codec_type === "audio")).toBe(true);
+ expect(fs.readdirSync(out)).toEqual(["source.mp4"]); // no partial file left behind
+ expect(progress.at(-1)).toBe(1);
+ // A second render of the same name never overwrites.
+ const again = await renderMediaFile({ src: clip, presetId: "mp4", outputDir: out, onProgress: () => undefined, signal: new AbortController().signal }, deps);
+ expect(path.basename(again)).toBe("source-1.mp4");
+ expect(streams(again).find((s) => s.codec_type === "video")).toMatchObject({ width: 1280, height: 720 });
+ });
+
+ it.skipIf(!haveFfprobe)("renders the audio preset to a 24-bit 48 kHz WAV", async () => {
+ const result = await renderMediaFile({ src: clip, presetId: "wav", outputDir: path.join(dir, "wav"), onProgress: () => undefined, signal: new AbortController().signal }, deps);
+ expect(path.extname(result)).toBe(".wav");
+ expect(streams(result)).toMatchObject([{ codec_type: "audio", codec_name: "pcm_s24le" }]);
+ });
+
+ it("fails with ffmpeg's reason on a file that is not media, and leaves nothing behind", async () => {
+ const bad = path.join(dir, "bad.mov");
+ fs.writeFileSync(bad, "this is not a video");
+ const out = path.join(dir, "out-bad");
+ await expect(renderMediaFile({ src: bad, presetId: "mp4", outputDir: out, onProgress: () => undefined, signal: new AbortController().signal }, deps)).rejects.toThrow();
+ expect(fs.existsSync(out) ? fs.readdirSync(out) : []).toEqual([]);
+ });
+
+ it("stops a render when it is cancelled", async () => {
+ const controller = new AbortController();
+ const out = path.join(dir, "out-cancel");
+ const pending = renderMediaFile({ src: clip, presetId: "4k", outputDir: out, onProgress: () => undefined, signal: controller.signal }, deps);
+ setTimeout(() => controller.abort(), 150);
+ await expect(pending).rejects.toThrow(/Cancelled/);
+ expect(fs.readdirSync(out)).toEqual([]);
+ });
+});
diff --git a/apps/web/e2e/spectral-editing.spec.ts b/apps/web/e2e/spectral-editing.spec.ts
new file mode 100644
index 00000000..4f3725c7
--- /dev/null
+++ b/apps/web/e2e/spectral-editing.spec.ts
@@ -0,0 +1,313 @@
+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 } from "./helpers";
+import { E2E_FFMPEG } from "./env";
+
+/**
+ * Spectral editing, checked in real Chrome with real audio:
+ * - paint a box over the 1 kHz tone of a three-tone fixture in the spectral editor and Remove it, then drag a
+ * frequency band over the 3 kHz tone and Attenuate it by 12 dB (real pointer input on the canvas);
+ * - the export mixdown has the 1 kHz tone gone, the 3 kHz tone 12 dB down and the 440 Hz tone untouched;
+ * - the live preview path (RealtimeAudioGraph on the same cached repair) renders the same samples as the export;
+ * - every edit is one undo step, and undo restores the original mixdown exactly;
+ * - a real export from the export queue, decoded with ffmpeg, carries the edit.
+ */
+
+const FFMPEG = E2E_FFMPEG;
+const workDir = mkdtempSync(join(tmpdir(), "openreel-spectral-"));
+const SR = 48000;
+const SECONDS = 4;
+
+interface Hook {
+ project: { getState(): Record<string, any> };
+ audio: Record<string, any>;
+ exportQueue: { getState(): 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;
+ });
+});
+
+/** 4 s mono WAV: 440 Hz, 1 kHz and 3 kHz sines at 0.2 each (steady, so a region measures cleanly). */
+function writeToneWav(path: string): void {
+ const n = SR * SECONDS;
+ const pcm = Buffer.alloc(44 + n * 2);
+ pcm.write("RIFF", 0);
+ pcm.writeUInt32LE(36 + n * 2, 4);
+ pcm.write("WAVEfmt ", 8);
+ pcm.writeUInt32LE(16, 16);
+ pcm.writeUInt16LE(1, 20);
+ pcm.writeUInt16LE(1, 22);
+ pcm.writeUInt32LE(SR, 24);
+ pcm.writeUInt32LE(SR * 2, 28);
+ pcm.writeUInt16LE(2, 32);
+ pcm.writeUInt16LE(16, 34);
+ pcm.write("data", 36);
+ pcm.writeUInt32LE(n * 2, 40);
+ for (let i = 0; i < n; i++) {
+ const t = i / SR;
+ const x = 0.2 * Math.sin(2 * Math.PI * 440 * t) + 0.2 * Math.sin(2 * Math.PI * 1000 * t + 1) + 0.2 * Math.sin(2 * Math.PI * 3000 * t + 2);
+ pcm.writeInt16LE(Math.round(x * 32767), 44 + i * 2);
+ }
+ writeFileSync(path, pcm);
+}
+
+const toneAmp = (x: Float32Array, freq: number, from: number, to: number): number => {
+ const a = Math.floor(from * SR);
+ const b = Math.floor(to * SR);
+ let re = 0;
+ let im = 0;
+ for (let i = a; i < b; i++) {
+ const w = (2 * Math.PI * freq * i) / SR;
+ re += x[i] * Math.cos(w);
+ im -= x[i] * Math.sin(w);
+ }
+ return (2 * Math.hypot(re, im)) / (b - a);
+};
+const db = (a: number, b: number) => 20 * Math.log10(a / b);
+
+function decodeAudio(file: string): Float32Array {
+ const buf = execFileSync(FFMPEG, ["-v", "error", "-i", file, "-vn", "-ac", "1", "-ar", String(SR), "-f", "f32le", "-"], { maxBuffer: 256 * 1024 * 1024 });
+ return new Float32Array(buf.buffer.slice(buf.byteOffset, buf.byteOffset + buf.byteLength));
+}
+
+const history = (page: Page) => page.evaluate(() => E().project.getState().actionExecutor.getHistory().getDisplayHistory().length as number);
+
+/** The export mixdown of [0, seconds], mono, as the export engine renders it. */
+async function renderMix(page: Page, seconds: number): Promise<number[]> {
+ return page.evaluate(async (len) => {
+ const engine = E().audio.getAudioEngine();
+ if (!engine.isInitialized()) await engine.initialize();
+ const out = await engine.renderAudio(E().project.getState().getFullProject(), 0, len);
+ return Array.from(out.buffer.getChannelData(0) as Float32Array);
+ }, seconds);
+}
+
+interface Stage {
+ box: { x: number; y: number; width: number; height: number };
+ start: number;
+ end: number;
+ minHz: number;
+ maxHz: number;
+}
+
+async function readStage(page: Page): Promise<Stage> {
+ const stage = page.getByTestId("spectral-stage");
+ const box = await stage.boundingBox();
+ if (!box) throw new Error("spectral stage is not visible");
+ const num = async (name: string) => Number(await stage.getAttribute(name));
+ return { box, start: await num("data-start"), end: await num("data-end"), minHz: await num("data-min-hz"), maxHz: await num("data-max-hz") };
+}
+const px = (s: Stage, t: number) => s.box.x + ((t - s.start) / (s.end - s.start)) * s.box.width;
+const py = (s: Stage, hz: number) => s.box.y + (1 - Math.log(hz / s.minHz) / Math.log(s.maxHz / s.minHz)) * s.box.height;
+
+async function drag(page: Page, from: { x: number; y: number }, to: { x: number; y: number }): Promise<void> {
+ await page.mouse.move(from.x, from.y);
+ await page.mouse.down();
+ await page.mouse.move((from.x + to.x) / 2, (from.y + to.y) / 2, { steps: 4 });
+ await page.mouse.move(to.x, to.y, { steps: 4 });
+ await page.mouse.up();
+}
+
+test("paint a region over a test tone: the exported and previewed audio lose it, undo restores it", async ({ page }, testInfo) => {
+ testInfo.setTimeout(300_000);
+ const wavPath = join(workDir, "three-tones.wav");
+ writeToneWav(wavPath);
+ await openEditor(page);
+ await importInput(page).setInputFiles(wavPath);
+ await page.getByLabel("Select media three-tones.wav").waitFor({ timeout: 30_000 });
+ const added = await page.evaluate(async () => {
+ const st = E().project.getState();
+ const item = st.project.mediaLibrary.items.find((m: any) => m.name === "three-tones.wav");
+ const target = st.project.timeline.tracks.find((t: any) => t.name === "Dialogue");
+ const main = st.project.timeline.tracks.find((t: any) => t.name === "Main");
+ await st.muteTrack(main.id, true);
+ return st.addClip(target.id, item.id, 0);
+ });
+ expect(added.success, JSON.stringify(added)).toBe(true);
+ await settle(page, 400);
+ const clipId = await page.evaluate(() => E().project.getState().project.timeline.tracks.find((t: any) => t.name === "Dialogue").clips[0].id as string);
+
+ const before = Float32Array.from(await renderMix(page, 3.8));
+ const beforeAmps = { a440: toneAmp(before, 440, 1, 3), a1k: toneAmp(before, 1000, 1, 3), a3k: toneAmp(before, 3000, 1, 3) };
+ console.log("[spectral] mix before", JSON.stringify(beforeAmps));
+ expect(beforeAmps.a1k, "fixture tone is audible").toBeGreaterThan(0.05);
+
+ await clickClip(page, clipId);
+ await page.getByRole("tab", { name: /^Audio$/ }).click();
+ await page.getByRole("button", { name: "Expand Spectral editing section" }).click();
+ const editor = page.getByTestId("spectral-editor");
+ await editor.waitFor({ timeout: 30_000 });
+ await expect(editor.getByTestId("spectral-canvas")).toHaveAttribute("data-ready", "true", { timeout: 60_000 });
+ // The spectrogram really shows the three tones: bright pixels at 440 Hz, 1 kHz and 3 kHz, dark in between.
+ await editor.getByTestId("spectral-range").selectOption("voice");
+ await expect(page.getByTestId("spectral-stage")).toHaveAttribute("data-min-hz", "80");
+ await page.waitForTimeout(500); // the canvas repaints in an effect after the range changes
+ const lines = await editor.getByTestId("spectral-canvas").evaluate(async (canvas: HTMLCanvasElement, hzList: number[]) => {
+ const stage = canvas.parentElement!;
+ const minHz = Number(stage.dataset.minHz);
+ const maxHz = Number(stage.dataset.maxHz);
+ const ctx = canvas.getContext("2d")!;
+ const luma = (hz: number) => {
+ const y = Math.round((1 - Math.log(hz / minHz) / Math.log(maxHz / minHz)) * (canvas.height - 1));
+ const x = Math.round(canvas.width / 2);
+ // A tone is a thin line (sub-pixel to a few px wide on a log axis), so take the brightest pixel within +-3 rows.
+ let best = 0;
+ for (let dy = -3; dy <= 3; dy++) {
+ const d = ctx.getImageData(x, Math.max(0, Math.min(canvas.height - 1, y + dy)), 1, 1).data;
+ best = Math.max(best, d[0] + d[1] + d[2]);
+ }
+ return best;
+ };
+ return hzList.map(luma);
+ }, [440, 700, 1000, 1700, 3000]);
+ await editor.screenshot({ path: join(workDir, "spectral-before.png") });
+ console.log("[spectral] spectrogram luma at 440/700/1000/1700/3000", JSON.stringify(lines));
+ expect(lines[0], "440 Hz line").toBeGreaterThan(lines[1] * 2);
+ expect(lines[2], "1 kHz line").toBeGreaterThan(lines[3] * 2);
+ expect(lines[4], "3 kHz line").toBeGreaterThan(lines[3] * 2);
+
+ // 1) Rectangle over the 1 kHz tone, 0.5 s to 3.5 s, then Remove.
+ const start = await history(page);
+ let stage = await readStage(page);
+ await drag(page, { x: px(stage, 0.5), y: py(stage, 1250) }, { x: px(stage, 3.5), y: py(stage, 800) });
+ await expect(editor.getByTestId("spectral-selection")).toBeVisible();
+ await expect(editor.getByTestId("spectral-readout")).toContainText("Selection");
+ await editor.getByTestId("spectral-remove").click();
+ await expect(editor.getByTestId("spectral-region-row")).toHaveCount(1, { timeout: 15_000 });
+ await expect(editor.getByTestId("spectral-canvas")).toHaveAttribute("data-ready", "true", { timeout: 60_000 });
+ expect(await history(page), "Remove is one undo step").toBe(start + 1);
+
+ // 2) Frequency-band marquee over the 3 kHz tone (whole source), attenuate 12 dB.
+ await editor.getByTestId("spectral-tool-band").click();
+ stage = await readStage(page);
+ await drag(page, { x: px(stage, 1), y: py(stage, 3800) }, { x: px(stage, 2), y: py(stage, 2400) });
+ await expect(editor.getByTestId("spectral-selection")).toBeVisible();
+ await editor.getByTestId("spectral-db").fill("12");
+ await editor.getByTestId("spectral-attenuate").click();
+ await expect(editor.getByTestId("spectral-region-row")).toHaveCount(2, { timeout: 15_000 });
+ expect(await history(page), "Attenuate is one more undo step").toBe(start + 2);
+ const regions = await page.evaluate((id) => {
+ const clip = E().project.getState().project.timeline.tracks.flatMap((t: any) => t.clips).find((c: any) => c.id === id);
+ return clip.audioEffects.filter((e: any) => e.type === "spectralRepair").map((e: any) => e.params.regions);
+ }, clipId);
+ console.log("[spectral] stored regions", JSON.stringify(regions));
+ expect(regions).toHaveLength(1);
+ expect(regions[0].map((r: any) => r.mode)).toEqual(["remove", "attenuate"]);
+ expect(regions[0][1].startTime, "band marquee covers the whole source").toBe(0);
+ expect(regions[0][1].endTime).toBeGreaterThan(SECONDS - 0.05);
+ expect(regions[0][1].gainDb).toBe(-12);
+ await expect(editor.getByTestId("spectral-canvas")).toHaveAttribute("data-ready", "true", { timeout: 60_000 });
+ await editor.screenshot({ path: join(workDir, "spectral-after.png") });
+ console.log(`[spectral] screenshots: ${join(workDir, "spectral-before.png")} ${join(workDir, "spectral-after.png")}`);
+
+ // Zoom keeps the region boxes on the sound they were painted on.
+ const regionBox = async () => editor.getByTestId(/^spectral-region-sr-/).first().boundingBox();
+ const unzoomed = await regionBox();
+ await editor.getByTestId("spectral-zoom-in").click();
+ await editor.getByTestId("spectral-zoom-in").click();
+ await expect(editor.getByTestId("spectral-pan")).toBeVisible();
+ const zoomedStage = await readStage(page);
+ expect(zoomedStage.end - zoomedStage.start).toBeLessThan(SECONDS * 0.3);
+ const zoomedBox = await regionBox();
+ expect(zoomedBox && unzoomed && zoomedBox.width > unzoomed.width * 0.9, "zoomed region stays visible and aligned").toBeTruthy();
+ await editor.getByTestId("spectral-zoom-fit").click();
+
+ // Export mixdown: 1 kHz gone, 3 kHz down 12 dB, 440 Hz untouched.
+ const after = Float32Array.from(await renderMix(page, 3.8));
+ const afterAmps = { a440: toneAmp(after, 440, 1, 3), a1k: toneAmp(after, 1000, 1, 3), a3k: toneAmp(after, 3000, 1, 3) };
+ console.log("[spectral] mix after", JSON.stringify(afterAmps));
+ expect(db(beforeAmps.a1k, afterAmps.a1k), "1 kHz removed by >= 25 dB").toBeGreaterThan(25);
+ expect(db(beforeAmps.a3k, afterAmps.a3k), "3 kHz attenuated by 12 dB").toBeGreaterThan(11.7);
+ expect(db(beforeAmps.a3k, afterAmps.a3k), "3 kHz attenuated by 12 dB").toBeLessThan(12.3);
+ expect(Math.abs(db(afterAmps.a440, beforeAmps.a440)), "440 Hz untouched").toBeLessThan(0.1);
+ // Outside the removal span the 1 kHz tone is still there (the region covered 0.5 s to 3.5 s).
+ expect(db(toneAmp(before, 1000, 0.05, 0.3), toneAmp(after, 1000, 0.05, 0.3)), "1 kHz before the region").toBeLessThan(0.5);
+
+ // The live-preview path plays the SAME samples: a RealtimeAudioGraph on an OfflineAudioContext fed the cached repair.
+ const parity = await page.evaluate(
+ async ({ id, exported }) => {
+ const { RealtimeAudioGraph, getAudioEngine } = E().audio;
+ const st = E().project.getState();
+ const clip = st.project.timeline.tracks.flatMap((t: any) => t.clips).find((c: any) => c.id === id);
+ const media = st.project.mediaLibrary.items.find((m: any) => m.id === clip.mediaId);
+ const decodeCtx = new OfflineAudioContext(2, 1, 48000);
+ const source: AudioBuffer = await decodeCtx.decodeAudioData(await media.blob.arrayBuffer());
+ const ctx = new OfflineAudioContext(2, Math.floor(48000 * 3.8), 48000);
+ const clock = { getAudioContext: () => ctx, currentTime: 0, isPlaying: true };
+ const graph = new RealtimeAudioGraph(clock as any);
+ const prepared = await graph.prepareSpectralRepair(source, clip.audioEffects);
+ graph.scheduleClip({ clipId: id, trackId: "t", audioBuffer: prepared.buffer, startTime: 0, endTime: 3.8, mediaOffset: 0, volume: 1, volumeAutomation: [], pan: 0, effects: prepared.effects, speed: 1 });
+ const played = (await ctx.startRendering()).getChannelData(0) as Float32Array;
+ const reference = exported as number[];
+ void getAudioEngine;
+ // Best scalar between the two paths (they may differ by a fixed bus gain), then the residual.
+ let ab = 0;
+ let bb = 0;
+ const from = 4800;
+ const to = Math.min(played.length, reference.length) - 4800;
+ for (let i = from; i < to; i++) {
+ ab += played[i] * reference[i];
+ bb += reference[i] * reference[i];
+ }
+ const gain = ab / bb;
+ let residual = 0;
+ for (let i = from; i < to; i++) residual += (played[i] - gain * reference[i]) ** 2;
+ return { gain, residualDb: 10 * Math.log10(residual / (gain * gain * bb)), appliedKey: prepared.key.length > 0, strippedEffect: !prepared.effects.some((e: any) => e.type === "spectralRepair") };
+ },
+ { id: clipId, exported: Array.from(after) },
+ );
+ console.log("[spectral] preview vs export", JSON.stringify(parity));
+ expect(parity.appliedKey, "the preview path applied the regions").toBe(true);
+ expect(parity.strippedEffect).toBe(true);
+ expect(parity.residualDb, "preview and export samples agree (residual below -80 dB)").toBeLessThan(-80);
+
+ // One undo restores the original mixdown exactly (the band marquee first, then the removal); redo reapplies.
+ await page.evaluate(async () => {
+ await E().project.getState().undo();
+ await E().project.getState().undo();
+ });
+ await settle(page, 500);
+ expect(await history(page)).toBe(start);
+ const undone = Float32Array.from(await renderMix(page, 3.8));
+ expect(toneAmp(undone, 1000, 1, 3)).toBeCloseTo(beforeAmps.a1k, 6);
+ expect(toneAmp(undone, 3000, 1, 3)).toBeCloseTo(beforeAmps.a3k, 6);
+ await page.evaluate(async () => {
+ await E().project.getState().redo();
+ await E().project.getState().redo();
+ });
+ await settle(page, 500);
+ expect(db(beforeAmps.a1k, toneAmp(Float32Array.from(await renderMix(page, 3.8)), 1000, 1, 3))).toBeGreaterThan(25);
+
+ // Real export through the queue, decoded with ffmpeg: the edit is in the delivered file.
+ const job = await page.evaluate(
+ (settings) => E().exportQueue.getState().enqueue({ settings, presetLabel: "spectral", outputName: "spectral-edit" }).id as string,
+ { width: 640, height: 360, frameRate: 30, format: "mp4", codec: "h264", bitrate: 2000 },
+ );
+ await page.evaluate(() => E().exportQueue.getState().start());
+ await expect
+ .poll(() => page.evaluate((id) => E().exportQueue.getState().queue.jobs.find((j: any) => j.id === id)?.status as string, job), { timeout: 180_000, intervals: [500] })
+ .toMatch(/completed|failed/);
+ const status = await page.evaluate((id) => E().exportQueue.getState().queue.jobs.find((j: any) => j.id === id), job);
+ expect(status.status, status.error).toBe("completed");
+ const panel = page.getByTestId("export-queue-panel");
+ if (!(await panel.isVisible())) await page.getByRole("button", { name: "Export queue", exact: true }).click();
+ await panel.waitFor();
+ const [download] = await Promise.all([page.waitForEvent("download"), panel.getByRole("button", { name: "Download spectral-edit.mp4" }).click()]);
+ const file = join(workDir, "spectral-edit.mp4");
+ await download.saveAs(file);
+ const exported = decodeAudio(file);
+ const e440 = toneAmp(exported, 440, 1, 3);
+ const e1k = toneAmp(exported, 1000, 1, 3);
+ const e3k = toneAmp(exported, 3000, 1, 3);
+ console.log("[spectral] exported file", JSON.stringify({ e440, e1k, e3k }));
+ expect(db(e440, e1k), "exported file: the 1 kHz tone is gone (>= 20 dB under the 440 Hz tone)").toBeGreaterThan(20);
+ expect(db(e440, e3k), "exported file: the 3 kHz tone is 12 dB under the 440 Hz tone").toBeGreaterThan(11);
+ expect(db(e440, e3k)).toBeLessThan(13);
+});
diff --git a/apps/web/src/components/audio-spectral/SpectralEditor.tsx b/apps/web/src/components/audio-spectral/SpectralEditor.tsx
new file mode 100644
index 00000000..6c11a36c
--- /dev/null
+++ b/apps/web/src/components/audio-spectral/SpectralEditor.tsx
@@ -0,0 +1,513 @@
+import React, { useCallback, useEffect, useMemo, useRef, useState } from "react";
+import { newSpectralRegionId, DEFAULT_SPECTRAL_ATTENUATION_DB, type SpectralRegion, type SpectralView } from "@openreel/core";
+import { Button, Switch, cn } from "@openreel/ui";
+import { X } from "@/icons/lucide-compat";
+import { useProjectStore } from "../../stores/project-store";
+import {
+ commitSpectralRegions,
+ forgetSpectralView,
+ loadSpectralSource,
+ prepareSpectralView,
+ regionsOf,
+ requestSpectralView,
+ type SpectralSource,
+} from "../../services/spectral-edit";
+import {
+ COLOUR_MAPS,
+ FREQUENCY_RANGES,
+ bandFromPixels,
+ colourTable,
+ formatHz,
+ formatSeconds,
+ frequencyRange,
+ panTime,
+ pixelsToRect,
+ rectToPixels,
+ timeToX,
+ yToFreq,
+ zoomTime,
+ type ColourMapId,
+ type FrequencyRangeId,
+ type SpectralViewport,
+ type TimeFrequencyRect,
+} from "./spectral-geometry";
+
+interface SpectralEditorProps {
+ clipId: string;
+}
+
+type Tool = "box" | "band";
+const MIN_DRAG_PIXELS = 4;
+const AXIS_GUIDES = [50, 100, 200, 500, 1000, 2000, 5000, 10000, 20000];
+
+/** Paints a spectrogram window onto a canvas through a colour table; columns map by source time so a stale image stays aligned while a new one loads. */
+function paintSpectrogram(canvas: HTMLCanvasElement, view: SpectralView | null, viewport: SpectralViewport, colour: ColourMapId, clipRange: { start: number; end: number }): void {
+ const dpr = Math.min(2, window.devicePixelRatio || 1);
+ const w = Math.max(1, Math.round(viewport.width * dpr));
+ const h = Math.max(1, Math.round(viewport.height * dpr));
+ if (canvas.width !== w) canvas.width = w;
+ if (canvas.height !== h) canvas.height = h;
+ const ctx = canvas.getContext("2d");
+ if (!ctx) return;
+ ctx.clearRect(0, 0, w, h);
+ if (!view) return;
+ const table = colourTable(colour);
+ const image = ctx.createImageData(w, h);
+ const binHz = view.sampleRate / view.fftSize;
+ const rowPos = new Float32Array(h);
+ // On a log axis one pixel row spans many linear bins at the top, so a thin tone would fall between samples; each row takes the peak of the bins it covers.
+ const rowLo = new Int32Array(h);
+ const rowHi = new Int32Array(h);
+ const clampBin = (hz: number) => Math.max(0, Math.min(view.bins - 1, Math.round(hz / binHz)));
+ for (let y = 0; y < h; y += 1) {
+ const here = { ...viewport, height: h };
+ rowPos[y] = Math.max(0, Math.min(view.bins - 1.001, yToFreq(here, y + 0.5) / binHz));
+ rowLo[y] = clampBin(yToFreq(here, y + 1));
+ rowHi[y] = clampBin(yToFreq(here, y));
+ }
+ const span = view.endTime - view.startTime || 1;
+ for (let x = 0; x < w; x += 1) {
+ const t = viewport.startTime + ((x + 0.5) / w) * (viewport.endTime - viewport.startTime);
+ const column = ((t - view.startTime) / span) * view.frames;
+ const inside = column >= 0 && column < view.frames;
+ const base = Math.min(view.frames - 1, Math.max(0, Math.floor(column))) * view.bins;
+ const dim = t < clipRange.start || t > clipRange.end ? 0.45 : 1;
+ for (let y = 0; y < h; y += 1) {
+ const o = (y * w + x) * 4;
+ if (!inside) {
+ image.data[o + 3] = 255;
+ continue;
+ }
+ const p = rowPos[y];
+ const i0 = Math.floor(p);
+ const f = p - i0;
+ let v = Math.round(view.data[base + i0] * (1 - f) + view.data[base + i0 + 1] * f);
+ for (let k = rowLo[y]; k <= rowHi[y]; k += 1) v = Math.max(v, view.data[base + k]);
+ image.data[o] = table[v * 3] * dim;
+ image.data[o + 1] = table[v * 3 + 1] * dim;
+ image.data[o + 2] = table[v * 3 + 2] * dim;
+ image.data[o + 3] = 255;
+ }
+ }
+ ctx.putImageData(image, 0, 0);
+ ctx.font = `${9 * dpr}px ui-monospace, monospace`;
+ ctx.fillStyle = "rgba(255,255,255,0.8)";
+ ctx.strokeStyle = "rgba(255,255,255,0.16)";
+ ctx.lineWidth = dpr;
+ const scaled = { ...viewport, width: w, height: h };
+ for (const hz of AXIS_GUIDES) {
+ if (hz <= viewport.minHz * 1.05 || hz >= viewport.maxHz) continue;
+ const y = (1 - Math.log(hz / viewport.minHz) / Math.log(viewport.maxHz / viewport.minHz)) * h;
+ ctx.beginPath();
+ ctx.moveTo(0, y);
+ ctx.lineTo(w, y);
+ ctx.stroke();
+ ctx.fillText(hz >= 1000 ? `${hz / 1000}k` : `${hz}`, 3 * dpr, y - 2 * dpr);
+ }
+ const range = viewport.endTime - viewport.startTime;
+ const step = [0.01, 0.02, 0.05, 0.1, 0.2, 0.5, 1, 2, 5, 10, 30, 60, 120, 300].find((s) => range / s <= 6) ?? 600;
+ for (let t = Math.ceil(viewport.startTime / step) * step; t < viewport.endTime; t += step) {
+ const x = timeToX(scaled, t);
+ ctx.beginPath();
+ ctx.moveTo(x, 0);
+ ctx.lineTo(x, 5 * dpr);
+ ctx.stroke();
+ ctx.fillText(`${Number(t.toFixed(3))}s`, x + 2 * dpr, 12 * dpr);
+ }
+}
+
+const describeRegion = (region: SpectralRegion): string =>
+ `${region.mode === "remove" ? "Remove" : `Attenuate ${Math.abs(region.gainDb)} dB`} · ${formatSeconds(region.startTime)}-${formatSeconds(region.endTime)} · ${formatHz(region.lowHz)}-${formatHz(region.highHz)}`;
+
+/**
+ * The spectral editor: STFT spectrogram of the clip's source on a log frequency axis with zoom, a colour map,
+ * rectangle and frequency-band selection, and attenuate / remove. Every commit is one undoable edit to the clip's
+ * "spectralRepair" effect, applied identically in the preview and the export.
+ */
+export const SpectralEditor: React.FC<SpectralEditorProps> = ({ clipId }) => {
+ const clip = useProjectStore((state) => state.project.timeline.tracks.flatMap((track) => track.clips).find((candidate) => candidate.id === clipId));
+ const regions = useMemo(() => regionsOf(clip), [clip]);
+ const regionsRef = useRef(regions);
+ regionsRef.current = regions;
+
+ const [source, setSource] = useState<SpectralSource | null>(null);
+ const [error, setError] = useState<string | null>(null);
+ const [spectrogram, setSpectrogram] = useState<SpectralView | null>(null);
+ const [viewKey, setViewKey] = useState<string | null>(null);
+ const [window_, setWindow] = useState<{ startTime: number; endTime: number } | null>(null);
+ const [rangeId, setRangeId] = useState<FrequencyRangeId>("full");
+ const [colour, setColour] = useState<ColourMapId>("heat");
+ const [tool, setTool] = useState<Tool>("box");
+ const [selection, setSelection] = useState<TimeFrequencyRect | null>(null);
+ const [drag, setDrag] = useState<{ a: { x: number; y: number }; b: { x: number; y: number } } | null>(null);
+ const [attenuation, setAttenuation] = useState(Math.abs(DEFAULT_SPECTRAL_ATTENUATION_DB));
+ const [showOriginal, setShowOriginal] = useState(false);
+ const [expanded, setExpanded] = useState(false);
+ const [busy, setBusy] = useState(false);
+ const [size, setSize] = useState({ width: 280, height: 190 });
+ const stageRef = useRef<HTMLDivElement>(null);
+ const canvasRef = useRef<HTMLCanvasElement>(null);
+
+ // Decode the clip's source once per media file.
+ useEffect(() => {
+ let live = true;
+ setSource(null);
+ setSpectrogram(null);
+ setViewKey(null);
+ setSelection(null);
+ setError(null);
+ loadSpectralSource(clipId)
+ .then((loaded) => {
+ if (!live) return;
+ setSource(loaded);
+ setWindow({ startTime: 0, endTime: loaded.duration });
+ })
+ .catch((e: unknown) => live && setError(e instanceof Error ? e.message : "Could not open the clip's audio"));
+ return () => {
+ live = false;
+ };
+ }, [clipId, clip?.mediaId]);
+
+ // Track the stage size.
+ useEffect(() => {
+ const stage = stageRef.current;
+ if (!stage) return;
+ const measure = () => setSize({ width: Math.max(80, Math.floor(stage.clientWidth)), height: Math.max(80, Math.floor(stage.clientHeight)) });
+ measure();
+ const observer = new ResizeObserver(measure);
+ observer.observe(stage);
+ return () => observer.disconnect();
+ }, [expanded, source]);
+
+ const regionKey = useMemo(() => JSON.stringify(regions.filter((r) => r.enabled).map((r) => [r.mode, r.startTime, r.endTime, r.lowHz, r.highHz, r.gainDb])), [regions]);
+
+ // Edited (or original) audio -> the spectrogram worker.
+ useEffect(() => {
+ if (!source) return;
+ let live = true;
+ setBusy(true);
+ prepareSpectralView(source, regionsRef.current, showOriginal)
+ .then((key) => live && setViewKey(key))
+ .catch((e: unknown) => live && setError(e instanceof Error ? e.message : "Could not compute the spectrogram"))
+ .finally(() => live && setBusy(false));
+ return () => {
+ live = false;
+ };
+ }, [source, regionKey, showOriginal]);
+
+ const nyquist = (source?.sampleRate ?? 48000) / 2;
+ const { minHz, maxHz } = frequencyRange(rangeId, nyquist);
+ const viewport: SpectralViewport = {
+ startTime: window_?.startTime ?? 0,
+ endTime: window_?.endTime ?? 1,
+ minHz,
+ maxHz,
+ width: size.width,
+ height: size.height,
+ };
+ const duration = source?.duration ?? 0;
+
+ // Debounced spectrogram window request.
+ const startKey = window_ ? `${window_.startTime.toFixed(4)}:${window_.endTime.toFixed(4)}` : "";
+ useEffect(() => {
+ if (!viewKey || !window_) return;
+ let live = true;
+ const timer = setTimeout(() => {
+ requestSpectralView(viewKey, { startTime: window_.startTime, endTime: window_.endTime, maxFrames: Math.min(1400, Math.max(60, size.width)), fftSize: 4096 })
+ .then((view) => live && setSpectrogram(view))
+ .catch(() => {
+ forgetSpectralView(viewKey);
+ if (live) setViewKey(null);
+ if (live && source) void prepareSpectralView(source, regionsRef.current, showOriginal).then((key) => live && setViewKey(key));
+ });
+ }, 90);
+ return () => {
+ live = false;
+ clearTimeout(timer);
+ };
+ // eslint-disable-next-line react-hooks/exhaustive-deps
+ }, [viewKey, startKey, size.width]);
+
+ useEffect(() => {
+ if (canvasRef.current) paintSpectrogram(canvasRef.current, spectrogram, viewport, colour, { start: clip?.inPoint ?? 0, end: clip?.outPoint ?? duration });
+ // eslint-disable-next-line react-hooks/exhaustive-deps
+ }, [spectrogram, size, colour, rangeId, startKey, clip?.inPoint, clip?.outPoint]);
+
+ useEffect(() => {
+ if (!expanded) return;
+ const onKey = (event: KeyboardEvent) => event.key === "Escape" && setExpanded(false);
+ globalThis.addEventListener("keydown", onKey);
+ return () => globalThis.removeEventListener("keydown", onKey);
+ }, [expanded]);
+
+ const local = (event: React.PointerEvent): { x: number; y: number } => {
+ const box = stageRef.current!.getBoundingClientRect();
+ return { x: Math.max(0, Math.min(box.width, event.clientX - box.left)), y: Math.max(0, Math.min(box.height, event.clientY - box.top)) };
+ };
+ const onPointerDown = (event: React.PointerEvent) => {
+ if (event.button !== 0 || !source) return;
+ event.currentTarget.setPointerCapture?.(event.pointerId);
+ const p = local(event);
+ setDrag({ a: p, b: p });
+ };
+ const onPointerMove = (event: React.PointerEvent) => {
+ if (drag) setDrag({ a: drag.a, b: local(event) });
+ };
+ const onPointerUp = (event: React.PointerEvent) => {
+ if (!drag || !source) return;
+ const b = local(event);
+ const wide = Math.abs(b.x - drag.a.x) >= MIN_DRAG_PIXELS;
+ const tall = Math.abs(b.y - drag.a.y) >= MIN_DRAG_PIXELS;
+ setDrag(null);
+ if (tool === "band" ? tall : wide && tall) {
+ setSelection(tool === "band" ? bandFromPixels(viewport, drag.a.y, b.y, source.duration, nyquist) : pixelsToRect(viewport, drag.a, b, source.duration, nyquist));
+ } else if (!wide && !tall) setSelection(null);
+ };
+
+ const commit = useCallback(
+ async (mode: "attenuate" | "remove") => {
+ if (!selection) return;
+ const region: SpectralRegion = {
+ id: newSpectralRegionId(),
+ mode,
+ startTime: selection.startTime,
+ endTime: selection.endTime,
+ lowHz: selection.lowHz,
+ highHz: selection.highHz,
+ gainDb: mode === "attenuate" ? -Math.abs(attenuation) : -120,
+ enabled: true,
+ };
+ if (region.endTime - region.startTime < 1e-3 || region.highHz <= region.lowHz) return;
+ const ok = await commitSpectralRegions(clipId, [...regionsRef.current, region]);
+ if (ok) setSelection(null);
+ else setError("Could not apply that edit.");
+ },
+ [attenuation, clipId, selection],
+ );
+
+ const zoom = (factor: number) => {
+ if (!window_ || !source) return;
+ const anchor = selection ? (selection.startTime + selection.endTime) / 2 : (window_.startTime + window_.endTime) / 2;
+ setWindow(zoomTime(window_.startTime, window_.endTime, source.duration, factor, anchor));
+ };
+ const zoomed = window_ && source ? window_.endTime - window_.startTime < source.duration - 1e-6 : false;
+
+ if (error && !source) {
+ return (
+ <p role="alert" className="text-[11px] text-status-error" data-testid="spectral-error">
+ {error}
+ </p>
+ );
+ }
+
+ const dragRect = drag
+ ? tool === "band"
+ ? { x: 0, y: Math.min(drag.a.y, drag.b.y), width: size.width, height: Math.abs(drag.b.y - drag.a.y) }
+ : { x: Math.min(drag.a.x, drag.b.x), y: Math.min(drag.a.y, drag.b.y), width: Math.abs(drag.b.x - drag.a.x), height: Math.abs(drag.b.y - drag.a.y) }
+ : null;
+ const selectionPx = selection ? rectToPixels(viewport, selection) : null;
+
+ return (
+ <div
+ className={cn("flex min-w-0 flex-col gap-2", expanded && "fixed inset-4 z-50 overflow-auto rounded-lg border border-border bg-bg-0 p-4 shadow-2xl")}
+ data-testid="spectral-editor"
+ data-expanded={expanded}
+ >
+ <p className="text-[11px] leading-snug text-fg-muted">
+ Drag a box over the sound you want to change, then attenuate or remove it. Edits are saved on the clip, can be undone, and play the same in preview and export.
+ </p>
+ <div className="flex flex-wrap items-center gap-1.5">
+ <div role="group" aria-label="Selection tool" className="flex overflow-hidden rounded border border-border">
+ {(["box", "band"] as const).map((id) => (
+ <button
+ key={id}
+ type="button"
+ aria-pressed={tool === id}
+ data-testid={`spectral-tool-${id}`}
+ onClick={() => setTool(id)}
+ className={cn("px-2 py-1 text-[11px]", tool === id ? "bg-accent text-white" : "bg-bg-1 text-fg hover:bg-bg-2")}
+ >
+ {id === "box" ? "Box" : "Frequency band"}
+ </button>
+ ))}
+ </div>
+ <Button type="button" variant="outline" size="sm" className="h-6 px-2 text-[11px]" onClick={() => zoom(0.5)} disabled={!source} data-testid="spectral-zoom-in" aria-label="Zoom in">
+ +
+ </Button>
+ <Button type="button" variant="outline" size="sm" className="h-6 px-2 text-[11px]" onClick={() => zoom(2)} disabled={!source || !zoomed} data-testid="spectral-zoom-out" aria-label="Zoom out">
+ -
+ </Button>
+ <Button type="button" variant="outline" size="sm" className="h-6 px-2 text-[11px]" onClick={() => source && setWindow({ startTime: 0, endTime: source.duration })} disabled={!source || !zoomed} data-testid="spectral-zoom-fit">
+ Fit
+ </Button>
+ <select
+ aria-label="Frequency range"
+ value={rangeId}
+ onChange={(e) => setRangeId(e.target.value as FrequencyRangeId)}
+ className="h-6 rounded border border-border bg-bg-1 px-1 text-[11px] text-fg"
+ data-testid="spectral-range"
+ >
+ {FREQUENCY_RANGES.map((range) => (
+ <option key={range.id} value={range.id}>
+ {range.label}
+ </option>
+ ))}
+ </select>
+ <select
+ aria-label="Colour map"
+ value={colour}
+ onChange={(e) => setColour(e.target.value as ColourMapId)}
+ className="h-6 rounded border border-border bg-bg-1 px-1 text-[11px] text-fg"
+ data-testid="spectral-colour"
+ >
+ {COLOUR_MAPS.map((map) => (
+ <option key={map.id} value={map.id}>
+ {map.label}
+ </option>
+ ))}
+ </select>
+ <Button type="button" variant="ghost" size="sm" className="ml-auto h-6 px-2 text-[11px]" onClick={() => setExpanded((v) => !v)} data-testid="spectral-expand" aria-pressed={expanded}>
+ {expanded ? "Close" : "Expand"}
+ </Button>
+ </div>
+
+ <div
+ ref={stageRef}
+ className={cn("relative w-full cursor-crosshair touch-none select-none overflow-hidden rounded border border-border bg-bg-1", expanded ? "min-h-0 flex-1" : "h-[190px]")}
+ style={expanded ? { minHeight: 320 } : undefined}
+ onPointerDown={onPointerDown}
+ onPointerMove={onPointerMove}
+ onPointerUp={onPointerUp}
+ onPointerCancel={() => setDrag(null)}
+ data-testid="spectral-stage"
+ data-start={viewport.startTime}
+ data-end={viewport.endTime}
+ data-min-hz={viewport.minHz}
+ data-max-hz={viewport.maxHz}
+ data-duration={duration}
+ data-nyquist={nyquist}
+ >
+ <canvas ref={canvasRef} className="absolute inset-0 h-full w-full" role="img" aria-label="Spectrogram of the clip's audio" data-testid="spectral-canvas" data-ready={spectrogram && !busy ? "true" : "false"} />
+ <div className="pointer-events-none absolute inset-0">
+ {regions.map((region) => {
+ const box = rectToPixels(viewport, region);
+ return (
+ <div
+ key={region.id}
+ data-testid={`spectral-region-${region.id}`}
+ data-mode={region.mode}
+ className={cn("absolute border", region.mode === "remove" ? "border-red-400 bg-red-500/25" : "border-sky-300 bg-sky-400/25", !region.enabled && "opacity-30")}
+ style={{ left: box.x, top: box.y, width: Math.max(1, box.width), height: Math.max(1, box.height) }}
+ />
+ );
+ })}
+ {selectionPx && (
+ <div
+ data-testid="spectral-selection"
+ className="absolute border border-dashed border-white bg-white/15"
+ style={{ left: selectionPx.x, top: selectionPx.y, width: Math.max(1, selectionPx.width), height: Math.max(1, selectionPx.height) }}
+ />
+ )}
+ {dragRect && <div className="absolute border border-dashed border-white/80 bg-white/10" style={{ left: dragRect.x, top: dragRect.y, width: dragRect.width, height: dragRect.height }} />}
+ </div>
+ {!source && (
+ <div className="absolute inset-0 flex items-center justify-center text-[11px] text-fg-muted" data-testid="spectral-loading">
+ Decoding audio…
+ </div>
+ )}
+ </div>
+
+ {zoomed && window_ && source && (
+ <input
+ type="range"
+ aria-label="Pan the spectrogram"
+ min={0}
+ max={Math.max(0, source.duration - (window_.endTime - window_.startTime))}
+ step={0.01}
+ value={window_.startTime}
+ onChange={(e) => setWindow(panTime(window_.startTime, window_.endTime, source.duration, Number(e.target.value) - window_.startTime))}
+ className="w-full"
+ data-testid="spectral-pan"
+ />
+ )}
+
+ <div className="flex min-h-[18px] items-center justify-between gap-2 text-[10px] text-fg-muted" data-testid="spectral-readout">
+ <span className="truncate">
+ {selection
+ ? `Selection ${formatSeconds(selection.startTime)}-${formatSeconds(selection.endTime)}, ${formatHz(selection.lowHz)}-${formatHz(selection.highHz)}`
+ : source
+ ? `${formatSeconds(viewport.startTime)} to ${formatSeconds(viewport.endTime)} of ${formatSeconds(source.duration)}${busy ? " (updating)" : ""}`
+ : ""}
+ </span>
+ <label className="flex shrink-0 items-center gap-1">
+ <span>Original</span>
+ <Switch checked={showOriginal} onCheckedChange={setShowOriginal} aria-label="Show the original, unedited spectrogram" className="workspace-switch flex-none" data-testid="spectral-show-original" />
+ </label>
+ </div>
+
+ <div className="flex flex-wrap items-center gap-1.5" data-testid="spectral-actions">
+ <label className="flex items-center gap-1 text-[11px] text-fg">
+ <span>Attenuate by</span>
+ <input
+ type="number"
+ min={1}
+ max={120}
+ step={1}
+ value={attenuation}
+ onChange={(e) => setAttenuation(Math.max(1, Math.min(120, Number(e.target.value) || 1)))}
+ className="h-6 w-14 rounded border border-border bg-bg-1 px-1 text-[11px] text-fg"
+ aria-label="Attenuation in dB"
+ data-testid="spectral-db"
+ />
+ <span>dB</span>
+ </label>
+ <Button type="button" size="sm" className="h-6 px-2 text-[11px]" disabled={!selection} onClick={() => void commit("attenuate")} data-testid="spectral-attenuate">
+ Attenuate
+ </Button>
+ <Button type="button" size="sm" variant="outline" className="h-6 px-2 text-[11px]" disabled={!selection} onClick={() => void commit("remove")} data-testid="spectral-remove">
+ Remove
+ </Button>
+ <Button type="button" size="sm" variant="ghost" className="h-6 px-2 text-[11px]" disabled={!selection} onClick={() => setSelection(null)} data-testid="spectral-clear-selection">
+ Clear selection
+ </Button>
+ </div>
+ {error && (
+ <p role="alert" className="text-[11px] text-status-error" data-testid="spectral-error">
+ {error}
+ </p>
+ )}
+
+ {regions.length > 0 && (
+ <div className="flex flex-col gap-1" data-testid="spectral-regions">
+ <span className="text-[10px] font-semibold uppercase tracking-wide text-fg-muted">Edits on this clip</span>
+ {regions.map((region) => (
+ <div key={region.id} className="flex min-w-0 items-center gap-1.5 rounded border border-border bg-bg-1 px-1.5 py-1" data-testid="spectral-region-row">
+ <Switch
+ checked={region.enabled}
+ onCheckedChange={(on) => void commitSpectralRegions(clipId, regionsRef.current.map((r) => (r.id === region.id ? { ...r, enabled: on } : r)))}
+ aria-label={`${region.enabled ? "Bypass" : "Enable"} edit ${describeRegion(region)}`}
+ className="workspace-switch flex-none"
+ />
+ <span className="min-w-0 flex-1 truncate text-[10px] text-fg" title={describeRegion(region)}>
+ {describeRegion(region)}
+ </span>
+ <Button
+ type="button"
+ variant="ghost"
+ size="icon-sm"
+ className="size-5 shrink-0 text-fg-muted hover:text-status-error"
+ aria-label={`Delete edit ${describeRegion(region)}`}
+ onClick={() => void commitSpectralRegions(clipId, regionsRef.current.filter((r) => r.id !== region.id))}
+ >
+ <X size={11} aria-hidden />
+ </Button>
+ </div>
+ ))}
+ </div>
+ )}
+ </div>
+ );
+};
+
+export default SpectralEditor;
+
diff --git a/apps/web/src/components/audio-spectral/spectral-geometry.test.ts b/apps/web/src/components/audio-spectral/spectral-geometry.test.ts
new file mode 100644
index 00000000..f2837f2a
--- /dev/null
+++ b/apps/web/src/components/audio-spectral/spectral-geometry.test.ts
@@ -0,0 +1,89 @@
+import { describe, expect, it } from "vitest";
+import {
+ bandFromPixels,
+ colourTable,
+ formatHz,
+ freqToY,
+ frequencyRange,
+ panTime,
+ pixelsToRect,
+ rectToPixels,
+ timeToX,
+ xToTime,
+ yToFreq,
+ zoomTime,
+ type SpectralViewport,
+} from "./spectral-geometry";
+
+const view: SpectralViewport = { startTime: 2, endTime: 6, minHz: 30, maxHz: 24000, width: 400, height: 200 };
+
+describe("spectral viewport geometry", () => {
+ it("maps time linearly and frequency logarithmically, and round-trips", () => {
+ expect(timeToX(view, 2)).toBe(0);
+ expect(timeToX(view, 6)).toBe(400);
+ expect(xToTime(view, 100)).toBeCloseTo(3, 9);
+ expect(freqToY(view, 24000)).toBeCloseTo(0, 6);
+ expect(freqToY(view, 30)).toBeCloseTo(200, 6);
+ for (const hz of [60, 440, 1000, 8000]) expect(yToFreq(view, freqToY(view, hz))).toBeCloseTo(hz, 6);
+ // Equal octaves are equal heights.
+ expect(freqToY(view, 200) - freqToY(view, 400)).toBeCloseTo(freqToY(view, 2000) - freqToY(view, 4000), 6);
+ });
+
+ it("turns a dragged box into a clamped time-frequency rectangle, in either drag direction", () => {
+ const a = { x: 100, y: freqToY(view, 2000) };
+ const b = { x: 300, y: freqToY(view, 500) };
+ const forward = pixelsToRect(view, a, b, 5, 24000);
+ const backward = pixelsToRect(view, b, a, 5, 24000);
+ expect(forward).toEqual(backward);
+ expect(forward.startTime).toBeCloseTo(3, 6);
+ expect(forward.endTime).toBeCloseTo(5, 6);
+ expect(forward.lowHz).toBeCloseTo(500, 4);
+ expect(forward.highHz).toBeCloseTo(2000, 4);
+ const clamped = pixelsToRect(view, { x: 0, y: 0 }, { x: 400, y: 200 }, 4.5, 20000);
+ expect(clamped.endTime).toBe(4.5);
+ expect(clamped.highHz).toBe(20000);
+ });
+
+ it("a frequency-band marquee spans the whole source whatever the zoom", () => {
+ const band = bandFromPixels(view, freqToY(view, 1000), freqToY(view, 3000), 12, 24000);
+ expect(band.startTime).toBe(0);
+ expect(band.endTime).toBe(12);
+ expect(band.lowHz).toBeCloseTo(1000, 4);
+ expect(band.highHz).toBeCloseTo(3000, 4);
+ });
+
+ it("projects a region back to pixels", () => {
+ const px = rectToPixels(view, { startTime: 3, endTime: 5, lowHz: 500, highHz: 2000 });
+ expect(px.x).toBeCloseTo(100, 6);
+ expect(px.width).toBeCloseTo(200, 6);
+ expect(px.y).toBeCloseTo(freqToY(view, 2000), 6);
+ expect(px.height).toBeCloseTo(freqToY(view, 500) - freqToY(view, 2000), 6);
+ });
+
+ it("zooms around an anchor and pans without leaving the source", () => {
+ const zoomed = zoomTime(0, 10, 10, 0.5, 5);
+ expect(zoomed.endTime - zoomed.startTime).toBeCloseTo(5, 9);
+ expect(zoomed.startTime).toBeCloseTo(2.5, 9);
+ const edge = zoomTime(0, 10, 10, 0.1, 0.2);
+ expect(edge.startTime).toBeCloseTo(0.18, 9); // the anchor keeps its relative position
+ expect(zoomTime(2, 4, 10, 100, 3)).toEqual({ startTime: 0, endTime: 10 });
+ expect(panTime(2, 4, 10, 100)).toEqual({ startTime: 8, endTime: 10 });
+ expect(panTime(2, 4, 10, -100)).toEqual({ startTime: 0, endTime: 2 });
+ });
+
+ it("keeps frequency presets inside Nyquist and formats labels", () => {
+ expect(frequencyRange("high", 8000)).toEqual({ minHz: 1000, maxHz: 8000 });
+ expect(frequencyRange("full", 24000).maxHz).toBe(24000);
+ expect(formatHz(440)).toBe("440 Hz");
+ expect(formatHz(2500)).toBe("2.5 kHz");
+ });
+
+ it("builds monotone colour tables", () => {
+ for (const id of ["heat", "viridis", "mono"] as const) {
+ const table = colourTable(id);
+ expect(table).toHaveLength(768);
+ const luma = (i: number) => table[i * 3] + table[i * 3 + 1] + table[i * 3 + 2];
+ expect(luma(255)).toBeGreaterThan(luma(0));
+ }
+ });
+});
diff --git a/apps/web/src/components/audio-spectral/spectral-geometry.ts b/apps/web/src/components/audio-spectral/spectral-geometry.ts
new file mode 100644
index 00000000..ab563266
--- /dev/null
+++ b/apps/web/src/components/audio-spectral/spectral-geometry.ts
@@ -0,0 +1,139 @@
+/** Pure mapping between pixels and (source time, frequency) for the spectral editor; the frequency axis is logarithmic. */
+
+export interface SpectralViewport {
+ /** Visible source-time window, seconds. */
+ readonly startTime: number;
+ readonly endTime: number;
+ /** Visible frequency window, Hz (log axis). */
+ readonly minHz: number;
+ readonly maxHz: number;
+ readonly width: number;
+ readonly height: number;
+}
+
+export interface TimeFrequencyRect {
+ readonly startTime: number;
+ readonly endTime: number;
+ readonly lowHz: number;
+ readonly highHz: number;
+}
+
+export interface PixelRect {
+ readonly x: number;
+ readonly y: number;
+ readonly width: number;
+ readonly height: number;
+}
+
+export const MIN_VIEW_SECONDS = 0.05;
+
+const clamp = (v: number, lo: number, hi: number) => Math.max(lo, Math.min(hi, v));
+
+export const timeToX = (view: SpectralViewport, t: number): number => ((t - view.startTime) / (view.endTime - view.startTime)) * view.width;
+export const xToTime = (view: SpectralViewport, x: number): number => view.startTime + (x / view.width) * (view.endTime - view.startTime);
+
+export const freqToY = (view: SpectralViewport, hz: number): number => {
+ const span = Math.log(view.maxHz / view.minHz);
+ return (1 - Math.log(clamp(hz, 1e-3, 1e9) / view.minHz) / span) * view.height;
+};
+export const yToFreq = (view: SpectralViewport, y: number): number => view.minHz * Math.exp((1 - y / view.height) * Math.log(view.maxHz / view.minHz));
+
+/** A dragged pixel box as a time-frequency rectangle clamped to the source and the audible range. */
+export function pixelsToRect(view: SpectralViewport, a: { x: number; y: number }, b: { x: number; y: number }, duration: number, nyquist: number): TimeFrequencyRect {
+ const t0 = clamp(xToTime(view, Math.min(a.x, b.x)), 0, duration);
+ const t1 = clamp(xToTime(view, Math.max(a.x, b.x)), 0, duration);
+ const f0 = clamp(yToFreq(view, Math.max(a.y, b.y)), 0, nyquist);
+ const f1 = clamp(yToFreq(view, Math.min(a.y, b.y)), 0, nyquist);
+ return { startTime: t0, endTime: t1, lowHz: f0, highHz: f1 };
+}
+
+/** A frequency-band marquee: the dragged vertical extent over the whole source. */
+export function bandFromPixels(view: SpectralViewport, y0: number, y1: number, duration: number, nyquist: number): TimeFrequencyRect {
+ return {
+ startTime: 0,
+ endTime: duration,
+ lowHz: clamp(yToFreq(view, Math.max(y0, y1)), 0, nyquist),
+ highHz: clamp(yToFreq(view, Math.min(y0, y1)), 0, nyquist),
+ };
+}
+
+export function rectToPixels(view: SpectralViewport, rect: TimeFrequencyRect): PixelRect {
+ const x0 = timeToX(view, rect.startTime);
+ const x1 = timeToX(view, rect.endTime);
+ const y0 = freqToY(view, rect.highHz);
+ const y1 = freqToY(view, Math.max(rect.lowHz, view.minHz * 0.5));
+ return { x: x0, y: y0, width: x1 - x0, height: y1 - y0 };
+}
+
+/** Zooms the time window by `factor` (< 1 zooms in) around `anchor` (seconds), staying inside [0, duration]. */
+export function zoomTime(startTime: number, endTime: number, duration: number, factor: number, anchor: number): { startTime: number; endTime: number } {
+ const span = clamp((endTime - startTime) * factor, Math.min(MIN_VIEW_SECONDS, duration), Math.max(duration, MIN_VIEW_SECONDS));
+ const ratio = endTime > startTime ? clamp((anchor - startTime) / (endTime - startTime), 0, 1) : 0.5;
+ let start = anchor - span * ratio;
+ start = clamp(start, 0, Math.max(0, duration - span));
+ return { startTime: start, endTime: Math.min(duration, start + span) };
+}
+
+/** Pans the window by `delta` seconds, staying inside [0, duration]. */
+export function panTime(startTime: number, endTime: number, duration: number, delta: number): { startTime: number; endTime: number } {
+ const span = endTime - startTime;
+ const start = clamp(startTime + delta, 0, Math.max(0, duration - span));
+ return { startTime: start, endTime: start + span };
+}
+
+export const FREQUENCY_RANGES = [
+ { id: "full", label: "Full range", minHz: 30, maxHz: Infinity },
+ { id: "low", label: "Low (30 Hz - 1 kHz)", minHz: 30, maxHz: 1000 },
+ { id: "voice", label: "Voice (80 Hz - 8 kHz)", minHz: 80, maxHz: 8000 },
+ { id: "high", label: "High (1 kHz - Nyquist)", minHz: 1000, maxHz: Infinity },
+] as const;
+export type FrequencyRangeId = (typeof FREQUENCY_RANGES)[number]["id"];
+
+export function frequencyRange(id: FrequencyRangeId, nyquist: number): { minHz: number; maxHz: number } {
+ const range = FREQUENCY_RANGES.find((item) => item.id === id) ?? FREQUENCY_RANGES[0];
+ return { minHz: Math.min(range.minHz, nyquist / 4), maxHz: Math.min(range.maxHz, nyquist) };
+}
+
+export function formatHz(hz: number): string {
+ return hz >= 1000 ? `${(hz / 1000).toFixed(hz >= 10000 ? 1 : 2).replace(/\.?0+$/, "")} kHz` : `${Math.round(hz)} Hz`;
+}
+
+export function formatSeconds(seconds: number): string {
+ const s = Math.max(0, seconds);
+ return s >= 60 ? `${Math.floor(s / 60)}:${(s % 60).toFixed(2).padStart(5, "0")}` : `${s.toFixed(2)} s`;
+}
+
+export type ColourMapId = "heat" | "viridis" | "mono";
+export const COLOUR_MAPS: ReadonlyArray<{ id: ColourMapId; label: string }> = [
+ { id: "heat", label: "Heat" },
+ { id: "viridis", label: "Viridis" },
+ { id: "mono", label: "Grey" },
+];
+
+const STOPS: Record<ColourMapId, Array<[number, number, number, number]>> = {
+ heat: [[0, 8, 10, 24], [0.3, 52, 36, 120], [0.55, 170, 52, 120], [0.8, 244, 150, 40], [1, 255, 248, 214]],
+ viridis: [[0, 68, 1, 84], [0.25, 59, 82, 139], [0.5, 33, 145, 140], [0.75, 94, 201, 98], [1, 253, 231, 37]],
+ mono: [[0, 0, 0, 0], [1, 255, 255, 255]],
+};
+
+const tables = new Map<ColourMapId, Uint8ClampedArray>();
+/** 256-entry RGB table for a colour map. */
+export function colourTable(id: ColourMapId): Uint8ClampedArray {
+ const cached = tables.get(id);
+ if (cached) return cached;
+ const stops = STOPS[id];
+ const out = new Uint8ClampedArray(256 * 3);
+ for (let i = 0; i < 256; i += 1) {
+ const t = i / 255;
+ let k = 0;
+ while (k < stops.length - 2 && t > stops[k + 1][0]) k += 1;
+ const [t0, r0, g0, b0] = stops[k];
+ const [t1, r1, g1, b1] = stops[k + 1];
+ const f = (t - t0) / (t1 - t0);
+ out[i * 3] = r0 + (r1 - r0) * f;
+ out[i * 3 + 1] = g0 + (g1 - g0) * f;
+ out[i * 3 + 2] = b0 + (b1 - b0) * f;
+ }
+ tables.set(id, out);
+ return out;
+}
diff --git a/apps/web/src/components/editor/ExportCaptionOptions.tsx b/apps/web/src/components/editor/ExportCaptionOptions.tsx
index c9465f7a..23649f70 100644
--- a/apps/web/src/components/editor/ExportCaptionOptions.tsx
+++ b/apps/web/src/components/editor/ExportCaptionOptions.tsx
@@ -25,7 +25,7 @@ interface ExportCaptionOptionsProps {
subtitles: readonly Subtitle[];
value: CaptionExportSettings;
onChange: (next: CaptionExportSettings) => void;
- format: "mp4" | "webm" | "mov" | "mxf";
+ format: "mp4" | "webm" | "mov" | "mxf" | "mkv";
isDesktop: boolean;
frameRate: number;
}
diff --git a/apps/web/src/components/editor/ExportDialog.tsx b/apps/web/src/components/editor/ExportDialog.tsx
index aeb5b489..c98f373a 100644
--- a/apps/web/src/components/editor/ExportDialog.tsx
+++ b/apps/web/src/components/editor/ExportDialog.tsx
@@ -40,7 +40,7 @@ import {
AlertTriangle,
X,
} from "@/icons/lucide-compat";
-import { isBroadcastCodec, effectiveRateControl, twoPassAvailability, BURN_IN_POSITIONS, DEFAULT_TIMECODE_BURN_IN, type TimecodeBurnInSettings, type BurnInPosition } from "@openreel/core";
+import { isBroadcastCodec, isDolbyFormat, dolbyContainerProblem, defaultDolbyBitrate, DOLBY_LABEL, DOLBY_VIDEO_CONTAINERS, DOLBY_VIDEO_DESKTOP_ONLY_REASON, effectiveRateControl, twoPassAvailability, BURN_IN_POSITIONS, DEFAULT_TIMECODE_BURN_IN, type TimecodeBurnInSettings, type BurnInPosition } from "@openreel/core";
import { EncoderPicker } from "./EncoderPicker";
import {
Button,
@@ -80,6 +80,7 @@ import {
} from "../../services/export-presets";
import type {
VideoExportSettings,
+ AudioExportSettings,
UpscaleQuality,
CompressionQuality,
CompressionSource,
@@ -127,6 +128,7 @@ import { usePhoneEditor } from "../../hooks/usePhoneEditor";
import { ExportCaptionOptions } from "./ExportCaptionOptions";
import { ExportStillPanel } from "./ExportStillPanel";
import { ExportBroadcastOptions } from "./ExportBroadcastOptions";
+import { ExportDolbyOptions } from "./ExportDolbyOptions";
import { saveCaptionSidecars, sidecarFilesFor } from "../../services/caption-sidecar";
import { exportFilename } from "../../services/export-runner";
import type { CaptionExportSettings } from "@openreel/core";
@@ -1815,12 +1817,17 @@ export const ExportDialog: React.FC<ExportDialogProps> = ({
? "vp9"
: value === "mxf"
? (customSettings.codec === "dnxhr" || isBroadcastCodec(customSettings.codec) ? customSettings.codec : "dnxhr")
- : customSettings.codec === "vp9" ||
+ : (customSettings.codec === "vp9" && value !== "mkv") ||
customSettings.codec === "vp8" ||
(customSettings.codec === "dnxhr" && value !== "mov") ||
(isBroadcastCodec(customSettings.codec) && value !== "mov")
? "h264"
: customSettings.codec,
+ // WebM and MXF cannot carry AC-3 / E-AC-3: the track goes back to AAC (or PCM for MXF).
+ audioSettings:
+ isDolbyFormat(customSettings.audioSettings.format) && dolbyContainerProblem(value)
+ ? { ...customSettings.audioSettings, format: "aac", bitrate: 192 }
+ : customSettings.audioSettings,
// OP-Atom only exists in MXF.
broadcast: value === "mxf" || !customSettings.broadcast?.mxfPattern
? customSettings.broadcast
@@ -1839,7 +1846,7 @@ export const ExportDialog: React.FC<ExportDialogProps> = ({
{ value: "mp4", label: "MP4" },
{ value: "webm", label: "WebM" },
{ value: "mov", label: "MOV" },
- ...(isDesktop ? [{ value: "mxf", label: "MXF" }] : []),
+ ...(isDesktop ? [{ value: "mxf", label: "MXF" }, { value: "mkv", label: "MKV" }] : []),
].map((option) => (
<SelectItem
key={option.value}
@@ -2420,6 +2427,11 @@ export const ExportDialog: React.FC<ExportDialogProps> = ({
<p className="text-[10px] text-fg-muted">
Compatible with this container
</p>
+ {isDolbyFormat(customSettings.audioSettings.format) && (
+ <p className="text-[10px] text-status-warning" data-testid="export-dolby-desktop-only">
+ {DOLBY_VIDEO_DESKTOP_ONLY_REASON}
+ </p>
+ )}
</div>
) : (
<div className="space-y-1.5">
@@ -2436,12 +2448,13 @@ export const ExportDialog: React.FC<ExportDialogProps> = ({
...customSettings,
audioSettings: {
...customSettings.audioSettings,
- format: value as
- | "mp3"
- | "wav"
- | "aac"
- | "flac"
- | "ogg",
+ format: value as AudioExportSettings["format"],
+ // A Dolby format starts at its usual rate for the channel count; leaving one returns to AAC's.
+ ...(isDolbyFormat(value)
+ ? { bitrate: defaultDolbyBitrate(value, sequenceIsSurround && audioChannelChoice === "5.1" ? 6 : 2) }
+ : isDolbyFormat(customSettings.audioSettings.format)
+ ? { bitrate: 192, dialnorm: undefined }
+ : {}),
},
})
}
@@ -2457,6 +2470,9 @@ export const ExportDialog: React.FC<ExportDialogProps> = ({
{ value: "aac", label: "AAC" },
{ value: "mp3", label: "MP3" },
{ value: "wav", label: "WAV" },
+ ...(DOLBY_VIDEO_CONTAINERS.includes(customSettings.format)
+ ? (["ac3", "eac3"] as const).map((codec) => ({ value: codec, label: DOLBY_LABEL[codec] }))
+ : []),
].map((option) => (
<SelectItem
key={option.value}
@@ -2499,7 +2515,7 @@ export const ExportDialog: React.FC<ExportDialogProps> = ({
{[
{ value: "44100", label: "44.1 kHz" },
{ value: "48000", label: "48 kHz" },
- { value: "96000", label: "96 kHz" },
+ ...(isDolbyFormat(customSettings.audioSettings.format) ? [] : [{ value: "96000", label: "96 kHz" }]),
].map((option) => (
<SelectItem
key={option.value}
@@ -2512,49 +2528,58 @@ export const ExportDialog: React.FC<ExportDialogProps> = ({
</SelectContent>
</Select>
</div>
- <div className="space-y-1.5">
- <Label
- htmlFor="export-audio-bitrate"
- className="text-[11px] text-fg-2"
- >
- Audio bitrate
- </Label>
- <Select
- value={String(customSettings.audioSettings.bitrate)}
- onValueChange={(value) =>
- setCustomSettings({
- ...customSettings,
- audioSettings: {
- ...customSettings.audioSettings,
- bitrate: Number(value),
- },
- })
- }
- >
- <SelectTrigger
- id="export-audio-bitrate"
- className="h-8 w-full text-xs"
+ {!(isDesktop && isDolbyFormat(customSettings.audioSettings.format)) && (
+ <div className="space-y-1.5">
+ <Label
+ htmlFor="export-audio-bitrate"
+ className="text-[11px] text-fg-2"
>
- <SelectValue />
- </SelectTrigger>
- <SelectContent>
- {[
- { value: "128", label: "128 kbps" },
- { value: "192", label: "192 kbps" },
- { value: "256", label: "256 kbps" },
- { value: "320", label: "320 kbps" },
- ].map((option) => (
- <SelectItem
- key={option.value}
- value={option.value}
- className="text-xs"
- >
- {option.label}
- </SelectItem>
- ))}
- </SelectContent>
- </Select>
- </div>
+ Audio bitrate
+ </Label>
+ <Select
+ value={String(customSettings.audioSettings.bitrate)}
+ onValueChange={(value) =>
+ setCustomSettings({
+ ...customSettings,
+ audioSettings: {
+ ...customSettings.audioSettings,
+ bitrate: Number(value),
+ },
+ })
+ }
+ >
+ <SelectTrigger
+ id="export-audio-bitrate"
+ className="h-8 w-full text-xs"
+ >
+ <SelectValue />
+ </SelectTrigger>
+ <SelectContent>
+ {[
+ { value: "128", label: "128 kbps" },
+ { value: "192", label: "192 kbps" },
+ { value: "256", label: "256 kbps" },
+ { value: "320", label: "320 kbps" },
+ ].map((option) => (
+ <SelectItem
+ key={option.value}
+ value={option.value}
+ className="text-xs"
+ >
+ {option.label}
+ </SelectItem>
+ ))}
+ </SelectContent>
+ </Select>
+ </div>
+ )}
+ {isDesktop && (
+ <ExportDolbyOptions
+ audio={customSettings.audioSettings}
+ onChange={(audioSettings) => setCustomSettings({ ...customSettings, audioSettings })}
+ surround={sequenceIsSurround && audioChannelChoice === "5.1"}
+ />
+ )}
{sequenceIsSurround && (
<div className="space-y-1.5" data-testid="export-audio-channels">
<Label htmlFor="export-audio-channels-select" className="text-[11px] text-fg-2">
@@ -2565,7 +2590,7 @@ export const ExportDialog: React.FC<ExportDialogProps> = ({
<SelectValue />
</SelectTrigger>
<SelectContent>
- <SelectItem value="5.1" className="text-xs">5.1 surround (6 channels, AAC 384 kbps+)</SelectItem>
+ <SelectItem value="5.1" className="text-xs">5.1 surround (6 channels, 384 kbps or more)</SelectItem>
<SelectItem value="stereo" className="text-xs">Stereo downmix</SelectItem>
</SelectContent>
</Select>
diff --git a/apps/web/src/components/editor/ExportDolbyOptions.tsx b/apps/web/src/components/editor/ExportDolbyOptions.tsx
new file mode 100644
index 00000000..4845a0da
--- /dev/null
+++ b/apps/web/src/components/editor/ExportDolbyOptions.tsx
@@ -0,0 +1,92 @@
+import React from "react";
+import {
+ Input,
+ Label,
+ Select,
+ SelectContent,
+ SelectItem,
+ SelectTrigger,
+ SelectValue,
+} from "@openreel/ui";
+import {
+ DEFAULT_DIALNORM,
+ DIALNORM_MAX,
+ DIALNORM_MIN,
+ DOLBY_BITRATES,
+ DOLBY_LABEL,
+ clampDialnorm,
+ clampDolbyBitrate,
+ isDolbyFormat,
+ type AudioExportSettings,
+} from "@openreel/core";
+
+interface ExportDolbyOptionsProps {
+ audio: AudioExportSettings;
+ onChange: (next: AudioExportSettings) => void;
+ /** The delivered audio is 5.1 (a 5.1 sequence with the 5.1 channel choice). */
+ surround: boolean;
+}
+
+/**
+ * Bitrate and dialogue-level controls of an AC-3 / E-AC-3 delivery (Export > Audio). Renders nothing for other
+ * audio formats. 5.1 is raised to 384 kbps by the export (see resolveSequenceAudioSettings), which the list shows.
+ */
+export function ExportDolbyOptions({ audio, onChange, surround }: ExportDolbyOptionsProps): React.ReactElement | null {
+ if (!isDolbyFormat(audio.format)) return null;
+ const codec = audio.format;
+ const floor = surround ? 384 : 0;
+ const options = DOLBY_BITRATES[codec].filter((kbps) => kbps >= floor);
+ const bitrate = String(Math.max(floor, clampDolbyBitrate(codec, audio.bitrate)));
+ return (
+ <>
+ <div className="space-y-1.5" data-testid="export-dolby-bitrate">
+ <Label htmlFor="export-dolby-bitrate-select" className="text-[11px] text-fg-2">
+ {DOLBY_LABEL[codec]} bitrate
+ </Label>
+ <Select value={bitrate} onValueChange={(value) => onChange({ ...audio, bitrate: Number(value) })}>
+ <SelectTrigger id="export-dolby-bitrate-select" className="h-8 w-full text-xs" data-testid="export-dolby-bitrate-select">
+ <SelectValue />
+ </SelectTrigger>
+ <SelectContent>
+ {options.map((kbps) => (
+ <SelectItem key={kbps} value={String(kbps)} className="text-xs">
+ {kbps} kbps
+ </SelectItem>
+ ))}
+ </SelectContent>
+ </Select>
+ </div>
+ <div className="space-y-1.5" data-testid="export-dolby-dialnorm">
+ <Label htmlFor="export-dolby-dialnorm-input" className="text-[11px] text-fg-2">
+ Dialogue level (dialnorm, dB)
+ </Label>
+ <Input
+ id="export-dolby-dialnorm-input"
+ data-testid="export-dolby-dialnorm-input"
+ type="number"
+ inputMode="numeric"
+ min={DIALNORM_MIN}
+ max={DIALNORM_MAX}
+ step={1}
+ className="h-8 text-xs"
+ placeholder={`Auto (${DEFAULT_DIALNORM})`}
+ value={audio.dialnorm ?? ""}
+ onChange={(event) => {
+ const raw = event.target.value.trim();
+ if (raw === "") {
+ const { dialnorm: _unused, ...rest } = audio;
+ void _unused;
+ onChange(rest);
+ return;
+ }
+ const parsed = Number(raw);
+ if (Number.isFinite(parsed)) onChange({ ...audio, dialnorm: clampDialnorm(parsed) });
+ }}
+ />
+ <p className="text-[10px] text-fg-muted">
+ Metadata the player uses to level the programme. Auto writes the loudness target when normalising, else {DEFAULT_DIALNORM} (no change).
+ </p>
+ </div>
+ </>
+ );
+}
diff --git a/apps/web/src/components/editor/Preview.tsx b/apps/web/src/components/editor/Preview.tsx
index 077cb42f..040784e9 100644
--- a/apps/web/src/components/editor/Preview.tsx
+++ b/apps/web/src/components/editor/Preview.tsx
@@ -1015,9 +1015,14 @@ export const Preview: React.FC = () => {
baseCacheKey: string,
effects: Effect[],
): Promise<{ audioBuffer: AudioBuffer; effects: Effect[] }> => {
- const previewEffects = getPreviewAudioEffects(
- effects.filter((effect) => effect.enabled),
+ // Spectral repair edits the decoded source (source-time regions) before anything else, exactly as the export does.
+ const spectral = await getRealtimeAudioGraph().prepareSpectralRepair(
+ audioBuffer,
+ getPreviewAudioEffects(effects.filter((effect) => effect.enabled)),
);
+ audioBuffer = spectral.buffer;
+ if (spectral.key) baseCacheKey = `${baseCacheKey}:spectral:${spectral.key}`;
+ const previewEffects = spectral.effects;
const { profileAwareNoiseEffects, realtimeEffects } =
splitProfileAwareNoiseReductionEffects(previewEffects);
diff --git a/apps/web/src/components/editor/Toolbar.tsx b/apps/web/src/components/editor/Toolbar.tsx
index 44a72345..0028b694 100644
--- a/apps/web/src/components/editor/Toolbar.tsx
+++ b/apps/web/src/components/editor/Toolbar.tsx
@@ -158,13 +158,13 @@ export const Toolbar: React.FC = () => {
const preset = getQuickExportPresets(exportProject.settings).find(entry => entry.id === id);
if (!preset) return;
try {
- const ext = preset.kind === "audio" ? "wav" : extForFormat(preset.settings.format ?? "mp4", preset.settings.codec);
+ const ext = preset.kind === "audio" ? preset.extension : extForFormat(preset.settings.format ?? "mp4", preset.settings.codec);
const writable = await showSavePicker(exportFilename(project.name, ext), ext, { delivery: "download" });
beginExport(writable);
if (preset.kind === "audio") {
await runAudioExport(preset.settings, writable);
markComplete();
- track(AnalyticsEvents.PROJECT_EXPORTED, { format: "wav", duration: project.timeline.duration });
+ track(AnalyticsEvents.PROJECT_EXPORTED, { format: preset.extension, duration: project.timeline.duration });
} else {
await runExport(preset.settings, ext, writable);
}
diff --git a/apps/web/src/components/editor/inspector/tabs/AudioTab.tsx b/apps/web/src/components/editor/inspector/tabs/AudioTab.tsx
index 826b3670..f5fbaba0 100644
--- a/apps/web/src/components/editor/inspector/tabs/AudioTab.tsx
+++ b/apps/web/src/components/editor/inspector/tabs/AudioTab.tsx
@@ -2,7 +2,7 @@ import { PrimaryAudioProperties } from "../PrimaryAudioProperties";
import { EssentialSoundSection } from "../EssentialSoundSection";
import { SurroundPanSection } from "../SurroundPanSection";
import { AudioChannelsSection } from "../AudioChannelsSection";
-import React from "react";
+import React, { Suspense, lazy } from "react";
import { getChannelLayout } from "@openreel/core";
import { useProjectStore } from "../../../../stores/project-store";
import {
@@ -16,6 +16,9 @@ import {
import { VoiceOverPanel } from "../VoiceOverPanel";
import { InspectorSection } from "../shell/InspectorSection";
+// The spectral editor (spectrogram, selection tools, worker client) loads when its section is first opened, never with the editor shell.
+const SpectralEditor = lazy(() => import("../../../audio-spectral/SpectralEditor"));
+
interface AudioTabProps {
clipId: string;
clipType: string | null;
@@ -62,6 +65,13 @@ export const AudioTab: React.FC<AudioTabProps> = ({
<RepairSection clipId={clipId} />
</InspectorSection>
)}
+ {showAudioEffects && clip && (
+ <InspectorSection title="Spectral editing" sectionId="spectral-editing" defaultOpen={false}>
+ <Suspense fallback={<p className="text-[11px] text-fg-muted">Loading spectral editor…</p>}>
+ <SpectralEditor clipId={clipId} />
+ </Suspense>
+ </InspectorSection>
+ )}
<InspectorSection
title="Advanced audio tools"
sectionId="advanced-audio"
diff --git a/apps/web/src/components/editor/settings/SettingsDialog.tsx b/apps/web/src/components/editor/settings/SettingsDialog.tsx
index f423709a..384556be 100644
--- a/apps/web/src/components/editor/settings/SettingsDialog.tsx
+++ b/apps/web/src/components/editor/settings/SettingsDialog.tsx
@@ -1,5 +1,5 @@
-import { useRef } from "react";
-import { Settings, Key, Plug, Bot } from "@/icons/lucide-compat";
+import { Suspense, lazy, useRef } from "react";
+import { Settings, Key, Plug, Bot, FolderInput } from "@/icons/lucide-compat";
import { Dialog, DialogContent, DialogHeader, DialogTitle, DialogDescription, ScrollArea, Tabs, TabsList, TabsTrigger, TabsContent } from "@openreel/ui";
import { useSettingsStore, type SettingsTab } from "../../../stores/settings-store";
import { GeneralPanel } from "./GeneralPanel";
@@ -7,6 +7,9 @@ import { ApiKeysPanel } from "./ApiKeysPanel";
import { McpPanel } from "./McpPanel";
import { AISettingsPanel } from "./AISettingsPanel";
+// Desktop only and rarely opened: its own chunk, off the editor bundle.
+const WatchFoldersPanel = lazy(() => import("./WatchFoldersPanel"));
+
export function SettingsDialog() {
const open = useSettingsStore(state => state.settingsOpen);
const selected = useSettingsStore(state => state.settingsTab);
@@ -18,6 +21,7 @@ export function SettingsDialog() {
{ id: "ai-editor", label: "AI Editor", icon: Bot },
{ id: "api-keys", label: "API Keys", icon: Key },
...(typeof window !== "undefined" && window.openreel?.platform === "desktop" ? [{ id: "mcp" as const, label: "MCP", icon: Plug }] : []),
+ ...(typeof window !== "undefined" && window.openreel?.watchFolders ? [{ id: "watch-folders" as const, label: "Watch folders", icon: FolderInput }] : []),
];
const value = tabs.some(tab => tab.id === selected) ? selected : "general";
return <Dialog open={open} onOpenChange={next => { if (!next) close(); }}>
@@ -38,6 +42,7 @@ export function SettingsDialog() {
<TabsContent value="ai-editor" className="mt-0"><AISettingsPanel /></TabsContent>
<TabsContent value="api-keys" className="mt-0"><ApiKeysPanel /></TabsContent>
{tabs.some(tab => tab.id === "mcp") && <TabsContent value="mcp" className="mt-0"><McpPanel /></TabsContent>}
+ {value === "watch-folders" && <TabsContent value="watch-folders" className="mt-0"><Suspense fallback={<p className="text-xs text-fg-2">Loading…</p>}><WatchFoldersPanel /></Suspense></TabsContent>}
</div>
</ScrollArea>
</Tabs>
diff --git a/apps/web/src/components/editor/settings/WatchFoldersPanel.test.tsx b/apps/web/src/components/editor/settings/WatchFoldersPanel.test.tsx
new file mode 100644
index 00000000..8424d6dd
--- /dev/null
+++ b/apps/web/src/components/editor/settings/WatchFoldersPanel.test.tsx
@@ -0,0 +1,95 @@
+import { afterEach, describe, expect, it, vi } from "vitest";
+import { fireEvent, render, screen, waitFor, within } from "@testing-library/react";
+import type { OpenReelWatchFolderConfig, OpenReelWatchFoldersSnapshot } from "../../../types/global";
+import { WatchFoldersPanel } from "./WatchFoldersPanel";
+
+const base: OpenReelWatchFolderConfig = { id: "f1", kind: "ingest", path: "/Volumes/Card/DCIM", paused: false, bin: "Cards", createProxies: false, presetId: "1080p-high", outputDir: "", includeProjects: false, baselined: true, processExisting: false };
+const exportFolder: OpenReelWatchFolderConfig = { ...base, id: "f2", kind: "export", path: "/Users/me/Hot", outputDir: "/Users/me/Hot/output", bin: "" };
+const idle = { state: "watching" as const, detecting: 0, queued: 0, running: 0, done: 2, failed: 1, duplicates: 0 };
+
+function install(snapshot: OpenReelWatchFoldersSnapshot) {
+ const bridge = {
+ list: vi.fn().mockResolvedValue(snapshot),
+ add: vi.fn().mockResolvedValue({ added: true, id: "new" }),
+ update: vi.fn().mockResolvedValue(undefined),
+ pickOutput: vi.fn().mockResolvedValue({ changed: true }),
+ remove: vi.fn().mockResolvedValue(undefined),
+ retry: vi.fn().mockResolvedValue(undefined),
+ clearFinished: vi.fn().mockResolvedValue(undefined),
+ onChange: vi.fn().mockReturnValue(() => undefined),
+ };
+ Object.defineProperty(window, "openreel", { configurable: true, value: { platform: "desktop", watchFolders: bridge } });
+ return bridge;
+}
+
+afterEach(() => {
+ vi.restoreAllMocks();
+ Reflect.deleteProperty(window, "openreel");
+});
+
+describe("WatchFoldersPanel", () => {
+ it("lists folders with their state and counts", async () => {
+ install({ folders: [{ config: base, status: idle }, { config: exportFolder, status: { ...idle, state: "paused", done: 0, failed: 0 } }], items: [] });
+ render(<WatchFoldersPanel />);
+ const cards = await screen.findAllByTestId("watch-folder");
+ expect(cards).toHaveLength(2);
+ expect(within(cards[0]).getByText("/Volumes/Card/DCIM")).toBeTruthy();
+ expect(within(cards[0]).getByTestId("watch-folder-summary").textContent).toBe("2 done · 1 failed");
+ expect(within(cards[1]).getByTestId("watch-folder-state").textContent).toBe("Paused");
+ expect(within(cards[1]).getByTestId("watch-folder-summary").textContent).toBe("Nothing yet");
+ });
+
+ it("adds folders through the native dialog (the page never supplies a path)", async () => {
+ const bridge = install({ folders: [], items: [] });
+ render(<WatchFoldersPanel />);
+ await screen.findByText("No watch folders yet.");
+ fireEvent.click(screen.getByText("Add ingest folder"));
+ await waitFor(() => expect(bridge.add).toHaveBeenCalledWith("ingest"));
+ fireEvent.click(screen.getByText("Add export folder"));
+ await waitFor(() => expect(bridge.add).toHaveBeenCalledWith("export"));
+ });
+
+ it("pauses, removes, and edits ingest options", async () => {
+ const bridge = install({ folders: [{ config: base, status: idle }], items: [] });
+ render(<WatchFoldersPanel />);
+ fireEvent.click(await screen.findByLabelText("Pause /Volumes/Card/DCIM"));
+ await waitFor(() => expect(bridge.update).toHaveBeenCalledWith("f1", { paused: true }));
+ fireEvent.click(screen.getByLabelText("Create proxies"));
+ await waitFor(() => expect(bridge.update).toHaveBeenCalledWith("f1", { createProxies: true }));
+ const bin = screen.getByLabelText("Bin name");
+ fireEvent.change(bin, { target: { value: "Day 2" } });
+ fireEvent.blur(bin);
+ await waitFor(() => expect(bridge.update).toHaveBeenCalledWith("f1", { bin: "Day 2" }));
+ fireEvent.click(screen.getByLabelText("Remove /Volumes/Card/DCIM"));
+ await waitFor(() => expect(bridge.remove).toHaveBeenCalledWith("f1"));
+ });
+
+ it("edits export options and changes the output folder through the dialog", async () => {
+ const bridge = install({ folders: [{ config: exportFolder, status: idle }], items: [] });
+ render(<WatchFoldersPanel />);
+ fireEvent.change(await screen.findByLabelText("Export preset"), { target: { value: "4k" } });
+ await waitFor(() => expect(bridge.update).toHaveBeenCalledWith("f2", { presetId: "4k" }));
+ fireEvent.click(screen.getByLabelText("Render project files"));
+ await waitFor(() => expect(bridge.update).toHaveBeenCalledWith("f2", { includeProjects: true }));
+ fireEvent.click(screen.getByText("Change"));
+ await waitFor(() => expect(bridge.pickOutput).toHaveBeenCalledWith("f2"));
+ });
+
+ it("retries failed items and shows a refusal from the main process", async () => {
+ const bridge = install({
+ folders: [{ config: base, status: idle }],
+ items: [{ id: "i1", folderId: "f1", name: "a.mp4", path: "/a.mp4", state: "failed", progress: null, error: "x", createdAt: 1 }],
+ });
+ bridge.update.mockRejectedValueOnce(new Error("Error invoking remote method 'openreel:watchFolders:update': Error: That watch folder no longer exists."));
+ render(<WatchFoldersPanel />);
+ fireEvent.click(await screen.findByText("Retry failed"));
+ await waitFor(() => expect(bridge.retry).toHaveBeenCalledWith("i1"));
+ fireEvent.click(screen.getByLabelText("Pause /Volumes/Card/DCIM"));
+ expect((await screen.findByRole("alert")).textContent).toBe("That watch folder no longer exists.");
+ });
+
+ it("explains itself off desktop", () => {
+ render(<WatchFoldersPanel />);
+ expect(screen.getByText(/available in the OpenReel desktop app/)).toBeTruthy();
+ });
+});
diff --git a/apps/web/src/components/editor/settings/WatchFoldersPanel.tsx b/apps/web/src/components/editor/settings/WatchFoldersPanel.tsx
new file mode 100644
index 00000000..e8f3abfc
--- /dev/null
+++ b/apps/web/src/components/editor/settings/WatchFoldersPanel.tsx
@@ -0,0 +1,217 @@
+import React, { useCallback, useEffect, useState } from "react";
+import { FolderInput, FolderOutput, Pause, Play, Plus, RotateCcw, Trash2 } from "@/icons/lucide-compat";
+import { Button, Switch } from "@openreel/ui";
+import type { OpenReelWatchFolderConfig, OpenReelWatchFoldersBridge, OpenReelWatchFoldersSnapshot, OpenReelWatchFolderStatus, OpenReelWatchItem } from "../../../types/global";
+
+type WatchPatch = Parameters<OpenReelWatchFoldersBridge["update"]>[1];
+
+/** Presets an export watch folder can render: the Export dialog's quick presets. */
+export const WATCH_EXPORT_PRESETS: ReadonlyArray<{ id: string; label: string; audioOnly?: boolean }> = [
+ { id: "mp4", label: "MP4 Standard (source size)" },
+ { id: "1080p-high", label: "1080p High Quality" },
+ { id: "1080p-60", label: "1080p 60fps" },
+ { id: "4k", label: "4K Standard" },
+ { id: "wav", label: "Audio Only (WAV)", audioOnly: true },
+];
+
+const STATE_LABEL: Record<OpenReelWatchFolderStatus["state"], string> = {
+ watching: "Watching",
+ paused: "Paused",
+ missing: "Folder missing",
+ error: "Error",
+};
+
+function summary(status: OpenReelWatchFolderStatus): string {
+ const parts: string[] = [];
+ if (status.detecting) parts.push(`${status.detecting} copying`);
+ if (status.running) parts.push(`${status.running} running`);
+ if (status.queued) parts.push(`${status.queued} queued`);
+ if (status.done) parts.push(`${status.done} done`);
+ if (status.failed) parts.push(`${status.failed} failed`);
+ if (status.duplicates) parts.push(`${status.duplicates} duplicate`);
+ return parts.join(" · ");
+}
+
+const fieldClass = "h-7 min-w-0 rounded-md border border-border bg-background px-2 text-xs text-fg outline-none focus-visible:ring-2 focus-visible:ring-ring";
+const iconButton = "inline-flex h-7 w-7 shrink-0 items-center justify-center rounded text-fg-2 outline-none transition-colors hover:bg-bg-2 hover:text-fg focus-visible:ring-2 focus-visible:ring-ring";
+
+function IngestOptions({ config, onPatch }: { config: OpenReelWatchFolderConfig; onPatch: (patch: WatchPatch) => void }) {
+ const [bin, setBin] = useState(config.bin);
+ useEffect(() => setBin(config.bin), [config.bin]);
+ return (
+ <div className="mt-2 space-y-2">
+ <label className="flex items-center gap-2 text-xs text-fg-2">
+ <span className="w-24 shrink-0">Import into bin</span>
+ <input
+ value={bin}
+ onChange={(e) => setBin(e.target.value)}
+ onBlur={() => bin !== config.bin && onPatch({ bin })}
+ onKeyDown={(e) => e.key === "Enter" && (e.target as HTMLInputElement).blur()}
+ aria-label="Bin name"
+ placeholder="Project root"
+ className={`${fieldClass} flex-1`}
+ />
+ </label>
+ <div className="flex items-center justify-between gap-3 text-xs text-fg-2">
+ <span>Create preview proxies for imported media</span>
+ <Switch aria-label="Create proxies" checked={config.createProxies} onCheckedChange={(createProxies) => onPatch({ createProxies })} />
+ </div>
+ </div>
+ );
+}
+
+function FolderCard({ config, status, items, bridge }: { config: OpenReelWatchFolderConfig; status: OpenReelWatchFolderStatus; items: OpenReelWatchItem[]; bridge: OpenReelWatchFoldersBridge }) {
+ const [error, setError] = useState<string | null>(null);
+ const run = useCallback(async (action: () => Promise<unknown>) => {
+ try {
+ setError(null);
+ await action();
+ } catch (err) {
+ setError(err instanceof Error ? err.message.replace(/^Error invoking remote method '[^']+': (Error: )?/, "") : "That did not work.");
+ }
+ }, []);
+ const patch = (next: WatchPatch) => void run(() => bridge.update(config.id, next));
+ const Icon = config.kind === "ingest" ? FolderInput : FolderOutput;
+ const failed = items.filter((item) => item.state === "failed");
+ return (
+ <li className="rounded-lg border border-border bg-bg-1 p-3" data-testid="watch-folder" data-kind={config.kind} data-state={status.state}>
+ <div className="flex items-center gap-2">
+ <Icon size={16} className="shrink-0 text-fg-2" aria-hidden />
+ <code className="min-w-0 flex-1 truncate font-mono text-xs text-fg" title={config.path}>
+ {config.path}
+ </code>
+ <span className="shrink-0 rounded bg-bg-3 px-1.5 text-[11px] font-semibold uppercase tracking-wide text-fg-muted" data-testid="watch-folder-state">
+ {STATE_LABEL[status.state]}
+ </span>
+ <button type="button" className={iconButton} aria-label={config.paused ? `Resume ${config.path}` : `Pause ${config.path}`} title={config.paused ? "Resume" : "Pause"} onClick={() => patch({ paused: !config.paused })}>
+ {config.paused ? <Play size={14} aria-hidden /> : <Pause size={14} aria-hidden />}
+ </button>
+ <button type="button" className={iconButton} aria-label={`Remove ${config.path}`} title="Stop watching" onClick={() => void run(() => bridge.remove(config.id))}>
+ <Trash2 size={14} aria-hidden />
+ </button>
+ </div>
+ <p className="mt-1 text-xs text-fg-2">
+ {config.kind === "ingest" ? "New media is imported into the open project." : "Media dropped here is rendered to the output folder; the source moves to done/ or failed/."}
+ {status.message ? ` ${status.message}` : ""}
+ </p>
+ {config.kind === "ingest" ? (
+ <IngestOptions config={config} onPatch={patch} />
+ ) : (
+ <div className="mt-2 space-y-2">
+ <label className="flex items-center gap-2 text-xs text-fg-2">
+ <span className="w-24 shrink-0">Export preset</span>
+ <select value={config.presetId} onChange={(e) => patch({ presetId: e.target.value })} aria-label="Export preset" className={`${fieldClass} flex-1`}>
+ {WATCH_EXPORT_PRESETS.map((preset) => (
+ <option key={preset.id} value={preset.id}>
+ {preset.label}
+ </option>
+ ))}
+ </select>
+ </label>
+ <div className="flex items-center gap-2 text-xs text-fg-2">
+ <span className="w-24 shrink-0">Output folder</span>
+ <code className="min-w-0 flex-1 truncate font-mono" title={config.outputDir}>
+ {config.outputDir}
+ </code>
+ <Button type="button" variant="ghost" className="h-7 px-2 text-xs" onClick={() => void run(() => bridge.pickOutput(config.id))}>
+ Change
+ </Button>
+ </div>
+ <div className="flex items-center justify-between gap-3 text-xs text-fg-2">
+ <span className="max-w-sm">Also render .oreel project files (opens each in the editor; the project open now is saved first)</span>
+ <Switch aria-label="Render project files" checked={config.includeProjects} onCheckedChange={(includeProjects) => patch({ includeProjects })} />
+ </div>
+ </div>
+ )}
+ <div className="mt-2 flex items-center gap-2 text-xs text-fg-2">
+ <span data-testid="watch-folder-summary">{summary(status) || "Nothing yet"}</span>
+ {failed.length > 0 && (
+ <Button type="button" variant="ghost" className="ml-auto h-6 gap-1 px-1.5 text-xs" onClick={() => void run(() => Promise.all(failed.map((item) => bridge.retry(item.id))))}>
+ <RotateCcw size={11} aria-hidden /> Retry failed
+ </Button>
+ )}
+ </div>
+ {error && (
+ <p role="alert" className="mt-1 text-xs text-status-error">
+ {error}
+ </p>
+ )}
+ </li>
+ );
+}
+
+/** Settings > Watch folders (desktop). The folder list lives in the main process; this edits it. */
+export const WatchFoldersPanel: React.FC = () => {
+ const bridge = typeof window !== "undefined" ? window.openreel?.watchFolders : undefined;
+ const [snapshot, setSnapshot] = useState<OpenReelWatchFoldersSnapshot | null>(null);
+ const [error, setError] = useState<string | null>(null);
+
+ useEffect(() => {
+ if (!bridge) return;
+ let alive = true;
+ void bridge.list().then((next) => alive && setSnapshot(next)).catch(() => undefined);
+ const off = bridge.onChange((next) => alive && setSnapshot(next));
+ return () => {
+ alive = false;
+ off();
+ };
+ }, [bridge]);
+
+ const add = useCallback(
+ async (kind: "ingest" | "export") => {
+ if (!bridge) return;
+ try {
+ setError(null);
+ await bridge.add(kind);
+ setSnapshot(await bridge.list());
+ } catch (err) {
+ setError(err instanceof Error ? err.message.replace(/^Error invoking remote method '[^']+': (Error: )?/, "") : "Could not add that folder.");
+ }
+ },
+ [bridge],
+ );
+
+ if (!bridge) return <p className="text-xs text-fg-2">Watch folders are available in the OpenReel desktop app.</p>;
+ const folders = snapshot?.folders ?? [];
+ return (
+ <div className="space-y-4" data-testid="watch-folders-panel">
+ <div>
+ <span className="block text-sm font-medium text-fg">Watch folders</span>
+ <span className="mt-0.5 block text-xs text-fg-2">
+ An ingest folder imports media dropped into it into the open project. An export folder renders media dropped into it with a preset.
+ Files are picked up once they stop growing, duplicates are skipped, and watching resumes when OpenReel starts. Progress shows in the background tasks panel.
+ </span>
+ </div>
+ <ul className="space-y-2" aria-label="Watch folders">
+ {snapshot === null && <li className="text-xs text-fg-2">Loading…</li>}
+ {snapshot !== null && folders.length === 0 && <li className="text-xs text-fg-2">No watch folders yet.</li>}
+ {folders.map(({ config, status }) => (
+ <FolderCard key={config.id} config={config} status={status} items={(snapshot?.items ?? []).filter((item) => item.folderId === config.id)} bridge={bridge} />
+ ))}
+ </ul>
+ <div className="flex flex-wrap items-center gap-2">
+ <Button type="button" onClick={() => void add("ingest")} className="inline-flex h-7 items-center gap-1.5 rounded-[7px] border border-border bg-bg-2 px-2.5 text-[12px] font-semibold text-fg-2 hover:bg-bg-3 hover:text-fg">
+ <Plus size={14} aria-hidden />
+ Add ingest folder
+ </Button>
+ <Button type="button" onClick={() => void add("export")} className="inline-flex h-7 items-center gap-1.5 rounded-[7px] border border-border bg-bg-2 px-2.5 text-[12px] font-semibold text-fg-2 hover:bg-bg-3 hover:text-fg">
+ <Plus size={14} aria-hidden />
+ Add export folder
+ </Button>
+ {snapshot?.items.some((item) => ["done", "failed", "duplicate", "cancelled"].includes(item.state)) && (
+ <Button type="button" variant="ghost" className="h-7 px-2 text-xs text-fg-2 hover:text-fg" onClick={() => void bridge.clearFinished()}>
+ Clear finished
+ </Button>
+ )}
+ </div>
+ <p className="text-xs text-fg-2">Files already in a folder when you add it are skipped; only files that arrive afterwards are processed.</p>
+ {error && (
+ <p role="alert" className="text-xs text-status-error">
+ {error}
+ </p>
+ )}
+ </div>
+ );
+};
+
+export default WatchFoldersPanel;
diff --git a/apps/web/src/desktop/editor/DesktopExportButton.tsx b/apps/web/src/desktop/editor/DesktopExportButton.tsx
index a6a81fde..161dd64b 100644
--- a/apps/web/src/desktop/editor/DesktopExportButton.tsx
+++ b/apps/web/src/desktop/editor/DesktopExportButton.tsx
@@ -180,7 +180,7 @@ export function DesktopExportButton({ compact = false }: { compact?: boolean } =
} else {
void (async () => {
try {
- const writable = await showSavePicker(exportFilename(project.name, "wav"), "wav");
+ const writable = await showSavePicker(exportFilename(project.name, preset.extension), preset.extension);
beginExport(writable);
await runAudioExport(preset.settings, writable);
markComplete();
diff --git a/apps/web/src/services/agent/mcp-listener.test.ts b/apps/web/src/services/agent/mcp-listener.test.ts
index ee151ae9..ae91e662 100644
--- a/apps/web/src/services/agent/mcp-listener.test.ts
+++ b/apps/web/src/services/agent/mcp-listener.test.ts
@@ -300,4 +300,29 @@ describe("handleMcpBridgeRequest", () => {
expect(res.ok).toBe(false);
expect(res.error).toMatch(/name/i);
});
+
+ describe("watch-folder origin", () => {
+ beforeEach(() => {
+ h.isDestructive.mockImplementation(() => true);
+ h.isExpensive.mockImplementation(() => true);
+ h.executeTool.mockResolvedValue({ ok: true, summary: "ran" });
+ });
+
+ it("runs the watch-folder tools without the agent confirmation gate", async () => {
+ for (const name of ["import_media_from_path", "list_bins", "create_bin", "open_project_file", "queue_export", "list_export_jobs", "cancel_export_job"]) {
+ const res = await handleMcpBridgeRequest({ callId: "w", kind: "callTool", name, args: {}, origin: "watch-folders" });
+ expect(res.ok).toBe(true);
+ expect((res.result as { ok: boolean }).ok, name).toBe(true);
+ }
+ expect(h.executeTool).toHaveBeenCalledTimes(7);
+ });
+
+ it("does not open the gate for other tools, or for the same tools without the origin", async () => {
+ const other = await handleMcpBridgeRequest({ callId: "w", kind: "callTool", name: "delete_clip", args: {}, origin: "watch-folders" });
+ expect((other.result as { error: { code: string } }).error.code).toBe("CONFIRMATION_REQUIRED");
+ const plain = await handleMcpBridgeRequest({ callId: "w", kind: "callTool", name: "import_media_from_path", args: {} });
+ expect((plain.result as { error: { code: string } }).error.code).toBe("CONFIRMATION_REQUIRED");
+ expect(h.executeTool).not.toHaveBeenCalled();
+ });
+ });
});
diff --git a/apps/web/src/services/agent/mcp-listener.ts b/apps/web/src/services/agent/mcp-listener.ts
index 0f8bbaaa..29d7e670 100644
--- a/apps/web/src/services/agent/mcp-listener.ts
+++ b/apps/web/src/services/agent/mcp-listener.ts
@@ -19,8 +19,16 @@ interface McpBridgeRequest {
readonly kind: "listTools" | "callTool";
readonly name?: string;
readonly args?: Record<string, unknown>;
+ /** Set by the main process for watch-folder work; see WATCH_FOLDER_TOOLS. */
+ readonly origin?: "watch-folders";
}
+/**
+ * The tools a watch folder may run without the agent confirmation gate. The folders are configured by
+ * the user in Settings (the folder path comes from a native dialog), so this is the user's own automation.
+ */
+const WATCH_FOLDER_TOOLS: ReadonlySet<string> = new Set(["import_media_from_path", "list_bins", "create_bin", "open_project_file", "queue_export", "list_export_jobs", "cancel_export_job", "relink_media"]);
+
interface McpBridgeResponse {
readonly ok: boolean;
readonly result?: unknown;
@@ -167,7 +175,7 @@ export async function handleMcpBridgeRequest(
const name = req.name;
if (!name) return { ok: false, error: "Missing tool name" };
- const autoAllow = useSettingsStore.getState().mcpAutoAllowTrustedLocal;
+ const autoAllow = useSettingsStore.getState().mcpAutoAllowTrustedLocal || (req.origin === "watch-folders" && WATCH_FOLDER_TOOLS.has(name));
if (!autoAllow && (isDestructive(name) || isExpensive(name))) {
const blocked: ToolResult = {
ok: false,
diff --git a/apps/web/src/services/background-task-sources.ts b/apps/web/src/services/background-task-sources.ts
index 73288de6..0bf68c8a 100644
--- a/apps/web/src/services/background-task-sources.ts
+++ b/apps/web/src/services/background-task-sources.ts
@@ -174,7 +174,18 @@ export function startBackgroundTaskSources(): () => void {
useDesktopIngestStore.subscribe((s, p) => { if (s.jobs !== p.jobs) syncProxies(); if (s.copying !== p.copying) syncCopies(); }),
getBeatSyncBridge().subscribe(syncBeats),
];
+ // Desktop watch folders: loaded on demand so the entry chunk does not carry it.
+ let stopWatchTasks: (() => void) | null = null;
+ let disposed = false;
+ if (typeof window !== "undefined" && window.openreel?.watchFolders) {
+ void import("./watch-folder-tasks").then((m) => {
+ if (disposed) return;
+ stopWatchTasks = m.startWatchFolderTasks();
+ });
+ }
const dispose = () => {
+ disposed = true;
+ stopWatchTasks?.();
offs.forEach((off) => off());
started = null;
};
diff --git a/apps/web/src/services/dolby-delivery.test.ts b/apps/web/src/services/dolby-delivery.test.ts
new file mode 100644
index 00000000..4194f2c9
--- /dev/null
+++ b/apps/web/src/services/dolby-delivery.test.ts
@@ -0,0 +1,80 @@
+import { describe, expect, it } from "vitest";
+import {
+ DOLBY_BITRATES,
+ exportSettingsRequireNativeEncoder,
+ getVideoExportValidationError,
+ isDolbyFormat,
+ type AudioExportSettings,
+ type VideoExportSettings,
+} from "@openreel/core";
+import { exportPresetsManager, parseVideoExportSettings } from "./export-presets";
+import { extForFormat, mimeForExt } from "./export-runner";
+import { getQuickExportPresets } from "./quick-export-presets";
+import { dolbyStartFields } from "./native-ffmpeg-backend";
+import { findVideoPreset } from "./agent/export-options";
+
+const project = { width: 1920, height: 1080, frameRate: 30 };
+const dolbyVideo = () => exportPresetsManager.getPresetsByPlatform("Dolby Digital");
+
+describe("Dolby Digital export presets", () => {
+ it("offers AC-3 and E-AC-3 video presets in MP4, MOV and MKV", () => {
+ const byId = Object.fromEntries(dolbyVideo().map((p) => [p.id, p.settings as VideoExportSettings]));
+ expect(Object.keys(byId).sort()).toEqual(["dolby-ac3-mkv", "dolby-ac3-mov", "dolby-ac3-mp4", "dolby-eac3-mkv", "dolby-eac3-mov", "dolby-eac3-mp4"]);
+ expect(byId["dolby-ac3-mp4"]).toMatchObject({ format: "mp4", codec: "h264", audioSettings: { format: "ac3", bitrate: 448 } });
+ expect(byId["dolby-eac3-mkv"]).toMatchObject({ format: "mkv", audioSettings: { format: "eac3", bitrate: 640 } });
+ });
+
+ it("every one is a delivery the desktop encoder writes (and the browser refuses with the desktop-only reason)", () => {
+ for (const preset of dolbyVideo()) {
+ const settings = preset.settings as VideoExportSettings;
+ expect(exportSettingsRequireNativeEncoder(settings), preset.id).toBe(true);
+ expect(isDolbyFormat(settings.audioSettings.format)).toBe(true);
+ expect(DOLBY_BITRATES[settings.audioSettings.format as "ac3" | "eac3"]).toContain(settings.audioSettings.bitrate);
+ expect(getVideoExportValidationError(settings, 10), preset.id).toBeNull();
+ }
+ });
+
+ it("offers raw .ac3 / .ec3 audio presets that are valid audio settings", () => {
+ const audio = exportPresetsManager.getPresetsByPlatform("Audio").filter((p) => isDolbyFormat((p.settings as AudioExportSettings).format));
+ expect(audio.map((p) => p.id).sort()).toEqual(["audio-ac3", "audio-ac3-448", "audio-eac3", "audio-eac3-640"]);
+ for (const preset of audio) expect(DOLBY_BITRATES[(preset.settings as AudioExportSettings).format as "ac3" | "eac3"]).toContain((preset.settings as AudioExportSettings).bitrate);
+ });
+
+ it("imported custom presets keep Dolby audio and the MKV container", () => {
+ const parsed = parseVideoExportSettings(dolbyVideo().find((p) => p.id === "dolby-eac3-mkv")!.settings);
+ expect(parsed).toMatchObject({ format: "mkv", audioSettings: { format: "eac3" } });
+ });
+
+ it("the agent's preset lookup finds them", () => {
+ expect(findVideoPreset("dolby-ac3-mov", project)?.settings).toMatchObject({ format: "mov", audioSettings: { format: "ac3" } });
+ });
+});
+
+describe("quick exports and file naming", () => {
+ it("lists audio-only Dolby Digital and Digital Plus with their extensions", () => {
+ const quick = getQuickExportPresets(project);
+ expect(quick.find((p) => p.id === "ac3")).toMatchObject({ kind: "audio", extension: "ac3", settings: { format: "ac3", bitrate: 192 } });
+ expect(quick.find((p) => p.id === "eac3")).toMatchObject({ kind: "audio", extension: "ec3", settings: { format: "eac3", bitrate: 256 } });
+ expect(quick.find((p) => p.id === "wav")).toMatchObject({ extension: "wav" });
+ });
+
+ it("names the files .ac3 / .ec3 / .mkv and gives them a type", () => {
+ expect(extForFormat("ac3")).toBe("ac3");
+ expect(extForFormat("eac3")).toBe("ec3");
+ expect(extForFormat("mkv", "h264")).toBe("mkv");
+ expect(mimeForExt("ac3")).toBe("audio/ac3");
+ expect(mimeForExt("ec3")).toBe("audio/eac3");
+ expect(mimeForExt("mkv")).toBe("video/x-matroska");
+ });
+});
+
+describe("desktop export request", () => {
+ const settings = (audioSettings: Partial<AudioExportSettings>) => ({ audioSettings: { format: "aac", sampleRate: 48000, bitDepth: 16, bitrate: 192, channels: 2, ...audioSettings } }) as VideoExportSettings;
+
+ it("carries the audio codec and the dialnorm for AC-3 / E-AC-3 only", () => {
+ expect(dolbyStartFields(settings({ format: "ac3" }))).toEqual({ audioCodec: "ac3", dialnorm: -31 });
+ expect(dolbyStartFields(settings({ format: "eac3", dialnorm: -24 }))).toEqual({ audioCodec: "eac3", dialnorm: -24 });
+ expect(dolbyStartFields(settings({ format: "ac3", loudness: { enabled: true, targetLufs: -23, truePeakCeilingDb: -1 } }))).toEqual({ audioCodec: "ac3", dialnorm: -23 });
+ expect(dolbyStartFields(settings({ format: "aac" }))).toEqual({});
+ });
+});
diff --git a/apps/web/src/services/export-presets.ts b/apps/web/src/services/export-presets.ts
index a57cddfd..96d009dd 100644
--- a/apps/web/src/services/export-presets.ts
+++ b/apps/web/src/services/export-presets.ts
@@ -762,6 +762,63 @@ const AUDIO_PRESETS: PlatformExportPreset[] = [
},
];
+/** Raw Dolby Digital / Digital Plus audio files (`.ac3` / `.ec3`); the browser encodes them on ffmpeg.wasm, the desktop app on its ffmpeg sidecar. */
+const dolbyAudioPreset = (id: string, name: string, description: string, format: "ac3" | "eac3", bitrate: number): PlatformExportPreset => ({
+ id,
+ name,
+ description,
+ platform: "Audio",
+ category: "broadcast",
+ settings: { format, sampleRate: 48000, bitDepth: 24, bitrate, channels: 2 } as AudioExportSettings,
+});
+
+AUDIO_PRESETS.push(
+ dolbyAudioPreset("audio-ac3", "Dolby Digital (AC-3) audio", "Raw .ac3 stream, 192 kbps stereo (a 5.1 sequence delivers 5.1 at 384 kbps or more)", "ac3", 192),
+ dolbyAudioPreset("audio-ac3-448", "Dolby Digital (AC-3) audio, 448 kbps", "Raw .ac3 stream at the DVD / broadcast rate for stereo or 5.1", "ac3", 448),
+ dolbyAudioPreset("audio-eac3", "Dolby Digital Plus (E-AC-3) audio", "Raw .ec3 stream, 256 kbps stereo (a 5.1 sequence delivers 5.1 at 384 kbps or more)", "eac3", 256),
+ dolbyAudioPreset("audio-eac3-640", "Dolby Digital Plus (E-AC-3) audio, 640 kbps", "Raw .ec3 stream at 640 kbps for stereo or 5.1", "eac3", 640),
+);
+
+/**
+ * Video files with Dolby Digital / Digital Plus audio (desktop only: the ffmpeg sidecar writes the AC-3 / E-AC-3 track).
+ * The picture is H.264 1080p30; the audio is stereo, or 5.1 when the sequence is 5.1 (then at 384 kbps or more).
+ */
+const dolbyVideoPreset = (
+ id: string,
+ name: string,
+ description: string,
+ format: "mp4" | "mov" | "mkv",
+ audio: { format: "ac3" | "eac3"; bitrate: number },
+): PlatformExportPreset => ({
+ id,
+ name,
+ description,
+ platform: "Dolby Digital",
+ category: "broadcast",
+ aspectRatio: "16:9",
+ settings: {
+ format,
+ codec: "h264",
+ width: 1920,
+ height: 1080,
+ frameRate: 30,
+ bitrate: 15000,
+ bitrateMode: "cbr",
+ quality: 90,
+ keyframeInterval: 60,
+ audioSettings: { format: audio.format, sampleRate: 48000, bitDepth: 24, bitrate: audio.bitrate, channels: 2 },
+ } as unknown as PlatformExportPreset["settings"],
+});
+
+const DOLBY_PRESETS: PlatformExportPreset[] = [
+ dolbyVideoPreset("dolby-ac3-mp4", "H.264 + Dolby Digital (MP4)", "MP4 with an AC-3 track (ac-3 sample entry), 448 kbps; 5.1 for a 5.1 sequence", "mp4", { format: "ac3", bitrate: 448 }),
+ dolbyVideoPreset("dolby-ac3-mov", "H.264 + Dolby Digital (MOV)", "QuickTime MOV with an AC-3 track, 448 kbps; 5.1 for a 5.1 sequence", "mov", { format: "ac3", bitrate: 448 }),
+ dolbyVideoPreset("dolby-ac3-mkv", "H.264 + Dolby Digital (MKV)", "Matroska with an AC-3 track, 448 kbps; 5.1 for a 5.1 sequence", "mkv", { format: "ac3", bitrate: 448 }),
+ dolbyVideoPreset("dolby-eac3-mp4", "H.264 + Dolby Digital Plus (MP4)", "MP4 with an E-AC-3 track (ec-3 sample entry), 640 kbps; 5.1 for a 5.1 sequence", "mp4", { format: "eac3", bitrate: 640 }),
+ dolbyVideoPreset("dolby-eac3-mov", "H.264 + Dolby Digital Plus (MOV)", "QuickTime MOV with an E-AC-3 track, 640 kbps; 5.1 for a 5.1 sequence", "mov", { format: "eac3", bitrate: 640 }),
+ dolbyVideoPreset("dolby-eac3-mkv", "H.264 + Dolby Digital Plus (MKV)", "Matroska with an E-AC-3 track, 640 kbps; 5.1 for a 5.1 sequence", "mkv", { format: "eac3", bitrate: 640 }),
+];
+
/**
* Delivery masters (desktop only: the ffmpeg sidecar encodes them): 24-bit PCM audio, 1080p24 defaults.
* Pick another size or rate in the dialog's controls; the codec and wrapper stay.
@@ -834,6 +891,7 @@ const ALL_EXPORT_PRESETS: PlatformExportPreset[] = [
...SOCIAL_MEDIA_PRESETS,
...BROADCAST_PRESETS,
...DELIVERY_PRESETS,
+ ...DOLBY_PRESETS,
...WEB_PRESETS,
...ARCHIVE_PRESETS,
...AUDIO_PRESETS,
@@ -1050,13 +1108,13 @@ function isRecord(value: unknown): value is Record<string, unknown> {
return typeof value === "object" && value !== null && !Array.isArray(value);
}
-const VIDEO_FORMATS = ["mp4", "webm", "mov", "mxf"] as const;
+const VIDEO_FORMATS = ["mp4", "webm", "mov", "mxf", "mkv"] as const;
const BITRATE_MODES = ["cbr", "vbr", "vbr1", "vbr2"] as const;
const RATE_CONTROLS = ["quality", "vbr", "vbr2"] as const;
const VIDEO_CODECS = [
"h264", "h265", "vp8", "vp9", "av1", "prores", "dnxhr", "xdcamhd422", "avcintra100",
] as const;
-const AUDIO_FORMATS = ["mp3", "wav", "aac", "flac", "ogg"] as const;
+const AUDIO_FORMATS = ["mp3", "wav", "aac", "flac", "ogg", "ac3", "eac3"] as const;
const FALLBACK_AUDIO_SETTINGS: AudioExportSettings = {
format: "aac",
diff --git a/apps/web/src/services/export-runner.ts b/apps/web/src/services/export-runner.ts
index 90400abc..7ef2573d 100644
--- a/apps/web/src/services/export-runner.ts
+++ b/apps/web/src/services/export-runner.ts
@@ -19,7 +19,7 @@ export interface ExportRunnerState {
complete: boolean;
}
-type ExportContainer = "mp4" | "webm" | "mov" | "mxf" | "wav";
+type ExportContainer = "mp4" | "webm" | "mov" | "mxf" | "mkv" | "wav" | "ac3" | "ec3";
export type ExportDeliveryMode = "download" | "file";
const MIME_BY_EXT: Record<string, string> = {
@@ -27,7 +27,10 @@ const MIME_BY_EXT: Record<string, string> = {
webm: "video/webm",
mov: "video/quicktime",
mxf: "application/mxf",
+ mkv: "video/x-matroska",
wav: "audio/wav",
+ ac3: "audio/ac3",
+ ec3: "audio/eac3",
};
export function mimeForExt(ext: string): string {
@@ -40,6 +43,9 @@ export function extForFormat(format: string, codec?: string): ExportContainer {
if (format === "mov") return "mov";
if (format === "webm") return "webm";
if (format === "wav") return "wav";
+ if (format === "mkv") return "mkv";
+ if (format === "ac3") return "ac3";
+ if (format === "eac3") return "ec3";
return "mp4";
}
@@ -632,7 +638,7 @@ export function useExportRunner(options: ExportRunnerOptions): UseExportRunner {
// The WAV path and any WebCodecs export (streamToFile) mux directly to
// disk through the fs bridge. The native ffmpeg video path writes the
// file itself via __openreelExportPath, so it gets the no-op stub below.
- if (ext === "wav" || opts?.streamToFile === true) {
+ if (ext === "wav" || ext === "ac3" || ext === "ec3" || opts?.streamToFile === true) {
const handleId = await window.openreel.fs.openWrite(chosen);
let cursor = 0;
return {
diff --git a/apps/web/src/services/native-ffmpeg-backend.ts b/apps/web/src/services/native-ffmpeg-backend.ts
index e3183beb..3bdd7a20 100644
--- a/apps/web/src/services/native-ffmpeg-backend.ts
+++ b/apps/web/src/services/native-ffmpeg-backend.ts
@@ -3,6 +3,8 @@ import {
effectiveRateControl,
exportStartTimecode,
exportWritesAlpha,
+ isDolbyFormat,
+ resolveDialnorm,
fingerprintBlob,
nativeProbeMismatch,
outputColorForExport,
@@ -124,6 +126,13 @@ export function broadcastStartFields(settings: VideoExportSettings): BroadcastSt
return fields;
}
+/** The Dolby fields of the start request: the audio codec and the dialnorm to write; nothing for AAC / Opus / PCM audio. */
+export function dolbyStartFields(settings: VideoExportSettings): { audioCodec?: "ac3" | "eac3"; dialnorm?: number } {
+ const audio = settings.audioSettings;
+ if (!isDolbyFormat(audio.format)) return {};
+ return { audioCodec: audio.format, dialnorm: resolveDialnorm(audio) };
+}
+
export class NativeFFmpegBackend implements EncoderBackend {
readonly requiresWebCodecsClamping = false;
// Native FFmpeg applies backpressure through frame credits. Clearing the
@@ -288,6 +297,7 @@ export class NativeFFmpegBackend implements EncoderBackend {
...(exportWritesAlpha(settings) ? { alpha: true } : {}),
keyframeInterval: settings.keyframeInterval,
audioBitrateKbps: settings.audioSettings.bitrate,
+ ...dolbyStartFields(settings),
...broadcastStartFields(settings),
...(this.colorOutput
? {
diff --git a/apps/web/src/services/quick-export-presets.ts b/apps/web/src/services/quick-export-presets.ts
index a8e7a81f..5a9617fc 100644
--- a/apps/web/src/services/quick-export-presets.ts
+++ b/apps/web/src/services/quick-export-presets.ts
@@ -1,6 +1,6 @@
import type { AudioExportSettings, VideoExportSettings } from "@openreel/core";
-export type QuickExportPresetId = "mp4" | "4k" | "1080p-high" | "1080p-60" | "wav";
+export type QuickExportPresetId = "mp4" | "4k" | "1080p-high" | "1080p-60" | "wav" | "ac3" | "eac3";
export type QuickVideoExportSettings = Pick<VideoExportSettings, "width" | "height" | "frameRate" | "format" | "codec"> & Partial<VideoExportSettings>;
type QuickExportPreset = {
@@ -9,7 +9,7 @@ type QuickExportPreset = {
description: string;
} & (
| { kind: "video"; settings: QuickVideoExportSettings }
- | { kind: "audio"; settings: Partial<AudioExportSettings> }
+ | { kind: "audio"; settings: Partial<AudioExportSettings>; /** File extension the save dialog offers. */ extension: "wav" | "ac3" | "ec3" }
);
/** The retained quick exports always cover the entire timeline. */
@@ -43,6 +43,19 @@ export function getQuickExportPresets(project: {
id: "wav", label: "Audio Only (WAV)", kind: "audio",
description: "48 kHz · stereo · 24-bit PCM",
settings: { format: "wav", sampleRate: 48000, channels: 2, bitDepth: 24 },
+ extension: "wav",
+ },
+ {
+ id: "ac3", label: "Audio Only (Dolby Digital)", kind: "audio",
+ description: "48 kHz · .ac3 · stereo 192 kbps, or 5.1 at 448 kbps for a 5.1 sequence",
+ settings: { format: "ac3", sampleRate: 48000, channels: 2, bitDepth: 24, bitrate: 192 },
+ extension: "ac3",
+ },
+ {
+ id: "eac3", label: "Audio Only (Dolby Digital Plus)", kind: "audio",
+ description: "48 kHz · .ec3 · stereo 256 kbps, or 5.1 at 640 kbps for a 5.1 sequence",
+ settings: { format: "eac3", sampleRate: 48000, channels: 2, bitDepth: 24, bitrate: 256 },
+ extension: "ec3",
},
];
}
diff --git a/apps/web/src/services/spectral-edit.ts b/apps/web/src/services/spectral-edit.ts
new file mode 100644
index 00000000..3f7f2731
--- /dev/null
+++ b/apps/web/src/services/spectral-edit.ts
@@ -0,0 +1,128 @@
+import {
+ clipSpectralRegions,
+ getSharedSpectralRepairCache,
+ getSpectralBackend,
+ planSpectralRegionsAction,
+ spectralRegionsKey,
+ type Clip,
+ type MediaItem,
+ type SpectralRegion,
+ type SpectralView,
+ type SpectralViewOptions,
+} from "@openreel/core";
+import { loadAudioBuffer } from "../utils/load-audio-buffer";
+import { useProjectStore } from "../stores/project-store";
+
+/**
+ * Spectral editing for a selected clip. The edit is the clip's "spectralRepair" audio effect (a list of
+ * regions in source time); committing one is a single undoable action. The spectrogram is computed in a
+ * worker from the decoded source with the edit applied, so what you see is what the preview and export play.
+ */
+
+export interface SpectralSource {
+ /** Identity of the decoded media (changes when the file does). */
+ readonly key: string;
+ readonly buffer: AudioBuffer;
+ readonly duration: number;
+ readonly sampleRate: number;
+}
+
+const sources = new Map<string, Promise<SpectralSource>>();
+const MAX_DECODE_BYTES = 400 * 1024 * 1024;
+
+export function findClip(clipId: string): Clip | undefined {
+ for (const track of useProjectStore.getState().project.timeline.tracks) {
+ const clip = track.clips.find((candidate) => candidate.id === clipId);
+ if (clip) return clip;
+ }
+ return undefined;
+}
+
+function findMedia(clip: Clip): MediaItem | undefined {
+ return useProjectStore.getState().project.mediaLibrary.items.find((item) => item.id === clip.mediaId);
+}
+
+/** The decoded source audio of a clip's media (cached per media file). Rejects when the clip has no decodable audio. */
+export function loadSpectralSource(clipId: string): Promise<SpectralSource> {
+ const clip = findClip(clipId);
+ const media = clip ? findMedia(clip) : undefined;
+ if (!clip || !media?.blob) return Promise.reject(new Error("This clip has no audio to edit."));
+ if (media.blob.size > MAX_DECODE_BYTES) return Promise.reject(new Error("This file is too large to open in the spectral editor."));
+ const key = `${media.id}:${media.blob.size}:${clip.audioTrackIndex ?? 0}`;
+ let job = sources.get(key);
+ if (!job) {
+ const rate = useProjectStore.getState().project.settings.sampleRate || 48000;
+ job = (async () => {
+ const context = new OfflineAudioContext(2, 1, rate);
+ const buffer = await loadAudioBuffer(context, media.blob as Blob, { audioTrackIndex: clip.audioTrackIndex ?? 0 });
+ if (!buffer) throw new Error("This clip has no decodable audio.");
+ return { key, buffer, duration: buffer.duration, sampleRate: buffer.sampleRate };
+ })();
+ job.catch(() => sources.delete(key));
+ sources.set(key, job);
+ }
+ return job;
+}
+
+/** Replaces the clip's region list as ONE undoable action (add / replace / remove the "spectralRepair" effect). Resolves false when rejected. */
+export async function commitSpectralRegions(clipId: string, regions: readonly SpectralRegion[]): Promise<boolean> {
+ const { project, actionExecutor } = useProjectStore.getState();
+ const clip = findClip(clipId);
+ if (!clip) return false;
+ const action = planSpectralRegionsAction(clip, regions, { actionId: crypto.randomUUID(), effectId: `spectral-${crypto.randomUUID()}` });
+ if (!action) return true;
+ const result = await actionExecutor.execute(action, project);
+ if (!result.success) {
+ console.error("Failed to edit spectral regions:", result.error?.message);
+ return false;
+ }
+ useProjectStore.setState({ project: { ...project, modifiedAt: Date.now() } });
+ return true;
+}
+
+export const regionsOf = (clip: Clip | undefined): SpectralRegion[] => clipSpectralRegions(clip);
+
+const loadedViews: string[] = [];
+const MAX_VIEW_SOURCES = 3;
+
+/**
+ * Makes the (optionally edited) source available to the spectrogram worker and returns its view key. With regions the
+ * edited audio comes from the shared repair cache (the same job the preview and export use); without, the original.
+ */
+export async function prepareSpectralView(source: SpectralSource, regions: readonly SpectralRegion[], showOriginal: boolean): Promise<string> {
+ const regionKey = showOriginal ? "" : spectralRegionsKey(regions);
+ const key = `${source.key}|${regionKey}`;
+ if (loadedViews.includes(key)) return key;
+ let buffer = source.buffer;
+ if (regionKey) {
+ const cache = getSharedSpectralRepairCache((channels, sampleRate) => {
+ const out = new OfflineAudioContext(1, 1, sampleRate).createBuffer(channels.length, Math.max(1, channels[0]?.length ?? 1), sampleRate);
+ channels.forEach((data, c) => out.getChannelData(c).set(data));
+ return out;
+ });
+ buffer = (await cache.request({ buffer: source.buffer, regions: regions.filter((region) => region.enabled) })) ?? source.buffer;
+ }
+ const mono = new Float32Array(buffer.length);
+ const channels = buffer.numberOfChannels;
+ for (let c = 0; c < channels; c += 1) {
+ const data = buffer.getChannelData(c);
+ for (let i = 0; i < mono.length; i += 1) mono[i] += data[i] / channels;
+ }
+ await getSpectralBackend().load(key, mono, buffer.sampleRate);
+ loadedViews.push(key);
+ while (loadedViews.length > MAX_VIEW_SOURCES) {
+ const old = loadedViews.shift();
+ if (old) void getSpectralBackend().drop(old);
+ }
+ return key;
+}
+
+export function requestSpectralView(viewKey: string, options: SpectralViewOptions): Promise<SpectralView> {
+ return getSpectralBackend().view(viewKey, options);
+}
+
+/** Forget a prepared view (its worker was restarted) so the next prepare loads it again. */
+export function forgetSpectralView(viewKey: string): void {
+ const at = loadedViews.indexOf(viewKey);
+ if (at >= 0) loadedViews.splice(at, 1);
+}
diff --git a/apps/web/src/services/watch-folder-tasks.test.ts b/apps/web/src/services/watch-folder-tasks.test.ts
new file mode 100644
index 00000000..0036fbd1
--- /dev/null
+++ b/apps/web/src/services/watch-folder-tasks.test.ts
@@ -0,0 +1,66 @@
+import { afterEach, describe, expect, it, vi } from "vitest";
+import { backgroundTasks } from "@openreel/core/tasks/task-registry";
+import type { OpenReelWatchFolderConfig, OpenReelWatchFoldersSnapshot, OpenReelWatchItem } from "../types/global";
+import { MAX_FINISHED_WATCH_TASKS, startWatchFolderTasks, syncWatchFolderTasks } from "./watch-folder-tasks";
+
+const ingest: OpenReelWatchFolderConfig = { id: "f1", kind: "ingest", path: "/Volumes/Card/DCIM", paused: false, bin: "Cards", createProxies: false, presetId: "1080p-high", outputDir: "", includeProjects: false, baselined: true, processExisting: false };
+const exportFolder: OpenReelWatchFolderConfig = { ...ingest, id: "f2", kind: "export", path: "/Users/me/Hot", outputDir: "/Users/me/Hot/output" };
+const status = { state: "watching" as const, detecting: 0, queued: 0, running: 0, done: 0, failed: 0, duplicates: 0 };
+const item = (extra: Partial<OpenReelWatchItem>): OpenReelWatchItem => ({ id: "i1", folderId: "f1", name: "a.mp4", path: "/Volumes/Card/DCIM/a.mp4", state: "queued", progress: null, createdAt: 1, ...extra });
+const snapshot = (items: OpenReelWatchItem[], folders = [ingest, exportFolder]): OpenReelWatchFoldersSnapshot => ({ folders: folders.map((config) => ({ config, status })), items });
+const tasks = () => backgroundTasks.getSnapshot().filter((task) => task.source === "watch-folders");
+
+afterEach(() => {
+ backgroundTasks.syncSource("watch-folders", []);
+ Reflect.deleteProperty(window, "openreel");
+});
+
+describe("watch folder tasks", () => {
+ it("shows ingest items as imports and export items as exports, with their state", () => {
+ syncWatchFolderTasks(snapshot([item({ id: "a", state: "running", progress: 0.4 }), item({ id: "b", folderId: "f2", name: "b.mov", state: "done", outputPath: "/o/b.mp4", detail: "Rendered to b.mp4" })]), vi.fn());
+ const [running, done] = tasks();
+ expect(running).toMatchObject({ kind: "import", status: "running", progress: 0.4, title: "Watch folder · Import a.mp4" });
+ expect(done).toMatchObject({ kind: "export", status: "completed", progress: 1, title: "Watch folder · Render b.mov", detail: "Rendered to b.mp4" });
+ });
+
+ it("explains a file that is still copying and a paused folder", () => {
+ syncWatchFolderTasks(snapshot([item({ id: "a", state: "detecting" })]), vi.fn());
+ expect(tasks()[0].detail).toBe("Waiting for the file to finish copying");
+ syncWatchFolderTasks(snapshot([item({ id: "a", state: "queued" })], [{ ...ingest, paused: true }]), vi.fn());
+ expect(tasks()[0].detail).toBe('Folder "DCIM" is paused');
+ });
+
+ it("offers Retry on a failed item and forwards it", () => {
+ const retry = vi.fn();
+ syncWatchFolderTasks(snapshot([item({ id: "bad", state: "failed", error: "Could not decode" })]), retry);
+ const [failed] = tasks();
+ expect(failed).toMatchObject({ status: "failed", error: "Could not decode" });
+ expect(failed.can.retry).toBe(true);
+ backgroundTasks.retry(failed.id);
+ expect(retry).toHaveBeenCalledWith("bad");
+ });
+
+ it("keeps every active item but only the newest finished ones, and drops items that left the list", () => {
+ const finished = Array.from({ length: MAX_FINISHED_WATCH_TASKS + 5 }, (_, n) => item({ id: `d${n}`, state: "done" }));
+ syncWatchFolderTasks(snapshot([item({ id: "run", state: "running" }), ...finished]), vi.fn());
+ expect(tasks()).toHaveLength(1 + MAX_FINISHED_WATCH_TASKS);
+ syncWatchFolderTasks(snapshot([]), vi.fn());
+ expect(tasks()).toHaveLength(0);
+ });
+
+ it("mirrors the bridge, and clears its tasks when stopped", async () => {
+ let push: (s: OpenReelWatchFoldersSnapshot) => void = () => undefined;
+ const off = vi.fn();
+ Object.defineProperty(window, "openreel", {
+ configurable: true,
+ value: { platform: "desktop", watchFolders: { list: vi.fn().mockResolvedValue(snapshot([item({ id: "x", state: "running" })])), onChange: (cb: typeof push) => ((push = cb), off), retry: vi.fn() } },
+ });
+ const stop = startWatchFolderTasks();
+ await vi.waitFor(() => expect(tasks()).toHaveLength(1));
+ push(snapshot([item({ id: "x", state: "done" }), item({ id: "y", state: "running" })]));
+ expect(tasks().map((t) => t.status).sort()).toEqual(["completed", "running"]);
+ stop();
+ expect(off).toHaveBeenCalled();
+ expect(tasks()).toHaveLength(0);
+ });
+});
diff --git a/apps/web/src/services/watch-folder-tasks.ts b/apps/web/src/services/watch-folder-tasks.ts
new file mode 100644
index 00000000..64a3014b
--- /dev/null
+++ b/apps/web/src/services/watch-folder-tasks.ts
@@ -0,0 +1,84 @@
+import { backgroundTasks, type BackgroundTaskInput, type BackgroundTaskStatus } from "@openreel/core/tasks/task-registry";
+import type { OpenReelWatchFoldersSnapshot, OpenReelWatchItem, OpenReelWatchItemState } from "../types/global";
+
+/**
+ * Mirrors desktop watch-folder activity into the background task panel. The work itself runs in the
+ * main process; this only presents it (the only control is Retry on a failed item).
+ */
+
+const STATUS: Record<OpenReelWatchItemState, BackgroundTaskStatus> = {
+ detecting: "queued",
+ queued: "queued",
+ waiting: "queued",
+ running: "running",
+ done: "completed",
+ failed: "failed",
+ duplicate: "completed",
+ cancelled: "cancelled",
+};
+
+const DETAIL: Partial<Record<OpenReelWatchItemState, string>> = {
+ detecting: "Waiting for the file to finish copying",
+ duplicate: "Duplicate, skipped",
+};
+
+/** Newest finished items kept in the panel (the main process keeps more; the panel stays short). */
+export const MAX_FINISHED_WATCH_TASKS = 12;
+
+const folderName = (snapshot: OpenReelWatchFoldersSnapshot, id: string): string => {
+ const folder = snapshot.folders.find((entry) => entry.config.id === id)?.config;
+ return folder ? (folder.path.split(/[\\/]/).filter(Boolean).pop() ?? folder.path) : "folder";
+};
+
+function toTask(snapshot: OpenReelWatchFoldersSnapshot, item: OpenReelWatchItem): BackgroundTaskInput {
+ const config = snapshot.folders.find((entry) => entry.config.id === item.folderId)?.config;
+ const verb = config?.kind === "export" ? "Render" : "Import";
+ const paused = config?.paused === true && (item.state === "queued" || item.state === "detecting");
+ return {
+ id: `watch-folders:${item.id}`,
+ kind: config?.kind === "export" ? "export" : "import",
+ source: "watch-folders",
+ title: `Watch folder · ${verb} ${item.name}`,
+ detail: paused ? `Folder "${folderName(snapshot, item.folderId)}" is paused` : (item.error ?? item.detail ?? DETAIL[item.state] ?? folderName(snapshot, item.folderId)),
+ status: STATUS[item.state],
+ progress: item.state === "running" ? item.progress : item.state === "done" ? 1 : item.state === "queued" || item.state === "detecting" ? 0 : null,
+ createdAt: item.createdAt,
+ startedAt: item.startedAt,
+ finishedAt: item.finishedAt,
+ error: item.state === "failed" ? item.error : undefined,
+ };
+}
+
+export function syncWatchFolderTasks(snapshot: OpenReelWatchFoldersSnapshot, retry: (itemId: string) => void): void {
+ const active = snapshot.items.filter((item) => item.state === "detecting" || item.state === "queued" || item.state === "waiting" || item.state === "running");
+ const finished = snapshot.items.filter((item) => !active.includes(item)).slice(0, MAX_FINISHED_WATCH_TASKS);
+ backgroundTasks.syncSource(
+ "watch-folders",
+ [...active, ...finished].map((item) => ({
+ task: toTask(snapshot, item),
+ controls: item.state === "failed" ? { retry: () => retry(item.id) } : {},
+ })),
+ );
+}
+
+/** Starts mirroring. Returns a stop function. A no-op off desktop. */
+export function startWatchFolderTasks(): () => void {
+ const bridge = window.openreel?.watchFolders;
+ if (!bridge) return () => undefined;
+ let alive = true;
+ const retry = (itemId: string): void => void bridge.retry(itemId).catch(() => undefined);
+ const off = bridge.onChange((snapshot) => {
+ if (alive) syncWatchFolderTasks(snapshot, retry);
+ });
+ void bridge
+ .list()
+ .then((snapshot) => {
+ if (alive) syncWatchFolderTasks(snapshot, retry);
+ })
+ .catch(() => undefined);
+ return () => {
+ alive = false;
+ off();
+ backgroundTasks.syncSource("watch-folders", []);
+ };
+}
diff --git a/apps/web/src/stores/settings-store.ts b/apps/web/src/stores/settings-store.ts
index 5ae85ae5..a014a7d3 100644
--- a/apps/web/src/stores/settings-store.ts
+++ b/apps/web/src/stores/settings-store.ts
@@ -51,7 +51,7 @@ 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";
+export type SettingsTab = "general" | "ai-editor" | "api-keys" | "mcp" | "watch-folders";
function isLlmProvider(value: unknown): value is LlmProvider {
return value === "openai-compatible" || value === "anthropic-compatible";
diff --git a/apps/web/src/types/global.d.ts b/apps/web/src/types/global.d.ts
index 2d47a727..2b30ed0d 100644
--- a/apps/web/src/types/global.d.ts
+++ b/apps/web/src/types/global.d.ts
@@ -39,6 +39,10 @@ interface OpenReelExportStartArgs {
alpha?: boolean;
keyframeInterval?: number;
audioBitrateKbps?: number;
+ /** Audio codec of the file: "ac3" (Dolby Digital) or "eac3" (Dolby Digital Plus); absent = AAC / Opus / PCM by container. */
+ audioCodec?: "ac3" | "eac3";
+ /** AC-3 / E-AC-3 dialogue normalisation in dB, -31 to -1. */
+ dialnorm?: number;
/**
* Colour-managed export: frames are raw planar YCbCr already converted to this output space (not RGBA);
* the sidecar tags the stream and writes 10-bit HEVC / ProRes 4444 for HDR.
@@ -425,6 +429,64 @@ export interface OpenReelIngestBridge {
}>;
}
+/** Mirrors apps/desktop/src/shared/watch-folders.ts (the web package cannot import apps/desktop). */
+export interface OpenReelWatchFolderConfig {
+ id: string;
+ kind: "ingest" | "export";
+ path: string;
+ paused: boolean;
+ bin: string;
+ createProxies: boolean;
+ presetId: string;
+ outputDir: string;
+ includeProjects: boolean;
+ baselined: boolean;
+ processExisting: boolean;
+}
+export type OpenReelWatchItemState = "detecting" | "queued" | "waiting" | "running" | "done" | "failed" | "duplicate" | "cancelled";
+export interface OpenReelWatchItem {
+ id: string;
+ folderId: string;
+ name: string;
+ path: string;
+ state: OpenReelWatchItemState;
+ progress: number | null;
+ detail?: string;
+ error?: string;
+ outputPath?: string;
+ startedAt?: number;
+ finishedAt?: number;
+ createdAt: number;
+}
+export interface OpenReelWatchFolderStatus {
+ state: "watching" | "paused" | "missing" | "error";
+ message?: string;
+ detecting: number;
+ queued: number;
+ running: number;
+ done: number;
+ failed: number;
+ duplicates: number;
+}
+export interface OpenReelWatchFoldersSnapshot {
+ folders: Array<{ config: OpenReelWatchFolderConfig; status: OpenReelWatchFolderStatus }>;
+ items: OpenReelWatchItem[];
+}
+export interface OpenReelWatchFoldersBridge {
+ list(): Promise<OpenReelWatchFoldersSnapshot>;
+ /** Opens the native folder dialog; the path never passes through the page. */
+ add(kind: "ingest" | "export"): Promise<{ added: boolean; id?: string }>;
+ update(
+ id: string,
+ patch: Partial<Pick<OpenReelWatchFolderConfig, "paused" | "bin" | "createProxies" | "presetId" | "includeProjects" | "processExisting">>,
+ ): Promise<void>;
+ pickOutput(id: string): Promise<{ changed: boolean }>;
+ remove(id: string): Promise<void>;
+ retry(itemId: string): Promise<void>;
+ clearFinished(): Promise<void>;
+ onChange(cb: (snapshot: OpenReelWatchFoldersSnapshot) => void): () => void;
+}
+
export type OpenReelProjectLockResult =
| { status: "acquired" }
| {
@@ -437,6 +499,7 @@ declare global {
interface Window {
openreel?: {
ingest?: OpenReelIngestBridge;
+ watchFolders?: OpenReelWatchFoldersBridge;
platform: "desktop";
publicOrigin: string;
/** True for perf/e2e/CI/agent launches (computed in main, read synchronously in preload). Suppresses onboarding. */
@@ -510,6 +573,15 @@ declare global {
writeAudioWav(jobId: string, wav: ArrayBuffer): Promise<void>;
writeAudioChunk(jobId: string, chunk: ArrayBuffer, position: number): Promise<void>;
finishAudio(jobId: string): Promise<void>;
+ /** Audio-only AC-3 / E-AC-3: encode a WAV mixdown (5.1 as L R C LFE Ls Rs) with the ffmpeg sidecar into a raw elementary stream. */
+ encodeDolbyAudio(args: {
+ wav: ArrayBuffer;
+ codec: "ac3" | "eac3";
+ channels: 2 | 6;
+ bitrateKbps: number;
+ sampleRate: 44100 | 48000;
+ dialnorm: number;
+ }): Promise<ArrayBuffer>;
cancel(jobId: string): Promise<void>;
/** Native smart render: stream-copy `frames` packets of a source file from its key frame at `sourceStart`. */
copyRun(
@@ -600,6 +672,8 @@ declare global {
kind: "listTools" | "callTool";
name?: string;
args?: Record<string, unknown>;
+ /** Set by the main process for watch-folder work only. */
+ origin?: "watch-folders";
}) => Promise<{ ok: boolean; result?: unknown; error?: string }>,
): () => void;
getStatus(): Promise<OpenReelMcpStatus>;
diff --git a/docs/AGENT-CAPABILITIES.md b/docs/AGENT-CAPABILITIES.md
index e4671ed4..9cc669d8 100644
--- a/docs/AGENT-CAPABILITIES.md
+++ b/docs/AGENT-CAPABILITIES.md
@@ -556,6 +556,7 @@ The agent exposes **453 tools** spanning read/observe, project, track, clip, tra
"gate",
"brickwallLimiter",
"lowPass",
+ "spectralRepair",
"fadeIn",
"fadeOut"
],
diff --git a/docs/PREMIERE-GAPS.md b/docs/PREMIERE-GAPS.md
index 4947db35..64c69a4f 100644
--- a/docs/PREMIERE-GAPS.md
+++ b/docs/PREMIERE-GAPS.md
@@ -36,13 +36,14 @@ Everything it cannot place goes in an import report shown before the import (dro
- **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, 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.
+- **Spectral editing (partly closed):** Audio tab > Spectral editing shows an STFT spectrogram of the clip's source (log frequency axis, colour maps, time zoom and pan, computed in a worker). Rectangle selection and a frequency-band marquee (whole source) can be attenuated by N dB or removed (filled by interpolating from the surrounding frames). Edits are a "spectralRepair" clip audio effect holding source-time regions: one undo step per edit, applied before every other clip effect in both the realtime preview and the export through one shared cached repair job. Covered by `spectral-dsp.test.ts` (STFT/ISTFT reconstruction, tone removal, N dB attenuation), `spectral-repair-cache.test.ts`, `realtime-audio-graph.spectral.test.ts`, `audio-engine.render-integration.test.ts` and `e2e/spectral-editing.spec.ts`. Not done: lasso and brush selection, per-region undo within the editor panel beyond Remove, spectral healing for non-stationary content, and the agent/MCP tools (see `known-limitations.md`).
- **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. **ACES is in** (project setting Preview options > Color management: Display-referred or ACES; analytic ACES 1.3 IDTs into ACEScg, ACEScct grading, RRT + ODT to sRGB, Rec.709 BT.1886, Rec.2020 PQ 1000 nit and HLG; GPU and CPU paths; per-footage and per-clip input override; undoable and saved with the project; unit tests against OpenColorIO's ACES 1.3 builtins in `aces.test.ts` and an e2e in `aces-color.spec.ts`, see docs/colour-management.md). **OCIO is partial:** an `.ocio` config's colour spaces are parsed and the ones that equal a built-in preset can be applied in Interpret Footage, the rest are reported as unsupported; OpenReel does not run an OCIO config's own transforms, LUTs, looks or views. **Still open:** ACES 2.0, gamut compression and LMTs, Display P3 and 2000/4000 nit output transforms, a full OCIO runtime.
- **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.
### Later list (section 4)
-Done since the audit: `.prproj` import (read-only, see below), multicam editable sources and retime, range markers, effect plugin hosting through the OpenReel plugin SDK (not VST3/AU), DNG and CinemaDNG RAW, 5.1 surround, MXF/ProRes/DNxHR ingest and delivery, desktop HDR10/HLG export. Everything else on that list remains open, including VST3/AU, Atmos and AC-3, BRAW/R3D/ARRIRAW, Dynamic Link, `.mogrt`, a full OCIO runtime (ACES 1.3 and partial OCIO config import are done, see WP4), Dolby Vision, spectral editing, Windows and Linux perf qualification, and watch folders.
+Done since the audit: `.prproj` import (read-only, see below), multicam editable sources and retime, range markers, effect plugin hosting through the OpenReel plugin SDK (not VST3/AU), DNG and CinemaDNG RAW, 5.1 surround, spectral editing (rectangle and band repair), Dolby Digital (AC-3) and Digital Plus (E-AC-3) delivery (stereo and 5.1; see below), MXF/ProRes/DNxHR ingest and delivery, desktop HDR10/HLG export. Everything else on that list remains open, including VST3/AU, Dolby Atmos, BRAW/R3D/ARRIRAW, Dynamic Link, `.mogrt`, a full OCIO runtime (ACES 1.3 and partial OCIO config import are done, see WP4), Dolby Vision, and Windows and Linux perf qualification. Desktop watch folders (ingest and render) are done.
## 1. Verdict
@@ -94,7 +95,7 @@ Perf work (must-fix 6 to 8) has its own owner in `apps/desktop/scripts/*` and `p
## 4. Later
-- **Large effort, low audience:** VST3/AU host, Atmos and AC-3 delivery, multichannel monitoring, native R3D/BRAW/ARRIRAW, Dynamic Link, `.mogrt` interchange, full OCIO (ACES 1.3 is done), display P3, HDR monitoring and Dolby Vision, spectral editing, ML speech enhancement, multicam editable sources and angle add/replace.
+- **Large effort, low audience:** VST3/AU host, Dolby Atmos delivery (AC-3 / E-AC-3 stereo and 5.1 is done; Atmos / JOC is not), multichannel monitoring, native R3D/BRAW/ARRIRAW, Dynamic Link, `.mogrt` interchange, full OCIO (ACES 1.3 is done), display P3, HDR monitoring and Dolby Vision, 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, 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.
@@ -108,3 +109,9 @@ Perf work (must-fix 6 to 8) has its own owner in `apps/desktop/scripts/*` and `p
- **Delivery and ingest:** the desktop ffmpeg sidecar decodes and exports ProRes, DNxHR and XDCAM MXF with no proxy. There is also smart render (93 to 98% copied), a persistent export queue, verified copy-ingest and a resumable proxy pipeline.
- **Interchange and reliability:** XMEML, FCPXML, OTIO and AAF with a dropped-items report, plus soak-tested stability (110 min, 787 clips, crash recovery, no leaked decoders).
- **Candid docs:** known-limitations, soak and perf reports state what is unverified.
+
+### Dolby Digital (AC-3) and Digital Plus (E-AC-3) delivery
+
+Done: stereo and 5.1 through ffmpeg's `ac3` / `eac3` encoders. Desktop (native ffmpeg sidecar): the audio track of MP4 and MOV (`ac-3` / `ec-3` sample entries) and MKV (`A_AC3` / `A_EAC3`), and raw `.ac3` / `.ec3` audio-only files. Web: raw `.ac3` / `.ec3` only, through the bundled ffmpeg.wasm 0.12.6 core (its `-encoders` list includes `ac3`, `ac3_fixed` and `eac3`, and its muxers include raw `ac3` / `eac3`); AC-3 tracks inside video files and MKV are refused in the browser with a desktop-only reason. Bitrates 192 to 640 kbps (AC-3) and 192 to 1024 kbps (E-AC-3), dialnorm -31 to -1 (defaults to the loudness target when loudness normalisation is on), 32 / 44.1 / 48 kHz (96 kHz is written at 48 kHz). The 5.1 mixer's L R C LFE Ls Rs order is relabelled by index to ffmpeg's `5.1(side)`. Export presets and quick exports added. Tested: the desktop integration suite runs the real sidecar and checks ffprobe `codec_name`, `channels`, `channel_layout`, `bit_rate`, duration and the Matroska codec ids, then decodes back and checks the level per channel.
+
+**Still open:** Dolby Atmos (E-AC-3 JOC and ADM/Atmos masters; needs Dolby's licensed encoder and object metadata, and the editor has no object-based mixer), 7.1, dynamic range control profiles / other metadata beyond dialnorm, and a browser AC-3 track inside video files.
diff --git a/docs/known-limitations.md b/docs/known-limitations.md
index 03e36202..383fb14b 100644
--- a/docs/known-limitations.md
+++ b/docs/known-limitations.md
@@ -150,7 +150,7 @@ Shipped and verified in a real browser (`apps/web/e2e/essential-sound.spec.ts`):
Limits that remain:
-- The SFX preset uses the lookahead Brickwall Limiter and the Ambience preset the Low-Pass Filter (see docs/pro-audio.md). 5.1 surround is supported (sequence layout, surround panner, six-channel AAC in MP4/MOV, 5.1 stems, BS.1770 surround loudness); its limits (stereo clip-level effects, stereo down-mix monitoring, no AC-3 or six-channel Opus) are listed in docs/pro-audio.md.
+- The SFX preset uses the lookahead Brickwall Limiter and the Ambience preset the Low-Pass Filter (see docs/pro-audio.md). 5.1 surround is supported (sequence layout, surround panner, six-channel AAC in MP4/MOV, 5.1 stems, BS.1770 surround loudness); its limits (stereo clip-level effects, stereo down-mix monitoring, six-channel Opus is not available; AC-3 / E-AC-3 delivery is covered in docs/PREMIERE-GAPS.md) are listed in docs/pro-audio.md.
- Auto-Match is limited by the +12 dB clip gain ceiling; a clip that needs more shows a warning and lands short of the target.
- Ducking is live: it follows the Dialogue clips when they move or trim (docs/pro-audio.md). It reacts to dialogue clip presence, not to speech level inside a clip. Ducks baked by earlier versions stay as keyframes until Duck is switched off and on.
- Matching is not repeated when you change the clarity or ducking options (it would re-measure every drag); press "Match again" if the effect chain changed the level.
@@ -324,3 +324,30 @@ The panel (status bar pill and popover) is a presentation layer over `Background
- Import only, and read from hand-authored fixtures: a project saved by Adobe Premiere Pro has not been tested. Treat the import report as the source of truth for what arrived.
- One sequence per import (pick it in the dialog). Other sequences, master-clip markers, Lumetri and other effects, time-remap ramps, keyframed motion/opacity/volume, titles and graphics, captions, adjustment layers, track mixer settings and Productions are not carried and are reported.
- A disabled clip is imported fully transparent and muted (there is no clip enable switch); Premiere sizes media from native pixels while OpenReel fits the frame first, so scaled or moved clips can frame differently.
+
+## Dolby Digital (AC-3) and Digital Plus (E-AC-3)
+
+- AC-3 / E-AC-3 inside MP4, MOV and MKV is desktop only (the native ffmpeg sidecar). The browser writes raw `.ac3` / `.ec3` audio-only files through ffmpeg.wasm and refuses AC-3 video-file tracks with a desktop-only message.
+- Stereo and 5.1 only. Dialnorm is the only Dolby metadata written; no DRC profiles, no Dolby Atmos (E-AC-3 JOC) and no 7.1.
+- The sample rate is 44.1 or 48 kHz (anything else is written at 48 kHz).
+- The browser path is tested at the unit level and by confirming the bundled core lists the encoders and muxers; the ffprobe and per-channel level checks run against the desktop sidecar only.
+
+## Spectral editing
+
+- **Rectangle and frequency-band selection only.** No lasso, brush or magic-wand selection, and no harmonic (overtone-following) selection. A band marquee always covers the whole source.
+- **Source-time regions.** Regions live in the clip's source time, so trimming the clip does not move them; a region outside the clip's in/out range stays stored but is inaudible. Behaviour under speed changes was not tested.
+- **Remove is interpolation, not resynthesis.** It fills the region from the bins above and below (and the frames around it) with a short cross-fade; it clears steady tones, hum and short clicks cleanly, but broadband or fast-moving sounds inside the box leave audible artefacts. Attenuation is exact only for steady content; the tested tolerance is a tone attenuated by N dB within 0.1 dB.
+- **Preview and export play the same repaired samples** (one shared cached repair job, applied before every other clip effect, verified at -92 dB residual in the e2e). The first repair of a clip renders before it can play, in a worker, and the cost grows with clip length (not benchmarked); very long sources (over 400 MB of media) are refused by the editor.
+- **No agent/MCP tool.** `packages/agent` does not expose spectral regions, so `docs/AGENT-CAPABILITIES.md` is unchanged (it is generated from the tool registry).
+- **The desktop app was not given its own spectral e2e**; the feature runs from the shared web bundle and was exercised end to end in the web e2e only.
+
+## Watch folders (desktop)
+
+- **Desktop only.** The web app has no folder access, so there is no web equivalent.
+- **Polling, not OS events.** Folders are rescanned every 5 s and candidate files are re-checked every 0.7 s; a file must keep the same size and modified time for 2.5 s before it is touched. A copy that stalls for longer than that (a slow network or card reader) can be picked up while still incomplete. Network shares are scanned the same way and were not tested.
+- **Ingest needs an open project and an editor window.** With none, files wait (shown as waiting in the panel) and import once a project is open. Imports go through the editor one file at a time, and the import tool's limits apply (files over 1 GiB are skipped and shown as failed).
+- **Existing files are not processed** when a folder is added (they are recorded and skipped) and there is no switch for it in the UI (only the saved `processExisting` setting in `watch-folders.json` turns it on).
+- **Media export is a re-encode by the bundled ffmpeg**, not the editor's renderer: it applies the preset's size, frame rate and bitrate to the source file (letterboxed to fit) and is not a render of a timeline. Colour management, HDR, LUTs and effects are not applied. Audio-only (WAV) cannot render a project.
+- **Project export uses the editor window.** Dropping a project file opens it in the editor (the open project is saved first and is replaced in the editor) and renders it through the export queue, so it is not a background render and it interrupts whatever is open. The project's footage must be reachable: the editor reconnects remembered paths, then searches the folders the project recorded and the folder the project file sits in; media that cannot be found fails the item with the editor's "Relink the original media" message. Only the video presets apply to projects.
+- **Duplicates** are detected by content (size plus a hash of the first and last 256 KiB), not by name, so a renamed copy is caught but a file that differs only in its middle is not. The ledger keeps 5,000 entries per folder, so a very old duplicate may be processed again.
+- **Verified** with synthetic clips on macOS (arm64) only. Not exercised: Windows and Linux, network drives, long camera-card ingests, 4K render timing.
diff --git a/docs/pro-audio.md b/docs/pro-audio.md
index 4c11b31b..8c96f6df 100644
--- a/docs/pro-audio.md
+++ b/docs/pro-audio.md
@@ -161,8 +161,9 @@ Audio Mixer > **Sequence audio** selects Stereo or 5.1 Surround. It is the
multichannel audio device; it monitors through the stereo down-mix (the meters
show all six). The stereo-only DeClick / DeClip / DeReverb repair effects still
process each channel on its own (they have no cross-channel state to link).
-* AC-3 / E-AC-3 (Dolby Digital) and 6-channel Opus export are not available;
- 5.1 delivery is AAC in MP4 / MOV and PCM WAV.
+* 6-channel Opus export is not available. 5.1 delivery is AAC in MP4 / MOV, PCM WAV,
+ and Dolby Digital (AC-3) / Digital Plus (E-AC-3) in MP4 / MOV / MKV (desktop) or
+ raw `.ac3` / `.ec3` (desktop and web); see docs/PREMIERE-GAPS.md.
* 7.1 and other layouts. Sources wider than six channels are folded to 5.1 by ffmpeg.
* The legacy clip "pan" effect and the stereo track pan are ignored in a 5.1
sequence (the surround panner replaces them); they come back with Stereo.
diff --git a/packages/core/src/audio/audio-engine.render-integration.test.ts b/packages/core/src/audio/audio-engine.render-integration.test.ts
index 0b8a6b9f..9b1f4168 100644
--- a/packages/core/src/audio/audio-engine.render-integration.test.ts
+++ b/packages/core/src/audio/audio-engine.render-integration.test.ts
@@ -2,6 +2,8 @@ import { describe, expect, it, vi } from "vitest";
import { AudioEngine } from "./audio-engine";
import type { AudioClipRenderInfo } from "./types";
import type { MediaItem } from "../types";
+import { applySpectralRegions } from "./spectral/spectral-dsp";
+import { createSpectralRepairEffect, type SpectralRegion } from "./spectral/spectral-regions";
const SR = 8000;
@@ -163,4 +165,44 @@ describe("export render with a realistic offline graph", () => {
expect(energy(l, 0, 1)).toBeGreaterThan(energy(r, 0, 1) * 4);
expect(energy(r, 3, 4)).toBeGreaterThan(energy(l, 3, 4) * 4);
});
+
+ describe("spectral repair", () => {
+ const region: SpectralRegion = { id: "r", mode: "remove", startTime: 0, endTime: 4, lowHz: 400, highHz: 600, gainDb: -120, enabled: true };
+ const two = () => makeBuffer(1, 4 * SR, (i) => 0.3 * Math.sin((2 * Math.PI * 500 * i) / SR) + 0.3 * Math.sin((2 * Math.PI * 1500 * i) / SR));
+ const amp = (x: Float32Array, f: number) => {
+ let re = 0, im = 0;
+ for (let i = SR; i < 3 * SR; i++) { re += x[i] * Math.cos((2 * Math.PI * f * i) / SR); im -= x[i] * Math.sin((2 * Math.PI * f * i) / SR); }
+ return (2 * Math.hypot(re, im)) / (2 * SR);
+ };
+
+ it("renders the repaired source: the same samples the DSP produces, tone gone, the other tone kept", async () => {
+ const ctx = new RealisticOffline(2, 4 * SR, SR);
+ const engine = engineFor(null);
+ const source = two();
+ await engine.renderBufferToContext(ctx, source, info({ effects: [createSpectralRepairEffect("sr", [region])] }), 0);
+ expect(ctx.sources).toHaveLength(1);
+ const played = ctx.sources[0].buffer!.getChannelData(0);
+ expect(Array.from(played)).toEqual(Array.from(applySpectralRegions([source.getChannelData(0)], SR, [region])[0]));
+ expect(amp(played, 500)).toBeLessThan(amp(source.getChannelData(0), 500) * 0.04);
+ expect(Math.abs(amp(played, 1500) / amp(source.getChannelData(0), 1500) - 1)).toBeLessThan(0.005);
+ });
+
+ it("leaves a clip with a disabled or empty spectral effect on the original source", async () => {
+ const ctx = new RealisticOffline(2, 4 * SR, SR);
+ const engine = engineFor(null);
+ const source = two();
+ await engine.renderBufferToContext(ctx, source, info({ effects: [createSpectralRepairEffect("a", []), { ...createSpectralRepairEffect("b", [region]), enabled: false }] }), 0);
+ expect(ctx.sources[0].buffer).toBe(source);
+ });
+
+ it("decodes the whole source instead of streaming segments, so the repair sees the same audio as the preview", async () => {
+ const ctx = new RealisticOffline(2, 4 * SR, SR);
+ const decoded = two();
+ const engine = engineFor(decoded, [makeBuffer(1, 2 * SR, () => 0.5), makeBuffer(1, 2 * SR, () => 0.5)]);
+ const media = { id: "m", metadata: { duration: 4 } } as unknown as MediaItem;
+ await engine.renderClipToContext(ctx, media, info({ effects: [createSpectralRepairEffect("sr", [region])] }), 0, true);
+ expect(ctx.sources).toHaveLength(1);
+ expect(amp(ctx.sources[0].buffer!.getChannelData(0), 500)).toBeLessThan(amp(decoded.getChannelData(0), 500) * 0.04);
+ });
+ });
});
diff --git a/packages/core/src/audio/audio-engine.ts b/packages/core/src/audio/audio-engine.ts
index f3636481..61c6bea8 100644
--- a/packages/core/src/audio/audio-engine.ts
+++ b/packages/core/src/audio/audio-engine.ts
@@ -30,6 +30,8 @@ import { scheduleVolumeAutomationOnGain } from "./clip-volume-automation";
import { schedulePanAutomationOnParam } from "./clip-pan-automation";
import { shouldPreservePitch, timeStretchChannels } from "./time-stretch";
import { getSharedStretchCache } from "./stretch-cache";
+import { getSharedSpectralRepairCache } from "./spectral/spectral-repair-cache";
+import { SPECTRAL_REPAIR_EFFECT_TYPE, getSpectralRepairRegions, type SpectralRegion } from "./spectral/spectral-regions";
import { hasAudioRouting, getAudioBuses } from "./audio-routing";
import { AudioRoutingGraph, buildOfflineTrackChain } from "./audio-routing-graph";
import { planTimelineDelayCompensation, rackLatencySamples } from "./effect-latency";
@@ -678,7 +680,8 @@ export class AudioEngine {
preferSegments = false,
): Promise<void> {
if (this.noAudioMedia.has(this.getAudioSourceKey(mediaItem, clipInfo.audioTrackIndex ?? 0))) return;
- if (this.shouldUseSegmentedAudioDecoding(mediaItem, preferSegments)) {
+ // Spectral repair processes the whole decoded source (the same samples the preview plays), so such clips skip the streaming decode.
+ if (getSpectralRepairRegions(clipInfo.effects).length === 0 && this.shouldUseSegmentedAudioDecoding(mediaItem, preferSegments)) {
const renderedSegment = await this.renderClipToContextFromSegments(
context,
mediaItem,
@@ -705,6 +708,12 @@ export class AudioEngine {
renderStartTime: number,
sourceOffset = clipInfo.sourceTime,
): Promise<void> {
+ // Spectral repair: the clip's region edits are applied to the whole decoded source (regions are source-time) through
+ // the cache the live preview shares, so preview and export play the same samples; everything below sees the repaired audio.
+ if (!clipInfo.compoundClipId) {
+ const regions = getSpectralRepairRegions(clipInfo.effects);
+ if (regions.length > 0) audioBuffer = await this.repairSpectrally(audioBuffer, regions);
+ }
// 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();
@@ -792,7 +801,7 @@ export class AudioEngine {
}> {
const enabledEffects = clipInfo.effects.filter(
(effect) =>
- effect.enabled && effect.type !== "pan" && effect.type !== "fadeIn" && effect.type !== "fadeOut",
+ effect.enabled && effect.type !== "pan" && effect.type !== "fadeIn" && effect.type !== "fadeOut" && effect.type !== SPECTRAL_REPAIR_EFFECT_TYPE,
);
if (
@@ -858,6 +867,16 @@ export class AudioEngine {
);
}
+ /** The source buffer with spectral regions applied: cached and computed off the main thread, with an inline fallback so an export is never silently unrepaired. */
+ private async repairSpectrally(buffer: AudioBuffer, regions: SpectralRegion[]): Promise<AudioBuffer> {
+ const cached = await getSharedSpectralRepairCache((channels, sampleRate) => this.buildStretchBuffer(channels, sampleRate)).request({ buffer, regions });
+ if (cached) return cached;
+ const { applySpectralRegions } = await import("./spectral/spectral-dsp");
+ const channels: Float32Array[] = [];
+ for (let c = 0; c < buffer.numberOfChannels; c += 1) channels.push(buffer.getChannelData(c));
+ return this.buildStretchBuffer(applySpectralRegions(channels, buffer.sampleRate, regions), buffer.sampleRate);
+ }
+
private buildStretchBuffer(channels: Float32Array[], sampleRate: number): AudioBuffer {
const out = this.audioContext!.createBuffer(channels.length, Math.max(1, channels[0]?.length ?? 1), sampleRate);
channels.forEach((data, c) => out.getChannelData(c).set(data));
diff --git a/packages/core/src/audio/index.ts b/packages/core/src/audio/index.ts
index 863ae605..d1d1a5ce 100644
--- a/packages/core/src/audio/index.ts
+++ b/packages/core/src/audio/index.ts
@@ -41,6 +41,7 @@ export * from "./scrub-grain";
export * from "./effect-latency";
export * from "./audio-routing-graph";
export * from "./repair";
+export * from "./spectral";
export * from "./essential-sound";
export * from "./surround";
export * from "./channel-map";
diff --git a/packages/core/src/audio/realtime-audio-graph.spectral.test.ts b/packages/core/src/audio/realtime-audio-graph.spectral.test.ts
new file mode 100644
index 00000000..3eb0bdb3
--- /dev/null
+++ b/packages/core/src/audio/realtime-audio-graph.spectral.test.ts
@@ -0,0 +1,177 @@
+import { afterEach, describe, expect, it, vi } from "vitest";
+import { RealtimeAudioGraph, type AudioClipSchedule } from "./realtime-audio-graph";
+import type { MasterTimelineClock } from "../playback/master-timeline-clock";
+import type { SpectralBackend } from "./spectral/spectral-worker-client";
+import { applySpectralRegions } from "./spectral/spectral-dsp";
+import { createSpectralRepairEffect, type SpectralRegion } from "./spectral/spectral-regions";
+
+function fixture() {
+ const nodes: Array<{ disconnect: ReturnType<typeof vi.fn> }> = [];
+ const gains: Array<{ gain: ReturnType<typeof parameter> }> = [];
+ const panners: Array<{ pan: { value: number } }> = [];
+ const sources: Array<ReturnType<typeof sourceNode>> = [];
+ const parameter = () => ({
+ value: 1,
+ setValueAtTime: vi.fn(),
+ cancelScheduledValues: vi.fn(),
+ linearRampToValueAtTime: vi.fn(),
+ });
+ const node = () => {
+ const result = { connect: vi.fn(), disconnect: vi.fn() };
+ nodes.push(result);
+ return result;
+ };
+ const sourceNode = () => ({
+ ...node(),
+ buffer: null as AudioBuffer | null,
+ playbackRate: parameter(),
+ start: vi.fn(),
+ stop: vi.fn(),
+ onended: null as (() => void) | null,
+ });
+ const context = {
+ currentTime: 0,
+ destination: {},
+ sampleRate: 8000,
+ createGain: () => {
+ const value = { ...node(), gain: parameter() };
+ gains.push(value);
+ return value;
+ },
+ createStereoPanner: () => {
+ const value = { ...node(), pan: parameter() };
+ panners.push(value);
+ return value;
+ },
+ createBuffer: (channels: number, length: number, sampleRate: number) => {
+ const data = Array.from({ length: channels }, () => new Float32Array(length));
+ return { numberOfChannels: channels, length, sampleRate, duration: length / sampleRate,
+ getChannelData: (c: number) => data[c] } as unknown as AudioBuffer;
+ },
+ createBufferSource: () => {
+ const value = sourceNode();
+ sources.push(value);
+ return value;
+ },
+ };
+ const state = { time: 0 };
+ const clock = {
+ getAudioContext: () => context,
+ get currentTime() {
+ return state.time;
+ },
+ isPlaying: true,
+ } as unknown as MasterTimelineClock;
+ return {
+ graph: new RealtimeAudioGraph(clock),
+ state,
+ context,
+ sources,
+ nodes,
+ panners,
+ gains,
+ };
+}
+function schedule(
+ id: string,
+ overrides: Partial<AudioClipSchedule> = {},
+): AudioClipSchedule {
+ return {
+ clipId: id,
+ trackId: "root",
+ audioBuffer: { duration: 20 } as AudioBuffer,
+ startTime: 0,
+ endTime: 5,
+ mediaOffset: 0,
+ volume: 1,
+ volumeAutomation: [],
+ pan: 0,
+ effects: [],
+ speed: 1,
+ ...overrides,
+ };
+}
+afterEach(() => {
+ vi.restoreAllMocks();
+});
+
+const SR = 8000;
+const REGION: SpectralRegion = { id: "r", mode: "attenuate", startTime: 0, endTime: 2, lowHz: 400, highHz: 600, gainDb: -30, enabled: true };
+
+const tone = (seconds: number): AudioBuffer => {
+ const data = Float32Array.from({ length: SR * seconds }, (_, i) => 0.5 * Math.sin((2 * Math.PI * 500 * i) / SR));
+ return { numberOfChannels: 1, sampleRate: SR, length: data.length, duration: seconds, getChannelData: () => data } as unknown as AudioBuffer;
+};
+const flush = () => new Promise<void>((resolve) => setTimeout(resolve, 0));
+
+/** A backend whose jobs finish when the test says so; it runs the real DSP. */
+const manualBackend = () => {
+ const jobs: Array<() => void> = [];
+ const repair = vi.fn(
+ (channels: Float32Array[], sampleRate: number, regions: SpectralRegion[]) =>
+ new Promise<Float32Array[]>((resolve) => jobs.push(() => resolve(applySpectralRegions(channels, sampleRate, regions)))),
+ );
+ const backend: SpectralBackend = { repair, load: async () => undefined, view: async () => { throw new Error("unused"); }, drop: async () => undefined };
+ return { backend, jobs, repair };
+};
+
+const peakOf = (buffer: AudioBuffer): number => Math.max(...Array.from(buffer.getChannelData(0).subarray(2000, 6000), Math.abs));
+
+describe("spectral repair in the realtime graph", () => {
+ it("plays the clip at once, then swaps in the repaired source and never plays a clip effect for it", async () => {
+ const { graph, sources } = fixture();
+ const { backend, jobs, repair } = manualBackend();
+ graph.setSpectralBackend(backend);
+ (graph as unknown as { isPlaying: boolean }).isPlaying = true;
+ const audioBuffer = tone(2);
+ const effects = [createSpectralRepairEffect("sr", [REGION])];
+ graph.scheduleClip(schedule("c", { audioBuffer, endTime: 2, effects }));
+ expect(sources).toHaveLength(1);
+ expect(sources[0].buffer).toBe(audioBuffer);
+ expect(repair).toHaveBeenCalledTimes(1);
+ // The same range scheduled again joins the running job.
+ graph.scheduleClip(schedule("c2", { audioBuffer, endTime: 2, effects }));
+ expect(repair).toHaveBeenCalledTimes(1);
+
+ jobs[0]();
+ await flush();
+ expect(sources[0].stop).toHaveBeenCalled();
+ expect(sources).toHaveLength(4);
+ const repaired = sources[2].buffer!;
+ expect(repaired).not.toBe(audioBuffer);
+ expect(peakOf(repaired)).toBeLessThan(peakOf(audioBuffer) * 0.1);
+ expect(sources[3].buffer).toBe(repaired);
+
+ // Later schedules use the cache at once.
+ graph.scheduleClip(schedule("c3", { audioBuffer, endTime: 2, effects }));
+ expect(sources[4].buffer).toBe(repaired);
+ expect(repair).toHaveBeenCalledTimes(1);
+ graph.dispose();
+ });
+
+ it("leaves clips without active regions untouched and does not start a job", () => {
+ const { graph, sources } = fixture();
+ const { backend, repair } = manualBackend();
+ graph.setSpectralBackend(backend);
+ const audioBuffer = tone(2);
+ graph.scheduleClip(schedule("plain", { audioBuffer, endTime: 2, effects: [createSpectralRepairEffect("sr", [])] }));
+ graph.scheduleClip(schedule("off", { audioBuffer, endTime: 2, effects: [{ ...createSpectralRepairEffect("sr2", [REGION]), enabled: false }] }));
+ expect(sources).toHaveLength(2);
+ expect(sources.every((source) => source.buffer === audioBuffer)).toBe(true);
+ expect(repair).not.toHaveBeenCalled();
+ graph.dispose();
+ });
+
+ it("keeps playing the original when the repair fails", async () => {
+ const { graph, sources } = fixture();
+ const backend: SpectralBackend = { repair: () => Promise.reject(new Error("boom")), load: async () => undefined, view: async () => { throw new Error("x"); }, drop: async () => undefined };
+ graph.setSpectralBackend(backend);
+ (graph as unknown as { isPlaying: boolean }).isPlaying = true;
+ const audioBuffer = tone(2);
+ graph.scheduleClip(schedule("c", { audioBuffer, endTime: 2, effects: [createSpectralRepairEffect("sr", [REGION])] }));
+ await flush();
+ expect(sources).toHaveLength(1);
+ expect(sources[0].buffer).toBe(audioBuffer);
+ graph.dispose();
+ });
+});
diff --git a/packages/core/src/audio/realtime-audio-graph.ts b/packages/core/src/audio/realtime-audio-graph.ts
index e251d6b4..04372a24 100644
--- a/packages/core/src/audio/realtime-audio-graph.ts
+++ b/packages/core/src/audio/realtime-audio-graph.ts
@@ -16,6 +16,9 @@ import { schedulePanAutomationOnParam } from "./clip-pan-automation";
import { shouldPreservePitch } from "./time-stretch";
import { SCRUB_GRAIN_SECONDS, SCRUB_MAX_GRAINS, planScrubGrains } from "./scrub-grain";
import { StretchCache, getSharedStretchCache, type StretchRequest, type StretchRunner } from "./stretch-cache";
+import { SpectralRepairCache, getSharedSpectralRepairCache, type SpectralRepairRequest } from "./spectral/spectral-repair-cache";
+import { SPECTRAL_REPAIR_EFFECT_TYPE, getSpectralRepairRegions, spectralRegionsKey } from "./spectral/spectral-regions";
+import type { SpectralBackend } from "./spectral/spectral-worker-client";
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";
@@ -75,6 +78,8 @@ interface ScheduledSource {
stretched: boolean;
/** Fades the source out over `seconds` and detaches it from the track (used to swap it for a rebuilt one). */
retire: (seconds: number) => void;
+ /** Spectral repair: the original schedule while the source plays the unrepaired audio, until the cached repair is ready. */
+ spectralWait?: AudioClipSchedule;
}
/** Click-free hand-over between a resampled source and its pitch-preserving replacement. */
@@ -955,7 +960,7 @@ export class RealtimeAudioGraph {
const wanted = this.stretchRequestFor(scheduled.schedule);
if (!wanted || wanted.speed !== request.speed || Math.abs(wanted.start - request.start) > 1e-4 || Math.abs(wanted.end - request.end) > 1e-4) continue;
scheduled.retire(STRETCH_SWAP_FADE_SECONDS);
- rebuild.push(scheduled.schedule);
+ rebuild.push(scheduled.spectralWait ?? scheduled.schedule);
}
}
this.scheduleBatch(() => { for (const schedule of rebuild) this.scheduleClip(schedule, { fadeInSeconds: STRETCH_SWAP_FADE_SECONDS }); });
@@ -994,8 +999,83 @@ export class RealtimeAudioGraph {
return { ...rest, audioBuffer: mapAudioBuffer(this.audioContext, schedule.audioBuffer, channelMap) };
}
+ private spectralCache: SpectralRepairCache | null = null;
+ private spectralBackend: SpectralBackend | undefined;
+ private spectralUnsubscribe: (() => void) | null = null;
+
+ /** Test / host hook: replaces where spectral repairs are computed (default: a Web Worker). */
+ setSpectralBackend(backend: SpectralBackend | undefined): void {
+ this.spectralBackend = backend;
+ this.spectralUnsubscribe?.();
+ this.spectralUnsubscribe = null;
+ this.spectralCache = null;
+ }
+
+ private getSpectralCache(): SpectralRepairCache {
+ if (!this.spectralCache) {
+ const makeBuffer = (channels: Float32Array[], sampleRate: number): AudioBuffer => {
+ const out = this.audioContext.createBuffer(channels.length, Math.max(1, channels[0]?.length ?? 1), sampleRate);
+ channels.forEach((data, c) => out.getChannelData(c).set(data));
+ return out;
+ };
+ // An injected backend gets a private cache; otherwise the process-wide one (shared with the export mixdown).
+ this.spectralCache = this.spectralBackend
+ ? new SpectralRepairCache({ backend: this.spectralBackend, makeBuffer })
+ : getSharedSpectralRepairCache(makeBuffer);
+ this.spectralUnsubscribe = this.spectralCache.onReady((request) => this.swapToSpectral(request));
+ }
+ return this.spectralCache;
+ }
+
+ /**
+ * The schedule with the clip's spectral repair applied to its source buffer (regions are source-time, so this
+ * happens before the channel map, stretch and offsets). The repair is computed once off the main thread; until it
+ * is ready the clip plays the unrepaired audio and `swapToSpectral` replaces it.
+ */
+ private withSpectralRepair(schedule: AudioClipSchedule): { schedule: AudioClipSchedule; waiting: boolean } {
+ const regions = getSpectralRepairRegions(schedule.effects);
+ if (regions.length === 0) return { schedule, waiting: false };
+ const effects = schedule.effects.filter((effect) => effect.type !== SPECTRAL_REPAIR_EFFECT_TYPE);
+ const request: SpectralRepairRequest = { buffer: schedule.audioBuffer, regions };
+ const cache = this.getSpectralCache();
+ const ready = cache.peek(request);
+ if (ready) return { schedule: { ...schedule, audioBuffer: ready, effects }, waiting: false };
+ void cache.request(request);
+ return { schedule: { ...schedule, effects }, waiting: true };
+ }
+
+ /**
+ * The source buffer with these clip effects' spectral repair applied (awaiting the cached, off-thread job) and the
+ * effects without the spectral entry, so a preview can schedule the repaired audio straight away. `key` identifies the
+ * regions that were applied ("" when none, or when the repair could not be computed and the graph falls back to the original).
+ */
+ async prepareSpectralRepair(buffer: AudioBuffer, effects: readonly Effect[]): Promise<{ buffer: AudioBuffer; effects: Effect[]; key: string }> {
+ const regions = getSpectralRepairRegions(effects);
+ if (regions.length === 0) return { buffer, effects: [...effects], key: "" };
+ const repaired = await this.getSpectralCache().request({ buffer, regions });
+ if (!repaired) return { buffer, effects: [...effects], key: "" };
+ return { buffer: repaired, effects: effects.filter((effect) => effect.type !== SPECTRAL_REPAIR_EFFECT_TYPE), key: spectralRegionsKey(regions) };
+ }
+
+ /** A repair finished: rebuild every source still playing that clip unrepaired, with a short crossfade. */
+ private swapToSpectral(request: SpectralRepairRequest): void {
+ if (!this.isPlaying || !this.masterClock.isPlaying) return;
+ const key = spectralRegionsKey(request.regions);
+ const rebuild: AudioClipSchedule[] = [];
+ for (const sources of this.scheduledSources.values()) {
+ for (const scheduled of [...sources]) {
+ const waiting = scheduled.spectralWait;
+ if (!waiting || waiting.audioBuffer !== request.buffer || spectralRegionsKey(getSpectralRepairRegions(waiting.effects)) !== key) continue;
+ scheduled.retire(STRETCH_SWAP_FADE_SECONDS);
+ rebuild.push(waiting);
+ }
+ }
+ this.scheduleBatch(() => { for (const schedule of rebuild) this.scheduleClip(schedule, { fadeInSeconds: STRETCH_SWAP_FADE_SECONDS }); });
+ }
+
scheduleClip(rawSchedule: AudioClipSchedule, options: { fadeInSeconds?: number } = {}): void {
- const schedule = this.withChannelMap(rawSchedule);
+ const spectral = this.withSpectralRepair(rawSchedule);
+ const schedule = this.withChannelMap(spectral.schedule);
if (!this.trackNodes.has(schedule.trackId)) {
this.createTrack({ trackId: schedule.trackId, volume: 1, pan: 0, muted: false, solo: false, effects: [] });
}
@@ -1006,7 +1086,7 @@ export class RealtimeAudioGraph {
const stretched = stretchRequest ? this.getStretchedBuffer(stretchRequest) : null;
const clipBuffer = stretched ?? schedule.audioBuffer;
const enabledEffects = schedule.effects.filter((effect) => effect.enabled);
- const processingEffects = enabledEffects.filter((effect) => effect.type !== "pan" && effect.type !== "fadeIn" && effect.type !== "fadeOut");
+ const processingEffects = enabledEffects.filter((effect) => effect.type !== "pan" && effect.type !== "fadeIn" && effect.type !== "fadeOut" && effect.type !== SPECTRAL_REPAIR_EFFECT_TYPE);
const chain = processingEffects.length > 0 ? this.buildEffectChain(processingEffects, Math.max(1, clipBuffer.numberOfChannels)) : null;
const source = this.audioContext.createBufferSource();
source.buffer = clipBuffer;
@@ -1097,7 +1177,7 @@ export class RealtimeAudioGraph {
source.onended = onSourceEnded;
};
scheduled = { clipId: schedule.clipId, trackId: schedule.trackId, panner, source, startedAt: schedule.startTime, duration: playbackDuration, release,
- schedule, stretched: !!stretched, retire };
+ schedule, stretched: !!stretched, retire, ...(spectral.waiting ? { spectralWait: rawSchedule } : {}) };
const sources = this.scheduledSources.get(schedule.trackId) ?? [];
sources.push(scheduled); this.scheduledSources.set(schedule.trackId, sources);
source.onended = onSourceEnded;
@@ -1280,6 +1360,9 @@ export class RealtimeAudioGraph {
this.stretchUnsubscribe?.();
this.stretchUnsubscribe = null;
this.stretchCache = null;
+ this.spectralUnsubscribe?.();
+ this.spectralUnsubscribe = null;
+ this.spectralCache = null;
this.stopScheduler();
for (const trackId of Array.from(this.trackNodes.keys())) {
this.removeTrack(trackId);
diff --git a/packages/core/src/audio/spectral/index.ts b/packages/core/src/audio/spectral/index.ts
new file mode 100644
index 00000000..4fc413cb
--- /dev/null
+++ b/packages/core/src/audio/spectral/index.ts
@@ -0,0 +1,6 @@
+export * from "./spectral-regions";
+export * from "./spectral-dsp";
+export * from "./spectral-repair-cache";
+export * from "./spectral-edit";
+export * from "./spectral-worker-client";
+export type { SpectralRequest, SpectralResponse } from "./spectral-worker-core";
diff --git a/packages/core/src/audio/spectral/spectral-dsp.test.ts b/packages/core/src/audio/spectral/spectral-dsp.test.ts
new file mode 100644
index 00000000..40d07224
--- /dev/null
+++ b/packages/core/src/audio/spectral/spectral-dsp.test.ts
@@ -0,0 +1,212 @@
+import { describe, expect, it } from "vitest";
+import {
+ applySpectralRegions,
+ applySpectralRegionsToChannel,
+ computeSpectralView,
+ getStftPlan,
+ stftForward,
+ stftInverse,
+} from "./spectral-dsp";
+import { sanitizeSpectralRegions, spectralRegionsKey, type SpectralRegion } from "./spectral-regions";
+
+const SR = 48000;
+
+const region = (patch: Partial<SpectralRegion> & Pick<SpectralRegion, "mode">): SpectralRegion => ({
+ id: "r",
+ startTime: 0,
+ endTime: 10,
+ lowHz: 0,
+ highHz: SR / 2,
+ gainDb: -12,
+ enabled: true,
+ ...patch,
+});
+
+function tones(seconds: number, parts: Array<[number, number]>, extra?: (i: number) => number): Float32Array {
+ const out = new Float32Array(Math.round(seconds * SR));
+ for (let i = 0; i < out.length; i += 1) {
+ let v = extra ? extra(i) : 0;
+ for (const [f, a] of parts) v += a * Math.sin((2 * Math.PI * f * i) / SR + f);
+ out[i] = v;
+ }
+ return out;
+}
+
+/** Amplitude of the sinusoid at `freq` over [from, to) seconds (single-bin DFT). */
+function amp(x: Float32Array, freq: number, from: number, to: number): number {
+ const a = Math.floor(from * SR);
+ const b = Math.floor(to * SR);
+ let re = 0;
+ let im = 0;
+ for (let i = a; i < b; i += 1) {
+ const w = (2 * Math.PI * freq * i) / SR;
+ re += x[i] * Math.cos(w);
+ im -= x[i] * Math.sin(w);
+ }
+ return (2 * Math.hypot(re, im)) / (b - a);
+}
+const db = (a: number, b: number) => 20 * Math.log10(a / b);
+
+describe("STFT / ISTFT", () => {
+ it("reconstructs a signal perfectly when no frame is modified", () => {
+ let seed = 7;
+ for (const length of [1, 100, 2047, 2048, 5000, 12345]) {
+ const x = new Float32Array(length);
+ for (let i = 0; i < length; i += 1) {
+ seed = (seed * 1664525 + 1013904223) >>> 0;
+ x[i] = (seed / 4294967296 - 0.5) * 1.6;
+ }
+ const y = stftInverse(stftForward(x), length);
+ let worst = 0;
+ for (let i = 0; i < length; i += 1) worst = Math.max(worst, Math.abs(y[i] - x[i]));
+ expect(worst, `length ${length}`).toBeLessThan(2e-5);
+ }
+ });
+
+ it("reconstructs a long tonal signal, edges included, to better than -100 dB", () => {
+ const x = tones(1.5, [[440, 0.4], [2500, 0.2]]);
+ const y = stftInverse(stftForward(x), x.length);
+ let err = 0;
+ let energy = 0;
+ for (let i = 0; i < x.length; i += 1) {
+ err += (y[i] - x[i]) ** 2;
+ energy += x[i] ** 2;
+ }
+ expect(10 * Math.log10(err / energy)).toBeLessThan(-100);
+ });
+
+ it("uses a squared-window overlap sum of 1.5 (the constant the exact reconstruction relies on)", () => {
+ expect(getStftPlan().norm).toBeCloseTo(1.5, 6);
+ });
+});
+
+describe("applySpectralRegions", () => {
+ it("returns the input untouched without active regions, and an unchanged copy for 0 dB", () => {
+ const x = tones(1, [[1000, 0.3]]);
+ expect(applySpectralRegionsToChannel(x, SR, [])).toBe(x);
+ expect(applySpectralRegionsToChannel(x, SR, [region({ mode: "remove", enabled: false })])).toBe(x);
+ const same = applySpectralRegionsToChannel(x, SR, [region({ mode: "attenuate", gainDb: 0, lowHz: 500, highHz: 2000 })]);
+ expect(same).not.toBe(x);
+ let worst = 0;
+ for (let i = 0; i < x.length; i += 1) worst = Math.max(worst, Math.abs(same[i] - x[i]));
+ expect(worst).toBeLessThan(1e-6);
+ });
+
+ it("removes a tone with a region covering it and leaves the other tones within tolerance", () => {
+ const x = tones(3, [[440, 0.3], [1000, 0.3], [3000, 0.3]]);
+ const y = applySpectralRegionsToChannel(x, SR, [region({ mode: "remove", startTime: 0, endTime: 3, lowHz: 900, highHz: 1100 })]);
+ expect(db(amp(x, 1000, 0.5, 2.5), amp(y, 1000, 0.5, 2.5)), "1 kHz tone removed").toBeGreaterThan(30);
+ expect(Math.abs(db(amp(y, 440, 0.5, 2.5), amp(x, 440, 0.5, 2.5))), "440 Hz").toBeLessThan(0.05);
+ expect(Math.abs(db(amp(y, 3000, 0.5, 2.5), amp(x, 3000, 0.5, 2.5))), "3 kHz").toBeLessThan(0.05);
+ });
+
+ it("removes a tone only inside the region's time span", () => {
+ const x = tones(3, [[1000, 0.3], [440, 0.2]]);
+ const y = applySpectralRegionsToChannel(x, SR, [region({ mode: "remove", startTime: 1, endTime: 2, lowHz: 900, highHz: 1100 })]);
+ expect(db(amp(x, 1000, 1.15, 1.85), amp(y, 1000, 1.15, 1.85)), "inside").toBeGreaterThan(25);
+ for (const [from, to] of [[0.1, 0.8], [2.2, 2.9]] as const) {
+ expect(Math.abs(db(amp(y, 1000, from, to), amp(x, 1000, from, to))), `outside ${from}-${to}`).toBeLessThan(0.1);
+ }
+ expect(Math.abs(db(amp(y, 440, 1.15, 1.85), amp(x, 440, 1.15, 1.85)))).toBeLessThan(0.05);
+ });
+
+ it("interpolates a click from the surrounding frames", () => {
+ const x = tones(2, [[500, 0.2]], (i) => (i === SR ? 0.8 : 0));
+ const before = Math.max(...Array.from(x.subarray(SR - 480, SR + 480), Math.abs));
+ expect(before).toBeGreaterThan(0.65);
+ const y = applySpectralRegionsToChannel(x, SR, [region({ mode: "remove", startTime: 0.99, endTime: 1.01, lowHz: 0, highHz: SR / 2 })]);
+ const after = Math.max(...Array.from(y.subarray(SR - 480, SR + 480), Math.abs));
+ expect(after).toBeLessThan(0.3);
+ expect(Math.abs(db(amp(y, 500, 0.2, 0.9), amp(x, 500, 0.2, 0.9)))).toBeLessThan(0.05);
+ });
+
+ it("attenuates a tone by exactly N dB", () => {
+ const x = tones(3, [[1000, 0.5], [5000, 0.25]]);
+ for (const n of [3, 6, 12, 24, 40]) {
+ const y = applySpectralRegionsToChannel(x, SR, [region({ mode: "attenuate", startTime: 0.5, endTime: 2.5, lowHz: 800, highHz: 1200, gainDb: -n })]);
+ const measured = db(amp(x, 1000, 1, 2), amp(y, 1000, 1, 2));
+ expect(measured, `-${n} dB`).toBeGreaterThan(n - 0.1);
+ expect(measured, `-${n} dB`).toBeLessThan(n + 0.1);
+ expect(Math.abs(db(amp(y, 5000, 1, 2), amp(x, 5000, 1, 2))), "5 kHz untouched").toBeLessThan(0.01);
+ expect(Math.abs(db(amp(y, 1000, 0.05, 0.3), amp(x, 1000, 0.05, 0.3))), "before the region").toBeLessThan(0.02);
+ }
+ });
+
+ it("a frequency-band marquee over the whole source attenuates from the first to the last sample", () => {
+ const x = tones(2, [[2000, 0.4], [300, 0.4]]);
+ const y = applySpectralRegionsToChannel(x, SR, [region({ mode: "attenuate", startTime: 0, endTime: 2, lowHz: 1500, highHz: 2500, gainDb: -20 })]);
+ for (const [from, to] of [[0.01, 0.15], [1.85, 1.99]] as const) {
+ expect(db(amp(x, 2000, from, to), amp(y, 2000, from, to)), `${from}-${to}`).toBeGreaterThan(17);
+ expect(Math.abs(db(amp(y, 300, from, to), amp(x, 300, from, to)))).toBeLessThan(0.1);
+ }
+ });
+
+ it("is deterministic and processes every channel", () => {
+ const left = tones(1, [[800, 0.3], [2000, 0.2]]);
+ const right = tones(1, [[800, 0.1], [2000, 0.3]]);
+ const regions = [region({ mode: "remove", startTime: 0.2, endTime: 0.8, lowHz: 700, highHz: 900 })];
+ const a = applySpectralRegions([left, right], SR, regions);
+ const b = applySpectralRegions([left, right], SR, regions);
+ expect(Array.from(a[0])).toEqual(Array.from(b[0]));
+ expect(Array.from(a[1])).toEqual(Array.from(b[1]));
+ expect(db(amp(left, 800, 0.35, 0.65), amp(a[0], 800, 0.35, 0.65))).toBeGreaterThan(25);
+ expect(db(amp(right, 800, 0.35, 0.65), amp(a[1], 800, 0.35, 0.65))).toBeGreaterThan(25);
+ expect(Math.abs(db(amp(a[1], 2000, 0.35, 0.65), amp(right, 2000, 0.35, 0.65)))).toBeLessThan(0.05);
+ });
+
+ it("applies overlapping regions in order", () => {
+ const x = tones(2, [[1000, 0.4]]);
+ const y = applySpectralRegionsToChannel(x, SR, [
+ region({ mode: "attenuate", startTime: 0, endTime: 2, lowHz: 800, highHz: 1200, gainDb: -6, id: "a" }),
+ region({ mode: "attenuate", startTime: 0, endTime: 2, lowHz: 800, highHz: 1200, gainDb: -6, id: "b" }),
+ ]);
+ expect(db(amp(x, 1000, 0.5, 1.5), amp(y, 1000, 0.5, 1.5))).toBeGreaterThan(11.8);
+ });
+});
+
+describe("spectral regions model", () => {
+ it("sanitises untrusted input", () => {
+ const out = sanitizeSpectralRegions([
+ { mode: "attenuate", startTime: 2, endTime: 1, lowHz: 5000, highHz: 100, gainDb: 5, id: "a" },
+ { mode: "remove", startTime: 0, endTime: 1, lowHz: 100, highHz: 200 },
+ { mode: "bogus", startTime: 0, endTime: 1, lowHz: 100, highHz: 200 },
+ { mode: "remove", startTime: 0, endTime: 0, lowHz: 100, highHz: 200 },
+ { mode: "remove", startTime: 0, endTime: 1, lowHz: NaN, highHz: 200 },
+ null,
+ ]);
+ expect(out).toHaveLength(2);
+ expect(out[0]).toMatchObject({ id: "a", startTime: 1, endTime: 2, lowHz: 100, highHz: 5000, gainDb: 0, enabled: true });
+ expect(sanitizeSpectralRegions("nope")).toEqual([]);
+ });
+
+ it("keys only what changes the audio", () => {
+ const a = region({ mode: "remove", id: "x" });
+ expect(spectralRegionsKey([a])).toBe(spectralRegionsKey([{ ...a, id: "y" }]));
+ expect(spectralRegionsKey([{ ...a, enabled: false }])).toBe("");
+ expect(spectralRegionsKey([a])).not.toBe(spectralRegionsKey([{ ...a, highHz: 1000 }]));
+ });
+});
+
+describe("computeSpectralView", () => {
+ it("puts a full-scale tone at its frequency on an absolute dBFS scale", () => {
+ const x = tones(1, [[3000, 1]]);
+ const view = computeSpectralView([x], SR, { maxFrames: 100 });
+ const column = Math.floor(view.frames / 2);
+ let best = 0;
+ for (let k = 0; k < view.bins; k += 1) if (view.data[column * view.bins + k] > view.data[column * view.bins + best]) best = k;
+ expect(Math.abs((best * SR) / view.fftSize - 3000)).toBeLessThan(SR / view.fftSize);
+ expect(view.data[column * view.bins + best]).toBeGreaterThan(245);
+ const half = computeSpectralView([tones(1, [[3000, 0.5]])], SR, { maxFrames: 100 });
+ // 6 dB lower over a 100 dB range is about 15 levels.
+ expect(view.data[column * view.bins + best] - half.data[column * half.bins + best]).toBeGreaterThan(12);
+ expect(view.data[column * view.bins + best] - half.data[column * half.bins + best]).toBeLessThan(18);
+ });
+
+ it("zooms into a time window", () => {
+ const x = tones(2, [[1000, 0.5]]);
+ const view = computeSpectralView([x], SR, { startTime: 0.5, endTime: 0.75, maxFrames: 50 });
+ expect(view.startTime).toBeCloseTo(0.5, 4);
+ expect(view.endTime).toBeCloseTo(0.75, 4);
+ expect(view.frames).toBeLessThanOrEqual(50);
+ });
+});
diff --git a/packages/core/src/audio/spectral/spectral-dsp.ts b/packages/core/src/audio/spectral/spectral-dsp.ts
new file mode 100644
index 00000000..2fd57ed5
--- /dev/null
+++ b/packages/core/src/audio/spectral/spectral-dsp.ts
@@ -0,0 +1,307 @@
+/**
+ * Spectral editing DSP: STFT / inverse STFT, region attenuation and removal, and the spectrogram a
+ * view draws.
+ *
+ * Analysis and synthesis use a periodic Hann window at 75 % overlap (2048 / 512). With the squared
+ * window summing to a constant (1.5), the inverse STFT reconstructs the input to float precision.
+ * Region edits do not rebuild the signal from modified frames. Each edit computes only the frames its
+ * region touches and ADDS the (modified - original) frame difference back with the synthesis window,
+ * so untouched audio is bit-identical, an edit that changes nothing changes nothing, and a long clip
+ * with one small region costs a handful of FFTs. Everything here is pure and deterministic: the
+ * preview, the export mixdown and the unit tests run this same code on the same samples.
+ */
+import { FFT } from "../fft";
+import { activeSpectralRegions, type SpectralRegion } from "./spectral-regions";
+
+export const SPECTRAL_FFT_SIZE = 2048;
+export const SPECTRAL_HOP = 512;
+/** Bins between a removed band and the bins its fill is interpolated from (clears the Hann main lobe). */
+const REF_BIN_GAP = 4;
+/** Frames between a removed time span and the frames its fill is interpolated from (clears the window overlap). */
+const REF_FRAME_GAP = 3;
+/** Attenuation fades over this many bins outside the selected band. */
+const FREQ_FEATHER_BINS = 3;
+
+export interface StftPlan {
+ readonly size: number;
+ readonly hop: number;
+ readonly fft: FFT;
+ readonly window: Float32Array;
+ /** Sum of the squared window over the frames that overlap any sample (constant for Hann at 75 % overlap). */
+ readonly norm: number;
+}
+
+const plans = new Map<string, StftPlan>();
+
+export function getStftPlan(size = SPECTRAL_FFT_SIZE, hop = SPECTRAL_HOP): StftPlan {
+ const key = `${size}:${hop}`;
+ const cached = plans.get(key);
+ if (cached) return cached;
+ const window = new Float32Array(size);
+ for (let i = 0; i < size; i += 1) window[i] = 0.5 - 0.5 * Math.cos((2 * Math.PI * i) / size);
+ let norm = 0;
+ for (let at = 0; at < size; at += hop) norm += window[at] * window[at];
+ const plan: StftPlan = { size, hop, fft: new FFT(size), window, norm };
+ plans.set(key, plan);
+ return plan;
+}
+
+/** Frame indices m whose window [m*hop, m*hop + size) overlaps a signal of `length` samples. */
+export function stftFrameRange(length: number, plan: StftPlan): { first: number; last: number } {
+ return { first: -(plan.size / plan.hop - 1), last: Math.max(-(plan.size / plan.hop - 1), Math.floor((length - 1) / plan.hop)) };
+}
+
+function analyseFrame(plan: StftPlan, signal: Float32Array, start: number, scratch: Float32Array): { real: Float32Array; imag: Float32Array } {
+ const { size, window } = plan;
+ for (let i = 0; i < size; i += 1) {
+ const at = start + i;
+ scratch[i] = at >= 0 && at < signal.length ? signal[at] * window[i] : 0;
+ }
+ return plan.fft.forward(scratch);
+}
+
+export interface StftFrames {
+ /** Index of the first frame (negative: frames that start before the signal). */
+ readonly first: number;
+ readonly real: Float32Array[];
+ readonly imag: Float32Array[];
+}
+
+/** Full STFT of a signal (every frame, full spectrum). */
+export function stftForward(signal: Float32Array, plan: StftPlan = getStftPlan()): StftFrames {
+ const { first, last } = stftFrameRange(signal.length, plan);
+ const scratch = new Float32Array(plan.size);
+ const real: Float32Array[] = [];
+ const imag: Float32Array[] = [];
+ for (let m = first; m <= last; m += 1) {
+ const spectrum = analyseFrame(plan, signal, m * plan.hop, scratch);
+ real.push(spectrum.real);
+ imag.push(spectrum.imag);
+ }
+ return { first, real, imag };
+}
+
+/** Weighted overlap-add inverse of {@link stftForward}: perfect reconstruction when the frames are unmodified. */
+export function stftInverse(frames: StftFrames, length: number, plan: StftPlan = getStftPlan()): Float32Array {
+ const out = new Float32Array(length);
+ const { size, hop, window, norm } = plan;
+ for (let f = 0; f < frames.real.length; f += 1) {
+ const start = (frames.first + f) * hop;
+ const time = plan.fft.inverse(frames.real[f], frames.imag[f]);
+ for (let i = 0; i < size; i += 1) {
+ const at = start + i;
+ if (at >= 0 && at < length) out[at] += (time[i] * window[i]) / norm;
+ }
+ }
+ return out;
+}
+
+/** Deterministic pseudo-random phase in [0, 1) for a (bin, frame, channel): fills are noise-like but identical on every run. */
+function hashUnit(k: number, m: number, channel: number): number {
+ let h = (Math.imul(k + 1, 0x9e3779b1) ^ Math.imul(m + 4096, 0x85ebca6b) ^ Math.imul(channel + 1, 0xc2b2ae35)) >>> 0;
+ h ^= h >>> 15;
+ h = Math.imul(h, 0x2c1b3c6d);
+ h ^= h >>> 12;
+ h = Math.imul(h, 0x297a2d39);
+ h ^= h >>> 15;
+ return (h >>> 0) / 4294967296;
+}
+
+const smooth = (x: number): number => {
+ const t = Math.max(0, Math.min(1, x));
+ return t * t * (3 - 2 * t);
+};
+
+function applyRegion(work: Float32Array, sampleRate: number, region: SpectralRegion, plan: StftPlan, channel: number): void {
+ const { size, hop, window, norm } = plan;
+ const half = size / 2;
+ const nyquist = sampleRate / 2;
+ if (region.lowHz >= nyquist || work.length === 0) return;
+ const binHz = sampleRate / size;
+ const kLo = Math.max(0, Math.min(half, Math.floor(region.lowHz / binHz)));
+ const kHi = Math.max(kLo, Math.min(half, Math.ceil(Math.min(region.highHz, nyquist) / binHz)));
+ const ramp = hop / sampleRate;
+ const range = stftFrameRange(work.length, plan);
+ const frameCentre = (m: number) => (m * hop + half) / sampleRate;
+ const timeWeight = (m: number): number => {
+ const c = frameCentre(m);
+ return smooth((c - region.startTime) / ramp + 0.5) * smooth((region.endTime - c) / ramp + 0.5);
+ };
+ let mFirst = Math.max(range.first, Math.ceil(((region.startTime - ramp / 2) * sampleRate - half) / hop));
+ let mLast = Math.min(range.last, Math.floor(((region.endTime + ramp / 2) * sampleRate - half) / hop));
+ while (mFirst <= mLast && timeWeight(mFirst) <= 1e-6) mFirst += 1;
+ while (mLast >= mFirst && timeWeight(mLast) <= 1e-6) mLast -= 1;
+ if (mLast < mFirst) return;
+
+ const remove = region.mode === "remove";
+ const gain = Math.pow(10, region.gainDb / 20);
+ const scratch = new Float32Array(size);
+ const dr = new Float32Array(size);
+ const di = new Float32Array(size);
+
+ // What a removed region is filled from: neighbouring bins in the same frame when the region is
+ // narrower in frequency than in time (a hum band), otherwise the neighbouring frames (a click).
+ const lowRef = kLo - REF_BIN_GAP >= 0 ? kLo - REF_BIN_GAP : -1;
+ const highRef = kHi + REF_BIN_GAP <= half ? kHi + REF_BIN_GAP : -1;
+ const binCount = kHi - kLo + 1;
+ const frameCount = mLast - mFirst + 1;
+ const frameRefA = mFirst - REF_FRAME_GAP >= range.first ? mFirst - REF_FRAME_GAP : null;
+ const frameRefB = mLast + REF_FRAME_GAP <= range.last ? mLast + REF_FRAME_GAP : null;
+ const freqAxis = remove && binCount <= frameCount && (lowRef >= 0 || highRef >= 0);
+ let magA: Float32Array | null = null;
+ let magB: Float32Array | null = null;
+ if (remove && !freqAxis) {
+ const magnitudes = (m: number): Float32Array => {
+ const s = analyseFrame(plan, work, m * hop, scratch);
+ const out = new Float32Array(half + 1);
+ for (let k = 0; k <= half; k += 1) out[k] = Math.hypot(s.real[k], s.imag[k]);
+ return out;
+ };
+ if (frameRefA !== null) magA = magnitudes(frameRefA);
+ if (frameRefB !== null) magB = magnitudes(frameRefB);
+ }
+
+ const sampleStart = mFirst * hop;
+ const delta = new Float32Array((mLast - mFirst) * hop + size);
+ for (let m = mFirst; m <= mLast; m += 1) {
+ const weight = timeWeight(m);
+ if (weight <= 1e-6) continue;
+ const { real, imag } = analyseFrame(plan, work, m * hop, scratch);
+ dr.fill(0);
+ di.fill(0);
+ const put = (k: number, re: number, im: number) => {
+ dr[k] = re;
+ di[k] = im;
+ if (k > 0 && k < half) {
+ dr[size - k] = re;
+ di[size - k] = -im;
+ }
+ };
+ if (!remove) {
+ const from = Math.max(0, kLo - FREQ_FEATHER_BINS + 1);
+ const to = Math.min(half, kHi + FREQ_FEATHER_BINS - 1);
+ for (let k = from; k <= to; k += 1) {
+ const feather = k < kLo ? 1 - (kLo - k) / FREQ_FEATHER_BINS : k > kHi ? 1 - (k - kHi) / FREQ_FEATHER_BINS : 1;
+ const scale = weight * feather * (gain - 1);
+ const edge = k === 0 || k === half;
+ put(k, real[k] * scale, edge ? 0 : imag[k] * scale);
+ }
+ } else {
+ const along = frameRefA !== null && frameRefB !== null ? (m - frameRefA) / (frameRefB - frameRefA) : 0;
+ for (let k = kLo; k <= kHi; k += 1) {
+ let target = 0;
+ if (freqAxis) {
+ const a = lowRef >= 0 ? Math.hypot(real[lowRef], imag[lowRef]) : null;
+ const b = highRef >= 0 ? Math.hypot(real[highRef], imag[highRef]) : null;
+ target = a !== null && b !== null ? a + ((b - a) * (k - lowRef)) / (highRef - lowRef) : (a ?? b ?? 0);
+ } else if (magA && magB) target = magA[k] + (magB[k] - magA[k]) * along;
+ else target = (magA ?? magB)?.[k] ?? 0;
+ const phase = 2 * Math.PI * hashUnit(k, m, channel);
+ const edge = k === 0 || k === half;
+ const fillRe = edge ? target * (Math.cos(phase) >= 0 ? 1 : -1) : target * Math.cos(phase);
+ const fillIm = edge ? 0 : target * Math.sin(phase);
+ put(k, (fillRe - real[k]) * weight, edge ? 0 : (fillIm - imag[k]) * weight);
+ }
+ }
+ const time = plan.fft.inverse(dr, di);
+ const base = m * hop - sampleStart;
+ for (let i = 0; i < size; i += 1) delta[base + i] += time[i] * window[i];
+ }
+ for (let i = 0; i < delta.length; i += 1) {
+ const at = sampleStart + i;
+ if (at >= 0 && at < work.length) work[at] += delta[i] / norm;
+ }
+}
+
+/**
+ * Applies a region list to one channel and returns the repaired channel. With no active region the SAME
+ * array is returned (nothing is copied or changed); otherwise a new array. Regions apply in order, each
+ * one to the result of the previous, so an overlapping attenuation after a removal acts on the filled audio.
+ */
+export function applySpectralRegionsToChannel(
+ signal: Float32Array,
+ sampleRate: number,
+ regions: readonly SpectralRegion[],
+ channel = 0,
+): Float32Array {
+ const active = activeSpectralRegions(regions);
+ if (active.length === 0 || signal.length === 0) return signal;
+ const work = Float32Array.from(signal);
+ const plan = getStftPlan();
+ for (const region of active) applyRegion(work, sampleRate, region, plan, channel);
+ return work;
+}
+
+/** All channels of a clip's source; identical samples whether called in a worker, in the export engine or in a test. */
+export function applySpectralRegions(channels: readonly Float32Array[], sampleRate: number, regions: readonly SpectralRegion[]): Float32Array[] {
+ return channels.map((data, index) => applySpectralRegionsToChannel(data, sampleRate, regions, index));
+}
+
+/* ------------------------------------------------------------------ */
+/* Spectrogram for the view */
+/* ------------------------------------------------------------------ */
+
+export interface SpectralViewOptions {
+ /** Source-time window in seconds (default: the whole signal). */
+ readonly startTime?: number;
+ readonly endTime?: number;
+ /** FFT size of the display analysis (default 4096: finer low-frequency resolution than the edit STFT). */
+ readonly fftSize?: number;
+ /** Columns to produce at most (default 900). */
+ readonly maxFrames?: number;
+ /** Level mapped to the darkest colour, dBFS (default -100). 0 dBFS (a full-scale sine) is the brightest. */
+ readonly minDb?: number;
+}
+
+export interface SpectralView {
+ readonly frames: number;
+ /** Linear bins from 0 to Nyquist (exclusive). */
+ readonly bins: number;
+ readonly sampleRate: number;
+ readonly fftSize: number;
+ readonly startTime: number;
+ readonly endTime: number;
+ readonly minDb: number;
+ /** frames x bins, 0..255 over [minDb, 0] dBFS. */
+ readonly data: Uint8Array;
+}
+
+/** Magnitude spectrogram of the mono mix of `channels` over a window, on an absolute dBFS scale so colours do not shift with zoom or edits. */
+export function computeSpectralView(channels: readonly Float32Array[], sampleRate: number, options: SpectralViewOptions = {}): SpectralView {
+ const fftSize = options.fftSize ?? 4096;
+ const length = channels[0]?.length ?? 0;
+ const duration = length / sampleRate;
+ const startTime = Math.max(0, Math.min(duration, options.startTime ?? 0));
+ const endTime = Math.max(startTime, Math.min(duration, options.endTime ?? duration));
+ const minDb = options.minDb ?? -100;
+ const maxFrames = Math.max(1, Math.floor(options.maxFrames ?? 900));
+ const from = Math.floor(startTime * sampleRate);
+ const to = Math.max(from, Math.min(length, Math.ceil(endTime * sampleRate)));
+ const span = to - from;
+ const hop = Math.max(32, Math.min(fftSize, Math.floor(span / maxFrames) || 32));
+ const frames = Math.max(1, Math.min(maxFrames, Math.ceil(span / hop)));
+ const bins = fftSize / 2;
+ const fft = new FFT(fftSize);
+ const window = new Float32Array(fftSize);
+ for (let i = 0; i < fftSize; i += 1) window[i] = 0.5 - 0.5 * Math.cos((2 * Math.PI * i) / fftSize);
+ const reference = fftSize / 4; // peak bin magnitude of a full-scale sine under a Hann window
+ const data = new Uint8Array(frames * bins);
+ const frame = new Float32Array(fftSize);
+ const inv = 1 / Math.max(1, channels.length);
+ for (let f = 0; f < frames; f += 1) {
+ // Frame centred on its column: analysis windows extend past the view edges so zooming does not blank them.
+ const begin = from + Math.min(span, f * hop + Math.floor(hop / 2)) - fftSize / 2;
+ for (let i = 0; i < fftSize; i += 1) {
+ const at = begin + i;
+ let sum = 0;
+ if (at >= 0 && at < length) for (const channel of channels) sum += channel[at];
+ frame[i] = sum * inv * window[i];
+ }
+ const { real, imag } = fft.forward(frame);
+ for (let k = 0; k < bins; k += 1) {
+ const db = 20 * Math.log10(Math.hypot(real[k], imag[k]) / reference + 1e-12);
+ data[f * bins + k] = Math.max(0, Math.min(255, Math.round(((db - minDb) / -minDb) * 255)));
+ }
+ }
+ return { frames, bins, sampleRate, fftSize, startTime, endTime, minDb, data };
+}
diff --git a/packages/core/src/audio/spectral/spectral-edit.test.ts b/packages/core/src/audio/spectral/spectral-edit.test.ts
new file mode 100644
index 00000000..6da9f2fe
--- /dev/null
+++ b/packages/core/src/audio/spectral/spectral-edit.test.ts
@@ -0,0 +1,66 @@
+import { describe, expect, it } from "vitest";
+import { ActionExecutor } from "../../actions/action-executor";
+import type { Project } from "../../types";
+import { clipSpectralRegions, findSpectralRepairEffect, planSpectralRegionsAction } from "./spectral-edit";
+import { getSpectralRepairRegions, type SpectralRegion } from "./spectral-regions";
+
+const region = (id: string, over: Partial<SpectralRegion> = {}): SpectralRegion => ({
+ id, mode: "attenuate", startTime: 1, endTime: 2, lowHz: 500, highHz: 900, gainDb: -12, enabled: true, ...over,
+});
+
+const makeProject = () =>
+ ({
+ id: "p", name: "p", createdAt: 0, modifiedAt: 0,
+ settings: { width: 640, height: 360, frameRate: 30, sampleRate: 48000, channels: 2 },
+ mediaLibrary: { items: [] },
+ timeline: {
+ duration: 4, subtitles: [], markers: [],
+ tracks: [{
+ id: "t", name: "A", type: "audio", hidden: false, muted: false, solo: false, locked: false, transitions: [],
+ clips: [{
+ id: "clip", mediaId: "m", trackId: "t", startTime: 0, duration: 4, inPoint: 0, outPoint: 4, volume: 1, effects: [], audioEffects: [], keyframes: [],
+ transform: { position: { x: 0, y: 0 }, scale: { x: 1, y: 1 }, anchor: { x: 0.5, y: 0.5 }, rotation: 0, opacity: 1 },
+ }],
+ }],
+ },
+ }) as unknown as Project;
+
+describe("spectral region edits go through the undoable action system", () => {
+ it("add, change, remove: each is one history step and undo / redo restore the exact region list", async () => {
+ const project = makeProject();
+ const executor = new ActionExecutor();
+ const clip = () => project.timeline.tracks[0].clips[0];
+ let n = 0;
+ const commit = async (regions: SpectralRegion[]) => {
+ const action = planSpectralRegionsAction(clip(), regions, { actionId: `a${++n}`, effectId: "fx" });
+ expect(action).not.toBeNull();
+ expect((await executor.execute(action!, project)).success).toBe(true);
+ };
+ expect(planSpectralRegionsAction(clip(), [], { actionId: "x", effectId: "fx" })).toBeNull();
+
+ const one = [region("r1")];
+ await commit(one);
+ expect(clipSpectralRegions(clip())).toEqual(one);
+ expect(findSpectralRepairEffect(clip())?.type).toBe("spectralRepair");
+
+ const two = [...one, region("r2", { mode: "remove", startTime: 2, endTime: 2.5 })];
+ await commit(two);
+ expect(clipSpectralRegions(clip())).toHaveLength(2);
+ expect(planSpectralRegionsAction(clip(), two, { actionId: "same", effectId: "fx" })).toBeNull();
+
+ await commit([]);
+ expect(clip().audioEffects).toHaveLength(0);
+
+ expect((await executor.undo(project)).success).toBe(true);
+ expect(clipSpectralRegions(clip())).toEqual(clipSpectralRegions({ audioEffects: [{ id: "fx", type: "spectralRepair", enabled: true, params: { regions: two } }] }));
+ expect(clipSpectralRegions(clip())).toHaveLength(2);
+ expect((await executor.undo(project)).success).toBe(true);
+ expect(clipSpectralRegions(clip())).toEqual(one);
+ expect((await executor.undo(project)).success).toBe(true);
+ expect(clip().audioEffects).toHaveLength(0);
+ expect((await executor.redo(project)).success).toBe(true);
+ expect((await executor.redo(project)).success).toBe(true);
+ expect(clipSpectralRegions(clip())).toHaveLength(2);
+ expect(getSpectralRepairRegions(clip().audioEffects)).toHaveLength(2);
+ });
+});
diff --git a/packages/core/src/audio/spectral/spectral-edit.ts b/packages/core/src/audio/spectral/spectral-edit.ts
new file mode 100644
index 00000000..c82e9102
--- /dev/null
+++ b/packages/core/src/audio/spectral/spectral-edit.ts
@@ -0,0 +1,52 @@
+import type { Action } from "../../types/actions";
+import type { Clip, Effect } from "../../types/timeline";
+import {
+ SPECTRAL_REPAIR_EFFECT_TYPE,
+ createSpectralRepairEffect,
+ sanitizeSpectralRegions,
+ type SpectralRegion,
+} from "./spectral-regions";
+
+/** The clip's own spectral-repair effect (a clip carries at most one; its region list is the edit). */
+export const findSpectralRepairEffect = (clip: Pick<Clip, "audioEffects"> | undefined): Effect | undefined =>
+ (clip?.audioEffects ?? []).find((effect) => effect.type === SPECTRAL_REPAIR_EFFECT_TYPE);
+
+/** The regions currently stored on the clip (enabled or not). */
+export const clipSpectralRegions = (clip: Pick<Clip, "audioEffects"> | undefined): SpectralRegion[] =>
+ sanitizeSpectralRegions(findSpectralRepairEffect(clip)?.params.regions);
+
+export interface SpectralActionIds {
+ readonly actionId: string;
+ readonly effectId: string;
+}
+
+/**
+ * The single undoable action that makes the clip's region list `regions`: add the effect when the clip has
+ * none, replace it (the whole effect, so undo restores the previous list exactly) when it has one, remove it
+ * when the list becomes empty. Null when nothing would change. Region edits are never merged into a neighbouring
+ * undo step: each commit is its own step.
+ */
+export function planSpectralRegionsAction(
+ clip: Pick<Clip, "id" | "audioEffects">,
+ regions: readonly SpectralRegion[],
+ ids: SpectralActionIds,
+ timestamp = Date.now(),
+): Action | null {
+ const next = sanitizeSpectralRegions(regions);
+ const existing = findSpectralRepairEffect(clip);
+ if (!existing) {
+ if (next.length === 0) return null;
+ return { id: ids.actionId, timestamp, type: "audio/addEffect", params: { clipId: clip.id, effect: createSpectralRepairEffect(ids.effectId, next) } };
+ }
+ const current = sanitizeSpectralRegions(existing.params.regions);
+ if (JSON.stringify(current) === JSON.stringify(next)) return null;
+ if (next.length === 0) {
+ return { id: ids.actionId, timestamp, type: "audio/removeEffect", params: { clipId: clip.id, effectId: existing.id } };
+ }
+ return {
+ id: ids.actionId,
+ timestamp,
+ type: "audio/replaceEffect",
+ params: { clipId: clip.id, effectId: existing.id, effect: { ...existing, params: { ...existing.params, regions: next } } },
+ };
+}
diff --git a/packages/core/src/audio/spectral/spectral-regions.ts b/packages/core/src/audio/spectral/spectral-regions.ts
new file mode 100644
index 00000000..8fe30041
--- /dev/null
+++ b/packages/core/src/audio/spectral/spectral-regions.ts
@@ -0,0 +1,106 @@
+/**
+ * Spectral repair regions: the data model stored in a clip's "spectralRepair" audio effect.
+ *
+ * Regions live in SOURCE time (seconds of the decoded media), not clip time, so trimming, moving,
+ * retiming or reversing the clip never shifts an edit off the sound it was painted on. This module
+ * is deliberately free of DSP so the realtime graph and the export engine can import it cheaply.
+ */
+import type { Effect } from "../../types/timeline";
+
+export const SPECTRAL_REPAIR_EFFECT_TYPE = "spectralRepair";
+export const MAX_SPECTRAL_REGIONS = 256;
+/** Deepest attenuation a region can ask for (below this "remove" is the right tool). */
+export const MIN_SPECTRAL_ATTENUATION_DB = -120;
+export const DEFAULT_SPECTRAL_ATTENUATION_DB = -12;
+const MAX_REGION_HZ = 192000;
+const MIN_REGION_SECONDS = 1e-4;
+
+export type SpectralRegionMode = "attenuate" | "remove";
+
+export interface SpectralRegion {
+ readonly id: string;
+ /** attenuate: scale the selection by `gainDb`. remove: replace it by interpolating the surrounding frames/bins. */
+ readonly mode: SpectralRegionMode;
+ /** Source-time bounds in seconds. A frequency-band marquee spans the whole source. */
+ readonly startTime: number;
+ readonly endTime: number;
+ readonly lowHz: number;
+ readonly highHz: number;
+ /** Attenuate only: gain in dB, <= 0 (a "12 dB cut" is -12). Unused (stored as the minimum) for remove. */
+ readonly gainDb: number;
+ readonly enabled: boolean;
+}
+
+const finite = (value: unknown): number | null => (typeof value === "number" && Number.isFinite(value) ? value : null);
+
+/** Normalises untrusted input (saved project, agent call, UI); invalid entries are dropped. */
+export function sanitizeSpectralRegions(raw: unknown): SpectralRegion[] {
+ if (!Array.isArray(raw)) return [];
+ const out: SpectralRegion[] = [];
+ const seen = new Set<string>();
+ for (const item of raw) {
+ if (out.length >= MAX_SPECTRAL_REGIONS) break;
+ if (!item || typeof item !== "object") continue;
+ const r = item as Record<string, unknown>;
+ const mode: SpectralRegionMode | null = r.mode === "remove" ? "remove" : r.mode === "attenuate" ? "attenuate" : null;
+ const t0 = finite(r.startTime);
+ const t1 = finite(r.endTime);
+ const f0 = finite(r.lowHz);
+ const f1 = finite(r.highHz);
+ if (!mode || t0 === null || t1 === null || f0 === null || f1 === null) continue;
+ const startTime = Math.max(0, Math.min(t0, t1));
+ const endTime = Math.max(0, Math.max(t0, t1));
+ const lowHz = Math.max(0, Math.min(f0, f1));
+ const highHz = Math.min(MAX_REGION_HZ, Math.max(f0, f1));
+ if (endTime - startTime < MIN_REGION_SECONDS || highHz - lowHz <= 0) continue;
+ const gain = finite(r.gainDb);
+ const gainDb =
+ mode === "attenuate"
+ ? Math.max(MIN_SPECTRAL_ATTENUATION_DB, Math.min(0, gain ?? DEFAULT_SPECTRAL_ATTENUATION_DB))
+ : MIN_SPECTRAL_ATTENUATION_DB;
+ let id = typeof r.id === "string" && r.id ? r.id : `region-${out.length + 1}`;
+ while (seen.has(id)) id = `${id}-x`;
+ seen.add(id);
+ out.push({ id, mode, startTime, endTime, lowHz, highHz, gainDb, enabled: r.enabled !== false });
+ }
+ return out;
+}
+
+/** The regions that actually process audio (enabled), in order. */
+export const activeSpectralRegions = (regions: readonly SpectralRegion[]): SpectralRegion[] => regions.filter((region) => region.enabled);
+
+/** Stable cache key of what the regions do to the audio ("" when nothing is processed). Ids and the enabled flag of off regions do not matter. */
+export function spectralRegionsKey(regions: readonly SpectralRegion[]): string {
+ return activeSpectralRegions(regions)
+ .map((r) => `${r.mode[0]}${r.startTime.toFixed(5)},${r.endTime.toFixed(5)},${r.lowHz.toFixed(2)},${r.highHz.toFixed(2)},${r.gainDb.toFixed(3)}`)
+ .join(";");
+}
+
+interface EffectLike {
+ readonly type: string;
+ readonly enabled?: boolean;
+ readonly params?: Readonly<Record<string, unknown>>;
+}
+
+export const isSpectralRepairEffect = (effect: Pick<Effect, "type">): boolean => effect.type === SPECTRAL_REPAIR_EFFECT_TYPE;
+
+/** Active regions of every enabled "spectralRepair" effect in a clip's chain, concatenated in chain order. */
+export function getSpectralRepairRegions(effects: readonly EffectLike[] | undefined): SpectralRegion[] {
+ const out: SpectralRegion[] = [];
+ for (const effect of effects ?? []) {
+ if (effect.type !== SPECTRAL_REPAIR_EFFECT_TYPE || effect.enabled === false) continue;
+ out.push(...activeSpectralRegions(sanitizeSpectralRegions(effect.params?.regions)));
+ }
+ return out;
+}
+
+export const hasSpectralRepair = (effects: readonly EffectLike[] | undefined): boolean => getSpectralRepairRegions(effects).length > 0;
+
+/** Builds the effect that carries a region list (one per clip; edits replace its `regions`). */
+export function createSpectralRepairEffect(id: string, regions: readonly SpectralRegion[] = []): Effect {
+ return { id, type: SPECTRAL_REPAIR_EFFECT_TYPE, enabled: true, params: { regions: sanitizeSpectralRegions(regions) } };
+}
+
+let regionCounter = 0;
+/** A fresh region id (unique within a session; collisions inside one clip are repaired by sanitize). */
+export const newSpectralRegionId = (): string => `sr-${Date.now().toString(36)}-${(regionCounter++).toString(36)}`;
diff --git a/packages/core/src/audio/spectral/spectral-repair-cache.test.ts b/packages/core/src/audio/spectral/spectral-repair-cache.test.ts
new file mode 100644
index 00000000..b23acdd9
--- /dev/null
+++ b/packages/core/src/audio/spectral/spectral-repair-cache.test.ts
@@ -0,0 +1,77 @@
+import { describe, expect, it, vi } from "vitest";
+import { SpectralRepairCache } from "./spectral-repair-cache";
+import { createInlineSpectralBackend, type SpectralBackend } from "./spectral-worker-client";
+import { applySpectralRegions } from "./spectral-dsp";
+import type { SpectralRegion } from "./spectral-regions";
+
+const SR = 8000;
+const REGION: SpectralRegion = { id: "a", mode: "remove", startTime: 0.5, endTime: 1.5, lowHz: 400, highHz: 600, gainDb: -120, enabled: true };
+
+const buffer = (seconds: number): AudioBuffer => {
+ const data = Float32Array.from({ length: SR * seconds }, (_, i) => 0.4 * Math.sin((2 * Math.PI * 500 * i) / SR) + 0.2 * Math.sin((2 * Math.PI * 2000 * i) / SR));
+ return { numberOfChannels: 1, sampleRate: SR, length: data.length, duration: seconds, getChannelData: () => data } as unknown as AudioBuffer;
+};
+const makeBuffer = (channels: Float32Array[], sampleRate: number): AudioBuffer =>
+ ({ numberOfChannels: channels.length, sampleRate, length: channels[0].length, duration: channels[0].length / sampleRate, getChannelData: (c: number) => channels[c] }) as unknown as AudioBuffer;
+
+describe("SpectralRepairCache", () => {
+ it("computes once per source and region set, shares running jobs, and peeks without computing", async () => {
+ const backend = createInlineSpectralBackend();
+ const repair = vi.spyOn(backend, "repair");
+ const cache = new SpectralRepairCache({ backend, makeBuffer });
+ const source = buffer(2);
+ expect(cache.peek({ buffer: source, regions: [REGION] })).toBeNull();
+ expect(repair).not.toHaveBeenCalled();
+ const [a, b] = await Promise.all([cache.request({ buffer: source, regions: [REGION] }), cache.request({ buffer: source, regions: [{ ...REGION, id: "other-id" }] })]);
+ expect(repair).toHaveBeenCalledTimes(1);
+ expect(a).toBe(b);
+ expect(cache.peek({ buffer: source, regions: [REGION] })).toBe(a);
+ expect(await cache.request({ buffer: source, regions: [REGION] })).toBe(a);
+ expect(repair).toHaveBeenCalledTimes(1);
+ // A different region set is a different entry; no active region is the source itself.
+ const other = await cache.request({ buffer: source, regions: [{ ...REGION, highHz: 700 }] });
+ expect(other).not.toBe(a);
+ expect(await cache.request({ buffer: source, regions: [{ ...REGION, enabled: false }] })).toBe(source);
+ expect(cache.peek({ buffer: source, regions: [] })).toBeNull();
+ });
+
+ it("produces exactly what the DSP produces (the export and the preview share these samples)", async () => {
+ const cache = new SpectralRepairCache({ backend: createInlineSpectralBackend(), makeBuffer });
+ const source = buffer(2);
+ const out = (await cache.request({ buffer: source, regions: [REGION] }))!;
+ const direct = applySpectralRegions([source.getChannelData(0)], SR, [REGION])[0];
+ expect(Array.from(out.getChannelData(0))).toEqual(Array.from(direct));
+ });
+
+ it("notifies listeners, and remembers a failure for a while", async () => {
+ let now = 0;
+ const failing: SpectralBackend = { repair: vi.fn(() => Promise.reject(new Error("no"))), load: async () => undefined, view: async () => { throw new Error("x"); }, drop: async () => undefined };
+ const cache = new SpectralRepairCache({ backend: failing, makeBuffer, now: () => now });
+ const source = buffer(1);
+ expect(await cache.request({ buffer: source, regions: [REGION] })).toBeNull();
+ expect(await cache.request({ buffer: source, regions: [REGION] })).toBeNull();
+ expect(failing.repair).toHaveBeenCalledTimes(1);
+ now = 31_000;
+ await cache.request({ buffer: source, regions: [REGION] });
+ expect(failing.repair).toHaveBeenCalledTimes(2);
+
+ const ok = new SpectralRepairCache({ backend: createInlineSpectralBackend(), makeBuffer });
+ const heard = vi.fn();
+ ok.onReady(heard);
+ await ok.request({ buffer: buffer(1), regions: [REGION] });
+ expect(heard).toHaveBeenCalledTimes(1);
+ });
+});
+
+describe("inline spectral backend", () => {
+ it("serves spectrograms of a loaded source and refuses unknown keys", async () => {
+ const backend = createInlineSpectralBackend();
+ await expect(backend.view("missing", {})).rejects.toThrow();
+ await backend.load("k", Float32Array.from({ length: SR }, (_, i) => Math.sin((2 * Math.PI * 1000 * i) / SR)), SR);
+ const view = await backend.view("k", { maxFrames: 20 });
+ expect(view.frames).toBeGreaterThan(0);
+ expect(view.sampleRate).toBe(SR);
+ await backend.drop("k");
+ await expect(backend.view("k", {})).rejects.toThrow();
+ });
+});
diff --git a/packages/core/src/audio/spectral/spectral-repair-cache.ts b/packages/core/src/audio/spectral/spectral-repair-cache.ts
new file mode 100644
index 00000000..fbb78cdd
--- /dev/null
+++ b/packages/core/src/audio/spectral/spectral-repair-cache.ts
@@ -0,0 +1,121 @@
+import { spectralRegionsKey, type SpectralRegion } from "./spectral-regions";
+import { getSpectralBackend, type SpectralBackend } from "./spectral-worker-client";
+
+/**
+ * Cached, off-thread spectral repair of a decoded source buffer.
+ *
+ * A clip's "spectralRepair" regions are applied to the whole decoded source (regions are in source
+ * time) once; the result is cached per source buffer and region set and shared by the live preview and
+ * the export mixdown, so both play the very same samples. The preview uses {@link peek} and swaps
+ * the repaired buffer in when {@link request} resolves; the export awaits {@link request}.
+ */
+
+export type SpectralBufferFactory = (channels: Float32Array[], sampleRate: number) => AudioBuffer;
+
+export interface SpectralRepairRequest {
+ readonly buffer: AudioBuffer;
+ readonly regions: readonly SpectralRegion[];
+}
+
+/** How long a failed key is remembered before a new attempt is made. */
+export const SPECTRAL_FAILURE_TTL_MS = 30_000;
+
+export interface SpectralRepairCacheOptions {
+ readonly backend?: SpectralBackend;
+ readonly makeBuffer: SpectralBufferFactory;
+ readonly now?: () => number;
+ readonly maxEntriesPerBuffer?: number;
+}
+
+export class SpectralRepairCache {
+ private readonly explicitBackend: SpectralBackend | undefined;
+ private makeBuffer: SpectralBufferFactory;
+ private readonly now: () => number;
+ private readonly maxEntries: number;
+ private readonly entries = new WeakMap<AudioBuffer, Map<string, AudioBuffer>>();
+ private readonly jobs = new WeakMap<AudioBuffer, Map<string, Promise<AudioBuffer | null>>>();
+ private readonly failures = new WeakMap<AudioBuffer, Map<string, number>>();
+ private readonly listeners = new Set<(request: SpectralRepairRequest, result: AudioBuffer) => void>();
+
+ constructor(options: SpectralRepairCacheOptions) {
+ this.explicitBackend = options.backend;
+ this.makeBuffer = options.makeBuffer;
+ this.now = options.now ?? Date.now;
+ this.maxEntries = options.maxEntriesPerBuffer ?? 6;
+ }
+
+ setBufferFactory(factory: SpectralBufferFactory): void {
+ this.makeBuffer = factory;
+ }
+
+ private get backend(): SpectralBackend {
+ return this.explicitBackend ?? getSpectralBackend();
+ }
+
+ /** The repaired buffer, or null when it is not (yet) available or there is nothing to repair. Never computes anything. */
+ peek(request: SpectralRepairRequest): AudioBuffer | null {
+ const key = spectralRegionsKey(request.regions);
+ return key ? (this.entries.get(request.buffer)?.get(key) ?? null) : null;
+ }
+
+ onReady(listener: (request: SpectralRepairRequest, result: AudioBuffer) => void): () => void {
+ this.listeners.add(listener);
+ return () => this.listeners.delete(listener);
+ }
+
+ /** Starts (or joins) the job. Resolves with the repaired buffer, the source itself when no region is active, or null on failure. */
+ request(request: SpectralRepairRequest): Promise<AudioBuffer | null> {
+ const key = spectralRegionsKey(request.regions);
+ const { buffer } = request;
+ if (!key) return Promise.resolve(buffer);
+ const cached = this.entries.get(buffer)?.get(key);
+ if (cached) return Promise.resolve(cached);
+ let byKey = this.jobs.get(buffer);
+ const running = byKey?.get(key);
+ if (running) return running;
+ const failedUntil = this.failures.get(buffer)?.get(key);
+ if (failedUntil !== undefined && failedUntil > this.now()) return Promise.resolve(null);
+ const channels: Float32Array[] = [];
+ for (let c = 0; c < buffer.numberOfChannels; c += 1) channels.push(buffer.getChannelData(c));
+ const regions = request.regions.map((region) => ({ ...region }));
+ const job = this.backend
+ .repair(channels, buffer.sampleRate, regions)
+ .then((repaired) => {
+ const out = this.makeBuffer(repaired, buffer.sampleRate);
+ this.store(buffer, key, out);
+ for (const listener of [...this.listeners]) listener(request, out);
+ return out;
+ })
+ .catch(() => {
+ let failed = this.failures.get(buffer);
+ if (!failed) this.failures.set(buffer, (failed = new Map()));
+ failed.set(key, this.now() + SPECTRAL_FAILURE_TTL_MS);
+ return null;
+ })
+ .finally(() => {
+ this.jobs.get(buffer)?.delete(key);
+ });
+ if (!byKey) this.jobs.set(buffer, (byKey = new Map()));
+ byKey.set(key, job);
+ return job;
+ }
+
+ private store(buffer: AudioBuffer, key: string, value: AudioBuffer): void {
+ let byKey = this.entries.get(buffer);
+ if (!byKey) this.entries.set(buffer, (byKey = new Map()));
+ if (byKey.size >= this.maxEntries) {
+ const oldest = byKey.keys().next().value;
+ if (oldest !== undefined) byKey.delete(oldest);
+ }
+ byKey.set(key, value);
+ }
+}
+
+let sharedCache: SpectralRepairCache | null = null;
+
+/** The process-wide cache used by preview and export, so a repair computed for one is reused by the other. */
+export function getSharedSpectralRepairCache(makeBuffer: SpectralBufferFactory): SpectralRepairCache {
+ if (!sharedCache) sharedCache = new SpectralRepairCache({ makeBuffer });
+ else sharedCache.setBufferFactory(makeBuffer);
+ return sharedCache;
+}
diff --git a/packages/core/src/audio/spectral/spectral-worker-client.ts b/packages/core/src/audio/spectral/spectral-worker-client.ts
new file mode 100644
index 00000000..f8863bf9
--- /dev/null
+++ b/packages/core/src/audio/spectral/spectral-worker-client.ts
@@ -0,0 +1,127 @@
+import type { SpectralView, SpectralViewOptions } from "./spectral-dsp";
+import type { SpectralRegion } from "./spectral-regions";
+import type { SpectralRequest, SpectralResponse } from "./spectral-worker-core";
+
+/**
+ * Where spectral work runs: a module Web Worker in the browser (nothing heavy on the main thread),
+ * a deferred inline call where workers do not exist. Both execute the same handler.
+ */
+export interface SpectralBackend {
+ repair(channels: Float32Array[], sampleRate: number, regions: SpectralRegion[]): Promise<Float32Array[]>;
+ /** Makes a mono source available to `view` under `key` (replaces an earlier load). */
+ load(key: string, mono: Float32Array, sampleRate: number): Promise<void>;
+ view(key: string, options: SpectralViewOptions): Promise<SpectralView>;
+ drop(key: string): Promise<void>;
+}
+
+/** Longest source the main-thread fallback will repair; longer ones are refused so playback never stalls on it. */
+export const INLINE_SPECTRAL_MAX_SECONDS = 120;
+
+export function createInlineSpectralBackend(): SpectralBackend {
+ let handler: Promise<(request: SpectralRequest) => SpectralResponse> | null = null;
+ let nextId = 1;
+ const run = async (request: (id: number) => SpectralRequest): Promise<SpectralResponse> => {
+ handler ??= import("./spectral-worker-core").then((mod) => mod.createSpectralHandler());
+ const handle = await handler;
+ await new Promise<void>((resolve) => setTimeout(resolve, 0));
+ const response = handle(request(nextId++));
+ if (response.error) throw new Error(response.error);
+ return response;
+ };
+ return {
+ async repair(channels, sampleRate, regions) {
+ const seconds = (channels[0]?.length ?? 0) / Math.max(1, sampleRate);
+ if (seconds > INLINE_SPECTRAL_MAX_SECONDS) throw new Error(`inline spectral repair limited to ${INLINE_SPECTRAL_MAX_SECONDS}s`);
+ return (await run((id) => ({ id, kind: "repair", channels, sampleRate, regions }))).channels ?? [];
+ },
+ async load(key, mono, sampleRate) {
+ await run((id) => ({ id, kind: "load", key, mono, sampleRate }));
+ },
+ async view(key, options) {
+ const response = await run((id) => ({ id, kind: "view", key, options }));
+ if (!response.view) throw new Error("no spectrogram");
+ return response.view;
+ },
+ async drop(key) {
+ await run((id) => ({ id, kind: "drop", key }));
+ },
+ };
+}
+
+export function createWorkerSpectralBackend(): SpectralBackend | null {
+ if (typeof Worker === "undefined") return null;
+ let worker: Worker | null = null;
+ let nextId = 1;
+ const pending = new Map<number, { resolve: (response: SpectralResponse) => void; reject: (error: Error) => void }>();
+ const failAll = (error: Error) => {
+ for (const job of pending.values()) job.reject(error);
+ pending.clear();
+ worker?.terminate();
+ worker = null;
+ };
+ const ensure = (): Worker => {
+ if (worker) return worker;
+ const created = new Worker(new URL("./spectral.worker.ts", import.meta.url), { type: "module", name: "openreel-spectral" });
+ created.onmessage = (event: MessageEvent<SpectralResponse>) => {
+ const job = pending.get(event.data.id);
+ if (!job) return;
+ pending.delete(event.data.id);
+ if (event.data.error) job.reject(new Error(event.data.error));
+ else job.resolve(event.data);
+ };
+ created.onerror = () => failAll(new Error("spectral worker failed"));
+ worker = created;
+ return created;
+ };
+ const call = (build: (id: number) => SpectralRequest, transfer: Transferable[]): Promise<SpectralResponse> =>
+ new Promise((resolve, reject) => {
+ try {
+ const id = nextId++;
+ pending.set(id, { resolve, reject });
+ ensure().postMessage(build(id), transfer);
+ } catch (error) {
+ reject(error instanceof Error ? error : new Error(String(error)));
+ }
+ });
+ return {
+ async repair(channels, sampleRate, regions) {
+ const copies = channels.map((channel) => channel.slice());
+ return (await call((id) => ({ id, kind: "repair", channels: copies, sampleRate, regions }), copies.map((c) => c.buffer))).channels ?? [];
+ },
+ async load(key, mono, sampleRate) {
+ const copy = mono.slice();
+ await call((id) => ({ id, kind: "load", key, mono: copy, sampleRate }), [copy.buffer]);
+ },
+ async view(key, options) {
+ const response = await call((id) => ({ id, kind: "view", key, options }), []);
+ if (!response.view) throw new Error("no spectrogram");
+ return response.view;
+ },
+ async drop(key) {
+ await call((id) => ({ id, kind: "drop", key }), []);
+ },
+ };
+}
+
+let shared: SpectralBackend | null = null;
+
+/** The shared backend: the worker when available, falling back to the inline one after a worker failure. */
+export function getSpectralBackend(): SpectralBackend {
+ if (shared) return shared;
+ const worker = createWorkerSpectralBackend();
+ const inline = createInlineSpectralBackend();
+ shared = worker
+ ? {
+ repair: (channels, sampleRate, regions) => worker.repair(channels, sampleRate, regions).catch(() => inline.repair(channels, sampleRate, regions)),
+ load: (key, mono, sampleRate) => worker.load(key, mono, sampleRate).catch(() => inline.load(key, mono, sampleRate)),
+ view: (key, options) => worker.view(key, options),
+ drop: (key) => worker.drop(key).catch(() => undefined),
+ }
+ : inline;
+ return shared;
+}
+
+/** Test / host hook: replaces the shared backend. */
+export function setSpectralBackend(backend: SpectralBackend | null): void {
+ shared = backend;
+}
diff --git a/packages/core/src/audio/spectral/spectral-worker-core.ts b/packages/core/src/audio/spectral/spectral-worker-core.ts
new file mode 100644
index 00000000..6d35d2b0
--- /dev/null
+++ b/packages/core/src/audio/spectral/spectral-worker-core.ts
@@ -0,0 +1,46 @@
+/**
+ * The request handler behind the spectral worker. It is the same code whether it runs in the module
+ * worker (spectral.worker.ts) or inline (node tests, browsers without workers), so a repair or a view
+ * never depends on where it was computed.
+ */
+import { applySpectralRegions, computeSpectralView, type SpectralView, type SpectralViewOptions } from "./spectral-dsp";
+import type { SpectralRegion } from "./spectral-regions";
+
+export type SpectralRequest =
+ | { readonly id: number; readonly kind: "repair"; readonly channels: Float32Array[]; readonly sampleRate: number; readonly regions: SpectralRegion[] }
+ | { readonly id: number; readonly kind: "load"; readonly key: string; readonly mono: Float32Array; readonly sampleRate: number }
+ | { readonly id: number; readonly kind: "view"; readonly key: string; readonly options: SpectralViewOptions }
+ | { readonly id: number; readonly kind: "drop"; readonly key: string };
+
+export interface SpectralResponse {
+ readonly id: number;
+ readonly channels?: Float32Array[];
+ readonly view?: SpectralView;
+ readonly ok?: boolean;
+ readonly error?: string;
+}
+
+export function createSpectralHandler(): (request: SpectralRequest) => SpectralResponse {
+ const sources = new Map<string, { mono: Float32Array; sampleRate: number }>();
+ return (request) => {
+ try {
+ switch (request.kind) {
+ case "repair":
+ return { id: request.id, channels: applySpectralRegions(request.channels, request.sampleRate, request.regions) };
+ case "load":
+ sources.set(request.key, { mono: request.mono, sampleRate: request.sampleRate });
+ return { id: request.id, ok: true };
+ case "drop":
+ sources.delete(request.key);
+ return { id: request.id, ok: true };
+ case "view": {
+ const source = sources.get(request.key);
+ if (!source) return { id: request.id, error: "spectral source not loaded" };
+ return { id: request.id, view: computeSpectralView([source.mono], source.sampleRate, request.options) };
+ }
+ }
+ } catch (error) {
+ return { id: request.id, error: error instanceof Error ? error.message : String(error) };
+ }
+ };
+}
diff --git a/packages/core/src/audio/spectral/spectral.worker.ts b/packages/core/src/audio/spectral/spectral.worker.ts
new file mode 100644
index 00000000..298e86bd
--- /dev/null
+++ b/packages/core/src/audio/spectral/spectral.worker.ts
@@ -0,0 +1,17 @@
+import { createSpectralHandler, type SpectralRequest, type SpectralResponse } from "./spectral-worker-core";
+
+/** Off-main-thread spectral repair and spectrogram computation. Imports only the pure DSP so it bundles as a small module worker. */
+const scope = self as unknown as {
+ onmessage: ((event: MessageEvent<SpectralRequest>) => void) | null;
+ postMessage(message: SpectralResponse, transfer: Transferable[]): void;
+};
+
+const handle = createSpectralHandler();
+
+scope.onmessage = (event) => {
+ const response = handle(event.data);
+ const transfer: Transferable[] = [];
+ for (const channel of response.channels ?? []) transfer.push(channel.buffer);
+ if (response.view) transfer.push(response.view.data.buffer);
+ scope.postMessage(response, transfer);
+};
diff --git a/packages/core/src/captions/caption-export.ts b/packages/core/src/captions/caption-export.ts
index 4aa4f804..fbeb4431 100644
--- a/packages/core/src/captions/caption-export.ts
+++ b/packages/core/src/captions/caption-export.ts
@@ -118,7 +118,7 @@ export interface EmbeddedCaptionPlan {
}
export interface EmbeddedCaptionContext {
- format: "mp4" | "mov" | "webm" | "mxf";
+ format: "mp4" | "mov" | "webm" | "mxf" | "mkv";
/** "native" = desktop ffmpeg; "web" = MediaBunny in the browser. */
engine: "native" | "web";
frameRate: number;
@@ -159,8 +159,8 @@ export function planEmbeddedCaptions(
plan.warnings.push(`MXF files cannot hold a subtitle track here; ${trackLabel(id)} was not embedded. Export a sidecar caption file instead.`);
continue;
}
- if (context.format === "webm") {
- plan.warnings.push(`WebM export cannot embed subtitle tracks here; ${trackLabel(id)} was not embedded.`);
+ if (context.format === "webm" || context.format === "mkv") {
+ plan.warnings.push(`${context.format === "mkv" ? "MKV" : "WebM"} export cannot embed subtitle tracks here; ${trackLabel(id)} was not embedded.`);
continue;
}
if (settings.embedded === "cea608" && context.format === "mov") {
diff --git a/packages/core/src/editing/portable-project.test.ts b/packages/core/src/editing/portable-project.test.ts
index 523b87b4..2a7ece00 100644
--- a/packages/core/src/editing/portable-project.test.ts
+++ b/packages/core/src/editing/portable-project.test.ts
@@ -217,3 +217,18 @@ describe("portable clip relationships", () => {
expect(() => createPortableEdit(before)).toThrow();
});
});
+
+describe("spectral repair in the portable edit boundary", () => {
+ it("round-trips regions and rejects malformed ones", () => {
+ const before = project();
+ const region = (id: string, mode: string) => ({ id, mode, startTime: 1, endTime: 2, lowHz: 500, highHz: 900, gainDb: -12, enabled: true });
+ const clip = before.timeline.tracks[0].clips[0];
+ before.timeline.tracks[0].clips[0] = { ...clip, audioEffects: [{ id: "fx", type: "spectralRepair", enabled: true, params: { regions: [region("r1", "attenuate"), region("r2", "remove")] } }] };
+ const doc = createPortableEdit(before);
+ const parsed = parsePortableEdit(JSON.stringify(doc));
+ expect(materializePortableEdit(parsed, before).project.timeline.tracks[0].clips[0].audioEffects[0]).toEqual(before.timeline.tracks[0].clips[0].audioEffects[0]);
+ const bad = JSON.parse(JSON.stringify(doc));
+ bad.project.timeline.tracks[0].clips[0].audioEffects[0].params.regions[0].mode = "explode";
+ expect(() => parsePortableEdit(JSON.stringify(bad))).toThrow();
+ });
+});
diff --git a/packages/core/src/editing/portable-project.ts b/packages/core/src/editing/portable-project.ts
index cc7a29b5..63c474ec 100644
--- a/packages/core/src/editing/portable-project.ts
+++ b/packages/core/src/editing/portable-project.ts
@@ -44,6 +44,7 @@ export const AUDIO_EDIT_PARAM_SCHEMAS: Record<string, EditSchema> = {
gate: obj({ threshold: num(-90, 0), range: num(-90, 0), attack: num(0.0002, 0.5), hold: num(0, 2), release: num(0.005, 3) }),
brickwallLimiter: obj({ ceiling: num(-24, 0), release: num(0.01, 1) }),
lowPass: obj({ frequency: num(100, 20000), slope: num(12, 48) }),
+ spectralRepair: obj({ regions: arr(obj({ id, mode: en(["attenuate", "remove"]), startTime: num(0, 86400), endTime: num(0, 86400), lowHz: num(0, 192000), highHz: num(0, 192000), gainDb: num(-120, 0), enabled: bool }, ["mode", "startTime", "endTime", "lowHz", "highHz"]), 256) }),
fadeIn: obj({ duration: time, curve: en(["linear", "exponential", "logarithmic", "s-curve"]) }),
fadeOut: obj({ duration: time, curve: en(["linear", "exponential", "logarithmic", "s-curve"]) }),
};
diff --git a/packages/core/src/export/browser-capabilities.ts b/packages/core/src/export/browser-capabilities.ts
index db6b814f..ca028a5e 100644
--- a/packages/core/src/export/browser-capabilities.ts
+++ b/packages/core/src/export/browser-capabilities.ts
@@ -1,3 +1,4 @@
+import { DOLBY_VIDEO_DESKTOP_ONLY_REASON, dolbyContainerProblem, isDolbyFormat } from "./dolby";
import { CODEC_MAP, type VideoExportSettings } from "./types";
import type { Project } from "../types/project";
import type { Clip } from "../types/timeline";
@@ -23,6 +24,10 @@ export function getVideoExportValidationError(settings: VideoExportSettings, dur
if (!Number.isFinite(settings.maxBitrate) || settings.maxBitrate <= 0) return "Choose a valid maximum bitrate.";
if (!profileRated && settings.maxBitrate < settings.bitrate) return "The maximum bitrate cannot be lower than the target bitrate.";
}
+ if (isDolbyFormat(settings.audioSettings?.format)) {
+ const dolbyProblem = dolbyContainerProblem(settings.format);
+ if (dolbyProblem) return dolbyProblem;
+ }
return broadcastDeliveryProblem(settings);
}
@@ -69,6 +74,8 @@ export async function checkBrowserExportCapability(
if (settings.codec === "prores" || settings.codec === "dnxhr" || isBroadcastCodec(settings.codec) || settings.format === "mxf" || (settings.colorDepth ?? 8) > 8 || (settings.pixelFormat && settings.pixelFormat !== "yuv420")) {
return { supported: false, reason: "ProRes, DNxHR, XDCAM HD422, AVC-Intra, MXF, timecode tracks, transparency, and high bit depth export require the desktop encoder. Choose H.264 for browser export." };
}
+ if (settings.format === "mkv") return { supported: false, reason: "MKV export needs the desktop app. Choose MP4, MOV or WebM." };
+ if (isDolbyFormat(settings.audioSettings?.format)) return { supported: false, reason: DOLBY_VIDEO_DESKTOP_ONLY_REASON };
try {
const library = mediaBunny ?? await import("mediabunny");
const format = settings.format === "webm" ? new library.WebMOutputFormat() : settings.format === "mov" ? new library.MovOutputFormat() : new library.Mp4OutputFormat();
diff --git a/packages/core/src/export/dolby-encode.ts b/packages/core/src/export/dolby-encode.ts
new file mode 100644
index 00000000..29063602
--- /dev/null
+++ b/packages/core/src/export/dolby-encode.ts
@@ -0,0 +1,55 @@
+import { dolbyEncodeArgs, dolbyRawMuxer, dolbyFileExtension, type DolbyEncodeParams } from "./dolby";
+
+/**
+ * Audio-only AC-3 / E-AC-3: a PCM WAV (5.1 as L R C LFE Ls Rs) becomes a raw elementary stream.
+ *
+ * Desktop: the ffmpeg sidecar (`openreel.export.encodeDolbyAudio`). Browser: the ffmpeg.wasm core, which this
+ * module loads on demand (it is a separate chunk, so none of it is on the app's entry path). Both run the same
+ * ffmpeg encoder with the same options (`dolbyEncodeArgs`).
+ */
+
+export interface DolbyStreamRequest {
+ /** PCM WAV, 2 or 6 channels (6 with the 5.1 speaker mask). */
+ wav: Uint8Array;
+ params: DolbyEncodeParams;
+}
+
+interface DesktopDolbyBridge {
+ export?: {
+ encodeDolbyAudio?: (args: {
+ wav: ArrayBuffer;
+ codec: "ac3" | "eac3";
+ channels: 2 | 6;
+ bitrateKbps: number;
+ sampleRate: 44100 | 48000;
+ dialnorm: number;
+ }) => Promise<ArrayBuffer>;
+ };
+}
+
+/** Which engine encodes: the desktop sidecar when the desktop bridge offers it, else ffmpeg.wasm. */
+export function dolbyEncoderEngine(): "sidecar" | "wasm" {
+ const bridge = (globalThis as { openreel?: DesktopDolbyBridge }).openreel;
+ return typeof bridge?.export?.encodeDolbyAudio === "function" ? "sidecar" : "wasm";
+}
+
+export async function encodeDolbyStream(request: DolbyStreamRequest, signal?: AbortSignal): Promise<Uint8Array> {
+ const { params } = request;
+ if (dolbyEncoderEngine() === "sidecar") {
+ const bridge = (globalThis as { openreel?: DesktopDolbyBridge }).openreel!;
+ const wav = request.wav.buffer.slice(request.wav.byteOffset, request.wav.byteOffset + request.wav.byteLength) as ArrayBuffer;
+ const encoded = await bridge.export!.encodeDolbyAudio!({
+ wav,
+ codec: params.codec,
+ channels: params.channels > 2 ? 6 : 2,
+ bitrateKbps: params.bitrateKbps,
+ sampleRate: params.sampleRate === 44100 ? 44100 : 48000,
+ dialnorm: params.dialnorm,
+ });
+ return new Uint8Array(encoded);
+ }
+ const { getFFmpegFallback } = await import("../media/ffmpeg-fallback");
+ const ffmpeg = getFFmpegFallback();
+ await ffmpeg.load(signal);
+ return ffmpeg.encodeAudioStream(request.wav, dolbyEncodeArgs(params), dolbyRawMuxer(params.codec), dolbyFileExtension(params.codec));
+}
diff --git a/packages/core/src/export/dolby.test.ts b/packages/core/src/export/dolby.test.ts
new file mode 100644
index 00000000..16312613
--- /dev/null
+++ b/packages/core/src/export/dolby.test.ts
@@ -0,0 +1,160 @@
+import { describe, expect, it, vi } from "vitest";
+
+// export-engine pulls in the decode worker module, which reads `self` at load time.
+vi.hoisted(() => {
+ (globalThis as { self?: unknown }).self ??= globalThis;
+});
+import {
+ AC3_VALID_BITRATES,
+ DEFAULT_DIALNORM,
+ DOLBY_BITRATES,
+ DOLBY_5_1_CHANNELMAP,
+ clampDialnorm,
+ clampDolbyBitrate,
+ defaultDolbyBitrate,
+ dolbyChannelsProblem,
+ dolbyContainerProblem,
+ dolbyDeliveryProblems,
+ dolbyEncodeArgs,
+ dolbyFileExtension,
+ dolbySampleRate,
+ isDolbyFormat,
+ resolveDialnorm,
+ resolveDolbyAudioSettings,
+} from "./dolby";
+import { exportSettingsRequireNativeEncoder, desktopExportRequiresNativeEncoder } from "./export-engine";
+import { getVideoExportValidationError } from "./browser-capabilities";
+import { resolveSequenceAudioSettings } from "./surround-export";
+import { DEFAULT_VIDEO_SETTINGS, type AudioExportSettings, type VideoExportSettings } from "./types";
+
+const audio = (patch: Partial<AudioExportSettings> = {}): AudioExportSettings => ({
+ format: "ac3",
+ sampleRate: 48000,
+ bitDepth: 24,
+ bitrate: 448,
+ channels: 6,
+ ...patch,
+});
+
+describe("Dolby Digital bitrate choices", () => {
+ it("offers AC-3 from 192 to 640 kbps, every one a rate the AC-3 bitstream can signal", () => {
+ expect(DOLBY_BITRATES.ac3[0]).toBe(192);
+ expect(DOLBY_BITRATES.ac3.at(-1)).toBe(640);
+ for (const kbps of DOLBY_BITRATES.ac3) expect(AC3_VALID_BITRATES).toContain(kbps);
+ });
+
+ it("offers E-AC-3 up to 1024 kbps", () => {
+ expect(DOLBY_BITRATES.eac3.at(-1)).toBe(1024);
+ expect(DOLBY_BITRATES.eac3).toContain(640);
+ });
+
+ it("snaps an unlisted bitrate up to the next offered one and clamps the ends", () => {
+ expect(clampDolbyBitrate("ac3", 300)).toBe(320);
+ expect(clampDolbyBitrate("ac3", 128)).toBe(192);
+ expect(clampDolbyBitrate("ac3", 5000)).toBe(640);
+ expect(clampDolbyBitrate("eac3", 960)).toBe(1024);
+ expect(clampDolbyBitrate("eac3", Number.NaN)).toBe(192);
+ });
+
+ it("defaults to the usual delivery rates", () => {
+ expect(defaultDolbyBitrate("ac3", 2)).toBe(192);
+ expect(defaultDolbyBitrate("ac3", 6)).toBe(448);
+ expect(defaultDolbyBitrate("eac3", 6)).toBe(640);
+ });
+});
+
+describe("dialnorm", () => {
+ it("clamps to -31..-1 dB", () => {
+ expect(clampDialnorm(-40)).toBe(-31);
+ expect(clampDialnorm(5)).toBe(-1);
+ expect(clampDialnorm(-23.6)).toBe(-24);
+ expect(clampDialnorm(Number.NaN)).toBe(DEFAULT_DIALNORM);
+ });
+
+ it("an explicit value wins, else the loudness target, else -31", () => {
+ expect(resolveDialnorm({ dialnorm: -27, loudness: { enabled: true, targetLufs: -24 } })).toBe(-27);
+ expect(resolveDialnorm({ loudness: { enabled: true, targetLufs: -24 } })).toBe(-24);
+ expect(resolveDialnorm({ loudness: { enabled: false, targetLufs: -24 } })).toBe(-31);
+ expect(resolveDialnorm({})).toBe(-31);
+ });
+});
+
+describe("delivery rules", () => {
+ it("is Dolby only for ac3 / eac3", () => {
+ expect(isDolbyFormat("ac3")).toBe(true);
+ expect(isDolbyFormat("eac3")).toBe(true);
+ expect(isDolbyFormat("aac")).toBe(false);
+ expect(isDolbyFormat(undefined)).toBe(false);
+ expect(dolbyFileExtension("ac3")).toBe("ac3");
+ expect(dolbyFileExtension("eac3")).toBe("ec3");
+ });
+
+ it("carries AC-3 in MP4, MOV and MKV and refuses WebM and MXF with a reason", () => {
+ for (const container of ["mp4", "mov", "mkv"]) expect(dolbyContainerProblem(container)).toBeNull();
+ expect(dolbyContainerProblem("webm")).toMatch(/WebM cannot carry/);
+ expect(dolbyContainerProblem("mxf")).toMatch(/PCM/);
+ });
+
+ it("takes stereo and 5.1 only", () => {
+ expect(dolbyChannelsProblem(2)).toBeNull();
+ expect(dolbyChannelsProblem(6)).toBeNull();
+ expect(dolbyChannelsProblem(1)).toMatch(/stereo or 5.1/);
+ expect(dolbyChannelsProblem(8)).toMatch(/stereo or 5.1/);
+ expect(dolbyDeliveryProblems({ format: "aac", channels: 1 }, "webm")).toEqual([]);
+ expect(dolbyDeliveryProblems({ format: "ac3", channels: 1 }, "webm")).toHaveLength(2);
+ });
+
+ it("writes 48 kHz for a 96 kHz request and keeps 44.1 kHz", () => {
+ expect(dolbySampleRate(96000)).toBe(48000);
+ expect(dolbySampleRate(44100)).toBe(44100);
+ expect(dolbySampleRate(48000)).toBe(48000);
+ });
+
+ it("resolves the audio settings a Dolby export uses", () => {
+ const resolved = resolveDolbyAudioSettings(audio({ sampleRate: 96000, bitrate: 300, loudness: { enabled: true, targetLufs: -24, truePeakCeilingDb: -2 } }));
+ expect(resolved).toMatchObject({ sampleRate: 48000, bitrate: 320, dialnorm: -24 });
+ const other = audio({ format: "aac" });
+ expect(resolveDolbyAudioSettings(other)).toBe(other);
+ });
+
+ it("raises a 5.1 sequence's Dolby bitrate to the 5.1 floor and leaves a stereo one", () => {
+ const surround = { settings: { channels: 6, channelLayout: "5.1" } } as Parameters<typeof resolveSequenceAudioSettings>[0];
+ const stereo = { settings: { channels: 2 } } as Parameters<typeof resolveSequenceAudioSettings>[0];
+ expect(resolveSequenceAudioSettings(surround, audio({ channels: 2, bitrate: 192 })).bitrate).toBe(384);
+ expect(resolveSequenceAudioSettings(surround, audio({ channels: 2, bitrate: 192 })).channels).toBe(6);
+ const same = audio({ channels: 2, bitrate: 192 });
+ expect(resolveSequenceAudioSettings(stereo, same)).toBe(same);
+ });
+});
+
+describe("ffmpeg arguments", () => {
+ it("5.1 relabels L R C LFE Ls Rs by index to the encoder's 5.1(side) layout, then encodes at the offered rate with dialnorm", () => {
+ expect(dolbyEncodeArgs({ codec: "ac3", channels: 6, bitrateKbps: 448, sampleRate: 48000, dialnorm: -27 })).toEqual([
+ "-af", DOLBY_5_1_CHANNELMAP,
+ "-c:a", "ac3", "-b:a", "448k", "-ar", "48000", "-dialnorm", "-27",
+ ]);
+ expect(DOLBY_5_1_CHANNELMAP).toBe("channelmap=map=0|1|2|3|4|5:channel_layout=5.1(side)");
+ });
+
+ it("stereo has no channel filter; E-AC-3 uses the eac3 encoder; 96 kHz and odd bitrates are corrected", () => {
+ expect(dolbyEncodeArgs({ codec: "eac3", channels: 2, bitrateKbps: 1000, sampleRate: 96000, dialnorm: -99 })).toEqual([
+ "-c:a", "eac3", "-b:a", "1024k", "-ar", "48000", "-dialnorm", "-31",
+ ]);
+ });
+});
+
+describe("routing and validation", () => {
+ const base = (patch: Partial<VideoExportSettings> = {}): VideoExportSettings => ({ ...DEFAULT_VIDEO_SETTINGS, ...patch });
+
+ it("MKV and Dolby audio need the native encoder; plain MP4 with AAC does not", () => {
+ expect(exportSettingsRequireNativeEncoder(base())).toBe(false);
+ expect(exportSettingsRequireNativeEncoder(base({ format: "mkv" }))).toBe(true);
+ expect(exportSettingsRequireNativeEncoder(base({ audioSettings: audio({ format: "eac3" }) }))).toBe(true);
+ expect(desktopExportRequiresNativeEncoder(base({ audioSettings: audio() }))).toBe(true);
+ });
+
+ it("validation refuses Dolby audio in WebM and MXF", () => {
+ expect(getVideoExportValidationError(base({ audioSettings: audio() }), 10)).toBeNull();
+ expect(getVideoExportValidationError(base({ format: "webm", codec: "vp9", audioSettings: audio() }), 10)).toMatch(/WebM cannot carry/);
+ });
+});
diff --git a/packages/core/src/export/dolby.ts b/packages/core/src/export/dolby.ts
new file mode 100644
index 00000000..37694f0b
--- /dev/null
+++ b/packages/core/src/export/dolby.ts
@@ -0,0 +1,178 @@
+/**
+ * Dolby Digital (AC-3) and Dolby Digital Plus (E-AC-3) delivery: the pure rules shared by the export dialog, the
+ * export engine and the two encoders (the desktop ffmpeg sidecar and the browser's ffmpeg.wasm core).
+ *
+ * Both encoders are ffmpeg's `ac3` / `eac3`. The mix reaches them as a Stereo or 5.1 buffer in the order the 5.1
+ * mixer produces, L R C LFE Ls Rs (Web Audio / SMPTE, WAV mask 0x3F); ffmpeg's `5.1(side)` layout lists the same
+ * six channels in the same order, which is what AC-3 carries (acmod 7 with the LFE flag).
+ */
+
+import type { AudioExportSettings } from "./types";
+
+export type DolbyCodec = "ac3" | "eac3";
+
+/** Audio export formats that are Dolby: the raw elementary stream (`.ac3` / `.ec3`) or the audio track of a video file. */
+export type DolbyAudioFormat = DolbyCodec;
+
+export const DOLBY_CODECS: readonly DolbyCodec[] = ["ac3", "eac3"];
+
+export const isDolbyFormat = (format: string | undefined): format is DolbyAudioFormat => format === "ac3" || format === "eac3";
+
+/** Display names: "Dolby Digital" is AC-3, "Dolby Digital Plus" is E-AC-3. */
+export const DOLBY_LABEL: Record<DolbyCodec, string> = {
+ ac3: "Dolby Digital (AC-3)",
+ eac3: "Dolby Digital Plus (E-AC-3)",
+};
+
+/** File extension of a raw elementary stream: `.ac3` for AC-3, `.ec3` for E-AC-3. */
+export const dolbyFileExtension = (codec: DolbyCodec): "ac3" | "ec3" => (codec === "eac3" ? "ec3" : "ac3");
+
+export const dolbyMimeType = (codec: DolbyCodec): string => (codec === "eac3" ? "audio/eac3" : "audio/ac3");
+
+/**
+ * Bitrates (kbps) the delivery offers. AC-3 is defined from 32 to 640 kbps in fixed steps (ATSC A/52 table
+ * 5.18); the picker offers the broadcast / DVD / Blu-ray range, 192 to 640. E-AC-3 goes higher: the picker stops
+ * at 1024 kbps, the limit of the broadcast and streaming profiles (the encoder itself accepts more).
+ */
+export const DOLBY_BITRATES: Record<DolbyCodec, readonly number[]> = {
+ ac3: [192, 224, 256, 320, 384, 448, 512, 576, 640],
+ eac3: [192, 256, 320, 384, 448, 512, 576, 640, 768, 896, 1024],
+};
+
+/** Every bitrate the AC-3 bitstream can signal, kbps. */
+export const AC3_VALID_BITRATES: readonly number[] = [32, 40, 48, 56, 64, 80, 96, 112, 128, 160, 192, 224, 256, 320, 384, 448, 512, 576, 640];
+
+/** Typical delivery rate: 192 kbps stereo AC-3, 448 kbps 5.1 AC-3 (DVD / broadcast), 640 kbps 5.1 E-AC-3. */
+export function defaultDolbyBitrate(codec: DolbyCodec, channels: number): number {
+ if (codec === "eac3") return channels > 2 ? 640 : 256;
+ return channels > 2 ? 448 : 192;
+}
+
+/** The nearest offered bitrate at or above `kbps` (below the first offer: the first; above the last: the last). */
+export function clampDolbyBitrate(codec: DolbyCodec, kbps: number): number {
+ const options = DOLBY_BITRATES[codec];
+ if (!Number.isFinite(kbps)) return options[0];
+ const requested = Math.round(kbps);
+ return options.find((option) => option >= requested) ?? options[options.length - 1];
+}
+
+/** Dialogue level metadata in dB (dBFS, A-weighted dialogue average): -31 (no attenuation by the decoder) to -1. */
+export const DIALNORM_MIN = -31;
+export const DIALNORM_MAX = -1;
+export const DEFAULT_DIALNORM = -31;
+
+export const clampDialnorm = (value: number): number =>
+ Number.isFinite(value) ? Math.max(DIALNORM_MIN, Math.min(DIALNORM_MAX, Math.round(value))) : DEFAULT_DIALNORM;
+
+/**
+ * The dialnorm to write. An explicit value wins. Without one, a loudness-targeted export declares the target it
+ * normalised to (so a -24 LUFS broadcast mix is flagged -24), and anything else leaves the decoder level alone (-31).
+ */
+export function resolveDialnorm(audio: { dialnorm?: number; loudness?: { enabled?: boolean; targetLufs?: number } }): number {
+ if (audio.dialnorm !== undefined) return clampDialnorm(audio.dialnorm);
+ const loudness = audio.loudness;
+ if (loudness?.enabled && typeof loudness.targetLufs === "number") return clampDialnorm(loudness.targetLufs);
+ return DEFAULT_DIALNORM;
+}
+
+/** AC-3 and E-AC-3 carry 32, 44.1 or 48 kHz; the delivery is 48 kHz and a 96 kHz setting is written at 48 kHz. */
+export const dolbySampleRate = (requested: number): 44100 | 48000 => (requested === 44100 ? 44100 : 48000);
+
+/** Channel counts the delivery supports: stereo and 5.1. */
+export const isDolbyChannelCount = (channels: number): channels is 2 | 6 => channels === 2 || channels === 6;
+
+/** Video containers that carry AC-3 / E-AC-3 (`ac-3` / `ec-3` sample entries in MP4 and MOV, A_AC3 / A_EAC3 in Matroska). */
+export const DOLBY_VIDEO_CONTAINERS: readonly string[] = ["mp4", "mov", "mkv"];
+
+/** Why `container` cannot carry Dolby audio, or null when it can. */
+export function dolbyContainerProblem(container: string): string | null {
+ if (DOLBY_VIDEO_CONTAINERS.includes(container)) return null;
+ if (container === "webm") return "WebM cannot carry AC-3 or E-AC-3 (it takes Opus or Vorbis). Choose MP4, MOV or MKV.";
+ if (container === "mxf") return "MXF deliveries carry PCM audio here. Choose MP4, MOV or MKV for Dolby Digital audio.";
+ return `${container.toUpperCase()} cannot carry AC-3 or E-AC-3.`;
+}
+
+/** Why an AC-3 / E-AC-3 delivery cannot be written with this many channels, or null. */
+export function dolbyChannelsProblem(channels: number): string | null {
+ return isDolbyChannelCount(channels) ? null : "Dolby Digital delivery is stereo or 5.1. Mono and other layouts are not supported.";
+}
+
+/**
+ * The reason Dolby delivery needs the desktop app, shown where the choice is made. The browser build cannot mux
+ * AC-3 into a video file (MediaBunny has no AC-3 track, and WebCodecs has no AC-3 encoder); the audio-only
+ * `.ac3` / `.ec3` export runs on the ffmpeg.wasm core.
+ */
+export const DOLBY_VIDEO_DESKTOP_ONLY_REASON =
+ "AC-3 and E-AC-3 audio in a video file needs the desktop app. The browser muxer (MediaBunny) cannot write an AC-3 track; audio-only .ac3 / .ec3 export works in the browser.";
+
+/** Settings problems of a Dolby delivery (empty when fine); used by validation before any work starts. */
+export function dolbyDeliveryProblems(
+ audio: { format: string; channels: number },
+ container?: string,
+): string[] {
+ if (!isDolbyFormat(audio.format)) return [];
+ const problems: string[] = [];
+ const channels = dolbyChannelsProblem(audio.channels);
+ if (channels) problems.push(channels);
+ if (container) {
+ const problem = dolbyContainerProblem(container);
+ if (problem) problems.push(problem);
+ }
+ return problems;
+}
+
+/**
+ * ffmpeg `-b:a` value for a Dolby delivery; the bitrate is snapped to an offered rate (AC-3 can only signal a
+ * fixed list, an unlisted value would be refused by the encoder or silently rounded).
+ */
+export function dolbyEncoderBitrateKbps(codec: DolbyCodec, requested: number): number {
+ return clampDolbyBitrate(codec, requested);
+}
+
+/**
+ * Where `ffmpeg -i <wav>` puts the channels is already the AC-3 order, so only the label needs fixing: a plain
+ * six-channel WAV reads as 5.1(back) and the encoder carries 5.1(side); `channelmap` by index relabels without
+ * mixing. Measured against the shipped ffmpeg: every channel decodes back at 0.0 dB on its own slot.
+ */
+export const DOLBY_5_1_CHANNELMAP = "channelmap=map=0|1|2|3|4|5:channel_layout=5.1(side)";
+
+/**
+ * The audio settings a Dolby delivery actually uses: 44.1 or 48 kHz, an offered bitrate (a stereo-sized or
+ * AAC-sized value is snapped, an unset one gets the usual rate for the channel count) and the dialnorm to write.
+ * Other formats are returned unchanged.
+ */
+export function resolveDolbyAudioSettings(audio: AudioExportSettings): AudioExportSettings {
+ if (!isDolbyFormat(audio.format)) return audio;
+ const codec = audio.format;
+ const bitrate = audio.bitrate > 0 ? clampDolbyBitrate(codec, audio.bitrate) : defaultDolbyBitrate(codec, audio.channels);
+ return { ...audio, sampleRate: dolbySampleRate(audio.sampleRate), bitrate, dialnorm: resolveDialnorm(audio) };
+}
+
+export interface DolbyEncodeParams {
+ codec: DolbyCodec;
+ /** 2 (stereo) or 6 (5.1, L R C LFE Ls Rs). */
+ channels: number;
+ bitrateKbps: number;
+ sampleRate: number;
+ /** dB, -31 to -1. */
+ dialnorm: number;
+}
+
+/**
+ * The ffmpeg audio options that encode a PCM input into AC-3 / E-AC-3: the `ac3` / `eac3` encoder at an offered
+ * bitrate and 44.1 / 48 kHz, the dialnorm, and for 5.1 the by-index relabel to the encoder's layout. The desktop
+ * sidecar and the browser's ffmpeg.wasm core both run these, so the two deliveries come out the same.
+ */
+export function dolbyEncodeArgs(params: DolbyEncodeParams): string[] {
+ const channels = params.channels > 2 ? 6 : 2;
+ return [
+ ...(channels === 6 ? ["-af", DOLBY_5_1_CHANNELMAP] : []),
+ "-c:a", params.codec,
+ "-b:a", `${clampDolbyBitrate(params.codec, params.bitrateKbps)}k`,
+ "-ar", String(dolbySampleRate(params.sampleRate)),
+ "-dialnorm", String(clampDialnorm(params.dialnorm)),
+ ];
+}
+
+/** ffmpeg muxer of a raw Dolby elementary stream. */
+export const dolbyRawMuxer = (codec: DolbyCodec): "ac3" | "eac3" => codec;
diff --git a/packages/core/src/export/export-engine.test.ts b/packages/core/src/export/export-engine.test.ts
index 94387e36..df61d827 100644
--- a/packages/core/src/export/export-engine.test.ts
+++ b/packages/core/src/export/export-engine.test.ts
@@ -92,6 +92,10 @@ vi.mock("../media/mediabunny-engine", () => ({
getMediaEngine: vi.fn().mockReturnValue(mockMediaEngine),
}));
+const { mockWasmEncode } = vi.hoisted(() => ({ mockWasmEncode: vi.fn() }));
+vi.mock("../media/ffmpeg-fallback", () => ({
+ getFFmpegFallback: () => ({ load: vi.fn().mockResolvedValue(undefined), encodeAudioStream: mockWasmEncode }),
+}));
vi.mock("./audio-priming", () => ({ getAacEncoderPriming: vi.fn().mockResolvedValue(2112) }));
vi.mock("./mp4-audio-timing", () => ({ applyMp4AudioTiming: vi.fn((bytes) => bytes) }));
@@ -832,4 +836,118 @@ describe("ExportEngine", () => {
expect(duration).toBe(3);
});
});
+
+ describe("Dolby Digital delivery", () => {
+ const AC3_BYTES = new Uint8Array([0x0b, 0x77, 1, 2, 3]);
+ const fakeMix = (channels: number, sampleRate = 48000, length = 480): AudioBuffer =>
+ ({
+ numberOfChannels: channels,
+ sampleRate,
+ length,
+ duration: length / sampleRate,
+ getChannelData: (c: number) => Float32Array.from({ length }, (_, i) => (c + 1) * 0.1 * Math.sin(i / 7)),
+ }) as unknown as AudioBuffer;
+ const project = (settings: Partial<Project["settings"]> = {}): Project =>
+ createMockProject({ settings: { ...createMockProject().settings, ...settings }, timeline: createMockTimeline() });
+ const stubMix = (buffer: AudioBuffer) =>
+ vi.spyOn(exportEngine as unknown as { renderTimelineAudio: () => Promise<AudioBuffer> }, "renderTimelineAudio").mockResolvedValue(buffer);
+ const drainAudio = async (p: Project, settings: Record<string, unknown>): Promise<ExportResult> => {
+ await exportEngine.initialize();
+ const generator = exportEngine.exportAudio(p, settings);
+ for (;;) {
+ const { done, value } = await generator.next();
+ if (done) return value;
+ }
+ };
+ const readWav = (wav: ArrayBuffer) => {
+ const view = new DataView(wav);
+ return {
+ channels: view.getUint16(22, true),
+ sampleRate: view.getUint32(24, true),
+ bits: view.getUint16(34, true),
+ mask: view.getUint16(22, true) > 2 ? view.getUint32(40, true) : 0,
+ };
+ };
+
+ it("desktop: a stereo AC-3 file goes to the sidecar as a 24-bit stereo WAV at the offered bitrate", async () => {
+ const encodeDolbyAudio = vi.fn().mockResolvedValue(AC3_BYTES.buffer);
+ vi.stubGlobal("openreel", { platform: "desktop", export: { encodeDolbyAudio } });
+ stubMix(fakeMix(2));
+ const result = await drainAudio(project(), { format: "ac3", sampleRate: 96000, bitrate: 300, channels: 2, bitDepth: 24 });
+ expect(result).toMatchObject({ success: true });
+ expect(result.blob?.type).toBe("audio/ac3");
+ expect(new Uint8Array(await result.blob!.arrayBuffer())).toEqual(AC3_BYTES);
+ const call = encodeDolbyAudio.mock.calls[0][0];
+ expect(call).toMatchObject({ codec: "ac3", channels: 2, bitrateKbps: 320, sampleRate: 48000, dialnorm: -31 });
+ expect(readWav(call.wav)).toMatchObject({ channels: 2, bits: 24 });
+ });
+
+ it("desktop: a 5.1 sequence sends six channels with the 5.1 speaker mask (L R C LFE Ls Rs) and at least 384 kbps; dialnorm follows the loudness target", async () => {
+ const encodeDolbyAudio = vi.fn().mockResolvedValue(AC3_BYTES.buffer);
+ vi.stubGlobal("openreel", { platform: "desktop", export: { encodeDolbyAudio } });
+ stubMix(fakeMix(6));
+ // The loudness step rebuilds the buffer through the Web Audio AudioBuffer constructor.
+ vi.stubGlobal("AudioBuffer", class {
+ readonly numberOfChannels: number; readonly sampleRate: number; readonly length: number;
+ private readonly data: Float32Array[];
+ constructor(o: { length: number; numberOfChannels: number; sampleRate: number }) {
+ Object.assign(this, o);
+ this.numberOfChannels = o.numberOfChannels; this.sampleRate = o.sampleRate; this.length = o.length;
+ this.data = Array.from({ length: o.numberOfChannels }, () => new Float32Array(o.length));
+ }
+ getChannelData(c: number) { return this.data[c]; }
+ copyToChannel(d: Float32Array, c: number) { this.data[c].set(d); }
+ });
+ const result = await drainAudio(project({ channels: 6, channelLayout: "5.1" }), {
+ format: "eac3", sampleRate: 48000, bitrate: 192, channels: 2, bitDepth: 24,
+ loudness: { enabled: true, targetLufs: -24, truePeakCeilingDb: -2 },
+ });
+ expect(result).toMatchObject({ success: true });
+ expect(result.blob?.type).toBe("audio/eac3");
+ const call = encodeDolbyAudio.mock.calls[0][0];
+ expect(call).toMatchObject({ codec: "eac3", channels: 6, bitrateKbps: 384, dialnorm: -24 });
+ expect(readWav(call.wav)).toMatchObject({ channels: 6, mask: 0x3f, bits: 24 });
+ });
+
+ it("browser: encodes on the ffmpeg.wasm core with the same arguments, the 5.1 relabel included", async () => {
+ vi.stubGlobal("openreel", undefined);
+ mockWasmEncode.mockResolvedValue(AC3_BYTES);
+ stubMix(fakeMix(6));
+ const result = await drainAudio(project({ channels: 6, channelLayout: "5.1" }), { format: "ac3", sampleRate: 48000, bitrate: 448, channels: 2, bitDepth: 24, dialnorm: -27 });
+ expect(result).toMatchObject({ success: true });
+ const [wav, args, muxer, extension] = mockWasmEncode.mock.calls[0];
+ expect(wav).toBeInstanceOf(Uint8Array);
+ expect(args).toEqual(["-af", "channelmap=map=0|1|2|3|4|5:channel_layout=5.1(side)", "-c:a", "ac3", "-b:a", "448k", "-ar", "48000", "-dialnorm", "-27"]);
+ expect([muxer, extension]).toEqual(["ac3", "ac3"]);
+ });
+
+ it("refuses mono and other layouts", async () => {
+ stubMix(fakeMix(1));
+ const result = await drainAudio(project(), { format: "ac3", sampleRate: 48000, bitrate: 192, channels: 1, bitDepth: 24 });
+ expect(result.success).toBe(false);
+ expect(result.error).toMatchObject({ code: "INVALID_SETTINGS" });
+ expect(result.error?.message).toMatch(/stereo or 5.1/);
+ });
+
+ it("the browser video exporter refuses an AC-3 track and MKV with a desktop-only reason, before any work", async () => {
+ await exportEngine.initialize();
+ const run = async (settings: Record<string, unknown>) => {
+ const generator = exportEngine.exportVideo(project(), { ...DEFAULT_VIDEO_SETTINGS, frameRate: 1, width: 640, height: 360, ...settings }, {} as FileSystemWritableFileStream);
+ for (;;) {
+ const { done, value } = await generator.next();
+ if (done) return value;
+ }
+ };
+ const dolby = await run({ audioSettings: { ...DEFAULT_VIDEO_SETTINGS.audioSettings, format: "ac3", bitrate: 448 } });
+ expect(dolby.success).toBe(false);
+ expect(dolby.error).toMatchObject({ code: "UNSUPPORTED_CODEC" });
+ expect(dolby.error?.message).toMatch(/needs the desktop app/);
+ const mkv = await run({ format: "mkv" });
+ expect(mkv.error).toMatchObject({ code: "UNSUPPORTED_CODEC" });
+ expect(mkv.error?.message).toMatch(/MKV export needs the desktop app/);
+ const webm = await run({ format: "webm", codec: "vp9", audioSettings: { ...DEFAULT_VIDEO_SETTINGS.audioSettings, format: "eac3", bitrate: 640 } });
+ expect(webm.error).toMatchObject({ code: "INVALID_SETTINGS" });
+ expect(webm.error?.message).toMatch(/WebM cannot carry/);
+ });
+ });
});
diff --git a/packages/core/src/export/export-engine.ts b/packages/core/src/export/export-engine.ts
index 2af64540..abfaf04b 100644
--- a/packages/core/src/export/export-engine.ts
+++ b/packages/core/src/export/export-engine.ts
@@ -23,6 +23,7 @@ import {
import { VideoEngine, getVideoEngine } from "../video/video-engine";
import { AudioEngine, getAudioEngine } from "../audio/audio-engine";
import { downmixSurroundToStereo, isSurroundLayout } from "../audio/surround";
+import { DEFAULT_DIALNORM, DOLBY_VIDEO_DESKTOP_ONLY_REASON, dolbyChannelsProblem, dolbyDeliveryProblems, dolbyMimeType, isDolbyFormat, resolveDolbyAudioSettings, type DolbyCodec } from "./dolby";
import { encodeMultichannelWav, isSurroundDelivery, resolveSequenceAudioSettings, surroundFormatProblem } from "./surround-export";
import { audioBufferFromChunk, renderMixdownCached } from "../audio/mixdown-cache";
import { titleEngine } from "../text/title-engine";
@@ -239,6 +240,11 @@ export class ExportEngine {
fullSettings.audioSettings = resolveSequenceAudioSettings(project, fullSettings.audioSettings);
const surroundProblem = isSurroundDelivery(fullSettings.audioSettings) ? surroundFormatProblem(fullSettings.format) : null;
if (surroundProblem) return { success: false, error: this.createError("INVALID_SETTINGS", surroundProblem, "preparing") };
+ if (isDolbyFormat(fullSettings.audioSettings.format)) {
+ const dolbyProblem = dolbyDeliveryProblems(fullSettings.audioSettings, fullSettings.format)[0];
+ if (dolbyProblem) return { success: false, error: this.createError("INVALID_SETTINGS", dolbyProblem, "preparing") };
+ fullSettings.audioSettings = resolveDolbyAudioSettings(fullSettings.audioSettings);
+ }
const encoderBackendFactory = getEncoderBackendFactory();
const backend: EncoderBackend = encoderBackendFactory
@@ -250,6 +256,9 @@ export class ExportEngine {
: {}),
});
+ if (backend.normalizesProResToH264 && (fullSettings.format === "mkv" || isDolbyFormat(fullSettings.audioSettings.format))) {
+ return { success: false, error: this.createError("UNSUPPORTED_CODEC", fullSettings.format === "mkv" ? "MKV export needs the desktop app. Choose MP4, MOV or WebM." : DOLBY_VIDEO_DESKTOP_ONLY_REASON, "preparing") };
+ }
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") };
}
@@ -735,12 +744,18 @@ export class ExportEngine {
...settings,
};
// A 5.1 sequence exports a six-channel WAV; the other audio formats are stereo, so they get the downmix.
- const fullSettings: AudioExportSettings = resolveSequenceAudioSettings(
+ let fullSettings: AudioExportSettings = resolveSequenceAudioSettings(
project,
- requested.format === "wav" ? requested : { ...requested, channelLayout: "stereo" },
+ requested.format === "wav" || isDolbyFormat(requested.format) ? requested : { ...requested, channelLayout: "stereo" },
);
- if (!this.mediabunny && fullSettings.format !== "wav") {
+ if (isDolbyFormat(fullSettings.format)) {
+ const problem = dolbyChannelsProblem(fullSettings.channels);
+ if (problem) return { success: false, error: this.createError("INVALID_SETTINGS", problem, "preparing") };
+ fullSettings = resolveDolbyAudioSettings(fullSettings);
+ }
+
+ if (!this.mediabunny && fullSettings.format !== "wav" && !isDolbyFormat(fullSettings.format)) {
return {
success: false,
error: this.createError(
@@ -796,6 +811,8 @@ export class ExportEngine {
if (fullSettings.format === "wav") {
blob = this.encodeWav(audioBuffer, fullSettings);
+ } else if (isDolbyFormat(fullSettings.format)) {
+ blob = await this.encodeDolbyAudioBlob(audioBuffer, fullSettings, this.abortController?.signal);
} else {
// Use MediaBunny for other formats
blob = await this.encodeAudioWithMediaBunny(audioBuffer, fullSettings);
@@ -1254,6 +1271,20 @@ export class ExportEngine {
sampleRate: 48000,
},
},
+ {
+ id: "audio-ac3",
+ name: "Dolby Digital (AC-3) Audio",
+ description: "Raw .ac3 stream, 192 kbps stereo or 5.1 at 384 kbps or more",
+ category: "broadcast",
+ settings: { ...DEFAULT_AUDIO_SETTINGS, format: "ac3", bitDepth: 24, bitrate: 192 },
+ },
+ {
+ id: "audio-eac3",
+ name: "Dolby Digital Plus (E-AC-3) Audio",
+ description: "Raw .ec3 stream, 256 kbps stereo or 5.1 at 384 kbps or more",
+ category: "broadcast",
+ settings: { ...DEFAULT_AUDIO_SETTINGS, format: "eac3", bitDepth: 24, bitrate: 256 },
+ },
];
}
@@ -1564,6 +1595,23 @@ export class ExportEngine {
});
}
+ /**
+ * AC-3 / E-AC-3 elementary stream (`.ac3` / `.ec3`) of the mixdown. The mix is already stereo or L R C LFE Ls Rs;
+ * it goes to the encoder as a 24-bit WAV (the 5.1 one carries the speaker mask) and ffmpeg does the rest.
+ */
+ private async encodeDolbyAudioBlob(buffer: AudioBuffer, settings: AudioExportSettings, signal?: AbortSignal): Promise<Blob> {
+ const codec = settings.format as DolbyCodec;
+ const channels = buffer.numberOfChannels >= 6 ? 6 : 2;
+ const planes = Array.from({ length: channels }, (_, c) => buffer.getChannelData(Math.min(c, buffer.numberOfChannels - 1)));
+ const wav = encodeMultichannelWav(planes, buffer.sampleRate, 24);
+ const { encodeDolbyStream } = await import("./dolby-encode");
+ const bytes = await encodeDolbyStream({
+ wav,
+ params: { codec, channels, bitrateKbps: settings.bitrate, sampleRate: buffer.sampleRate, dialnorm: settings.dialnorm ?? DEFAULT_DIALNORM },
+ }, signal);
+ return new Blob([bytes.buffer as ArrayBuffer], { type: dolbyMimeType(codec) });
+ }
+
private encodeWav(buffer: AudioBuffer, settings: AudioExportSettings): Blob {
const numberOfChannels = Math.min(
buffer.numberOfChannels,
@@ -1656,6 +1704,9 @@ export class ExportEngine {
return "audio/flac";
case "ogg":
return "audio/ogg";
+ case "ac3":
+ case "eac3":
+ return dolbyMimeType(format);
default:
return "audio/mpeg";
}
@@ -1834,9 +1885,9 @@ export function hasBroadcastOptions(broadcast: BroadcastDeliverySettings | undef
}
export function exportSettingsRequireNativeEncoder(
- settings: Pick<VideoExportSettings, "codec" | "format"> & Partial<Pick<VideoExportSettings, "colorDepth" | "pixelFormat" | "broadcast">>,
+ settings: Pick<VideoExportSettings, "codec" | "format"> & Partial<Pick<VideoExportSettings, "colorDepth" | "pixelFormat" | "broadcast" | "audioSettings">>,
): boolean {
- return settings.codec === "prores" || settings.codec === "dnxhr" || isBroadcastCodec(settings.codec) || hasBroadcastOptions(settings.broadcast) || settings.format === "mxf" || (settings.colorDepth ?? 8) > 8 || Boolean(settings.pixelFormat && settings.pixelFormat !== "yuv420");
+ return settings.format === "mkv" || isDolbyFormat(settings.audioSettings?.format) || settings.codec === "prores" || settings.codec === "dnxhr" || isBroadcastCodec(settings.codec) || hasBroadcastOptions(settings.broadcast) || settings.format === "mxf" || (settings.colorDepth ?? 8) > 8 || Boolean(settings.pixelFormat && settings.pixelFormat !== "yuv420");
}
/**
@@ -1845,7 +1896,7 @@ export function exportSettingsRequireNativeEncoder(
* The web build keeps using exportSettingsRequireNativeEncoder, where HDR goes through WebCodecs when it can.
*/
export function desktopExportRequiresNativeEncoder(
- settings: Pick<VideoExportSettings, "codec" | "format"> & Partial<Pick<VideoExportSettings, "colorDepth" | "pixelFormat" | "hdr" | "broadcast">>,
+ settings: Pick<VideoExportSettings, "codec" | "format"> & Partial<Pick<VideoExportSettings, "colorDepth" | "pixelFormat" | "hdr" | "broadcast" | "audioSettings">>,
): boolean {
return exportSettingsRequireNativeEncoder(settings) || settings.hdr === "pq" || settings.hdr === "hlg";
}
diff --git a/packages/core/src/export/index.ts b/packages/core/src/export/index.ts
index 6bb6def2..8614dcf2 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 "./dolby";
export * from "./encoder-choice";
export * from "./export-engine";
export * from "./loudness-export";
diff --git a/packages/core/src/export/surround-export.ts b/packages/core/src/export/surround-export.ts
index df652f12..a73a908b 100644
--- a/packages/core/src/export/surround-export.ts
+++ b/packages/core/src/export/surround-export.ts
@@ -2,7 +2,7 @@ import type { Project } from "../types/project";
import { getChannelLayout, SURROUND_CHANNELS, type ChannelLayout } from "../audio/surround";
import type { AudioExportSettings } from "./types";
-/** 5.1 AAC below this sounds poor; a stereo-sized bitrate is raised to it. */
+/** 5.1 AAC (and AC-3 / E-AC-3) below this sounds poor; a stereo-sized bitrate is raised to it. */
export const SURROUND_MIN_AAC_BITRATE_KBPS = 384;
/** Windows channel mask of a 5.1 file: FL FR FC LFE BL BR (the order L R C LFE Ls Rs is stored in). */
@@ -32,7 +32,7 @@ export function resolveSequenceAudioSettings(project: Pick<Project, "settings">,
export const isSurroundDelivery = (audio: Pick<AudioExportSettings, "channels">): boolean => audio.channels > 2;
/** Why a 6-channel delivery cannot be written in `format`, or null when it can. */
-export function surroundFormatProblem(videoFormat: "mp4" | "webm" | "mov" | "mxf"): string | null {
+export function surroundFormatProblem(videoFormat: "mp4" | "webm" | "mov" | "mxf" | "mkv"): string | null {
return videoFormat === "webm"
? "5.1 audio needs AAC, which MP4 and MOV carry. WebM export is stereo: switch the container to MP4 or MOV, or set the audio to Stereo."
: null;
diff --git a/packages/core/src/export/types.ts b/packages/core/src/export/types.ts
index a3e9337e..64c7058b 100644
--- a/packages/core/src/export/types.ts
+++ b/packages/core/src/export/types.ts
@@ -30,7 +30,8 @@ export function effectiveRateControl(settings: { rateControl?: RateControl; bitr
}
export interface VideoExportSettings {
- format: "mp4" | "webm" | "mov" | "mxf";
+ /** "mkv" (Matroska) is desktop only; it carries H.264 / H.265 / AV1 / VP9 with AAC, Opus or Dolby Digital audio. */
+ format: "mp4" | "webm" | "mov" | "mxf" | "mkv";
codec: "h264" | "h265" | "vp8" | "vp9" | "av1" | "prores" | "dnxhr" | BroadcastCodec;
proresProfile?: "proxy" | "lt" | "standard" | "hq" | "4444" | "4444xq";
/** DNxHR flavour (codec "dnxhr", MOV or MXF, desktop only). HQ when omitted. */
@@ -102,7 +103,12 @@ export interface VideoExportSettings {
}
export interface AudioExportSettings {
- format: "mp3" | "wav" | "aac" | "flac" | "ogg";
+ /**
+ * "ac3" / "eac3" are Dolby Digital / Dolby Digital Plus (stereo or 5.1, see ./dolby). As the audio-only format
+ * they write a raw `.ac3` / `.ec3` stream; as a video export's audio format they are the audio track of an
+ * MP4, MOV or MKV (desktop only).
+ */
+ format: "mp3" | "wav" | "aac" | "flac" | "ogg" | "ac3" | "eac3";
sampleRate: 44100 | 48000 | 96000;
bitDepth: 16 | 24 | 32;
bitrate: number;
@@ -118,6 +124,11 @@ export interface AudioExportSettings {
* on `targetLufs` and keep true peaks under the ceiling. Omitted = off.
*/
loudness?: LoudnessTargetSettings;
+ /**
+ * AC-3 / E-AC-3 only: dialogue-normalisation metadata in dB, -31 (default, the decoder leaves the level alone)
+ * to -1. Omitted = the loudness target when loudness normalisation is on, else -31.
+ */
+ dialnorm?: number;
}
export interface ImageExportSettings {
diff --git a/packages/core/src/export/webcodecs-backend.ts b/packages/core/src/export/webcodecs-backend.ts
index 0e35594f..007f4eb2 100644
--- a/packages/core/src/export/webcodecs-backend.ts
+++ b/packages/core/src/export/webcodecs-backend.ts
@@ -11,6 +11,7 @@ import type { Project } from "../types/project";
import type { EncoderBackend, SmartRenderMuxer } from "./encoder-backend";
import { descriptionBytes, parameterSetKey, parseAvcC, prependParameterSets, type AvcParameterSets } from "./avc-config";
import { getAacEncoderPriming } from "./audio-priming";
+import { DOLBY_VIDEO_DESKTOP_ONLY_REASON, isDolbyFormat } from "./dolby";
import { applyMp4AudioTiming, applyMovChannelLayout } from "./mp4-audio-timing";
import { CHAN_TAG_MPEG_5_1_A } from "./surround-export";
import { reorderChannels, resolveAacSurroundOrder } from "./aac-surround-order";
@@ -127,6 +128,8 @@ export class WebCodecsBackend implements EncoderBackend {
if (!writableStream) {
throw new Error("No writable stream provided. Export requires a file destination.");
}
+ if (settings.format === "mkv") throw new Error("MKV export needs the desktop app. Choose MP4, MOV or WebM.");
+ if (isDolbyFormat(settings.audioSettings.format)) throw new Error(DOLBY_VIDEO_DESKTOP_ONLY_REASON);
const {
Output,
diff --git a/packages/core/src/index.ts b/packages/core/src/index.ts
index 3029abe5..4be63a0d 100644
--- a/packages/core/src/index.ts
+++ b/packages/core/src/index.ts
@@ -374,6 +374,7 @@ export type {
ParsedLoc,
} from "./interchange/marker-export";
export * from "./export/surround-export";
+export * from "./export/dolby";
export {
translateCaptionTrack,
diff --git a/packages/core/src/media/ffmpeg-fallback.ts b/packages/core/src/media/ffmpeg-fallback.ts
index ed3caadc..5ac83c5f 100644
--- a/packages/core/src/media/ffmpeg-fallback.ts
+++ b/packages/core/src/media/ffmpeg-fallback.ts
@@ -729,6 +729,32 @@ export class FFmpegFallback {
}
}
+ /**
+ * Encodes a PCM WAV with the given ffmpeg audio options into a raw elementary stream (AC-3 / E-AC-3). The
+ * bundled core carries the `ac3` / `eac3` encoders and the raw `ac3` / `eac3` muxers.
+ */
+ async encodeAudioStream(
+ wav: Uint8Array,
+ encodeArgs: readonly string[],
+ muxer: string,
+ extension: string,
+ ): Promise<Uint8Array> {
+ await this.load();
+ this.ensureLoaded();
+ const operationId = crypto.randomUUID();
+ const inputFilename = `enc_${operationId}.wav`;
+ const outputFilename = `enc_${operationId}.${extension}`;
+ try {
+ await this.ffmpeg!.writeFile(inputFilename, wav);
+ const exitCode = await this.ffmpeg!.exec(["-y", "-i", inputFilename, "-vn", ...encodeArgs, "-f", muxer, outputFilename]);
+ if (exitCode !== 0) throw new Error(`FFmpeg could not encode the audio (exit code ${exitCode})`);
+ const data = await this.ffmpeg!.readFile(outputFilename);
+ return data.slice();
+ } finally {
+ await this.cleanupFiles([inputFilename, outputFilename]);
+ }
+ }
+
async extractFrame(
file: File | Blob,
timestamp: number,
diff --git a/packages/core/src/types/effects.ts b/packages/core/src/types/effects.ts
index 6cfef37b..38677917 100644
--- a/packages/core/src/types/effects.ts
+++ b/packages/core/src/types/effects.ts
@@ -564,6 +564,7 @@ export const AUDIO_EFFECT_TYPES = [
"gate",
"brickwallLimiter",
"lowPass",
+ "spectralRepair",
"fadeIn",
"fadeOut",
] as const;