conformtools 0.6.4 → 0.6.5

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 (94) hide show
  1. package/package.json +1 -1
  2. package/dist/arriraw-3GKCR6K2.js +0 -525
  3. package/dist/browser/timeline_core_bg.wasm +0 -0
  4. package/dist/chunk-42QQI3WX.js +0 -3
  5. package/dist/chunk-6FVGUJ6L.js +0 -3
  6. package/dist/chunk-6TM32YIJ.js +0 -7
  7. package/dist/chunk-7D7H6VFW.js +0 -3
  8. package/dist/chunk-AACY2V3L.js +0 -3
  9. package/dist/chunk-BUEIRRNY.js +0 -3
  10. package/dist/chunk-BW2NQ54J.js +0 -3
  11. package/dist/chunk-C2ESM27Z.js +0 -3
  12. package/dist/chunk-CL26XMDO.js +0 -3
  13. package/dist/chunk-DKGGJM6Z.js +0 -3
  14. package/dist/chunk-DRHOPOC7.js +0 -3
  15. package/dist/chunk-EO5NIBOV.js +0 -3
  16. package/dist/chunk-EPZ6NWE4.js +0 -3
  17. package/dist/chunk-GXEVALBL.js +0 -3
  18. package/dist/chunk-HKP4P6JN.js +0 -3
  19. package/dist/chunk-JB7PR2TQ.js +0 -3
  20. package/dist/chunk-P7OVDUA5.js +0 -3
  21. package/dist/chunk-PSANHDZM.js +0 -3
  22. package/dist/chunk-QDWB7QU7.js +0 -3
  23. package/dist/chunk-QTKRMXL5.js +0 -363
  24. package/dist/chunk-QTPCU2TF.js +0 -3
  25. package/dist/chunk-SP5RGDAM.js +0 -3
  26. package/dist/chunk-TEZP6VEQ.js +0 -3
  27. package/dist/chunk-TK55FA56.js +0 -3
  28. package/dist/chunk-UCMNH6Q6.js +0 -3
  29. package/dist/chunk-WHY3DVXS.js +0 -3
  30. package/dist/chunk-WT6NIJCB.js +0 -3
  31. package/dist/chunk-Y2BEEOPB.js +0 -3
  32. package/dist/claude-setup-BM3AAUKR.js +0 -5
  33. package/dist/cli.js +0 -17
  34. package/dist/clip-state-B6JOX3JE.js +0 -3
  35. package/dist/conformtools-decode +0 -0
  36. package/dist/cr3-wasm-WKWMEK3V.js +0 -3
  37. package/dist/dng-wasm-Z5OVO4UI.js +0 -3
  38. package/dist/dpx-wasm-QNYXAOAJ.js +0 -3
  39. package/dist/esm-SFFBP7PS.js +0 -3
  40. package/dist/exr-wasm-BHSBJLQH.js +0 -3
  41. package/dist/h264-LIZVHN2W.js +0 -3
  42. package/dist/h264-mxf-MWS7DDV7.js +0 -3
  43. package/dist/http.js +0 -4
  44. package/dist/i2o-transfer +0 -0
  45. package/dist/inspect-DZF537QL.js +0 -46
  46. package/dist/isobmff-HM3UPWPZ.js +0 -3
  47. package/dist/mcp.js +0 -14
  48. package/dist/media_core-R5PPN3AY.js +0 -9
  49. package/dist/media_core_bg-FGAR5KA5.js +0 -3
  50. package/dist/media_core_bg-YK63OUDM.js +0 -3
  51. package/dist/mxf-K465SWBN.js +0 -3
  52. package/dist/onnxruntime-web-stub-PKJ2NZBF.js +0 -3
  53. package/dist/ops-73NR3X6R.js +0 -3
  54. package/dist/premiere-uxp/icons/panel.png +0 -0
  55. package/dist/premiere-uxp/icons/panel@2x.png +0 -0
  56. package/dist/premiere-uxp/icons/plugin.png +0 -0
  57. package/dist/premiere-uxp/icons/plugin@2x.png +0 -0
  58. package/dist/premiere-uxp/index.html +0 -38
  59. package/dist/premiere-uxp/index.js +0 -93
  60. package/dist/premiere-uxp/lib/clipmeta.js +0 -170
  61. package/dist/premiere-uxp/lib/ctx.js +0 -62
  62. package/dist/premiere-uxp/lib/handles.js +0 -57
  63. package/dist/premiere-uxp/lib/markers.js +0 -198
  64. package/dist/premiere-uxp/lib/pairing.js +0 -58
  65. package/dist/premiere-uxp/lib/premiere.js +0 -82
  66. package/dist/premiere-uxp/lib/probe.js +0 -139
  67. package/dist/premiere-uxp/lib/protocol.js +0 -165
  68. package/dist/premiere-uxp/lib/render.js +0 -38
  69. package/dist/premiere-uxp/lib/session.js +0 -85
  70. package/dist/premiere-uxp/lib/sizing.js +0 -312
  71. package/dist/premiere-uxp/lib/time.js +0 -82
  72. package/dist/premiere-uxp/lib/timeline.js +0 -336
  73. package/dist/premiere-uxp/lib/verbs.js +0 -20
  74. package/dist/premiere-uxp/lib/write.js +0 -97
  75. package/dist/premiere-uxp/manifest.json +0 -102
  76. package/dist/prores-L4JZZWGH.js +0 -526
  77. package/dist/r3d-RR3FUM6H.js +0 -3
  78. package/dist/r3d-VUOYU2KQ.js +0 -1025
  79. package/dist/resolve-bridge.py +0 -1037
  80. package/dist/resolve-presets/conform.tools.xml +0 -127
  81. package/dist/source-BDJAUQVR.js +0 -3
  82. package/dist/sscd-embed-DHFTEIOC.js +0 -3
  83. package/dist/sscd-sweep-OYS4XAID.js +0 -3
  84. package/dist/statusline-GMMCFMOA.js +0 -4
  85. package/dist/statusline.js +0 -3
  86. package/dist/still-4G25EYN5.js +0 -3
  87. package/dist/tiff-wasm-QJPCR7JT.js +0 -3
  88. package/dist/timeline_core-VK2ZWPCO.js +0 -3
  89. package/dist/timeline_core_bg-2TYWZ35G.js +0 -3
  90. package/dist/udf_bg-A4WEMSAX.js +0 -3
  91. package/dist/wasm/media_core_bg.wasm +0 -0
  92. package/dist/wasm/udf_bg.wasm +0 -0
  93. package/dist/wasm-threads/media_core_bg.wasm +0 -0
  94. package/dist/wav-63QF6SCT.js +0 -3
