conformtools 0.6.5 → 0.6.7

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.
Files changed (149) hide show
  1. package/README.md +18 -13
  2. package/dist/account-DJTD3KYK.js +3 -0
  3. package/dist/arriraw-YIJ3BYNN.js +525 -0
  4. package/dist/avid-panel/MANIFEST.json +11 -0
  5. package/dist/avid-panel/avid-manifest.json +46 -0
  6. package/dist/avid-panel/icon.svg +4 -0
  7. package/dist/avid-panel/icons/conformtools.svg +4 -0
  8. package/dist/avid-panel/index.html +26 -0
  9. package/dist/avid-panel/panel.css +12 -0
  10. package/dist/avid-panel/panel.js +7 -0
  11. package/dist/bridge-JQF4V3V2.js +3 -0
  12. package/dist/browser/timeline_core_bg.wasm +0 -0
  13. package/dist/chunk-2BPR6LK6.js +3 -0
  14. package/dist/chunk-3D3Z4TBR.js +3 -0
  15. package/dist/chunk-55BKURYP.js +378 -0
  16. package/dist/chunk-5WEZRGXG.js +39 -0
  17. package/dist/chunk-6V4OEOOX.js +3 -0
  18. package/dist/chunk-7D7H6VFW.js +3 -0
  19. package/dist/chunk-A7FNR3T5.js +3 -0
  20. package/dist/chunk-AACY2V3L.js +3 -0
  21. package/dist/chunk-AMRJXYL4.js +3 -0
  22. package/dist/chunk-C2ESM27Z.js +3 -0
  23. package/dist/chunk-D4WPRRBT.js +3 -0
  24. package/dist/chunk-D6YDLKSA.js +3 -0
  25. package/dist/chunk-DKGGJM6Z.js +3 -0
  26. package/dist/chunk-EUBXH67N.js +7 -0
  27. package/dist/chunk-GK4YYKJ6.js +19 -0
  28. package/dist/chunk-GM6QKY7W.js +3 -0
  29. package/dist/chunk-J2JXLEAI.js +3 -0
  30. package/dist/chunk-JV7TZDKJ.js +3 -0
  31. package/dist/chunk-NAFLOZER.js +9 -0
  32. package/dist/chunk-NFJHWZJX.js +3 -0
  33. package/dist/chunk-NU3X7P4N.js +3 -0
  34. package/dist/chunk-P2LL3JMC.js +20 -0
  35. package/dist/chunk-PFISREY4.js +3 -0
  36. package/dist/chunk-PFZVET7S.js +3 -0
  37. package/dist/chunk-PHAMF4JF.js +4 -0
  38. package/dist/chunk-PLRB2YXJ.js +3 -0
  39. package/dist/chunk-PSANHDZM.js +3 -0
  40. package/dist/chunk-RGMTLNMF.js +3 -0
  41. package/dist/chunk-RJ6JA2LZ.js +3 -0
  42. package/dist/chunk-S5JDS5PQ.js +5 -0
  43. package/dist/chunk-SGLQY53R.js +3 -0
  44. package/dist/chunk-SKFMOLUO.js +8 -0
  45. package/dist/chunk-SNTAZJ5A.js +6 -0
  46. package/dist/chunk-TK55FA56.js +3 -0
  47. package/dist/chunk-TXQR2HI2.js +4 -0
  48. package/dist/chunk-VIBEEWPC.js +10 -0
  49. package/dist/chunk-WN53ARHJ.js +3 -0
  50. package/dist/chunk-XLEINKFL.js +5 -0
  51. package/dist/claude-setup-IIWUB4CE.js +5 -0
  52. package/dist/cli.js +17 -0
  53. package/dist/clip-state-B6JOX3JE.js +3 -0
  54. package/dist/conformtools-analyze +0 -0
  55. package/dist/conformtools-decode +0 -0
  56. package/dist/cr3-wasm-HLJWEV2S.js +3 -0
  57. package/dist/dng-wasm-CQDLPM5V.js +3 -0
  58. package/dist/dpx-wasm-TLGMM7BO.js +3 -0
  59. package/dist/engine-P6H5P6HP.js +5 -0
  60. package/dist/esm-SFFBP7PS.js +3 -0
  61. package/dist/exr-wasm-2NPKPTVB.js +3 -0
  62. package/dist/flame/hook/conformtools_flame/__init__.py +10 -0
  63. package/dist/flame/hook/conformtools_flame/building.py +191 -0
  64. package/dist/flame/hook/conformtools_flame/hook.py +177 -0
  65. package/dist/flame/hook/conformtools_flame/render.py +622 -0
  66. package/dist/flame/hook/conformtools_flame/util.py +33 -0
  67. package/dist/flame/hook/conformtools_flame/verbs.py +1037 -0
  68. package/dist/flame/hook/conformtools_flame_hook.py +42 -0
  69. package/dist/fonts/gfx/BarlowCondensed-Bold.ttf +0 -0
  70. package/dist/fonts/gfx/BarlowCondensed-Regular.ttf +0 -0
  71. package/dist/fonts/gfx/InstrumentSerif-Regular.ttf +0 -0
  72. package/dist/fonts/gfx/Inter-Bold.ttf +0 -0
  73. package/dist/fonts/gfx/Inter-Regular.ttf +0 -0
  74. package/dist/fonts/gfx/JetBrainsMono-Bold.ttf +0 -0
  75. package/dist/fonts/gfx/JetBrainsMono-Regular.ttf +0 -0
  76. package/dist/fonts/gfx/OFL.txt +100 -0
  77. package/dist/framing-SWOD4CWB.js +3 -0
  78. package/dist/gfx-worker.js +3 -0
  79. package/dist/h264-JJMZSUWW.js +3 -0
  80. package/dist/h264-mxf-DCUOGLDU.js +3 -0
  81. package/dist/host-relink-TWAF6WIG.js +10 -0
  82. package/dist/hosts-Z666EF7V.js +3 -0
  83. package/dist/http.js +5 -0
  84. package/dist/i2o-transfer +0 -0
  85. package/dist/inspect-FJKYPEXL.js +68 -0
  86. package/dist/isobmff-VJOWP4MH.js +3 -0
  87. package/dist/mc-video-5MGGOQN4.js +3 -0
  88. package/dist/mcp.js +13 -0
  89. package/dist/media-NZYVREUF.js +3 -0
  90. package/dist/media_core-YZ3PABEG.js +9 -0
  91. package/dist/media_core_bg-FDL7GJZP.js +3 -0
  92. package/dist/media_core_bg-XRBVKQZH.js +3 -0
  93. package/dist/mxf-FJSRFLJC.js +3 -0
  94. package/dist/nuke/panel/python/Startup/conformtools_nuke_startup.py +44 -0
  95. package/dist/nuke/panel/python/conformtools_nuke/__init__.py +10 -0
  96. package/dist/nuke/panel/python/conformtools_nuke/panel.py +217 -0
  97. package/dist/nuke/panel/python/conformtools_nuke/verbs.py +837 -0
  98. package/dist/ops-X7NAREC4.js +3 -0
  99. package/dist/peer-kit/ctpeer/__init__.py +21 -0
  100. package/dist/peer-kit/ctpeer/client.py +247 -0
  101. package/dist/peer-kit/ctpeer/neutral.py +178 -0
  102. package/dist/peer-kit/ctpeer/pairing.py +139 -0
  103. package/dist/peer-kit/ctpeer/protocol.py +209 -0
  104. package/dist/peer-kit/ctpeer/websocket.py +289 -0
  105. package/dist/premiere-uxp/icons/panel.png +0 -0
  106. package/dist/premiere-uxp/icons/panel@2x.png +0 -0
  107. package/dist/premiere-uxp/icons/plugin.png +0 -0
  108. package/dist/premiere-uxp/icons/plugin@2x.png +0 -0
  109. package/dist/premiere-uxp/index.html +38 -0
  110. package/dist/premiere-uxp/index.js +93 -0
  111. package/dist/premiere-uxp/lib/clipmeta.js +170 -0
  112. package/dist/premiere-uxp/lib/ctx.js +68 -0
  113. package/dist/premiere-uxp/lib/edit.js +516 -0
  114. package/dist/premiere-uxp/lib/handles.js +57 -0
  115. package/dist/premiere-uxp/lib/markers.js +198 -0
  116. package/dist/premiere-uxp/lib/pairing.js +67 -0
  117. package/dist/premiere-uxp/lib/premiere.js +91 -0
  118. package/dist/premiere-uxp/lib/probe.js +452 -0
  119. package/dist/premiere-uxp/lib/protocol.js +165 -0
  120. package/dist/premiere-uxp/lib/render.js +45 -0
  121. package/dist/premiere-uxp/lib/session.js +85 -0
  122. package/dist/premiere-uxp/lib/sizing.js +325 -0
  123. package/dist/premiere-uxp/lib/time.js +88 -0
  124. package/dist/premiere-uxp/lib/timeline.js +336 -0
  125. package/dist/premiere-uxp/lib/verbs.js +21 -0
  126. package/dist/premiere-uxp/lib/write.js +97 -0
  127. package/dist/premiere-uxp/manifest.json +102 -0
  128. package/dist/probe-F7WQHMIA.js +3 -0
  129. package/dist/prores-RIG37OIH.js +526 -0
  130. package/dist/r3d-CXUNG6VS.js +1025 -0
  131. package/dist/r3d-T5O6IIZZ.js +3 -0
  132. package/dist/resolve-bridge.py +2286 -0
  133. package/dist/resolve-presets/conform.tools.xml +127 -0
  134. package/dist/source-QGWWLMME.js +3 -0
  135. package/dist/statusline-GMMCFMOA.js +4 -0
  136. package/dist/statusline.js +3 -0
  137. package/dist/still-P4JJNTEO.js +3 -0
  138. package/dist/still-wasm-DN5LPASS.js +3 -0
  139. package/dist/store-7IOEBOZY.js +3 -0
  140. package/dist/tiff-wasm-BPRDR6EB.js +3 -0
  141. package/dist/timeline-DQG6TVPF.js +3 -0
  142. package/dist/timeline_core-IOENXK4Z.js +3 -0
  143. package/dist/timeline_core_bg-JW42YM3G.js +3 -0
  144. package/dist/udf_bg-B37GKRIH.js +3 -0
  145. package/dist/wasm/media_core_bg.wasm +0 -0
  146. package/dist/wasm/udf_bg.wasm +0 -0
  147. package/dist/wasm-threads/media_core_bg.wasm +0 -0
  148. package/dist/wav-64SC6P7U.js +3 -0
  149. package/package.json +6 -4
