douyinWEB/backend/app/youtube_relay.py
eric d409e416da Ship physical dual-edge stack, Studio CDP live metrics, and ops tooling.
Capture Neko/WG/network hubs, Studio viewer charts, physical deploy docs, and one-shot scripts so VPS vs physical can be toggled later without losing WIP.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-09-04 22:42:40 -05:00

472 lines
16 KiB
Python

# -*- 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
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]}"
)
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)
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}")
self._proc = subprocess.Popen(
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
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