File size: 8,305 Bytes
9abdbe8
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
from __future__ import annotations

import csv
import os
import shutil
import subprocess
from dataclasses import dataclass
from pathlib import Path
from typing import List, Optional

import numpy as np


TRANSNETV2_INPUT_CHANNELS = 3

FFMPEG_LOGLEVEL = "error"
FFMPEG_PIXEL_FORMAT_RGB24 = "rgb24"
FFMPEG_SCALE_FLAGS = "fast_bilinear"
FFMPEG_STDOUT_PIPE = "pipe:1"

FFMPEG_ENVIRONMENT_VARIABLE_KEYS = ("IMAGEIO_FFMPEG_EXE", "FFMPEG_BINARY")

SAFE_MAP_ARGS = ["-map", "0:v:0", "-map", "0:a?", "-dn", "-sn"]

CLIP_ID_NUMBER_WIDTH = 4


@dataclass(frozen=True)
class VideoSegment:
    path: Path
    start_seconds: float
    end_seconds: float


def resolve_ffmpeg_executable() -> str:
    """
    Resolve ffmpeg executable path:
    1) env var IMAGEIO_FFMPEG_EXE / FFMPEG_BINARY
    2) system PATH
    3) imageio-ffmpeg
    """

    for key in FFMPEG_ENVIRONMENT_VARIABLE_KEYS:
        configured_value = os.getenv(key)
        if not configured_value:
            continue

        configured_path = Path(configured_value).expanduser()
        if configured_path.exists():
            return str(configured_path)

        resolved_from_path = shutil.which(configured_value)
        if resolved_from_path:
            return resolved_from_path

    ffmpeg_in_path = shutil.which("ffmpeg")
    if ffmpeg_in_path:
        return ffmpeg_in_path

    try:
        import imageio_ffmpeg

        ffmpeg_from_imageio = imageio_ffmpeg.get_ffmpeg_exe()
        if ffmpeg_from_imageio:
            return ffmpeg_from_imageio
    except Exception:
        pass

    raise RuntimeError("ffmpeg not found (checked env vars, PATH, and imageio-ffmpeg).")


def read_video_frames_as_rgb24(
    input_video: Path,
    ffmpeg_executable: str,
    *,
    frames_per_second: int,
    target_width: int,
    target_height: int,
) -> np.ndarray:
    """
    Use ffmpeg to decode frames at fixed FPS and fixed size, output as raw RGB24 bytes.
    """

    video_filter = (
        f"fps={frames_per_second},"
        f"scale={target_width}:{target_height}:flags={FFMPEG_SCALE_FLAGS}"
    )

    command = [
        ffmpeg_executable,
        "-hide_banner",
        "-loglevel",
        FFMPEG_LOGLEVEL,
        "-nostdin",
        "-i",
        str(input_video),
        "-an",
        "-vf",
        video_filter,
        "-pix_fmt",
        FFMPEG_PIXEL_FORMAT_RGB24,
        "-f",
        "rawvideo",
        FFMPEG_STDOUT_PIPE,
    ]

    process = subprocess.Popen(command, stdout=subprocess.PIPE, stderr=subprocess.PIPE)

    stdout_bytes, stderr_bytes = process.communicate()

    if process.returncode != 0:
        raise RuntimeError(
            f"ffmpeg frame extraction failed: {input_video}\n"
            f"{stderr_bytes.decode('utf-8', errors='replace')}"
        )

    bytes_per_frame = target_width * target_height * TRANSNETV2_INPUT_CHANNELS

    frame_count = len(stdout_bytes) // bytes_per_frame

    if frame_count <= 0:
        return np.empty((0, target_height, target_width, 3), dtype=np.uint8)

    stdout_bytes = stdout_bytes[: frame_count * bytes_per_frame]

    frames = np.frombuffer(stdout_bytes, dtype=np.uint8).reshape(
        (frame_count, target_height, target_width, 3)
    )

    return frames