@@ -1,1037 +0,0 @@
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."""
148
- _pm, p = project_or_fail(resolve)
149
- mp = p.GetMediaPool()
150
- want_clips = bool(args.get("clips"))
151
- finds = [str(q) for q in args.get("find") or []]
152
- found = dict((q, []) for q in finds)
153
-
154
- # ponytail: GetClipProperty per clip walks the whole pool; fine for thousands, page it if it ever is not
155
- def walk(folder, path):
156
- clips = folder.GetClipList() or []
157
- node = {"path": path, "clips": len(clips), "folders": []}
158
- if want_clips or finds:
159
- rows = []
160
- for c in clips:
161
- pr = c.GetClipProperty() or {}
162
- row = {"name": c.GetName(), "file": pr.get("File Path") or "", "start_tc": pr.get("Start TC") or "",
163
- "usage": pr.get("Usage") or "", "folder": path}
164
- rows.append(row)
165
- for q in finds:
166
- if ("/" in q and row["file"] and os.path.normpath(row["file"]) == os.path.normpath(q)) or (
167
- "/" not in q and (q.lower() in row["name"].lower()
168
- or q.lower() in os.path.basename(row["file"]).lower())):
169
- found[q].append(row)
170
- if want_clips:
171
- node["clip_list"] = rows
172
- for sub in folder.GetSubFolderList() or []:
173
- node["folders"].append(walk(sub, (path + "/" if path else "") + sub.GetName()))
174
- return node
175
-
176
- jobs = []
177
- for j in p.GetRenderJobList() or []:
178
- j = dict(j)
179
- st = p.GetRenderJobStatus(j.get("JobId")) or {}
180
- j["JobStatus"] = st.get("JobStatus", "")
181
- j["CompletionPercentage"] = st.get("CompletionPercentage")
182
- jobs.append(j)
183
- t = find_timeline(p, args.get("timeline")) if (args.get("timeline") or p.GetCurrentTimeline()) else None
184
- return {"ok": True, "project": p.GetName(), "pool": walk(mp.GetRootFolder(), ""), "found": found,
185
- "jobs": jobs, "timeline": t.GetName() if t else None, "tracks": tracks_of(t) if t else [],
186
- "timelines": [x.GetName() for x in timelines(p)], "page": resolve.GetCurrentPage()}
187
-
188
-
189
- def a_export(resolve, args):
190
- """A timeline → Resolve's own .drt (read-only on the project). The user's current timeline
191
- is left (or put back) as it was.
192
-
193
- Resolve's Export is fussy about the target path (spaces / non-ASCII / a folder instead of a
194
- file all come back as a bare False), so it always writes to a plain ASCII temp file that we
195
- then move to out_path. Some builds also refuse a timeline that is not the current one: on a
196
- False we retry once with it made current, then restore the user's timeline."""
197
- _pm, p = project_or_fail(resolve)
198
- t = find_timeline(p, args.get("timeline"))
199
- out = args["out_path"]
200
- if os.path.isdir(out) or not os.path.splitext(out)[1]:
201
- out = os.path.join(out, safe_name(t.GetName()) + ".drt")
202
- parent = os.path.dirname(os.path.abspath(out))
203
- if not os.path.isdir(parent):
204
- os.makedirs(parent)
205
- tmp_dir = tempfile.mkdtemp(prefix="conform_export_")
206
- tmp = os.path.join(tmp_dir, "timeline.drt")
207
-
208
- def wrote():
209
- return os.path.isfile(tmp) and os.path.getsize(tmp) > 0
210
-
211
- try:
212
- ok = bool(t.Export(tmp, resolve.EXPORT_DRT))
213
- prev = p.GetCurrentTimeline()
214
- if not wrote() and (not prev or prev.GetName() != t.GetName()):
215
- p.SetCurrentTimeline(t)
216
- try:
217
- ok = bool(t.Export(tmp, resolve.EXPORT_DRT))
218
- finally:
219
- if prev:
220
- p.SetCurrentTimeline(prev)
221
- # Export returns True for some failures and writes a bundle for others: trust the file.
222
- if not wrote():
223
- fail("export_failed", "Resolve did not write the .drt for %r (Export returned %s)" % (t.GetName(), ok))
224
- if os.path.exists(out):
225
- os.remove(out)
226
- shutil.move(tmp, out)
227
- finally:
228
- shutil.rmtree(tmp_dir, ignore_errors=True)
229
- return {"ok": True, "path": out, "format": "drt", "project": p.GetName(), "timeline": t.GetName()}
230
-
231
-
232
- def safe_name(name):
233
- """A timeline name as a file name: anything but [A-Za-z0-9._-] becomes _."""
234
- return re.sub(r"[^A-Za-z0-9._-]+", "_", name).strip("_") or "timeline"
235
-
236
-
237
- OUR_FOLDER = "conform.tools"
238
-
239
-
240
- def unique_name(project, wanted):
241
- taken = set(t.GetName() for t in timelines(project))
242
- if wanted not in taken:
243
- return wanted
244
- n = 2
245
- while "%s (%d)" % (wanted, n) in taken:
246
- n += 1
247
- return "%s (%d)" % (wanted, n)
248
-
249
-
250
- def our_folder(media_pool):
251
- """The media pool folder our imports land in, created under the root if missing."""
252
- root = media_pool.GetRootFolder()
253
- for f in root.GetSubFolderList() or []:
254
- if f.GetName() == OUR_FOLDER:
255
- return f
256
- return media_pool.AddSubFolder(root, OUR_FOLDER)
257
-
258
-
259
- def named_media(path):
260
- """The media files a timeline file names (DRT MediaFilePath, FCP/FCPX file:// URLs); [] for
261
- formats that name none (EDL, AAF)."""
262
- import unicodedata, zipfile
263
- from urllib.parse import unquote
264
- try:
265
- if zipfile.is_zipfile(path):
266
- with zipfile.ZipFile(path) as z:
267
- text = "\n".join(z.read(n).decode("utf-8", "replace") for n in z.namelist() if n.endswith(".xml"))
268
- else:
269
- with open(path, encoding="utf-8", errors="replace") as f:
270
- text = f.read()
271
- except OSError:
272
- return []
273
- found = re.findall(r"<MediaFilePath>([^<]+)</MediaFilePath>", text)
274
- found += [unquote(u) for u in re.findall(r"file://(?:localhost)?(/[^<\"]+)", text)]
275
- return sorted({unicodedata.normalize("NFC", m.replace("&amp;", "&")) for m in found})
276
-
277
-
278
- def pool_ids(folder):
279
- ids = {c.GetMediaId() for c in folder.GetClipList() or []}
280
- for sub in folder.GetSubFolderList() or []:
281
- ids |= pool_ids(sub)
282
- return ids
283
-
284
-
285
- def mislinked(tl, named, before):
286
- """Items linked to a clip that was in the pool BEFORE the import and is a file the timeline file
287
- does not name: [(clip, frame, linked path)]. Clips the import made are its own (any path form)."""
288
- import unicodedata
289
- want, out = set(named), []
290
- for ti in range(1, (tl.GetTrackCount("video") or 0) + 1):
291
- for it in tl.GetItemListInTrack("video", ti) or []:
292
- m = it.GetMediaPoolItem()
293
- if not m or m.GetMediaId() not in before:
294
- continue
295
- got = unicodedata.normalize("NFC", m.GetClipProperty("File Path") or "")
296
- if got and got not in want:
297
- out.append((it.GetName(), it.GetStart(), got))
298
- return out
299
-
300
-
301
- def a_open(resolve, args):
302
- """A timeline file -> a NEW timeline in the open project (never overwrites), inside the
303
- conform.tools media pool folder, or `folder` ("000 - TIMELINES/20261006"; missing folders are
304
- created only with `create_folder`). `link_existing` imports with importSourceClips False: the
305
- timeline links to clips already in the pool, no duplicates. Otherwise the media the file names is
306
- imported first and the result checked: an item Resolve linked to some other pool clip fails the
307
- open (`import_mislinked`), the timeline deleted. The user's timeline, folder and page
308
- are restored unless `stay`. `into: scratch` switches to (or creates) our scratch project instead,
309
- saving the user's project first so nothing of theirs is lost, and switches back afterwards."""
310
- pm, p = project_or_fail(resolve)
311
- path = args["path"]
312
- if not os.path.isfile(path):
313
- fail("not_found", "no file at %s" % path)
314
- page = resolve.GetCurrentPage()
315
- prev_project = p.GetName()
316
- if args.get("into") == "scratch":
317
- scratch = args.get("scratch_project") or "conform.tools scratch"
318
- if prev_project != scratch:
319
- pm.SaveProject()
320
- if not pm.LoadProject(scratch):
321
- if not pm.CreateProject(scratch):
322
- fail("scratch_failed", "could not open or create the project %r" % scratch)
323
- p = pm.GetCurrentProject()
324
- prev_tl = p.GetCurrentTimeline()
325
- mp = p.GetMediaPool()
326
- prev_folder = mp.GetCurrentFolder()
327
-
328
- def restore():
329
- if prev_folder:
330
- mp.SetCurrentFolder(prev_folder)
331
- if prev_tl:
332
- p.SetCurrentTimeline(prev_tl)
333
- if args.get("into") == "scratch" and prev_project != p.GetName():
334
- pm.SaveProject()
335
- pm.LoadProject(prev_project)
336
- if resolve.GetCurrentPage() != page:
337
- resolve.OpenPage(page)
338
- return True
339
-
340
- if args.get("folder"):
341
- folder, missing = pool_folder(mp, args["folder"], bool(args.get("create_folder")))
342
- if not folder:
343
- restore()
344
- fail("no_folder", "no media pool folder %r in %r (pass create_folder to create it)" % (missing, args["folder"]))
345
- folder_name = args["folder"]
346
- else:
347
- folder, folder_name = our_folder(mp), OUR_FOLDER
348
- if folder:
349
- mp.SetCurrentFolder(folder)
350
- name = unique_name(p, args.get("name") or os.path.splitext(os.path.basename(path))[0])
351
- link = bool(args.get("link_existing"))
352
- opts = {"timelineName": name, "importSourceClips": not link}
353
- if args.get("media_dir") and not link:
354
- opts["sourceClipsPath"] = args["media_dir"]
355
- named = [] if link else named_media(path)
356
- # Resolve links a source clip to ANY pool clip its conform matcher accepts (same timecode, e.g.
357
- # every drone clip at 00:00:00:00) before importing the file's own; with the exact file already
358
- # in the pool it takes that one. So the named files go in first, and the result is checked.
359
- before = pool_ids(mp.GetRootFolder()) if named else set()
360
- on_disk = [m for m in named if os.path.isfile(m)]
361
- if on_disk:
362
- mp.ImportMedia(on_disk)
363
- tl = mp.ImportTimelineFromFile(path, opts)
364
- if not tl:
365
- restored = restore()
366
- 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)
367
- wrong = mislinked(tl, named, before)
368
- if wrong:
369
- mp.DeleteTimelines([tl])
370
- restored = restore()
371
- fail("import_mislinked", "Resolve linked %d clip(s) to other files than %s names: %s" % (
372
- len(wrong), os.path.basename(path), "; ".join("%s at frame %s -> %s" % w for w in wrong[:10])),
373
- restored=restored, mislinked=[{"clip": c, "frame": f, "linked": l} for c, f, l in wrong])
374
- notes = []
375
- if tl.GetName() != name: # Resolve may name it after the file
376
- tl.SetName(name)
377
- got = tl.GetName()
378
- restored = restore() if not args.get("stay") else False
379
- if not opts.get("sourceClipsPath") and args.get("media_dir"):
380
- notes.append("media_dir was not used" + (" (link_existing links to clips already in the pool)" if link else ""))
381
- return {"ok": True, "project": p.GetName(), "timeline": got, "folder": folder_name if folder else None,
382
- "linked_existing": link, "restored": restored, "notes": notes}
383
-
384
-
385
- def tc_frames(tc, fps):
386
- """"HH:MM:SS:FF" (";FF" drop-frame at 29.97/59.94) -> absolute frames; None when not a timecode."""
387
- m = re.match(r"^(\d+)[:;.](\d+)[:;.](\d+)([:;.])(\d+)$", str(tc).strip())
388
- if not m:
389
- return None
390
- h, mi, se, ff = int(m.group(1)), int(m.group(2)), int(m.group(3)), int(m.group(5))
391
- r = int(round(float(fps)))
392
- n = (h * 3600 + mi * 60 + se) * r + ff
393
- if m.group(4) == ";" and r in (30, 60):
394
- total = h * 60 + mi
395
- n -= (2 if r == 30 else 4) * (total - total // 10)
396
- return n
397
-
398
-
399
- # ── render ────────────────────────────────────────────────────────────────
400
- #
401
- # Stateless across calls: render_start returns what to restore, the engine keeps it in its job
402
- # record and hands it back to render_finish. Settings are restored right after AddRenderJob (a
403
- # queued job keeps the settings it was added with), so the user's Deliver page is theirs again
404
- # while our job renders; their timeline and page come back in render_finish.
405
-
406
- KEEP_PREFIX = "__ct_keep_"
407
-
408
-
409
- def find_job(project, job_id):
410
- for j in project.GetRenderJobList() or []:
411
- if j.get("JobId") == job_id:
412
- return j
413
- return None
414
-
415
-
416
- def track_matches(t, ref):
417
- """1-based video track indices named `ref` (case-insensitive, every track so named) or "V7"."""
418
- r = str(ref).strip().lower()
419
- return [i for i in range(1, int(t.GetTrackCount("video") or 0) + 1)
420
- if (t.GetTrackName("video", i) or "").strip().lower() == r or "v%d" % i == r]
421
-
422
-
423
- def video_tracks_named(t, refs):
424
- """track_matches for every ref; any ref without a track refuses before anything is touched."""
425
- out = []
426
- for ref in refs:
427
- hit = track_matches(t, ref)
428
- if not hit:
429
- fail("no_track", "no video track named %r on %r" % (ref, t.GetName()),
430
- tracks=[{"index": i, "name": t.GetTrackName("video", i)}
431
- for i in range(1, int(t.GetTrackCount("video") or 0) + 1)])
432
- out += [i for i in hit if i not in out]
433
- return sorted(out)
434
-
435
-
436
- def set_video_tracks(resolve, t, indices, enabled):
437
- """SetTrackEnable takes effect only on the Edit page (elsewhere it returns True and does
438
- nothing; Resolve 21.1): switch to Edit, set, read every track back. Returns those that did not
439
- take."""
440
- if indices and resolve.GetCurrentPage() != "edit":
441
- resolve.OpenPage("edit")
442
- for i in indices:
443
- t.SetTrackEnable("video", i, enabled)
444
- return [i for i in indices if bool(t.GetIsTrackEnabled("video", i)) != enabled]
445
-
446
-
447
- def a_render_start(resolve, args):
448
- _pm, p = project_or_fail(resolve)
449
- if p.IsRenderingInProgress():
450
- fail("busy", "Resolve is already rendering; we never interrupt someone else's render")
451
- target = args["target_dir"]
452
- if not os.path.isdir(target):
453
- os.makedirs(target)
454
- page = resolve.GetCurrentPage()
455
- if args.get("renderplugin") is not None or args.get("preset") or args.get("audio_tracks"):
456
- _deliver_ready(resolve, p)
457
- prev_tl = p.GetCurrentTimeline()
458
- tl = find_timeline(p, args.get("timeline"))
459
- if not prev_tl or prev_tl.GetName() != tl.GetName():
460
- p.SetCurrentTimeline(tl)
461
- # The documented RenderSettings have no per-job track selection ("Render All Video Tracks"):
462
- # the named tracks are switched off for our job and back on when it ends (render_finish).
463
- off = []
464
- if args.get("disable_tracks"):
465
- off = [i for i in video_tracks_named(tl, args["disable_tracks"]) if tl.GetIsTrackEnabled("video", i)]
466
- bad = set_video_tracks(resolve, tl, off, False)
467
- if bad:
468
- set_video_tracks(resolve, tl, off, True)
469
- resolve.OpenPage(page)
470
- fail("tracks_not_disabled", "Resolve did not switch off video track(s) %s; nothing was queued" % bad)
471
- if args.get("renderplugin") is not None or args.get("preset"):
472
- resolve.OpenPage("deliver")
473
- try:
474
- return _queue_and_start(resolve, p, tl, args, target, page, prev_tl, off)
475
- except BaseException:
476
- if off:
477
- set_video_tracks(resolve, tl, off, True)
478
- resolve.OpenPage(page)
479
- raise
480
-
481
-
482
- def _queue_and_start(resolve, p, tl, args, target, page, prev_tl, off):
483
- keep = "%s%d_%d" % (KEEP_PREFIX, os.getpid(), int(time.time() * 1000))
484
- kept = bool(p.SaveAsNewRenderPreset(keep))
485
- routed, rejected = None, []
486
- if args.get("renderplugin") is not None:
487
- args["preset"] = QC_PRESET
488
- for f in QC_REPORTS: # a stale report from an earlier run is the classic wrong answer
489
- if os.path.exists(os.path.join(target, f)):
490
- os.remove(os.path.join(target, f))
491
- _write_qc_config(target, args["renderplugin"])
492
- try:
493
- if args.get("preset"):
494
- if args["preset"] not in (p.GetRenderPresetList() or []):
495
- fail("no_preset", "no render preset named %r" % args["preset"], presets=p.GetRenderPresetList() or [])
496
- p.LoadRenderPreset(args["preset"])
497
- if args.get("audio_tracks"): # no API key for output routing: a preset carries it
498
- routed = _routed_settings(resolve, p, args["audio_tracks"])
499
- settings = {"TargetDir": target, "CustomName": args.get("name") or tl.GetName(),
500
- "ExportVideo": True, "ExportAudio": bool(args.get("audio") or args.get("audio_tracks"))}
501
- rng = args.get("range")
502
- if rng:
503
- settings.update({"SelectAllFrames": False, "MarkIn": int(rng["in"]), "MarkOut": int(rng["out"])})
504
- else:
505
- settings["SelectAllFrames"] = True
506
- if not p.SetRenderSettings(settings):
507
- # False when ANY key is refused, and nobody can tell what was applied: one key at a time says which
508
- rejected = [k for k, v in settings.items() if not p.SetRenderSettings({k: v})]
509
- job = p.AddRenderJob()
510
- if not job:
511
- fail("render_refused", "Resolve did not queue the job (check the format/codec and target folder)")
512
- finally:
513
- if routed:
514
- p.DeleteRenderPreset(routed)
515
- if kept:
516
- p.LoadRenderPreset(keep)
517
- p.DeleteRenderPreset(keep)
518
- if not p.StartRendering([job]):
519
- p.DeleteRenderJob(job)
520
- fail("render_refused", "Resolve would not start the job")
521
- return {"ok": True, "job_id": job, "timeline": tl.GetName(), "project": p.GetName(),
522
- "settings_restored": kept, "disabled_tracks": off, "audio_tracks": args.get("audio_tracks") or [],
523
- "rejected_settings": rejected,
524
- "restore": {"timeline": prev_tl.GetName() if prev_tl else None, "page": page,
525
- "rendered": tl.GetName(), "tracks": off}}
526
-
527
-
528
- def a_render_status(resolve, args):
529
- _pm, p = project_or_fail(resolve)
530
- st = p.GetRenderJobStatus(args["job_id"]) or {}
531
- status = st.get("JobStatus", "")
532
- rendering = bool(p.IsRenderingInProgress())
533
- if status in ("Complete", "Completed"):
534
- state = "complete"
535
- elif status in ("Failed",):
536
- state = "failed"
537
- elif status in ("Cancelled",):
538
- state = "cancelled"
539
- elif not rendering and status not in ("", "Rendering", "Queued", "Ready"):
540
- state = "complete"
541
- elif not find_job(p, args["job_id"]):
542
- state = "failed"
543
- st["Error"] = st.get("Error") or "the job is no longer in Resolve's render queue"
544
- else:
545
- state = "rendering" if rendering else "queued"
546
- return {"ok": True, "job_id": args["job_id"], "state": state, "status": status,
547
- "percent": int(st.get("CompletionPercentage") or 0), "error": st.get("Error")}
548
-
549
-
550
- def a_render_cancel(resolve, args):
551
- _pm, p = project_or_fail(resolve)
552
- if p.IsRenderingInProgress():
553
- st = p.GetRenderJobStatus(args["job_id"]) or {}
554
- if st.get("JobStatus") == "Rendering":
555
- p.StopRendering()
556
- return a_render_finish(resolve, args, state="cancelled")
557
-
558
-
559
- def a_render_finish(resolve, args, state=None):
560
- """Give the user back their timeline and page; a finished job stays queued, a cancelled one goes."""
561
- _pm, p = project_or_fail(resolve)
562
- job = find_job(p, args["job_id"])
563
- out = {"ok": True, "job_id": args["job_id"], "state": state or "complete"}
564
- if job:
565
- out["output"] = os.path.join(job.get("TargetDir", ""), job.get("OutputFilename", ""))
566
- # a finished render keeps its job, so the queue records what made each file (field report 1007);
567
- # a cancelled one is taken back out
568
- if out["state"] == "complete":
569
- out["job_kept"] = True
570
- else:
571
- p.DeleteRenderJob(args["job_id"])
572
- r = args.get("restore") or {}
573
- if r.get("tracks"): # the tracks we switched off for this job, back on (Edit page, read back)
574
- t = next((x for x in timelines(p) if x.GetName() == r.get("rendered")), None)
575
- if t:
576
- p.SetCurrentTimeline(t)
577
- bad = set_video_tracks(resolve, t, r["tracks"], True)
578
- out["tracks_restored"] = bool(t) and not bad
579
- out["tracks"] = r["tracks"]
580
- if r.get("timeline"):
581
- for t in timelines(p):
582
- if t.GetName() == r["timeline"]:
583
- p.SetCurrentTimeline(t)
584
- break
585
- if r.get("page") and resolve.GetCurrentPage() != r["page"]:
586
- resolve.OpenPage(r["page"])
587
- return out
588
-
589
-
590
- # ── the renderplugin (conform.tools render plugin) ───────────────────────────────────────
591
- #
592
- # Resolve's scripting API cannot select a plugin codec (GetRenderFormats omits it), but a saved
593
- # render preset can: it stores "<pluginUUID>:<codecUUID>". We ship that preset
594
- # (presets/conform.tools.xml) and import it with Resolve.ImportRenderPreset, which names the preset
595
- # after the FILE and also SELECTS it, so the user's Deliver settings are snapshotted around it.
596
- # Presets live per Resolve database: ensure on every QC run.
597
-
598
- # Resolve names an imported preset after its FILE (presets/conform.tools.xml) and may cut the name at
599
- # the first dot ("conform"); a cut name is renamed back below. Earlier names of ours are renamed to it.
600
- QC_PRESET = "conform.tools"
601
- LEGACY_PRESETS = ("CONFORM.TOOLS", "CONFORM.TOOLS QC", "Conform Tools QC")
602
- QC_REPORTS = ("qc_report.json", "qc_audio.json", "qc_filmstrip.jpg")
603
-
604
-
605
- def _codec_id(xml_text):
606
- import re
607
- m = re.search(r"<RecordFormatSubType>([^<]+)</RecordFormatSubType>", xml_text or "")
608
- return m.group(1).strip().upper() if m else ""
609
-
610
-
611
- def _saved_codec_id(resolve, name):
612
- """The codec a saved preset really selects (export it and read it); None when unknowable."""
613
- import glob
614
- import shutil
615
- import tempfile
616
- exporter = getattr(resolve, "ExportRenderPreset", None)
617
- if exporter is None:
618
- return None
619
- d = tempfile.mkdtemp(prefix="ct_preset_")
620
- try:
621
- exporter(name, d) # the 2nd argument is a DIRECTORY; returns True regardless: trust the file
622
- for f in glob.glob(os.path.join(d, "*.xml")):
623
- with open(f) as fh:
624
- return _codec_id(fh.read()) or None
625
- return None
626
- except Exception:
627
- return None
628
- finally:
629
- shutil.rmtree(d, ignore_errors=True)
630
-
631
-
632
- def _keeping_settings(project, fn):
633
- """Run fn() and put the user's Deliver settings back (import and load both SELECT a preset)."""
634
- keep = "%s%d_%d" % (KEEP_PREFIX, os.getpid(), int(time.time() * 1000))
635
- kept = bool(project.SaveAsNewRenderPreset(keep))
636
- try:
637
- return fn()
638
- finally:
639
- if kept:
640
- project.LoadRenderPreset(keep)
641
- project.DeleteRenderPreset(keep)
642
-
643
-
644
- def _rename_preset(project, src, dst):
645
- project.LoadRenderPreset(src)
646
- if not project.SaveAsNewRenderPreset(dst):
647
- return False
648
- project.DeleteRenderPreset(src)
649
- return True
650
-
651
-
652
- def _deliver_ready(resolve, project):
653
- """Open the Deliver page and give its panel a moment before touching render presets, and sweep
654
- snapshot presets an interrupted earlier run left behind (ours only: the __ct_keep_ prefix).
655
- Measured 2026-10-01 on Resolve Studio 20.3.2: a first renderplugin run on a project whose Deliver
656
- page had never been opened aborted Resolve inside its Deliver panel (assertion
657
- GetUseProjectTimelineFilter in UiDeliverPanelTimelineController); the same calls on a project
658
- whose Deliver page had been opened ran clean. This is the precaution; the exact trigger is not
659
- proven. Returns the page to restore."""
660
- page = resolve.GetCurrentPage()
661
- if page != "deliver":
662
- resolve.OpenPage("deliver")
663
- time.sleep(1.0)
664
- for name in project.GetRenderPresetList() or []:
665
- if name.startswith((KEEP_PREFIX, ROUTE_PREFIX)):
666
- project.DeleteRenderPreset(name)
667
- return page
668
-
669
-
670
- def a_renderplugin_preset(resolve, args):
671
- """Make sure the conform.tools render preset exists and selects OUR codec. Never deletes a preset
672
- the user named; replaces ours when it is stale; renames a legacy name of ours. The user's page and
673
- Deliver settings are put back."""
674
- _pm, p = project_or_fail(resolve)
675
- with open(args["preset_path"]) as fh:
676
- expected = _codec_id(fh.read())
677
- page = _deliver_ready(resolve, p)
678
- try:
679
- presets = p.GetRenderPresetList() or []
680
- if QC_PRESET in presets:
681
- got = _saved_codec_id(resolve, QC_PRESET)
682
- if got is None or got == expected:
683
- return {"ok": True, "preset": QC_PRESET, "imported": False}
684
- _keeping_settings(p, lambda: p.DeleteRenderPreset(QC_PRESET))
685
- replaced = True
686
- else:
687
- replaced = False
688
- for legacy in LEGACY_PRESETS:
689
- if legacy in presets:
690
- got = _saved_codec_id(resolve, legacy)
691
- if got is None or got == expected:
692
- if _keeping_settings(p, lambda: _rename_preset(p, legacy, QC_PRESET)):
693
- return {"ok": True, "preset": QC_PRESET, "imported": False, "renamed_from": legacy}
694
- importer = getattr(resolve, "ImportRenderPreset", None)
695
- if importer is None:
696
- fail("no_preset_import", "this Resolve cannot import render presets (Resolve 19 or later can)")
697
- before = set(p.GetRenderPresetList() or [])
698
- _keeping_settings(p, lambda: importer(os.path.abspath(args["preset_path"])))
699
- after = p.GetRenderPresetList() or []
700
- if QC_PRESET not in after:
701
- new = [x for x in after if x not in before]
702
- if len(new) == 1: # Resolve may cut the name at the first dot
703
- _keeping_settings(p, lambda: _rename_preset(p, new[0], QC_PRESET))
704
- if QC_PRESET not in (p.GetRenderPresetList() or []):
705
- fail("preset_import_failed", "Resolve did not import the conform.tools render preset")
706
- return {"ok": True, "preset": QC_PRESET, "imported": True, "replaced": replaced}
707
- finally:
708
- if resolve.GetCurrentPage() != page:
709
- resolve.OpenPage(page)
710
-
711
-
712
- def _write_qc_config(folder, config):
713
- """<render folder>/qc_config.txt, flat key=value lines the codec reads at its first frame. No config:
714
- remove any stale one so the codec runs every check."""
715
- path = os.path.join(folder, "qc_config.txt")
716
- if not config:
717
- if os.path.exists(path):
718
- os.remove(path)
719
- return
720
- lines = ["color_space=%s" % (config.get("color_space") or "sdr_rec709")]
721
- if config.get("id"):
722
- lines.append("template_id=%s" % config["id"])
723
- for check, params in (config.get("checks") or {}).items():
724
- params = params or {}
725
- lines.append("%s.enabled=%d" % (check, 1 if params.get("enabled", True) else 0))
726
- for k, v in params.items():
727
- if k != "enabled":
728
- lines.append("%s.%s=%s" % (check, k, int(v) if isinstance(v, bool) else v))
729
- with open(path, "w") as fh:
730
- fh.write("\n".join(lines) + "\n")
731
-
732
-
733
- def a_clips(resolve, args):
734
- """The video items of a timeline (absolute frames, end exclusive) + its start frame and raster:
735
- what maps a measured frame to the clip that composites it."""
736
- _pm, p = project_or_fail(resolve)
737
- t = find_timeline(p, args.get("timeline"))
738
- out = []
739
- for track in range(1, int(t.GetTrackCount("video") or 0) + 1):
740
- for i, it in enumerate(t.GetItemListInTrack("video", track) or []):
741
- out.append({"id": "%d:%d" % (track, i), "name": it.GetName(), "start": int(it.GetStart()),
742
- "end": int(it.GetEnd()), "track": track})
743
- return {"ok": True, "timeline": t.GetName(), "start_frame": int(t.GetStartFrame()),
744
- "end_frame": int(t.GetEndFrame()),
745
- "width": int(float(t.GetSetting("timelineResolutionWidth") or 0)),
746
- "height": int(float(t.GetSetting("timelineResolutionHeight") or 0)),
747
- "fps": t.GetSetting("timelineFrameRate"), "clips": out}
748
-
749
-
750
- def a_markers(resolve, args):
751
- """Place or clear OUR markers on a timeline. Ours carry customData starting with the tag; a marker
752
- someone else placed is never edited or deleted, and a frame they occupy is skipped and reported."""
753
- _pm, p = project_or_fail(resolve)
754
- t = find_timeline(p, args.get("timeline"))
755
- prefix = args["tag"]
756
-
757
- def ours_by_frame():
758
- return dict((int(f), m) for f, m in (t.GetMarkers() or {}).items()
759
- if str(m.get("customData") or "").startswith(prefix))
760
-
761
- cleared = 0
762
- if args.get("clear"):
763
- for f in ours_by_frame():
764
- if t.DeleteMarkerAtFrame(f):
765
- cleared += 1
766
- placed, skipped = 0, []
767
- for m in args.get("place") or []:
768
- f = int(m["frame"]) # relative to the timeline start, as Resolve counts markers
769
- everyone = t.GetMarkers() or {}
770
- if f in ours_by_frame():
771
- t.DeleteMarkerAtFrame(f) # re-running replaces our own marker, never stacks a second
772
- elif f in everyone or float(f) in everyone:
773
- skipped.append(f) # someone else's: leave it
774
- continue
775
- if t.AddMarker(f, m.get("color", "Red"), m.get("name", "conform.tools"), m.get("note", ""),
776
- max(1, int(m.get("duration", 1))), m.get("tag", prefix)):
777
- placed += 1
778
- else:
779
- skipped.append(f)
780
- return {"ok": True, "timeline": t.GetName(), "placed": placed, "cleared": cleared, "skipped": skipped}
781
-
782
-
783
- # ── render presets: read and author what the scripting API cannot set ──────────────────────
784
- #
785
- # The API has no key for the Deliver page's audio OUTPUT routing (which timeline track or bus feeds
786
- # each output track) — but a render preset stores it, and Resolve exports/imports presets as XML.
787
- # Decoded 2026-10-06 (LITTLE DYNAMO field report, Resolve 21.1; all 60 presets round-trip
788
- # byte-exact): <FieldsBlob> is a hex Qt QDataStream map — u32 version, u32 count, then (QString key,
789
- # QVariant value)*; QString = u32 byte length + UTF-16BE; QVariant = u32 type + u8 null + payload
790
- # (1 bool, 2 int32, 3 uint32, 10 QString, 12 QByteArray = a nested map). Routing lives in
791
- # RenderAudioTracks {"0": {TrackInfoType 0 = timeline track | 1 = bus, TrackInfoValue n (1-based)}, ...},
792
- # mirrored by RecordAudioNormalizationOutputTracksEnableState and ExtraInfoMap aud_src_config
793
- # ("TRK0:TRK1" = timeline tracks 1 and 2, "AUX0" = bus 1).
794
-
795
- ROUTE_PREFIX = "__ct_route_"
796
-
797
-
798
- def _qs(v):
799
- b = v.encode("utf-16-be")
800
- return struct.pack(">I", len(b)) + b
801
-
802
-
803
- def _rqs(b, i):
804
- n, = struct.unpack_from(">I", b, i)
805
- i += 4
806
- return (None, i) if n == 0xffffffff else (b[i:i + n].decode("utf-16-be"), i + n)
807
-
808
-
809
- def blob_decode(b):
810
- _ver, cnt = struct.unpack_from(">II", b, 0)
811
- i, d = 8, {}
812
- for _ in range(cnt):
813
- k, i = _rqs(b, i)
814
- t, = struct.unpack_from(">I", b, i)
815
- i += 5
816
- if t == 1:
817
- v = bool(b[i]); i += 1
818
- elif t == 2:
819
- v, = struct.unpack_from(">i", b, i); i += 4
820
- elif t == 3:
821
- v, = struct.unpack_from(">I", b, i); i += 4
822
- elif t == 10:
823
- v, i = _rqs(b, i)
824
- elif t == 12:
825
- n, = struct.unpack_from(">I", b, i); i += 4
826
- raw = b[i:i + n]; i += n
827
- try:
828
- v = blob_decode(raw)
829
- except Exception:
830
- v = raw
831
- else:
832
- raise ValueError("QVariant type %d for %r" % (t, k))
833
- d[k] = v
834
- if i != len(b):
835
- raise ValueError("trailing bytes in FieldsBlob")
836
- return d
837
-
838
-
839
- def blob_encode(d, ver=1):
840
- out = struct.pack(">II", ver, len(d))
841
- for k, v in d.items():
842
- out += _qs(k)
843
- if isinstance(v, bool):
844
- out += struct.pack(">IBB", 1, 0, v)
845
- elif isinstance(v, int):
846
- out += struct.pack(">IBi", 2, 0, v)
847
- elif isinstance(v, str):
848
- out += struct.pack(">IB", 10, 0) + _qs(v)
849
- elif isinstance(v, dict):
850
- raw = blob_encode(v)
851
- out += struct.pack(">IBI", 12, 0, len(raw)) + raw
852
- elif isinstance(v, bytes):
853
- out += struct.pack(">IBI", 12, 0, len(v)) + v
854
- else:
855
- raise TypeError(k)
856
- return out
857
-
858
-
859
- def _xml_field(xml, k):
860
- m = re.search(r"<%s>([^<]*)</%s>" % (k, k), xml)
861
- return m.group(1) if m else None
862
-
863
-
864
- def _extra(xml, k):
865
- m = re.search(r"<DbKey>%s</DbKey>\s*<DbVal>([^<]*)</DbVal>" % re.escape(k), xml)
866
- return m.group(1) if m else None
867
-
868
-
869
- def _fields(xml):
870
- m = re.search(r"<FieldsBlob>([0-9a-fA-F]*)</FieldsBlob>", xml)
871
- return blob_decode(bytes.fromhex(m.group(1))) if m else {}
872
-
873
-
874
- def preset_summary(xml):
875
- """What a preset renders: container, codec, raster, audio codec and output routing."""
876
- f = _fields(xml)
877
- routing = []
878
- for _k, o in sorted((f.get("RenderAudioTracks") or {}).items(), key=lambda kv: int(kv[0])):
879
- if isinstance(o, dict):
880
- routing.append(("Bus %d" if o.get("TrackInfoType") == 1 else "Timeline Track %d") % o.get("TrackInfoValue", 0))
881
- return {"format": _xml_field(xml, "RecordFormatType"), "codec": _xml_field(xml, "RecordFormatSubType"),
882
- "width": _xml_field(xml, "FormatWidth"), "height": _xml_field(xml, "FormatHeight"),
883
- "audio": _xml_field(xml, "RecordAudioEnabled"), "audio_codec": _extra(xml, "aud_codec"),
884
- "audio_outputs": routing, "discrete_audio": _extra(xml, "aud_discrete") == "1"}
885
-
886
-
887
- def with_audio_tracks(xml, tracks):
888
- """The preset with Deliver > Audio output n fed by timeline track tracks[n] (1-based), and a fresh DbId."""
889
- m = re.search(r"<FieldsBlob>([0-9a-fA-F]*)</FieldsBlob>", xml)
890
- if not m:
891
- raise ValueError("not a Resolve render preset (no FieldsBlob)")
892
- f = blob_decode(bytes.fromhex(m.group(1)))
893
- f["RenderAudioTracks"] = dict((str(i), {"TrackInfoValue": int(n), "TrackInfoType": 0}) for i, n in enumerate(tracks))
894
- f["RecordAudioNormalizationOutputTracksEnableState"] = dict((str(i), 1) for i in range(len(tracks)))
895
- x = xml[:m.start(1)] + blob_encode(f).hex() + xml[m.end(1):]
896
- x = re.sub(r"(<DbKey>aud_src_config</DbKey>\s*<DbVal>)[^<]*(</DbVal>)",
897
- lambda g: g.group(1) + ":".join("TRK%d" % (int(n) - 1) for n in tracks) + g.group(2), x)
898
- x = re.sub(r"<RecordAudioEnabled>[^<]*</RecordAudioEnabled>", "<RecordAudioEnabled>true</RecordAudioEnabled>", x)
899
- return re.sub(r'DbId="[^"]+"', 'DbId="%s"' % uuid.uuid4(), x, 1)
900
-
901
-
902
- def _export_xml(resolve, name):
903
- d = tempfile.mkdtemp(prefix="ct_preset_")
904
- try:
905
- resolve.ExportRenderPreset(name, d) # a DIRECTORY; returns True regardless: trust the file
906
- for root, _dirs, files in os.walk(d):
907
- for fn in files:
908
- if fn.endswith(".xml"):
909
- with open(os.path.join(root, fn), encoding="utf-8") as fh:
910
- return fh.read()
911
- return None
912
- finally:
913
- shutil.rmtree(d, ignore_errors=True)
914
-
915
-
916
- def _import_xml(resolve, p, xml, name):
917
- """Import xml as preset `name` (Resolve names it after the file; no dots in ours). It also SELECTS it."""
918
- d = tempfile.mkdtemp(prefix="ct_preset_")
919
- try:
920
- path = os.path.join(d, name + ".xml")
921
- with open(path, "w", encoding="utf-8") as fh:
922
- fh.write(xml)
923
- resolve.ImportRenderPreset(path)
924
- finally:
925
- shutil.rmtree(d, ignore_errors=True)
926
- return name in (p.GetRenderPresetList() or [])
927
-
928
-
929
- def _routed_settings(resolve, p, tracks):
930
- """Make the Deliver page's CURRENT settings route audio output n from timeline track tracks[n]:
931
- snapshot → export → rewrite the routing → import (which selects it). Returns the preset to delete."""
932
- snap = "%s%d_%d" % (ROUTE_PREFIX, os.getpid(), int(time.time() * 1000))
933
- if not p.SaveAsNewRenderPreset(snap):
934
- fail("render_refused", "Resolve would not snapshot the render settings to set the audio routing")
935
- xml = _export_xml(resolve, snap)
936
- p.DeleteRenderPreset(snap)
937
- if not xml:
938
- fail("render_refused", "Resolve did not export the render settings, so the audio routing cannot be set")
939
- if not _import_xml(resolve, p, with_audio_tracks(xml, tracks), snap) or not p.LoadRenderPreset(snap):
940
- fail("render_refused", "Resolve did not take the preset with the audio routing")
941
- return snap
942
-
943
-
944
- def a_presets(resolve, args):
945
- """Every render preset (or `names`) with what it renders, including the audio output routing."""
946
- _pm, p = project_or_fail(resolve)
947
- page = _deliver_ready(resolve, p)
948
- try:
949
- want = args.get("names") or [n for n in (p.GetRenderPresetList() or []) if not n.startswith(("__ct_",))]
950
- out = []
951
- for n in want:
952
- xml = _export_xml(resolve, n)
953
- row = {"name": n}
954
- try:
955
- row.update(preset_summary(xml) if xml else {"error": "Resolve did not export it"})
956
- except Exception as e:
957
- row["error"] = "could not read: %s" % e
958
- out.append(row)
959
- return {"ok": True, "project": p.GetName(), "presets": out}
960
- finally:
961
- if resolve.GetCurrentPage() != page:
962
- resolve.OpenPage(page)
963
-
964
-
965
- def a_preset_author(resolve, args):
966
- """Save a new preset = `base` (a preset, or the Deliver page's current settings) with the audio
967
- outputs fed by timeline tracks `audio_tracks`. Never replaces an existing preset."""
968
- _pm, p = project_or_fail(resolve)
969
- name = args["name"]
970
- if "." in name:
971
- fail("invalid_args", "Resolve cuts an imported preset's name at the first dot: use a name without dots")
972
- if name in (p.GetRenderPresetList() or []):
973
- fail("exists", "a render preset named %r already exists; pick another name (we never replace one)" % name)
974
- page = _deliver_ready(resolve, p)
975
-
976
- def go():
977
- if args.get("base"):
978
- if args["base"] not in (p.GetRenderPresetList() or []):
979
- fail("no_preset", "no render preset named %r" % args["base"], presets=p.GetRenderPresetList() or [])
980
- xml = _export_xml(resolve, args["base"])
981
- else:
982
- snap = "%s%d" % (ROUTE_PREFIX, os.getpid())
983
- p.SaveAsNewRenderPreset(snap)
984
- xml = _export_xml(resolve, snap)
985
- p.DeleteRenderPreset(snap)
986
- if not xml:
987
- fail("render_refused", "Resolve did not export the base settings")
988
- if not _import_xml(resolve, p, with_audio_tracks(xml, args["audio_tracks"]), name):
989
- fail("preset_import_failed", "Resolve did not import the new preset")
990
- back = _export_xml(resolve, name)
991
- return {"ok": True, "preset": name, "summary": preset_summary(back) if back else None}
992
- try:
993
- return _keeping_settings(p, go)
994
- finally:
995
- if resolve.GetCurrentPage() != page:
996
- resolve.OpenPage(page)
997
-
998
-
999
- ACTIONS = {
1000
- "version": a_version,
1001
- "current": a_current,
1002
- "project": a_project,
1003
- "export": a_export,
1004
- "open": a_open,
1005
- "render_start": a_render_start,
1006
- "render_status": a_render_status,
1007
- "render_cancel": a_render_cancel,
1008
- "render_finish": a_render_finish,
1009
- "renderplugin_preset": a_renderplugin_preset,
1010
- "clips": a_clips,
1011
- "markers": a_markers,
1012
- "presets": a_presets,
1013
- "preset_author": a_preset_author,
1014
- }
1015
-
1016
-
1017
- def main():
1018
- if len(sys.argv) < 2 or sys.argv[1] not in ACTIONS:
1019
- fail("usage", "bridge.py <%s> '<json>'" % "|".join(sorted(ACTIONS)))
1020
- try:
1021
- args = json.loads(sys.argv[2]) if len(sys.argv) > 2 else {}
1022
- except ValueError as e:
1023
- fail("usage", "arguments are not JSON: %s" % e)
1024
- resolve = connect()
1025
- t0 = time.time()
1026
- try:
1027
- out = ACTIONS[sys.argv[1]](resolve, args)
1028
- except SystemExit:
1029
- raise
1030
- except Exception as e: # report Resolve's own failure verbatim; never a traceback on stdout
1031
- fail("resolve_error", "%s: %s" % (type(e).__name__, e))
1032
- out["ms"] = int((time.time() - t0) * 1000)
1033
- reply(out)
1034
-
1035
-
1036
- if __name__ == "__main__":
1037
- main()