Files
2026-11-25 20:20:27 -06:00

1592 lines
44 KiB
Python

import json
import os
import subprocess
import signal
import time
from pathlib import Path
from metadata_sidecar import write_video_sidecar, youtube_metadata
from urllib.error import HTTPError, URLError
from urllib.parse import urlencode
from urllib.request import urlopen
from dotenv import load_dotenv
from library_index import (
delete_youtube_video_cache_record,
get_youtube_video_cache,
list_youtube_video_cache,
save_youtube_video_cache,
touch_youtube_video_cache,
)
from resolver_manager import RESOLVER_URL, resolver_status as managed_resolver_status
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")
MAX_VIDEO_HEIGHT = int(os.getenv("YOUTUBE_VIDEO_MAX_HEIGHT", "720"))
MEDIA_CACHE_DIR = Path(
os.getenv(
"YOUTUBE_CACHE_DIR",
"/blade-media/youtube-cache",
)
).expanduser().resolve()
VIDEO_CACHE_DIR = MEDIA_CACHE_DIR / "video"
MUSIC_CACHE_DIR = MEDIA_CACHE_DIR / "music"
MUSIC_AUDIO_BITRATE = os.getenv("MUSIC_AUDIO_BITRATE", "192k")
MAX_CACHE_ITEMS = max(1, int(os.getenv("YOUTUBE_CACHE_MAX_ITEMS", "100")))
MAX_CACHE_GB = max(0.0, float(os.getenv("YOUTUBE_CACHE_MAX_GB", "250")))
RESOLVER_HTTP_TIMEOUT = max(
5.0,
float(
os.getenv(
"KRONIC_RESOLVER_HTTP_TIMEOUT",
"60",
)
),
)
def resolver_get(path, params=None):
query = ""
if params:
query = "?" + urlencode(
{
key: value
for key, value in params.items()
if value is not None
}
)
url = (
RESOLVER_URL
+ path
+ query
)
try:
with urlopen(
url,
timeout=RESOLVER_HTTP_TIMEOUT,
) as response:
payload = response.read()
return json.loads(
payload.decode(
"utf-8",
"replace",
)
)
except HTTPError as error:
body = ""
try:
body = error.read().decode(
"utf-8",
"replace",
)
except Exception:
pass
raise RuntimeError(
"Resolver HTTP "
f"{error.code}: "
f"{body[:1000]}"
) from error
except URLError as error:
raise RuntimeError(
"Embedded Kronic resolver unavailable: "
f"{error}"
) from error
def resolver_video(video_id, refresh=False):
return resolver_get(
f"/api/video/{safe_media_id(video_id)}",
{
"refresh":
str(
bool(refresh)
).lower(),
},
)
def resolver_search(query, limit=20):
return resolver_get(
"/api/search",
{
"q": query,
"limit": limit,
},
)
def ensure_cache_dirs():
VIDEO_CACHE_DIR.mkdir(parents=True, exist_ok=True)
MUSIC_CACHE_DIR.mkdir(parents=True, exist_ok=True)
def safe_media_id(video_id):
value = "".join(
ch if (ch.isalnum() or ch in "_-") else "_"
for ch in str(video_id or "")
).strip("_")
if not value:
raise ValueError("Invalid YouTube video ID")
return value
def cache_path(video_id):
ensure_cache_dirs()
return VIDEO_CACHE_DIR / f"{safe_media_id(video_id)}.mp4"
def temp_cache_path(video_id):
path = cache_path(video_id)
return path.with_suffix(path.suffix + ".part")
def codec_family(codec):
codec = str(codec or "").lower()
if codec.startswith(("avc1", "avc3")) or "h264" in codec:
return "h264"
if codec.startswith("av01"):
return "av1"
if codec.startswith(("vp09", "vp9")):
return "vp9"
return codec
class CacheJobCancelled(RuntimeError):
def __init__(self, output_path=None):
super().__init__("Cache job cancelled")
self.output_path = output_path
def is_live_info(info):
info = info or {}
if info.get("is_live") is True:
return True
return str(info.get("live_status") or "").lower() in {
"is_live",
"live",
}
def _format_protocol(item):
return " ".join(
str(item.get(key) or "").lower()
for key in (
"protocol",
"manifest_url",
"url",
"direct_url",
"format_note",
)
)
def choose_live_muxed_format(formats):
"""
Some live YouTube HLS formats contain both A/V even when yt-dlp/resolver
metadata leaves acodec blank. For live streams, accept an HLS video
rendition as a single muxed FFmpeg input and let FFmpeg inspect the
manifest for the audio stream.
"""
candidates = [
item
for item in formats
if item.get("direct_url")
and (
item.get("vcodec")
or (item.get("height") or 0) > 0
)
and (
"m3u8" in _format_protocol(item)
or "hls" in _format_protocol(item)
)
]
if not candidates:
return None
at_or_below = [
item
for item in candidates
if not item.get("height")
or (item.get("height") or 0) <= MAX_VIDEO_HEIGHT
]
pool = at_or_below or candidates
def score(item):
return (
item.get("height") or 0,
1 if codec_family(item.get("vcodec")) == "h264" else 0,
item.get("fps") or 0,
item.get("bitrate") or 0,
)
return max(pool, key=score)
def detect_live_hls(info, formats):
"""
Do not rely only on resolver is_live/live_status metadata. Some stripped
resolver payloads omit those fields while still returning HLS/m3u8
renditions. Presence of a playable HLS video rendition with no normal
standalone audio is enough for Kronic's live fallback.
"""
if is_live_info(info):
return True
for item in formats or []:
if not item.get("direct_url"):
continue
if not (item.get("vcodec") or (item.get("height") or 0) > 0):
continue
protocol = _format_protocol(item)
if "m3u8" in protocol or "hls" in protocol:
return True
return False
def choose_video_format(formats):
candidates = [
item
for item in formats
if item.get("vcodec")
and not item.get("acodec")
and (item.get("height") or 0) > 0
and item.get("direct_url")
]
if not candidates:
candidates = [
item
for item in formats
if item.get("vcodec")
and (item.get("height") or 0) > 0
and item.get("direct_url")
]
if not candidates:
raise RuntimeError("Resolver returned no playable video format")
at_or_below = [
item
for item in candidates
if (item.get("height") or 0) <= MAX_VIDEO_HEIGHT
]
pool = at_or_below or candidates
def score(item):
codec_rank = {
"h264": 3,
"av1": 2,
"vp9": 1,
}.get(codec_family(item.get("vcodec")), 0)
return (
item.get("height") or 0,
codec_rank,
item.get("fps") or 0,
item.get("bitrate") or 0,
)
return max(pool, key=score)
def choose_audio_format(formats):
candidates = [
item
for item in formats
if item.get("acodec")
and not item.get("vcodec")
and item.get("direct_url")
]
if not candidates:
candidates = [
item
for item in formats
if item.get("acodec")
and item.get("direct_url")
]
if not candidates:
raise RuntimeError("Resolver returned no playable audio format")
def score(item):
codec = str(item.get("acodec") or "").lower()
separate = 1 if not item.get("vcodec") else 0
if "mp4a" in codec or codec.startswith("aac"):
codec_rank = 3
elif "opus" in codec:
codec_rank = 2
else:
codec_rank = 1
return (
separate,
codec_rank,
item.get("bitrate") or 0,
item.get("audio_channels") or 0,
)
return max(candidates, key=score)
def resolve_media(video_id, refresh=False):
info = resolver_video(
video_id,
refresh=refresh,
)
formats = info.get("formats") or []
video = choose_video_format(formats)
try:
audio = choose_audio_format(formats)
except RuntimeError as original_error:
# Resolver metadata for YouTube live HLS can be incomplete. In
# particular, a video rendition may have acodec=None even though a
# separate audio rendition exists. Do NOT assume the selected video
# input is muxed. Probe the live HLS URLs and use the streams ffprobe
# actually sees.
if choose_live_muxed_format(formats) is None:
raise original_error
try:
video, audio, probe_details = resolve_live_hls_inputs(
formats,
preferred_video=video,
)
except RuntimeError:
raise original_error
info = dict(info)
info["is_live"] = True
info.setdefault("live_status", "is_live")
print(
"[YOUTUBE] live HLS probed",
{
"video_id": video_id,
"video_format_id": video.get("id"),
"audio_format_id": audio.get("id"),
"same_input": (
video.get("direct_url") == audio.get("direct_url")
),
"height": video.get("height"),
"vcodec": video.get("vcodec"),
"acodec": audio.get("acodec"),
"probes": probe_details,
},
flush=True,
)
if detect_live_hls(info, formats):
info = dict(info)
info["is_live"] = True
info.setdefault("live_status", "is_live")
return info, video, audio
def youtube_search(query, limit=20):
query = str(query or "").strip()
if not query:
return {"items": []}
data = resolver_search(
query,
limit=max(
1,
min(
int(limit or 20),
50,
),
),
)
items = []
for raw in data.get("items") or []:
video_id = str(raw.get("id") or "").strip()
if not video_id:
continue
cache = get_youtube_video_cache(video_id)
cached = False
if cache:
path = Path(cache.get("cache_path") or "")
cached = path.is_file() and path.stat().st_size > 0
if not cached:
delete_youtube_video_cache_record(video_id)
items.append({
"id": video_id,
"title": raw.get("title") or video_id,
"artist": raw.get("channel") or raw.get("artist") or "",
"duration": raw.get("duration"),
"thumbnail": raw.get("thumbnail") or "",
"cached": cached,
"is_live": bool(raw.get("is_live")) or str(raw.get("live_status") or "").lower() in {"is_live", "live"},
"live_status": raw.get("live_status") or "",
"source": raw.get("source") or "yt-dlp",
})
return {"items": items}
def ffmpeg_headers(headers):
if not headers:
return None
allowed = {
"user-agent",
"referer",
"origin",
"accept",
"accept-language",
}
lines = []
for key, value in headers.items():
if key.lower() in allowed and value:
lines.append(f"{key}: {value}")
return "\r\n".join(lines) + "\r\n" if lines else None
def add_input(command, fmt, start_seconds=0.0):
if start_seconds > 0:
command.extend(["-ss", f"{start_seconds:.3f}"])
headers = ffmpeg_headers(fmt.get("http_headers"))
if headers:
command.extend(["-headers", headers])
command.extend(["-i", fmt["direct_url"]])
def _ffprobe_stream_types(fmt, timeout=12):
"""
Ask ffprobe what streams are ACTUALLY present in a resolved URL.
This is important for YouTube live HLS because resolver/yt-dlp metadata can
leave acodec blank even when audio exists, or can expose a video-only
rendition that looks muxed from the stripped metadata.
"""
url = str(fmt.get("direct_url") or "").strip()
if not url:
return {
"video": False,
"audio": False,
"video_codec": "",
"audio_codec": "",
}
command = [
FFPROBE_BIN,
"-v", "error",
]
headers = ffmpeg_headers(fmt.get("http_headers"))
if headers:
command.extend(["-headers", headers])
command.extend([
"-show_entries",
"stream=codec_type,codec_name",
"-of",
"json",
url,
])
try:
result = subprocess.run(
command,
capture_output=True,
text=True,
timeout=max(3, int(timeout)),
)
except Exception as error:
return {
"video": False,
"audio": False,
"video_codec": "",
"audio_codec": "",
"error": str(error),
}
if result.returncode != 0:
return {
"video": False,
"audio": False,
"video_codec": "",
"audio_codec": "",
"error": (result.stderr or "").strip()[-1000:],
}
try:
payload = json.loads(result.stdout or "{}")
except Exception as error:
return {
"video": False,
"audio": False,
"video_codec": "",
"audio_codec": "",
"error": f"invalid ffprobe JSON: {error}",
}
video_codec = ""
audio_codec = ""
for stream in payload.get("streams") or []:
kind = str(stream.get("codec_type") or "").lower()
codec = str(stream.get("codec_name") or "").lower()
if kind == "video" and not video_codec:
video_codec = codec
elif kind == "audio" and not audio_codec:
audio_codec = codec
return {
"video": bool(video_codec),
"audio": bool(audio_codec),
"video_codec": video_codec,
"audio_codec": audio_codec,
}
def _live_hls_probe_candidates(formats, preferred_video=None):
"""
Return unique live-HLS candidates in a useful probe order.
The selected video rendition is tried first. Then likely audio/low-bandwidth
entries, then the remaining HLS renditions.
We also consider manifest_url as a fallback source. yt-dlp often exposes a
child media-playlist URL as `url`/`direct_url` while retaining the master
HLS manifest separately. The master manifest can contain both A/V even when
the selected child rendition is video-only.
"""
candidates = []
seen = set()
def add(fmt, *, direct_url=None, source_note=None):
if not fmt:
return
url = str(direct_url or fmt.get("direct_url") or "").strip()
if not url or url in seen:
return
probe_fmt = dict(fmt)
probe_fmt["direct_url"] = url
if source_note:
probe_fmt["_probe_source"] = source_note
protocol_text = _format_protocol(probe_fmt)
if "m3u8" not in protocol_text and "hls" not in protocol_text:
# A manifest_url itself may not repeat "m3u8" in other fields.
if ".m3u8" not in url.lower():
return
seen.add(url)
candidates.append(probe_fmt)
add(preferred_video, source_note="preferred-video")
if preferred_video and preferred_video.get("manifest_url"):
add(
preferred_video,
direct_url=preferred_video.get("manifest_url"),
source_note="preferred-master-manifest",
)
hls = [
dict(item)
for item in (formats or [])
if item.get("direct_url")
and (
"m3u8" in _format_protocol(item)
or "hls" in _format_protocol(item)
)
]
# Entries with no height / no video metadata are more likely to be the
# missing audio representation, so probe them before another video tier.
hls.sort(
key=lambda item: (
0 if not item.get("height") else 1,
0 if not item.get("vcodec") else 1,
item.get("bitrate") or 0,
)
)
for item in hls:
add(item, source_note="format")
if item.get("manifest_url"):
add(
item,
direct_url=item.get("manifest_url"),
source_note="master-manifest",
)
return candidates
def resolve_live_hls_inputs(formats, preferred_video):
"""
Resolve a REAL video input and a REAL audio input for YouTube live HLS.
Returns (video_fmt, audio_fmt, probe_details).
- If one HLS input genuinely contains both A/V, both return values point to
that same URL.
- If the chosen video rendition is video-only, another HLS representation
is probed until an audio stream is found.
- If a master manifest exposes both, it can be used as the single muxed
input.
"""
candidates = _live_hls_probe_candidates(
formats,
preferred_video=preferred_video,
)
if not candidates:
raise RuntimeError("No live HLS candidates available for ffprobe")
video_fmt = None
audio_fmt = None
details = []
# Keep this bounded. A normal YouTube live payload should resolve well
# before this many probes.
for candidate in candidates[:16]:
probe = _ffprobe_stream_types(candidate)
details.append({
"format_id": candidate.get("id"),
"height": candidate.get("height"),
"source": candidate.get("_probe_source") or "",
"video": probe.get("video"),
"audio": probe.get("audio"),
"video_codec": probe.get("video_codec"),
"audio_codec": probe.get("audio_codec"),
"error": probe.get("error") or "",
})
if probe.get("video") and probe.get("audio"):
muxed = dict(candidate)
if not muxed.get("vcodec") and probe.get("video_codec"):
muxed["vcodec"] = probe["video_codec"]
if not muxed.get("acodec") and probe.get("audio_codec"):
muxed["acodec"] = probe["audio_codec"]
return muxed, muxed, details
if probe.get("video") and video_fmt is None:
video_fmt = dict(candidate)
if not video_fmt.get("vcodec") and probe.get("video_codec"):
video_fmt["vcodec"] = probe["video_codec"]
if probe.get("audio") and audio_fmt is None:
audio_fmt = dict(candidate)
if not audio_fmt.get("acodec") and probe.get("audio_codec"):
audio_fmt["acodec"] = probe["audio_codec"]
if video_fmt is not None and audio_fmt is not None:
return video_fmt, audio_fmt, details
raise RuntimeError(
"YouTube live HLS was found, but ffprobe could not find both "
"video and audio streams. "
f"Probes: {json.dumps(details[-8:], ensure_ascii=False)}"
)
def build_mux_command(
video,
audio,
start_seconds=0.0,
*,
live=False,
):
command = [
FFMPEG_BIN,
"-nostdin",
"-hide_banner",
"-loglevel",
"error",
]
if live:
# YouTube live HLS commonly carries long-running/discontinuous source
# timestamps. Regenerate timestamps before creating the browser MP4.
command.extend([
"-fflags",
"+genpts+discardcorrupt",
])
add_input(command, video, start_seconds=start_seconds)
muxed_same_input = (
bool(video.get("direct_url"))
and video.get("direct_url") == audio.get("direct_url")
)
if muxed_same_input:
command.extend([
"-map", "0:v:0",
"-map", "0:a:0",
])
else:
add_input(command, audio, start_seconds=start_seconds)
command.extend([
"-map", "0:v:0",
"-map", "1:a:0",
])
if live:
# Browser playback gets one deterministic codec combination.
#
# Copying YouTube live HLS codecs/timestamps directly into fragmented
# MP4 has proven fragile in Firefox. A live stream can be AVC, VP9,
# AV1, AAC variants, or have unusual timestamp/discontinuity behavior.
#
# Keep the recording/cache path separate; this is the interactive
# browser playback path where compatibility matters more than avoiding
# every transcode.
command.extend([
"-c:v", "libx264",
"-preset", "veryfast",
"-tune", "zerolatency",
"-crf", "23",
"-pix_fmt", "yuv420p",
"-profile:v", "main",
"-level", "4.1",
"-c:a", "aac",
"-b:a", "160k",
"-ac", "2",
"-ar", "48000",
])
else:
if codec_family(video.get("vcodec")) == "h264":
command.extend(["-c:v", "copy"])
else:
command.extend([
"-c:v", "libx264",
"-preset", "veryfast",
"-crf", "23",
"-pix_fmt", "yuv420p",
])
audio_codec = str(audio.get("acodec") or "").lower()
if "mp4a" in audio_codec or audio_codec.startswith("aac"):
command.extend(["-c:a", "copy"])
else:
command.extend(["-c:a", "aac", "-b:a", "160k"])
command.extend([
"-max_interleave_delta", "0",
"-muxdelay", "0",
"-muxpreload", "0",
"-movflags",
"frag_keyframe+empty_moov+default_base_moof",
"-f",
"mp4",
"pipe:1",
])
return command
def _metadata_from_info(video_id, info):
meta = youtube_metadata(video_id, info or {})
return {
"video_id": video_id,
"title": meta.get("title") or video_id,
"channel_name": meta.get("channel") or "",
"thumbnail_url": meta.get("thumbnail") or "",
"duration_seconds": meta.get("duration"),
"description": meta.get("description") or "",
"webpage_url": meta.get("webpage_url") or "",
"upload_date": meta.get("upload_date") or "",
"_raw_info": meta.get("raw") or info or {},
}
def prune_youtube_cache():
rows = list_youtube_video_cache()
valid = []
for row in rows:
path = Path(row.get("cache_path") or "")
if not path.is_file() or path.stat().st_size <= 0:
delete_youtube_video_cache_record(row["video_id"])
continue
row = dict(row)
row["size_bytes"] = path.stat().st_size
valid.append(row)
max_bytes = int(MAX_CACHE_GB * 1024 * 1024 * 1024) if MAX_CACHE_GB > 0 else None
total_bytes = sum(int(row.get("size_bytes") or 0) for row in valid)
while valid and (
len(valid) > MAX_CACHE_ITEMS
or (max_bytes is not None and total_bytes > max_bytes)
):
old = valid.pop()
path = Path(old.get("cache_path") or "")
size = int(old.get("size_bytes") or 0)
try:
path.unlink(missing_ok=True)
except OSError as exc:
print(f"[YOUTUBE] Could not remove old cache file {path}: {exc}", flush=True)
delete_youtube_video_cache_record(old["video_id"])
total_bytes = max(0, total_bytes - size)
def resolver_status():
return managed_resolver_status()
def cache_status():
prune_youtube_cache()
rows = list_youtube_video_cache()
return {
"items": len(rows),
"max_items": MAX_CACHE_ITEMS,
"max_gb": MAX_CACHE_GB,
"total_bytes": sum(int(row.get("size_bytes") or 0) for row in rows),
"directory": str(MEDIA_CACHE_DIR),
}
def _run_file_cache_command(
command,
duration_seconds=None,
progress_callback=None,
cancel_check=None,
live=False,
):
command = list(command)
insert_at = max(1, len(command) - 2)
command[insert_at:insert_at] = [
"-progress", "pipe:1",
"-nostats",
]
process = subprocess.Popen(
command,
stdout=subprocess.PIPE,
stderr=subprocess.DEVNULL,
text=True,
bufsize=1,
)
started = time.monotonic()
cancelled = False
if progress_callback:
progress_callback(
0.0 if live else 1.0,
"recording live · 00:00:00" if live else "starting",
)
if process.stdout:
for line in process.stdout:
if cancel_check and cancel_check():
cancelled = True
try:
process.send_signal(signal.SIGINT)
except Exception:
process.terminate()
line = line.strip()
if not line:
continue
if line.startswith("out_time_ms="):
if live:
elapsed = max(0, int(time.monotonic() - started))
hours, rem = divmod(elapsed, 3600)
minutes, seconds = divmod(rem, 60)
if progress_callback:
progress_callback(
0.0,
f"recording live · {hours:02d}:{minutes:02d}:{seconds:02d}",
)
elif duration_seconds:
try:
out_seconds = (
float(line.split("=", 1)[1])
/ 1_000_000.0
)
percent = max(
1.0,
min(
99.0,
out_seconds
* 100.0
/ float(duration_seconds),
),
)
if progress_callback:
progress_callback(percent, "caching")
except Exception:
pass
elif line == "progress=end":
if progress_callback and not cancelled:
progress_callback(100.0, "finalizing")
rc = process.wait()
if cancelled:
return True, rc
if rc != 0:
raise RuntimeError(
f"FFmpeg cache job failed with return code {rc}"
)
return False, rc
def build_youtube_video_cache(
video_id,
refresh=False,
progress_callback=None,
cancel_check=None,
):
video_id = safe_media_id(video_id)
cache = get_youtube_video_cache(video_id)
if cache:
cached_path = Path(cache.get("cache_path") or "")
if cached_path.is_file() and cached_path.stat().st_size > 0:
touch_youtube_video_cache(video_id)
if progress_callback:
progress_callback(100.0, "already cached")
return cached_path, True
delete_youtube_video_cache_record(video_id)
info, video, audio = resolve_media(
video_id,
refresh=refresh,
)
live = is_live_info(info)
metadata = _metadata_from_info(video_id, info)
duration = metadata.get("duration_seconds")
final_path = cache_path(video_id)
part_path = temp_cache_path(video_id)
part_path.unlink(missing_ok=True)
command = [
FFMPEG_BIN,
"-nostdin",
"-hide_banner",
"-loglevel",
"error",
]
add_input(command, video)
same_input = (
bool(video.get("direct_url"))
and video.get("direct_url") == audio.get("direct_url")
)
if same_input:
command.extend([
"-map", "0:v:0",
"-map", "0:a:0",
])
else:
add_input(command, audio)
command.extend([
"-map", "0:v:0",
"-map", "1:a:0",
])
if codec_family(video.get("vcodec")) == "h264":
command.extend(["-c:v", "copy"])
else:
command.extend([
"-c:v", "libx264",
"-preset", "veryfast",
"-crf", "23",
"-pix_fmt", "yuv420p",
])
audio_codec = str(audio.get("acodec") or "").lower()
if audio_codec and (
"mp4a" in audio_codec
or audio_codec.startswith("aac")
):
command.extend(["-c:a", "copy"])
else:
# For live HLS with blank acodec metadata this lets FFmpeg inspect
# the actual manifest audio and produce browser-safe AAC.
command.extend([
"-c:a", "aac",
"-b:a", "160k",
])
command.extend([
"-map_metadata", "-1",
"-map_chapters", "-1",
"-movflags", "+faststart",
"-f", "mp4",
"-y",
str(part_path),
])
print(
"[CACHE] video prepare",
{
"video_id": video_id,
"live": live,
"path": str(final_path),
},
flush=True,
)
cancelled, _rc = _run_file_cache_command(
command,
duration_seconds=duration,
progress_callback=progress_callback,
cancel_check=cancel_check,
live=live,
)
if not part_path.is_file() or part_path.stat().st_size <= 0:
if cancelled:
raise CacheJobCancelled()
raise RuntimeError("Video cache job produced no file")
# SIGINT gives FFmpeg an opportunity to write the MP4 trailer. If the
# user stops a live recording, retain that finished partial recording.
os.replace(part_path, final_path)
saved_duration = duration
if live and cancelled:
try:
probe = subprocess.run(
[
FFPROBE_BIN,
"-v", "error",
"-show_entries", "format=duration",
"-of",
"default=noprint_wrappers=1:nokey=1",
str(final_path),
],
capture_output=True,
text=True,
timeout=20,
check=False,
)
if probe.returncode == 0:
saved_duration = float(
(probe.stdout or "0").strip() or 0
) or None
except Exception:
pass
save_youtube_video_cache(
video_id=video_id,
cache_path=final_path,
title=metadata["title"],
channel_name=metadata["channel_name"],
thumbnail_url=metadata["thumbnail_url"],
duration_seconds=saved_duration,
size_bytes=final_path.stat().st_size,
)
try:
write_video_sidecar(
final_path,
video_id,
metadata.get("_raw_info") or info,
)
except Exception as error:
print("[YOUTUBE] sidecar write failed:", error, flush=True)
prune_youtube_cache()
print(
"[CACHE] video ready",
{
"video_id": video_id,
"live": live,
"cancelled": cancelled,
"path": str(final_path),
},
flush=True,
)
if cancelled:
raise CacheJobCancelled(final_path)
return final_path, False
def serve_youtube_video(handler, video_id, start_seconds=0.0, refresh=False, bypass_cache=False):
video_id = safe_media_id(video_id)
start_seconds = max(0.0, float(start_seconds or 0))
cache = None if bypass_cache else get_youtube_video_cache(video_id)
if cache:
cached_path = Path(cache.get("cache_path") or "")
if cached_path.is_file() and cached_path.stat().st_size > 0:
touch_youtube_video_cache(video_id)
return handler.stream_file(cached_path, content_type_override="video/mp4")
delete_youtube_video_cache_record(video_id)
info, video, audio = resolve_media(video_id, refresh=refresh)
live = is_live_info(info)
metadata = _metadata_from_info(video_id, info)
command = build_mux_command(
video,
audio,
start_seconds=start_seconds,
live=live,
)
print(
"[YOUTUBE] mux",
{
"video_id": video_id,
"height": video.get("height"),
"vcodec": video.get("vcodec"),
"acodec": audio.get("acodec"),
"start": start_seconds,
"live": live,
"cache": start_seconds <= 0 and not live,
},
flush=True,
)
process = subprocess.Popen(
command,
stdout=subprocess.PIPE,
stderr=subprocess.PIPE,
bufsize=0,
)
# VOD can opportunistically cache in the playback request.
# Live streams are recorded only by the independent background cache
# job so recording continues if the browser disconnects.
cache_allowed = start_seconds <= 0 and not live and not bypass_cache
final_path = cache_path(video_id)
part_path = temp_cache_path(video_id)
cache_file = None
completed = False
if cache_allowed:
try:
part_path.unlink(missing_ok=True)
except OSError:
pass
try:
first_chunk = process.stdout.read(256 * 1024) if process.stdout else b""
if not first_chunk:
try:
rc = process.wait(timeout=10)
except subprocess.TimeoutExpired:
process.terminate()
rc = process.wait(timeout=3)
stderr_text = ""
if process.stderr:
try:
stderr_text = process.stderr.read().decode(
"utf-8",
"replace",
)[-6000:]
except Exception:
stderr_text = ""
print(
"[YOUTUBE] playback FFmpeg failed before output",
{
"video_id": video_id,
"live": live,
"returncode": rc,
"stderr": stderr_text,
},
flush=True,
)
raise RuntimeError(
"FFmpeg failed before producing browser video "
f"(returncode={rc}): {stderr_text}"
)
if cache_allowed:
ensure_cache_dirs()
cache_file = open(part_path, "wb")
cache_file.write(first_chunk)
handler.send_response(200)
handler.send_header("Content-Type", "video/mp4")
handler.send_header("Transfer-Encoding", "chunked")
handler.send_header("Cache-Control", "no-store")
handler.send_header("Accept-Ranges", "none")
handler.send_header("X-Media-Source", "yt-dlp")
handler.send_header("X-YouTube-Cache", "MISS")
handler.end_headers()
def send_chunk(chunk):
handler.wfile.write(f"{len(chunk):X}\r\n".encode("ascii"))
handler.wfile.write(chunk)
handler.wfile.write(b"\r\n")
handler.wfile.flush()
send_chunk(first_chunk)
while True:
chunk = process.stdout.read(256 * 1024) if process.stdout else b""
if not chunk:
break
if cache_file is not None:
cache_file.write(chunk)
send_chunk(chunk)
rc = process.wait()
if rc != 0:
stderr_text = ""
if process.stderr:
try:
stderr_text = process.stderr.read().decode(
"utf-8",
"replace",
)[-6000:]
except Exception:
stderr_text = ""
print(
"[YOUTUBE] playback FFmpeg exited",
{
"video_id": video_id,
"live": live,
"returncode": rc,
"stderr": stderr_text,
},
flush=True,
)
raise RuntimeError(
f"FFmpeg exited with returncode={rc}: {stderr_text}"
)
if cache_file is not None:
cache_file.flush()
os.fsync(cache_file.fileno())
cache_file.close()
cache_file = None
os.replace(part_path, final_path)
completed = True
save_youtube_video_cache(
video_id=video_id,
cache_path=final_path,
title=metadata["title"],
channel_name=metadata["channel_name"],
thumbnail_url=metadata["thumbnail_url"],
duration_seconds=metadata["duration_seconds"],
size_bytes=final_path.stat().st_size,
)
try:
write_video_sidecar(
final_path,
video_id,
metadata.get("_raw_info") or info,
)
except Exception as error:
print("[YOUTUBE] sidecar write failed:", error, flush=True)
prune_youtube_cache()
print(f"[YOUTUBE] cached {video_id}: {final_path}", flush=True)
handler.wfile.write(b"0\r\n\r\n")
handler.wfile.flush()
except (BrokenPipeError, ConnectionResetError):
pass
finally:
if cache_file is not None:
try:
cache_file.close()
except Exception:
pass
if cache_allowed and not completed:
try:
part_path.unlink(missing_ok=True)
except OSError:
pass
if process.stdout:
try:
process.stdout.close()
except Exception:
pass
if process.stderr:
try:
process.stderr.close()
except Exception:
pass
if process.poll() is None:
process.terminate()
try:
process.wait(timeout=2)
except subprocess.TimeoutExpired:
process.kill()
def music_cache_path(video_id):
"""
Normal seekable M4A cache used by the HTML <audio> element.
The previous implementation cached the fragmented MP4 pipe directly.
That is useful for live streaming but Firefox can treat the resulting
static file as duration-less (0:00 / 0:00). Music cache files are now
ordinary finalized M4A/MP4 files with a normal moov atom.
"""
ensure_cache_dirs()
return MUSIC_CACHE_DIR / f"{safe_media_id(video_id)}.m4a"
def music_temp_cache_path(video_id):
path = music_cache_path(video_id)
return path.with_suffix(path.suffix + ".part")
def _probe_cached_audio(path):
"""
Return duration seconds for a usable cached audio file, otherwise 0.
This also detects old fragmented/duration-less cache files so they are
automatically rebuilt on the next play.
"""
if not path.is_file() or path.stat().st_size <= 0:
return 0.0
command = [
FFPROBE_BIN,
"-v", "error",
"-show_entries", "format=duration",
"-of", "default=noprint_wrappers=1:nokey=1",
str(path),
]
try:
result = subprocess.run(
command,
capture_output=True,
text=True,
timeout=15,
check=False,
)
if result.returncode != 0:
return 0.0
duration = float((result.stdout or "0").strip() or 0)
return duration if duration > 0.5 else 0.0
except Exception:
return 0.0
def music_audio_cache_status(video_id=None):
ensure_cache_dirs()
if video_id:
path = music_cache_path(video_id)
duration = _probe_cached_audio(path)
return {
"cached": duration > 0,
"size_bytes": path.stat().st_size if path.is_file() else 0,
"duration_seconds": duration,
}
files = []
total_bytes = 0
for path in MUSIC_CACHE_DIR.glob("*.m4a"):
if not path.is_file():
continue
duration = _probe_cached_audio(path)
if duration <= 0:
continue
files.append(path)
total_bytes += path.stat().st_size
return {
"items": len(files),
"total_bytes": total_bytes,
"directory": str(MUSIC_CACHE_DIR),
}
def build_seekable_music_cache(
video_id,
refresh=False,
progress_callback=None,
cancel_check=None,
):
"""
Resolve YouTube/YouTube Music audio and create one ordinary seekable M4A.
AAC/mp4a is stream-copied whenever possible. Other audio codecs are
converted to AAC. No video is downloaded.
"""
video_id = safe_media_id(video_id)
final_path = music_cache_path(video_id)
part_path = music_temp_cache_path(video_id)
existing_duration = _probe_cached_audio(final_path)
if existing_duration > 0:
return final_path, existing_duration, True
# An old fragmented/duration-less cache should not be reused.
try:
final_path.unlink(missing_ok=True)
part_path.unlink(missing_ok=True)
except OSError:
pass
_info, _video, audio = resolve_media(
video_id,
refresh=refresh,
)
command = [
FFMPEG_BIN,
"-nostdin",
"-hide_banner",
"-loglevel",
"warning",
]
add_input(
command,
audio,
start_seconds=0.0,
)
command.extend([
"-vn",
"-map", "0:a:0",
])
audio_codec = (audio.get("acodec") or "").lower()
if "mp4a" in audio_codec or audio_codec.startswith("aac"):
command.extend([
"-c:a", "copy",
])
audio_action = "copy"
else:
command.extend([
"-c:a", "aac",
"-b:a", MUSIC_AUDIO_BITRATE,
"-ar", "48000",
"-ac", "2",
"-af", "aresample=async=1:first_pts=0",
])
audio_action = "aac"
command.extend([
"-map_metadata", "-1",
"-map_chapters", "-1",
"-movflags", "+faststart",
"-f", "mp4",
"-y",
str(part_path),
])
print(
"[MUSIC] prepare",
{
"video_id": video_id,
"acodec": audio.get("acodec"),
"audio_action": audio_action,
"cache": str(final_path),
},
flush=True,
)
try:
cancelled, _rc = _run_file_cache_command(
command,
duration_seconds=(_info or {}).get("duration"),
progress_callback=progress_callback,
cancel_check=cancel_check,
live=False,
)
if cancelled:
raise CacheJobCancelled()
except Exception:
try:
part_path.unlink(missing_ok=True)
except OSError:
pass
raise
duration = _probe_cached_audio(part_path)
if duration <= 0:
try:
part_path.unlink(missing_ok=True)
except OSError:
pass
raise RuntimeError(
"FFmpeg produced a music file with no readable duration."
)
os.replace(part_path, final_path)
print(
"[MUSIC] cached",
{
"video_id": video_id,
"path": str(final_path),
"duration": round(duration, 3),
"size_bytes": final_path.stat().st_size,
},
flush=True,
)
return final_path, duration, False
def serve_youtube_audio(handler, video_id, start_seconds=0.0, refresh=False):
"""
Serve Music as a normal seekable audio file.
On first play the track is resolved and cached as finalized M4A, then the
existing stream_file() helper handles Content-Length and HTTP byte ranges.
Subsequent plays are immediate local Range requests.
"""
video_id = safe_media_id(video_id)
final_path, duration, was_cached = build_seekable_music_cache(
video_id,
refresh=refresh,
)
print(
"[MUSIC] serve",
{
"video_id": video_id,
"duration": round(duration, 3),
"cache": "HIT" if was_cached else "MISS",
"range": handler.headers.get("Range"),
},
flush=True,
)
return handler.stream_file(
final_path,
content_type_override="audio/mp4",
)