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

ACES colour management, .prproj import and faster desktop start (#128)

Augustus Otu1de5139c0f50
diff --git a/.github/workflows/desktop-readiness.yml b/.github/workflows/desktop-readiness.yml
index 60a80c9b..acbe91a6 100644
--- a/.github/workflows/desktop-readiness.yml
+++ b/.github/workflows/desktop-readiness.yml
@@ -128,6 +128,7 @@ jobs:
run: pnpm --filter @openreel/desktop build
env:
VITE_OPENREEL_E2E: '1'
+ NODE_OPTIONS: --max-old-space-size=6144
- name: Typecheck desktop
run: pnpm --filter @openreel/desktop typecheck
diff --git a/.github/workflows/perf-gate.yml b/.github/workflows/perf-gate.yml
index 5a3fd730..49acbdce 100644
--- a/.github/workflows/perf-gate.yml
+++ b/.github/workflows/perf-gate.yml
@@ -52,6 +52,8 @@ jobs:
- run: pnpm install --frozen-lockfile
- run: pnpm build:wasm
- run: pnpm --filter @openreel/desktop build
+ env:
+ NODE_OPTIONS: --max-old-space-size=6144
- name: Check budgets
run: |
mkdir -p perf-out
diff --git a/apps/desktop/PERF.md b/apps/desktop/PERF.md
index 32f2f038..6eaa7f7f 100644
--- a/apps/desktop/PERF.md
+++ b/apps/desktop/PERF.md
@@ -188,6 +188,98 @@ wall-clock deltas of that size are inside run-to-run noise. A larger step needs
remaining engines (video, motion, audio, ~1.4 MB, kept alive by the project store importing them)
moved behind lazy imports, which is a store-architecture change not done here.
+## Cold start round 2 (perf/cold-start-r2)
+
+Starting point: `cold.median.editorInteractiveFromSpawnMs` about 1,225 ms at machine load ~7 (base `8f928b3df`).
+The question was what sits between the welcome screen and the editor when the click is instant.
+
+### Where the time went (Chromium trace + V8 CPU profile, `OPENREEL_PERF_TRACE_EXTRA`)
+
+`perf-trace-preload.cjs` accepts `OPENREEL_PERF_TRACE_EXTRA="v8.wasm,disabled-by-default-v8.cpu_profiler,toplevel"`
+(comma separated extra trace categories); the profile samples show native frames, so a blocked main thread is
+attributable. Every cold trace had one main-thread task of **158-178 ms with 3-7 ms of CPU** between the editor chunk's
+compile and `openreel:engine:start`. The profile put it in `MasterTimelineClock`'s `new AudioContext()`
+(`getPlaybackController()` runs first in `engine-store.initialize`): the **first AudioContext of an app run blocks its
+constructor ~150-170 ms** (output-device discovery in the audio service), even at load 3.6. A micro-benchmark (bare
+Electron window, `new AudioContext()`; apps/desktop is not involved):
+
+| first `new AudioContext()` | ms |
+|---|---|
+| plain | 155-175 |
+| `latencyHint`, `sampleRate` variants | no change |
+| `--disable-features=AudioServiceOutOfProcess` | 90-95 (architecture change, not taken) |
+| `--enable-features=AudioServiceLaunchOnStartup` | 120-130 (no gain once enumeration is warm) |
+| a second renderer already created one | 3.8 |
+| `navigator.mediaDevices.enumerateDevices()` (async) issued 150-800 ms earlier | **46-50** (60-70 if issued 150 ms earlier, while enumeration is still running) |
+
+`enumerateDevices()` is asynchronous (it takes ~270 ms in the background and costs the main thread nothing), walks the
+same device list, and with no capture permission returns unlabelled entries, so it neither prompts nor reveals
+anything. `DesktopApp` now calls `warmAudioDevices(navigator)` (`src/desktop/audio-warmup.ts`) in the effect that
+marks the welcome screen mounted, i.e. after it is committed. macOS only was measured; Windows and Linux were not.
+
+### Interleaved A/B (A = `8f928b3df`, B = this branch)
+
+Real harness `cold` scenario (the budgeted metric), 8 alternating A/B launches, medians, ms. Load average per pair
+11.6 13.2 11.3 11.6 9.8 8.6 8.5 7.5 (the machine runs other agents' work; all numbers are "loaded", none is idle):
+
+| | A | B | B - A (median of pairs) |
+|---|---|---|---|
+| `editorInteractiveFromSpawnMs` | 1227 | 1150 | **-73** |
+| `welcomeVisibleMs` | 661 | 635 | -9 |
+| `clickToEditorInteractiveMs` (Playwright wall) | 455 | 373 | -82 |
+| `clickToEditorInPageMs` (pointerdown to first frame) | 155 | 161 | -4 |
+
+Chromium-trace A/B (`perf-ab.mjs`, 8 pairs, load 6.2-7.9), medians:
+
+| `traceCold` | A | B | pairDiff |
+|---|---|---|---|
+| `editorInteractiveFromSpawnMs` | 1211 | 1181 | -39 |
+| `clickToEditorInteractiveMs` | 528 | 405 | -121 |
+| `startupWallMs` / `startupCpuMs` | 254.6 / 98.2 | 251.9 / 98.5 | -2.7 / +0.6 |
+| `enterCpuMs` | 136.7 | 130.3 | -1.7 |
+| `totalCpuMs` / `totalCompileCpuMs` | 413 / 94.5 | 425 / 96.5 | +10 / +2.7 |
+| `warmCpuMs` | 190 | 200.4 | +13 |
+
+CPU did **not** go down: the enumeration adds about 10 ms of main-thread work (IPC replies) to the warm window; what
+shrinks is the blocked wall time. The `traceDwell` rows (human-speed click) are unchanged (`enterCpuMs` +1.4,
+`clickToEditorInteractiveMs` -8, `totalCpuMs` +12): a user who waits has the editor warm either way, the gain is for a
+click that lands while the warm-up is still running. `traceCached` (repeat launch, code cache): compile 10.8 ms, produce
+0 in both trees, so the cache path is unaffected.
+
+Where the enumeration is issued matters (each variant 8 interleaved pairs against the base, real `cold`):
+
+| variant | `editorInteractiveFromSpawnMs` pairDiff | `welcomeVisibleMs` pairDiff |
+|---|---|---|
+| issued from the preload (first thing in the renderer) | -63 | **+31** (the browser-side enumeration slows the first paint) |
+| issued when the welcome screen mounts (kept) | -73 | -9 |
+
+### Tried and rejected (all measured, interleaved)
+
+- **Serve built `.js`/`.css` from memory in the `app://` handler** instead of `net.fetch(file://)`: the warm-up's ~55
+ chunk requests did complete sooner (all done 33 ms after the burst vs 65 ms), and the code cache kept working, but the
+ editor opened 116-133 ms **later** (5 pairs, click to interactive +116). Not kept; the cause was not isolated.
+- **Start the warm-up right after the welcome's first paint (rAF + timeout) instead of an idle callback, run the effects
+ bridge in parallel with the engine init, prefetch the `mediabunny` chunk, and drop the eager 1920x1080 title canvas**:
+ on top of the audio warm-up, 6 pairs: `editorInteractiveFromSpawnMs` pairDiff +5 (click to interactive -61, but the
+ welcome screen moved later by the same amount). No net gain, so none of it was kept. (The title canvas was not the
+ blocking call; the profile showed the AudioContext.)
+- **Register `protocol.handle` after `createWindow()`** to overlap its 35-45 ms with the renderer starting: the page
+ never loaded (the navigation does not wait for the handler). Reverted.
+- **`experimentalMinChunkSize` 150k / 300k**: chunks on the editor path 57 -> 54 / 53 but compile CPU 97 -> 108 and no
+ wall gain.
+- **Vibrancy / `hiddenInset` cost in the `BrowserWindow` constructor**: 56-78 ms with it, 71-89 ms without (bare window);
+ it is the constructor itself, not those options.
+- A V8 code cache for the renderer already exists (`v8CacheOptions: "bypassHeatCheck"`, `codeCache: true`); `traceCached`
+ above shows it working. A *first* launch still compiles everything, which is what the harness measures.
+
+### What is left
+
+One main-thread block remains on the path: the first `AudioContext` still costs ~48 ms after the warm-up, plus the
+`EditorInterface` first commit (React 66 ms inclusive, 33 ms layout, 497 buttons / 164 Popper / 99 DropdownMenu mounted at
+once). Making the audio graph lazy until first play touches `MasterTimelineClock`, `RealtimeAudioGraph`, `AudioEngine` and
+`Preview`'s mount effects, which was not attempted here. The wall-clock budget stays 1200 ms: the measured 1150-1181 ms was
+taken at load 6-13, not on the idle machine the budget is defined for, so it is not tightened on that evidence.
+
## Desktop ingest + proxies (w9)
Proxies on desktop are built by the main process with the native ffmpeg sidecar (`src/main/ingest/`):
diff --git a/apps/desktop/scripts/perf-budgets.json b/apps/desktop/scripts/perf-budgets.json
index 479561ba..f564538d 100644
--- a/apps/desktop/scripts/perf-budgets.json
+++ b/apps/desktop/scripts/perf-budgets.json
@@ -52,12 +52,12 @@
"note": "main-thread tasks > 50 ms inside the enter-editor window"
},
"traceCold.median.totalCpuMs": {
- "max": 600,
+ "max": 540,
"note": "renderer main-thread CPU, navigation start -> editor interactive (clicking as soon as the welcome screen shows)"
},
"traceCold.median.totalCompileCpuMs": {
- "max": 120,
- "note": "all v8 compile on that path"
+ "max": 110,
+ "note": "all v8 compile on that path. 122 before the agent stack and three left the editor's static closure, 95 after (interleaved A/B at load ~10)"
},
"traceCold.median.totalChunksCompiled": {
"max": 58,
diff --git a/apps/desktop/scripts/perf-trace-preload.cjs b/apps/desktop/scripts/perf-trace-preload.cjs
index c42eca3c..4c85de5a 100644
--- a/apps/desktop/scripts/perf-trace-preload.cjs
+++ b/apps/desktop/scripts/perf-trace-preload.cjs
@@ -31,7 +31,15 @@ app
.whenReady()
.then(() =>
contentTracing.startRecording({
- included_categories: ["devtools.timeline", "disabled-by-default-devtools.timeline", "v8", "blink.user_timing", "loading"],
+ included_categories: [
+ "devtools.timeline",
+ "disabled-by-default-devtools.timeline",
+ "v8",
+ "blink.user_timing",
+ "loading",
+ // Extra categories for investigations only (OPENREEL_PERF_TRACE_EXTRA="v8.wasm,disabled-by-default-v8.cpu_profiler").
+ ...(process.env.OPENREEL_PERF_TRACE_EXTRA ? process.env.OPENREEL_PERF_TRACE_EXTRA.split(",") : []),
+ ],
recording_mode: "record-until-full",
}),
)
diff --git a/apps/web/bundle-budgets.json b/apps/web/bundle-budgets.json
index 69c71684..7c1752d1 100644
--- a/apps/web/bundle-budgets.json
+++ b/apps/web/bundle-budgets.json
@@ -3,8 +3,8 @@
"budgets": {
"entry": {
"rawKb": 640,
- "gzipKb": 180,
- "note": "startup entry chunk: everything the first paint compiles and evaluates. w9: video/motion/audio engines, action handlers, export engine and schema normalizers are behind services/lazy-engines (1988 KB / 568.8 KB gzip before; 608.5 / 179.0 after). Entry diet: the desktop-only native ffmpeg backend, native decode, path hydration and smart-render load lazily inside main.tsx's isDesktop branch, and the in-thread RAW developer (dng, develop, tiff, color) loads on first use (621.0 / 190.0 before; 577.3 / 174.7 after)"
+ "gzipKb": 182,
+ "note": "startup entry chunk: (1.0 release: 180 -> 182 for ACES project settings and .prproj import wiring; CI Linux measured 180.5) everything the first paint compiles and evaluates. w9: video/motion/audio engines, action handlers, export engine and schema normalizers are behind services/lazy-engines (1988 KB / 568.8 KB gzip before; 608.5 / 179.0 after). Entry diet: the desktop-only native ffmpeg backend, native decode, path hydration and smart-render load lazily inside main.tsx's isDesktop branch, and the in-thread RAW developer (dng, develop, tiff, color) loads on first use (621.0 / 190.0 before; 577.3 / 174.7 after)"
},
"initialJs": {
"rawKb": 1230,
diff --git a/apps/web/e2e/aces-color-lib.ts b/apps/web/e2e/aces-color-lib.ts
new file mode 100644
index 00000000..8bff9196
--- /dev/null
+++ b/apps/web/e2e/aces-color-lib.ts
@@ -0,0 +1,267 @@
+import { expect, type Page } from "@playwright/test";
+import { ensureLumetriFixtures, openWithClips } from "./lumetri-basic-lib";
+import { programMean, seek, settle, undo, redo, waitForPresentedPlayhead } from "./helpers";
+
+export { ensureLumetriFixtures };
+
+interface AcesHook {
+ project: { getState(): any };
+ video: { getVideoEngine(): any };
+ ProjectSerializer: new (storage: unknown) => { exportToJson(project: unknown): string; importFromJson(json: string): any };
+ core: { aces: Record<string, any>; acesOutput: Record<string, any>; hdrWorking: Record<string, any>; colorOutput: Record<string, any> };
+}
+
+export interface AcesProductResult {
+ /** Engine frame, display-referred vs ACES: mean absolute 8-bit difference (the pipeline really changed the pixels). */
+ meanChange: number;
+ /** ACES frame vs the CPU prediction (IDT -> OT of the display-referred frame's own pixels): max and mean 8-bit error. */
+ predictionMax: number;
+ predictionMean: number;
+ /** Same with a warm grade: the grade runs in ACEScct (CPU prediction through `gradeHdrPixel`). */
+ gradedMax: number;
+ gradedMean: number;
+ gradedRedShift: number;
+ gradedBlueShift: number;
+ /** Program monitor centre mean (live preview) in display-referred, in ACES, after undo, after redo, after save / load. */
+ monitor: { base: number[]; aces: number[]; undone: number[]; redone: number[]; reloaded: number[] };
+ /** Engine ACES frame centre mean, for the monitor comparison. */
+ engineAcesMean: number[];
+ settings: { afterMenu: unknown; afterUndo: unknown; afterRedo: unknown; savedJson: unknown; afterLoad: unknown };
+ badge: { shown: boolean; hiddenAfterUndo: boolean };
+ clipOverride: { before: number[]; after: number[]; undone: number[] };
+}
+
+/**
+ * ACES colour management through the product: the Preview options menu switches the project (one undoable step), the
+ * Program monitor and the engine (preview and export share it) render the ACES output transform, grading runs in ACEScct,
+ * the setting survives a save / load round trip, and a per-clip input override changes the picture and undoes.
+ */
+export async function runAcesProductFlow(page: Page): Promise<AcesProductResult> {
+ const [clipId] = await openWithClips(page, ["lumetri-gradient.mp4"]);
+ await seek(page, 1);
+ await settle(page, 900);
+ await waitForPresentedPlayhead(page);
+
+ const W = 640;
+ const H = 360;
+ const engineFrames = () =>
+ page.evaluate(
+ async ({ W, H, clipId }) => {
+ const h = (window as unknown as { __openreelE2E: AcesHook }).__openreelE2E;
+ const hw = h.core.hdrWorking;
+ const aces = h.core.acesOutput;
+ const out = h.core.colorOutput;
+ const engine = h.video.getVideoEngine();
+ const project = h.project.getState().project;
+ const readRgba = async (bitmap: ImageBitmap) => {
+ const c = new OffscreenCanvas(bitmap.width, bitmap.height);
+ const ctx = c.getContext("2d", { willReadFrequently: true })!;
+ ctx.drawImage(bitmap, 0, 0);
+ return ctx.getImageData(0, 0, bitmap.width, bitmap.height).data;
+ };
+ const render = async (p: unknown) => {
+ for (let i = 0; i < 2; i++) await engine.renderFrame(p, 1, W, H);
+ const f = await engine.renderFrame(p, 1, W, H);
+ return readRgba(f.image);
+ };
+ const withSettings = (extra: Record<string, unknown>) => ({ ...project, settings: { ...project.settings, ...extra } });
+ const base = await render(project);
+ const acesPx = await render(withSettings({ colorManagement: "aces" }));
+ const graded = {
+ ...withSettings({ colorManagement: "aces" }),
+ timeline: {
+ ...project.timeline,
+ tracks: project.timeline.tracks.map((t: any) => ({
+ ...t,
+ clips: t.clips.map((c: any) => (c.id === clipId ? { ...c, colorGrading: { temperature: 40 } } : c)),
+ })),
+ },
+ };
+ const gradedPx = await render(graded);
+
+ // CPU prediction from the display-referred frame's own pixels.
+ const pipeline = hw.acesPipeline("srgb");
+ const idt = hw.hdrSourceDecode(null, pipeline).toBt2020 as number[][];
+ const spec = hw.prepareHdrGrade({ temperature: 40 }, pipeline);
+ const rgb = [0, 0, 0];
+ const predict = (r: number, g: number, b: number, grade: boolean): number[] => {
+ const lr = out.srgbToLinear(r / 255);
+ const lg = out.srgbToLinear(g / 255);
+ const lb = out.srgbToLinear(b / 255);
+ let a = [
+ idt[0][0] * lr + idt[0][1] * lg + idt[0][2] * lb,
+ idt[1][0] * lr + idt[1][1] * lg + idt[1][2] * lb,
+ idt[2][0] * lr + idt[2][1] * lg + idt[2][2] * lb,
+ ];
+ if (grade) a = hw.gradeHdrPixel(a[0], a[1], a[2], spec);
+ aces.acesOutputTransform(Math.max(0, a[0]), Math.max(0, a[1]), Math.max(0, a[2]), "srgb", rgb);
+ return rgb.map((v) => v * 255);
+ };
+ const compare = (px: Uint8ClampedArray, grade: boolean) => {
+ let max = 0;
+ let sum = 0;
+ let n = 0;
+ for (let i = 0; i < base.length; i += 4 * 11) {
+ const p = predict(base[i], base[i + 1], base[i + 2], grade);
+ for (let c = 0; c < 3; c++) {
+ const d = Math.abs(px[i + c] - p[c]);
+ if (d > max) max = d;
+ sum += d;
+ n++;
+ }
+ }
+ return { max, mean: sum / n };
+ };
+ let change = 0;
+ let redShift = 0;
+ let blueShift = 0;
+ for (let i = 0; i < base.length; i += 4) {
+ change += Math.abs(base[i] - acesPx[i]) + Math.abs(base[i + 1] - acesPx[i + 1]) + Math.abs(base[i + 2] - acesPx[i + 2]);
+ redShift += gradedPx[i] - acesPx[i];
+ blueShift += gradedPx[i + 2] - acesPx[i + 2];
+ }
+ const n = base.length / 4;
+ const centre = (px: Uint8ClampedArray) => {
+ let r = 0, g = 0, b = 0, m = 0;
+ for (let y = Math.floor(H * 0.25); y < Math.floor(H * 0.75); y++)
+ for (let x = Math.floor(W * 0.25); x < Math.floor(W * 0.75); x++) {
+ const o = (y * W + x) * 4;
+ r += px[o]; g += px[o + 1]; b += px[o + 2]; m++;
+ }
+ return [r / m, g / m, b / m];
+ };
+ return {
+ meanChange: change / (n * 3),
+ plain: compare(acesPx, false),
+ graded: compare(gradedPx, true),
+ redShift: redShift / n,
+ blueShift: blueShift / n,
+ engineAcesMean: centre(acesPx),
+ };
+ },
+ { W, H, clipId },
+ );
+
+ const frames = await engineFrames();
+
+ // The Program monitor (live preview), display-referred baseline.
+ const monitorBase = await programMean(page);
+
+ // Preview options > Color management > ACES, the way a user does.
+ await page.getByRole("button", { name: "Preview options" }).click();
+ await page.getByTestId("color-management-trigger").click();
+ await page.getByTestId("color-management-aces").click();
+ await expect
+ .poll(() => page.evaluate(() => (window as unknown as { __openreelE2E: AcesHook }).__openreelE2E.project.getState().project.settings.colorManagement), { timeout: 10_000 })
+ .toBe("aces");
+ await seek(page, 1);
+ await settle(page, 1200);
+ await waitForPresentedPlayhead(page);
+ const badgeShown = await page.getByTestId("aces-badge").isVisible();
+ const settingsAfterMenu = await readSettings(page);
+ await expect.poll(async () => Math.abs((await programMean(page))[0] - monitorBase[0]), { timeout: 20_000, intervals: [300] }).toBeGreaterThan(8);
+ await settle(page, 600);
+ const monitorAces = await programMean(page);
+
+ // Undo is one step: the project returns to display-referred and the monitor to the baseline.
+ await undo(page);
+ await expect.poll(async () => (await readSettings(page)).colorManagement ?? null, { timeout: 10_000 }).toBeNull();
+ await settle(page, 1200);
+ await waitForPresentedPlayhead(page);
+ const settingsAfterUndo = await readSettings(page);
+ const badgeHiddenAfterUndo = !(await page.getByTestId("aces-badge").isVisible());
+ const monitorUndone = await programMean(page);
+ await redo(page);
+ await expect.poll(async () => (await readSettings(page)).colorManagement ?? null, { timeout: 10_000 }).toBe("aces");
+ await settle(page, 1200);
+ await waitForPresentedPlayhead(page);
+ const settingsAfterRedo = await readSettings(page);
+ const monitorRedone = await programMean(page);
+
+ // Save / load round trip through the project file.
+ const persisted = await page.evaluate(() => {
+ const h = (window as unknown as { __openreelE2E: AcesHook }).__openreelE2E;
+ const serializer = new h.ProjectSerializer({});
+ const state = h.project.getState().project;
+ const json = serializer.exportToJson(state);
+ const saved = JSON.parse(json).project.settings;
+ const imported = serializer.importFromJson(json);
+ const live = state.mediaLibrary.items;
+ h.project.getState().loadProject({
+ ...imported,
+ mediaLibrary: { ...imported.mediaLibrary, items: imported.mediaLibrary.items.map((item: any) => live.find((l: any) => l.id === item.id) ?? item) },
+ });
+ return { saved: saved.colorManagement as unknown, loaded: h.project.getState().project.settings.colorManagement as unknown };
+ });
+ await seek(page, 1);
+ await settle(page, 1400);
+ await waitForPresentedPlayhead(page);
+ const monitorReloaded = await programMean(page);
+
+ // Per-clip input override (Color tab > Camera input > This clip only) changes the picture; one undo reverts it.
+ const clipBefore = await programMean(page);
+ await page.evaluate(async (id) => {
+ const h = (window as unknown as { __openreelE2E: AcesHook }).__openreelE2E;
+ await (h.project.getState() as any).executeAction({ type: "clip/setColorInterpretation", id: `ov-${Date.now()}`, timestamp: Date.now(), params: { clipId: id, colorInterpretation: "log-logc3" } });
+ }, clipId);
+ await seek(page, 1);
+ await settle(page, 1200);
+ await waitForPresentedPlayhead(page);
+ const clipAfter = await programMean(page);
+ await undo(page);
+ await settle(page, 1200);
+ await seek(page, 1);
+ await waitForPresentedPlayhead(page);
+ const clipUndone = await programMean(page);
+
+ return {
+ meanChange: frames.meanChange,
+ predictionMax: frames.plain.max,
+ predictionMean: frames.plain.mean,
+ gradedMax: frames.graded.max,
+ gradedMean: frames.graded.mean,
+ gradedRedShift: frames.redShift,
+ gradedBlueShift: frames.blueShift,
+ monitor: { base: monitorBase, aces: monitorAces, undone: monitorUndone, redone: monitorRedone, reloaded: monitorReloaded },
+ engineAcesMean: frames.engineAcesMean,
+ settings: { afterMenu: settingsAfterMenu.colorManagement, afterUndo: settingsAfterUndo.colorManagement ?? null, afterRedo: settingsAfterRedo.colorManagement, savedJson: persisted.saved, afterLoad: persisted.loaded },
+ badge: { shown: badgeShown, hiddenAfterUndo: badgeHiddenAfterUndo },
+ clipOverride: { before: clipBefore, after: clipAfter, undone: clipUndone },
+ };
+}
+
+async function readSettings(page: Page): Promise<Record<string, any>> {
+ return page.evaluate(() => (window as unknown as { __openreelE2E: AcesHook }).__openreelE2E.project.getState().project.settings);
+}
+
+const maxDelta = (a: number[], b: number[]): number => Math.max(...a.map((v, i) => Math.abs(v - b[i])));
+
+export function assertAcesProductResult(r: AcesProductResult): void {
+ // 1. ACES really changes the pixels, and by exactly what the analytic transform predicts.
+ expect(r.meanChange, "display-referred vs ACES engine frame, mean 8-bit change").toBeGreaterThan(8);
+ expect(r.predictionMean, "ACES engine frame vs IDT -> RRT/ODT prediction (mean 8-bit error)").toBeLessThan(0.8);
+ expect(r.predictionMax, "ACES engine frame vs prediction (max 8-bit error)").toBeLessThanOrEqual(3);
+ // 2. The grade runs in ACEScct: a warm grade raises red and lowers blue by the amount the ACEScct model predicts.
+ expect(r.gradedRedShift).toBeGreaterThan(1);
+ expect(r.gradedBlueShift).toBeLessThan(-1);
+ expect(r.gradedMean, "graded ACES frame vs ACEScct grade prediction (mean 8-bit error)").toBeLessThan(1.2);
+ expect(r.gradedMax, "graded ACES frame vs prediction (max 8-bit error)").toBeLessThanOrEqual(5);
+ // 3. Setting, badge and undo / redo.
+ expect(r.settings.afterMenu).toBe("aces");
+ expect(r.badge.shown).toBe(true);
+ expect(r.settings.afterUndo).toBeNull();
+ expect(r.badge.hiddenAfterUndo).toBe(true);
+ expect(r.settings.afterRedo).toBe("aces");
+ // 4. The live Program monitor shows the engine's ACES frame (same output transform), not the display-referred one.
+ expect(maxDelta(r.monitor.aces, r.engineAcesMean), "Program monitor vs engine ACES frame").toBeLessThan(4);
+ expect(maxDelta(r.monitor.aces, r.monitor.base), "monitor changed when ACES was switched on").toBeGreaterThan(8);
+ expect(maxDelta(r.monitor.undone, r.monitor.base), "undo restores the display-referred monitor").toBeLessThan(2);
+ expect(maxDelta(r.monitor.redone, r.monitor.aces), "redo restores the ACES monitor").toBeLessThan(2);
+ // 5. Persisted: the saved file carries it and the reloaded project renders ACES again.
+ expect(r.settings.savedJson).toBe("aces");
+ expect(r.settings.afterLoad).toBe("aces");
+ expect(maxDelta(r.monitor.reloaded, r.monitor.aces), "reloaded project renders like before").toBeLessThan(2);
+ // 6. Per-clip input override: changes the picture, one undo reverts it.
+ expect(maxDelta(r.clipOverride.after, r.clipOverride.before), "LogC3 override on this clip changes the frame").toBeGreaterThan(8);
+ expect(maxDelta(r.clipOverride.undone, r.clipOverride.before), "undo restores the clip's interpretation").toBeLessThan(2);
+}
diff --git a/apps/web/e2e/aces-color.spec.ts b/apps/web/e2e/aces-color.spec.ts
new file mode 100644
index 00000000..d21ec560
--- /dev/null
+++ b/apps/web/e2e/aces-color.spec.ts
@@ -0,0 +1,132 @@
+import { expect, test, type Page } from "@playwright/test";
+import { SOFTWARE_GPU } from "./env";
+import { assertAcesProductResult, ensureLumetriFixtures, runAcesProductFlow } from "./aces-color-lib";
+import { openHookPage } from "./helpers";
+
+/**
+ * ACES colour management.
+ * 1. gpu project: the WebGL2 half-float ACES pipeline (ACEScct grade, sRGB / BT.1886 view, PQ and HLG encode) against the
+ * Float32 CPU reference that backs the no-GPU fallback, on one composite.
+ * 2. the product flow (lib): Preview options > Color management > ACES changes the rendered pixels by exactly what the
+ * analytic transforms predict, in the engine (preview and export) and on the Program monitor; the setting is one
+ * undo step and survives a save / load round trip; a per-clip input override works.
+ */
+
+test.beforeAll(() => ensureLumetriFixtures());
+
+interface CoreHook {
+ hdrWorking: Record<string, any>;
+ hdrGpu: Record<string, any>;
+ acesOutput: Record<string, any>;
+}
+
+async function parity(page: Page) {
+ return page.evaluate(() => {
+ const core = (window as unknown as { __openreelE2E: { core: CoreHook } }).__openreelE2E.core;
+ if (!core.hdrGpu.isGpuHdrAvailable()) return { skipped: "no WebGL2 with EXT_color_buffer_float" } as const;
+ const hw = core.hdrWorking;
+ // The CPU reference compositor runs the Output Transform through this registration (the engine does it per frame).
+ hw.registerAcesOutputTransform(core.acesOutput.acesOutputTransform);
+ const W = 192;
+ const H = 108;
+ // Layer 1: 8-bit sRGB ramp with hue drift. Layer 2: 16-bit ARRI LogC3 ramp. Overlay: translucent box + white bar.
+ const srgb = new Uint8ClampedArray(W * H * 4);
+ for (let y = 0; y < H; y++)
+ for (let x = 0; x < W; x++) {
+ const v = Math.round((255 * x) / (W - 1));
+ srgb.set([v, Math.round(v * (0.5 + 0.5 * (y / H))), Math.round(v * (1 - 0.6 * (y / H))), 255], (y * W + x) * 4);
+ }
+ const SW = 96;
+ const SH = 54;
+ const log = new Uint16Array(SW * SH * 4);
+ for (let y = 0; y < SH; y++)
+ for (let x = 0; x < SW; x++) {
+ const s = 0.15 + 0.7 * (x / (SW - 1));
+ const o = (y * SW + x) * 4;
+ log[o] = Math.round(s * 65535);
+ log[o + 1] = Math.round(s * (0.9 + 0.1 * (y / SH)) * 65535);
+ log[o + 2] = Math.round(s * (1 - 0.2 * (y / SH)) * 65535);
+ log[o + 3] = 65535;
+ }
+ const overlay = new OffscreenCanvas(W, H);
+ const octx = overlay.getContext("2d")!;
+ octx.fillStyle = "rgba(20,120,220,0.5)";
+ octx.fillRect(20, 14, 80, 40);
+ octx.fillStyle = "#ffffff";
+ octx.fillRect(8, 90, 120, 8);
+
+ const identity = { position: { x: 0, y: 0 }, scale: { x: 1, y: 1 }, rotation: 0, anchor: { x: 0.5, y: 0.5 }, opacity: 1, fitMode: "stretch" };
+ const results: Record<string, { viewDiffMax: number; viewOver: number; encMax: number }> = {};
+ for (const sdrOutput of ["srgb", "rec709"] as const) {
+ const pipeline = hw.acesPipeline(sdrOutput);
+ const grade = hw.prepareHdrGrade(
+ {
+ temperature: 25,
+ tint: -10,
+ tone: { exposure: 0.2, contrast: 0.2, highlights: -0.1, shadows: 0.1, whites: 0, blacks: 0 },
+ colorWheels: { shadows: { r: 0.02, g: 0, b: 0.03 }, midtones: { r: 0, g: 0.02, b: 0 }, highlights: { r: 0.01, g: 0, b: -0.02 }, shadowsLift: 0.01, midtonesGamma: 1.1, highlightsGain: 1.05 },
+ vignette: { amount: -0.4, midpoint: 0.4, roundness: 0, feather: 0.4 },
+ },
+ pipeline,
+ );
+ const run = (comp: any) => {
+ comp.setColorPipeline(pipeline);
+ comp.setGraphicsWhite(203);
+ comp.begin(W, H);
+ comp.drawCodes({ depth: 8, width: W, height: H, data: srgb }, hw.hdrSourceDecode(null, pipeline), { geometry: hw.computeLayerGeometry(identity, W, H, W, H), opacity: 1, grade });
+ const logGeometry = hw.computeLayerGeometry({ ...identity, scale: { x: 0.5, y: 0.5 }, position: { x: 30, y: 20 }, opacity: 0.8 }, SW, SH, W, H);
+ comp.drawCodes(
+ { depth: 16, width: SW, height: SH, data: log },
+ hw.hdrSourceDecode({ primaries: "awg3", transfer: "logc3", matrix: "rgb", fullRange: true }, pipeline),
+ { geometry: logGeometry, opacity: 0.8 },
+ );
+ comp.drawOverlay(overlay);
+ return comp;
+ };
+ const cpu = run(new hw.CpuHdrCompositor());
+ const gpu = run(new core.hdrGpu.GpuHdrCompositor());
+ const a = cpu.readSdrView() as Uint8ClampedArray;
+ const b = gpu.readSdrView() as Uint8ClampedArray;
+ let viewDiffMax = 0;
+ let over = 0;
+ for (let i = 0; i < a.length; i++) {
+ const d = Math.abs(a[i] - b[i]);
+ if (d > viewDiffMax) viewDiffMax = d;
+ if (d > 2) over++;
+ }
+ let encMax = 0;
+ for (const transfer of ["pq", "hlg"] as const) {
+ const spec = { primaries: "bt2020", transfer, matrix: "bt2020-ncl", fullRange: false, bitDepth: 10 };
+ const ea = cpu.readEncodedRgb(spec) as Float32Array;
+ const eb = gpu.readEncodedRgb(spec) as Float32Array;
+ for (let i = 0; i < ea.length; i++) encMax = Math.max(encMax, Math.abs(ea[i] - eb[i]));
+ }
+ results[sdrOutput] = { viewDiffMax, viewOver: over / a.length, encMax };
+ cpu.dispose();
+ gpu.dispose();
+ }
+ return { results } as const;
+ });
+}
+
+test("the WebGL2 ACES pipeline matches the float CPU reference (ACEScct grade, sRGB / BT.1886 view, PQ and HLG encode)", async ({ page }, testInfo) => {
+ test.setTimeout(150_000);
+ await openHookPage(page);
+ const result = await parity(page);
+ console.log(`[${testInfo.project.name}] ACES shader parity: ${JSON.stringify(result)}`);
+ if ("skipped" in result) test.skip(true, String(result.skipped));
+ const { results } = result as { results: Record<string, { viewDiffMax: number; viewOver: number; encMax: number }> };
+ for (const id of ["srgb", "rec709"]) {
+ const r = results[id];
+ // 8-bit view: float32 shader vs float32/double CPU reference. A GPU's pow / log2 are a few ulp off, which can flip a code by one.
+ expect(r.viewDiffMax, `${id} view, largest 8-bit difference`).toBeLessThanOrEqual(SOFTWARE_GPU ? 4 : 3);
+ expect(r.viewOver, `${id} view, fraction of channels off by more than 2 codes`).toBeLessThan(0.002);
+ // Encoded PQ / HLG signal, float: well under one 10-bit code (1/1023) in the highlights.
+ expect(r.encMax, `${id} PQ / HLG encode, largest signal difference`).toBeLessThan(0.004);
+ }
+});
+
+test("ACES through the product: menu, pixels vs the analytic prediction, ACEScct grade, undo, save / load, per-clip override", async ({ page }) => {
+ test.setTimeout(240_000);
+ assertAcesProductResult(await runAcesProductFlow(page));
+});
diff --git a/apps/web/e2e/color-wb-eyedropper-lib.ts b/apps/web/e2e/color-wb-eyedropper-lib.ts
index 05d4cddb..e810aa49 100644
--- a/apps/web/e2e/color-wb-eyedropper-lib.ts
+++ b/apps/web/e2e/color-wb-eyedropper-lib.ts
@@ -1,3 +1,5 @@
+import { tmpdir } from "node:os";
+import { join } from "node:path";
import { expect, type Page } from "@playwright/test";
import { clickClip, clipsOf, openEditor, press, readState, seek, settle, snap, undo } from "./helpers";
import { openColorGrading } from "./lumetri-basic-lib";
@@ -255,7 +257,7 @@ export async function runWbRealFootageFlow(
expect(clipped, `${label} label is clipped`).toBe(false);
}
await expect(sizeGroup).toBeVisible();
- await page.screenshot({ path: "/private/tmp/claude-501/wb-armed.png" });
+ await page.screenshot({ path: join(tmpdir(), "wb-armed.png") });
const box = await page.locator(PROGRAM).boundingBox();
if (!box) throw new Error("no Program canvas box");
const x = box.x + box.width * patch.fx;
diff --git a/apps/web/e2e/fallback-aces-color.spec.ts b/apps/web/e2e/fallback-aces-color.spec.ts
new file mode 100644
index 00000000..1bd4de32
--- /dev/null
+++ b/apps/web/e2e/fallback-aces-color.spec.ts
@@ -0,0 +1,24 @@
+import { test } from "@playwright/test";
+import { assertAcesProductResult, ensureLumetriFixtures, runAcesProductFlow } from "./aces-color-lib";
+
+// Runs under fallback-nowebgpu and fallback-software (playwright.config.ts): without WebGPU, and without any GPU, the ACES
+// pipeline renders through the same engine (WebGL2 half float where present, the Float32 CPU reference otherwise) and
+// must produce the same pixels as the analytic prediction, the same undo and the same persistence as aces-color.spec.ts.
+
+test.beforeAll(() => ensureLumetriFixtures());
+
+test.beforeEach(async ({ page }, testInfo) => {
+ if (testInfo.project.name !== "fallback-nowebgpu") return;
+ await page.addInitScript(() => {
+ try {
+ delete (Navigator.prototype as unknown as { gpu?: unknown }).gpu;
+ } catch {
+ /* non-configurable on this build; requestAdapter() is still null */
+ }
+ });
+});
+
+test("ACES colour management without WebGPU: the same pixels, undo and persistence", async ({ page }) => {
+ test.setTimeout(300_000);
+ assertAcesProductResult(await runAcesProductFlow(page));
+});
diff --git a/apps/web/e2e/interchange-prproj.spec.ts b/apps/web/e2e/interchange-prproj.spec.ts
new file mode 100644
index 00000000..ea899f5a
--- /dev/null
+++ b/apps/web/e2e/interchange-prproj.spec.ts
@@ -0,0 +1,108 @@
+import { readFileSync } from "node:fs";
+import { dirname, join } from "node:path";
+import { fileURLToPath } from "node:url";
+import { expect, test, type Page } from "@playwright/test";
+import { chooseFileMenu, openEditor, readState, undo } from "./helpers";
+
+interface E2E {
+ __openreelE2E: { project: { getState(): any } };
+}
+
+const here = dirname(fileURLToPath(import.meta.url));
+// Hand-authored gzip XML following the .prproj object graph (see packages/core/scripts/gen-prproj-fixture.py).
+const FIXTURE = join(here, "..", "..", "..", "packages", "core", "src", "interchange", "__fixtures__", "main-cut.prproj");
+
+async function timeline(page: Page) {
+ return page.evaluate(() => {
+ const p = (window as unknown as E2E).__openreelE2E.project.getState().project;
+ return {
+ tracks: p.timeline.tracks
+ .filter((t: any) => t.type === "video" || t.type === "audio")
+ .map((t: any) => ({
+ type: t.type,
+ name: t.name,
+ clips: [...t.clips]
+ .sort((a: any, b: any) => a.startTime - b.startTime)
+ .map((c: any) => ({
+ start: Math.round(c.startTime * 25),
+ end: Math.round((c.startTime + c.duration) * 25),
+ speed: c.speed ?? 1,
+ reversed: !!c.reversed,
+ opacity: c.transform.opacity,
+ scale: c.transform.scale.x,
+ disabled: !!c.metadata?.importedDisabled,
+ nested: typeof c.metadata?.compoundClipId === "string",
+ })),
+ transitions: t.transitions.length,
+ })),
+ markers: p.timeline.markers.map((m: any) => [m.label, m.time, m.duration ?? 0]),
+ placeholders: p.mediaLibrary.items.filter((m: any) => m.isPlaceholder).map((m: any) => m.name).sort(),
+ bins: (p.bins ?? []).map((b: any) => b.name).sort(),
+ sequences: (p.sequences ?? []).length,
+ };
+ });
+}
+
+test.describe("Premiere project (.prproj) import", () => {
+ test("imports a gzip .prproj as one undoable action: tracks, speed, motion, markers, dissolve, placeholders and report", async ({ page }) => {
+ await openEditor(page);
+ const before = await readState(page);
+ const chooser = page.waitForEvent("filechooser");
+ await chooseFileMenu(page, ["Import timeline", "Premiere project (.prproj)…"]);
+ await (await chooser).setFiles({ name: "main-cut.prproj", mimeType: "application/octet-stream", buffer: readFileSync(FIXTURE) });
+ await page.getByTestId("timeline-import-report").waitFor();
+
+ // dialog: format, the sequence picker, the report and the offline media list
+ await expect(page.getByText(/Premiere Pro project · Main Cut/)).toBeVisible();
+ await expect(page.getByTestId("prproj-sequence-picker")).toBeVisible();
+ await expect(page.getByTestId("import-clip-count")).toHaveText("8");
+ await expect(page.getByTestId("import-report-summary")).toHaveText("1 dropped, 2 approximated");
+ await expect(page.getByTestId("import-report")).toContainText("Effect: Gaussian Blur");
+ await expect(page.getByTestId("import-report")).toContainText("Disabled clip");
+ const unmatched = page.getByTestId("import-unmatched");
+ for (const name of ["interview.mp4", "broll.mov", "overlay.png", "theme song.wav"]) await expect(unmatched).toContainText(name);
+
+ await page.getByRole("radio", { name: /Replace the timeline/ }).check();
+ await page.getByRole("button", { name: "Import", exact: true }).click();
+ await expect(page.getByTestId("timeline-import-report")).toHaveCount(0);
+
+ const after = await readState(page);
+ expect(after.historyLength - before.historyLength).toBe(1);
+
+ const t = await timeline(page);
+ const v1 = t.tracks.find((x: any) => x.name === "V1");
+ const v2 = t.tracks.find((x: any) => x.name === "V2");
+ const a1 = t.tracks.find((x: any) => x.type === "audio");
+ expect(v1.clips.map((c: any) => [c.start, c.end])).toEqual([[0, 125], [125, 225], [225, 275]]);
+ expect(v1.clips[1]).toMatchObject({ speed: 2, scale: 0.5 });
+ expect(v1.clips[2].disabled).toBe(true);
+ expect(v1.transitions).toBe(1);
+ expect(v2.clips[0].opacity).toBe(0.5);
+ expect(v2.clips[1].nested).toBe(true);
+ expect(a1.clips.map((c: any) => [c.start, c.end, c.reversed])).toEqual([[0, 200, false], [200, 250, true]]);
+ expect(t.markers).toEqual([["Intro", 1, 0], ["Chapter 2", 6, 2]]);
+ // offline placeholders the relink flow can reconnect, in the bins of the Premiere project
+ expect(t.placeholders).toEqual(["broll.mov", "interview.mp4", "overlay.png", "theme song.wav"]);
+ expect(t.bins).toEqual(["Audio", "Footage", "Graphics"]);
+ expect(t.sequences).toBeGreaterThanOrEqual(2);
+
+ // one Undo reverts everything, bins and the nested sequence included
+ await undo(page);
+ expect((await readState(page)).historyLength).toBe(before.historyLength);
+ const reverted = await timeline(page);
+ expect(reverted.placeholders).toEqual([]);
+ expect(reverted.bins).toEqual([]);
+ expect(reverted.markers).toEqual([]);
+ });
+
+ test("choosing another sequence re-reads it", async ({ page }) => {
+ await openEditor(page);
+ const chooser = page.waitForEvent("filechooser");
+ await chooseFileMenu(page, ["Import timeline", "Premiere project (.prproj)…"]);
+ await (await chooser).setFiles({ name: "main-cut.prproj", mimeType: "application/octet-stream", buffer: readFileSync(FIXTURE) });
+ await page.getByTestId("timeline-import-report").waitFor();
+ await page.getByTestId("prproj-sequence-picker").locator("select").selectOption({ label: "Alt Cut (1920x1080 · 29.97 fps · 1 clips)" });
+ await expect(page.getByText(/Premiere Pro project · Alt Cut/)).toBeVisible();
+ await expect(page.getByTestId("import-clip-count")).toHaveText("1");
+ });
+});
diff --git a/apps/web/e2e/transcript.spec.ts b/apps/web/e2e/transcript.spec.ts
index 1bc4382c..3f3c60f4 100644
--- a/apps/web/e2e/transcript.spec.ts
+++ b/apps/web/e2e/transcript.spec.ts
@@ -197,7 +197,8 @@ test.describe("Transcript editing", () => {
const lines = vtt.split("\n");
expect(lines[0]).toBe("WEBVTT");
expect(lines[1]).toBe("");
- const blocks = vtt.trim().split(/\n\n/).slice(1);
+ // The caption style model may add a STYLE block before the cues.
+ const blocks = vtt.trim().split(/\n\n/).slice(1).filter((block) => !block.startsWith("STYLE"));
expect(blocks).toHaveLength(3);
const timing = /^(\d{2}):(\d{2}):(\d{2})\.(\d{3}) --> (\d{2}):(\d{2}):(\d{2})\.(\d{3})$/;
let last = -1;
diff --git a/apps/web/scripts/check-bundle-size.mjs b/apps/web/scripts/check-bundle-size.mjs
index a88b905f..58473451 100644
--- a/apps/web/scripts/check-bundle-size.mjs
+++ b/apps/web/scripts/check-bundle-size.mjs
@@ -70,7 +70,9 @@ const measured = {
entry: sizes(resolveAsset(entryRef)),
initialJs: sum([...closure]),
editor: biggest(find("EditorInterface-")) ? sizes(biggest(find("EditorInterface-"))) : null,
- agent: biggest(find("executor-")) ? sizes(biggest(find("executor-"))) : null,
+ // The tool registry is the bulk of the agent stack. It sits in the executor chunk or, when only the
+ // registry is shared with a lazy chat chunk, in a registry chunk of its own: measure the larger.
+ agent: biggest([...find("executor-"), ...find("registry-")]) ? sizes(biggest([...find("executor-"), ...find("registry-")])) : null,
};
const kb = (n) => Math.round(n / 100) / 10;
diff --git a/apps/web/src/components/editor/AssetsPanel.tsx b/apps/web/src/components/editor/AssetsPanel.tsx
index d99309f8..098438c1 100644
--- a/apps/web/src/components/editor/AssetsPanel.tsx
+++ b/apps/web/src/components/editor/AssetsPanel.tsx
@@ -30,6 +30,7 @@ import type { Project, TextStyle } from "@openreel/core";
import { useProjectStore } from "../../stores/project-store";
import { useUIStore } from "../../stores/ui-store";
import { useTimelineStore } from "../../stores/timeline-store";
+import { isPremiereProjectFile, openTimelineFileForImport } from "../../services/timeline-interchange";
import { RAW_FILE_ACCEPT, groupCinemaDng, interpretedDisplaySize, type MediaItem } from "@openreel/core";
import { enqueueImportBatch, takeNextImportBatch, type PendingImportBatch } from "../../services/import-batch-queue";
import { importCinemaDngSequence, looksLikeCinemaDngFrame } from "../../services/cinemadng-sequence";
@@ -890,7 +891,12 @@ export const AssetsPanel: React.FC = () => {
async (files: FileList | readonly File[] | null, dropOwner?: MediaOwner): Promise<void> => {
if (!files?.length) return;
// Snapshot now: the picker clears its FileList as soon as the change handler returns.
- const picked = Array.from(files);
+ const all = Array.from(files);
+ // Premiere projects are timelines, not media: the first one opens the import dialog (one undoable import).
+ const premiere = all.find((file) => isPremiereProjectFile(file.name));
+ if (premiere) void openTimelineFileForImport(premiere);
+ const picked = all.filter((file) => !isPremiereProjectFile(file.name));
+ if (picked.length === 0) return;
const current = useProjectStore.getState();
const owner = dropOwner ?? { projectId: current.project.id, executor: current.actionExecutor };
if (!ownsMediaSession(owner)) return;
@@ -1546,7 +1552,7 @@ export const AssetsPanel: React.FC = () => {
ref={fileInputRef}
type="file"
aria-label="Import media"
- accept={`video/*,audio/*,image/*,.mxf,${RAW_FILE_ACCEPT}`}
+ accept={`video/*,audio/*,image/*,.mxf,.prproj,${RAW_FILE_ACCEPT}`}
multiple
className="hidden"
onChange={(event) => {
diff --git a/apps/web/src/components/editor/EditorInterface.tsx b/apps/web/src/components/editor/EditorInterface.tsx
index 212c6d36..a97cb173 100644
--- a/apps/web/src/components/editor/EditorInterface.tsx
+++ b/apps/web/src/components/editor/EditorInterface.tsx
@@ -5,7 +5,6 @@ import "./reference-workspace.css";
import React, { useEffect, useState, useRef, useCallback } from "react";
import { Button, Button as ShadcnButton, Dialog, DialogContent, DialogTitle, ScrollArea } from "@openreel/ui";
-import { ChangesPanel } from "./chat/ChangesPanel";
import { BackgroundTasksIndicator } from "./BackgroundTasksPanel";
import { Toolbar } from "./Toolbar";
import { EditorActionRail } from "./EditorActionRail";
@@ -48,6 +47,8 @@ import "./editor-responsive.css";
const KeyboardShortcutsOverlay = React.lazy(() =>
import("./KeyboardShortcutsOverlay").then((module) => ({ default: module.KeyboardShortcutsOverlay })),
);
+// The AI changes list pulls in the agent tool registry (editing-tools); it only shows with the AI chat open.
+const ChangesPanel = React.lazy(() => import("./chat/ChangesPanel").then(module => ({ default: module.ChangesPanel })));
const ChatPanel = React.lazy(() =>
import("./chat/ChatPanel").then((module) => ({ default: module.ChatPanel })),
);
@@ -586,7 +587,7 @@ export const EditorInterface: React.FC = () => {
style={{ gridArea: "inspector" }}
>
<PanelErrorBoundary name="Inspector">
- {chatVisible && !compact ? <ChangesPanel /> : <InspectorPanel />}
+ {chatVisible && !compact ? <React.Suspense fallback={null}><ChangesPanel /></React.Suspense> : <InspectorPanel />}
</PanelErrorBoundary>
</div></>
diff --git a/apps/web/src/components/editor/EditorMenuBar.tsx b/apps/web/src/components/editor/EditorMenuBar.tsx
index 5e2659a3..5f3d2760 100644
--- a/apps/web/src/components/editor/EditorMenuBar.tsx
+++ b/apps/web/src/components/editor/EditorMenuBar.tsx
@@ -167,7 +167,8 @@ export function EditorMenuBar({
heading: "Bring in a sequence",
disabled: exporting || applying || playbackLocked,
children: [
- { label: "Timeline XML…", description: "Premiere/Resolve XML, FCPXML or OpenTimelineIO (.otio)", action: () => openTimelineImport("xml") },
+ { label: "Timeline XML…", description: "Premiere/Resolve XML, FCPXML, OpenTimelineIO (.otio) or EDL", action: () => openTimelineImport("xml") },
+ { label: "Premiere project (.prproj)…", description: "Sequences, clips, speed, motion, markers and dissolves; media is relinked to the bin by file name, the rest becomes offline placeholders", action: () => openTimelineImport("prproj") },
{ label: "AAF…", description: "Avid / Premiere / Resolve AAF; media is relinked to the bin by file name", action: () => openTimelineImport("aaf") },
],
},
diff --git a/apps/web/src/components/editor/Preview.tsx b/apps/web/src/components/editor/Preview.tsx
index f951da06..077cb42f 100644
--- a/apps/web/src/components/editor/Preview.tsx
+++ b/apps/web/src/components/editor/Preview.tsx
@@ -403,6 +403,9 @@ const drawBlurredBackdrop = (
ctx.restore();
};
+/** True when the project is in ACES colour management: the Program monitor then shows the engine's ACES Output Transform render. */
+const isAcesProject = (): boolean => useProjectStore.getState().project.settings.colorManagement === "aces";
+
const renderFrameWithGPU = async (
renderer: Renderer,
frame: ImageBitmap,
@@ -2885,7 +2888,8 @@ export const Preview: React.FC = () => {
// Compound clips are full nested timelines rather than media blobs.
// Route those frames through the canonical compositor so preview and
// export share identical nesting, timing, effects and transforms.
- const hasActiveCompound = timelineTracks.some((track) =>
+ // ACES mode: the Output Transform lives in the canonical float compositor, so every frame goes through it.
+ const hasActiveCompound = isAcesProject() || timelineTracks.some((track) =>
!track.hidden &&
track.clips.some(
(clip) =>
@@ -3921,6 +3925,8 @@ export const Preview: React.FC = () => {
}>;
} => {
const tracks = timelineTracks;
+ // The video element draws display-referred pixels; ACES mode renders every frame through the float compositor.
+ if (isAcesProject()) return { canUse: false, clips: [] };
if (
tracks.some(
(track) =>
@@ -5963,7 +5969,7 @@ export const Preview: React.FC = () => {
}
// Echo / Posterize Time pick other frames of the clip: the engine renderer (export's) decodes them.
- const hasActiveCompound = activeClips.some(
+ const hasActiveCompound = isAcesProject() || activeClips.some(
({ clip }) => getCompoundClipId(clip) !== null || clipHasTemporalEffects(clip),
);
// Anamorphic / interlaced footage is conformed by the engine renderer, never the raw video-element draw.
@@ -8497,6 +8503,16 @@ export const Preview: React.FC = () => {
<div className="workspace-preview-options">
<MaskPenButton />
<ProxyToggleButton />
+ {settings.colorManagement === "aces" && (
+ <span
+ data-testid="aces-badge"
+ role="status"
+ className="workspace-preview-choice text-xs"
+ title="ACES color management: input transform, ACEScct grading, RRT and output transform. The monitor and scopes show the output transform."
+ >
+ {`ACES · ${(settings.acesOutput ?? "srgb") === "rec709" ? "Rec.709" : "sRGB"}`}
+ </span>
+ )}
{memoryPolicy.pressure !== "normal" && (
<span
data-testid="memory-pressure-badge"
@@ -8519,6 +8535,18 @@ export const Preview: React.FC = () => {
<DropdownMenuCheckboxItem checked={showCompositionGrid} onCheckedChange={setShowCompositionGrid}>Composition grid</DropdownMenuCheckboxItem>
<DropdownMenuCheckboxItem checked={canvasSnappingEnabled} onCheckedChange={(enabled) => { setCanvasSnappingEnabled(enabled); setCanvasSnapGuides({x:null,y:null}); }}>Canvas snapping</DropdownMenuCheckboxItem>
<DropdownMenuSeparator />
+ <DropdownMenuSub><DropdownMenuSubTrigger data-testid="color-management-trigger">Color management</DropdownMenuSubTrigger><DropdownMenuSubContent>
+ {([["display-referred", "Display-referred (default)"], ["aces", "ACES (ACEScct grading)"]] as const).map(([value, label]) => (
+ <DropdownMenuCheckboxItem key={value} data-testid={`color-management-${value}`} checked={(settings.colorManagement ?? "display-referred") === value} onCheckedChange={() => { void updateSettings({ colorManagement: value === "aces" ? "aces" : undefined, ...(value === "aces" ? {} : { acesOutput: undefined }) }); }}>{label}</DropdownMenuCheckboxItem>
+ ))}
+ <DropdownMenuSeparator />
+ <DropdownMenuLabel className="text-[10px] font-normal text-fg-3">ACES output transform</DropdownMenuLabel>
+ {([["srgb", "sRGB (RRT + ODT)"], ["rec709", "Rec.709 (BT.1886)"]] as const).map(([value, label]) => (
+ <DropdownMenuCheckboxItem key={value} data-testid={`aces-output-${value}`} disabled={settings.colorManagement !== "aces"} checked={(settings.acesOutput ?? "srgb") === value} onCheckedChange={() => { void updateSettings({ acesOutput: value === "srgb" ? undefined : value }); }}>{label}</DropdownMenuCheckboxItem>
+ ))}
+ <DropdownMenuSeparator />
+ <DropdownMenuLabel className="max-w-[260px] whitespace-normal text-[10px] font-normal leading-snug">ACES: footage enters through an input transform (Interpret footage picks it per footage item), compositing runs in ACEScg half float, grading in ACEScct, and the picture leaves through the ACES RRT and the output transform above. HDR10 and HLG exports use the Rec.2020 1000 nit transforms. The monitor, scopes and SDR exports show the output transform. Frames with adjustment layers or text behind subject still render display-referred.</DropdownMenuLabel>
+ </DropdownMenuSubContent></DropdownMenuSub>
<DropdownMenuSub><DropdownMenuSubTrigger>Working color space</DropdownMenuSubTrigger><DropdownMenuSubContent>
{([["rec709", "Rec.709 (default)"], ["rec2020", "Rec.2020"]] as const).map(([value, label]) => (
<DropdownMenuCheckboxItem key={value} checked={(settings.workingColorSpace ?? "rec709") === value} onCheckedChange={() => { void updateSettings({ workingColorSpace: value }); }}>{label}</DropdownMenuCheckboxItem>
@@ -8526,7 +8554,7 @@ export const Preview: React.FC = () => {
<DropdownMenuSeparator />
<DropdownMenuLabel className="max-w-[240px] whitespace-normal text-[10px] font-normal leading-snug">Rec.2020 switches to the HDR working mode: compositing and grading run in half-float scene-linear Rec.2020 (HDR highlights above SDR white are kept), the preview shows a tone-mapped SDR view, and exports are tagged BT.2020.</DropdownMenuLabel>
</DropdownMenuSubContent></DropdownMenuSub>
- <DropdownMenuSub><DropdownMenuSubTrigger disabled={(settings.workingColorSpace ?? "rec709") !== "rec2020"}>HDR graphics white</DropdownMenuSubTrigger><DropdownMenuSubContent>
+ <DropdownMenuSub><DropdownMenuSubTrigger disabled={(settings.workingColorSpace ?? "rec709") !== "rec2020" && settings.colorManagement !== "aces"}>HDR graphics white</DropdownMenuSubTrigger><DropdownMenuSubContent>
{GRAPHICS_WHITE_OPTIONS.map(({ nits, label }) => (
<DropdownMenuCheckboxItem key={nits} checked={(settings.graphicsWhiteNits ?? DEFAULT_GRAPHICS_WHITE_NITS) === nits} onCheckedChange={() => { void updateSettings({ graphicsWhiteNits: nits === DEFAULT_GRAPHICS_WHITE_NITS ? undefined : nits }); }}>{label}</DropdownMenuCheckboxItem>
))}
diff --git a/apps/web/src/components/editor/TimelineImportDialog.tsx b/apps/web/src/components/editor/TimelineImportDialog.tsx
index 1236cf74..5cb1da81 100644
--- a/apps/web/src/components/editor/TimelineImportDialog.tsx
+++ b/apps/web/src/components/editor/TimelineImportDialog.tsx
@@ -17,6 +17,8 @@ const FORMAT_NAMES: Record<string, string> = {
fcpxml: "FCPXML",
otio: "OpenTimelineIO",
aaf: "AAF",
+ edl: "EDL",
+ prproj: "Premiere Pro project",
};
const MODES: { id: TimelineImportMode; label: string; hint: string }[] = [
@@ -31,6 +33,8 @@ export function TimelineImportDialog() {
const [busy, setBusy] = useState(false);
if (!preview) return null;
const { result } = preview;
+ const report = result.importReport;
+ const prproj = preview.prproj;
const close = () => {
if (!busy) setPreview(null);
};
@@ -81,6 +85,47 @@ export function TimelineImportDialog() {
</ul>
</div>
)}
+ {prproj && prproj.sequences.length > 1 && (
+ <label className="block space-y-1" data-testid="prproj-sequence-picker">
+ <span className="font-medium">Sequence to import</span>
+ <select
+ className="w-full rounded-md border border-border bg-bg-2 px-2 py-1.5 text-[13px]"
+ value={prproj.selectedId}
+ disabled={busy}
+ onChange={(event) => setPreview(prproj.select(event.target.value))}
+ >
+ {prproj.sequences.map((s) => (
+ <option key={s.id} value={s.id}>
+ {s.name} ({s.detail}){s.nested ? " · nested" : ""}
+ </option>
+ ))}
+ </select>
+ </label>
+ )}
+ {report ? (
+ <div className="space-y-2" data-testid="import-report">
+ <p className="font-medium" data-testid="import-report-summary">
+ {report.dropped} dropped, {report.approximated} approximated
+ </p>
+ {report.items.length > 0 && (
+ <ul className="max-h-40 list-disc space-y-0.5 overflow-y-auto pl-5 text-[12px] text-fg-muted">
+ {report.items.map((item, i) => (
+ <li key={`${i}-${item.feature}-${item.clipName ?? ""}`}>
+ <span className="text-fg">[{item.severity}] {item.feature}</span>
+ {item.clipName ? ` (${[item.trackName, item.clipName].filter(Boolean).join(" / ")})` : ""}: {item.detail}
+ </li>
+ ))}
+ </ul>
+ )}
+ {report.notes.length > 0 && (
+ <ul className="list-disc pl-5 text-[12px] text-fg-muted">
+ {report.notes.map((n) => (
+ <li key={n}>{n}</li>
+ ))}
+ </ul>
+ )}
+ </div>
+ ) : null}
{result.warnings.length > 0 && (
<ul className="list-disc pl-5 text-[12px] text-fg-muted">
{result.warnings.map((w, i) => (
diff --git a/apps/web/src/components/editor/inspector/looks/CameraInputPicker.tsx b/apps/web/src/components/editor/inspector/looks/CameraInputPicker.tsx
index 91f18185..f54ecaf3 100644
--- a/apps/web/src/components/editor/inspector/looks/CameraInputPicker.tsx
+++ b/apps/web/src/components/editor/inspector/looks/CameraInputPicker.tsx
@@ -7,6 +7,7 @@ import {
inputSpaceForItem,
type FootageColorPreset,
} from "@openreel/core";
+import { v4 as uuidv4 } from "uuid";
import { useProjectStore } from "../../../../stores/project-store";
import { applyFootageInterpretation, runOrganize } from "../../../../services/project-panel-commands";
@@ -20,6 +21,7 @@ const sectionTitle = "text-[10px] font-semibold uppercase tracking-wide text-fg-
const CameraInputPicker: React.FC<{ clipId: string }> = ({ clipId }) => {
const mediaId = useProjectStore((s) => s.getClip(clipId)?.mediaId);
const media = useProjectStore((s) => (mediaId ? s.project.mediaLibrary.items.find((i) => i.id === mediaId) : undefined));
+ const clipOverride = useProjectStore((s) => s.getClip(clipId)?.colorInterpretation);
const makers = useMemo(() => [...new Set(CAMERA_FOOTAGE_COLOR_PRESETS.map((p) => p.camera!.maker))], []);
if (!media || media.type === "audio") return null;
@@ -28,12 +30,23 @@ const CameraInputPicker: React.FC<{ clipId: string }> = ({ clipId }) => {
const otherOverride = current && !camera ? FOOTAGE_COLOR_PRESETS.find((p) => p.id === current) : undefined;
const value = camera ? camera.id : otherOverride ? otherOverride.id : "tagged";
const transforming = inputSpaceForItem(media) !== null;
+ const aces = useProjectStore((s) => s.project.settings.colorManagement === "aces");
const change = (next: string) => {
const color: FootageColorPreset | null = next === "tagged" ? null : (next as FootageColorPreset);
void runOrganize("Camera input", applyFootageInterpretation([media.id], { color }));
};
+ const changeClip = (next: string) => {
+ const colorInterpretation: FootageColorPreset | null = next === "footage" ? null : (next as FootageColorPreset);
+ void useProjectStore.getState().executeAction({
+ type: "clip/setColorInterpretation",
+ id: uuidv4(),
+ timestamp: Date.now(),
+ params: { clipId, colorInterpretation },
+ });
+ };
+
return (
<div className="space-y-2" data-testid="camera-input">
<div className={sectionTitle}>Camera input</div>
@@ -56,9 +69,24 @@ const CameraInputPicker: React.FC<{ clipId: string }> = ({ clipId }) => {
))}
{otherOverride && <option value={otherOverride.id}>{otherOverride.label} (Interpret Footage)</option>}
</select>
+ <div className={sectionTitle}>This clip only</div>
+ <select
+ aria-label="Input color space for this clip"
+ value={clipOverride ?? "footage"}
+ onChange={(e) => changeClip(e.target.value)}
+ className="h-7 w-full min-w-0 rounded-[6px] border border-border bg-bg-1 px-2 text-[11px] text-fg"
+ data-testid="clip-input-select"
+ >
+ <option value="footage">Use the footage setting</option>
+ {FOOTAGE_COLOR_PRESETS.map((p) => (
+ <option key={p.id} value={p.id}>
+ {p.label}
+ </option>
+ ))}
+ </select>
<div className="text-[9px] leading-snug text-fg-3" data-testid="camera-input-status">
{camera
- ? `${describeSourceColor(camera.space)} to Rec.709. A built-in formula, applied to every clip of "${media.name}" before the Input LUT and the grade, in the preview, scopes and export.`
+ ? `${describeSourceColor(camera.space)} to ${aces ? "ACEScg (ACES input transform)" : "Rec.709"}. A built-in formula, applied to every clip of "${media.name}" before the Input LUT and the grade, in the preview, scopes and export.`
: transforming
? "Footage is converted with its Interpret Footage setting."
: "Pick the camera that shot this clip to convert its log footage to Rec.709. Leave on None for footage that is already Rec.709."}
diff --git a/apps/web/src/components/editor/preview/clip-input-transform.ts b/apps/web/src/components/editor/preview/clip-input-transform.ts
index 990a665a..d5b55b88 100644
--- a/apps/web/src/components/editor/preview/clip-input-transform.ts
+++ b/apps/web/src/components/editor/preview/clip-input-transform.ts
@@ -26,10 +26,14 @@ function rebuild(): void {
const transform = inputTransformFor(inputSpaceForItem(item));
if (transform) byMedia.set(item.id, transform);
}
- if (byMedia.size === 0) return;
+ const itemById = new Map(mediaLibrary.items.map((item) => [item.id, item] as const));
for (const track of timeline.tracks) {
for (const clip of track.clips) {
- const transform = byMedia.get(clip.mediaId);
+ // A clip's own Interpret Footage override wins over its footage item's.
+ const item = clip.colorInterpretation ? itemById.get(clip.mediaId) : undefined;
+ const transform = item
+ ? item.type === "video" || item.type === "image" ? inputTransformFor(inputSpaceForItem(item, clip.colorInterpretation)) : null
+ : byMedia.get(clip.mediaId);
if (transform) byClip.set(clip.id, transform);
}
}
diff --git a/apps/web/src/components/editor/project-panel/InterpretFootageDialog.tsx b/apps/web/src/components/editor/project-panel/InterpretFootageDialog.tsx
index 200725ea..1b7ab82f 100644
--- a/apps/web/src/components/editor/project-panel/InterpretFootageDialog.tsx
+++ b/apps/web/src/components/editor/project-panel/InterpretFootageDialog.tsx
@@ -19,9 +19,14 @@ import {
effectiveSourceColor,
inputSpaceForItem,
isHdrTransfer,
+ mapOcioColorSpaces,
+ OcioConfigError,
+ parseOcioConfig,
type FootageColorPreset,
type MediaItem,
+ type OcioMapping,
} from "@openreel/core";
+import { useProjectStore } from "../../../stores/project-store";
import { applyFootageInterpretation, runOrganize } from "../../../services/project-panel-commands";
import { actionTargetIds } from "./ProjectPanelMenus";
@@ -36,6 +41,21 @@ export const InterpretFootageDialog: React.FC<{ media: MediaItem; onClose: () =>
const willTransform = inputSpaceForItem({ ...media, colorInterpretation: choice === "tagged" ? undefined : choice }) !== null;
const hdr = isHdrTransfer(effective);
const cameraLog = cameraPresetOf(choice === "tagged" ? undefined : choice);
+ const acesMode = useProjectStore((s) => s.project.settings.colorManagement === "aces");
+ // OCIO config import: a transient mapping of the config's colour spaces onto the built-in presets.
+ const [ocio, setOcio] = React.useState<{ fileName: string; mapping: OcioMapping } | null>(null);
+ const [ocioError, setOcioError] = React.useState<string | null>(null);
+ const importOcio = async (file: File | undefined) => {
+ if (!file) return;
+ try {
+ const mapping = mapOcioColorSpaces(parseOcioConfig(await file.text()));
+ setOcio({ fileName: file.name, mapping });
+ setOcioError(null);
+ } catch (error) {
+ setOcio(null);
+ setOcioError(error instanceof OcioConfigError ? error.message : "The file could not be read as an OCIO config.");
+ }
+ };
const isVideo = media.type === "video";
const [fps, setFps] = React.useState(String(media.interpretation?.frameRate ?? media.metadata.frameRate ?? ""));
@@ -92,7 +112,9 @@ export const InterpretFootageDialog: React.FC<{ media: MediaItem; onClose: () =>
<dd data-testid="media-color-effective">{describeSourceColor(effective)}</dd>
<dt className="text-fg-3">Input transform</dt>
<dd data-testid="media-color-transform">
- {willTransform
+ {acesMode
+ ? "ACES input transform (IDT) to ACEScg, then the ACES output transform, identical in preview and export"
+ : willTransform
? hdr
? "HDR to SDR working image (tone-mapped), identical in preview and export"
: cameraLog
@@ -132,6 +154,54 @@ export const InterpretFootageDialog: React.FC<{ media: MediaItem; onClose: () =>
))}
</select>
</div>
+ <div className="space-y-1 text-xs" data-testid="interpret-ocio">
+ <div className="grid grid-cols-[110px_minmax(0,1fr)] items-center gap-x-3">
+ <label htmlFor="interpret-ocio-file" className="text-fg-3">OCIO config</label>
+ <input
+ id="interpret-ocio-file"
+ type="file"
+ accept=".ocio,.yaml,.yml,text/plain"
+ onChange={(e) => { void importOcio(e.target.files?.[0]); e.target.value = ""; }}
+ className="min-w-0 text-[11px]"
+ data-testid="interpret-ocio-file"
+ />
+ </div>
+ {ocioError && <p className="text-[10px] text-red-400" data-testid="interpret-ocio-error">{ocioError}</p>}
+ {ocio && (
+ <div className="space-y-1" data-testid="interpret-ocio-result">
+ <div className="grid grid-cols-[110px_minmax(0,1fr)] items-center gap-x-3">
+ <label htmlFor="interpret-ocio-space" className="text-fg-3">Colour space</label>
+ <select
+ id="interpret-ocio-space"
+ value=""
+ onChange={(e) => e.target.value && setChoice(e.target.value as FootageColorPreset)}
+ className="h-7 w-full min-w-0 rounded border border-border bg-bg-2 px-1"
+ data-testid="interpret-ocio-select"
+ >
+ <option value="" disabled>{ocio.mapping.supported.length} supported of {ocio.mapping.supported.length + ocio.mapping.unsupported.length} in {ocio.fileName}</option>
+ {ocio.mapping.supported.map((space) => (
+ <option key={space.name} value={space.preset}>
+ {space.name} → {FOOTAGE_COLOR_PRESETS.find((p) => p.id === space.preset)?.label ?? space.preset}
+ </option>
+ ))}
+ </select>
+ </div>
+ {ocio.mapping.unsupported.length > 0 && (
+ <details className="text-[10px] leading-snug text-fg-3" data-testid="interpret-ocio-unsupported">
+ <summary className="cursor-pointer">{ocio.mapping.unsupported.length} colour spaces are not supported</summary>
+ <ul className="mt-1 space-y-0.5">
+ {ocio.mapping.unsupported.map((space) => (
+ <li key={space.name}><span className="text-fg-2">{space.name}</span>: {space.reason}</li>
+ ))}
+ </ul>
+ </details>
+ )}
+ </div>
+ )}
+ <p className="text-[10px] leading-snug text-fg-3">
+ Reads the colour space list of an .ocio file and applies the matching built-in preset. The config's own transforms and LUTs are not run.
+ </p>
+ </div>
{isVideo && (
<div className="grid grid-cols-[110px_minmax(0,1fr)] items-center gap-x-3 gap-y-2 text-xs" data-testid="interpret-timing">
<label htmlFor="interpret-fps" className="text-fg-3">Frame rate</label>
diff --git a/apps/web/src/components/editor/scopes/ScopesPanel.tsx b/apps/web/src/components/editor/scopes/ScopesPanel.tsx
index f34d5ae5..2da9d641 100644
--- a/apps/web/src/components/editor/scopes/ScopesPanel.tsx
+++ b/apps/web/src/components/editor/scopes/ScopesPanel.tsx
@@ -14,8 +14,8 @@ import {
} from "@openreel/core/video/scopes";
import { useUIStore } from "../../../stores/ui-store";
import { useTimelineStore } from "../../../stores/timeline-store";
-import { useProjectStore } from "../../../stores/project-store";
import { useColorMonitorStore } from "../../../stores/color-monitor-store";
+import { useProjectStore } from "../../../stores/project-store";
import { getPreviewCanvas } from "./preview-canvas-registry";
import {
frameHasContent,
@@ -229,6 +229,8 @@ const ScopesPanelBody: React.FC = () => {
const falseColor = useColorMonitorStore((s) => s.falseColor);
const setFalseColor = useColorMonitorStore((s) => s.setFalseColor);
const isPlaying = useTimelineStore((s) => s.playbackState === "playing");
+ // ACES mode: the Program monitor shows the output transform (RRT + ODT), and the scopes measure that picture.
+ const acesOutput = useProjectStore((s) => (s.project.settings.colorManagement === "aces" ? (s.project.settings.acesOutput ?? "srgb") : null));
const rootRef = useRef<HTMLDivElement>(null);
const scopeCanvasRef = useRef<HTMLCanvasElement>(null);
@@ -559,6 +561,15 @@ const ScopesPanelBody: React.FC = () => {
>
False colour
</Button>
+ {acesOutput ? (
+ <span
+ data-testid="scopes-aces-label"
+ title="ACES color management is on: the scopes read the Program monitor, which shows the ACES output transform, so they measure display-referred output code values."
+ className="rounded-[6px] bg-bg-2 px-1.5 py-0.5 text-[10px] text-fg-2"
+ >
+ ACES output · {acesOutput === "rec709" ? "Rec.709" : "sRGB"}
+ </span>
+ ) : null}
{isWaveform ? (
<select
aria-label="Waveform scale"
diff --git a/apps/web/src/desktop/DesktopApp.tsx b/apps/web/src/desktop/DesktopApp.tsx
index 30cd54cb..ed3104ac 100644
--- a/apps/web/src/desktop/DesktopApp.tsx
+++ b/apps/web/src/desktop/DesktopApp.tsx
@@ -17,6 +17,7 @@ import { useSettingsStore } from "../stores/settings-store";
import { usePluginManagerStore } from "../stores/plugin-manager-store";
import { keyboardShortcuts } from "../services/keyboard-shortcuts";
import { loadEditorModule } from "../editor-loader";
+import { warmAudioDevices } from "./audio-warmup";
import { useOnboardingStore } from "../stores/onboarding-store";
import { installOnboardingSync } from "../components/onboarding/shell/onboarding-sync";
import { handleProjectOpenedOnWelcomeRoute, isWelcomeRoute } from "../components/onboarding/shell/agent-flip";
@@ -45,6 +46,10 @@ const warmupSettled = new Promise<void>((resolve) => {
resolveWarmupSettled = resolve;
});
const AGENT_STACK_MAX_WAIT_MS = 6000;
+// After the editor route mounts, wait this long (then an idle slot) before loading the agent stack.
+const AGENT_STACK_SETTLE_MS = 1200;
+// On the welcome screen, load the agent stack after this long without the editor opening.
+const AGENT_STACK_WELCOME_WAIT_MS = 8000;
function whenIdle(callback: () => void, timeout: number): () => void {
if (typeof window.requestIdleCallback === "function") {
@@ -61,6 +66,8 @@ export function DesktopApp(): JSX.Element {
);
useEffect(() => {
mark("openreel:desktop-app-mounted");
+ // After the welcome screen is committed: see audio-warmup.ts.
+ warmAudioDevices(navigator);
// Warm the editor chunk and the engines (WebGPU adapter/device, audio,
// playback, export: ~1.1 s measured in the real app) while the welcome
// screen is showing, so "New project" does not wait for them. initialize()
@@ -239,17 +246,47 @@ export function DesktopApp(): JSX.Element {
return listener.handleMcpBridgeRequest(req);
});
const maxWait = window.setTimeout(resolveWarmupSettled, AGENT_STACK_MAX_WAIT_MS);
+ const inEditor = () => window.location.hash.startsWith("#/editor");
+ let scheduled = false;
+ let welcomeTimer: number | undefined;
+ let settleTimer: number | undefined;
+ const scheduleAgentStack = () => {
+ if (scheduled || cancelled) return;
+ scheduled = true;
+ window.removeEventListener("hashchange", onHash);
+ window.clearTimeout(welcomeTimer);
+ // A beat after the editor mounted, then an idle slot: the ~1 MB agent chunk's compile + evaluate must
+ // not run between the click on "New project" and the editor being interactive.
+ settleTimer = window.setTimeout(() => {
+ if (cancelled) return;
+ cancelIdle = whenIdle(() => {
+ loadAgentStack().catch((error) => {
+ console.warn("[desktop] agent/MCP bridge failed to load", error);
+ });
+ }, 1500);
+ }, AGENT_STACK_SETTLE_MS);
+ };
+ function onHash(): void {
+ if (inEditor()) scheduleAgentStack();
+ }
void warmupSettled.then(() => {
if (cancelled) return;
- cancelIdle = whenIdle(() => {
- loadAgentStack().catch((error) => {
- console.warn("[desktop] agent/MCP bridge failed to load", error);
- });
- }, 1500);
+ // The stack is only needed once something drives the editor, and an MCP request that arrives earlier
+ // loads it on demand (above). So it follows the editor opening; a session that stays on the welcome
+ // screen still gets it after a while, so the first agent call after a long idle is not cold.
+ if (inEditor()) {
+ scheduleAgentStack();
+ return;
+ }
+ window.addEventListener("hashchange", onHash);
+ welcomeTimer = window.setTimeout(scheduleAgentStack, AGENT_STACK_WELCOME_WAIT_MS);
});
return () => {
cancelled = true;
window.clearTimeout(maxWait);
+ window.clearTimeout(welcomeTimer);
+ window.clearTimeout(settleTimer);
+ window.removeEventListener("hashchange", onHash);
cancelIdle?.();
uninstall?.();
};
diff --git a/apps/web/src/desktop/audio-warmup.test.ts b/apps/web/src/desktop/audio-warmup.test.ts
new file mode 100644
index 00000000..cdefdefd
--- /dev/null
+++ b/apps/web/src/desktop/audio-warmup.test.ts
@@ -0,0 +1,35 @@
+import { describe, expect, it, vi } from "vitest";
+import { warmAudioDevices } from "./audio-warmup";
+
+describe("warmAudioDevices", () => {
+ it("starts one asynchronous device enumeration and does not wait for it", () => {
+ let resolve!: (value: unknown) => void;
+ const enumerateDevices = vi.fn(() => new Promise((r) => (resolve = r)));
+ expect(warmAudioDevices({ mediaDevices: { enumerateDevices } })).toBeUndefined();
+ expect(enumerateDevices).toHaveBeenCalledTimes(1);
+ resolve([]);
+ });
+
+ it("swallows a rejected enumeration (no unhandled rejection)", async () => {
+ const unhandled = vi.fn();
+ process.on("unhandledRejection", unhandled);
+ warmAudioDevices({ mediaDevices: { enumerateDevices: () => Promise.reject(new Error("denied")) } });
+ await new Promise((r) => setTimeout(r, 10));
+ process.off("unhandledRejection", unhandled);
+ expect(unhandled).not.toHaveBeenCalled();
+ });
+
+ it("swallows a synchronous throw and tolerates a missing mediaDevices", () => {
+ expect(() =>
+ warmAudioDevices({
+ mediaDevices: {
+ enumerateDevices: () => {
+ throw new Error("boom");
+ },
+ },
+ }),
+ ).not.toThrow();
+ expect(() => warmAudioDevices({})).not.toThrow();
+ expect(() => warmAudioDevices(undefined)).not.toThrow();
+ });
+});
diff --git a/apps/web/src/desktop/audio-warmup.ts b/apps/web/src/desktop/audio-warmup.ts
new file mode 100644
index 00000000..5efcef48
--- /dev/null
+++ b/apps/web/src/desktop/audio-warmup.ts
@@ -0,0 +1,17 @@
+/**
+ * Warms the OS audio stack off the main thread. The first `AudioContext` of an app run blocks its
+ * constructor for ~150 ms (output device discovery in the audio service, measured on macOS) and the
+ * editor creates one while it opens, i.e. on the "New project" path. `enumerateDevices()` is
+ * asynchronous and walks the same device list, after which the constructor takes ~45 ms. Without a
+ * capture permission the labels stay empty, so this neither prompts nor reveals anything.
+ * See apps/desktop/PERF.md, "Cold start round 2".
+ */
+export function warmAudioDevices(
+ nav: { mediaDevices?: { enumerateDevices(): Promise<unknown> } } | undefined,
+): void {
+ try {
+ void nav?.mediaDevices?.enumerateDevices().catch(() => undefined);
+ } catch {
+ // An optimisation: it must never break the app.
+ }
+}
diff --git a/apps/web/src/e2e-hook.ts b/apps/web/src/e2e-hook.ts
index 09b1d6ed..49e6f72d 100644
--- a/apps/web/src/e2e-hook.ts
+++ b/apps/web/src/e2e-hook.ts
@@ -68,6 +68,8 @@ import * as hueCurvesModule from "@openreel/core/video/hue-curves";
import * as lumetriPipelineModule from "@openreel/core/video/lumetri-pipeline";
import * as hdrWorkingModule from "@openreel/core/color/hdr-working";
import * as cameraLogModule from "@openreel/core/color/camera-log";
+import * as acesModule from "@openreel/core/color/aces";
+import * as acesOutputModule from "@openreel/core/color/aces-output";
import * as inputTransformModule from "@openreel/core/color/input-transform";
import * as hdrGpuModule from "@openreel/core/video/hdr-gpu";
import * as colorOutputModule from "@openreel/core/export/color-output";
@@ -233,6 +235,8 @@ export function installE2EHook(): void {
lumetriPipeline: lumetriPipelineModule,
hdrWorking: hdrWorkingModule,
cameraLog: cameraLogModule,
+ aces: acesModule,
+ acesOutput: acesOutputModule,
inputTransform: inputTransformModule,
hdrGpu: hdrGpuModule,
colorOutput: colorOutputModule,
diff --git a/apps/web/src/services/agent/chat-runtime.ts b/apps/web/src/services/agent/chat-runtime.ts
new file mode 100644
index 00000000..6ef28bb7
--- /dev/null
+++ b/apps/web/src/services/agent/chat-runtime.ts
@@ -0,0 +1,9 @@
+// The agent runtime the AI chat store needs once a turn is sent. It is imported lazily by
+// chat-store: these modules (the tool registry above all, ~1 MB of tool definitions) used to be a
+// static import of the store, and the store is a static import of the editor's settings dialog, so
+// every desktop editor open paid to load and compile the whole agent stack.
+export { runTurn } from "@openreel/agent";
+export { runExclusive } from "./host-lock";
+export { makeDirectBYOKClient, validateAIEndpoint } from "./direct-llm-transport";
+export { EditingSession } from "./editing-session";
+export { editingToolDefs, editingToolReadOnly, executeEditingTool, EDITING_SYSTEM } from "./editing-tools";
diff --git a/apps/web/src/services/agent/direct-llm-transport.ts b/apps/web/src/services/agent/direct-llm-transport.ts
index 11240061..7454b7f0 100644
--- a/apps/web/src/services/agent/direct-llm-transport.ts
+++ b/apps/web/src/services/agent/direct-llm-transport.ts
@@ -1,4 +1,4 @@
-import { makeClientFromSend, withRetry, LLMHttpError, parseRetryAfterMs, type LLMClient } from "@openreel/agent";
+import { makeClientFromSend, withRetry, LLMHttpError, parseRetryAfterMs, type LLMClient } from "@openreel/agent/llm";
import { isOllamaEndpoint, OLLAMA_ORIGINS_HINT } from "../ai-models";
import type { AIProvider } from "../../stores/ai-connection-store";
diff --git a/apps/web/src/services/agent/host-lock.ts b/apps/web/src/services/agent/host-lock.ts
new file mode 100644
index 00000000..26d810b2
--- /dev/null
+++ b/apps/web/src/services/agent/host-lock.ts
@@ -0,0 +1,17 @@
+let hostLock: Promise<unknown> = Promise.resolve();
+
+/**
+ * Serializes access to the shared host so a chat turn and an external MCP tool
+ * call never interleave their undo transactions on the same project-store.
+ *
+ * Lives apart from host-singleton so importing the lock does not import LiveEditorHost
+ * (and with it the whole agent tool registry).
+ */
+export function runExclusive<T>(fn: () => Promise<T>): Promise<T> {
+ const run = hostLock.then(fn, fn);
+ hostLock = run.then(
+ () => undefined,
+ () => undefined,
+ );
+ return run;
+}
diff --git a/apps/web/src/services/agent/host-singleton.ts b/apps/web/src/services/agent/host-singleton.ts
index aebed71b..0bea9a6b 100644
--- a/apps/web/src/services/agent/host-singleton.ts
+++ b/apps/web/src/services/agent/host-singleton.ts
@@ -11,17 +11,4 @@ export function getLiveEditorHost(): LiveEditorHost {
return (hostSingleton ??= new LiveEditorHost());
}
-let hostLock: Promise<unknown> = Promise.resolve();
-
-/**
- * Serializes access to the shared host so a chat turn and an external MCP tool
- * call never interleave their undo transactions on the same project-store.
- */
-export function runExclusive<T>(fn: () => Promise<T>): Promise<T> {
- const run = hostLock.then(fn, fn);
- hostLock = run.then(
- () => undefined,
- () => undefined,
- );
- return run;
-}
+export { runExclusive } from "./host-lock";
diff --git a/apps/web/src/services/ai-connection-test.ts b/apps/web/src/services/ai-connection-test.ts
index cac6f182..2a98ebb2 100644
--- a/apps/web/src/services/ai-connection-test.ts
+++ b/apps/web/src/services/ai-connection-test.ts
@@ -1,4 +1,4 @@
-import { LLMHttpError, type LLMClient } from "@openreel/agent";
+import { LLMHttpError, type LLMClient } from "@openreel/agent/llm";
import type { AIProvider } from "../stores/ai-connection-store";
import { isOllamaEndpoint, OLLAMA_ORIGINS_HINT } from "./ai-models";
import { makeDirectBYOKClient, validateAIEndpoint } from "./agent/direct-llm-transport";
diff --git a/apps/web/src/services/timeline-interchange.prproj.test.ts b/apps/web/src/services/timeline-interchange.prproj.test.ts
new file mode 100644
index 00000000..a9626f3d
--- /dev/null
+++ b/apps/web/src/services/timeline-interchange.prproj.test.ts
@@ -0,0 +1,38 @@
+import { readFileSync } from "node:fs";
+import { join } from "node:path";
+import { describe, expect, it } from "vitest";
+import { isPremiereProjectFile, previewTimelineFile } from "./timeline-interchange";
+
+const fixture = new Uint8Array(
+ readFileSync(join(process.cwd(), "..", "..", "packages", "core", "src", "interchange", "__fixtures__", "main-cut.prproj")),
+);
+
+describe("previewTimelineFile with a Premiere project", () => {
+ it("recognises .prproj names", () => {
+ expect(isPremiereProjectFile("Cut.PRPROJ")).toBe(true);
+ expect(isPremiereProjectFile("cut.xml")).toBe(false);
+ });
+
+ it("opens the biggest sequence, offers the others and re-reads a chosen one", async () => {
+ const preview = await previewTimelineFile("main-cut.prproj", fixture);
+ expect(preview.result.format).toBe("prproj");
+ expect(preview.result.sequenceName).toBe("Main Cut");
+ expect(preview.result.importReport?.dropped).toBe(1);
+ expect(preview.prproj?.sequences.map((s) => s.name).sort()).toEqual(["Alt Cut", "Lower Third Nest", "Main Cut"]);
+ const alt = preview.prproj!.sequences.find((s) => s.name === "Alt Cut")!;
+ const switched = preview.prproj!.select(alt.id);
+ expect(switched.result.sequenceName).toBe("Alt Cut");
+ expect(switched.prproj?.selectedId).toBe(alt.id);
+ });
+
+ it("sniffs gzip content even when the file name does not say .prproj", async () => {
+ const preview = await previewTimelineFile("renamed.bin", fixture);
+ expect(preview.result.format).toBe("prproj");
+ });
+
+ it("fails with a readable error on a corrupt project", async () => {
+ const bad = new Uint8Array(fixture);
+ bad.fill(9, 30, 90);
+ await expect(previewTimelineFile("bad.prproj", bad)).rejects.toThrow();
+ });
+});
diff --git a/apps/web/src/services/timeline-interchange.ts b/apps/web/src/services/timeline-interchange.ts
index c6fea621..b707e40b 100644
--- a/apps/web/src/services/timeline-interchange.ts
+++ b/apps/web/src/services/timeline-interchange.ts
@@ -113,9 +113,22 @@ export function exportTimelineInterchange(format: InterchangeFormat, sequenceId?
}
}
+export interface PrprojSequenceChoice {
+ readonly id: string;
+ readonly name: string;
+ readonly detail: string;
+ readonly nested: boolean;
+}
+
export interface TimelineImportPreview {
readonly filename: string;
readonly result: TimelineImportResult & { format: ImportableFormat };
+ /** .prproj only: every sequence of the file, the selected one, and a way to re-read another one. */
+ readonly prproj?: {
+ readonly sequences: readonly PrprojSequenceChoice[];
+ readonly selectedId: string;
+ readonly select: (id: string) => TimelineImportPreview;
+ };
}
interface TimelineImportState {
@@ -128,33 +141,74 @@ export const useTimelineImportStore = create<TimelineImportState>((set) => ({
setPreview: (preview) => set({ preview }),
}));
-/** Parse a timeline file (AAF binary, or xmeml / FCPXML / OTIO text) against the current media bin. */
-export function previewTimelineFile(filename: string, bytes: Uint8Array): TimelineImportPreview {
+const isPrprojName = (name: string): boolean => /\.prproj$/i.test(name);
+
+/** A .prproj import preview (Premiere project); the parser is loaded on demand, it is not part of the editor's first load. */
+async function previewPrproj(filename: string, bytes: Uint8Array): Promise<TimelineImportPreview> {
+ const core = await import("@openreel/core/interchange/prproj");
+ const doc = await core.readPrproj(bytes);
+ const project = useProjectStore.getState().project;
+ const build = (sequenceId?: string): TimelineImportPreview => {
+ const result = core.importPrprojDocument(doc, {
+ mediaItems: project.mediaLibrary.items,
+ frameRate: project.settings.frameRate,
+ ...(sequenceId ? { sequenceId } : {}),
+ });
+ return {
+ filename,
+ result,
+ prproj: {
+ selectedId: result.prproj.selectedId,
+ sequences: result.prproj.sequences.map((s) => ({
+ id: s.id,
+ name: s.name,
+ nested: s.nested,
+ detail: `${s.width}x${s.height} · ${Number(s.fps.toFixed(3))} fps · ${s.clipCount} clips`,
+ })),
+ select: (id) => build(id),
+ },
+ };
+ };
+ return build();
+}
+
+/** Parse a timeline file (.prproj, AAF binary, or xmeml / FCPXML / OTIO text) against the current media bin. */
+export async function previewTimelineFile(filename: string, bytes: Uint8Array): Promise<TimelineImportPreview> {
+ if (isPrprojName(filename) || (bytes.length > 2 && bytes[0] === 0x1f && bytes[1] === 0x8b)) return previewPrproj(filename, bytes);
const project = useProjectStore.getState().project;
const result = importTimelineFile(bytes, { mediaItems: project.mediaLibrary.items, frameRate: project.settings.frameRate });
return { filename, result };
}
+/** Read a timeline file the user picked or dropped and open the import dialog (errors become a toast). */
+export async function openTimelineFileForImport(file: File): Promise<void> {
+ try {
+ const buffer = await file.arrayBuffer();
+ useTimelineImportStore.getState().setPreview(await previewTimelineFile(file.name, new Uint8Array(buffer)));
+ } catch (error) {
+ toast.error("Could not read the timeline file", error instanceof Error ? error.message : undefined);
+ }
+}
+
+export const isPremiereProjectFile = isPrprojName;
+
/** File > Import timeline > Timeline XML… / AAF… — pick a file, then show the relink report. */
-export function openTimelineImport(kind: "xml" | "aaf" = "xml"): void {
+export function openTimelineImport(kind: "xml" | "aaf" | "prproj" = "xml"): void {
const input = document.createElement("input");
input.type = "file";
input.accept =
kind === "aaf"
? ".aaf,application/octet-stream"
- : ".xml,.fcpxml,.otio,.edl,.aaf,text/xml,application/xml,application/json,application/octet-stream";
+ : kind === "prproj"
+ ? ".prproj"
+ : ".xml,.fcpxml,.otio,.edl,.aaf,.prproj,text/xml,application/xml,application/json,application/octet-stream";
input.dataset.testid = "timeline-import-input";
input.style.display = "none";
input.addEventListener("change", () => {
const file = input.files?.[0];
input.remove();
if (!file) return;
- void file
- .arrayBuffer()
- .then((buffer) => useTimelineImportStore.getState().setPreview(previewTimelineFile(file.name, new Uint8Array(buffer))))
- .catch((error: unknown) =>
- toast.error("Could not read the timeline file", error instanceof Error ? error.message : undefined),
- );
+ void openTimelineFileForImport(file);
});
document.body.appendChild(input);
input.click();
diff --git a/apps/web/src/stores/chat-store.ts b/apps/web/src/stores/chat-store.ts
index 8fd967e7..a89f9121 100644
--- a/apps/web/src/stores/chat-store.ts
+++ b/apps/web/src/stores/chat-store.ts
@@ -1,7 +1,4 @@
import { create } from "zustand";
-import {
- runTurn,
-} from "@openreel/agent";
import type {
AgentEvent,
ConfirmDecision,
@@ -9,12 +6,16 @@ import type {
ToolResult,
LoopMessage,
} from "@openreel/agent";
-import { runExclusive } from "../services/agent/host-singleton";
-import { makeDirectBYOKClient, validateAIEndpoint } from "../services/agent/direct-llm-transport";
-import { EditingSession } from "../services/agent/editing-session";
import { resolveAIEditTarget, type AIEditTarget } from "../services/agent/edit-target";
import { aiUndoCheckpoint } from "../services/agent/undo-checkpoint";
-import { editingToolDefs, editingToolReadOnly, executeEditingTool, EDITING_SYSTEM } from "../services/agent/editing-tools";
+
+// The agent runtime (tool registry, editing tools, LLM transport) loads on the first send, not with the
+// editor: this store is statically imported by the settings dialog.
+let chatRuntime: Promise<typeof import("../services/agent/chat-runtime")> | undefined;
+const loadChatRuntime = () => (chatRuntime ??= import("../services/agent/chat-runtime").catch((error) => {
+ chatRuntime = undefined;
+ throw error;
+}));
import { useAIConnectionStore } from "./ai-connection-store";
import {
conversationTitle,
@@ -154,6 +155,8 @@ export const useChatStore = create<ChatState>((set, get) => ({
conversationStartedAt: null,
send: async (text: string) => {
+ // First, so the guards and the state they protect below still run in one synchronous stretch.
+ const { runTurn, runExclusive, makeDirectBYOKClient, validateAIEndpoint, EditingSession, editingToolDefs, editingToolReadOnly, executeEditingTool, EDITING_SYSTEM } = await loadChatRuntime();
const trimmed = text.trim();
if (!trimmed) return;
const current = get();
diff --git a/apps/web/vite.config.ts b/apps/web/vite.config.ts
index 457f9db1..6159c4ca 100644
--- a/apps/web/vite.config.ts
+++ b/apps/web/vite.config.ts
@@ -62,7 +62,7 @@ export default defineConfig({
// Desktop: every chunk is a request through the app:// protocol handler and a V8 compile unit, and the
// core barrel's small shared modules (executor, smart-bins, sequence-par, ...) were each split into a
// chunk of their own by the lazy dialogs. Fold chunks under this size into their neighbours.
- ...(isDesktop ? { experimentalMinChunkSize: 50_000 } : {}),
+ ...(isDesktop ? { experimentalMinChunkSize: 65_000 } : {}),
manualChunks: (id) => {
if (id.includes("node_modules/react") || id.includes("node_modules/react-dom")) return "react";
if (id.includes("node_modules/zustand")) return "zustand";
@@ -74,6 +74,11 @@ export default defineConfig({
// Desktop only: over HTTP/2 the tiny chunks are cheap, so the web build keeps its smaller
// initial closure (bundle-budgets.json).
if (isDesktop && id.includes("node_modules/lucide-react")) return "icons";
+ // Desktop: multicam-workflow is shared by the lazy multicam panel and the agent bridge but is
+ // only ~13 KB, so experimentalMinChunkSize folded it into the chunk that also holds the desktop
+ // shell's WindowControls, and the welcome screen then statically imported the whole export
+ // engine through it. A chunk of its own keeps the shell's closure small.
+ if (isDesktop && id.includes("/components/editor/inspector/multicam-workflow")) return "multicam-workflow";
},
},
},
diff --git a/docs/PREMIERE-GAPS.md b/docs/PREMIERE-GAPS.md
index 9a4084e6..4947db35 100644
--- a/docs/PREMIERE-GAPS.md
+++ b/docs/PREMIERE-GAPS.md
@@ -23,18 +23,26 @@
| 12 | Fonts not embedded or reported | Closed for TTF/OTF/WOFF/WOFF2: missing-font report on open and licence-aware embedding (`missing-fonts.test.ts`, `font-embedding.test.ts`). WOFF2 is read via `DecompressionStream("brotli")` or, in the desktop app, the main-process Node zlib bridge (`fonts:brotliDecompress`), or else the bundled `brotli-dec-wasm` decoder (lazy chunk), so every browser can embed it. |
| 13 | `path` shape draws nothing | Closed. Path shapes render from SVG path data or point lists (`shape-path.test.ts`). |
+### `.prproj` import
+
+**Partly closed.** File > Import timeline > Premiere project (.prproj)..., or dropping a `.prproj` on the Project panel, reads a gzip Premiere project (`packages/core/src/interchange/prproj.ts`). It reads: the object graph (ObjectID/ObjectRef, ObjectUID/ObjectURef), bins and master clips (bins are recreated for offline media), the sequences with frame rate and resolution (a picker chooses which one to import; the others are listed in the report), video and audio tracks, clip items with in/out/start/end in ticks (254016000000 per second, BigInt exact), enabled/disabled (imported transparent and muted: OpenReel has no clip enable switch), constant speed and reverse, track targeting, locks and mute, Motion position/scale/rotation, Opacity and Volume level (start value), sequence markers (range markers and chapter type), cross dissolve and dip to black/white, and nested sequences (as OpenReel nested sequences). Linked audio of a video clip is merged into that video clip, like the XMEML importer. Media is relinked to the bin by file name; the rest becomes offline placeholders for the existing relink flow. The commit is one `project/applyEditSnapshot` (one undo step, bins and nested sequences included).
+
+Everything it cannot place goes in an import report shown before the import (dropped / approximated per clip), not silently: other effects (Lumetri and every effect besides Motion/Opacity/Volume), time-remap ramps, keyframed Motion/Opacity/Volume (start value used), anchor point, blend modes, non-uniform scale, other transitions and audio crossfades, titles/captions/graphics, adjustment layers and mattes. Master-clip markers, track mixer settings and Productions are not read.
+
+**Not verified against Premiere.** No `.prproj` written by Adobe Premiere Pro was available. The element names and layout follow Premiere's saved-project structure as it is publicly documented and remembered (`docs/interchange.md` lists the walk), the reader looks names up tolerantly, and the tests use hand-authored gzip fixtures that follow that layout. Speed/reverse, disabled, targeting and the Motion position units (normalised 0..1 vs pixels is guessed from the value range) are the least certain parts. Real projects may use element spellings that are not read yet; those clips would show up in the report or import without that property. Tested by `prproj.test.ts` (tick math, graph, report, undo) and `e2e/interchange-prproj.spec.ts`.
+
### Work packages (section 3)
- **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.
-- **WP4 Colour fidelity:** closed for the LUT parser, 1D LUTs, LUT library, `.cube` export, Input LUT, scope modes, false colour, nit scale and saved looks. White-balance eyedropper is closed (Program-monitor sampling, point / 5x5, one undo step; `white-balance-eyedropper.test.ts`). Camera-log presets (Sony, Panasonic, ARRI, Canon, Nikon, Fujifilm, Blackmagic; formula based, Interpret Footage and Color tab picker) are in. **Open:** ACES / OCIO.
+- **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: 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, `.prproj` and Dynamic Link, `.mogrt`, ACES/OCIO, 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, 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.
## 1. Verdict
@@ -86,7 +94,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, `.prproj` read and Dynamic Link, `.mogrt` interchange, ACES/OCIO and display P3, HDR monitoring and Dolby Vision, spectral editing, ML speech enhancement, multicam editable sources and angle add/replace.
+- **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.
- **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.
diff --git a/docs/colour-management.md b/docs/colour-management.md
index e12ddeb5..de821f56 100644
--- a/docs/colour-management.md
+++ b/docs/colour-management.md
@@ -64,3 +64,29 @@ Unit: `packages/core/src/color/*.test.ts`, `apps/desktop/test/color-output-args.
## Camera RAW input
Camera RAW stills (DNG) are developed by OpenReel (`packages/core/src/raw/`, see `docs/raw.md`) into an sRGB-encoded 8-bit image in the primaries of the item's RAW output colour space (sRGB/Rec.709, Display P3 or Rec.2020). `inputSpaceForItem` returns that space for RAW items whatever the decode path, so the input transform above converts P3 / Rec.2020 RAW to the working image in preview and export; sRGB output has no transform. The scene-linear Float32 development (`developRawLinear`) is not yet fed into the Rec.2020 HDR working mode.
+
+## ACES colour management (project setting)
+
+Preview options > Color management: **Display-referred** (default, the pipeline described above, unchanged: the Rec.709 SDR path is byte-identical, checked by `hdr-float-effects.spec.ts` "SDR projects render byte-identically") or **ACES**. The choice is `project.settings.colorManagement` (`"aces"` or absent) and the SDR output transform is `settings.acesOutput` (`"srgb"` or `"rec709"`, absent = sRGB). Both go through `project/updateSettings`, so a change is one undo step, and both are part of the project file (checked by save / load in `aces-color.spec.ts`) and of the render-cache key.
+
+Code: `packages/core/src/color/aces.ts` (primaries, matrices, ACEScct, settings helpers; in the startup bundle), `color/aces-output.ts` (RRT, ODT, splines, HDR tone scale; lazy, registered by the video engine), `video/aces-glsl.ts` (GLSL port of the output transform, built from the same TypeScript constants), `color/hdr-working.ts` (pipeline selection, IDT, ACEScct grade, CPU compositor), `video/hdr-gpu.ts` (WebGL2 compositor), `color/ocio-config.ts`.
+
+### Pipeline
+
+ACES mode runs the float compositor of "Scene-referred HDR working mode" (above) with a different colour pipeline:
+
+1. **Input transform (IDT).** The existing decoders (sRGB, Rec.709, Rec.2020, P3, PQ, HLG, the nine camera log curves, linear, ACEScct) give scene-linear light where 1.0 is SDR reference white and 18% grey is 0.18, the same numbers as ACES scene values. The source primaries go to **AP1 (ACEScg)** with a Bradford adaptation from the source white to the ACES white (`gamutToAp1`). The input colour space of a clip is, in order: the clip's own override (Color tab > Camera input > "This clip only", `clip/setColorInterpretation`), the footage item's Interpret Footage choice, the file's tags (desktop decode), else sRGB. New Interpret Footage presets: ACEScg, ACES2065-1, ACEScct, Linear Rec.709 / Rec.2020 / Display P3.
+2. **Working space.** ACEScg, half float on the GPU or Float32 in the CPU reference, composited "over" in linear light. 8-bit overlays (titles, shapes, subtitles, clips that need the 8-bit path) enter through the sRGB IDT at the project's graphics white (203 nits = scene 1.0 by default).
+3. **Grading in ACEScct.** The Lumetri stages run on `acescctEncode(linear)` instead of the PQ encoding. Exposure is still a linear gain, a positive vignette lifts towards ACEScct(1.0). Negative scene light is floored at 0 for the grade.
+4. **Output Transform (RRT + ODT)**, from the ACES 1.3 CTL (`ampas/aces-dev` tag v1.3): sRGB (`RRT.ctl` + `ODT.Academy.sRGB_100nits_dim.ctl`), Rec.709 BT.1886 (`ODT.Academy.Rec709_100nits_dim.ctl`), Rec.2020 PQ 1000 nit (`RRTODT.Academy.Rec2020_1000nits_15nits_ST2084.ctl`), Rec.2020 HLG (`..._HLG.ctl`). The monitor, the render cache and SDR exports use the project's SDR transform; an HDR10 export uses the PQ transform and an HLG export the HLG one, regardless of the project's SDR choice.
+5. **Where it shows.** In ACES mode every Program monitor frame (scrub, pause and playback) is rendered by the engine's compositor, the same one export uses, so the monitor is not a re-implementation. The native video-element playback fast path is switched off. The scopes read the monitor, so they measure the output transform's code values (labelled in the Scopes panel).
+
+### Verification
+
+- `packages/core/src/color/aces.test.ts`: matrices against the published ACES constants (AP0/AP1, AP1 to XYZ, ACEScg to Rec.709) and against colour-science (Bradford) for every standard and camera gamut; ACEScct / ACEScc anchors; spline anchors and inverses; the SDR output on 68 scene colours (neutrals, saturated reds, random) against OpenColorIO 2.6's builtin ACES 1.3 `SDR-VIDEO_1.0` transform, max error 5.4e-6 for sRGB codes and 2.1e-4 for BT.1886 (float32 near black); the 1000 nit HDR output against OCIO's `HDR-VIDEO-1000nit-15nit-REC2020lim_1.1`, within a relative 1e-3 (worst 4.6e-4, from a small difference in how OCIO derives the exposure shift of the HDR tone scale); PQ and HLG signal anchors. The reference values are in `color/fixtures/aces-ocio-reference.ts`, regenerated by `scripts/aces-reference.py`. HLG has no OCIO oracle: it is checked against BT.2100 anchors (203 nits to 0.75, 1000 to 1.0) and as the HLG encoding of the PQ transform's luminance.
+- `aces-pipeline.test.ts`: IDT (sRGB grey and red, every camera log's published 18% grey to neutral ACEScg 0.18, PQ / HLG), the compositor's view and PQ / HLG encode, ACEScct grade behaviour, setting undo / redo, validator, export output selection.
+- `apps/web/e2e/aces-color.spec.ts` (gpu project) and `fallback-aces-color.spec.ts` (no WebGPU, no GPU): the WebGL2 shader against the CPU reference on one composite (ACEScct grade, camera log layer, overlay): 8-bit view within 1 code (sRGB) / 3 codes (Rec.709, near-black amplification) on Apple Metal and within 1 / 1 on SwiftShader, PQ / HLG signal within 4.3e-4 / 1.8e-4; the product flow (menu, undo, save / load, per-clip override) with the ACES engine frame matching the CPU prediction within 3 codes (graded: 5) and the Program monitor matching the engine frame within 4 codes.
+
+### OCIO config import (partial)
+
+Interpret footage > OCIO config reads an `.ocio` file (`parseOcioConfig`): version, roles and every `!<ColorSpace>` entry with aliases, family, `isdata`, transform kinds, `BuiltinTransform` styles and LUT file names. `mapOcioColorSpaces` marks a space supported when a `BuiltinTransform` style equals one of the presets (ACEScct, ACEScg, ARRI LogC3 EI800 / AWG, LogC4, Canon Log 3, V-Log, S-Log3 / S-Gamut3.Cine), or when its name or alias is a well-known name from the ACES / "cg" reference configs (sRGB - Texture, Linear Rec.709 (sRGB), Linear Rec.2020, Linear P3-D65, ACES2065-1, ACEScg, ACEScct, Rec.2100-PQ / HLG ...) and it carries no LUT of its own. Picking a supported space applies the matching built-in preset. Everything else is listed with its reason (LUT file, parametric transform with no preset, data space, no recognised name). Tested on the OCIO-written builtin cg config (15 spaces: 8 mapped, 7 reported) and on a hand-written v1 config. OpenReel does not run the config's transforms, so a space that merely resembles a preset is only matched by name or builtin style, never by evaluating it; displays, views, looks, file rules, includes and `.ocioz` archives are ignored; the config is not stored in the project.
diff --git a/docs/interchange.md b/docs/interchange.md
index 9f0d2265..180cc168 100644
--- a/docs/interchange.md
+++ b/docs/interchange.md
@@ -1,6 +1,6 @@
# Timeline interchange
-Formats: XMEML (Final Cut Pro 7 XML v5, what Premiere Pro and DaVinci Resolve
+Formats: Premiere Pro projects (`.prproj`, import only; see below), XMEML (Final Cut Pro 7 XML v5, what Premiere Pro and DaVinci Resolve
read), FCPXML 1.10, CMX3600 EDL, OpenTimelineIO (OTIO) and AAF (edit only). The pure code lives
in `packages/core/src/interchange`; the editor (File > Export timeline) and the
agent (`export_timeline_xml`, `import_timeline_xml`) share it.
@@ -161,3 +161,28 @@ respected), CommentMarkers / DescriptiveMarkers and the start timecode (reported
available here). They follow the pyaaf2 layout those tools read, but host-specific behaviour (how a host
resolves linked media from an ImportDescriptor, how it reads a dissolve at a clip boundary, stereo as two mono
slots) is untested.
+
+## Premiere Pro project (.prproj), import only
+
+File > Import timeline > Premiere project (.prproj)..., the "Timeline XML..." picker and dropping a `.prproj` on the Project panel all open the same import dialog (sequence picker, import report, offline media list), then commit one undoable `project/applyEditSnapshot` (replace or append). The parser is loaded on demand (`@openreel/core/interchange/prproj`), so it is not part of the editor's first load. There is no `.prproj` export and no agent tool.
+
+A `.prproj` is gzip-compressed XML (`<PremiereData Version="3">`) of flat objects linked by `ObjectID`/`ObjectRef` and `ObjectUID`/`ObjectURef`. The importer walks:
+
+```
+RootProjectItem / BinProjectItem > ProjectItemContainer > Items > Item bins and project items
+ClipProjectItem > MasterClip > Clips > Clip (VideoClip | AudioClip)
+ > Clip > Source (VideoMediaSource | AudioMediaSource) > MediaSource > Media FilePath, ActualMediaFilePath, RelativePath, VideoStream, AudioStream
+Sequence > TrackGroups > TrackGroup (First 0 video / 1 audio, Second) > VideoTrackGroup | AudioTrackGroup
+ > TrackGroup > Tracks > Track > VideoClipTrack | AudioClipTrack
+ > ClipTrack > ClipItems > TrackItems > TrackItem > VideoClipTrackItem | AudioClipTrackItem
+ > ClipTrackItem > TrackItem > Start / End (ticks), SubClip > Clip (InPoint / OutPoint),
+ ComponentOwner > Components > VideoComponentChain > VideoFilterComponent > Params > VideoComponentParam
+Sequence > Markers > Marker (Start, Duration, Name, Comment, Type)
+ClipTrack > TransitionItems > VideoTransitionItem
+```
+
+Times are ticks: 254016000000 per second, parsed as BigInt so a 10 hour sequence keeps its frames (`ticksToFrames` is exact rational arithmetic, rounded to the nearest frame). A stream or track group `FrameRate` is ticks per frame. Out points beyond 2^60 (Premiere's "whole clip" sentinels) are treated as missing. Speed is `(out - in) / (end - start)` unless the item states `Speed` / `PlaybackSpeed`; `Reversed` / `PlayBackwards` or a negative speed reverse.
+
+What each piece becomes is listed in `docs/PREMIERE-GAPS.md` ("`.prproj` import"). The report (`importReport` on the import result) counts dropped and approximated items per clip and carries notes for what is never read.
+
+Verification status: OpenReel's own tests with hand-authored fixtures only (`__fixtures__/main-cut.prproj`, generated by `packages/core/scripts/gen-prproj-fixture.py`; the readable XML sits next to it). A project written by Adobe Premiere Pro has NOT been opened with this importer.
diff --git a/docs/known-limitations.md b/docs/known-limitations.md
index d7c032b0..03e36202 100644
--- a/docs/known-limitations.md
+++ b/docs/known-limitations.md
@@ -178,6 +178,15 @@ Shipped and verified in a real browser (`apps/web/e2e/color-pipeline.spec.ts`, `
- **Hue curves.** Hue vs Sat, Hue vs Hue, Hue vs Luma and Luma vs Sat in the Color tab (Hue Curves). A point at 0.5 is neutral; Hue vs Sat and Luma vs Sat scale saturation by 0 to 2, Hue vs Hue rotates up to 90 degrees, Hue vs Luma shifts lightness by up to 0.25. Each curve is baked to a 256-entry float LUT; the WebGL2 shader and the CPU reference read the same LUT and run the same arithmetic. In the e2e card (hue x saturation x lightness, all four curves plus wheels and Basic Correction) the GPU pass and the CPU reference differed by at most 0 levels on the test machine; the spec allows 3.
- **Processing order.** A clip's first grade now uses the Premiere-order pipeline (`pipelineVersion` 2): white balance, then Basic Correction, colour wheels and hue curves in one float pass, then Curves, LUT, HSL and Vignette. Clips that already carry a grade have no version and keep the classic order (wheels, then 8-bit tone/vignette/curves/LUT/HSL, then white balance) exactly as before; the Color tab shows the order and switches it with one undoable click. Hue curves do nothing on a classic clip (the editor says so and offers the switch).
+- **ACES colour management (project setting, see docs/colour-management.md).**
+ - **Which frames.** ACES mode renders through the float compositor. Frames with an active adjustment layer or text-behind-subject still take the classic display-referred path as a whole (the same rule as the Rec.2020 mode), so the look jumps while one is on screen. Clips that need the 8-bit path (masks, background removal, stabilisation, effects other than blur / sharpen / glow, 3D transforms, emphasis animations, interpolated slow motion, an Input LUT, compound clips, other transitions) are treated as already display-referred: their camera log / wide-gamut input transform is the display-referred one, and the result then goes through the sRGB IDT and the RRT, so they are not scene-referred ACES clips.
+ - **Transforms.** ACES 1.3 RRT + ODT only: no ACES 2.0, no Reference Gamut Compression or other LMT, no D60 sim, and the only HDR targets are Rec.2020 PQ 1000 nit (15 nit mid) and the matching HLG; no P3 / Display P3 monitor transform, 2000 / 4000 nit or cinema targets. The sRGB / Rec.709 ODT renders sRGB code 255 (ACES scene 1.0) at display 0.812, which is how ACES behaves; 8-bit titles therefore look slightly grey until HDR graphics white is raised. The camera IDTs are the log decoders already in the product with matrices computed from the published primaries (Bradford adaptation to the ACES white), not the manufacturers' own IDT matrices; they agree with colour-science to 1e-6 but have not been compared with a camera vendor's IDT. HLG is a port without an independent oracle (BT.2100 anchors only); the PQ transform is within a relative 1e-3 of OCIO's builtin, not bit exact.
+ - **Grade.** Sliders operate on ACEScct code values (mid grey 0.41, black 0.073), so they do not behave like the display-referred sliders: Basic Correction, wheels and curves are tuned for PQ / display values and are only a first approximation in ACEScct. An sRGB / linear LUT sees ACEScg light with the sRGB curve applied (not a display-referred picture), a "PQ" LUT sees PQ of the working linear.
+ - **Preview cost.** The Program monitor renders every ACES frame through the engine (WebGL2 half float; the Float32 CPU reference at about 1 s per 1080p frame where WebGL2 float targets are missing), and the native video-element playback path is off in ACES mode. Playback frame rates in ACES mode were not measured; the float composite of the existing HDR mode costs about 14 ms per 1080p frame on an Apple GPU and the ACES output pass was not timed separately.
+ - **Export.** An SDR export in ACES mode is the classic 8-bit encode of the output-transformed frame (tagged like any SDR export, nothing says ACES); HDR10 / HLG exports encode the PQ / HLG transform output. The HDR export path was verified at the encoded-signal level (CPU / GPU parity, unit values), not through a real 10-bit encode, and the desktop (Electron) path was not run.
+ - **Scopes** measure the Program monitor, i.e. output-transform code values, not ACEScct. The Working color space setting is ignored while ACES is on.
+ - **Input override.** Per footage item (Interpret footage) and per timeline clip (Color tab > Camera input > This clip only, undoable). On the web build the browser still converts tagged HDR / wide-gamut files before OpenReel sees them, so only an override changes how they are read there. The override is available to the user; ACES mode and the clip override are not exposed to the agent / MCP tools.
+ - **OCIO** is import-and-map only (see docs/colour-management.md): no evaluation of an OCIO config's transforms, LUTs, looks or views, no `.ocioz`, and a space is matched by builtin style or well-known name only.
- **Working colour space.** Preview options, Working color space: Rec.709 (default; exports are byte-for-byte what they were) or Rec.2020 (undoable). With Rec.2020 the export converts sRGB-referred pixels to BT.2020 primaries, encodes them as BT.2020 non-constant-luminance YCbCr and tags the file (colr/nclx, verified with ffprobe on an H.264 export: `bt2020` primaries, `bt2020nc` matrix, `bt709` transfer).
- **HDR export.** Export dialog, Custom Settings, Color / HDR: HDR10 (PQ) or HLG, 10-bit H.265 (Main10) in MP4/MOV, BT.2020 primaries, tagged in the container and in the frames handed to the encoder.
@@ -309,3 +318,9 @@ The panel (status bar pill and popover) is a presentation layer over `Background
- **Hardware encoding on the desktop is not offered with Two-pass VBR or Rec.2020 / HDR output** (hardware encoders have no two-pass mode; HDR needs libx265 for the HDR metadata). Choosing Hardware there is refused with the reason; Software and Auto work. A failed hardware encode with Hardware chosen is reported, not retried on the software encoder.
- **Hardware encoders (VideoToolbox, NVENC, Quick Sync, AMF) were exercised end to end only on VideoToolbox (macOS).** NVENC, Quick Sync and AMF are covered by argument and capability-mapping tests, not by a run on that hardware.
- **Create Proxies with a preset only targets clips that have no proxy (or a failed or missing one).** To rebuild an existing proxy in another preset, use Rebuild on the row after changing the preset in the Proxies panel.
+
+## Premiere projects (.prproj)
+
+- 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.
diff --git a/packages/core/scripts/gen-prproj-fixture.py b/packages/core/scripts/gen-prproj-fixture.py
new file mode 100644
index 00000000..458a8a79
--- /dev/null
+++ b/packages/core/scripts/gen-prproj-fixture.py
@@ -0,0 +1,310 @@
+import sys
+S = 254016000000
+def t(sec): return str(int(round(sec * S)))
+TPF25 = str(S // 25)
+TPF2997 = "8475667200"
+ids = {"n": 100}
+out = []
+def nid():
+ ids["n"] += 1
+ return str(ids["n"])
+def emit(s): out.append(s)
+
+def uid(prefix, n): return f"{prefix}-0000-4000-8000-{n:012d}"
+
+# ---- media -----------------------------------------------------------------
+medias = {}
+def media(key, n, path, title, video=None, audio=False, dur=None):
+ u = uid("aaaaaaaa", n)
+ vs = nid() if video else None
+ as_ = nid() if audio else None
+ medias[key] = dict(uid=u, vs=vs, as_=as_, video=video, audio=audio, dur=dur, path=path, title=title)
+ return medias[key]
+
+media("interview", 1, "/Volumes/Shoot/Day1/interview.mp4", "interview.mp4", video=(TPF2997, 1920, 1080), audio=True, dur=60)
+media("broll", 2, "/Volumes/Shoot/Day1/broll.mov", "broll.mov", video=(TPF25, 3840, 2160), audio=False, dur=30)
+media("music", 3, "C:\\Music\\theme song.wav", "theme song.wav", audio=True, dur=180)
+media("overlay", 4, "/Volumes/Shoot/Graphics/overlay.png", "overlay.png", video=(TPF25, 1280, 720), audio=False, dur=5)
+
+for k, m in medias.items():
+ emit(f'<Media ObjectUID="{m["uid"]}" ClassID="7a78f4f1-ca6b-4fd5-a8c8-87a6a8b1c0c7" Version="31">')
+ emit(f' <ImplementationID>00000000-0000-0000-0000-000000000000</ImplementationID>')
+ emit(f' <FilePath>{m["path"]}</FilePath>')
+ emit(f' <ActualMediaFilePath>{m["path"]}</ActualMediaFilePath>')
+ emit(f' <Title>{m["title"]}</Title>')
+ if m["vs"]: emit(f' <VideoStream ObjectRef="{m["vs"]}"/>')
+ if m["as_"]: emit(f' <AudioStream ObjectRef="{m["as_"]}"/>')
+ emit('</Media>')
+ if m["vs"]:
+ tpf, w, h = m["video"]
+ emit(f'<VideoStream ObjectID="{m["vs"]}" ClassID="a2f2f1c0-1b7f-4a5c-8c55-0f2f5b9c7d11" Version="3">')
+ emit(f' <FrameRate>{tpf}</FrameRate>')
+ emit(f' <FrameRect>0,0,{w},{h}</FrameRect>')
+ emit('</VideoStream>')
+ if m["as_"]:
+ emit(f'<AudioStream ObjectID="{m["as_"]}" ClassID="b3c3f2d1-2c80-4b6d-9d66-1a3a6c0d8e22" Version="2">')
+ emit(' <SampleRate>48000</SampleRate>')
+ emit(' <NumChannels>2</NumChannels>')
+ emit('</AudioStream>')
+
+# ---- master clips: clip -> source -> media ---------------------------------
+masters = {}
+def master(key, n, name):
+ m = medias[key]
+ mu = uid("bbbbbbbb", n)
+ pu = uid("cccccccc", n)
+ clips = []
+ for kind in (["video"] if m["vs"] else []) + (["audio"] if m["as_"] else []):
+ src, clip = nid(), nid()
+ cls = "VideoClip" if kind == "video" else "AudioClip"
+ scls = "VideoMediaSource" if kind == "video" else "AudioMediaSource"
+ emit(f'<{scls} ObjectID="{src}" ClassID="e64ddf70-d1d1-4c0e-9e37-6e6aa1cbd3a6" Version="2">')
+ emit(' <MediaSource Version="4">')
+ emit(f' <Media ObjectURef="{m["uid"]}"/>')
+ emit(f' <OriginalDuration>{t(m["dur"])}</OriginalDuration>')
+ emit(' </MediaSource>')
+ emit(f'</{scls}>')
+ emit(f'<{cls} ObjectID="{clip}" ClassID="9308dbef-2440-4acb-9ab2-953b9a4e82ec" Version="3">')
+ emit(' <Clip Version="18">')
+ emit(f' <Source ObjectRef="{src}"/>')
+ emit(' <InPoint>0</InPoint>')
+ emit(f' <OutPoint>{t(m["dur"])}</OutPoint>')
+ emit(' </Clip>')
+ if kind == "video": emit(f' <FrameRect>0,0,{m["video"][1]},{m["video"][2]}</FrameRect>')
+ emit(f'</{cls}>')
+ clips.append((kind, clip, src))
+ emit(f'<MasterClip ObjectUID="{mu}" ClassID="fb11c33a-b0a3-4d5f-9a6a-8b1b8a1d0a5a" Version="12">')
+ emit(' <Clips Version="1">')
+ for i, (_, c, _) in enumerate(clips): emit(f' <Clip Index="{i}" ObjectRef="{c}"/>')
+ emit(' </Clips>')
+ emit(f' <Name>{name}</Name>')
+ emit('</MasterClip>')
+ emit(f'<ClipProjectItem ObjectUID="{pu}" ClassID="cb4e0ed7-aca1-4f8a-b5f5-0ca8a9a1b3f7" Version="1">')
+ emit(f' <ProjectItem Version="1"><Name>{name}</Name></ProjectItem>')
+ emit(f' <MasterClip ObjectURef="{mu}"/>')
+ emit('</ClipProjectItem>')
+ masters[key] = dict(master=mu, item=pu, clips={k: (c, s) for k, c, s in clips})
+
+master("interview", 1, "interview.mp4")
+master("broll", 2, "broll.mov")
+master("music", 3, "theme song.wav")
+master("overlay", 4, "overlay.png")
+
+# ---- bins -------------------------------------------------------------------
+def bin_(n, name, children):
+ u = uid("dddddddd", n)
+ emit(f'<BinProjectItem ObjectUID="{u}" ClassID="dbfd21a6-b6d3-4b6a-a4a0-0e8d6c6b1d33" Version="1">')
+ emit(' <ProjectItemContainer Version="1"><Items Version="1">')
+ for i, c in enumerate(children): emit(f' <Item Index="{i}" ObjectURef="{c}"/>')
+ emit(' </Items></ProjectItemContainer>')
+ emit(f' <ProjectItem Version="1"><Name>{name}</Name></ProjectItem>')
+ emit('</BinProjectItem>')
+ return u
+
+graphics = bin_(1, "Graphics", [masters["overlay"]["item"]])
+footage = bin_(2, "Footage", [masters["interview"]["item"], masters["broll"]["item"], graphics])
+audio = bin_(3, "Audio", [masters["music"]["item"]])
+
+# ---- sequences ---------------------------------------------------------------
+seq_objs = {}
+def component(match, display, params):
+ pids = []
+ for name, cur, extra in params:
+ pid = nid()
+ pids.append(pid)
+ emit(f'<VideoComponentParam ObjectID="{pid}" ClassID="a8f0a3e5-57a1-4e8e-8a3a-9e0f8f2a9a44" Version="7">')
+ emit(f' <Name>{name}</Name>')
+ emit(f' <CurrentValue>{cur}</CurrentValue>')
+ if extra: emit(f' {extra}')
+ emit('</VideoComponentParam>')
+ cid = nid()
+ emit(f'<VideoFilterComponent ObjectID="{cid}" ClassID="0970b8ba-3d9f-4c4a-8a3c-3a64cf6a7b55" Version="9">')
+ emit(f' <Component Version="7"><Params Version="1">')
+ for i, p in enumerate(pids): emit(f' <Param Index="{i}" ObjectRef="{p}"/>')
+ emit(' </Params></Component>')
+ emit(f' <MatchName>{match}</MatchName>')
+ emit(f' <DisplayName>{display}</DisplayName>')
+ emit('</VideoFilterComponent>')
+ return cid
+
+def chain(comps):
+ cid = nid()
+ emit(f'<VideoComponentChain ObjectID="{cid}" ClassID="0d6e4a9d-4b5c-4d0e-8f9a-6a7b8c9d0e1f" Version="3">')
+ emit(' <ComponentChain Version="3"><Components Version="1">')
+ for i, c in enumerate(comps): emit(f' <Component Index="{i}" ObjectRef="{c}"/>')
+ emit(' </Components></ComponentChain>')
+ emit('</VideoComponentChain>')
+ return cid
+
+MOTION_DEFAULT = lambda: component("AE.ADBE Motion", "Motion", [("Position", "0.5:0.5", None), ("Scale", "100", None), ("Rotation", "0", None)])
+OPACITY = lambda v: component("AE.ADBE Opacity", "Opacity", [("Opacity", str(v), None)])
+
+def item(kind, name, mediakey, start, end, inp, outp, comps=None, disabled=False, speed=None, reverse=False, nested_seq=None):
+ """Return the track item ObjectID."""
+ m = masters.get(mediakey)
+ if nested_seq:
+ src, clip = nid(), nid()
+ emit(f'<VideoSequenceSource ObjectID="{src}" ClassID="1c9a8d37-0e7a-4d6f-b0c3-2f4e5d6c7b88" Version="1">')
+ emit(f' <Sequence ObjectURef="{nested_seq}"/>')
+ emit('</VideoSequenceSource>')
+ emit(f'<VideoClip ObjectID="{clip}" ClassID="9308dbef-2440-4acb-9ab2-953b9a4e82ec" Version="3">')
+ emit(f' <Clip Version="18"><Source ObjectRef="{src}"/><InPoint>{t(inp)}</InPoint><OutPoint>{t(outp)}</OutPoint></Clip>')
+ emit('</VideoClip>')
+ else:
+ base_clip, src = m["clips"][kind]
+ clip = nid()
+ cls = "VideoClip" if kind == "video" else "AudioClip"
+ emit(f'<{cls} ObjectID="{clip}" ClassID="9308dbef-2440-4acb-9ab2-953b9a4e82ec" Version="3">')
+ emit(f' <Clip Version="18"><Source ObjectRef="{src}"/><InPoint>{t(inp)}</InPoint><OutPoint>{t(outp)}</OutPoint></Clip>')
+ emit(f' <PlaybackSpeed>{speed if speed else 1}</PlaybackSpeed>' if False else '')
+ emit(f'</{cls}>')
+ sub = nid()
+ emit(f'<SubClip ObjectID="{sub}" ClassID="e0c6bd4a-5f55-4a76-9bd8-6f0d3a1c2e99" Version="5">')
+ emit(f' <Clip ObjectRef="{clip}"/>')
+ if m: emit(f' <MasterClip ObjectURef="{m["master"]}"/>')
+ emit(f' <Name>{name}</Name>')
+ emit('</SubClip>')
+ comp_chain = chain(comps or []) if comps is not None else None
+ iid = nid()
+ cls = "VideoClipTrackItem" if kind == "video" else "AudioClipTrackItem"
+ emit(f'<{cls} ObjectID="{iid}" ClassID="368b0d13-5e1c-4b0f-a9a2-5d7f3e0c1b77" Version="8">')
+ emit(' <ClipTrackItem Version="8">')
+ if comp_chain: emit(f' <ComponentOwner Version="1"><Components ObjectRef="{comp_chain}"/></ComponentOwner>')
+ emit(f' <SubClip ObjectRef="{sub}"/>')
+ emit(' <TrackItem Version="4">')
+ emit(f' <Start>{t(start)}</Start>')
+ emit(f' <End>{t(end)}</End>')
+ if disabled: emit(' <Disabled>true</Disabled>')
+ emit(' </TrackItem>')
+ if speed is not None: emit(f' <Speed>{speed}</Speed>')
+ if reverse: emit(' <PlayBackwards>true</PlayBackwards>')
+ emit(' </ClipTrackItem>')
+ emit(f'</{cls}>')
+ return iid
+
+def transition(name, start, end):
+ comp = component("AE.ADBE Cross Dissolve" if name == "Cross Dissolve" else "AE.ADBE Cross Zoom", name, [])
+ chn = chain([comp])
+ iid = nid()
+ emit(f'<VideoTransitionItem ObjectID="{iid}" ClassID="4a3b2c1d-0e9f-4a8b-9c7d-6e5f4a3b2c1d" Version="3">')
+ emit(' <TransitionTrackItem Version="3">')
+ emit(f' <ComponentOwner Version="1"><Components ObjectRef="{chn}"/></ComponentOwner>')
+ emit(f' <TrackItem Version="4"><Start>{t(start)}</Start><End>{t(end)}</End></TrackItem>')
+ emit(' </TransitionTrackItem>')
+ emit(f' <TransitionName>{name}</TransitionName>')
+ emit('</VideoTransitionItem>')
+ return iid
+
+track_uid = {"n": 0}
+def track(kind, idx, items, transitions=(), extra=""):
+ track_uid["n"] += 1
+ u = uid("eeeeeeee", track_uid["n"] + (0 if kind == "video" else 500))
+ cls = "VideoClipTrack" if kind == "video" else "AudioClipTrack"
+ emit(f'<{cls} ObjectUID="{u}" ClassID="e2b8bcd1-8f2d-4a6e-b1d8-7a1f2c3d4e55" Version="5">')
+ emit(' <ClipTrack Version="3">')
+ emit(f' <Track Version="4"><ID>{idx + 1}</ID><Index>{idx}</Index>{extra}</Track>')
+ emit(' <ClipItems Version="3"><TrackItems Version="1">')
+ for i, it in enumerate(items): emit(f' <TrackItem Index="{i}" ObjectRef="{it}"/>')
+ emit(' </TrackItems></ClipItems>')
+ if transitions:
+ emit(' <TransitionItems Version="1"><TrackItems Version="1">')
+ for i, it in enumerate(transitions): emit(f' <TrackItem Index="{i}" ObjectRef="{it}"/>')
+ emit(' </TrackItems></TransitionItems>')
+ emit(' </ClipTrack>')
+ emit(f'</{cls}>')
+ return u
+
+def group(kind, track_uids, tpf=TPF25, w=1920, h=1080):
+ gid = nid()
+ cls = "VideoTrackGroup" if kind == "video" else "AudioTrackGroup"
+ emit(f'<{cls} ObjectID="{gid}" ClassID="f1e2d3c4-b5a6-4978-8a9b-0c1d2e3f4a5b" Version="9">')
+ emit(' <TrackGroup Version="1">')
+ emit(' <Tracks Version="1">')
+ for i, u in enumerate(track_uids): emit(f' <Track Index="{i}" ObjectURef="{u}"/>')
+ emit(' </Tracks>')
+ if kind == "video":
+ emit(f' <FrameRect>0,0,{w},{h}</FrameRect>')
+ emit(f' <FrameRate>{tpf}</FrameRate>')
+ emit(' </TrackGroup>')
+ emit(f'</{cls}>')
+ return gid
+
+def marker(name, at, dur, comment, typ):
+ mid = nid()
+ emit(f'<Marker ObjectID="{mid}" ClassID="5b6c7d8e-9f0a-4b1c-8d2e-3f4a5b6c7d8e" Version="4">')
+ emit(f' <Name>{name}</Name><Comment>{comment}</Comment><Type>{typ}</Type>')
+ emit(f' <Start>{t(at)}</Start><Duration>{t(dur)}</Duration>')
+ emit('</Marker>')
+ return mid
+
+def markers(ids):
+ mid = nid()
+ emit(f'<Markers ObjectID="{mid}" ClassID="6c7d8e9f-0a1b-4c2d-9e3f-4a5b6c7d8e9f" Version="3">')
+ emit(' <Markers Version="1">')
+ for i, m in enumerate(ids): emit(f' <Marker Index="{i}" ObjectRef="{m}"/>')
+ emit(' </Markers>')
+ emit('</Markers>')
+ return mid
+
+def sequence(n, name, vgroup, agroup, mk=None):
+ u = uid("ffffffff", n)
+ emit(f'<Sequence ObjectUID="{u}" ClassID="6a15d903-8739-11d5-af2d-9b7855ad8974" Version="1">')
+ emit(' <Node Version="1"><Properties Version="1"/></Node>')
+ emit(' <TrackGroups Version="1">')
+ emit(f' <TrackGroup Version="1" Index="0"><First>0</First><Second ObjectRef="{vgroup}"/></TrackGroup>')
+ if agroup: emit(f' <TrackGroup Version="1" Index="1"><First>1</First><Second ObjectRef="{agroup}"/></TrackGroup>')
+ emit(' </TrackGroups>')
+ if mk: emit(f' <Markers ObjectRef="{mk}"/>')
+ emit(f' <Name>{name}</Name>')
+ emit('</Sequence>')
+ return u
+
+# Nest sequence: one clip of broll
+nest_item = item("video", "broll.mov", "broll", 0, 3, 1, 4, comps=[MOTION_DEFAULT()])
+nest_track = track("video", 0, [nest_item])
+nest_group = group("video", [nest_track])
+nest_seq = sequence(3, "Lower Third Nest", nest_group, None)
+
+# Alt cut
+alt_item = item("video", "interview.mp4", "interview", 0, 2, 0, 2)
+alt_track = track("video", 0, [alt_item])
+alt_group = group("video", [alt_track], tpf=TPF2997)
+alt_seq = sequence(2, "Alt Cut", alt_group, None)
+
+# Main cut
+v1_a = item("video", "interview.mp4", "interview", 0, 5, 2, 7, comps=[MOTION_DEFAULT(), OPACITY(100)])
+v1_b = item("video", "broll.mov", "broll", 5, 9, 0, 8, comps=[
+ component("AE.ADBE Motion", "Motion", [("Position", "0.75:0.25", None), ("Scale", "50", None), ("Rotation", "0", None)]),
+ OPACITY(100)])
+v1_c = item("video", "interview.mp4", "interview", 9, 11, 0, 2, disabled=True)
+tr = transition("Cross Dissolve", 4.5, 5.5)
+v1 = track("video", 0, [v1_a, v1_b, v1_c], transitions=[tr])
+
+v2_a = item("video", "overlay.png", "overlay", 1, 4, 0, 3, comps=[
+ MOTION_DEFAULT(), OPACITY(50),
+ component("AE.ADBE Gaussian Blur 2", "Gaussian Blur", [("Blurriness", "25", None)])])
+v2_b = item("video", "Lower Third Nest", None, 6, 8, 0, 2, nested_seq=nest_seq)
+v2 = track("video", 1, [v2_a, v2_b])
+
+a1_a = item("audio", "interview.mp4", "interview", 0, 5, 2, 7, comps=[component("AC.ADBE Volume", "Volume", [("Level", "1", None)])])
+a1 = track("audio", 0, [a1_a])
+a2_a = item("audio", "theme song.wav", "music", 0, 8, 0, 8, comps=[component("AC.ADBE Volume", "Volume", [("Level", "0.5", None)])])
+a2_b = item("audio", "theme song.wav", "music", 8, 10, 20, 22, reverse=True)
+a2 = track("audio", 1, [a2_a, a2_b], extra="<IsMuted>false</IsMuted><IsTargeted>true</IsTargeted>")
+
+vg = group("video", [v1, v2])
+ag = group("audio", [a1, a2])
+mk = markers([marker("Intro", 1, 0, "start here", "Comment"), marker("Chapter 2", 6, 2, "", "Chapter")])
+main_seq = sequence(1, "Main Cut", vg, ag, mk)
+
+root = nid()
+emit(f'<RootProjectItem ObjectUID="{uid("99999999", 1)}" ClassID="1e2f3a4b-5c6d-4e7f-8091-a2b3c4d5e6f7" Version="1">')
+emit(' <ProjectItemContainer Version="1"><Items Version="1">')
+for i, c in enumerate([footage, audio]): emit(f' <Item Index="{i}" ObjectURef="{c}"/>')
+emit(' </Items></ProjectItemContainer>')
+emit(' <ProjectItem Version="1"><Name>Root</Name></ProjectItem>')
+emit('</RootProjectItem>')
+
+body = "\n".join(l for l in out if l.strip())
+xml = '<?xml version="1.0" encoding="UTF-8" ?>\n<PremiereData Version="3">\n' + body + '\n</PremiereData>\n'
+open(sys.argv[1], "w").write(xml)
diff --git a/packages/core/src/actions/action-validator.ts b/packages/core/src/actions/action-validator.ts
index b0c586ec..56e0dcc1 100644
--- a/packages/core/src/actions/action-validator.ts
+++ b/packages/core/src/actions/action-validator.ts
@@ -143,7 +143,18 @@ export class ActionValidator {
path: "params",
});
} else if (action.type === "project/updateSettings") {
- const { pixelAspectRatio, fieldOrder } = action.params as { pixelAspectRatio?: unknown; fieldOrder?: unknown };
+ const { pixelAspectRatio, fieldOrder, colorManagement, acesOutput } = action.params as {
+ pixelAspectRatio?: unknown;
+ fieldOrder?: unknown;
+ colorManagement?: unknown;
+ acesOutput?: unknown;
+ };
+ if (colorManagement !== undefined && colorManagement !== "display-referred" && colorManagement !== "aces") {
+ errors.push({ code: "INVALID_PARAMS", message: "Colour management must be display-referred or aces", path: "params.colorManagement" });
+ }
+ if (acesOutput !== undefined && acesOutput !== "srgb" && acesOutput !== "rec709") {
+ errors.push({ code: "INVALID_PARAMS", message: "ACES output transform must be srgb or rec709", path: "params.acesOutput" });
+ }
if (
pixelAspectRatio !== undefined &&
!(typeof pixelAspectRatio === "number" && Number.isFinite(pixelAspectRatio) && pixelAspectRatio >= 0.25 && pixelAspectRatio <= 4)
diff --git a/packages/core/src/actions/handlers/clip-fx.test.ts b/packages/core/src/actions/handlers/clip-fx.test.ts
index d2b5863e..607a2894 100644
--- a/packages/core/src/actions/handlers/clip-fx.test.ts
+++ b/packages/core/src/actions/handlers/clip-fx.test.ts
@@ -98,6 +98,29 @@ describe("clip fx handlers", () => {
expect(res.success).toBe(false);
});
+ it("clip/setColorInterpretation sets a per-clip Interpret Footage override, validates it, and is undoable", async () => {
+ const executor = new ActionExecutor();
+ const project = makeProjectWithClip();
+ const set = await executor.execute(act("clip/setColorInterpretation", { clipId: "c1", colorInterpretation: "log-logc3" }), project);
+ expect(set.success).toBe(true);
+ expect(clipOf(project).colorInterpretation).toBe("log-logc3");
+ await executor.execute(act("clip/setColorInterpretation", { clipId: "c1", colorInterpretation: "aces-acescg" }), project);
+ expect(clipOf(project).colorInterpretation).toBe("aces-acescg");
+ // Clearing restores "use the footage setting".
+ await executor.execute(act("clip/setColorInterpretation", { clipId: "c1", colorInterpretation: null }), project);
+ expect(clipOf(project).colorInterpretation).toBeUndefined();
+ await executor.undo(project);
+ expect(clipOf(project).colorInterpretation).toBe("aces-acescg");
+ await executor.undo(project);
+ expect(clipOf(project).colorInterpretation).toBe("log-logc3");
+ await executor.undo(project);
+ expect(clipOf(project).colorInterpretation).toBeUndefined();
+ const bad = await executor.execute(act("clip/setColorInterpretation", { clipId: "c1", colorInterpretation: "ocio:Rec709" }), project);
+ expect(bad.success).toBe(false);
+ const missing = await executor.execute(act("clip/setColorInterpretation", { clipId: "nope", colorInterpretation: "srgb" }), project);
+ expect(missing.success).toBe(false);
+ });
+
it("clip/setReverse toggles reversed and is undoable", async () => {
const executor = new ActionExecutor();
const project = makeProjectWithClip({ reversed: false });
diff --git a/packages/core/src/actions/handlers/clip-fx.ts b/packages/core/src/actions/handlers/clip-fx.ts
index b2d3eb69..06cdfe67 100644
--- a/packages/core/src/actions/handlers/clip-fx.ts
+++ b/packages/core/src/actions/handlers/clip-fx.ts
@@ -3,6 +3,7 @@ import type { Project } from "../../types/project";
import { registerActionHandler } from "../registry";
import type { ActionHandler } from "../registry";
import { makeClipFieldHandler, findClip, patchClip } from "./clip-helpers";
+import { isFootageColorPreset } from "../../color/source-color";
import { CLIP_SPEED_MIN as SPEED_MIN, CLIP_SPEED_MAX as SPEED_MAX } from "../../editing/speed-limits";
@@ -111,6 +112,14 @@ const handlers = [
validateValue: (v) =>
v == null || typeof v === "boolean" ? null : "reversed must be a boolean",
}),
+ makeClipFieldHandler({
+ type: "clip/setColorInterpretation",
+ paramKey: "colorInterpretation",
+ field: "colorInterpretation",
+ validateValue: (v) =>
+ v == null || isFootageColorPreset(v) ? null : "colorInterpretation must be an Interpret Footage preset id",
+ transform: (v) => (v == null ? undefined : v),
+ }),
makeClipFieldHandler({
type: "clip/setPitchCorrection",
paramKey: "pitchCorrection",
diff --git a/packages/core/src/actions/handlers/edit-snapshot.ts b/packages/core/src/actions/handlers/edit-snapshot.ts
index c0ad3850..b65d6619 100644
--- a/packages/core/src/actions/handlers/edit-snapshot.ts
+++ b/packages/core/src/actions/handlers/edit-snapshot.ts
@@ -3,13 +3,13 @@ import { registerActionHandler, createInverseAction } from "../registry";
import { syncActiveSequence, withNestProjection } from "../../timeline/sequences";
/** Internal commit boundary. External documents must pass the portable validator. */
-export type EditSnapshot = Pick<Project, "name" | "settings" | "timeline" | "mediaLibrary" | "textClips" | "shapeClips" | "svgClips" | "stickerClips" | "adjustmentLayers" | "masks" | "particleEffects" | "multicamGroups" | "multicamSources" | "compoundClips" | "sequences" | "activeSequenceId" | "openSequenceIds" | "nestedInstances" | "motionCompositions" | "motionInstances" | "generatedShaders" | "creation" | "graphicInstances" | "linkedCompositions">;
+export type EditSnapshot = Pick<Project, "name" | "settings" | "timeline" | "mediaLibrary" | "textClips" | "shapeClips" | "svgClips" | "stickerClips" | "adjustmentLayers" | "masks" | "particleEffects" | "multicamGroups" | "multicamSources" | "compoundClips" | "sequences" | "activeSequenceId" | "openSequenceIds" | "nestedInstances" | "motionCompositions" | "motionInstances" | "generatedShaders" | "creation" | "graphicInstances" | "linkedCompositions" | "bins">;
export function editSnapshot(source: Project): EditSnapshot {
// The stored active sequence is stale until flushed: snapshot a consistent view.
const project = syncActiveSequence(source);
const { sequences, activeSequenceId, openSequenceIds } = project;
- const { name, settings, timeline, mediaLibrary, textClips, shapeClips, svgClips, stickerClips, adjustmentLayers, masks, particleEffects, multicamGroups, multicamSources, compoundClips, nestedInstances, motionCompositions, motionInstances, generatedShaders, creation, graphicInstances, linkedCompositions } = project;
- return { name, settings, timeline, mediaLibrary, textClips, shapeClips, svgClips, stickerClips, adjustmentLayers, masks, particleEffects, multicamGroups, multicamSources, compoundClips, sequences, activeSequenceId, openSequenceIds, nestedInstances, motionCompositions, motionInstances, generatedShaders, creation, graphicInstances, linkedCompositions };
+ const { name, settings, timeline, mediaLibrary, textClips, shapeClips, svgClips, stickerClips, adjustmentLayers, masks, particleEffects, multicamGroups, multicamSources, compoundClips, nestedInstances, motionCompositions, motionInstances, generatedShaders, creation, graphicInstances, linkedCompositions, bins } = project;
+ return { name, settings, timeline, mediaLibrary, textClips, shapeClips, svgClips, stickerClips, adjustmentLayers, masks, particleEffects, multicamGroups, multicamSources, compoundClips, sequences, activeSequenceId, openSequenceIds, nestedInstances, motionCompositions, motionInstances, generatedShaders, creation, graphicInstances, linkedCompositions, bins };
}
const optionalSnapshotFields = [
"textClips", "shapeClips", "svgClips", "stickerClips", "adjustmentLayers",
@@ -26,6 +26,8 @@ registerActionHandler({
for (const field of optionalSnapshotFields) {
if (snapshot[field] === undefined) Reflect.deleteProperty(project, field);
}
+ // Bins are restored too (an undo of an import that created bins removes them); snapshots that never mention bins leave them alone.
+ if ("bins" in snapshot && snapshot.bins === undefined) Reflect.deleteProperty(project, "bins");
if (project.sequences) {
// compoundClips is a projection of the non-active sequences: rebuild it.
const projected = withNestProjection({ ...project, compoundClips: undefined });
diff --git a/packages/core/src/actions/inverse-action-generator.ts b/packages/core/src/actions/inverse-action-generator.ts
index fa79e627..01d2581a 100644
--- a/packages/core/src/actions/inverse-action-generator.ts
+++ b/packages/core/src/actions/inverse-action-generator.ts
@@ -178,6 +178,8 @@ export class InverseActionGenerator {
...projectBefore.settings,
// Optional settings must be named so undo can clear a value the project did not have before.
workingColorSpace: projectBefore.settings.workingColorSpace,
+ colorManagement: projectBefore.settings.colorManagement,
+ acesOutput: projectBefore.settings.acesOutput,
graphicsWhiteNits: projectBefore.settings.graphicsWhiteNits,
channelLayout: projectBefore.settings.channelLayout,
startTimecode: projectBefore.settings.startTimecode,
diff --git a/packages/core/src/color/aces-output.ts b/packages/core/src/color/aces-output.ts
new file mode 100644
index 00000000..1eafa3cc
--- /dev/null
+++ b/packages/core/src/color/aces-output.ts
@@ -0,0 +1,535 @@
+/**
+ * ACES Output Transform (RRT + ODT) and its building blocks: the segmented splines, the RRT sweeteners, the SDR cinema
+ * ODT and the 1000 nit HDR transform with its PQ / HLG encodings. Ported from the ACES 1.3 CTL reference (see `aces.ts`
+ * for the sources and the units).
+ *
+ * This file is deliberately separate from `aces.ts` (the matrices, ACEScct and the settings helpers the startup bundle
+ * needs): the Output Transform is only run by the compositors, so the video engine registers it with
+ * `registerAcesOutputTransform` and the startup entry never carries it.
+ */
+
+import { gamutDef, gamutToXyz, invert3x3 } from "./camera-log";
+import {
+ AP0_TO_AP1,
+ AP1_RGB2Y,
+ AP1_TO_AP0,
+ AP1_TO_XYZ,
+ D60_TO_D65,
+ XYZ_TO_AP1,
+ type AcesMatrix3 as Matrix3,
+ type AcesOutputId,
+ type AcesSdrOutput,
+} from "./aces";
+
+const REC709_PRIMARIES = /* @__PURE__ */ gamutDef("rec709");
+const REC2020_PRIMARIES = /* @__PURE__ */ gamutDef("bt2020");
+// -- RRT building blocks (ACESlib.RRT_Common.ctl, ACESlib.Utilities_Color.ctl) ---------------------------------------
+
+const HALF_MIN = 5.96046448e-8;
+const HALF_MAX = 65504;
+const TINY = 1e-10;
+const log10 = Math.log10;
+
+const RRT_GLOW_GAIN = 0.05;
+const RRT_GLOW_MID = 0.08;
+const RRT_RED_SCALE = 0.82;
+const RRT_RED_PIVOT = 0.03;
+const RRT_RED_HUE = 0;
+const RRT_RED_WIDTH = 135;
+const RRT_SAT_FACTOR = 0.96;
+const ODT_SAT_FACTOR = 0.93;
+const DIM_SURROUND_GAMMA = 0.9811;
+const CINEMA_WHITE = 48;
+const CINEMA_BLACK = 0.02;
+
+/** The sat-adjust matrix of the CTL (`calc_sat_adjust_matrix`) in column-vector form: out = (1-s) Y + s c. */
+function satMatrix(sat: number): Matrix3 {
+ const [rw, gw, bw] = AP1_RGB2Y;
+ const k = 1 - sat;
+ return [
+ [k * rw + sat, k * gw, k * bw],
+ [k * rw, k * gw + sat, k * bw],
+ [k * rw, k * gw, k * bw + sat],
+ ];
+}
+export const RRT_SAT_MAT: Matrix3 = /* @__PURE__ */ satMatrix(RRT_SAT_FACTOR);
+export const ODT_SAT_MAT: Matrix3 = /* @__PURE__ */ satMatrix(ODT_SAT_FACTOR);
+
+function glowFwd(ycIn: number, glowGainIn: number, glowMid: number): number {
+ if (ycIn <= (2 / 3) * glowMid) return glowGainIn;
+ if (ycIn >= 2 * glowMid) return 0;
+ return glowGainIn * (glowMid / ycIn - 0.5);
+}
+
+function sigmoidShaper(x: number): number {
+ const t = Math.max(1 - Math.abs(x / 2), 0);
+ return (1 + Math.sign(x) * (1 - t * t)) / 2;
+}
+
+function cubicBasisShaper(x: number, w: number): number {
+ const knots0 = -w / 2;
+ const knots4 = w / 2;
+ let y = 0;
+ if (x > knots0 && x < knots4) {
+ const coord = ((x - knots0) * 4) / w;
+ const j = Math.trunc(coord);
+ const t = coord - j;
+ const m0 = t * t * t;
+ const m1 = t * t;
+ // Columns of the CTL's M matrix, selected by j (3, 2, 1, 0), dotted with {t^3, t^2, t, 1}.
+ if (j === 3) y = m0 * (-1 / 6) + m1 * (3 / 6) + t * (-3 / 6) + 1 / 6;
+ else if (j === 2) y = m0 * (3 / 6) + m1 * (-6 / 6) + t * 0 + 4 / 6;
+ else if (j === 1) y = m0 * (-3 / 6) + m1 * (3 / 6) + t * (3 / 6) + 1 / 6;
+ else if (j === 0) y = m0 * (1 / 6);
+ }
+ return (y * 3) / 2;
+}
+
+function rgbToSaturation(r: number, g: number, b: number): number {
+ const mx = Math.max(r, g, b);
+ const mn = Math.min(r, g, b);
+ return (Math.max(mx, TINY) - Math.max(mn, TINY)) / Math.max(mx, 1e-2);
+}
+
+function rgbToYc(r: number, g: number, b: number): number {
+ const chroma = Math.sqrt(Math.max(b * (b - g) + g * (g - r) + r * (r - b), 0));
+ return (b + g + r + 1.75 * chroma) / 3;
+}
+
+/** Geometric hue in degrees; NaN for neutrals like the CTL (a NaN hue gives the red modifier weight 0). */
+function rgbToHue(r: number, g: number, b: number): number {
+ if (r === g && g === b) return Number.NaN;
+ let hue = (180 / Math.PI) * Math.atan2(Math.sqrt(3) * (g - b), 2 * r - g - b);
+ if (hue < 0) hue += 360;
+ return hue;
+}
+
+function centerHue(hue: number, center: number): number {
+ const h = hue - center;
+ if (h < -180) return h + 360;
+ if (h > 180) return h - 360;
+ return h;
+}
+
+/**
+ * `rrt_sweeteners`: glow module, red modifier, AP0 -> AP1, global desaturation. Input ACES2065-1 (AP0), output AP1
+ * with the RRT saturation applied, ready for a tone scale.
+ */
+function rrtSweeteners(r: number, g: number, b: number, out: number[]): void {
+ const saturation = rgbToSaturation(r, g, b);
+ const ycIn = rgbToYc(r, g, b);
+ const s = sigmoidShaper((saturation - 0.4) / 0.2);
+ const glow = 1 + glowFwd(ycIn, RRT_GLOW_GAIN * s, RRT_GLOW_MID);
+ r *= glow;
+ g *= glow;
+ b *= glow;
+ const hue = rgbToHue(r, g, b);
+ const weight = cubicBasisShaper(centerHue(hue, RRT_RED_HUE), RRT_RED_WIDTH);
+ r = r + weight * saturation * (RRT_RED_PIVOT - r) * (1 - RRT_RED_SCALE);
+ r = Math.min(Math.max(r, 0), HALF_MAX);
+ g = Math.min(Math.max(g, 0), HALF_MAX);
+ b = Math.min(Math.max(b, 0), HALF_MAX);
+ const a = AP0_TO_AP1;
+ let pr = a[0][0] * r + a[0][1] * g + a[0][2] * b;
+ let pg = a[1][0] * r + a[1][1] * g + a[1][2] * b;
+ let pb = a[2][0] * r + a[2][1] * g + a[2][2] * b;
+ pr = Math.min(Math.max(pr, 0), HALF_MAX);
+ pg = Math.min(Math.max(pg, 0), HALF_MAX);
+ pb = Math.min(Math.max(pb, 0), HALF_MAX);
+ const m = RRT_SAT_MAT;
+ out[0] = m[0][0] * pr + m[0][1] * pg + m[0][2] * pb;
+ out[1] = m[1][0] * pr + m[1][1] * pg + m[1][2] * pb;
+ out[2] = m[2][0] * pr + m[2][1] * pg + m[2][2] * pb;
+}
+
+// -- segmented splines (ACESlib.Tonescales.ctl, ACESlib.SSTS.ctl) ------------------------------------------------
+
+export interface SplineParams {
+ /** B-spline coefficients below the mid point (log10 of luminance): 6 for the c5 shape, 10 for c9. */
+ readonly coefsLow: readonly number[];
+ readonly coefsHigh: readonly number[];
+ readonly minX: number;
+ readonly minY: number;
+ readonly midX: number;
+ readonly midY: number;
+ readonly maxX: number;
+ readonly maxY: number;
+ readonly slopeLow: number;
+ readonly slopeHigh: number;
+}
+
+function quadratic(c0: number, c1: number, c2: number, t: number): number {
+ return (0.5 * c0 - c1 + 0.5 * c2) * t * t + (-c0 + c1) * t + 0.5 * c0 + 0.5 * c1;
+}
+
+/** `segmented_spline_c5_fwd`, `segmented_spline_c9_fwd` and `ssts`: one implementation, the knot count follows the coefficient count. */
+export function splineForward(x: number, c: SplineParams): number {
+ const nLow = c.coefsLow.length - 2;
+ const nHigh = c.coefsHigh.length - 2;
+ const logx = log10(Math.max(x, HALF_MIN));
+ const logMinX = log10(c.minX);
+ const logMidX = log10(c.midX);
+ const logMaxX = log10(c.maxX);
+ let logy: number;
+ if (logx <= logMinX) {
+ logy = logx * c.slopeLow + (log10(c.minY) - c.slopeLow * logMinX);
+ } else if (logx < logMidX) {
+ const coord = ((nLow - 1) * (logx - logMinX)) / (logMidX - logMinX);
+ const j = Math.trunc(coord);
+ logy = quadratic(c.coefsLow[j], c.coefsLow[j + 1], c.coefsLow[j + 2], coord - j);
+ } else if (logx < logMaxX) {
+ const coord = ((nHigh - 1) * (logx - logMidX)) / (logMaxX - logMidX);
+ const j = Math.trunc(coord);
+ logy = quadratic(c.coefsHigh[j], c.coefsHigh[j + 1], c.coefsHigh[j + 2], coord - j);
+ } else {
+ logy = logx * c.slopeHigh + (log10(c.maxY) - c.slopeHigh * logMaxX);
+ }
+ return Math.pow(10, logy);
+}
+
+/** `segmented_spline_*_rev` / `inv_ssts`. */
+export function splineInverse(y: number, c: SplineParams): number {
+ const nLow = c.coefsLow.length - 2;
+ const nHigh = c.coefsHigh.length - 2;
+ const logMinX = log10(c.minX);
+ const logMidX = log10(c.midX);
+ const logMaxX = log10(c.maxX);
+ const knotIncLow = (logMidX - logMinX) / (nLow - 1);
+ const knotIncHigh = (logMaxX - logMidX) / (nHigh - 1);
+ const logy = log10(Math.max(y, 1e-10));
+ const solve = (coefs: readonly number[], nKnots: number, base: number, inc: number): number => {
+ const knotY: number[] = [];
+ for (let i = 0; i < nKnots; i++) knotY.push((coefs[i] + coefs[i + 1]) / 2);
+ let j = 0;
+ for (let k = 0; k < nKnots - 1; k++) {
+ if (logy > knotY[k] && logy <= knotY[k + 1]) {
+ j = k;
+ break;
+ }
+ if (k === 0 && logy === knotY[0]) {
+ j = 0;
+ break;
+ }
+ }
+ const c0 = coefs[j];
+ const c1 = coefs[j + 1];
+ const c2 = coefs[j + 2];
+ const a = 0.5 * c0 - c1 + 0.5 * c2;
+ const b = -c0 + c1;
+ const c = 0.5 * c0 + 0.5 * c1 - logy;
+ const d = Math.sqrt(b * b - 4 * a * c);
+ const t = (2 * c) / (-d - b);
+ return base + (t + j) * inc;
+ };
+ let logx: number;
+ if (logy <= log10(c.minY)) logx = logMinX;
+ else if (logy <= log10(c.midY)) logx = solve(c.coefsLow, nLow, logMinX, knotIncLow);
+ else if (logy < log10(c.maxY)) logx = solve(c.coefsHigh, nHigh, logMidX, knotIncHigh);
+ else logx = logMaxX;
+ return Math.pow(10, logx);
+}
+
+/** RRT tone scale (c5): `RRT_PARAMS` of ACESlib.Tonescales.ctl. */
+export const RRT_SPLINE: SplineParams = {
+ coefsLow: [-4.0, -4.0, -3.1573765773, -0.4852499958, 1.8477324706, 1.8477324706],
+ coefsHigh: [-0.7185482425, 2.0810307172, 3.6681241237, 4.0, 4.0, 4.0],
+ minX: 0.18 * Math.pow(2, -15),
+ minY: 0.0001,
+ midX: 0.18,
+ midY: 4.8,
+ maxX: 0.18 * Math.pow(2, 18),
+ maxY: 10000,
+ slopeLow: 0,
+ slopeHigh: 0,
+};
+
+/** The 48 nit cinema ODT tone scale (c9): `ODT_48nits`, whose points are the RRT spline at the stops 0.18 x 2^-6.5, 0.18 and 0.18 x 2^6.5. */
+export const ODT_48_SPLINE: SplineParams = {
+ coefsLow: [-1.6989700043, -1.6989700043, -1.4779, -1.2291, -0.8648, -0.448, 0.00518, 0.4511080334, 0.9113744414, 0.9113744414],
+ coefsHigh: [0.5154386965, 0.8470437783, 1.1358, 1.3802, 1.5197, 1.5985, 1.6467, 1.6746091357, 1.6878733390, 1.6878733390],
+ minX: /* @__PURE__ */ splineForward(0.18 * Math.pow(2, -6.5), RRT_SPLINE),
+ minY: 0.02,
+ midX: /* @__PURE__ */ splineForward(0.18, RRT_SPLINE),
+ midY: 4.8,
+ maxX: /* @__PURE__ */ splineForward(0.18 * Math.pow(2, 6.5), RRT_SPLINE),
+ maxY: 48,
+ slopeLow: 0,
+ slopeHigh: 0.04,
+};
+
+// -- single stage tone scale (ACESlib.SSTS.ctl) ------------------------------------------------------------------
+
+const MIN_STOP_SDR = -6.5;
+const MAX_STOP_SDR = 6.5;
+const MIN_STOP_RRT = -15;
+const MAX_STOP_RRT = 18;
+const MIN_LUM_SDR = 0.02;
+const MAX_LUM_SDR = 48;
+const MIN_LUM_RRT = 0.0001;
+const MAX_LUM_RRT = 10000;
+
+/** CTL `interpolate1D` over a two-row table, clamped at both ends. */
+function interpolate2(table: readonly [readonly [number, number], readonly [number, number]], x: number): number {
+ const [[x0, y0], [x1, y1]] = table;
+ if (x <= x0) return y0;
+ if (x >= x1) return y1;
+ return y0 + ((x - x0) / (x1 - x0)) * (y1 - y0);
+}
+
+function lookupAcesMin(minLum: number): number {
+ return 0.18 * Math.pow(2, interpolate2([[log10(MIN_LUM_RRT), MIN_STOP_RRT], [log10(MIN_LUM_SDR), MIN_STOP_SDR]], log10(minLum)));
+}
+function lookupAcesMax(maxLum: number): number {
+ return 0.18 * Math.pow(2, interpolate2([[log10(MAX_LUM_SDR), MAX_STOP_SDR], [log10(MAX_LUM_RRT), MAX_STOP_RRT]], log10(maxLum)));
+}
+
+/** `init_TsParams(minLum, maxLum, expShift)`. */
+export function initTsParams(minLum: number, maxLum: number, expShift = 0): SplineParams {
+ const minPt = { x: lookupAcesMin(minLum), y: minLum, slope: 0 };
+ const midPt = { x: 0.18, y: 4.8, slope: 1.55 };
+ const maxPt = { x: lookupAcesMax(maxLum), y: maxLum, slope: 0 };
+
+ const knotIncLow = (log10(midPt.x) - log10(minPt.x)) / 3;
+ const lowLine = (p: { x: number; y: number; slope: number }, dx: number): number => p.slope * (log10(p.x) + dx) + (log10(p.y) - p.slope * log10(p.x));
+ const cLow = [0, 0, 0, 0, 0];
+ cLow[0] = lowLine(minPt, -0.5 * knotIncLow);
+ cLow[1] = lowLine(minPt, 0.5 * knotIncLow);
+ cLow[3] = lowLine(midPt, -0.5 * knotIncLow);
+ cLow[4] = lowLine(midPt, 0.5 * knotIncLow);
+ const pctLow = interpolate2([[MIN_STOP_RRT, 0.18], [MIN_STOP_SDR, 0.35]], Math.log2(minPt.x / 0.18));
+ cLow[2] = log10(minPt.y) + pctLow * (log10(midPt.y) - log10(minPt.y));
+
+ const knotIncHigh = (log10(maxPt.x) - log10(midPt.x)) / 3;
+ const cHigh = [0, 0, 0, 0, 0];
+ cHigh[0] = lowLine(midPt, -0.5 * knotIncHigh);
+ cHigh[1] = lowLine(midPt, 0.5 * knotIncHigh);
+ cHigh[3] = lowLine(maxPt, -0.5 * knotIncHigh);
+ cHigh[4] = lowLine(maxPt, 0.5 * knotIncHigh);
+ const pctHigh = interpolate2([[MAX_STOP_SDR, 0.89], [MAX_STOP_RRT, 0.9]], Math.log2(maxPt.x / 0.18));
+ cHigh[2] = log10(midPt.y) + pctHigh * (log10(maxPt.y) - log10(midPt.y));
+
+ const shift = (x: number): number => Math.pow(2, Math.log2(x) - expShift);
+ return {
+ coefsLow: [cLow[0], cLow[1], cLow[2], cLow[3], cLow[4], cLow[4]],
+ coefsHigh: [cHigh[0], cHigh[1], cHigh[2], cHigh[3], cHigh[4], cHigh[4]],
+ minX: shift(minPt.x),
+ minY: minPt.y,
+ midX: shift(midPt.x),
+ midY: midPt.y,
+ maxX: shift(maxPt.x),
+ maxY: maxPt.y,
+ slopeLow: minPt.slope,
+ slopeHigh: maxPt.slope,
+ };
+}
+
+/** The HDR tone scale of an `outputTransform(Y_MIN, Y_MID, Y_MAX)`: init_TsParams with the exposure shift that puts 0.18 at Y_MID. */
+export function hdrToneScale(yMin: number, yMid: number, yMax: number): SplineParams {
+ const base = initTsParams(yMin, yMax);
+ const expShift = Math.log2(splineInverse(yMid, base)) - Math.log2(0.18);
+ return initTsParams(yMin, yMax, expShift);
+}
+
+/** Mastering display of the HDR output transforms (`Rec2020_1000nits_15nits`): black, mid grey and peak in nits. */
+export const HDR_1000_Y_MIN = 0.0001;
+export const HDR_1000_Y_MID = 15;
+export const HDR_1000_Y_MAX = 1000;
+export const HDR_1000_SPLINE: SplineParams = /* @__PURE__ */ hdrToneScale(HDR_1000_Y_MIN, HDR_1000_Y_MID, HDR_1000_Y_MAX);
+
+// -- display encodings (ACESlib.Utilities_Color.ctl) -------------------------------------------------------------
+
+/** `moncurve_r(y, 2.4, 0.055)`: the sRGB OETF with the exact 0.0031308 break. */
+function srgbOetf(y: number): number {
+ const gamma = 2.4;
+ const offs = 0.055;
+ const yb = Math.pow((offs * gamma) / ((gamma - 1) * (1 + offs)), gamma);
+ const rs = Math.pow((gamma - 1) / offs, gamma - 1) * Math.pow((1 + offs) / gamma, gamma);
+ return y >= yb ? (1 + offs) * Math.pow(y, 1 / gamma) - offs : y * rs;
+}
+
+/** `bt1886_r(L, 2.4, 1, 0)`: the BT.1886 inverse EOTF for a display with zero black. */
+function bt1886Oetf(l: number): number {
+ return Math.pow(Math.max(l, 0), 1 / 2.4);
+}
+
+const PQ_M1 = 0.1593017578125;
+const PQ_M2 = 78.84375;
+const PQ_C1 = 0.8359375;
+const PQ_C2 = 18.8515625;
+const PQ_C3 = 18.6875;
+
+/** `Y_2_ST2084`: absolute luminance in nits to the PQ signal. */
+export function nitsToPq(nits: number): number {
+ const lm = Math.pow(Math.max(nits, 0) / 10000, PQ_M1);
+ return Math.pow((PQ_C1 + PQ_C2 * lm) / (1 + PQ_C3 * lm), PQ_M2);
+}
+
+const HLG_A = 0.17883277;
+const HLG_B = 0.28466892;
+const HLG_C = 0.55991073;
+
+/**
+ * Display luminance (nits, 1000 nit peak, black 0) to the HLG signal: the inverse HLG OOTF for L_w = 1000 and gamma
+ * 1.2 (BT.2100 table 5), then the HLG OETF. `ST2084_2_HLG_1000nits_f3` of the CTL, entered from nits directly.
+ */
+export function displayNitsToHlg(r: number, g: number, b: number, out: number[]): void {
+ const yd = 0.2627 * r + 0.678 * g + 0.0593 * b;
+ const k = yd === 0 ? 0 : Math.pow(yd / 1000, (1 - 1.2) / 1.2);
+ const enc = (c: number): number => {
+ const scene = yd === 0 ? 0 : k * (c / 1000);
+ return scene <= 1 / 12 ? Math.sqrt(3 * scene) : HLG_A * Math.log(12 * scene - HLG_B) + HLG_C;
+ };
+ out[0] = enc(r);
+ out[1] = enc(g);
+ out[2] = enc(b);
+}
+
+// -- output transforms ---------------------------------------------------------------------------------------------
+
+export const XYZ_TO_REC709: Matrix3 = /* @__PURE__ */ invert3x3(/* @__PURE__ */ gamutToXyz(REC709_PRIMARIES));
+export const XYZ_TO_REC2020: Matrix3 = /* @__PURE__ */ invert3x3(/* @__PURE__ */ gamutToXyz(REC2020_PRIMARIES));
+export const REC2020_TO_XYZ: Matrix3 = /* @__PURE__ */ gamutToXyz(REC2020_PRIMARIES);
+
+/** `darkSurround_to_dimSurround` on AP1 linearCV (a gamma of 0.9811 on luminance Y of xyY). */
+function darkToDim(r: number, g: number, b: number, out: number[]): void {
+ const a = AP1_TO_XYZ;
+ const X = a[0][0] * r + a[0][1] * g + a[0][2] * b;
+ const Y0 = a[1][0] * r + a[1][1] * g + a[1][2] * b;
+ const Z = a[2][0] * r + a[2][1] * g + a[2][2] * b;
+ let sum = X + Y0 + Z;
+ if (sum === 0) sum = 1e-10;
+ const x = X / sum;
+ const y = Y0 / sum;
+ const Y = Math.pow(Math.min(Math.max(Y0, 0), HALF_MAX), DIM_SURROUND_GAMMA);
+ const yy = Math.max(y, 1e-10);
+ const X2 = (x * Y) / yy;
+ const Z2 = ((1 - x - y) * Y) / yy;
+ const m = XYZ_TO_AP1;
+ out[0] = m[0][0] * X2 + m[0][1] * Y + m[0][2] * Z2;
+ out[1] = m[1][0] * X2 + m[1][1] * Y + m[1][2] * Z2;
+ out[2] = m[2][0] * X2 + m[2][1] * Y + m[2][2] * Z2;
+}
+
+const scratch = [0, 0, 0];
+const scratch2 = [0, 0, 0];
+
+/**
+ * ACES2065-1 (AP0, scene-linear) to the display-encoded signal of an SDR output, per the CTL: RRT then
+ * `ODT.Academy.sRGB_100nits_dim` / `ODT.Academy.Rec709_100nits_dim`. Alpha is not touched.
+ */
+export function acesToSdrDisplay(r: number, g: number, b: number, output: AcesSdrOutput, out: number[]): void {
+ // RRT
+ rrtSweeteners(r, g, b, scratch);
+ const rr = splineForward(scratch[0], RRT_SPLINE);
+ const rg = splineForward(scratch[1], RRT_SPLINE);
+ const rb = splineForward(scratch[2], RRT_SPLINE);
+ // OCES = AP1 -> AP0, then the ODT takes it back to AP1 (the CTLs do both multiplications).
+ const a10 = AP1_TO_AP0;
+ const oR = a10[0][0] * rr + a10[0][1] * rg + a10[0][2] * rb;
+ const oG = a10[1][0] * rr + a10[1][1] * rg + a10[1][2] * rb;
+ const oB = a10[2][0] * rr + a10[2][1] * rg + a10[2][2] * rb;
+ const a01 = AP0_TO_AP1;
+ const pR = a01[0][0] * oR + a01[0][1] * oG + a01[0][2] * oB;
+ const pG = a01[1][0] * oR + a01[1][1] * oG + a01[1][2] * oB;
+ const pB = a01[2][0] * oR + a01[2][1] * oG + a01[2][2] * oB;
+ // ODT tone scale and scaling to linear code values
+ const scale = 1 / (CINEMA_WHITE - CINEMA_BLACK);
+ const lr = (splineForward(pR, ODT_48_SPLINE) - CINEMA_BLACK) * scale;
+ const lg = (splineForward(pG, ODT_48_SPLINE) - CINEMA_BLACK) * scale;
+ const lb = (splineForward(pB, ODT_48_SPLINE) - CINEMA_BLACK) * scale;
+ darkToDim(lr, lg, lb, scratch2);
+ const s = ODT_SAT_MAT;
+ const sr = s[0][0] * scratch2[0] + s[0][1] * scratch2[1] + s[0][2] * scratch2[2];
+ const sg = s[1][0] * scratch2[0] + s[1][1] * scratch2[1] + s[1][2] * scratch2[2];
+ const sb = s[2][0] * scratch2[0] + s[2][1] * scratch2[1] + s[2][2] * scratch2[2];
+ // AP1 -> XYZ -> D60 to D65 -> Rec.709 primaries
+ const x1 = AP1_TO_XYZ;
+ let X = x1[0][0] * sr + x1[0][1] * sg + x1[0][2] * sb;
+ let Y = x1[1][0] * sr + x1[1][1] * sg + x1[1][2] * sb;
+ let Z = x1[2][0] * sr + x1[2][1] * sg + x1[2][2] * sb;
+ const c = D60_TO_D65;
+ const X2 = c[0][0] * X + c[0][1] * Y + c[0][2] * Z;
+ const Y2 = c[1][0] * X + c[1][1] * Y + c[1][2] * Z;
+ const Z2 = c[2][0] * X + c[2][1] * Y + c[2][2] * Z;
+ X = X2;
+ Y = Y2;
+ Z = Z2;
+ const d = XYZ_TO_REC709;
+ const cr = Math.min(Math.max(d[0][0] * X + d[0][1] * Y + d[0][2] * Z, 0), 1);
+ const cg = Math.min(Math.max(d[1][0] * X + d[1][1] * Y + d[1][2] * Z, 0), 1);
+ const cb = Math.min(Math.max(d[2][0] * X + d[2][1] * Y + d[2][2] * Z, 0), 1);
+ const encode = output === "srgb" ? srgbOetf : bt1886Oetf;
+ out[0] = encode(cr);
+ out[1] = encode(cg);
+ out[2] = encode(cb);
+}
+
+/**
+ * ACES2065-1 to the display luminance (nits, Rec.2020 primaries, D65) of the 1000 nit HDR output transform: the
+ * `outputTransform` of ACESlib.OutputTransforms.ctl with Y_MIN 0.0001, Y_MID 15, Y_MAX 1000, Rec.2020 display and
+ * limiting primaries, stretched black.
+ */
+export function acesToHdr1000Nits(r: number, g: number, b: number, out: number[]): void {
+ rrtSweeteners(r, g, b, scratch);
+ const tr = splineForward(scratch[0], HDR_1000_SPLINE);
+ const tg = splineForward(scratch[1], HDR_1000_SPLINE);
+ const tb = splineForward(scratch[2], HDR_1000_SPLINE);
+ const span = 1 / (HDR_1000_Y_MAX - HDR_1000_Y_MIN);
+ const lr = (tr - HDR_1000_Y_MIN) * span;
+ const lg = (tg - HDR_1000_Y_MIN) * span;
+ const lb = (tb - HDR_1000_Y_MIN) * span;
+ const x1 = AP1_TO_XYZ;
+ const X = x1[0][0] * lr + x1[0][1] * lg + x1[0][2] * lb;
+ const Y = x1[1][0] * lr + x1[1][1] * lg + x1[1][2] * lb;
+ const Z = x1[2][0] * lr + x1[2][1] * lg + x1[2][2] * lb;
+ // limit_to_primaries (Rec.2020 limiting): clamp in the limiting RGB, back to XYZ
+ const q = XYZ_TO_REC2020;
+ const lim0 = Math.min(Math.max(q[0][0] * X + q[0][1] * Y + q[0][2] * Z, 0), 1);
+ const lim1 = Math.min(Math.max(q[1][0] * X + q[1][1] * Y + q[1][2] * Z, 0), 1);
+ const lim2 = Math.min(Math.max(q[2][0] * X + q[2][1] * Y + q[2][2] * Z, 0), 1);
+ const p = REC2020_TO_XYZ;
+ const Xl = p[0][0] * lim0 + p[0][1] * lim1 + p[0][2] * lim2;
+ const Yl = p[1][0] * lim0 + p[1][1] * lim1 + p[1][2] * lim2;
+ const Zl = p[2][0] * lim0 + p[2][1] * lim1 + p[2][2] * lim2;
+ const c = D60_TO_D65;
+ const X2 = c[0][0] * Xl + c[0][1] * Yl + c[0][2] * Zl;
+ const Y2 = c[1][0] * Xl + c[1][1] * Yl + c[1][2] * Zl;
+ const Z2 = c[2][0] * Xl + c[2][1] * Yl + c[2][2] * Zl;
+ const d = XYZ_TO_REC2020;
+ out[0] = Math.min(Math.max(d[0][0] * X2 + d[0][1] * Y2 + d[0][2] * Z2, 0), HALF_MAX) * HDR_1000_Y_MAX;
+ out[1] = Math.min(Math.max(d[1][0] * X2 + d[1][1] * Y2 + d[1][2] * Z2, 0), HALF_MAX) * HDR_1000_Y_MAX;
+ out[2] = Math.min(Math.max(d[2][0] * X2 + d[2][1] * Y2 + d[2][2] * Z2, 0), HALF_MAX) * HDR_1000_Y_MAX;
+}
+
+/**
+ * ACEScg (linear AP1, the pipeline's working space) to the display-encoded signal of an output transform.
+ * `out` receives R'G'B' in 0..1: sRGB / BT.1886 for the SDR ids, the PQ or HLG signal of a 1000 nit display for
+ * the Rec.2020 ids.
+ */
+export function acesOutputTransform(r: number, g: number, b: number, output: AcesOutputId, out: number[] = [0, 0, 0]): number[] {
+ const m = AP1_TO_AP0;
+ const ar = m[0][0] * r + m[0][1] * g + m[0][2] * b;
+ const ag = m[1][0] * r + m[1][1] * g + m[1][2] * b;
+ const ab = m[2][0] * r + m[2][1] * g + m[2][2] * b;
+ acesAp0Output(ar, ag, ab, output, out);
+ return out;
+}
+
+/** The same for an ACES2065-1 (AP0) input. */
+export function acesAp0Output(r: number, g: number, b: number, output: AcesOutputId, out: number[] = [0, 0, 0]): number[] {
+ if (output === "srgb" || output === "rec709") {
+ acesToSdrDisplay(r, g, b, output, out);
+ return out;
+ }
+ const nits = [0, 0, 0];
+ acesToHdr1000Nits(r, g, b, nits);
+ if (output === "rec2020-pq") {
+ out[0] = nitsToPq(nits[0]);
+ out[1] = nitsToPq(nits[1]);
+ out[2] = nitsToPq(nits[2]);
+ } else {
+ displayNitsToHlg(nits[0], nits[1], nits[2], out);
+ }
+ return out;
+}
+
diff --git a/packages/core/src/color/aces-pipeline.test.ts b/packages/core/src/color/aces-pipeline.test.ts
new file mode 100644
index 00000000..be799da2
--- /dev/null
+++ b/packages/core/src/color/aces-pipeline.test.ts
@@ -0,0 +1,309 @@
+import { describe, expect, it } from "vitest";
+import {
+ ACES_SDR_DECODE,
+ CpuHdrCompositor,
+ acesPipeline,
+ computeLayerGeometry,
+ decodeSourceToLinear,
+ decodeToWorkingLinear,
+ gradeHdrPixel,
+ hdrFrameToSdrRgba,
+ hdrPipelineFor,
+ hdrSourceDecode,
+ isHdrWorkingMode,
+ prepareHdrGrade,
+ registerAcesOutputTransform,
+ HDR_TRANSFER_ACESCCT,
+ type HdrLayerDraw,
+} from "./hdr-working";
+import { acescctEncode, acesOutputForExport, isAcesMode } from "./aces";
+import { acesOutputTransform } from "./aces-output";
+import { CAMERA_LOGS } from "./camera-log";
+import {
+ ACES_FOOTAGE_COLOR_PRESETS,
+ effectiveSourceColor,
+ footageColorPresetSpace,
+ inputSpaceForItem,
+ isFootageColorPreset,
+ type SourceColorSpace,
+} from "./source-color";
+import { outputColorForExport, pqEncodeNits, srgbToLinear } from "../export/color-output";
+import { ActionExecutor } from "../actions/action-executor";
+import { ActionHistory } from "../actions/action-history";
+import { ActionValidator } from "../actions/action-validator";
+import type { Project } from "../types/project";
+
+registerAcesOutputTransform(acesOutputTransform);
+
+const IDENT_T = { position: { x: 0, y: 0 }, scale: { x: 1, y: 1 }, rotation: 0, anchor: { x: 0.5, y: 0.5 }, opacity: 1, fitMode: "stretch" as const };
+const ACES = acesPipeline("srgb");
+const close = (a: number, b: number, tol: number) => expect(Math.abs(a - b)).toBeLessThanOrEqual(tol);
+
+function flat8(w: number, h: number, r: number, g: number, b: number, a = 255) {
+ const data = new Uint8ClampedArray(w * h * 4);
+ for (let p = 0; p < w * h; p++) data.set([r, g, b, a], p * 4);
+ return { depth: 8 as const, width: w, height: h, data };
+}
+function draw(w: number, h: number, extra: Partial<HdrLayerDraw> = {}): HdrLayerDraw {
+ return { geometry: computeLayerGeometry(IDENT_T, w, h, w, h), opacity: 1, grade: null, ...extra };
+}
+
+describe("ACES mode selection", () => {
+ it("only the aces colour management setting enters the float pipeline for a Rec.709 SDR project", () => {
+ expect(isAcesMode({})).toBe(false);
+ expect(isAcesMode({ colorManagement: "display-referred" })).toBe(false);
+ expect(isAcesMode({ colorManagement: "aces" })).toBe(true);
+ expect(isHdrWorkingMode({ workingColorSpace: "rec709" }, undefined)).toBe(false);
+ expect(isHdrWorkingMode({ workingColorSpace: "rec709", colorManagement: "aces" }, undefined)).toBe(true);
+ expect(hdrPipelineFor(undefined).kind).toBe("scene-hdr");
+ expect(hdrPipelineFor({ colorManagement: "aces", acesOutput: "rec709" })).toEqual({ kind: "aces", sdrOutput: "rec709" });
+ expect(hdrPipelineFor({ colorManagement: "aces" })).toEqual({ kind: "aces", sdrOutput: "srgb" });
+ });
+
+ it("an ACES SDR export is the 8-bit classic path; HDR exports keep their Rec.2020 PQ / HLG spec", () => {
+ const aces = { settings: { workingColorSpace: "rec2020" as const, colorManagement: "aces" as const } };
+ expect(outputColorForExport(aces, undefined)).toBeNull();
+ expect(outputColorForExport(aces, "pq")?.transfer).toBe("pq");
+ expect(outputColorForExport(aces, "hlg")?.transfer).toBe("hlg");
+ // Display-referred projects are unchanged.
+ expect(outputColorForExport({ settings: { workingColorSpace: "rec2020" } }, undefined)?.primaries).toBe("bt2020");
+ expect(outputColorForExport({ settings: { workingColorSpace: "rec709" } }, undefined)).toBeNull();
+ expect(acesOutputForExport({ colorManagement: "aces" }, "pq")).toBe("rec2020-pq");
+ });
+});
+
+describe("ACES input transforms (IDT)", () => {
+ it("sRGB / Rec.709 white and mid grey enter as ACES 1.0 and the sRGB-decoded grey", () => {
+ const white = decodeSourceToLinear(flat8(1, 1, 255, 255, 255), ACES_SDR_DECODE);
+ for (let c = 0; c < 3; c++) close(white.data[c], 1, 1e-5);
+ const grey = decodeSourceToLinear(flat8(1, 1, 118, 118, 118), hdrSourceDecode(null, ACES));
+ // sRGB code 118 is 18% grey.
+ for (let c = 0; c < 3; c++) close(grey.data[c], 0.18, 2e-3);
+ // A saturated sRGB red lands in AP1 with the published ACEScg values (Bradford): R 0.6131, G 0.0702, B 0.0206.
+ const red = decodeSourceToLinear(flat8(1, 1, 255, 0, 0), ACES_SDR_DECODE);
+ close(red.data[0], 0.6131, 1e-3);
+ close(red.data[1], 0.0702, 1e-3);
+ close(red.data[2], 0.0206, 1e-3);
+ });
+
+ it("every camera log preset maps its published 18% grey signal to neutral ACEScg 0.18", () => {
+ for (const def of CAMERA_LOGS) {
+ const space: SourceColorSpace = { primaries: def.gamut, transfer: def.id, matrix: "rgb", fullRange: true };
+ const decode = hdrSourceDecode(space, ACES);
+ const code = Math.round(def.grey18 * 65535);
+ const px = decodeSourceToLinear({ depth: 16, width: 1, height: 1, data: new Uint16Array([code, code, code, 65535]) }, decode);
+ for (let c = 0; c < 3; c++) close(px.data[c], 0.18, 2.5e-3);
+ }
+ });
+
+ it("Rec.2020, PQ and HLG sources decode to ACEScg with 203 nits at 1.0", () => {
+ const pq: SourceColorSpace = { primaries: "bt2020", transfer: "pq", matrix: "bt2020-ncl", fullRange: false };
+ const code = Math.round(pqEncodeNits(203) * 65535);
+ const px = decodeSourceToLinear({ depth: 16, width: 1, height: 1, data: new Uint16Array([code, code, code, 65535]) }, hdrSourceDecode(pq, ACES));
+ for (let c = 0; c < 3; c++) close(px.data[c], 1, 2e-3);
+ const hlg: SourceColorSpace = { primaries: "bt2020", transfer: "hlg", matrix: "bt2020-ncl", fullRange: false };
+ const hlgSdrWhite = Math.round(0.75 * 65535);
+ const h = decodeSourceToLinear({ depth: 16, width: 1, height: 1, data: new Uint16Array([hlgSdrWhite, hlgSdrWhite, hlgSdrWhite, 65535]) }, hdrSourceDecode(hlg, ACES));
+ for (let c = 0; c < 3; c++) close(h.data[c], 1, 2e-2);
+ });
+
+ it("ACES-native footage presets: ACEScg is a pass-through, ACES2065-1 goes AP0 -> AP1, ACEScct decodes the log", () => {
+ expect(ACES_FOOTAGE_COLOR_PRESETS.map((p) => p.id)).toEqual(["aces-acescg", "aces-aces2065", "aces-acescct", "linear-rec709", "linear-rec2020", "linear-p3"]);
+ for (const p of ACES_FOOTAGE_COLOR_PRESETS) expect(isFootageColorPreset(p.id)).toBe(true);
+ const cg = hdrSourceDecode(footageColorPresetSpace("aces-acescg"), ACES);
+ for (let i = 0; i < 3; i++) for (let j = 0; j < 3; j++) close(cg.toBt2020[i][j], i === j ? 1 : 0, 1e-9);
+ const ap0 = hdrSourceDecode(footageColorPresetSpace("aces-aces2065"), ACES);
+ // ACES2065-1 white (1,1,1) is ACEScg white (1,1,1).
+ for (const row of ap0.toBt2020) close(row[0] + row[1] + row[2], 1, 1e-6);
+ const cct = hdrSourceDecode(footageColorPresetSpace("aces-acescct"), ACES);
+ expect(cct.transfer).toBe(HDR_TRANSFER_ACESCCT);
+ close(decodeToWorkingLinear(acescctEncode(0.18), HDR_TRANSFER_ACESCCT), 0.18, 1e-9);
+ });
+
+ it("a clip's own override wins over the footage item's interpretation", () => {
+ const item = { colorInterpretation: "srgb" as const };
+ expect(effectiveSourceColor(item, "aces-acescg").primaries).toBe("ap1");
+ expect(inputSpaceForItem(item, "log-slog3")?.transfer).toBe("slog3");
+ // No override: the footage's own setting, and plain sRGB footage needs no transform.
+ expect(inputSpaceForItem(item)).toBeNull();
+ expect(inputSpaceForItem({}, "aces-acescg")?.primaries).toBe("ap1");
+ });
+
+ it("an ACES preset set on a footage item is honoured as the input colour space (the Interpret Footage override)", () => {
+ const item = { colorInterpretation: "aces-acescg" as const };
+ expect(effectiveSourceColor(item).primaries).toBe("ap1");
+ expect(inputSpaceForItem(item)?.primaries).toBe("ap1");
+ });
+});
+
+describe("ACES compositing and output", () => {
+ const w = 4;
+ const h = 3;
+
+ it("the SDR view is the Output Transform of the composited ACEScg image", () => {
+ const comp = new CpuHdrCompositor();
+ comp.setColorPipeline(ACES);
+ comp.begin(w, h);
+ comp.drawCodes(flat8(w, h, 118, 118, 118), hdrSourceDecode(null, ACES), draw(w, h));
+ const view = comp.readSdrView();
+ const expected = acesOutputTransform(0.18, 0.18, 0.18, "srgb");
+ for (let c = 0; c < 3; c++) close(view[c] / 255, expected[c], 1 / 255 + 1e-3);
+ expect(view[3]).toBe(255);
+ // The same image in the default pipeline is the tone-mapped display-referred view, not the ACES look.
+ const plain = new CpuHdrCompositor();
+ plain.begin(w, h);
+ plain.drawCodes(flat8(w, h, 118, 118, 118), hdrSourceDecode(null), draw(w, h));
+ expect(Math.abs(plain.readSdrView()[0] - view[0])).toBeGreaterThan(20);
+ });
+
+ it("Rec.709 output uses the BT.1886 encoding", () => {
+ const comp = new CpuHdrCompositor();
+ comp.setColorPipeline(acesPipeline("rec709"));
+ comp.begin(2, 2);
+ comp.drawCodes(flat8(2, 2, 118, 118, 118), hdrSourceDecode(null, acesPipeline("rec709")), draw(2, 2));
+ const expected = acesOutputTransform(0.18, 0.18, 0.18, "rec709");
+ close(comp.readSdrView()[0] / 255, expected[0], 1 / 255 + 1e-3);
+ });
+
+ it("8-bit overlays enter at graphics white through the sRGB IDT, in ACEScg", () => {
+ const comp = new CpuHdrCompositor();
+ comp.setColorPipeline(ACES);
+ comp.begin(2, 2);
+ comp.setGraphicsWhite(203);
+ comp.drawOverlay(flat8(2, 2, 255, 255, 255));
+ const frame = comp.readFrame();
+ for (let c = 0; c < 3; c++) close(frame.data[c], 1, 1e-5);
+ const view = comp.readSdrView();
+ close(view[0] / 255, acesOutputTransform(1, 1, 1, "srgb")[0], 1 / 255 + 1e-3);
+ });
+
+ it("HDR export encodes through the Rec.2020 PQ and HLG Output Transforms", () => {
+ const comp = new CpuHdrCompositor();
+ comp.setColorPipeline(ACES);
+ comp.begin(2, 2);
+ comp.drawCodes(flat8(2, 2, 118, 118, 118), hdrSourceDecode(null, ACES), draw(2, 2));
+ const pq = comp.readEncodedRgb({ primaries: "bt2020", transfer: "pq", matrix: "bt2020-ncl", fullRange: false, bitDepth: 10 });
+ // sRGB code 118 decodes to 0.1812 (the float image holds exactly that, in float32).
+ const v = srgbToLinear(118 / 255);
+ close(pq[0], acesOutputTransform(v, v, v, "rec2020-pq")[0], 2e-6);
+ const hlg = comp.readEncodedRgb({ primaries: "bt2020", transfer: "hlg", matrix: "bt2020-ncl", fullRange: false, bitDepth: 10 });
+ close(hlg[0], acesOutputTransform(v, v, v, "rec2020-hlg")[0], 2e-6);
+ expect(Math.abs(pq[0] - hlg[0])).toBeGreaterThan(0.02);
+ });
+
+ it("changes the picture against the display-referred pipeline for the same footage (the ACES look)", () => {
+ const ramp = new Uint8ClampedArray(w * h * 4);
+ for (let p = 0; p < w * h; p++) {
+ const v = Math.round((p / (w * h - 1)) * 255);
+ ramp.set([v, Math.round(v * 0.6), Math.round(v * 0.3), 255], p * 4);
+ }
+ const codes = { depth: 8 as const, width: w, height: h, data: ramp };
+ const classic = new CpuHdrCompositor();
+ classic.begin(w, h);
+ classic.drawCodes(codes, hdrSourceDecode(null), draw(w, h));
+ const aces = new CpuHdrCompositor();
+ aces.setColorPipeline(ACES);
+ aces.begin(w, h);
+ aces.drawCodes(codes, hdrSourceDecode(null, ACES), draw(w, h));
+ const a = classic.readSdrView();
+ const b = aces.readSdrView();
+ let differing = 0;
+ for (let i = 0; i < a.length; i += 4) if (Math.abs(a[i] - b[i]) > 3 || Math.abs(a[i + 1] - b[i + 1]) > 3) differing++;
+ expect(differing).toBeGreaterThan(w * h * 0.6);
+ });
+
+ it("hdrFrameToSdrRgba in the aces pipeline keeps alpha and clamps negative light", () => {
+ const data = new Float32Array([-0.5, 0.2, 0.1, 0.5]);
+ const out = hdrFrameToSdrRgba({ width: 1, height: 1, data }, ACES);
+ expect(out[3]).toBe(128);
+ expect(out[0]).toBeGreaterThanOrEqual(0);
+ });
+});
+
+describe("grading in ACEScct", () => {
+ it("prepareHdrGrade marks the spec for ACEScct only in the aces pipeline", () => {
+ expect(prepareHdrGrade({ temperature: 30 })?.acescct).toBeUndefined();
+ expect(prepareHdrGrade({ temperature: 30 }, ACES)?.acescct).toBe(true);
+ expect(prepareHdrGrade(undefined, ACES)).toBeNull();
+ });
+
+ it("an offset in the grade is an offset of ACEScct code values (white balance on mid grey)", () => {
+ const spec = prepareHdrGrade({ temperature: 30 }, ACES)!;
+ const [r, g, b] = gradeHdrPixel(0.18, 0.18, 0.18, spec);
+ const wb = spec.whiteBalance!;
+ const base = acescctEncode(0.18);
+ // decode(encode(x) + offset) = x * 2^(17.52 * offset) in the log segment.
+ close(Math.log2(r / 0.18), 17.52 * wb[0], 1e-6);
+ close(Math.log2(g / 0.18), 17.52 * wb[1], 1e-6);
+ close(Math.log2(b / 0.18), 17.52 * wb[2], 1e-6);
+ expect(base).toBeCloseTo(0.4135884, 6);
+ });
+
+ it("exposure is a linear gain and a neutral grade round-trips through ACEScct unchanged", () => {
+ const exposure = prepareHdrGrade({ tone: { exposure: 0.5, contrast: 0, highlights: 0, shadows: 0, whites: 0, blacks: 0 } }, ACES)!;
+ const [r] = gradeHdrPixel(0.18, 0.18, 0.18, exposure);
+ close(r, 0.18 * 2, 1e-5);
+ const lut = prepareHdrGrade({ lut: { data: identity(9), size: 9, intensity: 1, space: "linear" } }, ACES);
+ if (lut) {
+ const out = gradeHdrPixel(0.18, 0.05, 0.4, lut);
+ close(out[0], 0.18, 2e-3);
+ close(out[1], 0.05, 2e-3);
+ close(out[2], 0.4, 2e-3);
+ }
+ });
+
+ it("a positive vignette lifts towards SDR white in ACEScct, not towards the top of the encoding", () => {
+ const spec = prepareHdrGrade({ vignette: { amount: 1, midpoint: 0, roundness: 0, feather: 0.01 } }, ACES)!;
+ const [r] = gradeHdrPixel(0.18, 0.18, 0.18, spec, { nx: 1, ny: 1, aspect: 1 });
+ expect(r).toBeGreaterThan(0.18);
+ expect(r).toBeLessThanOrEqual(1.0001);
+ });
+});
+
+function identity(n: number): number[] {
+ const out: number[] = [];
+ for (let b = 0; b < n; b++) for (let g = 0; g < n; g++) for (let r = 0; r < n; r++) out.push((r / (n - 1)) * 255, (g / (n - 1)) * 255, (b / (n - 1)) * 255);
+ return out;
+}
+
+describe("project setting: undoable and persisted", () => {
+ function project(): Project {
+ return {
+ id: "aces",
+ name: "ACES",
+ createdAt: 1,
+ modifiedAt: 1,
+ settings: { width: 1920, height: 1080, frameRate: 30, sampleRate: 48000, channels: 2 },
+ mediaLibrary: { items: [] },
+ timeline: { tracks: [], subtitles: [], markers: [], duration: 0 },
+ };
+ }
+
+ it("switching to ACES and changing the output transform undo and redo as one step each", async () => {
+ const p = project();
+ const history = new ActionHistory();
+ const executor = new ActionExecutor(history);
+ await executor.execute({ type: "project/updateSettings", id: "a", timestamp: 2, params: { colorManagement: "aces" } }, p);
+ expect(p.settings.colorManagement).toBe("aces");
+ await executor.execute({ type: "project/updateSettings", id: "b", timestamp: 3, params: { acesOutput: "rec709" } }, p);
+ expect(p.settings.acesOutput).toBe("rec709");
+ await executor.undo(p);
+ expect(p.settings.acesOutput).toBeUndefined();
+ expect(p.settings.colorManagement).toBe("aces");
+ await executor.undo(p);
+ expect(p.settings.colorManagement).toBeUndefined();
+ await executor.redo(p);
+ expect(p.settings.colorManagement).toBe("aces");
+ });
+
+ it("the validator rejects unknown modes and output transforms", () => {
+ const validator = new ActionValidator();
+ const p = project();
+ const bad = validator.validate({ type: "project/updateSettings", id: "x", timestamp: 1, params: { colorManagement: "ocio" } } as never, p);
+ expect(bad.valid).toBe(false);
+ const bad2 = validator.validate({ type: "project/updateSettings", id: "y", timestamp: 1, params: { acesOutput: "rec2020-pq" } } as never, p);
+ expect(bad2.valid).toBe(false);
+ const ok = validator.validate({ type: "project/updateSettings", id: "z", timestamp: 1, params: { colorManagement: "aces", acesOutput: "srgb" } } as never, p);
+ expect(ok.valid).toBe(true);
+ });
+});
diff --git a/packages/core/src/color/aces.test.ts b/packages/core/src/color/aces.test.ts
new file mode 100644
index 00000000..902caa41
--- /dev/null
+++ b/packages/core/src/color/aces.test.ts
@@ -0,0 +1,293 @@
+import { describe, expect, it } from "vitest";
+import { ACES_REFERENCE as reference } from "./fixtures/aces-ocio-reference";
+import {
+ acescctDecode,
+ acescctEncode,
+ acesccEncode,
+ acesOutputForExport,
+ AP0_TO_AP1,
+ AP1_TO_AP0,
+ AP1_TO_XYZ,
+ D60_TO_D65,
+ gamutToAp0,
+ gamutToAp1,
+ type AcesOutputId,
+} from "./aces";
+import {
+ acesOutputTransform,
+ acesToHdr1000Nits,
+ displayNitsToHlg,
+ HDR_1000_SPLINE,
+ initTsParams,
+ nitsToPq,
+ ODT_48_SPLINE,
+ RRT_SPLINE,
+ splineForward,
+ splineInverse,
+} from "./aces-output";
+import { gamutDef } from "./camera-log";
+
+const close = (a: number, b: number, tol: number) => expect(Math.abs(a - b)).toBeLessThanOrEqual(tol);
+const closeMatrix = (a: readonly (readonly number[])[], b: readonly (readonly number[])[], tol: number) => {
+ for (let i = 0; i < 3; i++) for (let j = 0; j < 3; j++) close(a[i][j], b[i][j], tol);
+};
+
+describe("ACES matrices (published constants)", () => {
+ it("AP0 -> AP1 and back match S-2014-004 / the ACES CTL", () => {
+ closeMatrix(
+ AP0_TO_AP1,
+ [
+ [1.4514393161, -0.2365107469, -0.2149285693],
+ [-0.0765537734, 1.1762296998, -0.0996759264],
+ [0.0083161484, -0.0060324498, 0.9977163014],
+ ],
+ 2e-9,
+ );
+ closeMatrix(
+ AP1_TO_AP0,
+ [
+ [0.6954522414, 0.1406786965, 0.1638690622],
+ [0.0447945634, 0.8596711185, 0.0955343182],
+ [-0.0055258826, 0.004025210306, 1.001500672],
+ ],
+ 2e-9,
+ );
+ });
+
+ it("AP1 -> XYZ matches the published ACEScg matrix", () => {
+ closeMatrix(
+ AP1_TO_XYZ,
+ [
+ [0.6624541811, 0.1340042065, 0.1561876870],
+ [0.2722287168, 0.6740817658, 0.0536895174],
+ [-0.0055746495, 0.0040607335, 1.0103391003],
+ ],
+ 2e-9,
+ );
+ });
+
+ it("the Bradford D60 -> D65 adaptation is the CTL's D60_2_D65_CAT", () => {
+ closeMatrix(
+ D60_TO_D65,
+ [
+ [0.9872240, -0.0061132, 0.0159533],
+ [-0.0075983, 1.0018614, 0.0053300],
+ [0.0030726, -0.0050959, 1.0816806],
+ ],
+ 1e-6,
+ );
+ });
+
+ it("ACEScg -> linear Rec.709 equals the OCIO builtin (AP1_to_LINEAR-REC709_BFD)", () => {
+ // gamutToAp1("rec709") is Rec.709 -> ACEScg; its inverse is OCIO's matrix.
+ const m = gamutToAp1("rec709");
+ const det = (a: readonly (readonly number[])[]) =>
+ a[0][0] * (a[1][1] * a[2][2] - a[1][2] * a[2][1]) - a[0][1] * (a[1][0] * a[2][2] - a[1][2] * a[2][0]) + a[0][2] * (a[1][0] * a[2][1] - a[1][1] * a[2][0]);
+ expect(det(m)).toBeGreaterThan(0);
+ // Round trip through the OCIO matrix is the identity.
+ const ocio = reference.matrices.ap1ToRec709;
+ const product = [0, 1, 2].map((i) => [0, 1, 2].map((j) => ocio[i][0] * m[0][j] + ocio[i][1] * m[1][j] + ocio[i][2] * m[2][j]));
+ closeMatrix(product, [[1, 0, 0], [0, 1, 0], [0, 0, 1]], 2e-6);
+ // And the familiar published numbers.
+ close(ocio[0][0], 1.70505, 1e-5);
+ close(ocio[1][1], 1.14080, 1e-5);
+ });
+
+ it("gamut -> ACEScg matrices agree with colour-science (Bradford) for every standard and camera gamut", () => {
+ for (const [key, expected] of Object.entries(reference.matrices.toAcescg)) {
+ // Blackmagic Wide Gamut: colour-science rounds the primaries to 4 digits, ours are the published 7.
+ closeMatrix(gamutToAp1(key as never), expected as number[][], key === "bmdwg" ? 2e-3 : 5e-6);
+ }
+ });
+
+ it("white maps to equal ACES values (the adaptation preserves white)", () => {
+ for (const id of ["rec709", "p3", "bt2020", "sgamut3cine", "vgamut", "awg3", "awg4", "cinemagamut", "bmdwg"] as const) {
+ for (const m of [gamutToAp1(id), gamutToAp0(id)]) {
+ const w = [m[0][0] + m[0][1] + m[0][2], m[1][0] + m[1][1] + m[1][2], m[2][0] + m[2][1] + m[2][2]];
+ close(w[0], 1, 1e-5);
+ close(w[1], 1, 1e-5);
+ close(w[2], 1, 1e-5);
+ }
+ }
+ // AP0 and AP1 share the ACES white, so ACES2065-1 <-> ACEScg is not adapted.
+ expect(gamutDef("ap1").white).toEqual(gamutDef("ap0").white);
+ });
+});
+
+describe("ACEScct / ACEScc", () => {
+ it("matches the published anchors", () => {
+ close(acescctEncode(0.18), 0.4135884, 1e-6);
+ close(acesccEncode(0.18), 0.4135884, 1e-6);
+ close(acescctEncode(0), 0.0729055341958355, 1e-12);
+ // The toe is linear up to 0.0078125 and the curves meet there.
+ close(acescctEncode(0.0078125), 0.155251141552511, 1e-12);
+ close(acescctEncode(1), 0.5547945205, 1e-8);
+ // ACEScct 1.0 is scene linear ~ 222.9 (the top of the 17.52 stop range).
+ close(acescctDecode(1), Math.pow(2, 17.52 - 9.72), 1e-9);
+ });
+
+ it("decode inverts encode across the toe and the log segment, and is continuous at the join", () => {
+ for (const x of [-0.002, 0, 0.0001, 0.003, 0.0078125, 0.0079, 0.05, 0.18, 1, 16, 222]) {
+ close(acescctDecode(acescctEncode(x)), x, Math.max(1e-9, Math.abs(x) * 1e-9));
+ }
+ close(acescctEncode(0.0078125), acescctEncode(0.0078125 + 1e-12), 1e-9);
+ });
+});
+
+describe("splines", () => {
+ it("the RRT c5 spline is anchored at the published points", () => {
+ close(splineForward(0.18, RRT_SPLINE), 4.8, 1e-6);
+ close(splineForward(0.18 * 2 ** -15, RRT_SPLINE), 0.0001, 1e-9);
+ close(splineForward(0.18 * 2 ** 18, RRT_SPLINE), 10000, 1e-3);
+ });
+
+ it("the ODT c9 spline maps the RRT output stops to 0.02, 4.8 and 48 nits", () => {
+ close(splineForward(ODT_48_SPLINE.minX, ODT_48_SPLINE), 0.02, 1e-6);
+ close(splineForward(ODT_48_SPLINE.midX, ODT_48_SPLINE), 4.8, 1e-6);
+ close(splineForward(ODT_48_SPLINE.maxX, ODT_48_SPLINE), 48, 1e-4);
+ });
+
+ it("the HDR tone scale puts 18% grey at 15 nits and the top stop at 1000", () => {
+ close(splineForward(0.18, HDR_1000_SPLINE), 15, 5e-3);
+ close(splineForward(HDR_1000_SPLINE.maxX, HDR_1000_SPLINE), 1000, 1e-3);
+ });
+
+ it("inverse undoes forward inside each segment", () => {
+ for (const p of [RRT_SPLINE, ODT_48_SPLINE, HDR_1000_SPLINE, initTsParams(0.0001, 100)]) {
+ for (const x of [p.minX * 1.5, p.minX * 8, p.midX * 0.3, p.midX, p.midX * 2, p.maxX * 0.01, p.maxX * 0.4]) {
+ const y = splineForward(x, p);
+ close(splineInverse(y, p) / x, 1, 1e-6);
+ }
+ }
+ });
+});
+
+const SDR_IDS: AcesOutputId[] = ["srgb", "rec709"];
+
+describe("Output Transform: SDR (RRT + ODT) against the OCIO ACES 1.3 builtin", () => {
+ it("matches sRGB display codes on 68 scene-referred colours, neutrals and saturated reds included", () => {
+ reference.acescg.forEach((p, i) => {
+ const out = acesOutputTransform(p[0], p[1], p[2], "srgb");
+ for (let c = 0; c < 3; c++) close(out[c], reference.srgb[i][c], 2e-5);
+ });
+ });
+
+ it("matches BT.1886 (Rec.709) display codes", () => {
+ reference.acescg.forEach((p, i) => {
+ const out = acesOutputTransform(p[0], p[1], p[2], "rec709");
+ // The reference is float32 near black, where the 1/2.4 power amplifies the quantisation of the linear value.
+ for (let c = 0; c < 3; c++) close(out[c], reference.rec709[i][c], 5e-4);
+ });
+ });
+
+ it("is anchored at known renderings: 0 -> 0, 18% grey -> sRGB 0.356, ACES 1.0 -> 0.812", () => {
+ const grey = acesOutputTransform(0.18, 0.18, 0.18, "srgb");
+ close(grey[0], 0.35595, 1e-4);
+ const white = acesOutputTransform(1, 1, 1, "srgb");
+ close(white[0], 0.81197, 1e-4);
+ const black = acesOutputTransform(0, 0, 0, "srgb");
+ expect(Math.max(...black)).toBeLessThan(1e-3);
+ });
+
+ it("is monotonic along the neutral axis and bounded to 0..1", () => {
+ for (const id of SDR_IDS) {
+ let previous = -1;
+ for (let stop = -12; stop <= 8; stop += 0.25) {
+ const v = 0.18 * 2 ** stop;
+ const [r, g, b] = acesOutputTransform(v, v, v, id);
+ expect(r).toBeGreaterThanOrEqual(previous);
+ expect(r).toBeGreaterThanOrEqual(0);
+ expect(r).toBeLessThanOrEqual(1);
+ close(r, g, 1e-4);
+ close(r, b, 1e-4);
+ previous = r;
+ }
+ }
+ });
+
+ it("clamps out-of-gamut and negative scene values instead of producing NaN or values outside 0..1", () => {
+ for (const p of [[-0.1, 0.2, 0.3], [5, -2, -1], [1e6, 0, 0], [0, 0, 1e-12], [65504, 65504, 65504]]) {
+ for (const id of SDR_IDS) {
+ const out = acesOutputTransform(p[0], p[1], p[2], id);
+ for (const v of out) {
+ expect(Number.isFinite(v)).toBe(true);
+ expect(v).toBeGreaterThanOrEqual(0);
+ expect(v).toBeLessThanOrEqual(1);
+ }
+ }
+ }
+ });
+});
+
+describe("Output Transform: Rec.2020 PQ 1000 nit and HLG", () => {
+ it("matches the OCIO HDR-VIDEO-1000nit-15nit-REC2020lim builtin in display nits (relative 1e-3)", () => {
+ reference.acescg.forEach((p, i) => {
+ const m = AP1_TO_AP0;
+ const nits = [0, 0, 0];
+ acesToHdr1000Nits(
+ m[0][0] * p[0] + m[0][1] * p[1] + m[0][2] * p[2],
+ m[1][0] * p[0] + m[1][1] * p[1] + m[1][2] * p[2],
+ m[2][0] * p[0] + m[2][1] * p[1] + m[2][2] * p[2],
+ nits,
+ );
+ for (let c = 0; c < 3; c++) {
+ const ref = reference.hdrNits[i][c];
+ close(nits[c], ref, Math.max(0.01, ref * 1e-3));
+ }
+ });
+ });
+
+ it("18% grey lands at 15 nits and the PQ signal is the ST 2084 inverse EOTF of the luminance", () => {
+ const pq = acesOutputTransform(0.18, 0.18, 0.18, "rec2020-pq");
+ close(pq[0], nitsToPq(15), 1e-4);
+ // ST 2084 anchors: 1000 nits = 0.7518, 203 nits = 0.5807, 10000 = 1.
+ close(nitsToPq(1000), 0.751827, 1e-5);
+ close(nitsToPq(203), 0.580691, 1e-5);
+ close(nitsToPq(10000), 1, 1e-9);
+ expect(nitsToPq(0)).toBeLessThan(1e-6);
+ });
+
+ it("HLG signal of the same display light: 203 nits -> 0.75 and 1000 nits -> 1.0 (BT.2100, 1000 nit display)", () => {
+ const out = [0, 0, 0];
+ displayNitsToHlg(203, 203, 203, out);
+ close(out[0], 0.75, 5e-3);
+ displayNitsToHlg(1000, 1000, 1000, out);
+ close(out[0], 1, 1e-6);
+ displayNitsToHlg(0, 0, 0, out);
+ expect(out).toEqual([0, 0, 0]);
+ });
+
+ it("HLG output of the transform is the HLG encoding of the PQ output's luminance", () => {
+ const rgb = [0.4, 0.2, 0.1] as const;
+ const nits = [0, 0, 0];
+ const m = AP1_TO_AP0;
+ acesToHdr1000Nits(
+ m[0][0] * rgb[0] + m[0][1] * rgb[1] + m[0][2] * rgb[2],
+ m[1][0] * rgb[0] + m[1][1] * rgb[1] + m[1][2] * rgb[2],
+ m[2][0] * rgb[0] + m[2][1] * rgb[1] + m[2][2] * rgb[2],
+ nits,
+ );
+ const expected = [0, 0, 0];
+ displayNitsToHlg(nits[0], nits[1], nits[2], expected);
+ const got = acesOutputTransform(rgb[0], rgb[1], rgb[2], "rec2020-hlg");
+ for (let c = 0; c < 3; c++) close(got[c], expected[c], 1e-9);
+ });
+
+ it("the peak of the 1000 nit transform stays at or below 1000 nits and bright scene values compress, not clip", () => {
+ const hi = [0, 0, 0];
+ acesToHdr1000Nits(...(AP1_TO_AP0.map((row) => row[0] * 100 + row[1] * 100 + row[2] * 100) as [number, number, number]), hi);
+ expect(hi[0]).toBeLessThanOrEqual(1000.0001);
+ const mid = [0, 0, 0];
+ acesToHdr1000Nits(...(AP1_TO_AP0.map((row) => row[0] * 4 + row[1] * 4 + row[2] * 4) as [number, number, number]), mid);
+ expect(hi[0]).toBeGreaterThan(mid[0]);
+ });
+});
+
+describe("export output selection", () => {
+ it("HDR exports pick the Rec.2020 transforms, SDR exports the project's SDR transform", () => {
+ expect(acesOutputForExport({ colorManagement: "aces" }, "pq")).toBe("rec2020-pq");
+ expect(acesOutputForExport({ colorManagement: "aces" }, "hlg")).toBe("rec2020-hlg");
+ expect(acesOutputForExport({ colorManagement: "aces" }, undefined)).toBe("srgb");
+ expect(acesOutputForExport({ colorManagement: "aces", acesOutput: "rec709" }, undefined)).toBe("rec709");
+ });
+});
diff --git a/packages/core/src/color/aces.ts b/packages/core/src/color/aces.ts
new file mode 100644
index 00000000..7dd6c300
--- /dev/null
+++ b/packages/core/src/color/aces.ts
@@ -0,0 +1,143 @@
+/**
+ * ACES colour management: analytic transforms, no LUT files and no OCIO runtime.
+ *
+ * IDT footage code values -> scene-linear in the source primaries (the existing camera-log / sRGB / Rec.709 /
+ * Rec.2020 / PQ / HLG decoders), source primaries -> AP1 with a Bradford adaptation to the ACES white
+ * (ACEScg, the working primaries of the pipeline). ACES2065-1 is AP0 = `AP1_TO_AP0 x ACEScg`.
+ * grade ACEScct (log, `acescctEncode`): the grading sliders run on this encoding in ACES mode.
+ * OT Output Transform = RRT + ODT, ported from the ACES 1.3 CTL reference (github.com/ampas/aces-dev, tag v1.3):
+ * sRGB / Rec.709 (BT.1886) `RRT.ctl` + `ODT.Academy.sRGB_100nits_dim.ctl` / `ODT.Academy.Rec709_100nits_dim.ctl`
+ * (segmented splines c5 and c9, dim surround, ODT saturation, D60 -> D65)
+ * Rec.2020 PQ, 1000 nit `RRTODT.Academy.Rec2020_1000nits_15nits_ST2084.ctl` (single stage SSTS,
+ * `outputTransform` of ACESlib.OutputTransforms.ctl)
+ * Rec.2020 HLG `RRTODT.Academy.Rec2020_1000nits_15nits_HLG.ctl` (the PQ result re-encoded to HLG
+ * for a 1000 nit display, BT.2100 / BT.2390 section 7)
+ *
+ * Units. Scene-linear 1.0 is the pipeline's "SDR reference white" (the unit of every other colour module here):
+ * 18% grey is 0.18, a 90% card 0.9. ACES2065-1 / ACEScg code values are the same numbers, so sRGB white 1.0 enters
+ * the RRT as ACES 1.0. SDR outputs return display-encoded 0..1; the PQ / HLG outputs return the 0..1 signal of a
+ * 1000 nit mastering display.
+ *
+ * Matrices are computed from the published chromaticities (the CTL does the same) and pinned against the published
+ * constants in `aces.test.ts`. Every function here is plain arithmetic on numbers so that the GLSL port
+ * (`aces-glsl.ts`) and this reference can be held against each other pixel for pixel.
+ *
+ * Row-major matrices, column vectors: out = M x in.
+ */
+
+import { chromaticAdaptation, gamutDef, gamutToXyz, invert3x3, multiply3x3, type CameraGamutId, type GamutDef } from "./camera-log";
+
+export type AcesMatrix3 = readonly [readonly number[], readonly number[], readonly number[]];
+type Matrix3 = AcesMatrix3;
+
+// -- primaries and matrices -----------------------------------------------------------------------------------
+
+/** AP0 (ACES2065-1) and AP1 (ACEScg) chromaticities. */
+export const AP0_PRIMARIES: GamutDef = /* @__PURE__ */ gamutDef("ap0");
+export const AP1_PRIMARIES: GamutDef = /* @__PURE__ */ gamutDef("ap1");
+
+export const AP0_TO_XYZ: Matrix3 = /* @__PURE__ */ gamutToXyz(AP0_PRIMARIES);
+export const XYZ_TO_AP0: Matrix3 = /* @__PURE__ */ invert3x3(AP0_TO_XYZ);
+export const AP1_TO_XYZ: Matrix3 = /* @__PURE__ */ gamutToXyz(AP1_PRIMARIES);
+export const XYZ_TO_AP1: Matrix3 = /* @__PURE__ */ invert3x3(AP1_TO_XYZ);
+export const AP0_TO_AP1: Matrix3 = /* @__PURE__ */ multiply3x3(XYZ_TO_AP1, AP0_TO_XYZ);
+export const AP1_TO_AP0: Matrix3 = /* @__PURE__ */ multiply3x3(XYZ_TO_AP0, AP1_TO_XYZ);
+
+const REC709_PRIMARIES = /* @__PURE__ */ gamutDef("rec709");
+
+/** Bradford adaptation from the ACES white (D60-ish) to D65, applied to XYZ. */
+export const D60_TO_D65: Matrix3 = /* @__PURE__ */ chromaticAdaptation(AP0_PRIMARIES.white, REC709_PRIMARIES.white);
+
+/** Luminance weights of AP1 (the Y row of AP1 -> XYZ). */
+export const AP1_RGB2Y: readonly [number, number, number] = [AP1_TO_XYZ[1][0], AP1_TO_XYZ[1][1], AP1_TO_XYZ[1][2]];
+
+/** Linear light in a camera / standard gamut (D65 or its own white) to ACEScg (AP1), Bradford adapted to the ACES white. */
+export function gamutToAp1(id: CameraGamutId | "rec709" | "p3"): Matrix3 {
+ const g = gamutDef(id);
+ return multiply3x3(XYZ_TO_AP1, multiply3x3(chromaticAdaptation(g.white, AP1_PRIMARIES.white), gamutToXyz(g)));
+}
+
+/** The same into ACES2065-1 (AP0). */
+export function gamutToAp0(id: CameraGamutId | "rec709" | "p3"): Matrix3 {
+ const g = gamutDef(id);
+ return multiply3x3(XYZ_TO_AP0, multiply3x3(chromaticAdaptation(g.white, AP0_PRIMARIES.white), gamutToXyz(g)));
+}
+
+export function applyAcesMatrix(m: Matrix3, r: number, g: number, b: number): [number, number, number] {
+ return [
+ m[0][0] * r + m[0][1] * g + m[0][2] * b,
+ m[1][0] * r + m[1][1] * g + m[1][2] * b,
+ m[2][0] * r + m[2][1] * g + m[2][2] * b,
+ ];
+}
+
+// -- ACEScct / ACEScc (S-2016-001, S-2014-003) -----------------------------------------------------------------
+
+const CCT_CUT_LIN = 0.0078125;
+const CCT_CUT_LOG = 0.155251141552511;
+const CCT_A = 10.5402377416545;
+const CCT_B = 0.0729055341958355;
+
+/** ACEScg (linear AP1) to ACEScct. */
+export function acescctEncode(lin: number): number {
+ return lin <= CCT_CUT_LIN ? CCT_A * lin + CCT_B : (Math.log2(lin) + 9.72) / 17.52;
+}
+
+/** ACEScct to ACEScg (linear AP1). */
+export function acescctDecode(cct: number): number {
+ return cct <= CCT_CUT_LOG ? (cct - CCT_B) / CCT_A : Math.pow(2, cct * 17.52 - 9.72);
+}
+
+/** ACEScct of scene-linear 1.0 (SDR white): where a positive vignette lifts towards in the grade. */
+export const ACESCCT_WHITE = /* @__PURE__ */ acescctEncode(1);
+
+/** ACEScc (S-2014-003), for completeness and the published-value tests. */
+export function acesccEncode(lin: number): number {
+ if (lin <= 0) return (Math.log2(Math.pow(2, -16)) + 9.72) / 17.52;
+ if (lin < Math.pow(2, -15)) return (Math.log2(Math.pow(2, -16) + lin * 0.5) + 9.72) / 17.52;
+ return (Math.log2(lin) + 9.72) / 17.52;
+}
+
+// -- output transform ids ----------------------------------------------------------------------------------------
+
+export type AcesSdrOutput = "srgb" | "rec709";
+export type AcesOutputId = AcesSdrOutput | "rec2020-pq" | "rec2020-hlg";
+
+export const ACES_OUTPUT_IDS: readonly AcesOutputId[] = ["srgb", "rec709", "rec2020-pq", "rec2020-hlg"];
+
+export function isAcesSdrOutput(value: unknown): value is AcesSdrOutput {
+ return value === "srgb" || value === "rec709";
+}
+
+/** Colour primaries the signal of each output transform is in. */
+export function acesOutputPrimaries(output: AcesOutputId): "bt709" | "bt2020" {
+ return output === "srgb" || output === "rec709" ? "bt709" : "bt2020";
+}
+
+// -- project settings ----------------------------------------------------------------------------------------------
+
+export type ColorManagementMode = "display-referred" | "aces";
+
+export interface AcesSettings {
+ readonly colorManagement?: ColorManagementMode;
+ readonly acesOutput?: AcesSdrOutput;
+}
+
+export function isAcesMode(settings: AcesSettings | undefined): boolean {
+ return settings?.colorManagement === "aces";
+}
+
+/** The SDR output transform of the monitor and of SDR exports (sRGB unless the project says Rec.709). */
+export function acesSdrOutputOf(settings: AcesSettings | undefined): AcesSdrOutput {
+ return settings?.acesOutput === "rec709" ? "rec709" : "srgb";
+}
+
+/**
+ * What an export renders to. An HDR10 export always uses the Rec.2020 PQ 1000 nit transform, HLG the HLG one; every
+ * SDR export uses the project's SDR output transform.
+ */
+export function acesOutputForExport(settings: AcesSettings | undefined, hdr: "pq" | "hlg" | undefined): AcesOutputId {
+ if (hdr === "pq") return "rec2020-pq";
+ if (hdr === "hlg") return "rec2020-hlg";
+ return acesSdrOutputOf(settings);
+}
diff --git a/packages/core/src/color/camera-log.ts b/packages/core/src/color/camera-log.ts
index ed11838c..ddbc78e9 100644
--- a/packages/core/src/color/camera-log.ts
+++ b/packages/core/src/color/camera-log.ts
@@ -41,7 +41,7 @@ export type CameraLogId =
| "flog2"
| "bmdfilm5";
-export type CameraGamutId = "sgamut3cine" | "vgamut" | "awg3" | "awg4" | "cinemagamut" | "bt2020" | "bmdwg";
+export type CameraGamutId = "sgamut3cine" | "vgamut" | "awg3" | "awg4" | "cinemagamut" | "bt2020" | "bmdwg" | "ap0" | "ap1";
type Matrix3 = readonly [readonly number[], readonly number[], readonly number[]];
@@ -194,7 +194,7 @@ export function cameraLogGlslExpression(id: CameraLogId): string {
// -- gamuts ----------------------------------------------------------------------------------------------------
type XY = readonly [number, number];
-interface GamutDef {
+export interface GamutDef {
readonly r: XY;
readonly g: XY;
readonly b: XY;
@@ -203,8 +203,15 @@ interface GamutDef {
const D65: XY = [0.3127, 0.329];
-const GAMUTS: Record<CameraGamutId | "rec709", GamutDef> = {
+/** ACES white point (ST 2065-1), the white of AP0 and AP1. */
+const ACES_WHITE: XY = [0.32168, 0.33767];
+
+const GAMUTS: Record<CameraGamutId | "rec709" | "p3", GamutDef> = {
rec709: { r: [0.64, 0.33], g: [0.3, 0.6], b: [0.15, 0.06], white: D65 },
+ p3: { r: [0.68, 0.32], g: [0.265, 0.69], b: [0.15, 0.06], white: D65 },
+ // ACES primaries (SMPTE ST 2065-1 AP0, S-2014-004 AP1). Used as footage spaces: ACES2065-1, ACEScg, ACEScct.
+ ap0: { r: [0.7347, 0.2653], g: [0, 1], b: [0.0001, -0.077], white: ACES_WHITE },
+ ap1: { r: [0.713, 0.293], g: [0.165, 0.83], b: [0.128, 0.044], white: ACES_WHITE },
bt2020: { r: [0.708, 0.292], g: [0.17, 0.797], b: [0.131, 0.046], white: D65 },
sgamut3cine: { r: [0.766, 0.275], g: [0.225, 0.8], b: [0.089, -0.087], white: D65 },
vgamut: { r: [0.73, 0.28], g: [0.165, 0.84], b: [0.1, -0.03], white: D65 },
@@ -214,6 +221,13 @@ const GAMUTS: Record<CameraGamutId | "rec709", GamutDef> = {
bmdwg: { r: [0.7177215, 0.3171181], g: [0.228041, 0.861569], b: [0.1005841, -0.0825512], white: [0.312717, 0.3290312] },
};
+/** Chromaticities of a camera / ACES gamut (or "rec709" / "p3"), for the ACES input transforms. */
+export function gamutDef(id: CameraGamutId | "rec709" | "p3"): GamutDef {
+ return GAMUTS[id];
+}
+
+export { mul3 as multiply3x3, inv3 as invert3x3, rgbToXyz as gamutToXyz, adaptation as chromaticAdaptation };
+
function mul3(a: Matrix3, b: Matrix3): Matrix3 {
const out = [0, 1, 2].map((i) => [0, 1, 2].map((j) => a[i][0] * b[0][j] + a[i][1] * b[1][j] + a[i][2] * b[2][j]));
return out as unknown as Matrix3;
@@ -270,7 +284,7 @@ function adaptation(from: XY, to: XY): Matrix3 {
}
/** Linear light in `from` primaries to linear light in `to` primaries, both viewed under D65. */
-export function gamutConversion(from: CameraGamutId | "rec709", to: CameraGamutId | "rec709"): Matrix3 {
+export function gamutConversion(from: CameraGamutId | "rec709" | "p3", to: CameraGamutId | "rec709" | "p3"): Matrix3 {
const f = GAMUTS[from];
const t = GAMUTS[to];
return mul3(inv3(rgbToXyz({ ...t, white: D65 })), mul3(adaptation(f.white, D65), rgbToXyz(f)));
diff --git a/packages/core/src/color/fixtures/aces-ocio-reference.ts b/packages/core/src/color/fixtures/aces-ocio-reference.ts
new file mode 100644
index 00000000..ed99c79c
--- /dev/null
+++ b/packages/core/src/color/fixtures/aces-ocio-reference.ts
@@ -0,0 +1,2 @@
+// Generated by scripts/aces-reference.py (OpenColorIO builtin ACES 1.3 transforms). Do not edit.
+export const ACES_REFERENCE = {"note":"Generated by scripts/aces-reference.py with OpenColorIO builtin ACES 1.3 transforms. srgb / rec709: display code values 0..1. hdrNits: Rec.2020 linear display luminance in nits (SDR-VIDEO_1.0 and HDR-VIDEO-1000nit-15nit-REC2020lim_1.1).","acescg":[[0.0,0.0,0.0],[0.0001,0.0001,0.0001],[0.001,0.001,0.001],[0.01,0.01,0.01],[0.05,0.05,0.05],[0.18,0.18,0.18],[0.5,0.5,0.5],[1.0,1.0,1.0],[2.0,2.0,2.0],[4.0,4.0,4.0],[8.0,8.0,8.0],[16.0,16.0,16.0],[100.0,100.0,100.0],[1.0,0.0,0.0],[0.0,1.0,0.0],[0.0,0.0,1.0],[1.0,1.0,0.0],[0.0,1.0,1.0],[1.0,0.0,1.0],[0.5,0.1,0.05],[0.05,0.3,0.1],[0.1,0.1,0.6],[0.9,0.5,0.2],[0.18,0.02,0.05],[0.02,0.18,0.5],[4.0,0.5,0.2],[0.3,2.0,0.3],[0.12,0.08,0.06],[0.3165059,3.8802098,1.2669012],[0.0079585,0.0158732,3.1204252],[0.0010497,1.9271418,1.5426866],[0.0744286,0.0162978,0.0129928],[0.0104587,0.0602983,0.1042781],[0.1636777,9.5940314,1.4813159],[0.3081179,9.0331785,0.007265],[0.0043737,0.2819411,0.0014989],[0.0013891,0.1146979,0.0732528],[4.663061,0.3287797,0.1138861],[0.0971614,0.0097737,0.0011147],[0.0058831,0.5863116,0.0063449],[0.0300708,0.001035,2.0902148],[0.0041481,0.0117597,3.3214569],[0.1094368,2.4468142,0.3621335],[0.9270087,0.0023226,0.1460748],[0.1074209,3.0574369,0.0278648],[0.2470224,0.0017259,0.0355244],[0.019595,0.0039884,1.8422663],[0.0329446,8.2222663,0.2290692],[0.2631631,0.3564399,0.5079266],[0.0040101,0.0577104,0.0090836],[0.0407374,0.0024368,7.4355347],[0.0072446,0.4864751,0.0159104],[3.1355094,0.4455115,0.003361],[2.4004755,6.0227202,4.1273106],[0.1900538,0.003818,0.0058865],[5.1478127,0.161922,0.0052748],[3.4373802,0.3683722,0.1900103],[0.0320001,0.0440373,0.0090773],[0.0014198,3.1979762,0.0742884],[0.1550746,0.0194381,1.0122777],[0.0012612,0.0308135,0.0013225],[0.0031015,7.3891238,0.4276051],[0.0516275,0.1244401,3.0991089],[0.0238146,0.2297016,0.5429221],[0.0264031,0.1192323,1.1507727],[4.3322874,0.0040202,5.4159865],[0.0010489,1.0278033,1.7462536],[0.0035242,0.0473821,1.8240012]],"srgb":[[0.0,0.0,0.0],[0.0,0.0,0.0],[0.0,0.0,0.0],[0.0128341,0.0128341,0.0128341],[0.1245197,0.1245196,0.1245197],[0.3559524,0.3559526,0.3559525],[0.6472044,0.6472042,0.6472043],[0.8119733,0.8119731,0.8119731],[0.9037293,0.9037294,0.9037294],[0.9552806,0.9552807,0.9552807],[0.9844337,0.9844338,0.9844338],[0.9997402,0.9997402,0.9997402],[1.0,1.0,1.0],[0.9593964,0.0,0.0],[0.0,0.8499458,0.0],[0.0,0.0,0.8524133],[0.8375741,0.8140955,0.0],[0.0,0.8477228,0.8133526],[0.9833054,0.0,0.8404991],[0.7296666,0.143513,0.1174468],[0.0,0.5176552,0.1982867],[0.1159774,0.2216597,0.7230536],[0.8630802,0.6349298,0.3704876],[0.4048242,0.0,0.1278787],[0.0,0.3684668,0.6627906],[1.0,0.646028,0.3991973],[0.0,0.9337651,0.4924899],[0.2900566,0.1840361,0.146475],[0.0,0.9830257,0.8493737],[0.0,0.0,0.9914932],[0.0,0.9402027,0.8769752],[0.2190243,0.0038092,0.0212512],[0.0,0.1568815,0.2414803],[0.0,1.0,0.8784416],[0.3749587,1.0,0.3585372],[0.0,0.5003973,0.0],[0.0,0.2673912,0.1715032],[1.0,0.5280571,0.2794106],[0.2654517,0.0,0.0],[0.0,0.7238661,0.0],[0.0,0.0,0.9566565],[0.0,0.0,0.9961174],[0.0,0.9607486,0.5547123],[0.9418453,0.0,0.314121],[0.0,0.9790308,0.0],[0.4959095,0.0,0.0892805],[0.0,0.0,0.9433761],[0.0,1.0,0.5660447],[0.3857403,0.5541835,0.6575526],[0.0,0.1568978,0.0],[0.0,0.0,1.0],[0.0,0.6674279,0.0],[1.0,0.6025466,0.0],[0.8912333,0.9798139,0.9562123],[0.4150303,0.0,0.0036552],[1.0,0.3291489,0.1119021],[1.0,0.5467059,0.3857335],[0.064283,0.1181241,0.0029654],[0.0,0.9857539,0.1688316],[0.316802,0.0,0.8509921],[0.0,0.0836667,0.0],[0.0,1.0,0.6749481],[0.0,0.2767777,0.9839831],[0.0,0.4372771,0.6852343],[0.0,0.2653915,0.8709149],[1.0,0.0,1.0],[0.0,0.852401,0.8976457],[0.0,0.1049074,0.9405354]],"rec709":[[0.0002137,0.0002137,0.0002137],[0.0002137,0.0002137,0.0002137],[0.0002137,0.0002137,0.0002137],[0.0560781,0.0560781,0.0560781],[0.1701608,0.1701608,0.1701608],[0.3895284,0.3895286,0.3895284],[0.6655966,0.6655964,0.6655965],[0.8217756,0.8217754,0.8217755],[0.9087481,0.9087483,0.9087483],[0.957612,0.957612,0.957612],[0.9852452,0.9852453,0.9852453],[0.9997538,0.9997537,0.9997538],[1.0,1.0,1.0],[0.9615132,0.0,0.0],[0.0,0.8577685,0.0],[0.0,0.0,0.8601074],[0.8460418,0.8237872,0.0],[0.0,0.8556614,0.823083],[0.9841757,0.0,0.8488143],[0.7437598,0.188164,0.1634567],[0.0,0.5428011,0.2400822],[0.1620639,0.2622367,0.7374916],[0.8702182,0.6539619,0.4033058],[0.4358523,0.0,0.1733448],[0.0,0.4013903,0.6803703],[1.0,0.6644815,0.4305187],[0.0,0.9372181,0.5189478],[0.3270679,0.2265745,0.1909715],[0.0,0.9839106,0.8572262],[0.0,0.0,0.9919367],[0.0,0.9433201,0.8833888],[0.2597387,0.0338056,0.0691912],[0.0,0.2008356,0.281024],[0.0,1.0,0.8847787],[0.4075437,1.0,0.3919784],[0.0,0.5264429,0.0],[0.0,0.3055841,0.214695],[1.0,0.5526608,0.3169769],[0.3037457,0.0,0.0],[0.0,0.7382617,0.0],[0.0,0.0,0.9589161],[0.0,0.0,0.9963198],[0.0,0.9627949,0.5779264],[0.9448771,0.0,0.3498777],[0.0,0.980124,0.0],[0.5221891,0.0,0.1367588],[0.0,0.0,0.946328],[0.0,1.0,0.588668],[0.4177633,0.5774252,0.6754053],[0.0,0.200851,0.0],[0.0,0.0,1.0],[0.0,0.6847657,0.0],[1.0,0.6232669,0.0],[0.8969036,0.9808662,0.9584951],[0.4455264,0.0,0.0332294],[1.0,0.3641222,0.158201],[1.0,0.5703374,0.4177569],[0.1130644,0.1640987,0.0304562],[0.0,0.9864966,0.2121626],[0.352419,0.0,0.8587603],[0.0,0.1314376,0.0],[0.0,1.0,0.6918939],[0.0,0.3144813,0.9848181],[0.0,0.4666134,0.7016439],[0.0,0.3036887,0.8776444],[1.0,0.0,1.0],[0.0,0.8600958,0.9029817],[0.0,0.151571,0.9436355]],"hdrNits":[[0.0,0.0,0.0],[0.0002,0.0002,0.0002],[0.0032,0.0032,0.0032],[0.15854,0.15854,0.15854],[2.20274,2.20274,2.20274],[14.99978,14.99979,14.99978],[52.86679,52.86678,52.86678],[107.4377,107.43769,107.4377],[194.2185,194.2184,194.21837],[316.16934,316.16929,316.16936],[465.76154,465.76144,465.76148],[620.69433,620.69384,620.69386],[891.0456,891.04569,891.04571],[89.28609,0.2054,0.05392],[0.0,106.60087,0.0],[0.11087,0.0,106.7364],[107.79416,107.45341,0.0],[0.0,106.57221,106.86616],[106.80033,0.0,107.34806],[44.79127,7.08933,2.25603],[2.15149,28.80732,6.41818],[6.25493,6.44538,63.95882],[93.56668,53.46281,17.80407],[12.79197,0.59004,2.23579],[0.16543,14.82652,52.41296],[283.70048,59.86971,19.68696],[31.39179,193.26884,30.56444],[8.17874,4.70093,2.99372],[36.91054,308.847,134.93672],[0.27769,0.0,269.50572],[0.0,187.4893,157.16168],[3.91142,0.41525,0.26953],[0.1269,2.983,6.93628],[33.54492,506.02667,161.77008],[49.36861,492.52938,11.60969],[0.0,26.60721,0.0],[0.0,7.96068,4.03819],[311.54343,41.46528,10.26465],[5.53448,0.18943,0.0032],[0.0,62.28456,0.0],[0.20877,0.0,200.98253],[0.29151,0.0,281.26079],[9.83665,224.97558,38.45531],[84.51555,0.23662,11.42925],[10.86987,263.70567,1.00994],[18.58526,0.02029,1.27702],[0.18903,0.0,181.97262],[14.55899,471.01267,35.50119],[24.67024,35.72979,53.58116],[0.00336,2.93923,0.11329],[0.47145,0.0,453.86563],[0.0,50.77488,0.0],[241.07426,51.64449,0.10582],[225.85188,401.21796,322.5512],[13.17281,0.05721,0.03376],[330.29368,22.57344,1.95631],[255.07662,43.52963,18.05522],[1.17513,1.93699,0.13066],[0.0,271.89631,6.01562],[11.71012,0.36322,108.13148],[0.0,1.08219,0.0],[8.80444,446.71869,56.30709],[1.32791,8.94521,268.20404],[0.28763,20.51274,57.41037],[0.21606,8.27915,121.76714],[333.05668,1.55933,382.38739],[0.0,109.35735,173.82874],[0.1686,1.85027,180.55708]],"matrices":{"ap1ToRec709":[[1.7050509452819824,-0.6217921376228333,-0.08325887471437454],[-0.13025641441345215,1.1408047676086426,-0.010548318736255169],[-0.02400335669517517,-0.1289689689874649,1.1529723405838013]],"ap1ToXyzD65":[[0.6522375345230103,0.12823612987995148,0.16998225450515747],[0.26767218112945557,0.674340009689331,0.05798783153295517],[-0.005381815601140261,0.0013690602499991655,1.0930705070495605]],"toAcescg":{"rec709":[[0.6130974024011874,0.3395231461841058,0.04737945141470674],[0.07019372246958172,0.9163538790573439,0.013452398473074095],[0.02061559288222692,0.10956977293813543,0.8698146341796376]],"p3":[[0.7357979140288916,0.21216648529317433,0.05203560067793393],[0.04717988497673046,0.9380457009217155,0.014774414101553907],[0.0035636646390989086,0.04114188562513294,0.9552944497357679]],"bt2020":[[0.9748949779244184,0.019599108637005182,0.005505913438576293],[0.0021795627977040004,0.9955354688932208,0.0022849683090751314],[0.004797239683772721,0.02453201663458948,0.9706707436816374]],"sgamut3cine":[[0.9347617186507087,0.14098364915277695,-0.0757453677013925],[-0.049979673170057984,1.2587857409490506,-0.20880606797103113],[-0.024670603412223494,-0.026185864478527863,1.0508564679281998]],"vgamut":[[1.0486621669083545,0.009552555838877154,-0.05821632238944859],[-0.029390700595328386,1.1458051122897244,-0.11641379559733266],[-0.0033173118814018255,-0.005607384021038587,1.0089249152731639]],"awg3":[[0.966739179719982,0.1129702380795168,-0.0797093568563894],[0.048586616828157486,1.1822104772028041,-0.23079713785996092],[0.007258721289937909,-0.06225081723588423,1.054992324319239]],"awg4":[[1.0902270411804198,-0.030918417887124905,-0.059308623293294796],[-0.0557798623905716,1.171289918195157,-0.11551005580458576],[0.005437679486258181,-0.0016192584457668969,0.9961815789595084]],"cinemagamut":[[1.1090239178145433,-0.0017313066822230163,-0.10729261113232029],[-0.05249667274807337,1.3090527018090123,-0.25655602906093933],[-0.003326329858909311,-0.21799428700024065,1.22132061685915]],"bmdwg":[[0.9298042268596871,0.12437270017911536,-0.05417692703880258],[0.03025719986509546,1.1923839691038358,-0.22264116896893088],[-0.022400467048442407,-0.08014696003428914,1.1025474270827313]]}}};
diff --git a/packages/core/src/color/fixtures/cg-config-v2.1.0_aces-v1.3_ocio-v2.3.ocio b/packages/core/src/color/fixtures/cg-config-v2.1.0_aces-v1.3_ocio-v2.3.ocio
new file mode 100644
index 00000000..6a474294
--- /dev/null
+++ b/packages/core/src/color/fixtures/cg-config-v2.1.0_aces-v1.3_ocio-v2.3.ocio
@@ -0,0 +1,593 @@
+ocio_profile_version: 2.3
+
+environment:
+ {}
+search_path: ""
+strictparsing: true
+luma: [0.2126, 0.7152, 0.0722]
+name: cg-config-v2.1.0_aces-v1.3_ocio-v2.3
+description: |
+ Academy Color Encoding System - CG Config [COLORSPACES v2.1.0] [ACES v1.3] [OCIO v2.3]
+ --------------------------------------------------------------------------------------
+
+ This minimalistic "OpenColorIO" config is geared toward computer graphics artists requiring a lean config that does not include camera colorspaces and the less common displays and looks.
+
+roles:
+ aces_interchange: ACES2065-1
+ cie_xyz_d65_interchange: CIE-XYZ-D65
+ color_picking: sRGB - Texture
+ color_timing: ACEScct
+ compositing_log: ACEScct
+ data: Raw
+ matte_paint: ACEScct
+ scene_linear: ACEScg
+ texture_paint: sRGB - Texture
+
+file_rules:
+ - !<Rule> {name: Default, colorspace: ACES2065-1}
+
+shared_views:
+ - !<View> {name: ACES 1.0 - SDR Video, view_transform: ACES 1.0 - SDR Video, display_colorspace: <USE_DISPLAY_NAME>}
+ - !<View> {name: "ACES 1.1 - HDR Video (1000 nits & Rec.2020 lim)", view_transform: "ACES 1.1 - HDR Video (1000 nits & Rec.2020 lim)", display_colorspace: <USE_DISPLAY_NAME>}
+ - !<View> {name: "ACES 1.1 - HDR Video (1000 nits & P3 lim)", view_transform: "ACES 1.1 - HDR Video (1000 nits & P3 lim)", display_colorspace: <USE_DISPLAY_NAME>}
+ - !<View> {name: ACES 1.0 - SDR Cinema, view_transform: ACES 1.0 - SDR Cinema, display_colorspace: <USE_DISPLAY_NAME>}
+ - !<View> {name: Un-tone-mapped, view_transform: Un-tone-mapped, display_colorspace: <USE_DISPLAY_NAME>}
+
+displays:
+ sRGB - Display:
+ - !<View> {name: Raw, colorspace: Raw}
+ - !<Views> [ACES 1.0 - SDR Video, Un-tone-mapped]
+ Display P3 - Display:
+ - !<View> {name: Raw, colorspace: Raw}
+ - !<Views> [ACES 1.0 - SDR Video, Un-tone-mapped]
+ Rec.1886 Rec.709 - Display:
+ - !<View> {name: Raw, colorspace: Raw}
+ - !<Views> [ACES 1.0 - SDR Video, Un-tone-mapped]
+ Rec.2100-PQ - Display:
+ - !<View> {name: Raw, colorspace: Raw}
+ - !<Views> ["ACES 1.1 - HDR Video (1000 nits & Rec.2020 lim)", Un-tone-mapped]
+ ST2084-P3-D65 - Display:
+ - !<View> {name: Raw, colorspace: Raw}
+ - !<Views> ["ACES 1.1 - HDR Video (1000 nits & P3 lim)", Un-tone-mapped]
+ P3-D65 - Display:
+ - !<View> {name: Raw, colorspace: Raw}
+ - !<Views> [ACES 1.0 - SDR Cinema, Un-tone-mapped]
+
+active_displays: [sRGB - Display, Display P3 - Display, Rec.1886 Rec.709 - Display, Rec.2100-PQ - Display, ST2084-P3-D65 - Display, P3-D65 - Display]
+active_views: [ACES 1.0 - SDR Video, "ACES 1.1 - HDR Video (1000 nits & Rec.2020 lim)", "ACES 1.1 - HDR Video (1000 nits & P3 lim)", ACES 1.0 - SDR Cinema, Un-tone-mapped, Raw]
+inactive_colorspaces: [CIE-XYZ-D65, sRGB - Display, Display P3 - Display, Rec.1886 Rec.709 - Display, Rec.2100-PQ - Display, ST2084-P3-D65 - Display, P3-D65 - Display]
+
+looks:
+ - !<Look>
+ name: ACES 1.3 Reference Gamut Compression
+ process_space: ACES2065-1
+ description: |
+ LMT (applied in ACES2065-1) to compress scene-referred values from common cameras into the AP1 gamut
+
+ ACEStransformID: urn:ampas:aces:transformId:v1.5:LMT.Academy.ReferenceGamutCompress.a1.v1.0
+
+ AMF Components
+ --------------
+ ACEStransformID: urn:ampas:aces:transformId:v1.5:InvLMT.Academy.ReferenceGamutCompress.a1.v1.0
+ transform: !<BuiltinTransform> {style: ACES-LMT - ACES 1.3 Reference Gamut Compression}
+
+
+default_view_transform: Un-tone-mapped
+
+view_transforms:
+ - !<ViewTransform>
+ name: ACES 1.0 - SDR Video
+ description: |
+ Component of ACES Output Transforms for SDR D65 video
+
+ ACEStransformID: urn:ampas:aces:transformId:v1.5:ODT.Academy.RGBmonitor_100nits_dim.a1.0.3
+ ACEStransformID: urn:ampas:aces:transformId:v1.5:ODT.Academy.DisplayP3_dim.a1.0.0
+ ACEStransformID: urn:ampas:aces:transformId:v1.5:ODT.Academy.Rec709_100nits_dim.a1.0.3
+ ACEStransformID: urn:ampas:aces:transformId:v1.5:ODT.Academy.Rec2020_100nits_dim.a1.0.3
+
+ AMF Components
+ --------------
+ ACEStransformID: urn:ampas:aces:transformId:v1.5:InvODT.Academy.RGBmonitor_100nits_dim.a1.0.3
+ ACEStransformID: urn:ampas:aces:transformId:v1.5:InvODT.Academy.DisplayP3_dim.a1.0.0
+ ACEStransformID: urn:ampas:aces:transformId:v1.5:InvODT.Academy.Rec709_100nits_dim.a1.0.3
+ ACEStransformID: urn:ampas:aces:transformId:v1.5:InvODT.Academy.Rec2020_100nits_dim.a1.0.3
+ from_scene_reference: !<BuiltinTransform> {style: ACES-OUTPUT - ACES2065-1_to_CIE-XYZ-D65 - SDR-VIDEO_1.0}
+
+ - !<ViewTransform>
+ name: "ACES 1.1 - HDR Video (1000 nits & Rec.2020 lim)"
+ description: |
+ Component of ACES Output Transforms for 1000 nit HDR D65 video
+
+ ACEStransformID: urn:ampas:aces:transformId:v1.5:RRTODT.Academy.Rec2020_1000nits_15nits_HLG.a1.1.0
+ ACEStransformID: urn:ampas:aces:transformId:v1.5:RRTODT.Academy.Rec2020_1000nits_15nits_ST2084.a1.1.0
+
+ AMF Components
+ --------------
+ ACEStransformID: urn:ampas:aces:transformId:v1.5:InvRRTODT.Academy.Rec2020_1000nits_15nits_HLG.a1.1.0
+ ACEStransformID: urn:ampas:aces:transformId:v1.5:InvRRTODT.Academy.Rec2020_1000nits_15nits_ST2084.a1.1.0
+ from_scene_reference: !<BuiltinTransform> {style: ACES-OUTPUT - ACES2065-1_to_CIE-XYZ-D65 - HDR-VIDEO-1000nit-15nit-REC2020lim_1.1}
+
+ - !<ViewTransform>
+ name: "ACES 1.1 - HDR Video (1000 nits & P3 lim)"
+ description: |
+ Component of ACES Output Transforms for 1000 nit HDR D65 video
+
+ ACEStransformID: urn:ampas:aces:transformId:v1.5:RRTODT.Academy.P3D65_1000nits_15nits_ST2084.a1.1.0
+
+ AMF Components
+ --------------
+ ACEStransformID: urn:ampas:aces:transformId:v1.5:InvRRTODT.Academy.P3D65_1000nits_15nits_ST2084.a1.1.0
+ from_scene_reference: !<BuiltinTransform> {style: ACES-OUTPUT - ACES2065-1_to_CIE-XYZ-D65 - HDR-VIDEO-1000nit-15nit-P3lim_1.1}
+
+ - !<ViewTransform>
+ name: ACES 1.0 - SDR Cinema
+ description: |
+ Component of ACES Output Transforms for SDR cinema
+
+ ACEStransformID: urn:ampas:aces:transformId:v1.5:ODT.Academy.P3D60_48nits.a1.0.3
+ ACEStransformID: urn:ampas:aces:transformId:v1.5:ODT.Academy.P3D65_48nits.a1.1.0
+
+ AMF Components
+ --------------
+ ACEStransformID: urn:ampas:aces:transformId:v1.5:InvODT.Academy.P3D60_48nits.a1.0.3
+ ACEStransformID: urn:ampas:aces:transformId:v1.5:InvODT.Academy.P3D65_48nits.a1.1.0
+ from_scene_reference: !<BuiltinTransform> {style: ACES-OUTPUT - ACES2065-1_to_CIE-XYZ-D65 - SDR-CINEMA_1.0}
+
+ - !<ViewTransform>
+ name: Un-tone-mapped
+ from_scene_reference: !<BuiltinTransform> {style: UTILITY - ACES-AP0_to_CIE-XYZ-D65_BFD}
+
+display_colorspaces:
+ - !<ColorSpace>
+ name: CIE-XYZ-D65
+ aliases: [cie_xyz_d65]
+ family: ""
+ equalitygroup: ""
+ bitdepth: 32f
+ description: The "CIE XYZ (D65)" display connection colorspace.
+ isdata: false
+ allocation: uniform
+
+ - !<ColorSpace>
+ name: sRGB - Display
+ aliases: [srgb_display]
+ family: Display
+ equalitygroup: ""
+ bitdepth: 32f
+ description: |
+ Convert CIE XYZ (D65 white) to sRGB (piecewise EOTF)
+
+ AMF Components
+ --------------
+ ACEStransformID: urn:ampas:aces:transformId:v1.5:ODT.Academy.RGBmonitor_100nits_dim.a1.0.3
+ ACEStransformID: urn:ampas:aces:transformId:v1.5:InvODT.Academy.RGBmonitor_100nits_dim.a1.0.3
+ ACEStransformID: urn:ampas:aces:transformId:v1.5:ODT.Academy.RGBmonitor_D60sim_100nits_dim.a1.0.3
+ ACEStransformID: urn:ampas:aces:transformId:v1.5:InvODT.Academy.RGBmonitor_D60sim_100nits_dim.a1.0.3
+ isdata: false
+ categories: [file-io]
+ encoding: sdr-video
+ allocation: uniform
+ from_display_reference: !<BuiltinTransform> {style: DISPLAY - CIE-XYZ-D65_to_sRGB}
+
+ - !<ColorSpace>
+ name: Display P3 - Display
+ aliases: [displayp3_display]
+ family: Display
+ equalitygroup: ""
+ bitdepth: 32f
+ description: |
+ Convert CIE XYZ (D65 white) to Apple Display P3
+
+ AMF Components
+ --------------
+ ACEStransformID: urn:ampas:aces:transformId:v1.5:ODT.Academy.DisplayP3_dim.a1.0.0
+ ACEStransformID: urn:ampas:aces:transformId:v1.5:InvODT.Academy.DisplayP3_dim.a1.0.0
+ ACEStransformID: urn:ampas:aces:transformId:v1.5:ODT.Academy.DisplayP3_D60sim_dim.a1.0.0
+ ACEStransformID: urn:ampas:aces:transformId:v1.5:InvODT.Academy.DisplayP3_D60sim_dim.a1.0.0
+ isdata: false
+ categories: [file-io]
+ encoding: sdr-video
+ allocation: uniform
+ from_display_reference: !<BuiltinTransform> {style: DISPLAY - CIE-XYZ-D65_to_DisplayP3}
+
+ - !<ColorSpace>
+ name: Rec.1886 Rec.709 - Display
+ aliases: [rec1886_rec709_display]
+ family: Display
+ equalitygroup: ""
+ bitdepth: 32f
+ description: |
+ Convert CIE XYZ (D65 white) to Rec.1886/Rec.709 (HD video)
+
+ AMF Components
+ --------------
+ ACEStransformID: urn:ampas:aces:transformId:v1.5:ODT.Academy.Rec709_100nits_dim.a1.0.3
+ ACEStransformID: urn:ampas:aces:transformId:v1.5:InvODT.Academy.Rec709_100nits_dim.a1.0.3
+ ACEStransformID: urn:ampas:aces:transformId:v1.5:ODT.Academy.Rec709_D60sim_100nits_dim.a1.0.3
+ ACEStransformID: urn:ampas:aces:transformId:v1.5:InvODT.Academy.Rec709_D60sim_100nits_dim.a1.0.3
+ isdata: false
+ categories: [file-io]
+ encoding: sdr-video
+ allocation: uniform
+ from_display_reference: !<BuiltinTransform> {style: DISPLAY - CIE-XYZ-D65_to_REC.1886-REC.709}
+
+ - !<ColorSpace>
+ name: Rec.2100-PQ - Display
+ aliases: [rec2100_pq_display]
+ family: Display
+ equalitygroup: ""
+ bitdepth: 32f
+ description: |
+ Convert CIE XYZ (D65 white) to Rec.2100-PQ
+
+ AMF Components
+ --------------
+ ACEStransformID: urn:ampas:aces:transformId:v1.5:RRTODT.Academy.Rec2020_1000nits_15nits_ST2084.a1.1.0
+ ACEStransformID: urn:ampas:aces:transformId:v1.5:InvRRTODT.Academy.Rec2020_1000nits_15nits_ST2084.a1.1.0
+ ACEStransformID: urn:ampas:aces:transformId:v1.5:RRTODT.Academy.Rec2020_2000nits_15nits_ST2084.a1.1.0
+ ACEStransformID: urn:ampas:aces:transformId:v1.5:InvRRTODT.Academy.Rec2020_2000nits_15nits_ST2084.a1.1.0
+ ACEStransformID: urn:ampas:aces:transformId:v1.5:RRTODT.Academy.Rec2020_4000nits_15nits_ST2084.a1.1.0
+ ACEStransformID: urn:ampas:aces:transformId:v1.5:InvRRTODT.Academy.Rec2020_4000nits_15nits_ST2084.a1.1.0
+ isdata: false
+ categories: [file-io]
+ encoding: hdr-video
+ allocation: uniform
+ from_display_reference: !<BuiltinTransform> {style: DISPLAY - CIE-XYZ-D65_to_REC.2100-PQ}
+
+ - !<ColorSpace>
+ name: ST2084-P3-D65 - Display
+ aliases: [st2084_p3d65_display]
+ family: Display
+ equalitygroup: ""
+ bitdepth: 32f
+ description: |
+ Convert CIE XYZ (D65 white) to ST-2084 (PQ), P3-D65 primaries
+
+ AMF Components
+ --------------
+ ACEStransformID: urn:ampas:aces:transformId:v1.5:RRTODT.Academy.P3D65_1000nits_15nits_ST2084.a1.1.0
+ ACEStransformID: urn:ampas:aces:transformId:v1.5:InvRRTODT.Academy.P3D65_1000nits_15nits_ST2084.a1.1.0
+ ACEStransformID: urn:ampas:aces:transformId:v1.5:RRTODT.Academy.P3D65_2000nits_15nits_ST2084.a1.1.0
+ ACEStransformID: urn:ampas:aces:transformId:v1.5:InvRRTODT.Academy.P3D65_2000nits_15nits_ST2084.a1.1.0
+ ACEStransformID: urn:ampas:aces:transformId:v1.5:RRTODT.Academy.P3D65_4000nits_15nits_ST2084.a1.1.0
+ ACEStransformID: urn:ampas:aces:transformId:v1.5:InvRRTODT.Academy.P3D65_4000nits_15nits_ST2084.a1.1.0
+ ACEStransformID: urn:ampas:aces:transformId:v1.5:RRTODT.Academy.P3D65_108nits_7point2nits_ST2084.a1.1.0
+ ACEStransformID: urn:ampas:aces:transformId:v1.5:InvRRTODT.Academy.P3D65_108nits_7point2nits_ST2084.a1.1.0
+ isdata: false
+ categories: [file-io]
+ encoding: hdr-video
+ allocation: uniform
+ from_display_reference: !<BuiltinTransform> {style: DISPLAY - CIE-XYZ-D65_to_ST2084-P3-D65}
+
+ - !<ColorSpace>
+ name: P3-D65 - Display
+ aliases: [p3d65_display]
+ family: Display
+ equalitygroup: ""
+ bitdepth: 32f
+ description: |
+ Convert CIE XYZ (D65 white) to Gamma 2.6, P3-D65
+
+ AMF Components
+ --------------
+ ACEStransformID: urn:ampas:aces:transformId:v1.5:ODT.Academy.P3D65_48nits.a1.1.0
+ ACEStransformID: urn:ampas:aces:transformId:v1.5:InvODT.Academy.P3D65_48nits.a1.1.0
+ ACEStransformID: urn:ampas:aces:transformId:v1.5:ODT.Academy.P3D65_Rec709limited_48nits.a1.1.0
+ ACEStransformID: urn:ampas:aces:transformId:v1.5:ODT.Academy.P3D65_D60sim_48nits.a1.1.0
+ ACEStransformID: urn:ampas:aces:transformId:v1.5:InvODT.Academy.P3D65_D60sim_48nits.a1.1.0
+ isdata: false
+ categories: [file-io]
+ encoding: sdr-video
+ allocation: uniform
+ from_display_reference: !<BuiltinTransform> {style: DISPLAY - CIE-XYZ-D65_to_G2.6-P3-D65}
+
+colorspaces:
+ - !<ColorSpace>
+ name: ACES2065-1
+ aliases: [aces2065_1, ACES - ACES2065-1, lin_ap0]
+ family: ACES
+ equalitygroup: ""
+ bitdepth: 32f
+ description: The "Academy Color Encoding System" reference colorspace.
+ isdata: false
+ categories: [file-io]
+ encoding: scene-linear
+ allocation: uniform
+
+ - !<ColorSpace>
+ name: ACEScc
+ aliases: [ACES - ACEScc, acescc_ap1]
+ family: ACES
+ equalitygroup: ""
+ bitdepth: 32f
+ description: |
+ Convert ACEScc to ACES2065-1
+
+ ACEStransformID: urn:ampas:aces:transformId:v1.5:ACEScsc.Academy.ACEScc_to_ACES.a1.0.3
+
+ AMF Components
+ --------------
+ ACEStransformID: urn:ampas:aces:transformId:v1.5:ACEScsc.Academy.ACES_to_ACEScc.a1.0.3
+ isdata: false
+ categories: [file-io]
+ encoding: log
+ allocation: uniform
+ to_scene_reference: !<BuiltinTransform> {style: ACEScc_to_ACES2065-1}
+
+ - !<ColorSpace>
+ name: ACEScct
+ aliases: [ACES - ACEScct, acescct_ap1]
+ family: ACES
+ equalitygroup: ""
+ bitdepth: 32f
+ description: |
+ Convert ACEScct to ACES2065-1
+
+ ACEStransformID: urn:ampas:aces:transformId:v1.5:ACEScsc.Academy.ACEScct_to_ACES.a1.0.3
+
+ AMF Components
+ --------------
+ ACEStransformID: urn:ampas:aces:transformId:v1.5:ACEScsc.Academy.ACES_to_ACEScct.a1.0.3
+ isdata: false
+ categories: [file-io, working-space]
+ encoding: log
+ allocation: uniform
+ to_scene_reference: !<BuiltinTransform> {style: ACEScct_to_ACES2065-1}
+
+ - !<ColorSpace>
+ name: ACEScg
+ aliases: [ACES - ACEScg, lin_ap1]
+ family: ACES
+ equalitygroup: ""
+ bitdepth: 32f
+ description: |
+ Convert ACEScg to ACES2065-1
+
+ ACEStransformID: urn:ampas:aces:transformId:v1.5:ACEScsc.Academy.ACEScg_to_ACES.a1.0.3
+
+ AMF Components
+ --------------
+ ACEStransformID: urn:ampas:aces:transformId:v1.5:ACEScsc.Academy.ACES_to_ACEScg.a1.0.3
+ isdata: false
+ categories: [file-io, working-space, texture]
+ encoding: scene-linear
+ allocation: uniform
+ to_scene_reference: !<BuiltinTransform> {style: ACEScg_to_ACES2065-1}
+
+ - !<ColorSpace>
+ name: Linear P3-D65
+ aliases: [lin_p3d65, Utility - Linear - P3-D65, lin_displayp3, Linear Display P3]
+ family: Utility
+ equalitygroup: ""
+ bitdepth: 32f
+ description: |
+ Convert ACES2065-1 to linear P3 primaries, D65 white point
+
+ CLFtransformID: urn:aswf:ocio:transformId:1.0:OCIO:Utility:AP0_to_Linear_P3-D65:1.0
+ isdata: false
+ categories: [file-io, working-space, texture]
+ encoding: scene-linear
+ allocation: uniform
+ from_scene_reference: !<GroupTransform>
+ name: AP0 to Linear P3-D65
+ children:
+ - !<MatrixTransform> {matrix: [2.02490528596679, -0.689069761034766, -0.335835524932019, 0, -0.183597032256178, 1.28950620775902, -0.105909175502841, 0, 0.00905856112234766, -0.0592796840575522, 1.0502211229352, 0, 0, 0, 0, 1]}
+
+ - !<ColorSpace>
+ name: Linear Rec.2020
+ aliases: [lin_rec2020, Utility - Linear - Rec.2020]
+ family: Utility
+ equalitygroup: ""
+ bitdepth: 32f
+ description: |
+ Convert ACES2065-1 to linear Rec.2020 primaries, D65 white point
+
+ CLFtransformID: urn:aswf:ocio:transformId:1.0:OCIO:Utility:AP0_to_Linear_Rec2020:1.0
+ isdata: false
+ categories: [file-io, texture]
+ encoding: scene-linear
+ allocation: uniform
+ from_scene_reference: !<GroupTransform>
+ name: AP0 to Linear Rec.2020
+ children:
+ - !<MatrixTransform> {matrix: [1.49040952054172, -0.26617091926613, -0.224238601275593, 0, -0.0801674998722558, 1.18216712109757, -0.10199962122531, 0, 0.00322763119162216, -0.0347764757450576, 1.03154884455344, 0, 0, 0, 0, 1]}
+
+ - !<ColorSpace>
+ name: Linear Rec.709 (sRGB)
+ aliases: [lin_rec709_srgb, Utility - Linear - Rec.709, lin_rec709, lin_srgb, Utility - Linear - sRGB]
+ family: Utility
+ equalitygroup: ""
+ bitdepth: 32f
+ description: |
+ Convert ACES2065-1 to linear Rec.709 primaries, D65 white point
+
+ CLFtransformID: urn:aswf:ocio:transformId:1.0:OCIO:Utility:AP0_to_Linear_Rec709:1.0
+ isdata: false
+ categories: [file-io, working-space, texture]
+ encoding: scene-linear
+ allocation: uniform
+ from_scene_reference: !<GroupTransform>
+ name: AP0 to Linear Rec.709 (sRGB)
+ children:
+ - !<MatrixTransform> {matrix: [2.52168618674388, -1.13413098823972, -0.387555198504164, 0, -0.276479914229922, 1.37271908766826, -0.096239173438334, 0, -0.0153780649660342, -0.152975335867399, 1.16835340083343, 0, 0, 0, 0, 1]}
+
+ - !<ColorSpace>
+ name: Gamma 1.8 Rec.709 - Texture
+ aliases: [g18_rec709_tx, Utility - Gamma 1.8 - Rec.709 - Texture, g18_rec709]
+ family: Utility
+ equalitygroup: ""
+ bitdepth: 32f
+ description: |
+ Convert ACES2065-1 to 1.8 gamma-corrected Rec.709 primaries, D65 white point
+
+ CLFtransformID: urn:aswf:ocio:transformId:1.0:OCIO:Utility:AP0_to_Gamma1.8_Rec709-Texture:1.0
+ isdata: false
+ categories: [file-io, texture]
+ encoding: sdr-video
+ allocation: uniform
+ from_scene_reference: !<GroupTransform>
+ name: AP0 to Gamma 1.8 Rec.709 - Texture
+ children:
+ - !<MatrixTransform> {matrix: [2.52168618674388, -1.13413098823972, -0.387555198504164, 0, -0.276479914229922, 1.37271908766826, -0.096239173438334, 0, -0.0153780649660342, -0.152975335867399, 1.16835340083343, 0, 0, 0, 0, 1]}
+ - !<ExponentTransform> {value: 1.8, style: pass_thru, direction: inverse}
+
+ - !<ColorSpace>
+ name: Gamma 2.2 AP1 - Texture
+ aliases: [g22_ap1_tx, g22_ap1]
+ family: Utility
+ equalitygroup: ""
+ bitdepth: 32f
+ description: |
+ Convert ACES2065-1 to 2.2 gamma-corrected AP1 primaries, ACES ~=D60 white point
+
+ CLFtransformID: urn:aswf:ocio:transformId:1.0:OCIO:Utility:AP0_to_Gamma2.2_AP1-Texture:1.0
+ isdata: false
+ categories: [file-io, texture]
+ encoding: sdr-video
+ allocation: uniform
+ from_scene_reference: !<GroupTransform>
+ name: AP0 to Gamma 2.2 AP1 - Texture
+ children:
+ - !<MatrixTransform> {matrix: [1.45143931614567, -0.23651074689374, -0.214928569251925, 0, -0.0765537733960206, 1.17622969983357, -0.0996759264375522, 0, 0.00831614842569772, -0.00603244979102102, 0.997716301365323, 0, 0, 0, 0, 1]}
+ - !<ExponentTransform> {value: 2.2, style: pass_thru, direction: inverse}
+
+ - !<ColorSpace>
+ name: Gamma 2.2 Rec.709 - Texture
+ aliases: [g22_rec709_tx, Utility - Gamma 2.2 - Rec.709 - Texture, g22_rec709]
+ family: Utility
+ equalitygroup: ""
+ bitdepth: 32f
+ description: |
+ Convert ACES2065-1 to 2.2 gamma-corrected Rec.709 primaries, D65 white point
+
+ CLFtransformID: urn:aswf:ocio:transformId:1.0:OCIO:Utility:AP0_to_Gamma2.2_Rec709-Texture:1.0
+ isdata: false
+ categories: [file-io, texture]
+ encoding: sdr-video
+ allocation: uniform
+ from_scene_reference: !<GroupTransform>
+ name: AP0 to Gamma 2.2 Rec.709 - Texture
+ children:
+ - !<MatrixTransform> {matrix: [2.52168618674388, -1.13413098823972, -0.387555198504164, 0, -0.276479914229922, 1.37271908766826, -0.096239173438334, 0, -0.0153780649660342, -0.152975335867399, 1.16835340083343, 0, 0, 0, 0, 1]}
+ - !<ExponentTransform> {value: 2.2, style: pass_thru, direction: inverse}
+
+ - !<ColorSpace>
+ name: Gamma 2.4 Rec.709 - Texture
+ aliases: [g24_rec709_tx, g24_rec709, rec709_display, Utility - Rec.709 - Display]
+ family: Utility
+ equalitygroup: ""
+ bitdepth: 32f
+ description: |
+ Convert ACES2065-1 to 2.4 gamma-corrected Rec.709 primaries, D65 white point
+
+ CLFtransformID: urn:aswf:ocio:transformId:1.0:OCIO:Utility:AP0_to_Gamma2.4_Rec709-Texture:1.0
+ isdata: false
+ categories: [file-io, texture]
+ encoding: sdr-video
+ allocation: uniform
+ from_scene_reference: !<GroupTransform>
+ name: AP0 to Gamma 2.4 Rec.709 - Texture
+ children:
+ - !<MatrixTransform> {matrix: [2.52168618674388, -1.13413098823972, -0.387555198504164, 0, -0.276479914229922, 1.37271908766826, -0.096239173438334, 0, -0.0153780649660342, -0.152975335867399, 1.16835340083343, 0, 0, 0, 0, 1]}
+ - !<ExponentTransform> {value: 2.4, style: pass_thru, direction: inverse}
+
+ - !<ColorSpace>
+ name: sRGB Encoded AP1 - Texture
+ aliases: [srgb_encoded_ap1_tx, srgb_ap1]
+ family: Utility
+ equalitygroup: ""
+ bitdepth: 32f
+ description: |
+ Convert ACES2065-1 to sRGB Encoded AP1 primaries, ACES ~=D60 white point
+
+ CLFtransformID: urn:aswf:ocio:transformId:1.0:OCIO:Utility:AP0_to_sRGB_Encoded_AP1-Texture:1.0
+ isdata: false
+ categories: [file-io, texture]
+ encoding: sdr-video
+ allocation: uniform
+ from_scene_reference: !<GroupTransform>
+ name: AP0 to sRGB Encoded AP1 - Texture
+ children:
+ - !<MatrixTransform> {matrix: [1.45143931614567, -0.23651074689374, -0.214928569251925, 0, -0.0765537733960206, 1.17622969983357, -0.0996759264375522, 0, 0.00831614842569772, -0.00603244979102102, 0.997716301365323, 0, 0, 0, 0, 1]}
+ - !<ExponentWithLinearTransform> {gamma: 2.4, offset: 0.055, direction: inverse}
+
+ - !<ColorSpace>
+ name: sRGB Encoded P3-D65 - Texture
+ aliases: [srgb_encoded_p3d65_tx, srgb_p3d65, srgb_displayp3]
+ family: Utility
+ equalitygroup: ""
+ bitdepth: 32f
+ description: |
+ Convert ACES2065-1 to sRGB Encoded P3-D65 primaries, D65 white point
+
+ CLFtransformID: urn:aswf:ocio:transformId:1.0:OCIO:Utility:AP0_to_sRGB_Encoded_P3-D65-Texture:1.0
+ isdata: false
+ categories: [file-io, texture]
+ encoding: sdr-video
+ allocation: uniform
+ from_scene_reference: !<GroupTransform>
+ name: AP0 to sRGB Encoded P3-D65 - Texture
+ children:
+ - !<MatrixTransform> {matrix: [2.02490528596679, -0.689069761034766, -0.335835524932019, 0, -0.183597032256178, 1.28950620775902, -0.105909175502841, 0, 0.00905856112234766, -0.0592796840575522, 1.0502211229352, 0, 0, 0, 0, 1]}
+ - !<ExponentWithLinearTransform> {gamma: 2.4, offset: 0.055, direction: inverse}
+
+ - !<ColorSpace>
+ name: sRGB - Texture
+ aliases: [srgb_tx, Utility - sRGB - Texture, srgb_texture, Input - Generic - sRGB - Texture]
+ family: Utility
+ equalitygroup: ""
+ bitdepth: 32f
+ description: |
+ Convert ACES2065-1 to sRGB
+
+ CLFtransformID: urn:aswf:ocio:transformId:1.0:OCIO:Utility:AP0_to_sRGB-Texture:1.0
+ isdata: false
+ categories: [file-io, texture]
+ allocation: uniform
+ from_scene_reference: !<GroupTransform>
+ name: AP0 to sRGB Rec.709
+ children:
+ - !<MatrixTransform> {matrix: [2.52168618674388, -1.13413098823972, -0.387555198504164, 0, -0.276479914229922, 1.37271908766826, -0.096239173438334, 0, -0.0153780649660342, -0.152975335867399, 1.16835340083343, 0, 0, 0, 0, 1]}
+ - !<ExponentWithLinearTransform> {gamma: 2.4, offset: 0.055, direction: inverse}
+
+ - !<ColorSpace>
+ name: Raw
+ aliases: [Utility - Raw]
+ family: Utility
+ equalitygroup: ""
+ bitdepth: 32f
+ description: The utility "Raw" colorspace.
+ isdata: true
+ categories: [file-io, texture]
+ allocation: uniform
+
+named_transforms:
+ - !<NamedTransform>
+ name: Rec.1886 - Curve
+ aliases: [rec1886_crv, Utility - Curve - Rec.1886, crv_rec1886]
+ description: |
+ Convert generic linear RGB to Rec.1886 encoded RGB
+
+ CLFtransformID: urn:aswf:ocio:transformId:1.0:OCIO:Utility:Linear_to_Rec1886-Curve:1.0
+ family: Utility
+ categories: [file-io]
+ encoding: sdr-video
+ inverse_transform: !<GroupTransform>
+ name: Linear to Rec.1886
+ children:
+ - !<ExponentTransform> {value: 2.4, style: pass_thru, direction: inverse}
+
+ - !<NamedTransform>
+ name: sRGB - Curve
+ aliases: [srgb_crv, Utility - Curve - sRGB, crv_srgb]
+ description: |
+ Convert generic linear RGB to sRGB encoded RGB
+
+ CLFtransformID: urn:aswf:ocio:transformId:1.0:OCIO:Utility:Linear_to_sRGB-Curve:1.0
+ family: Utility
+ categories: [file-io]
+ encoding: sdr-video
+ inverse_transform: !<GroupTransform>
+ name: Linear to sRGB
+ children:
+ - !<ExponentWithLinearTransform> {gamma: 2.4, offset: 0.055, direction: inverse}
diff --git a/packages/core/src/color/hdr-working.ts b/packages/core/src/color/hdr-working.ts
index c8b8a050..538040b4 100644
--- a/packages/core/src/color/hdr-working.ts
+++ b/packages/core/src/color/hdr-working.ts
@@ -32,6 +32,15 @@ import { applyColorWheelsToRgb } from "../video/lumetri-pipeline";
import { BT2020_TO_BT709, hlgInverseOetf, P3_TO_BT709, TONE_MAP_KNEE } from "./input-transform";
import type { SourceColorSpace, SourceTransfer } from "./source-color";
import { CAMERA_LOGS, cameraGamutToBt2020, cameraLogForShaderId, decodeCameraLog, type CameraGamutId } from "./camera-log";
+import {
+ acescctDecode,
+ acescctEncode,
+ ACESCCT_WHITE,
+ gamutToAp1,
+ isAcesMode,
+ type AcesOutputId,
+ type AcesSdrOutput,
+} from "./aces";
/**
* Scene-referred HDR working mode.
@@ -77,26 +86,65 @@ export const P3_TO_BT2020: Matrix3 = /* @__PURE__ */ mul3(BT709_TO_BT2020, P3_TO
/** True when the project's frames should be composed in float. SDR Rec.709 projects with no HDR output never are. */
export function isHdrWorkingMode(
- settings: Pick<ProjectSettings, "workingColorSpace"> | undefined,
+ settings: Pick<ProjectSettings, "workingColorSpace" | "colorManagement"> | undefined,
hdr: HdrTransfer | undefined,
): boolean {
- return settings?.workingColorSpace === "rec2020" || hdr === "pq" || hdr === "hlg";
+ return settings?.workingColorSpace === "rec2020" || hdr === "pq" || hdr === "hlg" || isAcesMode(settings);
+}
+
+/** `acesOutputTransform` of `color/aces-output.ts`, registered by whoever runs the ACES pipeline (the video engine, tests). */
+export type AcesOutputFn = (r: number, g: number, b: number, output: AcesOutputId, out: number[]) => number[];
+let acesOutputFn: AcesOutputFn | null = null;
+
+/**
+ * The Output Transform (RRT + ODT) is ~10 KB of tables and splines only the compositors run, so it lives in its own module
+ * that the startup bundle never imports; the code that runs an ACES pipeline hands it over here.
+ */
+export function registerAcesOutputTransform(fn: AcesOutputFn): void {
+ acesOutputFn = fn;
+}
+
+function acesOutput(): AcesOutputFn {
+ if (!acesOutputFn) throw new Error("The ACES output transform is not loaded: call registerAcesOutputTransform(acesOutputTransform) from color/aces-output.");
+ return acesOutputFn;
+}
+
+/**
+ * Which colour pipeline the float compositor runs.
+ * scene-hdr working space scene-linear BT.2020, grading in PQ, SDR view / HDR encode by tone map (the Rec.2020 / HDR mode)
+ * aces working space ACEScg (AP1), grading in ACEScct, SDR view / encode through the ACES Output Transform (RRT + ODT)
+ */
+export type HdrColorPipeline =
+ | { readonly kind: "scene-hdr" }
+ | { readonly kind: "aces"; readonly sdrOutput: AcesSdrOutput };
+
+export const SCENE_HDR_PIPELINE: HdrColorPipeline = { kind: "scene-hdr" };
+
+export function acesPipeline(sdrOutput: AcesSdrOutput = "srgb"): HdrColorPipeline {
+ return { kind: "aces", sdrOutput };
+}
+
+/** The pipeline a project's settings select. */
+export function hdrPipelineFor(settings: Pick<ProjectSettings, "colorManagement" | "acesOutput"> | undefined): HdrColorPipeline {
+ return isAcesMode(settings) ? acesPipeline(settings?.acesOutput === "rec709" ? "rec709" : "srgb") : SCENE_HDR_PIPELINE;
}
// -- source decode --------------------------------------------------------------------------------------------
-/** 0 sRGB, 1 PQ, 2 HLG, 3 linear, 4..12 the camera log curves (`CAMERA_LOGS[n].shaderId`). */
+/** 0 sRGB, 1 PQ, 2 HLG, 3 linear, 4..12 the camera log curves (`CAMERA_LOGS[n].shaderId`), 13 ACEScct. */
export type HdrTransferId = number;
export const HDR_TRANSFER_SRGB: HdrTransferId = 0;
export const HDR_TRANSFER_PQ: HdrTransferId = 1;
export const HDR_TRANSFER_HLG: HdrTransferId = 2;
export const HDR_TRANSFER_LINEAR: HdrTransferId = 3;
+/** ACEScct footage (4..12 are the camera log curves). */
+export const HDR_TRANSFER_ACESCCT: HdrTransferId = 13;
export interface HdrSourceDecode {
/** Stable identity: equal keys decode identically. */
readonly key: string;
readonly transfer: HdrTransferId;
- /** Source primaries to BT.2020, in linear light. */
+ /** Source primaries to the working primaries (BT.2020 in the scene-hdr pipeline, AP1 / ACEScg in the aces pipeline), in linear light. */
readonly toBt2020: Matrix3;
}
@@ -108,6 +156,8 @@ function transferId(transfer: SourceTransfer): HdrTransferId {
return HDR_TRANSFER_HLG;
case "linear":
return HDR_TRANSFER_LINEAR;
+ case "acescct":
+ return HDR_TRANSFER_ACESCCT;
default:
return CAMERA_LOGS.find((d) => d.id === transfer)?.shaderId ?? HDR_TRANSFER_SRGB;
}
@@ -128,8 +178,29 @@ function primariesToBt2020(primaries: SourceColorSpace["primaries"]): Matrix3 {
}
}
-/** Decode description of footage. `null` (untagged / plain SDR) reads the canvas as sRGB Rec.709. */
-export function hdrSourceDecode(space: SourceColorSpace | null | undefined): HdrSourceDecode {
+/** The gamut id the ACES input transform takes a source's primaries as. */
+function acesGamutOf(primaries: SourceColorSpace["primaries"]): CameraGamutId | "rec709" | "p3" {
+ switch (primaries) {
+ case "bt709":
+ case "bt601":
+ return "rec709";
+ case "p3":
+ return "p3";
+ default:
+ return primaries as CameraGamutId;
+ }
+}
+
+/**
+ * Decode description of footage. `null` (untagged / plain SDR) reads the canvas as sRGB Rec.709.
+ * In the aces pipeline this is the Input Transform (IDT): the same code-value decode, then the source primaries to
+ * AP1 with a Bradford adaptation to the ACES white.
+ */
+export function hdrSourceDecode(space: SourceColorSpace | null | undefined, pipeline: HdrColorPipeline = SCENE_HDR_PIPELINE): HdrSourceDecode {
+ if (pipeline.kind === "aces") {
+ if (!space) return ACES_SDR_DECODE;
+ return { key: `aces:${space.primaries}/${space.transfer}`, transfer: transferId(space.transfer), toBt2020: gamutToAp1(acesGamutOf(space.primaries)) };
+ }
if (!space) return SDR_DECODE;
const toBt2020 = primariesToBt2020(space.primaries);
return { key: `${space.primaries}/${space.transfer}`, transfer: transferId(space.transfer), toBt2020 };
@@ -137,9 +208,17 @@ export function hdrSourceDecode(space: SourceColorSpace | null | undefined): Hdr
export const SDR_DECODE: HdrSourceDecode = { key: "bt709/srgb", transfer: HDR_TRANSFER_SRGB, toBt2020: BT709_TO_BT2020 };
+/** sRGB / Rec.709 footage through the ACES input transform (sRGB EOTF, Rec.709 primaries to AP1). */
+export const ACES_SDR_DECODE: HdrSourceDecode = { key: "aces:bt709/srgb", transfer: HDR_TRANSFER_SRGB, toBt2020: /* @__PURE__ */ gamutToAp1("rec709") };
+
/** Graphics white: where 8-bit sRGB overlays sit in the working space. */
export const HDR_OVERLAY_DECODE: HdrSourceDecode = SDR_DECODE;
+/** Where 8-bit overlays enter: sRGB white in the working primaries of the pipeline. */
+export function overlayDecodeFor(pipeline: HdrColorPipeline): HdrSourceDecode {
+ return pipeline.kind === "aces" ? ACES_SDR_DECODE : HDR_OVERLAY_DECODE;
+}
+
/** Signal 0..1 to scene-linear where 1.0 = SDR reference white (no clipping above 1). */
export function decodeToWorkingLinear(signal: number, transfer: HdrTransferId): number {
const log = cameraLogForShaderId(transfer);
@@ -151,6 +230,8 @@ export function decodeToWorkingLinear(signal: number, transfer: HdrTransferId):
return hlgInverseOetf(signal) / HLG_SDR_WHITE_SCENE;
case HDR_TRANSFER_LINEAR:
return signal;
+ case HDR_TRANSFER_ACESCCT:
+ return acescctDecode(signal);
default:
return srgbToLinear(signal);
}
@@ -236,6 +317,8 @@ export interface HdrGradeSpec {
readonly hsl: HdrHslSpec | null;
/** Radial vignette in source-frame coordinates. Needs a position, see `HdrGradePosition`. */
readonly vignette: VignetteValues | null;
+ /** Grade in ACEScct instead of the PQ working encoding (the aces pipeline). */
+ readonly acescct?: boolean;
}
/** Colour space a clip's LUT was authored for (its input domain). */
@@ -365,7 +448,7 @@ function clampUnit(v: number | undefined): number {
}
/** Bakes a clip's grading into the data both the GPU pass and the CPU reference read. Null: nothing to do. */
-export function prepareHdrGrade(grading: ClipColorGrading | undefined): HdrGradeSpec | null {
+export function prepareHdrGrade(grading: ClipColorGrading | undefined, pipeline: HdrColorPipeline = SCENE_HDR_PIPELINE): HdrGradeSpec | null {
if (!grading) return null;
const exposure = clampUnit(grading.tone?.exposure);
const temperature = (grading.temperature ?? 0) / 100;
@@ -405,6 +488,7 @@ export function prepareHdrGrade(grading: ClipColorGrading | undefined): HdrGrade
lut,
hsl,
vignette,
+ ...(pipeline.kind === "aces" ? { acescct: true } : {}),
};
return isNeutralHdrGrade(spec) ? null : spec;
}
@@ -484,9 +568,14 @@ export function gradeHdrPixel(r: number, g: number, b: number, spec: HdrGradeSpe
g *= spec.exposureGain;
b *= spec.exposureGain;
}
- r = linearToPqWorking(r);
- g = linearToPqWorking(g);
- b = linearToPqWorking(b);
+ const cct = spec.acescct === true;
+ // The grade's working encoding: PQ (scene-hdr) or ACEScct (aces; negative light is floored at 0 like PQ's).
+ const enc = cct ? (v: number): number => acescctEncode(Math.max(0, v)) : linearToPqWorking;
+ const dec = cct ? acescctDecode : pqWorkingToLinear;
+ const white = cct ? ACESCCT_WHITE : PQ_WORKING_WHITE;
+ r = enc(r);
+ g = enc(g);
+ b = enc(b);
if (spec.whiteBalance) {
const wb = spec.whiteBalance;
r = Math.max(0, Math.min(1, r + wb[0]));
@@ -511,9 +600,9 @@ export function gradeHdrPixel(r: number, g: number, b: number, spec: HdrGradeSpe
// The LUT sees the image in its declared space. Signal above 1.0 (highlights over SDR white in an sRGB or
// linear LUT) bypasses the table and is added back on top of its output, so the grade never clips what it
// cannot address.
- const er = lutDomainEncode(pqWorkingToLinear(r), lut.space);
- const eg = lutDomainEncode(pqWorkingToLinear(g), lut.space);
- const eb = lutDomainEncode(pqWorkingToLinear(b), lut.space);
+ const er = lutDomainEncode(dec(r), lut.space);
+ const eg = lutDomainEncode(dec(g), lut.space);
+ const eb = lutDomainEncode(dec(b), lut.space);
// An exact 1D curve addresses its own domain; signal above its domainMax bypasses it like the 3D table.
const cr = Math.min(lut.curve ? lut.curve.domainMax[0] : 1, er);
const cg = Math.min(lut.curve ? lut.curve.domainMax[1] : 1, eg);
@@ -525,9 +614,9 @@ export function gradeHdrPixel(r: number, g: number, b: number, spec: HdrGradeSpe
const outR = er + (mapped[0] + (er - cr) - er) * k;
const outG = eg + (mapped[1] + (eg - cg) - eg) * k;
const outB = eb + (mapped[2] + (eb - cb) - eb) * k;
- r = linearToPqWorking(lutDomainDecode(outR, lut.space));
- g = linearToPqWorking(lutDomainDecode(outG, lut.space));
- b = linearToPqWorking(lutDomainDecode(outB, lut.space));
+ r = enc(lutDomainDecode(outR, lut.space));
+ g = enc(lutDomainDecode(outG, lut.space));
+ b = enc(lutDomainDecode(outB, lut.space));
}
if (spec.hsl) {
const hsl = spec.hsl;
@@ -551,13 +640,13 @@ export function gradeHdrPixel(r: number, g: number, b: number, spec: HdrGradeSpe
b *= gain;
} else {
const lift = amount * w;
- r += Math.max(PQ_WORKING_WHITE - r, 0) * lift;
- g += Math.max(PQ_WORKING_WHITE - g, 0) * lift;
- b += Math.max(PQ_WORKING_WHITE - b, 0) * lift;
+ r += Math.max(white - r, 0) * lift;
+ g += Math.max(white - g, 0) * lift;
+ b += Math.max(white - b, 0) * lift;
}
}
}
- return [pqWorkingToLinear(r), pqWorkingToLinear(g), pqWorkingToLinear(b)];
+ return [dec(r), dec(g), dec(b)];
}
// -- geometry -------------------------------------------------------------------------------------------------
@@ -659,6 +748,8 @@ export interface HdrFrame {
export interface HdrCompositor {
readonly kind: "gpu" | "cpu";
+ /** Which colour pipeline the compositor runs (overlay entry, SDR view, encode). Default scene-hdr. Persists across frames. */
+ setColorPipeline(pipeline: HdrColorPipeline): void;
begin(width: number, height: number): void;
/** Sets where 8-bit overlays (graphics) sit, as the nits of their white. Default 203. Persists across frames. */
setGraphicsWhite(nits: number): void;
@@ -709,6 +800,11 @@ export class CpuHdrCompositor implements HdrCompositor {
private height = 0;
private acc = new Float32Array(0);
private overlayGain = 1;
+ private pipeline: HdrColorPipeline = SCENE_HDR_PIPELINE;
+
+ setColorPipeline(pipeline: HdrColorPipeline): void {
+ this.pipeline = pipeline;
+ }
setGraphicsWhite(nits: number): void {
this.overlayGain = graphicsWhiteGain(nits);
@@ -784,7 +880,7 @@ export class CpuHdrCompositor implements HdrCompositor {
if (pixels.width !== this.width || pixels.height !== this.height) throw new Error("Overlay size does not match the HDR frame.");
const lut = decodeLut8(HDR_TRANSFER_SRGB);
const gain = this.overlayGain;
- const [m0, m1, m2] = HDR_OVERLAY_DECODE.toBt2020;
+ const [m0, m1, m2] = overlayDecodeFor(this.pipeline).toBt2020;
const src = pixels.data as ArrayLike<number>;
const acc = this.acc;
const n = this.width * this.height;
@@ -803,7 +899,7 @@ export class CpuHdrCompositor implements HdrCompositor {
}
readSdrView(): Uint8ClampedArray {
- return hdrFrameToSdrRgba(this.readFrame());
+ return hdrFrameToSdrRgba(this.readFrame(), this.pipeline);
}
readFrame(): HdrFrame {
@@ -811,7 +907,7 @@ export class CpuHdrCompositor implements HdrCompositor {
}
readEncodedRgb(spec: OutputColorSpec): Float32Array {
- return encodeHdrFrameRgb({ width: this.width, height: this.height, data: this.acc }, spec);
+ return encodeHdrFrameRgb({ width: this.width, height: this.height, data: this.acc }, spec, this.pipeline);
}
dispose(): void {
@@ -872,9 +968,22 @@ function srgbEncode(linear: number): number {
* sRGB. This is what the preview canvas shows and what an SDR export of an HDR
* project contains.
*/
-export function hdrFrameToSdrRgba(frame: HdrFrame): Uint8ClampedArray {
+export function hdrFrameToSdrRgba(frame: HdrFrame, pipeline: HdrColorPipeline = SCENE_HDR_PIPELINE): Uint8ClampedArray {
const n = frame.width * frame.height;
const out = new Uint8ClampedArray(n * 4);
+ if (pipeline.kind === "aces") {
+ const d = frame.data;
+ const rgb = [0, 0, 0];
+ const transform = acesOutput();
+ for (let p = 0, o = 0; p < n; p++, o += 4) {
+ transform(Math.max(0, d[o]), Math.max(0, d[o + 1]), Math.max(0, d[o + 2]), pipeline.sdrOutput, rgb);
+ out[o] = Math.round(rgb[0] * 255);
+ out[o + 1] = Math.round(rgb[1] * 255);
+ out[o + 2] = Math.round(rgb[2] * 255);
+ out[o + 3] = Math.round(Math.max(0, Math.min(1, d[o + 3])) * 255);
+ }
+ return out;
+ }
const [m0, m1, m2] = BT2020_TO_BT709;
const d = frame.data;
const rgb: [number, number, number] = [0, 0, 0];
@@ -932,9 +1041,27 @@ export function fastTransferEncoder(transfer: OutputColorSpec["transfer"]): (lin
* pixel, 0..1). PQ and HLG keep everything above SDR white up to their peak;
* an SDR transfer applies the highlight shoulder first.
*/
-export function encodeHdrFrameRgb(frame: HdrFrame, spec: OutputColorSpec): Float32Array {
+/** The ACES output transform an encode of `spec` runs: PQ / HLG targets use the Rec.2020 1000 nit transforms. */
+export function acesOutputForSpec(spec: OutputColorSpec, sdrOutput: AcesSdrOutput): AcesOutputId {
+ return spec.transfer === "pq" ? "rec2020-pq" : spec.transfer === "hlg" ? "rec2020-hlg" : sdrOutput;
+}
+
+export function encodeHdrFrameRgb(frame: HdrFrame, spec: OutputColorSpec, pipeline: HdrColorPipeline = SCENE_HDR_PIPELINE): Float32Array {
const n = frame.width * frame.height;
const out = new Float32Array(n * 3);
+ if (pipeline.kind === "aces") {
+ const id = acesOutputForSpec(spec, pipeline.sdrOutput);
+ const d = frame.data;
+ const rgb = [0, 0, 0];
+ const transform = acesOutput();
+ for (let p = 0, o = 0, q = 0; p < n; p++, o += 4, q += 3) {
+ transform(Math.max(0, d[o]), Math.max(0, d[o + 1]), Math.max(0, d[o + 2]), id, rgb);
+ out[q] = rgb[0];
+ out[q + 1] = rgb[1];
+ out[q + 2] = rgb[2];
+ }
+ return out;
+ }
const encode = fastTransferEncoder(spec.transfer);
const sdr = spec.transfer === "bt709";
const toBt709 = spec.primaries === "bt709";
diff --git a/packages/core/src/color/input-transform.ts b/packages/core/src/color/input-transform.ts
index a5aec995..7ef59abb 100644
--- a/packages/core/src/color/input-transform.ts
+++ b/packages/core/src/color/input-transform.ts
@@ -1,5 +1,6 @@
import { BT709_TO_BT2020, HLG_SDR_WHITE_SCENE, PQ_SDR_WHITE_NITS, linearToSrgb, pqDecodeToNits, srgbToLinear } from "../export/color-output";
import { cameraGamutToBt709, decodeCameraLog, type CameraGamutId } from "./camera-log";
+import { acescctDecode } from "./aces";
import { isCameraLogTransfer, needsInputTransform, type SourceColorSpace } from "./source-color";
/**
@@ -80,6 +81,8 @@ export function decodeSourceTransfer(signal: number, transfer: SourceColorSpace[
return hlgInverseOetf(signal) / HLG_SDR_WHITE_SCENE;
case "linear":
return signal;
+ case "acescct":
+ return acescctDecode(signal);
default:
return srgbToLinear(signal);
}
@@ -129,7 +132,13 @@ export function createInputTransform(source: SourceColorSpace): InputTransform |
source,
key: inputTransformKey(source),
// Camera log scene light goes through the same shoulder: log footage holds highlights far above white.
- toneMap: source.transfer === "pq" || source.transfer === "hlg" || isCameraLogTransfer(source.transfer),
+ toneMap:
+ source.transfer === "pq" ||
+ source.transfer === "hlg" ||
+ source.transfer === "acescct" ||
+ source.primaries === "ap0" ||
+ source.primaries === "ap1" ||
+ isCameraLogTransfer(source.transfer),
matrix: primariesToBt709(source.primaries),
decodeLut,
};
diff --git a/packages/core/src/color/ocio-config.test.ts b/packages/core/src/color/ocio-config.test.ts
new file mode 100644
index 00000000..31fa54e7
--- /dev/null
+++ b/packages/core/src/color/ocio-config.test.ts
@@ -0,0 +1,130 @@
+import { readFileSync } from "node:fs";
+import { describe, expect, it } from "vitest";
+import { mapOcioColorSpaces, OcioConfigError, parseOcioConfig } from "./ocio-config";
+import { footageColorPresetSpace } from "./source-color";
+
+// Serialised by OpenColorIO 2.6 from its builtin config cg-config-v2.1.0_aces-v1.3_ocio-v2.3 (see scripts/aces-reference.py).
+const CG = readFileSync(new URL("./fixtures/cg-config-v2.1.0_aces-v1.3_ocio-v2.3.ocio", import.meta.url), "utf8");
+
+describe("OCIO config import: the builtin ACES 1.3 cg config", () => {
+ const config = parseOcioConfig(CG);
+ const mapping = mapOcioColorSpaces(config);
+
+ it("reads the version, roles and all 15 colour spaces with their aliases", () => {
+ expect(config.profileVersion).toBe("2.3");
+ expect(config.roles.scene_linear).toBe("ACEScg");
+ expect(config.roles.compositing_log).toBe("ACEScct");
+ expect(config.colorSpaces.map((c) => c.name)).toEqual([
+ "ACES2065-1", "ACEScc", "ACEScct", "ACEScg", "Linear P3-D65", "Linear Rec.2020", "Linear Rec.709 (sRGB)",
+ "Gamma 1.8 Rec.709 - Texture", "Gamma 2.2 AP1 - Texture", "Gamma 2.2 Rec.709 - Texture", "Gamma 2.4 Rec.709 - Texture",
+ "sRGB Encoded AP1 - Texture", "sRGB Encoded P3-D65 - Texture", "sRGB - Texture", "Raw",
+ ]);
+ const cct = config.colorSpaces.find((c) => c.name === "ACEScct")!;
+ expect(cct.aliases).toEqual(["ACES - ACEScct", "acescct_ap1"]);
+ expect(cct.builtinStyles).toEqual(["ACEScct_to_ACES2065-1"]);
+ expect(cct.transformKinds).toContain("BuiltinTransform");
+ expect(config.colorSpaces.find((c) => c.name === "Raw")!.isData).toBe(true);
+ });
+
+ it("maps the spaces that are one of the built-in analytic transforms", () => {
+ const byName = new Map(mapping.supported.map((s) => [s.name, s]));
+ expect(byName.get("ACEScg")).toMatchObject({ preset: "aces-acescg", via: "builtin-transform" });
+ expect(byName.get("ACEScct")).toMatchObject({ preset: "aces-acescct", via: "builtin-transform" });
+ expect(byName.get("ACES2065-1")).toMatchObject({ preset: "aces-aces2065", via: "name" });
+ expect(byName.get("sRGB - Texture")?.preset).toBe("srgb");
+ expect(byName.get("Linear Rec.709 (sRGB)")?.preset).toBe("linear-rec709");
+ expect(byName.get("Linear Rec.2020")?.preset).toBe("linear-rec2020");
+ expect(byName.get("Linear P3-D65")?.preset).toBe("linear-p3");
+ expect(byName.get("sRGB Encoded P3-D65 - Texture")?.preset).toBe("p3");
+ // Each mapped preset is a real Interpret Footage space.
+ for (const s of mapping.supported) expect(() => footageColorPresetSpace(s.preset)).not.toThrow();
+ });
+
+ it("reports every other space as unsupported, with a reason", () => {
+ const names = mapping.unsupported.map((u) => u.name);
+ expect(names).toEqual(["ACEScc", "Gamma 1.8 Rec.709 - Texture", "Gamma 2.2 AP1 - Texture", "Gamma 2.2 Rec.709 - Texture", "Gamma 2.4 Rec.709 - Texture", "sRGB Encoded AP1 - Texture", "Raw"]);
+ expect(mapping.supported.length + mapping.unsupported.length).toBe(15);
+ for (const u of mapping.unsupported) expect(u.reason.length).toBeGreaterThan(10);
+ expect(mapping.unsupported.find((u) => u.name === "Raw")!.reason).toMatch(/data/);
+ expect(mapping.unsupported.find((u) => u.name === "ACEScc")!.reason).toMatch(/ACEScc_to_ACES2065-1/);
+ });
+});
+
+const V1 = `ocio_profile_version: 1
+
+search_path: luts
+roles:
+ reference: lin
+ default: raw
+
+displays:
+ sRGB:
+ - !<View> {name: Film, colorspace: lin}
+
+colorspaces:
+ - !<ColorSpace>
+ name: lin
+ family: ""
+ equalitygroup: ""
+ bitdepth: 32f
+ isdata: false
+ allocation: uniform
+
+ - !<ColorSpace>
+ name: Input - ARRI - V3 LogC (EI800) - Wide Gamut
+ family: Input/ARRI
+ isdata: false
+ to_reference: !<GroupTransform>
+ children:
+ - !<FileTransform> {src: LogC_to_lin.spi1d, interpolation: linear}
+ - !<MatrixTransform> {matrix: [0.68, 0.24, 0.07, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1]}
+
+ - !<ColorSpace>
+ name: Camera Log One
+ aliases:
+ - cam_log_one
+ - "Sony Cam"
+ family: Camera
+ to_scene_reference: !<BuiltinTransform> {style: SONY_SLOG3-SGAMUT3.CINE_to_ACES2065-1}
+
+ - !<ColorSpace>
+ name: Graded Look
+ family: Look
+ to_reference: !<ExponentWithLinearTransform> {gamma: 2.4, offset: 0.055}
+
+ - !<ColorSpace>
+ name: raw
+ isdata: true
+`;
+
+describe("OCIO config import: a v1 style config", () => {
+ const mapping = mapOcioColorSpaces(parseOcioConfig(V1));
+
+ it("parses block lists, group transforms and inline tags", () => {
+ const config = parseOcioConfig(V1);
+ expect(config.profileVersion).toBe("1");
+ expect(config.colorSpaces.map((c) => c.name)).toEqual(["lin", "Input - ARRI - V3 LogC (EI800) - Wide Gamut", "Camera Log One", "Graded Look", "raw"]);
+ const cam = config.colorSpaces[2];
+ expect(cam.aliases).toEqual(["cam_log_one", "Sony Cam"]);
+ expect(config.colorSpaces[1].files).toEqual(["LogC_to_lin.spi1d"]);
+ expect(config.colorSpaces[1].transformKinds).toEqual(expect.arrayContaining(["GroupTransform", "FileTransform", "MatrixTransform"]));
+ });
+
+ it("maps by builtin style even when the space is renamed, and refuses LUT and parametric spaces with a reason", () => {
+ expect(mapping.supported).toEqual([{ name: "Camera Log One", preset: "log-slog3", via: "builtin-transform" }]);
+ // The ARRI name is well known, but this space carries its own LUT, so the name is not trusted.
+ const byName = new Map(mapping.unsupported.map((u) => [u.name, u.reason]));
+ expect(byName.get("Input - ARRI - V3 LogC (EI800) - Wide Gamut")).toMatch(/LogC_to_lin\.spi1d/);
+ expect(byName.get("Graded Look")).toMatch(/parametric/);
+ expect(byName.get("raw")).toMatch(/data/);
+ expect(byName.get("lin")).toMatch(/no transform/);
+ });
+});
+
+describe("OCIO config import: rejects what is not a config", () => {
+ it("throws OcioConfigError", () => {
+ expect(() => parseOcioConfig("hello world")).toThrow(OcioConfigError);
+ expect(() => parseOcioConfig("ocio_profile_version: 2\ncolorspaces:\n")).toThrow(/no colour spaces/);
+ expect(() => parseOcioConfig("x".repeat(9 * 1024 * 1024))).toThrow(/too large/);
+ });
+});
diff --git a/packages/core/src/color/ocio-config.ts b/packages/core/src/color/ocio-config.ts
new file mode 100644
index 00000000..5b45a4fb
--- /dev/null
+++ b/packages/core/src/color/ocio-config.ts
@@ -0,0 +1,305 @@
+import { FOOTAGE_COLOR_PRESETS, isFootageColorPreset, type FootageColorPreset } from "./source-color";
+
+/**
+ * OCIO configuration import, deliberately partial.
+ *
+ * OpenReel does not embed OpenColorIO. What it can do honestly is read an `.ocio` file's colour space list and tell the
+ * user which of those spaces are the same thing as one of the built-in analytic Interpret Footage presets (sRGB,
+ * Rec.709, linear Rec.709 / Rec.2020 / P3, ACEScg, ACES2065-1, ACEScct and the camera log curves), and which are not.
+ * Choosing a supported OCIO colour space applies the matching preset; it does not run the config's own transforms.
+ *
+ * A space is supported when either
+ * - its transforms are (or contain) an OCIO `BuiltinTransform` whose style is one of the known camera / ACES styles
+ * below (matched on the style, so a renamed colour space still maps), or
+ * - its name or an alias is one of the well-known names the ACES and "cg" reference configs use for these spaces
+ * and it carries no LUT of its own (a LUT-based space of the same name may be a different curve).
+ * Everything else is reported as unsupported with the reason (LUT files, parametric curves, data spaces, unknown names).
+ *
+ * The parser reads the subset of YAML OCIO writes: top level keys, `colorspaces:` entries introduced by
+ * `!<ColorSpace>`, scalar / inline-list / block-list properties, `|` block scalars and nested transforms. It does not
+ * resolve anchors, includes or search paths.
+ */
+
+export interface OcioColorSpace {
+ readonly name: string;
+ readonly aliases: readonly string[];
+ readonly family: string;
+ readonly isData: boolean;
+ /** Transform tags found in the space's to / from reference sections, e.g. "BuiltinTransform", "FileTransform". */
+ readonly transformKinds: readonly string[];
+ /** `style:` values of its BuiltinTransforms. */
+ readonly builtinStyles: readonly string[];
+ /** `src:` values of its FileTransforms (LUT files). */
+ readonly files: readonly string[];
+}
+
+export interface OcioConfigSummary {
+ readonly profileVersion: string | null;
+ readonly name: string | null;
+ readonly roles: Readonly<Record<string, string>>;
+ readonly colorSpaces: readonly OcioColorSpace[];
+}
+
+export interface OcioSupportedSpace {
+ readonly name: string;
+ readonly preset: FootageColorPreset;
+ readonly via: "builtin-transform" | "name";
+}
+
+export interface OcioUnsupportedSpace {
+ readonly name: string;
+ readonly reason: string;
+}
+
+export interface OcioMapping {
+ readonly supported: readonly OcioSupportedSpace[];
+ readonly unsupported: readonly OcioUnsupportedSpace[];
+}
+
+export class OcioConfigError extends Error {}
+
+const MAX_CONFIG_BYTES = 8 * 1024 * 1024;
+
+function unquote(value: string): string {
+ const v = value.trim();
+ if (v.length >= 2 && ((v.startsWith('"') && v.endsWith('"')) || (v.startsWith("'") && v.endsWith("'")))) return v.slice(1, -1);
+ return v;
+}
+
+function stripComment(line: string): string {
+ // A '#' starts a comment unless it is inside quotes. OCIO configs do not use '#' inside values otherwise.
+ let quote: string | null = null;
+ for (let i = 0; i < line.length; i++) {
+ const c = line[i];
+ if (quote) {
+ if (c === quote) quote = null;
+ } else if (c === '"' || c === "'") quote = c;
+ else if (c === "#" && (i === 0 || /\s/.test(line[i - 1]))) return line.slice(0, i);
+ }
+ return line;
+}
+
+function indentOf(line: string): number {
+ let n = 0;
+ while (n < line.length && line[n] === " ") n++;
+ return n;
+}
+
+function parseInlineList(value: string): string[] {
+ const inner = value.trim().replace(/^\[/, "").replace(/\]$/, "");
+ if (!inner.trim()) return [];
+ const out: string[] = [];
+ let current = "";
+ let quote: string | null = null;
+ for (const c of inner) {
+ if (quote) {
+ if (c === quote) quote = null;
+ else current += c;
+ } else if (c === '"' || c === "'") quote = c;
+ else if (c === ",") {
+ out.push(current.trim());
+ current = "";
+ } else current += c;
+ }
+ out.push(current.trim());
+ return out.filter((item) => item.length > 0);
+}
+
+interface Block {
+ readonly lines: string[];
+}
+
+/** Splits the `colorspaces:` section into one block of lines per `!<ColorSpace>` entry. */
+function colorSpaceBlocks(lines: readonly string[]): Block[] {
+ const start = lines.findIndex((l) => /^colorspaces\s*:\s*$/.test(l));
+ if (start < 0) return [];
+ const blocks: Block[] = [];
+ let current: string[] | null = null;
+ for (let i = start + 1; i < lines.length; i++) {
+ const line = lines[i];
+ if (line.trim() === "") continue;
+ // A new top-level key ends the section.
+ if (indentOf(line) === 0 && /^[A-Za-z_][\w-]*\s*:/.test(line)) break;
+ if (/^\s*-\s*!<(ColorSpace)>/.test(line) || /^\s*-\s*!ColorSpace\b/.test(line)) {
+ current = [line];
+ blocks.push({ lines: current });
+ } else if (current) current.push(line);
+ }
+ return blocks;
+}
+
+function parseColorSpace(block: Block): OcioColorSpace | null {
+ const lines = block.lines;
+ const entryIndent = indentOf(lines[0]);
+ // The entry's own properties sit one level deeper than the dash (or on the dash line, for "- !<ColorSpace> {…}" which OCIO does not write).
+ let name = "";
+ let family = "";
+ let isData = false;
+ let aliases: string[] = [];
+ const kinds = new Set<string>();
+ const styles: string[] = [];
+ const files: string[] = [];
+ let propIndent = -1;
+ for (let i = 1; i < lines.length; i++) {
+ const line = lines[i];
+ const indent = indentOf(line);
+ const text = line.trim();
+ if (propIndent < 0) propIndent = indent;
+ if (indent === propIndent) {
+ const m = /^([A-Za-z_][\w-]*)\s*:\s*(.*)$/.exec(text);
+ if (!m) continue;
+ const [, key, rawValue] = m;
+ const value = rawValue.trim();
+ if (key === "name") name = unquote(value);
+ else if (key === "family") family = unquote(value);
+ else if (key === "isdata") isData = /^(true|yes)$/i.test(value);
+ else if (key === "aliases") {
+ if (value.startsWith("[")) aliases = parseInlineList(value);
+ else if (value === "") {
+ // Block list on the following lines (YAML allows the dashes at the key's own indent).
+ for (let j = i + 1; j < lines.length; j++) {
+ if (lines[j].trim() === "") continue;
+ const item = /^(\s*)-\s*(.+)$/.exec(lines[j]);
+ if (!item || item[1].length < propIndent) break;
+ aliases.push(unquote(item[2]));
+ }
+ } else aliases = [unquote(value)];
+ }
+ }
+ // Transform tags and their parameters may sit anywhere under to_/from_ reference sections.
+ for (const tag of text.matchAll(/!<([A-Za-z]+)>/g)) kinds.add(tag[1]);
+ const style = /\bstyle\s*:\s*([^,}\s][^,}]*)/.exec(text);
+ if (style) styles.push(unquote(style[1]));
+ const src = /\bsrc\s*:\s*([^,}\s][^,}]*)/.exec(text);
+ if (src) files.push(unquote(src[1]));
+ }
+ void entryIndent;
+ if (!name) return null;
+ return { name, aliases, family, isData, transformKinds: [...kinds].filter((k) => k !== "ColorSpace"), builtinStyles: styles, files };
+}
+
+/** Reads the colour spaces, roles and version of an OCIO config. Throws `OcioConfigError` for text that is not a config. */
+export function parseOcioConfig(text: string): OcioConfigSummary {
+ if (text.length > MAX_CONFIG_BYTES) throw new OcioConfigError("The file is too large to be an OCIO config.");
+ const lines = text.replace(/\r\n?/g, "\n").split("\n").map(stripComment);
+ const version = lines.map((l) => /^ocio_profile_version\s*:\s*(.+)$/.exec(l)?.[1]).find(Boolean);
+ if (!version && !lines.some((l) => /^colorspaces\s*:/.test(l))) {
+ throw new OcioConfigError("This does not look like an OCIO config (no ocio_profile_version or colorspaces).");
+ }
+ const roles: Record<string, string> = {};
+ const rolesStart = lines.findIndex((l) => /^roles\s*:\s*$/.test(l));
+ if (rolesStart >= 0) {
+ for (let i = rolesStart + 1; i < lines.length; i++) {
+ const line = lines[i];
+ if (line.trim() === "") continue;
+ if (indentOf(line) === 0) break;
+ const m = /^\s+([\w-]+)\s*:\s*(.+)$/.exec(line);
+ if (m) roles[m[1]] = unquote(m[2]);
+ }
+ }
+ const name = lines.map((l) => /^name\s*:\s*(.+)$/.exec(l)?.[1]).find(Boolean);
+ const colorSpaces = colorSpaceBlocks(lines)
+ .map(parseColorSpace)
+ .filter((space): space is OcioColorSpace => space !== null);
+ if (colorSpaces.length === 0) throw new OcioConfigError("The config has no colour spaces.");
+ return { profileVersion: version ? unquote(version) : null, name: name ? unquote(name) : null, roles, colorSpaces };
+}
+
+// -- mapping to the built-in presets ----------------------------------------------------------------------------------
+
+/**
+ * OCIO BuiltinTransform styles (`ocio://` builtin list) that are exactly one of our presets. S-Gamut3 (not .Cine) is a different gamut from
+ * the preset's S-Gamut3.Cine, so it is not listed.
+ */
+const BUILTIN_STYLE_PRESETS: Readonly<Record<string, FootageColorPreset>> = {
+ "ACEScct_to_ACES2065-1": "aces-acescct",
+ "ACEScg_to_ACES2065-1": "aces-acescg",
+ "ARRI_ALEXA-LOGC-EI800-AWG_to_ACES2065-1": "log-logc3",
+ "ARRI_LOGC4_to_ACES2065-1": "log-logc4",
+ "CANON_CLOG3-CGAMUT_to_ACES2065-1": "log-clog3",
+ "PANASONIC_VLOG-VGAMUT_to_ACES2065-1": "log-vlog",
+ "SONY_SLOG3-SGAMUT3.CINE_to_ACES2065-1": "log-slog3",
+};
+
+function normalise(name: string): string {
+ return name.toLowerCase().replace(/[^a-z0-9]+/g, " ").trim();
+}
+
+/** Well-known colour space names of the ACES / "cg" reference configs (and OCIO v1 ACES configs), normalised. */
+const NAME_PRESETS: Readonly<Record<string, FootageColorPreset>> = {
+ "srgb": "srgb",
+ "srgb texture": "srgb",
+ "srgb encoded p3 d65 texture": "p3",
+ "srgb encoded display p3": "p3",
+ "utility srgb texture": "srgb",
+ "input generic srgb texture": "srgb",
+ "srgb encoded rec 709 srgb": "srgb",
+ "camera rec 709": "rec709",
+ "rec 709 camera": "rec709",
+ "input generic rec 709 camera": "rec709",
+ "rec709": "rec709",
+ "linear rec 709 srgb": "linear-rec709",
+ "linear rec 709": "linear-rec709",
+ "utility linear srgb": "linear-rec709",
+ "utility linear rec 709": "linear-rec709",
+ "lin rec709": "linear-rec709",
+ "linear rec 2020": "linear-rec2020",
+ "utility linear rec 2020": "linear-rec2020",
+ "lin rec2020": "linear-rec2020",
+ "linear p3 d65": "linear-p3",
+ "utility linear p3 d65": "linear-p3",
+ "lin p3d65": "linear-p3",
+ "rec 2100 pq": "hdr10-pq",
+ "st2084 p3 d65": "hdr10-pq",
+ "rec 2100 hlg": "hlg",
+ "acescg": "aces-acescg",
+ "aces cg": "aces-acescg",
+ "aces2065 1": "aces-aces2065",
+ "aces": "aces-aces2065",
+ "acescct": "aces-acescct",
+ "aces cct": "aces-acescct",
+ "arri logc3 awg3": "log-logc3",
+ "input arri v3 logc ei800 wide gamut": "log-logc3",
+ "arri logc4 awg4": "log-logc4",
+ "input arri logc4": "log-logc4",
+ "input sony s log3 s gamut3 cine": "log-slog3",
+ "s log3 s gamut3 cine": "log-slog3",
+ "input panasonic v log v gamut": "log-vlog",
+ "v log v gamut": "log-vlog",
+ "input canon canon log 3 cinema gamut": "log-clog3",
+ "canon log 3 cinema gamut": "log-clog3",
+};
+
+/** Maps an OCIO config's colour spaces onto the built-in presets, and says why the rest cannot be. */
+export function mapOcioColorSpaces(config: OcioConfigSummary): OcioMapping {
+ const supported: OcioSupportedSpace[] = [];
+ const unsupported: OcioUnsupportedSpace[] = [];
+ for (const space of config.colorSpaces) {
+ const byStyle = space.builtinStyles.map((style) => BUILTIN_STYLE_PRESETS[style]).find((p) => p !== undefined);
+ if (byStyle && isFootageColorPreset(byStyle)) {
+ supported.push({ name: space.name, preset: byStyle, via: "builtin-transform" });
+ continue;
+ }
+ // A name is only trusted when the space does not carry its own LUT: a LUT-based space of the same name may be a different curve.
+ const usesLut = space.files.length > 0 || space.transformKinds.includes("FileTransform");
+ const byName = usesLut ? undefined : [space.name, ...space.aliases].map((n) => NAME_PRESETS[normalise(n)]).find((p) => p !== undefined);
+ if (byName && isFootageColorPreset(byName) && FOOTAGE_COLOR_PRESETS.some((p) => p.id === byName)) {
+ supported.push({ name: space.name, preset: byName, via: "name" });
+ continue;
+ }
+ unsupported.push({ name: space.name, reason: unsupportedReason(space) });
+ }
+ return { supported, unsupported };
+}
+
+function unsupportedReason(space: OcioColorSpace): string {
+ if (space.isData) return "data colour space (no colour interpretation)";
+ if (space.files.length > 0) return `needs the LUT file ${space.files[0]}; LUT-based spaces are not evaluated`;
+ if (space.transformKinds.includes("FileTransform")) return "uses a file transform (LUT); not evaluated";
+ if (space.builtinStyles.length > 0) return `OCIO builtin ${space.builtinStyles[0]} has no matching Interpret Footage preset`;
+ if (space.transformKinds.some((k) => /Exponent|Log|Matrix|CDL|Fixed|Grading|Range|Allocation/.test(k))) {
+ return `parametric ${space.transformKinds.join(" / ")} transform with no matching built-in preset`;
+ }
+ if (space.transformKinds.length === 0) return "no transform and no recognised name (a reference-like or display space)";
+ return "no matching built-in analytic transform";
+}
diff --git a/packages/core/src/color/source-color.ts b/packages/core/src/color/source-color.ts
index 9f7d7dcc..3c4b869c 100644
--- a/packages/core/src/color/source-color.ts
+++ b/packages/core/src/color/source-color.ts
@@ -11,7 +11,7 @@ import type { RawOutputColorSpace } from "../raw/color";
import { CAMERA_LOGS, type CameraGamutId, type CameraLogId } from "./camera-log";
export type SourcePrimaries = "bt709" | "bt2020" | "p3" | "bt601" | Exclude<CameraGamutId, "bt2020">;
-export type SourceTransfer = "srgb" | "bt709" | "pq" | "hlg" | "linear" | CameraLogId;
+export type SourceTransfer = "srgb" | "bt709" | "pq" | "hlg" | "linear" | "acescct" | CameraLogId;
export type SourceMatrix = "bt709" | "bt2020-ncl" | "bt601" | "rgb";
export interface SourceColorSpace {
@@ -31,9 +31,17 @@ export const DEFAULT_SOURCE_COLOR: SourceColorSpace = {
/** "Interpret footage" choices. `undefined` on the media item means "as tagged". */
export type StandardFootageColorPreset = "rec709" | "srgb" | "rec2020" | "p3" | "hdr10-pq" | "hlg";
+/** ACES-native footage: ACEScg (linear AP1), ACES2065-1 (linear AP0, e.g. EXR), ACEScct (log AP1, e.g. from a grading round trip). */
+export type AcesFootageColorPreset =
+ | "aces-acescg"
+ | "aces-aces2065"
+ | "aces-acescct"
+ | "linear-rec709"
+ | "linear-rec2020"
+ | "linear-p3";
/** Camera log input presets: "log-" + the curve id ("log-slog3", "log-logc4", ...). */
export type CameraFootageColorPreset = `log-${CameraLogId}`;
-export type FootageColorPreset = StandardFootageColorPreset | CameraFootageColorPreset;
+export type FootageColorPreset = StandardFootageColorPreset | AcesFootageColorPreset | CameraFootageColorPreset;
export interface FootageColorPresetDef {
readonly id: FootageColorPreset;
@@ -41,6 +49,8 @@ export interface FootageColorPresetDef {
readonly space: SourceColorSpace;
/** Set on camera log presets: the picker groups them under "Camera input". */
readonly camera?: { readonly logId: CameraLogId; readonly maker: string };
+ /** Set on the scene-linear / ACES presets: the picker groups them under "ACES and linear". */
+ readonly aces?: true;
}
const STANDARD_FOOTAGE_COLOR_PRESETS: ReadonlyArray<FootageColorPresetDef> = [
@@ -52,6 +62,19 @@ const STANDARD_FOOTAGE_COLOR_PRESETS: ReadonlyArray<FootageColorPresetDef> = [
{ id: "hlg", label: "Rec.2020 HLG", space: { primaries: "bt2020", transfer: "hlg", matrix: "bt2020-ncl", fullRange: false } },
];
+/**
+ * Scene-linear input spaces: ACES-native pixels (ACEScg, ACES2065-1, ACEScct) and plain linear light in the common
+ * primaries (what a linear EXR / 32-bit export carries). Full range RGB, no matrix; 1.0 is SDR reference white.
+ */
+export const ACES_FOOTAGE_COLOR_PRESETS: ReadonlyArray<FootageColorPresetDef> = [
+ { id: "aces-acescg", label: "ACEScg (linear AP1)", space: { primaries: "ap1", transfer: "linear", matrix: "rgb", fullRange: true }, aces: true },
+ { id: "aces-aces2065", label: "ACES2065-1 (linear AP0)", space: { primaries: "ap0", transfer: "linear", matrix: "rgb", fullRange: true }, aces: true },
+ { id: "aces-acescct", label: "ACEScct (log AP1)", space: { primaries: "ap1", transfer: "acescct", matrix: "rgb", fullRange: true }, aces: true },
+ { id: "linear-rec709", label: "Linear Rec.709", space: { primaries: "bt709", transfer: "linear", matrix: "rgb", fullRange: true }, aces: true },
+ { id: "linear-rec2020", label: "Linear Rec.2020", space: { primaries: "bt2020", transfer: "linear", matrix: "rgb", fullRange: true }, aces: true },
+ { id: "linear-p3", label: "Linear Display P3", space: { primaries: "p3", transfer: "linear", matrix: "rgb", fullRange: true }, aces: true },
+];
+
/**
* Camera log presets: the signal is the camera's log curve in its wide gamut (RGB after the decoder's YCbCr
* conversion, so the matrix is "rgb" and the range is whatever the decoder delivered).
@@ -70,6 +93,7 @@ export const CAMERA_FOOTAGE_COLOR_PRESETS: ReadonlyArray<FootageColorPresetDef>
export const FOOTAGE_COLOR_PRESETS: ReadonlyArray<FootageColorPresetDef> = [
...STANDARD_FOOTAGE_COLOR_PRESETS,
+ ...ACES_FOOTAGE_COLOR_PRESETS,
...CAMERA_FOOTAGE_COLOR_PRESETS,
];
@@ -163,6 +187,7 @@ export function needsInputTransform(space: SourceColorSpace): boolean {
space.primaries === "bt2020" ||
space.primaries === "p3" ||
space.transfer === "linear" ||
+ space.transfer === "acescct" ||
isCameraLogTransfer(space.transfer)
);
}
@@ -176,8 +201,8 @@ export function describeSourceColor(space: SourceColorSpace | null | undefined):
if (!space) return "Rec.709 (untagged)";
const camera = CAMERA_LOGS.find((d) => d.id === space.transfer);
if (camera) return camera.label;
- const primaries = ({ bt709: "Rec.709", bt2020: "Rec.2020", p3: "P3", bt601: "BT.601" } as Record<string, string>)[space.primaries] ?? space.primaries;
- const transfer = ({ srgb: "sRGB", bt709: "BT.709", pq: "PQ", hlg: "HLG", linear: "Linear" } as Record<string, string>)[space.transfer] ?? space.transfer;
+ const primaries = ({ bt709: "Rec.709", bt2020: "Rec.2020", p3: "P3", bt601: "BT.601", ap1: "ACES AP1", ap0: "ACES AP0" } as Record<string, string>)[space.primaries] ?? space.primaries;
+ const transfer = ({ srgb: "sRGB", bt709: "BT.709", pq: "PQ", hlg: "HLG", linear: "Linear", acescct: "ACEScct" } as Record<string, string>)[space.transfer] ?? space.transfer;
const matrix = { bt709: "BT.709", "bt2020-ncl": "BT.2020nc", bt601: "BT.601", rgb: "RGB" }[space.matrix];
return `${primaries} / ${transfer} / ${matrix} / ${space.fullRange ? "full" : "limited"}`;
}
@@ -197,8 +222,12 @@ export function rawOutputSourceSpace(output: RawOutputColorSpace): SourceColorSp
return { primaries, transfer: "srgb", matrix: "rgb", fullRange: true };
}
-/** What the footage is, after the user's override: tags, else the Rec.709 default. */
-export function effectiveSourceColor(item: FootageColorSource): SourceColorSpace {
+/**
+ * What the footage is, after the user's override: tags, else the Rec.709 default. `clipOverride` is the timeline clip's own
+ * Interpret Footage preset (`Clip.colorInterpretation`); it wins over the footage item's.
+ */
+export function effectiveSourceColor(item: FootageColorSource, clipOverride?: FootageColorPreset | null): SourceColorSpace {
+ if (clipOverride && isFootageColorPreset(clipOverride)) return footageColorPresetSpace(clipOverride);
if (item.colorInterpretation && isFootageColorPreset(item.colorInterpretation)) {
return footageColorPresetSpace(item.colorInterpretation);
}
@@ -219,14 +248,14 @@ export function effectiveSourceColor(item: FootageColorSource): SourceColorSpace
* - Desktop native (ffmpeg) decode: frames are raw RGBA codes in the
* source's own transfer and primaries, so the file's tags apply too.
*/
-export function inputSpaceForItem(item: FootageColorSource): SourceColorSpace | null {
+export function inputSpaceForItem(item: FootageColorSource, clipOverride?: FootageColorPreset | null): SourceColorSpace | null {
// RAW stills are developed by OpenReel into the chosen output primaries, whatever the decode path.
if (item.raw?.developedBy === "openreel" && item.raw.settings) {
const space = rawOutputSourceSpace(item.raw.settings.outputColorSpace);
return needsInputTransform(space) ? space : null;
}
- const override = !!item.colorInterpretation && isFootageColorPreset(item.colorInterpretation);
+ const override = (!!clipOverride && isFootageColorPreset(clipOverride)) || (!!item.colorInterpretation && isFootageColorPreset(item.colorInterpretation));
if (!override && !item.nativeSource) return null;
- const space = effectiveSourceColor(item);
+ const space = effectiveSourceColor(item, clipOverride);
return needsInputTransform(space) ? space : null;
}
diff --git a/packages/core/src/export/color-output.ts b/packages/core/src/export/color-output.ts
index b50e4335..21154133 100644
--- a/packages/core/src/export/color-output.ts
+++ b/packages/core/src/export/color-output.ts
@@ -85,9 +85,12 @@ export function toVideoColorSpace(spec: OutputColorSpec): OutputVideoColorSpace
}
export function outputColorForExport(
- project: { settings: Pick<ProjectSettings, "workingColorSpace"> },
+ project: { settings: Pick<ProjectSettings, "workingColorSpace"> & Partial<Pick<ProjectSettings, "colorManagement">> },
hdr: HdrTransfer | undefined,
): OutputColorSpec | null {
+ // ACES mode: an SDR export is the Output Transform's own display encoding (sRGB / Rec.709, 8-bit canvas path), so the
+ // Rec.2020 working-space tagging does not apply; HDR exports keep their PQ / HLG Rec.2020 spec.
+ if (project.settings.colorManagement === "aces" && hdr !== "pq" && hdr !== "hlg") return null;
return resolveOutputColorSpec(resolveWorkingColorSpace(project.settings), hdr);
}
diff --git a/packages/core/src/index.ts b/packages/core/src/index.ts
index fff668dd..3029abe5 100644
--- a/packages/core/src/index.ts
+++ b/packages/core/src/index.ts
@@ -54,6 +54,8 @@ export * from "./color/looks";
export * from "./color/input-transform";
export * from "./color/camera-log";
export * from "./color/hdr-working";
+export * from "./color/aces";
+export * from "./color/ocio-config";
export * from "./color/hdr-effects";
export * from "./color/hdr-light-level";
export { planHdrTransition, isHdrTransitionKind, type HdrTransitionStep, type HdrTransitionKind } from "./video/hdr-transition";
diff --git a/packages/core/src/interchange/__fixtures__/main-cut.prproj b/packages/core/src/interchange/__fixtures__/main-cut.prproj
new file mode 100644
index 00000000..239be75d
Binary files /dev/null and b/packages/core/src/interchange/__fixtures__/main-cut.prproj differ
diff --git a/packages/core/src/interchange/__fixtures__/main-cut.prproj.xml b/packages/core/src/interchange/__fixtures__/main-cut.prproj.xml
new file mode 100644
index 00000000..416c0e36
--- /dev/null
+++ b/packages/core/src/interchange/__fixtures__/main-cut.prproj.xml
@@ -0,0 +1,699 @@
+<?xml version="1.0" encoding="UTF-8" ?>
+<PremiereData Version="3">
+<Media ObjectUID="aaaaaaaa-0000-4000-8000-000000000001" ClassID="7a78f4f1-ca6b-4fd5-a8c8-87a6a8b1c0c7" Version="31">
+ <ImplementationID>00000000-0000-0000-0000-000000000000</ImplementationID>
+ <FilePath>/Volumes/Shoot/Day1/interview.mp4</FilePath>
+ <ActualMediaFilePath>/Volumes/Shoot/Day1/interview.mp4</ActualMediaFilePath>
+ <Title>interview.mp4</Title>
+ <VideoStream ObjectRef="101"/>
+ <AudioStream ObjectRef="102"/>
+</Media>
+<VideoStream ObjectID="101" ClassID="a2f2f1c0-1b7f-4a5c-8c55-0f2f5b9c7d11" Version="3">
+ <FrameRate>8475667200</FrameRate>
+ <FrameRect>0,0,1920,1080</FrameRect>
+</VideoStream>
+<AudioStream ObjectID="102" ClassID="b3c3f2d1-2c80-4b6d-9d66-1a3a6c0d8e22" Version="2">
+ <SampleRate>48000</SampleRate>
+ <NumChannels>2</NumChannels>
+</AudioStream>
+<Media ObjectUID="aaaaaaaa-0000-4000-8000-000000000002" ClassID="7a78f4f1-ca6b-4fd5-a8c8-87a6a8b1c0c7" Version="31">
+ <ImplementationID>00000000-0000-0000-0000-000000000000</ImplementationID>
+ <FilePath>/Volumes/Shoot/Day1/broll.mov</FilePath>
+ <ActualMediaFilePath>/Volumes/Shoot/Day1/broll.mov</ActualMediaFilePath>
+ <Title>broll.mov</Title>
+ <VideoStream ObjectRef="103"/>
+</Media>
+<VideoStream ObjectID="103" ClassID="a2f2f1c0-1b7f-4a5c-8c55-0f2f5b9c7d11" Version="3">
+ <FrameRate>10160640000</FrameRate>
+ <FrameRect>0,0,3840,2160</FrameRect>
+</VideoStream>
+<Media ObjectUID="aaaaaaaa-0000-4000-8000-000000000003" ClassID="7a78f4f1-ca6b-4fd5-a8c8-87a6a8b1c0c7" Version="31">
+ <ImplementationID>00000000-0000-0000-0000-000000000000</ImplementationID>
+ <FilePath>C:\Music\theme song.wav</FilePath>
+ <ActualMediaFilePath>C:\Music\theme song.wav</ActualMediaFilePath>
+ <Title>theme song.wav</Title>
+ <AudioStream ObjectRef="104"/>
+</Media>
+<AudioStream ObjectID="104" ClassID="b3c3f2d1-2c80-4b6d-9d66-1a3a6c0d8e22" Version="2">
+ <SampleRate>48000</SampleRate>
+ <NumChannels>2</NumChannels>
+</AudioStream>
+<Media ObjectUID="aaaaaaaa-0000-4000-8000-000000000004" ClassID="7a78f4f1-ca6b-4fd5-a8c8-87a6a8b1c0c7" Version="31">
+ <ImplementationID>00000000-0000-0000-0000-000000000000</ImplementationID>
+ <FilePath>/Volumes/Shoot/Graphics/overlay.png</FilePath>
+ <ActualMediaFilePath>/Volumes/Shoot/Graphics/overlay.png</ActualMediaFilePath>
+ <Title>overlay.png</Title>
+ <VideoStream ObjectRef="105"/>
+</Media>
+<VideoStream ObjectID="105" ClassID="a2f2f1c0-1b7f-4a5c-8c55-0f2f5b9c7d11" Version="3">
+ <FrameRate>10160640000</FrameRate>
+ <FrameRect>0,0,1280,720</FrameRect>
+</VideoStream>
+<VideoMediaSource ObjectID="106" ClassID="e64ddf70-d1d1-4c0e-9e37-6e6aa1cbd3a6" Version="2">
+ <MediaSource Version="4">
+ <Media ObjectURef="aaaaaaaa-0000-4000-8000-000000000001"/>
+ <OriginalDuration>15240960000000</OriginalDuration>
+ </MediaSource>
+</VideoMediaSource>
+<VideoClip ObjectID="107" ClassID="9308dbef-2440-4acb-9ab2-953b9a4e82ec" Version="3">
+ <Clip Version="18">
+ <Source ObjectRef="106"/>
+ <InPoint>0</InPoint>
+ <OutPoint>15240960000000</OutPoint>
+ </Clip>
+ <FrameRect>0,0,1920,1080</FrameRect>
+</VideoClip>
+<AudioMediaSource ObjectID="108" ClassID="e64ddf70-d1d1-4c0e-9e37-6e6aa1cbd3a6" Version="2">
+ <MediaSource Version="4">
+ <Media ObjectURef="aaaaaaaa-0000-4000-8000-000000000001"/>
+ <OriginalDuration>15240960000000</OriginalDuration>
+ </MediaSource>
+</AudioMediaSource>
+<AudioClip ObjectID="109" ClassID="9308dbef-2440-4acb-9ab2-953b9a4e82ec" Version="3">
+ <Clip Version="18">
+ <Source ObjectRef="108"/>
+ <InPoint>0</InPoint>
+ <OutPoint>15240960000000</OutPoint>
+ </Clip>
+</AudioClip>
+<MasterClip ObjectUID="bbbbbbbb-0000-4000-8000-000000000001" ClassID="fb11c33a-b0a3-4d5f-9a6a-8b1b8a1d0a5a" Version="12">
+ <Clips Version="1">
+ <Clip Index="0" ObjectRef="107"/>
+ <Clip Index="1" ObjectRef="109"/>
+ </Clips>
+ <Name>interview.mp4</Name>
+</MasterClip>
+<ClipProjectItem ObjectUID="cccccccc-0000-4000-8000-000000000001" ClassID="cb4e0ed7-aca1-4f8a-b5f5-0ca8a9a1b3f7" Version="1">
+ <ProjectItem Version="1"><Name>interview.mp4</Name></ProjectItem>
+ <MasterClip ObjectURef="bbbbbbbb-0000-4000-8000-000000000001"/>
+</ClipProjectItem>
+<VideoMediaSource ObjectID="110" ClassID="e64ddf70-d1d1-4c0e-9e37-6e6aa1cbd3a6" Version="2">
+ <MediaSource Version="4">
+ <Media ObjectURef="aaaaaaaa-0000-4000-8000-000000000002"/>
+ <OriginalDuration>7620480000000</OriginalDuration>
+ </MediaSource>
+</VideoMediaSource>
+<VideoClip ObjectID="111" ClassID="9308dbef-2440-4acb-9ab2-953b9a4e82ec" Version="3">
+ <Clip Version="18">
+ <Source ObjectRef="110"/>
+ <InPoint>0</InPoint>
+ <OutPoint>7620480000000</OutPoint>
+ </Clip>
+ <FrameRect>0,0,3840,2160</FrameRect>
+</VideoClip>
+<MasterClip ObjectUID="bbbbbbbb-0000-4000-8000-000000000002" ClassID="fb11c33a-b0a3-4d5f-9a6a-8b1b8a1d0a5a" Version="12">
+ <Clips Version="1">
+ <Clip Index="0" ObjectRef="111"/>
+ </Clips>
+ <Name>broll.mov</Name>
+</MasterClip>
+<ClipProjectItem ObjectUID="cccccccc-0000-4000-8000-000000000002" ClassID="cb4e0ed7-aca1-4f8a-b5f5-0ca8a9a1b3f7" Version="1">
+ <ProjectItem Version="1"><Name>broll.mov</Name></ProjectItem>
+ <MasterClip ObjectURef="bbbbbbbb-0000-4000-8000-000000000002"/>
+</ClipProjectItem>
+<AudioMediaSource ObjectID="112" ClassID="e64ddf70-d1d1-4c0e-9e37-6e6aa1cbd3a6" Version="2">
+ <MediaSource Version="4">
+ <Media ObjectURef="aaaaaaaa-0000-4000-8000-000000000003"/>
+ <OriginalDuration>45722880000000</OriginalDuration>
+ </MediaSource>
+</AudioMediaSource>
+<AudioClip ObjectID="113" ClassID="9308dbef-2440-4acb-9ab2-953b9a4e82ec" Version="3">
+ <Clip Version="18">
+ <Source ObjectRef="112"/>
+ <InPoint>0</InPoint>
+ <OutPoint>45722880000000</OutPoint>
+ </Clip>
+</AudioClip>
+<MasterClip ObjectUID="bbbbbbbb-0000-4000-8000-000000000003" ClassID="fb11c33a-b0a3-4d5f-9a6a-8b1b8a1d0a5a" Version="12">
+ <Clips Version="1">
+ <Clip Index="0" ObjectRef="113"/>
+ </Clips>
+ <Name>theme song.wav</Name>
+</MasterClip>
+<ClipProjectItem ObjectUID="cccccccc-0000-4000-8000-000000000003" ClassID="cb4e0ed7-aca1-4f8a-b5f5-0ca8a9a1b3f7" Version="1">
+ <ProjectItem Version="1"><Name>theme song.wav</Name></ProjectItem>
+ <MasterClip ObjectURef="bbbbbbbb-0000-4000-8000-000000000003"/>
+</ClipProjectItem>
+<VideoMediaSource ObjectID="114" ClassID="e64ddf70-d1d1-4c0e-9e37-6e6aa1cbd3a6" Version="2">
+ <MediaSource Version="4">
+ <Media ObjectURef="aaaaaaaa-0000-4000-8000-000000000004"/>
+ <OriginalDuration>1270080000000</OriginalDuration>
+ </MediaSource>
+</VideoMediaSource>
+<VideoClip ObjectID="115" ClassID="9308dbef-2440-4acb-9ab2-953b9a4e82ec" Version="3">
+ <Clip Version="18">
+ <Source ObjectRef="114"/>
+ <InPoint>0</InPoint>
+ <OutPoint>1270080000000</OutPoint>
+ </Clip>
+ <FrameRect>0,0,1280,720</FrameRect>
+</VideoClip>
+<MasterClip ObjectUID="bbbbbbbb-0000-4000-8000-000000000004" ClassID="fb11c33a-b0a3-4d5f-9a6a-8b1b8a1d0a5a" Version="12">
+ <Clips Version="1">
+ <Clip Index="0" ObjectRef="115"/>
+ </Clips>
+ <Name>overlay.png</Name>
+</MasterClip>
+<ClipProjectItem ObjectUID="cccccccc-0000-4000-8000-000000000004" ClassID="cb4e0ed7-aca1-4f8a-b5f5-0ca8a9a1b3f7" Version="1">
+ <ProjectItem Version="1"><Name>overlay.png</Name></ProjectItem>
+ <MasterClip ObjectURef="bbbbbbbb-0000-4000-8000-000000000004"/>
+</ClipProjectItem>
+<BinProjectItem ObjectUID="dddddddd-0000-4000-8000-000000000001" ClassID="dbfd21a6-b6d3-4b6a-a4a0-0e8d6c6b1d33" Version="1">
+ <ProjectItemContainer Version="1"><Items Version="1">
+ <Item Index="0" ObjectURef="cccccccc-0000-4000-8000-000000000004"/>
+ </Items></ProjectItemContainer>
+ <ProjectItem Version="1"><Name>Graphics</Name></ProjectItem>
+</BinProjectItem>
+<BinProjectItem ObjectUID="dddddddd-0000-4000-8000-000000000002" ClassID="dbfd21a6-b6d3-4b6a-a4a0-0e8d6c6b1d33" Version="1">
+ <ProjectItemContainer Version="1"><Items Version="1">
+ <Item Index="0" ObjectURef="cccccccc-0000-4000-8000-000000000001"/>
+ <Item Index="1" ObjectURef="cccccccc-0000-4000-8000-000000000002"/>
+ <Item Index="2" ObjectURef="dddddddd-0000-4000-8000-000000000001"/>
+ </Items></ProjectItemContainer>
+ <ProjectItem Version="1"><Name>Footage</Name></ProjectItem>
+</BinProjectItem>
+<BinProjectItem ObjectUID="dddddddd-0000-4000-8000-000000000003" ClassID="dbfd21a6-b6d3-4b6a-a4a0-0e8d6c6b1d33" Version="1">
+ <ProjectItemContainer Version="1"><Items Version="1">
+ <Item Index="0" ObjectURef="cccccccc-0000-4000-8000-000000000003"/>
+ </Items></ProjectItemContainer>
+ <ProjectItem Version="1"><Name>Audio</Name></ProjectItem>
+</BinProjectItem>
+<VideoComponentParam ObjectID="116" ClassID="a8f0a3e5-57a1-4e8e-8a3a-9e0f8f2a9a44" Version="7">
+ <Name>Position</Name>
+ <CurrentValue>0.5:0.5</CurrentValue>
+</VideoComponentParam>
+<VideoComponentParam ObjectID="117" ClassID="a8f0a3e5-57a1-4e8e-8a3a-9e0f8f2a9a44" Version="7">
+ <Name>Scale</Name>
+ <CurrentValue>100</CurrentValue>
+</VideoComponentParam>
+<VideoComponentParam ObjectID="118" ClassID="a8f0a3e5-57a1-4e8e-8a3a-9e0f8f2a9a44" Version="7">
+ <Name>Rotation</Name>
+ <CurrentValue>0</CurrentValue>
+</VideoComponentParam>
+<VideoFilterComponent ObjectID="119" ClassID="0970b8ba-3d9f-4c4a-8a3c-3a64cf6a7b55" Version="9">
+ <Component Version="7"><Params Version="1">
+ <Param Index="0" ObjectRef="116"/>
+ <Param Index="1" ObjectRef="117"/>
+ <Param Index="2" ObjectRef="118"/>
+ </Params></Component>
+ <MatchName>AE.ADBE Motion</MatchName>
+ <DisplayName>Motion</DisplayName>
+</VideoFilterComponent>
+<VideoClip ObjectID="120" ClassID="9308dbef-2440-4acb-9ab2-953b9a4e82ec" Version="3">
+ <Clip Version="18"><Source ObjectRef="110"/><InPoint>254016000000</InPoint><OutPoint>1016064000000</OutPoint></Clip>
+</VideoClip>
+<SubClip ObjectID="121" ClassID="e0c6bd4a-5f55-4a76-9bd8-6f0d3a1c2e99" Version="5">
+ <Clip ObjectRef="120"/>
+ <MasterClip ObjectURef="bbbbbbbb-0000-4000-8000-000000000002"/>
+ <Name>broll.mov</Name>
+</SubClip>
+<VideoComponentChain ObjectID="122" ClassID="0d6e4a9d-4b5c-4d0e-8f9a-6a7b8c9d0e1f" Version="3">
+ <ComponentChain Version="3"><Components Version="1">
+ <Component Index="0" ObjectRef="119"/>
+ </Components></ComponentChain>
+</VideoComponentChain>
+<VideoClipTrackItem ObjectID="123" ClassID="368b0d13-5e1c-4b0f-a9a2-5d7f3e0c1b77" Version="8">
+ <ClipTrackItem Version="8">
+ <ComponentOwner Version="1"><Components ObjectRef="122"/></ComponentOwner>
+ <SubClip ObjectRef="121"/>
+ <TrackItem Version="4">
+ <Start>0</Start>
+ <End>762048000000</End>
+ </TrackItem>
+ </ClipTrackItem>
+</VideoClipTrackItem>
+<VideoClipTrack ObjectUID="eeeeeeee-0000-4000-8000-000000000001" ClassID="e2b8bcd1-8f2d-4a6e-b1d8-7a1f2c3d4e55" Version="5">
+ <ClipTrack Version="3">
+ <Track Version="4"><ID>1</ID><Index>0</Index></Track>
+ <ClipItems Version="3"><TrackItems Version="1">
+ <TrackItem Index="0" ObjectRef="123"/>
+ </TrackItems></ClipItems>
+ </ClipTrack>
+</VideoClipTrack>
+<VideoTrackGroup ObjectID="124" ClassID="f1e2d3c4-b5a6-4978-8a9b-0c1d2e3f4a5b" Version="9">
+ <TrackGroup Version="1">
+ <Tracks Version="1">
+ <Track Index="0" ObjectURef="eeeeeeee-0000-4000-8000-000000000001"/>
+ </Tracks>
+ <FrameRect>0,0,1920,1080</FrameRect>
+ <FrameRate>10160640000</FrameRate>
+ </TrackGroup>
+</VideoTrackGroup>
+<Sequence ObjectUID="ffffffff-0000-4000-8000-000000000003" ClassID="6a15d903-8739-11d5-af2d-9b7855ad8974" Version="1">
+ <Node Version="1"><Properties Version="1"/></Node>
+ <TrackGroups Version="1">
+ <TrackGroup Version="1" Index="0"><First>0</First><Second ObjectRef="124"/></TrackGroup>
+ </TrackGroups>
+ <Name>Lower Third Nest</Name>
+</Sequence>
+<VideoClip ObjectID="125" ClassID="9308dbef-2440-4acb-9ab2-953b9a4e82ec" Version="3">
+ <Clip Version="18"><Source ObjectRef="106"/><InPoint>0</InPoint><OutPoint>508032000000</OutPoint></Clip>
+</VideoClip>
+<SubClip ObjectID="126" ClassID="e0c6bd4a-5f55-4a76-9bd8-6f0d3a1c2e99" Version="5">
+ <Clip ObjectRef="125"/>
+ <MasterClip ObjectURef="bbbbbbbb-0000-4000-8000-000000000001"/>
+ <Name>interview.mp4</Name>
+</SubClip>
+<VideoClipTrackItem ObjectID="127" ClassID="368b0d13-5e1c-4b0f-a9a2-5d7f3e0c1b77" Version="8">
+ <ClipTrackItem Version="8">
+ <SubClip ObjectRef="126"/>
+ <TrackItem Version="4">
+ <Start>0</Start>
+ <End>508032000000</End>
+ </TrackItem>
+ </ClipTrackItem>
+</VideoClipTrackItem>
+<VideoClipTrack ObjectUID="eeeeeeee-0000-4000-8000-000000000002" ClassID="e2b8bcd1-8f2d-4a6e-b1d8-7a1f2c3d4e55" Version="5">
+ <ClipTrack Version="3">
+ <Track Version="4"><ID>1</ID><Index>0</Index></Track>
+ <ClipItems Version="3"><TrackItems Version="1">
+ <TrackItem Index="0" ObjectRef="127"/>
+ </TrackItems></ClipItems>
+ </ClipTrack>
+</VideoClipTrack>
+<VideoTrackGroup ObjectID="128" ClassID="f1e2d3c4-b5a6-4978-8a9b-0c1d2e3f4a5b" Version="9">
+ <TrackGroup Version="1">
+ <Tracks Version="1">
+ <Track Index="0" ObjectURef="eeeeeeee-0000-4000-8000-000000000002"/>
+ </Tracks>
+ <FrameRect>0,0,1920,1080</FrameRect>
+ <FrameRate>8475667200</FrameRate>
+ </TrackGroup>
+</VideoTrackGroup>
+<Sequence ObjectUID="ffffffff-0000-4000-8000-000000000002" ClassID="6a15d903-8739-11d5-af2d-9b7855ad8974" Version="1">
+ <Node Version="1"><Properties Version="1"/></Node>
+ <TrackGroups Version="1">
+ <TrackGroup Version="1" Index="0"><First>0</First><Second ObjectRef="128"/></TrackGroup>
+ </TrackGroups>
+ <Name>Alt Cut</Name>
+</Sequence>
+<VideoComponentParam ObjectID="129" ClassID="a8f0a3e5-57a1-4e8e-8a3a-9e0f8f2a9a44" Version="7">
+ <Name>Position</Name>
+ <CurrentValue>0.5:0.5</CurrentValue>
+</VideoComponentParam>
+<VideoComponentParam ObjectID="130" ClassID="a8f0a3e5-57a1-4e8e-8a3a-9e0f8f2a9a44" Version="7">
+ <Name>Scale</Name>
+ <CurrentValue>100</CurrentValue>
+</VideoComponentParam>
+<VideoComponentParam ObjectID="131" ClassID="a8f0a3e5-57a1-4e8e-8a3a-9e0f8f2a9a44" Version="7">
+ <Name>Rotation</Name>
+ <CurrentValue>0</CurrentValue>
+</VideoComponentParam>
+<VideoFilterComponent ObjectID="132" ClassID="0970b8ba-3d9f-4c4a-8a3c-3a64cf6a7b55" Version="9">
+ <Component Version="7"><Params Version="1">
+ <Param Index="0" ObjectRef="129"/>
+ <Param Index="1" ObjectRef="130"/>
+ <Param Index="2" ObjectRef="131"/>
+ </Params></Component>
+ <MatchName>AE.ADBE Motion</MatchName>
+ <DisplayName>Motion</DisplayName>
+</VideoFilterComponent>
+<VideoComponentParam ObjectID="133" ClassID="a8f0a3e5-57a1-4e8e-8a3a-9e0f8f2a9a44" Version="7">
+ <Name>Opacity</Name>
+ <CurrentValue>100</CurrentValue>
+</VideoComponentParam>
+<VideoFilterComponent ObjectID="134" ClassID="0970b8ba-3d9f-4c4a-8a3c-3a64cf6a7b55" Version="9">
+ <Component Version="7"><Params Version="1">
+ <Param Index="0" ObjectRef="133"/>
+ </Params></Component>
+ <MatchName>AE.ADBE Opacity</MatchName>
+ <DisplayName>Opacity</DisplayName>
+</VideoFilterComponent>
+<VideoClip ObjectID="135" ClassID="9308dbef-2440-4acb-9ab2-953b9a4e82ec" Version="3">
+ <Clip Version="18"><Source ObjectRef="106"/><InPoint>508032000000</InPoint><OutPoint>1778112000000</OutPoint></Clip>
+</VideoClip>
+<SubClip ObjectID="136" ClassID="e0c6bd4a-5f55-4a76-9bd8-6f0d3a1c2e99" Version="5">
+ <Clip ObjectRef="135"/>
+ <MasterClip ObjectURef="bbbbbbbb-0000-4000-8000-000000000001"/>
+ <Name>interview.mp4</Name>
+</SubClip>
+<VideoComponentChain ObjectID="137" ClassID="0d6e4a9d-4b5c-4d0e-8f9a-6a7b8c9d0e1f" Version="3">
+ <ComponentChain Version="3"><Components Version="1">
+ <Component Index="0" ObjectRef="132"/>
+ <Component Index="1" ObjectRef="134"/>
+ </Components></ComponentChain>
+</VideoComponentChain>
+<VideoClipTrackItem ObjectID="138" ClassID="368b0d13-5e1c-4b0f-a9a2-5d7f3e0c1b77" Version="8">
+ <ClipTrackItem Version="8">
+ <ComponentOwner Version="1"><Components ObjectRef="137"/></ComponentOwner>
+ <SubClip ObjectRef="136"/>
+ <TrackItem Version="4">
+ <Start>0</Start>
+ <End>1270080000000</End>
+ </TrackItem>
+ </ClipTrackItem>
+</VideoClipTrackItem>
+<VideoComponentParam ObjectID="139" ClassID="a8f0a3e5-57a1-4e8e-8a3a-9e0f8f2a9a44" Version="7">
+ <Name>Position</Name>
+ <CurrentValue>0.75:0.25</CurrentValue>
+</VideoComponentParam>
+<VideoComponentParam ObjectID="140" ClassID="a8f0a3e5-57a1-4e8e-8a3a-9e0f8f2a9a44" Version="7">
+ <Name>Scale</Name>
+ <CurrentValue>50</CurrentValue>
+</VideoComponentParam>
+<VideoComponentParam ObjectID="141" ClassID="a8f0a3e5-57a1-4e8e-8a3a-9e0f8f2a9a44" Version="7">
+ <Name>Rotation</Name>
+ <CurrentValue>0</CurrentValue>
+</VideoComponentParam>
+<VideoFilterComponent ObjectID="142" ClassID="0970b8ba-3d9f-4c4a-8a3c-3a64cf6a7b55" Version="9">
+ <Component Version="7"><Params Version="1">
+ <Param Index="0" ObjectRef="139"/>
+ <Param Index="1" ObjectRef="140"/>
+ <Param Index="2" ObjectRef="141"/>
+ </Params></Component>
+ <MatchName>AE.ADBE Motion</MatchName>
+ <DisplayName>Motion</DisplayName>
+</VideoFilterComponent>
+<VideoComponentParam ObjectID="143" ClassID="a8f0a3e5-57a1-4e8e-8a3a-9e0f8f2a9a44" Version="7">
+ <Name>Opacity</Name>
+ <CurrentValue>100</CurrentValue>
+</VideoComponentParam>
+<VideoFilterComponent ObjectID="144" ClassID="0970b8ba-3d9f-4c4a-8a3c-3a64cf6a7b55" Version="9">
+ <Component Version="7"><Params Version="1">
+ <Param Index="0" ObjectRef="143"/>
+ </Params></Component>
+ <MatchName>AE.ADBE Opacity</MatchName>
+ <DisplayName>Opacity</DisplayName>
+</VideoFilterComponent>
+<VideoClip ObjectID="145" ClassID="9308dbef-2440-4acb-9ab2-953b9a4e82ec" Version="3">
+ <Clip Version="18"><Source ObjectRef="110"/><InPoint>0</InPoint><OutPoint>2032128000000</OutPoint></Clip>
+</VideoClip>
+<SubClip ObjectID="146" ClassID="e0c6bd4a-5f55-4a76-9bd8-6f0d3a1c2e99" Version="5">
+ <Clip ObjectRef="145"/>
+ <MasterClip ObjectURef="bbbbbbbb-0000-4000-8000-000000000002"/>
+ <Name>broll.mov</Name>
+</SubClip>
+<VideoComponentChain ObjectID="147" ClassID="0d6e4a9d-4b5c-4d0e-8f9a-6a7b8c9d0e1f" Version="3">
+ <ComponentChain Version="3"><Components Version="1">
+ <Component Index="0" ObjectRef="142"/>
+ <Component Index="1" ObjectRef="144"/>
+ </Components></ComponentChain>
+</VideoComponentChain>
+<VideoClipTrackItem ObjectID="148" ClassID="368b0d13-5e1c-4b0f-a9a2-5d7f3e0c1b77" Version="8">
+ <ClipTrackItem Version="8">
+ <ComponentOwner Version="1"><Components ObjectRef="147"/></ComponentOwner>
+ <SubClip ObjectRef="146"/>
+ <TrackItem Version="4">
+ <Start>1270080000000</Start>
+ <End>2286144000000</End>
+ </TrackItem>
+ </ClipTrackItem>
+</VideoClipTrackItem>
+<VideoClip ObjectID="149" ClassID="9308dbef-2440-4acb-9ab2-953b9a4e82ec" Version="3">
+ <Clip Version="18"><Source ObjectRef="106"/><InPoint>0</InPoint><OutPoint>508032000000</OutPoint></Clip>
+</VideoClip>
+<SubClip ObjectID="150" ClassID="e0c6bd4a-5f55-4a76-9bd8-6f0d3a1c2e99" Version="5">
+ <Clip ObjectRef="149"/>
+ <MasterClip ObjectURef="bbbbbbbb-0000-4000-8000-000000000001"/>
+ <Name>interview.mp4</Name>
+</SubClip>
+<VideoClipTrackItem ObjectID="151" ClassID="368b0d13-5e1c-4b0f-a9a2-5d7f3e0c1b77" Version="8">
+ <ClipTrackItem Version="8">
+ <SubClip ObjectRef="150"/>
+ <TrackItem Version="4">
+ <Start>2286144000000</Start>
+ <End>2794176000000</End>
+ <Disabled>true</Disabled>
+ </TrackItem>
+ </ClipTrackItem>
+</VideoClipTrackItem>
+<VideoFilterComponent ObjectID="152" ClassID="0970b8ba-3d9f-4c4a-8a3c-3a64cf6a7b55" Version="9">
+ <Component Version="7"><Params Version="1">
+ </Params></Component>
+ <MatchName>AE.ADBE Cross Dissolve</MatchName>
+ <DisplayName>Cross Dissolve</DisplayName>
+</VideoFilterComponent>
+<VideoComponentChain ObjectID="153" ClassID="0d6e4a9d-4b5c-4d0e-8f9a-6a7b8c9d0e1f" Version="3">
+ <ComponentChain Version="3"><Components Version="1">
+ <Component Index="0" ObjectRef="152"/>
+ </Components></ComponentChain>
+</VideoComponentChain>
+<VideoTransitionItem ObjectID="154" ClassID="4a3b2c1d-0e9f-4a8b-9c7d-6e5f4a3b2c1d" Version="3">
+ <TransitionTrackItem Version="3">
+ <ComponentOwner Version="1"><Components ObjectRef="153"/></ComponentOwner>
+ <TrackItem Version="4"><Start>1143072000000</Start><End>1397088000000</End></TrackItem>
+ </TransitionTrackItem>
+ <TransitionName>Cross Dissolve</TransitionName>
+</VideoTransitionItem>
+<VideoClipTrack ObjectUID="eeeeeeee-0000-4000-8000-000000000003" ClassID="e2b8bcd1-8f2d-4a6e-b1d8-7a1f2c3d4e55" Version="5">
+ <ClipTrack Version="3">
+ <Track Version="4"><ID>1</ID><Index>0</Index></Track>
+ <ClipItems Version="3"><TrackItems Version="1">
+ <TrackItem Index="0" ObjectRef="138"/>
+ <TrackItem Index="1" ObjectRef="148"/>
+ <TrackItem Index="2" ObjectRef="151"/>
+ </TrackItems></ClipItems>
+ <TransitionItems Version="1"><TrackItems Version="1">
+ <TrackItem Index="0" ObjectRef="154"/>
+ </TrackItems></TransitionItems>
+ </ClipTrack>
+</VideoClipTrack>
+<VideoComponentParam ObjectID="155" ClassID="a8f0a3e5-57a1-4e8e-8a3a-9e0f8f2a9a44" Version="7">
+ <Name>Position</Name>
+ <CurrentValue>0.5:0.5</CurrentValue>
+</VideoComponentParam>
+<VideoComponentParam ObjectID="156" ClassID="a8f0a3e5-57a1-4e8e-8a3a-9e0f8f2a9a44" Version="7">
+ <Name>Scale</Name>
+ <CurrentValue>100</CurrentValue>
+</VideoComponentParam>
+<VideoComponentParam ObjectID="157" ClassID="a8f0a3e5-57a1-4e8e-8a3a-9e0f8f2a9a44" Version="7">
+ <Name>Rotation</Name>
+ <CurrentValue>0</CurrentValue>
+</VideoComponentParam>
+<VideoFilterComponent ObjectID="158" ClassID="0970b8ba-3d9f-4c4a-8a3c-3a64cf6a7b55" Version="9">
+ <Component Version="7"><Params Version="1">
+ <Param Index="0" ObjectRef="155"/>
+ <Param Index="1" ObjectRef="156"/>
+ <Param Index="2" ObjectRef="157"/>
+ </Params></Component>
+ <MatchName>AE.ADBE Motion</MatchName>
+ <DisplayName>Motion</DisplayName>
+</VideoFilterComponent>
+<VideoComponentParam ObjectID="159" ClassID="a8f0a3e5-57a1-4e8e-8a3a-9e0f8f2a9a44" Version="7">
+ <Name>Opacity</Name>
+ <CurrentValue>50</CurrentValue>
+</VideoComponentParam>
+<VideoFilterComponent ObjectID="160" ClassID="0970b8ba-3d9f-4c4a-8a3c-3a64cf6a7b55" Version="9">
+ <Component Version="7"><Params Version="1">
+ <Param Index="0" ObjectRef="159"/>
+ </Params></Component>
+ <MatchName>AE.ADBE Opacity</MatchName>
+ <DisplayName>Opacity</DisplayName>
+</VideoFilterComponent>
+<VideoComponentParam ObjectID="161" ClassID="a8f0a3e5-57a1-4e8e-8a3a-9e0f8f2a9a44" Version="7">
+ <Name>Blurriness</Name>
+ <CurrentValue>25</CurrentValue>
+</VideoComponentParam>
+<VideoFilterComponent ObjectID="162" ClassID="0970b8ba-3d9f-4c4a-8a3c-3a64cf6a7b55" Version="9">
+ <Component Version="7"><Params Version="1">
+ <Param Index="0" ObjectRef="161"/>
+ </Params></Component>
+ <MatchName>AE.ADBE Gaussian Blur 2</MatchName>
+ <DisplayName>Gaussian Blur</DisplayName>
+</VideoFilterComponent>
+<VideoClip ObjectID="163" ClassID="9308dbef-2440-4acb-9ab2-953b9a4e82ec" Version="3">
+ <Clip Version="18"><Source ObjectRef="114"/><InPoint>0</InPoint><OutPoint>762048000000</OutPoint></Clip>
+</VideoClip>
+<SubClip ObjectID="164" ClassID="e0c6bd4a-5f55-4a76-9bd8-6f0d3a1c2e99" Version="5">
+ <Clip ObjectRef="163"/>
+ <MasterClip ObjectURef="bbbbbbbb-0000-4000-8000-000000000004"/>
+ <Name>overlay.png</Name>
+</SubClip>
+<VideoComponentChain ObjectID="165" ClassID="0d6e4a9d-4b5c-4d0e-8f9a-6a7b8c9d0e1f" Version="3">
+ <ComponentChain Version="3"><Components Version="1">
+ <Component Index="0" ObjectRef="158"/>
+ <Component Index="1" ObjectRef="160"/>
+ <Component Index="2" ObjectRef="162"/>
+ </Components></ComponentChain>
+</VideoComponentChain>
+<VideoClipTrackItem ObjectID="166" ClassID="368b0d13-5e1c-4b0f-a9a2-5d7f3e0c1b77" Version="8">
+ <ClipTrackItem Version="8">
+ <ComponentOwner Version="1"><Components ObjectRef="165"/></ComponentOwner>
+ <SubClip ObjectRef="164"/>
+ <TrackItem Version="4">
+ <Start>254016000000</Start>
+ <End>1016064000000</End>
+ </TrackItem>
+ </ClipTrackItem>
+</VideoClipTrackItem>
+<VideoSequenceSource ObjectID="167" ClassID="1c9a8d37-0e7a-4d6f-b0c3-2f4e5d6c7b88" Version="1">
+ <Sequence ObjectURef="ffffffff-0000-4000-8000-000000000003"/>
+</VideoSequenceSource>
+<VideoClip ObjectID="168" ClassID="9308dbef-2440-4acb-9ab2-953b9a4e82ec" Version="3">
+ <Clip Version="18"><Source ObjectRef="167"/><InPoint>0</InPoint><OutPoint>508032000000</OutPoint></Clip>
+</VideoClip>
+<SubClip ObjectID="169" ClassID="e0c6bd4a-5f55-4a76-9bd8-6f0d3a1c2e99" Version="5">
+ <Clip ObjectRef="168"/>
+ <Name>Lower Third Nest</Name>
+</SubClip>
+<VideoClipTrackItem ObjectID="170" ClassID="368b0d13-5e1c-4b0f-a9a2-5d7f3e0c1b77" Version="8">
+ <ClipTrackItem Version="8">
+ <SubClip ObjectRef="169"/>
+ <TrackItem Version="4">
+ <Start>1524096000000</Start>
+ <End>2032128000000</End>
+ </TrackItem>
+ </ClipTrackItem>
+</VideoClipTrackItem>
+<VideoClipTrack ObjectUID="eeeeeeee-0000-4000-8000-000000000004" ClassID="e2b8bcd1-8f2d-4a6e-b1d8-7a1f2c3d4e55" Version="5">
+ <ClipTrack Version="3">
+ <Track Version="4"><ID>2</ID><Index>1</Index></Track>
+ <ClipItems Version="3"><TrackItems Version="1">
+ <TrackItem Index="0" ObjectRef="166"/>
+ <TrackItem Index="1" ObjectRef="170"/>
+ </TrackItems></ClipItems>
+ </ClipTrack>
+</VideoClipTrack>
+<VideoComponentParam ObjectID="171" ClassID="a8f0a3e5-57a1-4e8e-8a3a-9e0f8f2a9a44" Version="7">
+ <Name>Level</Name>
+ <CurrentValue>1</CurrentValue>
+</VideoComponentParam>
+<VideoFilterComponent ObjectID="172" ClassID="0970b8ba-3d9f-4c4a-8a3c-3a64cf6a7b55" Version="9">
+ <Component Version="7"><Params Version="1">
+ <Param Index="0" ObjectRef="171"/>
+ </Params></Component>
+ <MatchName>AC.ADBE Volume</MatchName>
+ <DisplayName>Volume</DisplayName>
+</VideoFilterComponent>
+<AudioClip ObjectID="173" ClassID="9308dbef-2440-4acb-9ab2-953b9a4e82ec" Version="3">
+ <Clip Version="18"><Source ObjectRef="108"/><InPoint>508032000000</InPoint><OutPoint>1778112000000</OutPoint></Clip>
+</AudioClip>
+<SubClip ObjectID="174" ClassID="e0c6bd4a-5f55-4a76-9bd8-6f0d3a1c2e99" Version="5">
+ <Clip ObjectRef="173"/>
+ <MasterClip ObjectURef="bbbbbbbb-0000-4000-8000-000000000001"/>
+ <Name>interview.mp4</Name>
+</SubClip>
+<VideoComponentChain ObjectID="175" ClassID="0d6e4a9d-4b5c-4d0e-8f9a-6a7b8c9d0e1f" Version="3">
+ <ComponentChain Version="3"><Components Version="1">
+ <Component Index="0" ObjectRef="172"/>
+ </Components></ComponentChain>
+</VideoComponentChain>
+<AudioClipTrackItem ObjectID="176" ClassID="368b0d13-5e1c-4b0f-a9a2-5d7f3e0c1b77" Version="8">
+ <ClipTrackItem Version="8">
+ <ComponentOwner Version="1"><Components ObjectRef="175"/></ComponentOwner>
+ <SubClip ObjectRef="174"/>
+ <TrackItem Version="4">
+ <Start>0</Start>
+ <End>1270080000000</End>
+ </TrackItem>
+ </ClipTrackItem>
+</AudioClipTrackItem>
+<AudioClipTrack ObjectUID="eeeeeeee-0000-4000-8000-000000000505" ClassID="e2b8bcd1-8f2d-4a6e-b1d8-7a1f2c3d4e55" Version="5">
+ <ClipTrack Version="3">
+ <Track Version="4"><ID>1</ID><Index>0</Index></Track>
+ <ClipItems Version="3"><TrackItems Version="1">
+ <TrackItem Index="0" ObjectRef="176"/>
+ </TrackItems></ClipItems>
+ </ClipTrack>
+</AudioClipTrack>
+<VideoComponentParam ObjectID="177" ClassID="a8f0a3e5-57a1-4e8e-8a3a-9e0f8f2a9a44" Version="7">
+ <Name>Level</Name>
+ <CurrentValue>0.5</CurrentValue>
+</VideoComponentParam>
+<VideoFilterComponent ObjectID="178" ClassID="0970b8ba-3d9f-4c4a-8a3c-3a64cf6a7b55" Version="9">
+ <Component Version="7"><Params Version="1">
+ <Param Index="0" ObjectRef="177"/>
+ </Params></Component>
+ <MatchName>AC.ADBE Volume</MatchName>
+ <DisplayName>Volume</DisplayName>
+</VideoFilterComponent>
+<AudioClip ObjectID="179" ClassID="9308dbef-2440-4acb-9ab2-953b9a4e82ec" Version="3">
+ <Clip Version="18"><Source ObjectRef="112"/><InPoint>0</InPoint><OutPoint>2032128000000</OutPoint></Clip>
+</AudioClip>
+<SubClip ObjectID="180" ClassID="e0c6bd4a-5f55-4a76-9bd8-6f0d3a1c2e99" Version="5">
+ <Clip ObjectRef="179"/>
+ <MasterClip ObjectURef="bbbbbbbb-0000-4000-8000-000000000003"/>
+ <Name>theme song.wav</Name>
+</SubClip>
+<VideoComponentChain ObjectID="181" ClassID="0d6e4a9d-4b5c-4d0e-8f9a-6a7b8c9d0e1f" Version="3">
+ <ComponentChain Version="3"><Components Version="1">
+ <Component Index="0" ObjectRef="178"/>
+ </Components></ComponentChain>
+</VideoComponentChain>
+<AudioClipTrackItem ObjectID="182" ClassID="368b0d13-5e1c-4b0f-a9a2-5d7f3e0c1b77" Version="8">
+ <ClipTrackItem Version="8">
+ <ComponentOwner Version="1"><Components ObjectRef="181"/></ComponentOwner>
+ <SubClip ObjectRef="180"/>
+ <TrackItem Version="4">
+ <Start>0</Start>
+ <End>2032128000000</End>
+ </TrackItem>
+ </ClipTrackItem>
+</AudioClipTrackItem>
+<AudioClip ObjectID="183" ClassID="9308dbef-2440-4acb-9ab2-953b9a4e82ec" Version="3">
+ <Clip Version="18"><Source ObjectRef="112"/><InPoint>5080320000000</InPoint><OutPoint>5588352000000</OutPoint></Clip>
+</AudioClip>
+<SubClip ObjectID="184" ClassID="e0c6bd4a-5f55-4a76-9bd8-6f0d3a1c2e99" Version="5">
+ <Clip ObjectRef="183"/>
+ <MasterClip ObjectURef="bbbbbbbb-0000-4000-8000-000000000003"/>
+ <Name>theme song.wav</Name>
+</SubClip>
+<AudioClipTrackItem ObjectID="185" ClassID="368b0d13-5e1c-4b0f-a9a2-5d7f3e0c1b77" Version="8">
+ <ClipTrackItem Version="8">
+ <SubClip ObjectRef="184"/>
+ <TrackItem Version="4">
+ <Start>2032128000000</Start>
+ <End>2540160000000</End>
+ </TrackItem>
+ <PlayBackwards>true</PlayBackwards>
+ </ClipTrackItem>
+</AudioClipTrackItem>
+<AudioClipTrack ObjectUID="eeeeeeee-0000-4000-8000-000000000506" ClassID="e2b8bcd1-8f2d-4a6e-b1d8-7a1f2c3d4e55" Version="5">
+ <ClipTrack Version="3">
+ <Track Version="4"><ID>2</ID><Index>1</Index><IsMuted>false</IsMuted><IsTargeted>true</IsTargeted></Track>
+ <ClipItems Version="3"><TrackItems Version="1">
+ <TrackItem Index="0" ObjectRef="182"/>
+ <TrackItem Index="1" ObjectRef="185"/>
+ </TrackItems></ClipItems>
+ </ClipTrack>
+</AudioClipTrack>
+<VideoTrackGroup ObjectID="186" ClassID="f1e2d3c4-b5a6-4978-8a9b-0c1d2e3f4a5b" Version="9">
+ <TrackGroup Version="1">
+ <Tracks Version="1">
+ <Track Index="0" ObjectURef="eeeeeeee-0000-4000-8000-000000000003"/>
+ <Track Index="1" ObjectURef="eeeeeeee-0000-4000-8000-000000000004"/>
+ </Tracks>
+ <FrameRect>0,0,1920,1080</FrameRect>
+ <FrameRate>10160640000</FrameRate>
+ </TrackGroup>
+</VideoTrackGroup>
+<AudioTrackGroup ObjectID="187" ClassID="f1e2d3c4-b5a6-4978-8a9b-0c1d2e3f4a5b" Version="9">
+ <TrackGroup Version="1">
+ <Tracks Version="1">
+ <Track Index="0" ObjectURef="eeeeeeee-0000-4000-8000-000000000505"/>
+ <Track Index="1" ObjectURef="eeeeeeee-0000-4000-8000-000000000506"/>
+ </Tracks>
+ <FrameRate>10160640000</FrameRate>
+ </TrackGroup>
+</AudioTrackGroup>
+<Marker ObjectID="188" ClassID="5b6c7d8e-9f0a-4b1c-8d2e-3f4a5b6c7d8e" Version="4">
+ <Name>Intro</Name><Comment>start here</Comment><Type>Comment</Type>
+ <Start>254016000000</Start><Duration>0</Duration>
+</Marker>
+<Marker ObjectID="189" ClassID="5b6c7d8e-9f0a-4b1c-8d2e-3f4a5b6c7d8e" Version="4">
+ <Name>Chapter 2</Name><Comment></Comment><Type>Chapter</Type>
+ <Start>1524096000000</Start><Duration>508032000000</Duration>
+</Marker>
+<Markers ObjectID="190" ClassID="6c7d8e9f-0a1b-4c2d-9e3f-4a5b6c7d8e9f" Version="3">
+ <Markers Version="1">
+ <Marker Index="0" ObjectRef="188"/>
+ <Marker Index="1" ObjectRef="189"/>
+ </Markers>
+</Markers>
+<Sequence ObjectUID="ffffffff-0000-4000-8000-000000000001" ClassID="6a15d903-8739-11d5-af2d-9b7855ad8974" Version="1">
+ <Node Version="1"><Properties Version="1"/></Node>
+ <TrackGroups Version="1">
+ <TrackGroup Version="1" Index="0"><First>0</First><Second ObjectRef="186"/></TrackGroup>
+ <TrackGroup Version="1" Index="1"><First>1</First><Second ObjectRef="187"/></TrackGroup>
+ </TrackGroups>
+ <Markers ObjectRef="190"/>
+ <Name>Main Cut</Name>
+</Sequence>
+<RootProjectItem ObjectUID="99999999-0000-4000-8000-000000000001" ClassID="1e2f3a4b-5c6d-4e7f-8091-a2b3c4d5e6f7" Version="1">
+ <ProjectItemContainer Version="1"><Items Version="1">
+ <Item Index="0" ObjectURef="dddddddd-0000-4000-8000-000000000002"/>
+ <Item Index="1" ObjectURef="dddddddd-0000-4000-8000-000000000003"/>
+ </Items></ProjectItemContainer>
+ <ProjectItem Version="1"><Name>Root</Name></ProjectItem>
+</RootProjectItem>
+</PremiereData>
diff --git a/packages/core/src/interchange/index.ts b/packages/core/src/interchange/index.ts
index 6fbaf16b..3650d540 100644
--- a/packages/core/src/interchange/index.ts
+++ b/packages/core/src/interchange/index.ts
@@ -36,11 +36,31 @@ export { serializeEdl, serializeEdls } from "./edl";
export { parseEdl, looksLikeEdl, matchReelItems } from "./edl-import";
export type { EdlParseOptions, EdlClipInfo } from "./edl-import";
export { flattenNests, hasNests } from "./nest-flatten";
+export {
+ TICKS_PER_SECOND,
+ defaultPrprojSequence,
+ frameRateFromTicksPerFrame,
+ gunzip,
+ importPrproj,
+ importPrprojDocument,
+ listPrprojSequences,
+ looksLikeGzip,
+ looksLikePrproj,
+ parsePrprojXml,
+ parseTicks,
+ prprojToSequence,
+ readPrproj,
+ resolveRef,
+ ticksToFrames,
+ ticksToSeconds,
+} from "./prproj";
+export type { PrprojDocument, PrprojImportResult, PrprojOptions, PrprojParse, PrprojSequenceInfo } from "./prproj";
export { AAF_DECISION, AAF_LIMITS, aafNote } from "./aaf-decision";
export { looksLikeCompoundFile } from "./aaf/aaf-reader";
export type { EdlFile, EdlOptions } from "./edl";
export { projectToSequence, sequenceToTimeline, relinkMedia } from "./model";
export type {
+ ImportReport,
InterchangeReport,
Sequence,
SeqClip,
@@ -53,7 +73,7 @@ export type {
} from "./model";
export type InterchangeFormat = "xmeml" | "fcpxml" | "edl" | "otio" | "aaf";
-export type ImportableFormat = "xmeml" | "fcpxml" | "otio" | "aaf" | "edl";
+export type ImportableFormat = "xmeml" | "fcpxml" | "otio" | "aaf" | "edl" | "prproj";
export interface InterchangeFile {
readonly filename: string;
@@ -322,17 +342,43 @@ export function planTimelineImport(
return { timeline: { ...draft, duration }, mediaItems };
}
+/**
+ * Add the bins an import carries (.prproj master-clip bins) to the project. A bin that already exists (same name
+ * under the same parent) is reused, so importing twice does not duplicate the folder tree; the new media is
+ * re-pointed at the surviving bin ids.
+ */
+function mergeImportedBins(project: Project, result: TimelineImportResult): { project: Project; result: TimelineImportResult } {
+ if (!result.newBins?.length) return { project, result };
+ const bins = [...(project.bins ?? [])];
+ const remap = new Map<string, string>();
+ for (const bin of result.newBins) {
+ const parentId = bin.parentId ? remap.get(bin.parentId) ?? bin.parentId : undefined;
+ const existing = bins.find((b) => b.name === bin.name && b.parentId === parentId);
+ if (existing) {
+ remap.set(bin.id, existing.id);
+ } else {
+ remap.set(bin.id, bin.id);
+ bins.push({ ...bin, ...(parentId ? { parentId } : {}) });
+ }
+ }
+ const newMedia = result.newMedia.map((item) => (item.binId && remap.has(item.binId) ? { ...item, binId: remap.get(item.binId) } : item));
+ return { project: { ...project, bins }, result: { ...result, newMedia } };
+}
+
/**
* The project after an import commit: the planned timeline and media, plus, when the file carried
* compound clips (FCPXML media + ref-clip), one project sequence per compound clip and an instance
* record per imported nest clip. Commit the result through `editSnapshot` as ONE undo step.
*/
export function applyTimelineImport(
- project: Project,
+ input: Project,
result: TimelineImportResult,
mode: TimelineImportMode = "replace",
): Project {
- const plan = planTimelineImport(project, result, mode);
+ const binned = mergeImportedBins(input, result);
+ const project = binned.project;
+ const plan = planTimelineImport(project, binned.result, mode);
+ result = binned.result;
const mediaLibrary = { ...project.mediaLibrary, items: plan.mediaItems };
const multicamSources = result.multicamSources?.length
? { multicamSources: [...(project.multicamSources ?? []), ...result.multicamSources] }
diff --git a/packages/core/src/interchange/model.ts b/packages/core/src/interchange/model.ts
index e9ff88d3..8068ea39 100644
--- a/packages/core/src/interchange/model.ts
+++ b/packages/core/src/interchange/model.ts
@@ -1,6 +1,6 @@
import type { Clip, Marker, MarkerKind, Track, Transition } from "../types/timeline";
import { MARKER_KINDS } from "../types/timeline";
-import type { MediaItem, Project } from "../types/project";
+import type { MediaBin, MediaItem, Project } from "../types/project";
import { ensureSequences, syncActiveSequence } from "../timeline/sequences";
import { getCompoundClipId } from "../timeline/timeline-items";
import { getMulticamSource, multicamTag, MULTICAM_ANGLE_COLORS, type MulticamSource } from "../multicam/source";
@@ -41,6 +41,8 @@ export interface SeqMedia {
readonly startSec?: number;
/** A bin item the importer already chose (EDL reel + source timecode); relinking honours it before name matching. */
readonly mediaItemId?: string;
+ /** Project-panel bin path (outermost first) the source file lived in (.prproj master clips). */
+ readonly binPath?: readonly string[];
}
/** A marker on a clip (clip + master-clip markers merged); `sec` is in the media's own (source) time. */
@@ -87,6 +89,15 @@ export interface SeqClip {
readonly markers?: readonly SeqClipMarker[];
/** EDL import: the event's reel name and source timecodes, kept on the clip as `metadata.edl`. */
readonly edl?: { readonly reel: string; readonly sourceIn: string; readonly sourceOut: string; readonly event: number };
+ /**
+ * Basic motion from the source file: `x` / `y` are pixel offsets from the frame centre of the sequence,
+ * `scale` is a multiplier (1 = 100%). Absent = untouched. Only .prproj import fills it.
+ */
+ readonly motion?: { readonly x: number; readonly y: number; readonly scale: number; readonly rotation?: number };
+ /** The source file had the clip disabled. OpenReel has no clip enable flag: it is imported muted / transparent. */
+ readonly disabled?: boolean;
+ /** Extra clip metadata kept as `clip.metadata.<key>` (for example the .prproj origin). */
+ readonly metadata?: Readonly<Record<string, unknown>>;
}
/** One synchronised camera angle of a multicam source. */
@@ -544,6 +555,18 @@ export interface TimelineImportResult {
* of `tracks` / `nests` that cut them carry `metadata.multicam` pointing at these. Absent when there are none.
*/
readonly multicamSources?: MulticamSource[];
+ /** Project-panel bins to create for the imported media (`newMedia[].binId` points at them). Absent when none. */
+ readonly newBins?: MediaBin[];
+ /** What the importer dropped or approximated, per item (.prproj import). */
+ readonly importReport?: ImportReport;
+}
+
+export interface ImportReport {
+ readonly items: ReportItem[];
+ /** Informational lines (what was read, what is never read). */
+ readonly notes: string[];
+ readonly dropped: number;
+ readonly approximated: number;
}
/** A compound clip from an interchange file, converted to OpenReel tracks; becomes a project sequence on commit. */
@@ -654,10 +677,10 @@ export function relinkMedia(
return out;
}
-const DEFAULT_TRANSFORM = (opacity: number): Clip["transform"] => ({
- position: { x: 0, y: 0 },
- scale: { x: 1, y: 1 },
- rotation: 0,
+const DEFAULT_TRANSFORM = (opacity: number, motion?: SeqClip["motion"]): Clip["transform"] => ({
+ position: { x: motion?.x ?? 0, y: motion?.y ?? 0 },
+ scale: { x: motion?.scale ?? 1, y: motion?.scale ?? 1 },
+ rotation: motion?.rotation ?? 0,
anchor: { x: 0.5, y: 0.5 },
opacity,
fitMode: "contain",
@@ -678,6 +701,24 @@ export function sequenceToTimeline(
const mediaIdFor = new Map<string, string>();
const newMedia: MediaItem[] = [];
const clipCounts = new Map<string, number>();
+ // Bins for placeholder media (.prproj): one bin per distinct path prefix, parents first.
+ const newBins: MediaBin[] = [];
+ const binIds = new Map<string, string>();
+ const binFor = (path: readonly string[] | undefined): string | undefined => {
+ if (!path?.length) return undefined;
+ let parentId: string | undefined;
+ for (let depth = 1; depth <= path.length; depth++) {
+ const key = JSON.stringify(path.slice(0, depth));
+ let id = binIds.get(key);
+ if (!id) {
+ id = `bin-${makeId()}`;
+ binIds.set(key, id);
+ newBins.push({ id, name: path[depth - 1], ...(parentId ? { parentId } : {}) });
+ }
+ parentId = id;
+ }
+ return parentId;
+ };
for (const media of allMedia) {
const hit = links.get(media.key);
@@ -687,8 +728,10 @@ export function sequenceToTimeline(
}
const id = `media-${makeId()}`;
mediaIdFor.set(media.key, id);
+ const binId = binFor(media.binPath);
newMedia.push({
id,
+ ...(binId ? { binId } : {}),
name: media.name,
type: media.kind,
fileHandle: null,
@@ -802,10 +845,10 @@ export function sequenceToTimeline(
outPoint: sc.outSec,
effects: [],
audioEffects: [],
- transform: DEFAULT_TRANSFORM(sc.opacity),
- volume: sc.volume,
+ transform: DEFAULT_TRANSFORM(sc.disabled ? 0 : sc.opacity, sc.motion),
+ volume: sc.disabled ? 0 : sc.volume,
keyframes: [],
- metadata: { compoundClipId: nestId, compoundClipName: sc.nested.name, compoundClipColor: NEST_IMPORT_COLOR },
+ metadata: { ...(sc.metadata ?? {}), ...(sc.disabled ? { importedDisabled: true } : {}), compoundClipId: nestId, compoundClipName: sc.nested.name, compoundClipColor: NEST_IMPORT_COLOR },
...(sc.speed !== 1 ? { speed: sc.speed } : {}),
...(sc.reversed ? { reversed: true } : {}),
};
@@ -831,11 +874,18 @@ export function sequenceToTimeline(
outPoint: sc.outSec,
effects: [],
audioEffects: [],
- transform: DEFAULT_TRANSFORM(sc.opacity),
- volume: sc.volume,
+ transform: DEFAULT_TRANSFORM(sc.disabled ? 0 : sc.opacity, sc.motion),
+ volume: sc.disabled ? 0 : sc.volume,
keyframes: [],
- ...(multicamTagFor(sc) || sc.edl
- ? { metadata: { ...(multicamTagFor(sc) ? { multicam: multicamTagFor(sc) } : {}), ...(sc.edl ? { edl: sc.edl } : {}) } }
+ ...(multicamTagFor(sc) || sc.edl || sc.metadata || sc.disabled
+ ? {
+ metadata: {
+ ...(multicamTagFor(sc) ? { multicam: multicamTagFor(sc) } : {}),
+ ...(sc.edl ? { edl: sc.edl } : {}),
+ ...(sc.metadata ?? {}),
+ ...(sc.disabled ? { importedDisabled: true } : {}),
+ },
+ }
: {}),
...(sc.speed !== 1 ? { speed: sc.speed } : {}),
...(sc.reversed ? { reversed: true } : {}),
@@ -928,5 +978,6 @@ export function sequenceToTimeline(
...(targetedTrackIds.length ? { targetedTrackIds } : {}),
...(nests.length ? { nests } : {}),
...(multicamSources.length ? { multicamSources } : {}),
+ ...(newBins.length ? { newBins } : {}),
};
}
diff --git a/packages/core/src/interchange/prproj.test.ts b/packages/core/src/interchange/prproj.test.ts
new file mode 100644
index 00000000..e9374d93
--- /dev/null
+++ b/packages/core/src/interchange/prproj.test.ts
@@ -0,0 +1,408 @@
+import { readFileSync } from "node:fs";
+import { gzipSync } from "node:zlib";
+import { fileURLToPath } from "node:url";
+import { describe, expect, it } from "vitest";
+import { ActionExecutor } from "../actions/action-executor";
+import { editSnapshot } from "../actions/handlers/edit-snapshot";
+import type { MediaItem, Project } from "../types/project";
+import { buildProject } from "./__fixtures__/project";
+import { applyTimelineImport, importTimelineFile } from "./index";
+import { resolveFrameRate } from "./timecode";
+import {
+ TICKS_PER_SECOND,
+ frameRateFromTicksPerFrame,
+ gunzip,
+ importPrproj,
+ listPrprojSequences,
+ looksLikePrproj,
+ parsePrprojXml,
+ parseTicks,
+ prprojToSequence,
+ readPrproj,
+ resolveRef,
+ ticksToFrames,
+ ticksToSeconds,
+} from "./prproj";
+
+const fixtureDir = fileURLToPath(new URL("./__fixtures__/", import.meta.url));
+const xml = readFileSync(`${fixtureDir}main-cut.prproj.xml`, "utf8");
+const gz = new Uint8Array(readFileSync(`${fixtureDir}main-cut.prproj`));
+
+let counter = 0;
+const makeId = () => `t${++counter}`;
+const opts = (items: readonly MediaItem[] = []) => ({ mediaItems: items, makeId });
+const sec = (s: number) => BigInt(Math.round(s * Number(TICKS_PER_SECOND)));
+
+describe("tick math", () => {
+ it("uses Premiere's 254016000000 ticks per second", () => {
+ expect(TICKS_PER_SECOND).toBe(254_016_000_000n);
+ expect(ticksToSeconds(254_016_000_000n)).toBe(1);
+ expect(ticksToSeconds(127_008_000_000n)).toBe(0.5);
+ });
+
+ it("converts ticks to frames at the exact rational rate", () => {
+ const r25 = resolveFrameRate(25);
+ const r2997 = resolveFrameRate(29.97);
+ const r24 = resolveFrameRate(24);
+ expect(ticksToFrames(10_160_640_000n, r25)).toBe(1);
+ expect(ticksToFrames(sec(10), r25)).toBe(250);
+ // 29.97: one frame is 8475667200 ticks
+ expect(ticksToFrames(8_475_667_200n, r2997)).toBe(1);
+ expect(ticksToFrames(8_475_667_200n * 1800n, r2997)).toBe(1800);
+ expect(ticksToFrames(10_584_000_000n * 24n, r24)).toBe(24);
+ // rounds to the nearest frame, half up
+ expect(ticksToFrames(10_160_640_000n / 2n - 1n, r25)).toBe(0);
+ expect(ticksToFrames(10_160_640_000n / 2n, r25)).toBe(1);
+ expect(ticksToFrames(-10_160_640_000n, r25)).toBe(-1);
+ });
+
+ it("does not lose frames past 2^53 ticks (a 10 hour sequence)", () => {
+ const tenHours = 36_000n * TICKS_PER_SECOND; // 9.14e15 ticks
+ expect(Number(tenHours) > Number.MAX_SAFE_INTEGER).toBe(true);
+ expect(ticksToFrames(tenHours + 10_160_640_000n, resolveFrameRate(25))).toBe(900_001);
+ });
+
+ it("derives the frame rate from ticks per frame", () => {
+ expect(frameRateFromTicksPerFrame(10_160_640_000n)).toMatchObject({ num: 25, den: 1 });
+ expect(frameRateFromTicksPerFrame(8_475_667_200n)).toMatchObject({ num: 30000, den: 1001 });
+ expect(frameRateFromTicksPerFrame(10_594_584_000n)).toMatchObject({ num: 24000, den: 1001 });
+ expect(frameRateFromTicksPerFrame(0n)).toBeUndefined();
+ });
+
+ it("parses tick text strictly", () => {
+ expect(parseTicks("254016000000")).toBe(254_016_000_000n);
+ expect(parseTicks(" -91445760000000000 ")).toBe(-91_445_760_000_000_000n);
+ expect(parseTicks("9223372036854775807")).toBe(9_223_372_036_854_775_807n);
+ expect(parseTicks("12.5")).toBeUndefined();
+ expect(parseTicks("")).toBeUndefined();
+ expect(parseTicks(undefined)).toBeUndefined();
+ });
+});
+
+describe("gzip container", () => {
+ it("detects a .prproj by gzip magic or by PremiereData", () => {
+ expect(looksLikePrproj(gz)).toBe(true);
+ expect(looksLikePrproj(new TextEncoder().encode(xml))).toBe(true);
+ expect(looksLikePrproj(new TextEncoder().encode("<xmeml version='5'></xmeml>"))).toBe(false);
+ });
+
+ it("reads gzip through DecompressionStream and through the dependency-free fallback", async () => {
+ const viaStream = await gunzip(gz);
+ expect(new TextDecoder().decode(viaStream)).toBe(xml);
+ const g = globalThis as { DecompressionStream?: unknown };
+ const saved = g.DecompressionStream;
+ g.DecompressionStream = undefined;
+ try {
+ expect(new TextDecoder().decode(await gunzip(gz))).toBe(xml);
+ // a stream with a file name in the header (gzip FNAME), like `gzip file.prproj` writes
+ const named = new Uint8Array(gzipSync(Buffer.from(xml)));
+ expect(new TextDecoder().decode(await gunzip(named))).toBe(xml);
+ } finally {
+ g.DecompressionStream = saved;
+ }
+ });
+
+ it("rejects corrupt gzip and non-Premiere XML", async () => {
+ const bad = new Uint8Array(gz);
+ bad.fill(7, 40, 80);
+ await expect(readPrproj(bad)).rejects.toThrow();
+ await expect(readPrproj(new TextEncoder().encode("<xmeml/>"))).rejects.toThrow(/Premiere/);
+ });
+});
+
+describe("object graph", () => {
+ const doc = parsePrprojXml(xml);
+
+ it("indexes ObjectID and ObjectUID objects and resolves both reference kinds", () => {
+ expect(doc.version).toBe("3");
+ const byId = resolveRef(doc, { name: "X", attrs: { ObjectRef: "102" }, children: [], text: "" });
+ expect(byId?.attrs.ObjectID).toBe("102");
+ const byUid = resolveRef(doc, { name: "X", attrs: { ObjectURef: "aaaaaaaa-0000-4000-8000-000000000001" }, children: [], text: "" });
+ expect(byUid?.name).toBe("Media");
+ expect(resolveRef(doc, { name: "X", attrs: { ObjectRef: "999999" }, children: [], text: "" })).toBeUndefined();
+ });
+
+ it("lists sequences with size, rate, track counts and nesting", () => {
+ const list = listPrprojSequences(doc);
+ expect(list.map((s) => s.name).sort()).toEqual(["Alt Cut", "Lower Third Nest", "Main Cut"]);
+ const main = list.find((s) => s.name === "Main Cut")!;
+ expect(main).toMatchObject({ width: 1920, height: 1080, fps: 25, videoTracks: 2, audioTracks: 2, nested: false });
+ expect(main.clipCount).toBe(8);
+ expect(list.find((s) => s.name === "Lower Third Nest")!.nested).toBe(true);
+ expect(list.find((s) => s.name === "Alt Cut")!.fps).toBeCloseTo(29.97, 2);
+ });
+
+ it("defaults to the biggest sequence that is not a nest", () => {
+ expect(prprojToSequence(doc).sequence.name).toBe("Main Cut");
+ expect(prprojToSequence(doc, { sequenceId: listPrprojSequences(doc).find((s) => s.name === "Alt Cut")!.id }).sequence.name).toBe("Alt Cut");
+ });
+
+ it("walks Sequence > TrackGroups > Tracks > ClipItems > SubClip > Clip > Source > Media", () => {
+ const { sequence } = prprojToSequence(doc);
+ const media = Object.fromEntries(sequence.media.map((m) => [m.name, m]));
+ expect(Object.keys(media).sort()).toEqual(["broll.mov", "interview.mp4", "overlay.png", "theme song.wav"]);
+ expect(media["interview.mp4"]).toMatchObject({ kind: "video", hasAudio: true, hasVideo: true, width: 1920, durationSec: 60 });
+ expect(media["interview.mp4"].rate.num).toBe(30000);
+ expect(media["broll.mov"]).toMatchObject({ width: 3840, height: 2160, hasAudio: false });
+ expect(media["theme song.wav"]).toMatchObject({ kind: "audio", durationSec: 180 });
+ expect(media["overlay.png"].kind).toBe("image");
+ expect(media["theme song.wav"].pathUrl).toBe("file://localhost/C%3A/Music/theme%20song.wav");
+ expect(media["interview.mp4"].binPath).toEqual(["Footage"]);
+ expect(media["overlay.png"].binPath).toEqual(["Footage", "Graphics"]);
+ expect(media["theme song.wav"].binPath).toEqual(["Audio"]);
+ });
+});
+
+describe("main cut import", () => {
+ const parsed = prprojToSequence(parsePrprojXml(xml));
+ const seq = parsed.sequence;
+ const video = seq.tracks.filter((t) => t.kind === "video");
+ const audio = seq.tracks.filter((t) => t.kind === "audio");
+
+ it("reads sequence name, rate and size", () => {
+ expect(seq.name).toBe("Main Cut");
+ expect(seq.rate).toMatchObject({ num: 25, den: 1 });
+ expect([seq.width, seq.height]).toEqual([1920, 1080]);
+ });
+
+ it("places clips from start / end ticks with source in / out", () => {
+ const [a, b, c] = video[0].clips;
+ expect([a.startFrame, a.endFrame]).toEqual([0, 125]);
+ expect([a.inSec, a.outSec]).toEqual([2, 7]);
+ expect(a.speed).toBe(1);
+ expect([b.startFrame, b.endFrame]).toEqual([125, 225]);
+ expect([b.inSec, b.outSec]).toEqual([0, 8]);
+ expect([c.startFrame, c.endFrame]).toEqual([225, 275]);
+ });
+
+ it("derives speed from source range over timeline range", () => {
+ expect(video[0].clips[1].speed).toBe(2);
+ expect(video[0].clips[1].reversed).toBe(false);
+ });
+
+ it("reads reverse playback from an audio item", () => {
+ const reversed = audio.flatMap((t) => t.clips).find((c) => c.reversed);
+ expect(reversed).toMatchObject({ startFrame: 200, endFrame: 250, inSec: 20, outSec: 22, speed: 1 });
+ });
+
+ it("reads disabled items", () => {
+ expect(video[0].clips[2].disabled).toBe(true);
+ expect(video[0].clips[0].disabled).toBeUndefined();
+ });
+
+ it("reads basic motion, opacity and volume", () => {
+ const b = video[0].clips[1];
+ // position 0.75:0.25 of 1920x1080 -> +480 / -270 px from centre; scale 50%
+ expect(b.motion).toMatchObject({ x: 480, y: -270, scale: 0.5 });
+ expect(video[0].clips[0].motion).toBeUndefined();
+ const overlay = video[1].clips[0];
+ expect(overlay.opacity).toBe(0.5);
+ const music = audio.flatMap((t) => t.clips).find((c) => c.name === "theme song.wav" && !c.reversed)!;
+ expect(music.volume).toBe(0.5);
+ });
+
+ it("targets tracks from the track flag", () => {
+ // A1 held only the merged linked audio and is gone; the music track (now A1) is the targeted one.
+ expect(audio).toHaveLength(1);
+ expect(audio[0].targeted).toBe(true);
+ expect(video[0].targeted).toBeUndefined();
+ });
+
+ it("merges the linked audio item of a video clip into it", () => {
+ const interview = video[0].clips[0];
+ expect(interview.withAudio).toBe(true);
+ expect(audio.flatMap((t) => t.clips).some((c) => c.name === "interview.mp4")).toBe(false);
+ expect(parsed.report.notes.join(" ")).toMatch(/1 audio clips linked/);
+ });
+
+ it("reads a cross dissolve with its alignment", () => {
+ expect(video[0].transitions).toEqual([{ kind: "dissolve", startFrame: 112 + 1, endFrame: 138, alignment: "center" }]);
+ });
+
+ it("reads sequence markers, including range markers and chapter kind", () => {
+ expect(seq.markers).toEqual([
+ { frame: 25, name: "Intro", comment: "start here" },
+ { frame: 150, name: "Chapter 2", durationFrames: 50, kind: "chapter" },
+ ]);
+ });
+
+ it("builds a nested sequence from a sequence source", () => {
+ const nest = video[1].clips[1];
+ expect(nest.nested?.name).toBe("Lower Third Nest");
+ expect(nest.mediaKey).toBe("");
+ expect(nest.nested!.tracks[0].clips[0]).toMatchObject({ name: "broll.mov", inSec: 1, outSec: 4 });
+ expect(seq.media.map((m) => m.name)).not.toContain("Lower Third Nest");
+ });
+});
+
+describe("import report", () => {
+ const { report } = prprojToSequence(parsePrprojXml(xml));
+ const byFeature = (f: string) => report.items.filter((i) => i.feature === f);
+
+ it("reports effects other than motion, opacity and volume as dropped", () => {
+ const blur = byFeature("Effect: Gaussian Blur");
+ expect(blur).toHaveLength(1);
+ expect(blur[0]).toMatchObject({ severity: "dropped", clipName: "overlay.png" });
+ });
+
+ it("reports disabled clips and the motion approximation", () => {
+ expect(byFeature("Disabled clip")).toHaveLength(1);
+ expect(byFeature("Motion")[0].severity).toBe("approximated");
+ });
+
+ it("counts dropped and approximated items and lists what is never read", () => {
+ expect(report.dropped).toBe(report.items.filter((i) => i.severity === "dropped").length);
+ expect(report.approximated).toBe(report.items.filter((i) => i.severity === "approximated").length);
+ expect(report.dropped).toBeGreaterThan(0);
+ expect(report.notes.join(" ")).toMatch(/Lumetri/);
+ expect(report.notes.join(" ")).toMatch(/Alt Cut/);
+ });
+
+ it("reports unsupported transitions, animated values and unplaceable items instead of losing them silently", () => {
+ const changed = xml
+ .replace("<TransitionName>Cross Dissolve</TransitionName>", "<TransitionName>Cross Zoom</TransitionName>")
+ .replace(/AE\.ADBE Cross Dissolve/g, "AE.ADBE Cross Zoom")
+ .replace(/<DisplayName>Cross Dissolve<\/DisplayName>/, "<DisplayName>Cross Zoom</DisplayName>")
+ .replace(/(<Name>Opacity<\/Name>\s*<CurrentValue>50<\/CurrentValue>)/, "$1<IsTimeVarying>true</IsTimeVarying>");
+ const r = prprojToSequence(parsePrprojXml(changed));
+ expect(r.report.items.some((i) => i.feature === "Transition: Cross Zoom" && i.severity === "dropped")).toBe(true);
+ expect(r.sequence.tracks.find((t) => t.kind === "video")!.transitions).toHaveLength(0);
+ expect(r.report.items.some((i) => i.feature === "Animated opacity")).toBe(true);
+ });
+
+ it("reports a clip with no media", () => {
+ const changed = xml.replace(/<Media ObjectURef="aaaaaaaa-0000-4000-8000-000000000004"\/>/, "");
+ const r = prprojToSequence(parsePrprojXml(changed));
+ expect(r.report.items.some((i) => i.feature === "Clip without media" && i.clipName === "overlay.png")).toBe(true);
+ });
+
+ it("reports media with no file path and makes it a placeholder", async () => {
+ const changed = xml.replace(/<FilePath>\/Volumes\/Shoot\/Graphics\/overlay\.png<\/FilePath>\s*<ActualMediaFilePath>[^<]*<\/ActualMediaFilePath>/, "");
+ const r = prprojToSequence(parsePrprojXml(changed));
+ expect(r.report.items.some((i) => i.feature === "Media without a file path")).toBe(true);
+ });
+});
+
+describe("relink and import into a project", () => {
+ it("makes offline placeholders for media that is not in the bin", async () => {
+ const result = await importPrproj(gz, opts());
+ expect(result.format).toBe("prproj");
+ expect(result.unmatched.map((u) => u.name).sort()).toEqual(["broll.mov", "interview.mp4", "overlay.png", "theme song.wav"]);
+ expect(result.newMedia.every((m) => m.isPlaceholder)).toBe(true);
+ expect(result.sequenceName).toBe("Main Cut");
+ expect(result.settings).toEqual({ width: 1920, height: 1080, frameRate: 25 });
+ expect(result.prproj.sequences).toHaveLength(3);
+ expect(result.importReport?.dropped).toBeGreaterThan(0);
+ expect(result.importReport?.items.some((i) => i.feature === "Effect: Gaussian Blur")).toBe(true);
+ });
+
+ it("relinks media that is already in the bin by file name", async () => {
+ const existing = buildProject(25).mediaLibrary.items.find((m) => m.id === "m-interview")!;
+ const result = await importPrproj(gz, opts([existing]));
+ expect(result.matched.map((m) => m.name)).toContain("interview.mp4");
+ expect(result.newMedia.map((m) => m.name)).not.toContain("interview.mp4");
+ });
+
+ it("creates the bins of the master clips on the placeholders", async () => {
+ const result = await importPrproj(gz, opts());
+ const names = Object.fromEntries((result.newBins ?? []).map((b) => [b.id, b]));
+ const interview = result.newMedia.find((m) => m.name === "interview.mp4")!;
+ const overlay = result.newMedia.find((m) => m.name === "overlay.png")!;
+ expect(names[interview.binId!].name).toBe("Footage");
+ expect(names[overlay.binId!]).toMatchObject({ name: "Graphics", parentId: interview.binId });
+ });
+
+ it("turns tracks into OpenReel tracks with motion, opacity, volume, speed and disabled state", async () => {
+ const result = await importPrproj(gz, opts());
+ const clips = result.tracks.flatMap((t) => t.clips);
+ const broll = clips.find((c) => c.speed === 2)!;
+ expect(broll.transform).toMatchObject({ position: { x: 480, y: -270 }, scale: { x: 0.5, y: 0.5 } });
+ const disabled = clips.find((c) => c.metadata?.importedDisabled)!;
+ expect(disabled.transform.opacity).toBe(0);
+ expect(disabled.volume).toBe(0);
+ expect(clips.find((c) => c.reversed)?.speed).toBeUndefined();
+ expect(result.targetedTrackIds).toHaveLength(1);
+ expect(result.markers.map((m) => m.label)).toEqual(["Intro", "Chapter 2"]);
+ expect(result.markers[1]).toMatchObject({ time: 6, duration: 2, kind: "chapter" });
+ expect(result.nests).toHaveLength(1);
+ const video = result.tracks.filter((t) => t.type === "video");
+ expect(video[1].transitions.length + video[0].transitions.length).toBe(1);
+ });
+
+ it("is reachable through importTimelineFile (sync path rejects gzip with a clear message)", () => {
+ expect(() => importTimelineFile(gz, opts())).toThrow();
+ });
+
+ it("commits as ONE undoable action that also adds and removes the bins and nested sequence", async () => {
+ const project: Project = {
+ id: "p",
+ name: "P",
+ createdAt: 0,
+ modifiedAt: 0,
+ settings: { width: 1280, height: 720, frameRate: 25, sampleRate: 48000, channels: 2 },
+ mediaLibrary: { items: [] },
+ timeline: { duration: 0, tracks: [], markers: [], subtitles: [] },
+ };
+ const result = await importPrproj(gz, opts());
+ const next = applyTimelineImport(project, result, "replace");
+ expect(next.bins?.map((b) => b.name).sort()).toEqual(["Audio", "Footage", "Graphics"]);
+ expect(next.mediaLibrary.items).toHaveLength(4);
+ const executor = new ActionExecutor();
+ const outcome = await executor.execute({ type: "project/applyEditSnapshot", id: "imp", timestamp: 1, params: { snapshot: editSnapshot(next) } }, project);
+ expect(outcome.success).toBe(true);
+ expect(project.timeline.tracks.length).toBeGreaterThan(0);
+ expect(project.bins).toHaveLength(3);
+ expect(project.sequences?.length).toBeGreaterThanOrEqual(2);
+ await executor.undo(project);
+ expect(project.timeline.tracks).toHaveLength(0);
+ expect(project.bins).toBeUndefined();
+ expect(project.mediaLibrary.items).toHaveLength(0);
+ await executor.redo(project);
+ expect(project.bins).toHaveLength(3);
+ });
+
+ it("reuses bins that already exist instead of duplicating them", async () => {
+ const project: Project = {
+ id: "p",
+ name: "P",
+ createdAt: 0,
+ modifiedAt: 0,
+ settings: { width: 1280, height: 720, frameRate: 25, sampleRate: 48000, channels: 2 },
+ mediaLibrary: { items: [] },
+ timeline: { duration: 0, tracks: [], markers: [], subtitles: [] },
+ bins: [{ id: "existing", name: "Footage" }],
+ };
+ const result = await importPrproj(gz, opts());
+ const next = applyTimelineImport(project, result, "replace");
+ expect(next.bins?.filter((b) => b.name === "Footage")).toHaveLength(1);
+ const interview = next.mediaLibrary.items.find((m) => m.name === "interview.mp4")!;
+ expect(interview.binId).toBe("existing");
+ const overlay = next.mediaLibrary.items.find((m) => m.name === "overlay.png")!;
+ expect(next.bins?.find((b) => b.id === overlay.binId)).toMatchObject({ name: "Graphics", parentId: "existing" });
+ });
+});
+
+describe("robustness", () => {
+ it("fails clearly on a project with no sequences", () => {
+ const empty = '<?xml version="1.0"?><PremiereData Version="3"><Project ObjectID="1"/></PremiereData>';
+ expect(() => prprojToSequence(parsePrprojXml(empty))).toThrow(/no sequences/);
+ });
+
+ it("survives a reference loop between nested sequences", () => {
+ // Make the nest sequence contain a clip that plays the main sequence.
+ const main = parsePrprojXml(xml);
+ const list = listPrprojSequences(main);
+ const mainId = list.find((s) => s.name === "Main Cut")!.id;
+ const looped = xml.replace('<Sequence ObjectURef="ffffffff-0000-4000-8000-000000000003"/>', `<Sequence ObjectURef="${mainId}"/>`);
+ const r = prprojToSequence(parsePrprojXml(looped), { sequenceId: mainId });
+ expect(r.sequence.tracks.length).toBeGreaterThan(0);
+ });
+
+ it("clamps a sentinel out point to the clip length", () => {
+ const sentinel = xml.replace(new RegExp(`<OutPoint>${Number(TICKS_PER_SECOND) * 7}</OutPoint>`), "<OutPoint>9223372036854775807</OutPoint>");
+ const r = prprojToSequence(parsePrprojXml(sentinel));
+ const a = r.sequence.tracks[0].clips[0];
+ expect(a.outSec - a.inSec).toBeCloseTo(5, 6);
+ expect(a.speed).toBe(1);
+ });
+});
diff --git a/packages/core/src/interchange/prproj.ts b/packages/core/src/interchange/prproj.ts
new file mode 100644
index 00000000..3b089b40
--- /dev/null
+++ b/packages/core/src/interchange/prproj.ts
@@ -0,0 +1,962 @@
+import type { MarkerKind } from "../types/timeline";
+import { inflateRaw } from "./aaf/inflate";
+import {
+ sequenceToTimeline,
+ type ImportReport,
+ type SeqClip,
+ type SeqMarker,
+ type SeqMedia,
+ type Sequence,
+ type SeqTrack,
+ type SeqTransition,
+ type SeqTransitionKind,
+ type SequenceToTimelineOptions,
+ type TimelineImportResult,
+} from "./model";
+import type { ReportItem } from "./report";
+import { fpsOf, resolveFrameRate, type FrameRate } from "./timecode";
+import { parseXml, type XmlElement } from "./xml";
+
+/**
+ * Adobe Premiere Pro project (.prproj) import.
+ *
+ * A .prproj is a gzip-compressed XML document, `<PremiereData Version="3">`, holding a flat list of objects. An
+ * object either has an `ObjectID` (numeric, referenced with `ObjectRef`) or an `ObjectUID` (GUID, referenced with
+ * `ObjectURef`); everything else is a graph of those references:
+ *
+ * RootProjectItem / BinProjectItem -> ProjectItemContainer > Items > Item (ObjectURef)
+ * ClipProjectItem -> MasterClip (ObjectURef) -> Clips > Clip (ObjectRef) -> VideoClip | AudioClip
+ * -> Clip > Source (ObjectRef) -> VideoMediaSource | AudioMediaSource -> MediaSource > Media (ObjectURef)
+ * -> Media: FilePath / ActualMediaFilePath / RelativePath, VideoStream, AudioStream
+ * Sequence -> TrackGroups > TrackGroup (First = 0 video / 1 audio, Second = ObjectRef)
+ * -> VideoTrackGroup | AudioTrackGroup -> TrackGroup > Tracks > Track (ObjectURef)
+ * -> VideoClipTrack | AudioClipTrack -> ClipTrack > ClipItems > TrackItems > TrackItem (ObjectRef) (+ TransitionItems)
+ * -> VideoClipTrackItem | AudioClipTrackItem -> ClipTrackItem > TrackItem > Start / End (ticks),
+ * SubClip (ObjectRef) -> Clip (ObjectRef, the VideoClip / AudioClip with InPoint / OutPoint) and
+ * ComponentOwner > Components (ObjectRef) -> VideoComponentChain -> VideoFilterComponent -> Params
+ *
+ * Premiere does not document the format. The element names above come from the structure of saved projects as
+ * far as it is publicly described; reads are tolerant (a name is looked up anywhere inside its object, a few
+ * alternative spellings are accepted). The tests use hand-authored fixtures that follow this layout; a file
+ * Premiere itself wrote has not been available for verification. Anything the importer cannot place ends up in the
+ * import report rather than disappearing.
+ */
+
+/** Premiere's time base: every time in a .prproj is an integer count of 1 / 254016000000 s. */
+export const TICKS_PER_SECOND = 254_016_000_000n;
+const TICKS_NUMBER = Number(TICKS_PER_SECOND);
+/** Decompressed size cap: a project this large is a bomb or a corrupt file, not an edit. */
+const MAX_XML_BYTES = 768 * 1024 * 1024;
+
+// ── tick math ───────────────────────────────────────────────────────────────
+
+/** Parse a tick count (plain integer text, possibly negative). Anything else is undefined. */
+export function parseTicks(text: string | undefined): bigint | undefined {
+ if (text === undefined) return undefined;
+ const trimmed = text.trim();
+ return /^-?\d+$/.test(trimmed) ? BigInt(trimmed) : undefined;
+}
+
+/** Ticks to seconds, exact for the whole-second part (beyond 2^53 ticks a plain Number division would lose frames). */
+export function ticksToSeconds(ticks: bigint): number {
+ const whole = ticks / TICKS_PER_SECOND;
+ const rest = ticks % TICKS_PER_SECOND;
+ return Number(whole) + Number(rest) / TICKS_NUMBER;
+}
+
+const floorDiv = (a: bigint, b: bigint): bigint => {
+ const q = a / b;
+ return a % b !== 0n && a < 0n !== b < 0n ? q - 1n : q;
+};
+
+/** Ticks to whole frames of `rate`, rounded to the nearest frame (exact rational arithmetic). */
+export function ticksToFrames(ticks: bigint, rate: FrameRate): number {
+ const num = BigInt(rate.num);
+ const den = BigInt(rate.den);
+ const scaled = ticks * num;
+ const unit = TICKS_PER_SECOND * den;
+ return Number(floorDiv(scaled * 2n + unit, unit * 2n));
+}
+
+/** Frame rate from Premiere's "ticks per frame" (`FrameRate` of a stream or track group). */
+export function frameRateFromTicksPerFrame(ticksPerFrame: bigint): FrameRate | undefined {
+ if (ticksPerFrame <= 0n) return undefined;
+ const fps = TICKS_NUMBER / Number(ticksPerFrame);
+ return Number.isFinite(fps) && fps > 0 && fps < 1000 ? resolveFrameRate(fps) : undefined;
+}
+
+// ── gzip ────────────────────────────────────────────────────────────────────
+
+export const looksLikeGzip = (bytes: Uint8Array): boolean => bytes.length > 18 && bytes[0] === 0x1f && bytes[1] === 0x8b;
+
+/** True for a .prproj: a gzip stream, or the uncompressed `<PremiereData` XML some tools write. */
+export function looksLikePrproj(bytes: Uint8Array): boolean {
+ if (looksLikeGzip(bytes)) return true;
+ const head = new TextDecoder("utf-8").decode(bytes.subarray(0, Math.min(bytes.length, 2048)));
+ return /<PremiereData[\s>]/.test(head);
+}
+
+function gunzipSync(bytes: Uint8Array): Uint8Array {
+ // Header: ID1 ID2 CM FLG MTIME(4) XFL OS, then optional extra / name / comment / header crc.
+ const flags = bytes[3];
+ let pos = 10;
+ if (flags & 4) pos += 2 + (bytes[pos] | (bytes[pos + 1] << 8));
+ if (flags & 8) while (pos < bytes.length && bytes[pos++] !== 0);
+ if (flags & 16) while (pos < bytes.length && bytes[pos++] !== 0);
+ if (flags & 2) pos += 2;
+ // ISIZE (last 4 bytes) is the uncompressed length modulo 2^32: a good first guess for the output buffer.
+ const view = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength);
+ const size = view.getUint32(bytes.length - 4, true);
+ return inflateRaw(bytes.subarray(pos, bytes.length - 8), size > 0 && size < MAX_XML_BYTES ? size : 0).subarray(0, size > 0 ? size : undefined);
+}
+
+/**
+ * Gunzip with the platform's DecompressionStream (browsers, workers, Node 18+) and a dependency-free inflate
+ * fallback. The output is capped at 768 MB.
+ */
+export async function gunzip(bytes: Uint8Array): Promise<Uint8Array> {
+ if (!looksLikeGzip(bytes)) return bytes;
+ const Stream = (globalThis as { DecompressionStream?: new (format: string) => { readable: ReadableStream<Uint8Array>; writable: WritableStream<Uint8Array> } }).DecompressionStream;
+ if (!Stream) return gunzipSync(bytes);
+ const stream = new Stream("gzip");
+ const writer = stream.writable.getWriter();
+ const writing = writer.write(bytes as unknown as Uint8Array).then(() => writer.close());
+ const reader = stream.readable.getReader();
+ const chunks: Uint8Array[] = [];
+ let total = 0;
+ try {
+ for (;;) {
+ const { done, value } = await reader.read();
+ if (done) break;
+ total += value.length;
+ if (total > MAX_XML_BYTES) throw new Error("This project file decompresses to more than 768 MB and was not read.");
+ chunks.push(value);
+ }
+ await writing;
+ } catch (error) {
+ await reader.cancel().catch(() => undefined);
+ writing.catch(() => undefined);
+ throw error instanceof Error && /768 MB/.test(error.message) ? error : new Error("The project file is not valid gzip data.");
+ }
+ const out = new Uint8Array(total);
+ let at = 0;
+ for (const chunk of chunks) {
+ out.set(chunk, at);
+ at += chunk.length;
+ }
+ return out;
+}
+
+// ── object graph ────────────────────────────────────────────────────────────
+
+export interface PrprojDocument {
+ readonly root: XmlElement;
+ readonly version: string;
+ /** Top-level objects by `id:<ObjectID>` / `uid:<ObjectUID>`. */
+ readonly objects: ReadonlyMap<string, XmlElement>;
+}
+
+export interface PrprojSequenceInfo {
+ readonly id: string;
+ readonly name: string;
+ readonly width: number;
+ readonly height: number;
+ readonly fps: number;
+ readonly videoTracks: number;
+ readonly audioTracks: number;
+ readonly clipCount: number;
+ /** Used as a nested sequence by another sequence. */
+ readonly nested: boolean;
+}
+
+/** Parse the decompressed project XML into an object index. */
+export function parsePrprojXml(xml: string): PrprojDocument {
+ const root = parseXml(xml);
+ if (root.name !== "PremiereData") throw new Error("This is not an Adobe Premiere Pro project (no PremiereData element).");
+ const objects = new Map<string, XmlElement>();
+ for (const el of root.children) {
+ if (el.attrs.ObjectID !== undefined) objects.set(`id:${el.attrs.ObjectID}`, el);
+ if (el.attrs.ObjectUID !== undefined) objects.set(`uid:${el.attrs.ObjectUID}`, el);
+ }
+ return { root, version: root.attrs.Version ?? "", objects };
+}
+
+/** Gunzip (when compressed) and parse a .prproj. */
+export async function readPrproj(bytes: Uint8Array): Promise<PrprojDocument> {
+ const raw = await gunzip(bytes);
+ return parsePrprojXml(new TextDecoder("utf-8").decode(raw));
+}
+
+/** The object an `ObjectRef` / `ObjectURef` element points at. */
+export function resolveRef(doc: PrprojDocument, el: XmlElement | undefined): XmlElement | undefined {
+ if (!el) return undefined;
+ if (el.attrs.ObjectRef !== undefined) return doc.objects.get(`id:${el.attrs.ObjectRef}`);
+ if (el.attrs.ObjectURef !== undefined) return doc.objects.get(`uid:${el.attrs.ObjectURef}`);
+ return undefined;
+}
+
+const hasRef = (el: XmlElement): boolean => el.attrs.ObjectRef !== undefined || el.attrs.ObjectURef !== undefined;
+
+/** First descendant (depth first, document order) with this element name. */
+function dig(el: XmlElement | undefined, name: string): XmlElement | undefined {
+ if (!el) return undefined;
+ for (const c of el.children) {
+ if (c.name === name) return c;
+ const deeper = dig(c, name);
+ if (deeper) return deeper;
+ }
+ return undefined;
+}
+
+const digText = (el: XmlElement | undefined, ...names: string[]): string | undefined => {
+ for (const name of names) {
+ const found = dig(el, name);
+ if (found && found.children.length === 0 && !hasRef(found)) return found.text;
+ }
+ return undefined;
+};
+
+const digTicks = (el: XmlElement | undefined, ...names: string[]): bigint | undefined => {
+ for (const name of names) {
+ const value = parseTicks(digText(el, name));
+ if (value !== undefined) return value;
+ }
+ return undefined;
+};
+
+const digNumber = (el: XmlElement | undefined, ...names: string[]): number | undefined => {
+ const text = digText(el, ...names);
+ if (text === undefined || text === "") return undefined;
+ const value = Number(text);
+ return Number.isFinite(value) ? value : undefined;
+};
+
+const digBool = (el: XmlElement | undefined, ...names: string[]): boolean | undefined => {
+ const text = digText(el, ...names)?.toLowerCase();
+ if (text === undefined || text === "") return undefined;
+ if (text === "true" || text === "1") return true;
+ if (text === "false" || text === "0") return false;
+ return undefined;
+};
+
+/** The object the first descendant named `name` points at. */
+function digRef(doc: PrprojDocument, el: XmlElement | undefined, name: string): XmlElement | undefined {
+ if (!el) return undefined;
+ for (const c of el.children) {
+ if (c.name === name && hasRef(c)) return resolveRef(doc, c);
+ const deeper = digRef(doc, c, name);
+ if (deeper) return deeper;
+ }
+ return undefined;
+}
+
+/** Every referenced object below `el`, in `Index` order (list wrappers like Tracks, TrackItems, Items). */
+function refsIn(doc: PrprojDocument, el: XmlElement | undefined): XmlElement[] {
+ const found: { index: number; order: number; el: XmlElement }[] = [];
+ const walk = (node: XmlElement) => {
+ for (const c of node.children) {
+ if (hasRef(c)) {
+ const target = resolveRef(doc, c);
+ if (target) found.push({ index: Number(c.attrs.Index ?? found.length), order: found.length, el: target });
+ } else walk(c);
+ }
+ };
+ if (el) walk(el);
+ return found.sort((a, b) => a.index - b.index || a.order - b.order).map((f) => f.el);
+}
+
+const rectOf = (el: XmlElement | undefined): { width: number; height: number } | undefined => {
+ const text = digText(el, "FrameRect");
+ if (!text) return undefined;
+ const parts = text.split(",").map(Number);
+ if (parts.length < 4 || parts.some((p) => !Number.isFinite(p))) return undefined;
+ const width = parts[2] - parts[0];
+ const height = parts[3] - parts[1];
+ return width > 0 && height > 0 ? { width, height } : undefined;
+};
+
+const objectsNamed = (doc: PrprojDocument, name: string): XmlElement[] => doc.root.children.filter((c) => c.name === name);
+
+const nameOf = (el: XmlElement | undefined): string => digText(el, "Name") ?? "";
+
+// ── project items (bins, master clips) ──────────────────────────────────────
+
+interface MasterInfo {
+ readonly name: string;
+ readonly binPath: readonly string[];
+}
+
+/** Bin path (outermost first) of every media object reachable through a master clip. */
+function collectBins(doc: PrprojDocument): { bins: string[][]; masters: MasterInfo[]; byMedia: Map<XmlElement, MasterInfo> } {
+ const bins: string[][] = [];
+ const masters: MasterInfo[] = [];
+ const byMedia = new Map<XmlElement, MasterInfo>();
+ const seen = new Set<XmlElement>();
+ const visit = (item: XmlElement, path: string[]) => {
+ if (seen.has(item)) return;
+ seen.add(item);
+ if (item.name === "RootProjectItem" || item.name === "BinProjectItem") {
+ const nextPath = item.name === "RootProjectItem" ? path : [...path, nameOf(item) || "Bin"];
+ if (item.name === "BinProjectItem") bins.push(nextPath);
+ const container = dig(item, "ProjectItemContainer");
+ for (const child of refsIn(doc, container)) visit(child, nextPath);
+ return;
+ }
+ if (item.name === "ClipProjectItem") {
+ const master = digRef(doc, item, "MasterClip");
+ const info: MasterInfo = { name: nameOf(item) || nameOf(master), binPath: path };
+ masters.push(info);
+ for (const clip of refsIn(doc, dig(master, "Clips"))) {
+ const media = mediaOfClip(doc, clip);
+ if (media && !byMedia.has(media)) byMedia.set(media, info);
+ }
+ }
+ };
+ for (const root of objectsNamed(doc, "RootProjectItem")) visit(root, []);
+ // Bins nobody lists under a root (damaged projects) are still read.
+ for (const bin of objectsNamed(doc, "BinProjectItem")) visit(bin, []);
+ for (const item of objectsNamed(doc, "ClipProjectItem")) visit(item, []);
+ return { bins, masters, byMedia };
+}
+
+/** The Media object a VideoClip / AudioClip plays (Clip > Source > MediaSource > Media). */
+function mediaOfClip(doc: PrprojDocument, clip: XmlElement | undefined): XmlElement | undefined {
+ const source = digRef(doc, clip, "Source");
+ return digRef(doc, source, "Media");
+}
+
+/** The sequence a VideoClip / AudioClip plays when its source is a nested sequence. */
+function sequenceOfClip(doc: PrprojDocument, clip: XmlElement | undefined): XmlElement | undefined {
+ const source = digRef(doc, clip, "Source");
+ const nested = digRef(doc, source, "Sequence");
+ return nested?.name === "Sequence" ? nested : undefined;
+}
+
+// ── sequences ───────────────────────────────────────────────────────────────
+
+interface TrackGroups {
+ readonly video: XmlElement[];
+ readonly audio: XmlElement[];
+}
+
+function trackGroupsOf(doc: PrprojDocument, sequence: XmlElement): TrackGroups {
+ const video: XmlElement[] = [];
+ const audio: XmlElement[] = [];
+ const groups = dig(sequence, "TrackGroups");
+ for (const entry of groups?.children ?? []) {
+ const group = resolveRef(doc, dig(entry, "Second") ?? entry);
+ if (!group) continue;
+ // `First` is the media type (0 video, 1 audio); the object name says the same.
+ const first = digText(entry, "First");
+ const isAudio = /^Audio/.test(group.name) || (!/^Video/.test(group.name) && first === "1");
+ (isAudio ? audio : video).push(group);
+ }
+ return { video, audio };
+}
+
+const tracksOf = (doc: PrprojDocument, group: XmlElement): XmlElement[] => refsIn(doc, dig(group, "Tracks"));
+
+const itemsOf = (doc: PrprojDocument, track: XmlElement, listName: string): XmlElement[] => refsIn(doc, dig(track, listName));
+
+function countClips(doc: PrprojDocument, sequence: XmlElement): number {
+ const groups = trackGroupsOf(doc, sequence);
+ let total = 0;
+ for (const group of [...groups.video, ...groups.audio]) {
+ for (const track of tracksOf(doc, group)) total += itemsOf(doc, track, "ClipItems").length;
+ }
+ return total;
+}
+
+const sequenceId = (sequence: XmlElement): string => sequence.attrs.ObjectUID ?? `id:${sequence.attrs.ObjectID ?? ""}`;
+
+function sequenceSize(sequence: XmlElement, groups: TrackGroups): { rate: FrameRate; width: number; height: number } {
+ let rate: FrameRate | undefined;
+ let size: { width: number; height: number } | undefined;
+ for (const group of groups.video) {
+ const tpf = digTicks(group, "FrameRate");
+ rate = rate ?? (tpf !== undefined ? frameRateFromTicksPerFrame(tpf) : undefined);
+ size = size ?? rectOf(group);
+ }
+ rate = rate ?? frameRateFromTicksPerFrame(digTicks(sequence, "FrameRate") ?? 0n);
+ size = size ?? rectOf(sequence);
+ // Audio-only sequences carry no frame rate: 24 is Premiere's default editing timebase.
+ return { rate: rate ?? resolveFrameRate(24), width: size?.width ?? 1920, height: size?.height ?? 1080 };
+}
+
+/** Every sequence of the project, with what is needed to let the user pick one. */
+export function listPrprojSequences(doc: PrprojDocument): PrprojSequenceInfo[] {
+ const sequences = objectsNamed(doc, "Sequence");
+ const nestedIds = new Set<string>();
+ for (const clip of [...objectsNamed(doc, "VideoClip"), ...objectsNamed(doc, "AudioClip")]) {
+ const nested = sequenceOfClip(doc, clip);
+ if (nested) nestedIds.add(sequenceId(nested));
+ }
+ return sequences.map((sequence) => {
+ const groups = trackGroupsOf(doc, sequence);
+ const { rate, width, height } = sequenceSize(sequence, groups);
+ return {
+ id: sequenceId(sequence),
+ name: nameOf(sequence) || "Sequence",
+ width,
+ height,
+ fps: fpsOf(rate),
+ videoTracks: groups.video.reduce((n, g) => n + tracksOf(doc, g).length, 0),
+ audioTracks: groups.audio.reduce((n, g) => n + tracksOf(doc, g).length, 0),
+ clipCount: countClips(doc, sequence),
+ nested: nestedIds.has(sequenceId(sequence)),
+ };
+ });
+}
+
+/** The sequence to open by default: the biggest one that no other sequence nests. */
+export function defaultPrprojSequence(sequences: readonly PrprojSequenceInfo[]): PrprojSequenceInfo | undefined {
+ const pool = sequences.some((s) => !s.nested) ? sequences.filter((s) => !s.nested) : sequences;
+ return pool.reduce<PrprojSequenceInfo | undefined>((best, s) => (!best || s.clipCount > best.clipCount ? s : best), undefined);
+}
+
+// ── clip components (Motion, Opacity, Volume) ───────────────────────────────
+
+interface ParamValue {
+ readonly values: number[];
+ readonly animated: boolean;
+}
+
+function parseParam(param: XmlElement): ParamValue {
+ const numbers = (text: string): number[] => text.split(/[:,;\s]+/).filter(Boolean).map(Number).filter((n) => Number.isFinite(n));
+ let values: number[] = [];
+ const current = digText(param, "CurrentValue");
+ if (current) values = numbers(current);
+ const start = digText(param, "StartKeyframe");
+ if (values.length === 0 && start) {
+ // "time,value[,...];" keyframe records; the first record's value is the start value.
+ const fields = start.split(";")[0].split(",");
+ values = numbers(fields.slice(1, 2).join(","));
+ if (fields[1]?.includes(":")) values = numbers(fields[1]);
+ }
+ const keyframes = dig(param, "Keyframes");
+ const animated = digBool(param, "IsTimeVarying") === true || (keyframes !== undefined && keyframes.children.length > 1);
+ return { values, animated };
+}
+
+interface ComponentInfo {
+ readonly match: string;
+ readonly display: string;
+ readonly params: Map<string, ParamValue>;
+}
+
+function componentsOf(doc: PrprojDocument, item: XmlElement): ComponentInfo[] {
+ const chain = digRef(doc, dig(item, "ComponentOwner"), "Components");
+ const out: ComponentInfo[] = [];
+ for (const component of refsIn(doc, chain)) {
+ const params = new Map<string, ParamValue>();
+ for (const paramEl of refsIn(doc, dig(component, "Params"))) {
+ const name = nameOf(paramEl);
+ if (name) params.set(name.toLowerCase(), parseParam(paramEl));
+ }
+ out.push({ match: digText(component, "MatchName") ?? "", display: digText(component, "DisplayName") ?? digText(component, "InstanceName") ?? "", params });
+ }
+ return out;
+}
+
+const is = (c: ComponentInfo, ...needles: string[]): boolean => needles.some((n) => c.match.toLowerCase().includes(n) || c.display.toLowerCase() === n);
+
+interface ClipLook {
+ opacity: number;
+ volume: number;
+ motion?: SeqClip["motion"];
+}
+
+/** Position values at or below this are Premiere's normalised frame coordinates (0.5 = centre), above it pixels. */
+const NORMALISED_POSITION_LIMIT = 4;
+
+function readLook(
+ components: readonly ComponentInfo[],
+ seq: { width: number; height: number },
+ clipLabel: string,
+ trackName: string,
+ items: ReportItem[],
+): ClipLook {
+ const where = { clipName: clipLabel, trackName };
+ const look: ClipLook = { opacity: 1, volume: 1 };
+ let x = 0;
+ let y = 0;
+ let scale = 1;
+ let rotation = 0;
+ let hasMotion = false;
+ for (const c of components) {
+ if (is(c, "adbe motion")) {
+ const position = c.params.get("position");
+ if (position && position.values.length >= 2) {
+ const [px, py] = position.values;
+ const pixels = Math.abs(px) > NORMALISED_POSITION_LIMIT || Math.abs(py) > NORMALISED_POSITION_LIMIT;
+ x = pixels ? px - seq.width / 2 : (px - 0.5) * seq.width;
+ y = pixels ? py - seq.height / 2 : (py - 0.5) * seq.height;
+ if (Math.abs(x) > 0.5 || Math.abs(y) > 0.5) hasMotion = true;
+ if (position.animated) items.push({ severity: "approximated", feature: "Animated position", detail: "Position keyframes are not imported; the start value is used.", ...where });
+ }
+ const scaleParam = c.params.get("scale");
+ if (scaleParam && scaleParam.values.length >= 1) {
+ scale = scaleParam.values[0] / 100;
+ if (Math.abs(scale - 1) > 1e-6) hasMotion = true;
+ if (scaleParam.animated) items.push({ severity: "approximated", feature: "Animated scale", detail: "Scale keyframes are not imported; the start value is used.", ...where });
+ }
+ const uniform = c.params.get("uniform scale");
+ const width = c.params.get("scale width");
+ if (uniform && uniform.values[0] === 0 && width && width.values[0] !== undefined && scaleParam && Math.abs(width.values[0] - scaleParam.values[0]) > 1e-6) {
+ items.push({ severity: "approximated", feature: "Non-uniform scale", detail: "Scale Width and Scale Height differ; the single Scale value is used.", ...where });
+ }
+ const rot = c.params.get("rotation");
+ if (rot && rot.values.length >= 1) {
+ rotation = rot.values[0];
+ if (Math.abs(rotation) > 1e-6) hasMotion = true;
+ if (rot.animated) items.push({ severity: "approximated", feature: "Animated rotation", detail: "Rotation keyframes are not imported; the start value is used.", ...where });
+ }
+ const anchor = c.params.get("anchor point");
+ if (anchor && anchor.values.length >= 2 && (Math.abs(anchor.values[0] - 0.5) > 1e-4 || Math.abs(anchor.values[1] - 0.5) > 1e-4) && Math.abs(anchor.values[0]) <= NORMALISED_POSITION_LIMIT) {
+ items.push({ severity: "dropped", feature: "Anchor point", detail: "A moved anchor point is not imported (OpenReel rotates and scales around the centre).", ...where });
+ }
+ continue;
+ }
+ if (is(c, "adbe opacity")) {
+ const opacity = c.params.get("opacity");
+ if (opacity && opacity.values.length >= 1) {
+ look.opacity = Math.max(0, Math.min(1, opacity.values[0] / 100));
+ if (opacity.animated) items.push({ severity: "approximated", feature: "Animated opacity", detail: "Opacity keyframes are not imported; the start value is used.", ...where });
+ }
+ const blend = c.params.get("blend mode");
+ if (blend && blend.values[0] !== undefined && blend.values[0] !== 0) {
+ items.push({ severity: "dropped", feature: "Blend mode", detail: "The blend mode is not imported; the clip uses Normal.", ...where });
+ }
+ continue;
+ }
+ if (is(c, "adbe volume", "volume") && !is(c, "channel volume")) {
+ const level = c.params.get("level");
+ if (level && level.values.length >= 1) {
+ // Level is the linear amplitude (1 = 0 dB).
+ look.volume = Math.max(0, level.values[0]);
+ if (level.animated) items.push({ severity: "approximated", feature: "Animated volume", detail: "Volume keyframes are not imported; the start value is used.", ...where });
+ }
+ continue;
+ }
+ if (is(c, "time remapping")) {
+ items.push({ severity: "dropped", feature: "Time remapping", detail: "Speed ramps and time remapping keyframes are not imported; the constant clip speed is used.", ...where });
+ continue;
+ }
+ const label = c.display || c.match || "Unnamed effect";
+ items.push({ severity: "dropped", feature: `Effect: ${label}`, detail: "Effects other than Motion, Opacity and Volume are not imported.", ...where });
+ }
+ if (hasMotion) {
+ look.motion = { x, y, scale, rotation };
+ if (Math.abs(scale - 1) > 1e-6 || Math.abs(x) > 0.5 || Math.abs(y) > 0.5) {
+ items.push({
+ severity: "approximated",
+ feature: "Motion",
+ detail: "Premiere sizes media from its native pixels; OpenReel fits the frame first and then applies the scale, so the framing can differ.",
+ ...where,
+ });
+ }
+ }
+ return look;
+}
+
+// ── building the neutral sequence ───────────────────────────────────────────
+
+export interface PrprojOptions {
+ /** The sequence to import (ObjectUID from `listPrprojSequences`); default: the biggest top-level one. */
+ sequenceId?: string;
+}
+
+const MARKER_TYPES: Record<string, MarkerKind> = { chapter: "chapter", segmentation: "segmentation", weblink: "web", flashcuepoint: "chapter" };
+
+const kindOfAudio = /\.(wav|mp3|aac|m4a|aif|aiff|flac|ogg|opus|wma)$/i;
+const kindOfImage = /\.(jpe?g|png|gif|bmp|tiff?|webp|heic|psd|ai|svg|dng)$/i;
+
+function pathToUrl(path: string): string {
+ const unix = path.replace(/\\/g, "/");
+ const windows = /^[a-zA-Z]:\//.test(unix) ? `/${unix}` : unix;
+ const encoded = windows.split("/").map((part) => encodeURIComponent(part)).join("/");
+ return `file://localhost${encoded.startsWith("/") ? "" : "/"}${encoded}`;
+}
+
+const basename = (path: string): string => path.replace(/\\/g, "/").split("/").pop() ?? path;
+
+interface BuildContext {
+ readonly doc: PrprojDocument;
+ readonly items: ReportItem[];
+ readonly warnings: string[];
+ readonly masters: Map<XmlElement, MasterInfo>;
+ readonly mediaByObject: Map<XmlElement, SeqMedia>;
+ readonly nests: Map<XmlElement, Sequence | null>;
+ readonly building: Set<XmlElement>;
+ linkedAudioMerged: number;
+}
+
+function mediaFor(ctx: BuildContext, mediaEl: XmlElement, clipEl: XmlElement, label: string, trackKind: "video" | "audio", seqRate: FrameRate, seq: { width: number; height: number }): SeqMedia | undefined {
+ const known = ctx.mediaByObject.get(mediaEl);
+ if (known) return known;
+ const path = digText(mediaEl, "ActualMediaFilePath") || digText(mediaEl, "FilePath") || digText(mediaEl, "RelativePath") || "";
+ const videoStream = digRef(ctx.doc, mediaEl, "VideoStream");
+ const audioStream = digRef(ctx.doc, mediaEl, "AudioStream");
+ const name = path ? basename(path) : digText(mediaEl, "Title") || label;
+ const ext = name.toLowerCase();
+ let kind: SeqMedia["kind"];
+ if (kindOfImage.test(ext)) kind = "image";
+ else if (videoStream) kind = "video";
+ else if (audioStream || kindOfAudio.test(ext)) kind = "audio";
+ else kind = trackKind === "audio" ? "audio" : "video";
+ const streamTpf = digTicks(videoStream, "FrameRate");
+ const rate = (streamTpf !== undefined ? frameRateFromTicksPerFrame(streamTpf) : undefined) ?? seqRate;
+ const rect = rectOf(videoStream) ?? rectOf(clipEl);
+ const source = digRef(ctx.doc, clipEl, "Source");
+ const duration = digTicks(source, "OriginalDuration") ?? digTicks(mediaEl, "Duration", "OriginalDuration");
+ const info = ctx.masters.get(mediaEl);
+ const sampleRate = digNumber(audioStream, "SampleRate", "AudioSampleRate") ?? 48000;
+ const channels = digNumber(audioStream, "NumChannels", "ChannelCount") ?? 2;
+ if (!path) {
+ ctx.items.push({ severity: "approximated", feature: "Media without a file path", detail: `"${name}" has no file path in the project; it is added as an offline placeholder.`, clipName: name });
+ }
+ const media: SeqMedia = {
+ key: mediaEl.attrs.ObjectUID ?? `id:${mediaEl.attrs.ObjectID ?? name}`,
+ name,
+ ...(path ? { pathUrl: pathToUrl(path) } : {}),
+ kind,
+ durationSec: duration !== undefined && duration > 0n && duration < 1n << 60n ? ticksToSeconds(duration) : 0,
+ rate,
+ width: rect?.width ?? seq.width,
+ height: rect?.height ?? seq.height,
+ hasVideo: kind !== "audio" && (videoStream !== undefined || kind === "image" || trackKind === "video"),
+ hasAudio: kind === "audio" || audioStream !== undefined,
+ sampleRate,
+ channels,
+ ...(info?.binPath.length ? { binPath: info.binPath } : {}),
+ };
+ ctx.mediaByObject.set(mediaEl, media);
+ return media;
+}
+
+function transitionKind(name: string): { kind: SeqTransitionKind; exact: boolean } | undefined {
+ const n = name.toLowerCase();
+ if (/cross dissolve|adbe cross dissolve/.test(n)) return { kind: "dissolve", exact: true };
+ if (/dip to black/.test(n)) return { kind: "dipToBlack", exact: true };
+ if (/dip to white/.test(n)) return { kind: "dipToWhite", exact: true };
+ if (/additive dissolve|film dissolve|non-additive|dissolve/.test(n)) return { kind: "dissolve", exact: false };
+ return undefined;
+}
+
+function buildSequence(ctx: BuildContext, sequenceEl: XmlElement, isNest: boolean): Sequence {
+ const { doc } = ctx;
+ const groups = trackGroupsOf(doc, sequenceEl);
+ const { rate, width, height } = sequenceSize(sequenceEl, groups);
+ const seqName = nameOf(sequenceEl) || "Imported Sequence";
+ const prefix = isNest ? `${seqName} / ` : "";
+ const sizeInfo = { width, height };
+ const used = new Map<string, SeqMedia>();
+
+ interface Built {
+ clip: SeqClip;
+ kind: "video" | "audio";
+ }
+
+ const buildTrack = (trackEl: XmlElement, kind: "video" | "audio", index: number): { track: SeqTrack; built: Built[] } => {
+ const trackName = nameOf(trackEl) && !/^(video|audio) \d+$/i.test(nameOf(trackEl)) ? nameOf(trackEl) : kind === "video" ? `V${index + 1}` : `A${index + 1}`;
+ const where = `${prefix}${trackName}`;
+ const built: Built[] = [];
+ const itemEls = itemsOf(doc, trackEl, "ClipItems");
+ for (const item of itemEls) {
+ const isVideoItem = /^Video/.test(item.name);
+ const isAudioItem = /^Audio/.test(item.name);
+ const label = nameOf(dig(item, "SubClip") ? digRef(doc, item, "SubClip") : item) || nameOf(item) || "Clip";
+ if ((kind === "video" && !isVideoItem) || (kind === "audio" && !isAudioItem) || !/ClipTrackItem$/.test(item.name)) {
+ ctx.items.push({ severity: "dropped", feature: "Unsupported clip type", detail: `${item.name} items (titles, captions, graphics) are not imported.`, clipName: label, trackName: where });
+ continue;
+ }
+ const start = digTicks(item, "Start");
+ const end = digTicks(item, "End");
+ if (start === undefined || end === undefined || end <= start) {
+ ctx.warnings.push(`Clip "${label}" on ${where} has no valid start and end and was skipped.`);
+ ctx.items.push({ severity: "dropped", feature: "Invalid clip", detail: "The clip has no valid start and end time.", clipName: label, trackName: where });
+ continue;
+ }
+ const subClip = digRef(doc, item, "SubClip");
+ const clipObj = digRef(doc, subClip, "Clip") ?? digRef(doc, item, "Clip");
+ const startFrame = ticksToFrames(start, rate);
+ const endFrame = Math.max(startFrame + 1, ticksToFrames(end, rate));
+ const durationTicks = end - start;
+ const inTicksRaw = digTicks(clipObj, "InPoint");
+ const outTicksRaw = digTicks(clipObj, "OutPoint");
+ // Premiere writes sentinel out points (INT64_MAX) for "whole clip"; treat anything absurd as missing.
+ const sane = (t: bigint | undefined): bigint | undefined => (t !== undefined && t >= 0n && t < 1n << 60n ? t : undefined);
+ const inTicks = sane(inTicksRaw) ?? 0n;
+ let outTicks = sane(outTicksRaw);
+ const explicitSpeed = digNumber(item, "Speed", "PlaybackSpeed") ?? digNumber(subClip, "Speed", "PlaybackSpeed") ?? digNumber(clipObj, "Speed", "PlaybackSpeed");
+ const reversedFlag = digBool(item, "Reversed", "Reverse", "PlayBackwards") ?? digBool(subClip, "Reversed", "Reverse", "PlayBackwards") ?? digBool(clipObj, "Reversed", "Reverse", "PlayBackwards") ?? false;
+ let speed = 1;
+ if (explicitSpeed !== undefined && Math.abs(explicitSpeed) > 1e-6) {
+ speed = Math.abs(explicitSpeed);
+ if (outTicks === undefined) outTicks = inTicks + BigInt(Math.round(Number(durationTicks) * speed));
+ } else if (outTicks !== undefined && outTicks > inTicks) {
+ const ratio = Number(outTicks - inTicks) / Number(durationTicks);
+ speed = Math.abs(ratio - 1) > 0.001 ? ratio : 1;
+ }
+ if (outTicks === undefined) outTicks = inTicks + durationTicks;
+ const reversed = reversedFlag || (explicitSpeed !== undefined && explicitSpeed < 0);
+ if (speed < 0.01 || speed > 100) {
+ ctx.items.push({ severity: "approximated", feature: "Extreme speed", detail: `Speed ${speed.toFixed(3)}x is outside OpenReel's range; imported at 1x.`, clipName: label, trackName: where });
+ speed = 1;
+ }
+
+ const disabled = digBool(item, "Disabled", "IsDisabled") === true || digBool(item, "Enabled", "IsEnabled") === false;
+ if (disabled) {
+ ctx.items.push({ severity: "approximated", feature: "Disabled clip", detail: "OpenReel has no clip enable switch; the clip is imported fully transparent and muted so it plays as disabled.", clipName: label, trackName: where });
+ }
+ const look = readLook(componentsOf(doc, item), sizeInfo, label, where, ctx.items);
+ const base: Omit<SeqClip, "mediaKey"> = {
+ id: `prproj-${item.attrs.ObjectID ?? built.length}-${index}`,
+ name: label,
+ startFrame,
+ endFrame,
+ inSec: ticksToSeconds(inTicks),
+ outSec: ticksToSeconds(outTicks),
+ speed,
+ reversed,
+ opacity: look.opacity,
+ volume: look.volume,
+ withAudio: false,
+ ...(look.motion ? { motion: look.motion } : {}),
+ ...(disabled ? { disabled: true } : {}),
+ metadata: { prproj: { sequence: seqName, track: where, objectId: item.attrs.ObjectID ?? null } },
+ };
+
+ const nestedEl = sequenceOfClip(doc, clipObj);
+ if (nestedEl) {
+ let nested = ctx.nests.get(nestedEl);
+ if (nested === undefined) {
+ if (ctx.building.has(nestedEl)) {
+ ctx.warnings.push(`Nested sequence "${nameOf(nestedEl)}" contains itself; the clip "${label}" was skipped.`);
+ ctx.items.push({ severity: "dropped", feature: "Nested sequence", detail: "The nested sequence contains itself.", clipName: label, trackName: where });
+ continue;
+ }
+ ctx.building.add(nestedEl);
+ nested = { ...buildSequence(ctx, nestedEl, true), id: `prproj:${sequenceId(nestedEl)}` };
+ ctx.building.delete(nestedEl);
+ ctx.nests.set(nestedEl, nested);
+ }
+ if (!nested) continue;
+ built.push({ kind, clip: { ...base, mediaKey: "", nested } });
+ continue;
+ }
+ const mediaEl = mediaOfClip(doc, clipObj);
+ if (!mediaEl) {
+ ctx.items.push({ severity: "dropped", feature: "Clip without media", detail: "The clip has no media file (title, colour matte, adjustment layer or generated item) and was skipped.", clipName: label, trackName: where });
+ continue;
+ }
+ const media = mediaFor(ctx, mediaEl, clipObj as XmlElement, label, kind, rate, sizeInfo);
+ if (!media) continue;
+ used.set(media.key, media);
+ // Clip and master-clip markers are not read: they are listed once per project below.
+ built.push({ kind, clip: { ...base, mediaKey: media.key } });
+ }
+
+ // Transitions.
+ const transitions: SeqTransition[] = [];
+ const clips = built.map((b) => b.clip).sort((a, b) => a.startFrame - b.startFrame);
+ for (const tEl of itemsOf(doc, trackEl, "TransitionItems").concat(itemsOf(doc, trackEl, "Transitions"))) {
+ const name = digText(tEl, "TransitionName", "DisplayName", "MatchName") ?? digText(digRef(doc, dig(tEl, "ComponentOwner"), "Components") ?? undefined, "DisplayName", "MatchName") ?? nameOf(tEl) ?? "";
+ const label = name || "Transition";
+ if (kind === "audio") {
+ ctx.items.push({ severity: "dropped", feature: "Audio crossfade", detail: "Audio transitions are not imported.", clipName: label, trackName: where });
+ continue;
+ }
+ const match = transitionKind(name);
+ if (!match) {
+ ctx.items.push({ severity: "dropped", feature: `Transition: ${label}`, detail: "Only cross dissolve and dip to black / white transitions are imported.", clipName: label, trackName: where });
+ continue;
+ }
+ const ts = digTicks(tEl, "Start");
+ const te = digTicks(tEl, "End");
+ if (ts === undefined || te === undefined || te <= ts) continue;
+ const startFrame = ticksToFrames(ts, rate);
+ const endFrame = Math.max(startFrame + 1, ticksToFrames(te, rate));
+ const before = clips.find((c) => Math.abs(c.endFrame - startFrame) <= 1) ?? clips.find((c) => Math.abs(c.endFrame - (startFrame + endFrame) / 2) <= 1) ?? clips.find((c) => Math.abs(c.endFrame - endFrame) <= 1);
+ if (!before || !clips.some((c) => c !== before && Math.abs(c.startFrame - before.endFrame) <= 1)) {
+ ctx.items.push({ severity: "dropped", feature: "Transition at a clip edge", detail: "The transition is not between two adjacent clips (a fade at the start or end of a clip) and was skipped.", clipName: label, trackName: where });
+ continue;
+ }
+ const alignment: SeqTransition["alignment"] =
+ Math.abs(before.endFrame - startFrame) <= 1 ? "start" : Math.abs(before.endFrame - endFrame) <= 1 ? "end" : "center";
+ transitions.push({ kind: match.kind, startFrame, endFrame, alignment });
+ if (!match.exact) {
+ ctx.items.push({ severity: "approximated", feature: `Transition: ${label}`, detail: "Imported as a cross dissolve.", clipName: label, trackName: where });
+ }
+ }
+
+ const locked = digBool(trackEl, "IsLocked", "Locked") === true;
+ const muted = digBool(trackEl, "IsMuted", "Muted", "Mute") === true || digBool(trackEl, "IsHidden", "Hidden") === true || digBool(trackEl, "IsVisible", "Visible") === false;
+ const targeted = digBool(trackEl, "IsTargeted", "Targeted");
+ const syncLock = digBool(trackEl, "IsSyncLocked", "SyncLocked");
+ return {
+ built,
+ track: {
+ kind,
+ name: trackName,
+ clips,
+ transitions: transitions.sort((a, b) => a.startFrame - b.startFrame),
+ disabled: muted,
+ locked,
+ ...(syncLock !== undefined ? { syncLock } : {}),
+ ...(targeted ? { targeted: true } : {}),
+ },
+ };
+ };
+
+ const videoTracks = groups.video.flatMap((g) => tracksOf(doc, g)).map((t, i) => buildTrack(t, "video", i));
+ const audioTracks = groups.audio.flatMap((g) => tracksOf(doc, g)).map((t, i) => buildTrack(t, "audio", i));
+
+ // A video item and an audio item of the same file, range and speed are Premiere's linked pair: fold the audio into the video clip like the XMEML importer.
+ const videoByKey = new Map<string, SeqClip>();
+ for (const t of videoTracks) for (const b of t.built) if (!b.clip.nested) videoByKey.set(`${b.clip.mediaKey}|${b.clip.startFrame}|${b.clip.endFrame}|${b.clip.speed}|${b.clip.reversed}`, b.clip);
+ const absorbed = new Set<SeqClip>();
+ const folded = new Map<SeqClip, SeqClip>();
+ for (const t of audioTracks) {
+ for (const b of t.built) {
+ const c = b.clip;
+ if (c.nested || !used.get(c.mediaKey)?.hasVideo || !used.get(c.mediaKey)?.hasAudio) continue;
+ const v = videoByKey.get(`${c.mediaKey}|${c.startFrame}|${c.endFrame}|${c.speed}|${c.reversed}`);
+ if (v && !folded.has(v) && !!v.disabled === !!c.disabled) {
+ folded.set(v, c);
+ absorbed.add(c);
+ ctx.linkedAudioMerged++;
+ }
+ }
+ }
+ const finishVideo = (clip: SeqClip): SeqClip => {
+ const audio = folded.get(clip);
+ return audio ? { ...clip, withAudio: true, volume: audio.volume } : clip;
+ };
+
+ const tracks: SeqTrack[] = [];
+ videoTracks.forEach((t) => tracks.push({ ...t.track, clips: t.track.clips.map(finishVideo) }));
+ let audioIndex = 0;
+ for (const t of audioTracks) {
+ const remaining = t.track.clips.filter((c) => !absorbed.has(c));
+ if (remaining.length === 0 && t.track.clips.length > 0) continue;
+ audioIndex += 1;
+ tracks.push({ ...t.track, clips: remaining, name: t.track.name.startsWith("A") && /^A\d+$/.test(t.track.name) ? `A${audioIndex}` : t.track.name });
+ }
+
+ // Sequence markers.
+ const markers: SeqMarker[] = [];
+ const markerOwner = digRef(doc, sequenceEl, "Markers");
+ const markerEls = [...refsIn(doc, markerOwner), ...(markerOwner ? markerOwner.children.filter((c) => c.name === "Marker" && !hasRef(c)) : [])];
+ for (const m of markerEls.length ? markerEls : sequenceEl.children.filter((c) => c.name === "Marker")) {
+ const at = digTicks(m, "Start");
+ if (at === undefined) continue;
+ const dur = digTicks(m, "Duration");
+ const frame = Math.max(0, ticksToFrames(at, rate));
+ const durationFrames = dur !== undefined && dur > 0n && dur < 1n << 60n ? ticksToFrames(at + dur, rate) - frame : 0;
+ const comment = digText(m, "Comment");
+ const kind = MARKER_TYPES[(digText(m, "Type") ?? "").toLowerCase()];
+ markers.push({
+ frame,
+ name: digText(m, "Name") ?? "",
+ ...(durationFrames > 0 ? { durationFrames } : {}),
+ ...(comment ? { comment } : {}),
+ ...(kind ? { kind } : {}),
+ });
+ }
+ markers.sort((a, b) => a.frame - b.frame);
+
+ const maxEnd = tracks.reduce((m, t) => t.clips.reduce((x, c) => Math.max(x, c.endFrame), m), 0);
+ return {
+ name: seqName,
+ rate,
+ width,
+ height,
+ durationFrames: maxEnd,
+ tracks,
+ markers,
+ media: [...used.values()],
+ };
+}
+
+const unusedClipMarkers = (doc: PrprojDocument): number => {
+ let count = 0;
+ for (const master of objectsNamed(doc, "MasterClip")) {
+ const owner = digRef(doc, master, "Markers");
+ if (owner) count += refsIn(doc, owner).length;
+ }
+ return count;
+};
+
+export interface PrprojParse {
+ readonly sequence: Sequence;
+ readonly report: ImportReport;
+ readonly warnings: string[];
+ readonly sequences: PrprojSequenceInfo[];
+ readonly selectedId: string;
+}
+
+/** Turn one sequence of a parsed project into the neutral sequence plus the import report. */
+export function prprojToSequence(doc: PrprojDocument, options: PrprojOptions = {}): PrprojParse {
+ const sequences = listPrprojSequences(doc);
+ if (sequences.length === 0) throw new Error("This Premiere project contains no sequences to import.");
+ const chosen = sequences.find((s) => s.id === options.sequenceId) ?? defaultPrprojSequence(sequences)!;
+ const sequenceEl = objectsNamed(doc, "Sequence").find((s) => sequenceId(s) === chosen.id)!;
+ const bins = collectBins(doc);
+ const ctx: BuildContext = {
+ doc,
+ items: [],
+ warnings: [],
+ masters: bins.byMedia,
+ mediaByObject: new Map(),
+ nests: new Map(),
+ building: new Set([sequenceEl]),
+ linkedAudioMerged: 0,
+ };
+ const sequence = buildSequence(ctx, sequenceEl, false);
+ const notes: string[] = [];
+ if (bins.masters.length) notes.push(`Read ${bins.masters.length} master clips in ${bins.bins.length} bins; the bins are recreated for media that is not already in the project.`);
+ if (ctx.linkedAudioMerged > 0) notes.push(`${ctx.linkedAudioMerged} audio clips linked to a video clip of the same file and range were merged into that video clip (its audio level is kept).`);
+ const others = sequences.filter((s) => s.id !== chosen.id && !ctx.nests.has(objectsNamed(doc, "Sequence").find((el) => sequenceId(el) === s.id)!));
+ if (others.length) notes.push(`${others.length} other ${others.length === 1 ? "sequence was" : "sequences were"} not imported (${others.map((s) => s.name).join(", ")}). Import the file again and choose another sequence to bring it in.`);
+ const markerCount = unusedClipMarkers(doc);
+ if (markerCount > 0) notes.push(`${markerCount} master-clip markers were not imported (sequence markers are).`);
+ notes.push("Not read: Lumetri colour and other effects, Essential Graphics and legacy titles, captions, adjustment layers, audio track mixer settings, Dynamic Link and Productions.");
+ const items = ctx.items;
+ return {
+ sequence,
+ warnings: ctx.warnings,
+ sequences,
+ selectedId: chosen.id,
+ report: {
+ items,
+ notes,
+ dropped: items.filter((i) => i.severity === "dropped").length,
+ approximated: items.filter((i) => i.severity === "approximated").length,
+ },
+ };
+}
+
+export interface PrprojImportResult extends TimelineImportResult {
+ readonly format: "prproj";
+ /** Every sequence of the file (for a picker) and the one this import holds. */
+ readonly prproj: { readonly sequences: PrprojSequenceInfo[]; readonly selectedId: string };
+}
+
+/** Parse a .prproj (gzip or plain XML bytes) and relink its media against the bin. */
+export async function importPrproj(bytes: Uint8Array, options: SequenceToTimelineOptions & PrprojOptions): Promise<PrprojImportResult> {
+ return importPrprojDocument(await readPrproj(bytes), options);
+}
+
+/** Same as `importPrproj` for an already parsed document (switching sequences without re-reading the file). */
+export function importPrprojDocument(doc: PrprojDocument, options: SequenceToTimelineOptions & PrprojOptions): PrprojImportResult {
+ const parsed = prprojToSequence(doc, options);
+ const result = sequenceToTimeline(parsed.sequence, options, parsed.warnings);
+ return {
+ ...result,
+ importReport: parsed.report,
+ format: "prproj",
+ prproj: { sequences: parsed.sequences, selectedId: parsed.selectedId },
+ };
+}
+
diff --git a/packages/core/src/motion/index.ts b/packages/core/src/motion/index.ts
index 3232424b..814d14c9 100644
--- a/packages/core/src/motion/index.ts
+++ b/packages/core/src/motion/index.ts
@@ -39,7 +39,11 @@ export * from "./motion-gpu-blend";
export * from "./motion-gpu-compositor";
export * from "./motion-gpu-render";
export * from "./motion-scene3d";
-export * from "./motion-three-renderer";
+// The three.js renderer (MotionThreeRenderer and its environment helpers) is loaded on demand by
+// motion-renderer; re-exporting it from this barrel pulled the whole three chunk into every importer
+// of @openreel/core. Only its three-free parts stay on the barrel.
+export { DEFAULT_MOTION_RENDER_QUALITY, mergeMotionRenderQuality, type MotionRenderQuality } from "./motion-render-quality";
+export { sampleMotionObjectMeshFrame } from "./motion-object-sampling";
export * from "./shaders";
export * from "./native-aurora-bridge";
export * from "./motion-shape-path";
diff --git a/packages/core/src/render-cache/pixel-entities.ts b/packages/core/src/render-cache/pixel-entities.ts
index fd5334da..a44c4119 100644
--- a/packages/core/src/render-cache/pixel-entities.ts
+++ b/packages/core/src/render-cache/pixel-entities.ts
@@ -200,6 +200,9 @@ function globalFingerprint(project: Project): string {
// Undefined (the Rec.709 / 203 nit defaults) is dropped by stableStringify, so default projects keep their keys.
workingColorSpace: project.settings.workingColorSpace,
graphicsWhiteNits: project.settings.graphicsWhiteNits,
+ // ACES mode changes every pixel; absent (display-referred) keys are dropped so legacy caches stay valid.
+ colorManagement: project.settings.colorManagement === "aces" ? "aces" : undefined,
+ acesOutput: project.settings.colorManagement === "aces" ? project.settings.acesOutput : undefined,
// Sequence PAR / field order; undefined (square, progressive) is dropped so legacy keys are unchanged.
pixelAspectRatio: project.settings.pixelAspectRatio,
fieldOrder: project.settings.fieldOrder,
diff --git a/packages/core/src/types/actions.ts b/packages/core/src/types/actions.ts
index 319d2cae..69872881 100644
--- a/packages/core/src/types/actions.ts
+++ b/packages/core/src/types/actions.ts
@@ -241,6 +241,11 @@ export type ClipAction =
| { type: "clip/closeGapBefore"; params: { clipId: string } }
| { type: "clip/setSpeed"; params: { clipId: string; speed: number } }
| { type: "clip/setReverse"; params: { clipId: string; reversed: boolean } }
+ | {
+ type: "clip/setColorInterpretation";
+ /** `undefined` / null clears the override (the footage's own interpretation applies). */
+ params: { clipId: string; colorInterpretation?: import("../color/source-color").FootageColorPreset | null };
+ }
| {
type: "clip/setPitchCorrection";
params: { clipId: string; pitchCorrection: boolean };
diff --git a/packages/core/src/types/project.ts b/packages/core/src/types/project.ts
index f8dad46d..d6552cb0 100644
--- a/packages/core/src/types/project.ts
+++ b/packages/core/src/types/project.ts
@@ -46,6 +46,14 @@ export interface ProjectSettings {
readonly channelLayout?: import("../audio/surround").ChannelLayout;
/** Absent = Rec.709. */
readonly workingColorSpace?: WorkingColorSpace;
+ /**
+ * Project colour management. Absent / "display-referred": the classic display-referred pipeline, unchanged.
+ * "aces": footage goes through an ACES Input Transform (IDT) to ACEScg, grading runs in ACEScct, and the picture
+ * leaves through the ACES Output Transform (RRT + ODT). See `color/aces.ts`.
+ */
+ readonly colorManagement?: import("../color/aces").ColorManagementMode;
+ /** ACES mode only: the SDR Output Transform of the monitor and of SDR exports. Absent = sRGB. HDR exports pick the Rec.2020 PQ / HLG transforms. */
+ readonly acesOutput?: import("../color/aces").AcesSdrOutput;
/**
* HDR working mode only: the luminance, in nits, that the white of 8-bit graphics (titles, shapes, stickers,
* subtitles, motion graphics) is placed at. Absent = 203 nits, ITU-R BT.2408 graphics white. 80 to 1000.
diff --git a/packages/core/src/types/timeline.ts b/packages/core/src/types/timeline.ts
index 1a239d97..f61e8ebf 100644
--- a/packages/core/src/types/timeline.ts
+++ b/packages/core/src/types/timeline.ts
@@ -362,6 +362,11 @@ export interface Clip {
readonly speedKeyframes?: SpeedKeyframe[];
readonly freezeFrames?: FreezeFrame[];
readonly pitchCorrection?: boolean;
+ /**
+ * Input colour space override for this clip (an Interpret Footage preset). Wins over the footage item's own
+ * `colorInterpretation` and its tags; absent = use the footage's. See `inputSpaceForItem`.
+ */
+ readonly colorInterpretation?: import("../color/source-color").FootageColorPreset;
/**
* Essential Sound tag. When absent the type is inferred from the parent
* track's `role` (see resolveAudioType in audio/essential-sound.ts).
diff --git a/packages/core/src/video/aces-glsl.ts b/packages/core/src/video/aces-glsl.ts
new file mode 100644
index 00000000..964b2ad6
--- /dev/null
+++ b/packages/core/src/video/aces-glsl.ts
@@ -0,0 +1,219 @@
+import { ACESCCT_WHITE, AP0_TO_AP1, AP1_RGB2Y, AP1_TO_AP0, AP1_TO_XYZ, D60_TO_D65, XYZ_TO_AP1, type AcesMatrix3 as Matrix3 } from "../color/aces";
+import {
+ HDR_1000_SPLINE,
+ HDR_1000_Y_MAX,
+ HDR_1000_Y_MIN,
+ ODT_48_SPLINE,
+ ODT_SAT_MAT,
+ REC2020_TO_XYZ,
+ RRT_SAT_MAT,
+ RRT_SPLINE,
+ XYZ_TO_REC2020,
+ XYZ_TO_REC709,
+ type SplineParams,
+} from "../color/aces-output";
+
+/**
+ * GLSL ES 3.00 port of `color/aces.ts` (the CPU reference). Every constant is written from the same TypeScript values,
+ * so the shader and the reference cannot drift apart; `apps/web/e2e/aces-color.spec.ts` holds the shader to the
+ * reference on a GPU.
+ *
+ * Entry points (inputs and outputs are 0..1 signals, ACEScg linear in):
+ * vec3 acescctEncodeV(vec3 lin), vec3 acescctDecodeV(vec3 cct)
+ * vec3 acesOutputV(vec3 acescg, int output) 1 sRGB, 2 BT.1886 (Rec.709), 3 Rec.2020 PQ 1000 nit, 4 Rec.2020 HLG
+ */
+
+/** A GLSL float literal that always carries a decimal point or exponent. */
+function glf(value: number): string {
+ const text = value === 0 ? "0.0" : value.toPrecision(17).replace(/0+$/, "").replace(/\.$/, ".0");
+ const normalised = String(Number(text));
+ return /[.e]/i.test(normalised) ? normalised : `${normalised}.0`;
+}
+
+function glMat3(m: Matrix3): string {
+ const v = (i: number, j: number) => glf(m[i][j]);
+ return `mat3(${v(0, 0)}, ${v(1, 0)}, ${v(2, 0)}, ${v(0, 1)}, ${v(1, 1)}, ${v(2, 1)}, ${v(0, 2)}, ${v(1, 2)}, ${v(2, 2)})`;
+}
+
+function glArray(values: readonly number[]): string {
+ return `float[${values.length}](${values.map(glf).join(", ")})`;
+}
+
+function splineFunction(name: string, p: SplineParams): string {
+ const nLow = p.coefsLow.length - 2;
+ const nHigh = p.coefsHigh.length - 2;
+ const lMin = Math.log10(p.minX);
+ const lMid = Math.log10(p.midX);
+ const lMax = Math.log10(p.maxX);
+ return `
+float ${name}(float x) {
+ float cLow[${p.coefsLow.length}] = ${glArray(p.coefsLow)};
+ float cHigh[${p.coefsHigh.length}] = ${glArray(p.coefsHigh)};
+ float logx = log10f(max(x, HALF_MIN));
+ float logy;
+ if (logx <= ${glf(lMin)}) {
+ logy = logx * ${glf(p.slopeLow)} + ${glf(Math.log10(p.minY) - p.slopeLow * lMin)};
+ } else if (logx < ${glf(lMid)}) {
+ float coord = ${glf(nLow - 1)} * (logx - ${glf(lMin)}) / ${glf(lMid - lMin)};
+ int j = int(coord);
+ logy = bSplineQuad(cLow[j], cLow[j + 1], cLow[j + 2], coord - float(j));
+ } else if (logx < ${glf(lMax)}) {
+ float coord = ${glf(nHigh - 1)} * (logx - ${glf(lMid)}) / ${glf(lMax - lMid)};
+ int j = int(coord);
+ logy = bSplineQuad(cHigh[j], cHigh[j + 1], cHigh[j + 2], coord - float(j));
+ } else {
+ logy = logx * ${glf(p.slopeHigh)} + ${glf(Math.log10(p.maxY) - p.slopeHigh * lMax)};
+ }
+ return pow(10.0, logy);
+}
+`;
+}
+
+/** ACEScct encode / decode only: what the layer shader needs to grade in ACEScct and to decode ACEScct footage. */
+export function acescctGlsl(): string {
+ return `
+const float ACESCCT_CUT_LIN = 0.0078125;
+const float ACESCCT_CUT_LOG = 0.155251141552511;
+const float ACESCCT_A = 10.5402377416545;
+const float ACESCCT_B = 0.0729055341958355;
+const float ACESCCT_WHITE = ${glf(ACESCCT_WHITE)};
+float acescctEncode1(float l) {
+ return l <= ACESCCT_CUT_LIN ? ACESCCT_A * l + ACESCCT_B : (log2(l) + 9.72) / 17.52;
+}
+float acescctDecode1(float c) {
+ return c <= ACESCCT_CUT_LOG ? (c - ACESCCT_B) / ACESCCT_A : exp2(c * 17.52 - 9.72);
+}
+vec3 acescctEncodeV(vec3 l) { return vec3(acescctEncode1(l.r), acescctEncode1(l.g), acescctEncode1(l.b)); }
+vec3 acescctDecodeV(vec3 c) { return vec3(acescctDecode1(c.r), acescctDecode1(c.g), acescctDecode1(c.b)); }
+`;
+}
+
+/** The GLSL source of the Output Transform, to be placed after the COMMON block of the HDR shaders (it uses `pqEncodeNitsV`). */
+export function acesGlsl(): string {
+ return `
+const float HALF_MIN = 5.96046448e-8;
+const float HALF_MAX = 65504.0;
+const mat3 ACES_AP0_TO_AP1 = ${glMat3(AP0_TO_AP1)};
+const mat3 ACES_AP1_TO_AP0 = ${glMat3(AP1_TO_AP0)};
+const mat3 ACES_AP1_TO_XYZ = ${glMat3(AP1_TO_XYZ)};
+const mat3 ACES_XYZ_TO_AP1 = ${glMat3(XYZ_TO_AP1)};
+const mat3 ACES_D60_TO_D65 = ${glMat3(D60_TO_D65)};
+const mat3 ACES_XYZ_TO_REC709 = ${glMat3(XYZ_TO_REC709)};
+const mat3 ACES_XYZ_TO_REC2020 = ${glMat3(XYZ_TO_REC2020)};
+const mat3 ACES_REC2020_TO_XYZ = ${glMat3(REC2020_TO_XYZ)};
+const mat3 ACES_RRT_SAT = ${glMat3(RRT_SAT_MAT)};
+const mat3 ACES_ODT_SAT = ${glMat3(ODT_SAT_MAT)};
+const vec3 ACES_AP1_Y = vec3(${AP1_RGB2Y.map(glf).join(", ")});
+
+float log10f(float x) { return log(x) * 0.43429448190325176; }
+
+float bSplineQuad(float c0, float c1, float c2, float t) {
+ return (0.5 * c0 - c1 + 0.5 * c2) * t * t + (-c0 + c1) * t + 0.5 * c0 + 0.5 * c1;
+}
+${splineFunction("acesRrtSpline", RRT_SPLINE)}
+${splineFunction("acesOdtSpline", ODT_48_SPLINE)}
+${splineFunction("acesHdrSpline", HDR_1000_SPLINE)}
+
+float acesSigmoid(float x) {
+ float t = max(1.0 - abs(x / 2.0), 0.0);
+ return (1.0 + sign(x) * (1.0 - t * t)) / 2.0;
+}
+float acesCubicBasis(float x, float w) {
+ float y = 0.0;
+ if (x > -w / 2.0 && x < w / 2.0) {
+ float coord = (x + w / 2.0) * 4.0 / w;
+ int j = int(coord);
+ float t = coord - float(j);
+ float t2 = t * t;
+ float t3 = t2 * t;
+ if (j == 3) y = t3 * (-1.0 / 6.0) + t2 * (3.0 / 6.0) + t * (-3.0 / 6.0) + 1.0 / 6.0;
+ else if (j == 2) y = t3 * (3.0 / 6.0) + t2 * (-6.0 / 6.0) + 4.0 / 6.0;
+ else if (j == 1) y = t3 * (-3.0 / 6.0) + t2 * (3.0 / 6.0) + t * (3.0 / 6.0) + 1.0 / 6.0;
+ else if (j == 0) y = t3 * (1.0 / 6.0);
+ }
+ return y * 3.0 / 2.0;
+}
+
+vec3 acesRrtSweeteners(vec3 aces) {
+ float mx = max(aces.r, max(aces.g, aces.b));
+ float mn = min(aces.r, min(aces.g, aces.b));
+ float saturation = (max(mx, 1e-10) - max(mn, 1e-10)) / max(mx, 1e-2);
+ float chroma = sqrt(max(aces.b * (aces.b - aces.g) + aces.g * (aces.g - aces.r) + aces.r * (aces.r - aces.b), 0.0));
+ float yc = (aces.b + aces.g + aces.r + 1.75 * chroma) / 3.0;
+ float s = acesSigmoid((saturation - 0.4) / 0.2);
+ float glowGain = ${glf(0.05)} * s;
+ float glowMid = ${glf(0.08)};
+ float glow = yc <= 2.0 / 3.0 * glowMid ? glowGain : (yc >= 2.0 * glowMid ? 0.0 : glowGain * (glowMid / yc - 0.5));
+ aces *= 1.0 + glow;
+ float weight = 0.0;
+ if (!(aces.r == aces.g && aces.g == aces.b)) {
+ float hue = degrees(atan(sqrt(3.0) * (aces.g - aces.b), 2.0 * aces.r - aces.g - aces.b));
+ if (hue < 0.0) hue += 360.0;
+ float centered = hue;
+ if (centered > 180.0) centered -= 360.0;
+ weight = acesCubicBasis(centered, 135.0);
+ }
+ aces.r = aces.r + weight * saturation * (0.03 - aces.r) * (1.0 - 0.82);
+ aces = clamp(aces, 0.0, HALF_MAX);
+ vec3 rgbPre = clamp(ACES_AP0_TO_AP1 * aces, 0.0, HALF_MAX);
+ return ACES_RRT_SAT * rgbPre;
+}
+
+vec3 acesSrgbOetf(vec3 y) {
+ float yb = pow(0.055 * 2.4 / (1.4 * 1.055), 2.4);
+ float rs = pow(1.4 / 0.055, 1.4) * pow(1.055 / 2.4, 2.4);
+ return vec3(
+ y.r >= yb ? 1.055 * pow(y.r, 1.0 / 2.4) - 0.055 : y.r * rs,
+ y.g >= yb ? 1.055 * pow(y.g, 1.0 / 2.4) - 0.055 : y.g * rs,
+ y.b >= yb ? 1.055 * pow(y.b, 1.0 / 2.4) - 0.055 : y.b * rs
+ );
+}
+
+vec3 acesSdrDisplay(vec3 ap0, bool srgb) {
+ vec3 pre = acesRrtSweeteners(ap0);
+ vec3 rrt = vec3(acesRrtSpline(pre.r), acesRrtSpline(pre.g), acesRrtSpline(pre.b));
+ vec3 oces = ACES_AP1_TO_AP0 * rrt;
+ vec3 rgbPre = ACES_AP0_TO_AP1 * oces;
+ vec3 post = vec3(acesOdtSpline(rgbPre.r), acesOdtSpline(rgbPre.g), acesOdtSpline(rgbPre.b));
+ vec3 lin = (post - ${glf(0.02)}) / ${glf(48 - 0.02)};
+ vec3 xyz0 = ACES_AP1_TO_XYZ * lin;
+ float sum = xyz0.x + xyz0.y + xyz0.z;
+ if (sum == 0.0) sum = 1e-10;
+ vec2 xy = xyz0.xy / sum;
+ float Y = pow(clamp(xyz0.y, 0.0, HALF_MAX), 0.9811);
+ float yy = max(xy.y, 1e-10);
+ vec3 dim = ACES_XYZ_TO_AP1 * vec3(xy.x * Y / yy, Y, (1.0 - xy.x - xy.y) * Y / yy);
+ vec3 sat = ACES_ODT_SAT * dim;
+ vec3 xyz = ACES_D60_TO_D65 * (ACES_AP1_TO_XYZ * sat);
+ vec3 display = clamp(ACES_XYZ_TO_REC709 * xyz, 0.0, 1.0);
+ return srgb ? acesSrgbOetf(display) : pow(display, vec3(1.0 / 2.4));
+}
+
+vec3 acesHdrNits(vec3 ap0) {
+ vec3 pre = acesRrtSweeteners(ap0);
+ vec3 tone = vec3(acesHdrSpline(pre.r), acesHdrSpline(pre.g), acesHdrSpline(pre.b));
+ vec3 lin = (tone - ${glf(HDR_1000_Y_MIN)}) / ${glf(HDR_1000_Y_MAX - HDR_1000_Y_MIN)};
+ vec3 xyz = ACES_AP1_TO_XYZ * lin;
+ vec3 limited = clamp(ACES_XYZ_TO_REC2020 * xyz, 0.0, 1.0);
+ vec3 xyzLimited = ACES_REC2020_TO_XYZ * limited;
+ vec3 xyzD65 = ACES_D60_TO_D65 * xyzLimited;
+ return clamp(ACES_XYZ_TO_REC2020 * xyzD65, 0.0, HALF_MAX) * ${glf(HDR_1000_Y_MAX)};
+}
+
+float acesHlgOetf1(float e) {
+ return e <= 1.0 / 12.0 ? sqrt(3.0 * e) : 0.17883277 * log(12.0 * e - 0.28466892) + 0.55991073;
+}
+
+vec3 acesOutputV(vec3 acescg, int outId) {
+ vec3 ap0 = ACES_AP1_TO_AP0 * acescg;
+ if (outId <= 2) return acesSdrDisplay(ap0, outId == 1);
+ vec3 nits = acesHdrNits(ap0);
+ if (outId == 3) return pqEncodeNitsV(nits);
+ float yd = dot(nits, vec3(0.2627, 0.678, 0.0593));
+ if (yd <= 0.0) return vec3(0.0);
+ float k = pow(yd / 1000.0, (1.0 - 1.2) / 1.2);
+ vec3 scene = k * nits / 1000.0;
+ return vec3(acesHlgOetf1(scene.r), acesHlgOetf1(scene.g), acesHlgOetf1(scene.b));
+}
+`;
+}
diff --git a/packages/core/src/video/hdr-gpu.ts b/packages/core/src/video/hdr-gpu.ts
index c94e72cd..5e51cb9e 100644
--- a/packages/core/src/video/hdr-gpu.ts
+++ b/packages/core/src/video/hdr-gpu.ts
@@ -1,7 +1,10 @@
import {
- HDR_OVERLAY_DECODE,
PQ_WORKING_WHITE,
+ SCENE_HDR_PIPELINE,
+ acesOutputForSpec,
graphicsWhiteGain,
+ overlayDecodeFor,
+ type HdrColorPipeline,
type HdrCompositor,
type HdrFrame,
type HdrGradeSpec,
@@ -15,6 +18,7 @@ import { packRgbToRgba } from "../color/lut-tables";
import { HUE_CURVES_GLSL, HUE_CURVE_LUT_SIZE, packHueCurveLuts } from "./hue-curves";
import { BT2020_TO_BT709, TONE_MAP_KNEE } from "../color/input-transform";
import { cameraLogGlsl } from "../color/camera-log";
+import { acescctGlsl, acesGlsl } from "./aces-glsl";
import { BLUR_MAX_HALF, GLOW_BRIGHTNESS, GLOW_CONTRAST, gaussianKernel, glowWeight, type HdrLayerEffect } from "../color/hdr-effects";
/**
@@ -94,8 +98,10 @@ uniform int u_depth;
uniform int u_transfer;
uniform mat3 u_toBt2020;
+${acescctGlsl()}
${cameraLogGlsl()}
vec3 decodeTransfer(vec3 c) {
+ if (u_transfer == 13) return acescctDecodeV(c);
if (u_transfer >= 4) return decodeCameraLog(c, u_transfer);
if (u_transfer == 1) return pqDecodeNitsV(c) / SDR_WHITE_NITS;
if (u_transfer == 2) return hlgInverseV(c) / HLG_SDR_WHITE_SCENE;
@@ -243,6 +249,7 @@ uniform vec3 u_highlights;
uniform float u_shadowsLift;
uniform float u_midtonesGamma;
uniform float u_highlightsGain;
+uniform bool u_gradeAces;
const float PQ_WORKING_WHITE = ${PQ_WORKING_WHITE.toFixed(8)};
${COMMON}
${SOURCE_DECODE}
@@ -342,9 +349,13 @@ float curveSample(int channel, float x) {
return a + (b - a) * fraction;
}
+// The grade's working encoding: ACEScct in the aces pipeline (negative light floored at 0), PQ otherwise.
+vec3 gradeEnc(vec3 l) { return u_gradeAces ? acescctEncodeV(max(l, vec3(0.0))) : linearToPqWorking(l); }
+vec3 gradeDec(vec3 p) { return u_gradeAces ? acescctDecodeV(p) : pqWorkingToLinear(p); }
+
vec3 gradeHdr(vec3 lin, vec2 srcPos) {
lin *= u_exposureGain;
- vec3 p = linearToPqWorking(lin);
+ vec3 p = gradeEnc(lin);
if (u_useWB) p = clamp(p + u_wb, 0.0, 1.0);
if (u_useTone) p = vec3(toneSample(p.r), toneSample(p.g), toneSample(p.b));
if (u_useWheels) {
@@ -370,11 +381,12 @@ vec3 gradeHdr(vec3 lin, vec2 srcPos) {
);
}
if (u_useLut) {
- vec3 e = vec3(lutEncode1(pqWorkingToLinear(p).r), lutEncode1(pqWorkingToLinear(p).g), lutEncode1(pqWorkingToLinear(p).b));
+ vec3 pl = gradeDec(p);
+ vec3 e = vec3(lutEncode1(pl.r), lutEncode1(pl.g), lutEncode1(pl.b));
vec3 cl = u_useLutCurve ? min(e, u_lutDomainMax) : min(e, vec3(1.0));
vec3 mapped = u_useLutCurve ? sampleLutCurve(cl) : sampleLut3d(cl);
vec3 outE = e + (mapped + (e - cl) - e) * u_lutIntensity;
- p = linearToPqWorking(vec3(lutDecode1(outE.r), lutDecode1(outE.g), lutDecode1(outE.b)));
+ p = gradeEnc(vec3(lutDecode1(outE.r), lutDecode1(outE.g), lutDecode1(outE.b)));
}
if (u_useHsl) {
vec3 hsl = hcRgb2Hsl(p);
@@ -388,10 +400,10 @@ vec3 gradeHdr(vec3 lin, vec2 srcPos) {
float w = vignetteWeight(n, u_srcSize.x / u_srcSize.y);
if (w > 0.0) {
if (amount < 0.0) p *= 1.0 + amount * w;
- else p += max(vec3(PQ_WORKING_WHITE) - p, 0.0) * (amount * w);
+ else p += max(vec3(u_gradeAces ? ACESCCT_WHITE : PQ_WORKING_WHITE) - p, 0.0) * (amount * w);
}
}
- return pqWorkingToLinear(p);
+ return gradeDec(p);
}
void main() {
@@ -471,8 +483,30 @@ void main() {
}
`;
+/**
+ * The ACES Output Transform pass. Same inputs as OUTPUT_FRAGMENT (the premultiplied ACEScg image in u_acc): mode 0 is the
+ * SDR view (u_aces 1 = sRGB, 2 = BT.1886), mode 1 the encode (u_aces 3 = PQ 1000 nit, 4 = HLG, or an SDR id).
+ */
+const ACES_OUTPUT_FRAGMENT = `#version 300 es
+precision highp float;
+precision highp int;
+precision highp sampler2D;
+out vec4 outColor;
+uniform sampler2D u_acc;
+uniform int u_mode;
+uniform int u_aces;
+${COMMON}
+${acesGlsl()}
+
+void main() {
+ vec4 acc = texelFetch(u_acc, ivec2(gl_FragCoord.xy), 0);
+ vec3 enc = acesOutputV(max(acc.rgb, 0.0), u_aces);
+ outColor = vec4(enc, u_mode == 0 ? clamp(acc.a, 0.0, 1.0) : 1.0);
+}
+`;
+
/** The fragment shaders, for offline validation (glslangValidator) and tests. */
-export const HDR_SHADER_SOURCES = { layer: LAYER_FRAGMENT, output: OUTPUT_FRAGMENT, decode: DECODE_FRAGMENT, effect: EFFECT_FRAGMENT } as const;
+export const HDR_SHADER_SOURCES = { layer: LAYER_FRAGMENT, output: OUTPUT_FRAGMENT, acesOutput: ACES_OUTPUT_FRAGMENT, decode: DECODE_FRAGMENT, effect: EFFECT_FRAGMENT } as const;
interface Program {
program: WebGLProgram;
@@ -510,6 +544,9 @@ export class GpuHdrCompositor implements HdrCompositor {
private outputProgram: Program;
private decodeProgram: Program;
private effectProgram: Program;
+ /** Compiled the first time an ACES frame is output (the RRT / ODT shader is the largest one). */
+ private acesProgram: Program | null = null;
+ private pipeline: HdrColorPipeline = SCENE_HDR_PIPELINE;
private graphicsGain = 1;
private fx: FxTargets | null = null;
private dummy3d: WebGLTexture;
@@ -698,6 +735,7 @@ export class GpuHdrCompositor implements HdrCompositor {
const setB = (name: string, v: boolean): void => gl.uniform1i(this.uniform(p, name), v ? 1 : 0);
const set3 = (name: string, x: number, y: number, z: number): void => gl.uniform3f(this.uniform(p, name), x, y, z);
setB("u_useGrade", !!grade);
+ setB("u_gradeAces", grade?.acescct === true);
set1("u_exposureGain", grade?.exposureGain ?? 1);
setB("u_useWB", !!grade?.whiteBalance);
const wb = grade?.whiteBalance ?? [0, 0, 0];
@@ -804,6 +842,10 @@ export class GpuHdrCompositor implements HdrCompositor {
this.current = next;
}
+ setColorPipeline(pipeline: HdrColorPipeline): void {
+ this.pipeline = pipeline;
+ }
+
setGraphicsWhite(nits: number): void {
this.graphicsGain = graphicsWhiteGain(nits);
}
@@ -812,7 +854,7 @@ export class GpuHdrCompositor implements HdrCompositor {
const w = this.width;
this.runLayer(
{ depth: 8, texture: this.dummy8, width: 1, height: 1 },
- HDR_OVERLAY_DECODE,
+ overlayDecodeFor(this.pipeline),
{ geometry: { m: [1, 0, 0, 0, 1, 0], rect: [0, 0, w, this.height], scale: [1, 1] }, opacity: Math.max(0, Math.min(1, alpha)), grade: null },
{ solid: rgb },
);
@@ -975,7 +1017,7 @@ export class GpuHdrCompositor implements HdrCompositor {
try {
this.runLayer(
{ depth: 8, texture, width: w, height: h },
- HDR_OVERLAY_DECODE,
+ overlayDecodeFor(this.pipeline),
{
geometry: { m: [1, 0, 0, 0, 1, 0], rect: [0, 0, w, h], scale: [1, 1] },
opacity: 1,
@@ -990,6 +1032,18 @@ export class GpuHdrCompositor implements HdrCompositor {
private runOutput(mode: 0 | 1, spec: OutputColorSpec | null): void {
const gl = this.gl;
+ if (this.pipeline.kind === "aces") {
+ this.acesProgram ??= this.compile(ACES_OUTPUT_FRAGMENT);
+ const ap = this.acesProgram;
+ gl.useProgram(ap.program);
+ this.bindTex(0, this.accTextures[this.current], ap, "u_acc");
+ gl.uniform1i(this.uniform(ap, "u_mode"), mode);
+ const id = mode === 0 || !spec ? this.pipeline.sdrOutput : acesOutputForSpec(spec, this.pipeline.sdrOutput);
+ gl.uniform1i(this.uniform(ap, "u_aces"), id === "srgb" ? 1 : id === "rec709" ? 2 : id === "rec2020-pq" ? 3 : 4);
+ gl.viewport(0, 0, this.width, this.height);
+ gl.drawArrays(gl.TRIANGLES, 0, 3);
+ return;
+ }
const p = this.outputProgram;
gl.useProgram(p.program);
this.bindTex(0, this.accTextures[this.current], p, "u_acc");
@@ -1056,6 +1110,7 @@ export class GpuHdrCompositor implements HdrCompositor {
gl.deleteProgram(this.outputProgram.program);
gl.deleteProgram(this.decodeProgram.program);
gl.deleteProgram(this.effectProgram.program);
+ if (this.acesProgram) gl.deleteProgram(this.acesProgram.program);
gl.getExtension("WEBGL_lose_context")?.loseContext();
}
}
diff --git a/packages/core/src/video/video-engine.ts b/packages/core/src/video/video-engine.ts
index e9c23508..d5ef237a 100644
--- a/packages/core/src/video/video-engine.ts
+++ b/packages/core/src/video/video-engine.ts
@@ -16,7 +16,9 @@ import {
DEFAULT_GRAPHICS_WHITE_NITS,
computeLayerGeometry,
graphicsWhiteGain,
+ hdrPipelineFor,
hdrSourceDecode,
+ registerAcesOutputTransform,
isHdrWorkingMode,
prepareHdrGrade,
attachHdrPayload,
@@ -24,6 +26,7 @@ import {
type SourceCodes,
} from "../color/hdr-working";
import { resolveHdrEffects } from "../color/hdr-effects";
+import { acesOutputTransform } from "../color/aces-output";
import { isHdrTransitionKind, planHdrTransition } from "./hdr-transition";
import { getNativeFrameCodes } from "../media/native-frame-source";
import {
@@ -985,8 +988,12 @@ export class VideoEngine {
this.hdrCompositor ??= createHdrCompositor(!this.hdrGpuFailed);
hdr = this.hdrCompositor;
hdr.begin(width, height);
+ hdr.setColorPipeline(hdrPipelineFor(settings));
+ // The CPU reference compositor's ACES output (the GPU one runs the shader port).
+ registerAcesOutputTransform(acesOutputTransform);
hdr.setGraphicsWhite(settings.graphicsWhiteNits ?? DEFAULT_GRAPHICS_WHITE_NITS);
}
+ const colorPipeline = hdrPipelineFor(settings);
let hdrDirty = false;
await this.renderMotionInstancesToCanvasCtx(
@@ -1305,10 +1312,10 @@ export class VideoEngine {
this.flushHdrOverlay(hdr, ctx, width, height);
hdrDirty = false;
}
- hdr.drawCodes(codes, hdrSourceDecode(inputSpaceForItem(mediaItem)), {
+ hdr.drawCodes(codes, hdrSourceDecode(inputSpaceForItem(mediaItem, clip.colorInterpretation), colorPipeline), {
geometry,
opacity: t.opacity,
- grade: prepareHdrGrade(clipGrading),
+ grade: prepareHdrGrade(clipGrading, colorPipeline),
effects: resolveHdrEffects(clipInfo.effects ?? []).effects,
});
if (bitmap && !bitmapFromCache) bitmap.close();
@@ -1618,10 +1625,11 @@ export class VideoEngine {
width,
height,
);
- hdr.drawCodes(codes, hdrSourceDecode(inputSpaceForItem(mediaItem)), {
+ const colorPipeline = hdrPipelineFor(project.settings);
+ hdr.drawCodes(codes, hdrSourceDecode(inputSpaceForItem(mediaItem, clip.colorInterpretation), colorPipeline), {
geometry,
opacity: t.opacity * opacityScale,
- grade: prepareHdrGrade(grading),
+ grade: prepareHdrGrade(grading, colorPipeline),
effects: resolveHdrEffects(clipInfo.effects ?? []).effects,
});
return true;
@@ -2968,10 +2976,14 @@ export class VideoEngine {
}
}
this.clipInputTransforms = new Map();
- if (this.inputTransformByMedia.size === 0) return;
+ const itemById = new Map(items.map((item) => [item.id, item] as const));
for (const track of project.timeline.tracks) {
for (const clip of track.clips) {
- const transform = this.inputTransformByMedia.get(clip.mediaId);
+ // A clip's own Interpret Footage override wins over its footage item's.
+ const item = clip.colorInterpretation ? itemById.get(clip.mediaId) : undefined;
+ const transform = item
+ ? (item.type === "video" || item.type === "image") ? inputTransformFor(inputSpaceForItem(item, clip.colorInterpretation)) : null
+ : this.inputTransformByMedia.get(clip.mediaId);
if (transform) this.clipInputTransforms.set(clip.id, transform);
}
}
diff --git a/scripts/aces-reference.py b/scripts/aces-reference.py
new file mode 100644
index 00000000..fc11c679
--- /dev/null
+++ b/scripts/aces-reference.py
@@ -0,0 +1,106 @@
+#!/usr/bin/env python3
+"""Regenerates packages/core/src/color/fixtures/aces-ocio-reference.ts.
+
+The reference values come from OpenColorIO's builtin ACES 1.3 transforms (an independent implementation of the
+ACES CTL), not from OpenReel code:
+
+ python3 -m venv /tmp/aces-venv && /tmp/aces-venv/bin/pip install opencolorio numpy colour-science
+ /tmp/aces-venv/bin/python scripts/aces-reference.py
+
+Inputs are ACEScg (AP1 linear) triples; outputs are the SDR-VIDEO_1.0 transform to sRGB / BT.1886 display codes and
+the HDR-VIDEO-1000nit-15nit-REC2020lim_1.1 transform to Rec.2020 linear display light in nits.
+"""
+import json
+import os
+
+import numpy as np
+import PyOpenColorIO as ocio
+
+cfg = ocio.Config.CreateRaw()
+
+
+def builtin(style):
+ t = ocio.BuiltinTransform()
+ t.setStyle(style)
+ return t
+
+
+def processor(*transforms):
+ group = ocio.GroupTransform()
+ for t in transforms:
+ group.appendTransform(t)
+ return cfg.getProcessor(group).getDefaultCPUProcessor()
+
+
+to_aces = builtin("ACEScg_to_ACES2065-1")
+sdr = processor(to_aces, builtin("ACES-OUTPUT - ACES2065-1_to_CIE-XYZ-D65 - SDR-VIDEO_1.0"))
+hdr = processor(to_aces, builtin("ACES-OUTPUT - ACES2065-1_to_CIE-XYZ-D65 - HDR-VIDEO-1000nit-15nit-REC2020lim_1.1"))
+
+rng = np.random.default_rng(7)
+points = [[v, v, v] for v in [0, 0.0001, 0.001, 0.01, 0.05, 0.18, 0.5, 1, 2, 4, 8, 16, 100]]
+points += [
+ [1, 0, 0], [0, 1, 0], [0, 0, 1], [1, 1, 0], [0, 1, 1], [1, 0, 1],
+ [0.5, 0.1, 0.05], [0.05, 0.3, 0.1], [0.1, 0.1, 0.6], [0.9, 0.5, 0.2],
+ [0.18, 0.02, 0.05], [0.02, 0.18, 0.5], [4, 0.5, 0.2], [0.3, 2, 0.3], [0.12, 0.08, 0.06],
+]
+points += [[float(10 ** rng.uniform(-3, 1)) for _ in range(3)] for _ in range(40)]
+src = np.array(points, dtype=np.float32)
+
+
+def rgb_to_xyz(r, g, b, w):
+ def xyz(x, y):
+ return np.array([x / y, 1, (1 - x - y) / y])
+ p = np.column_stack([xyz(*r), xyz(*g), xyz(*b)])
+ return p * np.linalg.solve(p, xyz(*w))
+
+
+m709 = rgb_to_xyz((0.64, 0.33), (0.3, 0.6), (0.15, 0.06), (0.3127, 0.329))
+m2020 = rgb_to_xyz((0.708, 0.292), (0.17, 0.797), (0.131, 0.046), (0.3127, 0.329))
+
+xyz_sdr = src.copy()
+sdr.applyRGB(xyz_sdr)
+xyz_hdr = src.copy()
+hdr.applyRGB(xyz_hdr)
+lin709 = np.clip((np.linalg.inv(m709) @ xyz_sdr.T.astype(np.float64)).T, 0, 1)
+lin2020 = np.clip((np.linalg.inv(m2020) @ xyz_hdr.T.astype(np.float64)).T, 0, None)
+srgb = np.where(lin709 <= 0.0031308, lin709 * 12.92, 1.055 * np.power(lin709, 1 / 2.4) - 0.055)
+
+# Gamut -> ACEScg matrices. AP1 -> Rec.709 comes from OCIO's builtin; the rest from colour-science
+# (Bradford adaptation to the ACES white), an independent implementation of the same published chromaticities.
+def basis_matrix(style):
+ p = processor(builtin(style))
+ cols = np.eye(3, dtype=np.float32)
+ p.applyRGB(cols)
+ return cols.T.astype(np.float64) # applyRGB maps each row; transpose gives column-vector form
+
+
+matrices = {"ap1ToRec709": basis_matrix("UTILITY - ACES-AP1_to_LINEAR-REC709_BFD").tolist(), "ap1ToXyzD65": basis_matrix("UTILITY - ACES-AP1_to_CIE-XYZ-D65_BFD").tolist()}
+try:
+ import colour
+
+ names = {
+ "rec709": "ITU-R BT.709", "p3": "P3-D65", "bt2020": "ITU-R BT.2020", "sgamut3cine": "S-Gamut3.Cine", "vgamut": "V-Gamut",
+ "awg3": "ARRI Wide Gamut 3", "awg4": "ARRI Wide Gamut 4", "cinemagamut": "Cinema Gamut", "bmdwg": "Blackmagic Wide Gamut",
+ }
+ acescg = colour.RGB_COLOURSPACES["ACEScg"]
+ matrices["toAcescg"] = {
+ key: colour.matrix_RGB_to_RGB(colour.RGB_COLOURSPACES[name], acescg, chromatic_adaptation_transform="Bradford").tolist()
+ for key, name in names.items()
+ }
+except ImportError:
+ print("colour-science not installed: keeping the previous toAcescg matrices")
+
+round_all = lambda a, n: [[round(float(x), n) for x in row] for row in a]
+out = {
+ "note": "Generated by scripts/aces-reference.py with OpenColorIO builtin ACES 1.3 transforms. srgb / rec709: display code values 0..1. hdrNits: Rec.2020 linear display luminance in nits (SDR-VIDEO_1.0 and HDR-VIDEO-1000nit-15nit-REC2020lim_1.1).",
+ "acescg": round_all(points, 7),
+ "srgb": round_all(srgb, 7),
+ "rec709": round_all(np.power(lin709, 1 / 2.4), 7),
+ "hdrNits": round_all(lin2020 * 100, 5),
+ "matrices": matrices,
+}
+path = os.path.join(os.path.dirname(__file__), "..", "packages", "core", "src", "color", "fixtures", "aces-ocio-reference.ts")
+with open(path, "w") as f:
+ f.write("// Generated by scripts/aces-reference.py (OpenColorIO builtin ACES 1.3 transforms). Do not edit.\n")
+ f.write("export const ACES_REFERENCE = " + json.dumps(out, separators=(",", ":")) + ";\n")
+print("wrote", os.path.normpath(path), len(points), "points")