File size: 5,703 Bytes
dd6abf3
 
 
6cbe073
 
 
 
 
 
dd6abf3
6cbe073
dd6abf3
 
6cbe073
dd6abf3
 
 
 
 
 
 
 
 
 
 
 
 
6cbe073
 
 
 
 
 
 
 
 
 
 
 
 
dd6abf3
 
6cbe073
 
dd6abf3
 
6cbe073
 
 
dd6abf3
 
 
 
 
 
 
 
 
 
 
 
 
6cbe073
 
 
 
 
 
 
 
 
 
 
dd6abf3
6cbe073
 
 
 
 
 
dd6abf3
6cbe073
 
7da3ebf
 
 
 
 
 
 
 
 
304293a
 
 
7da3ebf
304293a
 
 
 
 
 
 
7da3ebf
304293a
 
7da3ebf
 
304293a
7da3ebf
dd6abf3
 
 
7da3ebf
 
 
304293a
7da3ebf
 
304293a
7da3ebf
dd6abf3
 
 
 
 
 
 
 
 
 
 
 
 
 
 
304293a
dd6abf3
304293a
 
 
 
 
 
dd6abf3
 
304293a
7da3ebf
 
 
 
 
 
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
"""ffmpeg helpers: video duration, single-frame screenshots and the 720p
re-encode. Every call has a time limit, so a broken file can never hang a scan.
"""

from __future__ import annotations

import json
import logging
import os
import re
import subprocess
import threading
import time

log = logging.getLogger("frames")

# The worker has a system ffmpeg; Render uses the pip-installed static one.
try:
    import imageio_ffmpeg
    FFMPEG = imageio_ffmpeg.get_ffmpeg_exe()
except Exception:  # noqa: BLE001
    FFMPEG = "ffmpeg"

PROBE_TIMEOUT = 60  # seconds
FRAME_TIMEOUT = 120
PREPARE_STALL = 300  # kill the re-encode if ffmpeg reports no progress for 5 min
PREPARE_MAX = 6 * 3600


def mmss(seconds: float) -> str:
    """Format seconds as mm:ss (or h:mm:ss past an hour)."""
    seconds = max(0, int(round(seconds)))
    h, rem = divmod(seconds, 3600)
    m, s = divmod(rem, 60)
    if h:
        return f"{h}:{m:02d}:{s:02d}"
    return f"{m:02d}:{s:02d}"


def probe_duration(video_path: str) -> float | None:
    """The video length in seconds (ffprobe, or ffmpeg's header when there is
    no ffprobe), or None if it can't be read."""
    try:
        out = subprocess.run(
            ["ffprobe", "-v", "quiet", "-print_format", "json", "-show_format", video_path],
            capture_output=True, text=True, check=True, timeout=PROBE_TIMEOUT,
        )
        return float(json.loads(out.stdout)["format"]["duration"])
    except Exception:  # noqa: BLE001
        pass
    try:
        out = subprocess.run(
            [FFMPEG, "-hide_banner", "-i", video_path],
            capture_output=True, text=True, timeout=PROBE_TIMEOUT,
        )
        m = re.search(r"Duration:\s*(\d+):(\d+):(\d+(?:\.\d+)?)", out.stderr or "")
        if m:
            return int(m.group(1)) * 3600 + int(m.group(2)) * 60 + float(m.group(3))
    except Exception:  # noqa: BLE001
        pass
    log.warning("could not read duration for %s", video_path)
    return None


def extract_frame(video_path: str, at_seconds: float, out_path: str) -> str:
    """Grab a single JPEG frame at `at_seconds`. Returns the output path.

    `-ss` before `-i` gives a fast keyframe-accurate seek, which is plenty for a
    representative thumbnail.
    """
    os.makedirs(os.path.dirname(out_path) or ".", exist_ok=True)
    subprocess.run(
        [
            FFMPEG, "-y",
            "-ss", f"{max(0.0, at_seconds):.3f}",
            "-i", video_path,
            "-frames:v", "1",
            "-q:v", "2",
            out_path,
        ],
        capture_output=True, check=True, timeout=FRAME_TIMEOUT,
    )
    return out_path


# Gemini's File API takes files up to 2 GB, and some camera formats (ProRes in
# .mov, etc.) are not accepted. Big or unusual files are re-encoded to a 720p
# H.264 MP4 first: plenty for the analysis and screenshots, and much faster.
SHRINK_ABOVE_BYTES = 1_500_000_000
GEMINI_FRIENDLY_EXTS = (".mp4", ".webm")


def needs_prepare(video_path: str, size: int | None = None) -> bool:
    """True if the file must be re-encoded before Gemini (too big or unusual format)."""
    size = os.path.getsize(video_path) if size is None and os.path.exists(video_path) else (size or 0)
    ext = os.path.splitext(video_path)[1].lower()
    return size > SHRINK_ABOVE_BYTES or ext not in GEMINI_FRIENDLY_EXTS


def prepare_for_gemini(video_path: str, workdir: str, duration: float | None = None, on_progress=None) -> str:
    """Return a path Gemini can take: the original, or a 720p MP4 copy.
    on_progress(fraction) follows ffmpeg's position when the length is known."""
    if not needs_prepare(video_path):
        return video_path
    size = os.path.getsize(video_path)
    ext = os.path.splitext(video_path)[1].lower()
    out_path = os.path.join(workdir, "prepared.mp4")
    log.info("Re-encoding %s (%d bytes, %s) to 720p MP4 for analysis", video_path, size, ext or "no ext")
    proc = subprocess.Popen(
        [
            FFMPEG, "-y", "-i", video_path,
            # even height (H.264 needs it): 720 or the source height if smaller
            "-vf", "scale=-2:'trunc(min(720,ih)/2)*2'",
            "-c:v", "libx264", "-preset", "veryfast", "-crf", "26", "-pix_fmt", "yuv420p",
            "-c:a", "aac", "-b:a", "96k",
            "-movflags", "+faststart",
            "-progress", "pipe:1", "-nostats",
            out_path,
        ],
        stdout=subprocess.PIPE, stderr=subprocess.DEVNULL, text=True,
    )

    # watchdog: stop ffmpeg if it stalls or runs far too long
    started = last_output = time.time()
    killed = threading.Event()

    def watch() -> None:
        while proc.poll() is None:
            now = time.time()
            if now - last_output > PREPARE_STALL or now - started > PREPARE_MAX:
                killed.set()
                proc.kill()
                return
            time.sleep(5)

    threading.Thread(target=watch, daemon=True).start()
    for line in proc.stdout or []:
        last_output = time.time()
        if on_progress and duration and line.startswith("out_time_us="):
            try:
                on_progress(min(1.0, int(line.split("=", 1)[1]) / 1e6 / duration))
            except ValueError:
                pass
    if proc.wait() != 0:
        if killed.is_set():
            raise RuntimeError("Converting this video took too long. Please export it as an MP4 (H.264) and try again.")
        raise RuntimeError("Could not convert this video. Please export it as an MP4 and try again.")
    try:
        os.remove(video_path)  # free the disk: a camera original can be many GB
    except OSError:
        pass
    log.info("Prepared %s (%d bytes)", out_path, os.path.getsize(out_path))
    return out_path