cmvr-visual/inference/llm_services/video_edit/media.py

168 lines
5.1 KiB
Python
Raw Permalink Normal View History

"""Timestamp-based CFR decode and exact-length mux, with bounded dimensions."""
import json
import math
import subprocess
def command(args):
return subprocess.run(args, check=True, capture_output=True).stdout
def probe(path):
return json.loads(
command(
[
"ffprobe",
"-v",
"error",
"-show_streams",
"-show_format",
"-of",
"json",
str(path),
]
)
)
def dimensions(width, height, pixels):
scale = min(1, math.sqrt(pixels / (width * height)))
return max(16, int(width * scale) // 16 * 16), max(
16, int(height * scale) // 16 * 16
)
def display_dimensions(video):
"""Square-pixel display geometry after FFmpeg's default autorotation."""
width, height = float(video["width"]), float(video["height"])
sar = video.get("sample_aspect_ratio", "1:1")
if sar not in (None, "N/A", "0:1"):
try:
numerator, denominator = map(float, sar.split(":"))
ratio = numerator / denominator
except (ValueError, ZeroDivisionError, AttributeError) as exc:
raise ValueError("Invalid source sample aspect ratio") from exc
if not math.isfinite(ratio) or ratio <= 0:
raise ValueError("Invalid source sample aspect ratio")
width *= ratio
rotation = next(
(
item["rotation"]
for item in video.get("side_data_list", [])
if "rotation" in item
),
video.get("tags", {}).get("rotate", 0),
)
rotation = float(rotation)
if not math.isfinite(rotation) or not math.isclose(
rotation / 90, round(rotation / 90), abs_tol=1e-5
):
raise ValueError("Unsupported non-right-angle video display rotation")
if round(rotation / 90) % 2:
width, height = height, width
if not all(math.isfinite(value) and value > 0 for value in (width, height)):
raise ValueError("Invalid video display dimensions")
return width, height
def decode(source, target, pixels, max_seconds):
info = probe(source)
video = next((s for s in info["streams"] if s["codec_type"] == "video"), None)
if not video:
raise ValueError("Source has no video stream")
# 容器时长可能由更长音轨撑大,不能作为视频时间轴。MKV等缺失
# stream.duration时,在既有有界CFR解码后由视频帧数确定时长。
try:
duration = float(video["duration"])
except (KeyError, TypeError, ValueError):
duration = None
if duration is not None and (not math.isfinite(duration) or duration <= 0):
duration = None
if duration is not None and duration > max_seconds:
raise ValueError("Source duration exceeds video editing budget")
width, height = dimensions(*display_dimensions(video), pixels)
target.mkdir()
command(
[
"ffmpeg",
"-v",
"error",
"-i",
str(source),
"-map",
"0:v:0",
"-vf",
f"fps=24,scale={width}:{height},setsar=1",
"-frames:v",
str(max_seconds * 24 + 1),
"-start_number",
"0",
str(target / "%06d.png"),
]
)
frames = len(list(target.glob("*.png")))
if frames > max_seconds * 24:
raise ValueError("Decoded video exceeds configured duration budget")
if not frames:
raise ValueError("Source video has no decodable frames")
if duration is None:
duration = frames / 24
elif abs(frames / 24 - duration) > 1 / 24 + 0.001:
raise ValueError("Decoded frame count does not preserve source duration")
return {
"width": width,
"height": height,
"fps": 24,
"frames": frames,
"duration_seconds": duration,
"source_has_audio": any(s["codec_type"] == "audio" for s in info["streams"]),
}
def mux(frames, source, target, video, preserve_audio):
args = [
"ffmpeg",
"-v",
"error",
"-framerate",
"24",
"-start_number",
"0",
"-i",
str(frames / "%06d.png"),
]
if preserve_audio:
args += ["-i", str(source), "-map", "0:v:0", "-map", "1:a:0?", "-c:a", "aac"]
else:
args += ["-map", "0:v:0", "-an"]
args += [
"-c:v",
"libx264",
"-crf",
"16",
"-pix_fmt",
"yuv420p",
"-frames:v",
str(video["frames"]),
"-t",
str(video["duration_seconds"]),
"-movflags",
"+faststart",
str(target),
]
command(args)
info = probe(target)
stream = next(s for s in info["streams"] if s["codec_type"] == "video")
if (
int(stream.get("nb_frames", 0)) != video["frames"]
or stream["avg_frame_rate"] != "24/1"
):
raise ValueError("Encoded output frame count/fps mismatch")
if (
preserve_audio
and video["source_has_audio"]
and not any(s["codec_type"] == "audio" for s in info["streams"])
):
raise ValueError("Source audio was lost during mux")