davinci-resolve-mcp 5.1.0 → 5.2.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +38 -0
- package/README.md +9 -4
- package/README.zh-CN.md +9 -5
- package/docs/SKILL.md +15 -0
- package/docs/guides/film-cues.md +57 -0
- package/docs/guides/film-picture-changes.md +196 -0
- package/docs/guides/film-workflow.md +145 -0
- package/docs/reference/api-coverage.md +26 -33
- package/install.py +1 -1
- package/package.json +1 -1
- package/src/granular/common.py +1 -1
- package/src/server.py +72 -2
- package/src/utils/destructive_hook.py +11 -0
- package/src/utils/execution_lifecycle.py +37 -0
- package/src/utils/film_cues.py +85 -0
- package/src/utils/film_picture_changes.py +381 -0
- package/src/utils/film_preflight.py +162 -0
- package/src/utils/film_stem_return.py +224 -0
- package/src/utils/operation_result.py +14 -0
- package/src/utils/resolve_versions.py +10 -7
- package/src/utils/timeline_versioning.py +16 -1
|
@@ -0,0 +1,224 @@
|
|
|
1
|
+
"""Verified film-stems/v1 return into new Resolve audio tracks."""
|
|
2
|
+
from fractions import Fraction
|
|
3
|
+
import hashlib
|
|
4
|
+
import json
|
|
5
|
+
import math
|
|
6
|
+
import os
|
|
7
|
+
from pathlib import Path
|
|
8
|
+
import re
|
|
9
|
+
import wave
|
|
10
|
+
|
|
11
|
+
from .film_cues import _rate
|
|
12
|
+
|
|
13
|
+
|
|
14
|
+
def digest(value):
|
|
15
|
+
return hashlib.sha256(json.dumps(value, sort_keys=True, separators=(',', ':'),
|
|
16
|
+
allow_nan=False).encode()).hexdigest()
|
|
17
|
+
|
|
18
|
+
|
|
19
|
+
def file_hash(path):
|
|
20
|
+
result = hashlib.sha256()
|
|
21
|
+
with open(path, 'rb') as stream:
|
|
22
|
+
for block in iter(lambda: stream.read(1024*1024), b''): result.update(block)
|
|
23
|
+
return result.hexdigest()
|
|
24
|
+
|
|
25
|
+
|
|
26
|
+
def integer(value, name, minimum=0):
|
|
27
|
+
if type(value) is not int or value < minimum or value > 2**53:
|
|
28
|
+
raise ValueError(f'{name} must be an integer in [{minimum}, 2**53]')
|
|
29
|
+
return value
|
|
30
|
+
|
|
31
|
+
|
|
32
|
+
def _round(value):
|
|
33
|
+
return (2*value.numerator + value.denominator)//(2*value.denominator)
|
|
34
|
+
|
|
35
|
+
|
|
36
|
+
def audit_package(delivery_dir):
|
|
37
|
+
"""Read-only independent manifest, PCM WAV and SHA verification."""
|
|
38
|
+
root = Path(delivery_dir).resolve(strict=True)
|
|
39
|
+
path = root/'manifest.json'
|
|
40
|
+
with path.open('rb') as stream: raw = stream.read(8*1024*1024+1)
|
|
41
|
+
if len(raw) > 8*1024*1024: raise ValueError('Manifest too large')
|
|
42
|
+
m = json.loads(raw)
|
|
43
|
+
if not isinstance(m, dict) or m.get('schema') != 'film-stems/v1' or m.get('subtype') != 'PCM_24':
|
|
44
|
+
raise ValueError('Expected film-stems/v1 PCM_24 manifest')
|
|
45
|
+
rate = m.get('frame_rate')
|
|
46
|
+
if not isinstance(rate, dict): raise ValueError('Invalid frame_rate')
|
|
47
|
+
fps = Fraction(integer(rate.get('numerator'), 'numerator', 1),
|
|
48
|
+
integer(rate.get('denominator'), 'denominator', 1))
|
|
49
|
+
if not 1 <= fps <= 240: raise ValueError('Unsupported frame rate')
|
|
50
|
+
start, end, tail = (integer(m.get(k), k) for k in ('start_frame','end_frame','tail_frames'))
|
|
51
|
+
sr = integer(m.get('sample_rate'), 'sample_rate', 8000)
|
|
52
|
+
if end <= start or sr > 384000: raise ValueError('Invalid range/sample rate')
|
|
53
|
+
a, b, c = (_round(Fraction(frame*sr, 1)/fps) for frame in (start,end,end+tail))
|
|
54
|
+
expected = dict(start_sample=a, end_sample=c, sample_count=c-a,
|
|
55
|
+
body_sample_count=b-a, tail_sample_count=c-b)
|
|
56
|
+
for key, value in expected.items():
|
|
57
|
+
if integer(m.get(key), key) != value: raise ValueError(f'Clock mismatch: {key}')
|
|
58
|
+
stems = m.get('stems')
|
|
59
|
+
if not isinstance(stems, list) or not 1 <= len(stems) <= 64: raise ValueError('Expected 1-64 stems')
|
|
60
|
+
seen, rows = set(), []
|
|
61
|
+
for stem in stems:
|
|
62
|
+
if not isinstance(stem, dict): raise ValueError('Stem must be an object')
|
|
63
|
+
name = stem.get('name')
|
|
64
|
+
if not isinstance(name, str) or not re.fullmatch(r'[A-Za-z0-9][A-Za-z0-9_-]{0,79}', name):
|
|
65
|
+
raise ValueError('Invalid stem name')
|
|
66
|
+
if name.casefold() in seen or stem.get('file') != name+'.wav': raise ValueError('Duplicate or unsafe filename')
|
|
67
|
+
seen.add(name.casefold())
|
|
68
|
+
target = root/stem['file']
|
|
69
|
+
if target.is_symlink() or target.resolve(strict=True).parent != root or target.is_reserved():
|
|
70
|
+
raise ValueError('Stem path escapes delivery directory')
|
|
71
|
+
sha = file_hash(target)
|
|
72
|
+
if sha != stem.get('sha256'): raise ValueError(f'{name}: SHA-256 mismatch')
|
|
73
|
+
with wave.open(str(target), 'rb') as wav:
|
|
74
|
+
channels = integer(stem.get('channels'), 'channels', 1)
|
|
75
|
+
if (channels not in (1,2) or wav.getnchannels() != channels or wav.getsampwidth()!=3
|
|
76
|
+
or wav.getframerate()!=sr or wav.getnframes()!=c-a or wav.getcomptype()!='NONE'):
|
|
77
|
+
raise ValueError(f'{name}: WAV format/count mismatch')
|
|
78
|
+
left = c-a
|
|
79
|
+
while left:
|
|
80
|
+
count = min(left,65536)
|
|
81
|
+
if len(wav.readframes(count)) != count*channels*3: raise ValueError('Truncated WAV')
|
|
82
|
+
left -= count
|
|
83
|
+
if file_hash(target) != sha: raise ValueError('Stem changed during audit')
|
|
84
|
+
rows.append({'name':name,'path':str(target),'channels':channels,'sha256':sha,
|
|
85
|
+
'tail_not_quiet':stem.get('tail_not_quiet')})
|
|
86
|
+
return {'schema':'film-stem-audit/v1','status':'passed','package_id':digest(m),
|
|
87
|
+
'manifest':m,'stems':rows,'delivery_dir':str(root),
|
|
88
|
+
'capture_alignment_verified':False}
|
|
89
|
+
|
|
90
|
+
|
|
91
|
+
def _path(value):
|
|
92
|
+
# realpath, not abspath: audit_package resolves the delivery root, so stem
|
|
93
|
+
# paths come back with symlinks resolved (/private/var/... on macOS), while
|
|
94
|
+
# Resolve reports the path it was handed (/var/...). Comparing unresolved
|
|
95
|
+
# forms never matched, so a previous import went undetected.
|
|
96
|
+
return os.path.normcase(os.path.realpath(value)) if value else ''
|
|
97
|
+
|
|
98
|
+
|
|
99
|
+
def _number(value):
|
|
100
|
+
if isinstance(value,bool) or not isinstance(value,(float,int)) or not math.isfinite(value):
|
|
101
|
+
raise ValueError('Unreadable timeline coordinate')
|
|
102
|
+
return value
|
|
103
|
+
|
|
104
|
+
|
|
105
|
+
def _snapshot(tl):
|
|
106
|
+
identity = tl.GetUniqueId()
|
|
107
|
+
if not isinstance(identity,str) or not identity: raise ValueError('Timeline identity unavailable')
|
|
108
|
+
tracks = []
|
|
109
|
+
count = integer(tl.GetTrackCount('audio'),'audio tracks')
|
|
110
|
+
for index in range(1,count+1):
|
|
111
|
+
items = tl.GetItemListInTrack('audio',index)
|
|
112
|
+
if not isinstance(items,list): raise ValueError('Audio track enumeration unavailable')
|
|
113
|
+
rows = []
|
|
114
|
+
for item in items:
|
|
115
|
+
media = item.GetMediaPoolItem()
|
|
116
|
+
rows.append({'id':item.GetUniqueId(),'path':_path(media.GetClipProperty('File Path')) if media else '',
|
|
117
|
+
'start':_number(item.GetStart(True)), 'duration':_number(item.GetDuration(True))})
|
|
118
|
+
tracks.append({'index':index,'name':tl.GetTrackName('audio',index),'items':rows})
|
|
119
|
+
return {'id':identity,'name':tl.GetName(),'start_frame':integer(tl.GetStartFrame(),'timeline start'),
|
|
120
|
+
'fps':str(_rate(tl.GetSetting('timelineFrameRate'))),'tracks':tracks}
|
|
121
|
+
|
|
122
|
+
|
|
123
|
+
def prepare_return(project, delivery_dir, preview=True, expected_timeline_id=None,
|
|
124
|
+
expected_fingerprint=None):
|
|
125
|
+
if type(preview) is not bool: raise ValueError('preview must be boolean')
|
|
126
|
+
if not preview and (not expected_timeline_id or not expected_fingerprint):
|
|
127
|
+
raise ValueError('Apply requires expected_timeline_id and preview fingerprint')
|
|
128
|
+
audit = audit_package(delivery_dir)
|
|
129
|
+
m = audit['manifest']; tl = project.GetCurrentTimeline()
|
|
130
|
+
if not tl: raise ValueError('No current timeline')
|
|
131
|
+
snapshot = _snapshot(tl)
|
|
132
|
+
fps = Fraction(m['frame_rate']['numerator'],m['frame_rate']['denominator'])
|
|
133
|
+
if Fraction(snapshot['fps']) != fps: raise ValueError('Delivery/timeline frame rate mismatch')
|
|
134
|
+
record = snapshot['start_frame']+m['start_frame']
|
|
135
|
+
duration = m['end_frame']+m['tail_frames']-m['start_frame']
|
|
136
|
+
tolerance = float(fps/m['sample_rate']) + 1e-8
|
|
137
|
+
names = [f"FILM_{audit['package_id'][:12]}_{s['name']}" for s in audit['stems']]
|
|
138
|
+
present = []
|
|
139
|
+
for stem,name in zip(audit['stems'],names):
|
|
140
|
+
matches = [(track,item) for track in snapshot['tracks'] for item in track['items']
|
|
141
|
+
if item['path']==_path(stem['path'])]
|
|
142
|
+
if matches:
|
|
143
|
+
if len(matches)!=1: raise ValueError('Duplicate stem instances; manual review required')
|
|
144
|
+
track,item = matches[0]
|
|
145
|
+
if (track['name']!=name or abs(item['start']-record)>tolerance
|
|
146
|
+
or abs(item['duration']-duration)>tolerance):
|
|
147
|
+
raise ValueError('Existing stem has conflicting placement or track')
|
|
148
|
+
present.append(name)
|
|
149
|
+
elif any(t['name']==name for t in snapshot['tracks']):
|
|
150
|
+
raise ValueError('Target track name already exists without matching stem')
|
|
151
|
+
if present and len(present)!=len(names): raise ValueError('Partial previous import; manual review required')
|
|
152
|
+
result = {'status':'already_present' if present else 'preview',
|
|
153
|
+
'schema':'film-stem-return/v1','timeline_id':snapshot['id'],
|
|
154
|
+
'package_id':audit['package_id'],'record_frame':record,'duration_frames':duration,
|
|
155
|
+
'track_names':names,'fingerprint':digest({'audit':audit,'timeline':snapshot}),
|
|
156
|
+
'sample_boundary_rounding':'nearest sample; timeline placement at the requested picture frame',
|
|
157
|
+
'capture_alignment_verified':False}
|
|
158
|
+
if not preview and (snapshot['id']!=expected_timeline_id or result['fingerprint']!=expected_fingerprint):
|
|
159
|
+
raise ValueError('Preview is stale or target timeline changed; preview again')
|
|
160
|
+
if preview or present: return result
|
|
161
|
+
created, imported = [], []
|
|
162
|
+
partially_created_unknown = False
|
|
163
|
+
def same_target():
|
|
164
|
+
current = project.GetCurrentTimeline()
|
|
165
|
+
if not current or current.GetUniqueId()!=snapshot['id']: raise ValueError('Active timeline changed')
|
|
166
|
+
try:
|
|
167
|
+
same_target()
|
|
168
|
+
pool = project.GetMediaPool()
|
|
169
|
+
# ImportMedia may mutate the pool before raising or returning partial handles.
|
|
170
|
+
# Keep every readable receipt; an empty receipt list does not prove no import.
|
|
171
|
+
partially_created_unknown = True
|
|
172
|
+
media = pool.ImportMedia([s['path'] for s in audit['stems']])
|
|
173
|
+
by_path = {}
|
|
174
|
+
if isinstance(media, list):
|
|
175
|
+
for item in media:
|
|
176
|
+
try:
|
|
177
|
+
path = item.GetClipProperty('File Path')
|
|
178
|
+
if not isinstance(path, str) or not path:
|
|
179
|
+
continue
|
|
180
|
+
imported.append(path)
|
|
181
|
+
by_path[_path(path)] = item
|
|
182
|
+
except Exception:
|
|
183
|
+
# One unusable handle must not hide receipts for other imports.
|
|
184
|
+
continue
|
|
185
|
+
if not isinstance(media,list) or len(media)!=len(names): raise ValueError('Media import incomplete')
|
|
186
|
+
if len(by_path)!=len(media): raise ValueError('Media import receipts incomplete')
|
|
187
|
+
partially_created_unknown = False
|
|
188
|
+
source_rates = {}
|
|
189
|
+
for stem in audit['stems']:
|
|
190
|
+
item = by_path.get(_path(stem['path']))
|
|
191
|
+
if not item: raise ValueError('Imported media paths differ from package')
|
|
192
|
+
source_rates[stem['path']] = _rate(item.GetClipProperty('FPS'))
|
|
193
|
+
if _snapshot(tl)!=snapshot: raise ValueError('Timeline changed during media import')
|
|
194
|
+
for stem,name in zip(audit['stems'],names):
|
|
195
|
+
same_target()
|
|
196
|
+
if file_hash(stem['path'])!=stem['sha256']: raise ValueError('Stem changed after preview')
|
|
197
|
+
index = tl.GetTrackCount('audio')+1
|
|
198
|
+
if not tl.AddTrack('audio',{'audioType':'mono' if stem['channels']==1 else 'stereo'}):
|
|
199
|
+
raise ValueError('AddTrack failed')
|
|
200
|
+
created.append({'index':index,'name':name})
|
|
201
|
+
if tl.GetTrackCount('audio')!=index or tl.GetItemListInTrack('audio',index):
|
|
202
|
+
raise ValueError('New track was not empty or track list changed')
|
|
203
|
+
if not tl.SetTrackName('audio',index,name): raise ValueError('SetTrackName failed')
|
|
204
|
+
same_target()
|
|
205
|
+
# WAV source coordinates use the media item's imported FPS, not the timeline FPS.
|
|
206
|
+
source_duration = Fraction(duration,1)/fps * source_rates[stem['path']]
|
|
207
|
+
# Audio endFrame is an exclusive endpoint on the verified Resolve build.
|
|
208
|
+
# Video's common inclusive-end convention would lose one source frame.
|
|
209
|
+
returned = pool.AppendToTimeline([{'mediaPoolItem':by_path[_path(stem['path'])],
|
|
210
|
+
'startFrame':0,'endFrame':float(source_duration),'recordFrame':record,
|
|
211
|
+
'trackIndex':index,'mediaType':2}])
|
|
212
|
+
if not returned: raise ValueError('AppendToTimeline returned no items')
|
|
213
|
+
readback = _snapshot(tl)['tracks'][index-1]
|
|
214
|
+
if readback['name']!=name or len(readback['items'])!=1: raise ValueError('Track readback mismatch')
|
|
215
|
+
row = readback['items'][0]
|
|
216
|
+
if (row['path']!=_path(stem['path']) or abs(row['start']-record)>tolerance
|
|
217
|
+
or abs(row['duration']-duration)>tolerance): raise ValueError('Placement readback mismatch')
|
|
218
|
+
same_target()
|
|
219
|
+
return {**result,'status':'imported','created_tracks':created,'verified':True}
|
|
220
|
+
except Exception as exc:
|
|
221
|
+
return {**result,'status':'partial_failure','error':str(exc),'created_tracks':created,
|
|
222
|
+
'imported_media':imported,'rollback_attempted':False,
|
|
223
|
+
'partially_created_unknown':partially_created_unknown,
|
|
224
|
+
'warning':'Inspect created tracks/media before retrying; nothing automatically deleted.'}
|
|
@@ -110,6 +110,20 @@ def normalize_status(raw: Any) -> str:
|
|
|
110
110
|
if raw.get("status") == "confirmation_required" or raw.get("confirmation_required") is True:
|
|
111
111
|
return "blocked"
|
|
112
112
|
|
|
113
|
+
# These film schemas define report outcomes, including partial mutations
|
|
114
|
+
# accompanied by an error. Do not infer these meanings for other schemas.
|
|
115
|
+
if raw.get("schema") == "film-preflight/v1":
|
|
116
|
+
film_statuses = {
|
|
117
|
+
"failed": "failed", "incomplete": "blocked",
|
|
118
|
+
"warnings": "partial", "passed": "success",
|
|
119
|
+
}
|
|
120
|
+
status = raw.get("status")
|
|
121
|
+
if isinstance(status, str) and status in film_statuses:
|
|
122
|
+
return film_statuses[status]
|
|
123
|
+
if (raw.get("schema") == "film-stem-return/v1"
|
|
124
|
+
and raw.get("status") == "partial_failure"):
|
|
125
|
+
return "partial"
|
|
126
|
+
|
|
113
127
|
if raw.get("error"):
|
|
114
128
|
return "failed"
|
|
115
129
|
if raw.get("success") is False:
|
|
@@ -151,18 +151,21 @@ _EVIDENCE_GATES: List[Dict[str, Any]] = [
|
|
|
151
151
|
{
|
|
152
152
|
"symbol": "Timeline.GetSelectedClips",
|
|
153
153
|
"introduced_in": "21.0.4",
|
|
154
|
-
"source": "
|
|
155
|
-
"note": "
|
|
156
|
-
"
|
|
157
|
-
"
|
|
158
|
-
"
|
|
154
|
+
"source": "measured",
|
|
155
|
+
"note": "Measured on free 21.0.4.5 through the in-app bridge "
|
|
156
|
+
"(tests/live_resolve2104_validation.py): [] with nothing selected, "
|
|
157
|
+
"the clicked timeline item after a click. First reported against 21.0.4.5 "
|
|
158
|
+
"and listed in the shipped scripting README.",
|
|
159
159
|
"issue": 131,
|
|
160
160
|
},
|
|
161
161
|
{
|
|
162
162
|
"symbol": "MediaPoolItem.GetTimeline",
|
|
163
163
|
"introduced_in": "21.0.4",
|
|
164
|
-
"source": "
|
|
165
|
-
"note": "
|
|
164
|
+
"source": "measured",
|
|
165
|
+
"note": "Measured on free 21.0.4.5 through the in-app bridge "
|
|
166
|
+
"(tests/live_resolve2104_validation.py): returns the timeline for a "
|
|
167
|
+
"timeline item and None for a plain clip. First reported against "
|
|
168
|
+
"21.0.4.5.",
|
|
166
169
|
"issue": 131,
|
|
167
170
|
},
|
|
168
171
|
{
|
|
@@ -156,11 +156,26 @@ def archive_current_timeline(
|
|
|
156
156
|
|
|
157
157
|
# Resolve duplication must happen on the live timeline; pin current folder
|
|
158
158
|
# to Archive bin first so the duplicate lands there directly.
|
|
159
|
+
# The caller's current bin is restored afterwards: the destructive action
|
|
160
|
+
# that runs next may import media (timeline.film_stems_return does), and
|
|
161
|
+
# ImportMedia lands in the CURRENT bin, i.e. the Archive bin if left there.
|
|
162
|
+
try:
|
|
163
|
+
prior_folder = media_pool.GetCurrentFolder()
|
|
164
|
+
except Exception:
|
|
165
|
+
prior_folder = None
|
|
159
166
|
archive_bin = _ensure_archive_bin(media_pool)
|
|
160
167
|
if not media_pool.SetCurrentFolder(archive_bin):
|
|
161
168
|
return {"success": False, "error": "Failed to set Archive as current bin"}
|
|
162
169
|
|
|
163
|
-
|
|
170
|
+
try:
|
|
171
|
+
dup = tl.DuplicateTimeline(archived_name)
|
|
172
|
+
finally:
|
|
173
|
+
if prior_folder is not None:
|
|
174
|
+
try:
|
|
175
|
+
if not media_pool.SetCurrentFolder(prior_folder):
|
|
176
|
+
logger.warning("could not restore the current bin after archiving")
|
|
177
|
+
except Exception as exc:
|
|
178
|
+
logger.warning("could not restore the current bin after archiving: %s", exc)
|
|
164
179
|
if dup is None:
|
|
165
180
|
return {"success": False, "error": f"DuplicateTimeline('{archived_name}') failed"}
|
|
166
181
|
|