Spaces:
Running

File size: 8,748 Bytes
b83d389
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
57cb628
 
 
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
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
# Copyright (c) Meta Platforms, Inc. and affiliates.
# All rights reserved.
#
# This source code is licensed under the BSD-style license found in the
# LICENSE file in the root directory of this source tree.

"""FFmpeg helpers: probe, segment extraction, encode, VMAF/SSIM, bitrate."""

from __future__ import annotations

import json
import logging
import re
import subprocess
import tempfile
import time
from pathlib import Path
from typing import Any

logger = logging.getLogger(__name__)


def _run_ffmpeg(args: list[str], *, timeout: float | None = None) -> subprocess.CompletedProcess[str]:
    return subprocess.run(
        args,
        capture_output=True,
        text=True,
        timeout=timeout,
        check=False,
    )


def ffprobe_duration_sec(path: Path) -> float:
    """Return container duration in seconds."""
    r = _run_ffmpeg(
        [
            "ffprobe",
            "-v",
            "error",
            "-show_entries",
            "format=duration",
            "-of",
            "default=noprint_wrappers=1:nokey=1",
            str(path),
        ]
    )
    if r.returncode != 0:
        raise RuntimeError(f"ffprobe failed for {path}: {r.stderr}")
    return float(r.stdout.strip())


def ffprobe_video_size(path: Path) -> tuple[int, int]:
    """Return width, height of the first video stream."""
    r = _run_ffmpeg(
        [
            "ffprobe",
            "-v",
            "error",
            "-select_streams",
            "v:0",
            "-show_entries",
            "stream=width,height",
            "-of",
            "csv=p=0:s=x",
            str(path),
        ]
    )
    if r.returncode != 0:
        raise RuntimeError(f"ffprobe size failed for {path}: {r.stderr}")
    parts = r.stdout.strip().split("x")
    if len(parts) != 2:
        raise RuntimeError(f"unexpected ffprobe size output: {r.stdout!r}")
    return int(parts[0]), int(parts[1])


def extract_segment(
    input_path: Path,
    start_sec: float,
    duration_sec: float,
    output_path: Path,
    *,
    timeout: float | None = None,
) -> None:
    """Extract [start_sec, start_sec+duration) to output_path (re-encode for robust cuts)."""
    output_path.parent.mkdir(parents=True, exist_ok=True)
    args = [
        "ffmpeg",
        "-hide_banner",
        "-loglevel",
        "error",
        "-y",
        "-ss",
        f"{start_sec:.4f}",
        "-i",
        str(input_path),
        "-t",
        f"{duration_sec:.4f}",
        "-c:v",
        "libx264",
        "-preset",
        "ultrafast",
        "-crf",
        "18",
        "-an",
        "-movflags",
        "+faststart",
        str(output_path),
    ]
    r = _run_ffmpeg(args, timeout=timeout)
    if r.returncode != 0:
        raise RuntimeError(f"ffmpeg segment extract failed: {r.stderr}")


def encode_segment(
    input_path: Path,
    output_path: Path,
    *,
    width: int,
    height: int,
    crf: int,
    preset: str,
    timeout: float | None = None,
) -> float:
    """Encode input to H.264 with scale + CRF. Returns wall-clock seconds for the encode."""
    output_path.parent.mkdir(parents=True, exist_ok=True)
    vf = f"scale={width}:{height}:flags=bicubic"
    args = [
        "ffmpeg",
        "-hide_banner",
        "-loglevel",
        "error",
        "-y",
        "-i",
        str(input_path),
        "-vf",
        vf,
        "-c:v",
        "libx264",
        "-preset",
        preset,
        "-crf",
        str(crf),
        "-an",
        "-movflags",
        "+faststart",
        str(output_path),
    ]
    t0 = time.perf_counter()
    r = _run_ffmpeg(args, timeout=timeout)
    elapsed = time.perf_counter() - t0
    if r.returncode != 0:
        raise RuntimeError(f"ffmpeg encode failed: {r.stderr}")
    return elapsed


def ffprobe_bitrate_kbps(path: Path) -> float:
    """Average bitrate in kbps from container format."""
    r = _run_ffmpeg(
        [
            "ffprobe",
            "-v",
            "error",
            "-show_entries",
            "format=bit_rate",
            "-of",
            "default=noprint_wrappers=1:nokey=1",
            str(path),
        ]
    )
    if r.returncode != 0:
        raise RuntimeError(f"ffprobe bitrate failed: {r.stderr}")
    line = r.stdout.strip()
    if not line or line == "N/A":
        size = path.stat().st_size
        dur = ffprobe_duration_sec(path)
        if dur <= 0:
            return 0.0
        return (size * 8) / dur / 1000.0
    return float(line) / 1000.0


