File size: 7,480 Bytes
c585bf5
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
8694a57
c585bf5
 
8694a57
c585bf5
 
 
 
 
 
 
 
 
 
 
 
 
8694a57
 
c585bf5
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
8694a57
 
c585bf5
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
#!/usr/bin/env python3
"""Extract every frame from the released 1 FPS videos, without media hosting."""

import argparse
import json
import shutil
import struct
import subprocess
import tempfile
from concurrent.futures import ThreadPoolExecutor
from fractions import Fraction
from pathlib import Path


def relative_file(root, value):
    path = Path(value)
    if path.is_absolute() or ".." in path.parts or "\\" in value:
        raise ValueError(f"Expected a relative media path: {value}")
    resolved = (root / path).resolve()
    if not resolved.is_relative_to(root.resolve()) or not resolved.is_file():
        raise ValueError(f"Missing media or path outside the dataset: {value}")
    return resolved


def validate_video(path, expected):
    result = subprocess.run(
        ["ffprobe", "-v", "error", "-analyzeduration", "0", "-probesize", "32768", "-show_entries",
         "stream=codec_type,avg_frame_rate,r_frame_rate,nb_frames,duration,start_time",
         "-of", "json", str(path)],
        check=True, capture_output=True, text=True, timeout=120,
    )
    streams = json.loads(result.stdout)["streams"]
    if len(streams) != 1 or streams[0]["codec_type"] != "video":
        raise ValueError(f"Expected one video stream without audio: {path.name}")
    stream = streams[0]
    if (Fraction(stream["avg_frame_rate"]) != 1
            or Fraction(stream["r_frame_rate"]) != 1
            or int(stream["nb_frames"]) != expected
            or abs(float(stream["duration"]) - expected) > 0.001
            or abs(float(stream["start_time"])) > 0.001):
        raise ValueError(f"Expected a zero-based 1 FPS/{expected}-frame video: {path.name}")


def decode_video(source, dest, expected):
    """Decode a validated video into ordered PNGs, replacing its frame cache."""
    dest.parent.mkdir(parents=True, exist_ok=True)
    names = [f"frame_{i:03d}.png" for i in range(expected)]
    with tempfile.TemporaryDirectory(prefix=source.stem + "-", dir=dest.parent) as temp:
        temp = Path(temp)
        subprocess.run(
            ["ffmpeg", "-nostdin", "-v", "error", "-xerror", "-threads", "1",
             "-i", str(source), "-map", "0:v:0", "-vsync", "0",
             "-threads", "1", "-start_number", "0", str(temp / "frame_%03d.png")],
            check=True, capture_output=True, timeout=300,
        )
        actual = sorted(p.name for p in temp.glob("*.png"))
        if actual != names or any((temp / name).stat().st_size == 0 for name in names):
            raise ValueError(f"Decoded frame count mismatch: {source.name}")
        if dest.exists():
            shutil.rmtree(dest)
        temp.rename(dest)
    return expected


def validate_frame_cache(root, record, video_info):
    """Check registered frame paths, order, byte sizes and PNG dimensions."""
    video = video_info["path"]
    n = video_info["n_frames"]
    if (record["video"] != video
            or record["n_frames"] != n or record["fps"] != 1
            or type(record["width"]) is not int or record["width"] <= 0
            or type(record["height"]) is not int or record["height"] <= 0
            or len(record["frames"]) != n):
        raise ValueError(f"Frame manifest does not match the video: {video}")
    directory = Path("runtime/frames") / Path(video).stem
    expected = [f"frame_{i:03d}.png" for i in range(n)]
    if sorted(p.name for p in (root / directory).glob("*.png")) != expected:
        raise ValueError(f"Cached frame count or filenames are incorrect: {video}")
    for i, frame in enumerate(record["frames"]):
        if frame["index"] != i or frame["path"] != str(directory / expected[i]):
            raise ValueError(f"Cached frame order is incorrect: {video}")
        path = relative_file(root, frame["path"])
        if path.stat().st_size != frame["bytes"]:
            raise ValueError(f"Cached frame byte size mismatch: {frame['path']}")
        with path.open("rb") as handle:
            header = handle.read(24)
        if (len(header) != 24 or header[:8] != b"\x89PNG\r\n\x1a\n"
                or header[12:16] != b"IHDR"
                or struct.unpack(">II", header[16:24]) != (record["width"], record["height"])):
            raise ValueError(f"Cached PNG dimensions differ from frames.jsonl: {frame['path']}")


def extract(root, output_dir, videos=None, workers=4):
    """Validate and decode registered videos; no QA or remote services required."""
    protected = (root / "runtime/frames").resolve()
    output = output_dir.resolve()
    if output.is_relative_to(protected) or protected.is_relative_to(output):
        raise ValueError("Decoded MP4 frames must not overwrite the original-resolution benchmark frames")
    records = [json.loads(line) for line in (root / "media.jsonl").read_text(encoding="utf-8").splitlines() if line.strip()]
    inventory = {record["path"]: record for record in records}
    if not inventory or len(inventory) != len(records):
        raise ValueError("Media inventory must be nonempty and contain unique paths")
    selected = list(dict.fromkeys(videos)) if videos else list(inventory)
    unknown = set(selected) - set(inventory)
    if unknown:
        raise ValueError(f"Videos absent from media.jsonl: {sorted(unknown)}")
    stems = [Path(path).stem for path in selected]
    if len(set(stems)) != len(stems):
        raise ValueError("Video filenames must have unique stems for frame directories")
    # Check destinations before starting any decode or replacing any frame cache.
    for relative in selected:
        source = relative_file(root, relative)
        dest = output_dir / source.stem
        if dest.is_symlink():
            raise ValueError(f"Frame output must not be a symlink: {dest.name}")
        resolved = dest.resolve()
        if root.resolve().is_relative_to(resolved) or (root / "media").resolve().is_relative_to(resolved):
            raise ValueError("Frame output must not replace the dataset or media directory")

    def process(relative):
        source = relative_file(root, relative)
        record = inventory[relative]
        if record["fps"] != 1 or type(record["n_frames"]) is not int or record["n_frames"] < 1:
            raise ValueError(f"Expected 1 FPS and a positive frame count: {relative}")
        if source.stat().st_size != record["bytes"]:
            raise ValueError(f"Video byte size mismatch: {relative}")
        validate_video(source, record["n_frames"])
        return decode_video(source, output_dir / source.stem, record["n_frames"])

    with ThreadPoolExecutor(max_workers=workers) as pool:
        counts = list(pool.map(process, selected))
    return {"videos": len(selected), "frames": sum(counts)}


def main():
    parser = argparse.ArgumentParser(description=__doc__)
    parser.add_argument("--data-root", type=Path, default=Path(__file__).resolve().parent)
    parser.add_argument("--output-dir", type=Path, help="Output directory; default: DATA_ROOT/runtime/decoded_frames")
    parser.add_argument("--video", action="append", help="A video path from media.jsonl, e.g. media/0000.mp4; repeat to select more")
    parser.add_argument("--workers", type=int, default=4)
    args = parser.parse_args()
    if args.workers < 1:
        parser.error("--workers must be positive")
    root = args.data_root.resolve()
    output = args.output_dir.resolve() if args.output_dir else root / "runtime/decoded_frames"
    print(json.dumps(extract(root, output, args.video, args.workers)))


if __name__ == "__main__":
    main()