sh2/d2ypp2/douyin_youtube_ffplay.py
eric 278b48497e Add YouTube relay log tooling and optional hub service controls.
This captures the current live stack updates across the API, Linux service scripts, tests, diagnostics, and exported console assets so the Ubuntu deployment can pull a consistent test3 build.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-07-30 05:10:09 -05:00

1304 lines
49 KiB
Python
Raw Permalink Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

# douyin_youtube_ffplay.py
# Linux:仓库内推流实现,编码由 config/hardware.env(LIVE_VIDEO_ENCODER)与可选 NVENC 探测决定。
import queue
import unicodedata
import platform
import traceback
import time
import datetime
import subprocess
import threading
import re
import os
import glob
import configparser
import socket
import shutil
from urllib.parse import urlparse
from src.youtube_runtime import resolve_live_video_encoder
from src.youtube_encoder_cache import get_cached_encoder, store_cached_encoder
from src.youtube_relay_heartbeat import clear_relay_heartbeat, write_relay_heartbeat
class StreamEnded(Exception):
"""主播真实下播的专用异常"""
pass
class SourceStalled(Exception):
"""当前直播源 URL 无进度,交回外层重新抓取源地址。"""
pass
_FFMPEG_STATS_PERIOD_OK: dict[str, bool] = {}
_FFMPEG_FILTERS_CACHE: dict[str, str] = {}
_FFMPEG_STATIC_CACHE: dict[str, bool] = {}
_FFMPEG_PROTOCOLS_CACHE: dict[str, str] = {}
def _youtube_bitrate_triplet(kbps: int) -> tuple[str, str, str]:
"""YouTube Live prefers CBR; keep maxrate equal to target and use a 2s VBV buffer."""
n = max(1500, min(int(kbps), 9000))
return f"{n}k", f"{n}k", f"{n * 2}k"
def _bounded_int(value: str | None, default: int, minimum: int, maximum: int) -> int:
try:
parsed = int(str(value or "").strip())
except (TypeError, ValueError):
return default
return max(minimum, min(parsed, maximum))
def _h264_vaapi_video_args(config: dict[str, str] | None = None) -> tuple[list[str], str]:
cfg = config or {}
qp_raw = (
os.environ.get("LIVE_VAAPI_QP")
or os.environ.get("YOUTUBE_VAAPI_QP")
or cfg.get("LIVE_VAAPI_QP")
or cfg.get("YOUTUBE_VAAPI_QP")
)
qp = _bounded_int(qp_raw, 24, 18, 32)
return ["-rc_mode", "CQP", "-qp", str(qp), "-profile:v", "high"], f"CQP qp={qp}"
def _load_simple_env_file(path: str) -> dict[str, str]:
out: dict[str, str] = {}
if not os.path.isfile(path):
return out
with open(path, "r", encoding="utf-8-sig", errors="ignore") as fh:
for line in fh:
line = line.strip()
if not line or line.startswith("#") or "=" not in line:
continue
k, _, v = line.partition("=")
key = k.strip()
if key.startswith("#"):
continue
out[key] = v.strip().strip('"').strip("'")
return out
def _ffmpeg_stats_period_seconds(default: int = 5) -> str:
raw = os.environ.get("LIVE_FFMPEG_STATS_PERIOD") or os.environ.get("YOUTUBE_FFMPEG_STATS_PERIOD") or str(default)
try:
value = int(float(str(raw).strip()))
except (TypeError, ValueError):
value = default
return str(max(1, min(value, 60)))
def _ffmpeg_display_name(ffmpeg_bin: str) -> str:
return ffmpeg_bin or "ffmpeg"
def _ffmpeg_resolved_path(ffmpeg_bin: str) -> str:
ffmpeg_bin = (ffmpeg_bin or "ffmpeg").strip()
if os.path.sep in ffmpeg_bin or (os.path.altsep and os.path.altsep in ffmpeg_bin):
return ffmpeg_bin
return shutil.which(ffmpeg_bin) or ffmpeg_bin
def _ffmpeg_supports_stats_period(ffmpeg_bin: str = "ffmpeg") -> bool:
key = _ffmpeg_resolved_path(ffmpeg_bin)
if key in _FFMPEG_STATS_PERIOD_OK:
return _FFMPEG_STATS_PERIOD_OK[key]
try:
r = subprocess.run(
[ffmpeg_bin, "-hide_banner", "-h", "full"],
capture_output=True,
text=True,
timeout=30,
)
blob = (r.stdout or "") + (r.stderr or "")
ok = "-stats_period" in blob
except FileNotFoundError:
_FFMPEG_STATS_PERIOD_OK[key] = False
raise RuntimeError("未找到 ffmpeg,请先安装。") from None
except Exception as e:
print(f"[WARN] 无法检测 {_ffmpeg_display_name(ffmpeg_bin)} 是否支持 -stats_period: {e}")
ok = True
_FFMPEG_STATS_PERIOD_OK[key] = ok
return ok
def _ffmpeg_stats_args(ffmpeg_bin: str = "ffmpeg") -> list[str]:
if _ffmpeg_supports_stats_period(ffmpeg_bin):
return ["-stats", "-stats_period", _ffmpeg_stats_period_seconds()]
print(f"[WARN] {_ffmpeg_display_name(ffmpeg_bin)} 不支持 -stats_period,已降级为 -stats")
return ["-stats"]
def _require_ffmpeg_stats_period(ffmpeg_bin: str = "ffmpeg") -> None:
"""推流依赖 -stats_period(ffmpeg 约 4.4+);Debian 11 默认 4.3 需升级。"""
if _ffmpeg_supports_stats_period(ffmpeg_bin):
return
raise RuntimeError(
"ffmpeg 不支持 -stats_period(需约 4.4+)。板端执行: sudo bash scripts/linux/upgrade_ffmpeg_newer.sh"
)
def _ffmpeg_filters(ffmpeg_bin: str = "ffmpeg") -> str:
key = _ffmpeg_resolved_path(ffmpeg_bin)
if key in _FFMPEG_FILTERS_CACHE:
return _FFMPEG_FILTERS_CACHE[key]
try:
r = subprocess.run(
[ffmpeg_bin, "-hide_banner", "-filters"],
capture_output=True,
text=True,
timeout=8,
)
blob = (r.stdout or "") + (r.stderr or "")
except Exception as e:
print(f"[WARN] 无法检测 {_ffmpeg_display_name(ffmpeg_bin)} filters: {e}")
blob = ""
_FFMPEG_FILTERS_CACHE[key] = blob
return blob
def _ffmpeg_has_filter(ffmpeg_bin: str, name: str) -> bool:
blob = _ffmpeg_filters(ffmpeg_bin)
return bool(re.search(rf"(^|\s){re.escape(name)}\s", blob))
def sanitize_title(text: str, max_len: int = 120) -> str:
if not text:
return ""
text = unicodedata.normalize("NFKC", text)
text = ''.join(ch for ch in text if unicodedata.category(ch)[0] != 'C')
text = ''.join(ch for ch in text if ord(ch) <= 0xFFFF)
return text.strip()[:max_len]
def _stderr_reader_thread(proc, q):
try:
while True:
line = proc.stderr.readline()
if not line:
break
q.put(line)
except Exception as e:
try:
q.put(f"__ERR__READER__:{e}")
except Exception:
pass
finally:
try:
q.put(None)
except Exception:
pass
def _ffmpeg_progress_values(line: str) -> tuple[int | None, float | None]:
frame = None
media_time = None
m = re.search(r"frame=\s*(\d+)", line)
if m:
try:
frame = int(m.group(1))
except ValueError:
frame = None
m = re.search(r"time=(\d+):(\d+):(\d+(?:\.\d+)?)", line)
if m:
try:
media_time = int(m.group(1)) * 3600 + int(m.group(2)) * 60 + float(m.group(3))
except ValueError:
media_time = None
return frame, media_time
def _ffmpeg_speed_value(line: str) -> float | None:
m = re.search(r"speed=\s*([\d.]+)x", line)
if not m:
return None
try:
return float(m.group(1))
except ValueError:
return None
def _looks_like_invalid_ts_drop(line: str) -> bool:
return "invalid dropping" in (line or "").lower()
def cleanup_proc(proc):
try:
if proc and proc.poll() is None:
try:
proc.terminate()
proc.wait(timeout=5)
except Exception:
if proc.poll() is None:
try:
proc.kill()
except Exception:
pass
except Exception:
pass
def _live_pm2_name() -> str:
return (os.environ.get("LIVE_PM2_PROCESS_NAME") or os.environ.get("PM2_SERVICE_NAME") or "").strip()
def _resolve_youtube_push_config_file(config_file: str | None = None, *, base_dir: str | None = None) -> str:
root_dir = os.path.abspath(base_dir or os.path.dirname(os.path.abspath(__file__)))
if config_file:
cfg = str(config_file).strip()
if cfg:
return cfg if os.path.isabs(cfg) else os.path.join(root_dir, cfg)
legacy = os.path.join(root_dir, "config", "youtube.ini")
pm2 = _live_pm2_name()
if pm2:
low = pm2.lower()
if low.startswith("youtube") or low.startswith("douyin_youtube"):
safe = re.sub(r"[^a-zA-Z0-9_.-]", "_", pm2)
managed = os.path.join(root_dir, "config", f"youtube.{safe}.ini")
if os.path.isfile(managed):
return managed
return legacy
def _load_youtube_push_settings(config_file: str) -> dict[str, str | bool]:
b_v, maxrate, bufsize = _youtube_bitrate_triplet(4000)
settings: dict[str, str | bool] = {
"use_rtmps": True,
"b_v": b_v,
"maxrate": maxrate,
"bufsize": bufsize,
"stream_key": "",
"fast_audio": True,
}
if not os.path.exists(config_file):
return settings
config = configparser.ConfigParser()
config.read(config_file, encoding="utf-8-sig")
if not config.has_section("youtube"):
return settings
for k, v in config.items("youtube"):
v = (v or "").strip()
if k == "rtmps" and v.lower() in ("0", "false", "否"):
settings["use_rtmps"] = False
elif k == "fast_audio":
settings["fast_audio"] = v.lower() in ("1", "true", "yes", "是", "开", "on")
elif k == "bitrate" and v:
try:
settings["b_v"], settings["maxrate"], settings["bufsize"] = _youtube_bitrate_triplet(int(v))
except ValueError:
pass
elif (k == "key" or k == "stream_key") and v and not v.startswith("#"):
settings["stream_key"] = v
return settings
def _is_local_tcp_open(host: str, port: int, timeout: float = 0.35) -> bool:
try:
with socket.create_connection((host, port), timeout=timeout):
return True
except OSError:
return False
def _redact_proxy_url(value: str) -> str:
return re.sub(r"(://[^:/@\s]+:)[^@/\s]+(@)", r"\1<redacted>\2", value)
def _is_disabled_value(value: str) -> bool:
return (value or "").strip().lower() in {"0", "false", "no", "off", "none", "direct"}
_PROXY_ENV_KEYS = (
"http_proxy",
"https_proxy",
"all_proxy",
"HTTP_PROXY",
"HTTPS_PROXY",
"ALL_PROXY",
)
def _normalize_push_proxy_mode(configured: str | None = None) -> str:
value = configured or os.environ.get("YOUTUBE_PUSH_PROXY_MODE") or os.environ.get("LIVE_YOUTUBE_PUSH_PROXY_MODE")
if not value:
attach = (os.environ.get("SHELLCRASH_ATTACH_FFMPEG") or "").strip()
if _is_disabled_value(attach):
return "off"
if attach.lower() in {"1", "true", "yes", "on", "enable", "enabled", "force", "forced", "proxy", "shellcrash"}:
return "proxychains"
value = "auto"
low = (value or "").strip().lower()
if low in {"0", "false", "no", "off", "none", "direct"}:
return "off"
if low in {"env", "environment", "http_proxy", "https_proxy"}:
return "env"
if low in {"proxychains", "proxychains4", "chain"}:
return "proxychains"
return "auto"
def _resolve_youtube_push_proxy(configured: str | None = None) -> str:
explicit_candidates = [
configured,
os.environ.get("YOUTUBE_PUSH_PROXY"),
os.environ.get("LIVE_YOUTUBE_PUSH_PROXY"),
]
for value in explicit_candidates:
value = (value or "").strip()
if _is_disabled_value(value):
return ""
if value:
return value
auto = os.environ.get("YOUTUBE_PUSH_PROXY_AUTO", "1").strip().lower()
proxy_port_raw = os.environ.get("YOUTUBE_PUSH_PROXY_PORT") or os.environ.get("LIVE_YOUTUBE_PUSH_PROXY_PORT") or "7890"
try:
proxy_port = int(str(proxy_port_raw).strip())
except (TypeError, ValueError):
proxy_port = 7890
if auto not in {"0", "false", "no", "off"} and _is_local_tcp_open("127.0.0.1", proxy_port):
return f"socks5://127.0.0.1:{proxy_port}"
for key in ("https_proxy", "http_proxy", "HTTPS_PROXY", "HTTP_PROXY"):
value = (os.environ.get(key) or "").strip()
if _is_disabled_value(value):
return ""
if value:
return value
return ""
def _ffmpeg_env_with_push_proxy(
push_proxy: str,
proxy_mode: str = "auto",
*,
use_proxychains: bool = False,
) -> dict[str, str]:
env = os.environ.copy()
pm2 = _live_pm2_name()
if pm2:
env["LIVE_PM2_PROCESS_NAME"] = pm2
env["PM2_SERVICE_NAME"] = pm2
for key in _PROXY_ENV_KEYS:
env.pop(key, None)
push_proxy = (push_proxy or "").strip()
if not push_proxy:
return env
mode = _normalize_push_proxy_mode(proxy_mode)
if mode == "off" or use_proxychains:
return env
for key in _PROXY_ENV_KEYS:
env[key] = push_proxy
return env
def _should_use_proxychains(push_proxy: str, proxy_mode: str = "auto") -> bool:
if not push_proxy:
return False
mode = _normalize_push_proxy_mode(proxy_mode)
if mode in {"off", "env"}:
return False
return bool(shutil.which("proxychains4"))
def _proxychains_proxy_line(push_proxy: str) -> str | None:
value = (push_proxy or "").strip()
if not value:
return None
parsed = urlparse(value if "://" in value else f"socks5://{value}")
host = parsed.hostname
port = parsed.port
if not host or not port:
return None
scheme = (parsed.scheme or "socks5").lower()
if scheme in {"socks", "socks5", "socks5h"}:
proxy_type = "socks5"
elif scheme == "socks4":
proxy_type = "socks4"
elif scheme in {"http", "https"}:
proxy_type = "http"
else:
return None
parts = [proxy_type, host, str(port)]
if parsed.username:
parts.append(parsed.username)
if parsed.password:
parts.append(parsed.password)
return " ".join(parts)
def _is_probable_stream_input(url: str) -> bool:
u = (url or "").strip().lower()
if not u.startswith("http"):
return False
if any(token in u for token in (".flv", ".m3u8", "pull-flv", "pull-hls", "/pull/", "/third/stream-")):
return True
if "live.douyin.com/" in u:
return False
return True
def _looks_like_youtube_output_rejected(line_lower: str) -> bool:
if not any(
marker in line_lower
for marker in (
"rtmps://a.rtmps.youtube.com/live2/",
"rtmp://a.rtmp.youtube.com/live2/",
"youtube.com/live2/",
)
):
return False
if not any(
marker in line_lower
for marker in ("error opening output", "error opening output file", "error opening output files")
):
return False
return any(
marker in line_lower
for marker in (
"input/output error",
"io error: end of file",
"error in the pull function",
"tls @",
"401",
"403",
"unauthorized",
"forbidden",
)
)
def _proxychains_config_for_push(push_proxy: str) -> str | None:
explicit = (
os.environ.get("YOUTUBE_PROXYCHAINS_CONF")
or os.environ.get("LIVE_YOUTUBE_PROXYCHAINS_CONF")
or ""
).strip()
if explicit and os.path.isfile(explicit):
return explicit
proxy_line = _proxychains_proxy_line(push_proxy)
if proxy_line:
root = os.path.dirname(os.path.abspath(__file__))
runtime_dir = os.path.join(root, ".process_runner")
try:
os.makedirs(runtime_dir, exist_ok=True)
conf = os.path.join(runtime_dir, "proxychains-youtube.conf")
with open(conf, "w", encoding="utf-8") as fh:
fh.write(
"strict_chain\n"
"proxy_dns\n"
"tcp_read_time_out 30000\n"
"tcp_connect_time_out 8000\n\n"
"[ProxyList]\n"
f"{proxy_line}\n"
)
try:
os.chmod(conf, 0o600)
except OSError:
pass
return conf
except OSError as e:
print(f"[WARN] 无法写入 proxychains runtime 配置: {e}")
conf = os.path.join(os.path.dirname(os.path.abspath(__file__)), "config", "proxychains-youtube.conf")
if os.path.isfile(conf):
return conf
return None
def _ffmpeg_is_static_binary(ffmpeg_bin: str) -> bool:
path = _ffmpeg_resolved_path(ffmpeg_bin)
if path in _FFMPEG_STATIC_CACHE:
return _FFMPEG_STATIC_CACHE[path]
if platform.system().lower() != "linux":
_FFMPEG_STATIC_CACHE[path] = False
return False
ldd = shutil.which("ldd")
if not ldd or not os.path.exists(path):
_FFMPEG_STATIC_CACHE[path] = False
return False
try:
r = subprocess.run([ldd, path], capture_output=True, text=True, timeout=5)
blob = ((r.stdout or "") + (r.stderr or "")).lower()
is_static = "not a dynamic executable" in blob or "statically linked" in blob
except Exception:
is_static = False
_FFMPEG_STATIC_CACHE[path] = is_static
return is_static
def _ffmpeg_protocols(ffmpeg_bin: str) -> str:
key = _ffmpeg_resolved_path(ffmpeg_bin)
if key in _FFMPEG_PROTOCOLS_CACHE:
return _FFMPEG_PROTOCOLS_CACHE[key]
try:
r = subprocess.run(
[ffmpeg_bin, "-hide_banner", "-protocols"],
capture_output=True,
text=True,
timeout=8,
)
blob = (r.stdout or "") + (r.stderr or "")
except Exception:
blob = ""
_FFMPEG_PROTOCOLS_CACHE[key] = blob
return blob
def _ffmpeg_supports_youtube_output(ffmpeg_bin: str) -> bool:
protocols = _ffmpeg_protocols(ffmpeg_bin)
return "rtmp" in protocols and "rtmps" in protocols
def _candidate_ffmpeg_binaries(preferred: str = "ffmpeg") -> list[str]:
raw = [
os.environ.get("YOUTUBE_PUSH_FFMPEG"),
os.environ.get("LIVE_YOUTUBE_PUSH_FFMPEG"),
os.environ.get("FFMPEG_PROXYCHAINS_BIN"),
os.environ.get("LIVE_FFMPEG_BIN"),
os.environ.get("FFMPEG_BIN"),
preferred,
shutil.which(preferred or "ffmpeg"),
shutil.which("ffmpeg"),
"/usr/bin/ffmpeg",
"/bin/ffmpeg",
"/usr/local/bin/ffmpeg",
]
out: list[str] = []
seen: set[str] = set()
for item in raw:
value = (item or "").strip()
if not value:
continue
key = _ffmpeg_resolved_path(value)
if key in seen:
continue
seen.add(key)
out.append(value)
return out
def _resolve_youtube_push_ffmpeg(preferred: str, push_proxy: str, proxy_mode: str = "auto") -> tuple[str, str]:
base = (
os.environ.get("LIVE_FFMPEG_BIN")
or os.environ.get("FFMPEG_BIN")
or preferred
or "ffmpeg"
).strip()
if not _should_use_proxychains(push_proxy, proxy_mode):
return base, ""
if not _ffmpeg_is_static_binary(base):
return base, ""
base_path = _ffmpeg_resolved_path(base)
for candidate in _candidate_ffmpeg_binaries(base):
if _ffmpeg_resolved_path(candidate) == base_path:
continue
if not os.path.exists(_ffmpeg_resolved_path(candidate)):
continue
if _ffmpeg_is_static_binary(candidate):
continue
if not _ffmpeg_supports_youtube_output(candidate):
continue
return (
candidate,
f"proxychains4 cannot hook static ffmpeg ({base_path}); using dynamic ffmpeg {candidate}",
)
return (
base,
f"proxychains4 cannot hook static ffmpeg ({base_path}); no dynamic ffmpeg fallback found",
)
def _proxychains_command(ffmpeg_command: list[str], push_proxy: str, proxy_mode: str = "auto") -> list[str] | None:
if not _should_use_proxychains(push_proxy, proxy_mode):
return None
conf = _proxychains_config_for_push(push_proxy)
if not conf:
return None
return ["proxychains4", "-q", "-f", conf, *ffmpeg_command]
def _record_cleanup_url(real_url: str, record_url: str | None) -> str:
original = (record_url or "").strip()
return original or real_url
def start_douyin_youtube_ffplay(
title: str,
anchor_name: str,
real_url: str,
rec_info: str,
record_name: str,
recording: set,
recording_time_list: dict,
running_list: list,
clear_record_info,
color_obj,
config_file: str | None = None,
record_url: str | None = None,
fallback_urls: list[str] | None = None,
):
"""
抖音 → YouTube 推流主函数(单路推流)
只从 config/youtube.ini 读取一个 stream key(取第一个有效值)
"""
# ====================== 读取 YouTube 配置 ======================
config_file = _resolve_youtube_push_config_file(config_file)
_config_dir = os.path.dirname(os.path.abspath(config_file))
_script_dir = os.path.dirname(os.path.abspath(__file__))
rtmps_base = os.environ.get("YOUTUBE_RTMPS_BASE", "rtmps://a.rtmps.youtube.com/live2/")
rtmp_base = os.environ.get("YOUTUBE_RTMP_BASE", "rtmp://a.rtmp.youtube.com/live2/")
use_rtmps = True
# 720p 竖屏直播基线:H.264 CBR、30fps、2s 关键帧、AAC 128k/48kHz。
b_v, maxrate, bufsize = _youtube_bitrate_triplet(4000)
stream_key = None
push_proxy = ""
push_proxy_mode = ""
fast_audio = True # 默认使用轻量音频链,优先保证 YouTube ingest speed >= 1.00x
if os.path.exists(config_file):
config = configparser.ConfigParser()
config.read(config_file, encoding="utf-8-sig")
if config.has_section("youtube"):
for k, v in config.items("youtube"):
v = (v or "").strip()
if k == "rtmps" and v.lower() in ("0", "false", "否"):
use_rtmps = False
elif k in ("rtmps_base", "rtmps_url_base") and v:
rtmps_base = v
elif k in ("rtmp_base", "rtmp_url_base") and v:
rtmp_base = v
elif k in ("push_proxy", "youtube_push_proxy") and v:
push_proxy = v
elif k in ("push_proxy_mode", "youtube_push_proxy_mode") and v:
push_proxy_mode = v
elif k == "fast_audio":
fast_audio = v.lower() in ("1", "true", "yes", "是", "开", "on")
elif k == "bitrate" and v:
try:
b_v, maxrate, bufsize = _youtube_bitrate_triplet(int(v))
except ValueError:
pass
elif (k == "key" or k == "stream_key") and v and not v.startswith("#"):
stream_key = v
if stream_key:
if stream_key.startswith("rtmp://") or stream_key.startswith("rtmps://"):
youtube_rtmp = stream_key
else:
youtube_rtmp = (rtmps_base if use_rtmps else rtmp_base) + stream_key
if youtube_rtmp.startswith("rtmps://a.rtmp.youtube.com/"):
youtube_rtmp = youtube_rtmp.replace(
"rtmps://a.rtmp.youtube.com/",
"rtmps://a.rtmps.youtube.com/",
1,
)
print(f"[INFO] 从 {config_file} 读取 YouTube 推流地址")
else:
raise ValueError(f"请在 {config_file} 中配置 key=你的stream_key")
# ====================== 常量配置 ======================
push_proxy_mode = _normalize_push_proxy_mode(push_proxy_mode)
push_proxy = "" if push_proxy_mode == "off" else _resolve_youtube_push_proxy(push_proxy)
if push_proxy:
print(f"[INFO] YouTube push proxy ({push_proxy_mode}): {_redact_proxy_url(push_proxy)}")
ffmpeg_bin, ffmpeg_note = _resolve_youtube_push_ffmpeg("ffmpeg", push_proxy, push_proxy_mode)
if ffmpeg_note:
print(f"[WARN] {ffmpeg_note}")
if ffmpeg_bin != "ffmpeg":
print(f"[INFO] YouTube push ffmpeg: {ffmpeg_bin}")
if not _ffmpeg_supports_stats_period(ffmpeg_bin):
print(
f"[WARN] {_ffmpeg_display_name(ffmpeg_bin)} 不支持 -stats_period;"
"建议执行 scripts/linux/upgrade_ffmpeg_newer.sh 以获得稳定 speed 指标"
)
MAX_RETRY_DELAY = 90
INITIAL_RETRY_DELAY = 3
STDERR_QUEUE_TIMEOUT = 1.0
NO_FRAME_TIMEOUT = 120
START_CHECK_AFTER = 25
STALE_OUTPUT_SECONDS = 40
RECONNECT_DELAY_MAX = 10
FAST_SPEED_THRESHOLD = 1.08
FAST_SPEED_STRIKES_NEEDED = 3
INVALID_DROP_WINDOW_SECONDS = 30
INVALID_DROP_LIMIT = 80
# 明确结束 / 平台拒绝:停止整条转推(与瞬时网络错误区分)
TERMINAL_KEYWORDS = [
"live has ended",
"server returned 404",
"ingestion error",
"access denied",
"server returned 403",
]
# 瞬时错误:结束当前 ffmpeg 进程后由外层循环退避重连
TRANSIENT_KEYWORDS = [
"connection reset by peer",
"failed to write trailer",
"invalid data found",
"server returned 500",
"packet too short",
"no route to host",
"connection timed out",
"connection refused",
"error writing output",
"broken pipe",
"i/o error",
"client disconnected",
"error opening output file",
"error opening output files",
"error opening output",
]
douyin_headers = (
"User-Agent: Mozilla/5.0 (iPhone; CPU iPhone OS 18_1 like Mac OS X) AppleWebKit/605.1.15\r\n"
"Referer: https://live.douyin.com/\r\n"
"Origin: https://live.douyin.com\r\n"
)
# ====================== 标题处理 ======================
timestamp_str = time.strftime("%Y-%m-%d_%H-%M-%S", time.localtime())
clean_title = sanitize_title(title)
stream_title = sanitize_title(f"{anchor_name}{('_' + clean_title) if clean_title else ''}_{timestamp_str}")
print(f"[INFO] {rec_info} 开始推流到 YouTube: {stream_title}")
try:
from src.youtube_relay_log import on_relay_push_start
ini_text = ""
if os.path.exists(config_file):
with open(config_file, encoding="utf-8-sig") as ini_fp:
ini_text = ini_fp.read()
on_relay_push_start(
process=_live_pm2_name() or "youtube",
anchor_name=anchor_name,
record_url=record_url,
stream_title=stream_title,
real_url=real_url,
youtube_ini_text=ini_text,
)
except Exception as relay_log_exc:
print(f"[WARN] relay session log start skipped: {relay_log_exc}")
# ====================== 视频编码:hardware.env(ARM)→ NVENC → libx264 ======================
_hw_env = _load_simple_env_file(os.path.join(_config_dir, "hardware.env"))
codec_v = "libx264"
video_args = [
"-preset", "ultrafast", "-tune", "zerolatency", "-profile:v", "high", "-level", "4.0",
"-b:v", b_v, "-minrate", b_v, "-maxrate", maxrate, "-bufsize", bufsize,
]
video_rate_label = f"CBR {b_v}"
_want_enc = (_hw_env.get("LIVE_VIDEO_ENCODER") or "").strip()
_hw_enc_active = False
_encoders_blob = ""
_machine = platform.machine().lower()
_vaapi_device = ""
for _candidate in ("/dev/dri/renderD128", "/dev/dri/renderD129", "/dev/dri/renderD130"):
if os.path.exists(_candidate):
_vaapi_device = _candidate
break
def _ffmpeg_encoder_smoke_test(name: str) -> bool:
if not name:
return False
cmd = [
ffmpeg_bin, "-hide_banner", "-loglevel", "error",
"-f", "lavfi", "-i", "testsrc2=size=128x128:rate=1",
"-frames:v", "1", "-an",
]
if name == "h264_vaapi":
if not _vaapi_device:
return False
cmd = [
ffmpeg_bin, "-hide_banner", "-loglevel", "error",
"-vaapi_device", _vaapi_device,
"-f", "lavfi", "-i", "testsrc2=size=128x128:rate=1",
"-vf", "format=nv12,hwupload",
"-frames:v", "1", "-an",
]
cmd += ["-c:v", name, "-f", "null", "-"]
try:
probe = subprocess.run(
cmd,
capture_output=True,
text=True,
timeout=8,
)
except Exception as e:
print(f"[WARN] Encoder smoke test failed for {name}: {e}")
return False
if probe.returncode == 0:
return True
detail = ((probe.stderr or "") + (probe.stdout or "")).strip().splitlines()
suffix = f": {detail[-1][:180]}" if detail else ""
print(f"[WARN] Encoder smoke test rejected {name}{suffix}")
return False
if platform.system().lower() == "linux":
_cached_enc = get_cached_encoder(_machine, ffmpeg_bin, base_dir=_script_dir)
if _cached_enc:
codec_v = _cached_enc
if codec_v == "h264_vaapi" and _vaapi_device:
video_args, video_rate_label = _h264_vaapi_video_args(_hw_env)
elif codec_v == "h264_nvenc":
video_args = [
"-profile:v", "high", "-level", "4.0",
"-tune", "ll", "-rc", "cbr", "-b:v", b_v, "-minrate", b_v,
"-maxrate", maxrate, "-bufsize", bufsize,
]
elif codec_v != "libx264":
video_args = ["-b:v", b_v, "-minrate", b_v, "-maxrate", maxrate, "-bufsize", bufsize]
video_rate_label = f"CBR {b_v}"
_hw_enc_active = True
print(f"[INFO] 使用编码器缓存: {codec_v}")
if not _hw_enc_active:
try:
enc = subprocess.run(
[ffmpeg_bin, "-hide_banner", "-encoders"],
capture_output=True,
text=True,
timeout=6,
)
_encoders_blob = (enc.stdout or "") + (enc.stderr or "")
_probe_names: list[str] = []
for _name in ("h264_rkmpp", "h264_v4l2m2m", "h264_vaapi", _want_enc):
if _name and _name.startswith("h264_") and _name in _encoders_blob and _name not in _probe_names:
_probe_names.append(_name)
_usable_encoders = {
_name for _name in _probe_names
if _ffmpeg_encoder_smoke_test(_name)
}
_selected_enc, _enc_note = resolve_live_video_encoder(
_want_enc,
_encoders_blob,
_machine,
has_mpp_service=os.path.exists("/dev/mpp_service"),
has_render_node=bool(_vaapi_device),
has_v4l2_device=bool(glob.glob("/dev/video*")),
usable_encoders=_usable_encoders,
)
if _enc_note:
print(f"[WARN] {_enc_note}")
if _selected_enc:
codec_v = _selected_enc
video_args = ["-b:v", b_v, "-minrate", b_v, "-maxrate", maxrate, "-bufsize", bufsize]
video_rate_label = f"CBR {b_v}"
_hw_enc_active = True
print(f"[INFO] 使用 config/hardware.env LIVE_VIDEO_ENCODER={codec_v}(板载硬件编码)")
except Exception as e:
print(f"[WARN] LIVE_VIDEO_ENCODER 校验失败: {e}")
if not _hw_enc_active:
try:
if platform.system().lower() == "linux":
check = subprocess.run(["nvidia-smi"], capture_output=True, timeout=5)
if check.returncode == 0:
enc = subprocess.run(
[ffmpeg_bin, "-hide_banner", "-encoders"],
capture_output=True,
text=True,
timeout=5,
)
if "h264_nvenc" in (enc.stdout or ""):
codec_v = "h264_nvenc"
video_args = [
"-profile:v", "high", "-level", "4.0",
"-tune", "ll", "-rc", "cbr", "-b:v", b_v, "-minrate", b_v,
"-maxrate", maxrate, "-bufsize", bufsize,
]
video_rate_label = f"CBR {b_v}"
print("[INFO] 检测到 NVIDIA GPU → 使用 NVENC 硬件加速")
except Exception as e:
print(f"[WARN] NVENC 检测失败,回退软件编码: {e}")
store_cached_encoder(_machine, ffmpeg_bin, codec_v, base_dir=_script_dir)
_filter_threads = "4"
# ====================== 开源音频处理:背景音乐弱化 + 防版权 ======================
_ffmpeg_cwd = None
if fast_audio:
print("[INFO] fast_audio=开:使用轻量音频链")
_af_chain = "afftdn=nf=-26:tn=1,aresample=async=1:first_pts=0"
else:
# 优先 RNNoise(arnndn),无模型则用 afftdn;aphaser 相位扰动可干扰 Content ID 指纹
_arnndn_paths = [
os.path.join(_script_dir, "arnndn-models", "cb.rnnn"),
os.path.join(os.path.dirname(_script_dir), "arnndn-models", "cb.rnnn"),
"arnndn-models/cb.rnnn",
]
_arnndn_model = None
for _p in _arnndn_paths:
if os.path.isfile(_p):
_arnndn_model = os.path.normpath(_p)
break
if _arnndn_model and _ffmpeg_has_filter(ffmpeg_bin, "arnndn"):
print(f"[INFO] 使用 RNNoise 降噪模型: {_arnndn_model}")
_arnndn_base = os.path.dirname(os.path.dirname(os.path.abspath(_arnndn_model)))
_af_denoise = "arnndn=m=arnndn-models/cb.rnnn:mix=0.82,"
_ffmpeg_cwd = _arnndn_base
else:
if _arnndn_model:
print(f"[WARN] {_ffmpeg_display_name(ffmpeg_bin)} 不支持 arnndn,改用 afftdn")
print("[INFO] 未找到 arnndn 模型,使用 afftdn 降噪(可克隆 richardpl/arnndn-models 到 arnndn-models/)")
_af_denoise = "afftdn=nf=-26:tn=1,"
# 强化版:收紧带通 + 频率偏移 + 音高微调 + 多段 EQ + 相位扰动
_freq_shift = "afreqshift=shift=22," if _ffmpeg_has_filter(ffmpeg_bin, "afreqshift") else ""
if not _freq_shift:
print(f"[WARN] {_ffmpeg_display_name(ffmpeg_bin)} 不支持 afreqshift,跳过频率偏移滤镜")
_af_chain = (
_af_denoise
+ "highpass=f=200,lowpass=f=3800,"
+ "equalizer=f=150:width_type=o:width=2.5:g=-14,"
+ "equalizer=f=350:width_type=o:width=2:g=-10,"
+ "equalizer=f=600:width_type=o:width=1.8:g=-8,"
+ "equalizer=f=1000:width_type=o:width=1.5:g=-6,"
+ "equalizer=f=2500:width_type=o:width=1.2:g=-4,"
+ "acompressor=threshold=-26dB:ratio=5:attack=8:release=80:makeup=5,"
+ _freq_shift
+ "asetrate=48000*1.035,aresample=48000,"
+ "aphaser=type=t:decay=0.4:delay=3:speed=0.7,"
+ "volume=1.12,"
+ "aresample=async=1:first_pts=0"
)
_video_mid = ["-vsync", "cfr", "-g", "60", "-keyint_min", "60", "-r", "30",
"-bf", "0", "-sc_threshold", "0"]
if codec_v == "libx264":
_video_mid += ["-x264-params", "force-cfr=1:scenecut=0:open_gop=0:sync-lookahead=0:keyint=60:min-keyint=60:nal-hrd=cbr"]
# -re:按源时间戳节奏拉流,避免突发过快;不用 realtime/arealtime(输入抖动时易让 YouTube 判为数据不足)
_vf_pad = (
"fps=30,scale=720:1280:force_original_aspect_ratio=decrease:flags=bilinear,"
"pad=720:1280:(ow-iw)/2:(oh-ih)/2:black"
)
_ffmpeg_pre_input = []
_pix_fmt = "yuv420p"
if codec_v == "h264_vaapi":
if _vaapi_device:
_ffmpeg_pre_input = ["-vaapi_device", _vaapi_device]
_vf_pad = f"{_vf_pad},format=nv12,hwupload"
_pix_fmt = "vaapi"
video_args, video_rate_label = _h264_vaapi_video_args(_hw_env)
print(f"[INFO] 使用 VAAPI 设备: {_vaapi_device}")
else:
print("[WARN] h264_vaapi 缺少 /dev/dri/renderD*,回退到 libx264")
codec_v = "libx264"
video_args = [
"-preset", "ultrafast", "-tune", "zerolatency", "-profile:v", "high", "-level", "4.0",
"-b:v", b_v, "-minrate", b_v, "-maxrate", maxrate, "-bufsize", bufsize,
]
video_rate_label = f"CBR {b_v}"
_hw_enc_active = False
_relay_pm2 = _live_pm2_name() or "youtube"
_stats_args = _ffmpeg_stats_args(ffmpeg_bin)
source_candidates: list[str] = []
_seen_source: set[str] = set()
for item in [real_url, *(fallback_urls or [])]:
u = (item or "").strip()
if not u or u in _seen_source:
continue
if not _is_probable_stream_input(u):
print(f"[WARN] 跳过非直链输入: {u[:120]}")
continue
_seen_source.add(u)
source_candidates.append(u)
if not source_candidates:
source_candidates = [real_url]
source_index = 0
def _emit_relay_heartbeat(state: str, **extra: object) -> None:
write_relay_heartbeat(
_relay_pm2,
{
"state": state,
"stream_title": stream_title,
"source_url": source_candidates[source_index],
"codec": codec_v,
"record_name": record_name,
**extra,
},
base_dir=_script_dir,
)
def _build_ffmpeg_command(input_url: str) -> list[str]:
input_path = os.path.normpath(os.path.expanduser(input_url))
input_is_file = os.path.isfile(input_path)
if input_is_file:
return [
ffmpeg_bin, "-y", "-loglevel", "info", "-nostdin",
*_stats_args,
"-fflags", "+genpts+discardcorrupt",
"-err_detect", "ignore_err",
"-thread_queue_size", "2048",
"-filter_threads", _filter_threads,
*_ffmpeg_pre_input,
"-re",
"-i", input_path,
"-vf", _vf_pad,
"-c:v", codec_v,
*video_args,
*_video_mid,
"-pix_fmt", _pix_fmt,
"-c:a", "aac", "-b:a", "128k", "-ar", "48000", "-ac", "2",
"-af", _af_chain,
"-flags", "+global_header",
"-flvflags", "no_duration_filesize",
"-f", "flv", youtube_rtmp,
]
return [
ffmpeg_bin, "-y", "-loglevel", "info", "-nostdin",
*_stats_args,
"-rw_timeout", "50000000",
"-reconnect", "1", "-reconnect_at_eof", "1", "-reconnect_streamed", "1",
"-reconnect_delay_max", str(RECONNECT_DELAY_MAX),
"-fflags", "+genpts+discardcorrupt",
"-err_detect", "ignore_err",
"-max_delay", "500000",
"-thread_queue_size", "2048",
"-filter_threads", _filter_threads,
*_ffmpeg_pre_input,
"-headers", douyin_headers,
"-re",
"-i", input_url,
"-vf", _vf_pad,
"-c:v", codec_v,
*video_args,
*_video_mid,
"-pix_fmt", _pix_fmt,
"-c:a", "aac", "-b:a", "128k", "-ar", "48000", "-ac", "2",
"-af", _af_chain,
"-flags", "+global_header",
"-flvflags", "no_duration_filesize",
"-f", "flv", youtube_rtmp,
]
print(
"[INFO] YouTube Live profile: "
f"{'RTMPS' if youtube_rtmp.startswith('rtmps://') else 'RTMP'} | "
f"H.264 {codec_v} {video_rate_label} | 720x1280@30 | keyint=2s | AAC 128k/48kHz | real-time input pacing"
)
ffmpeg_command = _build_ffmpeg_command(source_candidates[source_index])
_emit_relay_heartbeat("starting")
proc = None
stderr_q = None
reader_t = None
retry_delay = 0
try:
while True:
try:
if retry_delay > 0:
print(f"[WARN] 防风控等待 {retry_delay}s 后重新连接抖音源...")
time.sleep(retry_delay)
cleanup_proc(proc)
stderr_q = queue.Queue()
print(f"[INFO][{datetime.datetime.now():%H:%M:%S}] 启动 YouTube 推流 → {stream_title}")
_popen_kw = dict(
stdin=subprocess.DEVNULL,
stdout=subprocess.DEVNULL,
stderr=subprocess.PIPE,
text=True,
bufsize=1,
universal_newlines=True,
)
if _ffmpeg_cwd:
_popen_kw["cwd"] = _ffmpeg_cwd
ffmpeg_exec = _proxychains_command(ffmpeg_command, push_proxy, push_proxy_mode)
_uses_proxychains = ffmpeg_exec is not None
if ffmpeg_exec is None:
ffmpeg_exec = ffmpeg_command
_popen_kw["env"] = _ffmpeg_env_with_push_proxy(
push_proxy,
push_proxy_mode,
use_proxychains=_uses_proxychains,
)
proc = subprocess.Popen(ffmpeg_exec, **_popen_kw)
proc.last_out_ts = time.time()
reader_t = threading.Thread(target=_stderr_reader_thread, args=(proc, stderr_q))
reader_t.daemon = True
reader_t.start()
start_time = last_frame_time = time.time()
last_progress_frame = -1
last_progress_time = -1.0
last_ffmpeg_log_time = 0.0
fast_speed_strikes = 0
invalid_drop_window_start = time.time()
invalid_drop_count = 0
while True:
try:
try:
line = stderr_q.get(timeout=STDERR_QUEUE_TIMEOUT)
except queue.Empty:
if time.time() - getattr(proc, "last_out_ts", time.time()) > STALE_OUTPUT_SECONDS:
print("[WARN] 长时间无任何日志,交回监控循环重新获取直播源")
cleanup_proc(proc)
raise SourceStalled()
continue
if line is None:
if proc.poll() is not None:
break
continue
line = re.sub(r"[\r\n]+", " ", line).strip()
if line.startswith("__ERR__READER__"):
print(f"[ERROR] stderr reader 异常: {line}")
continue
if line:
now_ts = time.time()
proc.last_out_ts = now_ts
line_lower = line.lower()
is_progress_line = "frame=" in line_lower and ("time=" in line_lower or "speed=" in line_lower)
if not is_progress_line or now_ts - last_ffmpeg_log_time >= 15:
print(f"[FFmpeg] {line}")
if is_progress_line:
last_ffmpeg_log_time = now_ts
if any(kw in line_lower for kw in TERMINAL_KEYWORDS) or _looks_like_youtube_output_rejected(line_lower):
print("[ERROR] 判定直播结束或平台明确拒绝,停止推流")
cleanup_proc(proc)
raise StreamEnded()
if any(kw in line_lower for kw in TRANSIENT_KEYWORDS):
print(f"[WARN] 瞬时错误,将退避重试: {line[:160]}")
cleanup_proc(proc)
retry_delay = min(max(retry_delay, INITIAL_RETRY_DELAY) * 2, MAX_RETRY_DELAY)
break
if _looks_like_invalid_ts_drop(line_lower):
if now_ts - invalid_drop_window_start > INVALID_DROP_WINDOW_SECONDS:
invalid_drop_window_start = now_ts
invalid_drop_count = 0
invalid_drop_count += 1
if invalid_drop_count >= INVALID_DROP_LIMIT:
print("[WARN] 源流时间戳异常过多,重启 FFmpeg(保留 -re 参数)")
cleanup_proc(proc)
raise SourceStalled()
if is_progress_line:
speed = _ffmpeg_speed_value(line_lower)
frame, media_time = _ffmpeg_progress_values(line_lower)
_emit_relay_heartbeat(
"streaming",
frame=frame,
media_time=media_time,
speed=speed,
)
if speed is not None and time.time() - start_time > START_CHECK_AFTER:
if speed > FAST_SPEED_THRESHOLD:
fast_speed_strikes += 1
if fast_speed_strikes >= FAST_SPEED_STRIKES_NEEDED:
print(
f"[WARN] 推流 speed={speed:.2f}x 异常,"
"重启 FFmpeg(保留 -re 参数)"
)
cleanup_proc(proc)
raise SourceStalled()
else:
fast_speed_strikes = 0
frame, media_time = _ffmpeg_progress_values(line_lower)
if frame is not None or media_time is not None:
frame_advanced = frame is not None and frame > last_progress_frame
time_advanced = media_time is not None and media_time > last_progress_time + 0.01
if frame_advanced or time_advanced:
last_frame_time = time.time()
retry_delay = 0
if frame is not None:
last_progress_frame = frame
if media_time is not None:
last_progress_time = media_time
if time.time() - start_time > START_CHECK_AFTER:
if time.time() - last_frame_time > NO_FRAME_TIMEOUT:
print(f"[WARN] 连续 {NO_FRAME_TIMEOUT}s 无新帧,交回监控循环重新获取直播源")
cleanup_proc(proc)
raise SourceStalled()
except (StreamEnded, SourceStalled):
raise
except Exception as e:
print(f"[ERROR] 内层异常: {e}")
traceback.print_exc()
cleanup_proc(proc)
retry_delay = min(retry_delay * 2, MAX_RETRY_DELAY)
break
continue
except StreamEnded:
print(f"[INFO] 主播已下播,停止 YouTube 转推 → {record_name}")
break
except SourceStalled:
if source_index + 1 < len(source_candidates):
source_index += 1
ffmpeg_command = _build_ffmpeg_command(source_candidates[source_index])
print(
f"[WARN] 切换备用源 URL ({source_index + 1}/{len(source_candidates)}): "
f"{source_candidates[source_index][:120]}"
)
_emit_relay_heartbeat("source_failover", source_index=source_index)
retry_delay = INITIAL_RETRY_DELAY
continue
print(f"[WARN] 当前直播源无进度,返回监控循环刷新源地址 → {record_name}")
break
except Exception as e:
print(f"[ERROR] 外层异常: {e}")
traceback.print_exc()
retry_delay = min(retry_delay * 2, MAX_RETRY_DELAY)
continue
except Exception as e:
print(f"[FATAL] YouTube 推流最外层异常: {e}")
traceback.print_exc()
finally:
cleanup_proc(proc)
clear_relay_heartbeat(_relay_pm2, base_dir=_script_dir)
try:
from src.youtube_relay_log import on_relay_push_end
on_relay_push_end(_relay_pm2, anchor_name=anchor_name, reason="push_stopped")
except Exception as relay_log_exc:
print(f"[WARN] relay session log end skipped: {relay_log_exc}")
try:
recording_time_list.pop(record_name, None)
# 统一由 clear_record_info 维护 running_list / monitoring / url_comments
clear_record_info(record_name, _record_cleanup_url(real_url, record_url))
except Exception:
pass
color_obj.print_colored(f"[{record_name}] YouTube 推流已彻底停止并清理完毕\n", color_obj.GREEN)
if __name__ == "__main__":
# 兼容旧 PM2/脚本名:实际业务入口为 youtube.py(监控 URL_config + 调用本模块推流)
import runpy
from pathlib import Path
_root = Path(__file__).resolve().parent
runpy.run_path(str(_root / "youtube.py"), run_name="__main__")