From ce7b8f704e9a7c46acc28fc6c62499276b520bc4 Mon Sep 17 00:00:00 2001 From: admin Date: Wed, 25 Nov 2026 20:20:27 -0600 Subject: [PATCH] Upload files to "/" --- thumbnail_worker.py | 284 ++++++++ transcode_planner.py | 50 ++ twitch_jobs.py | 527 ++++++++++++++ youtube_metadata.py | 109 +++ youtube_stream.py | 1591 ++++++++++++++++++++++++++++++++++++++++++ 5 files changed, 2561 insertions(+) create mode 100644 thumbnail_worker.py create mode 100644 transcode_planner.py create mode 100644 twitch_jobs.py create mode 100644 youtube_metadata.py create mode 100644 youtube_stream.py diff --git a/thumbnail_worker.py b/thumbnail_worker.py new file mode 100644 index 0000000..321adb4 --- /dev/null +++ b/thumbnail_worker.py @@ -0,0 +1,284 @@ +from __future__ import annotations + +import hashlib +import json +import os +import subprocess +import time +from pathlib import Path + +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") +THUMBNAIL_DIR = Path( + os.getenv("THUMBNAIL_DIR", str(BASE_DIR / "thumbnails")) +).expanduser().resolve() + +THUMBNAIL_DIR.mkdir(parents=True, exist_ok=True) + +# A failed source is retried automatically when its size or mtime changes. +_FAILURE_SUFFIX = ".failed.json" + +# These errors mean the input itself could not be opened/parsed. Retrying at a +# different timestamp cannot possibly help and just creates duplicate log spam. +_FATAL_INPUT_ERRORS = ( + "ebml header parsing failed", + "invalid as first byte of an ebml number", + "invalid data found when processing input", + "error opening input", + "error opening input file", + "error opening input files", + "moov atom not found", + "invalid atom size", +) + + +def _key_text(key_path) -> str: + return str(key_path) + + +def _thumbnail_hash(key_path) -> str: + return hashlib.sha1( + _key_text(key_path).encode("utf-8", "surrogatepass") + ).hexdigest() + + +def get_thumbnail_path(key_path) -> Path: + return THUMBNAIL_DIR / f"{_thumbnail_hash(key_path)}.jpg" + + +def _failure_path(key_path) -> Path: + return THUMBNAIL_DIR / f"{_thumbnail_hash(key_path)}{_FAILURE_SUFFIX}" + + +def _source_fingerprint(path: Path) -> dict: + try: + stat = path.stat() + return { + "path": str(path), + "size": int(stat.st_size), + "mtime_ns": int(stat.st_mtime_ns), + } + except OSError: + return { + "path": str(path), + "size": -1, + "mtime_ns": -1, + } + + +def _load_failure(key_path): + marker = _failure_path(key_path) + try: + return json.loads(marker.read_text(encoding="utf-8")) + except Exception: + return None + + +def _failure_still_valid(source_path: Path, key_path) -> bool: + failure = _load_failure(key_path) + if not failure: + return False + + current = _source_fingerprint(source_path) + previous = failure.get("fingerprint") or {} + + return ( + current.get("path") == previous.get("path") + and current.get("size") == previous.get("size") + and current.get("mtime_ns") == previous.get("mtime_ns") + ) + + +def _write_failure(source_path: Path, key_path, error_text: str): + marker = _failure_path(key_path) + payload = { + "fingerprint": _source_fingerprint(source_path), + "failed_at": int(time.time()), + "error": str(error_text or "")[-4000:], + } + + temp = marker.with_suffix(marker.suffix + ".tmp") + try: + temp.write_text( + json.dumps(payload, ensure_ascii=False, indent=2), + encoding="utf-8", + ) + os.replace(temp, marker) + except OSError: + try: + temp.unlink(missing_ok=True) + except OSError: + pass + + +def _clear_failure(key_path): + try: + _failure_path(key_path).unlink(missing_ok=True) + except OSError: + pass + + +def _looks_like_obviously_invalid_matroska(path: Path): + """ + MKV/WebM files begin with the EBML magic 1A 45 DF A3. + + We only use this quick check for .mkv/.webm because it is deterministic + and avoids spawning FFmpeg for a file that starts with zeros or other + obviously invalid data. + + It is intentionally conservative: all other media types continue to + FFmpeg normally. + """ + if path.suffix.lower() not in {".mkv", ".webm"}: + return False, "" + + try: + with path.open("rb") as handle: + header = handle.read(4) + except OSError as error: + return True, f"could not read source file: {error}" + + if len(header) < 4: + return True, "file is too small to contain an EBML header" + + if header != b"\x1a\x45\xdf\xa3": + return True, ( + "invalid MKV/WebM EBML header " + f"(first bytes: {header.hex(' ')})" + ) + + return False, "" + + +def _fatal_input_error(stderr_text: str) -> bool: + text = str(stderr_text or "").lower() + return any(pattern in text for pattern in _FATAL_INPUT_ERRORS) + + +def _capture(source_path: Path, output_path: Path, seek_seconds: int): + command = [ + FFMPEG_BIN, + "-hide_banner", + "-loglevel", + "error", + "-ss", + str(int(seek_seconds)), + "-i", + str(source_path), + "-frames:v", + "1", + "-vf", + "scale=480:-2", + "-q:v", + "3", + "-y", + str(output_path), + ] + + result = subprocess.run( + command, + stdout=subprocess.DEVNULL, + stderr=subprocess.PIPE, + text=True, + errors="replace", + ) + + if result.returncode == 0 and output_path.is_file(): + try: + if output_path.stat().st_size > 0: + return True, "" + except OSError: + pass + + try: + output_path.unlink(missing_ok=True) + except OSError: + pass + + return False, (result.stderr or "").strip() + + +def generate_thumbnail( + source_path, + *, + key_path=None, +): + """ + Generate and return the JPEG thumbnail path, or None. + + Compatibility: + generate_thumbnail(path) + generate_thumbnail(path, key_path=original_library_path) + + Failed media is remembered persistently until the source file changes. + """ + source = Path(source_path).expanduser() + key = key_path if key_path is not None else source_path + output = get_thumbnail_path(key) + + if output.is_file(): + return output + + # If this exact source version already failed, do not run FFmpeg again. + if _failure_still_valid(source, key): + return None + + if not source.is_file(): + message = "source file does not exist" + _write_failure(source, key, message) + print( + f"[THUMBNAIL] Skipping {source}: {message}", + flush=True, + ) + return None + + # Cheap deterministic guard for the exact failure shown in the logs: + # 00 00 ... instead of the MKV EBML header. + invalid, reason = _looks_like_obviously_invalid_matroska(source) + if invalid: + _write_failure(source, key, reason) + print( + f"[THUMBNAIL] Skipping invalid media {source}: {reason}", + flush=True, + ) + return None + + # Normal first attempt. + ok, error = _capture(source, output, 5) + if ok: + _clear_failure(key) + return output + + # If FFmpeg could not even parse/open the input, seeking to 60 seconds + # cannot fix it. Persist the failure immediately. + if _fatal_input_error(error): + _write_failure(source, key, error) + summary = error.splitlines()[-1] if error else "invalid media input" + print( + f"[THUMBNAIL] Invalid media {source}: {summary}", + flush=True, + ) + return None + + # Some valid files have black/empty/opening frames at 5 seconds, so retain + # the original 60-second fallback for ordinary decode/capture failures. + ok60, error60 = _capture(source, output, 60) + if ok60: + _clear_failure(key) + return output + + final_error = error60 or error or "thumbnail capture failed" + _write_failure(source, key, final_error) + + # One concise log entry instead of subprocess traceback + a second wall of + # FFmpeg diagnostics every scan. + summary = final_error.splitlines()[-1] if final_error else "unknown error" + print( + f"[THUMBNAIL] Failed {source}: {summary}", + flush=True, + ) + return None diff --git a/transcode_planner.py b/transcode_planner.py new file mode 100644 index 0000000..104b16d --- /dev/null +++ b/transcode_planner.py @@ -0,0 +1,50 @@ +from dataclasses import dataclass +import re +@dataclass +class TranscodePlan: + input_path: str + video_codec: str + audio_codec: str + target_container: str = "mp4" + +# Example rules: +# - If not H.264 or not AAC → transcode +# - If resolution > 1080p → downscale +def plan_transcodes(media_items): + plans = [] + + for item in media_items: + needs_transcode = False + + if item.video_codec != "AVC": # pymediainfo may report H.264 as AVC + needs_transcode = True + + if item.audio_codec != "AAC": + needs_transcode = True + + if item.width and item.width > 1920: + needs_transcode = True + + if needs_transcode: + print(f"Planning transcode for: {item.path}") + plans.append( + TranscodePlan( + input_path=str(item.path), + video_codec="h264", + audio_codec="aac" + ) + ) + + return plans +def sanitize_filename(name: str) -> str: + """ + Make filename filesystem-safe and add _dup before extension. + """ + name = name.replace(":", "-").replace("@", "-").replace("–", "-") + name = re.sub(r"\s+", " ", name).strip() + + if "." in name: + base, ext = name.rsplit(".", 1) + return f"{base}_dup.{ext}" + else: + return f"{name}_dup" diff --git a/twitch_jobs.py b/twitch_jobs.py new file mode 100644 index 0000000..402c502 --- /dev/null +++ b/twitch_jobs.py @@ -0,0 +1,527 @@ +from __future__ import annotations + +import os +import sqlite3 +import threading +import time +from pathlib import Path + +from dotenv import load_dotenv + +from twitch_stream import ( + TwitchOffline, + probe_twitch, + record_twitch, + normalize_twitch_url, +) + +BASE_DIR = Path(__file__).resolve().parent +load_dotenv(BASE_DIR / "config.env") +DB_PATH = Path( + os.getenv("DB_PATH", str(BASE_DIR / "media_library.db")) +).expanduser().resolve() + +TWITCH_WATCH_INTERVAL = max( + 10, + int(os.getenv("TWITCH_WATCH_INTERVAL", "30")), +) + +_THREAD = None +_STOP = threading.Event() +_RECORD_THREADS = {} +_RECORD_LOCK = threading.Lock() + + +def _db(): + db = sqlite3.connect(DB_PATH, timeout=30) + db.row_factory = sqlite3.Row + return db + + +def init_twitch_db(): + with _db() as db: + db.executescript(""" + CREATE TABLE IF NOT EXISTS twitch_channels ( + id INTEGER PRIMARY KEY AUTOINCREMENT, + user_id INTEGER NOT NULL, + url TEXT NOT NULL, + channel_name TEXT NOT NULL, + quality TEXT NOT NULL DEFAULT 'best', + auto_record INTEGER NOT NULL DEFAULT 0, + enabled INTEGER NOT NULL DEFAULT 1, + live INTEGER NOT NULL DEFAULT 0, + stream_id TEXT NOT NULL DEFAULT '', + title TEXT NOT NULL DEFAULT '', + author TEXT NOT NULL DEFAULT '', + category TEXT NOT NULL DEFAULT '', + available_qualities TEXT NOT NULL DEFAULT '', + last_checked_at INTEGER, + created_at INTEGER NOT NULL, + updated_at INTEGER NOT NULL, + UNIQUE(user_id, channel_name) + ); + + CREATE TABLE IF NOT EXISTS twitch_recordings ( + id INTEGER PRIMARY KEY AUTOINCREMENT, + channel_id INTEGER NOT NULL, + user_id INTEGER NOT NULL, + status TEXT NOT NULL DEFAULT 'queued', + message TEXT NOT NULL DEFAULT '', + title TEXT NOT NULL DEFAULT '', + stream_id TEXT NOT NULL DEFAULT '', + output_path TEXT NOT NULL DEFAULT '', + error TEXT NOT NULL DEFAULT '', + cancel_requested INTEGER NOT NULL DEFAULT 0, + created_at INTEGER NOT NULL, + started_at INTEGER, + finished_at INTEGER + ); + + CREATE INDEX IF NOT EXISTS idx_twitch_recordings_status + ON twitch_recordings(status, created_at); + """) + + db.execute( + """UPDATE twitch_recordings + SET status='failed', + message='interrupted by service restart', + error='Recording was interrupted by Media Server restart.', + finished_at=? + WHERE status='recording'""", + (int(time.time()),), + ) + db.commit() + + +def add_channel(user_id: int, value: str, quality: str = "best"): + url, channel = normalize_twitch_url(value) + now = int(time.time()) + with _db() as db: + row = db.execute( + "SELECT id FROM twitch_channels WHERE user_id=? AND channel_name=?", + (int(user_id), channel.lower()), + ).fetchone() + + if row: + channel_id = int(row["id"]) + db.execute( + """UPDATE twitch_channels SET + url=?, + quality=?, + enabled=1, + updated_at=? + WHERE id=?""", + (url, quality or "best", now, channel_id), + ) + else: + cur = db.execute( + """INSERT INTO twitch_channels( + user_id,url,channel_name,quality,created_at,updated_at + ) VALUES(?,?,?,?,?,?)""", + ( + int(user_id), + url, + channel.lower(), + quality or "best", + now, + now, + ), + ) + channel_id = int(cur.lastrowid) + db.commit() + + refresh_channel(user_id, channel_id) + return get_channel(user_id, channel_id) + + +def get_channel(user_id: int, channel_id: int): + with _db() as db: + row = db.execute( + "SELECT * FROM twitch_channels WHERE id=? AND user_id=?", + (int(channel_id), int(user_id)), + ).fetchone() + return dict(row) if row else None + + +def list_channels(user_id: int): + with _db() as db: + rows = db.execute( + """SELECT * FROM twitch_channels + WHERE user_id=? + ORDER BY channel_name""", + (int(user_id),), + ).fetchall() + return [dict(row) for row in rows] + + +def delete_channel(user_id: int, channel_id: int): + channel = get_channel(user_id, channel_id) + if not channel: + return False + + active = active_recording_for_channel(channel_id) + if active: + raise ValueError("Stop the active recording before removing this channel.") + + with _db() as db: + db.execute( + "DELETE FROM twitch_channels WHERE id=? AND user_id=?", + (int(channel_id), int(user_id)), + ) + db.commit() + return True + + +def set_auto_record(user_id: int, channel_id: int, enabled: bool): + with _db() as db: + cur = db.execute( + """UPDATE twitch_channels + SET auto_record=?,updated_at=? + WHERE id=? AND user_id=?""", + ( + 1 if enabled else 0, + int(time.time()), + int(channel_id), + int(user_id), + ), + ) + db.commit() + if cur.rowcount != 1: + raise ValueError("Twitch channel not found.") + return get_channel(user_id, channel_id) + + +def set_quality(user_id: int, channel_id: int, quality: str): + quality = str(quality or "best").strip() or "best" + with _db() as db: + cur = db.execute( + """UPDATE twitch_channels + SET quality=?,updated_at=? + WHERE id=? AND user_id=?""", + ( + quality, + int(time.time()), + int(channel_id), + int(user_id), + ), + ) + db.commit() + if cur.rowcount != 1: + raise ValueError("Twitch channel not found.") + return get_channel(user_id, channel_id) + + +def refresh_channel(user_id: int, channel_id: int): + channel = get_channel(user_id, channel_id) + if not channel: + raise ValueError("Twitch channel not found.") + + status = probe_twitch( + channel["url"], + quality=channel.get("quality") or "best", + ) + now = int(time.time()) + + qualities = ",".join(status.get("available_qualities") or []) + with _db() as db: + db.execute( + """UPDATE twitch_channels SET + live=?, + stream_id=?, + title=?, + author=?, + category=?, + available_qualities=?, + last_checked_at=?, + updated_at=? + WHERE id=?""", + ( + 1 if status.get("live") else 0, + str(status.get("stream_id") or ""), + str(status.get("title") or ""), + str(status.get("author") or ""), + str(status.get("category") or ""), + qualities, + now, + now, + int(channel_id), + ), + ) + db.commit() + + return get_channel(user_id, channel_id) + + +def list_recordings(user_id: int, limit=50): + with _db() as db: + rows = db.execute( + """SELECT r.*,c.channel_name,c.url,c.quality + FROM twitch_recordings r + JOIN twitch_channels c ON c.id=r.channel_id + WHERE r.user_id=? + ORDER BY r.id DESC + LIMIT ?""", + (int(user_id), max(1, min(int(limit), 200))), + ).fetchall() + return [dict(row) for row in rows] + + +def active_recording_for_channel(channel_id: int): + with _db() as db: + row = db.execute( + """SELECT * FROM twitch_recordings + WHERE channel_id=? AND status IN ('queued','recording') + ORDER BY id DESC LIMIT 1""", + (int(channel_id),), + ).fetchone() + return dict(row) if row else None + + +def enqueue_recording(user_id: int, channel_id: int): + channel = get_channel(user_id, channel_id) + if not channel: + raise ValueError("Twitch channel not found.") + + existing = active_recording_for_channel(channel_id) + if existing: + return existing + + now = int(time.time()) + with _db() as db: + cur = db.execute( + """INSERT INTO twitch_recordings( + channel_id,user_id,status,message,created_at + ) VALUES(?,?,'queued','checking Twitch stream…',?)""", + (int(channel_id), int(user_id), now), + ) + job_id = int(cur.lastrowid) + db.commit() + + _start_record_thread(job_id) + return get_recording(user_id, job_id) + + +def get_recording(user_id: int, job_id: int): + with _db() as db: + row = db.execute( + "SELECT * FROM twitch_recordings WHERE id=? AND user_id=?", + (int(job_id), int(user_id)), + ).fetchone() + return dict(row) if row else None + + +def stop_recording(user_id: int, job_id: int): + with _db() as db: + row = db.execute( + "SELECT * FROM twitch_recordings WHERE id=? AND user_id=?", + (int(job_id), int(user_id)), + ).fetchone() + if not row: + raise ValueError("Twitch recording job not found.") + + if row["status"] in {"complete", "failed", "cancelled"}: + return dict(row) + + db.execute( + """UPDATE twitch_recordings + SET cancel_requested=1, + message='stopping recording…' + WHERE id=?""", + (int(job_id),), + ) + db.commit() + + return get_recording(user_id, job_id) + + +def clear_finished_recordings(user_id: int): + with _db() as db: + cur = db.execute( + """DELETE FROM twitch_recordings + WHERE user_id=? + AND status IN ('complete','failed','cancelled')""", + (int(user_id),), + ) + db.commit() + return int(cur.rowcount or 0) + + +def _cancel_requested(job_id: int): + with _db() as db: + row = db.execute( + "SELECT cancel_requested FROM twitch_recordings WHERE id=?", + (int(job_id),), + ).fetchone() + return bool(row and row["cancel_requested"]) + + +def _update_recording(job_id: int, **values): + if not values: + return + sets = [] + args = [] + for key, value in values.items(): + sets.append(f"{key}=?") + args.append(value) + args.append(int(job_id)) + with _db() as db: + db.execute( + f"UPDATE twitch_recordings SET {', '.join(sets)} WHERE id=?", + args, + ) + db.commit() + + +def _record_worker(job_id: int): + try: + with _db() as db: + job = db.execute( + "SELECT * FROM twitch_recordings WHERE id=?", + (int(job_id),), + ).fetchone() + if not job: + return + channel = db.execute( + "SELECT * FROM twitch_channels WHERE id=?", + (int(job["channel_id"]),), + ).fetchone() + if not channel: + raise RuntimeError("Twitch channel was removed.") + + try: + status = refresh_channel( + int(job["user_id"]), + int(job["channel_id"]), + ) + except Exception as error: + raise RuntimeError(f"Could not refresh Twitch channel: {error}") from error + + if not status.get("live"): + _update_recording( + job_id, + status="failed", + message="channel is offline", + error=f"{status.get('channel_name') or 'Channel'} is not live.", + finished_at=int(time.time()), + ) + return + + _update_recording( + job_id, + status="recording", + message="recording live · 00:00:00", + title=status.get("title") or "", + stream_id=status.get("stream_id") or "", + started_at=int(time.time()), + ) + + def progress(message): + _update_recording(job_id, message=message) + + result = record_twitch( + status["url"], + quality=status.get("quality") or "best", + stop_check=lambda: _cancel_requested(job_id), + progress_callback=progress, + ) + + cancelled = _cancel_requested(job_id) + _update_recording( + job_id, + status="cancelled" if cancelled else "complete", + message="recording saved" if cancelled else "complete", + output_path=result.get("output_path") or "", + finished_at=int(time.time()), + ) + except Exception as error: + _update_recording( + job_id, + status="failed", + message="failed", + error=str(error)[:4000], + finished_at=int(time.time()), + ) + print( + "[TWITCH] recording failed", + {"job_id": job_id, "error": str(error)}, + flush=True, + ) + finally: + with _RECORD_LOCK: + _RECORD_THREADS.pop(int(job_id), None) + + +def _start_record_thread(job_id: int): + with _RECORD_LOCK: + existing = _RECORD_THREADS.get(int(job_id)) + if existing and existing.is_alive(): + return + thread = threading.Thread( + target=_record_worker, + args=(int(job_id),), + daemon=True, + name=f"twitch-record-{job_id}", + ) + _RECORD_THREADS[int(job_id)] = thread + thread.start() + + +def _watch_loop(): + while not _STOP.is_set(): + try: + with _db() as db: + rows = db.execute( + """SELECT * FROM twitch_channels + WHERE enabled=1 AND auto_record=1 + ORDER BY id""" + ).fetchall() + + for row in rows: + if _STOP.is_set(): + break + + channel = dict(row) + try: + refreshed = refresh_channel( + int(channel["user_id"]), + int(channel["id"]), + ) + if refreshed.get("live"): + active = active_recording_for_channel( + int(channel["id"]) + ) + if not active: + enqueue_recording( + int(channel["user_id"]), + int(channel["id"]), + ) + except Exception as error: + print( + "[TWITCH] watcher check failed", + { + "channel": channel.get("channel_name"), + "error": str(error), + }, + flush=True, + ) + + if _STOP.wait(0.5): + break + + except Exception as error: + print("[TWITCH] watcher error:", error, flush=True) + + _STOP.wait(TWITCH_WATCH_INTERVAL) + + +def start_twitch_watcher(): + global _THREAD + if _THREAD and _THREAD.is_alive(): + return + _STOP.clear() + _THREAD = threading.Thread( + target=_watch_loop, + daemon=True, + name="twitch-live-watcher", + ) + _THREAD.start() diff --git a/youtube_metadata.py b/youtube_metadata.py new file mode 100644 index 0000000..784180e --- /dev/null +++ b/youtube_metadata.py @@ -0,0 +1,109 @@ +import json +import os +import re +from pathlib import Path +from urllib.error import HTTPError, URLError +from urllib.parse import urlencode +from urllib.request import Request, urlopen + +from dotenv import load_dotenv + +BASE_DIR = Path(__file__).resolve().parent +load_dotenv(BASE_DIR / "config.env") + +YOUTUBE_METADATA_TIMEOUT = float(os.getenv("YOUTUBE_METADATA_TIMEOUT", "12")) +YOUTUBE_OEMBED_URL = "https://www.youtube.com/oembed" +YOUTUBE_ID_RE = re.compile(r"^[A-Za-z0-9_-]{11}$") +INVALID_FILENAME_CHARS = re.compile(r'[<>:"/\\|?*\x00-\x1f]') +WHITESPACE_RE = re.compile(r"\s+") + + +def extract_youtube_id(value): + """Extract an 11-character YouTube video ID from a path or filename.""" + if value is None: + return None + + stem = Path(str(value)).stem.strip() + if YOUTUBE_ID_RE.fullmatch(stem): + return stem + + bracketed = re.findall(r"\[([A-Za-z0-9_-]{11})\]", stem) + if bracketed: + return bracketed[-1] + + # Common downloader filenames end in a space/dot/dash/underscore plus ID. + if len(stem) >= 11: + candidate = stem[-11:] + prefix = stem[:-11] + if YOUTUBE_ID_RE.fullmatch(candidate): + if not prefix or prefix[-1] in " ._-()[]": + return candidate + + # Last resort: scan delimited tokens without assuming words are IDs. + tokens = re.split(r"[\s.()\[\]]+", stem) + for token in reversed(tokens): + if YOUTUBE_ID_RE.fullmatch(token): + return token + + return None + + +def fetch_youtube_metadata(video_id, timeout=None): + """Fetch title/channel metadata using YouTube's public oEmbed endpoint.""" + if not YOUTUBE_ID_RE.fullmatch(str(video_id or "")): + raise ValueError("Invalid YouTube video ID") + + query = urlencode({ + "url": f"https://www.youtube.com/watch?v={video_id}", + "format": "json", + }) + + request = Request( + f"{YOUTUBE_OEMBED_URL}?{query}", + headers={ + "User-Agent": "MediaServer-YouTubeMetadata/1.0", + "Accept": "application/json", + }, + ) + + try: + with urlopen(request, timeout=timeout or YOUTUBE_METADATA_TIMEOUT) as response: + payload = json.loads(response.read().decode("utf-8")) + except HTTPError as exc: + if exc.code == 404: + raise LookupError(f"YouTube metadata not found for {video_id}") from exc + raise RuntimeError(f"YouTube HTTP error {exc.code} for {video_id}") from exc + except URLError as exc: + raise RuntimeError(f"YouTube request failed for {video_id}: {exc.reason}") from exc + + title = str(payload.get("title") or "").strip() + if not title: + raise LookupError(f"YouTube returned no title for {video_id}") + + return { + "video_id": video_id, + "title": title, + "channel_name": str(payload.get("author_name") or "").strip() or None, + "channel_url": str(payload.get("author_url") or "").strip() or None, + } + + +def safe_filename_title(title, max_length=180): + """Return a filesystem-safe title while keeping normal punctuation readable.""" + value = INVALID_FILENAME_CHARS.sub("", str(title or "")) + value = WHITESPACE_RE.sub(" ", value).strip(" .") + if not value: + value = "YouTube Video" + if len(value) > max_length: + value = value[:max_length].rstrip(" .") + return value + + +def build_youtube_filename(title, video_id, suffix): + """Build: Nice Video Title [VIDEO_ID].ext""" + if not YOUTUBE_ID_RE.fullmatch(str(video_id or "")): + raise ValueError("Invalid YouTube video ID") + suffix = str(suffix or "") + if suffix and not suffix.startswith("."): + suffix = "." + suffix + return f"{safe_filename_title(title)} [{video_id}]{suffix}" diff --git a/youtube_stream.py b/youtube_stream.py new file mode 100644 index 0000000..23d7172 --- /dev/null +++ b/youtube_stream.py @@ -0,0 +1,1591 @@ +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