File size: 9,607 Bytes
fac4aaf
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
#!/usr/bin/env python3
"""Visualize pixel-level differences between two videos."""

from __future__ import annotations

import argparse
import csv
import json
import subprocess
from pathlib import Path

import numpy as np


def run_json(cmd: list[str]) -> dict:
    out = subprocess.check_output(cmd, text=True)
    return json.loads(out)


def probe_video(path: Path) -> dict:
    data = run_json(
        [
            "ffprobe",
            "-v",
            "error",
            "-select_streams",
            "v:0",
            "-show_entries",
            "stream=width,height,avg_frame_rate,nb_frames,duration",
            "-of",
            "json",
            str(path),
        ]
    )
    stream = data["streams"][0]
    return {
        "width": int(stream["width"]),
        "height": int(stream["height"]),
        "avg_frame_rate": stream.get("avg_frame_rate", "0/1"),
        "nb_frames": int(stream["nb_frames"]) if stream.get("nb_frames", "N/A").isdigit() else None,
        "duration": float(stream.get("duration", 0.0)),
    }


def parse_rate(rate: str) -> float:
    num, den = rate.split("/")
    return float(num) / float(den)


def open_reader(path: Path, width: int, height: int, fps: float | None = None, align: bool = False) -> subprocess.Popen:
    cmd = [
        "ffmpeg",
        "-v",
        "error",
        "-i",
        str(path),
    ]
    if align:
        if fps is None:
            raise ValueError("fps is required when align=True")
        cmd += ["-vf", f"scale={width}:{height}:flags=bicubic,fps={fps:.6f}"]
    cmd += [
        "-f",
        "rawvideo",
        "-pix_fmt",
        "rgb24",
        "-",
    ]
    return subprocess.Popen(
        cmd,
        stdout=subprocess.PIPE,
    )


def open_writer(path: Path, width: int, height: int, fps: float) -> subprocess.Popen:
    return subprocess.Popen(
        [
            "ffmpeg",
            "-y",
            "-v",
            "error",
            "-f",
            "rawvideo",
            "-pix_fmt",
            "rgb24",
            "-s",
            f"{width}x{height}",
            "-r",
            f"{fps:.6f}",
            "-i",
            "-",
            "-an",
            "-pix_fmt",
            "yuv420p",
            "-c:v",
            "mpeg4",
            "-q:v",
            "2",
            str(path),
        ],
        stdin=subprocess.PIPE,
    )


def read_frame(proc: subprocess.Popen, frame_bytes: int) -> bytes | None:
    assert proc.stdout is not None
    data = proc.stdout.read(frame_bytes)
    if len(data) == 0:
        return None
    if len(data) != frame_bytes:
        raise RuntimeError(f"Short frame read: expected {frame_bytes} bytes, got {len(data)}")
    return data


def close_proc(proc: subprocess.Popen) -> None:
    try:
        proc.wait(timeout=5)
    except subprocess.TimeoutExpired:
        proc.kill()
        proc.wait()


