douyinWEB/backend/app/youtube_relay_pipeline.py
eric c06e2b1385 Add timeslot exclude list so manual Douyin lives are not auto-selected.
Prevents time-slot relay and schedule auto-fill from colliding with URLs already used for manual/featured pushes; UI sits beside full-channel fill.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-09-05 22:50:25 -05:00

1280 lines
59 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.

# -*- coding: utf-8 -*-
"""Background worker: Douyin live → YouTube RTMPS relay per assign group."""
from __future__ import annotations
import asyncio
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 _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:
return yt_assign_db.group_in_rotation_slot(group_id, keyed_only=keyed_only)
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 list (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()
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,
}
)
candidates.sort(key=lambda x: (0 if x["live"] else 1, x["idx"]))
for c in candidates:
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] = {}
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 = 1.0
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)
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=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"}:
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 (
"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_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:
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)
# 时间段: 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 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)
await self._halt_session(gid, reason="stopped")
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:
cfg = db.get_settings_map()
auto_on = bool(cfg.get("youtube_relay_enabled"))
groups = yt_assign_db.list_groups(include_urls=True)
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: 时间段 groups via 24/N; 普通 = 手动 only (skip auto).
if auto_on:
from . import youtube_neko
slot_winner_gid = ""
slot_winner_g: dict[str, Any] | None = None
time_slot_groups = [g for g in groups if _group_uses_time_slot(g)]
run_slot_auto = bool(time_slot_groups)
if run_slot_auto:
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 str(g.get("stream_key") or "").strip() and not g.get("has_stream_key"):
continue
# 普通分类:仅手动推流,不走自动排班。
if not _group_uses_time_slot(g):
continue
# 时间段:非当前时段 → 停推流;仅在「单频道独占」时顺带停 Neko。
if run_slot_auto and gid != slot_winner_gid:
exclusive_on = bool(cfg.get("youtube_relay_exclusive_live", True))
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:
if gid in self._sessions:
await self._halt_session(gid, reason="duplicate_channel_key")
neko_id = int(g.get("neko_instance_id") or 0)
if exclusive_on and neko_id > 0:
await asyncio.to_thread(youtube_neko.stop_instance, neko_id)
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:
if gid in self._sessions:
await self._halt_session(gid, reason="outside_slot")
neko_id = int(g.get("neko_instance_id") or 0)
if exclusive_on and neko_id > 0:
await asyncio.to_thread(youtube_neko.stop_instance, neko_id)
youtube_relay_db.upsert_relay_state(
gid,
status="outside_slot",
error="",
recent_log=["[relay] outside_slot — waiting schedule window"],
)
continue
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
# Outside schedule / empty list — idle, do not kill manual holds.
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"],
)
# Keep winner Neko warm while waiting for a live room.
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:
# 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.
Does NOT force exclusive Neko/FFmpeg — operators on physical hosts may
keep multiple Studios warm. 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
db.update_settings_map(patch)
self._status_cache = None
self._status_cache_at = 0.0
return await asyncio.to_thread(self.status)
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)
if gid in self._sessions:
await self._halt_session(gid, reason="exclusive_live")
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
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
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 "")
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:
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")
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).
# Time-slot: monitor「进行中场次」can lag; sticky prefer must not glue forever onto status=4.
if not cands and slot_mode:
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()
failed_rid = str(src.get("room_id") or "").strip()
if failed_rid:
exclude.add(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
if probe.get("anchor_name") and not src.get("anchor_name"):
pass
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)
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")
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,
}
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"))
# 待开播 only — never treat 断播(encoder_lost) as invalid-push kill.
pending = live_status in {"waiting", "ready", "signed_out", "offline"}
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,
},
}
if _yn._payload_encoder_lost(payload_probe) or live_status in {
"encoder_lost",
"stalled",
}:
pending = False
if not _yn._payload_nodata_or_pending(payload_probe):
pending = False
except Exception:
pass
# Only act on fresh evidence of 待开播 — never kill on 断播 / missing telemetry.
if fresh and page_open and (not on_air) and pending:
err = (
f"Studio 仍为 {live_status or '待开播/NODATA'}(未 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)
youtube_relay_db.upsert_relay_state(
gid,
status="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()
youtube_relay_pipeline = YoutubeRelayPipeline()