-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathvideo_utils.py
More file actions
158 lines (132 loc) · 4.89 KB
/
video_utils.py
File metadata and controls
158 lines (132 loc) · 4.89 KB
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
"""ffmpeg/ffprobe wrapper utilities for video processing."""
import json
import subprocess
import tempfile
from pathlib import Path
def get_video_info(video_path: str) -> dict:
"""Get video metadata using ffprobe."""
path = Path(video_path).expanduser().resolve()
if not path.exists():
raise FileNotFoundError(f"Video file not found: {path}")
cmd = [
"ffprobe",
"-v", "quiet",
"-print_format", "json",
"-show_format",
"-show_streams",
str(path),
]
result = subprocess.run(cmd, capture_output=True, text=True, timeout=30)
if result.returncode != 0:
raise RuntimeError(f"ffprobe failed: {result.stderr}")
probe = json.loads(result.stdout)
fmt = probe.get("format", {})
streams = probe.get("streams", [])
video_stream = next((s for s in streams if s.get("codec_type") == "video"), None)
audio_stream = next((s for s in streams if s.get("codec_type") == "audio"), None)
info: dict = {
"file_path": str(path),
"file_size_mb": round(int(fmt.get("size", 0)) / (1024 * 1024), 2),
"duration_seconds": round(float(fmt.get("duration", 0)), 2),
"format_name": fmt.get("format_name", "unknown"),
"bit_rate_kbps": round(int(fmt.get("bit_rate", 0)) / 1000),
}
if video_stream:
info["video"] = {
"codec": video_stream.get("codec_name", "unknown"),
"width": video_stream.get("width"),
"height": video_stream.get("height"),
"fps": _parse_fps(video_stream.get("r_frame_rate", "0/1")),
"total_frames": int(video_stream.get("nb_frames", 0) or 0),
}
if audio_stream:
info["audio"] = {
"codec": audio_stream.get("codec_name", "unknown"),
"sample_rate": audio_stream.get("sample_rate", "unknown"),
"channels": audio_stream.get("channels", 0),
}
return info
def extract_frames(
video_path: str,
fps: float = 1.0,
max_frames: int = 20,
quality: int = 5,
output_dir: str | None = None,
) -> dict:
"""Extract frames from video at specified fps.
Args:
video_path: Path to video file.
fps: Frames per second to extract.
max_frames: Maximum number of frames to extract.
quality: JPEG quality (2=best, 31=worst).
output_dir: Directory to save frames. Auto-created if None.
Returns:
Dict with output_dir and list of frame paths.
"""
path = Path(video_path).expanduser().resolve()
if not path.exists():
raise FileNotFoundError(f"Video file not found: {path}")
if output_dir:
out = Path(output_dir).expanduser().resolve()
out.mkdir(parents=True, exist_ok=True)
else:
out = Path(tempfile.mkdtemp(prefix="video-analyzer-"))
# Get duration to calculate frame count
info = get_video_info(str(path))
duration = info.get("duration_seconds", 0)
estimated_frames = int(duration * fps)
actual_max = min(estimated_frames, max_frames) if estimated_frames > 0 else max_frames
# Use vframes to limit output
cmd = [
"ffmpeg",
"-i", str(path),
"-vf", f"fps={fps}",
"-vframes", str(actual_max),
"-q:v", str(quality),
"-y",
str(out / "frame_%04d.jpg"),
]
result = subprocess.run(cmd, capture_output=True, text=True, timeout=300)
if result.returncode != 0:
raise RuntimeError(f"ffmpeg frame extraction failed: {result.stderr}")
frames = sorted(out.glob("frame_*.jpg"))
return {
"output_dir": str(out),
"frame_count": len(frames),
"frame_paths": [str(f) for f in frames],
}
def extract_audio(video_path: str, output_path: str | None = None) -> str:
"""Extract audio track from video as WAV.
Returns path to extracted audio file.
"""
path = Path(video_path).expanduser().resolve()
if not path.exists():
raise FileNotFoundError(f"Video file not found: {path}")
if output_path:
audio_path = Path(output_path).expanduser().resolve()
else:
tmp = tempfile.mktemp(prefix="video-analyzer-audio-", suffix=".wav")
audio_path = Path(tmp)
cmd = [
"ffmpeg",
"-i", str(path),
"-vn",
"-acodec", "pcm_s16le",
"-ar", "16000",
"-ac", "1",
"-y",
str(audio_path),
]
result = subprocess.run(cmd, capture_output=True, text=True, timeout=300)
if result.returncode != 0:
raise RuntimeError(f"ffmpeg audio extraction failed: {result.stderr}")
return str(audio_path)
def _parse_fps(rate_str: str) -> float:
"""Parse ffprobe frame rate string like '30/1' or '29.97'."""
try:
if "/" in rate_str:
num, den = rate_str.split("/")
return round(float(num) / float(den), 2) if float(den) != 0 else 0.0
return round(float(rate_str), 2)
except (ValueError, ZeroDivisionError):
return 0.0