def _read_vmaf_json(log_path: Path) -> float | None:
    try:
        data = json.loads(log_path.read_text())
    except (OSError, json.JSONDecodeError):
        return None
    pm = data.get("pooled_metrics")
    if isinstance(pm, dict) and "vmaf" in pm:
        v = pm["vmaf"]
        if isinstance(v, dict) and "mean" in v:
            return float(v["mean"])
    if "vmaf" in data and isinstance(data["vmaf"], dict):
        m = data["vmaf"].get("mean")
        if m is not None:
            return float(m)
    frames = data.get("frames")
    if isinstance(frames, list) and frames:
        metrics = frames[-1].get("metrics") or {}
        vmaf = metrics.get("vmaf")
        if vmaf is not None:
            return float(vmaf)
    return None


def _vmaf_from_stderr(stderr: str) -> float | None:
    m = re.search(r"VMAF[\s\w]*[:=]\s*([0-9]+(?:\.[0-9]+)?)", stderr, re.I)
    if m:
        return float(m.group(1))
    return None


def vmaf_score(
    distorted_path: Path,
    reference_path: Path,
    *,
    timeout: float | None = None,
) -> float | None:
    """
    Pooled VMAF mean (0..100) via libvmaf.
    Input 0 = distorted, input 1 = reference. Both streams are scaled to the
    distorted file's width/height — libvmaf requires matching dimensions on both inputs.
    """
    try:
        w, h = ffprobe_video_size(distorted_path)
    except RuntimeError as e:
        logger.warning("vmaf: could not read distorted size: %s", e)
        return None

    with tempfile.NamedTemporaryFile(suffix=".json", delete=False) as tmp:
        log_path = Path(tmp.name)
    try:
        lp = str(log_path)
        fc = (
            f"[0:v]scale={w}:{h}:flags=bicubic[dist];"
            f"[1:v]scale={w}:{h}:flags=bicubic[ref];"
            f"[dist][ref]libvmaf=log_path={lp}:log_fmt=json"
        )
        args = [
            "ffmpeg",
            "-hide_banner",
            "-loglevel",
            "error",
            "-i",
            str(distorted_path),
            "-i",
            str(reference_path),
            "-filter_complex",
            fc,
            "-f",
            "null",
            "-",
        ]
        r = _run_ffmpeg(args, timeout=timeout)
        pooled = _read_vmaf_json(log_path)
        if pooled is not None:
            return pooled
        if r.returncode != 0:
            logger.warning("libvmaf failed: %s", r.stderr)
        return _vmaf_from_stderr(r.stderr or "")
    finally:
        if log_path.exists():
            log_path.unlink(missing_ok=True)


def ssim_score(
    distorted_path: Path,
    reference_path: Path,
    *,
    timeout: float | None = None,
) -> float | None:
    """
    SSIM All (roughly 0..1). Distorted first, reference second.
    Both streams are scaled to the distorted resolution (same as VMAF).
    """
    try:
        w, h = ffprobe_video_size(distorted_path)
    except RuntimeError as e:
        logger.warning("ssim: could not read distorted size: %s", e)
        return None

    fc = (
        f"[0:v]scale={w}:{h}:flags=bicubic[dist];"
        f"[1:v]scale={w}:{h}:flags=bicubic[ref];"
        f"[dist][ref]ssim"
    )
    args = [
        "ffmpeg",
        "-hide_banner",
        "-loglevel",
        "info",
        "-i",
        str(distorted_path),
        "-i",
        str(reference_path),
        "-filter_complex",
        fc,
        "-f",
        "null",
        "-",
    ]
    r = _run_ffmpeg(args, timeout=timeout)
    if r.returncode != 0:
        logger.warning("ssim filter failed: %s", r.stderr)
        return None
    text = r.stderr + r.stdout
    m = re.search(r"All:([0-9.]+)", text)
    if m:
        return float(m.group(1))
    return None


def build_segment_features(
    segment_path: Path,
    *,
    video_id: str,
    segment_index: int,
) -> dict[str, Any]:
    w, h = ffprobe_video_size(segment_path)
    dur = ffprobe_duration_sec(segment_path)
    return {
        "segment_id": f"{video_id}_{segment_index:05d}",
        "video_id": video_id,
        "segment_index": segment_index,
        "duration_sec": dur,
        "width": w,
        "height": h,
        "file_size_bytes": segment_path.stat().st_size,
    }

if __name__ == "__main__":
    vmaf_score("./videos/sample_video.mp4", "./videos/sample_video.mp4", 1000)