davinci-resolve-mcp 5.0.8 → 5.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -772,42 +772,56 @@ _PROJECT_DIR = os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(_
772
772
 
773
773
 
774
774
  @mcp.tool(annotations=READ_ONLY_TOOL)
775
- def search_resolve_api(pattern: str, kind: str = "all", limit: int = 50) -> Dict[str, Any]:
776
- """Search the shipped Resolve 21.1 typed API stub. Needs no connection.
775
+ def search_resolve_api(pattern: str, kind: str = "all", limit: int = 50,
776
+ source: str = "auto") -> Dict[str, Any]:
777
+ """Search the Resolve typed API stub. Needs no connection.
777
778
 
778
779
  `api_truth` answers what is broken; this answers what exists. Each hit also
779
780
  reports whether THIS server references the method and in which files, so a
780
- search doubles as a parity check.
781
+ search doubles as a parity check. The reply names the stub that answered
782
+ (`stub`, `stub_source`), because "absent" from an outdated inventory is not
783
+ the same as absent from the running build.
781
784
 
782
785
  Args:
783
786
  pattern: Case-insensitive regular expression, e.g. "marker" or "(Get|Set)Setting".
784
787
  kind: 'all' (default), 'methods', or 'options' for TypedDicts only.
785
788
  limit: Maximum results per section (capped at 200).
789
+ source: 'auto' (default) prefers the stub the installed Resolve ships and
790
+ falls back to the shipped copy; 'shipped' forces the pinned file;
791
+ 'installed' refuses when no install is found.
786
792
  """
787
793
  try:
788
- return typed_api_search.search(_PROJECT_DIR, pattern, kind=kind, limit=limit)
794
+ return typed_api_search.search(_PROJECT_DIR, pattern, kind=kind, limit=limit,
795
+ source=source)
789
796
  except typed_api_search.TypedApiError as exc:
790
797
  return {"error": str(exc)}
791
798
 
792
799
 
793
800
  @mcp.tool(annotations=READ_ONLY_TOOL)
794
- def describe_resolve_api(symbol: str) -> Dict[str, Any]:
801
+ def describe_resolve_api(symbol: str, source: str = "auto") -> Dict[str, Any]:
795
802
  """Full typed detail for one Resolve API symbol. Needs no connection.
796
803
 
797
804
  Args:
798
805
  symbol: 'Class.Method' (e.g. "Project.GetName"), a bare method name when
799
806
  it is unambiguous, or a TypedDict name (e.g. "RenderSettings").
807
+ source: 'auto' (default) prefers the installed build's stub; 'shipped'
808
+ forces the pinned copy; 'installed' refuses without an install.
800
809
  """
801
810
  try:
802
- return typed_api_search.describe(_PROJECT_DIR, symbol)
811
+ return typed_api_search.describe(_PROJECT_DIR, symbol, source=source)
803
812
  except typed_api_search.TypedApiError as exc:
804
813
  return {"error": str(exc)}
805
814
 
806
815
 
807
816
  @mcp.tool(annotations=READ_ONLY_TOOL)
808
- def get_resolve_api_surface() -> Dict[str, Any]:
809
- """Counts and object list for the shipped typed stub. Needs no connection."""
817
+ def get_resolve_api_surface(source: str = "auto") -> Dict[str, Any]:
818
+ """Counts and object list for the typed stub. Needs no connection.
819
+
820
+ Args:
821
+ source: 'auto' (default) prefers the installed build's stub; 'shipped'
822
+ forces the pinned copy; 'installed' refuses without an install.
823
+ """
810
824
  try:
811
- return typed_api_search.summary(_PROJECT_DIR)
825
+ return typed_api_search.summary(_PROJECT_DIR, source=source)
812
826
  except typed_api_search.TypedApiError as exc:
813
827
  return {"error": str(exc)}
package/src/server.py CHANGED
@@ -11,7 +11,7 @@ Usage:
11
11
  python src/server.py --full # Start the 377-tool granular server instead
12
12
  """
13
13
 
14
- VERSION = "5.0.8"
14
+ VERSION = "5.2.0"
15
15
 
16
16
  import base64
17
17
  import os
@@ -58,6 +58,7 @@ from src.utils.title_library import list_title_presets as _list_installed_title_
58
58
  from src.utils.title_controls import title_text_targets as _title_text_targets
59
59
  from src.utils.title_controls import title_text_keys as _title_text_keys
60
60
  from src.utils.resolve211_edits import validate_edit_options, validate_transition_options, transition_result
61
+ from src.utils.film_cues import export_cue_sheet as _export_film_cue_sheet
61
62
 
62
63
  # Platform-specific Resolve paths
63
64
  from src.utils.cdl import normalize_cdl_payload
@@ -18706,15 +18707,20 @@ def resolve_control(action: str, params: Optional[Dict[str, Any]] = None) -> Dic
18706
18707
  set_keyframe_mode(mode) -> {success}
18707
18708
  quit() -> {success}
18708
18709
  get_fairlight_presets() -> {presets}
18709
- search_api(pattern, kind?, limit?) -> {methods, option_types, total_matches}
18710
- — regex over the shipped Resolve 21.1 typed stub. Each hit says whether
18711
- THIS server references the method, and where, so it doubles as a
18712
- parity check. kind: 'all' (default) | 'methods' | 'options'.
18710
+ search_api(pattern, kind?, limit?, source?) -> {methods, option_types, total_matches, stub, stub_source}
18711
+ — regex over the Resolve typed stub. Each hit says whether THIS server
18712
+ references the method, and where, so it doubles as a parity check.
18713
+ kind: 'all' (default) | 'methods' | 'options'.
18714
+ source: 'auto' (default) reads the stub the installed Resolve ships and
18715
+ falls back to the shipped copy; 'shipped' forces the pinned file;
18716
+ 'installed' refuses when no install is found. The reply names the stub
18717
+ that answered, because "absent" from an outdated inventory is not the
18718
+ same as absent from the running build.
18713
18719
  No connection needed.
18714
- describe_api(symbol) -> {signatures, stub_line, description, source_files}
18720
+ describe_api(symbol, source?) -> {signatures, stub_line, description, source_files, stub, stub_source}
18715
18721
  — one 'Class.Method' or one TypedDict name. No connection needed.
18716
- api_surface() -> {methods, option_types, option_fields, objects}
18717
- — what the shipped stub contains. No connection needed.
18722
+ api_surface(source?) -> {methods, option_types, option_fields, objects, stub, stub_source}
18723
+ — what the answering stub contains. No connection needed.
18718
18724
  set_high_priority(high?) -> {success, high_priority, signature, reversible, readback: null}
18719
18725
  — script execution priority. high: true (default, the old meaning)
18720
18726
  or false for normal. Resolve 21.1+ calls SetHighPriority(bool) and
@@ -18780,17 +18786,19 @@ def resolve_control(action: str, params: Optional[Dict[str, Any]] = None) -> Dic
18780
18786
  try:
18781
18787
  return typed_api_search.search(
18782
18788
  project_dir, p.get("pattern"),
18783
- kind=p.get("kind", "all"), limit=p.get("limit", 50))
18789
+ kind=p.get("kind", "all"), limit=p.get("limit", 50),
18790
+ source=p.get("source", "auto"))
18784
18791
  except typed_api_search.TypedApiError as exc:
