conformtools 0.6.4 → 0.6.6

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 (148) hide show
  1. package/README.md +3 -3
  2. package/dist/account-HDXVTS5T.js +3 -0
  3. package/dist/avid-panel/MANIFEST.json +11 -0
  4. package/dist/avid-panel/avid-manifest.json +46 -0
  5. package/dist/avid-panel/icon.svg +4 -0
  6. package/dist/avid-panel/icons/conformtools.svg +4 -0
  7. package/dist/avid-panel/index.html +26 -0
  8. package/dist/avid-panel/panel.css +12 -0
  9. package/dist/avid-panel/panel.js +7 -0
  10. package/dist/bridge-D5KPIUSY.js +3 -0
  11. package/dist/browser/timeline_core_bg.wasm +0 -0
  12. package/dist/chunk-3OCQA33E.js +3 -0
  13. package/dist/chunk-3XD6NC4G.js +10 -0
  14. package/dist/chunk-5JBUCVRI.js +20 -0
  15. package/dist/chunk-5RSNFPED.js +8 -0
  16. package/dist/{chunk-BW2NQ54J.js → chunk-5SUGU2YR.js} +1 -1
  17. package/dist/{chunk-HKP4P6JN.js → chunk-6ML26TIK.js} +1 -1
  18. package/dist/chunk-7MC7M2Y5.js +3 -0
  19. package/dist/chunk-AS7IXHYM.js +19 -0
  20. package/dist/chunk-BL6L5ZBP.js +39 -0
  21. package/dist/chunk-C5IX63YF.js +3 -0
  22. package/dist/chunk-EJGVNQ3E.js +8 -0
  23. package/dist/{chunk-EPZ6NWE4.js → chunk-HGDO3OED.js} +1 -1
  24. package/dist/chunk-JV7TZDKJ.js +3 -0
  25. package/dist/chunk-LFJLRLEP.js +3 -0
  26. package/dist/chunk-NFJHWZJX.js +3 -0
  27. package/dist/{chunk-WT6NIJCB.js → chunk-NQHQKEP5.js} +1 -1
  28. package/dist/chunk-NU3X7P4N.js +3 -0
  29. package/dist/chunk-OJWIBQK4.js +376 -0
  30. package/dist/chunk-OVUCL3YY.js +5 -0
  31. package/dist/chunk-PFISREY4.js +3 -0
  32. package/dist/chunk-PFZVET7S.js +3 -0
  33. package/dist/chunk-PLRB2YXJ.js +3 -0
  34. package/dist/chunk-RFIPLBQ4.js +5 -0
  35. package/dist/chunk-SZD4C5MB.js +6 -0
  36. package/dist/chunk-TXQR2HI2.js +4 -0
  37. package/dist/chunk-UKKRZ574.js +7 -0
  38. package/dist/{chunk-EO5NIBOV.js → chunk-VS3MKKJ5.js} +1 -1
  39. package/dist/{chunk-42QQI3WX.js → chunk-X53BNWNV.js} +1 -1
  40. package/dist/{chunk-QTPCU2TF.js → chunk-XNR7M4VX.js} +1 -1
  41. package/dist/{claude-setup-BM3AAUKR.js → claude-setup-IIWUB4CE.js} +1 -1
  42. package/dist/cli.js +8 -8
  43. package/dist/conformtools-analyze +0 -0
  44. package/dist/conformtools-decode +0 -0
  45. package/dist/{cr3-wasm-WKWMEK3V.js → cr3-wasm-L2LFY3LM.js} +1 -1
  46. package/dist/{dng-wasm-Z5OVO4UI.js → dng-wasm-U6NC3MDK.js} +1 -1
  47. package/dist/{dpx-wasm-QNYXAOAJ.js → dpx-wasm-RMKEUKED.js} +1 -1
  48. package/dist/engine-P6H5P6HP.js +5 -0
  49. package/dist/{exr-wasm-BHSBJLQH.js → exr-wasm-LBAOMOZD.js} +1 -1
  50. package/dist/flame/hook/conformtools_flame/__init__.py +10 -0
  51. package/dist/flame/hook/conformtools_flame/building.py +191 -0
  52. package/dist/flame/hook/conformtools_flame/hook.py +177 -0
  53. package/dist/flame/hook/conformtools_flame/render.py +622 -0
  54. package/dist/flame/hook/conformtools_flame/util.py +33 -0
  55. package/dist/flame/hook/conformtools_flame/verbs.py +1037 -0
  56. package/dist/flame/hook/conformtools_flame_hook.py +42 -0
  57. package/dist/fonts/gfx/BarlowCondensed-Bold.ttf +0 -0
  58. package/dist/fonts/gfx/BarlowCondensed-Regular.ttf +0 -0
  59. package/dist/fonts/gfx/InstrumentSerif-Regular.ttf +0 -0
  60. package/dist/fonts/gfx/Inter-Bold.ttf +0 -0
  61. package/dist/fonts/gfx/Inter-Regular.ttf +0 -0
  62. package/dist/fonts/gfx/JetBrainsMono-Bold.ttf +0 -0
  63. package/dist/fonts/gfx/JetBrainsMono-Regular.ttf +0 -0
  64. package/dist/fonts/gfx/OFL.txt +100 -0
  65. package/dist/framing-SRCJKAYO.js +3 -0
  66. package/dist/gfx-worker.js +3 -0
  67. package/dist/h264-3ESGVT6G.js +3 -0
  68. package/dist/{h264-mxf-MWS7DDV7.js → h264-mxf-NPFS7NGH.js} +1 -1
  69. package/dist/host-relink-D6CB2VOQ.js +10 -0
  70. package/dist/hosts-W4AD2MYH.js +3 -0
  71. package/dist/http.js +3 -2
  72. package/dist/i2o-transfer +0 -0
  73. package/dist/inspect-7ASUPU73.js +68 -0
  74. package/dist/isobmff-SIOE67WL.js +3 -0
  75. package/dist/mcp.js +7 -8
  76. package/dist/media-7AUNRKHF.js +3 -0
  77. package/dist/media_core-Q2PIEV7D.js +9 -0
  78. package/dist/{media_core_bg-FGAR5KA5.js → media_core_bg-FDL7GJZP.js} +1 -1
  79. package/dist/mxf-74TTDICM.js +3 -0
  80. package/dist/nuke/panel/python/Startup/conformtools_nuke_startup.py +44 -0
  81. package/dist/nuke/panel/python/conformtools_nuke/__init__.py +10 -0
  82. package/dist/nuke/panel/python/conformtools_nuke/panel.py +217 -0
  83. package/dist/nuke/panel/python/conformtools_nuke/verbs.py +837 -0
  84. package/dist/{ops-73NR3X6R.js → ops-FSOOBXMV.js} +1 -1
  85. package/dist/peer-kit/ctpeer/__init__.py +21 -0
  86. package/dist/peer-kit/ctpeer/client.py +247 -0
  87. package/dist/peer-kit/ctpeer/neutral.py +178 -0
  88. package/dist/peer-kit/ctpeer/pairing.py +139 -0
  89. package/dist/peer-kit/ctpeer/protocol.py +209 -0
  90. package/dist/peer-kit/ctpeer/websocket.py +289 -0
  91. package/dist/premiere-uxp/index.js +5 -5
  92. package/dist/premiere-uxp/lib/clipmeta.js +6 -6
  93. package/dist/premiere-uxp/lib/ctx.js +30 -24
  94. package/dist/premiere-uxp/lib/edit.js +516 -0
  95. package/dist/premiere-uxp/lib/markers.js +5 -5
  96. package/dist/premiere-uxp/lib/pairing.js +14 -5
  97. package/dist/premiere-uxp/lib/premiere.js +10 -1
  98. package/dist/premiere-uxp/lib/probe.js +102 -0
  99. package/dist/premiere-uxp/lib/render.js +15 -8
  100. package/dist/premiere-uxp/lib/session.js +1 -1
  101. package/dist/premiere-uxp/lib/sizing.js +30 -17
  102. package/dist/premiere-uxp/lib/time.js +7 -1
  103. package/dist/premiere-uxp/lib/timeline.js +2 -2
  104. package/dist/premiere-uxp/lib/verbs.js +3 -2
  105. package/dist/premiere-uxp/lib/write.js +3 -3
  106. package/dist/premiere-uxp/manifest.json +1 -1
  107. package/dist/probe-F7WQHMIA.js +3 -0
  108. package/dist/r3d-YTLOMC7C.js +3 -0
  109. package/dist/{r3d-VUOYU2KQ.js → r3d-ZDJ3WURS.js} +1 -1
  110. package/dist/resolve-bridge.py +1262 -13
  111. package/dist/{still-4G25EYN5.js → still-ZG2RUQAL.js} +1 -1
  112. package/dist/store-ZHXLQCGN.js +3 -0
  113. package/dist/{tiff-wasm-QJPCR7JT.js → tiff-wasm-D2FJ3L56.js} +1 -1
  114. package/dist/timeline-6DYFDVEH.js +3 -0
  115. package/dist/timeline_core-IOENXK4Z.js +3 -0
  116. package/dist/wasm/media_core_bg.wasm +0 -0
  117. package/dist/wasm-threads/media_core_bg.wasm +0 -0
  118. package/dist/wav-OWMUGQMM.js +3 -0
  119. package/package.json +6 -4
  120. package/dist/chunk-6FVGUJ6L.js +0 -3
  121. package/dist/chunk-6TM32YIJ.js +0 -7
  122. package/dist/chunk-BUEIRRNY.js +0 -3
  123. package/dist/chunk-CL26XMDO.js +0 -3
  124. package/dist/chunk-DRHOPOC7.js +0 -3
  125. package/dist/chunk-GXEVALBL.js +0 -3
  126. package/dist/chunk-JB7PR2TQ.js +0 -3
  127. package/dist/chunk-QDWB7QU7.js +0 -3
  128. package/dist/chunk-QTKRMXL5.js +0 -363
  129. package/dist/chunk-SP5RGDAM.js +0 -3
  130. package/dist/chunk-TEZP6VEQ.js +0 -3
  131. package/dist/chunk-Y2BEEOPB.js +0 -3
  132. package/dist/h264-LIZVHN2W.js +0 -3
  133. package/dist/inspect-DZF537QL.js +0 -46
  134. package/dist/isobmff-HM3UPWPZ.js +0 -3
  135. package/dist/media_core-R5PPN3AY.js +0 -9
  136. package/dist/mxf-K465SWBN.js +0 -3
  137. package/dist/onnxruntime-web-stub-PKJ2NZBF.js +0 -3
  138. package/dist/r3d-RR3FUM6H.js +0 -3
  139. package/dist/sscd-embed-DHFTEIOC.js +0 -3
  140. package/dist/sscd-sweep-OYS4XAID.js +0 -3
  141. package/dist/timeline_core-VK2ZWPCO.js +0 -3
  142. package/dist/wav-63QF6SCT.js +0 -3
  143. /package/dist/{arriraw-3GKCR6K2.js → arriraw-YIJ3BYNN.js} +0 -0
  144. /package/dist/{chunk-WHY3DVXS.js → chunk-D6YDLKSA.js} +0 -0
  145. /package/dist/{media_core_bg-YK63OUDM.js → media_core_bg-XRBVKQZH.js} +0 -0
  146. /package/dist/{prores-L4JZZWGH.js → prores-RIG37OIH.js} +0 -0
  147. /package/dist/{timeline_core_bg-2TYWZ35G.js → timeline_core_bg-JW42YM3G.js} +0 -0
  148. /package/dist/{udf_bg-A4WEMSAX.js → udf_bg-B37GKRIH.js} +0 -0
