douyinWEB/backend/app/youtube_relay_pipeline.py
eric c1f3bd3c57 Fix exclusive sticky when Douyin probe says offline (status=4).
Co-authored-by: Cursor <cursoragent@cursor.com>
2026-09-14 06:03:46 -05:00

2001 lines
94 KiB
Python
Raw 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.

# -*- coding: utf-8 -*-
"""Background worker: Douyin live → YouTube RTMPS relay per assign group."""
from __future__ import annotations
import asyncio
import os
import signal
import time
from typing import Any
from . import db
from . import yt_assign_db
from . import youtube_relay_db
from .douyin import check_room
from .shorts_clip import resolve_stream_candidates
from . import youtube_relay_sessions as relay_sessions
from .youtube_relay import RelayPushSession, RelayStats, build_youtube_rtmp_url
from .youtube_relay_presets import list_relay_quality_presets, resolve_relay_encoding
from .youtube_relay_status import log_age_seconds, summarize_relay_group, _key_suffix
def _ffmpeg_pid_alive(pid: int) -> bool:
"""True if OS still has this pid (orphan FFmpeg after API restart)."""
p = int(pid or 0)
if p <= 0:
return False
try:
os.kill(p, 0)
return True
except OSError:
return False
def _live_room_ids() -> set[str]:
rows = db.list_live_douyin_rooms_for_shorts(limit=500)
return {str(r.get("room_id") or "").strip() for r in rows if r.get("room_id")}
def _douyin_live_count_cached() -> int:
try:
from . import douyin_live
return int(douyin_live.build_live_map().get("live_count") or 0)
except Exception:
try:
return len(_live_room_ids())
except Exception:
return 0
def _time_slot_mode(cfg: dict[str, Any] | None = None) -> bool:
cfg = cfg or db.get_settings_map()
return bool(cfg.get("youtube_relay_time_slot_mode"))
def _group_uses_time_slot(group: dict[str, Any]) -> bool:
"""Per-group category: time_slot → schedule/live sources; normal → manual/featured."""
return yt_assign_db.group_is_time_slot(group)
def _group_in_active_slot(group_id: str, *, keyed_only: bool = False) -> bool:
"""True when this group should push under current schedule (or timeslot test override)."""
gid = str(group_id or "").strip()
if not gid:
return False
cfg = db.get_settings_map()
if bool(cfg.get("youtube_relay_timeslot_test")):
want = str(cfg.get("youtube_relay_timeslot_test_group_id") or "").strip()
if not want:
return False
if gid == want:
return True
try:
g = yt_assign_db.get_group(gid)
w = yt_assign_db.get_group(want)
if g and w and yt_assign_db.same_yt_channel(g, w):
return True
except Exception:
pass
return False
return yt_assign_db.group_in_rotation_slot(group_id, keyed_only=keyed_only)
def _timeslot_test_channels() -> list[dict[str, Any]]:
sched = yt_assign_db.build_rotation_schedule(include_urls=False, keyed_only=True)
return [c for c in (sched.get("channels") or []) if str(c.get("group_id") or "").strip()]
def _pick_default_timeslot_test_group_id(channels: list[dict[str, Any]] | None = None) -> str:
rows = channels if channels is not None else _timeslot_test_channels()
if not rows:
return ""
active = next((c for c in rows if c.get("active")), None)
pick = active or rows[0]
return str(pick.get("group_id") or "").strip()
def _group_has_stream_key(group: dict[str, Any]) -> bool:
return bool(str(group.get("stream_key") or "").strip() or group.get("has_stream_key"))
def _normal_auto_candidates(groups: list[dict[str, Any]]) -> list[dict[str, Any]]:
"""Enabled non-time_slot groups with a live KEY (auto when 时间段排班 off)."""
out: list[dict[str, Any]] = []
for g in groups:
if not g.get("enabled"):
continue
if _group_uses_time_slot(g):
continue
if not _group_has_stream_key(g):
continue
out.append(g)
return out
def _claim_first_live_normal(
groups: list[dict[str, Any]],
*,
exclude_room_ids: set[str] | frozenset[str] | None = None,
) -> tuple[str, dict[str, Any], dict[str, str]] | None:
"""Exclusive normal mode: claim the first group whose 直播地址列表 has a live room.
Deterministic order: sort_order, then group id. Sticky winner is handled by caller.
"""
live_ids = _live_room_ids()
exclude = {str(x).strip() for x in (exclude_room_ids or ()) if str(x or "").strip()}
ranked: list[tuple[int, str, dict[str, Any], dict[str, str]]] = []
for g in groups:
src = pick_source_for_group(g, respect_schedule=False, exclude_room_ids=exclude)
if not src:
continue
rid = str(src.get("room_id") or "").strip()
if not rid or rid not in live_ids or rid in exclude:
continue
ranked.append((int(g.get("sort_order") or 0), str(g.get("id") or ""), g, src))
if not ranked:
return None
ranked.sort(key=lambda x: (x[0], x[1]))
_ord, gid, g, src = ranked[0]
return gid, g, src
def pick_source_for_group(
group: dict[str, Any],
*,
respect_schedule: bool = True,
time_slot_mode: bool | None = None,
prefer_room_id: str = "",
prefer_source_url: str = "",
exclude_room_ids: set[str] | frozenset[str] | None = None,
) -> dict[str, str] | None:
"""Choose Douyin source.
- 时间段分类: only when group is in active 24/N slot; source = currently-live monitor rooms.
- 普通分类: 直播地址列表 / featured (prefer live), optionally gated by schedule.
``time_slot_mode`` kept for API compatibility; per-group ``category`` is authoritative.
``exclude_room_ids`` skips rooms already probed offline this tick (time_slot sticky-lag).
"""
gid = str(group.get("id") or "")
if not gid or not group.get("enabled"):
return None
slot_mode = _group_uses_time_slot(group)
_ = time_slot_mode # call-site compat; category is authoritative
exclude = {str(x).strip() for x in (exclude_room_ids or ()) if str(x or "").strip()}
if slot_mode:
if respect_schedule and not _group_in_active_slot(gid, keyed_only=True):
return None
rooms = db.list_live_douyin_rooms_for_shorts(limit=40)
prefer_rid = str(prefer_room_id or "").strip()
_ = str(prefer_source_url or "").strip() # kept for call-site compat; rid is authoritative
try:
manual_block = yt_assign_db.timeslot_exclude_room_ids(include_manual_featured=True)
except Exception:
manual_block = set()
exclude = set(exclude) | set(manual_block)
def _row_to_src(row: dict[str, Any]) -> dict[str, str]:
url = str(row.get("url") or "").strip()
rid = str(row.get("room_id") or "").strip()
return {
"source_url": url,
"room_id": rid,
"anchor_name": str(row.get("last_anchor") or row.get("last_title") or rid).strip(),
}
# Sticky prefer only while that room is still in the live list AND not excluded
# (exclude = probe just said offline — monitor list can lag behind Douyin status=4).
if prefer_rid and prefer_rid not in exclude:
for row in rooms:
if str(row.get("room_id") or "").strip() == prefer_rid:
return _row_to_src(row)
# Slot mode: never reuse stale featured URL when monitor says offline.
# FFmpeg keep-alive on probe flake is handled in _ensure_group_relay_locked.
for row in rooms:
url = str(row.get("url") or "").strip()
rid = str(row.get("room_id") or "").strip()
if not url or not rid or rid in exclude:
continue
return _row_to_src(row)
return None
if respect_schedule:
if not _group_in_active_slot(gid, keyed_only=False):
return None
live_ids = _live_room_ids()
candidates: list[dict[str, Any]] = []
for idx, item in enumerate(group.get("featured") or []):
if item.get("blacklisted"):
continue
url = str(item.get("url") or "").strip()
if not url:
continue
rid = str(item.get("room_id") or "").strip()
if rid and rid in exclude:
continue
live = rid in live_ids if rid else False
candidates.append(
{
"url": url,
"room_id": rid,
"title": str(item.get("title") or item.get("pool_note") or "").strip(),
"live": live,
"idx": idx,
}
)
# Auto-relay must not glue onto offline featured rows (monitor lag / status=4).
# Prefer live; if none live → None so exclusive can rotate to another group.
candidates.sort(key=lambda x: (0 if x["live"] else 1, x["idx"]))
for c in candidates:
if not c["live"]:
break
return {
"source_url": c["url"],
"room_id": c["room_id"],
"anchor_name": c["title"],
}
return None
class YoutubeRelayPipeline:
def __init__(self) -> None:
self._task: asyncio.Task | None = None
self._stop = asyncio.Event()
self._sessions: dict[str, RelayPushSession] = {}
# Manual Start holds the lane even outside schedule until Stop / auto window reclaim.
self._manual_hold: set[str] = set()
self._exclusive_winner: str | None = None
self._neko_paused_instances: set[int] = set()
# Serialize start/restart per group — prevents double FFmpeg on same stream key.
self._group_locks: dict[str, asyncio.Lock] = {}
# Consecutive Studio-not-on-air kills → cooldown (stops flap + daily stream burn).
self._studio_fail_times: dict[str, list[float]] = {}
self._studio_cooldown_until: dict[str, float] = {}
# Douyin probe said offline (status=4) while monitor may still list live — TTL exclude.
self._probe_offline_until: dict[str, float] = {}
self.last_error = ""
self.processed = 0
self._status_cache: dict[str, Any] | None = None
self._status_cache_at = 0.0
self._STATUS_CACHE_TTL_SEC = 5.0
def _studio_cooldown_active(self, gid: str) -> float:
until = float(self._studio_cooldown_until.get(gid) or 0)
if until <= time.time():
self._studio_cooldown_until.pop(gid, None)
return 0.0
return until
def _clear_studio_cooldown(self, gid: str) -> None:
self._studio_cooldown_until.pop(gid, None)
self._studio_fail_times.pop(gid, None)
def _probe_offline_room_ids(self) -> set[str]:
now = time.time()
alive = {rid: until for rid, until in self._probe_offline_until.items() if float(until) > now}
self._probe_offline_until = alive
return set(alive.keys())
def _mark_probe_offline(self, room_id: str, *, ttl_sec: float = 180.0) -> None:
rid = str(room_id or "").strip()
if not rid:
return
self._probe_offline_until[rid] = time.time() + max(30.0, float(ttl_sec))
def _note_studio_not_on_air(self, gid: str) -> tuple[bool, str]:
"""Record a Studio-not-on-air kill. Returns (tripped, message)."""
now = time.time()
window = 30 * 60.0
need = 3
cooldown = 6 * 3600.0
times = [t for t in self._studio_fail_times.get(gid, []) if now - t <= window]
times.append(now)
self._studio_fail_times[gid] = times
if len(times) < need:
return False, ""
self._studio_cooldown_until[gid] = now + cooldown
self._studio_fail_times[gid] = []
hrs = int(cooldown // 3600)
msg = (
f"Studio 连续 {need} 次推流后仍未 on_air(常见:YouTube daily stream limit / 待开播卡死),"
f"已熔断自动重试 {hrs} 小时,避免反复开停烧额度。手动「开始」可解除。"
)
return True, msg
def status(self) -> dict[str, Any]:
now = time.time()
cached = self._status_cache
if cached is not None and (now - self._status_cache_at) < self._STATUS_CACHE_TTL_SEC:
return cached
cfg = db.get_settings_map()
# featured_only: one DB pass with featured URLs (needed for url_count / misconfigured).
groups = yt_assign_db.list_groups(featured_only=True)
states = {str(s.get("group_id") or ""): s for s in youtube_relay_db.list_relay_states()}
relay_groups: list[dict[str, Any]] = []
pushing = 0
pipeline_enabled = bool(cfg.get("youtube_relay_enabled"))
# Batch Neko docker ps once per poll (read-only; no compose sync / no curl).
neko_by_id: dict[int, dict[str, Any]] = {}
try:
from . import youtube_neko
max_neko = max((int(g.get("neko_instance_id") or 0) for g in groups), default=0)
if max_neko > 0:
for inst in youtube_neko.list_instances(max_neko, check_http=False):
try:
neko_by_id[int(inst.get("id") or 0)] = inst
except (TypeError, ValueError):
continue
except Exception:
neko_by_id = {}
for g in groups:
gid = str(g.get("id") or "")
st = dict(states.get(gid) or {})
sess = self._sessions.get(gid)
running = bool(sess and sess.stats.running)
orphan_pid = int(st.get("ffmpeg_pid") or 0)
orphan_alive = (not running) and _ffmpeg_pid_alive(orphan_pid)
# After API restart, in-memory session is gone but FFmpeg may still push —
# treat pid-alive as running so UI stays 推流中 / 启动中 (not 监听中 flap).
effective_running = running or orphan_alive
recent_log = list(
sess.stats.recent_log if sess else youtube_relay_db._parse_recent_log(st.get("recent_log"))
)
# Keep enough for progress parsing; wire payload trims further below.
st["recent_log"] = recent_log[-80:]
monitor = summarize_relay_group(
group=g,
st=st,
session_running=effective_running,
pipeline_enabled=pipeline_enabled or gid in self._manual_hold,
log_age_seconds=log_age_seconds(st, now),
lane_armed=gid in self._manual_hold or pipeline_enabled,
time_slot_mode=_group_uses_time_slot(g),
)
receiving = bool(monitor.get("is_pushing"))
if monitor.get("is_pushing"):
pushing += 1
# Drop stale DB rows that claim pushing while FFmpeg is gone.
raw_st = str(st.get("status") or "").lower()
armed = gid in self._manual_hold or pipeline_enabled
if not receiving and not running and raw_st in {"pushing", "streaming", "starting"}:
if orphan_alive:
# Keep DB status; ensure path will reuse orphan instead of idle→start flap.
pass
else:
youtube_relay_db.upsert_relay_state(
gid,
status="idle",
ffmpeg_pid=0,
speed=0,
frame=0,
error="",
recent_log=st.get("recent_log") or [],
)
elif not receiving:
err = str(st.get("error") or "")
raw_st2 = str(st.get("status") or "").lower()
if (
err.startswith("非当前时段")
or err.startswith("时段外")
or raw_st2 == "outside_slot"
or "outside_slot" in str(
(st.get("recent_log") or [""])[-1] if isinstance(st.get("recent_log"), list) else ""
)
):
youtube_relay_db.upsert_relay_state(
gid,
status="outside_slot",
ffmpeg_pid=0,
error="",
recent_log=st.get("recent_log") or [],
)
elif not armed:
if err.startswith("同频道备用 KEY") or "outside_slot" in str(
(st.get("recent_log") or [""])[-1] if isinstance(st.get("recent_log"), list) else ""
):
youtube_relay_db.upsert_relay_state(
gid,
status="idle",
ffmpeg_pid=0,
error="",
recent_log=st.get("recent_log") or [],
)
neko_id = int(g.get("neko_instance_id") or 0)
raw_neko = neko_by_id.get(neko_id) if neko_id > 0 else None
prefer = str(g.get("neko_open_prefer") or "local").strip().lower()
remote_bound = bool(str(g.get("ops_neko_open_url") or "").strip())
neko_state: dict[str, Any] | None = {
"id": neko_id if neko_id > 0 else None,
"running": bool(raw_neko.get("running")) if isinstance(raw_neko, dict) else False,
"ready": bool(raw_neko.get("ready")) if isinstance(raw_neko, dict) else False,
"status": (raw_neko.get("status") if isinstance(raw_neko, dict) else None) or (
"remote" if prefer == "remote" and remote_bound else "stopped"
),
"studio_url": (
str(g.get("neko_open_url") or "")
or (raw_neko.get("studio_url") if isinstance(raw_neko, dict) else "")
or ""
),
"exists": bool(raw_neko.get("exists")) if isinstance(raw_neko, dict) else remote_bound,
"open_prefer": prefer,
"remote_bound": remote_bound,
"ops_neko_slot": int(g.get("ops_neko_slot") or 0),
}
try:
snap = youtube_neko.studio_snapshot_for_group(g, max_age_sec=120.0)
neko_state["studio"] = {
"live_page_open": bool(snap.get("live_page_open")),
"on_air": bool(snap.get("on_air")),
"live_status": snap.get("live_status") or "",
"health": snap.get("health") or "",
"viewer_count": snap.get("viewer_count"),
"like_count": snap.get("like_count"),
"total_views": snap.get("total_views"),
"live_duration": snap.get("live_duration") or "",
"live_duration_sec": snap.get("live_duration_sec"),
"stream_title": snap.get("stream_title") or "",
"url": snap.get("url") or "",
"received_at": snap.get("received_at") or 0,
"age_sec": snap.get("age_sec"),
"detect_source": snap.get("detect_source") or "",
"minute_reports": snap.get("minute_reports") or [],
"neko_ref": snap.get("neko_ref") or "",
"neko_kind": snap.get("neko_kind") or "",
"ui_source": snap.get("ui_source") or "",
}
except Exception:
neko_state["studio"] = None
# If neither local container nor remote bind, drop empty neko block.
if not neko_id and not remote_bound:
neko_state = None
# Trim log text for poll JSON (selected card still has enough to read).
rl = monitor.get("recent_log")
if isinstance(rl, str) and len(rl) > 3500:
monitor["recent_log"] = rl[-3500:]
elif isinstance(rl, list):
monitor["recent_log"] = rl[-40:]
re = monitor.get("recent_error")
if isinstance(re, str) and len(re) > 1200:
monitor["recent_error"] = re[-1200:]
row = {
"group_id": gid,
"name": g.get("name"),
"channel_pk": g.get("channel_pk"),
"enabled": bool(g.get("enabled")),
"status": (
"pushing"
if receiving
else (
(raw_st if raw_st in {"pushing", "streaming", "starting"} else "pushing")
if effective_running
else (
"idle"
if raw_st in {"pushing", "streaming", "starting"}
else str(st.get("status") or "idle")
)
)
),
"error": st.get("error") or "",
"manual_hold": gid in self._manual_hold,
"neko_instance_id": neko_id,
"neko_enabled": bool(g.get("neko_enabled")),
"neko": neko_state,
**monitor,
}
relay_groups.append(row)
# Light schedule — keyed-only when any 时间段 groups (or legacy global toggle).
schedule = yt_assign_db.build_rotation_schedule(
include_urls=False,
groups=groups,
keyed_only=None,
)
preset_id = str(cfg.get("youtube_relay_quality_preset") or "720p")
encoding = resolve_relay_encoding(cfg)
payload = {
"running": bool(self._task and not self._task.done()),
"enabled": pipeline_enabled,
"pushing_count": pushing,
"group_count": len(groups),
"enabled_groups": sum(1 for g in groups if g.get("enabled")),
"last_error": self.last_error,
"douyin_live_count": _douyin_live_count_cached(),
"process_backend": "cloud_pipeline",
"family": "youtube",
"light": True,
"settings": {
"youtube_relay_enabled": pipeline_enabled,
"youtube_relay_bitrate": int(cfg.get("youtube_relay_bitrate") or 2500),
"youtube_relay_use_rtmps": bool(cfg.get("youtube_relay_use_rtmps", True)),
"youtube_relay_respect_schedule": bool(cfg.get("youtube_relay_respect_schedule", True)),
"youtube_relay_quality_preset": preset_id,
"youtube_relay_encoding": {
"preset_id": encoding.get("preset_id"),
"width": encoding.get("width"),
"height": encoding.get("height"),
"fps": encoding.get("fps"),
"x264_preset": encoding.get("x264_preset"),
"bitrate_kbps": encoding.get("bitrate_kbps"),
"audio_bitrate_kbps": encoding.get("audio_bitrate_kbps"),
},
"youtube_relay_quality_presets": list_relay_quality_presets(active_id=preset_id),
"youtube_relay_exclusive_live": bool(cfg.get("youtube_relay_exclusive_live", True)),
"youtube_relay_time_slot_mode": bool(cfg.get("youtube_relay_time_slot_mode")),
"youtube_relay_timeslot_test": bool(cfg.get("youtube_relay_timeslot_test")),
"youtube_relay_timeslot_test_group_id": str(
cfg.get("youtube_relay_timeslot_test_group_id") or ""
).strip(),
"youtube_relay_timeslot_exclude_count": 0,
},
"groups": relay_groups,
"schedule": schedule,
"exclusive_winner_group_id": self._exclusive_winner,
"neko_paused_instances": sorted(self._neko_paused_instances),
"studio_live": None,
}
try:
if bool(cfg.get("youtube_relay_timeslot_test")):
payload["schedule"] = yt_assign_db.overlay_timeslot_test_schedule(
schedule,
test_on=True,
test_group_id=str(cfg.get("youtube_relay_timeslot_test_group_id") or ""),
)
except Exception:
pass
try:
payload["settings"]["youtube_relay_timeslot_exclude_count"] = len(
yt_assign_db.timeslot_exclude_room_ids(include_manual_featured=True)
)
except Exception:
pass
try:
from . import youtube_neko
winner_neko = 0
if self._exclusive_winner:
for g in groups:
if str(g.get("id") or "") == self._exclusive_winner:
winner_neko = int(g.get("neko_instance_id") or 0)
break
payload["studio_live"] = youtube_neko.youtube_live_confirmed(
max_age_sec=60.0, neko_id=winner_neko
)
except Exception:
payload["studio_live"] = {"ok": False, "live": False, "reason": "unavailable"}
self._status_cache = payload
self._status_cache_at = time.time()
return payload
async def start(self) -> None:
if self._task and not self._task.done():
return
self._stop.clear()
self._task = asyncio.create_task(self._loop(), name="youtube-relay-pipeline")
async def stop(self) -> None:
self._stop.set()
for sess in list(self._sessions.values()):
await asyncio.to_thread(sess.stop)
self._sessions.clear()
self._manual_hold.clear()
self._exclusive_winner = None
self._neko_paused_instances.clear()
if self._task:
try:
await asyncio.wait_for(self._task, timeout=8)
except Exception:
self._task.cancel()
self._task = None
async def start_group(self, group_id: str) -> dict[str, Any]:
"""Manual Start = arm monitor lane (sh2 Pro Start / start_record thread).
sh2 youtube.py: thread keeps polling forever; offline →「等待直播」+ continue;
only Stop / URL removed from active_monitor_urls exits. Never treat offline as fatal.
"""
gid = str(group_id or "").strip()
g = yt_assign_db.get_group(gid)
if not g:
raise ValueError("分配组不存在")
if not g.get("enabled"):
raise ValueError("该组已停用")
if not str(g.get("stream_key") or "").strip() and not g.get("has_stream_key"):
raise ValueError("请先配置 YouTube 直播 KEY")
# 时间段分类: sources come from currently-live monitor rooms (not 精选).
# 普通分类: still require 精选 list; manual Start ignores schedule.
group_slot = _group_uses_time_slot(g)
if not group_slot:
featured = [
x
for x in (g.get("featured") or [])
if str(x.get("url") or "").strip() and not x.get("blacklisted")
]
if not featured:
raise ValueError("直播地址列表(精选)为空,请先加入抖音房间")
# Ensure worker loop keeps polling this lane (even if auto relay is off).
# Exclusive FFmpeg/Neko lock applies only when push actually starts (see _ensure_group_relay).
await self.start()
self._manual_hold.add(gid)
self._clear_studio_cooldown(gid)
# 时间段: keep schedule gate so only the active slot winner pushes.
# 普通: manual Start ignores schedule window (force lane).
respect = True if group_slot else False
result = await self._ensure_group_relay(g, force=True, respect_schedule=respect)
# Fatal = missing key / empty source only. Offline/risk → waiting, hold stays.
if result.get("fatal"):
self._manual_hold.discard(gid)
raise ValueError(str(result.get("error") or "启动失败"))
return {"ok": True, "group_id": gid, "manual_hold": True, **result}
async def _halt_session(self, group_id: str, *, reason: str = "stopped") -> None:
"""Stop FFmpeg for a group without clearing manual_hold."""
gid = str(group_id or "").strip()
sess = self._sessions.pop(gid, None)
if sess:
await asyncio.to_thread(sess.stop)
youtube_relay_db.clear_relay_state(gid, status="stopped")
await asyncio.to_thread(relay_sessions.end_session, gid, reason=reason)
async def _graceful_retire_group(
self,
group: dict[str, Any] | None,
*,
reason: str,
stop_neko: bool = True,
was_pushing: bool | None = None,
) -> dict[str, Any]:
"""Stop FFmpeg → Studio End Stream (CDP / API) → optional Neko stop.
Avoid hard-killing Neko while YouTube still thinks the broadcast is LIVE.
"""
from . import youtube_neko
g = group or {}
gid = str(g.get("id") or "").strip()
neko_id = int(g.get("neko_instance_id") or 0)
channel_pk = str(g.get("channel_pk") or "").strip()
pushing = bool(was_pushing) if was_pushing is not None else (gid in self._sessions)
if gid:
await self._halt_session(gid, reason=reason)
end_res: dict[str, Any] = {"skipped": True}
neko_up = False
if neko_id > 0:
try:
neko_up = bool(
(await asyncio.to_thread(youtube_neko._container_state, neko_id, check_http=False)).get(
"running"
)
)
except Exception:
neko_up = False
# If Neko is still up and we are retiring the lane, try End Stream even when FFmpeg
# already died — Studio may still show LIVE + End Stream.
if neko_up and (pushing or stop_neko):
try:
end_res = await asyncio.to_thread(
youtube_neko.end_live_session,
neko_id,
channel_pk=channel_pk,
wait_encoder_lost_sec=12.0 if pushing else 4.0,
settle_sec=3.0,
)
except Exception as exc:
end_res = {"ok": False, "error": str(exc)[:200]}
if gid:
youtube_relay_db.upsert_relay_state(
gid,
status="ending",
error="",
recent_log=[
f"[relay] graceful_end reason={reason} ok={str(end_res.get('ok'))}"
],
)
stop_res: dict[str, Any] = {"skipped": True}
if stop_neko and neko_id > 0:
stop_res = await asyncio.to_thread(youtube_neko.stop_instance, neko_id)
return {"ok": True, "group_id": gid, "end": end_res, "neko_stop": stop_res}
async def stop_group(self, group_id: str) -> dict[str, Any]:
gid = str(group_id or "").strip()
was_exclusive = gid == self._exclusive_winner
self._manual_hold.discard(gid)
g = yt_assign_db.get_group(gid) or {"id": gid}
exclusive_on = bool(db.get_settings_map().get("youtube_relay_exclusive_live", True))
await self._graceful_retire_group(
g,
reason="stopped",
stop_neko=bool(was_exclusive and exclusive_on),
)
if was_exclusive:
await self._release_exclusive_live()
return {"ok": True, "group_id": gid}
async def restart_group(self, group_id: str) -> dict[str, Any]:
gid = str(group_id or "").strip()
await self.stop_group(gid)
return await self.start_group(gid)
async def apply_quality_preset(self, preset_id: str) -> dict[str, Any]:
from .youtube_relay_presets import RELAY_QUALITY_PRESETS
pid = str(preset_id or "").strip()
if pid not in RELAY_QUALITY_PRESETS:
raise ValueError(f"未知画质预设:{pid}")
db.update_settings_map({"youtube_relay_quality_preset": pid})
restarted: list[str] = []
for gid in list(self._sessions.keys()):
try:
if gid in self._manual_hold:
await self.restart_group(gid)
else:
g = yt_assign_db.get_group(gid)
await self._halt_session(gid, reason="quality_preset")
cfg = db.get_settings_map()
if g and g.get("enabled") and cfg.get("youtube_relay_enabled"):
src = pick_source_for_group(
g,
respect_schedule=bool(cfg.get("youtube_relay_respect_schedule", True)),
)
if src:
await self._ensure_group_relay(g, source=src, cfg=cfg)
restarted.append(gid)
except Exception:
continue
st = self.status()
return {"ok": True, "preset": pid, "restarted_groups": restarted, **st}
async def _loop(self) -> None:
"""sh2 outer monitor: forever poll armed lanes; offline never exits the lane."""
while not self._stop.is_set():
try:
# Heavy SQLite scans off the asyncio loop so /api/health stays responsive.
def _tick_inputs() -> tuple[dict[str, Any], list[dict[str, Any]]]:
return db.get_settings_map(), yt_assign_db.list_groups(include_urls=True)
cfg, groups = await asyncio.to_thread(_tick_inputs)
auto_on = bool(cfg.get("youtube_relay_enabled"))
by_id = {str(g.get("id") or ""): g for g in groups}
active_ids: set[str] = set()
# 1) Always poll manual-hold lanes (sh2: start_record keeps waiting).
for gid in list(self._manual_hold):
g = by_id.get(gid)
if not g or not g.get("enabled"):
self._manual_hold.discard(gid)
await self._halt_session(gid, reason="disabled")
continue
if not str(g.get("stream_key") or "").strip() and not g.get("has_stream_key"):
continue
active_ids.add(gid)
# Manual hold: 普通 ignore schedule; 时间段 still respects window.
hold_respect = True if _group_uses_time_slot(g) else False
await self._ensure_group_relay(
g, force=False, respect_schedule=hold_respect, cfg=cfg
)
# 2) Auto relay
# - 时间段排班 ON: 24/N for category=time_slot (源=监控在播抖音)
# - 时间段排班 OFF: all 普通 groups watch 直播地址列表; exclusive → first-live sticky
if auto_on:
from . import youtube_neko
time_slot_mode_on = bool(cfg.get("youtube_relay_time_slot_mode"))
exclusive_on = bool(cfg.get("youtube_relay_exclusive_live", True))
time_slot_groups = [g for g in groups if _group_uses_time_slot(g)]
run_slot_auto = bool(time_slot_mode_on and time_slot_groups)
if time_slot_mode_on and not time_slot_groups:
# 排班开但无可用「时间段」频道:禁止落入普通自动,避免与 UI 矛盾。
for g in _normal_auto_candidates(groups):
gid = str(g.get("id") or "")
if not gid or gid in self._manual_hold:
continue
if gid in self._sessions:
await self._halt_session(
gid, reason="timeslot_mode_no_slot_groups"
)
youtube_relay_db.upsert_relay_state(
gid,
status="idle",
error=(
"时间段排班已开,但没有可用的「时间段」分类频道"
"(需 KEY + 分类=时间段)"
),
recent_log=[
"[relay] time_slot_mode on but no time_slot groups"
],
)
elif run_slot_auto:
slot_winner_gid = ""
slot_winner_g: dict[str, Any] | None = None
test_on = bool(cfg.get("youtube_relay_timeslot_test"))
test_gid = str(cfg.get("youtube_relay_timeslot_test_group_id") or "").strip()
if test_on:
if test_gid and by_id.get(test_gid):
slot_winner_gid = test_gid
slot_winner_g = by_id.get(test_gid)
else:
fallback = _pick_default_timeslot_test_group_id()
if fallback and by_id.get(fallback):
slot_winner_gid = fallback
slot_winner_g = by_id.get(fallback)
if fallback != test_gid:
db.update_settings_map(
{"youtube_relay_timeslot_test_group_id": fallback}
)
else:
sched = yt_assign_db.build_rotation_schedule(
include_urls=False, keyed_only=True
)
active_ch = next(
(c for c in sched.get("channels") or [] if c.get("active")), None
)
if active_ch:
candidate_ids = [str(active_ch.get("group_id") or "")]
candidate_ids.extend(
str(x) for x in (active_ch.get("alias_group_ids") or []) if x
)
candidate_ids = [g for g in candidate_ids if g and by_id.get(g)]
for gid0 in candidate_ids:
sess = self._sessions.get(gid0)
if sess and sess.stats.running:
slot_winner_gid = gid0
slot_winner_g = by_id.get(gid0)
break
if not slot_winner_gid and candidate_ids:
slot_winner_gid = candidate_ids[0]
slot_winner_g = by_id.get(slot_winner_gid)
for g in groups:
gid = str(g.get("id") or "")
if not gid or not g.get("enabled"):
continue
if gid in active_ids:
continue
if not _group_has_stream_key(g):
continue
# 普通分类:时段排班开启时不走自动(仅手动 hold)
if not _group_uses_time_slot(g):
continue
if gid != slot_winner_gid:
same_channel_as_winner = bool(
slot_winner_g and yt_assign_db.same_yt_channel(g, slot_winner_g)
)
in_active_slot = _group_in_active_slot(gid, keyed_only=True)
if same_channel_as_winner and in_active_slot:
await self._graceful_retire_group(
g,
reason="duplicate_channel_key",
stop_neko=exclusive_on,
)
youtube_relay_db.upsert_relay_state(
gid,
status="paused_exclusive",
error=f"同频道备用 KEY:当前由 {slot_winner_g.get('name') if slot_winner_g else slot_winner_gid} 推流",
recent_log=["[relay] duplicate_yt_channel — paused"],
)
continue
if not in_active_slot:
await self._graceful_retire_group(
g,
reason="outside_slot",
stop_neko=exclusive_on,
)
youtube_relay_db.upsert_relay_state(
gid,
status="outside_slot",
error="",
recent_log=["[relay] outside_slot — waiting schedule window"],
)
continue
continue
cool_until = self._studio_cooldown_active(gid)
if cool_until > 0:
left = int(max(0, cool_until - time.time()))
youtube_relay_db.upsert_relay_state(
gid,
status="paused_studio",
error=(
f"Studio 未 on_air 熔断中(约剩 {left // 60} 分)。"
f"常见原因:YouTube daily stream limit。手动「开始」可解除。"
),
recent_log=["[relay] studio_cooldown — skip auto"],
)
continue
src = pick_source_for_group(
g,
respect_schedule=True,
prefer_room_id=str(
(youtube_relay_db.get_relay_state(gid) or {}).get("source_room_id")
or ""
),
prefer_source_url=str(
(youtube_relay_db.get_relay_state(gid) or {}).get("source_url") or ""
),
)
if not src:
sess = self._sessions.get(gid)
if sess and sess.stats.running:
active_ids.add(gid)
continue
if gid in self._sessions and gid not in self._manual_hold:
await self._halt_session(gid, reason="no_live_source")
youtube_relay_db.upsert_relay_state(
gid,
status="waiting",
error="时间段模式:等待在播抖音源",
recent_log=["[relay] waiting live Douyin source"],
)
if slot_winner_g and gid == slot_winner_gid:
await self._enforce_exclusive_live(gid, slot_winner_g)
continue
active_ids.add(gid)
await self._ensure_group_relay(
g, source=src, cfg=cfg, respect_schedule=True
)
else:
# 时间段排班关闭:普通频道自动监听直播地址列表
# Stop leftover time_slot auto sessions (manual hold kept).
for g in time_slot_groups:
gid = str(g.get("id") or "")
if not gid or gid in self._manual_hold:
continue
if gid in self._sessions:
await self._halt_session(gid, reason="timeslot_mode_off")
normal_groups = _normal_auto_candidates(groups)
winner_gid = ""
winner_g: dict[str, Any] | None = None
winner_src: dict[str, str] | None = None
if exclusive_on:
cur = str(self._exclusive_winner or "").strip()
cur_g = by_id.get(cur) if cur else None
probe_exclude = self._probe_offline_room_ids()
if (
cur_g
and cur_g.get("enabled")
and not _group_uses_time_slot(cur_g)
and _group_has_stream_key(cur_g)
):
sticky_src = pick_source_for_group(
cur_g,
respect_schedule=False,
exclude_room_ids=probe_exclude,
)
live_ids = _live_room_ids()
sticky_rid = str((sticky_src or {}).get("room_id") or "").strip()
sticky_live = bool(
sticky_src
and sticky_rid
and sticky_rid in live_ids
and sticky_rid not in probe_exclude
)
sess = self._sessions.get(cur)
still_pushing = bool(sess and sess.stats.running)
if sticky_live or still_pushing or cur in self._manual_hold:
winner_gid = cur
winner_g = cur_g
winner_src = sticky_src if sticky_live else None
else:
# 真正停播:无在播源且未在推 → 进入下一轮
self._exclusive_winner = None
await self._release_exclusive_live()
if not winner_gid:
claimed = _claim_first_live_normal(
normal_groups, exclude_room_ids=probe_exclude
)
if claimed:
winner_gid, winner_g, winner_src = claimed
for g in normal_groups:
gid = str(g.get("id") or "")
if not gid or gid in active_ids:
continue
if exclusive_on and winner_gid and gid != winner_gid:
await self._graceful_retire_group(
g, reason="exclusive_live", stop_neko=True
)
youtube_relay_db.upsert_relay_state(
gid,
status="paused_exclusive",
error=(
f"单路独占:当前仅允许 "
f"{(winner_g or {}).get('name') or winner_gid} 推流"
),
recent_log=[
f"[relay] exclusive_live winner={winner_gid} — paused"
],
)
continue
if exclusive_on and not winner_gid:
youtube_relay_db.upsert_relay_state(
gid,
status="waiting",
error="自动推流:等待直播地址列表中的房间开播",
recent_log=["[relay] waiting featured live (exclusive)"],
)
continue
cool_until = self._studio_cooldown_active(gid)
if cool_until > 0:
left = int(max(0, cool_until - time.time()))
youtube_relay_db.upsert_relay_state(
gid,
status="paused_studio",
error=(
f"Studio 未 on_air 熔断中(约剩 {left // 60} 分)。"
f"常见原因:YouTube daily stream limit。手动「开始」可解除。"
),
recent_log=["[relay] studio_cooldown — skip auto"],
)
continue
# Exclusive sticky: keep running FFmpeg while source flaps offline briefly.
if exclusive_on and gid == winner_gid and not winner_src:
sess = self._sessions.get(gid)
if sess and sess.stats.running:
active_ids.add(gid)
continue
src = (
winner_src
if exclusive_on and gid == winner_gid and winner_src
else pick_source_for_group(
g,
respect_schedule=False,
prefer_room_id=str(
(youtube_relay_db.get_relay_state(gid) or {}).get(
"source_room_id"
)
or ""
),
prefer_source_url=str(
(youtube_relay_db.get_relay_state(gid) or {}).get(
"source_url"
)
or ""
),
)
)
if src:
live_ids = _live_room_ids()
rid = str(src.get("room_id") or "").strip()
if not rid or rid not in live_ids:
src = None
if not src:
sess = self._sessions.get(gid)
if sess and sess.stats.running:
active_ids.add(gid)
continue
if gid in self._sessions and gid not in self._manual_hold:
await self._halt_session(gid, reason="no_live_source")
youtube_relay_db.upsert_relay_state(
gid,
status="waiting",
error="自动推流:等待直播地址列表中的房间开播",
recent_log=["[relay] waiting featured live"],
)
if exclusive_on and winner_g and gid == winner_gid:
await self._enforce_exclusive_live(gid, winner_g)
continue
active_ids.add(gid)
await self._ensure_group_relay(
g, source=src, cfg=cfg, respect_schedule=False
)
else:
# Auto off: stop non-manual ffmpeg sessions only.
for gid in list(self._sessions.keys()):
if gid not in self._manual_hold:
await self._halt_session(gid, reason="auto_off")
for gid in list(self._sessions.keys()):
if gid not in active_ids and gid not in self._manual_hold:
await self._halt_session(gid, reason="inactive")
await self._tick_stats()
except Exception as exc:
self.last_error = str(exc)[:240]
await asyncio.sleep(7.0)
async def _stop_all_sessions(self) -> None:
for gid in list(self._sessions.keys()):
await self.stop_group(gid)
async def set_exclusive_live(self, enabled: bool) -> dict[str, Any]:
"""Toggle hard exclusive (one FFmpeg + stop sibling Nekos). Independent of time-slot schedule."""
db.update_settings_map({"youtube_relay_exclusive_live": bool(enabled)})
if not enabled and (self._exclusive_winner or self._neko_paused_instances):
await self._release_exclusive_live()
return await asyncio.to_thread(self.status)
async def set_time_slot_mode(self, enabled: bool) -> dict[str, Any]:
"""Enable 24/N keyed-channel slots + live Douyin sources.
When OFF + 自动推流 ON: normal groups auto-watch 直播地址列表 instead.
Does NOT force exclusive Neko/FFmpeg. Does NOT turn on 自动推流.
"""
on = bool(enabled)
patch: dict[str, Any] = {"youtube_relay_time_slot_mode": on}
if on:
patch["youtube_relay_respect_schedule"] = True
else:
# Real schedule off ⇒ drop test override too.
patch["youtube_relay_timeslot_test"] = False
patch["youtube_relay_timeslot_test_group_id"] = ""
db.update_settings_map(patch)
self._status_cache = None
self._status_cache_at = 0.0
return await asyncio.to_thread(self.status)
async def set_timeslot_test_mode(self, enabled: bool) -> dict[str, Any]:
"""Force time_slot winner by operator (ignore Beijing 24/N clock) for quick tests."""
on = bool(enabled)
channels = _timeslot_test_channels()
if on and not channels:
raise ValueError("没有可测试的时间段频道(需:时间段分类 + KEY + 排班开关)")
patch: dict[str, Any] = {"youtube_relay_timeslot_test": on}
if on:
cur = str(db.get_settings_map().get("youtube_relay_timeslot_test_group_id") or "").strip()
ids = {str(c.get("group_id") or "") for c in channels}
if cur not in ids:
patch["youtube_relay_timeslot_test_group_id"] = _pick_default_timeslot_test_group_id(
channels
)
patch["youtube_relay_enabled"] = True
patch["youtube_relay_respect_schedule"] = True
else:
patch["youtube_relay_timeslot_test_group_id"] = ""
db.update_settings_map(patch)
self._status_cache = None
self._status_cache_at = 0.0
if on:
await self.start()
await self._kick_timeslot_test_winner()
return await asyncio.to_thread(self.status)
async def timeslot_test_next(self) -> dict[str, Any]:
"""Advance forced test winner to the next time_slot channel (wrap around)."""
channels = _timeslot_test_channels()
if not channels:
raise ValueError("没有可测试的时间段频道(需:时间段分类 + KEY + 排班开关)")
ids = [str(c.get("group_id") or "").strip() for c in channels if str(c.get("group_id") or "").strip()]
cfg = db.get_settings_map()
cur = str(cfg.get("youtube_relay_timeslot_test_group_id") or "").strip()
if cur in ids:
nxt = ids[(ids.index(cur) + 1) % len(ids)]
else:
# First click: jump to the channel after the real-clock active slot.
active_i = next((i for i, c in enumerate(channels) if c.get("active")), -1)
nxt = ids[(active_i + 1) % len(ids)] if active_i >= 0 else ids[0]
name = next(
(str(c.get("name") or "") for c in channels if str(c.get("group_id") or "") == nxt),
nxt,
)
db.update_settings_map(
{
"youtube_relay_timeslot_test": True,
"youtube_relay_timeslot_test_group_id": nxt,
"youtube_relay_enabled": True,
"youtube_relay_respect_schedule": True,
}
)
self._status_cache = None
self._status_cache_at = 0.0
await self.start()
await self._kick_timeslot_test_winner()
st = await asyncio.to_thread(self.status)
st["timeslot_test_next"] = {"group_id": nxt, "name": name}
return st
async def _kick_timeslot_test_winner(self) -> None:
"""Switch exclusive Neko to forced winner; FFmpeg starts on next pipeline tick.
Avoid blocking the HTTP request on Studio settle / stream resolve (can take minutes).
Still gracefully End Stream on the previous winner before stopping its Neko.
"""
cfg = db.get_settings_map()
gid = str(cfg.get("youtube_relay_timeslot_test_group_id") or "").strip()
if not gid:
return
group = yt_assign_db.get_group(gid)
if not group or not group.get("enabled"):
return
for other in list(self._sessions.keys()):
if other != gid:
self._manual_hold.discard(other)
og = yt_assign_db.get_group(other) or {"id": other}
await self._graceful_retire_group(
og,
reason="timeslot_test_rotate",
stop_neko=bool(cfg.get("youtube_relay_exclusive_live", True)),
)
await self._enforce_exclusive_live(gid, group)
youtube_relay_db.upsert_relay_state(
gid,
status="starting",
error="",
recent_log=["[relay] timeslot_test — winner set, waiting auto tick for push"],
)
async def _enforce_exclusive_live(self, winner_gid: str, winner_group: dict[str, Any]) -> None:
"""When one channel actually pushes: stop other FFmpeg + Neko; keep winner Neko up."""
cfg = db.get_settings_map()
if not bool(cfg.get("youtube_relay_exclusive_live", True)):
return
winner_gid = str(winner_gid or "").strip()
if not winner_gid:
return
self._exclusive_winner = winner_gid
winner_neko = int(winner_group.get("neko_instance_id") or 0)
for g in yt_assign_db.list_groups(include_urls=False):
gid = str(g.get("id") or "")
if not gid or gid == winner_gid:
continue
self._manual_hold.discard(gid)
await self._graceful_retire_group(g, reason="exclusive_live", stop_neko=True)
youtube_relay_db.upsert_relay_state(
gid,
status="paused_exclusive",
error=f"单频道独占:当前仅允许 {winner_group.get('name') or winner_gid} 推流",
recent_log=[f"[relay] exclusive_live winner={winner_gid} — paused"],
)
from . import youtube_neko
# Any leftover Nekos (never pushed / already halted) still stop for RAM.
paused = await asyncio.to_thread(youtube_neko.stop_instances_except, winner_neko)
self._neko_paused_instances |= set(paused)
prefer = str(winner_group.get("neko_open_prefer") or "local").strip().lower()
remote_bound = bool(str(winner_group.get("ops_neko_open_url") or "").strip())
# Prefer remote ops-neko: do not force-start local assign Neko.
if winner_neko > 0 and not (prefer == "remote" and remote_bound):
await asyncio.to_thread(youtube_neko.ensure_instance_running, winner_neko)
async def _release_exclusive_live(self) -> None:
if not self._exclusive_winner and not self._neko_paused_instances:
return
self._exclusive_winner = None
paused = set(self._neko_paused_instances)
self._neko_paused_instances.clear()
if not paused:
return
from . import youtube_neko
await asyncio.to_thread(youtube_neko.restore_enabled_instances)
async def _maybe_release_exclusive_live(self) -> None:
if not self._exclusive_winner:
return
gid = self._exclusive_winner
if gid in self._manual_hold:
return
sess = self._sessions.get(gid)
if sess and sess.stats.running:
return
# Normal exclusive sticky: keep claim while 直播地址列表 still has live rooms.
try:
g = next(
(
x
for x in yt_assign_db.list_groups(include_urls=True)
if str(x.get("id") or "") == gid
),
None,
)
except Exception:
g = None
if g and not _group_uses_time_slot(g) and pick_source_for_group(g, respect_schedule=False):
return
await self._release_exclusive_live()
async def _ensure_group_relay(
self,
group: dict[str, Any],
*,
source: dict[str, str] | None = None,
cfg: dict[str, Any] | None = None,
force: bool = False,
respect_schedule: bool | None = None,
) -> dict[str, Any]:
gid = str(group.get("id") or "")
if not force:
cool_until = self._studio_cooldown_active(gid)
if cool_until > 0:
left = int(max(0, cool_until - time.time()))
err = (
f"Studio 未 on_air 熔断中(约剩 {left // 60} 分)。"
f"常见原因:YouTube daily stream limit。手动「开始」可解除。"
)
youtube_relay_db.upsert_relay_state(
gid,
status="paused_studio",
error=err,
recent_log=["[relay] studio_cooldown — skip ensure"],
)
return {"ok": False, "error": err, "fatal": False}
lock = self._group_locks.setdefault(gid, asyncio.Lock())
async with lock:
return await self._ensure_group_relay_locked(
group,
source=source,
cfg=cfg,
force=force,
respect_schedule=respect_schedule,
)
async def _ensure_group_relay_locked(
self,
group: dict[str, Any],
*,
source: dict[str, str] | None = None,
cfg: dict[str, Any] | None = None,
force: bool = False,
respect_schedule: bool | None = None,
) -> dict[str, Any]:
cfg = cfg or db.get_settings_map()
encoding = resolve_relay_encoding(cfg)
gid = str(group.get("id") or "")
slot_mode = _group_uses_time_slot(group)
if respect_schedule is None:
respect_schedule = True if slot_mode else bool(cfg.get("youtube_relay_respect_schedule", True))
if force and not slot_mode:
respect_schedule = False
relay_st = youtube_relay_db.get_relay_state(gid) or {}
existing = self._sessions.get(gid)
prefer_room = str(
(existing.room_id if existing else "")
or relay_st.get("source_room_id")
or ""
).strip()
prefer_url = str(
(existing.source_url if existing else "")
or relay_st.get("source_url")
or ""
).strip()
src = source or pick_source_for_group(
group,
respect_schedule=respect_schedule,
prefer_room_id=prefer_room,
prefer_source_url=prefer_url,
)
if not src:
# Distinguish schedule block vs empty featured for diagnostics.
any_src = pick_source_for_group(
group,
respect_schedule=False,
prefer_room_id=prefer_room,
prefer_source_url=prefer_url,
)
if any_src and respect_schedule:
# 时间段分类:手动「开始」也不绕过 24/N 窗口(见 start_group)。
if slot_mode:
err = "当前不在分配时段(时间段频道受 24/N 窗口限制,需等到本频道轮播窗口)"
else:
err = "当前不在分配时段,自动推流已跳过"
fatal = False
elif slot_mode:
err = "时间段模式:当前没有在播的抖音直播间可作为推流源"
fatal = False
else:
err = "直播地址列表为空或没有可用抖音源"
fatal = True
youtube_relay_db.upsert_relay_state(
gid,
status="idle",
error=err,
recent_log=[f"[relay] skip: {err}"],
)
if force:
return {"ok": False, "fatal": fatal, "error": err}
# Auto path: stop if running.
if gid in self._sessions and gid not in self._manual_hold:
await self._halt_session(gid, reason="no_source")
return {"ok": False, "fatal": fatal, "error": err}
existing = self._sessions.get(gid)
if existing and existing.stats.running:
same_url = existing.source_url == src.get("source_url")
same_room = (
str(existing.room_id or "").strip()
and str(existing.room_id or "").strip() == str(src.get("room_id") or "").strip()
)
if same_url or same_room:
if force:
self._manual_hold.add(gid)
return {"ok": True, "group_id": gid, "reused": True, "ffmpeg_pid": int(existing.stats.pid or 0)}
await self._halt_session(gid, reason="source_switch")
elif existing and (force or not existing.stats.running):
# Dead/stale session (CDN 404 etc.) → drop and re-resolve FLV URL.
await self._halt_session(gid, reason="restart" if force else "stream_refresh")
# Orphan FFmpeg (API restart lost _sessions): reuse or kill — never start a second push.
orphan_pid = int(relay_st.get("ffmpeg_pid") or 0)
if _ffmpeg_pid_alive(orphan_pid) and not (self._sessions.get(gid) and self._sessions[gid].stats.running):
if not force:
orphan_logs = youtube_relay_db._parse_recent_log(relay_st.get("recent_log"))
if not orphan_logs:
orphan_logs = [f"[relay] reused orphan ffmpeg pid={orphan_pid}"]
youtube_relay_db.upsert_relay_state(
gid,
status="pushing",
ffmpeg_pid=orphan_pid,
error="",
recent_log=orphan_logs[-40:],
)
return {
"ok": True,
"group_id": gid,
"reused_orphan": True,
"ffmpeg_pid": orphan_pid,
}
try:
os.kill(orphan_pid, signal.SIGTERM)
except OSError:
pass
await asyncio.sleep(1.2)
youtube_relay_db.upsert_relay_state(gid, ffmpeg_pid=0)
if force:
self._manual_hold.add(gid)
stream_key = str(group.get("stream_key") or "").strip()
if not stream_key:
raw = yt_assign_db.get_group(gid)
stream_key = str((raw or {}).get("stream_key") or "").strip()
if not stream_key:
err = "缺少 stream key"
youtube_relay_db.upsert_relay_state(gid, status="error", error=err, recent_log=[f"[relay] {err}"])
return {"ok": False, "fatal": True, "error": err}
boot_log = [
f"[relay] resolve {src.get('source_url') or ''}",
f"[relay] room={src.get('room_id') or '-'} anchor={src.get('anchor_name') or '-'}",
]
youtube_relay_db.upsert_relay_state(
gid,
status="starting",
source_url=src.get("source_url") or "",
source_room_id=src.get("room_id") or "",
anchor_name=src.get("anchor_name") or "",
error="",
recent_log=boot_log,
)
# sh2: spider MUST use [Cookie]抖音cookie (= dy_cookie). FFmpeg itself does not send Cookie.
cookie = str(cfg.get("dy_cookie") or "").strip()
if not cookie:
# Keep lane armed — sh2 keeps polling even when fetch fails.
note = "缺少抖音 Cookie(dy_cookie / sh2 [Cookie]抖音cookie),轮询暂停推流但不会退出监听"
boot_log.append(f"[relay] 等待直播… {note}")
if gid in self._sessions:
await self._halt_session(gid, reason="wait_cookie")
youtube_relay_db.upsert_relay_state(
gid,
status="waiting",
error=note,
source_url=src.get("source_url") or "",
source_room_id=src.get("room_id") or "",
anchor_name=src.get("anchor_name") or "",
ffmpeg_pid=0,
recent_log=boot_log[-40:],
)
return {"ok": True, "waiting": True, "group_id": gid, "note": note}
boot_log.append(f"[relay] dy_cookie len={len(cookie)} (sh2 spider path)")
# Probe first (same as sh2 spider.get_douyin_web_stream_data + get_douyin_stream_url).
probe = await check_room(src["source_url"], cookie=cookie)
if probe.get("anchor_name"):
src["anchor_name"] = str(probe.get("anchor_name") or src.get("anchor_name") or "")
boot_log.append(
f"[relay] probe ok={probe.get('ok')} live={probe.get('is_live')} "
f"status={probe.get('status_code')} risk={bool(probe.get('risk'))}"
)
cands: list[str] = []
if probe.get("ok") and probe.get("is_live"):
raw_cands = probe.get("stream_candidates") or []
if isinstance(raw_cands, list):
cands = [str(x).strip() for x in raw_cands if str(x or "").strip().startswith("http")]
fresh = str(probe.get("stream_url") or "").strip()
if fresh.startswith("http") and fresh not in cands:
cands.insert(0, fresh)
if not cands and probe.get("ok") and probe.get("is_live"):
cands = await resolve_stream_candidates(
source_url=src["source_url"],
cookie=cookie,
prefer_fresh=True,
)
# sh2 youtube.py L1213-1229: is_live False → print 等待直播 + continue (never exit lane).
# Monitor「进行中场次」can lag; sticky prefer must not glue forever onto status=4.
# Time-slot rotates live list; normal exclusive rotates featured then releases sticky.
exclusive_on = bool(cfg.get("youtube_relay_exclusive_live", True))
if not cands and (slot_mode or exclusive_on):
live_sess = self._sessions.get(gid)
if live_sess and live_sess.stats.running:
return {
"ok": True,
"group_id": gid,
"reused": True,
"ffmpeg_pid": int(live_sess.stats.pid or 0),
"note": "probe_miss_keep_ffmpeg",
}
exclude: set[str] = set(self._probe_offline_room_ids())
failed_rid = str(src.get("room_id") or "").strip()
if failed_rid:
exclude.add(failed_rid)
if probe.get("ok") and not probe.get("is_live"):
self._mark_probe_offline(failed_rid)
boot_log.append(
f"[relay] room offline/probe-miss rid={failed_rid or '-'} "
f"status={probe.get('status_code')} → rotate live list"
)
for _ in range(8):
alt = pick_source_for_group(
group,
respect_schedule=respect_schedule,
prefer_room_id="",
prefer_source_url="",
exclude_room_ids=exclude,
)
if not alt:
break
alt_rid = str(alt.get("room_id") or "").strip()
if not alt_rid or alt_rid in exclude:
break
boot_log.append(
f"[relay] switch source {failed_rid or '-'} → {alt_rid} "
f"({alt.get('anchor_name') or '-'})"
)
src = alt
probe = await check_room(src["source_url"], cookie=cookie)
if probe.get("anchor_name"):
src["anchor_name"] = str(probe.get("anchor_name") or src.get("anchor_name") or "")
boot_log.append(
f"[relay] probe ok={probe.get('ok')} live={probe.get('is_live')} "
f"status={probe.get('status_code')} risk={bool(probe.get('risk'))}"
)
cands = []
if probe.get("ok") and probe.get("is_live"):
raw_cands = probe.get("stream_candidates") or []
if isinstance(raw_cands, list):
cands = [
str(x).strip()
for x in raw_cands
if str(x or "").strip().startswith("http")
]
fresh = str(probe.get("stream_url") or "").strip()
if fresh.startswith("http") and fresh not in cands:
cands.insert(0, fresh)
if not cands and probe.get("ok") and probe.get("is_live"):
cands = await resolve_stream_candidates(
source_url=src["source_url"],
cookie=cookie,
prefer_fresh=True,
)
if cands:
break
exclude.add(alt_rid)
if probe.get("ok") and not probe.get("is_live"):
self._mark_probe_offline(alt_rid)
failed_rid = alt_rid
if not cands:
live_sess = self._sessions.get(gid)
if live_sess and live_sess.stats.running:
# Probe flake must not kill an active FFmpeg pull.
return {
"ok": True,
"group_id": gid,
"reused": True,
"ffmpeg_pid": int(live_sess.stats.pid or 0),
"note": "probe_miss_keep_ffmpeg",
}
if gid in self._sessions:
await self._halt_session(gid, reason="wait_live")
failed_rid = str(src.get("room_id") or "").strip()
if failed_rid and probe.get("ok") and not probe.get("is_live"):
self._mark_probe_offline(failed_rid)
# Exclusive sticky: monitor can still list this room live while probe=4 —
# release so another normal group (with a real live featured) can claim.
if (
exclusive_on
and not slot_mode
and str(self._exclusive_winner or "") == gid
and gid not in self._manual_hold
and probe.get("ok")
and not probe.get("is_live")
):
boot_log.append(
f"[relay] exclusive release: winner featured probe offline "
f"rid={failed_rid or '-'} status={probe.get('status_code')}"
)
self._exclusive_winner = None
try:
await self._release_exclusive_live()
except Exception:
pass
anchor = str(src.get("anchor_name") or probe.get("anchor_name") or "").strip() or "-"
if probe.get("risk") or (probe.get("ok") is False):
note = str(probe.get("error") or "风控/接口失败,将继续轮询").strip()
line = f"[relay] 等待直播…(探测异常: {note})"
else:
note = f"status={probe.get('status_code')} 主播={anchor}"
line = f"[relay] 等待直播... ({note})"
boot_log.append(line)
youtube_relay_db.upsert_relay_state(
gid,
status="waiting",
error="",
source_url=src.get("source_url") or "",
source_room_id=src.get("room_id") or "",
anchor_name=src.get("anchor_name") or probe.get("anchor_name") or "",
ffmpeg_pid=0,
speed=0,
frame=0,
recent_log=boot_log[-40:],
)
return {
"ok": True,
"waiting": True,
"group_id": gid,
"source_url": src.get("source_url") or "",
"note": line,
"exclusive_released": str(self._exclusive_winner or "") != gid,
}
try:
rtmp = build_youtube_rtmp_url(
stream_key,
use_rtmps=bool(cfg.get("youtube_relay_use_rtmps", True)),
)
except ValueError as exc:
err = str(exc)
boot_log.append(f"[relay] ERROR {err}")
youtube_relay_db.upsert_relay_state(gid, status="error", error=err, recent_log=boot_log)
return {"ok": False, "error": err}
now = time.time()
boot_log.append(f"[relay] input {cands[0][:160]} (+{max(0, len(cands)-1)} fallbacks)")
boot_log.append(f"[relay] output {rtmp.split('/')[-1][:8]}… via {'rtmps' if 'rtmps' in rtmp else 'rtmp'}")
boot_log.append("[relay] starting ffmpeg…")
def _on_stats(st: RelayStats) -> None:
youtube_relay_db.upsert_relay_state(
gid,
status="pushing",
speed=float(st.speed),
frame=int(st.frame),
ffmpeg_pid=int(st.pid),
recent_log=st.recent_log,
)
old = self._sessions.pop(gid, None)
if old:
await asyncio.to_thread(old.stop)
await asyncio.to_thread(relay_sessions.end_session, gid, reason="restart")
boot_log.append(f"[relay] quality {encoding.get('preset_id')} {encoding.get('width')}x{encoding.get('height')}@{encoding.get('fps')}")
await self._enforce_exclusive_live(gid, group)
# Studio Live gate: prefer remote ops-neko when bound; else local assign Neko.
from . import youtube_neko
prefer = str(group.get("neko_open_prefer") or "local").strip().lower()
remote_bound = bool(str(group.get("ops_neko_open_url") or "").strip())
ops_slot = int(group.get("ops_neko_slot") or 0)
neko_id = int(group.get("neko_instance_id") or 0)
exclusive_on = bool(cfg.get("youtube_relay_exclusive_live", True))
use_remote = prefer == "remote" and remote_bound and ops_slot > 0
neko_gate = use_remote or exclusive_on or bool(group.get("neko_enabled")) or (
neko_id > 0 and bool(group.get("neko_enabled"))
)
if neko_gate and (use_remote or neko_id > 0):
target = f"远程 Ops Neko #{ops_slot}" if use_remote else f"本机 Neko #{neko_id}"
boot_log.append(
f"[relay] waiting {target} YouTube Live 控制页就绪"
f"(须新遥测 + 稳定 ≥20s,禁止抢跑)…"
)
youtube_relay_db.upsert_relay_state(
gid,
status="starting",
error=f"等待 {target} 打开 YouTube Live 控制页…",
recent_log=boot_log[-40:],
)
neko_wait = await asyncio.to_thread(
youtube_neko.wait_group_ready_for_live,
group,
timeout_sec=120.0,
settle_sec=20.0,
strict=True,
)
if not neko_wait.get("ok") or (
not neko_wait.get("skipped") and not neko_wait.get("live_studio")
):
err = str(
neko_wait.get("error")
or "YouTube Live 控制页未就绪,暂不推流(避免绿点无效 ingest)"
)
boot_log.append(f"[relay] neko wait blocked: {err}")
youtube_relay_db.upsert_relay_state(
gid,
status="waiting",
error=err,
recent_log=boot_log[-40:],
)
return {"ok": True, "waiting": True, "group_id": gid, "note": err, "neko": neko_wait}
if neko_wait.get("skipped"):
boot_log.append("[relay] neko Live 页检查跳过(无绑定)")
else:
boot_log.append(
f"[relay] neko Live 页就绪 kind={neko_wait.get('neko_kind') or '-'} "
f"src={neko_wait.get('detect_source') or 'telemetry'} "
f"settled={bool(neko_wait.get('settled'))} settle={neko_wait.get('settle_sec')}s "
f"live_status={neko_wait.get('live_status') or '-'} "
f"health={neko_wait.get('health') or '-'} "
f"url={(neko_wait.get('url') or '-')[:80]}"
)
sess = RelayPushSession(
group_id=gid,
input_urls=cands,
youtube_rtmp=rtmp,
anchor_name=src.get("anchor_name") or "",
source_url=src.get("source_url") or "",
room_id=src.get("room_id") or "",
bitrate_kbps=int(encoding.get("bitrate_kbps") or cfg.get("youtube_relay_bitrate") or 2500),
encoding=encoding,
on_stats=_on_stats,
)
# Seed in-memory log so UI sees lines before first ffmpeg frame
sess.stats.recent_log = list(boot_log)
self._sessions[gid] = sess
youtube_relay_db.upsert_relay_state(
gid,
status="starting",
source_url=src.get("source_url") or "",
source_room_id=src.get("room_id") or "",
anchor_name=src.get("anchor_name") or "",
stream_input=cands[0][:500],
started_at=now,
error="",
recent_log=boot_log,
)
await asyncio.to_thread(sess.start)
# Give reader a brief moment to attach
await asyncio.sleep(0.4)
sk = _key_suffix(ginfo if (ginfo := yt_assign_db.get_group(gid)) else group)
await asyncio.to_thread(
relay_sessions.start_session,
gid,
channel_name=str((ginfo or group).get("name") or ""),
anchor_name=src.get("anchor_name") or "",
source_url=src.get("source_url") or "",
source_room_id=src.get("room_id") or "",
youtube_key_suffix=sk,
metadata={"stream_input": cands[0][:240]},
)
self.processed += 1
return {
"ok": True,
"group_id": gid,
"source_url": src.get("source_url") or "",
"ffmpeg_pid": int(sess.stats.pid or 0),
"manual_hold": gid in self._manual_hold,
}
async def _tick_stats(self) -> None:
now = time.time()
# After FFmpeg is up, Studio must leave NODATA/待开播 and become on_air.
# Green-dot loading without You're Live = invalid push — stop it.
try:
from . import youtube_neko as _yn
on_air_deadline = float(
(db.get_settings_map() or {}).get("youtube_relay_on_air_deadline_sec") or 90
)
except Exception:
_yn = None # type: ignore
on_air_deadline = 90.0
on_air_deadline = max(45.0, min(300.0, float(on_air_deadline)))
for gid, sess in list(self._sessions.items()):
if sess.stats.running:
st = youtube_relay_db.get_relay_state(gid) or {}
started = float(st.get("started_at") or now)
push_sec = max(0.0, now - started)
# Watchdog: fresh Studio telemetry still NODATA/待开播 after deadline → kill invalid ingest
if _yn is not None and push_sec >= on_air_deadline:
try:
group = yt_assign_db.get_group(gid) or {}
snap = _yn.studio_snapshot_for_group(group, max_age_sec=75.0)
age = snap.get("age_sec")
try:
fresh = age is not None and float(age) <= 75.0
except (TypeError, ValueError):
fresh = bool(snap.get("received_at"))
on_air = bool(snap.get("on_air"))
live_status = str(snap.get("live_status") or "").strip().lower()
page_open = bool(snap.get("live_page_open"))
preparing = live_status == "preparing" or bool(snap.get("preparing_stream"))
# 待开播 / Preparing stream — never treat 断播(encoder_lost) as invalid-push kill.
pending = live_status in {"waiting", "ready", "signed_out", "offline", "preparing"}
try:
payload_probe = {
"live_status": live_status,
"live_duration": snap.get("live_duration") or "",
"live_duration_sec": snap.get("live_duration_sec"),
"text": "",
"signals": {
"nodata": live_status == "waiting",
"encoder_lost": live_status in {"encoder_lost", "stalled"},
"session_live": live_status in {"live", "encoder_lost", "stalled"},
"pending_go_live": pending and not preparing,
"preparing_stream": preparing,
},
}
if preparing:
pending = True
elif _yn._payload_encoder_lost(payload_probe) or live_status in {
"encoder_lost",
"stalled",
}:
pending = False
elif not _yn._payload_nodata_or_pending(payload_probe):
pending = False
except Exception:
if preparing:
pending = True
# Preparing stream + Excellent = invalid green-loading push — kill sooner.
prep_deadline = min(on_air_deadline, 45.0)
kill_prep = preparing and push_sec >= prep_deadline
# Only act on fresh evidence of 待开播 — never kill on 断播 / missing telemetry.
if fresh and page_open and (not on_air) and (pending or kill_prep):
why = "Preparing stream(预览未就绪)" if preparing else (live_status or "待开播/NODATA")
err = (
f"Studio 仍为 {why}(未 on_air),"
f"推流已 {int(push_sec)}s — 判定无效推流,已自动停止"
)
boot = list(sess.stats.recent_log or [])
boot.append(f"[relay] {err}")
await asyncio.to_thread(sess.stop)
self._sessions.pop(gid, None)
tripped, cool_msg = self._note_studio_not_on_air(gid)
if tripped:
err = cool_msg
boot.append(f"[relay] {cool_msg}")
youtube_relay_db.upsert_relay_state(
gid,
status="paused_studio" if tripped else "waiting",
ffmpeg_pid=0,
speed=0,
frame=0,
error=err,
recent_log=boot[-40:],
)
await asyncio.to_thread(
relay_sessions.end_session, gid, reason="studio_not_on_air"
)
# Drop manual hold so we don't immediately restart the same invalid push
self._manual_hold.discard(gid)
continue
except Exception:
pass
youtube_relay_db.upsert_relay_state(
gid,
status="pushing",
speed=float(sess.stats.speed),
frame=int(sess.stats.frame),
ffmpeg_pid=int(sess.stats.pid),
push_seconds=push_sec,
recent_log=sess.stats.recent_log,
)
else:
# Dead ffmpeg still registered — surface reconnecting, never leave "pushing".
last = (sess.stats.last_line or "").lower()
if "404" in last or "403" in last or "cdn 404" in "\n".join(sess.stats.recent_log[-8:]).lower():
err = "抖音 CDN 拉流地址失效(404),正在尝试换线重连;若主播已下播则需等开播后再开始"
else:
err = (sess.stats.last_line or "推流中断,等待重连")[:500]
youtube_relay_db.upsert_relay_state(
gid,
status="reconnecting",
ffmpeg_pid=0,
speed=0,
frame=0,
error=err,
recent_log=sess.stats.recent_log,
)
# Drop dead session object so next _ensure_group_relay always re-resolves.
# Keep manual_hold so user intent (开始) survives.
self._sessions.pop(gid, None)
await asyncio.to_thread(relay_sessions.end_session, gid, reason="stream_refresh")
await self._maybe_release_exclusive_live()
# Orphan FFmpeg (API restart left OS pid alive, no in-memory session) still needs
# the Studio on_air watchdog — otherwise green-loading can burn for hours.
if _yn is not None:
try:
for st_row in youtube_relay_db.list_relay_states():
gid = str(st_row.get("group_id") or "").strip()
if not gid or gid in self._sessions:
continue
if str(st_row.get("status") or "") not in {"pushing", "starting"}:
continue
try:
orphan_pid = int(st_row.get("ffmpeg_pid") or 0)
except (TypeError, ValueError):
orphan_pid = 0
if orphan_pid < 1 or not _ffmpeg_pid_alive(orphan_pid):
continue
started = float(st_row.get("started_at") or now)
push_sec = max(0.0, now - started)
if push_sec < on_air_deadline:
continue
group = yt_assign_db.get_group(gid) or {}
snap = _yn.studio_snapshot_for_group(group, max_age_sec=75.0)
try:
age = snap.get("age_sec")
fresh = age is not None and float(age) <= 75.0
except (TypeError, ValueError):
fresh = bool(snap.get("received_at"))
on_air = bool(snap.get("on_air"))
live_status = str(snap.get("live_status") or "").strip().lower()
page_open = bool(snap.get("live_page_open"))
preparing = live_status == "preparing" or bool(snap.get("preparing_stream"))
pending = live_status in {"waiting", "ready", "signed_out", "offline", "preparing"}
if preparing:
pending = True
elif live_status in {"encoder_lost", "stalled", "live"}:
pending = False
prep_deadline = min(on_air_deadline, 45.0)
kill_prep = preparing and push_sec >= prep_deadline
if not (fresh and page_open and (not on_air) and (pending or kill_prep)):
continue
why = "Preparing stream(预览未就绪)" if preparing else (live_status or "待开播/NODATA")
err = (
f"Studio 仍为 {why}(未 on_air),孤儿推流已 {int(push_sec)}s — 已自动停止"
)
try:
os.kill(orphan_pid, signal.SIGTERM)
except Exception:
try:
os.kill(orphan_pid, signal.SIGKILL)
except Exception:
pass
boot = youtube_relay_db._parse_recent_log(st_row.get("recent_log"))
boot.append(f"[relay] {err}")
tripped, cool_msg = self._note_studio_not_on_air(gid)
if tripped:
err = cool_msg
boot.append(f"[relay] {cool_msg}")
youtube_relay_db.upsert_relay_state(
gid,
status="paused_studio" if tripped else "waiting",
ffmpeg_pid=0,
speed=0,
frame=0,
error=err,
recent_log=boot[-40:],
)
await asyncio.to_thread(
relay_sessions.end_session, gid, reason="studio_not_on_air_orphan"
)
self._manual_hold.discard(gid)
except Exception:
pass
youtube_relay_pipeline = YoutubeRelayPipeline()