18785
18792
  return _err(str(exc), code="TYPED_API_QUERY", category="invalid_input")
18786
18793
  elif action == "describe_api":
18787
18794
  try:
18788
- return typed_api_search.describe(project_dir, p.get("symbol"))
18795
+ return typed_api_search.describe(project_dir, p.get("symbol"),
18796
+ source=p.get("source", "auto"))
18789
18797
  except typed_api_search.TypedApiError as exc:
18790
18798
  return _err(str(exc), code="TYPED_API_QUERY", category="invalid_input")
18791
18799
  elif action == "api_surface":
18792
18800
  try:
18793
- return typed_api_search.summary(project_dir)
18801
+ return typed_api_search.summary(project_dir, source=p.get("source", "auto"))
18794
18802
  except typed_api_search.TypedApiError as exc:
18795
18803
  return _err(str(exc), code="TYPED_API_QUERY", category="invalid_input")
18796
18804
  elif action == "api_truth":
@@ -27625,6 +27633,7 @@ _TIMELINE_ACTIONS = [
27625
27633
  "set_output_blanking", "normalize_audio_level", "auto_align_clips", "get_normalize_audio_modes", "get_output_blanking",
27626
27634
  # Offline authoring — served without a Resolve connection, above the _check() gate.
27627
27635
  "author_offline", "offline_fallback_capabilities",
27636
+ "film_stems_return", "film_preflight", "film_snapshot",
27628
27637
  "list", "get_current", "set_current", "get_name", "set_name", "get_start_frame",
27629
27638
  "get_end_frame", "get_start_timecode", "set_start_timecode", "get_track_count",
27630
27639
  "add_track", "delete_track", "get_track_sub_type", "set_track_enable",
@@ -27678,6 +27687,9 @@ def timeline(action: str, params: Optional[Dict[str, Any]] = None) -> Dict[str,
27678
27687
  get_output_blanking() -> {blanking} — documented on Resolve 21.1+. Pixel coordinates; empty on a clip inheriting timeline blanking.
27679
27688
  list() -> {timelines}
27680
27689
  get_current() -> {name, id, start_frame, end_frame, start_timecode}
27690
+ film_stems_return(delivery_dir, preview?, expected_timeline_id?, expected_fingerprint?) -> verified new-track film stem import; preview defaults true
27691
+ film_snapshot() -> cue_sheet, structural snapshot and picture_fingerprint for later picture-change comparison; read-only
27692
+ film_preflight(delivery_dir?, expected_picture_fingerprint?, tempo_evidence?, calibration_evidence?, capture_profile?, loudness_path?, target_lufs?, true_peak_max?) -> read-only film handoff checks; missing evidence stays unknown
27681
27693
  set_current(index|id|name) -> {success} — id/name are stable across archives; index is 1-based
27682
27694
  get_name() -> {name}
27683
27695
  set_name(name) -> {success}
@@ -27947,6 +27959,35 @@ def timeline(action: str, params: Optional[Dict[str, Any]] = None) -> Dict[str,
27947
27959
  if err:
27948
27960
  return err
27949
27961
 
27962
+ if action == "film_stems_return":
27963
+ from src.utils.film_stem_return import prepare_return
27964
+ try:
27965
+ return prepare_return(proj, p["delivery_dir"], preview=_coerce_bool(p.get("preview"), True),
27966
+ expected_timeline_id=p.get("expected_timeline_id"),
27967
+ expected_fingerprint=p.get("expected_fingerprint"))
27968
+ except (ValueError, TypeError, OSError) as exc:
27969
+ return _err(str(exc))
27970
+
27971
+ if action in ("film_preflight", "film_snapshot"):
27972
+ from src.utils.film_preflight import preflight
27973
+ tl = proj.GetCurrentTimeline()
27974
+ if not tl:
27975
+ return _err("No current timeline")
27976
+ try:
27977
+ snapshot = _timeline_conform_snapshot(tl)
27978
+ sheet = _export_film_cue_sheet(tl)
27979
+ report = preflight(sheet, snapshot,
27980
+ _detect_missing_media_from_snapshot(snapshot),
27981
+ **{key: p[key] for key in ("delivery_dir", "expected_picture_fingerprint",
27982
+ "tempo_evidence", "calibration_evidence", "capture_profile",
27983
+ "loudness_path", "target_lufs", "true_peak_max") if key in p})
27984
+ if action == "film_snapshot":
27985
+ return {"schema": "film-snapshot/v1", "cue_sheet": sheet, "snapshot": snapshot,
27986
+ "picture_fingerprint": report["picture_fingerprint"], "mutations": 0}
27987
+ return report
27988
+ except (ValueError, TypeError, OSError, KeyError) as exc:
27989
+ return _err(str(exc))
27990
+
27950
27991
  # Actions that don't need a current timeline
27951
27992
  if action == "list":
27952
27993
  count = proj.GetTimelineCount()
@@ -28645,6 +28686,8 @@ def timeline_markers(action: str, params: Optional[Dict[str, Any]] = None) -> An
28645
28686
  add(frame|frame_id|frameId|timecode?, color?, name?, note?, duration?, custom_data?, dry_run?/dryRun?) -> {success, frame} or dry-run preview
28646
28687
  If frame/timecode is omitted, add uses the current playhead timecode.
28647
28688
  get_all() -> {markers}
28689
+ export_cue_sheet(color?) -> film-cues/v1 JSON; read-only picture-to-score handoff
28690
+ compare_cue_sheets(before, after, identity_map?, before_snapshot?, after_snapshot?) -> offline film-picture-changes/v1 with optional structural picture impact; no automatic reconform
28648
28691
  get_by_custom_data(custom_data) -> {markers}
28649
28692
  update_custom_data(frame|frame_id|frameId|timecode, custom_data) -> {success}
28650
28693
  get_custom_data(frame|frame_id|frameId|timecode) -> {data}
@@ -28667,6 +28710,35 @@ def timeline_markers(action: str, params: Optional[Dict[str, Any]] = None) -> An
28667
28710
  annotation_boundary_report(scope?) -> {capabilities, annotations}
28668
28711
  """
28669
28712
  p = _params(params)
28713
+ if action == "compare_cue_sheets":
28714
+ from src.utils.film_picture_changes import compare_film_cues, compare_picture_impact
28715
+ try:
28716
+ report = compare_film_cues(p["before"], p["after"], p.get("identity_map"))
28717
+ if "before_snapshot" in p or "after_snapshot" in p:
28718
+ before_snapshot, after_snapshot = p["before_snapshot"], p["after_snapshot"]
28719
+ if not isinstance(before_snapshot, dict) or not isinstance(after_snapshot, dict):
28720
+ return _err("Both structural snapshots must be objects")
28721
+ impact = compare_picture_impact(p["before"], p["after"], before_snapshot, after_snapshot,
28722
+ {})
28723
+ try:
28724
+ impact["editorial_comparison"] = _compare_timeline_snapshots(before_snapshot, after_snapshot)
28725
+ except (AttributeError, TypeError, KeyError) as exc:
28726
+ # Impact validation retains unreadable spans as unknown. The
28727
+ # older comparator requires complete enumeration; its failure
28728
+ # must not discard that conservative evidence or imply a match.
28729
+ impact["editorial_comparison"] = {
28730
+ "status": "unknown", "reason": "Structural comparison unavailable: " + str(exc)}
28731
+ impact["requires_human_review"] = True
28732
+ report["picture_impact"] = impact
28733
+ report["requires_human_review"] |= impact["requires_human_review"]
28734
+ else:
28735
+ report["picture_impact"] = {"status": "unknown", "reason": "Supply both structural snapshots to assess picture edits beneath unchanged cues"}
28736
+ report["requires_human_review"] = True
28737
+ return report
28738
+ except _MissingParam as exc:
28739
+ return _missing_param_error(exc, action)
28740
+ except (ValueError, TypeError, OverflowError, KeyError) as exc:
28741
+ return _err(str(exc))
28670
28742
  _, tl, err = _get_tl()
28671
28743
  if err:
28672
28744
  return err
@@ -28693,6 +28765,11 @@ def timeline_markers(action: str, params: Optional[Dict[str, Any]] = None) -> An
28693
28765
  return _add_marker(tl, marker)
28694
28766
  elif action == "get_all":
28695
28767
  return {"markers": _ser(tl.GetMarkers())}
28768
+ elif action == "export_cue_sheet":
28769
+ try:
28770
+ return _export_film_cue_sheet(tl, color=p.get("color"))
28771
+ except (ValueError, TypeError, OverflowError) as exc:
28772
+ return _err(str(exc))
28696
28773
  elif action == "get_by_custom_data":
28697
28774
  return {"markers": _ser(tl.GetMarkerByCustomData(_first_param(p, "custom_data", "customData", default="")))}
28698
28775
  elif action == "update_custom_data":
@@ -28768,7 +28845,7 @@ def timeline_markers(action: str, params: Optional[Dict[str, Any]] = None) -> An
28768
28845
  return _export_review_report(tl, p)
28769
28846
  elif action == "annotation_boundary_report":
28770
28847
  return _annotation_boundary_report(tl, p)
28771
- return _unknown(action, ["add","get_all","get_by_custom_data","update_custom_data","get_custom_data","delete_by_color","delete_at_frame","delete_by_custom_data","get_current_timecode","set_current_timecode","get_current_video_item","get_thumbnail","get_thumbnail_image",*_ANNOTATION_KERNEL_ACTIONS])
28848
+ return _unknown(action, ["add","get_all","export_cue_sheet","compare_cue_sheets","get_by_custom_data","update_custom_data","get_custom_data","delete_by_color","delete_at_frame","delete_by_custom_data","get_current_timecode","set_current_timecode","get_current_video_item","get_thumbnail","get_thumbnail_image",*_ANNOTATION_KERNEL_ACTIONS])
28772
28849
 
28773
28850
 
28774
28851
  # ═══════════════════════════════════════════════════════════════════════════════
@@ -43,6 +43,7 @@ from src.utils.execution_lifecycle import (
43
43
  RiskClassificationHook,
44
44
  RiskLevel,
45
45
  classify_operation_risk,
46
+ is_preview_only,
46
47
  )
47
48
 
48
49
  logger = logging.getLogger("resolve-mcp.destructive-hook")
@@ -183,6 +184,10 @@ DESTRUCTIVE_ACTIONS_BY_TOOL: Dict[str, FrozenSet[str]] = {
183
184
  "clear_mark_in_out",
184
185
  "set_title_text",
185
186
  "import_into_timeline",
187
+ # Imports the stems and appends each onto a new audio track. Only the
188
+ # apply call (preview=false) mutates; is_preview_only keeps the default
189
+ # preview call from archiving a version.
190
+ "film_stems_return",
186
191
  }),
187
192
  "timeline_markers": frozenset({
188
193
  "add",
@@ -348,6 +353,10 @@ DRY_RUN_DEFAULT_TRUE_ACTIONS: frozenset = frozenset({
348
353
  ("timeline", "ripple_insert"),
349
354
  })
350
355
 
356
+ # Actions whose plan-only flag is `preview` rather than `dry_run` are listed
357
+ # in execution_lifecycle.PREVIEW_DEFAULT_TRUE_ACTIONS, so the risk rating and
358
+ # the archive decision read one table.
359
+
351
360
 
352
361
  # ── Native dry-run allowlist ────────────────────────────────────────────────
353
362
  #
@@ -458,6 +467,8 @@ def _payload_is_plan_only(
458
467
  tool_name: str, action: str, params: Optional[Dict[str, Any]],
459
468
  ) -> bool:
460
469
  """True iff this call only produces a plan and mutates nothing."""
470
+ if is_preview_only(tool_name, action, params):
471
+ return True
461
472
  dry_run = explicit_bool_param(params, "dry_run", "dryRun")
462
473
  if (tool_name, action) in NATIVE_DRY_RUN_ACTIONS and dry_run is True:
463
474
  return True
@@ -30,6 +30,22 @@ from src.utils.bool_params import coerce_bool
30
30
  logger = logging.getLogger("resolve-mcp.execution-lifecycle")
31
31
 
32
32
 
33
+ #: Actions whose plan-only flag is `preview`, defaulting to True: the call
34
+ #: mutates only when `preview` is explicitly false. Shared with
35
+ #: destructive_hook, which uses it to skip archiving a preview call.
36
+ PREVIEW_DEFAULT_TRUE_ACTIONS: frozenset = frozenset({
37
+ ("timeline", "film_stems_return"),
38
+ })
39
+
40
+
41
+ def is_preview_only(tool_name: str, action: str, params: Optional[Dict[str, Any]]) -> bool:
42
+ """True iff this is a `preview`-gated action called in preview mode."""
43
+ if (tool_name, action) not in PREVIEW_DEFAULT_TRUE_ACTIONS:
44
+ return False
45
+ value = params.get("preview") if isinstance(params, dict) else None
46
+ return coerce_bool(value, True)
47
+
48
+
33
49
  class RiskLevel(str, enum.Enum):
34
50
  """Categorized risk level for tool operations."""
35
51
  LOW = "low" # Read-only queries, info probes, and known-reversible edits
@@ -320,6 +336,12 @@ class RiskClassificationHook(LifecycleHook):
320
336
  ("timeline", "insert_fusion_composition"),
321
337
  ("timeline", "insert_ofx_generator"),
322
338
  ("media_pool", "append_to_timeline"),
339
+ # Applied (preview=false): imports the stems into the pool and appends
340
+ # each onto a NEW audio track. Existing tracks are refused rather than
341
+ # touched, but the pool and the track list change and a partial failure
342
+ # is left in place for review. The preview call is classified read-only
343
+ # before this table is consulted (PREVIEW_DEFAULT_TRUE_ACTIONS).
344
+ ("timeline", "film_stems_return"),
323
345
  # Timeline-wide settings. No content lost, but a wrong start timecode
324
346
  # silently invalidates every conform and reference built against it.
325
347
  ("timeline", "set_setting"),
@@ -424,6 +446,19 @@ class RiskClassificationHook(LifecycleHook):
424
446
 
425
447
  pair = (tool_name, action)
426
448
 
449
+ if is_preview_only(tool_name, action, params):
450
+ # Preview reads the package and the timeline and returns a plan
451
+ # with a fingerprint; nothing is written until preview=false.
452
+ return RiskAssessment(
453
+ level=RiskLevel.LOW,
454
+ destructive=False,
455
+ blast_radius=BlastRadius.ITEM,
456
+ confirmation_required=False,
457
+ snapshot_available=None,
458
+ reasons=[f"Preview of '{action}': read-only plan, nothing is written"],
459
+ recognised=True,
460
+ )
461
+
427
462
  if pair in cls._CRITICAL_ACTIONS:
428
463
  level = RiskLevel.CRITICAL
429
464
  destructive = True
@@ -658,6 +693,8 @@ class DriftDetectionHook(LifecycleHook):
658
693
  and post_dur is not None
659
694
  and pre_dur != post_dur
660
695
  and ctx.action not in self._DURATION_ALTERING_ACTIONS
696
+ and not (ctx.tool_name == "timeline" and ctx.action == "film_stems_return"
697
+ and not coerce_bool(ctx.params.get("preview"), True))
661
698
  ):
662
699
  warning = (
663
700
  f"Timeline duration drifted unexpectedly from {pre_dur} to {post_dur} frames "
@@ -0,0 +1,85 @@
1
+ """Read-only picture-to-score interchange; frames, not timecodes, are canonical.
2
+
3
+ Resolve timeline marker keys are relative to timeline start, even for markers
4
+ later than that start's absolute frame number. Never guess/rebase those keys.
5
+ """
6
+ from fractions import Fraction
7
+ import math
8
+ import re
9
+
10
+
11
+ def _integer(value, field, minimum=0):
12
+ if isinstance(value, bool):
13
+ raise ValueError(f"{field} must be an integer >= {minimum}")
14
+ try:
15
+ number = Fraction(str(value))
16
+ except (ValueError, ZeroDivisionError) as exc:
17
+ raise ValueError(f"{field} must be an integer >= {minimum}") from exc
18
+ if number.denominator != 1 or number < minimum:
19
+ raise ValueError(f"{field} must be an integer >= {minimum}")
20
+ return int(number)
21
+
22
+
23
+ def _rate(value):
24
+ text = str(value).strip()
25
+ match = re.fullmatch(r"(\d+(?:\.\d+)?(?:/\d+)?)\s*(?:DF|NDF)?", text)
26
+ if not match:
27
+ raise ValueError("timelineFrameRate must be a positive numeric frame rate")
28
+ text = match[1]
29
+ # Resolve displays rounded NTSC rates. Recover their standard clock rates
30
+ # before converting a feature-length timeline to seconds.
31
+ ntsc = {"23.976": 24000, "23.98": 24000, "29.97": 30000,
32
+ "47.952": 48000, "59.94": 60000, "119.88": 120000}
33
+ try:
34
+ rate = Fraction(ntsc[text], 1001) if text in ntsc else Fraction(text)
35
+ except (ValueError, ZeroDivisionError) as exc:
36
+ raise ValueError("Invalid timelineFrameRate") from exc
37
+ if rate <= 0 or rate > 1000:
38
+ raise ValueError("timelineFrameRate must be between 0 and 1000 fps")
39
+ return rate
40
+
41
+
42
+ def export_cue_sheet(timeline, *, color=None):
43
+ """Return a film-cues/v1 payload without writing files or changing Resolve.
44
+
45
+ ``start_frame`` inside each cue is relative; ``timeline.start_frame`` is
46
+ absolute metadata only. Seconds are convenient approximations; consumers
47
+ must derive timing from integer frames and the rational frame rate.
48
+ """
49
+ if color is not None and (not isinstance(color, str) or not color.strip()):
50
+ raise ValueError("color must be a non-empty marker colour name")
51
+ rate = _rate(timeline.GetSetting("timelineFrameRate"))
52
+ start = _integer(timeline.GetStartFrame(), "timeline start frame")
53
+ markers = timeline.GetMarkers()
54
+ if not isinstance(markers, dict):
55
+ raise ValueError("Resolve did not return a marker dictionary")
56
+ cues = []
57
+ seen = set()
58
+ for key, marker in markers.items():
59
+ if not isinstance(marker, dict):
60
+ raise ValueError("Resolve returned an invalid marker record")
61
+ frame = _integer(key, "marker frame")
62
+ if frame in seen:
63
+ raise ValueError(f"Duplicate marker frame {frame}")
64
+ seen.add(frame)
65
+ duration = _integer(marker.get("duration"), "marker duration", 1)
66
+ values = {}
67
+ for source, target in (("name", "name"), ("note", "note"),
68
+ ("color", "color"), ("customData", "custom_data")):
69
+ value = marker.get(source, "")
70
+ if not isinstance(value, str):
71
+ raise ValueError(f"marker {source} must be a string")
72
+ values[target] = value
73
+ seconds, duration_seconds = float(frame / rate), float(duration / rate)
74
+ if not math.isfinite(seconds) or not math.isfinite(duration_seconds):
75
+ raise ValueError("Marker timing exceeds the supported numeric range")
76
+ if color is not None and values["color"].casefold() != color.casefold():
77
+ continue
78
+ cues.append({"id": f"marker:{frame}", **values,
79
+ "start_frame": frame, "duration_frames": duration,
80
+ "start_seconds": seconds, "duration_seconds": duration_seconds})
81
+ return {"schema": "film-cues/v1",
82
+ "frame_rate": {"numerator": rate.numerator, "denominator": rate.denominator},
83
+ "timeline": {"name": timeline.GetName(), "start_frame": start,
84
+ "start_timecode": timeline.GetStartTimecode()},
85
+ "cues": sorted(cues, key=lambda cue: cue["start_frame"])}