davinci-resolve-mcp 4.18.5 → 4.19.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +40 -0
- package/README.md +1 -1
- package/README.zh-CN.md +2 -2
- package/install.py +1 -1
- package/package.json +1 -1
- package/resolve-advanced/server/db-patch.mjs +5 -3
- package/resolve-advanced/server/retime-db.mjs +125 -0
- package/resolve-advanced/server/tools/drx.mjs +20 -1
- package/resolve-advanced/server/tools/project_db.mjs +5 -1
- package/resolve-advanced/vendor/drp-format/media-timemap.js +222 -14
- package/resolve-advanced/vendor/drx-codec/cdl-exporter.js +4 -2
- package/resolve-advanced/vendor/drx-codec/drx-generator.js +27 -4
- package/resolve-advanced/vendor/drx-codec/grade-body-wire.js +80 -0
- package/resolve-advanced/vendor/drx-codec/grade-keyframes.js +90 -0
- package/resolve-advanced/vendor/drx-codec/magic-mask-author.js +101 -0
- package/resolve-advanced/vendor/drx-parameters/CALIBRATION-STATUS.md +68 -6
- package/resolve-advanced/vendor/drx-parameters/parameter-ranges.js +4 -1
- package/src/granular/common.py +1 -1
- package/src/server.py +1 -1
package/CHANGELOG.md
CHANGED
|
@@ -2,6 +2,46 @@
|
|
|
2
2
|
|
|
3
3
|
Release history for the DaVinci Resolve MCP Server. The latest release is summarized in the root README; older entries live here to keep the README focused.
|
|
4
4
|
|
|
5
|
+
## What's New in v4.19.0 — Studio 21 speed ramps, keyframed grades and Magic Mask clicks (offline writers)
|
|
6
|
+
|
|
7
|
+
@Reaperiguess measured three things the scripting API cannot do on Studio 21 and wrote offline writers for them, each checked by renders on Studio 21.0.4.5 (Windows) (#312).
|
|
8
|
+
|
|
9
|
+
### Added
|
|
10
|
+
|
|
11
|
+
- **`project_db` `list_video_items` / `set_speed_ramp`** write variable-speed ramps, eased speed points included (`easeFrames`), into a closed project's `Project.db`. The ramp changes exactly two `Sm2TiItem` columns, `MediaTimemapBA` and `Duration`, and `buildRampTimemapR21` reproduces a hand-made ramp byte for byte. It uses the subtitle-write safety path: Resolve fully quit, SQLite snapshot backup, schema guard, transaction, readback.
|
|
12
|
+
- **Keyframed grade parameters** (`keyframeCorrector`): one block per keyframe in a corrector's `F6`. Apply with gradeMode 2; gradeMode 0 drops the keyframes.
|
|
13
|
+
- **Magic Mask 2 click authoring** (`placeMagicMaskClick`): moves the stored subject click to another clip's frame and point, and can copy a Primary into the mask node. After `ApplyGradeFromDRX`, `CreateMagicMask("BI")` tracks it.
|
|
14
|
+
- **`drx generate` accepts `lumMixSlider`**, and an explicit 0 is now written (the old guard dropped it). `lumMixSlider: 0` makes lift/gamma/gain R/G/B moves per-channel, as Resolve's own `SetCDL` writes them.
|
|
15
|
+
|
|
16
|
+
### Changed on landing (differences from the PR)
|
|
17
|
+
|
|
18
|
+
- **Lum Mix 0 is opt-in, not the default.** The PR made every lift/gamma/gain R/G/B move write Lum Mix 0, and moved `shadowLift`, `highlightCompression` and the contrast node onto the masters. That changes the render of every existing `drx.generate` caller and has been measured only on Studio 21.0.4.5, so it is held back until the same grey-128 measurement exists on 19.1.3.7. Existing output is unchanged unless `lumMixSlider` is passed.
|
|
19
|
+
- **Keyframe and Magic Mask code runs on Node 20.** It no longer needs Node 22.15's zstd: bodies decode with `fzstd`, and without native zstd they are encoded as a spec-valid stored zstd frame. Whether Resolve accepts a stored frame in a grade `<Body>` has not been measured; Node 22.15+ keeps the compressed form. Eased speed ramps still need Node 22.15+ and say so.
|
|
20
|
+
- **`set_speed_ramp` refuses a trimmed clip.** A non-zero (or unreadable) source in-point `Sm2TiItem."In"` is refused, because the ramp is built from the media head and a windowed start has not been measured.
|
|
21
|
+
- **`set_speed_ramp` refuses a ramp that overlaps the next clip.** The `dryRun` plan reports `next.start`, `next.overlapFrames` and `wouldRefuse`.
|
|
22
|
+
|
|
23
|
+
### Fixed
|
|
24
|
+
|
|
25
|
+
- The `db-patch` Windows resolve-running check filters `tasklist` by image name; an unfiltered call took over 5 s on a busy machine.
|
|
26
|
+
|
|
27
|
+
### Validation
|
|
28
|
+
|
|
29
|
+
- Advanced Node suite on Node 20: the four keyframe/Magic Mask tests that failed on Node 20 in the PR now pass, and new tests cover the two `set_speed_ramp` refusals.
|
|
30
|
+
- Nothing here was exercised against a live Resolve: the open Resolve is Studio 19.1.3.7. The ramp, keyframe and Magic Mask results are the contributor's Studio 21.0.4.5 measurements.
|
|
31
|
+
|
|
32
|
+
## What's New in v4.18.6 — `cdl_io` keeps corrections with an empty or missing id
|
|
33
|
+
|
|
34
|
+
`drx` action `cdl_io` dropped ASC CDL corrections whose `id` was empty or missing, with no warning. `parseCDL` only matched an opening tag written exactly as `<ColorCorrection id="...">` with a non-empty id and no other attribute. OpenColorIO's reference `cdl_test1.ccc` has five corrections, two of them there to check that an empty or missing id does not stop a look from loading. `cdl_io` imported three of the five, and a `.cc` holding only such a correction was refused as "not a CDL/CCC/CC document".
|
|
35
|
+
|
|
36
|
+
### Fixed
|
|
37
|
+
|
|
38
|
+
- **`cdl_io` imports every correction in the file** (#342, thanks @Dev-next-gen). The opening tag may carry any attributes, and `id` is read from them. A correction with no id, or an empty one, is named `cc<index>`, the fallback `importCDL` already had but never reached. Self-closing `<ColorCorrection/>` elements are still skipped, and `<ColorCorrectionCollection>` is not mistaken for a correction.
|
|
39
|
+
|
|
40
|
+
### Validation
|
|
41
|
+
|
|
42
|
+
- The new test in `test/cdl-io.test.mjs` fails on 4.18.5 and passes with the fix. The 97 CDL-related Node tests pass on Node 20 with the PR merged into main.
|
|
43
|
+
- Parser-only change, no Resolve call is involved, so no live Resolve run applies. The open Resolve is Studio 19.1.3.7.
|
|
44
|
+
|
|
5
45
|
## What's New in v4.18.5 — The #336 ledger matches the re-measurement
|
|
6
46
|
|
|
7
47
|
@CaptRauti re-measured the six calls from v4.18.4. Three of them were the same broken timeline: `AppendToTimeline` took an absolute `recordFrame` below `StartFrame`, the clips landed outside the timeline, and `StartFrame` stayed equal to `EndFrame`.
|
package/README.md
CHANGED
|
@@ -2,7 +2,7 @@
|
|
|
2
2
|
|
|
3
3
|
English | [简体中文](README.zh-CN.md)
|
|
4
4
|
|
|
5
|
-
[](https://github.com/samuelgursky/davinci-resolve-mcp/releases)
|
|
6
6
|
[](https://www.npmjs.com/package/davinci-resolve-mcp)
|
|
7
7
|
[](docs/reference/api-coverage.md)
|
|
8
8
|
[-blue.svg)](#server-modes)
|
package/README.zh-CN.md
CHANGED
|
@@ -2,7 +2,7 @@
|
|
|
2
2
|
|
|
3
3
|
[English](README.md) | 简体中文
|
|
4
4
|
|
|
5
|
-
[](https://github.com/samuelgursky/davinci-resolve-mcp/releases)
|
|
6
6
|
[](https://www.npmjs.com/package/davinci-resolve-mcp)
|
|
7
7
|
[](docs/reference/api-coverage.md)
|
|
8
8
|
[-blue.svg)](#服务器模式)
|
|
@@ -12,7 +12,7 @@
|
|
|
12
12
|
[](https://www.python.org/downloads/)
|
|
13
13
|
[](https://opensource.org/licenses/MIT)
|
|
14
14
|
|
|
15
|
-
> 本翻译对应 v4.
|
|
15
|
+
> 本翻译对应 v4.19.0 版 README。如与英文原版有出入,以 [英文原版](README.md) 为准。
|
|
16
16
|
|
|
17
17
|
一个 Model Context Protocol (MCP) 服务器,让 AI 助手通过官方脚本 API 控制 DaVinci Resolve Studio(达芬奇)。它提供完整的 API 覆盖,外加带护栏的工作流助手,涵盖剪辑、媒体池整理、渲染设置、审阅标记、调色、Fusion、Fairlight、项目生命周期任务、扩展开发,以及不碰源媒体的媒体分析。
|
|
18
18
|
|
package/install.py
CHANGED
|
@@ -37,7 +37,7 @@ from src.utils.update_check import (
|
|
|
37
37
|
|
|
38
38
|
# ─── Version ──────────────────────────────────────────────────────────────────
|
|
39
39
|
|
|
40
|
-
VERSION = "4.
|
|
40
|
+
VERSION = "4.19.0"
|
|
41
41
|
# Only hard floor: mcp[cli] requires Python 3.10+. There is no upper bound —
|
|
42
42
|
# Resolve's scripting bridge loads into newer interpreters on recent builds
|
|
43
43
|
# (Python 3.14 verified against Resolve Studio 20.3.2). Older Resolve builds
|
package/package.json
CHANGED
|
@@ -151,14 +151,16 @@ export class BuiltinSqlite {
|
|
|
151
151
|
/** Verify the process is gone; a caller assertion alone is not sufficient. */
|
|
152
152
|
export function requireResolveQuit(opts) {
|
|
153
153
|
requireClosed(opts);
|
|
154
|
-
if (resolveRunning()) throw new Error('Fully QUIT Resolve before subtitle database writes (Resolve is running).');
|
|
154
|
+
if (resolveRunning()) throw new Error('Fully QUIT Resolve before subtitle/retime database writes (Resolve is running).');
|
|
155
155
|
}
|
|
156
156
|
|
|
157
157
|
function resolveRunning() {
|
|
158
158
|
const win = process.platform === 'win32';
|
|
159
|
+
// Filter on Windows: an unfiltered tasklist took >5 s on a busy laptop (measured
|
|
160
|
+
// 2026-10-19, ~230 processes) and timed out, refusing every write; filtered: ~1 s.
|
|
159
161
|
const result = childProcess.spawnSync(win ? 'tasklist.exe' : 'ps',
|
|
160
|
-
win ? ['/FO', 'CSV', '/NH'] : ['-A', '-o', 'comm='],
|
|
161
|
-
{ encoding: 'utf8', timeout:
|
|
162
|
+
win ? ['/FI', 'IMAGENAME eq Resolve.exe', '/FO', 'CSV', '/NH'] : ['-A', '-o', 'comm='],
|
|
163
|
+
{ encoding: 'utf8', timeout: 20000, windowsHide: true });
|
|
162
164
|
if (result.error || result.status !== 0) throw new Error('Cannot verify Resolve is quit; refusing database write.');
|
|
163
165
|
return result.stdout.split(/\r?\n/).some((line) => win
|
|
164
166
|
? /^"Resolve\.exe",/i.test(line.trim())
|
|
@@ -0,0 +1,125 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Variable-speed ramps written straight into a CLOSED project's Project.db (Studio 21 schema).
|
|
3
|
+
*
|
|
4
|
+
* A ramp made on Resolve's retime bar changes exactly two Sm2TiItem columns: MediaTimemapBA
|
|
5
|
+
* (an Sm2TimeMap with protobuf keyframes) and Duration. This writes the same two, render-verified
|
|
6
|
+
* on Studio 21.0.4.5 (see buildRampTimemapR21), eased speed points included (segment
|
|
7
|
+
* easeFrames). Same safety tier as subtitle-db: Resolve fully
|
|
8
|
+
* quit (process list), unique SQLite snapshot backup, schema guards, transaction, readback.
|
|
9
|
+
*/
|
|
10
|
+
import { randomUUID } from 'node:crypto';
|
|
11
|
+
import { createRequire } from 'node:module';
|
|
12
|
+
import { z } from 'zod';
|
|
13
|
+
import { openGuarded, requireResolveQuit, snapshotBackup } from './db-patch.mjs';
|
|
14
|
+
const require = createRequire(import.meta.url);
|
|
15
|
+
const { decodeTimemap, buildRampTimemapR21 } = require('../vendor/drp-format/media-timemap.js');
|
|
16
|
+
|
|
17
|
+
// "In" is the clip's source in-point: plain decimal, or the first field of a pipe-joined composite
|
|
18
|
+
// ('47|0000eaffffffef3f'). Empty reads as 0; anything else unparseable is null.
|
|
19
|
+
function decodeIn(v) {
|
|
20
|
+
if (v === null || v === undefined || v === '') return 0;
|
|
21
|
+
const head = String(v).split('|', 1)[0];
|
|
22
|
+
return /^-?\d+(\.\d+)?$/.test(head) ? Number(head) : null;
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
const target = { projectDb: z.string().optional(), projectName: z.string().optional() };
|
|
26
|
+
const segment = z.object({
|
|
27
|
+
durationFrames: z.number().int().positive(), speed: z.number().positive(),
|
|
28
|
+
easeFrames: z.union([z.number().positive(), z.literal('auto')]).optional()
|
|
29
|
+
.describe('ease the speed point where this segment starts ("Ease In and Out"): half-width in record frames, or auto = a third of the shorter neighbour'),
|
|
30
|
+
}).strict();
|
|
31
|
+
export const retimeSchemas = {
|
|
32
|
+
list_video_items: z.object({ ...target, timeline: z.string().optional() }).strict(),
|
|
33
|
+
set_speed_ramp: z.object({
|
|
34
|
+
...target,
|
|
35
|
+
itemId: z.string().optional().describe('Sm2TiItem_id from list_video_items'),
|
|
36
|
+
timeline: z.string().optional(), track: z.number().int().min(1).default(1), index: z.number().int().min(0).default(0),
|
|
37
|
+
segments: z.array(segment).min(1).describe('record-domain pieces from the clip head, e.g. [{durationFrames:30,speed:1},{durationFrames:90,speed:0.25}]'),
|
|
38
|
+
allowRetimed: z.boolean().default(false).describe('replace an existing retime (default: only an unretimed 1x clip)'),
|
|
39
|
+
dryRun: z.boolean().default(false), iConfirmProjectClosed: z.boolean().optional(),
|
|
40
|
+
}).strict(),
|
|
41
|
+
};
|
|
42
|
+
|
|
43
|
+
const COLS = ['Sm2TiItem_id', 'Name', 'Start', 'Duration', 'MediaTimemapBA', 'Sm2TiTrack_id'];
|
|
44
|
+
function videoItems(db, timeline) {
|
|
45
|
+
const rows = db.prepare(`SELECT it.Sm2TiItem_id id, it.Name name, it.Start start, it.Duration duration,
|
|
46
|
+
it.MediaTimemapBA timemap, it."In" inRaw, tr.Sm2TiTrack_id trackId, tl.Name timeline, sq.FrameRate fpsBlob
|
|
47
|
+
FROM Sm2TiItem it JOIN Sm2TiTrack tr ON it.Sm2TiTrack_id = tr.Sm2TiTrack_id
|
|
48
|
+
JOIN Sm2Sequence sq ON tr.Sequence = sq.Sm2Sequence_id
|
|
49
|
+
JOIN Sm2Timeline tl ON tl.Sm2Timeline_id = sq.Sm2Timeline_id
|
|
50
|
+
WHERE tr.Type = 0 ORDER BY tl.rowid, tr.rowid, CAST(it.Start AS INTEGER)`).all();
|
|
51
|
+
const trackNo = new Map(); const perTrack = new Map();
|
|
52
|
+
// Rows are ordered by Start within a track, so the next row on the same track is the next clip.
|
|
53
|
+
const nextStart = new Map(); const lastOnTrack = new Map();
|
|
54
|
+
for (const r of rows) {
|
|
55
|
+
if (lastOnTrack.has(r.trackId)) nextStart.set(lastOnTrack.get(r.trackId), Number(r.start));
|
|
56
|
+
lastOnTrack.set(r.trackId, r.id);
|
|
57
|
+
}
|
|
58
|
+
return rows.filter((r) => timeline == null || r.timeline === timeline).map((r) => {
|
|
59
|
+
const key = r.timeline;
|
|
60
|
+
if (!trackNo.has(key)) trackNo.set(key, []);
|
|
61
|
+
const list = trackNo.get(key); if (!list.includes(r.trackId)) list.push(r.trackId);
|
|
62
|
+
const idx = perTrack.get(r.trackId) || 0; perTrack.set(r.trackId, idx + 1);
|
|
63
|
+
const fps = r.fpsBlob && r.fpsBlob.length >= 8 ? Buffer.from(r.fpsBlob).readDoubleLE(0) : null;
|
|
64
|
+
let retime = null;
|
|
65
|
+
try { retime = r.timemap ? decodeTimemap(Buffer.from(r.timemap)) : null; } catch (e) { retime = { error: e.message }; }
|
|
66
|
+
return { id: r.id, name: r.name, timeline: r.timeline, track: list.indexOf(r.trackId) + 1, index: idx,
|
|
67
|
+
start: Number(r.start), duration: Number(r.duration), fps, retime,
|
|
68
|
+
sourceIn: decodeIn(r.inRaw), nextStart: nextStart.has(r.id) ? nextStart.get(r.id) : null };
|
|
69
|
+
});
|
|
70
|
+
}
|
|
71
|
+
const summary = (t) => (!t ? null : t.error ? { error: t.error } : t.form === 'identity'
|
|
72
|
+
? { form: 'identity', sourceFrames: null, seconds: t.seconds }
|
|
73
|
+
: { form: 'retimed', variable: t.variable, segments: t.segments, eases: t.eases?.map(({ recordSec, easeSec }) => ({ recordSec, easeSec })),
|
|
74
|
+
sourceDurationSec: t.sourceDurationSec, recordDurationSec: t.recordDurationSec });
|
|
75
|
+
|
|
76
|
+
export async function retimeDbAction(action, args, resolveDbPath) {
|
|
77
|
+
const p = retimeSchemas[action].parse(args);
|
|
78
|
+
const dbPath = await resolveDbPath(p);
|
|
79
|
+
if (action === 'list_video_items') {
|
|
80
|
+
const db = openGuarded(dbPath, { table: 'Sm2TiItem', column: 'MediaTimemapBA' });
|
|
81
|
+
try { return { items: videoItems(db, p.timeline).map((i) => ({ ...i, retime: summary(i.retime) })) }; } finally { db.close(); }
|
|
82
|
+
}
|
|
83
|
+
// set_speed_ramp
|
|
84
|
+
if (!p.dryRun) requireResolveQuit(p);
|
|
85
|
+
const db = openGuarded(dbPath, { writable: !p.dryRun, table: 'Sm2TiItem', column: 'MediaTimemapBA' });
|
|
86
|
+
try {
|
|
87
|
+
const names = db.prepare('PRAGMA table_info("Sm2TiItem")').all().map((c) => c.name);
|
|
88
|
+
for (const c of COLS) if (!names.includes(c)) throw new Error(`unsupported schema: missing Sm2TiItem.${c}`);
|
|
89
|
+
const all = videoItems(db, p.itemId ? undefined : p.timeline);
|
|
90
|
+
const item = p.itemId ? all.find((i) => i.id === p.itemId) : all.find((i) => i.track === p.track && i.index === p.index);
|
|
91
|
+
if (!item) throw new Error(p.itemId ? `no video item ${p.itemId}` : `no video item ${p.index} on V${p.track} of "${p.timeline}"`);
|
|
92
|
+
if (!item.fps) throw new Error('unsupported timeline FrameRate encoding');
|
|
93
|
+
// The ramp is built from the media head; a windowed start has not been measured.
|
|
94
|
+
if (item.sourceIn === null) throw new Error('cannot read the clip source in-point (Sm2TiItem."In"); refusing to ramp it');
|
|
95
|
+
if (item.sourceIn !== 0) throw new Error(`clip is trimmed (source in-point ${item.sourceIn}); the ramp is built from the media head, so a windowed start is not supported yet`);
|
|
96
|
+
if (item.retime?.error) throw new Error(`existing MediaTimemapBA does not decode: ${item.retime.error}`);
|
|
97
|
+
if (item.retime?.form !== 'identity' && !p.allowRetimed) throw new Error('item is already retimed; pass allowRetimed:true to replace it');
|
|
98
|
+
// Identity map = [02][(sourceFrames-1)/fps ...]: the media extent in seconds.
|
|
99
|
+
const extentSec = item.retime?.form === 'identity' ? item.retime.seconds[0] : item.retime?.sourceDurationSec;
|
|
100
|
+
const sourceFrames = Math.round(extentSec * item.fps) + 1;
|
|
101
|
+
if (!(sourceFrames > 1)) throw new Error('cannot derive the media frame count from the existing map');
|
|
102
|
+
const built = buildRampTimemapR21({ segments: p.segments, sourceFrames, fps: item.fps, uniqueId: randomUUID() });
|
|
103
|
+
const plan = { item: { id: item.id, name: item.name, timeline: item.timeline, track: item.track, index: item.index },
|
|
104
|
+
fps: item.fps, sourceFrames, durationFrames: built.durationFrames, sourceEndFrame: built.sourceEndFrame, eased: built.eased,
|
|
105
|
+
before: { duration: item.duration, retime: summary(item.retime) } };
|
|
106
|
+
// A slower segment lengthens the clip; it must not run into the next clip on the track.
|
|
107
|
+
const end = item.start + built.durationFrames;
|
|
108
|
+
const overlapFrames = item.nextStart !== null && end > item.nextStart ? end - item.nextStart : 0;
|
|
109
|
+
plan.next = { start: item.nextStart, overlapFrames };
|
|
110
|
+
if (p.dryRun) return { dryRun: true, ...plan, ...(overlapFrames ? { wouldRefuse: `ramp would overlap the next clip by ${overlapFrames} frame(s)` } : {}) };
|
|
111
|
+
if (overlapFrames) throw new Error(`ramp would overlap the next clip on the track by ${overlapFrames} frame(s): it ends at ${end}, the next clip starts at ${item.nextStart}`);
|
|
112
|
+
const backupPath = await snapshotBackup(dbPath);
|
|
113
|
+
db.exec('BEGIN IMMEDIATE');
|
|
114
|
+
try {
|
|
115
|
+
db.prepare('UPDATE Sm2TiItem SET MediaTimemapBA=?, Duration=? WHERE Sm2TiItem_id=?')
|
|
116
|
+
.run(built.timemap, String(built.durationFrames), item.id);
|
|
117
|
+
const back = db.prepare('SELECT MediaTimemapBA m, Duration d FROM Sm2TiItem WHERE Sm2TiItem_id=?').get(item.id);
|
|
118
|
+
if (!Buffer.from(back.m).equals(built.timemap) || Number(back.d) !== built.durationFrames) throw new Error('readback mismatch');
|
|
119
|
+
db.exec('COMMIT');
|
|
120
|
+
} catch (e) { db.exec('ROLLBACK'); throw e; }
|
|
121
|
+
const after = decodeTimemap(built.timemap);
|
|
122
|
+
return { ...plan, backupPath, after: summary(after),
|
|
123
|
+
note: 'Readback only. Prove timing with a render (frame-coded clip), not this result.' };
|
|
124
|
+
} finally { db.close(); }
|
|
125
|
+
}
|
|
@@ -247,7 +247,10 @@ const generateSchema = z.object({
|
|
|
247
247
|
"params obey it — no per-control cases): space:'ui' (DEFAULT) = Resolve panel numbers " +
|
|
248
248
|
'(lift/gamma ~+/-0.05, gain ~0.90-1.10, offset panel-delta, saturation 0-100/50=neutral); scaled ' +
|
|
249
249
|
"internally (lift x2, gamma x4, gain x1, offset x0.04, sat /50). space:'drx' = raw DRX-internal " +
|
|
250
|
-
'units (wheels raw, saturation ~1.0 neutral) for lossless/programmatic callers.'
|
|
250
|
+
'units (wheels raw, saturation ~1.0 neutral) for lossless/programmatic callers. lumMixSlider ' +
|
|
251
|
+
'(panel 0-100): unset = 0 whenever a wheel R/G/B channel moves, so R/G/B act per channel; at ' +
|
|
252
|
+
"Resolve's default 100 they preserve luminance and equal R/G/B renders unchanged. Use the " +
|
|
253
|
+
'wheel master to brighten or darken.'
|
|
251
254
|
),
|
|
252
255
|
metadata: z.object({}).passthrough().optional().describe('Optional { label, width, height } metadata'),
|
|
253
256
|
target: z
|
|
@@ -500,6 +503,22 @@ function normalizeGradeParams(gp = {}, warnings = null) {
|
|
|
500
503
|
out[w] = scaled;
|
|
501
504
|
}
|
|
502
505
|
}
|
|
506
|
+
// Lum Mix: panel 0–100, stored /100. Left unset, the encoder writes 0 whenever a lift/gamma/
|
|
507
|
+
// gain R/G/B channel moves, so the channels act as per-channel multipliers. Render-measured on
|
|
508
|
+
// Studio 21.0.4.5 (2026-10-19): Lum Mix cancels that share of an equal R/G/B move on luma,
|
|
509
|
+
// linearly (gain R=G=B 1.6 on grey 127.6: Lum Mix 0 → 204.1, 50 → 165.9, 100 → 127.6), so
|
|
510
|
+
// say so when a caller asks for that combination.
|
|
511
|
+
if (space === 'ui' && typeof out.lumMixSlider === 'number') out.lumMixSlider /= 100;
|
|
512
|
+
if (typeof out.lumMixSlider === 'number' && out.lumMixSlider > 0 && Array.isArray(warnings)) {
|
|
513
|
+
for (const [w, neutral] of [['lift', 0], ['gamma', 0], ['gain', 1]]) {
|
|
514
|
+
const v = out[w];
|
|
515
|
+
if (v && typeof v.r === 'number' && v.r === v.g && v.g === v.b && Math.abs(v.r - neutral) > 1e-6) {
|
|
516
|
+
const pct = Math.round(out.lumMixSlider * 100);
|
|
517
|
+
warnings.push(`${w} R=G=B=${v.r} with Lum Mix ${pct}: Resolve cancels ${pct}% of an equal R/G/B move ` +
|
|
518
|
+
`on luma (100 renders unchanged); use ${w}.master, or leave lumMixSlider unset for per-channel ${w}.`);
|
|
519
|
+
}
|
|
520
|
+
}
|
|
521
|
+
}
|
|
503
522
|
// Controls the ENCODER stores as UI/50 (it expects panel-scale 0–100): saturation and the
|
|
504
523
|
// two soft-clip softness params. In UI space, pass 0–100 as-is (the encoder ÷50s downstream).
|
|
505
524
|
// In DRX space the caller supplies the raw internal float, so pre-multiply ×50 to cancel the
|
|
@@ -19,6 +19,7 @@
|
|
|
19
19
|
|
|
20
20
|
import { z } from 'zod';
|
|
21
21
|
import { subtitleDbAction, subtitleSchemas } from '../subtitle-db.mjs';
|
|
22
|
+
import { retimeDbAction, retimeSchemas } from '../retime-db.mjs';
|
|
22
23
|
import { createRequire } from 'node:module';
|
|
23
24
|
import { resolveDbPath as _resolveDbPathRaw, responsiveRoots, openGuarded, backup, requireClosed } from '../db-patch.mjs';
|
|
24
25
|
|
|
@@ -112,9 +113,12 @@ export const projectDbTool = {
|
|
|
112
113
|
'list_captions(projectName|projectDb, timeline, track?) returns text, start/end and words plus originalWords; ' +
|
|
113
114
|
'write_captions(same selectors, add:[{text,start,end,words:[{text,start,end}]}]?, replace:[{id,text,start,end,words}]?, delete:[id]?, templateCaptionId?) edits/adds/deletes in one transaction; all times are absolute timeline frames, end exclusive, caption frames integers, word frames may be fractional; ' +
|
|
114
115
|
'check_captions(same selectors, maxCharacters?:24) flags timing gaps/zero lengths/overflow heuristics. Subtitle track defaults to 1. ' +
|
|
115
|
-
'
|
|
116
|
+
'Speed ramps: list_video_items(projectName|projectDb, timeline?) lists video items with their decoded retime; '+
|
|
117
|
+
'set_speed_ramp(projectName|projectDb, itemId | timeline+track?+index?, segments:[{durationFrames, speed, easeFrames?}], allowRetimed?, dryRun?) writes a variable-speed ramp from the clip head (Studio 21 protobuf Sm2TimeMap + Duration; render-verified on 21.0.4.5); easeFrames (frames, or auto) eases the speed point where that segment starts, like Ease In and Out. ' +
|
|
118
|
+
'New subtitle and speed-ramp writes require Resolve fully QUIT (checked through the process list) and iConfirmProjectClosed:true; dryRun:true previews without writing. Unique SQLite snapshot backup, schema guards, atomic transaction and readback. Readback is not render verification. Uses better-sqlite3 or node:sqlite (Node 22.16+ / 23.8+); automatic Windows/macOS/Linux library discovery.',
|
|
116
119
|
async handler({ action, args }) {
|
|
117
120
|
if (Object.hasOwn(subtitleSchemas, action)) return subtitleDbAction(action, args, resolveDbPath);
|
|
121
|
+
if (Object.hasOwn(retimeSchemas, action)) return retimeDbAction(action, args, resolveDbPath);
|
|
118
122
|
if (action === 'list_folders') {
|
|
119
123
|
const p = listFoldersSchema.parse(args);
|
|
120
124
|
const db = openGuarded(await resolveDbPath(p), { table: 'Sm2MpFolder', column: 'Name' });
|
|
@@ -19,13 +19,44 @@
|
|
|
19
19
|
* Verified live: a 50% clip exported XMax=305.33, LastValidYOffset=152.65 → speed 0.4999.
|
|
20
20
|
* encode(decode(x)) reproduces both forms exactly. See knowledge/blob-map.md.
|
|
21
21
|
*
|
|
22
|
+
* 3. EASED (Studio 21, a speed point set to "Ease In and Out") — the retimed form with Mode=2,
|
|
23
|
+
* no YMin, and KeyframesBA zstd-wrapped with per-point ease handles; see buildEasedTimemap
|
|
24
|
+
* and sourceSecAt.
|
|
25
|
+
*
|
|
22
26
|
* @module drp-format/media-timemap
|
|
23
27
|
*/
|
|
24
28
|
|
|
25
|
-
const
|
|
29
|
+
const nodeZlib = require('zlib');
|
|
30
|
+
const { decodeKeyedDict, encodeKeyedDict, T_INT32, T_DOUBLE, T_STRING, T_BYTES } = require('./keyed-dict');
|
|
26
31
|
const { decodeProtobuf, encodeProtobuf } = require('./protobuf-wire');
|
|
32
|
+
let fzstd = null;
|
|
33
|
+
try { fzstd = require('fzstd'); } catch (e) { /* optional; native zlib zstd covers Node 22.15+ */ }
|
|
27
34
|
|
|
28
35
|
const TYPE_LINEAR = 0x02;
|
|
36
|
+
const ZSTD_MAGIC = Buffer.from('28b52ffd', 'hex');
|
|
37
|
+
|
|
38
|
+
/**
|
|
39
|
+
* An EASED ramp (Studio 21.0.4.5, Inspector > Speed Change > Ease "Ease In and Out" with the
|
|
40
|
+
* playhead on a speed point) stores KeyframesBA as [0x81][zstd frame of the protobuf] — the
|
|
41
|
+
* same wrapper as a .drx Body — and Resolve's own frames are byte-identical to zstd level 1.
|
|
42
|
+
* "Ease In" and "Ease Out" are inert on retime points there: accepted by the dropdown, nothing
|
|
43
|
+
* stored, the render unchanged.
|
|
44
|
+
*/
|
|
45
|
+
function _unwrapKeyframes(buf) {
|
|
46
|
+
if (buf.length > 5 && buf[0] === 0x81 && buf.subarray(1, 5).equals(ZSTD_MAGIC)) {
|
|
47
|
+
const z = buf.subarray(1);
|
|
48
|
+
if (typeof nodeZlib.zstdDecompressSync === 'function') return { buf: nodeZlib.zstdDecompressSync(z), zstd: true };
|
|
49
|
+
if (fzstd) return { buf: Buffer.from(fzstd.decompress(new Uint8Array(z))), zstd: true };
|
|
50
|
+
throw new Error("MediaTimemapBA: eased KeyframesBA is zstd; needs Node 22.15+ or the optional dep 'fzstd'");
|
|
51
|
+
}
|
|
52
|
+
return { buf, zstd: false };
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
function _wrapKeyframes(buf) {
|
|
56
|
+
if (typeof nodeZlib.zstdCompressSync !== 'function') throw new Error('eased ramps need zstd compression: Node 22.15+ (node:zlib zstdCompressSync)');
|
|
57
|
+
const z = nodeZlib.zstdCompressSync(buf, { params: { [nodeZlib.constants.ZSTD_c_compressionLevel]: 1 } });
|
|
58
|
+
return Buffer.concat([Buffer.from([0x81]), z]);
|
|
59
|
+
}
|
|
29
60
|
|
|
30
61
|
function _isKeyedForm(b) {
|
|
31
62
|
return b.length >= 8 && b.readUInt32BE(0) === 1;
|
|
@@ -57,14 +88,70 @@ function _isKeyedForm(b) {
|
|
|
57
88
|
function _decodeKeyframePoint(buf) {
|
|
58
89
|
let recordSec = 0;
|
|
59
90
|
let sourceSec = 0;
|
|
91
|
+
let handles = null;
|
|
60
92
|
let i = 0;
|
|
61
93
|
while (i < buf.length) {
|
|
62
94
|
const tag = buf[i];
|
|
63
95
|
if (tag === 0x09 && i + 9 <= buf.length) { recordSec = buf.readDoubleLE(i + 1); i += 9; }
|
|
64
96
|
else if (tag === 0x11 && i + 9 <= buf.length) { sourceSec = buf.readDoubleLE(i + 1); i += 9; }
|
|
97
|
+
// Eased point: field 3 = six LE doubles [inRecord, inSource, outRecord, outSource, 0, 0],
|
|
98
|
+
// the ease handles relative to the point (in seconds; see sourceSecAt for how they render).
|
|
99
|
+
else if (tag === 0x1a && i + 2 + buf[i + 1] <= buf.length && buf[i + 1] % 8 === 0) {
|
|
100
|
+
const n = buf[i + 1] / 8;
|
|
101
|
+
handles = Array.from({ length: n }, (_, k) => buf.readDoubleLE(i + 2 + k * 8));
|
|
102
|
+
i += 2 + buf[i + 1];
|
|
103
|
+
}
|
|
65
104
|
else break; // unknown tag or truncated — stop rather than misread
|
|
66
105
|
}
|
|
67
|
-
return { recordSec, sourceSec };
|
|
106
|
+
return handles ? { recordSec, sourceSec, handles } : { recordSec, sourceSec };
|
|
107
|
+
}
|
|
108
|
+
|
|
109
|
+
/**
|
|
110
|
+
* Source seconds shown at `recordSec` for a decoded retimed map, eases included.
|
|
111
|
+
*
|
|
112
|
+
* Render-measured on Studio 21.0.4.5 (frame-coded clip): an eased point P with handles
|
|
113
|
+
* [inX, inY, outX, outY] replaces the corner between P+(inX,inY) and P+(outX,outY) with a cubic
|
|
114
|
+
* Bezier whose two inner control points both sit ON P. Elsewhere the map is the straight chord
|
|
115
|
+
* between points. Rendered frame = floor(fps x S(t)) (predictSourceFrames): every frame of two
|
|
116
|
+
* Resolve hand-made eased ramps and of two ramps written offline by buildRampTimemapR21; a
|
|
117
|
+
* quadratic corner, a smoothstep speed blend and a k=0.5 cubic each miss 11-57 frames.
|
|
118
|
+
*/
|
|
119
|
+
function sourceSecAt(decoded, recordSec) {
|
|
120
|
+
const pts = [decoded.origin || { recordSec: 0, sourceSec: 0 }, ...decoded.keyframes];
|
|
121
|
+
for (const p of pts) {
|
|
122
|
+
const h = p.handles;
|
|
123
|
+
if (!h || h.length < 4) continue;
|
|
124
|
+
const [inX, inY, outX, outY] = h;
|
|
125
|
+
if (recordSec < p.recordSec + inX || recordSec > p.recordSec + outX) continue;
|
|
126
|
+
// x(u) = Px + (1-u)^3 inX + u^3 outX is monotonic for inX < 0 < outX; solve by bisection.
|
|
127
|
+
let lo = 0; let hi = 1;
|
|
128
|
+
for (let k = 0; k < 80; k++) {
|
|
129
|
+
const u = (lo + hi) / 2;
|
|
130
|
+
const x = p.recordSec + (1 - u) ** 3 * inX + u ** 3 * outX;
|
|
131
|
+
if (x < recordSec) lo = u; else hi = u;
|
|
132
|
+
}
|
|
133
|
+
const u = (lo + hi) / 2;
|
|
134
|
+
return p.sourceSec + (1 - u) ** 3 * inY + u ** 3 * outY;
|
|
135
|
+
}
|
|
136
|
+
for (let i = 1; i < pts.length; i++) {
|
|
137
|
+
if (recordSec <= pts[i].recordSec || i === pts.length - 1) {
|
|
138
|
+
const a = pts[i - 1]; const b = pts[i];
|
|
139
|
+
const dr = b.recordSec - a.recordSec;
|
|
140
|
+
return dr ? a.sourceSec + (b.sourceSec - a.sourceSec) * (recordSec - a.recordSec) / dr : a.sourceSec;
|
|
141
|
+
}
|
|
142
|
+
}
|
|
143
|
+
return pts[0].sourceSec;
|
|
144
|
+
}
|
|
145
|
+
|
|
146
|
+
/**
|
|
147
|
+
* Predicted source frame on each of `frameCount` record frames: floor(fps x S(n/fps) + 0.002).
|
|
148
|
+
* The 0.002-frame tolerance is fitted, not derived: it absorbs float noise at exact boundaries
|
|
149
|
+
* (a 2.0 s point lands on 59.99999…) and Resolve's corner starting a hair flatter than the cubic
|
|
150
|
+
* (n - 0.0015 in the model shows as n). With it all 2274 frames of six Studio 21.0.4.5 renders
|
|
151
|
+
* match (two linear, two Resolve-eased, two written offline); 0.001 misses 3 and 0.003 misses 2.
|
|
152
|
+
*/
|
|
153
|
+
function predictSourceFrames(decoded, frameCount, fps) {
|
|
154
|
+
return Array.from({ length: frameCount }, (_, n) => Math.floor(fps * sourceSecAt(decoded, n / fps) + 2e-3));
|
|
68
155
|
}
|
|
69
156
|
|
|
70
157
|
/**
|
|
@@ -107,19 +194,22 @@ function _decodeKeyframes(hex) {
|
|
|
107
194
|
const origin = pts.length && pts[0].recordSec === 0 ? pts.shift() : { recordSec: 0, sourceSec: 0 };
|
|
108
195
|
return { origin, keyframes: pts, keyed: true };
|
|
109
196
|
}
|
|
110
|
-
const
|
|
197
|
+
const { buf, zstd } = _unwrapKeyframes(Buffer.from(kh, 'hex'));
|
|
198
|
+
const fields = decodeProtobuf(buf);
|
|
111
199
|
const originField = fields.find((f) => f.field === 2 && f.wire === 1);
|
|
112
200
|
const originSource = originField
|
|
113
201
|
? (Buffer.isBuffer(originField.value)
|
|
114
202
|
? originField.value.readDoubleLE(0)
|
|
115
203
|
: Number(originField.value))
|
|
116
204
|
: 0;
|
|
117
|
-
|
|
118
|
-
|
|
119
|
-
|
|
120
|
-
|
|
121
|
-
|
|
122
|
-
};
|
|
205
|
+
const keyframes = fields
|
|
206
|
+
.filter((f) => f.field === 1 && f.wire === 2)
|
|
207
|
+
.map((f) => _decodeKeyframePoint(f.value));
|
|
208
|
+
// The eased (zstd) form drops field 160 and writes the (0,0) origin as an explicit, empty
|
|
209
|
+
// first point (`0a 00`); fold it back into `origin` so segments start where they always did.
|
|
210
|
+
let origin = { recordSec: 0, sourceSec: Number.isFinite(originSource) ? originSource : 0 };
|
|
211
|
+
if (zstd && !originField && keyframes.length > 1 && keyframes[0].recordSec === 0) origin = keyframes.shift();
|
|
212
|
+
return { origin, keyframes, zstd };
|
|
123
213
|
}
|
|
124
214
|
|
|
125
215
|
/** Per-segment speeds from the keyframe points (slope Δsource/Δrecord). */
|
|
@@ -141,15 +231,18 @@ function decodeTimemap(input) {
|
|
|
141
231
|
const get = (k) => { const e = entries.find((x) => x.key === k); return e ? e.value : undefined; };
|
|
142
232
|
const recordDurationSec = get('XMax');
|
|
143
233
|
const sourceDurationSec = get('LastValidYOffset');
|
|
144
|
-
const { origin, keyframes, keyed } = _decodeKeyframes(get('KeyframesBA'));
|
|
234
|
+
const { origin, keyframes, keyed, zstd } = _decodeKeyframes(get('KeyframesBA'));
|
|
145
235
|
const segments = _segments(keyframes, origin);
|
|
146
236
|
// The EXACT speed lives in the keyframe ratios (source/record per segment); XMax and
|
|
147
237
|
// LastValidYOffset are frame-quantized. `speed` is the first segment's (whole clip if 1 kf);
|
|
148
|
-
// `segments` carries the full variable-speed ramp.
|
|
238
|
+
// `segments` carries the full variable-speed ramp (chord speeds; eases round the corners).
|
|
149
239
|
const speed = segments.length ? segments[0].speed : sourceDurationSec / recordDurationSec;
|
|
150
240
|
const variable = segments.length > 1;
|
|
241
|
+
const eases = keyframes.filter((k) => k.handles).map((k) => ({ recordSec: k.recordSec, easeSec: k.handles[2], handles: k.handles }));
|
|
151
242
|
return {
|
|
152
|
-
form: 'retimed', variable, speed, segments, keyframes, origin,
|
|
243
|
+
form: 'retimed', variable, speed, segments, keyframes, origin,
|
|
244
|
+
keyframeForm: keyed ? 'keyed' : zstd ? 'protobuf-zstd' : 'protobuf',
|
|
245
|
+
eased: eases.length > 0, eases, mode: get('Mode'),
|
|
153
246
|
sourceDurationSec, recordDurationSec, entries,
|
|
154
247
|
};
|
|
155
248
|
}
|
|
@@ -215,6 +308,41 @@ function buildTimemap({ keyframes, sourceDurationSec, recordDurationSec, uniqueI
|
|
|
215
308
|
return encodeKeyedDict({ hdr: 1, entries });
|
|
216
309
|
}
|
|
217
310
|
|
|
311
|
+
/**
|
|
312
|
+
* EASED Sm2TimeMap (Studio 21.0.4.5) from explicit points `[{ recordSec, sourceSec, handles? }]`
|
|
313
|
+
* after the origin. Shape copied from Resolve's own eased ramps (byte-identical for the same
|
|
314
|
+
* points, handles and uniqueId): no YMin; YMax = last point's source clamped to the media extent;
|
|
315
|
+
* an int32 `Mode` = 2 after UniqueId; KeyframesBA = [0x81][zstd-1( F1{} origin, F1{rec, src,
|
|
316
|
+
* F3 handles?}, … )] with no field 160.
|
|
317
|
+
*/
|
|
318
|
+
function buildEasedTimemap({ points, sourceDurationSec, recordDurationSec, uniqueId }) {
|
|
319
|
+
if (!points || !points.length) throw new Error('need at least one point');
|
|
320
|
+
const msgs = [{ field: 1, wire: 2, value: Buffer.alloc(0) }];
|
|
321
|
+
for (const p of points) {
|
|
322
|
+
const parts = [Buffer.alloc(18)];
|
|
323
|
+
parts[0].writeUInt8(0x09, 0); parts[0].writeDoubleLE(p.recordSec, 1);
|
|
324
|
+
parts[0].writeUInt8(0x11, 9); parts[0].writeDoubleLE(p.sourceSec, 10);
|
|
325
|
+
if (p.handles) {
|
|
326
|
+
const h = Buffer.alloc(2 + p.handles.length * 8);
|
|
327
|
+
h.writeUInt8(0x1a, 0); h.writeUInt8(p.handles.length * 8, 1);
|
|
328
|
+
p.handles.forEach((v, k) => h.writeDoubleLE(v, 2 + k * 8));
|
|
329
|
+
parts.push(h);
|
|
330
|
+
}
|
|
331
|
+
msgs.push({ field: 1, wire: 2, value: Buffer.concat(parts) });
|
|
332
|
+
}
|
|
333
|
+
const last = points[points.length - 1];
|
|
334
|
+
const record = recordDurationSec == null ? last.recordSec : recordDurationSec;
|
|
335
|
+
return encodeKeyedDict({ hdr: 1, entries: [
|
|
336
|
+
{ key: 'YMax', type: T_DOUBLE, subType: 0, value: Math.min(last.sourceSec, sourceDurationSec) },
|
|
337
|
+
{ key: 'XMax', type: T_DOUBLE, subType: 0, value: record },
|
|
338
|
+
{ key: 'UniqueId', type: T_STRING, subType: 0, value: uniqueId },
|
|
339
|
+
{ key: 'Mode', type: T_INT32, subType: 0, value: 2 },
|
|
340
|
+
{ key: 'LastValidYOffset', type: T_DOUBLE, subType: 0, value: sourceDurationSec },
|
|
341
|
+
{ key: 'KeyframesBA', type: T_BYTES, subType: 0, value: _wrapKeyframes(encodeProtobuf(msgs)).toString('hex') },
|
|
342
|
+
{ key: 'DbType', type: T_STRING, subType: 0, value: 'Sm2TimeMap' },
|
|
343
|
+
] });
|
|
344
|
+
}
|
|
345
|
+
|
|
218
346
|
/**
|
|
219
347
|
* Build a constant-speed retimed map for a clip whose source runs `sourceDurationSec`, played
|
|
220
348
|
* at `speed` (0.5 = half speed → 2× longer). Single keyframe at the geometric line end.
|
|
@@ -377,10 +505,90 @@ function buildRampTimemapKeyed({ segments, srcIn = 0, sourceFrames, fps = 24, un
|
|
|
377
505
|
] });
|
|
378
506
|
}
|
|
379
507
|
|
|
508
|
+
/**
|
|
509
|
+
* VARIABLE-SPEED RAMP, R21 form — the shape Studio 21.0.4.5 writes itself for a ramp made on
|
|
510
|
+
* the retime bar (speed point + segment speed): YMin/YMax -1, XMax = record seconds,
|
|
511
|
+
* LastValidYOffset = (sourceFrames-1)/fps, KeyframesBA = PROTOBUF points [recordSec, sourceSec]
|
|
512
|
+
* after the implicit (0,0) origin. Only MediaTimemapBA and the item's Duration change
|
|
513
|
+
* (measured: a hand 100%→50% ramp differed from its constant twin in exactly those two columns).
|
|
514
|
+
*
|
|
515
|
+
* Render-verified 2026-10-19 on Studio 21.0.4.5: a 100% (30f) → 25% (90f) → 200% (120f) map
|
|
516
|
+
* patched into a closed project's Sm2TiItem rendered 240/240 frames on the predicted source
|
|
517
|
+
* frame floor(fps × S(t)). Resolve's own hand ramp renders by the same floor rule (538/538).
|
|
518
|
+
* The ramp starts at the media head (srcIn 0); windowed starts are not measured in this form.
|
|
519
|
+
*
|
|
520
|
+
* EASED speed points: `easeFrames` on segment i (i >= 1) eases the point where that segment
|
|
521
|
+
* starts, like Resolve's Speed Change > Ease "Ease In and Out" — handles [-h, -h*s_prev, h,
|
|
522
|
+
* h*s_next, 0, 0] with h = easeFrames/fps, rendered as the cubic corner in sourceSecAt. 'auto' =
|
|
523
|
+
* a third of the shorter neighbouring segment (what Resolve chose for one of its three measured
|
|
524
|
+
* 100%->50% points; its own choice for the others was 0.72 s / 0.88 s with 3 s / 4 s
|
|
525
|
+
* neighbours, rule not decoded — pass explicit frames to match a look). Any ease switches the
|
|
526
|
+
* map to Resolve's eased form (buildEasedTimemap). Render-verified 2026-10-19 on 21.0.4.5:
|
|
527
|
+
* 100/25/150 with 15- and 12-frame eases rendered 310/310 frames on predictSourceFrames (286
|
|
528
|
+
* if the eases were ignored); 100/50/200 with two 'auto' (20-frame) eases 320/320 (281).
|
|
529
|
+
*
|
|
530
|
+
* @param {object} p
|
|
531
|
+
* @param {Array<{durationFrames:number, speed:number, easeFrames?:number|'auto'}>} p.segments -
|
|
532
|
+
* record-domain pieces from the clip head; speed is source/record (0.5 = half speed).
|
|
533
|
+
* @param {number} p.sourceFrames - media frame count at p.fps.
|
|
534
|
+
* @param {number} p.fps - timeline = media frame rate (the measured case).
|
|
535
|
+
* @param {string} p.uniqueId - fresh uuid.
|
|
536
|
+
* @returns {{ timemap: Buffer, durationFrames: number, keyframes: Array, sourceEndFrame: number, eased: boolean }}
|
|
537
|
+
*/
|
|
538
|
+
function buildRampTimemapR21({ segments, sourceFrames, fps, uniqueId }) {
|
|
539
|
+
if (!Array.isArray(segments) || !segments.length) throw new TypeError('buildRampTimemapR21: segments must be a non-empty array of {durationFrames, speed}');
|
|
540
|
+
if (!Number.isInteger(sourceFrames) || sourceFrames < 2) throw new TypeError('buildRampTimemapR21: sourceFrames must be an integer >= 2');
|
|
541
|
+
if (!(fps > 0)) throw new TypeError('buildRampTimemapR21: fps must be > 0');
|
|
542
|
+
// Seconds accumulate per segment, as Resolve does (byte-exact vs its own hand ramp).
|
|
543
|
+
let rec = 0; let src = 0; let recSec = 0; let srcSec = 0; const keyframes = [];
|
|
544
|
+
for (const [i, s] of segments.entries()) {
|
|
545
|
+
if (!Number.isInteger(s.durationFrames) || s.durationFrames < 1) throw new TypeError(`buildRampTimemapR21: segments[${i}].durationFrames must be a positive integer`);
|
|
546
|
+
if (!(s.speed > 0)) throw new RangeError(`buildRampTimemapR21: segments[${i}].speed must be > 0`);
|
|
547
|
+
rec += s.durationFrames; src += s.durationFrames * s.speed;
|
|
548
|
+
recSec += s.durationFrames / fps; srcSec += (s.durationFrames * s.speed) / fps;
|
|
549
|
+
keyframes.push({ recordSec: recSec, sourceSec: srcSec });
|
|
550
|
+
}
|
|
551
|
+
// Ease half-widths per speed point (frames); point i-1 sits between segments i-1 and i.
|
|
552
|
+
const ease = segments.map((s, i) => {
|
|
553
|
+
if (s.easeFrames == null || s.easeFrames === 0) return 0;
|
|
554
|
+
if (i === 0) throw new RangeError('buildRampTimemapR21: segments[0].easeFrames: the clip head is not a speed point');
|
|
555
|
+
const h = s.easeFrames === 'auto' ? Math.min(segments[i - 1].durationFrames, s.durationFrames) / 3 : s.easeFrames;
|
|
556
|
+
if (!(h > 0)) throw new RangeError(`buildRampTimemapR21: segments[${i}].easeFrames must be > 0 or 'auto'`);
|
|
557
|
+
return h;
|
|
558
|
+
});
|
|
559
|
+
for (const [i, s] of segments.entries()) {
|
|
560
|
+
const used = ease[i] + (ease[i + 1] || 0);
|
|
561
|
+
if (used > s.durationFrames) throw new RangeError(`buildRampTimemapR21: eases around segments[${i}] span ${used} frames but the segment has ${s.durationFrames}`);
|
|
562
|
+
}
|
|
563
|
+
const eased = ease.some((h) => h > 0);
|
|
564
|
+
if (eased) {
|
|
565
|
+
ease.forEach((hf, i) => {
|
|
566
|
+
if (!hf) return;
|
|
567
|
+
const h = hf / fps;
|
|
568
|
+
keyframes[i - 1].handles = [-h, -h * segments[i - 1].speed, h, h * segments[i].speed, 0, 0];
|
|
569
|
+
});
|
|
570
|
+
}
|
|
571
|
+
// Source frame shown on the LAST record frame (rec-1), Resolve's floor rule.
|
|
572
|
+
const last = segments[segments.length - 1];
|
|
573
|
+
let sourceEndFrame = Math.floor(src - last.speed);
|
|
574
|
+
if (eased) {
|
|
575
|
+
const decoded = { origin: { recordSec: 0, sourceSec: 0 }, keyframes };
|
|
576
|
+
sourceEndFrame = predictSourceFrames(decoded, rec, fps)[rec - 1];
|
|
577
|
+
}
|
|
578
|
+
if (sourceEndFrame > sourceFrames - 1) {
|
|
579
|
+
throw new RangeError(`buildRampTimemapR21: ramp reaches source frame ${sourceEndFrame} but the media ends at ${sourceFrames - 1}`);
|
|
580
|
+
}
|
|
581
|
+
const sourceDurationSec = (sourceFrames - 1) / fps;
|
|
582
|
+
const timemap = eased
|
|
583
|
+
? buildEasedTimemap({ points: keyframes, sourceDurationSec, recordDurationSec: recSec, uniqueId })
|
|
584
|
+
: buildTimemap({ keyframes, sourceDurationSec, recordDurationSec: recSec, uniqueId });
|
|
585
|
+
return { timemap, durationFrames: rec, keyframes, sourceEndFrame, eased };
|
|
586
|
+
}
|
|
587
|
+
|
|
380
588
|
module.exports = {
|
|
381
589
|
decodeTimemap, encodeTimemap, encodeRetimedTimemap,
|
|
382
590
|
identityTimemap, buildConstantSpeedTimemap, buildConstantSpeedTimemapKeyed,
|
|
383
|
-
buildFreezeTimemapKeyed, buildRampTimemapKeyed,
|
|
384
|
-
buildTimemap, decodeProtobuf,
|
|
591
|
+
buildFreezeTimemapKeyed, buildRampTimemapKeyed, buildRampTimemapR21,
|
|
592
|
+
buildTimemap, buildEasedTimemap, sourceSecAt, predictSourceFrames, decodeProtobuf,
|
|
385
593
|
TYPE_LINEAR,
|
|
386
594
|
};
|
|
@@ -320,11 +320,13 @@ function parseCDL(cdlContent) {
|
|
|
320
320
|
const results = [];
|
|
321
321
|
|
|
322
322
|
// Simple XML parsing for CDL (avoid external dependencies)
|
|
323
|
-
|
|
323
|
+
// The id attribute may be empty or absent; such corrections are still looks.
|
|
324
|
+
const correctionRegex = /<ColorCorrection(\s[^>]*?)?(?<!\/)>([\s\S]*?)<\/ColorCorrection>/gi;
|
|
324
325
|
let match;
|
|
325
326
|
|
|
326
327
|
while ((match = correctionRegex.exec(cdlContent)) !== null) {
|
|
327
|
-
const
|
|
328
|
+
const idMatch = (match[1] || '').match(/(?:^|\s)id\s*=\s*"([^"]*)"/);
|
|
329
|
+
const id = idMatch ? idMatch[1] : '';
|
|
328
330
|
const content = match[2];
|
|
329
331
|
|
|
330
332
|
const cdlValues = {
|
|
@@ -926,6 +926,25 @@ function createNode(nodeId, xPos, yPos, colorParams = null, options = {}) {
|
|
|
926
926
|
return protoBytes(7, Buffer.concat(parts));
|
|
927
927
|
}
|
|
928
928
|
|
|
929
|
+
/**
|
|
930
|
+
* Lum Mix value to write, or undefined to leave Resolve's default.
|
|
931
|
+
*
|
|
932
|
+
* Render-measured on Studio 21.0.4.5 (2026-10-19, 30p grey-128 clip): under the default Lum Mix
|
|
933
|
+
* (UI 100, stored 1.0) the lift/gamma/gain R/G/B channels are luminance-preserving, so gain
|
|
934
|
+
* R=G=B=1.6 rendered unchanged (127.59) and gain 1.6/1.0/0.7 rendered 190.5/114.1/76.0 (luma
|
|
935
|
+
* held). With Lum Mix 0 the same values render as per-channel multipliers (204.1 and
|
|
936
|
+
* 204.2/127.7/89.7), which is what Resolve itself writes for SetCDL. Masters and offset render
|
|
937
|
+
* the same either way.
|
|
938
|
+
*
|
|
939
|
+
* Opt-in: pass lumMixSlider (stored units; 0 is written, not dropped) for per-channel R/G/B
|
|
940
|
+
* moves. Defaulting every R/G/B move to Lum Mix 0 is NOT done: it would change the render of
|
|
941
|
+
* every existing caller and has only been measured on Studio 21.0.4.5.
|
|
942
|
+
*/
|
|
943
|
+
function resolveLumMix(colorParams) {
|
|
944
|
+
return typeof colorParams.lumMixSlider === 'number' && Number.isFinite(colorParams.lumMixSlider)
|
|
945
|
+
? colorParams.lumMixSlider : undefined;
|
|
946
|
+
}
|
|
947
|
+
|
|
929
948
|
/**
|
|
930
949
|
* Build Primary Corrector parameters (Lift/Gamma/Gain/Offset)
|
|
931
950
|
*/
|
|
@@ -1165,10 +1184,12 @@ function buildPrimaryCorrectorParams(colorParams) {
|
|
|
1165
1184
|
paramEntries.push(createParameterEntry(PARAM_IDS.SHADOWS, colorParams.shadows));
|
|
1166
1185
|
}
|
|
1167
1186
|
|
|
1168
|
-
// Lum Mix slider (0.0
|
|
1169
|
-
|
|
1170
|
-
|
|
1171
|
-
|
|
1187
|
+
// Lum Mix slider (0x8600000B, stored 0.0–1.0 = UI 0–100; Resolve's default is 1.0).
|
|
1188
|
+
// See resolveLumMix: written only when the caller sets lumMixSlider.
|
|
1189
|
+
const lumMix = resolveLumMix(colorParams);
|
|
1190
|
+
if (lumMix !== undefined) {
|
|
1191
|
+
debugLog('[DRX] Adding lumMixSlider:', lumMix);
|
|
1192
|
+
paramEntries.push(createParameterEntry(PARAM_IDS.LUM_MIX_SLIDER, lumMix));
|
|
1172
1193
|
}
|
|
1173
1194
|
|
|
1174
1195
|
// ═══════════════════════════════════════════════════════════════════════════
|
|
@@ -2252,6 +2273,8 @@ function parseAdjustments(adjustments) {
|
|
|
2252
2273
|
// Highlights/Shadows sliders — direct values
|
|
2253
2274
|
if (adjustments.highlights !== undefined) params.highlights = adjustments.highlights;
|
|
2254
2275
|
if (adjustments.shadows !== undefined) params.shadows = adjustments.shadows;
|
|
2276
|
+
// Lum Mix — 0-1 stored (UI 0-100 / 100); see resolveLumMix
|
|
2277
|
+
if (adjustments.lumMixSlider !== undefined) params.lumMixSlider = adjustments.lumMixSlider;
|
|
2255
2278
|
// Custom Curves
|
|
2256
2279
|
if (adjustments.customCurves) params.customCurves = adjustments.customCurves;
|
|
2257
2280
|
// HSL Curves
|
|
@@ -0,0 +1,80 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* grade-body-wire — path-directed edits of a decompressed grade body (.drx <Body>, or
|
|
3
|
+
* Project.db ListMgt::LmVersion.Body). Everything outside the edited path is carried
|
|
4
|
+
* byte-exact; parents are re-encoded with their new lengths.
|
|
5
|
+
*
|
|
6
|
+
* Shared by grade-keyframes.js and magic-mask-author.js.
|
|
7
|
+
*
|
|
8
|
+
* @module drx-codec/grade-body-wire
|
|
9
|
+
*/
|
|
10
|
+
|
|
11
|
+
const zlib = require('zlib');
|
|
12
|
+
const { decodeProtobuf, encodeProtobuf } = require('../drp-format/protobuf-wire');
|
|
13
|
+
const { zstdRawFrame } = require('../drp-format/timeline-markers-blob');
|
|
14
|
+
|
|
15
|
+
let fzstd = null;
|
|
16
|
+
try { fzstd = require('fzstd'); } catch (e) { /* optional; native zlib zstd covers Node 22.15+ */ }
|
|
17
|
+
|
|
18
|
+
/** <Body> hex (0x81 = zstd, 0x80 = stored) → raw protobuf Buffer. */
|
|
19
|
+
function decodeBody(hex) {
|
|
20
|
+
const b = Buffer.from(String(hex).replace(/[^0-9a-fA-F]/g, ''), 'hex');
|
|
21
|
+
if (b[0] === 0x80) return b.slice(1);
|
|
22
|
+
if (b[0] !== 0x81) throw new Error(`grade body: unknown magic 0x${b[0].toString(16)}`);
|
|
23
|
+
if (typeof zlib.zstdDecompressSync === 'function') return zlib.zstdDecompressSync(b.slice(1));
|
|
24
|
+
if (!fzstd) throw new Error("grade body: zstd decoding needs Node 22.15+ or the optional dep 'fzstd'");
|
|
25
|
+
return Buffer.from(fzstd.decompress(new Uint8Array(b.slice(1))));
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
/**
|
|
29
|
+
* raw protobuf Buffer → <Body> hex (0x81 + zstd), upper-case like Resolve writes it.
|
|
30
|
+
* Without native zstd (Node < 22.15) the frame is spec-valid but stored (raw blocks, no
|
|
31
|
+
* compression); a render check of such a Body in Resolve has not been measured.
|
|
32
|
+
*/
|
|
33
|
+
function encodeBody(raw) {
|
|
34
|
+
const frame = typeof zlib.zstdCompressSync === 'function' ? zlib.zstdCompressSync(raw) : zstdRawFrame(raw);
|
|
35
|
+
return Buffer.concat([Buffer.from([0x81]), frame]).toString('hex').toUpperCase();
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
const bodyHexOf = (xml) => {
|
|
39
|
+
const m = String(xml).match(/<Body>([0-9a-fA-F]+)<\/Body>/);
|
|
40
|
+
if (!m) throw new Error('no <Body> in .drx');
|
|
41
|
+
return m[1];
|
|
42
|
+
};
|
|
43
|
+
const withBodyHex = (xml, hex) => String(xml).replace(/<Body>[0-9a-fA-F]+<\/Body>/, () => `<Body>${hex}</Body>`);
|
|
44
|
+
|
|
45
|
+
/** True when a decoded message carries varint field 1 == n (corrector type, tool id, ...). */
|
|
46
|
+
const hasF1 = (n) => (fields) => fields.some((x) => x.field === 1 && x.wire === 0 && Number(x.value) === n);
|
|
47
|
+
|
|
48
|
+
/**
|
|
49
|
+
* Edit the message at `path` inside `buf`. A path step is a field number, or
|
|
50
|
+
* { field, where(fields) } to pick among repeated fields. `fn(fields)` mutates the
|
|
51
|
+
* leaf's field list in place. Every match of a step is visited; a step that matches
|
|
52
|
+
* nothing throws (so a layout drift fails loudly instead of writing nothing).
|
|
53
|
+
*/
|
|
54
|
+
function editAt(buf, path, fn) {
|
|
55
|
+
const fields = decodeProtobuf(buf);
|
|
56
|
+
if (!path.length) { fn(fields); return encodeProtobuf(fields); }
|
|
57
|
+
const [step, ...rest] = path;
|
|
58
|
+
const field = typeof step === 'number' ? step : step.field;
|
|
59
|
+
const where = typeof step === 'number' ? () => true : step.where;
|
|
60
|
+
let hits = 0;
|
|
61
|
+
for (const f of fields) {
|
|
62
|
+
if (f.field !== field || f.wire !== 2) continue;
|
|
63
|
+
if (!where(decodeProtobuf(f.value))) continue;
|
|
64
|
+
f.value = editAt(f.value, rest, fn);
|
|
65
|
+
hits++;
|
|
66
|
+
}
|
|
67
|
+
if (!hits) throw new Error(`grade body: path step F${field} not found`);
|
|
68
|
+
return encodeProtobuf(fields);
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
/** Read the field list of the (first) message at `path`. */
|
|
72
|
+
function readAt(buf, path) {
|
|
73
|
+
let out = null;
|
|
74
|
+
editAt(buf, path, (fields) => { if (!out) out = fields.map((f) => ({ ...f })); });
|
|
75
|
+
return out;
|
|
76
|
+
}
|
|
77
|
+
|
|
78
|
+
const float32 = (v) => { const b = Buffer.alloc(4); b.writeFloatLE(v, 0); return b; };
|
|
79
|
+
|
|
80
|
+
module.exports = { decodeBody, encodeBody, bodyHexOf, withBodyHex, hasF1, editAt, readAt, float32 };
|
|
@@ -0,0 +1,90 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* grade-keyframes — WRITE keyframed (animated) grade params into a .drx.
|
|
3
|
+
*
|
|
4
|
+
* Wire layout (decoded from Resolve's own captures, test/fixtures/keyframe-track.drx and
|
|
5
|
+
* keyframed-grade.drx): a keyframed corrector's F6 becomes REPEATED, one block per keyframe:
|
|
6
|
+
*
|
|
7
|
+
* F6 { F1: frame × 2 (absent at frame 0), F2: { F1: kind, F3: [params …] } }
|
|
8
|
+
*
|
|
9
|
+
* kind 2 = DYNAMIC keyframe (linear interpolation to the next one), kind 1 = STATIC keyframe
|
|
10
|
+
* (holds until the next one). Frames are clip frames when applied with ApplyGradeFromDRX
|
|
11
|
+
* gradeMode 2 ("start frames aligned"); gradeMode 0 drops keyframes.
|
|
12
|
+
*
|
|
13
|
+
* Render-verified on Studio 21.0.4.5 (2026-10-19, 30p barcode clip, Midtone Detail 0→100 over
|
|
14
|
+
* frames 0→100): kind 2 gave 0.0 / 50.1 / 75.1 % of the static-MD-100 detail lift at frames
|
|
15
|
+
* 0 / 50 / 75 and exactly 100 % from frame 100 on; kind 1 gave 0 % through frame 99 and 100 %
|
|
16
|
+
* from frame 100. Resolve stored the blocks unchanged (Project.db readback).
|
|
17
|
+
*
|
|
18
|
+
* Primary R/G/B wheel channels (gain 0x0600001D–1F etc.) need Lum Mix 0 (0x8600000B) in the
|
|
19
|
+
* corrector to act per channel; under Resolve's default Lum Mix equal R/G/B moves cancel on luma.
|
|
20
|
+
* A base from generateDRX carries it (it writes Lum Mix 0 for R/G/B moves), and every keyframe
|
|
21
|
+
* block copies the base params: keyframed gain R=G=B 1.0→1.6 over frames 0→28 rendered
|
|
22
|
+
* 127.59 → 165.86 (f14) → 204.14 (f28) on a grey-128 band (2026-10-19). Prove other params with
|
|
23
|
+
* a render.
|
|
24
|
+
*
|
|
25
|
+
* @module drx-codec/grade-keyframes
|
|
26
|
+
*/
|
|
27
|
+
|
|
28
|
+
const { decodeProtobuf, encodeProtobuf } = require('../drp-format/protobuf-wire');
|
|
29
|
+
const { decodeBody, encodeBody, bodyHexOf, withBodyHex, hasF1, editAt, float32 } = require('./grade-body-wire');
|
|
30
|
+
|
|
31
|
+
const KIND = { static: 1, dynamic: 2 };
|
|
32
|
+
|
|
33
|
+
/**
|
|
34
|
+
* Turn one corrector of a generated (or captured) .drx into a keyframe track.
|
|
35
|
+
*
|
|
36
|
+
* Every keyframe block carries the corrector's full param list; params named in a
|
|
37
|
+
* keyframe's `values` get that value, all others keep the base value.
|
|
38
|
+
*
|
|
39
|
+
* @param {string} drxXml - .drx content with a non-keyframed corrector of `correctorType`.
|
|
40
|
+
* @param {object} spec
|
|
41
|
+
* @param {number} [spec.nodeIndex=0] - 0-based node (F1.F7 entry) to edit.
|
|
42
|
+
* @param {number} [spec.correctorType=1] - 1 = Primary (lift/gamma/gain/MD/sat …).
|
|
43
|
+
* @param {'dynamic'|'static'|number} [spec.kind='dynamic']
|
|
44
|
+
* @param {Array<{frame:number, values:Object<string|number, number>}>} spec.keyframes -
|
|
45
|
+
* >= 2 keyframes, frames ascending; `values` maps param id (e.g. 0x86000113) → float.
|
|
46
|
+
* @returns {string} .drx content with the keyframed body.
|
|
47
|
+
*/
|
|
48
|
+
function keyframeCorrector(drxXml, { nodeIndex = 0, correctorType = 1, kind = 'dynamic', keyframes } = {}) {
|
|
49
|
+
const kindNum = typeof kind === 'number' ? kind : KIND[kind];
|
|
50
|
+
if (!kindNum) throw new TypeError(`keyframeCorrector: kind must be dynamic|static|1|2 (got ${kind})`);
|
|
51
|
+
if (!Array.isArray(keyframes) || keyframes.length < 2) throw new TypeError('keyframeCorrector: need >= 2 keyframes');
|
|
52
|
+
for (let i = 0; i < keyframes.length; i++) {
|
|
53
|
+
const k = keyframes[i];
|
|
54
|
+
if (!(k.frame >= 0) || (i && k.frame <= keyframes[i - 1].frame)) throw new RangeError('keyframeCorrector: frames must be >= 0 and ascending');
|
|
55
|
+
}
|
|
56
|
+
const raw = decodeBody(bodyHexOf(drxXml));
|
|
57
|
+
if (!encodeProtobuf(decodeProtobuf(raw)).equals(raw)) throw new Error('keyframeCorrector: body does not round-trip; refusing');
|
|
58
|
+
|
|
59
|
+
let nodeSeen = -1;
|
|
60
|
+
const out = editAt(raw, [1, { field: 7, where: () => (++nodeSeen === nodeIndex) }, 9, { field: 1, where: hasF1(correctorType) }], (corr) => {
|
|
61
|
+
const f6s = corr.filter((f) => f.field === 6);
|
|
62
|
+
if (f6s.length !== 1) throw new Error('keyframeCorrector: corrector is already keyframed');
|
|
63
|
+
const inner = decodeProtobuf(decodeProtobuf(f6s[0].value).find((f) => f.field === 2).value);
|
|
64
|
+
const params = inner.filter((f) => f.field === 3);
|
|
65
|
+
const ids = new Set(params.map((p) => decodeProtobuf(p.value).find((f) => f.field === 1).value));
|
|
66
|
+
for (const k of keyframes) {
|
|
67
|
+
for (const id of Object.keys(k.values)) {
|
|
68
|
+
if (!ids.has(BigInt(id))) throw new Error(`keyframeCorrector: param ${id} is not in the base corrector — write it once statically first`);
|
|
69
|
+
}
|
|
70
|
+
}
|
|
71
|
+
const blocks = keyframes.map((k) => {
|
|
72
|
+
const ps = params.map((p) => {
|
|
73
|
+
const pf = decodeProtobuf(p.value);
|
|
74
|
+
const id = pf.find((f) => f.field === 1).value;
|
|
75
|
+
const key = Object.keys(k.values).find((x) => BigInt(x) === id);
|
|
76
|
+
if (key === undefined) return p;
|
|
77
|
+
const val = encodeProtobuf([{ field: 1, wire: 5, value: float32(k.values[key]) }]);
|
|
78
|
+
return { field: 3, wire: 2, value: encodeProtobuf(pf.map((f) => (f.field === 2 ? { field: 2, wire: 2, value: val } : f))) };
|
|
79
|
+
});
|
|
80
|
+
const rest = inner.filter((f) => f.field !== 1 && f.field !== 3);
|
|
81
|
+
const f2 = encodeProtobuf([{ field: 1, wire: 0, value: BigInt(kindNum) }, ...rest, ...ps]);
|
|
82
|
+
const head = k.frame > 0 ? [{ field: 1, wire: 0, value: BigInt(Math.round(k.frame * 2)) }] : [];
|
|
83
|
+
return { field: 6, wire: 2, value: encodeProtobuf([...head, { field: 2, wire: 2, value: f2 }]) };
|
|
84
|
+
});
|
|
85
|
+
corr.splice(corr.indexOf(f6s[0]), 1, ...blocks);
|
|
86
|
+
});
|
|
87
|
+
return withBodyHex(drxXml, encodeBody(out));
|
|
88
|
+
}
|
|
89
|
+
|
|
90
|
+
module.exports = { keyframeCorrector, KIND };
|
|
@@ -0,0 +1,101 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* magic-mask-author — move a Magic Mask 2 subject click inside a captured grade, so a mask can
|
|
3
|
+
* be placed on another clip with no Viewer clicks.
|
|
4
|
+
*
|
|
5
|
+
* Decoded from a hand-made Magic Mask 2 (person click, Better) on Studio 21.0.4.5, 2026-10-19.
|
|
6
|
+
* The grade body stores the CLICK, not the tracked mattes (those are regenerated):
|
|
7
|
+
*
|
|
8
|
+
* node.F9 corrector type 2 → F6.F2:
|
|
9
|
+
* F3 { F1: 0x88300037, F2 { F2: 2 } } mask mode
|
|
10
|
+
* F4 { F1 { F1: frame × 2, SOURCE frame of the click
|
|
11
|
+
* F2 { F1: 0x88300036, F2 { F23 { F1 {
|
|
12
|
+
* F1: 2048 (stroke id), F2 { F1: 2, F2: 6 (add point),
|
|
13
|
+
* F3 { F1: x f32, F2: y f32 } } } } } } } }
|
|
14
|
+
* node.F10 tool list: 0xC00000B3 (stroke list, "Overall Track"), 0xC00000B6/B7 (= stroke id),
|
|
15
|
+
* 0xC00000CA { F2.F11.F1.F220 = frame × 2 }, 0xC00000CC { F2.F2 = frame × 2 }
|
|
16
|
+
*
|
|
17
|
+
* x / y are centred and y-up, normalised to the image: x = u − 0.5, y = 0.5 − v for a click at
|
|
18
|
+
* (u, v) of the frame measured from its top-left (the hand click at u 0.484, v 0.371 stored
|
|
19
|
+
* −0.0156, 0.1286).
|
|
20
|
+
*
|
|
21
|
+
* Proven 2026-10-19: the authored grade applied with ApplyGradeFromDRX (gradeMode 0) to a
|
|
22
|
+
* DIFFERENT clip, then TimelineItem.CreateMagicMask("BI") — no clicks — tracked all 50 frames;
|
|
23
|
+
* a Saturation 0 Primary in the same node dropped subject saturation 170 → 4.6 while the
|
|
24
|
+
* background stayed 164.6 → 164.6. RegenerateMagicMask() returned False on the fresh apply;
|
|
25
|
+
* use CreateMagicMask.
|
|
26
|
+
*
|
|
27
|
+
* @module drx-codec/magic-mask-author
|
|
28
|
+
*/
|
|
29
|
+
|
|
30
|
+
const { decodeProtobuf, encodeProtobuf } = require('../drp-format/protobuf-wire');
|
|
31
|
+
const { decodeBody, encodeBody, bodyHexOf, withBodyHex, hasF1, editAt, readAt } = require('./grade-body-wire');
|
|
32
|
+
|
|
33
|
+
const MASK_CORRECTOR = 2;
|
|
34
|
+
const TOOL_REF_FRAME_A = 0xc00000ca;
|
|
35
|
+
const TOOL_REF_FRAME_B = 0xc00000cc;
|
|
36
|
+
const CLICK = [1, 7, 9, { field: 1, where: hasF1(MASK_CORRECTOR) }, 6, 2, 4, 1];
|
|
37
|
+
|
|
38
|
+
/** Read the click(s) of a Magic Mask grade body: [{ frame, x, y, op }]. */
|
|
39
|
+
function readMagicMaskClicks(bodyHex) {
|
|
40
|
+
const raw = decodeBody(bodyHex);
|
|
41
|
+
const out = [];
|
|
42
|
+
editAt(raw, CLICK.slice(0, -1), (f4) => {
|
|
43
|
+
for (const blk of f4.filter((f) => f.field === 1 && f.wire === 2)) {
|
|
44
|
+
const b = decodeProtobuf(blk.value);
|
|
45
|
+
const t = b.find((f) => f.field === 1 && f.wire === 0);
|
|
46
|
+
const frame = t ? Number(t.value) / 2 : 0;
|
|
47
|
+
const strokes = readAt(blk.value, [2, 2, 23]) || [];
|
|
48
|
+
for (const s of strokes.filter((f) => f.field === 1 && f.wire === 2)) {
|
|
49
|
+
const pt = readAt(s.value, [2]);
|
|
50
|
+
const xy = readAt(s.value, [2, 3]);
|
|
51
|
+
out.push({
|
|
52
|
+
frame,
|
|
53
|
+
op: Number((pt.find((f) => f.field === 2) || {}).value),
|
|
54
|
+
x: xy.find((f) => f.field === 1).value.readFloatLE(0),
|
|
55
|
+
y: xy.find((f) => f.field === 2).value.readFloatLE(0),
|
|
56
|
+
});
|
|
57
|
+
}
|
|
58
|
+
}
|
|
59
|
+
});
|
|
60
|
+
return out;
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
/**
|
|
64
|
+
* Re-place the single subject click of a captured Magic Mask 2 grade.
|
|
65
|
+
*
|
|
66
|
+
* @param {string} drxXml - .drx whose <Body> is a captured Magic Mask grade (one click).
|
|
67
|
+
* @param {{frame:number, x:number, y:number}} click - SOURCE frame; x/y centred, y-up, in [-0.5, 0.5].
|
|
68
|
+
* @param {object} [opts]
|
|
69
|
+
* @param {string} [opts.primaryFromDrx] - .drx whose Primary corrector (type 1) is copied into the
|
|
70
|
+
* mask node, so the correction lands inside the mask (e.g. saturation, Midtone Detail).
|
|
71
|
+
* @returns {string} .drx content.
|
|
72
|
+
*/
|
|
73
|
+
function placeMagicMaskClick(drxXml, { frame, x, y }, { primaryFromDrx } = {}) {
|
|
74
|
+
if (!Number.isInteger(frame) || frame < 0) throw new TypeError('placeMagicMaskClick: frame must be a non-negative integer (source frame)');
|
|
75
|
+
if (!(Math.abs(x) <= 0.5 && Math.abs(y) <= 0.5)) throw new RangeError('placeMagicMaskClick: x/y are centred image fractions in [-0.5, 0.5]');
|
|
76
|
+
let raw = decodeBody(bodyHexOf(drxXml));
|
|
77
|
+
if (!encodeProtobuf(decodeProtobuf(raw)).equals(raw)) throw new Error('placeMagicMaskClick: body does not round-trip; refusing');
|
|
78
|
+
if (readMagicMaskClicks(bodyHexOf(drxXml)).length !== 1) throw new Error('placeMagicMaskClick: expected exactly one captured click');
|
|
79
|
+
const t2 = BigInt(frame * 2);
|
|
80
|
+
raw = editAt(raw, CLICK, (f) => { for (const x_ of f) if (x_.field === 1 && x_.wire === 0) x_.value = t2; });
|
|
81
|
+
raw = editAt(raw, [...CLICK, 2, 2, 23, 1, 2, 3], (f) => {
|
|
82
|
+
for (const v of f) {
|
|
83
|
+
if (v.field === 1 && v.wire === 5) v.value.writeFloatLE(x, 0);
|
|
84
|
+
if (v.field === 2 && v.wire === 5) v.value.writeFloatLE(y, 0);
|
|
85
|
+
}
|
|
86
|
+
});
|
|
87
|
+
raw = editAt(raw, [1, 7, 10, { field: 1, where: hasF1(TOOL_REF_FRAME_A) }, 2, 11, 1], (f) => { for (const v of f) if (v.field === 220) v.value = t2; });
|
|
88
|
+
raw = editAt(raw, [1, 7, 10, { field: 1, where: hasF1(TOOL_REF_FRAME_B) }, 2], (f) => { for (const v of f) if (v.field === 2 && v.wire === 0) v.value = t2; });
|
|
89
|
+
if (primaryFromDrx) {
|
|
90
|
+
const praw = decodeBody(bodyHexOf(primaryFromDrx));
|
|
91
|
+
const prim = (readAt(praw, [1, 7, 9]) || []).find((f) => f.field === 1 && f.wire === 2 && hasF1(1)(decodeProtobuf(f.value)));
|
|
92
|
+
if (!prim) throw new Error('placeMagicMaskClick: primaryFromDrx has no Primary corrector');
|
|
93
|
+
raw = editAt(raw, [1, 7, 9], (list) => {
|
|
94
|
+
if (list.some((f) => f.field === 1 && f.wire === 2 && hasF1(1)(decodeProtobuf(f.value)))) throw new Error('placeMagicMaskClick: mask node already has a Primary');
|
|
95
|
+
list.splice(list.findIndex((f) => f.field === 1), 0, prim);
|
|
96
|
+
});
|
|
97
|
+
}
|
|
98
|
+
return withBodyHex(drxXml, encodeBody(raw));
|
|
99
|
+
}
|
|
100
|
+
|
|
101
|
+
module.exports = { placeMagicMaskClick, readMagicMaskClicks };
|
|
@@ -25,10 +25,10 @@ The `space` flag unifies input units: **`space:'ui'` (default)** = Resolve panel
|
|
|
25
25
|
|
|
26
26
|
| Parameter | `ui`→DRX factor | Status | Verified |
|
|
27
27
|
|-----------|-----------------|--------|----------|
|
|
28
|
-
| lift (r/g/b/master) | ×2 | ✅ | panel (0.10→0.05) + round-trip |
|
|
29
|
-
| gamma (r/g/b/master) | ×4 | ✅ | panel (0.20→0.05) + round-trip |
|
|
30
|
-
| gain (r/g/b/master) | ×1 | ✅ | panel (1.10→1.10) + round-trip |
|
|
31
|
-
| offset (r/g/b) | ÷25, **delta from neutral** | ✅ | panel (0.04→+1.00) + round-trip |
|
|
28
|
+
| lift (r/g/b/master) | ×2 | ✅ | panel (0.10→0.05) + round-trip; render R21 2026-10-19 (R/G/B need Lum Mix 0, see Studio 21 section) |
|
|
29
|
+
| gamma (r/g/b/master) | ×4 | ✅ | panel (0.20→0.05) + round-trip; render R21 2026-10-19 (as lift) |
|
|
30
|
+
| gain (r/g/b/master) | ×1 | ✅ | panel (1.10→1.10) + round-trip; render R21 2026-10-19 (as lift) |
|
|
31
|
+
| offset (r/g/b) | ÷25, **delta from neutral** | ✅ | panel (0.04→+1.00) + round-trip; render R21 2026-10-19 |
|
|
32
32
|
| saturation | ÷50 (0–100, 50=neutral) | ✅ | panel (55) + round-trip |
|
|
33
33
|
| contrast | 1:1 (1.0-scale) | ✅ | panel (1.2→1.200) + round-trip |
|
|
34
34
|
| pivot | 1:1 | ✅ | panel (0.5→0.500) + round-trip |
|
|
@@ -262,8 +262,9 @@ Everything below is flagged in code/tests where it applies; this list is the sum
|
|
|
262
262
|
|
|
263
263
|
**Decoded but no write path (deliberate; transfer via Body copy works byte-exact):**
|
|
264
264
|
- Tracker data (per-frame 3×3 transforms) — authoring synthetic tracks not built.
|
|
265
|
-
- Keyframed/animated params — decode cracked;
|
|
266
|
-
(
|
|
265
|
+
- Keyframed/animated params — decode cracked; WRITE built 2026-10-19 as a library function
|
|
266
|
+
(`grade-keyframes.js`, see the Studio 21.0.4.5 section) but not yet exposed as a `drx`
|
|
267
|
+
tool action (verify_grade still flags keyframed grades `unverifiable`).
|
|
267
268
|
|
|
268
269
|
**Known-soft spots (documented in place):**
|
|
269
270
|
- HDR zone-def STOCK defaults: only Dark is capture-verified; other zones' F2/F4
|
|
@@ -280,6 +281,67 @@ Everything below is flagged in code/tests where it applies; this list is the sum
|
|
|
280
281
|
- Pipeline run-level status doesn't roll up when stages are driven individually (rollup
|
|
281
282
|
polish); gallery ExportStills / export_frame_as_still fail HEADLESS-only.
|
|
282
283
|
|
|
284
|
+
## Studio 21.0.4.5 writers — render-verified 2026-10-19
|
|
285
|
+
|
|
286
|
+
Measured on Windows, Studio 21.0.4.5, throwaway projects; every claim below is a render
|
|
287
|
+
measurement (frame-coded barcode clip or per-frame metric), not a readback.
|
|
288
|
+
|
|
289
|
+
- **Keyframed grade params — WRITE built** (`vendor/drx-codec/grade-keyframes.js`). A keyframed
|
|
290
|
+
corrector's F6 repeats per keyframe `{F1: frame×2, F2:{F1: kind, F3:[params]}}`. kind 2 =
|
|
291
|
+
dynamic (linear): Midtone Detail 0→100 over frames 0→100 gave 0.0 / 50.1 / 75.1 % of the
|
|
292
|
+
static MD-100 detail lift at frames 0 / 50 / 75 and 100 % from frame 100. kind 1 = static
|
|
293
|
+
(hold): 0 % through frame 99, 100 % from frame 100. Apply with gradeMode 2 (gradeMode 0 drops
|
|
294
|
+
keyframes).
|
|
295
|
+
- **Primary wheels render; R/G/B channels follow Lum Mix (0x8600000B) — FIXED.** The ids
|
|
296
|
+
were right all along (lift 0x06000018–1B, gain 0x0600001D–20, gamma 0x06000022–25, offset
|
|
297
|
+
0x0600007D–7F); Resolve's own `SetCDL` writes the same ids plus Lum Mix 0 (fixture
|
|
298
|
+
`r21-setcdl-slope-body.hex`). Under Resolve's default Lum Mix (UI 100, stored 1.0, written as
|
|
299
|
+
"absent") the lift/gamma/gain R/G/B channels preserve luminance, so the earlier "gain 1.6 shows
|
|
300
|
+
in the panel but does not render" was gain R=G=B: equal channel moves cancel on luma. Grey-128
|
|
301
|
+
band, ProRes render, mean R/G/B:
|
|
302
|
+
|
|
303
|
+
| written | Lum Mix | render |
|
|
304
|
+
|---|---|---|
|
|
305
|
+
| none | — | 127.59 |
|
|
306
|
+
| gain R=G=B 1.6 | unset (100) | 127.59 |
|
|
307
|
+
| gain R=G=B 1.6 | 50 | 165.86 |
|
|
308
|
+
| gain R=G=B 1.6 | 0 | 204.14 |
|
|
309
|
+
| gain master 1.6 | unset | 204.14 |
|
|
310
|
+
| gain 1.6/1.0/0.7 | unset | 190.54/114.08/76.04 (luma 127.59) |
|
|
311
|
+
| gain 1.6/1.0/0.7 | 0 (= Resolve SetCDL) | 204.16/127.71/89.67 |
|
|
312
|
+
| lift 0.1/0/−0.05 (stored) | unset / 0 | 137.86/125.39/119.17 / 140.18/127.70/121.49 |
|
|
313
|
+
| gamma 0.1/0/−0.05 (stored) | unset / 0 | 134.28/126.18/121.80 / 135.74/127.63/123.25 |
|
|
314
|
+
| offset 0.05/0/−0.05 (stored) | unset / 0 | 129.67/127.61/125.25 (both) |
|
|
315
|
+
| lift master 0.1 / gamma master 0.1 | unset | 140.35 / 135.71 |
|
|
316
|
+
|
|
317
|
+
Lum Mix is linear in its effect and the masters and offset ignore it. The varint 0x8600009B
|
|
318
|
+
`{F2:2}` that SetCDL also writes changed nothing when dropped. Generator: a caller sets `lumMixSlider` (UI 0–100 in `space:'ui'`,
|
|
319
|
+
stored 0–1 in `space:'drx'`; an explicit 0 is now written, the old guard dropped it) to get per-channel
|
|
320
|
+
R/G/B moves. This is opt-in: making Lum Mix 0 the default for every R/G/B move, and moving
|
|
321
|
+
`shadowLift`, `highlightCompression` and the simple-mode contrast node onto the masters, was
|
|
322
|
+
held back because it changes every existing caller's render and was measured only on Studio 21.0.4.5.
|
|
323
|
+
Proof with `drx generate` output that sets `lumMixSlider: 0`: gain R=G=B 1.6 → 204.14,
|
|
324
|
+
gain 1.6/1.0/0.7 → 204.16/127.71/89.67 (identical to SetCDL), lift/gamma/offset R/G/B equal the
|
|
325
|
+
Lum Mix 0 rows above, and keyframed gain R=G=B 1.0→1.6 over frames 0→28 (gradeMode 2) ramped
|
|
326
|
+
127.59 → 165.86 (f14) → 204.14 (f28). Not done: a hand-typed R/G/B gain in the panel (screen
|
|
327
|
+
control was blocked by a Windows overlay), so what Lum Mix the panel itself pairs with typed
|
|
328
|
+
R/G/B values is unmeasured. Tests: `test/primary-wheels-lum-mix.test.mjs`. Evidence:
|
|
329
|
+
`D:/Temp/resolve-gain-20261019/`.
|
|
330
|
+
- **Variable-speed ramps, Studio 21 form — WRITE built** (`buildRampTimemapR21` +
|
|
331
|
+
`project_db set_speed_ramp`). 21 writes protobuf KeyframesBA points (YMin/YMax -1); a ramp made
|
|
332
|
+
on the retime bar changes only `Sm2TiItem.MediaTimemapBA` and `Duration`. A written
|
|
333
|
+
100 %→25 %→200 % map rendered 240/240 frames on the predicted source frame, floor(fps×S(t));
|
|
334
|
+
Resolve's own hand ramp follows the same rule (538/538). The builder reproduces the hand ramp
|
|
335
|
+
byte-for-byte. Eased (curved) ramps: still not captured — the Inspector "Ease" options stay
|
|
336
|
+
disabled for a speed point and changing them wrote nothing.
|
|
337
|
+
- **Magic Mask 2 — the click is stored, the mattes are not** (`magic-mask-author.js`). Corrector
|
|
338
|
+
type 2 holds the subject click: source frame×2, stroke id 2048, op 6, and x/y centred y-up
|
|
339
|
+
image fractions (x = u−0.5, y = 0.5−v). The tracked per-frame mattes are not in the body or
|
|
340
|
+
Project.db. An authored click (moved to another clip's frame 10, x 0.15, y 0.05) applied with
|
|
341
|
+
ApplyGradeFromDRX, then `CreateMagicMask("BI")` with no clicks, tracked all 50 frames; a
|
|
342
|
+
Saturation-0 Primary in the same node took subject saturation 170 → 4.6 while the background
|
|
343
|
+
stayed 164.6. `RegenerateMagicMask()` returned False on that fresh apply.
|
|
344
|
+
|
|
283
345
|
## Remaining gaps (follow-ups)
|
|
284
346
|
- **Color Warper write on R21**: the built pin-list path matches the R21 fixture exactly
|
|
285
347
|
but Resolve 19.1.3 ignores it. CONFIRMED version split 2026-07-02: the original
|
|
@@ -348,7 +348,10 @@ const PARAMETER_RANGES = {
|
|
|
348
348
|
},
|
|
349
349
|
|
|
350
350
|
lumMixSlider: {
|
|
351
|
-
|
|
351
|
+
// UI 0–100 → stored /100. Resolve's default is UI 100 (stored 1.0), under which R/G/B wheel
|
|
352
|
+
// moves are luminance-preserving; 0 makes them plain per-channel multipliers (render-measured
|
|
353
|
+
// on Studio 21.0.4.5, 2026-10-19).
|
|
354
|
+
master: { min: 0.0, max: 1.0, default: 1.0, precision: 3 },
|
|
352
355
|
},
|
|
353
356
|
|
|
354
357
|
// ========================================================================
|
package/src/granular/common.py
CHANGED
|
@@ -93,7 +93,7 @@ if not logging.getLogger().handlers:
|
|
|
93
93
|
handlers=[logging.StreamHandler()],
|
|
94
94
|
)
|
|
95
95
|
|
|
96
|
-
VERSION = "4.
|
|
96
|
+
VERSION = "4.19.0"
|
|
97
97
|
logger = logging.getLogger("davinci-resolve-mcp")
|
|
98
98
|
logger.info(f"Starting DaVinci Resolve MCP Server v{VERSION}")
|
|
99
99
|
logger.info(f"Detected platform: {get_platform()}")
|