#!/usr/bin/env python3 """Read-only silent H264 timing audit; no generation, tracking or runtime approval.""" import argparse from decimal import Decimal, ROUND_HALF_EVEN from fractions import Fraction import hashlib import json from pathlib import Path import subprocess class AuditError(Exception): pass def require(value, reason): if not value: raise AuditError(reason) def file_sha(path): with path.open('rb') as stream: digest = hashlib.sha256() for block in iter(lambda: stream.read(1024 * 1024), b''): digest.update(block) return digest.hexdigest() def microseconds(value): return int((Decimal(str(value)) * 1_000_000).to_integral_value(rounding=ROUND_HALF_EVEN)) def audit(video, role, width, height, fps, ffprobe, ffmpeg): before = file_sha(video) result = subprocess.run([ ffprobe, '-v', 'error', '-show_entries', 'stream=codec_type,codec_name,width,height,r_frame_rate,duration:stream_disposition=attached_pic:frame=media_type,best_effort_timestamp_time', '-show_streams', '-show_frames', '-of', 'json', str(video), ], capture_output=True, timeout=60) require(result.returncode == 0, 'ffprobe_failed') data = json.loads(result.stdout) streams = data['streams'] require(len(streams) == 1 and streams[0]['codec_type'] == 'video', 'requires_single_video_no_audio') stream = streams[0] require(stream['codec_name'] == 'h264' and not stream.get('disposition', {}).get('attached_pic', 0), 'requires_normal_h264') require((stream['width'], stream['height']) == (width, height), 'shape_mismatch') actual_fps = Fraction(stream['r_frame_rate']) require(actual_fps == fps and 1 <= actual_fps <= 60, 'fps_mismatch') frames = [frame for frame in data['frames'] if frame.get('media_type') == 'video'] pts = [microseconds(frame['best_effort_timestamp_time']) for frame in frames] limit = 5400 if role == 'action' else 720 duration = microseconds(stream['duration']) require(2 <= len(pts) <= limit, 'frame_count_bound') require((1_000_000 if role == 'action' else 100_000) <= duration <= (90_000_000 if role == 'action' else 30_000_000), 'duration_bound') require(pts[0] == 0 and pts[-1] < duration and all(a < b for a, b in zip(pts, pts[1:])), 'invalid_actual_pts') period = Fraction(1_000_000, 1) / fps require(abs(Fraction(duration) - len(pts) * period) <= period + 2 and duration - pts[-1] <= 2 * period + 2 and all(b - a <= 2 * period + 2 for a, b in zip(pts, pts[1:])), 'timeline_inconsistent') decoded = subprocess.run([ ffmpeg, '-nostdin', '-v', 'error', '-xerror', '-i', str(video), '-map', '0:v:0', '-f', 'null', '-', ], capture_output=True, timeout=60) require(decoded.returncode == 0, 'full_decode_failed') require(file_sha(video) == before, 'source_drift') return { 'status': 'passed', 'scope': 'silent_media_only_not_runtime_admission', 'source_file': video.name, 'role': role, 'sha256': before, 'bytes': video.stat().st_size, 'codec': 'h264', 'width': width, 'height': height, 'frameCount': len(pts), 'ptsUs': pts, 'durationUs': duration, 'fpsNumerator': fps.numerator, 'fpsDenominator': fps.denominator, 'hasAudio': False, 'streams': 1, 'full_decode': 'passed', 'talking_visual_review': 'not_run', 'seam_review': 'not_run', 'production_parser': 'not_run', 'device': 'not_run', } def main(): parser = argparse.ArgumentParser(description=__doc__) parser.add_argument('--video', type=Path, required=True) parser.add_argument('--output', type=Path, required=True) parser.add_argument('--role', choices=('body', 'bridge', 'action'), required=True) parser.add_argument('--width', type=int, default=720) parser.add_argument('--height', type=int, default=1280) parser.add_argument('--fps', default='24') parser.add_argument('--ffprobe', default='ffprobe') parser.add_argument('--ffmpeg', default='ffmpeg') args = parser.parse_args() video = args.video.resolve(strict=True) output = args.output.resolve() require(video.is_file(), 'source_not_file') require(not output.exists() and not output.is_relative_to(video.parent), 'fresh_evidence_outside_media_directory_required') require((args.width, args.height) in ((720, 1280), (480, 848)), 'unsupported_target_shape') try: fps = Fraction(args.fps) require(1 <= fps <= 60, 'invalid_target_fps') report = audit(video, args.role, args.width, args.height, fps, args.ffprobe, args.ffmpeg) except AuditError as error: report = {'status': 'rejected', 'scope': 'silent_media_only_not_runtime_admission', 'reason': str(error)} except FileNotFoundError: report = {'status': 'not_run', 'reason': 'required_media_tool_missing'} except subprocess.TimeoutExpired: report = {'status': 'rejected', 'reason': 'media_tool_timeout'} except (KeyError, ValueError, TypeError, ArithmeticError): report = {'status': 'rejected', 'reason': 'invalid_probe_metadata_or_target_fps'} output.parent.mkdir(parents=True, exist_ok=True) with output.open('x') as target: json.dump(report, target, indent=2) target.write('\n') print(json.dumps({key: value for key, value in report.items() if key != 'ptsUs'})) return 0 if report['status'] == 'passed' else 1 if __name__ == '__main__': try: raise SystemExit(main()) except (AuditError, OSError) as error: print(json.dumps({'status': 'rejected', 'reason': str(error) if isinstance(error, AuditError) else 'file_operation_failed'})) raise SystemExit(1)