File size: 3,970 Bytes
09c6e66
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
"""Bounded media inspection at the actual decoded presentation clock."""
import hashlib
import json
import subprocess
from fractions import Fraction
from pathlib import Path


class MediaError(RuntimeError):
    pass


class MediaToolError(MediaError):
    pass


def sha256(path):
    digest = hashlib.sha256()
    with Path(path).open('rb') as stream:
        for block in iter(lambda: stream.read(1024 * 1024), b''):
            digest.update(block)
    return digest.hexdigest()


def run_json(args, timeout=120):
    try:
        p = subprocess.run(args, capture_output=True, text=True, timeout=timeout)
    except (OSError, subprocess.TimeoutExpired) as exc:
        raise MediaToolError(f'Media tool unavailable or timed out: {exc}') from exc
    if p.returncode:
        raise MediaError(p.stderr[-1500:] or f'Media tool exit {p.returncode}')
    try:
        return json.loads(p.stdout)
    except json.JSONDecodeError as exc:
        raise MediaError('Invalid media tool response') from exc


def probe(path):
    path = Path(path)
    if not path.is_file() or not path.stat().st_size:
        return {'path': str(path), 'status': 'missing', 'decoded': False}
    try:
        meta = run_json(['ffprobe', '-v', 'error', '-select_streams', 'v:0',
            '-count_frames', '-show_streams', '-show_format', '-show_frames',
            '-show_entries', 'stream=width,height,avg_frame_rate,r_frame_rate,nb_read_frames,codec_name,pix_fmt:format=duration:frame=best_effort_timestamp_time,pkt_duration_time',
            '-of', 'json', str(path)])
        if not meta.get('streams'):
            raise MediaError('No video stream')
        stream = meta['streams'][0]
        times = [float(f['best_effort_timestamp_time']) for f in meta.get('frames', [])
                 if 'best_effort_timestamp_time' in f]
        if not times or any(b <= a for a, b in zip(times, times[1:])):
            raise MediaError('Missing or nonmonotonic decoded timestamps')
        return {'path': str(path), 'status': 'ok', 'decoded': True,
            'sha256': sha256(path), 'width': stream['width'], 'height': stream['height'],
            'fps': float(Fraction(stream['avg_frame_rate'])),
            'frame_count': int(stream['nb_read_frames']),
            'duration': float(meta['format']['duration']), 'codec': stream['codec_name'],
            'pts': times, 'pixel_format': stream.get('pix_fmt')}
    except MediaToolError as exc:
        return {'path': str(path), 'status': 'verifier_error', 'decoded': False,
                'error': str(exc), 'sha256': sha256(path)}
    except (MediaError, KeyError, ValueError, ZeroDivisionError) as exc:
        return {'path': str(path), 'status': 'decode_error', 'decoded': False,
                'error': str(exc), 'sha256': sha256(path)}


def decode_rgb(path, size=(320, 180), max_frames=2000, timeout=120):
    """Decode every frame; no fps filter, preserves frame order and duration."""
    import numpy as np
    width, height = size
    if not 1 <= width <= 4096 or not 1 <= height <= 4096 or max_frames <= 0:
        raise MediaError('Invalid decode bounds')
    command = ['ffmpeg', '-v', 'error', '-i', str(path), '-map', '0:v:0',
        '-vf', f'scale={width}:{height}:flags=area', '-frames:v', str(max_frames + 1),
        '-vsync', '0', '-pix_fmt', 'rgb24', '-f', 'rawvideo', '-']
    try:
        p = subprocess.run(command, capture_output=True, timeout=timeout)
    except (OSError, subprocess.TimeoutExpired) as exc:
        raise MediaError(str(exc)) from exc
    if p.returncode:
        raise MediaError(p.stderr.decode(errors='replace')[-1500:])
    stride = width * height * 3
    if not p.stdout or len(p.stdout) % stride:
        raise MediaError('Incomplete RGB decode')
    count = len(p.stdout) // stride
    if count > max_frames:
        raise MediaError(f'Frame limit {max_frames} exceeded; inspection incomplete')
    return np.frombuffer(p.stdout, dtype=np.uint8).reshape(count, height, width, 3)