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.
@@ -0,0 +1,381 @@
1
+ """Pure film-cues/v1 comparison. No application access, reconform or file writes."""
2
+ from __future__ import annotations
3
+
4
+ from copy import deepcopy
5
+ from bisect import bisect_right
6
+ from fractions import Fraction
7
+ import hashlib
8
+ import json
9
+ import math
10
+
11
+ _MAX_INTEGER = 2**53 - 1
12
+ _TIMING_FIELDS = {"id", "start_frame", "duration_frames", "start_seconds", "duration_seconds"}
13
+
14
+
15
+ def _integer(value, field, minimum=0):
16
+ # Unlike Resolve API values, interchange coordinates must already be JSON integers.
17
+ if type(value) is not int or not minimum <= value <= _MAX_INTEGER:
18
+ raise ValueError(f"{field} must be an integer in [{minimum}, {_MAX_INTEGER}]")
19
+ return value
20
+
21
+
22
+ def _json_value(value, depth=0):
23
+ if depth > 64:
24
+ raise ValueError("Cue sheet JSON nesting exceeds 64")
25
+ if isinstance(value, dict):
26
+ for key, child in value.items():
27
+ if not isinstance(key, str):
28
+ raise ValueError("Cue sheet JSON object keys must be strings")
29
+ _json_value(child, depth + 1)
30
+ elif isinstance(value, list):
31
+ for child in value:
32
+ _json_value(child, depth + 1)
33
+ elif type(value) not in (str, int, float, bool, type(None)):
34
+ raise ValueError("Cue sheets must contain only JSON values")
35
+ elif isinstance(value, float) and not math.isfinite(value):
36
+ raise ValueError("Cue sheet numbers must be finite")
37
+
38
+
39
+ def _validate(document, label):
40
+ if not isinstance(document, dict) or document.get("schema") != "film-cues/v1":
41
+ raise ValueError(f"{label} must be a film-cues/v1 object")
42
+ _json_value(document)
43
+ rate = document.get("frame_rate")
44
+ if not isinstance(rate, dict):
45
+ raise ValueError(f"{label}.frame_rate must be a rational object")
46
+ rate = Fraction(_integer(rate.get("numerator"), "frame_rate.numerator", 1),
47
+ _integer(rate.get("denominator"), "frame_rate.denominator", 1))
48
+ if rate > 1000:
49
+ raise ValueError("Frame rate must not exceed 1000 fps")
50
+ timeline = document.get("timeline")
51
+ if not isinstance(timeline, dict):
52
+ raise ValueError(f"{label}.timeline must be an object")
53
+ _integer(timeline.get("start_frame"), "timeline.start_frame")
54
+ if any(not isinstance(timeline.get(k), str) for k in ("name", "start_timecode")):
55
+ raise ValueError("timeline.name and start_timecode must be strings")
56
+ cues = document.get("cues")
57
+ if not isinstance(cues, list) or len(cues) > 10000:
58
+ raise ValueError("cues must be a list of at most 10000 objects")
59
+ indexed = {}
60
+ for cue in cues:
61
+ if not isinstance(cue, dict):
62
+ raise ValueError("Each cue must be an object")
63
+ identity = cue.get("id")
64
+ if not isinstance(identity, str) or not identity.strip() or identity in indexed:
65
+ raise ValueError("Cue IDs must be nonempty, unique strings")
66
+ start = _integer(cue.get("start_frame"), "cue.start_frame")
67
+ duration = _integer(cue.get("duration_frames"), "cue.duration_frames", 1)
68
+ _integer(start + duration, "cue exclusive end frame")
69
+ if identity.startswith("marker:") and identity != f"marker:{start}":
70
+ raise ValueError("Position-based marker ID must agree with its start_frame")
71
+ if not isinstance(cue.get("name"), str):
72
+ raise ValueError("cue.name must be a string")
73
+ for field in ("note", "color", "custom_data"):
74
+ if field in cue and not isinstance(cue[field], str):
75
+ raise ValueError(f"cue.{field} must be a string")
76
+ for field in ("start_seconds", "duration_seconds"):
77
+ if field in cue and (type(cue[field]) not in (int, float) or cue[field] < 0):
78
+ raise ValueError(f"cue.{field} must be a nonnegative finite number")
79
+ indexed[identity] = cue
80
+ try:
81
+ encoded = json.dumps(document, sort_keys=True, separators=(",", ":"),
82
+ ensure_ascii=True, allow_nan=False).encode("ascii")
83
+ except (TypeError, ValueError, RecursionError) as exc:
84
+ raise ValueError("Cue sheet cannot be represented as canonical JSON") from exc
85
+ if len(encoded) > 8 * 1024 * 1024:
86
+ raise ValueError("Cue sheet exceeds 8 MiB canonical JSON limit")
87
+ snapshot = {"timeline": deepcopy(timeline), "frame_rate": _rational(rate),
88
+ "fingerprint_sha256": hashlib.sha256(encoded).hexdigest()}
89
+ return rate, indexed, snapshot
90
+
91
+
92
+ def _rational(value):
93
+ return {"numerator": value.numerator, "denominator": value.denominator}
94
+
95
+
96
+ def _range(cue, rate):
97
+ if cue is None:
98
+ return None
99
+ start = cue["start_frame"]
100
+ end = start + cue["duration_frames"]
101
+ return {"start_frame": start, "end_frame": end,
102
+ "start_seconds": _rational(Fraction(start) / rate),
103
+ "end_seconds": _rational(Fraction(end) / rate)}
104
+
105
+
106
+ def _metadata(cue):
107
+ return {k: v for k, v in cue.items() if k not in _TIMING_FIELDS}
108
+
109
+
110
+ def compare_film_cues(before: dict, after: dict,
111
+ identity_map: dict[str, str] | None = None) -> dict:
112
+ """Compare immutable cue sheets; raise ValueError for invalid input/mappings.
113
+
114
+ Explicit mappings run before stable-ID matches. Unmapped ``marker:<frame>``
115
+ IDs are not stable: identical records at the same clock position are only
116
+ observations; changed records remain removals/additions requiring review.
117
+ All ranges are half-open and relative to each sheet's picture origin.
118
+ """
119
+ old_rate, old, old_picture = _validate(before, "before")
120
+ new_rate, new, new_picture = _validate(after, "after")
121
+ compatible = old_rate == new_rate
122
+ mapping = {} if identity_map is None else identity_map
123
+ if not isinstance(mapping, dict):
124
+ raise ValueError("identity_map must be an object of before IDs to after IDs")
125
+ matches, used = {}, set()
126
+ for source, target in mapping.items():
127
+ if (not isinstance(source, str) or not isinstance(target, str)
128
+ or source not in old or target not in new or target in used):
129
+ raise ValueError("identity_map must reference existing IDs one-to-one")
130
+ matches[source] = (target, "explicit_mapping")
131
+ used.add(target)
132
+ for identity in sorted(old.keys() & new.keys()):
133
+ if identity in matches or identity.startswith("marker:"):
134
+ continue
135
+ if identity in used:
136
+ raise ValueError("Explicit mapping conflicts with an implicit stable-ID match")
137
+ matches[identity] = (identity, "stable_id")
138
+ used.add(identity)
139
+ position_only = []
140
+ for identity in sorted(old.keys() & new.keys()):
141
+ if (identity.startswith("marker:") and identity not in matches and identity not in used
142
+ and compatible and old[identity]["start_frame"] == new[identity]["start_frame"]
143
+ and old[identity]["duration_frames"] == new[identity]["duration_frames"]
144
+ and _metadata(old[identity]) == _metadata(new[identity])):
145
+ matches[identity] = (identity, "same_position_observation")
146
+ used.add(identity)
147
+ position_only.append(identity)
148
+ changes, unchanged = [], 0
149
+ for identity in sorted(old):
150
+ previous = old[identity]
151
+ matched = matches.get(identity)
152
+ if matched is None:
153
+ changes.append({"before_id": identity, "after_id": None,
154
+ "kinds": ["removed"], "match_basis": "unmatched",
155
+ "before_range": _range(previous, old_rate), "after_range": None,
156
+ "before_cue": deepcopy(previous), "after_cue": None})
157
+ continue
158
+ target, basis = matched
159
+ current = new[target]
160
+ frame_delta, second_delta = {}, {}
161
+ for field, a, b in (("start", previous["start_frame"], current["start_frame"]),
162
+ ("end", previous["start_frame"] + previous["duration_frames"],
163
+ current["start_frame"] + current["duration_frames"]),
164
+ ("duration", previous["duration_frames"], current["duration_frames"])):
165
+ frame_delta[field] = b - a
166
+ second_delta[field] = Fraction(b) / new_rate - Fraction(a) / old_rate
167
+ a_meta, b_meta = _metadata(previous), _metadata(current)
168
+ metadata_changes = {}
169
+ for key in sorted(a_meta.keys() | b_meta.keys()):
170
+ if key not in a_meta or key not in b_meta or a_meta[key] != b_meta[key]:
171
+ edit = {"before": deepcopy(a_meta.get(key)), "after": deepcopy(b_meta.get(key))}
172
+ if key not in a_meta or key not in b_meta:
173
+ edit.update(before_present=key in a_meta, after_present=key in b_meta)
174
+ metadata_changes[key] = edit
175
+ kinds = []
176
+ if second_delta["start"]:
177
+ kinds.append("moved")
178
+ if second_delta["duration"]:
179
+ kinds.append("resized")
180
+ if metadata_changes:
181
+ kinds.append("metadata_edited")
182
+ if not kinds:
183
+ unchanged += 1
184
+ continue
185
+ changes.append({"before_id": identity, "after_id": target, "match_basis": basis,
186
+ "kinds": kinds, "delta_frames": frame_delta if compatible else None,
187
+ "delta_seconds": {k: _rational(v) for k, v in second_delta.items()},
188
+ "metadata_changes": metadata_changes,
189
+ "before_range": _range(previous, old_rate),
190
+ "after_range": _range(current, new_rate)})
191
+ for identity in sorted(new.keys() - used):
192
+ changes.append({"before_id": None, "after_id": identity,
193
+ "kinds": ["added"], "match_basis": "unmatched",
194
+ "before_range": None, "after_range": _range(new[identity], new_rate),
195
+ "before_cue": None, "after_cue": deepcopy(new[identity])})
196
+ picture_changed = before["timeline"] != after["timeline"]
197
+ unmatched = any(c["match_basis"] == "unmatched" for c in changes)
198
+ return {"schema": "film-picture-changes/v1",
199
+ "status": "compared" if compatible else "incompatible_frame_rates",
200
+ "frame_rates_compatible": compatible, "before": old_picture, "after": new_picture,
201
+ "picture_metadata_changed": picture_changed,
202
+ "identity_map": deepcopy(mapping), "changes": changes, "unchanged_count": unchanged,
203
+ "position_only_unchanged": position_only,
204
+ "requires_human_review": bool(not compatible or picture_changed or unmatched or position_only),
205
+ "range_basis": "half-open frames relative to each picture origin; timeline start is metadata",
206
+ "identity_basis": "caller-stable IDs or explicit mapping; position IDs are not persistent",
207
+ "fingerprint_basis": "SHA-256 of sorted-key compact ASCII JSON documents, not picture media",
208
+ "media_identity_verified": False, "automatic_reconform": False}
209
+
210
+
211
+ def _picture_snapshot(snapshot, document, side, unknowns):
212
+ if not isinstance(snapshot, dict):
213
+ raise ValueError(f"{side}_snapshot must be an object")
214
+ _json_value(snapshot)
215
+ encoded = json.dumps(snapshot, sort_keys=True, separators=(",", ":"),
216
+ ensure_ascii=True, allow_nan=False).encode("ascii")
217
+ if len(encoded) > 8 * 1024 * 1024:
218
+ raise ValueError("Snapshot exceeds 8 MiB canonical JSON limit")
219
+ fingerprint = hashlib.sha256(encoded).hexdigest()
220
+ origin = snapshot.get("start_frame")
221
+ uncertain = False
222
+
223
+ def unknown(reason):
224
+ nonlocal uncertain
225
+ uncertain = True
226
+ unknowns.append({"side": side, "reason": reason})
227
+
228
+ try:
229
+ _integer(origin, "snapshot.start_frame")
230
+ except ValueError:
231
+ origin = None
232
+ unknown("Snapshot origin is unavailable")
233
+ if origin is not None and origin != document["timeline"]["start_frame"]:
234
+ raise ValueError(f"{side} cue sheet/snapshot origins differ")
235
+ if snapshot.get("name") is not None and snapshot["name"] != document["timeline"]["name"]:
236
+ raise ValueError(f"{side} cue sheet/snapshot names differ")
237
+ tracks = snapshot.get("tracks")
238
+ video = tracks.get("video") if isinstance(tracks, dict) else None
239
+ if not isinstance(video, dict) or not isinstance(video.get("tracks"), list):
240
+ unknown("Video track enumeration is unavailable")
241
+ return {}, origin, fingerprint, uncertain
242
+ if type(video.get("track_count")) is not int or video["track_count"] != len(video["tracks"]):
243
+ unknown("Video track count is missing or inconsistent")
244
+ indexed, total = {}, 0
245
+ for track in video["tracks"]:
246
+ if not isinstance(track, dict):
247
+ unknown("Video track is unreadable")
248
+ continue
249
+ index = _integer(track.get("track_index"), "video.track_index", 1)
250
+ if index in indexed:
251
+ raise ValueError("Duplicate video track index")
252
+ items = track.get("items")
253
+ if not isinstance(items, list):
254
+ unknown(f"Video track {index} item enumeration is unavailable")
255
+ items = []
256
+ if type(track.get("item_count")) is not int or track["item_count"] != len(items):
257
+ unknown(f"Video track {index} item count is missing or inconsistent")
258
+ total += len(items)
259
+ if total > 10000:
260
+ raise ValueError("Snapshot exceeds 10000 video items")
261
+ indexed[index] = items
262
+ return indexed, origin, fingerprint, uncertain
263
+
264
+
265
+ def _picture_item(item, origin):
266
+ """Return relative span/signature and evidence completeness, without matching."""
267
+ if not isinstance(item, dict):
268
+ return None, None, True
269
+ try:
270
+ start = _integer(item.get("start"), "video item start")
271
+ end = _integer(item.get("end"), "video item end")
272
+ if origin is None or end <= start:
273
+ raise ValueError("Unknown video interval")
274
+ span = (start - origin, end - origin)
275
+ except ValueError:
276
+ span = None
277
+ incomplete = span is None
278
+ for key in ("source_start", "source_end", "source_fps"):
279
+ value = item.get(key)
280
+ if (type(value) not in (int, float) or not math.isfinite(value)
281
+ or (key == "source_fps" and value <= 0)):
282
+ incomplete = True
283
+ if not isinstance(item.get("file_path"), str) or not item["file_path"]:
284
+ incomplete = True
285
+ # Duplicating timelines or reimporting media regenerates object IDs. They
286
+ # are not picture content; array position already supplies enumeration.
287
+ ignored = {"timeline_item_id", "item_index"}
288
+ if isinstance(item.get("file_path"), str) and item["file_path"]:
289
+ ignored.add("media_pool_item_id")
290
+ # Keep the path itself: ignoring a pool ID never equates different paths.
291
+ signature = {key: value for key, value in item.items() if key not in ignored}
292
+ if span is not None:
293
+ signature.update(start=span[0], end=span[1])
294
+ return span, signature, incomplete
295
+
296
+
297
+ def _impacted_cues(cues, spans, unlocated):
298
+ if unlocated:
299
+ return sorted(cues)
300
+ # Merge only for intersection lookup; the report retains every changed slot.
301
+ merged = []
302
+ for start, end in sorted(spans):
303
+ if merged and start <= merged[-1][1]:
304
+ merged[-1][1] = max(end, merged[-1][1])
305
+ else:
306
+ merged.append([start, end])
307
+ ends = [end for _, end in merged]
308
+ affected = []
309
+ for identity, cue in sorted(cues.items()):
310
+ index = bisect_right(ends, cue["start_frame"])
311
+ if index < len(merged) and merged[index][0] < cue["start_frame"] + cue["duration_frames"]:
312
+ affected.append(identity)
313
+ return affected
314
+
315
+
316
+ def compare_picture_impact(before: dict, after: dict, before_snapshot: dict,
317
+ after_snapshot: dict, editorial_comparison: dict) -> dict:
318
+ """Conservative structural impact by track/array slot, never clip identity.
319
+
320
+ Main supplies the existing conform comparison. Unknown unlocatable spans
321
+ make every cue on that side potentially affected; unknown source coordinates
322
+ with known timeline spans mark just those spans. No application calls occur.
323
+ """
324
+ old_rate, old_cues, _ = _validate(before, "before")
325
+ new_rate, new_cues, _ = _validate(after, "after")
326
+ if not isinstance(editorial_comparison, dict):
327
+ raise ValueError("editorial_comparison must be an object")
328
+ _json_value(editorial_comparison)
329
+ unknowns = []
330
+ old, old_origin, old_hash, old_uncertain = _picture_snapshot(before_snapshot, before, "before", unknowns)
331
+ new, new_origin, new_hash, new_uncertain = _picture_snapshot(after_snapshot, after, "after", unknowns)
332
+ compatible = old_rate == new_rate
333
+ ranges, spans = [], {"before": [], "after": []}
334
+ unlocated = {"before": old_uncertain, "after": new_uncertain}
335
+ for track in sorted(old.keys() | new.keys()):
336
+ a_items, b_items = old.get(track, []), new.get(track, [])
337
+ for index in range(max(len(a_items), len(b_items))):
338
+ entries = []
339
+ for side, items, origin, rate in (("before", a_items, old_origin, old_rate),
340
+ ("after", b_items, new_origin, new_rate)):
341
+ if index >= len(items):
342
+ entries.append(None)
343
+ continue
344
+ span, signature, incomplete = _picture_item(items[index], origin)
345
+ entries.append((span, signature, incomplete, side, rate))
346
+ if incomplete:
347
+ unknowns.append({"side": side, "track_index": track, "item_index": index,
348
+ "reason": "Video item has unknown timeline/source coordinates or media path"})
349
+ if span is None:
350
+ unlocated[side] = True
351
+ left, right = entries
352
+ changed = (left is None or right is None or not compatible
353
+ or left[2] or right[2] or left[1] != right[1])
354
+ if not changed:
355
+ continue
356
+ for entry in entries:
357
+ if entry is None or entry[0] is None:
358
+ continue
359
+ (start, end), _, incomplete, side, rate = entry
360
+ spans[side].append((start, end))
361
+ ranges.append({"side": side, "track_index": track, "item_index": index,
362
+ "start_frame": start, "end_frame": end,
363
+ "start_seconds": _rational(Fraction(start) / rate),
364
+ "end_seconds": _rational(Fraction(end) / rate),
365
+ "evidence_status": "unknown" if incomplete else "structural_change"})
366
+ return {"schema": "film-picture-impact/v1",
367
+ "status": "unknown" if unknowns else "compared" if compatible else "incompatible_frame_rates",
368
+ "frame_rates_compatible": compatible,
369
+ "before_affected_cue_ids": _impacted_cues(old_cues, spans["before"], unlocated["before"]),
370
+ "after_affected_cue_ids": _impacted_cues(new_cues, spans["after"], unlocated["after"]),
371
+ "changed_ranges": ranges, "unknowns": unknowns,
372
+ "unlocated_impact": unlocated,
373
+ "before_snapshot_fingerprint": old_hash, "after_snapshot_fingerprint": new_hash,
374
+ "editorial_comparison": deepcopy(editorial_comparison),
375
+ "requires_human_review": bool(ranges or unknowns or not compatible),
376
+ "comparison_basis": "video track index and array position only; both sides of changed slots",
377
+ "range_basis": "half-open frames relative to each snapshot origin, intersected with that version's cues",
378
+ "fingerprint_basis": "SHA-256 of complete sorted-key compact ASCII JSON snapshots, not media bytes",
379
+ "structural_only": True, "media_identity_verified": False,
380
+ "grade_effects_verified": False, "clip_correspondence_inferred": False,
381
+ "automatic_reconform": False}
@@ -0,0 +1,162 @@
1
+ """Read-only evidence-based film handoff preflight."""
2
+ from fractions import Fraction
3
+ import math
4
+ from pathlib import Path
5
+ import wave
6
+
7
+ from .film_stem_return import audit_package, digest, file_hash, integer
8
+
9
+
10
+ def _bound_file(path, expected):
11
+ if not isinstance(path,str) or not Path(path).is_absolute(): raise ValueError('Evidence path must be absolute')
12
+ if not isinstance(expected,str) or len(expected)!=64 or file_hash(path)!=expected:
13
+ raise ValueError('Evidence file hash changed or is invalid')
14
+
15
+
16
+ def _tail_peak(path, sample_rate):
17
+ with wave.open(path,'rb') as wav:
18
+ count=min(wav.getnframes(),max(1,sample_rate//100))
19
+ wav.setpos(wav.getnframes()-count)
20
+ raw=wav.readframes(count)
21
+ return max((abs(int.from_bytes(raw[i:i+3],'little',signed=True))/8388608
22
+ for i in range(0,len(raw),3)),default=0.0)
23
+
24
+
25
+ def _tempo(evidence):
26
+ if not isinstance(evidence,dict) or evidence.get('schema')!='film-tempo/v1' or evidence.get('status')!='ok':
27
+ raise ValueError('Expected successful film-tempo/v1 receipt')
28
+ _bound_file(evidence.get('source_set_path'),evidence.get('source_sha256'))
29
+ maps=evidence.get('tempo_map_beats')
30
+ if not isinstance(maps,list) or not 1<=len(maps)<=1000: raise ValueError('Invalid tempo map')
31
+ last=-1
32
+ for i,row in enumerate(maps):
33
+ beat,bpm=row['start_beats'],row['bpm']
34
+ if any(isinstance(v,bool) or not isinstance(v,(int,float)) or not math.isfinite(v) for v in (beat,bpm)):
35
+ raise ValueError('Invalid tempo values')
36
+ if (i==0 and beat!=0) or beat<=last or not 20<=bpm<=999: raise ValueError('Invalid tempo steps')
37
+ last=beat
38
+ return {'source_set_path':evidence['source_set_path'],'source_sha256':evidence['source_sha256'],
39
+ 'segments':len(maps),'mode':evidence.get('mode'),'saved_only':True}
40
+
41
+
42
+ def _calibration(evidence,configuration):
43
+ if not isinstance(evidence,dict) or evidence.get('schema')!='film-calibration/v1' or evidence.get('status')!='measured':
44
+ raise ValueError('Expected measured film-calibration/v1 receipt')
45
+ if not isinstance(configuration,dict): raise ValueError('Current capture_profile is required with calibration evidence')
46
+ if digest(configuration)!=evidence.get('configuration_sha256'): raise ValueError('Capture configuration changed')
47
+ if digest({k:v for k,v in evidence.items() if k!='profile_sha256'})!=evidence.get('profile_sha256'):
48
+ raise ValueError('Calibration receipt hash mismatch')
49
+ probe=evidence['probe']; _bound_file(probe['path'],probe['sha256'])
50
+ captures=evidence.get('captures')
51
+ if not isinstance(captures,list) or not 2<=len(captures)<=5: raise ValueError('Expected 2-5 calibration captures')
52
+ for capture in captures: _bound_file(capture['path'],capture['sha256'])
53
+ offset=evidence.get('offset_samples')
54
+ if type(offset) is not int or evidence.get('correction_samples')!=-offset: raise ValueError('Invalid offset evidence')
55
+ return {'profile_sha256':evidence['profile_sha256'],'offset_samples':offset,
56
+ 'configuration_matches':True,'files_match':True,'dsp_remeasured_here':False,
57
+ 'absolute_picture_alignment_verified':False}
58
+
59
+
60
+ def preflight(cue_sheet, snapshot, missing_media, *, delivery_dir=None,
61
+ expected_picture_fingerprint=None, tempo_evidence=None,
62
+ calibration_evidence=None, capture_profile=None, loudness_path=None,
63
+ target_lufs=None, true_peak_max=None):
64
+ """Evidence integrity is not proof of current hardware settings or creative approval."""
65
+ if not isinstance(cue_sheet,dict) or cue_sheet.get('schema')!='film-cues/v1':
66
+ raise ValueError('Expected film-cues/v1')
67
+ rate=cue_sheet['frame_rate']
68
+ fps=Fraction(integer(rate['numerator'],'numerator',1),integer(rate['denominator'],'denominator',1))
69
+ if not 1<=fps<=240: raise ValueError('Invalid frame rate')
70
+ start=integer(snapshot['start_frame'],'timeline start')
71
+ end=integer(snapshot['end_frame'],'timeline end')
72
+ if end<start or not snapshot.get('id'): raise ValueError('Invalid picture snapshot')
73
+ if cue_sheet['timeline']['start_frame']!=start: raise ValueError('Cue/snapshot origin mismatch')
74
+ cues=cue_sheet.get('cues')
75
+ if not isinstance(cues,list) or len(cues)>10000: raise ValueError('Invalid cue collection')
76
+ ranges=[]; ids=set()
77
+ for cue in cues:
78
+ if not isinstance(cue,dict) or not isinstance(cue.get('id'),str) or not cue['id'] or cue['id'] in ids:
79
+ raise ValueError('Cue IDs must be unique nonempty strings')
80
+ ids.add(cue['id'])
81
+ a=integer(cue.get('start_frame'),'cue frame'); b=a+integer(cue.get('duration_frames'),'cue duration',1)
82
+ ranges.append((cue['id'],a,b))
83
+ # Audio changes do not invalidate the picture baseline. This is structural
84
+ # identity, not a rendered-image/grade/effects/content hash.
85
+ picture={'id':snapshot['id'],'name':snapshot.get('name'),'start_frame':start,
86
+ 'frame_rate':rate,'video':snapshot.get('tracks',{}).get('video'),
87
+ 'cues':cue_sheet}
88
+ fingerprint=digest(picture); checks=[]
89
+ def add(name,status,detail=None,**evidence):
90
+ checks.append({'name':name,'status':status,'detail':detail,**evidence})
91
+ add('picture_version','unknown' if expected_picture_fingerprint is None else
92
+ ('pass' if fingerprint==expected_picture_fingerprint else 'fail'),
93
+ 'Structural picture/cue fingerprint; not rendered-image, grade or source-content verification.',
94
+ fingerprint=fingerprint)
95
+ video_items=[item for track in snapshot.get('tracks',{}).get('video',{}).get('tracks',[])
96
+ for item in track.get('items',[])]
97
+ video_ends=[item.get('end') for item in video_items]
98
+ picture_end=max(video_ends) if video_ends and all(type(v) is int and v>=start for v in video_ends) else None
99
+ out=[identity for identity,a,b in ranges if picture_end is not None and b>picture_end-start]
100
+ add('cue_range','unknown' if picture_end is None else 'fail' if out else ('pass' if ranges else 'warn'),
101
+ 'Cues checked against video extent, not the potentially longer audio timeline.',
102
+ out_of_range=out,picture_end_frame=picture_end)
103
+ if not isinstance(missing_media,dict): add('missing_media','unknown','Media inspection unavailable')
104
+ else:
105
+ missing=integer(missing_media.get('missing_count'),'missing_count')
106
+ unlinked=integer(missing_media.get('unlinked_count'),'unlinked_count')
107
+ present=integer(missing_media.get('present_count'),'present_count')
108
+ unknown=sum(1 for kind in snapshot.get('tracks',{}).values()
109
+ for track in kind.get('tracks',[]) for item in track.get('items',[])
110
+ if not item.get('file_path'))
111
+ add('missing_media','fail' if missing else 'unknown' if unknown else ('warn' if unlinked or not present else 'pass'),
112
+ 'Source presence from the existing conform inspection; no relink performed.',
113
+ missing_count=missing,unlinked_count=unlinked,present_count=present,unknown_count=unknown)
114
+ audit=None
115
+ if delivery_dir is None: add('delivery','unknown','No film-stems/v1 package supplied')
116
+ else:
117
+ try:
118
+ audit=audit_package(delivery_dir); m=audit['manifest']
119
+ delivered_fps=Fraction(m['frame_rate']['numerator'],m['frame_rate']['denominator'])
120
+ if delivered_fps!=fps: raise ValueError('Delivery/picture frame rates differ')
121
+ uncovered=[identity for identity,a,b in ranges if a<m['start_frame'] or b>m['end_frame']]
122
+ peaks=[{'name':s['name'],'last_10ms_peak':_tail_peak(s['path'],m['sample_rate'])} for s in audit['stems']]
123
+ for stem in audit['stems']: _bound_file(stem['path'],stem['sha256'])
124
+ add('delivery','pass','PCM24 headers, counts and hashes verified',package_id=audit['package_id'])
125
+ add('stem_cue_coverage','warn' if uncovered else 'pass',
126
+ 'Cue coverage against package body; cue markers may include non-music notes.',uncovered_cues=uncovered)
127
+ add('tails','warn' if any(p['last_10ms_peak']>.001 for p in peaks) else 'pass',
128
+ 'Measured endpoint quietness, not proof that the chosen reverb tail is artistically complete.',
129
+ tail_frames=m['tail_frames'],measurements=peaks)
130
+ except (ValueError,OSError,KeyError,TypeError,EOFError,wave.Error) as exc:
131
+ add('delivery','fail',str(exc))
132
+ if tempo_evidence is None: add('tempo','unknown','No saved-set tempo evidence supplied')
133
+ else:
134
+ try: add('tempo','warn','Saved receipt/file checked; live state, map origin and unsaved tempo remain unverified.',**_tempo(tempo_evidence))
135
+ except (ValueError,OSError,KeyError,TypeError) as exc: add('tempo','fail',str(exc))
136
+ if calibration_evidence is None: add('capture_alignment','unknown','No calibration evidence supplied')
137
+ else:
138
+ try: add('capture_alignment','warn','Receipt/config/file integrity checked. Use Ableton validate_capture_calibration for fresh DSP; actual settings and absolute picture origin remain caller-verified.',**_calibration(calibration_evidence,capture_profile))
139
+ except (ValueError,OSError,KeyError,TypeError) as exc: add('capture_alignment','fail',str(exc))
140
+ if loudness_path is None: add('loudness','unknown','No final mix or stem selected for measurement')
141
+ else:
142
+ try:
143
+ from .mix_plan import measure
144
+ path=str(Path(loudness_path).resolve(strict=True)); sha=file_hash(path)
145
+ measured=measure(path); _bound_file(path,sha)
146
+ values=[measured.get('integrated_lufs'),measured.get('true_peak_dbtp')]
147
+ if any(not isinstance(v,(int,float)) or not math.isfinite(v) for v in values):
148
+ raise ValueError('No finite loudness/true-peak reading')
149
+ if target_lufs is None or true_peak_max is None:
150
+ status='unknown'; detail='Measured; explicit delivery targets required for pass/fail'
151
+ else:
152
+ if any(isinstance(v,bool) or not isinstance(v,(int,float)) or not math.isfinite(v) for v in (target_lufs,true_peak_max)):
153
+ raise ValueError('Loudness targets must be finite numbers')
154
+ status='pass' if abs(values[0]-target_lufs)<=.5 and values[1]<=true_peak_max else 'fail'
155
+ detail='Whole-file integrated LUFS ±0.5 and true peak; not dialogue-gated measurement'
156
+ add('loudness',status,detail,measurement=measured,sha256=sha)
157
+ except Exception as exc: add('loudness','unknown','Measurement unavailable: '+str(exc))
158
+ states={c['status'] for c in checks}
159
+ status='failed' if 'fail' in states else 'incomplete' if 'unknown' in states else 'warnings' if 'warn' in states else 'passed'
160
+ return {'schema':'film-preflight/v1','status':status,'picture_fingerprint':fingerprint,
161
+ 'timeline_id':snapshot['id'],'checks':checks,'mutations':0,
162
+ 'creative_approval_verified':False}