@@ -0,0 +1,2286 @@
1
+ #!/usr/bin/env python3
2
+ """The engine's door into a running DaVinci Resolve (mcp/hosts/resolve/adapter.ts).
3
+
4
+ python3 bridge.py <action> '<json args>' -> one JSON line on stdout
5
+
6
+ Resolve's scripting API exists only for Python and Lua, so this file is the one place the engine
7
+ speaks it. It is glue, not know-how: every decision (what to import, what to render, what the
8
+ findings mean) is made in TypeScript; this file performs one host action and reports exactly what
9
+ Resolve said. One process per action: connecting costs ~0.1 s, and a crashed call can never wedge
10
+ the next one.
11
+
12
+ Safety, kept by every action (see mcp/hosts/contract.ts):
13
+ - read-only unless the action's name says otherwise
14
+ - the user's project, page and Deliver settings are restored after we touch them
15
+ - only our render job is ever started (StartRendering([job])), never the user's queue
16
+ Python 3.6+ (what Resolve supports); standard library only.
17
+ """
18
+ import json
19
+ import os
20
+ import re
21
+ import shutil
22
+ import struct
23
+ import sys
24
+ import tempfile
25
+ import time
26
+ import uuid
27
+
28
+ OK = 0
29
+ FAIL = 1
30
+
31
+
32
+ def reply(obj, code=OK):
33
+ sys.stdout.write(json.dumps(obj) + "\n")
34
+ sys.stdout.flush()
35
+ sys.exit(code)
36
+
37
+
38
+ def fail(why, detail="", **extra):
39
+ out = {"ok": False, "why": why, "detail": detail}
40
+ out.update(extra)
41
+ reply(out, FAIL)
42
+
43
+
44
+ # ── connection ────────────────────────────────────────────────────────────
45
+
46
+ def connect():
47
+ """The Resolve object, or a reply naming exactly what is missing."""
48
+ try:
49
+ import DaVinciResolveScript as dvr # noqa: N813 (Resolve's own module name)
50
+ except Exception as e: # module not installed / paths not set
51
+ fail("module", "the Resolve scripting module could not be imported: %s" % e)
52
+ resolve = dvr.scriptapp("Resolve")
53
+ if not resolve:
54
+ fail(
55
+ "no_connection",
56
+ "Resolve is not running, or refused the connection. Start Resolve, and set "
57
+ "Preferences > System > General > External scripting using: Local (Studio only).",
58
+ )
59
+ return resolve
60
+
61
+
62
+ def project_or_fail(resolve):
63
+ pm = resolve.GetProjectManager()
64
+ p = pm.GetCurrentProject()
65
+ if not p:
66
+ fail("no_project", "no project is open in Resolve (only the Project Manager)")
67
+ return pm, p
68
+
69
+
70
+ def timelines(project):
71
+ return [project.GetTimelineByIndex(i + 1) for i in range(int(project.GetTimelineCount() or 0))]
72
+
73
+
74
+ def find_timeline(project, name):
75
+ if not name:
76
+ t = project.GetCurrentTimeline()
77
+ if not t:
78
+ fail("no_timeline", "the project %r has no timeline open" % project.GetName())
79
+ return t
80
+ for t in timelines(project):
81
+ if t.GetName() == name:
82
+ return t
83
+ fail("not_found", "no timeline named %r in project %r" % (name, project.GetName()),
84
+ timelines=[t.GetName() for t in timelines(project)])
85
+
86
+
87
+ # ── actions ───────────────────────────────────────────────────────────────
88
+
89
+ def a_version(resolve, _args):
90
+ """Product, version and what the API offers on this install."""
91
+ pm = resolve.GetProjectManager()
92
+ p = pm.GetCurrentProject()
93
+ return {
94
+ "ok": True,
95
+ "product": resolve.GetProductName(),
96
+ "version": resolve.GetVersionString(),
97
+ "project": p.GetName() if p else None,
98
+ "page": resolve.GetCurrentPage(),
99
+ "db": pm.GetCurrentDatabase() or {},
100
+ }
101
+
102
+
103
+ def a_current(resolve, _args):
104
+ """What is open: project, its timelines, the timeline in the viewer, the database."""
105
+ pm, p = project_or_fail(resolve)
106
+ t = p.GetCurrentTimeline()
107
+ return {
108
+ "ok": True,
109
+ "product": resolve.GetProductName(),
110
+ "version": resolve.GetVersionString(),
111
+ "project": p.GetName(),
112
+ "timelines": [x.GetName() for x in timelines(p)],
113
+ "timeline": t.GetName() if t else None,
114
+ "tracks": tracks_of(t) if t else [],
115
+ "page": resolve.GetCurrentPage(),
116
+ "db": pm.GetCurrentDatabase() or {},
117
+ }
118
+
119
+
120
+ def tracks_of(t):
121
+ """Every track of a timeline: kind, 1-based index, name, enabled, locked."""
122
+ out = []
123
+ for kind in ("video", "audio", "subtitle"):
124
+ for i in range(1, int(t.GetTrackCount(kind) or 0) + 1):
125
+ out.append({"kind": kind, "index": i, "name": t.GetTrackName(kind, i),
126
+ "enabled": bool(t.GetIsTrackEnabled(kind, i)), "locked": bool(t.GetIsTrackLocked(kind, i))})
127
+ return out
128
+
129
+
130
+ def pool_folder(media_pool, path, create=False):
131
+ """The media pool folder at "A/B/C" under the root ("" = the root). Missing folders are created
132
+ only when `create`; otherwise (None, the first missing name)."""
133
+ f = media_pool.GetRootFolder()
134
+ for seg in [x for x in (path or "").split("/") if x]:
135
+ nxt = next((x for x in f.GetSubFolderList() or [] if x.GetName() == seg), None)
136
+ if not nxt and create:
137
+ nxt = media_pool.AddSubFolder(f, seg)
138
+ if not nxt:
139
+ return None, seg
140
+ f = nxt
141
+ return f, None
142
+
143
+
144
+ def a_project(resolve, args):
145
+ """Read-only project awareness: the media pool tree (folders, clip counts, optionally every clip
146
+ with its file), which pool clips match `find` (a path, or a name fragment), the render queue
147
+ with every job's settings as Resolve reports them, and the tracks of a timeline. `into: scratch` reads
148
+ our scratch project (live tests)."""
149
+ return _in_scratch(resolve, args, lambda p: _project(resolve, p, args))
150
+
151
+
152
+ def _project(resolve, p, args):
153
+ mp = p.GetMediaPool()
154
+ want_clips = bool(args.get("clips"))
155
+ finds = [str(q) for q in args.get("find") or []]
156
+ found = dict((q, []) for q in finds)
157
+
158
+ # ponytail: GetClipProperty per clip walks the whole pool; fine for thousands, page it if it ever is not
159
+ def walk(folder, path):
160
+ clips = folder.GetClipList() or []
161
+ node = {"path": path, "clips": len(clips), "folders": []}
162
+ if want_clips or finds:
163
+ rows = []
164
+ for c in clips:
165
+ pr = c.GetClipProperty() or {}
166
+ row = {"id": c.GetUniqueId(), "name": c.GetName(), "file": pr.get("File Path") or "", "start_tc": pr.get("Start TC") or "",
167
+ "usage": pr.get("Usage") or "", "folder": path, "type": pr.get("Type") or ""}
168
+ rows.append(row)
169
+ for q in finds:
170
+ if ("/" in q and row["file"] and os.path.normpath(row["file"]) == os.path.normpath(q)) or (
171
+ "/" not in q and (q.lower() in row["name"].lower()
172
+ or q.lower() in os.path.basename(row["file"]).lower())):
173
+ found[q].append(row)
174
+ if want_clips:
175
+ node["clip_list"] = rows
176
+ for sub in folder.GetSubFolderList() or []:
177
+ node["folders"].append(walk(sub, (path + "/" if path else "") + sub.GetName()))
178
+ return node
179
+
180
+ jobs = []
181
+ for j in p.GetRenderJobList() or []:
182
+ j = dict(j)
183
+ st = p.GetRenderJobStatus(j.get("JobId")) or {}
184
+ j["JobStatus"] = st.get("JobStatus", "")
185
+ j["CompletionPercentage"] = st.get("CompletionPercentage")
186
+ jobs.append(j)
187
+ t = find_timeline(p, args.get("timeline")) if (args.get("timeline") or p.GetCurrentTimeline()) else None
188
+ return {"ok": True, "project": p.GetName(), "pool": walk(mp.GetRootFolder(), ""), "found": found,
189
+ "jobs": jobs, "timeline": t.GetName() if t else None, "tracks": tracks_of(t) if t else [],
190
+ "timelines": [x.GetName() for x in timelines(p)], "page": resolve.GetCurrentPage()}
191
+
192
+
193
+ def a_export(resolve, args):
194
+ """A timeline → Resolve's own .drt (read-only on the project). The user's current timeline
195
+ is left (or put back) as it was.
196
+
197
+ Resolve's Export is fussy about the target path (spaces / non-ASCII / a folder instead of a
198
+ file all come back as a bare False), so it always writes to a plain ASCII temp file that we
199
+ then move to out_path. Some builds also refuse a timeline that is not the current one: on a
200
+ False we retry once with it made current, then restore the user's timeline.
201
+ `into: scratch` reads our scratch project (live tests)."""
202
+ return _in_scratch(resolve, args, lambda p: _export(resolve, p, args))
203
+
204
+
205
+ def _export(resolve, p, args):
206
+ if args.get("clip_id"):
207
+ return _export_clip(resolve, p, args)
208
+ t = find_timeline(p, args.get("timeline"))
209
+ out = args["out_path"]
210
+ if os.path.isdir(out) or not os.path.splitext(out)[1]:
211
+ out = os.path.join(out, safe_name(t.GetName()) + ".drt")
212
+ parent = os.path.dirname(os.path.abspath(out))
213
+ if not os.path.isdir(parent):
214
+ os.makedirs(parent)
215
+ tmp_dir = tempfile.mkdtemp(prefix="conform_export_")
216
+ tmp = os.path.join(tmp_dir, "timeline.drt")
217
+
218
+ def wrote():
219
+ return os.path.isfile(tmp) and os.path.getsize(tmp) > 0
220
+
221
+ try:
222
+ ok = bool(t.Export(tmp, resolve.EXPORT_DRT))
223
+ prev = p.GetCurrentTimeline()
224
+ if not wrote() and (not prev or prev.GetName() != t.GetName()):
225
+ p.SetCurrentTimeline(t)
226
+ try:
227
+ ok = bool(t.Export(tmp, resolve.EXPORT_DRT))
228
+ finally:
229
+ if prev:
230
+ p.SetCurrentTimeline(prev)
231
+ # Export returns True for some failures and writes a bundle for others: trust the file.
232
+ if not wrote():
233
+ fail("export_failed", "Resolve did not write the .drt for %r (Export returned %s)" % (t.GetName(), ok))
234
+ if os.path.exists(out):
235
+ os.remove(out)
236
+ shutil.move(tmp, out)
237
+ finally:
238
+ shutil.rmtree(tmp_dir, ignore_errors=True)
239
+ return {"ok": True, "path": out, "format": "drt", "project": p.GetName(), "timeline": t.GetName(), "start_frame": int(t.GetStartFrame())}
240
+
241
+
242
+ def _pool_clip(p, uid):
243
+ def walk(f):
244
+ for c in f.GetClipList() or []:
245
+ if c.GetUniqueId() == uid:
246
+ return c
247
+ for sub in f.GetSubFolderList() or []:
248
+ hit = walk(sub)
249
+ if hit:
250
+ return hit
251
+ return None
252
+ return walk(p.GetMediaPool().GetRootFolder())
253
+
254
+
255
+ def _export_clip(resolve, p, args):
256
+ """A media pool clip that is not a timeline (a compound clip) as a .drt: Resolve exports timelines only, so the clip
257
+ goes on a temporary timeline of its own (its contents ride along, nested), that is exported and deleted again;
258
+ the user's current timeline is put back."""
259
+ clip = _pool_clip(p, args["clip_id"])
260
+ if not clip:
261
+ fail("not_found", "no media pool clip %r" % args["clip_id"])
262
+ mp, prev = p.GetMediaPool(), p.GetCurrentTimeline()
263
+ tmp_tl = mp.CreateTimelineFromClips(unique_name(p, "conform.tools offline ref"), [clip])
264
+ if not tmp_tl:
265
+ fail("export_failed", "Resolve could not make a timeline from %r" % clip.GetName())
266
+ try:
267
+ return a_export(resolve, dict(args, clip_id=None, timeline=tmp_tl.GetName()))
268
+ finally:
269
+ mp.DeleteTimelines([tmp_tl])
270
+ if prev:
271
+ p.SetCurrentTimeline(prev)
272
+
273
+
274
+ def a_clip_lut(resolve, args):
275
+ """The grade of the video clip at (track, start: record frames from the timeline start) as Resolve's own 3D LUT
276
+ (TimelineItem.ExportLUT, 33-point .cube): its colour function through every node, for the app's viewer to paint
277
+ the clip as Resolve shows it. Spatial tools (blur, windows, NR) are not in a LUT."""
278
+ _pm, p = project_or_fail(resolve)
279
+ t = find_timeline(p, args.get("timeline"))
280
+ t0 = int(t.GetStartFrame())
281
+ track, start = int(args["track"]), int(args["start"])
282
+ it = next((i for i in t.GetItemListInTrack("video", track) or [] if int(i.GetStart()) - t0 == start), None)
283
+ if not it:
284
+ fail("not_found", "no video clip on V%d at frame %d" % (track, start))
285
+ out = args["out_path"]
286
+ if os.path.exists(out):
287
+ os.remove(out)
288
+ if not it.ExportLUT(resolve.EXPORT_LUT_33PTCUBE, out) or not os.path.isfile(out):
289
+ fail("export_failed", "Resolve did not export the grade of %r" % it.GetName())
290
+ return {"ok": True, "path": out, "name": it.GetName()}
291
+
292
+
293
+ def safe_name(name):
294
+ """A timeline name as a file name: anything but [A-Za-z0-9._-] becomes _."""
295
+ return re.sub(r"[^A-Za-z0-9._-]+", "_", name).strip("_") or "timeline"
296
+
297
+
298
+ OUR_FOLDER = "conform.tools"
299
+
300
+
301
+ def unique_name(project, wanted):
302
+ taken = set(t.GetName() for t in timelines(project))
303
+ if wanted not in taken:
304
+ return wanted
305
+ n = 2
306
+ while "%s (%d)" % (wanted, n) in taken:
307
+ n += 1
308
+ return "%s (%d)" % (wanted, n)
309
+
310
+
311
+ def our_folder(media_pool):
312
+ """The media pool folder our imports land in, created under the root if missing."""
313
+ root = media_pool.GetRootFolder()
314
+ for f in root.GetSubFolderList() or []:
315
+ if f.GetName() == OUR_FOLDER:
316
+ return f
317
+ return media_pool.AddSubFolder(root, OUR_FOLDER)
318
+
319
+
320
+ def named_media(path):
321
+ """The media files a timeline file names (DRT MediaFilePath, FCP/FCPX file:// URLs); [] for
322
+ formats that name none (EDL, AAF)."""
323
+ import unicodedata, zipfile
324
+ from urllib.parse import unquote
325
+ try:
326
+ if zipfile.is_zipfile(path):
327
+ with zipfile.ZipFile(path) as z:
328
+ text = "\n".join(z.read(n).decode("utf-8", "replace") for n in z.namelist() if n.endswith(".xml"))
329
+ else:
330
+ with open(path, encoding="utf-8", errors="replace") as f:
331
+ text = f.read()
332
+ except OSError:
333
+ return []
334
+ found = re.findall(r"<MediaFilePath>([^<]+)</MediaFilePath>", text)
335
+ found += [url_path(u) for u in re.findall(r"file://(?:localhost)?(/[^<\"]+)", text)]
336
+ return sorted({unicodedata.normalize("NFC", m.replace("&amp;", "&")) for m in found})
337
+
338
+
339
+ def url_path(u):
340
+ """A file URL's path as this OS writes it: file:///C:/Media/a.mov is C:\\Media\\a.mov on Windows (not /C:/…, which
341
+ names nothing there, so the named file was never imported first and Resolve linked another job's clip)."""
342
+ from urllib.parse import unquote
343
+ p = unquote(u)
344
+ if re.match(r"^/[A-Za-z]:[/\\]", p):
345
+ p = p[1:]
346
+ return os.path.normpath(p) if os.name == "nt" else p
347
+
348
+
349
+ def same_file_key(p):
350
+ """How two paths compare as the same file: Windows paths by normalised case and separators."""
351
+ import unicodedata
352
+ p = unicodedata.normalize("NFC", p)
353
+ return os.path.normcase(os.path.normpath(p)) if os.name == "nt" else p
354
+
355
+
356
+ def pool_ids(folder):
357
+ ids = {c.GetMediaId() for c in folder.GetClipList() or []}
358
+ for sub in folder.GetSubFolderList() or []:
359
+ ids |= pool_ids(sub)
360
+ return ids
361
+
362
+
363
+ def mislinked(tl, named, before):
364
+ """Items linked to a clip that was in the pool BEFORE the import and is a file the timeline file
365
+ does not name: [(clip, frame, linked path)]. Clips the import made are its own (any path form)."""
366
+ import unicodedata
367
+ want, out = {same_file_key(m) for m in named}, []
368
+ for ti in range(1, (tl.GetTrackCount("video") or 0) + 1):
369
+ for it in tl.GetItemListInTrack("video", ti) or []:
370
+ m = it.GetMediaPoolItem()
371
+ if not m or m.GetMediaId() not in before:
372
+ continue
373
+ got = unicodedata.normalize("NFC", m.GetClipProperty("File Path") or "")
374
+ if got and same_file_key(got) not in want:
375
+ out.append((it.GetName(), it.GetStart(), got))
376
+ return out
377
+
378
+
379
+ def a_open(resolve, args):
380
+ """A timeline file -> a NEW timeline in the open project (never overwrites), inside the
381
+ conform.tools media pool folder, or `folder` ("000 - TIMELINES/20261006"; missing folders are
382
+ created only with `create_folder`). `link_existing` imports with importSourceClips False: the
383
+ timeline links to clips already in the pool, no duplicates. Otherwise the media the file names is
384
+ imported first and the result checked: an item Resolve linked to some other pool clip fails the
385
+ open (`import_mislinked`), the timeline deleted. The user's timeline, folder and page
386
+ are restored unless `stay`. `into: scratch` switches to (or creates) our scratch project instead,
387
+ saving the user's project first so nothing of theirs is lost, and switches back afterwards."""
388
+ pm, p = project_or_fail(resolve)
389
+ path = args["path"]
390
+ if not os.path.isfile(path):
391
+ fail("not_found", "no file at %s" % path)
392
+ page = resolve.GetCurrentPage()
393
+ prev_project = p.GetName()
394
+ if args.get("into") == "scratch":
395
+ scratch = args.get("scratch_project") or "conform.tools scratch"
396
+ if prev_project != scratch:
397
+ pm.SaveProject()
398
+ if not pm.LoadProject(scratch):
399
+ if not pm.CreateProject(scratch):
400
+ fail("scratch_failed", "could not open or create the project %r" % scratch)
401
+ p = pm.GetCurrentProject()
402
+ prev_tl = p.GetCurrentTimeline()
403
+ mp = p.GetMediaPool()
404
+ prev_folder = mp.GetCurrentFolder()
405
+
406
+ def restore():
407
+ if prev_folder:
408
+ mp.SetCurrentFolder(prev_folder)
409
+ if prev_tl:
410
+ p.SetCurrentTimeline(prev_tl)
411
+ if args.get("into") == "scratch" and prev_project != p.GetName():
412
+ pm.SaveProject()
413
+ pm.LoadProject(prev_project)
414
+ if resolve.GetCurrentPage() != page:
415
+ resolve.OpenPage(page)
416
+ return True
417
+
418
+ if args.get("folder"):
419
+ folder, missing = pool_folder(mp, args["folder"], bool(args.get("create_folder")))
420
+ if not folder:
421
+ restore()
422
+ fail("no_folder", "no media pool folder %r in %r (pass create_folder to create it)" % (missing, args["folder"]))
423
+ folder_name = args["folder"]
424
+ else:
425
+ folder, folder_name = our_folder(mp), OUR_FOLDER
426
+ if folder:
427
+ mp.SetCurrentFolder(folder)
428
+ name = unique_name(p, args.get("name") or os.path.splitext(os.path.basename(path))[0])
429
+ link = bool(args.get("link_existing"))
430
+ opts = {"timelineName": name, "importSourceClips": not link}
431
+ if args.get("media_dir") and not link:
432
+ opts["sourceClipsPath"] = args["media_dir"]
433
+ named = [] if link else named_media(path)
434
+ # Resolve links a source clip to ANY pool clip its conform matcher accepts (same timecode, e.g.
435
+ # every drone clip at 00:00:00:00) before importing the file's own; with the exact file already
436
+ # in the pool it takes that one. So the named files go in first, and the result is checked.
437
+ before = pool_ids(mp.GetRootFolder()) if named else set()
438
+ on_disk = [m for m in named if os.path.isfile(m)]
439
+ if on_disk:
440
+ mp.ImportMedia(on_disk)
441
+ tl = mp.ImportTimelineFromFile(path, opts)
442
+ if not tl:
443
+ restored = restore()
444
+ fail("import_failed", "Resolve refused to import %s%s" % (path, "" if link else " (link_existing links to clips already in the pool by name)"), restored=restored)
445
+ wrong = mislinked(tl, named, before)
446
+ if wrong:
447
+ mp.DeleteTimelines([tl])
448
+ restored = restore()
449
+ fail("import_mislinked", "Resolve linked %d clip(s) to other files than %s names: %s" % (
450
+ len(wrong), os.path.basename(path), "; ".join("%s at frame %s -> %s" % w for w in wrong[:10])),
451
+ restored=restored, mislinked=[{"clip": c, "frame": f, "linked": l} for c, f, l in wrong])
452
+ if args.get("same_as"):
453
+ # a copy of a timeline (the Aligner's <name> ALIGNED): every clip must link to the SAME pool clip as the
454
+ # original's at that place — its remote grades live there — or the copy is deleted and refused
455
+ orig = find_timeline(p, args["same_as"])
456
+ def links(t):
457
+ t0 = int(t.GetStartFrame())
458
+ return {("%d:%d" % (k, int(it.GetStart()) - t0)): (it.GetMediaPoolItem().GetUniqueId() if it.GetMediaPoolItem() else None)
459
+ for k in range(1, int(t.GetTrackCount("video") or 0) + 1) for it in (t.GetItemListInTrack("video", k) or [])}
460
+ want, got_links = links(orig), links(tl)
461
+ off = sorted(set(want) ^ set(got_links)) + [k for k in want if k in got_links and want[k] != got_links[k]]
462
+ if off:
463
+ mp.DeleteTimelines([tl])
464
+ restored = restore()
465
+ fail("import_mislinked", "the copy did not link every clip to the original's pool clip (%d off: %s); deleted, nothing changed" % (
466
+ len(off), ", ".join(off[:10])), restored=restored)
467
+ notes = []
468
+ if tl.GetName() != name: # Resolve may name it after the file
469
+ tl.SetName(name)
470
+ got = tl.GetName()
471
+ restored = restore() if not args.get("stay") else False
472
+ if not opts.get("sourceClipsPath") and args.get("media_dir"):
473
+ notes.append("media_dir was not used" + (" (link_existing links to clips already in the pool)" if link else ""))
474
+ return {"ok": True, "project": p.GetName(), "timeline": got, "folder": folder_name if folder else None,
475
+ "linked_existing": link, "restored": restored, "notes": notes}
476
+
477
+
478
+ def tc_frames(tc, fps):
479
+ """"HH:MM:SS:FF" (";FF" drop-frame at 29.97/59.94) -> absolute frames; None when not a timecode."""
480
+ m = re.match(r"^(\d+)[:;.](\d+)[:;.](\d+)([:;.])(\d+)$", str(tc).strip())
481
+ if not m:
482
+ return None
483
+ h, mi, se, ff = int(m.group(1)), int(m.group(2)), int(m.group(3)), int(m.group(5))
484
+ r = int(round(float(fps)))
485
+ n = (h * 3600 + mi * 60 + se) * r + ff
486
+ if m.group(4) == ";" and r in (30, 60):
487
+ total = h * 60 + mi
488
+ n -= (2 if r == 30 else 4) * (total - total // 10)
489
+ return n
490
+
491
+
492
+ # ── render ────────────────────────────────────────────────────────────────
493
+ #
494
+ # Stateless across calls: render_start returns what to restore, the engine keeps it in its job
495
+ # record and hands it back to render_finish. Settings are restored right after AddRenderJob (a
496
+ # queued job keeps the settings it was added with), so the user's Deliver page is theirs again
497
+ # while our job renders; their timeline and page come back in render_finish.
498
+
499
+ KEEP_PREFIX = "__ct_keep_"
500
+
501
+
502
+ def find_job(project, job_id):
503
+ for j in project.GetRenderJobList() or []:
504
+ if j.get("JobId") == job_id:
505
+ return j
506
+ return None
507
+
508
+
509
+ def track_matches(t, ref):
510
+ """1-based video track indices named `ref` (case-insensitive, every track so named) or "V7"."""
511
+ r = str(ref).strip().lower()
512
+ return [i for i in range(1, int(t.GetTrackCount("video") or 0) + 1)
513
+ if (t.GetTrackName("video", i) or "").strip().lower() == r or "v%d" % i == r]
514
+
515
+
516
+ def video_tracks_named(t, refs):
517
+ """track_matches for every ref; any ref without a track refuses before anything is touched."""
518
+ out = []
519
+ for ref in refs:
520
+ hit = track_matches(t, ref)
521
+ if not hit:
522
+ fail("no_track", "no video track named %r on %r" % (ref, t.GetName()),
523
+ tracks=[{"index": i, "name": t.GetTrackName("video", i)}
524
+ for i in range(1, int(t.GetTrackCount("video") or 0) + 1)])
525
+ out += [i for i in hit if i not in out]
526
+ return sorted(out)
527
+
528
+
529
+ def set_video_tracks(resolve, t, indices, enabled):
530
+ """SetTrackEnable takes effect only on the Edit page (elsewhere it returns True and does
531
+ nothing; Resolve 21.1): switch to Edit, set, read every track back. Returns those that did not
532
+ take."""
533
+ if indices and resolve.GetCurrentPage() != "edit":
534
+ resolve.OpenPage("edit")
535
+ for i in indices:
536
+ t.SetTrackEnable("video", i, enabled)
537
+ return [i for i in indices if bool(t.GetIsTrackEnabled("video", i)) != enabled]
538
+
539
+
540
+ def a_render_start(resolve, args):
541
+ _pm, p = project_or_fail(resolve)
542
+ if p.IsRenderingInProgress():
543
+ fail("busy", "Resolve is already rendering; we never interrupt someone else's render")
544
+ target = args["target_dir"]
545
+ if not os.path.isdir(target):
546
+ os.makedirs(target)
547
+ page = resolve.GetCurrentPage()
548
+ if args.get("renderplugin") is not None or args.get("preset") or args.get("audio_tracks"):
549
+ _deliver_ready(resolve, p)
550
+ prev_tl = p.GetCurrentTimeline()
551
+ tl = find_timeline(p, args.get("timeline"))
552
+ if not prev_tl or prev_tl.GetName() != tl.GetName():
553
+ p.SetCurrentTimeline(tl)
554
+ # The documented RenderSettings have no per-job track selection ("Render All Video Tracks"):
555
+ # the named tracks are switched off for our job and back on when it ends (render_finish).
556
+ off = []
557
+ if args.get("disable_tracks"):
558
+ off = [i for i in video_tracks_named(tl, args["disable_tracks"]) if tl.GetIsTrackEnabled("video", i)]
559
+ bad = set_video_tracks(resolve, tl, off, False)
560
+ if bad:
561
+ set_video_tracks(resolve, tl, off, True)
562
+ resolve.OpenPage(page)
563
+ fail("tracks_not_disabled", "Resolve did not switch off video track(s) %s; nothing was queued" % bad)
564
+ if args.get("renderplugin") is not None or args.get("preset"):
565
+ resolve.OpenPage("deliver")
566
+ try:
567
+ return _queue_and_start(resolve, p, tl, args, target, page, prev_tl, off)
568
+ except BaseException:
569
+ if off:
570
+ set_video_tracks(resolve, tl, off, True)
571
+ resolve.OpenPage(page)
572
+ raise
573
+
574
+
575
+ def _queue_and_start(resolve, p, tl, args, target, page, prev_tl, off):
576
+ keep = "%s%d_%d" % (KEEP_PREFIX, os.getpid(), int(time.time() * 1000))
577
+ kept = bool(p.SaveAsNewRenderPreset(keep))
578
+ routed, rejected = None, []
579
+ if args.get("renderplugin") is not None:
580
+ args["preset"] = QC_PRESET
581
+ for f in QC_REPORTS: # a stale report from an earlier run is the classic wrong answer
582
+ if os.path.exists(os.path.join(target, f)):
583
+ os.remove(os.path.join(target, f))
584
+ _write_qc_config(target, args["renderplugin"])
585
+ try:
586
+ if args.get("preset"):
587
+ if args["preset"] not in (p.GetRenderPresetList() or []):
588
+ fail("no_preset", "no render preset named %r" % args["preset"], presets=p.GetRenderPresetList() or [])
589
+ p.LoadRenderPreset(args["preset"])
590
+ if args.get("audio_tracks"): # no API key for output routing: a preset carries it
591
+ routed = _routed_settings(resolve, p, args["audio_tracks"])
592
+ settings = {"TargetDir": target, "CustomName": args.get("name") or tl.GetName(),
593
+ "ExportVideo": True, "ExportAudio": bool(args.get("audio") or args.get("audio_tracks"))}
594
+ rng = args.get("range")
595
+ if rng:
596
+ settings.update({"SelectAllFrames": False, "MarkIn": int(rng["in"]), "MarkOut": int(rng["out"])})
597
+ else:
598
+ settings["SelectAllFrames"] = True
599
+ if not p.SetRenderSettings(settings):
600
+ # False when ANY key is refused, and nobody can tell what was applied: one key at a time says which
601
+ rejected = [k for k, v in settings.items() if not p.SetRenderSettings({k: v})]
602
+ job = p.AddRenderJob()
603
+ if not job:
604
+ fail("render_refused", "Resolve did not queue the job (check the format/codec and target folder)")
605
+ finally:
606
+ if routed:
607
+ p.DeleteRenderPreset(routed)
608
+ if kept:
609
+ p.LoadRenderPreset(keep)
610
+ # Starting a job loads ITS settings into the Deliver panel (measured on 21.1.1: ProRes 422 HQ
611
+ # before a renderplugin scan, the plugin codec after), so the snapshot is kept and loaded again
612
+ # when the job ends (render_finish), then deleted.
613
+ if not p.StartRendering([job]):
614
+ p.DeleteRenderJob(job)
615
+ if kept:
616
+ p.DeleteRenderPreset(keep)
617
+ fail("render_refused", "Resolve would not start the job")
618
+ return {"ok": True, "job_id": job, "timeline": tl.GetName(), "project": p.GetName(),
619
+ "settings_restored": kept, "disabled_tracks": off, "audio_tracks": args.get("audio_tracks") or [],
620
+ "rejected_settings": rejected,
621
+ "restore": {"timeline": prev_tl.GetName() if prev_tl else None, "page": page,
622
+ "rendered": tl.GetName(), "tracks": off, "keep": keep if kept else None}}
623
+
624
+
625
+ def a_render_status(resolve, args):
626
+ _pm, p = project_or_fail(resolve)
627
+ st = p.GetRenderJobStatus(args["job_id"]) or {}
628
+ status = st.get("JobStatus", "")
629
+ rendering = bool(p.IsRenderingInProgress())
630
+ if status in ("Complete", "Completed"):
631
+ state = "complete"
632
+ elif status in ("Failed",):
633
+ state = "failed"
634
+ elif status in ("Cancelled",):
635
+ state = "cancelled"
636
+ elif not rendering and status not in ("", "Rendering", "Queued", "Ready"):
637
+ state = "complete"
638
+ elif not find_job(p, args["job_id"]):
639
+ state = "failed"
640
+ st["Error"] = st.get("Error") or "the job is no longer in Resolve's render queue"
641
+ elif status == "Rendering" and not rendering:
642
+ # Resolve 21.1 leaves an interrupted job on "Rendering" with the queue idle: it will never finish (desktop MBR 1.26)
643
+ state = "failed"
644
+ st["Error"] = st.get("Error") or "the render was interrupted (Resolve stopped it part-way): start it again"
645
+ else:
646
+ state = "rendering" if rendering else "queued"
647
+ return {"ok": True, "job_id": args["job_id"], "state": state, "status": status,
648
+ "percent": int(st.get("CompletionPercentage") or 0), "error": st.get("Error")}
649
+
650
+
651
+ def a_render_cancel(resolve, args):
652
+ _pm, p = project_or_fail(resolve)
653
+ if p.IsRenderingInProgress():
654
+ st = p.GetRenderJobStatus(args["job_id"]) or {}
655
+ if st.get("JobStatus") == "Rendering":
656
+ p.StopRendering()
657
+ return a_render_finish(resolve, args, state="cancelled")
658
+
659
+
660
+ def a_render_finish(resolve, args, state=None):
661
+ """Give the user back their timeline and page; a finished job stays queued, a cancelled one goes."""
662
+ _pm, p = project_or_fail(resolve)
663
+ job = find_job(p, args["job_id"])
664
+ out = {"ok": True, "job_id": args["job_id"], "state": state or "complete"}
665
+ if job:
666
+ out["output"] = os.path.join(job.get("TargetDir", ""), job.get("OutputFilename", ""))
667
+ # a finished render keeps its job, so the queue records what made each file (field report 1007);
668
+ # a cancelled one is taken back out
669
+ if out["state"] == "complete":
670
+ out["job_kept"] = True
671
+ else:
672
+ p.DeleteRenderJob(args["job_id"])
673
+ r = args.get("restore") or {}
674
+ if r.get("keep") and r["keep"] in (p.GetRenderPresetList() or []):
675
+ p.LoadRenderPreset(r["keep"]) # the user's Deliver settings, again: starting our job replaced them
676
+ p.DeleteRenderPreset(r["keep"])
677
+ out["settings_restored"] = True
678
+ if r.get("tracks"): # the tracks we switched off for this job, back on (Edit page, read back)
679
+ t = next((x for x in timelines(p) if x.GetName() == r.get("rendered")), None)
680
+ if t:
681
+ p.SetCurrentTimeline(t)
682
+ bad = set_video_tracks(resolve, t, r["tracks"], True)
683
+ out["tracks_restored"] = bool(t) and not bad
684
+ out["tracks"] = r["tracks"]
685
+ if r.get("timeline"):
686
+ for t in timelines(p):
687
+ if t.GetName() == r["timeline"]:
688
+ p.SetCurrentTimeline(t)
689
+ break
690
+ if r.get("page") and resolve.GetCurrentPage() != r["page"]:
691
+ resolve.OpenPage(r["page"])
692
+ return out
693
+
694
+
695
+ # ── the renderplugin (conform.tools render plugin) ───────────────────────────────────────
696
+ #
697
+ # Resolve's scripting API cannot select a plugin codec (GetRenderFormats omits it), but a saved
698
+ # render preset can: it stores "<pluginUUID>:<codecUUID>". We ship that preset
699
+ # (presets/conform.tools.xml) and import it with Resolve.ImportRenderPreset, which names the preset
700
+ # after the FILE and also SELECTS it, so the user's Deliver settings are snapshotted around it.
701
+ # Presets live per Resolve database: ensure on every QC run.
702
+
703
+ # Resolve names an imported preset after its FILE (presets/conform.tools.xml) and may cut the name at
704
+ # the first dot ("conform"); a cut name is renamed back below. Earlier names of ours are renamed to it.
705
+ QC_PRESET = "conform.tools"
706
+ LEGACY_PRESETS = ("CONFORM.TOOLS", "CONFORM.TOOLS QC", "Conform Tools QC")
707
+ QC_REPORTS = ("qc_report.json", "qc_audio.json", "qc_filmstrip.jpg")
708
+
709
+
710
+ def _codec_id(xml_text):
711
+ import re
712
+ m = re.search(r"<RecordFormatSubType>([^<]+)</RecordFormatSubType>", xml_text or "")
713
+ return m.group(1).strip().upper() if m else ""
714
+
715
+
716
+ def _saved_codec_id(resolve, name):
717
+ """The codec a saved preset really selects (export it and read it); None when unknowable."""
718
+ import glob
719
+ import shutil
720
+ import tempfile
721
+ exporter = getattr(resolve, "ExportRenderPreset", None)
722
+ if exporter is None:
723
+ return None
724
+ d = tempfile.mkdtemp(prefix="ct_preset_")
725
+ try:
726
+ exporter(name, d) # the 2nd argument is a DIRECTORY; returns True regardless: trust the file
727
+ for f in glob.glob(os.path.join(d, "*.xml")):
728
+ with open(f) as fh:
729
+ return _codec_id(fh.read()) or None
730
+ return None
731
+ except Exception:
732
+ return None
733
+ finally:
734
+ shutil.rmtree(d, ignore_errors=True)
735
+
736
+
737
+ def _keeping_settings(project, fn):
738
+ """Run fn() and put the user's Deliver settings back (import and load both SELECT a preset)."""
739
+ keep = "%s%d_%d" % (KEEP_PREFIX, os.getpid(), int(time.time() * 1000))
740
+ kept = bool(project.SaveAsNewRenderPreset(keep))
741
+ try:
742
+ return fn()
743
+ finally:
744
+ if kept:
745
+ project.LoadRenderPreset(keep)
746
+ project.DeleteRenderPreset(keep)
747
+
748
+
749
+ def _rename_preset(project, src, dst):
750
+ project.LoadRenderPreset(src)
751
+ if not project.SaveAsNewRenderPreset(dst):
752
+ return False
753
+ project.DeleteRenderPreset(src)
754
+ return True
755
+
756
+
757
+ def _deliver_ready(resolve, project):
758
+ """Open the Deliver page and give its panel a moment before touching render presets, and sweep
759
+ snapshot presets an interrupted earlier run left behind (ours only: the __ct_keep_ prefix).
760
+ Measured 2026-10-01 on Resolve Studio 20.3.2: a first renderplugin run on a project whose Deliver
761
+ page had never been opened aborted Resolve inside its Deliver panel (assertion
762
+ GetUseProjectTimelineFilter in UiDeliverPanelTimelineController); the same calls on a project
763
+ whose Deliver page had been opened ran clean. This is the precaution; the exact trigger is not
764
+ proven. Returns the page to restore."""
765
+ page = resolve.GetCurrentPage()
766
+ if page != "deliver":
767
+ resolve.OpenPage("deliver")
768
+ time.sleep(1.0)
769
+ for name in project.GetRenderPresetList() or []:
770
+ if name.startswith((KEEP_PREFIX, ROUTE_PREFIX)):
771
+ project.DeleteRenderPreset(name)
772
+ return page
773
+
774
+
775
+ def a_renderplugin_preset(resolve, args):
776
+ """Make sure the conform.tools render preset exists and selects OUR codec. Never deletes a preset
777
+ the user named; replaces ours when it is stale; renames a legacy name of ours. The user's page and
778
+ Deliver settings are put back."""
779
+ _pm, p = project_or_fail(resolve)
780
+ with open(args["preset_path"]) as fh:
781
+ expected = _codec_id(fh.read())
782
+ page = _deliver_ready(resolve, p)
783
+ try:
784
+ presets = p.GetRenderPresetList() or []
785
+ if QC_PRESET in presets:
786
+ got = _saved_codec_id(resolve, QC_PRESET)
787
+ if got is None or got == expected:
788
+ return {"ok": True, "preset": QC_PRESET, "imported": False}
789
+ _keeping_settings(p, lambda: p.DeleteRenderPreset(QC_PRESET))
790
+ replaced = True
791
+ else:
792
+ replaced = False
793
+ for legacy in LEGACY_PRESETS:
794
+ if legacy in presets:
795
+ got = _saved_codec_id(resolve, legacy)
796
+ if got is None or got == expected:
797
+ if _keeping_settings(p, lambda: _rename_preset(p, legacy, QC_PRESET)):
798
+ return {"ok": True, "preset": QC_PRESET, "imported": False, "renamed_from": legacy}
799
+ importer = getattr(resolve, "ImportRenderPreset", None)
800
+ if importer is None:
801
+ fail("no_preset_import", "this Resolve cannot import render presets (Resolve 19 or later can)")
802
+ before = set(p.GetRenderPresetList() or [])
803
+ _keeping_settings(p, lambda: importer(os.path.abspath(args["preset_path"])))
804
+ after = p.GetRenderPresetList() or []
805
+ if QC_PRESET not in after:
806
+ new = [x for x in after if x not in before]
807
+ if len(new) == 1: # Resolve may cut the name at the first dot
808
+ _keeping_settings(p, lambda: _rename_preset(p, new[0], QC_PRESET))
809
+ if QC_PRESET not in (p.GetRenderPresetList() or []):
810
+ fail("preset_import_failed", "Resolve did not import the conform.tools render preset")
811
+ return {"ok": True, "preset": QC_PRESET, "imported": True, "replaced": replaced}
812
+ finally:
813
+ if resolve.GetCurrentPage() != page:
814
+ resolve.OpenPage(page)
815
+
816
+
817
+ def _write_qc_config(folder, config):
818
+ """<render folder>/qc_config.txt, flat key=value lines the codec reads at its first frame. No config:
819
+ remove any stale one so the codec runs every check."""
820
+ path = os.path.join(folder, "qc_config.txt")
821
+ if not config:
822
+ if os.path.exists(path):
823
+ os.remove(path)
824
+ return
825
+ lines = ["color_space=%s" % (config.get("color_space") or "sdr_rec709")]
826
+ if config.get("id"):
827
+ lines.append("template_id=%s" % config["id"])
828
+ for check, params in (config.get("checks") or {}).items():
829
+ params = params or {}
830
+ lines.append("%s.enabled=%d" % (check, 1 if params.get("enabled", True) else 0))
831
+ for k, v in params.items():
832
+ if k != "enabled":
833
+ lines.append("%s.%s=%s" % (check, k, int(v) if isinstance(v, bool) else v))
834
+ with open(path, "w") as fh:
835
+ fh.write("\n".join(lines) + "\n")
836
+
837
+
838
+ def a_clips(resolve, args):
839
+ """The video items of a timeline (absolute frames, end exclusive) + its start frame and raster:
840
+ what maps a measured frame to the clip that composites it."""
841
+ _pm, p = project_or_fail(resolve)
842
+ t = find_timeline(p, args.get("timeline"))
843
+ out = []
844
+ for track in range(1, int(t.GetTrackCount("video") or 0) + 1):
845
+ for i, it in enumerate(t.GetItemListInTrack("video", track) or []):
846
+ out.append({"id": "%d:%d" % (track, i), "name": it.GetName(), "start": int(it.GetStart()),
847
+ "end": int(it.GetEnd()), "track": track})
848
+ return {"ok": True, "timeline": t.GetName(), "start_frame": int(t.GetStartFrame()),
849
+ "end_frame": int(t.GetEndFrame()),
850
+ "width": int(float(t.GetSetting("timelineResolutionWidth") or 0)),
851
+ "height": int(float(t.GetSetting("timelineResolutionHeight") or 0)),
852
+ "fps": t.GetSetting("timelineFrameRate"), "clips": out}
853
+
854
+
855
+ def a_markers(resolve, args):
856
+ """Place or clear OUR markers on a timeline. Ours carry customData starting with the tag; a marker
857
+ someone else placed is never edited or deleted, and a frame they occupy is skipped and reported."""
858
+ _pm, p = project_or_fail(resolve)
859
+ t = find_timeline(p, args.get("timeline"))
860
+ prefix = args["tag"]
861
+
862
+ def ours_by_frame():
863
+ return dict((int(f), m) for f, m in (t.GetMarkers() or {}).items()
864
+ if str(m.get("customData") or "").startswith(prefix))
865
+
866
+ cleared = 0
867
+ if args.get("clear"):
868
+ for f in ours_by_frame():
869
+ if t.DeleteMarkerAtFrame(f):
870
+ cleared += 1
871
+ placed, skipped = 0, []
872
+ for m in args.get("place") or []:
873
+ f = int(m["frame"]) # relative to the timeline start, as Resolve counts markers
874
+ everyone = t.GetMarkers() or {}
875
+ if f in ours_by_frame():
876
+ t.DeleteMarkerAtFrame(f) # re-running replaces our own marker, never stacks a second
877
+ elif f in everyone or float(f) in everyone:
878
+ skipped.append(f) # someone else's: leave it
879
+ continue
880
+ if t.AddMarker(f, m.get("color", "Red"), m.get("name", "conform.tools"), m.get("note", ""),
881
+ max(1, int(m.get("duration", 1))), m.get("tag", prefix)):
882
+ placed += 1
883
+ else:
884
+ skipped.append(f)
885
+ return {"ok": True, "timeline": t.GetName(), "placed": placed, "cleared": cleared, "skipped": skipped}
886
+
887
+
888
+ # ── live edits: what the IR does not hold (clip colour, flags, grades, versions, pool names) ─────
889
+ #
890
+ # The tools decide in TypeScript, on the session read from this same timeline; `apply` only carries
891
+ # out a list of edits and reads each one back. A timeline item is addressed by kind + 1-based track
892
+ # + record start in frames FROM THE TIMELINE START (what the session's rows say), or by its unique
893
+ # id. Every op answers {ok, undo}: the ops that put back what it changed, so the engine can undo a
894
+ # whole batch by applying them.
895
+
896
+ PROPS = ("Pan", "Tilt", "ZoomX", "ZoomY", "ZoomGang", "RotationAngle", "AnchorPointX", "AnchorPointY", "Pitch",
897
+ "Yaw", "FlipX", "FlipY", "CropLeft", "CropRight", "CropTop", "CropBottom", "CropSoftness", "CropRetain",
898
+ "DynamicZoomEase", "CompositeMode", "Opacity", "Distortion", "RetimeProcess", "MotionEstimation", "Scaling",
899
+ "ResizeFilter")
900
+ VERSION_TYPE = {"local": 0, "remote": 1}
901
+
902
+
903
+ def _item_index(t):
904
+ """Every item of the timeline by (kind, track, start from the timeline start) and by unique id."""
905
+ t0 = int(t.GetStartFrame())
906
+ by_pos, by_id = {}, {}
907
+ for kind in ("video", "audio"):
908
+ for track in range(1, int(t.GetTrackCount(kind) or 0) + 1):
909
+ for it in t.GetItemListInTrack(kind, track) or []:
910
+ by_pos[(kind, track, int(it.GetStart()) - t0)] = it
911
+ by_id[it.GetUniqueId()] = it
912
+ return by_pos, by_id
913
+
914
+
915
+ def _item_row(it, kind, track, t0):
916
+ mpi = it.GetMediaPoolItem()
917
+ v = it.GetCurrentVersion() or {} if kind == "video" else {}
918
+ g = it.GetColorGroup() if kind == "video" else None
919
+ return {"kind": kind, "track": track, "start": int(it.GetStart()) - t0, "end": int(it.GetEnd()) - t0,
920
+ "id": it.GetUniqueId(), "name": it.GetName(), "color": it.GetClipColor() or "",
921
+ "flags": list(it.GetFlagList() or []), "enabled": bool(it.GetClipEnabled()),
922
+ "version": v.get("versionName", ""), "version_type": v.get("versionType"),
923
+ "group": g.GetName() if g else "", "markers": len(it.GetMarkers() or {}),
924
+ "nodes": int(it.GetNodeGraph().GetNumNodes() or 0) if kind == "video" and it.GetNodeGraph() else 0,
925
+ "stacks": _stacks(it) if kind == "video" else [],
926
+ "media_id": mpi.GetUniqueId() if mpi else "",
927
+ "src_in": _int_or_none(it.GetSourceStartFrame) if kind == "video" else None,
928
+ "keywords": (mpi.GetMetadata("Keywords") or "") if mpi else ""}
929
+
930
+
931
+ def _stacks(it):
932
+ """The clip's node tree per node stack (layer 1, 2, …): each node's label ("" unlabelled), in Resolve's numbering."""
933
+ out = []
934
+ for layer in range(1, 9): # GetNodeGraph(n) is None past the last stack
935
+ g = it.GetNodeGraph(layer)
936
+ if not g:
937
+ break
938
+ label = getattr(g, "GetNodeLabel", None)
939
+ out.append([(label(k) if label else "") or "" for k in range(1, int(g.GetNumNodes() or 0) + 1)])
940
+ return out
941
+
942
+
943
+ def _int_or_none(fn):
944
+ try:
945
+ return int(fn())
946
+ except Exception:
947
+ return None
948
+
949
+
950
+ def _onto_local_version(it, name):
951
+ """Put `it` on a LOCAL grade version (its current one when local, else `name`, made if missing) so a copied
952
+ grade never lands in a REMOTE version every timeline using that media shares (Copy Grades 1.11)."""
953
+ cur = it.GetCurrentVersion() or {}
954
+ if not cur.get("versionName") or int(cur.get("versionType") or 0) == 0:
955
+ return True
956
+ if name not in (it.GetVersionNameList(0) or []) and not it.AddVersion(name, 0):
957
+ return False
958
+ return bool(it.LoadVersionByName(name, 0)) and int((it.GetCurrentVersion() or {}).get("versionType") or 0) == 0
959
+
960
+
961
+ def a_items(resolve, args):
962
+ """The live attributes of every item (or one kind/track) that a timeline file does not carry:
963
+ clip colour, flags, enabled, grade version, colour group, node count, unique ids, keywords.
964
+ `into: scratch` reads our scratch project (as apply)."""
965
+ return _in_scratch(resolve, args, lambda p: _items(p, args))
966
+
967
+
968
+ # ── ColorMatchProbe (resolve_hook/, shipped with the app): what Resolve's own API cannot see ─────────────────────
969
+ # 21.1 layout (resolve_hook/selection_21.py, DISCOVERIES.md): the filmstrip is the UiVSRWidget whose item vector at +1216
970
+ # holds one item per filmstrip clip; item +776 = Cmd-selected, +784 = clip handle -> timeline object (+0) -> record
971
+ # start (+392). The selected node: UiNodeGraphListView +848 -> node object, +32 = node number (1-based, the API's).
972
+ PROBE = "http://127.0.0.1:9876"
973
+ _P_VEC, _P_SEL, _P_CLIP = 1216, 776, 784
974
+
975
+
976
+ def _pget(path):
977
+ import urllib.request
978
+ return json.load(urllib.request.urlopen(PROBE + path, timeout=2))
979
+
980
+
981
+ def _pread(addr, n):
982
+ d = _pget("/read?addr=%#x&len=%d" % (addr, n))
983
+ return bytes.fromhex(d["hex"]) if "hex" in d else None
984
+
985
+
986
+ def _probe_config():
987
+ """Point the probe at the filmstrip (after each Resolve restart): the UiVSRWidget with the longest clip vector."""
988
+ best, most = None, 0
989
+ for w in _pget("/widgets?q=UiVSRWidget").get("widgets", []):
990
+ if w.get("class") != "UiVSRWidget":
991
+ continue
992
+ b = _pread(int(w["ptr"], 16), _P_VEC + 16)
993
+ if not b:
994
+ continue
995
+ beg, end = struct.unpack_from("<QQ", b, _P_VEC)
996
+ n = (end - beg) // 8 if 0x100000000 <= beg <= end <= 0x700000000000 and not (end - beg) % 8 else 0
997
+ if n > most:
998
+ best, most = w["ptr"], n
999
+ if best:
1000
+ _pget("/config?panel=%s&vec=%d&sel=%d&clip=%d" % (best, _P_VEC, _P_SEL, _P_CLIP))
1001
+ return best
1002
+
1003
+
1004
+ def _probe_selection(t):
1005
+ """{on, items, node} from the probe; {} when it is not running (not installed, Intel Mac, Resolve not restarted)."""
1006
+ try:
1007
+ _pget("/")
1008
+ except Exception:
1009
+ return {}
1010
+ try:
1011
+ d = _pget("/selection")
1012
+ if "error" in d or _pget("/config").get("sel") != _P_SEL:
1013
+ _probe_config()
1014
+ d = _pget("/selection")
1015
+ by_start = {}
1016
+ for track in range(1, int(t.GetTrackCount("video") or 0) + 1):
1017
+ for it in t.GetItemListInTrack("video", track) or []:
1018
+ by_start.setdefault(int(it.GetStart()), it) # the lowest track at that start (the filmstrip's clip)
1019
+ items = []
1020
+ for c in d.get("selected", []) if "error" not in d else []:
1021
+ if not c.get("multi_sel"):
1022
+ continue
1023
+ obj = _pread(int(c["clip"], 16), 8)
1024
+ st = _pread(struct.unpack("<Q", obj)[0] + 392, 4) if obj else None
1025
+ it = by_start.get(struct.unpack("<i", st)[0]) if st else None
1026
+ if it is not None:
1027
+ items.append(it)
1028
+ cur = t.GetCurrentVideoItem()
1029
+ if cur is not None and items:
1030
+ items.insert(0, cur)
1031
+ node = None
1032
+ lv = [w["ptr"] for w in _pget("/widgets?q=UiNodeGraphListView").get("widgets", []) if w.get("class") == "UiNodeGraphListView"]
1033
+ if len(lv) == 1:
1034
+ p = _pread(int(lv[0], 16) + 848, 8)
1035
+ o = _pread(struct.unpack("<Q", p)[0], 40) if p and struct.unpack("<Q", p)[0] else None
1036
+ node = struct.unpack_from("<i", o, 32)[0] if o else None
1037
+ return {"on": True, "items": items, "node": node}
1038
+ except Exception:
1039
+ return {"on": True, "items": [], "node": None}
1040
+
1041
+
1042
+ def _items(p, args):
1043
+ t = find_timeline(p, args.get("timeline"))
1044
+ t0 = int(t.GetStartFrame())
1045
+ if args.get("selected"):
1046
+ # what the artist has selected in Resolve's timeline right now (GetSelectedClips, Resolve 21), addressed
1047
+ # like every item row: kind + track + start
1048
+ # like every item row: kind + track + start. With ColorMatchProbe in Resolve, the Color page filmstrip's
1049
+ # Cmd-selected clips are added (the API does not report them) and `node` says which node is selected.
1050
+ out, seen = [], set()
1051
+ def add(it):
1052
+ if it is None or it.GetUniqueId() in seen:
1053
+ return
1054
+ seen.add(it.GetUniqueId())
1055
+ kind, track = it.GetTrackTypeAndIndex()
1056
+ out.append({"kind": kind, "track": int(track), "start": int(it.GetStart()) - t0, "id": it.GetUniqueId(), "name": it.GetName()})
1057
+ for it in t.GetSelectedClips() or []:
1058
+ add(it)
1059
+ probe = _probe_selection(t)
1060
+ for it in probe.get("items", []):
1061
+ add(it)
1062
+ return {"ok": True, "timeline": t.GetName(), "start_frame": t0, "selected": out,
1063
+ **({"probe": True, "node": probe["node"]} if probe.get("on") else {})}
1064
+ kinds = [args["kind"]] if args.get("kind") else ["video", "audio"]
1065
+ out = []
1066
+ for kind in kinds:
1067
+ tracks = [int(args["track"])] if args.get("track") else range(1, int(t.GetTrackCount(kind) or 0) + 1)
1068
+ for track in tracks:
1069
+ for it in t.GetItemListInTrack(kind, track) or []:
1070
+ out.append(_item_row(it, kind, track, t0))
1071
+ groups = [g.GetName() for g in (p.GetColorGroupsList() or [])]
1072
+ return {"ok": True, "timeline": t.GetName(), "start_frame": t0, "items": out, "color_groups": groups,
1073
+ "layers": int(p.GetSetting("nodeStackLayers") or 1)}
1074
+
1075
+
1076
+ def _graph(it, t, where):
1077
+ """A grade graph: {"layer": n} on the clip (1 = the first), "pre"/"post" = its colour group's
1078
+ pre/post-clip graph, "timeline" = the timeline grade."""
1079
+ w = where or {"layer": 1}
1080
+ if w.get("timeline"):
1081
+ return t.GetNodeGraph()
1082
+ if w.get("pre") or w.get("post"):
1083
+ g = it.GetColorGroup()
1084
+ if not g:
1085
+ raise ValueError("the clip is in no colour group")
1086
+ return g.GetPreClipNodeGraph() if w.get("pre") else g.GetPostClipNodeGraph()
1087
+ return it.GetNodeGraph(int(w.get("layer", 1)))
1088
+
1089
+
1090
+ def _marker_host(it, t):
1091
+ return it if it is not None else t
1092
+
1093
+
1094
+ def _same_value(a, b):
1095
+ try:
1096
+ return abs(float(a) - float(b)) < 1e-6
1097
+ except (TypeError, ValueError):
1098
+ return a == b
1099
+
1100
+
1101
+ def _op(p, t, op, find):
1102
+ """One edit → {ok, undo:[ops], detail?}. Raises on a bad address; returns ok False when Resolve refuses."""
1103
+ kind = op["op"]
1104
+ it = find(op["item"]) if op.get("item") and not op.get("from_timeline") else None
1105
+ if kind.startswith("marker_"):
1106
+ h = _marker_host(it, t)
1107
+ f = int(op["frame"])
1108
+ here = (h.GetMarkers() or {})
1109
+ old = here.get(f) or here.get(float(f))
1110
+ addr = {"item": op["item"]} if op.get("item") else {}
1111
+ if kind == "marker_delete":
1112
+ if not old:
1113
+ return {"ok": True, "undo": [], "detail": "no marker there"}
1114
+ ok = h.DeleteMarkerAtFrame(f)
1115
+ return {"ok": bool(ok), "undo": [dict(addr, op="marker_add", frame=f, color=old["color"], name=old["name"],
1116
+ note=old["note"], duration=int(old["duration"]),
1117
+ data=old.get("customData", ""))]}
1118
+ if kind == "marker_add" or kind == "marker_update":
1119
+ if kind == "marker_update" and not old:
1120
+ return {"ok": False, "undo": [], "detail": "no marker at frame %d" % f}
1121
+ new = dict(old or {})
1122
+ for k, src in (("color", "color"), ("name", "name"), ("note", "note"), ("duration", "duration"),
1123
+ ("customData", "data")):
1124
+ if src in op:
1125
+ new[k] = op[src]
1126
+ to = int(op.get("to_frame", f))
1127
+ undo = []
1128
+ if old:
1129
+ h.DeleteMarkerAtFrame(f)
1130
+ undo = [dict(addr, op="marker_delete", frame=to),
1131
+ dict(addr, op="marker_add", frame=f, color=old["color"], name=old["name"], note=old["note"],
1132
+ duration=int(old["duration"]), data=old.get("customData", ""))]
1133
+ else:
1134
+ undo = [dict(addr, op="marker_delete", frame=to)]
1135
+ ok = h.AddMarker(to, new.get("color", "Blue"), new.get("name", ""), new.get("note", ""),
1136
+ max(1, int(new.get("duration", 1))), new.get("customData", "") or "")
1137
+ if not ok and old: # put the old one back rather than lose it
1138
+ h.AddMarker(f, old["color"], old["name"], old["note"], int(old["duration"]), old.get("customData", ""))
1139
+ return {"ok": bool(ok), "undo": undo if ok else []}
1140
+ if kind == "playhead": # navigation, not an edit: show the frame a finding is about
1141
+ return {"ok": bool(t.SetCurrentTimecode(op["tc"])), "undo": []}
1142
+ if kind == "timeline_rename":
1143
+ tl = find_timeline(p, op.get("timeline")) if op.get("timeline") else t
1144
+ old = tl.GetName()
1145
+ return {"ok": bool(tl.SetName(op["name"])), "undo": [{"op": "timeline_rename", "timeline": op["name"], "name": old}]}
1146
+ if kind == "timeline_duplicate":
1147
+ # a copy of the timeline under a name no other timeline has (Reconform builds the new cut on one: B is
1148
+ # never edited); it becomes the open timeline. Undo leaves it: deleting a timeline is the artist's call.
1149
+ tl = find_timeline(p, op.get("timeline")) if op.get("timeline") else t
1150
+ name = unique_name(p, op.get("name") or tl.GetName() + "_RECONFORMED")
1151
+ new = tl.DuplicateTimeline(name)
1152
+ if new:
1153
+ p.SetCurrentTimeline(new)
1154
+ return {"ok": bool(new), "name": new.GetName() if new else None, "undo": []}
1155
+ if kind == "goto":
1156
+ # make `timeline` the open one with the playhead on `frame` (from its start): On A / On B
1157
+ tl = find_timeline(p, op.get("timeline")) if op.get("timeline") else t
1158
+ p.SetCurrentTimeline(tl)
1159
+ fps = float(tl.GetSetting("timelineFrameRate") or 24)
1160
+ # ponytail: non-drop timecode; a drop-frame timeline needs the DF count here
1161
+ n, f = int(round(fps)), int(tl.GetStartFrame()) + int(op.get("frame", 0))
1162
+ tc = "%02d:%02d:%02d:%02d" % (f // (3600 * n), f // (60 * n) % 60, f // n % 60, f % n)
1163
+ return {"ok": bool(tl.SetCurrentTimecode(tc)), "timeline": tl.GetName(), "tc": tc, "undo": []}
1164
+ if kind == "pool_import":
1165
+ # files into a pool folder (made if missing); undo takes back exactly the clips this added
1166
+ mp = p.GetMediaPool()
1167
+ cur = mp.GetCurrentFolder() # before the folder is made: Resolve makes a new bin current
1168
+ folder, _ = pool_folder(mp, op.get("folder", ""), create=True)
1169
+ before = pool_ids(mp.GetRootFolder())
1170
+ mp.SetCurrentFolder(folder)
1171
+ try:
1172
+ clips = mp.ImportMedia(list(op["paths"])) or []
1173
+ finally:
1174
+ mp.SetCurrentFolder(cur)
1175
+ ids = [c.GetUniqueId() for c in clips]
1176
+ added = [c.GetUniqueId() for c in clips if c.GetMediaId() not in before]
1177
+ undo = [{"op": "pool_delete", "clips": added}] if added else []
1178
+ ok = len(ids) == len(op["paths"])
1179
+ placed = 0
1180
+ if ok and op.get("at"):
1181
+ # `at`: a record frame (from the timeline start) per path → each clip on ONE new top
1182
+ # video track. AppendToTimeline lays clips on the current timeline only.
1183
+ was = p.GetCurrentTimeline()
1184
+ p.SetCurrentTimeline(t)
1185
+ try:
1186
+ t.AddTrack("video")
1187
+ k = int(t.GetTrackCount("video"))
1188
+ t0 = int(t.GetStartFrame())
1189
+ got = mp.AppendToTimeline([{"mediaPoolItem": c, "startFrame": 0, "endFrame": int(c.GetClipProperty("Frames") or 1) - 1,
1190
+ "trackIndex": k, "recordFrame": t0 + int(f), "mediaType": 1} for c, f in zip(clips, op["at"])]) or []
1191
+ placed = len(got)
1192
+ undo = [{"op": "track_delete", "kind": "video", "index": k}] + undo
1193
+ finally:
1194
+ if was and was.GetName() != t.GetName():
1195
+ p.SetCurrentTimeline(was)
1196
+ ok = placed == len(op["at"])
1197
+ return {"ok": ok, "clips": ids, "already": len(ids) - len(added), "placed": placed, "undo": undo}
1198
+ if kind == "track_delete":
1199
+ return {"ok": bool(t.DeleteTrack(op.get("kind", "video"), int(op["index"]))), "undo": []}
1200
+ if kind.startswith("pool_"):
1201
+ mp = p.GetMediaPool()
1202
+ clips = _pool_clips(mp, op["clips"] if "clips" in op else [op["clip"]])
1203
+ if kind == "pool_rename":
1204
+ c = clips[0]
1205
+ old = c.GetClipProperty("Clip Name")
1206
+ ok = c.SetClipProperty("Clip Name", op["name"])
1207
+ return {"ok": bool(ok) and c.GetClipProperty("Clip Name") == op["name"],
1208
+ "undo": [{"op": "pool_rename", "clip": op["clip"], "name": old}]}
1209
+ if kind == "pool_move":
1210
+ olds = [_folder_path(mp, c) for c in clips]
1211
+ cur = mp.GetCurrentFolder()
1212
+ folder, _missing = pool_folder(mp, op["folder"], create=bool(op.get("create", True)))
1213
+ mp.SetCurrentFolder(cur) # a bin made here became current; the user's stays theirs
1214
+ ok = folder is not None and mp.MoveClips(clips, folder)
1215
+ undo = [{"op": "pool_move", "clips": [op["clips"][i]], "folder": olds[i], "create": False}
1216
+ for i in range(len(clips)) if olds[i] is not None]
1217
+ return {"ok": bool(ok), "undo": undo}
1218
+ if kind == "pool_delete":
1219
+ return {"ok": bool(mp.DeleteClips(clips)), "undo": []} # Resolve cannot bring a deleted clip back
1220
+ if it is None and not op.get("from_timeline"):
1221
+ raise ValueError("%s needs an item" % kind)
1222
+ item = op["item"]
1223
+ if kind == "clip_color":
1224
+ old = it.GetClipColor() or ""
1225
+ ok = it.SetClipColor(op["color"]) if op.get("color") else it.ClearClipColor()
1226
+ return {"ok": bool(ok) and (it.GetClipColor() or "") == (op.get("color") or ""),
1227
+ "undo": [{"op": "clip_color", "item": item, "color": old}]}
1228
+ if kind == "flags":
1229
+ old = list(it.GetFlagList() or [])
1230
+ if op.get("clear"):
1231
+ it.ClearFlags(op["clear"])
1232
+ for c in op.get("add") or []:
1233
+ if c not in (it.GetFlagList() or []):
1234
+ it.AddFlag(c)
1235
+ now = list(it.GetFlagList() or [])
1236
+ return {"ok": all(c in now for c in op.get("add") or []), "flags": now,
1237
+ "undo": [{"op": "flags", "item": item, "clear": "All", "add": old}]}
1238
+ if kind == "enabled":
1239
+ old = bool(it.GetClipEnabled())
1240
+ ok = it.SetClipEnabled(bool(op["on"]))
1241
+ return {"ok": bool(ok), "undo": [{"op": "enabled", "item": item, "on": old}]}
1242
+ if kind == "name":
1243
+ old = it.GetName()
1244
+ return {"ok": bool(it.SetName(op["name"])), "undo": [{"op": "name", "item": item, "name": old}]}
1245
+ if kind == "properties":
1246
+ want = op["set"]
1247
+ bad = [k for k in want if k not in PROPS]
1248
+ if bad:
1249
+ raise ValueError("unknown propert%s %s (known: %s)" % ("y" if len(bad) == 1 else "ies", ", ".join(bad), ", ".join(PROPS)))
1250
+ old = dict((k, it.GetProperty(k)) for k in want)
1251
+ # only what differs: Resolve refuses a write of the value a property already holds (AnchorPoint, 21.1),
1252
+ # and an undo puts back every key, changed or not
1253
+ refused = [k for k, v in want.items() if not _same_value(v, old[k]) and not it.SetProperty(k, v)]
1254
+ return {"ok": not refused, "refused": refused, "undo": [{"op": "properties", "item": item, "set": old}]}
1255
+ if kind == "metadata":
1256
+ mpi = it.GetMediaPoolItem()
1257
+ if not mpi:
1258
+ return {"ok": False, "undo": [], "detail": "no media pool clip behind this item"}
1259
+ old = dict((k, mpi.GetMetadata(k) or "") for k in op["set"])
1260
+ return {"ok": bool(mpi.SetMetadata(op["set"])), "undo": [{"op": "metadata", "item": item, "set": old}]}
1261
+ if kind in ("copy_properties", "copy_grade") and op.get("from_timeline"):
1262
+ # the source lives in another timeline of the project (Grade Tracer, Reconform's carry)
1263
+ pos, ids = _item_index(find_timeline(p, op["from_timeline"]))
1264
+ a = op["item"]
1265
+ it = ids.get(a["id"]) if a.get("id") else pos.get((a.get("kind", "video"), int(a["track"]), int(a["start"])))
1266
+ if it is None:
1267
+ raise ValueError("no item at %s in %r" % (json.dumps(a, sort_keys=True), op["from_timeline"]))
1268
+ if kind == "copy_properties":
1269
+ # exact: the values as Resolve holds them on the source, written to each target (not re-derived)
1270
+ keys = op["keys"]
1271
+ bad = [k for k in keys if k not in PROPS]
1272
+ if bad:
1273
+ raise ValueError("unknown propert%s %s" % ("y" if len(bad) == 1 else "ies", ", ".join(bad)))
1274
+ want = dict((k, it.GetProperty(k)) for k in keys)
1275
+ undo, refused = [], []
1276
+ for a in op["to"]:
1277
+ x = find(a)
1278
+ have = dict((k, x.GetProperty(k)) for k in keys)
1279
+ undo.append({"op": "properties", "item": a, "set": have})
1280
+ # only what differs: Resolve refuses a write of the value a property already holds (AnchorPoint, 21.1)
1281
+ refused += ["%s %s" % (json.dumps(a, sort_keys=True), k) for k, v in want.items()
1282
+ if v is not None and not _same_value(v, have[k]) and not x.SetProperty(k, v)]
1283
+ return {"ok": not refused, "refused": refused, "undo": undo}
1284
+ if kind == "copy_grade":
1285
+ targets = [find(a) for a in op["to"]]
1286
+ sv = it.GetCurrentVersion() or {}
1287
+ local = sv.get("versionName") if int(sv.get("versionType") or 0) == 0 and sv.get("versionName") else "Version 1"
1288
+ stuck = [op["to"][i] for i, x in enumerate(targets) if not _onto_local_version(x, local)]
1289
+ if stuck: # never copy over a shared remote grade
1290
+ return {"ok": False, "undo": [], "detail": "on a shared remote grade and could not move to a local version: nothing copied",
1291
+ "unverified": stuck}
1292
+ n = int(it.GetNodeGraph().GetNumNodes() or 0)
1293
+ ok = it.CopyGrades(targets)
1294
+ short = [i for i, x in enumerate(targets) if int(x.GetNodeGraph().GetNumNodes() or 0) != n]
1295
+ return {"ok": bool(ok) and not short, "nodes": n, "unverified": [op["to"][i] for i in short], "undo": []}
1296
+ if kind == "version":
1297
+ vt = VERSION_TYPE[op.get("type", "local")]
1298
+ cur = (it.GetCurrentVersion() or {}).get("versionName", "")
1299
+ if op.get("add"):
1300
+ ok = it.AddVersion(op["add"], vt)
1301
+ return {"ok": bool(ok), "undo": [{"op": "version", "item": item, "type": op.get("type", "local"),
1302
+ "load": cur, "delete": op["add"]}]}
1303
+ if op.get("delete"):
1304
+ if op.get("load"):
1305
+ it.LoadVersionByName(op["load"], vt)
1306
+ return {"ok": bool(it.DeleteVersionByName(op["delete"], vt)), "undo": []}
1307
+ ok = it.LoadVersionByName(op["load"], vt)
1308
+ return {"ok": bool(ok), "undo": [{"op": "version", "item": item, "type": op.get("type", "local"), "load": cur}]}
1309
+ if kind == "color_group":
1310
+ g = it.GetColorGroup()
1311
+ old = g.GetName() if g else ""
1312
+ if not op.get("group"):
1313
+ ok = it.RemoveFromColorGroup()
1314
+ else:
1315
+ grp = next((x for x in (p.GetColorGroupsList() or []) if x.GetName() == op["group"]), None) or p.AddColorGroup(op["group"])
1316
+ ok = it.AssignToColorGroup(grp)
1317
+ return {"ok": bool(ok), "undo": [{"op": "color_group", "item": item, "group": old}]}
1318
+ if kind == "cache":
1319
+ undo = {"op": "cache", "item": item}
1320
+ if "color" in op:
1321
+ undo["color"] = bool(it.GetIsColorOutputCacheEnabled())
1322
+ it.SetColorOutputCache(bool(op["color"]))
1323
+ if "fusion" in op:
1324
+ undo["fusion"] = it.GetIsFusionOutputCacheEnabled()
1325
+ it.SetFusionOutputCache(op["fusion"])
1326
+ return {"ok": True, "undo": [undo]}
1327
+ if kind == "fades":
1328
+ old = it.GetFades() or {}
1329
+ return {"ok": bool(it.SetFades(op["set"])), "undo": [{"op": "fades", "item": item, "set": old}]}
1330
+ if kind == "output_blanking":
1331
+ old = it.GetOutputBlanking() or {}
1332
+ return {"ok": bool(it.SetOutputBlanking(op["set"])), "undo": [{"op": "output_blanking", "item": item, "set": old}]}
1333
+ if kind == "drx":
1334
+ g = _graph(it, t, op.get("graph"))
1335
+ return {"ok": bool(g.ApplyGradeFromDRX(op["path"], int(op.get("mode", 0)))), "undo": []}
1336
+ if kind == "grade_sizing":
1337
+ if op.get("reset"): # the undo of an older sizing written onto an ungraded clip
1338
+ return _grade_sizing(t, it, op)
1339
+ # Sizing is only ever ADDED to the grade the clip has, read from the timeline's own .drt export (`bodies`, the
1340
+ # adapter): a clip whose grade could not be read there is refused, never guessed at from what Resolve's API shows
1341
+ if op.get("bodies") is None and not op.get("structure"):
1342
+ return {"ok": False, "undo": [], "refused": ["grade unreadable"],
1343
+ "detail": "refused: the clip's grade could not be read from the timeline's export; nothing changed"}
1344
+ if op["target"] == "node":
1345
+ return _grade_node_kept(it, op, t)
1346
+ return _grade_sizing_kept(it, op, t)
1347
+ if kind == "node_structure": # a .drx node tree onto the clip, on a new version (the colourist's own untouched)
1348
+ return _grade_node_kept(it, dict(op, structure_only=True))
1349
+ if kind == "grade_version_back": # the undo of an Align: the clip back on the version it was on. Ours stays in the
1350
+ # version list, never deleted (whatever was graded on it since stays too): undo only switches versions
1351
+ return {"ok": bool(it.LoadVersionByName(op["load"], int(op.get("type") or 0))), "undo": []}
1352
+ if kind == "lut":
1353
+ g = _graph(it, t, op.get("graph"))
1354
+ old = g.GetLUT(int(op["node"])) or ""
1355
+ return {"ok": bool(g.SetLUT(int(op["node"]), op["path"])),
1356
+ "undo": [{"op": "lut", "item": item, "graph": op.get("graph"), "node": op["node"], "path": old}]}
1357
+ if kind == "node_copy":
1358
+ # Copy (or swap) a whole node tree between grade graphs: CopyNodeTree → reset → PasteNodeTree,
1359
+ # the one path that carries a full tree on every build tested (old app, node_stack_transfer.py).
1360
+ dst_it = find(op["to_item"]) if op.get("to_item") else it
1361
+ src, dst = _graph(it, t, op.get("from")), _graph(dst_it, t, op.get("to"))
1362
+ n = int(src.GetNumNodes() or 0)
1363
+ if not hasattr(src, "CopyNodeTree"):
1364
+ return {"ok": False, "undo": [], "detail": "this Resolve has no node-tree copy in its API"}
1365
+ # ponytail: no swap (needs a parking graph); copy A→B then B's old tree is gone. Add via a temp version if asked.
1366
+ ok = bool(src.CopyNodeTree()) and bool(dst.ResetAllGrades()) and bool(dst.PasteNodeTree())
1367
+ if ok and op.get("clear_source"):
1368
+ src.ResetAllGrades()
1369
+ return {"ok": ok and int(dst.GetNumNodes() or 0) == n, "nodes": n, "undo": []}
1370
+ raise ValueError("unknown op %r" % kind)
1371
+
1372
+
1373
+ # ── Color-page sizing: a grade .drx of our own, applied with Graph.ApplyGradeFromDRX ─────────────
1374
+ #
1375
+ # Resolve 21's API sets only the Edit page transform; Input Sizing and node Sizing live in the clip's grade
1376
+ # Body (protobuf; decoded 2026-10-19, mcp/docs/ALIGNER.md). Input Sizing = the Body's clip-input record
1377
+ # (root field 3, type 84) group 10, params 0x1030_0001 width, 02 height, 03 zoom, 04 rotate (clockwise),
1378
+ # 05 pan, 06 tilt (fractions of the timeline width / height, tilt up), 07 flip V, 08 flip H (bools). Node
1379
+ # Sizing = group 19 of the corrector node, 0x0600_00E4 pan, E5 tilt, E6 width, E7 height, E8 zoom, E9 rotate,
1380
+ # same units. The rest is Resolve's own ungraded Body. Only non-default values are written, as Resolve does.
1381
+
1382
+ def _pv(n):
1383
+ out = bytearray()
1384
+ while True:
1385
+ b, n = n & 0x7F, n >> 7
1386
+ out.append(b | (0x80 if n else 0))
1387
+ if not n:
1388
+ return bytes(out)
1389
+
1390
+
1391
+ def _fv(num, n):
1392
+ return _pv(num << 3) + _pv(n)
1393
+
1394
+
1395
+ def _fb(num, b):
1396
+ return _pv(num << 3 | 2) + _pv(len(b)) + b
1397
+
1398
+
1399
+ def _ff(num, v):
1400
+ return _pv(num << 3 | 5) + struct.pack("<f", v)
1401
+
1402
+
1403
+ def _gparam(pid, v):
1404
+ """One grade param: a float as f32 (field 1), a bool / int as a varint (field 2)."""
1405
+ return _fb(3, _fv(1, pid) + _fb(2, _fv(2, int(v)) if isinstance(v, int) else _ff(1, v)))
1406
+
1407
+
1408
+ def _ggroup(gid, params):
1409
+ return _fb(1, _fv(1, gid) + _fv(3, 1) + _fb(6, _fb(2, _fv(1, 1) + b"".join(_gparam(k, v) for k, v in params))))
1410
+
1411
+
1412
+ _NODE_ON = _fb(10, _fb(1, _fv(1, 0xC0000001) + _fb(2, _fv(2, 2))))
1413
+
1414
+
1415
+ def sizing_body(target, op, w=1920, h=1080, sw=None, sh=None):
1416
+ """The grade Body (hex, 0x80 = raw protobuf) of an ungraded clip carrying only this sizing, on a w×h
1417
+ timeline over a sw×sh source. The source raster must be the clip's own: with any other, Resolve 21.1
1418
+ drops the Input Sizing flips (measured; pan / tilt / zoom / rotate apply either way)."""
1419
+ zoom, height, rot = float(op.get("zoom", 1)), float(op.get("height", 1)), float(op.get("rotation", 0))
1420
+ pan, tilt = float(op.get("pan", 0)), float(op.get("tilt", 0))
1421
+ near = lambda a, b: abs(a - b) < 1e-9 # noqa: E731
1422
+ if target == "input":
1423
+ params = [(0x10300002, height), (0x10300003, zoom), (0x10300004, rot), (0x10300005, pan), (0x10300006, tilt)]
1424
+ params = [(k, v) for k, v in params if not near(v, 1 if k in (0x10300002, 0x10300003) else 0)]
1425
+ params += [(0x10300007, True)] if op.get("flip_y") else []
1426
+ params += [(0x10300008, True)] if op.get("flip_x") else []
1427
+ node19 = b""
1428
+ elif target == "node":
1429
+ if op.get("flip_x") or op.get("flip_y"):
1430
+ raise ValueError("node sizing has no flip")
1431
+ params = [(0x060000E4, pan), (0x060000E5, tilt), (0x060000E7, height), (0x060000E8, zoom), (0x060000E9, rot)]
1432
+ params = [(k, v) for k, v in params if not near(v, 1 if k in (0x060000E7, 0x060000E8) else 0)]
1433
+ node19 = _ggroup(19, params) if params else b""
1434
+ else:
1435
+ raise ValueError("target must be input or node, not %r" % target)
1436
+ geometry = (_fv(1, w) + _fv(2, h) + _ff(3, 1.0) + _fv(4, sw or w) + _fv(5, sh or h) + _ff(6, 1.0) + _fv(7, w) + _fv(8, h) +
1437
+ _fv(9, 0xFFFFFFFF) + _fb(15, struct.pack("<9f", 1, 0, 0, 0, 1, 0, 0, 0, 1)))
1438
+ groups = node19 + _ggroup(2, [(0x88300001, 0)]) + _fb(2, bytes([3, 4, 5, 6, 0x12]))
1439
+ node = _fv(1, 1) + _fv(2, 1) + _fv(4, 190) + _fv(5, 180) + _fv(7, 1) + _fv(8, 44) + _fb(9, groups) + _NODE_ON
1440
+ graph = (_fv(1, 1) + _fv(2, 1) + _fb(3, geometry) + _fb(7, node) +
1441
+ _fb(9, _fv(1, 1) + _fv(2, 80) + _fb(3, _fv(1, 1) + _fv(2, 64) + _fv(3, 1) + _fv(4, 1))) +
1442
+ _fb(10, _fv(1, 2) + _fv(2, 64) + _fb(3, _fv(1, 2) + _fv(2, 64) + _fv(3, 2) + _fv(4, 1))) + _fv(11, 1))
1443
+ root = _fb(1, graph)
1444
+ if target == "input" and params:
1445
+ root += _fb(3, _fv(4, 190) + _fv(5, 180) + _fv(7, 1) + _fv(8, 84) + _fb(9, _ggroup(10, params)) + _NODE_ON)
1446
+ return "80" + root.hex()
1447
+
1448
+
1449
+ def sizing_drx(body):
1450
+ """A gallery still (.drx) holding one clip grade: what Graph.ApplyGradeFromDRX reads."""
1451
+ return ('<?xml version="1.0" encoding="UTF-8"?>\n<Gallery::GyStill DbId="%s">\n <pClipFullVer>\n'
1452
+ ' <ListMgt::LmVersion DbId="%s">\n <FieldsBlob/>\n <Name/>\n <HasCorrection>true</HasCorrection>\n'
1453
+ ' <VerType>0</VerType>\n <ImplVersion>1</ImplVersion>\n <IncludedInRecording>true</IncludedInRecording>\n'
1454
+ ' <FlatPassEnabled>false</FlatPassEnabled>\n <RGBAOutputEnabled>false</RGBAOutputEnabled>\n'
1455
+ ' <Body>%s</Body>\n <UseVersionClipProcParams>true</UseVersionClipProcParams>\n </ListMgt::LmVersion>\n'
1456
+ ' </pClipFullVer>\n</Gallery::GyStill>\n') % (uuid.uuid4(), uuid.uuid4(), body)
1457
+
1458
+
1459
+ def _grade_state(it):
1460
+ g = it.GetNodeGraph(1)
1461
+ n = int(g.GetNumNodes() or 0) if g else 0
1462
+ tools = list((g.GetToolsInNode(1) or []) if g and n else [])
1463
+ lut = (g.GetLUT(1) or "") if g and n else ""
1464
+ return n, tools, lut
1465
+
1466
+
1467
+ def _grade_sizing(t, it, op):
1468
+ """The undo of a sizing written (by an older build) onto an UNGRADED clip: its grade reset. A clip that has a grade
1469
+ since is left alone: nothing ever resets a colourist's grade."""
1470
+ n, tools, lut = _grade_state(it)
1471
+ if not (n <= 1 and not lut and (not tools or tools == ["Sizing"])):
1472
+ return {"ok": False, "undo": [], "refused": ["has a grade"], "detail": "refused: the clip has a grade now; nothing changed"}
1473
+ return {"ok": bool(it.GetNodeGraph(1).ResetAllGrades()), "undo": []}
1474
+
1475
+
1476
+ # ── Input Sizing ADDED to the grade the clip has: nothing a colourist did is lost ──────────────────────────
1477
+ #
1478
+ # The clip's grade as it stands comes in the op (`bodies`: every local and remote version's raw Body, read by the
1479
+ # engine from the timeline's .drt, grade-bodies.ts). The new Body = that Body with its clip-input record (root field 3,
1480
+ # type 84) replaced by one carrying the sizing; every node, version, LUT and colour group is left exactly as it was.
1481
+ # It goes onto a NEW local version (the colourist's own version is never written), checked node for node after.
1482
+
1483
+ ALIGNED = "conform.tools aligned"
1484
+
1485
+
1486
+ def _pb(raw):
1487
+ """Top-level protobuf fields of `raw`: (field number, wire type, the field's bytes incl. tag, payload)."""
1488
+ i, out = 0, []
1489
+ def varint():
1490
+ nonlocal i
1491
+ n = sh = 0
1492
+ while True:
1493
+ b = raw[i]; i += 1
1494
+ n |= (b & 0x7F) << sh; sh += 7
1495
+ if not b & 0x80:
1496
+ return n
1497
+ while i < len(raw):
1498
+ st = i; tag = varint(); num, wt = tag >> 3, tag & 7
1499
+ if wt == 0:
1500
+ v0 = i; varint(); pay = raw[v0:i]
1501
+ elif wt == 2:
1502
+ ln = varint(); pay = raw[i:i + ln]; i += ln
1503
+ elif wt == 5:
1504
+ pay = raw[i:i + 4]; i += 4
1505
+ elif wt == 1:
1506
+ pay = raw[i:i + 8]; i += 8
1507
+ else:
1508
+ raise ValueError("protobuf wire type %d" % wt)
1509
+ out.append((num, wt, raw[st:i], pay))
1510
+ return out
1511
+
1512
+
1513
+ def _is_clip_input(f):
1514
+ if f[0] != 3 or f[1] != 2:
1515
+ return False
1516
+ try:
1517
+ return any(n == 8 and w == 0 and pay == _pv(84) for n, w, _, pay in _pb(f[3]))
1518
+ except (IndexError, ValueError):
1519
+ return False
1520
+
1521
+
1522
+ _INPUT_DEFAULT = {0x10300001: 1.0, 0x10300002: 1.0, 0x10300003: 1.0, 0x10300004: 0.0, 0x10300005: 0.0, 0x10300006: 0.0,
1523
+ 0x10300007: 0, 0x10300008: 0}
1524
+
1525
+
1526
+ _NODE_DEFAULT = {0x060000E4: 0.0, 0x060000E5: 0.0, 0x060000E6: 1.0, 0x060000E7: 1.0, 0x060000E8: 1.0, 0x060000E9: 0.0}
1527
+
1528
+
1529
+ def _input_values(rec):
1530
+ return _values(rec, _INPUT_DEFAULT)
1531
+
1532
+
1533
+ def _values(rec, defaults):
1534
+ """The Input Sizing params in a clip-input record that differ from their defaults ({} = untouched sizing):
1535
+ every grade carries the record, so "has Input Sizing" means a value someone set, not the record itself."""
1536
+ out = {}
1537
+ def walk(b, depth=0):
1538
+ if depth > 8:
1539
+ return
1540
+ try:
1541
+ fs = _pb(b)
1542
+ except (IndexError, ValueError):
1543
+ return
1544
+ pid = next((int.from_bytes(bytes(_pvd(pay)), "little") for n, w, _, pay in fs if n == 1 and w == 0), None)
1545
+ if pid in defaults:
1546
+ val = None
1547
+ for n, w, _, pay in fs:
1548
+ if n == 2 and w == 2:
1549
+ for n2, w2, _, p2 in _pb(pay):
1550
+ val = struct.unpack("<f", p2)[0] if (n2 == 1 and w2 == 5) else (_varint(p2) if (n2 == 2 and w2 == 0) else val)
1551
+ if val is not None and abs(float(val) - defaults[pid]) > 1e-6:
1552
+ out[pid] = val
1553
+ return
1554
+ for n, w, _, pay in fs:
1555
+ if w == 2 and pay:
1556
+ walk(pay, depth + 1)
1557
+ walk(rec)
1558
+ return out
1559
+
1560
+
1561
+ def _varint(b):
1562
+ n = sh = 0
1563
+ for x in b:
1564
+ n |= (x & 0x7F) << sh; sh += 7
1565
+ if not x & 0x80:
1566
+ break
1567
+ return n
1568
+
1569
+
1570
+ def _pvd(b):
1571
+ return _varint(b).to_bytes(8, "little")
1572
+
1573
+
1574
+ def _input_params(op):
1575
+ zoom, height, rot = float(op.get("zoom", 1)), float(op.get("height", 1)), float(op.get("rotation", 0))
1576
+ pan, tilt = float(op.get("pan", 0)), float(op.get("tilt", 0))
1577
+ near = lambda a, b: abs(a - b) < 1e-9 # noqa: E731
1578
+ params = [(0x10300002, height), (0x10300003, zoom), (0x10300004, rot), (0x10300005, pan), (0x10300006, tilt)]
1579
+ params = [(k, v) for k, v in params if not near(v, 1 if k in (0x10300002, 0x10300003) else 0)]
1580
+ params += [(0x10300007, True)] if op.get("flip_y") else []
1581
+ params += [(0x10300008, True)] if op.get("flip_x") else []
1582
+ return params
1583
+
1584
+
1585
+ # Keyframed Input Sizing (decoded 2026-10-19 from a hand-keyed clip, render-measured): the group carries f5 = 1 and one
1586
+ # f6 per keyframe = { f1 time (2 units a FRAME from the clip start; absent = 0), f2 snapshot { f1 2 = dynamic, every
1587
+ # param as f3 { f1 id, f2 { f1 f32 } }, f5 dissolve { f1 Start, f2 End } } }. Dissolve S (1-11) eases over (S-1)/10 of
1588
+ # the segment at constant acceleration (S = 4 matched Resolve's render within 0.002 zoom on every frame); 1/1 = linear.
1589
+ UNITS_PER_FRAME = 2
1590
+
1591
+
1592
+ def _key_frames(keys, params_of):
1593
+ """One f6 per keyframe: { f1 time (2 units a frame from the clip start; absent = 0), f2 { f1 2 = dynamic, every
1594
+ param (snapshots, not deltas), f5 { f1 dissolve Start, f2 End } } }: the same records for Input Sizing (group 10)
1595
+ and node Sizing (group 19), render-proven for both (here; timeline-core's drt writer for node sizing, 2026-10-19)."""
1596
+ def snap(k):
1597
+ return _fv(1, 2) + b"".join(_gparam(p, v) for p, v in params_of(k)) + _fb(5, _fv(1, int(k.get("ease_in", 1))) + _fv(2, int(k.get("ease_out", 1))))
1598
+ keys = sorted(keys, key=lambda k: k["t"])
1599
+ return b"".join(_fb(6, (_fv(1, int(round(UNITS_PER_FRAME * float(k["t"])))) if k["t"] else b"") + _fb(2, snap(k))) for k in keys)
1600
+
1601
+
1602
+ def _input_key_params(k):
1603
+ params = [(0x10300002, float(k.get("height", 1))), (0x10300003, float(k.get("zoom", 1))), (0x10300004, float(k.get("rotation", 0))),
1604
+ (0x10300005, float(k.get("pan", 0))), (0x10300006, float(k.get("tilt", 0)))]
1605
+ params += [(0x10300007, True)] if k.get("flip_y") else []
1606
+ params += [(0x10300008, True)] if k.get("flip_x") else []
1607
+ return params
1608
+
1609
+
1610
+ def _node_key_params(k):
1611
+ return [(0x060000E4, float(k.get("pan", 0))), (0x060000E5, float(k.get("tilt", 0))), (0x060000E7, float(k.get("height", 1))),
1612
+ (0x060000E8, float(k.get("zoom", 1))), (0x060000E9, float(k.get("rotation", 0)))]
1613
+
1614
+
1615
+ def _keyed_group(gid, keys):
1616
+ keys = sorted(keys, key=lambda k: k["t"])
1617
+ frames = _key_frames(keys, _input_key_params)
1618
+ # beside the group: the slots that ANIMATE, each as 2 × slot (Resolve's own record for a zoom-only move lists 06 =
1619
+ # zoom, slot 3); without it Resolve holds the first keyframe for the whole clip
1620
+ chans = [(2, "height", 1.0), (3, "zoom", 1.0), (4, "rotation", 0.0), (5, "pan", 0.0), (6, "tilt", 0.0)]
1621
+ moving = [slot for slot, k, d in chans if len({round(float(x.get(k, d)), 7) for x in keys}) > 1]
1622
+ return _fb(1, _fv(1, gid) + _fv(3, 1) + _fv(5, 1) + frames) + (_fb(2, bytes(2 * s for s in moving)) if moving else b"")
1623
+
1624
+
1625
+ def _gid(g):
1626
+ """The group id of one group field (f1 { f1 id … })."""
1627
+ return next((_varint(x[3]) for x in _pb(g[3]) if x[0] == 1 and x[1] == 0), None) if g[0] == 1 and g[1] == 2 else None
1628
+
1629
+
1630
+ def splice_input_sizing(base_hex, op):
1631
+ """`base_hex` (a raw Body, "80…") with op's Input Sizing written into its clip-input record: ONLY the sizing group
1632
+ (10) is replaced — every other record and every other field and group of the clip-input record (whatever else the
1633
+ colourist set there) is kept byte for byte. A grade without a clip-input record gets one carrying just the sizing.
1634
+ Returns (new Body hex, whether the old Body already had Input Sizing of its own)."""
1635
+ if not base_hex.lower().startswith("80"):
1636
+ raise ValueError("grade body must be raw (80…)")
1637
+ fields = _pb(bytes.fromhex(base_hex[2:]))
1638
+ old = next((f for f in fields if _is_clip_input(f)), None)
1639
+ had = bool(old and _values(old[3], _INPUT_DEFAULT))
1640
+ if op.get("keys"):
1641
+ sizing = _keyed_group(10, op["keys"]) # the group, and beside it the animating slots (f2)
1642
+ else:
1643
+ params = _input_params(op)
1644
+ sizing = _ggroup(10, params) if params else b""
1645
+ if old is None:
1646
+ rec = _fb(3, _fv(4, 190) + _fv(5, 180) + _fv(7, 1) + _fv(8, 84) + _fb(9, sizing) + _NODE_ON) if sizing else b""
1647
+ return "80" + (b"".join(f[2] for f in fields) + rec).hex(), had
1648
+ inner = []
1649
+ for n, w, whole, pay in _pb(old[3]):
1650
+ if n == 9 and w == 2:
1651
+ # the old sizing out (its group, and its animating-slot list when it was keyed); the rest stays as it was
1652
+ groups = [g[2] for g in _pb(pay) if _gid(g) != 10 and not (g[0] == 2 and (op.get("keys") or had))]
1653
+ whole = _fb(9, b"".join(groups) + sizing)
1654
+ inner.append(whole)
1655
+ if not any(n == 9 for n, *_ in _pb(old[3])) and sizing:
1656
+ inner.append(_fb(9, sizing))
1657
+ rec = _fb(3, b"".join(inner))
1658
+ return "80" + b"".join(rec if f is old else f[2] for f in fields).hex(), had
1659
+
1660
+
1661
+ def _signature(it):
1662
+ """What a colourist made, node by node, on the clip's current version: tools, LUT, label."""
1663
+ g = it.GetNodeGraph(1)
1664
+ n = int(g.GetNumNodes() or 0) if g else 0
1665
+ label = getattr(g, "GetNodeLabel", None) if g else None
1666
+ return [(tuple(g.GetToolsInNode(k) or []), g.GetLUT(k) or "", (label(k) if label else "") or "") for k in range(1, n + 1)]
1667
+
1668
+
1669
+ def _aligned_version(it, vname, vtype):
1670
+ """The version our sizing goes on: (name, made). The clip already on OUR version (a re-run) is written in place;
1671
+ anything else gets a new local version, so the colourist's own version is never written. (None, True) = no version."""
1672
+ if vtype == 0 and (vname or "").startswith(ALIGNED):
1673
+ return vname, False
1674
+ taken = set(it.GetVersionNameList(0) or [])
1675
+ name = ALIGNED if ALIGNED not in taken else next("%s %d" % (ALIGNED, k) for k in range(2, 999) if "%s %d" % (ALIGNED, k) not in taken)
1676
+ if not it.AddVersion(name, 0) or not it.LoadVersionByName(name, 0):
1677
+ return None, True
1678
+ return name, True
1679
+
1680
+
1681
+ def _put_back(it, vname, vtype, name, made, base):
1682
+ if made:
1683
+ it.LoadVersionByName(vname, vtype)
1684
+ it.DeleteVersionByName(name, 0)
1685
+ else:
1686
+ _apply_body(it, base)
1687
+
1688
+
1689
+ def _undo_of(item, vname, vtype, name, made, base):
1690
+ """Undo switches the clip back to the version it was on; a re-run on our own version has nothing to switch back to
1691
+ (the first Align's undo still does)."""
1692
+ return [{"op": "grade_version_back", "item": item, "load": vname, "type": vtype}] if made else []
1693
+
1694
+
1695
+ def _grade_sizing_kept(it, op, t=None):
1696
+ item = op["item"]
1697
+ cur = it.GetCurrentVersion() or {}
1698
+ vname, vtype = cur.get("versionName"), int(cur.get("versionType") or 0)
1699
+ base = (op["bodies"].get("remote" if vtype == 1 else "local") or {}).get(vname) or _empty_base(it, t, "input")
1700
+ if not base:
1701
+ n, tools, lut = _grade_state(it)
1702
+ return {"ok": False, "undo": [], "refused": ["grade unreadable"],
1703
+ "detail": "refused: has a grade (%d node(s)%s) on %s version %r that could not be read to keep it; nothing changed" % (
1704
+ n, "; tools " + ", ".join(tools) if tools else "", "remote" if vtype else "local", vname)}
1705
+ body, had = splice_input_sizing(base, op)
1706
+ ours = vtype == 0 and (vname or "").startswith(ALIGNED)
1707
+ if had and not ours and not op.get("replace_sizing"):
1708
+ return {"ok": False, "undo": [], "refused": ["has input sizing"],
1709
+ "detail": "refused: the clip already has Input Sizing of its own; replace_sizing replaces it"}
1710
+ before = _signature(it)
1711
+ name, made = _aligned_version(it, vname, vtype)
1712
+ if not name:
1713
+ return {"ok": False, "undo": [], "refused": ["no version"], "detail": "refused: could not add a local version; nothing changed"}
1714
+ # gradeMode 2 = "start frames aligned": 0 means "no keyframes" and silently drops every keyframe (measured:
1715
+ # Resolve's own keyframed still applied with 0 held its first key; with 2 it animates exactly as keyed)
1716
+ ok = _apply_body(it, body)
1717
+ after = _signature(it)
1718
+ if not ok or after != before:
1719
+ _put_back(it, vname, vtype, name, made, base)
1720
+ return {"ok": False, "undo": [], "refused": ["grade changed"],
1721
+ "detail": "refused: the grade did not come through intact (%d node(s) before, %d after); put back, nothing changed" % (len(before), len(after))}
1722
+ return {"ok": True, "undo": _undo_of(item, vname, vtype, name, made, base),
1723
+ "detail": ("on new local version %r = %s version %r + Input Sizing (%d node(s) kept)" % (name, "remote" if vtype else "local", vname, len(before))
1724
+ if made else "Input Sizing replaced on our own version %r (%d node(s) kept)" % (name, len(before)))}
1725
+
1726
+
1727
+ def _pool_clips(mp, ids):
1728
+ """Media pool clips by unique id (GetUniqueId), anywhere in the pool."""
1729
+ want = set(ids)
1730
+ found = {}
1731
+
1732
+ def walk(folder):
1733
+ for c in folder.GetClipList() or []:
1734
+ if c.GetUniqueId() in want:
1735
+ found[c.GetUniqueId()] = c
1736
+ for sub in folder.GetSubFolderList() or []:
1737
+ walk(sub)
1738
+ walk(mp.GetRootFolder())
1739
+ missing = [i for i in ids if i not in found]
1740
+ if missing:
1741
+ raise ValueError("no media pool clip with id %s" % ", ".join(missing))
1742
+ return [found[i] for i in ids]
1743
+
1744
+
1745
+ def _folder_path(mp, clip):
1746
+ target = clip.GetUniqueId()
1747
+
1748
+ def walk(folder, path):
1749
+ if any(c.GetUniqueId() == target for c in folder.GetClipList() or []):
1750
+ return path
1751
+ for sub in folder.GetSubFolderList() or []:
1752
+ r = walk(sub, (path + "/" if path else "") + sub.GetName())
1753
+ if r is not None:
1754
+ return r
1755
+ return None
1756
+ return walk(mp.GetRootFolder(), "")
1757
+
1758
+
1759
+ def _in_scratch(resolve, args, fn):
1760
+ """fn(project) in the open project, or with `into: scratch` in our scratch project (`scratch_project`,
1761
+ made if missing): the user's project is saved first and opened again afterwards, timeline and page as
1762
+ they were — the safe way for live tests and probes to edit (a_open does the same for imports)."""
1763
+ pm, p = project_or_fail(resolve)
1764
+ if args.get("into") != "scratch":
1765
+ return fn(p)
1766
+ scratch = args.get("scratch_project") or "conform.tools scratch"
1767
+ user, page = p.GetName(), resolve.GetCurrentPage()
1768
+ tl = p.GetCurrentTimeline()
1769
+ utl = tl.GetName() if tl else None
1770
+ if user == scratch:
1771
+ return fn(p)
1772
+ pm.SaveProject()
1773
+ if not pm.LoadProject(scratch) and not pm.CreateProject(scratch):
1774
+ fail("scratch_failed", "could not open or create the project %r" % scratch)
1775
+ try:
1776
+ return fn(pm.GetCurrentProject())
1777
+ finally:
1778
+ pm.SaveProject()
1779
+ pm.LoadProject(user)
1780
+ back = pm.GetCurrentProject()
1781
+ for t in (timelines(back) if back and utl else []):
1782
+ if t.GetName() == utl:
1783
+ back.SetCurrentTimeline(t)
1784
+ if resolve.GetCurrentPage() != page:
1785
+ resolve.OpenPage(page)
1786
+
1787
+
1788
+ def a_still(resolve, args):
1789
+ """The picture Resolve shows at record `frame` (from the timeline start) of `timeline`, written to `path`
1790
+ (.png / .jpg / .tif …, absolute) with ExportCurrentFrameAsStill. Timeline, playhead and page are put back.
1791
+ `into: scratch` as for apply."""
1792
+ path = args["path"]
1793
+ if not os.path.isabs(path):
1794
+ fail("usage", "path must be absolute (Resolve resolves paths against its own cwd)")
1795
+
1796
+ def go(p):
1797
+ prev, page = p.GetCurrentTimeline(), resolve.GetCurrentPage()
1798
+ t = find_timeline(p, args.get("timeline"))
1799
+ p.SetCurrentTimeline(t)
1800
+ tc0 = t.GetCurrentTimecode()
1801
+ fps = float(t.GetSetting("timelineFrameRate") or 24)
1802
+ # ponytail: non-drop timecode; a drop-frame timeline needs the DF count here
1803
+ n, f = int(round(fps)), int(t.GetStartFrame()) + int(args.get("frame", 0))
1804
+ # `disable_tracks` (video track numbers): off for this still only, then back as they were
1805
+ off = [int(i) for i in args.get("disable_tracks") or [] if t.GetIsTrackEnabled("video", int(i))]
1806
+ set_video_tracks(resolve, t, off, False)
1807
+ resolve.OpenPage("color")
1808
+ t.SetCurrentTimecode("%02d:%02d:%02d:%02d" % (f // (3600 * n), f // (60 * n) % 60, f // n % 60, f % n))
1809
+ time.sleep(0.3) # the viewer catches up with the playhead
1810
+ if os.path.exists(path):
1811
+ os.remove(path)
1812
+ ok = bool(p.ExportCurrentFrameAsStill(path)) and os.path.isfile(path)
1813
+ set_video_tracks(resolve, t, off, True)
1814
+ t.SetCurrentTimecode(tc0)
1815
+ if prev:
1816
+ p.SetCurrentTimeline(prev)
1817
+ resolve.OpenPage(page)
1818
+ return {"ok": ok, "project": p.GetName(), "timeline": t.GetName(), "path": path}
1819
+ return _in_scratch(resolve, args, go)
1820
+
1821
+
1822
+ def a_apply(resolve, args):
1823
+ """Carry out a list of live edits on one timeline, in order; each is read back. Stops at nothing:
1824
+ every op reports its own result, and `undo` (newest first) puts back everything that changed.
1825
+ `into: scratch` edits our scratch project instead (live tests), the user's project put back after."""
1826
+ return _in_scratch(resolve, args, lambda p: _apply(p, args))
1827
+
1828
+
1829
+ def _apply(p, args):
1830
+ t = find_timeline(p, args.get("timeline"))
1831
+ by_pos, by_id = _item_index(t)
1832
+
1833
+ def find(a):
1834
+ if a.get("id"):
1835
+ it = by_id.get(a["id"])
1836
+ else:
1837
+ it = by_pos.get((a.get("kind", "video"), int(a["track"]), int(a["start"])))
1838
+ if it is None:
1839
+ raise ValueError("no %s item at %s" % (a.get("kind", "video"), json.dumps(a, sort_keys=True)))
1840
+ return it
1841
+
1842
+ # the batch runs on the open timeline: Resolve drops AddFlag on an item of a timeline that is not open (21.1, while
1843
+ # clip colour still lands), so the edits' timeline is opened and the artist's put back after, unless an op opened
1844
+ # another on purpose (timeline_duplicate, goto)
1845
+ prev = p.GetCurrentTimeline()
1846
+ away = prev is not None and prev.GetName() != t.GetName()
1847
+ if away:
1848
+ p.SetCurrentTimeline(t)
1849
+ results, undo = [], []
1850
+ for op in args.get("ops") or []:
1851
+ try:
1852
+ r = _op(p, t, op, find)
1853
+ except Exception as e:
1854
+ r = {"ok": False, "undo": [], "detail": "%s: %s" % (type(e).__name__, e)}
1855
+ undo = list(r.pop("undo", [])) + undo
1856
+ results.append(dict(r, op=op["op"]))
1857
+ now = p.GetCurrentTimeline()
1858
+ if away and now is not None and now.GetName() == t.GetName():
1859
+ p.SetCurrentTimeline(prev)
1860
+ return {"ok": True, "project": p.GetName(), "timeline": t.GetName(), "results": results, "undo": undo,
1861
+ "applied": sum(1 for r in results if r["ok"]), "failed": sum(1 for r in results if not r["ok"])}
1862
+
1863
+
1864
+ # ── render presets: read and author what the scripting API cannot set ──────────────────────
1865
+ #
1866
+ # The API has no key for the Deliver page's audio OUTPUT routing (which timeline track or bus feeds
1867
+ # each output track) — but a render preset stores it, and Resolve exports/imports presets as XML.
1868
+ # Decoded 2026-10-06 (LITTLE DYNAMO field report, Resolve 21.1; all 60 presets round-trip
1869
+ # byte-exact): <FieldsBlob> is a hex Qt QDataStream map — u32 version, u32 count, then (QString key,
1870
+ # QVariant value)*; QString = u32 byte length + UTF-16BE; QVariant = u32 type + u8 null + payload
1871
+ # (1 bool, 2 int32, 3 uint32, 10 QString, 12 QByteArray = a nested map). Routing lives in
1872
+ # RenderAudioTracks {"0": {TrackInfoType 0 = timeline track | 1 = bus, TrackInfoValue n (1-based)}, ...},
1873
+ # mirrored by RecordAudioNormalizationOutputTracksEnableState and ExtraInfoMap aud_src_config
1874
+ # ("TRK0:TRK1" = timeline tracks 1 and 2, "AUX0" = bus 1).
1875
+
1876
+ ROUTE_PREFIX = "__ct_route_"
1877
+
1878
+
1879
+ def _qs(v):
1880
+ b = v.encode("utf-16-be")
1881
+ return struct.pack(">I", len(b)) + b
1882
+
1883
+
1884
+ def _rqs(b, i):
1885
+ n, = struct.unpack_from(">I", b, i)
1886
+ i += 4
1887
+ return (None, i) if n == 0xffffffff else (b[i:i + n].decode("utf-16-be"), i + n)
1888
+
1889
+
1890
+ def blob_decode(b):
1891
+ _ver, cnt = struct.unpack_from(">II", b, 0)
1892
+ i, d = 8, {}
1893
+ for _ in range(cnt):
1894
+ k, i = _rqs(b, i)
1895
+ t, = struct.unpack_from(">I", b, i)
1896
+ i += 5
1897
+ if t == 1:
1898
+ v = bool(b[i]); i += 1
1899
+ elif t == 2:
1900
+ v, = struct.unpack_from(">i", b, i); i += 4
1901
+ elif t == 3:
1902
+ v, = struct.unpack_from(">I", b, i); i += 4
1903
+ elif t == 10:
1904
+ v, i = _rqs(b, i)
1905
+ elif t == 12:
1906
+ n, = struct.unpack_from(">I", b, i); i += 4
1907
+ raw = b[i:i + n]; i += n
1908
+ try:
1909
+ v = blob_decode(raw)
1910
+ except Exception:
1911
+ v = raw
1912
+ else:
1913
+ raise ValueError("QVariant type %d for %r" % (t, k))
1914
+ d[k] = v
1915
+ if i != len(b):
1916
+ raise ValueError("trailing bytes in FieldsBlob")
1917
+ return d
1918
+
1919
+
1920
+ def blob_encode(d, ver=1):
1921
+ out = struct.pack(">II", ver, len(d))
1922
+ for k, v in d.items():
1923
+ out += _qs(k)
1924
+ if isinstance(v, bool):
1925
+ out += struct.pack(">IBB", 1, 0, v)
1926
+ elif isinstance(v, int):
1927
+ out += struct.pack(">IBi", 2, 0, v)
1928
+ elif isinstance(v, str):
1929
+ out += struct.pack(">IB", 10, 0) + _qs(v)
1930
+ elif isinstance(v, dict):
1931
+ raw = blob_encode(v)
1932
+ out += struct.pack(">IBI", 12, 0, len(raw)) + raw
1933
+ elif isinstance(v, bytes):
1934
+ out += struct.pack(">IBI", 12, 0, len(v)) + v
1935
+ else:
1936
+ raise TypeError(k)
1937
+ return out
1938
+
1939
+
1940
+ def _xml_field(xml, k):
1941
+ m = re.search(r"<%s>([^<]*)</%s>" % (k, k), xml)
1942
+ return m.group(1) if m else None
1943
+
1944
+
1945
+ def _extra(xml, k):
1946
+ m = re.search(r"<DbKey>%s</DbKey>\s*<DbVal>([^<]*)</DbVal>" % re.escape(k), xml)
1947
+ return m.group(1) if m else None
1948
+
1949
+
1950
+ def _fields(xml):
1951
+ m = re.search(r"<FieldsBlob>([0-9a-fA-F]*)</FieldsBlob>", xml)
1952
+ return blob_decode(bytes.fromhex(m.group(1))) if m else {}
1953
+
1954
+
1955
+ def preset_summary(xml):
1956
+ """What a preset renders: container, codec, raster, audio codec and output routing."""
1957
+ f = _fields(xml)
1958
+ routing = []
1959
+ for _k, o in sorted((f.get("RenderAudioTracks") or {}).items(), key=lambda kv: int(kv[0])):
1960
+ if isinstance(o, dict):
1961
+ routing.append(("Bus %d" if o.get("TrackInfoType") == 1 else "Timeline Track %d") % o.get("TrackInfoValue", 0))
1962
+ return {"format": _xml_field(xml, "RecordFormatType"), "codec": _xml_field(xml, "RecordFormatSubType"),
1963
+ "width": _xml_field(xml, "FormatWidth"), "height": _xml_field(xml, "FormatHeight"),
1964
+ "audio": _xml_field(xml, "RecordAudioEnabled"), "audio_codec": _extra(xml, "aud_codec"),
1965
+ "audio_outputs": routing, "discrete_audio": _extra(xml, "aud_discrete") == "1"}
1966
+
1967
+
1968
+ def with_audio_tracks(xml, tracks):
1969
+ """The preset with Deliver > Audio output n fed by timeline track tracks[n] (1-based), and a fresh DbId."""
1970
+ m = re.search(r"<FieldsBlob>([0-9a-fA-F]*)</FieldsBlob>", xml)
1971
+ if not m:
1972
+ raise ValueError("not a Resolve render preset (no FieldsBlob)")
1973
+ f = blob_decode(bytes.fromhex(m.group(1)))
1974
+ f["RenderAudioTracks"] = dict((str(i), {"TrackInfoValue": int(n), "TrackInfoType": 0}) for i, n in enumerate(tracks))
1975
+ f["RecordAudioNormalizationOutputTracksEnableState"] = dict((str(i), 1) for i in range(len(tracks)))
1976
+ x = xml[:m.start(1)] + blob_encode(f).hex() + xml[m.end(1):]
1977
+ x = re.sub(r"(<DbKey>aud_src_config</DbKey>\s*<DbVal>)[^<]*(</DbVal>)",
1978
+ lambda g: g.group(1) + ":".join("TRK%d" % (int(n) - 1) for n in tracks) + g.group(2), x)
1979
+ x = re.sub(r"<RecordAudioEnabled>[^<]*</RecordAudioEnabled>", "<RecordAudioEnabled>true</RecordAudioEnabled>", x)
1980
+ return re.sub(r'DbId="[^"]+"', 'DbId="%s"' % uuid.uuid4(), x, 1)
1981
+
1982
+
1983
+ def _export_xml(resolve, name):
1984
+ d = tempfile.mkdtemp(prefix="ct_preset_")
1985
+ try:
1986
+ resolve.ExportRenderPreset(name, d) # a DIRECTORY; returns True regardless: trust the file
1987
+ for root, _dirs, files in os.walk(d):
1988
+ for fn in files:
1989
+ if fn.endswith(".xml"):
1990
+ with open(os.path.join(root, fn), encoding="utf-8") as fh:
1991
+ return fh.read()
1992
+ return None
1993
+ finally:
1994
+ shutil.rmtree(d, ignore_errors=True)
1995
+
1996
+
1997
+ def _import_xml(resolve, p, xml, name):
1998
+ """Import xml as preset `name` (Resolve names it after the file; no dots in ours). It also SELECTS it."""
1999
+ d = tempfile.mkdtemp(prefix="ct_preset_")
2000
+ try:
2001
+ path = os.path.join(d, name + ".xml")
2002
+ with open(path, "w", encoding="utf-8") as fh:
2003
+ fh.write(xml)
2004
+ resolve.ImportRenderPreset(path)
2005
+ finally:
2006
+ shutil.rmtree(d, ignore_errors=True)
2007
+ return name in (p.GetRenderPresetList() or [])
2008
+
2009
+
2010
+ def _routed_settings(resolve, p, tracks):
2011
+ """Make the Deliver page's CURRENT settings route audio output n from timeline track tracks[n]:
2012
+ snapshot → export → rewrite the routing → import (which selects it). Returns the preset to delete."""
2013
+ snap = "%s%d_%d" % (ROUTE_PREFIX, os.getpid(), int(time.time() * 1000))
2014
+ if not p.SaveAsNewRenderPreset(snap):
2015
+ fail("render_refused", "Resolve would not snapshot the render settings to set the audio routing")
2016
+ xml = _export_xml(resolve, snap)
2017
+ p.DeleteRenderPreset(snap)
2018
+ if not xml:
2019
+ fail("render_refused", "Resolve did not export the render settings, so the audio routing cannot be set")
2020
+ if not _import_xml(resolve, p, with_audio_tracks(xml, tracks), snap) or not p.LoadRenderPreset(snap):
2021
+ fail("render_refused", "Resolve did not take the preset with the audio routing")
2022
+ return snap
2023
+
2024
+
2025
+ def a_presets(resolve, args):
2026
+ """Every render preset (or `names`) with what it renders, including the audio output routing."""
2027
+ _pm, p = project_or_fail(resolve)
2028
+ page = _deliver_ready(resolve, p)
2029
+ try:
2030
+ want = args.get("names") or [n for n in (p.GetRenderPresetList() or []) if not n.startswith(("__ct_",))]
2031
+ out = []
2032
+ for n in want:
2033
+ xml = _export_xml(resolve, n)
2034
+ row = {"name": n}
2035
+ try:
2036
+ row.update(preset_summary(xml) if xml else {"error": "Resolve did not export it"})
2037
+ except Exception as e:
2038
+ row["error"] = "could not read: %s" % e
2039
+ out.append(row)
2040
+ return {"ok": True, "project": p.GetName(), "presets": out}
2041
+ finally:
2042
+ if resolve.GetCurrentPage() != page:
2043
+ resolve.OpenPage(page)
2044
+
2045
+
2046
+ def a_preset_author(resolve, args):
2047
+ """Save a new preset = `base` (a preset, or the Deliver page's current settings) with the audio
2048
+ outputs fed by timeline tracks `audio_tracks`. Never replaces an existing preset."""
2049
+ _pm, p = project_or_fail(resolve)
2050
+ name = args["name"]
2051
+ if "." in name:
2052
+ fail("invalid_args", "Resolve cuts an imported preset's name at the first dot: use a name without dots")
2053
+ if name in (p.GetRenderPresetList() or []):
2054
+ fail("exists", "a render preset named %r already exists; pick another name (we never replace one)" % name)
2055
+ page = _deliver_ready(resolve, p)
2056
+
2057
+ def go():
2058
+ if args.get("base"):
2059
+ if args["base"] not in (p.GetRenderPresetList() or []):
2060
+ fail("no_preset", "no render preset named %r" % args["base"], presets=p.GetRenderPresetList() or [])
2061
+ xml = _export_xml(resolve, args["base"])
2062
+ else:
2063
+ snap = "%s%d" % (ROUTE_PREFIX, os.getpid())
2064
+ p.SaveAsNewRenderPreset(snap)
2065
+ xml = _export_xml(resolve, snap)
2066
+ p.DeleteRenderPreset(snap)
2067
+ if not xml:
2068
+ fail("render_refused", "Resolve did not export the base settings")
2069
+ if not _import_xml(resolve, p, with_audio_tracks(xml, args["audio_tracks"]), name):
2070
+ fail("preset_import_failed", "Resolve did not import the new preset")
2071
+ back = _export_xml(resolve, name)
2072
+ return {"ok": True, "preset": name, "summary": preset_summary(back) if back else None}
2073
+ try:
2074
+ return _keeping_settings(p, go)
2075
+ finally:
2076
+ if resolve.GetCurrentPage() != page:
2077
+ resolve.OpenPage(page)
2078
+
2079
+
2080
+ ACTIONS = {
2081
+ "version": a_version,
2082
+ "current": a_current,
2083
+ "project": a_project,
2084
+ "export": a_export,
2085
+ "open": a_open,
2086
+ "render_start": a_render_start,
2087
+ "render_status": a_render_status,
2088
+ "render_cancel": a_render_cancel,
2089
+ "render_finish": a_render_finish,
2090
+ "renderplugin_preset": a_renderplugin_preset,
2091
+ "clips": a_clips,
2092
+ "markers": a_markers,
2093
+ "items": a_items,
2094
+ "clip_lut": a_clip_lut,
2095
+ "apply": a_apply,
2096
+ "still": a_still,
2097
+ "presets": a_presets,
2098
+ "preset_author": a_preset_author,
2099
+ }
2100
+
2101
+
2102
+ def main():
2103
+ if len(sys.argv) < 2 or sys.argv[1] not in ACTIONS:
2104
+ fail("usage", "bridge.py <%s> '<json>'" % "|".join(sorted(ACTIONS)))
2105
+ try:
2106
+ raw = sys.argv[2] if len(sys.argv) > 2 else "{}"
2107
+ # @<path>: the JSON is in that file (argv is capped: ~1 MB on macOS, ~32 K on Windows; grade bodies exceed it)
2108
+ if raw.startswith("@"):
2109
+ with open(raw[1:], encoding="utf-8") as f:
2110
+ raw = f.read()
2111
+ args = json.loads(raw)
2112
+ except ValueError as e:
2113
+ fail("usage", "arguments are not JSON: %s" % e)
2114
+ resolve = connect()
2115
+ t0 = time.time()
2116
+ try:
2117
+ out = ACTIONS[sys.argv[1]](resolve, args)
2118
+ except SystemExit:
2119
+ raise
2120
+ except Exception as e: # report Resolve's own failure verbatim; never a traceback on stdout
2121
+ fail("resolve_error", "%s: %s" % (type(e).__name__, e))
2122
+ out["ms"] = int((time.time() - t0) * 1000)
2123
+ reply(out)
2124
+
2125
+
2126
+
2127
+ # ── Node Sizing into ONE node of a grade: the clip's own grade, or a node tree from a .drx ───────────────────
2128
+ #
2129
+ # Resolve numbers nodes in signal-flow order (walking the graph from its input), not in the order the Body stores
2130
+ # them (measured 2026-10-19 on a 42-node grade: node 1 = the stored 25th). So the node is found through Resolve: the
2131
+ # grade goes onto the new version unchanged, Resolve says which label node N carries (or which N carries a label),
2132
+ # that label names exactly one stored node (Body node field 6), the Sizing (group 19) is written into it, and the
2133
+ # grade is applied again and checked: same node count, Sizing in node N, every other node's tools unchanged.
2134
+
2135
+ def _body_nodes(raw):
2136
+ graph = next(f for f in _pb(raw) if f[0] == 1)
2137
+ return graph, [f for f in _pb(graph[3]) if f[0] == 7]
2138
+
2139
+
2140
+ def _node_label(node_field):
2141
+ lab = [pay for n, w, _, pay in _pb(node_field[3]) if n == 6 and w == 2]
2142
+ return lab[0].decode("utf-8", "replace") if lab else ""
2143
+
2144
+
2145
+ def _node_params(op):
2146
+ zoom, height, rot = float(op.get("zoom", 1)), float(op.get("height", 1)), float(op.get("rotation", 0))
2147
+ pan, tilt = float(op.get("pan", 0)), float(op.get("tilt", 0))
2148
+ params = [(0x060000E4, pan), (0x060000E5, tilt), (0x060000E7, height), (0x060000E8, zoom), (0x060000E9, rot)]
2149
+ return [(k, v) for k, v in params if abs(v - (1 if k in (0x060000E7, 0x060000E8) else 0)) >= 1e-9]
2150
+
2151
+
2152
+ def splice_node_sizing(base_hex, op, label):
2153
+ """`base_hex` with node Sizing (group 19) written into the one stored node labelled `label`."""
2154
+ if op.get("flip_x") or op.get("flip_y") or any(k.get("flip_x") or k.get("flip_y") for k in op.get("keys") or []):
2155
+ raise ValueError("node sizing has no flip")
2156
+ raw = bytes.fromhex(base_hex[2:])
2157
+ graph, nodes = _body_nodes(raw)
2158
+ correctors = [k for k, n in enumerate(nodes) if any(f[0] == 8 and f[1] == 0 and _varint(f[3]) == 44 for f in _pb(n[3]))]
2159
+ hits = correctors if label is None and len(correctors) == 1 else [k for k, n in enumerate(nodes) if _node_label(n) == label]
2160
+ if len(hits) != 1:
2161
+ raise ValueError("%d stored nodes are labelled %r" % (len(hits), label))
2162
+ target = hits[0] # its position among the graph's node fields
2163
+ def with_sizing(node_bytes):
2164
+ out = b""
2165
+ for n, w, whole, pay in _pb(node_bytes):
2166
+ if n == 9 and w == 2:
2167
+ is19 = lambda g: g[0] == 1 and g[1] == 2 and next((_varint(x[3]) for x in _pb(g[3]) if x[0] == 1 and x[1] == 0), None) == 19 # noqa: E731
2168
+ if any(is19(g) and _values(g[3], _NODE_DEFAULT) for g in _pb(pay)) and not op.get("replace_sizing"):
2169
+ raise ValueError("node already has Sizing of its own: replace_sizing replaces it")
2170
+ groups = [g for g in _pb(pay) if not is19(g)]
2171
+ if op.get("keys"): # a move: one keyed Sizing group (beside it Resolve keeps its own list, unchanged)
2172
+ g19 = _fb(1, _fv(1, 19) + _fv(3, 1) + _fv(5, 1) + _key_frames(op["keys"], _node_key_params))
2173
+ else:
2174
+ p = _node_params(op)
2175
+ g19 = _ggroup(19, p) if p else b""
2176
+ pay = b"".join(g[2] for g in groups) + g19
2177
+ whole = _fb(9, pay)
2178
+ out += whole
2179
+ return out
2180
+ k, parts = -1, []
2181
+ for f in _pb(graph[3]):
2182
+ k += f[0] == 7
2183
+ parts.append(_fb(7, with_sizing(f[3])) if f[0] == 7 and k == target else f[2])
2184
+ # the alpha: node sizing uncovers canvas; with the output node's alpha wired to the graph's alpha output it shows
2185
+ # what is under the clip instead of black (Stefan's own wiring, 2026-10-22: graph field 10 {id, 16, {id, 16, id,
2186
+ # node, 1}} beside the picture output {id, 64, {id, 64, id, node}})
2187
+ outs = [f for f in _pb(graph[3]) if f[0] == 10 and f[1] == 2]
2188
+ def link(f):
2189
+ d = {n: (_varint(p) if w == 0 else p) for n, w, _, p in _pb(f[3])}
2190
+ sub = {n: _varint(p) for n, w, _, p in _pb(d.get(3, b"")) if w == 0} if isinstance(d.get(3), bytes) else {}
2191
+ return d.get(2), sub.get(4)
2192
+ if not any(link(f)[0] == 16 for f in outs):
2193
+ picture = next((link(f)[1] for f in outs if link(f)[0] == 64), None)
2194
+ if picture is not None:
2195
+ ids = [_varint(p) for f in _pb(graph[3]) if f[0] in (7, 9, 10) and f[1] == 2 for n, w, _, p in _pb(f[3]) if n == 1 and w == 0]
2196
+ nid = max(ids + [0]) + 1
2197
+ parts.append(_fb(10, _fv(1, nid) + _fv(2, 16) + _fb(3, _fv(1, nid) + _fv(2, 16) + _fv(3, nid) + _fv(4, picture) + _fv(5, 1))))
2198
+ new_graph = b"".join(parts)
2199
+ return "80" + b"".join((_fb(1, new_graph) if f[0] == 1 else f[2]) for f in _pb(raw)).hex()
2200
+
2201
+
2202
+ def _apply_body(it, body):
2203
+ d = tempfile.mkdtemp(prefix="ct-sizing-")
2204
+ path = os.path.join(d, "grade.drx")
2205
+ try:
2206
+ with open(path, "w", encoding="utf-8") as f:
2207
+ f.write(sizing_drx(body))
2208
+ return bool(it.GetNodeGraph(1).ApplyGradeFromDRX(path, 2)) # 2: keep keyframes, start frames aligned
2209
+ finally:
2210
+ shutil.rmtree(d, ignore_errors=True)
2211
+
2212
+
2213
+ def _empty_base(it, t, target):
2214
+ """A clip the .drt shows with no stored grade on this version was never graded: it starts from Resolve's empty
2215
+ grade on its own raster, but only when Resolve agrees (one node, no tools, no LUT)."""
2216
+ n, tools, lut = _grade_state(it)
2217
+ if t is None or n > 1 or tools or lut:
2218
+ return None
2219
+ mpi = it.GetMediaPoolItem()
2220
+ m = re.match(r"\s*(\d+)\s*x\s*(\d+)", (mpi.GetClipProperty("Resolution") or "") if mpi else "")
2221
+ return sizing_body(target, {}, int(t.GetSetting("timelineResolutionWidth") or 1920),
2222
+ int(t.GetSetting("timelineResolutionHeight") or 1080), *(map(int, m.groups()) if m else ()))
2223
+
2224
+
2225
+ def _grade_node_kept(it, op, t=None):
2226
+ item = op["item"]
2227
+ if not op.get("structure_only") and (op.get("flip_x") or op.get("flip_y")):
2228
+ return {"ok": False, "undo": [], "refused": ["flip"], "detail": "refused: node sizing has no flip (use Input Sizing); nothing changed"}
2229
+ cur = it.GetCurrentVersion() or {}
2230
+ vname, vtype = cur.get("versionName"), int(cur.get("versionType") or 0)
2231
+ base = op.get("structure") or ((op.get("bodies") or {}).get("remote" if vtype == 1 else "local") or {}).get(vname) or _empty_base(it, t, "node")
2232
+ if not base:
2233
+ return {"ok": False, "undo": [], "refused": ["grade unreadable"], "detail": "refused: could not read the grade to start from; nothing changed"}
2234
+ name, made = _aligned_version(it, vname, vtype)
2235
+ if not name:
2236
+ return {"ok": False, "undo": [], "refused": ["no version"], "detail": "refused: could not add a local version; nothing changed"}
2237
+ back = _undo_of(item, vname, vtype, name, made, base) # a list
2238
+ if not made: # a re-run on our own version: our earlier Sizing is ours to replace
2239
+ op = dict(op, replace_sizing=True)
2240
+ def refuse(why):
2241
+ _put_back(it, vname, vtype, name, made, base)
2242
+ return {"ok": False, "undo": [], "refused": [why.split(":")[0]], "detail": "refused: %s; put back, nothing changed" % why}
2243
+ if not _apply_body(it, base):
2244
+ return refuse("Resolve would not take the grade")
2245
+ first = _signature(it)
2246
+ src = "node tree %s" % os.path.basename(op.get("structure_name") or ".drx") if op.get("structure") else "%s version %r" % ("remote" if vtype else "local", vname)
2247
+ if op.get("structure_only"):
2248
+ return {"ok": True, "undo": back, "detail": "on new local version %r = %s (%d node(s))" % (name, src, len(first))}
2249
+ if int(op.get("layer") or 1) != 1:
2250
+ return refuse("node stack %s: sizing is written into node stack 1 only so far" % op.get("layer"))
2251
+ g = it.GetNodeGraph(1)
2252
+ n = int(g.GetNumNodes() or 0)
2253
+ label_of = getattr(g, "GetNodeLabel", None)
2254
+ if not label_of:
2255
+ return refuse("this Resolve cannot name its nodes (GetNodeLabel)")
2256
+ labels = [label_of(k) or "" for k in range(1, n + 1)]
2257
+ want = op.get("node", 1)
2258
+ if isinstance(want, str) and not want.strip().isdigit():
2259
+ hits = [k + 1 for k, l in enumerate(labels) if l == want]
2260
+ if len(hits) != 1:
2261
+ return refuse("%d nodes are labelled %r: label the sizing node uniquely" % (len(hits), want))
2262
+ num, label = hits[0], want
2263
+ else:
2264
+ num = int(want)
2265
+ if not 1 <= num <= n:
2266
+ return refuse("there is no node %d (the grade has %d)" % (num, n))
2267
+ label = labels[num - 1]
2268
+ if n == 1 and num == 1 and not label:
2269
+ label = None # one node, unlabelled: it is the only corrector, no name needed
2270
+ elif not label or labels.count(label) != 1:
2271
+ return refuse("node %d has no label of its own (%r): label it, or target it by label" % (num, label))
2272
+ try:
2273
+ body = splice_node_sizing(base, op, label)
2274
+ except ValueError as e:
2275
+ return refuse(str(e))
2276
+ if not _apply_body(it, body):
2277
+ return refuse("Resolve would not take the sized grade")
2278
+ after = _signature(it)
2279
+ others = lambda sig: [x for k, x in enumerate(sig) if k != num - 1] # noqa: E731
2280
+ kept = set(first[num - 1][0]) <= set(after[num - 1][0]) # the target node keeps every tool it had, + Sizing
2281
+ if len(after) != len(first) or "Sizing" not in after[num - 1][0] or not kept or others(after) != others(first):
2282
+ return refuse("the sized grade did not come through intact")
2283
+ return {"ok": True, "undo": back, "detail": (("on new local version %r" if made else "Sizing replaced on our own version %r") + " = %s + Sizing in node %d%s (%d node(s) kept)") % (name, src, num, " %r" % label if label else "", len(after))}
2284
+
2285
+ if __name__ == "__main__":
2286
+ main()