@@ -144,8 +144,12 @@ def pool_folder(media_pool, path, create=False):
144
144
  def a_project(resolve, args):
145
145
  """Read-only project awareness: the media pool tree (folders, clip counts, optionally every clip
146
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)
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):
149
153
  mp = p.GetMediaPool()
150
154
  want_clips = bool(args.get("clips"))
151
155
  finds = [str(q) for q in args.get("find") or []]
@@ -159,8 +163,8 @@ def a_project(resolve, args):
159
163
  rows = []
160
164
  for c in clips:
161
165
  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}
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 ""}
164
168
  rows.append(row)
165
169
  for q in finds:
166
170
  if ("/" in q and row["file"] and os.path.normpath(row["file"]) == os.path.normpath(q)) or (
@@ -193,8 +197,14 @@ def a_export(resolve, args):
193
197
  Resolve's Export is fussy about the target path (spaces / non-ASCII / a folder instead of a
194
198
  file all come back as a bare False), so it always writes to a plain ASCII temp file that we
195
199
  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)
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)
198
208
  t = find_timeline(p, args.get("timeline"))
199
209
  out = args["out_path"]
200
210
  if os.path.isdir(out) or not os.path.splitext(out)[1]:
@@ -226,7 +236,58 @@ def a_export(resolve, args):
226
236
  shutil.move(tmp, out)
227
237
  finally:
228
238
  shutil.rmtree(tmp_dir, ignore_errors=True)
229
- return {"ok": True, "path": out, "format": "drt", "project": p.GetName(), "timeline": t.GetName()}
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()}
230
291
 
231
292
 
232
293
  def safe_name(name):
@@ -271,10 +332,27 @@ def named_media(path):
271
332
  except OSError:
272
333
  return []
273
334
  found = re.findall(r"<MediaFilePath>([^<]+)</MediaFilePath>", text)
274
- found += [unquote(u) for u in re.findall(r"file://(?:localhost)?(/[^<\"]+)", text)]
335
+ found += [url_path(u) for u in re.findall(r"file://(?:localhost)?(/[^<\"]+)", text)]
275
336
  return sorted({unicodedata.normalize("NFC", m.replace("&amp;", "&")) for m in found})
276
337
 
277
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
+
278
356
  def pool_ids(folder):
279
357
  ids = {c.GetMediaId() for c in folder.GetClipList() or []}
280
358
  for sub in folder.GetSubFolderList() or []:
@@ -286,14 +364,14 @@ def mislinked(tl, named, before):
286
364
  """Items linked to a clip that was in the pool BEFORE the import and is a file the timeline file
