Open source CapCut alternative.
TypeScript
feat(cut): ProRes proxies, Apple Log sources, Library LUTs and HDR export [rebuild]
David Led27227c8f1b7
diff --git a/docs/README.md b/docs/README.mdindex 813da9ae..dd72b42d 100644--- a/docs/README.md+++ b/docs/README.md@@ -13,9 +13,10 @@ Supported product and engineering guides live in `docs/guides/`. This list is th**The product**- [Donkey Cut](guides/cut/README.md) — the video editor: what runs in the browser, what runs on the Mac, and the local resources behind it.-- [Donkey Cut's AI Assistant](guides/cut/ai-assistant.md) — how a chat turn runs: the providers, the tool bridge into the editor, what the model knows, and the context budgets.-- [Brief to Video](guides/cut/brief-to-video.md) — the director pipeline's strategy: story planning, the identity ladder that keeps a cast consistent, and where audio goes next.-- [Local Compute](guides/cut/local-compute.md) — why a project the engine doesn't store still uses the Mac when there is one, and the rule that keeps its data where it lives regardless.+- [Donkey Cut's AI Assistant](guides/cut/ai-assistant.md) — how a chat turn runs: the providers, the tool bridge, what the model knows, and the context budgets.+- [Brief to Video](guides/cut/brief-to-video.md) — the director pipeline: story planning and the identity ladder that keeps a cast consistent.+- [Local Compute](guides/cut/local-compute.md) — why a project the engine doesn't store still uses the Mac, and the rule that keeps its data where it lives.+- [Color](guides/cut/color.md) — one recipe per clip, and HDR delivery.- [Performance](guides/performance.md) — the frame budget, the four ways we keep the main thread clear, the memory budget, and how a change is measured before it ships.- [ChatGPT App](guides/chatgpt-app.md) — account linking, cloud project previews, and the boundary between the ChatGPT client and shared playback.diff --git a/docs/guides/cut/README.md b/docs/guides/cut/README.mdindex 99e00384..97529260 100644--- a/docs/guides/cut/README.md+++ b/docs/guides/cut/README.md@@ -52,7 +52,7 @@ Guides draw over the preview from the button beside the timeline zoom: thirds, c## The export-Best uses original resolution, cadence, supported H.264/HEVC codec and audio settings. Whole files and trims copy compressed streams; compatible sequences copy video and encode joined audio. Interior joins need matching codec configurations and keyframes. Effects and incompatible joins render at source settings. Browser, Mac and cloud share packet copying; audio joins use FFmpeg on the project’s machine. Files land in project storage. The [local-compute guide](local-compute.md) covers browser handoff.+Best uses original resolution, cadence, supported H.264/HEVC codec and audio settings. Whole files and trims copy compressed streams; compatible sequences copy video and encode joined audio. Interior joins need matching codec configurations and keyframes. Browser, Mac and cloud share packet copying; audio joins use FFmpeg on the project’s machine. The [local-compute guide](local-compute.md) covers browser handoff, the [color guide](color.md) HDR delivery.## Sharingdiff --git a/docs/guides/cut/ai-assistant.md b/docs/guides/cut/ai-assistant.mdindex 9b4fb74d..27d42a3e 100644--- a/docs/guides/cut/ai-assistant.md+++ b/docs/guides/cut/ai-assistant.md@@ -68,7 +68,7 @@ Every knowledge surface is defined once — the catalog file ships in the engine| The rendered frame | One 640px JPEG | The capture-frame tool: the composite an export would write at that time — footage, transitions, effects, elements, captions — at the playhead or any time asked for. || The footage itself | 36 thumbnails, or 6 whole frames | The watch-video tool: the browser decodes candidates on a dense floor and on the lines the source speaks, keeping the frames that differ. A detail ladder sets how many pixels each is worth — thumbnails for coverage, the source's own frames for reading type a mosaic cell destroys. Captions and transcript fuse in as one clock; text that only repeats them is read for treatment, not words. Detect-silence reports dead air. |-Folder and note mentions retain identity through saved chats; the assistant reads current note text and paged folder contents in the browser, engine and worker, opens accessible Donkey folder links through their sharing grants, and imports selected files, while a detached Mac needs the editor’s session for Library and Notes access.+Folder and note mentions keep their identity in saved chats and resolve on every surface. Each Library file type declares how chat mentions it; a LUT arrives as its set_color_lut call.## The decision layerdiff --git a/docs/guides/cut/color.md b/docs/guides/cut/color.mdnew file mode 100644index 00000000..18b4d2b0--- /dev/null+++ b/docs/guides/cut/color.md@@ -0,0 +1,36 @@+# Color++A clip's color is one recipe: what its code values mean (the source profile), the grade on top, and the space the project delivers in. The kit bakes the recipe into one 3D LUT, and the preview, the thumbnails and the export all draw through that lattice, so the picture is the same number everywhere.++**The one rule:** the project's color space decides the target of every recipe. SDR projects deliver Rec.709; an HDR project composites in HLG, and everything drawn into the frame — footage, titles, stickers, captions, the frame color — is mapped into that space before it is blended.++## Source color++Every video carries a source profile, read from its header at import: Apple Log and Log 2 by Apple's metadata identifier, HLG and PQ by the transfer tag beside a BT.2020 matrix, sRGB by its transfer, Rec.709 otherwise. The Color panel shows the detection and takes a per-asset override.++Rec.709 and sRGB sources draw as they are. A Log or HDR source goes through the ACES 2.0 output transform first, so the grade and any creative LUT see a Rec.709 picture. A technical Log→Rec.709 LUT is a conversion of its own: it goes on a clip whose source is set to "Rec.709 (no conversion)".++That needs the code values untouched, and a browser converts a decoded frame by its bitstream tags before anything can draw it, so the parameter set's tags are rewritten to neutral Rec.709 / sRGB before the decoder sees them. The matrix a decoder then draws with differs by browser, so each route is measured once per session on a small fixture and the clip's LUT undoes it before applying the file's own. ffmpeg and headless renders read the file's matrix and need no fix. ProRes masters and their preview proxies are in [Local Compute](local-compute.md). Start in the source color module.++## LUTs++A `.cube` or `.3dl` file is a Library file keyed by its content, so the same file dropped twice is one LUT and it travels with a project. A clip's grade names it by `lut:<key>` with an intensity, and the recipe bakes it into the clip's lattice between the source conversion and the grade, so the preview, ffmpeg's lut3d and the headless worker all apply the same numbers. An export stages the LUT's bytes beside the job, so the engine and the worker parse the file the tab did.++## HDR delivery++An HDR project keeps what the footage has. Log sources convert into the HLG container through the ACES output transform; HLG and PQ cross straight over the BT.2100 transfer, so their range survives. Rec.709 footage and every graphic take the BT.2408 mapping, SDR white at 75% HLG signal (203 nits), so a title sits at reference white beside the footage. The grade works inside the container at 10 bits.++```+clip ─ source profile ─▶ recipe LUT (output: hlg) ─┐+title / sticker / caption ─▶ sRGB→HLG LUT ─────────┼─▶ HLG composite, 10-bit, Rec.2020+frame color ─▶ hex mapped to HLG ──────────────────┘ │+ PQ project: HLG→PQ lattice at 1000 nits+ │+ HEVC Main 10 or ProRes, tagged bt2020 + HLG or PQ+```++PQ is one fixed pass at the end: every recipe targets HLG, and the PQ file is that composite through the OOTF and the ST 2084 curve. H.264 is 8-bit and greys out. The worker's HEVC writes HDR10 static metadata for PQ; the Mac's hardware encoder writes none, and players take the 1000-nit reference. A file already in the project's space with no grade copies its streams as is.++## HDR preview++On an HDR display in a browser with WebGPU, the stage composites in HLG and one extra pass per frame on a float16 canvas decodes the signal to display light, reference white at 1.0 with the headroom above it. When the display, the browser or the GPU cannot carry it, the stage renders the same grade as SDR and says "Previewing SDR". That is the one fallback.diff --git a/docs/guides/cut/local-compute.md b/docs/guides/cut/local-compute.mdindex 6534c06e..72a2ee44 100644--- a/docs/guides/cut/local-compute.md+++ b/docs/guides/cut/local-compute.md@@ -51,13 +51,11 @@ A client with no compositor at all asks by project id instead. The phone sends t## Converting footage-Imports and the assistant's conversion tool prepare playable H.264/AAC media through the backend that holds the file. Compatible streams copy into the new container. Unsupported streams are encoded, and a playable audio rendition takes precedence over optional spatial audio.+Imports and the assistant's conversion tool prepare playable H.264/AAC media through the backend that holds the file. Compatible streams copy into the new container; the rest are encoded, and a playable audio rendition takes precedence over optional spatial audio. The Library uploads originals even when browser probing fails; the worker prepares playback and retains the source. A browser-local project or shelf without the codec borrows hosted preparation, saves the result into its own storage, and removes the cloud copy. Project conversion keeps the asset id, so clips keep pointing at it.-The Library uploads originals even when browser probing fails; the worker prepares playback and retains the source for download. A browser-local project or shelf without the required codec borrows preparation, saves the result into its own storage, and removes the temporary cloud copy. The engine shelf uses the same worker when its tools fail. Hosted preparation requires a signed-in account with available storage and worker capacity.+## ProRes masters and preview proxies-Library drops share local previews and background storage across folders and panels; cards show “Importing”, and retries reuse uploaded bytes and jobs.--Project conversion keeps the asset id, so existing clips continue to reference it. The same tools run in the editor and headless clients.+ProRes is the one format kept as shot. The master stays in the project and is what every export reads; beside it lands a 10-bit HEVC preview proxy, carried into the Rec.709 matrix and tagged so that every decoder draws its values untouched. The asset's color record still describes the master, so the grade is the same picture either way. The proxy is built where the project lives — the engine for a Mac project, the worker for a cloud one (quota-exempt; the master counts), and for a browser project the page itself when it can encode 10-bit frames (Chrome; WebKit cannot), else the Mac when the app is there. Until it lands, and on a browser that can make none, the preview decodes the master through a WASM decoder: the same picture, slower. That is the one fallback, and the Color panel says so.## Rules@@ -74,6 +72,7 @@ Project conversion keeps the asset id, so existing clips continue to reference i| Export | the Mac for its own projects, the browser for cloud and browser ones, the worker when the tab can't encode the choice | see Export above || Thumbnails, waveforms, media probing | the browser, always | it decodes the media itself || Converting media to MP4 | the backend holding the bytes, with hosted preparation when the browser lacks a codec | see Converting footage above |+| Preview proxies of ProRes masters | the backend holding the bytes; a browser project encodes in the tab or on the Mac | see ProRes masters above || Image, video, and voice generation | hosted, always | no local counterpart || Cutout mattes | the quick person matte in the tab, on-device and free; the quality and tracked bakes hosted (credits), driven by the tab | the tab decodes the clip and owns the session; the engine and the worker only consume the stored matte asset || The assistant's Gemini models | hosted, always | credits and the user's session |diff --git a/evals/cut-chat.latest-report.json b/evals/cut-chat.latest-report.jsonindex 051ad4b9..da660bd6 100644--- a/evals/cut-chat.latest-report.json+++ b/evals/cut-chat.latest-report.json@@ -1,8 +1,8 @@{"schema": "cut-chat-eval/v1",- "generatedAt": "2026-09-18T07:05:46.192Z",+ "generatedAt": "2026-09-29T09:35:22.156Z","base": "http://localhost:3000",- "runsPerCase": 1,+ "runsPerCase": 3,"configs": [{"label": "config",@@ -12,70 +12,70 @@"cases": 9,"passRate": 1,"gateMs": {- "p50": 752,- "p95": 1078,- "mean": 694,+ "p50": 283,+ "p95": 329,+ "mean": 279,"n": 9},"ttftMs": {- "p50": 3301,- "p95": 5905,- "mean": 3347,+ "p50": 4931,+ "p95": 6805,+ "mean": 4349,"n": 9},"totalMs": {- "p50": 3601,- "p95": 6080,- "mean": 3723,+ "p50": 5027,+ "p95": 8093,+ "mean": 4978,"n": 9},- "meanRounds": 1.1+ "meanRounds": 1},"multi-tool": {"cases": 10,- "passRate": 0.8,+ "passRate": 0.9,"gateMs": {- "p50": 512,- "p95": 866,- "mean": 543,- "n": 8+ "p50": 299,+ "p95": 363,+ "mean": 303,+ "n": 9},"ttftMs": {- "p50": 5245,- "p95": 21510,- "mean": 8623,- "n": 8+ "p50": 6042,+ "p95": 35207,+ "mean": 10888,+ "n": 9},"totalMs": {- "p50": 5425,- "p95": 21856,- "mean": 8911,- "n": 8+ "p50": 6242,+ "p95": 35498,+ "mean": 11255,+ "n": 9},- "meanRounds": 3.5+ "meanRounds": 4.3},"single-tool": {"cases": 24,- "passRate": 1,+ "passRate": 0.99,"gateMs": {- "p50": 592,- "p95": 850,- "mean": 594,+ "p50": 288,+ "p95": 318,+ "mean": 287,"n": 24},"ttftMs": {- "p50": 3969,- "p95": 8597,- "mean": 4101,+ "p50": 3965,+ "p95": 13719,+ "mean": 5493,"n": 24},"totalMs": {- "p50": 4425,- "p95": 8859,- "mean": 4315,+ "p50": 4229,+ "p95": 14041,+ "mean": 5688,"n": 24},- "meanRounds": 1.8+ "meanRounds": 2.4}},"cases": [@@ -86,34 +86,34 @@"budgetBreaches": [],"latency": {"gateMs": {- "p50": 752,- "p95": 752,- "mean": 752,- "n": 1+ "p50": 226,+ "p95": 353,+ "mean": 266,+ "n": 3},"ttftMs": {- "p50": 3500,- "p95": 3500,- "mean": 3500,- "n": 1+ "p50": 6805,+ "p95": 9528,+ "mean": 6392,+ "n": 3},"totalMs": {- "p50": 3601,- "p95": 3601,- "mean": 3601,- "n": 1+ "p50": 7279,+ "p95": 9852,+ "mean": 6759,+ "n": 3},"modelMs": {- "p50": 2840,- "p95": 2840,- "mean": 2840,- "n": 1+ "p50": 6542,+ "p95": 9378,+ "mean": 6210,+ "n": 3},"toolMs": {"p50": 0,"p95": 0,"mean": 0,- "n": 1+ "n": 3},"rounds": {"mean": 1,@@ -133,26 +133,106 @@"side_panel","editor"],- "declaredTools": 63,+ "declaredTools": 66,+ "routingMisses": [],+ "roundModel": "gemini-3.8-flash",+ "notes": [],+ "instant": null,+ "qualityGate": [],+ "judgeNote": null,+ "trace": [],+ "timings": {+ "gateMs": 352.5657920000001,+ "gateSkipped": true,+ "ttftMs": 6804.758417,+ "modelMs": 6541.570333,+ "toolMs": 0,+ "totalMs": 7279.050333,+ "judgeMs": 202.53833399999894,+ "retryMs": 0,+ "retries": 0,+ "rounds": [+ {+ "roundMs": 6541.570333,+ "firstDeltaMs": 6447.532540999999,+ "calls": []+ }+ ]+ }+ },+ {+ "pass": true,+ "intent": "complex",+ "skill": null,+ "areas": [+ "inspector",+ "subtitles",+ "audio",+ "library",+ "side_panel",+ "editor"+ ],+ "declaredTools": 66,+ "routingMisses": [],+ "roundModel": "gemini-3.8-flash",+ "notes": [],+ "instant": null,+ "qualityGate": [],+ "judgeNote": null,+ "trace": [],+ "timings": {+ "gateMs": 225.58595799999966,+ "gateSkipped": true,+ "ttftMs": 9527.671041,+ "modelMs": 9378.321292,+ "toolMs": 0,+ "totalMs": 9852.140416,+ "judgeMs": 210.40312500000073,+ "retryMs": 0,+ "retries": 0,+ "rounds": [+ {+ "roundMs": 9378.321292,+ "firstDeltaMs": 9301.344417,+ "calls": []+ }+ ]+ }+ },+ {+ "pass": true,+ "intent": "complex",+ "skill": null,+ "areas": [+ "inspector",+ "subtitles",+ "audio",+ "library",+ "side_panel",+ "editor"+ ],+ "declaredTools": 66,"routingMisses": [],"roundModel": "gemini-3.8-flash","notes": [],"instant": null,+ "qualityGate": [],"judgeNote": null,"trace": [],"timings": {- "gateMs": 751.9499999999998,+ "gateMs": 220.65787499999715,"gateSkipped": true,- "ttftMs": 3500.395917,- "modelMs": 2840.4413749999994,+ "ttftMs": 2844.0305829999998,+ "modelMs": 2710.038249999998,"toolMs": 0,- "totalMs": 3600.748625,+ "totalMs": 3144.4576670000024,+ "judgeMs": 262.7090420000022,"retryMs": 0,"retries": 0,"rounds": [{- "roundMs": 2840.4413749999994,- "firstDeltaMs": 2740.714709,+ "roundMs": 2710.038249999998,+ "firstDeltaMs": 2621.184416,"calls": []}]@@ -167,34 +247,34 @@"budgetBreaches": [],"latency": {"gateMs": {- "p50": 475,- "p95": 475,- "mean": 475,- "n": 1+ "p50": 275,+ "p95": 324,+ "mean": 285,+ "n": 3},"ttftMs": {- "p50": 2381,- "p95": 2381,- "mean": 2381,- "n": 1+ "p50": 3755,+ "p95": 5724,+ "mean": 4038,+ "n": 3},"totalMs": {- "p50": 2510,- "p95": 2510,- "mean": 2510,- "n": 1+ "p50": 3778,+ "p95": 5758,+ "mean": 4067,+ "n": 3},"modelMs": {- "p50": 2034,- "p95": 2034,- "mean": 2034,- "n": 1+ "p50": 3522,+ "p95": 5481,+ "mean": 3780,+ "n": 3},"toolMs": {"p50": 0,"p95": 0,"mean": 0,- "n": 1+ "n": 3},"rounds": {"mean": 1,@@ -212,21 +292,87 @@"roundModel": "gemini-3.8-flash","notes": [],"instant": null,+ "qualityGate": [],+ "judgeNote": null,+ "trace": [],+ "timings": {+ "gateMs": 274.7531249999993,+ "gateSkipped": false,+ "ttftMs": 5724.422707999998,+ "modelMs": 5480.611250000002,+ "toolMs": 0,+ "totalMs": 5758.151915999999,+ "judgeMs": 217.0037080000002,+ "retryMs": 0,+ "retries": 0,+ "rounds": [+ {+ "roundMs": 5480.611250000002,+ "firstDeltaMs": 5447.382250000002,+ "calls": []+ }+ ]+ }+ },+ {+ "pass": true,+ "intent": "chat",+ "skill": null,+ "areas": [],+ "declaredTools": 0,+ "routingMisses": [],+ "roundModel": "gemini-3.8-flash",+ "notes": [],+ "instant": null,+ "qualityGate": [],+ "judgeNote": null,+ "trace": [],+ "timings": {+ "gateMs": 324.2627079999984,+ "gateSkipped": false,+ "ttftMs": 2633.5315839999967,+ "modelMs": 2338.3022089999977,+ "toolMs": 0,+ "totalMs": 2663.329167,+ "judgeMs": 231.75733300000138,+ "retryMs": 0,+ "retries": 0,+ "rounds": [+ {+ "roundMs": 2338.3022089999977,+ "firstDeltaMs": 2308.6519169999992,+ "calls": []+ }+ ]+ }+ },+ {+ "pass": true,+ "intent": "chat",+ "skill": null,+ "areas": [],+ "declaredTools": 0,+ "routingMisses": [],+ "roundModel": "gemini-3.8-flash",+ "notes": [],+ "instant": null,+ "qualityGate": [],"judgeNote": null,"trace": [],"timings": {- "gateMs": 475.3485419999997,+ "gateMs": 255.84183399999893,"gateSkipped": false,- "ttftMs": 2381.3076659999997,- "modelMs": 2033.6695000000009,+ "ttftMs": 3754.8822080000027,+ "modelMs": 3521.598665999998,"toolMs": 0,- "totalMs": 2509.934,+ "totalMs": 3778.106040999999,+ "judgeMs": 219.99225000000297,"retryMs": 0,"retries": 0,"rounds": [{- "roundMs": 2033.6695000000009,- "firstDeltaMs": 1905.125833000001,+ "roundMs": 3521.598665999998,+ "firstDeltaMs": 3498.4723749999976,"calls": []}]@@ -241,34 +387,34 @@"budgetBreaches": [],"latency": {"gateMs": {- "p50": 278,- "p95": 278,- "mean": 278,- "n": 1+ "p50": 301,+ "p95": 331,+ "mean": 311,+ "n": 3},"ttftMs": {- "p50": 4083,- "p95": 4083,- "mean": 4083,- "n": 1+ "p50": 4931,+ "p95": 5418,+ "mean": 4743,+ "n": 3},"totalMs": {- "p50": 4195,- "p95": 4195,- "mean": 4195,- "n": 1+ "p50": 5027,+ "p95": 5511,+ "mean": 4814,+ "n": 3},"modelMs": {- "p50": 3916,- "p95": 3916,- "mean": 3916,- "n": 1+ "p50": 4725,+ "p95": 5180,+ "mean": 4502,+ "n": 3},"toolMs": {"p50": 0,"p95": 0,"mean": 0,- "n": 1+ "n": 3},"rounds": {"mean": 1,@@ -286,21 +432,87 @@"roundModel": "gemini-3.8-flash","notes": [],"instant": null,+ "qualityGate": [],+ "judgeNote": "concise factual 0.46",+ "trace": [],+ "timings": {+ "gateMs": 301.02241700000013,+ "gateSkipped": false,+ "ttftMs": 4931.060791999997,+ "modelMs": 4724.819624999996,+ "toolMs": 0,+ "totalMs": 5026.555,+ "judgeMs": 235.64329100000032,+ "retryMs": 0,+ "retries": 0,+ "rounds": [+ {+ "roundMs": 4724.819624999996,+ "firstDeltaMs": 4629.475124999997,+ "calls": []+ }+ ]+ }+ },+ {+ "pass": true,+ "intent": "chat",+ "skill": null,+ "areas": [],+ "declaredTools": 0,+ "routingMisses": [],+ "roundModel": "gemini-3.8-flash",+ "notes": [],+ "instant": null,+ "qualityGate": [],+ "judgeNote": "concise factual 0.45",+ "trace": [],+ "timings": {+ "gateMs": 330.9295409999977,+ "gateSkipped": false,+ "ttftMs": 5418.156958,+ "modelMs": 5179.641499999998,+ "toolMs": 0,+ "totalMs": 5511.137750000002,+ "judgeMs": 221.82791599999473,+ "retryMs": 0,+ "retries": 0,+ "rounds": [+ {+ "roundMs": 5179.641499999998,+ "firstDeltaMs": 5086.774540999999,+ "calls": []+ }+ ]+ }+ },+ {+ "pass": true,+ "intent": "chat",+ "skill": null,+ "areas": [],+ "declaredTools": 0,+ "routingMisses": [],+ "roundModel": "gemini-3.8-flash",+ "notes": [],+ "instant": null,+ "qualityGate": [],"judgeNote": null,"trace": [],"timings": {- "gateMs": 277.72391699999935,+ "gateMs": 300.5991670000003,"gateSkipped": false,- "ttftMs": 4082.982749999999,- "modelMs": 3916.0172920000005,+ "ttftMs": 3879.5976660000015,+ "modelMs": 3601.7352909999972,"toolMs": 0,- "totalMs": 4194.766416999999,+ "totalMs": 3903.035125000002,+ "judgeMs": 245.40783300000476,"retryMs": 0,"retries": 0,"rounds": [{- "roundMs": 3916.0172920000005,- "firstDeltaMs": 3804.474957999999,+ "roundMs": 3601.7352909999972,+ "firstDeltaMs": 3578.5,"calls": []}]@@ -315,38 +527,38 @@"budgetBreaches": [],"latency": {"gateMs": {- "p50": 407,- "p95": 407,- "mean": 407,- "n": 1+ "p50": 288,+ "p95": 309,+ "mean": 295,+ "n": 3},"ttftMs": {- "p50": 4928,- "p95": 4928,- "mean": 4928,- "n": 1+ "p50": 4900,+ "p95": 6263,+ "mean": 5029,+ "n": 3},"totalMs": {- "p50": 5242,- "p95": 5242,- "mean": 5242,- "n": 1+ "p50": 5704,+ "p95": 6854,+ "mean": 5694,+ "n": 3},"modelMs": {- "p50": 4810,- "p95": 4810,- "mean": 4810,- "n": 1+ "p50": 5413,+ "p95": 6530,+ "mean": 5392,+ "n": 3},"toolMs": {"p50": 0,"p95": 0,"mean": 0,- "n": 1+ "n": 3},"rounds": {- "mean": 3,- "max": 3+ "mean": 2,+ "max": 2}},"runs": [@@ -362,305 +574,225 @@"library","editor"],- "declaredTools": 88,+ "declaredTools": 90,"routingMisses": [],"roundModel": "gemini-3.1-flash-lite","notes": [],"instant": null,+ "qualityGate": [],"judgeNote": null,"trace": [{"name": "update_cue","round": 0,- "atMs": 2124.233791999999,- "execMs": 0.25512499999967986,+ "atMs": 5040.534,+ "execMs": 0.19741700000304263,"args": {- "text": "So today we're",+ "text": "so today we're","id": "cue1"}},{"name": "update_cue","round": 0,- "atMs": 2125.486417,- "execMs": 0.0054579999996349216,- "args": {- "id": "cue3",- "text": "And they absolutely love the water"- }- },- {- "name": "delete_cue",- "round": 0,- "atMs": 2126.4399999999987,- "execMs": 0.030208000000129687,- "args": {- "id": "cue4"- }- },- {- "name": "update_cue",- "round": 0,- "atMs": 2126.7381669999995,- "execMs": 0.0301660000004631,- "args": {- "id": "cue5",- "text": "So let's watch them play"- }- },- {- "name": "align_to_audio",- "round": 1,- "atMs": 3672.1529169999994,- "execMs": 0.0031249999992724042,+ "atMs": 5041.484332999993,+ "execMs": 0.002499999995052349,"args": {- "track": 0,- "target": "captions"+ "text": "you know,",+ "id": "cue3"}}],"timings": {- "gateMs": 406.8742080000011,+ "gateMs": 308.6308749999953,"gateSkipped": false,- "ttftMs": 4928.412874999998,- "modelMs": 4810.0971240000035,- "toolMs": 0.32408199999917997,- "totalMs": 5242.333749999998,+ "ttftMs": 6263.223624999999,+ "modelMs": 6529.586832999994,+ "toolMs": 0.19991699999809498,+ "totalMs": 6854.3088329999955,+ "judgeMs": 256.5859999999957,"retryMs": 0,"retries": 0,"rounds": [{- "roundMs": 1698.6945830000004,+ "roundMs": 4718.679416999999,"firstDeltaMs": null,"calls": [{"name": "update_cue",- "execMs": 0.25512499999967986- },- {- "name": "update_cue",- "execMs": 0.0054579999996349216- },- {- "name": "delete_cue",- "execMs": 0.030208000000129687+ "execMs": 0.19741700000304263},{"name": "update_cue",- "execMs": 0.0301660000004631- }- ]- },- {- "roundMs": 1542.283416000002,- "firstDeltaMs": null,- "calls": [- {- "name": "align_to_audio",- "execMs": 0.0031249999992724042+ "execMs": 0.002499999995052349}]},{- "roundMs": 1569.119125000001,- "firstDeltaMs": 1255.656750000002,+ "roundMs": 1810.9074159999946,+ "firstDeltaMs": 1220.4254159999982,"calls": []}]}- }- ]- },- {- "name": "question-answers-in-chat",- "bucket": "chat",- "passRate": 1,- "budgetBreaches": [],- "latency": {- "gateMs": {- "p50": 1078,- "p95": 1078,- "mean": 1078,- "n": 1- },- "ttftMs": {- "p50": 2959,- "p95": 2959,- "mean": 2959,- "n": 1- },- "totalMs": {- "p50": 3498,- "p95": 3498,- "mean": 3498,- "n": 1},- "modelMs": {- "p50": 2486,- "p95": 2486,- "mean": 2486,- "n": 1- },- "toolMs": {- "p50": 0,- "p95": 0,- "mean": 0,- "n": 1- },- "rounds": {- "mean": 1,- "max": 1- }- },- "runs": [{"pass": true,"intent": "simple","skill": null,"areas": [- "timeline"+ "preview",+ "timeline",+ "inspector",+ "subtitles",+ "library",+ "editor"],- "declaredTools": 47,+ "declaredTools": 90,"routingMisses": [],"roundModel": "gemini-3.1-flash-lite","notes": [],"instant": null,+ "qualityGate": [],"judgeNote": null,- "trace": [],+ "trace": [+ {+ "name": "update_cue",+ "round": 0,+ "atMs": 1866.0425000000032,+ "execMs": 0.007666999998036772,+ "args": {+ "id": "cue1",+ "text": "So today we're"+ }+ },+ {+ "name": "update_cue",+ "round": 0,+ "atMs": 1866.2134159999987,+ "execMs": 0.0037919999958830886,+ "args": {+ "text": "you know,",+ "id": "cue3"+ }+ }+ ],"timings": {- "gateMs": 1078.0407919999998,+ "gateMs": 287.3754160000026,"gateSkipped": false,- "ttftMs": 2958.941083999998,- "modelMs": 2485.712374999999,- "toolMs": 0,- "totalMs": 3497.586959,+ "ttftMs": 3923.485915999998,+ "modelMs": 4232.716166999991,+ "toolMs": 0.01145899999391986,+ "totalMs": 4523.615082999997,+ "judgeMs": 219.96620800000528,"retryMs": 0,"retries": 0,"rounds": [{- "roundMs": 2485.712374999999,- "firstDeltaMs": 1947.2791660000003,- "calls": []- }- ]+ "roundMs": 1576.5418749999953,+ "firstDeltaMs": null,+ "calls": [+ {+ "name": "update_cue",+ "execMs": 0.007666999998036772+ },+ {+ "name": "update_cue",+ "execMs": 0.0037919999958830886+ }+ ]+ },+ {+ "roundMs": 2656.174291999996,+ "firstDeltaMs": 2056.1984999999986,+ "calls": []+ }+ ]}- }- ]- },- {- "name": "photos-request-places-clips",- "bucket": "multi-tool",- "passRate": 1,- "budgetBreaches": [],- "latency": {- "gateMs": {- "p50": 249,- "p95": 249,- "mean": 249,- "n": 1- },- "ttftMs": {- "p50": 5113,- "p95": 5113,- "mean": 5113,- "n": 1- },- "totalMs": {- "p50": 5420,- "p95": 5420,- "mean": 5420,- "n": 1- },- "modelMs": {- "p50": 5163,- "p95": 5163,- "mean": 5163,- "n": 1- },- "toolMs": {- "p50": 0,- "p95": 0,- "mean": 0,- "n": 1},- "rounds": {- "mean": 2,- "max": 2- }- },- "runs": [{"pass": true,- "intent": "complex",+ "intent": "simple","skill": null,"areas": ["preview","timeline","inspector",- "animation",- "transitions","subtitles",- "audio",- "video_gen",- "scene","library",- "side_panel",- "top_bar","editor"],- "declaredTools": 113,+ "declaredTools": 90,"routingMisses": [],- "roundModel": "gemini-3.8-flash",+ "roundModel": "gemini-3.1-flash-lite","notes": [],"instant": null,+ "qualityGate": [],"judgeNote": null,"trace": [{- "name": "add_clip",+ "name": "update_cue","round": 0,- "atMs": 2795.091916000001,- "execMs": 0.1444999999985157,+ "atMs": 3079.256125,+ "execMs": 0.008166999999957625,"args": {- "asset_id": "a-i1"+ "text": "so today we're",+ "id": "cue1"}},{- "name": "add_clip",+ "name": "update_cue","round": 0,- "atMs": 2795.5780410000007,- "execMs": 0.005708999997295905,+ "atMs": 3079.436624999995,+ "execMs": 0.004000000000814907,"args": {- "asset_id": "a-i2"+ "id": "cue3",+ "text": "you know,"+ }+ },+ {+ "name": "align_to_audio",+ "round": 0,+ "atMs": 3080.996165999997,+ "execMs": 0.0058749999952851795,+ "args": {+ "target": "captions",+ "track": 0}}],"timings": {- "gateMs": 248.82308300000295,- "gateSkipped": true,- "ttftMs": 5112.952958000002,- "modelMs": 5162.855334,- "toolMs": 0.1502089999958116,- "totalMs": 5419.996500000001,+ "gateMs": 287.60533399999986,+ "gateSkipped": false,+ "ttftMs": 4900.479290999996,+ "modelMs": 5412.996790999998,+ "toolMs": 0.01804199999605771,+ "totalMs": 5704.4517909999995,+ "judgeMs": 213.9017920000042,"retryMs": 0,"retries": 0,"rounds": [{- "roundMs": 2541.1369589999995,+ "roundMs": 2790.592582999998,"firstDeltaMs": null,"calls": [{- "name": "add_clip",- "execMs": 0.1444999999985157+ "name": "update_cue",+ "execMs": 0.008166999999957625},{- "name": "add_clip",- "execMs": 0.005708999997295905+ "name": "update_cue",+ "execMs": 0.004000000000814907+ },+ {+ "name": "align_to_audio",+ "execMs": 0.0058749999952851795}]},{- "roundMs": 2621.7183750000004,- "firstDeltaMs": 2316.1846250000017,+ "roundMs": 2622.404208,+ "firstDeltaMs": 1818.6448749999909,"calls": []}]@@ -669,40 +801,40 @@]},{- "name": "photos-question-stays-in-chat",+ "name": "question-answers-in-chat","bucket": "chat","passRate": 1,"budgetBreaches": [],"latency": {"gateMs": {- "p50": 817,- "p95": 817,- "mean": 817,- "n": 1+ "p50": 315,+ "p95": 367,+ "mean": 326,+ "n": 3},"ttftMs": {- "p50": 2992,- "p95": 2992,- "mean": 2992,- "n": 1+ "p50": 1314,+ "p95": 4220,+ "mean": 2251,+ "n": 3},"totalMs": {- "p50": 4421,- "p95": 4421,- "mean": 4421,- "n": 1+ "p50": 1804,+ "p95": 4675,+ "mean": 2680,+ "n": 3},"modelMs": {- "p50": 3601,- "p95": 3601,- "mean": 3601,- "n": 1+ "p50": 1206,+ "p95": 4018,+ "mean": 2102,+ "n": 3},"toolMs": {"p50": 0,"p95": 0,"mean": 0,- "n": 1+ "n": 3},"rounds": {"mean": 1,@@ -712,124 +844,101 @@"runs": [{"pass": true,- "intent": "complex",+ "intent": "simple","skill": null,"areas": [- "preview",- "timeline",- "inspector",- "elements",- "effects",- "animation",- "transitions",- "subtitles",- "video_gen",- "scene",- "stock",- "library",- "side_panel",- "top_bar",- "editor"+ "timeline"],- "declaredTools": 115,+ "declaredTools": 49,"routingMisses": [],- "roundModel": "gemini-3.8-flash",+ "roundModel": "gemini-3.1-flash-lite","notes": [],"instant": null,+ "qualityGate": [],"judgeNote": null,"trace": [],"timings": {- "gateMs": 817.0380829999995,- "gateSkipped": true,- "ttftMs": 2992.1068749999977,- "modelMs": 3601.0534579999985,+ "gateMs": 367.2477079999953,+ "gateSkipped": false,+ "ttftMs": 4220.395292000001,+ "modelMs": 4018.25,"toolMs": 0,- "totalMs": 4421.4308329999985,+ "totalMs": 4674.570416999995,+ "judgeMs": 190.72358299999905,"retryMs": 0,"retries": 0,"rounds": [{- "roundMs": 3601.0534579999985,- "firstDeltaMs": 2172.756792,+ "roundMs": 4018.25,+ "firstDeltaMs": 3852.0521249999874,"calls": []}]}- }- ]- },- {- "name": "clutter-complaint-deletes-nothing",- "bucket": "chat",- "passRate": 1,- "budgetBreaches": [],- "latency": {- "gateMs": {- "p50": 492,- "p95": 492,- "mean": 492,- "n": 1- },- "ttftMs": {- "p50": 5905,- "p95": 5905,- "mean": 5905,- "n": 1- },- "totalMs": {- "p50": 6080,- "p95": 6080,- "mean": 6080,- "n": 1- },- "modelMs": {- "p50": 5585,- "p95": 5585,- "mean": 5585,- "n": 1},- "toolMs": {- "p50": 0,- "p95": 0,- "mean": 0,- "n": 1+ {+ "pass": true,+ "intent": "simple",+ "skill": null,+ "areas": [+ "timeline"+ ],+ "declaredTools": 49,+ "routingMisses": [],+ "roundModel": "gemini-3.1-flash-lite",+ "notes": [],+ "instant": null,+ "qualityGate": [],+ "judgeNote": null,+ "trace": [],+ "timings": {+ "gateMs": 294.8747500000027,+ "gateSkipped": false,+ "ttftMs": 1220.4067080000095,+ "modelMs": 1083.1540419999947,+ "toolMs": 0,+ "totalMs": 1562.9170000000013,+ "judgeMs": 217.79933399999572,+ "retryMs": 0,+ "retries": 0,+ "rounds": [+ {+ "roundMs": 1083.1540419999947,+ "firstDeltaMs": 925.085917000004,+ "calls": []+ }+ ]+ }},- "rounds": {- "mean": 1,- "max": 1- }- },- "runs": [{"pass": true,- "intent": "chat",+ "intent": "simple","skill": null,"areas": [- "library",- "side_panel",- "top_bar",- "editor"+ "timeline"],- "declaredTools": 0,+ "declaredTools": 49,"routingMisses": [],- "roundModel": "gemini-3.8-flash",+ "roundModel": "gemini-3.1-flash-lite","notes": [],"instant": null,+ "qualityGate": [],"judgeNote": null,"trace": [],"timings": {- "gateMs": 491.5361249999987,+ "gateMs": 314.6208750000078,"gateSkipped": false,- "ttftMs": 5905.113250000002,- "modelMs": 5585.389167000001,+ "ttftMs": 1313.6030420000025,+ "modelMs": 1205.8607920000068,"toolMs": 0,- "totalMs": 6079.908624999996,+ "totalMs": 1803.9524589999928,+ "judgeMs": 241.892875000005,"retryMs": 0,"retries": 0,"rounds": [{- "roundMs": 5585.389167000001,- "firstDeltaMs": 5412.544207999999,+ "roundMs": 1205.8607920000068,+ "firstDeltaMs": 998.6018750000076,"calls": []}]@@ -838,40 +947,40 @@]},{- "name": "video-ask-single-generate",- "bucket": "single-tool",+ "name": "photos-request-places-clips",+ "bucket": "multi-tool","passRate": 1,"budgetBreaches": [],"latency": {"gateMs": {- "p50": 795,- "p95": 795,- "mean": 795,- "n": 1+ "p50": 299,+ "p95": 526,+ "mean": 347,+ "n": 3},"ttftMs": {- "p50": 6448,- "p95": 6448,- "mean": 6448,- "n": 1+ "p50": 9058,+ "p95": 16581,+ "mean": 10515,+ "n": 3},"totalMs": {- "p50": 6618,- "p95": 6618,- "mean": 6618,- "n": 1+ "p50": 9476,+ "p95": 16780,+ "mean": 10777,+ "n": 3},"modelMs": {- "p50": 5812,- "p95": 5812,- "mean": 5812,- "n": 1+ "p50": 9173,+ "p95": 16557,+ "mean": 10425,+ "n": 3},"toolMs": {"p50": 0,"p95": 0,"mean": 0,- "n": 1+ "n": 3},"rounds": {"mean": 2,@@ -881,115 +990,86 @@"runs": [{"pass": true,- "intent": "simple",+ "intent": "complex","skill": null,"areas": ["preview","timeline","inspector",+ "animation","transitions","subtitles","audio",- "image_gen","video_gen","scene",- "stock","library","side_panel",- "top_bar"+ "top_bar",+ "editor"],- "declaredTools": 110,+ "declaredTools": 115,"routingMisses": [],- "roundModel": "gemini-3.1-flash-lite",+ "roundModel": "gemini-3.8-flash","notes": [],"instant": null,+ "qualityGate": [],"judgeNote": null,"trace": [{- "name": "generate_video",+ "name": "add_clip",+ "round": 0,+ "atMs": 13439.891208000001,+ "execMs": 0.16291699999419507,+ "args": {+ "asset_id": "a-i1"+ }+ },+ {+ "name": "add_clip","round": 0,- "atMs": 5088.884749999997,- "execMs": 0.012250000007043127,+ "atMs": 13440.412375,+ "execMs": 0.0032499999942956492,"args": {- "prompt": "A cheerful, high-quality video clip of various dogs playing happily in a park, with sunlight filtering through the trees."+ "asset_id": "a-i2"}}],"timings": {- "gateMs": 795.0334579999981,- "gateSkipped": false,- "ttftMs": 6448.112207999999,- "modelMs": 5811.547957999996,- "toolMs": 0.012250000007043127,- "totalMs": 6618.454958000002,+ "gateMs": 214.77137500001118,+ "gateSkipped": true,+ "ttftMs": 16580.75787500001,+ "modelMs": 16557.499582999997,+ "toolMs": 0.16616699998849072,+ "totalMs": 16780.034750000006,+ "judgeMs": 228.37012500000128,"retryMs": 0,"retries": 0,"rounds": [{- "roundMs": 4285.026957999995,+ "roundMs": 13219.850583000007,"firstDeltaMs": null,"calls": [{- "name": "generate_video",- "execMs": 0.012250000007043127+ "name": "add_clip",+ "execMs": 0.16291699999419507+ },+ {+ "name": "add_clip",+ "execMs": 0.0032499999942956492}]},{- "roundMs": 1526.5210000000006,- "firstDeltaMs": 1357.8164160000015,+ "roundMs": 3337.6489999999903,+ "firstDeltaMs": 3138.8479579999985,"calls": []}]}- }- ]- },- {- "name": "video-ask-with-size-and-length",- "bucket": "single-tool",- "passRate": 1,- "budgetBreaches": [],- "latency": {- "gateMs": {- "p50": 811,- "p95": 811,- "mean": 811,- "n": 1- },- "ttftMs": {- "p50": 3969,- "p95": 3969,- "mean": 3969,- "n": 1- },- "totalMs": {- "p50": 4485,- "p95": 4485,- "mean": 4485,- "n": 1- },- "modelMs": {- "p50": 3668,- "p95": 3668,- "mean": 3668,- "n": 1- },- "toolMs": {- "p50": 0,- "p95": 0,- "mean": 0,- "n": 1},- "rounds": {- "mean": 2,- "max": 2- }- },- "runs": [{"pass": true,- "intent": "simple",+ "intent": "complex","skill": null,"areas": ["preview",@@ -997,165 +1077,150 @@"inspector","effects","animation",- "image_gen",+ "transitions",+ "subtitles",+ "audio","video_gen","scene",- "stock","library","side_panel","top_bar","editor"],- "declaredTools": 100,+ "declaredTools": 116,"routingMisses": [],- "roundModel": "gemini-3.1-flash-lite",+ "roundModel": "gemini-3.8-flash","notes": [],"instant": null,+ "qualityGate": [],"judgeNote": null,"trace": [{- "name": "generate_video",+ "name": "add_clip","round": 0,- "atMs": 2322.886375000002,- "execMs": 0.17270799999823794,+ "atMs": 6817.213625000004,+ "execMs": 0.008666999987326562,"args": {- "prompt": "A paper boat drifting across a calm puddle, cinematic lighting, realistic style.",- "resolution": "1080p",- "duration_seconds": 6+ "asset_id": "a-i1"+ }+ },+ {+ "name": "add_clip",+ "round": 0,+ "atMs": 6817.4075840000005,+ "execMs": 0.0028750000055879354,+ "args": {+ "asset_id": "a-i2"}}],"timings": {- "gateMs": 810.7333750000034,- "gateSkipped": false,- "ttftMs": 3968.5961670000033,- "modelMs": 3668.3251660000024,- "toolMs": 0.17270799999823794,- "totalMs": 4484.626792000003,+ "gateMs": 298.9635419999977,+ "gateSkipped": true,+ "ttftMs": 9057.790667000008,+ "modelMs": 9172.570582,+ "toolMs": 0.011541999992914498,+ "totalMs": 9475.603042000002,+ "judgeMs": 282.852040999991,"retryMs": 0,"retries": 0,"rounds": [{- "roundMs": 1508.015999999996,+ "roundMs": 6516.063290999999,"firstDeltaMs": null,"calls": [{- "name": "generate_video",- "execMs": 0.17270799999823794+ "name": "add_clip",+ "execMs": 0.008666999987326562+ },+ {+ "name": "add_clip",+ "execMs": 0.0028750000055879354}]},{- "roundMs": 2160.3091660000064,- "firstDeltaMs": 1644.4830409999995,+ "roundMs": 2656.5072910000017,+ "firstDeltaMs": 2239.090624999997,"calls": []}]}- }- ]- },- {- "name": "iterate-keeps-existing-clip",- "bucket": "single-tool",- "passRate": 1,- "budgetBreaches": [],- "latency": {- "gateMs": {- "p50": 307,- "p95": 307,- "mean": 307,- "n": 1- },- "ttftMs": {- "p50": 5298,- "p95": 5298,- "mean": 5298,- "n": 1- },- "totalMs": {- "p50": 5533,- "p95": 5533,- "mean": 5533,- "n": 1},- "modelMs": {- "p50": 5214,- "p95": 5214,- "mean": 5214,- "n": 1- },- "toolMs": {- "p50": 0,- "p95": 0,- "mean": 0,- "n": 1- },- "rounds": {- "mean": 2,- "max": 2- }- },- "runs": [{"pass": true,"intent": "complex",- "skill": "color-grading",+ "skill": "timeline-editing","areas": ["preview","timeline","inspector",- "color",- "effects",- "image_gen",+ "animation",+ "transitions",+ "subtitles",+ "audio","video_gen","scene","library","side_panel",- "top_bar"+ "top_bar",+ "editor"],- "declaredTools": 99,+ "declaredTools": 115,"routingMisses": [],"roundModel": "gemini-3.8-flash","notes": [],"instant": null,+ "qualityGate": [],"judgeNote": null,"trace": [{- "name": "generate_video",+ "name": "add_clip","round": 0,- "atMs": 3027.0715839999975,- "execMs": 0.13591699999960838,+ "atMs": 3465.237208000006,+ "execMs": 0.006999999997788109,"args": {- "reference_asset_id": "a-v1",- "prompt": "Ocean beach at golden-hour sunset, warm amber sunlight reflecting off the water and wet sand, gentle breaking waves, cinematic lighting, peaceful evening atmosphere",- "aspect": "9:16"+ "asset_id": "a-i1"+ }+ },+ {+ "name": "add_clip",+ "round": 0,+ "atMs": 3465.418583000006,+ "execMs": 0.002666000000317581,+ "args": {+ "asset_id": "a-i2"}}],"timings": {- "gateMs": 306.9752920000028,- "gateSkipped": false,- "ttftMs": 5298.402291999999,- "modelMs": 5213.711875000001,- "toolMs": 0.13591699999960838,- "totalMs": 5532.8675,+ "gateMs": 526.1055420000048,+ "gateSkipped": true,+ "ttftMs": 5907.248625000007,+ "modelMs": 5544.6760839999915,+ "toolMs": 0.00966599999810569,+ "totalMs": 6073.960541000008,+ "judgeMs": 225.02583300000697,"retryMs": 0,"retries": 0,"rounds": [{- "roundMs": 2712.246333000003,+ "roundMs": 2937.4768339999864,"firstDeltaMs": null,"calls": [{- "name": "generate_video",- "execMs": 0.13591699999960838+ "name": "add_clip",+ "execMs": 0.006999999997788109+ },+ {+ "name": "add_clip",+ "execMs": 0.002666000000317581}]},{- "roundMs": 2501.465541999998,- "firstDeltaMs": 2269.875957999997,+ "roundMs": 2607.199250000005,+ "firstDeltaMs": 2440.756999999998,"calls": []}]@@ -1164,184 +1229,106 @@]},{- "name": "mute-all-does-not-redo-prior-turn",- "bucket": "single-tool",+ "name": "photos-question-stays-in-chat",+ "bucket": "chat","passRate": 1,"budgetBreaches": [],"latency": {"gateMs": {- "p50": 909,- "p95": 909,- "mean": 909,- "n": 1+ "p50": 223,+ "p95": 323,+ "mean": 252,+ "n": 3},"ttftMs": {- "p50": 4834,- "p95": 4834,- "mean": 4834,- "n": 1+ "p50": 6418,+ "p95": 7141,+ "mean": 5188,+ "n": 3},"totalMs": {- "p50": 5123,- "p95": 5123,- "mean": 5123,- "n": 1+ "p50": 8093,+ "p95": 8955,+ "mean": 6874,+ "n": 3},"modelMs": {- "p50": 4204,- "p95": 4204,- "mean": 4204,- "n": 1+ "p50": 7485,+ "p95": 8415,+ "mean": 6350,+ "n": 3},"toolMs": {"p50": 0,"p95": 0,"mean": 0,- "n": 1+ "n": 3},"rounds": {- "mean": 3,- "max": 3+ "mean": 1,+ "max": 1}},"runs": [{"pass": true,- "intent": "simple",+ "intent": "complex","skill": null,"areas": [+ "preview","timeline","inspector",+ "elements",+ "transitions",+ "subtitles","audio",+ "video_gen",+ "scene",+ "stock",+ "library",+ "side_panel",+ "top_bar","editor"],- "declaredTools": 67,+ "declaredTools": 118,"routingMisses": [],- "roundModel": "gemini-3.1-flash-lite",+ "roundModel": "gemini-3.8-flash","notes": [],"instant": null,- "judgeNote": null,- "trace": [- {- "name": "select_items",- "round": 0,- "atMs": 2385.5478339999972,- "execMs": 0.19141600000148173,- "args": {- "kind": "clip",- "describe": "all clips on track 0"- }- },- {- "name": "set_clip_muted",- "round": 1,- "atMs": 3529.144124999999,- "execMs": 0.017082999998820014,- "args": {- "muted": true,- "ids": [- "c1",- "c2",- "c3"- ]- }- }- ],+ "qualityGate": [],+ "judgeNote": "concise factual 0.29; upsell 0.86; long 2.0",+ "trace": [],"timings": {- "gateMs": 908.9641670000055,- "gateSkipped": false,- "ttftMs": 4834.076333999998,- "modelMs": 4203.940291999999,- "toolMs": 0.20849900000030175,- "totalMs": 5123.414583999998,+ "gateMs": 211.3352920000034,+ "gateSkipped": true,+ "ttftMs": 6418.420958000002,+ "modelMs": 7484.65058300001,+ "toolMs": 0,+ "totalMs": 8093.259667000006,+ "judgeMs": 261.5647920000047,"retryMs": 0,"retries": 0,"rounds": [{- "roundMs": 1470.966999999997,- "firstDeltaMs": null,- "calls": [- {- "name": "select_items",- "execMs": 0.19141600000148173- }- ]- },- {- "roundMs": 1140.6413749999992,- "firstDeltaMs": null,- "calls": [- {- "name": "set_clip_muted",- "execMs": 0.017082999998820014- }- ]- },- {- "roundMs": 1592.3319170000032,- "firstDeltaMs": 1303.296374999998,+ "roundMs": 7484.65058300001,+ "firstDeltaMs": 6206.224249999999,"calls": []}]}- }- ]- },- {- "name": "imported-photo-edit-references-photo",- "bucket": "single-tool",- "passRate": 1,- "budgetBreaches": [],- "latency": {- "gateMs": {- "p50": 757,- "p95": 757,- "mean": 757,- "n": 1- },- "ttftMs": {- "p50": 4128,- "p95": 4128,- "mean": 4128,- "n": 1- },- "totalMs": {- "p50": 4425,- "p95": 4425,- "mean": 4425,- "n": 1- },- "modelMs": {- "p50": 3665,- "p95": 3665,- "mean": 3665,- "n": 1- },- "toolMs": {- "p50": 0,- "p95": 0,- "mean": 0,- "n": 1},- "rounds": {- "mean": 2,- "max": 2- }- },- "runs": [{"pass": true,- "intent": "simple",+ "intent": "complex","skill": null,"areas": ["preview","timeline","inspector",- "removal","elements",- "effects",- "animation",- "image_gen",+ "transitions",+ "subtitles",+ "audio","video_gen","scene","stock",@@ -1350,106 +1337,44 @@"top_bar","editor"],- "declaredTools": 106,+ "declaredTools": 118,"routingMisses": [],- "roundModel": "gemini-3.1-flash-lite",+ "roundModel": "gemini-3.8-flash","notes": [],"instant": null,- "judgeNote": null,- "trace": [- {- "name": "generate_image",- "round": 0,- "atMs": 2502.2063749999943,- "execMs": 0.04870800000207964,- "args": {- "prompt": "The girl from the referenced image wearing a festive Santa hat in the snow, same style, pose, and background.",- "reference_asset_ids": [- "a-tw1"- ]- }- }- ],+ "qualityGate": [],+ "judgeNote": "concise factual 0.17; upsell 0.62; long 2.0",+ "trace": [],"timings": {- "gateMs": 756.6971669999984,- "gateSkipped": false,- "ttftMs": 4127.637624999996,- "modelMs": 3664.519748999999,- "toolMs": 0.04870800000207964,- "totalMs": 4424.780249999996,+ "gateMs": 222.674125000005,+ "gateSkipped": true,+ "ttftMs": 2005.486791000003,+ "modelMs": 3151.868583000003,+ "toolMs": 0,+ "totalMs": 3574.1149999999907,+ "judgeMs": 291.90154199999233,"retryMs": 0,"retries": 0,"rounds": [{- "roundMs": 1742.7812909999993,- "firstDeltaMs": null,- "calls": [- {- "name": "generate_image",- "execMs": 0.04870800000207964- }- ]- },- {- "roundMs": 1921.7384579999998,- "firstDeltaMs": 1624.8548329999976,+ "roundMs": 3151.868583000003,+ "firstDeltaMs": 1780.6883329999982,"calls": []}]}- }- ]- },- {- "name": "audio-ask-single-generate",- "bucket": "single-tool",- "passRate": 1,- "budgetBreaches": [],- "latency": {- "gateMs": {- "p50": 322,- "p95": 322,- "mean": 322,- "n": 1- },- "ttftMs": {- "p50": 3948,- "p95": 3948,- "mean": 3948,- "n": 1- },- "totalMs": {- "p50": 4216,- "p95": 4216,- "mean": 4216,- "n": 1- },- "modelMs": {- "p50": 3823,- "p95": 3823,- "mean": 3823,- "n": 1- },- "toolMs": {- "p50": 0,- "p95": 0,- "mean": 0,- "n": 1},- "rounds": {- "mean": 2,- "max": 2- }- },- "runs": [{"pass": true,- "intent": "simple",+ "intent": "complex","skill": null,"areas": ["preview","timeline","inspector",+ "elements",+ "effects",+ "transitions","subtitles","audio","video_gen",@@ -1457,48 +1382,31 @@"stock","library","side_panel",- "top_bar"+ "top_bar",+ "editor"],- "declaredTools": 109,+ "declaredTools": 119,"routingMisses": [],- "roundModel": "gemini-3.1-flash-lite",+ "roundModel": "gemini-3.8-flash","notes": [],"instant": null,- "judgeNote": null,- "trace": [- {- "name": "voiceover_generate",- "round": 0,- "atMs": 1921.885417000005,- "execMs": 0.005000000004656613,- "args": {- "script": "Welcome to the dog show."- }- }- ],+ "qualityGate": [],+ "judgeNote": "concise factual 0.19; upsell 0.91; long 2.0",+ "trace": [],"timings": {- "gateMs": 321.8137080000015,- "gateSkipped": false,- "ttftMs": 3947.758750000001,- "modelMs": 3823.3654579999857,- "toolMs": 0.005000000004656613,- "totalMs": 4215.509624999999,+ "gateMs": 322.5453750000015,+ "gateSkipped": true,+ "ttftMs": 7140.687458,+ "modelMs": 8414.779208999986,+ "toolMs": 0,+ "totalMs": 8954.787332999986,+ "judgeMs": 285.74741700000595,"retryMs": 0,"retries": 0,"rounds": [{- "roundMs": 1592.3975829999981,- "firstDeltaMs": null,- "calls": [- {- "name": "voiceover_generate",- "execMs": 0.005000000004656613- }- ]- },- {- "roundMs": 2230.9678749999875,- "firstDeltaMs": 2025.0072919999948,+ "roundMs": 8414.779208999986,+ "firstDeltaMs": 6817.368124999994,"calls": []}]@@ -1507,110 +1415,153 @@]},{- "name": "music-ask-single-generate",- "bucket": "single-tool",+ "name": "clutter-complaint-deletes-nothing",+ "bucket": "chat","passRate": 1,"budgetBreaches": [],"latency": {"gateMs": {- "p50": 850,- "p95": 850,- "mean": 850,- "n": 1+ "p50": 267,+ "p95": 285,+ "mean": 268,+ "n": 3},"ttftMs": {- "p50": 6096,- "p95": 6096,- "mean": 6096,- "n": 1+ "p50": 5790,+ "p95": 7918,+ "mean": 6454,+ "n": 3},"totalMs": {- "p50": 6399,- "p95": 6399,- "mean": 6399,- "n": 1+ "p50": 5935,+ "p95": 8169,+ "mean": 6628,+ "n": 3},"modelMs": {- "p50": 5536,- "p95": 5536,- "mean": 5536,- "n": 1+ "p50": 5649,+ "p95": 7901,+ "mean": 6359,+ "n": 3},"toolMs": {"p50": 0,"p95": 0,"mean": 0,- "n": 1+ "n": 3},"rounds": {- "mean": 2,- "max": 2+ "mean": 1,+ "max": 1}},"runs": [{"pass": true,- "intent": "complex",- "skill": "audio-and-subtitles",+ "intent": "chat",+ "skill": null,"areas": [- "preview",- "timeline",- "inspector",- "subtitles",- "audio",- "stock","library","side_panel",- "top_bar"+ "top_bar",+ "editor"],- "declaredTools": 101,+ "declaredTools": 0,"routingMisses": [],"roundModel": "gemini-3.8-flash","notes": [],"instant": null,+ "qualityGate": [],"judgeNote": null,- "trace": [- {- "name": "generate_music",- "round": 0,- "atMs": 3481.038625000001,- "execMs": 0.0917500000068685,- "args": {- "add_to_timeline": true,- "volume": 0.4,- "instrumental": true,- "reference_asset_ids": [- "a-v1"- ],- "length": "clip",- "prompt": "Chill, relaxing lofi background music with mellow electric piano, soft downtempo beats, and a warm, breezy beach vibe",- "start": 0+ "trace": [],+ "timings": {+ "gateMs": 266.54287500001374,+ "gateSkipped": false,+ "ttftMs": 7917.823957999994,+ "modelMs": 7900.989583999995,+ "toolMs": 0,+ "totalMs": 8168.597749999986,+ "judgeMs": 216.06266599998344,+ "retryMs": 0,+ "retries": 0,+ "rounds": [+ {+ "roundMs": 7900.989583999995,+ "firstDeltaMs": 7650.463292,+ "calls": []}- }+ ]+ }+ },+ {+ "pass": true,+ "intent": "chat",+ "skill": null,+ "areas": [+ "library",+ "side_panel",+ "top_bar",+ "editor"],+ "declaredTools": 0,+ "routingMisses": [],+ "roundModel": "gemini-3.8-flash",+ "notes": [],+ "instant": null,+ "qualityGate": [],+ "judgeNote": null,+ "trace": [],"timings": {- "gateMs": 850.0238329999993,+ "gateMs": 253.84899999998743,"gateSkipped": false,- "ttftMs": 6096.321041999996,- "modelMs": 5535.9060839999875,- "toolMs": 0.0917500000068685,- "totalMs": 6399.091459000003,+ "ttftMs": 5653.489499999996,+ "modelMs": 5525.969624999998,+ "toolMs": 0,+ "totalMs": 5780.543166999996,+ "judgeMs": 245.9249579999887,"retryMs": 0,"retries": 0,"rounds": [{- "roundMs": 2619.8032089999906,- "firstDeltaMs": null,- "calls": [- {- "name": "generate_music",- "execMs": 0.0917500000068685- }- ]- },+ "roundMs": 5525.969624999998,+ "firstDeltaMs": 5399.108584000001,+ "calls": []+ }+ ]+ }+ },+ {+ "pass": true,+ "intent": "chat",+ "skill": null,+ "areas": [+ "library",+ "side_panel",+ "top_bar",+ "editor"+ ],+ "declaredTools": 0,+ "routingMisses": [],+ "roundModel": "gemini-3.8-flash",+ "notes": [],+ "instant": null,+ "qualityGate": [],+ "judgeNote": "concise factual 0.46",+ "trace": [],+ "timings": {+ "gateMs": 284.60658299998613,+ "gateSkipped": false,+ "ttftMs": 5789.619500000001,+ "modelMs": 5649.31025000001,+ "toolMs": 0,+ "totalMs": 5934.561249999999,+ "judgeMs": 341.0812910000095,+ "retryMs": 0,+ "retries": 0,+ "rounds": [{- "roundMs": 2916.102874999997,- "firstDeltaMs": 2614.406124999994,+ "roundMs": 5649.31025000001,+ "firstDeltaMs": 5504.599749999994,"calls": []}]@@ -1619,40 +1570,40 @@]},{- "name": "trim-ask-single-tool",+ "name": "video-ask-single-generate","bucket": "single-tool","passRate": 1,"budgetBreaches": [],"latency": {"gateMs": {- "p50": 837,- "p95": 837,- "mean": 837,- "n": 1+ "p50": 299,+ "p95": 299,+ "mean": 294,+ "n": 3},"ttftMs": {- "p50": 3502,- "p95": 3502,- "mean": 3502,- "n": 1+ "p50": 6543,+ "p95": 6568,+ "mean": 5416,+ "n": 3},"totalMs": {- "p50": 3588,- "p95": 3588,- "mean": 3588,- "n": 1+ "p50": 6718,+ "p95": 6746,+ "mean": 5602,+ "n": 3},"modelMs": {- "p50": 2744,- "p95": 2744,- "mean": 2744,- "n": 1+ "p50": 6414,+ "p95": 6442,+ "mean": 5304,+ "n": 3},"toolMs": {"p50": 0,"p95": 0,"mean": 0,- "n": 1+ "n": 3},"rounds": {"mean": 2,@@ -1668,184 +1619,238 @@"preview","timeline","inspector",- "editor"+ "animation",+ "transitions",+ "subtitles",+ "audio",+ "image_gen",+ "video_gen",+ "scene",+ "stock",+ "library",+ "side_panel",+ "top_bar"],- "declaredTools": 68,+ "declaredTools": 114,"routingMisses": [],"roundModel": "gemini-3.1-flash-lite","notes": [],"instant": null,+ "qualityGate": [],"judgeNote": null,"trace": [{- "name": "trim_clip",+ "name": "generate_video","round": 0,- "atMs": 2280.0104170000122,- "execMs": 0.008708000008482486,+ "atMs": 5251.609457999992,+ "execMs": 0.0026670000224839896,"args": {- "out": 5,- "clipId": "c1"+ "prompt": "A playful, high-energy video of various dogs running, playing, and wagging their tails in a sunlit park, cinematic quality."}}],"timings": {- "gateMs": 836.6947920000093,+ "gateMs": 299.0597499999858,"gateSkipped": false,- "ttftMs": 3501.8193750000064,- "modelMs": 2744.2223740000045,- "toolMs": 0.008708000008482486,- "totalMs": 3587.7598340000113,+ "ttftMs": 6567.9794160000165,+ "modelMs": 6414.450792000018,+ "toolMs": 0.0026670000224839896,+ "totalMs": 6717.698540999991,+ "judgeMs": 234.98737499999697,"retryMs": 0,"retries": 0,"rounds": [{- "roundMs": 1438.0812910000095,+ "roundMs": 4949.058500000014,"firstDeltaMs": null,"calls": [{- "name": "trim_clip",- "execMs": 0.008708000008482486+ "name": "generate_video",+ "execMs": 0.0026670000224839896}]},{- "roundMs": 1306.141082999995,- "firstDeltaMs": 1220.7547079999931,+ "roundMs": 1465.392292000004,+ "firstDeltaMs": 1315.7593749999942,"calls": []}]}- }- ]- },- {- "name": "transition-ask-styled",- "bucket": "single-tool",- "passRate": 1,- "budgetBreaches": [],- "latency": {- "gateMs": {- "p50": 592,- "p95": 592,- "mean": 592,- "n": 1- },- "ttftMs": {- "p50": 595,- "p95": 595,- "mean": 595,- "n": 1},- "totalMs": {- "p50": 595,- "p95": 595,- "mean": 595,- "n": 1- },- "modelMs": {- "p50": 0,- "p95": 0,- "mean": 0,- "n": 1- },- "toolMs": {- "p50": 0,- "p95": 0,- "mean": 0,- "n": 1+ {+ "pass": true,+ "intent": "simple",+ "skill": null,+ "areas": [+ "preview",+ "timeline",+ "inspector",+ "transitions",+ "subtitles",+ "audio",+ "image_gen",+ "video_gen",+ "scene",+ "stock",+ "library",+ "side_panel",+ "top_bar"+ ],+ "declaredTools": 112,+ "routingMisses": [],+ "roundModel": "gemini-3.1-flash-lite",+ "notes": [],+ "instant": null,+ "qualityGate": [],+ "judgeNote": null,+ "trace": [+ {+ "name": "generate_video",+ "round": 0,+ "atMs": 5383.152834000008,+ "execMs": 0.007874999981140718,+ "args": {+ "prompt": "a dog playing in a park, happy, sunny weather, high quality"+ }+ }+ ],+ "timings": {+ "gateMs": 299.3892079999787,+ "gateSkipped": false,+ "ttftMs": 6543.118125000008,+ "modelMs": 6442.472707999987,+ "toolMs": 0.007874999981140718,+ "totalMs": 6745.6967920000025,+ "judgeMs": 218.95854200000758,+ "retryMs": 0,+ "retries": 0,+ "rounds": [+ {+ "roundMs": 5082.10824999999,+ "firstDeltaMs": null,+ "calls": [+ {+ "name": "generate_video",+ "execMs": 0.007874999981140718+ }+ ]+ },+ {+ "roundMs": 1360.3644579999964,+ "firstDeltaMs": 1158.0721670000057,+ "calls": []+ }+ ]+ }},- "rounds": {- "mean": 0,- "max": 0- }- },- "runs": [{"pass": true,- "intent": "complex",- "skill": "transitions-and-fades",+ "intent": "simple",+ "skill": null,"areas": ["preview","timeline","inspector",- "effects",- "animation","transitions",- "top_bar",- "editor"+ "subtitles",+ "audio",+ "image_gen",+ "video_gen",+ "scene",+ "stock",+ "library",+ "side_panel",+ "top_bar"],- "declaredTools": 75,+ "declaredTools": 112,"routingMisses": [],- "roundModel": "gemini-3.8-flash",+ "roundModel": "gemini-3.1-flash-lite","notes": [],- "instant": "set_transition",+ "instant": null,+ "qualityGate": [],"judgeNote": null,"trace": [{- "name": "set_transition",+ "name": "generate_video","round": 0,- "atMs": 594.0010829999956,- "execMs": 0.13120899999921676,+ "atMs": 1732.363667000027,+ "execMs": 0.00229199999012053,"args": {- "clipId": "c1",- "style": "pushdown",- "seconds": 0.44+ "prompt": "A playful, high-energy video of various dog breeds running and jumping in a park, bright sunny lighting, handheld camera movement."}}],"timings": {- "gateMs": 592.17908300001,+ "gateMs": 282.55079199999454,"gateSkipped": false,- "ttftMs": 594.9516670000012,- "modelMs": 0,- "toolMs": 0.13120899999921676,- "totalMs": 594.9638750000013,+ "ttftMs": 3137.222417000012,+ "modelMs": 3056.4819990000105,+ "toolMs": 0.00229199999012053,+ "totalMs": 3342.322084000014,+ "judgeMs": 224.98716600000625,"retryMs": 0,"retries": 0,- "rounds": []+ "rounds": [+ {+ "roundMs": 1447.3806660000118,+ "firstDeltaMs": null,+ "calls": [+ {+ "name": "generate_video",+ "execMs": 0.00229199999012053+ }+ ]+ },+ {+ "roundMs": 1609.1013329999987,+ "firstDeltaMs": 1404.2079580000136,+ "calls": []+ }+ ]}}]},{- "name": "slide-in-direction-correct",+ "name": "video-ask-with-size-and-length","bucket": "single-tool","passRate": 1,"budgetBreaches": [],"latency": {"gateMs": {- "p50": 296,- "p95": 296,- "mean": 296,- "n": 1+ "p50": 310,+ "p95": 372,+ "mean": 316,+ "n": 3},"ttftMs": {- "p50": 298,- "p95": 298,- "mean": 298,- "n": 1+ "p50": 2955,+ "p95": 6634,+ "mean": 4111,+ "n": 3},"totalMs": {- "p50": 298,- "p95": 298,- "mean": 298,- "n": 1+ "p50": 3169,+ "p95": 6819,+ "mean": 4323,+ "n": 3},"modelMs": {- "p50": 0,- "p95": 0,- "mean": 0,- "n": 1+ "p50": 2902,+ "p95": 6443,+ "mean": 4004,+ "n": 3},"toolMs": {"p50": 0,"p95": 0,"mean": 0,- "n": 1+ "n": 3},"rounds": {- "mean": 0,- "max": 0+ "mean": 2,+ "max": 2}},"runs": [@@ -1859,85 +1864,64 @@"inspector","effects","animation",- "transitions",+ "image_gen",+ "video_gen",+ "scene",+ "stock",+ "library",+ "side_panel",+ "top_bar","editor"],- "declaredTools": 71,+ "declaredTools": 102,"routingMisses": [],"roundModel": "gemini-3.1-flash-lite","notes": [],- "instant": "set_animation",+ "instant": null,+ "qualityGate": [],"judgeNote": null,"trace": [{- "name": "set_animation",+ "name": "generate_video","round": 0,- "atMs": 297.36262500000885,- "execMs": 0.33029199999873526,+ "atMs": 5339.653666999977,+ "execMs": 0.38020799998776056,"args": {- "clipId": "c2",- "which": "in",- "style": "slideright",- "seconds": 0.46+ "prompt": "A paper boat drifting across a puddle, cinematic lighting, top-down perspective, high quality, 1080p.",+ "duration_seconds": 6,+ "resolution": "1080p"}}],"timings": {- "gateMs": 296.43612500000745,+ "gateMs": 372.2609999999986,"gateSkipped": false,- "ttftMs": 298.36795800000255,- "modelMs": 0,- "toolMs": 0.33029199999873526,- "totalMs": 298.38979200000176,+ "ttftMs": 6633.895874999987,+ "modelMs": 6442.698667999997,+ "toolMs": 0.38020799998776056,+ "totalMs": 6818.572583000001,+ "judgeMs": 310.25191700001596,"retryMs": 0,"retries": 0,- "rounds": []+ "rounds": [+ {+ "roundMs": 4966.019333999982,+ "firstDeltaMs": null,+ "calls": [+ {+ "name": "generate_video",+ "execMs": 0.38020799998776056+ }+ ]+ },+ {+ "roundMs": 1476.679334000015,+ "firstDeltaMs": 1292.443459000002,+ "calls": []+ }+ ]}- }- ]- },- {- "name": "look-ask-single-tool",- "bucket": "single-tool",- "passRate": 1,- "budgetBreaches": [],- "latency": {- "gateMs": {- "p50": 309,- "p95": 309,- "mean": 309,- "n": 1- },- "ttftMs": {- "p50": 310,- "p95": 310,- "mean": 310,- "n": 1},- "totalMs": {- "p50": 310,- "p95": 310,- "mean": 310,- "n": 1- },- "modelMs": {- "p50": 0,- "p95": 0,- "mean": 0,- "n": 1- },- "toolMs": {- "p50": 0,- "p95": 0,- "mean": 0,- "n": 1- },- "rounds": {- "mean": 0,- "max": 0- }- },- "runs": [{"pass": true,"intent": "simple",@@ -1946,90 +1930,66 @@"preview","timeline","inspector",- "color","effects",+ "animation",+ "image_gen","video_gen","scene",+ "stock","library","side_panel",- "top_bar"+ "top_bar",+ "editor"],- "declaredTools": 98,+ "declaredTools": 102,"routingMisses": [],"roundModel": "gemini-3.1-flash-lite","notes": [],- "instant": "add_effect",+ "instant": null,+ "qualityGate": [],"judgeNote": null,"trace": [{- "name": "add_effect",+ "name": "generate_video","round": 0,- "atMs": 310.01116699998965,- "execMs": 0.05783299999893643,+ "atMs": 1584.980291999993,+ "execMs": 0.004374999989522621,"args": {- "effect": "vhs",- "amount": 0.68,- "start": 6,- "end": 12.5+ "duration_seconds": 6,+ "resolution": "1080p",+ "prompt": "A paper boat drifting across a puddle, realistic and close up, cinematic lighting, 1080p."}}],"timings": {- "gateMs": 309.3189999999886,+ "gateMs": 310.2955420000071,"gateSkipped": false,- "ttftMs": 310.1793340000004,- "modelMs": 0,- "toolMs": 0.05783299999893643,- "totalMs": 310.18399999999383,+ "ttftMs": 2743.3947089999856,+ "modelMs": 2667.625916000019,+ "toolMs": 0.004374999989522621,+ "totalMs": 2981.154291999992,+ "judgeMs": 224.60754200001247,"retryMs": 0,"retries": 0,- "rounds": []+ "rounds": [+ {+ "roundMs": 1272.787083000003,+ "firstDeltaMs": null,+ "calls": [+ {+ "name": "generate_video",+ "execMs": 0.004374999989522621+ }+ ]+ },+ {+ "roundMs": 1394.8388330000162,+ "firstDeltaMs": 1157.1951250000275,+ "calls": []+ }+ ]}- }- ]- },- {- "name": "audio-effect-single-tool",- "bucket": "single-tool",- "passRate": 1,- "budgetBreaches": [],- "latency": {- "gateMs": {- "p50": 446,- "p95": 446,- "mean": 446,- "n": 1- },- "ttftMs": {- "p50": 448,- "p95": 448,- "mean": 448,- "n": 1- },- "totalMs": {- "p50": 448,- "p95": 448,- "mean": 448,- "n": 1- },- "modelMs": {- "p50": 0,- "p95": 0,- "mean": 0,- "n": 1- },- "toolMs": {- "p50": 1,- "p95": 1,- "mean": 1,- "n": 1},- "rounds": {- "mean": 0,- "max": 0- }- },- "runs": [{"pass": true,"intent": "simple",@@ -2039,78 +1999,102 @@"timeline","inspector","effects",- "audio",- "side_panel"+ "animation",+ "image_gen",+ "video_gen",+ "scene",+ "stock",+ "library",+ "side_panel",+ "top_bar",+ "editor"],- "declaredTools": 76,+ "declaredTools": 102,"routingMisses": [],"roundModel": "gemini-3.1-flash-lite","notes": [],- "instant": "add_effect",+ "instant": null,+ "qualityGate": [],"judgeNote": null,"trace": [{- "name": "add_effect",+ "name": "generate_video","round": 0,- "atMs": 446.8479170000064,- "execMs": 0.6220420000026934,+ "atMs": 1816.2158749999944,+ "execMs": 0.0025000000023283064,"args": {- "effect": "telephone",- "amount": 0.69,- "start": 6,- "end": 12.5+ "prompt": "a paper boat drifting across a puddle, cinematic lighting, top-down view, 1080p resolution",+ "resolution": "1080p",+ "duration_seconds": 6}}],"timings": {- "gateMs": 446.43024999999034,+ "gateMs": 264.6728749999893,"gateSkipped": false,- "ttftMs": 447.7173330000078,- "modelMs": 0,- "toolMs": 0.6220420000026934,- "totalMs": 447.7283330000064,+ "ttftMs": 2954.834541999997,+ "modelMs": 2901.8779170000053,+ "toolMs": 0.0025000000023283064,+ "totalMs": 3168.7127920000057,+ "judgeMs": 228.03629200000432,"retryMs": 0,"retries": 0,- "rounds": []+ "rounds": [+ {+ "roundMs": 1550.0100000000093,+ "firstDeltaMs": null,+ "calls": [+ {+ "name": "generate_video",+ "execMs": 0.0025000000023283064+ }+ ]+ },+ {+ "roundMs": 1351.867916999996,+ "firstDeltaMs": 1138.1755419999827,+ "calls": []+ }+ ]}}]},{- "name": "sound-dissolve-single-tool",+ "name": "iterate-keeps-existing-clip","bucket": "single-tool","passRate": 1,"budgetBreaches": [],"latency": {"gateMs": {- "p50": 318,- "p95": 318,- "mean": 318,- "n": 1+ "p50": 289,+ "p95": 329,+ "mean": 302,+ "n": 3},"ttftMs": {- "p50": 3053,- "p95": 3053,- "mean": 3053,- "n": 1+ "p50": 9848,+ "p95": 16469,+ "mean": 12013,+ "n": 3},"totalMs": {- "p50": 3551,- "p95": 3551,- "mean": 3551,- "n": 1+ "p50": 10348,+ "p95": 16769,+ "mean": 12415,+ "n": 3},"modelMs": {- "p50": 3220,- "p95": 3220,- "mean": 3220,- "n": 1+ "p50": 10056,+ "p95": 16476,+ "mean": 12110,+ "n": 3},"toolMs": {"p50": 0,"p95": 0,"mean": 0,- "n": 1+ "n": 3},"rounds": {"mean": 2,@@ -2120,532 +2104,189 @@"runs": [{"pass": true,- "intent": "simple",- "skill": null,+ "intent": "complex",+ "skill": "color-grading","areas": ["preview","timeline","inspector",+ "color","effects",- "transitions",- "audio",- "editor"+ "video_gen",+ "scene",+ "side_panel",+ "top_bar"],- "declaredTools": 73,+ "declaredTools": 93,"routingMisses": [],- "roundModel": "gemini-3.1-flash-lite",+ "roundModel": "gemini-3.8-flash","notes": [],"instant": null,+ "qualityGate": [],"judgeNote": null,"trace": [{- "name": "set_transition",+ "name": "generate_video","round": 0,- "atMs": 1756.446041999996,- "execMs": 0.19091699999989942,+ "atMs": 14305.236291999987,+ "execMs": 0.12679199999547563,"args": {- "clipId": "c1",- "style": "audiocross",- "seconds": 0.3+ "aspect": "9:16",+ "reference_asset_id": "a-v1",+ "prompt": "Cinematic beach shoreline during a vibrant golden-hour sunset, warm amber and orange sunlight reflecting across rolling ocean waves and wet sand, gentle breeze, serene coastal atmosphere"}}],"timings": {- "gateMs": 317.8935840000049,+ "gateMs": 287.8058749999909,"gateSkipped": false,- "ttftMs": 3052.691292000003,- "modelMs": 3220.23208300001,- "toolMs": 0.19091699999989942,- "totalMs": 3551.0160000000033,+ "ttftMs": 16468.722875000007,+ "modelMs": 16476.01899900002,+ "toolMs": 0.12679199999547563,+ "totalMs": 16768.567500000005,+ "judgeMs": 246.86837499999092,"retryMs": 0,"retries": 0,"rounds": [{- "roundMs": 1434.482250000001,+ "roundMs": 14014.608583000023,"firstDeltaMs": null,"calls": [{- "name": "set_transition",- "execMs": 0.19091699999989942+ "name": "generate_video",+ "execMs": 0.12679199999547563}]},{- "roundMs": 1785.749833000009,- "firstDeltaMs": 1294.739207999999,+ "roundMs": 2461.410415999999,+ "firstDeltaMs": 2161.850582999992,"calls": []}]}- }- ]- },- {- "name": "animation-overrides-transition",- "bucket": "single-tool",- "passRate": 1,- "budgetBreaches": [],- "latency": {- "gateMs": {- "p50": 419,- "p95": 419,- "mean": 419,- "n": 1- },- "ttftMs": {- "p50": 5550,- "p95": 5550,- "mean": 5550,- "n": 1- },- "totalMs": {- "p50": 6064,- "p95": 6064,- "mean": 6064,- "n": 1- },- "modelMs": {- "p50": 5627,- "p95": 5627,- "mean": 5627,- "n": 1- },- "toolMs": {- "p50": 0,- "p95": 0,- "mean": 0,- "n": 1},- "rounds": {- "mean": 3,- "max": 3- }- },- "runs": [{"pass": true,- "intent": "simple",- "skill": null,+ "intent": "complex",+ "skill": "color-grading","areas": ["preview","timeline","inspector",+ "color","effects",- "animation",- "transitions",- "editor"+ "video_gen",+ "scene",+ "side_panel",+ "top_bar"],- "declaredTools": 71,+ "declaredTools": 93,"routingMisses": [],- "roundModel": "gemini-3.1-flash-lite",+ "roundModel": "gemini-3.8-flash","notes": [],"instant": null,+ "qualityGate": [],"judgeNote": null,"trace": [{- "name": "remove_transition",+ "name": "generate_video","round": 0,- "atMs": 1942.414957999994,- "execMs": 0.11066700000083074,- "args": {- "transitionId": "t1-p-eval"- }- },- {- "name": "set_animation",- "round": 1,- "atMs": 4171.297500000001,- "execMs": 0.022165999995195307,+ "atMs": 7417.076957999991,+ "execMs": 0.0054579999996349216,"args": {- "clipId": "c2",- "style": "pop",- "which": "in",- "seconds": 0.5+ "prompt": "A scenic beach at golden-hour sunset, warm sunlight reflecting off gentle ocean waves, golden light illuminating the sandy shore, cinematic camera motion, peaceful mood",+ "reference_asset_id": "a-v1"}}],"timings": {- "gateMs": 419.45404199999757,+ "gateMs": 288.767709000007,"gateSkipped": false,- "ttftMs": 5550.080457999997,- "modelMs": 5627.432083000007,- "toolMs": 0.13283299999602605,- "totalMs": 6064.423874999993,+ "ttftMs": 9848.250249999983,+ "modelMs": 10055.999248999986,+ "toolMs": 0.0054579999996349216,+ "totalMs": 10347.86258300001,+ "judgeMs": 255.11712500001886,"retryMs": 0,"retries": 0,"rounds": [{- "roundMs": 1510.5909580000007,- "firstDeltaMs": null,- "calls": [- {- "name": "remove_transition",- "execMs": 0.11066700000083074- }- ]- },- {- "roundMs": 2225.092749999996,+ "roundMs": 7126.448790999973,"firstDeltaMs": null,"calls": [{- "name": "set_animation",- "execMs": 0.022165999995195307+ "name": "generate_video",+ "execMs": 0.0054579999996349216}]},{- "roundMs": 1891.7483750000101,- "firstDeltaMs": 1378.0056250000052,+ "roundMs": 2929.5504580000124,+ "firstDeltaMs": 2430.29454100001,"calls": []}]}- }- ]- },- {- "name": "filler-words-cut-with-editor",- "bucket": "multi-tool",- "passRate": 0,- "budgetBreaches": [],- "latency": null,- "runs": [+ },{- "pass": false,+ "pass": true,"intent": "complex",- "skill": "watching-and-cutting",+ "skill": "color-grading","areas": ["preview","timeline","inspector",- "transitions",- "subtitles",- "audio",- "library",+ "color",+ "effects",+ "video_gen","side_panel",- "top_bar",- "editor"+ "top_bar"],- "declaredTools": 103,+ "declaredTools": 87,"routingMisses": [],"roundModel": "gemini-3.8-flash",- "notes": [- "mutating tools called: remove_gap"- ],+ "notes": [],"instant": null,+ "qualityGate": [],"judgeNote": null,"trace": [{- "name": "find_filler",- "round": 0,- "atMs": 4014.6329169999954,- "execMs": 0.07762499999080319,- "args": {- "clip_id": "c1"- }- },- {- "name": "detect_silence",+ "name": "generate_video","round": 0,- "atMs": 4015.3596249999973,- "execMs": 0.005583999998634681,- "args": {- "clip_id": "c1"- }- },- {- "name": "watch_video",- "round": 1,- "atMs": 7103.964708999993,- "execMs": 0.012000000002444722,- "args": {- "to": 6,- "clip_id": "c1",- "from": 0- }- },- {- "name": "note_source",- "round": 2,- "atMs": 9967.675499999998,- "execMs": 0.009500000000116415,- "args": {- "clip_id": "c1",- "notes": [- {- "text": "Video of dogs at the beach with spoken dialogue.",- "from": 0,- "to": 6- }- ]- }- },- {- "name": "split_at",- "round": 3,- "atMs": 16264.579750000004,- "execMs": 0.2727920000033919,- "args": {- "t": 0.45- }- },- {- "name": "split_at",- "round": 3,- "atMs": 16265.101125000001,- "execMs": 0.01495900000736583,- "args": {- "t": 4.55- }- },- {- "name": "split_at",- "round": 3,- "atMs": 16265.17525,- "execMs": 0.008041999986744486,- "args": {- "t": 5.6- }- },- {- "name": "delete_item",- "round": 4,- "atMs": 18355.536999999997,- "execMs": 0.08508300001267344,- "args": {- "id": "c1-1",- "kind": "clip"- }- },- {- "name": "delete_item",- "round": 4,- "atMs": 18355.720917,- "execMs": 0.008625000002211891,- "args": {- "kind": "clip",- "id": "c1-2-6-7"- }- },- {- "name": "delete_item",- "round": 4,- "atMs": 18355.762208999993,- "execMs": 0.013208999997004867,- "args": {- "kind": "audio",- "id": "au1-3"- }- },- {- "name": "remove_gap",- "round": 4,- "atMs": 18356.033041999995,- "execMs": 0.01179200000478886,- "args": {- "track": 0,- "at": 0- }- },- {- "name": "get_state",- "round": 5,- "atMs": 20122.913709,- "execMs": 0.2041659999958938,- "args": {}- },- {- "name": "refine_speech_cuts",- "round": 6,- "atMs": 22141.327999999994,- "execMs": 0.0922500000015134,- "args": {- "pace": "natural",- "clip_ids": [- "c1-2-5",- "c1-2-6-8"- ]- }- },- {- "name": "align_to_audio",- "round": 7,- "atMs": 23948.996084,- "execMs": 0.006540999995195307,- "args": {- "target": "captions"- }- },- {- "name": "get_state",- "round": 8,- "atMs": 26739.580499999996,- "execMs": 0.01904100000683684,- "args": {}- },- {- "name": "update_cue",- "round": 9,- "atMs": 30044.936208999992,- "execMs": 0.021875000005820766,- "args": {- "text": "So today we're",- "id": "cue1"- }- },- {- "name": "update_cue",- "round": 9,- "atMs": 30045.160709000003,- "execMs": 0.0022920000046724454,+ "atMs": 7499.506499999989,+ "execMs": 0.0037500000034924597,"args": {- "id": "cue3",- "text": "and"+ "reference_asset_id": "a-v1",+ "prompt": "Scenic golden-hour sunset over the ocean and sandy beach, warm golden light spilling across gentle breaking waves, calm and cinematic atmosphere",+ "aspect": "9:16"}}],"timings": {- "gateMs": 786.1377919999941,+ "gateMs": 328.66312499999185,"gateSkipped": false,- "ttftMs": 32209.795125000004,- "modelMs": 31695.895751999997,- "toolMs": 0.8653760000161128,- "totalMs": 32510.183917000002,+ "ttftMs": 9722.059000000008,+ "modelMs": 9797.73008400001,+ "toolMs": 0.0037500000034924597,+ "totalMs": 10128.584624999989,+ "judgeMs": 212.2879589999793,"retryMs": 0,"retries": 0,"rounds": [{- "roundMs": 3223.399875000003,- "firstDeltaMs": null,- "calls": [- {- "name": "find_filler",- "execMs": 0.07762499999080319- },- {- "name": "detect_silence",- "execMs": 0.005583999998634681- }- ]- },- {- "roundMs": 3086.6103339999972,- "firstDeltaMs": null,- "calls": [- {- "name": "watch_video",- "execMs": 0.012000000002444722- }- ]- },- {- "roundMs": 2859.277833999993,- "firstDeltaMs": null,- "calls": [- {- "name": "note_source",- "execMs": 0.009500000000116415- }- ]- },- {- "roundMs": 6292.973666999998,- "firstDeltaMs": null,- "calls": [- {- "name": "split_at",- "execMs": 0.2727920000033919- },- {- "name": "split_at",- "execMs": 0.01495900000736583- },- {- "name": "split_at",- "execMs": 0.008041999986744486- }- ]- },- {- "roundMs": 2088.3671250000043,- "firstDeltaMs": null,- "calls": [- {- "name": "delete_item",- "execMs": 0.08508300001267344- },- {- "name": "delete_item",- "execMs": 0.008625000002211891- },- {- "name": "delete_item",- "execMs": 0.013208999997004867- },- {- "name": "remove_gap",- "execMs": 0.01179200000478886- }- ]- },- {- "roundMs": 1765.3996670000051,- "firstDeltaMs": null,- "calls": [- {- "name": "get_state",- "execMs": 0.2041659999958938- }- ]- },- {- "roundMs": 2016.4116670000076,- "firstDeltaMs": null,- "calls": [- {- "name": "refine_speech_cuts",- "execMs": 0.0922500000015134- }- ]- },- {- "roundMs": 1806.1372909999918,- "firstDeltaMs": null,- "calls": [- {- "name": "align_to_audio",- "execMs": 0.006540999995195307- }- ]- },- {- "roundMs": 2789.485625000001,- "firstDeltaMs": null,- "calls": [- {- "name": "get_state",- "execMs": 0.01904100000683684- }- ]- },- {- "roundMs": 3304.1427919999987,+ "roundMs": 7169.828375000012,"firstDeltaMs": null,"calls": [{- "name": "update_cue",- "execMs": 0.021875000005820766- },- {- "name": "update_cue",- "execMs": 0.0022920000046724454+ "name": "generate_video",+ "execMs": 0.0037500000034924597}]},{- "roundMs": 2463.6898749999964,- "firstDeltaMs": 2163.776417000001,+ "roundMs": 2627.901708999998,+ "firstDeltaMs": 2221.645124999981,"calls": []}]@@ -2654,44 +2295,44 @@]},{- "name": "edit-request-still-uses-tools",+ "name": "mute-all-does-not-redo-prior-turn","bucket": "single-tool","passRate": 1,"budgetBreaches": [],"latency": {"gateMs": {- "p50": 837,- "p95": 837,- "mean": 837,- "n": 1+ "p50": 318,+ "p95": 421,+ "mean": 348,+ "n": 3},"ttftMs": {- "p50": 6814,- "p95": 6814,- "mean": 6814,- "n": 1+ "p50": 7022,+ "p95": 7121,+ "mean": 6068,+ "n": 3},"totalMs": {- "p50": 7089,- "p95": 7089,- "mean": 7089,- "n": 1+ "p50": 7093,+ "p95": 7199,+ "mean": 6155,+ "n": 3},"modelMs": {- "p50": 6248,- "p95": 6248,- "mean": 6248,- "n": 1+ "p50": 6770,+ "p95": 6886,+ "mean": 5801,+ "n": 3},"toolMs": {"p50": 0,"p95": 0,"mean": 0,- "n": 1+ "n": 3},"rounds": {- "mean": 2,- "max": 2+ "mean": 3,+ "max": 3}},"runs": [@@ -2700,344 +2341,243 @@"intent": "simple","skill": null,"areas": [- "preview","timeline","inspector",- "subtitles",- "library",- "side_panel",- "top_bar",+ "audio","editor"],- "declaredTools": 99,+ "declaredTools": 69,"routingMisses": [],"roundModel": "gemini-3.1-flash-lite","notes": [],"instant": null,+ "qualityGate": [],"judgeNote": null,"trace": [{- "name": "subtitles_generate",+ "name": "select_items","round": 0,- "atMs": 4805.348333000002,- "execMs": 0.005541999998968095,+ "atMs": 5030.151666999998,+ "execMs": 0.34395899999071844,"args": {- "track": 0+ "kind": "clip",+ "describe": "all video clips"}- }+ },+ {+ "name": "set_clip_muted",+ "round": 1,+ "atMs": 6118.733750000014,+ "execMs": 0.007042000012006611,+ "args": {+ "muted": true,+ "ids": [+ "c1",+ "c2",+ "c3"+ ]+ }+ }],"timings": {- "gateMs": 837.1546250000101,+ "gateMs": 304.8868749999965,"gateSkipped": false,- "ttftMs": 6813.814249999996,- "modelMs": 6248.236417000007,- "toolMs": 0.005541999998968095,- "totalMs": 7089.477958000003,+ "ttftMs": 7120.990917000017,+ "modelMs": 6885.719458000036,+ "toolMs": 0.35100100000272505,+ "totalMs": 7198.936500000011,+ "judgeMs": 241.19633299999987,"retryMs": 0,"retries": 0,"rounds": [{- "roundMs": 3965.3435000000027,+ "roundMs": 4721.502375000011,"firstDeltaMs": null,"calls": [{- "name": "subtitles_generate",- "execMs": 0.005541999998968095+ "name": "select_items",+ "execMs": 0.34395899999071844+ }+ ]+ },+ {+ "roundMs": 1085.1692500000063,+ "firstDeltaMs": null,+ "calls": [+ {+ "name": "set_clip_muted",+ "execMs": 0.007042000012006611}]},{- "roundMs": 2282.8929170000047,- "firstDeltaMs": 2007.4431250000052,+ "roundMs": 1079.0478330000187,+ "firstDeltaMs": 1001.2170420000039,"calls": []}]}- }- ]- },- {- "name": "cartoon-from-audio-plans-scene",- "bucket": "single-tool",- "passRate": 1,- "budgetBreaches": [],- "latency": {- "gateMs": {- "p50": 779,- "p95": 779,- "mean": 779,- "n": 1- },- "ttftMs": {- "p50": 9503,- "p95": 9503,- "mean": 9503,- "n": 1- },- "totalMs": {- "p50": 9735,- "p95": 9735,- "mean": 9735,- "n": 1- },- "modelMs": {- "p50": 8936,- "p95": 8936,- "mean": 8936,- "n": 1- },- "toolMs": {- "p50": 0,- "p95": 0,- "mean": 0,- "n": 1},- "rounds": {- "mean": 4,- "max": 4- }- },- "runs": [{"pass": true,- "intent": "complex",- "skill": "scene-productions",+ "intent": "simple",+ "skill": null,"areas": ["preview","timeline","inspector",- "color",- "removal",- "elements",- "effects",- "animation",- "transitions",- "subtitles","audio",- "image_gen",- "video_gen",- "scene",- "stock",- "library",- "side_panel",- "top_bar","editor"],- "declaredTools": 130,+ "declaredTools": 74,"routingMisses": [],- "roundModel": "gemini-3.8-flash",+ "roundModel": "gemini-3.1-flash-lite","notes": [],"instant": null,+ "qualityGate": [],"judgeNote": null,"trace": [{- "name": "listen_audio",+ "name": "select_items","round": 0,- "atMs": 2930.491166000007,- "execMs": 0.07395900000119582,+ "atMs": 4551.601832999993,+ "execMs": 0.03699999998207204,"args": {- "asset_id": "a-au1"+ "describe": "all clips on the video track",+ "kind": "clip"}},{- "name": "detect_silence",+ "name": "set_clip_muted","round": 1,- "atMs": 5205.547458000001,- "execMs": 0.03362500001094304,- "args": {- "asset_id": "a-au1"- }- },- {- "name": "generate_scene",- "round": 2,- "atMs": 7829.868540999989,- "execMs": 0.09141600001021288,+ "atMs": 6002.901832999982,+ "execMs": 0.007958000001963228,"args": {- "brief": "Smooth 2D cartoon animation illustrating the narration topic in fluid hand-drawn style. Clean line art, vibrant harmonious colors, expressive animated characters, and continuous fluid 2D motion matching the audio pacing.",- "style": "smooth 2D cartoon, fluid hand-drawn animation, clean outlines, vibrant flat colors",- "from_audio_asset_id": "a-au1"+ "ids": [+ "c1",+ "c2",+ "c3"+ ],+ "muted": true}}],"timings": {- "gateMs": 779.1240419999958,+ "gateMs": 317.6171660000109,"gateSkipped": false,- "ttftMs": 9502.852040999991,- "modelMs": 8935.731042000029,- "toolMs": 0.19900000002235174,- "totalMs": 9734.84529099999,+ "ttftMs": 7021.600458000001,+ "modelMs": 6769.820791999984,+ "toolMs": 0.04495799998403527,+ "totalMs": 7092.728415999998,+ "judgeMs": 251.0344589999877,"retryMs": 0,"retries": 0,"rounds": [{- "roundMs": 2148.349459000019,- "firstDeltaMs": null,- "calls": [- {- "name": "listen_audio",- "execMs": 0.07395900000119582- }- ]- },- {- "roundMs": 2271.8245830000087,+ "roundMs": 4232.605374999985,"firstDeltaMs": null,"calls": [{- "name": "detect_silence",- "execMs": 0.03362500001094304+ "name": "select_items",+ "execMs": 0.03699999998207204}]},{- "roundMs": 2619.0696250000037,+ "roundMs": 1449.5802919999987,"firstDeltaMs": null,"calls": [{- "name": "generate_scene",- "execMs": 0.09141600001021288+ "name": "set_clip_muted",+ "execMs": 0.007958000001963228}]},{- "roundMs": 1896.487374999997,- "firstDeltaMs": 1665.1122500000056,+ "roundMs": 1087.6351250000007,+ "firstDeltaMs": 1017.4927079999761,"calls": []}]}- }- ]- },- {- "name": "cartoon-korean-audio-passes-language",- "bucket": "single-tool",- "passRate": 1,- "budgetBreaches": [],- "latency": {- "gateMs": {- "p50": 721,- "p95": 721,- "mean": 721,- "n": 1- },- "ttftMs": {- "p50": 8597,- "p95": 8597,- "mean": 8597,- "n": 1- },- "totalMs": {- "p50": 8859,- "p95": 8859,- "mean": 8859,- "n": 1- },- "modelMs": {- "p50": 8130,- "p95": 8130,- "mean": 8130,- "n": 1- },- "toolMs": {- "p50": 1,- "p95": 1,- "mean": 1,- "n": 1},- "rounds": {- "mean": 3,- "max": 3- }- },- "runs": [{"pass": true,- "intent": "complex",- "skill": "scene-productions",+ "intent": "simple",+ "skill": null,"areas": [- "preview","timeline","inspector",- "removal",- "elements",- "effects",- "animation",- "transitions",- "subtitles","audio",- "image_gen",- "video_gen",- "scene",- "stock",- "library",- "side_panel",- "top_bar","editor"],- "declaredTools": 123,+ "declaredTools": 69,"routingMisses": [],- "roundModel": "gemini-3.8-flash",+ "roundModel": "gemini-3.1-flash-lite","notes": [],"instant": null,+ "qualityGate": [],"judgeNote": null,"trace": [{- "name": "listen_audio",+ "name": "select_items","round": 0,- "atMs": 3310.7753749999974,- "execMs": 0.04008299999986775,+ "atMs": 1772.855292000022,+ "execMs": 0.021708000014768913,"args": {- "asset_id": "a-au1"+ "kind": "clip",+ "describe": "all clips on the video track"}},{- "name": "generate_scene",+ "name": "set_clip_muted","round": 1,- "atMs": 6096.124207999994,- "execMs": 1.4455830000224523,+ "atMs": 2942.752334000019,+ "execMs": 0.004124999977648258,"args": {- "style": "smooth 2D cartoon animation, clean line art, vibrant flat colors, fluid cel animation",- "brief": "A smooth 2D cartoon animation visualizing the narration topic in order with expressive animated characters and gentle fluid motion.",- "audio_language": "ko-KR",- "from_audio_asset_id": "a-au1"+ "ids": [+ "c1",+ "c2",+ "c3"+ ],+ "muted": true}}],"timings": {- "gateMs": 720.5638329999929,+ "gateMs": 420.586707999988,"gateSkipped": false,- "ttftMs": 8597.330500000011,- "modelMs": 8130.383165999985,- "toolMs": 1.48566600002232,- "totalMs": 8858.839582999994,+ "ttftMs": 4062.4324590000033,+ "modelMs": 3748.286207999976,+ "toolMs": 0.02583299999241717,+ "totalMs": 4173.034209000005,+ "judgeMs": 221.5738340000098,"retryMs": 0,"retries": 0,"rounds": [{- "roundMs": 2587.2615410000144,+ "roundMs": 1350.1406669999997,"firstDeltaMs": null,"calls": [{- "name": "listen_audio",- "execMs": 0.04008299999986775+ "name": "select_items",+ "execMs": 0.021708000014768913}]},{- "roundMs": 2783.3916249999893,+ "roundMs": 1168.9457499999844,"firstDeltaMs": null,"calls": [{- "name": "generate_scene",- "execMs": 1.4455830000224523+ "name": "set_clip_muted",+ "execMs": 0.004124999977648258}]},{- "roundMs": 2759.7299999999814,- "firstDeltaMs": 2498.405624999985,+ "roundMs": 1229.1997909999918,+ "firstDeltaMs": 1118.9669160000049,"calls": []}]@@ -3046,63 +2586,59 @@]},{- "name": "cartoon-style-reference-anchors-look",+ "name": "imported-photo-edit-references-photo","bucket": "single-tool","passRate": 1,"budgetBreaches": [],"latency": {"gateMs": {- "p50": 785,- "p95": 785,- "mean": 785,- "n": 1+ "p50": 307,+ "p95": 370,+ "mean": 316,+ "n": 3},"ttftMs": {- "p50": 8268,- "p95": 8268,- "mean": 8268,- "n": 1+ "p50": 3139,+ "p95": 6485,+ "mean": 4153,+ "n": 3},"totalMs": {- "p50": 8584,- "p95": 8584,- "mean": 8584,- "n": 1+ "p50": 3278,+ "p95": 6631,+ "mean": 4312,+ "n": 3},"modelMs": {- "p50": 7793,- "p95": 7793,- "mean": 7793,- "n": 1+ "p50": 2969,+ "p95": 6355,+ "mean": 3993,+ "n": 3},"toolMs": {- "p50": 1,- "p95": 1,- "mean": 1,- "n": 1+ "p50": 0,+ "p95": 0,+ "mean": 0,+ "n": 3},"rounds": {- "mean": 3,- "max": 3+ "mean": 2,+ "max": 2}},"runs": [{"pass": true,- "intent": "complex",- "skill": "scene-productions",+ "intent": "simple",+ "skill": null,"areas": ["preview","timeline","inspector",- "color","removal","elements","effects","animation",- "transitions",- "subtitles",- "audio","image_gen","video_gen","scene",@@ -3112,124 +2648,60 @@"top_bar","editor"],- "declaredTools": 130,+ "declaredTools": 108,"routingMisses": [],- "roundModel": "gemini-3.8-flash",+ "roundModel": "gemini-3.1-flash-lite","notes": [],"instant": null,+ "qualityGate": [],"judgeNote": null,"trace": [{- "name": "listen_audio",+ "name": "generate_image","round": 0,- "atMs": 3370.2075420000183,- "execMs": 0.032207999989623204,- "args": {- "asset_id": "a-au1"- }- },- {- "name": "generate_scene",- "round": 1,- "atMs": 6432.973041999998,- "execMs": 1.4452089999977034,+ "atMs": 5290.043917000003,+ "execMs": 0.05966599998646416,"args": {- "style": "flat hand-drawn 2D cartoon animation, vibrant cheerful colors, clean lines, playful storybook illustration style",- "target_seconds": 24,- "from_audio_asset_id": "a-au1",+ "prompt": "a girl in the snow wearing a santa hat, same style as the provided image of snow scenery","reference_asset_ids": [- "a-i1"- ],- "brief": "A playful animated cartoon about a dog's morning adventure at the dog park, meeting puppy friends, chasing a red ball, and rolling in the grass. Flat hand-drawn 2D animation style, vibrant colorful park setting, clean outlines, cute expressive dog characters."+ "a-tw1"+ ]}}],"timings": {- "gateMs": 784.916916999995,- "gateSkipped": true,- "ttftMs": 8267.621084000013,- "modelMs": 7793.160666999989,- "toolMs": 1.4774169999873266,- "totalMs": 8584.366084000008,+ "gateMs": 271.9621249999909,+ "gateSkipped": false,+ "ttftMs": 6484.776916999981,+ "modelMs": 6354.983042000007,+ "toolMs": 0.05966599998646416,+ "totalMs": 6630.66741699999,+ "judgeMs": 232.30124999998952,"retryMs": 0,"retries": 0,"rounds": [{- "roundMs": 2583.361124999996,+ "roundMs": 5015.172709000006,"firstDeltaMs": null,"calls": [{- "name": "listen_audio",- "execMs": 0.032207999989623204- }- ]- },- {- "roundMs": 3061.5369169999904,- "firstDeltaMs": null,- "calls": [- {- "name": "generate_scene",- "execMs": 1.4452089999977034+ "name": "generate_image",+ "execMs": 0.05966599998646416}]},{- "roundMs": 2148.262625000003,- "firstDeltaMs": 1832.1068749999977,+ "roundMs": 1339.8103330000013,+ "firstDeltaMs": 1194.0998330000148,"calls": []}]}- }- ]- },- {- "name": "cartoon-question-stays-in-chat",- "bucket": "chat",- "passRate": 1,- "budgetBreaches": [],- "latency": {- "gateMs": {- "p50": 854,- "p95": 854,- "mean": 854,- "n": 1- },- "ttftMs": {- "p50": 3335,- "p95": 3335,- "mean": 3335,- "n": 1- },- "totalMs": {- "p50": 4001,- "p95": 4001,- "mean": 4001,- "n": 1},- "modelMs": {- "p50": 3143,- "p95": 3143,- "mean": 3143,- "n": 1- },- "toolMs": {- "p50": 0,- "p95": 0,- "mean": 0,- "n": 1- },- "rounds": {- "mean": 1,- "max": 1- }- },- "runs": [{"pass": true,- "intent": "complex",- "skill": "scene-productions",+ "intent": "simple",+ "skill": null,"areas": ["preview","timeline",@@ -3238,326 +2710,65 @@"elements","effects","animation",- "transitions",- "subtitles",- "audio","image_gen","video_gen","scene","stock","library","side_panel",- "top_bar"+ "top_bar",+ "editor"],- "declaredTools": 119,+ "declaredTools": 108,"routingMisses": [],- "roundModel": "gemini-3.8-flash",- "notes": [],- "instant": null,- "judgeNote": null,- "trace": [],- "timings": {- "gateMs": 854.4787910000014,- "gateSkipped": false,- "ttftMs": 3335.1546660000167,- "modelMs": 3143.064875000011,- "toolMs": 0,- "totalMs": 4000.527666000009,- "retryMs": 0,- "retries": 0,- "rounds": [- {- "roundMs": 3143.064875000011,- "firstDeltaMs": 2479.2405000000144,- "calls": []- }- ]- }- }- ]- },- {- "name": "clip-mentions-redo-their-shots",- "bucket": "multi-tool",- "passRate": 1,- "budgetBreaches": [],- "latency": {- "gateMs": {- "p50": 275,- "p95": 275,- "mean": 275,- "n": 1- },- "ttftMs": {- "p50": 21510,- "p95": 21510,- "mean": 21510,- "n": 1- },- "totalMs": {- "p50": 21856,- "p95": 21856,- "mean": 21856,- "n": 1- },- "modelMs": {- "p50": 21561,- "p95": 21561,- "mean": 21561,- "n": 1- },- "toolMs": {- "p50": 1,- "p95": 1,- "mean": 1,- "n": 1- },- "rounds": {- "mean": 8,- "max": 8- }- },- "runs": [- {- "pass": true,- "intent": "complex",- "skill": "audio-and-subtitles",- "areas": [- "preview",- "timeline",- "inspector",- "transitions",- "subtitles",- "audio",- "video_gen",- "scene",- "stock",- "library",- "side_panel",- "top_bar",- "editor"- ],- "declaredTools": 113,- "routingMisses": [],- "roundModel": "gemini-3.8-flash",+ "roundModel": "gemini-3.1-flash-lite","notes": [],"instant": null,+ "qualityGate": [],"judgeNote": null,"trace": [{- "name": "listen_audio",+ "name": "generate_image","round": 0,- "atMs": 2483.165249999991,- "execMs": 0.7464160000090487,- "args": {- "to": 9,- "from": 0,- "asset_id": "a-au1"- }- },- {- "name": "watch_video",- "round": 1,- "atMs": 8062.491167,- "execMs": 0.0167080000101123,- "args": {- "clip_id": "sc-1"- }- },- {- "name": "note_source",- "round": 2,- "atMs": 11869.86391700001,- "execMs": 0.011583999992581084,- "args": {- "notes": [- {- "from": 0,- "text": "Shot 1 showing initial scene footage.",- "to": 3- }- ],- "clip_id": "sc-1"- }- },- {- "name": "watch_video",- "round": 3,- "atMs": 13849.198208999995,- "execMs": 0.024624999990919605,- "args": {- "clip_id": "sc-2"- }- },- {- "name": "note_source",- "round": 4,- "atMs": 15763.635584000003,- "execMs": 0.016791999980341643,+ "atMs": 1864.8342499999853,+ "execMs": 0.005250000016530976,"args": {- "clip_id": "sc-2",- "notes": [- {- "from": 0,- "text": "Shot 2 showing similar footage to shot 1.",- "to": 3- }+ "prompt": "A woman wearing a santa hat, matching the snowy setting of the original photo.",+ "reference_asset_ids": [+ "a-tw1"]}- },- {- "name": "regenerate_shot",- "round": 5,- "atMs": 18002.527459000004,- "execMs": 0.013042000005953014,- "args": {- "note": "Make visually distinct and closely aligned with the narration audio",- "n": 1- }- },- {- "name": "regenerate_shot",- "round": 6,- "atMs": 19937.37375,- "execMs": 0.009707999997772276,- "args": {- "note": "Make visually distinct from shot 1 and match the narration audio for this section",- "n": 2- }}],"timings": {- "gateMs": 275.30583299999125,- "gateSkipped": true,- "ttftMs": 21509.938208999985,- "modelMs": 21560.97749900003,- "toolMs": 0.8388749999867287,- "totalMs": 21856.35045900001,+ "gateMs": 307.0209170000162,+ "gateSkipped": false,+ "ttftMs": 3138.883582999988,+ "modelMs": 2969.3477080000157,+ "toolMs": 0.005250000016530976,+ "totalMs": 3278.2796249999956,+ "judgeMs": 242.69666600000346,"retryMs": 0,"retries": 0,"rounds": [{- "roundMs": 2200.006708000001,- "firstDeltaMs": null,- "calls": [- {- "name": "listen_audio",- "execMs": 0.7464160000090487- }- ]- },- {- "roundMs": 5577.087458000024,- "firstDeltaMs": null,- "calls": [- {- "name": "watch_video",- "execMs": 0.0167080000101123- }- ]- },- {- "roundMs": 3806.0307909999974,- "firstDeltaMs": null,- "calls": [- {- "name": "note_source",- "execMs": 0.011583999992581084- }- ]- },- {- "roundMs": 1978.2822079999896,- "firstDeltaMs": null,- "calls": [- {- "name": "watch_video",- "execMs": 0.024624999990919605- }- ]- },- {- "roundMs": 1912.6293339999975,- "firstDeltaMs": null,- "calls": [- {- "name": "note_source",- "execMs": 0.016791999980341643- }- ]- },- {- "roundMs": 2234.8886250000214,- "firstDeltaMs": null,- "calls": [- {- "name": "regenerate_shot",- "execMs": 0.013042000005953014- }- ]- },- {- "roundMs": 1934.0359579999931,+ "roundMs": 1556.7005000000063,"firstDeltaMs": null,"calls": [{- "name": "regenerate_shot",- "execMs": 0.009707999997772276+ "name": "generate_image",+ "execMs": 0.005250000016530976}]},{- "roundMs": 1918.0164170000062,- "firstDeltaMs": 1571.8924169999955,+ "roundMs": 1412.6472080000094,+ "firstDeltaMs": 1273.4667080000218,"calls": []}]}- }- ]- },- {- "name": "parked-debris-cleanup-after-retime",- "bucket": "multi-tool",- "passRate": 1,- "budgetBreaches": [],- "latency": {- "gateMs": {- "p50": 774,- "p95": 774,- "mean": 774,- "n": 1- },- "ttftMs": {- "p50": 7433,- "p95": 7433,- "mean": 7433,- "n": 1- },- "totalMs": {- "p50": 7611,- "p95": 7611,- "mean": 7611,- "n": 1- },- "modelMs": {- "p50": 6826,- "p95": 6826,- "mean": 6826,- "n": 1- },- "toolMs": {- "p50": 1,- "p95": 1,- "mean": 1,- "n": 1},- "rounds": {- "mean": 3,- "max": 3- }- },- "runs": [{"pass": true,"intent": "simple",@@ -3566,70 +2777,64 @@"preview","timeline","inspector",+ "removal",+ "elements","effects",+ "animation",+ "image_gen",+ "video_gen",+ "scene",+ "stock",+ "library",+ "side_panel","top_bar","editor"],- "declaredTools": 73,+ "declaredTools": 108,"routingMisses": [],"roundModel": "gemini-3.1-flash-lite","notes": [],"instant": null,+ "qualityGate": [],"judgeNote": null,"trace": [{- "name": "set_speed",+ "name": "generate_image","round": 0,- "atMs": 4716.689417000016,- "execMs": 0.8657909999892581,- "args": {- "clipId": "c2",- "speed": 2- }- },- {- "name": "remove_transition",- "round": 1,- "atMs": 6250.872499999998,- "execMs": 0.007958000001963228,+ "atMs": 1544.2185419999878,+ "execMs": 0.0021659999911207706,"args": {- "transitionId": "tr-2"+ "prompt": "A high-quality, atmospheric portrait of a woman in the snow, wearing a Santa hat. The style matches the provided reference photo.",+ "reference_asset_ids": [+ "a-tw1"+ ]}}],"timings": {- "gateMs": 774.1965830000117,+ "gateMs": 369.5519170000043,"gateSkipped": false,- "ttftMs": 7432.601167000015,- "modelMs": 6825.519373999967,- "toolMs": 0.8737489999912214,- "totalMs": 7610.611459000007,+ "ttftMs": 2836.6649169999873,+ "modelMs": 2655.652875000029,+ "toolMs": 0.0021659999911207706,+ "totalMs": 3027.089458000002,+ "judgeMs": 265.0380410000216,"retryMs": 0,"retries": 0,"rounds": [{- "roundMs": 3937.119832999975,- "firstDeltaMs": null,- "calls": [- {- "name": "set_speed",- "execMs": 0.8657909999892581- }- ]- },- {- "roundMs": 1530.3040829999954,+ "roundMs": 1173.3577920000243,"firstDeltaMs": null,"calls": [{- "name": "remove_transition",- "execMs": 0.007958000001963228+ "name": "generate_image",+ "execMs": 0.0021659999911207706}]},{- "roundMs": 1358.0954579999961,- "firstDeltaMs": 1180.5906250000116,+ "roundMs": 1482.2950830000045,+ "firstDeltaMs": 1291.9899159999914,"calls": []}]@@ -3638,40 +2843,40 @@]},{- "name": "speed-ramp-from-description",+ "name": "audio-ask-single-generate","bucket": "single-tool","passRate": 1,"budgetBreaches": [],"latency": {"gateMs": {- "p50": 815,- "p95": 815,- "mean": 815,- "n": 1+ "p50": 259,+ "p95": 264,+ "mean": 256,+ "n": 3},"ttftMs": {- "p50": 3356,- "p95": 3356,- "mean": 3356,- "n": 1+ "p50": 2857,+ "p95": 6136,+ "mean": 3935,+ "n": 3},"totalMs": {- "p50": 3615,- "p95": 3615,- "mean": 3615,- "n": 1+ "p50": 3043,+ "p95": 6368,+ "mean": 4141,+ "n": 3},"modelMs": {- "p50": 2792,- "p95": 2792,- "mean": 2792,- "n": 1+ "p50": 2781,+ "p95": 6120,+ "mean": 3882,+ "n": 3},"toolMs": {"p50": 0,"p95": 0,"mean": 0,- "n": 1+ "n": 3},"rounds": {"mean": 2,@@ -3687,50 +2892,185 @@"preview","timeline","inspector",- "effects",- "transitions"+ "subtitles",+ "audio",+ "video_gen",+ "scene",+ "stock",+ "library",+ "side_panel",+ "top_bar"],- "declaredTools": 65,+ "declaredTools": 111,"routingMisses": [],"roundModel": "gemini-3.1-flash-lite","notes": [],"instant": null,+ "qualityGate": [],"judgeNote": null,"trace": [{- "name": "set_speed_curve",+ "name": "voiceover_generate","round": 0,- "atMs": 2137.8395830000227,- "execMs": 0.16199999998207204,+ "atMs": 4702.946250000008,+ "execMs": 0.00483300001360476,"args": {- "preset": "rampOut",- "clipId": "c2"+ "script": "Welcome to the dog show."}}],"timings": {- "gateMs": 815.4818749999977,+ "gateMs": 245.72429199999897,"gateSkipped": false,- "ttftMs": 3355.7278750000114,- "modelMs": 2792.3324999999895,- "toolMs": 0.16199999998207204,- "totalMs": 3614.7368330000027,+ "ttftMs": 6135.654791000008,+ "modelMs": 6119.53925099998,+ "toolMs": 0.00483300001360476,+ "totalMs": 6368.155958000018,+ "judgeMs": 244.4287080000213,"retryMs": 0,"retries": 0,"rounds": [{- "roundMs": 1316.7665829999896,+ "roundMs": 4455.206166999997,"firstDeltaMs": null,"calls": [{- "name": "set_speed_curve",- "execMs": 0.16199999998207204+ "name": "voiceover_generate",+ "execMs": 0.00483300001360476+ }+ ]+ },+ {+ "roundMs": 1664.3330839999835,+ "firstDeltaMs": 1431.9489999999932,+ "calls": []+ }+ ]+ }+ },+ {+ "pass": true,+ "intent": "simple",+ "skill": null,+ "areas": [+ "preview",+ "timeline",+ "inspector",+ "subtitles",+ "audio",+ "video_gen",+ "scene",+ "stock",+ "library",+ "side_panel",+ "top_bar"+ ],+ "declaredTools": 111,+ "routingMisses": [],+ "roundModel": "gemini-3.1-flash-lite",+ "notes": [],+ "instant": null,+ "qualityGate": [],+ "judgeNote": null,+ "trace": [+ {+ "name": "voiceover_generate",+ "round": 0,+ "atMs": 1594.999541999976,+ "execMs": 0.003749999974388629,+ "args": {+ "script": "Welcome to the dog show."+ }+ }+ ],+ "timings": {+ "gateMs": 259.14762499998324,+ "gateSkipped": false,+ "ttftMs": 2856.8558340000163,+ "modelMs": 2781.4767500000016,+ "toolMs": 0.003749999974388629,+ "totalMs": 3043.4790419999918,+ "judgeMs": 302.17270799999824,+ "retryMs": 0,+ "retries": 0,+ "rounds": [+ {+ "roundMs": 1334.262000000017,+ "firstDeltaMs": null,+ "calls": [+ {+ "name": "voiceover_generate",+ "execMs": 0.003749999974388629+ }+ ]+ },+ {+ "roundMs": 1447.2147499999846,+ "firstDeltaMs": 1260.7392499999842,+ "calls": []+ }+ ]+ }+ },+ {+ "pass": true,+ "intent": "simple",+ "skill": null,+ "areas": [+ "preview",+ "timeline",+ "inspector",+ "subtitles",+ "audio",+ "video_gen",+ "scene",+ "stock",+ "library",+ "side_panel",+ "top_bar"+ ],+ "declaredTools": 111,+ "routingMisses": [],+ "roundModel": "gemini-3.1-flash-lite",+ "notes": [],+ "instant": null,+ "qualityGate": [],+ "judgeNote": null,+ "trace": [+ {+ "name": "voiceover_generate",+ "round": 0,+ "atMs": 1526.9769169999636,+ "execMs": 0.00229199999012053,+ "args": {+ "script": "welcome to the dog show"+ }+ }+ ],+ "timings": {+ "gateMs": 263.6788340000203,+ "gateSkipped": false,+ "ttftMs": 2813.426291999989,+ "modelMs": 2745.775250000006,+ "toolMs": 0.00229199999012053,+ "totalMs": 3011.1399999999558,+ "judgeMs": 296.57595800003037,+ "retryMs": 0,+ "retries": 0,+ "rounds": [+ {+ "roundMs": 1262.1901250000228,+ "firstDeltaMs": null,+ "calls": [+ {+ "name": "voiceover_generate",+ "execMs": 0.00229199999012053}]},{- "roundMs": 1475.565917,- "firstDeltaMs": 1216.8702499999781,+ "roundMs": 1483.5851249999832,+ "firstDeltaMs": 1285.9516669999575,"calls": []}]@@ -3739,805 +3079,9964 @@]},{- "name": "replicate-a-video-blocks-out-the-cuts",- "bucket": "multi-tool",- "passRate": 0,+ "name": "music-ask-single-generate",+ "bucket": "single-tool",+ "passRate": 0.6666666666666666,"budgetBreaches": [],- "latency": null,+ "latency": {+ "gateMs": {+ "p50": 293,+ "p95": 324,+ "mean": 308,+ "n": 2+ },+ "ttftMs": {+ "p50": 8841,+ "p95": 8897,+ "mean": 8869,+ "n": 2+ },+ "totalMs": {+ "p50": 9229,+ "p95": 9270,+ "mean": 9250,+ "n": 2+ },+ "modelMs": {+ "p50": 8902,+ "p95": 8975,+ "mean": 8938,+ "n": 2+ },+ "toolMs": {+ "p50": 0,+ "p95": 0,+ "mean": 0,+ "n": 2+ },+ "rounds": {+ "mean": 2,+ "max": 2+ }+ },"runs": [{- "pass": false,+ "pass": true,"intent": "complex",- "skill": "replicating-a-video",+ "skill": "audio-and-subtitles","areas": ["preview","timeline","inspector",- "elements",- "effects",- "animation",- "transitions","subtitles","audio",- "video_gen",- "scene",+ "stock","library",- "side_panel",- "top_bar",- "editor"+ "side_panel"],- "declaredTools": 117,+ "declaredTools": 99,"routingMisses": [],"roundModel": "gemini-3.8-flash",+ "notes": [],+ "instant": null,+ "qualityGate": [],+ "judgeNote": null,+ "trace": [+ {+ "name": "generate_music",+ "round": 0,+ "atMs": 6858.3898749999935,+ "execMs": 0.04375000001164153,+ "args": {+ "add_to_timeline": true,+ "prompt": "Chill, relaxed lo-fi background beat with soft electric piano and mellow groove",+ "volume": 0.4,+ "instrumental": true,+ "length": "clip",+ "start": 0+ }+ }+ ],+ "timings": {+ "gateMs": 323.64420899999095,+ "gateSkipped": false,+ "ttftMs": 8841.34275000001,+ "modelMs": 8901.61633400002,+ "toolMs": 0.04375000001164153,+ "totalMs": 9229.258083000022,+ "judgeMs": 216.17620799998986,+ "retryMs": 0,+ "retries": 0,+ "rounds": [+ {+ "roundMs": 6531.584792000009,+ "firstDeltaMs": null,+ "calls": [+ {+ "name": "generate_music",+ "execMs": 0.04375000001164153+ }+ ]+ },+ {+ "roundMs": 2370.0315420000115,+ "firstDeltaMs": 1982.2433749999618,+ "calls": []+ }+ ]+ }+ },+ {+ "pass": false,+ "intent": "simple",+ "skill": null,+ "areas": [+ "preview",+ "timeline",+ "inspector",+ "audio",+ "stock",+ "library",+ "side_panel"+ ],+ "declaredTools": 86,+ "routingMisses": [],+ "roundModel": "gemini-3.1-flash-lite","notes": [- "put the reference itself on the timeline"+ "slow: 9 tool calls (cap 3)",+ "mutating tools called: update_audio, update_audio, update_audio, update_audio, update_audio, update_audio, update_audio, update_audio"],"instant": null,+ "qualityGate": [],"judgeNote": null,"trace": [{- "name": "watch_video",+ "name": "generate_music","round": 0,- "atMs": 3346.820667000022,- "execMs": 0.1794590000063181,+ "atMs": 4874.502084000036,+ "execMs": 0.0024170000106096268,"args": {- "asset_id": "a-ref1",- "from": 0,- "interval_seconds": 2,- "to": 71.6+ "prompt": "chill lo-fi hip hop background music with a relaxed, mellow vibe",+ "start": 0,+ "instrumental": true,+ "volume": 0.3,+ "add_to_timeline": true}},{- "name": "note_source",+ "name": "update_audio","round": 1,- "atMs": 5870.332417000027,- "execMs": 0.0052090000244788826,+ "atMs": 6353.414667000005,+ "execMs": 0.003416999999899417,"args": {- "notes": [- {- "to": 24,- "text": "Yellow Archivo-Black hook titles over talking head, cuts roughly every 2 seconds.",- "from": 0- }- ],- "asset_id": "a-ref1"+ "id": "au1",+ "lane": 0,+ "duck": 0.4}},{- "name": "watch_video",+ "name": "update_audio",+ "round": 1,+ "atMs": 6353.506375000055,+ "execMs": 0.0035409999545663595,+ "args": {+ "volume": 0.35,+ "id": "a-music1",+ "start": 0,+ "lane": 1+ }+ },+ {+ "name": "update_audio","round": 2,- "atMs": 7934.507125000004,- "execMs": 0.027750000008381903,+ "atMs": 7833.417000000016,+ "execMs": 0.0018339999951422215,"args": {- "interval_seconds": 2,- "from": 24,- "to": 71.6,- "asset_id": "a-ref1"+ "duck": 0.4,+ "lane": 0,+ "id": "au1"}},{- "name": "note_source",+ "name": "update_audio",+ "round": 2,+ "atMs": 7833.489709000045,+ "execMs": 0.00045900000259280205,+ "args": {+ "volume": 0.35,+ "start": 0,+ "lane": 1,+ "id": "a-music1"+ }+ },+ {+ "name": "update_audio","round": 3,- "atMs": 10021.203709000023,- "execMs": 0.002582999994046986,+ "atMs": 8956.677292000037,+ "execMs": 0.0024170000106096268,"args": {- "asset_id": "a-ref1",- "notes": [- {- "from": 24,- "text": "Talking head continues with rhythmic ~2s cuts and yellow text callouts.",- "to": 48- }- ]+ "lane": 0,+ "id": "au1",+ "duck": 0.4}},{- "name": "watch_video",- "round": 4,- "atMs": 12185.132792000019,- "execMs": 0.04379200001130812,+ "name": "update_audio",+ "round": 3,+ "atMs": 8956.781000000017,+ "execMs": 0.000708000035956502,"args": {- "from": 48,- "to": 71.6,- "interval_seconds": 2,- "asset_id": "a-ref1"+ "start": 0,+ "id": "a-music1",+ "lane": 1,+ "volume": 0.35}},{- "name": "note_source",- "round": 5,- "atMs": 15263.372417000006,- "execMs": 0.01770799999940209,+ "name": "update_audio",+ "round": 4,+ "atMs": 10560.706417000038,+ "execMs": 0.004249999998137355,"args": {- "asset_id": "a-ref1",- "notes": [- {- "to": 71.6,- "text": "Talking head conclusion with rhythmic ~2s cuts to 71.6s.",- "from": 48- }- ]+ "id": "au1",+ "duck": 0.4,+ "lane": 0}},{- "name": "add_placeholders",- "round": 6,- "atMs": 20084.199250000005,- "execMs": 0.1306660000118427,+ "name": "update_audio",+ "round": 4,+ "atMs": 10560.854375000054,+ "execMs": 0.000750000006519258,"args": {- "source_asset_id": "a-ref1",- "shots": [- {- "from": 0,- "seconds": 2,- "label": "Talking head - opening hook"- },- {- "label": "Talking head",- "seconds": 2,- "from": 2- },- {- "from": 4,- "seconds": 2,- "label": "Talking head"- },- {- "label": "Talking head",- "seconds": 2,- "from": 6- },- {- "seconds": 2,- "from": 8,- "label": "Talking head"- },- {- "label": "Talking head",- "from": 10,- "seconds": 2- },- {- "from": 12,- "seconds": 2,- "label": "Talking head"- },- {- "seconds": 2,- "label": "Talking head",- "from": 14- },- {- "seconds": 2,- "from": 16,- "label": "Talking head"- },- {- "seconds": 2,- "label": "Talking head",- "from": 18- },- {- "seconds": 2,- "from": 20,- "label": "Talking head"- },- {- "label": "Talking head",- "from": 22,- "seconds": 2- },- {- "from": 24,- "seconds": 2,- "label": "Talking head"- },- {- "from": 26,- "label": "Talking head",- "seconds": 2- },- {- "from": 28,- "seconds": 2,- "label": "Talking head"- },- {- "seconds": 2,- "label": "Talking head",- "from": 30- },- {- "label": "Talking head",- "from": 32,- "seconds": 2- },- {- "from": 34,- "seconds": 2,- "label": "Talking head"- },- {- "label": "Talking head",- "seconds": 2,- "from": 36- },- {- "label": "Talking head",- "seconds": 2,- "from": 38- },- {- "seconds": 2,- "from": 40,- "label": "Talking head"- },- {- "from": 42,- "label": "Talking head",- "seconds": 2- },- {- "label": "Talking head",- "from": 44,- "seconds": 2- },- {- "from": 46,- "label": "Talking head",- "seconds": 2- },- {- "label": "Talking head",- "from": 48,- "seconds": 2- },+ "volume": 0.35,+ "id": "a-music1",+ "lane": 1,+ "start": 0+ }+ }+ ],+ "timings": {+ "gateMs": 312.2920419999864,+ "gateSkipped": false,+ "ttftMs": 11747.616584000003,+ "modelMs": 11899.193247999996,+ "toolMs": 0.01979300001403317,+ "totalMs": 12217.388959000004,+ "judgeMs": 225.95666599995457,+ "retryMs": 0,+ "retries": 0,+ "rounds": [+ {+ "roundMs": 4561.031041999988,+ "firstDeltaMs": null,+ "calls": [{- "seconds": 2,- "from": 50,- "label": "Talking head"- },+ "name": "generate_music",+ "execMs": 0.0024170000106096268+ }+ ]+ },+ {+ "roundMs": 1477.7010829999927,+ "firstDeltaMs": null,+ "calls": [{- "seconds": 2,- "from": 52,- "label": "Talking head"+ "name": "update_audio",+ "execMs": 0.003416999999899417},{- "from": 54,- "seconds": 2,- "label": "Talking head"- },+ "name": "update_audio",+ "execMs": 0.0035409999545663595+ }+ ]+ },+ {+ "roundMs": 1479.376958000008,+ "firstDeltaMs": null,+ "calls": [{- "from": 56,- "label": "Talking head",- "seconds": 2+ "name": "update_audio",+ "execMs": 0.0018339999951422215},{- "seconds": 2,- "from": 58,- "label": "Talking head"- },+ "name": "update_audio",+ "execMs": 0.00045900000259280205+ }+ ]+ },+ {+ "roundMs": 1122.644541000016,+ "firstDeltaMs": null,+ "calls": [{- "from": 60,- "label": "Talking head",- "seconds": 2+ "name": "update_audio",+ "execMs": 0.0024170000106096268},{- "seconds": 2,- "label": "Talking head",- "from": 62- },+ "name": "update_audio",+ "execMs": 0.000708000035956502+ }+ ]+ },+ {+ "roundMs": 1603.0200409999816,+ "firstDeltaMs": null,+ "calls": [{- "label": "Talking head",- "from": 64,- "seconds": 2+ "name": "update_audio",+ "execMs": 0.004249999998137355},{- "label": "Talking head",- "from": 66,- "seconds": 2- },+ "name": "update_audio",+ "execMs": 0.000750000006519258+ }+ ]+ },+ {+ "roundMs": 1655.4195830000099,+ "firstDeltaMs": 1185.8099159999983,+ "calls": []+ }+ ]+ }+ },+ {+ "pass": true,+ "intent": "complex",+ "skill": "audio-and-subtitles",+ "areas": [+ "preview",+ "timeline",+ "inspector",+ "subtitles",+ "audio",+ "stock",+ "library",+ "side_panel",+ "top_bar"+ ],+ "declaredTools": 103,+ "routingMisses": [],+ "roundModel": "gemini-3.8-flash",+ "notes": [],+ "instant": null,+ "qualityGate": [],+ "judgeNote": null,+ "trace": [+ {+ "name": "generate_music",+ "round": 0,+ "atMs": 6853.7098340000375,+ "execMs": 0.0013329999637790024,+ "args": {+ "prompt": "Chill, mellow lo-fi ambient background music, soft electric piano, smooth relaxed beat, sunny beach vibe",+ "start": 0,+ "volume": 0.3,+ "add_to_timeline": true,+ "length": "clip",+ "instrumental": true,+ "reference_asset_ids": [+ "a-v1"+ ]+ }+ }+ ],+ "timings": {+ "gateMs": 292.982416999992,+ "gateSkipped": false,+ "ttftMs": 8896.698875000002,+ "modelMs": 8974.924916999997,+ "toolMs": 0.0013329999637790024,+ "totalMs": 9269.925374999992,+ "judgeMs": 307.85679200000595,+ "retryMs": 0,+ "retries": 0,+ "rounds": [+ {+ "roundMs": 6559.319749999966,+ "firstDeltaMs": null,+ "calls": [{- "seconds": 2,- "from": 68,- "label": "Talking head"- },+ "name": "generate_music",+ "execMs": 0.0013329999637790024+ }+ ]+ },+ {+ "roundMs": 2415.6051670000306,+ "firstDeltaMs": 2042.4562499999884,+ "calls": []+ }+ ]+ }+ }+ ]+ },+ {+ "name": "trim-ask-single-tool",+ "bucket": "single-tool",+ "passRate": 1,+ "budgetBreaches": [],+ "latency": {+ "gateMs": {+ "p50": 295,+ "p95": 308,+ "mean": 297,+ "n": 3+ },+ "ttftMs": {+ "p50": 3113,+ "p95": 5886,+ "mean": 3817,+ "n": 3+ },+ "totalMs": {+ "p50": 3229,+ "p95": 6076,+ "mean": 3953,+ "n": 3+ },+ "modelMs": {+ "p50": 2931,+ "p95": 5765,+ "mean": 3653,+ "n": 3+ },+ "toolMs": {+ "p50": 0,+ "p95": 0,+ "mean": 0,+ "n": 3+ },+ "rounds": {+ "mean": 2,+ "max": 2+ }+ },+ "runs": [+ {+ "pass": true,+ "intent": "simple",+ "skill": null,+ "areas": [+ "preview",+ "timeline",+ "inspector",+ "editor"+ ],+ "declaredTools": 70,+ "routingMisses": [],+ "roundModel": "gemini-3.1-flash-lite",+ "notes": [],+ "instant": null,+ "qualityGate": [],+ "judgeNote": null,+ "trace": [+ {+ "name": "trim_clip",+ "round": 0,+ "atMs": 4755.06362500001,+ "execMs": 0.006583000009413809,+ "args": {+ "in": 0,+ "clipId": "c1",+ "out": 5+ }+ }+ ],+ "timings": {+ "gateMs": 307.56374999997206,+ "gateSkipped": false,+ "ttftMs": 5885.744249999989,+ "modelMs": 5765.08929199999,+ "toolMs": 0.006583000009413809,+ "totalMs": 6075.649541000021,+ "judgeMs": 281.2807909999974,+ "retryMs": 0,+ "retries": 0,+ "rounds": [+ {+ "roundMs": 4445.752957999997,+ "firstDeltaMs": null,+ "calls": [{- "label": "Talking head - outro",- "from": 70,- "seconds": 1.6+ "name": "trim_clip",+ "execMs": 0.006583000009413809}- ],- "start": 0+ ]+ },+ {+ "roundMs": 1319.3363339999923,+ "firstDeltaMs": 1129.8835419999668,+ "calls": []+ }+ ]+ }+ },+ {+ "pass": true,+ "intent": "simple",+ "skill": null,+ "areas": [+ "preview",+ "timeline",+ "inspector",+ "editor"+ ],+ "declaredTools": 70,+ "routingMisses": [],+ "roundModel": "gemini-3.1-flash-lite",+ "notes": [],+ "instant": null,+ "qualityGate": [],+ "judgeNote": null,+ "trace": [+ {+ "name": "trim_clip",+ "round": 0,+ "atMs": 1378.729915999982,+ "execMs": 0.014957999985199422,+ "args": {+ "clipId": "c1",+ "out": 5+ }+ }+ ],+ "timings": {+ "gateMs": 286.7538749999949,+ "gateSkipped": false,+ "ttftMs": 2451.0434159999713,+ "modelMs": 2263.99770800001,+ "toolMs": 0.014957999985199422,+ "totalMs": 2553.3215829999535,+ "judgeMs": 342.14708399999654,+ "retryMs": 0,+ "retries": 0,+ "rounds": [+ {+ "roundMs": 1090.4872909999685,+ "firstDeltaMs": null,+ "calls": [+ {+ "name": "trim_clip",+ "execMs": 0.014957999985199422+ }+ ]+ },+ {+ "roundMs": 1173.5104170000413,+ "firstDeltaMs": 1071.464708000014,+ "calls": []+ }+ ]+ }+ },+ {+ "pass": true,+ "intent": "simple",+ "skill": null,+ "areas": [+ "preview",+ "timeline",+ "inspector",+ "editor"+ ],+ "declaredTools": 70,+ "routingMisses": [],+ "roundModel": "gemini-3.1-flash-lite",+ "notes": [],+ "instant": null,+ "qualityGate": [],+ "judgeNote": null,+ "trace": [+ {+ "name": "trim_clip",+ "round": 0,+ "atMs": 2064.502832999977,+ "execMs": 0.00604200002271682,+ "args": {+ "in": 0,+ "out": 5,+ "clipId": "c1"+ }+ }+ ],+ "timings": {+ "gateMs": 295.4639999999781,+ "gateSkipped": false,+ "ttftMs": 3113.1877499999828,+ "modelMs": 2930.8606669999426,+ "toolMs": 0.00604200002271682,+ "totalMs": 3228.944541999954,+ "judgeMs": 216.67524999997113,+ "retryMs": 0,+ "retries": 0,+ "rounds": [+ {+ "roundMs": 1767.761999999988,+ "firstDeltaMs": null,+ "calls": [+ {+ "name": "trim_clip",+ "execMs": 0.00604200002271682+ }+ ]+ },+ {+ "roundMs": 1163.0986669999547,+ "firstDeltaMs": 1047.5580829999526,+ "calls": []+ }+ ]+ }+ }+ ]+ },+ {+ "name": "transition-ask-styled",+ "bucket": "single-tool",+ "passRate": 1,+ "budgetBreaches": [],+ "latency": {+ "gateMs": {+ "p50": 287,+ "p95": 335,+ "mean": 300,+ "n": 3+ },+ "ttftMs": {+ "p50": 6393,+ "p95": 9196,+ "mean": 5294,+ "n": 3+ },+ "totalMs": {+ "p50": 6552,+ "p95": 9331,+ "mean": 5392,+ "n": 3+ },+ "modelMs": {+ "p50": 6272,+ "p95": 8988,+ "mean": 5087,+ "n": 3+ },+ "toolMs": {+ "p50": 0,+ "p95": 0,+ "mean": 0,+ "n": 3+ },+ "rounds": {+ "mean": 1.3,+ "max": 2+ }+ },+ "runs": [+ {+ "pass": true,+ "intent": "complex",+ "skill": "transitions-and-fades",+ "areas": [+ "preview",+ "timeline",+ "inspector",+ "effects",+ "animation",+ "transitions",+ "editor"+ ],+ "declaredTools": 73,+ "routingMisses": [],+ "roundModel": "gemini-3.8-flash",+ "notes": [],+ "instant": null,+ "qualityGate": [],+ "judgeNote": null,+ "trace": [+ {+ "name": "set_transition",+ "round": 0,+ "atMs": 7230.907999999996,+ "execMs": 0.04824999999254942,+ "args": {+ "seconds": 0.5,+ "clipId": "c1",+ "style": "pushdown"+ }+ }+ ],+ "timings": {+ "gateMs": 335.4893339999835,+ "gateSkipped": false,+ "ttftMs": 9195.887707999966,+ "modelMs": 8988.162375000014,+ "toolMs": 0.04824999999254942,+ "totalMs": 9331.445666000014,+ "judgeMs": 297.6030000000028,+ "retryMs": 0,+ "retries": 0,+ "rounds": [+ {+ "roundMs": 6889.254625000001,+ "firstDeltaMs": null,+ "calls": [+ {+ "name": "set_transition",+ "execMs": 0.04824999999254942+ }+ ]+ },+ {+ "roundMs": 2098.907750000013,+ "firstDeltaMs": 1963.700084000011,+ "calls": []+ }+ ]+ }+ },+ {+ "pass": true,+ "intent": "simple",+ "skill": null,+ "areas": [+ "preview",+ "timeline",+ "inspector",+ "effects",+ "animation",+ "transitions",+ "library",+ "top_bar",+ "editor"+ ],+ "declaredTools": 84,+ "routingMisses": [],+ "roundModel": "gemini-3.1-flash-lite",+ "notes": [],+ "instant": "set_transition",+ "qualityGate": [],+ "judgeNote": null,+ "trace": [+ {+ "name": "set_transition",+ "round": 0,+ "atMs": 292.2096249999595,+ "execMs": 0.0036250000121071935,+ "args": {+ "clipId": "c1",+ "style": "pushdown",+ "seconds": 0.44+ }+ }+ ],+ "timings": {+ "gateMs": 287.3120409999974,+ "gateSkipped": false,+ "ttftMs": 292.48870899999747,+ "modelMs": 0,+ "toolMs": 0.0036250000121071935,+ "totalMs": 292.4946249999921,+ "judgeMs": 230.67624999996042,+ "retryMs": 0,+ "retries": 0,+ "rounds": []+ }+ },+ {+ "pass": true,+ "intent": "simple",+ "skill": null,+ "areas": [+ "preview",+ "timeline",+ "inspector",+ "effects",+ "animation",+ "transitions",+ "top_bar",+ "editor"+ ],+ "declaredTools": 77,+ "routingMisses": [],+ "roundModel": "gemini-3.1-flash-lite",+ "notes": [],+ "instant": null,+ "qualityGate": [],+ "judgeNote": null,+ "trace": [+ {+ "name": "set_transition",+ "round": 0,+ "atMs": 5124.744375000009,+ "execMs": 0.0032500000088475645,+ "args": {+ "clipId": "c1",+ "seconds": 0.5,+ "style": "pushdown"+ }+ }+ ],+ "timings": {+ "gateMs": 277.24412500002654,+ "gateSkipped": false,+ "ttftMs": 6392.705499999982,+ "modelMs": 6272.208874000004,+ "toolMs": 0.0032500000088475645,+ "totalMs": 6552.322417000018,+ "judgeMs": 277.97829200001433,+ "retryMs": 0,+ "retries": 0,+ "rounds": [+ {+ "roundMs": 4845.824208000035,+ "firstDeltaMs": null,+ "calls": [+ {+ "name": "set_transition",+ "execMs": 0.0032500000088475645+ }+ ]+ },+ {+ "roundMs": 1426.384665999969,+ "firstDeltaMs": 1267.3150409999653,+ "calls": []+ }+ ]+ }+ }+ ]+ },+ {+ "name": "slide-in-direction-correct",+ "bucket": "single-tool",+ "passRate": 1,+ "budgetBreaches": [],+ "latency": {+ "gateMs": {+ "p50": 288,+ "p95": 296,+ "mean": 290,+ "n": 3+ },+ "ttftMs": {+ "p50": 289,+ "p95": 296,+ "mean": 291,+ "n": 3+ },+ "totalMs": {+ "p50": 289,+ "p95": 296,+ "mean": 291,+ "n": 3+ },+ "modelMs": {+ "p50": 0,+ "p95": 0,+ "mean": 0,+ "n": 3+ },+ "toolMs": {+ "p50": 0,+ "p95": 0,+ "mean": 0,+ "n": 3+ },+ "rounds": {+ "mean": 0,+ "max": 0+ }+ },+ "runs": [+ {+ "pass": true,+ "intent": "simple",+ "skill": null,+ "areas": [+ "preview",+ "timeline",+ "inspector",+ "effects",+ "animation",+ "transitions",+ "editor"+ ],+ "declaredTools": 73,+ "routingMisses": [],+ "roundModel": "gemini-3.1-flash-lite",+ "notes": [],+ "instant": "set_animation",+ "qualityGate": [],+ "judgeNote": "failures owned 0.49",+ "trace": [+ {+ "name": "set_animation",+ "round": 0,+ "atMs": 288.58908300002804,+ "execMs": 0.10308299999451265,+ "args": {+ "clipId": "c2",+ "which": "in",+ "style": "slideright",+ "seconds": 0.47+ }+ }+ ],+ "timings": {+ "gateMs": 288.10062500002095,+ "gateSkipped": false,+ "ttftMs": 289.0498329999973,+ "modelMs": 0,+ "toolMs": 0.10308299999451265,+ "totalMs": 289.0702080000192,+ "judgeMs": 221.4971249999944,+ "retryMs": 0,+ "retries": 0,+ "rounds": []+ }+ },+ {+ "pass": true,+ "intent": "simple",+ "skill": null,+ "areas": [+ "preview",+ "timeline",+ "inspector",+ "effects",+ "animation",+ "transitions",+ "editor"+ ],+ "declaredTools": 73,+ "routingMisses": [],+ "roundModel": "gemini-3.1-flash-lite",+ "notes": [],+ "instant": "set_animation",+ "qualityGate": [],+ "judgeNote": null,+ "trace": [+ {+ "name": "set_animation",+ "round": 0,+ "atMs": 286.19412499998,+ "execMs": 0.0040840000146999955,+ "args": {+ "clipId": "c2",+ "which": "in",+ "style": "slideright",+ "seconds": 0.46+ }+ }+ ],+ "timings": {+ "gateMs": 286.0055000000284,+ "gateSkipped": false,+ "ttftMs": 286.25808399997186,+ "modelMs": 0,+ "toolMs": 0.0040840000146999955,+ "totalMs": 286.26204199995846,+ "judgeMs": 240.00829099997645,+ "retryMs": 0,+ "retries": 0,+ "rounds": []+ }+ },+ {+ "pass": true,+ "intent": "simple",+ "skill": null,+ "areas": [+ "preview",+ "timeline",+ "inspector",+ "effects",+ "animation",+ "transitions",+ "editor"+ ],+ "declaredTools": 73,+ "routingMisses": [],+ "roundModel": "gemini-3.1-flash-lite",+ "notes": [],+ "instant": "set_animation",+ "qualityGate": [],+ "judgeNote": "failures owned 0.46",+ "trace": [+ {+ "name": "set_animation",+ "round": 0,+ "atMs": 296.20054200000595,+ "execMs": 0.004167000006418675,+ "args": {+ "clipId": "c2",+ "which": "in",+ "style": "slideright",+ "seconds": 0.47+ }+ }+ ],+ "timings": {+ "gateMs": 295.90124999999534,+ "gateSkipped": false,+ "ttftMs": 296.3215419999906,+ "modelMs": 0,+ "toolMs": 0.004167000006418675,+ "totalMs": 296.32895799999824,+ "judgeMs": 225.91437499999302,+ "retryMs": 0,+ "retries": 0,+ "rounds": []+ }+ }+ ]+ },+ {+ "name": "look-ask-single-tool",+ "bucket": "single-tool",+ "passRate": 1,+ "budgetBreaches": [],+ "latency": {+ "gateMs": {+ "p50": 269,+ "p95": 275,+ "mean": 267,+ "n": 3+ },+ "ttftMs": {+ "p50": 270,+ "p95": 275,+ "mean": 268,+ "n": 3+ },+ "totalMs": {+ "p50": 270,+ "p95": 275,+ "mean": 268,+ "n": 3+ },+ "modelMs": {+ "p50": 0,+ "p95": 0,+ "mean": 0,+ "n": 3+ },+ "toolMs": {+ "p50": 0,+ "p95": 0,+ "mean": 0,+ "n": 3+ },+ "rounds": {+ "mean": 0,+ "max": 0+ }+ },+ "runs": [+ {+ "pass": true,+ "intent": "simple",+ "skill": null,+ "areas": [+ "preview",+ "timeline",+ "inspector",+ "color",+ "effects",+ "video_gen",+ "scene",+ "library",+ "side_panel",+ "top_bar"+ ],+ "declaredTools": 100,+ "routingMisses": [],+ "roundModel": "gemini-3.1-flash-lite",+ "notes": [],+ "instant": "add_effect",+ "qualityGate": [],+ "judgeNote": null,+ "trace": [+ {+ "name": "add_effect",+ "round": 0,+ "atMs": 269.38970800000243,+ "execMs": 0.05199999996693805,+ "args": {+ "effect": "vhs",+ "amount": 0.69,+ "start": 6,+ "end": 12.5+ }+ }+ ],+ "timings": {+ "gateMs": 269.0963749999646,+ "gateSkipped": false,+ "ttftMs": 269.514749999973,+ "modelMs": 0,+ "toolMs": 0.05199999996693805,+ "totalMs": 269.5209160000086,+ "judgeMs": 254.70250000001397,+ "retryMs": 0,+ "retries": 0,+ "rounds": []+ }+ },+ {+ "pass": true,+ "intent": "simple",+ "skill": null,+ "areas": [+ "preview",+ "timeline",+ "inspector",+ "color",+ "effects",+ "video_gen",+ "scene",+ "library",+ "side_panel",+ "top_bar"+ ],+ "declaredTools": 100,+ "routingMisses": [],+ "roundModel": "gemini-3.1-flash-lite",+ "notes": [],+ "instant": "add_effect",+ "qualityGate": [],+ "judgeNote": null,+ "trace": [+ {+ "name": "add_effect",+ "round": 0,+ "atMs": 275.35920799995074,+ "execMs": 0.0038330000243149698,+ "args": {+ "effect": "vhs",+ "amount": 0.68,+ "start": 6,+ "end": 12.5+ }+ }+ ],+ "timings": {+ "gateMs": 275.1068750000559,+ "gateSkipped": false,+ "ttftMs": 275.45583299995633,+ "modelMs": 0,+ "toolMs": 0.0038330000243149698,+ "totalMs": 275.46241699997336,+ "judgeMs": 249.15562500001397,+ "retryMs": 0,+ "retries": 0,+ "rounds": []+ }+ },+ {+ "pass": true,+ "intent": "simple",+ "skill": null,+ "areas": [+ "preview",+ "timeline",+ "inspector",+ "color",+ "effects",+ "animation",+ "video_gen",+ "scene",+ "library",+ "side_panel",+ "top_bar"+ ],+ "declaredTools": 102,+ "routingMisses": [],+ "roundModel": "gemini-3.1-flash-lite",+ "notes": [],+ "instant": "add_effect",+ "qualityGate": [],+ "judgeNote": null,+ "trace": [+ {+ "name": "add_effect",+ "round": 0,+ "atMs": 258.08333300001686,+ "execMs": 0.0028750000055879354,+ "args": {+ "effect": "vhs",+ "amount": 0.68,+ "start": 6,+ "end": 12.5+ }+ }+ ],+ "timings": {+ "gateMs": 257.90475000004517,+ "gateSkipped": false,+ "ttftMs": 258.1542500000214,+ "modelMs": 0,+ "toolMs": 0.0028750000055879354,+ "totalMs": 258.15895800001454,+ "judgeMs": 263.5490829999908,+ "retryMs": 0,+ "retries": 0,+ "rounds": []+ }+ }+ ]+ },+ {+ "name": "audio-effect-single-tool",+ "bucket": "single-tool",+ "passRate": 1,+ "budgetBreaches": [],+ "latency": {+ "gateMs": {+ "p50": 266,+ "p95": 287,+ "mean": 270,+ "n": 3+ },+ "ttftMs": {+ "p50": 267,+ "p95": 288,+ "mean": 271,+ "n": 3+ },+ "totalMs": {+ "p50": 267,+ "p95": 288,+ "mean": 271,+ "n": 3+ },+ "modelMs": {+ "p50": 0,+ "p95": 0,+ "mean": 0,+ "n": 3+ },+ "toolMs": {+ "p50": 0,+ "p95": 0,+ "mean": 0,+ "n": 3+ },+ "rounds": {+ "mean": 0,+ "max": 0+ }+ },+ "runs": [+ {+ "pass": true,+ "intent": "simple",+ "skill": null,+ "areas": [+ "preview",+ "timeline",+ "inspector",+ "effects",+ "audio",+ "library",+ "side_panel"+ ],+ "declaredTools": 85,+ "routingMisses": [],+ "roundModel": "gemini-3.1-flash-lite",+ "notes": [],+ "instant": "add_effect",+ "qualityGate": [],+ "judgeNote": null,+ "trace": [+ {+ "name": "add_effect",+ "round": 0,+ "atMs": 287.232209000038,+ "execMs": 0.24045799998566508,+ "args": {+ "effect": "telephone",+ "amount": 0.68,+ "start": 6,+ "end": 12.5+ }+ }+ ],+ "timings": {+ "gateMs": 286.7231659999816,+ "gateSkipped": false,+ "ttftMs": 287.5645000000368,+ "modelMs": 0,+ "toolMs": 0.24045799998566508,+ "totalMs": 287.5706670000218,+ "judgeMs": 236.46583299996564,+ "retryMs": 0,+ "retries": 0,+ "rounds": []+ }+ },+ {+ "pass": true,+ "intent": "simple",+ "skill": null,+ "areas": [+ "preview",+ "timeline",+ "inspector",+ "effects",+ "audio",+ "side_panel",+ "editor"+ ],+ "declaredTools": 82,+ "routingMisses": [],+ "roundModel": "gemini-3.1-flash-lite",+ "notes": [],+ "instant": "add_effect",+ "qualityGate": [],+ "judgeNote": null,+ "trace": [+ {+ "name": "add_effect",+ "round": 0,+ "atMs": 258.01304099999834,+ "execMs": 0.004541000002063811,+ "args": {+ "effect": "telephone",+ "amount": 0.69,+ "start": 6,+ "end": 12.5+ }+ }+ ],+ "timings": {+ "gateMs": 257.85229200002505,+ "gateSkipped": false,+ "ttftMs": 258.08445799996844,+ "modelMs": 0,+ "toolMs": 0.004541000002063811,+ "totalMs": 258.08895799994934,+ "judgeMs": 268.93137499998556,+ "retryMs": 0,+ "retries": 0,+ "rounds": []+ }+ },+ {+ "pass": true,+ "intent": "simple",+ "skill": null,+ "areas": [+ "preview",+ "timeline",+ "inspector",+ "effects",+ "audio",+ "side_panel",+ "editor"+ ],+ "declaredTools": 82,+ "routingMisses": [],+ "roundModel": "gemini-3.1-flash-lite",+ "notes": [],+ "instant": "add_effect",+ "qualityGate": [],+ "judgeNote": null,+ "trace": [+ {+ "name": "add_effect",+ "round": 0,+ "atMs": 266.5954170000041,+ "execMs": 0.007082999974954873,+ "args": {+ "effect": "telephone",+ "amount": 0.69,+ "start": 6,+ "end": 12.5+ }+ }+ ],+ "timings": {+ "gateMs": 266.2927079999936,+ "gateSkipped": false,+ "ttftMs": 266.7177500000107,+ "modelMs": 0,+ "toolMs": 0.007082999974954873,+ "totalMs": 266.72541700000875,+ "judgeMs": 254.47275000001537,+ "retryMs": 0,+ "retries": 0,+ "rounds": []+ }+ }+ ]+ },+ {+ "name": "sound-dissolve-single-tool",+ "bucket": "single-tool",+ "passRate": 1,+ "budgetBreaches": [],+ "latency": {+ "gateMs": {+ "p50": 289,+ "p95": 309,+ "mean": 286,+ "n": 3+ },+ "ttftMs": {+ "p50": 3564,+ "p95": 7128,+ "mean": 4603,+ "n": 3+ },+ "totalMs": {+ "p50": 3961,+ "p95": 7435,+ "mean": 4947,+ "n": 3+ },+ "modelMs": {+ "p50": 3649,+ "p95": 7143,+ "mean": 4658,+ "n": 3+ },+ "toolMs": {+ "p50": 0,+ "p95": 0,+ "mean": 0,+ "n": 3+ },+ "rounds": {+ "mean": 2,+ "max": 2+ }+ },+ "runs": [+ {+ "pass": true,+ "intent": "simple",+ "skill": null,+ "areas": [+ "preview",+ "timeline",+ "inspector",+ "effects",+ "transitions",+ "audio",+ "editor"+ ],+ "declaredTools": 75,+ "routingMisses": [],+ "roundModel": "gemini-3.1-flash-lite",+ "notes": [],+ "instant": null,+ "qualityGate": [],+ "judgeNote": null,+ "trace": [+ {+ "name": "set_transition",+ "round": 0,+ "atMs": 5764.952665999997,+ "execMs": 0.18366599996807054,+ "args": {+ "clipId": "c1",+ "seconds": 0.3,+ "style": "audiocross"+ }+ }+ ],+ "timings": {+ "gateMs": 289.1781659999979,+ "gateSkipped": false,+ "ttftMs": 7128.057499999995,+ "modelMs": 7142.5439169999445,+ "toolMs": 0.18366599996807054,+ "totalMs": 7434.578082999971,+ "judgeMs": 248.58254099998157,+ "retryMs": 0,+ "retries": 0,+ "rounds": [+ {+ "roundMs": 5474.448374999978,+ "firstDeltaMs": null,+ "calls": [+ {+ "name": "set_transition",+ "execMs": 0.18366599996807054+ }+ ]+ },+ {+ "roundMs": 1668.0955419999664,+ "firstDeltaMs": 1362.1745829999563,+ "calls": []+ }+ ]+ }+ },+ {+ "pass": true,+ "intent": "simple",+ "skill": null,+ "areas": [+ "preview",+ "timeline",+ "inspector",+ "effects",+ "transitions",+ "audio",+ "editor"+ ],+ "declaredTools": 75,+ "routingMisses": [],+ "roundModel": "gemini-3.1-flash-lite",+ "notes": [],+ "instant": null,+ "qualityGate": [],+ "judgeNote": null,+ "trace": [+ {+ "name": "set_transition",+ "round": 0,+ "atMs": 2276.402833,+ "execMs": 0.007791999960318208,+ "args": {+ "clipId": "c1",+ "style": "audiocross",+ "seconds": 0.3+ }+ }+ ],+ "timings": {+ "gateMs": 308.84325000003446,+ "gateSkipped": false,+ "ttftMs": 3564.4721659999923,+ "modelMs": 3648.954417000001,+ "toolMs": 0.007791999960318208,+ "totalMs": 3961.0801249999786,+ "judgeMs": 194.6512920000241,+ "retryMs": 0,+ "retries": 0,+ "rounds": [+ {+ "roundMs": 1965.453542000032,+ "firstDeltaMs": null,+ "calls": [+ {+ "name": "set_transition",+ "execMs": 0.007791999960318208+ }+ ]+ },+ {+ "roundMs": 1683.5008749999688,+ "firstDeltaMs": 1287.251540999976,+ "calls": []+ }+ ]+ }+ },+ {+ "pass": true,+ "intent": "simple",+ "skill": null,+ "areas": [+ "preview",+ "timeline",+ "inspector",+ "effects",+ "transitions",+ "audio",+ "editor"+ ],+ "declaredTools": 75,+ "routingMisses": [],+ "roundModel": "gemini-3.1-flash-lite",+ "notes": [],+ "instant": null,+ "qualityGate": [],+ "judgeNote": null,+ "trace": [+ {+ "name": "set_transition",+ "round": 0,+ "atMs": 1967.5905839999905,+ "execMs": 0.00620800000615418,+ "args": {+ "style": "audiocross",+ "clipId": "c1",+ "seconds": 0.3+ }+ }+ ],+ "timings": {+ "gateMs": 259.63266699999804,+ "gateSkipped": false,+ "ttftMs": 3117.8015840000007,+ "modelMs": 3181.908584000019,+ "toolMs": 0.00620800000615418,+ "totalMs": 3443.9027500000084,+ "judgeMs": 206.35820800001966,+ "retryMs": 0,+ "retries": 0,+ "rounds": [+ {+ "roundMs": 1706.5325840000296,+ "firstDeltaMs": null,+ "calls": [+ {+ "name": "set_transition",+ "execMs": 0.00620800000615418+ }+ ]+ },+ {+ "roundMs": 1475.3759999999893,+ "firstDeltaMs": 1149.4281670000055,+ "calls": []+ }+ ]+ }+ }+ ]+ },+ {+ "name": "animation-overrides-transition",+ "bucket": "single-tool",+ "passRate": 1,+ "budgetBreaches": [],+ "latency": {+ "gateMs": {+ "p50": 278,+ "p95": 340,+ "mean": 291,+ "n": 3+ },+ "ttftMs": {+ "p50": 5725,+ "p95": 6109,+ "mean": 5161,+ "n": 3+ },+ "totalMs": {+ "p50": 6074,+ "p95": 6553,+ "mean": 5592,+ "n": 3+ },+ "modelMs": {+ "p50": 5730,+ "p95": 6294,+ "mean": 5295,+ "n": 3+ },+ "toolMs": {+ "p50": 0,+ "p95": 0,+ "mean": 0,+ "n": 3+ },+ "rounds": {+ "mean": 2.3,+ "max": 3+ }+ },+ "runs": [+ {+ "pass": true,+ "intent": "simple",+ "skill": null,+ "areas": [+ "preview",+ "timeline",+ "inspector",+ "effects",+ "animation",+ "transitions",+ "editor"+ ],+ "declaredTools": 73,+ "routingMisses": [],+ "roundModel": "gemini-3.1-flash-lite",+ "notes": [],+ "instant": null,+ "qualityGate": [],+ "judgeNote": null,+ "trace": [+ {+ "name": "set_transition",+ "round": 0,+ "atMs": 4957.611708000011,+ "execMs": 0.1391670000157319,+ "args": {+ "seconds": 0,+ "clipId": "c1"+ }+ },+ {+ "name": "set_animation",+ "round": 0,+ "atMs": 4959.681582999998,+ "execMs": 0.005208000016864389,+ "args": {+ "style": "pop",+ "clipId": "c2",+ "which": "in",+ "seconds": 0.5+ }+ }+ ],+ "timings": {+ "gateMs": 255.6330420000013,+ "gateSkipped": false,+ "ttftMs": 6109.203333000012,+ "modelMs": 6293.60170900001,+ "toolMs": 0.1443750000325963,+ "totalMs": 6553.404916999978,+ "judgeMs": 262.70691599999554,+ "retryMs": 0,+ "retries": 0,+ "rounds": [+ {+ "roundMs": 4700.71666700003,+ "firstDeltaMs": null,+ "calls": [+ {+ "name": "set_transition",+ "execMs": 0.1391670000157319+ },+ {+ "name": "set_animation",+ "execMs": 0.005208000016864389+ }+ ]+ },+ {+ "roundMs": 1592.8850419999799,+ "firstDeltaMs": 1148.7802919999813,+ "calls": []+ }+ ]+ }+ },+ {+ "pass": true,+ "intent": "simple",+ "skill": null,+ "areas": [+ "preview",+ "timeline",+ "inspector",+ "effects",+ "animation",+ "transitions",+ "editor"+ ],+ "declaredTools": 73,+ "routingMisses": [],+ "roundModel": "gemini-3.1-flash-lite",+ "notes": [],+ "instant": null,+ "qualityGate": [],+ "judgeNote": null,+ "trace": [+ {+ "name": "set_transition",+ "round": 0,+ "atMs": 2236.17074999999,+ "execMs": 0.006666999950539321,+ "args": {+ "seconds": 0,+ "clipId": "c1"+ }+ },+ {+ "name": "set_animation",+ "round": 0,+ "atMs": 2236.3257919999887,+ "execMs": 0.001125000009778887,+ "args": {+ "style": "pop",+ "clipId": "c2",+ "seconds": 0.5,+ "which": "in"+ }+ },+ {+ "name": "remove_transition",+ "round": 1,+ "atMs": 4429.580332999991,+ "execMs": 0.0034580000210553408,+ "args": {+ "transitionId": "c1"+ }+ }+ ],+ "timings": {+ "gateMs": 339.65454100002535,+ "gateSkipped": false,+ "ttftMs": 5724.758207999985,+ "modelMs": 5730.387707000016,+ "toolMs": 0.011249999981373549,+ "totalMs": 6073.837500000023,+ "judgeMs": 214.58708399999887,+ "retryMs": 0,+ "retries": 0,+ "rounds": [+ {+ "roundMs": 1895.211958000029,+ "firstDeltaMs": null,+ "calls": [+ {+ "name": "set_transition",+ "execMs": 0.006666999950539321+ },+ {+ "name": "set_animation",+ "execMs": 0.001125000009778887+ }+ ]+ },+ {+ "roundMs": 2191.698708000011,+ "firstDeltaMs": null,+ "calls": [+ {+ "name": "remove_transition",+ "execMs": 0.0034580000210553408+ }+ ]+ },+ {+ "roundMs": 1643.4770409999765,+ "firstDeltaMs": 1294.5286249999772,+ "calls": []+ }+ ]+ }+ },+ {+ "pass": true,+ "intent": "simple",+ "skill": null,+ "areas": [+ "preview",+ "timeline",+ "inspector",+ "effects",+ "animation",+ "transitions",+ "editor"+ ],+ "declaredTools": 73,+ "routingMisses": [],+ "roundModel": "gemini-3.1-flash-lite",+ "notes": [],+ "instant": null,+ "qualityGate": [],+ "judgeNote": null,+ "trace": [+ {+ "name": "set_transition",+ "round": 0,+ "atMs": 2171.0417080000043,+ "execMs": 0.018166999972891062,+ "args": {+ "clipId": "c1",+ "seconds": 0+ }+ },+ {+ "name": "set_animation",+ "round": 0,+ "atMs": 2171.9010000000126,+ "execMs": 0.008458000025711954,+ "args": {+ "style": "pop",+ "clipId": "c2",+ "which": "in",+ "seconds": 0.5+ }+ }+ ],+ "timings": {+ "gateMs": 277.67399999999907,+ "gateSkipped": false,+ "ttftMs": 3648.9808750000084,+ "modelMs": 3861.243666000024,+ "toolMs": 0.026624999998603016,+ "totalMs": 4147.93441700004,+ "judgeMs": 288.43741600000067,+ "retryMs": 0,+ "retries": 0,+ "rounds": [+ {+ "roundMs": 1887.5172080000048,+ "firstDeltaMs": null,+ "calls": [+ {+ "name": "set_transition",+ "execMs": 0.018166999972891062+ },+ {+ "name": "set_animation",+ "execMs": 0.008458000025711954+ }+ ]+ },+ {+ "roundMs": 1973.7264580000192,+ "firstDeltaMs": 1475.392749999999,+ "calls": []+ }+ ]+ }+ }+ ]+ },+ {+ "name": "filler-words-cut-with-editor",+ "bucket": "multi-tool",+ "passRate": 1,+ "budgetBreaches": [],+ "latency": {+ "gateMs": {+ "p50": 363,+ "p95": 670,+ "mean": 438,+ "n": 3+ },+ "ttftMs": {+ "p50": 35207,+ "p95": 50332,+ "mean": 37519,+ "n": 3+ },+ "totalMs": {+ "p50": 35498,+ "p95": 50836,+ "mean": 37925,+ "n": 3+ },+ "modelMs": {+ "p50": 35185,+ "p95": 50416,+ "mean": 37454,+ "n": 3+ },+ "toolMs": {+ "p50": 1,+ "p95": 2,+ "mean": 1,+ "n": 3+ },+ "rounds": {+ "mean": 13.3,+ "max": 22+ }+ },+ "runs": [+ {+ "pass": true,+ "intent": "complex",+ "skill": "watching-and-cutting",+ "areas": [+ "preview",+ "timeline",+ "inspector",+ "subtitles",+ "audio",+ "library",+ "side_panel",+ "top_bar",+ "editor"+ ],+ "declaredTools": 105,+ "routingMisses": [],+ "roundModel": "gemini-3.8-flash",+ "notes": [],+ "instant": null,+ "qualityGate": [],+ "judgeNote": null,+ "trace": [+ {+ "name": "find_filler",+ "round": 0,+ "atMs": 6423.560666999954,+ "execMs": 0.19024999998509884,+ "args": {+ "clip_id": "c1",+ "track": 0+ }+ },+ {+ "name": "detect_silence",+ "round": 1,+ "atMs": 8914.558833999967,+ "execMs": 0.05137499998090789,+ "args": {+ "min_silence": 0.1,+ "to": 6,+ "threshold_db": -35,+ "clip_id": "c1",+ "from": 0+ }+ },+ {+ "name": "split_at",+ "round": 2,+ "atMs": 11007.473750000005,+ "execMs": 0.11587500001769513,+ "args": {+ "t": 4.55+ }+ },+ {+ "name": "split_at",+ "round": 2,+ "atMs": 11007.670333999966,+ "execMs": 0.007249999966006726,+ "args": {+ "t": 5.6+ }+ },+ {+ "name": "delete_item",+ "round": 3,+ "atMs": 13390.454833999975,+ "execMs": 0.27799999999115244,+ "args": {+ "kind": "clip",+ "id": "c1-2-3"+ }+ },+ {+ "name": "trim_clip",+ "round": 3,+ "atMs": 13391.036334000004,+ "execMs": 0.10795799997868016,+ "args": {+ "in": 0.45,+ "clipId": "c1-1"+ }+ },+ {+ "name": "refine_speech_cuts",+ "round": 4,+ "atMs": 27092.396374999953,+ "execMs": 0.1305419999989681,+ "args": {+ "pace": "natural",+ "clip_ids": [+ "c1-1",+ "c1-2-4"+ ]+ }+ },+ {+ "name": "get_state",+ "round": 5,+ "atMs": 29709.528541999985,+ "execMs": 0.41791699995519593,+ "args": {}+ },+ {+ "name": "align_to_audio",+ "round": 6,+ "atMs": 31641.34724999999,+ "execMs": 0.017667000007349998,+ "args": {+ "target": "captions",+ "track": 0+ }+ },+ {+ "name": "update_cue",+ "round": 7,+ "atMs": 33554.104208999954,+ "execMs": 0.05537499999627471,+ "args": {+ "id": "cue1",+ "text": "So today we're"+ }+ },+ {+ "name": "update_cue",+ "round": 7,+ "atMs": 33554.452624999976,+ "execMs": 0.008333000005222857,+ "args": {+ "id": "cue3",+ "text": "and"+ }+ }+ ],+ "timings": {+ "gateMs": 279.37712499999907,+ "gateSkipped": false,+ "ttftMs": 35206.940249999985,+ "modelMs": 35184.756250999984,+ "toolMs": 1.3805419998825528,+ "totalMs": 35497.60491699999,+ "judgeMs": 310.3287910000072,+ "retryMs": 0,+ "retries": 0,+ "rounds": [+ {+ "roundMs": 6139.123957999982,+ "firstDeltaMs": null,+ "calls": [+ {+ "name": "find_filler",+ "execMs": 0.19024999998509884+ }+ ]+ },+ {+ "roundMs": 2486.63079200004,+ "firstDeltaMs": null,+ "calls": [+ {+ "name": "detect_silence",+ "execMs": 0.05137499998090789+ }+ ]+ },+ {+ "roundMs": 2090.33908299997,+ "firstDeltaMs": null,+ "calls": [+ {+ "name": "split_at",+ "execMs": 0.11587500001769513+ },+ {+ "name": "split_at",+ "execMs": 0.007249999966006726+ }+ ]+ },+ {+ "roundMs": 2380.0327919999836,+ "firstDeltaMs": null,+ "calls": [+ {+ "name": "delete_item",+ "execMs": 0.27799999999115244+ },+ {+ "name": "trim_clip",+ "execMs": 0.10795799997868016+ }+ ]+ },+ {+ "roundMs": 13696.37854200002,+ "firstDeltaMs": null,+ "calls": [+ {+ "name": "refine_speech_cuts",+ "execMs": 0.1305419999989681+ }+ ]+ },+ {+ "roundMs": 2613.7787499999977,+ "firstDeltaMs": null,+ "calls": [+ {+ "name": "get_state",+ "execMs": 0.41791699995519593+ }+ ]+ },+ {+ "roundMs": 1928.9118749999907,+ "firstDeltaMs": null,+ "calls": [+ {+ "name": "align_to_audio",+ "execMs": 0.017667000007349998+ }+ ]+ },+ {+ "roundMs": 1909.4799999999814,+ "firstDeltaMs": null,+ "calls": [+ {+ "name": "update_cue",+ "execMs": 0.05537499999627471+ },+ {+ "name": "update_cue",+ "execMs": 0.008333000005222857+ }+ ]+ },+ {+ "roundMs": 1940.080459000019,+ "firstDeltaMs": 1650.6597499999916,+ "calls": []+ }+ ]+ }+ },+ {+ "pass": true,+ "intent": "complex",+ "skill": "watching-and-cutting",+ "areas": [+ "preview",+ "timeline",+ "inspector",+ "transitions",+ "subtitles",+ "audio",+ "library",+ "side_panel",+ "top_bar",+ "editor"+ ],+ "declaredTools": 105,+ "routingMisses": [],+ "roundModel": "gemini-3.8-flash",+ "notes": [],+ "instant": null,+ "qualityGate": [],+ "judgeNote": null,+ "trace": [+ {+ "name": "find_filler",+ "round": 0,+ "atMs": 2465.97195799998,+ "execMs": 0.03591600002255291,+ "args": {+ "clip_id": "c1"+ }+ },+ {+ "name": "detect_silence",+ "round": 1,+ "atMs": 4283.671625000017,+ "execMs": 0.1032499999855645,+ "args": {+ "min_silence": 0.1,+ "clip_id": "c1",+ "from": 0,+ "to": 6,+ "threshold_db": -30+ }+ },+ {+ "name": "trim_clip",+ "round": 2,+ "atMs": 6181.593791000021,+ "execMs": 0.032833000004757196,+ "args": {+ "in": 0.45,+ "clipId": "c1"+ }+ },+ {+ "name": "get_state",+ "round": 3,+ "atMs": 8030.2934160000295,+ "execMs": 0.050749999994877726,+ "args": {}+ },+ {+ "name": "undo",+ "round": 4,+ "atMs": 9800.059291000012,+ "execMs": 0.009040999982971698,+ "args": {}+ },+ {+ "name": "split_at",+ "round": 5,+ "atMs": 11517.143250000023,+ "execMs": 0.04658300004666671,+ "args": {+ "t": 5.6+ }+ },+ {+ "name": "split_at",+ "round": 6,+ "atMs": 13153.54879099998,+ "execMs": 0.017042000021319836,+ "args": {+ "t": 4.55+ }+ },+ {+ "name": "split_at",+ "round": 7,+ "atMs": 14942.620540999982,+ "execMs": 0.054875000030733645,+ "args": {+ "t": 0.45+ }+ },+ {+ "name": "get_state",+ "round": 8,+ "atMs": 16987.046374999976,+ "execMs": 0.2518339999951422,+ "args": {}+ },+ {+ "name": "delete_item",+ "round": 9,+ "atMs": 19798.928375000018,+ "execMs": 0.19750000000931323,+ "args": {+ "id": "c1-1-3-5",+ "kind": "clip"+ }+ },+ {+ "name": "delete_item",+ "round": 10,+ "atMs": 21935.19733300002,+ "execMs": 0.3006250000325963,+ "args": {+ "id": "c1-1-4",+ "kind": "clip"+ }+ },+ {+ "name": "get_state",+ "round": 11,+ "atMs": 24042.764790999994,+ "execMs": 0.05141699995147064,+ "args": {}+ },+ {+ "name": "delete_item",+ "round": 12,+ "atMs": 26056.646833000006,+ "execMs": 0.447708000021521,+ "args": {+ "kind": "audio",+ "id": "au1-7"+ }+ },+ {+ "name": "get_state",+ "round": 13,+ "atMs": 28727.604915999982,+ "execMs": 0.03308399999514222,+ "args": {}+ },+ {+ "name": "update_audio",+ "round": 14,+ "atMs": 31400.913249999983,+ "execMs": 0.4530410000006668,+ "args": {+ "start": 0,+ "id": "au1-8"+ }+ },+ {+ "name": "get_state",+ "round": 15,+ "atMs": 33264.96195800003,+ "execMs": 0.08083300001453608,+ "args": {}+ },+ {+ "name": "update_cue",+ "round": 16,+ "atMs": 36635.31766599999,+ "execMs": 0.027415999968070537,+ "args": {+ "text": "so today we're",+ "id": "cue1"+ }+ },+ {+ "name": "get_state",+ "round": 17,+ "atMs": 39013.65083300002,+ "execMs": 0.18770800001220778,+ "args": {}+ },+ {+ "name": "update_cue",+ "round": 18,+ "atMs": 41068.66145800002,+ "execMs": 0.03391699999338016,+ "args": {+ "id": "cue3",+ "text": "and"+ }+ },+ {+ "name": "refine_speech_cuts",+ "round": 19,+ "atMs": 44928.08066600002,+ "execMs": 0.06620900001144037,+ "args": {+ "pace": "natural",+ "clip_ids": [+ "c1-1-3-6",+ "c1-2"+ ]+ }+ },+ {+ "name": "align_to_audio",+ "round": 20,+ "atMs": 46833.981791,+ "execMs": 0.004167000006418675,+ "args": {+ "target": "captions"+ }+ }+ ],+ "timings": {+ "gateMs": 363.17774999997346,+ "gateSkipped": false,+ "ttftMs": 50332.33041599998,+ "modelMs": 50415.61825300008,+ "toolMs": 2.4857490001013502,+ "totalMs": 50835.67916599999,+ "judgeMs": 236.2410829999717,+ "retryMs": 0,+ "retries": 0,+ "rounds": [+ {+ "roundMs": 2100.9943750000093,+ "firstDeltaMs": null,+ "calls": [+ {+ "name": "find_filler",+ "execMs": 0.03591600002255291+ }+ ]+ },+ {+ "roundMs": 1816.155374999973,+ "firstDeltaMs": null,+ "calls": [+ {+ "name": "detect_silence",+ "execMs": 0.1032499999855645+ }+ ]+ },+ {+ "roundMs": 1896.8156249999884,+ "firstDeltaMs": null,+ "calls": [+ {+ "name": "trim_clip",+ "execMs": 0.032833000004757196+ }+ ]+ },+ {+ "roundMs": 1847.6458340000245,+ "firstDeltaMs": null,+ "calls": [+ {+ "name": "get_state",+ "execMs": 0.050749999994877726+ }+ ]+ },+ {+ "roundMs": 1768.2988339999574,+ "firstDeltaMs": null,+ "calls": [+ {+ "name": "undo",+ "execMs": 0.009040999982971698+ }+ ]+ },+ {+ "roundMs": 1716.445875000034,+ "firstDeltaMs": null,+ "calls": [+ {+ "name": "split_at",+ "execMs": 0.04658300004666671+ }+ ]+ },+ {+ "roundMs": 1635.714250000019,+ "firstDeltaMs": null,+ "calls": [+ {+ "name": "split_at",+ "execMs": 0.017042000021319836+ }+ ]+ },+ {+ "roundMs": 1788.2793330000131,+ "firstDeltaMs": null,+ "calls": [+ {+ "name": "split_at",+ "execMs": 0.054875000030733645+ }+ ]+ },+ {+ "roundMs": 2042.8841660000035,+ "firstDeltaMs": null,+ "calls": [+ {+ "name": "get_state",+ "execMs": 0.2518339999951422+ }+ ]+ },+ {+ "roundMs": 2807.625417000032,+ "firstDeltaMs": null,+ "calls": [+ {+ "name": "delete_item",+ "execMs": 0.19750000000931323+ }+ ]+ },+ {+ "roundMs": 2131.5503340000287,+ "firstDeltaMs": null,+ "calls": [+ {+ "name": "delete_item",+ "execMs": 0.3006250000325963+ }+ ]+ },+ {+ "roundMs": 2104.593499999959,+ "firstDeltaMs": null,+ "calls": [+ {+ "name": "get_state",+ "execMs": 0.05141699995147064+ }+ ]+ },+ {+ "roundMs": 2010.0908750000526,+ "firstDeltaMs": null,+ "calls": [+ {+ "name": "delete_item",+ "execMs": 0.447708000021521+ }+ ]+ },+ {+ "roundMs": 2667.412708000047,+ "firstDeltaMs": null,+ "calls": [+ {+ "name": "get_state",+ "execMs": 0.03308399999514222+ }+ ]+ },+ {+ "roundMs": 2669.556416999956,+ "firstDeltaMs": null,+ "calls": [+ {+ "name": "update_audio",+ "execMs": 0.4530410000006668+ }+ ]+ },+ {+ "roundMs": 1859.6817089999677,+ "firstDeltaMs": null,+ "calls": [+ {+ "name": "get_state",+ "execMs": 0.08083300001453608+ }+ ]+ },+ {+ "roundMs": 3366.3862090000184,+ "firstDeltaMs": null,+ "calls": [+ {+ "name": "update_cue",+ "execMs": 0.027415999968070537+ }+ ]+ },+ {+ "roundMs": 2373.349749999994,+ "firstDeltaMs": null,+ "calls": [+ {+ "name": "get_state",+ "execMs": 0.18770800001220778+ }+ ]+ },+ {+ "roundMs": 2050.4419580000103,+ "firstDeltaMs": null,+ "calls": [+ {+ "name": "update_cue",+ "execMs": 0.03391699999338016+ }+ ]+ },+ {+ "roundMs": 3857.207791999972,+ "firstDeltaMs": null,+ "calls": [+ {+ "name": "refine_speech_cuts",+ "execMs": 0.06620900001144037+ }+ ]+ },+ {+ "roundMs": 1904.6372919999994,+ "firstDeltaMs": null,+ "calls": [+ {+ "name": "align_to_audio",+ "execMs": 0.004167000006418675+ }+ ]+ },+ {+ "roundMs": 3999.850625000021,+ "firstDeltaMs": 3496.994834000012,+ "calls": []+ }+ ]+ }+ },+ {+ "pass": true,+ "intent": "complex",+ "skill": "watching-and-cutting",+ "areas": [+ "preview",+ "timeline",+ "inspector",+ "subtitles",+ "audio",+ "library",+ "side_panel",+ "top_bar",+ "editor"+ ],+ "declaredTools": 105,+ "routingMisses": [],+ "roundModel": "gemini-3.8-flash",+ "notes": [],+ "instant": null,+ "qualityGate": [],+ "judgeNote": null,+ "trace": [+ {+ "name": "find_filler",+ "round": 0,+ "atMs": 2493.229624999978,+ "execMs": 0.05712499999208376,+ "args": {+ "clip_id": "c1"+ }+ },+ {+ "name": "detect_silence",+ "round": 1,+ "atMs": 4141.955499999982,+ "execMs": 0.01204100000904873,+ "args": {+ "clip_id": "c1"+ }+ },+ {+ "name": "split_at",+ "round": 2,+ "atMs": 15915.409875000012,+ "execMs": 0.11891700001433492,+ "args": {+ "t": 0.45+ }+ },+ {+ "name": "split_at",+ "round": 3,+ "atMs": 18050.555125000014,+ "execMs": 0.03425000002607703,+ "args": {+ "t": 4.55+ }+ },+ {+ "name": "split_at",+ "round": 4,+ "atMs": 19620.45641600003,+ "execMs": 0.02412499999627471,+ "args": {+ "t": 5.6+ }+ },+ {+ "name": "delete_item",+ "round": 5,+ "atMs": 21524.928375000018,+ "execMs": 0.025957999983802438,+ "args": {+ "kind": "clip",+ "id": "c1-1"+ }+ },+ {+ "name": "delete_item",+ "round": 5,+ "atMs": 21525.02879100002,+ "execMs": 0.008333000005222857,+ "args": {+ "kind": "clip",+ "id": "c1-2-6-7"+ }+ },+ {+ "name": "delete_item",+ "round": 5,+ "atMs": 21525.065125000023,+ "execMs": 0.008583999995607883,+ "args": {+ "id": "au1-3",+ "kind": "audio"+ }+ },+ {+ "name": "get_state",+ "round": 6,+ "atMs": 23256.531415999983,+ "execMs": 0.08904099999926984,+ "args": {}+ },+ {+ "name": "update_audio",+ "round": 7,+ "atMs": 25532.989125000022,+ "execMs": 0.051124999998137355,+ "args": {+ "start": 0,+ "id": "au1-4"+ }+ },+ {+ "name": "refine_speech_cuts",+ "round": 7,+ "atMs": 25533.187916000024,+ "execMs": 0.02504199999384582,+ "args": {+ "pace": "natural",+ "clip_ids": [+ "c1-2-5",+ "c1-2-6-8"+ ]+ }+ },+ {+ "name": "update_cue",+ "round": 7,+ "atMs": 25533.290041,+ "execMs": 0.011416000023018569,+ "args": {+ "text": "So today we're",+ "id": "cue1"+ }+ },+ {+ "name": "update_cue",+ "round": 7,+ "atMs": 25533.349708000023,+ "execMs": 0.015749999962281436,+ "args": {+ "text": "And",+ "id": "cue3"+ }+ }+ ],+ "timings": {+ "gateMs": 670.1086249999935,+ "gateSkipped": false,+ "ttftMs": 27018.361416,+ "modelMs": 26762.549081000092,+ "toolMs": 0.48170699999900535,+ "totalMs": 27442.874375000014,+ "judgeMs": 244.11712499998976,+ "retryMs": 0,+ "retries": 0,+ "rounds": [+ {+ "roundMs": 1821.524291000038,+ "firstDeltaMs": null,+ "calls": [+ {+ "name": "find_filler",+ "execMs": 0.05712499999208376+ }+ ]+ },+ {+ "roundMs": 1647.8133749999688,+ "firstDeltaMs": null,+ "calls": [+ {+ "name": "detect_silence",+ "execMs": 0.01204100000904873+ }+ ]+ },+ {+ "roundMs": 11772.277416000026,+ "firstDeltaMs": null,+ "calls": [+ {+ "name": "split_at",+ "execMs": 0.11891700001433492+ }+ ]+ },+ {+ "roundMs": 2133.7217079999973,+ "firstDeltaMs": null,+ "calls": [+ {+ "name": "split_at",+ "execMs": 0.03425000002607703+ }+ ]+ },+ {+ "roundMs": 1569.235624999972,+ "firstDeltaMs": null,+ "calls": [+ {+ "name": "split_at",+ "execMs": 0.02412499999627471+ }+ ]+ },+ {+ "roundMs": 1903.7515410000342,+ "firstDeltaMs": null,+ "calls": [+ {+ "name": "delete_item",+ "execMs": 0.025957999983802438+ },+ {+ "name": "delete_item",+ "execMs": 0.008333000005222857+ },+ {+ "name": "delete_item",+ "execMs": 0.008583999995607883+ }+ ]+ },+ {+ "roundMs": 1730.8703749999986,+ "firstDeltaMs": null,+ "calls": [+ {+ "name": "get_state",+ "execMs": 0.08904099999926984+ }+ ]+ },+ {+ "roundMs": 2275.1513330000453,+ "firstDeltaMs": null,+ "calls": [+ {+ "name": "update_audio",+ "execMs": 0.051124999998137355+ },+ {+ "name": "refine_speech_cuts",+ "execMs": 0.02504199999384582+ },+ {+ "name": "update_cue",+ "execMs": 0.011416000023018569+ },+ {+ "name": "update_cue",+ "execMs": 0.015749999962281436+ }+ ]+ },+ {+ "roundMs": 1908.2034170000115,+ "firstDeltaMs": 1484.029582999996,+ "calls": []+ }+ ]+ }+ }+ ]+ },+ {+ "name": "edit-request-still-uses-tools",+ "bucket": "single-tool",+ "passRate": 1,+ "budgetBreaches": [],+ "latency": {+ "gateMs": {+ "p50": 307,+ "p95": 418,+ "mean": 327,+ "n": 3+ },+ "ttftMs": {+ "p50": 3970,+ "p95": 6243,+ "mean": 4314,+ "n": 3+ },+ "totalMs": {+ "p50": 4229,+ "p95": 6413,+ "mean": 4501,+ "n": 3+ },+ "modelMs": {+ "p50": 3920,+ "p95": 5992,+ "mean": 4171,+ "n": 3+ },+ "toolMs": {+ "p50": 0,+ "p95": 0,+ "mean": 0,+ "n": 3+ },+ "rounds": {+ "mean": 2,+ "max": 2+ }+ },+ "runs": [+ {+ "pass": true,+ "intent": "simple",+ "skill": null,+ "areas": [+ "preview",+ "timeline",+ "inspector",+ "subtitles",+ "library",+ "side_panel",+ "top_bar",+ "editor"+ ],+ "declaredTools": 101,+ "routingMisses": [],+ "roundModel": "gemini-3.1-flash-lite",+ "notes": [],+ "instant": null,+ "qualityGate": [],+ "judgeNote": null,+ "trace": [+ {+ "name": "subtitles_generate",+ "round": 0,+ "atMs": 4963.909291999997,+ "execMs": 0.0043329999898560345,+ "args": {+ "track": 0+ }+ }+ ],+ "timings": {+ "gateMs": 417.5009999999893,+ "gateSkipped": false,+ "ttftMs": 6243.4855830000015,+ "modelMs": 5991.626040999952,+ "toolMs": 0.0043329999898560345,+ "totalMs": 6413.435708000034,+ "judgeMs": 347.80133299995214,+ "retryMs": 0,+ "retries": 0,+ "rounds": [+ {+ "roundMs": 4542.725457999972,+ "firstDeltaMs": null,+ "calls": [+ {+ "name": "subtitles_generate",+ "execMs": 0.0043329999898560345+ }+ ]+ },+ {+ "roundMs": 1448.9005829999805,+ "firstDeltaMs": 1279.0630830000155,+ "calls": []+ }+ ]+ }+ },+ {+ "pass": true,+ "intent": "simple",+ "skill": null,+ "areas": [+ "preview",+ "timeline",+ "inspector",+ "subtitles",+ "library",+ "side_panel",+ "top_bar",+ "editor"+ ],+ "declaredTools": 101,+ "routingMisses": [],+ "roundModel": "gemini-3.1-flash-lite",+ "notes": [],+ "instant": null,+ "qualityGate": [],+ "judgeNote": null,+ "trace": [+ {+ "name": "subtitles_generate",+ "round": 0,+ "atMs": 2575.7401669999817,+ "execMs": 0.01195800001733005,+ "args": {+ "track": 0+ }+ }+ ],+ "timings": {+ "gateMs": 306.6463329999824,+ "gateSkipped": false,+ "ttftMs": 3969.60708300001,+ "modelMs": 3920.3630839999532,+ "toolMs": 0.01195800001733005,+ "totalMs": 4228.688832999964,+ "judgeMs": 265.9667920000502,+ "retryMs": 0,+ "retries": 0,+ "rounds": [+ {+ "roundMs": 2268.197374999989,+ "firstDeltaMs": null,+ "calls": [+ {+ "name": "subtitles_generate",+ "execMs": 0.01195800001733005+ }+ ]+ },+ {+ "roundMs": 1652.1657089999644,+ "firstDeltaMs": 1393.1727090000059,+ "calls": []+ }+ ]+ }+ },+ {+ "pass": true,+ "intent": "simple",+ "skill": null,+ "areas": [+ "preview",+ "timeline",+ "inspector",+ "subtitles",+ "library",+ "side_panel",+ "top_bar",+ "editor"+ ],+ "declaredTools": 101,+ "routingMisses": [],+ "roundModel": "gemini-3.1-flash-lite",+ "notes": [],+ "instant": null,+ "qualityGate": [],+ "judgeNote": null,+ "trace": [+ {+ "name": "subtitles_generate",+ "round": 0,+ "atMs": 1629.4270000000251,+ "execMs": 0.0015830000047571957,+ "args": {+ "track": 0+ }+ }+ ],+ "timings": {+ "gateMs": 256.53483299998334,+ "gateSkipped": false,+ "ttftMs": 2729.1182499999995,+ "modelMs": 2600.701915999991,+ "toolMs": 0.0015830000047571957,+ "totalMs": 2860.4588330000406,+ "judgeMs": 286.3098750000354,+ "retryMs": 0,+ "retries": 0,+ "rounds": [+ {+ "roundMs": 1372.2659579999745,+ "firstDeltaMs": null,+ "calls": [+ {+ "name": "subtitles_generate",+ "execMs": 0.0015830000047571957+ }+ ]+ },+ {+ "roundMs": 1228.4359580000164,+ "firstDeltaMs": 1099.1026670000283,+ "calls": []+ }+ ]+ }+ }+ ]+ },+ {+ "name": "cartoon-from-audio-plans-scene",+ "bucket": "single-tool",+ "passRate": 1,+ "budgetBreaches": [],+ "latency": {+ "gateMs": {+ "p50": 288,+ "p95": 317,+ "mean": 292,+ "n": 3+ },+ "ttftMs": {+ "p50": 13719,+ "p95": 19715,+ "mean": 13323,+ "n": 3+ },+ "totalMs": {+ "p50": 14041,+ "p95": 19916,+ "mean": 13562,+ "n": 3+ },+ "modelMs": {+ "p50": 13762,+ "p95": 19622,+ "mean": 13264,+ "n": 3+ },+ "toolMs": {+ "p50": 0,+ "p95": 0,+ "mean": 0,+ "n": 3+ },+ "rounds": {+ "mean": 3.3,+ "max": 4+ }+ },+ "runs": [+ {+ "pass": true,+ "intent": "complex",+ "skill": "scene-productions",+ "areas": [+ "preview",+ "timeline",+ "inspector",+ "color",+ "removal",+ "elements",+ "effects",+ "animation",+ "transitions",+ "subtitles",+ "audio",+ "image_gen",+ "video_gen",+ "scene",+ "stock",+ "library",+ "side_panel",+ "top_bar",+ "editor"+ ],+ "declaredTools": 132,+ "routingMisses": [],+ "roundModel": "gemini-3.8-flash",+ "notes": [],+ "instant": null,+ "qualityGate": [],+ "judgeNote": null,+ "trace": [+ {+ "name": "listen_audio",+ "round": 0,+ "atMs": 7362.682417000004,+ "execMs": 0.03154200001154095,+ "args": {+ "asset_id": "a-au1"+ }+ },+ {+ "name": "note_source",+ "round": 1,+ "atMs": 9963.262541999982,+ "execMs": 0.005459000007249415,+ "args": {+ "asset_id": "a-au1",+ "notes": [+ {+ "text": "Narration describing a story to be visualized as animation",+ "to": 24,+ "from": 0+ }+ ]+ }+ },+ {+ "name": "generate_scene",+ "round": 2,+ "atMs": 12068.898042000015,+ "execMs": 0.049666999955661595,+ "args": {+ "style": "smooth 2D cartoon animation, fluid motion, clean vector outlines, flat shading",+ "from_audio_asset_id": "a-au1",+ "brief": "A smooth 2D cartoon bringing the narration to life with fluid animation, clean outlines, vibrant solid colors, and expressive character movement"+ }+ }+ ],+ "timings": {+ "gateMs": 270.3110829999787,+ "gateSkipped": false,+ "ttftMs": 13719.221250000002,+ "modelMs": 13762.489540000039,+ "toolMs": 0.08666799997445196,+ "totalMs": 14041.008374999976,+ "judgeMs": 396.9947909999755,+ "retryMs": 0,+ "retries": 0,+ "rounds": [+ {+ "roundMs": 7089.053083000006,+ "firstDeltaMs": null,+ "calls": [+ {+ "name": "listen_audio",+ "execMs": 0.03154200001154095+ }+ ]+ },+ {+ "roundMs": 2598.1457080000546,+ "firstDeltaMs": null,+ "calls": [+ {+ "name": "note_source",+ "execMs": 0.005459000007249415+ }+ ]+ },+ {+ "roundMs": 2104.328165999963,+ "firstDeltaMs": null,+ "calls": [+ {+ "name": "generate_scene",+ "execMs": 0.049666999955661595+ }+ ]+ },+ {+ "roundMs": 1970.962583000015,+ "firstDeltaMs": 1649.428292000026,+ "calls": []+ }+ ]+ }+ },+ {+ "pass": true,+ "intent": "complex",+ "skill": "scene-productions",+ "areas": [+ "preview",+ "timeline",+ "inspector",+ "color",+ "removal",+ "elements",+ "effects",+ "animation",+ "transitions",+ "subtitles",+ "audio",+ "image_gen",+ "video_gen",+ "scene",+ "stock",+ "library",+ "side_panel",+ "top_bar",+ "editor"+ ],+ "declaredTools": 132,+ "routingMisses": [],+ "roundModel": "gemini-3.8-flash",+ "notes": [],+ "instant": null,+ "qualityGate": [],+ "judgeNote": null,+ "trace": [+ {+ "name": "listen_audio",+ "round": 0,+ "atMs": 1913.8164589999942,+ "execMs": 0.01433299999916926,+ "args": {+ "asset_id": "a-au1"+ }+ },+ {+ "name": "note_source",+ "round": 1,+ "atMs": 4766.566959000018,+ "execMs": 0.012125000008381903,+ "args": {+ "asset_id": "a-au1",+ "notes": [+ {+ "from": 0,+ "text": "Narration audio track (24s) to be animated into a smooth 2D cartoon scene.",+ "to": 24+ }+ ]+ }+ },+ {+ "name": "generate_scene",+ "round": 1,+ "atMs": 4766.675334000029,+ "execMs": 0.001500000013038516,+ "args": {+ "from_audio_asset_id": "a-au1",+ "style": "smooth 2D cartoon animation, fluid movement, clean line art, vibrant flat colors",+ "brief": "A smooth, vibrant 2D animated cartoon illustrating the narration: clean bold outlines, expressive character animation, fluid motion, flat cel shading, rich colorful backgrounds."+ }+ }+ ],+ "timings": {+ "gateMs": 316.8707090000389,+ "gateSkipped": false,+ "ttftMs": 6533.403584000014,+ "modelMs": 6407.625498999958,+ "toolMs": 0.02795800002058968,+ "totalMs": 6728.721542000014,+ "judgeMs": 332.666790999996,+ "retryMs": 0,+ "retries": 0,+ "rounds": [+ {+ "roundMs": 1595.5531249999767,+ "firstDeltaMs": null,+ "calls": [+ {+ "name": "listen_audio",+ "execMs": 0.01433299999916926+ }+ ]+ },+ {+ "roundMs": 2851.052083000017,+ "firstDeltaMs": null,+ "calls": [+ {+ "name": "note_source",+ "execMs": 0.012125000008381903+ },+ {+ "name": "generate_scene",+ "execMs": 0.001500000013038516+ }+ ]+ },+ {+ "roundMs": 1961.0202909999643,+ "firstDeltaMs": 1766.0304159999941,+ "calls": []+ }+ ]+ }+ },+ {+ "pass": true,+ "intent": "complex",+ "skill": "scene-productions",+ "areas": [+ "preview",+ "timeline",+ "inspector",+ "color",+ "removal",+ "elements",+ "effects",+ "animation",+ "transitions",+ "subtitles",+ "audio",+ "image_gen",+ "video_gen",+ "scene",+ "stock",+ "library",+ "side_panel",+ "top_bar",+ "editor"+ ],+ "declaredTools": 132,+ "routingMisses": [],+ "roundModel": "gemini-3.8-flash",+ "notes": [],+ "instant": null,+ "qualityGate": [],+ "judgeNote": null,+ "trace": [+ {+ "name": "listen_audio",+ "round": 0,+ "atMs": 14462.90266599995,+ "execMs": 0.023000000044703484,+ "args": {+ "asset_id": "a-au1"+ }+ },+ {+ "name": "note_source",+ "round": 1,+ "atMs": 17471.089665999985,+ "execMs": 0.005708000040613115,+ "args": {+ "notes": [+ {+ "text": "A 24-second narration track.",+ "to": 24,+ "from": 0+ }+ ],+ "asset_id": "a-au1"+ }+ },+ {+ "name": "generate_scene",+ "round": 1,+ "atMs": 17471.221583000035,+ "execMs": 0.002250000019557774,+ "args": {+ "style": "smooth 2D cartoon animation, clean line art, vibrant flat colors, fluid motion",+ "from_audio_asset_id": "a-au1",+ "brief": "A smooth 2D animated cartoon illustrating the narration: clean hand-drawn line art, expressive cartoon characters, fluid character animation, vibrant flat colors."+ }+ }+ ],+ "timings": {+ "gateMs": 287.8705000000191,+ "gateSkipped": false,+ "ttftMs": 19714.876958000008,+ "modelMs": 19622.24733299995,+ "toolMs": 0.030958000104874372,+ "totalMs": 19915.61279100005,+ "judgeMs": 253.7644169999985,+ "retryMs": 0,+ "retries": 0,+ "rounds": [+ {+ "roundMs": 14172.487124999985,+ "firstDeltaMs": null,+ "calls": [+ {+ "name": "listen_audio",+ "execMs": 0.023000000044703484+ }+ ]+ },+ {+ "roundMs": 3006.621207999997,+ "firstDeltaMs": null,+ "calls": [+ {+ "name": "note_source",+ "execMs": 0.005708000040613115+ },+ {+ "name": "generate_scene",+ "execMs": 0.002250000019557774+ }+ ]+ },+ {+ "roundMs": 2443.1389999999665,+ "firstDeltaMs": 2242.7570839999244,+ "calls": []+ }+ ]+ }+ }+ ]+ },+ {+ "name": "cartoon-korean-audio-passes-language",+ "bucket": "single-tool",+ "passRate": 1,+ "budgetBreaches": [],+ "latency": {+ "gateMs": {+ "p50": 315,+ "p95": 358,+ "mean": 319,+ "n": 3+ },+ "ttftMs": {+ "p50": 18063,+ "p95": 18316,+ "mean": 17579,+ "n": 3+ },+ "totalMs": {+ "p50": 18291,+ "p95": 18618,+ "mean": 17856,+ "n": 3+ },+ "modelMs": {+ "p50": 18001,+ "p95": 18297,+ "mean": 17531,+ "n": 3+ },+ "toolMs": {+ "p50": 0,+ "p95": 0,+ "mean": 0,+ "n": 3+ },+ "rounds": {+ "mean": 4,+ "max": 4+ }+ },+ "runs": [+ {+ "pass": true,+ "intent": "complex",+ "skill": "scene-productions",+ "areas": [+ "preview",+ "timeline",+ "inspector",+ "removal",+ "elements",+ "effects",+ "animation",+ "transitions",+ "subtitles",+ "audio",+ "image_gen",+ "video_gen",+ "scene",+ "stock",+ "library",+ "side_panel",+ "top_bar",+ "editor"+ ],+ "declaredTools": 125,+ "routingMisses": [],+ "roundModel": "gemini-3.8-flash",+ "notes": [],+ "instant": null,+ "qualityGate": [],+ "judgeNote": null,+ "trace": [+ {+ "name": "listen_audio",+ "round": 0,+ "atMs": 9011.650041999994,+ "execMs": 0.004249999998137355,+ "args": {+ "asset_id": "a-au1"+ }+ },+ {+ "name": "get_state",+ "round": 1,+ "atMs": 12421.365082999924,+ "execMs": 0.027916999999433756,+ "args": {}+ },+ {+ "name": "generate_scene",+ "round": 2,+ "atMs": 16541.807792000007,+ "execMs": 0.2664579999400303,+ "args": {+ "style": "smooth 2D cartoon, fluid hand-drawn 2D animation, clean outlines, colorful vibrant palette",+ "from_audio_asset_id": "a-au1",+ "target_seconds": 24,+ "brief": "Smooth 2D cartoon animation illustrating the Korean narration with expressive characters, clean lines, vibrant palette, and fluid motion.",+ "audio_language": "ko-KR"+ }+ }+ ],+ "timings": {+ "gateMs": 314.77779199997894,+ "gateSkipped": false,+ "ttftMs": 18316.070624999935,+ "modelMs": 18297.32733499992,+ "toolMs": 0.2986249999376014,+ "totalMs": 18618.37150000001,+ "judgeMs": 251.4206669999985,+ "retryMs": 0,+ "retries": 0,+ "rounds": [+ {+ "roundMs": 8694.752458999981,+ "firstDeltaMs": null,+ "calls": [+ {+ "name": "listen_audio",+ "execMs": 0.004249999998137355+ }+ ]+ },+ {+ "roundMs": 3409.022666999954,+ "firstDeltaMs": null,+ "calls": [+ {+ "name": "get_state",+ "execMs": 0.027916999999433756+ }+ ]+ },+ {+ "roundMs": 4118.825084000011,+ "firstDeltaMs": null,+ "calls": [+ {+ "name": "generate_scene",+ "execMs": 0.2664579999400303+ }+ ]+ },+ {+ "roundMs": 2074.727124999976,+ "firstDeltaMs": 1772.658666000003,+ "calls": []+ }+ ]+ }+ },+ {+ "pass": true,+ "intent": "complex",+ "skill": "scene-productions",+ "areas": [+ "preview",+ "timeline",+ "inspector",+ "removal",+ "elements",+ "effects",+ "animation",+ "transitions",+ "subtitles",+ "audio",+ "image_gen",+ "video_gen",+ "scene",+ "stock",+ "library",+ "side_panel",+ "top_bar",+ "editor"+ ],+ "declaredTools": 125,+ "routingMisses": [],+ "roundModel": "gemini-3.8-flash",+ "notes": [],+ "instant": null,+ "qualityGate": [],+ "judgeNote": null,+ "trace": [+ {+ "name": "listen_audio",+ "round": 0,+ "atMs": 3800.8949579999316,+ "execMs": 0.010250000050291419,+ "args": {+ "asset_id": "a-au1"+ }+ },+ {+ "name": "get_state",+ "round": 1,+ "atMs": 6438.398333000019,+ "execMs": 0.010000000009313226,+ "args": {}+ },+ {+ "name": "generate_scene",+ "round": 2,+ "atMs": 14570.597667000024,+ "execMs": 0.009916999959386885,+ "args": {+ "from_audio_asset_id": "a-au1",+ "style": "smooth 2D cartoon animation, fluid motion, clean outlines, soft vibrant colors",+ "audio_language": "ko-KR"+ }+ }+ ],+ "timings": {+ "gateMs": 358.1557909999974,+ "gateSkipped": false,+ "ttftMs": 16357.016416999977,+ "modelMs": 16294.908041999792,+ "toolMs": 0.03016700001899153,+ "totalMs": 16658.72666699998,+ "judgeMs": 252.65341699996497,+ "retryMs": 0,+ "retries": 0,+ "rounds": [+ {+ "roundMs": 3441.4169999998994,+ "firstDeltaMs": null,+ "calls": [+ {+ "name": "listen_audio",+ "execMs": 0.010250000050291419+ }+ ]+ },+ {+ "roundMs": 2636.155541999964,+ "firstDeltaMs": null,+ "calls": [+ {+ "name": "get_state",+ "execMs": 0.010000000009313226+ }+ ]+ },+ {+ "roundMs": 8130.9032919999445,+ "firstDeltaMs": null,+ "calls": [+ {+ "name": "generate_scene",+ "execMs": 0.009916999959386885+ }+ ]+ },+ {+ "roundMs": 2086.432207999984,+ "firstDeltaMs": 1785.360042000073,+ "calls": []+ }+ ]+ }+ },+ {+ "pass": true,+ "intent": "complex",+ "skill": "scene-productions",+ "areas": [+ "preview",+ "timeline",+ "inspector",+ "removal",+ "elements",+ "effects",+ "animation",+ "transitions",+ "subtitles",+ "audio",+ "image_gen",+ "video_gen",+ "scene",+ "stock",+ "library",+ "side_panel",+ "top_bar",+ "editor"+ ],+ "declaredTools": 125,+ "routingMisses": [],+ "roundModel": "gemini-3.8-flash",+ "notes": [],+ "instant": null,+ "qualityGate": [],+ "judgeNote": null,+ "trace": [+ {+ "name": "listen_audio",+ "round": 0,+ "atMs": 4338.667917000013,+ "execMs": 0.05991599999833852,+ "args": {+ "asset_id": "a-au1"+ }+ },+ {+ "name": "note_source",+ "round": 1,+ "atMs": 9972.311083000037,+ "execMs": 0.022417000029236078,+ "args": {+ "notes": [+ {+ "text": "Korean narration describing an energetic dog's fun adventure playing outdoors at the park and on the beach.",+ "to": 24,+ "from": 0+ }+ ],+ "asset_id": "a-au1"+ }+ },+ {+ "name": "generate_scene",+ "round": 2,+ "atMs": 13614.331707999925,+ "execMs": 0.019582999986596406,+ "args": {+ "style": "smooth 2D cartoon, hand-drawn vector animation, clean linework, vibrant flat colors, fluid motion",+ "audio_language": "ko-KR",+ "brief": "A smooth 2D cartoon following a playful dog exploring the outdoors, running happily through a green park, and visiting a sunny beach.",+ "target_seconds": 24,+ "from_audio_asset_id": "a-au1"+ }+ }+ ],+ "timings": {+ "gateMs": 282.84612499992363,+ "gateSkipped": false,+ "ttftMs": 18063.01662499993,+ "modelMs": 18001.100376000046,+ "toolMs": 0.101916000014171,+ "totalMs": 18291.207166999928,+ "judgeMs": 207.9362919999985,+ "retryMs": 0,+ "retries": 0,+ "rounds": [+ {+ "roundMs": 4053.087749999948,+ "firstDeltaMs": null,+ "calls": [+ {+ "name": "listen_audio",+ "execMs": 0.05991599999833852+ }+ ]+ },+ {+ "roundMs": 5631.896917000064,+ "firstDeltaMs": null,+ "calls": [+ {+ "name": "note_source",+ "execMs": 0.022417000029236078+ }+ ]+ },+ {+ "roundMs": 3640.746749999933,+ "firstDeltaMs": null,+ "calls": [+ {+ "name": "generate_scene",+ "execMs": 0.019582999986596406+ }+ ]+ },+ {+ "roundMs": 4675.368959000101,+ "firstDeltaMs": 4447.385375000071,+ "calls": []+ }+ ]+ }+ }+ ]+ },+ {+ "name": "cartoon-style-reference-anchors-look",+ "bucket": "single-tool",+ "passRate": 1,+ "budgetBreaches": [],+ "latency": {+ "gateMs": {+ "p50": 220,+ "p95": 250,+ "mean": 227,+ "n": 3+ },+ "ttftMs": {+ "p50": 10236,+ "p95": 11751,+ "mean": 10207,+ "n": 3+ },+ "totalMs": {+ "p50": 10552,+ "p95": 11994,+ "mean": 10485,+ "n": 3+ },+ "modelMs": {+ "p50": 10333,+ "p95": 11737,+ "mean": 10251,+ "n": 3+ },+ "toolMs": {+ "p50": 0,+ "p95": 0,+ "mean": 0,+ "n": 3+ },+ "rounds": {+ "mean": 4,+ "max": 4+ }+ },+ "runs": [+ {+ "pass": true,+ "intent": "complex",+ "skill": "scene-productions",+ "areas": [+ "preview",+ "timeline",+ "inspector",+ "color",+ "removal",+ "elements",+ "effects",+ "animation",+ "transitions",+ "subtitles",+ "audio",+ "image_gen",+ "video_gen",+ "scene",+ "stock",+ "library",+ "side_panel",+ "top_bar",+ "editor"+ ],+ "declaredTools": 132,+ "routingMisses": [],+ "roundModel": "gemini-3.8-flash",+ "notes": [],+ "instant": null,+ "qualityGate": [],+ "judgeNote": null,+ "trace": [+ {+ "name": "listen_audio",+ "round": 0,+ "atMs": 2612.082959000021,+ "execMs": 0.006459000054746866,+ "args": {+ "asset_id": "a-au1"+ }+ },+ {+ "name": "note_source",+ "round": 1,+ "atMs": 5420.980916999979,+ "execMs": 0.005708000040613115,+ "args": {+ "notes": [+ {+ "text": "Narrator tells a story for a cartoon episode about a playful puppy visiting a sunny dog park, meeting furry friends, chasing a frisbee across the grass, and resting happily under a shade tree.",+ "to": 24,+ "from": 0+ }+ ],+ "asset_id": "a-au1"+ }+ },+ {+ "name": "generate_scene",+ "round": 2,+ "atMs": 8028.66412500001,+ "execMs": 0.14650000003166497,+ "args": {+ "style": "Vibrant cartoon illustration, colorful stylized 2D animation look matching the dog park reference image",+ "reference_asset_ids": [+ "a-i1"+ ],+ "brief": "A lively cartoon episode following a playful puppy visiting a vibrant, sunny dog park, making friends with other dogs, chasing a flying frisbee across lush green lawns, and resting contentedly under a shady tree.",+ "from_audio_asset_id": "a-au1"+ }+ }+ ],+ "timings": {+ "gateMs": 212.7123750000028,+ "gateSkipped": true,+ "ttftMs": 10236.009375000023,+ "modelMs": 10333.3265829999,+ "toolMs": 0.15866700012702495,+ "totalMs": 10552.049084000057,+ "judgeMs": 231.5101250000298,+ "retryMs": 0,+ "retries": 0,+ "rounds": [+ {+ "roundMs": 2397.277000000002,+ "firstDeltaMs": null,+ "calls": [+ {+ "name": "listen_audio",+ "execMs": 0.006459000054746866+ }+ ]+ },+ {+ "roundMs": 2808.089249999961,+ "firstDeltaMs": null,+ "calls": [+ {+ "name": "note_source",+ "execMs": 0.005708000040613115+ }+ ]+ },+ {+ "roundMs": 2606.533666000003,+ "firstDeltaMs": null,+ "calls": [+ {+ "name": "generate_scene",+ "execMs": 0.14650000003166497+ }+ ]+ },+ {+ "roundMs": 2521.4266669999342,+ "firstDeltaMs": 2205.639208999928,+ "calls": []+ }+ ]+ }+ },+ {+ "pass": true,+ "intent": "complex",+ "skill": "scene-productions",+ "areas": [+ "preview",+ "timeline",+ "inspector",+ "color",+ "removal",+ "elements",+ "effects",+ "animation",+ "transitions",+ "subtitles",+ "audio",+ "image_gen",+ "video_gen",+ "scene",+ "stock",+ "library",+ "side_panel",+ "top_bar",+ "editor"+ ],+ "declaredTools": 132,+ "routingMisses": [],+ "roundModel": "gemini-3.8-flash",+ "notes": [],+ "instant": null,+ "qualityGate": [],+ "judgeNote": null,+ "trace": [+ {+ "name": "listen_audio",+ "round": 0,+ "atMs": 2062.9541660000104,+ "execMs": 0.009625000064261258,+ "args": {+ "asset_id": "a-au1"+ }+ },+ {+ "name": "note_source",+ "round": 1,+ "atMs": 6914.006625000038,+ "execMs": 0.007375000044703484,+ "args": {+ "notes": [+ {+ "from": 0,+ "text": "Narration audio about a cartoon dog's adventure in the park.",+ "to": 24+ }+ ],+ "asset_id": "a-au1"+ }+ },+ {+ "name": "generate_scene",+ "round": 2,+ "atMs": 10026.779582999996,+ "execMs": 0.014375000027939677,+ "args": {+ "from_audio_asset_id": "a-au1",+ "style": "2D cartoon animation, vibrant playful colors, bold outlines, expressive character design",+ "reference_asset_ids": [+ "a-i1"+ ],+ "brief": "Cartoon episode following the narration about a dog's adventure in the park, featuring vibrant 2D animated styling, expressive canine character animation, and warm colorful park backgrounds matching the reference image."+ }+ }+ ],+ "timings": {+ "gateMs": 250.11012500000652,+ "gateSkipped": true,+ "ttftMs": 11751.02754099993,+ "modelMs": 11736.876000999939,+ "toolMs": 0.03137500013690442,+ "totalMs": 11994.302999999956,+ "judgeMs": 282.21175000001676,+ "retryMs": 0,+ "retries": 0,+ "rounds": [+ {+ "roundMs": 1810.9785420000553,+ "firstDeltaMs": null,+ "calls": [+ {+ "name": "listen_audio",+ "execMs": 0.009625000064261258+ }+ ]+ },+ {+ "roundMs": 4849.677416999941,+ "firstDeltaMs": null,+ "calls": [+ {+ "name": "note_source",+ "execMs": 0.007375000044703484+ }+ ]+ },+ {+ "roundMs": 3110.9392499999376,+ "firstDeltaMs": null,+ "calls": [+ {+ "name": "generate_scene",+ "execMs": 0.014375000027939677+ }+ ]+ },+ {+ "roundMs": 1965.280792000005,+ "firstDeltaMs": 1722.4753749999218,+ "calls": []+ }+ ]+ }+ },+ {+ "pass": true,+ "intent": "complex",+ "skill": "scene-productions",+ "areas": [+ "preview",+ "timeline",+ "inspector",+ "color",+ "removal",+ "elements",+ "effects",+ "animation",+ "transitions",+ "subtitles",+ "audio",+ "image_gen",+ "video_gen",+ "scene",+ "stock",+ "library",+ "side_panel",+ "top_bar",+ "editor"+ ],+ "declaredTools": 132,+ "routingMisses": [],+ "roundModel": "gemini-3.8-flash",+ "notes": [],+ "instant": null,+ "qualityGate": [],+ "judgeNote": null,+ "trace": [+ {+ "name": "listen_audio",+ "round": 0,+ "atMs": 2097.89612499997,+ "execMs": 0.023000000044703484,+ "args": {+ "asset_id": "a-au1"+ }+ },+ {+ "name": "note_source",+ "round": 1,+ "atMs": 4436.2976250000065,+ "execMs": 0.013500000000931323,+ "args": {+ "notes": [+ {+ "from": 0,+ "text": "Narration track for a cartoon episode about a playful dog enjoying a day at the dog park, running around, catching a frisbee, and playing with friends.",+ "to": 24+ }+ ],+ "asset_id": "a-au1"+ }+ },+ {+ "name": "generate_scene",+ "round": 2,+ "atMs": 6851.660166000016,+ "execMs": 0.010041999979875982,+ "args": {+ "brief": "A cartoon episode about a playful dog at a sunny dog park, running freely, catching a frisbee, and playing with other dogs. Style matches the colorful, whimsical 2D hand-drawn cartoon aesthetic of the reference image.",+ "reference_asset_ids": [+ "a-i1"+ ],+ "from_audio_asset_id": "a-au1",+ "style": "whimsical 2D hand-drawn cartoon illustration, vibrant cheerful colors, thick clean line art, charming storybook aesthetic"+ }+ }+ ],+ "timings": {+ "gateMs": 219.54387499997392,+ "gateSkipped": true,+ "ttftMs": 8635.100499999942,+ "modelMs": 8682.401375999907,+ "toolMs": 0.04654200002551079,+ "totalMs": 8909.428624999942,+ "judgeMs": 314.7087499999907,+ "retryMs": 0,+ "retries": 0,+ "rounds": [+ {+ "roundMs": 1875.6595840000082,+ "firstDeltaMs": null,+ "calls": [+ {+ "name": "listen_audio",+ "execMs": 0.023000000044703484+ }+ ]+ },+ {+ "roundMs": 2337.405124999932,+ "firstDeltaMs": null,+ "calls": [+ {+ "name": "note_source",+ "execMs": 0.013500000000931323+ }+ ]+ },+ {+ "roundMs": 2413.645917000016,+ "firstDeltaMs": null,+ "calls": [+ {+ "name": "generate_scene",+ "execMs": 0.010041999979875982+ }+ ]+ },+ {+ "roundMs": 2055.6907499999506,+ "firstDeltaMs": 1781.7861249999842,+ "calls": []+ }+ ]+ }+ }+ ]+ },+ {+ "name": "cartoon-question-stays-in-chat",+ "bucket": "chat",+ "passRate": 1,+ "budgetBreaches": [],+ "latency": {+ "gateMs": {+ "p50": 329,+ "p95": 363,+ "mean": 322,+ "n": 3+ },+ "ttftMs": {+ "p50": 2810,+ "p95": 7041,+ "mean": 3920,+ "n": 3+ },+ "totalMs": {+ "p50": 4482,+ "p95": 8339,+ "mean": 5270,+ "n": 3+ },+ "modelMs": {+ "p50": 3899,+ "p95": 7832,+ "mean": 4729,+ "n": 3+ },+ "toolMs": {+ "p50": 0,+ "p95": 0,+ "mean": 0,+ "n": 3+ },+ "rounds": {+ "mean": 1,+ "max": 1+ }+ },+ "runs": [+ {+ "pass": true,+ "intent": "complex",+ "skill": "scene-productions",+ "areas": [+ "preview",+ "timeline",+ "inspector",+ "removal",+ "elements",+ "effects",+ "animation",+ "transitions",+ "subtitles",+ "audio",+ "image_gen",+ "video_gen",+ "scene",+ "stock",+ "library",+ "side_panel",+ "top_bar"+ ],+ "declaredTools": 121,+ "routingMisses": [],+ "roundModel": "gemini-3.8-flash",+ "notes": [],+ "instant": null,+ "qualityGate": [],+ "judgeNote": "long 1.6",+ "trace": [],+ "timings": {+ "gateMs": 273.95699999993667,+ "gateSkipped": false,+ "ttftMs": 7041.193749999977,+ "modelMs": 7832.378540999955,+ "toolMs": 0,+ "totalMs": 8339.371541999979,+ "judgeMs": 258.5448750000214,+ "retryMs": 0,+ "retries": 0,+ "rounds": [+ {+ "roundMs": 7832.378540999955,+ "firstDeltaMs": 6765.902583000017,+ "calls": []+ }+ ]+ }+ },+ {+ "pass": true,+ "intent": "complex",+ "skill": "scene-productions",+ "areas": [+ "preview",+ "timeline",+ "inspector",+ "removal",+ "elements",+ "effects",+ "animation",+ "transitions",+ "subtitles",+ "audio",+ "image_gen",+ "video_gen",+ "scene",+ "stock",+ "library",+ "side_panel",+ "top_bar",+ "editor"+ ],+ "declaredTools": 125,+ "routingMisses": [],+ "roundModel": "gemini-3.8-flash",+ "notes": [],+ "instant": null,+ "qualityGate": [],+ "judgeNote": "concise factual 0.39; long 2.0",+ "trace": [],+ "timings": {+ "gateMs": 362.56400000001304,+ "gateSkipped": false,+ "ttftMs": 2810.4324999999953,+ "modelMs": 3898.9005840000464,+ "toolMs": 0,+ "totalMs": 4481.982583999983,+ "judgeMs": 239.52262500009965,+ "retryMs": 0,+ "retries": 0,+ "rounds": [+ {+ "roundMs": 3898.9005840000464,+ "firstDeltaMs": 2446.904542000033,+ "calls": []+ }+ ]+ }+ },+ {+ "pass": true,+ "intent": "complex",+ "skill": "scene-productions",+ "areas": [+ "preview",+ "timeline",+ "inspector",+ "removal",+ "elements",+ "effects",+ "animation",+ "transitions",+ "subtitles",+ "audio",+ "image_gen",+ "video_gen",+ "scene",+ "stock",+ "library",+ "side_panel",+ "top_bar",+ "editor"+ ],+ "declaredTools": 125,+ "routingMisses": [],+ "roundModel": "gemini-3.8-flash",+ "notes": [],+ "instant": null,+ "qualityGate": [],+ "judgeNote": "long 1.6",+ "trace": [],+ "timings": {+ "gateMs": 329.076166999992,+ "gateSkipped": false,+ "ttftMs": 1907.3634169999277,+ "modelMs": 2455.725833000033,+ "toolMs": 0,+ "totalMs": 2989.9816249998985,+ "judgeMs": 203.20095899992157,+ "retryMs": 0,+ "retries": 0,+ "rounds": [+ {+ "roundMs": 2455.725833000033,+ "firstDeltaMs": 1577.076500000083,+ "calls": []+ }+ ]+ }+ }+ ]+ },+ {+ "name": "clip-mentions-redo-their-shots",+ "bucket": "multi-tool",+ "passRate": 1,+ "budgetBreaches": [],+ "latency": {+ "gateMs": {+ "p50": 259,+ "p95": 322,+ "mean": 272,+ "n": 3+ },+ "ttftMs": {+ "p50": 18104,+ "p95": 23095,+ "mean": 19169,+ "n": 3+ },+ "totalMs": {+ "p50": 18543,+ "p95": 23294,+ "mean": 19494,+ "n": 3+ },+ "modelMs": {+ "p50": 18296,+ "p95": 22964,+ "mean": 19213,+ "n": 3+ },+ "toolMs": {+ "p50": 0,+ "p95": 1,+ "mean": 0,+ "n": 3+ },+ "rounds": {+ "mean": 6,+ "max": 7+ }+ },+ "runs": [+ {+ "pass": true,+ "intent": "complex",+ "skill": "audio-and-subtitles",+ "areas": [+ "preview",+ "timeline",+ "inspector",+ "effects",+ "transitions",+ "subtitles",+ "audio",+ "video_gen",+ "scene",+ "stock",+ "library",+ "side_panel",+ "top_bar",+ "editor"+ ],+ "declaredTools": 116,+ "routingMisses": [],+ "roundModel": "gemini-3.8-flash",+ "notes": [],+ "instant": null,+ "qualityGate": [],+ "judgeNote": null,+ "trace": [+ {+ "name": "listen_audio",+ "round": 0,+ "atMs": 6771.978583000018,+ "execMs": 1.0475420000730082,+ "args": {+ "to": 9,+ "asset_id": "a-au1",+ "from": 0+ }+ },+ {+ "name": "watch_video",+ "round": 1,+ "atMs": 9040.511874999967,+ "execMs": 0.007959000067785382,+ "args": {+ "clip_id": "sc-1"+ }+ },+ {+ "name": "watch_video",+ "round": 1,+ "atMs": 9040.628874999937,+ "execMs": 0.0012080000014975667,+ "args": {+ "clip_id": "sc-2"+ }+ },+ {+ "name": "note_source",+ "round": 2,+ "atMs": 11727.347833000007,+ "execMs": 0.010500000091269612,+ "args": {+ "asset_id": "a-au1",+ "notes": [+ {+ "text": "Narration audio for the project.",+ "from": 0,+ "to": 9+ }+ ]+ }+ },+ {+ "name": "note_source",+ "round": 3,+ "atMs": 13839.683874999988,+ "execMs": 0.006959000020287931,+ "args": {+ "notes": [+ {+ "to": 3,+ "from": 0,+ "text": "Shot 1 footage currently placed in sc-1."+ }+ ],+ "asset_id": "t-1"+ }+ },+ {+ "name": "note_source",+ "round": 3,+ "atMs": 13839.764957999927,+ "execMs": 0.0011249999515712261,+ "args": {+ "asset_id": "t-2",+ "notes": [+ {+ "from": 0,+ "text": "Shot 2 footage currently placed in sc-2.",+ "to": 3+ }+ ]+ }+ },+ {+ "name": "regenerate_shot",+ "round": 4,+ "atMs": 16099.686791999964,+ "execMs": 0.006374999997206032,+ "args": {+ "note": "Differentiate visual composition from shot 2 to better match the narration audio",+ "n": 1+ }+ },+ {+ "name": "regenerate_shot",+ "round": 4,+ "atMs": 16099.785291999928,+ "execMs": 0.0015839999541640282,+ "args": {+ "n": 2,+ "note": "Create a contrasting shot distinct from shot 1 aligned with the narration audio"+ }+ }+ ],+ "timings": {+ "gateMs": 235.3153750000056,+ "gateSkipped": true,+ "ttftMs": 18104.01658299996,+ "modelMs": 18295.742456999957,+ "toolMs": 1.08325200015679,+ "totalMs": 18543.282957999967,+ "judgeMs": 311.52329200005624,+ "retryMs": 0,+ "retries": 0,+ "rounds": [+ {+ "roundMs": 6534.10491600004,+ "firstDeltaMs": null,+ "calls": [+ {+ "name": "listen_audio",+ "execMs": 1.0475420000730082+ }+ ]+ },+ {+ "roundMs": 2263.647916999995,+ "firstDeltaMs": null,+ "calls": [+ {+ "name": "watch_video",+ "execMs": 0.007959000067785382+ },+ {+ "name": "watch_video",+ "execMs": 0.0012080000014975667+ }+ ]+ },+ {+ "roundMs": 2685.8785830000415,+ "firstDeltaMs": null,+ "calls": [+ {+ "name": "note_source",+ "execMs": 0.010500000091269612+ }+ ]+ },+ {+ "roundMs": 2111.5064579999307,+ "firstDeltaMs": null,+ "calls": [+ {+ "name": "note_source",+ "execMs": 0.006959000020287931+ },+ {+ "name": "note_source",+ "execMs": 0.0011249999515712261+ }+ ]+ },+ {+ "roundMs": 2258.3414999999804,+ "firstDeltaMs": null,+ "calls": [+ {+ "name": "regenerate_shot",+ "execMs": 0.006374999997206032+ },+ {+ "name": "regenerate_shot",+ "execMs": 0.0015839999541640282+ }+ ]+ },+ {+ "roundMs": 2442.263082999969,+ "firstDeltaMs": 2003.2772910000058,+ "calls": []+ }+ ]+ }+ },+ {+ "pass": true,+ "intent": "complex",+ "skill": "audio-and-subtitles",+ "areas": [+ "preview",+ "timeline",+ "inspector",+ "transitions",+ "subtitles",+ "audio",+ "video_gen",+ "scene",+ "stock",+ "library",+ "side_panel",+ "top_bar",+ "editor"+ ],+ "declaredTools": 115,+ "routingMisses": [],+ "roundModel": "gemini-3.8-flash",+ "notes": [],+ "instant": null,+ "qualityGate": [],+ "judgeNote": null,+ "trace": [+ {+ "name": "listen_audio",+ "round": 0,+ "atMs": 6433.507417000015,+ "execMs": 0.084874999942258,+ "args": {+ "asset_id": "a-au1",+ "to": 7,+ "from": 0+ }+ },+ {+ "name": "watch_video",+ "round": 0,+ "atMs": 6433.739917000057,+ "execMs": 0.004540999885648489,+ "args": {+ "clip_id": "sc-1"+ }+ },+ {+ "name": "watch_video",+ "round": 0,+ "atMs": 6433.803874999983,+ "execMs": 0.0028750000055879354,+ "args": {+ "clip_id": "sc-2"+ }+ },+ {+ "name": "note_source",+ "round": 1,+ "atMs": 9301.335375000024,+ "execMs": 0.007916999980807304,+ "args": {+ "notes": [+ {+ "to": 7,+ "from": 0,+ "text": "Audio narration track: spoken narration corresponding to the video shots."+ }+ ],+ "asset_id": "a-au1"+ }+ },+ {+ "name": "note_source",+ "round": 1,+ "atMs": 9301.41399999999,+ "execMs": 0.009084000019356608,+ "args": {+ "asset_id": "t-1",+ "notes": [+ {+ "to": 3,+ "from": 0,+ "text": "Generated shot 1 take footage."+ }+ ]+ }+ },+ {+ "name": "note_source",+ "round": 1,+ "atMs": 9301.453500000061,+ "execMs": 0.0005830000154674053,+ "args": {+ "asset_id": "t-2",+ "notes": [+ {+ "to": 3,+ "from": 0,+ "text": "Generated shot 2 take footage."+ }+ ]+ }+ },+ {+ "name": "regenerate_shot",+ "round": 2,+ "atMs": 11279.128083000076,+ "execMs": 0.009542000014334917,+ "args": {+ "n": 1,+ "note": "Differentiate from shot 2 and match the opening audio narration"+ }+ },+ {+ "name": "regenerate_shot",+ "round": 3,+ "atMs": 13113.694000000018,+ "execMs": 0.004249999998137355,+ "args": {+ "n": 2,+ "note": "Match the audio narration from second 3 to 6 and contrast clearly with shot 1"+ }+ }+ ],+ "timings": {+ "gateMs": 259.1030000000028,+ "gateSkipped": true,+ "ttftMs": 16306.932333000004,+ "modelMs": 16378.79429300013,+ "toolMs": 0.12366699986159801,+ "totalMs": 16643.60079200007,+ "judgeMs": 305.4105409999611,+ "retryMs": 0,+ "retries": 0,+ "rounds": [+ {+ "roundMs": 6172.752625000081,+ "firstDeltaMs": null,+ "calls": [+ {+ "name": "listen_audio",+ "execMs": 0.084874999942258+ },+ {+ "name": "watch_video",+ "execMs": 0.004540999885648489+ },+ {+ "name": "watch_video",+ "execMs": 0.0028750000055879354+ }+ ]+ },+ {+ "roundMs": 2866.306709000026,+ "firstDeltaMs": null,+ "calls": [+ {+ "name": "note_source",+ "execMs": 0.007916999980807304+ },+ {+ "name": "note_source",+ "execMs": 0.009084000019356608+ },+ {+ "name": "note_source",+ "execMs": 0.0005830000154674053+ }+ ]+ },+ {+ "roundMs": 1976.9020419999724,+ "firstDeltaMs": null,+ "calls": [+ {+ "name": "regenerate_shot",+ "execMs": 0.009542000014334917+ }+ ]+ },+ {+ "roundMs": 1833.6816670000553,+ "firstDeltaMs": null,+ "calls": [+ {+ "name": "regenerate_shot",+ "execMs": 0.004249999998137355+ }+ ]+ },+ {+ "roundMs": 3529.1512499999953,+ "firstDeltaMs": 3192.6798329999438,+ "calls": []+ }+ ]+ }+ },+ {+ "pass": true,+ "intent": "complex",+ "skill": "audio-and-subtitles",+ "areas": [+ "preview",+ "timeline",+ "inspector",+ "transitions",+ "subtitles",+ "audio",+ "video_gen",+ "scene",+ "stock",+ "library",+ "side_panel",+ "editor"+ ],+ "declaredTools": 111,+ "routingMisses": [],+ "roundModel": "gemini-3.8-flash",+ "notes": [],+ "instant": null,+ "qualityGate": [],+ "judgeNote": null,+ "trace": [+ {+ "name": "listen_audio",+ "round": 0,+ "atMs": 6508.911167000071,+ "execMs": 0.008749999920837581,+ "args": {+ "asset_id": "a-au1",+ "from": 0,+ "to": 9+ }+ },+ {+ "name": "watch_video",+ "round": 1,+ "atMs": 9235.296500000055,+ "execMs": 0.01345900003798306,+ "args": {+ "detail": "scan",+ "asset_id": "t-1"+ }+ },+ {+ "name": "note_source",+ "round": 2,+ "atMs": 11480.35520900006,+ "execMs": 0.006749999942258,+ "args": {+ "notes": [+ {+ "from": 0,+ "text": "Shot 1 footage",+ "to": 10+ }+ ],+ "asset_id": "t-1"+ }+ },+ {+ "name": "watch_video",+ "round": 3,+ "atMs": 13474.911500000046,+ "execMs": 0.006374999997206032,+ "args": {+ "detail": "scan",+ "asset_id": "t-2"+ }+ },+ {+ "name": "note_source",+ "round": 4,+ "atMs": 15193.942459000042,+ "execMs": 0.019749999977648258,+ "args": {+ "asset_id": "t-2",+ "notes": [+ {+ "to": 10,+ "from": 0,+ "text": "Shot 2 footage"+ }+ ]+ }+ },+ {+ "name": "regenerate_shot",+ "round": 5,+ "atMs": 19800.33612500003,+ "execMs": 0.008958999998867512,+ "args": {+ "n": 1,+ "note": "Make the scene match the opening narration and distinctly differ from shot 2"+ }+ },+ {+ "name": "regenerate_shot",+ "round": 5,+ "atMs": 19800.522750000004,+ "execMs": 0.002250000019557774,+ "args": {+ "note": "Make the scene match the second part of narration with fresh action and composition distinct from shot 1",+ "n": 2+ }+ }+ ],+ "timings": {+ "gateMs": 321.6334580000257,+ "gateSkipped": true,+ "ttftMs": 23095.11937500001,+ "modelMs": 22963.914833000163,+ "toolMs": 0.06629299989435822,+ "totalMs": 23294.259416999994,+ "judgeMs": 325.9206249999115,+ "retryMs": 0,+ "retries": 0,+ "rounds": [+ {+ "roundMs": 6185.745791999972,+ "firstDeltaMs": null,+ "calls": [+ {+ "name": "listen_audio",+ "execMs": 0.008749999920837581+ }+ ]+ },+ {+ "roundMs": 2725.584125000052,+ "firstDeltaMs": null,+ "calls": [+ {+ "name": "watch_video",+ "execMs": 0.01345900003798306+ }+ ]+ },+ {+ "roundMs": 2243.3027500000317,+ "firstDeltaMs": null,+ "calls": [+ {+ "name": "note_source",+ "execMs": 0.006749999942258+ }+ ]+ },+ {+ "roundMs": 1993.499582999968,+ "firstDeltaMs": null,+ "calls": [+ {+ "name": "watch_video",+ "execMs": 0.006374999997206032+ }+ ]+ },+ {+ "roundMs": 1718.3457090000156,+ "firstDeltaMs": null,+ "calls": [+ {+ "name": "note_source",+ "execMs": 0.019749999977648258+ }+ ]+ },+ {+ "roundMs": 4604.92291600001,+ "firstDeltaMs": null,+ "calls": [+ {+ "name": "regenerate_shot",+ "execMs": 0.008958999998867512+ },+ {+ "name": "regenerate_shot",+ "execMs": 0.002250000019557774+ }+ ]+ },+ {+ "roundMs": 3492.5139580001123,+ "firstDeltaMs": 3293.5729580000043,+ "calls": []+ }+ ]+ }+ }+ ]+ },+ {+ "name": "parked-debris-cleanup-after-retime",+ "bucket": "multi-tool",+ "passRate": 1,+ "budgetBreaches": [],+ "latency": {+ "gateMs": {+ "p50": 310,+ "p95": 330,+ "mean": 313,+ "n": 3+ },+ "ttftMs": {+ "p50": 3907,+ "p95": 7150,+ "mean": 4920,+ "n": 3+ },+ "totalMs": {+ "p50": 4190,+ "p95": 7337,+ "mean": 5133,+ "n": 3+ },+ "modelMs": {+ "p50": 3858,+ "p95": 7022,+ "mean": 4816,+ "n": 3+ },+ "toolMs": {+ "p50": 0,+ "p95": 0,+ "mean": 0,+ "n": 3+ },+ "rounds": {+ "mean": 3,+ "max": 3+ }+ },+ "runs": [+ {+ "pass": true,+ "intent": "simple",+ "skill": null,+ "areas": [+ "preview",+ "timeline",+ "inspector",+ "effects",+ "editor"+ ],+ "declaredTools": 71,+ "routingMisses": [],+ "roundModel": "gemini-3.1-flash-lite",+ "notes": [],+ "instant": null,+ "qualityGate": [],+ "judgeNote": null,+ "trace": [+ {+ "name": "set_speed",+ "round": 0,+ "atMs": 4834.244665999897,+ "execMs": 0.0744999999878928,+ "args": {+ "speed": 2,+ "clipId": "c2"+ }+ },+ {+ "name": "set_transition",+ "round": 1,+ "atMs": 6222.863916000002,+ "execMs": 0.007166999974288046,+ "args": {+ "style": "crosszoom",+ "clipId": "c2",+ "seconds": 1+ }+ }+ ],+ "timings": {+ "gateMs": 310.1376249999739,+ "gateSkipped": false,+ "ttftMs": 7150.197415999952,+ "modelMs": 7021.506873999955,+ "toolMs": 0.08166699996218085,+ "totalMs": 7336.698707999894,+ "judgeMs": 298.00458399998024,+ "retryMs": 0,+ "retries": 0,+ "rounds": [+ {+ "roundMs": 4521.468583000009,+ "firstDeltaMs": null,+ "calls": [+ {+ "name": "set_speed",+ "execMs": 0.0744999999878928+ }+ ]+ },+ {+ "roundMs": 1387.44070799998,+ "firstDeltaMs": null,+ "calls": [+ {+ "name": "set_transition",+ "execMs": 0.007166999974288046+ }+ ]+ },+ {+ "roundMs": 1112.597582999966,+ "firstDeltaMs": 926.2512499999721,+ "calls": []+ }+ ]+ }+ },+ {+ "pass": true,+ "intent": "simple",+ "skill": null,+ "areas": [+ "preview",+ "timeline",+ "inspector",+ "effects",+ "editor"+ ],+ "declaredTools": 71,+ "routingMisses": [],+ "roundModel": "gemini-3.1-flash-lite",+ "notes": [],+ "instant": null,+ "qualityGate": [],+ "judgeNote": null,+ "trace": [+ {+ "name": "set_speed",+ "round": 0,+ "atMs": 1573.5160419999156,+ "execMs": 0.0040840000146999955,+ "args": {+ "clipId": "c2",+ "speed": 2+ }+ },+ {+ "name": "remove_transition",+ "round": 1,+ "atMs": 2623.170334000024,+ "execMs": 0.00729099998716265,+ "args": {+ "transitionId": "tr-2"+ }+ }+ ],+ "timings": {+ "gateMs": 299.3481250000186,+ "gateSkipped": false,+ "ttftMs": 3701.282125000027,+ "modelMs": 3568.832208000007,+ "toolMs": 0.011375000001862645,+ "totalMs": 3873.2035419999156,+ "judgeMs": 320.6592500000261,+ "retryMs": 0,+ "retries": 0,+ "rounds": [+ {+ "roundMs": 1272.8748749999795,+ "firstDeltaMs": null,+ "calls": [+ {+ "name": "set_speed",+ "execMs": 0.0040840000146999955+ }+ ]+ },+ {+ "roundMs": 1047.9654580000788,+ "firstDeltaMs": null,+ "calls": [+ {+ "name": "remove_transition",+ "execMs": 0.00729099998716265+ }+ ]+ },+ {+ "roundMs": 1247.9918749999488,+ "firstDeltaMs": 1076.6612089999253,+ "calls": []+ }+ ]+ }+ },+ {+ "pass": true,+ "intent": "simple",+ "skill": null,+ "areas": [+ "preview",+ "timeline",+ "inspector",+ "effects",+ "editor"+ ],+ "declaredTools": 71,+ "routingMisses": [],+ "roundModel": "gemini-3.1-flash-lite",+ "notes": [],+ "instant": null,+ "qualityGate": [],+ "judgeNote": null,+ "trace": [+ {+ "name": "set_speed",+ "round": 0,+ "atMs": 1622.1324579999782,+ "execMs": 0.0058750000316649675,+ "args": {+ "clipId": "c2",+ "speed": 2+ }+ },+ {+ "name": "remove_transition",+ "round": 1,+ "atMs": 2935.9930409999797,+ "execMs": 0.004165999940596521,+ "args": {+ "transitionId": "tr-2"+ }+ }+ ],+ "timings": {+ "gateMs": 330.10820799996145,+ "gateSkipped": false,+ "ttftMs": 3907.240165999974,+ "modelMs": 3857.7134589999914,+ "toolMs": 0.010040999972261488,+ "totalMs": 4190.35470799997,+ "judgeMs": 323.0179169999901,+ "retryMs": 0,+ "retries": 0,+ "rounds": [+ {+ "roundMs": 1290.936958999955,+ "firstDeltaMs": null,+ "calls": [+ {+ "name": "set_speed",+ "execMs": 0.0058750000316649675+ }+ ]+ },+ {+ "roundMs": 1313.184709000052,+ "firstDeltaMs": null,+ "calls": [+ {+ "name": "remove_transition",+ "execMs": 0.004165999940596521+ }+ ]+ },+ {+ "roundMs": 1253.5917909999844,+ "firstDeltaMs": 970.6840830000583,+ "calls": []+ }+ ]+ }+ }+ ]+ },+ {+ "name": "speed-ramp-from-description",+ "bucket": "single-tool",+ "passRate": 1,+ "budgetBreaches": [],+ "latency": {+ "gateMs": {+ "p50": 340,+ "p95": 448,+ "mean": 374,+ "n": 3+ },+ "ttftMs": {+ "p50": 10713,+ "p95": 38183,+ "mean": 18777,+ "n": 3+ },+ "totalMs": {+ "p50": 10886,+ "p95": 38382,+ "mean": 18959,+ "n": 3+ },+ "modelMs": {+ "p50": 10427,+ "p95": 38007,+ "mean": 18567,+ "n": 3+ },+ "toolMs": {+ "p50": 0,+ "p95": 0,+ "mean": 0,+ "n": 3+ },+ "rounds": {+ "mean": 13.7,+ "max": 27+ }+ },+ "runs": [+ {+ "pass": true,+ "intent": "simple",+ "skill": null,+ "areas": [+ "preview",+ "timeline",+ "inspector",+ "effects",+ "transitions",+ "editor"+ ],+ "declaredTools": 71,+ "routingMisses": [],+ "roundModel": "gemini-3.1-flash-lite",+ "notes": [],+ "instant": null,+ "qualityGate": [],+ "judgeNote": null,+ "trace": [+ {+ "name": "set_speed_curve",+ "round": 0,+ "atMs": 1907.2352080000564,+ "execMs": 0.02841699996497482,+ "args": {+ "smooth": true,+ "clipId": "c2",+ "nodes": [+ {+ "at": 0,+ "speed": 1+ },+ {+ "speed": 0.3,+ "at": 3.7+ }+ ]+ }+ },+ {+ "name": "list_skills",+ "round": 1,+ "atMs": 3208.395332999993,+ "execMs": 0.03429199999663979,+ "args": {}+ },+ {+ "name": "get_state",+ "round": 2,+ "atMs": 4262.4094160000095,+ "execMs": 0.023916999925859272,+ "args": {}+ },+ {+ "name": "set_speed_curve",+ "round": 3,+ "atMs": 5566.878458000021,+ "execMs": 0.002374999923631549,+ "args": {+ "nodes": [+ {+ "speed": 1,+ "at": 0+ },+ {+ "speed": 0.3,+ "at": 3.5+ }+ ],+ "clipId": "c2",+ "smooth": true+ }+ },+ {+ "name": "set_speed_curve",+ "round": 4,+ "atMs": 6800.936416000011,+ "execMs": 0.0024579999735578895,+ "args": {+ "nodes": [+ {+ "speed": 1,+ "at": 0+ },+ {+ "at": 3.5,+ "speed": 0.3+ }+ ],+ "clipId": "c2",+ "smooth": true+ }+ },+ {+ "name": "set_speed_curve",+ "round": 5,+ "atMs": 8277.770541000064,+ "execMs": 0.004874999984167516,+ "args": {+ "clipId": "c2",+ "nodes": [+ {+ "at": 0,+ "speed": 1+ },+ {+ "speed": 0.3,+ "at": 3.5+ }+ ]+ }+ },+ {+ "name": "set_speed_curve",+ "round": 6,+ "atMs": 9371.066165999975,+ "execMs": 0.003499999991618097,+ "args": {+ "nodes": [+ {+ "at": 0,+ "speed": 1+ },+ {+ "at": 3.5,+ "speed": 0.3+ }+ ],+ "clipId": "c2",+ "smooth": true+ }+ }+ ],+ "timings": {+ "gateMs": 447.6125839999877,+ "gateSkipped": false,+ "ttftMs": 10712.897915999987,+ "modelMs": 10426.759750999976,+ "toolMs": 0.09983399976044893,+ "totalMs": 10885.737208000035,+ "judgeMs": 233.90895900002215,+ "retryMs": 0,+ "retries": 0,+ "rounds": [+ {+ "roundMs": 1455.907707999926,+ "firstDeltaMs": null,+ "calls": [+ {+ "name": "set_speed_curve",+ "execMs": 0.02841699996497482+ }+ ]+ },+ {+ "roundMs": 1300.0084590000333,+ "firstDeltaMs": null,+ "calls": [+ {+ "name": "list_skills",+ "execMs": 0.03429199999663979+ }+ ]+ },+ {+ "roundMs": 1052.9886670000851,+ "firstDeltaMs": null,+ "calls": [+ {+ "name": "get_state",+ "execMs": 0.023916999925859272+ }+ ]+ },+ {+ "roundMs": 1303.1813329999568,+ "firstDeltaMs": null,+ "calls": [+ {+ "name": "set_speed_curve",+ "execMs": 0.002374999923631549+ }+ ]+ },+ {+ "roundMs": 1233.3818749999627,+ "firstDeltaMs": null,+ "calls": [+ {+ "name": "set_speed_curve",+ "execMs": 0.0024579999735578895+ }+ ]+ },+ {+ "roundMs": 1476.0065000000177,+ "firstDeltaMs": null,+ "calls": [+ {+ "name": "set_speed_curve",+ "execMs": 0.004874999984167516+ }+ ]+ },+ {+ "roundMs": 1091.9814999999944,+ "firstDeltaMs": null,+ "calls": [+ {+ "name": "set_speed_curve",+ "execMs": 0.003499999991618097+ }+ ]+ },+ {+ "roundMs": 1513.3037089999998,+ "firstDeltaMs": 1341.003667000099,+ "calls": []+ }+ ]+ }+ },+ {+ "pass": true,+ "intent": "simple",+ "skill": null,+ "areas": [+ "preview",+ "timeline",+ "inspector",+ "effects",+ "transitions",+ "editor"+ ],+ "declaredTools": 71,+ "routingMisses": [],+ "roundModel": "gemini-3.1-flash-lite",+ "notes": [],+ "instant": null,+ "qualityGate": [],+ "judgeNote": null,+ "trace": [+ {+ "name": "set_speed_curve",+ "round": 0,+ "atMs": 1665.4296660000691,+ "execMs": 0.00704199995379895,+ "args": {+ "clipId": "c2",+ "preset": "rampOut"+ }+ },+ {+ "name": "get_state",+ "round": 1,+ "atMs": 2826.738291000016,+ "execMs": 0.04937500006053597,+ "args": {}+ },+ {+ "name": "set_speed_curve",+ "round": 2,+ "atMs": 4024.670207999996,+ "execMs": 0.007542000035755336,+ "args": {+ "clipId": "c2",+ "smooth": true,+ "nodes": [+ {+ "at": 0,+ "speed": 1+ },+ {+ "at": 3,+ "speed": 1+ },+ {+ "speed": 0.4,+ "at": 4.7+ }+ ]+ }+ },+ {+ "name": "set_speed_curve",+ "round": 3,+ "atMs": 5223.467833000002,+ "execMs": 0.0047079999931156635,+ "args": {+ "clipId": "c2",+ "smooth": true,+ "nodes": [+ {+ "at": 0,+ "speed": 1+ },+ {+ "at": 3.5,+ "speed": 1+ },+ {+ "speed": 0.3,+ "at": 4.7+ }+ ]+ }+ },+ {+ "name": "set_speed_curve",+ "round": 4,+ "atMs": 6540.693708000006,+ "execMs": 0.0039579999865964055,+ "args": {+ "nodes": [+ {+ "speed": 1,+ "at": 0+ },+ {+ "at": 3.5,+ "speed": 1+ },+ {+ "at": 4.7,+ "speed": 0.3+ }+ ],+ "clipId": "c2",+ "smooth": true+ }+ }+ ],+ "timings": {+ "gateMs": 333.498041999992,+ "gateSkipped": false,+ "ttftMs": 7433.934208000079,+ "modelMs": 7265.878542000195,+ "toolMs": 0.07262500002980232,+ "totalMs": 7608.296208000043,+ "judgeMs": 254.47412500006612,+ "retryMs": 0,+ "retries": 0,+ "rounds": [+ {+ "roundMs": 1330.798708000104,+ "firstDeltaMs": null,+ "calls": [+ {+ "name": "set_speed_curve",+ "execMs": 0.00704199995379895+ }+ ]+ },+ {+ "roundMs": 1159.9662920000264,+ "firstDeltaMs": null,+ "calls": [+ {+ "name": "get_state",+ "execMs": 0.04937500006053597+ }+ ]+ },+ {+ "roundMs": 1195.3122080001049,+ "firstDeltaMs": null,+ "calls": [+ {+ "name": "set_speed_curve",+ "execMs": 0.007542000035755336+ }+ ]+ },+ {+ "roundMs": 1197.1209579999559,+ "firstDeltaMs": null,+ "calls": [+ {+ "name": "set_speed_curve",+ "execMs": 0.0047079999931156635+ }+ ]+ },+ {+ "roundMs": 1316.0827920000302,+ "firstDeltaMs": null,+ "calls": [+ {+ "name": "set_speed_curve",+ "execMs": 0.0039579999865964055+ }+ ]+ },+ {+ "roundMs": 1066.5975839999737,+ "firstDeltaMs": 892.4294590000063,+ "calls": []+ }+ ]+ }+ },+ {+ "pass": true,+ "intent": "simple",+ "skill": null,+ "areas": [+ "preview",+ "timeline",+ "inspector",+ "effects",+ "animation",+ "transitions",+ "library"+ ],+ "declaredTools": 76,+ "routingMisses": [],+ "roundModel": "gemini-3.1-flash-lite",+ "notes": [],+ "instant": null,+ "qualityGate": [],+ "judgeNote": null,+ "trace": [+ {+ "name": "set_speed_curve",+ "round": 0,+ "atMs": 4813.077833999996,+ "execMs": 0.013082999968901277,+ "args": {+ "nodes": [+ {+ "at": 0,+ "speed": 1+ },+ {+ "at": 3.7,+ "speed": 0.3+ }+ ],+ "clipId": "c2",+ "smooth": true+ }+ },+ {+ "name": "get_state",+ "round": 1,+ "atMs": 6071.004500000039,+ "execMs": 0.04554199997801334,+ "args": {}+ },+ {+ "name": "set_speed_curve",+ "round": 2,+ "atMs": 7434.719959000009,+ "execMs": 0.005082999938167632,+ "args": {+ "smooth": true,+ "nodes": [+ {+ "at": 0,+ "speed": 1+ },+ {+ "speed": 0.3,+ "at": 3.5+ }+ ],+ "clipId": "c2"+ }+ },+ {+ "name": "set_speed_curve",+ "round": 3,+ "atMs": 8668.722167000058,+ "execMs": 0.006667000008746982,+ "args": {+ "clipId": "c2",+ "smooth": true,+ "nodes": [+ {+ "at": 0,+ "speed": 1+ },+ {+ "speed": 0.3,+ "at": 3.5+ }+ ]+ }+ },+ {+ "name": "set_speed_curve",+ "round": 4,+ "atMs": 10055.493292000028,+ "execMs": 0.005707999924197793,+ "args": {+ "nodes": [+ {+ "at": 0,+ "speed": 1+ },+ {+ "at": 3.5,+ "speed": 0.3+ }+ ],+ "smooth": true,+ "clipId": "c2"+ }+ },+ {+ "name": "set_speed_curve",+ "round": 5,+ "atMs": 11303.18120900006,+ "execMs": 0.0027920000720769167,+ "args": {+ "smooth": true,+ "clipId": "c2",+ "nodes": [+ {+ "at": 0,+ "speed": 1+ },+ {+ "speed": 0.3,+ "at": 3.5+ }+ ]+ }+ },+ {+ "name": "list_skills",+ "round": 6,+ "atMs": 12328.23354200006,+ "execMs": 0.01966700004413724,+ "args": {}+ },+ {+ "name": "set_speed_curve",+ "round": 7,+ "atMs": 14246.97333399998,+ "execMs": 0.0046660000225529075,+ "args": {+ "clipId": "c2",+ "nodes": [+ {+ "speed": 1,+ "at": 0+ },+ {+ "at": 3,+ "speed": 0.3+ }+ ],+ "smooth": true+ }+ },+ {+ "name": "set_speed_curve",+ "round": 8,+ "atMs": 15549.769500000053,+ "execMs": 0.0029170000925660133,+ "args": {+ "nodes": [+ {+ "at": 0,+ "speed": 1+ },+ {+ "at": 3,+ "speed": 0.3+ }+ ],+ "smooth": true,+ "clipId": "c2"+ }+ },+ {+ "name": "set_speed_curve",+ "round": 9,+ "atMs": 16711.149749999982,+ "execMs": 0.0046660000225529075,+ "args": {+ "clipId": "c2",+ "smooth": true,+ "nodes": [+ {+ "speed": 1,+ "at": 0+ },+ {+ "speed": 0.3,+ "at": 3.5+ }+ ]+ }+ },+ {+ "name": "set_speed_curve",+ "round": 10,+ "atMs": 18036.499375000014,+ "execMs": 0.003041999996639788,+ "args": {+ "smooth": true,+ "clipId": "c2",+ "nodes": [+ {+ "at": 0,+ "speed": 1+ },+ {+ "speed": 0.3,+ "at": 3.5+ }+ ]+ }+ },+ {+ "name": "set_speed_curve",+ "round": 11,+ "atMs": 19156.34258399997,+ "execMs": 0.0038750000530853868,+ "args": {+ "clipId": "c2",+ "smooth": true,+ "nodes": [+ {+ "at": 0,+ "speed": 1+ },+ {+ "speed": 0.3,+ "at": 3.5+ }+ ]+ }+ },+ {+ "name": "set_speed_curve",+ "round": 12,+ "atMs": 20370.917791999993,+ "execMs": 0.0025420000310987234,+ "args": {+ "smooth": true,+ "clipId": "c2",+ "nodes": [+ {+ "speed": 1,+ "at": 0+ },+ {+ "speed": 0.3,+ "at": 3.5+ }+ ]+ }+ },+ {+ "name": "set_speed_curve",+ "round": 13,+ "atMs": 21590.87062499998,+ "execMs": 0.0029169999761506915,+ "args": {+ "nodes": [+ {+ "speed": 1,+ "at": 0+ },+ {+ "speed": 0.3,+ "at": 3.5+ }+ ],+ "smooth": true,+ "clipId": "c2"+ }+ },+ {+ "name": "set_speed_curve",+ "round": 14,+ "atMs": 22925.33720900002,+ "execMs": 0.005082999938167632,+ "args": {+ "smooth": true,+ "nodes": [+ {+ "at": 0,+ "speed": 1+ },+ {+ "at": 3.5,+ "speed": 0.3+ }+ ],+ "clipId": "c2"+ }+ },+ {+ "name": "set_speed_curve",+ "round": 15,+ "atMs": 24005.223791999975,+ "execMs": 0.0023750000400468707,+ "args": {+ "nodes": [+ {+ "speed": 1,+ "at": 0+ },+ {+ "speed": 0.3,+ "at": 3.5+ }+ ],+ "clipId": "c2",+ "smooth": true+ }+ },+ {+ "name": "set_speed_curve",+ "round": 16,+ "atMs": 25258.501416999963,+ "execMs": 0.0031660000095143914,+ "args": {+ "nodes": [+ {+ "at": 0,+ "speed": 1+ },+ {+ "speed": 0.3,+ "at": 3.5+ }+ ],+ "smooth": true,+ "clipId": "c2"+ }+ },+ {+ "name": "set_speed_curve",+ "round": 17,+ "atMs": 26522.295541999978,+ "execMs": 0.0016250000335276127,+ "args": {+ "nodes": [+ {+ "at": 0,+ "speed": 1+ },+ {+ "at": 3.5,+ "speed": 0.3+ }+ ],+ "clipId": "c2",+ "smooth": true+ }+ },+ {+ "name": "set_speed_curve",+ "round": 18,+ "atMs": 27898.891334000044,+ "execMs": 0.0019580000080168247,+ "args": {+ "clipId": "c2",+ "smooth": true,+ "nodes": [+ {+ "speed": 1,+ "at": 0+ },+ {+ "speed": 0.3,+ "at": 3.5+ }+ ]+ }+ },+ {+ "name": "set_speed_curve",+ "round": 19,+ "atMs": 29098.859999999986,+ "execMs": 0.0020829999120905995,+ "args": {+ "nodes": [+ {+ "at": 0,+ "speed": 1+ },+ {+ "at": 3.5,+ "speed": 0.3+ }+ ],+ "smooth": true,+ "clipId": "c2"+ }+ },+ {+ "name": "set_speed_curve",+ "round": 20,+ "atMs": 30406.784250000026,+ "execMs": 0.003333000000566244,+ "args": {+ "smooth": true,+ "clipId": "c2",+ "nodes": [+ {+ "at": 0,+ "speed": 1+ },+ {+ "speed": 0.3,+ "at": 3.5+ }+ ]+ }+ },+ {+ "name": "set_speed_curve",+ "round": 21,+ "atMs": 31617.301084000035,+ "execMs": 0.007041000062599778,+ "args": {+ "nodes": [+ {+ "speed": 1,+ "at": 0+ },+ {+ "at": 3,+ "speed": 0.3+ }+ ],+ "smooth": true,+ "clipId": "c2"+ }+ },+ {+ "name": "set_speed_curve",+ "round": 22,+ "atMs": 33007.34499999997,+ "execMs": 0.0058750000316649675,+ "args": {+ "smooth": true,+ "nodes": [+ {+ "speed": 1,+ "at": 0+ },+ {+ "speed": 0.3,+ "at": 3+ }+ ],+ "clipId": "c2"+ }+ },+ {+ "name": "set_speed_curve",+ "round": 23,+ "atMs": 34294.80050000001,+ "execMs": 0.01791699999012053,+ "args": {+ "clipId": "c2",+ "nodes": [+ {+ "at": 0,+ "speed": 1+ },+ {+ "speed": 0.3,+ "at": 3.5+ }+ ]+ }+ },+ {+ "name": "set_speed_curve",+ "round": 24,+ "atMs": 35532.61725000001,+ "execMs": 0.023874999955296516,+ "args": {+ "nodes": [+ {+ "at": 0,+ "speed": 1+ },+ {+ "at": 3,+ "speed": 0.3+ }+ ],+ "clipId": "c2",+ "smooth": true+ }+ },+ {+ "name": "set_speed_curve",+ "round": 25,+ "atMs": 36825.66208399995,+ "execMs": 0.016874999972060323,+ "args": {+ "nodes": [+ {+ "at": 0,+ "speed": 1+ },+ {+ "speed": 0.3,+ "at": 3+ }+ ],+ "smooth": true,+ "clipId": "c2"+ }+ }+ ],+ "timings": {+ "gateMs": 340.04562500002794,+ "gateSkipped": false,+ "ttftMs": 38182.86729199998,+ "modelMs": 38007.16762600036,+ "toolMs": 0.21437300008255988,+ "totalMs": 38382.030708999955,+ "judgeMs": 235.03075000003446,+ "retryMs": 0,+ "retries": 0,+ "rounds": [+ {+ "roundMs": 4470.962584000081,+ "firstDeltaMs": null,+ "calls": [+ {+ "name": "set_speed_curve",+ "execMs": 0.013082999968901277+ }+ ]+ },+ {+ "roundMs": 1255.8474169999827,+ "firstDeltaMs": null,+ "calls": [+ {+ "name": "get_state",+ "execMs": 0.04554199997801334+ }+ ]+ },+ {+ "roundMs": 1362.0033340000082,+ "firstDeltaMs": null,+ "calls": [+ {+ "name": "set_speed_curve",+ "execMs": 0.005082999938167632+ }+ ]+ },+ {+ "roundMs": 1232.5105840000324,+ "firstDeltaMs": null,+ "calls": [+ {+ "name": "set_speed_curve",+ "execMs": 0.006667000008746982+ }+ ]+ },+ {+ "roundMs": 1385.3968330000062,+ "firstDeltaMs": null,+ "calls": [+ {+ "name": "set_speed_curve",+ "execMs": 0.005707999924197793+ }+ ]+ },+ {+ "roundMs": 1246.2852919999277,+ "firstDeltaMs": null,+ "calls": [+ {+ "name": "set_speed_curve",+ "execMs": 0.0027920000720769167+ }+ ]+ },+ {+ "roundMs": 1024.0098749999888,+ "firstDeltaMs": null,+ "calls": [+ {+ "name": "list_skills",+ "execMs": 0.01966700004413724+ }+ ]+ },+ {+ "roundMs": 1917.314000000013,+ "firstDeltaMs": null,+ "calls": [+ {+ "name": "set_speed_curve",+ "execMs": 0.0046660000225529075+ }+ ]+ },+ {+ "roundMs": 1301.3625000000466,+ "firstDeltaMs": null,+ "calls": [+ {+ "name": "set_speed_curve",+ "execMs": 0.0029170000925660133+ }+ ]+ },+ {+ "roundMs": 1160.595667000045,+ "firstDeltaMs": null,+ "calls": [+ {+ "name": "set_speed_curve",+ "execMs": 0.0046660000225529075+ }+ ]+ },+ {+ "roundMs": 1324.0202079999726,+ "firstDeltaMs": null,+ "calls": [+ {+ "name": "set_speed_curve",+ "execMs": 0.003041999996639788+ }+ ]+ },+ {+ "roundMs": 1118.7093330000062,+ "firstDeltaMs": null,+ "calls": [+ {+ "name": "set_speed_curve",+ "execMs": 0.0038750000530853868+ }+ ]+ },+ {+ "roundMs": 1213.388957999996,+ "firstDeltaMs": null,+ "calls": [+ {+ "name": "set_speed_curve",+ "execMs": 0.0025420000310987234+ }+ ]+ },+ {+ "roundMs": 1219.1501670000143,+ "firstDeltaMs": null,+ "calls": [+ {+ "name": "set_speed_curve",+ "execMs": 0.0029169999761506915+ }+ ]+ },+ {+ "roundMs": 1333.437333000009,+ "firstDeltaMs": null,+ "calls": [+ {+ "name": "set_speed_curve",+ "execMs": 0.005082999938167632+ }+ ]+ },+ {+ "roundMs": 1078.58970900008,+ "firstDeltaMs": null,+ "calls": [+ {+ "name": "set_speed_curve",+ "execMs": 0.0023750000400468707+ }+ ]+ },+ {+ "roundMs": 1252.3047080000397,+ "firstDeltaMs": null,+ "calls": [+ {+ "name": "set_speed_curve",+ "execMs": 0.0031660000095143914+ }+ ]+ },+ {+ "roundMs": 1262.7010409999639,+ "firstDeltaMs": null,+ "calls": [+ {+ "name": "set_speed_curve",+ "execMs": 0.0016250000335276127+ }+ ]+ },+ {+ "roundMs": 1376.0862500000512,+ "firstDeltaMs": null,+ "calls": [+ {+ "name": "set_speed_curve",+ "execMs": 0.0019580000080168247+ }+ ]+ },+ {+ "roundMs": 1199.347208000021,+ "firstDeltaMs": null,+ "calls": [+ {+ "name": "set_speed_curve",+ "execMs": 0.0020829999120905995+ }+ ]+ },+ {+ "roundMs": 1307.2001250000903,+ "firstDeltaMs": null,+ "calls": [+ {+ "name": "set_speed_curve",+ "execMs": 0.003333000000566244+ }+ ]+ },+ {+ "roundMs": 1209.5728329999838,+ "firstDeltaMs": null,+ "calls": [+ {+ "name": "set_speed_curve",+ "execMs": 0.007041000062599778+ }+ ]+ },+ {+ "roundMs": 1389.2945840000175,+ "firstDeltaMs": null,+ "calls": [+ {+ "name": "set_speed_curve",+ "execMs": 0.0058750000316649675+ }+ ]+ },+ {+ "roundMs": 1286.0864999999758,+ "firstDeltaMs": null,+ "calls": [+ {+ "name": "set_speed_curve",+ "execMs": 0.01791699999012053+ }+ ]+ },+ {+ "roundMs": 1235.404749999987,+ "firstDeltaMs": null,+ "calls": [+ {+ "name": "set_speed_curve",+ "execMs": 0.023874999955296516+ }+ ]+ },+ {+ "roundMs": 1291.3292080000974,+ "firstDeltaMs": null,+ "calls": [+ {+ "name": "set_speed_curve",+ "execMs": 0.016874999972060323+ }+ ]+ },+ {+ "roundMs": 1554.2566249999218,+ "firstDeltaMs": 1355.919750000001,+ "calls": []+ }+ ]+ }+ }+ ]+ },+ {+ "name": "replicate-a-video-blocks-out-the-cuts",+ "bucket": "multi-tool",+ "passRate": 0,+ "budgetBreaches": [],+ "latency": null,+ "runs": [+ {+ "pass": false,+ "intent": "complex",+ "skill": "replicating-a-video",+ "areas": [+ "preview",+ "timeline",+ "inspector",+ "elements",+ "effects",+ "animation",+ "transitions",+ "subtitles",+ "audio",+ "video_gen",+ "scene",+ "stock",+ "library",+ "side_panel",+ "top_bar",+ "editor"+ ],+ "declaredTools": 121,+ "routingMisses": [],+ "roundModel": "gemini-3.8-flash",+ "notes": [+ "mutating tools called: detach_audio, compare_to_source"+ ],+ "instant": null,+ "qualityGate": [],+ "judgeNote": null,+ "trace": [+ {+ "name": "watch_video",+ "round": 0,+ "atMs": 7651.853792000096,+ "execMs": 1.3317089999327436,+ "args": {+ "detail": "scan",+ "to": 71.6,+ "from": 0,+ "asset_id": "a-ref1"+ }+ },+ {+ "name": "note_source",+ "round": 1,+ "atMs": 10133.366125000059,+ "execMs": 0.004541000002063811,+ "args": {+ "notes": [+ {+ "text": "Talking head video with rapid cuts every ~2s, hook titles in bold yellow Archivo Black over the speaker.",+ "from": 0,+ "to": 24+ }+ ],+ "asset_id": "a-ref1"+ }+ },+ {+ "name": "watch_video",+ "round": 2,+ "atMs": 13902.610292000114,+ "execMs": 0.027584000024944544,+ "args": {+ "asset_id": "a-ref1",+ "to": 71.6,+ "detail": "scan",+ "from": 24+ }+ },+ {+ "name": "note_source",+ "round": 3,+ "atMs": 16201.765042000101,+ "execMs": 0.005083999945782125,+ "args": {+ "asset_id": "a-ref1",+ "notes": [+ {+ "text": "Talking head video continues with cuts every ~2s, hook and topic titles over speaker.",+ "from": 24,+ "to": 48+ }+ ]+ }+ },+ {+ "name": "watch_video",+ "round": 4,+ "atMs": 18646.350292000105,+ "execMs": 0.03141699999105185,+ "args": {+ "asset_id": "a-ref1",+ "to": 71.6,+ "detail": "scan",+ "from": 48+ }+ },+ {+ "name": "note_source",+ "round": 5,+ "atMs": 20813.67875000008,+ "execMs": 0.002791999955661595,+ "args": {+ "asset_id": "a-ref1",+ "notes": [+ {+ "text": "Talking head video continues with cuts every ~2s through 71.6s, yellow hook titles over speaker.",+ "from": 48,+ "to": 71.6+ }+ ]+ }+ },+ {+ "name": "watch_video",+ "round": 6,+ "atMs": 23144.796792000066,+ "execMs": 0.03737499995622784,+ "args": {+ "detail": "read",+ "from": 0,+ "to": 10,+ "asset_id": "a-ref1",+ "interval_seconds": 0.5+ }+ },+ {+ "name": "note_source",+ "round": 7,+ "atMs": 27155.734459000058,+ "execMs": 0.0037089999532327056,+ "args": {+ "notes": [+ {+ "text": "Hook title '4.6 YEARS UNTIL I NEVER WORK AGAIN' in yellow Archivo Black over talking head shot.",+ "to": 10,+ "from": 0+ }+ ],+ "asset_id": "a-ref1"+ }+ },+ {+ "name": "detach_audio",+ "round": 8,+ "atMs": 29109.927125000046,+ "execMs": 0.01049999997485429,+ "args": {+ "start": 0,+ "assetId": "a-ref1"+ }+ },+ {+ "name": "add_clip",+ "round": 9,+ "atMs": 35508.461834000074,+ "execMs": 0.11791699996683747,+ "args": {+ "blocks": [+ {+ "color": "#1a1a1a",+ "seconds": 2,+ "label": "Talking head - shot 1"+ },+ {+ "label": "Talking head - shot 2",+ "color": "#1a1a1a",+ "seconds": 2+ },+ {+ "label": "Talking head - shot 3",+ "color": "#1a1a1a",+ "seconds": 2+ },+ {+ "seconds": 2,+ "label": "Talking head - shot 4",+ "color": "#1a1a1a"+ },+ {+ "label": "Talking head - shot 5",+ "seconds": 2,+ "color": "#1a1a1a"+ },+ {+ "seconds": 2,+ "label": "Talking head - shot 6",+ "color": "#1a1a1a"+ },+ {+ "label": "Talking head - shot 7",+ "seconds": 2,+ "color": "#1a1a1a"+ },+ {+ "label": "Talking head - shot 8",+ "color": "#1a1a1a",+ "seconds": 2+ },+ {+ "label": "Talking head - shot 9",+ "seconds": 2,+ "color": "#1a1a1a"+ },+ {+ "seconds": 2,+ "color": "#1a1a1a",+ "label": "Talking head - shot 10"+ },+ {+ "color": "#1a1a1a",+ "seconds": 2,+ "label": "Talking head - shot 11"+ },+ {+ "label": "Talking head - shot 12",+ "color": "#1a1a1a",+ "seconds": 2+ },+ {+ "color": "#1a1a1a",+ "label": "Talking head - shot 13",+ "seconds": 2+ },+ {+ "color": "#1a1a1a",+ "label": "Talking head - shot 14",+ "seconds": 2+ },+ {+ "seconds": 2,+ "color": "#1a1a1a",+ "label": "Talking head - shot 15"+ },+ {+ "label": "Talking head - shot 16",+ "color": "#1a1a1a",+ "seconds": 2+ },+ {+ "color": "#1a1a1a",+ "label": "Talking head - shot 17",+ "seconds": 2+ },+ {+ "label": "Talking head - shot 18",+ "color": "#1a1a1a",+ "seconds": 2+ },+ {+ "label": "Talking head - shot 19",+ "seconds": 2,+ "color": "#1a1a1a"+ },+ {+ "color": "#1a1a1a",+ "label": "Talking head - shot 20",+ "seconds": 2+ },+ {+ "seconds": 2,+ "label": "Talking head - shot 21",+ "color": "#1a1a1a"+ },+ {+ "seconds": 2,+ "color": "#1a1a1a",+ "label": "Talking head - shot 22"+ },+ {+ "seconds": 2,+ "label": "Talking head - shot 23",+ "color": "#1a1a1a"+ },+ {+ "color": "#1a1a1a",+ "seconds": 2,+ "label": "Talking head - shot 24"+ },+ {+ "label": "Talking head - shot 25",+ "color": "#1a1a1a",+ "seconds": 2+ },+ {+ "seconds": 2,+ "label": "Talking head - shot 26",+ "color": "#1a1a1a"+ },+ {+ "seconds": 2,+ "label": "Talking head - shot 27",+ "color": "#1a1a1a"+ },+ {+ "seconds": 2,+ "color": "#1a1a1a",+ "label": "Talking head - shot 28"+ },+ {+ "seconds": 2,+ "label": "Talking head - shot 29",+ "color": "#1a1a1a"+ },+ {+ "label": "Talking head - shot 30",+ "color": "#1a1a1a",+ "seconds": 2+ },+ {+ "label": "Talking head - shot 31",+ "seconds": 2,+ "color": "#1a1a1a"+ },+ {+ "label": "Talking head - shot 32",+ "seconds": 2,+ "color": "#1a1a1a"+ },+ {+ "seconds": 2,+ "color": "#1a1a1a",+ "label": "Talking head - shot 33"+ },+ {+ "seconds": 2,+ "color": "#1a1a1a",+ "label": "Talking head - shot 34"+ },+ {+ "color": "#1a1a1a",+ "seconds": 2,+ "label": "Talking head - shot 35"+ },+ {+ "label": "Talking head - shot 36",+ "color": "#1a1a1a",+ "seconds": 1.6+ }+ ]+ }+ },+ {+ "name": "add_title",+ "round": 10,+ "atMs": 38894.09595900006,+ "execMs": 0.022624999983236194,+ "args": {+ "size": 84,+ "font": "archivoblack",+ "color": "#FFD700",+ "stroke_width": 0.04,+ "start": 0,+ "stroke_color": "#000000",+ "weight": 700,+ "x": 0.5,+ "end": 4,+ "y": 0.35,+ "text": "4.6 YEARS UNTIL\nI NEVER WORK AGAIN"+ }+ },+ {+ "name": "compare_to_source",+ "round": 11,+ "atMs": 41018.14554200007,+ "execMs": 0.008916999911889434,+ "args": {+ "asset_id": "a-ref1",+ "times": [+ 1,+ 3+ ]+ }+ }+ ],+ "timings": {+ "gateMs": 316.11187500006054,+ "gateSkipped": false,+ "ttftMs": 42785.785417000065,+ "modelMs": 42921.28175099997,+ "toolMs": 1.6041699995985255,+ "totalMs": 43545.976125000045,+ "judgeMs": 242.09712499997113,+ "retryMs": 0,+ "retries": 0,+ "rounds": [+ {+ "roundMs": 7333.578458999982,+ "firstDeltaMs": null,+ "calls": [+ {+ "name": "watch_video",+ "execMs": 1.3317089999327436+ }+ ]+ },+ {+ "roundMs": 2478.904000000097,+ "firstDeltaMs": null,+ "calls": [+ {+ "name": "note_source",+ "execMs": 0.004541000002063811+ }+ ]+ },+ {+ "roundMs": 3768.4792919999454,+ "firstDeltaMs": null,+ "calls": [+ {+ "name": "watch_video",+ "execMs": 0.027584000024944544+ }+ ]+ },+ {+ "roundMs": 2297.895707999938,+ "firstDeltaMs": null,+ "calls": [+ {+ "name": "note_source",+ "execMs": 0.005083999945782125+ }+ ]+ },+ {+ "roundMs": 2443.2579160000896,+ "firstDeltaMs": null,+ "calls": [+ {+ "name": "watch_video",+ "execMs": 0.03141699999105185+ }+ ]+ },+ {+ "roundMs": 2165.743417000049,+ "firstDeltaMs": null,+ "calls": [+ {+ "name": "note_source",+ "execMs": 0.002791999955661595+ }+ ]+ },+ {+ "roundMs": 2330.1352079999633,+ "firstDeltaMs": null,+ "calls": [+ {+ "name": "watch_video",+ "execMs": 0.03737499995622784+ }+ ]+ },+ {+ "roundMs": 4010.056125000003,+ "firstDeltaMs": null,+ "calls": [+ {+ "name": "note_source",+ "execMs": 0.0037089999532327056+ }+ ]+ },+ {+ "roundMs": 1951.2360839999747,+ "firstDeltaMs": null,+ "calls": [+ {+ "name": "detach_audio",+ "execMs": 0.01049999997485429+ }+ ]+ },+ {+ "roundMs": 6396.062082999968,+ "firstDeltaMs": null,+ "calls": [+ {+ "name": "add_clip",+ "execMs": 0.11791699996683747+ }+ ]+ },+ {+ "roundMs": 3381.6100000001024,+ "firstDeltaMs": null,+ "calls": [+ {+ "name": "add_title",+ "execMs": 0.022624999983236194+ }+ ]+ },+ {+ "roundMs": 2120.4634999999544,+ "firstDeltaMs": null,+ "calls": [+ {+ "name": "compare_to_source",+ "execMs": 0.008916999911889434+ }+ ]+ },+ {+ "roundMs": 2243.8599589999067,+ "firstDeltaMs": 1766.9238749999786,+ "calls": []+ }+ ]+ }+ },+ {+ "pass": false,+ "intent": "complex",+ "skill": "replicating-a-video",+ "areas": [+ "preview",+ "timeline",+ "inspector",+ "elements",+ "effects",+ "animation",+ "transitions",+ "subtitles",+ "audio",+ "video_gen",+ "scene",+ "stock",+ "library",+ "side_panel",+ "top_bar",+ "editor"+ ],+ "declaredTools": 121,+ "routingMisses": [],+ "roundModel": "gemini-3.8-flash",+ "notes": [+ "mutating tools called: detach_audio, compare_to_source"+ ],+ "instant": null,+ "qualityGate": [],+ "judgeNote": null,+ "trace": [+ {+ "name": "watch_video",+ "round": 0,+ "atMs": 2920.111957999994,+ "execMs": 0.019791000057011843,+ "args": {+ "from": 0,+ "asset_id": "a-ref1",+ "detail": "scan",+ "to": 71.6+ }+ },+ {+ "name": "note_source",+ "round": 1,+ "atMs": 5120.832874999964,+ "execMs": 0.004000000073574483,+ "args": {+ "asset_id": "a-ref1",+ "notes": [+ {+ "to": 24,+ "text": "Talking head with yellow Archivo-Black hook titles over video, cuts roughly every 2 seconds.",+ "from": 0+ }+ ]+ }+ },+ {+ "name": "watch_video",+ "round": 2,+ "atMs": 7062.144916999969,+ "execMs": 0.029125000000931323,+ "args": {+ "from": 24,+ "asset_id": "a-ref1",+ "detail": "scan",+ "to": 71.6+ }+ },+ {+ "name": "note_source",+ "round": 3,+ "atMs": 8817.70637499995,+ "execMs": 0.007083000033162534,+ "args": {+ "asset_id": "a-ref1",+ "notes": [+ {+ "to": 48,+ "from": 24,+ "text": "Talking head with yellow Archivo-Black hook titles over video, cuts every 2s."+ }+ ]+ }+ },+ {+ "name": "watch_video",+ "round": 4,+ "atMs": 10765.183582999976,+ "execMs": 0.0287080000853166,+ "args": {+ "asset_id": "a-ref1",+ "detail": "scan",+ "from": 48,+ "to": 71.6+ }+ },+ {+ "name": "note_source",+ "round": 5,+ "atMs": 13108.372417000006,+ "execMs": 0.004542000009678304,+ "args": {+ "asset_id": "a-ref1",+ "notes": [+ {+ "text": "Talking head with yellow Archivo-Black hook titles over video, cuts every 2s to the end at 71.6s.",+ "to": 71.6,+ "from": 48+ }+ ]+ }+ },+ {+ "name": "watch_video",+ "round": 6,+ "atMs": 14821.983332999982,+ "execMs": 0.06145799998193979,+ "args": {+ "to": 6,+ "from": 0,+ "detail": "read",+ "asset_id": "a-ref1"+ }+ },+ {+ "name": "note_source",+ "round": 7,+ "atMs": 16781.84474999993,+ "execMs": 0.003041999996639788,+ "args": {+ "notes": [+ {+ "to": 6,+ "from": 0,+ "text": "Hook: Yellow Archivo Black title '4.6 YEARS UNTIL I NEVER WORK AGAIN' in upper-middle frame. Cuts every 2s across talking head shots."+ }+ ],+ "asset_id": "a-ref1"+ }+ },+ {+ "name": "detach_audio",+ "round": 8,+ "atMs": 18349.087541999994,+ "execMs": 0.02137500001117587,+ "args": {+ "assetId": "a-ref1"+ }+ },+ {+ "name": "add_clip",+ "round": 9,+ "atMs": 25062.19179199997,+ "execMs": 0.04466699995100498,+ "args": {+ "blocks": [+ {+ "color": "#1a1a1a",+ "label": "Shot 1 - Talking Head Hook",+ "seconds": 2+ },+ {+ "color": "#1a1a1a",+ "label": "Shot 2 - Talking Head",+ "seconds": 2+ },+ {+ "color": "#1a1a1a",+ "seconds": 2,+ "label": "Shot 3 - Talking Head"+ },+ {+ "label": "Shot 4 - Talking Head",+ "color": "#1a1a1a",+ "seconds": 2+ },+ {+ "label": "Shot 5 - Talking Head",+ "color": "#1a1a1a",+ "seconds": 2+ },+ {+ "label": "Shot 6 - Talking Head",+ "seconds": 2,+ "color": "#1a1a1a"+ },+ {+ "color": "#1a1a1a",+ "label": "Shot 7 - Talking Head",+ "seconds": 2+ },+ {+ "seconds": 2,+ "label": "Shot 8 - Talking Head",+ "color": "#1a1a1a"+ },+ {+ "seconds": 2,+ "color": "#1a1a1a",+ "label": "Shot 9 - Talking Head"+ },+ {+ "seconds": 2,+ "color": "#1a1a1a",+ "label": "Shot 10 - Talking Head"+ },+ {+ "color": "#1a1a1a",+ "seconds": 2,+ "label": "Shot 11 - Talking Head"+ },+ {+ "label": "Shot 12 - Talking Head",+ "seconds": 2,+ "color": "#1a1a1a"+ },+ {+ "label": "Shot 13 - Talking Head",+ "color": "#1a1a1a",+ "seconds": 2+ },+ {+ "color": "#1a1a1a",+ "label": "Shot 14 - Talking Head",+ "seconds": 2+ },+ {+ "color": "#1a1a1a",+ "label": "Shot 15 - Talking Head",+ "seconds": 2+ },+ {+ "seconds": 2,+ "label": "Shot 16 - Talking Head",+ "color": "#1a1a1a"+ },+ {+ "label": "Shot 17 - Talking Head",+ "seconds": 2,+ "color": "#1a1a1a"+ },+ {+ "seconds": 2,+ "label": "Shot 18 - Talking Head",+ "color": "#1a1a1a"+ },+ {+ "seconds": 2,+ "color": "#1a1a1a",+ "label": "Shot 19 - Talking Head"+ },+ {+ "color": "#1a1a1a",+ "label": "Shot 20 - Talking Head",+ "seconds": 2+ },+ {+ "color": "#1a1a1a",+ "seconds": 2,+ "label": "Shot 21 - Talking Head"+ },+ {+ "color": "#1a1a1a",+ "label": "Shot 22 - Talking Head",+ "seconds": 2+ },+ {+ "seconds": 2,+ "label": "Shot 23 - Talking Head",+ "color": "#1a1a1a"+ },+ {+ "label": "Shot 24 - Talking Head",+ "color": "#1a1a1a",+ "seconds": 2+ },+ {+ "color": "#1a1a1a",+ "seconds": 2,+ "label": "Shot 25 - Talking Head"+ },+ {+ "label": "Shot 26 - Talking Head",+ "color": "#1a1a1a",+ "seconds": 2+ },+ {+ "seconds": 2,+ "color": "#1a1a1a",+ "label": "Shot 27 - Talking Head"+ },+ {+ "color": "#1a1a1a",+ "label": "Shot 28 - Talking Head",+ "seconds": 2+ },+ {+ "color": "#1a1a1a",+ "label": "Shot 29 - Talking Head",+ "seconds": 2+ },+ {+ "label": "Shot 30 - Talking Head",+ "color": "#1a1a1a",+ "seconds": 2+ },+ {+ "seconds": 2,+ "color": "#1a1a1a",+ "label": "Shot 31 - Talking Head"+ },+ {+ "color": "#1a1a1a",+ "seconds": 2,+ "label": "Shot 32 - Talking Head"+ },+ {+ "label": "Shot 33 - Talking Head",+ "seconds": 2,+ "color": "#1a1a1a"+ },+ {+ "seconds": 2,+ "label": "Shot 34 - Talking Head",+ "color": "#1a1a1a"+ },+ {+ "seconds": 2,+ "label": "Shot 35 - Talking Head",+ "color": "#1a1a1a"+ },+ {+ "label": "Shot 36 - Talking Head",+ "seconds": 1.6,+ "color": "#1a1a1a"+ }+ ]+ }+ },+ {+ "name": "add_title",+ "round": 10,+ "atMs": 27887.89970800001,+ "execMs": 0.016167000052519143,+ "args": {+ "start": 0,+ "text": "4.6 YEARS UNTIL I NEVER WORK AGAIN",+ "shadow": true,+ "font": "archivo-black",+ "weight": 700,+ "stroke_width": 0.04,+ "end": 4,+ "color": "#FFE600",+ "x": 0.5,+ "stroke_color": "#000000",+ "size": 72,+ "y": 0.35+ }+ },+ {+ "name": "compare_to_source",+ "round": 11,+ "atMs": 30154.67937499995,+ "execMs": 0.01441599999088794,+ "args": {+ "asset_id": "a-ref1",+ "times": [+ 1,+ 3+ ]+ }+ }+ ],+ "timings": {+ "gateMs": 249.90333400003146,+ "gateSkipped": false,+ "ttftMs": 32229.36166699999,+ "modelMs": 32365.15333299979,+ "toolMs": 0.2543740002438426,+ "totalMs": 32903.33833299996,+ "judgeMs": 196.00445799995214,+ "retryMs": 0,+ "retries": 0,+ "rounds": [+ {+ "roundMs": 2669.0592079999624,+ "firstDeltaMs": null,+ "calls": [+ {+ "name": "watch_video",+ "execMs": 0.019791000057011843+ }+ ]+ },+ {+ "roundMs": 2199.4125419999473,+ "firstDeltaMs": null,+ "calls": [+ {+ "name": "note_source",+ "execMs": 0.004000000073574483+ }+ ]+ },+ {+ "roundMs": 1940.07337499992,+ "firstDeltaMs": null,+ "calls": [+ {+ "name": "watch_video",+ "execMs": 0.029125000000931323+ }+ ]+ },+ {+ "roundMs": 1754.0145000000484,+ "firstDeltaMs": null,+ "calls": [+ {+ "name": "note_source",+ "execMs": 0.007083000033162534+ }+ ]+ },+ {+ "roundMs": 1946.110999999917,+ "firstDeltaMs": null,+ "calls": [+ {+ "name": "watch_video",+ "execMs": 0.0287080000853166+ }+ ]+ },+ {+ "roundMs": 2341.584125000052,+ "firstDeltaMs": null,+ "calls": [+ {+ "name": "note_source",+ "execMs": 0.004542000009678304+ }+ ]+ },+ {+ "roundMs": 1712.4732089999598,+ "firstDeltaMs": null,+ "calls": [+ {+ "name": "watch_video",+ "execMs": 0.06145799998193979+ }+ ]+ },+ {+ "roundMs": 1958.4459580000257,+ "firstDeltaMs": null,+ "calls": [+ {+ "name": "note_source",+ "execMs": 0.003041999996639788+ }+ ]+ },+ {+ "roundMs": 1566.4760000000242,+ "firstDeltaMs": null,+ "calls": [+ {+ "name": "detach_audio",+ "execMs": 0.02137500001117587+ }+ ]+ },+ {+ "roundMs": 6711.534665999934,+ "firstDeltaMs": null,+ "calls": [+ {+ "name": "add_clip",+ "execMs": 0.04466699995100498+ }+ ]+ },+ {+ "roundMs": 2824.0153750000754,+ "firstDeltaMs": null,+ "calls": [+ {+ "name": "add_title",+ "execMs": 0.016167000052519143+ }+ ]+ },+ {+ "roundMs": 2265.438709000009,+ "firstDeltaMs": null,+ "calls": [+ {+ "name": "compare_to_source",+ "execMs": 0.01441599999088794+ }+ ]+ },+ {+ "roundMs": 2476.5146659999155,+ "firstDeltaMs": 2073.804582999903,+ "calls": []+ }+ ]+ }+ },+ {+ "pass": false,+ "intent": "complex",+ "skill": "replicating-a-video",+ "areas": [+ "preview",+ "timeline",+ "inspector",+ "elements",+ "effects",+ "animation",+ "transitions",+ "subtitles",+ "audio",+ "video_gen",+ "scene",+ "stock",+ "library",+ "side_panel",+ "top_bar",+ "editor"+ ],+ "declaredTools": 121,+ "routingMisses": [],+ "roundModel": "gemini-3.8-flash",+ "notes": [+ "mutating tools called: detach_audio, compare_to_source",+ "blocked out 143.2s over a 71.6s reference",+ "put the reference itself on the timeline"+ ],+ "instant": null,+ "qualityGate": [+ "repair",+ "repair"+ ],+ "judgeNote": "concise factual 0.39; long 2.0",+ "trace": [+ {+ "name": "watch_video",+ "round": 0,+ "atMs": 2454.3938749999506,+ "execMs": 0.13158299995120615,+ "args": {+ "detail": "scan",+ "interval_seconds": 2,+ "asset_id": "a-ref1"+ }+ },+ {+ "name": "note_source",+ "round": 1,+ "atMs": 4819.524041999946,+ "execMs": 0.01533299998845905,+ "args": {+ "asset_id": "a-ref1",+ "notes": [+ {+ "text": "Hook title cards in yellow Archivo-Black over talking head shots, cuts approximately every 2 seconds",+ "from": 0,+ "to": 24+ }+ ]+ }+ },+ {+ "name": "watch_video",+ "round": 2,+ "atMs": 7010.304208999965,+ "execMs": 0.02549999998882413,+ "args": {+ "interval_seconds": 2,+ "detail": "scan",+ "to": 71.6,+ "asset_id": "a-ref1",+ "from": 24+ }+ },+ {+ "name": "note_source",+ "round": 3,+ "atMs": 9040.837708999985,+ "execMs": 0.007208000053651631,+ "args": {+ "notes": [+ {+ "to": 48,+ "text": "Talking head shots continuing with cuts every 2s, captions/titles in bold yellow centered",+ "from": 24+ }+ ],+ "asset_id": "a-ref1"+ }+ },+ {+ "name": "watch_video",+ "round": 4,+ "atMs": 10944.034375000047,+ "execMs": 0.029792000073939562,+ "args": {+ "asset_id": "a-ref1",+ "to": 71.6,+ "detail": "scan",+ "interval_seconds": 2,+ "from": 48+ }+ },+ {+ "name": "note_source",+ "round": 5,+ "atMs": 12899.244042000035,+ "execMs": 0.004750000080093741,+ "args": {+ "notes": [+ {+ "from": 48,+ "text": "Talking head shots continuing with cuts every 2s to end at 71.6s",+ "to": 71.6+ }+ ],+ "asset_id": "a-ref1"+ }+ },+ {+ "name": "watch_video",+ "round": 6,+ "atMs": 14999.003917000024,+ "execMs": 0.039582999888807535,+ "args": {+ "detail": "read",+ "to": 10,+ "from": 0,+ "interval_seconds": 1,+ "asset_id": "a-ref1"+ }+ },+ {+ "name": "note_source",+ "round": 7,+ "atMs": 17129.839666999993,+ "execMs": 0.0017499999376013875,+ "args": {+ "asset_id": "a-ref1",+ "notes": [+ {+ "to": 10,+ "text": "Yellow Archivo-Black hook title cards: \"4.6 YEARS UNTIL I NEVER WORK AGAIN\" over talking head shots cut every ~2s.",+ "from": 0+ }+ ]+ }+ },+ {+ "name": "detach_audio",+ "round": 9,+ "atMs": 21677.02537499997,+ "execMs": 0.006416999967768788,+ "args": {+ "start": 0,+ "assetId": "a-ref1"+ }+ },+ {+ "name": "add_clip",+ "round": 10,+ "atMs": 23550.73091699998,+ "execMs": 2.669542000046931,+ "args": {+ "asset_id": "a-ref1",+ "lane": 0,+ "start": 0+ }+ },+ {+ "name": "add_clip",+ "round": 11,+ "atMs": 30098.456833999953,+ "execMs": 0.04029200004879385,+ "args": {+ "blocks": [+ {+ "label": "Shot 1",+ "color": "#1a1a1a",+ "seconds": 2+ },+ {+ "seconds": 2,+ "color": "#1a1a1a",+ "label": "Shot 2"+ },+ {+ "seconds": 2,+ "label": "Shot 3",+ "color": "#1a1a1a"+ },+ {+ "color": "#1a1a1a",+ "label": "Shot 4",+ "seconds": 2+ },+ {+ "color": "#1a1a1a",+ "seconds": 2,+ "label": "Shot 5"+ },+ {+ "label": "Shot 6",+ "color": "#1a1a1a",+ "seconds": 2+ },+ {+ "label": "Shot 7",+ "color": "#1a1a1a",+ "seconds": 2+ },+ {+ "label": "Shot 8",+ "color": "#1a1a1a",+ "seconds": 2+ },+ {+ "seconds": 2,+ "label": "Shot 9",+ "color": "#1a1a1a"+ },+ {+ "color": "#1a1a1a",+ "label": "Shot 10",+ "seconds": 2+ },+ {+ "seconds": 2,+ "label": "Shot 11",+ "color": "#1a1a1a"+ },+ {+ "label": "Shot 12",+ "seconds": 2,+ "color": "#1a1a1a"+ },+ {+ "seconds": 2,+ "color": "#1a1a1a",+ "label": "Shot 13"+ },+ {+ "label": "Shot 14",+ "seconds": 2,+ "color": "#1a1a1a"+ },+ {+ "seconds": 2,+ "label": "Shot 15",+ "color": "#1a1a1a"+ },+ {+ "seconds": 2,+ "label": "Shot 16",+ "color": "#1a1a1a"+ },+ {+ "seconds": 2,+ "color": "#1a1a1a",+ "label": "Shot 17"+ },+ {+ "label": "Shot 18",+ "seconds": 2,+ "color": "#1a1a1a"+ },+ {+ "label": "Shot 19",+ "color": "#1a1a1a",+ "seconds": 2+ },+ {+ "color": "#1a1a1a",+ "label": "Shot 20",+ "seconds": 2+ },+ {+ "seconds": 2,+ "color": "#1a1a1a",+ "label": "Shot 21"+ },+ {+ "label": "Shot 22",+ "color": "#1a1a1a",+ "seconds": 2+ },+ {+ "label": "Shot 23",+ "color": "#1a1a1a",+ "seconds": 2+ },+ {+ "label": "Shot 24",+ "color": "#1a1a1a",+ "seconds": 2+ },+ {+ "label": "Shot 25",+ "seconds": 2,+ "color": "#1a1a1a"+ },+ {+ "seconds": 2,+ "label": "Shot 26",+ "color": "#1a1a1a"+ },+ {+ "color": "#1a1a1a",+ "label": "Shot 27",+ "seconds": 2+ },+ {+ "color": "#1a1a1a",+ "label": "Shot 28",+ "seconds": 2+ },+ {+ "seconds": 2,+ "label": "Shot 29",+ "color": "#1a1a1a"+ },+ {+ "seconds": 2,+ "label": "Shot 30",+ "color": "#1a1a1a"+ },+ {+ "seconds": 2,+ "label": "Shot 31",+ "color": "#1a1a1a"+ },+ {+ "color": "#1a1a1a",+ "label": "Shot 32",+ "seconds": 2+ },+ {+ "label": "Shot 33",+ "seconds": 2,+ "color": "#1a1a1a"+ },+ {+ "color": "#1a1a1a",+ "label": "Shot 34",+ "seconds": 2+ },+ {+ "color": "#1a1a1a",+ "label": "Shot 35",+ "seconds": 2+ },+ {+ "label": "Shot 36",+ "seconds": 1.6,+ "color": "#1a1a1a"+ }+ ]+ }+ },+ {+ "name": "add_title",+ "round": 12,+ "atMs": 33018.68437499995,+ "execMs": 0.0033340000081807375,+ "args": {+ "end": 2,+ "font": "archivo-black",+ "stroke_width": 0.04,+ "stroke_color": "#000000",+ "color": "#FFEB3B",+ "text": "4.6 YEARS UNTIL I\nNEVER WORK AGAIN",+ "size": 84,+ "weight": 700,+ "start": 0,+ "line_height": 1.1,+ "x": 0.5,+ "y": 0.42+ }+ },+ {+ "name": "compare_to_source",+ "round": 13,+ "atMs": 34935.40466700005,+ "execMs": 0.005375000066123903,+ "args": {+ "times": [+ 1+ ],+ "asset_id": "a-ref1"+ }+ },+ {+ "name": "get_state",+ "round": 15,+ "atMs": 39551.863459000015,+ "execMs": 0.014167000073939562,+ "args": {}+ },+ {+ "name": "add_clip",+ "round": 16,+ "atMs": 46965.54874999996,+ "execMs": 0.022790999966673553,+ "args": {+ "blocks": [+ {+ "seconds": 2,+ "label": "Talking Head 1",+ "color": "#1a1a1a"+ },+ {+ "label": "Talking Head 2",+ "color": "#1a1a1a",+ "seconds": 2+ },+ {+ "seconds": 2,+ "label": "Talking Head 3",+ "color": "#1a1a1a"+ },+ {+ "seconds": 2,+ "label": "Talking Head 4",+ "color": "#1a1a1a"+ },+ {+ "color": "#1a1a1a",+ "label": "Talking Head 5",+ "seconds": 2+ },+ {+ "color": "#1a1a1a",+ "label": "Talking Head 6",+ "seconds": 2+ },+ {+ "color": "#1a1a1a",+ "seconds": 2,+ "label": "Talking Head 7"+ },+ {+ "seconds": 2,+ "label": "Talking Head 8",+ "color": "#1a1a1a"+ },+ {+ "color": "#1a1a1a",+ "label": "Talking Head 9",+ "seconds": 2+ },+ {+ "seconds": 2,+ "label": "Talking Head 10",+ "color": "#1a1a1a"+ },+ {+ "seconds": 2,+ "color": "#1a1a1a",+ "label": "Talking Head 11"+ },+ {+ "label": "Talking Head 12",+ "color": "#1a1a1a",+ "seconds": 2+ },+ {+ "seconds": 2,+ "label": "Talking Head 13",+ "color": "#1a1a1a"+ },+ {+ "seconds": 2,+ "color": "#1a1a1a",+ "label": "Talking Head 14"+ },+ {+ "seconds": 2,+ "label": "Talking Head 15",+ "color": "#1a1a1a"+ },+ {+ "label": "Talking Head 16",+ "color": "#1a1a1a",+ "seconds": 2+ },+ {+ "color": "#1a1a1a",+ "seconds": 2,+ "label": "Talking Head 17"+ },+ {+ "label": "Talking Head 18",+ "seconds": 2,+ "color": "#1a1a1a"+ },+ {+ "color": "#1a1a1a",+ "label": "Talking Head 19",+ "seconds": 2+ },+ {+ "color": "#1a1a1a",+ "seconds": 2,+ "label": "Talking Head 20"+ },+ {+ "label": "Talking Head 21",+ "color": "#1a1a1a",+ "seconds": 2+ },+ {+ "seconds": 2,+ "label": "Talking Head 22",+ "color": "#1a1a1a"+ },+ {+ "seconds": 2,+ "color": "#1a1a1a",+ "label": "Talking Head 23"+ },+ {+ "seconds": 2,+ "label": "Talking Head 24",+ "color": "#1a1a1a"+ },+ {+ "label": "Talking Head 25",+ "seconds": 2,+ "color": "#1a1a1a"+ },+ {+ "color": "#1a1a1a",+ "label": "Talking Head 26",+ "seconds": 2+ },+ {+ "seconds": 2,+ "color": "#1a1a1a",+ "label": "Talking Head 27"+ },+ {+ "color": "#1a1a1a",+ "label": "Talking Head 28",+ "seconds": 2+ },+ {+ "seconds": 2,+ "label": "Talking Head 29",+ "color": "#1a1a1a"+ },+ {+ "color": "#1a1a1a",+ "seconds": 2,+ "label": "Talking Head 30"+ },+ {+ "color": "#1a1a1a",+ "label": "Talking Head 31",+ "seconds": 2+ },+ {+ "seconds": 2,+ "color": "#1a1a1a",+ "label": "Talking Head 32"+ },+ {+ "seconds": 2,+ "color": "#1a1a1a",+ "label": "Talking Head 33"+ },+ {+ "label": "Talking Head 34",+ "color": "#1a1a1a",+ "seconds": 2+ },+ {+ "label": "Talking Head 35",+ "seconds": 2,+ "color": "#1a1a1a"+ },+ {+ "seconds": 1.6,+ "label": "Talking Head 36",+ "color": "#1a1a1a"+ }+ ]+ }+ },+ {+ "name": "get_state",+ "round": 18,+ "atMs": 57080.39316700003,+ "execMs": 0.024834000039845705,+ "args": {}+ }+ ],+ "timings": {+ "gateMs": 301.26170800009277,+ "gateSkipped": false,+ "ttftMs": 36839.36379199999,+ "modelMs": 59014.770918000024,+ "toolMs": 3.0422510001808405,+ "totalMs": 59870.99829200003,+ "judgeMs": 358.0040000000736,+ "retryMs": 0,+ "retries": 0,+ "rounds": [+ {+ "roundMs": 2151.130375000066,+ "firstDeltaMs": null,+ "calls": [+ {+ "name": "watch_video",+ "execMs": 0.13158299995120615+ }+ ]+ },+ {+ "roundMs": 2363.417000000016,+ "firstDeltaMs": null,+ "calls": [+ {+ "name": "note_source",+ "execMs": 0.01533299998845905+ }+ ]+ },+ {+ "roundMs": 2189.395750000025,+ "firstDeltaMs": null,+ "calls": [+ {+ "name": "watch_video",+ "execMs": 0.02549999998882413+ }+ ]+ },+ {+ "roundMs": 2029.7997090000426,+ "firstDeltaMs": null,+ "calls": [+ {+ "name": "note_source",+ "execMs": 0.007208000053651631+ }+ ]+ },+ {+ "roundMs": 1902.327042000019,+ "firstDeltaMs": null,+ "calls": [+ {+ "name": "watch_video",+ "execMs": 0.029792000073939562+ }+ ]+ },+ {+ "roundMs": 1953.394250000012,+ "firstDeltaMs": null,+ "calls": [+ {+ "name": "note_source",+ "execMs": 0.004750000080093741+ }+ ]+ },+ {+ "roundMs": 2098.0664169999072,+ "firstDeltaMs": null,+ "calls": [+ {+ "name": "watch_video",+ "execMs": 0.039582999888807535+ }+ ]+ },+ {+ "roundMs": 2129.202500000014,+ "firstDeltaMs": null,+ "calls": [+ {+ "name": "note_source",+ "execMs": 0.0017499999376013875+ }+ ]+ },+ {+ "roundMs": 2724.828082999913,+ "firstDeltaMs": null,+ "calls": []+ },+ {+ "roundMs": 1819.6345829999773,+ "firstDeltaMs": null,+ "calls": [+ {+ "name": "detach_audio",+ "execMs": 0.006416999967768788+ }+ ]+ },+ {+ "roundMs": 1872.1347499999683,+ "firstDeltaMs": null,+ "calls": [+ {+ "name": "add_clip",+ "execMs": 2.669542000046931+ }+ ]+ },+ {+ "roundMs": 6542.076791000087,+ "firstDeltaMs": null,+ "calls": [+ {+ "name": "add_clip",+ "execMs": 0.04029200004879385+ }+ ]+ },+ {+ "roundMs": 2918.550667000003,+ "firstDeltaMs": null,+ "calls": [+ {+ "name": "add_title",+ "execMs": 0.0033340000081807375+ }+ ]+ },+ {+ "roundMs": 1915.3446249999106,+ "firstDeltaMs": null,+ "calls": [+ {+ "name": "compare_to_source",+ "execMs": 0.005375000066123903+ }+ ]+ },+ {+ "roundMs": 2251.7953330000164,+ "firstDeltaMs": 1903.3696249999339,+ "calls": []+ },+ {+ "roundMs": 2122.2408329999307,+ "firstDeltaMs": null,+ "calls": [+ {+ "name": "get_state",+ "execMs": 0.014167000073939562+ }+ ]+ },+ {+ "roundMs": 7412.891708999989,+ "firstDeltaMs": null,+ "calls": [+ {+ "name": "add_clip",+ "execMs": 0.022790999966673553+ }+ ]+ },+ {+ "roundMs": 7229.142375000054,+ "firstDeltaMs": 6484.924750000006,+ "calls": []+ },+ {+ "roundMs": 2601.054584000027,+ "firstDeltaMs": null,+ "calls": [+ {+ "name": "get_state",+ "execMs": 0.024834000039845705+ }+ ]+ },+ {+ "roundMs": 2788.343542000046,+ "firstDeltaMs": 2098.1253750000615,+ "calls": []+ }+ ]+ }+ }+ ]+ },+ {+ "name": "remove-grey-ones-scope",+ "bucket": "multi-tool",+ "passRate": 1,+ "budgetBreaches": [],+ "latency": {+ "gateMs": {+ "p50": 332,+ "p95": 339,+ "mean": 326,+ "n": 3+ },+ "ttftMs": {+ "p50": 2780,+ "p95": 3343,+ "mean": 2877,+ "n": 3+ },+ "totalMs": {+ "p50": 2910,+ "p95": 3468,+ "mean": 3000,+ "n": 3+ },+ "modelMs": {+ "p50": 2567,+ "p95": 3132,+ "mean": 2670,+ "n": 3+ },+ "toolMs": {+ "p50": 0,+ "p95": 0,+ "mean": 0,+ "n": 3+ },+ "rounds": {+ "mean": 2,+ "max": 2+ }+ },+ "runs": [+ {+ "pass": true,+ "intent": "simple",+ "skill": null,+ "areas": [+ "preview",+ "timeline",+ "inspector",+ "effects",+ "animation",+ "transitions",+ "editor"+ ],+ "declaredTools": 73,+ "routingMisses": [],+ "roundModel": "gemini-3.1-flash-lite",+ "notes": [],+ "instant": null,+ "qualityGate": [],+ "judgeNote": null,+ "trace": [+ {+ "name": "remove_transition",+ "round": 0,+ "atMs": 2097.5943330000155,+ "execMs": 0.13962500006891787,+ "args": {+ "transitionId": "tr-8"+ }+ },+ {+ "name": "remove_transition",+ "round": 0,+ "atMs": 2097.8902499999385,+ "execMs": 0.001541999983601272,+ "args": {+ "transitionId": "tr-9"+ }+ }+ ],+ "timings": {+ "gateMs": 332.49479200004134,+ "gateSkipped": false,+ "ttftMs": 3342.98675000004,+ "modelMs": 3132.257249999908,+ "toolMs": 0.14116700005251914,+ "totalMs": 3467.7593329999363,+ "judgeMs": 201.20833299995866,+ "retryMs": 0,+ "retries": 0,+ "rounds": [+ {+ "roundMs": 1763.6550419999985,+ "firstDeltaMs": null,+ "calls": [+ {+ "name": "remove_transition",+ "execMs": 0.13962500006891787+ },+ {+ "name": "remove_transition",+ "execMs": 0.001541999983601272+ }+ ]+ },+ {+ "roundMs": 1368.6022079999093,+ "firstDeltaMs": 1244.1644159998978,+ "calls": []+ }+ ]+ }+ },+ {+ "pass": true,+ "intent": "simple",+ "skill": null,+ "areas": [+ "preview",+ "timeline",+ "inspector",+ "effects",+ "animation",+ "transitions",+ "editor"+ ],+ "declaredTools": 73,+ "routingMisses": [],+ "roundModel": "gemini-3.1-flash-lite",+ "notes": [],+ "instant": null,+ "qualityGate": [],+ "judgeNote": null,+ "trace": [+ {+ "name": "remove_transition",+ "round": 0,+ "atMs": 1573.5173749999376,+ "execMs": 0.005667000077664852,+ "args": {+ "transitionId": "tr-8"+ }+ },+ {+ "name": "remove_transition",+ "round": 0,+ "atMs": 1573.986042000004,+ "execMs": 0.0034169999416917562,+ "args": {+ "transitionId": "tr-9"+ }+ }+ ],+ "timings": {+ "gateMs": 338.90870799997356,+ "gateSkipped": false,+ "ttftMs": 2780.159624999971,+ "modelMs": 2567.4020819999278,+ "toolMs": 0.009084000019356608,+ "totalMs": 2910.2213749999646,+ "judgeMs": 230.54316699993797,+ "retryMs": 0,+ "retries": 0,+ "rounds": [+ {+ "roundMs": 1232.939916000003,+ "firstDeltaMs": null,+ "calls": [+ {+ "name": "remove_transition",+ "execMs": 0.005667000077664852+ },+ {+ "name": "remove_transition",+ "execMs": 0.0034169999416917562+ }+ ]+ },+ {+ "roundMs": 1334.4621659999248,+ "firstDeltaMs": 1204.9325829999289,+ "calls": []+ }+ ]+ }+ },+ {+ "pass": true,+ "intent": "simple",+ "skill": null,+ "areas": [+ "preview",+ "timeline",+ "inspector",+ "effects",+ "animation",+ "transitions",+ "editor"+ ],+ "declaredTools": 73,+ "routingMisses": [],+ "roundModel": "gemini-3.1-flash-lite",+ "notes": [],+ "instant": null,+ "qualityGate": [],+ "judgeNote": null,+ "trace": [+ {+ "name": "remove_transition",+ "round": 0,+ "atMs": 1470.7916250000708,+ "execMs": 0.004791999934241176,+ "args": {+ "transitionId": "tr-8"+ }+ },+ {+ "name": "remove_transition",+ "round": 0,+ "atMs": 1470.9183330000378,+ "execMs": 0.001125000067986548,+ "args": {+ "transitionId": "tr-9"+ }+ }+ ],+ "timings": {+ "gateMs": 306.5627910000039,+ "gateSkipped": false,+ "ttftMs": 2508.268374999985,+ "modelMs": 2311.191542000044,+ "toolMs": 0.005917000002227724,+ "totalMs": 2620.5352500000736,+ "judgeMs": 258.4564170000376,+ "retryMs": 0,+ "retries": 0,+ "rounds": [+ {+ "roundMs": 1162.6628750000382,+ "firstDeltaMs": null,+ "calls": [+ {+ "name": "remove_transition",+ "execMs": 0.004791999934241176+ },+ {+ "name": "remove_transition",+ "execMs": 0.001125000067986548+ }+ ]+ },+ {+ "roundMs": 1148.528667000006,+ "firstDeltaMs": 1036.4800420000684,+ "calls": []+ }+ ]+ }+ }+ ]+ },+ {+ "name": "errored-call-not-claimed-done",+ "bucket": "single-tool",+ "passRate": 1,+ "budgetBreaches": [],+ "latency": {+ "gateMs": {+ "p50": 301,+ "p95": 457,+ "mean": 348,+ "n": 3+ },+ "ttftMs": {+ "p50": 3965,+ "p95": 7080,+ "mean": 4943,+ "n": 3+ },+ "totalMs": {+ "p50": 4419,+ "p95": 7514,+ "mean": 5428,+ "n": 3+ },+ "modelMs": {+ "p50": 3814,+ "p95": 6958,+ "mean": 4839,+ "n": 3+ },+ "toolMs": {+ "p50": 0,+ "p95": 0,+ "mean": 0,+ "n": 3+ },+ "rounds": {+ "mean": 3,+ "max": 3+ }+ },+ "runs": [+ {+ "pass": true,+ "intent": "simple",+ "skill": null,+ "areas": [+ "preview",+ "timeline",+ "inspector",+ "effects",+ "transitions"+ ],+ "declaredTools": 67,+ "routingMisses": [],+ "roundModel": "gemini-3.1-flash-lite",+ "notes": [],+ "instant": "set_transition",+ "qualityGate": [],+ "judgeNote": null,+ "trace": [+ {+ "name": "set_transition",+ "round": 0,+ "atMs": 288.18920800008345,+ "execMs": 0.04779099998995662,+ "args": {+ "clipId": "c2",+ "style": "crossfade",+ "seconds": 0.2+ }+ },+ {+ "name": "set_transition",+ "round": 1,+ "atMs": 6061.827291000052,+ "execMs": 0.027624999987892807,+ "args": {+ "seconds": 0.5,+ "style": "crossfade",+ "clipId": "c2"+ }+ }+ ],+ "timings": {+ "gateMs": 286.5878340000054,+ "gateSkipped": false,+ "ttftMs": 7079.678458000068,+ "modelMs": 6958.492833000026,+ "toolMs": 0.07541599997784942,+ "totalMs": 7513.968165999977,+ "judgeMs": 329.7229170000646,+ "retryMs": 0,+ "retries": 0,+ "rounds": [+ {+ "roundMs": 4488.138917000033,+ "firstDeltaMs": null,+ "calls": []+ },+ {+ "roundMs": 1283.171500000055,+ "firstDeltaMs": null,+ "calls": [+ {+ "name": "set_transition",+ "execMs": 0.027624999987892807+ }+ ]+ },+ {+ "roundMs": 1187.1824159999378,+ "firstDeltaMs": 1016.874749999959,+ "calls": []+ }+ ]+ }+ },+ {+ "pass": true,+ "intent": "simple",+ "skill": null,+ "areas": [+ "preview",+ "timeline",+ "inspector",+ "effects",+ "transitions",+ "editor"+ ],+ "declaredTools": 71,+ "routingMisses": [],+ "roundModel": "gemini-3.1-flash-lite",+ "notes": [],+ "instant": "set_transition",+ "qualityGate": [],+ "judgeNote": null,+ "trace": [+ {+ "name": "set_transition",+ "round": 0,+ "atMs": 301.01533299998846,+ "execMs": 0.012875000014901161,+ "args": {+ "clipId": "c2",+ "style": "crossfade",+ "seconds": 0.19+ }+ },+ {+ "name": "set_transition",+ "round": 1,+ "atMs": 2905.997040999937,+ "execMs": 0.01779099996201694,+ "args": {+ "clipId": "c2",+ "style": "crossfade",+ "seconds": 0.5+ }+ }+ ],+ "timings": {+ "gateMs": 300.7593329999363,+ "gateSkipped": false,+ "ttftMs": 3785.6064999999944,+ "modelMs": 3814.476918000146,+ "toolMs": 0.0306659999769181,+ "totalMs": 4351.899416,+ "judgeMs": 198.83600000001024,+ "retryMs": 0,+ "retries": 0,+ "rounds": [+ {+ "roundMs": 1343.8409170000814,+ "firstDeltaMs": null,+ "calls": []+ },+ {+ "roundMs": 1259.3202920000767,+ "firstDeltaMs": null,+ "calls": [+ {+ "name": "set_transition",+ "execMs": 0.01779099996201694+ }+ ]+ },+ {+ "roundMs": 1211.3157089999877,+ "firstDeltaMs": 878.1186249998864,+ "calls": []+ }+ ]+ }+ },+ {+ "pass": true,+ "intent": "simple",+ "skill": null,+ "areas": [+ "preview",+ "timeline",+ "inspector",+ "effects",+ "transitions"+ ],+ "declaredTools": 67,+ "routingMisses": [],+ "roundModel": "gemini-3.1-flash-lite",+ "notes": [],+ "instant": "set_transition",+ "qualityGate": [],+ "judgeNote": null,+ "trace": [+ {+ "name": "set_transition",+ "round": 0,+ "atMs": 457.28316600003745,+ "execMs": 0.02616700006183237,+ "args": {+ "clipId": "c2",+ "style": "crossfade",+ "seconds": 0.21+ }+ },+ {+ "name": "set_transition",+ "round": 1,+ "atMs": 2775.8807080000406,+ "execMs": 0.04191699996590614,+ "args": {+ "clipId": "c2",+ "seconds": 0.5,+ "style": "crossfade"+ }+ }+ ],+ "timings": {+ "gateMs": 456.5734170000069,+ "gateSkipped": false,+ "ttftMs": 3964.6268329999875,+ "modelMs": 3745.0069170000497,+ "toolMs": 0.06808400002773851,+ "totalMs": 4418.885790999979,+ "judgeMs": 250.55925000004936,+ "retryMs": 0,+ "retries": 0,+ "rounds": [+ {+ "roundMs": 1152.3065840000054,+ "firstDeltaMs": null,+ "calls": []+ },+ {+ "roundMs": 1162.9895000000251,+ "firstDeltaMs": null,+ "calls": [+ {+ "name": "set_transition",+ "execMs": 0.04191699996590614+ }+ ]+ },+ {+ "roundMs": 1429.7108330000192,+ "firstDeltaMs": 1187.8084580000723,+ "calls": []}- },+ ]+ }+ }+ ]+ },+ {+ "name": "auto-continue-no-handoff",+ "bucket": "multi-tool",+ "passRate": 1,+ "budgetBreaches": [],+ "latency": {+ "gateMs": {+ "p50": 297,+ "p95": 302,+ "mean": 299,+ "n": 3+ },+ "ttftMs": {+ "p50": 5258,+ "p95": 6719,+ "mean": 5623,+ "n": 3+ },+ "totalMs": {+ "p50": 5744,+ "p95": 7115,+ "mean": 6073,+ "n": 3+ },+ "modelMs": {+ "p50": 5443,+ "p95": 6808,+ "mean": 5770,+ "n": 3+ },+ "toolMs": {+ "p50": 0,+ "p95": 0,+ "mean": 0,+ "n": 3+ },+ "rounds": {+ "mean": 3.3,+ "max": 4+ }+ },+ "runs": [+ {+ "pass": true,+ "intent": "simple",+ "skill": null,+ "areas": [+ "preview",+ "timeline",+ "inspector",+ "subtitles",+ "library",+ "editor"+ ],+ "declaredTools": 90,+ "routingMisses": [],+ "roundModel": "gemini-3.1-flash-lite",+ "notes": [],+ "instant": null,+ "qualityGate": [],+ "judgeNote": null,+ "trace": [{- "name": "add_title",- "round": 7,- "atMs": 22201.69650000002,- "execMs": 0.022083999996539205,+ "name": "update_cue",+ "round": 0,+ "atMs": 2458.586917000008,+ "execMs": 0.050249999971129,"args": {- "font": "archivo-black",- "text": "4.6 YEARS UNTIL I NEVER WORK AGAIN",- "end": 4,- "y": 0.35,- "size": 88,- "color": "#FFD700",- "start": 0,- "x": 0.5,- "weight": 700+ "text": "Today we're",+ "id": "cue1"}},{- "name": "watch_video",- "round": 9,- "atMs": 26919.320959000004,- "execMs": 0.03233399998862296,+ "name": "update_cue",+ "round": 0,+ "atMs": 2458.7164999999804,+ "execMs": 0.005166999995708466,"args": {- "asset_id": "a-ref1",- "interval_seconds": 0.5,- "to": 10,- "from": 0+ "text": "and",+ "id": "cue3"}},{- "name": "get_state",- "round": 10,- "atMs": 28808.375250000012,- "execMs": 0.05308300000615418,- "args": {}- },- {- "name": "add_placeholders",- "round": 11,- "atMs": 33194.522417,- "execMs": 0.035416999977314845,+ "name": "align_to_audio",+ "round": 1,+ "atMs": 4054.1312919999473,+ "execMs": 0.006249999976716936,"args": {- "start": 0,- "shots": [- {- "label": "Talking head - opening hook",- "from": 0,- "seconds": 2- },- {- "from": 2,- "seconds": 2,- "label": "Talking head"- },- {- "label": "Talking head",- "seconds": 2,- "from": 4- },- {- "seconds": 2,- "from": 6,- "label": "Talking head"- },- {- "label": "Talking head",- "seconds": 2,- "from": 8- },- {- "label": "Talking head",- "seconds": 2,- "from": 10- },- {- "seconds": 2,- "from": 12,- "label": "Talking head"- },- {- "seconds": 2,- "from": 14,- "label": "Talking head"- },- {- "from": 16,- "seconds": 2,- "label": "Talking head"- },- {- "label": "Talking head",- "seconds": 2,- "from": 18- },- {- "seconds": 2,- "label": "Talking head",- "from": 20- },- {- "seconds": 2,- "label": "Talking head",- "from": 22- },- {- "label": "Talking head",- "seconds": 2,- "from": 24- },- {- "from": 26,- "label": "Talking head",- "seconds": 2- },- {- "label": "Talking head",- "seconds": 2,- "from": 28- },- {- "label": "Talking head",- "seconds": 2,- "from": 30- },- {- "label": "Talking head",- "from": 32,- "seconds": 2- },- {- "label": "Talking head",- "seconds": 2,- "from": 34- },- {- "seconds": 2,- "label": "Talking head",- "from": 36- },- {- "from": 38,- "seconds": 2,- "label": "Talking head"- },- {- "label": "Talking head",- "from": 40,- "seconds": 2- },- {- "seconds": 2,- "label": "Talking head",- "from": 42- },- {- "label": "Talking head",- "seconds": 2,- "from": 44- },- {- "seconds": 2,- "label": "Talking head",- "from": 46- },- {- "from": 48,- "label": "Talking head",- "seconds": 2- },- {- "seconds": 2,- "label": "Talking head",- "from": 50- },- {- "seconds": 2,- "from": 52,- "label": "Talking head"- },- {- "label": "Talking head",- "seconds": 2,- "from": 54- },- {- "seconds": 2,- "label": "Talking head",- "from": 56- },- {- "from": 58,- "label": "Talking head",- "seconds": 2- },- {- "seconds": 2,- "label": "Talking head",- "from": 60- },- {- "from": 62,- "label": "Talking head",- "seconds": 2- },- {- "label": "Talking head",- "from": 64,- "seconds": 2- },+ "track": 0,+ "target": "captions"+ }+ }+ ],+ "timings": {+ "gateMs": 296.934666999965,+ "gateSkipped": false,+ "ttftMs": 5258.275582999922,+ "modelMs": 5443.119707000093,+ "toolMs": 0.0616669999435544,+ "totalMs": 5743.867291999981,+ "judgeMs": 224.02866700000595,+ "retryMs": 0,+ "retries": 0,+ "rounds": [+ {+ "roundMs": 2160.697166000027,+ "firstDeltaMs": null,+ "calls": [{- "seconds": 2,- "from": 66,- "label": "Talking head"+ "name": "update_cue",+ "execMs": 0.050249999971129},{- "label": "Talking head",- "seconds": 2,- "from": 68- },+ "name": "update_cue",+ "execMs": 0.005166999995708466+ }+ ]+ },+ {+ "roundMs": 1594.5442080000648,+ "firstDeltaMs": null,+ "calls": [{- "seconds": 1.6,- "label": "Talking head - outro",- "from": 70+ "name": "align_to_audio",+ "execMs": 0.006249999976716936}- ],- "source_asset_id": "a-ref1"+ ]+ },+ {+ "roundMs": 1687.8783330000006,+ "firstDeltaMs": 1202.7097500000382,+ "calls": []}- },+ ]+ }+ },+ {+ "pass": true,+ "intent": "simple",+ "skill": null,+ "areas": [+ "preview",+ "timeline",+ "inspector",+ "subtitles",+ "library",+ "editor"+ ],+ "declaredTools": 90,+ "routingMisses": [],+ "roundModel": "gemini-3.1-flash-lite",+ "notes": [],+ "instant": null,+ "qualityGate": [],+ "judgeNote": null,+ "trace": [{- "name": "set_overlay_animation",- "round": 12,- "atMs": 38527.49550000002,- "execMs": 0.01187499999650754,+ "name": "update_cue",+ "round": 0,+ "atMs": 2001.020790999988,+ "execMs": 0.009874999988824129,"args": {- "in_style": "pop",- "id": "o1",- "out_seconds": 0.3,- "out_style": "fade",- "in_seconds": 0.3+ "text": "Today we're",+ "id": "cue1"}},{- "name": "get_state",- "round": 14,- "atMs": 43035.07966700001,- "execMs": 0.02291599998716265,- "args": {}- },- {- "name": "listen_audio",- "round": 15,- "atMs": 45086.617375,- "execMs": 0.05874999999650754,+ "name": "update_cue",+ "round": 0,+ "atMs": 2001.1779579999857,+ "execMs": 0.01629200007300824,"args": {- "asset_id": "a-ref1",- "from": 0,- "to": 30+ "id": "cue3",+ "text": "they play"}},{- "name": "add_clip",- "round": 16,- "atMs": 47151.757292000024,- "execMs": 0.5747919999994338,+ "name": "align_to_audio",+ "round": 1,+ "atMs": 3748.931957999943,+ "execMs": 0.004249999998137355,"args": {- "start": 0,- "asset_id": "a-ref1"+ "target": "captions",+ "track": 0}},{- "name": "get_state",- "round": 17,- "atMs": 49045.877750000014,- "execMs": 0.023917000013170764,- "args": {}+ "name": "update_cue",+ "round": 2,+ "atMs": 5398.819166000001,+ "execMs": 0.01808299997355789,+ "args": {+ "text": "Today we're",+ "id": "cue1",+ "start": 0.9,+ "end": 1.8+ }},{- "name": "watch_video",- "round": 18,- "atMs": 51077.644,- "execMs": 0.035042000003159046,+ "name": "update_cue",+ "round": 2,+ "atMs": 5398.967249999987,+ "execMs": 0.016792000038549304,"args": {- "to": 71.6,- "from": 0,- "asset_id": "a-ref1",- "interval_seconds": 1+ "id": "cue3",+ "start": 5.2,+ "end": 5.6,+ "text": "they play"}}],"timings": {- "gateMs": 298.4326669999864,+ "gateMs": 302.2190410000039,"gateSkipped": false,- "ttftMs": 23835.078542000003,- "modelMs": 54422.93637399995,- "toolMs": 1.2773770000203513,- "totalMs": 56595.07720900001,+ "ttftMs": 6718.881374999997,+ "modelMs": 6807.91866700002,+ "toolMs": 0.06529200007207692,+ "totalMs": 7115.108415999915,+ "judgeMs": 228.49795899994206,"retryMs": 0,"retries": 0,"rounds": [{- "roundMs": 3045.3337919999904,+ "roundMs": 1697.326000000001,"firstDeltaMs": null,"calls": [{- "name": "watch_video",- "execMs": 0.1794590000063181- }- ]- },- {- "roundMs": 2521.8455419999955,- "firstDeltaMs": null,- "calls": [+ "name": "update_cue",+ "execMs": 0.009874999988824129+ },{- "name": "note_source",- "execMs": 0.0052090000244788826+ "name": "update_cue",+ "execMs": 0.01629200007300824}]},{- "roundMs": 2062.9651669999876,+ "roundMs": 1746.545000000042,"firstDeltaMs": null,"calls": [{- "name": "watch_video",- "execMs": 0.027750000008381903+ "name": "align_to_audio",+ "execMs": 0.004249999998137355}]},{- "roundMs": 2085.39495799999,+ "roundMs": 1649.076250000042,"firstDeltaMs": null,"calls": [{- "name": "note_source",- "execMs": 0.002582999994046986- }- ]- },- {- "roundMs": 2160.5252079999773,- "firstDeltaMs": null,- "calls": [+ "name": "update_cue",+ "execMs": 0.01808299997355789+ },{- "name": "watch_video",- "execMs": 0.04379200001130812+ "name": "update_cue",+ "execMs": 0.016792000038549304}]},{- "roundMs": 3076.175957999978,+ "roundMs": 1714.9714169999352,+ "firstDeltaMs": 1318.9660419999855,+ "calls": []+ }+ ]+ }+ },+ {+ "pass": true,+ "intent": "simple",+ "skill": null,+ "areas": [+ "preview",+ "timeline",+ "inspector",+ "subtitles",+ "library",+ "editor"+ ],+ "declaredTools": 90,+ "routingMisses": [],+ "roundModel": "gemini-3.1-flash-lite",+ "notes": [],+ "instant": null,+ "qualityGate": [],+ "judgeNote": null,+ "trace": [+ {+ "name": "update_cue",+ "round": 0,+ "atMs": 1945.1699580000713,+ "execMs": 0.012666000053286552,+ "args": {+ "id": "cue1",+ "text": "So today we're"+ }+ },+ {+ "name": "update_cue",+ "round": 0,+ "atMs": 1945.3039580000332,+ "execMs": 0.015875000040978193,+ "args": {+ "text": "and they",+ "id": "cue3"+ }+ },+ {+ "name": "align_to_audio",+ "round": 1,+ "atMs": 3591.2255420000292,+ "execMs": 0.0031660000095143914,+ "args": {+ "target": "captions",+ "track": 0+ }+ }+ ],+ "timings": {+ "gateMs": 297.4486249999609,+ "gateSkipped": false,+ "ttftMs": 4890.999582999968,+ "modelMs": 5059.223957999959,+ "toolMs": 0.03170700010377914,+ "totalMs": 5360.604875000077,+ "judgeMs": 210.88808300008532,+ "retryMs": 0,+ "retries": 0,+ "rounds": [+ {+ "roundMs": 1646.3052090000128,"firstDeltaMs": null,"calls": [{- "name": "note_source",- "execMs": 0.01770799999940209+ "name": "update_cue",+ "execMs": 0.012666000053286552+ },+ {+ "name": "update_cue",+ "execMs": 0.015875000040978193}]},{- "roundMs": 4813.9630419999885,+ "roundMs": 1644.7147079999559,"firstDeltaMs": null,"calls": [{- "name": "add_placeholders",- "execMs": 0.1306660000118427+ "name": "align_to_audio",+ "execMs": 0.0031660000095143914}]},{- "roundMs": 2111.675958000007,+ "roundMs": 1768.20404099999,+ "firstDeltaMs": 1298.895166000002,+ "calls": []+ }+ ]+ }+ }+ ]+ },+ {+ "name": "question-when-ambiguous",+ "bucket": "chat",+ "passRate": 1,+ "budgetBreaches": [],+ "latency": {+ "gateMs": {+ "p50": 283,+ "p95": 309,+ "mean": 286,+ "n": 3+ },+ "ttftMs": {+ "p50": 5979,+ "p95": 7101,+ "mean": 5990,+ "n": 3+ },+ "totalMs": {+ "p50": 6340,+ "p95": 7448,+ "mean": 6382,+ "n": 3+ },+ "modelMs": {+ "p50": 5850,+ "p95": 6862,+ "mean": 5855,+ "n": 3+ },+ "toolMs": {+ "p50": 0,+ "p95": 0,+ "mean": 0,+ "n": 3+ },+ "rounds": {+ "mean": 1,+ "max": 1+ }+ },+ "runs": [+ {+ "pass": true,+ "intent": "complex",+ "skill": "timeline-editing",+ "areas": [+ "preview",+ "timeline",+ "inspector",+ "library",+ "editor"+ ],+ "declaredTools": 77,+ "routingMisses": [],+ "roundModel": "gemini-3.8-flash",+ "notes": [],+ "instant": null,+ "qualityGate": [],+ "judgeNote": null,+ "trace": [],+ "timings": {+ "gateMs": 309.3911659999285,+ "gateSkipped": false,+ "ttftMs": 7101.408166000037,+ "modelMs": 6861.569957999978,+ "toolMs": 0,+ "totalMs": 7448.010791000095,+ "judgeMs": 231.86612500005867,+ "retryMs": 0,+ "retries": 0,+ "rounds": [+ {+ "roundMs": 6861.569957999978,+ "firstDeltaMs": 6790.612833000021,+ "calls": []+ }+ ]+ }+ },+ {+ "pass": true,+ "intent": "complex",+ "skill": "timeline-editing",+ "areas": [+ "preview",+ "timeline",+ "inspector",+ "editor"+ ],+ "declaredTools": 70,+ "routingMisses": [],+ "roundModel": "gemini-3.8-flash",+ "notes": [],+ "instant": null,+ "qualityGate": [],+ "judgeNote": null,+ "trace": [],+ "timings": {+ "gateMs": 267.1626670000842,+ "gateSkipped": false,+ "ttftMs": 5978.738708000048,+ "modelMs": 5850.395832999959,+ "toolMs": 0,+ "totalMs": 6339.920958000002,+ "judgeMs": 210.21554200001992,+ "retryMs": 0,+ "retries": 0,+ "rounds": [+ {+ "roundMs": 5850.395832999959,+ "firstDeltaMs": 5709.851792000001,+ "calls": []+ }+ ]+ }+ },+ {+ "pass": true,+ "intent": "complex",+ "skill": "timeline-editing",+ "areas": [+ "preview",+ "timeline",+ "inspector",+ "library",+ "editor"+ ],+ "declaredTools": 77,+ "routingMisses": [],+ "roundModel": "gemini-3.8-flash",+ "notes": [],+ "instant": null,+ "qualityGate": [],+ "judgeNote": null,+ "trace": [],+ "timings": {+ "gateMs": 282.731541999965,+ "gateSkipped": false,+ "ttftMs": 4889.53891699994,+ "modelMs": 4852.281040999922,+ "toolMs": 0,+ "totalMs": 5357.837666999898,+ "judgeMs": 205.09566600003745,+ "retryMs": 0,+ "retries": 0,+ "rounds": [+ {+ "roundMs": 4852.281040999922,+ "firstDeltaMs": 4606.070915999939,+ "calls": []+ }+ ]+ }+ }+ ]+ },+ {+ "name": "orphaned-overlay-debris",+ "bucket": "multi-tool",+ "passRate": 1,+ "budgetBreaches": [],+ "latency": {+ "gateMs": {+ "p50": 314,+ "p95": 388,+ "mean": 322,+ "n": 3+ },+ "ttftMs": {+ "p50": 6042,+ "p95": 9783,+ "mean": 6096,+ "n": 3+ },+ "totalMs": {+ "p50": 6242,+ "p95": 10061,+ "mean": 6383,+ "n": 3+ },+ "modelMs": {+ "p50": 5925,+ "p95": 9670,+ "mean": 6058,+ "n": 3+ },+ "toolMs": {+ "p50": 0,+ "p95": 0,+ "mean": 0,+ "n": 3+ },+ "rounds": {+ "mean": 2,+ "max": 2+ }+ },+ "runs": [+ {+ "pass": true,+ "intent": "simple",+ "skill": null,+ "areas": [+ "preview",+ "timeline",+ "inspector",+ "top_bar",+ "editor"+ ],+ "declaredTools": 74,+ "routingMisses": [],+ "roundModel": "gemini-3.1-flash-lite",+ "notes": [],+ "instant": null,+ "qualityGate": [],+ "judgeNote": null,+ "trace": [+ {+ "name": "trim_clip",+ "round": 0,+ "atMs": 8593.476040999987,+ "execMs": 0.13020800007507205,+ "args": {+ "clipId": "c1",+ "out": 10+ }+ }+ ],+ "timings": {+ "gateMs": 388.2952090000035,+ "gateSkipped": false,+ "ttftMs": 9783.287708000047,+ "modelMs": 9669.656374999904,+ "toolMs": 0.13020800007507205,+ "totalMs": 10061.404125000001,+ "judgeMs": 294.0668750000186,+ "retryMs": 0,+ "retries": 0,+ "rounds": [+ {+ "roundMs": 8203.397832999937,"firstDeltaMs": null,"calls": [{- "name": "add_title",- "execMs": 0.022083999996539205+ "name": "trim_clip",+ "execMs": 0.13020800007507205}]},{- "roundMs": 2213.0891249999986,- "firstDeltaMs": 1631.9469999999856,+ "roundMs": 1466.2585419999668,+ "firstDeltaMs": 1188.611499999999,"calls": []- },- {- "roundMs": 1980.38400000002,- "firstDeltaMs": null,- "calls": [- {- "name": "watch_video",- "execMs": 0.03233399998862296- }- ]- },- {- "roundMs": 1887.7677909999911,- "firstDeltaMs": null,- "calls": [- {- "name": "get_state",- "execMs": 0.05308300000615418- }- ]- },- {- "roundMs": 4385.212958000018,- "firstDeltaMs": null,- "calls": [- {- "name": "add_placeholders",- "execMs": 0.035416999977314845- }- ]- },+ }+ ]+ }+ },+ {+ "pass": true,+ "intent": "simple",+ "skill": null,+ "areas": [+ "preview",+ "timeline",+ "inspector",+ "top_bar",+ "editor"+ ],+ "declaredTools": 74,+ "routingMisses": [],+ "roundModel": "gemini-3.1-flash-lite",+ "notes": [],+ "instant": null,+ "qualityGate": [],+ "judgeNote": null,+ "trace": [+ {+ "name": "trim_clip",+ "round": 0,+ "atMs": 1391.031834000023,+ "execMs": 0.007833999930880964,+ "args": {+ "out": 10,+ "clipId": "c1"+ }+ }+ ],+ "timings": {+ "gateMs": 263.7203749999171,+ "gateSkipped": false,+ "ttftMs": 2464.244249999989,+ "modelMs": 2578.2683749998687,+ "toolMs": 0.007833999930880964,+ "totalMs": 2845.1521250000224,+ "judgeMs": 251.72354100004304,+ "retryMs": 0,+ "retries": 0,+ "rounds": [{- "roundMs": 5330.360167000006,+ "roundMs": 1125.7029169999296,"firstDeltaMs": null,"calls": [{- "name": "set_overlay_animation",- "execMs": 0.01187499999650754+ "name": "trim_clip",+ "execMs": 0.007833999930880964}]},{- "roundMs": 2240.512374999991,- "firstDeltaMs": 1678.7992919999815,+ "roundMs": 1452.565457999939,+ "firstDeltaMs": 1072.1131659999955,"calls": []- },- {- "roundMs": 1598.4076669999922,- "firstDeltaMs": null,- "calls": [- {- "name": "get_state",- "execMs": 0.02291599998716265- }- ]- },- {- "roundMs": 2049.222792000015,- "firstDeltaMs": null,- "calls": [- {- "name": "listen_audio",- "execMs": 0.05874999999650754- }- ]- },+ }+ ]+ }+ },+ {+ "pass": true,+ "intent": "simple",+ "skill": null,+ "areas": [+ "preview",+ "timeline",+ "inspector"+ ],+ "declaredTools": 66,+ "routingMisses": [],+ "roundModel": "gemini-3.1-flash-lite",+ "notes": [],+ "instant": null,+ "qualityGate": [],+ "judgeNote": null,+ "trace": [+ {+ "name": "trim_clip",+ "round": 0,+ "atMs": 4995.075582999969,+ "execMs": 0.008750000037252903,+ "args": {+ "clipId": "c1",+ "out": 10,+ "in": 0+ }+ }+ ],+ "timings": {+ "gateMs": 314.46520900004543,+ "gateSkipped": false,+ "ttftMs": 6041.705915999948,+ "modelMs": 5924.758042000001,+ "toolMs": 0.008750000037252903,+ "totalMs": 6242.069832999958,+ "judgeMs": 327.4109999999637,+ "retryMs": 0,+ "retries": 0,+ "rounds": [{- "roundMs": 2063.125667000015,+ "roundMs": 4679.272750000004,"firstDeltaMs": null,"calls": [{- "name": "add_clip",- "execMs": 0.5747919999994338+ "name": "trim_clip",+ "execMs": 0.008750000037252903}]},{- "roundMs": 1892.2514160000137,- "firstDeltaMs": null,- "calls": [- {- "name": "get_state",- "execMs": 0.023917000013170764- }- ]- },+ "roundMs": 1245.4852919999976,+ "firstDeltaMs": 1045.3875830000034,+ "calls": []+ }+ ]+ }+ }+ ]+ },+ {+ "name": "legacy-thread-no-leak",+ "bucket": "chat",+ "passRate": 1,+ "budgetBreaches": [],+ "latency": {+ "gateMs": {+ "p50": 295,+ "p95": 325,+ "mean": 303,+ "n": 3+ },+ "ttftMs": {+ "p50": 1341,+ "p95": 4189,+ "mean": 2290,+ "n": 3+ },+ "totalMs": {+ "p50": 2064,+ "p95": 4778,+ "mean": 2916,+ "n": 3+ },+ "modelMs": {+ "p50": 1534,+ "p95": 4232,+ "mean": 2392,+ "n": 3+ },+ "toolMs": {+ "p50": 0,+ "p95": 0,+ "mean": 0,+ "n": 3+ },+ "rounds": {+ "mean": 1,+ "max": 1+ }+ },+ "runs": [+ {+ "pass": true,+ "intent": "simple",+ "skill": null,+ "areas": [+ "preview",+ "timeline",+ "inspector",+ "effects",+ "animation",+ "transitions"+ ],+ "declaredTools": 69,+ "routingMisses": [],+ "roundModel": "gemini-3.1-flash-lite",+ "notes": [],+ "instant": null,+ "qualityGate": [],+ "judgeNote": null,+ "trace": [],+ "timings": {+ "gateMs": 294.5056249999907,+ "gateSkipped": false,+ "ttftMs": 4188.674500000081,+ "modelMs": 4232.158459000057,+ "toolMs": 0,+ "totalMs": 4778.277584000025,+ "judgeMs": 190.55870900000446,+ "retryMs": 0,+ "retries": 0,+ "rounds": [{- "roundMs": 2030.2715829999943,- "firstDeltaMs": null,- "calls": [- {- "name": "watch_video",- "execMs": 0.035042000003159046- }- ]- },+ "roundMs": 4232.158459000057,+ "firstDeltaMs": 3892.109541999991,+ "calls": []+ }+ ]+ }+ },+ {+ "pass": true,+ "intent": "simple",+ "skill": null,+ "areas": [+ "preview",+ "timeline",+ "inspector",+ "effects",+ "animation",+ "transitions"+ ],+ "declaredTools": 69,+ "routingMisses": [],+ "roundModel": "gemini-3.1-flash-lite",+ "notes": [],+ "instant": null,+ "qualityGate": [],+ "judgeNote": null,+ "trace": [],+ "timings": {+ "gateMs": 325.06541600008495,+ "gateSkipped": false,+ "ttftMs": 1341.0014580000425,+ "modelMs": 1534.4287909999257,+ "toolMs": 0,+ "totalMs": 2064.325208000024,+ "judgeMs": 300.84645800001454,+ "retryMs": 0,+ "retries": 0,+ "rounds": [{- "roundMs": 2255.8277499999967,- "firstDeltaMs": 1712.4350419999973,+ "roundMs": 1534.4287909999257,+ "firstDeltaMs": 1014.5977499999572,"calls": []- },+ }+ ]+ }+ },+ {+ "pass": true,+ "intent": "simple",+ "skill": null,+ "areas": [+ "preview",+ "timeline",+ "inspector",+ "effects",+ "animation",+ "transitions"+ ],+ "declaredTools": 69,+ "routingMisses": [],+ "roundModel": "gemini-3.1-flash-lite",+ "notes": [],+ "instant": null,+ "qualityGate": [],+ "judgeNote": null,+ "trace": [],+ "timings": {+ "gateMs": 288.61504199996125,+ "gateSkipped": false,+ "ttftMs": 1341.4840829999885,+ "modelMs": 1408.2594579999568,+ "toolMs": 0,+ "totalMs": 1905.2468329999829,+ "judgeMs": 202.67575000005309,+ "retryMs": 0,+ "retries": 0,+ "rounds": [{- "roundMs": 2618.6234579999873,- "firstDeltaMs": 1732.002542000002,+ "roundMs": 1408.2594579999568,+ "firstDeltaMs": 1051.8072920000413,"calls": []}]@@ -4546,44 +13045,44 @@]},{- "name": "remove-grey-ones-scope",- "bucket": "multi-tool",+ "name": "cinematic-ask-picks-preset",+ "bucket": "single-tool","passRate": 1,"budgetBreaches": [],"latency": {"gateMs": {- "p50": 521,- "p95": 521,- "mean": 521,- "n": 1+ "p50": 281,+ "p95": 316,+ "mean": 289,+ "n": 3},"ttftMs": {- "p50": 5658,- "p95": 5658,- "mean": 5658,- "n": 1+ "p50": 281,+ "p95": 316,+ "mean": 290,+ "n": 3},"totalMs": {- "p50": 5962,- "p95": 5962,- "mean": 5962,- "n": 1+ "p50": 281,+ "p95": 316,+ "mean": 290,+ "n": 3},"modelMs": {- "p50": 5435,- "p95": 5435,- "mean": 5435,- "n": 1+ "p50": 0,+ "p95": 0,+ "mean": 0,+ "n": 3},"toolMs": {"p50": 0,"p95": 0,"mean": 0,- "n": 1+ "n": 3},"rounds": {- "mean": 2,- "max": 2+ "mean": 0,+ "max": 0}},"runs": [@@ -4593,108 +13092,174 @@"skill": null,"areas": ["preview",- "timeline","inspector",+ "color","effects",- "animation",- "transitions",- "editor"+ "library",+ "side_panel",+ "top_bar"],- "declaredTools": 71,+ "declaredTools": 62,"routingMisses": [],"roundModel": "gemini-3.1-flash-lite","notes": [],- "instant": null,+ "instant": "set_color_preset",+ "qualityGate": [],"judgeNote": null,"trace": [{- "name": "remove_transition",+ "name": "set_color_preset","round": 0,- "atMs": 4456.801999999996,- "execMs": 0.09841600002255291,+ "atMs": 271.3472499999916,+ "execMs": 0.2413749999832362,"args": {- "transitionId": "tr-8"+ "clipId": "c1",+ "preset": "teal-orange",+ "amount": 0.68}- },+ }+ ],+ "timings": {+ "gateMs": 270.89441599999554,+ "gateSkipped": false,+ "ttftMs": 271.8105000000214,+ "modelMs": 0,+ "toolMs": 0.2413749999832362,+ "totalMs": 271.82199999992736,+ "judgeMs": 240.18416599999182,+ "retryMs": 0,+ "retries": 0,+ "rounds": []+ }+ },+ {+ "pass": true,+ "intent": "simple",+ "skill": null,+ "areas": [+ "preview",+ "inspector",+ "color",+ "effects",+ "library",+ "side_panel",+ "top_bar"+ ],+ "declaredTools": 62,+ "routingMisses": [],+ "roundModel": "gemini-3.1-flash-lite",+ "notes": [],+ "instant": "set_color_preset",+ "qualityGate": [],+ "judgeNote": null,+ "trace": [{- "name": "remove_transition",+ "name": "set_color_preset","round": 0,- "atMs": 4457.216832999984,- "execMs": 0.001125000009778887,+ "atMs": 316.05529100005515,+ "execMs": 0.01837499998509884,"args": {- "transitionId": "tr-9"+ "clipId": "c1",+ "preset": "teal-orange",+ "amount": 0.68}}],"timings": {- "gateMs": 520.9745830000029,+ "gateMs": 315.734832999995,"gateSkipped": false,- "ttftMs": 5657.888875000004,- "modelMs": 5434.934958000027,- "toolMs": 0.0995410000323318,- "totalMs": 5962.104082999984,+ "ttftMs": 316.19758300005924,+ "modelMs": 0,+ "toolMs": 0.01837499998509884,+ "totalMs": 316.21208299999125,+ "judgeMs": 224.74179200001527,"retryMs": 0,"retries": 0,- "rounds": [- {- "roundMs": 3932.5741250000137,- "firstDeltaMs": null,- "calls": [- {- "name": "remove_transition",- "execMs": 0.09841600002255291- },- {- "name": "remove_transition",- "execMs": 0.001125000009778887- }- ]- },- {- "roundMs": 1502.3608330000134,- "firstDeltaMs": 1199.1565000000119,- "calls": []+ "rounds": []+ }+ },+ {+ "pass": true,+ "intent": "simple",+ "skill": null,+ "areas": [+ "preview",+ "inspector",+ "color",+ "effects",+ "side_panel",+ "top_bar"+ ],+ "declaredTools": 55,+ "routingMisses": [],+ "roundModel": "gemini-3.1-flash-lite",+ "notes": [],+ "instant": "set_color_preset",+ "qualityGate": [],+ "judgeNote": null,+ "trace": [+ {+ "name": "set_color_preset",+ "round": 0,+ "atMs": 280.8964579999447,+ "execMs": 0.029541999916546047,+ "args": {+ "clipId": "c1",+ "preset": "teal-orange",+ "amount": 0.68}- ]+ }+ ],+ "timings": {+ "gateMs": 280.60920800000895,+ "gateSkipped": false,+ "ttftMs": 281.0176249999786,+ "modelMs": 0,+ "toolMs": 0.029541999916546047,+ "totalMs": 281.02358299994376,+ "judgeMs": 222.97600000002421,+ "retryMs": 0,+ "retries": 0,+ "rounds": []}}]},{- "name": "errored-call-not-claimed-done",+ "name": "warmer-crushed-blacks-in-range","bucket": "single-tool","passRate": 1,"budgetBreaches": [],"latency": {"gateMs": {- "p50": 846,- "p95": 846,- "mean": 846,- "n": 1+ "p50": 279,+ "p95": 285,+ "mean": 279,+ "n": 3},"ttftMs": {- "p50": 4786,- "p95": 4786,- "mean": 4786,- "n": 1+ "p50": 3518,+ "p95": 8915,+ "mean": 5261,+ "n": 3},"totalMs": {- "p50": 5038,- "p95": 5038,- "mean": 5038,- "n": 1+ "p50": 3598,+ "p95": 8979,+ "mean": 5355,+ "n": 3},"modelMs": {- "p50": 4189,- "p95": 4189,- "mean": 4189,- "n": 1+ "p50": 3310,+ "p95": 8700,+ "mean": 5072,+ "n": 3},"toolMs": {"p50": 0,"p95": 0,"mean": 0,- "n": 1+ "n": 3},"rounds": {"mean": 3,@@ -4708,290 +13273,187 @@"skill": null,"areas": ["preview",- "timeline","inspector",- "effects",- "transitions",- "audio"+ "color",+ "effects"],- "declaredTools": 69,+ "declaredTools": 44,"routingMisses": [],"roundModel": "gemini-3.1-flash-lite","notes": [],- "instant": "set_transition",+ "instant": null,+ "qualityGate": [],"judgeNote": null,"trace": [{- "name": "set_transition",- "round": 0,- "atMs": 846.7186670000083,- "execMs": 0.01708300001337193,- "args": {- "clipId": "c2",- "style": "crossfade",- "seconds": 0.19- }- },- {- "name": "set_transition",+ "name": "set_color_grade","round": 1,- "atMs": 3705.49549999999,- "execMs": 0.0170829999842681,+ "atMs": 7871.148541999981,+ "execMs": 0.16458400001283735,"args": {- "style": "crossfade",- "clipId": "c2",- "seconds": 0.5+ "shadows": -15,+ "temperature": 15,+ "clipId": "c1"}}],"timings": {- "gateMs": 846.2908330000064,+ "gateMs": 272.6927910000086,"gateSkipped": false,- "ttftMs": 4786.45866699997,- "modelMs": 4188.516083000053,- "toolMs": 0.03416599999764003,- "totalMs": 5038.260957999999,+ "ttftMs": 8914.829249999952,+ "modelMs": 8700.419750000117,+ "toolMs": 0.16458400001283735,+ "totalMs": 8979.177000000025,+ "judgeMs": 247.29529199993704,"retryMs": 0,"retries": 0,"rounds": [{- "roundMs": 1317.3540420000209,+ "roundMs": 6100.306125000003,"firstDeltaMs": null,"calls": []},{- "roundMs": 1538.991000000009,+ "roundMs": 1493.093208000064,"firstDeltaMs": null,"calls": [{- "name": "set_transition",- "execMs": 0.0170829999842681+ "name": "set_color_grade",+ "execMs": 0.16458400001283735}]},{- "roundMs": 1332.1710410000233,- "firstDeltaMs": 1080.4870829999854,+ "roundMs": 1107.0204170000507,+ "firstDeltaMs": 1042.8402920000954,"calls": []}]}- }- ]- },- {- "name": "auto-continue-no-handoff",- "bucket": "multi-tool",- "passRate": 1,- "budgetBreaches": [],- "latency": {- "gateMs": {- "p50": 866,- "p95": 866,- "mean": 866,- "n": 1- },- "ttftMs": {- "p50": 5245,- "p95": 5245,- "mean": 5245,- "n": 1- },- "totalMs": {- "p50": 5425,- "p95": 5425,- "mean": 5425,- "n": 1- },- "modelMs": {- "p50": 4555,- "p95": 4555,- "mean": 4555,- "n": 1- },- "toolMs": {- "p50": 0,- "p95": 0,- "mean": 0,- "n": 1},- "rounds": {- "mean": 3,- "max": 3- }- },- "runs": [{"pass": true,"intent": "simple","skill": null,"areas": ["preview",- "timeline","inspector",- "subtitles",- "library",- "editor"+ "color",+ "effects"],- "declaredTools": 88,+ "declaredTools": 44,"routingMisses": [],"roundModel": "gemini-3.1-flash-lite","notes": [],"instant": null,+ "qualityGate": [],"judgeNote": null,"trace": [{- "name": "update_cue",- "round": 0,- "atMs": 2624.5890409999993,- "execMs": 0.059542000002693385,- "args": {- "text": "So today we're",- "id": "cue1"- }- },- {- "name": "update_cue",- "round": 0,- "atMs": 2624.8115000000107,- "execMs": 0.009624999947845936,- "args": {- "text": "and...",- "id": "cue3"- }- },- {- "name": "align_to_audio",+ "name": "set_color_grade","round": 1,- "atMs": 3957.837416000024,- "execMs": 0.005541999998968095,+ "atMs": 2592.940583999967,+ "execMs": 0.006874999962747097,"args": {- "track": 0,- "target": "captions"+ "clipId": "c1",+ "temperature": 20,+ "shadows": -10}}],"timings": {- "gateMs": 865.5596670000232,+ "gateMs": 285.3356249999488,"gateSkipped": false,- "ttftMs": 5244.905000000028,- "modelMs": 4555.360501000017,- "toolMs": 0.07470899994950742,- "totalMs": 5424.956041000027,+ "ttftMs": 3517.742666999926,+ "modelMs": 3309.556333000073,+ "toolMs": 0.006874999962747097,+ "totalMs": 3598.3159999999916,+ "judgeMs": 286.9692919999361,"retryMs": 0,"retries": 0,"rounds": [{- "roundMs": 1757.2150419999962,+ "roundMs": 1254.375,"firstDeltaMs": null,- "calls": [- {- "name": "update_cue",- "execMs": 0.059542000002693385- },- {- "name": "update_cue",- "execMs": 0.009624999947845936- }- ]+ "calls": []},{- "roundMs": 1331.9037920000264,+ "roundMs": 1050.8838329999708,"firstDeltaMs": null,"calls": [{- "name": "align_to_audio",- "execMs": 0.005541999998968095+ "name": "set_color_grade",+ "execMs": 0.006874999962747097}]},{- "roundMs": 1466.2416669999948,- "firstDeltaMs": 1286.3516669999808,+ "roundMs": 1004.2975000001024,+ "firstDeltaMs": 923.9367499999935,"calls": []}]}- }- ]- },- {- "name": "question-when-ambiguous",- "bucket": "chat",- "passRate": 1,- "budgetBreaches": [],- "latency": {- "gateMs": {- "p50": 1024,- "p95": 1024,- "mean": 1024,- "n": 1- },- "ttftMs": {- "p50": 3301,- "p95": 3301,- "mean": 3301,- "n": 1- },- "totalMs": {- "p50": 3390,- "p95": 3390,- "mean": 3390,- "n": 1- },- "modelMs": {- "p50": 2386,- "p95": 2386,- "mean": 2386,- "n": 1- },- "toolMs": {- "p50": 0,- "p95": 0,- "mean": 0,- "n": 1},- "rounds": {- "mean": 2,- "max": 2- }- },- "runs": [{"pass": true,- "intent": "complex",- "skill": "timeline-editing",+ "intent": "simple",+ "skill": null,"areas": ["preview",- "timeline","inspector",- "editor"+ "color",+ "effects"],- "declaredTools": 68,+ "declaredTools": 44,"routingMisses": [],- "roundModel": "gemini-3.8-flash",+ "roundModel": "gemini-3.1-flash-lite","notes": [],"instant": null,+ "qualityGate": [],"judgeNote": null,- "trace": [],+ "trace": [+ {+ "name": "set_color_grade",+ "round": 1,+ "atMs": 2427.673165999935,+ "execMs": 0.009791000047698617,+ "args": {+ "clipId": "c1",+ "temperature": 20,+ "shadows": -10+ }+ }+ ],"timings": {- "gateMs": 1024.3687500000233,+ "gateMs": 279.30174999998417,"gateSkipped": false,- "ttftMs": 3301.290875000006,- "modelMs": 2385.7487919999985,- "toolMs": 0,- "totalMs": 3389.605333000014,+ "ttftMs": 3349.621415999951,+ "modelMs": 3205.25758399989,+ "toolMs": 0.009791000047698617,+ "totalMs": 3488.6754159999546,+ "judgeMs": 260.33887500001583,"retryMs": 0,"retries": 0,"rounds": [{- "roundMs": 21.842791999981273,+ "roundMs": 975.57483399997,"firstDeltaMs": null,"calls": []},{- "roundMs": 2363.9060000000172,- "firstDeltaMs": 2275.878250000009,+ "roundMs": 1170.5284999998985,+ "firstDeltaMs": null,+ "calls": [+ {+ "name": "set_color_grade",+ "execMs": 0.009791000047698617+ }+ ]+ },+ {+ "roundMs": 1059.1542500000214,+ "firstDeltaMs": 920.3352090000408,"calls": []}]@@ -5000,44 +13462,44 @@]},{- "name": "orphaned-overlay-debris",- "bucket": "multi-tool",+ "name": "sky-bluer-single-band",+ "bucket": "single-tool","passRate": 1,"budgetBreaches": [],"latency": {"gateMs": {- "p50": 512,- "p95": 512,- "mean": 512,- "n": 1+ "p50": 282,+ "p95": 298,+ "mean": 283,+ "n": 3},"ttftMs": {- "p50": 2933,- "p95": 2933,- "mean": 2933,- "n": 1+ "p50": 282,+ "p95": 299,+ "mean": 284,+ "n": 3},"totalMs": {- "p50": 3154,- "p95": 3154,- "mean": 3154,- "n": 1+ "p50": 283,+ "p95": 299,+ "mean": 284,+ "n": 3},"modelMs": {- "p50": 2640,- "p95": 2640,- "mean": 2640,- "n": 1+ "p50": 0,+ "p95": 0,+ "mean": 0,+ "n": 3},"toolMs": {"p50": 0,"p95": 0,"mean": 0,- "n": 1+ "n": 3},"rounds": {- "mean": 2,- "max": 2+ "mean": 0,+ "max": 0}},"runs": [@@ -5047,180 +13509,90 @@"skill": null,"areas": ["preview",- "timeline",- "inspector"+ "inspector",+ "color",+ "effects",+ "image_gen",+ "side_panel",+ "editor"],- "declaredTools": 64,+ "declaredTools": 56,"routingMisses": [],"roundModel": "gemini-3.1-flash-lite","notes": [],- "instant": null,+ "instant": "set_color_hsl",+ "qualityGate": [],"judgeNote": null,"trace": [{- "name": "trim_clip",+ "name": "set_color_hsl","round": 0,- "atMs": 1683.448333999957,- "execMs": 0.0800419999868609,+ "atMs": 269.7356669999426,+ "execMs": 0.11162500001955777,"args": {- "out": 10,- "clipId": "c1"+ "clipId": "c1",+ "band": "blue",+ "sat": 29}}],"timings": {- "gateMs": 512.083666999999,+ "gateMs": 269.23950000002515,"gateSkipped": false,- "ttftMs": 2933.2738339999923,- "modelMs": 2640.280000000028,- "toolMs": 0.0800419999868609,- "totalMs": 3154.3483339999802,+ "ttftMs": 269.9770830000052,+ "modelMs": 0,+ "toolMs": 0.11162500001955777,+ "totalMs": 269.9851250000065,+ "judgeMs": 192.6352079999633,"retryMs": 0,"retries": 0,- "rounds": [- {- "roundMs": 1170.0628750000033,- "firstDeltaMs": null,- "calls": [- {- "name": "trim_clip",- "execMs": 0.0800419999868609- }- ]- },- {- "roundMs": 1470.2171250000247,- "firstDeltaMs": 1249.2705410000053,- "calls": []- }- ]+ "rounds": []}- }- ]- },- {- "name": "legacy-thread-no-leak",- "bucket": "chat",- "passRate": 1,- "budgetBreaches": [],- "latency": {- "gateMs": {- "p50": 479,- "p95": 479,- "mean": 479,- "n": 1- },- "ttftMs": {- "p50": 1665,- "p95": 1665,- "mean": 1665,- "n": 1- },- "totalMs": {- "p50": 1808,- "p95": 1808,- "mean": 1808,- "n": 1- },- "modelMs": {- "p50": 1329,- "p95": 1329,- "mean": 1329,- "n": 1- },- "toolMs": {- "p50": 0,- "p95": 0,- "mean": 0,- "n": 1},- "rounds": {- "mean": 1,- "max": 1- }- },- "runs": [{"pass": true,"intent": "simple","skill": null,"areas": ["preview",- "timeline","inspector",+ "color","effects",- "animation",- "transitions"+ "editor"],- "declaredTools": 67,+ "declaredTools": 48,"routingMisses": [],"roundModel": "gemini-3.1-flash-lite","notes": [],- "instant": null,+ "instant": "set_color_hsl",+ "qualityGate": [],"judgeNote": null,- "trace": [],+ "trace": [+ {+ "name": "set_color_hsl",+ "round": 0,+ "atMs": 298.81466600007843,+ "execMs": 0.009040999924764037,+ "args": {+ "clipId": "c1",+ "band": "blue",+ "sat": 29+ }+ }+ ],"timings": {- "gateMs": 478.5380829999922,+ "gateMs": 298.3649999999907,"gateSkipped": false,- "ttftMs": 1664.5661670000409,- "modelMs": 1328.5469579999917,- "toolMs": 0,- "totalMs": 1808.194792000053,+ "ttftMs": 298.96770799998194,+ "modelMs": 0,+ "toolMs": 0.009040999924764037,+ "totalMs": 298.9746659999946,+ "judgeMs": 239.36141600005794,"retryMs": 0,"retries": 0,- "rounds": [- {- "roundMs": 1328.5469579999917,- "firstDeltaMs": 1185.0779999999795,- "calls": []- }- ]+ "rounds": []}- }- ]- },- {- "name": "cinematic-ask-picks-preset",- "bucket": "single-tool",- "passRate": 1,- "budgetBreaches": [],- "latency": {- "gateMs": {- "p50": 403,- "p95": 403,- "mean": 403,- "n": 1- },- "ttftMs": {- "p50": 405,- "p95": 405,- "mean": 405,- "n": 1- },- "totalMs": {- "p50": 405,- "p95": 405,- "mean": 405,- "n": 1- },- "modelMs": {- "p50": 0,- "p95": 0,- "mean": 0,- "n": 1- },- "toolMs": {- "p50": 1,- "p95": 1,- "mean": 1,- "n": 1},- "rounds": {- "mean": 0,- "max": 0- }- },- "runs": [{"pass": true,"intent": "simple",@@ -5229,36 +13601,36 @@"preview","inspector","color",- "effects",- "side_panel",- "top_bar"+ "effects"],- "declaredTools": 52,+ "declaredTools": 44,"routingMisses": [],"roundModel": "gemini-3.1-flash-lite","notes": [],- "instant": "set_color_preset",+ "instant": "set_color_hsl",+ "qualityGate": [],"judgeNote": null,"trace": [{- "name": "set_color_preset",+ "name": "set_color_hsl","round": 0,- "atMs": 403.8911659999867,- "execMs": 0.5663749999948777,+ "atMs": 282.34375,+ "execMs": 0.010624999995343387,"args": {"clipId": "c1",- "preset": "teal-orange",- "amount": 0.68+ "band": "blue",+ "sat": 29}}],"timings": {- "gateMs": 403.4980000000214,+ "gateMs": 282.0682090000482,"gateSkipped": false,- "ttftMs": 404.58883299998706,+ "ttftMs": 282.4948330000043,"modelMs": 0,- "toolMs": 0.5663749999948777,- "totalMs": 404.5983750000014,+ "toolMs": 0.010624999995343387,+ "totalMs": 282.51049999997485,+ "judgeMs": 255.56366600003093,"retryMs": 0,"retries": 0,"rounds": []@@ -5267,40 +13639,40 @@]},{- "name": "warmer-crushed-blacks-in-range",+ "name": "reference-photo-matches-grade","bucket": "single-tool","passRate": 1,"budgetBreaches": [],"latency": {"gateMs": {- "p50": 500,- "p95": 500,- "mean": 500,- "n": 1+ "p50": 220,+ "p95": 234,+ "mean": 221,+ "n": 3},"ttftMs": {- "p50": 3153,- "p95": 3153,- "mean": 3153,- "n": 1+ "p50": 6257,+ "p95": 7816,+ "mean": 5886,+ "n": 3},"totalMs": {- "p50": 3334,- "p95": 3334,- "mean": 3334,- "n": 1+ "p50": 6416,+ "p95": 8140,+ "mean": 6157,+ "n": 3},"modelMs": {- "p50": 2830,- "p95": 2830,- "mean": 2830,- "n": 1+ "p50": 6194,+ "p95": 7924,+ "mean": 5933,+ "n": 3},"toolMs": {"p50": 0,"p95": 0,"mean": 0,- "n": 1+ "n": 3},"rounds": {"mean": 2,@@ -5310,56 +13682,179 @@"runs": [{"pass": true,- "intent": "simple",+ "intent": "complex",+ "skill": null,+ "areas": [+ "preview",+ "inspector",+ "color",+ "effects",+ "side_panel",+ "top_bar"+ ],+ "declaredTools": 55,+ "routingMisses": [],+ "roundModel": "gemini-3.8-flash",+ "notes": [],+ "instant": null,+ "qualityGate": [],+ "judgeNote": null,+ "trace": [+ {+ "name": "match_color_grade",+ "round": 0,+ "atMs": 5850.925332999905,+ "execMs": 0.07704100001137704,+ "args": {+ "ref_asset_id": "a-i1",+ "clipId": "c1"+ }+ }+ ],+ "timings": {+ "gateMs": 209.8849169999594,+ "gateSkipped": true,+ "ttftMs": 7815.744291999959,+ "modelMs": 7923.824125999934,+ "toolMs": 0.07704100001137704,+ "totalMs": 8139.716332999989,+ "judgeMs": 236.04670800000895,+ "retryMs": 0,+ "retries": 0,+ "rounds": [+ {+ "roundMs": 5636.063833999913,+ "firstDeltaMs": null,+ "calls": [+ {+ "name": "match_color_grade",+ "execMs": 0.07704100001137704+ }+ ]+ },+ {+ "roundMs": 2287.760292000021,+ "firstDeltaMs": 1963.9594999999972,+ "calls": []+ }+ ]+ }+ },+ {+ "pass": true,+ "intent": "complex",+ "skill": null,+ "areas": [+ "preview",+ "inspector",+ "color",+ "effects",+ "side_panel",+ "top_bar"+ ],+ "declaredTools": 55,+ "routingMisses": [],+ "roundModel": "gemini-3.8-flash",+ "notes": [],+ "instant": null,+ "qualityGate": [],+ "judgeNote": null,+ "trace": [+ {+ "name": "match_color_grade",+ "round": 0,+ "atMs": 4314.961750000017,+ "execMs": 0.01483400003053248,+ "args": {+ "ref_asset_id": "a-i1",+ "clipId": "c1"+ }+ }+ ],+ "timings": {+ "gateMs": 220.39616699994076,+ "gateSkipped": true,+ "ttftMs": 6256.921875,+ "modelMs": 6193.614956999896,+ "toolMs": 0.01483400003053248,+ "totalMs": 6415.878875000053,+ "judgeMs": 241.6962080000667,+ "retryMs": 0,+ "retries": 0,+ "rounds": [+ {+ "roundMs": 4093.6745409999276,+ "firstDeltaMs": null,+ "calls": [+ {+ "name": "match_color_grade",+ "execMs": 0.01483400003053248+ }+ ]+ },+ {+ "roundMs": 2099.9404159999685,+ "firstDeltaMs": 1941.1765000000596,+ "calls": []+ }+ ]+ }+ },+ {+ "pass": true,+ "intent": "complex","skill": null,"areas": ["preview","inspector","color",- "effects"+ "effects",+ "side_panel",+ "top_bar"],- "declaredTools": 41,+ "declaredTools": 55,"routingMisses": [],- "roundModel": "gemini-3.1-flash-lite",+ "roundModel": "gemini-3.8-flash","notes": [],"instant": null,+ "qualityGate": [],"judgeNote": null,"trace": [{- "name": "set_color_grade",+ "name": "match_color_grade","round": 0,- "atMs": 1915.5917910000426,- "execMs": 0.10349999996833503,+ "atMs": 1874.874375000014,+ "execMs": 0.0034580000210553408,"args": {- "clipId": "c1",- "temperature": 15,- "shadows": -15+ "ref_asset_id": "a-i1",+ "clipId": "c1"}}],"timings": {- "gateMs": 500.2998330000555,- "gateSkipped": false,- "ttftMs": 3153.4604160000454,- "modelMs": 2830.113541999948,- "toolMs": 0.10349999996833503,- "totalMs": 3333.7069580000243,+ "gateMs": 234.0555409999797,+ "gateSkipped": true,+ "ttftMs": 3584.0434580000583,+ "modelMs": 3680.9424999998882,+ "toolMs": 0.0034580000210553408,+ "totalMs": 3916.8096659999574,+ "judgeMs": 215.73795800004154,"retryMs": 0,"retries": 0,"rounds": [{- "roundMs": 1412.8241249999846,+ "roundMs": 1639.7180839999346,"firstDeltaMs": null,"calls": [{- "name": "set_color_grade",- "execMs": 0.10349999996833503+ "name": "match_color_grade",+ "execMs": 0.0034580000210553408}]},{- "roundMs": 1417.2894169999636,- "firstDeltaMs": 1237.2517089999747,+ "roundMs": 2041.2244159999536,+ "firstDeltaMs": 1708.7469159999164,"calls": []}]@@ -5368,236 +13863,311 @@]},{- "name": "sky-bluer-single-band",- "bucket": "single-tool",+ "name": "replicate-link-reads-then-replicates",+ "bucket": "multi-tool","passRate": 1,"budgetBreaches": [],"latency": {"gateMs": {- "p50": 338,- "p95": 338,- "mean": 338,- "n": 1+ "p50": 268,+ "p95": 268,+ "mean": 267,+ "n": 3},"ttftMs": {- "p50": 338,- "p95": 338,- "mean": 338,- "n": 1+ "p50": 12736,+ "p95": 18398,+ "mean": 13056,+ "n": 3},"totalMs": {- "p50": 338,- "p95": 338,- "mean": 338,- "n": 1+ "p50": 12989,+ "p95": 18787,+ "mean": 13404,+ "n": 3},"modelMs": {- "p50": 0,- "p95": 0,- "mean": 0,- "n": 1+ "p50": 12713,+ "p95": 18508,+ "mean": 13127,+ "n": 3},"toolMs": {"p50": 0,"p95": 0,"mean": 0,- "n": 1+ "n": 3},"rounds": {- "mean": 0,- "max": 0+ "mean": 4.7,+ "max": 5}},"runs": [{"pass": true,- "intent": "simple",- "skill": null,+ "intent": "complex",+ "skill": "replicating-a-project","areas": ["preview",+ "timeline","inspector","color",- "effects",- "side_panel"+ "animation",+ "transitions",+ "subtitles",+ "audio",+ "video_gen",+ "scene",+ "library",+ "side_panel",+ "top_bar",+ "editor"],- "declaredTools": 48,+ "declaredTools": 122,"routingMisses": [],- "roundModel": "gemini-3.1-flash-lite",+ "roundModel": "gemini-3.8-flash","notes": [],- "instant": "set_color_hsl",- "judgeNote": null,+ "instant": null,+ "qualityGate": [],+ "judgeNote": "upsell 0.50","trace": [{- "name": "set_color_hsl",+ "name": "read_project","round": 0,- "atMs": 338.1892499999958,- "execMs": 0.08095799997681752,+ "atMs": 9618.684749999898,+ "execMs": 0.12041600001975894,"args": {- "clipId": "c1",- "band": "blue",- "sat": 29+ "link": "https://donkeycut.com/app/p/ref-123"+ }+ },+ {+ "name": "replicate_project",+ "round": 1,+ "atMs": 12247.076415999909,+ "execMs": 0.11241699988022447,+ "args": {+ "link": "https://donkeycut.com/app/p/ref-123",+ "media": [+ {+ "source_asset_id": "r-v1",+ "asset_id": "a-v1"+ },+ {+ "source_asset_id": "r-v2",+ "asset_id": "a-v2"+ }+ ]+ }+ },+ {+ "name": "update_overlay",+ "round": 2,+ "atMs": 14026.830457999953,+ "execMs": 0.02137500001117587,+ "args": {+ "id": "t-n1",+ "text": "MY DESK SETUP"}+ },+ {+ "name": "subtitles_generate",+ "round": 3,+ "atMs": 16570.528957999893,+ "execMs": 0.03979200008325279,+ "args": {}}],"timings": {- "gateMs": 337.8056660000002,+ "gateMs": 265.04670900001656,"gateSkipped": false,- "ttftMs": 338.36724999995204,- "modelMs": 0,- "toolMs": 0.08095799997681752,- "totalMs": 338.37658300000476,+ "ttftMs": 18397.837625000044,+ "modelMs": 18507.73500099976,+ "toolMs": 0.29399999999441206,+ "totalMs": 18786.737208000035,+ "judgeMs": 270.68866700003855,"retryMs": 0,"retries": 0,- "rounds": []+ "rounds": [+ {+ "roundMs": 9351.207374999882,+ "firstDeltaMs": null,+ "calls": [+ {+ "name": "read_project",+ "execMs": 0.12041600001975894+ }+ ]+ },+ {+ "roundMs": 2624.855458999984,+ "firstDeltaMs": null,+ "calls": [+ {+ "name": "replicate_project",+ "execMs": 0.11241699988022447+ }+ ]+ },+ {+ "roundMs": 1775.4115830000956,+ "firstDeltaMs": null,+ "calls": [+ {+ "name": "update_overlay",+ "execMs": 0.02137500001117587+ }+ ]+ },+ {+ "roundMs": 2541.948124999879,+ "firstDeltaMs": null,+ "calls": [+ {+ "name": "subtitles_generate",+ "execMs": 0.03979200008325279+ }+ ]+ },+ {+ "roundMs": 2214.3124589999206,+ "firstDeltaMs": 1825.893167000031,+ "calls": []+ }+ ]}- }- ]- },- {- "name": "reference-photo-matches-grade",- "bucket": "single-tool",- "passRate": 1,- "budgetBreaches": [],- "latency": {- "gateMs": {- "p50": 261,- "p95": 261,- "mean": 261,- "n": 1- },- "ttftMs": {- "p50": 4737,- "p95": 4737,- "mean": 4737,- "n": 1- },- "totalMs": {- "p50": 4903,- "p95": 4903,- "mean": 4903,- "n": 1- },- "modelMs": {- "p50": 4639,- "p95": 4639,- "mean": 4639,- "n": 1- },- "toolMs": {- "p50": 0,- "p95": 0,- "mean": 0,- "n": 1},- "rounds": {- "mean": 2,- "max": 2- }- },- "runs": [{"pass": true,"intent": "complex",- "skill": null,+ "skill": "replicating-a-project","areas": ["preview",+ "timeline","inspector","color",- "effects",+ "animation",+ "transitions",+ "subtitles",+ "audio",+ "video_gen",+ "scene",+ "library","side_panel","top_bar","editor"],- "declaredTools": 56,+ "declaredTools": 122,"routingMisses": [],"roundModel": "gemini-3.8-flash","notes": [],"instant": null,+ "qualityGate": [],"judgeNote": null,"trace": [{- "name": "match_color_grade",+ "name": "read_project","round": 0,- "atMs": 2886.530167000019,- "execMs": 0.06316700001480058,+ "atMs": 2292.7692500001285,+ "execMs": 0.03287500003352761,"args": {- "ref_asset_id": "a-i1",- "clipId": "c1"+ "link": "https://donkeycut.com/app/p/ref-123"+ }+ },+ {+ "name": "replicate_project",+ "round": 1,+ "atMs": 4412.061083000153,+ "execMs": 0.02191699994727969,+ "args": {+ "caption_look": true,+ "link": "https://donkeycut.com/app/p/ref-123",+ "frame": true,+ "media": [+ {+ "asset_id": "a-v1",+ "source_asset_id": "r-v1"+ },+ {+ "asset_id": "a-v2",+ "source_asset_id": "r-v2"+ }+ ]+ }+ },+ {+ "name": "update_overlay",+ "round": 2,+ "atMs": 6374.140374999959,+ "execMs": 0.006125000072643161,+ "args": {+ "id": "t-n1",+ "text": "MY DESK SETUP"+ }+ },+ {+ "name": "subtitles_generate",+ "round": 2,+ "atMs": 6374.328625000082,+ "execMs": 0.0013329999055713415,+ "args": {+ "track": 0}}],"timings": {- "gateMs": 260.5434580000001,- "gateSkipped": true,- "ttftMs": 4736.761750000005,- "modelMs": 4639.108375000011,- "toolMs": 0.06316700001480058,- "totalMs": 4902.827500000014,+ "gateMs": 268.1119999999646,+ "gateSkipped": false,+ "ttftMs": 8032.902708000038,+ "modelMs": 8160.712040999904,+ "toolMs": 0.06224999995902181,+ "totalMs": 8434.717792000156,+ "judgeMs": 229.99841600004584,"retryMs": 0,"retries": 0,"rounds": [{- "roundMs": 2623.5515000000014,+ "roundMs": 2023.4075410000514,"firstDeltaMs": null,"calls": [{- "name": "match_color_grade",- "execMs": 0.06316700001480058+ "name": "read_project",+ "execMs": 0.03287500003352761+ }+ ]+ },+ {+ "roundMs": 2117.823166999966,+ "firstDeltaMs": null,+ "calls": [+ {+ "name": "replicate_project",+ "execMs": 0.02191699994727969+ }+ ]+ },+ {+ "roundMs": 1960.4494999998715,+ "firstDeltaMs": null,+ "calls": [+ {+ "name": "update_overlay",+ "execMs": 0.006125000072643161+ },+ {+ "name": "subtitles_generate",+ "execMs": 0.0013329999055713415}]},{- "roundMs": 2015.5568750000093,- "firstDeltaMs": 1849.6177920000046,+ "roundMs": 2059.0318330000155,+ "firstDeltaMs": 1657.332083000103,"calls": []}]}- }- ]- },- {- "name": "replicate-link-reads-then-replicates",- "bucket": "multi-tool",- "passRate": 1,- "budgetBreaches": [],- "latency": {- "gateMs": {- "p50": 743,- "p95": 743,- "mean": 743,- "n": 1- },- "ttftMs": {- "p50": 16166,- "p95": 16166,- "mean": 16166,- "n": 1- },- "totalMs": {- "p50": 16618,- "p95": 16618,- "mean": 16618,- "n": 1- },- "modelMs": {- "p50": 15837,- "p95": 15837,- "mean": 15837,- "n": 1- },- "toolMs": {- "p50": 1,- "p95": 1,- "mean": 1,- "n": 1},- "rounds": {- "mean": 5,- "max": 5- }- },- "runs": [{"pass": true,"intent": "complex",@@ -5606,8 +14176,6 @@"preview","timeline","inspector",- "color",- "effects","animation","transitions","subtitles",@@ -5619,18 +14187,19 @@"top_bar","editor"],- "declaredTools": 121,+ "declaredTools": 115,"routingMisses": [],"roundModel": "gemini-3.8-flash","notes": [],"instant": null,+ "qualityGate": [],"judgeNote": null,"trace": [{"name": "read_project","round": 0,- "atMs": 3513.029125000001,- "execMs": 0.13958399998955429,+ "atMs": 2951.3764170000795,+ "execMs": 0.006000000052154064,"args": {"link": "https://donkeycut.com/app/p/ref-123"}@@ -5638,8 +14207,8 @@{"name": "replicate_project","round": 1,- "atMs": 9873.157667000021,- "execMs": 0.7092919999849983,+ "atMs": 5354.426875000121,+ "execMs": 0.02987500000745058,"args": {"link": "https://donkeycut.com/app/p/ref-123","media": [@@ -5648,8 +14217,8 @@"source_asset_id": "r-v1"},{- "asset_id": "a-v2",- "source_asset_id": "r-v2"+ "source_asset_id": "r-v2",+ "asset_id": "a-v2"}]}@@ -5657,74 +14226,75 @@{"name": "update_overlay","round": 2,- "atMs": 12561.435792000033,- "execMs": 0.009208999981638044,+ "atMs": 7837.614999999991,+ "execMs": 0.011292000068351626,"args": {- "id": "t-n1",- "text": "MY DESK SETUP"+ "text": "MY DESK SETUP",+ "id": "t-n1"}},{"name": "subtitles_generate","round": 3,- "atMs": 14662.868000000017,- "execMs": 0.02183300000615418,+ "atMs": 10824.02470900002,+ "execMs": 0.005374999949708581,"args": {}}],"timings": {- "gateMs": 742.5230419999571,+ "gateMs": 268.31379200005904,"gateSkipped": false,- "ttftMs": 16166.359959000023,- "modelMs": 15837.093500999908,- "toolMs": 0.8799179999623448,- "totalMs": 16618.03820900002,+ "ttftMs": 12736.049708999926,+ "modelMs": 12712.916081999894,+ "toolMs": 0.05254200007766485,+ "totalMs": 12989.225875000004,+ "judgeMs": 368.0419999998994,"retryMs": 0,"retries": 0,"rounds": [{- "roundMs": 2768.8802079999587,+ "roundMs": 2681.336333000101,"firstDeltaMs": null,"calls": [{"name": "read_project",- "execMs": 0.13958399998955429+ "execMs": 0.006000000052154064}]},{- "roundMs": 6339.8562089999905,+ "roundMs": 2401.853374999948,"firstDeltaMs": null,"calls": [{"name": "replicate_project",- "execMs": 0.7092919999849983+ "execMs": 0.02987500000745058}]},{- "roundMs": 2674.8063339999644,+ "roundMs": 2481.443750000093,"firstDeltaMs": null,"calls": [{"name": "update_overlay",- "execMs": 0.009208999981638044+ "execMs": 0.011292000068351626}]},{- "roundMs": 2099.859625000041,+ "roundMs": 2984.6976659998763,"firstDeltaMs": null,"calls": [{"name": "subtitles_generate",- "execMs": 0.02183300000615418+ "execMs": 0.005374999949708581}]},{- "roundMs": 1953.691124999954,- "firstDeltaMs": 1502.542541999952,+ "roundMs": 2163.5849579998758,+ "firstDeltaMs": 1910.7884579999372,"calls": []}]diff --git a/evals/cut-perf.latest-report.json b/evals/cut-perf.latest-report.jsonindex 7beb7359..4fc015dc 100644--- a/evals/cut-perf.latest-report.json+++ b/evals/cut-perf.latest-report.json@@ -51,10 +51,10 @@},"frameMs": 16.7,"scrub": {- "p50": 15.8,- "p95": 31.6,- "mean": 18.23,- "max": 32.2,+ "p50": 16,+ "p95": 32.2,+ "mean": 18.08,+ "max": 33.9,"n": 41},"longTasks": {@@ -64,7 +64,7 @@"max": 0,"n": 0},- "liveSamples": 46,+ "liveSamples": 36,"machine": "desktop"},{@@ -75,16 +75,16 @@"late": {"p50": 0,"p95": 1,- "mean": 0.12,- "max": 1,+ "mean": 0.17,+ "max": 2,"n": 41},"frameMs": 16.7,"scrub": {"p50": 15.7,- "p95": 32.4,- "mean": 17.45,- "max": 33.1,+ "p95": 33.2,+ "mean": 18.36,+ "max": 49.2,"n": 41},"longTasks": {@@ -94,7 +94,7 @@"max": 0,"n": 0},- "liveSamples": 53,+ "liveSamples": 46,"machine": "desktop"},{@@ -105,16 +105,16 @@"late": {"p50": 0,"p95": 0,- "mean": 0.02,- "max": 1,+ "mean": 0.05,+ "max": 2,"n": 41},"frameMs": 16.7,"scrub": {- "p50": 15.7,- "p95": 16,- "mean": 15.9,- "max": 31.6,+ "p50": 15.6,+ "p95": 17.9,+ "mean": 16.47,+ "max": 47.9,"n": 41},"longTasks": {@@ -135,16 +135,16 @@"late": {"p50": 0,"p95": 0,- "mean": 0.02,- "max": 1,+ "mean": 0.05,+ "max": 3,"n": 81},"frameMs": 16.7,"scrub": {- "p50": 15.8,- "p95": 16.1,- "mean": 15.94,- "max": 32,+ "p50": 15.6,+ "p95": 17.7,+ "mean": 16.16,+ "max": 64.7,"n": 81},"longTasks": {@@ -165,16 +165,16 @@"late": {"p50": 0,"p95": 1,- "mean": 0.17,- "max": 1,+ "mean": 0.2,+ "max": 2,"n": 41},"frameMs": 16.7,"scrub": {- "p50": 15.8,- "p95": 32.5,- "mean": 18.4,- "max": 32.7,+ "p50": 16,+ "p95": 33.6,+ "mean": 18.88,+ "max": 49.1,"n": 41},"longTasks": {@@ -184,7 +184,7 @@"max": 0,"n": 0},- "liveSamples": 63,+ "liveSamples": 46,"machine": "desktop"},{@@ -201,10 +201,10 @@},"frameMs": 16.7,"scrub": {- "p50": 16,- "p95": 32.7,- "mean": 18.45,- "max": 33.5,+ "p50": 15.6,+ "p95": 32.9,+ "mean": 18.41,+ "max": 34.4,"n": 41},"longTasks": {@@ -214,7 +214,7 @@"max": 0,"n": 0},- "liveSamples": 44,+ "liveSamples": 45,"machine": "desktop"},{@@ -225,16 +225,16 @@"late": {"p50": 1,"p95": 1,- "mean": 0.95,+ "mean": 0.9,"max": 1,"n": 41},"frameMs": 16.7,"scrub": {- "p50": 32,- "p95": 33.6,- "mean": 31.26,- "max": 34.4,+ "p50": 31.9,+ "p95": 32.6,+ "mean": 30.22,+ "max": 32.9,"n": 41},"longTasks": {@@ -317,7 +317,7 @@"liveSources": 12,"keptSources": 20,"warmMb": 354,- "memMb": 1108,+ "memMb": 1111,"machine": "desktop"},{@@ -326,13 +326,13 @@"pass": true,"notes": [],"drops": 0,- "presented": 3238,+ "presented": 3236,"lag": {"p50": 0.02,"p95": 0.03,"mean": 0.02,"max": 0.03,- "n": 3238+ "n": 3236},"stallShare": 0,"decay": {@@ -354,7 +354,7 @@"liveSources": 12,"keptSources": 20,"warmMb": 354,- "memMb": 1108,+ "memMb": 1111,"machine": "desktop"},{@@ -363,13 +363,13 @@"pass": true,"notes": [],"drops": 0,- "presented": 223,+ "presented": 222,"lag": {"p50": 0.02,"p95": 0.03,- "mean": 0.01,+ "mean": 0.02,"max": 0.03,- "n": 223+ "n": 222},"stallShare": 0,"decay": {@@ -391,7 +391,7 @@"liveSources": 6,"keptSources": 6,"warmMb": 0,- "memMb": 389,+ "memMb": 390,"machine": "desktop"},{@@ -400,13 +400,13 @@"pass": true,"notes": [],"drops": 0,- "presented": 1027,+ "presented": 1028,"lag": {"p50": 0.02,"p95": 0.03,"mean": 0.02,"max": 0.03,- "n": 1027+ "n": 1028},"stallShare": 0,"decay": {@@ -428,7 +428,7 @@"liveSources": 6,"keptSources": 6,"warmMb": 0,- "memMb": 418,+ "memMb": 422,"machine": "desktop"},{@@ -465,7 +465,7 @@"liveSources": 6,"keptSources": 6,"warmMb": 0,- "memMb": 418,+ "memMb": 422,"machine": "desktop"},{@@ -476,7 +476,7 @@"drops": 0,"presented": 3444,"lag": {- "p50": 0.01,+ "p50": 0.02,"p95": 0.03,"mean": 0.02,"max": 0.03,@@ -550,7 +550,7 @@"drops": 0,"presented": 3444,"lag": {- "p50": 0.02,+ "p50": 0.01,"p95": 0.03,"mean": 0.02,"max": 0.03,@@ -587,7 +587,7 @@"drops": 0,"presented": 3444,"lag": {- "p50": 0.01,+ "p50": 0.02,"p95": 0.03,"mean": 0.02,"max": 0.03,@@ -621,18 +621,18 @@"bucket": "playback","pass": true,"notes": [],- "drops": 1,- "presented": 3427,+ "drops": 0,+ "presented": 3444,"lag": {"p50": 0.01,"p95": 0.01,"mean": 0.01,- "max": 0.1,- "n": 3427+ "max": 0.02,+ "n": 3444},"stallShare": 0,"decay": {- "first": 0.001,+ "first": 0,"last": 0},"clock": {@@ -640,17 +640,17 @@"reported": 0.04},"longTasks": {- "p50": 257,- "p95": 257,- "mean": 257,- "max": 257,- "n": 1+ "p50": 0,+ "p95": 0,+ "mean": 0,+ "max": 0,+ "n": 0},"liveSamples": 10,"liveSources": 1,"keptSources": 1,"warmMb": 0,- "memMb": 144,+ "memMb": 143,"machine": "desktop"},{@@ -661,7 +661,7 @@"drops": 0,"presented": 3444,"lag": {- "p50": 0.02,+ "p50": 0.01,"p95": 0.03,"mean": 0.02,"max": 0.03,@@ -696,13 +696,13 @@"pass": true,"notes": [],"drops": 0,- "presented": 1622,+ "presented": 1619,"lag": {"p50": 0.02,"p95": 0.03,"mean": 0.02,"max": 0.03,- "n": 1622+ "n": 1619},"stallShare": 0,"decay": {@@ -724,7 +724,7 @@"liveSources": 12,"keptSources": 20,"warmMb": 354,- "memMb": 1108,+ "memMb": 1112,"machine": "desktop"},{@@ -763,20 +763,22 @@{"name": "play-4k-from-library","bucket": "playback",- "pass": true,- "notes": [],- "drops": 3,- "presented": 1095,+ "pass": false,+ "notes": [+ "19ms of a 72ms frame blocked the main thread (?@src_cut_lib_0tszo-4._.js)"+ ],+ "drops": 2,+ "presented": 1094,"lag": {"p50": 0.02,"p95": 0.03,- "mean": 0.01,+ "mean": 0.02,"max": 0.03,"n": 1092},"stallShare": 0,"decay": {- "first": 0.008,+ "first": 0.005,"last": 0},"clock": {@@ -784,17 +786,17 @@"reported": 0.04},"longTasks": {- "p50": 137,- "p95": 137,- "mean": 136.5,- "max": 137,- "n": 2+ "p50": 66,+ "p95": 145,+ "mean": 90.67,+ "max": 145,+ "n": 3},"liveSamples": 10,"liveSources": 1,"keptSources": 1,"warmMb": 0,- "memMb": 218,+ "memMb": 209,"machine": "desktop"}]diff --git a/site/package-lock.json b/site/package-lock.jsonindex de26fe6c..0e671c3c 100644--- a/site/package-lock.json+++ b/site/package-lock.json@@ -31,6 +31,7 @@"@mdx-js/loader": "^3.1.1","@mdx-js/react": "^3.1.1","@mdxeditor/editor": "^4.2.4",+ "@mediabunny/prores": "^1.55.1","@mediabunny/server": "^1.55.1","@mediapipe/tasks-vision": "^1.0.1","@modelcontextprotocol/client": "^2.0.0",@@ -62,6 +63,7 @@"mediabunny": "^1.55.5","next": "16.3.4","next-mdx-remote": "^6.0.0",+ "node-av": "^6.1.1","node-web-audio-api": "^2.2.0","onnxruntime-web": "1.29.0","openai": "^6.39.0",diff --git a/site/package.json b/site/package.jsonindex a6969fb5..67d0a121 100644--- a/site/package.json+++ b/site/package.json@@ -21,7 +21,7 @@"prisma:prod": "dotenv -e .env -- prisma db push","engine:dev": "bun run src/cut/engine/main.ts","engine:build": "bash scripts/build-cut-engine.sh",- "worker:build": "NODE_ENV=production bun build --target=node --minify --external=pg-native --external=skia-canvas --external=mediabunny --external=@mediabunny/server --external=node-web-audio-api --loader .css:text src/cut/worker/main.ts --outfile dist/cut-worker/main.js && bun scripts/check-worker-bundle.ts",+ "worker:build": "NODE_ENV=production bun build --target=node --minify --external=pg-native --external=skia-canvas --external=mediabunny --external=@mediabunny/server --external=node-av --external=node-web-audio-api --loader .css:text src/cut/worker/main.ts --outfile dist/cut-worker/main.js && bun scripts/check-worker-bundle.ts","bench:watch": "bun run scripts/bench-watch.ts","eval:cut-chat": "bun run scripts/eval-cut-chat.ts","eval:cut-instant": "bun run scripts/eval-cut-instant.ts",@@ -72,7 +72,9 @@"@mdx-js/loader": "^3.1.1","@mdx-js/react": "^3.1.1","@mdxeditor/editor": "^4.2.4",+ "@mediabunny/prores": "^1.55.1","@mediabunny/server": "^1.55.1",+ "node-av": "^6.1.1","@mediapipe/tasks-vision": "^1.0.1","@modelcontextprotocol/client": "^2.0.0","@modelcontextprotocol/core": "^2.0.0",diff --git a/site/patches/mediabunny+1.55.5.patch b/site/patches/mediabunny+1.55.5.patchindex 049da81b..b7046ec6 100644--- a/site/patches/mediabunny+1.55.5.patch+++ b/site/patches/mediabunny+1.55.5.patch@@ -1,8 +1,8 @@diff --git a/node_modules/mediabunny/dist/bundles/mediabunny.cjs b/node_modules/mediabunny/dist/bundles/mediabunny.cjs-index 3c514ad..66faf6a 100644+index 3c514ad..c225790 100644--- a/node_modules/mediabunny/dist/bundles/mediabunny.cjs+++ b/node_modules/mediabunny/dist/bundles/mediabunny.cjs-@@ -23941,7 +23941,7 @@ var Mediabunny = (() => {+@@ -23941,11 +23941,13 @@ var Mediabunny = (() => {}};var computeMaxQueueSize = (decodedSampleQueueSize) => {@@ -10,16 +10,47 @@ index 3c514ad..66faf6a 100644+ return decodedSampleQueueSize === 0 ? 16 : 8;};var VideoDecoderWrapper = class extends DecoderWrapper {- constructor(onSample, onError, codec, decoderConfig, rotation, timeResolution) {-@@ -23954,6 +23954,7 @@ var Mediabunny = (() => {+- constructor(onSample, onError, codec, decoderConfig, rotation, timeResolution) {++ constructor(onSample, onError, codec, decoderConfig, rotation, timeResolution, colorSpaceOverride = null, transformPacket = null) {+ super(onSample, onError);++ // The sink's packet hook: rewrites packet bytes before they reach the WebCodecs decoder.++ this.transformPacket = transformPacket;+ this.codec = codec;+ this.decoderConfig = decoderConfig;+ this.rotation = rotation;+@@ -23954,6 +23956,13 @@ var Mediabunny = (() => {this.customDecoder = null;this.customDecoderCallSerializer = new CallSerializer();this.customDecoderQueueSize = 0;++ // The sink's color space override: already merged into `decoderConfig` for WebCodecs, and stamped onto the++ // samples a custom decoder produces (see restampSample).++ this.colorSpaceOverride = colorSpaceOverride;++ this.restampBuffer = null; // Reused across restamps, sized on the first frame.++ this.restampChain = Promise.resolve(); // Restamps in emission order.++ this.restampsInFlight = 0;+ this.inFlight = 0; // Packets sent to the decoder whose frames have not come back yet.this.inputTimestamps = [];// Timestamps input into the decoder, sorted.this.sampleQueue = [];-@@ -24031,6 +24032,7 @@ var Mediabunny = (() => {+@@ -23985,6 +23994,17 @@ var Mediabunny = (() => {+ if (!(sample instanceof VideoSample)) {+ throw new TypeError("The argument passed to onSample must be a VideoSample.");+ }++ if (this.colorSpaceOverride) {++ // A custom decoder tags its samples from the bitstream. The override replaces that tag so the++ // sample draws the way a WebCodecs frame configured with the same color space does. The restamp++ // copies frame data, so it runs on its own chain: samples stay in order, the pump counts the++ // ones still copying, and a flush waits for the chain to drain.++ this.restampsInFlight++;++ this.restampChain = this.restampChain.then(() => this.restampSample(sample)).then((restamped) => this.finalizeAndEmitSample(restamped), (error) => onError(error)).finally(() => {++ this.restampsInFlight--;++ });++ return;++ }+ this.finalizeAndEmitSample(sample);+ };+ this.customDecoder.onError = (error) => {+@@ -24031,6 +24051,7 @@ var Mediabunny = (() => {const stack = new Error("Decoding error").stack;this.decoder = new VideoDecoder({output: (frame) => {@@ -27,8 +58,12 @@ index 3c514ad..66faf6a 100644try {colorHandler(frame);} catch (error) {-@@ -24050,10 +24052,7 @@ var Mediabunny = (() => {- return this.customDecoderQueueSize;+@@ -24047,13 +24068,10 @@ var Mediabunny = (() => {+ }+ getDecodeQueueSize() {+ if (this.customDecoder) {+- return this.customDecoderQueueSize;++ return this.customDecoderQueueSize + this.restampsInFlight;} else {assert(this.decoder);- return Math.max(@@ -39,15 +74,83 @@ index 3c514ad..66faf6a 100644}}decode(packet) {-@@ -24098,6 +24097,7 @@ var Mediabunny = (() => {+@@ -24098,6 +24116,13 @@ var Mediabunny = (() => {}}}++ if (this.transformPacket) {++ const transformed = this.transformPacket(packet.data, this.decoderConfig);++ if (transformed) {++ packet = new EncodedPacket(transformed, packet.type, packet.timestamp, packet.duration);++ }++ }+ this.inFlight++;this.decoder.decode(packet.toEncodedVideoChunk());this.decodeAlphaData(packet);}-@@ -24265,6 +24265,7 @@ var Mediabunny = (() => {+@@ -24213,6 +24238,49 @@ var Mediabunny = (() => {+ sample.setRotation(this.rotation);+ this.onSample(sample);+ }++ /**++ * Returns `sample` carrying the sink's color space override. A sample over raw planes takes the tag directly:++ * the VideoFrame it later builds reads `sample.colorSpace`. A sample already wrapping a VideoFrame is rebuilt,++ * since a VideoFrame's color space is fixed at construction and is what the browser draws it by.++ */++ async restampSample(sample) {++ const override = this.colorSpaceOverride;++ assert(override);++ const data = sample._data;++ if (!(typeof VideoFrame !== "undefined" && data instanceof VideoFrame)) {++ sample.colorSpace = new VideoSampleColorSpace(override);++ return sample;++ }++ if (data.format === null) {++ return sample;++ }++ const rect = { x: 0, y: 0, width: data.codedWidth, height: data.codedHeight };++ const size = data.allocationSize({ rect });++ if (!this.restampBuffer || this.restampBuffer.byteLength < size) {++ this.restampBuffer = new ArrayBuffer(size);++ }++ // The sample is closed on every path: a failed copy or frame build must not leak the decoder's frame.++ const { timestamp, duration, rotation } = sample;++ let restamped;++ try {++ const layout = await data.copyTo(this.restampBuffer, { rect });++ restamped = new VideoFrame(new Uint8Array(this.restampBuffer, 0, size), {++ format: data.format,++ codedWidth: data.codedWidth,++ codedHeight: data.codedHeight,++ layout,++ visibleRect: data.visibleRect ?? void 0,++ displayWidth: data.displayWidth,++ displayHeight: data.displayHeight,++ timestamp: data.timestamp,++ duration: data.duration ?? void 0,++ colorSpace: override++ });++ } finally {++ sample.close();++ }++ return new VideoSample(restamped, { timestamp, duration, rotation });++ }+ async mergeAlpha(color, alpha) {+ const resolver = promiseWithResolvers();+ this.mergeAlphaPromises.push(resolver.promise);+@@ -24241,6 +24309,11 @@ var Mediabunny = (() => {+ async flush() {+ if (this.customDecoder) {+ await this.customDecoderCallSerializer.call(() => this.customDecoder.flush());++ // A custom decoder may hand out its last samples a microtask after its flush resolves (the same++ // ordering the sink's own flush relies on), so drain the chain until nothing is still copying.++ do {++ await this.restampChain;++ } while (this.restampsInFlight > 0);+ } else {+ assert(this.decoder);+ await Promise.all([+@@ -24265,6 +24338,7 @@ var Mediabunny = (() => {}this.sampleQueue.length = 0;}@@ -55,11 +158,52 @@ index 3c514ad..66faf6a 100644this.currentPacketIndex = 0;this.raslSkipped = false;}+@@ -24521,6 +24595,18 @@ var Mediabunny = (() => {+ if (decoderOptions.optimizeForLatency !== void 0 && typeof decoderOptions.optimizeForLatency !== "boolean") {+ throw new TypeError("decoderOptions.optimizeForLatency, when provided, must be a boolean.");+ }++ if (decoderOptions.colorSpace !== void 0) {++ if (!decoderOptions.colorSpace || typeof decoderOptions.colorSpace !== "object") {++ throw new TypeError("decoderOptions.colorSpace, when provided, must be an object.");++ }++ new VideoSampleColorSpace(decoderOptions.colorSpace);++ }++ if (decoderOptions.transformConfig !== undefined && typeof decoderOptions.transformConfig !== "function") {++ throw new TypeError("decoderOptions.transformConfig, when provided, must be a function.");++ }++ if (decoderOptions.transformPacket !== undefined && typeof decoderOptions.transformPacket !== "function") {++ throw new TypeError("decoderOptions.transformPacket, when provided, must be a function.");++ }+ };+ var VideoSampleSink = class extends BaseMediaSampleSink {+ /** Creates a new {@link VideoSampleSink} for the given {@link InputVideoTrack}. */+@@ -24548,12 +24634,19 @@ var Mediabunny = (() => {+ let decoderConfig = await this._track.getDecoderConfig();+ const timeResolution = await this._track.getTimeResolution();+ assert(codec && decoderConfig);++ const colorSpaceOverride = this._decoderOptions.colorSpace ?? null;+ decoderConfig = {+ ...decoderConfig,+ hardwareAcceleration: this._decoderOptions.hardwareAcceleration,+- optimizeForLatency: this._decoderOptions.optimizeForLatency++ optimizeForLatency: this._decoderOptions.optimizeForLatency,++ // The override replaces whatever the track carries, so the decoder emits frames tagged the way the++ // caller asked, in-band tags included.++ ...colorSpaceOverride ? { colorSpace: colorSpaceOverride } : {}+ };+- return new VideoDecoderWrapper(onSample, onError, codec, decoderConfig, rotation, timeResolution);++ if (this._decoderOptions.transformConfig) {++ decoderConfig = this._decoderOptions.transformConfig(decoderConfig);++ }++ return new VideoDecoderWrapper(onSample, onError, codec, decoderConfig, rotation, timeResolution, colorSpaceOverride, this._decoderOptions.transformPacket ?? null);+ }+ /** @internal */+ _createPacketSink() {diff --git a/node_modules/mediabunny/dist/bundles/mediabunny.mjs b/node_modules/mediabunny/dist/bundles/mediabunny.mjs-index 9a62e92..5abfb37 100644+index 9a62e92..9da68cc 100644--- a/node_modules/mediabunny/dist/bundles/mediabunny.mjs+++ b/node_modules/mediabunny/dist/bundles/mediabunny.mjs-@@ -23784,7 +23784,7 @@ var BaseMediaSampleSink = class {+@@ -23784,11 +23784,13 @@ var BaseMediaSampleSink = class {}};var computeMaxQueueSize = (decodedSampleQueueSize) => {@@ -67,16 +211,47 @@ index 9a62e92..5abfb37 100644+ return decodedSampleQueueSize === 0 ? 16 : 8;};var VideoDecoderWrapper = class extends DecoderWrapper {- constructor(onSample, onError, codec, decoderConfig, rotation, timeResolution) {-@@ -23797,6 +23797,7 @@ var VideoDecoderWrapper = class extends DecoderWrapper {+- constructor(onSample, onError, codec, decoderConfig, rotation, timeResolution) {++ constructor(onSample, onError, codec, decoderConfig, rotation, timeResolution, colorSpaceOverride = null, transformPacket = null) {+ super(onSample, onError);++ // The sink's packet hook: rewrites packet bytes before they reach the WebCodecs decoder.++ this.transformPacket = transformPacket;+ this.codec = codec;+ this.decoderConfig = decoderConfig;+ this.rotation = rotation;+@@ -23797,6 +23799,13 @@ var VideoDecoderWrapper = class extends DecoderWrapper {this.customDecoder = null;this.customDecoderCallSerializer = new CallSerializer();this.customDecoderQueueSize = 0;++ // The sink's color space override: already merged into `decoderConfig` for WebCodecs, and stamped onto the++ // samples a custom decoder produces (see restampSample).++ this.colorSpaceOverride = colorSpaceOverride;++ this.restampBuffer = null; // Reused across restamps, sized on the first frame.++ this.restampChain = Promise.resolve(); // Restamps in emission order.++ this.restampsInFlight = 0;+ this.inFlight = 0; // Packets sent to the decoder whose frames have not come back yet.this.inputTimestamps = [];// Timestamps input into the decoder, sorted.this.sampleQueue = [];-@@ -23874,6 +23875,7 @@ var VideoDecoderWrapper = class extends DecoderWrapper {+@@ -23828,6 +23837,17 @@ var VideoDecoderWrapper = class extends DecoderWrapper {+ if (!(sample instanceof VideoSample)) {+ throw new TypeError("The argument passed to onSample must be a VideoSample.");+ }++ if (this.colorSpaceOverride) {++ // A custom decoder tags its samples from the bitstream. The override replaces that tag so the++ // sample draws the way a WebCodecs frame configured with the same color space does. The restamp++ // copies frame data, so it runs on its own chain: samples stay in order, the pump counts the++ // ones still copying, and a flush waits for the chain to drain.++ this.restampsInFlight++;++ this.restampChain = this.restampChain.then(() => this.restampSample(sample)).then((restamped) => this.finalizeAndEmitSample(restamped), (error) => onError(error)).finally(() => {++ this.restampsInFlight--;++ });++ return;++ }+ this.finalizeAndEmitSample(sample);+ };+ this.customDecoder.onError = (error) => {+@@ -23874,6 +23894,7 @@ var VideoDecoderWrapper = class extends DecoderWrapper {const stack = new Error("Decoding error").stack;this.decoder = new VideoDecoder({output: (frame) => {@@ -84,8 +259,12 @@ index 9a62e92..5abfb37 100644try {colorHandler(frame);} catch (error) {-@@ -23893,10 +23895,7 @@ var VideoDecoderWrapper = class extends DecoderWrapper {- return this.customDecoderQueueSize;+@@ -23890,13 +23911,10 @@ var VideoDecoderWrapper = class extends DecoderWrapper {+ }+ getDecodeQueueSize() {+ if (this.customDecoder) {+- return this.customDecoderQueueSize;++ return this.customDecoderQueueSize + this.restampsInFlight;} else {assert(this.decoder);- return Math.max(@@ -96,15 +275,83 @@ index 9a62e92..5abfb37 100644}}decode(packet) {-@@ -23941,6 +23940,7 @@ var VideoDecoderWrapper = class extends DecoderWrapper {+@@ -23941,6 +23959,13 @@ var VideoDecoderWrapper = class extends DecoderWrapper {}}}++ if (this.transformPacket) {++ const transformed = this.transformPacket(packet.data, this.decoderConfig);++ if (transformed) {++ packet = new EncodedPacket(transformed, packet.type, packet.timestamp, packet.duration);++ }++ }+ this.inFlight++;this.decoder.decode(packet.toEncodedVideoChunk());this.decodeAlphaData(packet);}-@@ -24108,6 +24108,7 @@ var VideoDecoderWrapper = class extends DecoderWrapper {+@@ -24056,6 +24081,49 @@ var VideoDecoderWrapper = class extends DecoderWrapper {+ sample.setRotation(this.rotation);+ this.onSample(sample);+ }++ /**++ * Returns `sample` carrying the sink's color space override. A sample over raw planes takes the tag directly:++ * the VideoFrame it later builds reads `sample.colorSpace`. A sample already wrapping a VideoFrame is rebuilt,++ * since a VideoFrame's color space is fixed at construction and is what the browser draws it by.++ */++ async restampSample(sample) {++ const override = this.colorSpaceOverride;++ assert(override);++ const data = sample._data;++ if (!(typeof VideoFrame !== "undefined" && data instanceof VideoFrame)) {++ sample.colorSpace = new VideoSampleColorSpace(override);++ return sample;++ }++ if (data.format === null) {++ return sample;++ }++ const rect = { x: 0, y: 0, width: data.codedWidth, height: data.codedHeight };++ const size = data.allocationSize({ rect });++ if (!this.restampBuffer || this.restampBuffer.byteLength < size) {++ this.restampBuffer = new ArrayBuffer(size);++ }++ // The sample is closed on every path: a failed copy or frame build must not leak the decoder's frame.++ const { timestamp, duration, rotation } = sample;++ let restamped;++ try {++ const layout = await data.copyTo(this.restampBuffer, { rect });++ restamped = new VideoFrame(new Uint8Array(this.restampBuffer, 0, size), {++ format: data.format,++ codedWidth: data.codedWidth,++ codedHeight: data.codedHeight,++ layout,++ visibleRect: data.visibleRect ?? void 0,++ displayWidth: data.displayWidth,++ displayHeight: data.displayHeight,++ timestamp: data.timestamp,++ duration: data.duration ?? void 0,++ colorSpace: override++ });++ } finally {++ sample.close();++ }++ return new VideoSample(restamped, { timestamp, duration, rotation });++ }+ async mergeAlpha(color, alpha) {+ const resolver = promiseWithResolvers();+ this.mergeAlphaPromises.push(resolver.promise);+@@ -24084,6 +24152,11 @@ var VideoDecoderWrapper = class extends DecoderWrapper {+ async flush() {+ if (this.customDecoder) {+ await this.customDecoderCallSerializer.call(() => this.customDecoder.flush());++ // A custom decoder may hand out its last samples a microtask after its flush resolves (the same++ // ordering the sink's own flush relies on), so drain the chain until nothing is still copying.++ do {++ await this.restampChain;++ } while (this.restampsInFlight > 0);+ } else {+ assert(this.decoder);+ await Promise.all([+@@ -24108,6 +24181,7 @@ var VideoDecoderWrapper = class extends DecoderWrapper {}this.sampleQueue.length = 0;}@@ -112,11 +359,285 @@ index 9a62e92..5abfb37 100644this.currentPacketIndex = 0;this.raslSkipped = false;}+@@ -24364,6 +24438,18 @@ var validateVideoSinkDecoderOptions = (decoderOptions) => {+ if (decoderOptions.optimizeForLatency !== void 0 && typeof decoderOptions.optimizeForLatency !== "boolean") {+ throw new TypeError("decoderOptions.optimizeForLatency, when provided, must be a boolean.");+ }++ if (decoderOptions.colorSpace !== void 0) {++ if (!decoderOptions.colorSpace || typeof decoderOptions.colorSpace !== "object") {++ throw new TypeError("decoderOptions.colorSpace, when provided, must be an object.");++ }++ new VideoSampleColorSpace(decoderOptions.colorSpace);++ }++ if (decoderOptions.transformConfig !== undefined && typeof decoderOptions.transformConfig !== "function") {++ throw new TypeError("decoderOptions.transformConfig, when provided, must be a function.");++ }++ if (decoderOptions.transformPacket !== undefined && typeof decoderOptions.transformPacket !== "function") {++ throw new TypeError("decoderOptions.transformPacket, when provided, must be a function.");++ }+ };+ var VideoSampleSink = class extends BaseMediaSampleSink {+ /** Creates a new {@link VideoSampleSink} for the given {@link InputVideoTrack}. */+@@ -24391,12 +24477,19 @@ var VideoSampleSink = class extends BaseMediaSampleSink {+ let decoderConfig = await this._track.getDecoderConfig();+ const timeResolution = await this._track.getTimeResolution();+ assert(codec && decoderConfig);++ const colorSpaceOverride = this._decoderOptions.colorSpace ?? null;+ decoderConfig = {+ ...decoderConfig,+ hardwareAcceleration: this._decoderOptions.hardwareAcceleration,+- optimizeForLatency: this._decoderOptions.optimizeForLatency++ optimizeForLatency: this._decoderOptions.optimizeForLatency,++ // The override replaces whatever the track carries, so the decoder emits frames tagged the way the++ // caller asked, in-band tags included.++ ...colorSpaceOverride ? { colorSpace: colorSpaceOverride } : {}+ };+- return new VideoDecoderWrapper(onSample, onError, codec, decoderConfig, rotation, timeResolution);++ if (this._decoderOptions.transformConfig) {++ decoderConfig = this._decoderOptions.transformConfig(decoderConfig);++ }++ return new VideoDecoderWrapper(onSample, onError, codec, decoderConfig, rotation, timeResolution, colorSpaceOverride, this._decoderOptions.transformPacket ?? null);+ }+ /** @internal */+ _createPacketSink() {+diff --git a/node_modules/mediabunny/dist/bundles/mediabunny.node.cjs b/node_modules/mediabunny/dist/bundles/mediabunny.node.cjs+index 10786e4..6fe91dd 100644+--- a/node_modules/mediabunny/dist/bundles/mediabunny.node.cjs++++ b/node_modules/mediabunny/dist/bundles/mediabunny.node.cjs+@@ -23947,8 +23947,10 @@ var Mediabunny = (() => {+ return decodedSampleQueueSize === 0 ? 40 : 8;+ };+ var VideoDecoderWrapper = class extends DecoderWrapper {+- constructor(onSample, onError, codec, decoderConfig, rotation, timeResolution) {++ constructor(onSample, onError, codec, decoderConfig, rotation, timeResolution, colorSpaceOverride = null, transformPacket = null) {+ super(onSample, onError);++ // The sink's packet hook: rewrites packet bytes before they reach the WebCodecs decoder.++ this.transformPacket = transformPacket;+ this.codec = codec;+ this.decoderConfig = decoderConfig;+ this.rotation = rotation;+@@ -23957,6 +23959,12 @@ var Mediabunny = (() => {+ this.customDecoder = null;+ this.customDecoderCallSerializer = new CallSerializer();+ this.customDecoderQueueSize = 0;++ // The sink's color space override: already merged into `decoderConfig` for WebCodecs, and stamped onto the++ // samples a custom decoder produces (see restampSample).++ this.colorSpaceOverride = colorSpaceOverride;++ this.restampBuffer = null; // Reused across restamps, sized on the first frame.++ this.restampChain = Promise.resolve(); // Restamps in emission order.++ this.restampsInFlight = 0;+ this.inputTimestamps = [];+ // Timestamps input into the decoder, sorted.+ this.sampleQueue = [];+@@ -23988,6 +23996,17 @@ var Mediabunny = (() => {+ if (!(sample instanceof VideoSample)) {+ throw new TypeError("The argument passed to onSample must be a VideoSample.");+ }++ if (this.colorSpaceOverride) {++ // A custom decoder tags its samples from the bitstream. The override replaces that tag so the++ // sample draws the way a WebCodecs frame configured with the same color space does. The restamp++ // copies frame data, so it runs on its own chain: samples stay in order, the pump counts the++ // ones still copying, and a flush waits for the chain to drain.++ this.restampsInFlight++;++ this.restampChain = this.restampChain.then(() => this.restampSample(sample)).then((restamped) => this.finalizeAndEmitSample(restamped), (error) => onError(error)).finally(() => {++ this.restampsInFlight--;++ });++ return;++ }+ this.finalizeAndEmitSample(sample);+ };+ this.customDecoder.onError = (error) => {+@@ -24050,7 +24069,7 @@ var Mediabunny = (() => {+ }+ getDecodeQueueSize() {+ if (this.customDecoder) {+- return this.customDecoderQueueSize;++ return this.customDecoderQueueSize + this.restampsInFlight;+ } else {+ assert(this.decoder);+ return Math.max(+@@ -24101,6 +24120,12 @@ var Mediabunny = (() => {+ }+ }+ }++ if (this.transformPacket) {++ const transformed = this.transformPacket(packet.data, this.decoderConfig);++ if (transformed) {++ packet = new EncodedPacket(transformed, packet.type, packet.timestamp, packet.duration);++ }++ }+ this.decoder.decode(packet.toEncodedVideoChunk());+ this.decodeAlphaData(packet);+ }+@@ -24216,6 +24241,49 @@ var Mediabunny = (() => {+ sample.setRotation(this.rotation);+ this.onSample(sample);+ }++ /**++ * Returns `sample` carrying the sink's color space override. A sample over raw planes takes the tag directly:++ * the VideoFrame it later builds reads `sample.colorSpace`. A sample already wrapping a VideoFrame is rebuilt,++ * since a VideoFrame's color space is fixed at construction and is what the browser draws it by.++ */++ async restampSample(sample) {++ const override = this.colorSpaceOverride;++ assert(override);++ const data = sample._data;++ if (!(typeof VideoFrame !== "undefined" && data instanceof VideoFrame)) {++ sample.colorSpace = new VideoSampleColorSpace(override);++ return sample;++ }++ if (data.format === null) {++ return sample;++ }++ const rect = { x: 0, y: 0, width: data.codedWidth, height: data.codedHeight };++ const size = data.allocationSize({ rect });++ if (!this.restampBuffer || this.restampBuffer.byteLength < size) {++ this.restampBuffer = new ArrayBuffer(size);++ }++ // The sample is closed on every path: a failed copy or frame build must not leak the decoder's frame.++ const { timestamp, duration, rotation } = sample;++ let restamped;++ try {++ const layout = await data.copyTo(this.restampBuffer, { rect });++ restamped = new VideoFrame(new Uint8Array(this.restampBuffer, 0, size), {++ format: data.format,++ codedWidth: data.codedWidth,++ codedHeight: data.codedHeight,++ layout,++ visibleRect: data.visibleRect ?? void 0,++ displayWidth: data.displayWidth,++ displayHeight: data.displayHeight,++ timestamp: data.timestamp,++ duration: data.duration ?? void 0,++ colorSpace: override++ });++ } finally {++ sample.close();++ }++ return new VideoSample(restamped, { timestamp, duration, rotation });++ }+ async mergeAlpha(color, alpha) {+ const resolver = promiseWithResolvers();+ this.mergeAlphaPromises.push(resolver.promise);+@@ -24244,6 +24312,11 @@ var Mediabunny = (() => {+ async flush() {+ if (this.customDecoder) {+ await this.customDecoderCallSerializer.call(() => this.customDecoder.flush());++ // A custom decoder may hand out its last samples a microtask after its flush resolves (the same++ // ordering the sink's own flush relies on), so drain the chain until nothing is still copying.++ do {++ await this.restampChain;++ } while (this.restampsInFlight > 0);+ } else {+ assert(this.decoder);+ await Promise.all([+@@ -24524,6 +24597,18 @@ var Mediabunny = (() => {+ if (decoderOptions.optimizeForLatency !== void 0 && typeof decoderOptions.optimizeForLatency !== "boolean") {+ throw new TypeError("decoderOptions.optimizeForLatency, when provided, must be a boolean.");+ }++ if (decoderOptions.colorSpace !== void 0) {++ if (!decoderOptions.colorSpace || typeof decoderOptions.colorSpace !== "object") {++ throw new TypeError("decoderOptions.colorSpace, when provided, must be an object.");++ }++ new VideoSampleColorSpace(decoderOptions.colorSpace);++ }++ if (decoderOptions.transformConfig !== undefined && typeof decoderOptions.transformConfig !== "function") {++ throw new TypeError("decoderOptions.transformConfig, when provided, must be a function.");++ }++ if (decoderOptions.transformPacket !== undefined && typeof decoderOptions.transformPacket !== "function") {++ throw new TypeError("decoderOptions.transformPacket, when provided, must be a function.");++ }+ };+ var VideoSampleSink = class extends BaseMediaSampleSink {+ /** Creates a new {@link VideoSampleSink} for the given {@link InputVideoTrack}. */+@@ -24551,12 +24636,19 @@ var Mediabunny = (() => {+ let decoderConfig = await this._track.getDecoderConfig();+ const timeResolution = await this._track.getTimeResolution();+ assert(codec && decoderConfig);++ const colorSpaceOverride = this._decoderOptions.colorSpace ?? null;+ decoderConfig = {+ ...decoderConfig,+ hardwareAcceleration: this._decoderOptions.hardwareAcceleration,+- optimizeForLatency: this._decoderOptions.optimizeForLatency++ optimizeForLatency: this._decoderOptions.optimizeForLatency,++ // The override replaces whatever the track carries, so the decoder emits frames tagged the way the++ // caller asked, in-band tags included.++ ...colorSpaceOverride ? { colorSpace: colorSpaceOverride } : {}+ };+- return new VideoDecoderWrapper(onSample, onError, codec, decoderConfig, rotation, timeResolution);++ if (this._decoderOptions.transformConfig) {++ decoderConfig = this._decoderOptions.transformConfig(decoderConfig);++ }++ return new VideoDecoderWrapper(onSample, onError, codec, decoderConfig, rotation, timeResolution, colorSpaceOverride, this._decoderOptions.transformPacket ?? null);+ }+ /** @internal */+ _createPacketSink() {+diff --git a/node_modules/mediabunny/dist/mediabunny.d.ts b/node_modules/mediabunny/dist/mediabunny.d.ts+index f0667c1..b556ba8 100644+--- a/node_modules/mediabunny/dist/mediabunny.d.ts++++ b/node_modules/mediabunny/dist/mediabunny.d.ts+@@ -5090,6 +5090,21 @@ export declare type VideoSinkDecoderOptions = {+ * before video frames are output.+ */+ optimizeForLatency?: boolean;++ /**++ * The color space the decoded frames are tagged with, replacing whatever the track carries. Merged into the++ * WebCodecs decoder config, and stamped onto the samples a custom decoder produces. Use it to read a file whose++ * tags the browser would otherwise convert or tone-map, so the drawn pixels are the untouched code values.++ */++ colorSpace?: VideoColorSpaceInit;++ /**++ * Rewrites the WebCodecs decoder config before the decoder is configured, after the sink's own fields are++ * merged in. Use it to edit codec-specific data such as the bitstream's in-band color tags.++ */++ transformConfig?: (config: VideoDecoderConfig) => VideoDecoderConfig;++ /**++ * Rewrites a packet's bytes before they reach the WebCodecs decoder. Return null to send the packet as is.++ */++ transformPacket?: (data: Uint8Array, config: VideoDecoderConfig) => Uint8Array | null;+ };++ /**+diff --git a/node_modules/mediabunny/dist/modules/src/media-sink.d.ts b/node_modules/mediabunny/dist/modules/src/media-sink.d.ts+index c830d17..1308a21 100644+--- a/node_modules/mediabunny/dist/modules/src/media-sink.d.ts++++ b/node_modules/mediabunny/dist/modules/src/media-sink.d.ts+@@ -129,6 +129,21 @@ export type VideoSinkDecoderOptions = {+ * before video frames are output.+ */+ optimizeForLatency?: boolean;++ /**++ * The color space the decoded frames are tagged with, replacing whatever the track carries. Merged into the++ * WebCodecs decoder config, and stamped onto the samples a custom decoder produces. Use it to read a file whose++ * tags the browser would otherwise convert or tone-map, so the drawn pixels are the untouched code values.++ */++ colorSpace?: VideoColorSpaceInit;++ /**++ * Rewrites the WebCodecs decoder config before the decoder is configured, after the sink's own fields are++ * merged in. Use it to edit codec-specific data such as the bitstream's in-band color tags.++ */++ transformConfig?: (config: VideoDecoderConfig) => VideoDecoderConfig;++ /**++ * Rewrites a packet's bytes before they reach the WebCodecs decoder. Return null to send the packet as is.++ */++ transformPacket?: (data: Uint8Array, config: VideoDecoderConfig) => Uint8Array | null;+ };+ /**+ * A sink that retrieves decoded video samples (video frames) from a video track.diff --git a/node_modules/mediabunny/dist/modules/src/media-sink.js b/node_modules/mediabunny/dist/modules/src/media-sink.js-index da1cc3a..28c15d3 100644+index da1cc3a..a3bdd0c 100644--- a/node_modules/mediabunny/dist/modules/src/media-sink.js+++ b/node_modules/mediabunny/dist/modules/src/media-sink.js-@@ -650,10 +650,11 @@ export class BaseMediaSampleSink {+@@ -13,7 +13,7 @@ import { InputAudioTrack, InputTrack, InputVideoTrack } from './input-track.js';+ import { assert, assertNever, CallSerializer, clamp, colorSpaceIsComplete, getInt24, getUint24, insertSorted, isChromium, isFirefox, isNumber, isWebKit, last, mapAsyncGenerator, missingWebCodecsClassMessage, promiseWithResolvers, removeItem, toAsyncIterator, toDataView, toUint8Array, validateAnyIterable, } from './misc.js';+ import { EncodedPacket } from './packet.js';+ import { fromAlaw, fromUlaw } from './pcm.js';+-import { AudioSample, clampCropRectangle, validateCropRectangle, VideoSample, } from './sample.js';++import { AudioSample, clampCropRectangle, validateCropRectangle, VideoSample, VideoSampleColorSpace, } from './sample.js';+ const validatePacketRetrievalOptions = (options) => {+ if (!options || typeof options !== 'object') {+ throw new TypeError('options must be an object.');+@@ -650,14 +650,17 @@ export class BaseMediaSampleSink {}}const computeMaxQueueSize = (decodedSampleQueueSize) => {@@ -131,16 +652,50 @@ index da1cc3a..28c15d3 100644+ return decodedSampleQueueSize === 0 ? 16 : 8;};class VideoDecoderWrapper extends DecoderWrapper {- constructor(onSample, onError, codec, decoderConfig, rotation, timeResolution) {-@@ -666,6 +667,7 @@ class VideoDecoderWrapper extends DecoderWrapper {+- constructor(onSample, onError, codec, decoderConfig, rotation, timeResolution) {++ constructor(onSample, onError, codec, decoderConfig, rotation, timeResolution, colorSpaceOverride = null, transformPacket = null) {+ super(onSample, onError);++ // The sink's packet hook: rewrites packet bytes before they reach the WebCodecs decoder.++ this.transformPacket = transformPacket;+ this.codec = codec;+ this.decoderConfig = decoderConfig;+ this.rotation = rotation;+@@ -666,6 +669,13 @@ class VideoDecoderWrapper extends DecoderWrapper {this.customDecoder = null;this.customDecoderCallSerializer = new CallSerializer();this.customDecoderQueueSize = 0;++ // The sink's color space override: already merged into `decoderConfig` for WebCodecs, and stamped onto the++ // samples a custom decoder produces (see restampSample).++ this.colorSpaceOverride = colorSpaceOverride;++ this.restampBuffer = null; // Reused across restamps, sized on the first frame.++ this.restampChain = Promise.resolve(); // Restamps in emission order.++ this.restampsInFlight = 0;+ this.inFlight = 0; // Packets sent to the decoder whose frames have not come back yet.this.inputTimestamps = []; // Timestamps input into the decoder, sorted.this.sampleQueue = []; // Safari-specific thing, check usage.this.currentPacketIndex = 0;-@@ -756,6 +758,7 @@ class VideoDecoderWrapper extends DecoderWrapper {+@@ -697,6 +707,20 @@ class VideoDecoderWrapper extends DecoderWrapper {+ if (!(sample instanceof VideoSample)) {+ throw new TypeError('The argument passed to onSample must be a VideoSample.');+ }++ if (this.colorSpaceOverride) {++ // A custom decoder tags its samples from the bitstream. The override replaces that tag so the++ // sample draws the way a WebCodecs frame configured with the same color space does. The restamp++ // copies frame data, so it runs on its own chain: samples stay in order, the pump counts the++ // ones still copying, and a flush waits for the chain to drain.++ this.restampsInFlight++;++ this.restampChain = this.restampChain++ .then(() => this.restampSample(sample))++ .then(restamped => this.finalizeAndEmitSample(restamped), error => onError(error))++ .finally(() => {++ this.restampsInFlight--;++ });++ return;++ }+ this.finalizeAndEmitSample(sample);+ };+ // @ts-expect-error It's technically readonly+@@ -756,6 +780,7 @@ class VideoDecoderWrapper extends DecoderWrapper {const stack = new Error('Decoding error').stack;this.decoder = new VideoDecoder({output: (frame) => {@@ -148,7 +703,12 @@ index da1cc3a..28c15d3 100644try {colorHandler(frame);}-@@ -777,7 +780,7 @@ class VideoDecoderWrapper extends DecoderWrapper {+@@ -773,11 +798,11 @@ class VideoDecoderWrapper extends DecoderWrapper {+ }+ getDecodeQueueSize() {+ if (this.customDecoder) {+- return this.customDecoderQueueSize;++ return this.customDecoderQueueSize + this.restampsInFlight;}else {assert(this.decoder);@@ -157,15 +717,83 @@ index da1cc3a..28c15d3 100644}}decode(packet) {-@@ -835,6 +838,7 @@ class VideoDecoderWrapper extends DecoderWrapper {+@@ -835,6 +860,13 @@ class VideoDecoderWrapper extends DecoderWrapper {}}}++ if (this.transformPacket) {++ const transformed = this.transformPacket(packet.data, this.decoderConfig);++ if (transformed) {++ packet = new EncodedPacket(transformed, packet.type, packet.timestamp, packet.duration);++ }++ }+ this.inFlight++;this.decoder.decode(packet.toEncodedVideoChunk());this.decodeAlphaData(packet);}-@@ -1042,6 +1046,7 @@ class VideoDecoderWrapper extends DecoderWrapper {+@@ -981,6 +1013,49 @@ class VideoDecoderWrapper extends DecoderWrapper {+ sample.setRotation(this.rotation);+ this.onSample(sample);+ }++ /**++ * Returns `sample` carrying the sink's color space override. A sample over raw planes takes the tag directly:++ * the VideoFrame it later builds reads `sample.colorSpace`. A sample already wrapping a VideoFrame is rebuilt,++ * since a VideoFrame's color space is fixed at construction and is what the browser draws it by.++ */++ async restampSample(sample) {++ const override = this.colorSpaceOverride;++ assert(override);++ const data = sample._data;++ if (!(typeof VideoFrame !== 'undefined' && data instanceof VideoFrame)) {++ sample.colorSpace = new VideoSampleColorSpace(override);++ return sample;++ }++ if (data.format === null) {++ return sample; // Opaque frame; nothing to copy.++ }++ const rect = { x: 0, y: 0, width: data.codedWidth, height: data.codedHeight };++ const size = data.allocationSize({ rect });++ if (!this.restampBuffer || this.restampBuffer.byteLength < size) {++ this.restampBuffer = new ArrayBuffer(size);++ }++ // The sample is closed on every path: a failed copy or frame build must not leak the decoder's frame.++ const { timestamp, duration, rotation } = sample;++ let restamped;++ try {++ const layout = await data.copyTo(this.restampBuffer, { rect });++ restamped = new VideoFrame(new Uint8Array(this.restampBuffer, 0, size), {++ format: data.format,++ codedWidth: data.codedWidth,++ codedHeight: data.codedHeight,++ layout,++ visibleRect: data.visibleRect ?? undefined,++ displayWidth: data.displayWidth,++ displayHeight: data.displayHeight,++ timestamp: data.timestamp,++ duration: data.duration ?? undefined,++ colorSpace: override,++ });++ } finally {++ sample.close();++ }++ return new VideoSample(restamped, { timestamp, duration, rotation });++ }+ async mergeAlpha(color, alpha) {+ const resolver = promiseWithResolvers();+ this.mergeAlphaPromises.push(resolver.promise);+@@ -1017,6 +1092,11 @@ class VideoDecoderWrapper extends DecoderWrapper {+ async flush() {+ if (this.customDecoder) {+ await this.customDecoderCallSerializer.call(() => this.customDecoder.flush());++ // A custom decoder may hand out its last samples a microtask after its flush resolves (the same++ // ordering the sink's own flush relies on), so drain the chain until nothing is still copying.++ do {++ await this.restampChain;++ } while (this.restampsInFlight > 0);+ }+ else {+ assert(this.decoder);+@@ -1042,6 +1122,7 @@ class VideoDecoderWrapper extends DecoderWrapper {}this.sampleQueue.length = 0;}@@ -173,3 +801,43 @@ index da1cc3a..28c15d3 100644this.currentPacketIndex = 0;this.raslSkipped = false;}+@@ -1319,6 +1400,18 @@ const validateVideoSinkDecoderOptions = (decoderOptions) => {+ if (decoderOptions.optimizeForLatency !== undefined && typeof decoderOptions.optimizeForLatency !== 'boolean') {+ throw new TypeError('decoderOptions.optimizeForLatency, when provided, must be a boolean.');+ }++ if (decoderOptions.colorSpace !== undefined) {++ if (!decoderOptions.colorSpace || typeof decoderOptions.colorSpace !== 'object') {++ throw new TypeError('decoderOptions.colorSpace, when provided, must be an object.');++ }++ new VideoSampleColorSpace(decoderOptions.colorSpace); // Validates the fields++ }++ if (decoderOptions.transformConfig !== undefined && typeof decoderOptions.transformConfig !== 'function') {++ throw new TypeError('decoderOptions.transformConfig, when provided, must be a function.');++ }++ if (decoderOptions.transformPacket !== undefined && typeof decoderOptions.transformPacket !== 'function') {++ throw new TypeError('decoderOptions.transformPacket, when provided, must be a function.');++ }+ };+ /**+ * A sink that retrieves decoded video samples (video frames) from a video track.+@@ -1350,12 +1443,19 @@ export class VideoSampleSink extends BaseMediaSampleSink {+ let decoderConfig = await this._track.getDecoderConfig();+ const timeResolution = await this._track.getTimeResolution();+ assert(codec && decoderConfig);++ const colorSpaceOverride = this._decoderOptions.colorSpace ?? null;+ decoderConfig = {+ ...decoderConfig,+ hardwareAcceleration: this._decoderOptions.hardwareAcceleration,+ optimizeForLatency: this._decoderOptions.optimizeForLatency,++ // The override replaces whatever the track carries, so the decoder emits frames tagged the way the++ // caller asked, in-band tags included.++ ...(colorSpaceOverride ? { colorSpace: colorSpaceOverride } : {}),+ };+- return new VideoDecoderWrapper(onSample, onError, codec, decoderConfig, rotation, timeResolution);++ if (this._decoderOptions.transformConfig) {++ decoderConfig = this._decoderOptions.transformConfig(decoderConfig);++ }++ return new VideoDecoderWrapper(onSample, onError, codec, decoderConfig, rotation, timeResolution, colorSpaceOverride, this._decoderOptions.transformPacket ?? null);+ }+ /** @internal */+ _createPacketSink() {diff --git a/site/public/cut/lut-file-mark.svg b/site/public/cut/lut-file-mark.svgnew file mode 100644index 00000000..967c615a--- /dev/null+++ b/site/public/cut/lut-file-mark.svg@@ -0,0 +1,112 @@+<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 512 512" width="512" height="512">+ <g transform="translate(256 256) scale(2) translate(-256 -235.6)">+ <polygon points="151.1,174.0 166.5,182.9 181.9,174.0 166.5,165.1" fill="#15ff15"/>+ <polygon points="169.0,163.7 184.4,172.6 199.8,163.7 184.4,154.8" fill="#15ff40"/>+ <polygon points="186.9,153.3 202.3,162.2 217.7,153.3 202.3,144.4" fill="#15ff6a"/>+ <polygon points="204.8,143.0 220.2,151.9 235.6,143.0 220.2,134.1" fill="#15ff95"/>+ <polygon points="222.7,132.7 238.1,141.6 253.5,132.7 238.1,123.8" fill="#15ffbf"/>+ <polygon points="240.6,122.3 256.0,131.2 271.4,122.3 256.0,113.4" fill="#15ffea"/>+ <polygon points="169.0,184.3 184.4,193.2 199.8,184.3 184.4,175.4" fill="#40ff15"/>+ <polygon points="186.9,174.0 202.3,182.9 217.7,174.0 202.3,165.1" fill="#40ff40"/>+ <polygon points="204.8,163.7 220.2,172.6 235.6,163.7 220.2,154.8" fill="#40ff6a"/>+ <polygon points="222.7,153.3 238.1,162.2 253.5,153.3 238.1,144.4" fill="#40ff95"/>+ <polygon points="240.6,143.0 256.0,151.9 271.4,143.0 256.0,134.1" fill="#40ffbf"/>+ <polygon points="258.5,132.7 273.9,141.6 289.3,132.7 273.9,123.8" fill="#40ffea"/>+ <polygon points="186.9,194.7 202.3,203.6 217.7,194.7 202.3,185.8" fill="#6aff15"/>+ <polygon points="204.8,184.3 220.2,193.2 235.6,184.3 220.2,175.4" fill="#6aff40"/>+ <polygon points="222.7,174.0 238.1,182.9 253.5,174.0 238.1,165.1" fill="#6aff6a"/>+ <polygon points="240.6,163.7 256.0,172.6 271.4,163.7 256.0,154.8" fill="#6aff95"/>+ <polygon points="258.5,153.3 273.9,162.2 289.3,153.3 273.9,144.4" fill="#6affbf"/>+ <polygon points="276.4,143.0 291.8,151.9 307.2,143.0 291.8,134.1" fill="#6affea"/>+ <polygon points="204.8,205.0 220.2,213.9 235.6,205.0 220.2,196.1" fill="#95ff15"/>+ <polygon points="222.7,194.7 238.1,203.6 253.5,194.7 238.1,185.8" fill="#95ff40"/>+ <polygon points="240.6,184.3 256.0,193.2 271.4,184.3 256.0,175.4" fill="#95ff6a"/>+ <polygon points="258.5,174.0 273.9,182.9 289.3,174.0 273.9,165.1" fill="#95ff95"/>+ <polygon points="276.4,163.7 291.8,172.6 307.2,163.7 291.8,154.8" fill="#95ffbf"/>+ <polygon points="294.3,153.3 309.7,162.2 325.1,153.3 309.7,144.4" fill="#95ffea"/>+ <polygon points="222.7,215.3 238.1,224.2 253.5,215.3 238.1,206.4" fill="#bfff15"/>+ <polygon points="240.6,205.0 256.0,213.9 271.4,205.0 256.0,196.1" fill="#bfff40"/>+ <polygon points="258.5,194.7 273.9,203.6 289.3,194.7 273.9,185.8" fill="#bfff6a"/>+ <polygon points="276.4,184.3 291.8,193.2 307.2,184.3 291.8,175.4" fill="#bfff95"/>+ <polygon points="294.3,174.0 309.7,182.9 325.1,174.0 309.7,165.1" fill="#bfffbf"/>+ <polygon points="312.2,163.7 327.6,172.6 343.0,163.7 327.6,154.8" fill="#bfffea"/>+ <polygon points="240.6,225.7 256.0,234.6 271.4,225.7 256.0,216.8" fill="#eaff15"/>+ <polygon points="258.5,215.3 273.9,224.2 289.3,215.3 273.9,206.4" fill="#eaff40"/>+ <polygon points="276.4,205.0 291.8,213.9 307.2,205.0 291.8,196.1" fill="#eaff6a"/>+ <polygon points="294.3,194.7 309.7,203.6 325.1,194.7 309.7,185.8" fill="#eaff95"/>+ <polygon points="312.2,184.3 327.6,193.2 343.0,184.3 327.6,175.4" fill="#eaffbf"/>+ <polygon points="330.1,174.0 345.5,182.9 360.9,174.0 345.5,165.1" fill="#eaffea"/>+ <polygon points="149.9,297.3 165.3,306.2 165.3,288.4 149.9,279.5" fill="#151500"/>+ <polygon points="149.9,276.6 165.3,285.5 165.3,267.7 149.9,258.8" fill="#154000"/>+ <polygon points="149.9,255.9 165.3,264.8 165.3,247.1 149.9,238.2" fill="#156a00"/>+ <polygon points="149.9,235.3 165.3,244.2 165.3,226.4 149.9,217.5" fill="#159500"/>+ <polygon points="149.9,214.6 165.3,223.5 165.3,205.7 149.9,196.8" fill="#15bf00"/>+ <polygon points="149.9,193.9 165.3,202.8 165.3,185.1 149.9,176.2" fill="#15ea00"/>+ <polygon points="167.8,307.6 183.2,316.5 183.2,298.7 167.8,289.8" fill="#401500"/>+ <polygon points="167.8,286.9 183.2,295.8 183.2,278.1 167.8,269.2" fill="#404000"/>+ <polygon points="167.8,266.3 183.2,275.2 183.2,257.4 167.8,248.5" fill="#406a00"/>+ <polygon points="167.8,245.6 183.2,254.5 183.2,236.7 167.8,227.8" fill="#409500"/>+ <polygon points="167.8,224.9 183.2,233.8 183.2,216.1 167.8,207.2" fill="#40bf00"/>+ <polygon points="167.8,204.3 183.2,213.2 183.2,195.4 167.8,186.5" fill="#40ea00"/>+ <polygon points="185.7,317.9 201.1,326.8 201.1,309.1 185.7,300.2" fill="#6a1500"/>+ <polygon points="185.7,297.3 201.1,306.2 201.1,288.4 185.7,279.5" fill="#6a4000"/>+ <polygon points="185.7,276.6 201.1,285.5 201.1,267.7 185.7,258.8" fill="#6a6a00"/>+ <polygon points="185.7,255.9 201.1,264.8 201.1,247.1 185.7,238.2" fill="#6a9500"/>+ <polygon points="185.7,235.3 201.1,244.2 201.1,226.4 185.7,217.5" fill="#6abf00"/>+ <polygon points="185.7,214.6 201.1,223.5 201.1,205.7 185.7,196.8" fill="#6aea00"/>+ <polygon points="203.6,328.3 219.0,337.2 219.0,319.4 203.6,310.5" fill="#951500"/>+ <polygon points="203.6,307.6 219.0,316.5 219.0,298.7 203.6,289.8" fill="#954000"/>+ <polygon points="203.6,286.9 219.0,295.8 219.0,278.1 203.6,269.2" fill="#956a00"/>+ <polygon points="203.6,266.3 219.0,275.2 219.0,257.4 203.6,248.5" fill="#959500"/>+ <polygon points="203.6,245.6 219.0,254.5 219.0,236.7 203.6,227.8" fill="#95bf00"/>+ <polygon points="203.6,224.9 219.0,233.8 219.0,216.1 203.6,207.2" fill="#95ea00"/>+ <polygon points="221.5,338.6 236.8,347.5 236.8,329.7 221.5,320.8" fill="#bf1500"/>+ <polygon points="221.5,317.9 236.8,326.8 236.8,309.1 221.5,300.2" fill="#bf4000"/>+ <polygon points="221.5,297.3 236.8,306.2 236.8,288.4 221.5,279.5" fill="#bf6a00"/>+ <polygon points="221.5,276.6 236.8,285.5 236.8,267.7 221.5,258.8" fill="#bf9500"/>+ <polygon points="221.5,255.9 236.8,264.8 236.8,247.1 221.5,238.2" fill="#bfbf00"/>+ <polygon points="221.5,235.3 236.8,244.2 236.8,226.4 221.5,217.5" fill="#bfea00"/>+ <polygon points="239.4,348.9 254.7,357.8 254.7,340.1 239.4,331.2" fill="#ea1500"/>+ <polygon points="239.4,328.3 254.7,337.2 254.7,319.4 239.4,310.5" fill="#ea4000"/>+ <polygon points="239.4,307.6 254.7,316.5 254.7,298.7 239.4,289.8" fill="#ea6a00"/>+ <polygon points="239.4,286.9 254.7,295.8 254.7,278.1 239.4,269.2" fill="#ea9500"/>+ <polygon points="239.4,266.3 254.7,275.2 254.7,257.4 239.4,248.5" fill="#eabf00"/>+ <polygon points="239.4,245.6 254.7,254.5 254.7,236.7 239.4,227.8" fill="#eaea00"/>+ <polygon points="257.3,357.8 257.3,340.1 272.6,331.2 272.6,348.9" fill="#ff1515"/>+ <polygon points="275.2,347.5 275.2,329.7 290.5,320.8 290.5,338.6" fill="#ff1540"/>+ <polygon points="293.0,337.2 293.0,319.4 308.4,310.5 308.4,328.3" fill="#ff156a"/>+ <polygon points="310.9,326.8 310.9,309.1 326.3,300.2 326.3,317.9" fill="#ff1595"/>+ <polygon points="328.8,316.5 328.8,298.7 344.2,289.8 344.2,307.6" fill="#ff15bf"/>+ <polygon points="346.7,306.2 346.7,288.4 362.1,279.5 362.1,297.3" fill="#ff15ea"/>+ <polygon points="257.3,337.2 257.3,319.4 272.6,310.5 272.6,328.3" fill="#ff4015"/>+ <polygon points="275.2,326.8 275.2,309.1 290.5,300.2 290.5,317.9" fill="#ff4040"/>+ <polygon points="293.0,316.5 293.0,298.7 308.4,289.8 308.4,307.6" fill="#ff406a"/>+ <polygon points="310.9,306.2 310.9,288.4 326.3,279.5 326.3,297.3" fill="#ff4095"/>+ <polygon points="328.8,295.8 328.8,278.1 344.2,269.2 344.2,286.9" fill="#ff40bf"/>+ <polygon points="346.7,285.5 346.7,267.7 362.1,258.8 362.1,276.6" fill="#ff40ea"/>+ <polygon points="257.3,316.5 257.3,298.7 272.6,289.8 272.6,307.6" fill="#ff6a15"/>+ <polygon points="275.2,306.2 275.2,288.4 290.5,279.5 290.5,297.3" fill="#ff6a40"/>+ <polygon points="293.0,295.8 293.0,278.1 308.4,269.2 308.4,286.9" fill="#ff6a6a"/>+ <polygon points="310.9,285.5 310.9,267.7 326.3,258.8 326.3,276.6" fill="#ff6a95"/>+ <polygon points="328.8,275.2 328.8,257.4 344.2,248.5 344.2,266.3" fill="#ff6abf"/>+ <polygon points="346.7,264.8 346.7,247.1 362.1,238.2 362.1,255.9" fill="#ff6aea"/>+ <polygon points="257.3,295.8 257.3,278.1 272.6,269.2 272.6,286.9" fill="#ff9515"/>+ <polygon points="275.2,285.5 275.2,267.7 290.5,258.8 290.5,276.6" fill="#ff9540"/>+ <polygon points="293.0,275.2 293.0,257.4 308.4,248.5 308.4,266.3" fill="#ff956a"/>+ <polygon points="310.9,264.8 310.9,247.1 326.3,238.2 326.3,255.9" fill="#ff9595"/>+ <polygon points="328.8,254.5 328.8,236.7 344.2,227.8 344.2,245.6" fill="#ff95bf"/>+ <polygon points="346.7,244.2 346.7,226.4 362.1,217.5 362.1,235.3" fill="#ff95ea"/>+ <polygon points="257.3,275.2 257.3,257.4 272.6,248.5 272.6,266.3" fill="#ffbf15"/>+ <polygon points="275.2,264.8 275.2,247.1 290.5,238.2 290.5,255.9" fill="#ffbf40"/>+ <polygon points="293.0,254.5 293.0,236.7 308.4,227.8 308.4,245.6" fill="#ffbf6a"/>+ <polygon points="310.9,244.2 310.9,226.4 326.3,217.5 326.3,235.3" fill="#ffbf95"/>+ <polygon points="328.8,233.8 328.8,216.1 344.2,207.2 344.2,224.9" fill="#ffbfbf"/>+ <polygon points="346.7,223.5 346.7,205.7 362.1,196.8 362.1,214.6" fill="#ffbfea"/>+ <polygon points="257.3,254.5 257.3,236.7 272.6,227.8 272.6,245.6" fill="#ffea15"/>+ <polygon points="275.2,244.2 275.2,226.4 290.5,217.5 290.5,235.3" fill="#ffea40"/>+ <polygon points="293.0,233.8 293.0,216.1 308.4,207.2 308.4,224.9" fill="#ffea6a"/>+ <polygon points="310.9,223.5 310.9,205.7 326.3,196.8 326.3,214.6" fill="#ffea95"/>+ <polygon points="328.8,213.2 328.8,195.4 344.2,186.5 344.2,204.3" fill="#ffeabf"/>+ <polygon points="346.7,202.8 346.7,185.1 362.1,176.2 362.1,193.9" fill="#ffeaea"/>+ </g>+</svg>diff --git a/site/public/cut/lut-file.svg b/site/public/cut/lut-file.svgnew file mode 100644index 00000000..1692efec--- /dev/null+++ b/site/public/cut/lut-file.svg@@ -0,0 +1,113 @@+<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 512 512" width="512" height="512">+ <g transform="translate(256 212) scale(1.6) translate(-256 -235.6)">+ <polygon points="151.1,174.0 166.5,182.9 181.9,174.0 166.5,165.1" fill="#15ff15"/>+ <polygon points="169.0,163.7 184.4,172.6 199.8,163.7 184.4,154.8" fill="#15ff40"/>+ <polygon points="186.9,153.3 202.3,162.2 217.7,153.3 202.3,144.4" fill="#15ff6a"/>+ <polygon points="204.8,143.0 220.2,151.9 235.6,143.0 220.2,134.1" fill="#15ff95"/>+ <polygon points="222.7,132.7 238.1,141.6 253.5,132.7 238.1,123.8" fill="#15ffbf"/>+ <polygon points="240.6,122.3 256.0,131.2 271.4,122.3 256.0,113.4" fill="#15ffea"/>+ <polygon points="169.0,184.3 184.4,193.2 199.8,184.3 184.4,175.4" fill="#40ff15"/>+ <polygon points="186.9,174.0 202.3,182.9 217.7,174.0 202.3,165.1" fill="#40ff40"/>+ <polygon points="204.8,163.7 220.2,172.6 235.6,163.7 220.2,154.8" fill="#40ff6a"/>+ <polygon points="222.7,153.3 238.1,162.2 253.5,153.3 238.1,144.4" fill="#40ff95"/>+ <polygon points="240.6,143.0 256.0,151.9 271.4,143.0 256.0,134.1" fill="#40ffbf"/>+ <polygon points="258.5,132.7 273.9,141.6 289.3,132.7 273.9,123.8" fill="#40ffea"/>+ <polygon points="186.9,194.7 202.3,203.6 217.7,194.7 202.3,185.8" fill="#6aff15"/>+ <polygon points="204.8,184.3 220.2,193.2 235.6,184.3 220.2,175.4" fill="#6aff40"/>+ <polygon points="222.7,174.0 238.1,182.9 253.5,174.0 238.1,165.1" fill="#6aff6a"/>+ <polygon points="240.6,163.7 256.0,172.6 271.4,163.7 256.0,154.8" fill="#6aff95"/>+ <polygon points="258.5,153.3 273.9,162.2 289.3,153.3 273.9,144.4" fill="#6affbf"/>+ <polygon points="276.4,143.0 291.8,151.9 307.2,143.0 291.8,134.1" fill="#6affea"/>+ <polygon points="204.8,205.0 220.2,213.9 235.6,205.0 220.2,196.1" fill="#95ff15"/>+ <polygon points="222.7,194.7 238.1,203.6 253.5,194.7 238.1,185.8" fill="#95ff40"/>+ <polygon points="240.6,184.3 256.0,193.2 271.4,184.3 256.0,175.4" fill="#95ff6a"/>+ <polygon points="258.5,174.0 273.9,182.9 289.3,174.0 273.9,165.1" fill="#95ff95"/>+ <polygon points="276.4,163.7 291.8,172.6 307.2,163.7 291.8,154.8" fill="#95ffbf"/>+ <polygon points="294.3,153.3 309.7,162.2 325.1,153.3 309.7,144.4" fill="#95ffea"/>+ <polygon points="222.7,215.3 238.1,224.2 253.5,215.3 238.1,206.4" fill="#bfff15"/>+ <polygon points="240.6,205.0 256.0,213.9 271.4,205.0 256.0,196.1" fill="#bfff40"/>+ <polygon points="258.5,194.7 273.9,203.6 289.3,194.7 273.9,185.8" fill="#bfff6a"/>+ <polygon points="276.4,184.3 291.8,193.2 307.2,184.3 291.8,175.4" fill="#bfff95"/>+ <polygon points="294.3,174.0 309.7,182.9 325.1,174.0 309.7,165.1" fill="#bfffbf"/>+ <polygon points="312.2,163.7 327.6,172.6 343.0,163.7 327.6,154.8" fill="#bfffea"/>+ <polygon points="240.6,225.7 256.0,234.6 271.4,225.7 256.0,216.8" fill="#eaff15"/>+ <polygon points="258.5,215.3 273.9,224.2 289.3,215.3 273.9,206.4" fill="#eaff40"/>+ <polygon points="276.4,205.0 291.8,213.9 307.2,205.0 291.8,196.1" fill="#eaff6a"/>+ <polygon points="294.3,194.7 309.7,203.6 325.1,194.7 309.7,185.8" fill="#eaff95"/>+ <polygon points="312.2,184.3 327.6,193.2 343.0,184.3 327.6,175.4" fill="#eaffbf"/>+ <polygon points="330.1,174.0 345.5,182.9 360.9,174.0 345.5,165.1" fill="#eaffea"/>+ <polygon points="149.9,297.3 165.3,306.2 165.3,288.4 149.9,279.5" fill="#151500"/>+ <polygon points="149.9,276.6 165.3,285.5 165.3,267.7 149.9,258.8" fill="#154000"/>+ <polygon points="149.9,255.9 165.3,264.8 165.3,247.1 149.9,238.2" fill="#156a00"/>+ <polygon points="149.9,235.3 165.3,244.2 165.3,226.4 149.9,217.5" fill="#159500"/>+ <polygon points="149.9,214.6 165.3,223.5 165.3,205.7 149.9,196.8" fill="#15bf00"/>+ <polygon points="149.9,193.9 165.3,202.8 165.3,185.1 149.9,176.2" fill="#15ea00"/>+ <polygon points="167.8,307.6 183.2,316.5 183.2,298.7 167.8,289.8" fill="#401500"/>+ <polygon points="167.8,286.9 183.2,295.8 183.2,278.1 167.8,269.2" fill="#404000"/>+ <polygon points="167.8,266.3 183.2,275.2 183.2,257.4 167.8,248.5" fill="#406a00"/>+ <polygon points="167.8,245.6 183.2,254.5 183.2,236.7 167.8,227.8" fill="#409500"/>+ <polygon points="167.8,224.9 183.2,233.8 183.2,216.1 167.8,207.2" fill="#40bf00"/>+ <polygon points="167.8,204.3 183.2,213.2 183.2,195.4 167.8,186.5" fill="#40ea00"/>+ <polygon points="185.7,317.9 201.1,326.8 201.1,309.1 185.7,300.2" fill="#6a1500"/>+ <polygon points="185.7,297.3 201.1,306.2 201.1,288.4 185.7,279.5" fill="#6a4000"/>+ <polygon points="185.7,276.6 201.1,285.5 201.1,267.7 185.7,258.8" fill="#6a6a00"/>+ <polygon points="185.7,255.9 201.1,264.8 201.1,247.1 185.7,238.2" fill="#6a9500"/>+ <polygon points="185.7,235.3 201.1,244.2 201.1,226.4 185.7,217.5" fill="#6abf00"/>+ <polygon points="185.7,214.6 201.1,223.5 201.1,205.7 185.7,196.8" fill="#6aea00"/>+ <polygon points="203.6,328.3 219.0,337.2 219.0,319.4 203.6,310.5" fill="#951500"/>+ <polygon points="203.6,307.6 219.0,316.5 219.0,298.7 203.6,289.8" fill="#954000"/>+ <polygon points="203.6,286.9 219.0,295.8 219.0,278.1 203.6,269.2" fill="#956a00"/>+ <polygon points="203.6,266.3 219.0,275.2 219.0,257.4 203.6,248.5" fill="#959500"/>+ <polygon points="203.6,245.6 219.0,254.5 219.0,236.7 203.6,227.8" fill="#95bf00"/>+ <polygon points="203.6,224.9 219.0,233.8 219.0,216.1 203.6,207.2" fill="#95ea00"/>+ <polygon points="221.5,338.6 236.8,347.5 236.8,329.7 221.5,320.8" fill="#bf1500"/>+ <polygon points="221.5,317.9 236.8,326.8 236.8,309.1 221.5,300.2" fill="#bf4000"/>+ <polygon points="221.5,297.3 236.8,306.2 236.8,288.4 221.5,279.5" fill="#bf6a00"/>+ <polygon points="221.5,276.6 236.8,285.5 236.8,267.7 221.5,258.8" fill="#bf9500"/>+ <polygon points="221.5,255.9 236.8,264.8 236.8,247.1 221.5,238.2" fill="#bfbf00"/>+ <polygon points="221.5,235.3 236.8,244.2 236.8,226.4 221.5,217.5" fill="#bfea00"/>+ <polygon points="239.4,348.9 254.7,357.8 254.7,340.1 239.4,331.2" fill="#ea1500"/>+ <polygon points="239.4,328.3 254.7,337.2 254.7,319.4 239.4,310.5" fill="#ea4000"/>+ <polygon points="239.4,307.6 254.7,316.5 254.7,298.7 239.4,289.8" fill="#ea6a00"/>+ <polygon points="239.4,286.9 254.7,295.8 254.7,278.1 239.4,269.2" fill="#ea9500"/>+ <polygon points="239.4,266.3 254.7,275.2 254.7,257.4 239.4,248.5" fill="#eabf00"/>+ <polygon points="239.4,245.6 254.7,254.5 254.7,236.7 239.4,227.8" fill="#eaea00"/>+ <polygon points="257.3,357.8 257.3,340.1 272.6,331.2 272.6,348.9" fill="#ff1515"/>+ <polygon points="275.2,347.5 275.2,329.7 290.5,320.8 290.5,338.6" fill="#ff1540"/>+ <polygon points="293.0,337.2 293.0,319.4 308.4,310.5 308.4,328.3" fill="#ff156a"/>+ <polygon points="310.9,326.8 310.9,309.1 326.3,300.2 326.3,317.9" fill="#ff1595"/>+ <polygon points="328.8,316.5 328.8,298.7 344.2,289.8 344.2,307.6" fill="#ff15bf"/>+ <polygon points="346.7,306.2 346.7,288.4 362.1,279.5 362.1,297.3" fill="#ff15ea"/>+ <polygon points="257.3,337.2 257.3,319.4 272.6,310.5 272.6,328.3" fill="#ff4015"/>+ <polygon points="275.2,326.8 275.2,309.1 290.5,300.2 290.5,317.9" fill="#ff4040"/>+ <polygon points="293.0,316.5 293.0,298.7 308.4,289.8 308.4,307.6" fill="#ff406a"/>+ <polygon points="310.9,306.2 310.9,288.4 326.3,279.5 326.3,297.3" fill="#ff4095"/>+ <polygon points="328.8,295.8 328.8,278.1 344.2,269.2 344.2,286.9" fill="#ff40bf"/>+ <polygon points="346.7,285.5 346.7,267.7 362.1,258.8 362.1,276.6" fill="#ff40ea"/>+ <polygon points="257.3,316.5 257.3,298.7 272.6,289.8 272.6,307.6" fill="#ff6a15"/>+ <polygon points="275.2,306.2 275.2,288.4 290.5,279.5 290.5,297.3" fill="#ff6a40"/>+ <polygon points="293.0,295.8 293.0,278.1 308.4,269.2 308.4,286.9" fill="#ff6a6a"/>+ <polygon points="310.9,285.5 310.9,267.7 326.3,258.8 326.3,276.6" fill="#ff6a95"/>+ <polygon points="328.8,275.2 328.8,257.4 344.2,248.5 344.2,266.3" fill="#ff6abf"/>+ <polygon points="346.7,264.8 346.7,247.1 362.1,238.2 362.1,255.9" fill="#ff6aea"/>+ <polygon points="257.3,295.8 257.3,278.1 272.6,269.2 272.6,286.9" fill="#ff9515"/>+ <polygon points="275.2,285.5 275.2,267.7 290.5,258.8 290.5,276.6" fill="#ff9540"/>+ <polygon points="293.0,275.2 293.0,257.4 308.4,248.5 308.4,266.3" fill="#ff956a"/>+ <polygon points="310.9,264.8 310.9,247.1 326.3,238.2 326.3,255.9" fill="#ff9595"/>+ <polygon points="328.8,254.5 328.8,236.7 344.2,227.8 344.2,245.6" fill="#ff95bf"/>+ <polygon points="346.7,244.2 346.7,226.4 362.1,217.5 362.1,235.3" fill="#ff95ea"/>+ <polygon points="257.3,275.2 257.3,257.4 272.6,248.5 272.6,266.3" fill="#ffbf15"/>+ <polygon points="275.2,264.8 275.2,247.1 290.5,238.2 290.5,255.9" fill="#ffbf40"/>+ <polygon points="293.0,254.5 293.0,236.7 308.4,227.8 308.4,245.6" fill="#ffbf6a"/>+ <polygon points="310.9,244.2 310.9,226.4 326.3,217.5 326.3,235.3" fill="#ffbf95"/>+ <polygon points="328.8,233.8 328.8,216.1 344.2,207.2 344.2,224.9" fill="#ffbfbf"/>+ <polygon points="346.7,223.5 346.7,205.7 362.1,196.8 362.1,214.6" fill="#ffbfea"/>+ <polygon points="257.3,254.5 257.3,236.7 272.6,227.8 272.6,245.6" fill="#ffea15"/>+ <polygon points="275.2,244.2 275.2,226.4 290.5,217.5 290.5,235.3" fill="#ffea40"/>+ <polygon points="293.0,233.8 293.0,216.1 308.4,207.2 308.4,224.9" fill="#ffea6a"/>+ <polygon points="310.9,223.5 310.9,205.7 326.3,196.8 326.3,214.6" fill="#ffea95"/>+ <polygon points="328.8,213.2 328.8,195.4 344.2,186.5 344.2,204.3" fill="#ffeabf"/>+ <polygon points="346.7,202.8 346.7,185.1 362.1,176.2 362.1,193.9" fill="#ffeaea"/>+ </g>+ <text x="256" y="494" text-anchor="middle" font-family="-apple-system, 'SF Pro Text', Inter, 'Helvetica Neue', Arial, sans-serif" font-size="56" font-weight="700" letter-spacing="6" fill="#1F2328">LUT</text>+</svg>diff --git a/site/scripts/lib/cut-eval/cases.ts b/site/scripts/lib/cut-eval/cases.tsindex 4559a42e..28e9883b 100644--- a/site/scripts/lib/cut-eval/cases.ts+++ b/site/scripts/lib/cut-eval/cases.ts@@ -30,6 +30,7 @@ import {STRANDED_TITLE_STATE,TWEET_ASSET,TWEET_STATE,+ LUT_STATE,TWO_CLIP_STATE,type EvalMessage,assistantToolTurn,@@ -304,6 +305,57 @@ export function cases(audio: { dataBase64: string; mimeType: string }): EvalCase},},},+ {+ // A LUT already on one clip, asked onto every clip: one copy of the+ // grade (or one LUT sweep over the whole timeline), no clip-by-clip+ // walk and no fresh LUT invented.+ name: "lut-to-all-clips",+ instant: null,+ bucket: "single-tool",+ state: LUT_STATE,+ input: () => [userTurn("apply this LUT to all clips")],+ reply: /LUT|look|all|both|every|clips/i,+ anyTools: ["copy_color_grade", "set_color_lut"],+ maxToolCalls: 4,+ simulate: () => (name, args) => {+ if (name === "set_color_lut") {+ if (args.lut !== "lut:kodak2383")+ throw new Error(`set_color_lut must name the shelf LUT, got ${JSON.stringify(args.lut)}`);+ if (args.all_clips !== true && !Array.isArray(args.ids))+ throw new Error("set_color_lut must land on all clips (all_clips or ids), not one at a time");+ return { ran: 2, ids: ["c1", "c2"], results: [] };+ }+ if (name === "copy_color_grade") {+ if (args.clipId !== "c1") throw new Error(`copy_color_grade must copy from c1, got ${JSON.stringify(args.clipId)}`);+ if (args.all_clips !== true && !Array.isArray(args.ids))+ throw new Error("copy_color_grade must land on all clips (all_clips or ids)");+ return { from: "c1", ids: ["c2"], grade: { lut: { id: "lut:kodak2383" } } };+ }+ return undefined;+ },+ },+ {+ // Footage the header did not settle, named by the user: the source+ // colour switch, not a grade that fights the log curve by hand.+ name: "convert-apple-log-source",+ instant: null,+ bucket: "single-tool",+ state: LUT_STATE,+ input: () => [userTurn("this beach footage is Apple Log, convert it")],+ reply: /Apple Log|converted|Rec\.?709|source/i,+ requiredTools: ["set_source_color"],+ maxToolCalls: 4,+ simulate: () => (name, args) => {+ if (name === "set_source_color") {+ if (args.profile !== "apple-log")+ throw new Error(`set_source_color must pick apple-log, got ${JSON.stringify(args.profile)}`);+ return { assetId: "a-v1", profile: "apple-log", detected: "rec709", clips: ["c1", "c2"] };+ }+ if (name === "set_color_grade" || name === "set_color_lut")+ throw new Error(`${name} — a log source is converted with set_source_color, never graded by hand`);+ return undefined;+ },+ },{// The screenshot regression: after a turn that imported a reference and// styled the cut, "mute all clips" mutes and stops. A replayeddiff --git a/site/scripts/lib/cut-eval/fixtures.ts b/site/scripts/lib/cut-eval/fixtures.tsindex 4efdbbd2..2b2fbf84 100644--- a/site/scripts/lib/cut-eval/fixtures.ts+++ b/site/scripts/lib/cut-eval/fixtures.ts@@ -184,6 +184,19 @@ export const TWO_CLIP_STATE = {],};+/** The pair with a Library LUT on the first clip and the shelf's LUT list,+ * for the copy-to-all case; the source is listed as plain Rec.709 with no+ * header reading, for the source-colour case. */+export const LUT_STATE = {+ ...TWO_CLIP_STATE,+ luts: [{ id: "lut:kodak2383", label: "Kodak 2383" }],+ savedGrades: [],+ videoTrack: [+ { ...TWO_CLIP_STATE.videoTrack[0], lut: { id: "lut:kodak2383", amount: 1 } },+ TWO_CLIP_STATE.videoTrack[1],+ ],+};+/** The same pair already joined by a crossfade, for the edge-override case. */export const CROSSFADED_STATE = {...TWO_CLIP_STATE,diff --git a/site/src/cut/components/AiPanel.tools.ts b/site/src/cut/components/AiPanel.tools.tsindex 24180495..6267f22f 100644--- a/site/src/cut/components/AiPanel.tools.ts+++ b/site/src/cut/components/AiPanel.tools.ts@@ -172,7 +172,7 @@ export const AI_PANEL_TOOLS = [{name: "import_url",description:- "Read any URL — TikTok, YouTube, Instagram Reels, an X/Twitter post or Article, an ordinary web page, or a direct video/audio/image link — with the bundled downloader and import what it holds into the project. Free and local. A web page comes back as its article text plus the pictures on it; a post as its video or photos; and the source's own words (returned as sourceText) are quoted for the user beside the media automatically — don't retype them in your reply. A source that is only words returns sourceText with no assets, which is a success: read it and answer from it. This is how you look something up: point it at the page and read what comes back. When the user wants only the sound — a song, a soundtrack, a podcast — pass audio_only and the source's audio track lands as an audio asset. Media lands on a card in this chat and the user drags it to the timeline, Media, or the Library; place it yourself (add_clip) only when they asked for it in the cut. A short clip downloads in seconds; a long video can take a couple of minutes.",+ "Read a web or media URL. For Donkey folder links use read_folder; for Donkey project links use read_project. Supports TikTok, YouTube, Instagram Reels, an X/Twitter post or Article, an ordinary web page, or a direct video/audio/image link — with the bundled downloader and import what it holds into the project. Free and local. A web page comes back as its article text plus the pictures on it; a post as its video or photos; and the source's own words (returned as sourceText) are quoted for the user beside the media automatically — don't retype them in your reply. A source that is only words returns sourceText with no assets, which is a success: read it and answer from it. This is how you look something up: point it at the page and read what comes back. When the user wants only the sound — a song, a soundtrack, a podcast — pass audio_only and the source's audio track lands as an audio asset. Media lands on a card in this chat and the user drags it to the timeline, Media, or the Library; place it yourself (add_clip) only when they asked for it in the cut. A short clip downloads in seconds; a long video can take a couple of minutes.",inputSchema: obj({url: str("The page or media URL to download"),diff --git a/site/src/cut/components/ColorPanel.tsx b/site/src/cut/components/ColorPanel.tsxindex 32c717c0..56b56d7c 100644--- a/site/src/cut/components/ColorPanel.tsx+++ b/site/src/cut/components/ColorPanel.tsx@@ -1,33 +1,64 @@"use client";import { useEffect, useMemo, useRef, useState } from "react";-import { ChevronLeft, RotateCcw, SlidersHorizontal, Wand2 } from "lucide-react";+import { useQueryClient } from "@tanstack/react-query";+import { ChevronLeft, Loader2, RotateCcw, SlidersHorizontal, Trash2, Wand2, X } from "lucide-react";import {applyLutToImageData,autoGradeFromImageData,- buildGradeLut,+ buildClipLut,GRADE_BASIC_FIELDS,+ GRADE_DETAIL_FIELDS,GRADE_HUE_MAX,GRADE_MAX,GRADE_PRESET_CATEGORIES,gradeCssApprox,+ gradeKey,gradePresetsInCategory,gradeToolDirty,HSL_BANDS,normalizeGrade,+ OUTPUT_SPACES,+ SOURCE_PROFILES,+ WHEEL_LABELS,+ WHEEL_ZONES,type ColorGrade,type GradeLut,type GradePreset,type GradePresetCategory,type HslBand,type HslTuple,+ type OutputSpace,+ type ParsedLut,+ type SourceProfile,type WheelTuple,+ type WheelZone,} from "@donkeycut/effects-kit";-import { getPreviewCanvas, sampleClipFrameData } from "@/cut/lib/previewCanvas";+import { getPreviewCanvas } from "@/cut/lib/previewCanvas";+import { beginLutDraft, endLutDraft } from "@/cut/lib/lutBuild";+import { sampleClipBaseFrameData, sourceProfileOf, toBaseRendering } from "@/cut/lib/baseFrame";import { useEditor } from "@/cut/lib/store";import { usePanelState, useRememberedScroll } from "@/cut/lib/panelState";-import type { VideoClip } from "@/cut/lib/types";-import { ResetButton, Row, useSliderCheckpoint } from "@/cut/components/panelBits";+import type { MediaAsset, VideoClip } from "@/cut/lib/types";+import { needsProxy, useProxyJobs } from "@/cut/lib/mediaProxy";+import {+ cachedLut,+ libraryLutId,+ listLibraryLuts,+ loadLibraryLut,+ LUT_MARK_ICON,+ lutIdOf,+ onLinkedChanged,+} from "@/cut/lib/linkedLibrary";+import {+ deleteGradePreset,+ rememberSavedGrades,+ saveGradePreset,+ savedGradeOf,+ type SavedGrade,+} from "@/cut/lib/gradePresets";+import { patchLibrary, refetchLibrary, useLibrary } from "@/cut/lib/queries";+import { ResetButton, Row, Tip, useSliderCheckpoint } from "@/cut/components/panelBits";import { ColorWheel } from "@/cut/components/ColorWheel";import { CurveEditor } from "@/cut/components/CurveEditor";import { ValueSlider } from "@/cut/components/ValueSlider";@@ -35,19 +66,27 @@ import { parseNumberInput } from "@/cut/components/ScrubValue";import { useClipSourceFrame } from "@/cut/components/usePlayheadFrame";import { cn } from "@/lib/utils";import { PICKED_RING } from "@/cut/lib/assetPick";+import { draggedLutKey } from "@/cut/lib/assetDrag";+import { Button } from "@/components/ui/button";+import { Dialog, DialogContent, DialogFooter, DialogHeader, DialogTitle } from "@/components/ui/dialog";+import { Input } from "@/components/ui/input";import { ScrollArea } from "@/components/ui/scroll-area";+import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select";import { Switch } from "@/components/ui/switch";+import { Tooltip, TooltipContent, TooltipTrigger } from "@/components/ui/tooltip";/*** The clip panel's Color subview, two levels deep. The first level is the- * preset grid — category chips over click-to-apply tiles, with the applied+ * preset grid — the source-colour switch, category chips over click-to-apply+ * tiles (the shipped catalog and the person's saved grades), the applied* preset's intensity and skin-tone protection on the panel floor. The second* level, behind the header's sliders button, is Adjust: Basic sliders,- * Curves, Wheels and per-hue HSL as segmented tools, every manual adjustment- * layering over whatever preset is applied. Both levels write the one `grade`- * field, drafts stream through the transient updater under one history- * checkpoint per gesture, and preview, filmstrip and exports render the same- * numbers.+ * Curves, Wheels, per-hue HSL and the LUT as segmented tools, every+ * manual adjustment layering over whatever preset is applied. Both levels+ * write the one `grade` field, drafts stream through the transient updater+ * under one history checkpoint per gesture, and preview, filmstrip and+ * exports render the same numbers. Both levels end in the same footer: save+ * the grade as a preset, or land it on the selection or every clip.*/export function ColorPanel({ clip, peers }: { clip: VideoClip; peers?: readonly VideoClip[] }) {// The open level holds for the session per clip, so deselecting and coming@@ -60,67 +99,305 @@ export function ColorPanel({ clip, peers }: { clip: VideoClip; peers?: readonlyreturn <PresetView clip={clip} peers={peers} onAdjust={() => setView("adjust")} />;}-/** The tools of the Adjust view; `dirty` feeds each tab's marker dot. */+/** The tools of the Adjust view; `dirty` feeds each tab's marker dot. The+ * Basic tab owns the Detail group too. */const TOOLS = [{ id: "basic", label: "Basic" },{ id: "curves", label: "Curves" },{ id: "wheels", label: "Wheels" },{ id: "hsl", label: "HSL" },+ { id: "lut", label: "LUT" },] as const;type Tool = (typeof TOOLS)[number]["id"];+const toolDirty = (g: ColorGrade | undefined, tool: Tool) =>+ tool === "basic" ? gradeToolDirty(g, "basic") || gradeToolDirty(g, "detail") : gradeToolDirty(g, tool);+/** Shared write path: normalize and store a whole grade, transiently while a- * gesture is live, committed at its end. */+ * gesture is live, committed at its end. A live gesture — a slider, wheel or+ * curve drag — bakes its LUTs at the draft size; the commit brings the full+ * cube back. */function useGradeWriter(clip: VideoClip, peers?: readonly VideoClip[]) {const ck = useSliderCheckpoint();+ const drafting = useRef(false);+ const settle = () => {+ if (!drafting.current) return;+ drafting.current = false;+ endLutDraft();+ };+ // A panel unmounted mid-drag still ends its draft.+ useEffect(() => settle, []);const write = (g: ColorGrade | undefined) => {// The checkpoint taken on the gesture's first change is the whole undo// step, so every write — drag frames and the commit alike — goes through// the transient updater. updateClip would push a second checkpoint and// make ⌘Z a two-press affair.ck.begin();+ if (!drafting.current) {+ drafting.current = true;+ beginLutDraft();+ }const grade = normalizeGrade(g);useEditor.getState().updateClipsTransient((peers ?? [clip]).map((c) => ({ id: c.id, patch: { grade } })));};const commit = (g: ColorGrade | undefined) => {write(g);ck.end();+ settle();};return { draft: write, commit };}++/* ------------------------------------------------------------------ */+/* Source colour */+/* ------------------------------------------------------------------ */++/** What the clip's code values mean. The header's reading is the default;+ * picking another profile writes the override onto the asset, with undo. */+function SourceColorRow({ clip }: { clip: VideoClip }) {+ const asset = useEditor((s) => s.assets.find((a) => a.id === clip.assetId));+ if (!asset || (asset.type !== "video" && asset.type !== "image")) return null;+ const detected: SourceProfile = asset.color?.detected ?? "rec709";+ const value = sourceProfileOf(asset);+ // The menu sets what the file said, and what Rec.709 means here, as a+ // small line under the name; the button carries the name alone.+ const noteOf = (id: SourceProfile) =>+ [id === detected && "Detected", id === "rec709" && "No conversion"].filter(Boolean).join(" · ");+ const items = Object.fromEntries(SOURCE_PROFILES.map((p) => [p.id, p.label]));+ return (+ <div className="px-3.5">+ <Row label="Source color">+ <Select+ value={value}+ items={items}+ onValueChange={(id) =>+ useEditor+ .getState()+ .setAssetColorProfile(asset.id, id === detected ? undefined : (id as SourceProfile))+ }+ >+ <SelectTrigger className="clip-source-color h-8 w-36 text-[12px]">+ <SelectValue />+ </SelectTrigger>+ <SelectContent>+ {SOURCE_PROFILES.map((p) => {+ const note = noteOf(p.id);+ return (+ <SelectItem key={p.id} value={p.id} className="text-[12px]">+ <span className="flex flex-col">+ {p.label}+ {note && <span className="text-[10px] leading-tight text-muted-foreground">{note}</span>}+ </span>+ </SelectItem>+ );+ })}+ </SelectContent>+ </Select>+ </Row>+ <ProxyLine asset={asset} />+ </div>+ );+}++/** Where a ProRes master's preview is coming from: the proxy being made, or+ * the master itself when no proxy could be made here. Silent once the proxy+ * is in place, and for every other kind of file. */+function ProxyLine({ asset }: { asset: MediaAsset }) {+ const job = useProxyJobs((s) => s.jobs[asset.id]);+ if (!job || !needsProxy(asset)) return null;+ const text =+ job.kind === "making"+ ? `Preview proxy: ${Math.round(job.progress * 100)}%`+ : job.kind === "none"+ ? "No preview proxy on this browser. The preview plays the ProRes master."+ : `Preview proxy failed: ${job.error}`;+ return <p className="pb-2 text-[11px] leading-snug text-muted-foreground">{text}</p>;+}++/** The project's delivery space: what every clip converts to, what the+ * export writes, and what the stage shows on an HDR display. */+function ProjectColorRow() {+ const colorSpace = useEditor((s) => s.colorSpace);+ const items = Object.fromEntries(OUTPUT_SPACES.map((o) => [o.id, o.label]));+ return (+ <div className="px-3.5">+ <Row label="Project color">+ <Select+ value={colorSpace}+ items={items}+ onValueChange={(id) => useEditor.getState().setColorSpace(id as OutputSpace)}+ >+ <SelectTrigger className="project-color-space h-8 w-36 text-[12px]">+ <SelectValue />+ </SelectTrigger>+ <SelectContent>+ {OUTPUT_SPACES.map((o) => (+ <SelectItem key={o.id} value={o.id} className="text-[12px]">+ {o.label}+ </SelectItem>+ ))}+ </SelectContent>+ </Select>+ </Row>+ </div>+ );+}++/* ------------------------------------------------------------------ */+/* Footer: save, apply to selected, apply to all */+/* ------------------------------------------------------------------ */++/** Land the clip's whole grade — preset, sliders, LUT and all — on the other+ * selected clips or on every clip, as one undo step; or keep it on the shelf+ * under a name. */+function GradeFooter({ clip }: { clip: VideoClip }) {+ const ck = useSliderCheckpoint();+ const client = useQueryClient();+ const others = useEditor((s) =>+ s.multiSelection.filter((m): m is { kind: "clip"; id: string } => !!m && m.kind === "clip" && m.id !== clip.id)+ .length+ );+ const [naming, setNaming] = useState(false);+ const [name, setName] = useState("");+ const [busy, setBusy] = useState(false);+ const grade = normalizeGrade(clip.grade);+ const apply = (ids: string[]) => {+ if (ids.length === 0) return;+ ck.begin();+ useEditor.getState().updateClipsTransient(ids.map((id) => ({ id, patch: { grade } })));+ ck.end();+ };+ const applySelected = () => {+ const s = useEditor.getState();+ apply(+ s.multiSelection+ .filter((m): m is { kind: "clip"; id: string } => !!m && m.kind === "clip" && m.id !== clip.id)+ .map((m) => m.id)+ );+ };+ const applyAll = () => apply(useEditor.getState().clips.filter((c) => c.id !== clip.id).map((c) => c.id));+ const save = async () => {+ const projectId = useEditor.getState().projectId;+ const trimmed = name.trim();+ if (!projectId || !trimmed || busy || !grade) return;+ setBusy(true);+ try {+ await saveGradePreset(projectId, trimmed, grade);+ await refetchLibrary(client);+ setNaming(false);+ setName("");+ } catch {+ // Signed out or offline shelf — the list just doesn't gain one.+ } finally {+ setBusy(false);+ }+ };+ const link =+ "clip-grade-footer-button whitespace-nowrap text-[11.5px] font-medium text-muted-foreground transition-colors hover:text-foreground disabled:opacity-40 disabled:hover:text-muted-foreground";+ return (+ <div className="flex shrink-0 items-center gap-3 border-t border-border bg-card px-3.5 py-2">+ <button type="button" className={cn("clip-grade-save-preset", link)} disabled={!grade} onClick={() => setNaming(true)}>+ Save Preset+ </button>+ <span className="ml-auto" />+ <button+ type="button"+ className={cn("clip-grade-apply-selected", link)}+ disabled={others === 0}+ onClick={applySelected}+ >+ Apply Selected+ </button>+ <button type="button" className={cn("clip-grade-apply-all", link)} onClick={applyAll}>+ Apply to All+ </button>+ <Dialog open={naming} onOpenChange={(o) => !o && setNaming(false)}>+ <DialogContent className="sm:max-w-sm">+ <DialogHeader>+ <DialogTitle>Save color preset</DialogTitle>+ </DialogHeader>+ <form+ onSubmit={(e) => {+ e.preventDefault();+ void save();+ }}+ >+ <Input autoFocus placeholder="Preset name" value={name} onChange={(e) => setName(e.target.value)} />+ <DialogFooter className="mt-4">+ <Button type="submit" disabled={busy || !name.trim()} className="w-full">+ {busy && <Loader2 className="animate-spin" data-icon="inline-start" />}+ Save preset+ </Button>+ </DialogFooter>+ </form>+ </DialogContent>+ </Dialog>+ </div>+ );+}+/* ------------------------------------------------------------------ *//* Level 1: presets *//* ------------------------------------------------------------------ */+const SAVED = "saved";+type Category = GradePresetCategory | "all" | typeof SAVED;++/** A saved grade in the tile's shape: its id names the shelf copy, so a tile+ * can delete it, and its grade replaces the clip's whole grade when picked. */+type SavedTile = GradePreset & { saved: SavedGrade };+function PresetView({ clip, peers, onAdjust }: { clip: VideoClip; peers?: readonly VideoClip[]; onAdjust: () => void }) {- const [category, setCategory] = usePanelState<GradePresetCategory | "all">(- clip.id,- "colorPresetCategory",- "all"- );+ const [category, setCategory] = usePanelState<Category>(clip.id, "colorPresetCategory", "all");const gridScroll = useRememberedScroll(clip.id, `color-presets:${category}`);// The clip's own frame, ungraded: a swatch shows what its preset does to the// footage, never what the clip's current grade already did.const frame = useClipSourceFrame(clip.id);+ const profile = useEditor((s) => sourceProfileOf(s.assets.find((a) => a.id === clip.assetId)));const { draft, commit } = useGradeWriter(clip, peers);+ const client = useQueryClient();+ const library = useLibrary();+ const saved = useMemo<SavedTile[]>(+ () =>+ (library.data?.templates ?? [])+ .map(savedGradeOf)+ .filter((p): p is SavedGrade => p !== null)+ .map((p) => ({ id: `saved:${p.residency}:${p.id}`, label: p.name, category: "film", grade: p.grade, saved: p })),+ [library.data]+ );+ // The chat reads the same list off editor_state.+ useEffect(() => rememberSavedGrades(saved.map((t) => t.saved)), [saved]);const active = clip.grade?.preset;- const manualDirty = TOOLS.some((t) => gradeToolDirty(clip.grade, t.id));- const presets =+ const manualDirty = TOOLS.some((t) => toolDirty(clip.grade, t.id));+ const presets: (GradePreset | SavedTile)[] =category === "all"? GRADE_PRESET_CATEGORIES.flatMap((c) => gradePresetsInCategory(c.id))- : gradePresetsInCategory(category);+ : category === SAVED+ ? saved+ : gradePresetsInCategory(category);+ const currentKey = gradeKey(clip.grade);- const pick = (id: string) => {+ const pick = (p: GradePreset | SavedTile) => {+ if ("saved" in p) {+ // A saved grade is the whole grade — it replaces what the clip wears,+ // and picking it again takes the clip back to neutral.+ commit(gradeKey(p.grade) === currentKey ? undefined : p.grade);+ return;+ }commit({...clip.grade,- preset:- active?.id === id- ? undefined- : { id, amount: active?.amount ?? 1, skin: active?.skin },+ preset: active?.id === p.id ? undefined : { id: p.id, amount: active?.amount ?? 1, skin: active?.skin },});};+ const remove = (p: SavedTile) => {+ void deleteGradePreset(p.saved).catch(() => {});+ patchLibrary(client, (prev) => ({+ ...prev,+ templates: prev.templates.filter((t) => !(t.id === p.saved.id && t.residency === p.saved.residency)),+ }));+ };const chip = (activeChip: boolean) =>cn(@@ -133,33 +410,38 @@ function PresetView({ clip, peers, onAdjust }: { clip: VideoClip; peers?: readon<div className="shrink-0 bg-card pb-2"><div className="flex h-10 shrink-0 items-center gap-1 px-3.5 text-sm font-semibold tracking-tight">Color- <button- type="button"- title="Adjust"- aria-label="Adjust"- className="clip-color-adjust relative ml-auto grid size-6 place-items-center rounded text-muted-foreground transition-colors hover:text-foreground"- onClick={onAdjust}- >- <SlidersHorizontal className="size-4" />- {manualDirty && (- <span className="absolute top-0.5 right-0.5 size-1.5 rounded-full bg-violet-500" aria-label="Adjusted" />- )}- </button>+ <Tip label="Adjust">+ <button+ type="button"+ aria-label="Adjust"+ className="clip-color-adjust relative ml-auto grid size-6 place-items-center rounded text-muted-foreground transition-colors hover:text-foreground"+ onClick={onAdjust}+ >+ <SlidersHorizontal className="size-4" />+ {manualDirty && (+ <span className="absolute top-0.5 right-0.5 size-1.5 rounded-full bg-violet-500" aria-label="Adjusted" />+ )}+ </button>+ </Tip></div>+ <SourceColorRow clip={clip} />+ <ProjectColorRow /><div className="flex min-w-0 flex-wrap gap-1 px-3.5"><button type="button" className={chip(category === "all")} onClick={() => setCategory("all")}>All</button>{GRADE_PRESET_CATEGORIES.map((c) => (- <button- key={c.id}- type="button"- className={chip(category === c.id)}- onClick={() => setCategory(c.id)}- >+ <button key={c.id} type="button" className={chip(category === c.id)} onClick={() => setCategory(c.id)}>{c.label}</button>))}+ <button+ type="button"+ className={cn("clip-grade-category-saved", chip(category === SAVED))}+ onClick={() => setCategory(SAVED)}+ >+ Saved+ </button></div></div><ScrollArea@@ -177,10 +459,17 @@ function PresetView({ clip, peers, onAdjust }: { clip: VideoClip; peers?: readonkey={`${clip.id}:${p.id}`}preset={p}frame={frame}- selected={active?.id === p.id}- onPick={pick}+ profile={profile}+ selected={"saved" in p ? gradeKey(p.grade) === currentKey : active?.id === p.id}+ onPick={() => pick(p)}+ onRemove={"saved" in p ? () => remove(p) : undefined}/>))}+ {category === SAVED && presets.length === 0 && (+ <p className="col-span-2 py-6 text-center text-[12px] text-muted-foreground">+ Grades you save land here.+ </p>+ )}</ScrollArea><div className="shrink-0 border-t border-border bg-card px-3.5 py-1"><Row label="Intensity">@@ -195,12 +484,8 @@ function PresetView({ clip, peers, onAdjust }: { clip: VideoClip; peers?: readondisabled={!active}format={(v) => `${Math.round(v)}%`}parse={parseNumberInput}- onDraft={(v) =>- active && draft({ ...clip.grade, preset: { ...active, amount: v / 100 } })- }- onCommit={(v) =>- active && commit({ ...clip.grade, preset: { ...active, amount: v / 100 } })- }+ onDraft={(v) => active && draft({ ...clip.grade, preset: { ...active, amount: v / 100 } })}+ onCommit={(v) => active && commit({ ...clip.grade, preset: { ...active, amount: v / 100 } })}/></Row><Row label="Protect skin tones">@@ -209,59 +494,79 @@ function PresetView({ clip, peers, onAdjust }: { clip: VideoClip; peers?: readonclassName="clip-grade-protect-skin"checked={!!active?.skin}disabled={!active}- onCheckedChange={(on: boolean) =>- active && commit({ ...clip.grade, preset: { ...active, skin: on || undefined } })- }+ onCheckedChange={(on: boolean) => active && commit({ ...clip.grade, preset: { ...active, skin: on || undefined } })}/></Row></div>+ <GradeFooter clip={clip} /></div>);}/** Rendered preset thumbnails for the tiles whose recipes go beyond CSS- * filters: the playhead frame pushed through the preset's real LUT at a thumb- * size, cached per (frame, preset). The LUTs themselves are built once per- * preset and kept for the session. */+ * filters, and for footage whose code values need converting first: the+ * playhead frame pushed through the source conversion and the preset's real+ * LUT at a thumb size, cached per (frame, preset). The LUTs themselves are+ * built once per preset and kept for the session; a saved grade naming a+ * shelf LUT gets its table read once and its tile redrawn when it lands. */const presetLutCache = new Map<string, GradeLut | null>();const presetThumbCache = new Map<string, string>();-function presetLut(p: GradePreset): GradeLut | null {- let lut = presetLutCache.get(p.id);+function presetLut(p: GradePreset, userLut: ParsedLut | undefined): GradeLut | null {+ const key = `${p.id}|${userLut ? "lut" : ""}`;+ let lut = presetLutCache.get(key);if (lut === undefined) {- lut = buildGradeLut(p.grade);- presetLutCache.set(p.id, lut);+ lut = buildClipLut({ profile: "rec709", grade: p.grade, output: "sdr", size: 33 }, userLut);+ presetLutCache.set(key, lut);}return lut;}/** A preset's recipe reaches past what a CSS filter can draw. */-const presetNeedsLutThumb = (p: GradePreset) => !!(p.grade.curves || p.grade.wheels || p.grade.hsl);+const presetNeedsLutThumb = (p: GradePreset) => !!(p.grade.curves || p.grade.wheels || p.grade.hsl || p.grade.lut);function PresetTile({preset,frame,+ profile,selected,onPick,+ onRemove,}: {preset: GradePreset;frame: string | null;+ profile: SourceProfile;selected: boolean;- onPick: (id: string) => void;+ onPick: () => void;+ onRemove?: () => void;}) {- const needsLut = presetNeedsLutThumb(preset);+ const converted = profile !== "rec709" && profile !== "srgb";+ const needsLut = presetNeedsLutThumb(preset) || converted;const approx = useMemo(() => gradeCssApprox(preset.grade), [preset]);- const key = needsLut && frame ? `${preset.id}|${frame}` : null;+ const lutId = lutIdOf(preset.grade);+ const userLut = lutId ? cachedLut(lutId) : undefined;+ const key = needsLut && frame ? `${preset.id}|${profile}|${userLut ? "lut" : ""}|${frame}` : null;// The render reads the module cache; the effect fills it asynchronously- // (decode → LUT → data URL) and bumps to re-read.+ // (decode → convert → LUT → data URL) and bumps to re-read.const [, bump] = useState(0);+ useEffect(() => {+ if (!lutId || userLut) return;+ let gone = false;+ loadLibraryLut(lutId).then(+ () => !gone && bump((n) => n + 1),+ () => {}+ );+ return () => {+ gone = true;+ };+ }, [lutId, userLut]);useEffect(() => {if (!key || !frame || presetThumbCache.has(key)) return;let gone = false;const img = new Image();img.onload = () => {if (gone) return;- const lut = presetLut(preset);+ const lut = presetLut(preset, userLut);const w = 128;const h = Math.max(1, Math.round((img.naturalHeight / (img.naturalWidth || 1)) * w));const c = document.createElement("canvas");@@ -270,9 +575,10 @@ function PresetTile({const ctx = c.getContext("2d", { willReadFrequently: true });if (!ctx) return;ctx.drawImage(img, 0, 0, w, h);- if (lut) {+ if (lut || converted) {const px = ctx.getImageData(0, 0, w, h);- applyLutToImageData(px.data, lut);+ if (converted) toBaseRendering(px.data, profile);+ if (lut) applyLutToImageData(px.data, lut);ctx.putImageData(px, 0, 0);}const url = c.toDataURL("image/jpeg", 0.72);@@ -280,8 +586,7 @@ function PresetTile({// The frame refreshes as the playhead moves; drop the thumbs of frames// that have gone by, never the ones the mounted tiles are showing.if (presetThumbCache.size > 128)- for (const k of presetThumbCache.keys())- if (!k.endsWith(`|${frame}`)) presetThumbCache.delete(k);+ for (const k of presetThumbCache.keys()) if (!k.endsWith(`|${frame}`)) presetThumbCache.delete(k);// Decoded before the swap, so the tile flips straight from the old// thumb to a ready bitmap.const pre = new Image();@@ -295,7 +600,7 @@ function PresetTile({return () => {gone = true;};- }, [key, frame, preset]);+ }, [key, frame, preset, userLut, converted, profile]);const fresh = needsLut ? (key ? presetThumbCache.get(key) ?? null : null) : frame;// The last thumb this tile showed holds while the fresh frame's is still@@ -304,44 +609,50 @@ function PresetTile({if (fresh && fresh !== held) setHeld(fresh);const src = fresh ?? held;return (- <button- type="button"- aria-pressed={selected}- className={cn(- `clip-grade-preset-${preset.id} group flex flex-col items-center gap-1 rounded-lg p-1 text-[11px] font-medium outline-none transition-colors`,- selected ? "text-foreground" : "text-muted-foreground hover:text-foreground"- )}- onClick={() => onPick(preset.id)}- >- <span+ <div className="group relative">+ <button+ type="button"+ aria-pressed={selected}className={cn(- "relative block aspect-square w-full overflow-hidden rounded-md bg-muted",- selected && PICKED_RING+ `clip-grade-preset-${preset.id} flex w-full flex-col items-center gap-1 rounded-lg p-1 text-[11px] font-medium outline-none transition-colors`,+ selected ? "text-foreground" : "text-muted-foreground hover:text-foreground")}+ onClick={onPick}>- {src ? (- <>- {/* eslint-disable-next-line @next/next/no-img-element */}- <img- src={src}- alt=""- draggable={false}- className="absolute inset-0 h-full w-full object-cover"- style={needsLut ? undefined : { filter: approx.filter || undefined }}- />- {!needsLut && approx.tint && (- <span- className="absolute inset-0"- style={{ backgroundColor: approx.tint, mixBlendMode: "multiply" }}+ <span className={cn("relative block aspect-square w-full overflow-hidden rounded-md bg-muted", selected && PICKED_RING)}>+ {src ? (+ <>+ {/* eslint-disable-next-line @next/next/no-img-element */}+ <img+ src={src}+ alt=""+ draggable={false}+ className="absolute inset-0 h-full w-full object-cover"+ style={needsLut ? undefined : { filter: approx.filter || undefined }}/>- )}- </>- ) : (- <StandInScene filter={approx.filter} tint={approx.tint} />- )}- </span>- {preset.label}- </button>+ {!needsLut && approx.tint && (+ <span className="absolute inset-0" style={{ backgroundColor: approx.tint, mixBlendMode: "multiply" }} />+ )}+ </>+ ) : (+ <StandInScene filter={approx.filter} tint={approx.tint} />+ )}+ </span>+ <span className="max-w-full truncate">{preset.label}</span>+ </button>+ {onRemove && (+ <Tip label="Delete preset">+ <button+ type="button"+ aria-label={`Delete ${preset.label}`}+ className="absolute top-2 right-2 grid size-6 place-items-center rounded-full bg-black/55 text-white opacity-0 transition-opacity group-hover:opacity-100 hover:bg-black/75"+ onClick={onRemove}+ >+ <Trash2 className="size-3" />+ </button>+ </Tip>+ )}+ </div>);}@@ -369,13 +680,14 @@ function AdjustView({ clip, peers, onBack }: { clip: VideoClip; peers?: readonlyconst { draft, commit } = useGradeWriter(clip, peers);const grade = clip.grade;// Manual adjustments only — reset-all keeps the preset layer.- const manualDirty = TOOLS.some((t) => gradeToolDirty(grade, t.id));- // Fit a starting grade from the clip's raw decoder frame (never the graded- // preview, which would fold the current grade back into the fit); the- // sliders show the result and stay fully adjustable after.+ const manualDirty = TOOLS.some((t) => toolDirty(grade, t.id));+ // Fit a starting grade from the clip's base rendering (the decoder frame+ // through the source conversion alone, never the graded preview, which+ // would fold the current grade back into the fit); the sliders show the+ // result and stay fully adjustable after.const autoGrade = () => {- const data = sampleClipFrameData(clip.id);- if (data) commit({ ...autoGradeFromImageData(data), preset: grade?.preset });+ const data = sampleClipBaseFrameData(clip.id);+ if (data) commit({ ...autoGradeFromImageData(data), preset: grade?.preset, lut: grade?.lut });};const resetAll = () => commit(grade?.preset ? { preset: grade.preset } : undefined);return (@@ -399,18 +711,19 @@ function AdjustView({ clip, peers, onBack }: { clip: VideoClip; peers?: readonly<Wand2 className="size-3" />Auto</button>- <button- type="button"- title="Reset all adjustments"- aria-label="Reset all adjustments"- className={cn(- "clip-grade-reset grid size-6 place-items-center rounded text-muted-foreground transition-colors hover:text-foreground",- !manualDirty && "invisible"- )}- onClick={resetAll}- >- <RotateCcw className="size-3.5" />- </button>+ <Tip label="Reset all adjustments">+ <button+ type="button"+ aria-label="Reset all adjustments"+ className={cn(+ "clip-grade-reset grid size-6 place-items-center rounded text-muted-foreground transition-colors hover:text-foreground",+ !manualDirty && "invisible"+ )}+ onClick={resetAll}+ >+ <RotateCcw className="size-3.5" />+ </button>+ </Tip></div><div className="mx-3.5 flex shrink-0 rounded-lg bg-muted p-0.5 text-[11.5px] font-medium">{TOOLS.map((t) => (@@ -418,18 +731,15 @@ function AdjustView({ clip, peers, onBack }: { clip: VideoClip; peers?: readonlykey={t.id}type="button"className={cn(- `clip-grade-tab-${t.id} relative flex-1 rounded-md px-1.5 py-1 transition-colors`,+ `clip-grade-tab-${t.id} relative flex-1 rounded-md px-1 py-1 transition-colors`,tool === t.id ? "bg-neutral-900 text-white" : "text-muted-foreground hover:text-foreground")}onClick={() => setTool(t.id)}>{t.label}- {gradeToolDirty(grade, t.id) && (+ {toolDirty(grade, t.id) && (<span- className={cn(- "absolute top-1 right-1.5 size-1 rounded-full",- tool === t.id ? "bg-white/80" : "bg-violet-500"- )}+ className={cn("absolute top-1 right-1 size-1 rounded-full", tool === t.id ? "bg-white/80" : "bg-violet-500")}aria-label={`${t.label} adjusted`}/>)}@@ -455,7 +765,9 @@ function AdjustView({ clip, peers, onBack }: { clip: VideoClip; peers?: readonly)}{tool === "wheels" && <WheelsTool grade={grade} draft={draft} commit={commit} />}{tool === "hsl" && <HslTool clipId={clip.id} grade={grade} draft={draft} commit={commit} />}+ {tool === "lut" && <LutTool grade={grade} draft={draft} commit={commit} />}</ScrollArea>+ <GradeFooter clip={clip} /></div>);}@@ -471,15 +783,17 @@ const formatSigned = (v: number) => (v > 0 ? `+${Math.round(v)}` : `${Math.roundfunction BasicTool({ grade, draft, commit }: GradeWrite) {// Legacy fields keep rendering and stay editable on clips that carry them;// fresh grades never surface the rows.- const legacy: { key: "brightness" | "hue"; label: string; max: number }[] = [];- if (grade?.brightness) legacy.push({ key: "brightness", label: "Brightness", max: GRADE_MAX });- if (grade?.hue) legacy.push({ key: "hue", label: "Hue", max: GRADE_HUE_MAX });+ const legacy: { key: "brightness" | "hue"; label: string; min: number; max: number }[] = [];+ if (grade?.brightness) legacy.push({ key: "brightness", label: "Brightness", min: -GRADE_MAX, max: GRADE_MAX });+ if (grade?.hue) legacy.push({ key: "hue", label: "Hue", min: -GRADE_HUE_MAX, max: GRADE_HUE_MAX });const groups = [{ id: "light" as const, label: "Light" },{ id: "color" as const, label: "Color" },];- const sliderRow = (key: keyof ColorGrade & string, label: string, max: number) => {+ const sliderRow = (key: keyof ColorGrade & string, label: string, min: number, max: number) => {const value = (grade?.[key] as number | undefined) ?? 0;+ // A one-sided slider reads as a plain amount; a centred one carries its sign.+ const format = (v: number) => (key === "hue" ? `${Math.round(v)}°` : min < 0 ? formatSigned(v) : `${Math.round(v)}`);return (<Row key={key} label={label}><ValueSlider@@ -487,20 +801,16 @@ function BasicTool({ grade, draft, commit }: GradeWrite) {sliderClassName={`clip-grade-${key} data-horizontal:w-24`}valueClassName="w-9 text-muted-foreground"value={value}- min={-max}+ min={min}max={max}step={1}- snap={[0]}- format={(v) => (key === "hue" ? `${Math.round(v)}°` : formatSigned(v))}+ snap={min < 0 ? [0] : undefined}+ format={format}parse={parseNumberInput}onDraft={(v) => draft({ ...grade, [key]: v })}onCommit={(v) => commit({ ...grade, [key]: v })}/>- <ResetButton- title={`Reset ${label.toLowerCase()}`}- show={value !== 0}- onClick={() => commit({ ...grade, [key]: 0 })}- />+ <ResetButton title={`Reset ${label.toLowerCase()}`} show={value !== 0} onClick={() => commit({ ...grade, [key]: 0 })} /></Row>);};@@ -509,47 +819,40 @@ function BasicTool({ grade, draft, commit }: GradeWrite) {{groups.map((g) => (<div key={g.id} className="flex flex-col gap-1"><span className="mt-1 text-xs font-semibold text-muted-foreground">{g.label}</span>- {GRADE_BASIC_FIELDS.filter((f) => f.group === g.id).map((f) =>- sliderRow(f.key, f.label, GRADE_MAX)- )}+ {GRADE_BASIC_FIELDS.filter((f) => f.group === g.id).map((f) => sliderRow(f.key, f.label, f.min, GRADE_MAX))}</div>))}+ <div className="flex flex-col gap-1">+ <span className="mt-1 text-xs font-semibold text-muted-foreground">Detail</span>+ {GRADE_DETAIL_FIELDS.map((f) => sliderRow(f.key, f.label, f.min, GRADE_MAX))}+ </div>{legacy.length > 0 && (<div className="flex flex-col gap-1"><span className="mt-1 text-xs font-semibold text-muted-foreground">Legacy</span>- {legacy.map((f) => sliderRow(f.key, f.label, f.max))}+ {legacy.map((f) => sliderRow(f.key, f.label, f.min, f.max))}</div>)}</>);}-const WHEEL_ZONES = [- { id: "s" as const, label: "Shadows" },- { id: "m" as const, label: "Midtones" },- { id: "h" as const, label: "Highlights" },-];-function WheelsTool({ grade, draft, commit }: GradeWrite) {const wheels = grade?.wheels;- const tuple = (z: "s" | "m" | "h"): WheelTuple => wheels?.[z] ?? [0, 0, 0];- const write = (- to: (g: ColorGrade) => void,- z: "s" | "m" | "h",- next: WheelTuple- ) => to({ ...grade, wheels: { ...wheels, [z]: next } });+ const tuple = (z: WheelZone): WheelTuple => wheels?.[z] ?? [0, 0, 0];+ const write = (to: (g: ColorGrade) => void, z: WheelZone, next: WheelTuple) =>+ to({ ...grade, wheels: { ...wheels, [z]: next } });return (<>- <div className="mt-1 grid grid-cols-3 gap-2">+ <div className="mt-1 grid grid-cols-2 gap-2">{WHEEL_ZONES.map((z) => {- const [dx, dy, lum] = tuple(z.id);+ const [dx, dy, lum] = tuple(z);return (- <div key={z.id} className={`clip-grade-wheel-${z.id}`}>+ <div key={z} className={`clip-grade-wheel-${z}`}><ColorWheel- label={z.label}+ label={WHEEL_LABELS[z]}value={[dx, dy]}- onDraft={([nx, ny]) => write(draft, z.id, [nx, ny, lum])}- onCommit={([nx, ny]) => write(commit, z.id, [nx, ny, lum])}+ onDraft={([nx, ny]) => write(draft, z, [nx, ny, lum])}+ onCommit={([nx, ny]) => write(commit, z, [nx, ny, lum])}/></div>);@@ -557,12 +860,13 @@ function WheelsTool({ grade, draft, commit }: GradeWrite) {</div><span className="mt-2 text-xs font-semibold text-muted-foreground">Luminance</span>{WHEEL_ZONES.map((z) => {- const [dx, dy, lum] = tuple(z.id);+ const [dx, dy, lum] = tuple(z);+ const label = WHEEL_LABELS[z];return (- <Row key={z.id} label={z.label}>+ <Row key={z} label={label}><ValueSlider- label={`${z.label} luminance`}- sliderClassName={`clip-grade-wheel-${z.id}-luma data-horizontal:w-24`}+ label={`${label} luminance`}+ sliderClassName={`clip-grade-wheel-${z}-luma data-horizontal:w-24`}valueClassName="w-9 text-muted-foreground"value={lum}min={-GRADE_MAX}@@ -571,13 +875,13 @@ function WheelsTool({ grade, draft, commit }: GradeWrite) {snap={[0]}format={formatSigned}parse={parseNumberInput}- onDraft={(v) => write(draft, z.id, [dx, dy, v])}- onCommit={(v) => write(commit, z.id, [dx, dy, v])}+ onDraft={(v) => write(draft, z, [dx, dy, v])}+ onCommit={(v) => write(commit, z, [dx, dy, v])}/><ResetButton- title={`Reset ${z.label.toLowerCase()} wheel`}+ title={`Reset ${label.toLowerCase()} wheel`}show={dx !== 0 || dy !== 0 || lum !== 0}- onClick={() => write(commit, z.id, [0, 0, 0])}+ onClick={() => write(commit, z, [0, 0, 0])}/></Row>);@@ -596,29 +900,26 @@ function HslTool({ clipId, grade, draft, commit }: GradeWrite & { clipId: stringconst [band, setBand] = usePanelState<HslBand>(clipId, "hslBand", "orange");const active = HSL_BANDS.find((b) => b.id === band)!;const tuple: HslTuple = grade?.hsl?.[band] ?? [0, 0, 0];- const write = (to: (g: ColorGrade) => void, next: HslTuple) =>- to({ ...grade, hsl: { ...grade?.hsl, [band]: next } });+ const write = (to: (g: ColorGrade) => void, next: HslTuple) => to({ ...grade, hsl: { ...grade?.hsl, [band]: next } });return (<><div className="mt-1 flex flex-wrap gap-1.5">{HSL_BANDS.map((b) => (- <button- key={b.id}- type="button"- title={b.label}- aria-label={b.label}- aria-pressed={band === b.id}- className={cn(- `clip-grade-hsl-${b.id} relative size-7 rounded-full border-2 transition-transform`,- band === b.id ? "border-[#0a84ff]" : "border-transparent hover:scale-105"- )}- style={{ backgroundColor: b.swatch }}- onClick={() => setBand(b.id)}- >- {!!grade?.hsl?.[b.id] && (- <span className="absolute -top-0.5 -right-0.5 size-1.5 rounded-full bg-violet-500" />- )}- </button>+ <Tip key={b.id} label={b.label}>+ <button+ type="button"+ aria-label={b.label}+ aria-pressed={band === b.id}+ className={cn(+ `clip-grade-hsl-${b.id} relative size-7 rounded-full border-2 transition-transform`,+ band === b.id ? "border-[#0a84ff]" : "border-transparent hover:scale-105"+ )}+ style={{ backgroundColor: b.swatch }}+ onClick={() => setBand(b.id)}+ >+ {!!grade?.hsl?.[b.id] && <span className="absolute -top-0.5 -right-0.5 size-1.5 rounded-full bg-violet-500" />}+ </button>+ </Tip>))}</div><div className="mt-1 text-[12px] text-muted-foreground">@@ -663,6 +964,92 @@ function HslTool({ clipId, grade, draft, commit }: GradeWrite & { clipId: string);}+/* ------------------------------------------------------------------ */+/* LUT */+/* ------------------------------------------------------------------ */++/** The label of a LUT file in the Library, re-read as the Library changes. */+function useLutLabel(id: string | null): string | undefined {+ const [, bump] = useState(0);+ useEffect(() => onLinkedChanged(() => bump((n) => n + 1)), []);+ return id ? listLibraryLuts().find((l) => libraryLutId(l.key) === id)?.label : undefined;+}++/** The LUT tool: the applied table as a chip with its intensity. A LUT file+ * dragged from the Library onto this tool or onto a clip applies it. A LUT+ * sits under the grade — the picture after the source conversion goes+ * through it, and the sliders work on what comes out. */+function LutTool({ grade, draft, commit }: GradeWrite) {+ const [over, setOver] = useState(false);+ const applied = lutIdOf(grade);+ const label = useLutLabel(applied);+ const amount = Math.round((grade?.lut?.amount ?? 1) * 100);+ const remove = () => {+ const next = { ...grade };+ delete next.lut;+ commit(next);+ };+ return (+ <div+ className={cn("clip-grade-lut-drop -mx-1 rounded-md px-1 pb-1", over && "bg-[#0a84ff]/10 shadow-[inset_0_0_0_1.5px_rgba(10,132,255,0.4)]")}+ onDragOver={(e) => {+ if (!draggedLutKey(e)) return;+ e.preventDefault();+ e.dataTransfer.dropEffect = "copy";+ setOver(true);+ }}+ onDragLeave={(e) => {+ if (!e.currentTarget.contains(e.relatedTarget as Node | null)) setOver(false);+ }}+ onDrop={(e) => {+ const key = draggedLutKey(e);+ setOver(false);+ if (!key) return;+ e.preventDefault();+ commit({ ...grade, lut: { id: libraryLutId(key), amount: grade?.lut?.amount } });+ }}+ >+ {applied ? (+ <div className="clip-grade-lut-chip mt-1 flex items-center gap-2 rounded-md bg-muted px-2 py-1.5 text-[12px]">+ {/* eslint-disable-next-line @next/next/no-img-element */}+ <img src={LUT_MARK_ICON} alt="" aria-hidden className="size-5 shrink-0" />+ <span className="min-w-0 flex-1 truncate font-medium">{label ?? "LUT not in the library"}</span>+ <Tip label="Remove LUT">+ <button+ type="button"+ aria-label="Remove LUT"+ className="clip-grade-lut-remove grid size-5 shrink-0 place-items-center rounded text-muted-foreground transition-colors hover:text-foreground"+ onClick={remove}+ >+ <X className="size-3.5" />+ </button>+ </Tip>+ </div>+ ) : (+ <p className="clip-grade-lut-empty mt-1 rounded-md border border-dashed border-input py-3 text-center text-[12px] text-muted-foreground">+ Drag a LUT from the Library+ </p>+ )}+ <Row label="Intensity">+ <ValueSlider+ label="LUT intensity"+ sliderClassName="clip-grade-lut-amount data-horizontal:w-24"+ valueClassName="w-9 text-muted-foreground"+ value={amount}+ min={0}+ max={100}+ step={1}+ disabled={!applied}+ format={(v) => `${Math.round(v)}%`}+ parse={parseNumberInput}+ onDraft={(v) => applied && draft({ ...grade, lut: { id: applied, amount: v / 100 } })}+ onCommit={(v) => applied && commit({ ...grade, lut: { id: applied, amount: v / 100 } })}+ />+ </Row>+ </div>+ );+}+/** Live RGB histogram of the composited preview frame: the three channel* curves screen over each other so overlaps read light. Samples a small* downscale of the preview canvas on a short interval while open. */diff --git a/site/src/cut/components/Editor.tsx b/site/src/cut/components/Editor.tsxindex e499568e..db2968b2 100644--- a/site/src/cut/components/Editor.tsx+++ b/site/src/cut/components/Editor.tsx@@ -30,8 +30,8 @@ import { copyTimelineSelection, pasteCutPayload, payloadFromHtml } from "@/cut/limport { useLibrary } from "@/cut/lib/queries";import { copyableRefs } from "@/cut/lib/refCopy";import { startUpload } from "@/cut/lib/importQueue";-import { enrichAsset, importFileToProject, isFontFile, isMediaFile, prepareImport } from "@/cut/lib/media";-import { uploadLibraryFont } from "@/cut/lib/linkedLibrary";+import { enrichAsset, importFileToProject, isMediaFile, prepareImport } from "@/cut/lib/media";+import { isLinkedFile, uploadLinkedFile } from "@/cut/lib/linkedLibrary";import { copiedFrameFile, hasCopiedFrame } from "@/cut/lib/stageFrame";// Side-effect import: registers the brief-to-video resume subscription, so a// persisted run resumes on project load even when the AI panel never mounts.@@ -67,7 +67,7 @@ import {shortcutDecline,shortcutReached,} from "@/cut/lib/shortcutGate";-import { docAudioClips, docClips, docOverlays, projectDuration, serializeDoc, storedAssets, timelineHMax, useEditor, clipLen, type VideoTrackPlacement } from "@/cut/lib/store";+import { docFieldsEdited, projectDuration, serializeDoc, storedAssets, timelineHMax, useEditor, clipLen, type VideoTrackPlacement } from "@/cut/lib/store";import { fileLandingAt } from "@/cut/lib/timelineDrop";import { landOnRow } from "@/cut/lib/laneTracks";import { playheadAt, previewAt, skimAt } from "@/cut/lib/playhead";@@ -520,7 +520,6 @@ export function Editor({};let timer: ReturnType<typeof setTimeout> | null = null;let last = serializeDoc(useEditor.getState());- let lastName = useEditor.getState().projectName;// serializeDoc copies the bars, so the store's array is the baseline: a// parked bar changes no clip field, and comparing the copies would never// see it.@@ -622,7 +621,6 @@ export function Editor({// arriving at one never counts as an edit.primedEpoch = s.loadEpoch;last = serializeDoc(s);- lastName = s.projectName;lastBars = s.transitions;assetsChanged(s.assets);return;@@ -639,36 +637,9 @@ export function Editor({// Evaluated every tick (not short-circuited) so the asset baseline// advances even when another slice triggered this save.const assetsDirty = assetsChanged(s.assets);- const changed =- assetsDirty ||- // The projections, not the raw arrays: clips waiting on an upload are- // held out of the document, and holding one is not an edit.- docClips(s.clips, s.assets) !== (last.clips as unknown) ||- docAudioClips(s.audioClips, s.assets) !== (last.audioClips as unknown) ||- docOverlays(s.overlays) !== (last.overlays as unknown) ||- s.transitions !== lastBars ||- s.templates !== (last.templates as unknown) ||- s.mediaFolders !== (last.mediaFolders as unknown) ||- s.subtitles !== (last.subtitles as unknown) ||- s.aspect !== last.aspect ||- s.guides !== last.guides ||- s.guideLines !== last.guideLines ||- s.background !== last.background ||- s.publish.caption !== last.publish?.caption ||- s.publish.tags !== last.publish?.tags ||- s.publish.soundTitle !== last.publish?.soundTitle ||- s.publish.handle !== last.publish?.handle ||- s.notes.text !== last.notes?.text ||- s.notes.publishedAt !== last.notes?.publishedAt ||- s.notes.links.join("") !== (last.notes?.links ?? []).join("") ||- // Normalized like serializeDoc stores it (?? null): a project with no- // run holds undefined in state and null in the doc — not a change.- (s.genvideo ?? null) !== ((last.genvideo ?? null) as unknown) ||- s.renders !== (last.renders as unknown) ||- s.projectName !== lastName;+ const changed = assetsDirty || docFieldsEdited(s, last, lastBars);if (!changed) return;last = serializeDoc(s);- lastName = s.projectName;lastBars = s.transitions;editSeq++;// Every edit lands on disk marked dirty before it lands on the server,@@ -770,7 +741,18 @@ export function Editor({onOutcome?: (result: { file: File; assetId: string } | { file: File; failed: true }) => void;}) => {- const list = Array.from(files);+ // A font or a LUT dropped on the editor goes on the Library shelf, the+ // way a paste of one does: it has no place on the timeline.+ const linked = Array.from(files).filter(isLinkedFile);+ for (const file of linked) {+ void uploadLinkedFile(file)+ .then(() => opts?.onOutcome?.({ file, assetId: "" }))+ .catch((err) => {+ reportSwallowed(`[cut] shelving failed for ${file.name}`, err);+ opts?.onOutcome?.({ file, failed: true });+ });+ }+ const list = Array.from(files).filter((f) => !isLinkedFile(f));// A run of files lands in order, each after the last; a new track is// opened by the first and the rest join it.let at = opts?.at;@@ -1018,20 +1000,21 @@ export function Editor({if (isPasteTarget(e.target)) return;const at = Math.max(0, previewAt());const pasted = Array.from(e.clipboardData?.files ?? []);- // A font is not media for the timeline: it goes on the shelf and lights- // up in the font menu, the way the Library panel takes a dropped one.- const fonts = pasted.filter(isFontFile);- if (fonts.length > 0) {+ // A font or a LUT is no media for the timeline: it goes on the shelf+ // and lights up in its menu, the way the Library panel takes a dropped+ // one.+ const linked = pasted.filter(isLinkedFile);+ if (linked.length > 0) {e.preventDefault();- for (const font of fonts) {- void uploadLibraryFont(font).catch((err) =>- reportSwallowed(`[cut] paste failed for ${font.name}`, err)+ for (const file of linked) {+ void uploadLinkedFile(file).catch((err) =>+ reportSwallowed(`[cut] paste failed for ${file.name}`, err));}}- const files = pasted.filter((f) => isMediaFile(f) && !isFontFile(f));+ const files = pasted.filter((f) => isMediaFile(f) && !isLinkedFile(f));if (files.length === 0) {- if (fonts.length > 0) return;+ if (linked.length > 0) return;// A copy made in Cut — this tab, another tab, another project — rides// the HTML flavor whole. It is the newest copy whichever tab made it,// so it goes ahead of this tab's own timeline clipboard; a card copy@@ -1051,7 +1034,7 @@ export function Editor({}// A ⌘C on a tile — a media card, a library card, a stock sound, a// sticker, an effect, a shape, a transition, a template — put its- // mention token here; each one lands the way the tile's + button+ // mention token here; each one lands the way the tile's add action// lands it. Imports run behind the editor; a run lands in copy order.const library = libraryRef.current;const candidates = refCandidatesOf(s, library);diff --git a/site/src/cut/components/ExportDialog.tsx b/site/src/cut/components/ExportDialog.tsxindex 7cf5d427..a719a575 100644--- a/site/src/cut/components/ExportDialog.tsx+++ b/site/src/cut/components/ExportDialog.tsx@@ -14,6 +14,7 @@ import {} from "@/components/ui/dialog";import { Input } from "@/components/ui/input";import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select";+import { OUTPUT_SPACES, type OutputSpace } from "@donkeycut/effects-kit";import { Slider } from "@/components/ui/slider";import { Switch } from "@/components/ui/switch";import {@@ -76,6 +77,12 @@ export function ExportDialog() {const subtitles = useEditor((s) => s.subtitles);const multiSelection = useEditor((s) => s.multiSelection);const projectName = useEditor((s) => s.projectName);+ // The delivery's color space is the project's own setting: it decides what+ // every clip converts to, so it lives on the document rather than in this+ // dialog's choice.+ const colorSpace = useEditor((s) => s.colorSpace);+ const setColorSpace = useEditor((s) => s.setColorSpace);+ const hdr = colorSpace !== "sdr";const duration = useMemo(() => projectDuration({ clips, audioClips, overlays }),[clips, audioClips, overlays]@@ -132,13 +139,19 @@ export function ExportDialog() {const baseName = exportBaseName(name || projectName);const typedName = baseName !== exportBaseName(projectName);const settings = useMemo<ExportSettings>(- () => ({- ...choiceSettings(choice, resolutions, sourceFps ?? DEFAULT_EXPORT_FPS,- !probing && probe ? { ...probe, ...(audioClips.length > 0 ? { audioBitrate: undefined, audioSampleRate: undefined, audioChannels: undefined } : {}) } : undefined),- ...(typedName ? { name: baseName } : {}),- ...(range ? { range } : {}),- }),- [choice, resolutions, sourceFps, probe, probing, audioClips.length, typedName, baseName, range]+ () => {+ const chosen = choiceSettings(choice, resolutions, sourceFps ?? DEFAULT_EXPORT_FPS,+ !probing && probe ? { ...probe, ...(audioClips.length > 0 ? { audioBitrate: undefined, audioSampleRate: undefined, audioChannels: undefined } : {}) } : undefined);+ return {+ ...chosen,+ // H.264 is 8-bit: an HDR delivery takes HEVC in its place, whatever+ // the preset or the probe asked for.+ ...(hdr && chosen.codec === "h264" ? { codec: "hevc" as const, copySource: false } : {}),+ ...(typedName ? { name: baseName } : {}),+ ...(range ? { range } : {}),+ };+ },+ [choice, resolutions, sourceFps, probe, probing, audioClips.length, typedName, baseName, range, hdr]);const set = (patch: Partial<ExportChoice>) => setChoice((c) => ({ ...c, ...patch }));const captionFiles = useMemo(@@ -167,8 +180,10 @@ export function ExportDialog() {overlays: s.overlays,subtitles: s.subtitles,background: s.background,+ colorSpace: s.colorSpace,},- settings+ settings,+ s.colorSpace ?? "sdr").then((ok) => {if (alive) setBrowserFits(ok);});@@ -190,6 +205,7 @@ export function ExportDialog() {overlays: s.overlays,subtitles: s.subtitles,background: s.background,+ colorSpace: s.colorSpace,},settings,baseName@@ -338,8 +354,23 @@ export function ExportDialog() {</SelectTrigger><SelectContent align="end">{FORMATS.map((f) => (- <SelectItem key={f.id} value={f.id} title={f.detail}>+ <SelectItem key={f.id} value={f.id} title={f.detail} disabled={hdr && f.codec === "h264"}>{f.label}+ {hdr && f.codec === "h264" ? " · 8-bit" : ""}+ </SelectItem>+ ))}+ </SelectContent>+ </Select>+ </Field>+ <Field label="Color">+ <Select value={colorSpace} onValueChange={(v) => setColorSpace(v as OutputSpace)}>+ <SelectTrigger className="w-fit min-w-32" aria-label="Color">+ <SelectValue />+ </SelectTrigger>+ <SelectContent align="end">+ {OUTPUT_SPACES.map((o) => (+ <SelectItem key={o.id} value={o.id}>+ {o.label}</SelectItem>))}</SelectContent>@@ -422,7 +453,7 @@ export function ExportDialog() {{!inTab && (<p className="text-xs leading-relaxed text-muted-foreground">- This browser can't encode {prores ? "ProRes" : "this"} itself, so it renders in the+ This browser can't encode {prores ? "ProRes" : hdr ? "HDR" : "this"} itself, so it renders in thecloud and lands here when done.</p>)}@@ -433,6 +464,7 @@ export function ExportDialog() {<span className="truncate">{settings.width} × {settings.height} · {settings.fps} fps ·{" "}{FORMATS.find((f) => f.id === formatId)?.label ?? formatId} · {settings.audioCodec.toUpperCase()}+ {hdr ? ` · ${OUTPUT_SPACES.find((o) => o.id === colorSpace)?.label}` : ""}{range ? ` · ${formatTime(span)}` : ""}</span><span className="shrink-0 tabular-nums">{sizeEstimate}</span>diff --git a/site/src/cut/components/FontPicker.tsx b/site/src/cut/components/FontPicker.tsxindex d6df7103..29503bcd 100644--- a/site/src/cut/components/FontPicker.tsx+++ b/site/src/cut/components/FontPicker.tsx@@ -40,7 +40,7 @@ const PANEL_INSET = 24;/** Picking this row opens the file dialog; it never becomes the value. */const UPLOAD = "__upload";-const ACCEPT = linkedAccept();+const ACCEPT = linkedAccept("font");/** The row's text size, and the cap height it is drawn to. */const ROW_PX = 14;diff --git a/site/src/cut/components/GroupPanel.tsx b/site/src/cut/components/GroupPanel.tsxindex de77a745..ab5122e1 100644--- a/site/src/cut/components/GroupPanel.tsx+++ b/site/src/cut/components/GroupPanel.tsx@@ -342,7 +342,7 @@ function TransformRows({ items }: { items: { overlays: Overlay[]; clips: VideoCl}/** A title's whole look over a selection of titles: saved styles, face,- * weight and slant, alignment, size, spacing, stretch, color, outline,+ * weight and slant, alignment, size, spacing, text box width, color, outline,* shadow and backdrop. */function TextRows({ texts }: { texts: TextOverlay[] }) {const write = useGroupWrite();diff --git a/site/src/cut/components/Inspector.tools.ts b/site/src/cut/components/Inspector.tools.tsindex 1c0c3bd2..28adff56 100644--- a/site/src/cut/components/Inspector.tools.ts+++ b/site/src/cut/components/Inspector.tools.ts@@ -8,11 +8,15 @@import {GRADE_BASIC_FIELDS,+ GRADE_DETAIL_FIELDS,GRADE_HUE_MAX,GRADE_MAX,GRADE_PRESET_IDS,gradePresetCatalogText,HSL_BANDS,+ SOURCE_PROFILES,+ WHEEL_LABELS,+ WHEEL_ZONES,SOUND_COMPRESSOR_RANGE,SOUND_EQ_BANDS,SOUND_EQ_DB_RANGE,@@ -32,25 +36,45 @@ import { bool, ids, num, obj, str, type AiToolDef } from "@/cut/lib/aiToolDef";/** Per-field slider hints; ranges interpolate the exported constants so the* schema can never drift from the model the renderer clamps to. */const GRADE_FIELD_HINTS: Record<string, string> = {- exposure: "(±1 stop)",- contrast: "",+ exposure: "(±2 stops, in linear light)",+ contrast: "around 18% grey",highlights: "trim (-) or boost (+) the brights",shadows: "lift (+) or crush (-) the darks",- temperature: "positive = warmer",+ whites: "the white point: pull (-) or push (+) the very brightest values",+ blacks: "the black point: lift (+) or deepen (-) the very darkest values",+ brilliance: "brings up the darks and tames the brights together, like a photo app's brilliance",+ fade: "lifts the blacks toward grey for a faded-film look",+ temperature: "positive = warmer (mireds, CAT02 white balance)",tint: "negative = green, positive = magenta",saturation: `(-${GRADE_MAX} = grayscale)`,vibrance: "saturation weighted toward the muted colors",+ sharpen: "sharpens fine edges (luma only)",+ clarity: "local contrast across larger structures (luma only)",};+/** A slider's range text: centred sliders run ±GRADE_MAX, one-sided ones 0..GRADE_MAX. */+const gradeRange = (min: number) => `${min < 0 ? `-${GRADE_MAX}` : "0"}..${GRADE_MAX}, 0 neutral`;+const gradeFieldProps = Object.fromEntries(- GRADE_BASIC_FIELDS.map((f) => [+ [...GRADE_BASIC_FIELDS, ...GRADE_DETAIL_FIELDS].map((f) => [f.key,- num(- `-${GRADE_MAX}..${GRADE_MAX}, 0 neutral${GRADE_FIELD_HINTS[f.key] ? ` — ${GRADE_FIELD_HINTS[f.key]}` : ""}`- ),+ num(`${gradeRange(f.min)}${GRADE_FIELD_HINTS[f.key] ? ` — ${GRADE_FIELD_HINTS[f.key]}` : ""}`),]));+/** The tool argument for each wheel, keyed by the wheel's label in lower case+ * (lift, gamma, gain, offset). */+const WHEEL_ARGS: Record<string, (typeof WHEEL_ZONES)[number]> = Object.fromEntries(+ WHEEL_ZONES.map((z) => [WHEEL_LABELS[z].toLowerCase(), z])+);++/** Several clips at once, the same way `ids` fans a sweep out, plus every+ * clip on the timeline. */+const manyClips = {+ ids: ids("clipId"),+ all_clips: bool("Land the change on every clip on the timeline (instead of clipId or ids)"),+};+/** [input, output] control points, 0..255, for one curve channel. */const curvePoints = (channel: string) => ({type: "array" as const,@@ -65,6 +89,10 @@ const wheelArg = (zone: string) =>luma: num(`${zone} brightness trim -${GRADE_MAX}..${GRADE_MAX}`),});+const wheelArgs = Object.fromEntries(+ Object.entries(WHEEL_ARGS).map(([name, z]) => [name, wheelArg(WHEEL_LABELS[z])])+);+export const INSPECTOR_TOOLS = [{name: "update_overlay",@@ -323,15 +351,16 @@ export const INSPECTOR_TOOLS = [{name: "set_color_grade",description:- "Color-grade a video clip's basic sliders (any track; stills too). Fields patch the clip's current grade: only the ones you pass change, and every value 0 is neutral. Manual adjustments layer OVER the clip's color preset (set_color_preset), never replacing it. reset:true clears the manual grade first (the preset stays); auto:true fits a starting grade from the clip's decoded frame (auto-tone: exposure to middle gray, contrast stretch, gray-world white balance — needs the clip's frame decoded, so seek into it first if this errors), and explicit fields then override it. Preview, timeline thumbnails, and export all render the same result. Read read_color_stats before grading so the numbers ground the move.",+ `Color-grade a video clip's basic sliders (any track; stills too): the Light group (${GRADE_BASIC_FIELDS.filter((f) => f.group === "light").map((f) => f.key).join(", ")}), the Color group (${GRADE_BASIC_FIELDS.filter((f) => f.group === "color").map((f) => f.key).join(", ")}) and the Detail pair (${GRADE_DETAIL_FIELDS.map((f) => f.key).join(", ")}). Fields patch the clip's current grade: only the ones you pass change, and every value 0 is neutral. The light sliders work in linear light on the picture after its source conversion and LUT; manual adjustments layer OVER the clip's color preset (set_color_preset), never replacing it. reset:true clears the manual grade first (the preset and LUT stay); auto:true fits a starting grade from the clip's base rendering (auto-tone: exposure to middle gray, contrast stretch, gray-world white balance — needs the clip's frame decoded, so seek into it first if this errors), and explicit fields then override it. Preview, timeline thumbnails, and export all render the same result. Read read_color_stats before grading so the numbers ground the move. Pass ids or all_clips to land the same patch on several clips as one undo step.`,inputSchema: obj({clipId: str("Video clip id"),+ ...manyClips,...gradeFieldProps,brightness: num(`-${GRADE_MAX}..${GRADE_MAX}, 0 neutral (plain gain; prefer exposure)`),hue: num(`Whole-frame hue rotation in degrees, -${GRADE_HUE_MAX}..${GRADE_HUE_MAX} (for one hue only, use set_color_hsl)`),auto: bool("Fit a starting grade from the clip's current frame"),- reset: bool("Clear the existing manual grade before applying fields (keeps the preset)"),- }, ["clipId"]),+ reset: bool("Clear the existing manual grade before applying fields (keeps the preset and the LUT)"),+ }),},{name: "set_color_preset",@@ -339,7 +368,7 @@ export const INSPECTOR_TOOLS = [`Apply a named color preset to a video clip, layered under its manual grade. Presets by category — ${gradePresetCatalogText()}. amount 0..1 scales the preset toward neutral (default 1); protect_skin keeps its color shifts off skin tones. Pass preset "none" to clear. Preview, tiles, and export all render the same result.`,inputSchema: obj({clipId: str("Video clip id"),- ids: ids("clipId"),+ ...manyClips,preset: {type: "string",enum: [...GRADE_PRESET_IDS, "none"],@@ -352,29 +381,28 @@ export const INSPECTOR_TOOLS = [{name: "set_color_curves",description:- `Set a video clip's tone curves: per-channel [input, output] control points (0..255) through a monotone spline — master shapes all three channels, red/green/blue shape one each. A channel you pass replaces that channel; an empty list clears it; others keep their curve. The semantic knobs write the master curve for you: curve_contrast (-${GRADE_MAX}..${GRADE_MAX}) is an s-curve around mid-gray, fade (0..${GRADE_MAX}) lifts the blacks for a faded-film look; passing either replaces the master curve. reset:true clears every curve first.`,+ `Set a video clip's tone curves: per-channel [input, output] control points (0..255) through a monotone spline — master shapes all three channels, red/green/blue shape one each. A channel you pass replaces that channel; an empty list clears it; others keep their curve. curve_contrast (-${GRADE_MAX}..${GRADE_MAX}) writes an s-curve around mid-gray into the master curve for you, replacing it (lifted, faded blacks are the fade slider of set_color_grade). reset:true clears every curve first. Pass ids or all_clips to land the same curves on several clips.`,inputSchema: obj({clipId: str("Video clip id"),+ ...manyClips,master: curvePoints("Master"),red: curvePoints("Red"),green: curvePoints("Green"),blue: curvePoints("Blue"),curve_contrast: num(`S-curve contrast -${GRADE_MAX}..${GRADE_MAX} (compiled into master points)`),- fade: num(`Lifted blacks 0..${GRADE_MAX} (compiled into master points)`),reset: bool("Clear all curves before applying"),- }, ["clipId"]),+ }),},{name: "set_color_wheels",description:- `Set a video clip's color wheels — shadows, midtones, highlights — for split-toning: each wheel pushes its tonal range toward a hue (dx/dy is the wheel puck: angle = hue, 0° = red, 120° = green, 240° = blue; distance = strength) and trims its brightness (luma). A wheel you pass is replaced whole; {dx:0,dy:0,luma:0} clears it. reset:true clears all three.`,+ `Set a video clip's four color wheels — ${WHEEL_ZONES.map((z) => WHEEL_LABELS[z].toLowerCase()).join(", ")} — the ASC CDL set: lift moves the shadows, gamma the midtones, gain the highlights, and offset shifts the whole picture equally. Each wheel pushes its range toward a hue (dx/dy is the wheel puck: angle = hue, 0° = red, 120° = green, 240° = blue; distance = strength) and trims its brightness (luma). A wheel you pass is replaced whole; {dx:0,dy:0,luma:0} clears it. reset:true clears all four. Pass ids or all_clips to land the same wheels on several clips.`,inputSchema: obj({clipId: str("Video clip id"),- shadows: wheelArg("Shadow"),- midtones: wheelArg("Midtone"),- highlights: wheelArg("Highlight"),+ ...manyClips,+ ...wheelArgs,reset: bool("Clear all wheels before applying"),- }, ["clipId"]),+ }),},{name: "set_color_hsl",@@ -382,6 +410,7 @@ export const INSPECTOR_TOOLS = [`Adjust one hue band of a video clip — shift its hue (±${GRADE_MAX} ≈ ±30°), scale its saturation, and lift or darken its luminance — leaving every other color alone ("just the sky bluer", "mute the greens"). Bands: ${HSL_BANDS.map((b) => b.id).join(", ")}. The band's three values are replaced whole (omitted values 0); all-zero clears the band. reset_all clears every band first.`,inputSchema: obj({clipId: str("Video clip id"),+ ...manyClips,band: {type: "string",enum: HSL_BANDS.map((b) => b.id),@@ -391,25 +420,76 @@ export const INSPECTOR_TOOLS = [sat: num(`Saturation -${GRADE_MAX}..${GRADE_MAX}`),luma: num(`Luminance -${GRADE_MAX}..${GRADE_MAX}`),reset_all: bool("Clear every hue band first"),+ }),+ },+ {+ name: "set_color_lut",+ description:+ 'Put a LUT from the user\'s Library on a video clip, or take it off. The LUT is a .cube or .3dl file in the Library (editor_state lists them under `luts` with their ids, "lut:<key>"); it is applied to the picture after the clip\'s source conversion and under the grade, so a creative LUT works on log footage and the sliders shape what comes out. amount 0..1 mixes the LUT\'s result with its input (default 1). Pass lut "none" to remove it. A Log-to-Rec.709 technical LUT (a camera maker\'s) belongs on a clip whose source color is set to rec709 (set_source_color) so it is not converted twice. Pass ids or all_clips to land the same LUT on several clips as one undo step.',+ inputSchema: obj({+ clipId: str("Video clip id"),+ ...manyClips,+ lut: str('A Library LUT id ("lut:<key>", from editor_state.luts) or "none" to remove the LUT'),+ amount: num("Intensity 0..1 (default 1; omitted keeps the clip's current amount)"),+ }, ["lut"]),+ },+ {+ name: "copy_color_grade",+ description:+ "Copy a video clip's whole color grade — preset, sliders, curves, wheels, hue bands, LUT and intensity — onto other clips, as one undo step. This is \"apply to all\": pass all_clips for every clip on the timeline, or ids for a chosen set. The source clip's grade replaces whatever the targets wore.",+ inputSchema: obj({+ clipId: str("The clip whose grade to copy"),+ ids: ids("clipId (the clips to copy it onto)"),+ all_clips: bool("Copy it onto every other clip on the timeline"),}, ["clipId"]),},+ {+ name: "set_source_color",+ description:+ `Set what a source's code values mean — its color profile — for footage the header did not settle or the user wants read differently: ${SOURCE_PROFILES.map((p) => `${p.id} (${p.label}: ${p.detail.replace(/\.$/, "")})`).join("; ")}. A log or HDR profile is converted to Rec.709 display values before any LUT or grade (Apple Log through the ACES output transform, HLG/PQ through BT.2100). "auto" returns the asset to the profile read from its file (editor_state.media shows each asset's sourceColor with what was detected). Pass assetId, or clipId for the clip's own source; every clip cut from that source changes with it.`,+ inputSchema: obj({+ assetId: str("Project asset id"),+ clipId: str("A video clip id — its source asset is the one changed"),+ profile: {+ type: "string",+ enum: [...SOURCE_PROFILES.map((p) => p.id), "auto"],+ description: 'Source profile, or "auto" for the detected one',+ },+ }, ["profile"]),+ },+ {+ name: "save_color_grade",+ description:+ "Save a clip's current color grade — preset, sliders, curves, wheels, hue bands and LUT — to the user's Library under a name, so apply_saved_grade can put it on other clips and the Color panel's Saved category offers it.",+ inputSchema: obj({ clipId: str("Video clip whose grade to save"), name: str("Preset name") }, ["clipId", "name"]),+ },+ {+ name: "apply_saved_grade",+ description:+ "Put one of the user's saved color grades (editor_state.savedGrades, or library_list templates carrying a grade) on a video clip, replacing the clip's whole grade. Pass ids or all_clips for several clips as one undo step.",+ inputSchema: obj({+ clipId: str("Video clip id"),+ ...manyClips,+ preset_id: str("The saved grade's id, or its name"),+ }, ["preset_id"]),+ },{name: "read_color_stats",description:- "Read color statistics off a frame — per-channel and luma quantiles (0..255), channel means, mean saturation, and warmth (red/blue midtone ratio; >1 warm, <1 cool). Pass clipId for a video clip's current frame (pre-grade, so the numbers describe the footage itself; seek into the clip first if it errors) or assetId for an image (a chat attachment or Media import). Read stats before grading — never grade blind — and read them again after to verify the move.",+ "Read color statistics off a frame — per-channel and luma quantiles (0..255), channel means, mean saturation, and warmth (red/blue midtone ratio; >1 warm, <1 cool). Pass clipId for a video clip's current frame as its base rendering (through the source conversion, before any LUT or grade, so the numbers describe the footage itself; seek into the clip first if it errors) or assetId for an image (a chat attachment or Media import). Read stats before grading — never grade blind — and read them again after to verify the move.",inputSchema: obj({- clipId: str("Video clip id (its current decoded frame)"),+ clipId: str("Video clip id (its current frame's base rendering)"),assetId: str("Image asset id (chat attachment or import)"),}),},{name: "match_color_grade",description:- "Match a video clip's color to a reference, computed from the pixels: per-channel quantile mapping compiled into tone curves plus a saturation delta. The computed curves carry the whole look, so the match replaces the clip's entire grade, preset included. The reference is ref_asset_id (an attached or imported image) or ref_clip_id (another clip's current frame). Use when the user shares a look to copy or asks to match two shots; refine afterward with the other grading tools, checking read_color_stats.",+ "Match a video clip's color to a reference, computed from the pixels: per-channel quantile mapping compiled into tone curves plus a saturation delta. The computed curves carry the whole look, so the match replaces the clip's entire grade, preset and LUT included. The reference is ref_asset_id (an attached or imported image) or ref_clip_id (another clip's current frame). Use when the user shares a look to copy or asks to match two shots; refine afterward with the other grading tools, checking read_color_stats.",inputSchema: obj({clipId: str("Video clip to grade"),ref_asset_id: str("Reference image asset id"),- ref_clip_id: str("Reference video clip id (its current decoded frame)"),+ ref_clip_id: str("Reference video clip id (its current frame's base rendering)"),}, ["clipId"]),},] as const satisfies readonly AiToolDef[];diff --git a/site/src/cut/components/LibraryView.tools.ts b/site/src/cut/components/LibraryView.tools.tsindex 9b9bc3cb..8014d381 100644--- a/site/src/cut/components/LibraryView.tools.ts+++ b/site/src/cut/components/LibraryView.tools.ts@@ -38,7 +38,7 @@ export const LIBRARY_TOOLS = [{name: "library_list",description:- CLOUD_LIBRARY_IMPORT_DESCRIPTION + " " + "List the shared Library — reusable media saved across projects: folders (nested; a folder's parentId names the folder it sits in), assets (video/audio/image, and the account's own font files), and templates (saved arrangements of clips, overlays, titles, and captions). An asset's `origin` says it came from the user's iOS app: \"camera\" is a clip they recorded on their phone (their Camera Roll), \"inspiration\" a reference they saved to the Inspiration folder. Library items live outside the project: library_add imports an asset, template_add re-materializes a template.",+ CLOUD_LIBRARY_IMPORT_DESCRIPTION + " " + "List the shared Library — reusable media saved across projects: folders (nested; a folder's parentId names the folder it sits in), assets (video/audio/image, the account's own font files, and its LUT files — .cube/.3dl, offered to every clip as \"lut:<key>\" via set_color_lut), and templates (saved arrangements of clips, overlays, titles, and captions). An asset's `origin` says it came from the user's iOS app: \"camera\" is a clip they recorded on their phone (their Camera Roll), \"inspiration\" a reference they saved to the Inspiration folder. Library items live outside the project: library_add imports an asset, template_add re-materializes a template.",inputSchema: obj({}),},{diff --git a/site/src/cut/components/LibraryView.tsx b/site/src/cut/components/LibraryView.tsxindex 832ae2d6..56dd3d53 100644--- a/site/src/cut/components/LibraryView.tsx+++ b/site/src/cut/components/LibraryView.tsx@@ -27,7 +27,7 @@ import {} from "@/components/ui/dialog";import { Input } from "@/components/ui/input";import { setObjectDragImage } from "@/cut/lib/assetDrag";-import { LibraryCard, LIBRARY_TILE_AREA, LIBRARY_AUDIO_TILE_AREA } from "@/cut/components/LibraryCard";+import { LibraryCard, LIBRARY_TILE_AREA, LIBRARY_AUDIO_TILE_AREA, LIBRARY_SQUARE } from "@/cut/components/LibraryCard";import { ShelfBadge } from "@/cut/components/ShelfBadge";import { MEDIA_ACCEPT } from "@/cut/lib/media";import { saveNote } from "@/cut/lib/notes";@@ -638,7 +638,8 @@ export function LibraryView() {pending: p,});for (const a of shown) band(shapeOf(a)).push({ asset: a });- // Sound tiles are 70% of the shared tile's width and height.+ // Sound tiles, and every other file that is no picture, are 70% of the+ // shared tile's width and height.const TILE_AREA = LIBRARY_TILE_AREA;const audioArea = LIBRARY_AUDIO_TILE_AREA;// Where a new folder goes: inside the open folder on its shelf, or at the@@ -826,10 +827,11 @@ export function LibraryView() {setSelected={setSelected}>{shownTemplates.length > 0 && (- <div className="grid grid-cols-[repeat(auto-fill,minmax(240px,1fr))] gap-3">+ <div className="flex flex-wrap items-start gap-4">{shownTemplates.map((t) => (<TemplateCardkey={t.id}+ tile={LIBRARY_SQUARE}template={t}mediaSrc={(f) => libraryMediaUrl(f, t.residency)}drag={@@ -873,7 +875,7 @@ export function LibraryView() {key={a.id}asset={a}onShare={() => setSharing({ kind: "asset", id: a.id, residency: a.residency })}- area={a.type === "audio" ? audioArea : TILE_AREA}+ area={a.type === "video" || a.type === "image" ? TILE_AREA : audioArea}selected={selected.has(a.id)}dragGroup={pickedRun}offline={!live(a.residency)}diff --git a/site/src/cut/components/Preview.tsx b/site/src/cut/components/Preview.tsxindex 5240cacd..50d19ded 100644--- a/site/src/cut/components/Preview.tsx+++ b/site/src/cut/components/Preview.tsx@@ -1,6 +1,6 @@"use client";-import { useCallback, useEffect, useLayoutEffect, useMemo, useRef, useState, type RefObject } from "react";+import { useCallback, useEffect, useLayoutEffect, useMemo, useRef, useState, useSyncExternalStore, type RefObject } from "react";import { Check, Copy, Loader2, ZoomIn, ZoomOut } from "lucide-react";import { usePlayback } from "@/cut/hooks/usePlayback";import { startDrag } from "@/cut/lib/drag";@@ -22,6 +22,7 @@ import {readPoster,} from "@/cut/lib/posterCache";import { resizePreviewSurface, setPreviewCanvas } from "@/cut/lib/previewCanvas";+import { hdrPreviewState, subscribeHdrPreviewState } from "@/cut/lib/hdrPresent";import { CLIP_MAX_ZOOM, clipCovers, clipKeyed, clipPoseAt, clipZoom, contentRect, frameOf, isFullRect, rectOf, REGION_MAX_SCALE, type VideoClip } from "@/cut/lib/types";import { hasMaskKeys, type MaskKey, type MaskPoint } from "@donkeycut/effects-kit";import {@@ -63,7 +64,10 @@ function stageClick() {* fetches and seeks — the engine leaves the canvas alone until it has a frame,* which is what lets a poster sit there in the meantime. Once a real frame* lands it is kept for the next open. */-function useCachedFirstFrame(canvasRef: RefObject<HTMLCanvasElement | null>) {+function useCachedFirstFrame(+ canvasRef: RefObject<HTMLCanvasElement | null>,+ presentRef: RefObject<HTMLCanvasElement | null>+) {// Re-runs per load, so reopening a project repaints and re-captures.const epoch = useEditor((s) => (s.loaded ? s.loadEpoch : 0));const projectId = useEditor((s) => s.projectId);@@ -78,12 +82,16 @@ function useCachedFirstFrame(canvasRef: RefObject<HTMLCanvasElement | null>) {void paintPoster(canvas, data);}});- const stop = capturePosterOnPicture("frame", projectId, () => canvasRef.current);+ // An HDR preview's poster reads off the presented picture: the composite+ // canvas beneath holds an HLG signal, which is not a picture to keep.+ const stop = capturePosterOnPicture("frame", projectId, () =>+ hdrPreviewState() === "hdr" ? presentRef.current : canvasRef.current+ );return () => {alive = false;stop();};- }, [canvasRef, epoch, projectId]);+ }, [canvasRef, presentRef, epoch, projectId]);}/** How far the camera zooms from the fitted size, in multiples of the fit. */@@ -160,6 +168,10 @@ function BufferingBadge() {export function Preview() {const canvasRef = useRef<HTMLCanvasElement>(null);+ // The extended-range canvas the HDR picture is presented on, over the+ // composite canvas; shown only while the stage is in HDR.+ const presentRef = useRef<HTMLCanvasElement>(null);+ const hdr = useSyncExternalStore(subscribeHdrPreviewState, hdrPreviewState, () => "off" as const);const wrapRef = useRef<HTMLDivElement>(null);// The camera: the picture's fitted size at 100%, the pane it lives in, and// the view's zoom and pan on top. The stage's on-screen size stays the unit@@ -306,7 +318,7 @@ export function Preview() {[zoomAt]);- usePlayback(canvasRef);+ usePlayback(canvasRef, presentRef);// An effect grades what plays under it, so the stage is built in slices: the// picture, then the elements of each lane band with the look of the effects// above them, and each effect's paints sitting where the effect does. Only@@ -350,7 +362,7 @@ export function Preview() {return () => setPreviewCanvas(null);}, []);- useCachedFirstFrame(canvasRef);+ useCachedFirstFrame(canvasRef, presentRef);// The canvas backing store matches the pixels the screen will actually show,// capped at the project's own frame. Painting a 4K backing store into a box@@ -642,7 +654,17 @@ export function Preview() {// blank the canvas on every change.className="block size-full"/>+ <canvas+ ref={presentRef}+ // Sized by the present pass to the composite beneath it.+ className={cn("pointer-events-none absolute inset-0 size-full", hdr !== "hdr" && "hidden")}+ /></StagePictureFx>+ {hdr === "sdr" && (+ <span className="pointer-events-none absolute top-2 left-2 rounded-full bg-black/55 px-2 py-0.5 text-[11px] font-medium text-white">+ Previewing SDR+ </span>+ )}<BufferingBadge /><OriginalPeekBadge /><GuideHandles stage={stage} />diff --git a/site/src/cut/components/RequireSession.tsx b/site/src/cut/components/RequireSession.tsxindex 9f40447b..f6bbbbc0 100644--- a/site/src/cut/components/RequireSession.tsx+++ b/site/src/cut/components/RequireSession.tsx@@ -1,5 +1,6 @@"use client";import { bindChatRuntime, bindChatgptPolling, bindCutClip, bindCutJudge } from "@/cut/lib/chatRuntime";+import { bindCutColor } from "@/cut/lib/colorSettings";import { useEffect, type ReactNode } from "react";import { useEnvironment } from "@/cut/lib/environment";@@ -44,6 +45,7 @@ export function RequireSession({ children }: { children: ReactNode }) {bindChatgptPolling(config.data.settings.chatgptPolling);bindCutJudge(config.data.settings.cutJudge);bindCutClip(config.data.settings.cutClip);+ bindCutColor(config.data.settings.cutColor);reportExposures(config.data);}, [userId, config.data]);diff --git a/site/src/cut/components/SharedLibraryView.tsx b/site/src/cut/components/SharedLibraryView.tsxindex d6c5ed38..0b86b687 100644--- a/site/src/cut/components/SharedLibraryView.tsx+++ b/site/src/cut/components/SharedLibraryView.tsx@@ -17,7 +17,7 @@ function Asset({ asset, token }: { asset: SharedLibraryAsset; token: string }) {const poster = asset.hasPoster ? `${src}?poster=1` : undefined;return <LibraryCardasset={{ ...asset, addedAt: 0, residency: "cloud" }}- area={asset.type === "audio" ? LIBRARY_AUDIO_TILE_AREA : LIBRARY_TILE_AREA}+ area={asset.type === "video" || asset.type === "image" ? LIBRARY_TILE_AREA : LIBRARY_AUDIO_TILE_AREA}sharedMedia={{ src, poster, downloadHref: `${src}?download=1` }}/>;}diff --git a/site/src/cut/components/SidePanel.tsx b/site/src/cut/components/SidePanel.tsxindex c347c858..a821e18b 100644--- a/site/src/cut/components/SidePanel.tsx+++ b/site/src/cut/components/SidePanel.tsx@@ -90,14 +90,17 @@ import {type Residency,} from "@/cut/lib/residency";import { isSoundPresetTemplate } from "@/cut/lib/soundPresets";+import { isGradePresetTemplate } from "@/cut/lib/gradePresets";import { isStylePresetTemplate } from "@/cut/lib/stylePresets";import { retryUpload } from "@/cut/lib/importQueue";import {forgetLinkedCopies,linkedAccept,+ LUT_FILE_ICON,} from "@/cut/lib/linkedLibrary";import { downloadMedia, MEDIA_ACCEPT, revealMedia } from "@/cut/lib/media";-import { mediaUrl } from "@/cut/lib/types";+import { useProxyJobs } from "@/cut/lib/mediaProxy";+import { isLinkedAssetType, mediaUrl } from "@/cut/lib/types";import {genPulseOverlay,isGenTab,@@ -803,7 +806,7 @@ function ProjectFilesPanel({// `origin` and stays where it was made.// Fonts are project assets (their bytes live in media/) but they belong to// the text inspector's font menu, never the Media grid.- const assets = useEditor((s) => s.assets).filter((a) => a.origin == null && a.type !== "font");+ const assets = useEditor((s) => s.assets).filter((a) => a.origin == null && !isLinkedAssetType(a.type));// The panel's folders, plus which one is open; the grid shows the open// folder's files, or the unfiled ones at the root.const folders = useEditor((s) => s.mediaFolders);@@ -1101,10 +1104,11 @@ function ProjectFilesPanel({)}{openFolder === null && templates.length > 0 && (- <div className="flex flex-col gap-1.5 px-3.5 pb-3">+ <div className="grid grid-cols-2 gap-2.5 px-3.5 pb-3">{templates.map((t) => (<TemplateCardkey={t.id}+ tile="fill"template={t}mediaSrc={(f) => mediaUrl(projectId, f)}drag={{ scope: "project", template: t }}@@ -1382,6 +1386,22 @@ function UploadState({ asset }: { asset: MediaAsset }) {);}+/** The line across the bottom of a ProRes tile while its preview proxy is+ * being made. The clip already plays, off the master, so this stays as quiet+ * as an upload's. */+function ProxyState({ asset }: { asset: MediaAsset }) {+ const job = useProxyJobs((s) => s.jobs[asset.id]);+ if (!job || job.kind !== "making") return null;+ return (+ <span className="absolute inset-x-0 bottom-0 h-[3px] bg-black/25">+ <span+ className="block h-full bg-primary transition-[width] duration-150"+ style={{ width: `${Math.round(job.progress * 100)}%` }}+ />+ </span>+ );+}+function AssetCard({asset,projectId,@@ -1395,7 +1415,7 @@ function AssetCard({selected?: boolean;/** Clicking the card picks it — plain replaces the selection, ⇧/⌘ adds to* it. A pick never places anything; the timeline gets media by drag or by- * the card's own + button. */+ * the card's "Add to timeline" menu item. */onSelect?: (e: React.MouseEvent) => void;/** Everything picked right now, so dragging one card drags them all. */dragGroup?: string[];@@ -1458,7 +1478,6 @@ function AssetCard({view={asset.upload ? undefined : () => lightboxItemFromAsset(asset)}restTime={0.1}className="asset-card group flex flex-col gap-1.5 text-left"- title="Drag onto the timeline, or click + to add"onClick={onSelect}onDragStart={(e) => {setAssetDragData(e, asset.id, dragGroup);@@ -1480,7 +1499,7 @@ function AssetCard({ref={tileRef}data-drag-objectclassName={cn(- "relative aspect-square overflow-hidden rounded-lg border border-border bg-muted transition-colors group-hover:border-input",+ "relative aspect-square overflow-hidden rounded-xl border border-border bg-muted shadow-sm transition-colors group-hover:border-input",(flash || selected) && PICKED_RING)}>@@ -1501,13 +1520,14 @@ function AssetCard({) : asset.type === "image" ? (// eslint-disable-next-line @next/next/no-img-element -- engine/static file, not Next-optimizable<img crossOrigin={MEDIA_CORS} src={asset.url} alt={asset.name} loading="lazy" className="size-full object-cover" />+ ) : asset.type === "lut" ? (+ // eslint-disable-next-line @next/next/no-img-element -- static icon+ <img src={LUT_FILE_ICON} alt={asset.name} className="size-full object-contain p-2" />) : (<AudioCardFaceurl={asset.url}duration={asset.duration}peaks={asset.peaks}- // On hover the + button takes the pill's corner, as on Library cards.- durationClassName="transition-opacity group-hover:opacity-0"/>)}{asset.type === "video" && (@@ -1531,35 +1551,19 @@ function AssetCard({{formatBytes(sizeBytes)}</span>)}- <span- className={cn(- "absolute flex gap-1 opacity-0 transition-opacity group-hover:opacity-100",- // Audio keeps play bottom-left; + swaps in where the duration pill hides.- asset.type === "audio" ? "right-1.5 bottom-2.5" : "top-1 left-1"- )}- >- <span- role="button"- title="Add to timeline"- className="grid size-5 scale-75 cursor-pointer place-items-center rounded-full bg-primary text-primary-foreground transition-transform group-hover:scale-100 hover:brightness-110"- onClick={(e) => {- e.stopPropagation();- add();- }}- >- <Plus className="size-3" />- </span>- </span><DropdownMenu><DropdownMenuTriggeraria-label="More actions"- title="More actions"className="absolute top-1 right-1 grid size-5 place-items-center rounded-full bg-black/45 text-white opacity-0 transition-opacity group-hover:opacity-100 hover:bg-black/65 data-[state=open]:opacity-100"onClick={(e) => e.stopPropagation()}>{saved ? <Check className="size-3" /> : <Ellipsis className="size-3" />}</DropdownMenuTrigger><DropdownMenuContent align="end" className="w-48" onClick={(e) => e.stopPropagation()}>+ <DropdownMenuItem onClick={add}>+ <Plus /> Add to timeline+ </DropdownMenuItem>+ <DropdownMenuSeparator /><DropdownMenuItem onClick={saveToLibrary} disabled={!!asset.upload}><FolderPlus /> Save to library</DropdownMenuItem>@@ -1590,6 +1594,7 @@ function AssetCard({/>)}{asset.upload && <UploadState asset={asset} />}+ {!asset.upload && <ProxyState asset={asset} />}</div>{asset.type !== "audio" && (<CopyNameLabel name={asset.name} className="text-[11px] text-muted-foreground" />@@ -1652,7 +1657,7 @@ function LibraryPanel({ projectId, onImport }: {// Saved text styles and sound presets ride the template rails but are not// templates: they belong to their inspectors, not this shelf.const templates = (library.data?.templates ?? []).filter(- (t) => reachable(t.residency) && !isStylePresetTemplate(t) && !isSoundPresetTemplate(t)+ (t) => reachable(t.residency) && !isStylePresetTemplate(t) && !isSoundPresetTemplate(t) && !isGradePresetTemplate(t));const listing: LibraryData = { assets, folders, templates };const patch = useCallback(@@ -2000,10 +2005,11 @@ function LibraryPanel({ projectId, onImport }: {) : null}{shownTemplates.length > 0 && (<div className="shrink-0 px-3.5 pb-3">- <div className="flex flex-col gap-1.5">+ <div className="grid grid-cols-2 gap-2.5">{shownTemplates.map((t) => (<TemplateCardkey={t.id}+ tile="fill"template={t}mediaSrc={(f) => libraryMediaUrl(f, t.residency)}drag={{ scope: "library", template: t }}@@ -2064,9 +2070,9 @@ function LibraryPanel({ projectId, onImport }: {selected={picked.has(a.id)}onClick={(e) => pick(e, a.id, order)}dragGroup={pickedRun}- // A font is used from the font menu; there is nothing to place.+ // A linked item is used from its own menu; there is nothing to place.onUse={- a.type === "font" ? undefined : () => void addLibraryAssetToProject(projectId, a)+ isLinkedAssetType(a.type) ? undefined : () => void addLibraryAssetToProject(projectId, a)}onDelete={() => setDeleting(setOf(a))}onDragStartExtra={(e) => onCardDragExtra(e, a)}diff --git a/site/src/cut/components/Timeline.tsx b/site/src/cut/components/Timeline.tsxindex 024e1a3a..7512dd9d 100644--- a/site/src/cut/components/Timeline.tsx+++ b/site/src/cut/components/Timeline.tsx@@ -22,6 +22,7 @@ import {draggingAssetId,draggingAssetIds,draggingElement,+ draggedLutKey,draggingLibraryMany,draggingTemplate,hasAssetDrag,@@ -29,6 +30,7 @@ import {hasLibraryDrag,hasTemplateDrag,} from "@/cut/lib/assetDrag";+import { libraryLutId, LUT_MARK_ICON } from "@/cut/lib/linkedLibrary";import { registerFileLanding, registerTransitionLanding } from "@/cut/lib/timelineDrop";import { audioClipRefs, clipRefs, draggingRef, hasRefDrag, refFromAsset, type AssetRef } from "@/cut/lib/assetRef";import { sendFrameToChat, type FrameGrabOrigin } from "@/cut/lib/chatIntake";@@ -64,10 +66,10 @@ import { laneHidden, subtitleLaneCount } from "@/cut/lib/subtitles";import { formatTime, formatTimecode } from "@/cut/lib/time";import { EFFECT_LABELS, hasSpeedCurve, headSrc, retimeOf, SPEED_CURVE_MAX, SPEED_CURVE_MIN, tailSrc, type EffectId, type Retime, type SpeedNode } from "@donkeycut/effects-kit";import { BLOCK_COLOR } from "@/cut/lib/blockSource";-import { assetIsSilent, emptySubtitles, fontStack, IMAGE_CLIP_SECONDS, isAudioTransition, clipName, isTextOverlay, overlayName, SHAPE_LABELS, TRANSITION_STYLE_LABELS, transitionBarStart, transitionDefaultSeconds, XBAR_MAGNET_PX, type ShapeKind } from "@/cut/lib/types";+import { isLinkedAssetType, assetIsSilent, emptySubtitles, fontStack, IMAGE_CLIP_SECONDS, isAudioTransition, clipName, isTextOverlay, overlayName, SHAPE_LABELS, TRANSITION_STYLE_LABELS, transitionBarStart, transitionDefaultSeconds, XBAR_MAGNET_PX, type ShapeKind } from "@/cut/lib/types";import type { AudioClip, ClipSpan, ColorGrade, MediaAsset, Overlay, Selection, StickerOverlay, SubtitleCue, TimelineTransition, TransitionBoundaryKind, TransitionStyle, VideoClip } from "@/cut/lib/types";import { isLottieAsset } from "@/cut/lib/lottieAssets";-import { gradeCssApprox } from "@donkeycut/effects-kit";+import { gradeCssApprox, normalizeGrade } from "@donkeycut/effects-kit";import { cn } from "@/lib/utils";/**@@ -429,13 +431,30 @@ interface CarriedMedia {ghost?: DropGhost;}+/** The grade id of the LUT a library drag is carrying, or null when the drag+ * holds anything else. A LUT has no place on the timeline as a clip: it lands+ * on the clip under the pointer as that clip's grade. */+function draggedLut(e: React.DragEvent): string | null {+ const key = draggedLutKey(e);+ return key ? libraryLutId(key) : null;+}++/** The clip box under a point, read off the DOM the boxes are drawn in. */+function clipIdAt(x: number, y: number): string | null {+ for (const el of document.elementsFromPoint(x, y)) {+ const sel = (el as HTMLElement).dataset?.tlSel;+ if (sel?.startsWith("clip:")) return sel.slice(5);+ }+ return null;+}+/** Everything a drag carries, the grabbed item first. A single card is a run* of one, so every media drop takes the same path; a font, which has no* place on the timeline, is left out. */function carriedMedia(e: React.DragEvent): CarriedMedia[] {if (hasLibraryDrag(e)) {return draggingLibraryMany().flatMap((lib) =>- lib.type === "font"+ isLinkedAssetType(lib.type)? []: [{@@ -468,7 +487,7 @@ function carriedMedia(e: React.DragEvent): CarriedMedia[] {const assets = useEditor.getState().assets;return draggingAssetIds().flatMap((id) => {const asset = assets.find((a) => a.id === id);- if (!asset || asset.type === "font") return [];+ if (!asset || isLinkedAssetType(asset.type)) return [];return [{kind: asset.type,@@ -748,6 +767,8 @@ export function Timeline() {} | null>(null);// Kind of external media being dragged over the timeline (audio vs video).const [dropType, setDropType] = useState<"video" | "audio" | null>(null);+ // The clip a carried LUT is held over, lit as the drop's target.+ const [lutTarget, setLutTarget] = useState<string | null>(null);// The pending drop preview: which track/gap, at what time, for how long —// and which resident clips slide right to open the room, so the row can// paint them parting ahead of the drop.@@ -1706,7 +1727,7 @@ export function Timeline() {// The landing outlived a project switch: the asset belongs to the// project it was landed in.if (useEditor.getState().projectId !== projectId) return;- if (asset.type === "font") continue;+ if (isLinkedAssetType(asset.type)) continue;if (only && !only(asset)) continue;const sticker = !!stickerOf(asset);if (block && !sticker && isClipMedia(asset.type)) {@@ -1776,8 +1797,9 @@ export function Timeline() {// A sticker crossing a video row is still headed for the element rows,// and OS files belong to the timeline's own drop, which stashes their// landing for the editor's import and clears every preview; both pass- // through here untouched.- if (hasElementDrag(e) || draggedSticker() || draggedFiles(e)) return;+ // through here untouched. A LUT lands on a clip, which the footer's+ // drop resolves.+ if (hasElementDrag(e) || draggedSticker() || draggedFiles(e) || draggedLut(e)) return;e.preventDefault();e.stopPropagation();cancelPreview();@@ -1910,6 +1932,20 @@ export function Timeline() {// surface's own landing previews while a drag is over it.data-segment-droponDragOver={(e) => {+ // A LUT is a grade, so its landing is the clip under the pointer:+ // lit while the drag is over it, and none of the slot previews.+ if (draggedLut(e)) {+ e.preventDefault();+ e.dataTransfer.dropEffect = "copy";+ cancelPreview();+ setAssetDrop(null);+ setOverlayDrop(null);+ setAudioDrop(null);+ setDropType(null);+ const target = clipIdAt(e.clientX, e.clientY);+ setLutTarget((cur) => (cur === target ? cur : target));+ return;+ }// A template materializes as a whole arrangement, so it accepts the// drop without a single-clip landing preview.if (hasTemplateDrag(e)) {@@ -2055,6 +2091,7 @@ export function Timeline() {onDragLeave={(e) => {if (!e.currentTarget.contains(e.relatedTarget as Node | null)) {cancelPreview();+ setLutTarget(null);setAssetDrop(null);endCrossDrag();setAudioDrop(null);@@ -2066,6 +2103,34 @@ export function Timeline() {}}onDrop={(e) => {cancelPreview();+ // A LUT dropped on a clip becomes that clip's grade LUT — the whole+ // selection's when the clip is selected. The clip never moves.+ const lut = draggedLut(e);+ if (lut) {+ e.preventDefault();+ const target = lutTarget ?? clipIdAt(e.clientX, e.clientY);+ setLutTarget(null);+ clearAssetDrag();+ if (!target) return;+ const st = useEditor.getState();+ const picked = st.multiSelection+ .filter((m): m is { kind: "clip"; id: string } => !!m && m.kind === "clip")+ .map((m) => m.id);+ const ids = picked.includes(target) ? picked : [target];+ st.beginHistoryBatch();+ try {+ for (const id of ids) {+ const clip = st.clips.find((c) => c.id === id);+ if (!clip) continue;+ st.updateClip(id, {+ grade: normalizeGrade({ ...clip.grade, lut: { id: lut, amount: clip.grade?.lut?.amount } }),+ });+ }+ } finally {+ st.endHistoryBatch();+ }+ return;+ }// OS files: the window-level drop in the editor imports them and// reads the landing resolved here, before the previews (and the new// row a drag past the stack opened) clear under it.@@ -2597,6 +2662,7 @@ export function Timeline() {mention={clipMentions.get(span.clip.id)}pps={pps}selected={selKeys.has(`clip:${span.clip.id}`)}+ lutTarget={lutTarget === span.clip.id}drag={laneDragFor(laneDrag, "video", span.clip.id)}parting={laneDragParts(laneDrag, "video", span.clip.id) || videoDragActive}partAt={dropPartAt.get(span.clip.id)}@@ -2667,6 +2733,7 @@ export function Timeline() {mention={clipMentions.get(span.clip.id)}pps={pps}selected={selKeys.has(`clip:${span.clip.id}`)}+ lutTarget={lutTarget === span.clip.id}drag={laneDragFor(laneDrag, "video", span.clip.id)}parting={laneDragParts(laneDrag, "video", span.clip.id) || videoDragActive}partAt={dropPartAt.get(span.clip.id)}@@ -3700,6 +3767,7 @@ function ClipView({mention,pps,selected,+ lutTarget,drag,parting,partAt,@@ -3716,6 +3784,8 @@ function ClipView({mention?: string;pps: number;selected: boolean;+ /** A carried LUT is held over this clip: it lights as the drop's target. */+ lutTarget?: boolean;/** This clip's live drag when it is the one being carried (ghost mode). */drag: LaneDrag | null;/** Another clip on this row is dragging: animate this one's parting shifts. */@@ -3797,6 +3867,7 @@ function ClipView({className={cn("tl-clip group absolute top-0.5 cursor-grab overflow-hidden rounded-[2.5px] bg-black shadow-[inset_0_0_0_1px_rgba(0,0,0,0.12)]",selected && SELECTED_SHADOW,+ lutTarget && "tl-clip-lut-target z-10 shadow-[inset_0_0_0_2px_#0a84ff]",clip.hidden && "opacity-40 grayscale",drag? "tl-clip-ghost pointer-events-none cursor-grabbing opacity-80 shadow-2xl"@@ -3834,6 +3905,15 @@ function ClipView({<div className="pointer-events-none absolute inset-x-0 top-0" style={{ height: FILM_H }}><Filmstrip frames={filmstrip} grade={clip.grade} failed={stripFailed} hidden={offscreen} block={asset?.block} /></div>+ {clip.grade?.lut && (+ // The LUT badge: the file mark, small, where the clip's chrome sits.+ // eslint-disable-next-line @next/next/no-img-element+ <img+ src={LUT_MARK_ICON}+ alt="LUT"+ className="tl-clip-lut pointer-events-none absolute top-1 left-1 z-4 size-3.5 drop-shadow-[0_0_1px_rgba(0,0,0,0.6)]"+ />+ )}{hasWave && (<divclassName={cn(diff --git a/site/src/cut/components/TopBar.tools.ts b/site/src/cut/components/TopBar.tools.tsindex dca9b86d..6a873415 100644--- a/site/src/cut/components/TopBar.tools.ts+++ b/site/src/cut/components/TopBar.tools.ts@@ -5,6 +5,7 @@* keys its handlers on `TopBarToolName`.*/+import { OUTPUT_SPACES } from "@donkeycut/effects-kit";import { obj, str, type AiToolDef } from "@/cut/lib/aiToolDef";import { EXPORT_RESOLUTIONS } from "@/cut/lib/exportPresets";import { GUIDE_IDS, GUIDE_PRESETS } from "@/cut/lib/guides";@@ -45,10 +46,16 @@ export const TOP_BAR_TOOLS = [description: "Rename the current project.",inputSchema: obj({ name: str("New project name") }, ["name"]),},+ {+ name: "set_project_color",+ description:+ `Set the project's delivery color space: ${OUTPUT_SPACES.map((o) => `${o.id} = ${o.label} (${o.detail})`).join("; ")}. The export writes it — an HDR project encodes 10-bit HEVC Main 10 or ProRes tagged Rec.2020 with the HLG or PQ transfer, and H.264 is not offered — and the preview shows the HDR picture on an HDR display, or the same grade rendered as SDR with a "Previewing SDR" label elsewhere. SDR footage placed in an HDR project sits at reference white (BT.2408); HLG and PQ footage keeps its range. Call it when the user asks for HDR, HLG, PQ, Rec.2100, or to go back to SDR; editor_state project.colorSpace reports the current one.`,+ inputSchema: obj({ space: { type: "string", enum: OUTPUT_SPACES.map((o) => o.id), description: "The delivery color space" } }, ["space"]),+ },{name: "open_export",description:- `Open the export dialog: Best uses original resolution, frame rate, supported H.264/HEVC codec and audio settings. Whole files, trims and compatible sequences copy compressed video; joined audio is encoded at source settings. Effects or incompatible joins render with source settings. Other presets are Share, Social 4K, Small and Master. Controls include file name, whole video or selection range, MP4/MOV, H.264/HEVC/ProRes, resolution (${EXPORT_RESOLUTIONS.map((r) => r.label).join(", ")}, Source), frame rate, quality or custom bitrate, AAC/PCM, and an SRT captions file. Exporting itself stays a user action.`,+ `Open the export dialog: Best uses original resolution, frame rate, supported H.264/HEVC codec and audio settings. Whole files, trims and compatible sequences copy compressed video; joined audio is encoded at source settings. Effects or incompatible joins render with source settings. Other presets are Share, Social 4K, Small and Master. Controls include file name, whole video or selection range, MP4/MOV, H.264/HEVC/ProRes, resolution (${EXPORT_RESOLUTIONS.map((r) => r.label).join(", ")}, Source), frame rate, quality or custom bitrate, AAC/PCM, the project's color space (SDR, or HDR as HLG or PQ — a 10-bit HEVC or ProRes file; H.264 greys out), and an SRT captions file. Exporting itself stays a user action.`,inputSchema: obj({}),},] as const satisfies readonly AiToolDef[];diff --git a/site/src/cut/components/groupPanelParity.test.ts b/site/src/cut/components/groupPanelParity.test.tsindex ae41cf53..60b4a9a1 100644--- a/site/src/cut/components/groupPanelParity.test.ts+++ b/site/src/cut/components/groupPanelParity.test.ts@@ -20,7 +20,7 @@ const names = (label: string) =>const SHARED: Record<string, string[]> = {"video clips": ["Speed", "Reverse", "Volume", "Mute audio", "Sound quality", "Framing", "Zoom", "Flip", "Rotation", "Opacity", "Hidden", "Border", "Shadow"],"audio clips": ["Speed", "Reverse", "Volume", "Duck others", "Fade in", "Fade out", "Sound quality", "Hidden"],- titles: ["Font", "Bold", "Italic", "Align ${a}", "Text size", "Line height", "Letter spacing", "${label} stretch", "Color", "Outline", "Shadow", "Backdrop", "Position", "Rotation", "Opacity", "Hidden"],+ titles: ["Font", "Bold", "Italic", "Align ${a}", "Text size", "Line height", "Letter spacing", "Text box width", "Color", "Outline", "Shadow", "Backdrop", "Position", "Rotation", "Opacity", "Hidden"],shapes: ["Fill color", "Corner radius", "Outline", "Position", "Rotation", "Opacity", "Hidden"],stickers: ["Sticker size", "Position", "Rotation", "Opacity", "Hidden"],effects: ["Effect amount", "Depth", "Zoom speed", "Hidden"],diff --git a/site/src/cut/components/inspectorToolFields.test.ts b/site/src/cut/components/inspectorToolFields.test.tsindex 4660f8bf..f8d51c6b 100644--- a/site/src/cut/components/inspectorToolFields.test.ts+++ b/site/src/cut/components/inspectorToolFields.test.ts@@ -1,7 +1,7 @@import { describe, expect, test } from "bun:test";import { readFileSync } from "node:fs";import { fileURLToPath } from "node:url";-import { GRADE_BASIC_FIELDS } from "@donkeycut/effects-kit";+import { GRADE_BASIC_FIELDS, GRADE_DETAIL_FIELDS, WHEEL_LABELS, WHEEL_ZONES } from "@donkeycut/effects-kit";import { OVERLAY_ANIMATION_TOOLS } from "./AnimationTiles.tools";import { EFFECTS_TOOLS } from "./EffectsPanel.tools";import { INSPECTOR_TOOLS } from "./Inspector.tools";@@ -34,6 +34,11 @@ const ITEM_TOOLS = new Set(["set_color_curves","set_color_wheels","set_color_hsl",+ "set_color_lut",+ "copy_color_grade",+ "set_source_color",+ "save_color_grade",+ "apply_saved_grade","set_overlay_animation","set_overlay_keyframes","set_animation",@@ -61,7 +66,7 @@ const PLACEMENT = new Set(["id", "ids", "clipId", "transitionId", "which", "kind", "effect","start", "end", "in", "out", "at", "t", "track", "lane", "layout","region", "region.x", "region.y", "region.w", "region.h",- "clear", "reset", "reset_all", "auto",+ "clear", "reset", "reset_all", "auto", "assetId",]);/** A parameter whose panel control reads the document under another name:@@ -101,23 +106,29 @@ const PANEL_NAME: Record<string, string> = {green: "CurveEditor",blue: "CurveEditor",curve_contrast: "CurveEditor",- "shadows.dx": "WheelsTool",- "shadows.dy": "WheelsTool",- "shadows.luma": "WheelsTool",- "midtones.dx": "WheelsTool",- "midtones.dy": "WheelsTool",- "midtones.luma": "WheelsTool",- "highlights.dx": "WheelsTool",- "highlights.dy": "WheelsTool",- "highlights.luma": "WheelsTool",- midtones: "WheelsTool",+ // The four wheels and their puck/luma parts are the wheel tool.+ ...Object.fromEntries(+ WHEEL_ZONES.flatMap((z) => {+ const name = WHEEL_LABELS[z].toLowerCase();+ return [name, `${name}.dx`, `${name}.dy`, `${name}.luma`].map((k) => [k, "WheelsTool"]);+ })+ ),band: "HslTool",sat: "HslTool",+ // The whole-timeline switch is the footer's "Apply to All".+ all_clips: "clip-grade-apply-all",+ // A saved grade is picked from the Saved category.+ preset_id: "clip-grade-category-saved",+ // The source-colour select.+ profile: "clip-source-color",};-/** The basic grade sliders draw from the registry the tool's parameters are- * built from, so the panel renders the registry itself. */-const GRADE_FIELD_IDS = new Set<string>(GRADE_BASIC_FIELDS.map((f) => f.key));+/** The basic and detail grade sliders draw from the registries the tool's+ * parameters are built from, so the panel renders the registries themselves. */+const GRADE_FIELD_IDS = new Map<string, string>([+ ...GRADE_BASIC_FIELDS.map((f) => [f.key, "GRADE_BASIC_FIELDS"] as const),+ ...GRADE_DETAIL_FIELDS.map((f) => [f.key, "GRADE_DETAIL_FIELDS"] as const),+]);const camel = (name: string) => name.replace(/_([a-z])/g, (_, c: string) => c.toUpperCase());@@ -155,7 +166,7 @@ describe("inspector tool fields", () => {if (PLACEMENT.has(path) || PLACEMENT.has(leaf)) continue;const token =PANEL_NAME[path] ??- (GRADE_FIELD_IDS.has(path) ? "GRADE_BASIC_FIELDS" : undefined) ??+ GRADE_FIELD_IDS.get(path) ??PANEL_NAME[leaf] ??camel(leaf);if (!rendered(token)) missing.push(`${tool.name}.${path} (${token})`);diff --git a/site/src/cut/hooks/usePlayback.ts b/site/src/cut/hooks/usePlayback.tsindex 49d2a941..4188ba66 100644--- a/site/src/cut/hooks/usePlayback.ts+++ b/site/src/cut/hooks/usePlayback.ts@@ -16,6 +16,8 @@ import { assetIsSilent, clipCovers, rectOf } from "@/cut/lib/types";import type { ClipSpan, MediaAsset, VideoClip } from "@/cut/lib/types";import { SubjectMaskCompositor } from "@/cut/lib/behindPass";import { FrameCompositor, MISSING_FRAME, PENDING_FRAME, type Frame } from "@/cut/lib/composite";+import { hdrCanvasSupport } from "@/cut/lib/hdrCanvas";+import { displayIsHdr, HdrPresenter, onDisplayRangeChange, setHdrPreviewState } from "@/cut/lib/hdrPresent";import { crossHandles, duckGainAt, overlayPlan, soundCrossGain, trackZeroPlan } from "@/cut/lib/framePlan";import { type ClipFrameSource, FrameSourcePool, mappingKey, walkCostMs } from "@/cut/lib/frameSource";import { liveAudioFxAt } from "@/cut/lib/audioEffects";@@ -33,9 +35,11 @@ import {markTick,tracing,} from "@/cut/lib/perfTrace";-import { registerSourceSampler } from "@/cut/lib/previewCanvas";+import { registerSourceColor, registerSourceSampler } from "@/cut/lib/previewCanvas";+import { colorRead, previewFile, type ColorRead } from "@/cut/lib/sourceColor";import { backdropStill } from "@/cut/lib/backdropStills";import { createRasterCanvas, type RasterSurface } from "@/cut/lib/raster";+import { disposeDetailGpu } from "@/cut/lib/detailGpu";/*** The preview engine.@@ -114,6 +118,14 @@ const PLAY_SETTLE_MS = 6_000;const keyOf = (clip: VideoClip, asset: MediaAsset) =>mappingKey(asset.id, retimeOf(clip), clip.start);+/** Assets by id, built once per assets array. */+const assetIndexes = new WeakMap<readonly MediaAsset[], Map<string, MediaAsset>>();+function assetIndex(assets: readonly MediaAsset[]): Map<string, MediaAsset> {+ let index = assetIndexes.get(assets);+ if (!index) assetIndexes.set(assets, (index = new Map(assets.map((a) => [a.id, a]))));+ return index;+}+/*** Which way a clip's source is read at this moment: playing, a reversed clip* reads down its source; paused, the reader's own direction along the@@ -241,10 +253,30 @@ class Engine {private unwatch: () => void;private sizeWatch: MutationObserver;private onHidden: () => void;+ private unwatchDisplay: () => void;++ /** The HDR present pass over the composite, once the browser has handed+ * over an extended-range canvas; null until then and where it cannot. */+ private presenter: HdrPresenter | null = null;+ /** Whether the presenter is still being made — a project that turns HDR+ * later asks once. */+ private presenting = false;+ /** Whether the browser hands over an extended-range canvas: unknown until+ * the first HDR frame asks, so an SDR project never probes the GPU. */+ private canPresent: boolean | null = null;- constructor(private canvas: HTMLCanvasElement) {+ constructor(+ private canvas: HTMLCanvasElement,+ /** The extended-range canvas over the stage the HDR picture lands on. */+ private presentCanvas: HTMLCanvasElement | null+ ) {this.comp = new FrameCompositor(canvas);this.comp.removalMatteProvider = (clip, at) => this.matteFor(clip, at);+ // A clip's color recipe describes the frames its source hands over — the+ // file that source reads, read the way it reads it; a LUT built off the+ // thread repaints when it lands.+ this.comp.sourceProvider = (clip) => this.colorOf(clip)?.recipe() ?? { profile: "rec709" };+ this.comp.wake = () => this.wake();// A backdrop still decodes out of band; the frame that finds it missing// draws without it and the landing repaints.this.comp.backdropImageProvider = (assetId) =>@@ -281,10 +313,55 @@ class Engine {this.wake();};document.addEventListener("visibilitychange", this.onHidden);+ // A window dragged onto or off an HDR display changes what the stage can+ // show; the answer is read per frame and the change wakes a repaint.+ this.unwatchDisplay = onDisplayRangeChange(() => this.wake());engineLog(`engine ${this.serial} constructed`);this.wake();}+ /**+ * Whether this frame draws the HDR picture: the project delivers HDR, the+ * display carries it, and the extended-range canvas is in hand. The+ * presenter is made on the first HDR frame asked for, off the loop; until+ * it lands the stage shows the grade rendered as SDR.+ */+ private hdrFrame(colorSpace: string): boolean {+ if (colorSpace === "sdr" || !this.presentCanvas || !displayIsHdr()) return false;+ if (this.canPresent === null) {+ if (!this.presenting) {+ this.presenting = true;+ void hdrCanvasSupport().then((support) => {+ this.presenting = false;+ if (this.disposed) return;+ this.canPresent = support.webgpu;+ this.wake();+ });+ }+ return false;+ }+ if (!this.canPresent) return false;+ if (this.presenter?.gone) {+ this.presenter.dispose();+ this.presenter = null;+ }+ if (this.presenter) return true;+ if (!this.presenting) {+ this.presenting = true;+ void HdrPresenter.create(this.presentCanvas).then((p) => {+ this.presenting = false;+ if (this.disposed) {+ p?.dispose();+ return;+ }+ if (p) this.presenter = p;+ else this.canPresent = false;+ this.wake();+ });+ }+ return false;+ }+dispose() {engineLog(`engine ${this.serial} disposed`);flushMeter();@@ -294,9 +371,14 @@ class Engine {this.unwatch();this.sizeWatch.disconnect();document.removeEventListener("visibilitychange", this.onHidden);+ this.unwatchDisplay();+ this.presenter?.dispose();+ this.presenter = null;+ setHdrPreviewState("off");this.pool.dispose();this.behind.dispose();this.mixer.dispose();+ disposeDetailGpu();}/**@@ -393,6 +475,15 @@ class Engine {];}+ /** How the clip's frames are read: the frame its open source last handed+ * out, else the file the preview would open for it. */+ colorOf(clip: VideoClip): ColorRead | null {+ const asset = assetIndex(useEditor.getState().assets).get(clip.assetId);+ if (!asset) return null;+ const src = this.pool.peek(keyOf(clip, asset), this.decodeHeight());+ return src ? src.shownColorRead : colorRead(asset, previewFile(asset));+ }+/** The clip's raw, ungraded decoder frame for analysis (the color panel's* Auto), or null when nothing has been decoded for it. */sourceFor(clipId: string): CanvasImageSource | null {@@ -495,7 +586,7 @@ class Engine {if (metering()) meterFrame(lag, !frame);}if (frame)- return { kind: "ready", image: frame.image, width: frame.width, height: frame.height };+ return { kind: "ready", image: frame.image, width: frame.width, height: frame.height, source: frame.read?.recipe() };return src.failed ? MISSING_FRAME : PENDING_FRAME;}@@ -528,7 +619,7 @@ class Engine {if (oldest !== undefined) this.smoothed.delete(oldest);}blendInto(canvas, pair.a.image, pair.b.image, w);- return { image: canvas as CanvasImageSource, width, height, timestamp: pair.a.timestamp };+ return { image: canvas as CanvasImageSource, width, height, timestamp: pair.a.timestamp, read: pair.a.read };}/** Open and start the decoders for clips about to arrive — on track 0 and@@ -752,7 +843,7 @@ class Engine {src.want(b.at, false);const f = src.frameAt(b.at, b.span.clip.in, b.span.clip.out);this.comp.drawLayer(- f ? { kind: "ready", image: f.image, width: f.width, height: f.height } : PENDING_FRAME,+ f ? { kind: "ready", image: f.image, width: f.width, height: f.height, source: f.read?.recipe() } : PENDING_FRAME,b.span.clip,false,1,@@ -843,6 +934,12 @@ class Engine {// and every letterbox below paints it, so a cut with no footage at all// still plays a picture.this.comp.background = s.background;+ // An HDR project composites in HLG, the space its export composites in,+ // and the present pass decodes that for the display; without the+ // display or the canvas for it, the same grade renders as SDR.+ const hdr = this.hdrFrame(s.colorSpace);+ this.comp.output = hdr ? "hlg" : "sdr";+ setHdrPreviewState(s.colorSpace === "sdr" ? "off" : hdr ? "hdr" : "sdr");this.comp.removalBypass = s.removalPeek;this.renderPlaying = playing;this.pool.beginFrame();@@ -957,6 +1054,9 @@ class Engine {// publishes the matte the DOM's front subject-masked elements read.this.comp.subjectMatteProvider = (at) => this.behind.clipMatteOf(this.canvas, at);this.behind.draw(this.canvas, s.overlays, s.assets, t);+ // The HDR picture: the HLG composite decoded onto the extended-range+ // canvas over the stage. One pass, on the frame just drawn.+ if (hdr) this.presenter!.present(this.canvas);// A paused draw is the picture standing still, which is when a// readback of it costs nothing anyone is watching; a play's first// frame is read back once the play stops and the frame is redrawn.@@ -1047,20 +1147,28 @@ class Engine {}}-export function usePlayback(canvasRef: RefObject<HTMLCanvasElement | null>) {+export function usePlayback(+ canvasRef: RefObject<HTMLCanvasElement | null>,+ presentRef?: RefObject<HTMLCanvasElement | null>+) {useEffect(() => {const canvas = canvasRef.current;if (!canvas) return;- const engine = new Engine(canvas);+ const engine = new Engine(canvas, presentRef?.current ?? null);// Dev-only automation hook, like installDevHooks: lets a headless run (or a// debugging session) reach the live engine.if (process.env.NODE_ENV !== "production") {(window as unknown as Record<string, unknown>).__cutDevEngine = engine;}registerSourceSampler((clipId) => engine.sourceFor(clipId));+ registerSourceColor((clipId) => {+ const clip = useEditor.getState().clips.find((c) => c.id === clipId);+ return clip ? engine.colorOf(clip) : null;+ });return () => {registerSourceSampler(null);+ registerSourceColor(null);engine.dispose();};- }, [canvasRef]);+ }, [canvasRef, presentRef]);}diff --git a/site/src/cut/lib/aiContext.test.ts b/site/src/cut/lib/aiContext.test.tsindex f3b86c40..bb189b81 100644--- a/site/src/cut/lib/aiContext.test.ts+++ b/site/src/cut/lib/aiContext.test.ts@@ -60,4 +60,29 @@ describe("describeDoc", () => {expect(other.media.some((m) => m.id === "g1")).toBe(false);expect(describeDoc(doc, { fullCues: true }).media.some((m) => m.id === "g1")).toBe(false);});++ test("colour reads as the grading tools take it: source colour, LUT, wheels by name", async () => {+ const doc = richDoc();+ doc.assets[0] = {+ ...doc.assets[0],+ color: { matrix: "bt2020nc", fullRange: false, bitDepth: 10, detected: "apple-log" },+ colorProfile: "rec709",+ };+ doc.clips[1] = {+ ...doc.clips[1],+ grade: { exposure: 4, fade: 10, lut: { id: "lut:abc", amount: 0.5 }, wheels: { s: [1, 2, 0], o: [0, 0, 3] } },+ };+ const assets = doc.assets.map((a) => ({ ...a, url: "" }));+ await useEditor.getState().openProjectDoc("colour", doc, assets);+ const live = buildAiContext({ chatId: null });+ expect(live.media[0]).toMatchObject({ sourceColor: { profile: "rec709", detected: "apple-log" } });+ expect(live.videoTrack[1]).toMatchObject({+ lut: { id: "lut:abc", amount: 0.5 },+ grade: { exposure: 4, fade: 10 },+ wheels: ["lift", "offset"],+ });+ expect(Array.isArray(live.luts)).toBe(true);+ expect(Array.isArray(live.savedGrades)).toBe(true);+ expect(describeDoc(doc).media[0]).toMatchObject({ sourceColor: { profile: "rec709", detected: "apple-log" } });+ });});diff --git a/site/src/cut/lib/aiContext.ts b/site/src/cut/lib/aiContext.tsindex 2f37697f..0bde2640 100644--- a/site/src/cut/lib/aiContext.ts+++ b/site/src/cut/lib/aiContext.ts@@ -1,8 +1,9 @@"use client";import { formatBytes } from "@/lib/bytes";+import { isLinkedAssetType } from "./types";import { GUIDE_PRESETS, guideFits, guideGeometry, safeAreaOf, sanitizeGuideLines, sanitizeGuides, type GuideId, type GuideLines } from "./guides";-import { hasOverlayAnim, retimeOf, speedCurveOf, type ClipSound, type SpeedNode } from "@donkeycut/effects-kit";+import { hasOverlayAnim, retimeOf, speedCurveOf, WHEEL_LABELS, WHEEL_ZONES, type ClipSound, type OutputSpace, type SpeedNode } from "@donkeycut/effects-kit";import { chatOwner } from "./chatAssets";import { useGenerate } from "./generate";import { useMatteBakes } from "./removal/bakeJobs";@@ -12,7 +13,9 @@ import { playheadAt, skimAt } from "./playhead";import { cueWordCount } from "./cueChunk";import { laneCues, subtitleLaneCount } from "./subtitles";import { watchSweepActive } from "./watch/sweep";-import { libraryFontId, listLibraryFonts } from "./linkedLibrary";+import { libraryFontId, libraryLutId, listLibraryFonts, listLibraryLuts } from "./linkedLibrary";+import { savedGradesKnown } from "./gradePresets";+import { sourceProfileOf } from "./baseFrame";import {clipZoom,frameOf,@@ -45,9 +48,10 @@ function transitionToNext(sp: ClipSpan, index: number, spans: ClipSpan[]) {}/** The clip's own effects — entrance/exit animations, box styling, and its- * color state in the shape the grading tools take: the preset ref plus a- * compact summary of the manual grade (nonzero sliders verbatim; curves and- * wheels as presence flags; the touched hue bands by name). */+ * color state in the shape the grading tools take: the LUT and the preset+ * refs plus a compact summary of the manual grade (nonzero sliders verbatim;+ * curves as presence flags; the wheels by their tool names; the touched hue+ * bands by name). */function clipEffects(clip: VideoClip, live: boolean) {const grade = clip.grade;const sliders: Record<string, number> = {};@@ -56,6 +60,7 @@ function clipEffects(clip: VideoClip, live: boolean) {}const color = grade? {+ ...(grade.lut ? { lut: { id: grade.lut.id, amount: r(grade.lut.amount ?? 1) } } : {}),...(grade.preset? {colorPreset: {@@ -67,7 +72,9 @@ function clipEffects(clip: VideoClip, live: boolean) {: {}),...(Object.keys(sliders).length ? { grade: sliders } : {}),...(grade.curves ? { curves: Object.keys(grade.curves) } : {}),- ...(grade.wheels ? { wheels: Object.keys(grade.wheels) } : {}),+ ...(grade.wheels+ ? { wheels: WHEEL_ZONES.filter((z) => grade.wheels?.[z]).map((z) => WHEEL_LABELS[z].toLowerCase()) }+ : {}),...(grade.hsl ? { hslBands: Object.keys(grade.hsl) } : {}),}: {};@@ -223,6 +230,10 @@ export function buildAiContext(opts?: { fullCues?: boolean; chatId?: string | nu.filter((a) => a.type === "font").map((a) => ({ id: uploadedFontId(a.id), label: a.name })),],+ // The LUT files in the Library, by the id set_color_lut takes, and the+ // grades saved there by name for apply_saved_grade.+ luts: listLibraryLuts().map((l) => ({ id: libraryLutId(l.key), label: l.label })),+ savedGrades: savedGradesKnown().map((g) => ({ id: g.id, name: g.name })),...(core.mediaFolders ? { mediaFolders: core.mediaFolders } : {}),media: core.media,mediaTruncated: core.mediaTruncated,@@ -290,6 +301,7 @@ export function describeDoc(doc: ProjectDoc, opts?: { fullCues?: boolean; chatIdsubtitleStatus: state.subtitles.cues.length > 0 ? "ready" : "idle",aspect: state.aspect ?? "9:16",background: state.background,+ colorSpace: state.colorSpace,guides: sanitizeGuides(doc.guides),guideLines: sanitizeGuideLines(doc.guideLines),genvideo: doc.genvideo ?? undefined,@@ -316,6 +328,7 @@ interface DescribedState {subtitleStatus: string;aspect: Aspect;background: string;+ colorSpace: OutputSpace;guides: GuideId[];guideLines: GuideLines;genvideo?: VideoProject | null;@@ -351,7 +364,7 @@ function describeState(hiddenFromChat(a, chatId, placed);// A font asset is a typeface, not footage: it is listed under `fonts` with// the account's shelf fonts, where a font id is what the model needs.- const visibleAssets = s.assets.filter((a) => a.type !== "font" && !ownedByOtherChat(a));+ const visibleAssets = s.assets.filter((a) => !isLinkedAssetType(a.type) && !ownedByOtherChat(a));// The cap trims the tail of a huge media list, and a source someone has// watched and written up stays regardless of where it sits: the record is// what later decisions are made from.@@ -380,6 +393,9 @@ function describeState(aspect: s.aspect,frame: `${frameOf(s.aspect).w}x${frameOf(s.aspect).h}`,background: s.background,+ // The delivery's color space (set_project_color): sdr, or hlg / pq+ // for an HDR export and an HDR preview where the display carries it.+ colorSpace: s.colorSpace,// Every guide preset's safe area for this frame, whether or not it// shows, so placement can respect a platform's UI without a guide on:// safeArea and keepOut are frame fractions (x, y, w, h).@@ -426,6 +442,17 @@ function describeState(duration: r(a.duration),...(a.origin ? { origin: a.origin } : {}),...(a.folderId != null ? { folderId: a.folderId } : {}),+ // What the file's code values mean, for footage that is not plain+ // Rec.709: the profile in force and, when the person overrode it, what+ // the header read (set_source_color changes it).+ ...(sourceProfileOf(a) !== "rec709" || (a.color && a.color.detected !== "rec709")+ ? {+ sourceColor: {+ profile: sourceProfileOf(a),+ ...(a.color && a.colorProfile && a.colorProfile !== a.color.detected ? { detected: a.color.detected } : {}),+ },+ }+ : {}),// Source spans whose frame map exists (persisted with the project):// distinct-moment times and cut candidates recorded by an earlier watch// or by the background sweep. The map aims a watch — it is not seendiff --git a/site/src/cut/lib/aiTools.ts b/site/src/cut/lib/aiTools.tsindex 0274bf24..d0649c73 100644--- a/site/src/cut/lib/aiTools.ts+++ b/site/src/cut/lib/aiTools.ts@@ -26,14 +26,20 @@ import { DONKEYCUT_CANONICAL } from "@/cut/lib/hosts";import { GUIDE_IDS, guideFits, guidePreset, isGuideId, safeAreaOf, sanitizeGuideLines, type GuideId } from "./guides";import { textSpots } from "./textPlace";import {+ OUTPUT_SPACES,ALL_EFFECT_IDS,autoGradeFromImageData,colorStatsFromImageData,GRADE_BASIC_FIELDS,+ GRADE_DETAIL_FIELDS,GRADE_PRESETS,HSL_BANDS,matchGrade,normalizeGrade,+ SOURCE_PROFILES,+ WHEEL_LABELS,+ WHEEL_ZONES,+ type SourceProfile,normalizeSound,retimeOf,semanticMasterCurve,@@ -165,7 +171,10 @@ import { parseProjectLink } from "./projectLink";import { landReferenceAssets as landReferenceAssetsInto, openReference, referenceMediaUrl, type LandedAsset, type ReferenceProject } from "./projectReference";import { clampLayersToAssets, mediaTypeFits, templateFromDoc } from "./projectTemplate";import { isSoundPresetTemplate, listSoundPresets, saveSoundPreset } from "./soundPresets";+import { isGradePresetTemplate, listSavedGrades, saveGradePreset } from "./gradePresets";import { isStylePresetTemplate } from "./stylePresets";+import { libraryLutId, listLibraryLuts } from "./linkedLibrary";+import { sampleClipBaseFrameData, sourceProfileOf, toBaseRendering } from "./baseFrame";import { applyOverlayPatchSettled, clipLen, track0Clips, laneGapAt, getClipSpans, overlayLaneOrder, overlayLayers, parkedTransitions, projectDuration, resolveTransitions, totalDuration, useEditor } from "./store";import { playheadAt } from "./playhead";import { renderProjectFrame, renderProjectFrames } from "./exportRender";@@ -173,7 +182,6 @@ import { framesAt, readMediaFileSize } from "./mediaRead";import { renderStageFrame, storeStageStill } from "./stageFrame";import { createRasterCanvas, decodeRasterImageUrl, rasterCanvasToDataUrl } from "./raster";import { buildAiContext, describeDoc, hiddenFromChat, placedAssetIds } from "./aiContext";-import { sampleClipFrameData } from "./previewCanvas";import { CAPTION_STYLES, laneCues, subtitleLaneCount } from "./subtitles";import { findHighlights } from "./highlights";import { fuseTimeline, renderFusedTimeline, speechOnsets, speechOver } from "./watch/fuse";@@ -349,19 +357,25 @@ const ANIM_STYLE_SYNONYMS: Record<string, AnimStyle> = {wipedown: "slidedown",};-/** The basic sliders the grade tool patches — the panel's field list plus the- * legacy pair, so the schema and handler can never disagree. */-const GRADE_KEYS = [...GRADE_BASIC_FIELDS.map((f) => f.key), "brightness", "hue"] as const;--/** Color stats for a grading reference: a clip's current decoded frame- * (pre-grade, like Auto reads) or an image asset's pixels. */+/** The sliders the grade tool patches — the panel's basic and detail lists+ * plus the legacy pair, so the schema and handler can never disagree. */+const GRADE_KEYS = [+ ...GRADE_BASIC_FIELDS.map((f) => f.key),+ ...GRADE_DETAIL_FIELDS.map((f) => f.key),+ "brightness",+ "hue",+] as const;++/** Color stats for a grading reference: a clip's current frame as the base+ * rendering (through the source conversion, before any grade — what Auto+ * reads) or an image asset's pixels. */async function colorStatsForRef(s: ReturnType<typeof useEditor.getState>,ref: { clipId?: string; assetId?: string }): Promise<ColorStats> {if (ref.clipId) {const clip = requireItem(s.clips, ref.clipId, "video clip");- const data = sampleClipFrameData(clip.id, 192, 108);+ const data = sampleClipBaseFrameData(clip.id, 192, 108);if (!data)throw new ToolError("No decoded frame for that clip yet — seek into it so it is on screen, then retry."@@ -384,7 +398,8 @@ async function colorStatsForRef(const ctx = c.getContext("2d") as CanvasRenderingContext2D | null;if (!ctx) throw new ToolError("Could not read that image's pixels.");ctx.drawImage(img.source, 0, 0, w, h);- const stats = colorStatsFromImageData(ctx.getImageData(0, 0, w, h).data);+ // A still cut from log footage carries its source's profile.+ const stats = colorStatsFromImageData(toBaseRendering(ctx.getImageData(0, 0, w, h).data, sourceProfileOf(asset)));if (!stats) throw new ToolError("Could not read pixels off that image.");return stats;}@@ -3000,6 +3015,11 @@ const toolRuns: Record<BrowserToolName, ToolRun> = {...body,url: await storedMediaUrl(projectId, body.fileName),origin: "freeze",+ // A frame grabbed off the source keeps its code values, so the still+ // carries the source's profile and draws through the same conversion;+ // a stage render is already the finished picture.+ ...(input.with_elements !== true && span.asset.color ? { color: span.asset.color } : {}),+ ...(input.with_elements !== true && span.asset.colorProfile ? { colorProfile: span.asset.colorProfile } : {}),};const cur = useEditor.getState();cur.addAsset(asset);@@ -3750,7 +3770,7 @@ const toolRuns: Record<BrowserToolName, ToolRun> = {...(a.origin ? { origin: a.origin } : {}),})),templates: lib.templates- .filter((t) => !isSoundPresetTemplate(t) && !isStylePresetTemplate(t))+ .filter((t) => !isSoundPresetTemplate(t) && !isStylePresetTemplate(t) && !isGradePresetTemplate(t)).map((t) => ({id: t.id,name: t.name,@@ -4561,16 +4581,16 @@ const toolRuns: Record<BrowserToolName, ToolRun> = {set_color_grade: (s, input) => {const clip = requireItem(s.clips, input.clipId, "video clip");- // reset and auto rebuild the manual layer; the preset layer stays.+ // reset and auto rebuild the manual layer; the preset and LUT stay.let grade: ColorGrade =- input.reset === true ? { preset: clip.grade?.preset } : { ...clip.grade };+ input.reset === true ? { preset: clip.grade?.preset, lut: clip.grade?.lut } : { ...clip.grade };if (input.auto === true) {- const data = sampleClipFrameData(clip.id);+ const data = sampleClipBaseFrameData(clip.id);if (!data)throw new ToolError("No decoded frame for that clip yet — seek into it so it is on screen, then retry.");- grade = { ...autoGradeFromImageData(data), preset: clip.grade?.preset };+ grade = { ...autoGradeFromImageData(data), preset: clip.grade?.preset, lut: clip.grade?.lut };}for (const k of GRADE_KEYS) if (isNum(input[k])) grade[k] = input[k];s.updateClip(clip.id, { grade: normalizeGrade(grade) });@@ -4617,11 +4637,8 @@ const toolRuns: Record<BrowserToolName, ToolRun> = {if (pts.length === 0) delete curves[ch];else curves[ch] = pts as CurvePoint[];}- if (isNum(input.curve_contrast) || isNum(input.fade)) {- const master = semanticMasterCurve(- isNum(input.curve_contrast) ? input.curve_contrast : 0,- isNum(input.fade) ? input.fade : 0- );+ if (isNum(input.curve_contrast)) {+ const master = semanticMasterCurve(input.curve_contrast, 0);if (master) curves.m = master;else delete curves.m;}@@ -4633,12 +4650,12 @@ const toolRuns: Record<BrowserToolName, ToolRun> = {set_color_wheels: (s, input) => {const clip = requireItem(s.clips, input.clipId, "video clip");const wheels = input.reset === true ? {} : { ...clip.grade?.wheels };- const zones = [- ["s", input.shadows],- ["m", input.midtones],- ["h", input.highlights],- ] as const;- for (const [zone, w] of zones) {+ // The wheels by their labels (lift, gamma, gain, offset); the older+ // names a thread may still carry map onto the first three.+ const zones = WHEEL_ZONES.map((z) => [z, input[WHEEL_LABELS[z].toLowerCase()]] as const);+ const legacy = { s: input.shadows, m: input.midtones, h: input.highlights } as const;+ for (const [zone, given] of zones) {+ const w = given ?? (legacy as Partial<Record<string, unknown>>)[zone];if (!w || typeof w !== "object") continue;const t = w as { dx?: number; dy?: number; luma?: number };wheels[zone] = [t.dx ?? 0, t.dy ?? 0, t.luma ?? 0] as WheelTuple;@@ -4676,6 +4693,101 @@ const toolRuns: Record<BrowserToolName, ToolRun> = {return statsReport(stats);},+ set_color_lut: (s, input) => {+ const clip = requireItem(s.clips, input.clipId, "video clip");+ const lut = typeof input.lut === "string" ? input.lut.trim() : "";+ const amount = isNum(input.amount) ? Math.max(0, Math.min(1, input.amount)) : clip.grade?.lut?.amount;+ const grade: ColorGrade = { ...clip.grade };+ if (lut === "none") {+ delete grade.lut;+ } else {+ const item = listLibraryLuts().find((l) => libraryLutId(l.key) === lut);+ if (!item)+ throw new ToolError(+ `No LUT "${lut}" in the Library — pass one of editor_state.luts, or "none".`+ );+ grade.lut = { id: lut, amount };+ }+ s.updateClip(clip.id, { grade: normalizeGrade(grade) });+ const next = useEditor.getState().clips.find((c) => c.id === clip.id)!;+ return { id: next.id, lut: next.grade?.lut ?? "none" };+ },++ copy_color_grade: (s, input) => {+ const clip = requireItem(s.clips, input.clipId, "video clip");+ const ids = clipTargets(s, input, clip.id);+ if (ids.length === 0)+ throw new ToolError("Pass ids for the clips to copy onto, or all_clips for every clip.");+ const grade = normalizeGrade(clip.grade);+ s.beginHistoryBatch();+ const landed: string[] = [];+ const failed: { id: string; error: string }[] = [];+ try {+ for (const id of ids) {+ const target = useEditor.getState().clips.find((c) => c.id === id);+ if (!target) {+ failed.push({ id, error: `No video clip "${id}".` });+ continue;+ }+ useEditor.getState().updateClip(id, { grade });+ landed.push(id);+ }+ } finally {+ s.endHistoryBatch();+ }+ if (landed.length === 0)+ throw new ToolError(`None of those ${ids.length} landed: ${failed.map((f) => f.error).join("; ")}`);+ return { from: clip.id, ids: landed, grade: grade ?? "neutral", ...(failed.length ? { failed } : {}) };+ },++ set_source_color: (s, input) => {+ const profile = typeof input.profile === "string" ? input.profile : "";+ if (profile !== "auto" && !SOURCE_PROFILES.some((p) => p.id === profile))+ throw new ToolError(`profile must be one of ${SOURCE_PROFILES.map((p) => p.id).join(", ")}, or "auto".`);+ let assetId = typeof input.assetId === "string" ? input.assetId : "";+ if (!assetId && typeof input.clipId === "string")+ assetId = requireItem(s.clips, input.clipId, "video clip").assetId;+ const asset = requireItem(s.assets, assetId, "project asset");+ if (asset.type !== "video" && asset.type !== "image")+ throw new ToolError("Source color is a picture's setting — pass a video or image asset.");+ const detected = asset.color?.detected ?? "rec709";+ s.setAssetColorProfile(+ asset.id,+ profile === "auto" || profile === detected ? undefined : (profile as SourceProfile)+ );+ const next = useEditor.getState().assets.find((a) => a.id === asset.id)!;+ return {+ assetId: next.id,+ profile: sourceProfileOf(next),+ detected,+ clips: useEditor.getState().clips.filter((c) => c.assetId === next.id).map((c) => c.id),+ };+ },++ save_color_grade: async (s, input) => {+ const clip = requireItem(s.clips, input.clipId, "video clip");+ const name = typeof input.name === "string" ? input.name.trim() : "";+ if (!name) throw new ToolError("name is required.");+ if (!normalizeGrade(clip.grade)) throw new ToolError("That clip's grade is neutral; grade it first.");+ if (!s.projectId) throw new ToolError("No open project.");+ const saved = await saveGradePreset(s.projectId, name, clip.grade);+ if (!saved) throw new ToolError("The grade could not be saved.");+ return { id: saved.id, name: saved.name, residency: saved.residency, grade: saved.grade };+ },++ apply_saved_grade: async (s, input) => {+ const clip = requireItem(s.clips, input.clipId, "video clip");+ const wanted = typeof input.preset_id === "string" ? input.preset_id.trim() : "";+ if (!wanted) throw new ToolError("preset_id is required.");+ const saved = (await listSavedGrades()).find(+ (p) => p.id === wanted || p.name.toLowerCase() === wanted.toLowerCase()+ );+ if (!saved) throw new ToolError(`No saved grade called "${wanted}" — editor_state.savedGrades lists them.`);+ s.updateClip(clip.id, { grade: saved.grade });+ const next = useEditor.getState().clips.find((c) => c.id === clip.id)!;+ return { id: next.id, preset: { id: saved.id, name: saved.name }, grade: next.grade ?? "neutral" };+ },+match_color_grade: async (s, input) => {const clip = requireItem(s.clips, input.clipId, "video clip");const source = await colorStatsForRef(s, { clipId: clip.id });@@ -4764,6 +4876,14 @@ const toolRuns: Record<BrowserToolName, ToolRun> = {s.setProjectName(input.name.trim());return { name: input.name.trim() };},++ set_project_color: (s, input) => {+ const space = OUTPUT_SPACES.find((o) => o.id === input.space);+ if (!space)+ throw new ToolError(`Unknown color space ${String(input.space)} — pick from ${OUTPUT_SPACES.map((o) => o.id).join(", ")}.`);+ s.setColorSpace(space.id);+ return { colorSpace: useEditor.getState().colorSpace };+ },};class ToolError extends Error {}@@ -4859,13 +4979,13 @@ async function dispatchTool(s: Editor, name: string, input: Record<string, unknoconst run = (toolRuns as Partial<Record<string, ToolRun>>)[key];if (!run) throw new ToolError(`Unknown tool: ${name}`);const field = SWEEP_TARGETS[key];- const ids = field ? sweepIds(key, field, input) : null;+ const ids = field ? sweepIds(s, key, field, input) : null;if (!ids) return run(s, input, operation);// A sweep's apply: the same write over every id, as one undo step, with// the live state re-read each time because a write can move or remove the// items after it. A failure on one item is reported and the rest still land.- const rest = Object.fromEntries(Object.entries(input).filter(([k]) => k !== "ids"));+ const rest = Object.fromEntries(Object.entries(input).filter(([k]) => k !== "ids" && k !== "all_clips"));s.beginHistoryBatch();const landed: string[] = [];const ran: unknown[] = [];@@ -4892,7 +5012,13 @@ async function dispatchTool(s: Editor, name: string, input: Record<string, unkno/** The ids a fan-out writes, or null for a one-item call. Every sweepable* tool takes one target or a list, and a call carrying neither reaches no* item at all, so it is refused here rather than in each handler. */-function sweepIds(name: string, field: string, input: Record<string, unknown>): string[] | null {+function sweepIds(s: Editor, name: string, field: string, input: Record<string, unknown>): string[] | null {+ // `all_clips` is the whole video timeline, every track, as the id list.+ if (input.all_clips === true && field === "clipId") {+ const all = s.clips.map((c) => c.id);+ if (all.length === 0) throw new ToolError("The timeline has no clips.");+ return all;+ }const list = Array.isArray(input.ids)? input.ids.filter((x): x is string => typeof x === "string" && x.length > 0): null;@@ -4905,6 +5031,15 @@ function sweepIds(name: string, field: string, input: Record<string, unknown>):return null;}+/** The clips a copy lands on: every other clip for all_clips, else the ids+ * given, the source itself left out. */+function clipTargets(s: Editor, input: Record<string, unknown>, source: string): string[] {+ if (input.all_clips === true) return s.clips.filter((c) => c.id !== source).map((c) => c.id);+ return Array.isArray(input.ids)+ ? input.ids.filter((x): x is string => typeof x === "string" && x.length > 0 && x !== source)+ : [];+}+/** Used inside the existing serialized engine session or isolated cloud worker.* The caller supplies a hydrated project; deterministic commands invoke no model. */export async function runProjectCommand(@@ -5505,6 +5640,12 @@ const SWEEP_TARGETS: Readonly<Record<string, string>> = {set_clip_hidden: "clipId",set_clip_volume: "clipId",set_color_preset: "clipId",+ set_color_grade: "clipId",+ set_color_curves: "clipId",+ set_color_wheels: "clipId",+ set_color_hsl: "clipId",+ set_color_lut: "clipId",+ apply_saved_grade: "clipId",set_speed: "clipId",set_framing: "clipId",set_transition: "clipId",diff --git a/site/src/cut/lib/artifactPolicy.test.ts b/site/src/cut/lib/artifactPolicy.test.tsindex 6969e464..a674a913 100644--- a/site/src/cut/lib/artifactPolicy.test.ts+++ b/site/src/cut/lib/artifactPolicy.test.ts@@ -2,7 +2,7 @@ import { expect, test } from "bun:test";import { artifactLifecycle, artifactUsageBytes } from "./artifactPolicy";test("derived playback and scratch are distinct from retained media", () => {- for (const kind of ["preview", "card", "hls"]) expect(artifactLifecycle(kind)).toBe("derived");+ for (const kind of ["preview", "card", "hls", "proxy"]) expect(artifactLifecycle(kind)).toBe("derived");expect(artifactLifecycle("overlay")).toBe("scratch");for (const kind of ["media", "export", "library"]) expect(artifactLifecycle(kind)).toBe("retained");});diff --git a/site/src/cut/lib/artifactPolicy.ts b/site/src/cut/lib/artifactPolicy.tsindex 352857e1..8457027b 100644--- a/site/src/cut/lib/artifactPolicy.ts+++ b/site/src/cut/lib/artifactPolicy.ts@@ -2,7 +2,7 @@ export type ArtifactLifecycle = "retained" | "derived" | "scratch";/** Derived playback files can be rebuilt from retained project media. */export function artifactLifecycle(kind: string): ArtifactLifecycle {- if (kind === "preview" || kind === "card" || kind === "hls") return "derived";+ if (kind === "preview" || kind === "card" || kind === "hls" || kind === "proxy") return "derived";if (kind === "overlay") return "scratch";return "retained";}diff --git a/site/src/cut/lib/assetDrag.ts b/site/src/cut/lib/assetDrag.tsindex 29ba7b15..ac53475c 100644--- a/site/src/cut/lib/assetDrag.ts+++ b/site/src/cut/lib/assetDrag.ts@@ -85,6 +85,13 @@ export function hasLibraryDrag(e: React.DragEvent | DragEvent): boolean {return !!dt && Array.from(dt.types).includes(LIBRARY_MIME);}+/** The content key of the LUT file a library drag carries, or null when the+ * drag holds anything else. */+export function draggedLutKey(e: React.DragEvent | DragEvent): string | null {+ if (!hasLibraryDrag(e)) return null;+ return inFlightLibrary?.type === "lut" ? inFlightLibrary.contentKey ?? null : null;+}+export function draggedLibraryId(e: React.DragEvent | DragEvent): string | null {const dt = "dataTransfer" in e ? e.dataTransfer : null;if (!dt || !Array.from(dt.types).includes(LIBRARY_MIME)) return null;@@ -276,7 +283,10 @@ export function setCardDragImage(e: React.DragEvent, host: HTMLElement) {* grabbed tile's picture covering it edge to edge — center-cropped to fill,* so no aspect leaves bars. A node marked `data-drag-object="bare"` — a* folder glyph — is the marker itself: fitted whole into the unit, with no- * frame, fill or shadow around it. */+ * frame, fill or shadow around it. A node that also carries+ * `data-drag-ghost="<url>"` rides that picture instead of a clone of itself,+ * fitted whole the same way: a LUT tile wears its wordmark at rest and its+ * bare mark in hand. */const OBJECT_GHOST_UNIT = 48;export function setObjectDragImage(@@ -293,7 +303,8 @@ export function setObjectDragImage(const rect = el.getBoundingClientRect();if (!rect.width || !rect.height) return;const unit = OBJECT_GHOST_UNIT;- const bare = el.dataset.dragObject === "bare";+ const ghostSrc = el.dataset.dragGhost;+ const bare = el.dataset.dragObject === "bare" || !!ghostSrc;const blank = document.createElement("canvas");blank.width = blank.height = 1;@@ -305,8 +316,17 @@ export function setObjectDragImage(const root = document.createElement("div");root.style.cssText ="position:fixed;left:0;top:0;z-index:1000;pointer-events:none;will-change:transform;";- const object = el.cloneNode(true) as HTMLElement;- bakeGhostClone(el, object);+ let object: HTMLElement;+ if (ghostSrc) {+ const img = document.createElement("img");+ img.src = ghostSrc;+ img.alt = "";+ img.style.objectFit = "contain";+ object = img;+ } else {+ object = el.cloneNode(true) as HTMLElement;+ bakeGhostClone(el, object);+ }object.style.width = `${rect.width}px`;object.style.height = `${rect.height}px`;object.style.margin = "0";diff --git a/site/src/cut/lib/assetRef.ts b/site/src/cut/lib/assetRef.tsindex 3df7d3e9..1c3f6342 100644--- a/site/src/cut/lib/assetRef.ts+++ b/site/src/cut/lib/assetRef.ts@@ -4,8 +4,10 @@ import { noteRef, noteIdSchema } from "@/cut/lib/noteReference";import { folderRef, folderReferenceSchema, projectFolderRef, libraryFolderRefs, type FolderReference } from "@/cut/lib/folderReference";import { useCallback, useEffect, useMemo, useRef, useState } from "react";+import { isLinkedAssetType } from "./types";import type React from "react";-import { libraryRouteUrl, type LibraryAsset, type LibraryData } from "./library";+import { libraryAssetName, libraryRouteUrl, type LibraryAsset, type LibraryData } from "./library";+import { libraryLutId, LUT_MARK_ICON } from "./linkedLibrary/luts";import { useLibrary, useNotes } from "./queries";import { stockAspectDims, stockTitle, type StockImage, type StockMusic, type StockSfx, type StockVideo } from "./stock";import { STOCK_IMAGES } from "./stockManifest";@@ -30,6 +32,7 @@ import {type ShapeKind,type TransitionStyle, type LibraryTemplate } from "./types";import type {+ AssetType,AudioClip,MediaAsset,Overlay,@@ -122,15 +125,51 @@ export interface AssetRef {keyTrack?: "pose" | "mask";/** Tiny image the pill shows instead of an icon — the sticker's own art. */preview?: string;+ /** The Library file type a linked item (font, LUT) came from. */+ fileType?: AssetType;+ /** For a Library file chat acts on by id: the tool and the arguments that+ * name it, and what to call it in the model's text. */+ use?: { noun: string; tool: string; args: Record<string, string> };+}++/** How reference menus offer a Library file of each type. "media" rides every+ * menu and reaches the model as the file itself. "chat" rides only chat's+ * menu, next to notes and folders, and reaches the model as the tool call+ * that uses it. "none" stays out. Keyed by every asset type, so a new type+ * does not compile until it says how it is referenced. */+type LibraryMention =+ | { menu: "media" | "none" }+ | { menu: "chat"; noun: string; icon: string; use: (a: LibraryAsset) => { tool: string; args: Record<string, string> } | null };++export const LIBRARY_MENTION: { [T in AssetType]: LibraryMention } = {+ video: { menu: "media" },+ audio: { menu: "media" },+ image: { menu: "media" },+ // A font is used from the font menu, so there is nothing to point a tool at.+ font: { menu: "none" },+ lut: {+ menu: "chat",+ noun: "LUT file",+ icon: LUT_MARK_ICON,+ use: (a) => (a.contentKey ? { tool: "set_color_lut", args: { lut: libraryLutId(a.contentKey) } } : null),+ },+};++/** The chat use of a Library file, when its type is one chat acts on. */+function libraryUse(a: LibraryAsset): Pick<AssetRef, "use" | "preview"> {+ const mention = LIBRARY_MENTION[a.type];+ if (mention.menu !== "chat") return {};+ const use = mention.use(a);+ return use ? { use: { noun: mention.noun, ...use }, preview: mention.icon } : {};}export const refFromAsset = (a: MediaAsset): AssetRef => ({scope: "project",id: a.id,name: a.name,- // Fonts have no card and no drag source, and `projectRefs` keeps them out- // of the @-mention candidates; the arm only keeps the mapping total.- kind: a.type === "font" ? "text" : a.type,+ // Linked kinds have no card and no drag source, and `projectRefs` keeps+ // them out of the @-mention candidates; the arm only keeps the mapping total.+ kind: isLinkedAssetType(a.type) ? "text" : a.type,url: a.url,duration: a.duration,});@@ -138,9 +177,9 @@ export const refFromAsset = (a: MediaAsset): AssetRef => ({export const refFromLibrary = (a: LibraryAsset): AssetRef => ({scope: "library",id: a.id,- name: a.name,- // A font is not media to point a tool at; the mapping only stays total.- kind: a.type === "font" ? "text" : a.type,+ name: a.type === "lut" ? libraryAssetName(a) : a.name,+ // A linked item is no media to point a tool at; the mapping only stays total.+ kind: isLinkedAssetType(a.type) ? "text" : a.type,// A ref outlives the session it was made in — it is saved with the chat// thread — so it carries the shelf route rather than a minted URL that// expires inside the hour.@@ -149,6 +188,8 @@ export const refFromLibrary = (a: LibraryAsset): AssetRef => ({...(a.width !== undefined ? { width: a.width } : {}),...(a.height !== undefined ? { height: a.height } : {}),...(a.posterFile ? { thumb: libraryRouteUrl(a.posterFile, a.residency) } : {}),+ ...(isLinkedAssetType(a.type) ? { fileType: a.type } : {}),+ ...libraryUse(a),});export const refFromStock = (i: StockImage): AssetRef => ({@@ -478,7 +519,7 @@ export function unlistedRefs(assets: MediaAsset[]): AssetRef[] {export function projectRefs(assets: MediaAsset[]): AssetRef[] {const counters = { v: 0, i: 0, a: 0 };return assets- .filter((a) => a.origin !== "chat" && a.origin !== "matte" && a.type !== "font")+ .filter((a) => a.origin !== "chat" && a.origin !== "matte" && !isLinkedAssetType(a.type)).map((a) => {const prefix = a.type === "image" ? "i" : a.type === "video" ? "v" : "a";counters[prefix] += 1;@@ -905,12 +946,16 @@ export function useRefCandidates(enabled = true, includeCollections = false): As...(projectId ? (folders ?? []).map((f) => projectFolderRef(f, projectId)) : []),...libraryFolderRefs(lib.folders),...(notes?.notes ?? []).map(noteRef),+ ...lib.assets+ .filter((a) => LIBRARY_MENTION[a.type].menu === "chat")+ .map(refFromLibrary)+ .filter((r) => r.use),];const counts = new Map<string, number>();for (const ref of refs) counts.set(ref.name.toLowerCase(), (counts.get(ref.name.toLowerCase()) ?? 0) + 1);return refs.map((ref) => (counts.get(ref.name.toLowerCase()) ?? 0) > 1? { ...ref, name: `${ref.name} [${ref.id}]` } : ref);- }, [includeCollections, projectId, folders, lib.folders, notes]);+ }, [includeCollections, projectId, folders, lib.folders, lib.assets, notes]);return useMemo(() => {if (!assets || !clips || !audioClips || !overlays || !transitions || !subtitles || !projectTemplates) return [];@@ -937,9 +982,7 @@ export function refCandidatesOf(...entityRefs({ clips, assets, overlays, transitions, subtitles }),...project,...templates.map(refFromTemplate),- // A font is used from the font menu, so there is nothing to point a tool- // at; library fonts stay out of the candidates the way project fonts do.- ...lib.assets.filter((a) => a.type !== "font").map(refFromLibrary),+ ...lib.assets.filter((a) => LIBRARY_MENTION[a.type].menu === "media").map(refFromLibrary),...lib.templates.map(refFromTemplate),...STOCK_IMAGES.map(refFromStock),...STOCK_VIDEOS.map(refFromStockVideo),diff --git a/site/src/cut/lib/assetWrites.test.ts b/site/src/cut/lib/assetWrites.test.tsnew file mode 100644index 00000000..990e3c06--- /dev/null+++ b/site/src/cut/lib/assetWrites.test.ts@@ -0,0 +1,132 @@+import { expect, test } from "bun:test";+import { patchIsNoop, useEditor } from "./store";+import type { MediaAsset } from "./types";++const COLOR = { matrix: "bt709", fullRange: false, bitDepth: 8, detected: "rec709", codec: "avc1" } as const;+const asset: MediaAsset = {+ id: "a",+ fileName: "a.mp4",+ name: "a",+ type: "video",+ duration: 4,+ width: 3840,+ height: 2160,+ url: "https://media.test/a.mp4",+ color: { ...COLOR },+};++test("a patch that restates the asset changes nothing", () => {+ expect(patchIsNoop(asset, { width: 3840, height: 2160, color: { ...COLOR } })).toBe(true);+ expect(patchIsNoop(asset, { color: { ...COLOR, fullRange: true } })).toBe(false);+ expect(patchIsNoop(asset, { width: 1920 })).toBe(false);+ // Lists are new pictures whenever they are new arrays.+ expect(patchIsNoop({ ...asset, thumbs: ["x"] }, { thumbs: ["x"] })).toBe(false);+});++test("an asset write that changes nothing wakes nobody", () => {+ useEditor.setState({ assets: [asset], readOnly: false });+ let writes = 0;+ const stop = useEditor.subscribe(() => writes++);+ try {+ // Two probes of the same file land the same answer: one write at most.+ useEditor.getState().updateAsset("a", { width: 3840, height: 2160, color: { ...COLOR } });+ expect(writes).toBe(0);+ useEditor.getState().updateAsset("a", { color: { ...COLOR, detected: "srgb" } });+ expect(writes).toBe(1);+ } finally {+ stop();+ }+});++test("a probe write that leaves the picture alone waits for the play to stop", async () => {+ const { landProbedFacts } = await import("./media");+ const bare = { ...asset, id: "b", color: undefined };+ useEditor.setState({ assets: [bare], readOnly: false, playing: true });+ // A Rec.709 record draws what the unprobed asset already draws.+ const landed = landProbedFacts("b", { width: 3840, height: 2160, color: { ...COLOR } });+ await new Promise((r) => setTimeout(r, 10));+ expect(useEditor.getState().assets[0].color).toBeUndefined();+ useEditor.setState({ playing: false });+ await landed;+ expect(useEditor.getState().assets[0].color).toEqual({ ...COLOR });+});++test("a probe write that changes the picture lands mid-play", async () => {+ const { landProbedFacts } = await import("./media");+ const bare = { ...asset, id: "c", color: undefined };+ useEditor.setState({ assets: [bare], readOnly: false, playing: true });+ const hlg = { matrix: "bt2020nc", fullRange: false, bitDepth: 10, detected: "hlg", codec: "hvc1" } as const;+ await landProbedFacts("c", { color: { ...hlg } });+ expect(useEditor.getState().assets[0].color).toEqual({ ...hlg });+ useEditor.setState({ playing: false });+});++test("a profile override set while a probe write waits for the play survives it", async () => {+ const { landProbedFacts } = await import("./media");+ const bare = { ...asset, id: "d", color: undefined };+ useEditor.setState({ assets: [bare], readOnly: false, playing: true });+ const landed = landProbedFacts("d", { width: 3840, height: 2160, color: { ...COLOR } });+ await new Promise((r) => setTimeout(r, 10));+ useEditor.getState().setAssetColorProfile("d", "apple-log-2");+ useEditor.setState({ playing: false });+ await landed;+ expect(useEditor.getState().assets[0].color).toEqual({ ...COLOR });+ expect(useEditor.getState().assets[0].colorProfile).toBe("apple-log-2");+});++test("a slow import probe lands under the profile the person set first", async () => {+ const { landProbedFacts } = await import("./media");+ const bare = { ...asset, id: "e", color: undefined };+ useEditor.setState({ assets: [bare], readOnly: false, playing: true });+ // Set on the asset before the header walk came back, as an importRemote or+ // registerLandedAsset probe does behind the placement.+ useEditor.getState().setAssetColorProfile("e", "apple-log");+ const hlg = { matrix: "bt2020nc", fullRange: false, bitDepth: 10, detected: "hlg", codec: "hvc1" } as const;+ await landProbedFacts("e", { color: { ...hlg } });+ expect(useEditor.getState().assets[0].color).toEqual({ ...hlg });+ expect(useEditor.getState().assets[0].colorProfile).toBe("apple-log");+ useEditor.setState({ playing: false });+});++test("whether a probe changes the picture is read with the override in place", async () => {+ const { probeChangesPicture } = await import("./media");+ const overridden: MediaAsset = { ...asset, color: { ...COLOR }, colorProfile: "apple-log-2" };+ // The header's profile guess changes nothing the override already decides.+ expect(probeChangesPicture(overridden, { color: { ...COLOR, detected: "hlg" } })).toBe(false);+ expect(probeChangesPicture(overridden, { color: { ...COLOR, fullRange: true } })).toBe(true);+});++test("a profile override on media never read leaves the header facts to the probe, and undo restores the asset exactly", async () => {+ const { landProbedFacts } = await import("./media");+ const { lacksColor } = await import("./colorProbe");+ const { sourceProfileOf } = await import("./sourceColor");+ const bare: MediaAsset = { ...asset, id: "f" };+ delete bare.color;+ useEditor.setState({ assets: [bare], readOnly: false, playing: false });+ useEditor.getState().setAssetColorProfile("f", "apple-log");+ const set = useEditor.getState().assets[0];+ expect(set.color).toBeUndefined();+ expect(set.colorProfile).toBe("apple-log");+ // The override is no header fact: the header read still runs.+ expect(lacksColor(set)).toBe(true);+ useEditor.getState().undo();+ expect(useEditor.getState().assets[0]).toEqual(bare);+ useEditor.getState().redo();+ const hlg = { matrix: "bt2020nc", fullRange: false, bitDepth: 10, detected: "hlg", codec: "hvc1" } as const;+ await landProbedFacts("f", { color: { ...hlg } });+ const probed = useEditor.getState().assets[0];+ expect(probed.color).toEqual({ ...hlg });+ expect(sourceProfileOf(probed)).toBe("apple-log");+ useEditor.getState().undo();+ expect(useEditor.getState().assets[0]).toEqual({ ...bare, color: { ...hlg } });+});++test("a project saved with the override inside the header record loads it beside the record", async () => {+ const { liftColorProfile, storedAssets } = await import("./store");+ const old = { ...asset, color: { ...COLOR, profile: "hlg" } } as MediaAsset;+ const lifted = liftColorProfile(old);+ expect(lifted.color).toEqual({ ...COLOR });+ expect(lifted.colorProfile).toBe("hlg");+ expect(storedAssets([lifted])[0]).toMatchObject({ color: { ...COLOR }, colorProfile: "hlg" });+ expect(liftColorProfile(asset)).toBe(asset);+});diff --git a/site/src/cut/lib/backend/browser/library.ts b/site/src/cut/lib/backend/browser/library.tsindex 5fedbc9f..f6651c4b 100644--- a/site/src/cut/lib/backend/browser/library.ts+++ b/site/src/cut/lib/backend/browser/library.ts@@ -12,6 +12,7 @@// adopted afterwards (`lib/library.ts`); those paths fall through to the// hosted twin.import { resolveParent, settleParents, subtreeOf } from "../../folderTree";+import { libraryTypeOf } from "../../libraryFileType";import type {AssetType,LibraryTemplate,@@ -53,6 +54,10 @@ type StoredAsset = {/** The source's cover image, stored beside the media and served by the same* route — an import from a site that publishes one carries it. */posterFile?: string;+ /** A linked item's identity, computed by the page before the file was+ * shelved; a LUT's row also says what kind of table it holds. */+ contentKey?: string;+ lut?: { kind: "1d" | "3d" | "shaper+3d"; size: number };};type StoredFolder = {@@ -105,19 +110,6 @@ async function mutateIndex<T>(fn: (idx: LibraryIndex) => T): Promise<T> {});}-const VIDEO_RE = /\.(mp4|mov|m4v|webm|mkv)$/i;-const AUDIO_RE = /\.(mp3|m4a|aac|wav|ogg|flac)$/i;-const IMAGE_RE = /\.(png|jpe?g|webp|gif|avif|bmp)$/i;-const FONT_RE = /\.(ttf|otf|woff2?)$/i;--function typeOf(fileName: string): AssetType | null {- if (VIDEO_RE.test(fileName)) return "video";- if (AUDIO_RE.test(fileName)) return "audio";- if (IMAGE_RE.test(fileName)) return "image";- if (FONT_RE.test(fileName)) return "font";- return null;-}-function parseField<T>(value: FormDataEntryValue | null): T | null {if (typeof value !== "string" || !value) return null;try {@@ -155,20 +147,25 @@ async function list(): Promise<Response> {});}+/** What the page sends alongside a file it has already measured or checked. */+type UploadMeta = {+ type?: AssetType;+ duration?: number;+ width?: number;+ height?: number;+ contentKey?: string;+ lut?: StoredAsset["lut"];+};+/** Write the row for a file already stored in the library. */async function addAsset(fileName: string,name: string,- meta: {- type?: AssetType;- duration?: number;- width?: number;- height?: number;- } | null,+ meta: UploadMeta | null,source?: LibrarySource | null,posterFile?: string,): Promise<StoredAsset> {- const type = meta?.type ?? typeOf(fileName);+ const type = meta?.type ?? libraryTypeOf(fileName);if (!type) throw new Error("Unsupported file type.");const asset: StoredAsset = {id: crypto.randomUUID().slice(0, 8),@@ -183,6 +180,8 @@ async function addAsset(folderId: null,...(source ? { source } : {}),...(posterFile ? { posterFile } : {}),+ ...(typeof meta?.contentKey === "string" ? { contentKey: meta.contentKey } : {}),+ ...(meta?.lut ? { lut: meta.lut } : {}),};await mutateIndex((idx) => {idx.assets.push(asset);@@ -205,14 +204,9 @@ async function upload(req: Request): Promise<Response> {typeof nameField === "string" && nameField.trim()? nameField.trim(): file.name;- const meta = parseField<{- type?: AssetType;- duration?: number;- width?: number;- height?: number;- }>(form.get("meta"));+ const meta = parseField<UploadMeta>(form.get("meta"));const source = parseField<LibrarySource>(form.get("source"));- if (!(meta?.type ?? typeOf(file.name)))+ if (!(meta?.type ?? libraryTypeOf(file.name)))return err("Unsupported file type.", 400);const fileName = await store.saveLibraryMedia(file, file.name);await register(fileName, file);@@ -468,12 +462,13 @@ type TemplateInput = {texts: LibraryTemplate["texts"];cues: LibraryTemplate["cues"];sound?: LibraryTemplate["sound"];+ grade?: LibraryTemplate["grade"];};-/** A template with nothing on it saves nothing; a sound preset is a template- * carrying only its treatment. */+/** A template with nothing on it saves nothing; a sound preset or a saved+ * grade is a template carrying only its treatment. */const templateEmpty = (input: TemplateInput) =>- !input.media?.length && !input.texts?.length && !input.cues?.length && !input.sound;+ !input.media?.length && !input.texts?.length && !input.cues?.length && !input.sound && !input.grade;async function saveTemplate(req: Request): Promise<Response> {try {@@ -501,6 +496,7 @@ async function saveTemplate(req: Request): Promise<Response> {texts: input.texts ?? [],cues: input.cues ?? [],...(input.sound ? { sound: input.sound } : {}),+ ...(input.grade ? { grade: input.grade } : {}),};await mutateIndex((idx) => {idx.templates.push(template);@@ -546,6 +542,7 @@ async function importTemplate(req: Request): Promise<Response> {texts: input.texts ?? [],cues: input.cues ?? [],...(input.sound ? { sound: input.sound } : {}),+ ...(input.grade ? { grade: input.grade } : {}),folderId: input.folderId ?? null,};await mutateIndex((idx) => {diff --git a/site/src/cut/lib/baseFrame.ts b/site/src/cut/lib/baseFrame.tsnew file mode 100644index 00000000..937ea618--- /dev/null+++ b/site/src/cut/lib/baseFrame.ts@@ -0,0 +1,139 @@+"use client";++/**+ * A clip's frame as the base rendering sees it: the decoder's code values put+ * through the source conversion alone — Apple Log, HLG or PQ into Rec.709+ * display values — and nothing of the grade. Analysis (Auto, the chat's+ * colour stats, a match), thumbnails, watch frames and freeze frames read+ * this, so a log clip's numbers and pictures describe what the grade works+ * on, never the flat log encoding. The frames are read the way the preview+ * reads them (sourceColor.ts): tags overridden so the decoder draws code+ * values, and the matrix it drew them through undone first.+ */++import {+ applyLutToImageData,+ buildClipLut,+ drawnColorKey,+ type DrawnColor,+ type GradeLut,+ type SourceProfile,+} from "@donkeycut/effects-kit";+import { frameSink, openMedia, videoTrackOf, type FrameCanvasSink, type FrameSize, type FrameSinkOptions } from "./mediaRead";+import { sampleClipColorRead, sampleClipFrameData } from "./previewCanvas";+import { colorRead, fileAt, previewFile, type ColorRead } from "./sourceColor";+import { useEditor } from "./store";+import type { InputVideoTrack, WrappedCanvas } from "mediabunny";++export { sourceProfileOf } from "./sourceColor";++/** The source conversion for a readout, sampled once per profile and drawn+ * matrix and kept: a 17³ lattice is plenty for quantiles and means. */+const conversions = new Map<string, GradeLut | null>();++function conversionFor(profile: SourceProfile, drawn: Partial<DrawnColor> | undefined): GradeLut | null {+ const key = `${profile}|${drawnColorKey(drawn)}`;+ let lut = conversions.get(key);+ if (lut === undefined) {+ lut = buildClipLut({ profile, output: "sdr", size: 17, ...drawn });+ conversions.set(key, lut);+ }+ return lut;+}++/** Convert raw code values in place into the base rendering. Identity for a+ * Rec.709 or sRGB source drawn through its own matrix. */+export function toBaseRendering(+ px: Uint8ClampedArray,+ profile: SourceProfile,+ drawn?: Partial<DrawnColor>+): Uint8ClampedArray {+ const lut = conversionFor(profile, drawn);+ if (lut) applyLutToImageData(px, lut);+ return px;+}++/** A small RGBA readout of a clip's base rendering; null when the clip has no+ * decoded frame ready. */+export function sampleClipBaseFrameData(clipId: string, w = 96, h = 54): Uint8ClampedArray | null {+ const px = sampleClipFrameData(clipId, w, h);+ if (!px) return null;+ const s = useEditor.getState();+ const clip = s.clips.find((c) => c.id === clipId);+ const asset = clip ? s.assets.find((a) => a.id === clip.assetId) : undefined;+ if (!asset) return toBaseRendering(px, "rec709");+ // The frame came through the engine's read of the clip; convert it the way+ // the compositor does.+ const input = (sampleClipColorRead(clipId) ?? colorRead(asset, previewFile(asset))).recipe();+ return toBaseRendering(px, input.profile, input);+}++/** How the frames at `url` are to be read: the project asset the URL belongs+ * to, and which of its files the URL is. An unknown URL reads as Rec.709. */+export function colorReadAt(url: string): ColorRead {+ const asset = useEditor.getState().assets.find((a) => a.url === url || a.proxyUrl === url);+ return colorRead(asset ?? {}, asset ? fileAt(asset, url) : "master");+}++function convertInPlace(wrapped: WrappedCanvas, profile: SourceProfile, drawn: DrawnColor): WrappedCanvas {+ const canvas = wrapped.canvas;+ const ctx = canvas.getContext("2d") as CanvasRenderingContext2D | null;+ if (!ctx) return wrapped;+ const image = ctx.getImageData(0, 0, canvas.width, canvas.height);+ toBaseRendering(image.data, profile, drawn);+ ctx.putImageData(image, 0, 0);+ return wrapped;+}++/** A sink whose frames are the base rendering of what `read` reads: the+ * plain sink for a Rec.709 or sRGB source, and for any other the override+ * read followed by the source conversion on each frame. The route's drawn+ * matrix is settled before the first frame, so what comes out never depends+ * on timing. */+export function baseFrameSink(+ track: InputVideoTrack,+ size: FrameSize | undefined,+ read: ColorRead,+ opts?: Omit<FrameSinkOptions, "colorSpace">+): FrameCanvasSink {+ const colorSpace = read.colorSpace;+ const sink = frameSink(track, size, { ...opts, ...(colorSpace ? { colorSpace } : {}) });+ const profile = read.recipe().profile;+ if (!colorSpace && (profile === "rec709" || profile === "srgb")) return sink;+ const ready = read.settled();+ const convert = async (frame: WrappedCanvas | null) => (frame ? convertInPlace(frame, profile, await ready) : frame);+ return {+ getCanvas: async (t) => convert(await sink.getCanvas(t)),+ canvases: async function* (start, end) {+ for await (const frame of sink.canvases(start, end)) yield convertInPlace(frame, profile, await ready);+ },+ canvasesAtTimestamps: async function* (times) {+ for await (const frame of sink.canvasesAtTimestamps(times)) yield await convert(frame);+ },+ };+}++/** One base-rendering frame of the file at `url`. */+export async function baseFrameAt(url: string, time: number, size?: FrameSize): Promise<WrappedCanvas | null> {+ const input = openMedia(url);+ try {+ const track = await videoTrackOf(input);+ if (!track) throw new Error("This file has no readable video.");+ return await baseFrameSink(track, size, colorReadAt(url)).getCanvas(Math.max(0, time));+ } finally {+ input.dispose();+ }+}++/** Base-rendering frames at ascending `times`, in one decode pass; null for a+ * time the track has no frame for. */+export async function* baseFramesAt(url: string, times: number[], size?: FrameSize): AsyncGenerator<WrappedCanvas | null> {+ const input = openMedia(url);+ try {+ const track = await videoTrackOf(input);+ if (!track) throw new Error("This file has no readable video.");+ yield* baseFrameSink(track, size, colorReadAt(url)).canvasesAtTimestamps(times);+ } finally {+ input.dispose();+ }+}diff --git a/site/src/cut/lib/cloudJob.ts b/site/src/cut/lib/cloudJob.tsindex fc3dbfb1..91fb3da9 100644--- a/site/src/cut/lib/cloudJob.ts+++ b/site/src/cut/lib/cloudJob.ts@@ -10,13 +10,18 @@ import { apiJson, type CutBackend } from "./backend";* Failure reports what the job itself said, or `fallback`.** `onState` sees every state the job reports ("queued", "running", …), so a- * surface waiting on the job can say which one it is in.+ * surface waiting on the job can say which one it is in; `onProgress` sees+ * the share done as the worker reports it.*/export async function pollCloudJob<T>(jobId: string,backend: CutBackend,fallback: string,- { timedOut = fallback, onState }: { timedOut?: string; onState?: (state: string) => void } = {}+ {+ timedOut = fallback,+ onState,+ onProgress,+ }: { timedOut?: string; onState?: (state: string) => void; onProgress?: (progress: number) => void } = {}): Promise<T> {const deadline = Date.now() + 10 * 60 * 1000;const MAX_STRIKES = 6;@@ -37,8 +42,9 @@ export async function pollCloudJob<T>(continue;}strikes = 0;- const job = await apiJson<{ state?: string; result?: T }>(res);+ const job = await apiJson<{ state?: string; progress?: number; result?: T }>(res);if (job.state) onState?.(job.state);+ if (typeof job.progress === "number") onProgress?.(job.progress);if (job.state === "error") throw new Error(job.error ?? fallback);if (job.state === "done") return (job.result ?? {}) as T;}diff --git a/site/src/cut/lib/colorProbe.test.ts b/site/src/cut/lib/colorProbe.test.tsnew file mode 100644index 00000000..0cedb97d--- /dev/null+++ b/site/src/cut/lib/colorProbe.test.ts@@ -0,0 +1,259 @@+import { describe, expect, test } from "bun:test";+import { DEFAULT_COLOR, probeColor, probeMissingColors, rangeOfBytes } from "./colorProbe";++// Tiny MOV/MP4 builders: enough of the box structure for the probe to walk.++const str = (s: string) => new Uint8Array([...s].map((c) => c.charCodeAt(0)));+const u16 = (n: number) => new Uint8Array([(n >> 8) & 0xff, n & 0xff]);+const u32 = (n: number) => new Uint8Array([(n >>> 24) & 0xff, (n >>> 16) & 0xff, (n >>> 8) & 0xff, n & 0xff]);+const cat = (...parts: Uint8Array[]) => {+ const out = new Uint8Array(parts.reduce((n, p) => n + p.length, 0));+ let at = 0;+ for (const p of parts) {+ out.set(p, at);+ at += p.length;+ }+ return out;+};+const box = (type: string, ...payload: Uint8Array[]) => {+ const body = cat(...payload);+ return cat(u32(8 + body.length), str(type), body);+};+/** A box with a 64-bit size field (a large `mdat`). */+const largeBox = (type: string, body: Uint8Array) =>+ cat(u32(1), str(type), u32(0), u32(16 + body.length), body);+const fullBox = (type: string, ...payload: Uint8Array[]) => box(type, u32(0), ...payload);++const hdlr = (kind: string) => fullBox("hdlr", u32(0), str(kind), new Uint8Array(12), new Uint8Array([0]));++/** A VisualSampleEntry of `format` with 78 bytes of fixed fields, then children. */+const visualEntry = (format: string, ...children: Uint8Array[]) =>+ box(format, new Uint8Array(78), ...children);++const colr = (kind: "nclx" | "nclc", primaries: number, transfer: number, matrix: number, full = false) =>+ box("colr", str(kind), u16(primaries), u16(transfer), u16(matrix), ...(kind === "nclx" ? [new Uint8Array([full ? 0x80 : 0])] : []));++/** hvcC with the given luma bit depth; the other fields are zero. */+const hvcC = (bitDepth: number) => {+ const rec = new Uint8Array(23);+ rec[0] = 1;+ rec[17] = 0xf8 | (bitDepth - 8);+ rec[18] = 0xf8 | (bitDepth - 8);+ return box("hvcC", rec);+};++/** avcC for `profile` with one SPS and one PPS, then the depth fields the+ * high profiles carry. */+const avcC = (profile: number, bitDepth: number) =>+ box(+ "avcC",+ new Uint8Array([1, profile, 0, 40, 0xff, 0xe1]),+ u16(2),+ new Uint8Array([0x67, 0]),+ new Uint8Array([1]),+ u16(2),+ new Uint8Array([0x68, 0]),+ new Uint8Array([0xfd, 0xf8 | (bitDepth - 8), 0xf8 | (bitDepth - 8), 0])+ );++const videoTrak = (entry: Uint8Array) =>+ box("trak", box("mdia", hdlr("vide"), box("minf", box("stbl", fullBox("stsd", u32(1), entry)))));+const audioTrak = () =>+ box("trak", box("mdia", hdlr("soun"), box("minf", box("stbl", fullBox("stsd", u32(1), box("mp4a", new Uint8Array(28)))))));++const movie = (moov: Uint8Array, opts: { mdatFirst?: boolean } = {}) => {+ const ftyp = box("ftyp", str("qt "), u32(0), str("qt "));+ const mdat = largeBox("mdat", new Uint8Array(4096));+ return opts.mdatFirst ? cat(ftyp, mdat, moov) : cat(ftyp, moov, mdat);+};++const probe = (file: Uint8Array) => probeColor(rangeOfBytes(file), file.length);++describe("colorProbe", () => {+ test("Apple Log ProRes: identifier in the movie metadata, 2020 matrix, 10-bit", async () => {+ const moov = box(+ "moov",+ audioTrak(),+ videoTrak(visualEntry("apch", colr("nclc", 9, 18, 9))),+ box("udta", box("meta", box("keys", str("mdtacom.apple.rec2020.apple-log"))))+ );+ expect(await probe(movie(moov))).toEqual({+ code: { matrix: "bt2020nc", fullRange: false, bitDepth: 10 },+ detected: "apple-log",+ codec: "apch",+ });+ });++ test("Apple Log 2 wins over the plain identifier", async () => {+ const moov = box(+ "moov",+ videoTrak(visualEntry("apch", colr("nclc", 9, 18, 9))),+ box("udta", box("logs", str("com.apple.apple-wide-gamut.apple-log")))+ );+ expect((await probe(movie(moov))).detected).toBe("apple-log-2");+ });++ test("the custom-gamma identifier reads as Apple Log", async () => {+ const moov = box(+ "moov",+ videoTrak(visualEntry("apcn", colr("nclc", 9, 18, 9))),+ box("udta", box("meta", str("com.apple.proapps.customgamma")))+ );+ expect((await probe(movie(moov))).detected).toBe("apple-log");+ });++ test("HLG HEVC Main10: transfer 18, nclx full-range flag, hvcC depth", async () => {+ const moov = box("moov", videoTrak(visualEntry("hvc1", colr("nclx", 9, 18, 9, true), hvcC(10))));+ expect(await probe(movie(moov))).toEqual({+ code: { matrix: "bt2020nc", fullRange: true, bitDepth: 10 },+ detected: "hlg",+ codec: "hvc1",+ });+ });++ test("PQ reads as pq, sRGB transfer as srgb", async () => {+ const pq = box("moov", videoTrak(visualEntry("hvc1", colr("nclx", 9, 16, 9), hvcC(10))));+ expect((await probe(movie(pq))).detected).toBe("pq");+ const srgb = box("moov", videoTrak(visualEntry("avc1", colr("nclx", 1, 13, 1), avcC(66, 8))));+ expect((await probe(movie(srgb))).detected).toBe("srgb");+ });++ test("Rec.709 H.264 with a high-profile avcC depth", async () => {+ const moov = box("moov", videoTrak(visualEntry("avc1", colr("nclx", 1, 1, 1), avcC(110, 10))));+ expect(await probe(movie(moov))).toEqual({+ code: { matrix: "bt709", fullRange: false, bitDepth: 10 },+ detected: "rec709",+ codec: "avc1",+ });+ const baseline = box("moov", videoTrak(visualEntry("avc1", colr("nclx", 1, 1, 1), avcC(66, 10))));+ expect((await probe(movie(baseline))).code.bitDepth).toBe(8);+ });++ test("BT.601 matrices map to bt601; no colr means Rec.709", async () => {+ const sd = box("moov", videoTrak(visualEntry("avc1", colr("nclx", 6, 6, 6), avcC(66, 8))));+ expect((await probe(movie(sd))).code.matrix).toBe("bt601");+ const bare = box("moov", videoTrak(visualEntry("avc1", avcC(66, 8))));+ expect(await probe(movie(bare))).toEqual({ ...DEFAULT_COLOR, codec: "avc1" });+ });++ test("moov after a large mdat is reached by skipping the data box", async () => {+ const moov = box("moov", videoTrak(visualEntry("hvc1", colr("nclx", 9, 18, 9), hvcC(10))));+ const file = cat(box("ftyp", str("qt "), u32(0)), largeBox("mdat", new Uint8Array(8 * 2 ** 20)), moov);+ let read = 0;+ const result = await probeColor(async (offset, length) => {+ read += Math.min(length, file.length - offset);+ return file.subarray(offset, offset + length);+ }, file.length);+ expect(result.detected).toBe("hlg");+ // The first block and the file's tail: the data box is never pulled.+ expect(read).toBeLessThan(256 * 1024);+ });++ test("a file that is not MOV/MP4 reads as Rec.709", async () => {+ const webm = cat(new Uint8Array([0x1a, 0x45, 0xdf, 0xa3]), new Uint8Array(512));+ expect(await probe(webm)).toEqual(DEFAULT_COLOR);+ expect(await probe(new Uint8Array(0))).toEqual(DEFAULT_COLOR);+ });++ test("a truncated moov settles on what it holds", async () => {+ const moov = box("moov", videoTrak(visualEntry("hvc1", colr("nclx", 9, 18, 9), hvcC(10))));+ const file = cat(box("ftyp", str("isom"), u32(0)), moov);+ expect(await probe(file.subarray(0, file.length - 3))).toEqual(DEFAULT_COLOR);+ });++ test("the matrix decides HDR: a bt709-matrix file with HLG or PQ tags is Rec.709", async () => {+ // A social app's 8-bit H.264 transcode keeps the phone's 2020/HLG tags+ // and converts through the Rec.709 matrix.+ const social = box("moov", videoTrak(visualEntry("avc1", colr("nclx", 9, 18, 1), avcC(100, 8))));+ expect(await probe(movie(social))).toEqual({+ code: { matrix: "bt709", fullRange: false, bitDepth: 8 },+ detected: "rec709",+ codec: "avc1",+ });+ const pq709 = box("moov", videoTrak(visualEntry("hvc1", colr("nclx", 9, 16, 1), hvcC(10))));+ expect((await probe(movie(pq709))).detected).toBe("rec709");+ });++ test("an unspecified matrix on BT.2020 primaries reads as BT.2020", async () => {+ const moov = box("moov", videoTrak(visualEntry("hvc1", colr("nclx", 9, 18, 2), hvcC(10))));+ expect(await probe(movie(moov))).toEqual({+ code: { matrix: "bt2020nc", fullRange: false, bitDepth: 10 },+ detected: "hlg",+ codec: "hvc1",+ });+ const sdr = box("moov", videoTrak(visualEntry("avc1", colr("nclx", 1, 18, 2), avcC(66, 8))));+ expect((await probe(movie(sdr))).detected).toBe("rec709");+ });++ test("the sample tables are stepped over, never read", async () => {+ // Hours of footage: megabytes of sample sizes and chunk offsets after the+ // sample description, then the movie metadata.+ const tables = new Uint8Array(6 * 2 ** 20).fill(0x61);+ const trak = box(+ "trak",+ box(+ "mdia",+ hdlr("vide"),+ box(+ "minf",+ box(+ "stbl",+ fullBox("stsd", u32(1), visualEntry("apch", colr("nclc", 9, 1, 9))),+ fullBox("stsz", u32(0), tables),+ fullBox("stco", tables.subarray(0, 2 ** 20))+ )+ )+ )+ );+ const moov = box("moov", trak, box("meta", box("keys", str("mdtacom.apple.apple-wide-gamut.apple-log"))));+ const file = movie(moov, { mdatFirst: true });+ let read = 0;+ const result = await probeColor(async (offset, length) => {+ read += Math.min(length, file.length - offset);+ return file.subarray(offset, offset + length);+ }, file.length);+ expect(result.detected).toBe("apple-log-2");+ expect(result.code).toEqual({ matrix: "bt2020nc", fullRange: false, bitDepth: 10 });+ expect(read).toBeLessThan(512 * 1024);+ });++ test("a movie header at the end of the file costs two reads", async () => {+ const moov = box("moov", videoTrak(visualEntry("hvc1", colr("nclx", 9, 18, 9), hvcC(10))));+ const file = cat(box("ftyp", str("qt "), u32(0)), largeBox("mdat", new Uint8Array(3 * 2 ** 20)), moov);+ let reads = 0;+ const result = await probeColor(async (offset, length) => {+ reads++;+ return file.subarray(offset, offset + length);+ }, file.length);+ expect(result.detected).toBe("hlg");+ expect(reads).toBe(2);+ });++ test("a probe of unknown length walks until a read comes back short", async () => {+ const moov = box("moov", videoTrak(visualEntry("hvc1", colr("nclx", 9, 16, 9), hvcC(10))));+ const file = movie(moov, { mdatFirst: true });+ expect((await probeColor(rangeOfBytes(file))).detected).toBe("pq");+ });+});++describe("probeMissingColors", () => {+ const assets = [+ { id: "drawn", type: "video", fileName: "drawn.mp4" },+ { id: "shelf", type: "video", fileName: "shelf.mp4" },+ ];+ const probe = async (a: { fileName: string }) => {+ if (a.fileName === "shelf.mp4") throw new Error("unreadable");+ return DEFAULT_COLOR;+ };++ test("an unreadable file nothing draws is never read", async () => {+ const found = await probeMissingColors(assets, new Set(["drawn"]), probe);+ expect([...found.keys()]).toEqual(["drawn.mp4"]);+ });++ test("an unreadable file the timeline draws fails the call, naming it", async () => {+ await expect(probeMissingColors(assets, new Set(["drawn", "shelf"]), probe)).rejects.toThrow(+ "The color of shelf.mp4 could not be read"+ );+ });+});diff --git a/site/src/cut/lib/colorProbe.ts b/site/src/cut/lib/colorProbe.tsnew file mode 100644index 00000000..8be6578d--- /dev/null+++ b/site/src/cut/lib/colorProbe.ts@@ -0,0 +1,466 @@+/**+ * What color a video file's header says its code values mean.+ *+ * A source's color is settled from its container alone: the sample entry's+ * `colr` atom names the primaries, transfer and matrix and whether the+ * range is full, the codec configuration names the bit depth, and Apple Log+ * footage carries a log identifier string in the movie's metadata. The probe+ * walks the atom tree by their headers and reads the payloads of only the+ * atoms that can carry those: the video track's sample description, and the+ * metadata and user-data atoms of the movie and that track. The sample+ * tables — the bulk of a long movie's header — are stepped over unread. The+ * bytes come in blocks, so a typical file costs two ranged reads and no+ * decode, and the probe runs the same over a dropped File, a URL and a file+ * handle.+ *+ * Anything that is not a MOV/MP4 — a WebM recording, a Matroska file — reads+ * as Rec.709 8-bit limited, which is what such files carry.+ *+ * The matrix decides whether a file is HDR. Social apps transcode phone+ * footage to 8-bit H.264 through the Rec.709 matrix and keep the source's+ * BT.2020 / HLG tags; those files are SDR, so an HLG or PQ transfer reads as+ * HDR only beside a BT.2020 matrix (or an unspecified one on BT.2020+ * primaries).+ */++import type { CodeFormat, SourceProfile } from "@donkeycut/effects-kit";++/** Read `length` bytes at `offset`; fewer come back at the end of the file. */+export type ReadRange = (offset: number, length: number) => Promise<Uint8Array>;++export interface ColorProbe {+ code: CodeFormat;+ /** The profile the header settles on. */+ detected: SourceProfile;+ /** The video sample entry's four-character code (avc1, hvc1, apch, …);+ * "" when the header has no video. */+ codec: string;+}++export const DEFAULT_COLOR: ColorProbe = {+ code: { matrix: "bt709", fullRange: false, bitDepth: 8 },+ detected: "rec709",+ codec: "",+};++/** Bytes fetched per block. The top-level walk usually finds `ftyp`, the+ * data box's header and, in a fast-start file, the whole movie header in the+ * first one. */+const BLOCK = 64 * 1024;+/** A movie header up to this size is fetched in one read as soon as its+ * header is seen; a longer one — hours of footage, megabytes of sample+ * tables — is read block by block, and only where the walk lands. */+const MOOV_PREFETCH = 512 * 1024;+/** The most of any one metadata or sample-description atom scanned for the+ * log identifiers. Those atoms are a few kilobytes; past this the rest is+ * something else (cover art, a thumbnail track). */+const SCAN_MAX = 64 * 1024;+/** Atoms visited before the walk gives up on a malformed file. */+const MAX_ATOMS = 4096;++/** Identifier strings Apple writes into the movie metadata of log footage. */+const APPLE_LOG_2 = "com.apple.apple-wide-gamut.apple-log";+const APPLE_LOG = "com.apple.rec2020.apple-log";+const APPLE_CUSTOM_GAMMA = "com.apple.proapps.customgamma";++const ascii = (b: Uint8Array, at: number) => String.fromCharCode(b[at], b[at + 1], b[at + 2], b[at + 3]);+const u16 = (b: Uint8Array, at: number) => (b[at] << 8) | b[at + 1];+const u32 = (b: Uint8Array, at: number) => ((b[at] << 24) | (b[at + 1] << 16) | (b[at + 2] << 8) | b[at + 3]) >>> 0;+const u64 = (b: Uint8Array, at: number) => u32(b, at) * 2 ** 32 + u32(b, at + 4);++/** Ranged reads through a block cache: every byte is fetched once, in+ * BLOCK-aligned pieces, and a span read back comes out of the cache. */+class Blocks {+ private cache = new Map<number, Promise<Uint8Array>>();+ constructor(+ private read: ReadRange,+ /** The file's length, Infinity when unknown: the end is then wherever a+ * read comes back short. */+ readonly size: number+ ) {}++ /** Fetch `[offset, offset + length)` ahead in one read, into the cache. */+ prefetch(offset: number, length: number): void {+ let first = Math.floor(offset / BLOCK);+ const last = Math.floor((offset + Math.max(1, length) - 1) / BLOCK);+ while (first <= last && this.cache.has(first)) first++;+ if (first > last) return;+ const from = first * BLOCK;+ const whole = this.read(from, (last - first + 1) * BLOCK);+ for (let i = first; i <= last; i++) {+ if (this.cache.has(i)) continue;+ const at = (i - first) * BLOCK;+ const piece = whole.then((b) => b.subarray(Math.min(at, b.length), Math.min(at + BLOCK, b.length)));+ // A prefetched block the walk never reaches must not surface a failed+ // read as unhandled; one it does reach rejects there.+ piece.catch(() => {});+ this.cache.set(i, piece);+ }+ }++ private block(i: number): Promise<Uint8Array> {+ let p = this.cache.get(i);+ if (!p) {+ p = this.read(i * BLOCK, BLOCK);+ this.cache.set(i, p);+ }+ return p;+ }++ /** The bytes of `[offset, offset + length)` that the file holds; fewer at+ * its end. */+ async bytes(offset: number, length: number): Promise<Uint8Array> {+ const end = Math.min(offset + length, this.size);+ if (end <= offset) return new Uint8Array(0);+ const first = Math.floor(offset / BLOCK);+ const last = Math.floor((end - 1) / BLOCK);+ if (first === last) {+ const b = await this.block(first);+ const from = offset - first * BLOCK;+ return b.subarray(Math.min(from, b.length), Math.min(end - first * BLOCK, b.length));+ }+ const out = new Uint8Array(end - offset);+ let filled = 0;+ for (let i = first; i <= last; i++) {+ const b = await this.block(i);+ const from = i === first ? offset - first * BLOCK : 0;+ const to = Math.min(b.length, end - i * BLOCK);+ if (to <= from) break;+ out.set(b.subarray(from, to), filled);+ filled += to - from;+ if (b.length < BLOCK) break;+ }+ return out.subarray(0, filled);+ }+}++interface Atom {+ type: string;+ /** File offset of the payload. */+ start: number;+ /** File offset one past the payload. */+ end: number;+}++/** The atoms of `[from, to)`, read header by header. An atom whose size lies+ * (too small, or running past the span) ends the walk: what follows is not+ * atoms. */+async function* atoms(blocks: Blocks, from: number, to: number, budget: { left: number }): AsyncGenerator<Atom> {+ let at = from;+ while (at + 8 <= to && budget.left-- > 0) {+ const head = await blocks.bytes(at, 16);+ if (head.length < 8) return;+ let size = u32(head, 0);+ let headLen = 8;+ if (size === 1) {+ if (head.length < 16) return;+ size = u64(head, 8);+ headLen = 16;+ } else if (size === 0) {+ size = to - at;+ }+ if (size < headLen || at + size > to) return;+ yield { type: ascii(head, 4), start: at + headLen, end: at + size };+ at += size;+ }+}++async function childAtom(blocks: Blocks, parent: Atom, type: string, budget: { left: number }): Promise<Atom | null> {+ for await (const c of atoms(blocks, parent.start, parent.end, budget)) if (c.type === type) return c;+ return null;+}++/** Whether the byte string `needle` occurs in `hay`. The search is over a+ * metadata atom's bytes — a technical container field. */+function contains(hay: Uint8Array, needle: string): boolean {+ const n = needle.length;+ const first = needle.charCodeAt(0);+ outer: for (let i = 0; i + n <= hay.length; i++) {+ if (hay[i] !== first) continue;+ for (let j = 1; j < n; j++) if (hay[i + j] !== needle.charCodeAt(j)) continue outer;+ return true;+ }+ return false;+}++const MATRIX: Record<number, CodeFormat["matrix"]> = {+ 1: "bt709",+ 5: "bt601",+ 6: "bt601",+ 9: "bt2020nc",+};+/** colr's code for BT.2020 primaries, and for "unspecified". */+const BT2020 = 9;+const UNSPECIFIED = 2;++/** ProRes and other codecs whose depth is the four-character code. */+const CODEC_DEPTH: Record<string, number> = {+ apco: 10,+ apcs: 10,+ apcn: 10,+ apch: 10,+ ap4h: 12,+ ap4x: 12,+};++interface Box {+ type: string;+ /** Offset of the payload inside the buffer. */+ start: number;+ /** Offset one past the payload. */+ end: number;+}++/** Child boxes of the span `[from, to)` of an in-memory buffer. */+function* boxes(b: Uint8Array, from: number, to: number): Generator<Box> {+ let at = from;+ while (at + 8 <= to) {+ let size = u32(b, at);+ let head = 8;+ if (size === 1) {+ if (at + 16 > to) return;+ size = u64(b, at + 8);+ head = 16;+ } else if (size === 0) {+ size = to - at;+ }+ if (size < head || at + size > to) return;+ yield { type: ascii(b, at + 4), start: at + head, end: at + size };+ at += size;+ }+}++function child(b: Uint8Array, box: Box, type: string): Box | null {+ for (const c of boxes(b, box.start, box.end)) if (c.type === type) return c;+ return null;+}++/** Bit depth from the codec configuration record inside a sample entry. */+function bitDepthOf(b: Uint8Array, entry: Box, format: string): number {+ const fixed = CODEC_DEPTH[format];+ if (fixed) return fixed;+ const hvcC = child(b, entry, "hvcC");+ // HEVCDecoderConfigurationRecord: bitDepthLumaMinus8 sits at byte 17.+ if (hvcC && hvcC.end - hvcC.start >= 18) return 8 + (b[hvcC.start + 17] & 0x07);+ const avcC = child(b, entry, "avcC");+ if (avcC) {+ // The depth fields follow the parameter sets, and only for the high+ // profiles (100, 110, 122, 144); the other profiles are 8-bit.+ const profile = b[avcC.start + 1];+ if (![100, 110, 122, 144].includes(profile)) return 8;+ let at = avcC.start + 5;+ const spsCount = b[at++] & 0x1f;+ for (let i = 0; i < spsCount && at + 2 <= avcC.end; i++) at += 2 + u16(b, at);+ if (at >= avcC.end) return 8;+ const ppsCount = b[at++];+ for (let i = 0; i < ppsCount && at + 2 <= avcC.end; i++) at += 2 + u16(b, at);+ if (at + 3 > avcC.end) return 8;+ return 8 + (b[at + 1] & 0x07);+ }+ const av1C = child(b, entry, "av1C");+ if (av1C && av1C.end - av1C.start >= 3) {+ const highBitdepth = (b[av1C.start + 2] >> 6) & 1;+ const twelveBit = (b[av1C.start + 2] >> 5) & 1;+ return highBitdepth ? (twelveBit ? 12 : 10) : 8;+ }+ const vpcC = child(b, entry, "vpcC");+ if (vpcC && vpcC.end - vpcC.start >= 6) return b[vpcC.start + 6] >> 4 || 8;+ return 8;+}++/** What the probe reads out of a movie header: the first video sample entry+ * (its payload, the fixed fields dropped) and the metadata bytes that can+ * name a log curve. */+interface MovieFacts {+ entry: { format: string; bytes: Uint8Array } | null;+ metadata: Uint8Array[];+}++/** Atoms whose payload can hold the log identifiers. */+const METADATA = new Set(["meta", "udta"]);++async function scan(blocks: Blocks, atom: Atom): Promise<Uint8Array> {+ return blocks.bytes(atom.start, Math.min(atom.end - atom.start, SCAN_MAX));+}++/** Walk `moov` for the facts, reading only the atoms that carry them. */+async function readMovie(blocks: Blocks, moov: Atom): Promise<MovieFacts> {+ const facts: MovieFacts = { entry: null, metadata: [] };+ const budget = { left: MAX_ATOMS };+ for await (const top of atoms(blocks, moov.start, moov.end, budget)) {+ if (METADATA.has(top.type)) {+ facts.metadata.push(await scan(blocks, top));+ continue;+ }+ if (top.type !== "trak" || facts.entry) continue;+ let isVideo = false;+ let stsd: Atom | null = null;+ const trakMeta: Atom[] = [];+ for await (const t of atoms(blocks, top.start, top.end, budget)) {+ if (METADATA.has(t.type)) trakMeta.push(t);+ if (t.type !== "mdia") continue;+ for await (const m of atoms(blocks, t.start, t.end, budget)) {+ if (m.type === "hdlr") {+ // Full box: version/flags (4), pre_defined (4), handler_type (4).+ const h = await blocks.bytes(m.start, 12);+ isVideo = h.length >= 12 && ascii(h, 8) === "vide";+ if (!isVideo) break;+ } else if (m.type === "minf" && isVideo) {+ const stbl = await childAtom(blocks, m, "stbl", budget);+ stsd = stbl ? await childAtom(blocks, stbl, "stsd", budget) : null;+ }+ }+ }+ if (!isVideo || !stsd) continue;+ // Full box header (4) + entry count (4), then the sample entries.+ const first = (await atoms(blocks, stsd.start + 8, stsd.end, budget).next()).value as Atom | undefined;+ // VisualSampleEntry: 78 bytes of fixed fields before the child boxes.+ if (first && first.end - first.start >= 78) {+ const bytes = await blocks.bytes(first.start + 78, Math.min(first.end - first.start - 78, SCAN_MAX));+ facts.entry = { format: first.type, bytes };+ }+ for (const a of trakMeta) facts.metadata.push(await scan(blocks, a));+ }+ return facts;+}++/** Settle a file's color from its header. `size` is the file's byte length,+ * when known; without it the walk ends where a read comes back short. */+export async function probeColor(readRange: ReadRange, size = Infinity): Promise<ColorProbe> {+ const blocks = new Blocks(readRange, size);+ const moov = await findMoov(blocks);+ if (!moov) return DEFAULT_COLOR;+ return colorOf(await readMovie(blocks, moov));+}++/** Walk the top-level atoms for `moov`. Null when the file is not an ISO+ * base media file or has no movie header in reach. Once the walk is within+ * reach of the end of a file of known length, the rest comes in one read:+ * that is where a camera writes the movie header. */+async function findMoov(blocks: Blocks): Promise<Atom | null> {+ let at = 0;+ for (let seen = 0; seen < 64 && at + 8 <= blocks.size; seen++) {+ if (blocks.size - at <= MOOV_PREFETCH) blocks.prefetch(at, blocks.size - at);+ const head = await blocks.bytes(at, 16);+ if (head.length < 8) return null;+ const type = ascii(head, 4);+ let size = u32(head, 0);+ let headLen = 8;+ if (size === 1) {+ if (head.length < 16) return null;+ size = u64(head, 8);+ headLen = 16;+ } else if (size === 0) {+ size = blocks.size - at;+ }+ if (at === 0 && !["ftyp", "moov", "wide", "free", "mdat", "skip"].includes(type)) return null;+ if (size < headLen) return null;+ if (type === "moov") {+ // A header cut short by the file's end ends there: the atoms that run+ // past it are not read.+ const atom = { type, start: at + headLen, end: Math.min(at + size, blocks.size) };+ if (atom.end - atom.start <= MOOV_PREFETCH) blocks.prefetch(atom.start, atom.end - atom.start);+ return atom;+ }+ at += size;+ }+ return null;+}++/** The profile a sample entry's `colr` and the movie's metadata settle on. */+function colorOf(facts: MovieFacts): ColorProbe {+ if (!facts.entry) return DEFAULT_COLOR;+ const { format, bytes } = facts.entry;+ const entry: Box = { type: format, start: 0, end: bytes.length };+ let matrix: CodeFormat["matrix"] = "bt709";+ let fullRange = false;+ let transfer = 1;+ let hdrMatrix = false;+ for (const c of boxes(bytes, entry.start, entry.end)) {+ if (c.type !== "colr" || c.end - c.start < 10) continue;+ const kind = ascii(bytes, c.start);+ if (kind !== "nclx" && kind !== "nclc") continue;+ const primaries = u16(bytes, c.start + 4);+ transfer = u16(bytes, c.start + 6);+ const code = u16(bytes, c.start + 8);+ // An unspecified matrix on BT.2020 primaries is BT.2020's own.+ hdrMatrix = code === BT2020 || (code === UNSPECIFIED && primaries === BT2020);+ matrix = hdrMatrix ? "bt2020nc" : (MATRIX[code] ?? "bt709");+ fullRange = kind === "nclx" && c.end - c.start >= 11 ? (bytes[c.start + 10] & 0x80) !== 0 : false;+ break;+ }+ const bitDepth = bitDepthOf(bytes, entry, format);+ const named = (id: string) => contains(bytes, id) || facts.metadata.some((m) => contains(m, id));+ let detected: SourceProfile;+ if (named(APPLE_LOG_2)) detected = "apple-log-2";+ else if (named(APPLE_LOG) || named(APPLE_CUSTOM_GAMMA)) detected = "apple-log";+ else if (transfer === 18 && hdrMatrix) detected = "hlg";+ else if (transfer === 16 && hdrMatrix) detected = "pq";+ else if (transfer === 13) detected = "srgb";+ else detected = "rec709";+ return { code: { matrix, fullRange, bitDepth }, detected, codec: format };+}++/** An asset's color record from a probe: the code format and the profile+ * the header settles on. */+export type ProbedColor = CodeFormat & { detected: SourceProfile; codec: string };++export const colorRecord = (probe: ColorProbe): ProbedColor => ({+ ...probe.code,+ detected: probe.detected,+ codec: probe.codec,+});++/** The video assets that carry no color record yet. */+export const lacksColor = <A extends { type: string; color?: unknown; block?: unknown }>(a: A): boolean =>+ a.type === "video" && !a.color && !a.block;++/**+ * Color records for every video asset the timeline draws that has none, one+ * header walk per file, keyed by file name. `used` names the assets the+ * frame reads (`pictureAssetIds`): a file sitting unused in the Media panel is+ * never walked, and a used file whose header cannot be read fails the call,+ * naming it. Each process hands in its own way to reach the bytes — a URL in+ * the tab and the runner, the file on disk in the engine — and every caller+ * fills its assets from the one answer.+ */+export async function probeMissingColors<A extends { id: string; type: string; fileName: string; color?: unknown; block?: unknown }>(+ assets: readonly A[],+ used: ReadonlySet<string>,+ probe: (asset: A) => Promise<ColorProbe>+): Promise<Map<string, ProbedColor>> {+ const found = new Map<string, ProbedColor>();+ const walks = new Map<string, A>();+ for (const a of assets) if (used.has(a.id) && lacksColor(a) && !walks.has(a.fileName)) walks.set(a.fileName, a);+ await Promise.all(+ [...walks].map(async ([fileName, asset]) => {+ try {+ found.set(fileName, colorRecord(await probe(asset)));+ } catch (e) {+ throw new Error(`The color of ${fileName} could not be read: ${e instanceof Error ? e.message : String(e)}`);+ }+ })+ );+ return found;+}++/** `assets` with the colors `probeMissingColors` found filled in. */+export const withFoundColors = <A extends { type: string; fileName: string; color?: unknown; block?: unknown }>(+ assets: A[],+ found: ReadonlyMap<string, ProbedColor>+): A[] =>+ found.size === 0+ ? assets+ : assets.map((a) => (lacksColor(a) && found.has(a.fileName) ? { ...a, color: found.get(a.fileName) } : a));++/** `readRange` over bytes already in hand. */+export const rangeOfBytes =+ (bytes: Uint8Array): ReadRange =>+ async (offset, length) =>+ bytes.subarray(offset, Math.min(bytes.length, offset + length));++/** `readRange` over a Blob or File. */+export const rangeOfBlob =+ (blob: Blob): ReadRange =>+ async (offset, length) =>+ new Uint8Array(await blob.slice(offset, Math.min(blob.size, offset + length)).arrayBuffer());diff --git a/site/src/cut/lib/colorSettings.ts b/site/src/cut/lib/colorSettings.tsnew file mode 100644index 00000000..3c92bf6d--- /dev/null+++ b/site/src/cut/lib/colorSettings.ts@@ -0,0 +1,16 @@+import { SETTINGS, type Settings } from "@/lib/config/registry";++// The color pipeline's tunables — LUT sizes, the proxy's size and quality, the+// LUT file cap — bound once at session start from account config (the tab) or+// the global setting (a worker job), and read wherever a LUT is sized.++let color: Settings["cutColor"] = SETTINGS.cutColor.default;++export function bindCutColor(value: unknown): void {+ const parsed = SETTINGS.cutColor.schema.safeParse(value);+ if (parsed.success) color = parsed.data;+}++export function cutColor(): Settings["cutColor"] {+ return color;+}diff --git a/site/src/cut/lib/colorTools.test.ts b/site/src/cut/lib/colorTools.test.tsnew file mode 100644index 00000000..a55fe2ab--- /dev/null+++ b/site/src/cut/lib/colorTools.test.ts@@ -0,0 +1,168 @@+import { beforeEach, expect, test } from "bun:test";+import { GRADE_MAX } from "@donkeycut/effects-kit";+import { stubModule } from "@/lib/testing/stubModule";+import type { LibraryAsset, LibraryData } from "./library";+import type { SavedGrade } from "./gradePresets";+import type { MediaAsset } from "./types";++// The colour tools: every slider the panel renders, four wheels, the LUT+// off the shelf, one grade copied across the timeline as one undo step, the+// source-colour switch, and the saved grades — the chat surface of the+// Color panel, kept true to it.++// One LUT on the shelf, listed the way the registry lists a lazy kind: off+// its row's content key, with no bytes read.+const shelf: LibraryAsset[] = [+ {+ id: "l1",+ fileName: "kodak.cube",+ name: "Kodak 2383",+ type: "lut",+ duration: 0,+ addedAt: 1,+ residency: "cloud",+ contentKey: "kodak",+ lut: { kind: "3d", size: 33 },+ },+];+await stubModule<typeof import("./library")>("./library", import.meta.url, {+ fetchLibrary: async (): Promise<LibraryData> => ({ assets: shelf, folders: [], templates: [] }),+});+await stubModule<typeof import("./cache")>("./cache", import.meta.url, {+ readSnapshot: async () => null,+ writeSnapshot: () => {},+});++const shelfGrades: SavedGrade[] = [];+await stubModule<typeof import("./gradePresets")>("./gradePresets", import.meta.url, {+ listSavedGrades: async () => shelfGrades,+ saveGradePreset: async (_projectId, name, grade) => {+ const saved: SavedGrade = { id: `g${shelfGrades.length + 1}`, name, residency: "browser", grade: grade! };+ shelfGrades.push(saved);+ return saved;+ },+});++const { runAiTool } = await import("./aiTools");+const { useEditor } = await import("./store");+const { syncLinkedLibrary } = await import("./linkedLibrary");+await syncLinkedLibrary();++const LOG_ASSET: MediaAsset = {+ id: "a1",+ fileName: "log.mov",+ name: "Log",+ type: "video",+ duration: 5,+ url: "",+ color: { matrix: "bt2020nc", fullRange: false, bitDepth: 10, detected: "apple-log" },+};++beforeEach(async () => {+ shelfGrades.length = 0;+ useEditor.setState({+ projectId: "p1",+ clips: [],+ overlays: [],+ transitions: [],+ audioClips: [],+ assets: [+ LOG_ASSET,+ { id: "a2", fileName: "two.mp4", name: "Two", type: "video", duration: 5, url: "" },+ { id: "a3", fileName: "three.mp4", name: "Three", type: "video", duration: 5, url: "" },+ ],+ });+ for (const id of ["a1", "a2", "a3"]) await runAiTool("add_clip", { asset_id: id });+});++const clips = () => useEditor.getState().clips;+const clipIds = () => clips().map((c) => c.id);+const gradeOf = (id: string) => clips().find((c) => c.id === id)?.grade;++test("set_color_grade takes every basic and detail slider, clamped to its range", async () => {+ const [id] = clipIds();+ await runAiTool("set_color_grade", {+ clipId: id,+ whites: 10,+ blacks: -5,+ brilliance: 20,+ fade: -30,+ sharpen: 80,+ clarity: 15,+ });+ expect(gradeOf(id)).toEqual({ whites: 10, blacks: -5, brilliance: 20, sharpen: GRADE_MAX, clarity: 15 });+});++test("set_color_grade all_clips lands one patch on the whole timeline as one undo step", async () => {+ const out = (await runAiTool("set_color_grade", { all_clips: true, exposure: 12 })) as { ran: number; ids: string[] };+ expect(out.ran).toBe(3);+ expect(out.ids).toEqual(clipIds());+ expect(clips().every((c) => c.grade?.exposure === 12)).toBe(true);+ useEditor.getState().undo();+ expect(clips().every((c) => !c.grade)).toBe(true);+});++test("set_color_wheels writes the offset wheel and still reads the older zone names", async () => {+ const [id] = clipIds();+ await runAiTool("set_color_wheels", { clipId: id, offset: { dx: 5, dy: -5, luma: 2 }, shadows: { dx: 1, dy: 0, luma: 0 } });+ expect(gradeOf(id)?.wheels).toEqual({ o: [5, -5, 2], s: [1, 0, 0] });+ await runAiTool("set_color_wheels", { clipId: id, lift: { dx: 3, dy: 3, luma: 0 } });+ expect(gradeOf(id)?.wheels).toEqual({ o: [5, -5, 2], s: [3, 3, 0] });+});++test("set_color_curves knows no fade: only curve_contrast writes the master curve", async () => {+ const [id] = clipIds();+ await runAiTool("set_color_curves", { clipId: id, fade: 30 });+ expect(gradeOf(id)).toBeUndefined();+ await runAiTool("set_color_curves", { clipId: id, curve_contrast: 20 });+ expect(gradeOf(id)?.curves?.m?.length).toBeGreaterThan(1);+});++test("set_color_lut names a shelf LUT, keeps its amount, and takes it off again", async () => {+ const [id] = clipIds();+ await expect(runAiTool("set_color_lut", { clipId: id, lut: "lut:nope" })).rejects.toThrow(/No LUT/);+ await runAiTool("set_color_lut", { clipId: id, lut: "lut:kodak", amount: 0.5 });+ expect(gradeOf(id)?.lut).toEqual({ id: "lut:kodak", amount: 0.5 });+ await runAiTool("set_color_grade", { clipId: id, reset: true, exposure: 3 });+ expect(gradeOf(id)).toEqual({ exposure: 3, lut: { id: "lut:kodak", amount: 0.5 } });+ await runAiTool("set_color_lut", { clipId: id, lut: "none" });+ expect(gradeOf(id)).toEqual({ exposure: 3 });+});++test("copy_color_grade puts one clip's whole grade on every other clip, one undo step", async () => {+ const [a, b, c] = clipIds();+ await runAiTool("set_color_lut", { clipId: a, lut: "lut:kodak" });+ await runAiTool("set_color_grade", { clipId: a, exposure: 4, fade: 10 });+ const out = (await runAiTool("copy_color_grade", { clipId: a, all_clips: true })) as { ids: string[] };+ expect(out.ids).toEqual([b, c]);+ expect(gradeOf(c)).toEqual({ exposure: 4, fade: 10, lut: { id: "lut:kodak" } });+ useEditor.getState().undo();+ expect(gradeOf(b)).toBeUndefined();+ expect(gradeOf(c)).toBeUndefined();+ await expect(runAiTool("copy_color_grade", { clipId: a })).rejects.toThrow(/ids|all_clips/);+});++test("set_source_color overrides the detected profile on the clip's asset, with undo", async () => {+ const [id] = clipIds();+ const out = (await runAiTool("set_source_color", { clipId: id, profile: "rec709" })) as { profile: string; detected: string };+ expect(out).toMatchObject({ profile: "rec709", detected: "apple-log" });+ expect(useEditor.getState().assets[0].colorProfile).toBe("rec709");+ useEditor.getState().undo();+ expect(useEditor.getState().assets[0].colorProfile).toBeUndefined();+ await runAiTool("set_source_color", { assetId: "a1", profile: "hlg" });+ await runAiTool("set_source_color", { assetId: "a1", profile: "auto" });+ expect(useEditor.getState().assets[0].colorProfile).toBeUndefined();+ await expect(runAiTool("set_source_color", { assetId: "a1", profile: "cineon" })).rejects.toThrow(/profile must be/);+});++test("save_color_grade keeps the grade under a name and apply_saved_grade puts it on clips", async () => {+ const [a, b, c] = clipIds();+ await expect(runAiTool("save_color_grade", { clipId: a, name: "Warm" })).rejects.toThrow(/neutral/);+ await runAiTool("set_color_grade", { clipId: a, temperature: 15 });+ const saved = (await runAiTool("save_color_grade", { clipId: a, name: "Warm" })) as { id: string; name: string };+ expect(saved.name).toBe("Warm");+ const out = (await runAiTool("apply_saved_grade", { ids: [b, c], preset_id: "warm" })) as { ran: number };+ expect(out.ran).toBe(2);+ expect(gradeOf(c)).toEqual({ temperature: 15 });+ await expect(runAiTool("apply_saved_grade", { clipId: b, preset_id: "cold" })).rejects.toThrow(/No saved grade/);+});diff --git a/site/src/cut/lib/colorWalk.test.ts b/site/src/cut/lib/colorWalk.test.tsnew file mode 100644index 00000000..cd678ce8--- /dev/null+++ b/site/src/cut/lib/colorWalk.test.ts@@ -0,0 +1,13 @@+import { expect, spyOn, test } from "bun:test";+import { movieHeader } from "./fixtures/movieHeader";+import { probeMediaColor } from "./mediaRead";++test("an import's probe and the lazy fill of the same file share one walk", async () => {+ const file = new File([movieHeader({ primaries: 9, transfer: 16, matrix: 9 }) as BlobPart], "pq.mp4");+ const slices = spyOn(file, "slice");+ const [a, b] = await Promise.all([probeMediaColor(file), probeMediaColor(file)]);+ expect(a).toBe(b);+ expect(a.detected).toBe("pq");+ // The whole file is one block: one read, however many ask.+ expect(slices.mock.calls.length).toBe(1);+});diff --git a/site/src/cut/lib/composite.test.ts b/site/src/cut/lib/composite.test.tsnew file mode 100644index 00000000..83229f84--- /dev/null+++ b/site/src/cut/lib/composite.test.ts@@ -0,0 +1,285 @@+import { afterAll, beforeEach, describe, expect, spyOn, test } from "bun:test";+import * as kit from "@donkeycut/effects-kit";+import { applyDetail, applyLutToImageData, buildClipLut } from "@donkeycut/effects-kit";+import { FrameCompositor, type Frame } from "./composite";+import { beginLutDraft, clearClipLuts, clipLutKey, endLutDraft, peekClipLut, requestClipLut } from "./lutBuild";+import { setRasterFactory, type RasterSurface } from "./raster";+import type { VideoClip } from "./types";++// The compositor's color path, drawn onto a pixel canvas that stands in for+// the DOM's: what a clip's pixels are after its source conversion, its grade+// and its detail pass — the same numbers the kit's reference passes produce,+// which is what ties the preview to the export.++/** A canvas of bytes: same-size draws copy pixels source-over, reads and+ * writes go straight to the buffer, and everything else is accepted and+ * ignored. No WebGL, so the GPU passes step aside for the CPU ones. */+class PixelCanvas {+ data: Uint8ClampedArray;+ private w: number;+ private h: number;+ readonly ctx: Record<string, unknown>;+ constructor(w: number, h: number) {+ this.w = Math.max(1, w);+ this.h = Math.max(1, h);+ this.data = new Uint8ClampedArray(this.w * this.h * 4);+ this.ctx = new Proxy(+ {+ canvas: this,+ filter: "none",+ globalAlpha: 1,+ globalCompositeOperation: "source-over",+ fillStyle: "#000000",+ imageSmoothingEnabled: true,+ clearRect: () => this.data.fill(0),+ fillRect: () => {+ const hex = /^#?([0-9a-f]{6})$/i.exec(String(this.ctx.fillStyle))?.[1] ?? "000000";+ const [r, g, b] = [0, 2, 4].map((i) => parseInt(hex.slice(i, i + 2), 16));+ for (let i = 0; i < this.data.length; i += 4) {+ this.data[i] = r;+ this.data[i + 1] = g;+ this.data[i + 2] = b;+ this.data[i + 3] = 255;+ }+ },+ drawImage: (src: PixelCanvas, ...args: number[]) => {+ const [dx, dy, dw, dh] =+ args.length >= 8 ? args.slice(4) : args.length >= 4 ? args : [args[0], args[1], src.w, src.h];+ for (let y = 0; y < this.h; y++) {+ for (let x = 0; x < this.w; x++) {+ const sx = Math.floor(((x - dx) / dw) * src.w);+ const sy = Math.floor(((y - dy) / dh) * src.h);+ if (sx < 0 || sy < 0 || sx >= src.w || sy >= src.h) continue;+ const si = (sy * src.w + sx) * 4;+ const di = (y * this.w + x) * 4;+ const a = src.data[si + 3] / 255;+ for (let c = 0; c < 3; c++) this.data[di + c] = Math.round(src.data[si + c] * a + this.data[di + c] * (1 - a));+ this.data[di + 3] = Math.round(255 * (a + (this.data[di + 3] / 255) * (1 - a)));+ }+ }+ },+ getImageData: (x: number, y: number, w: number, h: number) => ({+ data: this.data.slice(0),+ width: w,+ height: h,+ }),+ putImageData: (img: { data: Uint8ClampedArray }) => this.data.set(img.data),+ } as Record<string, unknown>,+ {+ get: (target, prop) =>+ prop in target ? target[prop as string] : typeof prop === "string" ? () => undefined : undefined,+ set: (target, prop, value) => ((target[prop as string] = value), true),+ }+ );+ }+ get width() {+ return this.w;+ }+ set width(v: number) {+ this.w = Math.max(1, v);+ this.data = new Uint8ClampedArray(this.w * this.h * 4);+ }+ get height() {+ return this.h;+ }+ set height(v: number) {+ this.h = Math.max(1, v);+ this.data = new Uint8ClampedArray(this.w * this.h * 4);+ }+ getContext(kind: string) {+ return kind === "2d" ? this.ctx : null;+ }+}++setRasterFactory({+ createCanvas: (w, h) => new PixelCanvas(w, h) as unknown as RasterSurface,+ decodeImage: async () => null,+ canvasToBlob: async () => new Blob(),+});+afterAll(() => clearClipLuts());++const W = 8;+const H = 8;++/** A picture that walks the cube: red across, green down, blue held. */+function picture(): PixelCanvas {+ const c = new PixelCanvas(W, H);+ for (let y = 0; y < H; y++) {+ for (let x = 0; x < W; x++) {+ const i = (y * W + x) * 4;+ c.data[i] = x * 32;+ c.data[i + 1] = y * 32;+ c.data[i + 2] = 128;+ c.data[i + 3] = 255;+ }+ }+ return c;+}++const frameOf = (c: PixelCanvas): Frame => ({ kind: "ready", image: c as unknown as CanvasImageSource, width: W, height: H });++const clipOf = (over: Partial<VideoClip> = {}): VideoClip => ({+ id: "c1",+ assetId: "a1",+ track: 0,+ start: 0,+ in: 0,+ out: 4,+ muted: false,+ ...over,+});++let canvas: PixelCanvas;+let comp: FrameCompositor;++beforeEach(() => {+ clearClipLuts();+ canvas = new PixelCanvas(W, H);+ comp = new FrameCompositor(canvas as unknown as RasterSurface);+ comp.colorMode = "exact";+});++const drawn = () => Array.from(canvas.data);+const rgb = (px: ArrayLike<number>) => Array.from(px).filter((_, i) => i % 4 !== 3);++describe("the compositor's color path", () => {+ test("a Rec.709 clip with no grade draws its pixels as they are", () => {+ const src = picture();+ comp.drawLayer(frameOf(src), clipOf(), true, 1, 0);+ expect(drawn()).toEqual(Array.from(src.data));+ expect(requestClipLut(comp.recipeFor(clipOf()))).toBeNull();+ });++ test("a log source draws through its conversion LUT, graded or not", () => {+ comp.sourceProvider = () => ({ profile: "apple-log" });+ const src = picture();+ comp.drawLayer(frameOf(src), clipOf(), true, 1, 0);+ const expected = picture().data;+ applyLutToImageData(expected, buildClipLut({ profile: "apple-log", output: "sdr", size: 65 })!);+ expect(rgb(drawn())).toEqual(rgb(expected));+ expect(rgb(drawn())).not.toEqual(rgb(src.data));+ });++ test("a grade bakes into the LUT the export writes, and the pixels match it", () => {+ const grade = { exposure: 10, contrast: 8, saturation: -10 };+ comp.drawLayer(frameOf(picture()), clipOf({ grade }), true, 1, 0);+ const expected = picture().data;+ applyLutToImageData(expected, buildClipLut({ profile: "rec709", grade, output: "sdr", size: 33 })!);+ expect(rgb(drawn())).toEqual(rgb(expected));+ });++ test("sharpen and clarity run after the LUT as the detail pass", () => {+ const grade = { exposure: 10, sharpen: 30, clarity: 20 };+ comp.drawLayer(frameOf(picture()), clipOf({ grade }), true, 1, 0);+ const expected = picture().data;+ applyLutToImageData(expected, buildClipLut({ profile: "rec709", grade: { exposure: 10 }, output: "sdr", size: 33 })!);+ applyDetail(expected, W, H, { sharpen: 30, clarity: 20 });+ expect(rgb(drawn())).toEqual(rgb(expected));+ });++ test("a library LUT that is not on the shelf renders the grade without it, keyed apart", () => {+ const grade = { exposure: 10, lut: { id: "lut:nothere" } };+ comp.drawLayer(frameOf(picture()), clipOf({ grade }), true, 1, 0);+ const expected = picture().data;+ applyLutToImageData(expected, buildClipLut({ profile: "rec709", grade: { exposure: 10 }, output: "sdr", size: 33 })!);+ expect(rgb(drawn())).toEqual(rgb(expected));+ const recipe = comp.recipeFor(clipOf({ grade }));+ expect(clipLutKey(recipe, "lut:nothere", false).endsWith("|lut:nothere:off")).toBe(true);+ expect(clipLutKey(recipe, "lut:nothere", true).endsWith("|lut:nothere:on")).toBe(true);+ });++ test("an HLG composite maps every recipe into HLG, the frame color with it", () => {+ comp.output = "hlg";+ expect(comp.recipeFor(clipOf()).output).toBe("hlg");+ comp.sourceProvider = () => ({ profile: "apple-log" });+ expect(comp.recipeFor(clipOf()).output).toBe("hlg");+ comp.sourceProvider = () => ({ profile: "rec709" });+ // A Rec.709 clip is a conversion now: its pixels land at HLG code values,+ // white at reference white.+ const src = picture();+ comp.drawLayer(frameOf(src), clipOf(), true, 1, 0);+ const expected = picture().data;+ applyLutToImageData(expected, buildClipLut({ profile: "rec709", output: "hlg", size: 33 })!);+ expect(rgb(drawn())).toEqual(rgb(expected));+ expect(rgb(drawn())).not.toEqual(rgb(src.data));+ comp.background = "#ffffff";+ comp.clear();+ expect(Array.from(canvas.data.slice(0, 3))).toEqual([191, 191, 191]);+ comp.output = "sdr";+ expect(comp.recipeFor(clipOf()).output).toBe("sdr");+ comp.clear();+ expect(Array.from(canvas.data.slice(0, 3))).toEqual([255, 255, 255]);+ });++ test("a live drag sizes the cube down and the settle brings the full one back", () => {+ const log = clipOf({ id: "log", assetId: "log" });+ comp.colorMode = "live";+ comp.sourceProvider = (c) => ({ profile: c.assetId === "log" ? "apple-log" : "rec709" });+ expect(comp.recipeFor(clipOf()).size).toBe(33);+ expect(comp.recipeFor(log).size).toBe(65);+ beginLutDraft();+ expect(comp.recipeFor(clipOf()).size).toBe(17);+ expect(comp.recipeFor(log).size).toBe(17);+ endLutDraft();+ expect(comp.recipeFor(clipOf()).size).toBe(33);+ });++ test("a render that writes a picture builds the full cube during a drag", () => {+ // An in-tab export, mask or removal bake running while a slider moves in+ // the editor keeps the full cube: the drag's draft is the preview's alone.+ const log = clipOf({ id: "log", assetId: "log" });+ comp.sourceProvider = (c) => ({ profile: c.assetId === "log" ? "apple-log" : "rec709" });+ beginLutDraft();+ try {+ expect(comp.recipeFor(clipOf()).size).toBe(33);+ expect(comp.recipeFor(log).size).toBe(65);+ } finally {+ endLutDraft();+ }+ });++ test("a frame that changes nothing reuses the clip's recipe and key", () => {+ const log = { profile: "apple-log" as const };+ comp.sourceProvider = () => log;+ const grade = { exposure: 10 };+ const clip = clipOf({ grade });+ const keyOf = spyOn(kit, "recipeKey");+ try {+ const recipe = comp.recipeFor(clip);+ const first = requestClipLut(recipe, { exact: true })!;+ const keyed = keyOf.mock.calls.length;+ expect(keyed).toBeGreaterThan(0);+ for (let i = 0; i < 5; i++) {+ const again = comp.recipeFor(clip);+ expect(again).toBe(recipe);+ expect(requestClipLut(again, { exact: true })).toBe(first);+ }+ expect(keyOf.mock.calls.length).toBe(keyed);+ // A new grade, a new source or a new output is a new recipe and key.+ const regraded = comp.recipeFor(clipOf({ grade: { exposure: 20 } }));+ expect(regraded).not.toBe(recipe);+ expect(clipLutKey(regraded, null, false)).not.toBe(first.key);+ comp.sourceProvider = () => ({ profile: "hlg" });+ const resourced = comp.recipeFor(clip);+ expect(resourced).not.toBe(recipe);+ expect(clipLutKey(resourced, null, false)).not.toBe(first.key);+ comp.sourceProvider = () => log;+ comp.output = "hlg";+ expect(comp.recipeFor(clip)).not.toBe(recipe);+ comp.output = "sdr";+ expect(comp.recipeFor(clip)).toBe(recipe);+ } finally {+ keyOf.mockRestore();+ }+ });++ test("a built LUT is kept and answered from the cache", () => {+ const recipe = comp.recipeFor(clipOf({ grade: { exposure: 10 } }));+ const first = requestClipLut(recipe, { exact: true })!;+ expect(first.lut.size).toBe(33);+ expect(peekClipLut(first.key)?.lut).toBe(first.lut);+ expect(requestClipLut(recipe, { exact: true })!.lut).toBe(first.lut);+ clearClipLuts();+ expect(peekClipLut(first.key)).toBeUndefined();+ });+});diff --git a/site/src/cut/lib/composite.ts b/site/src/cut/lib/composite.tsindex 321a291d..3b557b06 100644--- a/site/src/cut/lib/composite.ts+++ b/site/src/cut/lib/composite.ts@@ -19,8 +19,10 @@* it was reached by playing there or by rendering the 135th frame.*/-import { applyLutToImageData, applyMaskToCanvas, buildGradeLut, gradeKey, gradeNeedsLut, gradeTint, gradeToCssFilter, grainTile, isNeutralGrade, lookCssFilter, lookPost, maskComposite, paintStrokeInk, removalActive, type GradeLut } from "@donkeycut/effects-kit";+import { applyDetail, applyLutToImageData, applyMaskToCanvas, detailActive, grainTile, hexToHlgHex, lookCssFilter, lookPost, maskComposite, paintStrokeInk, removalActive, type ClipColorRecipe, type OutputSpace } from "@donkeycut/effects-kit";+import { applyDetailGpu } from "./detailGpu";import { applyLutGpu } from "./gradeGpu";+import { clipRecipe, peekClipLut, requestClipLut, type ClipLut, type RecipeSource } from "./lutBuild";import { createRasterCanvas } from "./raster";import { clipCovers, clipPosed, clipPoseAt, clipZoom, contentRect, DEFAULT_BACKGROUND, isFullRect, rectOf, shadowInk } from "./types";import type { ClipShadow, FrameRect, TransitionStyle, VideoClip } from "./types";@@ -35,7 +37,16 @@ import type { ClipShadow, FrameRect, TransitionStyle, VideoClip } from "./types"export type Frame =| { kind: "missing" }| { kind: "pending" }- | { kind: "ready"; image: CanvasImageSource; width: number; height: number };+ | {+ kind: "ready";+ image: CanvasImageSource;+ width: number;+ height: number;+ /** What these pixels' code values mean, from the reader that decoded+ * them. A frame held across a move to another file keeps its own;+ * absent, the clip's `sourceProvider` answers. */+ source?: RecipeSource;+ };export const MISSING_FRAME: Frame = { kind: "missing" };export const PENDING_FRAME: Frame = { kind: "pending" };@@ -66,55 +77,12 @@ type Ctx = CanvasRenderingContext2D | OffscreenCanvasRenderingContext2D;/** The grain tile advances on this cadence, in seconds per step. */const GRAIN_STEP = 0.08;-/** Compiled grade LUTs, shared across compositors and rebuilt only when a- * grade actually changes. A cut rarely holds more than a handful of distinct- * grades at once; the cap just bounds a long editing session. */-const lutCache = new Map<string, GradeLut | null>();-const LUT_CACHE_MAX = 24;--/** What a grade object means to the renderer, memoized on the object itself.- * Every store edit hands out a fresh grade, so identity is a safe key — and- * the reads that decide the path (neutral? LUT? which LUT?) each normalize the- * grade, which is far too much allocation to repeat per clip per frame. */-interface GradeFacts {- neutral: boolean;- needsLut: boolean;- key: string;-}-const gradeFacts = new WeakMap<object, GradeFacts>();--function factsFor(grade: VideoClip["grade"]): GradeFacts | null {- if (!grade) return null;- let facts = gradeFacts.get(grade);- if (!facts) {- facts = {- neutral: isNeutralGrade(grade),- needsLut: gradeNeedsLut(grade),- key: gradeKey(grade) ?? "",- };- gradeFacts.set(grade, facts);- }- return facts;-}+/** The source every clip renders as when nothing says otherwise: Rec.709+ * display values, which need no conversion. */+const REC709_SOURCE: RecipeSource = { profile: "rec709" };-function lutForGrade(grade: VideoClip["grade"], key: string): { lut: GradeLut; key: string } | null {- if (!key) return null;- if (lutCache.has(key)) {- const hit = lutCache.get(key)!;- // Re-insert so the cap evicts the least recently used grade, never one the- // cut is still playing.- lutCache.delete(key);- lutCache.set(key, hit);- return hit ? { lut: hit, key } : null;- }- const lut = buildGradeLut(grade);- if (lutCache.size >= LUT_CACHE_MAX) {- const oldest = lutCache.keys().next().value;- if (oldest !== undefined) lutCache.delete(oldest);- }- lutCache.set(key, lut);- return lut ? { lut, key } : null;-}+/** How many clips a compositor remembers the last drawn LUT for. */+const LAST_LUT_MAX = 64;export class FrameCompositor {/** Scratch buffers, kept for the compositor's life: the grade pass, the@@ -145,6 +113,33 @@ export class FrameCompositor {* `removalLookB`. */private removalLookA: Surface | null = null;private removalLookB: Surface | null = null;+ /** The pixel pass of the grade's spatial controls, when the GPU cannot+ * run it: a scratch the CPU reads and writes. */+ private detailScratch: Surface | null = null;++ /** What a clip's code values mean — its source profile, and whatever the+ * decode route adds — so the compositor can build the clip's color recipe.+ * Absent, every clip is Rec.709. */+ sourceProvider: ((clip: VideoClip) => RecipeSource) | null = null;++ /** The project's delivery space, which the recipe bakes toward. */+ output: OutputSpace = "sdr";++ /**+ * How a LUT that is not in hand is handled. `live` (the preview) never+ * waits: the build goes off the thread and the clip draws through the last+ * LUT it had, or plain, until it lands and `wake` repaints. `exact` (an+ * export, a baked layer) builds on this thread, so every frame is drawn+ * through its own LUT.+ */+ colorMode: "live" | "exact" = "live";++ /** Repaint request, fired when a LUT built off the thread lands. */+ wake: (() => void) | null = null;++ /** Per clip, the key of the LUT it last drew through: what stands in while+ * a newer one builds. Bounded; the LUTs themselves live in the cache. */+ private lastLut = new Map<string, string>();/** Where a subject-masked clip's person matte comes from: the host hands a* reader over the canvas as it stands (the layers beneath the clip), so@@ -213,7 +208,8 @@ export class FrameCompositor {| "removalSil"| "removalInk"| "removalLookA"- | "removalLookB",+ | "removalLookB"+ | "detailScratch",w: number,h: number): { surface: Surface; resized: boolean } {@@ -231,10 +227,24 @@ export class FrameCompositor {return { surface, resized };}+ /** The frame color as the composite holds it: as is in SDR, and mapped+ * like every other sRGB graphic when the composite is HLG. One conversion+ * per color, held for the frames that follow. */+ private backgroundFill: { hex: string; output: OutputSpace; fill: string } | null = null;++ private backgroundFor(): string {+ if (this.output === "sdr") return this.background;+ const held = this.backgroundFill;+ if (held && held.hex === this.background && held.output === this.output) return held.fill;+ const fill = hexToHlgHex(this.background);+ this.backgroundFill = { hex: this.background, output: this.output, fill };+ return fill;+ }+clear() {const ctx = this.ctx();if (!ctx) return;- ctx.fillStyle = this.background;+ ctx.fillStyle = this.backgroundFor();ctx.fillRect(0, 0, this.canvas.width, this.canvas.height);}@@ -259,11 +269,49 @@ export class FrameCompositor {this.fillVeil("0,0,0", amount, rect);}+ /** The recipe a clip renders through: its source, its grade, the output.+ * `frameSource` is the drawn frame's own, when its reader named one. */+ recipeFor(clip: VideoClip | undefined, frameSource?: RecipeSource): ClipColorRecipe {+ const source = frameSource ?? (clip && this.sourceProvider?.(clip)) ?? REC709_SOURCE;+ return clipRecipe(source, clip?.grade, this.output, this.colorMode === "live");+ }++ /**+ * The LUT a clip draws through this frame: its own when it is in hand,+ * the last one it drew through while a newer build is out, and none for+ * an identity recipe or a clip whose first LUT has not landed yet.+ */+ private lutFor(clip: VideoClip | undefined, recipe: ClipColorRecipe): ClipLut | null {+ const got = requestClipLut(recipe, {+ exact: this.colorMode === "exact",+ wake: this.wake ?? undefined,+ });+ if (got === null) {+ if (clip) this.lastLut.delete(clip.id);+ return null;+ }+ if (got) {+ if (clip && this.lastLut.get(clip.id) !== got.key) {+ this.lastLut.delete(clip.id);+ this.lastLut.set(clip.id, got.key);+ if (this.lastLut.size > LAST_LUT_MAX) {+ const oldest = this.lastLut.keys().next().value;+ if (oldest !== undefined) this.lastLut.delete(oldest);+ }+ }+ return got;+ }+ const last = clip && this.lastLut.get(clip.id);+ return last ? (peekClipLut(last) ?? null) : null;+ }+/**- * The clip's picture with its color grade and look grading applied, or the- * raw image when there is nothing to apply. Mirrors the export's chain order- * — grade first (lutrgb/hue), then the look's color pass — as CSS filters,- * with the grade's warm tint as a multiply pass, and source alpha restored so+ * The clip's picture with its color and look applied, or the raw image+ * when there is nothing to apply. The color is one LUT per clip — source+ * conversion, library LUT and grade baked together — applied on the GPU+ * (the CPU where there is none), then the grade's sharpen and clarity as a+ * spatial pass, then the look's color pass as a canvas filter, in the order+ * the export's chain runs. Source alpha rides through every pass, so* transparent stills keep their transparency. The look's post passes* (vignette, grain, glow…) draw over the composited layer instead.*/@@ -271,61 +319,55 @@ export class FrameCompositor {frame: Extract<Frame, { kind: "ready" }>,clip: VideoClip | undefined): CanvasImageSource {- const grade = clip?.grade;- const facts = factsFor(grade);+ const recipe = this.recipeFor(clip, frame.source);+ const compiled = this.lutFor(clip, recipe);+ const detail = detailActive(clip?.grade) ? clip!.grade! : null;const lookCss = lookCssFilter(clip?.look, clip?.lookAmount);- if ((!facts || facts.neutral) && !lookCss) return frame.image;+ if (!compiled && !detail && !lookCss) return frame.image;const w = frame.width;const h = frame.height;+ let picture: CanvasImageSource = frame.image;+ if (compiled) {+ const gpu = applyLutGpu(picture, w, h, compiled.lut, compiled.key);+ if (gpu) {+ picture = gpu as CanvasImageSource;+ } else {+ const { surface: pixels } = this.scratch("gradeLutScratch", w, h);+ const pctx = pixels.getContext("2d") as Ctx | null;+ if (!pctx) return frame.image;+ pctx.clearRect(0, 0, w, h);+ pctx.drawImage(picture, 0, 0, w, h);+ const img = pctx.getImageData(0, 0, w, h);+ applyLutToImageData(img.data, compiled.lut);+ pctx.putImageData(img, 0, 0);+ picture = pixels as CanvasImageSource;+ }+ }+ if (detail) {+ const gpu = applyDetailGpu(picture, w, h, detail);+ if (gpu) {+ picture = gpu as CanvasImageSource;+ } else {+ const { surface: pixels } = this.scratch("detailScratch", w, h);+ const pctx = pixels.getContext("2d") as Ctx | null;+ if (!pctx) return picture;+ pctx.clearRect(0, 0, w, h);+ pctx.drawImage(picture, 0, 0, w, h);+ const img = pctx.getImageData(0, 0, w, h);+ applyDetail(img.data, w, h, detail);+ pctx.putImageData(img, 0, 0);+ picture = pixels as CanvasImageSource;+ }+ }+ if (!lookCss) return picture;const { surface: scratch } = this.scratch("gradeCanvas", w, h);const ctx = scratch.getContext("2d") as Ctx | null;- // Without ctx.filter support, skip the whole treatment rather than- // half-applying the tint.- if (!ctx || !("filter" in ctx)) return frame.image;+ // A context with no filter support draws the color without the look.+ if (!ctx || !("filter" in ctx)) return picture;ctx.clearRect(0, 0, w, h);- if (facts?.needsLut) {- const compiled = lutForGrade(grade, facts.key);- if (compiled) {- // The LUT carries the whole grade (preset, curves, wheels, HSL and- // the scalar sliders); the look's color pass still applies after it,- // keeping the export's grade-before-look order.- const gpu = applyLutGpu(frame.image, w, h, compiled.lut, compiled.key);- if (gpu) {- ctx.filter = lookCss || "none";- ctx.drawImage(gpu as CanvasImageSource, 0, 0, w, h);- ctx.filter = "none";- } else {- const { surface: pixels } = this.scratch("gradeLutScratch", w, h);- const pctx = pixels.getContext("2d") as Ctx | null;- if (!pctx) return frame.image;- pctx.clearRect(0, 0, w, h);- pctx.drawImage(frame.image, 0, 0, w, h);- const img = pctx.getImageData(0, 0, w, h);- applyLutToImageData(img.data, compiled.lut);- pctx.putImageData(img, 0, 0);- ctx.filter = lookCss || "none";- ctx.drawImage(pixels, 0, 0, w, h);- ctx.filter = "none";- }- return scratch;- }- // A grade whose LUT resolves neutral (an unknown preset id alone)- // falls through to the fast path for whatever scalars remain.- }- ctx.filter = [gradeToCssFilter(grade), lookCss].filter(Boolean).join(" ") || "none";- ctx.drawImage(frame.image, 0, 0, w, h);+ ctx.filter = lookCss;+ ctx.drawImage(picture, 0, 0, w, h);ctx.filter = "none";- const tint = gradeTint(grade);- if (tint) {- ctx.globalCompositeOperation = "multiply";- ctx.fillStyle = tint;- ctx.fillRect(0, 0, w, h);- // Multiply painted the transparent areas solid; carve the source's alpha- // back in.- ctx.globalCompositeOperation = "destination-in";- ctx.drawImage(frame.image, 0, 0, w, h);- ctx.globalCompositeOperation = "source-over";- }return scratch;}diff --git a/site/src/cut/lib/contentKey.ts b/site/src/cut/lib/contentKey.tsnew file mode 100644index 00000000..f36c2256--- /dev/null+++ b/site/src/cut/lib/contentKey.ts@@ -0,0 +1,10 @@+/** A linked library item's identity: enough SHA-256 of its bytes to never+ * collide in one account's shelf. The same file on two shelves is one item+ * and one id, which is what lets a project change residency without a word+ * of it being rewritten. */+export async function contentKey(bytes: ArrayBuffer): Promise<string> {+ const digest = await crypto.subtle.digest("SHA-256", bytes);+ return [...new Uint8Array(digest).slice(0, 8)]+ .map((b) => b.toString(16).padStart(2, "0"))+ .join("");+}diff --git a/site/src/cut/lib/cutClipboard.ts b/site/src/cut/lib/cutClipboard.tsindex b016648f..b05c724e 100644--- a/site/src/cut/lib/cutClipboard.ts+++ b/site/src/cut/lib/cutClipboard.ts@@ -11,6 +11,7 @@// finds it, and then lands the items on the copies.import { clearCopiedFrame } from "./stageFrame";+import { isLinkedAssetType } from "./types";import { reportSwallowed } from "./report";import { refFromAsset, selectionRefTokens } from "./assetRef";import { trackEditorTool } from "./editorWork";@@ -144,7 +145,7 @@ export async function pasteCutPayload(if (payload.items.length === 0) {let placed = false;for (const l of landed) {- if (l.asset.type === "font") continue;+ if (isLinkedAssetType(l.asset.type)) continue;if (await placeRefAtPlayhead(refFromAsset(l.asset), { projectId, library, at })) placed = true;}return placed || landed.length > 0;diff --git a/site/src/cut/lib/decoderCheck.test.ts b/site/src/cut/lib/decoderCheck.test.tsnew file mode 100644index 00000000..b9204e1c--- /dev/null+++ b/site/src/cut/lib/decoderCheck.test.ts@@ -0,0 +1,53 @@+import { afterAll, expect, test } from "bun:test";+import { decodeYcc } from "@donkeycut/effects-kit";+import { clearDecodePaths, decodePath } from "./decoderCheck";+import { setFrameSinkFactory, type FrameSinkOptions } from "./mediaRead";++// The H.264 fixture's four tiles, as code values on [0,1].+const TILES: Record<string, readonly [number, number, number]> = {+ "16,16": [135 / 255, 91 / 255, 157 / 255],+ "48,16": [113 / 255, 164 / 255, 97 / 255],+ "16,48": [124 / 255, 128 / 255, 128 / 255],+ "48,48": [206 / 255, 128 / 255, 128 / 255],+};++/** A decoder that draws through Rec.709 and honors the override's range+ * flag, the way a browser that follows the rewritten tags does. */+function honoringDecoder(opts?: FrameSinkOptions) {+ const fullRange = opts?.colorSpace?.fullRange ?? false;+ const canvas = {+ width: 64,+ height: 64,+ getContext: () => ({+ getImageData: (x: number, y: number) => {+ const [yy, cb, cr] = TILES[`${x},${y}`];+ const rgb = decodeYcc({ matrix: "bt709", fullRange }, yy, cb, cr);+ return { data: new Uint8ClampedArray([...rgb.map((v) => Math.round(Math.min(1, Math.max(0, v)) * 255)), 255]) };+ },+ }),+ };+ const frame = { canvas, timestamp: 0, duration: 1 / 30 };+ return {+ getCanvas: async () => frame,+ canvases: async function* () {+ yield frame;+ },+ canvasesAtTimestamps: async function* () {+ yield frame;+ },+ };+}++afterAll(() => {+ setFrameSinkFactory(null);+ clearDecodePaths();+});++test("each range the override names is measured on its own", async () => {+ clearDecodePaths();+ setFrameSinkFactory((_track, _size, opts) => honoringDecoder(opts) as never);+ expect(await decodePath("webcodecs", false)).toEqual({ kind: "code", drawnMatrix: "bt709", drawnFullRange: false });+ // A full-range master is read under a full-range override; a decoder that+ // honors the flag draws full range, and the recipe has to say so.+ expect(await decodePath("webcodecs", true)).toEqual({ kind: "code", drawnMatrix: "bt709", drawnFullRange: true });+});diff --git a/site/src/cut/lib/decoderCheck.ts b/site/src/cut/lib/decoderCheck.tsnew file mode 100644index 00000000..ce3fe45b--- /dev/null+++ b/site/src/cut/lib/decoderCheck.ts@@ -0,0 +1,170 @@+/**+ * What this runtime's decoders draw when asked for code values.+ *+ * A log or HDR master is read with a color space override (mediaRead.ts+ * `FrameSinkOptions.colorSpace`): the file's tags are replaced by sRGB /+ * Rec.709 limited, in the decoder config and inside the bitstream's own SPS,+ * so the browser neither tone-maps an HLG file nor converts a wide-gamut one.+ * The picture it draws is then the file's Y'CbCr through whatever matrix the+ * decoder honored — the rewritten Rec.709 tag on most routes, BT.601 on+ * Chrome's 10-bit 4:2:2 path — and the grade pipeline undoes that matrix+ * (`DrawnColor`, effects-kit colorPipeline.ts). Each decode route is measured+ * once per session and per range the override names, on a one-frame,+ * four-tile fixture: the drawn tiles are matched against the code values+ * through every matrix and range, and the nearest wins. A decoder may honor+ * the full-range flag or ignore it, so a full-range master is read through+ * what the full-range override measured. A route whose picture matches none+ * was converted anyway.+ */++import { decodeYcc, type CodeFormat } from "@donkeycut/effects-kit";+import { frameSink, openMedia, videoTrackOf } from "./mediaRead";+import { ensureProresDecoder } from "./proresDecoder";++/** How a track's frames reach the page: a WebCodecs decoder for H.264 / HEVC+ * and the other browser codecs, the WASM ProRes decoder, or the process's+ * own decoder when a headless runner installed one (sourceColor.ts picks+ * the route for an asset). */+export type DecodeRoute = "webcodecs" | "prores" | "headless";++export type DecodePathResult =+ /** Code values, drawn through this matrix and range. */+ | { kind: "code"; drawnMatrix: CodeFormat["matrix"]; drawnFullRange: boolean }+ /** The file's own matrix and range, untouched (headless decoders). */+ | { kind: "source" }+ /** The override was ignored and the picture converted; read a proxy. */+ | { kind: "converted" };++interface Fixture {+ base64: string;+ mime: string;+ /** Y'CbCr at the four tile centers, each on [0,1] of its scale. */+ codes: readonly (readonly [number, number, number])[];+}++/** 64×64, one frame, H.264 Main tagged bt2020 / arib-std-b67 / bt2020nc,+ * limited range. Four flat tiles. */+const H264_HLG: Fixture = {+ base64:+ "AAAAIGZ0eXBpc29tAAACAGlzb21pc28yYXZjMW1wNDEAAAMabW9vdgAAAGxtdmhkAAAAAAAAAAAAAAAAAAAD6AAAACIAAQAAAQAAAAAAAAAAAAAAAAEAAAAAAAAAAAAAAAAAAAABAAAAAAAAAAAAAAAAAABAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAgAAAkV0cmFrAAAAXHRraGQAAAADAAAAAAAAAAAAAAABAAAAAAAAACIAAAAAAAAAAAAAAAAAAAAAAAEAAAAAAAAAAAAAAAAAAAABAAAAAAAAAAAAAAAAAABAAAAAAEAAAABAAAAAAAAkZWR0cwAAABxlbHN0AAAAAAAAAAEAAAAiAAAAAAABAAAAAAG9bWRpYQAAACBtZGhkAAAAAAAAAAAAAAAAAAA8AAAAAgBVxAAAAAAALWhkbHIAAAAAAAAAAHZpZGUAAAAAAAAAAAAAAABWaWRlb0hhbmRsZXIAAAABaG1pbmYAAAAUdm1oZAAAAAEAAAAAAAAAAAAAACRkaW5mAAAAHGRyZWYAAAAAAAAAAQAAAAx1cmwgAAAAAQAAAShzdGJsAAAAxHN0c2QAAAAAAAAAAQAAALRhdmMxAAAAAAAAAAEAAAAAAAAAAAAAAAAAAAAAAEAAQABIAAAASAAAAAAAAAABH0xhdmM2MS4xOS4xMDEgaDI2NF92aWRlb3Rvb2xib3gAGP//AAAAJ2F2Y0MBTQAL/+EAECdNAAurQYbwIMIzUJEgkCABAAQo7jyAAAAAE2NvbHJuY2x4AAIAAgAJAAAAABBwYXNwAAAAAQAAAAEAAAAUYnRydAAAAAAAAJUQAACVEAAAABhzdHRzAAAAAAAAAAEAAAABAAACAAAAABxzdHNjAAAAAAAAAAEAAAABAAAAAQAAAAEAAAAUc3RzegAAAAAAAACfAAAAAQAAABRzdGNvAAAAAAAAAAEAAANKAAAAYXVkdGEAAABZbWV0YQAAAAAAAAAhaGRscgAAAAAAAAAAbWRpcmFwcGwAAAAAAAAAAAAAAAAsaWxzdAAAACSpdG9vAAAAHGRhdGEAAAABAAAAAExhdmY2MS43LjEwMAAAAAhmcmVlAAAAp21kYXQAAAA7BgUyR1ZK3FxMQz+U78URPNFDqAEAAAMAAQMAAAMAAQIAAeYACwAAAwAAAwAAAwGaDAOJKAEN/////4AAAABcJbggH7gVWFA+XJt3fYfLvbZyD9goKjzUORp5UAEPi6t1Upz3k/qQpq6LHdk5Q9uIvzmp5qmxsyDADd2gh4TlwwfWnsBiU1spQZPGFNnA0SWQFUAAai1ugoAypEw=",+ mime: "video/mp4",+ codes: [+ [135 / 255, 91 / 255, 157 / 255],+ [113 / 255, 164 / 255, 97 / 255],+ [124 / 255, 128 / 255, 128 / 255],+ [206 / 255, 128 / 255, 128 / 255],+ ],+};++/** The same four tiles as ProRes 422 10-bit, tagged bt2020 / arib-std-b67 /+ * bt2020nc, limited range. */+const PRORES_HLG: Fixture = {+ base64: "AAAAFGZ0eXBxdCAgAAACAHF0ICAAAAAId2lkZQAAAQZtZGF0AAAA/mljcGYAlAAATGF2YwBAAECAAAICCQAAAwQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQFBAQEBAQEBQUEBAQEBAUFBgQEBAQFBQYHBAQEBAUGBwcEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBQQEBAQEBAUFBAQEBAQFBQYEBAQEBQUGBwQEBAQFBgcHQAAAAGIABDAAGAAYABEAETAEAAYABicj8ArkfgmeMAJKxggiMAexGDAEAAYABicj8ArkfgmeMAJKxggiMAexGDAEAAcAAlOPwApbH4CCP4I/MAQABwACU4/AClsfgII/gj8AAALTbW9vdgAAAGxtdmhkAAAAAAAAAAAAAAAAAAAD6AAAACIAAQAAAQAAAAAAAAAAAAAAAAEAAAAAAAAAAAAAAAAAAAABAAAAAAAAAAAAAAAAAABAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAgAAAj90cmFrAAAAXHRraGQAAAADAAAAAAAAAAAAAAABAAAAAAAAACIAAAAAAAAAAAAAAAAAAAAAAAEAAAAAAAAAAAAAAAAAAAABAAAAAAAAAAAAAAAAAABAAAAAAEAAAABAAAAAAAAkZWR0cwAAABxlbHN0AAAAAAAAAAEAAAAiAAAAAAABAAAAAAG3bWRpYQAAACBtZGhkAAAAAAAAAAAAAAAAAAA8AAAAAgB//wAAAAAALWhkbHIAAAAAbWhscnZpZGUAAAAAAAAAAAAAAAAMVmlkZW9IYW5kbGVyAAABYm1pbmYAAAAUdm1oZAAAAAEAAAAAAAAAAAAAACxoZGxyAAAAAGRobHJ1cmwgAAAAAAAAAAAAAAAAC0RhdGFIYW5kbGVyAAAAJGRpbmYAAAAcZHJlZgAAAAAAAAABAAAADHVybCAAAAABAAAA9nN0YmwAAACSc3RzZAAAAAAAAAABAAAAgmFwY2gAAAAAAAAAAQAAAABGRk1QAAACAAAAAgAAQABAAEgAAABIAAAAAAAAAAEXTGF2YzYxLjE5LjEwMSBwcm9yZXNfa3MAAAAAAAAAAAAY//8AAAAKZmllbAEAAAAAEmNvbHJuY2xjAAIAAgAJAAAAEHBhc3AAAAABAAAAAQAAABhzdHRzAAAAAAAAAAEAAAABAAACAAAAABxzdHNjAAAAAAAAAAEAAAABAAAAAQAAAAEAAAAUc3RzegAAAAAAAAD+AAAAAQAAABRzdGNvAAAAAAAAAAEAAAAkAAAAIHVkdGEAAAAYqXN3cgAMVcRMYXZmNjEuNy4xMDA=",+ mime: "video/quicktime",+ codes: [+ [543 / 1023, 366 / 1023, 634 / 1023],+ [456 / 1023, 659 / 1023, 388 / 1023],+ [499 / 1023, 512 / 1023, 512 / 1023],+ [830 / 1023, 512 / 1023, 512 / 1023],+ ],+};++const SAMPLE_AT: readonly (readonly [number, number])[] = [+ [16, 16],+ [48, 16],+ [16, 48],+ [48, 48],+];++/** The color space a route's decoder is asked to tag frames with: sRGB at+ * the file's own range, through Rec.709 for the WebCodecs decoders, whose+ * rewritten SPS carries the same tags. The WASM ProRes route asks for+ * BT.601: Chrome's 4:2:2 10-bit draw mixes the coefficients under a Rec.709+ * tag and follows a BT.601 tag exactly, and WebKit follows either, so the+ * one tag both draw exactly is the one asked for. */+export function decodeOverrideFor(route: DecodeRoute, fullRange: boolean): VideoColorSpaceInit {+ return { primaries: "bt709", transfer: "iec61966-2-1", matrix: route === "prores" ? "smpte170m" : "bt709", fullRange };+}++const MATRICES: readonly CodeFormat["matrix"][] = ["bt709", "bt601", "bt2020nc"];+/** The nearest candidate wins when its worst channel is within this many+ * 8-bit levels: chroma upsampling and rounding. The candidates sit far+ * further apart from each other, and a converted frame from all of them. */+const TOLERANCE = 6;++const results = new Map<string, Promise<DecodePathResult>>();+const settled = new Map<string, DecodePathResult>();+const keyOf = (route: DecodeRoute, fullRange: boolean) => `${route}|${fullRange ? "full" : "limited"}`;++/** What the route draws for a track read with the override at `fullRange`;+ * measured once per session, on a failure counted as converted. */+export function decodePath(route: DecodeRoute, fullRange: boolean): Promise<DecodePathResult> {+ const key = keyOf(route, fullRange);+ let p = results.get(key);+ if (!p) {+ p = (route === "headless" ? Promise.resolve<DecodePathResult>({ kind: "source" }) : measure(route, fullRange)).catch(+ (): DecodePathResult => ({ kind: "converted" })+ );+ p.then((r) => settled.set(key, r));+ results.set(key, p);+ }+ return p;+}++/** The measured result, or undefined while the measurement runs. Asking+ * starts it. */+export function decodePathNow(route: DecodeRoute, fullRange: boolean): DecodePathResult | undefined {+ void decodePath(route, fullRange);+ return settled.get(keyOf(route, fullRange));+}++/** Forget every measurement (tests). */+export function clearDecodePaths(): void {+ results.clear();+ settled.clear();+}++async function measure(route: "webcodecs" | "prores", fullRange: boolean): Promise<DecodePathResult> {+ const fixture = route === "prores" ? PRORES_HLG : H264_HLG;+ if (route === "prores") await ensureProresDecoder();+ const bytes = Uint8Array.from(atob(fixture.base64), (c) => c.charCodeAt(0));+ const input = openMedia(new Blob([bytes], { type: fixture.mime }));+ try {+ const track = await videoTrackOf(input);+ if (!track) return { kind: "converted" };+ // The fixture is coded limited range; read under a full-range override+ // it shows whether this decoder honors the flag.+ const sink = frameSink(track, undefined, { colorSpace: decodeOverrideFor(route, fullRange) });+ const frame = await sink.getCanvas(0);+ if (!frame) return { kind: "converted" };+ const ctx = frame.canvas.getContext("2d") as CanvasRenderingContext2D | null;+ if (!ctx) return { kind: "converted" };+ const drawn = SAMPLE_AT.map(([x, y]) => Array.from(ctx.getImageData(x, y, 1, 1).data.subarray(0, 3)));+ return classify(drawn, fixture.codes);+ } finally {+ input.dispose();+ }+}++/** The matrix and range whose expected tiles sit nearest the drawn ones. */+export function classify(+ drawn: readonly (readonly number[])[],+ codes: Fixture["codes"]+): DecodePathResult {+ let best: DecodePathResult = { kind: "converted" };+ let bestErr = Infinity;+ for (const matrix of MATRICES) {+ for (const fullRange of [false, true]) {+ let err = 0;+ codes.forEach(([y, cb, cr], i) => {+ const want = decodeYcc({ matrix, fullRange }, y, cb, cr);+ for (let c = 0; c < 3; c++) err = Math.max(err, Math.abs(drawn[i][c] - Math.round(Math.min(1, Math.max(0, want[c])) * 255)));+ });+ if (err < bestErr) {+ bestErr = err;+ best = { kind: "code", drawnMatrix: matrix, drawnFullRange: fullRange };+ }+ }+ }+ return bestErr <= TOLERANCE ? best : { kind: "converted" };+}diff --git a/site/src/cut/lib/detailGpu.test.ts b/site/src/cut/lib/detailGpu.test.tsnew file mode 100644index 00000000..fcef5d50--- /dev/null+++ b/site/src/cut/lib/detailGpu.test.ts@@ -0,0 +1,87 @@+import { afterAll, afterEach, expect, test } from "bun:test";+import { stubModule } from "@/lib/testing/stubModule";+import { memoryUsage } from "./memoryBudget";++// A stand-in WebGL2 context: constants read as their own names, calls are+// recorded, and the allocation calls hand back fresh objects.+const allocations: { internal: string; w: number; h: number }[] = [];+let deleted = 0;+const gl = new Proxy({} as Record<string, unknown>, {+ get(_t, key: string) {+ if (/^[A-Z0-9_]+$/.test(key)) return key;+ if (key === "texImage2D")+ return (_target: unknown, _level: number, internal: string, w: unknown, h: unknown) => {+ if (typeof w === "number") allocations.push({ internal, w, h: h as number });+ };+ if (key === "deleteTexture") return () => void deleted++;+ if (key === "isContextLost") return () => false;+ if (key.startsWith("get") && key.endsWith("Parameter")) return () => true;+ if (key === "getExtension") return () => ({ loseContext() {} });+ if (key.startsWith("create") || key.startsWith("get")) return () => ({});+ return () => {};+ },+});+const canvas = { width: 2, height: 2, getContext: () => gl };+await stubModule<typeof import("./raster")>("./raster", import.meta.url, {+ createRasterCanvas: (() => canvas) as never,+});+const { applyDetailGpu, detailGpuBytes, DETAIL_IDLE_MS, disposeDetailGpu, releaseDetailGpu } = await import("./detailGpu");+// The pass is a module singleton: files after this one build their own.+afterAll(disposeDetailGpu);++afterEach(() => {+ releaseDetailGpu();+ allocations.length = 0;+ deleted = 0;+});++test("a 4K frame's detail buffers are one and two float channels, reported to the budget", () => {+ const w = 3840;+ const h = 2160;+ expect(applyDetailGpu({} as CanvasImageSource, w, h, { sharpen: 40, clarity: 40 })).not.toBeNull();+ const full = allocations.filter((a) => a.w === w);+ const half = allocations.filter((a) => a.w === w / 2);+ expect(full.map((a) => a.internal)).toEqual(["R32F", "R32F", "R32F"]);+ expect(half.map((a) => a.internal).sort()).toEqual(["RG16F", "RG32F", "RG32F", "RG32F", "RG32F", "RG32F"]);+ const px = w * h;+ const expected = px * 4 * 2 + px * 4 * 3 + (px / 4) * (8 * 5 + 4);+ expect(detailGpuBytes()).toBe(expected);+ // Well under the 530MB four-channel float buffers held before.+ expect(detailGpuBytes()).toBeLessThan(260 * 2 ** 20);+ expect(memoryUsage().canvases).toBeGreaterThanOrEqual(expected);+});++test("detail left idle lets its buffers go, and comes back on the next frame", () => {+ const realNow = performance.now.bind(performance);+ const realSet = globalThis.setTimeout;+ let now = 1000;+ const timers: (() => void)[] = [];+ performance.now = () => now;+ globalThis.setTimeout = ((fn: () => void) => {+ timers.push(fn);+ return timers.length;+ }) as unknown as typeof setTimeout;+ try {+ applyDetailGpu({} as CanvasImageSource, 1920, 1080, { sharpen: 30 });+ expect(detailGpuBytes()).toBeGreaterThan(0);+ // Used again inside the window: the check re-arms and holds on.+ now += DETAIL_IDLE_MS / 2;+ applyDetailGpu({} as CanvasImageSource, 1920, 1080, { sharpen: 30 });+ now += DETAIL_IDLE_MS / 2;+ timers.shift()!();+ expect(detailGpuBytes()).toBeGreaterThan(0);+ now += DETAIL_IDLE_MS;+ timers.shift()!();+ // What stays is the one-pixel canvas the programs draw into.+ expect(detailGpuBytes()).toBeLessThanOrEqual(4);+ expect(deleted).toBe(3);+ applyDetailGpu({} as CanvasImageSource, 1920, 1080, { sharpen: 30 });+ expect(detailGpuBytes()).toBeGreaterThan(0);+ // Disposed with the preview, the pass holds nothing at all.+ disposeDetailGpu();+ expect(detailGpuBytes()).toBe(0);+ } finally {+ performance.now = realNow;+ globalThis.setTimeout = realSet;+ }+});diff --git a/site/src/cut/lib/detailGpu.ts b/site/src/cut/lib/detailGpu.tsnew file mode 100644index 00000000..6d706c80--- /dev/null+++ b/site/src/cut/lib/detailGpu.ts@@ -0,0 +1,438 @@+/**+ * GPU sharpen and clarity for the preview and the in-tab export: the two+ * spatial controls of a grade, run after the clip LUT and before the look,+ * with the math of effects-kit detail.ts — detail is luma minus a smoothed+ * base, added back with a gain on every channel. Sharpen's base is a small+ * Gaussian blur at full resolution; clarity's base is the self-guided+ * filter over a wide window, computed at half resolution (its means vary+ * slowly, so the half-size pass reads the same and costs a quarter).+ *+ * One WebGL2 context, its canvas from the raster seam, a handful of small+ * programs and float framebuffers ping-ponged between them: one channel for+ * a luma and its blurs, two for a mean beside its square. The framebuffers+ * are the size of the picture, so they are let go once detail has been idle+ * for a while and when the preview goes away, and what they hold is reported+ * to the memory budget. Under a headless factory there is no WebGL2 and the+ * caller runs the CPU pass instead; the same happens when float render+ * targets are missing.+ */++import { CLARITY_EPS, detailGain, detailRadius, type DetailSettings } from "@donkeycut/effects-kit";+import { holdMemory } from "./memoryBudget";+import { createRasterCanvas, type RasterSurface } from "./raster";++const VERT = `#version 300 es+in vec2 aPos;+out vec2 vUv;+void main() {+ vUv = aPos * 0.5 + 0.5;+ gl_Position = vec4(aPos, 0.0, 1.0);+}`;++const HEAD = `#version 300 es+precision highp float;+in vec2 vUv;+out vec4 outColor;+const vec3 LUMA = vec3(0.2126, 0.7152, 0.0722);+`;++/** Luma of the uploaded source (rows top-down, so sampled flipped), with its+ * square beside it for the guided filter's variance. */+const LUMA_FRAG = `${HEAD}+uniform sampler2D uSrc;+void main() {+ vec4 s = texture(uSrc, vec2(vUv.x, 1.0 - vUv.y));+ float l = dot(s.rgb, LUMA);+ outColor = vec4(l, l * l, 0.0, 1.0);+}`;++/** The largest half-kernel a blur pass takes; sigma 3·radius covers 8K. */+const MAX_RADIUS = 48;++/** One direction of a separable Gaussian over the red channel. */+const GAUSS_FRAG = `${HEAD}+uniform sampler2D uTex;+uniform vec2 uStep;+uniform int uRadius;+uniform float uWeights[${MAX_RADIUS + 1}];+void main() {+ float acc = texture(uTex, vUv).r * uWeights[0];+ for (int i = 1; i <= ${MAX_RADIUS}; i++) {+ if (i > uRadius) break;+ vec2 d = uStep * float(i);+ acc += (texture(uTex, vUv + d).r + texture(uTex, vUv - d).r) * uWeights[i];+ }+ outColor = vec4(acc, 0.0, 0.0, 1.0);+}`;++/** One direction of a box mean over the red and green channels. */+const BOX_FRAG = `${HEAD}+uniform sampler2D uTex;+uniform vec2 uStep;+uniform int uRadius;+void main() {+ vec2 acc = texture(uTex, vUv).rg;+ for (int i = 1; i <= ${MAX_RADIUS}; i++) {+ if (i > uRadius) break;+ vec2 d = uStep * float(i);+ acc += texture(uTex, vUv + d).rg + texture(uTex, vUv - d).rg;+ }+ outColor = vec4(acc / float(2 * uRadius + 1), 0.0, 1.0);+}`;++/** The guided filter's local linear coefficients from the window means of+ * the luma and its square: a = var / (var + eps), b = mean − a·mean. */+const AB_FRAG = `${HEAD}+uniform sampler2D uTex;+uniform float uEps;+void main() {+ vec2 m = texture(uTex, vUv).rg;+ float v = max(0.0, m.g - m.r * m.r);+ float a = v / (v + uEps);+ outColor = vec4(a, m.r - a * m.r, 0.0, 1.0);+}`;++/** Detail back onto the picture: the source luma against each base, gained,+ * added to every channel; alpha passes through. */+const FINAL_FRAG = `${HEAD}+uniform sampler2D uSrc;+uniform sampler2D uSharp;+uniform sampler2D uAB;+uniform float uKs;+uniform float uKc;+void main() {+ vec4 s = texture(uSrc, vec2(vUv.x, 1.0 - vUv.y));+ float l = dot(s.rgb, LUMA);+ float delta = 0.0;+ if (uKs > 0.0) delta += uKs * (l - texture(uSharp, vUv).r);+ if (uKc > 0.0) {+ vec2 ab = texture(uAB, vUv).rg;+ delta += uKc * (l - (ab.r * l + ab.g));+ }+ outColor = vec4(clamp(s.rgb + delta, 0.0, 1.0), s.a);+}`;++interface Program {+ program: WebGLProgram;+ loc: Record<string, WebGLUniformLocation | null>;+}++/** A render target's storage: one float channel (a luma, a blur of it), two+ * (a mean beside the mean of its square, or the guided filter's a and b), or+ * two half floats where the target is sampled with linear filtering, which+ * 32-bit floats need an extension for. */+type TargetKind = "r32f" | "rg32f" | "rg16f";+const TARGET_BYTES: Record<TargetKind, number> = { r32f: 4, rg32f: 8, rg16f: 4 };++interface Target {+ tex: WebGLTexture;+ fbo: WebGLFramebuffer;+ w: number;+ h: number;+ kind: TargetKind;+}++interface DetailPass {+ canvas: RasterSurface;+ gl: WebGL2RenderingContext;+ srcTex: WebGLTexture;+ luma: Program;+ gauss: Program;+ box: Program;+ ab: Program;+ final: Program;+ targets: Map<string, Target>;+ /** The source texture's size, for the report. */+ srcW: number;+ srcH: number;+}++let pass: DetailPass | null | false = null;++/** Bytes the pass stands on: its float targets, the uploaded source, and the+ * canvas the result is drawn into. */+export function detailGpuBytes(): number {+ if (!pass) return 0;+ let n = (pass.srcW * pass.srcH + pass.canvas.width * pass.canvas.height) * 4;+ for (const t of pass.targets.values()) n += t.w * t.h * TARGET_BYTES[t.kind];+ return n;+}+holdMemory("detailTargets", detailGpuBytes);++/** How long detail may sit unused before its picture-sized buffers go. */+export const DETAIL_IDLE_MS = 4000;+let lastUsed = 0;+let idleTimer: ReturnType<typeof setTimeout> | null = null;++/** Let go of every picture-sized buffer; the programs stay, so the next+ * frame with detail only reallocates what it draws into. */+export function releaseDetailGpu(): void {+ if (idleTimer) clearTimeout(idleTimer);+ idleTimer = null;+ if (!pass) return;+ const { gl } = pass;+ if (!gl.isContextLost()) {+ for (const t of pass.targets.values()) {+ gl.deleteFramebuffer(t.fbo);+ gl.deleteTexture(t.tex);+ }+ gl.bindTexture(gl.TEXTURE_2D, pass.srcTex);+ gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, 1, 1, 0, gl.RGBA, gl.UNSIGNED_BYTE, null);+ }+ pass.targets.clear();+ pass.srcW = 0;+ pass.srcH = 0;+ pass.canvas.width = 1;+ pass.canvas.height = 1;+}++/** Let go of the pass itself with its buffers: the preview is going away,+ * and a page holds only so many WebGL contexts. The next use builds anew. */+export function disposeDetailGpu(): void {+ releaseDetailGpu();+ if (pass) pass.gl.getExtension("WEBGL_lose_context")?.loseContext();+ pass = null;+}++/** Book the idle check: one timer, re-armed only when it fires early. */+function noteUse(): void {+ lastUsed = performance.now();+ if (idleTimer || typeof setTimeout === "undefined") return;+ const check = () => {+ idleTimer = null;+ const idle = performance.now() - lastUsed;+ if (idle >= DETAIL_IDLE_MS) releaseDetailGpu();+ else idleTimer = setTimeout(check, DETAIL_IDLE_MS - idle);+ };+ idleTimer = setTimeout(check, DETAIL_IDLE_MS);+}++function compile(gl: WebGL2RenderingContext, frag: string, uniforms: string[]): Program | null {+ const make = (type: number, src: string) => {+ const sh = gl.createShader(type)!;+ gl.shaderSource(sh, src);+ gl.compileShader(sh);+ return gl.getShaderParameter(sh, gl.COMPILE_STATUS) ? sh : null;+ };+ const vs = make(gl.VERTEX_SHADER, VERT);+ const fs = make(gl.FRAGMENT_SHADER, frag);+ if (!vs || !fs) return null;+ const program = gl.createProgram()!;+ gl.attachShader(program, vs);+ gl.attachShader(program, fs);+ gl.linkProgram(program);+ if (!gl.getProgramParameter(program, gl.LINK_STATUS)) return null;+ const loc: Program["loc"] = {};+ for (const u of uniforms) loc[u] = gl.getUniformLocation(program, u);+ return { program, loc };+}++function init(): DetailPass | false {+ const canvas = createRasterCanvas(2, 2);+ const gl = (canvas.getContext as (id: string, opts?: unknown) => unknown)("webgl2", {+ premultipliedAlpha: false,+ preserveDrawingBuffer: true,+ }) as WebGL2RenderingContext | null;+ if (!gl) return false;+ // Float render targets: the means and the linear coefficients need more+ // than eight bits, or flat regions come back noisy.+ if (!gl.getExtension("EXT_color_buffer_float")) return false;+ const luma = compile(gl, LUMA_FRAG, ["uSrc"]);+ const gauss = compile(gl, GAUSS_FRAG, ["uTex", "uStep", "uRadius", "uWeights"]);+ const box = compile(gl, BOX_FRAG, ["uTex", "uStep", "uRadius"]);+ const ab = compile(gl, AB_FRAG, ["uTex", "uEps"]);+ const final = compile(gl, FINAL_FRAG, ["uSrc", "uSharp", "uAB", "uKs", "uKc"]);+ if (!luma || !gauss || !box || !ab || !final) return false;+ const buf = gl.createBuffer();+ gl.bindBuffer(gl.ARRAY_BUFFER, buf);+ gl.bufferData(gl.ARRAY_BUFFER, new Float32Array([-1, -1, 3, -1, -1, 3]), gl.STATIC_DRAW);+ // Every program binds aPos at the same location, so one attribute setup+ // serves them all.+ for (const p of [luma, gauss, box, ab, final]) {+ const posLoc = gl.getAttribLocation(p.program, "aPos");+ gl.enableVertexAttribArray(posLoc);+ gl.vertexAttribPointer(posLoc, 2, gl.FLOAT, false, 0, 0);+ }+ const srcTex = gl.createTexture()!;+ gl.bindTexture(gl.TEXTURE_2D, srcTex);+ gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.LINEAR);+ gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.LINEAR);+ gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);+ gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);+ return { canvas, gl, srcTex, luma, gauss, box, ab, final, targets: new Map(), srcW: 0, srcH: 0 };+}++/** A float render target of the given size, made once and resized in place. */+function target(p: DetailPass, name: string, w: number, h: number, kind: TargetKind): Target {+ const { gl } = p;+ let t = p.targets.get(name);+ const linear = kind === "rg16f";+ if (!t) {+ const tex = gl.createTexture()!;+ gl.bindTexture(gl.TEXTURE_2D, tex);+ gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, linear ? gl.LINEAR : gl.NEAREST);+ gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, linear ? gl.LINEAR : gl.NEAREST);+ gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);+ gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);+ const fbo = gl.createFramebuffer()!;+ t = { tex, fbo, w: 0, h: 0, kind };+ p.targets.set(name, t);+ }+ if (t.w !== w || t.h !== h) {+ const [internal, format] =+ kind === "r32f" ? [gl.R32F, gl.RED] : kind === "rg32f" ? [gl.RG32F, gl.RG] : [gl.RG16F, gl.RG];+ gl.bindTexture(gl.TEXTURE_2D, t.tex);+ gl.texImage2D(gl.TEXTURE_2D, 0, internal, w, h, 0, format, gl.FLOAT, null);+ gl.bindFramebuffer(gl.FRAMEBUFFER, t.fbo);+ gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, t.tex, 0);+ t.w = w;+ t.h = h;+ }+ return t;+}++function draw(p: DetailPass, prog: Program, into: Target | null, w: number, h: number): void {+ const { gl } = p;+ gl.useProgram(prog.program);+ gl.bindFramebuffer(gl.FRAMEBUFFER, into ? into.fbo : null);+ gl.viewport(0, 0, w, h);+ gl.drawArrays(gl.TRIANGLES, 0, 3);+}++function bind(p: DetailPass, unit: number, tex: WebGLTexture): void {+ p.gl.activeTexture(p.gl.TEXTURE0 + unit);+ p.gl.bindTexture(p.gl.TEXTURE_2D, tex);+}++const weightCache = new Map<number, Float32Array>();++/** Half of a normalized Gaussian kernel (center first), the same kernel+ * detail.ts builds, kept per sigma. */+function gaussWeights(sigma: number): { weights: Float32Array; radius: number } {+ const radius = Math.min(MAX_RADIUS, Math.max(1, Math.ceil(sigma * 3)));+ let w = weightCache.get(sigma);+ if (!w) {+ w = new Float32Array(MAX_RADIUS + 1);+ let sum = 0;+ for (let i = 0; i <= radius; i++) {+ w[i] = Math.exp(-(i * i) / (2 * sigma * sigma));+ sum += i === 0 ? w[i] : 2 * w[i];+ }+ for (let i = 0; i <= radius; i++) w[i] /= sum;+ weightCache.set(sigma, w);+ }+ return { weights: w, radius };+}++/**+ * Render `source` with sharpen and clarity applied and return the canvas+ * holding the result, or null when the GPU pass is unavailable — callers+ * then run applyDetail on the pixels. The returned canvas is shared and+ * valid until the next call.+ */+export function applyDetailGpu(+ source: CanvasImageSource,+ w: number,+ h: number,+ d: DetailSettings+): RasterSurface | null {+ if (pass && pass.gl.isContextLost()) pass = null;+ if (pass === false) return null;+ if (!pass) {+ try {+ pass = init();+ } catch {+ pass = false;+ }+ if (!pass) return null;+ }+ const p = pass;+ const { gl } = p;+ noteUse();+ const ks = detailGain("sharpen", d.sharpen || 0);+ const kc = detailGain("clarity", d.clarity || 0);+ try {+ if (p.canvas.width !== w || p.canvas.height !== h) {+ p.canvas.width = w;+ p.canvas.height = h;+ }+ bind(p, 0, p.srcTex);+ gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, gl.RGBA, gl.UNSIGNED_BYTE, source as TexImageSource);+ p.srcW = w;+ p.srcH = h;++ let sharpTex: WebGLTexture | null = null;+ if (ks > 0) {+ const lum = target(p, "lumaFull", w, h, "r32f");+ const tmp = target(p, "gaussTmp", w, h, "r32f");+ const base = target(p, "gaussBase", w, h, "r32f");+ gl.useProgram(p.luma.program);+ gl.uniform1i(p.luma.loc.uSrc, 0);+ draw(p, p.luma, lum, w, h);+ const { weights, radius } = gaussWeights(detailRadius("sharpen", h));+ gl.useProgram(p.gauss.program);+ gl.uniform1i(p.gauss.loc.uTex, 1);+ gl.uniform1i(p.gauss.loc.uRadius, radius);+ gl.uniform1fv(p.gauss.loc.uWeights, weights);+ bind(p, 1, lum.tex);+ gl.uniform2f(p.gauss.loc.uStep, 1 / w, 0);+ draw(p, p.gauss, tmp, w, h);+ bind(p, 1, tmp.tex);+ gl.uniform2f(p.gauss.loc.uStep, 0, 1 / h);+ draw(p, p.gauss, base, w, h);+ sharpTex = base.tex;+ }++ let abTex: WebGLTexture | null = null;+ if (kc > 0) {+ const hw = Math.max(1, Math.round(w / 2));+ const hh = Math.max(1, Math.round(h / 2));+ const lum = target(p, "lumaHalf", hw, hh, "rg32f");+ const tmp = target(p, "boxTmp", hw, hh, "rg32f");+ const mean = target(p, "boxMean", hw, hh, "rg32f");+ const ab = target(p, "ab", hw, hh, "rg32f");+ const abTmp = target(p, "abTmp", hw, hh, "rg32f");+ const abMean = target(p, "abMean", hw, hh, "rg16f");+ gl.useProgram(p.luma.program);+ gl.uniform1i(p.luma.loc.uSrc, 0);+ draw(p, p.luma, lum, hw, hh);+ // The window at half size: half the radius the CPU pass takes at full.+ const radius = Math.min(MAX_RADIUS, Math.max(1, Math.round(detailRadius("clarity", h) / 2)));+ gl.useProgram(p.box.program);+ gl.uniform1i(p.box.loc.uTex, 1);+ gl.uniform1i(p.box.loc.uRadius, radius);+ bind(p, 1, lum.tex);+ gl.uniform2f(p.box.loc.uStep, 1 / hw, 0);+ draw(p, p.box, tmp, hw, hh);+ bind(p, 1, tmp.tex);+ gl.uniform2f(p.box.loc.uStep, 0, 1 / hh);+ draw(p, p.box, mean, hw, hh);+ gl.useProgram(p.ab.program);+ gl.uniform1i(p.ab.loc.uTex, 1);+ gl.uniform1f(p.ab.loc.uEps, CLARITY_EPS);+ bind(p, 1, mean.tex);+ draw(p, p.ab, ab, hw, hh);+ gl.useProgram(p.box.program);+ bind(p, 1, ab.tex);+ gl.uniform2f(p.box.loc.uStep, 1 / hw, 0);+ draw(p, p.box, abTmp, hw, hh);+ bind(p, 1, abTmp.tex);+ gl.uniform2f(p.box.loc.uStep, 0, 1 / hh);+ draw(p, p.box, abMean, hw, hh);+ abTex = abMean.tex;+ }++ gl.useProgram(p.final.program);+ gl.uniform1i(p.final.loc.uSrc, 0);+ gl.uniform1i(p.final.loc.uSharp, 1);+ gl.uniform1i(p.final.loc.uAB, 2);+ gl.uniform1f(p.final.loc.uKs, ks);+ gl.uniform1f(p.final.loc.uKc, kc);+ bind(p, 1, sharpTex ?? p.srcTex);+ bind(p, 2, abTex ?? p.srcTex);+ draw(p, p.final, null, w, h);+ return p.canvas;+ } catch {+ return null;+ }+}diff --git a/site/src/cut/lib/engineFeatures.ts b/site/src/cut/lib/engineFeatures.tsindex df78a9bb..07e81874 100644--- a/site/src/cut/lib/engineFeatures.ts+++ b/site/src/cut/lib/engineFeatures.ts@@ -4,6 +4,6 @@* hands an engine work an older app would silently drop. A build from before* the list existed answers with none.*/-export const ENGINE_FEATURES = ["export.range", "export.name", "export.prores4444"] as const;+export const ENGINE_FEATURES = ["export.range", "export.name", "export.prores4444", "color.v2", "media.proxy", "export.hdr"] as const;export type EngineFeature = (typeof ENGINE_FEATURES)[number];diff --git a/site/src/cut/lib/exportClient.ts b/site/src/cut/lib/exportClient.tsindex 51e0d834..e79da201 100644--- a/site/src/cut/lib/exportClient.ts+++ b/site/src/cut/lib/exportClient.ts@@ -9,6 +9,8 @@ import { projectOperation } from "./projectOperation";import { apiFetch, apiJson, getBackend, type CutBackend } from "./backend";import { engineFeatures } from "./api";import type { EngineFeature } from "./engineFeatures";+import { cutColor } from "./colorSettings";+import { loadLibraryLutFile, lutIdOf } from "./linkedLibrary/luts";import {removeBrowserExportJob,reserveBrowserExportJob,@@ -20,6 +22,7 @@ import { captureCloudBackend } from "./backend/cloud";import { downloadFile, downloadFromUrl } from "./download";import { bitrateFor, canRenderInBrowser, renderProjectToMp4, type SourceExportProfile } from "./exportRender";import { putSigned } from "./media";+import { withAssetColors } from "./mediaRead";import { renderRemovalPieces } from "./removalVideo";import { drawBlock } from "./blockSource";import { createRasterCanvas, rasterCanvasToPng } from "./raster";@@ -48,6 +51,7 @@ import {EXPORT_CONTAINERS,exportBaseName,fixedRate,+ type SpecClipColor,specMediaFiles,type ExportAudioCodec,type ExportCodec,@@ -780,6 +784,21 @@ function renderClipBorderPng(return rasterCanvasToPng(canvas);}+/** What a source's code values mean, for the spec: the profile the header+ * settled (with the person's override), and the matrix and range the file+ * decodes with. A still is sRGB, decoded to full-range RGB, and a block is+ * painted in Rec.709. The spec builder reads every video's header first+ * (`withAssetColors`), so a video without a record is a caller's bug. */+export function specColor(+ asset: Pick<MediaAsset, "type" | "color" | "colorProfile" | "block" | "fileName"> | undefined+): SpecClipColor {+ if (!asset || asset.type === "image") return { profile: "srgb", matrix: "bt709", fullRange: true };+ if (asset.block) return { profile: "rec709", matrix: "bt709", fullRange: false };+ const c = asset.color;+ if (!c) throw new Error(`The color of ${asset.fileName} was never read.`);+ return { profile: asset.colorProfile ?? c.detected, matrix: c.matrix, fullRange: c.fullRange };+}+/** Build the export spec + overlay PNGs from the cut. Media already lives in* the project folder — the spec references it by file name; only overlay PNGs* travel with the request. Shared by full exports and the low-res hover proxy. */@@ -789,6 +808,13 @@ export async function buildExportPayload(settings: ExportSettings,target: "export" | "preview" | "card" | "hls"): Promise<ExportPayload> {+ // H.264 is an 8-bit delivery; an HDR picture takes HEVC Main 10 or ProRes.+ if ((doc.colorSpace ?? "sdr") !== "sdr" && settings.codec === "h264" && target === "export") {+ throw new Error("H.264 is 8-bit. Export HDR as HEVC or ProRes.");+ }+ // Every video's color is read before the spec is: footage the lazy fill+ // has not reached would otherwise go out as Rec.709.+ doc = { ...doc, assets: await withAssetColors(doc.assets, doc) };const spans = getClipSpans(doc.clips, doc.assets);const duration = projectDuration(doc);const pngs: ExportPayload["pngs"] = [];@@ -890,6 +916,7 @@ export async function buildExportPayload(// trimming a source span.image: sp.asset.type === "image",grade: normalizeGrade(sp.clip.grade),+ color: specColor(sp.asset),mask: undefined as SpecMask | undefined,shadow: undefined as SpecMask | undefined,kf: posed(sp.clip).kf,@@ -1093,6 +1120,7 @@ export async function buildExportPayload(smoothSlow: c.smoothSlow,image: assetById.get(c.assetId)!.type === "image",grade: normalizeGrade(c.grade),+ color: specColor(assetById.get(c.assetId)),look: c.look,lookAmount: c.lookAmount,mask: undefined as SpecMask | undefined,@@ -1176,6 +1204,24 @@ export async function buildExportPayload(}}+ // The library LUTs the grades name travel with the job, once per file, so+ // the engine parses the same bytes the tab drew through. One that cannot+ // be read fails the export here, naming it.+ const lutFiles = new Map<string, string>();+ for (const entry of [...clipEntries, ...overlayVideos]) {+ const id = lutIdOf(entry.grade);+ if (!id) continue;+ let file = lutFiles.get(id);+ if (!file) {+ const { fileName, bytes } = await loadLibraryLutFile(id);+ const ext = /\.([a-z0-9]+)$/i.exec(fileName)?.[1]?.toLowerCase() ?? "cube";+ file = `lut_${id.replace(/^lut:/, "").replace(/[^a-z0-9]/gi, "")}.${ext}`;+ pngs.push({ name: file, blob: new Blob([bytes as BlobPart]) });+ lutFiles.set(id, file);+ }+ entry.color = { ...entry.color, lutFile: file };+ }+const audio = doc.audioClips.filter((a) => !a.hidden && a.start < duration && assetById.has(a.assetId)).map((a) => ({@@ -1333,6 +1379,11 @@ export async function buildExportPayload(target,...settings,...(target === "export" ? { sourceSegments: sourceExportPlan(doc, settings) ?? undefined } : {}),+ // The hover proxy, the share card and the streaming ladder are SDR web+ // pictures whatever the project delivers.+ colorSpace: target === "export" ? doc.colorSpace ?? "sdr" : "sdr",+ lutSize: cutColor().lutSize,+ lutSizeWide: cutColor().lutSizeWide,duration,background: projectBackground(doc.background),clips,@@ -1479,14 +1530,20 @@ export function downloadExport(jobId: string, outName: string, backend: CutBacke* not know — a range export would come back as the whole cut, a typed name* as the project's — so what the settings ask of the engine is checked* against what it says it carries, and the export refuses with the fix. */-async function assertEngineCarries(settings: ExportSettings): Promise<void> {+async function assertEngineCarries(settings: ExportSettings, doc: ExportDoc): Promise<void> {const wants: [EngineFeature, boolean, string][] = [+ // The color pipeline: an engine from before it grades nothing and folds+ // a log or HDR file the old way, so every export needs it.+ ["color.v2", true, "export this cut"],["export.range", !!settings.range, "export a range"],["export.name", !!settings.name, "name the file"],// An engine that does not know the codec falls through to H.264, which// would hand back a .mov of exactly the picture the master was chosen to// avoid.["export.prores4444", settings.codec === "prores4444", "export a ProRes 4444 master"],+ // An engine from before HDR composites at 8 bits in BT.709 and tags the+ // file so; the HLG or PQ picture would land as a wrong SDR file.+ ["export.hdr", (doc.colorSpace ?? "sdr") !== "sdr", "export HDR"],];const has = await engineFeatures();for (const [feature, wanted, what] of wants) {@@ -1507,7 +1564,7 @@ export async function createExportJob(): Promise<string> {const backend = projectOperation(projectId).backend;const outName = exportOutName(settings);- if (backend.kind === "local") await assertEngineCarries(settings);+ if (backend.kind === "local") await assertEngineCarries(settings, doc);const payload = await buildExportPayload(projectId, doc, settings, "export");const res = await postExport(projectId, payload, outName, backend);const body = await apiJson<{ id?: string }>(res);@@ -1644,7 +1701,7 @@ async function runEngineExport(opts: NonNullable<Parameters<typeof runBrowserExport>[3]>,backend: CutBackend): Promise<string> {- await assertEngineCarries(settings);+ await assertEngineCarries(settings, doc);const claim = await backend.fetch("/api/cut/export/client", {method: "POST",headers: { "Content-Type": "application/json" },@@ -1934,7 +1991,8 @@ export async function submitPreviewSnapshot(if (!directory) throw new Error("Project not found in browser storage.");holdRegistered(`/api/cut/projects/${projectId}/`);try {- const rendered = await canRenderInBrowser(doc, settings)+ // The hover preview is an SDR web picture whatever the project delivers.+ const rendered = await canRenderInBrowser(doc, settings, "sdr")? await renderProjectToMp4(doc, settings, {resolve: (asset) => asset.url, signal,onProgress: ({ ratio }) => onProgress("Rendering", ratio),diff --git a/site/src/cut/lib/exportColor.test.ts b/site/src/cut/lib/exportColor.test.tsnew file mode 100644index 00000000..586e4074--- /dev/null+++ b/site/src/cut/lib/exportColor.test.ts@@ -0,0 +1,94 @@+import { expect, test } from "bun:test";+import { stubModule } from "@/lib/testing/stubModule";+import type { ExportDoc } from "@/cut/lib/renderSnapshot";++// The export spec's color: what each clip's code values mean, and the+// library LUTs its grades name staged beside the pictures, once per file.++const CUBE = 'TITLE "warm"\nLUT_3D_SIZE 2\n0 0 0\n1 0 0\n0 1 0\n1 1 0\n0 0 1\n1 0 1\n0 1 1\n1 1 1\n';++await stubModule<typeof import("./linkedLibrary/luts")>("./linkedLibrary/luts", import.meta.url, {+ loadLibraryLutFile: async (id) => {+ if (id === "lut:abc123") return { fileName: "Warm Film.cube", bytes: new TextEncoder().encode(CUBE) };+ throw new Error(`The LUT "Broken" could not be read.`);+ },+});++const { buildExportPayload, originalSettings } = await import("./exportClient");+const { registerBlobFile } = await import("./backend/browser/registry");+const { movieHeader } = await import("./fixtures/movieHeader");++// Footage imported before its color was read: the spec builder reads the+// header itself. This one is an HLG phone clip.+const plainUrl = registerBlobFile(+ "/api/cut/projects/project/media/plain.mp4",+ new File([movieHeader({ primaries: 9, transfer: 18, matrix: 9 }) as BlobPart], "plain.mp4")+);++const doc: ExportDoc = {+ aspect: "16:9",+ assets: [+ { id: "log", fileName: "log.mov", name: "Log", type: "video", duration: 10, width: 1920, height: 1080, url: "",+ color: { matrix: "bt2020nc", fullRange: false, bitDepth: 10, detected: "apple-log" } },+ { id: "sd", fileName: "sd.mp4", name: "SD", type: "video", duration: 10, width: 640, height: 480, url: "",+ color: { matrix: "bt601", fullRange: true, bitDepth: 8, detected: "rec709" }, colorProfile: "srgb" },+ { id: "plain", fileName: "plain.mp4", name: "Plain", type: "video", duration: 10, width: 1920, height: 1080, url: plainUrl },+ { id: "still", fileName: "still.png", name: "Still", type: "image", duration: 5, width: 800, height: 600, url: "" },+ ],+ clips: [+ { id: "c1", assetId: "log", track: 0, start: 0, in: 0, out: 2, muted: false, grade: { lut: { id: "lut:abc123" }, exposure: 5 } },+ { id: "c2", assetId: "sd", track: 0, start: 2, in: 0, out: 2, muted: false },+ { id: "c3", assetId: "plain", track: 0, start: 4, in: 0, out: 2, muted: false, grade: { lut: { id: "lut:abc123", amount: 0.5 } } },+ { id: "o1", assetId: "still", track: 1, start: 0, in: 0, out: 2, muted: true, grade: { lut: { id: "lut:abc123" } } },+ ],+ audioClips: [],+ overlays: [],+ subtitles: { cues: [], showOnVideo: false, showOnTimeline: false },+};++test("every clip carries its color, and a library LUT travels once by content key", async () => {+ const settings = originalSettings(doc.aspect, doc.clips, doc.assets, doc);+ const payload = await buildExportPayload("project", doc, settings, "export");+ const spec = payload.spec as {+ colorSpace: string;+ lutSize: number;+ lutSizeWide: number;+ clips: { file: string; color?: Record<string, unknown> }[];+ overlayVideos: { file: string; color?: Record<string, unknown> }[];+ };+ expect(spec).toMatchObject({ colorSpace: "sdr", lutSize: 33, lutSizeWide: 65 });+ const byFile = new Map(spec.clips.map((c) => [c.file, c.color]));+ expect(byFile.get("log.mov")).toEqual({ profile: "apple-log", matrix: "bt2020nc", fullRange: false, lutFile: "lut_abc123.cube" });+ expect(byFile.get("sd.mp4")).toEqual({ profile: "srgb", matrix: "bt601", fullRange: true });+ expect(byFile.get("plain.mp4")).toEqual({ profile: "hlg", matrix: "bt2020nc", fullRange: false, lutFile: "lut_abc123.cube" });+ expect(spec.overlayVideos[0].color).toEqual({ profile: "srgb", matrix: "bt709", fullRange: true, lutFile: "lut_abc123.cube" });+ const luts = payload.pngs.filter((p) => p.name.endsWith(".cube"));+ expect(luts.map((p) => p.name)).toEqual(["lut_abc123.cube"]);+ expect(await luts[0].blob.text()).toBe(CUBE);+ // A converted source never rides the packet copy.+ expect("sourceSegments" in spec && (spec as { sourceSegments?: unknown }).sourceSegments).toBeFalsy();+});++test("a LUT that cannot be read fails the export, naming it", async () => {+ const broken: ExportDoc = {+ ...doc,+ clips: [{ id: "c1", assetId: "plain", track: 0, start: 0, in: 0, out: 2, muted: false, grade: { lut: { id: "lut:gone" } } }],+ };+ const settings = originalSettings(broken.aspect, broken.clips, broken.assets, broken);+ await expect(buildExportPayload("project", broken, settings, "export")).rejects.toThrow(/The LUT "Broken" could not be read/);+});++test("a source profile set before the header was read still exports the file's own code values", async () => {+ // An HLG clip imported before its color was read, set to Apple Log by hand:+ // the override names the profile, and the header read still supplies the+ // matrix and range.+ const overridden: ExportDoc = {+ ...doc,+ assets: doc.assets.map((a) => (a.id === "plain" ? { ...a, colorProfile: "apple-log" as const } : a)),+ clips: [{ id: "c1", assetId: "plain", track: 0, start: 0, in: 0, out: 2, muted: false }],+ };+ const settings = originalSettings(overridden.aspect, overridden.clips, overridden.assets, overridden);+ const payload = await buildExportPayload("project", overridden, settings, "export");+ const spec = payload.spec as { clips: { file: string; color?: Record<string, unknown> }[] };+ expect(spec.clips[0].color).toEqual({ profile: "apple-log", matrix: "bt2020nc", fullRange: false });+});diff --git a/site/src/cut/lib/exportDelivery.ts b/site/src/cut/lib/exportDelivery.tsindex b254584a..2a81ca14 100644--- a/site/src/cut/lib/exportDelivery.ts+++ b/site/src/cut/lib/exportDelivery.ts@@ -4,7 +4,20 @@* cloud routes and the worker all read the one table.*/+import type { CodeFormat, SourceProfile } from "@donkeycut/effects-kit";+export type ExportCodec = "h264" | "hevc" | "prores" | "prores4444";++/** What a clip's code values mean, as the tab settled it from the file's+ * header (and the person's override): the profile the color pipeline+ * converts from, and the matrix and range ffmpeg decodes the Y'CbCr with. */+export interface SpecClipColor {+ profile: SourceProfile;+ matrix: CodeFormat["matrix"];+ fullRange: boolean;+ /** The library LUT the grade names, staged in the job dir by base name. */+ lutFile?: string;+}export type ExportContainer = "mp4" | "mov";export type ExportAudioCodec = "aac" | "pcm";diff --git a/site/src/cut/lib/exportPreviewColor.test.ts b/site/src/cut/lib/exportPreviewColor.test.tsnew file mode 100644index 00000000..f692fec6--- /dev/null+++ b/site/src/cut/lib/exportPreviewColor.test.ts@@ -0,0 +1,45 @@+import { afterEach, expect, spyOn, test } from "bun:test";+import * as opfs from "./backend/browser/opfs";+import * as exportClient from "./exportClient";+import * as exportRender from "./exportRender";+import type { RenderSnapshot } from "./renderSnapshot";++const restores: (() => void)[] = [];+afterEach(() => {+ for (const restore of restores.splice(0)) restore();+});++const hdrDoc = {+ aspect: "16:9",+ assets: [],+ clips: [],+ audioClips: [],+ overlays: [],+ subtitles: { cues: [], showOnVideo: false, showOnTimeline: false },+ colorSpace: "hlg",+} as unknown as RenderSnapshot["doc"];++test("an HDR delivery never renders in the tab", async () => {+ const settings = exportClient.previewSettings("16:9");+ expect(await exportRender.canRenderInBrowser(hdrDoc, settings, "hlg")).toBe(false);+});++test("the hover preview of an HDR project asks for an SDR render", async () => {+ const dir = spyOn(opfs, "projectDir").mockResolvedValue({} as FileSystemDirectoryHandle);+ restores.push(() => dir.mockRestore());+ const asked: unknown[] = [];+ const probe = spyOn(exportRender, "canRenderInBrowser").mockImplementation(async (_doc, _settings, output) => {+ asked.push(output);+ throw new Error("stop here");+ });+ restores.push(() => probe.mockRestore());+ const snapshot = {+ operation: { projectId: "p", backend: { kind: "browser" } },+ revision: "r",+ doc: hdrDoc,+ } as unknown as RenderSnapshot;+ await expect(exportClient.submitPreviewSnapshot(snapshot)).rejects.toThrow("stop here");+ // The hover preview is an SDR web picture: the tab carries it, and the+ // project's media stays home.+ expect(asked).toEqual(["sdr"]);+});diff --git a/site/src/cut/lib/exportRender.ts b/site/src/cut/lib/exportRender.tsindex 21198ed7..4a273d7d 100644--- a/site/src/cut/lib/exportRender.ts+++ b/site/src/cut/lib/exportRender.ts@@ -33,8 +33,11 @@ import { drawBlock } from "./blockSource";import { audioFxSpans } from "./audioEffects";import { renderMix, type MixClip, type MixItem, type MixSpec } from "./audioMix";import { FrameCompositor, MISSING_FRAME, type Frame } from "./composite";+import { ensureClipLuts, sourceLookup } from "./lutBuild";+import { colorRead, type ColorRead, type ReadFile } from "./sourceColor";+import type { OutputSpace } from "@donkeycut/effects-kit";import { overlayPlan, trackZeroPlan } from "./framePlan";-import { frameSink, keyframeTimeAt, openMedia, videoTrackOf } from "./mediaRead";+import { frameSink, keyframeTimeAt, openMedia, videoTrackOf, withAssetColors } from "./mediaRead";import type { InputVideoTrack, WrappedCanvas } from "mediabunny";import { allowance, canvasBytes, holdMemory } from "./memoryBudget";import { getClipSpans, overlayLayers, projectDuration, spanSequence } from "./store";@@ -301,6 +304,18 @@ const frameOfWrapped = (wrapped: WrappedCanvas): Frame => ({height: wrapped.canvas.height,});+/** The file a render reads: an asset's master, never the preview proxy. The+ * readers open it and the compositors take their recipes from it through+ * this one choice, so a frame is always drawn through the recipe of the read+ * that produced it. */+export const renderFile = (): ReadFile => "master";++/** Settle the drawn matrix of every master the render reads, so the recipes+ * built before its first frame are the final ones. */+export async function settleRenderColor(assets: readonly Pick<MediaAsset, "color" | "type">[]): Promise<void> {+ await Promise.all(assets.filter((a) => a.type === "video").map((a) => colorRead(a, renderFile()).settled()));+}+/** A clip's source time at timeline time `t`. */function sourceTimeAt(span: ClipSpan, t: number): number {return retimeOf(span.clip).srcAt(Math.max(0, t - span.start));@@ -338,6 +353,8 @@ export class ClipReader {/** The frame number this reader was last asked for, for the painter's* between-frames eviction. */usedAt = 0;+ /** How this reader reads its file, and the recipe its frames mean. */+ readonly colorRead: ColorRead;/*** Pixels in a frame of the source.@@ -366,7 +383,19 @@ export class ClipReader {* render is running is picked up rather than the render dying on the* snapshot's expired one. */private url: () => string- ) {}+ ) {+ this.colorRead = colorRead(asset, renderFile());+ }++ /** The sink options every reader of this source opens with. */+ private sinkOptions(poolSize: number) {+ const colorSpace = this.colorRead.colorSpace;+ return {+ poolSize,+ ...(this.software ? { software: true } : {}),+ ...(colorSpace ? { colorSpace } : {}),+ };+ }/** Open the source and hand back its frame reader, or null when it has no* readable picture (a still, which is served from `this.still`, or a source@@ -401,10 +430,7 @@ export class ClipReader {this.track = track;// A small pool keeps the render's canvas allocation flat over thousands// of frames.- this.sink = frameSink(track, undefined, {- poolSize: READER_POOL,- ...(this.software ? { software: true } : {}),- });+ this.sink = frameSink(track, undefined, this.sinkOptions(READER_POOL));return this.sink;})());}@@ -504,10 +530,7 @@ export class ClipReader {const kt = await keyframeTimeAt(this.track, Math.max(0, at));if (kt === null) return null;const window = this.windowFrames;- this.backSink ??= frameSink(this.track, undefined, {- poolSize: window + 3,- ...(this.software ? { software: true } : {}),- });+ this.backSink ??= frameSink(this.track, undefined, this.sinkOptions(window + 3));const start = Math.max(kt, at - (window - 1) * this.frameDt, 0);const frames: WrappedCanvas[] = [];const stream = this.backSink.canvases(start);@@ -1246,6 +1269,11 @@ export class FramePainter {) {this.comp = new FrameCompositor(canvas);this.comp.background = projectBackground(doc.background);+ // Every frame of a render goes through its clip's own LUT, built before+ // the first frame (prepare) and on this thread if it ever falls out of+ // the cache.+ this.comp.colorMode = "exact";+ this.comp.sourceProvider = sourceLookup(doc.assets, renderFile);this.stamps = new StampCache(canvas.width, canvas.height, doc.assets);this.duration = projectDuration(doc);}@@ -1253,6 +1281,12 @@ export class FramePainter {/** Make the text layers, the span geometry and the subject pass resident.* Runs once, before the first frame. */async prepare(): Promise<void> {+ // Footage the lazy fill has not reached reads its color here, before any+ // recipe is built from it.+ this.doc = { ...this.doc, assets: await withAssetColors(this.doc.assets, this.doc, this.resolve) };+ this.comp.sourceProvider = sourceLookup(this.doc.assets, renderFile);+ await settleRenderColor(this.doc.assets);+ await ensureClipLuts(this.doc.clips.map((c) => this.comp.recipeFor(c)));this.stacked = [...(await stampText(this.doc))].sort((a, b) => b.stackLane - a.stackLane);// The subject pass is created only when something reads the person matte;// prepare() makes rasters and the segmenter resident before the first@@ -1582,10 +1616,16 @@ export async function renderProjectFrame(*/export async function canRenderInBrowser(doc: ExportDoc,- settings: ExportSettings+ settings: ExportSettings,+ /** The color space the file is delivered in: the project's for an export,+ * SDR for the web pictures (hover preview, share card, stream). */+ output: OutputSpace): Promise<boolean> {const duration = projectDuration(doc);if (!(deliverySpan(settings.range, duration) > 0)) return false;+ // The tab composites on 8-bit canvases; an HDR delivery is a 10-bit+ // composite, which the engine and the worker build in ffmpeg.+ if (output !== "sdr") return false;if (typeof navigator.storage?.getDirectory !== "function" ||typeof FileSystemFileHandle === "undefined" ||diff --git a/site/src/cut/lib/exportStore.ts b/site/src/cut/lib/exportStore.tsindex 686a051a..da46d02f 100644--- a/site/src/cut/lib/exportStore.ts+++ b/site/src/cut/lib/exportStore.ts@@ -124,7 +124,7 @@ export const useExports = create<ExportsState>((set, get) => ({// worker for a cloud one, and the worker again for a browser project,// whose media goes up with the job and whose file comes back into its own// storage. Whatever the user chose, something renders it.- const inBrowser = await canRenderInBrowser(doc, settings);+ const inBrowser = await canRenderInBrowser(doc, settings, doc.colorSpace ?? "sdr");const tabOwned = backend.kind !== "local" || inBrowser;const abort = tabOwned ? new AbortController() : undefined;set((s) => ({diff --git a/site/src/cut/lib/fixtures/movieHeader.ts b/site/src/cut/lib/fixtures/movieHeader.tsnew file mode 100644index 00000000..bb7e4619--- /dev/null+++ b/site/src/cut/lib/fixtures/movieHeader.ts@@ -0,0 +1,37 @@+/** A MOV/MP4 of headers alone: ftyp, a small data box and a movie header+ * whose one video track's sample entry carries `colr` — enough for the+ * color probe (colorProbe.ts) to settle a file's color in tests. */++const str = (s: string) => new Uint8Array([...s].map((c) => c.charCodeAt(0)));+const u16 = (n: number) => new Uint8Array([(n >> 8) & 0xff, n & 0xff]);+const u32 = (n: number) => new Uint8Array([(n >>> 24) & 0xff, (n >>> 16) & 0xff, (n >>> 8) & 0xff, n & 0xff]);+const cat = (...parts: Uint8Array[]) => {+ const out = new Uint8Array(parts.reduce((n, p) => n + p.length, 0));+ let at = 0;+ for (const p of parts) {+ out.set(p, at);+ at += p.length;+ }+ return out;+};+const box = (type: string, ...payload: Uint8Array[]) => {+ const body = cat(...payload);+ return cat(u32(8 + body.length), str(type), body);+};+const fullBox = (type: string, ...payload: Uint8Array[]) => box(type, u32(0), ...payload);++/** The file's bytes, tagged with `colr` nclx codes. */+export function movieHeader(tags: { primaries: number; transfer: number; matrix: number; fullRange?: boolean }): Uint8Array {+ const colr = box(+ "colr",+ str("nclx"),+ u16(tags.primaries),+ u16(tags.transfer),+ u16(tags.matrix),+ new Uint8Array([tags.fullRange ? 0x80 : 0])+ );+ const entry = box("avc1", new Uint8Array(78), colr);+ const hdlr = fullBox("hdlr", u32(0), str("vide"), new Uint8Array(12), new Uint8Array([0]));+ const trak = box("trak", box("mdia", hdlr, box("minf", box("stbl", fullBox("stsd", u32(1), entry)))));+ return cat(box("ftyp", str("isom"), u32(0)), box("mdat", new Uint8Array(64)), box("moov", trak));+}diff --git a/site/src/cut/lib/fixtures/prores-422hq-10bit.mov b/site/src/cut/lib/fixtures/prores-422hq-10bit.movnew file mode 100644index 00000000..346d6937Binary files /dev/null and b/site/src/cut/lib/fixtures/prores-422hq-10bit.mov differdiff --git a/site/src/cut/lib/frameSource.test.ts b/site/src/cut/lib/frameSource.test.tsindex 2a399ed5..5661816d 100644--- a/site/src/cut/lib/frameSource.test.ts+++ b/site/src/cut/lib/frameSource.test.ts@@ -112,6 +112,14 @@ await stubModule<typeof import("./mediaRead")>("./mediaRead", import.meta.url, {keyframeTimeAt,});+/** Proxies a reader reported as unopenable. */+const unopenable: MediaAsset[] = [];+await stubModule<typeof import("./mediaProxy")>("./mediaProxy", import.meta.url, {+ proxyUnreadable: (async (a: MediaAsset) => {+ unopenable.push(a);+ }) as never,+});+const { BACK_WINDOW, ClipFrameSource, FrameRing, FrameSourcePool, mappingKey, walkClaim } =await import("./frameSource");@@ -425,6 +433,26 @@ describe("FrameSourcePool", () => {expect(pool.size).toBe(1);});+ test("a source moves onto the proxy the moment it lands", () => {+ // A ProRes master plays through the WASM decoder until its proxy is+ // written onto the asset; the same mapping then reads the proxy's URL,+ // in place, with nothing reloaded.+ const pool = new FrameSourcePool(4);+ pool.beginFrame();+ const master = asset("a");+ const before = pool.get("k", master, 480);+ expect(before.url).toBe(master.url);+ const proxied = {+ ...master,+ proxy: { fileName: "a.proxy.mp4", sizeBytes: 1 },+ proxyUrl: "https://example.test/a.proxy.mp4",+ };+ const after = pool.get("k", proxied, 480);+ expect(after).toBe(before);+ expect(after.url).toBe(proxied.proxyUrl);+ expect(pool.size).toBe(1);+ });+test("suspends the least recently asked-for, never this frame's", () => {const pool = new FrameSourcePool(2);pool.beginFrame();@@ -606,6 +634,34 @@ describe("ClipFrameSource retarget", () => {src.close();});+ test("a proxy that will not open hands the source back to the master", async () => {+ // A copied project once named a proxy file it never received: the source+ // retried that address forever and the clip stayed black. The reader+ // reports it, the store drops the proxy, and the pool moves the source+ // onto the master.+ reset();+ unopenable.length = 0;+ const pool = new FrameSourcePool(4);+ pool.beginFrame();+ const master = asset("lost");+ const proxied = { ...master, proxy: { fileName: "lost.proxy.mp4", sizeBytes: 1 }, proxyUrl: "https://example.test/lost.proxy.mp4" };+ gate(proxied.proxyUrl).refuse();+ const src = pool.get("k", proxied, 360);+ src.want(0.1, true);+ await settle();+ expect(unopenable.map((a) => a.id)).toEqual(["lost"]);+ expect(src.failed).toBe(true);+ // What proxyUnreadable does to the store: the asset loses its proxy.+ expect(pool.get("k", master, 360)).toBe(src);+ expect(src.url).toBe(master.url);+ expect(src.failed).toBe(false);+ src.want(0.1, true);+ await settle();+ expect(src.frameAt(0.1)).not.toBeNull();+ expect(sinkWalks[sinkWalks.length - 1].url).toBe(master.url);+ pool.dispose();+ });+test("a new address that will not open leaves the picture standing", async () => {reset();const before = asset("stay");@@ -628,6 +684,81 @@ describe("ClipFrameSource retarget", () => {});});+describe("ClipFrameSource held frames keep their read", () => {+ // A full-range master reads full range; its proxy is limited-range Rec.709.+ // A frame decoded from one keeps meaning what it meant when the source moves+ // to the other, until frames off the new file replace it.+ const color = { matrix: "bt709", fullRange: true, bitDepth: 8, detected: "rec709", codec: "avc1" } as const;+ const master = (): MediaAsset => ({ ...asset("held"), color: { ...color } });+ const proxied = (): MediaAsset => ({+ ...master(),+ proxy: { fileName: "held.proxy.mp4", sizeBytes: 1 },+ proxyUrl: "https://example.test/held.proxy.mp4",+ });+ const rangeOf = (read: { recipe(): { fullRange?: boolean } } | undefined) => read?.recipe().fullRange;++ test("a master frame held after its proxy lands is read as the master", async () => {+ inputs.length = 0;+ sinkWalks.length = 0;+ gates.clear();+ const src = new ClipFrameSource(master(), 360);+ src.want(0.1, true);+ await settle();+ expect(rangeOf(src.frameAt(0.1)!.read)).toBe(true);+ src.retarget(proxied());+ await settle();+ // Paused on the same moment: the held master frame answers exactly, so+ // nothing re-decodes it, and it keeps the master's read while the source+ // itself now reads the proxy.+ src.want(0.1, false);+ await settle();+ expect(src.hasExact(0.1)).toBe(true);+ expect(rangeOf(src.colorRead)).toBe(false);+ expect(rangeOf(src.frameAt(0.1)!.read)).toBe(true);+ expect(rangeOf(src.shownColorRead)).toBe(true);+ // Frames the walk lands off the proxy read as the proxy.+ src.want(2, true);+ await settle();+ expect(sinkWalks[sinkWalks.length - 1].url).toBe(proxied().proxyUrl!);+ expect(rangeOf(src.frameAt(2)!.read)).toBe(false);+ expect(rangeOf(src.shownColorRead)).toBe(false);+ src.close();+ });++ test("a proxy frame held after the fallback to the master is read as the proxy", async () => {+ inputs.length = 0;+ sinkWalks.length = 0;+ gates.clear();+ const src = new ClipFrameSource(proxied(), 360);+ src.want(0.1, true);+ await settle();+ expect(rangeOf(src.frameAt(0.1)!.read)).toBe(false);+ src.retarget(master());+ await settle();+ src.want(0.1, false);+ await settle();+ expect(rangeOf(src.colorRead)).toBe(true);+ expect(rangeOf(src.frameAt(0.1)!.read)).toBe(false);+ src.want(2, true);+ await settle();+ expect(sinkWalks[sinkWalks.length - 1].url).toBe(master().url);+ expect(rangeOf(src.frameAt(2)!.read)).toBe(true);+ src.close();+ });++ test("a profile override reaches a held frame at once", async () => {+ inputs.length = 0;+ sinkWalks.length = 0;+ gates.clear();+ const src = new ClipFrameSource(master(), 360);+ src.want(0.1, true);+ await settle();+ src.follow({ ...master(), colorProfile: "srgb" });+ expect(src.frameAt(0.1)!.read!.recipe().profile).toBe("srgb");+ src.close();+ });+});+describe("ClipFrameSource replay", () => {test("a playing reader back at a clip's head gets a fresh walk", async () => {// The cut played once: the walk read the clip from 2s to its end at 5s anddiff --git a/site/src/cut/lib/frameSource.ts b/site/src/cut/lib/frameSource.tsindex a41212dc..cc63bdf3 100644--- a/site/src/cut/lib/frameSource.ts+++ b/site/src/cut/lib/frameSource.ts@@ -37,7 +37,12 @@ import {import { allowance, canvasBytes, decodedFrameBytes, holdMemory } from "./memoryBudget";import { meterPull, meterSource, meterWalk } from "./perfTrace";import { drawBlock } from "./blockSource";-import type { MediaAsset } from "./types";+import { colorRead, fileAt, type ColorRead, type ReadFile } from "./sourceColor";+import { previewUrl, type MediaAsset } from "./types";++const sameColorSpace = (a: VideoColorSpaceInit | undefined, b: VideoColorSpaceInit | undefined): boolean =>+ a === b ||+ (!!a && !!b && a.primaries === b.primaries && a.transfer === b.transfer && a.matrix === b.matrix && a.fullRange === b.fullRange);/** Dev-only: pool lifecycle events, into the same log the engine writes.* Bounded so an ordinary dev session never accumulates it. */@@ -350,14 +355,28 @@ export interface SourceFrame {/** The frame's own timestamp in the source, for telling a held frame from a* fresh one. */timestamp: number;+ /** How this frame's code values are read: the read of the file and sink+ * it was decoded on, which a held frame keeps across a change of file. */+ read?: ColorRead;+}++/** The stack a frame was decoded on: which of the asset's files, the tag its+ * sink read it under, and the asset record the stack opened with. */+interface DecodedAs {+ file: ReadFile;+ colorSpace: VideoColorSpaceInit | undefined;+ asset: MediaAsset;}-const frameOfCanvas = (c: WrappedCanvas): SourceFrame => ({- image: c.canvas,- width: c.canvas.width,- height: c.canvas.height,- timestamp: c.timestamp,-});+/** A decoded canvas as the rings hold it, tagged with the stack it came off. */+type HeldCanvas = WrappedCanvas & { as?: DecodedAs | null };++/** Tag a frame with the stack it came off, in place: the rings hold the+ * sink's own objects, so the tag costs no allocation. */+const tagged = (c: WrappedCanvas, as: DecodedAs | null): HeldCanvas => {+ (c as HeldCanvas).as = as;+ return c;+};/** What the ring stores: a frame and the stretch of source it stands for. */export interface Timed {@@ -509,9 +528,9 @@ export class FrameRing<T extends Timed> {interface BackWalk {/** The fine windows landed, newest at the bottom. Bounded by arrival to* what the backward sink's pool still holds. */- fine: FrameRing<WrappedCanvas>;+ fine: FrameRing<HeldCanvas>;/** The coarse spread over the keyframe span, at half size. */- coarse: FrameRing<WrappedCanvas>;+ coarse: FrameRing<HeldCanvas>;/** The lowest fine frame landed. */floor: number;/** The moment the pointer last asked for. */@@ -544,7 +563,17 @@ export class ClipFrameSource {private reader: MediaHandle | null = null;private track: InputVideoTrack | null = null;private sink: FrameCanvasSink | null = null;- private ring = new FrameRing<WrappedCanvas>(RING);+ private ring = new FrameRing<HeldCanvas>(RING);+ /** The stack the installed track and sink belong to. Frames decoded on it+ * carry it, so a frame held across a move to another file keeps the read+ * it was decoded under. */+ private decodedAs: DecodedAs | null = null;+ /** The stack the forward walk and the backward sinks decode on. */+ private streamAs: DecodedAs | null = null;+ private backAs: DecodedAs | null = null;+ private backCoarseAs: DecodedAs | null = null;+ /** The stack of the frame `frameAt` last handed out. */+ private shownAs: DecodedAs | null = null;/** A still's single frame; stills never stream. */private still: SourceFrame | null = null;private opening: Promise<void> | null = null;@@ -557,6 +586,8 @@ export class ClipFrameSource {private ahead = DECODE_AHEAD_S;/** Set when the file turns out to hold no picture this browser can read. */private unreadable = false;+ /** Parked on a proxy that would not open, until the store drops it. */+ private proxyDown = false;/** Failed opens so far, and the timer that will clear `unreadable` for the* next try. */private attempts = 0;@@ -725,10 +756,65 @@ export class ClipFrameSource {return this.asleep ? 0 : decodedFrameBytes(this.decodePixels) * DECODER_FRAMES;}- /** The URL this source is reading. The pool compares it against the store's- * current one, so a re-minted signed URL replaces the source under it. */+ /** The URL this source is reading — the proxy when the asset has one. The+ * pool compares it against the store's current one, so a re-minted signed+ * URL, or a proxy that just landed, replaces the source under it. */get url(): string {- return this.asset.url;+ return previewUrl(this.asset);+ }++ /** Which of the asset's files this source reads. */+ get file(): ReadFile {+ return fileAt(this.asset, this.url);+ }++ /** How this source's frames are read and what they mean: the sink's color+ * space, and the recipe the compositor draws them through+ * (`colorRead`, sourceColor.ts). Both come from the file this source+ * reads, so they follow it wherever it moves. */+ get colorRead(): ColorRead {+ return colorRead(this.asset, this.file);+ }++ private get decodeColorSpace(): VideoColorSpaceInit | undefined {+ return this.colorRead.colorSpace;+ }++ /** The stack a reader opened now would be: this address, read this way. */+ private stackNow(): DecodedAs {+ return { file: this.file, colorSpace: this.decodeColorSpace, asset: this.asset };+ }++ /** How frames decoded on `as` are read. The asset's live record decides+ * while it tags the sink the same way — a profile override reaches a held+ * frame at once — and the record the stack opened with otherwise, since+ * the pixels were decoded under that tag. */+ private readOf(as: DecodedAs | null | undefined): ColorRead {+ if (!as) return this.colorRead;+ const live = colorRead(this.asset, as.file);+ return sameColorSpace(live.colorSpace, as.colorSpace) ? live : colorRead(as.asset, as.file);+ }++ /** How the frame this source last handed out is read: what an analysis of+ * that frame (the color panel's scopes and Auto) reads it through. */+ get shownColorRead(): ColorRead {+ return this.still ? this.colorRead : this.readOf(this.shownAs);+ }++ private frameOf(c: HeldCanvas): SourceFrame {+ return { image: c.canvas, width: c.canvas.width, height: c.canvas.height, timestamp: c.timestamp, read: this.readOf(c.as) };+ }++ /** Take the store's newer record of the asset at the same address. A+ * color record that changes how the file is decoded — a master's color+ * read after it opened — reopens the reader behind the frames it holds;+ * any other change (a profile override, a new strip) is picked up as is,+ * and the next recipe follows it. */+ follow(asset: MediaAsset): void {+ if (asset === this.asset) return;+ const next = colorRead(asset, fileAt(asset, this.url)).colorSpace;+ if (sameColorSpace(next, this.decodeColorSpace)) this.asset = asset;+ else this.retarget(asset);}constructor(@@ -767,7 +853,7 @@ export class ClipFrameSource {/** What this source is doing, for the perf eval's pool dump. */debugState(): Record<string, unknown> {return {- url: this.asset.url.slice(-24),+ url: this.url.slice(-24),ring: this.ring.size,oldest: this.ring.size ? +this.ring.oldest.toFixed(2) : null,newest: this.ring.size ? +this.ring.newest.toFixed(2) : null,@@ -853,7 +939,9 @@ export class ClipFrameSource {const rough = b.coarse.atNearest(t, from, to);if (rough && (!c || Math.abs(rough.timestamp - t) < Math.abs(c.timestamp - t))) c = rough;}- return c ? frameOfCanvas(c) : null;+ if (!c) return null;+ this.shownAs = c.as ?? null;+ return this.frameOf(c);}/**@@ -875,7 +963,9 @@ export class ClipFrameSource {let next = this.ring.after(a.timestamp, to);const other = fine?.after(a.timestamp, to) ?? null;if (other && (!next || other.timestamp < next.timestamp)) next = other;- return { a, b: next ? frameOfCanvas(next) : null };+ // A blend is drawn through one recipe, so both frames come off one stack.+ if (next && next.as !== sharp.as) next = null;+ return { a, b: next ? this.frameOf(next) : null };}/** Whether a frame covering `t` exactly is already held. Coarse frames do@@ -1014,6 +1104,7 @@ export class ClipFrameSource {this.streamDone = false;this.hopping = false;this.ring.clear();+ this.shownAs = null;this.dropBack(true);this.wanted = null;this.lastAsk = null;@@ -1055,7 +1146,17 @@ export class ClipFrameSource {if (this.closed || asset.type === "image") return;const aim = ++this.aim;// Nothing open and nothing opening: the next ask opens the new address.- if (!this.reader && !this.opening) return;+ // A source parked on a proxy that would not open is willing again, since+ // the address it failed on is gone.+ if (!this.reader && !this.opening) {+ if (this.proxyDown) {+ this.proxyDown = false;+ this.unreadable = false;+ this.attempts = 0;+ this.onFrame();+ }+ return;+ }void (async () => {// An open in flight built its stack for the old address; it settles// first, so the swap below replaces a stack that has stopped moving.@@ -1063,16 +1164,21 @@ export class ClipFrameSource {await this.opening;} catch {}if (this.closed || this.aim !== aim) return;- const reader = openMediaShared(this.asset.url);+ const as = this.stackNow();+ const reader = openMediaShared(this.url);try {const track = await videoTrackOf(reader.input);if (this.closed || this.aim !== aim) return reader.release();if (!track) {reader.release();- this.fail();+ if (!this.proxyFailed()) this.fail();return;}- const sink = frameSink(track, { height: this.height }, { poolSize: POOL, lowLatency: true });+ const sink = frameSink(+ track,+ { height: this.height },+ { poolSize: POOL, lowLatency: true, colorSpace: as.colorSpace }+ );// The new stack installs first, so a walk starting this instant is// already on it; the walk still running was on the old one and ends// now. Its frames stay: the old sink has stopped cycling its@@ -1083,6 +1189,7 @@ export class ClipFrameSource {this.reader = reader;this.track = track;this.sink = sink;+ this.decodedAs = as;this.opening = Promise.resolve();this.dropBack(true);this.stopStream();@@ -1095,6 +1202,7 @@ export class ClipFrameSource {this.shortEndAt = -1;this.failStreak = 0;this.unreadable = false;+ this.proxyDown = false;this.attempts = 0;// A paused reader is only asked again on a repaint; the nudge is what// sends its ask to the new stack.@@ -1104,11 +1212,27 @@ export class ClipFrameSource {// The old stack stays installed and keeps serving its ring; the// failure books the usual retries, and the retry's open reads the// current address.- if (this.aim === aim && !this.closed) this.fail();+ if (this.aim === aim && !this.closed && !this.proxyFailed()) this.fail();}})();}+ /**+ * A preview proxy would not open. The master is the same picture, so the+ * source parks until the store drops the proxy (`proxyUnreadable`), and the+ * pool then retargets it onto the master. False when the master itself is+ * what failed.+ */+ private proxyFailed(): boolean {+ const asset = this.asset;+ if (!asset.proxyUrl || this.url === asset.url) return false;+ this.opening = null;+ this.unreadable = true;+ this.proxyDown = true;+ void import("./mediaProxy").then((m) => m.proxyUnreadable(asset));+ return true;+ }+/*** An open failed. That is usually a moment — a network blip, a signed URL a* few seconds past its window — so the source tells the link keeper (which@@ -1139,12 +1263,13 @@ export class ClipFrameSource {private open(): Promise<void> {if (this.opening) return this.opening;this.opening = (async () => {- const reader = openMediaShared(this.asset.url);+ const as = this.stackNow();+ const reader = openMediaShared(this.url);try {const track = await videoTrackOf(reader.input);if (!track) {reader.release();- this.unreadable = true;+ if (!this.proxyFailed()) this.unreadable = true;return;}if (this.closed) {@@ -1166,13 +1291,18 @@ export class ClipFrameSource {// Height alone: the sink keeps the source's aspect and applies the// file's rotation, so a phone clip arrives upright at preview size and// no caller has to know it was ever sideways.- this.sink = frameSink(track, { height: this.height }, { poolSize: POOL, lowLatency: true });+ this.sink = frameSink(+ track,+ { height: this.height },+ { poolSize: POOL, lowLatency: true, colorSpace: as.colorSpace }+ );+ this.decodedAs = as;// A clean open ends any failure streak: the next outage starts from// the quick retries again.this.attempts = 0;} catch {reader.release();- this.fail();+ if (!this.proxyFailed()) this.fail();}})();return this.opening;@@ -1335,6 +1465,7 @@ export class ClipFrameSource {// The read may have been overtaken while the file was opening.if (Math.abs(this.streamFrom - from) > SAME) return;this.stream = this.sink.canvases(Math.max(0, from));+ this.streamAs = this.decodedAs;void this.drain(from);}@@ -1351,9 +1482,10 @@ export class ClipFrameSource {const kt = await keyframeTimeAt(this.track, Math.max(0, t)).catch(() => null);if (kt === null || this.closed) return;if (this.ring.between(kt, t) > 0) return;+ const as = this.decodedAs;const c = await this.sink.getCanvas(kt).catch(() => null);if (!c || this.closed) return;- this.ring.push(c);+ this.ring.push(tagged(c, as));this.onFrame();}@@ -1371,8 +1503,8 @@ export class ClipFrameSource {} else {this.onBack();this.back = {- fine: new FrameRing<WrappedCanvas>(BACK_POOL - 2),- coarse: new FrameRing<WrappedCanvas>(BACK_COARSE),+ fine: new FrameRing<HeldCanvas>(BACK_POOL - 2),+ coarse: new FrameRing<HeldCanvas>(BACK_COARSE),floor: Infinity,want: t,sentFor: null,@@ -1479,11 +1611,15 @@ export class ClipFrameSource {// over that prefix goes out from `backSpread` if the pointer gets there// before the windows do.if (b.prefix?.kt !== kt) b.prefix = start - kt > 2 * dt ? { kt, to: start - dt } : null;- this.backSink ??= frameSink(- this.track,- { height: this.height },- { poolSize: BACK_POOL, lowLatency: true }- );+ if (!this.backSink) {+ this.backAs = this.decodedAs;+ this.backSink = frameSink(+ this.track,+ { height: this.height },+ { poolSize: BACK_POOL, lowLatency: true, colorSpace: this.backAs?.colorSpace }+ );+ }+ const as = this.backAs;const stream = this.backSink.canvases(start);try {// The pass opens on the frame covering `start`, which can sit a frame@@ -1495,7 +1631,7 @@ export class ClipFrameSource {if (done || !value || this.closed || this.back !== b) break;if (value.duration > 0) this.frameDt = value.duration;if (value.timestamp > top + SAME) break;- b.fine.push(value);+ b.fine.push(tagged(value, as));b.floor = Math.min(b.floor, value.timestamp);b.landed++;n++;@@ -1525,11 +1661,15 @@ export class ClipFrameSource {if (n <= 0) return;const step = n > 1 ? (to - from) / (n - 1) : 0;const asks = Array.from({ length: n }, (_, i) => from + i * step);- this.backCoarseSink ??= frameSink(- this.track,- { height: Math.max(180, Math.round(this.height / 2)) },- { poolSize: BACK_COARSE_POOL, lowLatency: true }- );+ if (!this.backCoarseSink) {+ this.backCoarseAs = this.decodedAs;+ this.backCoarseSink = frameSink(+ this.track,+ { height: Math.max(180, Math.round(this.height / 2)) },+ { poolSize: BACK_COARSE_POOL, lowLatency: true, colorSpace: this.backCoarseAs?.colorSpace }+ );+ }+ const as = this.backCoarseAs;const stream = this.backCoarseSink.canvasesAtTimestamps(asks);try {let last = -1;@@ -1538,7 +1678,7 @@ export class ClipFrameSource {if (done || this.closed || this.back !== b) break;if (!value || value.timestamp === last) continue;last = value.timestamp;- b.coarse.push(value);+ b.coarse.push(tagged(value, as));this.onFrame();}} catch {@@ -1659,7 +1799,7 @@ export class ClipFrameSource {);}}- this.ring.push(value);+ this.ring.push(tagged(value, this.streamAs));this.onFrame();}} catch {@@ -1730,6 +1870,7 @@ export class ClipFrameSource {this.hopping = false;this.walkFor = t;this.stream = this.sink.canvases(Math.max(0, t));+ this.streamAs = this.decodedAs;await this.drain(t);// The walk ended before it reached the ask. Whatever ended it — bytes// that never came, a decoder closed under it — the pointer is left on@@ -1796,6 +1937,12 @@ export class FrameSourcePool {* `key` must identify a mapping — same file, speed and source-time offset —* so clips showing identical pictures share one decoder.*/+ /** The source for one clip mapping when it is open, without opening it or+ * touching its place in the eviction order. */+ peek(key: string, height: number): ClipFrameSource | undefined {+ return this.sources.get(`${key}|${height}`);+ }+get(key: string, asset: MediaAsset, height: number): ClipFrameSource {const id = `${key}|${height}`;let src = this.sources.get(id);@@ -1804,7 +1951,8 @@ export class FrameSourcePool {// re-mints. The source follows the move in place, holding every frame it// has decoded, so a clip mid-play rides across the swap on its ring while// the new address opens behind it.- if (src && src.url !== asset.url) src.retarget(asset);+ if (src && src.url !== previewUrl(asset)) src.retarget(asset);+ else src?.follow(asset);if (!src) {poolLog(`pool open ${id}`);const own = new ClipFrameSource(asset, height, this.onFrame, () => this.backOwner(own));diff --git a/site/src/cut/lib/genScene.ts b/site/src/cut/lib/genScene.tsindex 0e55ff39..c16a5d0b 100644--- a/site/src/cut/lib/genScene.ts+++ b/site/src/cut/lib/genScene.ts@@ -14,7 +14,7 @@ import { onActivity } from "./genvideo/activity";import { projectWriteMode, withProjectDoc } from "./genvideo/docWriter";import type { RefAsset, Shot, VideoEvent, VideoPhase, VideoProject } from "./genvideo/types";import { useEditor } from "./store";-import { nearestAspect } from "./types";+import { isLinkedAssetType, nearestAspect } from "./types";import { defaultVideoAspects } from "./videoModels";// Brief-to-video ("generate a video") controller. It owns one VideoOrchestrator@@ -247,7 +247,7 @@ function toReferences(ids: string[] | undefined): RefAsset[] {const out: RefAsset[] = [];for (const id of ids) {const a = assets.find((x) => x.id === id);- if (a && a.type !== "font") out.push({ mediaId: a.id, kind: a.type, purpose: "style", name: a.name });+ if (a && !isLinkedAssetType(a.type)) out.push({ mediaId: a.id, kind: a.type, purpose: "style", name: a.name });}return out;}diff --git a/site/src/cut/lib/gradeGpu.ts b/site/src/cut/lib/gradeGpu.tsindex 4b3892e4..d502eddf 100644--- a/site/src/cut/lib/gradeGpu.ts+++ b/site/src/cut/lib/gradeGpu.ts@@ -8,6 +8,7 @@import type { GradeLut } from "@donkeycut/effects-kit";import { gpuPassSingleton, uploadPassSource, type GpuPass } from "./gpuPass";+import { allowance, holdMemory } from "./memoryBudget";import type { RasterSurface } from "./raster";const FRAG = `#version 300 es@@ -48,18 +49,23 @@ void main() {interface GradeExt {sizeLoc: WebGLUniformLocation;- /** One uploaded texture per grade, so two graded clips in the same frame- * take turns binding instead of re-uploading 33³ floats twice a frame. */- luts: Map<string, WebGLTexture>;+ /** One uploaded texture per LUT, so two graded clips in the same frame+ * take turns binding instead of re-uploading the lattice twice a frame. */+ luts: Map<string, { tex: WebGLTexture; bytes: number }>;}-/** Uploaded LUT textures kept at once; a 33³ RGBA32F texture is ~0.6MB. */-const LUT_TEXTURE_MAX = 6;+/** Bytes of uploaded textures kept before the budget has its say: a 33³+ * RGBA32F texture is ~0.6MB, a 65³ one ~4.4MB. */+const TUNED_TEXTURE_BYTES = 24 * 2 ** 20;+let textureBytes = 0;+holdMemory("gradeLutTextures", () => textureBytes);const acquire = gpuPassSingleton(FRAG, ({ gl, program }): GradeExt | null => {gl.uniform1i(gl.getUniformLocation(program, "uLut"), 1);const sizeLoc = gl.getUniformLocation(program, "uSize");if (!sizeLoc) return null;+ // A rebuilt pass (context loss) starts with no textures.+ textureBytes = 0;return { sizeLoc, luts: new Map() };});@@ -69,8 +75,8 @@ function bindLut(s: { pass: GpuPass; ext: GradeExt }, lut: GradeLut, key: stringgl.activeTexture(gl.TEXTURE1);const held = s.ext.luts.get(key);if (held) {- gl.bindTexture(gl.TEXTURE_3D, held);- // Re-insert so the cap drops the grade least recently drawn.+ gl.bindTexture(gl.TEXTURE_3D, held.tex);+ // Re-insert so the cap drops the LUT least recently drawn.s.ext.luts.delete(key);s.ext.luts.set(key, held);return;@@ -91,15 +97,17 @@ function bindLut(s: { pass: GpuPass; ext: GradeExt }, lut: GradeLut, key: stringrgba[i * 4 + 3] = 1;}gl.texImage3D(gl.TEXTURE_3D, 0, gl.RGBA32F, lut.size, lut.size, lut.size, 0, gl.RGBA, gl.FLOAT, rgba);- s.ext.luts.set(key, tex);- if (s.ext.luts.size > LUT_TEXTURE_MAX) {- const oldest = s.ext.luts.keys().next().value;- if (oldest !== undefined && oldest !== key) {- const stale = s.ext.luts.get(oldest);- if (stale) gl.deleteTexture(stale);- s.ext.luts.delete(oldest);- }+ const bytes = rgba.byteLength;+ // Make room first, in bytes: the LUTs least recently drawn go.+ const cap = allowance("gradeLutTextures", TUNED_TEXTURE_BYTES);+ for (const [oldest, stale] of s.ext.luts) {+ if (textureBytes + bytes <= cap) break;+ gl.deleteTexture(stale.tex);+ s.ext.luts.delete(oldest);+ textureBytes -= stale.bytes;}+ s.ext.luts.set(key, { tex, bytes });+ textureBytes += bytes;}/**diff --git a/site/src/cut/lib/gradePresets.test.ts b/site/src/cut/lib/gradePresets.test.tsnew file mode 100644index 00000000..fb268037--- /dev/null+++ b/site/src/cut/lib/gradePresets.test.ts@@ -0,0 +1,54 @@+import { describe, expect, test } from "bun:test";+import { isGradePresetTemplate, rememberSavedGrades, savedGradeOf, savedGradesKnown } from "./gradePresets";+import type { LibraryTemplate } from "./types";++// A saved grade is a template carrying only a grade: the template shelves+// leave it out, the Color panel lists it, and the chat can name it.++const bare = (extra: Partial<LibraryTemplate>): LibraryTemplate & { residency: "cloud" } => ({+ id: "t1",+ name: "Warm",+ addedAt: 1,+ duration: 0,+ media: [],+ layers: [],+ audio: [],+ texts: [],+ cues: [],+ residency: "cloud",+ ...extra,+});++describe("saved grades", () => {+ test("a template carrying only a grade is a saved grade", () => {+ const t = bare({ grade: { temperature: 12, lut: { id: "lut:abc" } } });+ expect(isGradePresetTemplate(t)).toBe(true);+ expect(savedGradeOf(t)).toEqual({+ id: "t1",+ name: "Warm",+ residency: "cloud",+ grade: { temperature: 12, lut: { id: "lut:abc" } },+ });+ });++ test("a template with media, a sound preset or a neutral grade is not one", () => {+ expect(isGradePresetTemplate(bare({}))).toBe(false);+ expect(isGradePresetTemplate(bare({ sound: { limiter: { ceiling: -1 } } }))).toBe(false);+ expect(+ isGradePresetTemplate(+ bare({+ grade: { exposure: 3 },+ media: [{ fileName: "a.mp4", name: "a", type: "video", duration: 1 }],+ })+ )+ ).toBe(false);+ expect(savedGradeOf(bare({ grade: { exposure: 0 } }))).toBeNull();+ });++ test("the last listing is what the editor state names", () => {+ rememberSavedGrades([{ id: "g1", name: "Warm", residency: "cloud", grade: { exposure: 2 } }]);+ expect(savedGradesKnown().map((g) => g.name)).toEqual(["Warm"]);+ rememberSavedGrades([]);+ expect(savedGradesKnown()).toEqual([]);+ });+});diff --git a/site/src/cut/lib/gradePresets.ts b/site/src/cut/lib/gradePresets.tsnew file mode 100644index 00000000..4e3bee0e--- /dev/null+++ b/site/src/cut/lib/gradePresets.ts@@ -0,0 +1,78 @@+"use client";++/**+ * Named colour grades, saved in the shared Library. A saved grade rides the+ * template rails the way a sound preset does: a library template with no+ * media, no layers and no text, carrying only a `grade` — so every shelf+ * stores, lists and deletes it with machinery that already exists, and a+ * grade saved on this Mac shows beside one saved in the cloud.+ */++import { normalizeGrade, type ColorGrade } from "@donkeycut/effects-kit";+import { deleteTemplate, fetchLibrary, saveTemplate } from "./library";+import type { Residency } from "./residency";+import type { LibraryTemplate } from "./types";++export interface SavedGrade {+ id: string;+ name: string;+ residency: Residency;+ grade: ColorGrade;+}++/** Whether a library template is a saved grade: a template surface filters+ * on this so grades stay in the Color panel where they were saved. */+export function isGradePresetTemplate(t: LibraryTemplate): boolean {+ if (!t.grade) return false;+ return !t.media.length && !t.layers.length && !t.audio.length && !t.texts.length && !t.cues.length;+}++/** Read a template as a saved grade, or null when it is an ordinary one. */+export function savedGradeOf(t: LibraryTemplate & { residency: Residency }): SavedGrade | null {+ if (!isGradePresetTemplate(t)) return null;+ const grade = normalizeGrade(t.grade);+ if (!grade) return null;+ return { id: t.id, name: t.name, residency: t.residency, grade };+}++/** The saved grades as last listed — by the Color panel's shelf read or a+ * tool — so the chat's editor_state can name them without a fetch. */+let known: SavedGrade[] = [];++export const savedGradesKnown = (): SavedGrade[] => known;++export function rememberSavedGrades(list: SavedGrade[]): void {+ known = list;+}++/** Every saved grade across every reachable shelf, newest first. */+export async function listSavedGrades(): Promise<SavedGrade[]> {+ const lib = await fetchLibrary();+ known = lib.templates.map(savedGradeOf).filter((p): p is SavedGrade => p !== null);+ return known;+}++/** Save a grade as a named preset on the active shelf. */+export async function saveGradePreset(+ projectId: string,+ name: string,+ grade: ColorGrade | undefined+): Promise<SavedGrade | null> {+ const normalized = normalizeGrade(grade);+ if (!normalized) throw new Error("A neutral grade is nothing to save.");+ const saved = await saveTemplate(projectId, {+ name,+ duration: 0,+ media: [],+ layers: [],+ audio: [],+ texts: [],+ cues: [],+ grade: normalized,+ });+ return savedGradeOf(saved);+}++export function deleteGradePreset(preset: SavedGrade): Promise<void> {+ return deleteTemplate(preset.residency, preset.id);+}diff --git a/site/src/cut/lib/hdrCanvas.ts b/site/src/cut/lib/hdrCanvas.tsnew file mode 100644index 00000000..ae874452--- /dev/null+++ b/site/src/cut/lib/hdrCanvas.ts@@ -0,0 +1,75 @@+/**+ * Whether this browser can put an extended-range picture on screen.+ *+ * An HDR preview needs a canvas whose values may run past 1.0 and reach the+ * display unclipped. Two routes exist: a WebGPU canvas configured for+ * `rgba16float` with extended tone mapping, and a WebGL drawing buffer+ * re-declared as RGBA16F with a wide color space. Both are feature-detected+ * once per session by configuring a one-pixel canvas; the display's own+ * range is a media query beside them. A headless process has none of this+ * and answers false on every count.+ */++export interface HdrCanvasSupport {+ /** WebGPU: `configure({ format: "rgba16float", toneMapping: { mode: "extended" } })` took. */+ webgpu: boolean;+ /** WebGL 2: `drawingBufferStorage(RGBA16F)` took and `drawingBufferColorSpace` exists. */+ webgl: boolean;+ /** The display the page is on reports a high dynamic range right now. */+ display: boolean;+}++const NONE: HdrCanvasSupport = { webgpu: false, webgl: false, display: false };++let cached: Promise<HdrCanvasSupport> | null = null;++/** Detect once and hold the answer for the session. */+export function hdrCanvasSupport(): Promise<HdrCanvasSupport> {+ return (cached ??= detect().catch(() => NONE));+}++async function detect(): Promise<HdrCanvasSupport> {+ if (typeof OffscreenCanvas === "undefined") return NONE;+ const [webgpu, webgl] = await Promise.all([detectWebGpu(), Promise.resolve(detectWebGl())]);+ const display =+ typeof matchMedia === "function" ? matchMedia("(dynamic-range: high)").matches : false;+ return { webgpu, webgl, display };+}++type GpuCanvasContext = {+ configure(config: Record<string, unknown>): void;+ getConfiguration?(): { toneMapping?: { mode?: string } } | null;+ unconfigure?(): void;+};++async function detectWebGpu(): Promise<boolean> {+ const gpu = (navigator as { gpu?: { requestAdapter(): Promise<{ requestDevice(): Promise<{ destroy(): void }> } | null> } }).gpu;+ if (!gpu) return false;+ const adapter = await gpu.requestAdapter();+ if (!adapter) return false;+ const device = await adapter.requestDevice();+ try {+ const ctx = new OffscreenCanvas(1, 1).getContext("webgpu" as "2d") as unknown as GpuCanvasContext | null;+ if (!ctx) return false;+ ctx.configure({ device, format: "rgba16float", toneMapping: { mode: "extended" } });+ const mode = ctx.getConfiguration?.()?.toneMapping?.mode;+ ctx.unconfigure?.();+ return mode === "extended";+ } finally {+ device.destroy();+ }+}++function detectWebGl(): boolean {+ const gl = new OffscreenCanvas(1, 1).getContext("webgl2") as+ | (WebGL2RenderingContext & { drawingBufferStorage?: (format: number, w: number, h: number) => void })+ | null;+ if (!gl) return false;+ if (typeof gl.drawingBufferStorage !== "function" || !("drawingBufferColorSpace" in gl)) return false;+ // A float drawing buffer is allowed only once a float color buffer extension is on.+ if (!gl.getExtension("EXT_color_buffer_float") && !gl.getExtension("EXT_color_buffer_half_float")) return false;+ gl.drawingBufferStorage(gl.RGBA16F, 1, 1);+ const ok = gl.getError() === gl.NO_ERROR;+ gl.getExtension("WEBGL_lose_context")?.loseContext();+ return ok;+}diff --git a/site/src/cut/lib/hdrPresent.test.ts b/site/src/cut/lib/hdrPresent.test.tsnew file mode 100644index 00000000..c34be7f0--- /dev/null+++ b/site/src/cut/lib/hdrPresent.test.ts@@ -0,0 +1,48 @@+import { describe, expect, test } from "bun:test";+import { BT2408_HLG_WHITE, pqEncode } from "@donkeycut/effects-kit";+import { extendedSrgbEncode, hdrPreviewState, hlgSignalToDisplayLinear, setHdrPreviewState, subscribeHdrPreviewState } from "./hdrPresent";++describe("the HDR present pass", () => {+ test("HLG reference white lands at 1.0, black at 0, the nominal peak near five", () => {+ const w = BT2408_HLG_WHITE;+ const white = hlgSignalToDisplayLinear(w, w, w);+ for (const v of white) expect(Math.abs(v - 1)).toBeLessThan(2e-3);+ for (const v of hlgSignalToDisplayLinear(0, 0, 0)) expect(v).toBe(0);+ const peak = hlgSignalToDisplayLinear(1, 1, 1);+ for (const v of peak) expect(Math.abs(v - 1000 / 203)).toBeLessThan(2e-2);+ // Neutral stays neutral through the primaries change.+ for (const s of [0.2, 0.5, 0.9]) {+ const [r, g, b] = hlgSignalToDisplayLinear(s, s, s);+ expect(Math.abs(r - g)).toBeLessThan(1e-6);+ expect(Math.abs(g - b)).toBeLessThan(1e-6);+ }+ // A Rec.2020 red goes outside Rec.709: negative green and blue.+ const [, g, b] = hlgSignalToDisplayLinear(w, 0, 0);+ expect(g).toBeLessThan(0);+ expect(b).toBeLessThan(0);+ });++ test("extended sRGB holds the headroom and the negative side", () => {+ expect(extendedSrgbEncode(0)).toBe(0);+ expect(Math.abs(extendedSrgbEncode(1) - 1)).toBeLessThan(1e-9);+ expect(extendedSrgbEncode(4)).toBeGreaterThan(1.5);+ expect(extendedSrgbEncode(-0.5)).toBe(-extendedSrgbEncode(0.5));+ expect(extendedSrgbEncode(0.5)).toBeCloseTo(0.7354, 3);+ // PQ has no part in the present pass: the preview composites in HLG.+ expect(pqEncode(203)).toBeLessThan(BT2408_HLG_WHITE);+ });++ test("the stage state is a store its label subscribes to", () => {+ let fired = 0;+ const off = subscribeHdrPreviewState(() => fired++);+ setHdrPreviewState("sdr");+ expect(hdrPreviewState()).toBe("sdr");+ setHdrPreviewState("sdr");+ expect(fired).toBe(1);+ setHdrPreviewState("off");+ off();+ setHdrPreviewState("hdr");+ expect(fired).toBe(2);+ setHdrPreviewState("off");+ });+});diff --git a/site/src/cut/lib/hdrPresent.ts b/site/src/cut/lib/hdrPresent.tsnew file mode 100644index 00000000..d13fbd15--- /dev/null+++ b/site/src/cut/lib/hdrPresent.ts@@ -0,0 +1,343 @@+/**+ * The HDR present pass: the last step of an HDR preview.+ *+ * When a project delivers HLG or PQ, the compositor draws the frame in the+ * same HLG signal space the export composites in, onto its ordinary 8-bit+ * canvas. That picture is not what a display should show — an HLG signal on+ * an sRGB canvas reads flat and dim — so a second canvas, configured through+ * WebGPU as `rgba16float` with extended tone mapping, decodes it to display+ * light every frame: the BT.2100 inverse OETF and the OOTF for a 1000-nit+ * display, scaled so the 203-nit reference white of BT.2408 lands on 1.0 —+ * SDR white on the display, where the titles the DOM draws over the stage+ * already sit — then encoded with the sRGB transfer extended past 1.0, which+ * is what the extended-range canvas takes.+ *+ * One pass per frame, only in HDR mode: the source texture and the bind+ * group live as long as the size does, so a frame allocates nothing. The+ * pure decode is exported on its own so the math is testable and the shader+ * can be read against it.+ */++import { BT2408_REFERENCE_WHITE_NITS, hlgOetfInverse, hlgOotf, REC2020_PRIMARIES, REC709_PRIMARIES, rgbToRgbMatrix } from "@donkeycut/effects-kit";+import type { RasterSurface } from "./raster";++/** The display the present pass decodes for; HLG's nominal 1000-nit peak. */+export const HDR_PRESENT_PEAK_NITS = 1000;++const REC2020_TO_REC709 = rgbToRgbMatrix(REC2020_PRIMARIES, REC709_PRIMARIES);++/** HLG signal (Rec.2020) → Rec.709 display-linear light with reference white+ * (203 nits) at 1.0. Past 1.0 is HDR headroom; below 0 is color outside+ * Rec.709, which the extended-range canvas carries. */+export function hlgSignalToDisplayLinear(r: number, g: number, b: number): [number, number, number] {+ const [rd, gd, bd] = hlgOotf(hlgOetfInverse(r), hlgOetfInverse(g), hlgOetfInverse(b), HDR_PRESENT_PEAK_NITS);+ const k = 1 / BT2408_REFERENCE_WHITE_NITS;+ const m = REC2020_TO_REC709;+ const x = rd * k;+ const y = gd * k;+ const z = bd * k;+ return [+ m[0] * x + m[1] * y + m[2] * z,+ m[3] * x + m[4] * y + m[5] * z,+ m[6] * x + m[7] * y + m[8] * z,+ ];+}++/** The sRGB transfer function extended past 1.0 and mirrored below 0 — the+ * encoding an extended-range sRGB canvas holds. */+export function extendedSrgbEncode(v: number): number {+ const a = Math.abs(v);+ const e = a <= 0.0031308 ? 12.92 * a : 1.055 * Math.pow(a, 1 / 2.4) - 0.055;+ return v < 0 ? -e : e;+}++/* ------------------------------------------------------------------ */+/* What the stage is showing */+/* ------------------------------------------------------------------ */++/** `off`: the project is SDR. `hdr`: the HDR picture is on screen. `sdr`:+ * the project is HDR and the stage shows the grade rendered as SDR, because+ * the display, the browser or the GPU cannot carry the HDR picture. */+export type HdrPreviewState = "off" | "hdr" | "sdr";++let state: HdrPreviewState = "off";+const listeners = new Set<() => void>();++export function hdrPreviewState(): HdrPreviewState {+ return state;+}++export function setHdrPreviewState(next: HdrPreviewState): void {+ if (state === next) return;+ state = next;+ for (const fn of listeners) fn();+}++export function subscribeHdrPreviewState(fn: () => void): () => void {+ listeners.add(fn);+ return () => {+ listeners.delete(fn);+ };+}++/** Whether the display the page is on reports a high dynamic range now — a+ * window dragged to another monitor changes the answer, so `onChange` fires+ * when it does. */+let displayQuery: MediaQueryList | null | undefined;++function displayRange(): MediaQueryList | null {+ if (displayQuery !== undefined) return displayQuery;+ displayQuery = typeof matchMedia === "function" ? matchMedia("(dynamic-range: high)") : null;+ return displayQuery;+}++export function displayIsHdr(): boolean {+ return displayRange()?.matches ?? false;+}++export function onDisplayRangeChange(fn: () => void): () => void {+ const q = displayRange();+ if (!q) return () => {};+ q.addEventListener("change", fn);+ return () => q.removeEventListener("change", fn);+}++/* ------------------------------------------------------------------ */+/* The WebGPU presenter */+/* ------------------------------------------------------------------ */++// The page ships no WebGPU type package; the slice of the API the pass uses+// is spelled here, the way hdrCanvas.ts spells its own.+interface GpuTextureLike {+ createView(): unknown;+ destroy(): void;+}+interface GpuCanvasContextLike {+ configure(config: Record<string, unknown>): void;+ unconfigure(): void;+ getCurrentTexture(): GpuTextureLike;+}+interface GpuQueueLike {+ copyExternalImageToTexture(source: { source: RasterSurface; flipY?: boolean }, dest: { texture: GpuTextureLike }, size: [number, number]): void;+ writeBuffer(buffer: unknown, offset: number, data: BufferSource): void;+ submit(buffers: unknown[]): void;+}+interface GpuRenderPassLike {+ setPipeline(p: unknown): void;+ setBindGroup(i: number, g: unknown): void;+ draw(n: number): void;+ end(): void;+}+interface GpuEncoderLike {+ beginRenderPass(desc: Record<string, unknown>): GpuRenderPassLike;+ finish(): unknown;+}+interface GpuDeviceLike {+ queue: GpuQueueLike;+ lost: Promise<unknown>;+ createShaderModule(desc: { code: string }): unknown;+ createRenderPipeline(desc: Record<string, unknown>): { getBindGroupLayout(i: number): unknown };+ createSampler(desc: Record<string, unknown>): unknown;+ createBuffer(desc: Record<string, unknown>): unknown;+ createTexture(desc: Record<string, unknown>): GpuTextureLike;+ createBindGroup(desc: Record<string, unknown>): unknown;+ createCommandEncoder(): GpuEncoderLike;+ destroy(): void;+}+interface GpuLike {+ requestAdapter(): Promise<{ requestDevice(): Promise<GpuDeviceLike> } | null>;+}++// GPUTextureUsage bits, spelled out for the same reason.+const TEXTURE_BINDING = 0x04;+const COPY_DST = 0x02;+const RENDER_ATTACHMENT = 0x10;+// GPUBufferUsage bits.+const UNIFORM = 0x40;+const BUFFER_COPY_DST = 0x08;++const SHADER = /* wgsl */ `+struct Params { m: mat3x3<f32>, peak: f32, white: f32 };+@group(0) @binding(0) var samp: sampler;+@group(0) @binding(1) var src: texture_2d<f32>;+@group(0) @binding(2) var<uniform> params: Params;++struct VsOut { @builtin(position) pos: vec4<f32>, @location(0) uv: vec2<f32> };++@vertex fn vs(@builtin(vertex_index) i: u32) -> VsOut {+ // One triangle over the whole target; uv runs top-down like the canvas.+ var p = array<vec2<f32>, 3>(vec2(-1.0, -1.0), vec2(3.0, -1.0), vec2(-1.0, 3.0));+ var o: VsOut;+ o.pos = vec4(p[i], 0.0, 1.0);+ o.uv = vec2(p[i].x * 0.5 + 0.5, 0.5 - p[i].y * 0.5);+ return o;+}++// BT.2100 HLG inverse OETF: signal → scene-linear.+fn hlgInv(s: f32) -> f32 {+ let a = 0.17883277;+ let b = 0.28466892;+ let c = 0.55991073;+ if (s <= 0.0) { return 0.0; }+ if (s <= 0.5) { return s * s / 3.0; }+ return (exp((s - c) / a) + b) / 12.0;+}++// The sRGB transfer, extended past 1.0 and mirrored below 0.+fn srgbx(v: f32) -> f32 {+ let a = abs(v);+ let e = select(1.055 * pow(a, 1.0 / 2.4) - 0.055, 12.92 * a, a <= 0.0031308);+ return select(e, -e, v < 0.0);+}++@fragment fn fs(in: VsOut) -> @location(0) vec4<f32> {+ let s = textureSample(src, samp, in.uv).rgb;+ let scene = vec3(hlgInv(s.r), hlgInv(s.g), hlgInv(s.b));+ // The OOTF for the display's peak: system gamma 1.2 at 1000 nits.+ let gamma = 1.2 + 0.42 * log(params.peak / 1000.0) / log(10.0);+ let ys = dot(scene, vec3(0.2627, 0.6780, 0.0593));+ let k = select(0.0, params.peak * pow(ys, gamma - 1.0), ys > 0.0);+ let lin709 = params.m * (scene * (k / params.white));+ return vec4(srgbx(lin709.r), srgbx(lin709.g), srgbx(lin709.b), 1.0);+}+`;++/**+ * Presents a canvas holding an HLG-signal picture on an extended-range+ * canvas. `create` resolves null where the browser has no WebGPU device or+ * refuses the extended configuration — the caller then previews SDR.+ */+export class HdrPresenter {+ private texture: GpuTextureLike | null = null;+ private bindGroup: unknown = null;+ private w = 0;+ private h = 0;+ private lost = false;++ private constructor(+ private readonly canvas: HTMLCanvasElement,+ private readonly device: GpuDeviceLike,+ private readonly ctx: GpuCanvasContextLike,+ private readonly pipeline: { getBindGroupLayout(i: number): unknown },+ private readonly sampler: unknown,+ private readonly params: unknown+ ) {+ void device.lost.then(() => {+ this.lost = true;+ });+ }++ static async create(canvas: HTMLCanvasElement): Promise<HdrPresenter | null> {+ const gpu = (navigator as { gpu?: GpuLike }).gpu;+ if (!gpu) return null;+ let device: GpuDeviceLike;+ try {+ const adapter = await gpu.requestAdapter();+ if (!adapter) return null;+ device = await adapter.requestDevice();+ } catch {+ return null;+ }+ const ctx = canvas.getContext("webgpu" as "2d") as unknown as GpuCanvasContextLike | null;+ if (!ctx) {+ device.destroy();+ return null;+ }+ try {+ ctx.configure({+ device,+ format: "rgba16float",+ colorSpace: "srgb",+ toneMapping: { mode: "extended" },+ alphaMode: "opaque",+ });+ const shader = device.createShaderModule({ code: SHADER });+ const pipeline = device.createRenderPipeline({+ layout: "auto",+ vertex: { module: shader, entryPoint: "vs" },+ fragment: { module: shader, entryPoint: "fs", targets: [{ format: "rgba16float" }] },+ primitive: { topology: "triangle-list" },+ });+ const sampler = device.createSampler({ magFilter: "linear", minFilter: "linear" });+ // mat3x3<f32> is three vec4-aligned columns (48 bytes), then two floats.+ const params = device.createBuffer({ size: 64, usage: UNIFORM | BUFFER_COPY_DST });+ const m = REC2020_TO_REC709;+ const data = new Float32Array(16);+ // Column-major: column j holds row entries m[j], m[3+j], m[6+j].+ for (let j = 0; j < 3; j++) {+ data[j * 4] = m[j];+ data[j * 4 + 1] = m[3 + j];+ data[j * 4 + 2] = m[6 + j];+ }+ data[12] = HDR_PRESENT_PEAK_NITS;+ data[13] = BT2408_REFERENCE_WHITE_NITS;+ device.queue.writeBuffer(params, 0, data);+ return new HdrPresenter(canvas, device, ctx, pipeline, sampler, params);+ } catch {+ device.destroy();+ return null;+ }+ }++ /** The device went away; the caller makes a new presenter or falls back. */+ get gone(): boolean {+ return this.lost;+ }++ /** Decode `source` (an HLG-signal picture) onto the extended-range canvas,+ * sized to match it. */+ present(source: RasterSurface): void {+ if (this.lost) return;+ const w = source.width;+ const h = source.height;+ if (w < 1 || h < 1) return;+ if (this.canvas.width !== w) this.canvas.width = w;+ if (this.canvas.height !== h) this.canvas.height = h;+ if (!this.texture || this.w !== w || this.h !== h) {+ this.texture?.destroy();+ this.texture = this.device.createTexture({+ size: [w, h],+ format: "rgba8unorm",+ usage: TEXTURE_BINDING | COPY_DST | RENDER_ATTACHMENT,+ });+ this.bindGroup = this.device.createBindGroup({+ layout: this.pipeline.getBindGroupLayout(0),+ entries: [+ { binding: 0, resource: this.sampler },+ { binding: 1, resource: this.texture.createView() },+ { binding: 2, resource: { buffer: this.params } },+ ],+ });+ this.w = w;+ this.h = h;+ }+ try {+ this.device.queue.copyExternalImageToTexture({ source }, { texture: this.texture }, [w, h]);+ const encoder = this.device.createCommandEncoder();+ const pass = encoder.beginRenderPass({+ colorAttachments: [+ { view: this.ctx.getCurrentTexture().createView(), loadOp: "clear", storeOp: "store", clearValue: { r: 0, g: 0, b: 0, a: 1 } },+ ],+ });+ pass.setPipeline(this.pipeline);+ pass.setBindGroup(0, this.bindGroup);+ pass.draw(3);+ pass.end();+ this.device.queue.submit([encoder.finish()]);+ } catch {+ this.lost = true;+ }+ }++ dispose(): void {+ this.lost = true;+ this.texture?.destroy();+ this.texture = null;+ try {+ this.ctx.unconfigure();+ } catch {+ // A context already torn down with its canvas.+ }+ this.device.destroy();+ }+}diff --git a/site/src/cut/lib/headless/docSession.ts b/site/src/cut/lib/headless/docSession.tsindex 983b2f51..3d19ed45 100644--- a/site/src/cut/lib/headless/docSession.ts+++ b/site/src/cut/lib/headless/docSession.ts@@ -3,6 +3,8 @@ import { noteProjectRevision } from "../projectRevision";import { fetchWithRetry } from "./http";import { syncFontAssets } from "../fontAssets";import { syncLinkedLibrary } from "../linkedLibrary";+import { withAssetColors } from "../mediaRead";+import { drawnLists } from "../itemKinds";import { serializeDoc, useEditor } from "../store";import type { MediaAsset, ProjectDoc } from "../types";@@ -71,10 +73,15 @@ export async function openCloudSnapshot(for (const u of body.urls ?? []) signed.set(u.fileName, u.url);}}- const assets: MediaAsset[] = (doc.assets ?? []).map((a) => ({- ...a,- url: signed.get(a.fileName) ?? `${projectPath(s, projectId)}/media/${encodeURIComponent(a.fileName)}`,- }));+ // Footage imported before its color was read gets it here, from the+ // header, so what a run renders and what it saves both read it right.+ const assets: MediaAsset[] = await withAssetColors(+ (doc.assets ?? []).map((a) => ({+ ...a,+ url: signed.get(a.fileName) ?? `${projectPath(s, projectId)}/media/${encodeURIComponent(a.fileName)}`,+ })),+ drawnLists(doc)+ );await useEditor.getState().openProjectDoc(projectId, doc, assets);noteProjectRevision(projectId, version);// The page does this from the editor; a run has to do it before it draws,diff --git a/site/src/cut/lib/headless/nodeMedia.ts b/site/src/cut/lib/headless/nodeMedia.tsindex 4da20da8..9a39b54d 100644--- a/site/src/cut/lib/headless/nodeMedia.ts+++ b/site/src/cut/lib/headless/nodeMedia.ts@@ -1,7 +1,58 @@import { VideoSampleSink, type InputVideoTrack, type VideoSample, type WrappedCanvas } from "mediabunny";+import type { toAvFrame as ToAvFrame } from "@mediabunny/server";import { setFrameSinkFactory, type FrameCanvasSink, type FrameSize } from "../mediaRead";import { createRasterCanvas } from "../raster";+type NodeAv = typeof import("node-av");+let nodeAvModule: Promise<NodeAv> | null = null;+const nodeAv = (): Promise<NodeAv> => (nodeAvModule ??= import("node-av"));++/** Tight RGBA of `sample`, converted with the matrix and range the sample+ * carries. The server package's own RGBA copy runs the legacy scaler, which+ * converts every file as BT.601 whatever its tags say, so a 2020-tagged+ * frame came out with the wrong chroma; a filter graph reads the frame's+ * color fields and converts by them. */+async function rgbaOf(sample: VideoSample, toAvFrame: typeof ToAvFrame): Promise<Uint8Array> {+ const av = await nodeAv();+ const src = new av.Frame();+ src.alloc();+ const dst = new av.Frame();+ dst.alloc();+ const graph = new av.FilterGraph();+ graph.alloc();+ try {+ await toAvFrame(sample, src);+ const args =+ `video_size=${src.width}x${src.height}:pix_fmt=${src.format}:time_base=1/1000000` ++ `:pixel_aspect=1/1:colorspace=${src.colorSpace}:range=${src.colorRange}`;+ const bufferSrc = graph.createFilter(av.Filter.getByName("buffer")!, "src", args);+ const bufferSink = graph.createFilter(av.Filter.getByName("buffersink")!, "sink");+ if (!bufferSrc || !bufferSink) throw new Error("Could not build the frame converter.");+ const outputs = av.FilterInOut.createList([{ name: "in", filterCtx: bufferSrc, padIdx: 0 }]);+ const inputs = av.FilterInOut.createList([{ name: "out", filterCtx: bufferSink, padIdx: 0 }]);+ av.FFmpegError.throwIfError(graph.parsePtr("[in]format=rgba[out]", inputs, outputs), "FilterGraph.parsePtr");+ av.FFmpegError.throwIfError(await graph.config(), "FilterGraph.config");+ av.FFmpegError.throwIfError(await bufferSrc.buffersrcAddFrame(src), "buffersrcAddFrame");+ await bufferSrc.buffersrcAddFrame(null);+ av.FFmpegError.throwIfError(await bufferSink.buffersinkGetFrame(dst), "buffersinkGetFrame");+ const plane = dst.data?.[0];+ if (!plane) throw new Error("The frame converter returned no pixels.");+ const row = dst.width * 4;+ const stride = dst.linesize[0];+ const out = new Uint8Array(row * dst.height);+ if (stride === row) {+ out.set(plane.subarray(0, out.length));+ } else {+ for (let y = 0; y < dst.height; y++) out.set(plane.subarray(y * stride, y * stride + row), y * row);+ }+ return out;+ } finally {+ graph.free();+ src.free();+ dst.free();+ }+}+/*** The media runtime a headless process needs to read what the page reads.*@@ -30,7 +81,8 @@ export class NodeFrameSink implements FrameCanvasSink {constructor(private readonly imageData: new (data: Uint8ClampedArray, w: number, h: number) => ImageData,track: InputVideoTrack,- private readonly size?: FrameSize+ private readonly size: FrameSize | undefined,+ private readonly toAvFrame: typeof ToAvFrame) {this.samples = new VideoSampleSink(track);}@@ -50,8 +102,7 @@ export class NodeFrameSink implements FrameCanvasSink {sample.close();}try {- const pixels = new Uint8Array(out.allocationSize({ format: "RGBA" }));- await out.copyTo(pixels, { format: "RGBA" });+ const pixels = await rgbaOf(out, this.toAvFrame);const image = new this.imageData(new Uint8ClampedArray(pixels.buffer, pixels.byteOffset, pixels.byteLength),out.codedWidth,@@ -123,7 +174,7 @@ export async function installNodeMedia(): Promise<boolean> {w: number,h: number) => ImageData;- setFrameSinkFactory((track, size) => new NodeFrameSink(imageData, track, size));+ setFrameSinkFactory((track, size) => new NodeFrameSink(imageData, track, size, server.toAvFrame));return true;} catch {return false;diff --git a/site/src/cut/lib/importQueue.ts b/site/src/cut/lib/importQueue.tsindex d235817f..2c94b750 100644--- a/site/src/cut/lib/importQueue.ts+++ b/site/src/cut/lib/importQueue.ts@@ -213,6 +213,14 @@ async function run(job: Job) {upload: undefined,...(asset.type === "image" ? { thumbs: [url] } : {}),});+ // A ProRes master's preview proxy is built once the bytes are at rest in+ // the project's own storage, which is now.+ const landed = useEditor.getState().assets.find((a) => a.id === asset.id);+ if (landed) {+ void import("./mediaProxy")+ .then((m) => (m.needsProxy(landed) ? m.ensureProxy(job.projectId, landed, job.backend) : undefined))+ .catch(() => {});+ }// Decoders and voices carry across the URL change on what they already// hold; the source bytes stay readable while their new stacks open.setTimeout(() => revokeTabUrl(localUrl), 10_000);diff --git a/site/src/cut/lib/instantAction.ts b/site/src/cut/lib/instantAction.tsindex 1b358e0a..e1f78a60 100644--- a/site/src/cut/lib/instantAction.ts+++ b/site/src/cut/lib/instantAction.ts@@ -3,6 +3,7 @@ import {ALL_EFFECT_IDS,EFFECT_LABELS,GRADE_BASIC_FIELDS,+ GRADE_DETAIL_FIELDS,GRADE_MAX,GRADE_PRESET_CATEGORIES,GRADE_PRESET_IDS,@@ -278,7 +279,7 @@ const ENUMS: Record<string, EnumFamily> = {},grade_field: {instructions: "Which colour slider does the request move?",- options: Object.fromEntries(GRADE_BASIC_FIELDS.map((f) => [f.key, f.label])),+ options: Object.fromEntries([...GRADE_BASIC_FIELDS, ...GRADE_DETAIL_FIELDS].map((f) => [f.key, f.label])),},hsl_band: {instructions: "Which colour band does the request single out?",@@ -998,7 +999,7 @@ export const INSTANT_ACTIONS: Record<string, ActionDef> = {build: (p) => {const field = p.enumOf("grade_field");const value = p.level("grade_amount");- const label = GRADE_BASIC_FIELDS.find((f) => f.key === field)?.label ?? field;+ const label = [...GRADE_BASIC_FIELDS, ...GRADE_DETAIL_FIELDS].find((f) => f.key === field)?.label ?? field;return {args: { clipId: p.target("clip").id, [field]: value },say: `${label} ${value >= 0 ? "up" : "down"} on "${p.target("clip").name}".`,diff --git a/site/src/cut/lib/itemKinds.test.ts b/site/src/cut/lib/itemKinds.test.tsindex bf645261..de407410 100644--- a/site/src/cut/lib/itemKinds.test.ts+++ b/site/src/cut/lib/itemKinds.test.ts@@ -123,3 +123,16 @@ describe("copy and paste, kind by kind", () => {expect(useEditor.getState().subtitles.cues).toHaveLength(1);});});++describe("pictureAssetIds", () => {+ test("names what the frame draws and leaves the soundtrack and the shelf out", async () => {+ const { drawnLists, pictureAssetIds } = await import("./itemKinds");+ const doc = {+ clips: [{ assetId: "base", removal: { matte: { assetId: "matte" } } }],+ overlayClips: [{ assetId: "upper" }],+ overlays: [{ kind: "sticker", assetId: "sticker" }],+ audioClips: [{ assetId: "song" }],+ } as never;+ expect([...pictureAssetIds(drawnLists(doc))].sort()).toEqual(["base", "matte", "sticker", "upper"]);+ });+});diff --git a/site/src/cut/lib/itemKinds.ts b/site/src/cut/lib/itemKinds.tsindex 13cbe1e0..35e433ce 100644--- a/site/src/cut/lib/itemKinds.ts+++ b/site/src/cut/lib/itemKinds.ts@@ -235,6 +235,24 @@ export function listedAssetIds(s: ItemLists): Set<string> {return used;}+/** Every asset id whose picture the frame draws: the clips on every video+ * track with what is baked for them, and the elements. What a render has to+ * read the color of before its first frame. */+export const pictureAssetIds = (s: Pick<ItemLists, "clips" | "overlays">): Set<string> =>+ listedAssetIds({ clips: s.clips, overlays: s.overlays, audioClips: [], transitions: [], subtitles: { cues: [] } });++/** The drawn lists of a stored document as it comes off disk or the wire,+ * before the loader folds it: an older doc keeps its upper-track clips in+ * `overlayClips`. */+export const drawnLists = (doc: {+ clips?: VideoClip[];+ overlayClips?: VideoClip[];+ overlays?: Overlay[];+}): Pick<ItemLists, "clips" | "overlays"> => ({+ clips: [...(doc.clips ?? []), ...(doc.overlayClips ?? [])],+ overlays: doc.overlays ?? [],+});+/** A switch over kinds is complete or it does not compile. */export const assertNever = (x: never): never => {throw new Error(`Unhandled item kind ${String(x)}`);diff --git a/site/src/cut/lib/library.ts b/site/src/cut/lib/library.tsindex 18ab67b0..558d0df4 100644--- a/site/src/cut/lib/library.ts+++ b/site/src/cut/lib/library.ts@@ -3,10 +3,12 @@import { uploadCloudLibraryMedia, withCloudPreparedMedia } from "@/cut/lib/cloudLibraryUpload";import type { LibraryUploadStage, LibraryUploadState } from "@/cut/lib/libraryUpload";import { assetTypeOf } from "@/cut/lib/media";-+import { cutColor } from "@/cut/lib/colorSettings";+import { lutFacts, parseLutFile } from "@donkeycut/effects-kit";import { apiJson, getBackend } from "./backend";import { cloudBackend } from "./backend/cloud";import { readSnapshot, writeSnapshot } from "./cache";+import { contentKey } from "./contentKey";import { pollCloudJob } from "./cloudJob";import { downloadFromUrl } from "./download";import { subtreeOf } from "./folderTree";@@ -18,6 +20,7 @@ import {enrichAsset,importRemote,isFontFile,+ isLutFile,MAX_FONT_BYTES,presignedUpload,probeFileMeta,@@ -38,12 +41,23 @@ import { reportSwallowed } from "./report";import { useEditor } from "./store";import { playheadAt } from "./playhead";import type {+ AssetType,LibraryTemplate,MediaAsset,TemplateMedia,TemplateSaveInput,} from "./types";-import { IMAGE_CLIP_SECONDS, mediaUrl } from "./types";+import { IMAGE_CLIP_SECONDS, isLinkedAssetType, mediaUrl } from "./types";+++/** A LUT goes by its file's name. The TITLE line inside the file is whatever+ * the tool that wrote it put there. */+export const lutFileName = (fileName: string) => fileName.replace(/\.[^.]+$/, "");++/** What a Library file is called wherever it is shown: a LUT by its file name,+ * a clip by the title read off it, anything else by its name. */+export const libraryAssetName = (a: Pick<LibraryAsset, "type" | "fileName" | "name" | "title">) =>+ a.type === "lut" ? lutFileName(a.fileName) : a.title || a.name;export interface LibrarySource {url: string;@@ -52,19 +66,28 @@ export interface LibrarySource {uploadDate?: string;}+/** What a LUT's row says about its table. */+export type LutFactsMeta = { kind: "1d" | "3d" | "shaper+3d"; size: number };+export interface LibraryAsset {id: string;fileName: string;/** Uploaded source retained when playback needs conversion. */originalFile?: string;name: string;- type: "video" | "audio" | "image" | "font";+ type: AssetType;duration: number;width?: number;height?: number;addedAt: number;folderId?: string | null;source?: LibrarySource;+ /** A linked item's identity — the content hash every project names it by.+ * Written by the page that checked the file, so a sync of a lazy kind+ * never reads the bytes back. */+ contentKey?: string;+ /** For a LUT, what kind of table the file holds. */+ lut?: LutFactsMeta;/** The source's own cover image, stored beside the media on the same shelf.* An import from a site that publishes one carries it; it is what a card and* the viewer show while the video itself loads. */@@ -544,8 +567,8 @@ export async function carryAssetTo();if (!res.ok) throw new Error("Could not read that file off its shelf.");// A font's cover is baked from its bytes on the way in, so the shelf it- // lands on draws its own — always the current sheet.- const from = asset.type === "font" ? undefined : libraryPosterUrl(asset);+ // lands on draws its own — always the current sheet. A LUT has none.+ const from = isLinkedAssetType(asset.type) ? undefined : libraryPosterUrl(asset);const cover = from? await backendFor(asset.residency).fetch(@@ -598,6 +621,48 @@ async function checkFont(};}+/** A LUT is readable when the parser takes it, so the file is parsed once+ * here — a truncated download or a renamed text file is refused before a byte+ * leaves the browser. What comes back is the row's fields: the content key+ * every project names it by and what kind of table it is, so a sync lists+ * the shelf without reading the file again. */+async function checkLut(+ file: File,+): Promise<{ label: string; meta: LinkedUploadMeta }> {+ const maxBytes = cutColor().lutFileMaxBytes;+ if (file.size > maxBytes) {+ throw new Error(+ `LUT files are limited to ${Math.round(maxBytes / 1024 ** 2)}MB.`,+ );+ }+ const bytes = await file.arrayBuffer();+ let parsed: ReturnType<typeof parseLutFile>;+ try {+ parsed = parseLutFile(file.name, new TextDecoder().decode(bytes));+ } catch (e) {+ throw new Error(+ `That file isn't a LUT Cut can read. ${e instanceof Error ? e.message : ""}`.trim(),+ );+ }+ return {+ label: lutFileName(file.name),+ meta: {+ type: "lut",+ duration: 0,+ contentKey: await contentKey(bytes),+ lut: lutFacts(parsed),+ },+ };+}++/** The row a linked upload writes in place of a probe. */+type LinkedUploadMeta = {+ type: "font" | "lut";+ duration: 0;+ contentKey?: string;+ lut?: LutFactsMeta;+};+export async function uploadToLibrary(file: File,residency: Residency = activeResidency(),@@ -607,22 +672,26 @@ export async function uploadToLibrary(keep: { name?: string; source?: LibrarySource; poster?: Blob; folderId?: string | null; state?: LibraryUploadState; onStage?: (stage: LibraryUploadStage) => void } = {},): Promise<LibraryAsset> {const backend = backendFor(residency);- // A font has no streams to measure; it is checked by installing it instead,- // and the check hands back the specimen the shelf keeps as its cover.+ // A linked item has no streams to measure. A font is checked by installing+ // it, and the check hands back the specimen the shelf keeps as its cover;+ // a LUT is checked by parsing it, and the check hands back its row.const font = isFontFile(file) ? await checkFont(file) : null;- const fontLabel = font?.label ?? null;+ const lut = !font && isLutFile(file) ? await checkLut(file) : null;+ const linkedLabel = font?.label ?? lut?.label ?? null;const poster = keep.poster ?? font?.poster ?? null;const posterName = `${file.name}${SPECIMEN_FILE_SUFFIX}`;- const fontMeta = { type: "font" as const, duration: 0 };+ const linkedMeta: LinkedUploadMeta | null = font+ ? { type: "font", duration: 0 }+ : (lut?.meta ?? null);if (residency === "cloud") {const type = assetTypeOf(file);- const meta = fontLabel ? fontMeta : await probeFileMeta(file).catch(() => null);+ const meta = linkedMeta ?? (await probeFileMeta(file).catch(() => null));if ((!meta || !(meta.duration > 0)) && (type === "video" || type === "audio")) {return uploadCloudLibraryMedia(file, keep);}if (!meta ||- (meta.type !== "image" && meta.type !== "font" && !(meta.duration > 0))+ (meta.type !== "image" && !isLinkedAssetType(meta.type) && !(meta.duration > 0))) {throw new Error("This image could not be read.",@@ -651,7 +720,7 @@ export async function uploadToLibrary(key,...(posterKey ? { posterKey } : {}),meta: {- name: keep.name ?? fontLabel ?? file.name,+ name: keep.name ?? linkedLabel ?? file.name,...(keep.source ? { source: keep.source } : {}),...meta,},@@ -663,16 +732,16 @@ export async function uploadToLibrary(}const form = new FormData();form.append("file", file, file.name);- const name = keep.name ?? fontLabel;+ const name = keep.name ?? linkedLabel;if (name) form.append("name", name);if (keep.source) form.append("source", JSON.stringify(keep.source));if (poster) form.append("poster", poster, posterName);if (residency === "browser") {// Hosted preparation supplies missing decoders before the page stores media.- const meta = fontLabel ? fontMeta : await probeFileMeta(file).catch(() => null);+ const meta = linkedMeta ?? (await probeFileMeta(file).catch(() => null));if (!meta ||- (meta.type !== "image" && meta.type !== "font" && !(meta.duration > 0))+ (meta.type !== "image" && !isLinkedAssetType(meta.type) && !(meta.duration > 0))) {const type = assetTypeOf(file);if (type === "video" || type === "audio") {@@ -684,6 +753,8 @@ export async function uploadToLibrary(throw new Error("This image could not be read.");}form.append("meta", JSON.stringify(meta));+ } else if (linkedMeta) {+ form.append("meta", JSON.stringify(linkedMeta));} else {const type = assetTypeOf(file);if ((type === "video" || type === "audio") && !(await probeFileMeta(file).catch(() => null))) {@@ -768,6 +839,8 @@ export async function importLibraryAsset(): Promise<MediaAsset> {if (lib.type === "font")throw new Error("Fonts are used from the font menu, not the timeline.");+ if (isLinkedAssetType(lib.type))+ throw new Error("A LUT is applied to a clip's color, from the Color panel.");// The project's media takes the name the shelf shows, so a phone// recording lands on the timeline under its title.const name = lib.title || lib.name;@@ -915,6 +988,8 @@ export async function carryTemplateTo(...(t.stickers ? { stickers: t.stickers } : {}),...(t.captions ? { captions: t.captions } : {}),...(t.project ? { project: t.project } : {}),+ ...(t.sound ? { sound: t.sound } : {}),+ ...(t.grade ? { grade: t.grade } : {}),};const backend = backendFor(to);let res: Response;diff --git a/site/src/cut/lib/libraryFileType.test.ts b/site/src/cut/lib/libraryFileType.test.tsnew file mode 100644index 00000000..07fea640--- /dev/null+++ b/site/src/cut/lib/libraryFileType.test.ts@@ -0,0 +1,19 @@+import { describe, expect, test } from "bun:test";+import { libraryTypeOf } from "./libraryFileType";++describe("libraryTypeOf", () => {+ test("reads the kind off the extension, whatever its case", () => {+ expect(libraryTypeOf("clip.MOV")).toBe("video");+ expect(libraryTypeOf("song.m4a")).toBe("audio");+ expect(libraryTypeOf("still.jpeg")).toBe("image");+ expect(libraryTypeOf("Inter.woff2")).toBe("font");+ expect(libraryTypeOf("Kodak 2383.cube")).toBe("lut");+ expect(libraryTypeOf("look.3DL")).toBe("lut");+ });++ test("refuses what no shelf takes", () => {+ expect(libraryTypeOf("notes.txt")).toBeNull();+ expect(libraryTypeOf("archive.zip")).toBeNull();+ expect(libraryTypeOf("cube")).toBeNull();+ });+});diff --git a/site/src/cut/lib/libraryFileType.ts b/site/src/cut/lib/libraryFileType.tsnew file mode 100644index 00000000..04ddf957--- /dev/null+++ b/site/src/cut/lib/libraryFileType.ts@@ -0,0 +1,20 @@+// What kind of library asset a file name makes. One table for every shelf —+// the engine's disk, the cloud rows, the browser's store — and for the page+// that files a drop, so no shelf takes a file another would refuse. The+// extension is a technical field, never the user's words.+import type { AssetType } from "./types";++export const VIDEO_RE = /\.(mp4|mov|m4v|webm|mkv)$/i;+export const AUDIO_RE = /\.(mp3|m4a|aac|wav|ogg|flac)$/i;+export const IMAGE_RE = /\.(png|jpe?g|webp|gif|avif|bmp)$/i;+export const FONT_RE = /\.(ttf|otf|woff2?)$/i;+export const LUT_RE = /\.(cube|3dl)$/i;++export function libraryTypeOf(fileName: string): AssetType | null {+ if (VIDEO_RE.test(fileName)) return "video";+ if (AUDIO_RE.test(fileName)) return "audio";+ if (IMAGE_RE.test(fileName)) return "image";+ if (FONT_RE.test(fileName)) return "font";+ if (LUT_RE.test(fileName)) return "lut";+ return null;+}diff --git a/site/src/cut/lib/libraryMention.test.ts b/site/src/cut/lib/libraryMention.test.tsnew file mode 100644index 00000000..0f785bf3--- /dev/null+++ b/site/src/cut/lib/libraryMention.test.ts@@ -0,0 +1,29 @@+import { describe, expect, test } from "bun:test";+import { refFromLibrary } from "./assetRef";+import { refsToParts } from "./refMedia";+import type { LibraryAsset } from "./library";++const row = (a: Pick<LibraryAsset, "id" | "fileName" | "type"> & Partial<LibraryAsset>): LibraryAsset => ({+ name: a.fileName,+ duration: 0,+ addedAt: 1,+ residency: "cloud",+ ...a,+});++describe("Library files in chat references", () => {+ test("a LUT file reaches the model as the set_color_lut call that uses it", async () => {+ const ref = refFromLibrary(row({ id: "l1", fileName: "Teal.cube", name: "Teal", type: "lut", contentKey: "abc123" }));+ expect(ref.use).toEqual({ noun: "LUT file", tool: "set_color_lut", args: { lut: "lut:abc123" } });+ expect(ref.fileType).toBe("lut");+ const { parts, visuals } = await refsToParts([ref]);+ expect(visuals).toHaveLength(0);+ expect(parts).toEqual([+ { text: 'Referenced LUT file "Teal" in the Library. Use it with set_color_lut: {"lut":"lut:abc123"}' },+ ]);+ });++ test("a LUT row with no content key has no id to hand chat", () => {+ expect(refFromLibrary(row({ id: "l2", fileName: "old.cube", type: "lut" })).use).toBeUndefined();+ });+});diff --git a/site/src/cut/lib/librarySharing.ts b/site/src/cut/lib/librarySharing.tsindex 64a85fd1..7646688b 100644--- a/site/src/cut/lib/librarySharing.ts+++ b/site/src/cut/lib/librarySharing.ts@@ -1,4 +1,5 @@import { z } from "zod";+import type { AssetType } from "./types";export const LIBRARY_SHARE_KINDS = ["folder", "asset"] as const;export const SHARE_ACCESS = ["restricted", "public"] as const;@@ -19,7 +20,7 @@ export type LibraryShareState = ShareSettings & { id: string };export type SharedLibraryAsset = {id: string;name: string;- type: "video" | "audio" | "image" | "font";+ type: AssetType;duration: number;fileName: string;width?: number;diff --git a/site/src/cut/lib/lightbox.ts b/site/src/cut/lib/lightbox.tsindex 5c893fe0..8e406ecd 100644--- a/site/src/cut/lib/lightbox.ts+++ b/site/src/cut/lib/lightbox.ts@@ -2,7 +2,7 @@import { create } from "zustand";import type { AssetRef } from "./assetRef";-import { libraryMediaUrl, libraryPosterUrl, type LibraryAsset } from "./library";+import { libraryAssetName, libraryMediaUrl, libraryPosterUrl, type LibraryAsset } from "./library";import type { MediaAsset } from "./types";// The asset lightbox: a full-screen viewer opened from stock tiles, generated@@ -10,7 +10,7 @@ import type { MediaAsset } from "./types";// surface can open it and a single mounted overlay renders it.export interface LightboxItem {- kind: "video" | "image" | "audio" | "text" | "font";+ kind: "video" | "image" | "audio" | "text" | "font" | "lut";/** Fetchable source for the media or file. */src: string;name: string;@@ -40,7 +40,7 @@ export interface LightboxItem {/** The lightbox view of an asset ref — how chat cards and attachment chips* open the big version of whatever they show. */export const lightboxItemFromRef = (ref: AssetRef): LightboxItem => ({- kind: ref.kind,+ kind: ref.fileType ?? ref.kind,src: ref.url,name: ref.name,prompt: "",@@ -75,7 +75,7 @@ export const lightboxItemFromLibrary = (src: libraryMediaUrl(a.fileName, a.residency),// The title read off the clip is what it is called wherever it is shown, so// the viewer captions it that way and an import from here lands under it.- name: a.title || a.name,+ name: libraryAssetName(a),prompt: "",assetId: null,libraryId: a.id,diff --git a/site/src/cut/lib/linkedLibrary/fonts.ts b/site/src/cut/lib/linkedLibrary/fonts.tsindex d57b73bd..0eaabe90 100644--- a/site/src/cut/lib/linkedLibrary/fonts.ts+++ b/site/src/cut/lib/linkedLibrary/fonts.ts@@ -24,6 +24,7 @@ import {registerLinkedKind,uploadLinkedItem,type LinkedItem,+ type LinkedKind,} from "./registry";import type { ProjectDoc } from "../types";import { registerFonts, unregisterFonts } from "../types";@@ -37,7 +38,8 @@ export const libraryFontId = (key: string) => linkId(PREFIX, key);/** The CSS/skia family name its bytes are installed under. */const familyOf = (key: string) => `lf-${key}`;-registerLinkedKind({+/** The font kind as the registry holds it. */+export const fontKind: LinkedKind = {prefix: PREFIX,type: "font",homeFolder: "Fonts",@@ -62,7 +64,8 @@ registerLinkedKind({unregisterFonts(keys.map(libraryFontId));forgetTextWidths();},-});+};+registerLinkedKind(fontKind);/** The account's fonts, one entry per typeface however many shelves hold it. */export const listLibraryFonts = (): LinkedItem[] => listLinked(PREFIX);diff --git a/site/src/cut/lib/linkedLibrary/index.ts b/site/src/cut/lib/linkedLibrary/index.tsindex 59c195ff..acd6a1f0 100644--- a/site/src/cut/lib/linkedLibrary/index.ts+++ b/site/src/cut/lib/linkedLibrary/index.ts@@ -14,6 +14,16 @@*/import "./fonts";+import "./luts";export * from "./registry";export { libraryFontId, listLibraryFonts, uploadLibraryFont } from "./fonts";+export {+ cachedLut,+ libraryLutId,+ listLibraryLuts,+ loadLibraryLut,+ LUT_FILE_ICON,+ LUT_MARK_ICON,+ lutIdOf,+} from "./luts";diff --git a/site/src/cut/lib/linkedLibrary/luts.test.ts b/site/src/cut/lib/linkedLibrary/luts.test.tsnew file mode 100644index 00000000..fb80f5c1--- /dev/null+++ b/site/src/cut/lib/linkedLibrary/luts.test.ts@@ -0,0 +1,88 @@+import { describe, expect, test } from "bun:test";+import { stubModule } from "@/lib/testing/stubModule";+import type { LibraryAsset, LibraryData } from "../library";+import type { ProjectDoc } from "../types";++/** A 2-node identity cube, as a shelf would serve it. */+const CUBE = [+ "LUT_3D_SIZE 2",+ "0 0 0", "1 0 0", "0 1 0", "1 1 0",+ "0 0 1", "1 0 1", "0 1 1", "1 1 1",+].join("\n");++const shelf: LibraryAsset[] = [+ {+ id: "l1",+ fileName: "look.cube",+ name: "Look",+ type: "lut",+ duration: 0,+ addedAt: 1,+ residency: "cloud",+ contentKey: "abc123",+ lut: { kind: "3d", size: 2 },+ },+];++const fetched: string[] = [];+await stubModule<typeof import("../library")>("../library", import.meta.url, {+ fetchLibrary: async (): Promise<LibraryData> => ({ assets: shelf, folders: [], templates: [] }),+});+await stubModule<typeof import("../residency")>("../residency", import.meta.url, {+ backendFor: (() => ({+ fetch: async (path: string) => {+ fetched.push(path);+ return new Response(CUBE);+ },+ })) as never,+});+await stubModule<typeof import("../cache")>("../cache", import.meta.url, {+ readSnapshot: async () => null,+ writeSnapshot: () => {},+});++const { linkedIdsIn, syncLinkedLibrary } = await import("./registry");+const { cachedLut, loadLibraryLut, lutIdOf, lutKind } = await import("./luts");++const grade = (id: string) => ({ lut: { id } }) as unknown as NonNullable<ProjectDoc["clips"][number]["grade"]>;++describe("the LUT kind", () => {+ test("files a new LUT where it was dropped, like any Library file", () => {+ expect(lutKind.homeFolder).toBeUndefined();+ });++ test("extracts the LUTs clips, template layers and saved grades name", () => {+ const doc = {+ clips: [+ { id: "c1", grade: grade("lut:aaa") },+ { id: "c2", grade: grade("lut:aaa") },+ { id: "c3", grade: { exposure: 1 } },+ { id: "c4" },+ ],+ templates: [+ { id: "t1", grade: grade("lut:bbb"), layers: [{ grade: grade("lut:ccc") }, {}] },+ { id: "t2", layers: [] },+ ],+ } as unknown as ProjectDoc;+ expect(linkedIdsIn(doc).filter((id) => id.startsWith("lut:")).sort()).toEqual([+ "lut:aaa",+ "lut:bbb",+ "lut:ccc",+ ]);+ expect(lutIdOf(grade("font:zzz"))).toBeNull();+ expect(lutIdOf(undefined)).toBeNull();+ });++ test("reads a LUT's bytes once, on demand, and keeps the parsed table", async () => {+ await syncLinkedLibrary();+ expect(fetched).toEqual([]);+ expect(cachedLut("lut:abc123")).toBeUndefined();+ const lut = await loadLibraryLut("lut:abc123");+ expect(lut.cube?.size).toBe(2);+ expect(fetched).toEqual(["/api/cut/library/media/look.cube"]);+ expect(await loadLibraryLut("lut:abc123")).toBe(lut);+ expect(cachedLut("lut:abc123")).toBe(lut);+ expect(fetched.length).toBe(1);+ await expect(loadLibraryLut("lut:missing")).rejects.toThrow(/not in the library/);+ });+});diff --git a/site/src/cut/lib/linkedLibrary/luts.ts b/site/src/cut/lib/linkedLibrary/luts.tsnew file mode 100644index 00000000..38588e7e--- /dev/null+++ b/site/src/cut/lib/linkedLibrary/luts.ts@@ -0,0 +1,162 @@+"use client";++/**+ * The account's colour LUTs: `.cube` and `.3dl` files on the Library shelf,+ * named by a clip's grade (`grade.lut.id = "lut:<contentKey>"`) and read the+ * moment a renderer needs the table.+ *+ * A LUT is a linked kind, so identity, placement and travelling with a+ * project live in `registry.ts`. It is also a lazy one: the page that shelved+ * the file parsed it and wrote its content key onto the row, so listing the+ * shelf reads no bytes. The parsed tables are held here under the memory+ * budget and read back on demand.+ */++import { lutBytes, parseLutFile, type ColorGrade, type ParsedLut } from "@donkeycut/effects-kit";+import { allowance, holdMemory } from "../memoryBudget";+import { lutFileName } from "../library";+import { isLutFile, LUT_ACCEPT } from "../media";+import type { ProjectDoc } from "../types";+import {+ linkedBytes,+ linkId,+ listLinked,+ registerLinkedKind,+ type LinkedItem,+ type LinkedKind,+} from "./registry";++const PREFIX = "lut";++/** The grade id a shelf LUT answers to. */+export const libraryLutId = (key: string) => linkId(PREFIX, key);++/** The file icon with its wordmark: the tile where the file sits at rest. */+export const LUT_FILE_ICON = "/cut/lut-file.svg";+/** The file icon alone: the drag ghost, a clip's LUT badge, the applied chip. */+export const LUT_MARK_ICON = "/cut/lut-file-mark.svg";++/** The LUT a grade names, when it names one off the shelf. */+export function lutIdOf(grade: ColorGrade | undefined | null): string | null {+ const id = (grade as { lut?: { id?: unknown } } | null | undefined)?.lut?.id;+ return typeof id === "string" && id.startsWith(`${PREFIX}:`) ? id : null;+}++/** Bytes of parsed tables kept, before the budget has its say. */+const TUNED_BYTES = 32 * 2 ** 20;++/** Parsed LUTs by id, oldest use first. */+const tables = new Map<string, { lut: ParsedLut; bytes: number }>();+let held = 0;+holdMemory("lutTables", () => held);++function remember(id: string, lut: ParsedLut): void {+ const bytes = lutBytes(lut);+ forget(id);+ const cap = allowance("lutTables", TUNED_BYTES);+ for (const [oldest, entry] of tables) {+ if (held + bytes <= cap) break;+ tables.delete(oldest);+ held -= entry.bytes;+ }+ tables.set(id, { lut, bytes });+ held += bytes;+}++function forget(id: string): void {+ const hit = tables.get(id);+ if (!hit) return;+ tables.delete(id);+ held -= hit.bytes;+}++/** A parsed LUT already in hand, bumped to most recently used. */+export function cachedLut(id: string): ParsedLut | undefined {+ const hit = tables.get(id);+ if (!hit) return undefined;+ tables.delete(id);+ tables.set(id, hit);+ return hit.lut;+}++const loading = new Map<string, Promise<ParsedLut>>();++/** The parsed LUT for a grade id, read off whichever shelf holds it. Fails+ * when no shelf in reach has it, naming the id. */+export function loadLibraryLut(id: string): Promise<ParsedLut> {+ const hit = cachedLut(id);+ if (hit) return Promise.resolve(hit);+ let pending = loading.get(id);+ if (pending) return pending;+ pending = (async () => {+ const item = listLinked(PREFIX).find((i) => libraryLutId(i.key) === id);+ if (!item) throw new Error(`The LUT ${id} is not in the library.`);+ let lastError: unknown = null;+ for (const copy of item.copies) {+ try {+ const bytes = await linkedBytes({+ id: copy.assetId,+ fileName: copy.fileName,+ residency: copy.residency,+ });+ const lut = parseLutFile(copy.fileName, new TextDecoder().decode(bytes));+ remember(id, lut);+ return lut;+ } catch (e) {+ lastError = e; // That shelf isn't answering; another copy may still serve.+ }+ }+ throw lastError instanceof Error ? lastError : new Error(`Could not read the LUT ${id}.`);+ })().finally(() => loading.delete(id));+ loading.set(id, pending);+ return pending;+}++/** The LUT file itself, off whichever shelf holds it: what an export stages+ * beside its pictures so the engine parses the same bytes the tab did. Fails+ * naming the id when no shelf in reach has it. */+export async function loadLibraryLutFile(id: string): Promise<{ fileName: string; bytes: Uint8Array }> {+ const item = listLinked(PREFIX).find((i) => libraryLutId(i.key) === id);+ if (!item) throw new Error(`The LUT ${id} is not in the library.`);+ let lastError: unknown = null;+ for (const copy of item.copies) {+ try {+ const bytes = await linkedBytes({ id: copy.assetId, fileName: copy.fileName, residency: copy.residency });+ return { fileName: copy.fileName, bytes: new Uint8Array(bytes) };+ } catch (e) {+ lastError = e;+ }+ }+ const why = lastError instanceof Error ? ` ${lastError.message}` : "";+ throw new Error(`The LUT "${item.label}" could not be read.${why}`);+}++/** The LUT kind as the registry holds it. */+export const lutKind: LinkedKind = {+ prefix: PREFIX,+ type: "lut",+ lazy: true,+ labelOf: (a) => lutFileName(a.fileName),+ matches: isLutFile,+ accept: LUT_ACCEPT,+ extract: (doc: ProjectDoc) => {+ const ids = new Set<string>();+ const take = (grade: ColorGrade | undefined) => {+ const id = lutIdOf(grade);+ if (id) ids.add(id);+ };+ for (const c of doc.clips ?? []) take(c.grade);+ for (const t of doc.templates ?? []) {+ take(t.grade);+ for (const l of t.layers ?? []) take(l.grade);+ }+ return [...ids];+ },+ drop: (keys) => {+ for (const key of keys) forget(libraryLutId(key));+ },+};+registerLinkedKind(lutKind);++/** The account's LUTs, one entry per file however many shelves hold it. */+export const listLibraryLuts = (): LinkedItem[] => listLinked(PREFIX);diff --git a/site/src/cut/lib/linkedLibrary/registry.test.ts b/site/src/cut/lib/linkedLibrary/registry.test.tsnew file mode 100644index 00000000..1d645a4b--- /dev/null+++ b/site/src/cut/lib/linkedLibrary/registry.test.ts@@ -0,0 +1,100 @@+import { afterAll, describe, expect, test } from "bun:test";+import { stubModule } from "@/lib/testing/stubModule";+import type { LibraryAsset, LibraryData } from "../library";++/**+ * A lazy kind is keyed off its shelf row. Listing the account's LUTs reads no+ * bytes; the eager kinds beside them are still read and keyed by content.+ */++const row = (a: Partial<LibraryAsset> & Pick<LibraryAsset, "id" | "fileName" | "type">): LibraryAsset => ({+ name: a.fileName,+ duration: 0,+ addedAt: 1,+ residency: "cloud",+ ...a,+});++const shelf: LibraryAsset[] = [+ row({ id: "l1", fileName: "look.cube", type: "lut", contentKey: "abc123" }),+ // The same LUT on a second shelf: one item, two copies.+ row({ id: "l2", fileName: "look-copy.cube", type: "lut", contentKey: "abc123", residency: "browser" }),+ // Shelved before the row carried a key: nothing to list it by.+ row({ id: "l3", fileName: "unkeyed.cube", type: "lut" }),+ row({ id: "f1", fileName: "Inter.ttf", type: "font" }),+];++const fetched: string[] = [];+await stubModule<typeof import("../library")>("../library", import.meta.url, {+ fetchLibrary: async (): Promise<LibraryData> => ({ assets: shelf, folders: [], templates: [] }),+});+await stubModule<typeof import("../residency")>("../residency", import.meta.url, {+ backendFor: (() => ({+ fetch: async (path: string) => {+ fetched.push(path);+ return new Response(new Uint8Array([1, 2, 3]));+ },+ })) as never,+});+await stubModule<typeof import("../cache")>("../cache", import.meta.url, {+ readSnapshot: async () => null,+ writeSnapshot: () => {},+});++const { registerLinkedKind, syncLinkedLibrary, listLinked, linkedAccept, linkedTypeOfFile } = await import(+ "./registry"+);++// The kinds below stand in for the real ones under the same prefixes; the+// real registrations come back once this file is done.+afterAll(async () => {+ const [{ lutKind }, { fontKind }] = await Promise.all([import("./luts"), import("./fonts")]);+ registerLinkedKind(lutKind);+ registerLinkedKind(fontKind);+});++const used: string[] = [];+registerLinkedKind({+ prefix: "lut",+ type: "lut",+ lazy: true,+ matches: (f) => /\.cube$/i.test(f.name),+ accept: ".cube",+ extract: () => [],+});+registerLinkedKind({+ prefix: "font",+ type: "font",+ matches: (f) => /\.ttf$/i.test(f.name),+ accept: ".ttf",+ extract: () => [],+ use: async (key) => {+ used.push(key);+ },+});++describe("syncLinkedLibrary", () => {+ test("keys a lazy kind off its rows and reads no bytes for it", async () => {+ await syncLinkedLibrary();+ // Only the font came down: one read, one key made from its bytes.+ expect(fetched).toEqual(["/api/cut/library/media/Inter.ttf"]);+ expect(used.length).toBe(1);+ const luts = listLinked("lut");+ expect(luts.map((i) => i.key)).toEqual(["abc123"]);+ // The cloud copy names the item; both shelves hold it.+ expect(luts[0].label).toBe("look.cube");+ expect(luts[0].copies.map((c) => c.assetId).sort()).toEqual(["l1", "l2"]);+ });+});++describe("kind lookups", () => {+ test("a picker can ask for one kind's accept", () => {+ expect(linkedAccept("lut")).toBe(".cube");+ expect(linkedAccept()).toBe(".cube,.ttf");+ });++ test("a dropped file names the kind that shelves it", () => {+ expect(linkedTypeOfFile(new File([""], "grade.cube"))).toBe("lut");+ expect(linkedTypeOfFile(new File([""], "clip.mp4"))).toBeNull();+ });+});diff --git a/site/src/cut/lib/linkedLibrary/registry.ts b/site/src/cut/lib/linkedLibrary/registry.tsindex 0c50d3b5..5b4113cb 100644--- a/site/src/cut/lib/linkedLibrary/registry.ts+++ b/site/src/cut/lib/linkedLibrary/registry.ts@@ -24,6 +24,7 @@*/import { readSnapshot, writeSnapshot } from "../cache";+import { contentKey } from "../contentKey";import {fetchLibrary,moveLibraryItem,@@ -59,6 +60,11 @@ export interface LinkedKind {prefix: string;/** The library asset type carrying it. */type: LibraryAsset["type"];+ /** A kind keyed off its shelf row: the page that shelved the file wrote its+ * content key onto the row (`LibraryAsset.contentKey`), so a sync lists it+ * without reading a byte. Its bytes are read when something uses it. A row+ * without a key is left out of the listing. */+ lazy?: true;/** The ids of this kind a document is set in, so a project move can carry* them. */extract: (doc: ProjectDoc) => string[];@@ -67,6 +73,8 @@ export interface LinkedKind {use?: (key: string, label: string, bytes: ArrayBuffer) => Promise<void>;/** Keys that have left the shelf, so the feature can drop them. */drop?: (keys: string[]) => void;+ /** What an item is called, when that is not the shelf row's name. */+ labelOf?: (a: LibraryAsset) => string;/** Folder a new one is filed into when the shelf has one by that name. */homeFolder?: string;/** Whether a dropped OS file is one of these. */@@ -97,9 +105,13 @@ export const isLinkedType = (type: LibraryAsset["type"]): boolean =>export const isLinkedFile = (file: File): boolean =>[...kinds.values()].some((k) => k.matches(file));-/** What every linked kind takes, for a file input's `accept`. */-export const linkedAccept = (): string =>- [...kinds.values()].flatMap((k) => (k.accept ? [k.accept] : [])).join(",");+/** What every linked kind takes, for a file input's `accept` — or one kind's,+ * for a picker that offers only that. */+export const linkedAccept = (prefix?: string): string =>+ [...kinds.values()]+ .filter((k) => !prefix || k.prefix === prefix)+ .flatMap((k) => (k.accept ? [k.accept] : []))+ .join(",");/** The library asset type a dropped OS file would shelve as, when a linked* kind claims it. */@@ -169,13 +181,7 @@ function publish(next: LinkedItem[]): void {for (const cb of listeners) cb();}-/** An item's identity: enough SHA-256 to never collide in one account's shelf. */-export async function contentKey(bytes: ArrayBuffer): Promise<string> {- const digest = await crypto.subtle.digest("SHA-256", bytes);- return [...new Uint8Array(digest).slice(0, 8)]- .map((b) => b.toString(16).padStart(2, "0"))- .join("");-}+export { contentKey };const bytesKey = (assetId: string) => `linked/${assetId}`;@@ -186,7 +192,9 @@ const bytesKey = (assetId: string) => `linked/${assetId}`;* Read through the shelf's own backend rather than its URL: a render job* carries its auth in headers the page gets from a cookie, and the browser* shelf answers in the page rather than over the network. */-export async function linkedBytes(a: LibraryAsset): Promise<ArrayBuffer> {+export async function linkedBytes(+ a: Pick<LibraryAsset, "id" | "fileName" | "residency">,+): Promise<ArrayBuffer> {try {const res = await backendFor(a.residency).fetch(`/api/cut/library/media/${encodeURIComponent(a.fileName)}`,@@ -206,12 +214,12 @@ function put(kind: LinkedKind,key: string,label: string,- bytes: ArrayBuffer,+ bytes: ArrayBuffer | null,): Promise<void> {const id = linkId(kind.prefix, key);let hit = used.get(id);if (hit) return hit;- hit = (kind.use ? kind.use(key, label, bytes) : Promise.resolve()).catch(+ hit = (kind.use && bytes ? kind.use(key, label, bytes) : Promise.resolve()).catch(() => {// Bytes that will not load: drop the marker so a later pass retries, and// let whatever points at them fall back.@@ -246,10 +254,12 @@ export async function syncLinkedLibrary(): Promise<void> {// order: two shelves holding one item may have stored it under different// names, and a menu should not label it differently from one session to the// next. The cloud copy's name wins, since that is the one every surface reads.+ // A lazy kind is keyed off its row and read only when used.const read = await Promise.all(shelf.map(async (a) => {const kind = kindFor(a);if (!kind) return null;+ if (kind.lazy) return a.contentKey ? { a, kind, bytes: null, key: a.contentKey } : null;try {const bytes = await linkedBytes(a);return { a, kind, bytes, key: await contentKey(bytes) };@@ -267,7 +277,8 @@ export async function syncLinkedLibrary(): Promise<void> {);const found = new Map<string, LinkedItem>();for (const { a, kind, bytes, key } of ordered) {- await put(kind, key, a.name, bytes);+ const label = kind.labelOf?.(a) ?? a.name;+ await put(kind, key, label, bytes);const copy: LinkedCopy = {assetId: a.id,residency: a.residency,@@ -281,7 +292,7 @@ export async function syncLinkedLibrary(): Promise<void> {found.set(id, {key,prefix: kind.prefix,- label: a.name,+ label,copies: [copy],});}diff --git a/site/src/cut/lib/lutBuild.ts b/site/src/cut/lib/lutBuild.tsnew file mode 100644index 00000000..ce0197e0--- /dev/null+++ b/site/src/cut/lib/lutBuild.ts@@ -0,0 +1,460 @@+/**+ * Where a clip's color LUT comes from.+ *+ * A clip's color is one recipe — its source profile, its grade, the project's+ * output space and a lattice size — and the kit bakes that recipe into a 3D+ * LUT (effects-kit colorPipeline.ts). Baking is the one expensive step, and+ * it must never hold the frame loop: in the tab a module Worker builds the+ * lattice and transfers it back, and the compositor keeps drawing the last+ * LUT it had for the clip until the new one lands. A process with no Worker+ * (the headless runner, tests) builds inline, and a caller that needs the+ * exact picture now (an export) asks for it inline in the tab too.+ *+ * Sizes come from the color setting: the standard cube for Rec.709 and sRGB+ * sources, the wide cube for log and HDR, and a draft cube while a slider is+ * moving — the full cube follows when the drag settles. The built LUTs are a+ * cache bounded in bytes through the memory budget.+ */++import {+ buildClipLut,+ recipeKey,+ type ClipColorRecipe,+ type ColorGrade,+ type GradeLut,+ type OutputSpace,+ type ParsedLut,+ type SourceProfile,+} from "@donkeycut/effects-kit";+import { cutColor } from "./colorSettings";+import { cachedLut, loadLibraryLut, lutIdOf } from "./linkedLibrary/luts";+import { allowance, holdMemory } from "./memoryBudget";+import { colorRead, type ReadFile } from "./sourceColor";+import type { MediaAsset } from "./types";++/** The source half of a recipe: the profile, the file's matrix and range,+ * and the ones this process drew the picture with (sourceColor.ts). */+export type RecipeSource = Omit<ClipColorRecipe, "grade" | "output" | "size">;++type LookupAsset = { id: string } & Pick<MediaAsset, "color" | "proxyUrl">;++const lookups = new WeakMap<object, Map<unknown, (clip: { assetId: string }) => RecipeSource>>();++/** A clip → source lookup over a document's assets, for frames read from+ * `fileOf(asset)`: the reader that draws the clip names the same file, so+ * the recipe describes the frames it hands over. Kept per assets array and+ * file choice, so a frame loop pays one map build per document change. The+ * source itself is read per call: the decode route's measurement can settle+ * after the map was built, and the recipe key follows it. */+export function sourceLookup(+ assets: readonly LookupAsset[],+ fileOf: (asset: LookupAsset) => ReadFile+): (clip: { assetId: string }) => RecipeSource {+ let byFile = lookups.get(assets);+ if (!byFile) lookups.set(assets, (byFile = new Map()));+ let fn = byFile.get(fileOf);+ if (!fn) {+ const byId = new Map(assets.map((a) => [a.id, a] as const));+ fn = (clip) => {+ const asset = byId.get(clip.assetId);+ return asset ? colorRead(asset, fileOf(asset)).recipe() : REC709;+ };+ byFile.set(fileOf, fn);+ }+ return fn;+}++const REC709: RecipeSource = { profile: "rec709" };++const isSdrSource = (profile: SourceProfile) => profile === "rec709" || profile === "srgb";++/** Lattice nodes per axis for a source, at draft or full quality. */+export function lutSizeFor(profile: SourceProfile, draft = false): number {+ const c = cutColor();+ return draft ? c.draftLutSize : isSdrSource(profile) ? c.lutSize : c.lutSizeWide;+}++/* ------------------------------------------------------------------ */+/* Draft mode */+/* ------------------------------------------------------------------ */++let drafting = 0;++/** A slider drag has begun: LUTs build at the draft size until it ends. */+export function beginLutDraft(): void {+ drafting++;+}++export function endLutDraft(): void {+ drafting = Math.max(0, drafting - 1);+}++export const lutDraftActive = (): boolean => drafting > 0;++/** Recipes already made, by grade object, then source object, then output+ * and size. The compositor asks for every graded clip's recipe every frame,+ * and grades, sources and recipes are all replaced whole when they change,+ * so a frame that changes nothing hands back the recipe it had — and the key+ * cached on it — without building either again. */+const NO_GRADE = {};+const recipes = new WeakMap<object, WeakMap<RecipeSource, ClipColorRecipe[]>>();+/** Output and size pairs one grade and source keep: the live cube, the draft+ * one, and an export's alongside. */+const RECIPE_VARIANTS = 4;++/** The recipe a clip renders through: its source, its grade, the output+ * space, sized by the source. `draft` takes the drag's cube while one is+ * live; only the live preview asks for it, and every render that writes a+ * picture (an export, a baked layer) builds the full cube. The same inputs+ * answer the same recipe object. */+export function clipRecipe(+ source: RecipeSource,+ grade: ColorGrade | undefined | null,+ output: OutputSpace = "sdr",+ draft = false+): ClipColorRecipe {+ const size = lutSizeFor(source.profile, draft && lutDraftActive());+ let bySource = recipes.get(grade ?? NO_GRADE);+ if (!bySource) recipes.set(grade ?? NO_GRADE, (bySource = new WeakMap()));+ let made = bySource.get(source);+ if (!made) bySource.set(source, (made = []));+ for (let i = 0; i < made.length; i++) {+ const r = made[i];+ if (r.output === output && r.size === size) return r;+ }+ const recipe: ClipColorRecipe = { ...source, grade: grade ?? undefined, output, size };+ made.unshift(recipe);+ if (made.length > RECIPE_VARIANTS) made.pop();+ return recipe;+}++/* ------------------------------------------------------------------ */+/* The cache */+/* ------------------------------------------------------------------ */++export interface ClipLut {+ lut: GradeLut;+ key: string;+}++/** Bytes of built lattices kept before the budget has its say. */+const TUNED_BYTES = 24 * 2 ** 20;++const built = new Map<string, { clip: ClipLut; bytes: number }>();+let held = 0;+holdMemory("gradeLuts", () => held);++function remember(key: string, lut: GradeLut): ClipLut {+ const bytes = lut.data.byteLength;+ forget(key);+ const cap = allowance("gradeLuts", TUNED_BYTES);+ for (const [oldest, entry] of built) {+ if (held + bytes <= cap) break;+ built.delete(oldest);+ held -= entry.bytes;+ }+ const clip = { lut, key };+ built.set(key, { clip, bytes });+ held += bytes;+ return clip;+}++function forget(key: string): void {+ const hit = built.get(key);+ if (!hit) return;+ built.delete(key);+ held -= hit.bytes;+}++/** A built LUT already in hand, bumped to most recently used. */+export function peekClipLut(key: string): ClipLut | undefined {+ const hit = built.get(key);+ if (!hit) return undefined;+ built.delete(key);+ built.set(key, hit);+ return hit.clip;+}++/** Keys already worked out, by recipe object: the recipe's own, and the last+ * library-LUT state it was keyed with. */+const keys = new WeakMap<ClipColorRecipe, { base: string; lutId: string | null; lutLoaded: boolean; key: string }>();++/** The identity of a recipe's baked result, the library LUT included: the+ * table the recipe was baked with, or the fact that it was baked without it+ * while the file was still loading. "" for the identity mapping. Kept per+ * recipe object, so a recipe asked for again is keyed without any JSON. */+export function clipLutKey(recipe: ClipColorRecipe, lutId: string | null, lutLoaded: boolean): string {+ let held = keys.get(recipe);+ if (held && held.lutId === lutId && held.lutLoaded === lutLoaded) return held.key;+ const base = held ? held.base : recipeKey(recipe);+ const key = base && lutId ? `${base}|${lutId}:${lutLoaded ? "on" : "off"}` : base;+ if (held) {+ held.lutId = lutId;+ held.lutLoaded = lutLoaded;+ held.key = key;+ } else keys.set(recipe, (held = { base, lutId, lutLoaded, key }));+ return key;+}++/** Bake the recipe now, on this thread. */+function buildNow(recipe: ClipColorRecipe, userLut: ParsedLut | undefined, key: string): ClipLut | null {+ const lut = buildClipLut(recipe, userLut);+ if (!lut) return null;+ return remember(key, lut);+}++/* ------------------------------------------------------------------ */+/* The worker */+/* ------------------------------------------------------------------ */++export interface LutWorkerBuild {+ kind: "build";+ key: string;+ recipe: ClipColorRecipe;+ lutId: string | null;+}++export interface LutWorkerTable {+ kind: "lut";+ id: string;+ lut: ParsedLut;+ /** Bytes of tables the worker may hold: this cache's allowance. */+ cap: number;+}++export type LutWorkerRequest = LutWorkerBuild | LutWorkerTable;++export type LutWorkerReply =+ | {+ kind: "built";+ key: string;+ size: number;+ /** Null for an identity recipe. */+ data: Float32Array | null;+ }+ /** The worker no longer holds the library LUT the build named. */+ | { kind: "missing"; key: string; id: string }+ /** What the worker holds after taking a table, and what it let go. */+ | { kind: "tables"; bytes: number; evicted: string[] };++type Waiter = {+ resolve: (lut: ClipLut | null) => void;+ wake: (() => void)[];+ /** What the build was asked with, to ask again with the table. */+ build: LutWorkerBuild;+ userLut: ParsedLut | undefined;+};++let worker: Worker | null | false = null;+const sentTables = new Set<string>();+const inFlight = new Map<string, Waiter>();++/** Bytes of library tables the worker may hold before the budget has its+ * say. A 65-point cube is 3.3 MB. */+const WORKER_TABLE_BYTES = 48 * 2 ** 20;++/** Bytes of library tables the worker holds, as it last reported them. */+let workerTables = 0;+holdMemory("lutWorkerTables", () => workerTables);++/** Take the worker's report of the tables it holds: the bytes count in the+ * budget, and a table it let go is sent again with its next build. */+export function noteWorkerTables(reply: { bytes: number; evicted: string[] }): void {+ workerTables = reply.bytes;+ for (const id of reply.evicted) sentTables.delete(id);+}++/** Bytes of library tables the worker holds, as last reported. */+export const workerTableBytes = (): number => workerTables;++/** A library table on its way to the worker, and the buffers it moves. The+ * page keeps its own table for inline builds, so the worker gets a copy made+ * once here and transferred, never cloned again on the way over. */+export function tableMessage(id: string, lut: ParsedLut): { msg: LutWorkerTable; transfer: ArrayBuffer[] } {+ const transfer: ArrayBuffer[] = [];+ const copy = <T extends { data: Float32Array }>(t: T | undefined): T | undefined => {+ if (!t) return undefined;+ const data = t.data.slice();+ transfer.push(data.buffer);+ return { ...t, data };+ };+ const moved: ParsedLut = { ...lut, shaper: copy(lut.shaper), cube: copy(lut.cube) };+ if (!moved.shaper) delete moved.shaper;+ if (!moved.cube) delete moved.cube;+ return {+ msg: { kind: "lut", id, lut: moved, cap: allowance("lutWorkerTables", WORKER_TABLE_BYTES) },+ transfer,+ };+}++function sendTable(w: Worker, id: string, lut: ParsedLut): void {+ const { msg, transfer } = tableMessage(id, lut);+ sentTables.add(id);+ w.postMessage(msg, transfer);+}++/** The build worker, made on first use; false once it is known not to+ * exist here (no Worker, or one that would not start). */+function lutWorker(): Worker | null {+ if (worker === false) return null;+ if (worker) return worker;+ if (typeof window === "undefined" || typeof Worker !== "function") {+ worker = false;+ return null;+ }+ try {+ const w = new Worker(new URL("./lutBuild.worker.ts", import.meta.url), { type: "module" });+ w.onmessage = (e: MessageEvent<LutWorkerReply>) => {+ const reply = e.data;+ if (reply.kind === "tables") {+ noteWorkerTables(reply);+ return;+ }+ if (reply.kind === "missing") {+ // The worker let the table go: send it again, then the same build.+ const waiter = inFlight.get(reply.key);+ if (!waiter?.userLut) return;+ sendTable(w, reply.id, waiter.userLut);+ w.postMessage(waiter.build);+ return;+ }+ const { key, size, data } = reply;+ const waiter = inFlight.get(key);+ inFlight.delete(key);+ let result: ClipLut | null = null;+ if (data) result = remember(key, { size, data });+ waiter?.resolve(result);+ for (const wake of waiter?.wake ?? []) wake();+ };+ w.onerror = () => {+ // A worker that dies takes its queue and its tables with it: settle the+ // waiters by building here, and build inline from now on.+ worker = false;+ w.terminate();+ workerTables = 0;+ sentTables.clear();+ const pending = [...inFlight.values()];+ inFlight.clear();+ for (const waiter of pending) {+ waiter.resolve(null);+ for (const wake of waiter.wake) wake();+ }+ };+ worker = w;+ return w;+ } catch {+ worker = false;+ return null;+ }+}++/** Hand the worker a build, giving it the library LUT first the one time. */+function buildInWorker(+ w: Worker,+ recipe: ClipColorRecipe,+ lutId: string | null,+ userLut: ParsedLut | undefined,+ key: string,+ wake: (() => void) | undefined+): Promise<ClipLut | null> {+ const held = inFlight.get(key);+ if (held) {+ if (wake) held.wake.push(wake);+ return new Promise((resolve) => {+ const prev = held.resolve;+ held.resolve = (lut) => {+ prev(lut);+ resolve(lut);+ };+ });+ }+ if (lutId && userLut && !sentTables.has(lutId)) sendTable(w, lutId, userLut);+ const build: LutWorkerBuild = { kind: "build", key, recipe, lutId: userLut ? lutId : null };+ return new Promise((resolve) => {+ inFlight.set(key, { resolve, wake: wake ? [wake] : [], build, userLut });+ w.postMessage(build);+ });+}++/* ------------------------------------------------------------------ */+/* Requests */+/* ------------------------------------------------------------------ */++const lutLoads = new Map<string, Promise<void>>();++/** Start reading a library LUT the recipe names, waking the caller when it is+ * in hand. A read that fails is dropped, so the clip renders without it. */+function fetchLibraryLut(lutId: string, wake: (() => void) | undefined): Promise<void> {+ let p = lutLoads.get(lutId);+ if (!p) {+ p = loadLibraryLut(lutId)+ .then(() => undefined)+ .catch(() => undefined)+ .finally(() => lutLoads.delete(lutId));+ lutLoads.set(lutId, p);+ }+ if (wake) void p.then(wake);+ return p;+}++/**+ * The LUT for a recipe: `null` when the recipe is the identity (draw the+ * picture as it is), the built LUT when it is in hand, and `undefined` while+ * it is being built off the thread — the caller draws what it drew last and+ * `wake` fires when the LUT lands. `exact` builds on this thread instead, so+ * the answer is never `undefined`.+ */+export function requestClipLut(+ recipe: ClipColorRecipe,+ opts: { exact?: boolean; wake?: () => void } = {}+): ClipLut | null | undefined {+ const lutId = lutIdOf(recipe.grade);+ const userLut = lutId ? cachedLut(lutId) : undefined;+ if (lutId && !userLut) void fetchLibraryLut(lutId, opts.wake);+ const key = clipLutKey(recipe, lutId, !!userLut);+ if (!key) return null;+ const hit = peekClipLut(key);+ if (hit) return hit;+ const w = opts.exact ? null : lutWorker();+ if (!w) return buildNow(recipe, userLut, key);+ void buildInWorker(w, recipe, lutId, userLut, key, opts.wake);+ return undefined;+}++/**+ * Every LUT the recipes need, in hand: library LUTs read, lattices built.+ * What an export calls before its first frame, so no frame is drawn through+ * a LUT that was still loading. A library LUT that cannot be read fails the+ * call, naming it.+ */+export async function ensureClipLuts(recipes: ClipColorRecipe[]): Promise<void> {+ const ids = new Set<string>();+ for (const r of recipes) {+ const id = lutIdOf(r.grade);+ if (id) ids.add(id);+ }+ await Promise.all([...ids].map((id) => loadLibraryLut(id)));+ const w = lutWorker();+ await Promise.all(+ recipes.map((recipe) => {+ const lutId = lutIdOf(recipe.grade);+ const userLut = lutId ? cachedLut(lutId) : undefined;+ const key = clipLutKey(recipe, lutId, !!userLut);+ if (!key || peekClipLut(key)) return Promise.resolve();+ if (!w) {+ buildNow(recipe, userLut, key);+ return Promise.resolve();+ }+ return buildInWorker(w, recipe, lutId, userLut, key, undefined).then((lut) => {+ // A worker that died mid-build answers null for a live recipe.+ if (!lut && !peekClipLut(key) && recipeKey(recipe)) buildNow(recipe, userLut, key);+ });+ })+ );+}++/** Drop every built LUT (tests, and a session that changes its settings). */+export function clearClipLuts(): void {+ built.clear();+ held = 0;+}diff --git a/site/src/cut/lib/lutBuild.worker.ts b/site/src/cut/lib/lutBuild.worker.tsnew file mode 100644index 00000000..fdd5b698--- /dev/null+++ b/site/src/cut/lib/lutBuild.worker.ts@@ -0,0 +1,92 @@+/**+ * The LUT build worker: bakes clip color recipes off the main thread+ * (lutBuild.ts). Library LUTs arrive once by id and are held here, least+ * recently used first out past the byte cap the page hands over with every+ * table (its memory budget's allowance for this cache); after each table the+ * worker reports what it holds and what it let go, so the page counts these+ * bytes in the budget and sends an evicted table again with its next build. A+ * build that names a table no longer held answers `missing`, and the page+ * sends the table again with the build. The kit's source-lattice cache lives+ * in this thread too, so a grade-only change composes over an+ * already-sampled source conversion.+ */++import { buildClipLut, lutBytes, type ParsedLut } from "@donkeycut/effects-kit";+import type { LutWorkerReply, LutWorkerRequest } from "./lutBuild";++/** Tables always held, whatever the cap: two clips graded with two large+ * LUTs build in turn, and a cache that kept only the newest would drop and+ * re-receive a table on every build. */+const KEEP_NEWEST = 2;++/** Parsed library LUTs by id, least recently used first out past `cap`+ * bytes. The two most recently used tables are always kept. */+export class TableCache {+ private tables = new Map<string, { lut: ParsedLut; bytes: number }>();+ private held = 0;+ constructor(private cap: number) {}++ /** Hold `lut` under `id`, returning the ids let go to make room. */+ keep(id: string, lut: ParsedLut): string[] {+ const old = this.tables.get(id);+ if (old) {+ this.tables.delete(id);+ this.held -= old.bytes;+ }+ const bytes = lutBytes(lut);+ this.tables.set(id, { lut, bytes });+ this.held += bytes;+ return this.shed();+ }++ /** Take a new cap, returning the ids let go to fit under it. */+ setCap(cap: number): string[] {+ this.cap = cap;+ return this.shed();+ }++ take(id: string): ParsedLut | undefined {+ const hit = this.tables.get(id);+ if (!hit) return undefined;+ this.tables.delete(id);+ this.tables.set(id, hit);+ return hit.lut;+ }++ get bytes(): number {+ return this.held;+ }++ private shed(): string[] {+ const evicted: string[] = [];+ for (const [oldest, entry] of this.tables) {+ if (this.held <= this.cap || this.tables.size <= KEEP_NEWEST) break;+ this.tables.delete(oldest);+ this.held -= entry.bytes;+ evicted.push(oldest);+ }+ return evicted;+ }+}++/** Until the page's first table names the cap, nothing is held to cap. */+const tables = new TableCache(0);++const post = (reply: LutWorkerReply, transfer: Transferable[] = []) =>+ (self as unknown as Worker).postMessage(reply, transfer);++self.onmessage = (e: MessageEvent<LutWorkerRequest>) => {+ const msg = e.data;+ if (msg.kind === "lut") {+ const evicted = [...tables.setCap(msg.cap), ...tables.keep(msg.id, msg.lut)];+ post({ kind: "tables", bytes: tables.bytes, evicted });+ return;+ }+ const userLut = msg.lutId ? tables.take(msg.lutId) : undefined;+ if (msg.lutId && !userLut) {+ post({ kind: "missing", key: msg.key, id: msg.lutId });+ return;+ }+ const lut = buildClipLut(msg.recipe, userLut);+ post({ kind: "built", key: msg.key, size: lut?.size ?? 0, data: lut?.data ?? null }, lut ? [lut.data.buffer] : []);+};diff --git a/site/src/cut/lib/lutBuildWorker.test.ts b/site/src/cut/lib/lutBuildWorker.test.tsnew file mode 100644index 00000000..c62c78be--- /dev/null+++ b/site/src/cut/lib/lutBuildWorker.test.ts@@ -0,0 +1,73 @@+import { expect, test } from "bun:test";+import type { ParsedLut } from "@donkeycut/effects-kit";+import { allowance, memoryUsage } from "./memoryBudget";+import { noteWorkerTables, tableMessage, workerTableBytes } from "./lutBuild";+import { TableCache } from "./lutBuild.worker";++const table = (floats: number): ParsedLut => ({+ cube: { size: 2, data: new Float32Array(floats), min: [0, 0, 0], max: [1, 1, 1] },+});++test("the worker's library LUTs are bounded in bytes, least recently used out first", () => {+ const cache = new TableCache(1000);+ expect(cache.keep("a", table(100))).toEqual([]); // 400 bytes+ expect(cache.keep("b", table(100))).toEqual([]);+ expect(cache.take("a")).toBeDefined(); // a is now the newest+ expect(cache.keep("c", table(100))).toEqual(["b"]);+ expect(cache.bytes).toBeLessThanOrEqual(1000);+ expect(cache.take("b")).toBeUndefined();+ expect(cache.take("a")).toBeDefined();+ expect(cache.take("c")).toBeDefined();+});++test("two large tables used in turn are both kept, so neither is sent again per build", () => {+ // Each is past the cap on its own. Keeping only the newest would drop one+ // and re-receive it on every build that alternates between them.+ const cache = new TableCache(1000);+ cache.keep("big1", table(1000));+ expect(cache.keep("big2", table(1000))).toEqual([]);+ for (let i = 0; i < 4; i++) {+ expect(cache.take("big1")).toBeDefined();+ expect(cache.take("big2")).toBeDefined();+ }+ // A third makes the oldest go.+ cache.take("big1");+ expect(cache.keep("big3", table(1000))).toEqual(["big2"]);+ expect(cache.bytes).toBe(8000);+});++test("a smaller cap from the page sheds down to it", () => {+ const cache = new TableCache(10_000);+ cache.keep("a", table(100));+ cache.keep("b", table(100));+ cache.keep("c", table(100));+ expect(cache.setCap(800)).toEqual(["a"]);+ expect(cache.bytes).toBe(800);+});++test("the worker's tables count in the page's memory budget", () => {+ const before = memoryUsage().pictures;+ noteWorkerTables({ bytes: 5_000_000, evicted: [] });+ expect(workerTableBytes()).toBe(5_000_000);+ expect(memoryUsage().pictures - before).toBe(5_000_000);+ noteWorkerTables({ bytes: 0, evicted: ["lut:x"] });+ expect(memoryUsage().pictures).toBe(before);+});++test("a table goes to the worker as a transferred copy under the budget's cap", () => {+ const lut: ParsedLut = {+ shaper: { size: 2, data: new Float32Array([0, 0, 0, 1, 1, 1]), min: [0, 0, 0], max: [1, 1, 1] },+ ...table(24),+ };+ const { msg, transfer } = tableMessage("lut:x", lut);+ expect(msg.cap).toBe(allowance("lutWorkerTables", 48 * 2 ** 20));+ // The page keeps its own table; the worker gets its own buffers, moved.+ expect(transfer).toEqual([msg.lut.shaper!.data.buffer, msg.lut.cube!.data.buffer] as ArrayBuffer[]);+ expect(msg.lut.cube!.data).not.toBe(lut.cube!.data);+ expect(Array.from(msg.lut.cube!.data)).toEqual(Array.from(lut.cube!.data));+ const clone = structuredClone(msg, { transfer });+ expect(clone.lut.cube!.data.length).toBe(24);+ // Transferred away from the message, the page's own table untouched.+ expect(msg.lut.cube!.data.length).toBe(0);+ expect(lut.cube!.data.length).toBe(24);+});diff --git a/site/src/cut/lib/maskVideo.ts b/site/src/cut/lib/maskVideo.tsindex 5259d928..9f89a481 100644--- a/site/src/cut/lib/maskVideo.ts+++ b/site/src/cut/lib/maskVideo.ts@@ -24,8 +24,9 @@ import {} from "mediabunny";import { personSegmenter, segmentSubjectAlpha } from "./cutout";import { FrameCompositor, MISSING_FRAME } from "./composite";+import { ensureClipLuts, sourceLookup } from "./lutBuild";import { overlayPlan, trackZeroPlan } from "./framePlan";-import { ClipReader, WORKING_VIDEO_CODECS } from "./exportRender";+import { ClipReader, renderFile, settleRenderColor, WORKING_VIDEO_CODECS } from "./exportRender";import type { ExportDoc } from "./renderSnapshot";import { createRasterCanvas } from "./raster";import { getClipSpans } from "./store";@@ -90,6 +91,12 @@ export async function renderSubjectMask(// A small compositor: the video layers only, at mask resolution.const compose = createRasterCanvas(W, H);const comp = new FrameCompositor(compose);+ comp.colorMode = "exact";+ // The matte composites what the readers below read: every master, through+ // the recipe of that read.+ comp.sourceProvider = sourceLookup(doc.assets, renderFile);+ await settleRenderColor(doc.assets);+ await ensureClipLuts(doc.clips.map((c) => comp.recipeFor(c)));const mask = createRasterCanvas(W, H);const mctx = mask.getContext("2d") as CanvasRenderingContext2D;diff --git a/site/src/cut/lib/media.ts b/site/src/cut/lib/media.tsindex 70c154a5..11535b91 100644--- a/site/src/cut/lib/media.ts+++ b/site/src/cut/lib/media.ts@@ -10,24 +10,26 @@ import { encodeWav } from "./cloudTranscribe";import { allowance, canvasBytes, holdMemory } from "./memoryBudget";import { normalizeLink } from "./link";import { downloadFromUrl } from "./download";+import { FONT_RE, LUT_RE } from "./libraryFileType";import { markUploadStored, startUpload, uploadInFlight } from "./importQueue";import { convertProjectFile, dropProjectFile, mp4DisplayName } from "./mediaConvert";+import { ensureProxy, needsProxy } from "./mediaProxy";import {audioChunks,audioPeaks,audioTrackOf,decodeAudioSpan,- frameAt,- framesAt,frameSink,openMedia,openMediaShared,+ probeMediaColor,probeMediaFile,readMediaFileSize,UnreadableMediaError,videoTrackOf,type IdleGate,type MediaHandle,+ type MediaProbe,} from "./mediaRead";import type { WrappedCanvas } from "mediabunny";import {@@ -51,6 +53,9 @@ import {} from "./raster";import { pickThumbTimes, type ThumbProbe } from "./filmstrip";import { reportSwallowed } from "./report";+import { baseFrameAt, baseFramesAt, baseFrameSink, colorReadAt } from "./baseFrame";+import { colorRecord } from "./colorProbe";+import { previewFile, sameColorRead } from "./sourceColor";import { assetIdsInUse, useEditor } from "./store";import type { AssetBeats, AssetType, AudioClip, MediaAsset, ProjectSummary, StoredAsset, VideoClip, WatchDetail, WatchKeepReason } from "./types";import { contentRect, IMAGE_CLIP_SECONDS, mediaUrl } from "./types";@@ -179,9 +184,18 @@ export function isTextFile(file: File) {/** A font file the Library takes. Browsers often report an empty type for* .otf, so the extension has the final say. */export function isFontFile(file: File) {- return file.type.startsWith("font/") || /\.(ttf|otf|woff2?)$/i.test(file.name);+ return file.type.startsWith("font/") || FONT_RE.test(file.name);}+/** A colour LUT file the Library takes. Browsers report no type for .cube or+ * .3dl, so the extension is the whole test. */+export function isLutFile(file: File) {+ return LUT_RE.test(file.name);+}++/** What a file picker offers for LUTs. */+export const LUT_ACCEPT = ".cube,.3dl";+/** The kind mark a card wears for a file: its extension, uppercased. Empty for* a name that carries none. */export const fileKind = (fileName: string) =>@@ -403,7 +417,9 @@ export async function uploadProjectImage(}/** The kind of asset a dropped file becomes, or null if Cut can't use it.- * MIME wins over extension: recordings are .webm for both video and audio. */+ * MIME wins over extension: recordings are .webm for both video and audio.+ * Linked kinds (fonts, LUTs) are not project assets: they land on the Library+ * shelf through `linkedLibrary`, so they answer null here. */export function assetTypeOf(file: File): AssetType | null {if (file.type.startsWith("video/")) return "video";if (file.type.startsWith("audio/")) return "audio";@@ -420,8 +436,57 @@ type ProbedMeta = {sizeBytes?: number;width?: number;height?: number;+ /** What a video's code values mean, from its header. */+ color?: StoredAsset["color"];};+/** The asset's `color` field from a header probe. */+const assetColor = (probe: MediaProbe["color"]): StoredAsset["color"] | undefined =>+ probe ? colorRecord(probe) : undefined;++/**+ * Write what a header probe learned about an asset.+ *+ * Every asset write re-renders what reads the assets, and on a slow machine+ * that is a long beat of the main thread. A probe lands a few reads after the+ * drop, which is often inside the play that followed it, so a write that+ * leaves the picture as it is — the size the shelf already said, the color+ * the preview already draws — waits for the play to stop, and one that+ * changes what is drawn lands now.+ *+ * The probe writes the header's facts into `color`; the person's profile+ * override lives beside it in `colorProfile`, so a header write never+ * touches it. The decision reads the live asset, so an override set while+ * the probe or the play ran is weighed with it.+ */+export async function landProbedFacts(id: string, patch: Pick<Partial<MediaAsset>, "width" | "height" | "color">): Promise<void> {+ const live = () => useEditor.getState().assets.find((a) => a.id === id);+ let asset = live();+ if (!asset) return;+ if (!probeChangesPicture(asset, patch)) {+ await idlePlayback();+ asset = live();+ if (!asset) return;+ }+ useEditor.getState().updateAsset(id, patch);+}++/** Whether a probe's facts change what `asset` draws: its size, or the read+ * its color record makes under the asset's profile override. */+export function probeChangesPicture(+ asset: MediaAsset,+ patch: Pick<Partial<MediaAsset>, "width" | "height" | "color">+): boolean {+ const resized =+ (patch.width !== undefined && patch.width !== asset.width) ||+ (patch.height !== undefined && patch.height !== asset.height);+ return (+ resized ||+ (patch.color !== undefined &&+ !sameColorRead(asset, { color: patch.color, colorProfile: asset.colorProfile }, previewFile(asset)))+ );+}+/** Read a media source's kind/duration/dimensions from its container. The* probe can correct the guessed kind: a "video" container with no video track* is really audio, and an "audio" one that turns out to carry picture is video.@@ -455,7 +520,14 @@ async function probeMedia(type: AssetType, src: string | Blob): Promise<ProbedMe// the import kept, so a song is on the timeline the moment its container// has been read.if (!meta.hasVideo) return { type: "audio", duration: meta.duration, sizeBytes: meta.sizeBytes };- return { type: "video", duration: meta.duration, sizeBytes: meta.sizeBytes, width: meta.width, height: meta.height };+ return {+ type: "video",+ duration: meta.duration,+ sizeBytes: meta.sizeBytes,+ width: meta.width,+ height: meta.height,+ color: assetColor(meta.color),+ };}/** Probe a media file's kind/duration/dimensions from the bytes in hand — for@@ -528,6 +600,7 @@ export async function prepareImport(sizeBytes: file.size,...(meta.width !== undefined ? { width: meta.width } : {}),...(meta.height !== undefined ? { height: meta.height } : {}),+ ...(meta.color !== undefined ? { color: meta.color } : {}),url: localUrl,upload: { progress: 0 },};@@ -771,6 +844,7 @@ export async function importFileToProject(sizeBytes: meta.sizeBytes,...(meta.width !== undefined ? { width: meta.width } : {}),...(meta.height !== undefined ? { height: meta.height } : {}),+ ...(meta.color !== undefined ? { color: meta.color } : {}),url,};}@@ -861,9 +935,7 @@ export function importRemote(height: m.height,});}- if (m.hasVideo) {- useEditor.getState().updateAsset(asset.id, { width: m.width, height: m.height });- }+ if (m.hasVideo) void landProbedFacts(asset.id, { width: m.width, height: m.height, color: assetColor(m.color) });}).catch(() => {});}@@ -922,9 +994,7 @@ export async function registerLandedAsset(if (init.type === "video") {void probeMediaFile(asset.url).then((m) => {- if (m.hasVideo) {- useEditor.getState().updateAsset(asset.id, { width: m.width, height: m.height });- }+ if (m.hasVideo) void landProbedFacts(asset.id, { width: m.width, height: m.height, color: assetColor(m.color) });}).catch(() => {});}@@ -1156,6 +1226,8 @@ export async function assetFromProjectFile(} else {asset.width = meta.width;asset.height = meta.height;+ const color = assetColor(meta.color);+ if (color) asset.color = color;}return asset;}@@ -1184,7 +1256,7 @@ export async function captureFreezeFrame(flipV?: boolean;}): Promise<MediaAsset> {- const frame = await frameAt(sourceUrl, srcTime);+ const frame = await baseFrameAt(sourceUrl, srcTime);if (!frame) throw new Error("Could not render the freeze frame.");let picture = frame.canvas;if (framed) {@@ -1491,6 +1563,7 @@ export async function sampleWatchFrames(try {const track = await videoTrackOf(input);if (!track) throw new Error("Could not sample the video.");+ const reading = colorReadAt(sourceUrl);const from = Math.max(0, opts.from);const wanted = opts.to ?? (await input.computeDuration());if (opts.to === undefined && !(wanted > 0))@@ -1533,7 +1606,7 @@ export async function sampleWatchFrames(const deadline = Date.now() + (opts.budgetMs ?? Infinity);const outOfTime = () => Date.now() > deadline;const sigG16At = async (t: number): Promise<Float32Array | null> => {- const one = await frameSink(track, { width: cw, height: ch, fit: "fill" }).getCanvas(t);+ const one = await baseFrameSink(track, { width: cw, height: ch, fit: "fill" }, reading).getCanvas(t);if (!one) return null;sigCtx.imageSmoothingQuality = "high";sigCtx.drawImage(one.canvas as CanvasImageSource, 0, 0, SIGNATURE_SIZE, SIGNATURE_SIZE);@@ -1542,9 +1615,7 @@ export async function sampleWatchFrames(};// The times are ascending, so the whole span decodes once, in order.- const cells = frameSink(track, { width: cw, height: ch, fit: "fill" }).canvasesAtTimestamps(- times- );+ const cells = baseFrameSink(track, { width: cw, height: ch, fit: "fill" }, reading).canvasesAtTimestamps(times);let paused = false;let capped = false;try {@@ -1604,7 +1675,7 @@ export async function sampleWatchFrames(const shot = createRasterCanvas(nw, nh);const shotCtx = shot.getContext("2d") as CanvasRenderingContext2D | null;if (!shotCtx) throw new Error("Could not sample the video.");- const walk = frameSink(track, { width: nw, height: nh, fit: "fill" }).canvasesAtTimestamps(+ const walk = baseFrameSink(track, { width: nw, height: nh, fit: "fill" }, reading).canvasesAtTimestamps(keptAll.map((i) => candTimes[i]));try {@@ -1971,7 +2042,7 @@ async function* idleFramesAt(while (from < times.length) {await idlePlayback();const before = from;- for await (const frame of framesAt(url, times.slice(from), size)) {+ for await (const frame of baseFramesAt(url, times.slice(from), size)) {yield frame;from++;if (useEditor.getState().playing) break;@@ -2008,6 +2079,24 @@ export async function enrichAsset(asset: MediaAsset, src = asset.url) {// A play is long enough to leave the project in it. Nothing this sweep// writes belongs to whatever is open now.if (useEditor.getState().projectId !== openProject) return;+ // Footage imported before its color was read at import settles it now,+ // from the header alone: the grade pipeline and the preview's decoder+ // both read `color`, and a file without it would draw as Rec.709.+ // The asset's live record decides: the import's own probe may have+ // written it while this sweep waited, and that walk is shared.+ asset = useEditor.getState().assets.find((a) => a.id === asset.id) ?? asset;+ if (!asset.color && !asset.upload) {+ const color = await probeMediaColor(held ?? src).catch(() => null);+ if (useEditor.getState().projectId !== openProject) return;+ if (color) {+ await landProbedFacts(asset.id, { color: assetColor(color) });+ asset = useEditor.getState().assets.find((a) => a.id === asset.id) ?? asset;+ }+ }+ // A ProRes master previews through the WASM decoder until its proxy+ // lands; the proxy is built behind the editor, once the bytes are at+ // rest in the project's own storage.+ if (openProject && !asset.upload && needsProxy(asset)) void ensureProxy(openProject, asset);// Footage stored without a length — a shelf row that was never measured// — reads its own before anything is swept from it: a zero-length sweep// has no tiles to place and no buckets to fill, and the clips cut from@@ -2781,6 +2870,7 @@ function edgeReader(url: string): Promise<EdgeReader> {// holds its own pool of canvases, and a drag through a dozen zoom levels// would otherwise leave a dozen pools behind it.const sinks = new Map<number, ReturnType<typeof frameSink>>();+ const reading = colorReadAt(url);const sinkFor = (height: number) => {let sink = sinks.get(height);if (sink) {@@ -2788,7 +2878,7 @@ function edgeReader(url: string): Promise<EdgeReader> {sinks.set(height, sink);return sink;}- sink = frameSink(track, { height }, { poolSize: EDGE_SINK_POOL, lowLatency: true });+ sink = baseFrameSink(track, { height }, reading, { poolSize: EDGE_SINK_POOL, lowLatency: true });sinks.set(height, sink);while (sinks.size > EDGE_SINK_HEIGHTS) sinks.delete(sinks.keys().next().value!);return sink;diff --git a/site/src/cut/lib/mediaLinks.ts b/site/src/cut/lib/mediaLinks.tsindex 1836c077..3507ea13 100644--- a/site/src/cut/lib/mediaLinks.ts+++ b/site/src/cut/lib/mediaLinks.ts@@ -85,7 +85,9 @@ export function refreshSignedUrls(force = false): Promise<void> {const { useEditor } = await import("./store");const s = useEditor.getState();if (!s.loaded || s.projectId !== b.projectId) return;- const minted = await fetchSignedMediaUrls(b.projectId, s.assets.map((a) => a.fileName));+ // A proxy's link expires with its master's, so it re-mints in the batch.+ const names = s.assets.flatMap((a) => (a.proxy ? [a.fileName, a.proxy.fileName] : [a.fileName]));+ const minted = await fetchSignedMediaUrls(b.projectId, names);const st = useEditor.getState();if (batch !== b || st.projectId !== b.projectId || !st.loaded) return;// Mint down but the current URLs still work (inside the eager-refresh@@ -98,6 +100,9 @@ export function refreshSignedUrls(force = false): Promise<void> {const url = minted.urls.get(a.fileName) ?? mediaUrl(b.projectId, a.fileName);urls.set(a.fileName, url);if (url !== a.url) rotated++;+ if (a.proxy) {+ urls.set(a.proxy.fileName, minted.urls.get(a.proxy.fileName) ?? mediaUrl(b.projectId, a.proxy.fileName));+ }}console.debug(`[cut-media] re-mint: ${rotated}/${st.assets.length} url(s) rotated` + (force ? " (forced by a load failure)" : "")diff --git a/site/src/cut/lib/mediaProxy.test.ts b/site/src/cut/lib/mediaProxy.test.tsnew file mode 100644index 00000000..7c67f9dd--- /dev/null+++ b/site/src/cut/lib/mediaProxy.test.ts@@ -0,0 +1,216 @@+import { afterEach, describe, expect, mock, test } from "bun:test";+import { stubModule } from "@/lib/testing/stubModule";+import type { CutBackend } from "./backend/types";+import type { MediaAsset } from "./types";++let features = new Set<string>();+await stubModule("./api", import.meta.url, {+ engineFeatures: async () => features as ReadonlySet<string>,+});+await stubModule("./mediaSync", import.meta.url, {+ storedMediaUrl: async (projectId: string, fileName: string) => `stored:${projectId}/${fileName}`,+});+let storedReads = true;+await stubModule<typeof import("./mediaRead")>("./mediaRead", import.meta.url, {+ probeMediaFile: (async () => {+ if (!storedReads) throw new Error("gone");+ return { hasVideo: true };+ }) as never,+});+const { ensureProxy, needsProxy, proxyUnreadable, useProxyJobs } = await import("./mediaProxy");+const { useEditor } = await import("./store");++const prores = (id: string, extra: Partial<MediaAsset> = {}): MediaAsset => ({+ id,+ fileName: `${id}.MOV`,+ name: `${id}.MOV`,+ type: "video",+ duration: 4,+ url: `https://example.test/${id}.MOV`,+ color: { matrix: "bt2020nc", fullRange: false, bitDepth: 10, detected: "apple-log", codec: "apch" },+ ...extra,+});++function backend(kind: CutBackend["kind"], answer: (path: string, body: unknown) => Response) {+ const calls: { path: string; body: unknown }[] = [];+ const fetch = mock(async (path: string, init?: RequestInit) => {+ const body = typeof init?.body === "string" ? JSON.parse(init.body) : undefined;+ calls.push({ path, body });+ return answer(path, body);+ });+ return { api: { kind, caps: {}, fetch, url: (p: string) => p } as unknown as CutBackend, calls };+}++afterEach(() => {+ useProxyJobs.setState({ jobs: {} });+ useEditor.setState({ projectId: null, assets: [], readOnly: false });+});++describe("needsProxy", () => {+ test("a ProRes video without a proxy needs one; everything else does not", () => {+ expect(needsProxy(prores("a"))).toBe(true);+ expect(needsProxy(prores("a", { proxy: { fileName: "a.proxy.mp4", sizeBytes: 1 } }))).toBe(false);+ expect(needsProxy(prores("a", { color: { matrix: "bt709", fullRange: false, bitDepth: 8, detected: "rec709", codec: "avc1" } }))).toBe(false);+ expect(needsProxy(prores("a", { color: undefined }))).toBe(false);+ expect(needsProxy(prores("a", { type: "audio" }))).toBe(false);+ });+});++describe("ensureProxy", () => {+ test("a Mac project asks its engine and writes the proxy onto the asset", async () => {+ features = new Set(["media.proxy"]);+ const asset = prores("a");+ useEditor.setState({ projectId: "p", assets: [asset] });+ const b = backend("local", () => Response.json({ fileName: "a.proxy.mp4", sizeBytes: 321, width: 64, height: 64 }));+ await ensureProxy("p", asset, b.api);+ expect(b.calls[0].path).toBe("/api/cut/projects/p/proxy");+ const body = b.calls[0].body as { file: string; maxHeight: number; crf: number };+ expect(body.file).toBe("a.MOV");+ expect(body.maxHeight).toBeGreaterThan(0);+ expect(body.crf).toBeGreaterThanOrEqual(0);+ const after = useEditor.getState().assets[0];+ expect(after.proxy).toEqual({ fileName: "a.proxy.mp4", sizeBytes: 321 });+ expect(after.proxyUrl).toBe("stored:p/a.proxy.mp4");+ expect(useProxyJobs.getState().jobs.a).toBeUndefined();+ });++ test("an engine without the route makes none, and the panel is told", async () => {+ features = new Set();+ const asset = prores("a");+ useEditor.setState({ projectId: "p", assets: [asset] });+ const b = backend("local", () => Response.json({}));+ await ensureProxy("p", asset, b.api);+ expect(b.calls).toHaveLength(0);+ expect(useEditor.getState().assets[0].proxy).toBeUndefined();+ expect(useProxyJobs.getState().jobs.a).toEqual({ kind: "none" });+ });++ test("a cloud project takes a proxy the worker already built", async () => {+ const asset = prores("a");+ useEditor.setState({ projectId: "p", assets: [asset] });+ const b = backend("cloud", () => Response.json({ fileName: "a.proxy.mp4", sizeBytes: 9 }));+ await ensureProxy("p", asset, b.api);+ expect(b.calls[0]).toEqual({ path: "/api/cut/projects/p/proxy", body: { file: "a.MOV" } });+ expect(useEditor.getState().assets[0].proxy).toEqual({ fileName: "a.proxy.mp4", sizeBytes: 9 });+ });++ test("a failure leaves the asset on the master and says why", async () => {+ features = new Set(["media.proxy"]);+ const asset = prores("a");+ useEditor.setState({ projectId: "p", assets: [asset] });+ const b = backend("local", () => Response.json({ error: "ffmpeg fell over" }, { status: 500 }));+ await ensureProxy("p", asset, b.api);+ expect(useEditor.getState().assets[0].proxy).toBeUndefined();+ expect(useProxyJobs.getState().jobs.a).toEqual({ kind: "failed", error: "ffmpeg fell over" });+ });++ test("an asset still uploading, or one with a proxy, is left alone", async () => {+ features = new Set(["media.proxy"]);+ const b = backend("local", () => Response.json({}));+ await ensureProxy("p", prores("a", { upload: { progress: 0.5 } }), b.api);+ await ensureProxy("p", prores("b", { proxy: { fileName: "b.proxy.mp4", sizeBytes: 1 } }), b.api);+ expect(b.calls).toHaveLength(0);+ });+});++describe("proxyUnreadable", () => {+ // A doc can name a proxy whose file is not there (a copy made before+ // proxies travelled, a file lost from storage). The reader that failed to+ // open it hands it here: the asset drops back to the master at once, and+ // the project heals it once.+ const broken = (id: string) =>+ prores(id, { proxy: { fileName: `${id}.proxy.mp4`, sizeBytes: 3 }, proxyUrl: `https://example.test/${id}.proxy.mp4` });++ test("a proxy whose file is gone comes off the asset and is made again", async () => {+ features = new Set(["media.proxy"]);+ storedReads = false;+ const asset = broken("gone");+ useEditor.setState({ projectId: "p", assets: [asset] });+ const b = backend("local", () => Response.json({ fileName: "gone.proxy.mp4", sizeBytes: 44 }));+ const healed = proxyUnreadable(asset, b.api);+ // The master plays from the moment the reader gives up.+ expect(useEditor.getState().assets[0].proxy).toBeUndefined();+ expect(useEditor.getState().assets[0].proxyUrl).toBeUndefined();+ await healed;+ expect(b.calls[0].path).toBe("/api/cut/projects/p/proxy");+ expect(useEditor.getState().assets[0].proxy).toEqual({ fileName: "gone.proxy.mp4", sizeBytes: 44 });+ storedReads = true;+ });++ test("a proxy that still reads comes back under a fresh address, unbuilt", async () => {+ storedReads = true;+ const asset = broken("lapsed");+ useEditor.setState({ projectId: "p", assets: [asset] });+ const b = backend("local", () => Response.json({}));+ await proxyUnreadable(asset, b.api);+ expect(b.calls).toHaveLength(0);+ expect(useEditor.getState().assets[0].proxy).toEqual(asset.proxy!);+ expect(useEditor.getState().assets[0].proxyUrl).toBe("stored:p/lapsed.proxy.mp4");+ });++ test("heals once a session: a second failure leaves the master playing", async () => {+ storedReads = true;+ const asset = broken("twice");+ useEditor.setState({ projectId: "p", assets: [asset] });+ const b = backend("local", () => Response.json({}));+ await proxyUnreadable(asset, b.api);+ const back = useEditor.getState().assets[0];+ await proxyUnreadable(back, b.api);+ expect(useEditor.getState().assets[0].proxy).toBeUndefined();+ });++ test("a shared view drops the proxy for itself and builds nothing", async () => {+ const asset = broken("viewer");+ useEditor.setState({ projectId: "p", assets: [asset], readOnly: true });+ const b = backend("local", () => Response.json({}));+ await proxyUnreadable(asset, b.api);+ expect(useEditor.getState().assets[0].proxyUrl).toBeUndefined();+ expect(b.calls).toHaveLength(0);+ });+});++describe("the in-page proxy's muxer", () => {+ // The page writes the proxy to disk while it encodes. What it holds between+ // writes is one chunk, whatever the master's length, and the header it+ // reserved up front makes the finished file read from its start.+ test("streams the file out a bounded chunk at a time and reads back", async () => {+ const { EncodedPacket, EncodedVideoPacketSource, Input, BufferSource, MP4 } = await import("mediabunny");+ const { PROXY_WRITE_CHUNK, proxyOutput, proxyPacketBudget } = await import("./mediaProxy");+ const file = new Uint8Array(64 * 1024 * 1024);+ let size = 0;+ let written = 0;+ let largestWrite = 0;+ const writable = new WritableStream<{ type: "write"; data: Uint8Array; position: number }>({+ write(chunk) {+ file.set(chunk.data, chunk.position);+ size = Math.max(size, chunk.position + chunk.data.byteLength);+ written += chunk.data.byteLength;+ largestWrite = Math.max(largestWrite, chunk.data.byteLength);+ },+ });+ const frames = 240;+ const frameBytes = 128 * 1024;+ const output = proxyOutput(writable);+ const source = new EncodedVideoPacketSource("vp9");+ output.addVideoTrack(source, { maximumPacketCount: proxyPacketBudget(frames, 8, 0).video });+ await output.start();+ let writtenMidway = 0;+ for (let i = 0; i < frames; i++) {+ const packet = new EncodedPacket(new Uint8Array(frameBytes).fill(i & 0xff), i === 0 ? "key" : "delta", i / 30, 1 / 30);+ await source.add(packet, i === 0 ? { decoderConfig: { codec: "vp09.02.51.10", codedWidth: 64, codedHeight: 64 } } : undefined);+ if (i === frames / 2) writtenMidway = written;+ }+ await output.finalize();+ // Half the frames in, most of their bytes are already on disk.+ expect(writtenMidway).toBeGreaterThan((frames / 2) * frameBytes - 2 * PROXY_WRITE_CHUNK);+ expect(largestWrite).toBeLessThanOrEqual(PROXY_WRITE_CHUNK);+ const input = new Input({ source: new BufferSource(file.slice(0, size).buffer), formats: [MP4] });+ const track = await input.getPrimaryVideoTrack();+ expect(track).not.toBeNull();+ expect((await track!.computePacketStats()).packetCount).toBe(frames);+ // Fast start: the header sits ahead of the media.+ const text = new TextDecoder("latin1").decode(file.slice(0, 64 * 1024));+ expect(text.indexOf("moov")).toBeGreaterThan(-1);+ expect(text.indexOf("moov")).toBeLessThan(text.indexOf("mdat"));+ });+});diff --git a/site/src/cut/lib/mediaProxy.ts b/site/src/cut/lib/mediaProxy.tsnew file mode 100644index 00000000..925a9c97--- /dev/null+++ b/site/src/cut/lib/mediaProxy.ts@@ -0,0 +1,417 @@+"use client";++/**+ * The preview proxy of a ProRes master.+ *+ * A ProRes file has no hardware decoder in any browser. The master stays in+ * the project — an export reads it — and beside it lands a 10-bit HEVC (or+ * AV1, or VP9) proxy the preview plays at speed (server/proxy.ts says what+ * the file is). Until the proxy lands, and wherever none can be made, the+ * preview decodes the master through the WASM decoder: slower, and the+ * same picture.+ *+ * Who builds it follows the residency: the engine for a project on this Mac,+ * the worker for a cloud project, and for a browser project the page itself+ * when it has a 10-bit encoder, else the Mac's engine when the app is there+ * and carries the route, else nobody — the one fallback, shown in the panel.+ * The result always lands in the project's own storage and is written onto+ * the asset through the store.+ */++import {+ AudioSampleSink,+ AudioSampleSource,+ canEncodeAudio,+ canEncodeVideo,+ Mp4OutputFormat,+ Output,+ QUALITY_HIGH,+ StreamTarget,+ VideoSample,+ VideoSampleSink,+ VideoSampleSource,+ type VideoCodec,+} from "mediabunny";+import { create } from "zustand";+import { apiFetch as engineFetch, engineFeatures } from "./api";+import { getBackend, hasLocalCompute, type CutBackend } from "./backend";+import { freeName, mediaDir } from "./backend/browser/opfs";+import { resolveRegisteredBlob } from "./backend/browser/registry";+import { pollCloudJob } from "./cloudJob";+import { cutColor } from "./colorSettings";+import { uploadProjectMediaTo } from "./media";+import { audioTrackOf, frameSinkIsCustom, openMedia, probeMediaFile, videoTrackOf } from "./mediaRead";+import { forgetLocalMediaUrl, storedMediaUrl } from "./mediaSync";+import { ensureProresDecoder } from "./proresDecoder";+import { convertPlanes, isPlanarFormat, planesPassThrough, proxySize } from "./proxyPlanes";+import { useEditor } from "./store";+import type { MediaAsset, StoredAsset } from "./types";++/** The proxy's file name beside its master (server/proxy.ts `proxyNameFor`). */+export const proxyNameFor = (fileName: string) =>+ `${fileName.replace(/\.[^./\\]+$/, "") || "media"}.proxy.mp4`;++/** A video whose master needs a proxy and has none: ProRes (a four-character+ * code starting `ap`), read off the header at import. */+export function needsProxy(asset: Pick<StoredAsset, "type" | "color" | "proxy" | "block">): boolean {+ return asset.type === "video" && !asset.proxy && !asset.block && !!asset.color?.codec?.startsWith("ap");+}++/** What the panel shows about an asset's proxy. */+export type ProxyState =+ | { kind: "making"; progress: number }+ /** No residency could make one; the preview plays the master. */+ | { kind: "none" }+ | { kind: "failed"; error: string };++interface ProxyJobs {+ jobs: Record<string, ProxyState>;+ set: (assetId: string, state: ProxyState | null) => void;+}++/** The proxies being made, or found unmakeable, this session, by asset id. */+export const useProxyJobs = create<ProxyJobs>((set) => ({+ jobs: {},+ set: (assetId, state) =>+ set((s) => {+ const jobs = { ...s.jobs };+ if (state) jobs[assetId] = state;+ else delete jobs[assetId];+ return { jobs };+ }),+}));++const inFlight = new Set<string>();++/** The 10-bit codecs the page may encode a proxy with, best first. Chrome+ * encodes 10-bit only as VP9 profile 2. WebKit answers yes to all three and+ * then has no 10-bit `VideoFrame` to feed them — the WASM decoder falls+ * back to 8-bit frames there — so a WebKit page makes no proxy and the Mac+ * beside it does. */+export const PROXY_CODECS: { codec: VideoCodec; fullCodecString: string }[] = [+ { codec: "hevc", fullCodecString: "hev1.2.4.L153.B0" },+ { codec: "av1", fullCodecString: "av01.0.13M.10" },+ { codec: "vp9", fullCodecString: "vp09.02.51.10" },+];++/** A result from any residency: the file the project now holds. */+interface Landed {+ fileName: string;+ sizeBytes: number;+}++/**+ * Make sure the asset has a proxy: build one through the residency that can,+ * and write it onto the asset. Runs once per asset at a time; a second ask+ * while one is on its way does nothing. A failure leaves the asset on the+ * master and says so in the panel.+ */+export async function ensureProxy(+ projectId: string,+ asset: MediaAsset,+ backend: CutBackend = getBackend()+): Promise<void> {+ // A proxy is for the screen. A headless runner draws for a render or a+ // chat tool and reads the master; the page queues the proxy when the+ // project is next opened.+ if (frameSinkIsCustom()) return;+ if (!needsProxy(asset) || asset.upload || inFlight.has(asset.id)) return;+ inFlight.add(asset.id);+ const jobs = useProxyJobs.getState();+ const progress = (p: number) => jobs.set(asset.id, { kind: "making", progress: Math.max(0, Math.min(1, p)) });+ progress(0);+ try {+ const landed = await buildProxy(projectId, asset, backend, progress);+ if (!landed) {+ jobs.set(asset.id, { kind: "none" });+ return;+ }+ const proxyUrl = await storedMediaUrl(projectId, landed.fileName, backend);+ useEditor.getState().setAssetProxy(asset.id, { fileName: landed.fileName, sizeBytes: landed.sizeBytes }, proxyUrl);+ jobs.set(asset.id, null);+ } catch (e) {+ jobs.set(asset.id, { kind: "failed", error: e instanceof Error ? e.message : "Could not make the preview proxy." });+ } finally {+ inFlight.delete(asset.id);+ }+}++const healing = new Set<string>();++/**+ * A reader could not open the asset's proxy. The proxy comes off the asset at+ * once, so every reader plays the master, and the project heals it once per+ * session: the stored file comes back under a fresh address when it still+ * reads (a lapsed link), and otherwise `ensureProxy` makes a new one.+ */+export async function proxyUnreadable(asset: MediaAsset, backend: CutBackend = getBackend()): Promise<void> {+ const s = useEditor.getState();+ const live = s.assets.find((a) => a.id === asset.id);+ // Dropped or replaced since the reader tried it.+ if (!live?.proxy || live.proxyUrl !== asset.proxyUrl) return;+ const broken = live.proxy;+ s.dropAssetProxy(asset.id);+ const projectId = s.projectId;+ if (!projectId || s.readOnly || frameSinkIsCustom()) return;+ const key = `${projectId}:${asset.id}`;+ if (healing.has(key)) return;+ healing.add(key);+ const stillOpen = () => useEditor.getState().projectId === projectId;+ try {+ forgetLocalMediaUrl(projectId, broken.fileName);+ const url = await storedMediaUrl(projectId, broken.fileName, backend);+ if ((await probeMediaFile(url)).hasVideo) {+ if (stillOpen()) useEditor.getState().setAssetProxy(asset.id, broken, url);+ return;+ }+ } catch {+ // The file is gone or unreadable: build a new one.+ }+ const now = stillOpen() ? useEditor.getState().assets.find((a) => a.id === asset.id) : undefined;+ if (now) await ensureProxy(projectId, now, backend);+}++/** Every asset in the open project that still needs a proxy. */+export function ensureProjectProxies(): void {+ const s = useEditor.getState();+ if (!s.projectId || s.readOnly) return;+ for (const asset of s.assets) if (needsProxy(asset)) void ensureProxy(s.projectId, asset);+}++async function buildProxy(+ projectId: string,+ asset: MediaAsset,+ backend: CutBackend,+ onProgress: (p: number) => void+): Promise<Landed | null> {+ const { proxyMaxHeight, proxyCrf } = cutColor();+ if (backend.kind === "local") {+ if (!(await engineFeatures()).has("media.proxy")) return null;+ const res = await backend.fetch(`/api/cut/projects/${projectId}/proxy`, {+ method: "POST",+ headers: { "Content-Type": "application/json" },+ body: JSON.stringify({ file: asset.fileName, maxHeight: proxyMaxHeight, crf: proxyCrf }),+ });+ const body = (await res.json().catch(() => ({}))) as Partial<Landed> & { error?: string };+ if (!res.ok || !body.fileName || typeof body.sizeBytes !== "number") {+ throw new Error(body.error ?? "Could not make the preview proxy.");+ }+ return { fileName: body.fileName, sizeBytes: body.sizeBytes };+ }+ if (backend.kind === "cloud") {+ const res = await backend.fetch(`/api/cut/projects/${projectId}/proxy`, {+ method: "POST",+ headers: { "Content-Type": "application/json" },+ body: JSON.stringify({ file: asset.fileName }),+ });+ const started = (await res.json().catch(() => ({}))) as Partial<Landed> & { jobId?: string; error?: string };+ if (!res.ok) throw new Error(started.error ?? "Could not make the preview proxy.");+ // A proxy already built answers with the file itself.+ if (started.fileName && typeof started.sizeBytes === "number") {+ return { fileName: started.fileName, sizeBytes: started.sizeBytes };+ }+ if (!started.jobId) throw new Error(started.error ?? "Could not make the preview proxy.");+ const result = await pollCloudJob<Partial<Landed>>(started.jobId, backend, "Could not make the preview proxy.", {+ timedOut: "The preview proxy took too long.",+ onProgress,+ });+ if (!result.fileName || typeof result.sizeBytes !== "number") throw new Error("Could not make the preview proxy.");+ return { fileName: result.fileName, sizeBytes: result.sizeBytes };+ }+ // A browser project: the page first, writing straight into the project's+ // storage, then the Mac beside it.+ const inPage = await proxyInPage(projectId, asset, proxyMaxHeight, onProgress);+ if (inPage) return inPage;+ const blob = await proxyOnTheMac(asset, proxyMaxHeight, proxyCrf);+ if (!blob) return null;+ const fileName = await uploadProjectMediaTo(backend, projectId, blob, proxyNameFor(asset.fileName));+ return { fileName, sizeBytes: blob.size };+}++/** The first 10-bit codec this browser encodes at the master's size. */+async function encodableProxyCodec(width: number, height: number) {+ for (const c of PROXY_CODECS) {+ if (await canEncodeVideo(c.codec, { width, height, fullCodecString: c.fullCodecString })) return c;+ }+ return null;+}++/** How much encoded output the page holds before it writes to disk. */+export const PROXY_WRITE_CHUNK = 4 * 1024 * 1024;++/** The packet ceilings the reserved header is sized for: the master's own+ * frame count and the AAC frames its duration makes, each with the headroom+ * the muxer asks for. */+export function proxyPacketBudget(videoPackets: number, duration: number, sampleRate: number) {+ return {+ video: Math.ceil(videoPackets * 1.33) + 16,+ audio: Math.ceil(((duration * sampleRate) / 1024) * 1.33) + 16,+ };+}++/** The proxy's muxer: MP4 with its header in space reserved up front, written+ * through `writable` a bounded chunk at a time, so what the page holds does not+ * grow with the master's length. */+export function proxyOutput(writable: WritableStream) {+ return new Output({+ format: new Mp4OutputFormat({ fastStart: "reserve" }),+ target: new StreamTarget(writable, { chunked: true, chunkSize: PROXY_WRITE_CHUNK }),+ });+}++/**+ * Build the proxy in this page and write it into the project's own storage:+ * decode the master through the WASM decoder, carry every frame's planes into+ * Rec.709 limited 4:2:0 at 10 bits, and encode with the browser's first+ * 10-bit codec, streaming the file to disk as it goes; a master taller than+ * the proxy may be is brought down in the same pass. Null when the page+ * cannot: no 10-bit encoder, no AAC encoder for the sound, or a decoder+ * handing out 8-bit frames (WebKit, whose `VideoFrame` takes no 10-bit+ * format).+ */+export async function proxyInPage(+ projectId: string,+ asset: MediaAsset,+ maxHeight: number,+ onProgress: (p: number) => void+): Promise<Landed | null> {+ if (typeof VideoFrame === "undefined") return null;+ await ensureProresDecoder();+ const input = openMedia(asset.url);+ try {+ const video = await videoTrackOf(input);+ if (!video) return null;+ const [coded, duration, rotated] = await Promise.all([+ Promise.all([video.getCodedWidth(), video.getCodedHeight()]),+ input.computeDuration(),+ video.getRotation(),+ ]);+ // The planes are converted at the coded size; the display size is the+ // coded one turned by the container's rotation, which the proxy keeps —+ // so a sideways master's cap applies to its coded width.+ const cap = rotated % 180 === 0 ? maxHeight : Math.round((maxHeight * coded[1]) / Math.max(1, coded[0]));+ const target = proxySize(coded[0], coded[1], cap);+ const codec = await encodableProxyCodec(target.width, target.height);+ if (!codec) return null;+ const audio = await audioTrackOf(input);+ if (audio && !(await canEncodeAudio("aac"))) return null;+ const from = { matrix: asset.color?.matrix ?? "bt709", fullRange: asset.color?.fullRange ?? false } as const;+ const budget = proxyPacketBudget(+ (await video.computePacketStats()).packetCount,+ duration,+ audio ? await audio.getSampleRate() : 0+ );++ const dir = await mediaDir(projectId, true);+ if (!dir) return null;+ const fileName = await freeName(dir, proxyNameFor(asset.fileName));+ const handle = await dir.getFileHandle(fileName, { create: true });+ const writable = await handle.createWritable();+ const output = proxyOutput(writable);+ let landed = false;+ try {+ const videoSource = new VideoSampleSource({+ codec: codec.codec,+ fullCodecString: codec.fullCodecString,+ quality: QUALITY_HIGH,+ });+ output.addVideoTrack(videoSource, { rotation: rotated, maximumPacketCount: budget.video });+ const audioSource = audio ? new AudioSampleSource({ codec: "aac", quality: QUALITY_HIGH }) : null;+ if (audioSource) output.addAudioTrack(audioSource, { maximumPacketCount: budget.audio });+ await output.start();++ const frames = new VideoSampleSink(video);+ for await (const sample of frames.samples()) {+ try {+ const converted = await convertSample(sample, from, target);+ if (!converted) return null;+ try {+ await videoSource.add(converted);+ } finally {+ if (converted !== sample) converted.close();+ }+ if (duration > 0) onProgress(Math.min(0.95, sample.timestamp / duration));+ } finally {+ sample.close();+ }+ }+ if (audio && audioSource) {+ const sounds = new AudioSampleSink(audio);+ for await (const sample of sounds.samples()) {+ try {+ await audioSource.add(sample);+ } finally {+ sample.close();+ }+ }+ }+ await output.finalize();+ // The file the project keeps has to read back as what was asked for.+ const file = await handle.getFile();+ const probe = await probeMediaFile(file);+ const want = rotated % 180 === 0 ? target.width : target.height;+ if (!probe.hasVideo || probe.width !== want) throw new Error("The preview proxy did not read back.");+ landed = true;+ onProgress(1);+ return { fileName, sizeBytes: file.size };+ } finally {+ if (!landed) {+ if (output.state !== "finalized" && output.state !== "canceled") await output.cancel().catch(() => {});+ // A muxer that never started never took the stream.+ if (!writable.locked) await writable.abort().catch(() => {});+ await dir.removeEntry(fileName).catch(() => {});+ }+ }+ } finally {+ input.dispose();+ }+}++/** The sample as Rec.709 limited 4:2:0 10-bit planes, tagged so; the sample+ * itself when it already is that. Null for a frame the page cannot carry at+ * 10 bits. */+async function convertSample(+ sample: VideoSample,+ from: { matrix: "bt709" | "bt601" | "bt2020nc"; fullRange: boolean },+ target: { width: number; height: number }+): Promise<VideoSample | null> {+ const format = sample.format;+ if (!isPlanarFormat(format)) return null;+ const colorSpace = { primaries: "bt709", transfer: "iec61966-2-1", matrix: "bt709", fullRange: false } as const;+ const init = { timestamp: sample.timestamp, duration: sample.duration, colorSpace };+ const data = new ArrayBuffer(sample.allocationSize());+ const layout = await sample.copyTo(data);+ const size = { width: sample.codedWidth, height: sample.codedHeight, maxHeight: target.height };+ if (planesPassThrough(format, from, size) && sample.codedWidth === target.width) {+ return new VideoSample(data, { ...init, format: "I420P10", codedWidth: sample.codedWidth, codedHeight: sample.codedHeight, layout });+ }+ const converted = convertPlanes(+ { format, width: sample.codedWidth, height: sample.codedHeight, data, layout },+ from,+ { maxHeight: target.height }+ );+ return new VideoSample(converted.data, {+ ...init,+ format: converted.format,+ codedWidth: converted.width,+ codedHeight: converted.height,+ layout: converted.layout,+ });+}++/** Hand the master's bytes to the Mac and take the proxy back; the engine+ * keeps nothing. Null when the app is not there or is older than the route. */+async function proxyOnTheMac(asset: MediaAsset, maxHeight: number, crf: number): Promise<Blob | null> {+ if (!hasLocalCompute() || !(await engineFeatures()).has("media.proxy")) return null;+ const bytes = resolveRegisteredBlob(asset.url) ?? (await (await fetch(asset.url)).blob());+ const form = new FormData();+ form.append("file", bytes, asset.fileName);+ form.append("maxHeight", String(maxHeight));+ form.append("crf", String(crf));+ const res = await engineFetch("/api/cut/proxy", { method: "POST", body: form });+ if (!res.ok) {+ const body = (await res.json().catch(() => ({}))) as { error?: string };+ throw new Error(body.error ?? "Could not make the preview proxy.");+ }+ return res.blob();+}diff --git a/site/src/cut/lib/mediaRead.ts b/site/src/cut/lib/mediaRead.tsindex af753888..248a1ec6 100644--- a/site/src/cut/lib/mediaRead.ts+++ b/site/src/cut/lib/mediaRead.ts@@ -44,7 +44,10 @@ import {import { confirmEngine, engineConnected, isEngineUrl } from "./api";import { resolveRegisteredBlob } from "./backend/browser/registry";import { CHUNK_SIZE, chunkSourceOptions } from "./chunkCache";+import { probeColor, probeMissingColors, rangeOfBlob, withFoundColors, type ColorProbe, type ReadRange } from "./colorProbe";+import { pictureAssetIds, type ItemLists } from "./itemKinds";import { allowance, holdMemory } from "./memoryBudget";+import { SpsColorRewriter, descriptionLengthSize, spsCodecOf, tagsOfColorSpace } from "./spsColor";/** What a file turns out to be, read from its container. */export interface MediaProbe {@@ -58,6 +61,8 @@ export interface MediaProbe {width?: number;height?: number;rotation?: Rotation;+ /** What the video's code values mean, from its header (video only). */+ color?: ColorProbe;}/** Frames read back at a target size. Height alone preserves aspect. */@@ -343,7 +348,19 @@ async function tracked<T>(read: Promise<T>): Promise<T> {export async function videoTrackOf(input: Input): Promise<InputVideoTrack | null> {const track = await tracked(input.getPrimaryVideoTrack());if (!track) return null;- return headless() || (await track.canDecode()) ? track : null;+ return (await decodable(track)) ? track : null;+}++/** Whether this runtime decodes the track. A ProRes track has no WebCodecs+ * decoder anywhere; the WASM one is registered on the first ask and answers+ * for every reader after — the preview of a master whose proxy has not+ * landed, the in-tab export, which always reads the master. */+async function decodable(track: InputVideoTrack): Promise<boolean> {+ if (headless()) return true;+ if (await track.canDecode()) return true;+ if (track.codec !== "prores") return false;+ await (await import("./proresDecoder")).ensureProresDecoder();+ return track.canDecode();}/** True when the file carries video this browser cannot decode.@@ -355,7 +372,7 @@ export async function videoTrackOf(input: Input): Promise<InputVideoTrack | nullexport async function hasUndecodableVideo(input: Input): Promise<boolean> {if (headless()) return false;const track = await tracked(input.getPrimaryVideoTrack());- return !!track && !(await track.canDecode());+ return !!track && !(await decodable(track));}/** The primary audio track, or null — same decodability rule as video. */@@ -386,18 +403,73 @@ export async function probeMediaFile(src: string | Blob): Promise<MediaProbe> {throw new UnreadableMediaError("This file's audio needs conversion.", true);}if (!video && !audio) throw new UnreadableMediaError();+ // The color walk runs beside the rest of the probe: it is a few ranged+ // reads of its own, and waiting on them in turn would hold every caller+ // that writes what the probe found.+ const color = video ? input.source.getSizeOrNull().then((bytes) => probeMediaColorOnce(src, bytes)) : null;+ // Awaited below; a probe that fails before then fails on its own.+ color?.catch(() => {});const [duration, bytes] = await Promise.all([input.computeDuration(), input.source.getSizeOrNull()]);const size = bytes === null ? {} : { sizeBytes: bytes };- if (!video) return { ...size, duration, hasVideo: false, hasAudio: true };+ if (!video || !color) return { ...size, duration, hasVideo: false, hasAudio: true };const [width, height, rotation] = await Promise.all([video.getDisplayWidth(),video.getDisplayHeight(),video.getRotation(),]);- return { ...size, duration, hasVideo: true, hasAudio: !!audio, width, height, rotation };+ return { ...size, duration, hasVideo: true, hasAudio: !!audio, width, height, rotation, color: await color };});}+/** Color walks in flight, by source: an import's probe and the lazy fill of+ * the same file share one walk, and so one write of what it found. */+const colorWalks = new Map<string | Blob, Promise<ColorProbe>>();++function probeMediaColorOnce(src: string | Blob, bytes?: number | null): Promise<ColorProbe> {+ let walk = colorWalks.get(src);+ if (!walk) {+ const size = bytes ?? (typeof src === "string" ? Infinity : src.size);+ walk = probeColor(rangeReader(src), size).finally(() => colorWalks.delete(src));+ colorWalks.set(src, walk);+ }+ return walk;+}++/** Read a video's color from its header alone: the same walk the import+ * probe makes, for media imported before the probe existed. */+export function probeMediaColor(src: string | Blob): Promise<ColorProbe> {+ return probeMediaColorOnce(src);+}++/** `assets` with the color record of every video the timeline draws filled+ * from its header: what a render or an export spec reads before its first+ * frame, so footage the lazy fill has not reached yet is not drawn as+ * Rec.709. A drawn file whose header cannot be read fails the call, naming+ * it; files nothing on the timeline uses are not read. */+export async function withAssetColors<+ A extends { id: string; type: string; fileName: string; url: string; color?: unknown; block?: unknown },+>(assets: A[], lists: Pick<ItemLists, "clips" | "overlays">, urlOf: (asset: A) => string = (a) => a.url): Promise<A[]> {+ return withFoundColors(assets, await probeMissingColors(assets, pictureAssetIds(lists), (a) => probeMediaColor(urlOf(a))));+}++/** Ranged byte reads over what `openMedia` reads: a Blob (or the File behind+ * a store-minted URL) by slicing, a URL by a Range request through the same+ * fetch the readers use. A server that answers the whole file is sliced. */+function rangeReader(src: string | Blob): ReadRange {+ const blob = typeof src === "string" ? (resolveRegisteredBlob(src) ?? src) : src;+ if (typeof blob !== "string") return rangeOfBlob(blob);+ const read = trackedFetch(blob);+ return async (offset, length) => {+ const res = await read(blob, {+ mode: "cors",+ headers: { Range: `bytes=${offset}-${offset + length - 1}` },+ });+ if (!res.ok) throw new MediaFetchError(`Cut couldn't read the media header (${res.status}).`);+ const bytes = new Uint8Array(await res.arrayBuffer());+ return res.status === 206 ? bytes : bytes.subarray(offset, offset + length);+ };+}+/** What every frame reader in Cut asks of a video track: one frame at a* time, a span in order, or a set of moments in one pass. mediabunny's* CanvasSink is this in a browser; a headless process installs its own,@@ -422,8 +494,46 @@ export interface FrameSinkOptions {* machine resource; a reader rebuilt after losing one asks for software,* which always opens. */software?: boolean;+ /** Tag the decoded frames with this color space in place of the file's own,+ * so the browser draws the code values untouched: no tone mapping of an+ * HDR file, no gamut conversion of a wide one. The grade pipeline then+ * reads the meaning from the asset's `color`. Reaches WebCodecs as the+ * decoder config's `colorSpace` and is stamped on the frames a WASM decoder+ * produces. An H.264 or HEVC decoder reads its tags from the bitstream's+ * own SPS, so the same tags are written into the SPS inside the codec+ * description and into any SPS a sample carries in-band, the way ffmpeg's+ * metadata filters do. What a route then draws is measured once per session+ * by `decodePath` (decoderCheck.ts). */+ colorSpace?: VideoColorSpaceInit;}+/** Decoder hooks that write `colorSpace` into the bitstream's own SPS tags+ * for H.264 and HEVC; empty for every other codec. */+function spsHooks(colorSpace: VideoColorSpaceInit): {+ transformConfig?: (config: VideoDecoderConfig) => VideoDecoderConfig;+ transformPacket?: (data: Uint8Array, config: VideoDecoderConfig) => Uint8Array | null;+} {+ const tags = tagsOfColorSpace(colorSpace);+ let rewriter: SpsColorRewriter | null = null;+ let lengthSize = 4;+ return {+ transformConfig: (config) => {+ const codec = spsCodecOf(config.codec);+ if (!codec || !config.description) return config;+ rewriter = new SpsColorRewriter(codec, tags);+ const desc = bytesOf(config.description);+ lengthSize = descriptionLengthSize(codec, desc);+ return { ...config, description: rewriter.description(desc) };+ },+ transformPacket: (data) => rewriter?.sample(data, lengthSize) ?? null,+ };+}++const bytesOf = (buffer: AllowSharedBufferSource): Uint8Array =>+ buffer instanceof ArrayBuffer || buffer instanceof SharedArrayBuffer+ ? new Uint8Array(buffer)+ : new Uint8Array(buffer.buffer, buffer.byteOffset, buffer.byteLength);+export type FrameSinkFactory = (track: InputVideoTrack,size?: FrameSize,@@ -434,6 +544,7 @@ const canvasSinkFactory: FrameSinkFactory = (track, size, opts) => {const decoderOptions = {...(opts?.lowLatency ? { optimizeForLatency: true } : {}),...(opts?.software ? { hardwareAcceleration: "prefer-software" as const } : {}),+ ...(opts?.colorSpace ? { colorSpace: opts.colorSpace, ...spsHooks(opts.colorSpace) } : {}),};return new CanvasSink(track, {...size,@@ -445,9 +556,16 @@ const canvasSinkFactory: FrameSinkFactory = (track, size, opts) => {let sinkFactory: FrameSinkFactory = canvasSinkFactory;/** Install a replacement frame reader, e.g. the skia-backed one a headless- * process uses. Affects every later `frameSink` call. */-export function setFrameSinkFactory(f: FrameSinkFactory): void {- sinkFactory = f;+ * process uses; null puts the page's own back. Affects every later+ * `frameSink` call. */+export function setFrameSinkFactory(f: FrameSinkFactory | null): void {+ sinkFactory = f ?? canvasSinkFactory;+}++/** True once a replacement frame reader is installed: frames then come from+ * the process's own decoder, drawn through the file's own matrix. */+export function frameSinkIsCustom(): boolean {+ return sinkFactory !== canvasSinkFactory;}/** A sink that draws this track's frames at `size`. Rotation from the file'sdiff --git a/site/src/cut/lib/memoryBudget.ts b/site/src/cut/lib/memoryBudget.tsindex 72669a54..32f28ae7 100644--- a/site/src/cut/lib/memoryBudget.ts+++ b/site/src/cut/lib/memoryBudget.ts@@ -130,10 +130,13 @@ const HOLDERS = {previewDecoders: { bucket: "decoders", portion: 1 },/** The preview pool: the ring each live source lands frames on, and the* shelf of canvases kept for the sources that have stood down. */- previewCanvases: { bucket: "canvases", portion: 0.75 },+ previewCanvases: { bucket: "canvases", portion: 0.72 },/** Readers a render keeps open between frames, each with its own pool of* canvases at the source's size. */- exportReaders: { bucket: "canvases", portion: 0.25 },+ exportReaders: { bucket: "canvases", portion: 0.2 },+ /** The sharpen and clarity pass's float framebuffers, at the picture's+ * size while detail is in use. */+ detailTargets: { bucket: "canvases", portion: 0.08 },/** File bytes held once for every reader on a cloud file. */chunkMemory: { bucket: "reads", portion: 0.5 },/** What each open reader keeps of its own walk through a file. */@@ -141,7 +144,16 @@ const HOLDERS = {/** Decoded sound waiting for the mixer to schedule it. */mixerAudio: { bucket: "audio", portion: 1 },/** Filmstrips and waveforms drawn for shelf entries. */- libraryPictures: { bucket: "pictures", portion: 0.45 },+ libraryPictures: { bucket: "pictures", portion: 0.25 },+ /** Parsed LUT files off the Library shelf, held for the clips that use them. */+ lutTables: { bucket: "pictures", portion: 0.05 },+ /** The same tables held again by the LUT build worker, which bakes from+ * its own copies. */+ lutWorkerTables: { bucket: "pictures", portion: 0.05 },+ /** Baked clip color LUTs: the lattices the compositor samples. */+ gradeLuts: { bucket: "pictures", portion: 0.06 },+ /** The same LUTs uploaded as 3D textures for the GPU pass. */+ gradeLutTextures: { bucket: "pictures", portion: 0.04 },/** Captured frames behind trim edges and filmstrip tiles. */edgeFrames: { bucket: "pictures", portion: 0.3 },/** Decoded sticker images, shared across the page's renders. */diff --git a/site/src/cut/lib/previewCanvas.ts b/site/src/cut/lib/previewCanvas.tsindex 7e739294..9713d477 100644--- a/site/src/cut/lib/previewCanvas.ts+++ b/site/src/cut/lib/previewCanvas.ts@@ -1,6 +1,7 @@"use client";import { createRasterCanvas, type RasterSurface } from "./raster";+import type { ColorRead } from "./sourceColor";/*** The live preview <canvas>, registered by Preview while it is mounted, so@@ -79,6 +80,19 @@ export function sampleClipSource(clipId: string): CanvasImageSource | null {return sampler?.(clipId) ?? null;}+/** How the engine reads a clip's frames — the read the sampled frame came+ * through, so an analysis converts it the way the compositor does. */+type SourceColor = (clipId: string) => ColorRead | null;+let sourceColor: SourceColor | null = null;++export function registerSourceColor(fn: SourceColor | null) {+ sourceColor = fn;+}++export function sampleClipColorRead(clipId: string): ColorRead | null {+ return sourceColor?.(clipId) ?? null;+}+/** A small RGBA readout of the clip's raw frame, for analysis (auto grade);* null when no decoder is ready or the pixels are unreadable. */export function sampleClipFrameData(clipId: string, w = 96, h = 54): Uint8ClampedArray | null {diff --git a/site/src/cut/lib/projectCopy.test.ts b/site/src/cut/lib/projectCopy.test.tsnew file mode 100644index 00000000..11e66ed6--- /dev/null+++ b/site/src/cut/lib/projectCopy.test.ts@@ -0,0 +1,93 @@+import { describe, expect, mock, test } from "bun:test";+import { stubModule } from "@/lib/testing/stubModule";+import type { CutBackend } from "./backend/types";+import type { ProjectDoc } from "./types";++const uploads: { kind: string; fileName: string }[] = [];+await stubModule("./media", import.meta.url, {+ uploadProjectMediaTo: async (backend: CutBackend, _projectId: string, _blob: Blob, name: string) => {+ uploads.push({ kind: backend.kind, fileName: name });+ return name;+ },+});+await stubModule("./mediaSync", import.meta.url, { localMediaFile: async () => null });+await stubModule("./chatCloud", import.meta.url, {+ fetchCloudThreads: async () => [],+ putCloudThread: async () => {},+});+await stubModule("./chatThreads", import.meta.url, {+ readProjectThreads: () => [],+ writeProjectThreads: () => {},+ mergeThreads: () => [],+});+await stubModule("./linkedLibrary", import.meta.url, {+ ensureLinkedOnCloud: async () => {},+ linkedIdsIn: () => [],+});+const { copyProjectAcross } = await import("./projectCopy");++const doc = {+ id: "src",+ name: "Cut",+ assets: [+ {+ id: "a",+ fileName: "IMG_1.MOV",+ name: "IMG_1.MOV",+ type: "video",+ duration: 4,+ color: { matrix: "bt2020nc", fullRange: false, bitDepth: 10, detected: "apple-log", codec: "apch" },+ proxy: { fileName: "IMG_1.proxy.mp4", sizeBytes: 100 },+ },+ { id: "b", fileName: "b.mp4", name: "b.mp4", type: "video", duration: 2 },+ ],+} as unknown as ProjectDoc;++function backend(kind: CutBackend["kind"]) {+ const calls: { path: string; method: string; body?: unknown }[] = [];+ let saved: ProjectDoc | null = null;+ const fetch = mock(async (path: string, init?: RequestInit) => {+ const method = init?.method ?? "GET";+ calls.push({ path, method, body: typeof init?.body === "string" ? JSON.parse(init.body) : undefined });+ if (method === "GET" && path === "/api/cut/projects/src") return Response.json(doc);+ if (method === "GET" && path.includes("/media/")) return new Response("bytes");+ if (method === "POST" && path === "/api/cut/projects") return Response.json({ id: "dst" });+ if (method === "PUT") {+ saved = JSON.parse(init!.body as string) as ProjectDoc;+ return Response.json({ ok: true });+ }+ return Response.json({ jobId: "j" });+ });+ return {+ api: { kind, caps: {}, fetch, url: (p: string) => p } as unknown as CutBackend,+ calls,+ saved: () => saved,+ };+}++describe("copying a project with a ProRes master", () => {+ test("carries the proxy and the color record to a Mac", async () => {+ uploads.length = 0;+ const src = backend("browser");+ const dst = backend("local");+ expect(await copyProjectAcross(src.api, dst.api, "src")).toBe("dst");+ expect(uploads.map((u) => u.fileName)).toEqual(["IMG_1.MOV", "IMG_1.proxy.mp4", "b.mp4"]);+ const copied = dst.saved()!;+ expect(copied.assets[0].proxy).toEqual({ fileName: "IMG_1.proxy.mp4", sizeBytes: 100 });+ expect(copied.assets[0].color).toMatchObject({ detected: "apple-log", codec: "apch" });+ expect(dst.calls.some((c) => c.path.endsWith("/proxy"))).toBe(false);+ });++ test("leaves the proxy behind on the way to the cloud and asks the worker for a new one", async () => {+ uploads.length = 0;+ const src = backend("local");+ const dst = backend("cloud");+ await copyProjectAcross(src.api, dst.api, "src");+ expect(uploads.map((u) => u.fileName)).toEqual(["IMG_1.MOV", "b.mp4"]);+ const copied = dst.saved()!;+ expect(copied.assets[0].proxy).toBeUndefined();+ expect(copied.assets[0].color).toMatchObject({ detected: "apple-log" });+ const queued = dst.calls.filter((c) => c.method === "POST" && c.path === "/api/cut/projects/dst/proxy");+ expect(queued.map((c) => c.body)).toEqual([{ file: "IMG_1.MOV" }]);+ });+});diff --git a/site/src/cut/lib/projectCopy.ts b/site/src/cut/lib/projectCopy.tsindex bf03644f..ef8d4a20 100644--- a/site/src/cut/lib/projectCopy.ts+++ b/site/src/cut/lib/projectCopy.ts@@ -10,7 +10,7 @@ import { mergeThreads, readProjectThreads, writeProjectThreads } from "./chatThrimport { ensureLinkedOnCloud, linkedIdsIn } from "./linkedLibrary";import { uploadProjectMediaTo } from "./media";import { localMediaFile } from "./mediaSync";-import type { ProjectDoc } from "./types";+import type { ProjectDoc, StoredAsset } from "./types";/** Move a project's conversations onto the copy.*@@ -63,26 +63,35 @@ export async function copyProjectAcross(created = summary.id;const assets = Array.isArray(doc.assets) ? doc.assets : [];const names = new Map<string, string>();- const unique = new Set(assets.map((a) => a.fileName)).size;- for (const a of assets) {- if (names.has(a.fileName)) continue;+ // A preview proxy travels with its master to a Mac or a browser. The+ // cloud writes proxies only through its worker — they are the one+ // quota-exempt media there — so a copy landing in the cloud leaves the+ // proxy behind and asks the worker for a new one once the doc is saved.+ const carryProxies = dst.kind !== "cloud";+ const files = assets.flatMap((a) => [+ { fileName: a.fileName, name: a.name },+ ...(carryProxies && a.proxy ? [{ fileName: a.proxy.fileName, name: a.name }] : []),+ ]);+ const unique = new Set(files.map((f) => f.fileName)).size;+ for (const f of files) {+ if (names.has(f.fileName)) continue;// A cloud project's media may exist only in this browser's store so far// (an import the lazy upload hasn't drained — a full account's, say).// The local copy is the same write-once bytes, and for the undrained// file it is the only copy, so it is read first; the network serves the// rest.- const local = src.kind === "cloud" ? await localMediaFile(projectId, a.fileName) : null;+ const local = src.kind === "cloud" ? await localMediaFile(projectId, f.fileName) : null;let blob: Blob;if (local) {blob = local;} else {const bytes = await src.fetch(- `/api/cut/projects/${projectId}/media/${encodeURIComponent(a.fileName)}`+ `/api/cut/projects/${projectId}/media/${encodeURIComponent(f.fileName)}`);- if (!bytes.ok) throw new Error(`Could not read “${a.name}”.`);+ if (!bytes.ok) throw new Error(`Could not read “${f.name}”.`);blob = await bytes.blob();}- names.set(a.fileName, await uploadProjectMediaTo(dst, summary.id, blob, a.fileName));+ names.set(f.fileName, await uploadProjectMediaTo(dst, summary.id, blob, f.fileName));opts.onProgress?.(names.size, unique);}// A project moving to the cloud takes what it links to with it: a render@@ -96,7 +105,14 @@ export async function copyProjectAcross(id: undefined,name,folderId: null,- assets: assets.map((a) => ({ ...a, fileName: names.get(a.fileName) ?? a.fileName })),+ assets: assets.map((a) => {+ const { proxy, ...rest } = a;+ const copied: StoredAsset = { ...rest, fileName: names.get(a.fileName) ?? a.fileName };+ if (proxy && carryProxies) {+ copied.proxy = { ...proxy, fileName: names.get(proxy.fileName) ?? proxy.fileName };+ }+ return copied;+ }),};const putRes = await dst.fetch(`/api/cut/projects/${summary.id}`, {method: "PUT",@@ -105,6 +121,20 @@ export async function copyProjectAcross(});if (!putRes.ok) throw new Error("Could not save the project.");await copyChatThreads(src, dst, projectId, summary.id);+ if (!carryProxies) {+ // The worker builds the proxies the copy left behind; the editor writes+ // each onto its asset when the project is next opened.+ for (const a of assets) {+ if (!a.proxy) continue;+ void dst+ .fetch(`/api/cut/projects/${summary.id}/proxy`, {+ method: "POST",+ headers: { "Content-Type": "application/json" },+ body: JSON.stringify({ file: names.get(a.fileName) ?? a.fileName }),+ })+ .catch(() => {});+ }+ }return summary.id;} catch (e) {if (created) {diff --git a/site/src/cut/lib/projectReference.ts b/site/src/cut/lib/projectReference.tsindex 0d76ac98..feadfb3b 100644--- a/site/src/cut/lib/projectReference.ts+++ b/site/src/cut/lib/projectReference.ts@@ -9,6 +9,7 @@// needs the editor page's sign-in there and is refused with a plain reason.import { getBackend, type CutBackend } from "./backend";+import { isLinkedAssetType } from "./types";import { sharedBackendFor } from "./backend/shared";import { apiJson } from "./api";import { tagChatAsset } from "./chatAssets";@@ -190,7 +191,7 @@ export async function landReferenceAssets(useEditor.getState().addAsset(asset);if (opts.chatId !== undefined) tagChatAsset(asset.id, opts.chatId);if (asset.type === "font") void registerFontAsset(asset).catch(() => {});- else void enrichAsset(asset).catch(() => {});+ else if (!isLinkedAssetType(asset.type)) void enrichAsset(asset).catch(() => {});out.push({ sourceId: source.id, asset, reused: false });}// In the order asked for, so a caller's index arithmetic holds.diff --git a/site/src/cut/lib/projectTemplate.ts b/site/src/cut/lib/projectTemplate.tsindex d15eb0f5..20594dfb 100644--- a/site/src/cut/lib/projectTemplate.ts+++ b/site/src/cut/lib/projectTemplate.ts@@ -6,6 +6,7 @@// plays each part.import { ITEM_KINDS, type ItemKind, type ItemOf } from "./itemKinds";+import { isLinkedAssetType } from "./types";import { getClipSpans, layerFromClip, normalizeDocState, resolveTransitions, totalDuration } from "./store";import {CAPTION_LOOK_KEYS,@@ -256,6 +257,6 @@ export function clampLayersToAssets(/** Whether an asset of this type can stand in for a source of that type. */export const mediaTypeFits = (source: AssetType, replacement: AssetType): boolean =>- source === "audio" || source === "font"+ source === "audio" || isLinkedAssetType(source)? replacement === source: replacement === "video" || replacement === "image";diff --git a/site/src/cut/lib/proresDecoder.ts b/site/src/cut/lib/proresDecoder.tsnew file mode 100644index 00000000..76864504--- /dev/null+++ b/site/src/cut/lib/proresDecoder.ts@@ -0,0 +1,13 @@+/**+ * The WASM ProRes decoder, registered with mediabunny on first need. A+ * ProRes master decodes through it in the page until its proxy lands, and+ * the in-tab export reads the master through it always.+ */++let registered: Promise<void> | null = null;++export function ensureProresDecoder(): Promise<void> {+ return (registered ??= import("@mediabunny/prores").then((m) => {+ m.registerProresDecoder();+ }));+}diff --git a/site/src/cut/lib/proxyPlanes.test.ts b/site/src/cut/lib/proxyPlanes.test.tsnew file mode 100644index 00000000..f61ace2c--- /dev/null+++ b/site/src/cut/lib/proxyPlanes.test.ts@@ -0,0 +1,154 @@+import { describe, expect, test } from "bun:test";+import { decodeYcc } from "@donkeycut/effects-kit";+import { convertPlanes, isPlanarFormat, planesPassThrough, proxySize, type PlanarFormat } from "./proxyPlanes";++/** A flat frame of one Y'CbCr triple in `format`, planes packed tight. */+function flat(format: PlanarFormat, width: number, height: number, y: number, cb: number, cr: number) {+ const hs = format.startsWith("I444") ? 0 : 1;+ const vs = format.startsWith("I420") ? 1 : 0;+ const cw = (width + (1 << hs) - 1) >> hs;+ const ch = (height + (1 << vs) - 1) >> vs;+ const data = new ArrayBuffer((width * height + 2 * cw * ch) * 2);+ const u16 = new Uint16Array(data);+ u16.fill(y, 0, width * height);+ u16.fill(cb, width * height, width * height + cw * ch);+ u16.fill(cr, width * height + cw * ch);+ return {+ format,+ width,+ height,+ data,+ layout: [+ { offset: 0, stride: width * 2 },+ { offset: width * height * 2, stride: cw * 2 },+ { offset: (width * height + cw * ch) * 2, stride: cw * 2 },+ ],+ };+}++/** R'G'B' of a code triple at `depth` bits: BT.2100's scaling — limited+ * range on 16..235 / 16..240 times 2^(d-8), full range on 0..2^d-1 with+ * chroma centered on 2^(d-1). */+function rgbOf(matrix: "bt709" | "bt601" | "bt2020nc", fullRange: boolean, depth: number, y: number, cb: number, cr: number) {+ const scale = 1 << (depth - 8);+ const [yn, cbn, crn] = fullRange+ ? [y / ((1 << depth) - 1), (cb - (1 << (depth - 1))) / ((1 << depth) - 1), (cr - (1 << (depth - 1))) / ((1 << depth) - 1)]+ : [(y - 16 * scale) / (219 * scale), (cb - 128 * scale) / (224 * scale), (cr - 128 * scale) / (224 * scale)];+ // decodeYcc takes 8-bit-scaled limited code values; hand it the same+ // normalized numbers by re-encoding them on that scale.+ return decodeYcc({ matrix, fullRange: false }, (16 + 219 * yn) / 255, (128 + 224 * cbn) / 255, (128 + 224 * crn) / 255);+}++describe("proxy planes", () => {+ test("knows the decoder's 10- and 12-bit planar formats", () => {+ expect(isPlanarFormat("I422P10")).toBe(true);+ expect(isPlanarFormat("I420")).toBe(false);+ expect(isPlanarFormat("RGBA")).toBe(false);+ const fits = { width: 1920, height: 1080, maxHeight: 2160 };+ expect(planesPassThrough("I420P10", { matrix: "bt709", fullRange: false }, fits)).toBe(true);+ expect(planesPassThrough("I422P10", { matrix: "bt709", fullRange: false }, fits)).toBe(false);+ expect(planesPassThrough("I420P10", { matrix: "bt2020nc", fullRange: false }, fits)).toBe(false);+ expect(planesPassThrough("I420P10", { matrix: "bt709", fullRange: false }, { ...fits, maxHeight: 720 })).toBe(false);+ expect(planesPassThrough("I420P10", { matrix: "bt709", fullRange: false }, { width: 1921, height: 1080, maxHeight: 2160 })).toBe(false);+ });++ test("carries a BT.2020 4:2:2 picture into Rec.709 limited 4:2:0 at the same RGB", () => {+ const [y, cb, cr] = [543, 366, 634];+ const out = convertPlanes(flat("I422P10", 8, 4, y, cb, cr), { matrix: "bt2020nc", fullRange: false });+ expect(out.format).toBe("I420P10");+ const u16 = new Uint16Array(out.data);+ const oy = u16[0], ocb = u16[out.layout[1].offset / 2], ocr = u16[out.layout[2].offset / 2];+ expect(ocb).not.toBe(cb);+ const want = rgbOf("bt2020nc", false, 10, y, cb, cr);+ const got = rgbOf("bt709", false, 10, oy, ocb, ocr);+ for (let c = 0; c < 3; c++) expect(Math.abs(got[c] - want[c]) * 1023).toBeLessThan(1.5);+ // Flat in, flat out.+ expect(new Set(u16.subarray(0, 32))).toEqual(new Set([oy]));+ });++ test("brings a full-range 12-bit 4:4:4 picture down to 10-bit limited", () => {+ const [y, cb, cr] = [3000, 1200, 2600];+ const out = convertPlanes(flat("I444P12", 4, 4, y, cb, cr), { matrix: "bt709", fullRange: true });+ const u16 = new Uint16Array(out.data);+ const want = rgbOf("bt709", true, 12, y, cb, cr);+ const got = rgbOf("bt709", false, 10, u16[0], u16[out.layout[1].offset / 2], u16[out.layout[2].offset / 2]);+ for (let c = 0; c < 3; c++) expect(Math.abs(got[c] - want[c]) * 1023).toBeLessThan(1.5);+ expect(u16[0]).toBeGreaterThanOrEqual(64);+ expect(u16[0]).toBeLessThanOrEqual(940);+ });++ test("averages chroma over each 2×2 block", () => {+ const frame = flat("I444P10", 2, 2, 512, 512, 512);+ const u16 = new Uint16Array(frame.data);+ // Cb: 400, 600 on the top row, 400, 600 below → 500.+ u16.set([400, 600, 400, 600], 4);+ const out = convertPlanes(frame, { matrix: "bt709", fullRange: false });+ const o = new Uint16Array(out.data);+ expect(o.length).toBe(4 + 1 + 1);+ expect(Math.abs(o[4] - 500)).toBeLessThanOrEqual(1);+ });++ test("sizes the proxy no taller than the cap, aspect kept, both sides even", () => {+ expect(proxySize(3840, 2160, 2160)).toEqual({ width: 3840, height: 2160 });+ expect(proxySize(3840, 2160, 1080)).toEqual({ width: 1920, height: 1080 });+ expect(proxySize(2160, 3840, 1080)).toEqual({ width: 608, height: 1080 });+ expect(proxySize(1001, 563, 2160)).toEqual({ width: 1000, height: 562 });+ expect(proxySize(4096, 2160, 1000)).toEqual({ width: 1896, height: 1000 });+ expect(proxySize(3, 3, 1080)).toEqual({ width: 2, height: 2 });+ });++ test("brings a taller master down with an area filter: means over the boxes each output pixel covers", () => {+ // 8×8 luma: the left half at 400, the right at 800, 4:2:0 neutral chroma.+ const frame = flat("I420P10", 8, 8, 400, 512, 512);+ const u16 = new Uint16Array(frame.data);+ for (let y = 0; y < 8; y++) for (let x = 4; x < 8; x++) u16[y * 8 + x] = 800;+ const out = convertPlanes(frame, { matrix: "bt709", fullRange: false }, { maxHeight: 4 });+ expect(out.width).toBe(4);+ expect(out.height).toBe(4);+ const o = new Uint16Array(out.data);+ expect(o.length).toBe(16 + 4 + 4);+ // Whole boxes: 2×2 of one value.+ expect(o[0]).toBe(400);+ expect(o[3]).toBe(800);+ expect(o[5]).toBe(400);+ expect(o[6]).toBe(800);+ // Chroma stays neutral.+ expect(o[16]).toBe(512);+ expect(o[20]).toBe(512);++ // A 3:1 ratio: 6 rows into 2, so the second output row averages rows 3..5.+ const tall = flat("I444P10", 2, 6, 100, 512, 512);+ const t = new Uint16Array(tall.data);+ for (let y = 3; y < 6; y++) for (let x = 0; x < 2; x++) t[y * 2 + x] = 700;+ const down = convertPlanes(tall, { matrix: "bt709", fullRange: false }, { maxHeight: 2 });+ expect(down.height).toBe(2);+ const d = new Uint16Array(down.data);+ expect(d[0]).toBe(100);+ expect(d[2]).toBe(700);++ // A fractional ratio: 5 columns into 2 — the middle column splits half and half.+ const wide = flat("I444P10", 5, 2, 200, 512, 512);+ const w = new Uint16Array(wide.data);+ for (let y = 0; y < 2; y++) for (let x = 3; x < 5; x++) w[y * 5 + x] = 600;+ for (let y = 0; y < 2; y++) w[y * 5 + 2] = 400;+ // The height fits, so the frame is only evened: 5×2 → 4×2.+ const evened = convertPlanes(wide, { matrix: "bt709", fullRange: false }, { maxHeight: 2 });+ expect([evened.width, evened.height]).toEqual([4, 2]);+ const e = new Uint16Array(evened.data);+ // Column 0 covers 0..1.25: 200; column 3 covers 3.75..5: 600.+ expect(e[0]).toBe(200);+ expect(e[3]).toBe(600);+ // Column 1 covers 1.25..2.5: 0.75 of 200 and 0.5 of 400 → 280.+ expect(Math.abs(e[1] - 280)).toBeLessThanOrEqual(1);+ });++ test("a scaled BT.2020 picture still lands on the same RGB", () => {+ const [y, cb, cr] = [543, 366, 634];+ const out = convertPlanes(flat("I422P10", 16, 8, y, cb, cr), { matrix: "bt2020nc", fullRange: false }, { maxHeight: 4 });+ expect([out.width, out.height]).toEqual([8, 4]);+ const u16 = new Uint16Array(out.data);+ const want = rgbOf("bt2020nc", false, 10, y, cb, cr);+ const got = rgbOf("bt709", false, 10, u16[0], u16[out.layout[1].offset / 2], u16[out.layout[2].offset / 2]);+ for (let c = 0; c < 3; c++) expect(Math.abs(got[c] - want[c]) * 1023).toBeLessThan(1.5);+ });+});diff --git a/site/src/cut/lib/proxyPlanes.ts b/site/src/cut/lib/proxyPlanes.tsnew file mode 100644index 00000000..01d4ac84--- /dev/null+++ b/site/src/cut/lib/proxyPlanes.ts@@ -0,0 +1,236 @@+/**+ * Y'CbCr planes through one matrix and out through Rec.709 limited, for the+ * proxy a browser builds in the page (mediaProxy.ts). The WASM ProRes decoder+ * hands out 10- or 12-bit planes carrying the master's own matrix — BT.2020+ * non-constant on an iPhone Apple Log file — and a proxy must carry the same+ * picture as Rec.709 limited code values, so every decoder draws it untouched.+ * A canvas would do the conversion in 8 bits; this does it on the planes and+ * keeps the depth. The output is always 4:2:0 at 10 bits — what the browser's+ * 10-bit encoders take — with chroma averaged over each 2×2 block, and a+ * master taller than the proxy may be is brought down in the same pass with+ * an area filter: every source pixel lands in the output pixels it covers,+ * weighted by how much of it they cover.+ */++import type { CodeFormat } from "@donkeycut/effects-kit";++export type PlanarFormat =+ | "I420P10" | "I420P12" | "I422P10" | "I422P12" | "I444P10" | "I444P12";++/** Chroma subsampling shifts and sample depth of each format. */+const FORMATS: Record<PlanarFormat, { hs: number; vs: number; depth: number }> = {+ I420P10: { hs: 1, vs: 1, depth: 10 },+ I420P12: { hs: 1, vs: 1, depth: 12 },+ I422P10: { hs: 1, vs: 0, depth: 10 },+ I422P12: { hs: 1, vs: 0, depth: 12 },+ I444P10: { hs: 0, vs: 0, depth: 10 },+ I444P12: { hs: 0, vs: 0, depth: 12 },+};++export const isPlanarFormat = (format: string | null | undefined): format is PlanarFormat =>+ !!format && format in FORMATS;++/** Luma coefficients of each matrix. */+const COEFFICIENTS: Record<CodeFormat["matrix"], { kr: number; kb: number }> = {+ bt709: { kr: 0.2126, kb: 0.0722 },+ bt601: { kr: 0.299, kb: 0.114 },+ bt2020nc: { kr: 0.2627, kb: 0.0593 },+};++export interface PlaneLayoutLike {+ offset: number;+ stride: number;+}++export interface PlanarFrame {+ format: PlanarFormat;+ width: number;+ height: number;+ data: ArrayBuffer;+ /** Byte offset and stride of the Y, Cb and Cr planes. */+ layout: PlaneLayoutLike[];+}++export interface ConvertedFrame {+ format: "I420P10";+ width: number;+ height: number;+ data: ArrayBuffer;+ layout: PlaneLayoutLike[];+}++/** The proxy's size for a master of `width`×`height`: no taller than+ * `maxHeight`, the aspect kept, both sides even (4:2:0 has no odd sizes). */+export function proxySize(width: number, height: number, maxHeight: number): { width: number; height: number } {+ const even = (n: number) => Math.max(2, n - (n % 2));+ if (height <= maxHeight) return { width: even(width), height: even(height) };+ const h = even(Math.floor(maxHeight));+ return { width: even(Math.round((width * h) / height)), height: h };+}++/** For each source index along one axis, the output indexes it lands in and+ * the share of it each one takes: an area filter, separable. A source pixel+ * on an output boundary is split between the two. */+function areaMap(srcSize: number, outSize: number): { at: Int32Array; w: Float32Array; n: Uint8Array } {+ const ratio = outSize / srcSize;+ const at = new Int32Array(srcSize * 2);+ const w = new Float32Array(srcSize * 2);+ const n = new Uint8Array(srcSize);+ for (let i = 0; i < srcSize; i++) {+ const a = i * ratio;+ const b = (i + 1) * ratio;+ const first = Math.min(outSize - 1, Math.floor(a));+ const last = Math.min(outSize - 1, Math.ceil(b) - 1);+ if (last <= first) {+ at[i * 2] = first;+ w[i * 2] = 1;+ n[i] = 1;+ } else {+ // Straddles the boundary at `first + 1`: split by the share on each side.+ const cut = (first + 1 - a) / ratio;+ at[i * 2] = first;+ w[i * 2] = cut;+ at[i * 2 + 1] = last;+ w[i * 2 + 1] = 1 - cut;+ n[i] = 2;+ }+ }+ return { at, w, n };+}++/** Whether the frame already is what the conversion would produce, so the+ * planes pass through untouched. */+export const planesPassThrough = (+ format: PlanarFormat,+ from: Pick<CodeFormat, "matrix" | "fullRange">,+ size: { width: number; height: number; maxHeight: number }+): boolean =>+ format === "I420P10" &&+ from.matrix === "bt709" &&+ !from.fullRange &&+ size.height <= size.maxHeight &&+ size.width % 2 === 0 &&+ size.height % 2 === 0;++/**+ * Convert a frame's planes from `from` to Rec.709 limited 4:2:0 10-bit.+ * Chroma is read at the nearest sample and written as the mean over each+ * output block, so a 4:2:2 or 4:4:4 source keeps its luma and averages+ * its chroma down.+ */+export function convertPlanes(+ frame: PlanarFrame,+ from: Pick<CodeFormat, "matrix" | "fullRange">,+ opts: { maxHeight?: number } = {}+): ConvertedFrame {+ const { hs, vs, depth } = FORMATS[frame.format];+ const { kr, kb } = COEFFICIENTS[from.matrix];+ const kg = 1 - kr - kb;+ const { width, height } = frame;+ const src = new Uint16Array(frame.data);+ const [ly, lu, lv] = frame.layout;+ const yOff = ly.offset >> 1, yStride = ly.stride >> 1;+ const uOff = lu.offset >> 1, uStride = lu.stride >> 1;+ const vOff = lv.offset >> 1, vStride = lv.stride >> 1;++ const scale = 1 << (depth - 8);+ const full = from.fullRange;+ const yBias = full ? 0 : 16 * scale;+ const yRange = full ? (1 << depth) - 1 : 219 * scale;+ // Full-range chroma centers on 2^(d-1) and spans 2^d - 1 (BT.2100).+ const cBias = full ? 1 << (depth - 1) : 128 * scale;+ const cRange = full ? (1 << depth) - 1 : 224 * scale;+ const rCr = 2 * (1 - kr);+ const bCb = 2 * (1 - kb);+ // Rec.709 limited, 10-bit out.+ const OKR = 0.2126, OKB = 0.0722, OKG = 1 - OKR - OKB;+ const oCb = 1 / (2 * (1 - OKB));+ const oCr = 1 / (2 * (1 - OKR));++ const size = proxySize(width, height, opts.maxHeight ?? height);+ const outW = size.width;+ const outH = size.height;+ const scaled = outW !== width || outH !== height;+ const cw = outW >> 1;+ const ch = outH >> 1;+ const bytes = (outW * outH + 2 * cw * ch) * 2;+ const data = new ArrayBuffer(bytes);+ const out = new Uint16Array(data);+ const outU = outW * outH;+ const outV = outU + cw * ch;+ const sumCb = new Float32Array(cw * ch);+ const sumCr = new Float32Array(cw * ch);+ const wC = new Float32Array(cw * ch);+ // The scaled path gathers luma too; the unscaled one writes it straight.+ const sumY = scaled ? new Float32Array(outW * outH) : null;+ const wY = scaled ? new Float32Array(outW * outH) : null;+ const xm = scaled ? areaMap(width, outW) : null;+ const ym = scaled ? areaMap(height, outH) : null;++ const clampY = (v: number) => (v < 0 ? 0 : v > 1023 ? 1023 : v);+ for (let y = 0; y < height; y++) {+ const sy = y >> vs;+ const rowY = yOff + y * yStride;+ const rowU = uOff + sy * uStride;+ const rowV = vOff + sy * vStride;+ const oy = Math.min(outH - 1, y);+ for (let x = 0; x < width; x++) {+ const sx = x >> hs;+ const yy = (src[rowY + x] - yBias) / yRange;+ const cb = (src[rowU + sx] - cBias) / cRange;+ const cr = (src[rowV + sx] - cBias) / cRange;+ const r = yy + rCr * cr;+ const b = yy + bCb * cb;+ const g = (yy - kr * r - kb * b) / kg;+ const ny = OKR * r + OKG * g + OKB * b;+ const ncb = (b - ny) * oCb;+ const ncr = (r - ny) * oCr;+ if (!scaled) {+ out[oy * outW + x] = clampY(Math.round(64 + 876 * ny));+ const ci = (oy >> 1) * cw + (x >> 1);+ sumCb[ci] += ncb;+ sumCr[ci] += ncr;+ wC[ci] += 1;+ continue;+ }+ for (let j = 0; j < ym!.n[y]; j++) {+ const ty = ym!.at[y * 2 + j];+ const wy = ym!.w[y * 2 + j];+ for (let i = 0; i < xm!.n[x]; i++) {+ const tx = xm!.at[x * 2 + i];+ const w = wy * xm!.w[x * 2 + i];+ const li = ty * outW + tx;+ sumY![li] += w * ny;+ wY![li] += w;+ const ci = (ty >> 1) * cw + (tx >> 1);+ sumCb[ci] += w * ncb;+ sumCr[ci] += w * ncr;+ wC[ci] += w;+ }+ }+ }+ }+ if (scaled) {+ for (let i = 0; i < outW * outH; i++) {+ out[i] = clampY(Math.round(64 + 876 * (sumY![i] / (wY![i] || 1))));+ }+ }+ for (let i = 0; i < cw * ch; i++) {+ const n = wC[i] || 1;+ const cbv = Math.round(512 + 896 * (sumCb[i] / n));+ const crv = Math.round(512 + 896 * (sumCr[i] / n));+ out[outU + i] = cbv < 0 ? 0 : cbv > 1023 ? 1023 : cbv;+ out[outV + i] = crv < 0 ? 0 : crv > 1023 ? 1023 : crv;+ }+ return {+ format: "I420P10",+ width: outW,+ height: outH,+ data,+ layout: [+ { offset: 0, stride: outW * 2 },+ { offset: outU * 2, stride: cw * 2 },+ { offset: outV * 2, stride: cw * 2 },+ ],+ };+}diff --git a/site/src/cut/lib/refMedia.ts b/site/src/cut/lib/refMedia.tsindex ec2999ca..81e43b6a 100644--- a/site/src/cut/lib/refMedia.ts+++ b/site/src/cut/lib/refMedia.ts@@ -412,6 +412,8 @@ export async function refsToParts(text:ref.scope === "note"? `Referenced note "${ref.name}". Read its current text with read_note: ${JSON.stringify({ id: ref.id })}`+ : ref.use+ ? `Referenced ${ref.use.noun} "${ref.name}" in the Library. Use it with ${ref.use.tool}: ${JSON.stringify(ref.use.args)}`: ref.scope === "folder"? `Referenced folder "${ref.name}". Read its current contents with read_folder: ${JSON.stringify(ref.folder)}`: isCatalogRef(ref)diff --git a/site/src/cut/lib/refPlace.ts b/site/src/cut/lib/refPlace.tsindex a4926e3c..0b165465 100644--- a/site/src/cut/lib/refPlace.ts+++ b/site/src/cut/lib/refPlace.ts@@ -9,6 +9,7 @@*/import { CATALOG_PREFIX, type AssetRef } from "./assetRef";+import { isLinkedAssetType } from "./types";import {addProjectTemplateToTimeline,addTemplateToProject,@@ -27,7 +28,7 @@ import type { EffectId } from "@donkeycut/effects-kit";* sound on the first audio lane with room. */function placeAsset(asset: MediaAsset, at: number): void {const s = useEditor.getState();- if (asset.type === "font") return;+ if (isLinkedAssetType(asset.type)) return;if (asset.origin === "sticker") {s.addSticker({ assetId: asset.id, ...(isLottieAsset(asset) ? { lottie: true } : {}), at });return;@@ -61,7 +62,7 @@ export async function placeRefAtPlayhead(}case "library": {const lib = library.assets.find((a) => a.id === ref.id);- if (!lib || lib.type === "font") return false;+ if (!lib || isLinkedAssetType(lib.type)) return false;placeWhenReady(await importLibraryAsset(projectId, lib));return true;}diff --git a/site/src/cut/lib/removalVideo.ts b/site/src/cut/lib/removalVideo.tsindex 640335fa..c9efdab8 100644--- a/site/src/cut/lib/removalVideo.ts+++ b/site/src/cut/lib/removalVideo.ts@@ -13,6 +13,7 @@import { matteLumaToAlpha, removalActive, retimeOf } from "@donkeycut/effects-kit";import { openCanvasVideo, scaledEvenSize } from "./canvasVideo";import { FrameCompositor, type Frame } from "./composite";+import { ensureClipLuts } from "./lutBuild";import { createRasterCanvas, decodeRasterImageUrl, type RasterSurface } from "./raster";import type { MediaAsset, VideoClip } from "./types";import { liveReader } from "./liveReader";@@ -109,7 +110,12 @@ export async function renderRemovalPieces(// The compositor renders the layer with the preview's own code; its// drawing canvas never draws, the scratches do the work.const comp = new FrameCompositor(createRasterCanvas(2, 2));+ comp.colorMode = "exact";+ // The layer is drawn through the recipe of the read that decoded it.+ await reader.colorRead.settled();+ comp.sourceProvider = () => reader.colorRead.recipe();const bakeClip = opts.bakeLook ? clip : { ...clip, look: undefined };+ await ensureClipLuts([comp.recipeFor(bakeClip)]);const matteFrame = createRasterCanvas(2, 2);// The alpha plane's staging buffer, rewritten whole every frame.const alphaPlane = new ImageData(w, h);diff --git a/site/src/cut/lib/renderSnapshot.ts b/site/src/cut/lib/renderSnapshot.tsindex e7839772..6116c581 100644--- a/site/src/cut/lib/renderSnapshot.ts+++ b/site/src/cut/lib/renderSnapshot.ts@@ -1,3 +1,4 @@+import type { OutputSpace } from "@donkeycut/effects-kit";import type { Aspect, MediaAsset, VideoClip, AudioClip, Overlay, SubtitlesBlock } from "@/cut/lib/types";import type { ProjectOperation } from "@/cut/lib/projectOperation";@@ -13,6 +14,8 @@ export type ExportDoc = {subtitles: SubtitlesBlock;/** The frame's own color behind every clip and element (hex); absent = black. */background?: string;+ /** The delivery's color space; absent = SDR. */+ colorSpace?: OutputSpace;};export type RenderSnapshot = {@@ -30,5 +33,6 @@ export function renderDoc(doc: ExportDoc): ExportDoc {return {aspect: doc.aspect, assets: doc.assets, clips: doc.clips, audioClips: doc.audioClips,overlays: doc.overlays, subtitles: doc.subtitles, background: doc.background,+ ...(doc.colorSpace ? { colorSpace: doc.colorSpace } : {}),};}diff --git a/site/src/cut/lib/sourceColor.test.ts b/site/src/cut/lib/sourceColor.test.tsnew file mode 100644index 00000000..e302001f--- /dev/null+++ b/site/src/cut/lib/sourceColor.test.ts@@ -0,0 +1,87 @@+import { describe, expect, test } from "bun:test";+import { decodeOverrideFor } from "./decoderCheck";+import { ClipReader, renderFile } from "./exportRender";+import { FrameSourcePool } from "./frameSource";+import { sourceLookup } from "./lutBuild";+import { colorRead, fileAt, previewFile, sameColorRead } from "./sourceColor";+import type { MediaAsset } from "./types";++const HLG = { matrix: "bt2020nc", fullRange: false, bitDepth: 10, detected: "hlg", codec: "hvc1" } as const;++const asset = (over: Partial<MediaAsset> = {}): MediaAsset => ({+ id: "a",+ fileName: "a.mov",+ name: "a",+ type: "video",+ duration: 10,+ url: "https://media.test/a.mov",+ color: { ...HLG },+ ...over,+});++describe("colorRead", () => {+ test("a proxy is read as tagged, as Rec.709 limited, with the master's meaning", () => {+ const read = colorRead(asset(), "proxy");+ expect(read.colorSpace).toBeUndefined();+ expect(read.recipe()).toEqual({ profile: "hlg", matrix: "bt709", fullRange: false, drawnMatrix: "bt709", drawnFullRange: false });+ });++ test("an HLG master is read through the override at its own range", () => {+ const full = asset({ color: { ...HLG, fullRange: true } });+ const read = colorRead(full, "master");+ expect(read.colorSpace).toEqual(decodeOverrideFor("webcodecs", true));+ expect(read.recipe()).toMatchObject({ profile: "hlg", matrix: "bt2020nc", fullRange: true });+ });++ test("the file a URL names", () => {+ const withProxy = asset({ proxyUrl: "https://media.test/a.proxy.mp4" });+ expect(fileAt(withProxy, withProxy.proxyUrl!)).toBe("proxy");+ expect(fileAt(withProxy, withProxy.url)).toBe("master");+ expect(previewFile(withProxy)).toBe("proxy");+ expect(previewFile(asset())).toBe("master");+ });++ test("a Rec.709 record reads the picture an unprobed asset draws; an HLG one does not", () => {+ const rec709 = { color: { matrix: "bt709", fullRange: false, bitDepth: 8, detected: "rec709", codec: "avc1" } } as const;+ expect(sameColorRead({}, rec709, "master")).toBe(true);+ expect(sameColorRead({}, { color: { ...HLG } }, "master")).toBe(false);+ expect(sameColorRead({ color: { ...HLG } }, { color: { ...HLG } }, "proxy")).toBe(true);+ });+});++describe("a render reads the master, and draws it through the master's recipe", () => {+ test("even when the asset has a proxy", () => {+ const a = asset({ proxyUrl: "https://media.test/a.proxy.mp4" });+ const reader = new ClipReader(a, () => a.url);+ // The reader decodes the master through the override …+ expect(reader.colorRead.colorSpace).toEqual(decodeOverrideFor("webcodecs", false));+ // … and the compositor's recipe describes that read, never the proxy's.+ const recipe = sourceLookup([a], renderFile)({ assetId: a.id });+ expect(recipe).toEqual(reader.colorRead.recipe());+ expect(recipe).toMatchObject({ matrix: "bt2020nc" });+ });+});++describe("the preview's source and its recipe name the same file", () => {+ test("a source reports the read it decodes with, and follows a color that lands later", () => {+ const pool = new FrameSourcePool(4);+ pool.beginFrame();+ const unprobed = asset({ color: undefined });+ const src = pool.get("k", unprobed, 480);+ expect(src.colorRead.colorSpace).toBeUndefined();+ // The header is read after the source opened: the decode tag changes,+ // and the source takes the new record.+ const probed = asset();+ pool.get("k", probed, 480);+ expect(src.colorRead.colorSpace).toEqual(decodeOverrideFor("webcodecs", false));+ expect(pool.peek("k", 480)).toBe(src);+ });++ test("a source on the proxy is read as the proxy", () => {+ const pool = new FrameSourcePool(4);+ pool.beginFrame();+ const src = pool.get("k", asset({ proxyUrl: "https://media.test/a.proxy.mp4" }), 480);+ expect(src.file).toBe("proxy");+ expect(src.colorRead.colorSpace).toBeUndefined();+ });+});diff --git a/site/src/cut/lib/sourceColor.ts b/site/src/cut/lib/sourceColor.tsnew file mode 100644index 00000000..f2d84460--- /dev/null+++ b/site/src/cut/lib/sourceColor.ts@@ -0,0 +1,134 @@+/**+ * What a clip's frames mean, for the grade pipeline.+ *+ * A reader and the recipe its frames are drawn through have to agree on one+ * thing: which file is read, and how. `colorRead` answers both from the same+ * pair — the asset and the file being read, its master or its preview proxy+ * — so a reader takes its sink options and the compositor takes its recipe+ * from one value, and they cannot drift apart.+ *+ * A Rec.709 or sRGB master is drawn as it is. Any other master — Apple Log,+ * HLG, PQ — is decoded with its tags replaced by sRGB / Rec.709 at the file's+ * own range, so the browser draws code values, and the recipe names the+ * file's own matrix beside the one the decoder drew with (`decodePath`,+ * decoderCheck.ts, measured per route and range), so the source stage can+ * undo the drawn matrix before the profile conversion. A preview proxy is+ * tagged Rec.709 limited and needs neither.+ */++import type { DrawnColor, SourceProfile } from "@donkeycut/effects-kit";+import { decodeOverrideFor, decodePath, decodePathNow, type DecodeRoute } from "./decoderCheck";+import { frameSinkIsCustom } from "./mediaRead";+import type { MediaAsset, StoredAsset } from "./types";++export type { DecodeRoute } from "./decoderCheck";++/** Which of an asset's files a reader reads. */+export type ReadFile = "master" | "proxy";++type ColorOf = Pick<MediaAsset, "color" | "colorProfile">;++export interface RecipeInput extends DrawnColor {+ profile: SourceProfile;+}++/** How one reader reads an asset's frames, and what those frames mean. */+export interface ColorRead {+ /** The color space the reader's sink tags frames with; undefined draws the+ * file as it is tagged. */+ colorSpace: VideoColorSpaceInit | undefined;+ /** The recipe's source fields for these frames now. While the route's+ * measurement runs the drawn matrix is taken as the file's own, and the+ * recipe key changes once it settles. */+ recipe(): RecipeInput;+ /** The recipe once the route's drawn matrix is measured: what a job that+ * needs the exact picture from its first frame waits on. */+ settled(): Promise<RecipeInput>;+}++const REC709_LIMITED: DrawnColor = { matrix: "bt709", fullRange: false, drawnMatrix: "bt709", drawnFullRange: false };++/** What a source's code values mean: the person's override, else what the+ * header said, else Rec.709 for media imported before the probe existed. */+export function sourceProfileOf(asset: Pick<StoredAsset, "color" | "colorProfile"> | undefined | null): SourceProfile {+ return asset?.colorProfile ?? asset?.color?.detected ?? "rec709";+}++/** The file the preview reads: the proxy once there is one. */+export const previewFile = (asset: Pick<MediaAsset, "proxyUrl">): ReadFile => (asset.proxyUrl ? "proxy" : "master");++/** The file a URL of the asset names. */+export const fileAt = (asset: Pick<MediaAsset, "proxyUrl">, url: string): ReadFile =>+ asset.proxyUrl !== undefined && url === asset.proxyUrl ? "proxy" : "master";++/** The route a master's frames take in this process. */+function routeOf(asset: ColorOf): DecodeRoute {+ if (frameSinkIsCustom()) return "headless";+ if (asset.color?.codec?.startsWith("ap")) return "prores";+ return "webcodecs";+}++const fixedRead = (input: RecipeInput): ColorRead => ({+ colorSpace: undefined,+ recipe: () => input,+ settled: () => Promise.resolve(input),+});+/** A source whose header was never read: its code values are taken as+ * Rec.709 limited, meaning whatever profile it is set to. */+const unprobed: Partial<Record<SourceProfile, ColorRead>> = {};+/** Reads by header record, then file and profile: the compositor asks per+ * clip per frame, and a record is replaced whole whenever it changes. */+const reads = new WeakMap<object, Partial<Record<ReadFile, Partial<Record<SourceProfile, ColorRead>>>>>();++/** How `file` of `asset` is read in this process, and what its frames mean. */+export function colorRead(asset: ColorOf, file: ReadFile): ColorRead {+ const color = asset.color;+ const profile = sourceProfileOf(asset);+ if (!color) return (unprobed[profile] ??= fixedRead({ profile, ...REC709_LIMITED }));+ let held = reads.get(color);+ if (!held) reads.set(color, (held = {}));+ const byProfile = (held[file] ??= {});+ return (byProfile[profile] ??= readOf(asset, file, profile));+}++function readOf(asset: ColorOf, file: ReadFile, profile: SourceProfile): ColorRead {+ const color = asset.color;+ if (file === "proxy" || !color) {+ return fixedRead({ profile, ...REC709_LIMITED });+ }+ const own = { matrix: color.matrix, fullRange: color.fullRange };+ const asTagged: RecipeInput = { profile, ...own, drawnMatrix: own.matrix, drawnFullRange: own.fullRange };+ if (profile === "rec709" || profile === "srgb") return fixedRead(asTagged);+ const route = routeOf(asset);+ let measured: RecipeInput | null = null;+ const drawn = (path: ReturnType<typeof decodePathNow>): RecipeInput => {+ if (measured) return measured;+ if (!path) return asTagged;+ measured =+ path.kind === "code" ? { profile, ...own, drawnMatrix: path.drawnMatrix, drawnFullRange: path.drawnFullRange } : asTagged;+ return measured;+ };+ return {+ colorSpace: decodeOverrideFor(route, own.fullRange),+ recipe: () => measured ?? drawn(decodePathNow(route, own.fullRange)),+ settled: () => decodePath(route, own.fullRange).then(drawn),+ };+}++/** Whether two color records read the same picture from the same file: the+ * same sink tag and the same recipe. Both go through the same route at the+ * same range whenever the tags match, so the drawn matrix is theirs alike. */+export function sameColorRead(a: ColorOf, b: ColorOf, file: ReadFile): boolean {+ const ra = colorRead(a, file);+ const rb = colorRead(b, file);+ if (JSON.stringify(ra.colorSpace) !== JSON.stringify(rb.colorSpace)) return false;+ const x = ra.recipe();+ const y = rb.recipe();+ return (+ x.profile === y.profile &&+ x.matrix === y.matrix &&+ x.fullRange === y.fullRange &&+ x.drawnMatrix === y.drawnMatrix &&+ x.drawnFullRange === y.drawnFullRange+ );+}diff --git a/site/src/cut/lib/sourceExportPlan.test.ts b/site/src/cut/lib/sourceExportPlan.test.tsindex 9a81e5af..9b0b31d2 100644--- a/site/src/cut/lib/sourceExportPlan.test.ts+++ b/site/src/cut/lib/sourceExportPlan.test.ts@@ -5,7 +5,8 @@ import type { ExportDoc } from "@/cut/lib/renderSnapshot";import type { VideoClip } from "@/cut/lib/types";const doc: ExportDoc = {- aspect: "16:9", assets: [{ id: "source", fileName: "source.mp4", name: "Source", type: "video", duration: 904, width: 320, height: 240, url: "" }],+ aspect: "16:9", assets: [{ id: "source", fileName: "source.mp4", name: "Source", type: "video", duration: 904, width: 320, height: 240, url: "",+ color: { matrix: "bt709", fullRange: false, bitDepth: 8, detected: "rec709" } }],clips: [{ id: "clip", assetId: "source", track: 0, start: 0, in: 15.137, out: 870.437, muted: false }],audioClips: [], overlays: [], subtitles: { cues: [], showOnVideo: false, showOnTimeline: false },};@@ -55,3 +56,19 @@ test("whole files, contiguous splits and reordered sequences produce source planexpect(sourceExportPlan(sequence, settings)).toEqual([{ file: "source.mp4", from: 4, to: 8 }, { file: "source.mp4", from: 0, to: 2 }]);expect(sourceExportPlan(sequence, { ...settings, range: { start: 2, end: 5 } })).toEqual([{ file: "source.mp4", from: 6, to: 8 }, { file: "source.mp4", from: 0, to: 1 }]);});++test("a source whose code values need converting renders; a Rec.709 override copies again", () => {+ const log = { ...doc.assets[0], color: { matrix: "bt2020nc" as const, fullRange: false, bitDepth: 10, detected: "apple-log" as const } };+ expect(sourceSequence({ ...doc, assets: [log] })).toBeNull();+ expect(sourceSequence({ ...doc, assets: [{ ...log, colorProfile: "rec709" as const }] })).not.toBeNull();+ expect(sourceSequence({ ...doc, assets: [{ ...log, color: { ...log.color, detected: "hlg" as const } }] })).toBeNull();+});++test("an HLG file copies into an HLG delivery and renders into a PQ or SDR one", () => {+ const hlg = { ...doc.assets[0], color: { matrix: "bt2020nc" as const, fullRange: false, bitDepth: 10, detected: "hlg" as const } };+ expect(sourceSequence({ ...doc, assets: [hlg], colorSpace: "hlg" })).not.toBeNull();+ expect(sourceSequence({ ...doc, assets: [hlg], colorSpace: "pq" })).toBeNull();+ expect(sourceSequence({ ...doc, assets: [hlg] })).toBeNull();+ // A Rec.709 file into an HDR delivery is a conversion, so it renders.+ expect(sourceSequence({ ...doc, colorSpace: "hlg" })).toBeNull();+});diff --git a/site/src/cut/lib/sourceExportPlan.ts b/site/src/cut/lib/sourceExportPlan.tsindex 164b7933..cb48699b 100644--- a/site/src/cut/lib/sourceExportPlan.ts+++ b/site/src/cut/lib/sourceExportPlan.ts@@ -1,3 +1,4 @@+import { recipeIsIdentity } from "@donkeycut/effects-kit";import type { ExportDoc } from "@/cut/lib/renderSnapshot";import type { ExportSettings } from "@/cut/lib/exportClient";import type { VideoClip } from "@/cut/lib/types";@@ -26,6 +27,11 @@ export function sourceSequence(doc: ExportDoc) {const asset = doc.assets.find((a) => a.id === clip.assetId);if (!asset || asset.type !== "video" || asset.block || !asset.width || !asset.height ||!Number.isFinite(clip.in) || !Number.isFinite(clip.out) || clip.in < 0 || clip.out <= clip.in || clip.out > asset.duration + 0.000001) return null;+ // A file whose code values need converting (a log source, or an HDR file+ // into another delivery) has to render; an ungraded file already in the+ // delivery's own encoding copies as is.+ const profile = asset.colorProfile ?? asset.color?.detected ?? "rec709";+ if (!recipeIsIdentity(profile, doc.colorSpace ?? "sdr")) return null;if (segments.length && (asset.width !== segments[0].asset.width || asset.height !== segments[0].asset.height)) return null;const previous = segments.at(-1);if (previous?.asset.id === asset.id && Math.abs(previous.to - clip.in) < 0.000001) previous.to = clip.out;diff --git a/site/src/cut/lib/spsColor.test.ts b/site/src/cut/lib/spsColor.test.tsnew file mode 100644index 00000000..9bc75b6f--- /dev/null+++ b/site/src/cut/lib/spsColor.test.ts@@ -0,0 +1,401 @@+import { describe, expect, test } from "bun:test";+import {+ BitWriter,+ NEUTRAL_TAGS,+ SpsColorRewriter,+ descriptionLengthSize,+ escapeRbsp,+ readSpsColor,+ rewriteSpsColor,+ unescapeRbsp,+} from "./spsColor";++// Codec descriptions (avcC / hvcC) read off files the bundled ffmpeg+// encoded, before and after its h264_metadata / hevc_metadata filters set+// colour_primaries=1, transfer_characteristics=13, matrix_coefficients=1,+// video_full_range_flag=0. `iphoneHevc` is a 1080p HEVC phone recording.+const DESC = {+ h264hlg: "AU0AC//hABAnTQALq0GG8CDCM1CRIJAgAQAEKO48gA==",+ h264hlgRewritten: "AU0AC//hABAnTQALq0GG8CDCM1AQ0BAgAQAEKO48gA==",+ h264709: "AU0AC//hABAnTQALq0GG8CDCM1AQEBAgAQAEKO48gA==",+ h264709Rewritten: "AU0AC//hABAnTQALq0GG8CDCM1AQ0BAgAQAEKO48gA==",+ hevc10hlg: "AQIgAAAAsAAAAAAAHvAA/P36+gAADwOgAAEAGEABDAH//wIgAAADALAAAAMAAAMAHhcCQKEAAQAqQgEBAiAAAAMAsAAAAwAAAwAeoBQgQcGO2IF7kWRS/8ufxP6wFqEiQSAQogABAAdEAcBy9FNk",+ hevc10hlgRewritten: "AQIgAAAAsAAAAAAAHvAA/P36+gAADwOgAAEAGEABDAH//wIgAAADALAAAAMAAAMAHhcCQKEAAQAqQgEBAiAAAAMAsAAAAwAAAwAeoBQgQcGO2IF7kWRS/8ufxP6wFqAhoCAQogABAAdEAcBy9FNk",+ iphonehevc: "AQFgAAAAsAAAAAAAePAA/P34+AAACwOgAAEAGEABDAH//wFgAAADALAAAAMAAAMAeBXAkKEAAQAkQgEBAWAAAAMAsAAAAwAAAwB4oAPAgBEHy4gV7kWVTUBAQEAgogABAAdEAcAsvBTJ",+ iphonehevcRewritten: "AQFgAAAAsAAAAAAAePAA/P34+AAADwOgAAEAGEABDAH//wFgAAADALAAAAMAAAMAeBXAkKEAAQAkQgEBAWAAAAMAsAAAAwAAAwB4oAPAgBEHy4gV7kWVTUBDQEAgogABAAdEAcAsvBTJ",+};++const b64 = (s: string) => Uint8Array.from(atob(s), (c) => c.charCodeAt(0));+const hex = (b: Uint8Array) => Array.from(b, (x) => x.toString(16).padStart(2, "0")).join("");++const NEUTRAL = NEUTRAL_TAGS(false);++describe("spsColor against ffmpeg's metadata filters", () => {+ test("H.264 avcC tagged bt2020/HLG comes out byte-identical to h264_metadata", () => {+ const rw = new SpsColorRewriter("avc", NEUTRAL);+ expect(hex(rw.description(b64(DESC.h264hlg)))).toBe(hex(b64(DESC.h264hlgRewritten)));+ });+ test("H.264 avcC already Rec.709 only changes the transfer", () => {+ const rw = new SpsColorRewriter("avc", NEUTRAL);+ expect(hex(rw.description(b64(DESC.h264709)))).toBe(hex(b64(DESC.h264709Rewritten)));+ });+ test("HEVC Main10 hvcC tagged bt2020/HLG comes out byte-identical to hevc_metadata", () => {+ const rw = new SpsColorRewriter("hevc", NEUTRAL);+ expect(hex(rw.description(b64(DESC.hevc10hlg)))).toBe(hex(b64(DESC.hevc10hlgRewritten)));+ });+ test("a phone's HEVC hvcC comes out with the same parameter sets as hevc_metadata", () => {+ const rw = new SpsColorRewriter("hevc", NEUTRAL);+ const made = rw.description(b64(DESC.iphonehevc));+ const ffmpeg = b64(DESC.iphonehevcRewritten);+ // ffmpeg rebuilds the hvcC header from the SPS and flips+ // temporalIdNested (byte 21) on this file; the rewriter keeps the header.+ expect(hex(made.subarray(22))).toBe(hex(ffmpeg.subarray(22)));+ expect(hex(made.subarray(0, 21))).toBe(hex(ffmpeg.subarray(0, 21)));+ expect(made[21] & 3).toBe(ffmpeg[21] & 3);+ });+ test("descriptions declare their NAL length size", () => {+ expect(descriptionLengthSize("avc", b64(DESC.h264hlg))).toBe(4);+ expect(descriptionLengthSize("hevc", b64(DESC.iphonehevc))).toBe(4);+ });+});++/** Every SPS NAL inside a description, for the in-band sample tests. */+function spsOf(codec: "avc" | "hevc", desc: Uint8Array): Uint8Array[] {+ const out: Uint8Array[] = [];+ if (codec === "avc") {+ let at = 6;+ for (let i = 0; i < (desc[5] & 0x1f); i++) {+ const len = (desc[at] << 8) | desc[at + 1];+ out.push(desc.subarray(at + 2, at + 2 + len));+ at += 2 + len;+ }+ } else {+ let at = 23;+ for (let a = 0; a < desc[22]; a++) {+ const type = desc[at] & 0x3f;+ const count = (desc[at + 1] << 8) | desc[at + 2];+ at += 3;+ for (let i = 0; i < count; i++) {+ const len = (desc[at] << 8) | desc[at + 1];+ if (type === 33) out.push(desc.subarray(at + 2, at + 2 + len));+ at += 2 + len;+ }+ }+ }+ return out;+}++const withLength = (nal: Uint8Array) =>+ new Uint8Array([nal.length >>> 24, (nal.length >>> 16) & 255, (nal.length >>> 8) & 255, nal.length & 255, ...nal]);++describe("in-band parameter sets", () => {+ test("a sample carrying an SPS has it rewritten and its length fixed; the rest is untouched", () => {+ const desc = b64(DESC.hevc10hlg);+ const [sps] = spsOf("hevc", desc);+ const rw = new SpsColorRewriter("hevc", NEUTRAL);+ const slice = new Uint8Array([0x26, 0x01, 0xaf, 0x00, 0x00, 0x03, 0x01, 0x42]); // IDR-ish payload+ const sample = new Uint8Array([...withLength(sps), ...withLength(slice)]);+ const made = rw.sample(sample, 4);+ expect(made).not.toBeNull();+ const expectedSps = rewriteSpsColor("hevc", sps, NEUTRAL);+ expect(hex(made!)).toBe(hex(new Uint8Array([...withLength(expectedSps), ...withLength(slice)])));+ expect(readSpsColor("hevc", expectedSps)).toMatchObject({ primaries: 1, transfer: 13, matrix: 1, fullRange: false });+ });+ test("a sample without an SPS is left alone (null)", () => {+ const rw = new SpsColorRewriter("avc", NEUTRAL);+ const slice = new Uint8Array([0x65, 0x88, 0x84, 0x00, 0x21]);+ expect(rw.sample(withLength(slice), 4)).toBeNull();+ });+ test("the same SPS bytes rewrite once", () => {+ const desc = b64(DESC.h264hlg);+ const [sps] = spsOf("avc", desc);+ const rw = new SpsColorRewriter("avc", NEUTRAL);+ expect(rw.sps(sps)).toBe(rw.sps(new Uint8Array(sps)));+ });+});++/** An H.264 SPS RBSP with the given shape, written field by field. */+function avcSps(opts: {+ profile: number;+ scaling?: boolean;+ pocType?: number;+ vui?: null | { aspect255?: boolean; signal?: { full: boolean; described: boolean } };+}): Uint8Array {+ const w = new BitWriter();+ w.u(opts.profile, 8);+ w.u(0, 8);+ w.u(40, 8);+ w.ue(0);+ if ([100, 110, 122, 244].includes(opts.profile)) {+ w.ue(1); // chroma 4:2:0+ w.ue(2); // bit depth luma 10+ w.ue(2);+ w.u(0, 1);+ w.u(opts.scaling ? 1 : 0, 1);+ if (opts.scaling) {+ for (let i = 0; i < 8; i++) {+ w.u(1, 1);+ // a list that ends early through a zero next scale+ w.se(-8);+ }+ }+ }+ w.ue(4);+ w.ue(opts.pocType ?? 0);+ if ((opts.pocType ?? 0) === 0) w.ue(4);+ else if (opts.pocType === 1) {+ w.u(0, 1);+ w.se(-3);+ w.se(2);+ w.ue(2);+ w.se(1);+ w.se(-1);+ }+ w.ue(2);+ w.u(0, 1);+ w.ue(119);+ w.ue(67);+ w.u(1, 1);+ w.u(1, 1);+ w.u(1, 1); // cropping+ w.ue(0);+ w.ue(0);+ w.ue(0);+ w.ue(4);+ if (opts.vui === null) {+ w.u(0, 1);+ } else {+ w.u(1, 1);+ const vui = opts.vui ?? {};+ if (vui.aspect255) {+ w.u(1, 1);+ w.u(255, 8);+ w.u(1, 16);+ w.u(1, 16);+ } else w.u(0, 1);+ w.u(1, 1);+ w.u(1, 1); // overscan appropriate+ if (vui.signal) {+ w.u(1, 1);+ w.u(5, 3);+ w.u(vui.signal.full ? 1 : 0, 1);+ w.u(vui.signal.described ? 1 : 0, 1);+ if (vui.signal.described) {+ w.u(9, 8);+ w.u(18, 8);+ w.u(9, 8);+ }+ } else w.u(0, 1);+ w.u(0, 1); // chroma loc+ w.u(1, 1); // timing info+ w.u(1001, 32);+ w.u(60000, 32);+ w.u(1, 1);+ w.u(0, 1);+ w.u(0, 1);+ w.u(0, 1);+ w.u(1, 1); // bitstream restriction+ w.u(1, 1);+ w.ue(0);+ w.ue(0);+ w.ue(16);+ w.ue(16);+ w.ue(4);+ w.ue(4);+ }+ w.trailing();+ return new Uint8Array([0x67, ...escapeRbsp(w.toBytes())]);+}++/** Bits after the video signal block, as a string, for comparing tails. */+function tailBits(codec: "avc" | "hevc", nal: Uint8Array): string {+ const rbsp = unescapeRbsp(nal.subarray(codec === "avc" ? 1 : 2));+ const bits = Array.from(rbsp, (b) => b.toString(2).padStart(8, "0")).join("");+ // Everything from the colour block on is 27 bits of tags; the tail is what+ // follows them. Locating it requires the parse, so the test compares the+ // last 40 bits before the stop bit, which sit in the tail in every shape.+ const stop = bits.lastIndexOf("1");+ return bits.slice(Math.max(0, stop - 40), stop);+}++describe("SPS shapes", () => {+ const shapes: [string, Uint8Array][] = [+ ["baseline, VUI with signal", avcSps({ profile: 66, vui: { signal: { full: true, described: true } } })],+ ["high 10 with scaling lists, poc type 1", avcSps({ profile: 110, scaling: true, pocType: 1, vui: { aspect255: true, signal: { full: false, described: false } } })],+ ["high, VUI without signal block", avcSps({ profile: 100, vui: {} })],+ ["main, no VUI at all", avcSps({ profile: 77, vui: null })],+ ];+ for (const [name, nal] of shapes) {+ test(`H.264 ${name}`, () => {+ const before = readSpsColor("avc", nal);+ const made = rewriteSpsColor("avc", nal, { primaries: 1, transfer: 13, matrix: 1, fullRange: before?.fullRange ?? false });+ expect(readSpsColor("avc", made)).toEqual({+ videoFormat: before?.videoFormat ?? 5,+ primaries: 1,+ transfer: 13,+ matrix: 1,+ fullRange: before?.fullRange ?? false,+ });+ if (name !== "main, no VUI at all") expect(tailBits("avc", made)).toBe(tailBits("avc", nal));+ // Idempotent: rewriting the result changes nothing.+ expect(hex(rewriteSpsColor("avc", made, { primaries: 1, transfer: 13, matrix: 1, fullRange: before?.fullRange ?? false }))).toBe(hex(made));+ });+ }+ test("H.264 rewrite inserts emulation prevention where the new bytes need it", () => {+ const nal = avcSps({ profile: 66, vui: { signal: { full: false, described: true } } });+ const made = rewriteSpsColor("avc", nal, { primaries: 0, transfer: 0, matrix: 1, fullRange: false });+ expect(readSpsColor("avc", made)).toMatchObject({ primaries: 0, transfer: 0, matrix: 1 });+ // No 00 00 {00,01,02} run survives in the payload, and an escape byte+ // is never followed by a byte that would need another one.+ const p = made.subarray(1);+ for (let i = 2; i < p.length; i++) {+ expect(p[i - 2] === 0 && p[i - 1] === 0 && p[i] <= 2).toBe(false);+ if (p[i - 2] === 0 && p[i - 1] === 0 && p[i] === 3 && i + 1 < p.length) expect(p[i + 1] <= 3).toBe(true);+ }+ });+});++/** An HEVC SPS RBSP with sub-layers, scaling lists, inter-predicted+ * reference sets and long-term pictures — the shape phone encoders write. */+function hevcSps(opts: { subLayers: number; scaling: boolean; vui: boolean }): Uint8Array {+ const w = new BitWriter();+ w.u(0, 4);+ w.u(opts.subLayers, 3);+ w.u(1, 1);+ w.u(0, 2);+ w.u(0, 1);+ w.u(1, 5);+ w.u(0x60000000, 32);+ w.u(0, 48);+ w.u(120, 8);+ for (let i = 0; i < opts.subLayers; i++) {+ w.u(1, 1);+ w.u(1, 1);+ }+ if (opts.subLayers > 0) for (let i = opts.subLayers; i < 8; i++) w.u(0, 2);+ for (let i = 0; i < opts.subLayers; i++) {+ w.u(0, 88);+ w.u(90, 8);+ }+ w.ue(0);+ w.ue(1);+ w.ue(1920);+ w.ue(1080);+ w.u(1, 1);+ w.ue(0);+ w.ue(0);+ w.ue(0);+ w.ue(4);+ w.ue(0);+ w.ue(0);+ w.ue(4); // log2_max_poc_lsb_minus4 → 8 bits+ w.u(1, 1);+ for (let i = 0; i <= opts.subLayers; i++) {+ w.ue(4);+ w.ue(2);+ w.ue(0);+ }+ w.ue(0);+ w.ue(3);+ w.ue(0);+ w.ue(3);+ w.ue(1);+ w.ue(1);+ w.u(opts.scaling ? 1 : 0, 1);+ if (opts.scaling) {+ w.u(1, 1);+ for (let sizeId = 0; sizeId < 4; sizeId++) {+ for (let matrixId = 0; matrixId < 6; matrixId += sizeId === 3 ? 3 : 1) {+ if (matrixId % 2) {+ w.u(0, 1);+ w.ue(0);+ continue;+ }+ w.u(1, 1);+ const coefNum = Math.min(64, 1 << (4 + (sizeId << 1)));+ if (sizeId > 1) w.se(2);+ for (let i = 0; i < coefNum; i++) w.se(i % 3 === 0 ? 1 : -1);+ }+ }+ }+ w.u(1, 1);+ w.u(1, 1);+ w.u(1, 1); // pcm+ w.u(7, 4);+ w.u(7, 4);+ w.ue(0);+ w.ue(2);+ w.u(1, 1);+ // three short-term sets: explicit, explicit, inter-predicted from the second+ w.ue(3);+ w.ue(2); // set 0: two negative, one positive+ w.ue(1);+ w.ue(0);+ w.u(1, 1);+ w.ue(1);+ w.u(1, 1);+ w.ue(0);+ w.u(1, 1);+ w.u(0, 1); // set 1: explicit, one negative+ w.ue(1);+ w.ue(0);+ w.ue(3);+ w.u(1, 1);+ w.u(1, 1); // set 2: inter from set 1 (delta idx 1), deltaRps = -2+ w.u(1, 1);+ w.ue(1);+ w.u(1, 1); // used j=0+ w.u(0, 1); // not used j=1 → use_delta_flag+ w.u(1, 1);+ w.u(1, 1); // long-term+ w.ue(2);+ w.u(17, 8);+ w.u(1, 1);+ w.u(33, 8);+ w.u(0, 1);+ w.u(1, 1);+ w.u(1, 1);+ w.u(opts.vui ? 1 : 0, 1);+ if (opts.vui) {+ w.u(1, 1);+ w.u(1, 8);+ w.u(0, 1);+ w.u(1, 1); // signal+ w.u(5, 3);+ w.u(0, 1);+ w.u(1, 1);+ w.u(9, 8);+ w.u(18, 8);+ w.u(9, 8);+ w.u(0, 1); // chroma loc+ w.u(0, 1);+ w.u(0, 1);+ w.u(0, 1);+ w.u(0, 1); // default display window+ w.u(1, 1); // timing+ w.u(1001, 32);+ w.u(60000, 32);+ w.u(0, 1);+ w.u(0, 1);+ w.u(0, 1); // bitstream restriction+ }+ w.u(0, 1); // sps_extension_present_flag+ w.trailing();+ return new Uint8Array([0x42, 0x01, ...escapeRbsp(w.toBytes())]);+}++describe("HEVC SPS shapes", () => {+ for (const [name, nal] of [+ ["two sub-layers, scaling lists, inter RPS, long-term, VUI", hevcSps({ subLayers: 2, scaling: true, vui: true })],+ ["no sub-layers, no scaling, VUI", hevcSps({ subLayers: 0, scaling: false, vui: true })],+ ["no VUI", hevcSps({ subLayers: 1, scaling: true, vui: false })],+ ] as [string, Uint8Array][]) {+ test(name, () => {+ const before = readSpsColor("hevc", nal);+ const made = rewriteSpsColor("hevc", nal, NEUTRAL);+ expect(readSpsColor("hevc", made)).toEqual({ videoFormat: 5, primaries: 1, transfer: 13, matrix: 1, fullRange: false });+ if (before) expect(tailBits("hevc", made)).toBe(tailBits("hevc", nal));+ expect(hex(rewriteSpsColor("hevc", made, NEUTRAL))).toBe(hex(made));+ });+ }+});diff --git a/site/src/cut/lib/spsColor.ts b/site/src/cut/lib/spsColor.tsnew file mode 100644index 00000000..c822067a--- /dev/null+++ b/site/src/cut/lib/spsColor.ts@@ -0,0 +1,577 @@+/**+ * Rewriting the color tags an H.264 / HEVC bitstream carries.+ *+ * A hardware decoder reads the picture's color from the sequence parameter+ * set's VUI, and a browser converts the decoded frame by those tags before+ * anything can draw it: an HLG file is tone-mapped, a wide-gamut one is gamut+ * mapped. The decoder config's `colorSpace` does not override them. So when+ * the preview needs code values untouched, the tags in the bitstream are+ * rewritten to Rec.709 / sRGB before the decoder sees them — the same+ * operation ffmpeg's `h264_metadata` / `hevc_metadata` filters perform — and+ * the grade pipeline applies the file's real meaning from the asset's+ * `color`.+ *+ * The rewrite parses the SPS up to the VUI, replaces (or inserts) the video+ * signal fields, and copies every bit after them unchanged, so the parameter+ * set stays exactly what the encoder wrote apart from the three tags and the+ * range flag. It runs on the codec description (avcC / hvcC) once per+ * decoder, and on in-band parameter sets when a sample carries them, cached+ * by their bytes so a repeated SPS costs one lookup.+ */++export interface SpsColorTags {+ /** colour_primaries, H.273 code. */+ primaries: number;+ /** transfer_characteristics, H.273 code. */+ transfer: number;+ /** matrix_coefficients, H.273 code. */+ matrix: number;+ fullRange: boolean;+}++/** Rec.709 primaries, sRGB transfer, Rec.709 matrix: the tags a browser+ * draws without converting. */+export const NEUTRAL_TAGS = (fullRange: boolean): SpsColorTags => ({+ primaries: 1,+ transfer: 13,+ matrix: 1,+ fullRange,+});++export type SpsCodec = "avc" | "hevc";++const PRIMARIES_CODE: Record<string, number> = { bt709: 1, bt470bg: 5, smpte170m: 6, bt2020: 9 };+const TRANSFER_CODE: Record<string, number> = { bt709: 1, smpte170m: 6, linear: 8, "iec61966-2-1": 13, pq: 16, hlg: 18 };+const MATRIX_CODE: Record<string, number> = { rgb: 0, bt709: 1, bt470bg: 5, smpte170m: 6, "bt2020-ncl": 9 };++/** The VUI codes a WebCodecs color space init spells; a field it leaves out+ * stays unspecified (2), the code a decoder reads as "no information". */+export function tagsOfColorSpace(cs: VideoColorSpaceInit): SpsColorTags {+ return {+ primaries: (cs.primaries && PRIMARIES_CODE[cs.primaries]) ?? 2,+ transfer: (cs.transfer && TRANSFER_CODE[cs.transfer]) ?? 2,+ matrix: (cs.matrix && MATRIX_CODE[cs.matrix]) ?? 2,+ fullRange: cs.fullRange ?? false,+ };+}++/** The rewriter's codec for a WebCodecs codec string; null for a codec whose+ * color tags live outside an SPS. */+export function spsCodecOf(codec: string): SpsCodec | null {+ if (codec.startsWith("avc1") || codec.startsWith("avc3")) return "avc";+ if (codec.startsWith("hev1") || codec.startsWith("hvc1")) return "hevc";+ return null;+}++/* ------------------------------------------------------------------ */+/* Bits */+/* ------------------------------------------------------------------ */++export class BitReader {+ pos = 0;+ constructor(private readonly bytes: Uint8Array) {}+ get length(): number {+ return this.bytes.length * 8;+ }+ bit(): number {+ if (this.pos >= this.length) throw new RangeError("SPS ended early.");+ const b = (this.bytes[this.pos >> 3] >> (7 - (this.pos & 7))) & 1;+ this.pos++;+ return b;+ }+ u(n: number): number {+ let v = 0;+ for (let i = 0; i < n; i++) v = v * 2 + this.bit();+ return v;+ }+ ue(): number {+ let zeros = 0;+ while (this.bit() === 0) {+ if (++zeros > 32) throw new RangeError("Bad Exp-Golomb code.");+ }+ return zeros === 0 ? 0 : (1 << zeros) - 1 + this.u(zeros);+ }+ se(): number {+ const k = this.ue();+ return k & 1 ? (k + 1) / 2 : -(k / 2);+ }+ skip(n: number): void {+ this.pos += n;+ if (this.pos > this.length) throw new RangeError("SPS ended early.");+ }+}++export class BitWriter {+ private bits: number[] = [];+ u(value: number, n: number): void {+ for (let i = n - 1; i >= 0; i--) this.bits.push(Math.floor(value / 2 ** i) & 1);+ }+ ue(value: number): void {+ const v = value + 1;+ const len = 32 - Math.clz32(v);+ this.u(0, len - 1);+ this.u(v, len);+ }+ se(value: number): void {+ this.ue(value > 0 ? 2 * value - 1 : -2 * value);+ }+ /** Append bits [from, to) of `bytes`. */+ copy(bytes: Uint8Array, from: number, to: number): void {+ for (let p = from; p < to; p++) this.bits.push((bytes[p >> 3] >> (7 - (p & 7))) & 1);+ }+ /** RBSP trailing bits: a stop bit and zeros to the byte. */+ trailing(): void {+ this.bits.push(1);+ while (this.bits.length & 7) this.bits.push(0);+ }+ get length(): number {+ return this.bits.length;+ }+ toBytes(): Uint8Array {+ const out = new Uint8Array(Math.ceil(this.bits.length / 8));+ for (let i = 0; i < this.bits.length; i++) if (this.bits[i]) out[i >> 3] |= 0x80 >> (i & 7);+ return out;+ }+}++/** The bit index of the RBSP stop bit: the last 1 in the payload. */+function stopBit(rbsp: Uint8Array): number {+ for (let i = rbsp.length - 1; i >= 0; i--) {+ const b = rbsp[i];+ if (b === 0) continue;+ for (let k = 0; k < 8; k++) if ((b >> k) & 1) return i * 8 + (7 - k);+ }+ throw new RangeError("No RBSP stop bit.");+}++/** Remove emulation prevention bytes from a NAL payload. */+export function unescapeRbsp(payload: Uint8Array): Uint8Array {+ const out: number[] = [];+ let zeros = 0;+ for (let i = 0; i < payload.length; i++) {+ const b = payload[i];+ if (zeros >= 2 && b === 3) {+ zeros = 0;+ continue;+ }+ out.push(b);+ zeros = b === 0 ? zeros + 1 : 0;+ }+ return Uint8Array.from(out);+}++/** Insert emulation prevention bytes so no 00 00 0x (x ≤ 3) sequence+ * appears in the payload. */+export function escapeRbsp(rbsp: Uint8Array): Uint8Array {+ const out: number[] = [];+ let zeros = 0;+ for (let i = 0; i < rbsp.length; i++) {+ const b = rbsp[i];+ if (zeros >= 2 && b <= 3) {+ out.push(3);+ zeros = 0;+ }+ out.push(b);+ zeros = b === 0 ? zeros + 1 : 0;+ }+ return Uint8Array.from(out);+}++/* ------------------------------------------------------------------ */+/* Parsing to the VUI */+/* ------------------------------------------------------------------ */++/** Where the video signal fields sit in an SPS RBSP, in bits. */+interface VuiSpot {+ /** vui_parameters_present_flag. */+ vuiFlag: number;+ vuiPresent: boolean;+ /** video_signal_type_present_flag, when the VUI is present. */+ signal: number;+ /** First bit after the video signal block (or after the flag when 0). */+ resume: number;+ /** The tags the SPS carries, when it carries them. */+ tags: (SpsColorTags & { videoFormat: number }) | null;+}++const AVC_HIGH_PROFILES = new Set([100, 110, 122, 244, 44, 83, 86, 118, 128, 138, 139, 134, 135]);++function readAvcScalingList(r: BitReader, size: number): void {+ let last = 8;+ let next = 8;+ for (let j = 0; j < size; j++) {+ if (next !== 0) {+ const delta = r.se();+ next = (last + delta + 256) % 256;+ }+ last = next === 0 ? last : next;+ }+}++function readVideoSignal(r: BitReader): VuiSpot["tags"] {+ const videoFormat = r.u(3);+ const fullRange = r.bit() === 1;+ const described = r.bit() === 1;+ if (!described) return { videoFormat, fullRange, primaries: 2, transfer: 2, matrix: 2 };+ return { videoFormat, fullRange, primaries: r.u(8), transfer: r.u(8), matrix: r.u(8) };+}++/** Aspect ratio and overscan, then the signal block: shared by both VUIs. */+function readVuiHead(r: BitReader, vuiFlag: number, vuiPresent: boolean): VuiSpot {+ if (!vuiPresent) return { vuiFlag, vuiPresent, signal: -1, resume: vuiFlag + 1, tags: null };+ if (r.bit()) {+ const idc = r.u(8);+ if (idc === 255) r.skip(32);+ }+ if (r.bit()) r.skip(1);+ const signal = r.pos;+ const present = r.bit() === 1;+ const tags = present ? readVideoSignal(r) : null;+ return { vuiFlag, vuiPresent, signal, resume: r.pos, tags };+}++function locateAvcVui(rbsp: Uint8Array): VuiSpot {+ const r = new BitReader(rbsp);+ const profile = r.u(8);+ r.skip(16); // constraint flags, level+ r.ue(); // sps id+ let chroma = 1;+ if (AVC_HIGH_PROFILES.has(profile)) {+ chroma = r.ue();+ if (chroma === 3) r.skip(1);+ r.ue();+ r.ue();+ r.skip(1);+ if (r.bit()) {+ const lists = chroma !== 3 ? 8 : 12;+ for (let i = 0; i < lists; i++) if (r.bit()) readAvcScalingList(r, i < 6 ? 16 : 64);+ }+ }+ r.ue(); // log2_max_frame_num_minus4+ const pocType = r.ue();+ if (pocType === 0) r.ue();+ else if (pocType === 1) {+ r.skip(1);+ r.se();+ r.se();+ const n = r.ue();+ for (let i = 0; i < n; i++) r.se();+ }+ r.ue(); // max_num_ref_frames+ r.skip(1);+ r.ue();+ r.ue();+ if (!r.bit()) r.skip(1); // frame_mbs_only_flag → mb_adaptive_frame_field_flag+ r.skip(1); // direct_8x8_inference_flag+ if (r.bit()) for (let i = 0; i < 4; i++) r.ue(); // cropping+ const vuiFlag = r.pos;+ const vuiPresent = r.bit() === 1;+ return readVuiHead(r, vuiFlag, vuiPresent);+}++interface RefPicSet {+ s0: number[];+ s1: number[];+}++function readStRefPicSet(r: BitReader, idx: number, count: number, sets: RefPicSet[]): RefPicSet {+ const inter = idx !== 0 && r.bit() === 1;+ if (inter) {+ const deltaIdx = idx === count ? r.ue() + 1 : 1;+ const sign = r.bit();+ const deltaRps = (1 - 2 * sign) * (r.ue() + 1);+ const ref = sets[idx - deltaIdx];+ const numDelta = ref.s0.length + ref.s1.length;+ const useDelta: boolean[] = [];+ for (let j = 0; j <= numDelta; j++) {+ const used = r.bit() === 1;+ useDelta.push(used ? true : r.bit() === 1);+ }+ const s0: number[] = [];+ const s1: number[] = [];+ for (let j = ref.s1.length - 1; j >= 0; j--) {+ const d = ref.s1[j] + deltaRps;+ if (d < 0 && useDelta[ref.s0.length + j]) s0.push(d);+ }+ if (deltaRps < 0 && useDelta[numDelta]) s0.push(deltaRps);+ for (let j = 0; j < ref.s0.length; j++) {+ const d = ref.s0[j] + deltaRps;+ if (d < 0 && useDelta[j]) s0.push(d);+ }+ for (let j = ref.s0.length - 1; j >= 0; j--) {+ const d = ref.s0[j] + deltaRps;+ if (d > 0 && useDelta[j]) s1.push(d);+ }+ if (deltaRps > 0 && useDelta[numDelta]) s1.push(deltaRps);+ for (let j = 0; j < ref.s1.length; j++) {+ const d = ref.s1[j] + deltaRps;+ if (d > 0 && useDelta[ref.s0.length + j]) s1.push(d);+ }+ return { s0, s1 };+ }+ const numNeg = r.ue();+ const numPos = r.ue();+ const s0: number[] = [];+ const s1: number[] = [];+ let poc = 0;+ for (let j = 0; j < numNeg; j++) {+ poc -= r.ue() + 1;+ r.skip(1);+ s0.push(poc);+ }+ poc = 0;+ for (let j = 0; j < numPos; j++) {+ poc += r.ue() + 1;+ r.skip(1);+ s1.push(poc);+ }+ return { s0, s1 };+}++function readHevcScalingListData(r: BitReader): void {+ for (let sizeId = 0; sizeId < 4; sizeId++) {+ for (let matrixId = 0; matrixId < 6; matrixId += sizeId === 3 ? 3 : 1) {+ if (!r.bit()) {+ r.ue();+ continue;+ }+ let next = 8;+ const coefNum = Math.min(64, 1 << (4 + (sizeId << 1)));+ if (sizeId > 1) next = r.se() + 8;+ for (let i = 0; i < coefNum; i++) next = (next + r.se() + 256) % 256;+ }+ }+}++function locateHevcVui(rbsp: Uint8Array): VuiSpot {+ const r = new BitReader(rbsp);+ r.skip(4); // vps id+ const maxSubLayersMinus1 = r.u(3);+ r.skip(1); // temporal id nesting+ // profile_tier_level+ r.skip(2 + 1 + 5 + 32 + 48 + 8);+ const subProfile: boolean[] = [];+ const subLevel: boolean[] = [];+ for (let i = 0; i < maxSubLayersMinus1; i++) {+ subProfile.push(r.bit() === 1);+ subLevel.push(r.bit() === 1);+ }+ if (maxSubLayersMinus1 > 0) for (let i = maxSubLayersMinus1; i < 8; i++) r.skip(2);+ for (let i = 0; i < maxSubLayersMinus1; i++) {+ if (subProfile[i]) r.skip(88);+ if (subLevel[i]) r.skip(8);+ }+ r.ue(); // sps id+ const chroma = r.ue();+ if (chroma === 3) r.skip(1);+ r.ue();+ r.ue();+ if (r.bit()) for (let i = 0; i < 4; i++) r.ue(); // conformance window+ r.ue();+ r.ue();+ const log2MaxPocLsb = r.ue() + 4;+ const orderingInfo = r.bit() === 1;+ for (let i = orderingInfo ? 0 : maxSubLayersMinus1; i <= maxSubLayersMinus1; i++) {+ r.ue();+ r.ue();+ r.ue();+ }+ for (let i = 0; i < 6; i++) r.ue();+ if (r.bit() && r.bit()) readHevcScalingListData(r);+ r.skip(2); // amp, sao+ if (r.bit()) {+ r.skip(8);+ r.ue();+ r.ue();+ r.skip(1);+ }+ const numSets = r.ue();+ const sets: RefPicSet[] = [];+ for (let i = 0; i < numSets; i++) sets.push(readStRefPicSet(r, i, numSets, sets));+ if (r.bit()) {+ const n = r.ue();+ for (let i = 0; i < n; i++) {+ r.skip(log2MaxPocLsb);+ r.skip(1);+ }+ }+ r.skip(2); // temporal mvp, strong intra smoothing+ const vuiFlag = r.pos;+ const vuiPresent = r.bit() === 1;+ return readVuiHead(r, vuiFlag, vuiPresent);+}++/* ------------------------------------------------------------------ */+/* Rewriting */+/* ------------------------------------------------------------------ */++const HEADER_BYTES: Record<SpsCodec, number> = { avc: 1, hevc: 2 };++/** The color tags an SPS NAL (header included) carries, or null when its+ * VUI has no video signal block. */+export function readSpsColor(codec: SpsCodec, nal: Uint8Array): (SpsColorTags & { videoFormat: number }) | null {+ const rbsp = unescapeRbsp(nal.subarray(HEADER_BYTES[codec]));+ const spot = codec === "avc" ? locateAvcVui(rbsp) : locateHevcVui(rbsp);+ return spot.tags;+}++/** The same SPS NAL carrying `tags`. The header, every field before the+ * video signal block and every bit after it are kept as they were. */+export function rewriteSpsColor(codec: SpsCodec, nal: Uint8Array, tags: SpsColorTags): Uint8Array {+ const header = HEADER_BYTES[codec];+ const rbsp = unescapeRbsp(nal.subarray(header));+ const spot = codec === "avc" ? locateAvcVui(rbsp) : locateHevcVui(rbsp);+ const stop = stopBit(rbsp);+ const w = new BitWriter();+ if (spot.vuiPresent) {+ w.copy(rbsp, 0, spot.signal);+ } else {+ w.copy(rbsp, 0, spot.vuiFlag);+ w.u(1, 1); // vui_parameters_present_flag+ w.u(0, 1); // aspect_ratio_info_present_flag+ w.u(0, 1); // overscan_info_present_flag+ }+ w.u(1, 1); // video_signal_type_present_flag+ w.u(spot.tags?.videoFormat ?? 5, 3);+ w.u(tags.fullRange ? 1 : 0, 1);+ w.u(1, 1); // colour_description_present_flag+ w.u(tags.primaries, 8);+ w.u(tags.transfer, 8);+ w.u(tags.matrix, 8);+ if (!spot.vuiPresent) {+ w.u(0, 1); // chroma_loc_info_present_flag+ if (codec === "avc") {+ // timing, nal hrd, vcl hrd, pic_struct, bitstream restriction+ w.u(0, 5);+ } else {+ // neutral chroma, field seq, frame field info, default display+ // window, timing, bitstream restriction+ w.u(0, 6);+ }+ }+ w.copy(rbsp, spot.resume, stop);+ w.trailing();+ const payload = escapeRbsp(w.toBytes());+ const result = new Uint8Array(header + payload.length);+ result.set(nal.subarray(0, header), 0);+ result.set(payload, header);+ return result;+}++const nalType = (codec: SpsCodec, nal: Uint8Array): number =>+ codec === "avc" ? nal[0] & 0x1f : (nal[0] >> 1) & 0x3f;+const SPS_TYPE: Record<SpsCodec, number> = { avc: 7, hevc: 33 };++/** Rewrites parameter sets once per distinct SPS: the same bytes come back+ * from the cache. One per decoder, so a stream's handful of SPS live here. */+export class SpsColorRewriter {+ private readonly cache = new Map<string, Uint8Array>();+ constructor(+ readonly codec: SpsCodec,+ readonly tags: SpsColorTags+ ) {}++ sps(nal: Uint8Array): Uint8Array {+ let key = "";+ for (let i = 0; i < nal.length; i++) key += String.fromCharCode(nal[i]);+ const hit = this.cache.get(key);+ if (hit) return hit;+ const made = rewriteSpsColor(this.codec, nal, this.tags);+ this.cache.set(key, made);+ return made;+ }++ /** The codec description (avcC or hvcC) with its SPS entries rewritten. */+ description(desc: Uint8Array): Uint8Array {+ return this.codec === "avc" ? this.avcC(desc) : this.hvcC(desc);+ }++ /** Length-prefixed sample data with any in-band SPS rewritten; null when+ * the sample carries none, so the caller keeps its packet. */+ sample(data: Uint8Array, lengthSize: number): Uint8Array | null {+ const parts: Uint8Array[] = [];+ let changed = false;+ let at = 0;+ while (at + lengthSize <= data.length) {+ let len = 0;+ for (let i = 0; i < lengthSize; i++) len = len * 256 + data[at + i];+ const start = at + lengthSize;+ const end = Math.min(data.length, start + len);+ if (end <= start) break;+ const nal = data.subarray(start, end);+ if (nalType(this.codec, nal) === SPS_TYPE[this.codec]) {+ const made = this.sps(nal);+ if (made !== nal) {+ changed = true;+ parts.push(lengthPrefix(made.length, lengthSize), made);+ at = end;+ continue;+ }+ }+ parts.push(data.subarray(at, end));+ at = end;+ }+ if (!changed) return null;+ if (at < data.length) parts.push(data.subarray(at));+ return concat(parts);+ }++ private avcC(desc: Uint8Array): Uint8Array {+ const parts: Uint8Array[] = [desc.subarray(0, 6)];+ let at = 6;+ const numSps = desc[5] & 0x1f;+ for (let i = 0; i < numSps; i++) {+ const len = (desc[at] << 8) | desc[at + 1];+ const made = this.sps(desc.subarray(at + 2, at + 2 + len));+ parts.push(lengthPrefix(made.length, 2), made);+ at += 2 + len;+ }+ parts.push(desc.subarray(at));+ return concat(parts);+ }++ private hvcC(desc: Uint8Array): Uint8Array {+ const parts: Uint8Array[] = [desc.subarray(0, 23)];+ const numArrays = desc[22];+ let at = 23;+ for (let a = 0; a < numArrays; a++) {+ const type = desc[at] & 0x3f;+ const count = (desc[at + 1] << 8) | desc[at + 2];+ parts.push(desc.subarray(at, at + 3));+ at += 3;+ for (let i = 0; i < count; i++) {+ const len = (desc[at] << 8) | desc[at + 1];+ const nal = desc.subarray(at + 2, at + 2 + len);+ const made = type === SPS_TYPE.hevc ? this.sps(nal) : nal;+ parts.push(lengthPrefix(made.length, 2), made);+ at += 2 + len;+ }+ }+ parts.push(desc.subarray(at));+ return concat(parts);+ }+}++/** NAL length size (1–4) a description declares. */+export function descriptionLengthSize(codec: SpsCodec, desc: Uint8Array): number {+ return (codec === "avc" ? desc[4] & 3 : desc[21] & 3) + 1;+}++function lengthPrefix(length: number, size: number): Uint8Array {+ const out = new Uint8Array(size);+ for (let i = size - 1; i >= 0; i--) {+ out[i] = length & 0xff;+ length >>>= 8;+ }+ return out;+}++function concat(parts: Uint8Array[]): Uint8Array {+ const out = new Uint8Array(parts.reduce((n, p) => n + p.length, 0));+ let at = 0;+ for (const p of parts) {+ out.set(p, at);+ at += p.length;+ }+ return out;+}diff --git a/site/src/cut/lib/store.test.ts b/site/src/cut/lib/store.test.tsindex ca50b209..db2fd76d 100644--- a/site/src/cut/lib/store.test.ts+++ b/site/src/cut/lib/store.test.ts@@ -1,6 +1,6 @@import { beforeEach, describe, expect, test } from "bun:test";import { groupRemap } from "@donkeycut/effects-kit";-import { adoptTransitionFields, assetIdsInUse, clipLen, closeMicroGaps, cutTranscribeSpec, deriveTransitionFields, docOverlays, getClipSpans, liftClipLooks, moveOverlayGroup, overlayLaneOrder, normalizeElementLanes, parkedTransitions, placeInRun, projectDuration, rippleInsert, separateOverlaps, serializeDoc, useEditor } from "./store";+import { adoptTransitionFields, assetIdsInUse, clipLen, closeMicroGaps, cutTranscribeSpec, deriveTransitionFields, docOverlays, getClipSpans, liftClipLooks, moveOverlayGroup, overlayLaneOrder, normalizeElementLanes, parkedTransitions, placeInRun, projectDuration, rippleInsert, separateOverlaps, serializeDoc, useEditor, DOC_KEYS, docFieldsEdited } from "./store";import type React from "react";import { runAiTool } from "./aiTools";import { selectedMembers, startLaneMove } from "./laneTracks";@@ -185,6 +185,21 @@ describe("the document projection", () => {expect("kind" in after.overlays![0]).toBe(false);});+ test("a project color change alone is an edit the autosave sees", () => {+ const last = serializeDoc(s() as Parameters<typeof serializeDoc>[0]);+ expect(docFieldsEdited(s(), last, s().transitions)).toBe(false);+ s().setColorSpace(s().colorSpace === "hlg" ? "pq" : "hlg");+ expect(docFieldsEdited(s(), last, s().transitions)).toBe(true);+ });++ test("every serialized document field is a doc key the autosave compares", () => {+ const doc = serializeDoc(s() as Parameters<typeof serializeDoc>[0]);+ const keys = Object.keys(doc)+ .filter((k) => k !== "firstOpen")+ .map((k) => (k === "name" ? "projectName" : k));+ for (const k of keys) expect(DOC_KEYS as readonly string[]).toContain(k);+ });+test("a document with nothing to strip is passed straight through", () => {const overlays = [{ id: "s1", kind: "shape", shape: "rect", start: 0, end: 2, x: 0.5, y: 0.5, w: 0.2, h: 0.2, fill: "#fff" },diff --git a/site/src/cut/lib/store.ts b/site/src/cut/lib/store.tsindex db71eeca..4dcfbc45 100644--- a/site/src/cut/lib/store.ts+++ b/site/src/cut/lib/store.ts@@ -18,7 +18,10 @@ import {upsertKey,type EffectId,type MaskKey,+ OUTPUT_SPACES,+ type OutputSpace,type OverlayKey,+ type SourceProfile,type SpeedNode,} from "@donkeycut/effects-kit";import { create } from "zustand";@@ -342,6 +345,20 @@ const clampPps = (v: number) =>/** An asset filed into a Media folder. The Media panel shows what the user put* there — assets with no `origin` — so filing a created clip (a render, a* voiceover, a recording) is also its move out of the place that made it. */+/** Whether writing `patch` onto `asset` would leave it as it is. Values are+ * compared as they are, and a flat record (an asset's color) field by field;+ * lists compare by identity, so a new strip is always a change. */+export function patchIsNoop(asset: MediaAsset, patch: Partial<MediaAsset>): boolean {+ const same = (a: unknown, b: unknown): boolean => {+ if (Object.is(a, b)) return true;+ if (!a || !b || typeof a !== "object" || typeof b !== "object" || Array.isArray(a) || Array.isArray(b)) return false;+ const ka = Object.keys(a);+ if (ka.length !== Object.keys(b).length) return false;+ return ka.every((k) => Object.is((a as Record<string, unknown>)[k], (b as Record<string, unknown>)[k]));+ };+ return (Object.keys(patch) as (keyof MediaAsset)[]).every((k) => same(asset[k], patch[k]));+}+const filedInMedia = (a: MediaAsset, folderId: string | null): MediaAsset => ({...a,folderId: folderId ?? undefined,@@ -362,11 +379,18 @@ interface DocSnapshot {/** The custom guide lines: placed, dragged and removed on the preview, so* undo brings one back. */guideLines: GuideLines;+ /** The delivery's color space, set from the export dialog, the Color+ * panel and the chat. */+ colorSpace: OutputSpace;/** Each asset's beat grid. Beats are edited on the timeline like anything* else — dragged, added, removed, cleared — but they live on the asset* rather than in the doc arrays, so the checkpoint carries them separately* and the restore puts them back. */beats: { id: string; grid: AssetBeats | undefined }[];+ /** Each asset's source-colour override, set from the Color panel and the+ * chat; it lives on the asset like the beat grid, so the checkpoint+ * carries it the same way. */+ sourceColor: { id: string; profile: SourceProfile | undefined }[];}export type SubtitleStatus = "idle" | "running" | "ready" | "empty" | "error";@@ -425,6 +449,9 @@ export interface EditorState {* nothing but titles and shapes plays over it, a fitted clip letterboxes* into it, and a gap on track 0 shows it. */background: string;+ /** The delivery's color space: SDR, or HDR in HLG or PQ. The export writes+ * it and the preview shows it on an HDR display. */+ colorSpace: OutputSpace;selection: Selection;/** Everything selected, including `selection` (the primary that drives the* inspector). Bulk actions — delete, copy — act on this whole set. */@@ -525,8 +552,22 @@ export interface EditorState {/** Set the frame color. Project-level, so it sits outside undo like the* aspect. */setBackground: (hex: string) => void;+ /** Set the delivery's color space, with undo. */+ setColorSpace: (space: OutputSpace) => void;addAsset: (asset: MediaAsset) => void;updateAsset: (id: string, patch: Partial<MediaAsset>) => void;+ /** Set what a source's code values mean — the person's override of the+ * profile the header read — with an undo step. `undefined` returns the+ * asset to the detected profile. */+ setAssetColorProfile: (id: string, profile: SourceProfile | undefined) => void;+ /** Write the preview proxy that landed beside a master onto its asset, and+ * the address the preview reads it from. The preview retargets on the next+ * frame; the document saves the proxy with the asset. No undo step: the+ * proxy is a fact about the file. */+ setAssetProxy: (id: string, proxy: NonNullable<StoredAsset["proxy"]>, proxyUrl: string) => void;+ /** Take a proxy that would not open off its asset, so every reader falls+ * back to the master. A read-only view drops it for this session only. */+ dropAssetProxy: (id: string) => void;/** Give a video asset stored without a length the duration and size a probe* read off its file, and open every zero-length clip cut from it to the* footage — up to the next clip on its track, so nothing overlaps. A doc@@ -1317,7 +1358,7 @@ export async function runTranscription(projectId: string, spec: object): Promise// Doc-mutating state: in a read-only shared view the set wrapper drops these// keys from every write, so edit paths anywhere in the app become no-ops.// Hydration (loadProject, the shared-view poll) escapes via `hydrating`.-const DOC_KEYS = [+export const DOC_KEYS = ["projectName","saveState","assets",@@ -1331,6 +1372,7 @@ const DOC_KEYS = ["guides","guideLines","background",+ "colorSpace","publish","notes","subtitles",@@ -1511,10 +1553,12 @@ export const useEditor = create<EditorState>((baseSet, get, api) => {api.setState = set as typeof api.setState;const snapshot = (): DocSnapshot => {- const { clips, transitions, audioClips, overlays, subtitles, assets, guideLines } = get();+ const { clips, transitions, audioClips, overlays, subtitles, assets, guideLines, colorSpace } = get();return {beats: assets.map((a) => ({ id: a.id, grid: a.beats })),+ sourceColor: assets.map((a) => ({ id: a.id, profile: a.colorProfile })),guideLines: { v: [...guideLines.v], h: [...guideLines.h] },+ colorSpace,// Render-owned clips are excluded — history captures the user's timeline,// not the background run's placements (restoreDoc re-attaches the live ones).clips: clips.filter((c) => !genClipIds.has(c.id)).map((c) => ({ ...c })),@@ -1535,16 +1579,21 @@ export const useEditor = create<EditorState>((baseSet, get, api) => {* doc — an undo mid-session (a brush stroke, a panel edit) keeps the panel* and its stage gizmos on the clip being worked. */const restoreDoc = (snap: DocSnapshot) => {- const { beats, ...doc } = snap;+ const { beats, sourceColor, ...doc } = snap;const { clips, audioClips, assets, selection, multiSelection } = get();const genClips = clips.filter((c) => genClipIds.has(c.id));const genAudio = audioClips.filter((c) => genAudioIds.has(c.id));// Beat grids go back onto the assets they came off. An asset imported// since the checkpoint was taken is not in it and keeps the grid it has.const grids = new Map(beats.map((b) => [b.id, b.grid]));- const withBeats = assets.map((a) =>- grids.has(a.id) && grids.get(a.id) !== a.beats ? { ...a, beats: grids.get(a.id) } : a- );+ const profiles = new Map(sourceColor.map((c) => [c.id, c.profile]));+ const withBeats = assets.map((a) => {+ let next = a;+ if (grids.has(a.id) && grids.get(a.id) !== a.beats) next = { ...next, beats: grids.get(a.id) };+ if (profiles.has(a.id) && profiles.get(a.id) !== a.colorProfile)+ next = withColorProfile(next, profiles.get(a.id));+ return next;+ });const beatsMoved = withBeats.some((a, i) => a !== assets[i]);const nextClips = [...doc.clips, ...genClips].sort((a, b) => a.start - b.start);const nextAudio = [...doc.audioClips, ...genAudio];@@ -1713,6 +1762,7 @@ export const useEditor = create<EditorState>((baseSet, get, api) => {guidesHidden: false,guideLines: EMPTY_GUIDE_LINES,background: DEFAULT_BACKGROUND,+ colorSpace: "sdr",selection: null,multiSelection: [],playing: false,@@ -1765,6 +1815,7 @@ export const useEditor = create<EditorState>((baseSet, get, api) => {guidesHidden: false,guideLines: EMPTY_GUIDE_LINES,background: DEFAULT_BACKGROUND,+ colorSpace: "sdr",selection: null,multiSelection: [],selectedKey: null,@@ -1881,6 +1932,7 @@ export const useEditor = create<EditorState>((baseSet, get, api) => {stale.map((a) => ({...a,url: held.get(a.fileName) ?? links?.urls.get(a.fileName) ?? mediaUrl(id, a.fileName),+ ...(a.proxy ? { proxyUrl: links?.urls.get(a.proxy.fileName) ?? mediaUrl(id, a.proxy.fileName) } : {}),})),ui);@@ -1935,6 +1987,7 @@ export const useEditor = create<EditorState>((baseSet, get, api) => {...(kept?.sceneCuts !== undefined ? { sceneCuts: kept.sceneCuts } : {}),...(kept?.peaks !== undefined ? { peaks: kept.peaks } : {}),url: mediaUrl(id, a.fileName),+ ...(a.proxy ? { proxyUrl: mediaUrl(id, a.proxy.fileName) } : {}),};});// Cloud and shared media ride signed R2 URLs, batch-minted once per@@ -1955,10 +2008,14 @@ export const useEditor = create<EditorState>((baseSet, get, api) => {}if (!current()) return;const missing = assets.filter((a) => !held.has(a.fileName));- const signed = await fetchSignedMediaUrls(id, missing.map((a) => a.fileName));+ // A proxy is served like the master it stands in for, so its link+ // is minted in the same batch.+ const proxies = assets.flatMap((a) => (a.proxy ? [a.proxy.fileName] : []));+ const signed = await fetchSignedMediaUrls(id, [...missing.map((a) => a.fileName), ...proxies]);if (!current()) return;for (const a of assets) {a.url = held.get(a.fileName) ?? signed.urls.get(a.fileName) ?? a.url;+ if (a.proxy) a.proxyUrl = signed.urls.get(a.proxy.fileName) ?? a.proxyUrl;}markSignedBatch(id, signed.expiresAt);// A browser project's "mint" hands back session blob URLs, dead on@@ -2072,7 +2129,7 @@ export const useEditor = create<EditorState>((baseSet, get, api) => {try {set({projectName: doc.name ?? "",- assets,+ assets: assets.map(liftColorProfile),clips: state.clips,transitions: state.transitions,audioClips: state.audioClips,@@ -2085,6 +2142,7 @@ export const useEditor = create<EditorState>((baseSet, get, api) => {guidesHidden: false,guideLines: sanitizeGuideLines(doc.guideLines),background: state.background,+ colorSpace: state.colorSpace,// View state lives in IndexedDB; doc.ui covers projects saved// before the move.pxPerSec: clampPps(ui.pxPerSec ?? doc.ui?.pxPerSec ?? 60),@@ -2353,6 +2411,11 @@ export const useEditor = create<EditorState>((baseSet, get, api) => {}));},setBackground: (hex) => set({ background: projectBackground(hex) }),+ setColorSpace: (space) => {+ if (get().colorSpace === space || get().readOnly) return;+ push();+ set({ colorSpace: space });+ },addAsset: (asset) =>set((s) => {@@ -2374,6 +2437,43 @@ export const useEditor = create<EditorState>((baseSet, get, api) => {return { assets: [...s.assets, asset], ...(guess ? { aspect: guess } : {}) };}),+ setAssetColorProfile: (id, profile) => {+ const asset = get().assets.find((a) => a.id === id);+ if (!asset || get().readOnly || asset.colorProfile === profile) return;+ push();+ set((s) => ({+ assets: s.assets.map((a) => (a.id === id ? withColorProfile(a, profile) : a)),+ }));+ },++ setAssetProxy: (id, proxy, proxyUrl) => {+ if (get().readOnly) return;+ set((s) => ({+ assets: s.assets.map((a) => (a.id === id ? { ...a, proxy, proxyUrl } : a)),+ }));+ },++ dropAssetProxy: (id) => {+ const target = get().assets.find((a) => a.id === id);+ if (!target || (!target.proxy && !target.proxyUrl)) return;+ const drop = (s: EditorState) => ({+ assets: s.assets.map((a) => {+ if (a.id !== id) return a;+ const rest = { ...a };+ delete rest.proxy;+ delete rest.proxyUrl;+ return rest;+ }),+ });+ if (!get().readOnly) return set(drop);+ hydrating = true;+ try {+ set(drop);+ } finally {+ hydrating = false;+ }+ },+updateAsset: (id, patch) => {// A read-only view still takes runtime enrichment (signed URLs,// filmstrips, waveforms) — decorative fields only; doc fields stay@@ -2396,6 +2496,11 @@ export const useEditor = create<EditorState>((baseSet, get, api) => {}return;}+ // A patch that changes nothing writes nothing: every asset write+ // re-renders what reads the assets, and probes that land twice with+ // the same answer (an import's and the lazy fill's) cost one render.+ const current = get().assets.find((a) => a.id === id);+ if (!current || patchIsNoop(current, patch)) return;set((s) => ({assets: s.assets.map((a) => (a.id === id ? { ...a, ...patch } : a)),}));@@ -2444,14 +2549,20 @@ export const useEditor = create<EditorState>((baseSet, get, api) => {// browser store serves keeps its blob URL — link rotation is for// links that expire.if (a.upload || resolveRegisteredBlob(a.url)) return a;- const url = urls.get(a.fileName);- if (!url || url === a.url) return a;+ const url = urls.get(a.fileName) ?? a.url;+ const proxyUrl = a.proxy ? (urls.get(a.proxy.fileName) ?? a.proxyUrl) : a.proxyUrl;+ if (url === a.url && proxyUrl === a.proxyUrl) return a;// A still's filmstrip is its source URL, so it moves with it.const thumbs =a.type === "image" && a.thumbs?.length && a.thumbs.every((t) => t === a.url)? [url]: a.thumbs;- return { ...a, url, ...(thumbs !== a.thumbs ? { thumbs } : {}) };+ return {+ ...a,+ url,+ ...(proxyUrl !== undefined ? { proxyUrl } : {}),+ ...(thumbs !== a.thumbs ? { thumbs } : {}),+ };}),}));} finally {@@ -2477,14 +2588,20 @@ export const useEditor = create<EditorState>((baseSet, get, api) => {if (pending) scrub(pending.snap);const dropFile = () => {const s = get();- if (!s.projectId || s.assets.some((a) => a.fileName === gone.fileName)) return;- void apiFetch(- `/api/cut/projects/${s.projectId}/media/${encodeURIComponent(gone.fileName)}`,- { method: "DELETE" }- ).catch(() => {});- // A cloud project's browser-store copy — pin, bytes, and blob URL —- // dies with the cloud object.- if (getBackend().kind === "cloud") void dropLocalMedia(s.projectId, gone.fileName);+ if (!s.projectId) return;+ const drop = (fileName: string) => {+ void apiFetch(+ `/api/cut/projects/${s.projectId}/media/${encodeURIComponent(fileName)}`,+ { method: "DELETE" }+ ).catch(() => {});+ // A cloud project's browser-store copy — pin, bytes, and blob URL —+ // dies with the cloud object.+ if (getBackend().kind === "cloud") void dropLocalMedia(s.projectId!, fileName);+ };+ if (!s.assets.some((a) => a.fileName === gone.fileName)) drop(gone.fileName);+ // The master's preview proxy goes with it.+ const proxy = gone.proxy?.fileName;+ if (proxy && !s.assets.some((a) => a.proxy?.fileName === proxy)) drop(proxy);};// An unreferenced asset is no doc edit: history snapshots don't cover// the asset list, so removing one must not open a checkpoint or churn@@ -4802,12 +4919,34 @@ export const useEditor = create<EditorState>((baseSet, get, api) => {};});-/** Whether any asset's beat grid was rewritten between two asset lists. An- * asset arriving or leaving is no beat edit; only a grid changing under an id- * that was already there counts. */+/** Whether any asset's beat grid or source-colour override was rewritten+ * between two asset lists. An asset arriving or leaving is no edit; only a+ * value changing under an id that was already there counts. */function beatsEdited(prev: MediaAsset[], next: MediaAsset[]): boolean {- const before = new Map(prev.map((a) => [a.id, a.beats]));- return next.some((a) => before.has(a.id) && before.get(a.id) !== a.beats);+ const before = new Map(prev.map((a) => [a.id, a]));+ return next.some((a) => {+ const was = before.get(a.id);+ return !!was && (was.beats !== a.beats || was.colorProfile !== a.colorProfile);+ });+}++/** The asset with the person's source profile override set or cleared. The+ * header's record in `color` is left as it is. */+function withColorProfile<A extends StoredAsset>(asset: A, profile: SourceProfile | undefined): A {+ const { colorProfile: _was, ...rest } = asset;+ void _was;+ return (profile ? { ...rest, colorProfile: profile } : rest) as A;+}++/** A stored asset in the current shape. Projects saved while the override+ * rode inside the header record (`color.profile`) carry it out to+ * `colorProfile` once, on load. */+export function liftColorProfile<A extends StoredAsset>(asset: A): A {+ const color = asset.color as (StoredAsset["color"] & { profile?: SourceProfile }) | undefined;+ if (!color || !("profile" in color)) return asset;+ const { profile, ...header } = color;+ const lifted = { ...asset, color: header };+ return profile && asset.colorProfile === undefined ? { ...lifted, colorProfile: profile } : lifted;}// Track real edits to the persistable doc so a deferred checkpoint (see push)@@ -4823,6 +4962,7 @@ useEditor.subscribe((s, prev) => {s.overlays !== prev.overlays ||s.subtitles !== prev.subtitles ||s.guideLines !== prev.guideLines ||+ s.colorSpace !== prev.colorSpace ||(s.assets !== prev.assets && beatsEdited(prev.assets, s.assets)))docSeq++;@@ -4894,7 +5034,7 @@ export const docOverlays = (() => {export function storedAssets(assets: MediaAsset[]): StoredAsset[] {return assets.filter((a) => !tabOnlyUpload(a))- .map(({ id, fileName, name, type, duration, sizeBytes, width, height, origin, chatId, folderId, language, watch, speech, beats, sceneCuts, copiedFrom, block }) => ({+ .map(({ id, fileName, name, type, duration, sizeBytes, width, height, origin, chatId, folderId, language, watch, speech, beats, sceneCuts, copiedFrom, block, color, colorProfile, proxy }) => ({id,fileName,name,@@ -4913,6 +5053,9 @@ export function storedAssets(assets: MediaAsset[]): StoredAsset[] {...(sceneCuts !== undefined ? { sceneCuts } : {}),...(copiedFrom !== undefined ? { copiedFrom } : {}),...(block !== undefined ? { block } : {}),+ ...(color !== undefined ? { color } : {}),+ ...(colorProfile !== undefined ? { colorProfile } : {}),+ ...(proxy !== undefined ? { proxy } : {}),}));}@@ -4930,6 +5073,7 @@ export function serializeDoc(s: {guides: GuideId[];guideLines: GuideLines;background: string;+ colorSpace: OutputSpace;publish: { caption: string; tags: string; soundTitle: string; handle: string };notes: { text: string; publishedAt: string; links: string[] };subtitles: SubtitlesBlock;@@ -4952,6 +5096,7 @@ export function serializeDoc(s: {guides: s.guides,guideLines: s.guideLines,background: s.background,+ colorSpace: s.colorSpace,subtitles: s.subtitles,publish: { ...s.publish },notes: { ...s.notes, links: [...s.notes.links] },@@ -4963,6 +5108,60 @@ export function serializeDoc(s: {};}+export type DocKey = (typeof DOC_KEYS)[number];++/** The autosave's edit test, one comparator per document field. Keyed by+ * DOC_KEYS, so a field added there without a comparator is a type error.+ * `saveState` is status, and `assets` compares by its stored projection in+ * the caller, which keeps a baseline across ticks. */+const DOC_FIELD_EDITED: {+ [K in Exclude<DocKey, "saveState" | "assets">]: (+ s: EditorState,+ last: Partial<ProjectDoc>,+ lastBars: TimelineTransition[]+ ) => boolean;+} = {+ projectName: (s, last) => s.projectName !== last.name,+ // The projections, not the raw arrays: clips waiting on an upload are held+ // out of the document, and holding one is not an edit.+ clips: (s, last) => docClips(s.clips, s.assets) !== (last.clips as unknown),+ audioClips: (s, last) => docAudioClips(s.audioClips, s.assets) !== (last.audioClips as unknown),+ overlays: (s, last) => docOverlays(s.overlays) !== (last.overlays as unknown),+ transitions: (s, _last, lastBars) => s.transitions !== lastBars,+ templates: (s, last) => s.templates !== (last.templates as unknown),+ mediaFolders: (s, last) => s.mediaFolders !== (last.mediaFolders as unknown),+ subtitles: (s, last) => s.subtitles !== (last.subtitles as unknown),+ aspect: (s, last) => s.aspect !== last.aspect,+ guides: (s, last) => s.guides !== last.guides,+ guideLines: (s, last) => s.guideLines !== last.guideLines,+ background: (s, last) => s.background !== last.background,+ colorSpace: (s, last) => s.colorSpace !== last.colorSpace,+ publish: (s, last) =>+ s.publish.caption !== last.publish?.caption ||+ s.publish.tags !== last.publish?.tags ||+ s.publish.soundTitle !== last.publish?.soundTitle ||+ s.publish.handle !== last.publish?.handle,+ notes: (s, last) =>+ s.notes.text !== last.notes?.text ||+ s.notes.publishedAt !== last.notes?.publishedAt ||+ s.notes.links.join("") !== (last.notes?.links ?? []).join(""),+ // Normalized like serializeDoc stores it (?? null): a project with no run+ // holds undefined in state and null in the doc, which is no change.+ genvideo: (s, last) => (s.genvideo ?? null) !== ((last.genvideo ?? null) as unknown),+ renders: (s, last) => s.renders !== (last.renders as unknown),+};+const DOC_FIELD_TESTS = Object.values(DOC_FIELD_EDITED);++/** Whether the live state differs from the last serialized doc on any+ * document field other than assets. */+export function docFieldsEdited(+ s: EditorState,+ last: Partial<ProjectDoc>,+ lastBars: TimelineTransition[]+): boolean {+ return DOC_FIELD_TESTS.some((edited) => edited(s, last, lastBars));+}+/** A clip's uniform playback rate (>0, default 1). A clip carrying a speed* curve has no single rate; read `retimeOf(c)` for its map. */export function clipSpeed(c: VideoClip) {@@ -5547,6 +5746,7 @@ export function normalizeDocState(subtitles: SubtitlesBlock;aspect: Aspect | null;background: string;+ colorSpace: OutputSpace;} {const docClips = doc.clips ?? [];// Older docs stored video track 0 packed (array order implied the@@ -5613,6 +5813,7 @@ export function normalizeDocState(subtitles: { ...subtitles, cues: merged.cues },aspect: normalizeAspect(doc.aspect) ?? null,background: projectBackground(doc.background),+ colorSpace: OUTPUT_SPACES.some((o) => o.id === doc.colorSpace) ? doc.colorSpace! : "sdr",};}diff --git a/site/src/cut/lib/storeProxy.test.ts b/site/src/cut/lib/storeProxy.test.tsnew file mode 100644index 00000000..6519d197--- /dev/null+++ b/site/src/cut/lib/storeProxy.test.ts@@ -0,0 +1,60 @@+import { afterEach, describe, expect, mock, test } from "bun:test";+import { stubModule } from "@/lib/testing/stubModule";+import type { MediaAsset } from "./types";++const deletes: string[] = [];+await stubModule("./backend", import.meta.url, {+ apiFetch: mock(async (path: string, init?: RequestInit) => {+ if (init?.method === "DELETE") deletes.push(path);+ return Response.json({ ok: true });+ }),+});+const { useEditor } = await import("./store");++const master = (id: string, proxy?: MediaAsset["proxy"]): MediaAsset => ({+ id,+ fileName: `${id}.MOV`,+ name: `${id}.MOV`,+ type: "video",+ duration: 4,+ url: `https://example.test/${id}.MOV`,+ ...(proxy ? { proxy, proxyUrl: `https://example.test/${proxy.fileName}` } : {}),+});++afterEach(() => {+ deletes.length = 0;+ useEditor.setState({ projectId: null, assets: [], clips: [], audioClips: [], readOnly: false });+});++describe("a ProRes master's proxy in the store", () => {+ test("setAssetProxy writes the proxy and its address onto the asset, in the saved projection", () => {+ useEditor.setState({ projectId: "p", assets: [master("a")] });+ useEditor.getState().setAssetProxy("a", { fileName: "a.proxy.mp4", sizeBytes: 12 }, "blob:proxy");+ const asset = useEditor.getState().assets[0];+ expect(asset.proxy).toEqual({ fileName: "a.proxy.mp4", sizeBytes: 12 });+ expect(asset.proxyUrl).toBe("blob:proxy");+ });++ test("a read-only view takes no proxy", () => {+ useEditor.setState({ projectId: "p", assets: [master("a")], readOnly: true });+ useEditor.getState().setAssetProxy("a", { fileName: "a.proxy.mp4", sizeBytes: 12 }, "blob:proxy");+ expect(useEditor.getState().assets[0].proxy).toBeUndefined();+ });++ test("deleting the asset drops the master and its proxy", () => {+ useEditor.setState({ projectId: "p", assets: [master("a", { fileName: "a.proxy.mp4", sizeBytes: 12 })] });+ useEditor.getState().removeAsset("a");+ expect(useEditor.getState().assets).toHaveLength(0);+ expect(deletes).toEqual(["/api/cut/projects/p/media/a.MOV", "/api/cut/projects/p/media/a.proxy.mp4"]);+ });++ test("a proxy another asset still points at stays", () => {+ const proxy = { fileName: "a.proxy.mp4", sizeBytes: 12 };+ useEditor.setState({+ projectId: "p",+ assets: [master("a", proxy), { ...master("b", proxy), fileName: "a.MOV" }],+ });+ useEditor.getState().removeAsset("a");+ expect(deletes).toEqual([]);+ });+});diff --git a/site/src/cut/lib/types.ts b/site/src/cut/lib/types.tsindex 5d44dc4e..cc87cfe2 100644--- a/site/src/cut/lib/types.ts+++ b/site/src/cut/lib/types.ts@@ -1,5 +1,6 @@import type { GuideId, GuideLines } from "./guides";import {+ type OutputSpace,EFFECT_LABELS,behindSubjectMask,overlayKind,@@ -24,10 +25,18 @@ import {type TextOverlay as KitTextOverlay,type WordEffectId,} from "@donkeycut/effects-kit";+import type { CodeFormat, SourceProfile } from "@donkeycut/effects-kit";import { getBackend, type CutBackend } from "./backend";import type { VideoProject } from "./genvideo/types";-export type AssetType = "video" | "audio" | "image" | "font";+export type AssetType = "video" | "audio" | "image" | "font" | "lut";++/** Library kinds a document links to by content key and never copies: fonts+ * and LUTs. They have no place on the timeline and no streams to probe. */+export const LINKED_ASSET_TYPES = ["font", "lut"] as const;+export type LinkedAssetType = (typeof LINKED_ASSET_TYPES)[number];+export const isLinkedAssetType = (type: string): type is LinkedAssetType =>+ (LINKED_ASSET_TYPES as readonly string[]).includes(type);/** Default on-timeline length (seconds) a still image occupies when placed —* an image has no intrinsic duration, so the clip carries this as its `out`. */@@ -258,6 +267,18 @@ export interface StoredAsset {* blockSource.ts. Replacing it with real footage is an ordinary item* replace; the clip keeps its place and its length. */block?: { label: string; color?: string };+ /** What the video's header says its code values are, read at import+ * (lib/colorProbe.ts): matrix, range, bit depth, the profile it names and+ * the codec. Only a header read writes it. Absent on media imported before+ * the probe existed; enrichAsset fills it from a header read. */+ color?: CodeFormat & { detected: SourceProfile; codec?: string };+ /** The person's override of what this source's code values mean. */+ colorProfile?: SourceProfile;+ /** A preview proxy of a master the browser cannot play at speed (a ProRes+ * master, an HDR file on a browser that tone-maps): a bt709-tagged HEVC+ * file beside the master in the project's media. The preview reads it; an+ * export reads the master. */+ proxy?: { fileName: string; sizeBytes: number };}/** A folder in the Media panel's Project Files view — a flat, project-local@@ -312,8 +333,16 @@ export interface MediaAsset extends StoredAsset {peaks?: number[];/** Present only while the file is still uploading. */upload?: AssetUpload;+ /** Where the preview proxy is served from, when `proxy` is set. */+ proxyUrl?: string;}+/** The URL the preview decodes: the proxy when the asset has one, else the+ * master. Every reader that draws for the screen goes through this; a+ * render reads `url`. */+export const previewUrl = (asset: Pick<MediaAsset, "url" | "proxyUrl">): string =>+ asset.proxyUrl ?? asset.url;+/*** A layout region inside the output frame, as fractions with a top-left origin* (x,y = top-left corner; w,h = size). Absent on a clip means it fills the@@ -1195,6 +1224,9 @@ export interface LibraryTemplate {* preset (see soundPresets.ts), listed in the audio inspector and kept* off the template shelf. */sound?: ClipSound;+ /** A saved colour grade: a template carrying only this is a grade preset,+ * listed in the Color panel and kept off the template shelf. */+ grade?: ColorGrade;}/** What the client sends to save a selection (media are project file names). */export type TemplateSaveInput = Omit<LibraryTemplate, "id" | "addedAt">;@@ -1580,6 +1612,9 @@ export interface ProjectDoc {* cut plays over, what letterboxes a fitted clip, and what fills a gap in the* timeline. Hex; absent = `DEFAULT_BACKGROUND`. */background?: string;+ /** The delivery's color space — what the export writes and, on an HDR+ * display, what the preview shows. Absent = SDR. */+ colorSpace?: OutputSpace;/** Auto-generated (then hand-edited) subtitles. */subtitles?: SubtitlesBlock;/** Legacy per-project view metadata — view state now lives in IndexedDB;diff --git a/site/src/cut/server/ai/catalog.ts b/site/src/cut/server/ai/catalog.tsindex f802cd18..fd64df33 100644--- a/site/src/cut/server/ai/catalog.ts+++ b/site/src/cut/server/ai/catalog.ts@@ -26,7 +26,7 @@ import {MIN_WORDS_PER_CUE,} from "@/cut/lib/cueChunk";import { CAPTION_STYLES } from "@/cut/lib/subtitles";-import { SOUND_PRESETS, wordEffectCatalog, WORD_EFFECT_IDS } from "@donkeycut/effects-kit";+import { OUTPUT_SPACES, SOUND_PRESETS, wordEffectCatalog, WORD_EFFECT_IDS } from "@donkeycut/effects-kit";import { textMoveCatalog } from "@/cut/lib/textMotion";import { OVERLAY_ANIMATION_TOOLS } from "@/cut/components/AnimationTiles.tools";import { AUDIO_TOOLS } from "@/cut/components/AudioPanel.tools";@@ -48,6 +48,9 @@ import { TOP_BAR_TOOLS } from "@/cut/components/TopBar.tools";import { TRANSITIONS_TOOLS } from "@/cut/components/TransitionsPanel.tools";import {AUDIO_EFFECT_IDS,+ GRADE_BASIC_FIELDS,+ GRADE_DETAIL_FIELDS,+ GRADE_MAX,gradePresetCatalogText,HSL_BANDS,LOOK_EFFECTS,@@ -55,6 +58,9 @@ import {OVERLAY_ANIM_STYLE_IDS,OVERLAY_LOOP_STYLE_IDS,SOUND_EQ_BANDS,+ SOURCE_PROFILES,+ WHEEL_LABELS,+ WHEEL_ZONES,} from "@donkeycut/effects-kit";import type { AiToolDef } from "../../lib/aiToolDef";import { GOOGLE_FONT_IDS } from "../../lib/fontCatalog";@@ -88,7 +94,7 @@ export const PROJECT_TOOLS: AiToolDef[] = AI_TOOLS.filter((tool) => !tool.server/** The assistant's own senses and flows, declared on every work turn. */export const CORE_TOOLS: AiToolDef[] = [...AI_PANEL_TOOLS];-const COLOR_TOOL = /^(set_color_|read_color_stats$|match_color_grade$)/;+const COLOR_TOOL = /^(set_color_|read_color_stats$|match_color_grade$|copy_color_grade$|set_source_color$|save_color_grade$|apply_saved_grade$)/;/** The catalog by area: each `*.tools.ts` module is one area (the inspector's* color tools stand on their own), named and described once here so the turn@@ -111,7 +117,7 @@ export const TOOL_AREAS: Record<string, { blurb: string; tools: AiToolDef[] }> =tools: INSPECTOR_TOOLS.filter((t) => !COLOR_TOOL.test(t.name)),},color: {- blurb: "color grading: a clip's color stats, grades, presets, curves, wheels, HSL, matching a reference's grade",+ blurb: "color grading: a clip's color stats, grades, presets, curves, wheels, HSL, LUTs, source color (log/HDR footage), matching a reference's grade, copying a grade to other clips, saved grades",tools: INSPECTOR_TOOLS.filter((t) => COLOR_TOOL.test(t.name)),},removal: {@@ -169,7 +175,7 @@ export const TOOL_AREAS: Record<string, { blurb: string; tools: AiToolDef[] }> =tools: [...SIDE_PANEL_TOOLS],},top_bar: {- blurb: "the aspect ratio, guides, the project name, export",+ blurb: "the aspect ratio, guides, the project name, the delivery color space (SDR or HDR), export",tools: [...TOP_BAR_TOOLS],},editor: {@@ -239,9 +245,9 @@ Times are in seconds on the shared timeline. The playhead is currentTime; a skim- trim_clip changes in/out inside the source media. in >= 0, out <= source duration, out-in >= 0.1.- Trims and speed changes keep other rows in place. Growth pushes overlapping neighbors on the same row; shrinking leaves a gap.- set_speed sets a clip's playback rate; it changes the clip's timeline length and pushes overlapping neighbors on its own row. set_speed with \`reverse: true\` plays the clip backward (a rewind, a drop that rises, a pour that un-pours); it changes nothing about length or the curve. set_speed_curve makes the rate change through the footage — nodes of {at: source seconds, speed} or a named preset ramp — for speed ramps, whips, holds, and hits on the beat: detect_beats first, then place nodes at the beats it returns (same unit, no arithmetic). set_speed on a curved clip makes it uniform again. Either tool takes \`smooth: true\` — smooth slow motion — which synthesizes the frames between source frames wherever the clip's rate is under 1× (the export estimates the motion between them) and leaves the rest of the clip alone; editor_state shows it as \`smooth\`. Ordinary footage slowed below about 0.5× wants it on.-- set_transition joins a clip into the next one (0–2s, ${TRANSITION_STYLE_IDS.length} styles); set_animation animates one clip's own entrance/exit — read the transitions-and-fades skill before styling cuts. A transition is a bar on its own row at an absolute time, so an edit can leave one lining up with nothing: every timeline mutation reports those as \`parkedTransitions\`, and clearing them (remove_transition) is part of finishing the edit. Grading a clip's picture is the color tools (set_color_preset, set_color_grade, set_color_curves, set_color_wheels, set_color_hsl — read the color-grading skill); a stylized post treatment (grain, VHS, halation…) is add_effect, dropped over the stretch of timeline it covers — as is a treatment on the sound (echo, reverb, telephone…).+- set_transition joins a clip into the next one (0–2s, ${TRANSITION_STYLE_IDS.length} styles); set_animation animates one clip's own entrance/exit — read the transitions-and-fades skill before styling cuts. A transition is a bar on its own row at an absolute time, so an edit can leave one lining up with nothing: every timeline mutation reports those as \`parkedTransitions\`, and clearing them (remove_transition) is part of finishing the edit. Grading a clip's picture is the color tools (set_color_preset, set_color_grade, set_color_curves, set_color_wheels, set_color_hsl, set_color_lut, copy_color_grade — read the color-grading skill); a stylized post treatment (grain, VHS, halation…) is add_effect, dropped over the stretch of timeline it covers — as is a treatment on the sound (echo, reverb, telephone…).- Cutting a clip's background away — the AI person matte, ink around the silhouette, a fill behind the subject — is the cutout suite (set_removal, set_removal_stroke, set_removal_background); read the background-removal skill.-- A sweep is find, then apply. select_items judges every item on a row against a description at once and hands back the ids that match ("the clips with no one talking", "the titles that are all caps"); set_clip_muted, set_clip_hidden, set_clip_volume, set_color_preset, set_speed, set_framing, set_transition, delete_item, update_cue, delete_cue, update_audio and update_overlay then take \`ids\` in place of their one-item argument and land the change on all of them in one call, as one undo step. Reading the state and deciding item by item is the slow way to do the same thing. select_items reads what the timeline already says about each item, so anything that depends on the footage or the audio is measured first (watch_video, detect_silence, measure_level) and named in the description.+- A sweep is find, then apply. select_items judges every item on a row against a description at once and hands back the ids that match ("the clips with no one talking", "the titles that are all caps"); set_clip_muted, set_clip_hidden, set_clip_volume, set_color_preset, set_color_grade, set_color_curves, set_color_wheels, set_color_hsl, set_color_lut, apply_saved_grade, set_speed, set_framing, set_transition, delete_item, update_cue, delete_cue, update_audio and update_overlay then take \`ids\` in place of their one-item argument (the color tools take \`all_clips\` for the whole timeline) and land the change on all of them in one call, as one undo step. Reading the state and deciding item by item is the slow way to do the same thing. select_items reads what the timeline already says about each item, so anything that depends on the footage or the audio is measured first (watch_video, detect_silence, measure_level) and named in the description.- split_at cuts selected video, audio, elements and captions at the requested time. Transitions stay whole. With no selection, it cuts the track-0 clip at that time.- The Media and Library panels take the same gestures: ⌘/⇧-click a tile, or sweep a rubber-band over the grid, and dragging any picked tile onto the timeline lays the whole set down one after another from the drop point.- The user can multi-select (⌘/⇧-click, or sweep a rubber-band over empty track space) across every kind at once — clips, audio, elements, cues and transitions. Deleting or copying acts on the whole selection, and dragging any member moves the set as one: every item shifts by the same time, relative spacing kept, while unselected items slide out of the way and flow back. A selection of one kind on the multi-row tracks (audio, titles) also retracks together on a vertical drag, one row past the end opening a new track. A hover chip on each video clip toggles its own audio.@@ -258,21 +264,28 @@ Times are in seconds on the shared timeline. The playhead is currentTime; a skim"color-grading": `# Color gradingGrade like a colorist: read the image, correct it, then style it — in that order.-**Read before you write.** Call read_color_stats on the clip before grading (never grade blind) and again after a move to verify it landed. The quantiles tell you where the tones sit: p2 well above 0 = lifted/milky blacks, p98 well below 255 = no real whites (flat), a p50 far from ~118 = exposure off. warmth > 1 reads warm, < 1 cool; meanSat under ~0.15 reads muted, over ~0.35 vivid. The clip's current color state is in editor_state (colorPreset, grade, curves/wheels/hslBands).+**Read before you write.** Call read_color_stats on the clip before grading (never grade blind) and again after a move to verify it landed. The stats describe the base rendering — the footage through its source conversion, before any LUT or grade. The quantiles tell you where the tones sit: p2 well above 0 = lifted/milky blacks, p98 well below 255 = no real whites (flat), a p50 far from ~118 = exposure off. warmth > 1 reads warm, < 1 cool; meanSat under ~0.15 reads muted, over ~0.35 vivid. The clip's current color state is in editor_state (colorPreset, grade, lut, curves/wheels/hslBands); each asset's sourceColor says what its code values mean.-**Correct first.** Balance and tone before any look: auto (set_color_grade auto:true) is a computed starting point — exposure to middle gray, contrast stretch, gray-world white balance — then nudge. Neutralize a cast with temperature/tint before styling warmth on top, or the style fights the cast. Every value 0 is neutral and fields patch, so small moves are cheap; slider range is ±50.+**Source color first.** Log and HDR footage (${SOURCE_PROFILES.filter((p) => p.id !== "rec709" && p.id !== "srgb").map((p) => `${p.id} = ${p.label}`).join(", ")}) is detected from the file and converted to Rec.709 display values before anything else, so it grades like ordinary footage. When a clip reads flat and grey and its sourceColor is rec709, the header did not say — set_source_color with the right profile fixes the whole clip in one move. A camera maker's Log-to-Rec.709 LUT is the other route: set_source_color rec709 on that asset, then set_color_lut, so the picture is converted once.-**One model, layered.** A clip's color is one grade: an optional preset underneath, manual adjustments on top. set_color_preset never touches the manual layer and vice versa; intensity (amount) scales only the preset. Preview, thumbnails, and export render the same numbers.+**HDR delivery.** The project's color space (editor_state project.colorSpace; set_project_color: ${OUTPUT_SPACES.map((o) => o.id).join(", ")}) decides what the clips convert to. In an HDR project log and HDR footage keeps its range, SDR footage and every title or sticker sits at reference white (BT.2408, 203 nits), and the grade works in the HDR container; the export is 10-bit HEVC Main 10 or ProRes tagged Rec.2020 HLG or PQ. "Export in HDR" or "make this HLG/PQ" is set_project_color; the export then carries it.++**Correct next.** Balance and tone before any look: auto (set_color_grade auto:true) is a computed starting point — exposure to middle gray, contrast stretch, gray-world white balance — then nudge. Neutralize a cast with temperature/tint before styling warmth on top, or the style fights the cast. Every value 0 is neutral and fields patch, so small moves are cheap; centred sliders run ±${GRADE_MAX}, fade/sharpen/clarity 0..${GRADE_MAX}.++**One model, layered.** A clip's color is one pipeline: the source conversion, then its LUT (scaled by amount), then the preset, then the manual adjustments on top. set_color_preset never touches the manual layer and vice versa; intensity (amount) scales only the preset; the LUT sits under both. Preview, thumbnails, and export render the same numbers.**Which tool for which job.**+- set_color_lut — a look from a file: the user's .cube/.3dl LUTs are in editor_state.luts; amount 0..1 blends it. "none" removes it.- set_color_preset — a fast, coherent base. Catalog: ${gradePresetCatalogText()}. Start amount around 0.6–0.8 and tune to taste; protect_skin when a strong palette would discolor faces.-- set_color_grade — the basic sliders: exposure/contrast for tone, highlights/shadows for the ends, temperature/tint for balance, saturation/vibrance for color amount (vibrance favors the muted colors and spares what is already rich).-- set_color_curves — tonal shape: curve_contrast for an s-curve, fade for lifted film blacks, explicit points when you need a precise remap; red/green/blue channels split-tone tonally (a touch of blue lifted in shadows = cool shadows).-- set_color_wheels — split-toning by range: push shadows toward one hue and highlights toward another (teal shadows dx<0, warm highlights dx>0 is the classic pairing); luma trims each range's brightness.+- set_color_grade — the sliders. Light: ${GRADE_BASIC_FIELDS.filter((f) => f.group === "light").map((f) => f.key).join(", ")} — exposure/contrast for tone, highlights/shadows for the ends, whites/blacks for the end points, brilliance to open the darks and hold the brights at once, fade for lifted film blacks. Color: ${GRADE_BASIC_FIELDS.filter((f) => f.group === "color").map((f) => f.key).join(", ")} — temperature/tint for balance, saturation/vibrance for color amount (vibrance favors the muted colors and spares what is already rich). Detail: ${GRADE_DETAIL_FIELDS.map((f) => f.key).join(", ")} — sharpen for fine edges, clarity for local contrast, both on luma only.+- set_color_curves — tonal shape: curve_contrast for an s-curve, explicit points when you need a precise remap; red/green/blue channels split-tone tonally (a touch of blue lifted in shadows = cool shadows).+- set_color_wheels — the four wheels ${WHEEL_ZONES.map((z) => WHEEL_LABELS[z].toLowerCase()).join("/")}: lift for shadows, gamma for midtones, gain for highlights, offset for the whole picture; split-toning is a hue on lift and another on gain (teal shadows dx<0, warm highlights dx>0 is the classic pairing); luma trims each range's brightness.- set_color_hsl — one hue only (${HSL_BANDS.map((b) => b.id).join(", ")}): "sky bluer" = aqua/blue sat up, "mute the greens" = green sat down, skin smoothing = orange band, gently.- match_color_grade — a reference exists (attached image or another clip): the grade is computed from the pixels (quantile-matched curves + saturation), then refine with the tools above. Matching adjacent clips for consistency is this too — match the odd clip to its neighbor.+- copy_color_grade — "apply this look to everything": one clip's whole grade (LUT included) onto ids or all_clips, as one undo step. Every set_color_* tool also takes ids or all_clips for the same patch on several clips.+- save_color_grade / apply_saved_grade — keep a finished grade under a name in the Library (editor_state.savedGrades) and put it on clips in this or any project.-**Craft.** Skin lives around orange at modest saturation — check faces after strong saturation, hue, or wheel moves, and reach for protect_skin or a gentle orange-band correction rather than abandoning the look. Keep adjacent clips consistent: one preset + per-clip correction reads as one film; different presets per clip read as a slideshow. Strong looks sit better with contrast established first. Grades are per-clip — "grade the whole video" means every clip, same recipe.`,+**Craft.** Skin lives around orange at modest saturation — check faces after strong saturation, hue, or wheel moves, and reach for protect_skin or a gentle orange-band correction rather than abandoning the look. Keep adjacent clips consistent: one preset + per-clip correction reads as one film; different presets per clip read as a slideshow. Strong looks sit better with contrast established first. Grades are per-clip — "grade the whole video" means every clip, same recipe: grade one, then copy_color_grade all_clips.`,"background-removal": `# Background removal (Cutout)Every video clip — any track, stills too — can carry a cutout, the Inspector's Cutout tab: the clip's picture keys to an alpha matte, the subject stays, and where the background was, lower tracks or the project background show through. Preview, timeline thumbnails, and export render the same matte. A long clip tracks in parts automatically — cutout length needs no special handling.@@ -567,7 +580,7 @@ Templates (save_template / template_add) ride the same rail and now keep grades,"publish-and-export": `# Publish & exportPublish tab fields (set_publish): caption (TikTok limit 4,000 chars INCLUDING tags/emoji; hook in the first line), tags (3–5 focused tags recommended; stored space-separated, rendered as #tags), soundTitle (TikTok lets you rename the sound once after posting), handle (shown as @handle in platform previews).-Export (open_export): one-click presets — Share (1080p H.264 MP4, plays everywhere), Best (original file settings, H.264/HEVC MP4), Social 4K (the cut upscaled to 4K in H.264, because TikTok, Reels and YouTube transcode a 4K upload on a higher bitrate rung than a 1080p one, so it comes back sharper), Small (720p, fastest), Master (source size, ProRes 4444 in a MOV with PCM audio, for handing to another editor or archiving the cut) — and an Advanced panel with every axis: file name (the project's until typed over), range (the whole video, or the span from the first selected item's start to the last one's end when something is selected), format (MP4 or MOV), codec (H.264, HEVC at about half the size for newer devices, ProRes 422 HQ, ProRes 4444), resolution (Source, which matches the sharpest clip on the timeline along the project aspect with a 4K cap, preserving smaller sources; the named rungs below it; and the named rungs above it as marked upscales: ${EXPORT_RESOLUTIONS.map((r) => r.label).join(", ")}), frame rate (Source, the rate the footage plays at, read from the files; or 24, 30, 60), quality (High, Balanced, Small, or a typed bitrate in Mbps), audio (AAC or uncompressed PCM), and a captions file — the subtitle track saved as an SRT to the browser's Downloads folder (the video lands in the project's exports), one per visible language, for platforms that take their own captions. ProRes and PCM take a MOV, and ProRes sets its own rate, so the quality scale and a typed bitrate grey out. A ProRes 4444 master keeps every pixel's own color: the whole composite is built at 4:4:4 for it, so titles, captions and stickers land in the file without the color smearing a 4:2:0 delivery gives them. The other formats subsample, which is what H.264 and HEVC do at the encoder anyway. Every preset runs at the source frame rate. Best preserves source resolution, fractional frame rate, supported H.264/HEVC codec, audio sample rate, channels and bitrates. Whole files and trims copy compressed streams; compatible sequences copy video and encode joined audio. Interior video joins need matching codec configurations and keyframe boundaries. Effects, captions, additional tracks and incompatible joins render with the selected source settings. Source resolution also matches source video/audio bitrates unless a custom bitrate or ProRes is chosen; extra soundtrack audio keeps the delivery audio budget. The dialog shows the size the choice will land at. Rendered H.264 files use High profile and HEVC uses Main, with two-second keyframes; packet copies keep source encoding. An engine from an older Donkey app cannot take a range or a typed name, and the export says to update the app. Source copies preserve the media frame. Composited exports use the project aspect, with titles and subtitles burned in. Files land in the project's exports/ folder and appear in the Media tab's Exports section, where each can be previewed plain or in TikTok/Instagram/YouTube chrome with the publish metadata rendered in place, revealed in Finder, or deleted.`,+Export (open_export): one-click presets — Share (1080p H.264 MP4, plays everywhere), Best (original file settings, H.264/HEVC MP4), Social 4K (the cut upscaled to 4K in H.264, because TikTok, Reels and YouTube transcode a 4K upload on a higher bitrate rung than a 1080p one, so it comes back sharper), Small (720p, fastest), Master (source size, ProRes 4444 in a MOV with PCM audio, for handing to another editor or archiving the cut) — and an Advanced panel with every axis: file name (the project's until typed over), range (the whole video, or the span from the first selected item's start to the last one's end when something is selected), format (MP4 or MOV), codec (H.264, HEVC at about half the size for newer devices, ProRes 422 HQ, ProRes 4444), resolution (Source, which matches the sharpest clip on the timeline along the project aspect with a 4K cap, preserving smaller sources; the named rungs below it; and the named rungs above it as marked upscales: ${EXPORT_RESOLUTIONS.map((r) => r.label).join(", ")}), frame rate (Source, the rate the footage plays at, read from the files; or 24, 30, 60), quality (High, Balanced, Small, or a typed bitrate in Mbps), audio (AAC or uncompressed PCM), color (the project's SDR / HDR HLG / HDR PQ space — set_project_color writes the same setting; HDR takes HEVC Main 10 or ProRes and greys H.264 out, tagged Rec.2020 with the HLG or PQ transfer, PQ from the Mac app carrying no static metadata), and a captions file — the subtitle track saved as an SRT to the browser's Downloads folder (the video lands in the project's exports), one per visible language, for platforms that take their own captions. ProRes and PCM take a MOV, and ProRes sets its own rate, so the quality scale and a typed bitrate grey out. A ProRes 4444 master keeps every pixel's own color: the whole composite is built at 4:4:4 for it, so titles, captions and stickers land in the file without the color smearing a 4:2:0 delivery gives them. The other formats subsample, which is what H.264 and HEVC do at the encoder anyway. Every preset runs at the source frame rate. Best preserves source resolution, fractional frame rate, supported H.264/HEVC codec, audio sample rate, channels and bitrates. Whole files and trims copy compressed streams; compatible sequences copy video and encode joined audio. Interior video joins need matching codec configurations and keyframe boundaries. Effects, captions, additional tracks and incompatible joins render with the selected source settings. Source resolution also matches source video/audio bitrates unless a custom bitrate or ProRes is chosen; extra soundtrack audio keeps the delivery audio budget. The dialog shows the size the choice will land at. Rendered H.264 files use High profile and HEVC uses Main, with two-second keyframes; packet copies keep source encoding. An engine from an older Donkey app cannot take a range or a typed name, and the export says to update the app. Source copies preserve the media frame. Composited exports use the project aspect, with titles and subtitles burned in. Files land in the project's exports/ folder and appear in the Media tab's Exports section, where each can be previewed plain or in TikTok/Instagram/YouTube chrome with the publish metadata rendered in place, revealed in Finder, or deleted.`,};/** System prompt shared by all providers. */diff --git a/site/src/cut/server/ai/headlessTools.ts b/site/src/cut/server/ai/headlessTools.tsindex 939cdd8a..62672cb3 100644--- a/site/src/cut/server/ai/headlessTools.ts+++ b/site/src/cut/server/ai/headlessTools.ts@@ -13,6 +13,8 @@ import { convertToMp4 } from "../convert";import { probeDuration } from "../frames";import { deleteMedia, mediaPath, readProject, writeProject } from "../projects";import { uniqueName } from "../util";+import { withFileColors } from "../fileColor";+import { drawnLists } from "../../lib/itemKinds";// The engine's own tool executor, for a chat whose editor tab is gone: the// project doc hydrates into the same store the page uses, tools run against@@ -130,10 +132,16 @@ async function ensureOpen(projectId: string): Promise<OpenDoc | null> {) {return open;}- const assets: MediaAsset[] = (stored.assets ?? []).map((a) => ({- ...a,- url: `/api/cut/projects/${encodeURIComponent(projectId)}/media/${encodeURIComponent(a.fileName)}`,- }));+ // Footage imported before its color was read gets it here, off the file,+ // so what a tool renders and what the doc saves both read it right.+ const assets: MediaAsset[] = await withFileColors(+ (stored.assets ?? []).map((a) => ({+ ...a,+ url: `/api/cut/projects/${encodeURIComponent(projectId)}/media/${encodeURIComponent(a.fileName)}`,+ })),+ drawnLists(stored),+ (fileName) => mediaPath(projectId, fileName)+ );await useEditor.getState().openProjectDoc(projectId, stored, assets);open = { projectId, stored };return open;diff --git a/site/src/cut/server/cloud/copyQueue.test.ts b/site/src/cut/server/cloud/copyQueue.test.tsnew file mode 100644index 00000000..f34abd77--- /dev/null+++ b/site/src/cut/server/cloud/copyQueue.test.ts@@ -0,0 +1,86 @@+import { beforeEach, expect, mock, test } from "bun:test";+import { stubModule } from "@/lib/testing/stubModule";++// A copy carries each master's preview proxy under the name the doc's asset+// holds, quota-exempt. A proxy with no complete object comes off its asset, so+// the copy builds a fresh one on open.+type Obj = { fileName: string; kind: string; r2Key: string; mime: string; bytes: bigint; uploadState: string };+const objects: Obj[] = [];+const created: Record<string, unknown>[] = [];+const copied: [string, string][] = [];+let savedDoc: { assets: { fileName: string; proxy?: { fileName: string } }[] } | null = null;+const job = { id: "j", kind: "duplicate", projectId: "p", userId: "u", shareId: null, newProjectId: "n", state: "queued" };+const project = {+ id: "p",+ userId: "u",+ folderId: null,+ doc: {+ name: "Cut",+ assets: [+ { id: "a", fileName: "log.mov", type: "video", duration: 1, proxy: { fileName: "log.proxy.mp4", sizeBytes: 3 } },+ { id: "b", fileName: "raw.mov", type: "video", duration: 1, proxy: { fileName: "raw.proxy.mp4", sizeBytes: 3 } },+ ],+ clips: [],+ },+};+const matches = (o: Obj, where: { kind?: string; fileName?: { in: string[] } }) =>+ (!where.kind || o.kind === where.kind) && (!where.fileName || where.fileName.in.includes(o.fileName));+const tx = {+ cutProject: { create: mock(async ({ data }: { data: { doc: typeof savedDoc } }) => { savedDoc = data.doc; return {}; }) },+ cutMediaObject: { createMany: mock(async ({ data }: { data: Record<string, unknown>[] }) => { created.push(...data); return { count: data.length }; }) },+ cutChatThread: { createMany: mock(async () => ({ count: 0 })) },+ cutCopyJob: { update: mock(async () => ({})) },+};+const prisma = {+ cutCopyJob: {+ updateMany: mock(async () => ({ count: 1 })),+ findUnique: mock(async () => job),+ update: mock(async () => ({})),+ },+ cutProject: { findFirst: mock(async () => project) },+ cutMediaObject: { findMany: mock(async ({ where }: { where: Parameters<typeof matches>[1] }) => objects.filter((o) => matches(o, where))) },+ cutChatThread: { findMany: mock(async () => []) },+ $transaction: mock(async (fn: (t: typeof tx) => Promise<unknown>) => fn(tx)),+};+await stubModule<typeof import("@/lib/prisma")>("@/lib/prisma", import.meta.url, { prisma: prisma as never });+await stubModule<typeof import("./r2")>("./r2", import.meta.url, {+ copy: (async (from: string, to: string) => { copied.push([from, to]); }) as never,+ projectMediaKey: ((userId: string, projectId: string, fileName: string) => `cut/${userId}/${projectId}/${fileName}`) as never,+});+const added: number[] = [];+await stubModule<typeof import("./usage")>("./usage", import.meta.url, {+ quotaCheck: (async () => null) as never,+ addUsage: (async (_tx: unknown, _user: string, delta: number) => { added.push(delta); }) as never,+});+const { executeCopyJob } = await import("./copyQueue");++const obj = (fileName: string, kind: string, bytes: number): Obj =>+ ({ fileName, kind, r2Key: `cut/u/p/${fileName}`, mime: "video/mp4", bytes: BigInt(bytes), uploadState: "complete" });++beforeEach(() => {+ objects.splice(0, objects.length, obj("log.mov", "media", 100), obj("raw.mov", "media", 50), obj("log.proxy.mp4", "proxy", 7));+ created.splice(0);+ copied.splice(0);+ added.splice(0);+ savedDoc = null;+});++test("a duplicate copies each built proxy beside its master, quota-exempt", async () => {+ expect((await executeCopyJob("j")).status).toBe(200);+ expect(copied.filter(([from]) => from.endsWith(".proxy.mp4"))).toEqual([["cut/u/p/log.proxy.mp4", "cut/u/n/log.proxy.mp4"]]);+ expect(created.find((r) => r.fileName === "log.proxy.mp4")).toMatchObject({+ kind: "proxy",+ quotaExempt: true,+ projectId: "n",+ r2Key: "cut/u/n/log.proxy.mp4",+ });+ // Only the masters count toward the new owner's storage.+ expect(added).toEqual([150]);+ expect(savedDoc?.assets.find((a) => a.fileName === "log.mov")?.proxy?.fileName).toBe("log.proxy.mp4");+});++test("an asset whose proxy object is missing lands without one", async () => {+ await executeCopyJob("j");+ expect(savedDoc?.assets.find((a) => a.fileName === "raw.mov")?.proxy).toBeUndefined();+ expect(created.some((r) => r.fileName === "raw.proxy.mp4")).toBe(false);+});diff --git a/site/src/cut/server/cloud/copyQueue.ts b/site/src/cut/server/cloud/copyQueue.tsindex 18350c2e..abfa24e7 100644--- a/site/src/cut/server/cloud/copyQueue.ts+++ b/site/src/cut/server/cloud/copyQueue.ts@@ -86,6 +86,9 @@ interface CopySource {name: string;folderId: string | null;media: MediaRow[];+ /** Preview proxies of the copied masters, under the names the doc's assets+ * carry. Quota-exempt, so they add nothing to `added`. */+ proxies: MediaRow[];chats: { id: string; data: unknown }[];added: number;}@@ -108,15 +111,44 @@ function completeMedia(const mediaBytes = (media: MediaRow[]) => media.reduce((sum, m) => sum + Number(m.bytes), 0);+/** The copy's proxies and the doc that names them. A proxy travels with its+ * master: its object is copied under the same name, and an asset whose master+ * or proxy has no complete object drops its `proxy`, so the copy's first open+ * builds a fresh one. */+async function withProxies(+ ownerId: string,+ projectId: string,+ doc: ProjectDoc,+ media: MediaRow[]+): Promise<{ doc: ProjectDoc; proxies: MediaRow[] }> {+ if (!Array.isArray(doc.assets)) return { doc, proxies: [] };+ const masters = new Set(media.map((m) => m.fileName));+ const wanted = doc.assets.flatMap((a) => (a.proxy && masters.has(a.fileName) ? [a.proxy.fileName] : []));+ const proxies = wanted.length+ ? await prisma.cutMediaObject.findMany({+ where: { userId: ownerId, projectId, kind: "proxy", uploadState: "complete", fileName: { in: wanted } },+ })+ : [];+ const built = new Set(proxies.map((p) => p.fileName));+ const assets = doc.assets.map((a) => {+ if (!a.proxy || (masters.has(a.fileName) && built.has(a.proxy.fileName))) return a;+ const rest = { ...a };+ delete rest.proxy;+ return rest;+ });+ return { doc: { ...doc, assets }, proxies };+}+async function copyPlan(share: ShareRow) {const features = normalizeFeatures(share.features);const row = await prisma.cutProject.findFirst({where: { id: share.projectId, userId: share.userId },});if (!row) return null;- const doc = filterDocForShare(row.doc as unknown as ProjectDoc, features);- const media = await completeMedia(share.userId, share.projectId, doc.assets.map((a) => a.fileName));- return { features, doc, media, added: mediaBytes(media) };+ const filtered = filterDocForShare(row.doc as unknown as ProjectDoc, features);+ const media = await completeMedia(share.userId, share.projectId, filtered.assets.map((a) => a.fileName));+ const { doc, proxies } = await withProxies(share.userId, share.projectId, filtered, media);+ return { features, doc, media, proxies, added: mediaBytes(media) };}/** A share copy's source: access re-checked at drain time, doc filtered to@@ -149,6 +181,7 @@ async function shareSource(job: { shareId: string | null; userId: string }): Proname: plan.doc.name,folderId: null,media: plan.media,+ proxies: plan.proxies,chats,added: plan.added,};@@ -168,8 +201,8 @@ async function duplicateSource(job: {? await prisma.cutProject.findFirst({ where: { id: job.projectId, userId: job.userId } }): null;if (!row) return "The project was deleted.";- const doc = row.doc as unknown as ProjectDoc;const media = await completeMedia(job.userId, row.id);+ const { doc, proxies } = await withProxies(job.userId, row.id, row.doc as unknown as ProjectDoc, media);const chats = await prisma.cutChatThread.findMany({where: { userId: job.userId, projectId: row.id },select: { id: true, data: true },@@ -183,6 +216,7 @@ async function duplicateSource(job: {name: `${doc.name} copy`,folderId: row.folderId,media,+ proxies,chats,added: mediaBytes(media),};@@ -333,7 +367,7 @@ export async function executeCopyJob(jobId: string): Promise<Response> {// R2 copies run before the transaction (network I/O can't sit inside one)// but are idempotent: same source to the same deterministic destination// key, so a redelivery just overwrites with identical bytes.- for (const m of src.media) {+ for (const m of [...src.media, ...src.proxies]) {await copy(m.r2Key, projectMediaKey(job.userId, newProjectId, m.fileName));}@@ -368,6 +402,21 @@ export async function executeCopyJob(jobId: string): Promise<Response> {})),});}+ if (src.proxies.length > 0) {+ await tx.cutMediaObject.createMany({+ data: src.proxies.map((m) => ({+ userId: job.userId,+ projectId: newProjectId,+ r2Key: projectMediaKey(job.userId, newProjectId, m.fileName),+ fileName: m.fileName,+ mime: m.mime,+ bytes: m.bytes,+ kind: "proxy",+ uploadState: "complete",+ quotaExempt: true,+ })),+ });+ }if (src.chats.length > 0) {// Thread ids are client-generated and keyed (projectId, id), so the// copies keep their ids under the new project.diff --git a/site/src/cut/server/cloud/gc.test.ts b/site/src/cut/server/cloud/gc.test.tsnew file mode 100644index 00000000..83cea451--- /dev/null+++ b/site/src/cut/server/cloud/gc.test.ts@@ -0,0 +1,15 @@+import { expect, test } from "bun:test";+import { proxyNamesIn } from "./gc";++test("a stored document names the proxies its assets carry, and nothing else", () => {+ const names = proxyNamesIn({+ assets: [+ { fileName: "IMG_1.MOV", proxy: { fileName: "IMG_1.proxy.mp4", sizeBytes: 5 } },+ { fileName: "b.mp4" },+ { fileName: "c.MOV", proxy: {} },+ ],+ });+ expect([...names]).toEqual(["IMG_1.proxy.mp4"]);+ expect(proxyNamesIn(null).size).toBe(0);+ expect(proxyNamesIn({}).size).toBe(0);+});diff --git a/site/src/cut/server/cloud/gc.ts b/site/src/cut/server/cloud/gc.tsindex 6ba3d1c5..529fbccb 100644--- a/site/src/cut/server/cloud/gc.ts+++ b/site/src/cut/server/cloud/gc.ts@@ -54,6 +54,34 @@ const HLS_PENDING_TIMEOUT_MS = 6 * 60 * 60 * 1000;type ReclaimPlan = { projects: string[]; assets: string[]; bytes: number };+/** The proxy file names a stored document's assets carry — what keeps a+ * kind "proxy" object alive. */+export function proxyNamesIn(doc: unknown): Set<string> {+ const assets = (doc as { assets?: { proxy?: { fileName?: string } }[] } | null)?.assets ?? [];+ return new Set(assets.flatMap((a) => (a.proxy?.fileName ? [a.proxy.fileName] : [])));+}++/** Delete stored objects and their rows, one transaction per account.+ * Quota-exempt rows never added usage, so only the counted ones subtract. */+async function dropMediaRows(+ rows: { id: string; userId: string; r2Key: string; bytes: bigint; quotaExempt: boolean }[]+): Promise<void> {+ const byUser = new Map<string, typeof rows>();+ for (const o of rows) {+ const list = byUser.get(o.userId) ?? [];+ list.push(o);+ byUser.set(o.userId, list);+ }+ for (const [userId, list] of byUser) {+ const counted = list.filter((r) => !r.quotaExempt);+ await prisma.$transaction(async (tx) => {+ await tx.cutMediaObject.deleteMany({ where: { id: { in: list.map((r) => r.id) } } });+ await addUsage(tx, userId, -counted.reduce((sum, r) => sum + Number(r.bytes), 0));+ });+ await del(list.map((r) => r.r2Key));+ }+}+/*** Drop ladder versions a project has moved on from, and the leftovers of* renders that died partway.@@ -358,21 +386,27 @@ export async function runGc(): Promise<Response> {referenced.set(job.projectId, files);}const orphans = mediaCandidates.filter((c) => !referenced.get(c.projectId!)?.has(c.fileName));- const byUser = new Map<string, typeof orphans>();- for (const o of orphans) {- const list = byUser.get(o.userId) ?? [];- list.push(o);- byUser.set(o.userId, list);- }- for (const [userId, rows] of byUser) {- // Quota-exempt rows never added usage, so only the counted ones subtract.- const counted = rows.filter((r) => !r.quotaExempt);- await prisma.$transaction(async (tx) => {- await tx.cutMediaObject.deleteMany({ where: { id: { in: rows.map((r) => r.id) } } });- await addUsage(tx, userId, -counted.reduce((sum, r) => sum + Number(r.bytes), 0));- });- await del(rows.map((r) => r.r2Key));- }+ await dropMediaRows(orphans);++ // Preview proxies no asset names any more — the master's asset was deleted+ // by a client that never got to drop the proxy, or the doc is gone. An+ // asset carries its proxy's file name, so that is the reference.+ const proxyCandidates = await prisma.cutMediaObject.findMany({+ where: {+ kind: "proxy",+ uploadState: "complete",+ projectId: { not: null },+ updatedAt: { lt: new Date(Date.now() - ORPHAN_MAX_AGE_MS) },+ },+ select: { id: true, userId: true, projectId: true, fileName: true, r2Key: true, bytes: true, quotaExempt: true },+ });+ const proxyProjects = await prisma.cutProject.findMany({+ where: { id: { in: [...new Set(proxyCandidates.map((c) => c.projectId!))] } },+ select: { id: true, doc: true },+ });+ const referencedProxies = new Map(proxyProjects.map((p) => [p.id, proxyNamesIn(p.doc)]));+ const orphanProxies = proxyCandidates.filter((c) => !referencedProxies.get(c.projectId!)?.has(c.fileName));+ await dropMediaRows(orphanProxies);// Retired preview revisions get the same grace as other unreferenced media.// The current preview remains available for an idle project indefinitely.@@ -452,6 +486,7 @@ export async function runGc(): Promise<Response> {return Response.json({pendingObjects: pending.length,orphanedMedia: orphans.length,+ orphanedProxies: orphanProxies.length,inferenceScratch: scratch.length,staleOverlays: overlays,renderJobs: jobs.count,diff --git a/site/src/cut/server/cloud/jobs.ts b/site/src/cut/server/cloud/jobs.tsindex 9b42b8d6..8251cb0f 100644--- a/site/src/cut/server/cloud/jobs.ts+++ b/site/src/cut/server/cloud/jobs.ts@@ -14,6 +14,10 @@ import { containerOfName, deliveryContainer, exportBaseName, specMediaFiles, typimport { addUsage, outputByteCeiling, quotaCheck } from "./usage";import { caught, err, redirect } from "./util";+/** A master's file name without its extension: what its proxy's name starts+ * with (server/proxy.ts `proxyNameFor`). */+const proxyStem = (fileName: string) => fileName.replace(/\.[^./\\]+$/, "") || "media";+/** How long finished jobs stay in the export-jobs feed — the engine's registry* keeps a bounded terminal backlog; the cloud keeps a day. */const FEED_WINDOW_MS = 24 * 60 * 60 * 1000;@@ -868,7 +872,47 @@ export const jobsCloud = {}},- /** Generic job poll for non-export kinds (import_url, convert). */+ /** Queue a preview proxy of a ProRes master: the worker builds it and+ * registers it beside the master as a quota-exempt object. A proxy already+ * built answers at once, and a job already on its way answers with that+ * job, so a project copied to the cloud and then opened queues one. */+ async proxy(userId: string, projectId: string, req: Request) {+ try {+ const { file } = (await req.json()) as { file?: string };+ if (!file) return err("file is required.", 400);+ if (!(await getProject(userId, projectId))) return err("Project not found.", 404);+ const source = await prisma.cutMediaObject.findFirst({+ where: { userId, projectId, fileName: file, kind: "media", uploadState: "complete" },+ select: { id: true },+ });+ if (!source) return err("Media file missing from project.", 404);+ const built = await prisma.cutMediaObject.findFirst({+ where: { userId, projectId, kind: "proxy", uploadState: "complete", fileName: { startsWith: `${proxyStem(file)}.proxy` } },+ select: { fileName: true, bytes: true },+ orderBy: { createdAt: "desc" },+ });+ if (built) return Response.json({ fileName: built.fileName, sizeBytes: Number(built.bytes) });+ const running = await prisma.cutRenderJob.findFirst({+ where: { userId, projectId, kind: "proxy", state: { in: ["queued", "running"] }, spec: { path: ["file"], equals: file } },+ select: { id: true },+ });+ if (running) {+ wakeRenderWorker();+ return Response.json({ jobId: running.id });+ }+ const capped = await renderJobCheck(userId);+ if (capped) return capped;+ const row = await prisma.cutRenderJob.create({+ data: { userId, projectId, kind: "proxy", spec: { file } as unknown as Prisma.InputJsonValue },+ });+ wakeRenderWorker();+ return Response.json({ jobId: row.id });+ } catch (e) {+ return caught(e, "Could not make the preview proxy.");+ }+ },++ /** Generic job poll for non-export kinds (import_url, convert, proxy). */async status(userId: string, jobId: string) {const row = await findJob(userId, jobId);if (!row) return err("Unknown job.", 404);diff --git a/site/src/cut/server/cloud/library.ts b/site/src/cut/server/cloud/library.tsindex 70495348..543ed471 100644--- a/site/src/cut/server/cloud/library.ts+++ b/site/src/cut/server/cloud/library.ts@@ -21,7 +21,9 @@ import { MEDIA_REDIRECT_HEADERS, mediaObjectUrl, mediaUrlLifetime } from "./mediimport { getProject, takenMediaNames } from "./projects";import { copy, del, head, libraryKey, presignPut, projectMediaKey } from "./r2";import { addUsage, quotaCheck } from "./usage";-import { caught, decodeFileParam, dedupeName, err, HttpResponseError, inspirationFolderId, redirect, safeFileName, typeOf } from "./util";+import { libraryTypeOf } from "@/cut/lib/libraryFileType";+import type { AssetType } from "@/cut/lib/types";+import { caught, decodeFileParam, dedupeName, err, HttpResponseError, inspirationFolderId, redirect, safeFileName } from "./util";/** Cap on one signed-URL batch, matching the project media batch. */const PRESIGN_GET_BATCH_MAX = 500;@@ -36,7 +38,7 @@ interface AssetMeta {* for the file's own name wherever the asset is shown. Written once, by* cloud/clipTitle.ts. */title?: string;- type?: "video" | "audio" | "image" | "font";+ type?: AssetType;duration?: number;width?: number;height?: number;@@ -44,6 +46,11 @@ interface AssetMeta {/** File name of the source's cover image, an object of its own under this* account's library prefix. */posterFile?: string;+ /** A linked item's identity: the hash every project names it by. The+ * page computes it before the upload, so a sync never reads the bytes. */+ contentKey?: string;+ /** What kind of table a LUT holds. */+ lut?: { kind: "1d" | "3d" | "shaper+3d"; size: number };/** How the asset entered the account from the iOS app: a phone camera* recording (the desktop's Camera Roll) or an inspiration item. */origin?: "camera" | "inspiration";@@ -58,16 +65,17 @@ interface TemplateDoc {texts: unknown[];cues: unknown[];sound?: LibraryTemplate["sound"];+ grade?: LibraryTemplate["grade"];transitions?: unknown[];stickers?: unknown[];captions?: unknown;project?: unknown;}-/** A template with nothing on it saves nothing; a sound preset is a template- * carrying only its treatment. */+/** A template with nothing on it saves nothing; a sound preset or a saved+ * grade is a template carrying only its treatment. */const templateEmpty = (input: TemplateInput) =>- !input.media?.length && !input.texts?.length && !input.cues?.length && !input.sound;+ !input.media?.length && !input.texts?.length && !input.cues?.length && !input.sound && !input.grade;type MediaObjectRow = {id: string;@@ -96,7 +104,7 @@ export function assetView(fileName: obj.fileName,...(meta.originalFile ? { originalFile: meta.originalFile } : {}),name: meta.name ?? obj.fileName,- type: meta.type ?? typeOf(obj.fileName) ?? "video",+ type: meta.type ?? libraryTypeOf(obj.fileName) ?? "video",duration: meta.duration ?? 0,...(meta.width ? { width: meta.width, height: meta.height } : {}),addedAt: row.createdAt.getTime(),@@ -105,6 +113,8 @@ export function assetView(...(meta.posterFile ? { posterFile: meta.posterFile } : {}),...(meta.title ? { title: meta.title } : {}),...(meta.origin ? { origin: meta.origin } : {}),+ ...(meta.contentKey ? { contentKey: meta.contentKey } : {}),+ ...(meta.lut ? { lut: meta.lut } : {}),};}@@ -127,7 +137,7 @@ export function templateView(row: {texts: doc.texts ?? [],cues: doc.cues ?? [],...(doc.sound ? { sound: doc.sound } : {}),- ...(templateExtras(doc) as Pick<LibraryTemplate, "transitions" | "stickers" | "captions" | "project">),+ ...(templateExtras(doc) as Pick<LibraryTemplate, "transitions" | "stickers" | "captions" | "project" | "grade">),};}@@ -367,7 +377,7 @@ export const libraryCloud = {if (!body.fileName || typeof body.bytes !== "number" || body.bytes <= 0) {return err("fileName and bytes are required.", 400);}- if (!typeOf(body.fileName)) return err("Unsupported file type.", 400);+ if (!libraryTypeOf(body.fileName)) return err("Unsupported file type.", 400);// A resumed upload already holds its claim: the client kept the bytes// (the iOS app's journal) and asks for a fresh URL under the same name.// A claim that completed in the meantime reports done and uploads@@ -492,7 +502,7 @@ export const libraryCloud = {folderId: destFolder,meta: {name: meta?.name ?? obj.fileName,- type: meta?.type ?? typeOf(obj.fileName) ?? "video",+ type: meta?.type ?? libraryTypeOf(obj.fileName) ?? "video",duration: meta?.duration ?? 0,...(meta?.width? { width: meta.width, height: meta.height }@@ -504,6 +514,8 @@ export const libraryCloud = {...(meta?.origin === "camera" || meta?.origin === "inspiration"? { origin: meta.origin }: {}),+ ...(typeof meta?.contentKey === "string" ? { contentKey: meta.contentKey } : {}),+ ...(meta?.lut ? { lut: meta.lut } : {}),} as unknown as Prisma.InputJsonValue,},});@@ -570,7 +582,7 @@ export const libraryCloud = {mediaObjectId: obj.id,meta: {name: name || fileName,- type: docAsset?.type ?? typeOf(dest) ?? "video",+ type: docAsset?.type ?? libraryTypeOf(dest) ?? "video",duration: docAsset?.duration ?? 0,...(docAsset?.width? { width: docAsset.width, height: docAsset.height }diff --git a/site/src/cut/server/cloud/libraryUpload.ts b/site/src/cut/server/cloud/libraryUpload.tsindex 7920489c..e6f1340c 100644--- a/site/src/cut/server/cloud/libraryUpload.ts+++ b/site/src/cut/server/cloud/libraryUpload.ts@@ -1,5 +1,5 @@import { libraryUploadId, libraryUploadSchema } from "@/cut/lib/libraryUpload";-import { typeOf as libraryTypeOf } from "./util";+import { libraryTypeOf } from "@/cut/lib/libraryFileType";import { assetView } from "@/cut/server/cloud/library";import { renderJobCheck } from "@/cut/server/cloud/limits";import { head } from "@/cut/server/cloud/r2";diff --git a/site/src/cut/server/cloud/media.ts b/site/src/cut/server/cloud/media.tsindex 7ffd3b6d..598a6c29 100644--- a/site/src/cut/server/cloud/media.ts+++ b/site/src/cut/server/cloud/media.ts@@ -168,7 +168,7 @@ export const mediaCloud = {const rows = await prisma.cutMediaObject.findMany({where: {userId,- kind: "media",+ kind: { in: ["media", "proxy"] },projectId: { in: [...new Set(wanted.map((i) => i.projectId!))] },},select: { projectId: true, fileName: true, updatedAt: true },diff --git a/site/src/cut/server/cloud/projects.ts b/site/src/cut/server/cloud/projects.tsindex c33cc5c7..fc7096f3 100644--- a/site/src/cut/server/cloud/projects.ts+++ b/site/src/cut/server/cloud/projects.ts@@ -43,7 +43,7 @@ export async function getProject(userId: string, id: string): Promise<ProjectRow* their name too, so a racing presign can't hand out the same one. */export async function takenMediaNames(userId: string, projectId: string): Promise<Set<string>> {const rows = await prisma.cutMediaObject.findMany({- where: { userId, projectId, kind: "media" },+ where: { userId, projectId, kind: { in: ["media", "proxy"] } },select: { fileName: true },});return new Set(rows.map((r) => r.fileName));@@ -385,7 +385,7 @@ export const projectsCloud = {try {const fileName = decodeFileParam(file);const row = await prisma.cutMediaObject.findFirst({- where: { userId, projectId: id, kind: "media", fileName },+ where: { userId, projectId: id, kind: { in: ["media", "proxy"] }, fileName },select: { updatedAt: true },});if (!row) return err("Not found.", 404);@@ -404,7 +404,7 @@ export const projectsCloud = {try {const fileName = decodeFileParam(file);const row = await prisma.cutMediaObject.findFirst({- where: { userId, projectId: id, kind: "media", fileName },+ where: { userId, projectId: id, kind: { in: ["media", "proxy"] }, fileName },});if (row) {await prisma.$transaction(async (tx) => {diff --git a/site/src/cut/server/cloud/routes.ts b/site/src/cut/server/cloud/routes.tsindex 8e85e774..20cd1828 100644--- a/site/src/cut/server/cloud/routes.ts+++ b/site/src/cut/server/cloud/routes.ts@@ -71,6 +71,7 @@ const CUT_CLOUD_ROUTES: CloudRoute[] = [{ method: "POST", path: "/api/cut-cloud/projects/:id/media/complete", handler: (r, u) => mediaCloud.complete(u, r) },{ method: "POST", path: "/api/cut-cloud/projects/:id/import-url", handler: (r, u, p) => jobsCloud.importUrl(u, p.id, r) },{ method: "POST", path: "/api/cut-cloud/projects/:id/convert", handler: (r, u, p) => jobsCloud.convert(u, p.id, r) },+ { method: "POST", path: "/api/cut-cloud/projects/:id/proxy", handler: (r, u, p) => jobsCloud.proxy(u, p.id, r) },{ method: "POST", path: "/api/cut-cloud/media/presign-get", handler: (r, u) => mediaCloud.presignGetBatch(u, r) },{ method: "GET", path: "/api/cut-cloud/library/shares/:kind/:id", handler: (r, u, p) => librarySharing.manage(r, u, p.kind, p.id) },diff --git a/site/src/cut/server/cloud/sharedView.test.ts b/site/src/cut/server/cloud/sharedView.test.tsindex 382e1845..95fd0406 100644--- a/site/src/cut/server/cloud/sharedView.test.ts+++ b/site/src/cut/server/cloud/sharedView.test.ts@@ -1,7 +1,7 @@import { describe, expect, test } from "bun:test";import type { ProjectDoc, ShareFeatures } from "@/cut/lib/types";-import { filterDocForShare } from "./sharedView";+import { filterDocForShare, sharedFileNames } from "./sharedView";// The doc a viewer receives is also the copy's manifest: a share copy moves the// media of exactly the assets that survive this filter, so what a shared project@@ -95,4 +95,15 @@ describe("filterDocForShare", () => {]);expect(ids(filterDocForShare(captioned, features()))).toEqual(["placed"]);});++ test("a shared master's preview proxy is fetchable with it", () => {+ const proxied = {+ ...doc,+ assets: [+ { ...doc.assets[1], proxy: { fileName: "placed.proxy.mp4", sizeBytes: 5 } },+ { ...doc.assets[0], proxy: { fileName: "imported.proxy.mp4", sizeBytes: 5 } },+ ],+ } as unknown as ProjectDoc;+ expect([...sharedFileNames(proxied, features())].sort()).toEqual(["placed.mp4", "placed.proxy.mp4"]);+ });});diff --git a/site/src/cut/server/cloud/sharedView.ts b/site/src/cut/server/cloud/sharedView.tsindex a418b549..6f3f93cf 100644--- a/site/src/cut/server/cloud/sharedView.ts+++ b/site/src/cut/server/cloud/sharedView.ts@@ -60,7 +60,7 @@ async function ownerProject(share: ShareRow) {async function mediaVersions(share: ShareRow, fileNames: string[]): Promise<Map<string, string>> {if (!fileNames.length) return new Map();const rows = await prisma.cutMediaObject.findMany({- where: { userId: share.userId, projectId: share.projectId, kind: "media", fileName: { in: fileNames } },+ where: { userId: share.userId, projectId: share.projectId, kind: { in: ["media", "proxy"] }, fileName: { in: fileNames } },select: { fileName: true, updatedAt: true },});return new Map(rows.map((r) => [r.fileName, String(r.updatedAt.getTime())]));@@ -130,10 +130,18 @@ export function filterDocForShare(doc: ProjectDoc, features: ShareFeatures): Proreturn filtered;}+/** The files a viewer may fetch: each allowed asset's master and, when it has+ * one, its preview proxy, which is what the viewer's preview decodes. */+export function sharedFileNames(doc: ProjectDoc, features: ShareFeatures): Set<string> {+ return new Set(+ allowedAssets(doc, features).flatMap((a) => (a.proxy ? [a.fileName, a.proxy.fileName] : [a.fileName]))+ );+}+async function allowedFileNames(share: ShareRow, features: ShareFeatures): Promise<Set<string>> {const row = await ownerProject(share);if (!row) return new Set();- return new Set(allowedAssets(row.doc as unknown as ProjectDoc, features).map((a) => a.fileName));+ return sharedFileNames(row.doc as unknown as ProjectDoc, features);}export const sharedView = {diff --git a/site/src/cut/server/cloud/util.ts b/site/src/cut/server/cloud/util.tsindex a25b39b9..a5df16fb 100644--- a/site/src/cut/server/cloud/util.ts+++ b/site/src/cut/server/cloud/util.ts@@ -72,16 +72,3 @@ export function dedupeName(base: string, taken: ReadonlySet<string>): string {* every writer — the complete route, the URL-import worker — upserts the same* row instead of racing to create one. An ordinary folder otherwise. */export const inspirationFolderId = (userId: string) => `inspiration-${userId}`;--const VIDEO_RE = /\.(mp4|mov|m4v|webm|mkv)$/i;-const AUDIO_RE = /\.(mp3|m4a|aac|wav|ogg|flac)$/i;-const IMAGE_RE = /\.(png|jpe?g|webp|gif|avif|bmp)$/i;-const FONT_RE = /\.(ttf|otf|woff2?)$/i;--export function typeOf(fileName: string): "video" | "audio" | "image" | "font" | null {- if (VIDEO_RE.test(fileName)) return "video";- if (AUDIO_RE.test(fileName)) return "audio";- if (IMAGE_RE.test(fileName)) return "image";- if (FONT_RE.test(fileName)) return "font";- return null;-}diff --git a/site/src/cut/server/convert.ts b/site/src/cut/server/convert.tsindex 83699d15..5dd917ea 100644--- a/site/src/cut/server/convert.ts+++ b/site/src/cut/server/convert.ts@@ -1,7 +1,7 @@import { spawn } from "node:child_process";-import { h264Encoder, runFfmpeg, sdrConvert, vtQuality, type RenderHandle } from "./exportPipeline";+import { h264Encoder, runFfmpeg, vtQuality, type RenderHandle } from "./exportPipeline";import { assertGraphSafe } from "./filterGraph";-import { videoColorInfo, videoDimensions } from "./util";+import { videoDimensions } from "./util";/*** Re-wrapping one media file as an MP4 every player and every browser opens.@@ -11,7 +11,10 @@ import { videoColorInfo, videoDimensions } from "./util";* container untouched, which costs a read and a write and loses nothing. A* file whose picture is HEVC or ProRes, or whose sound is the raw PCM a phone* and a camera write into QuickTime, is re-encoded, one stream at a time, so- * a .mov with H.264 picture and PCM sound only pays for its audio.+ * a .mov with H.264 picture and PCM sound only pays for its audio. A+ * re-encode keeps the picture's code values and its color tags: what the+ * file means is settled at import (the asset's color) and rendered from+ * there, never folded here.** The engine calls this on the Mac's own ffmpeg; the render worker calls it in* the container. Both hand it a `RenderHandle`, which is what carries a cancel@@ -45,11 +48,10 @@ const MP4_EXT = /\.(mp4|m4v)$/i;export const fitsAlready = (file: string,codecs: { video?: string; audio?: string; remux?: boolean; videoNeedsEncoding?: boolean },- work: { shrink: boolean; sdr: boolean }+ work: { shrink: boolean }) =>MP4_EXT.test(file) &&!work.shrink &&- !work.sdr &&!codecs.remux &&!codecs.videoNeedsEncoding &&(!codecs.video || KEEPS_VIDEO.has(codecs.video)) &&@@ -124,11 +126,9 @@ export async function convertToMp4(const cap = opts.maxHeight && opts.maxHeight > 0 ? Math.round(opts.maxHeight) : 0;const shrink = !!(cap && dims && dims.height > cap);- const color = codecs.video ? await videoColorInfo(src) : null;- const sdr = sdrConvert(color, "yuv420p");- const transcodedVideo = !!codecs.video && (codecs.videoNeedsEncoding || shrink || !!sdr);+ const transcodedVideo = !!codecs.video && (codecs.videoNeedsEncoding || shrink);const transcodedAudio = !!codecs.audio && !KEEPS_AUDIO.has(codecs.audio);- if (fitsAlready(src, codecs, { shrink, sdr: !!sdr })) {+ if (fitsAlready(src, codecs, { shrink })) {return {transcodedVideo: false,transcodedAudio: false,@@ -145,9 +145,7 @@ export async function convertToMp4(} else {// Even dimensions: H.264 in 4:2:0 has no odd sizes, and the scale filter// is where an odd source height would otherwise land.- const scale = shrink ? `scale=-2:${cap - (cap % 2)},` : "";- const chain = `${sdr}${scale}`.replace(/,$/, "");- if (chain) video.push("-vf", assertGraphSafe(chain));+ if (shrink) video.push("-vf", assertGraphSafe(`scale=-2:${cap - (cap % 2)}`));const enc = await h264Encoder();video.push(...(enc === "libx264"diff --git a/site/src/cut/server/exportPipeline.e2e.test.ts b/site/src/cut/server/exportPipeline.e2e.test.tsindex b0033930..1ba56d64 100644--- a/site/src/cut/server/exportPipeline.e2e.test.ts+++ b/site/src/cut/server/exportPipeline.e2e.test.ts@@ -20,7 +20,7 @@ import { runExport, type ExportSpec, type RenderHandle } from "./exportPipeline"// filter and every `overlay` negotiates a different pixel family than the// 4:2:0 the H.264 file is built in.const DELIVERIES = [- { name: "an H.264 MP4", ext: "mp4", codec: "h264", pixFmt: "yuv420p", over: {} },+ { name: "an H.264 MP4", ext: "mp4", codec: "h264", pixFmt: "yuv420p", trc: "bt709", over: {} },{// ProRes 4444's bitstream carries twelve bits, so the file reads back as// yuv444p12le whatever the encoder was handed.@@ -28,14 +28,28 @@ const DELIVERIES = [ext: "mov",codec: "prores",pixFmt: "yuv444p12le",+ trc: "bt709",over: { codec: "prores4444", container: "mov", audioCodec: "pcm" },},+ {+ // An HDR delivery composites at ten bits; every alpha segment (the+ // masked keyed clip, the subject matte, the masked overlay) must reach+ // the Main 10 file without an 8-bit hop.+ name: "an HLG HEVC file",+ ext: "mp4",+ codec: "hevc",+ pixFmt: "yuv420p10le",+ trc: "arib-std-b67",+ over: { codec: "hevc", colorSpace: "hlg" },+ },] as const satisfies readonly {name: string;ext: string;codec: string;/** What the finished file decodes as. */pixFmt: string;+ /** The transfer the file's header signals. */+ trc: string;over: Partial<ExportSpec>;}[];@@ -56,7 +70,7 @@ const probe = (file: string) => {["-v", "error","-show_entries", "format=duration",- "-show_entries", "stream=codec_type,codec_name,pix_fmt,width,height",+ "-show_entries", "stream=codec_type,codec_name,pix_fmt,width,height,color_transfer","-of", "json",file,],@@ -65,7 +79,14 @@ const probe = (file: string) => {if (r.status !== 0) throw new Error(`ffprobe failed:\n${r.stderr}`);return JSON.parse(r.stdout) as {format: { duration: string };- streams: { codec_type: string; codec_name: string; pix_fmt?: string; width?: number; height?: number }[];+ streams: {+ codec_type: string;+ codec_name: string;+ pix_fmt?: string;+ width?: number;+ height?: number;+ color_transfer?: string;+ }[];};};@@ -221,6 +242,9 @@ for (const delivery of DELIVERIES) describe("export pipeline end to end", () =>// The chroma the composite was built in is the chroma the file holds:// 4:4:4 all the way through for the master, 4:2:0 for the MP4.expect(video?.pix_fmt).toBe(delivery.pixFmt);+ // The header signals the delivery's transfer whatever the container:+ // a MOV takes it from the frames, an MP4 from the bitstream.+ expect(video?.color_transfer).toBe(delivery.trc);expect(meta.streams.some((s) => s.codec_type === "audio")).toBe(true);} finally {await rm(mediaDir, { recursive: true, force: true });diff --git a/site/src/cut/server/exportPipeline.test.ts b/site/src/cut/server/exportPipeline.test.tsindex e7f6677f..58074ba3 100644--- a/site/src/cut/server/exportPipeline.test.ts+++ b/site/src/cut/server/exportPipeline.test.ts@@ -1,8 +1,12 @@import { describe, expect, test } from "bun:test";+import path from "node:path";import { retimeOf } from "@donkeycut/effects-kit";import {+ colorParamsFilter,+ colorTagArgs,narrowSpecToRange,runExport,+ videoCodecArgs,type ExportPipelineIO,type ExportSpec,type RenderHandle,@@ -13,21 +17,33 @@ import {// software encoders, and every ffmpeg run is captured for the assertions./** Every ffmpeg run the pipeline made for a spec, in order; the graph is the* one carrying `-filter_complex`. */+/** Every file the pipeline wrote in the last run, in order. */+let written: { file: string; data: string }[] = [];+/** Files staged in the job dir by base name, as an upload would leave them. */+const stagedFiles = new Map<string, string>();+/** Source sizes the probe reports, by staged path; absent probes as unknown. */+const probedDims = new Map<string, { width: number; height: number }>();+const runsFor = async (over: Partial<ExportSpec>): Promise<string[][]> => {const ffmpegCalls: string[][] = [];+ written = [];// Seconds each turned file was asked to produce, summed off the `-t` of the// chunk runs that wrote its pieces, so the bake reads back a whole file.const produced = new Map<string, number>();const io: ExportPipelineIO = {exportSourceFiles: async () => false,stat: (async () => ({ isFile: () => true })) as unknown as ExportPipelineIO["stat"],- writeFile: (async () => {}) as unknown as ExportPipelineIO["writeFile"],- readFile: (async () => new Uint8Array(0)) as unknown as ExportPipelineIO["readFile"],+ writeFile: (async (file: string, data: string) => {+ written.push({ file, data });+ }) as unknown as ExportPipelineIO["writeFile"],+ readFile: (async (file: string) => {+ return new TextEncoder().encode(stagedFiles.get(path.basename(file)) ?? "");+ }) as unknown as ExportPipelineIO["readFile"],unlink: (async () => {}) as unknown as ExportPipelineIO["unlink"],hasStream: async () => true,audioChannels: async (file) => (file.includes("mono") ? 1 : 2),- videoColorInfo: async () => null,videoDecodeCost: async () => null,+ videoDimensions: async (file) => probedDims.get(file) ?? null,mediaDuration: async (file) => produced.get(file) ?? 0,videoEncoder: async (codec) =>codec === "hevc" ? "libx265" : codec.startsWith("prores") ? "prores_ks" : "libx264",@@ -62,6 +78,10 @@ const runsFor = async (over: Partial<ExportSpec>): Promise<string[][]> => {return ffmpegCalls;};+/** The graph without its last line, the delivery's signalling stamped on the+ * finished frames (colorParamsFilter), for assertions about the chains. */+const untagged = (g: string[]): string[] => g.filter((l) => !l.endsWith("[vtag]"));+const graphFor = async (over: Partial<ExportSpec>): Promise<string[]> => {const runs = await runsFor(over);const enc = runs.find((a) => a.includes("-filter_complex"))!;@@ -698,7 +718,7 @@ describe("the project background in the filtergraph", () => {const g = await graphFor({ clips: [clip("a.mp4", { fit: "fill", flipH: true })] });expect(g.join(";")).toContain(":(ih-oh)*0.500,hflip,setsar=1");const v = await graphFor({ clips: [clip("a.mp4", { flipV: true })] });- expect(v.join(";")).toContain(",vflip,pad=");+ expect(v.join(";")).toContain(",vflip,setsar=1,format=yuv420p,pad=");});test("no background named keeps the black frame every cut had before", async () => {@@ -999,3 +1019,458 @@ describe("channel layout", () => {expect(stanza("stereo.mp4")).not.toContain("pan=");});});++describe("clip color in the filtergraph", () => {+ const graphText = async (over: Partial<ExportSpec>) => untagged(await graphFor(over)).join(";");++ test("an ungraded Rec.709 clip runs no color at all", async () => {+ const g = await graphText({ clips: [clip("a.mp4")] });+ expect(g).not.toContain("lut3d");+ expect(g).not.toContain("gbrp16le");+ expect(g).not.toContain("colorspace=");+ expect(g).not.toContain("in_color_matrix");+ });++ test("a graded clip bakes one LUT and runs it in 16-bit RGB before the pad, then back to BT.709 video", async () => {+ const g = await graphFor({+ clips: [clip("a.mp4", { grade: { exposure: 10 } }), clip("b.mp4", { grade: { exposure: 10 } })],+ });+ const joined = g.join(";");+ // One .cube for the two clips sharing a recipe.+ const cubes = written.filter((w) => w.file.endsWith(".cube"));+ expect(cubes).toHaveLength(1);+ expect(cubes[0].file).toBe(path.join("/tmp/graph-test", "clip_0.cube"));+ expect(cubes[0].data).toContain("LUT_3D_SIZE 33");+ const line = g.find((l) => l.startsWith("[0:v]"))!;+ // The framing scale spells the file's matrix and range; the picture goes+ // to 16-bit RGB, through the LUT, and comes back as BT.709 video before+ // the letterbox pad.+ expect(line).toMatch(/scale=[^,]*in_color_matrix=bt709:in_range=tv/);+ const at = (needle: string) => {+ const i = line.indexOf(needle);+ expect(i).toBeGreaterThanOrEqual(0);+ return i;+ };+ expect(at("format=gbrp16le")).toBeLessThan(at("lut3d=file="));+ expect(line).toContain(`lut3d=file='${path.join("/tmp/graph-test", "clip_0.cube")}':interp=tetrahedral`);+ expect(at("lut3d=file=")).toBeLessThan(at("scale=out_color_matrix=bt709:out_range=tv"));+ expect(at("scale=out_color_matrix=bt709:out_range=tv")).toBeLessThan(at("format=yuv420p"));+ expect(at("format=yuv420p")).toBeLessThan(at("pad=1080:1920"));+ expect(untagged(g).join(";")).not.toContain("colorspace=");+ expect(joined).not.toContain("lutrgb");+ expect(joined).not.toContain("hue=");+ });++ test("a log source converts through the wide LUT with its own matrix, graded or not", async () => {+ const g = await graphFor({+ lutSize: 33,+ lutSizeWide: 65,+ clips: [clip("log.mov", { color: { profile: "apple-log", matrix: "bt2020nc", fullRange: false } })],+ });+ const line = g.find((l) => l.startsWith("[0:v]"))!;+ expect(line).toMatch(/scale=[^,]*in_color_matrix=bt2020:in_range=tv/);+ expect(line).toContain("format=gbrp16le,lut3d=file=");+ expect(written.find((w) => w.file.endsWith(".cube"))!.data).toContain("LUT_3D_SIZE 65");+ });++ test("an ungraded file in another matrix or range converts in video, with no LUT", async () => {+ const g = await graphFor({+ clips: [clip("sd.mp4", { color: { profile: "rec709", matrix: "bt601", fullRange: true } })],+ });+ const line = g.find((l) => l.startsWith("[0:v]"))!;+ expect(line).not.toContain("lut3d");+ expect(line).toContain("scale:in_color_matrix=bt601:in_range=pc:out_color_matrix=bt709:out_range=tv");+ expect(line.indexOf("out_range=tv")).toBeLessThan(line.indexOf("pad=1080:1920"));+ });++ test("sharpen and clarity run on 16-bit luma after the LUT and before the pad", async () => {+ const g = await graphFor({+ clips: [clip("a.mp4", { grade: { exposure: 5, sharpen: 25, clarity: 30 } })],+ });+ const joined = g.join(";");+ const head = g.find((l) => l.startsWith("[0:v]"))!;+ expect(head).toContain("lut3d=file=");+ expect(head).toMatch(/scale=out_color_matrix=bt709:out_range=pc,format=yuv444p16le\[dtic0\]$/);+ // The detail pass: bases from the input luma, gained detail merged back.+ expect(joined).toContain("[dtic0]split=6[dtc0o][dtc0ss][dtc0sr][dtc0cs][dtc0cr][dtc0cx]");+ expect(joined).toMatch(/\[dtc0ss\]gblur=sigma=1\.77\d*:planes=1\[dtc0sb\]/);+ expect(joined).toContain("[dtc0sr][dtc0sb]blend=c0_mode=grainextract,lutyuv=y='clip((val-32768)*0.750+32768,0,65535)'[dtc0sd]");+ // Clarity's window at 1920 tall is 43, past guided's reach: a reduced copy.+ expect(joined).toContain("[dtc0cs]scale='ceil(iw/3)':'ceil(ih/3)':flags=bilinear,guided=radius=14:eps=0.010:planes=1[dtc0cq]");+ expect(joined).toContain("[dtc0cq][dtc0cx]scale=rw:rh:flags=bilinear[dtc0cb]");+ expect(joined).toContain("[dtc0cr][dtc0cb]blend=c0_mode=grainextract,lutyuv=y='clip((val-32768)*0.900+32768,0,65535)'[dtc0cd]");+ expect(joined).toContain("[dtc0o][dtc0sd]blend=c0_mode=grainmerge[dtc0m1]");+ expect(joined).toContain("[dtc0m1][dtc0cd]blend=c0_mode=grainmerge[dtoc0]");+ const tail = g.find((l) => l.startsWith("[dtoc0]"))!;+ expect(tail).toContain("null,scale=in_color_matrix=bt709:in_range=pc:out_color_matrix=bt709:out_range=tv,format=yuv420p,pad=1080:1920");+ expect(xfadeMismatches(g)).toEqual([]);+ });++ test("a fitted 16:9 clip in a 9:16 frame sizes its detail to its own picture", async () => {+ // The preview runs sharpen and clarity on the whole decoded picture, so+ // the radii follow the picture's height: 1080 wide at 16:9 is 607.5 tall,+ // not the 1920 of the frame it letterboxes into.+ probedDims.set("/media/wide.mp4", { width: 1920, height: 1080 });+ try {+ const g = await graphFor({+ clips: [clip("wide.mp4", { fit: "fit", grade: { sharpen: 25, clarity: 30 } })],+ });+ const joined = g.join(";");+ expect(joined).toMatch(/\[dtc0ss\]gblur=sigma=0\.56\d*:planes=1\[dtc0sb\]/);+ // A window of 14 fits guided's reach: no reduced copy.+ expect(joined).toContain("[dtc0cs]guided=radius=14:eps=0.010:planes=1[dtc0cb]");+ // Covering the frame, the picture is 1920 tall and 3413 wide.+ const covered = (+ await graphFor({ clips: [clip("wide.mp4", { fit: "fill", grade: { sharpen: 25 } })] })+ ).join(";");+ expect(covered).toMatch(/\[dtc0ss\]gblur=sigma=1\.77\d*:planes=1\[dtc0sb\]/);+ } finally {+ probedDims.clear();+ }+ });++ test("clarity alone at a small frame runs guided at the picture's own size", async () => {+ const g = await graphFor({+ width: 640,+ height: 360,+ clips: [clip("a.mp4", { grade: { clarity: 50 } })],+ });+ const joined = g.join(";");+ expect(joined).not.toContain("lut3d");+ expect(joined).toContain("[dtic0]split=3[dtc0o][dtc0cs][dtc0cr]");+ expect(joined).toContain("[dtc0cs]guided=radius=8:eps=0.010:planes=1[dtc0cb]");+ expect(joined).toContain("[dtc0o][dtc0cd]blend=c0_mode=grainmerge[dtoc0]");+ });++ test("a graded overlay colors before its box pad, and a still keeps its alpha", async () => {+ const g = await graphFor({+ clips: [clip("a.mp4", { out: 6 })],+ overlayVideos: [+ { file: "ov.mp4", in: 0, out: 2, start: 1, track: 1, muted: true, grade: { contrast: 10 },+ frame: { x: 0.5, y: 0.5, w: 0.5, h: 0.5 }, mask: { file: "mask_ov0.png" } },+ { file: "still.png", in: 0, out: 2, start: 3, track: 1, muted: true, image: true, grade: { contrast: 10 },+ color: { profile: "srgb", matrix: "bt709", fullRange: true } },+ ],+ });+ const ov = g.find((l) => l.includes("[ovv0]") || (l.includes("lut3d") && l.includes("540:960")))!;+ expect(ov).toContain("format=gbrp16le,lut3d=file=");+ expect(ov.indexOf("out_range=tv")).toBeLessThan(ov.indexOf("pad=540:960"));+ const still = g.find((l) => l.includes("gbrap16le"))!;+ expect(still).toContain("format=gbrap16le,lut3d=file=");+ expect(still).not.toContain("in_color_matrix");+ // One recipe each: a video and a still share nothing but the grade.+ expect(written.filter((w) => w.file.endsWith(".cube"))).toHaveLength(1);+ });++ test("a smoothed slow clip spells the conversion again after its interpolation", async () => {+ const g = await graphFor({+ clips: [clip("a.mp4", { speed: 0.5, smoothSlow: true, grade: { exposure: 5 } })],+ });+ const line = g.find((l) => l.startsWith("[0:v]"))!;+ expect(line).toContain("minterpolate=");+ expect(line.indexOf("minterpolate=")).toBeLessThan(line.indexOf("scale:in_color_matrix=bt709:in_range=tv,format=gbrp16le,lut3d"));+ });++ test("a staged library LUT bakes into the clip's cube, and one that will not read fails naming it", async () => {+ stagedFiles.set("lut_abc.cube", "TITLE \"warm\"\nLUT_3D_SIZE 2\n0 0 0\n1 0 0\n0 1 0\n1 1 0\n0 0 1\n1 0 1\n0 1 1\n1 1 1\n");+ const g = await graphFor({+ clips: [clip("a.mp4", { grade: { lut: { id: "lut:abc" } }, color: { profile: "rec709", matrix: "bt709", fullRange: false, lutFile: "lut_abc.cube" } })],+ });+ expect(g.join(";")).toContain("lut3d=file=");+ expect(written.filter((w) => w.file.endsWith(".cube"))).toHaveLength(1);+ await expect(+ graphFor({+ clips: [clip("a.mp4", { grade: { lut: { id: "lut:missing" } }, color: { profile: "rec709", matrix: "bt709", fullRange: false, lutFile: "lut_missing.cube" } })],+ })+ ).rejects.toThrow(/The LUT lut_missing\.cube could not be read/);+ });++ test("a reversed clip's turned copy carries its code values as they are", async () => {+ const runs = await runsFor({+ clips: [clip("hdr.mp4", { reverse: true, color: { profile: "hlg", matrix: "bt2020nc", fullRange: false } })],+ });+ const chunk = runs.find((a) => a.includes("-ss"))!;+ expect(chunk[chunk.indexOf("-vf") + 1]).toBe("reverse,format=yuv420p");+ const enc = runs.find((a) => a.includes("-filter_complex"))!;+ const graph = enc[enc.indexOf("-filter_complex") + 1];+ expect(graph).toMatch(/scale=[^,]*in_color_matrix=bt2020:in_range=tv/);+ expect(graph).toContain("lut3d=file=");+ expect(untagged(graph.split(";")).join(";")).not.toContain("colorspace=");+ });+});++describe("an HDR delivery", () => {+ const hdrSpec = (over: Partial<ExportSpec> = {}): Partial<ExportSpec> => ({+ colorSpace: "hlg",+ codec: "hevc",+ clips: [clip("a.mp4")],+ ...over,+ });++ test("composites at ten bits in HLG: every clip maps into Rec.2020 and comes back as 10-bit video", async () => {+ const g = await graphFor(hdrSpec());+ const line = g.find((l) => l.startsWith("[0:v]"))!;+ // An ungraded Rec.709 clip is a conversion here, so it takes the LUT.+ expect(line).toMatch(/scale=[^,]*in_color_matrix=bt709:in_range=tv/);+ expect(line).toContain("format=gbrp16le,lut3d=file=");+ expect(line).toContain("scale=out_color_matrix=bt2020:out_range=tv");+ expect(line).toContain("format=yuv420p10le");+ expect(g.join(";")).not.toContain("format=yuv420p,");+ expect(g.join(";")).not.toContain("format=yuv420p[");+ const cubes = written.filter((w) => w.file.endsWith(".cube")).map((w) => path.basename(w.file));+ expect(cubes).toContain("clip_0.cube");+ expect(cubes).toContain("graphics.cube");+ expect(cubes).not.toContain("hlg_to_pq.cube");+ });++ test("an HLG file ungraded runs no LUT, and a graded one grades in place", async () => {+ const hlg = { profile: "hlg" as const, matrix: "bt2020nc" as const, fullRange: false };+ const plain = await graphFor(hdrSpec({ clips: [clip("h.mp4", { color: hlg })] }));+ expect(plain.find((l) => l.startsWith("[0:v]"))).not.toContain("lut3d");+ const graded = await graphFor(hdrSpec({ clips: [clip("h.mp4", { color: hlg, grade: { exposure: 10 } })] }));+ const line = graded.find((l) => l.startsWith("[0:v]"))!;+ expect(line).toMatch(/scale=[^,]*in_color_matrix=bt2020:in_range=tv/);+ expect(line).toContain("lut3d=file=");+ expect(line).toContain("scale=out_color_matrix=bt2020:out_range=tv");+ });++ test("graphics take the sRGB to HLG lattice before they overlay, and overlays blend at ten bits", async () => {+ const g = await graphFor(+ hdrSpec({+ duration: 4,+ overlays: [{ file: "o0.png", start: 0, end: 4 }],+ captions: [{ file: "cap1.png", start: 0, end: 2 }],+ })+ );+ const joined = g.join(";");+ const gfxLines = g.filter((l) => l.includes("format=gbrap16le,lut3d=file="));+ expect(gfxLines.length).toBeGreaterThanOrEqual(2);+ expect(gfxLines[0]).toContain(path.join("/tmp/graph-test", "graphics.cube"));+ expect(gfxLines[0]).toMatch(/\[gfx\d+\]$/);+ const graphics = written.find((w) => w.file.endsWith("graphics.cube"))!;+ expect(graphics.data).toContain("LUT_3D_SIZE 33");+ // The lattice's last node: sRGB white sits at HLG reference white.+ const last = graphics.data.trim().split("\n").at(-1)!.split(" ").map(Number);+ for (const v of last) expect(Math.abs(v - 0.75)).toBeLessThan(2e-4);+ expect(joined).toMatch(/overlay=[^\[]*:format=yuv420p10/);+ expect(joined).not.toMatch(/overlay=[^\[]*:format=yuv420p\b(?!10)/);+ });++ test("a PQ delivery ends with the fixed HLG to PQ pass and carries HDR10 metadata", async () => {+ const runs = await runsFor(hdrSpec({ colorSpace: "pq" }));+ const enc = runs.find((a) => a.includes("-filter_complex"))!;+ const graph = enc[enc.indexOf("-filter_complex") + 1];+ const pq = graph.split(";").find((l) => l.includes("hlg_to_pq.cube"))!;+ expect(pq).toContain("scale=in_color_matrix=bt2020:in_range=tv,format=gbrp16le,lut3d=file=");+ expect(pq).toContain("scale=out_color_matrix=bt2020:out_range=tv,format=yuv420p10le[vpq]");+ expect(written.find((w) => w.file.endsWith("hlg_to_pq.cube"))!.data).toContain("LUT_3D_SIZE 65");+ expect(arg(enc, "-x265-params")).toContain("transfer=smpte2084");+ expect(arg(enc, "-x265-params")).toContain("hdr10=1");+ expect(arg(enc, "-x265-params")).toContain("master-display=G(13250,34500)");+ expect(arg(enc, "-x265-params")).toContain("max-cll=1000,400");+ expect(arg(enc, "-color_trc")).toBe("smpte2084");+ expect(arg(enc, "-bsf:v")).toBe("hevc_metadata=colour_primaries=9:transfer_characteristics=16:matrix_coefficients=9:video_full_range_flag=0");+ });++ test("the worker's HEVC is Main 10 with its color in the bitstream and the container", async () => {+ const args = await encodeRun(hdrSpec());+ expect(arg(args, "-c:v")).toBe("libx265");+ expect(arg(args, "-pix_fmt")).toBe("yuv420p10le");+ expect(arg(args, "-profile:v")).toBe("main10");+ expect(arg(args, "-tag:v")).toBe("hvc1");+ const params = arg(args, "-x265-params");+ expect(params).toContain("colorprim=bt2020");+ expect(params).toContain("transfer=arib-std-b67");+ expect(params).toContain("colormatrix=bt2020nc");+ expect(params).not.toContain("hdr10");+ expect(arg(args, "-colorspace")).toBe("bt2020nc");+ expect(arg(args, "-color_primaries")).toBe("bt2020");+ expect(arg(args, "-color_trc")).toBe("arib-std-b67");+ expect(arg(args, "-color_range")).toBe("tv");+ expect(arg(args, "-bsf:v")).toContain("transfer_characteristics=18");+ expect(args.join(" ")).not.toContain("hlg_to_pq");+ });++ test("the Mac's HEVC is Main 10 over p010, PQ with no static metadata", () => {+ const spec = { fps: 30, crf: 24, preset: "veryfast", codec: "hevc", colorSpace: "pq", width: 1080, height: 1920 } as ExportSpec;+ const args = videoCodecArgs("hevc_videotoolbox", spec);+ expect(arg(args, "-c:v")).toBe("hevc_videotoolbox");+ expect(arg(args, "-profile:v")).toBe("main10");+ expect(arg(args, "-pix_fmt")).toBe("p010le");+ expect(arg(args, "-tag:v")).toBe("hvc1");+ expect(arg(args, "-bsf:v")).toContain("transfer_characteristics=16");+ expect(args.join(" ")).not.toContain("master-display");+ expect(colorTagArgs(spec)).toEqual(["-color_range", "tv", "-colorspace", "bt2020nc", "-color_primaries", "bt2020", "-color_trc", "smpte2084"]);+ expect(colorTagArgs({ colorSpace: "hlg" })[7]).toBe("arib-std-b67");+ expect(colorTagArgs({})).toEqual(["-color_range", "tv", "-colorspace", "bt709", "-color_primaries", "bt709", "-color_trc", "bt709"]);+ });++ test("ProRes carries HDR at ten bits with the Rec.2020 tags", async () => {+ const args = await encodeRun(hdrSpec({ codec: "prores", container: "mov", audioCodec: "pcm" }));+ expect(arg(args, "-c:v")).toBe("prores_ks");+ expect(arg(args, "-pix_fmt")).toBe("yuv422p10le");+ expect(arg(args, "-color_trc")).toBe("arib-std-b67");+ expect(arg(args, "-colorspace")).toBe("bt2020nc");+ });++ test("H.264 is refused", async () => {+ await expect(runsFor(hdrSpec({ codec: "h264" }))).rejects.toThrow(/H\.264 is 8-bit/);+ await expect(runsFor(hdrSpec({ codec: undefined }))).rejects.toThrow(/H\.264 is 8-bit/);+ const spec = { fps: 30, crf: 24, preset: "veryfast", codec: "h264", colorSpace: "hlg" } as ExportSpec;+ expect(() => videoCodecArgs("libx264", spec)).toThrow(/H\.264 is 8-bit/);+ expect(() => videoCodecArgs("h264_videotoolbox", spec)).toThrow(/H\.264 is 8-bit/);+ });++ /** Every alpha-carrying segment kind at once: a painted mask on a keyed,+ * shadowed track-0 clip, a subject-matted clip, a removal clip, a masked+ * keyed overlay, and a subject-trimmed element. */+ const alphaSpec = (over: Partial<ExportSpec> = {}): Partial<ExportSpec> => ({+ duration: 12,+ clips: [+ clip("a.mp4", {+ mask: { file: "mask.png" },+ kf: [{ t: 0, x: 0.5, y: 0.5, scale: 1, rotation: 10, opacity: 1 }],+ shadow: { file: "shadow.png" },+ }),+ clip("b.mp4", { mask: { subject: { feather: 1 } } }),+ clip("c.mp4", { removal: { rgb: "rm_rgb.mov", alpha: "rm_a.mov" } }),+ ],+ overlayVideos: [+ {+ file: "o.mp4",+ in: 0,+ out: 2,+ start: 1,+ track: 1,+ muted: true,+ frame: { x: 0.5, y: 0.5, w: 0.4, h: 0.4 },+ mask: { file: "omask.png" },+ kf: [{ t: 0, x: 0.5, y: 0.5, scale: 1, rotation: 5, opacity: 1 }],+ },+ ],+ overlays: [+ {+ frames: [{ file: "f0.png", duration: 0.5 }],+ blank: "blank.png",+ x: 0,+ y: 0,+ start: 1,+ end: 2,+ subject: { invert: true },+ lane: 0,+ },+ ],+ behindMask: { file: "matte.mp4", from: 0 },+ ...over,+ });++ test("alpha segments hold ten bits: masks merge as planes, multiply as a blend, and no rgba or alphamerge hop remains", async () => {+ const g = await graphFor(hdrSpec(alphaSpec()));+ const joined = g.join(";");+ expect(joined).not.toContain("format=rgba");+ expect(joined).not.toContain("alphamerge");+ expect(joined).not.toContain("alphaextract");+ // An 8-bit mask widens through 8-bit gray, which is exact, and nothing+ // reaches the alpha filters below ten bits.+ expect(joined).not.toMatch(/format=gray[,\]](?!format=gray10le)/);+ expect(joined).not.toMatch(/format=yuva?4[24][04]p[,\]]/);+ // Every mask reaches the alpha filters as a four-plane copy carrying the+ // composite's own tags, so negotiation never converts it on the way in.+ const carrier = "mergeplanes=0x00000000:format=yuva444p10le,setparams=range=tv:colorspace=bt2020nc";+ const multiply = "blend=c0_mode=normal:c1_mode=normal:c2_mode=normal:c3_mode=multiply";+ // Painted mask on track 0: the mask is ten-bit gray, the segment joins+ // the alpha family tagged like the video, the multiply is per plane.+ expect(joined).toContain("setsar=1,format=gray,format=gray10le[cmk0]");+ expect(joined).toContain(`[cmk0]${carrier}[cm0k]`);+ expect(joined).toContain("format=yuva444p10le,setparams=range=tv:colorspace=bt2020nc[cm0c]");+ expect(joined).toContain(`[cm0c][cm0k]${multiply}[cmc0]`);+ // The subject matte is ten-bit gray at the source and multiplies the same way.+ expect(joined).toMatch(/format=gray10le,tpad=start_duration=0\.000:color=black\[bh_src\]/);+ expect(joined).toContain(`[cs1c][cs1k]${multiply}[csc1]`);+ // A removal clip's keyed pair: the color piece converts with the+ // composite's matrix, the luma piece lands in the alpha plane by mergeplanes.+ expect(joined).toContain("scale=out_color_matrix=bt2020:out_range=tv,format=yuva444p10le[rvc2]");+ expect(joined).toContain("format=gray10le[rva2]");+ expect(joined).toContain("[rvc2][rv2k]mergeplanes=0x00010210:format=yuva444p10le,tpad=stop_mode=clone:stop_duration=1[rvs2]");+ // Shadow PNG, masked keyed overlay, subject-trimmed element.+ expect(joined).toContain("scale=out_color_matrix=bt2020:out_range=tv,format=yuva444p10le[csh0]");+ expect(joined).toContain(`[om0c][om0k]${multiply},format=yuva420p10le[omc0]`);+ expect(joined).toMatch(/\[omc0\]format=yuva444p10le,setparams=range=tv:colorspace=bt2020nc,rotate=/);+ expect(joined).toContain(`[oe0c][oe0k]${multiply},format=yuva420p10le[oes0]`);+ });++ test("nothing overlays onto a main that carries alpha: a pose lands as color and alpha, each on an opaque backdrop", async () => {+ // ffmpeg's ten-bit overlay onto a main with alpha unpremultiplies with+ // eight-bit constants: a keyed pose on a clear frame came out at a+ // quarter of its brightness. The posed picture changes size frame by+ // frame, so its alpha is read back after it lands, off a zero frame and+ // a full one.+ const g = await graphFor(+ hdrSpec(+ alphaSpec({+ clips: [+ clip("a.mp4", { kf: [{ t: 0, x: 0.5, y: 0.5, scale: 1, rotation: 10, opacity: 1 }] }),+ clip("c.mp4", { removal: { rgb: "rm_rgb.mov", alpha: "rm_a.mov" }, animOut: { style: "pop", seconds: 0.5 } }),+ ],+ overlayVideos: [+ {+ file: "o.mp4", in: 0, out: 2, start: 1, track: 1, muted: true,+ frame: { x: 0.5, y: 0.5, w: 0.4, h: 0.4 },+ mask: { subject: { feather: 1 } },+ kf: [{ t: 0, x: 0.5, y: 0.5, scale: 1, rotation: 5, opacity: 1 }],+ },+ ],+ })+ )+ );+ const joined = g.join(";");+ expect(joined).not.toContain("[email protected]:s=");+ expect(joined).toContain("[ckt0]format=yuva444p10le,split=3[ckb0c][ckb0z][ckb0f]");+ expect(joined).toContain("[ckb0c]format=yuv444p10le,setparams=range=tv:colorspace=bt2020nc[ckb0co]");+ expect(joined).toMatch(/\[ckb0zb\]\[ckb0z\]overlay=[^\[]*format=yuv444p10\[ckb0zp\]/);+ expect(joined).toContain("[ckb0fp][ckb0zp]blend=all_mode=subtract[ckb0inv]");+ expect(joined).toContain("[ckb0ff][ckb0inv]blend=all_mode=subtract[ckb0ap]");+ expect(joined).toContain("[ckb0cp][ckb0ap]mergeplanes=0x00010210:format=yuva444p10le[ckp0]");+ expect(joined).toContain("[osb0cp][osb0ap]mergeplanes=0x00010210:format=yuva444p10le[osp0]");+ // The removal clip's pop lands on the bare frame, opaque in format.+ expect(joined).toMatch(/color=c=black:s=1080x1920:r=30:d=0\.500,format=yuv444p10le\[xbc1_tail\]/);+ const mains = [...joined.matchAll(/\[([^\]]+)\]\[[^\]]+\]overlay=/g)].map((m) => m[1]);+ for (const main of mains) {+ const made = g.find((l) => l.endsWith(`[${main}]`)) ?? "";+ expect(made).not.toMatch(/format=yuva[^,\[]*\[[^\]]+\]$/);+ }+ });++ test("the finished frames carry the delivery's signalling, so a ProRes MOV gets its colr atom", async () => {+ const hlg = await graphFor(hdrSpec({ codec: "prores", container: "mov", audioCodec: "pcm" }));+ expect(hlg.at(-1)).toMatch(/^\[v\w*\]setparams=range=tv:colorspace=bt2020nc:color_primaries=bt2020:color_trc=arib-std-b67\[vtag\]$/);+ const pq = await graphFor(hdrSpec({ colorSpace: "pq" }));+ expect(pq.at(-1)).toBe("[vpq]setparams=range=tv:colorspace=bt2020nc:color_primaries=bt2020:color_trc=smpte2084[vtag]");+ const sdr = await graphFor({ codec: "prores", container: "mov", audioCodec: "pcm", clips: [clip("a.mp4")] });+ expect(sdr.at(-1)).toMatch(/^\[v\w*\]setparams=range=tv:colorspace=bt709:color_primaries=bt709:color_trc=bt709\[vtag\]$/);+ const enc = (await runsFor(hdrSpec())).find((a) => a.includes("-filter_complex"))!;+ expect(enc[enc.indexOf("-map") + 1]).toBe("[vtag]");+ expect(colorParamsFilter({ colorSpace: "hlg" })).toContain("color_trc=arib-std-b67");+ });++ test("the same segments in SDR keep their rgba chains", async () => {+ const g = await graphFor(alphaSpec({ codec: "h264" }));+ const joined = untagged(g).join(";");+ expect(g.at(-1)).toContain("setparams=range=tv:colorspace=bt709");+ expect(joined).not.toContain("mergeplanes");+ expect(joined).not.toContain("setparams");+ expect(joined).not.toContain("gray10le");+ expect(joined).toContain("[cmk0]blend=all_mode=multiply");+ expect(joined).toContain("[rvc2][rva2]alphamerge,tpad=stop_mode=clone:stop_duration=1[rvs2]");+ expect(joined).toContain("[oe10]alphaextract,fps=30[oea0]");+ expect(joined).toContain("alphamerge,format=yuva420p[oes0]");+ });++ test("an SDR delivery is untouched: BT.709 tags, 8-bit planes, no graphics lattice", async () => {+ const args = await encodeRun({ codec: "hevc" });+ expect(arg(args, "-pix_fmt")).toBe("yuv420p");+ expect(arg(args, "-color_trc")).toBe("bt709");+ expect(args).not.toContain("-bsf:v");+ expect(written.some((w) => w.file.endsWith("graphics.cube"))).toBe(false);+ });+});diff --git a/site/src/cut/server/exportPipeline.ts b/site/src/cut/server/exportPipeline.tsindex 9f4b2809..eb714cd6 100644--- a/site/src/cut/server/exportPipeline.ts+++ b/site/src/cut/server/exportPipeline.ts@@ -1,15 +1,18 @@import { spawn, type ChildProcess } from "node:child_process";import { exportSourceFiles } from "./sourceExport";import type { SourceSegment } from "../lib/sourceExportPlan";-import { deliveryCodec, deliveryContainer, deliverySpan, KEYFRAME_INTERVAL_S, videoBitrateFor, type ExportCodec, type ExportRange } from "../lib/exportDelivery";+import { deliveryCodec, deliveryContainer, deliverySpan, KEYFRAME_INTERVAL_S, videoBitrateFor, type ExportCodec, type ExportRange, type SpecClipColor } from "../lib/exportDelivery";++export type { SpecClipColor };import { readFile, stat, unlink, writeFile } from "node:fs/promises";import path from "node:path";-import { atempoChain, audioChannels, hasStream, mediaDuration, num, videoColorInfo, videoDecodeCost } from "./util";+import { atempoChain, audioChannels, hasStream, mediaDuration, num, videoDecodeCost, videoDimensions } from "./util";import { assertGraphSafe, fexpr } from "./filterGraph";import { bakeRetimedAudio, setptsExpr, type BakedAudio } from "./retimeAudio";import { bakeTurnedMedia } from "./turnMedia";+import { withSpecColors } from "./fileColor";import { CLIP_MAX_ZOOM, regionPx, TRANSITION_XFADE, TRANSITION_ZOOM, type ColorGrade, type TransitionStyle } from "../lib/types";-import { audioFxFilters, buildGradeLut, effectFilterLines, gradeKey, gradeNeedsLut, gradeToFfmpegFilter, isAudioEffect, lookFilterLines, lutToCube, mirrorRetimable, retimeOf, shortestTurn, slowRuns, srcSpan, sortedKeys, soundFilters, type ClipSound, type OverlayKey, type Retime, type SpeedNode } from "@donkeycut/effects-kit";+import { audioFxFilters, buildClipLut, buildTransferLut, CLARITY_EPS, compositeSpaceFor, detailActive, detailGain, detailRadius, effectFilterLines, graphicsToHlg, hexToHlgHex, hlgToPq, isAudioEffect, lookFilterLines, lutToCube, mirrorRetimable, parseLutFile, recipeKey, retimeOf, shortestTurn, slowRuns, srcSpan, sortedKeys, soundFilters, type ChainChroma, type ClipColorRecipe, type ClipSound, type CodeFormat, type OutputSpace, type OverlayKey, type ParsedLut, type Retime, type SpeedNode } from "@donkeycut/effects-kit";// The render pipeline itself: spec in, finished mp4 out. Shared by the local// engine's job registry (jobs.ts) and the cloud render worker, which stage@@ -56,6 +59,12 @@ const soundChain = (sound: ClipSound | undefined): string => {export interface ExportSpec {sourceSegments?: SourceSegment[];projectId: string;+ /** The delivery's color space; absent = SDR. */+ colorSpace?: OutputSpace;+ /** Lattice nodes per axis of the clip color LUTs: `lutSize` for Rec.709+ * and sRGB sources, `lutSizeWide` for log and HDR. */+ lutSize?: number;+ lutSizeWide?: number;/** Where the render lands instead of a stamped file in exports/: "hls" is the* share's streaming ladder, "preview"* writes the project's low-res hover proxy, "card" the opening seconds the@@ -152,6 +161,8 @@ export interface ExportSpec {staged?: boolean;/** Manual color adjustments, baked into this clip's segment. */grade?: ColorGrade;+ /** The source's color, which the grade is built over. Absent = Rec.709. */+ color?: SpecClipColor;/** Client-painted grayscale coverage trimming this clip's picture (white* keeps the pixel; feather and invert are baked into the pictures): one* full-frame still, or a sampled `frames` sequence for a keyframed mask@@ -237,6 +248,8 @@ export interface ExportSpec {image?: boolean;/** Manual color adjustments, baked into this overlay's segment. */grade?: ColorGrade;+ /** The source's color, which the grade is built over. Absent = Rec.709. */+ color?: SpecClipColor;/** Preset filter look id + strength (footage overlays only — image* overlays may carry alpha the look chain would flatten). */look?: string;@@ -420,21 +433,52 @@ export function targetBitrate(width: number, height: number, fps: number, crf: n*/export function videoCodecArgs(enc: string, spec: ExportSpec): string[] {const codec = spec.codec ?? "h264";+ const hdr = (spec.colorSpace ?? "sdr") !== "sdr";const bitrate = videoBitrateFor({ ...spec, codec });const rate = ["-b:v", String(bitrate), "-maxrate", String(Math.round(bitrate * 1.5)), "-bufsize", String(bitrate * 3)];// A key frame every two seconds, the cadence the platforms ask for and the// one the tab's encoder writes.const gop = ["-g", String(Math.max(1, Math.round(spec.fps * KEYFRAME_INTERVAL_S)))];+ // The HEVC bitstream's own color signalling, written into its VUI whatever+ // the encoder put there: Rec.2020 primaries (9), the HLG (18) or PQ (16)+ // transfer, the Rec.2020 non-constant matrix (9), limited range.+ const hevcVui = hdr+ ? ["-bsf:v", `hevc_metadata=colour_primaries=9:transfer_characteristics=${spec.colorSpace === "pq" ? 16 : 18}:matrix_coefficients=9:video_full_range_flag=0`]+ : [];switch (enc) {case "libx264":+ if (hdr) throw new Error("H.264 is 8-bit. Export HDR as HEVC or ProRes.");return ["-c:v", "libx264", "-preset", spec.preset, ...(spec.bitrate ? rate : ["-crf", String(spec.crf)]), ...gop, "-profile:v", "high", "-pix_fmt", "yuv420p"];case "h264_videotoolbox":+ if (hdr) throw new Error("H.264 is 8-bit. Export HDR as HEVC or ProRes.");return ["-c:v", "h264_videotoolbox", ...rate, ...gop, "-profile:v", "high", "-pix_fmt", "yuv420p", "-allow_sw", "1"];- case "libx265":+ case "libx265": {// x265's CRF scale sits about four points above x264's for the same picture.- return ["-c:v", "libx265", "-preset", spec.preset, ...(spec.bitrate ? rate : ["-crf", String(spec.crf + 4)]), ...gop, "-x265-params", "log-level=error", "-tag:v", "hvc1", "-pix_fmt", "yuv420p"];+ // An HDR file is Main 10 with its color in the stream; a PQ file also+ // carries HDR10 static metadata — the Rec.2020 mastering display at+ // 1000 nits and the content light it implies — which players read for+ // their tone mapping.+ const params = hdr+ ? [+ "log-level=error",+ "colorprim=bt2020",+ `transfer=${spec.colorSpace === "pq" ? "smpte2084" : "arib-std-b67"}`,+ "colormatrix=bt2020nc",+ "range=limited",+ ...(spec.colorSpace === "pq"+ ? ["hdr10=1", "hdr10-opt=1", "master-display=G(13250,34500)B(7500,3000)R(34000,16000)WP(15635,16450)L(10000000,1)", "max-cll=1000,400"]+ : []),+ ].join(":")+ : "log-level=error";+ return ["-c:v", "libx265", "-preset", spec.preset, ...(spec.bitrate ? rate : ["-crf", String(spec.crf + 4)]), ...gop, "-x265-params", params, "-tag:v", "hvc1", "-pix_fmt", hdr ? "yuv420p10le" : "yuv420p", ...(hdr ? ["-profile:v", "main10"] : []), ...hevcVui];+ }case "hevc_videotoolbox":- return ["-c:v", "hevc_videotoolbox", ...rate, ...gop, "-profile:v", "main", "-tag:v", "hvc1", "-pix_fmt", "yuv420p", "-allow_sw", "1"];+ // Main 10 takes its 10-bit planes as p010; the color signalling rides+ // the stream's own tags and the VUI rewrite. A PQ file from this Mac+ // carries no static metadata: players take the 1000-nit reference.+ return hdr+ ? ["-c:v", "hevc_videotoolbox", ...rate, ...gop, "-profile:v", "main10", "-tag:v", "hvc1", "-pix_fmt", "p010le", "-allow_sw", "1", ...hevcVui]+ : ["-c:v", "hevc_videotoolbox", ...rate, ...gop, "-profile:v", "main", "-tag:v", "hvc1", "-pix_fmt", "yuv420p", "-allow_sw", "1"];case "prores_ks": {// Profile 3 is 422 HQ, profile 4 is 4444. 4444 keeps the chroma the// graph composited at — every pixel its own color, which is what the@@ -449,6 +493,24 @@ export function videoCodecArgs(enc: string, spec: ExportSpec): string[] {}}+/** The color tags a delivered file carries, container and stream alike:+ * BT.709 for SDR; Rec.2020 primaries and matrix with the HLG or PQ transfer+ * for HDR. */+export function colorTagArgs(spec: Pick<ExportSpec, "colorSpace">): string[] {+ const space = spec.colorSpace ?? "sdr";+ if (space === "sdr") return ["-color_range", "tv", "-colorspace", "bt709", "-color_primaries", "bt709", "-color_trc", "bt709"];+ return ["-color_range", "tv", "-colorspace", "bt2020nc", "-color_primaries", "bt2020", "-color_trc", space === "pq" ? "smpte2084" : "arib-std-b67"];+}++/** The same signalling stamped on the finished frames. The MOV muxer writes+ * ProRes's colr atom from what the frames carry, and the encoder options+ * alone leave that file untagged. */+export function colorParamsFilter(spec: Pick<ExportSpec, "colorSpace">): string {+ const space = spec.colorSpace ?? "sdr";+ if (space === "sdr") return "setparams=range=tv:colorspace=bt709:color_primaries=bt709:color_trc=bt709";+ return `setparams=range=tv:colorspace=bt2020nc:color_primaries=bt2020:color_trc=${space === "pq" ? "smpte2084" : "arib-std-b67"}`;+}+/** The audio arguments for a spec's delivery. */export function audioCodecArgs(spec: ExportSpec): string[] {return [...(spec.audioCodec === "pcm" ? ["-c:a", "pcm_s16le"] : ["-c:a", "aac", "-b:a", String(spec.audioBitrate ?? 192_000)]),@@ -472,37 +534,6 @@ async function resolveMedia(return p;}-/**- * Filter prefix converting a wide-gamut/HDR source (phone footage: BT.2020- * primaries with an HLG or PQ transfer) down to the BT.709 SDR the export is- * tagged as, or "" for an SDR source. The blind `format=yuv420p` squeeze keeps- * BT.2020 code values, and players reading them as 709 wash the clip out —- * visible whenever phone footage sits next to Cut-rendered (already-709)- * clips. The native `colorspace` filter has no HLG/PQ transfer, so the input- * is pinned to bt2020-10, a close stand-in over HLG's SDR-compatible range;- * the 10-bit format hop feeds it a planar format it accepts (decoders hand- * HDR frames over as p010, which it rejects).- *- * The matrix decides, the way players decide. Social-app transcodes (8-bit- * H.264) keep BT.2020 primaries + HLG transfer tags from the phone original- * but write an explicit bt709 matrix — players read those as plain 709 SDR,- * so converting them shifts hue and saturation against what every player- * shows (verified frame-for-frame against WebKit playback). Convert only- * when the matrix itself is BT.2020, or when it's untagged and the wide- * primaries/transfer tags are the only signal there is.- */-export function sdrConvert(c: Awaited<ReturnType<typeof videoColorInfo>>, fmt: string) {- if (c == null) return "";- const matrix = c.matrix && c.matrix !== "unknown" ? c.matrix : null;- const wide =- matrix?.startsWith("bt2020") === true ||- (matrix === null &&- (c.primaries === "bt2020" ||- c.transfer === "arib-std-b67" ||- c.transfer === "smpte2084"));- return wide ? `format=yuv420p10le,colorspace=all=bt709:iall=bt2020:format=${fmt},` : "";-}-/** A clip's effective playback rate (>0, default 1). *//** A spec color as an ffmpeg color argument: `0xRRGGBB`. Anything the spec* did not carry, or carried malformed, is black — the frame every cut had@@ -692,8 +723,8 @@ export interface ExportPipelineIO {unlink: typeof unlink;hasStream: typeof hasStream;audioChannels: typeof audioChannels;- videoColorInfo: typeof videoColorInfo;videoDecodeCost: typeof videoDecodeCost;+ videoDimensions: typeof videoDimensions;mediaDuration: typeof mediaDuration;videoEncoder: (codec: ExportVideoCodec) => Promise<string>;runFfmpeg: typeof runFfmpeg;@@ -707,8 +738,8 @@ const realIO: ExportPipelineIO = {unlink,hasStream,audioChannels,- videoColorInfo,videoDecodeCost,+ videoDimensions,mediaDuration,videoEncoder,runFfmpeg,@@ -738,9 +769,18 @@ export async function runExport(}if (await io.exportSourceFiles(job, mediaPathFor, given.sourceSegments, codec, given.audioBitrate)) return;}- let spec = narrowSpecToRange(given);+ let spec = await withSpecColors(narrowSpecToRange(given), mediaPathFor);const { width: W, height: H, fps } = spec;+ // The delivery's color space. An HDR file composites in HLG signal space+ // — every clip converts into it, every graphic maps into it, the effects+ // scale their constants to it — and a PQ file is one fixed pass over the+ // finished picture. H.264 is 8-bit and never carries it.+ const output: OutputSpace = spec.colorSpace ?? "sdr";+ const hdr = output !== "sdr";+ const compositeSpace = compositeSpaceFor(output);+ if (hdr && codec === "h264") throw new Error("H.264 is 8-bit. Export HDR as HEVC or ProRes.");+// The chroma the composite is built at. A full-chroma delivery composites// at 4:4:4, so the titles, captions, stickers and masks the graph draws in// RGBA reach the file with every pixel's own color — a 4:2:0 graph averages@@ -748,17 +788,45 @@ export async function runExport(// as afterward. H.264 and HEVC subsample at the encoder regardless, so their// graph stays 4:2:0 and costs what it always did.//- // Eight bits a plane either way: the looks and effects carry 0–255- // constants (`geq`, `lutyuv`), the sources decode to eight, and ProRes 4444- // takes the exact widening to ten at the encoder.+ // Eight bits a plane for SDR: the sources decode to eight, and ProRes 4444+ // takes the exact widening to ten at the encoder. An HDR composite holds+ // ten, and the looks and effects scale their 8-bit constants to it.const full = deliveryCodec(spec.codec).chroma444 === true;- const clipFmt = full ? "yuv444p" : "yuv420p";- const alphaFmt = full ? "yuva444p" : "yuva420p";+ const depth: 8 | 10 = hdr ? 10 : 8;+ const bits = hdr ? "10le" : "";+ const clipFmt = full ? `yuv444p${bits}` : `yuv420p${bits}`;+ const alphaFmt = full ? `yuva444p${bits}` : `yuva420p${bits}`;// `overlay` blends in its own pixel family, and its default is yuv420 —// left alone it would undo the graph's chroma at every composite.- const ovl = full ? ":format=yuv444" : "";+ const ovl = full ? (hdr ? ":format=yuv444p10" : ":format=yuv444") : hdr ? ":format=yuv420p10" : "";/** The same family, for the effect chains the kit writes. */- const chroma = { pixFmt: clipFmt, overlay: ovl };+ const chroma: ChainChroma = { pixFmt: clipFmt, overlay: ovl, depth };+ /** The matrix the composite's video carries, as ffmpeg spells it for the+ * scale filter and as a file's header names it. */+ const outMatrix = hdr ? "bt2020" : "bt709";+ const outMatrixName: CodeFormat["matrix"] = hdr ? "bt2020nc" : "bt709";+ // A segment that carries alpha — a painted or subject mask, a keyed pose,+ // a removal clip's keyed pair — rides RGBA through an SDR composite. An+ // HDR composite keeps it at ten bits in the video's own family, tagged+ // like the video so no negotiation converts it on the way: a mask reaches+ // the alpha plane through mergeplanes (alphamerge is an 8-bit filter) and+ // a mask multiply is a per-plane blend.+ const alphaHi = hdr ? "yuva444p10le" : "rgba";+ // Masks are 8-bit files. They widen to ten bits through 8-bit gray, which+ // is exact; a direct conversion lands white short of opaque (1020 of 1023).+ const maskFmt = hdr ? "gray,format=gray10le" : "gray";+ /** A format without its alpha plane. ffmpeg's ten-bit overlay onto a main+ * that carries alpha unpremultiplies with eight-bit constants and darkens+ * everything short of opaque, so an HDR composite never overlays onto one:+ * an opaque backdrop is opaque in format too. */+ const opaqueFmt = (fmt: string): string => (hdr ? fmt.replace(/^yuva/, "yuv") : fmt);+ /** The format an alpha-carrying segment holds through its edge effects. */+ const segAlpha = hdr ? alphaHi : alphaFmt;+ /** Into the alpha family from the composite's video. */+ const videoToAlpha = hdr ? `format=${alphaHi},setparams=range=tv:colorspace=${outMatrixName}` : "format=rgba";+ /** Into the alpha family from an RGB graphic (a mapped PNG, a keyed+ * pair's color piece), converted with the composite's matrix. */+ const rgbToAlpha = hdr ? `scale=out_color_matrix=${outMatrix}:out_range=tv,format=${alphaHi}` : "format=rgba";// A clip that plays backward is rendered off a turned copy of its span,// baked ahead of the graph in bounded chunks (turnMedia.ts): the clip@@ -798,7 +866,6 @@ export async function runExport(const video = !soundOnly && (await io.hasStream(src, "v"));const audio = await io.hasStream(src, "a");const mono = audio && (await io.audioChannels(src)) === 1;- const colorFix = video ? sdrConvert(await io.videoColorInfo(src), clipFmt) : "";const decodeCost = video ? ((await io.videoDecodeCost(src)) ?? 0) : 0;const file = path.join(job.tmpDir, `turned_${tag}.${video ? "mov" : "wav"}`);const pivot = await bakeTurnedMedia(@@ -809,7 +876,7 @@ export async function runExport(duration: io.mediaDuration,},src,- { lo, hi, video, audio, colorFix, decodeCost, fmt: clipFmt, master: full },+ { lo, hi, video, audio, decodeCost, fmt: clipFmt, master: full || hdr },file);turned.set(file, { video, audio, mono });@@ -833,7 +900,7 @@ export async function runExport(// Every bare patch of frame in the graph — the letterbox around a fitted// clip, a gap on track 0, the backdrop behind an edge animation — is the// project's own background color. ffmpeg takes it as 0xRRGGBB.- const padColor = ffColor(spec.background);+ const padColor = ffColor(hdr && spec.background ? hexToHlgHex(spec.background) : spec.background);/*** The chain that meets a clip's picture with its box: covering it (cropping* the overflow) or fitted inside it, zoomed, with the pan choosing what the@@ -847,21 +914,36 @@ export async function runExport(cover: boolean,zoom?: number,panX?: number,- panY?: number+ panY?: number,+ /** The source's matrix and range, so the scale that first touches the+ * code values converts them the way the file meant (see colorPlanFor). */+ flags = ""): string => {const z = Math.max(1, Math.min(CLIP_MAX_ZOOM, zoom ?? 1));const even = (n: number) => 2 * Math.round(n / 2);const tw = even(bw * z);const th = even(bh * z);const scale = cover- ? `scale=${tw}:${th}:force_original_aspect_ratio=increase`- : `scale=${tw}:${th}:force_original_aspect_ratio=decrease:force_divisible_by=2`;+ ? `scale=${tw}:${th}:force_original_aspect_ratio=increase${flags}`+ : `scale=${tw}:${th}:force_original_aspect_ratio=decrease:force_divisible_by=2${flags}`;// A fitted picture at rest overflows nothing, so it needs no crop at all.if (!cover && z <= 1.0001) return scale;const kx = num(0.5 + Math.max(-1, Math.min(1, panX ?? 0)) / 2);const ky = num(0.5 + Math.max(-1, Math.min(1, panY ?? 0)) / 2);return `${scale},crop=${fexpr(`min(iw,${bw})`)}:${fexpr(`min(ih,${bh})`)}:(iw-ow)*${kx}:(ih-oh)*${ky}`;};+ /** The height of the whole picture as `boxFraming` scales it into its box,+ * before any crop: the size the preview's detail pass sizes its radii to.+ * The zoomed box's height when the source size is unknown. */+ const framedPictureHeight = (file: string, bw: number, bh: number, cover: boolean, zoom?: number): number => {+ const z = Math.max(1, Math.min(CLIP_MAX_ZOOM, zoom ?? 1));+ const tw = 2 * Math.round((bw * z) / 2);+ const th = 2 * Math.round((bh * z) / 2);+ const dims = pictureDims.get(file);+ if (!dims) return th;+ const fitted = (tw * dims.height) / dims.width;+ return cover ? Math.max(th, fitted) : Math.min(th, fitted);+ };/** The mirror after the framing: the picture flips inside its box, the* way the canvas turns it about the box center. */const mirror = (c: { flipH?: boolean; flipV?: boolean }): string =>@@ -892,8 +974,6 @@ export async function runExport(const toStereo = (file: string) =>`aresample=44100,${monoFiles.has(file) ? "pan=stereo|c0=c0|c1=c0," : ""}` +"aformat=sample_fmts=fltp:channel_layouts=stereo,";- // file → filter prefix folding a wide-gamut/HDR source down to BT.709 (or "").- const colorFix = new Map<string, string>();const inputs: string[] = [];const inputIndex = new Map<string, number>();// Counted explicitly: the concat input below carries extra flags, so the@@ -919,18 +999,29 @@ export async function runExport(let videoProbeFailed = false;const hasVideo = await io.hasStream(paths[i], "v", () => (videoProbeFailed = true));videoPresence.set(f, hasVideo || videoProbeFailed);- // A failed color probe (null) means no conversion — SDR passthrough.- colorFix.set(f, sdrConvert(await io.videoColorInfo(paths[i]), clipFmt));}));- // The turned copies: already probed at the bake, already folded to SDR.+ // The source size of every picture a detail pass runs on: its radii follow+ // the whole picture's height as framed, which the size and the box decide.+ const pictureDims = new Map<string, { width: number; height: number } | null>();+ const detailed = [...spec.clips, ...overlayVideos].filter((c) => c.file && detailActive(c.grade));+ await Promise.all(+ [...new Map(detailed.map((c) => [c.file, c])).values()].map(async (c) => {+ const at = turned.has(c.file)+ ? c.file+ : c.image && "staged" in c && c.staged+ ? path.join(job.tmpDir, path.basename(c.file))+ : await resolveMedia(io.stat, mediaPathFor, c.file);+ pictureDims.set(c.file, await io.videoDimensions(at));+ })+ );+ // The turned copies: already probed at the bake.for (const [file, streams] of turned) {inputIndex.set(file, nInputs++);inputs.push("-i", file);audioPresence.set(file, streams.audio);videoPresence.set(file, streams.video);if (streams.mono) monoFiles.add(file);- colorFix.set(file, "");}// Animated overlays: each is its own concat-demuxer slideshow (region-sized// frames with transparent filler around the element's window), the exact@@ -1134,29 +1225,243 @@ export async function runExport(const filters: string[] = [];- // Grades that use the extended primitives (curves, wheels, HSL, presets…)- // bake through the shared 3D LUT: one .cube per distinct grade, written to- // the job dir and applied with lut3d at the exact chain position the- // fast-path lutrgb/hue chain occupies. Scalar-only grades keep that- // original chain byte for byte.- const gradeLutChain = new Map<string, string>();+ // One color mapping per clip: the source conversion, the library LUT and+ // the grade baked into one 3D LUT (effects-kit colorPipeline.ts), written+ // to the job dir as .cube once per distinct recipe and applied with lut3d.+ // The clip's picture goes through it in 16-bit RGB with the file's own+ // matrix and range spelled out, so what the file meant is what the LUT+ // sees, and comes back to BT.709 video for the rest of the chain.+ type ColorOwner = { color?: SpecClipColor; grade?: ColorGrade; image?: boolean };+ const REC709: SpecClipColor = { profile: "rec709", matrix: "bt709", fullRange: false };+ const SRGB: SpecClipColor = { profile: "srgb", matrix: "bt709", fullRange: true };+ const colorOf = (o: ColorOwner): SpecClipColor => o.color ?? (o.image ? SRGB : REC709);+ const recipeOf = (o: ColorOwner): ClipColorRecipe => {+ const profile = colorOf(o).profile;+ const wide = profile !== "rec709" && profile !== "srgb";+ return { profile, grade: o.grade, output: compositeSpace, size: wide ? spec.lutSizeWide ?? 65 : spec.lutSize ?? 33 };+ };+ const recipeId = (o: ColorOwner): string => {+ const key = recipeKey(recipeOf(o));+ return key ? `${key}|${colorOf(o).lutFile ?? ""}` : "";+ };+ const userLuts = new Map<string, ParsedLut>();+ const userLutFor = async (file: string): Promise<ParsedLut> => {+ const held = userLuts.get(file);+ if (held) return held;+ let parsed: ParsedLut;+ try {+ const text = Buffer.from(await io.readFile(path.join(job.tmpDir, path.basename(file)))).toString("utf8");+ parsed = parseLutFile(file, text);+ } catch (e) {+ throw new Error(`The LUT ${file} could not be read: ${e instanceof Error ? e.message : String(e)}`);+ }+ userLuts.set(file, parsed);+ return parsed;+ };+ /** Recipe identity → the lut3d filter over its .cube, or "" for identity. */+ const lutFilters = new Map<string, string>();for (const owner of [...spec.clips, ...(spec.overlayVideos ?? [])]) {- if (!gradeNeedsLut(owner.grade)) continue;- const key = gradeKey(owner.grade);- if (!key || gradeLutChain.has(key)) continue;- const lut = buildGradeLut(owner.grade);+ const id = recipeId(owner);+ if (!id || lutFilters.has(id)) continue;+ const lutFile = colorOf(owner).lutFile;+ const lut = buildClipLut(recipeOf(owner), lutFile ? await userLutFor(lutFile) : undefined);if (!lut) {- gradeLutChain.set(key, "");+ lutFilters.set(id, "");continue;}- const file = path.join(job.tmpDir, `grade_${gradeLutChain.size}.cube`);+ const file = path.join(job.tmpDir, `clip_${lutFilters.size}.cube`);await io.writeFile(file, lutToCube(lut));- gradeLutChain.set(key, `lut3d=file=${fexpr(file)}:interp=tetrahedral,`);+ lutFilters.set(id, `lut3d=file=${fexpr(file)}:interp=tetrahedral`);+ }+ // Every graphic the graph lays over the picture — titles, captions,+ // stickers, border rings, shadows, the keyed pieces a removal clip ships+ // — is drawn in sRGB. An HDR composite takes each one through the same+ // BT.2408 mapping the SDR clips take, so a white title sits at reference+ // white beside them.+ let graphicsLut = "";+ if (hdr) {+ const file = path.join(job.tmpDir, "graphics.cube");+ await io.writeFile(file, lutToCube(buildTransferLut(spec.lutSize ?? 33, graphicsToHlg), "sRGB to HLG"));+ graphicsLut = `lut3d=file=${fexpr(file)}:interp=tetrahedral`;+ }+ let gfxN = 0;+ /** A graphic input's stream mapped into the composite: the input label as+ * is for SDR, a mapped copy in HDR. */+ const gfx = (src: string): string => {+ if (!graphicsLut) return src;+ const out = `gfx${gfxN++}`;+ filters.push(`[${src}]format=gbrap16le,${graphicsLut}[${out}]`);+ return out;+ };+ /** A gray mask as the operand the HDR alpha filters take: a four-plane+ * copy of it in the alpha family, stamped with the video's tags. */+ const maskCarrier = (mask: string, out: string): string => {+ filters.push(+ `[${mask}]mergeplanes=0x00000000:format=${alphaHi},setparams=range=tv:colorspace=${outMatrixName}[${out}]`+ );+ return out;+ };+ /** `[cur]` with its alpha multiplied by the gray mask `[mask]`, into+ * `[out]`; `tail` follows the merge and `tag` names the intermediates. */+ const alphaMultiply = (cur: string, mask: string, out: string, tag: string, tail = "") => {+ if (hdr) {+ const m = maskCarrier(mask, `${tag}k`);+ filters.push(`[${cur}]${videoToAlpha}[${tag}c]`);+ filters.push(+ `[${tag}c][${m}]blend=c0_mode=normal:c1_mode=normal:c2_mode=normal:c3_mode=multiply${tail}[${out}]`+ );+ return;+ }+ filters.push(`[${cur}]format=rgba,split[${tag}0][${tag}1]`);+ filters.push(`[${tag}1]alphaextract[${tag}a]`);+ filters.push(`[${tag}a][${mask}]blend=all_mode=multiply[${tag}m]`);+ filters.push(`[${tag}0][${tag}m]alphamerge${tail}[${out}]`);+ };+ /** `[cur]` with its alpha set to the gray `[mask]` (a keyed pair's luma+ * piece), into `[out]`; `tail` follows the merge. */+ const alphaSet = (cur: string, mask: string, out: string, tag: string, tail = "") => {+ if (hdr) {+ const m = maskCarrier(mask, `${tag}k`);+ filters.push(`[${cur}][${m}]mergeplanes=0x00010210:format=${alphaHi}${tail}[${out}]`);+ return;+ }+ filters.push(`[${cur}][${mask}]alphamerge${tail}[${out}]`);+ };+ /**+ * `[top]` placed at (`x`, `y`) on a clear W×H frame `dur` seconds long,+ * into `[out]`; `base` names the clear frame. An HDR composite overlays+ * only onto opaque frames (see `opaqueFmt`), and the posed picture may+ * change size every frame, which only `overlay` takes: the color lands with+ * its alpha dropped, and the alpha is read back off the picture laid on a+ * zero frame and on a full one, whose difference is `1 − alpha`.+ */+ const placeOnClear = (top: string, x: string, y: string, dur: number, base: string, out: string) => {+ const frame = `s=${W}x${H}:r=${fps}:d=${num(dur)}`;+ if (!hdr) {+ filters.push(`[email protected]:${frame},format=${alphaFmt}[${base}]`);+ filters.push(`[${base}][${top}]overlay=x=${x}:y=${y}:eof_action=pass${ovl}[${out}]`);+ return;+ }+ const plain = "yuv444p10le";+ const tags = `setparams=range=tv:colorspace=${outMatrixName}`;+ const place = `overlay=x=${x}:y=${y}:eof_action=pass:format=yuv444p10`;+ /** A constant frame with every plane at `level`'s gray value. */+ const flat = (level: "black" | "white") => `color=c=${level}:${frame},format=gray10le,mergeplanes=0x00000000:format=${plain},${tags}`;+ filters.push(`[${top}]format=${alphaHi},split=3[${base}c][${base}z][${base}f]`);+ filters.push(`color=c=black:${frame},format=${plain},${tags}[${base}cb]`);+ filters.push(`[${base}c]format=${plain},${tags}[${base}co]`);+ filters.push(`[${base}cb][${base}co]${place}[${base}cp]`);+ filters.push(`${flat("black")}[${base}zb]`);+ filters.push(`${flat("white")},split[${base}fb][${base}ff]`);+ filters.push(`[${base}zb][${base}z]${place}[${base}zp]`);+ filters.push(`[${base}fb][${base}f]${place}[${base}fp]`);+ filters.push(`[${base}fp][${base}zp]blend=all_mode=subtract[${base}inv]`);+ filters.push(`[${base}ff][${base}inv]blend=all_mode=subtract[${base}ap]`);+ filters.push(`[${base}cp][${base}ap]mergeplanes=0x00010210:format=${alphaHi}[${out}]`);+ };+ const ffMatrix = (m: CodeFormat["matrix"]): string => (m === "bt601" ? "bt601" : m === "bt2020nc" ? "bt2020" : "bt709");+ /** The sharpen and clarity pass on 16-bit 4:4:4 video, luma only: each+ * detail is the luma against its own base (a Gaussian blur, or the guided+ * filter over its window — sized to the picture, run on a reduced copy+ * when the window outgrows the filter's reach), gained and merged back.+ * Both bases read the input luma, so the two controls never feed each+ * other (detail.ts). */+ const detailLines = (inLabel: string, outLabel: string, g: ColorGrade, hPx: number, tag: string): string[] => {+ const ks = detailGain("sharpen", g.sharpen || 0);+ const kc = detailGain("clarity", g.clarity || 0);+ const t = `dt${tag}`;+ const lines: string[] = [];+ const radius = kc > 0 ? detailRadius("clarity", hPx) : 0;+ // guided takes a window up to 20; a wider one runs on a copy reduced to+ // fit and is read back at the picture's own size, off one more copy.+ const sub = Math.ceil(radius / 20);+ const copies = 1 + (ks > 0 ? 2 : 0) + (kc > 0 ? (sub > 1 ? 3 : 2) : 0);+ lines.push(+ `[${inLabel}]split=${copies}[${t}o]${ks > 0 ? `[${t}ss][${t}sr]` : ""}${kc > 0 ? `[${t}cs][${t}cr]${sub > 1 ? `[${t}cx]` : ""}` : ""}`+ );+ const gain = (k: number) => `lutyuv=y=${fexpr(`clip((val-32768)*${num(k)}+32768,0,65535)`)}`;+ const extract = "blend=c0_mode=grainextract";+ const merge = "blend=c0_mode=grainmerge";+ if (ks > 0) {+ lines.push(`[${t}ss]gblur=sigma=${num(detailRadius("sharpen", hPx))}:planes=1[${t}sb]`);+ lines.push(`[${t}sr][${t}sb]${extract},${gain(ks)}[${t}sd]`);+ }+ if (kc > 0) {+ if (sub <= 1) {+ lines.push(`[${t}cs]guided=radius=${radius}:eps=${num(CLARITY_EPS)}:planes=1[${t}cb]`);+ lines.push(`[${t}cr][${t}cb]${extract},${gain(kc)}[${t}cd]`);+ } else {+ const r = Math.max(1, Math.round(radius / sub));+ lines.push(+ `[${t}cs]scale=${fexpr(`ceil(iw/${sub})`)}:${fexpr(`ceil(ih/${sub})`)}:flags=bilinear,` ++ `guided=radius=${r}:eps=${num(CLARITY_EPS)}:planes=1[${t}cq]`+ );+ lines.push(`[${t}cq][${t}cx]scale=rw:rh:flags=bilinear[${t}cb]`);+ lines.push(`[${t}cr][${t}cb]${extract},${gain(kc)}[${t}cd]`);+ }+ }+ let cur = `${t}o`;+ if (ks > 0) {+ const next = kc > 0 ? `${t}m1` : outLabel;+ lines.push(`[${cur}][${t}sd]${merge}[${next}]`);+ cur = next;+ }+ if (kc > 0) lines.push(`[${cur}][${t}cd]${merge}[${outLabel}]`);+ return lines;+ };+ /**+ * How a picture's color runs: the flags its framing scale takes, and the+ * chain that follows the framing — into 16-bit RGB with the file's matrix+ * and range, through the LUT, the detail pass, and back to BT.709 video.+ * Null when the picture is Rec.709 video already and carries no color.+ */+ interface ColorPlan {+ flags: string;+ /** Extend `core` (a chain ending in the framed picture) with the color+ * chain, pushing any multi-input lines; returns the new chain. */+ run: (core: string, tag: string) => string;}- const gradeChain = (grade: ExportSpec["clips"][number]["grade"]): string =>- gradeNeedsLut(grade)- ? gradeLutChain.get(gradeKey(grade)) ?? ""- : gradeToFfmpegFilter(grade);+ const colorPlanFor = (+ o: ColorOwner,+ opts: { alpha: boolean; hPx: number; interpolated: boolean }+ ): ColorPlan | null => {+ const color = colorOf(o);+ const lut = lutFilters.get(recipeId(o)) ?? "";+ const det = o.grade && detailActive(o.grade) ? o.grade : null;+ // A still decodes to RGB, where a matrix means nothing.+ const yuv = !o.image;+ const inFlags = yuv ? `:in_color_matrix=${ffMatrix(color.matrix)}:in_range=${color.fullRange ? "pc" : "tv"}` : "";+ if (!lut && !det) {+ // Nothing to bake: a file whose code values are not the composite's+ // video still converts to it, in video, so the delivery's tags tell+ // the truth.+ if (yuv && (color.matrix !== outMatrixName || color.fullRange)) {+ return { flags: inFlags, run: (core) => `${core},scale${inFlags}:out_color_matrix=${outMatrix}:out_range=tv` };+ }+ return null;+ }+ const rgb16 = opts.alpha ? "gbrap16le" : "gbrp16le";+ const yuv16 = opts.alpha ? "yuva444p16le" : "yuv444p16le";+ return {+ flags: inFlags,+ run: (core, tag) => {+ // Motion interpolation between the framing and here works in video,+ // so the conversion is spelled out again where it actually happens.+ let chain = core + (yuv && opts.interpolated ? `,scale${inFlags},format=${rgb16}` : `,format=${rgb16}`);+ if (lut) chain += `,${lut}`;+ if (det) {+ chain += `,scale=out_color_matrix=${outMatrix}:out_range=pc,format=${yuv16}`;+ filters.push(`${chain}[dti${tag}]`);+ filters.push(...detailLines(`dti${tag}`, `dto${tag}`, det, opts.hPx, tag));+ return `[dto${tag}]null,scale=in_color_matrix=${outMatrix}:in_range=pc:out_color_matrix=${outMatrix}:out_range=tv`;+ }+ return `${chain},scale=out_color_matrix=${outMatrix}:out_range=tv`;+ },+ };+ };+ /** Whether a clip's framing is followed by motion interpolation. */+ const interpolates = (c: { smoothSlow?: boolean; image?: boolean }, rt: Retime): boolean =>+ !c.image && !!c.smoothSlow && slowRuns(rt, 1 / fps).length > 0;// Per-clip timeline length (source span compressed/expanded by speed). A// gap spacer (no file) keeps its exact length: flooring it at 0.1s would@@ -1257,7 +1562,7 @@ export async function runExport(let matteN = 0;if (subjectActive && matteConsumers > 0) {filters.push(- `[${behindMaskInput}:v]fps=${fps},scale=${W}:${H},setsar=1,format=gray,` ++ `[${behindMaskInput}:v]fps=${fps},scale=${W}:${H},setsar=1,format=${maskFmt},` +`tpad=start_duration=${num(Math.max(0, spec.behindMask!.from))}:color=black[bh_src]`);filters.push(@@ -1400,7 +1705,7 @@ export async function runExport(let bg = fx.bg;if (!bg) {bg = `xb${tag}_${side}`;- filters.push(`color=c=${padColor}:s=${w}x${h}:r=${fps}:d=${d},format=${fmt}[${bg}]`);+ filters.push(`color=c=${padColor}:s=${w}x${h}:r=${fps}:d=${d},format=${opaqueFmt(fmt)}[${bg}]`);}if (fx.kind === "xfade") {// Entering: the backdrop hands off to the picture; exiting: the@@ -1584,9 +1889,9 @@ export async function runExport(// never shortens the join, and rides the same framing chain in rgba.let timebase: string;if (rmIn) {- filters.push(`[${rmIn.a}:v]setpts=PTS-STARTPTS,format=gray[rva${j}]`);- filters.push(`[${rmIn.rgb}:v]setpts=PTS-STARTPTS,format=rgba[rvc${j}]`);- filters.push(`[rvc${j}][rva${j}]alphamerge,tpad=stop_mode=clone:stop_duration=1[rvs${j}]`);+ filters.push(`[${rmIn.a}:v]setpts=PTS-STARTPTS,format=${maskFmt}[rva${j}]`);+ filters.push(`[${gfx(`${rmIn.rgb}:v`)}]setpts=PTS-STARTPTS,${rgbToAlpha}[rvc${j}]`);+ alphaSet(`rvc${j}`, `rva${j}`, `rvs${j}`, `rv${j}`, ",tpad=stop_mode=clone:stop_duration=1");timebase = `[rvs${j}]null`;} else {timebase = c.image@@ -1598,8 +1903,16 @@ export async function runExport(// The keyed layer's letterbox stays transparent (the flatten below lays// the frame color behind it), and its alpha survives the chain.const segPad = rmIn ? "[email protected]" : padColor;- const segFmt = rmIn ? "rgba" : clipFmt;+ const segFmt = rmIn ? alphaHi : clipFmt;+ const plan = rmIn+ ? null+ : colorPlanFor(c, {+ alpha: false,+ hPx: framedPictureHeight(c.file, region ? region.rw : W, region ? region.rh : H, c.fit === "fill", c.zoom),+ interpolated: interpolates(c, rt),+ });let frame: string;+ let padding: string;if (region) {// A regioned track-0 clip (split-screen half) scales into its rect,// then pads out to the full frame with black around it. The rect may@@ -1614,28 +1927,26 @@ export async function runExport(const win = bw > W || bh > H ? `,crop=${W}:${H}:${-bx}:${-by}` : "";// The framed picture lands centered in its rect: a covering one fills// the rect exactly, a fitted one keeps its margins.- frame =- `${boxFraming(rw, rh, c.fit === "fill", c.zoom, c.panX, c.panY)}${mirror(c)},` +- `pad=${bw}:${bh}:${rx - bx}+(${rw}-iw)/2:${ry - by}+(${rh}-ih)/2:color=${segPad}${win}`;+ frame = `${boxFraming(rw, rh, c.fit === "fill", c.zoom, c.panX, c.panY, plan?.flags)}${mirror(c)}`;+ padding = `,pad=${bw}:${bh}:${rx - bx}+(${rw}-iw)/2:${ry - by}+(${rh}-ih)/2:color=${segPad}${win}`;} else {const cover = c.fit === "fill";- frame =- boxFraming(W, H, cover, c.zoom, c.panX, c.panY) +- mirror(c) +- // A covering picture already spans the frame; a fitted one letterboxes.- (cover ? "" : `,pad=${W}:${H}:(ow-iw)/2:(oh-ih)/2:color=${segPad}`);+ frame = boxFraming(W, H, cover, c.zoom, c.panX, c.panY, plan?.flags) + mirror(c);+ // A covering picture already spans the frame; a fitted one letterboxes.+ padding = cover ? "" : `,pad=${W}:${H}:(ow-iw)/2:(oh-ih)/2:color=${segPad}`;}// setpts/speed rescales the clip's duration on the timeline (footage);- // a still just replays its looped input.- // The grade sits after the color conversion (so it acts on the same- // BT.709 values the preview shows) and before the terminal format.- let core = `${framedTimebase(timebase, frame, `c${j}`, rmIn ? {} : c, rt, fps, filters)},${rmIn ? "" : colorFix.get(c.file) ?? ""}${gradeChain(rmIn ? undefined : c.grade)}format=${segFmt}`;+ // a still just replays its looped input. The color runs on the framed+ // picture before the letterbox pad, so the bars stay the frame color.+ let core = framedTimebase(timebase, frame, `c${j}`, rmIn ? {} : c, rt, fps, filters);+ if (plan) core = plan.run(core, `c${j}`);+ core += `,format=${segFmt}${padding}`;// The look bakes in after grade + framing, before the edge effects, so// animations move already-graded pixels (matching the preview order). A// removal clip's look runs after the flatten below instead — the chain's// internal blends would drop the keyed layer's alpha.if (c.look && !rmIn) {- const lines = lookFilterLines(`lki${j}`, `lko${j}`, c.look, c.lookAmount, H, clipFmt, `c${j}`);+ const lines = lookFilterLines(`lki${j}`, `lko${j}`, c.look, c.lookAmount, H, clipFmt, `c${j}`, depth);if (lines) {filters.push(`${core}[lki${j}]`);filters.push(...lines);@@ -1647,7 +1958,7 @@ export async function runExport(const brIdx = clipBorderInput.get(j);if (brIdx !== undefined) {filters.push(`${core}[cbi${j}]`);- filters.push(`[cbi${j}][${brIdx}:v]overlay=0:0:eof_action=pass${ovl},format=${segFmt}[cbo${j}]`);+ filters.push(`[cbi${j}][${gfx(`${brIdx}:v`)}]overlay=0:0:eof_action=pass${ovl},format=${segFmt}[cbo${j}]`);core = `[cbo${j}]null`;}// A removal segment carries alpha, so its fades must ramp the alpha@@ -1678,17 +1989,14 @@ export async function runExport(// restores the constant-size opaque frame the join expects. The// multiply chains (alphaextract → blend → alphamerge) compose with// any alpha the segment carries.- pushEdgeFx(core, dur, headFx, tailFx, W, H, rmIn ? alphaFmt : clipFmt, fades, `vmr${j}`, `c${j}`);+ pushEdgeFx(core, dur, headFx, tailFx, W, H, rmIn ? segAlpha : clipFmt, fades, `vmr${j}`, `c${j}`);let cur = `vmr${j}`;if (mkIdx !== undefined) {- filters.push(`[${mkIdx}:v]fps=${fps},scale=${W}:${H},setsar=1,format=gray[cmk${j}]`);- filters.push(`[${cur}]format=rgba,split[cm0_${j}][cm1_${j}]`);- filters.push(`[cm1_${j}]alphaextract[cma${j}]`);- filters.push(`[cma${j}][cmk${j}]blend=all_mode=multiply[cmm${j}]`);- filters.push(`[cm0_${j}][cmm${j}]alphamerge[cmc${j}]`);+ filters.push(`[${mkIdx}:v]fps=${fps},scale=${W}:${H},setsar=1,format=${maskFmt}[cmk${j}]`);+ alphaMultiply(cur, `cmk${j}`, `cmc${j}`, `cm${j}`);cur = `cmc${j}`;} else {- filters.push(`[${cur}]format=rgba[cmc${j}]`);+ filters.push(`[${cur}]${videoToAlpha}[cmc${j}]`);cur = `cmc${j}`;}if (keyed) {@@ -1698,12 +2006,7 @@ export async function runExport(cur = `ckt${j}`;}const pos = posePositionExprs(c.kf!, 0);- filters.push(- `[email protected]:s=${W}x${H}:r=${fps}:d=${num(dur)},format=${alphaFmt}[ckb${j}]`- );- filters.push(- `[ckb${j}][${cur}]overlay=x=${pos.x}:y=${pos.y}:eof_action=pass${ovl}[ckp${j}]`- );+ placeOnClear(cur, pos.x, pos.y, dur, `ckb${j}`, `ckp${j}`);cur = `ckp${j}`;}if (subjMask) {@@ -1715,10 +2018,7 @@ export async function runExport(`setpts=PTS-STARTPTS,fps=${fps},tpad=stop_mode=clone:stop_duration=${num(dur)},` +`trim=0:${num(dur)},setpts=PTS-STARTPTS,fps=${fps}[cms${j}]`);- filters.push(`[${cur}]format=rgba,split[cs0_${j}][cs1_${j}]`);- filters.push(`[cs1_${j}]alphaextract[csa${j}]`);- filters.push(`[csa${j}][cms${j}]blend=all_mode=multiply[csm${j}]`);- filters.push(`[cs0_${j}][csm${j}]alphamerge[csc${j}]`);+ alphaMultiply(cur, `cms${j}`, `csc${j}`, `cs${j}`);cur = `csc${j}`;}// A keyed layer flattens onto the frame color — where the removal@@ -1733,7 +2033,7 @@ export async function runExport();if (flatOut !== segCore) {// The removal clip's look, over the flattened opaque segment.- const lines = lookFilterLines(`vrl${j}`, segCore, c.look!, c.lookAmount, H, clipFmt, `cr${j}`);+ const lines = lookFilterLines(`vrl${j}`, segCore, c.look!, c.lookAmount, H, clipFmt, `cr${j}`, depth);if (lines) filters.push(...lines);else filters.push(`[vrl${j}]null[${segCore}]`);}@@ -1741,7 +2041,7 @@ export async function runExport(pushEdgeFx(core, dur, headFx, tailFx, W, H, clipFmt, fades, segCore, `c${j}`);}if (shIdx !== undefined) {- filters.push(`[${shIdx}:v]fps=${fps},scale=${W}:${H},setsar=1,format=rgba[csh${j}]`);+ filters.push(`[${gfx(`${shIdx}:v`)}]fps=${fps},scale=${W}:${H},setsar=1,${rgbToAlpha}[csh${j}]`);filters.push(`[${segCore}][csh${j}]overlay=0:0:eof_action=pass${ovl},format=${clipFmt},fps=${fps}[${segOut}]`);@@ -1987,7 +2287,14 @@ export async function runExport(const boxH = region ? region.rh : H;// The overlay's picture meets its box the same way a track-0 clip meets// the frame; whatever the box does not swallow sits centered in it.- const framing = boxFraming(boxW, boxH, cover, oc.zoom, oc.panX, oc.panY) + mirror(oc);+ const plan = orIn+ ? null+ : colorPlanFor(oc, {+ alpha: !!oc.image,+ hPx: framedPictureHeight(oc.file, boxW, boxH, cover, oc.zoom),+ interpolated: interpolates(oc, ort),+ });+ const framing = boxFraming(boxW, boxH, cover, oc.zoom, oc.panX, oc.panY, plan?.flags) + mirror(oc);let pos: string;if (!region) {pos = cover ? "0:0" : `x=(${W}-w)/2:y=(${H}-h)/2`;@@ -2023,21 +2330,23 @@ export async function runExport(// and clone-padded, grade and look already baked into the pixels.let timebase: string;if (orIn) {- filters.push(`[${orIn.a}:v]setpts=PTS-STARTPTS,format=gray[ova${k}]`);- filters.push(`[${orIn.rgb}:v]setpts=PTS-STARTPTS,format=rgba[ovc${k}]`);- filters.push(`[ovc${k}][ova${k}]alphamerge,tpad=stop_mode=clone:stop_duration=1[ovr${k}]`);+ filters.push(`[${orIn.a}:v]setpts=PTS-STARTPTS,format=${maskFmt}[ova${k}]`);+ filters.push(`[${gfx(`${orIn.rgb}:v`)}]setpts=PTS-STARTPTS,${rgbToAlpha}[ovc${k}]`);+ alphaSet(`ovc${k}`, `ova${k}`, `ovr${k}`, `ov${k}`, ",tpad=stop_mode=clone:stop_duration=1");timebase = `[ovr${k}]null`;} else {timebase = oc.image? `[${idx}:v]setpts=PTS-STARTPTS`: `[${idx}:v]trim=${num(oc.in)}:${num(oc.out)},setpts=${retimedPts(ort)}`;}- let core = `${framedTimebase(timebase, framing, `o${k}`, orIn ? {} : oc, ort, fps, filters)},${orIn ? "" : colorFix.get(oc.file) ?? ""}${gradeChain(orIn ? undefined : oc.grade)}format=${orIn ? alphaFmt : lookFmt}`;+ let core = framedTimebase(timebase, framing, `o${k}`, orIn ? {} : oc, ort, fps, filters);+ if (plan) core = plan.run(core, `o${k}`);+ core += `,format=${orIn ? alphaFmt : lookFmt}`;// Looks bake into footage overlays only: an image may carry alpha, which// the look chain's internal filters would flatten onto black over the// tracks beneath. The alpha fades stay safe: they apply after the look.if (oc.look && !oc.image && !orIn) {- const lines = lookFilterLines(`olki${k}`, `olko${k}`, oc.look, oc.lookAmount, H, lookFmt, `o${k}`);+ const lines = lookFilterLines(`olki${k}`, `olko${k}`, oc.look, oc.lookAmount, H, lookFmt, `o${k}`, depth);if (lines) {filters.push(`${core}[olki${k}]`);filters.push(...lines);@@ -2050,7 +2359,7 @@ export async function runExport(const obIdx = overlayBorderInput.get(oc);if (obIdx !== undefined) {filters.push(`${core}[obi${k}]`);- filters.push(`[obi${k}][${obIdx}:v]overlay=0:0:eof_action=pass${ovl},format=${fmt}[obo${k}]`);+ filters.push(`[obi${k}][${gfx(`${obIdx}:v`)}]overlay=0:0:eof_action=pass${ovl},format=${fmt}[obo${k}]`);core = `[obo${k}]null`;}const pre = `ovp${k}`;@@ -2072,17 +2381,14 @@ export async function runExport(// scales on the segment's local clock before the delay.let masked = pre;if (maskIdx !== undefined) {- filters.push(`[${maskIdx}:v]fps=${fps},scale=${boxW}:${boxH},setsar=1,format=gray[omk${k}]`);- filters.push(`[${pre}]format=rgba,split[om0${k}][om1${k}]`);- filters.push(`[om1${k}]alphaextract[oma${k}]`);- filters.push(`[oma${k}][omk${k}]blend=all_mode=multiply[omm${k}]`);- filters.push(`[om0${k}][omm${k}]alphamerge,format=${alphaFmt}[omc${k}]`);+ filters.push(`[${maskIdx}:v]fps=${fps},scale=${boxW}:${boxH},setsar=1,format=${maskFmt}[omk${k}]`);+ alphaMultiply(pre, `omk${k}`, `omc${k}`, `om${k}`, `,format=${alphaFmt}`);masked = `omc${k}`;}if (keyed) {const tf = poseTransformFilters(oc.kf!, boxW, boxH);if (tf) {- filters.push(`[${masked}]format=rgba${tf},format=${alphaFmt}[okt${k}]`);+ filters.push(`[${masked}]${videoToAlpha}${tf},format=${alphaFmt}[okt${k}]`);masked = `okt${k}`;}}@@ -2098,7 +2404,7 @@ export async function runExport(if (oshIdx !== undefined) {const lit = `ovsh${k}`;filters.push(- `[${oshIdx}:v]fps=${fps},scale=${W}:${H},setsar=1,format=rgba,` ++ `[${gfx(`${oshIdx}:v`)}]fps=${fps},scale=${W}:${H},setsar=1,${rgbToAlpha},` +`tpad=start_duration=${num(oc.start)}:[email protected][${lit}]`);const shOnto = `vovs${k}`;@@ -2113,12 +2419,7 @@ export async function runExport(const matte = nextMatte(`bso${k}`, subjMask);if (keyed) {const kpos = posePositionExprs(oc.kf!, oc.start);- filters.push(- `[email protected]:s=${W}x${H}:r=${fps}:d=${num(spec.duration)},format=${alphaFmt}[osb${k}]`- );- filters.push(- `[osb${k}][${seg}]overlay=x=${kpos.x}:y=${kpos.y}:eof_action=pass${ovl}[osp${k}]`- );+ placeOnClear(seg, kpos.x, kpos.y, spec.duration, `osb${k}`, `osp${k}`);} else {// The box may reach past the frame; pad to the box holding both and// crop the frame window back out (pad rejects placement outside its@@ -2131,13 +2432,10 @@ export async function runExport(const bh = Math.max(H, padY + boxH) - by;const win = bw > W || bh > H ? `,crop=${W}:${H}:${-bx}:${-by}` : "";filters.push(- `[${seg}]format=rgba,pad=${bw}:${bh}:${padX - bx}:${padY - by}:[email protected]${win}[osp${k}]`+ `[${seg}]${videoToAlpha},pad=${bw}:${bh}:${padX - bx}:${padY - by}:[email protected]${win}[osp${k}]`);}- filters.push(`[osp${k}]format=rgba,split[os0${k}][os1${k}]`);- filters.push(`[os1${k}]alphaextract[osa${k}]`);- filters.push(`[osa${k}][${matte}]blend=all_mode=multiply[osm${k}]`);- filters.push(`[os0${k}][osm${k}]alphamerge,format=${alphaFmt}[osc${k}]`);+ alphaMultiply(`osp${k}`, matte, `osc${k}`, `os${k}`, `,format=${alphaFmt}`);filters.push(`[${onto}][osc${k}]overlay=0:0:${enable}:eof_action=pass${ovl}[${next}]`);} else if (keyed) {const kpos = posePositionExprs(oc.kf!, oc.start);@@ -2203,25 +2501,30 @@ export async function runExport(// by the matte.const matte = nextMatte(`bse${k}`, o.subject);filters.push(- `[${animIdx}:v]format=rgba,` ++ `[${gfx(`${animIdx}:v`)}]${rgbToAlpha},` +`pad=${W}:${H}:${num(o.x ?? 0)}:${num(o.y ?? 0)}:[email protected],setsar=1[oep${k}]`);- filters.push(`[oep${k}]split[oe0${k}][oe1${k}]`);- filters.push(`[oe0${k}]fps=${fps}[oef${k}]`);- filters.push(`[oe1${k}]alphaextract,fps=${fps}[oea${k}]`);- filters.push(`[oea${k}][${matte}]blend=all_mode=multiply[oem${k}]`);- filters.push(`[oef${k}][oem${k}]alphamerge,format=${alphaFmt}[oes${k}]`);+ if (hdr) {+ filters.push(`[oep${k}]fps=${fps}[oef${k}]`);+ alphaMultiply(`oef${k}`, matte, `oes${k}`, `oe${k}`, `,format=${alphaFmt}`);+ } else {+ filters.push(`[oep${k}]split[oe0${k}][oe1${k}]`);+ filters.push(`[oe0${k}]fps=${fps}[oef${k}]`);+ filters.push(`[oe1${k}]alphaextract,fps=${fps}[oea${k}]`);+ filters.push(`[oea${k}][${matte}]blend=all_mode=multiply[oem${k}]`);+ filters.push(`[oef${k}][oem${k}]alphamerge,format=${alphaFmt}[oes${k}]`);+ }filters.push(`[${onto}][oes${k}]overlay=0:0:eof_action=pass${ovl}[${next}]`);return next;}- filters.push(`[${animIdx}:v]format=${alphaFmt},fps=${fps},setsar=1[oanim${k}]`);+ filters.push(`[${gfx(`${animIdx}:v`)}]format=${alphaFmt},fps=${fps},setsar=1[oanim${k}]`);filters.push(`[${onto}][oanim${k}]overlay=${num(o.x ?? 0)}:${num(o.y ?? 0)}:eof_action=pass${ovl}[${next}]`);} else if (o.file) {const idx = inputIndex.get(o.file)!;filters.push(- `[${onto}][${idx}:v]overlay=0:0:enable='gte(t,${num(o.start)})*lt(t,${num(o.end)})'${ovl}[${next}]`+ `[${onto}][${gfx(`${idx}:v`)}]overlay=0:0:enable='gte(t,${num(o.start)})*lt(t,${num(o.end)})'${ovl}[${next}]`);} else {return onto;@@ -2277,7 +2580,7 @@ export async function runExport(// costs one ffmpeg input per language instead of one per still. They sit// over every element and every effect.captionInputs.forEach((idx, k) => {- filters.push(`[${idx}:v]format=${alphaFmt},fps=${fps},setsar=1[caps${k}]`);+ filters.push(`[${gfx(`${idx}:v`)}]format=${alphaFmt},fps=${fps},setsar=1[caps${k}]`);filters.push(`[${vLabel}][caps${k}]overlay=0:0:eof_action=pass${ovl}[vcaps${k}]`);vLabel = `vcaps${k}`;});@@ -2409,6 +2712,20 @@ export async function runExport(aLabel = `afx${k}`;});+ // A PQ delivery: the finished HLG composite through the BT.2100 OOTF at+ // 1000 nits and the ST 2084 curve, one fixed lattice, then back to video.+ if (output === "pq") {+ const file = path.join(job.tmpDir, "hlg_to_pq.cube");+ await io.writeFile(file, lutToCube(buildTransferLut(spec.lutSizeWide ?? 65, hlgToPq), "HLG to PQ"));+ filters.push(+ `[${vLabel}]scale=in_color_matrix=bt2020:in_range=tv,format=gbrp16le,lut3d=file=${fexpr(file)}:interp=tetrahedral,` ++ `scale=out_color_matrix=bt2020:out_range=tv,format=${clipFmt}[vpq]`+ );+ vLabel = "vpq";+ }+ filters.push(`[${vLabel}]${colorParamsFilter(spec)}[vtag]`);+ vLabel = "vtag";+// A range is cut from the finished composite, so it carries what the// timeline shows there — fades, captions, and elements in place.const span = deliverySpan(spec.range, spec.duration);@@ -2436,10 +2753,7 @@ export async function runExport("-map", `[${vLabel}]`,"-map", `[${aLabel}]`,...videoCodecArgs(enc, spec),- "-color_range", "tv",- "-colorspace", "bt709",- "-color_primaries", "bt709",- "-color_trc", "bt709",+ ...colorTagArgs(spec),...audioCodecArgs(spec),"-t", num(span),encodePath,diff --git a/site/src/cut/server/fileColor.test.ts b/site/src/cut/server/fileColor.test.tsnew file mode 100644index 00000000..8a76ad60--- /dev/null+++ b/site/src/cut/server/fileColor.test.ts@@ -0,0 +1,73 @@+import { afterAll, expect, test } from "bun:test";+import { mkdtemp, rm, writeFile } from "node:fs/promises";+import { tmpdir } from "node:os";+import path from "node:path";+import { movieHeader } from "../lib/fixtures/movieHeader";+import type { Overlay, VideoClip } from "../lib/types";+import { probeFileColor, withFileColors, withSpecColors } from "./fileColor";++const dir = await mkdtemp(path.join(tmpdir(), "file-color-"));+afterAll(() => rm(dir, { recursive: true, force: true }));+await writeFile(path.join(dir, "hlg.mp4"), movieHeader({ primaries: 9, transfer: 18, matrix: 9 }));+await writeFile(path.join(dir, "social.mp4"), movieHeader({ primaries: 9, transfer: 18, matrix: 1 }));+const at = (file: string) => path.join(dir, file);++test("a file's color is read off the disk", async () => {+ expect((await probeFileColor(at("hlg.mp4"))).detected).toBe("hlg");+ // A bt709-matrix transcode keeps its HLG tags and is SDR.+ expect((await probeFileColor(at("social.mp4"))).detected).toBe("rec709");+});++test("a spec that arrives without a clip's color reads it from the file", async () => {+ const spec = {+ clips: [+ { file: "hlg.mp4" },+ { file: "social.mp4", color: { profile: "apple-log" as const, matrix: "bt2020nc" as const, fullRange: false } },+ { file: "still.png", image: true },+ { file: "gone.mp4" },+ ],+ overlayVideos: [{ file: "hlg.mp4" }],+ };+ const filled = await withSpecColors(spec, at);+ expect(filled.clips[0].color).toEqual({ profile: "hlg", matrix: "bt2020nc", fullRange: false });+ // What the spec said stands.+ expect(filled.clips[1].color).toEqual(spec.clips[1].color);+ expect(filled.clips[2]).toEqual(spec.clips[2]);+ // A file that is not there is the render's to name.+ expect(filled.clips[3]).toEqual({ file: "gone.mp4" });+ expect((filled.overlayVideos![0] as { color?: unknown }).color).toEqual({ profile: "hlg", matrix: "bt2020nc", fullRange: false });+});++const clipOf = (assetId: string) => ({ assetId }) as VideoClip;++test("assets the timeline draws without a color record get one, once per file", async () => {+ const assets = [+ { id: "1", type: "video", fileName: "hlg.mp4" },+ { id: "2", type: "video", fileName: "hlg.mp4" },+ { id: "3", type: "video", fileName: "social.mp4", color: { detected: "pq" } },+ { id: "4", type: "audio", fileName: "song.mp3" },+ ];+ const filled = await withFileColors(assets, { clips: ["1", "2", "3", "4"].map(clipOf), overlays: [] }, at);+ expect(filled[0].color).toMatchObject({ detected: "hlg", matrix: "bt2020nc", codec: "avc1" });+ expect(filled[1].color).toEqual(filled[0].color);+ expect(filled[2].color).toEqual({ detected: "pq" });+ expect(filled[3]).toEqual(assets[3]);+});++test("an unreadable file nothing draws is skipped; one the timeline draws fails the call", async () => {+ const assets: { id: string; type: string; fileName: string; color?: unknown }[] = [+ { id: "1", type: "video", fileName: "hlg.mp4" },+ { id: "2", type: "video", fileName: "gone.mp4" },+ ];+ // An unused Media-panel file never blocks the project it sits in.+ const filled = await withFileColors(assets, { clips: [clipOf("1")], overlays: [] }, at);+ expect(filled[0].color).toMatchObject({ detected: "hlg" });+ expect(filled[1]).toEqual(assets[1]);+ // An upper-track clip or an element that draws it makes it the render's.+ await expect(withFileColors(assets, { clips: [clipOf("1"), clipOf("2")], overlays: [] }, at)).rejects.toThrow(+ "The color of gone.mp4 could not be read"+ );+ await expect(+ withFileColors(assets, { clips: [], overlays: [{ kind: "sticker", assetId: "2" } as Overlay] }, at)+ ).rejects.toThrow("gone.mp4");+});diff --git a/site/src/cut/server/fileColor.ts b/site/src/cut/server/fileColor.tsnew file mode 100644index 00000000..d0cd7fc3--- /dev/null+++ b/site/src/cut/server/fileColor.ts@@ -0,0 +1,75 @@+/**+ * Source color read off the file on disk.+ *+ * The engine and the worker hold the media themselves, so a clip that+ * reaches them without a color record — a spec from a client that never read+ * the header, an asset imported before the probe existed — is read here with+ * the same header walk the page runs (lib/colorProbe.ts), over ranged reads+ * of the file.+ */++import { open } from "node:fs/promises";+import type { SpecClipColor } from "../lib/exportDelivery";+import { probeColor, probeMissingColors, withFoundColors, type ColorProbe } from "../lib/colorProbe";+import { pictureAssetIds, type ItemLists } from "../lib/itemKinds";++/** The color a file's header describes. */+export async function probeFileColor(filePath: string): Promise<ColorProbe> {+ const handle = await open(filePath, "r");+ try {+ const { size } = await handle.stat();+ return await probeColor(async (offset, length) => {+ const buf = new Uint8Array(Math.max(0, Math.min(length, size - offset)));+ const { bytesRead } = await handle.read(buf, 0, buf.length, offset);+ return buf.subarray(0, bytesRead);+ }, size);+ } finally {+ await handle.close();+ }+}++/** `assets` with the color record of every video the timeline draws filled+ * from its file. A drawn file whose header cannot be read fails the call,+ * naming it; files nothing on the timeline uses are not read. */+export async function withFileColors<A extends { id: string; type: string; fileName: string; color?: unknown; block?: unknown }>(+ assets: A[],+ lists: Pick<ItemLists, "clips" | "overlays">,+ pathFor: (fileName: string) => string+): Promise<A[]> {+ return withFoundColors(assets, await probeMissingColors(assets, pictureAssetIds(lists), (a) => probeFileColor(pathFor(a.fileName))));+}++type SpecSource = { file?: string; image?: boolean; staged?: boolean; color?: SpecClipColor };++/**+ * A render spec whose video sources each carry their color: a clip or video+ * overlay that arrived without one is read from its media file. Stills are+ * sRGB and staged pictures are painted by the page, so neither is read. A+ * file that is not there is left as it came: the render names it missing+ * when it reaches for it.+ */+export async function withSpecColors<S extends { clips: SpecSource[]; overlayVideos?: SpecSource[] }>(+ spec: S,+ mediaPathFor: (file: string) => string+): Promise<S> {+ const owners = [...spec.clips, ...(spec.overlayVideos ?? [])];+ const wanted = new Set(owners.filter((o) => !o.color && !o.image && !o.staged && o.file).map((o) => o.file!));+ if (wanted.size === 0) return spec;+ const colors = new Map<string, SpecClipColor>();+ await Promise.all(+ [...wanted].map(async (file) => {+ const probe = await probeFileColor(mediaPathFor(file)).catch((e: unknown) => {+ if ((e as { code?: string }).code === "ENOENT") return null;+ throw new Error(`The color of ${file} could not be read: ${e instanceof Error ? e.message : String(e)}`);+ });+ if (probe) colors.set(file, { profile: probe.detected, matrix: probe.code.matrix, fullRange: probe.code.fullRange });+ })+ );+ const fill = <T extends SpecSource>(o: T): T =>+ !o.color && o.file && colors.has(o.file) ? { ...o, color: colors.get(o.file) } : o;+ return {+ ...spec,+ clips: spec.clips.map(fill),+ ...(spec.overlayVideos ? { overlayVideos: spec.overlayVideos.map(fill) } : {}),+ } as S;+}diff --git a/site/src/cut/server/http/library.ts b/site/src/cut/server/http/library.tsindex 8346ef9e..4ad54b9b 100644--- a/site/src/cut/server/http/library.ts+++ b/site/src/cut/server/http/library.ts@@ -18,6 +18,7 @@ import {copyLibraryAssetToProject,copyTemplateToProject,type LibrarySource,+ type LinkedMeta,type TemplateInput,} from "../library";import { serveFileRange, wantsDownload } from "../serveFile";@@ -181,12 +182,27 @@ export const libraryApi = {// Malformed notes are dropped; the media still lands.}const poster = form.get("poster");+ // A linked item's row fields (its content key, a LUT's facts) come from+ // the page that checked the file; the engine has no parser for them.+ const metaField = form.get("meta");+ let linked: LinkedMeta | undefined;+ if (typeof metaField === "string" && metaField)+ try {+ const meta = JSON.parse(metaField) as LinkedMeta;+ linked = {+ ...(typeof meta.contentKey === "string" ? { contentKey: meta.contentKey } : {}),+ ...(meta.lut ? { lut: meta.lut } : {}),+ };+ } catch {+ // Malformed fields are dropped; the file still lands.+ }return Response.json(await addUpload(file,typeof name === "string" ? name : undefined,source,poster instanceof File ? poster : undefined,+ linked,form.get("prepare") === "true",),);diff --git a/site/src/cut/server/http/projects.ts b/site/src/cut/server/http/projects.tsindex d3161f4b..083daa06 100644--- a/site/src/cut/server/http/projects.ts+++ b/site/src/cut/server/http/projects.ts@@ -25,6 +25,7 @@ import {writeProject,} from "../projects";import { convertToMp4, mp4NameFor } from "../convert";+import { makeProxy, proxyNameFor } from "../proxy";import { serveFileRange, wantsDownload } from "../serveFile";import { importUrlToProject } from "../urlImport";import { createTranscribeJob, getTranscribeJob, type TranscribeSpec } from "../transcribe";@@ -453,6 +454,28 @@ export const projectsApi = {}},+ /** Build the preview proxy of a ProRes master in this project (see+ * server/proxy.ts). The proxy lands beside the master; writing it onto the+ * asset is the client's call. The page sends the size and quality it was+ * configured with. */+ async proxy(req: Request, { id }: { id: string }) {+ try {+ if (!(await readProject(id))) return err("Project not found.", 404);+ const body = (await req.json()) as { file?: string; maxHeight?: number; crf?: number };+ if (!body.file) return err("file is required.", 400);+ if (typeof body.maxHeight !== "number" || typeof body.crf !== "number") return err("maxHeight and crf are required.", 400);+ const src = mediaPath(id, body.file);+ if (!(await exists(src))) return err("Media file missing from project.", 404);+ const fileName = await uniqueName(proxyNameFor(body.file), (n) => mediaPath(id, n));+ const outPath = mediaPath(id, fileName);+ const handle = { tmpDir: "", outPath, progress: 0, log: [] as string[] };+ const outcome = await makeProxy(handle, src, outPath, { maxHeight: body.maxHeight, crf: body.crf });+ return Response.json({ fileName, ...outcome });+ } catch (e) {+ return caught(e, "Could not make the preview proxy.");+ }+ },+/** Report silent stretches in a media file's audio. */async silence(req: Request, { id }: { id: string }) {try {diff --git a/site/src/cut/server/http/proxy.ts b/site/src/cut/server/http/proxy.tsnew file mode 100644index 00000000..3ad8cb8d--- /dev/null+++ b/site/src/cut/server/http/proxy.ts@@ -0,0 +1,47 @@+import { mkdtemp, readFile, rm, writeFile } from "node:fs/promises";+import os from "node:os";+import path from "node:path";+import { makeProxy, proxyNameFor } from "../proxy";++/**+ * Build a preview proxy of a master the caller supplies, for a project this+ * engine does not store. A browser project's ProRes file lives in the page,+ * and a browser with no 10-bit encoder has nothing to build the proxy with —+ * so the bytes come here, the Mac's ffmpeg encodes them, and the proxy goes+ * back to the page that owns the project. Nothing is kept: the temp+ * directory goes with the response.+ */+export const proxyApi = {+ async create(req: Request) {+ const tmp = await mkdtemp(path.join(os.tmpdir(), "cut-proxy-"));+ try {+ const form = await req.formData();+ const file = form.get("file");+ if (!(file instanceof File)) {+ return Response.json({ error: "file is required." }, { status: 400 });+ }+ const maxHeight = Number(form.get("maxHeight"));+ const crf = Number(form.get("crf"));+ if (!Number.isFinite(maxHeight) || !Number.isFinite(crf)) {+ return Response.json({ error: "maxHeight and crf are required." }, { status: 400 });+ }+ const name = path.basename(file.name) || "source";+ const src = path.join(tmp, name);+ const out = path.join(tmp, proxyNameFor(name));+ await writeFile(src, new Uint8Array(await file.arrayBuffer()));+ const handle = { tmpDir: tmp, outPath: out, progress: 0, log: [] as string[] };+ await makeProxy(handle, src, out, { maxHeight, crf });+ const bytes = await readFile(out);+ return new Response(new Uint8Array(bytes), {+ headers: { "Content-Type": "video/mp4", "Content-Length": String(bytes.length) },+ });+ } catch (e) {+ return Response.json(+ { error: e instanceof Error ? e.message : "Could not make the preview proxy." },+ { status: 500 }+ );+ } finally {+ void rm(tmp, { recursive: true, force: true });+ }+ },+};diff --git a/site/src/cut/server/http/routes.ts b/site/src/cut/server/http/routes.tsindex 40f84270..ef3cd5fd 100644--- a/site/src/cut/server/http/routes.ts+++ b/site/src/cut/server/http/routes.ts@@ -2,6 +2,7 @@ import { matchRouteTable } from "./match";import { aiApi } from "./ai";import { localSceneLease } from "../ai/sceneLease";import { convertApi } from "./convert";+import { proxyApi } from "./proxy";import { engineApi } from "./engine";import { exportApi } from "./export";import { libraryApi } from "./library";@@ -50,6 +51,7 @@ export const CUT_ROUTES: CutRoute[] = [{ method: "POST", path: "/api/cut/projects/:id/image", handler: (req, p) => projectsApi.importImage(req, { id: p.id }) },{ method: "POST", path: "/api/cut/projects/:id/freeze", handler: (req, p) => projectsApi.freeze(req, { id: p.id }) },{ method: "POST", path: "/api/cut/projects/:id/convert", handler: (req, p) => projectsApi.convert(req, { id: p.id }) },+ { method: "POST", path: "/api/cut/projects/:id/proxy", handler: (req, p) => projectsApi.proxy(req, { id: p.id }) },{ method: "POST", path: "/api/cut/projects/:id/silence", handler: (req, p) => projectsApi.silence(req, { id: p.id }) },{ method: "POST", path: "/api/cut/projects/:id/audio", handler: (req, p) => projectsApi.audio(req, { id: p.id }) },{ method: "POST", path: "/api/cut/projects/:id/duplicate", handler: (req, p) => projectsApi.duplicate(req, { id: p.id }) },@@ -101,6 +103,7 @@ export const CUT_ROUTES: CutRoute[] = [{ method: "GET", path: "/api/cut/export/:jobId/file", handler: (req, p) => exportApi.file(req, { jobId: p.jobId }) },{ method: "POST", path: "/api/cut/convert", handler: (req) => convertApi.create(req) },+ { method: "POST", path: "/api/cut/proxy", handler: (req) => proxyApi.create(req) },{ method: "POST", path: "/api/cut/stt", handler: (req) => sttApi.create(req) },{ method: "GET", path: "/api/cut/stt/:jobId", handler: (req, p) => sttApi.status(req, { jobId: p.jobId }) },diff --git a/site/src/cut/server/library.ts b/site/src/cut/server/library.tsindex c171131c..2071ec53 100644--- a/site/src/cut/server/library.ts+++ b/site/src/cut/server/library.ts@@ -4,6 +4,8 @@ import { copyFile, constants, mkdir, readFile, rm, writeFile } from "node:fs/proimport path from "node:path";import type { ClipSound } from "@donkeycut/effects-kit";import { resolveParent, settleParents, subtreeOf } from "@/cut/lib/folderTree";+import { IMAGE_RE, libraryTypeOf, VIDEO_RE } from "@/cut/lib/libraryFileType";+import { isLinkedAssetType, type AssetType } from "@/cut/lib/types";import { cutDataRoot } from "./dataDir";import { assertLocalRuntime } from "./local-only";import { mediaPath as projectMediaPath, readProject } from "./projects";@@ -24,13 +26,20 @@ export interface LibrarySource {uploadDate?: string; // yt-dlp YYYYMMDD}-export interface LibraryAsset {+/** What a linked item carries on its row instead of streams: the content key+ * every project names it by, and for a LUT what kind of table it holds. */+export interface LinkedMeta {+ contentKey?: string;+ lut?: { kind: "1d" | "3d" | "shaper+3d"; size: number };+}++export interface LibraryAsset extends LinkedMeta {id: string;fileName: string;/** Uploaded source retained when playback needs conversion. */originalFile?: string;name: string;- type: "video" | "audio" | "image" | "font";+ type: AssetType;duration: number;width?: number;height?: number;@@ -67,7 +76,7 @@ export interface LibraryFolder {export interface TemplateMedia {fileName: string; // private copy inside the library media foldername: string;- type: "video" | "audio" | "image" | "font";+ type: AssetType;duration: number;width?: number;height?: number;@@ -119,6 +128,8 @@ export interface LibraryTemplate {cues: unknown[]; // opaque SubtitleCue[]/** A template carrying only this is a saved sound preset. */sound?: ClipSound;+ /** A template carrying only this is a saved colour grade. */+ grade?: unknown;/** Opaque, round-tripped for the client: transition bars, which texts are* stickers drawn from media, the caption look, the source's frame. */transitions?: unknown[];@@ -197,11 +208,6 @@ export async function listLibrary(): Promise<LibraryAsset[]> {return idx.assets.sort((a, b) => b.addedAt - a.addedAt);}-const VIDEO_RE = /\.(mp4|mov|m4v|webm|mkv)$/i;-const AUDIO_RE = /\.(mp3|m4a|aac|wav|ogg|flac)$/i;-const IMAGE_RE = /\.(png|jpe?g|webp|gif|avif|bmp)$/i;-const FONT_RE = /\.(ttf|otf|woff2?)$/i;-function ffprobe(args: string[]): Promise<string> {return new Promise((resolve, reject) => {const p = spawn("ffprobe", ["-v", "error", ...args]);@@ -260,25 +266,20 @@ async function freeName(original: string) {return uniqueName(base, libMediaPath);}-function typeOf(fileName: string): "video" | "audio" | "image" | "font" | null {- if (VIDEO_RE.test(fileName)) return "video";- if (AUDIO_RE.test(fileName)) return "audio";- if (IMAGE_RE.test(fileName)) return "image";- if (FONT_RE.test(fileName)) return "font";- return null;-}-export async function register(fileName: string,name: string,source?: LibrarySource,posterFile?: string,+ linked?: LinkedMeta,originalFile?: string,): Promise<LibraryAsset> {- const type = typeOf(fileName);+ const type = libraryTypeOf(fileName);if (!type) throw new Error("Unsupported file type.");+ // A linked item has no streams to measure; the page that checked it sends+ // what its row carries instead.const meta: { duration: number; width?: number; height?: number } =- type === "font" ? { duration: 0 } : await probe(libMediaPath(fileName));+ isLinkedAssetType(type) ? { duration: 0 } : await probe(libMediaPath(fileName));const asset: LibraryAsset = {id: crypto.randomUUID().slice(0, 8),fileName,@@ -291,6 +292,8 @@ export async function register(folderId: null,...(source ? { source } : {}),...(posterFile ? { posterFile } : {}),+ ...(linked?.contentKey ? { contentKey: linked.contentKey } : {}),+ ...(linked?.lut ? { lut: linked.lut } : {}),};await mutateIndex((idx) => {idx.assets.push(asset);@@ -304,9 +307,10 @@ export async function addUpload(name?: string,source?: LibrarySource,poster?: File,+ linked?: LinkedMeta,prepare = false,): Promise<LibraryAsset> {- if (!typeOf(file.name)) throw new Error("Unsupported file type.");+ if (!libraryTypeOf(file.name)) throw new Error("Unsupported file type.");await mkdir(libMedia(), { recursive: true });const fileName = await freeName(file.name);await writeFile(@@ -334,7 +338,7 @@ export async function addUpload(const outcome = await convertToMp4(handle, libMediaPath(fileName), libMediaPath(playback));if (outcome.unchanged) playback = fileName;}- return await register(playback, name?.trim() || file.name, source, posterFile,+ return await register(playback, name?.trim() || file.name, source, posterFile, linked,playback === fileName ? undefined : fileName);} catch (error) {await removeFiles([...new Set([fileName, playback, ...(posterFile ? [posterFile] : [])])]);@@ -364,7 +368,7 @@ export async function addDownloaded(source?: LibrarySource,posterPath?: string,): Promise<LibraryAsset> {- if (!typeOf(srcPath)) throw new Error("Unsupported file type.");+ if (!libraryTypeOf(srcPath)) throw new Error("Unsupported file type.");await mkdir(libMedia(), { recursive: true });const dest = await freeName(path.basename(srcPath));await copyFile(srcPath, libMediaPath(dest));@@ -545,16 +549,17 @@ export interface TemplateInput {texts: unknown[];cues: unknown[];sound?: LibraryTemplate["sound"];+ grade?: unknown;transitions?: unknown[];stickers?: unknown[];captions?: unknown;project?: unknown;}-/** A template with nothing on it saves nothing; a sound preset is a template- * carrying only its treatment. */+/** A template with nothing on it saves nothing; a sound preset or a saved+ * grade is a template carrying only its treatment. */const templateEmpty = (input: TemplateInput) =>- !input.media?.length && !input.texts?.length && !input.cues?.length && !input.sound;+ !input.media?.length && !input.texts?.length && !input.cues?.length && !input.sound && !input.grade;export async function listTemplates(): Promise<LibraryTemplate[]> {const idx = await readIndex();diff --git a/site/src/cut/server/projects.ts b/site/src/cut/server/projects.tsindex e21ef264..230e6fa6 100644--- a/site/src/cut/server/projects.ts+++ b/site/src/cut/server/projects.ts@@ -301,7 +301,7 @@ const ORPHAN_MAX_AGE_MS = 24 * 60 * 60 * 1000;export async function sweepOrphanMedia(id: string, doc: ProjectDoc): Promise<void> {const dir = mediaDir(id);const names = await readdir(dir).catch(() => [] as string[]);- const referenced = new Set(doc.assets.map((a) => a.fileName));+ const referenced = new Set(doc.assets.flatMap((a) => (a.proxy ? [a.fileName, a.proxy.fileName] : [a.fileName])));const cutoff = Date.now() - ORPHAN_MAX_AGE_MS;for (const name of names) {if (referenced.has(name) || name.startsWith(".")) continue;diff --git a/site/src/cut/server/proxy.test.ts b/site/src/cut/server/proxy.test.tsnew file mode 100644index 00000000..f58a8374--- /dev/null+++ b/site/src/cut/server/proxy.test.ts@@ -0,0 +1,136 @@+import { afterAll, beforeAll, describe, expect, test } from "bun:test";+import { execFileSync } from "node:child_process";+import { mkdtemp, readFile, rm } from "node:fs/promises";+import os from "node:os";+import path from "node:path";+import { fileURLToPath } from "node:url";+import { makeProxy, probeProxySource, proxyFfmpegArgs, proxyMatrixOf, proxyNameFor } from "./proxy";+import { openMedia, probeMediaFile, videoTrackOf } from "@/cut/lib/mediaRead";++const FIXTURE = path.join(path.dirname(fileURLToPath(import.meta.url)), "../lib/fixtures/prores-422hq-10bit.mov");++let dir: string;+beforeAll(async () => { dir = await mkdtemp(path.join(os.tmpdir(), "cut-proxy-test-")); });+afterAll(async () => { await rm(dir, { recursive: true, force: true }); });+const handle = (out: string) => ({ tmpDir: dir, outPath: out, progress: 0, log: [] as string[] });+const ffprobe = (args: string[]) =>+ execFileSync("ffprobe", ["-v", "error", ...args], { timeout: 30_000 }).toString();+const ffmpeg = (args: string[]) =>+ execFileSync("ffmpeg", ["-hide_banner", "-loglevel", "error", ...args], { timeout: 30_000 });++/** The RGB of the fixture's flat picture as ffmpeg decodes `file` through+ * `matrix`, 16 bits per channel. */+function rgbThrough(file: string, matrix: string): number[] {+ const raw = ffmpeg([+ "-i", file, "-frames:v", "1",+ "-vf", `scale=in_color_matrix=${matrix}:in_range=tv:out_range=pc,format=gbrp16le,crop=1:1:32:32`,+ "-f", "rawvideo", "-pix_fmt", "rgb48le", "-",+ ]);+ return [raw.readUInt16LE(0), raw.readUInt16LE(2), raw.readUInt16LE(4)];+}++describe("proxy", () => {+ test("names the proxy beside its master", () => {+ expect(proxyNameFor("IMG_4450.MOV")).toBe("IMG_4450.proxy.mp4");+ expect(proxyNameFor("clip")).toBe("clip.proxy.mp4");+ });++ test("reads the master's matrix from ffprobe's names, untagged as Rec.709", () => {+ expect(proxyMatrixOf("bt2020nc")).toBe("bt2020nc");+ expect(proxyMatrixOf("smpte170m")).toBe("bt601");+ expect(proxyMatrixOf("bt709")).toBe("bt709");+ expect(proxyMatrixOf(undefined)).toBe("bt709");+ });++ test("builds the graph: master matrix in, Rec.709 limited out, 10-bit, tagged, timestamps kept", () => {+ const args = proxyFfmpegArgs("in.mov", "out.mp4", {+ encoder: "libx265",+ source: { matrix: "bt2020nc", fullRange: false, height: 2160, hasAudio: true },+ maxHeight: 1080,+ crf: 18,+ });+ const graph = args[args.indexOf("-vf") + 1];+ expect(graph).toBe(+ "scale=in_color_matrix=bt2020:in_range=tv:out_range=pc:w=-2:h=1080,format=gbrp16le," ++ "scale=out_color_matrix=bt709:out_range=tv,format=yuv420p10le," ++ "setparams=color_primaries=bt709:color_trc=iec61966-2-1:colorspace=bt709:range=tv"+ );+ expect(args.slice(0, 4)).toEqual(["-y", "-copyts", "-i", "in.mov"]);+ expect(args).toContain("-crf");+ expect(args[args.indexOf("-crf") + 1]).toBe("18");+ expect(args[args.indexOf("-profile:v") + 1]).toBe("main10");+ expect(args[args.indexOf("-c:a") + 1]).toBe("aac");+ expect(args[args.indexOf("-movflags") + 1]).toBe("+faststart");++ const vt = proxyFfmpegArgs("in.mov", "out.mp4", {+ encoder: "hevc_videotoolbox",+ source: { matrix: "bt709", fullRange: true, height: 1080, hasAudio: false },+ maxHeight: 2160,+ crf: 18,+ });+ const vtGraph = vt[vt.indexOf("-vf") + 1];+ expect(vtGraph.startsWith("scale=in_color_matrix=bt709:in_range=pc:out_range=pc,")).toBe(true);+ expect(vtGraph).toContain("format=p010le");+ expect(vt).not.toContain("-c:a");+ expect(vt).not.toContain("0:a:0");+ expect(vt[vt.indexOf("-c:v") + 1]).toBe("hevc_videotoolbox");+ });++ test("reads the fixture as a 10-bit BT.2020 ProRes master with sound", async () => {+ expect(await probeProxySource(FIXTURE)).toEqual({ matrix: "bt2020nc", fullRange: false, height: 64, hasAudio: true });+ });++ test("makes a Rec.709-tagged Main10 proxy whose RGB and timestamps match the master", async () => {+ const out = path.join(dir, "fixture.proxy.mp4");+ const outcome = await makeProxy(handle(out), FIXTURE, out, { maxHeight: 2160, crf: 18 });+ expect(outcome).toMatchObject({ width: 64, height: 64 });+ expect(outcome.sizeBytes).toBeGreaterThan(0);++ const stream = ffprobe([+ "-select_streams", "v:0",+ "-show_entries", "stream=codec_name,profile,pix_fmt,color_space,color_range,color_primaries,color_transfer,codec_tag_string",+ "-of", "json", out,+ ]);+ expect(JSON.parse(stream).streams[0]).toMatchObject({+ codec_name: "hevc",+ profile: "Main 10",+ pix_fmt: "yuv420p10le",+ color_space: "bt709",+ color_range: "tv",+ color_primaries: "bt709",+ color_transfer: "iec61966-2-1",+ codec_tag_string: "hvc1",+ });+ expect(ffprobe(["-select_streams", "a:0", "-show_entries", "stream=codec_name", "-of", "csv=p=0", out]).trim()).toBe("aac");++ // The same picture: the master through its own matrix, the proxy+ // through Rec.709, within a 10-bit code value at 16-bit scale.+ const master = rgbThrough(FIXTURE, "bt2020");+ const proxy = rgbThrough(out, "bt709");+ for (let c = 0; c < 3; c++) expect(Math.abs(master[c] - proxy[c])).toBeLessThan(96);+ // And unmistakably a different picture through the wrong matrix.+ const wrong = rgbThrough(out, "bt2020");+ expect(Math.max(...wrong.map((v, c) => Math.abs(v - master[c])))).toBeGreaterThan(400);++ // Frame N of the proxy sits where frame N of the master sits, as the+ // page's reader sees both.+ const firstOf = async (file: string) => {+ const input = openMedia(new Blob([await readFile(file)]));+ try {+ const track = await videoTrackOf(input);+ return track!.getFirstTimestamp();+ } finally {+ input.dispose();+ }+ };+ expect(await firstOf(out)).toBeCloseTo(await firstOf(FIXTURE), 3);+ expect((await probeMediaFile(new Blob([await readFile(out)]))).duration).toBeCloseTo(+ (await probeMediaFile(new Blob([await readFile(FIXTURE)]))).duration,+ 1+ );++ // faststart: the index rides ahead of the samples.+ const bytes = await readFile(out);+ expect(bytes.indexOf("moov")).toBeLessThan(bytes.indexOf("mdat"));+ }, 60_000);+});diff --git a/site/src/cut/server/proxy.ts b/site/src/cut/server/proxy.tsnew file mode 100644index 00000000..275c2f2f--- /dev/null+++ b/site/src/cut/server/proxy.ts@@ -0,0 +1,176 @@+import { spawn } from "node:child_process";+import { stat } from "node:fs/promises";+import { runFfmpeg, videoEncoder, vtQuality, type RenderHandle } from "./exportPipeline";+import { assertGraphSafe } from "./filterGraph";+import { videoDimensions } from "./util";++/**+ * The preview proxy of a ProRes master: a 10-bit HEVC file the browser's+ * hardware decoder plays at speed, kept beside the master in the project's+ * media. The master stays what an export reads.+ *+ * The proxy carries the master's code values through the Rec.709 matrix: the+ * picture is taken out of the master's own matrix (BT.2020 non-constant on an+ * iPhone Apple Log file) into RGB at 16 bits and put back through Rec.709,+ * limited range, and the file is tagged Rec.709 / sRGB / Rec.709 all the way+ * down. Every decoder then draws the proxy's frames untouched — no tone+ * mapping, no gamut conversion — and the grade pipeline reads what the values+ * mean from the asset's `color`, which is still the master's. Timestamps are+ * copied, so frame N of the proxy sits where frame N of the master sits.+ *+ * The engine encodes with VideoToolbox, the worker with x265; both run the+ * argument list `proxyFfmpegArgs` builds.+ */++/** The proxy's file name beside its master: same stem, `.proxy.mp4`. */+export const proxyNameFor = (fileName: string) =>+ `${fileName.replace(/\.[^./\\]+$/, "") || "media"}.proxy.mp4`;++export type ProxyMatrix = "bt709" | "bt601" | "bt2020nc";++/** What the proxy is built from: the master's matrix and range, its height,+ * and whether it carries sound. */+export interface ProxySource {+ matrix: ProxyMatrix;+ fullRange: boolean;+ height: number;+ hasAudio: boolean;+}++export type ProxyEncoder = "hevc_videotoolbox" | "libx265";++export interface ProxyArgs {+ encoder: ProxyEncoder;+ source: ProxySource;+ /** The proxy's largest height; a taller master is scaled down. */+ maxHeight: number;+ /** x265 crf; VideoToolbox's constant quality maps from it. */+ crf: number;+}++/** swscale's name for a matrix. */+const SWS_MATRIX: Record<ProxyMatrix, string> = { bt709: "bt709", bt601: "bt601", bt2020nc: "bt2020" };++/** ffmpeg's color_space name for what ffprobe reports. Untagged is Rec.709,+ * the reading every NLE gives an untagged file. */+export function proxyMatrixOf(colorSpace: string | undefined): ProxyMatrix {+ if (colorSpace === "bt2020nc" || colorSpace === "bt2020c") return "bt2020nc";+ if (colorSpace === "smpte170m" || colorSpace === "bt470bg" || colorSpace === "bt601") return "bt601";+ return "bt709";+}++/** The ffmpeg argument list for one proxy. */+export function proxyFfmpegArgs(src: string, out: string, opts: ProxyArgs): string[] {+ const { source, encoder } = opts;+ const cap = Math.max(2, Math.round(opts.maxHeight));+ const shrink = source.height > cap;+ // Even dimensions: 4:2:0 has no odd sizes.+ const size = shrink ? `:w=-2:h=${cap - (cap % 2)}` : "";+ const graph = [+ `scale=in_color_matrix=${SWS_MATRIX[source.matrix]}:in_range=${source.fullRange ? "pc" : "tv"}:out_range=pc${size}`,+ "format=gbrp16le",+ "scale=out_color_matrix=bt709:out_range=tv",+ `format=${encoder === "libx265" ? "yuv420p10le" : "p010le"}`,+ // The frames carry the tags the encoder writes into its own headers;+ // the stream options below cover the container.+ "setparams=color_primaries=bt709:color_trc=iec61966-2-1:colorspace=bt709:range=tv",+ ].join(",");+ const video =+ encoder === "libx265"+ ? ["-c:v", "libx265", "-preset", "medium", "-crf", String(opts.crf), "-profile:v", "main10", "-x265-params", "log-level=error"]+ : ["-c:v", "hevc_videotoolbox", "-profile:v", "main10", "-q:v", String(vtQuality(opts.crf)), "-allow_sw", "1"];+ return [+ "-y",+ // The master's timestamps, unshifted: the preview maps clip time to+ // proxy time exactly as it maps it to master time.+ "-copyts",+ "-i", src,+ "-map", "0:v:0",+ ...(source.hasAudio ? ["-map", "0:a:0"] : []),+ "-vf", assertGraphSafe(graph),+ "-color_primaries", "bt709",+ "-color_trc", "iec61966-2-1",+ "-colorspace", "bt709",+ "-color_range", "tv",+ ...video,+ "-tag:v", "hvc1",+ ...(source.hasAudio ? ["-c:a", "aac", "-b:a", "192k"] : []),+ "-movflags", "+faststart",+ out,+ ];+}++/** Read what the proxy is built from off the master's header. */+export function probeProxySource(file: string): Promise<ProxySource> {+ return new Promise((resolve, reject) => {+ const p = spawn("ffprobe", [+ "-v", "error",+ "-show_entries", "stream=codec_type,color_space,color_range,height:stream_side_data=rotation",+ "-of", "json",+ file,+ ]);+ let out = "";+ const timer = setTimeout(() => {+ p.kill("SIGKILL");+ reject(new Error("Media inspection timed out."));+ }, 30_000);+ timer.unref();+ p.stdout.on("data", (d) => (out += d));+ p.on("close", (code) => {+ clearTimeout(timer);+ if (code !== 0) return reject(new Error("Could not inspect this media file."));+ try {+ const streams = (JSON.parse(out).streams ?? []) as {+ codec_type?: string;+ color_space?: string;+ color_range?: string;+ height?: number;+ width?: number;+ side_data_list?: { rotation?: number }[];+ }[];+ const video = streams.find((s) => s.codec_type === "video");+ if (!video) return reject(new Error("That file carries no video."));+ resolve({+ matrix: proxyMatrixOf(video.color_space),+ fullRange: video.color_range === "pc",+ height: Number(video.height) || 0,+ hasAudio: streams.some((s) => s.codec_type === "audio"),+ });+ } catch (error) {+ reject(error);+ }+ });+ p.on("error", (error) => {+ clearTimeout(timer);+ reject(error);+ });+ });+}++/** The HEVC encoder this machine's ffmpeg carries: x265 in the worker's+ * build, VideoToolbox on the Mac's. */+export async function proxyEncoder(): Promise<ProxyEncoder> {+ return (await videoEncoder("hevc")) === "libx265" ? "libx265" : "hevc_videotoolbox";+}++export interface ProxyOutcome {+ sizeBytes: number;+ width?: number;+ height?: number;+}++/** Build the proxy of `src` at `out`. */+export async function makeProxy(+ handle: RenderHandle,+ src: string,+ out: string,+ opts: { maxHeight: number; crf: number; onProgress?: (seconds: number) => void }+): Promise<ProxyOutcome> {+ const [source, dims, encoder] = await Promise.all([probeProxySource(src), videoDimensions(src), proxyEncoder()]);+ // The display height decides the scale — a phone's sideways file is+ // measured upright everywhere else in Cut.+ if (dims) source.height = dims.height;+ await runFfmpeg(handle, proxyFfmpegArgs(src, out, { encoder, source, maxHeight: opts.maxHeight, crf: opts.crf }), opts.onProgress);+ const [info, outDims] = await Promise.all([stat(out), videoDimensions(out)]);+ return { sizeBytes: info.size, ...(outDims ? { width: outDims.width, height: outDims.height } : {}) };+}diff --git a/site/src/cut/server/serveFile.ts b/site/src/cut/server/serveFile.tsindex 184b2709..68c3565a 100644--- a/site/src/cut/server/serveFile.ts+++ b/site/src/cut/server/serveFile.ts@@ -26,6 +26,8 @@ const TYPES: Record<string, string> = {".otf": "font/otf",".woff": "font/woff",".woff2": "font/woff2",+ ".cube": "text/plain",+ ".3dl": "text/plain",};export function contentTypeFor(p: string) {diff --git a/site/src/cut/server/templateExtras.ts b/site/src/cut/server/templateExtras.tsindex b73446c9..23fd73a2 100644--- a/site/src/cut/server/templateExtras.ts+++ b/site/src/cut/server/templateExtras.ts@@ -8,6 +8,8 @@ export interface TemplateExtras {stickers?: unknown[];captions?: unknown;project?: unknown;+ /** A saved colour grade: a template carrying only this is a grade preset. */+ grade?: unknown;}export const templateExtras = (input: TemplateExtras): TemplateExtras => ({@@ -15,4 +17,5 @@ export const templateExtras = (input: TemplateExtras): TemplateExtras => ({...(input.stickers?.length ? { stickers: input.stickers } : {}),...(input.captions ? { captions: input.captions } : {}),...(input.project ? { project: input.project } : {}),+ ...(input.grade ? { grade: input.grade } : {}),});diff --git a/site/src/cut/server/turnMedia.test.ts b/site/src/cut/server/turnMedia.test.tsindex 3e111097..05f65a6a 100644--- a/site/src/cut/server/turnMedia.test.ts+++ b/site/src/cut/server/turnMedia.test.ts@@ -29,7 +29,6 @@ const spec = (over: Partial<TurnSpec> = {}): TurnSpec => ({hi: 6,video: true,audio: true,- colorFix: "",fmt: "yuv420p",...over,});diff --git a/site/src/cut/server/turnMedia.ts b/site/src/cut/server/turnMedia.tsindex 5ec442e8..b9f6f50a 100644--- a/site/src/cut/server/turnMedia.ts+++ b/site/src/cut/server/turnMedia.ts@@ -53,9 +53,6 @@ export interface TurnSpec {/** Which streams the source carries; the file carries the same. */video: boolean;audio: boolean;- /** The picture's fold to BT.709 (see `sdrConvert`), run before the turn so- * the file is plain SDR the graph converts nothing about. */- colorFix: string;/** Bytes a second of the source's picture comes to decoded (see* `videoDecodeCost`), which sizes the chunks. */decodeCost?: number;@@ -100,7 +97,7 @@ export async function bakeTurnedMedia(const piece = `${outFile}.${i}${spec.video ? ".mov" : ".wav"}`;const args = ["-y", "-hide_banner", "-loglevel", "error", "-ss", num(from), "-t", num(to - from), "-i", src];if (spec.video) {- args.push("-vf", `${spec.colorFix}reverse,format=${spec.fmt}`);+ args.push("-vf", `reverse,format=${spec.fmt}`);args.push(...(spec.master? ["-c:v", "prores_ks", "-profile:v", "4", "-vendor", "apl0", "-pix_fmt", "yuv444p10le"]diff --git a/site/src/cut/server/urlDownload.ts b/site/src/cut/server/urlDownload.tsindex 7ea0301d..39b52d04 100644--- a/site/src/cut/server/urlDownload.ts+++ b/site/src/cut/server/urlDownload.ts@@ -203,7 +203,7 @@ export async function playableMedia(file: string): Promise<string> {const codecs = await streamCodecs(file);// Sound alone decodes everywhere the import goes.if (!codecs.video) return file;- if (fitsAlready(file, codecs, { shrink: false, sdr: false })) return file;+ if (fitsAlready(file, codecs, { shrink: false })) return file;const out = path.join(path.dirname(file), `${path.parse(file).name}.h264.mp4`);try {await convertToMp4({ log: [], outPath: out, progress: 0, tmpDir: path.dirname(file) }, file, out);diff --git a/site/src/cut/server/util.ts b/site/src/cut/server/util.tsindex b2630363..a5fb5916 100644--- a/site/src/cut/server/util.ts+++ b/site/src/cut/server/util.ts@@ -89,48 +89,6 @@ export function atempoChain(speed: number) {return parts.join(",");}-/**- * The first video stream's color tags (e.g. primaries "bt2020", transfer- * "arib-std-b67"), or null when the probe fails or the file has no video- * stream. Untagged fields come back undefined.- */-export function videoColorInfo(- file: string-): Promise<{ primaries?: string; transfer?: string; matrix?: string } | null> {- return new Promise((resolve) => {- const p = spawn("ffprobe", [- "-v", "error",- "-select_streams", "v:0",- "-show_entries", "stream=color_primaries,color_transfer,color_space",- "-of", "json",- file,- ]);- let out = "";- const timer = setTimeout(() => {- p.kill("SIGKILL");- resolve(null);- }, 30_000);- timer.unref();- p.stdout.on("data", (d) => (out += d));- p.on("close", (code) => {- clearTimeout(timer);- if (code !== 0) return resolve(null);- try {- const s = JSON.parse(out).streams?.[0];- resolve(- s ? { primaries: s.color_primaries, transfer: s.color_transfer, matrix: s.color_space } : null- );- } catch {- resolve(null);- }- });- p.on("error", () => {- clearTimeout(timer);- resolve(null);- });- });-}-/*** The first video stream's coded size, or null when the probe fails or the file* has no video. Reported in display orientation: ffprobe gives coded dimensions,diff --git a/site/src/cut/worker/Dockerfile b/site/src/cut/worker/Dockerfileindex f3a4949c..43c1b174 100644--- a/site/src/cut/worker/Dockerfile+++ b/site/src/cut/worker/Dockerfile@@ -32,6 +32,22 @@ RUN ffmpeg -hide_banner -encoders 2>&1 | grep -q '\blibx264\b' \# only encoder on this image.RUN ffmpeg -hide_banner -encoders 2>&1 | grep -q '\blibx265\b' \|| { echo "ffmpeg has no libx265: HEVC exports cannot encode." >&2; exit 1; }+# The color pipeline: every graded clip runs through lut3d in 16-bit RGB, and+# sharpen and clarity through gblur, guided and blend. A build missing one+# of them fails the graph at render time, so it fails here.+RUN for f in lut3d guided gblur blend split lutyuv; do \+ ffmpeg -hide_banner -filters 2>&1 | grep -q " $f " \+ || { echo "ffmpeg has no $f filter: the color pipeline cannot render." >&2; exit 1; }; \+ done+# Clarity's reduced copy comes back to the picture's size through scale's+# reference input (rw/rh), which ffmpeg gained in 7.1.+RUN ffmpeg -hide_banner -loglevel error -f lavfi -i color=s=8x8:d=0.1 -f lavfi -i color=s=4x4:d=0.1 \+ -filter_complex '[1:v][0:v]scale=rw:rh' -f null - \+ || { echo "ffmpeg's scale takes no reference input: the clarity pass cannot render." >&2; exit 1; }+# 10-bit input into libx265: the graded picture is sampled at 16 bits and+# handed to the encoder as 10-bit planes.+RUN ffmpeg -hide_banner -h encoder=libx265 2>&1 | grep -q 'yuv420p10le' \+ || { echo "libx265 takes no 10-bit input: HDR and 10-bit exports cannot encode." >&2; exit 1; }WORKDIR /app# The browser primitives a job draws and decodes with: the server canvas, thediff --git a/site/src/cut/worker/db.ts b/site/src/cut/worker/db.tsindex 0c05f277..cdb4d6ca 100644--- a/site/src/cut/worker/db.ts+++ b/site/src/cut/worker/db.ts@@ -39,7 +39,7 @@ export interface ClaimedJob {/** The kinds someone is watching happen: an export, a URL import, or a chat* turn has a progress surface on screen, while a hover proxy and a share card* are background polish nobody is waiting on. */-const WATCHED_KINDS = ["export", "import_url", "convert", "agent_turn"];+const WATCHED_KINDS = ["export", "import_url", "convert", "proxy", "agent_turn"];/** Atomically claim the next queued job: the updateMany's state guard makes* exactly one worker win each row, so replicas never double-run a job.diff --git a/site/src/cut/worker/exportJob.ts b/site/src/cut/worker/exportJob.tsindex 5c88fe8f..b085957d 100644--- a/site/src/cut/worker/exportJob.ts+++ b/site/src/cut/worker/exportJob.ts@@ -11,6 +11,8 @@ import { overlayKey } from "../server/cloud/r2";import { STORAGE_FULL } from "../lib/operationFailure";import { specMediaFiles } from "../lib/exportDelivery";import { runnerSession } from "./session";+import { bindCutColor } from "../lib/colorSettings";+import { getGlobalSetting } from "@/lib/config/effective";/** The stored spec of an export/preview CutRenderJob: the engine export spec* plus the R2 keys of the browser-rendered overlay PNGs (title/caption stills@@ -136,6 +138,8 @@ export async function runExportJob(// own straight into it, so it exists before the spec does.handle.tmpDir = path.join(work, "overlays");await mkdir(handle.tmpDir, { recursive: true });+ // A doc-built spec sizes its LUTs from the same setting the tab binds.+ if (stored.fromDoc) bindCutColor(await getGlobalSetting("cutColor"));const body: ExportJobSpec = stored.fromDoc? {...stored,diff --git a/site/src/cut/worker/importUrlJob.ts b/site/src/cut/worker/importUrlJob.tsindex c7a5701f..65214133 100644--- a/site/src/cut/worker/importUrlJob.ts+++ b/site/src/cut/worker/importUrlJob.ts@@ -3,7 +3,8 @@ import os from "node:os";import path from "node:path";import type { Prisma } from "@/generated/prisma/client";import { deleteLibraryAssetCascade } from "../server/cloud/library";-import { dedupeName, inspirationFolderId, safeFileName, typeOf } from "../server/cloud/util";+import { libraryTypeOf } from "../lib/libraryFileType";+import { dedupeName, inspirationFolderId, safeFileName } from "../server/cloud/util";import type { LibraryAsset } from "../server/library";import { probeDuration } from "../server/frames";import { download } from "../server/urlDownload";@@ -199,7 +200,7 @@ async function addLibraryRow(posterFile?: string,filing?: { folderId: string; origin: "inspiration" }): Promise<LibraryAsset> {- const type = typeOf(fileName);+ const type = libraryTypeOf(fileName);if (!type) throw new Error("Unsupported file type.");const duration = type === "image" ? 0 : await probeDuration(localFile);const dims = type === "audio" ? null : await videoDimensions(localFile);diff --git a/site/src/cut/worker/main.ts b/site/src/cut/worker/main.tsindex d3ec9938..95af5663 100644--- a/site/src/cut/worker/main.ts+++ b/site/src/cut/worker/main.ts@@ -4,13 +4,14 @@ import { claimNextJob, prisma, type ClaimedJob } from "./db";import { overlayKeysOf, runExportJob } from "./exportJob";import { runHlsJob } from "./hlsJob";import { runConvertJob } from "./convertJob";+import { runProxyJob } from "./proxyJob";import { runImportUrlJob } from "./importUrlJob";import { runTurnJob } from "./turnJob";import { describeRuntime, installHeadlessRuntime } from "../lib/headless/runtime";import { deleteObjects } from "./r2";// The cloud render worker: a headless loop that claims CutRenderJob rows the-// hosted API queues (export, preview, import_url, convert, agent_turn),+// hosted API queues (export, preview, import_url, convert, proxy, agent_turn),// executes them with the same pipeline code the local engine runs, and writes// progress and results// back to the row the client polls. Scale is horizontal: one job per process,@@ -51,6 +52,7 @@ const MAX_RUNTIME_MS: Record<string, number> = {hls: 3 * 60 * 60_000,import_url: 20 * 60_000,convert: 60 * 60_000,+ proxy: 60 * 60_000,agent_turn: 20 * 60_000,};const DEFAULT_MAX_RUNTIME_MS = 60 * 60_000;@@ -173,6 +175,12 @@ async function runJob(job: ClaimedJob): Promise<void> {where: { id: job.id, state: "running" },data: { state: "done", progress: 1, result: result as unknown as Prisma.InputJsonValue },});+ } else if (job.kind === "proxy") {+ const result = await runProxyJob(job, handle, () => entry.canceled);+ await prisma.cutRenderJob.updateMany({+ where: { id: job.id, state: "running" },+ data: { state: "done", progress: 1, result: result as unknown as Prisma.InputJsonValue },+ });} else if (job.kind === "agent_turn") {const result = await runTurnJob(job, handle, () => entry.canceled);await prisma.cutRenderJob.updateMany({diff --git a/site/src/cut/worker/proxyJob.test.ts b/site/src/cut/worker/proxyJob.test.tsnew file mode 100644index 00000000..cd3fb8d2--- /dev/null+++ b/site/src/cut/worker/proxyJob.test.ts@@ -0,0 +1,67 @@+import { describe, expect, mock, test } from "bun:test";+import { writeFile } from "node:fs/promises";+import type { prisma } from "@/lib/prisma";+import { runProxyJob, type ProxyJobIO } from "./proxyJob";++function harness(taken: string[] = []) {+ const findMany = mock(async (_args: unknown) => { void _args; return taken.map((fileName) => ({ fileName })); });+ const io = {+ db: { cutMediaObject: { findMany } } as unknown as typeof prisma,+ download: mock(async (_key: string, file: string) => { await writeFile(file, "master"); }),+ upload: mock(async (_key: string, _file: string, _mime: string) => { void _file; void _mime; return 7; }),+ remove: mock(async (_keys: string[]) => { void _keys; }),+ register: mock(async (object: { fileName: string }) => object.fileName),+ unregister: mock(async (_user: string, _keys: string[]) => { void _keys; }),+ make: mock(async (_handle: unknown, _src: string, out: string, opts: { maxHeight: number; crf: number; onProgress?: (s: number) => void }) => {+ opts.onProgress?.(1);+ await writeFile(out, "proxy");+ return { sizeBytes: 5, width: 64, height: 64 };+ }),+ duration: mock(async () => 2),+ settings: mock(async () => ({ proxyMaxHeight: 1080, proxyCrf: 20 })),+ } satisfies ProxyJobIO;+ const job = { id: "proxy-1", userId: "owner", projectId: "project", kind: "proxy", outName: null, spec: { file: "clip.mov" } };+ const handle = { tmpDir: "", outPath: "", progress: 0, log: [] as string[] };+ const run = (canceled = () => false) => runProxyJob(job, handle, canceled, io);+ return { run, io, handle, findMany };+}++describe("proxy worker", () => {+ test("builds the proxy at the account's size and quality and registers it exempt beside the master", async () => {+ const h = harness();+ expect(await h.run()).toEqual({ fileName: "clip.proxy.mp4", sizeBytes: 5, width: 64, height: 64 });+ expect(h.io.download.mock.calls[0][0]).toBe("cut/owner/projects/project/media/clip.mov");+ expect(h.io.make.mock.calls[0][3]).toMatchObject({ maxHeight: 1080, crf: 20 });+ expect(h.io.upload.mock.calls[0][0]).toBe("cut/owner/projects/project/media/clip.proxy.mp4");+ expect(h.io.register.mock.calls[0][0]).toMatchObject({+ userId: "owner",+ projectId: "project",+ fileName: "clip.proxy.mp4",+ kind: "proxy",+ mime: "video/mp4",+ bytes: 7,+ });+ expect(h.handle.progress).toBeGreaterThan(0);+ });++ test("dedupes the proxy's name against the project's media and proxies", async () => {+ const h = harness(["clip.proxy.mp4"]);+ expect((await h.run()).fileName).toBe("clip.proxy-1.mp4");+ expect(h.findMany.mock.calls[0][0]).toMatchObject({ where: { projectId: "project", kind: { in: ["media", "proxy"] } } });+ });++ test("a failed upload leaves no object behind", async () => {+ const h = harness();+ h.io.upload.mockImplementation(async () => { throw new Error("R2 down"); });+ await expect(h.run()).rejects.toThrow("R2 down");+ expect(h.io.unregister).toHaveBeenCalled();+ expect(h.io.remove.mock.calls[0][0]).toEqual(["cut/owner/projects/project/media/clip.proxy.mp4"]);+ expect(h.io.register).not.toHaveBeenCalled();+ });++ test("a cancel stops before the encode", async () => {+ const h = harness();+ await expect(h.run(() => true)).rejects.toThrow("canceled");+ expect(h.io.make).not.toHaveBeenCalled();+ });+});diff --git a/site/src/cut/worker/proxyJob.ts b/site/src/cut/worker/proxyJob.tsnew file mode 100644index 00000000..63c14ff4--- /dev/null+++ b/site/src/cut/worker/proxyJob.ts@@ -0,0 +1,110 @@+import { mkdtemp, rm } from "node:fs/promises";+import os from "node:os";+import path from "node:path";+import { getGlobalSetting } from "@/lib/config/effective";+import type { RenderHandle } from "../server/exportPipeline";+import { makeProxy, proxyNameFor } from "../server/proxy";+import { probeDuration } from "../server/frames";+import { dedupeName } from "../server/cloud/util";+import { prisma, registerObject, unregisterObjects, type ClaimedJob } from "./db";+import { deleteObjects, downloadToFile, mediaKey, uploadFile } from "./r2";++/** What a proxy job records in CutRenderJob.result — the same shape the+ * engine's synchronous proxy route returns. */+export interface ProxyResult {+ fileName: string;+ sizeBytes: number;+ width?: number;+ height?: number;+}++/** The edges a proxy job crosses, stubbed by its test. */+export interface ProxyJobIO {+ db: typeof prisma;+ download: typeof downloadToFile;+ upload: typeof uploadFile;+ remove: typeof deleteObjects;+ register: typeof registerObject;+ unregister: typeof unregisterObjects;+ make: typeof makeProxy;+ duration: typeof probeDuration;+ settings: () => Promise<{ proxyMaxHeight: number; proxyCrf: number }>;+}++const defaultIO: ProxyJobIO = {+ db: prisma,+ download: downloadToFile,+ upload: uploadFile,+ remove: deleteObjects,+ register: registerObject,+ unregister: unregisterObjects,+ make: makeProxy,+ duration: probeDuration,+ settings: () => getGlobalSetting("cutColor"),+};++/**+ * Run one proxy job: pull the ProRes master out of R2, build its preview+ * proxy with the same code the engine runs on a Mac, and land it in the+ * project's media prefix as a quota-exempt object (kind "proxy") under a+ * name deduped against the project's files. The master is left alone; the+ * client writes the proxy onto the asset.+ */+export async function runProxyJob(+ job: ClaimedJob,+ handle: RenderHandle,+ isCanceled: () => boolean,+ io: ProxyJobIO = defaultIO+): Promise<ProxyResult> {+ const { file } = (job.spec ?? {}) as { file?: string };+ if (!file) throw new Error("Proxy job has no file.");+ const projectId = job.projectId;+ if (!projectId) throw new Error("Proxy job has no project.");++ const tmp = await mkdtemp(path.join(os.tmpdir(), "cut-proxy-"));+ handle.tmpDir = tmp;+ try {+ const src = path.join(tmp, path.basename(file));+ await io.download(mediaKey(job.userId, projectId, file), src);+ if (isCanceled()) throw new Error("Proxy canceled.");++ const rows = await io.db.cutMediaObject.findMany({+ where: { projectId, kind: { in: ["media", "proxy"] } },+ select: { fileName: true },+ });+ const fileName = dedupeName(proxyNameFor(file), new Set(rows.map((r) => r.fileName)));+ const out = path.join(tmp, fileName);+ handle.outPath = out;++ const [total, settings] = await Promise.all([io.duration(src), io.settings()]);+ const outcome = await io.make(handle, src, out, {+ maxHeight: settings.proxyMaxHeight,+ crf: settings.proxyCrf,+ onProgress: (seconds) => {+ if (total > 0) handle.progress = Math.min(0.99, seconds / total);+ },+ });+ if (isCanceled()) throw new Error("Proxy canceled.");++ const key = mediaKey(job.userId, projectId, fileName);+ try {+ const bytes = await io.upload(key, out, "video/mp4");+ await io.register({+ userId: job.userId,+ projectId,+ r2Key: key,+ fileName,+ mime: "video/mp4",+ bytes,+ kind: "proxy",+ });+ } catch (err) {+ await io.unregister(job.userId, [key]).catch(() => {});+ await io.remove([key]);+ throw err;+ }+ return { fileName, ...outcome };+ } finally {+ void rm(tmp, { recursive: true, force: true });+ }+}diff --git a/site/src/cut/worker/turnJob.ts b/site/src/cut/worker/turnJob.tsindex 27227414..790cc495 100644--- a/site/src/cut/worker/turnJob.ts+++ b/site/src/cut/worker/turnJob.ts@@ -1,6 +1,7 @@import type { UIMessage } from "ai";import { getGlobalSetting } from "@/lib/config/effective";import { bindCutClip, bindCutJudge } from "@/cut/lib/chatRuntime";+import { bindCutColor } from "@/cut/lib/colorSettings";import { geminiModelRoleNames } from "@/lib/inference/gemini-models";import { openCloudProject, pushCloudProject } from "../lib/headless/docSession";import { dropPiSession, streamCutChat } from "../lib/pi/cutAgent";@@ -109,6 +110,7 @@ export async function runTurnJob(const judgeSettings = await getGlobalSetting("cutJudge");bindCutJudge(judgeSettings);bindCutClip(await getGlobalSetting("cutClip"));+ bindCutColor(await getGlobalSetting("cutColor"));deps.judgeSettings = judgeSettings;const toolCalls: string[] = [];const exec = deps.execTool;diff --git a/site/src/lib/config/registry.ts b/site/src/lib/config/registry.tsindex 1bc51233..248ed100 100644--- a/site/src/lib/config/registry.ts+++ b/site/src/lib/config/registry.ts@@ -292,6 +292,37 @@ export const SETTINGS = defineSettings({description:"How a talk or an interview is read for the moments worth cutting a short from: what a clip may run, how widely the first sweep looks, how many moments earn the close read, and what the ranking weighs.",},+ cutColor: {+ schema: z+ .object({+ // Lattice nodes per axis of a clip's color LUT: Rec.709 and sRGB+ // sources take the smaller cube, log and HDR sources the wider one.+ lutSize: z.number().int().min(9).max(129),+ lutSizeWide: z.number().int().min(9).max(129),+ // The cube drawn while a slider is moving; the full cube follows.+ draftLutSize: z.number().int().min(5).max(65),+ // The preview proxy's largest height, and its HEVC quality (x265 crf;+ // the VideoToolbox quality maps from it). 18 is visually lossless for+ // 10-bit footage that is only ever previewed.+ proxyMaxHeight: z.number().int().min(360).max(4320),+ proxyCrf: z.number().int().min(0).max(51),+ // A LUT file past this is something else.+ lutFileMaxBytes: z.number().int().min(1024).max(1024 ** 3),+ })+ .strict(),+ default: {+ lutSize: 33,+ lutSizeWide: 65,+ draftLutSize: 17,+ proxyMaxHeight: 2160,+ proxyCrf: 18,+ lutFileMaxBytes: 64 * 1024 ** 2,+ },+ public: true,+ title: "Color pipeline",+ description:+ "The color LUT sizes a clip is rendered through (standard, wide-gamut and the draft drawn mid-drag), the preview proxy's size and quality, and the largest LUT file the library takes.",+ },experimentResults: {schema: z.object({