def make_heatmap(diff_mag: np.ndarray, changed: np.ndarray, show_all_diffs: bool) -> np.ndarray:
    heat = np.zeros((*diff_mag.shape, 3), dtype=np.uint8)
    visible_diff = diff_mag if show_all_diffs else np.where(changed, diff_mag, 0)
    heat[..., 0] = visible_diff
    heat[..., 1] = np.where(changed, np.clip(diff_mag // 3, 0, 255), 0).astype(np.uint8)
    return heat


def compare_videos(args: argparse.Namespace) -> None:
    original = args.original.resolve()
    edited = args.edited.resolve()
    output_dir = args.output_dir.resolve()
    output_dir.mkdir(parents=True, exist_ok=True)

    original_info = probe_video(original)
    edited_info = probe_video(edited)
    width = original_info["width"]
    height = original_info["height"]
    fps = parse_rate(original_info["avg_frame_rate"])
    mismatch = (width, height) != (edited_info["width"], edited_info["height"])
    fps_mismatch = original_info["avg_frame_rate"] != edited_info["avg_frame_rate"]
    if (mismatch or fps_mismatch) and not args.align_edited_to_original:
        raise ValueError(
            "Video geometry mismatch. For strict pixel-by-pixel comparison, compare a final composited video "
            "with the same resolution and fps as the original. To inspect a raw model output anyway, rerun with "
            f"--align-edited-to-original. original={original_info}, edited={edited_info}"
        )

    frame_bytes = width * height * 3
    max_frames = args.max_frames
    if max_frames is None:
        candidates = [original_info["nb_frames"]]
        if not args.align_edited_to_original:
            candidates.append(edited_info["nb_frames"])
        candidates = [v for v in candidates if v is not None]
        max_frames = min(candidates) if candidates else 10**12

    reader_a = open_reader(original, width, height)
    reader_b = open_reader(edited, width, height, fps=fps, align=args.align_edited_to_original)
    writers = {
        "changed_mask": open_writer(output_dir / "changed_mask.mp4", width, height, fps),
        "diff_heatmap": open_writer(output_dir / "diff_heatmap.mp4", width, height, fps),
        "diff_overlay": open_writer(output_dir / "diff_overlay.mp4", width, height, fps),
    }

    rows: list[dict[str, int | float]] = []
    total_changed = 0
    total_pixels = 0
    threshold = args.threshold

    try:
        for frame_index in range(max_frames):
            raw_a = read_frame(reader_a, frame_bytes)
            raw_b = read_frame(reader_b, frame_bytes)
            if raw_a is None or raw_b is None:
                break

            a = np.frombuffer(raw_a, dtype=np.uint8).reshape((height, width, 3))
            b = np.frombuffer(raw_b, dtype=np.uint8).reshape((height, width, 3))
            absdiff = np.abs(a.astype(np.int16) - b.astype(np.int16)).astype(np.uint8)
            diff_mag = absdiff.max(axis=2)
            changed = diff_mag > threshold
            changed_count = int(changed.sum())
            total_changed += changed_count
            total_pixels += width * height

            mask_rgb = np.repeat((changed.astype(np.uint8) * 255)[:, :, None], 3, axis=2)
            heat = make_heatmap(diff_mag, changed, args.heatmap_all_diffs)
            overlay = a.copy()
            overlay[changed] = (overlay[changed].astype(np.uint16) // 3 + np.array([170, 0, 0], dtype=np.uint16)).clip(0, 255).astype(np.uint8)

            assert writers["changed_mask"].stdin is not None
            assert writers["diff_heatmap"].stdin is not None
            assert writers["diff_overlay"].stdin is not None
            writers["changed_mask"].stdin.write(mask_rgb.tobytes())
            writers["diff_heatmap"].stdin.write(heat.tobytes())
            writers["diff_overlay"].stdin.write(overlay.tobytes())

            rows.append(
                {
                    "frame": frame_index,
                    "changed_pixels": changed_count,
                    "total_pixels": width * height,
                    "changed_ratio": changed_count / (width * height),
                    "mean_abs_diff": float(absdiff.mean()),
                    "max_abs_diff": int(absdiff.max()),
                }
            )
    finally:
        for writer in writers.values():
            if writer.stdin is not None:
                writer.stdin.close()
            close_proc(writer)
        close_proc(reader_a)
        close_proc(reader_b)

    with (output_dir / "per_frame_stats.csv").open("w", newline="", encoding="utf-8") as handle:
        fieldnames = ["frame", "changed_pixels", "total_pixels", "changed_ratio", "mean_abs_diff", "max_abs_diff"]
        writer = csv.DictWriter(handle, fieldnames=fieldnames)
        writer.writeheader()
        writer.writerows(rows)

    summary = {
        "original": str(original),
        "edited": str(edited),
        "original_info": original_info,
        "edited_info": edited_info,
        "threshold": threshold,
        "heatmap_all_diffs": args.heatmap_all_diffs,
        "align_edited_to_original": args.align_edited_to_original,
        "compared_frames": len(rows),
        "changed_pixels": total_changed,
        "total_pixels": total_pixels,
        "changed_ratio": total_changed / total_pixels if total_pixels else 0.0,
        "outputs": {
            "changed_mask": str(output_dir / "changed_mask.mp4"),
            "diff_heatmap": str(output_dir / "diff_heatmap.mp4"),
            "diff_overlay": str(output_dir / "diff_overlay.mp4"),
            "per_frame_stats": str(output_dir / "per_frame_stats.csv"),
        },
    }
    (output_dir / "summary.json").write_text(json.dumps(summary, indent=2), encoding="utf-8")
    print(json.dumps(summary, indent=2))


def parse_args() -> argparse.Namespace:
    parser = argparse.ArgumentParser(description="Create pixel-level video difference visualizations.")
    parser.add_argument("--original", type=Path, required=True)
    parser.add_argument("--edited", type=Path, required=True)
    parser.add_argument("--output-dir", type=Path, required=True)
    parser.add_argument("--threshold", type=int, default=2, help="Per-channel max RGB diff threshold before a pixel counts as changed.")
    parser.add_argument(
        "--heatmap-all-diffs",
        action="store_true",
        help="Show every nonzero diff in diff_heatmap. By default, diff_heatmap only shows pixels above --threshold.",
    )
    parser.add_argument("--max-frames", type=int)
    parser.add_argument(
        "--align-edited-to-original",
        action="store_true",
        help="Scale and resample the edited video to the original resolution/fps before comparing. Use for raw model outputs.",
    )
    return parser.parse_args()


if __name__ == "__main__":
    compare_videos(parse_args())