Files
Kronic-Krusaders/playback_planner.py
T
2026-11-25 20:20:43 -06:00

842 lines
21 KiB
Python

from __future__ import annotations
import hashlib
import json
import os
import subprocess
import threading
import time
from pathlib import Path
from typing import Any
from dotenv import load_dotenv
BASE_DIR = Path(__file__).resolve().parent
load_dotenv(BASE_DIR / "config.env")
FFMPEG_BIN = os.getenv("FFMPEG_BIN", "/usr/bin/ffmpeg")
FFPROBE_BIN = os.getenv("FFPROBE_BIN", "/usr/bin/ffprobe")
BROWSER_CACHE_DIR = Path(
os.getenv(
"BROWSER_CACHE_DIR",
str(BASE_DIR / "browser-cache"),
)
).expanduser().resolve()
BROWSER_CACHE_MAX_GB = max(
0.0,
float(os.getenv("BROWSER_CACHE_MAX_GB", "100")),
)
BROWSER_AUDIO_CHANNELS = max(
1,
min(
6,
int(os.getenv("BROWSER_AUDIO_CHANNELS", "2")),
),
)
BROWSER_AUDIO_BITRATE = os.getenv(
"BROWSER_AUDIO_BITRATE",
"192k",
)
BROWSER_X264_PRESET = os.getenv(
"BROWSER_X264_PRESET",
"veryfast",
)
BROWSER_X264_CRF = str(
int(os.getenv("BROWSER_X264_CRF", "21"))
)
QUALITY_BITRATES = {
720: os.getenv("QUALITY_720P_BITRATE", "3500k"),
480: os.getenv("QUALITY_480P_BITRATE", "1800k"),
360: os.getenv("QUALITY_360P_BITRATE", "900k"),
}
_probe_lock = threading.Lock()
_probe_cache: dict[str, tuple[tuple[int, int], dict[str, Any]]] = {}
_cache_locks_guard = threading.Lock()
_cache_locks: dict[str, threading.Lock] = {}
def _fingerprint(path: Path) -> tuple[int, int]:
stat = path.stat()
return (
int(stat.st_size),
int(stat.st_mtime_ns),
)
def _cache_lock(key: str) -> threading.Lock:
with _cache_locks_guard:
lock = _cache_locks.get(key)
if lock is None:
lock = threading.Lock()
_cache_locks[key] = lock
return lock
def probe_media(path: str | Path) -> dict[str, Any]:
path = Path(path).resolve()
fingerprint = _fingerprint(path)
cache_key = str(path)
with _probe_lock:
cached = _probe_cache.get(cache_key)
if cached and cached[0] == fingerprint:
return dict(cached[1])
command = [
FFPROBE_BIN, "-v", "error",
"-show_streams", "-show_format", "-of", "json", str(path),
]
result = subprocess.run(
command, stdout=subprocess.PIPE, stderr=subprocess.PIPE,
text=True, timeout=30, check=True,
)
raw = json.loads(result.stdout or "{}")
streams = raw.get("streams") or []
videos = [x for x in streams if x.get("codec_type") == "video"]
audios = [x for x in streams if x.get("codec_type") == "audio"]
video = videos[0] if videos else {}
audio = audios[0] if audios else {}
format_data = raw.get("format") or {}
audio_tracks = []
for ordinal, stream in enumerate(audios):
tags = stream.get("tags") or {}
disposition = stream.get("disposition") or {}
channels = _safe_int(stream.get("channels"))
layout = str(stream.get("channel_layout") or "").strip()
language = str(tags.get("language") or "").strip().lower()
title = str(tags.get("title") or "").strip()
codec = str(stream.get("codec_name") or "").lower()
audio_tracks.append({
"ordinal": ordinal,
"stream_index": _safe_int(stream.get("index")),
"codec": codec,
"codec_long_name": str(stream.get("codec_long_name") or ""),
"language": language,
"title": title,
"channels": channels,
"channel_layout": layout,
"bit_rate": _safe_int(stream.get("bit_rate")),
"sample_rate": _safe_int(stream.get("sample_rate")),
"default": bool(disposition.get("default")),
})
info = {
"path": str(path),
"suffix": path.suffix.lower(),
"size": fingerprint[0],
"mtime_ns": fingerprint[1],
"container": str(format_data.get("format_name") or "").lower(),
"duration": _safe_float(format_data.get("duration")),
"video_codec": str(video.get("codec_name") or "").lower(),
"video_profile": str(video.get("profile") or ""),
"pixel_format": str(video.get("pix_fmt") or "").lower(),
"width": _safe_int(video.get("width")),
"height": _safe_int(video.get("height")),
"video_bitrate": _safe_int(video.get("bit_rate")),
"fps": _frame_rate(video.get("avg_frame_rate") or video.get("r_frame_rate")),
"audio_codec": str(audio.get("codec_name") or "").lower(),
"audio_channels": _safe_int(audio.get("channels")),
"audio_sample_rate": _safe_int(audio.get("sample_rate")),
"audio_tracks": audio_tracks,
}
with _probe_lock:
_probe_cache[cache_key] = (fingerprint, dict(info))
return info
def quality_options(info: dict[str, Any]) -> list[dict[str, Any]]:
height = int(info.get("height") or 0)
native = f"{height}p" if height else "Original"
options = [{"value": "original", "label": f"Original {native}" if height else "Original", "height": height or None}]
for target in (720, 480, 360):
if height > target:
options.append({"value": str(target), "label": f"{target}p", "height": target, "bitrate": QUALITY_BITRATES[target]})
return options
def _safe_float(value: Any) -> float | None:
try:
return float(value)
except (TypeError, ValueError):
return None
def _safe_int(value: Any) -> int | None:
try:
return int(value)
except (TypeError, ValueError):
return None
def _frame_rate(value: Any) -> float | None:
text = str(value or "").strip()
if not text:
return None
if "/" in text:
numerator, denominator = text.split("/", 1)
try:
denominator_value = float(denominator)
if denominator_value == 0:
return None
return float(numerator) / denominator_value
except (TypeError, ValueError):
return None
return _safe_float(text)
def _truthy(value: Any) -> bool:
return str(value or "").strip().lower() in {
"1",
"true",
"yes",
"on",
"probably",
"maybe",
}
def _browser_name(value: Any) -> str:
value = str(value or "").strip().lower()
if value in {
"firefox",
"chrome",
"edge",
"safari",
"unknown",
}:
return value
return "unknown"
def plan_playback(
path: str | Path,
*,
capabilities: dict[str, Any] | None = None,
browser: str = "unknown",
force_compat: bool = False,
quality: str = "original",
audio_stream_index: int | None = None,
) -> dict[str, Any]:
info = probe_media(path)
capabilities = capabilities or {}
browser = _browser_name(browser)
quality = str(quality or "original").lower().strip()
requested_height = None if quality == "original" else _safe_int(quality)
if requested_height not in {None, 720, 480, 360}:
requested_height = None
quality = "original"
tracks = info.get("audio_tracks") or []
selected_audio = None
if audio_stream_index is not None:
selected_audio = next((t for t in tracks if t.get("stream_index") == int(audio_stream_index)), None)
if selected_audio is None and tracks:
selected_audio = next((t for t in tracks if t.get("default")), tracks[0])
selected_audio_index = selected_audio.get("stream_index") if selected_audio else None
selected_audio_codec = (selected_audio or {}).get("codec") or info.get("audio_codec") or ""
def finalize(plan: dict[str, Any]) -> dict[str, Any]:
plan["selected_audio_stream_index"] = selected_audio_index
plan["selected_audio"] = selected_audio
plan["selected_quality"] = quality
plan.setdefault("quality_options", quality_options(info))
return plan
suffix = info["suffix"]
vcodec = info["video_codec"]
acodec = selected_audio_codec
supports_h264 = _truthy(
capabilities.get("h264", True)
)
supports_av1 = _truthy(
capabilities.get("av1", False)
)
supports_hevc = _truthy(
capabilities.get("hevc", False)
)
supports_webm_vp9 = _truthy(
capabilities.get("webm_vp9", False)
)
supports_webm_av1 = _truthy(
capabilities.get("webm_av1", False)
)
is_mp4 = suffix in {
".mp4",
".m4v",
".mov",
}
is_webm = suffix == ".webm"
if requested_height is not None and int(info.get("height") or 0) > requested_height:
plan = _plan(
"transcode_stream", info, browser,
f"Manual {requested_height}p lower-bandwidth transcode selected.",
seek_mode="server",
)
plan["requested_height"] = requested_height
plan["video_bitrate"] = QUALITY_BITRATES[requested_height]
return finalize(plan)
# A retry requested by the frontend must use the most conservative path.
# Do not select remux_cache again or the retry simply repeats the same
# startup failure.
if force_compat:
return finalize(_plan(
"transcode_stream",
info,
browser,
"Forced compatibility retry: H.264/AAC live transcode.",
seek_mode="server",
))
video_direct = False
if vcodec in {
"h264",
"avc1",
}:
video_direct = supports_h264
elif vcodec == "av1":
video_direct = supports_av1
elif vcodec in {
"hevc",
"h265",
}:
video_direct = supports_hevc
elif vcodec in {
"vp9",
"vp09",
}:
video_direct = supports_webm_vp9
if vcodec == "av1" and is_webm:
video_direct = supports_webm_av1
audio_mp4_direct = acodec in {
"",
"aac",
"mp3",
}
audio_webm_direct = acodec in {
"",
"opus",
"vorbis",
}
default_track = next((t for t in tracks if t.get("default")), tracks[0] if tracks else None)
default_audio_index = default_track.get("stream_index") if default_track else None
alternate_audio_selected = (
audio_stream_index is not None
and selected_audio_index is not None
and selected_audio_index != default_audio_index
)
# The most stable path is an ordinary seekable source that the browser
# already supports. Never run FFmpeg simply because it exists.
if (
is_mp4
and video_direct
and audio_mp4_direct
and not alternate_audio_selected
):
return finalize(_plan(
"direct",
info,
browser,
"Source is already browser-compatible MP4.",
seek_mode="client",
))
if (
is_webm
and video_direct
and audio_webm_direct
and not alternate_audio_selected
):
return finalize(_plan(
"direct",
info,
browser,
"Source is already browser-compatible WebM.",
seek_mode="client",
))
# H.264 is already the desired compatibility video codec. Repackage it
# once into a normal +faststart MP4 instead of feeding Firefox an endless
# fragmented MP4 pipe on every playback.
if vcodec in {
"h264",
"avc1",
} and supports_h264:
return finalize(_plan(
"remux_stream",
info,
browser,
(
"H.264 video can be copied immediately while the selected "
"audio track is normalized for browser playback."
),
seek_mode="server",
))
# Unsupported video codecs must be transcoded while playing. Waiting for
# a full movie-length H.264 cache before first playback would be a poor UX.
return finalize(_plan(
"transcode_stream",
info,
browser,
(
f"{vcodec or 'unknown'} video is not directly usable by this "
"browser; stream a normalized H.264/AAC fragmented MP4."
),
seek_mode="server",
))
def _plan(
mode: str,
info: dict[str, Any],
browser: str,
reason: str,
*,
seek_mode: str,
) -> dict[str, Any]:
return {
"mode": mode,
"seek_mode": seek_mode,
"browser": browser,
"reason": reason,
"source": info,
"quality_options": quality_options(info),
}
def cache_path_for(
source_path: str | Path,
*,
media_id: int | str,
) -> Path:
source_path = Path(source_path).resolve()
size, mtime_ns = _fingerprint(source_path)
digest = hashlib.sha1(
(
f"{source_path}\0"
f"{size}\0"
f"{mtime_ns}\0"
"compat-mp4-v2"
).encode("utf-8")
).hexdigest()[:20]
return (
BROWSER_CACHE_DIR
/ f"{media_id}-{digest}.mp4"
)
def compatibility_cache_status(
source_path: str | Path,
*,
media_id: int | str,
) -> dict[str, Any]:
path = cache_path_for(
source_path,
media_id=media_id,
)
return {
"cached": path.is_file()
and path.stat().st_size > 0,
"path": str(path),
"size_bytes": (
path.stat().st_size
if path.is_file()
else 0
),
}
def ensure_remux_cache(
source_path: str | Path,
*,
media_id: int | str,
) -> Path:
source_path = Path(source_path).resolve()
BROWSER_CACHE_DIR.mkdir(
parents=True,
exist_ok=True,
)
destination = cache_path_for(
source_path,
media_id=media_id,
)
lock = _cache_lock(str(destination))
with lock:
if (
destination.is_file()
and destination.stat().st_size > 0
):
try:
os.utime(destination, None)
except OSError:
pass
return destination
info = probe_media(source_path)
temporary = destination.with_suffix(
".part.mp4"
)
temporary.unlink(missing_ok=True)
command = [
FFMPEG_BIN,
"-nostdin",
"-hide_banner",
"-loglevel",
"warning",
"-fflags",
"+genpts+discardcorrupt",
"-i",
str(source_path),
"-map",
"0:v:0",
"-map",
"0:a:0?",
"-sn",
"-dn",
"-c:v",
"copy",
]
if info.get("audio_codec") in {
"",
"aac",
"mp3",
}:
command.extend(
[
"-c:a",
"copy",
]
)
else:
command.extend(
[
"-c:a",
"aac",
"-b:a",
BROWSER_AUDIO_BITRATE,
"-ar",
"48000",
"-ac",
str(BROWSER_AUDIO_CHANNELS),
"-af",
"aresample=async=1:first_pts=0",
]
)
command.extend(
[
"-avoid_negative_ts",
"make_zero",
"-map_metadata",
"-1",
"-map_chapters",
"-1",
"-movflags",
"+faststart",
"-f",
"mp4",
"-y",
str(temporary),
]
)
result = subprocess.run(
command,
stdout=subprocess.DEVNULL,
stderr=subprocess.PIPE,
text=True,
)
if (
result.returncode != 0
or not temporary.is_file()
or temporary.stat().st_size <= 0
):
temporary.unlink(
missing_ok=True
)
raise RuntimeError(
"FFmpeg compatibility remux failed: "
+ (
result.stderr[-4000:]
if result.stderr
else f"return code {result.returncode}"
)
)
temporary.replace(destination)
prune_browser_cache()
return destination
def remux_stream_command(
source_path: str | Path,
*,
start_seconds: float = 0.0,
audio_stream_index: int | None = None,
) -> list[str]:
"""
Start immediately for H.264 sources that only need container/audio cleanup.
Video is copied. Audio is normalized to AAC. Output is fragmented MP4 so
the browser can begin playback before the entire movie has been remuxed.
"""
source_path = Path(source_path).resolve()
command = [
FFMPEG_BIN,
"-nostdin",
"-hide_banner",
"-loglevel",
"warning",
"-fflags",
"+genpts+discardcorrupt",
]
if start_seconds > 0:
command.extend([
"-ss",
f"{start_seconds:.3f}",
])
command.extend([
"-i",
str(source_path),
"-map",
"0:v:0",
"-map",
(f"0:{audio_stream_index}?" if audio_stream_index is not None else "0:a:0?"),
"-sn",
"-dn",
"-c:v",
"copy",
"-c:a",
"aac",
"-b:a",
BROWSER_AUDIO_BITRATE,
"-ar",
"48000",
"-ac",
str(BROWSER_AUDIO_CHANNELS),
"-af",
"aresample=async=1:first_pts=0",
"-avoid_negative_ts",
"make_zero",
"-map_metadata",
"-1",
"-map_chapters",
"-1",
"-movflags",
(
"+frag_keyframe"
"+empty_moov"
"+default_base_moof"
"+omit_tfhd_offset"
),
"-frag_duration",
"2000000",
"-min_frag_duration",
"1000000",
"-video_track_timescale",
"90000",
"-max_interleave_delta",
"0",
"-flush_packets",
"1",
"-f",
"mp4",
"pipe:1",
])
return command
def transcode_stream_command(
source_path: str | Path,
*,
start_seconds: float = 0.0,
audio_stream_index: int | None = None,
target_height: int | None = None,
video_bitrate: str | None = None,
) -> list[str]:
source_path = Path(source_path).resolve()
command = [
FFMPEG_BIN,
"-nostdin",
"-hide_banner",
"-loglevel",
"warning",
"-fflags",
"+genpts+discardcorrupt",
]
if start_seconds > 0:
command.extend(
[
"-ss",
f"{start_seconds:.3f}",
]
)
command.extend(
[
"-i",
str(source_path),
"-map",
"0:v:0",
"-map",
(f"0:{audio_stream_index}?" if audio_stream_index is not None else "0:a:0?"),
"-sn",
"-dn",
"-c:v",
"libx264",
"-preset",
BROWSER_X264_PRESET,
"-crf",
BROWSER_X264_CRF,
"-profile:v",
"high",
"-level:v",
"4.1",
"-pix_fmt",
"yuv420p",
]
)
if target_height:
command.extend(["-vf", f"scale=-2:{int(target_height)}"])
if video_bitrate:
command.extend([
"-b:v", str(video_bitrate),
"-maxrate", str(video_bitrate),
"-bufsize", str(video_bitrate),
])
command.extend(
[
"-c:a",
"aac",
"-b:a",
BROWSER_AUDIO_BITRATE,
"-ar",
"48000",
"-ac",
str(BROWSER_AUDIO_CHANNELS),
"-af",
"aresample=async=1:first_pts=0",
"-avoid_negative_ts",
"make_zero",
"-map_metadata",
"-1",
"-map_chapters",
"-1",
"-movflags",
(
"+frag_keyframe"
"+empty_moov"
"+default_base_moof"
"+omit_tfhd_offset"
),
"-frag_duration",
"2000000",
"-min_frag_duration",
"1000000",
"-video_track_timescale",
"90000",
"-f",
"mp4",
"pipe:1",
]
)
return command
def prune_browser_cache() -> None:
if (
BROWSER_CACHE_MAX_GB
<= 0
or not BROWSER_CACHE_DIR.is_dir()
):
return
maximum = int(
BROWSER_CACHE_MAX_GB
* 1024
* 1024
* 1024
)
files = [
path
for path in BROWSER_CACHE_DIR.glob("*.mp4")
if path.is_file()
]
entries = []
total = 0
for path in files:
try:
stat = path.stat()
except OSError:
continue
total += stat.st_size
entries.append(
(
stat.st_mtime,
stat.st_size,
path,
)
)
if total <= maximum:
return
entries.sort(
key=lambda item: item[0]
)
for _mtime, size, path in entries:
if total <= maximum:
break
try:
path.unlink()
total -= size
except OSError:
pass