287
365
  does not name: [(clip, frame, linked path)]. Clips the import made are its own (any path form)."""
288
366
  import unicodedata
289
- want, out = set(named), []
367
+ want, out = {same_file_key(m) for m in named}, []
290
368
  for ti in range(1, (tl.GetTrackCount("video") or 0) + 1):
291
369
  for it in tl.GetItemListInTrack("video", ti) or []:
292
370
  m = it.GetMediaPoolItem()
293
371
  if not m or m.GetMediaId() not in before:
294
372
  continue
295
373
  got = unicodedata.normalize("NFC", m.GetClipProperty("File Path") or "")
296
- if got and got not in want:
374
+ if got and same_file_key(got) not in want:
297
375
  out.append((it.GetName(), it.GetStart(), got))
298
376
  return out
299
377
 
@@ -371,6 +449,21 @@ def a_open(resolve, args):
371
449
  fail("import_mislinked", "Resolve linked %d clip(s) to other files than %s names: %s" % (
372
450
  len(wrong), os.path.basename(path), "; ".join("%s at frame %s -> %s" % w for w in wrong[:10])),
373
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)
374
467
  notes = []
375
468
  if tl.GetName() != name: # Resolve may name it after the file
376
469
  tl.SetName(name)
@@ -514,15 +607,19 @@ def _queue_and_start(resolve, p, tl, args, target, page, prev_tl, off):
514
607
  p.DeleteRenderPreset(routed)
515
608
  if kept:
516
609
  p.LoadRenderPreset(keep)
517
- p.DeleteRenderPreset(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.
518
613
  if not p.StartRendering([job]):
519
614
  p.DeleteRenderJob(job)
615
+ if kept:
616
+ p.DeleteRenderPreset(keep)
520
617
  fail("render_refused", "Resolve would not start the job")
521
618
  return {"ok": True, "job_id": job, "timeline": tl.GetName(), "project": p.GetName(),
522
619
  "settings_restored": kept, "disabled_tracks": off, "audio_tracks": args.get("audio_tracks") or [],
523
620
  "rejected_settings": rejected,
524
621
  "restore": {"timeline": prev_tl.GetName() if prev_tl else None, "page": page,
525
- "rendered": tl.GetName(), "tracks": off}}
622
+ "rendered": tl.GetName(), "tracks": off, "keep": keep if kept else None}}
526
623
 
527
624
 
528
625
  def a_render_status(resolve, args):
@@ -541,6 +638,10 @@ def a_render_status(resolve, args):
541
638
  elif not find_job(p, args["job_id"]):
542
639
  state = "failed"
543
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"
544
645
  else:
545
646
  state = "rendering" if rendering else "queued"
546
647
  return {"ok": True, "job_id": args["job_id"], "state": state, "status": status,
@@ -570,6 +671,10 @@ def a_render_finish(resolve, args, state=None):
570
671
  else:
571
672
  p.DeleteRenderJob(args["job_id"])
572
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
573
678
  if r.get("tracks"): # the tracks we switched off for this job, back on (Edit page, read back)
574
679
  t = next((x for x in timelines(p) if x.GetName() == r.get("rendered")), None)
575
680
  if t:
@@ -780,6 +885,982 @@ def a_markers(resolve, args):
780
885
  return {"ok": True, "timeline": t.GetName(), "placed": placed, "cleared": cleared, "skipped": skipped}
781
886
 
782
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
+
783
1864
  # ── render presets: read and author what the scripting API cannot set ──────────────────────
784
1865
  #
785
1866
  # The API has no key for the Deliver page's audio OUTPUT routing (which timeline track or bus feeds
@@ -1009,6 +2090,10 @@ ACTIONS = {
1009
2090
  "renderplugin_preset": a_renderplugin_preset,
1010
2091
  "clips": a_clips,
1011
2092
  "markers": a_markers,
2093
+ "items": a_items,
2094
+ "clip_lut": a_clip_lut,
2095
+ "apply": a_apply,
2096
+ "still": a_still,
1012
2097
  "presets": a_presets,
1013
2098
  "preset_author": a_preset_author,
1014
2099
  }
@@ -1018,7 +2103,12 @@ def main():
1018
2103
  if len(sys.argv) < 2 or sys.argv[1] not in ACTIONS:
1019
2104
  fail("usage", "bridge.py <%s> '<json>'" % "|".join(sorted(ACTIONS)))
1020
2105
  try:
1021
- args = json.loads(sys.argv[2]) if len(sys.argv) > 2 else {}
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)
1022
2112
  except ValueError as e:
1023
2113
  fail("usage", "arguments are not JSON: %s" % e)
1024
2114
  resolve = connect()
@@ -1033,5 +2123,164 @@ def main():
1033
2123
  reply(out)
1034
2124
 
1035
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
+
1036
2285
  if __name__ == "__main__":
1037
2286
  main()