from __future__ import annotations import json import logging import os import re import signal import subprocess import threading import time import xml.etree.ElementTree as ET from dataclasses import dataclass 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") TWITCH_RECORD_DIR = Path( os.getenv("TWITCH_RECORD_DIR", "/blade-media/twitch-cache") ).expanduser().resolve() TWITCH_STREAM_TIMEOUT = max( 5, int(os.getenv("TWITCH_STREAM_TIMEOUT", "30")), ) TWITCH_SUPPORTED_CODECS = [ item.strip().lower() for item in os.getenv("TWITCH_SUPPORTED_CODECS", "h264").split(",") if item.strip() ] logger = logging.getLogger("kronic.twitch") class TwitchOffline(RuntimeError): pass class TwitchResolutionError(RuntimeError): pass @dataclass class TwitchResolved: url: str channel: str quality: str stream: Any available_qualities: list[str] stream_id: str = "" title: str = "" author: str = "" category: str = "" def as_dict(self): return { "url": self.url, "channel": self.channel, "quality": self.quality, "available_qualities": list(self.available_qualities), "stream_id": self.stream_id, "title": self.title, "author": self.author, "category": self.category, "live": True, } def normalize_twitch_url(value: str) -> tuple[str, str]: value = str(value or "").strip() if not value: raise ValueError("Twitch channel or URL is required.") if re.fullmatch(r"[A-Za-z0-9_]{2,40}", value): channel = value return f"https://www.twitch.tv/{channel}", channel if not re.match(r"^https?://", value, re.I): value = "https://" + value.lstrip("/") match = re.search( r"(?:www\.)?twitch\.tv/([A-Za-z0-9_]{2,40})", value, re.I, ) if not match: raise ValueError("Enter a Twitch channel name or twitch.tv channel URL.") channel = match.group(1) return f"https://www.twitch.tv/{channel}", channel def _new_session(): try: from streamlink import Streamlink except ImportError as error: raise RuntimeError( "Streamlink is not installed in the Kronic virtualenv. " "Run: pip install -r requirements-twitch.txt" ) from error session = Streamlink() session.set_option("stream-timeout", TWITCH_STREAM_TIMEOUT) # Streamlink normally sits ~3 HLS segments behind live. Five segments # adds ~67% headroom at the cost of additional live latency. session.set_option("hls-live-edge", max(3, int(os.getenv("TWITCH_HLS_LIVE_EDGE", "5")))) return session def _plugin_options(): options = {} # Streamlink's Twitch plugin defaults to H.264. Explicitly keep Kronic's # supported codec list conservative because browser playback is H.264/AAC. if TWITCH_SUPPORTED_CODECS: options["supported-codecs"] = ",".join(TWITCH_SUPPORTED_CODECS) return options def resolve_twitch( value: str, quality: str = "best", ) -> TwitchResolved: url, channel = normalize_twitch_url(value) session = _new_session() try: plugin_name, plugin_class, resolved_url = session.resolve_url(url) plugin = plugin_class( session, resolved_url, options=_plugin_options(), ) streams = plugin.streams() except Exception as error: text = str(error) if "No playable streams found" in text or "offline" in text.lower(): raise TwitchOffline(f"{channel} is offline.") from error raise TwitchResolutionError( f"Streamlink could not resolve {channel}: {error}" ) from error if not streams: raise TwitchOffline(f"{channel} is offline.") available = [ key for key in streams.keys() if key not in {"best", "worst"} ] requested = str(quality or "best").strip() selected_name = requested if requested in streams else "best" selected = streams.get(selected_name) if selected is None: # Streamlink normally exposes best/worst aliases, but be defensive. selected_name, selected = next(iter(streams.items())) return TwitchResolved( url=url, channel=channel, quality=selected_name, stream=selected, available_qualities=available, stream_id=str(getattr(plugin, "id", "") or ""), title=str(getattr(plugin, "title", "") or ""), author=str(getattr(plugin, "author", "") or channel), category=str(getattr(plugin, "category", "") or ""), ) def probe_twitch(value: str, quality: str = "best") -> dict: try: resolved = resolve_twitch(value, quality=quality) except TwitchOffline: url, channel = normalize_twitch_url(value) return { "url": url, "channel": channel, "live": False, "available_qualities": [], "quality": quality or "best", "stream_id": "", "title": "", "author": channel, "category": "", } return resolved.as_dict() class TwitchFFmpegPipeline: """Streamlink -> Python pipe -> FFmpeg. Streamlink owns Twitch/HLS specifics. FFmpeg owns browser-compatible remuxing/transcoding. This works for HLSStream and MuxedHLSStream because both expose Stream.open(). """ def __init__( self, resolved: TwitchResolved, *, output_path: Path | None = None, browser_output: bool = False, ): self.resolved = resolved self.output_path = Path(output_path).resolve() if output_path else None self.browser_output = bool(browser_output) self.source = None self.process = None self.pump_thread = None self.stop_event = threading.Event() self.stderr_chunks: list[bytes] = [] self.stderr_thread = None def _ffmpeg_command(self): command = [ FFMPEG_BIN, "-nostdin", "-hide_banner", "-loglevel", "warning", "-fflags", "+genpts", "-i", "pipe:0", "-map", "0:v:0?", "-map", "0:a:0?", "-c:v", "copy", "-c:a", "aac", "-b:a", "192k", "-ac", "2", ] if self.browser_output: command.extend([ "-movflags", "frag_keyframe+empty_moov+default_base_moof", "-f", "mp4", "pipe:1", ]) else: command.extend([ "-movflags", "+faststart", "-f", "mp4", "-y", str(self.output_path), ]) return command def start(self): self.source = self.resolved.stream.open() self.process = subprocess.Popen( self._ffmpeg_command(), stdin=subprocess.PIPE, stdout=subprocess.PIPE if self.browser_output else subprocess.DEVNULL, stderr=subprocess.PIPE, bufsize=0, ) def pump(): try: while not self.stop_event.is_set(): chunk = self.source.read(256 * 1024) if not chunk: break if not self.process or not self.process.stdin: break try: self.process.stdin.write(chunk) self.process.stdin.flush() except (BrokenPipeError, OSError): break except Exception as error: logger.debug("Twitch source pump ended: %s", error) finally: try: if self.process and self.process.stdin: self.process.stdin.close() except Exception: pass def collect_stderr(): try: if not self.process or not self.process.stderr: return while True: chunk = self.process.stderr.read(8192) if not chunk: break self.stderr_chunks.append(chunk) total = sum(len(part) for part in self.stderr_chunks) if total > 128 * 1024: del self.stderr_chunks[:-8] except Exception: pass self.pump_thread = threading.Thread( target=pump, daemon=True, name=f"twitch-pump-{self.resolved.channel}", ) self.stderr_thread = threading.Thread( target=collect_stderr, daemon=True, name=f"twitch-ffmpeg-stderr-{self.resolved.channel}", ) self.pump_thread.start() self.stderr_thread.start() return self def stop(self, graceful=True): self.stop_event.set() try: if self.source is not None: self.source.close() except Exception: pass if self.process is not None and self.process.poll() is None: if graceful: try: self.process.send_signal(signal.SIGINT) except Exception: self.process.terminate() else: self.process.terminate() try: self.process.wait(timeout=8 if graceful else 3) except subprocess.TimeoutExpired: self.process.kill() try: self.process.wait(timeout=2) except Exception: pass if self.pump_thread: self.pump_thread.join(timeout=2) if self.stderr_thread: self.stderr_thread.join(timeout=1) def wait(self): if not self.process: return -1 return self.process.wait() def stderr_text(self): return b"".join(self.stderr_chunks).decode("utf-8", "replace") def start_browser_pipeline(value: str, quality: str = "best"): resolved = resolve_twitch(value, quality=quality) pipeline = TwitchFFmpegPipeline( resolved, browser_output=True, ).start() return resolved, pipeline def safe_recording_stem(resolved: TwitchResolved): timestamp = time.strftime("%Y-%m-%d_%H-%M-%S") title = resolved.title or resolved.channel safe_title = re.sub(r"[^A-Za-z0-9._ -]+", "", title).strip() safe_title = re.sub(r"\s+", " ", safe_title)[:100] or resolved.channel return f"{resolved.channel} - {timestamp} - {safe_title}" def write_twitch_nfo(path: Path, resolved: TwitchResolved): root = ET.Element("movie") def add(tag, value): if value in (None, ""): return child = ET.SubElement(root, tag) child.text = str(value) add("title", resolved.title or f"{resolved.channel} Twitch Stream") add("plot", f"Recorded live from Twitch channel {resolved.author or resolved.channel}.") add("studio", resolved.author or resolved.channel) add("genre", resolved.category) add("source", "twitch") add("webpage", resolved.url) add("recorded", time.strftime("%Y-%m-%d %H:%M:%S")) if resolved.stream_id: uid = ET.SubElement( root, "uniqueid", {"type": "twitch", "default": "true"}, ) uid.text = resolved.stream_id tree = ET.ElementTree(root) try: ET.indent(tree, space=" ") except AttributeError: pass tree.write( path.with_suffix(".nfo"), encoding="utf-8", xml_declaration=True, ) def record_twitch( value: str, quality: str = "best", *, stop_check=None, progress_callback=None, ): TWITCH_RECORD_DIR.mkdir(parents=True, exist_ok=True) resolved = resolve_twitch(value, quality=quality) final_path = TWITCH_RECORD_DIR / f"{safe_recording_stem(resolved)}.mp4" part_path = final_path.with_suffix(".part.mp4") pipeline = TwitchFFmpegPipeline( resolved, output_path=part_path, browser_output=False, ).start() started = time.monotonic() try: while pipeline.process and pipeline.process.poll() is None: if stop_check and stop_check(): pipeline.stop(graceful=True) break elapsed = max(0, int(time.monotonic() - started)) hours, rem = divmod(elapsed, 3600) minutes, seconds = divmod(rem, 60) if progress_callback: progress_callback( f"recording live ยท {hours:02d}:{minutes:02d}:{seconds:02d}" ) time.sleep(1) returncode = pipeline.process.returncode if pipeline.process else -1 finally: if pipeline.process and pipeline.process.poll() is None: pipeline.stop(graceful=True) else: pipeline.stop_event.set() try: if pipeline.source is not None: pipeline.source.close() except Exception: pass if part_path.is_file() and part_path.stat().st_size > 0: os.replace(part_path, final_path) try: write_twitch_nfo(final_path, resolved) except Exception as error: logger.warning("Could not write Twitch NFO: %s", error) return { **resolved.as_dict(), "output_path": str(final_path), "size_bytes": final_path.stat().st_size, "returncode": returncode, } error = pipeline.stderr_text()[-4000:] raise RuntimeError( f"Twitch recording produced no playable file. " f"FFmpeg return code {returncode}. {error}" )