# -*- coding: utf-8 -*- """FFmpeg Douyin live → YouTube RTMPS relay (cloud server, no ShellCrash/Neko).""" from __future__ import annotations import re import subprocess import threading import time from dataclasses import dataclass, field from typing import Any, Callable from .config import settings class RelayStreamEnded(Exception): """Source ended / CDN terminal (404) — outer loop must re-resolve with Cookie.""" class RelaySourceStalled(Exception): """No progress — try next fallback URL from same parse batch.""" MAX_RELAY_LOG_LINES = 200 # Aligned with sh2/douyin_youtube_ffplay.py TERMINAL / TRANSIENT split. _TERMINAL_HINTS = ( "404 not found", "server returned 404", "403 forbidden", "server returned 403", "live has ended", "stream ends prematurely", "end of file", "stream ended", "access denied", "ingestion error", ) _TRANSIENT_HINTS = ( "connection reset", "connection timed out", "connection refused", "broken pipe", "i/o error", "input/output error", "server returned 500", "error writing output", "no route to host", ) @dataclass class RelayStats: speed: float = 0.0 frame: int = 0 pid: int = 0 running: bool = False last_line: str = "" recent_log: list[str] = field(default_factory=list) def _headers_arg() -> str: return ( "User-Agent: Mozilla/5.0 (iPhone; CPU iPhone OS 18_1 like Mac OS X) " "AppleWebKit/605.1.15 (KHTML, like Gecko) Version/18.1 Mobile/15E148 Safari/604.1\r\n" "Referer: https://live.douyin.com/\r\n" ) def _bitrate_triplet(kbps: int) -> tuple[str, str, str]: n = max(1500, min(int(kbps), 9000)) s = f"{n}k" return s, s, f"{n * 2}k" def _parse_ffmpeg_line(line: str) -> tuple[float | None, int | None]: speed = None frame = None m = re.search(r"speed=\s*([\d.]+)x", line) if m: try: speed = float(m.group(1)) except ValueError: pass m2 = re.search(r"frame=\s*(\d+)", line) if m2: try: frame = int(m2.group(1)) except ValueError: pass return speed, frame def build_youtube_rtmp_url(stream_key: str, *, use_rtmps: bool = True) -> str: key = str(stream_key or "").strip() if not key: raise ValueError("缺少 YouTube 直播 KEY") if key.startswith("rtmp"): return key base = "rtmps://a.rtmps.youtube.com/live2/" if use_rtmps else "rtmp://a.rtmp.youtube.com/live2/" return f"{base}{key}" def build_ffmpeg_relay_cmd( input_url: str, youtube_rtmp: str, *, bitrate_kbps: int = 4000, ffmpeg_bin: str | None = None, width: int = 720, height: int = 1280, fps: int = 30, x264_preset: str = "veryfast", gop: int = 60, profile: str = "high", level: str = "4.0", audio_bitrate_kbps: int = 128, x264_threads: int = 0, scale_flags: str = "bilinear", ) -> list[str]: b_v, maxrate, bufsize = _bitrate_triplet(bitrate_kbps) ff = str(ffmpeg_bin or settings.ffmpeg_bin or "ffmpeg") w, h = max(360, int(width)), max(640, int(height)) out_fps = max(15, min(int(fps), 60)) gop_frames = max(out_fps, int(gop)) vf = ( f"fps={out_fps},scale={w}:{h}:force_original_aspect_ratio=decrease:flags={scale_flags}," f"pad={w}:{h}:(ow-iw)/2:(oh-ih)/2:black" ) is_flv = ".flv" in input_url.lower() or "pull-" in input_url.lower() input_args: list[str] = [] if is_flv: input_args = ["-reconnect", "1", "-reconnect_at_eof", "1", "-reconnect_streamed", "1", "-reconnect_delay_max", "30"] return [ ff, "-y", "-loglevel", "info", "-nostdin", "-stats", "-rw_timeout", "50000000", *input_args, "-fflags", "+genpts+discardcorrupt", "-thread_queue_size", "2048", "-headers", _headers_arg(), "-re", "-i", input_url, "-vf", vf, "-c:v", "libx264", *([] if int(x264_threads or 0) <= 0 else ["-threads", str(int(x264_threads))]), "-preset", str(x264_preset or "veryfast"), "-tune", "zerolatency", "-profile:v", str(profile or "high"), "-level", str(level or "4.0"), "-b:v", b_v, "-minrate", b_v, "-maxrate", maxrate, "-bufsize", bufsize, "-g", str(gop_frames), "-keyint_min", str(gop_frames), "-r", str(out_fps), "-pix_fmt", "yuv420p", # Douyin FLV often has audio as stream 0 — explicit maps keep AAC on YouTube ingest. "-map", "0:v:0", "-map", "0:a:0?", "-c:a", "aac", "-profile:a", "aac_low", "-b:a", f"{max(128, min(int(audio_bitrate_kbps), 192))}k", "-ar", "48000", "-ac", "2", "-af", "aresample=async=1:first_pts=0", "-flags", "+global_header", "-flvflags", "no_duration_filesize", "-f", "flv", youtube_rtmp, ] def _terminate_proc(proc: subprocess.Popen | None) -> None: if not proc: return try: if proc.poll() is None: proc.terminate() try: proc.wait(timeout=5) except subprocess.TimeoutExpired: proc.kill() except Exception: pass def kill_ffmpeg_sharing_rtmp(youtube_rtmp: str, *, keep_pid: int = 0) -> list[int]: """Kill other host ffmpeg processes already pushing the same YouTube stream key. YouTube returns "More than one ingestion is using the primary URL" when two encoders share one key — Studio health goes Poor and public live flaps. """ import os key = (youtube_rtmp or "").rstrip("/").split("/")[-1].strip() if len(key) < 8: return [] try: out = subprocess.check_output(["ps", "-eo", "pid,cmd"], text=True, timeout=8) except Exception: return [] killed: list[int] = [] keep = int(keep_pid or 0) keep_set = {keep} if keep > 0 else set() # Also protect children of keep (proxychains → ffmpeg). if keep > 0: try: for line in out.splitlines(): parts = line.split(None, 1) if len(parts) < 2: continue try: pid = int(parts[0]) except Exception: continue # /proc ppid check below except Exception: pass try: import pathlib for proc_dir in pathlib.Path("/proc").iterdir(): if not proc_dir.name.isdigit(): continue pid = int(proc_dir.name) try: status = (proc_dir / "status").read_text(encoding="utf-8", errors="ignore") except Exception: continue for ln in status.splitlines(): if ln.startswith("PPid:"): try: ppid = int(ln.split()[1]) except Exception: break if ppid in keep_set or pid == keep: keep_set.add(pid) break except Exception: pass for line in out.splitlines(): low = line.lower() if "ffmpeg" not in low or key not in line: continue # Only YouTube ingest destinations — never match unrelated ffmpeg with same token. if "rtmps.youtube.com" not in low and "rtmp.youtube.com" not in low and "/live2/" not in low: continue try: pid = int(line.split(None, 1)[0]) except Exception: continue if pid in keep_set: continue try: os.kill(pid, 9) killed.append(pid) except Exception: pass return killed _RTMP_SPAWN_LOCKS: dict[str, threading.Lock] = {} _RTMP_SPAWN_LOCKS_MU = threading.Lock() def _rtmp_spawn_lock(youtube_rtmp: str) -> threading.Lock: key = (youtube_rtmp or "").rstrip("/").split("/")[-1].strip() or "_" with _RTMP_SPAWN_LOCKS_MU: lock = _RTMP_SPAWN_LOCKS.get(key) if lock is None: lock = threading.Lock() _RTMP_SPAWN_LOCKS[key] = lock return lock class RelayPushSession: """One FFmpeg push subprocess with stderr monitoring. Aligned with sh2 start_douyin_youtube_ffplay: - TRANSIENT errors: rebuild same URL after short backoff - SourceStalled / no progress: advance to next fallback URL (same spider batch) - TERMINAL (404 / live ended): exit session → outer pipeline re-resolves with Cookie """ STALE_SEC = 40.0 NO_FRAME_SEC = 120.0 START_GRACE_SEC = 25.0 def __init__( self, *, group_id: str, input_url: str = "", input_urls: list[str] | None = None, youtube_rtmp: str, anchor_name: str = "", source_url: str = "", room_id: str = "", bitrate_kbps: int = 4000, encoding: dict[str, Any] | None = None, on_stats: Callable[[RelayStats], None] | None = None, ) -> None: self.group_id = group_id urls: list[str] = [] for u in list(input_urls or []) + ([input_url] if input_url else []): s = str(u or "").strip() if s.startswith("http") and s not in urls: urls.append(s) if not urls: raise ValueError("缺少抖音拉流地址") self.input_urls = urls self.input_url = urls[0] self.youtube_rtmp = youtube_rtmp self.anchor_name = anchor_name self.source_url = source_url self.room_id = room_id self.bitrate_kbps = bitrate_kbps self.encoding = dict(encoding or {}) self.on_stats = on_stats self._proc: subprocess.Popen | None = None self._stop = threading.Event() self._thread: threading.Thread | None = None self.stats = RelayStats() self._source_index = 0 def start(self) -> None: if self._thread and self._thread.is_alive(): return self._stop.clear() self._thread = threading.Thread(target=self._run, name=f"yt-relay-{self.group_id}", daemon=True) self._thread.start() def stop(self) -> None: self._stop.set() _terminate_proc(self._proc) if self._thread: self._thread.join(timeout=8) self.stats.running = False def _build_cmd(self, input_url: str) -> list[str]: enc = self.encoding return build_ffmpeg_relay_cmd( input_url, self.youtube_rtmp, bitrate_kbps=self.bitrate_kbps, width=int(enc.get("width") or 720), height=int(enc.get("height") or 1280), fps=int(enc.get("fps") or 30), x264_preset=str(enc.get("x264_preset") or "veryfast"), gop=int(enc.get("gop") or 60), profile=str(enc.get("profile") or "high"), level=str(enc.get("level") or "4.0"), audio_bitrate_kbps=int(enc.get("audio_bitrate_kbps") or 128), x264_threads=int(enc.get("x264_threads") or 0), scale_flags=str(enc.get("scale_flags") or "bilinear"), ) def _run(self) -> None: import queue as _queue enc = self.encoding preset_id = str(enc.get("preset_id") or "720p") self.stats.recent_log.append( f"[ffmpeg] quality={preset_id} {enc.get('width')}x{enc.get('height')}@{enc.get('fps')} " f"preset={enc.get('x264_preset')} bitrate={self.bitrate_kbps}k candidates={len(self.input_urls)}" ) retry_delay = 0.0 while not self._stop.is_set() and self._source_index < len(self.input_urls): self.input_url = self.input_urls[self._source_index] cmd = self._build_cmd(self.input_url) q: _queue.Queue[str | None] = _queue.Queue() if retry_delay > 0: self.stats.recent_log.append(f"[ffmpeg] backoff {retry_delay:.0f}s then retry same URL") time.sleep(min(retry_delay, 90.0)) if self._stop.is_set(): break self.stats.recent_log.append( f"[ffmpeg] source {self._source_index + 1}/{len(self.input_urls)} -i {self.input_url[:160]}" ) # Serialize spawn per stream key so two sessions cannot Popen then # mutually kill each other via post-spawn rival cleanup. with _rtmp_spawn_lock(self.youtube_rtmp): # Do NOT pre-kill without keep_pid: a concurrent session may already # hold the only healthy encoder for this key. try: try: from . import egress_hub wrapped = egress_hub.wrap_ffmpeg_cmd(cmd) if wrapped != cmd: self.stats.recent_log.append( f"[ffmpeg] egress proxychains mode={egress_hub.get_mode()}" ) cmd = wrapped except Exception as exc: self.stats.recent_log.append(f"[ffmpeg] egress wrap skipped: {exc}") # Keep encode RAM out of douyinweb-api MemoryHigh (D-state hang). from .procutil import popen_outside_api_cgroup self._proc = popen_outside_api_cgroup( cmd, stdin=subprocess.DEVNULL, stdout=subprocess.DEVNULL, stderr=subprocess.PIPE, text=True, bufsize=1, ) except FileNotFoundError: self.stats.recent_log.append("[ffmpeg] ERROR: ffmpeg binary not found") self.stats.running = False return except Exception as exc: self.stats.recent_log.append(f"[ffmpeg] ERROR spawn failed: {exc}") self.stats.running = False return self.stats.pid = int(self._proc.pid or 0) self.stats.running = True try: rivals = kill_ffmpeg_sharing_rtmp(self.youtube_rtmp, keep_pid=self.stats.pid) if rivals: self.stats.recent_log.append(f"[ffmpeg] post-spawn killed rivals {rivals}") except Exception: pass def _reader() -> None: proc = self._proc if not proc or not proc.stderr: q.put(None) return try: for line in proc.stderr: if self._stop.is_set(): break # FFmpeg progress often uses \r without \n for part in line.replace("\r", "\n").split("\n"): part = part.strip() if part: q.put(part) except Exception as exc: q.put(f"[ffmpeg] reader error: {exc}") finally: q.put(None) self.stats.recent_log.append(f"[ffmpeg] pid={self.stats.pid} started") if self.on_stats: try: self.on_stats(self.stats) except Exception: pass last_out = time.time() started = time.time() last_frame_at = time.time() last_frame_n = 0 reader = threading.Thread(target=_reader, daemon=True) reader.start() terminal = False stalled = False transient = False while not self._stop.is_set(): try: line = q.get(timeout=2.0) except _queue.Empty: now = time.time() if now - last_out > self.STALE_SEC: self.stats.recent_log.append("[ffmpeg] stale: no stderr — try fallback / refresh") stalled = True _terminate_proc(self._proc) break if ( now - started > self.START_GRACE_SEC and now - last_frame_at > self.NO_FRAME_SEC ): self.stats.recent_log.append("[ffmpeg] no frame progress 120s — try fallback") stalled = True _terminate_proc(self._proc) break continue if line is None: break last_out = time.time() self.stats.last_line = line[:240] self.stats.recent_log.append(line[:500]) if len(self.stats.recent_log) > MAX_RELAY_LOG_LINES: self.stats.recent_log = self.stats.recent_log[-MAX_RELAY_LOG_LINES:] sp, fr = _parse_ffmpeg_line(line) if sp is not None: self.stats.speed = sp if fr is not None: if fr > last_frame_n: last_frame_n = fr last_frame_at = time.time() self.stats.frame = fr if self.on_stats: try: self.on_stats(self.stats) except Exception: pass low = line.lower() if any(h in low for h in _TERMINAL_HINTS): self.stats.recent_log.append("[ffmpeg] TERMINAL — exit for Cookie re-resolve (sh2)") terminal = True _terminate_proc(self._proc) break if any(h in low for h in _TRANSIENT_HINTS): transient = True _terminate_proc(self._proc) self.stats.running = False if self._stop.is_set(): return if terminal: # Outer youtube_relay_pipeline must re-spider with dy_cookie. return if stalled or (not transient and self._source_index + 1 < len(self.input_urls)): if self._source_index + 1 < len(self.input_urls): self._source_index += 1 retry_delay = 0.0 self.stats.recent_log.append( f"[ffmpeg] source_failover → {self._source_index + 1}/{len(self.input_urls)}" ) continue # Fallbacks exhausted — exit for outer Cookie re-resolve (sh2 SourceStalled end). self.stats.recent_log.append("[ffmpeg] fallbacks exhausted — exit for refresh") return if transient: retry_delay = 3.0 if retry_delay <= 0 else min(90.0, retry_delay * 2) continue # Unknown exit: brief retry then give outer loop a chance. retry_delay = 3.0 if retry_delay <= 0 else min(30.0, retry_delay * 1.5) if retry_delay >= 20: self.stats.recent_log.append("[ffmpeg] repeated exit — leave for outer refresh") return self.stats.running = False