def segment_video_stream_copy_with_ffmpeg(
    input_video: Path,
    ffmpeg_executable: str,
    *,
    split_points_seconds: List[float],
    output_directory: Path,
    filename_prefix: str,
    start_index: int = 0,
) -> List[VideoSegment]:

    output_directory.mkdir(parents=True, exist_ok=True)

    if not split_points_seconds:

        output_path = output_directory / f"{filename_prefix}_{start_index:04d}.mp4"

        command = [
            ffmpeg_executable,
            "-hide_banner",
            "-loglevel",
            FFMPEG_LOGLEVEL,
            "-nostdin",
            "-y",
            "-i",
            str(input_video),
            *SAFE_MAP_ARGS,
            "-c",
            "copy",
            "-movflags",
            "+faststart",
            str(output_path),
        ]

        completed = subprocess.run(command, stdout=subprocess.PIPE, stderr=subprocess.PIPE)

        if completed.returncode != 0:
            raise RuntimeError(
                f"ffmpeg stream copy failed: {input_video}\n"
                f"{completed.stderr.decode('utf-8', errors='replace')}"
            )

        return [VideoSegment(path=output_path, start_seconds=0.0, end_seconds=-1.0)]

    split_points_argument = ",".join(f"{t:.3f}" for t in split_points_seconds)

    segment_list_csv_path = output_directory / f"{filename_prefix}_{start_index:04d}.csv"

    output_pattern = output_directory / f"{filename_prefix}_%04d.mp4"

    command = [
        ffmpeg_executable,
        "-hide_banner",
        "-loglevel",
        FFMPEG_LOGLEVEL,
        "-nostdin",
        "-y",
        "-i",
        str(input_video),
        *SAFE_MAP_ARGS,
        "-c",
        "copy",
        "-f",
        "segment",
        "-segment_start_number",
        str(start_index),
        "-segment_list",
        str(segment_list_csv_path),
        "-segment_list_type",
        "csv",
        "-segment_times",
        split_points_argument,
        "-reset_timestamps",
        "1",
        "-segment_format_options",
        "movflags=+faststart",
        str(output_pattern),
    ]

    completed = subprocess.run(command, stdout=subprocess.PIPE, stderr=subprocess.PIPE)

    if completed.returncode != 0:
        raise RuntimeError(
            f"ffmpeg segment failed: {input_video}\n"
            f"{completed.stderr.decode('utf-8', errors='replace')}"
        )

    segments: List[VideoSegment] = []

    with segment_list_csv_path.open("r", encoding="utf-8") as f:

        reader = csv.reader(f)

        for row in reader:
            if not row or len(row) < 3:
                continue

            segments.append(
                VideoSegment(
                    path=output_directory / row[0],
                    start_seconds=float(row[1]),
                    end_seconds=float(row[2]),
                )
            )

    return segments

def cut_video_segment_with_ffmpeg(
    video_path: Path,
    start: float,
    end: float,
    output_path: Path,
    ffmpeg_executable: str = "ffmpeg",
    video_codec: str = "libx264",
    audio_codec: str = "aac",
    extra_args: Optional[List[str]] = None,
) -> VideoSegment:
    """
    Precisely cut a video segment using ffmpeg and return a VideoSegment object.
    
    Args:
        video_path: Path to the input video file.
        start: Segment start time in seconds.
        end: Segment end time in seconds.
        output_path: Path to the output video file.
        ffmpeg_executable: Path to ffmpeg executable (default "ffmpeg").
        video_codec: Video codec for output (default "libx264").
        audio_codec: Audio codec for output (default "aac").
        extra_args: Optional list of additional ffmpeg arguments.
        
    Returns:
        VideoSegment: Object containing the output path and start/end times.
        
    Raises:
        RuntimeError: If ffmpeg fails to cut the video.
    """
    # Ensure output directory exists
    output_path.parent.mkdir(parents=True, exist_ok=True)

    # Construct ffmpeg command
    command = [
        ffmpeg_executable,
        "-hide_banner",
        "-loglevel", "error",    # only show errors
        "-y",                    # overwrite output if exists
        "-ss", f"{start:.3f}",   # precise start time
        "-to", f"{end:.3f}",     # precise end time
        "-i", str(video_path),
        "-c:v", video_codec,     # video codec
        "-c:a", audio_codec,     # audio codec
        "-movflags", "+faststart",  # optimize for streaming
    ]

    if extra_args:
        command.extend(extra_args)

    command.append(str(output_path))

    # Run ffmpeg
    completed = subprocess.run(command, stdout=subprocess.PIPE, stderr=subprocess.PIPE)

    if completed.returncode != 0:
        raise RuntimeError(
            f"ffmpeg failed to cut video:\n{video_path}\n"
            f"start={start}, end={end}\n"
            f"{completed.stderr.decode('utf-8', errors='replace')}"
        )

    # Return VideoSegment with exact requested start/end
    return VideoSegment(
        path=output_path,
        start_seconds=start,
        end_seconds=end
    )